@mpcore/simulator 0.1.4 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,13 +1,57 @@
1
1
  import { dirname, join, normalize, posix } from "pathe";
2
- import { parseDocument } from "htmlparser2";
3
2
  import fs from "node:fs";
4
3
  import path from "node:path";
4
+ import { WEVU_NATIVE_INSTANCE_KEY } from "@weapp-core/constants";
5
+ import { parseDocument } from "htmlparser2";
6
+ import { parseExpression } from "@babel/parser";
5
7
  import process from "node:process";
6
8
  import vm from "node:vm";
7
9
  //#region src/host/globals.ts
8
10
  function createDuplicateRegistrationError(kind, id) {
9
11
  return /* @__PURE__ */ new Error(`Duplicate ${kind} registration in headless runtime: ${id}`);
10
12
  }
13
+ function callDefinitionMethod(instance, method, args) {
14
+ if (typeof method === "function") return method.apply(instance, args);
15
+ }
16
+ function normalizeComponentPageDefinition(definition) {
17
+ const { lifetimes = {}, methods = {}, pageLifetimes = {}, ...rest } = definition;
18
+ const created = lifetimes.created ?? rest.created;
19
+ const attached = lifetimes.attached ?? rest.attached;
20
+ const ready = lifetimes.ready ?? rest.ready ?? methods.onReady ?? rest.onReady;
21
+ const detached = lifetimes.detached ?? rest.detached ?? methods.onUnload ?? rest.onUnload;
22
+ const load = methods.onLoad ?? rest.onLoad;
23
+ const show = pageLifetimes.show ?? methods.onShow ?? rest.onShow;
24
+ const hide = pageLifetimes.hide ?? methods.onHide ?? rest.onHide;
25
+ const resize = pageLifetimes.resize ?? methods.onResize ?? rest.onResize;
26
+ const routeDone = pageLifetimes.routeDone ?? methods.onRouteDone ?? rest.onRouteDone;
27
+ return {
28
+ ...rest,
29
+ ...methods,
30
+ onLoad(...args) {
31
+ callDefinitionMethod(this, created, []);
32
+ callDefinitionMethod(this, attached, []);
33
+ return callDefinitionMethod(this, load, args);
34
+ },
35
+ onShow(...args) {
36
+ return callDefinitionMethod(this, show, args);
37
+ },
38
+ onHide(...args) {
39
+ return callDefinitionMethod(this, hide, args);
40
+ },
41
+ onReady(...args) {
42
+ return callDefinitionMethod(this, ready, args);
43
+ },
44
+ onUnload(...args) {
45
+ return callDefinitionMethod(this, detached, args);
46
+ },
47
+ onResize(...args) {
48
+ return callDefinitionMethod(this, resize, args);
49
+ },
50
+ onRouteDone(...args) {
51
+ return callDefinitionMethod(this, routeDone, args);
52
+ }
53
+ };
54
+ }
11
55
  function createHostRegistries() {
12
56
  return {
13
57
  appDefinition: null,
@@ -29,13 +73,70 @@ function registerPageDefinition(registries, definition) {
29
73
  return definition;
30
74
  }
31
75
  function registerComponentDefinition(registries, definition) {
76
+ if (registries.currentLoadContext?.kind === "page") return registerPageDefinition(registries, normalizeComponentPageDefinition(definition));
32
77
  const id = registries.currentLoadContext?.route ?? `anonymous:${registries.components.size}`;
33
78
  if (registries.components.has(id)) throw createDuplicateRegistrationError("component", id);
34
79
  registries.components.set(id, definition);
35
80
  return definition;
36
81
  }
82
+ function registerExportedComponentDefinition(registries, id, moduleExports, registeredDefinition) {
83
+ const exportedDefinition = registeredDefinition ?? moduleExports?.default ?? moduleExports;
84
+ if (!exportedDefinition || typeof exportedDefinition !== "object" || Array.isArray(exportedDefinition) || Object.keys(exportedDefinition).length === 0) return null;
85
+ registries.components.set(id, exportedDefinition);
86
+ return exportedDefinition;
87
+ }
88
+ //#endregion
89
+ //#region src/host/wx/eventBus.ts
90
+ function createHeadlessUniEventBus() {
91
+ const listeners = /* @__PURE__ */ new Map();
92
+ const $off = (eventName, handler) => {
93
+ if (eventName === void 0) {
94
+ listeners.clear();
95
+ return;
96
+ }
97
+ if (typeof eventName !== "string") return;
98
+ if (typeof handler !== "function") {
99
+ listeners.delete(eventName);
100
+ return;
101
+ }
102
+ const eventListeners = listeners.get(eventName);
103
+ if (!eventListeners) return;
104
+ for (const record of eventListeners) if (record.handler === handler || record.original === handler) eventListeners.delete(record);
105
+ if (eventListeners.size === 0) listeners.delete(eventName);
106
+ };
107
+ return {
108
+ $emit(eventName, ...args) {
109
+ const eventListeners = listeners.get(eventName);
110
+ if (!eventListeners) return;
111
+ for (const record of [...eventListeners]) record.handler(...args);
112
+ },
113
+ $off,
114
+ $on(eventName, handler) {
115
+ if (typeof eventName !== "string" || typeof handler !== "function") return;
116
+ const eventListeners = listeners.get(eventName) ?? /* @__PURE__ */ new Set();
117
+ eventListeners.add({
118
+ handler,
119
+ original: handler
120
+ });
121
+ listeners.set(eventName, eventListeners);
122
+ },
123
+ $once(eventName, handler) {
124
+ if (typeof eventName !== "string" || typeof handler !== "function") return;
125
+ const onceHandler = (...args) => {
126
+ $off(eventName, handler);
127
+ handler(...args);
128
+ };
129
+ const eventListeners = listeners.get(eventName) ?? /* @__PURE__ */ new Set();
130
+ eventListeners.add({
131
+ handler: onceHandler,
132
+ original: handler
133
+ });
134
+ listeners.set(eventName, eventListeners);
135
+ }
136
+ };
137
+ }
37
138
  //#endregion
38
- //#region src/host/wx.ts
139
+ //#region src/host/wx/index.ts
39
140
  function invokeWxApi(operation, option) {
40
141
  try {
41
142
  const result = operation();
@@ -58,6 +159,11 @@ function resolveCapabilityValue(source, schema) {
58
159
  return current;
59
160
  }
60
161
  function createHeadlessWx(driver) {
162
+ const eventBus = createHeadlessUniEventBus();
163
+ const rpx2px = (value) => {
164
+ const width = driver.getWindowInfoSync().windowWidth;
165
+ return Number.isFinite(value) && width > 0 ? value * width / 750 : 0;
166
+ };
61
167
  const capabilityTree = {
62
168
  canIUse: true,
63
169
  canvasToTempFilePath: true,
@@ -102,6 +208,17 @@ function createHeadlessWx(driver) {
102
208
  type: true,
103
209
  width: true
104
210
  } },
211
+ getLocation: { return: {
212
+ accuracy: true,
213
+ altitude: true,
214
+ errMsg: true,
215
+ horizontalAccuracy: true,
216
+ latitude: true,
217
+ longitude: true,
218
+ speed: true,
219
+ verticalAccuracy: true
220
+ } },
221
+ getLocale: true,
105
222
  getFileInfo: { return: {
106
223
  digest: true,
107
224
  errMsg: true,
@@ -138,6 +255,17 @@ function createHeadlessWx(driver) {
138
255
  platform: true,
139
256
  version: true
140
257
  } },
258
+ getDeviceInfo: { return: {
259
+ abi: true,
260
+ benchmarkLevel: true,
261
+ brand: true,
262
+ cpuType: true,
263
+ deviceAbi: true,
264
+ memorySize: true,
265
+ model: true,
266
+ platform: true,
267
+ system: true
268
+ } },
141
269
  getEnterOptionsSync: { return: {
142
270
  path: true,
143
271
  query: true,
@@ -225,6 +353,7 @@ function createHeadlessWx(driver) {
225
353
  windowHeight: true,
226
354
  windowWidth: true
227
355
  } },
356
+ loadFontFace: { return: { errMsg: true } },
228
357
  hideLoading: true,
229
358
  hideToast: true,
230
359
  downloadFile: true,
@@ -241,6 +370,7 @@ function createHeadlessWx(driver) {
241
370
  saveVideoToPhotosAlbum: true,
242
371
  removeStorage: true,
243
372
  removeStorageSync: true,
373
+ rpx2px: true,
244
374
  request: true,
245
375
  saveFile: true,
246
376
  setBackgroundColor: true,
@@ -268,9 +398,11 @@ function createHeadlessWx(driver) {
268
398
  uploadFile: true,
269
399
  removeTabBarBadge: true,
270
400
  setTabBarBadge: true,
271
- updateShareMenu: true
401
+ updateShareMenu: true,
402
+ upx2px: true
272
403
  };
273
404
  return {
405
+ ...eventBus,
274
406
  canIUse: (schema) => typeof schema === "string" && schema.trim() !== "" && resolveCapabilityValue(capabilityTree, schema.trim()) != null,
275
407
  canvasToTempFilePath: (option) => invokeWxApi(() => driver.canvasToTempFilePath(option), option),
276
408
  chooseImage: (option) => invokeWxApi(() => driver.chooseImage(option ?? {}), option),
@@ -278,10 +410,7 @@ function createHeadlessWx(driver) {
278
410
  chooseMedia: (option) => invokeWxApi(() => driver.chooseMedia(option ?? {}), option),
279
411
  chooseVideo: (option) => invokeWxApi(() => driver.chooseVideo(option ?? {}), option),
280
412
  compressImage: (option) => invokeWxApi(() => driver.compressImage(option), option),
281
- clearStorage: (option) => invokeWxApi(() => {
282
- driver.clearStorageSync();
283
- return { errMsg: "clearStorage:ok" };
284
- }, option),
413
+ clearStorage: (option) => invokeWxApi(() => ({ errMsg: (driver.clearStorageSync(), "clearStorage:ok") }), option),
285
414
  clearStorageSync: () => driver.clearStorageSync(),
286
415
  createAnimation: (option) => driver.createAnimation(option),
287
416
  createCanvasContext: (canvasId, component) => driver.createCanvasContext(canvasId, component),
@@ -316,6 +445,16 @@ function createHeadlessWx(driver) {
316
445
  if (callback) callbacks.push(callback);
317
446
  return query;
318
447
  },
448
+ node: (callback) => {
449
+ requests.push({
450
+ fields: { node: true },
451
+ selector,
452
+ single,
453
+ target
454
+ });
455
+ if (callback) callbacks.push(callback);
456
+ return query;
457
+ },
319
458
  scrollOffset: (callback) => {
320
459
  requests.push({
321
460
  fields: { scrollOffset: true },
@@ -347,12 +486,20 @@ function createHeadlessWx(driver) {
347
486
  getEnterOptionsSync: () => driver.getEnterOptionsSync(),
348
487
  getFileInfo: (option) => invokeWxApi(() => driver.getFileInfo(option), option),
349
488
  getImageInfo: (option) => invokeWxApi(() => driver.getImageInfo(option), option),
489
+ getLocation: (option) => invokeWxApi(() => driver.getLocation(option), option),
490
+ getLocale: () => {
491
+ const locale = driver.getSystemInfoSync().language.trim().replace("_", "-").toLowerCase();
492
+ if (locale === "zh-tw" || locale === "zh-hk" || locale === "zh-mo" || locale.startsWith("zh-hant")) return "zh-Hant";
493
+ if (locale.startsWith("zh")) return "zh-Hans";
494
+ return locale.split("-")[0] || "en";
495
+ },
350
496
  getVideoInfo: (option) => invokeWxApi(() => driver.getVideoInfo(option), option),
351
497
  getFileSystemManager: () => driver.getFileSystemManager(),
352
498
  getSavedFileInfo: (option) => invokeWxApi(() => driver.getSavedFileInfo(option), option),
353
499
  getSavedFileList: (option) => invokeWxApi(() => driver.getSavedFileList(option), option),
354
500
  getAppBaseInfo: (option) => invokeWxApi(() => driver.getAppBaseInfoSync(), option),
355
501
  getAppBaseInfoSync: () => driver.getAppBaseInfoSync(),
502
+ getDeviceInfo: () => driver.getDeviceInfo(),
356
503
  getLaunchOptionsSync: () => driver.getLaunchOptionsSync(),
357
504
  getClipboardData: (option) => invokeWxApi(() => driver.getClipboardData(), option),
358
505
  getMenuButtonBoundingClientRect: () => driver.getMenuButtonBoundingClientRect(),
@@ -368,6 +515,10 @@ function createHeadlessWx(driver) {
368
515
  getSystemInfoSync: () => driver.getSystemInfoSync(),
369
516
  getWindowInfo: (option) => invokeWxApi(() => driver.getWindowInfoSync(), option),
370
517
  getWindowInfoSync: () => driver.getWindowInfoSync(),
518
+ loadFontFace: (option) => invokeWxApi(() => {
519
+ if (!option || typeof option.family !== "string" || !option.family.trim() || typeof option.source !== "string" || !option.source.trim()) throw new TypeError("loadFontFace:fail invalid options");
520
+ return { errMsg: "loadFontFace:ok" };
521
+ }, option),
371
522
  hideLoading: (option) => invokeWxApi(() => driver.hideLoading(), option),
372
523
  hideToast: () => driver.hideToast(),
373
524
  downloadFile: (option) => driver.downloadFile(option),
@@ -399,6 +550,7 @@ function createHeadlessWx(driver) {
399
550
  return { errMsg: "removeStorage:ok" };
400
551
  }, option),
401
552
  removeStorageSync: (key) => driver.removeStorageSync(key),
553
+ rpx2px,
402
554
  request: (option) => driver.request(option),
403
555
  saveFile: (option) => invokeWxApi(() => driver.saveFile(option), option),
404
556
  setBackgroundColor: (option) => invokeWxApi(() => driver.setBackgroundColor(option), option),
@@ -431,7 +583,8 @@ function createHeadlessWx(driver) {
431
583
  uploadFile: (option) => driver.uploadFile(option),
432
584
  removeTabBarBadge: (option) => invokeWxApi(() => driver.removeTabBarBadge(option), option),
433
585
  setTabBarBadge: (option) => invokeWxApi(() => driver.setTabBarBadge(option), option),
434
- updateShareMenu: (option) => invokeWxApi(() => driver.updateShareMenu(option ?? {}), option)
586
+ updateShareMenu: (option) => invokeWxApi(() => driver.updateShareMenu(option ?? {}), option),
587
+ upx2px: rpx2px
435
588
  };
436
589
  }
437
590
  //#endregion
@@ -472,7 +625,7 @@ function resolveRequiredModulePath$1(files, importer, request) {
472
625
  for (const candidate of candidates) if (hasBrowserVirtualFile(files, candidate)) return candidate;
473
626
  throw createRequireNotFoundError$1(request, importer);
474
627
  }
475
- function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver) {
628
+ function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, kernel, globals) {
476
629
  const wx = createHeadlessWx(wxDriver);
477
630
  return {
478
631
  App(definition) {
@@ -491,50 +644,64 @@ function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver)
491
644
  return registerPageDefinition(registries, definition);
492
645
  },
493
646
  URLSearchParams,
494
- clearInterval,
495
- clearTimeout,
496
- console,
647
+ clearInterval: (handle) => kernel.scheduler.clearInterval(handle),
648
+ clearTimeout: (handle) => kernel.scheduler.clearTimeout(handle),
649
+ console: kernel.diagnostics.createConsole(),
497
650
  getApp,
498
651
  getCurrentPages,
499
652
  globalThis: void 0,
500
653
  require: void 0,
501
- setInterval,
502
- setTimeout,
503
- wx
654
+ setInterval: kernel.scheduler.setInterval.bind(kernel.scheduler),
655
+ setTimeout: kernel.scheduler.setTimeout.bind(kernel.scheduler),
656
+ wx,
657
+ ...globals
504
658
  };
505
659
  }
506
- function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, wxDriver) {
660
+ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, wxDriver, options) {
507
661
  const moduleCache = /* @__PURE__ */ new Map();
508
- const executionContext = createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver);
662
+ const executionContext = createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {});
509
663
  executionContext.globalThis = executionContext;
510
664
  function executeModule(filePath, loadContext) {
511
665
  const resolvedPath = normalize(filePath);
512
666
  const cached = moduleCache.get(resolvedPath);
513
- if (cached) return cached.exports;
667
+ if (cached) return cached;
514
668
  const source = readBrowserVirtualFile(files, resolvedPath);
515
- if (typeof source !== "string") throw new Error(`Missing virtual module in browser simulator runtime: ${resolvedPath}`);
516
- const module = { exports: {} };
669
+ if (typeof source !== "string") throw new TypeError(`Missing virtual module in browser simulator runtime: ${resolvedPath}`);
670
+ const module = {
671
+ componentDefinitions: [],
672
+ exports: {}
673
+ };
517
674
  moduleCache.set(resolvedPath, module);
675
+ const registeredDefinitionsBefore = new Set(registries.components.values());
676
+ const requiredComponentDefinitions = [];
518
677
  const previousLoadContext = registries.currentLoadContext;
519
678
  registries.currentLoadContext = loadContext;
520
- const localRequire = (request) => {
679
+ const localRequire = ((request) => {
521
680
  const requiredPath = resolveRequiredModulePath$1(files, resolvedPath, request);
522
681
  if (requiredPath.endsWith(".json")) {
523
682
  const content = readBrowserVirtualFile(files, requiredPath);
524
- if (typeof content !== "string") throw new Error(`Missing virtual json module in browser simulator runtime: ${requiredPath}`);
683
+ if (typeof content !== "string") throw new TypeError(`Missing virtual json module in browser simulator runtime: ${requiredPath}`);
525
684
  return JSON.parse(content);
526
685
  }
527
- return executeModule(requiredPath, null);
528
- };
686
+ const requiredModule = executeModule(requiredPath, null);
687
+ requiredComponentDefinitions.push(...requiredModule.componentDefinitions);
688
+ return requiredModule.exports;
689
+ });
690
+ localRequire.async = (request) => Promise.resolve().then(() => localRequire(request));
529
691
  try {
530
692
  const contextEntries = Object.entries(executionContext);
531
693
  new Function(...contextEntries.map(([key]) => key), "exports", "module", "require", "__filename", "__dirname", source)(...contextEntries.map(([, value]) => value), module.exports, module, localRequire, resolvedPath, dirname(resolvedPath));
532
- return module.exports;
694
+ const registeredDefinitions = [...registries.components.values()].filter((definition) => !registeredDefinitionsBefore.has(definition));
695
+ module.componentDefinitions = [.../* @__PURE__ */ new Set([...requiredComponentDefinitions, ...registeredDefinitions])];
696
+ return module;
533
697
  } finally {
534
698
  registries.currentLoadContext = previousLoadContext;
535
699
  }
536
700
  }
537
701
  return {
702
+ close() {
703
+ moduleCache.clear();
704
+ },
538
705
  executeAppModule(filePath) {
539
706
  executeModule(filePath, { kind: "app" });
540
707
  if (!registries.appDefinition) throw new Error(`App() was not registered while executing ${normalize(filePath)} in browser simulator runtime.`);
@@ -550,17 +717,172 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
550
717
  return definition;
551
718
  },
552
719
  executeComponentModule(filePath, id) {
553
- executeModule(filePath, {
720
+ const loadedModule = executeModule(filePath, {
554
721
  kind: "component",
555
722
  route: id
556
723
  });
557
- const definition = registries.components.get(id);
724
+ const definition = registries.components.get(id) ?? registerExportedComponentDefinition(registries, id, loadedModule.exports, loadedModule.componentDefinitions.at(-1));
558
725
  if (!definition) throw new Error(`Component() was not registered for id "${id}" while executing ${normalize(filePath)}.`);
559
726
  return definition;
727
+ },
728
+ wx: executionContext.wx
729
+ };
730
+ }
731
+ //#endregion
732
+ //#region src/kernel/artifactSource.ts
733
+ function normalizeArtifactPath(filePath) {
734
+ return path.normalize(path.resolve(filePath));
735
+ }
736
+ function createFileSystemArtifactSource() {
737
+ return {
738
+ has: (filePath) => fs.existsSync(filePath),
739
+ readText(filePath) {
740
+ try {
741
+ return fs.readFileSync(filePath, "utf8");
742
+ } catch {
743
+ return;
744
+ }
745
+ }
746
+ };
747
+ }
748
+ function createMemoryArtifactSource(entries) {
749
+ const files = /* @__PURE__ */ new Map();
750
+ for (const [filePath, content] of entries) files.set(normalizeArtifactPath(filePath), content);
751
+ return {
752
+ has: (filePath) => files.has(normalizeArtifactPath(filePath)),
753
+ readText: (filePath) => files.get(normalizeArtifactPath(filePath))
754
+ };
755
+ }
756
+ function createOverlayArtifactSource(overlay, fallback) {
757
+ return {
758
+ has: (filePath) => overlay.has(filePath) || fallback.has(filePath),
759
+ readText(filePath) {
760
+ return overlay.has(filePath) ? overlay.readText(filePath) : fallback.readText(filePath);
560
761
  }
561
762
  };
562
763
  }
563
764
  //#endregion
765
+ //#region src/kernel/diagnostics.ts
766
+ var RuntimeDiagnostics = class {
767
+ entries = [];
768
+ clear() {
769
+ this.entries.length = 0;
770
+ }
771
+ getEntries() {
772
+ return this.entries.map((entry) => ({
773
+ ...entry,
774
+ args: [...entry.args]
775
+ }));
776
+ }
777
+ record(level, args) {
778
+ this.entries.push({
779
+ args: [...args],
780
+ level,
781
+ timestamp: Date.now()
782
+ });
783
+ }
784
+ createConsole(baseConsole = console) {
785
+ const runtimeConsole = Object.create(baseConsole);
786
+ runtimeConsole.error = (...args) => {
787
+ this.record("error", args);
788
+ baseConsole.error(...args);
789
+ };
790
+ runtimeConsole.warn = (...args) => {
791
+ this.record("warn", args);
792
+ baseConsole.warn(...args);
793
+ };
794
+ return runtimeConsole;
795
+ }
796
+ };
797
+ //#endregion
798
+ //#region src/kernel/platform.ts
799
+ function wechat() {
800
+ return { name: "wechat" };
801
+ }
802
+ //#endregion
803
+ //#region src/kernel/scheduler.ts
804
+ var RuntimeScheduler = class {
805
+ intervals = /* @__PURE__ */ new Set();
806
+ timeouts = /* @__PURE__ */ new Set();
807
+ closed = false;
808
+ onError;
809
+ constructor(onError) {
810
+ this.onError = onError;
811
+ }
812
+ clearInterval(handle) {
813
+ this.intervals.delete(handle);
814
+ clearInterval(handle);
815
+ }
816
+ clearTimeout(handle) {
817
+ this.timeouts.delete(handle);
818
+ clearTimeout(handle);
819
+ }
820
+ close() {
821
+ if (this.closed) return;
822
+ this.closed = true;
823
+ for (const handle of this.intervals) clearInterval(handle);
824
+ for (const handle of this.timeouts) clearTimeout(handle);
825
+ this.intervals.clear();
826
+ this.timeouts.clear();
827
+ }
828
+ queueMicrotask(handler) {
829
+ if (this.closed) throw new Error("Cannot schedule work after the runtime session has closed.");
830
+ queueMicrotask(() => {
831
+ if (this.closed) return;
832
+ try {
833
+ handler();
834
+ } catch (error) {
835
+ this.onError(error);
836
+ }
837
+ });
838
+ }
839
+ setInterval(handler, timeout, ...args) {
840
+ if (this.closed) throw new Error("Cannot schedule work after the runtime session has closed.");
841
+ const handle = setInterval(() => {
842
+ try {
843
+ handler(...args);
844
+ } catch (error) {
845
+ this.onError(error);
846
+ }
847
+ }, timeout);
848
+ this.intervals.add(handle);
849
+ return handle;
850
+ }
851
+ setTimeout(handler, timeout, ...args) {
852
+ if (this.closed) throw new Error("Cannot schedule work after the runtime session has closed.");
853
+ const handle = setTimeout(() => {
854
+ this.timeouts.delete(handle);
855
+ try {
856
+ handler(...args);
857
+ } catch (error) {
858
+ this.onError(error);
859
+ }
860
+ }, timeout);
861
+ this.timeouts.add(handle);
862
+ return handle;
863
+ }
864
+ };
865
+ //#endregion
866
+ //#region src/kernel/runtimeKernel.ts
867
+ var RuntimeKernel = class {
868
+ diagnostics = new RuntimeDiagnostics();
869
+ scheduler = new RuntimeScheduler((error) => {
870
+ this.diagnostics.record("exception", [error]);
871
+ });
872
+ closed = false;
873
+ assertActive() {
874
+ if (this.closed) throw new Error("The headless runtime session has already closed.");
875
+ }
876
+ close() {
877
+ if (this.closed) return;
878
+ this.closed = true;
879
+ this.scheduler.close();
880
+ }
881
+ get isClosed() {
882
+ return this.closed;
883
+ }
884
+ };
885
+ //#endregion
564
886
  //#region src/project/resolveRoutes.ts
565
887
  const LEADING_SLASH_RE$6 = /^\/+/;
566
888
  const TRAILING_SLASH_RE$1 = /\/+$/;
@@ -609,6 +931,7 @@ function resolveRoutesFromAppConfig(config) {
609
931
  //#region src/project/createProjectDescriptor.ts
610
932
  function createProjectDescriptor(options) {
611
933
  return {
934
+ artifactSource: options.artifactSource ?? createFileSystemArtifactSource(),
612
935
  appConfig: options.appConfig,
613
936
  appConfigPath: options.appConfigPath,
614
937
  miniprogramRoot: options.miniprogramRoot,
@@ -638,6 +961,10 @@ function createBrowserProject(files, options = {}) {
638
961
  return createProjectDescriptor({
639
962
  appConfig,
640
963
  appConfigPath,
964
+ artifactSource: {
965
+ has: (filePath) => hasBrowserVirtualFile(files, filePath),
966
+ readText: (filePath) => readBrowserVirtualFile(files, filePath)
967
+ },
641
968
  miniprogramRoot: options.miniprogramRoot ?? ".",
642
969
  miniprogramRootPath: options.miniprogramRootPath ?? "/",
643
970
  projectPath: options.projectPath ?? "browser://simulator",
@@ -645,9 +972,12 @@ function createBrowserProject(files, options = {}) {
645
972
  });
646
973
  }
647
974
  //#endregion
648
- //#region src/runtime/componentInstance.ts
975
+ //#region src/runtime/componentInstance/shared.ts
649
976
  const ARRAY_INDEX_PATH_RE$1 = /\[(\d+)\]/g;
650
977
  const ARRAY_INDEX_SEGMENT_RE$1 = /^\d+$/;
978
+ function cloneObject$1(value) {
979
+ return JSON.parse(JSON.stringify(value));
980
+ }
651
981
  function bindFunction$2(target, key, value) {
652
982
  if (typeof value !== "function") {
653
983
  target[key] = value;
@@ -655,14 +985,27 @@ function bindFunction$2(target, key, value) {
655
985
  }
656
986
  target[key] = (...args) => value.apply(target, args);
657
987
  }
658
- function cloneObject$1(value) {
659
- return JSON.parse(JSON.stringify(value));
660
- }
661
988
  function cloneValue(value) {
662
989
  if (Array.isArray(value)) return JSON.parse(JSON.stringify(value));
663
990
  if (value && typeof value === "object") return cloneObject$1(value);
664
991
  return value;
665
992
  }
993
+ function isStructuralValue(value) {
994
+ return value !== null && typeof value === "object";
995
+ }
996
+ function hasComponentPropertyValueChanged(currentValue, previousSnapshot, nextValue, bindingAffected) {
997
+ const identityChanged = !Object.is(currentValue, nextValue);
998
+ if (!identityChanged && !bindingAffected) return false;
999
+ if (!isStructuralValue(currentValue) && !isStructuralValue(nextValue)) return identityChanged;
1000
+ try {
1001
+ return JSON.stringify(previousSnapshot) !== JSON.stringify(nextValue);
1002
+ } catch {
1003
+ return identityChanged;
1004
+ }
1005
+ }
1006
+ function cloneRecord(value) {
1007
+ return cloneObject$1(value);
1008
+ }
666
1009
  function parseDataPath$1(path) {
667
1010
  return path.replace(ARRAY_INDEX_PATH_RE$1, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
668
1011
  }
@@ -688,13 +1031,70 @@ function assignByPath$1(target, path, value) {
688
1031
  const normalizedLeafSegment = isArrayIndexSegment$1(leafSegment) ? Number(leafSegment) : leafSegment;
689
1032
  current[normalizedLeafSegment] = value;
690
1033
  }
1034
+ function mergeRecord(...records) {
1035
+ return Object.assign({}, ...records.filter(Boolean));
1036
+ }
1037
+ //#endregion
1038
+ //#region src/runtime/componentInstance/observers.ts
1039
+ function runPropertyObservers(definition, instance, changedKeys, previousProperties) {
1040
+ const propOptions = definition.properties;
1041
+ if (!propOptions || typeof propOptions !== "object" || Array.isArray(propOptions)) return;
1042
+ for (const changedKey of changedKeys) {
1043
+ const option = propOptions[changedKey];
1044
+ if (!option || typeof option !== "object" || Array.isArray(option)) continue;
1045
+ const observer = option.observer;
1046
+ if (typeof observer !== "function") continue;
1047
+ observer.call(instance, instance.properties[changedKey], previousProperties[changedKey]);
1048
+ }
1049
+ }
1050
+ function normalizeObserverPattern(pattern) {
1051
+ return pattern.split(",").map((item) => item.trim()).filter(Boolean);
1052
+ }
1053
+ function resolveObservedValue(instance, pattern) {
1054
+ if (pattern === "**") return {
1055
+ ...instance.properties,
1056
+ ...instance.data
1057
+ };
1058
+ const segments = parseDataPath$1(pattern);
1059
+ if (segments.length === 0) return;
1060
+ const [rootSegment, ...restSegments] = segments;
1061
+ let current = (Object.hasOwn(instance.properties, rootSegment) ? instance.properties : instance.data)?.[rootSegment];
1062
+ for (const segment of restSegments) {
1063
+ const normalizedSegment = isArrayIndexSegment$1(segment) ? Number(segment) : segment;
1064
+ current = current?.[normalizedSegment];
1065
+ }
1066
+ return current;
1067
+ }
1068
+ function matchObserverPattern(pattern, changedKeys) {
1069
+ if (pattern === "**") return changedKeys.length > 0;
1070
+ const patterns = normalizeObserverPattern(pattern);
1071
+ return changedKeys.some((changedKey) => {
1072
+ return patterns.some((item) => {
1073
+ if (item === "**") return true;
1074
+ if (changedKey === item) return true;
1075
+ return changedKey.startsWith(`${item}.`) || changedKey.startsWith(`${item}[`);
1076
+ });
1077
+ });
1078
+ }
1079
+ function runComponentObservers(definition, instance, changedKeys, previousProperties = {}) {
1080
+ if (changedKeys.length === 0) return;
1081
+ runPropertyObservers(definition, instance, changedKeys, previousProperties);
1082
+ const observers = definition.observers;
1083
+ if (observers && typeof observers === "object" && !Array.isArray(observers)) for (const [pattern, handler] of Object.entries(observers)) {
1084
+ if (typeof handler !== "function" || !matchObserverPattern(pattern, changedKeys)) continue;
1085
+ const args = normalizeObserverPattern(pattern).map((item) => resolveObservedValue(instance, item));
1086
+ handler.call(instance, ...args);
1087
+ }
1088
+ }
1089
+ //#endregion
1090
+ //#region src/runtime/componentInstance/properties.ts
691
1091
  function resolveInitialData$2(definition) {
692
1092
  const rawData = definition.data;
693
1093
  if (typeof rawData === "function") {
694
1094
  const next = rawData.call(definition);
695
- return next && typeof next === "object" && !Array.isArray(next) ? cloneObject$1(next) : {};
1095
+ return next && typeof next === "object" && !Array.isArray(next) ? cloneRecord(next) : {};
696
1096
  }
697
- return rawData && typeof rawData === "object" && !Array.isArray(rawData) ? cloneObject$1(rawData) : {};
1097
+ return rawData && typeof rawData === "object" && !Array.isArray(rawData) ? cloneRecord(rawData) : {};
698
1098
  }
699
1099
  function isBehaviorDefinition(value) {
700
1100
  return !!value && typeof value === "object" && !Array.isArray(value) && value.__isHeadlessBehavior__ === true;
@@ -709,9 +1109,6 @@ function flattenBehaviors(definition) {
709
1109
  }
710
1110
  return flattened;
711
1111
  }
712
- function mergeRecord(...records) {
713
- return Object.assign({}, ...records.filter(Boolean));
714
- }
715
1112
  function normalizeComponentDefinition(definition) {
716
1113
  const behaviors = flattenBehaviors(definition);
717
1114
  if (behaviors.length === 0) return definition;
@@ -732,11 +1129,21 @@ function normalizeComponentDefinition(definition) {
732
1129
  };
733
1130
  return mergedDefinition;
734
1131
  }
1132
+ function normalizePropertyConstructor(candidate) {
1133
+ if (candidate === String || candidate === Number || candidate === Boolean || candidate === Array || candidate === Object) return candidate;
1134
+ if (typeof candidate !== "function") return;
1135
+ if (candidate.name === "String") return String;
1136
+ if (candidate.name === "Number") return Number;
1137
+ if (candidate.name === "Boolean") return Boolean;
1138
+ if (candidate.name === "Array") return Array;
1139
+ if (candidate.name === "Object") return Object;
1140
+ }
735
1141
  function normalizePropertyType(option) {
736
1142
  if (option === null) return null;
737
- if (option === String || option === Number || option === Boolean || option === Array || option === Object) return option;
1143
+ const constructor = normalizePropertyConstructor(option);
1144
+ if (constructor) return constructor;
738
1145
  if (!option || typeof option !== "object" || Array.isArray(option)) return;
739
- return option.type;
1146
+ return normalizePropertyType(option.type);
740
1147
  }
741
1148
  function resolvePropertyTypeCandidates(option) {
742
1149
  const candidates = [];
@@ -744,7 +1151,10 @@ function resolvePropertyTypeCandidates(option) {
744
1151
  if (primaryType) candidates.push(primaryType);
745
1152
  if (option && typeof option === "object" && !Array.isArray(option)) {
746
1153
  const optionalTypes = option.optionalTypes;
747
- if (Array.isArray(optionalTypes)) candidates.push(...optionalTypes);
1154
+ if (Array.isArray(optionalTypes)) for (const optionalType of optionalTypes) {
1155
+ const normalizedType = normalizePropertyType(optionalType);
1156
+ if (normalizedType !== void 0) candidates.push(normalizedType);
1157
+ }
748
1158
  }
749
1159
  return candidates;
750
1160
  }
@@ -753,7 +1163,7 @@ function resolveDefaultValueByType(type) {
753
1163
  if (type === Boolean) return false;
754
1164
  if (type === String) return "";
755
1165
  if (type === Array) return [];
756
- if (type === Object) return {};
1166
+ if (type === Object) return null;
757
1167
  if (type === null) return null;
758
1168
  }
759
1169
  function matchesRuntimeType(rawValue, type) {
@@ -785,7 +1195,6 @@ function coerceComponentPropertyValue(rawValue, option) {
785
1195
  if (type === String) return rawValue == null ? "" : String(rawValue);
786
1196
  if (type === Array && Array.isArray(rawValue)) return rawValue;
787
1197
  if (type === Object && rawValue && typeof rawValue === "object" && !Array.isArray(rawValue)) return rawValue;
788
- if (type === null) return rawValue;
789
1198
  }
790
1199
  if (primaryType === Number) {
791
1200
  const nextValue = typeof rawValue === "number" ? rawValue : Number(rawValue);
@@ -798,81 +1207,38 @@ function coerceComponentPropertyValue(rawValue, option) {
798
1207
  return Boolean(rawValue);
799
1208
  }
800
1209
  if (primaryType === String) return rawValue == null ? "" : String(rawValue);
1210
+ if (fallbackCandidates.includes(null)) return rawValue;
801
1211
  return rawValue;
802
1212
  }
1213
+ function resolvePropertyDefaultValue(option, definition) {
1214
+ if (!option || typeof option !== "object" || Array.isArray(option) || !("value" in option)) return;
1215
+ const rawDefaultValue = option.value;
1216
+ return cloneValue(typeof rawDefaultValue === "function" ? rawDefaultValue.call(definition) : rawDefaultValue);
1217
+ }
1218
+ function normalizeComponentPropertyValue(definition, key, rawValue) {
1219
+ const option = definition.properties?.[key];
1220
+ if (rawValue == null) {
1221
+ if (option && typeof option === "object" && !Array.isArray(option) && "value" in option) return resolvePropertyDefaultValue(option, definition);
1222
+ return cloneValue(resolveDefaultValueByType(normalizePropertyType(option)));
1223
+ }
1224
+ return coerceComponentPropertyValue(rawValue, option);
1225
+ }
803
1226
  function resolveInitialProperties(definition, properties) {
804
1227
  const resolved = {};
805
1228
  const propOptions = definition.properties;
806
1229
  if (propOptions && typeof propOptions === "object" && !Array.isArray(propOptions)) for (const [key, option] of Object.entries(propOptions)) {
807
1230
  if (Object.hasOwn(properties, key)) {
808
- resolved[key] = coerceComponentPropertyValue(properties[key], option);
1231
+ resolved[key] = normalizeComponentPropertyValue(definition, key, properties[key]);
809
1232
  continue;
810
1233
  }
811
- if (option && typeof option === "object" && !Array.isArray(option) && "value" in option) resolved[key] = cloneValue(typeof option.value === "function" ? option.value.call(definition) : option.value);
1234
+ if (option && typeof option === "object" && !Array.isArray(option) && "value" in option) resolved[key] = resolvePropertyDefaultValue(option, definition);
812
1235
  else resolved[key] = cloneValue(resolveDefaultValueByType(normalizePropertyType(option)));
813
1236
  }
814
1237
  for (const [key, value] of Object.entries(properties)) if (!(key in resolved)) resolved[key] = value;
815
1238
  return resolved;
816
1239
  }
817
- function resolvePropertyDefaultValue(option) {
818
- if (!option || typeof option !== "object" || Array.isArray(option) || !("value" in option)) return;
819
- return cloneValue(option.value);
820
- }
821
- function runPropertyObservers(definition, instance, changedKeys, previousProperties) {
822
- const propOptions = definition.properties;
823
- if (!propOptions || typeof propOptions !== "object" || Array.isArray(propOptions)) return;
824
- for (const changedKey of changedKeys) {
825
- const option = propOptions[changedKey];
826
- if (!option || typeof option !== "object" || Array.isArray(option)) continue;
827
- const observer = option.observer;
828
- if (typeof observer !== "function") continue;
829
- observer.call(instance, instance.properties[changedKey], previousProperties[changedKey]);
830
- }
831
- }
832
- function normalizeObserverPattern(pattern) {
833
- return pattern.split(",").map((item) => item.trim()).filter(Boolean);
834
- }
835
- function resolveObservedValue(instance, pattern) {
836
- if (pattern === "**") return {
837
- ...instance.properties,
838
- ...instance.data
839
- };
840
- const segments = parseDataPath$1(pattern);
841
- if (segments.length === 0) return;
842
- const [rootSegment, ...restSegments] = segments;
843
- let current = (Object.hasOwn(instance.properties, rootSegment) ? instance.properties : instance.data)?.[rootSegment];
844
- for (const segment of restSegments) {
845
- const normalizedSegment = isArrayIndexSegment$1(segment) ? Number(segment) : segment;
846
- current = current?.[normalizedSegment];
847
- }
848
- return current;
849
- }
850
- function matchObserverPattern(pattern, changedKeys) {
851
- if (pattern === "**") return changedKeys.length > 0;
852
- const patterns = normalizeObserverPattern(pattern);
853
- return changedKeys.some((changedKey) => {
854
- return patterns.some((item) => {
855
- if (item === "**") return true;
856
- if (changedKey === item) return true;
857
- return changedKey.startsWith(`${item}.`) || changedKey.startsWith(`${item}[`);
858
- });
859
- });
860
- }
861
- function runComponentObservers(definition, instance, changedKeys, previousProperties = {}) {
862
- if (changedKeys.length === 0) return;
863
- runPropertyObservers(definition, instance, changedKeys, previousProperties);
864
- const observers = definition.observers;
865
- if (observers && typeof observers === "object" && !Array.isArray(observers)) for (const [pattern, handler] of Object.entries(observers)) {
866
- if (typeof handler !== "function" || !matchObserverPattern(pattern, changedKeys)) continue;
867
- const args = normalizeObserverPattern(pattern).map((item) => resolveObservedValue(instance, item));
868
- handler.call(instance, ...args);
869
- }
870
- }
871
- function normalizeComponentPropertyValue(definition, key, rawValue) {
872
- const option = definition.properties?.[key];
873
- if (rawValue == null) return resolvePropertyDefaultValue(option);
874
- return coerceComponentPropertyValue(rawValue, option);
875
- }
1240
+ //#endregion
1241
+ //#region src/runtime/componentInstance/index.ts
876
1242
  function createComponentInstance(options) {
877
1243
  const definition = normalizeComponentDefinition(options.definition);
878
1244
  const instance = {
@@ -884,7 +1250,8 @@ function createComponentInstance(options) {
884
1250
  const changedKeys = Object.keys(patch);
885
1251
  for (const [key, value] of Object.entries(patch)) assignByPath$1(instance.data, key, value);
886
1252
  runComponentObservers(definition, instance, changedKeys);
887
- callback?.();
1253
+ if (options.requestRender) options.requestRender(callback);
1254
+ else callback?.();
888
1255
  },
889
1256
  triggerEvent(eventName, detail, triggerOptions) {
890
1257
  options.triggerEvent?.(instance, eventName, detail, triggerOptions);
@@ -913,21 +1280,268 @@ function runComponentPageLifetime(instance, lifetimeName, payload) {
913
1280
  handler.call(instance, payload);
914
1281
  }
915
1282
  //#endregion
916
- //#region src/browser/render.ts
917
- const LEADING_SLASH_RE$5 = /^\/+/;
1283
+ //#region src/view/eventBinding.ts
1284
+ const LEGACY_EVENT_NAME_RE = /^\w+$/;
1285
+ const EVENT_BINDING_PREFIXES = [
1286
+ {
1287
+ prefix: "bind:",
1288
+ priority: 0,
1289
+ stopAfter: false
1290
+ },
1291
+ {
1292
+ prefix: "catch:",
1293
+ priority: 0,
1294
+ stopAfter: true
1295
+ },
1296
+ {
1297
+ prefix: "bind",
1298
+ priority: 1,
1299
+ stopAfter: false
1300
+ },
1301
+ {
1302
+ prefix: "catch",
1303
+ priority: 1,
1304
+ stopAfter: true
1305
+ }
1306
+ ];
1307
+ function parseEventBinding(attributeName, method) {
1308
+ const definition = EVENT_BINDING_PREFIXES.find((item) => attributeName.startsWith(item.prefix));
1309
+ if (!definition) return null;
1310
+ const eventName = attributeName.slice(definition.prefix.length);
1311
+ if (!eventName || !definition.prefix.endsWith(":") && !LEGACY_EVENT_NAME_RE.test(eventName)) return null;
1312
+ return {
1313
+ eventName,
1314
+ method,
1315
+ priority: definition.priority,
1316
+ stopAfter: definition.stopAfter
1317
+ };
1318
+ }
1319
+ function collectMiniProgramEventBindings(attributes = {}) {
1320
+ const bindings = /* @__PURE__ */ new Map();
1321
+ const priorities = /* @__PURE__ */ new Map();
1322
+ for (const [attributeName, method] of Object.entries(attributes)) {
1323
+ const candidate = parseEventBinding(attributeName, method);
1324
+ if (!candidate || candidate.priority < (priorities.get(candidate.eventName) ?? -1)) continue;
1325
+ bindings.set(candidate.eventName, {
1326
+ method: candidate.method,
1327
+ stopAfter: candidate.stopAfter
1328
+ });
1329
+ priorities.set(candidate.eventName, candidate.priority);
1330
+ }
1331
+ return bindings;
1332
+ }
1333
+ function resolveMiniProgramEventBinding(attributes, eventName) {
1334
+ return collectMiniProgramEventBindings(attributes).get(eventName) ?? null;
1335
+ }
1336
+ //#endregion
1337
+ //#region src/view/selectorQueryScope.ts
1338
+ const MPCORE_COMPONENT_SCOPE_ID = "__mpcoreComponentScopeId";
1339
+ function isScopeCandidate(value) {
1340
+ return typeof value === "object" && value !== null || typeof value === "function";
1341
+ }
1342
+ function resolveScopeCandidates(scope) {
1343
+ const candidates = [];
1344
+ const visited = /* @__PURE__ */ new Set();
1345
+ const queue = [scope];
1346
+ while (queue.length > 0) {
1347
+ const candidate = queue.shift();
1348
+ if (!isScopeCandidate(candidate) || visited.has(candidate)) continue;
1349
+ visited.add(candidate);
1350
+ candidates.push(candidate);
1351
+ queue.push(candidate.$, candidate.$el, candidate.$state, candidate[WEVU_NATIVE_INSTANCE_KEY]);
1352
+ }
1353
+ return candidates;
1354
+ }
1355
+ function resolveSelectorQueryNativeScope(scope, page, components) {
1356
+ if (!scope) return;
1357
+ const nativeScopes = [page, ...components];
1358
+ const nativeScopeSet = new Set(nativeScopes);
1359
+ for (const candidate of resolveScopeCandidates(scope)) {
1360
+ if (nativeScopeSet.has(candidate)) return candidate;
1361
+ const scopeId = candidate[MPCORE_COMPONENT_SCOPE_ID];
1362
+ if (typeof scopeId !== "string" || !scopeId) continue;
1363
+ const currentScope = nativeScopes.find((nativeScope) => nativeScope[MPCORE_COMPONENT_SCOPE_ID] === scopeId);
1364
+ if (currentScope) return currentScope;
1365
+ }
1366
+ return null;
1367
+ }
1368
+ function setSelectorQueryScopeId(scope, scopeId) {
1369
+ Object.defineProperty(scope, MPCORE_COMPONENT_SCOPE_ID, {
1370
+ configurable: true,
1371
+ enumerable: false,
1372
+ value: scopeId,
1373
+ writable: false
1374
+ });
1375
+ }
1376
+ function resolveSelectorQueryScopeId(scope) {
1377
+ if (!scope) return null;
1378
+ for (const candidate of resolveScopeCandidates(scope)) {
1379
+ const scopeId = candidate[MPCORE_COMPONENT_SCOPE_ID];
1380
+ if (typeof scopeId === "string" && scopeId) return scopeId;
1381
+ }
1382
+ return null;
1383
+ }
1384
+ function resolveSelectorQueryScopeSnapshot(scope, snapshots) {
1385
+ if (!scope) return null;
1386
+ for (const candidate of resolveScopeCandidates(scope)) {
1387
+ const snapshot = snapshots.get(candidate);
1388
+ if (snapshot) return {
1389
+ nativeScope: candidate,
1390
+ snapshot
1391
+ };
1392
+ }
1393
+ return null;
1394
+ }
1395
+ //#endregion
1396
+ //#region src/view/templateExpression.ts
1397
+ const expressionCache = /* @__PURE__ */ new Map();
1398
+ const BLOCKED_MEMBER_KEYS = /* @__PURE__ */ new Set([
1399
+ "__proto__",
1400
+ "constructor",
1401
+ "prototype"
1402
+ ]);
1403
+ const NUMERIC_DOT_PATH_RE = /\.(\d+)(?=[.[\s]|$)/g;
1404
+ function isMustacheOnly$2(value) {
1405
+ const trimmed = value.trim();
1406
+ return trimmed.startsWith("{{") && trimmed.endsWith("}}") && !trimmed.includes("{{", 2);
1407
+ }
1408
+ function unwrapMustacheExpression(expression) {
1409
+ const normalized = expression.trim();
1410
+ if (isMustacheOnly$2(normalized)) return normalized.slice(2, -2).trim();
1411
+ return normalized;
1412
+ }
1413
+ function parseTemplateExpression(expression) {
1414
+ const normalized = expression.replace(NUMERIC_DOT_PATH_RE, "[$1]");
1415
+ if (expressionCache.has(normalized)) return expressionCache.get(normalized) ?? null;
1416
+ let parsed = null;
1417
+ try {
1418
+ parsed = parseExpression(normalized);
1419
+ } catch {
1420
+ parsed = null;
1421
+ }
1422
+ expressionCache.set(normalized, parsed);
1423
+ return parsed;
1424
+ }
1425
+ function resolveIdentifier(source, name) {
1426
+ if (name === "undefined") return;
1427
+ if (name === "NaN") return NaN;
1428
+ if (name === "Infinity") return Number.POSITIVE_INFINITY;
1429
+ return source[name];
1430
+ }
1431
+ function resolveMemberKey(node, source) {
1432
+ if (node.computed) return evaluateExpressionNode(node.property, source);
1433
+ return node.property?.name;
1434
+ }
1435
+ function readMemberValue(node, source) {
1436
+ const target = evaluateExpressionNode(node.object, source);
1437
+ if (target == null) return;
1438
+ const key = resolveMemberKey(node, source);
1439
+ if (typeof key !== "string" && typeof key !== "number" || BLOCKED_MEMBER_KEYS.has(String(key))) return;
1440
+ return target[key];
1441
+ }
1442
+ function evaluateUnaryExpression(node, source) {
1443
+ const value = evaluateExpressionNode(node.argument, source);
1444
+ if (node.operator === "!") return !value;
1445
+ if (node.operator === "+") return Number(value);
1446
+ if (node.operator === "-") return -Number(value);
1447
+ if (node.operator === "~") return ~Number(value);
1448
+ if (node.operator === "typeof") return typeof value;
1449
+ if (node.operator === "void") return;
1450
+ }
1451
+ function evaluateBinaryExpression(node, source) {
1452
+ const left = evaluateExpressionNode(node.left, source);
1453
+ const right = evaluateExpressionNode(node.right, source);
1454
+ switch (node.operator) {
1455
+ case "===": return left === right;
1456
+ case "!==": return left !== right;
1457
+ case "==": return left == right;
1458
+ case "!=": return left != right;
1459
+ case "<": return left < right;
1460
+ case "<=": return left <= right;
1461
+ case ">": return left > right;
1462
+ case ">=": return left >= right;
1463
+ case "+": return left + right;
1464
+ case "-": return Number(left) - Number(right);
1465
+ case "*": return Number(left) * Number(right);
1466
+ case "/": return Number(left) / Number(right);
1467
+ case "%": return Number(left) % Number(right);
1468
+ case "**": return Number(left) ** Number(right);
1469
+ case "|": return Number(left) | Number(right);
1470
+ case "&": return Number(left) & Number(right);
1471
+ case "^": return Number(left) ^ Number(right);
1472
+ case "<<": return Number(left) << Number(right);
1473
+ case ">>": return Number(left) >> Number(right);
1474
+ case ">>>": return Number(left) >>> Number(right);
1475
+ case "in": return right != null && (typeof right === "object" || typeof right === "function") ? left in right : false;
1476
+ default: return;
1477
+ }
1478
+ }
1479
+ function evaluateObjectExpression(node, source) {
1480
+ const result = {};
1481
+ for (const property of node.properties ?? []) {
1482
+ if (property.type === "SpreadElement") {
1483
+ const spreadValue = evaluateExpressionNode(property.argument, source);
1484
+ if (spreadValue && typeof spreadValue === "object") Object.assign(result, spreadValue);
1485
+ continue;
1486
+ }
1487
+ if (property.type !== "ObjectProperty") continue;
1488
+ const key = property.computed ? evaluateExpressionNode(property.key, source) : property.key?.name ?? property.key?.value;
1489
+ if (typeof key !== "string" && typeof key !== "number" || BLOCKED_MEMBER_KEYS.has(String(key))) continue;
1490
+ result[key] = evaluateExpressionNode(property.value, source);
1491
+ }
1492
+ return result;
1493
+ }
1494
+ function evaluateTemplateLiteral(node, source) {
1495
+ let result = "";
1496
+ for (let index = 0; index < node.quasis.length; index += 1) {
1497
+ result += node.quasis[index]?.value?.cooked ?? "";
1498
+ if (index < node.expressions.length) result += String(evaluateExpressionNode(node.expressions[index], source) ?? "");
1499
+ }
1500
+ return result;
1501
+ }
1502
+ function evaluateExpressionNode(node, source) {
1503
+ if (!node) return;
1504
+ switch (node.type) {
1505
+ case "Identifier": return resolveIdentifier(source, node.name);
1506
+ case "StringLiteral":
1507
+ case "NumericLiteral":
1508
+ case "BooleanLiteral": return node.value;
1509
+ case "NullLiteral": return null;
1510
+ case "MemberExpression":
1511
+ case "OptionalMemberExpression": return readMemberValue(node, source);
1512
+ case "UnaryExpression": return evaluateUnaryExpression(node, source);
1513
+ case "BinaryExpression": return evaluateBinaryExpression(node, source);
1514
+ case "LogicalExpression": {
1515
+ const left = evaluateExpressionNode(node.left, source);
1516
+ if (node.operator === "&&") return left ? evaluateExpressionNode(node.right, source) : left;
1517
+ if (node.operator === "||") return left || evaluateExpressionNode(node.right, source);
1518
+ if (node.operator === "??") return left ?? evaluateExpressionNode(node.right, source);
1519
+ return;
1520
+ }
1521
+ case "ConditionalExpression": return evaluateExpressionNode(node.test, source) ? evaluateExpressionNode(node.consequent, source) : evaluateExpressionNode(node.alternate, source);
1522
+ case "ArrayExpression": return node.elements.map((item) => evaluateExpressionNode(item, source));
1523
+ case "ObjectExpression": return evaluateObjectExpression(node, source);
1524
+ case "TemplateLiteral": return evaluateTemplateLiteral(node, source);
1525
+ case "SequenceExpression": return node.expressions.reduce((_value, item) => evaluateExpressionNode(item, source), void 0);
1526
+ default: return;
1527
+ }
1528
+ }
1529
+ function resolveTemplateExpression(source, expression) {
1530
+ const normalized = unwrapMustacheExpression(expression);
1531
+ if (!normalized) return;
1532
+ return evaluateExpressionNode(parseTemplateExpression(normalized), source);
1533
+ }
1534
+ //#endregion
1535
+ //#region src/browser/render/shared.ts
918
1536
  const TEMPLATE_INTERPOLATION_RE$2 = /\{\{([^{}]+)\}\}/g;
1537
+ const DATASET_NAME_RE$4 = /-([a-z])/g;
1538
+ const LEADING_SLASH_RE$5 = /^\/+/;
919
1539
  const EVENT_BINDING_ATTRS$1 = [
920
1540
  "bindtap",
921
1541
  "bind:tap",
922
1542
  "catchtap",
923
1543
  "catch:tap"
924
1544
  ];
925
- const COMPONENT_EVENT_PREFIXES$1 = [
926
- "bind:",
927
- "bind",
928
- "catch:",
929
- "catch"
930
- ];
931
1545
  const STRUCTURAL_ATTRS$1 = [
932
1546
  "wx:if",
933
1547
  "wx:elif",
@@ -937,9 +1551,7 @@ const STRUCTURAL_ATTRS$1 = [
937
1551
  "wx:for-index",
938
1552
  "wx:key"
939
1553
  ];
940
- const WX_ELSE_ATTRS$1 = new Set(["wx:elif", "wx:else"]);
941
- const DATASET_NAME_RE$4 = /-([a-z])/g;
942
- const BRACKET_INDEX_RE$1 = /\[(\d+)\]/g;
1554
+ const WX_ELSE_ATTRS$1 = /* @__PURE__ */ new Set(["wx:elif", "wx:else"]);
943
1555
  const CLASS_SPLIT_RE$1 = /\s+/;
944
1556
  const JS_FILE_RE$1 = /\.js$/;
945
1557
  function isMustacheOnly$1(value) {
@@ -970,39 +1582,11 @@ function cloneNode$1(node) {
970
1582
  children: node.children?.map((child) => cloneNode$1(child))
971
1583
  };
972
1584
  }
973
- function parseExpressionSegments$1(expression) {
974
- return expression.replace(BRACKET_INDEX_RE$1, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
975
- }
976
- function unwrapMustacheExpression$1(expression) {
977
- const normalized = expression.trim();
978
- if (isMustacheOnly$1(normalized)) return normalized.slice(2, -2).trim();
979
- return normalized;
980
- }
981
- function resolveLiteralValue$1(expression) {
982
- if (expression === "true") return true;
983
- if (expression === "false") return false;
984
- if (expression === "null") return null;
985
- if (expression === "undefined") return;
986
- if (expression.startsWith("\"") && expression.endsWith("\"") || expression.startsWith("'") && expression.endsWith("'")) return expression.slice(1, -1);
987
- const numericValue = Number(expression);
988
- if (!Number.isNaN(numericValue) && expression !== "") return numericValue;
989
- }
990
- function resolveValueByExpression$1(source, expression) {
991
- const normalized = unwrapMustacheExpression$1(expression);
992
- if (!normalized) return;
993
- if (normalized.startsWith("!")) return !resolveValueByExpression$1(source, normalized.slice(1));
994
- const literalValue = resolveLiteralValue$1(normalized);
995
- if (literalValue !== void 0 || normalized === "undefined") return literalValue;
996
- const segments = parseExpressionSegments$1(normalized);
997
- let current = source;
998
- for (const segment of segments) current = current?.[segment];
999
- return current;
1000
- }
1001
1585
  function resolveValueByPath$2(source, expression) {
1002
- return resolveValueByExpression$1(source, expression) ?? "";
1586
+ return resolveTemplateExpression(source, expression) ?? "";
1003
1587
  }
1004
1588
  function resolveRawValueByPath$1(source, expression) {
1005
- return resolveValueByExpression$1(source, expression);
1589
+ return resolveTemplateExpression(source, expression);
1006
1590
  }
1007
1591
  function interpolateTemplate$2(input, data) {
1008
1592
  return input.replace(TEMPLATE_INTERPOLATION_RE$2, (_match, expression) => {
@@ -1019,6 +1603,8 @@ function parseTemplateDocument$1(templateSource) {
1019
1603
  return parseDocument(`<page>${templateSource}</page>`, {
1020
1604
  xmlMode: false,
1021
1605
  decodeEntities: false,
1606
+ lowerCaseAttributeNames: false,
1607
+ lowerCaseTags: false,
1022
1608
  recognizeSelfClosing: true
1023
1609
  });
1024
1610
  }
@@ -1029,31 +1615,90 @@ function serializeDomNode$2(node) {
1029
1615
  if (!tagName) return (node.children ?? []).map(serializeDomNode$2).join("");
1030
1616
  return `<${tagName}${Object.entries(node.attribs ?? {}).map(([key, value]) => ` ${key}="${escapeAttribute$3(value)}"`).join("")}>${(node.children ?? []).map(serializeDomNode$2).join("")}</${tagName}>`;
1031
1617
  }
1032
- function isTagNode$1(node) {
1033
- return node.type === "tag" && typeof node.name === "string";
1618
+ function isTagNode$1(node) {
1619
+ return node.type === "tag" && typeof node.name === "string";
1620
+ }
1621
+ function isIgnorableTextNode$1(node) {
1622
+ return node.type === "text" && typeof node.data === "string" && node.data.trim() === "";
1623
+ }
1624
+ function resolveAttributeValue$1(value, scope) {
1625
+ if (isMustacheOnly$1(value)) {
1626
+ const expression = value.trim().slice(2, -2);
1627
+ return resolveValueByPath$2(scope.data, expression);
1628
+ }
1629
+ return interpolateTemplate$2(value, scope.data);
1630
+ }
1631
+ function resolveComponentAttributeValue$1(value, scope) {
1632
+ if (isMustacheOnly$1(value)) {
1633
+ const expression = value.trim().slice(2, -2);
1634
+ return resolveRawValueByPath$1(scope.data, expression);
1635
+ }
1636
+ return interpolateTemplate$2(value, scope.data);
1637
+ }
1638
+ function applyNodeBindings$1(node, scope) {
1639
+ if (!isTagNode$1(node)) {
1640
+ if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate$2(node.data, scope.data);
1641
+ return;
1642
+ }
1643
+ node.attribs ??= {};
1644
+ node.attribs["data-sim-scope"] = scope.getScopeId();
1645
+ for (const key of STRUCTURAL_ATTRS$1) delete node.attribs[key];
1646
+ for (const [key, value] of Object.entries({ ...node.attribs })) {
1647
+ if (EVENT_BINDING_ATTRS$1.includes(key)) {
1648
+ node.attribs["data-sim-tap"] = value;
1649
+ continue;
1650
+ }
1651
+ node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue$1(value, scope)) : String(value);
1652
+ }
1653
+ }
1654
+ function createMergedScopeData$1(pageData, componentProperties, componentData) {
1655
+ return {
1656
+ ...pageData,
1657
+ ...componentProperties,
1658
+ ...componentData
1659
+ };
1034
1660
  }
1035
- function isIgnorableTextNode$1(node) {
1036
- return node.type === "text" && typeof node.data === "string" && node.data.trim() === "";
1661
+ function evaluateConditionalBranch$1(node, scope) {
1662
+ const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
1663
+ if (condition == null) return true;
1664
+ return Boolean(resolveRawValueByPath$1(scope.data, condition));
1037
1665
  }
1038
- function resolveAttributeValue$1(value, scope) {
1039
- if (isMustacheOnly$1(value)) {
1040
- const expression = value.trim().slice(2, -2);
1041
- return resolveValueByPath$2(scope.data, expression);
1042
- }
1043
- return interpolateTemplate$2(value, scope.data);
1666
+ function createLoopScope$1(scope, itemName, indexName, item, index) {
1667
+ return {
1668
+ ...scope,
1669
+ data: {
1670
+ ...scope.data,
1671
+ [indexName]: index,
1672
+ [itemName]: item
1673
+ }
1674
+ };
1044
1675
  }
1045
- function resolveComponentAttributeValue$1(value, scope) {
1046
- if (isMustacheOnly$1(value)) {
1047
- const expression = value.trim().slice(2, -2);
1048
- return resolveRawValueByPath$1(scope.data, expression);
1676
+ //#endregion
1677
+ //#region src/browser/render/component.ts
1678
+ function resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, alias, genericComponentBasePath) {
1679
+ const usingComponents = resolveUsingComponents$1(context.files, ownerJsonPath, ownerFilePath);
1680
+ const componentBasePath = genericComponentBasePath ?? usingComponents.get(alias);
1681
+ if (!componentBasePath) return null;
1682
+ const filePath = `${componentBasePath}.js`;
1683
+ const templatePath = `${componentBasePath}.wxml`;
1684
+ return {
1685
+ definition: context.moduleLoader.executeComponentModule(filePath, componentBasePath),
1686
+ filePath,
1687
+ templatePath
1688
+ };
1689
+ }
1690
+ function readComponentConfig$1(files, jsonPath) {
1691
+ const source = readBrowserVirtualFile(files, jsonPath);
1692
+ if (typeof source !== "string") return {};
1693
+ try {
1694
+ return JSON.parse(source);
1695
+ } catch {
1696
+ return {};
1049
1697
  }
1050
- return interpolateTemplate$2(value, scope.data);
1051
1698
  }
1052
1699
  function resolveUsingComponents$1(files, ownerJsonPath, ownerFilePath) {
1053
- const ownerJson = readBrowserVirtualFile(files, ownerJsonPath);
1054
- if (typeof ownerJson !== "string") return /* @__PURE__ */ new Map();
1055
1700
  try {
1056
- const usingComponents = JSON.parse(ownerJson).usingComponents;
1701
+ const usingComponents = readComponentConfig$1(files, ownerJsonPath).usingComponents;
1057
1702
  if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
1058
1703
  const resolved = /* @__PURE__ */ new Map();
1059
1704
  for (const [alias, rawPath] of Object.entries(usingComponents)) {
@@ -1066,30 +1711,28 @@ function resolveUsingComponents$1(files, ownerJsonPath, ownerFilePath) {
1066
1711
  return /* @__PURE__ */ new Map();
1067
1712
  }
1068
1713
  }
1069
- function resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, alias) {
1070
- const componentBasePath = resolveUsingComponents$1(context.files, ownerJsonPath, ownerFilePath).get(alias);
1071
- if (!componentBasePath) return null;
1072
- const filePath = `${componentBasePath}.js`;
1073
- const templatePath = `${componentBasePath}.wxml`;
1074
- return {
1075
- definition: context.moduleLoader.executeComponentModule(filePath, componentBasePath),
1076
- filePath,
1077
- templatePath
1078
- };
1714
+ function resolveComponentGenerics$1(context, hostNode, ownerJsonPath, ownerFilePath, componentFilePath) {
1715
+ const componentJsonPath = `${componentFilePath.replace(JS_FILE_RE$1, "")}.json`;
1716
+ const componentGenerics = readComponentConfig$1(context.files, componentJsonPath).componentGenerics;
1717
+ if (!componentGenerics || typeof componentGenerics !== "object" || Array.isArray(componentGenerics)) return;
1718
+ const ownerComponents = resolveUsingComponents$1(context.files, ownerJsonPath, ownerFilePath);
1719
+ const resolved = /* @__PURE__ */ new Map();
1720
+ for (const [genericName, definition] of Object.entries(componentGenerics)) {
1721
+ const selectedAlias = hostNode.attribs?.[`generic:${genericName}`];
1722
+ const selectedPath = selectedAlias ? ownerComponents.get(selectedAlias) : void 0;
1723
+ if (selectedPath) {
1724
+ resolved.set(genericName, selectedPath);
1725
+ continue;
1726
+ }
1727
+ const defaultPath = typeof definition === "object" && definition !== null ? definition.default : void 0;
1728
+ if (typeof defaultPath !== "string" || !defaultPath) continue;
1729
+ const resolvedDefault = defaultPath.startsWith("/") ? defaultPath.replace(LEADING_SLASH_RE$5, "") : normalize(join(dirname(componentFilePath), defaultPath));
1730
+ resolved.set(genericName, resolvedDefault.replace(LEADING_SLASH_RE$5, ""));
1731
+ }
1732
+ return resolved.size > 0 ? resolved : void 0;
1079
1733
  }
1080
1734
  function collectComponentEventBindings$1(hostNode) {
1081
- const eventBindings = /* @__PURE__ */ new Map();
1082
- for (const [key, value] of Object.entries(hostNode.attribs ?? {})) {
1083
- const matchedPrefix = COMPONENT_EVENT_PREFIXES$1.find((prefix) => key.startsWith(prefix));
1084
- if (!matchedPrefix) continue;
1085
- const eventName = key.slice(matchedPrefix.length);
1086
- if (!eventName) continue;
1087
- eventBindings.set(eventName, {
1088
- method: value,
1089
- stopAfter: matchedPrefix.startsWith("catch")
1090
- });
1091
- }
1092
- return eventBindings;
1735
+ return collectMiniProgramEventBindings(hostNode.attribs);
1093
1736
  }
1094
1737
  function buildComponentTrigger$1(componentScopeId, context, hostNode) {
1095
1738
  const hostDataset = collectDataset$4(hostNode);
@@ -1127,22 +1770,6 @@ function buildComponentTrigger$1(componentScopeId, context, hostNode) {
1127
1770
  }
1128
1771
  };
1129
1772
  }
1130
- function applyNodeBindings$1(node, scope) {
1131
- if (!isTagNode$1(node)) {
1132
- if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate$2(node.data, scope.data);
1133
- return;
1134
- }
1135
- node.attribs ??= {};
1136
- node.attribs["data-sim-scope"] = scope.getScopeId();
1137
- for (const key of STRUCTURAL_ATTRS$1) delete node.attribs[key];
1138
- for (const [key, value] of Object.entries({ ...node.attribs })) {
1139
- if (EVENT_BINDING_ATTRS$1.includes(key)) {
1140
- node.attribs["data-sim-tap"] = value;
1141
- continue;
1142
- }
1143
- node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue$1(value, scope)) : String(value);
1144
- }
1145
- }
1146
1773
  function syncComponentProperties$1(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
1147
1774
  const changedRootKeys = [];
1148
1775
  const previousProperties = {};
@@ -1153,8 +1780,7 @@ function syncComponentProperties$1(instance, definition, nextProperties, binding
1153
1780
  return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
1154
1781
  });
1155
1782
  const previousSnapshot = instance.__propertySnapshots?.[key];
1156
- const deepChanged = bindingAffected && JSON.stringify(previousSnapshot) !== JSON.stringify(nextValue);
1157
- if (instance.properties[key] !== nextValue || deepChanged) {
1783
+ if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
1158
1784
  previousProperties[key] = instance.properties[key];
1159
1785
  instance.properties[key] = nextValue;
1160
1786
  changedRootKeys.push(key);
@@ -1165,31 +1791,71 @@ function syncComponentProperties$1(instance, definition, nextProperties, binding
1165
1791
  if (changedRootKeys.length === 0) return;
1166
1792
  runComponentObservers(definition, instance, changedRootKeys, previousProperties);
1167
1793
  }
1168
- function createMergedScopeData$1(pageData, componentProperties, componentData) {
1794
+ function createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots) {
1795
+ const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
1169
1796
  return {
1170
- ...pageData,
1171
- ...componentProperties,
1172
- ...componentData
1797
+ alias: clonedNode.name,
1798
+ classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE$1).map((item) => item.trim()).filter(Boolean),
1799
+ data: createMergedScopeData$1(scope.data, componentInstance.properties, componentInstance.data),
1800
+ dataset: collectDataset$4(clonedNode),
1801
+ eventBindings: collectComponentEventBindings$1(clonedNode),
1802
+ getMethod: (methodName) => {
1803
+ const method = componentInstance?.[methodName];
1804
+ return typeof method === "function" ? method : void 0;
1805
+ },
1806
+ getScopeId: () => componentScopeId,
1807
+ genericComponents,
1808
+ hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
1809
+ id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
1810
+ listenerScopeId: scope.getScopeId(),
1811
+ ownerScopeId,
1812
+ slots
1173
1813
  };
1174
1814
  }
1175
- function isTruthy$1(value) {
1176
- return Boolean(value);
1177
- }
1178
- function createLoopScope$1(scope, itemName, indexName, item, index) {
1815
+ function resolveComponentProperties$1(clonedNode, scope, definition) {
1816
+ const nextProperties = {};
1817
+ const bindingExpressions = {};
1818
+ const declaredProperties = definition.properties ?? {};
1819
+ for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
1820
+ if (key.startsWith("bind") || key.startsWith("generic:")) continue;
1821
+ const camelizedKey = key.replace(/-([a-z])/g, (_match, char) => char.toUpperCase());
1822
+ const propertyKey = key in declaredProperties || !(camelizedKey in declaredProperties) ? key : camelizedKey;
1823
+ if (isMustacheOnly$1(String(value))) bindingExpressions[propertyKey] = String(value).trim().slice(2, -2).trim();
1824
+ nextProperties[propertyKey] = resolveComponentAttributeValue$1(String(value), scope);
1825
+ }
1179
1826
  return {
1180
- ...scope,
1181
- data: {
1182
- ...scope.data,
1183
- [indexName]: index,
1184
- [itemName]: item
1185
- }
1827
+ nextProperties,
1828
+ bindingExpressions
1186
1829
  };
1187
1830
  }
1188
- function evaluateConditionalBranch$1(node, scope) {
1189
- const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
1190
- if (condition == null) return true;
1191
- return isTruthy$1(resolveRawValueByPath$1(scope.data, condition));
1831
+ function createBrowserComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId) {
1832
+ const componentInstance = createComponentInstance({
1833
+ definition: componentEntry.definition,
1834
+ properties: nextProperties,
1835
+ requestRender: (callback) => context.session.requestRender(callback),
1836
+ triggerEvent: buildComponentTrigger$1(componentScopeId, context, clonedNode)
1837
+ });
1838
+ setSelectorQueryScopeId(componentInstance, componentScopeId);
1839
+ componentInstance.is = componentEntry.filePath.replace(JS_FILE_RE$1, "");
1840
+ componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
1841
+ componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
1842
+ componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
1843
+ componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
1844
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? context.componentCache.get(ownerScopeId) ?? null : null;
1845
+ context.componentCache.set(componentScopeId, componentInstance);
1846
+ runComponentLifecycle(componentInstance, "created");
1847
+ runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
1848
+ componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
1849
+ runComponentLifecycle(componentInstance, "attached");
1850
+ runComponentPageLifetime(componentInstance, "show");
1851
+ return componentInstance;
1852
+ }
1853
+ function renderBrowserComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
1854
+ const componentDocument = parseTemplateDocument$1(readTemplateSource$1(context.files, componentEntry.templatePath));
1855
+ return renderNodeTree((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes);
1192
1856
  }
1857
+ //#endregion
1858
+ //#region src/browser/render/index.ts
1193
1859
  function expandNodeByFor$1(node, scope) {
1194
1860
  const forExpression = node.attribs?.["wx:for"];
1195
1861
  if (!forExpression) return [{
@@ -1249,63 +1915,68 @@ function renderChildren$1(children, scope, context, ownerJsonPath, ownerFilePath
1249
1915
  }
1250
1916
  return renderedChildren;
1251
1917
  }
1918
+ function collectComponentSlots$1(componentNode, scope, ownerJsonPath, ownerFilePath, instancePath) {
1919
+ const slots = /* @__PURE__ */ new Map();
1920
+ (componentNode.children ?? []).forEach((node, index) => {
1921
+ const slotName = isTagNode$1(node) && typeof node.attribs?.slot === "string" && node.attribs.slot.trim() ? node.attribs.slot.trim() : "default";
1922
+ const entries = slots.get(slotName) ?? [];
1923
+ entries.push({
1924
+ instancePath: `${instancePath}/slot-${slotName}/node-${index}`,
1925
+ node,
1926
+ ownerFilePath,
1927
+ ownerJsonPath,
1928
+ scope
1929
+ });
1930
+ slots.set(slotName, entries);
1931
+ });
1932
+ for (const key of Object.keys(componentNode.attribs ?? {})) {
1933
+ if (!key.startsWith("generic:scoped-slots-")) continue;
1934
+ const slotName = key.slice(21);
1935
+ const inherited = scope.slots?.get(slotName);
1936
+ if (slotName && inherited?.length && !slots.has(slotName)) slots.set(slotName, inherited);
1937
+ }
1938
+ if (componentNode.name?.startsWith("scoped-slots-") && !slots.has("default")) {
1939
+ const slotName = componentNode.name.slice(13);
1940
+ const inherited = scope.slots?.get(slotName);
1941
+ if (inherited?.length) slots.set("default", inherited);
1942
+ }
1943
+ return slots;
1944
+ }
1252
1945
  function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1253
1946
  const clonedNode = cloneNode$1(node);
1254
1947
  if (!isTagNode$1(clonedNode)) {
1255
1948
  applyNodeBindings$1(clonedNode, scope);
1256
1949
  return clonedNode;
1257
1950
  }
1258
- const componentEntry = resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, clonedNode.name);
1951
+ if (clonedNode.name === "slot") {
1952
+ const slotName = clonedNode.attribs?.name?.trim() || "default";
1953
+ const projected = scope.slots?.get(slotName) ?? [];
1954
+ const children = projected.length ? projected.flatMap((entry) => renderNodeVariants$1(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, seenComponentScopes)) : renderChildren$1(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, seenComponentScopes);
1955
+ return {
1956
+ type: "tag",
1957
+ name: "block",
1958
+ attribs: { "data-sim-scope": scope.getScopeId() },
1959
+ children
1960
+ };
1961
+ }
1962
+ const componentEntry = resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, clonedNode.name, scope.genericComponents?.get(clonedNode.name));
1259
1963
  if (componentEntry) {
1260
1964
  const componentScopeId = `${instancePath}/${clonedNode.name}`;
1261
1965
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
1262
- const nextProperties = {};
1263
- const bindingExpressions = {};
1264
- for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
1265
- if (key.startsWith("bind")) continue;
1266
- if (isMustacheOnly$1(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
1267
- nextProperties[key] = resolveComponentAttributeValue$1(String(value), scope);
1268
- }
1966
+ const { nextProperties, bindingExpressions } = resolveComponentProperties$1(clonedNode, scope, componentEntry.definition);
1269
1967
  let componentInstance = context.componentCache.get(componentScopeId);
1270
- if (!componentInstance) {
1271
- componentInstance = createComponentInstance({
1272
- definition: componentEntry.definition,
1273
- properties: nextProperties,
1274
- triggerEvent: buildComponentTrigger$1(componentScopeId, context, clonedNode)
1275
- });
1276
- componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
1277
- componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
1278
- componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
1279
- componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
1280
- componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
1281
- runComponentLifecycle(componentInstance, "created");
1282
- runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
1283
- componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
1284
- runComponentLifecycle(componentInstance, "attached");
1285
- runComponentPageLifetime(componentInstance, "show");
1286
- context.componentCache.set(componentScopeId, componentInstance);
1287
- } else syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
1968
+ if (!componentInstance) componentInstance = createBrowserComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId);
1969
+ else syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
1288
1970
  seenComponentScopes.add(componentScopeId);
1289
- const componentScope = {
1290
- alias: clonedNode.name,
1291
- classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE$1).map((item) => item.trim()).filter(Boolean),
1292
- data: createMergedScopeData$1(scope.data, componentInstance.properties, componentInstance.data),
1293
- dataset: collectDataset$4(clonedNode),
1294
- eventBindings: collectComponentEventBindings$1(clonedNode),
1295
- getMethod: (methodName) => {
1296
- const method = componentInstance?.[methodName];
1297
- return typeof method === "function" ? method : void 0;
1298
- },
1299
- getScopeId: () => componentScopeId,
1300
- hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
1301
- id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
1302
- listenerScopeId: scope.getScopeId(),
1303
- ownerScopeId
1304
- };
1971
+ const genericComponents = resolveComponentGenerics$1(context, clonedNode, ownerJsonPath, ownerFilePath, componentEntry.filePath);
1972
+ const slots = collectComponentSlots$1(clonedNode, scope, ownerJsonPath, ownerFilePath, componentScopeId);
1973
+ const componentScope = createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots);
1305
1974
  context.componentScopes.set(componentScopeId, componentScope);
1306
- const componentDocument = parseTemplateDocument$1(readTemplateSource$1(context.files, componentEntry.templatePath));
1307
- const renderedComponentRoot = renderNodeTree$1((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, `${componentEntry.filePath.replace(JS_FILE_RE$1, "")}.json`, componentEntry.filePath, componentScopeId, seenComponentScopes);
1308
- if (renderedComponentRoot.attribs) renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
1975
+ const renderedComponentRoot = renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, componentScope, componentScopeId, seenComponentScopes);
1976
+ if (renderedComponentRoot.attribs) {
1977
+ renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
1978
+ renderedComponentRoot.attribs["data-sim-scope"] = componentScopeId;
1979
+ }
1309
1980
  if (!componentInstance.__ready__) {
1310
1981
  runComponentLifecycle(componentInstance, "ready");
1311
1982
  componentInstance.__ready__ = true;
@@ -1508,6 +2179,18 @@ function createPageInstance(route, definition, options = {}, pageState = {}) {
1508
2179
  }
1509
2180
  //#endregion
1510
2181
  //#region src/runtime/systemInfo.ts
2182
+ function createDefaultLocationResult() {
2183
+ return {
2184
+ accuracy: 10,
2185
+ altitude: 0,
2186
+ errMsg: "getLocation:ok",
2187
+ horizontalAccuracy: 10,
2188
+ latitude: 31.2304,
2189
+ longitude: 121.4737,
2190
+ speed: 0,
2191
+ verticalAccuracy: 0
2192
+ };
2193
+ }
1511
2194
  function createDefaultSystemInfo() {
1512
2195
  return {
1513
2196
  SDKVersion: "0.0.0",
@@ -1516,6 +2199,20 @@ function createDefaultSystemInfo() {
1516
2199
  model: "headless-simulator",
1517
2200
  pixelRatio: 2,
1518
2201
  platform: "devtools",
2202
+ safeArea: {
2203
+ bottom: 667,
2204
+ height: 647,
2205
+ left: 0,
2206
+ right: 375,
2207
+ top: 20,
2208
+ width: 375
2209
+ },
2210
+ safeAreaInsets: {
2211
+ bottom: 0,
2212
+ left: 0,
2213
+ right: 0,
2214
+ top: 20
2215
+ },
1519
2216
  screenHeight: 667,
1520
2217
  screenWidth: 375,
1521
2218
  system: "iOS 0.0.0",
@@ -1536,11 +2233,27 @@ function applyResizeToSystemInfo(systemInfo, options) {
1536
2233
  systemInfo.windowHeight = nextWindowHeight;
1537
2234
  systemInfo.screenHeight = nextWindowHeight;
1538
2235
  }
2236
+ systemInfo.safeArea = {
2237
+ bottom: systemInfo.windowHeight,
2238
+ height: Math.max(0, systemInfo.windowHeight - 20),
2239
+ left: 0,
2240
+ right: systemInfo.windowWidth,
2241
+ top: 20,
2242
+ width: systemInfo.windowWidth
2243
+ };
2244
+ systemInfo.safeAreaInsets = {
2245
+ bottom: 0,
2246
+ left: 0,
2247
+ right: 0,
2248
+ top: 20
2249
+ };
1539
2250
  return systemInfo;
1540
2251
  }
1541
2252
  function deriveWindowInfo(systemInfo) {
1542
2253
  return {
1543
2254
  pixelRatio: systemInfo.pixelRatio,
2255
+ safeArea: { ...systemInfo.safeArea },
2256
+ safeAreaInsets: { ...systemInfo.safeAreaInsets },
1544
2257
  screenHeight: systemInfo.screenHeight,
1545
2258
  screenWidth: systemInfo.screenWidth,
1546
2259
  statusBarHeight: 20,
@@ -1558,16 +2271,28 @@ function deriveAppBaseInfo(systemInfo) {
1558
2271
  version: systemInfo.version
1559
2272
  };
1560
2273
  }
2274
+ function deriveDeviceInfo(systemInfo) {
2275
+ return {
2276
+ abi: "unknown",
2277
+ benchmarkLevel: 1,
2278
+ brand: systemInfo.brand,
2279
+ cpuType: "unknown",
2280
+ deviceAbi: "unknown",
2281
+ memorySize: 4096,
2282
+ model: systemInfo.model,
2283
+ platform: systemInfo.platform,
2284
+ system: systemInfo.system
2285
+ };
2286
+ }
1561
2287
  function deriveMenuButtonBoundingClientRect(systemInfo) {
1562
2288
  const width = 87;
1563
2289
  const height = 32;
1564
2290
  const top = 32;
1565
2291
  const right = Math.max(systemInfo.windowWidth - 12, width);
1566
- const left = Math.max(0, right - width);
1567
2292
  return {
1568
- bottom: top + height,
2293
+ bottom: 64,
1569
2294
  height,
1570
- left,
2295
+ left: Math.max(0, right - width),
1571
2296
  right,
1572
2297
  top,
1573
2298
  width
@@ -1585,7 +2310,7 @@ const SAVED_FILE_PREFIXES = ["headless://saved/", "headless://wxfile/saved/"];
1585
2310
  const textEncoder = new TextEncoder();
1586
2311
  const IMAGE_EXTENSION_RE = /\.([^.?#/]+)(?:[?#].*)?$/;
1587
2312
  const LEADING_DOT_RE = /^\.+/;
1588
- const IMAGE_FILE_EXTENSIONS = new Set([
2313
+ const IMAGE_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
1589
2314
  "bmp",
1590
2315
  "gif",
1591
2316
  "heic",
@@ -1594,7 +2319,7 @@ const IMAGE_FILE_EXTENSIONS = new Set([
1594
2319
  "png",
1595
2320
  "webp"
1596
2321
  ]);
1597
- const VIDEO_FILE_EXTENSIONS = new Set([
2322
+ const VIDEO_FILE_EXTENSIONS = /* @__PURE__ */ new Set([
1598
2323
  "avi",
1599
2324
  "m4v",
1600
2325
  "mov",
@@ -2056,7 +2781,11 @@ function listParentDirectories(input) {
2056
2781
  }
2057
2782
  return parents;
2058
2783
  }
2059
- function createHeadlessWxState() {
2784
+ const nativeScheduler = {
2785
+ clearTimeout,
2786
+ setTimeout
2787
+ };
2788
+ function createHeadlessWxState(scheduler = nativeScheduler, options = {}) {
2060
2789
  const actionSheetLogs = [];
2061
2790
  const actionSheetMocks = [];
2062
2791
  const downloadFileLogs = [];
@@ -2096,7 +2825,7 @@ function createHeadlessWxState() {
2096
2825
  return createNoopTask();
2097
2826
  }
2098
2827
  let completed = false;
2099
- const timer = setTimeout(() => {
2828
+ const timer = scheduler.setTimeout(() => {
2100
2829
  if (completed) return;
2101
2830
  completed = true;
2102
2831
  onSuccess(void 0);
@@ -2104,7 +2833,7 @@ function createHeadlessWxState() {
2104
2833
  return { abort() {
2105
2834
  if (completed) return;
2106
2835
  completed = true;
2107
- clearTimeout(timer);
2836
+ scheduler.clearTimeout(timer);
2108
2837
  onFail(new Error(abortMessage));
2109
2838
  } };
2110
2839
  };
@@ -2464,6 +3193,9 @@ function createHeadlessWxState() {
2464
3193
  }
2465
3194
  };
2466
3195
  return {
3196
+ close() {
3197
+ networkStatusChangeCallbacks.clear();
3198
+ },
2467
3199
  clearStorageSync() {
2468
3200
  storage.clear();
2469
3201
  },
@@ -2477,6 +3209,7 @@ function createHeadlessWxState() {
2477
3209
  };
2478
3210
  downloadFileLogs.push(logEntry);
2479
3211
  const error = /* @__PURE__ */ new Error(`No downloadFile mock matched in headless runtime: ${option.url}`);
3212
+ if (options.strictMocks) throw error;
2480
3213
  option.fail?.(error);
2481
3214
  option.complete?.();
2482
3215
  return createNoopTask();
@@ -2896,6 +3629,7 @@ function createHeadlessWxState() {
2896
3629
  };
2897
3630
  requestLogs.push(logEntry);
2898
3631
  const error = /* @__PURE__ */ new Error(`No request mock matched in headless runtime: ${normalizeMethod(option.method)} ${option.url}`);
3632
+ if (options.strictMocks) throw error;
2899
3633
  option.fail?.(error);
2900
3634
  option.complete?.();
2901
3635
  return createNoopTask();
@@ -2973,6 +3707,7 @@ function createHeadlessWxState() {
2973
3707
  const itemList = Array.isArray(option.itemList) ? option.itemList.filter((item) => typeof item === "string") : [];
2974
3708
  if (itemList.length === 0) throw new Error("showActionSheet:fail invalid itemList");
2975
3709
  const nextMock = actionSheetMocks.shift();
3710
+ if (!nextMock && options.strictMocks) throw new Error("No actionSheet mock matched in headless runtime.");
2976
3711
  if (nextMock?.cancel) {
2977
3712
  actionSheetLogs.push({ itemList: [...itemList] });
2978
3713
  throw new Error("showActionSheet:fail cancel");
@@ -3008,6 +3743,7 @@ function createHeadlessWxState() {
3008
3743
  showModal(option) {
3009
3744
  const showCancel = option.showCancel !== false;
3010
3745
  const nextMock = modalMocks.shift();
3746
+ if (!nextMock && options.strictMocks) throw new Error("No modal mock matched in headless runtime.");
3011
3747
  let confirm = nextMock?.confirm ?? true;
3012
3748
  let cancel = nextMock?.cancel ?? !confirm;
3013
3749
  if (!showCancel) {
@@ -3063,6 +3799,7 @@ function createHeadlessWxState() {
3063
3799
  if (!matchedMock) {
3064
3800
  uploadFileLogs.push(logEntry);
3065
3801
  const error = /* @__PURE__ */ new Error(`No uploadFile mock matched in headless runtime: ${option.url}`);
3802
+ if (options.strictMocks) throw error;
3066
3803
  option.fail?.(error);
3067
3804
  option.complete?.();
3068
3805
  return createNoopTask();
@@ -3107,6 +3844,7 @@ function getClassList(node) {
3107
3844
  function matchesSimpleSelector(node, selector) {
3108
3845
  if (node.type !== "tag") return false;
3109
3846
  if (selector === "page") return node.name === "page";
3847
+ if (selector === "*") return true;
3110
3848
  if (selector.startsWith("#")) return node.attribs?.id === selector.slice(1);
3111
3849
  if (selector.startsWith(".")) return getClassList(node).includes(selector.slice(1));
3112
3850
  const dataAttrMatch = selector.match(DATA_ATTR_SELECTOR_RE$2);
@@ -3121,6 +3859,7 @@ function parseCompoundSelector$2(selector) {
3121
3859
  return parts.join("") === selector ? parts : [];
3122
3860
  }
3123
3861
  function matchesSelectorToken(node, selector) {
3862
+ if (selector === "*") return node.type === "tag";
3124
3863
  const simpleSelectors = parseCompoundSelector$2(selector);
3125
3864
  if (simpleSelectors.length === 0) return false;
3126
3865
  return simpleSelectors.every((simpleSelector) => matchesSimpleSelector(node, simpleSelector));
@@ -3164,21 +3903,6 @@ function collectDataset$3(node) {
3164
3903
  }
3165
3904
  return dataset;
3166
3905
  }
3167
- function resolveEventBinding$1(node, eventName) {
3168
- const normalizedEventName = eventName.trim();
3169
- if (!normalizedEventName) return null;
3170
- const bindingAttrs = [
3171
- `bind${normalizedEventName}`,
3172
- `bind:${normalizedEventName}`,
3173
- `catch${normalizedEventName}`,
3174
- `catch:${normalizedEventName}`
3175
- ];
3176
- for (const attributeName of bindingAttrs) {
3177
- const methodName = node.attribs?.[attributeName]?.trim();
3178
- if (methodName) return methodName;
3179
- }
3180
- return null;
3181
- }
3182
3906
  function createEventPayload$1(node, eventName, event) {
3183
3907
  const dataset = collectDataset$3(node);
3184
3908
  const nodeId = node.attribs?.id ?? "";
@@ -3230,54 +3954,74 @@ function resolveComponentScopeId(scopeId) {
3230
3954
  return scopeId;
3231
3955
  }
3232
3956
  var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
3957
+ node;
3958
+ interactions;
3233
3959
  constructor(node, interactions) {
3234
3960
  this.node = node;
3235
3961
  this.interactions = interactions;
3236
3962
  }
3963
+ assertActive() {
3964
+ this.interactions?.assertActive?.();
3965
+ }
3237
3966
  async $(selector) {
3967
+ this.assertActive();
3238
3968
  const match = querySelectorAll(this.node, selector)[0];
3239
3969
  return match ? new HeadlessTestingNodeHandle(match, this.interactions) : null;
3240
3970
  }
3241
3971
  async $$(selector) {
3972
+ this.assertActive();
3242
3973
  return querySelectorAll(this.node, selector).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
3243
3974
  }
3244
3975
  async attr(name) {
3976
+ this.assertActive();
3245
3977
  return this.node.attribs?.[name];
3246
3978
  }
3247
3979
  async dataset() {
3980
+ this.assertActive();
3248
3981
  return collectDataset$3(this.node);
3249
3982
  }
3250
3983
  async scope() {
3984
+ this.assertActive();
3251
3985
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
3252
3986
  return this.interactions.createScopeHandle(this.node.attribs?.["data-sim-scope"] ?? null);
3253
3987
  }
3254
3988
  async componentScope() {
3989
+ this.assertActive();
3255
3990
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
3256
3991
  return this.interactions.createScopeHandle(resolveComponentScopeId(this.node.attribs?.["data-sim-scope"] ?? null));
3257
3992
  }
3258
3993
  async pageScope() {
3994
+ this.assertActive();
3259
3995
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
3260
3996
  return this.interactions.createScopeHandle(resolvePageScopeId$1(this.node.attribs?.["data-sim-scope"] ?? null));
3261
3997
  }
3262
3998
  async page() {
3999
+ this.assertActive();
3263
4000
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
3264
4001
  return this.interactions.createPageHandle();
3265
4002
  }
3266
4003
  async ownerComponentScope() {
4004
+ this.assertActive();
3267
4005
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
3268
4006
  const scopeId = resolveComponentScopeId(this.node.attribs?.["data-sim-scope"] ?? null);
3269
4007
  return this.interactions.createScopeHandle(this.interactions.ownerScopeId(scopeId));
3270
4008
  }
3271
4009
  async text() {
4010
+ this.assertActive();
3272
4011
  return collectText(this.node);
3273
4012
  }
4013
+ async tagName() {
4014
+ this.assertActive();
4015
+ return this.node.type === "tag" ? this.node.name : void 0;
4016
+ }
3274
4017
  async trigger(eventName, event = {}) {
4018
+ this.assertActive();
3275
4019
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
3276
4020
  const normalizedEventName = eventName.trim();
3277
4021
  if (!normalizedEventName) throw new Error("Event name must be a non-empty string in headless testing runtime.");
3278
- const methodName = resolveEventBinding$1(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(this.node.attribs?.["data-sim-scope"] ?? null, methodName, createEventPayload$1(this.node, normalizedEventName, event));
4022
+ const binding = resolveMiniProgramEventBinding(this.node.attribs, normalizedEventName);
4023
+ if (!binding?.method) throw new Error(`No ${normalizedEventName} binding was found on <${this.node.name ?? "unknown"}> in headless testing runtime.`);
4024
+ return await this.interactions.callMethod(this.node.attribs?.["data-sim-scope"] ?? null, binding.method, createEventPayload$1(this.node, normalizedEventName, event));
3281
4025
  }
3282
4026
  async tap(event = {}) {
3283
4027
  return await this.trigger("tap", event);
@@ -3301,6 +4045,7 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
3301
4045
  });
3302
4046
  }
3303
4047
  async wxml() {
4048
+ this.assertActive();
3304
4049
  return serializeNode(this.node);
3305
4050
  }
3306
4051
  };
@@ -3348,7 +4093,9 @@ function serializeDomNode$1(node) {
3348
4093
  function renderPageTree(project, page) {
3349
4094
  const route = page.route.replace(LEADING_SLASH_RE$4, "");
3350
4095
  const templatePath = path.resolve(project.miniprogramRootPath, `${route}.wxml`);
3351
- const document = parseDocument(`<page>${fs.readFileSync(templatePath, "utf8")}</page>`, {
4096
+ const templateSource = project.artifactSource.readText(templatePath);
4097
+ if (templateSource == null) throw new Error(`Missing template in headless runtime: ${templatePath}`);
4098
+ const document = parseDocument(`<page>${templateSource}</page>`, {
3352
4099
  xmlMode: false,
3353
4100
  decodeEntities: false,
3354
4101
  recognizeSelfClosing: true
@@ -3480,7 +4227,13 @@ function resolveFieldsResult(node, fields, options) {
3480
4227
  if (Array.isArray(fields.properties) && fields.properties.length > 0) Object.assign(result, pickProperties(node, fields.properties));
3481
4228
  if (Array.isArray(fields.computedStyle) && fields.computedStyle.length > 0) Object.assign(result, pickComputedStyle(node, fields.computedStyle));
3482
4229
  if (fields.context) result.context = options.resolveContext?.(node) ?? { type: "unsupported-context" };
3483
- if (fields.node) result.node = { type: node.name ?? "unknown" };
4230
+ if (fields.node) {
4231
+ const context = options.resolveContext?.(node);
4232
+ result.node = node.name === "canvas" && context ? {
4233
+ getContext: () => context,
4234
+ type: "canvas"
4235
+ } : { type: node.name ?? "unknown" };
4236
+ }
3484
4237
  return result;
3485
4238
  }
3486
4239
  function resolveViewportResult(fields, options) {
@@ -4177,21 +4930,6 @@ function collectDataset$1(node) {
4177
4930
  }
4178
4931
  return dataset;
4179
4932
  }
4180
- function resolveEventBinding(node, eventName) {
4181
- const normalizedEventName = eventName.trim();
4182
- if (!normalizedEventName) return null;
4183
- const bindingAttrs = [
4184
- `bind${normalizedEventName}`,
4185
- `bind:${normalizedEventName}`,
4186
- `catch${normalizedEventName}`,
4187
- `catch:${normalizedEventName}`
4188
- ];
4189
- for (const attributeName of bindingAttrs) {
4190
- const methodName = node.attribs?.[attributeName]?.trim();
4191
- if (methodName) return methodName;
4192
- }
4193
- return null;
4194
- }
4195
4933
  function createEventPayload(node, eventName, detail) {
4196
4934
  const dataset = collectDataset$1(node);
4197
4935
  const nodeId = node.attribs?.id ?? "";
@@ -4227,9 +4965,9 @@ function createHeadlessVideoContext(driver, videoId, scope) {
4227
4965
  const dispatch = (eventName, detail) => {
4228
4966
  const node = resolveNode();
4229
4967
  if (!node) return;
4230
- const methodName = resolveEventBinding(node, eventName);
4231
- if (!methodName) return;
4232
- driver.callScopeMethod(node.attribs?.["data-sim-scope"] ?? null, methodName, createEventPayload(node, eventName, detail));
4968
+ const binding = resolveMiniProgramEventBinding(node.attribs, eventName);
4969
+ if (!binding?.method) return;
4970
+ driver.callScopeMethod(node.attribs?.["data-sim-scope"] ?? null, binding.method, createEventPayload(node, eventName, detail));
4233
4971
  };
4234
4972
  return {
4235
4973
  exitFullScreen() {
@@ -4346,11 +5084,15 @@ var BrowserHeadlessSession = class {
4346
5084
  appDefinition = null;
4347
5085
  appInstance = null;
4348
5086
  moduleLoader;
5087
+ onRender;
4349
5088
  registries;
4350
5089
  currentPageInstance = null;
4351
5090
  pages = [];
4352
5091
  componentCache = /* @__PURE__ */ new Map();
4353
5092
  componentScopes = /* @__PURE__ */ new Map();
5093
+ selectorQueryScopeSnapshots = /* @__PURE__ */ new WeakMap();
5094
+ renderRequestPending = false;
5095
+ renderRequestCallbacks = [];
4354
5096
  tabBarRoutes;
4355
5097
  tabPages = /* @__PURE__ */ new Map();
4356
5098
  tabBarItems = /* @__PURE__ */ new Map();
@@ -4361,13 +5103,16 @@ var BrowserHeadlessSession = class {
4361
5103
  canvasContexts = /* @__PURE__ */ new Map();
4362
5104
  enterOptions = createAppLaunchOptions$1("", {});
4363
5105
  launchOptions = createAppLaunchOptions$1("", {});
4364
- wxState = createHeadlessWxState();
5106
+ kernel = new RuntimeKernel();
5107
+ wxState;
4365
5108
  pullDownRefreshState = {
4366
5109
  active: false,
4367
5110
  stopCalls: 0
4368
5111
  };
4369
5112
  constructor(options) {
4370
5113
  this.files = options.files;
5114
+ this.wxState = createHeadlessWxState(this.kernel.scheduler, { strictMocks: options.strictHostMocks });
5115
+ this.onRender = options.onRender;
4371
5116
  this.project = options.project ?? createBrowserProject(options.files);
4372
5117
  this.registries = createHostRegistries();
4373
5118
  const rawTabBarList = Array.isArray(this.project.appConfig.tabBar?.list) ? this.project.appConfig.tabBar.list : [];
@@ -4418,6 +5163,7 @@ var BrowserHeadlessSession = class {
4418
5163
  }
4419
5164
  }),
4420
5165
  getAppBaseInfoSync: () => deriveAppBaseInfo(this.systemInfo),
5166
+ getDeviceInfo: () => deriveDeviceInfo(this.systemInfo),
4421
5167
  getLaunchOptionsSync: () => ({
4422
5168
  ...this.launchOptions,
4423
5169
  query: { ...this.launchOptions.query },
@@ -4427,6 +5173,7 @@ var BrowserHeadlessSession = class {
4427
5173
  }
4428
5174
  }),
4429
5175
  getClipboardData: () => this.wxState.getClipboardData(),
5176
+ getLocation: () => createDefaultLocationResult(),
4430
5177
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
4431
5178
  getNetworkType: () => this.wxState.getNetworkType(),
4432
5179
  navigateBack: (option) => this.navigateBack(option?.delta),
@@ -4446,7 +5193,7 @@ var BrowserHeadlessSession = class {
4446
5193
  removeSavedFile: (option) => this.wxState.removeSavedFile(option),
4447
5194
  saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
4448
5195
  saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
4449
- nextTick: (callback) => queueMicrotask(() => callback?.()),
5196
+ nextTick: (callback) => this.kernel.scheduler.queueMicrotask(() => callback?.()),
4450
5197
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
4451
5198
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
4452
5199
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
@@ -4478,12 +5225,36 @@ var BrowserHeadlessSession = class {
4478
5225
  removeTabBarBadge: (option) => this.removeTabBarBadge(option.index),
4479
5226
  setTabBarBadge: (option) => this.setTabBarBadge(option.index, option.text),
4480
5227
  updateShareMenu: (option) => this.wxState.updateShareMenu(option)
5228
+ }, {
5229
+ globals: options.globals,
5230
+ kernel: this.kernel
4481
5231
  });
4482
5232
  }
5233
+ assertActive() {
5234
+ this.kernel.assertActive();
5235
+ }
5236
+ close() {
5237
+ if (this.kernel.isClosed) return;
5238
+ this.unloadAllPages();
5239
+ this.canvasContexts.clear();
5240
+ this.renderRequestCallbacks.length = 0;
5241
+ this.renderRequestPending = false;
5242
+ this.wxState.close();
5243
+ this.moduleLoader.close();
5244
+ this.kernel.close();
5245
+ }
5246
+ getDiagnostics() {
5247
+ return this.kernel.diagnostics.getEntries();
5248
+ }
5249
+ get isClosed() {
5250
+ return this.kernel.isClosed;
5251
+ }
4483
5252
  getApp() {
5253
+ this.assertActive();
4484
5254
  return this.appInstance;
4485
5255
  }
4486
5256
  getCurrentPages() {
5257
+ this.assertActive();
4487
5258
  return this.pages.slice();
4488
5259
  }
4489
5260
  getCurrentPageNavigationBarTitle() {
@@ -4566,6 +5337,9 @@ var BrowserHeadlessSession = class {
4566
5337
  getAppBaseInfo() {
4567
5338
  return deriveAppBaseInfo(this.systemInfo);
4568
5339
  }
5340
+ getDeviceInfo() {
5341
+ return deriveDeviceInfo(this.systemInfo);
5342
+ }
4569
5343
  getLaunchOptions() {
4570
5344
  return {
4571
5345
  ...this.launchOptions,
@@ -4589,6 +5363,9 @@ var BrowserHeadlessSession = class {
4589
5363
  getMenuButtonBoundingClientRect() {
4590
5364
  return deriveMenuButtonBoundingClientRect(this.systemInfo);
4591
5365
  }
5366
+ getLocation() {
5367
+ return createDefaultLocationResult();
5368
+ }
4592
5369
  getNetworkType() {
4593
5370
  return this.wxState.getNetworkType();
4594
5371
  }
@@ -4764,15 +5541,19 @@ var BrowserHeadlessSession = class {
4764
5541
  return this.getComponentScopeId(component);
4765
5542
  }
4766
5543
  selectComponent(selector) {
5544
+ this.renderCurrentPage();
4767
5545
  return this.selectComponentsWithin(null, selector)[0] ?? null;
4768
5546
  }
4769
5547
  selectAllComponents(selector) {
5548
+ this.renderCurrentPage();
4770
5549
  return this.selectComponentsWithin(null, selector);
4771
5550
  }
4772
5551
  selectComponentWithin(scopeId, selector) {
5552
+ this.renderCurrentPage();
4773
5553
  return this.selectComponentsWithin(scopeId, selector)[0] ?? null;
4774
5554
  }
4775
5555
  selectAllComponentsWithin(scopeId, selector) {
5556
+ this.renderCurrentPage();
4776
5557
  return this.selectComponentsWithin(scopeId, selector);
4777
5558
  }
4778
5559
  selectOwnerComponent(scopeId) {
@@ -4783,7 +5564,7 @@ var BrowserHeadlessSession = class {
4783
5564
  selectComponentsWithin(rootScopeId, selector) {
4784
5565
  const selectorParts = normalizeSelectorParts$1(selector);
4785
5566
  if (selectorParts.length === 0) return [];
4786
- return [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
5567
+ const matches = [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
4787
5568
  if (!candidateScopeId.includes("/")) return false;
4788
5569
  if (rootScopeId && candidateScopeId === rootScopeId) return false;
4789
5570
  if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
@@ -4796,9 +5577,12 @@ var BrowserHeadlessSession = class {
4796
5577
  currentScope = currentScope.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
4797
5578
  }
4798
5579
  return true;
4799
- }).map(([candidateScopeId]) => this.componentCache.get(candidateScopeId)).filter(Boolean);
5580
+ });
5581
+ const directlyOwned = rootScopeId ? matches.filter(([, scope]) => scope.ownerScopeId === rootScopeId) : [];
5582
+ return (directlyOwned.length > 0 ? directlyOwned : matches).map(([candidateScopeId]) => this.componentCache.get(candidateScopeId)).filter(Boolean);
4800
5583
  }
4801
5584
  renderCurrentPage() {
5585
+ this.assertActive();
4802
5586
  const current = this.requireCurrentPage("renderCurrentPage()");
4803
5587
  const rendered = renderBrowserPageTree({
4804
5588
  changedPageKeys: current.__lastChangedKeys__ ?? [],
@@ -4810,14 +5594,35 @@ var BrowserHeadlessSession = class {
4810
5594
  session: {
4811
5595
  createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
4812
5596
  createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
5597
+ requestRender: (callback) => this.requestRender(callback),
4813
5598
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
4814
5599
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
4815
5600
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
4816
5601
  }
4817
5602
  }, current);
4818
5603
  current.__lastChangedKeys__ = [];
5604
+ const componentScopePrefix = `page:${stripLeadingSlash$1(current.route)}`;
5605
+ for (const [scopeId, instance] of this.componentCache.entries()) if (scopeId.startsWith(componentScopePrefix)) this.selectorQueryScopeSnapshots.set(instance, {
5606
+ page: current,
5607
+ root: rendered.root,
5608
+ scopeId
5609
+ });
4819
5610
  return rendered;
4820
5611
  }
5612
+ requestRender(callback) {
5613
+ this.assertActive();
5614
+ if (callback) this.renderRequestCallbacks.push(callback);
5615
+ if (this.renderRequestPending) return;
5616
+ this.renderRequestPending = true;
5617
+ Promise.resolve().then(() => {
5618
+ if (this.kernel.isClosed) return;
5619
+ this.renderRequestPending = false;
5620
+ const callbacks = this.renderRequestCallbacks.splice(0);
5621
+ if (this.currentPageInstance) this.renderCurrentPage();
5622
+ callbacks.forEach((cb) => cb());
5623
+ this.onRender?.();
5624
+ });
5625
+ }
4821
5626
  callScopeMethod(scopeId, methodName, event) {
4822
5627
  const current = this.requireCurrentPage(`scope method "${methodName}"`);
4823
5628
  this.renderCurrentPage();
@@ -4841,6 +5646,7 @@ var BrowserHeadlessSession = class {
4841
5646
  const normalizedScopeId = scopeId.trim();
4842
5647
  if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in browser simulator runtime.");
4843
5648
  const current = this.requireCurrentPage(`scope method "${methodName}"`);
5649
+ this.renderCurrentPage();
4844
5650
  if (normalizedScopeId === `page:${stripLeadingSlash$1(current.route)}`) {
4845
5651
  const method = current[methodName];
4846
5652
  if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator page ${current.route}.`);
@@ -4895,6 +5701,7 @@ var BrowserHeadlessSession = class {
4895
5701
  });
4896
5702
  }
4897
5703
  bootstrap(launchOptions = createAppLaunchOptions$1("", {})) {
5704
+ this.assertActive();
4898
5705
  if (this.appInstance) return this.appInstance;
4899
5706
  this.launchOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
4900
5707
  this.enterOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
@@ -4912,6 +5719,7 @@ var BrowserHeadlessSession = class {
4912
5719
  const pageInstance = this.createFreshPage(target);
4913
5720
  this.pages.push(pageInstance);
4914
5721
  this.currentPageInstance = pageInstance;
5722
+ this.runInitialPageLifecycles(pageInstance, target.query);
4915
5723
  return pageInstance;
4916
5724
  }
4917
5725
  navigateTo(url) {
@@ -4924,6 +5732,7 @@ var BrowserHeadlessSession = class {
4924
5732
  const pageInstance = this.createFreshPage(target);
4925
5733
  this.pages.push(pageInstance);
4926
5734
  this.currentPageInstance = pageInstance;
5735
+ this.runInitialPageLifecycles(pageInstance, target.query);
4927
5736
  return pageInstance;
4928
5737
  }
4929
5738
  redirectTo(url) {
@@ -4938,6 +5747,7 @@ var BrowserHeadlessSession = class {
4938
5747
  const pageInstance = this.createFreshPage(target);
4939
5748
  this.pages.push(pageInstance);
4940
5749
  this.currentPageInstance = pageInstance;
5750
+ this.runInitialPageLifecycles(pageInstance, target.query);
4941
5751
  return pageInstance;
4942
5752
  }
4943
5753
  navigateBack(delta = 1) {
@@ -4959,11 +5769,7 @@ var BrowserHeadlessSession = class {
4959
5769
  if (!this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.switchTab() can only open a tabBar page in browser simulator runtime: ${url}`);
4960
5770
  const current = this.currentPageInstance;
4961
5771
  const cachedTarget = this.tabPages.get(target.routeRecord.route) ?? null;
4962
- const tabItem = this.resolveTabBarItem(target.routeRecord.route);
4963
- if (current === cachedTarget && current) {
4964
- current.onTabItemTap?.(tabItem);
4965
- return current;
4966
- }
5772
+ if (current === cachedTarget && current) return current;
4967
5773
  if (current && current !== cachedTarget) {
4968
5774
  current.onHide?.();
4969
5775
  this.runPageComponentLifetime(current.route, "hide");
@@ -4974,17 +5780,20 @@ var BrowserHeadlessSession = class {
4974
5780
  this.unloadPage(page);
4975
5781
  }
4976
5782
  let nextPage = cachedTarget;
5783
+ let shouldRunInitialLifecycles = false;
4977
5784
  if (!nextPage) {
4978
5785
  nextPage = this.createFreshPage(target);
4979
5786
  this.tabPages.set(target.routeRecord.route, nextPage);
4980
- } else if (current !== nextPage) {
4981
- nextPage.onShow?.();
4982
- this.runPageComponentLifetime(nextPage.route, "show");
5787
+ shouldRunInitialLifecycles = true;
4983
5788
  }
4984
- nextPage.onTabItemTap?.(tabItem);
4985
5789
  this.pages.length = 0;
4986
5790
  this.pages.push(nextPage);
4987
5791
  this.currentPageInstance = nextPage;
5792
+ if (shouldRunInitialLifecycles) this.runInitialPageLifecycles(nextPage, target.query);
5793
+ else if (current !== nextPage) {
5794
+ nextPage.onShow?.();
5795
+ this.runPageComponentLifetime(nextPage.route, "show");
5796
+ }
4988
5797
  return nextPage;
4989
5798
  }
4990
5799
  pageScrollTo(option) {
@@ -4999,6 +5808,7 @@ var BrowserHeadlessSession = class {
4999
5808
  session: {
5000
5809
  createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
5001
5810
  createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
5811
+ requestRender: (callback) => this.requestRender(callback),
5002
5812
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
5003
5813
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
5004
5814
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
@@ -5046,14 +5856,32 @@ var BrowserHeadlessSession = class {
5046
5856
  }
5047
5857
  executeSelectorQuery(requests, scope) {
5048
5858
  const current = this.requireCurrentPage("wx.createSelectorQuery().exec()");
5049
- if (scope && scope !== current && !Array.from(this.componentCache.values()).includes(scope)) throw new Error("wx.createSelectorQuery().in(component) received an unknown scope in browser simulator runtime.");
5050
- const scopeId = scope && scope !== current ? this.getComponentScopeId(scope) : null;
5859
+ const nativeScope = resolveSelectorQueryNativeScope(scope, current, this.componentCache.values());
5860
+ const staleScope = scope && !nativeScope ? resolveSelectorQueryScopeSnapshot(scope, this.selectorQueryScopeSnapshots) : null;
5861
+ if (scope && !nativeScope && !staleScope) {
5862
+ if (resolveSelectorQueryScopeId(scope)) return requests.map((request) => request.target === "viewport" ? {
5863
+ scrollLeft: 0,
5864
+ scrollTop: current.__scrollTop__ ?? 0
5865
+ } : request.single ? null : []);
5866
+ throw new Error("wx.createSelectorQuery().in(component) received an unknown scope in browser simulator runtime.");
5867
+ }
5868
+ if (staleScope) return executeSelectorQueryRequests(requests, {
5869
+ page: staleScope.snapshot.page,
5870
+ resolveContext: (node) => {
5871
+ if (node.name !== "canvas") return { type: "unsupported-context" };
5872
+ const canvasId = node.attribs?.["canvas-id"];
5873
+ return typeof canvasId === "string" && canvasId ? this.createCanvasContext(canvasId, staleScope.nativeScope) : { type: "unsupported-context" };
5874
+ },
5875
+ root: resolveSelectorQueryScopeRoot(staleScope.snapshot.root, staleScope.snapshot.scopeId),
5876
+ windowInfo: this.getWindowInfo()
5877
+ });
5878
+ const scopeId = nativeScope && nativeScope !== current ? this.getComponentScopeId(nativeScope) : null;
5051
5879
  return executeSelectorQueryRequests(requests, {
5052
5880
  page: current,
5053
5881
  resolveContext: (node) => {
5054
5882
  if (node.name !== "canvas") return { type: "unsupported-context" };
5055
5883
  const canvasId = node.attribs?.["canvas-id"];
5056
- return typeof canvasId === "string" && canvasId ? this.createCanvasContext(canvasId, scope) : { type: "unsupported-context" };
5884
+ return typeof canvasId === "string" && canvasId ? this.createCanvasContext(canvasId, nativeScope ?? void 0) : { type: "unsupported-context" };
5057
5885
  },
5058
5886
  root: resolveSelectorQueryScopeRoot(renderBrowserPageTree({
5059
5887
  changedPageKeys: current.__lastChangedKeys__ ?? [],
@@ -5065,6 +5893,7 @@ var BrowserHeadlessSession = class {
5065
5893
  session: {
5066
5894
  createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
5067
5895
  createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
5896
+ requestRender: (callback) => this.requestRender(callback),
5068
5897
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
5069
5898
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
5070
5899
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
@@ -5086,12 +5915,15 @@ var BrowserHeadlessSession = class {
5086
5915
  pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
5087
5916
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
5088
5917
  pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
5089
- pageInstance.onLoad?.(target.query);
5090
- pageInstance.onShow?.();
5091
- pageInstance.onReady?.();
5092
5918
  if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
5093
5919
  return pageInstance;
5094
5920
  }
5921
+ runInitialPageLifecycles(pageInstance, query) {
5922
+ pageInstance.onLoad?.(query);
5923
+ pageInstance.onShow?.();
5924
+ pageInstance.onReady?.();
5925
+ pageInstance.onRouteDone?.({});
5926
+ }
5095
5927
  isTabBarRoute(route) {
5096
5928
  return this.tabBarRoutes.has(stripLeadingSlash$1(route));
5097
5929
  }
@@ -5114,12 +5946,6 @@ var BrowserHeadlessSession = class {
5114
5946
  routeRecord
5115
5947
  };
5116
5948
  }
5117
- resolveTabBarItem(route) {
5118
- const pagePath = stripLeadingSlash$1(route);
5119
- const item = this.tabBarItems.get(pagePath);
5120
- if (!item) throw new Error(`Missing tabBar metadata for route "${route}" in browser simulator runtime.`);
5121
- return { ...item };
5122
- }
5123
5949
  requireTabBarItem(index, action) {
5124
5950
  const normalizedIndex = Number.isFinite(index) ? Math.trunc(index) : NaN;
5125
5951
  const item = this.tabBarState.get(normalizedIndex);
@@ -5127,7 +5953,7 @@ var BrowserHeadlessSession = class {
5127
5953
  return item;
5128
5954
  }
5129
5955
  unloadAllPages() {
5130
- const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
5956
+ const pagesToUnload = /* @__PURE__ */ new Set([...this.pages, ...this.tabPages.values()]);
5131
5957
  for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
5132
5958
  this.pages.length = 0;
5133
5959
  this.tabPages.clear();
@@ -5279,6 +6105,32 @@ function createBrowserHeadlessSession(options) {
5279
6105
  return new BrowserHeadlessSession(options);
5280
6106
  }
5281
6107
  //#endregion
6108
+ //#region src/project/createArtifactProject.ts
6109
+ function createArtifactProject(options) {
6110
+ const artifactSource = options.artifactSource ?? createFileSystemArtifactSource();
6111
+ const miniprogramRootPath = path.resolve(options.miniprogramRootPath);
6112
+ const appConfigPath = path.resolve(miniprogramRootPath, options.appConfigPath ?? "app.json");
6113
+ const appConfigSource = artifactSource.readText(appConfigPath);
6114
+ if (appConfigSource == null) throw new Error(`Missing built app.json for headless runtime artifact: ${appConfigPath}`);
6115
+ let appConfig;
6116
+ try {
6117
+ const parsed = JSON.parse(appConfigSource);
6118
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new TypeError("app.json must contain an object.");
6119
+ appConfig = parsed;
6120
+ } catch (error) {
6121
+ throw new Error(`Failed to read built app.json for headless runtime artifact: ${appConfigPath}`, { cause: error });
6122
+ }
6123
+ return createProjectDescriptor({
6124
+ appConfig,
6125
+ appConfigPath,
6126
+ artifactSource,
6127
+ miniprogramRoot: ".",
6128
+ miniprogramRootPath,
6129
+ projectConfigFiles: [],
6130
+ projectPath: path.resolve(options.projectPath ?? miniprogramRootPath)
6131
+ });
6132
+ }
6133
+ //#endregion
5282
6134
  //#region src/project/loadProject.ts
5283
6135
  function readJsonObject$1(filePath) {
5284
6136
  try {
@@ -5338,21 +6190,16 @@ function loadProject(projectPath) {
5338
6190
  });
5339
6191
  }
5340
6192
  //#endregion
5341
- //#region src/runtime/render.ts
5342
- const LEADING_SLASH_RE$2 = /^\/+/;
6193
+ //#region src/runtime/render/shared.ts
5343
6194
  const TEMPLATE_INTERPOLATION_RE = /\{\{([^{}]+)\}\}/g;
6195
+ const DATASET_NAME_RE = /-([a-z])/g;
6196
+ const LEADING_SLASH_RE$2 = /^\/+/;
5344
6197
  const EVENT_BINDING_ATTRS = [
5345
6198
  "bindtap",
5346
6199
  "bind:tap",
5347
6200
  "catchtap",
5348
6201
  "catch:tap"
5349
6202
  ];
5350
- const COMPONENT_EVENT_PREFIXES = [
5351
- "bind:",
5352
- "bind",
5353
- "catch:",
5354
- "catch"
5355
- ];
5356
6203
  const STRUCTURAL_ATTRS = [
5357
6204
  "wx:if",
5358
6205
  "wx:elif",
@@ -5362,9 +6209,7 @@ const STRUCTURAL_ATTRS = [
5362
6209
  "wx:for-index",
5363
6210
  "wx:key"
5364
6211
  ];
5365
- const WX_ELSE_ATTRS = new Set(["wx:elif", "wx:else"]);
5366
- const DATASET_NAME_RE = /-([a-z])/g;
5367
- const BRACKET_INDEX_RE = /\[(\d+)\]/g;
6212
+ const WX_ELSE_ATTRS = /* @__PURE__ */ new Set(["wx:elif", "wx:else"]);
5368
6213
  const CLASS_SPLIT_RE = /\s+/;
5369
6214
  const JS_FILE_RE = /\.js$/;
5370
6215
  function isMustacheOnly(value) {
@@ -5395,39 +6240,11 @@ function cloneNode(node) {
5395
6240
  children: node.children?.map((child) => cloneNode(child))
5396
6241
  };
5397
6242
  }
5398
- function parseExpressionSegments(expression) {
5399
- return expression.replace(BRACKET_INDEX_RE, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
5400
- }
5401
- function unwrapMustacheExpression(expression) {
5402
- const normalized = expression.trim();
5403
- if (isMustacheOnly(normalized)) return normalized.slice(2, -2).trim();
5404
- return normalized;
5405
- }
5406
- function resolveLiteralValue(expression) {
5407
- if (expression === "true") return true;
5408
- if (expression === "false") return false;
5409
- if (expression === "null") return null;
5410
- if (expression === "undefined") return;
5411
- if (expression.startsWith("\"") && expression.endsWith("\"") || expression.startsWith("'") && expression.endsWith("'")) return expression.slice(1, -1);
5412
- const numericValue = Number(expression);
5413
- if (!Number.isNaN(numericValue) && expression !== "") return numericValue;
5414
- }
5415
- function resolveValueByExpression(source, expression) {
5416
- const normalized = unwrapMustacheExpression(expression);
5417
- if (!normalized) return;
5418
- if (normalized.startsWith("!")) return !resolveValueByExpression(source, normalized.slice(1));
5419
- const literalValue = resolveLiteralValue(normalized);
5420
- if (literalValue !== void 0 || normalized === "undefined") return literalValue;
5421
- const segments = parseExpressionSegments(normalized);
5422
- let current = source;
5423
- for (const segment of segments) current = current?.[segment];
5424
- return current;
5425
- }
5426
6243
  function resolveValueByPath(source, expression) {
5427
- return resolveValueByExpression(source, expression) ?? "";
6244
+ return resolveTemplateExpression(source, expression) ?? "";
5428
6245
  }
5429
6246
  function resolveRawValueByPath(source, expression) {
5430
- return resolveValueByExpression(source, expression);
6247
+ return resolveTemplateExpression(source, expression);
5431
6248
  }
5432
6249
  function interpolateTemplate(input, data) {
5433
6250
  return input.replace(TEMPLATE_INTERPOLATION_RE, (_match, expression) => {
@@ -5435,13 +6252,17 @@ function interpolateTemplate(input, data) {
5435
6252
  return typeof value === "string" ? value : String(value);
5436
6253
  });
5437
6254
  }
5438
- function readTemplateSource(filePath) {
5439
- return fs.readFileSync(filePath, "utf8");
6255
+ function readTemplateSource(artifactSource, filePath) {
6256
+ const source = artifactSource.readText(filePath);
6257
+ if (source == null) throw new Error(`Missing template in headless runtime: ${filePath}`);
6258
+ return source;
5440
6259
  }
5441
6260
  function parseTemplateDocument(templateSource) {
5442
6261
  return parseDocument(`<page>${templateSource}</page>`, {
5443
6262
  xmlMode: false,
5444
6263
  decodeEntities: false,
6264
+ lowerCaseAttributeNames: false,
6265
+ lowerCaseTags: false,
5445
6266
  recognizeSelfClosing: true
5446
6267
  });
5447
6268
  }
@@ -5465,16 +6286,79 @@ function resolveAttributeValue(value, scope) {
5465
6286
  }
5466
6287
  return interpolateTemplate(value, scope.data);
5467
6288
  }
5468
- function resolveComponentAttributeValue(value, scope) {
5469
- if (isMustacheOnly(value)) {
5470
- const expression = value.trim().slice(2, -2);
5471
- return resolveRawValueByPath(scope.data, expression);
6289
+ function resolveComponentAttributeValue(value, scope) {
6290
+ if (isMustacheOnly(value)) {
6291
+ const expression = value.trim().slice(2, -2);
6292
+ return resolveRawValueByPath(scope.data, expression);
6293
+ }
6294
+ return interpolateTemplate(value, scope.data);
6295
+ }
6296
+ function applyNodeBindings(node, scope) {
6297
+ if (!isTagNode(node)) {
6298
+ if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate(node.data, scope.data);
6299
+ return;
6300
+ }
6301
+ node.attribs ??= {};
6302
+ node.attribs["data-sim-scope"] = scope.getScopeId();
6303
+ for (const key of STRUCTURAL_ATTRS) delete node.attribs[key];
6304
+ for (const [key, value] of Object.entries({ ...node.attribs })) {
6305
+ if (EVENT_BINDING_ATTRS.includes(key)) {
6306
+ node.attribs["data-sim-tap"] = value;
6307
+ continue;
6308
+ }
6309
+ node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
6310
+ }
6311
+ }
6312
+ function createMergedScopeData(pageData, componentProperties, componentData) {
6313
+ return {
6314
+ ...pageData,
6315
+ ...componentProperties,
6316
+ ...componentData
6317
+ };
6318
+ }
6319
+ function evaluateConditionalBranch(node, scope) {
6320
+ const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
6321
+ if (condition == null) return true;
6322
+ return Boolean(resolveRawValueByPath(scope.data, condition));
6323
+ }
6324
+ function createLoopScope(scope, itemName, indexName, item, index) {
6325
+ return {
6326
+ ...scope,
6327
+ data: {
6328
+ ...scope.data,
6329
+ [indexName]: index,
6330
+ [itemName]: item
6331
+ }
6332
+ };
6333
+ }
6334
+ //#endregion
6335
+ //#region src/runtime/render/component.ts
6336
+ function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias, genericComponentBasePath) {
6337
+ const usingComponents = resolveUsingComponents(context.artifactSource, ownerJsonPath, ownerFilePath);
6338
+ const componentBasePath = genericComponentBasePath ?? usingComponents.get(alias);
6339
+ if (!componentBasePath) return null;
6340
+ const filePath = `${componentBasePath}.js`;
6341
+ const templatePath = `${componentBasePath}.wxml`;
6342
+ const absoluteFilePath = path.resolve(context.project.miniprogramRootPath, filePath);
6343
+ const absoluteTemplatePath = path.resolve(context.project.miniprogramRootPath, templatePath);
6344
+ return {
6345
+ definition: context.moduleLoader.executeComponentModule(absoluteFilePath, componentBasePath),
6346
+ filePath,
6347
+ templatePath,
6348
+ absoluteTemplatePath
6349
+ };
6350
+ }
6351
+ function readComponentConfig(artifactSource, jsonPath) {
6352
+ try {
6353
+ const source = artifactSource.readText(jsonPath);
6354
+ return source ? JSON.parse(source) : {};
6355
+ } catch {
6356
+ return {};
5472
6357
  }
5473
- return interpolateTemplate(value, scope.data);
5474
6358
  }
5475
- function resolveUsingComponents(ownerJsonPath, ownerFilePath) {
6359
+ function resolveUsingComponents(artifactSource, ownerJsonPath, ownerFilePath) {
5476
6360
  try {
5477
- const usingComponents = JSON.parse(fs.readFileSync(ownerJsonPath, "utf8")).usingComponents;
6361
+ const usingComponents = readComponentConfig(artifactSource, ownerJsonPath).usingComponents;
5478
6362
  if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
5479
6363
  const resolved = /* @__PURE__ */ new Map();
5480
6364
  for (const [alias, rawPath] of Object.entries(usingComponents)) {
@@ -5487,33 +6371,28 @@ function resolveUsingComponents(ownerJsonPath, ownerFilePath) {
5487
6371
  return /* @__PURE__ */ new Map();
5488
6372
  }
5489
6373
  }
5490
- function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias) {
5491
- const componentBasePath = resolveUsingComponents(ownerJsonPath, ownerFilePath).get(alias);
5492
- if (!componentBasePath) return null;
5493
- const filePath = `${componentBasePath}.js`;
5494
- const templatePath = `${componentBasePath}.wxml`;
5495
- const absoluteFilePath = path.resolve(context.project.miniprogramRootPath, filePath);
5496
- const absoluteTemplatePath = path.resolve(context.project.miniprogramRootPath, templatePath);
5497
- return {
5498
- definition: context.moduleLoader.executeComponentModule(absoluteFilePath, componentBasePath),
5499
- filePath,
5500
- templatePath,
5501
- absoluteTemplatePath
5502
- };
6374
+ function resolveComponentGenerics(context, hostNode, ownerJsonPath, ownerFilePath, componentFilePath) {
6375
+ const componentJsonPath = path.resolve(context.project.miniprogramRootPath, `${componentFilePath.replace(JS_FILE_RE, "")}.json`);
6376
+ const componentGenerics = readComponentConfig(context.artifactSource, componentJsonPath).componentGenerics;
6377
+ if (!componentGenerics || typeof componentGenerics !== "object" || Array.isArray(componentGenerics)) return;
6378
+ const ownerComponents = resolveUsingComponents(context.artifactSource, ownerJsonPath, ownerFilePath);
6379
+ const resolved = /* @__PURE__ */ new Map();
6380
+ for (const [genericName, definition] of Object.entries(componentGenerics)) {
6381
+ const selectedAlias = hostNode.attribs?.[`generic:${genericName}`];
6382
+ const selectedPath = selectedAlias ? ownerComponents.get(selectedAlias) : void 0;
6383
+ if (selectedPath) {
6384
+ resolved.set(genericName, selectedPath);
6385
+ continue;
6386
+ }
6387
+ const defaultPath = typeof definition === "object" && definition !== null ? definition.default : void 0;
6388
+ if (typeof defaultPath !== "string" || !defaultPath) continue;
6389
+ const resolvedDefault = defaultPath.startsWith("/") ? defaultPath.replace(LEADING_SLASH_RE$2, "") : path.posix.normalize(path.posix.join(path.posix.dirname(componentFilePath), defaultPath));
6390
+ resolved.set(genericName, resolvedDefault.replace(LEADING_SLASH_RE$2, ""));
6391
+ }
6392
+ return resolved.size > 0 ? resolved : void 0;
5503
6393
  }
5504
6394
  function collectComponentEventBindings(hostNode) {
5505
- const eventBindings = /* @__PURE__ */ new Map();
5506
- for (const [key, value] of Object.entries(hostNode.attribs ?? {})) {
5507
- const matchedPrefix = COMPONENT_EVENT_PREFIXES.find((prefix) => key.startsWith(prefix));
5508
- if (!matchedPrefix) continue;
5509
- const eventName = key.slice(matchedPrefix.length);
5510
- if (!eventName) continue;
5511
- eventBindings.set(eventName, {
5512
- method: value,
5513
- stopAfter: matchedPrefix.startsWith("catch")
5514
- });
5515
- }
5516
- return eventBindings;
6395
+ return collectMiniProgramEventBindings(hostNode.attribs);
5517
6396
  }
5518
6397
  function buildComponentTrigger(componentScopeId, context, hostNode) {
5519
6398
  const hostDataset = collectDataset(hostNode);
@@ -5551,22 +6430,6 @@ function buildComponentTrigger(componentScopeId, context, hostNode) {
5551
6430
  }
5552
6431
  };
5553
6432
  }
5554
- function applyNodeBindings(node, scope) {
5555
- if (!isTagNode(node)) {
5556
- if (node.type === "text" && typeof node.data === "string") node.data = interpolateTemplate(node.data, scope.data);
5557
- return;
5558
- }
5559
- node.attribs ??= {};
5560
- node.attribs["data-sim-scope"] = scope.getScopeId();
5561
- for (const key of STRUCTURAL_ATTRS) delete node.attribs[key];
5562
- for (const [key, value] of Object.entries({ ...node.attribs })) {
5563
- if (EVENT_BINDING_ATTRS.includes(key)) {
5564
- node.attribs["data-sim-tap"] = value;
5565
- continue;
5566
- }
5567
- node.attribs[key] = typeof value === "string" ? String(resolveAttributeValue(value, scope)) : String(value);
5568
- }
5569
- }
5570
6433
  function syncComponentProperties(instance, definition, nextProperties, bindingExpressions, changedPageKeys) {
5571
6434
  const changedRootKeys = [];
5572
6435
  const previousProperties = {};
@@ -5577,8 +6440,7 @@ function syncComponentProperties(instance, definition, nextProperties, bindingEx
5577
6440
  return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
5578
6441
  });
5579
6442
  const previousSnapshot = instance.__propertySnapshots?.[key];
5580
- const deepChanged = bindingAffected && JSON.stringify(previousSnapshot) !== JSON.stringify(nextValue);
5581
- if (instance.properties[key] !== nextValue || deepChanged) {
6443
+ if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
5582
6444
  previousProperties[key] = instance.properties[key];
5583
6445
  instance.properties[key] = nextValue;
5584
6446
  changedRootKeys.push(key);
@@ -5589,31 +6451,70 @@ function syncComponentProperties(instance, definition, nextProperties, bindingEx
5589
6451
  if (changedRootKeys.length === 0) return;
5590
6452
  runComponentObservers(definition, instance, changedRootKeys, previousProperties);
5591
6453
  }
5592
- function createMergedScopeData(pageData, componentProperties, componentData) {
6454
+ function createComponentScope(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots) {
6455
+ const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
5593
6456
  return {
5594
- ...pageData,
5595
- ...componentProperties,
5596
- ...componentData
6457
+ alias: clonedNode.name,
6458
+ classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
6459
+ data: createMergedScopeData(scope.data, componentInstance.properties, componentInstance.data),
6460
+ dataset: collectDataset(clonedNode),
6461
+ eventBindings: collectComponentEventBindings(clonedNode),
6462
+ getMethod: (methodName) => {
6463
+ const method = componentInstance?.[methodName];
6464
+ return typeof method === "function" ? method : void 0;
6465
+ },
6466
+ getScopeId: () => componentScopeId,
6467
+ genericComponents,
6468
+ hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
6469
+ id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
6470
+ listenerScopeId: scope.getScopeId(),
6471
+ ownerScopeId,
6472
+ slots
5597
6473
  };
5598
6474
  }
5599
- function isTruthy(value) {
5600
- return Boolean(value);
5601
- }
5602
- function createLoopScope(scope, itemName, indexName, item, index) {
6475
+ function resolveComponentProperties(clonedNode, scope, definition) {
6476
+ const nextProperties = {};
6477
+ const bindingExpressions = {};
6478
+ const declaredProperties = definition.properties ?? {};
6479
+ for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
6480
+ if (key.startsWith("bind") || key.startsWith("generic:")) continue;
6481
+ const camelizedKey = key.replace(/-([a-z])/g, (_match, char) => char.toUpperCase());
6482
+ const propertyKey = key in declaredProperties || !(camelizedKey in declaredProperties) ? key : camelizedKey;
6483
+ if (isMustacheOnly(String(value))) bindingExpressions[propertyKey] = String(value).trim().slice(2, -2).trim();
6484
+ nextProperties[propertyKey] = resolveComponentAttributeValue(String(value), scope);
6485
+ }
5603
6486
  return {
5604
- ...scope,
5605
- data: {
5606
- ...scope.data,
5607
- [indexName]: index,
5608
- [itemName]: item
5609
- }
6487
+ nextProperties,
6488
+ bindingExpressions
5610
6489
  };
5611
6490
  }
5612
- function evaluateConditionalBranch(node, scope) {
5613
- const condition = node.attribs?.["wx:if"] ?? node.attribs?.["wx:elif"];
5614
- if (condition == null) return true;
5615
- return isTruthy(resolveRawValueByPath(scope.data, condition));
6491
+ function createRuntimeComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId) {
6492
+ const componentInstance = createComponentInstance({
6493
+ definition: componentEntry.definition,
6494
+ properties: nextProperties,
6495
+ requestRender: (callback) => context.session.requestRender(callback),
6496
+ triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
6497
+ });
6498
+ setSelectorQueryScopeId(componentInstance, componentScopeId);
6499
+ componentInstance.is = componentEntry.filePath.replace(JS_FILE_RE, "");
6500
+ componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
6501
+ componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
6502
+ componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
6503
+ componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
6504
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? context.componentCache.get(ownerScopeId) ?? null : null;
6505
+ context.componentCache.set(componentScopeId, componentInstance);
6506
+ runComponentLifecycle(componentInstance, "created");
6507
+ runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
6508
+ componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
6509
+ runComponentLifecycle(componentInstance, "attached");
6510
+ return componentInstance;
6511
+ }
6512
+ function renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
6513
+ const componentDocument = parseTemplateDocument(readTemplateSource(context.artifactSource, componentEntry.absoluteTemplatePath));
6514
+ return renderNodeTree((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, path.resolve(context.project.miniprogramRootPath, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`), componentEntry.filePath, componentScopeId, seenComponentScopes);
5616
6515
  }
6516
+ //#endregion
6517
+ //#region src/runtime/render/index.ts
5617
6518
  function expandNodeByFor(node, scope) {
5618
6519
  const forExpression = node.attribs?.["wx:for"];
5619
6520
  if (!forExpression) return [{
@@ -5673,62 +6574,72 @@ function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath,
5673
6574
  }
5674
6575
  return renderedChildren;
5675
6576
  }
6577
+ function collectComponentSlots(componentNode, scope, ownerJsonPath, ownerFilePath, instancePath) {
6578
+ const slots = /* @__PURE__ */ new Map();
6579
+ (componentNode.children ?? []).forEach((node, index) => {
6580
+ const slotName = isTagNode(node) && typeof node.attribs?.slot === "string" && node.attribs.slot.trim() ? node.attribs.slot.trim() : "default";
6581
+ const entries = slots.get(slotName) ?? [];
6582
+ entries.push({
6583
+ instancePath: `${instancePath}/slot-${slotName}/node-${index}`,
6584
+ node,
6585
+ ownerFilePath,
6586
+ ownerJsonPath,
6587
+ scope
6588
+ });
6589
+ slots.set(slotName, entries);
6590
+ });
6591
+ for (const key of Object.keys(componentNode.attribs ?? {})) {
6592
+ if (!key.startsWith("generic:scoped-slots-")) continue;
6593
+ const slotName = key.slice(21);
6594
+ const inherited = scope.slots?.get(slotName);
6595
+ if (slotName && inherited?.length && !slots.has(slotName)) slots.set(slotName, inherited);
6596
+ }
6597
+ if (componentNode.name?.startsWith("scoped-slots-") && !slots.has("default")) {
6598
+ const slotName = componentNode.name.slice(13);
6599
+ const inherited = scope.slots?.get(slotName);
6600
+ if (inherited?.length) slots.set("default", inherited);
6601
+ }
6602
+ return slots;
6603
+ }
5676
6604
  function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
5677
6605
  const clonedNode = cloneNode(node);
5678
6606
  if (!isTagNode(clonedNode)) {
5679
6607
  applyNodeBindings(clonedNode, scope);
5680
6608
  return clonedNode;
5681
6609
  }
5682
- const componentEntry = resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, clonedNode.name);
6610
+ if (clonedNode.name === "slot") {
6611
+ const slotName = clonedNode.attribs?.name?.trim() || "default";
6612
+ const projected = scope.slots?.get(slotName) ?? [];
6613
+ const children = projected.length ? projected.flatMap((entry) => renderNodeVariants(entry.node, entry.scope, context, entry.ownerJsonPath, entry.ownerFilePath, entry.instancePath, seenComponentScopes)) : renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/slot-fallback-${slotName}`, seenComponentScopes);
6614
+ return {
6615
+ type: "tag",
6616
+ name: "block",
6617
+ attribs: {
6618
+ "data-sim-node": instancePath,
6619
+ "data-sim-scope": scope.getScopeId()
6620
+ },
6621
+ children
6622
+ };
6623
+ }
6624
+ const componentEntry = resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, clonedNode.name, scope.genericComponents?.get(clonedNode.name));
5683
6625
  if (componentEntry) {
5684
6626
  const componentScopeId = `${instancePath}/${clonedNode.name}`;
5685
6627
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
5686
- const nextProperties = {};
5687
- const bindingExpressions = {};
5688
- for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
5689
- if (key.startsWith("bind")) continue;
5690
- if (isMustacheOnly(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
5691
- nextProperties[key] = resolveComponentAttributeValue(String(value), scope);
5692
- }
6628
+ const { nextProperties, bindingExpressions } = resolveComponentProperties(clonedNode, scope, componentEntry.definition);
5693
6629
  let componentInstance = context.componentCache.get(componentScopeId);
5694
- if (!componentInstance) {
5695
- componentInstance = createComponentInstance({
5696
- definition: componentEntry.definition,
5697
- properties: nextProperties,
5698
- triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
5699
- });
5700
- componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
5701
- componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
5702
- componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
5703
- componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
5704
- componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
5705
- runComponentLifecycle(componentInstance, "created");
5706
- runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
5707
- componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
5708
- runComponentLifecycle(componentInstance, "attached");
5709
- context.componentCache.set(componentScopeId, componentInstance);
5710
- } else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
6630
+ if (!componentInstance) componentInstance = createRuntimeComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId);
6631
+ else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
5711
6632
  seenComponentScopes.add(componentScopeId);
5712
- const componentScope = {
5713
- alias: clonedNode.name,
5714
- classList: String(clonedNode.attribs?.class ?? "").split(CLASS_SPLIT_RE).map((item) => item.trim()).filter(Boolean),
5715
- data: createMergedScopeData(scope.data, componentInstance.properties, componentInstance.data),
5716
- dataset: collectDataset(clonedNode),
5717
- eventBindings: collectComponentEventBindings(clonedNode),
5718
- getMethod: (methodName) => {
5719
- const method = componentInstance?.[methodName];
5720
- return typeof method === "function" ? method : void 0;
5721
- },
5722
- getScopeId: () => componentScopeId,
5723
- hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
5724
- id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
5725
- listenerScopeId: scope.getScopeId(),
5726
- ownerScopeId
5727
- };
6633
+ const genericComponents = resolveComponentGenerics(context, clonedNode, ownerJsonPath, ownerFilePath, componentEntry.filePath);
6634
+ const slots = collectComponentSlots(clonedNode, scope, ownerJsonPath, ownerFilePath, componentScopeId);
6635
+ const componentScope = createComponentScope(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots);
5728
6636
  context.componentScopes.set(componentScopeId, componentScope);
5729
- const componentDocument = parseTemplateDocument(readTemplateSource(componentEntry.absoluteTemplatePath));
5730
- const renderedComponentRoot = renderNodeTree((componentDocument.children ?? [])[0] ?? componentDocument, componentScope, context, path.resolve(context.project.miniprogramRootPath, `${componentEntry.filePath.replace(JS_FILE_RE, "")}.json`), componentEntry.filePath, componentScopeId, seenComponentScopes);
5731
- if (renderedComponentRoot.attribs) renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
6637
+ const renderedComponentRoot = renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes);
6638
+ if (renderedComponentRoot.attribs) {
6639
+ renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
6640
+ renderedComponentRoot.attribs["data-sim-node"] = instancePath;
6641
+ renderedComponentRoot.attribs["data-sim-scope"] = componentScopeId;
6642
+ }
5732
6643
  if (!componentInstance.__ready__) {
5733
6644
  runComponentLifecycle(componentInstance, "ready");
5734
6645
  componentInstance.__ready__ = true;
@@ -5737,12 +6648,14 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
5737
6648
  return renderedComponentRoot;
5738
6649
  }
5739
6650
  applyNodeBindings(clonedNode, scope);
6651
+ clonedNode.attribs["data-sim-node"] = instancePath;
5740
6652
  clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes);
5741
6653
  return clonedNode;
5742
6654
  }
5743
6655
  function renderRuntimePageTree(context, page) {
5744
6656
  const route = page.route.replace(LEADING_SLASH_RE$2, "");
5745
- const document = parseTemplateDocument(readTemplateSource(path.resolve(context.project.miniprogramRootPath, `${route}.wxml`)));
6657
+ const templatePath = path.resolve(context.project.miniprogramRootPath, `${route}.wxml`);
6658
+ const document = parseTemplateDocument(readTemplateSource(context.artifactSource, templatePath));
5746
6659
  const pageScopeId = `page:${route}`;
5747
6660
  const pageScope = {
5748
6661
  data: page.data,
@@ -5772,7 +6685,7 @@ function renderRuntimePageTree(context, page) {
5772
6685
  function createRequireNotFoundError(request, importer) {
5773
6686
  return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in headless runtime.`);
5774
6687
  }
5775
- function resolveRequiredModulePath(importer, request) {
6688
+ function resolveRequiredModulePath(artifactSource, importer, request) {
5776
6689
  if (!request.startsWith(".")) throw createRequireNotFoundError(request, importer);
5777
6690
  const basePath = path.resolve(path.dirname(importer), request);
5778
6691
  const candidates = [
@@ -5781,10 +6694,10 @@ function resolveRequiredModulePath(importer, request) {
5781
6694
  `${basePath}.json`,
5782
6695
  path.join(basePath, "index.js")
5783
6696
  ];
5784
- for (const candidate of candidates) if (fs.existsSync(candidate)) return candidate;
6697
+ for (const candidate of candidates) if (artifactSource.has(candidate)) return candidate;
5785
6698
  throw createRequireNotFoundError(request, importer);
5786
6699
  }
5787
- function createExecutionContext(registries, getCurrentPages, getApp, wxDriver) {
6700
+ function createExecutionContext(registries, getCurrentPages, getApp, wxDriver, kernel, globals) {
5788
6701
  const wx = createHeadlessWx(wxDriver);
5789
6702
  return {
5790
6703
  App(definition) {
@@ -5802,47 +6715,64 @@ function createExecutionContext(registries, getCurrentPages, getApp, wxDriver) {
5802
6715
  Page(definition) {
5803
6716
  return registerPageDefinition(registries, definition);
5804
6717
  },
5805
- console,
5806
- clearTimeout,
6718
+ console: kernel.diagnostics.createConsole(),
6719
+ clearInterval: (handle) => kernel.scheduler.clearInterval(handle),
6720
+ clearTimeout: (handle) => kernel.scheduler.clearTimeout(handle),
5807
6721
  getApp,
5808
6722
  getCurrentPages,
5809
6723
  globalThis: void 0,
5810
6724
  process,
5811
6725
  require: void 0,
5812
- setInterval,
5813
- setTimeout,
5814
- wx
6726
+ setInterval: kernel.scheduler.setInterval.bind(kernel.scheduler),
6727
+ setTimeout: kernel.scheduler.setTimeout.bind(kernel.scheduler),
6728
+ wx,
6729
+ ...globals
5815
6730
  };
5816
6731
  }
5817
- function createModuleLoader(registries, getCurrentPages, getApp, wxDriver) {
6732
+ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, options) {
5818
6733
  const moduleCache = /* @__PURE__ */ new Map();
5819
- const executionContext = createExecutionContext(registries, getCurrentPages, getApp, wxDriver);
6734
+ const executionContext = createExecutionContext(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {});
5820
6735
  executionContext.globalThis = executionContext;
5821
6736
  function executeModule(filePath, loadContext) {
5822
6737
  const resolvedPath = path.resolve(filePath);
5823
6738
  const cached = moduleCache.get(resolvedPath);
5824
- if (cached) return cached.exports;
5825
- const source = fs.readFileSync(resolvedPath, "utf8");
5826
- const module = { exports: {} };
6739
+ if (cached) return cached;
6740
+ const source = options.artifactSource.readText(resolvedPath);
6741
+ if (source == null) throw new TypeError(`Missing module in headless runtime: ${normalize(resolvedPath)}`);
6742
+ const module = {
6743
+ componentDefinitions: [],
6744
+ exports: {}
6745
+ };
5827
6746
  moduleCache.set(resolvedPath, module);
6747
+ const registeredDefinitionsBefore = new Set(registries.components.values());
6748
+ const requiredComponentDefinitions = [];
5828
6749
  const previousLoadContext = registries.currentLoadContext;
5829
6750
  registries.currentLoadContext = loadContext;
5830
- const localRequire = (request) => {
5831
- const requiredPath = resolveRequiredModulePath(resolvedPath, request);
6751
+ const localRequire = ((request) => {
6752
+ const requiredPath = resolveRequiredModulePath(options.artifactSource, resolvedPath, request);
5832
6753
  if (requiredPath.endsWith(".json")) {
5833
- const content = fs.readFileSync(requiredPath, "utf8");
6754
+ const content = options.artifactSource.readText(requiredPath);
6755
+ if (content == null) throw createRequireNotFoundError(request, resolvedPath);
5834
6756
  return JSON.parse(content);
5835
6757
  }
5836
- return executeModule(requiredPath, null);
5837
- };
6758
+ const requiredModule = executeModule(requiredPath, null);
6759
+ requiredComponentDefinitions.push(...requiredModule.componentDefinitions);
6760
+ return requiredModule.exports;
6761
+ });
6762
+ localRequire.async = (request) => Promise.resolve().then(() => localRequire(request));
5838
6763
  try {
5839
6764
  new vm.Script(`(function (exports, module, require, __filename, __dirname) { ${source}\n})`, { filename: resolvedPath }).runInNewContext(executionContext)(module.exports, module, localRequire, resolvedPath, path.dirname(resolvedPath));
5840
- return module.exports;
6765
+ const registeredDefinitions = [...registries.components.values()].filter((definition) => !registeredDefinitionsBefore.has(definition));
6766
+ module.componentDefinitions = [.../* @__PURE__ */ new Set([...requiredComponentDefinitions, ...registeredDefinitions])];
6767
+ return module;
5841
6768
  } finally {
5842
6769
  registries.currentLoadContext = previousLoadContext;
5843
6770
  }
5844
6771
  }
5845
6772
  return {
6773
+ close() {
6774
+ moduleCache.clear();
6775
+ },
5846
6776
  executeAppModule(filePath) {
5847
6777
  executeModule(filePath, { kind: "app" });
5848
6778
  if (!registries.appDefinition) throw new Error(`App() was not registered while executing ${normalize(filePath)} in headless runtime.`);
@@ -5858,14 +6788,15 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver) {
5858
6788
  return definition;
5859
6789
  },
5860
6790
  executeComponentModule(filePath, id) {
5861
- executeModule(filePath, {
6791
+ const loadedModule = executeModule(filePath, {
5862
6792
  kind: "component",
5863
6793
  route: id
5864
6794
  });
5865
- const definition = registries.components.get(id);
6795
+ const definition = registries.components.get(id) ?? registerExportedComponentDefinition(registries, id, loadedModule.exports, loadedModule.componentDefinitions.at(-1));
5866
6796
  if (!definition) throw new Error(`Component() was not registered for id "${id}" while executing ${normalize(filePath)}.`);
5867
6797
  return definition;
5868
- }
6798
+ },
6799
+ wx: executionContext.wx
5869
6800
  };
5870
6801
  }
5871
6802
  //#endregion
@@ -5928,9 +6859,10 @@ function createAppLaunchOptions(pathname, query) {
5928
6859
  scene: 1001
5929
6860
  };
5930
6861
  }
5931
- function readJsonObject(filePath) {
6862
+ function readJsonObject(project, filePath) {
5932
6863
  try {
5933
- const value = JSON.parse(fs.readFileSync(filePath, "utf8"));
6864
+ const source = project.artifactSource.readText(filePath);
6865
+ const value = source == null ? void 0 : JSON.parse(source);
5934
6866
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
5935
6867
  } catch {
5936
6868
  return;
@@ -5944,6 +6876,7 @@ function resolveNavigationPath(targetPath, baseRoute) {
5944
6876
  }
5945
6877
  var HeadlessSession = class {
5946
6878
  project;
6879
+ kernel = new RuntimeKernel();
5947
6880
  appDefinition = null;
5948
6881
  appInstance = null;
5949
6882
  moduleLoader;
@@ -5952,6 +6885,9 @@ var HeadlessSession = class {
5952
6885
  pages = [];
5953
6886
  componentCache = /* @__PURE__ */ new Map();
5954
6887
  componentScopes = /* @__PURE__ */ new Map();
6888
+ selectorQueryScopeSnapshots = /* @__PURE__ */ new WeakMap();
6889
+ renderRequestPending = false;
6890
+ renderRequestCallbacks = [];
5955
6891
  tabBarRoutes;
5956
6892
  tabPages = /* @__PURE__ */ new Map();
5957
6893
  tabBarItems = /* @__PURE__ */ new Map();
@@ -5962,13 +6898,15 @@ var HeadlessSession = class {
5962
6898
  canvasContexts = /* @__PURE__ */ new Map();
5963
6899
  enterOptions = createAppLaunchOptions("", {});
5964
6900
  launchOptions = createAppLaunchOptions("", {});
5965
- wxState = createHeadlessWxState();
6901
+ wxState;
5966
6902
  pullDownRefreshState = {
5967
6903
  active: false,
5968
6904
  stopCalls: 0
5969
6905
  };
5970
6906
  constructor(options) {
5971
- this.project = loadProject(options.projectPath);
6907
+ if (!options.project && !options.projectPath) throw new Error("Headless runtime requires projectPath or project.");
6908
+ this.project = options.project ?? loadProject(options.projectPath);
6909
+ this.wxState = createHeadlessWxState(this.kernel.scheduler, { strictMocks: options.strictHostMocks });
5972
6910
  this.registries = createHostRegistries();
5973
6911
  const rawTabBarList = Array.isArray(this.project.appConfig.tabBar?.list) ? this.project.appConfig.tabBar.list : [];
5974
6912
  this.tabBarRoutes = /* @__PURE__ */ new Set();
@@ -6018,6 +6956,7 @@ var HeadlessSession = class {
6018
6956
  }
6019
6957
  }),
6020
6958
  getAppBaseInfoSync: () => deriveAppBaseInfo(this.systemInfo),
6959
+ getDeviceInfo: () => deriveDeviceInfo(this.systemInfo),
6021
6960
  getLaunchOptionsSync: () => ({
6022
6961
  ...this.launchOptions,
6023
6962
  query: { ...this.launchOptions.query },
@@ -6027,6 +6966,7 @@ var HeadlessSession = class {
6027
6966
  }
6028
6967
  }),
6029
6968
  getClipboardData: () => this.wxState.getClipboardData(),
6969
+ getLocation: () => createDefaultLocationResult(),
6030
6970
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
6031
6971
  getNetworkType: () => this.wxState.getNetworkType(),
6032
6972
  navigateBack: (option) => this.navigateBack(option?.delta),
@@ -6046,7 +6986,7 @@ var HeadlessSession = class {
6046
6986
  removeSavedFile: (option) => this.wxState.removeSavedFile(option),
6047
6987
  saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
6048
6988
  saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
6049
- nextTick: (callback) => queueMicrotask(() => callback?.()),
6989
+ nextTick: (callback) => this.kernel.scheduler.queueMicrotask(() => callback?.()),
6050
6990
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
6051
6991
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
6052
6992
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
@@ -6078,14 +7018,45 @@ var HeadlessSession = class {
6078
7018
  removeTabBarBadge: (option) => this.removeTabBarBadge(option.index),
6079
7019
  setTabBarBadge: (option) => this.setTabBarBadge(option.index, option.text),
6080
7020
  updateShareMenu: (option) => this.wxState.updateShareMenu(option)
7021
+ }, {
7022
+ artifactSource: this.project.artifactSource,
7023
+ globals: options.globals,
7024
+ kernel: this.kernel
6081
7025
  });
6082
7026
  }
7027
+ assertActive() {
7028
+ this.kernel.assertActive();
7029
+ }
7030
+ close() {
7031
+ if (this.kernel.isClosed) return;
7032
+ this.unloadAllPages();
7033
+ this.canvasContexts.clear();
7034
+ this.renderRequestCallbacks.length = 0;
7035
+ this.renderRequestPending = false;
7036
+ this.wxState.close();
7037
+ this.moduleLoader.close();
7038
+ this.kernel.close();
7039
+ }
7040
+ getDiagnostics() {
7041
+ return this.kernel.diagnostics.getEntries();
7042
+ }
7043
+ get isClosed() {
7044
+ return this.kernel.isClosed;
7045
+ }
6083
7046
  getApp() {
7047
+ this.assertActive();
6084
7048
  return this.appInstance;
6085
7049
  }
6086
7050
  getCurrentPages() {
7051
+ this.assertActive();
6087
7052
  return this.pages.slice();
6088
7053
  }
7054
+ callWxMethod(methodName, ...args) {
7055
+ this.assertActive();
7056
+ const method = this.moduleLoader.wx[methodName];
7057
+ if (typeof method !== "function") throw new TypeError(`wx.${methodName} is not available in headless runtime.`);
7058
+ return Reflect.apply(method, this.moduleLoader.wx, args);
7059
+ }
6089
7060
  getCurrentPageNavigationBarTitle() {
6090
7061
  return this.currentPageInstance?.__navigationBarTitle__ ?? null;
6091
7062
  }
@@ -6122,9 +7093,11 @@ var HeadlessSession = class {
6122
7093
  return this.wxState.getSavedFileList().fileList;
6123
7094
  }
6124
7095
  renderCurrentPage() {
7096
+ this.assertActive();
6125
7097
  const current = this.requireCurrentPage("renderCurrentPage()");
6126
- return renderRuntimePageTree({
7098
+ const rendered = renderRuntimePageTree({
6127
7099
  changedPageKeys: current.__lastChangedKeys__ ?? [],
7100
+ artifactSource: this.project.artifactSource,
6128
7101
  componentCache: this.componentCache,
6129
7102
  componentScopes: this.componentScopes,
6130
7103
  moduleLoader: this.moduleLoader,
@@ -6132,11 +7105,32 @@ var HeadlessSession = class {
6132
7105
  session: {
6133
7106
  createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
6134
7107
  createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
7108
+ requestRender: (callback) => this.requestRender(callback),
6135
7109
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
6136
7110
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
6137
7111
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
6138
7112
  }
6139
7113
  }, current);
7114
+ const componentScopePrefix = `page:${stripLeadingSlash(current.route)}`;
7115
+ for (const [scopeId, instance] of this.componentCache.entries()) if (scopeId.startsWith(componentScopePrefix)) this.selectorQueryScopeSnapshots.set(instance, {
7116
+ page: current,
7117
+ root: rendered.root,
7118
+ scopeId
7119
+ });
7120
+ return rendered;
7121
+ }
7122
+ requestRender(callback) {
7123
+ this.assertActive();
7124
+ if (callback) this.renderRequestCallbacks.push(callback);
7125
+ if (this.renderRequestPending) return;
7126
+ this.renderRequestPending = true;
7127
+ Promise.resolve().then(() => {
7128
+ if (this.kernel.isClosed) return;
7129
+ this.renderRequestPending = false;
7130
+ const callbacks = this.renderRequestCallbacks.splice(0);
7131
+ if (this.currentPageInstance) this.renderCurrentPage();
7132
+ callbacks.forEach((cb) => cb());
7133
+ });
6140
7134
  }
6141
7135
  getScopeSnapshot(scopeId) {
6142
7136
  const scope = this.componentScopes.get(scopeId);
@@ -6192,6 +7186,7 @@ var HeadlessSession = class {
6192
7186
  const normalizedScopeId = scopeId.trim();
6193
7187
  if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in headless runtime.");
6194
7188
  const current = this.requireCurrentPage(`scope method "${methodName}"`);
7189
+ this.renderCurrentPage();
6195
7190
  if (normalizedScopeId === `page:${stripLeadingSlash(current.route)}`) {
6196
7191
  const method = current[methodName];
6197
7192
  if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${current.route}.`);
@@ -6270,6 +7265,9 @@ var HeadlessSession = class {
6270
7265
  getAppBaseInfo() {
6271
7266
  return deriveAppBaseInfo(this.systemInfo);
6272
7267
  }
7268
+ getDeviceInfo() {
7269
+ return deriveDeviceInfo(this.systemInfo);
7270
+ }
6273
7271
  getLaunchOptions() {
6274
7272
  return {
6275
7273
  ...this.launchOptions,
@@ -6293,6 +7291,9 @@ var HeadlessSession = class {
6293
7291
  getMenuButtonBoundingClientRect() {
6294
7292
  return deriveMenuButtonBoundingClientRect(this.systemInfo);
6295
7293
  }
7294
+ getLocation() {
7295
+ return createDefaultLocationResult();
7296
+ }
6296
7297
  getNetworkType() {
6297
7298
  return this.wxState.getNetworkType();
6298
7299
  }
@@ -6437,6 +7438,7 @@ var HeadlessSession = class {
6437
7438
  return { errMsg: "setTabBarBadge:ok" };
6438
7439
  }
6439
7440
  bootstrap(launchOptions = createAppLaunchOptions("", {})) {
7441
+ this.assertActive();
6440
7442
  if (this.appInstance) return this.appInstance;
6441
7443
  this.launchOptions = createAppLaunchOptions(launchOptions.path, launchOptions.query);
6442
7444
  this.enterOptions = createAppLaunchOptions(launchOptions.path, launchOptions.query);
@@ -6454,6 +7456,7 @@ var HeadlessSession = class {
6454
7456
  const pageInstance = this.createFreshPage(target);
6455
7457
  this.pages.push(pageInstance);
6456
7458
  this.currentPageInstance = pageInstance;
7459
+ this.runInitialPageLifecycles(pageInstance, target.query);
6457
7460
  return pageInstance;
6458
7461
  }
6459
7462
  navigateTo(url) {
@@ -6466,6 +7469,7 @@ var HeadlessSession = class {
6466
7469
  const pageInstance = this.createFreshPage(target);
6467
7470
  this.pages.push(pageInstance);
6468
7471
  this.currentPageInstance = pageInstance;
7472
+ this.runInitialPageLifecycles(pageInstance, target.query);
6469
7473
  return pageInstance;
6470
7474
  }
6471
7475
  redirectTo(url) {
@@ -6480,6 +7484,7 @@ var HeadlessSession = class {
6480
7484
  const pageInstance = this.createFreshPage(target);
6481
7485
  this.pages.push(pageInstance);
6482
7486
  this.currentPageInstance = pageInstance;
7487
+ this.runInitialPageLifecycles(pageInstance, target.query);
6483
7488
  return pageInstance;
6484
7489
  }
6485
7490
  navigateBack(delta = 1) {
@@ -6501,11 +7506,7 @@ var HeadlessSession = class {
6501
7506
  if (!this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.switchTab() can only open a tabBar page in headless runtime: ${url}`);
6502
7507
  const current = this.currentPageInstance;
6503
7508
  const cachedTarget = this.tabPages.get(target.routeRecord.route) ?? null;
6504
- const tabItem = this.resolveTabBarItem(target.routeRecord.route);
6505
- if (current === cachedTarget && current) {
6506
- current.onTabItemTap?.(tabItem);
6507
- return current;
6508
- }
7509
+ if (current === cachedTarget && current) return current;
6509
7510
  if (current && current !== cachedTarget) {
6510
7511
  current.onHide?.();
6511
7512
  this.runPageComponentLifetime(current.route, "hide");
@@ -6516,17 +7517,20 @@ var HeadlessSession = class {
6516
7517
  this.unloadPage(page);
6517
7518
  }
6518
7519
  let nextPage = cachedTarget;
7520
+ let shouldRunInitialLifecycles = false;
6519
7521
  if (!nextPage) {
6520
7522
  nextPage = this.createFreshPage(target);
6521
7523
  this.tabPages.set(target.routeRecord.route, nextPage);
6522
- } else if (current !== nextPage) {
6523
- nextPage.onShow?.();
6524
- this.runPageComponentLifetime(nextPage.route, "show");
7524
+ shouldRunInitialLifecycles = true;
6525
7525
  }
6526
- nextPage.onTabItemTap?.(tabItem);
6527
7526
  this.pages.length = 0;
6528
7527
  this.pages.push(nextPage);
6529
7528
  this.currentPageInstance = nextPage;
7529
+ if (shouldRunInitialLifecycles) this.runInitialPageLifecycles(nextPage, target.query);
7530
+ else if (current !== nextPage) {
7531
+ nextPage.onShow?.();
7532
+ this.runPageComponentLifetime(nextPage.route, "show");
7533
+ }
6530
7534
  return nextPage;
6531
7535
  }
6532
7536
  pageScrollTo(option) {
@@ -6574,15 +7578,33 @@ var HeadlessSession = class {
6574
7578
  }
6575
7579
  executeSelectorQuery(requests, scope) {
6576
7580
  const current = this.requireCurrentPage("wx.createSelectorQuery().exec()");
6577
- if (scope && scope !== current && !Array.from(this.componentCache.values()).includes(scope)) throw new Error("wx.createSelectorQuery().in(component) received an unknown scope in headless runtime.");
7581
+ const nativeScope = resolveSelectorQueryNativeScope(scope, current, this.componentCache.values());
7582
+ const staleScope = scope && !nativeScope ? resolveSelectorQueryScopeSnapshot(scope, this.selectorQueryScopeSnapshots) : null;
7583
+ if (scope && !nativeScope && !staleScope) {
7584
+ if (resolveSelectorQueryScopeId(scope)) return requests.map((request) => request.target === "viewport" ? {
7585
+ scrollLeft: 0,
7586
+ scrollTop: current.__scrollTop__ ?? 0
7587
+ } : request.single ? null : []);
7588
+ throw new Error("wx.createSelectorQuery().in(component) received an unknown scope in headless runtime.");
7589
+ }
7590
+ if (staleScope) return executeSelectorQueryRequests(requests, {
7591
+ page: staleScope.snapshot.page,
7592
+ resolveContext: (node) => {
7593
+ if (node.name !== "canvas") return { type: "unsupported-context" };
7594
+ const canvasId = node.attribs?.["canvas-id"];
7595
+ return typeof canvasId === "string" && canvasId ? this.createCanvasContext(canvasId, staleScope.nativeScope) : { type: "unsupported-context" };
7596
+ },
7597
+ root: resolveSelectorQueryScopeRoot(staleScope.snapshot.root, staleScope.snapshot.scopeId),
7598
+ windowInfo: this.getWindowInfo()
7599
+ });
6578
7600
  const rendered = this.renderCurrentPage();
6579
- const scopeId = scope && scope !== current ? this.getComponentScopeId(scope) : null;
7601
+ const scopeId = nativeScope && nativeScope !== current ? this.getComponentScopeId(nativeScope) : null;
6580
7602
  return executeSelectorQueryRequests(requests, {
6581
7603
  page: current,
6582
7604
  resolveContext: (node) => {
6583
7605
  if (node.name !== "canvas") return { type: "unsupported-context" };
6584
7606
  const canvasId = node.attribs?.["canvas-id"];
6585
- return typeof canvasId === "string" && canvasId ? this.createCanvasContext(canvasId, scope) : { type: "unsupported-context" };
7607
+ return typeof canvasId === "string" && canvasId ? this.createCanvasContext(canvasId, nativeScope ?? void 0) : { type: "unsupported-context" };
6586
7608
  },
6587
7609
  root: resolveSelectorQueryScopeRoot(rendered.root, scopeId),
6588
7610
  windowInfo: this.getWindowInfo()
@@ -6592,7 +7614,7 @@ var HeadlessSession = class {
6592
7614
  const pageModulePath = path.resolve(this.project.miniprogramRootPath, `${target.routeRecord.route}.js`);
6593
7615
  const pageConfigPath = path.resolve(this.project.miniprogramRootPath, `${target.routeRecord.route}.json`);
6594
7616
  const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, target.routeRecord.route);
6595
- const pageConfig = readJsonObject(pageConfigPath);
7617
+ const pageConfig = readJsonObject(this.project, pageConfigPath);
6596
7618
  const pageInstance = createPageInstance(`/${target.routeRecord.route}`, pageDefinition, target.query, {
6597
7619
  background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
6598
7620
  navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
@@ -6601,21 +7623,18 @@ var HeadlessSession = class {
6601
7623
  pageInstance.createMediaQueryObserver = () => this.createMediaQueryObserver(pageInstance);
6602
7624
  pageInstance.selectComponent = (selector) => this.selectComponent(selector);
6603
7625
  pageInstance.selectAllComponents = (selector) => this.selectAllComponents(selector);
6604
- pageInstance.onLoad?.(target.query);
6605
- pageInstance.onShow?.();
6606
- pageInstance.onReady?.();
6607
7626
  if (this.isTabBarRoute(target.routeRecord.route)) this.tabPages.set(target.routeRecord.route, pageInstance);
6608
7627
  return pageInstance;
6609
7628
  }
7629
+ runInitialPageLifecycles(pageInstance, query) {
7630
+ pageInstance.onLoad?.(query);
7631
+ pageInstance.onShow?.();
7632
+ pageInstance.onReady?.();
7633
+ pageInstance.onRouteDone?.({});
7634
+ }
6610
7635
  isTabBarRoute(route) {
6611
7636
  return this.tabBarRoutes.has(stripLeadingSlash(route));
6612
7637
  }
6613
- resolveTabBarItem(route) {
6614
- const pagePath = stripLeadingSlash(route);
6615
- const item = this.tabBarItems.get(pagePath);
6616
- if (!item) throw new Error(`Missing tabBar metadata for route "${route}" in headless runtime.`);
6617
- return { ...item };
6618
- }
6619
7638
  requireTabBarItem(index, action) {
6620
7639
  const normalizedIndex = Number.isFinite(index) ? Math.trunc(index) : NaN;
6621
7640
  const item = this.tabBarState.get(normalizedIndex);
@@ -6642,7 +7661,7 @@ var HeadlessSession = class {
6642
7661
  };
6643
7662
  }
6644
7663
  unloadAllPages() {
6645
- const pagesToUnload = new Set([...this.pages, ...this.tabPages.values()]);
7664
+ const pagesToUnload = /* @__PURE__ */ new Set([...this.pages, ...this.tabPages.values()]);
6646
7665
  for (const page of [...pagesToUnload].reverse()) this.unloadPage(page);
6647
7666
  this.pages.length = 0;
6648
7667
  this.tabPages.clear();
@@ -6666,7 +7685,7 @@ var HeadlessSession = class {
6666
7685
  selectComponentsWithin(rootScopeId, selector) {
6667
7686
  const selectorParts = normalizeSelectorParts(selector);
6668
7687
  if (selectorParts.length === 0) return [];
6669
- return [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
7688
+ const matches = [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
6670
7689
  if (!candidateScopeId.includes("/")) return false;
6671
7690
  if (rootScopeId && candidateScopeId === rootScopeId) return false;
6672
7691
  if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
@@ -6679,7 +7698,9 @@ var HeadlessSession = class {
6679
7698
  currentScope = currentScope.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
6680
7699
  }
6681
7700
  return true;
6682
- }).map(([candidateScopeId]) => this.componentCache.get(candidateScopeId)).filter(Boolean);
7701
+ });
7702
+ const directlyOwned = rootScopeId ? matches.filter(([, scope]) => scope.ownerScopeId === rootScopeId) : [];
7703
+ return (directlyOwned.length > 0 ? directlyOwned : matches).map(([candidateScopeId]) => this.componentCache.get(candidateScopeId)).filter(Boolean);
6683
7704
  }
6684
7705
  detachPageComponents(route) {
6685
7706
  const prefix = `page:${stripLeadingSlash(route)}`;
@@ -6812,15 +7833,246 @@ function createHeadlessSession(options) {
6812
7833
  return new HeadlessSession(options);
6813
7834
  }
6814
7835
  //#endregion
6815
- //#region src/testing/pageHandle.ts
7836
+ //#region src/testing/logicalSnapshot.ts
7837
+ function collectNodeText(node) {
7838
+ if (node.type === "text") return node.data ?? "";
7839
+ return (node.children ?? []).map(collectNodeText).join("");
7840
+ }
7841
+ function createLogicalNode(node) {
7842
+ if (node.type === "text") return {
7843
+ attrs: {},
7844
+ children: [],
7845
+ text: node.data ?? "",
7846
+ type: "text"
7847
+ };
7848
+ return {
7849
+ attrs: Object.fromEntries(Object.entries(node.attribs ?? {}).filter(([key]) => !key.startsWith("data-sim-"))),
7850
+ children: (node.children ?? []).map(createLogicalNode),
7851
+ nodeId: node.attribs?.["data-sim-node"],
7852
+ tag: node.name,
7853
+ text: collectNodeText(node),
7854
+ type: "element"
7855
+ };
7856
+ }
7857
+ //#endregion
7858
+ //#region src/testing/pageNodeAccess.ts
7859
+ function createPageRootNodeHandle(options) {
7860
+ const { page, project, session } = options;
7861
+ const tree = session?.getCurrentPages().includes(page) ? session.renderCurrentPage() : renderPageTree(project, page);
7862
+ return new HeadlessTestingNodeHandle(tree.root.type === "root" ? tree.root.children?.[0] ?? tree.root : tree.root, {
7863
+ assertActive: options.assertActive,
7864
+ callMethod: (scopeId, methodName, event) => {
7865
+ if (session?.getCurrentPages().includes(page)) return session.callScopeMethod(scopeId, methodName, event);
7866
+ const method = page[methodName];
7867
+ if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${page.route}.`);
7868
+ return method.call(page, event);
7869
+ },
7870
+ createPageHandle: options.createPageHandle,
7871
+ createScopeHandle: (scopeId) => {
7872
+ if (!session) throw new Error("Scope handles are not available without an active headless testing session.");
7873
+ return scopeId ? new HeadlessTestingScopeHandle(scopeId, project, session) : null;
7874
+ },
7875
+ ownerScopeId: (scopeId) => {
7876
+ if (!session || !scopeId) return null;
7877
+ if (session.getScopeSnapshot(scopeId)?.type !== "component") return null;
7878
+ const owner = session.selectOwnerComponent(scopeId);
7879
+ return session.getScopeIdForComponent(owner);
7880
+ }
7881
+ });
7882
+ }
7883
+ //#endregion
7884
+ //#region src/testing/pageWait.ts
6816
7885
  const DEFAULT_WAIT_TIMEOUT$1 = 1e3;
6817
7886
  const DEFAULT_WAIT_INTERVAL$1 = 10;
7887
+ function normalizeInput(value, label) {
7888
+ const normalized = value.trim();
7889
+ if (!normalized) throw new Error(`${label} must be a non-empty string in headless testing runtime.`);
7890
+ return normalized;
7891
+ }
7892
+ async function pollUntil$2(access, check, errorMessage, options) {
7893
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT$1)) : DEFAULT_WAIT_TIMEOUT$1;
7894
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_WAIT_INTERVAL$1)) : DEFAULT_WAIT_INTERVAL$1;
7895
+ const deadline = Date.now() + timeout;
7896
+ while (true) {
7897
+ const result = await check();
7898
+ if (result != null) return result;
7899
+ if (Date.now() >= deadline) throw new Error(errorMessage);
7900
+ await access.waitFor(interval);
7901
+ }
7902
+ }
7903
+ async function waitForPageSelector(access, selector, options = {}) {
7904
+ const normalizedSelector = normalizeInput(selector, "Selector");
7905
+ if (options.state === "detached") {
7906
+ await pollUntil$2(access, async () => await access.findOne(normalizedSelector) ? null : true, `Timed out waiting for selector "${normalizedSelector}" to become detached in headless testing runtime.`, options);
7907
+ return null;
7908
+ }
7909
+ return await pollUntil$2(access, async () => await access.findOne(normalizedSelector), `Timed out waiting for selector "${normalizedSelector}" to appear in headless testing runtime.`, options);
7910
+ }
7911
+ async function waitForPageComponent(access, selector, options = {}) {
7912
+ const normalizedSelector = normalizeInput(selector, "Selector");
7913
+ return await pollUntil$2(access, async () => await access.selectComponent(normalizedSelector), `Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`, options);
7914
+ }
7915
+ async function waitForPageComponents(access, selector, count = 1, options = {}) {
7916
+ const normalizedSelector = normalizeInput(selector, "Selector");
7917
+ const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
7918
+ return await pollUntil$2(access, async () => {
7919
+ const components = await access.selectComponents(normalizedSelector);
7920
+ return components.length >= normalizedCount ? components : null;
7921
+ }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
7922
+ }
7923
+ async function waitForPageText(access, text, options = {}) {
7924
+ const normalizedText = normalizeInput(text, "Text");
7925
+ return await pollUntil$2(access, async () => (await access.wxml()).includes(normalizedText) ? normalizedText : null, `Timed out waiting for text "${normalizedText}" in headless testing runtime.`, options);
7926
+ }
7927
+ async function waitForPageTextGone(access, text, options = {}) {
7928
+ const normalizedText = normalizeInput(text, "Text");
7929
+ await pollUntil$2(access, async () => (await access.wxml()).includes(normalizedText) ? null : true, `Timed out waiting for text "${normalizedText}" to disappear in headless testing runtime.`, options);
7930
+ }
7931
+ async function waitForPageData(access, path, matcher, hasMatcher, options = {}) {
7932
+ const normalizedPath = normalizeInput(path, "Data path");
7933
+ return await pollUntil$2(access, async () => {
7934
+ const value = await access.data(normalizedPath);
7935
+ if (typeof matcher === "function") return matcher(value) ? value : null;
7936
+ if (hasMatcher) return Object.is(value, matcher) ? value : null;
7937
+ return value === void 0 ? null : value;
7938
+ }, `Timed out waiting for data "${normalizedPath}" in headless testing runtime.`, options);
7939
+ }
7940
+ //#endregion
7941
+ //#region src/testing/rendered.ts
7942
+ const DEFAULT_RENDERED_WAIT_TIMEOUT = 15e3;
7943
+ const DEFAULT_RENDERED_WAIT_INTERVAL = 10;
7944
+ function normalizeSelector(selector) {
7945
+ const normalizedSelector = selector.trim();
7946
+ if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7947
+ return normalizedSelector;
7948
+ }
7949
+ function matchesDataset(node, expected) {
7950
+ if (!expected) return true;
7951
+ const dataset = node.dataset ?? {};
7952
+ return Object.entries(expected).every(([key, value]) => String(dataset[key] ?? "") === String(value));
7953
+ }
7954
+ async function pollUntil$1(access, check, errorMessage, options) {
7955
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_RENDERED_WAIT_TIMEOUT)) : DEFAULT_RENDERED_WAIT_TIMEOUT;
7956
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_RENDERED_WAIT_INTERVAL)) : DEFAULT_RENDERED_WAIT_INTERVAL;
7957
+ const deadline = Date.now() + timeout;
7958
+ while (true) {
7959
+ const result = await check();
7960
+ if (result != null) return result;
7961
+ if (Date.now() >= deadline) throw new Error(errorMessage);
7962
+ await access.waitFor(interval);
7963
+ }
7964
+ }
7965
+ async function readRenderedNodes(access, selector, _options = {}) {
7966
+ access.assertActive();
7967
+ const normalizedSelector = normalizeSelector(selector);
7968
+ const nodes = await access.findAll(normalizedSelector);
7969
+ return await Promise.all(nodes.map(async (node) => {
7970
+ return {
7971
+ bottom: 1,
7972
+ dataset: await node.dataset(),
7973
+ height: 1,
7974
+ id: await node.attr("id") ?? "",
7975
+ left: 0,
7976
+ right: 1,
7977
+ top: 0,
7978
+ width: 1
7979
+ };
7980
+ }));
7981
+ }
7982
+ async function readRenderedSelectorNodes(access, selectors, options = {}) {
7983
+ access.assertActive();
7984
+ const normalizedSelectors = selectors.map((selector) => String(selector || "").trim()).filter(Boolean);
7985
+ const result = {};
7986
+ for (const selector of normalizedSelectors) result[selector] = await readRenderedNodes(access, selector, options);
7987
+ return result;
7988
+ }
7989
+ async function waitForRenderedPage(access, options = {}) {
7990
+ access.assertActive();
7991
+ if (options.selector) {
7992
+ const selector = normalizeSelector(options.selector);
7993
+ return await pollUntil$1(access, async () => {
7994
+ const nodes = await readRenderedNodes(access, selector, options);
7995
+ return nodes.some((node) => matchesDataset(node, options.dataset)) ? JSON.stringify({
7996
+ nodes,
7997
+ selector
7998
+ }) : null;
7999
+ }, `Timed out waiting page rendered: selector=${selector} dataset=${JSON.stringify(options.dataset ?? {})}`, options);
8000
+ }
8001
+ return await pollUntil$1(access, async () => {
8002
+ const wxml = await access.wxml();
8003
+ const normalizedWxml = wxml.trim();
8004
+ if (options.predicate?.(wxml)) return wxml;
8005
+ if (options.text && normalizedWxml.includes(options.text)) return wxml;
8006
+ if (!options.text && !options.predicate && normalizedWxml && normalizedWxml !== "<text></text>") return wxml;
8007
+ return null;
8008
+ }, options.text ? `Timed out waiting page rendered: text=${options.text}` : options.predicate ? "Timed out waiting page rendered: predicate=true" : "Timed out waiting page rendered: non-empty wxml", options);
8009
+ }
8010
+ //#endregion
8011
+ //#region src/testing/sessionHandle/shared.ts
8012
+ const LEADING_SLASH_RE = /^\/+/;
8013
+ const DEFAULT_WAIT_TIMEOUT = 1e3;
8014
+ const DEFAULT_WAIT_INTERVAL = 10;
8015
+ function normalizeRoute(route) {
8016
+ return route.replace(LEADING_SLASH_RE, "");
8017
+ }
8018
+ function resolvePageScopeId(scopeId) {
8019
+ const pagePathIndex = scopeId.indexOf("/page/");
8020
+ return pagePathIndex >= 0 ? scopeId.slice(0, pagePathIndex) : scopeId;
8021
+ }
8022
+ function normalizeNonEmptyInput(value, label) {
8023
+ const normalizedValue = value.trim();
8024
+ if (!normalizedValue) throw new Error(`${label} must be a non-empty string in headless testing runtime.`);
8025
+ return normalizedValue;
8026
+ }
8027
+ function cloneProtocolValue(value) {
8028
+ if (!value || typeof value !== "object") return value;
8029
+ return JSON.parse(JSON.stringify(value));
8030
+ }
8031
+ async function waitForDelay(ms = 0) {
8032
+ if (ms <= 0) return;
8033
+ await new Promise((resolve) => setTimeout(resolve, ms));
8034
+ }
8035
+ async function pollUntil(check, errorMessage, options = {}) {
8036
+ const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT)) : DEFAULT_WAIT_TIMEOUT;
8037
+ const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_WAIT_INTERVAL)) : DEFAULT_WAIT_INTERVAL;
8038
+ const deadline = Date.now() + timeout;
8039
+ while (true) {
8040
+ const result = await check();
8041
+ if (result != null) return result;
8042
+ if (Date.now() >= deadline) throw new Error(errorMessage);
8043
+ await waitForDelay(interval);
8044
+ }
8045
+ }
8046
+ async function runWithTimeout(operation, timeout, message) {
8047
+ if (!Number.isFinite(timeout) || (timeout ?? 0) <= 0) return await operation();
8048
+ let timer;
8049
+ try {
8050
+ return await Promise.race([Promise.resolve().then(operation), new Promise((_resolve, reject) => {
8051
+ timer = setTimeout(() => reject(new Error(message)), Math.trunc(timeout));
8052
+ })]);
8053
+ } finally {
8054
+ if (timer) clearTimeout(timer);
8055
+ }
8056
+ }
8057
+ //#endregion
8058
+ //#region src/testing/pageHandle.ts
6818
8059
  var HeadlessTestingPageHandle = class {
8060
+ project;
8061
+ page;
8062
+ session;
6819
8063
  constructor(project, page, session) {
6820
8064
  this.project = project;
6821
8065
  this.page = page;
6822
8066
  this.session = session;
6823
8067
  }
8068
+ get path() {
8069
+ this.assertActive();
8070
+ return this.page.route;
8071
+ }
8072
+ get query() {
8073
+ this.assertActive();
8074
+ return { ...this.page.options };
8075
+ }
6824
8076
  resolveDataByPath(path) {
6825
8077
  if (!path) return this.page.data;
6826
8078
  const segments = path.split(".").filter(Boolean);
@@ -6828,36 +8080,39 @@ var HeadlessTestingPageHandle = class {
6828
8080
  for (const segment of segments) current = current?.[segment];
6829
8081
  return current;
6830
8082
  }
6831
- async pollUntil(check, errorMessage, options = {}) {
6832
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT$1)) : DEFAULT_WAIT_TIMEOUT$1;
6833
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_WAIT_INTERVAL$1)) : DEFAULT_WAIT_INTERVAL$1;
6834
- const deadline = Date.now() + timeout;
6835
- while (true) {
6836
- const result = await check();
6837
- if (result != null) return result;
6838
- if (Date.now() >= deadline) throw new Error(errorMessage);
6839
- await this.waitFor(interval);
6840
- }
8083
+ assertActive() {
8084
+ this.session?.assertActive();
6841
8085
  }
6842
8086
  createScopeHandle(component) {
6843
8087
  const scopeId = this.session?.getScopeIdForComponent(component);
6844
8088
  return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
6845
8089
  }
6846
8090
  async callMethod(methodName, ...args) {
6847
- const method = this.page[methodName];
6848
- if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${this.page.route}.`);
6849
- return await method.apply(this.page, args);
8091
+ return await this.callMethodWithOptions(methodName, {}, ...args);
8092
+ }
8093
+ async callMethodWithOptions(methodName, options = {}, ...args) {
8094
+ this.assertActive();
8095
+ const normalizedMethodName = normalizeNonEmptyInput(methodName, "Page method name");
8096
+ return await runWithTimeout(async () => {
8097
+ this.session?.renderCurrentPage();
8098
+ const method = this.page[normalizedMethodName];
8099
+ if (typeof method !== "function") throw new TypeError(`Method "${normalizedMethodName}" does not exist on headless page ${this.page.route}.`);
8100
+ return cloneProtocolValue(await method.apply(this.page, args));
8101
+ }, options.timeout, `Timed out calling page method "${normalizedMethodName}" in headless testing runtime.`);
6850
8102
  }
6851
8103
  async data(path) {
6852
- return this.resolveDataByPath(path);
8104
+ this.assertActive();
8105
+ return cloneProtocolValue(this.resolveDataByPath(path));
6853
8106
  }
6854
8107
  async selectComponent(selector) {
8108
+ this.assertActive();
6855
8109
  const normalizedSelector = selector.trim();
6856
8110
  if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
6857
8111
  const component = this.page.selectComponent?.(normalizedSelector) ?? null;
6858
8112
  return this.createScopeHandle(component);
6859
8113
  }
6860
8114
  async selectAllComponents(selector) {
8115
+ this.assertActive();
6861
8116
  const normalizedSelector = selector.trim();
6862
8117
  if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
6863
8118
  return (this.page.selectAllComponents?.(normalizedSelector) ?? []).map((component) => this.createScopeHandle(component)).filter((handle) => Boolean(handle));
@@ -6867,24 +8122,13 @@ var HeadlessTestingPageHandle = class {
6867
8122
  await new Promise((resolve) => setTimeout(resolve, ms));
6868
8123
  }
6869
8124
  async $(selector) {
6870
- const tree = this.session?.getCurrentPages().includes(this.page) ? this.session.renderCurrentPage() : renderPageTree(this.project, this.page);
6871
- const root = new HeadlessTestingNodeHandle(tree.root.type === "root" ? tree.root.children?.[0] ?? tree.root : tree.root, {
6872
- callMethod: (scopeId, methodName, event) => {
6873
- if (this.session?.getCurrentPages().includes(this.page)) return this.session.callScopeMethod(scopeId, methodName, event);
6874
- return this.callMethod(methodName, event);
6875
- },
8125
+ this.assertActive();
8126
+ const root = createPageRootNodeHandle({
8127
+ assertActive: () => this.assertActive(),
6876
8128
  createPageHandle: () => this,
6877
- createScopeHandle: (scopeId) => {
6878
- if (!this.session) throw new Error("Scope handles are not available without an active headless testing session.");
6879
- if (!scopeId) return null;
6880
- return new HeadlessTestingScopeHandle(scopeId, this.project, this.session);
6881
- },
6882
- ownerScopeId: (scopeId) => {
6883
- if (!this.session || !scopeId) return null;
6884
- if (this.session.getScopeSnapshot(scopeId)?.type !== "component") return null;
6885
- const owner = this.session.selectOwnerComponent(scopeId);
6886
- return this.session.getScopeIdForComponent(owner);
6887
- }
8129
+ page: this.page,
8130
+ project: this.project,
8131
+ session: this.session
6888
8132
  });
6889
8133
  if (selector === "page") return root;
6890
8134
  return await root.$(selector);
@@ -6895,71 +8139,75 @@ var HeadlessTestingPageHandle = class {
6895
8139
  if (selector === "page") return [root];
6896
8140
  return await root.$$(selector);
6897
8141
  }
8142
+ async renderedNodes(selector, options = {}) {
8143
+ return await readRenderedNodes(this.renderedAccess(), selector, options);
8144
+ }
8145
+ async renderedSelectorNodes(selectors, options = {}) {
8146
+ return await readRenderedSelectorNodes(this.renderedAccess(), selectors, options);
8147
+ }
8148
+ async waitForRendered(options = {}) {
8149
+ return await waitForRenderedPage(this.renderedAccess(), options);
8150
+ }
6898
8151
  async waitForSelector(selector, options = {}) {
6899
- const normalizedSelector = selector.trim();
6900
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
6901
- if ((options.state ?? "attached") === "detached") {
6902
- await this.pollUntil(async () => await this.$(normalizedSelector) ? null : true, `Timed out waiting for selector "${normalizedSelector}" to become detached in headless testing runtime.`, options);
6903
- return null;
6904
- }
6905
- return await this.pollUntil(async () => await this.$(normalizedSelector), `Timed out waiting for selector "${normalizedSelector}" to appear in headless testing runtime.`, options);
8152
+ return await waitForPageSelector(this.waitAccess(), selector, options);
6906
8153
  }
6907
8154
  async waitForComponent(selector, options = {}) {
6908
- const normalizedSelector = selector.trim();
6909
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
6910
- return await this.pollUntil(async () => await this.selectComponent(normalizedSelector), `Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`, options);
8155
+ return await waitForPageComponent(this.waitAccess(), selector, options);
6911
8156
  }
6912
8157
  async waitForComponents(selector, count = 1, options = {}) {
6913
- const normalizedSelector = selector.trim();
6914
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
6915
- const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
6916
- return await this.pollUntil(async () => {
6917
- const components = await this.selectAllComponents(normalizedSelector);
6918
- return components.length >= normalizedCount ? components : null;
6919
- }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
8158
+ return await waitForPageComponents(this.waitAccess(), selector, count, options);
6920
8159
  }
6921
8160
  async waitForText(text, options = {}) {
6922
- const normalizedText = text.trim();
6923
- if (!normalizedText) throw new Error("Text must be a non-empty string in headless testing runtime.");
6924
- return await this.pollUntil(async () => {
6925
- return (await this.wxml()).includes(normalizedText) ? normalizedText : null;
6926
- }, `Timed out waiting for text "${normalizedText}" in headless testing runtime.`, options);
8161
+ return await waitForPageText(this.waitAccess(), text, options);
6927
8162
  }
6928
8163
  async waitForTextGone(text, options = {}) {
6929
- const normalizedText = text.trim();
6930
- if (!normalizedText) throw new Error("Text must be a non-empty string in headless testing runtime.");
6931
- await this.pollUntil(async () => {
6932
- return (await this.wxml()).includes(normalizedText) ? null : true;
6933
- }, `Timed out waiting for text "${normalizedText}" to disappear in headless testing runtime.`, options);
8164
+ await waitForPageTextGone(this.waitAccess(), text, options);
6934
8165
  }
6935
8166
  async waitForData(path, matcher, options = {}) {
6936
- const normalizedPath = path.trim();
6937
- if (!normalizedPath) throw new Error("Data path must be a non-empty string in headless testing runtime.");
6938
8167
  const hasMatcher = arguments.length >= 2;
6939
- return await this.pollUntil(async () => {
6940
- const value = this.resolveDataByPath(normalizedPath);
6941
- if (typeof matcher === "function") return matcher(value) ? value : null;
6942
- if (hasMatcher) return Object.is(value, matcher) ? value : null;
6943
- return value === void 0 ? null : value;
6944
- }, `Timed out waiting for data "${normalizedPath}" in headless testing runtime.`, options);
8168
+ return await waitForPageData(this.waitAccess(), path, matcher, hasMatcher, options);
6945
8169
  }
6946
8170
  async wxml() {
8171
+ this.assertActive();
6947
8172
  return this.session?.getCurrentPages().includes(this.page) ? this.session.renderCurrentPage().wxml : renderPageTree(this.project, this.page).wxml;
6948
8173
  }
8174
+ async snapshot() {
8175
+ this.assertActive();
8176
+ const tree = this.session?.getCurrentPages().includes(this.page) ? this.session.renderCurrentPage() : renderPageTree(this.project, this.page);
8177
+ const rootNode = tree.root.type === "root" ? tree.root.children?.[0] ?? tree.root : tree.root;
8178
+ return {
8179
+ data: cloneProtocolValue(this.page.data),
8180
+ path: this.path,
8181
+ query: this.query,
8182
+ root: createLogicalNode(rootNode),
8183
+ wxml: tree.wxml
8184
+ };
8185
+ }
8186
+ renderedAccess() {
8187
+ return {
8188
+ assertActive: () => this.assertActive(),
8189
+ findAll: async (selector) => await this.$$(selector),
8190
+ waitFor: async (ms) => await this.waitFor(ms),
8191
+ wxml: async () => await this.wxml()
8192
+ };
8193
+ }
8194
+ waitAccess() {
8195
+ return {
8196
+ data: async (path) => await this.data(path),
8197
+ findOne: async (selector) => await this.$(selector),
8198
+ selectComponent: async (selector) => await this.selectComponent(selector),
8199
+ selectComponents: async (selector) => await this.selectAllComponents(selector),
8200
+ waitFor: async (ms) => await this.waitFor(ms),
8201
+ wxml: async () => await this.wxml()
8202
+ };
8203
+ }
6949
8204
  };
6950
8205
  //#endregion
6951
- //#region src/testing/sessionHandle.ts
6952
- const LEADING_SLASH_RE = /^\/+/;
6953
- const DEFAULT_WAIT_TIMEOUT = 1e3;
6954
- const DEFAULT_WAIT_INTERVAL = 10;
6955
- function normalizeRoute(route) {
6956
- return route.replace(LEADING_SLASH_RE, "");
6957
- }
6958
- function resolvePageScopeId(scopeId) {
6959
- const pagePathIndex = scopeId.indexOf("/page/");
6960
- return pagePathIndex >= 0 ? scopeId.slice(0, pagePathIndex) : scopeId;
6961
- }
8206
+ //#region src/testing/sessionHandle/scope.ts
6962
8207
  var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
8208
+ scopeId;
8209
+ project;
8210
+ session;
6963
8211
  constructor(scopeId, project, session) {
6964
8212
  this.scopeId = scopeId;
6965
8213
  this.project = project;
@@ -6970,8 +8218,7 @@ var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
6970
8218
  return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
6971
8219
  }
6972
8220
  async callMethod(methodName, ...args) {
6973
- const normalizedMethodName = methodName.trim();
6974
- if (!normalizedMethodName) throw new Error("Method name must be a non-empty string in headless testing runtime.");
8221
+ const normalizedMethodName = normalizeNonEmptyInput(methodName, "Method name");
6975
8222
  return this.session.callScopeMethodDirect(this.scopeId, normalizedMethodName, ...args);
6976
8223
  }
6977
8224
  async snapshot() {
@@ -6988,122 +8235,110 @@ var HeadlessTestingScopeHandle = class HeadlessTestingScopeHandle {
6988
8235
  return this.createScopeHandle(this.session.selectOwnerComponent(this.scopeId));
6989
8236
  }
6990
8237
  async waitForOwnerComponent(options = {}) {
6991
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
6992
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
6993
- const deadline = Date.now() + timeout;
6994
- while (true) {
6995
- const owner = await this.ownerComponent();
6996
- if (owner) return owner;
6997
- if (Date.now() >= deadline) throw new Error("Timed out waiting for owner component in headless testing runtime.");
6998
- await new Promise((resolve) => setTimeout(resolve, interval));
6999
- }
8238
+ return await pollUntil(async () => await this.ownerComponent(), "Timed out waiting for owner component in headless testing runtime.", options);
7000
8239
  }
7001
8240
  async selectComponent(selector) {
7002
- const normalizedSelector = selector.trim();
7003
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
8241
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7004
8242
  const component = this.session.selectComponentWithin(this.scopeId, normalizedSelector);
7005
8243
  return this.createScopeHandle(component);
7006
8244
  }
7007
8245
  async selectAllComponents(selector) {
7008
- const normalizedSelector = selector.trim();
7009
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
8246
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7010
8247
  return this.session.selectAllComponentsWithin(this.scopeId, normalizedSelector).map((component) => this.createScopeHandle(component)).filter((handle) => Boolean(handle));
7011
8248
  }
7012
8249
  async waitForComponent(selector, options = {}) {
7013
- const normalizedSelector = selector.trim();
7014
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7015
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
7016
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
7017
- const deadline = Date.now() + timeout;
7018
- while (true) {
7019
- const component = await this.selectComponent(normalizedSelector);
7020
- if (component) return component;
7021
- if (Date.now() >= deadline) throw new Error(`Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`);
7022
- await new Promise((resolve) => setTimeout(resolve, interval));
7023
- }
8250
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
8251
+ return await pollUntil(async () => await this.selectComponent(normalizedSelector), `Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`, options);
7024
8252
  }
7025
8253
  async waitForComponents(selector, count = 1, options = {}) {
7026
- const normalizedSelector = selector.trim();
7027
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
8254
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7028
8255
  const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
7029
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? 1e3)) : 1e3;
7030
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? 10)) : 10;
7031
- const deadline = Date.now() + timeout;
7032
- while (true) {
8256
+ return await pollUntil(async () => {
7033
8257
  const components = await this.selectAllComponents(normalizedSelector);
7034
- if (components.length >= normalizedCount) return components;
7035
- if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`);
7036
- await new Promise((resolve) => setTimeout(resolve, interval));
7037
- }
8258
+ return components.length >= normalizedCount ? components : null;
8259
+ }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
7038
8260
  }
7039
8261
  };
8262
+ //#endregion
8263
+ //#region src/testing/sessionHandle/index.ts
7040
8264
  var HeadlessTestingSessionHandle = class {
8265
+ project;
8266
+ session;
7041
8267
  constructor(project, session) {
7042
8268
  this.project = project;
7043
8269
  this.session = session;
7044
8270
  }
7045
- async waitFor(ms = 0) {
7046
- if (ms <= 0) return;
7047
- await new Promise((resolve) => setTimeout(resolve, ms));
7048
- }
7049
- async pollUntil(check, errorMessage, options = {}) {
7050
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT)) : DEFAULT_WAIT_TIMEOUT;
7051
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_WAIT_INTERVAL)) : DEFAULT_WAIT_INTERVAL;
7052
- const deadline = Date.now() + timeout;
7053
- while (true) {
7054
- const result = await check();
7055
- if (result != null) return result;
7056
- if (Date.now() >= deadline) throw new Error(errorMessage);
7057
- await this.waitFor(interval);
7058
- }
8271
+ async close() {
8272
+ this.session.close();
7059
8273
  }
7060
- async close() {}
7061
8274
  async currentPage() {
8275
+ this.session.assertActive();
7062
8276
  const current = this.session.getCurrentPages().at(-1);
7063
8277
  return current ? new HeadlessTestingPageHandle(this.project, current, this.session) : null;
7064
8278
  }
7065
8279
  async getCurrentPages() {
8280
+ this.session.assertActive();
7066
8281
  return this.session.getCurrentPages().map((page) => new HeadlessTestingPageHandle(this.project, page, this.session));
7067
8282
  }
8283
+ async callWxMethod(methodName, ...args) {
8284
+ return await this.callWxMethodWithOptions(methodName, {}, ...args);
8285
+ }
8286
+ async callWxMethodWithOptions(methodName, options = {}, ...args) {
8287
+ const normalizedMethodName = normalizeNonEmptyInput(methodName, "wx method name");
8288
+ return await runWithTimeout(() => this.session.callWxMethod(normalizedMethodName, ...args), options.timeout, `Timed out calling wx.${normalizedMethodName} in headless testing runtime.`);
8289
+ }
7068
8290
  async scopeSnapshot(scopeId) {
7069
- const normalizedScopeId = scopeId.trim();
7070
- if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in headless testing runtime.");
8291
+ const normalizedScopeId = normalizeNonEmptyInput(scopeId, "Scope id");
7071
8292
  return this.session.getScopeSnapshot(normalizedScopeId);
7072
8293
  }
7073
8294
  async selectComponent(selector) {
7074
- const normalizedSelector = selector.trim();
7075
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
8295
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7076
8296
  const component = this.session.selectComponent(normalizedSelector);
7077
8297
  const scopeId = this.session.getScopeIdForComponent(component);
7078
8298
  return scopeId ? new HeadlessTestingScopeHandle(scopeId, this.project, this.session) : null;
7079
8299
  }
7080
8300
  async selectAllComponents(selector) {
7081
- const normalizedSelector = selector.trim();
7082
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
8301
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7083
8302
  return this.session.selectAllComponents(normalizedSelector).map((component) => this.session.getScopeIdForComponent(component)).filter((scopeId) => Boolean(scopeId)).map((scopeId) => new HeadlessTestingScopeHandle(scopeId, this.project, this.session));
7084
8303
  }
7085
8304
  async waitForComponent(selector, options = {}) {
7086
- const normalizedSelector = selector.trim();
7087
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7088
- return await this.pollUntil(async () => await this.selectComponent(normalizedSelector), `Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`, options);
8305
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
8306
+ return await pollUntil(async () => await this.selectComponent(normalizedSelector), `Timed out waiting for component "${normalizedSelector}" in headless testing runtime.`, options);
7089
8307
  }
7090
8308
  async waitForComponents(selector, count = 1, options = {}) {
7091
- const normalizedSelector = selector.trim();
7092
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
8309
+ const normalizedSelector = normalizeNonEmptyInput(selector, "Selector");
7093
8310
  const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
7094
- return await this.pollUntil(async () => {
8311
+ return await pollUntil(async () => {
7095
8312
  const components = await this.selectAllComponents(normalizedSelector);
7096
8313
  return components.length >= normalizedCount ? components : null;
7097
8314
  }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
7098
8315
  }
7099
8316
  async reLaunch(route) {
7100
- const page = this.session.reLaunch(route);
8317
+ this.session.callWxMethod("reLaunch", { url: route });
8318
+ const page = this.session.getCurrentPages().at(-1);
8319
+ if (!page) throw new Error(`Failed to reLaunch route "${route}" through the headless wx runtime.`);
7101
8320
  return new HeadlessTestingPageHandle(this.project, page, this.session);
7102
8321
  }
8322
+ async navigateTo(route) {
8323
+ this.session.callWxMethod("navigateTo", { url: route });
8324
+ return await this.requireCurrentPage("navigateTo", route);
8325
+ }
8326
+ async redirectTo(route) {
8327
+ this.session.callWxMethod("redirectTo", { url: route });
8328
+ return await this.requireCurrentPage("redirectTo", route);
8329
+ }
8330
+ async navigateBack(delta = 1) {
8331
+ this.session.callWxMethod("navigateBack", { delta });
8332
+ return await this.currentPage();
8333
+ }
8334
+ async switchTab(route) {
8335
+ this.session.callWxMethod("switchTab", { url: route });
8336
+ return await this.requireCurrentPage("switchTab", route);
8337
+ }
7103
8338
  async waitForCurrentPage(route, options = {}) {
7104
8339
  const normalizedRoute = route?.trim();
7105
8340
  if (normalizedRoute != null && !normalizedRoute) throw new Error("Route must be a non-empty string in headless testing runtime.");
7106
- return await this.pollUntil(async () => {
8341
+ return await pollUntil(async () => {
7107
8342
  const currentPageInstance = this.session.getCurrentPages().at(-1);
7108
8343
  if (!currentPageInstance) return null;
7109
8344
  const current = new HeadlessTestingPageHandle(this.project, currentPageInstance, this.session);
@@ -7127,6 +8362,11 @@ var HeadlessTestingSessionHandle = class {
7127
8362
  async triggerRouteDone(options) {
7128
8363
  this.session.triggerRouteDone(options);
7129
8364
  }
8365
+ async requireCurrentPage(methodName, route) {
8366
+ const page = await this.currentPage();
8367
+ if (!page) throw new Error(`Failed to ${methodName} route "${route}" through the headless wx runtime.`);
8368
+ return page;
8369
+ }
7130
8370
  };
7131
8371
  //#endregion
7132
8372
  //#region src/testing/launch.ts
@@ -7136,4 +8376,4 @@ async function launch(options) {
7136
8376
  return new HeadlessTestingSessionHandle(session.project, session);
7137
8377
  }
7138
8378
  //#endregion
7139
- export { BrowserHeadlessSession, HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingScopeHandle, HeadlessTestingSessionHandle, cloneValue, coerceComponentPropertyValue, createAppInstance, createBrowserHeadlessSession, createBrowserModuleLoader, createBrowserProject, createBrowserVirtualFiles, createBrowserVirtualFilesFromDirectory, createComponentInstance, createHeadlessSession, createHeadlessWx, createHeadlessWxState, createHostRegistries, createPageInstance, createProjectDescriptor, executeSelectorQueryRequests, hasBrowserVirtualFile, launch, loadProject, normalizeBrowserFilePath, normalizeComponentPropertyValue, querySelectorAll, readBrowserVirtualFile, registerAppDefinition, registerComponentDefinition, registerPageDefinition, renderBrowserPageTree, renderPageTree, renderRuntimePageTree, resolveRoutesFromAppConfig, resolveSelectorQueryScopeRoot, resolveSelectorScrollTop, runComponentLifecycle, runComponentObservers, runComponentPageLifetime };
8379
+ export { BrowserHeadlessSession, HeadlessSession, HeadlessTestingNodeHandle, HeadlessTestingPageHandle, HeadlessTestingScopeHandle, HeadlessTestingSessionHandle, RuntimeDiagnostics, RuntimeKernel, RuntimeScheduler, cloneValue, coerceComponentPropertyValue, collectMiniProgramEventBindings, createAppInstance, createArtifactProject, createBrowserHeadlessSession, createBrowserModuleLoader, createBrowserProject, createBrowserVirtualFiles, createBrowserVirtualFilesFromDirectory, createComponentInstance, createFileSystemArtifactSource, createHeadlessSession, createHeadlessUniEventBus, createHeadlessWx, createHeadlessWxState, createHostRegistries, createLogicalNode, createMemoryArtifactSource, createOverlayArtifactSource, createPageInstance, createProjectDescriptor, executeSelectorQueryRequests, hasBrowserVirtualFile, hasComponentPropertyValueChanged, launch, loadProject, normalizeBrowserFilePath, normalizeComponentPropertyValue, querySelectorAll, readBrowserVirtualFile, readRenderedNodes, readRenderedSelectorNodes, registerAppDefinition, registerComponentDefinition, registerExportedComponentDefinition, registerPageDefinition, renderBrowserPageTree, renderPageTree, renderRuntimePageTree, resolveMiniProgramEventBinding, resolveRoutesFromAppConfig, resolveSelectorQueryScopeRoot, resolveSelectorScrollTop, runComponentLifecycle, runComponentObservers, runComponentPageLifetime, waitForPageComponent, waitForPageComponents, waitForPageData, waitForPageSelector, waitForPageText, waitForPageTextGone, waitForRenderedPage, wechat };