@mpcore/simulator 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,9 @@
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
@@ -77,6 +79,62 @@ function registerComponentDefinition(registries, definition) {
77
79
  registries.components.set(id, definition);
78
80
  return definition;
79
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
+ }
80
138
  //#endregion
81
139
  //#region src/host/wx/index.ts
82
140
  function invokeWxApi(operation, option) {
@@ -101,6 +159,11 @@ function resolveCapabilityValue(source, schema) {
101
159
  return current;
102
160
  }
103
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
+ };
104
167
  const capabilityTree = {
105
168
  canIUse: true,
106
169
  canvasToTempFilePath: true,
@@ -145,6 +208,17 @@ function createHeadlessWx(driver) {
145
208
  type: true,
146
209
  width: true
147
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,
148
222
  getFileInfo: { return: {
149
223
  digest: true,
150
224
  errMsg: true,
@@ -181,6 +255,17 @@ function createHeadlessWx(driver) {
181
255
  platform: true,
182
256
  version: true
183
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
+ } },
184
269
  getEnterOptionsSync: { return: {
185
270
  path: true,
186
271
  query: true,
@@ -268,6 +353,7 @@ function createHeadlessWx(driver) {
268
353
  windowHeight: true,
269
354
  windowWidth: true
270
355
  } },
356
+ loadFontFace: { return: { errMsg: true } },
271
357
  hideLoading: true,
272
358
  hideToast: true,
273
359
  downloadFile: true,
@@ -284,6 +370,7 @@ function createHeadlessWx(driver) {
284
370
  saveVideoToPhotosAlbum: true,
285
371
  removeStorage: true,
286
372
  removeStorageSync: true,
373
+ rpx2px: true,
287
374
  request: true,
288
375
  saveFile: true,
289
376
  setBackgroundColor: true,
@@ -311,9 +398,11 @@ function createHeadlessWx(driver) {
311
398
  uploadFile: true,
312
399
  removeTabBarBadge: true,
313
400
  setTabBarBadge: true,
314
- updateShareMenu: true
401
+ updateShareMenu: true,
402
+ upx2px: true
315
403
  };
316
404
  return {
405
+ ...eventBus,
317
406
  canIUse: (schema) => typeof schema === "string" && schema.trim() !== "" && resolveCapabilityValue(capabilityTree, schema.trim()) != null,
318
407
  canvasToTempFilePath: (option) => invokeWxApi(() => driver.canvasToTempFilePath(option), option),
319
408
  chooseImage: (option) => invokeWxApi(() => driver.chooseImage(option ?? {}), option),
@@ -356,6 +445,16 @@ function createHeadlessWx(driver) {
356
445
  if (callback) callbacks.push(callback);
357
446
  return query;
358
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
+ },
359
458
  scrollOffset: (callback) => {
360
459
  requests.push({
361
460
  fields: { scrollOffset: true },
@@ -387,12 +486,20 @@ function createHeadlessWx(driver) {
387
486
  getEnterOptionsSync: () => driver.getEnterOptionsSync(),
388
487
  getFileInfo: (option) => invokeWxApi(() => driver.getFileInfo(option), option),
389
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
+ },
390
496
  getVideoInfo: (option) => invokeWxApi(() => driver.getVideoInfo(option), option),
391
497
  getFileSystemManager: () => driver.getFileSystemManager(),
392
498
  getSavedFileInfo: (option) => invokeWxApi(() => driver.getSavedFileInfo(option), option),
393
499
  getSavedFileList: (option) => invokeWxApi(() => driver.getSavedFileList(option), option),
394
500
  getAppBaseInfo: (option) => invokeWxApi(() => driver.getAppBaseInfoSync(), option),
395
501
  getAppBaseInfoSync: () => driver.getAppBaseInfoSync(),
502
+ getDeviceInfo: () => driver.getDeviceInfo(),
396
503
  getLaunchOptionsSync: () => driver.getLaunchOptionsSync(),
397
504
  getClipboardData: (option) => invokeWxApi(() => driver.getClipboardData(), option),
398
505
  getMenuButtonBoundingClientRect: () => driver.getMenuButtonBoundingClientRect(),
@@ -408,6 +515,10 @@ function createHeadlessWx(driver) {
408
515
  getSystemInfoSync: () => driver.getSystemInfoSync(),
409
516
  getWindowInfo: (option) => invokeWxApi(() => driver.getWindowInfoSync(), option),
410
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),
411
522
  hideLoading: (option) => invokeWxApi(() => driver.hideLoading(), option),
412
523
  hideToast: () => driver.hideToast(),
413
524
  downloadFile: (option) => driver.downloadFile(option),
@@ -439,6 +550,7 @@ function createHeadlessWx(driver) {
439
550
  return { errMsg: "removeStorage:ok" };
440
551
  }, option),
441
552
  removeStorageSync: (key) => driver.removeStorageSync(key),
553
+ rpx2px,
442
554
  request: (option) => driver.request(option),
443
555
  saveFile: (option) => invokeWxApi(() => driver.saveFile(option), option),
444
556
  setBackgroundColor: (option) => invokeWxApi(() => driver.setBackgroundColor(option), option),
@@ -471,7 +583,8 @@ function createHeadlessWx(driver) {
471
583
  uploadFile: (option) => driver.uploadFile(option),
472
584
  removeTabBarBadge: (option) => invokeWxApi(() => driver.removeTabBarBadge(option), option),
473
585
  setTabBarBadge: (option) => invokeWxApi(() => driver.setTabBarBadge(option), option),
474
- updateShareMenu: (option) => invokeWxApi(() => driver.updateShareMenu(option ?? {}), option)
586
+ updateShareMenu: (option) => invokeWxApi(() => driver.updateShareMenu(option ?? {}), option),
587
+ upx2px: rpx2px
475
588
  };
476
589
  }
477
590
  //#endregion
@@ -512,7 +625,7 @@ function resolveRequiredModulePath$1(files, importer, request) {
512
625
  for (const candidate of candidates) if (hasBrowserVirtualFile(files, candidate)) return candidate;
513
626
  throw createRequireNotFoundError$1(request, importer);
514
627
  }
515
- function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver) {
628
+ function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, kernel, globals) {
516
629
  const wx = createHeadlessWx(wxDriver);
517
630
  return {
518
631
  App(definition) {
@@ -531,50 +644,64 @@ function createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver)
531
644
  return registerPageDefinition(registries, definition);
532
645
  },
533
646
  URLSearchParams,
534
- clearInterval,
535
- clearTimeout,
536
- console,
647
+ clearInterval: (handle) => kernel.scheduler.clearInterval(handle),
648
+ clearTimeout: (handle) => kernel.scheduler.clearTimeout(handle),
649
+ console: kernel.diagnostics.createConsole(),
537
650
  getApp,
538
651
  getCurrentPages,
539
652
  globalThis: void 0,
540
653
  require: void 0,
541
- setInterval,
542
- setTimeout,
543
- wx
654
+ setInterval: kernel.scheduler.setInterval.bind(kernel.scheduler),
655
+ setTimeout: kernel.scheduler.setTimeout.bind(kernel.scheduler),
656
+ wx,
657
+ ...globals
544
658
  };
545
659
  }
546
- function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, wxDriver) {
660
+ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, wxDriver, options) {
547
661
  const moduleCache = /* @__PURE__ */ new Map();
548
- const executionContext = createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver);
662
+ const executionContext = createExecutionContext$1(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {});
549
663
  executionContext.globalThis = executionContext;
550
664
  function executeModule(filePath, loadContext) {
551
665
  const resolvedPath = normalize(filePath);
552
666
  const cached = moduleCache.get(resolvedPath);
553
- if (cached) return cached.exports;
667
+ if (cached) return cached;
554
668
  const source = readBrowserVirtualFile(files, resolvedPath);
555
- if (typeof source !== "string") throw new Error(`Missing virtual module in browser simulator runtime: ${resolvedPath}`);
556
- 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
+ };
557
674
  moduleCache.set(resolvedPath, module);
675
+ const registeredDefinitionsBefore = new Set(registries.components.values());
676
+ const requiredComponentDefinitions = [];
558
677
  const previousLoadContext = registries.currentLoadContext;
559
678
  registries.currentLoadContext = loadContext;
560
- const localRequire = (request) => {
679
+ const localRequire = ((request) => {
561
680
  const requiredPath = resolveRequiredModulePath$1(files, resolvedPath, request);
562
681
  if (requiredPath.endsWith(".json")) {
563
682
  const content = readBrowserVirtualFile(files, requiredPath);
564
- 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}`);
565
684
  return JSON.parse(content);
566
685
  }
567
- return executeModule(requiredPath, null);
568
- };
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));
569
691
  try {
570
692
  const contextEntries = Object.entries(executionContext);
571
693
  new Function(...contextEntries.map(([key]) => key), "exports", "module", "require", "__filename", "__dirname", source)(...contextEntries.map(([, value]) => value), module.exports, module, localRequire, resolvedPath, dirname(resolvedPath));
572
- 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;
573
697
  } finally {
574
698
  registries.currentLoadContext = previousLoadContext;
575
699
  }
576
700
  }
577
701
  return {
702
+ close() {
703
+ moduleCache.clear();
704
+ },
578
705
  executeAppModule(filePath) {
579
706
  executeModule(filePath, { kind: "app" });
580
707
  if (!registries.appDefinition) throw new Error(`App() was not registered while executing ${normalize(filePath)} in browser simulator runtime.`);
@@ -590,17 +717,172 @@ function createBrowserModuleLoader(files, registries, getCurrentPages, getApp, w
590
717
  return definition;
591
718
  },
592
719
  executeComponentModule(filePath, id) {
593
- executeModule(filePath, {
720
+ const loadedModule = executeModule(filePath, {
594
721
  kind: "component",
595
722
  route: id
596
723
  });
597
- const definition = registries.components.get(id);
724
+ const definition = registries.components.get(id) ?? registerExportedComponentDefinition(registries, id, loadedModule.exports, loadedModule.componentDefinitions.at(-1));
598
725
  if (!definition) throw new Error(`Component() was not registered for id "${id}" while executing ${normalize(filePath)}.`);
599
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);
600
761
  }
601
762
  };
602
763
  }
603
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
604
886
  //#region src/project/resolveRoutes.ts
605
887
  const LEADING_SLASH_RE$6 = /^\/+/;
606
888
  const TRAILING_SLASH_RE$1 = /\/+$/;
@@ -649,6 +931,7 @@ function resolveRoutesFromAppConfig(config) {
649
931
  //#region src/project/createProjectDescriptor.ts
650
932
  function createProjectDescriptor(options) {
651
933
  return {
934
+ artifactSource: options.artifactSource ?? createFileSystemArtifactSource(),
652
935
  appConfig: options.appConfig,
653
936
  appConfigPath: options.appConfigPath,
654
937
  miniprogramRoot: options.miniprogramRoot,
@@ -678,6 +961,10 @@ function createBrowserProject(files, options = {}) {
678
961
  return createProjectDescriptor({
679
962
  appConfig,
680
963
  appConfigPath,
964
+ artifactSource: {
965
+ has: (filePath) => hasBrowserVirtualFile(files, filePath),
966
+ readText: (filePath) => readBrowserVirtualFile(files, filePath)
967
+ },
681
968
  miniprogramRoot: options.miniprogramRoot ?? ".",
682
969
  miniprogramRootPath: options.miniprogramRootPath ?? "/",
683
970
  projectPath: options.projectPath ?? "browser://simulator",
@@ -703,6 +990,19 @@ function cloneValue(value) {
703
990
  if (value && typeof value === "object") return cloneObject$1(value);
704
991
  return value;
705
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
+ }
706
1006
  function cloneRecord(value) {
707
1007
  return cloneObject$1(value);
708
1008
  }
@@ -829,11 +1129,21 @@ function normalizeComponentDefinition(definition) {
829
1129
  };
830
1130
  return mergedDefinition;
831
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
+ }
832
1141
  function normalizePropertyType(option) {
833
1142
  if (option === null) return null;
834
- if (option === String || option === Number || option === Boolean || option === Array || option === Object) return option;
1143
+ const constructor = normalizePropertyConstructor(option);
1144
+ if (constructor) return constructor;
835
1145
  if (!option || typeof option !== "object" || Array.isArray(option)) return;
836
- return option.type;
1146
+ return normalizePropertyType(option.type);
837
1147
  }
838
1148
  function resolvePropertyTypeCandidates(option) {
839
1149
  const candidates = [];
@@ -841,7 +1151,10 @@ function resolvePropertyTypeCandidates(option) {
841
1151
  if (primaryType) candidates.push(primaryType);
842
1152
  if (option && typeof option === "object" && !Array.isArray(option)) {
843
1153
  const optionalTypes = option.optionalTypes;
844
- 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
+ }
845
1158
  }
846
1159
  return candidates;
847
1160
  }
@@ -850,7 +1163,7 @@ function resolveDefaultValueByType(type) {
850
1163
  if (type === Boolean) return false;
851
1164
  if (type === String) return "";
852
1165
  if (type === Array) return [];
853
- if (type === Object) return {};
1166
+ if (type === Object) return null;
854
1167
  if (type === null) return null;
855
1168
  }
856
1169
  function matchesRuntimeType(rawValue, type) {
@@ -882,7 +1195,6 @@ function coerceComponentPropertyValue(rawValue, option) {
882
1195
  if (type === String) return rawValue == null ? "" : String(rawValue);
883
1196
  if (type === Array && Array.isArray(rawValue)) return rawValue;
884
1197
  if (type === Object && rawValue && typeof rawValue === "object" && !Array.isArray(rawValue)) return rawValue;
885
- if (type === null) return rawValue;
886
1198
  }
887
1199
  if (primaryType === Number) {
888
1200
  const nextValue = typeof rawValue === "number" ? rawValue : Number(rawValue);
@@ -895,31 +1207,36 @@ function coerceComponentPropertyValue(rawValue, option) {
895
1207
  return Boolean(rawValue);
896
1208
  }
897
1209
  if (primaryType === String) return rawValue == null ? "" : String(rawValue);
1210
+ if (fallbackCandidates.includes(null)) return rawValue;
898
1211
  return rawValue;
899
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
+ }
900
1226
  function resolveInitialProperties(definition, properties) {
901
1227
  const resolved = {};
902
1228
  const propOptions = definition.properties;
903
1229
  if (propOptions && typeof propOptions === "object" && !Array.isArray(propOptions)) for (const [key, option] of Object.entries(propOptions)) {
904
1230
  if (Object.hasOwn(properties, key)) {
905
- resolved[key] = coerceComponentPropertyValue(properties[key], option);
1231
+ resolved[key] = normalizeComponentPropertyValue(definition, key, properties[key]);
906
1232
  continue;
907
1233
  }
908
- 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);
909
1235
  else resolved[key] = cloneValue(resolveDefaultValueByType(normalizePropertyType(option)));
910
1236
  }
911
1237
  for (const [key, value] of Object.entries(properties)) if (!(key in resolved)) resolved[key] = value;
912
1238
  return resolved;
913
1239
  }
914
- function resolvePropertyDefaultValue(option) {
915
- if (!option || typeof option !== "object" || Array.isArray(option) || !("value" in option)) return;
916
- return cloneValue(option.value);
917
- }
918
- function normalizeComponentPropertyValue(definition, key, rawValue) {
919
- const option = definition.properties?.[key];
920
- if (rawValue == null) return resolvePropertyDefaultValue(option);
921
- return coerceComponentPropertyValue(rawValue, option);
922
- }
923
1240
  //#endregion
924
1241
  //#region src/runtime/componentInstance/index.ts
925
1242
  function createComponentInstance(options) {
@@ -933,7 +1250,8 @@ function createComponentInstance(options) {
933
1250
  const changedKeys = Object.keys(patch);
934
1251
  for (const [key, value] of Object.entries(patch)) assignByPath$1(instance.data, key, value);
935
1252
  runComponentObservers(definition, instance, changedKeys);
936
- callback?.();
1253
+ if (options.requestRender) options.requestRender(callback);
1254
+ else callback?.();
937
1255
  },
938
1256
  triggerEvent(eventName, detail, triggerOptions) {
939
1257
  options.triggerEvent?.(instance, eventName, detail, triggerOptions);
@@ -962,10 +1280,261 @@ function runComponentPageLifetime(instance, lifetimeName, payload) {
962
1280
  handler.call(instance, payload);
963
1281
  }
964
1282
  //#endregion
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
965
1535
  //#region src/browser/render/shared.ts
966
1536
  const TEMPLATE_INTERPOLATION_RE$2 = /\{\{([^{}]+)\}\}/g;
967
1537
  const DATASET_NAME_RE$4 = /-([a-z])/g;
968
- const BRACKET_INDEX_RE$1 = /\[(\d+)\]/g;
969
1538
  const LEADING_SLASH_RE$5 = /^\/+/;
970
1539
  const EVENT_BINDING_ATTRS$1 = [
971
1540
  "bindtap",
@@ -973,12 +1542,6 @@ const EVENT_BINDING_ATTRS$1 = [
973
1542
  "catchtap",
974
1543
  "catch:tap"
975
1544
  ];
976
- const COMPONENT_EVENT_PREFIXES$1 = [
977
- "bind:",
978
- "bind",
979
- "catch:",
980
- "catch"
981
- ];
982
1545
  const STRUCTURAL_ATTRS$1 = [
983
1546
  "wx:if",
984
1547
  "wx:elif",
@@ -1019,39 +1582,11 @@ function cloneNode$1(node) {
1019
1582
  children: node.children?.map((child) => cloneNode$1(child))
1020
1583
  };
1021
1584
  }
1022
- function parseExpressionSegments$1(expression) {
1023
- return expression.replace(BRACKET_INDEX_RE$1, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
1024
- }
1025
- function unwrapMustacheExpression$1(expression) {
1026
- const normalized = expression.trim();
1027
- if (isMustacheOnly$1(normalized)) return normalized.slice(2, -2).trim();
1028
- return normalized;
1029
- }
1030
- function resolveLiteralValue$1(expression) {
1031
- if (expression === "true") return true;
1032
- if (expression === "false") return false;
1033
- if (expression === "null") return null;
1034
- if (expression === "undefined") return;
1035
- if (expression.startsWith("\"") && expression.endsWith("\"") || expression.startsWith("'") && expression.endsWith("'")) return expression.slice(1, -1);
1036
- const numericValue = Number(expression);
1037
- if (!Number.isNaN(numericValue) && expression !== "") return numericValue;
1038
- }
1039
- function resolveValueByExpression$1(source, expression) {
1040
- const normalized = unwrapMustacheExpression$1(expression);
1041
- if (!normalized) return;
1042
- if (normalized.startsWith("!")) return !resolveValueByExpression$1(source, normalized.slice(1));
1043
- const literalValue = resolveLiteralValue$1(normalized);
1044
- if (literalValue !== void 0 || normalized === "undefined") return literalValue;
1045
- const segments = parseExpressionSegments$1(normalized);
1046
- let current = source;
1047
- for (const segment of segments) current = current?.[segment];
1048
- return current;
1049
- }
1050
1585
  function resolveValueByPath$2(source, expression) {
1051
- return resolveValueByExpression$1(source, expression) ?? "";
1586
+ return resolveTemplateExpression(source, expression) ?? "";
1052
1587
  }
1053
1588
  function resolveRawValueByPath$1(source, expression) {
1054
- return resolveValueByExpression$1(source, expression);
1589
+ return resolveTemplateExpression(source, expression);
1055
1590
  }
1056
1591
  function interpolateTemplate$2(input, data) {
1057
1592
  return input.replace(TEMPLATE_INTERPOLATION_RE$2, (_match, expression) => {
@@ -1068,6 +1603,8 @@ function parseTemplateDocument$1(templateSource) {
1068
1603
  return parseDocument(`<page>${templateSource}</page>`, {
1069
1604
  xmlMode: false,
1070
1605
  decodeEntities: false,
1606
+ lowerCaseAttributeNames: false,
1607
+ lowerCaseTags: false,
1071
1608
  recognizeSelfClosing: true
1072
1609
  });
1073
1610
  }
@@ -1138,8 +1675,9 @@ function createLoopScope$1(scope, itemName, indexName, item, index) {
1138
1675
  }
1139
1676
  //#endregion
1140
1677
  //#region src/browser/render/component.ts
1141
- function resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath, alias) {
1142
- const componentBasePath = resolveUsingComponents$1(context.files, ownerJsonPath, ownerFilePath).get(alias);
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);
1143
1681
  if (!componentBasePath) return null;
1144
1682
  const filePath = `${componentBasePath}.js`;
1145
1683
  const templatePath = `${componentBasePath}.wxml`;
@@ -1149,11 +1687,18 @@ function resolveComponentRegistryEntry$1(context, ownerJsonPath, ownerFilePath,
1149
1687
  templatePath
1150
1688
  };
1151
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 {};
1697
+ }
1698
+ }
1152
1699
  function resolveUsingComponents$1(files, ownerJsonPath, ownerFilePath) {
1153
- const ownerJson = readBrowserVirtualFile(files, ownerJsonPath);
1154
- if (typeof ownerJson !== "string") return /* @__PURE__ */ new Map();
1155
1700
  try {
1156
- const usingComponents = JSON.parse(ownerJson).usingComponents;
1701
+ const usingComponents = readComponentConfig$1(files, ownerJsonPath).usingComponents;
1157
1702
  if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
1158
1703
  const resolved = /* @__PURE__ */ new Map();
1159
1704
  for (const [alias, rawPath] of Object.entries(usingComponents)) {
@@ -1166,19 +1711,28 @@ function resolveUsingComponents$1(files, ownerJsonPath, ownerFilePath) {
1166
1711
  return /* @__PURE__ */ new Map();
1167
1712
  }
1168
1713
  }
1169
- function collectComponentEventBindings$1(hostNode) {
1170
- const eventBindings = /* @__PURE__ */ new Map();
1171
- for (const [key, value] of Object.entries(hostNode.attribs ?? {})) {
1172
- const matchedPrefix = COMPONENT_EVENT_PREFIXES$1.find((prefix) => key.startsWith(prefix));
1173
- if (!matchedPrefix) continue;
1174
- const eventName = key.slice(matchedPrefix.length);
1175
- if (!eventName) continue;
1176
- eventBindings.set(eventName, {
1177
- method: value,
1178
- stopAfter: matchedPrefix.startsWith("catch")
1179
- });
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, ""));
1180
1731
  }
1181
- return eventBindings;
1732
+ return resolved.size > 0 ? resolved : void 0;
1733
+ }
1734
+ function collectComponentEventBindings$1(hostNode) {
1735
+ return collectMiniProgramEventBindings(hostNode.attribs);
1182
1736
  }
1183
1737
  function buildComponentTrigger$1(componentScopeId, context, hostNode) {
1184
1738
  const hostDataset = collectDataset$4(hostNode);
@@ -1226,8 +1780,7 @@ function syncComponentProperties$1(instance, definition, nextProperties, binding
1226
1780
  return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
1227
1781
  });
1228
1782
  const previousSnapshot = instance.__propertySnapshots?.[key];
1229
- const deepChanged = bindingAffected && JSON.stringify(previousSnapshot) !== JSON.stringify(nextValue);
1230
- if (instance.properties[key] !== nextValue || deepChanged) {
1783
+ if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
1231
1784
  previousProperties[key] = instance.properties[key];
1232
1785
  instance.properties[key] = nextValue;
1233
1786
  changedRootKeys.push(key);
@@ -1238,7 +1791,7 @@ function syncComponentProperties$1(instance, definition, nextProperties, binding
1238
1791
  if (changedRootKeys.length === 0) return;
1239
1792
  runComponentObservers(definition, instance, changedRootKeys, previousProperties);
1240
1793
  }
1241
- function createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance) {
1794
+ function createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots) {
1242
1795
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
1243
1796
  return {
1244
1797
  alias: clonedNode.name,
@@ -1251,19 +1804,24 @@ function createComponentScope$1(clonedNode, scope, componentScopeId, componentIn
1251
1804
  return typeof method === "function" ? method : void 0;
1252
1805
  },
1253
1806
  getScopeId: () => componentScopeId,
1807
+ genericComponents,
1254
1808
  hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
1255
1809
  id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
1256
1810
  listenerScopeId: scope.getScopeId(),
1257
- ownerScopeId
1811
+ ownerScopeId,
1812
+ slots
1258
1813
  };
1259
1814
  }
1260
- function resolveComponentProperties$1(clonedNode, scope) {
1815
+ function resolveComponentProperties$1(clonedNode, scope, definition) {
1261
1816
  const nextProperties = {};
1262
1817
  const bindingExpressions = {};
1818
+ const declaredProperties = definition.properties ?? {};
1263
1819
  for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
1264
- if (key.startsWith("bind")) continue;
1265
- if (isMustacheOnly$1(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
1266
- nextProperties[key] = resolveComponentAttributeValue$1(String(value), scope);
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);
1267
1825
  }
1268
1826
  return {
1269
1827
  nextProperties,
@@ -1274,19 +1832,22 @@ function createBrowserComponentInstance(componentScopeId, context, clonedNode, c
1274
1832
  const componentInstance = createComponentInstance({
1275
1833
  definition: componentEntry.definition,
1276
1834
  properties: nextProperties,
1835
+ requestRender: (callback) => context.session.requestRender(callback),
1277
1836
  triggerEvent: buildComponentTrigger$1(componentScopeId, context, clonedNode)
1278
1837
  });
1838
+ setSelectorQueryScopeId(componentInstance, componentScopeId);
1839
+ componentInstance.is = componentEntry.filePath.replace(JS_FILE_RE$1, "");
1279
1840
  componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
1280
1841
  componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
1281
1842
  componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
1282
1843
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
1283
- componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
1844
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? context.componentCache.get(ownerScopeId) ?? null : null;
1845
+ context.componentCache.set(componentScopeId, componentInstance);
1284
1846
  runComponentLifecycle(componentInstance, "created");
1285
1847
  runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
1286
1848
  componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
1287
1849
  runComponentLifecycle(componentInstance, "attached");
1288
1850
  runComponentPageLifetime(componentInstance, "show");
1289
- context.componentCache.set(componentScopeId, componentInstance);
1290
1851
  return componentInstance;
1291
1852
  }
1292
1853
  function renderBrowserComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
@@ -1354,25 +1915,68 @@ function renderChildren$1(children, scope, context, ownerJsonPath, ownerFilePath
1354
1915
  }
1355
1916
  return renderedChildren;
1356
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
+ }
1357
1945
  function renderNodeTree$1(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
1358
1946
  const clonedNode = cloneNode$1(node);
1359
1947
  if (!isTagNode$1(clonedNode)) {
1360
1948
  applyNodeBindings$1(clonedNode, scope);
1361
1949
  return clonedNode;
1362
1950
  }
1363
- 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));
1364
1963
  if (componentEntry) {
1365
1964
  const componentScopeId = `${instancePath}/${clonedNode.name}`;
1366
1965
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
1367
- const { nextProperties, bindingExpressions } = resolveComponentProperties$1(clonedNode, scope);
1966
+ const { nextProperties, bindingExpressions } = resolveComponentProperties$1(clonedNode, scope, componentEntry.definition);
1368
1967
  let componentInstance = context.componentCache.get(componentScopeId);
1369
1968
  if (!componentInstance) componentInstance = createBrowserComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId);
1370
1969
  else syncComponentProperties$1(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
1371
1970
  seenComponentScopes.add(componentScopeId);
1372
- const componentScope = createComponentScope$1(clonedNode, scope, componentScopeId, componentInstance);
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);
1373
1974
  context.componentScopes.set(componentScopeId, componentScope);
1374
1975
  const renderedComponentRoot = renderBrowserComponentTemplate(context, componentEntry, renderNodeTree$1, componentScope, componentScopeId, seenComponentScopes);
1375
- if (renderedComponentRoot.attribs) renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
1976
+ if (renderedComponentRoot.attribs) {
1977
+ renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
1978
+ renderedComponentRoot.attribs["data-sim-scope"] = componentScopeId;
1979
+ }
1376
1980
  if (!componentInstance.__ready__) {
1377
1981
  runComponentLifecycle(componentInstance, "ready");
1378
1982
  componentInstance.__ready__ = true;
@@ -1575,6 +2179,18 @@ function createPageInstance(route, definition, options = {}, pageState = {}) {
1575
2179
  }
1576
2180
  //#endregion
1577
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
+ }
1578
2194
  function createDefaultSystemInfo() {
1579
2195
  return {
1580
2196
  SDKVersion: "0.0.0",
@@ -1583,6 +2199,20 @@ function createDefaultSystemInfo() {
1583
2199
  model: "headless-simulator",
1584
2200
  pixelRatio: 2,
1585
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
+ },
1586
2216
  screenHeight: 667,
1587
2217
  screenWidth: 375,
1588
2218
  system: "iOS 0.0.0",
@@ -1603,11 +2233,27 @@ function applyResizeToSystemInfo(systemInfo, options) {
1603
2233
  systemInfo.windowHeight = nextWindowHeight;
1604
2234
  systemInfo.screenHeight = nextWindowHeight;
1605
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
+ };
1606
2250
  return systemInfo;
1607
2251
  }
1608
2252
  function deriveWindowInfo(systemInfo) {
1609
2253
  return {
1610
2254
  pixelRatio: systemInfo.pixelRatio,
2255
+ safeArea: { ...systemInfo.safeArea },
2256
+ safeAreaInsets: { ...systemInfo.safeAreaInsets },
1611
2257
  screenHeight: systemInfo.screenHeight,
1612
2258
  screenWidth: systemInfo.screenWidth,
1613
2259
  statusBarHeight: 20,
@@ -1625,6 +2271,19 @@ function deriveAppBaseInfo(systemInfo) {
1625
2271
  version: systemInfo.version
1626
2272
  };
1627
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
+ }
1628
2287
  function deriveMenuButtonBoundingClientRect(systemInfo) {
1629
2288
  const width = 87;
1630
2289
  const height = 32;
@@ -1641,7 +2300,7 @@ function deriveMenuButtonBoundingClientRect(systemInfo) {
1641
2300
  }
1642
2301
  //#endregion
1643
2302
  //#region src/runtime/wxState.ts
1644
- const STORAGE_LIMIT_SIZE = 10 * 1024;
2303
+ const STORAGE_LIMIT_SIZE = 10240;
1645
2304
  const DEFAULT_MODAL_CANCEL_COLOR = "#000000";
1646
2305
  const DEFAULT_MODAL_CANCEL_TEXT = "取消";
1647
2306
  const DEFAULT_MODAL_CONFIRM_COLOR = "#576B95";
@@ -2122,7 +2781,11 @@ function listParentDirectories(input) {
2122
2781
  }
2123
2782
  return parents;
2124
2783
  }
2125
- function createHeadlessWxState() {
2784
+ const nativeScheduler = {
2785
+ clearTimeout,
2786
+ setTimeout
2787
+ };
2788
+ function createHeadlessWxState(scheduler = nativeScheduler, options = {}) {
2126
2789
  const actionSheetLogs = [];
2127
2790
  const actionSheetMocks = [];
2128
2791
  const downloadFileLogs = [];
@@ -2162,7 +2825,7 @@ function createHeadlessWxState() {
2162
2825
  return createNoopTask();
2163
2826
  }
2164
2827
  let completed = false;
2165
- const timer = setTimeout(() => {
2828
+ const timer = scheduler.setTimeout(() => {
2166
2829
  if (completed) return;
2167
2830
  completed = true;
2168
2831
  onSuccess(void 0);
@@ -2170,7 +2833,7 @@ function createHeadlessWxState() {
2170
2833
  return { abort() {
2171
2834
  if (completed) return;
2172
2835
  completed = true;
2173
- clearTimeout(timer);
2836
+ scheduler.clearTimeout(timer);
2174
2837
  onFail(new Error(abortMessage));
2175
2838
  } };
2176
2839
  };
@@ -2530,6 +3193,9 @@ function createHeadlessWxState() {
2530
3193
  }
2531
3194
  };
2532
3195
  return {
3196
+ close() {
3197
+ networkStatusChangeCallbacks.clear();
3198
+ },
2533
3199
  clearStorageSync() {
2534
3200
  storage.clear();
2535
3201
  },
@@ -2543,6 +3209,7 @@ function createHeadlessWxState() {
2543
3209
  };
2544
3210
  downloadFileLogs.push(logEntry);
2545
3211
  const error = /* @__PURE__ */ new Error(`No downloadFile mock matched in headless runtime: ${option.url}`);
3212
+ if (options.strictMocks) throw error;
2546
3213
  option.fail?.(error);
2547
3214
  option.complete?.();
2548
3215
  return createNoopTask();
@@ -2962,6 +3629,7 @@ function createHeadlessWxState() {
2962
3629
  };
2963
3630
  requestLogs.push(logEntry);
2964
3631
  const error = /* @__PURE__ */ new Error(`No request mock matched in headless runtime: ${normalizeMethod(option.method)} ${option.url}`);
3632
+ if (options.strictMocks) throw error;
2965
3633
  option.fail?.(error);
2966
3634
  option.complete?.();
2967
3635
  return createNoopTask();
@@ -3039,6 +3707,7 @@ function createHeadlessWxState() {
3039
3707
  const itemList = Array.isArray(option.itemList) ? option.itemList.filter((item) => typeof item === "string") : [];
3040
3708
  if (itemList.length === 0) throw new Error("showActionSheet:fail invalid itemList");
3041
3709
  const nextMock = actionSheetMocks.shift();
3710
+ if (!nextMock && options.strictMocks) throw new Error("No actionSheet mock matched in headless runtime.");
3042
3711
  if (nextMock?.cancel) {
3043
3712
  actionSheetLogs.push({ itemList: [...itemList] });
3044
3713
  throw new Error("showActionSheet:fail cancel");
@@ -3074,6 +3743,7 @@ function createHeadlessWxState() {
3074
3743
  showModal(option) {
3075
3744
  const showCancel = option.showCancel !== false;
3076
3745
  const nextMock = modalMocks.shift();
3746
+ if (!nextMock && options.strictMocks) throw new Error("No modal mock matched in headless runtime.");
3077
3747
  let confirm = nextMock?.confirm ?? true;
3078
3748
  let cancel = nextMock?.cancel ?? !confirm;
3079
3749
  if (!showCancel) {
@@ -3129,6 +3799,7 @@ function createHeadlessWxState() {
3129
3799
  if (!matchedMock) {
3130
3800
  uploadFileLogs.push(logEntry);
3131
3801
  const error = /* @__PURE__ */ new Error(`No uploadFile mock matched in headless runtime: ${option.url}`);
3802
+ if (options.strictMocks) throw error;
3132
3803
  option.fail?.(error);
3133
3804
  option.complete?.();
3134
3805
  return createNoopTask();
@@ -3173,6 +3844,7 @@ function getClassList(node) {
3173
3844
  function matchesSimpleSelector(node, selector) {
3174
3845
  if (node.type !== "tag") return false;
3175
3846
  if (selector === "page") return node.name === "page";
3847
+ if (selector === "*") return true;
3176
3848
  if (selector.startsWith("#")) return node.attribs?.id === selector.slice(1);
3177
3849
  if (selector.startsWith(".")) return getClassList(node).includes(selector.slice(1));
3178
3850
  const dataAttrMatch = selector.match(DATA_ATTR_SELECTOR_RE$2);
@@ -3187,6 +3859,7 @@ function parseCompoundSelector$2(selector) {
3187
3859
  return parts.join("") === selector ? parts : [];
3188
3860
  }
3189
3861
  function matchesSelectorToken(node, selector) {
3862
+ if (selector === "*") return node.type === "tag";
3190
3863
  const simpleSelectors = parseCompoundSelector$2(selector);
3191
3864
  if (simpleSelectors.length === 0) return false;
3192
3865
  return simpleSelectors.every((simpleSelector) => matchesSimpleSelector(node, simpleSelector));
@@ -3230,21 +3903,6 @@ function collectDataset$3(node) {
3230
3903
  }
3231
3904
  return dataset;
3232
3905
  }
3233
- function resolveEventBinding$1(node, eventName) {
3234
- const normalizedEventName = eventName.trim();
3235
- if (!normalizedEventName) return null;
3236
- const bindingAttrs = [
3237
- `bind${normalizedEventName}`,
3238
- `bind:${normalizedEventName}`,
3239
- `catch${normalizedEventName}`,
3240
- `catch:${normalizedEventName}`
3241
- ];
3242
- for (const attributeName of bindingAttrs) {
3243
- const methodName = node.attribs?.[attributeName]?.trim();
3244
- if (methodName) return methodName;
3245
- }
3246
- return null;
3247
- }
3248
3906
  function createEventPayload$1(node, eventName, event) {
3249
3907
  const dataset = collectDataset$3(node);
3250
3908
  const nodeId = node.attribs?.id ?? "";
@@ -3302,50 +3960,68 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
3302
3960
  this.node = node;
3303
3961
  this.interactions = interactions;
3304
3962
  }
3963
+ assertActive() {
3964
+ this.interactions?.assertActive?.();
3965
+ }
3305
3966
  async $(selector) {
3967
+ this.assertActive();
3306
3968
  const match = querySelectorAll(this.node, selector)[0];
3307
3969
  return match ? new HeadlessTestingNodeHandle(match, this.interactions) : null;
3308
3970
  }
3309
3971
  async $$(selector) {
3972
+ this.assertActive();
3310
3973
  return querySelectorAll(this.node, selector).map((node) => new HeadlessTestingNodeHandle(node, this.interactions));
3311
3974
  }
3312
3975
  async attr(name) {
3976
+ this.assertActive();
3313
3977
  return this.node.attribs?.[name];
3314
3978
  }
3315
3979
  async dataset() {
3980
+ this.assertActive();
3316
3981
  return collectDataset$3(this.node);
3317
3982
  }
3318
3983
  async scope() {
3984
+ this.assertActive();
3319
3985
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
3320
3986
  return this.interactions.createScopeHandle(this.node.attribs?.["data-sim-scope"] ?? null);
3321
3987
  }
3322
3988
  async componentScope() {
3989
+ this.assertActive();
3323
3990
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
3324
3991
  return this.interactions.createScopeHandle(resolveComponentScopeId(this.node.attribs?.["data-sim-scope"] ?? null));
3325
3992
  }
3326
3993
  async pageScope() {
3994
+ this.assertActive();
3327
3995
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
3328
3996
  return this.interactions.createScopeHandle(resolvePageScopeId$1(this.node.attribs?.["data-sim-scope"] ?? null));
3329
3997
  }
3330
3998
  async page() {
3999
+ this.assertActive();
3331
4000
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
3332
4001
  return this.interactions.createPageHandle();
3333
4002
  }
3334
4003
  async ownerComponentScope() {
4004
+ this.assertActive();
3335
4005
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
3336
4006
  const scopeId = resolveComponentScopeId(this.node.attribs?.["data-sim-scope"] ?? null);
3337
4007
  return this.interactions.createScopeHandle(this.interactions.ownerScopeId(scopeId));
3338
4008
  }
3339
4009
  async text() {
4010
+ this.assertActive();
3340
4011
  return collectText(this.node);
3341
4012
  }
4013
+ async tagName() {
4014
+ this.assertActive();
4015
+ return this.node.type === "tag" ? this.node.name : void 0;
4016
+ }
3342
4017
  async trigger(eventName, event = {}) {
4018
+ this.assertActive();
3343
4019
  if (!this.interactions) throw new Error("Node interactions are not available for this headless testing node.");
3344
4020
  const normalizedEventName = eventName.trim();
3345
4021
  if (!normalizedEventName) throw new Error("Event name must be a non-empty string in headless testing runtime.");
3346
- const methodName = resolveEventBinding$1(this.node, normalizedEventName);
3347
- if (!methodName) throw new Error(`No ${normalizedEventName} binding was found on <${this.node.name ?? "unknown"}> in headless testing runtime.`);
3348
- 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));
3349
4025
  }
3350
4026
  async tap(event = {}) {
3351
4027
  return await this.trigger("tap", event);
@@ -3369,6 +4045,7 @@ var HeadlessTestingNodeHandle = class HeadlessTestingNodeHandle {
3369
4045
  });
3370
4046
  }
3371
4047
  async wxml() {
4048
+ this.assertActive();
3372
4049
  return serializeNode(this.node);
3373
4050
  }
3374
4051
  };
@@ -3416,7 +4093,9 @@ function serializeDomNode$1(node) {
3416
4093
  function renderPageTree(project, page) {
3417
4094
  const route = page.route.replace(LEADING_SLASH_RE$4, "");
3418
4095
  const templatePath = path.resolve(project.miniprogramRootPath, `${route}.wxml`);
3419
- 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>`, {
3420
4099
  xmlMode: false,
3421
4100
  decodeEntities: false,
3422
4101
  recognizeSelfClosing: true
@@ -3548,7 +4227,13 @@ function resolveFieldsResult(node, fields, options) {
3548
4227
  if (Array.isArray(fields.properties) && fields.properties.length > 0) Object.assign(result, pickProperties(node, fields.properties));
3549
4228
  if (Array.isArray(fields.computedStyle) && fields.computedStyle.length > 0) Object.assign(result, pickComputedStyle(node, fields.computedStyle));
3550
4229
  if (fields.context) result.context = options.resolveContext?.(node) ?? { type: "unsupported-context" };
3551
- 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
+ }
3552
4237
  return result;
3553
4238
  }
3554
4239
  function resolveViewportResult(fields, options) {
@@ -4245,21 +4930,6 @@ function collectDataset$1(node) {
4245
4930
  }
4246
4931
  return dataset;
4247
4932
  }
4248
- function resolveEventBinding(node, eventName) {
4249
- const normalizedEventName = eventName.trim();
4250
- if (!normalizedEventName) return null;
4251
- const bindingAttrs = [
4252
- `bind${normalizedEventName}`,
4253
- `bind:${normalizedEventName}`,
4254
- `catch${normalizedEventName}`,
4255
- `catch:${normalizedEventName}`
4256
- ];
4257
- for (const attributeName of bindingAttrs) {
4258
- const methodName = node.attribs?.[attributeName]?.trim();
4259
- if (methodName) return methodName;
4260
- }
4261
- return null;
4262
- }
4263
4933
  function createEventPayload(node, eventName, detail) {
4264
4934
  const dataset = collectDataset$1(node);
4265
4935
  const nodeId = node.attribs?.id ?? "";
@@ -4295,9 +4965,9 @@ function createHeadlessVideoContext(driver, videoId, scope) {
4295
4965
  const dispatch = (eventName, detail) => {
4296
4966
  const node = resolveNode();
4297
4967
  if (!node) return;
4298
- const methodName = resolveEventBinding(node, eventName);
4299
- if (!methodName) return;
4300
- 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));
4301
4971
  };
4302
4972
  return {
4303
4973
  exitFullScreen() {
@@ -4414,11 +5084,15 @@ var BrowserHeadlessSession = class {
4414
5084
  appDefinition = null;
4415
5085
  appInstance = null;
4416
5086
  moduleLoader;
5087
+ onRender;
4417
5088
  registries;
4418
5089
  currentPageInstance = null;
4419
5090
  pages = [];
4420
5091
  componentCache = /* @__PURE__ */ new Map();
4421
5092
  componentScopes = /* @__PURE__ */ new Map();
5093
+ selectorQueryScopeSnapshots = /* @__PURE__ */ new WeakMap();
5094
+ renderRequestPending = false;
5095
+ renderRequestCallbacks = [];
4422
5096
  tabBarRoutes;
4423
5097
  tabPages = /* @__PURE__ */ new Map();
4424
5098
  tabBarItems = /* @__PURE__ */ new Map();
@@ -4429,13 +5103,16 @@ var BrowserHeadlessSession = class {
4429
5103
  canvasContexts = /* @__PURE__ */ new Map();
4430
5104
  enterOptions = createAppLaunchOptions$1("", {});
4431
5105
  launchOptions = createAppLaunchOptions$1("", {});
4432
- wxState = createHeadlessWxState();
5106
+ kernel = new RuntimeKernel();
5107
+ wxState;
4433
5108
  pullDownRefreshState = {
4434
5109
  active: false,
4435
5110
  stopCalls: 0
4436
5111
  };
4437
5112
  constructor(options) {
4438
5113
  this.files = options.files;
5114
+ this.wxState = createHeadlessWxState(this.kernel.scheduler, { strictMocks: options.strictHostMocks });
5115
+ this.onRender = options.onRender;
4439
5116
  this.project = options.project ?? createBrowserProject(options.files);
4440
5117
  this.registries = createHostRegistries();
4441
5118
  const rawTabBarList = Array.isArray(this.project.appConfig.tabBar?.list) ? this.project.appConfig.tabBar.list : [];
@@ -4486,6 +5163,7 @@ var BrowserHeadlessSession = class {
4486
5163
  }
4487
5164
  }),
4488
5165
  getAppBaseInfoSync: () => deriveAppBaseInfo(this.systemInfo),
5166
+ getDeviceInfo: () => deriveDeviceInfo(this.systemInfo),
4489
5167
  getLaunchOptionsSync: () => ({
4490
5168
  ...this.launchOptions,
4491
5169
  query: { ...this.launchOptions.query },
@@ -4495,6 +5173,7 @@ var BrowserHeadlessSession = class {
4495
5173
  }
4496
5174
  }),
4497
5175
  getClipboardData: () => this.wxState.getClipboardData(),
5176
+ getLocation: () => createDefaultLocationResult(),
4498
5177
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
4499
5178
  getNetworkType: () => this.wxState.getNetworkType(),
4500
5179
  navigateBack: (option) => this.navigateBack(option?.delta),
@@ -4514,7 +5193,7 @@ var BrowserHeadlessSession = class {
4514
5193
  removeSavedFile: (option) => this.wxState.removeSavedFile(option),
4515
5194
  saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
4516
5195
  saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
4517
- nextTick: (callback) => queueMicrotask(() => callback?.()),
5196
+ nextTick: (callback) => this.kernel.scheduler.queueMicrotask(() => callback?.()),
4518
5197
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
4519
5198
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
4520
5199
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
@@ -4546,12 +5225,36 @@ var BrowserHeadlessSession = class {
4546
5225
  removeTabBarBadge: (option) => this.removeTabBarBadge(option.index),
4547
5226
  setTabBarBadge: (option) => this.setTabBarBadge(option.index, option.text),
4548
5227
  updateShareMenu: (option) => this.wxState.updateShareMenu(option)
5228
+ }, {
5229
+ globals: options.globals,
5230
+ kernel: this.kernel
4549
5231
  });
4550
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
+ }
4551
5252
  getApp() {
5253
+ this.assertActive();
4552
5254
  return this.appInstance;
4553
5255
  }
4554
5256
  getCurrentPages() {
5257
+ this.assertActive();
4555
5258
  return this.pages.slice();
4556
5259
  }
4557
5260
  getCurrentPageNavigationBarTitle() {
@@ -4634,6 +5337,9 @@ var BrowserHeadlessSession = class {
4634
5337
  getAppBaseInfo() {
4635
5338
  return deriveAppBaseInfo(this.systemInfo);
4636
5339
  }
5340
+ getDeviceInfo() {
5341
+ return deriveDeviceInfo(this.systemInfo);
5342
+ }
4637
5343
  getLaunchOptions() {
4638
5344
  return {
4639
5345
  ...this.launchOptions,
@@ -4657,6 +5363,9 @@ var BrowserHeadlessSession = class {
4657
5363
  getMenuButtonBoundingClientRect() {
4658
5364
  return deriveMenuButtonBoundingClientRect(this.systemInfo);
4659
5365
  }
5366
+ getLocation() {
5367
+ return createDefaultLocationResult();
5368
+ }
4660
5369
  getNetworkType() {
4661
5370
  return this.wxState.getNetworkType();
4662
5371
  }
@@ -4832,15 +5541,19 @@ var BrowserHeadlessSession = class {
4832
5541
  return this.getComponentScopeId(component);
4833
5542
  }
4834
5543
  selectComponent(selector) {
5544
+ this.renderCurrentPage();
4835
5545
  return this.selectComponentsWithin(null, selector)[0] ?? null;
4836
5546
  }
4837
5547
  selectAllComponents(selector) {
5548
+ this.renderCurrentPage();
4838
5549
  return this.selectComponentsWithin(null, selector);
4839
5550
  }
4840
5551
  selectComponentWithin(scopeId, selector) {
5552
+ this.renderCurrentPage();
4841
5553
  return this.selectComponentsWithin(scopeId, selector)[0] ?? null;
4842
5554
  }
4843
5555
  selectAllComponentsWithin(scopeId, selector) {
5556
+ this.renderCurrentPage();
4844
5557
  return this.selectComponentsWithin(scopeId, selector);
4845
5558
  }
4846
5559
  selectOwnerComponent(scopeId) {
@@ -4851,7 +5564,7 @@ var BrowserHeadlessSession = class {
4851
5564
  selectComponentsWithin(rootScopeId, selector) {
4852
5565
  const selectorParts = normalizeSelectorParts$1(selector);
4853
5566
  if (selectorParts.length === 0) return [];
4854
- return [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
5567
+ const matches = [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
4855
5568
  if (!candidateScopeId.includes("/")) return false;
4856
5569
  if (rootScopeId && candidateScopeId === rootScopeId) return false;
4857
5570
  if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
@@ -4864,9 +5577,12 @@ var BrowserHeadlessSession = class {
4864
5577
  currentScope = currentScope.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
4865
5578
  }
4866
5579
  return true;
4867
- }).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);
4868
5583
  }
4869
5584
  renderCurrentPage() {
5585
+ this.assertActive();
4870
5586
  const current = this.requireCurrentPage("renderCurrentPage()");
4871
5587
  const rendered = renderBrowserPageTree({
4872
5588
  changedPageKeys: current.__lastChangedKeys__ ?? [],
@@ -4878,14 +5594,35 @@ var BrowserHeadlessSession = class {
4878
5594
  session: {
4879
5595
  createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
4880
5596
  createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
5597
+ requestRender: (callback) => this.requestRender(callback),
4881
5598
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
4882
5599
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
4883
5600
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
4884
5601
  }
4885
5602
  }, current);
4886
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
+ });
4887
5610
  return rendered;
4888
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
+ }
4889
5626
  callScopeMethod(scopeId, methodName, event) {
4890
5627
  const current = this.requireCurrentPage(`scope method "${methodName}"`);
4891
5628
  this.renderCurrentPage();
@@ -4909,6 +5646,7 @@ var BrowserHeadlessSession = class {
4909
5646
  const normalizedScopeId = scopeId.trim();
4910
5647
  if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in browser simulator runtime.");
4911
5648
  const current = this.requireCurrentPage(`scope method "${methodName}"`);
5649
+ this.renderCurrentPage();
4912
5650
  if (normalizedScopeId === `page:${stripLeadingSlash$1(current.route)}`) {
4913
5651
  const method = current[methodName];
4914
5652
  if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on browser simulator page ${current.route}.`);
@@ -4963,6 +5701,7 @@ var BrowserHeadlessSession = class {
4963
5701
  });
4964
5702
  }
4965
5703
  bootstrap(launchOptions = createAppLaunchOptions$1("", {})) {
5704
+ this.assertActive();
4966
5705
  if (this.appInstance) return this.appInstance;
4967
5706
  this.launchOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
4968
5707
  this.enterOptions = createAppLaunchOptions$1(launchOptions.path, launchOptions.query);
@@ -5030,11 +5769,7 @@ var BrowserHeadlessSession = class {
5030
5769
  if (!this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.switchTab() can only open a tabBar page in browser simulator runtime: ${url}`);
5031
5770
  const current = this.currentPageInstance;
5032
5771
  const cachedTarget = this.tabPages.get(target.routeRecord.route) ?? null;
5033
- const tabItem = this.resolveTabBarItem(target.routeRecord.route);
5034
- if (current === cachedTarget && current) {
5035
- current.onTabItemTap?.(tabItem);
5036
- return current;
5037
- }
5772
+ if (current === cachedTarget && current) return current;
5038
5773
  if (current && current !== cachedTarget) {
5039
5774
  current.onHide?.();
5040
5775
  this.runPageComponentLifetime(current.route, "hide");
@@ -5059,7 +5794,6 @@ var BrowserHeadlessSession = class {
5059
5794
  nextPage.onShow?.();
5060
5795
  this.runPageComponentLifetime(nextPage.route, "show");
5061
5796
  }
5062
- nextPage.onTabItemTap?.(tabItem);
5063
5797
  return nextPage;
5064
5798
  }
5065
5799
  pageScrollTo(option) {
@@ -5074,6 +5808,7 @@ var BrowserHeadlessSession = class {
5074
5808
  session: {
5075
5809
  createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
5076
5810
  createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
5811
+ requestRender: (callback) => this.requestRender(callback),
5077
5812
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
5078
5813
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
5079
5814
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
@@ -5121,14 +5856,32 @@ var BrowserHeadlessSession = class {
5121
5856
  }
5122
5857
  executeSelectorQuery(requests, scope) {
5123
5858
  const current = this.requireCurrentPage("wx.createSelectorQuery().exec()");
5124
- 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.");
5125
- 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;
5126
5879
  return executeSelectorQueryRequests(requests, {
5127
5880
  page: current,
5128
5881
  resolveContext: (node) => {
5129
5882
  if (node.name !== "canvas") return { type: "unsupported-context" };
5130
5883
  const canvasId = node.attribs?.["canvas-id"];
5131
- 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" };
5132
5885
  },
5133
5886
  root: resolveSelectorQueryScopeRoot(renderBrowserPageTree({
5134
5887
  changedPageKeys: current.__lastChangedKeys__ ?? [],
@@ -5140,6 +5893,7 @@ var BrowserHeadlessSession = class {
5140
5893
  session: {
5141
5894
  createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
5142
5895
  createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
5896
+ requestRender: (callback) => this.requestRender(callback),
5143
5897
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
5144
5898
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
5145
5899
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
@@ -5168,6 +5922,7 @@ var BrowserHeadlessSession = class {
5168
5922
  pageInstance.onLoad?.(query);
5169
5923
  pageInstance.onShow?.();
5170
5924
  pageInstance.onReady?.();
5925
+ pageInstance.onRouteDone?.({});
5171
5926
  }
5172
5927
  isTabBarRoute(route) {
5173
5928
  return this.tabBarRoutes.has(stripLeadingSlash$1(route));
@@ -5191,12 +5946,6 @@ var BrowserHeadlessSession = class {
5191
5946
  routeRecord
5192
5947
  };
5193
5948
  }
5194
- resolveTabBarItem(route) {
5195
- const pagePath = stripLeadingSlash$1(route);
5196
- const item = this.tabBarItems.get(pagePath);
5197
- if (!item) throw new Error(`Missing tabBar metadata for route "${route}" in browser simulator runtime.`);
5198
- return { ...item };
5199
- }
5200
5949
  requireTabBarItem(index, action) {
5201
5950
  const normalizedIndex = Number.isFinite(index) ? Math.trunc(index) : NaN;
5202
5951
  const item = this.tabBarState.get(normalizedIndex);
@@ -5356,6 +6105,32 @@ function createBrowserHeadlessSession(options) {
5356
6105
  return new BrowserHeadlessSession(options);
5357
6106
  }
5358
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
5359
6134
  //#region src/project/loadProject.ts
5360
6135
  function readJsonObject$1(filePath) {
5361
6136
  try {
@@ -5418,7 +6193,6 @@ function loadProject(projectPath) {
5418
6193
  //#region src/runtime/render/shared.ts
5419
6194
  const TEMPLATE_INTERPOLATION_RE = /\{\{([^{}]+)\}\}/g;
5420
6195
  const DATASET_NAME_RE = /-([a-z])/g;
5421
- const BRACKET_INDEX_RE = /\[(\d+)\]/g;
5422
6196
  const LEADING_SLASH_RE$2 = /^\/+/;
5423
6197
  const EVENT_BINDING_ATTRS = [
5424
6198
  "bindtap",
@@ -5426,12 +6200,6 @@ const EVENT_BINDING_ATTRS = [
5426
6200
  "catchtap",
5427
6201
  "catch:tap"
5428
6202
  ];
5429
- const COMPONENT_EVENT_PREFIXES = [
5430
- "bind:",
5431
- "bind",
5432
- "catch:",
5433
- "catch"
5434
- ];
5435
6203
  const STRUCTURAL_ATTRS = [
5436
6204
  "wx:if",
5437
6205
  "wx:elif",
@@ -5472,39 +6240,11 @@ function cloneNode(node) {
5472
6240
  children: node.children?.map((child) => cloneNode(child))
5473
6241
  };
5474
6242
  }
5475
- function parseExpressionSegments(expression) {
5476
- return expression.replace(BRACKET_INDEX_RE, ".$1").split(".").map((segment) => segment.trim()).filter(Boolean);
5477
- }
5478
- function unwrapMustacheExpression(expression) {
5479
- const normalized = expression.trim();
5480
- if (isMustacheOnly(normalized)) return normalized.slice(2, -2).trim();
5481
- return normalized;
5482
- }
5483
- function resolveLiteralValue(expression) {
5484
- if (expression === "true") return true;
5485
- if (expression === "false") return false;
5486
- if (expression === "null") return null;
5487
- if (expression === "undefined") return;
5488
- if (expression.startsWith("\"") && expression.endsWith("\"") || expression.startsWith("'") && expression.endsWith("'")) return expression.slice(1, -1);
5489
- const numericValue = Number(expression);
5490
- if (!Number.isNaN(numericValue) && expression !== "") return numericValue;
5491
- }
5492
- function resolveValueByExpression(source, expression) {
5493
- const normalized = unwrapMustacheExpression(expression);
5494
- if (!normalized) return;
5495
- if (normalized.startsWith("!")) return !resolveValueByExpression(source, normalized.slice(1));
5496
- const literalValue = resolveLiteralValue(normalized);
5497
- if (literalValue !== void 0 || normalized === "undefined") return literalValue;
5498
- const segments = parseExpressionSegments(normalized);
5499
- let current = source;
5500
- for (const segment of segments) current = current?.[segment];
5501
- return current;
5502
- }
5503
6243
  function resolveValueByPath(source, expression) {
5504
- return resolveValueByExpression(source, expression) ?? "";
6244
+ return resolveTemplateExpression(source, expression) ?? "";
5505
6245
  }
5506
6246
  function resolveRawValueByPath(source, expression) {
5507
- return resolveValueByExpression(source, expression);
6247
+ return resolveTemplateExpression(source, expression);
5508
6248
  }
5509
6249
  function interpolateTemplate(input, data) {
5510
6250
  return input.replace(TEMPLATE_INTERPOLATION_RE, (_match, expression) => {
@@ -5512,13 +6252,17 @@ function interpolateTemplate(input, data) {
5512
6252
  return typeof value === "string" ? value : String(value);
5513
6253
  });
5514
6254
  }
5515
- function readTemplateSource(filePath) {
5516
- 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;
5517
6259
  }
5518
6260
  function parseTemplateDocument(templateSource) {
5519
6261
  return parseDocument(`<page>${templateSource}</page>`, {
5520
6262
  xmlMode: false,
5521
6263
  decodeEntities: false,
6264
+ lowerCaseAttributeNames: false,
6265
+ lowerCaseTags: false,
5522
6266
  recognizeSelfClosing: true
5523
6267
  });
5524
6268
  }
@@ -5589,8 +6333,9 @@ function createLoopScope(scope, itemName, indexName, item, index) {
5589
6333
  }
5590
6334
  //#endregion
5591
6335
  //#region src/runtime/render/component.ts
5592
- function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias) {
5593
- const componentBasePath = resolveUsingComponents(ownerJsonPath, ownerFilePath).get(alias);
6336
+ function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, alias, genericComponentBasePath) {
6337
+ const usingComponents = resolveUsingComponents(context.artifactSource, ownerJsonPath, ownerFilePath);
6338
+ const componentBasePath = genericComponentBasePath ?? usingComponents.get(alias);
5594
6339
  if (!componentBasePath) return null;
5595
6340
  const filePath = `${componentBasePath}.js`;
5596
6341
  const templatePath = `${componentBasePath}.wxml`;
@@ -5603,9 +6348,17 @@ function resolveComponentRegistryEntry(context, ownerJsonPath, ownerFilePath, al
5603
6348
  absoluteTemplatePath
5604
6349
  };
5605
6350
  }
5606
- function resolveUsingComponents(ownerJsonPath, ownerFilePath) {
6351
+ function readComponentConfig(artifactSource, jsonPath) {
6352
+ try {
6353
+ const source = artifactSource.readText(jsonPath);
6354
+ return source ? JSON.parse(source) : {};
6355
+ } catch {
6356
+ return {};
6357
+ }
6358
+ }
6359
+ function resolveUsingComponents(artifactSource, ownerJsonPath, ownerFilePath) {
5607
6360
  try {
5608
- const usingComponents = JSON.parse(fs.readFileSync(ownerJsonPath, "utf8")).usingComponents;
6361
+ const usingComponents = readComponentConfig(artifactSource, ownerJsonPath).usingComponents;
5609
6362
  if (!usingComponents || typeof usingComponents !== "object" || Array.isArray(usingComponents)) return /* @__PURE__ */ new Map();
5610
6363
  const resolved = /* @__PURE__ */ new Map();
5611
6364
  for (const [alias, rawPath] of Object.entries(usingComponents)) {
@@ -5618,19 +6371,28 @@ function resolveUsingComponents(ownerJsonPath, ownerFilePath) {
5618
6371
  return /* @__PURE__ */ new Map();
5619
6372
  }
5620
6373
  }
5621
- function collectComponentEventBindings(hostNode) {
5622
- const eventBindings = /* @__PURE__ */ new Map();
5623
- for (const [key, value] of Object.entries(hostNode.attribs ?? {})) {
5624
- const matchedPrefix = COMPONENT_EVENT_PREFIXES.find((prefix) => key.startsWith(prefix));
5625
- if (!matchedPrefix) continue;
5626
- const eventName = key.slice(matchedPrefix.length);
5627
- if (!eventName) continue;
5628
- eventBindings.set(eventName, {
5629
- method: value,
5630
- stopAfter: matchedPrefix.startsWith("catch")
5631
- });
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, ""));
5632
6391
  }
5633
- return eventBindings;
6392
+ return resolved.size > 0 ? resolved : void 0;
6393
+ }
6394
+ function collectComponentEventBindings(hostNode) {
6395
+ return collectMiniProgramEventBindings(hostNode.attribs);
5634
6396
  }
5635
6397
  function buildComponentTrigger(componentScopeId, context, hostNode) {
5636
6398
  const hostDataset = collectDataset(hostNode);
@@ -5678,8 +6440,7 @@ function syncComponentProperties(instance, definition, nextProperties, bindingEx
5678
6440
  return changedKey === bindingExpression || changedKey.startsWith(`${bindingExpression}.`) || changedKey.startsWith(`${bindingExpression}[`);
5679
6441
  });
5680
6442
  const previousSnapshot = instance.__propertySnapshots?.[key];
5681
- const deepChanged = bindingAffected && JSON.stringify(previousSnapshot) !== JSON.stringify(nextValue);
5682
- if (instance.properties[key] !== nextValue || deepChanged) {
6443
+ if (hasComponentPropertyValueChanged(instance.properties[key], previousSnapshot, nextValue, bindingAffected)) {
5683
6444
  previousProperties[key] = instance.properties[key];
5684
6445
  instance.properties[key] = nextValue;
5685
6446
  changedRootKeys.push(key);
@@ -5690,7 +6451,7 @@ function syncComponentProperties(instance, definition, nextProperties, bindingEx
5690
6451
  if (changedRootKeys.length === 0) return;
5691
6452
  runComponentObservers(definition, instance, changedRootKeys, previousProperties);
5692
6453
  }
5693
- function createComponentScope(clonedNode, scope, componentScopeId, componentInstance) {
6454
+ function createComponentScope(clonedNode, scope, componentScopeId, componentInstance, genericComponents, slots) {
5694
6455
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
5695
6456
  return {
5696
6457
  alias: clonedNode.name,
@@ -5703,19 +6464,24 @@ function createComponentScope(clonedNode, scope, componentScopeId, componentInst
5703
6464
  return typeof method === "function" ? method : void 0;
5704
6465
  },
5705
6466
  getScopeId: () => componentScopeId,
6467
+ genericComponents,
5706
6468
  hostId: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
5707
6469
  id: typeof clonedNode.attribs?.id === "string" ? clonedNode.attribs.id : void 0,
5708
6470
  listenerScopeId: scope.getScopeId(),
5709
- ownerScopeId
6471
+ ownerScopeId,
6472
+ slots
5710
6473
  };
5711
6474
  }
5712
- function resolveComponentProperties(clonedNode, scope) {
6475
+ function resolveComponentProperties(clonedNode, scope, definition) {
5713
6476
  const nextProperties = {};
5714
6477
  const bindingExpressions = {};
6478
+ const declaredProperties = definition.properties ?? {};
5715
6479
  for (const [key, value] of Object.entries(clonedNode.attribs ?? {})) {
5716
- if (key.startsWith("bind")) continue;
5717
- if (isMustacheOnly(String(value))) bindingExpressions[key] = String(value).trim().slice(2, -2).trim();
5718
- nextProperties[key] = resolveComponentAttributeValue(String(value), scope);
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);
5719
6485
  }
5720
6486
  return {
5721
6487
  nextProperties,
@@ -5726,22 +6492,25 @@ function createRuntimeComponentInstance(componentScopeId, context, clonedNode, c
5726
6492
  const componentInstance = createComponentInstance({
5727
6493
  definition: componentEntry.definition,
5728
6494
  properties: nextProperties,
6495
+ requestRender: (callback) => context.session.requestRender(callback),
5729
6496
  triggerEvent: buildComponentTrigger(componentScopeId, context, clonedNode)
5730
6497
  });
6498
+ setSelectorQueryScopeId(componentInstance, componentScopeId);
6499
+ componentInstance.is = componentEntry.filePath.replace(JS_FILE_RE, "");
5731
6500
  componentInstance.createIntersectionObserver = (options) => context.session.createIntersectionObserver(componentInstance, options);
5732
6501
  componentInstance.createMediaQueryObserver = () => context.session.createMediaQueryObserver(componentInstance);
5733
6502
  componentInstance.selectComponent = (selector) => context.session.selectComponentWithin(componentScopeId, selector);
5734
6503
  componentInstance.selectAllComponents = (selector) => context.session.selectAllComponentsWithin(componentScopeId, selector);
5735
- componentInstance.selectOwnerComponent = () => ownerScopeId ? context.session.selectOwnerComponent(componentScopeId) : null;
6504
+ componentInstance.selectOwnerComponent = () => ownerScopeId ? context.componentCache.get(ownerScopeId) ?? null : null;
6505
+ context.componentCache.set(componentScopeId, componentInstance);
5736
6506
  runComponentLifecycle(componentInstance, "created");
5737
6507
  runComponentObservers(componentInstance.__definition__ ?? componentEntry.definition, componentInstance, Object.keys(nextProperties), {});
5738
6508
  componentInstance.__propertySnapshots = Object.fromEntries(Object.entries(componentInstance.properties).map(([key, propertyValue]) => [key, cloneValue(propertyValue)]));
5739
6509
  runComponentLifecycle(componentInstance, "attached");
5740
- context.componentCache.set(componentScopeId, componentInstance);
5741
6510
  return componentInstance;
5742
6511
  }
5743
6512
  function renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes) {
5744
- const componentDocument = parseTemplateDocument(readTemplateSource(componentEntry.absoluteTemplatePath));
6513
+ const componentDocument = parseTemplateDocument(readTemplateSource(context.artifactSource, componentEntry.absoluteTemplatePath));
5745
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);
5746
6515
  }
5747
6516
  //#endregion
@@ -5805,25 +6574,72 @@ function renderChildren(children, scope, context, ownerJsonPath, ownerFilePath,
5805
6574
  }
5806
6575
  return renderedChildren;
5807
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
+ }
5808
6604
  function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, instancePath, seenComponentScopes) {
5809
6605
  const clonedNode = cloneNode(node);
5810
6606
  if (!isTagNode(clonedNode)) {
5811
6607
  applyNodeBindings(clonedNode, scope);
5812
6608
  return clonedNode;
5813
6609
  }
5814
- 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));
5815
6625
  if (componentEntry) {
5816
6626
  const componentScopeId = `${instancePath}/${clonedNode.name}`;
5817
6627
  const ownerScopeId = scope.getScopeId().includes("/") ? scope.getScopeId() : void 0;
5818
- const { nextProperties, bindingExpressions } = resolveComponentProperties(clonedNode, scope);
6628
+ const { nextProperties, bindingExpressions } = resolveComponentProperties(clonedNode, scope, componentEntry.definition);
5819
6629
  let componentInstance = context.componentCache.get(componentScopeId);
5820
6630
  if (!componentInstance) componentInstance = createRuntimeComponentInstance(componentScopeId, context, clonedNode, componentEntry, nextProperties, ownerScopeId);
5821
6631
  else syncComponentProperties(componentInstance, componentInstance.__definition__ ?? componentEntry.definition, nextProperties, bindingExpressions, context.changedPageKeys);
5822
6632
  seenComponentScopes.add(componentScopeId);
5823
- const componentScope = createComponentScope(clonedNode, scope, componentScopeId, componentInstance);
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);
5824
6636
  context.componentScopes.set(componentScopeId, componentScope);
5825
6637
  const renderedComponentRoot = renderRuntimeComponentTemplate(context, componentEntry, renderNodeTree, componentScope, componentScopeId, seenComponentScopes);
5826
- if (renderedComponentRoot.attribs) renderedComponentRoot.attribs["data-sim-component"] = clonedNode.name;
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
+ }
5827
6643
  if (!componentInstance.__ready__) {
5828
6644
  runComponentLifecycle(componentInstance, "ready");
5829
6645
  componentInstance.__ready__ = true;
@@ -5832,12 +6648,14 @@ function renderNodeTree(node, scope, context, ownerJsonPath, ownerFilePath, inst
5832
6648
  return renderedComponentRoot;
5833
6649
  }
5834
6650
  applyNodeBindings(clonedNode, scope);
6651
+ clonedNode.attribs["data-sim-node"] = instancePath;
5835
6652
  clonedNode.children = renderChildren(clonedNode.children ?? [], scope, context, ownerJsonPath, ownerFilePath, `${instancePath}/${clonedNode.name}`, seenComponentScopes);
5836
6653
  return clonedNode;
5837
6654
  }
5838
6655
  function renderRuntimePageTree(context, page) {
5839
6656
  const route = page.route.replace(LEADING_SLASH_RE$2, "");
5840
- 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));
5841
6659
  const pageScopeId = `page:${route}`;
5842
6660
  const pageScope = {
5843
6661
  data: page.data,
@@ -5867,7 +6685,7 @@ function renderRuntimePageTree(context, page) {
5867
6685
  function createRequireNotFoundError(request, importer) {
5868
6686
  return /* @__PURE__ */ new Error(`Cannot resolve require("${request}") from ${normalize(importer)} in headless runtime.`);
5869
6687
  }
5870
- function resolveRequiredModulePath(importer, request) {
6688
+ function resolveRequiredModulePath(artifactSource, importer, request) {
5871
6689
  if (!request.startsWith(".")) throw createRequireNotFoundError(request, importer);
5872
6690
  const basePath = path.resolve(path.dirname(importer), request);
5873
6691
  const candidates = [
@@ -5876,10 +6694,10 @@ function resolveRequiredModulePath(importer, request) {
5876
6694
  `${basePath}.json`,
5877
6695
  path.join(basePath, "index.js")
5878
6696
  ];
5879
- for (const candidate of candidates) if (fs.existsSync(candidate)) return candidate;
6697
+ for (const candidate of candidates) if (artifactSource.has(candidate)) return candidate;
5880
6698
  throw createRequireNotFoundError(request, importer);
5881
6699
  }
5882
- function createExecutionContext(registries, getCurrentPages, getApp, wxDriver) {
6700
+ function createExecutionContext(registries, getCurrentPages, getApp, wxDriver, kernel, globals) {
5883
6701
  const wx = createHeadlessWx(wxDriver);
5884
6702
  return {
5885
6703
  App(definition) {
@@ -5897,47 +6715,64 @@ function createExecutionContext(registries, getCurrentPages, getApp, wxDriver) {
5897
6715
  Page(definition) {
5898
6716
  return registerPageDefinition(registries, definition);
5899
6717
  },
5900
- console,
5901
- clearTimeout,
6718
+ console: kernel.diagnostics.createConsole(),
6719
+ clearInterval: (handle) => kernel.scheduler.clearInterval(handle),
6720
+ clearTimeout: (handle) => kernel.scheduler.clearTimeout(handle),
5902
6721
  getApp,
5903
6722
  getCurrentPages,
5904
6723
  globalThis: void 0,
5905
6724
  process,
5906
6725
  require: void 0,
5907
- setInterval,
5908
- setTimeout,
5909
- wx
6726
+ setInterval: kernel.scheduler.setInterval.bind(kernel.scheduler),
6727
+ setTimeout: kernel.scheduler.setTimeout.bind(kernel.scheduler),
6728
+ wx,
6729
+ ...globals
5910
6730
  };
5911
6731
  }
5912
- function createModuleLoader(registries, getCurrentPages, getApp, wxDriver) {
6732
+ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver, options) {
5913
6733
  const moduleCache = /* @__PURE__ */ new Map();
5914
- const executionContext = createExecutionContext(registries, getCurrentPages, getApp, wxDriver);
6734
+ const executionContext = createExecutionContext(registries, getCurrentPages, getApp, wxDriver, options.kernel, options.globals ?? {});
5915
6735
  executionContext.globalThis = executionContext;
5916
6736
  function executeModule(filePath, loadContext) {
5917
6737
  const resolvedPath = path.resolve(filePath);
5918
6738
  const cached = moduleCache.get(resolvedPath);
5919
- if (cached) return cached.exports;
5920
- const source = fs.readFileSync(resolvedPath, "utf8");
5921
- 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
+ };
5922
6746
  moduleCache.set(resolvedPath, module);
6747
+ const registeredDefinitionsBefore = new Set(registries.components.values());
6748
+ const requiredComponentDefinitions = [];
5923
6749
  const previousLoadContext = registries.currentLoadContext;
5924
6750
  registries.currentLoadContext = loadContext;
5925
- const localRequire = (request) => {
5926
- const requiredPath = resolveRequiredModulePath(resolvedPath, request);
6751
+ const localRequire = ((request) => {
6752
+ const requiredPath = resolveRequiredModulePath(options.artifactSource, resolvedPath, request);
5927
6753
  if (requiredPath.endsWith(".json")) {
5928
- const content = fs.readFileSync(requiredPath, "utf8");
6754
+ const content = options.artifactSource.readText(requiredPath);
6755
+ if (content == null) throw createRequireNotFoundError(request, resolvedPath);
5929
6756
  return JSON.parse(content);
5930
6757
  }
5931
- return executeModule(requiredPath, null);
5932
- };
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));
5933
6763
  try {
5934
6764
  new vm.Script(`(function (exports, module, require, __filename, __dirname) { ${source}\n})`, { filename: resolvedPath }).runInNewContext(executionContext)(module.exports, module, localRequire, resolvedPath, path.dirname(resolvedPath));
5935
- 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;
5936
6768
  } finally {
5937
6769
  registries.currentLoadContext = previousLoadContext;
5938
6770
  }
5939
6771
  }
5940
6772
  return {
6773
+ close() {
6774
+ moduleCache.clear();
6775
+ },
5941
6776
  executeAppModule(filePath) {
5942
6777
  executeModule(filePath, { kind: "app" });
5943
6778
  if (!registries.appDefinition) throw new Error(`App() was not registered while executing ${normalize(filePath)} in headless runtime.`);
@@ -5953,11 +6788,11 @@ function createModuleLoader(registries, getCurrentPages, getApp, wxDriver) {
5953
6788
  return definition;
5954
6789
  },
5955
6790
  executeComponentModule(filePath, id) {
5956
- executeModule(filePath, {
6791
+ const loadedModule = executeModule(filePath, {
5957
6792
  kind: "component",
5958
6793
  route: id
5959
6794
  });
5960
- const definition = registries.components.get(id);
6795
+ const definition = registries.components.get(id) ?? registerExportedComponentDefinition(registries, id, loadedModule.exports, loadedModule.componentDefinitions.at(-1));
5961
6796
  if (!definition) throw new Error(`Component() was not registered for id "${id}" while executing ${normalize(filePath)}.`);
5962
6797
  return definition;
5963
6798
  },
@@ -6024,9 +6859,10 @@ function createAppLaunchOptions(pathname, query) {
6024
6859
  scene: 1001
6025
6860
  };
6026
6861
  }
6027
- function readJsonObject(filePath) {
6862
+ function readJsonObject(project, filePath) {
6028
6863
  try {
6029
- 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);
6030
6866
  return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
6031
6867
  } catch {
6032
6868
  return;
@@ -6040,6 +6876,7 @@ function resolveNavigationPath(targetPath, baseRoute) {
6040
6876
  }
6041
6877
  var HeadlessSession = class {
6042
6878
  project;
6879
+ kernel = new RuntimeKernel();
6043
6880
  appDefinition = null;
6044
6881
  appInstance = null;
6045
6882
  moduleLoader;
@@ -6048,6 +6885,9 @@ var HeadlessSession = class {
6048
6885
  pages = [];
6049
6886
  componentCache = /* @__PURE__ */ new Map();
6050
6887
  componentScopes = /* @__PURE__ */ new Map();
6888
+ selectorQueryScopeSnapshots = /* @__PURE__ */ new WeakMap();
6889
+ renderRequestPending = false;
6890
+ renderRequestCallbacks = [];
6051
6891
  tabBarRoutes;
6052
6892
  tabPages = /* @__PURE__ */ new Map();
6053
6893
  tabBarItems = /* @__PURE__ */ new Map();
@@ -6058,13 +6898,15 @@ var HeadlessSession = class {
6058
6898
  canvasContexts = /* @__PURE__ */ new Map();
6059
6899
  enterOptions = createAppLaunchOptions("", {});
6060
6900
  launchOptions = createAppLaunchOptions("", {});
6061
- wxState = createHeadlessWxState();
6901
+ wxState;
6062
6902
  pullDownRefreshState = {
6063
6903
  active: false,
6064
6904
  stopCalls: 0
6065
6905
  };
6066
6906
  constructor(options) {
6067
- 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 });
6068
6910
  this.registries = createHostRegistries();
6069
6911
  const rawTabBarList = Array.isArray(this.project.appConfig.tabBar?.list) ? this.project.appConfig.tabBar.list : [];
6070
6912
  this.tabBarRoutes = /* @__PURE__ */ new Set();
@@ -6114,6 +6956,7 @@ var HeadlessSession = class {
6114
6956
  }
6115
6957
  }),
6116
6958
  getAppBaseInfoSync: () => deriveAppBaseInfo(this.systemInfo),
6959
+ getDeviceInfo: () => deriveDeviceInfo(this.systemInfo),
6117
6960
  getLaunchOptionsSync: () => ({
6118
6961
  ...this.launchOptions,
6119
6962
  query: { ...this.launchOptions.query },
@@ -6123,6 +6966,7 @@ var HeadlessSession = class {
6123
6966
  }
6124
6967
  }),
6125
6968
  getClipboardData: () => this.wxState.getClipboardData(),
6969
+ getLocation: () => createDefaultLocationResult(),
6126
6970
  getMenuButtonBoundingClientRect: () => deriveMenuButtonBoundingClientRect(this.systemInfo),
6127
6971
  getNetworkType: () => this.wxState.getNetworkType(),
6128
6972
  navigateBack: (option) => this.navigateBack(option?.delta),
@@ -6142,7 +6986,7 @@ var HeadlessSession = class {
6142
6986
  removeSavedFile: (option) => this.wxState.removeSavedFile(option),
6143
6987
  saveImageToPhotosAlbum: (option) => this.wxState.saveImageToPhotosAlbum(option),
6144
6988
  saveVideoToPhotosAlbum: (option) => this.wxState.saveVideoToPhotosAlbum(option),
6145
- nextTick: (callback) => queueMicrotask(() => callback?.()),
6989
+ nextTick: (callback) => this.kernel.scheduler.queueMicrotask(() => callback?.()),
6146
6990
  offNetworkStatusChange: (callback) => this.wxState.offNetworkStatusChange(callback),
6147
6991
  onNetworkStatusChange: (callback) => this.wxState.onNetworkStatusChange(callback),
6148
6992
  removeStorageSync: (key) => this.wxState.removeStorageSync(key),
@@ -6174,15 +7018,41 @@ var HeadlessSession = class {
6174
7018
  removeTabBarBadge: (option) => this.removeTabBarBadge(option.index),
6175
7019
  setTabBarBadge: (option) => this.setTabBarBadge(option.index, option.text),
6176
7020
  updateShareMenu: (option) => this.wxState.updateShareMenu(option)
7021
+ }, {
7022
+ artifactSource: this.project.artifactSource,
7023
+ globals: options.globals,
7024
+ kernel: this.kernel
6177
7025
  });
6178
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
+ }
6179
7046
  getApp() {
7047
+ this.assertActive();
6180
7048
  return this.appInstance;
6181
7049
  }
6182
7050
  getCurrentPages() {
7051
+ this.assertActive();
6183
7052
  return this.pages.slice();
6184
7053
  }
6185
7054
  callWxMethod(methodName, ...args) {
7055
+ this.assertActive();
6186
7056
  const method = this.moduleLoader.wx[methodName];
6187
7057
  if (typeof method !== "function") throw new TypeError(`wx.${methodName} is not available in headless runtime.`);
6188
7058
  return Reflect.apply(method, this.moduleLoader.wx, args);
@@ -6223,9 +7093,11 @@ var HeadlessSession = class {
6223
7093
  return this.wxState.getSavedFileList().fileList;
6224
7094
  }
6225
7095
  renderCurrentPage() {
7096
+ this.assertActive();
6226
7097
  const current = this.requireCurrentPage("renderCurrentPage()");
6227
- return renderRuntimePageTree({
7098
+ const rendered = renderRuntimePageTree({
6228
7099
  changedPageKeys: current.__lastChangedKeys__ ?? [],
7100
+ artifactSource: this.project.artifactSource,
6229
7101
  componentCache: this.componentCache,
6230
7102
  componentScopes: this.componentScopes,
6231
7103
  moduleLoader: this.moduleLoader,
@@ -6233,11 +7105,32 @@ var HeadlessSession = class {
6233
7105
  session: {
6234
7106
  createIntersectionObserver: (scope, options) => this.createIntersectionObserver(scope, options),
6235
7107
  createMediaQueryObserver: (scope) => this.createMediaQueryObserver(scope),
7108
+ requestRender: (callback) => this.requestRender(callback),
6236
7109
  selectAllComponentsWithin: (scopeId, selector) => this.selectAllComponentsWithin(scopeId, selector),
6237
7110
  selectComponentWithin: (scopeId, selector) => this.selectComponentWithin(scopeId, selector),
6238
7111
  selectOwnerComponent: (scopeId) => this.selectOwnerComponent(scopeId)
6239
7112
  }
6240
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
+ });
6241
7134
  }
6242
7135
  getScopeSnapshot(scopeId) {
6243
7136
  const scope = this.componentScopes.get(scopeId);
@@ -6293,6 +7186,7 @@ var HeadlessSession = class {
6293
7186
  const normalizedScopeId = scopeId.trim();
6294
7187
  if (!normalizedScopeId) throw new Error("Scope id must be a non-empty string in headless runtime.");
6295
7188
  const current = this.requireCurrentPage(`scope method "${methodName}"`);
7189
+ this.renderCurrentPage();
6296
7190
  if (normalizedScopeId === `page:${stripLeadingSlash(current.route)}`) {
6297
7191
  const method = current[methodName];
6298
7192
  if (typeof method !== "function") throw new TypeError(`Method "${methodName}" does not exist on headless page ${current.route}.`);
@@ -6371,6 +7265,9 @@ var HeadlessSession = class {
6371
7265
  getAppBaseInfo() {
6372
7266
  return deriveAppBaseInfo(this.systemInfo);
6373
7267
  }
7268
+ getDeviceInfo() {
7269
+ return deriveDeviceInfo(this.systemInfo);
7270
+ }
6374
7271
  getLaunchOptions() {
6375
7272
  return {
6376
7273
  ...this.launchOptions,
@@ -6394,6 +7291,9 @@ var HeadlessSession = class {
6394
7291
  getMenuButtonBoundingClientRect() {
6395
7292
  return deriveMenuButtonBoundingClientRect(this.systemInfo);
6396
7293
  }
7294
+ getLocation() {
7295
+ return createDefaultLocationResult();
7296
+ }
6397
7297
  getNetworkType() {
6398
7298
  return this.wxState.getNetworkType();
6399
7299
  }
@@ -6538,6 +7438,7 @@ var HeadlessSession = class {
6538
7438
  return { errMsg: "setTabBarBadge:ok" };
6539
7439
  }
6540
7440
  bootstrap(launchOptions = createAppLaunchOptions("", {})) {
7441
+ this.assertActive();
6541
7442
  if (this.appInstance) return this.appInstance;
6542
7443
  this.launchOptions = createAppLaunchOptions(launchOptions.path, launchOptions.query);
6543
7444
  this.enterOptions = createAppLaunchOptions(launchOptions.path, launchOptions.query);
@@ -6605,11 +7506,7 @@ var HeadlessSession = class {
6605
7506
  if (!this.isTabBarRoute(target.routeRecord.route)) throw new Error(`wx.switchTab() can only open a tabBar page in headless runtime: ${url}`);
6606
7507
  const current = this.currentPageInstance;
6607
7508
  const cachedTarget = this.tabPages.get(target.routeRecord.route) ?? null;
6608
- const tabItem = this.resolveTabBarItem(target.routeRecord.route);
6609
- if (current === cachedTarget && current) {
6610
- current.onTabItemTap?.(tabItem);
6611
- return current;
6612
- }
7509
+ if (current === cachedTarget && current) return current;
6613
7510
  if (current && current !== cachedTarget) {
6614
7511
  current.onHide?.();
6615
7512
  this.runPageComponentLifetime(current.route, "hide");
@@ -6634,7 +7531,6 @@ var HeadlessSession = class {
6634
7531
  nextPage.onShow?.();
6635
7532
  this.runPageComponentLifetime(nextPage.route, "show");
6636
7533
  }
6637
- nextPage.onTabItemTap?.(tabItem);
6638
7534
  return nextPage;
6639
7535
  }
6640
7536
  pageScrollTo(option) {
@@ -6682,15 +7578,33 @@ var HeadlessSession = class {
6682
7578
  }
6683
7579
  executeSelectorQuery(requests, scope) {
6684
7580
  const current = this.requireCurrentPage("wx.createSelectorQuery().exec()");
6685
- 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
+ });
6686
7600
  const rendered = this.renderCurrentPage();
6687
- const scopeId = scope && scope !== current ? this.getComponentScopeId(scope) : null;
7601
+ const scopeId = nativeScope && nativeScope !== current ? this.getComponentScopeId(nativeScope) : null;
6688
7602
  return executeSelectorQueryRequests(requests, {
6689
7603
  page: current,
6690
7604
  resolveContext: (node) => {
6691
7605
  if (node.name !== "canvas") return { type: "unsupported-context" };
6692
7606
  const canvasId = node.attribs?.["canvas-id"];
6693
- 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" };
6694
7608
  },
6695
7609
  root: resolveSelectorQueryScopeRoot(rendered.root, scopeId),
6696
7610
  windowInfo: this.getWindowInfo()
@@ -6700,7 +7614,7 @@ var HeadlessSession = class {
6700
7614
  const pageModulePath = path.resolve(this.project.miniprogramRootPath, `${target.routeRecord.route}.js`);
6701
7615
  const pageConfigPath = path.resolve(this.project.miniprogramRootPath, `${target.routeRecord.route}.json`);
6702
7616
  const pageDefinition = this.moduleLoader.executePageModule(pageModulePath, target.routeRecord.route);
6703
- const pageConfig = readJsonObject(pageConfigPath);
7617
+ const pageConfig = readJsonObject(this.project, pageConfigPath);
6704
7618
  const pageInstance = createPageInstance(`/${target.routeRecord.route}`, pageDefinition, target.query, {
6705
7619
  background: resolveBackgroundSnapshot(this.project.appConfig, pageConfig),
6706
7620
  navigationBar: resolveNavigationBarSnapshot(this.project.appConfig, pageConfig)
@@ -6716,16 +7630,11 @@ var HeadlessSession = class {
6716
7630
  pageInstance.onLoad?.(query);
6717
7631
  pageInstance.onShow?.();
6718
7632
  pageInstance.onReady?.();
7633
+ pageInstance.onRouteDone?.({});
6719
7634
  }
6720
7635
  isTabBarRoute(route) {
6721
7636
  return this.tabBarRoutes.has(stripLeadingSlash(route));
6722
7637
  }
6723
- resolveTabBarItem(route) {
6724
- const pagePath = stripLeadingSlash(route);
6725
- const item = this.tabBarItems.get(pagePath);
6726
- if (!item) throw new Error(`Missing tabBar metadata for route "${route}" in headless runtime.`);
6727
- return { ...item };
6728
- }
6729
7638
  requireTabBarItem(index, action) {
6730
7639
  const normalizedIndex = Number.isFinite(index) ? Math.trunc(index) : NaN;
6731
7640
  const item = this.tabBarState.get(normalizedIndex);
@@ -6776,7 +7685,7 @@ var HeadlessSession = class {
6776
7685
  selectComponentsWithin(rootScopeId, selector) {
6777
7686
  const selectorParts = normalizeSelectorParts(selector);
6778
7687
  if (selectorParts.length === 0) return [];
6779
- return [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
7688
+ const matches = [...this.componentScopes.entries()].filter(([candidateScopeId, scope]) => {
6780
7689
  if (!candidateScopeId.includes("/")) return false;
6781
7690
  if (rootScopeId && candidateScopeId === rootScopeId) return false;
6782
7691
  if (rootScopeId && !candidateScopeId.startsWith(`${rootScopeId}/`)) return false;
@@ -6789,7 +7698,9 @@ var HeadlessSession = class {
6789
7698
  currentScope = currentScope.ownerScopeId ? this.componentScopes.get(currentScope.ownerScopeId) : void 0;
6790
7699
  }
6791
7700
  return true;
6792
- }).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);
6793
7704
  }
6794
7705
  detachPageComponents(route) {
6795
7706
  const prefix = `page:${stripLeadingSlash(route)}`;
@@ -6922,10 +7833,185 @@ function createHeadlessSession(options) {
6922
7833
  return new HeadlessSession(options);
6923
7834
  }
6924
7835
  //#endregion
6925
- //#region src/testing/sessionHandle/shared.ts
6926
- const LEADING_SLASH_RE = /^\/+/;
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
6927
7885
  const DEFAULT_WAIT_TIMEOUT$1 = 1e3;
6928
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;
6929
8015
  function normalizeRoute(route) {
6930
8016
  return route.replace(LEADING_SLASH_RE, "");
6931
8017
  }
@@ -6938,13 +8024,17 @@ function normalizeNonEmptyInput(value, label) {
6938
8024
  if (!normalizedValue) throw new Error(`${label} must be a non-empty string in headless testing runtime.`);
6939
8025
  return normalizedValue;
6940
8026
  }
8027
+ function cloneProtocolValue(value) {
8028
+ if (!value || typeof value !== "object") return value;
8029
+ return JSON.parse(JSON.stringify(value));
8030
+ }
6941
8031
  async function waitForDelay(ms = 0) {
6942
8032
  if (ms <= 0) return;
6943
8033
  await new Promise((resolve) => setTimeout(resolve, ms));
6944
8034
  }
6945
8035
  async function pollUntil(check, errorMessage, options = {}) {
6946
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT$1)) : DEFAULT_WAIT_TIMEOUT$1;
6947
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_WAIT_INTERVAL$1)) : DEFAULT_WAIT_INTERVAL$1;
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;
6948
8038
  const deadline = Date.now() + timeout;
6949
8039
  while (true) {
6950
8040
  const result = await check();
@@ -6966,8 +8056,6 @@ async function runWithTimeout(operation, timeout, message) {
6966
8056
  }
6967
8057
  //#endregion
6968
8058
  //#region src/testing/pageHandle.ts
6969
- const DEFAULT_WAIT_TIMEOUT = 1e3;
6970
- const DEFAULT_WAIT_INTERVAL = 10;
6971
8059
  var HeadlessTestingPageHandle = class {
6972
8060
  project;
6973
8061
  page;
@@ -6978,9 +8066,11 @@ var HeadlessTestingPageHandle = class {
6978
8066
  this.session = session;
6979
8067
  }
6980
8068
  get path() {
8069
+ this.assertActive();
6981
8070
  return this.page.route;
6982
8071
  }
6983
8072
  get query() {
8073
+ this.assertActive();
6984
8074
  return { ...this.page.options };
6985
8075
  }
6986
8076
  resolveDataByPath(path) {
@@ -6990,16 +8080,8 @@ var HeadlessTestingPageHandle = class {
6990
8080
  for (const segment of segments) current = current?.[segment];
6991
8081
  return current;
6992
8082
  }
6993
- async pollUntil(check, errorMessage, options = {}) {
6994
- const timeout = Number.isFinite(options.timeout) ? Math.max(0, Math.trunc(options.timeout ?? DEFAULT_WAIT_TIMEOUT)) : DEFAULT_WAIT_TIMEOUT;
6995
- const interval = Number.isFinite(options.interval) ? Math.max(1, Math.trunc(options.interval ?? DEFAULT_WAIT_INTERVAL)) : DEFAULT_WAIT_INTERVAL;
6996
- const deadline = Date.now() + timeout;
6997
- while (true) {
6998
- const result = await check();
6999
- if (result != null) return result;
7000
- if (Date.now() >= deadline) throw new Error(errorMessage);
7001
- await this.waitFor(interval);
7002
- }
8083
+ assertActive() {
8084
+ this.session?.assertActive();
7003
8085
  }
7004
8086
  createScopeHandle(component) {
7005
8087
  const scopeId = this.session?.getScopeIdForComponent(component);
@@ -7009,23 +8091,28 @@ var HeadlessTestingPageHandle = class {
7009
8091
  return await this.callMethodWithOptions(methodName, {}, ...args);
7010
8092
  }
7011
8093
  async callMethodWithOptions(methodName, options = {}, ...args) {
8094
+ this.assertActive();
7012
8095
  const normalizedMethodName = normalizeNonEmptyInput(methodName, "Page method name");
7013
8096
  return await runWithTimeout(async () => {
8097
+ this.session?.renderCurrentPage();
7014
8098
  const method = this.page[normalizedMethodName];
7015
8099
  if (typeof method !== "function") throw new TypeError(`Method "${normalizedMethodName}" does not exist on headless page ${this.page.route}.`);
7016
- return await method.apply(this.page, args);
8100
+ return cloneProtocolValue(await method.apply(this.page, args));
7017
8101
  }, options.timeout, `Timed out calling page method "${normalizedMethodName}" in headless testing runtime.`);
7018
8102
  }
7019
8103
  async data(path) {
7020
- return this.resolveDataByPath(path);
8104
+ this.assertActive();
8105
+ return cloneProtocolValue(this.resolveDataByPath(path));
7021
8106
  }
7022
8107
  async selectComponent(selector) {
8108
+ this.assertActive();
7023
8109
  const normalizedSelector = selector.trim();
7024
8110
  if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7025
8111
  const component = this.page.selectComponent?.(normalizedSelector) ?? null;
7026
8112
  return this.createScopeHandle(component);
7027
8113
  }
7028
8114
  async selectAllComponents(selector) {
8115
+ this.assertActive();
7029
8116
  const normalizedSelector = selector.trim();
7030
8117
  if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7031
8118
  return (this.page.selectAllComponents?.(normalizedSelector) ?? []).map((component) => this.createScopeHandle(component)).filter((handle) => Boolean(handle));
@@ -7035,24 +8122,13 @@ var HeadlessTestingPageHandle = class {
7035
8122
  await new Promise((resolve) => setTimeout(resolve, ms));
7036
8123
  }
7037
8124
  async $(selector) {
7038
- const tree = this.session?.getCurrentPages().includes(this.page) ? this.session.renderCurrentPage() : renderPageTree(this.project, this.page);
7039
- const root = new HeadlessTestingNodeHandle(tree.root.type === "root" ? tree.root.children?.[0] ?? tree.root : tree.root, {
7040
- callMethod: (scopeId, methodName, event) => {
7041
- if (this.session?.getCurrentPages().includes(this.page)) return this.session.callScopeMethod(scopeId, methodName, event);
7042
- return this.callMethod(methodName, event);
7043
- },
8125
+ this.assertActive();
8126
+ const root = createPageRootNodeHandle({
8127
+ assertActive: () => this.assertActive(),
7044
8128
  createPageHandle: () => this,
7045
- createScopeHandle: (scopeId) => {
7046
- if (!this.session) throw new Error("Scope handles are not available without an active headless testing session.");
7047
- if (!scopeId) return null;
7048
- return new HeadlessTestingScopeHandle(scopeId, this.project, this.session);
7049
- },
7050
- ownerScopeId: (scopeId) => {
7051
- if (!this.session || !scopeId) return null;
7052
- if (this.session.getScopeSnapshot(scopeId)?.type !== "component") return null;
7053
- const owner = this.session.selectOwnerComponent(scopeId);
7054
- return this.session.getScopeIdForComponent(owner);
7055
- }
8129
+ page: this.page,
8130
+ project: this.project,
8131
+ session: this.session
7056
8132
  });
7057
8133
  if (selector === "page") return root;
7058
8134
  return await root.$(selector);
@@ -7063,57 +8139,68 @@ var HeadlessTestingPageHandle = class {
7063
8139
  if (selector === "page") return [root];
7064
8140
  return await root.$$(selector);
7065
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
+ }
7066
8151
  async waitForSelector(selector, options = {}) {
7067
- const normalizedSelector = selector.trim();
7068
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7069
- if ((options.state ?? "attached") === "detached") {
7070
- await this.pollUntil(async () => await this.$(normalizedSelector) ? null : true, `Timed out waiting for selector "${normalizedSelector}" to become detached in headless testing runtime.`, options);
7071
- return null;
7072
- }
7073
- 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);
7074
8153
  }
7075
8154
  async waitForComponent(selector, options = {}) {
7076
- const normalizedSelector = selector.trim();
7077
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7078
- 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);
7079
8156
  }
7080
8157
  async waitForComponents(selector, count = 1, options = {}) {
7081
- const normalizedSelector = selector.trim();
7082
- if (!normalizedSelector) throw new Error("Selector must be a non-empty string in headless testing runtime.");
7083
- const normalizedCount = Number.isFinite(count) ? Math.max(1, Math.trunc(count)) : 1;
7084
- return await this.pollUntil(async () => {
7085
- const components = await this.selectAllComponents(normalizedSelector);
7086
- return components.length >= normalizedCount ? components : null;
7087
- }, `Timed out waiting for ${normalizedCount} component(s) matching "${normalizedSelector}" in headless testing runtime.`, options);
8158
+ return await waitForPageComponents(this.waitAccess(), selector, count, options);
7088
8159
  }
7089
8160
  async waitForText(text, options = {}) {
7090
- const normalizedText = text.trim();
7091
- if (!normalizedText) throw new Error("Text must be a non-empty string in headless testing runtime.");
7092
- return await this.pollUntil(async () => {
7093
- return (await this.wxml()).includes(normalizedText) ? normalizedText : null;
7094
- }, `Timed out waiting for text "${normalizedText}" in headless testing runtime.`, options);
8161
+ return await waitForPageText(this.waitAccess(), text, options);
7095
8162
  }
7096
8163
  async waitForTextGone(text, options = {}) {
7097
- const normalizedText = text.trim();
7098
- if (!normalizedText) throw new Error("Text must be a non-empty string in headless testing runtime.");
7099
- await this.pollUntil(async () => {
7100
- return (await this.wxml()).includes(normalizedText) ? null : true;
7101
- }, `Timed out waiting for text "${normalizedText}" to disappear in headless testing runtime.`, options);
8164
+ await waitForPageTextGone(this.waitAccess(), text, options);
7102
8165
  }
7103
8166
  async waitForData(path, matcher, options = {}) {
7104
- const normalizedPath = path.trim();
7105
- if (!normalizedPath) throw new Error("Data path must be a non-empty string in headless testing runtime.");
7106
8167
  const hasMatcher = arguments.length >= 2;
7107
- return await this.pollUntil(async () => {
7108
- const value = this.resolveDataByPath(normalizedPath);
7109
- if (typeof matcher === "function") return matcher(value) ? value : null;
7110
- if (hasMatcher) return Object.is(value, matcher) ? value : null;
7111
- return value === void 0 ? null : value;
7112
- }, `Timed out waiting for data "${normalizedPath}" in headless testing runtime.`, options);
8168
+ return await waitForPageData(this.waitAccess(), path, matcher, hasMatcher, options);
7113
8169
  }
7114
8170
  async wxml() {
8171
+ this.assertActive();
7115
8172
  return this.session?.getCurrentPages().includes(this.page) ? this.session.renderCurrentPage().wxml : renderPageTree(this.project, this.page).wxml;
7116
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
+ }
7117
8204
  };
7118
8205
  //#endregion
7119
8206
  //#region src/testing/sessionHandle/scope.ts
@@ -7181,12 +8268,16 @@ var HeadlessTestingSessionHandle = class {
7181
8268
  this.project = project;
7182
8269
  this.session = session;
7183
8270
  }
7184
- async close() {}
8271
+ async close() {
8272
+ this.session.close();
8273
+ }
7185
8274
  async currentPage() {
8275
+ this.session.assertActive();
7186
8276
  const current = this.session.getCurrentPages().at(-1);
7187
8277
  return current ? new HeadlessTestingPageHandle(this.project, current, this.session) : null;
7188
8278
  }
7189
8279
  async getCurrentPages() {
8280
+ this.session.assertActive();
7190
8281
  return this.session.getCurrentPages().map((page) => new HeadlessTestingPageHandle(this.project, page, this.session));
7191
8282
  }
7192
8283
  async callWxMethod(methodName, ...args) {
@@ -7228,6 +8319,22 @@ var HeadlessTestingSessionHandle = class {
7228
8319
  if (!page) throw new Error(`Failed to reLaunch route "${route}" through the headless wx runtime.`);
7229
8320
  return new HeadlessTestingPageHandle(this.project, page, this.session);
7230
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
+ }
7231
8338
  async waitForCurrentPage(route, options = {}) {
7232
8339
  const normalizedRoute = route?.trim();
7233
8340
  if (normalizedRoute != null && !normalizedRoute) throw new Error("Route must be a non-empty string in headless testing runtime.");
@@ -7255,6 +8362,11 @@ var HeadlessTestingSessionHandle = class {
7255
8362
  async triggerRouteDone(options) {
7256
8363
  this.session.triggerRouteDone(options);
7257
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
+ }
7258
8370
  };
7259
8371
  //#endregion
7260
8372
  //#region src/testing/launch.ts
@@ -7264,4 +8376,4 @@ async function launch(options) {
7264
8376
  return new HeadlessTestingSessionHandle(session.project, session);
7265
8377
  }
7266
8378
  //#endregion
7267
- 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 };