@skillbuilder/miniapp-simulator 0.2.7 → 0.2.8

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.
Files changed (37) hide show
  1. package/README.md +18 -1
  2. package/docs/assets/road-king-controls.png +0 -0
  3. package/docs/desktop-gesture-design.redoc.xml +96 -0
  4. package/lib/client-C59iNO5u.mjs +1371 -0
  5. package/lib/{index-CqClPZVv.mjs → index-BSj1bmle.mjs} +1 -1
  6. package/lib/index.js +4130 -2739
  7. package/lib/remote-client.js +2 -2
  8. package/lib/types/core/simulator.d.ts +2 -0
  9. package/lib/types/gesture/host-bus.d.ts +27 -2
  10. package/lib/types/gesture/input-scheduler.d.ts +29 -0
  11. package/lib/types/gesture/keyboard-panel-view.d.ts +16 -0
  12. package/lib/types/gesture/keyboard-panel.d.ts +54 -0
  13. package/lib/types/gesture/plugins/index.d.ts +11 -14
  14. package/lib/types/gesture/plugins/keyboard-touch.d.ts +4 -0
  15. package/lib/types/gesture/plugins/multi-touch-hint.d.ts +1 -9
  16. package/lib/types/gesture/plugins/multi-touch-switch.d.ts +1 -1
  17. package/lib/types/gesture/plugins/touch-emitter.d.ts +1 -9
  18. package/lib/types/gesture/plugins/wheel-pinch.d.ts +3 -0
  19. package/lib/types/gesture/plugins/wheel-scroll.d.ts +1 -1
  20. package/lib/types/gesture/touch-cursor.d.ts +4 -0
  21. package/lib/types/gesture/touch-sequence.d.ts +12 -0
  22. package/lib/types/gesture/types.d.ts +33 -9
  23. package/lib/types/host/shadow-host.d.ts +14 -4
  24. package/lib/types/inspector/host-inspector.d.ts +1 -1
  25. package/lib/types/remote/audit-controller.d.ts +2 -0
  26. package/lib/types/remote/audit-leave-monitor.d.ts +2 -0
  27. package/lib/types/remote/client.d.ts +2 -0
  28. package/lib/types/remote/keyboard-panel-host.d.ts +19 -0
  29. package/lib/types/remote/protocol.d.ts +24 -1
  30. package/lib/types/remote/runtime-entry.d.ts +2 -1
  31. package/lib/types/remote/runtime.d.ts +1 -1
  32. package/lib/types/types/options.d.ts +4 -0
  33. package/lib/types/types/renderer.d.ts +8 -0
  34. package/lib/types/utils/screen-coordinates.d.ts +31 -0
  35. package/lib/workbench.js +1 -1
  36. package/package.json +1 -1
  37. package/lib/client-BjYHK9LR.mjs +0 -1220
@@ -0,0 +1,1371 @@
1
+ import { c as Ve, r as We, v as be, o as Ge, e as Je } from "./index-BSj1bmle.mjs";
2
+ function V(t) {
3
+ return Object.fromEntries(
4
+ Object.entries(t).filter(
5
+ ([, i]) => i != null && (typeof i != "number" || Number.isFinite(i))
6
+ )
7
+ );
8
+ }
9
+ function Ke(t) {
10
+ return t.map(V).filter(
11
+ (i) => i.result !== void 0 || i.message !== void 0 || ["time", "memory", "size", "score", "weight", "ratio", "value", "count"].some(
12
+ (n) => i[n] !== void 0
13
+ )
14
+ );
15
+ }
16
+ function Ee(t, i) {
17
+ const n = U(t), o = U(i), s = U(n.quality), v = U(n.score), h = U(v.byCategory), O = U(n.blocking), b = U(n.classification), _ = U(n.versions), R = U(n.paintTiming), M = Array.isArray(O.failures) ? O.failures.map(U) : [], P = M[0] ?? {}, E = q(U(n.loadFailure).code) ?? q(P.code) ?? q(P.id), N = Array.isArray(b.frameworks) ? b.frameworks.map(U) : [], W = Array.isArray(n.items) ? n.items.map(U) : [], m = (T) => W.find((A) => A.id === T) ?? {}, B = {
18
+ failure_code: E,
19
+ truncated_reason: Ye(s.truncatedReason),
20
+ quality: V({
21
+ sample_count: c(s.sampleCount),
22
+ interaction_count: c(s.interactionCount),
23
+ first_interaction_ms: c(s.firstInteractionAt),
24
+ reload_count: c(s.reloadCount),
25
+ infrastructure_error_count: c(s.infrastructureErrorCount),
26
+ complete: D(s.complete),
27
+ sufficient: D(s.sufficient),
28
+ probe_saturated: D(s.probeSaturated),
29
+ auto_stop_on_leave_ms: c(n.autoStopOnLeaveMs)
30
+ }),
31
+ blocking: V({ passed: D(O.passed), enforced: D(O.enforced) }),
32
+ classification: {
33
+ engine: q(b.engine)?.slice(0, 32),
34
+ tag_mismatch: D(n.tagMismatch),
35
+ inferred: D(b.inferred),
36
+ source_scan_complete: D(b.sourceScanComplete),
37
+ webgl_3d_active_samples: c(o.webgl3dActiveSamples),
38
+ evidence: Array.isArray(b.evidence) ? b.evidence.filter((T) => typeof T == "string").slice(0, 3).map((T) => T.slice(0, 48)) : [],
39
+ frameworks: N.slice(0, 6).map((T) => ({
40
+ id: q(T.id)?.slice(0, 32),
41
+ confidence: q(T.confidence)?.slice(0, 16),
42
+ evidence: Array.isArray(T.evidence) ? T.evidence.filter((A) => typeof A == "string").slice(0, 3).map(
43
+ (A) => A.startsWith("source:") ? "source:brand+api" : A.startsWith("filename:") ? "filename" : A.slice(0, 32)
44
+ ) : []
45
+ }))
46
+ },
47
+ category_scores: V({
48
+ memory: te(h.memory),
49
+ stability: te(h.stability),
50
+ performance: te(h.performance),
51
+ experience: te(h.experience),
52
+ package: te(h.package)
53
+ }),
54
+ paint: V({
55
+ fcp_status: q(R.fcpStatus),
56
+ lcp_status: q(R.lcpStatus),
57
+ fcp_threshold_ms: c(m("fcp").threshold),
58
+ lcp_threshold_ms: c(m("lcp").threshold)
59
+ })
60
+ }, x = [
61
+ {
62
+ name: "total_score",
63
+ score: c(v.total),
64
+ result: q(n.status),
65
+ count: M.length,
66
+ ratio: c(U(n.coverage).ratio),
67
+ time: c(s.effectiveMs),
68
+ message: JSON.stringify(B)
69
+ },
70
+ {
71
+ name: "fcp",
72
+ time: c(R.fcpMs),
73
+ score: c(m("fcp").score),
74
+ weight: c(m("fcp").weight)
75
+ },
76
+ {
77
+ name: "lcp",
78
+ time: c(R.lcpMs),
79
+ score: c(m("lcp").score),
80
+ weight: c(m("lcp").weight)
81
+ },
82
+ {
83
+ name: "zip_size",
84
+ size: c(o.zipBytes),
85
+ score: c(m("zipSize").score),
86
+ weight: c(m("zipSize").weight)
87
+ },
88
+ {
89
+ name: "unpacked_size",
90
+ size: c(o.unpackedBytes),
91
+ score: c(m("unpackedSize").score),
92
+ weight: c(m("unpackedSize").weight)
93
+ },
94
+ {
95
+ name: "largest_image",
96
+ size: c(o.largestImageBytes),
97
+ score: c(m("singleImage").score),
98
+ weight: c(m("singleImage").weight)
99
+ },
100
+ {
101
+ name: "uncompressed_js",
102
+ size: c(o.uncompressedJsBytes),
103
+ score: c(m("uncompressedJs").score),
104
+ weight: c(m("uncompressedJs").weight)
105
+ },
106
+ {
107
+ name: "fps_median",
108
+ value: c(o.fpsMedian),
109
+ unit: "fps",
110
+ score: c(m("fps").score),
111
+ weight: c(m("fps").weight)
112
+ },
113
+ {
114
+ name: "long_task_max",
115
+ time: c(o.longTaskMaxMs),
116
+ count: c(o.longTaskTotal),
117
+ score: c(m("longTask").score),
118
+ weight: c(m("longTask").weight)
119
+ },
120
+ {
121
+ name: "js_error_total",
122
+ count: c(o.jsErrorTotal),
123
+ score: c(m("jsError").score),
124
+ weight: c(m("jsError").weight)
125
+ },
126
+ {
127
+ name: "peak_heap",
128
+ memory: c(o.peakHeapBytes),
129
+ score: c(m("peakHeap").score),
130
+ weight: c(m("peakHeap").weight)
131
+ },
132
+ {
133
+ name: "heap_growth",
134
+ value: c(o.heapGrowthMBPerMin),
135
+ unit: "MB/min",
136
+ score: c(m("heapGrowth").score),
137
+ weight: c(m("heapGrowth").weight)
138
+ },
139
+ {
140
+ name: "texture_watermark",
141
+ memory: c(o.texWatermarkBytes),
142
+ score: c(m("texWatermark").score),
143
+ weight: c(m("texWatermark").weight)
144
+ },
145
+ {
146
+ name: "canvas",
147
+ memory: c(o.canvasWatermarkBytes),
148
+ score: c(m("canvasBuffer").score),
149
+ weight: c(m("canvasBuffer").weight)
150
+ },
151
+ {
152
+ name: "decoded_images",
153
+ memory: c(o.imgWatermarkBytes),
154
+ score: c(m("decodedImages").score),
155
+ weight: c(m("decodedImages").weight)
156
+ },
157
+ {
158
+ name: "wasm",
159
+ memory: c(o.wasmPeakBytes),
160
+ score: c(m("wasmMemory").score),
161
+ weight: c(m("wasmMemory").weight)
162
+ },
163
+ {
164
+ name: "max_workers",
165
+ count: c(o.maxWorkers),
166
+ score: c(m("workerCount").score),
167
+ weight: c(m("workerCount").weight)
168
+ },
169
+ { name: "heap_p95", memory: c(o.heapP95Bytes) },
170
+ { name: "buffer_watermark", memory: c(o.bufWatermarkBytes) },
171
+ { name: "fps_p5", value: c(o.fpsP5), unit: "fps" }
172
+ ], S = Ke(x);
173
+ return S[0].message = JSON.stringify({
174
+ ...B,
175
+ result_record_count: S.length
176
+ }), S.map(
177
+ (T) => V({
178
+ app_type: q(n.appType),
179
+ policy_version: q(_.policyVersion),
180
+ rules_version: q(_.rulesVersion),
181
+ probe_version: q(_.probeVersion),
182
+ result: q(n.status),
183
+ stage: q(n.stopReason),
184
+ ...T
185
+ })
186
+ );
187
+ }
188
+ function U(t) {
189
+ return t && typeof t == "object" && !Array.isArray(t) ? t : {};
190
+ }
191
+ function c(t) {
192
+ return typeof t == "number" && Number.isFinite(t) ? t : void 0;
193
+ }
194
+ function q(t) {
195
+ return typeof t == "string" && t ? t : void 0;
196
+ }
197
+ function D(t) {
198
+ return typeof t == "boolean" ? Number(t) : void 0;
199
+ }
200
+ function te(t) {
201
+ const i = U(t), n = c(i.got), o = c(i.max);
202
+ return n !== void 0 && o !== void 0 && o > 0 ? Math.round(n / o * 1e4) / 100 : void 0;
203
+ }
204
+ function Ye(t) {
205
+ const i = q(t);
206
+ if (i)
207
+ return /runtime|失去响应|超时/i.test(i) ? "runtime_hung" : /内存|熔断|guard/i.test(i) ? "simulator_guard" : /销毁|中断|unload|destroy/i.test(i) ? "session_interrupted" : /reload|刷新/i.test(i) ? "guest_reload" : "collection_interrupted";
208
+ }
209
+ const le = "RUNTIME_HUNG", Ze = 12e3, Xe = 35e3;
210
+ function Qe(t, i) {
211
+ const n = i ? "评测超时未返回:小工具长时间占用主线程,Runtime 失去响应" : "评测超时未返回:探针未上报任何数据,小工具可能在加载期即阻塞主线程", o = t.blocking.failures.map(
212
+ (s) => s.id === "loadFailed" ? { ...s, code: le, message: n } : s
213
+ );
214
+ return o.some((s) => s.id === "loadFailed") || o.push({ id: "loadFailed", code: le, message: n }), {
215
+ ...t,
216
+ status: "loadFailed",
217
+ blocking: { ...t.blocking, passed: !1, failures: o },
218
+ loadFailure: { code: le, message: n },
219
+ quality: { ...t.quality, complete: !1, truncatedReason: n }
220
+ };
221
+ }
222
+ function et(t, i, n, o) {
223
+ const s = t.ownerDocument, v = s.defaultView, h = /* @__PURE__ */ new Map(), O = /* @__PURE__ */ new Map(), b = /* @__PURE__ */ new Set();
224
+ let _ = !1, R;
225
+ const M = /* @__PURE__ */ new Map(), P = () => {
226
+ let f = s.activeElement;
227
+ for (; f?.shadowRoot?.activeElement; ) f = f.shadowRoot.activeElement;
228
+ return f;
229
+ }, E = (f = !1) => {
230
+ if (!_)
231
+ for (const [u, w] of h) {
232
+ const g = !f && !s.hidden && s.hasFocus() && w.state.open && w.state.available && (w.root.matches(":hover") || w.root.contains(P()) || [...M.values()].includes(u));
233
+ g !== w.active && (w.active = g, i({ type: "keyboard-panel-presence", controllerId: u, active: g }));
234
+ }
235
+ }, N = () => {
236
+ if (!_)
237
+ for (const [f, u] of h)
238
+ u.state.open && u.state.available && i({ type: "keyboard-panel-command", controllerId: f, command: { type: "outside" } });
239
+ }, W = (f) => {
240
+ if (!f) return !1;
241
+ for (const u of h.values())
242
+ if (f === u.root || "nodeType" in f && u.root.contains(f))
243
+ return !0;
244
+ return !1;
245
+ }, m = (f) => {
246
+ E();
247
+ const u = f.composedPath();
248
+ u.includes(t) || u.some(W) || N();
249
+ }, B = () => {
250
+ M.clear(), E(!0), !(P() === t || W(P())) && N();
251
+ }, x = () => {
252
+ E(), s.hidden && N();
253
+ }, S = () => E(), T = (f) => {
254
+ M.delete(f.pointerId), E();
255
+ };
256
+ s.addEventListener("mousedown", m, !0), s.addEventListener("focusin", m, !0), s.addEventListener("focusout", S, !0), s.addEventListener("pointerup", T, !0), s.addEventListener("pointercancel", T, !0), s.addEventListener("lostpointercapture", T, !0), s.addEventListener("visibilitychange", x), v.addEventListener("blur", B), v.addEventListener("focus", S);
257
+ const A = (f, u, w) => {
258
+ u.root.replaceChildren();
259
+ const g = s.createElement("div");
260
+ if (g.setAttribute("data-mini-app-remote-panel-status", ""), g.setAttribute("role", w ? "alert" : "status"), g.style.cssText = "position:fixed;right:16px;top:16px;max-width:calc(100vw - 32px);padding:16px;background:#172033;border:1px solid #526078;border-radius:10px;box-sizing:border-box", g.textContent = w ? "键位面板加载失败,请重试。" : "正在加载键位面板…", w) {
261
+ const I = s.createElement("button");
262
+ I.type = "button", I.textContent = "重试", I.style.marginLeft = "12px", I.addEventListener("click", () => J(f, u)), g.appendChild(I);
263
+ }
264
+ u.root.appendChild(g);
265
+ }, J = (f, u) => {
266
+ u.view || u.loading || !u.state.open || !u.state.available || (u.loading = !0, A(f, u, !1), R ?? (R = n().catch((w) => {
267
+ throw R = void 0, w;
268
+ })), R.then((w) => {
269
+ u.loading = !1, !(_ || h.get(f) !== u || !u.state.open || !u.state.available) && (u.root.replaceChildren(), u.view = w.createKeyboardPanelView({
270
+ root: u.root,
271
+ getAnchor: () => {
272
+ const g = t.getBoundingClientRect(), I = g.width / Math.max(1, u.state.viewport.width), H = g.height / Math.max(1, u.state.viewport.height), F = u.state.anchor;
273
+ return {
274
+ left: g.left + F.left * I,
275
+ top: g.top + F.top * H,
276
+ right: g.left + F.right * I,
277
+ bottom: g.top + F.bottom * H
278
+ };
279
+ },
280
+ onCommand: (g) => {
281
+ _ || h.get(f) !== u || (w.keyboardPanelCommandNeedsGameFocus(g) && t.focus({ preventScroll: !0 }), i({ type: "keyboard-panel-command", controllerId: f, command: g }));
282
+ }
283
+ }), u.view.update(u.state), E());
284
+ }).catch((w) => {
285
+ u.loading = !1, !_ && h.get(f) === u && (A(f, u, !0), o(w));
286
+ }));
287
+ };
288
+ return {
289
+ receive(f) {
290
+ if (_ || typeof f.controllerId != "string" || !Number.isSafeInteger(f.revision) || f.revision <= (O.get(f.controllerId) ?? 0) || b.has(f.controllerId))
291
+ return;
292
+ const { controllerId: u, state: w } = f;
293
+ O.set(u, f.revision);
294
+ const g = h.get(u);
295
+ if (w === null) {
296
+ b.add(u), g?.view?.dispose(), g?.root.remove(), h.delete(u);
297
+ for (const [F, Z] of M) Z === u && M.delete(F);
298
+ return;
299
+ }
300
+ if (g) {
301
+ g.state = w, g.root.hidden = !w.open || !w.available, g.view?.update(w), J(u, g), E();
302
+ return;
303
+ }
304
+ if (!w.open || !w.available) return;
305
+ const I = s.createElement("div");
306
+ I.setAttribute("data-mini-app-keyboard-ui", ""), I.setAttribute("data-mini-app-keyboard-controller", u), I.style.cssText = "position:absolute;left:0;top:0;width:0;height:0;z-index:2147483000;cursor:default;font:12px/1.5 system-ui,sans-serif;color:#e5e7eb;box-sizing:border-box", s.body.appendChild(I);
307
+ const H = {
308
+ state: w,
309
+ root: I,
310
+ loading: !1,
311
+ active: !1
312
+ };
313
+ I.addEventListener("pointerenter", () => E()), I.addEventListener("pointerleave", () => E()), I.addEventListener(
314
+ "pointerdown",
315
+ (F) => {
316
+ M.set(F.pointerId, u), E();
317
+ },
318
+ !0
319
+ ), h.set(u, H), J(u, H), E();
320
+ },
321
+ destroy() {
322
+ if (!_) {
323
+ E(!0), _ = !0, s.removeEventListener("mousedown", m, !0), s.removeEventListener("focusin", m, !0), s.removeEventListener("focusout", S, !0), s.removeEventListener("pointerup", T, !0), s.removeEventListener("pointercancel", T, !0), s.removeEventListener("lostpointercapture", T, !0), s.removeEventListener("visibilitychange", x), v.removeEventListener("blur", B), v.removeEventListener("focus", S);
324
+ for (const f of h.values())
325
+ f.view?.dispose(), f.root.remove();
326
+ h.clear(), O.clear(), b.clear(), M.clear();
327
+ }
328
+ }
329
+ };
330
+ }
331
+ const Te = {
332
+ report() {
333
+ },
334
+ reportEvent() {
335
+ },
336
+ flush() {
337
+ }
338
+ };
339
+ function tt(t) {
340
+ if (!t.enabled) return Te;
341
+ let i;
342
+ try {
343
+ const n = { business_line: t.businessLine };
344
+ i = Ve({
345
+ endpoint: We(n),
346
+ region: "cn",
347
+ resolveUserId: t.resolveUserId ?? (() => Promise.resolve("")),
348
+ onDelivery: t.onDelivery
349
+ });
350
+ } catch {
351
+ return Te;
352
+ }
353
+ return {
354
+ report(n, o = {}) {
355
+ try {
356
+ i.sendCustomPoint({
357
+ name: "simulator_load_stage",
358
+ timestamp: Date.now(),
359
+ payload: {
360
+ business_line: t.businessLine,
361
+ sdk_version: be,
362
+ renderer: "iframe-service-worker",
363
+ app_id: t.appId,
364
+ session_id: t.sessionId,
365
+ runtime_version: t.runtimeVersion,
366
+ stage: n,
367
+ ...o
368
+ }
369
+ });
370
+ } catch {
371
+ }
372
+ },
373
+ reportEvent(n, o, s) {
374
+ try {
375
+ i.sendCustomPoint({
376
+ name: n,
377
+ timestamp: Date.now(),
378
+ payload: {
379
+ business_line: t.businessLine,
380
+ sdk_version: be,
381
+ renderer: "iframe-service-worker",
382
+ app_id: t.appId,
383
+ simulator_session_id: t.sessionId,
384
+ runtime_version: t.runtimeVersion,
385
+ ...o
386
+ }
387
+ }), s?.flush && i.flush();
388
+ } catch {
389
+ }
390
+ },
391
+ flush() {
392
+ const n = () => {
393
+ try {
394
+ i.flush();
395
+ } catch {
396
+ }
397
+ };
398
+ try {
399
+ typeof queueMicrotask == "function" ? queueMicrotask(n) : setTimeout(n, 0);
400
+ } catch {
401
+ }
402
+ }
403
+ };
404
+ }
405
+ function z() {
406
+ try {
407
+ return typeof performance < "u" && typeof performance.now == "function" ? performance.now() : Date.now();
408
+ } catch {
409
+ return Date.now();
410
+ }
411
+ }
412
+ function L(t) {
413
+ return Math.max(0, Math.round(z() - t));
414
+ }
415
+ function Me(t, i, n, o = {}) {
416
+ try {
417
+ const s = rt(n);
418
+ if (!s) {
419
+ Object.keys(o).length > 0 && t.report(i, o);
420
+ return;
421
+ }
422
+ const { duration: v, ...h } = ot(s);
423
+ t.report(i, {
424
+ result: "success",
425
+ duration: h.network_duration,
426
+ ...o,
427
+ ...h
428
+ }), t.report(`${i}_download`, {
429
+ result: "success",
430
+ duration: v
431
+ });
432
+ } catch {
433
+ Object.keys(o).length > 0 && t.report(i, o);
434
+ }
435
+ }
436
+ function rt(t) {
437
+ if (typeof performance > "u" || !performance.getEntriesByName) return;
438
+ const i = typeof window > "u" ? t : new URL(t, window.location.href).href, n = performance.getEntriesByName(i, "resource");
439
+ return n[n.length - 1];
440
+ }
441
+ function ot(t) {
442
+ return {
443
+ network_duration: Math.round(t.duration),
444
+ dns_duration: Math.round(t.domainLookupEnd - t.domainLookupStart),
445
+ connect_duration: Math.round(t.connectEnd - t.connectStart),
446
+ ttfb_duration: Math.round(t.responseStart - t.requestStart),
447
+ duration: Math.round(t.responseEnd - t.responseStart),
448
+ bytes: t.transferSize
449
+ };
450
+ }
451
+ const nt = 8, st = {
452
+ version: nt
453
+ }, G = st.version, it = "miniapp-simulator:connect", kt = "inspectorPauseRuntime", Ie = "keyboardPanelPortal", at = 3e4, ke = 2, ct = 100;
454
+ function St(t) {
455
+ if (!t.appId.trim()) throw new Error("remote simulator appId is required");
456
+ if (!t.businessLine.trim()) throw new Error("remote simulator businessLine is required");
457
+ if (t.auditContext && (!t.auditContext.reviewTaskId.trim() || !t.auditContext.packageVersion.trim()))
458
+ throw new Error("remote simulator auditContext requires reviewTaskId and packageVersion");
459
+ const i = ut(t.gateway), n = gt(t.mount), o = wt([t.serviceUrl, ...t.fallbackServiceUrls ?? []]), s = document.createElement("iframe");
460
+ s.className = t.className ?? "", s.allow = t.iframeAllow ?? "camera; microphone; autoplay; geolocation", s.referrerPolicy = "no-referrer", s.style.display = "block", s.style.width = "100%", s.style.height = "100%", s.style.border = "0";
461
+ const v = t.timeout ?? at, h = /* @__PURE__ */ new Map(), O = ze(t.options), b = new Map(Object.entries(t.hostApi ?? {})), _ = /* @__PURE__ */ new Map(), R = /* @__PURE__ */ new Map();
462
+ let M = 0, P = Ae(), E, N, W = !1, m, B, x, S = !1, T, A = !1, J = "single", f = null, u = !1;
463
+ const w = z();
464
+ let g = w, I = w, H, F, Z = t.auditContext?.packageHash;
465
+ const de = /* @__PURE__ */ new Map(), fe = /* @__PURE__ */ new Map(), ie = /* @__PURE__ */ new Map(), ae = /* @__PURE__ */ new Map(), X = /* @__PURE__ */ new Set(), k = tt({
466
+ enabled: t.tracker !== !1,
467
+ businessLine: t.businessLine,
468
+ appId: t.appId,
469
+ sessionId: P,
470
+ resolveUserId: () => Promise.resolve(typeof F?.userId == "string" ? F.userId : ""),
471
+ onDelivery: t.onTrackerDelivery
472
+ });
473
+ let pe, Q;
474
+ const Ue = new Promise((e, r) => {
475
+ pe = e, Q = r;
476
+ });
477
+ let oe;
478
+ function K() {
479
+ oe !== void 0 && (window.clearTimeout(oe), oe = void 0);
480
+ }
481
+ function me() {
482
+ K(), oe = window.setTimeout(() => {
483
+ const e = new Error(`remote simulator timed out after ${v}ms`);
484
+ u = !0, k.report("client_ready", {
485
+ result: "timeout",
486
+ duration: L(w)
487
+ }), k.flush(), x(e), Q(e);
488
+ }, v);
489
+ }
490
+ ve();
491
+ function Pe(e) {
492
+ const r = R.get(e.requestId);
493
+ if (r)
494
+ if (R.delete(e.requestId), window.clearTimeout(r.timer), e.ok)
495
+ k.report("remote_request", {
496
+ type: r.method,
497
+ request_id: e.requestId,
498
+ result: "success",
499
+ duration: L(r.startedAt)
500
+ }), r.resolve(e.result);
501
+ else {
502
+ const a = new Error(
503
+ e.error?.message ?? "remote simulator request failed"
504
+ );
505
+ e.error?.code && (a.code = e.error.code), k.report("remote_request", {
506
+ type: r.method,
507
+ request_id: e.requestId,
508
+ result: "fail",
509
+ duration: L(r.startedAt),
510
+ error_name: e.error?.code,
511
+ message: a.message.slice(0, 512)
512
+ }), r.reject(a);
513
+ }
514
+ }
515
+ async function Oe(e, r) {
516
+ const a = b.get(e.event);
517
+ if (typeof a != "function") {
518
+ r.postMessage({
519
+ type: "host-api-response",
520
+ requestId: e.requestId,
521
+ ok: !1,
522
+ error: { message: `hostApi handler is unavailable: ${e.event}` }
523
+ });
524
+ return;
525
+ }
526
+ try {
527
+ const l = await a(e.request);
528
+ r.postMessage({
529
+ type: "host-api-response",
530
+ requestId: e.requestId,
531
+ ok: !0,
532
+ result: l
533
+ });
534
+ } catch (l) {
535
+ const d = l;
536
+ r.postMessage({
537
+ type: "host-api-response",
538
+ requestId: e.requestId,
539
+ ok: !1,
540
+ error: {
541
+ message: d instanceof Error ? d.message : String(l),
542
+ code: d?.code
543
+ }
544
+ });
545
+ }
546
+ }
547
+ async function Ne(e, r) {
548
+ const a = b.get("request");
549
+ if (typeof a != "function") {
550
+ r.postMessage({
551
+ type: "host-request-response",
552
+ requestId: e.requestId,
553
+ ok: !1,
554
+ error: { message: "host request implementation is unavailable" }
555
+ });
556
+ return;
557
+ }
558
+ const l = new AbortController();
559
+ _.set(e.requestId, l);
560
+ try {
561
+ const d = await Je(a, e.options, {
562
+ signal: l.signal,
563
+ onHeaders(C) {
564
+ r.postMessage({
565
+ type: "host-request-event",
566
+ requestId: e.requestId,
567
+ event: "headers",
568
+ payload: C
569
+ });
570
+ },
571
+ onChunk(C) {
572
+ r.postMessage({
573
+ type: "host-request-event",
574
+ requestId: e.requestId,
575
+ event: "chunk",
576
+ payload: C
577
+ });
578
+ }
579
+ });
580
+ r.postMessage({
581
+ type: "host-request-response",
582
+ requestId: e.requestId,
583
+ ok: !0,
584
+ result: d
585
+ });
586
+ } catch (d) {
587
+ const C = d;
588
+ r.postMessage({
589
+ type: "host-request-response",
590
+ requestId: e.requestId,
591
+ ok: !1,
592
+ error: {
593
+ message: C instanceof Error ? C.message : String(d),
594
+ code: C?.code
595
+ }
596
+ });
597
+ } finally {
598
+ _.delete(e.requestId);
599
+ }
600
+ }
601
+ function xe(e) {
602
+ _.get(e.requestId)?.abort();
603
+ }
604
+ function Fe(e) {
605
+ if (e.event === "auditTelemetry") {
606
+ const a = $e(e.payload);
607
+ a && He(a);
608
+ return;
609
+ }
610
+ e.event === "inspectorChange" && (A = !!e.payload?.enabled);
611
+ const r = Be(e.payload);
612
+ if (e.event === "auditStarted") {
613
+ const a = De(e.payload);
614
+ a && we(a);
615
+ }
616
+ if (e.event === "auditProgress" && (!r || r === p.sessionId) && (p.sawProgress = !0, ye(p.sessionId)), e.event === "auditReport" || e.event === "auditFailed") {
617
+ if (r && r === p.terminalSessionId) return;
618
+ if (ce(r), r && !X.has(r))
619
+ if (e.event === "auditReport") {
620
+ const a = e.payload;
621
+ $(
622
+ "miniapp_audit_result",
623
+ r,
624
+ Ee(a?.report, a?.metrics),
625
+ !0
626
+ );
627
+ } else {
628
+ const a = e.payload?.code;
629
+ $(
630
+ "miniapp_audit_result",
631
+ r,
632
+ [
633
+ {
634
+ name: "total_score",
635
+ result: "loadFailed",
636
+ message: typeof a == "string" ? a : "AUDIT_FAILED"
637
+ }
638
+ ],
639
+ !0
640
+ );
641
+ }
642
+ }
643
+ ee(e.event, e.payload);
644
+ }
645
+ function He(e) {
646
+ const r = e.fields.attempt_no;
647
+ typeof r == "number" && Number.isFinite(r) && de.set(e.sessionId, r), e.name === "miniapp_audit_result" && X.add(e.sessionId), $(
648
+ e.name,
649
+ e.sessionId,
650
+ [e.fields],
651
+ e.flush === !0
652
+ );
653
+ }
654
+ function $(e, r, a, l = !1) {
655
+ a.forEach((d, C) => {
656
+ const se = V({
657
+ app_type: d.app_type,
658
+ policy_version: d.policy_version,
659
+ rules_version: d.rules_version,
660
+ probe_version: d.probe_version
661
+ });
662
+ ae.set(r, {
663
+ ...ae.get(r),
664
+ ...se
665
+ });
666
+ const Y = { ...ae.get(r), ...d };
667
+ if (e === "miniapp_audit_session") {
668
+ d.stage === "started" && !ie.has(r) && ie.set(r, Date.now());
669
+ const _e = typeof d.count == "number" ? d.count : fe.get(r) ?? 0;
670
+ Y.count = _e, Y.duration = d.duration ?? Math.max(0, Date.now() - (ie.get(r) ?? Date.now())), fe.set(r, _e + 1);
671
+ }
672
+ k.reportEvent(
673
+ e,
674
+ V({
675
+ ...Y,
676
+ review_task_id: t.auditContext?.reviewTaskId,
677
+ audit_session_id: r,
678
+ attempt_no: Y.attempt_no ?? de.get(r) ?? 1,
679
+ package_version: t.auditContext?.packageVersion,
680
+ package_hash: Z,
681
+ runtime_version: H
682
+ }),
683
+ { flush: l && C === a.length - 1 }
684
+ );
685
+ });
686
+ }
687
+ const p = {
688
+ deadlineTimer: null,
689
+ stallTimer: null,
690
+ sessionId: null,
691
+ sawProgress: !1,
692
+ runtimeHungReport: null,
693
+ terminalSessionId: null,
694
+ terminalReport: null
695
+ };
696
+ function Be(e) {
697
+ if (!e || typeof e != "object") return null;
698
+ const r = e.sessionId;
699
+ return typeof r == "string" && r ? r : null;
700
+ }
701
+ function $e(e) {
702
+ if (!e || typeof e != "object") return null;
703
+ const r = e, a = /* @__PURE__ */ new Set([
704
+ "miniapp_audit_session",
705
+ "miniapp_audit_paint",
706
+ "miniapp_audit_incident",
707
+ "miniapp_audit_package",
708
+ "miniapp_audit_result"
709
+ ]);
710
+ return typeof r.name != "string" || !a.has(r.name) || typeof r.sessionId != "string" || !r.sessionId || !r.fields || typeof r.fields != "object" || Array.isArray(r.fields) ? null : r;
711
+ }
712
+ function De(e) {
713
+ if (!e || typeof e != "object") return null;
714
+ const r = e;
715
+ return r.ok === !0 && typeof r.sessionId == "string" && r.sessionId ? r : null;
716
+ }
717
+ function ce(e) {
718
+ e && p.sessionId && e !== p.sessionId || (p.deadlineTimer !== null && clearTimeout(p.deadlineTimer), p.stallTimer !== null && clearTimeout(p.stallTimer), p.deadlineTimer = null, p.stallTimer = null, p.sessionId = null, p.sawProgress = !1, p.runtimeHungReport = null);
719
+ }
720
+ function he(e) {
721
+ if (p.sessionId !== e) return;
722
+ const r = p.runtimeHungReport, a = p.sawProgress;
723
+ if (p.deadlineTimer !== null && clearTimeout(p.deadlineTimer), p.stallTimer !== null && clearTimeout(p.stallTimer), p.deadlineTimer = null, p.stallTimer = null, p.sessionId = null, p.runtimeHungReport = null, $("miniapp_audit_session", e, [
724
+ { name: "interrupted", stage: "interrupted", result: "runtime_hung" }
725
+ ]), !r) {
726
+ $(
727
+ "miniapp_audit_result",
728
+ e,
729
+ [{ name: "total_score", result: "loadFailed", message: "RUNTIME_HUNG" }],
730
+ !0
731
+ ), X.add(e), ee("auditFailed", {
732
+ sessionId: e,
733
+ code: "RUNTIME_HUNG",
734
+ message: "评测超时未返回:Runtime 失去响应"
735
+ });
736
+ return;
737
+ }
738
+ const l = Qe(r, a);
739
+ p.terminalSessionId = e, p.terminalReport = l, $("miniapp_audit_result", e, Ee(l), !0), X.add(e), ee("auditReport", {
740
+ sessionId: e,
741
+ source: "host-watchdog",
742
+ report: l
743
+ });
744
+ }
745
+ function ye(e) {
746
+ if (!e || p.sessionId !== e) return;
747
+ p.stallTimer !== null && clearTimeout(p.stallTimer);
748
+ const r = setTimeout(() => {
749
+ p.stallTimer === r && he(e);
750
+ }, Ze);
751
+ p.stallTimer = r;
752
+ }
753
+ function we(e, r) {
754
+ ce(), p.terminalSessionId = null, p.terminalReport = null, p.sessionId = e.sessionId, p.runtimeHungReport = e.runtimeHungReport ?? null, p.sawProgress = !1, ye(e.sessionId);
755
+ const l = (typeof e.evaluationDurationMs == "number" ? e.evaluationDurationMs : r?.durationMs ?? 3e4) + Xe, d = e.sessionId, C = setTimeout(() => {
756
+ p.deadlineTimer === C && he(d);
757
+ }, l);
758
+ p.deadlineTimer = C;
759
+ }
760
+ function ge(e, r) {
761
+ let a = h.get(e);
762
+ a || (a = /* @__PURE__ */ new Set(), h.set(e, a)), a.add(r);
763
+ }
764
+ function ze(e) {
765
+ if (!e) return {};
766
+ const { onRouterChange: r, onScreenShot: a, ...l } = e;
767
+ return r && ge(
768
+ "routerChange",
769
+ (d) => r(d)
770
+ ), a && ge("screenShot", (d) => a(d)), l;
771
+ }
772
+ s.onload = () => {
773
+ S || (W && (ve(), me()), W = !0, f && Me(k, "runtime_document", f.href, {
774
+ result: "success",
775
+ duration: L(g)
776
+ }), je());
777
+ };
778
+ async function je() {
779
+ if (S || !f) return;
780
+ const e = E, r = P, a = await dt(b);
781
+ if (F = a, S || !f || e !== E) return;
782
+ const l = {
783
+ type: it,
784
+ protocolVersion: G,
785
+ sessionId: r,
786
+ appId: t.appId,
787
+ businessLine: t.businessLine,
788
+ tracker: t.tracker !== !1,
789
+ auditContext: t.auditContext,
790
+ gateway: i,
791
+ userInfo: a,
792
+ hostApiMethods: Se(b),
793
+ hostApiStubs: Re(b),
794
+ clientCapabilities: [Ie],
795
+ options: O
796
+ };
797
+ I = z(), s.contentWindow?.postMessage(l, f.origin, [e.port2]);
798
+ }
799
+ s.onerror = () => {
800
+ N?.destroy();
801
+ const e = new Error(
802
+ `remote simulator failed to load: ${f?.href ?? o[0]}`
803
+ );
804
+ k.report("runtime_document", {
805
+ result: "fail",
806
+ duration: L(g),
807
+ message: e.message.slice(0, 512)
808
+ }), k.flush(), x(e), u ? ee("error", {
809
+ code: "LOAD_FAILED",
810
+ message: e.message,
811
+ url: f?.href,
812
+ cause: e
813
+ }) : (u = !0, K(), Q(e));
814
+ }, pt(o, k).then(
815
+ (e) => {
816
+ S || (f = e, g = z(), me(), s.src = e.href, n.appendChild(s));
817
+ },
818
+ (e) => {
819
+ const r = e instanceof Error ? e : new Error(String(e));
820
+ u = !0, K(), k.report("client_ready", {
821
+ result: "fail",
822
+ duration: L(w),
823
+ message: r.message.slice(0, 512)
824
+ }), k.flush(), x(r), Q(r);
825
+ }
826
+ );
827
+ async function y(e, ...r) {
828
+ return ue(`${P}-${++M}`, e, ...r);
829
+ }
830
+ async function ue(e, r, ...a) {
831
+ if (S) throw new Error("remote simulator has been destroyed");
832
+ await m;
833
+ const l = vt(a);
834
+ return new Promise((d, C) => {
835
+ const se = z(), Y = window.setTimeout(() => {
836
+ R.delete(e), k.report("remote_request", {
837
+ type: r,
838
+ request_id: e,
839
+ result: "timeout",
840
+ duration: L(se)
841
+ }), C(new Error(`remote simulator ${r} timed out after ${v}ms`));
842
+ }, v);
843
+ R.set(e, { resolve: d, reject: C, timer: Y, method: r, startedAt: se }), E.port1.postMessage({ type: "request", requestId: e, method: r, args: a }, l);
844
+ });
845
+ }
846
+ return {
847
+ iframe: s,
848
+ ready: Ue,
849
+ load: () => y("load"),
850
+ async loadZip(e, r) {
851
+ const a = `${P}-${++M}`, l = z();
852
+ try {
853
+ const d = await Le(e).arrayBuffer();
854
+ return Z = t.auditContext?.packageHash ?? await Ce(d), k.report("package_materialize", {
855
+ request_id: a,
856
+ result: "success",
857
+ duration: L(l),
858
+ bytes: d.byteLength,
859
+ type: "zip"
860
+ }), ue(a, "loadZip", {
861
+ buffer: d,
862
+ options: r
863
+ });
864
+ } catch (d) {
865
+ throw k.report("package_materialize", {
866
+ request_id: a,
867
+ result: "fail",
868
+ duration: L(l),
869
+ type: "zip",
870
+ message: re(d).slice(0, 512)
871
+ }), d;
872
+ }
873
+ },
874
+ loadFiles: async (e, r) => {
875
+ const a = `${P}-${++M}`, l = z();
876
+ try {
877
+ const d = await _t(e);
878
+ return Z = t.auditContext?.packageHash ?? await Et(d), k.report("package_materialize", {
879
+ request_id: a,
880
+ result: "success",
881
+ duration: L(l),
882
+ type: "files",
883
+ count: Object.keys(d).length,
884
+ bytes: bt(d)
885
+ }), ue(a, "loadFiles", {
886
+ files: d,
887
+ options: r
888
+ });
889
+ } catch (d) {
890
+ throw k.report("package_materialize", {
891
+ request_id: a,
892
+ result: "fail",
893
+ duration: L(l),
894
+ type: "files",
895
+ message: re(d).slice(0, 512)
896
+ }), d;
897
+ }
898
+ },
899
+ loadApp: (e, r) => y("loadApp", e, r),
900
+ unload: () => void y("unload"),
901
+ reload: () => y("reload"),
902
+ capture: (e) => y("capture", e),
903
+ setViewport: (e) => {
904
+ y("setViewport", e);
905
+ },
906
+ switchContentMode: (e) => y("switchContentMode", e),
907
+ switchPhoneFrame: (e) => y("switchPhoneFrame", e),
908
+ permissionSheet: {
909
+ show: (e) => y("permissionSheet.show", e),
910
+ hide: () => {
911
+ y("permissionSheet.hide");
912
+ }
913
+ },
914
+ notePreview: {
915
+ update: (e) => {
916
+ y("notePreview.update", e);
917
+ },
918
+ updateUser: (e) => {
919
+ y("notePreview.updateUser", e);
920
+ },
921
+ updateAppCard: (e) => {
922
+ y("notePreview.updateAppCard", e);
923
+ }
924
+ },
925
+ widgetCover: {
926
+ update: (e) => {
927
+ y("widgetCover.update", e);
928
+ }
929
+ },
930
+ redirectTo: (e, r) => y("router.redirectTo", e, r),
931
+ getCurrentRoute: () => y("router.getRoute"),
932
+ screenShot: () => y("screenShot"),
933
+ setAutoScreenShot: (e) => y("setAutoScreenShot", e),
934
+ inspector: {
935
+ enable: () => {
936
+ A = !0, y("inspector.enable");
937
+ },
938
+ disable: () => {
939
+ A = !1, y("inspector.disable");
940
+ },
941
+ toggle: () => {
942
+ A = !A, y("inspector.toggle");
943
+ },
944
+ isEnabled: () => A,
945
+ clear: () => {
946
+ y("inspector.clear");
947
+ },
948
+ setSelectionMode: (e) => {
949
+ J = e, y("inspector.setSelectionMode", e);
950
+ },
951
+ getSelectionMode: () => J,
952
+ getSceneTree: () => y("inspector.getSceneTree"),
953
+ selectByRef: (e) => y("inspector.selectByRef", e)
954
+ },
955
+ hostApi: {
956
+ set(e, r) {
957
+ b.set(e, r), ne();
958
+ },
959
+ registerAll(e) {
960
+ for (const [r, a] of Object.entries(e)) b.set(r, a);
961
+ ne();
962
+ },
963
+ remove(e) {
964
+ b.delete(e), ne();
965
+ },
966
+ clear() {
967
+ b.clear(), ne();
968
+ },
969
+ has: (e) => b.has(e),
970
+ emit: (e, r) => {
971
+ y("hostApi.emit", e, r);
972
+ }
973
+ },
974
+ audit: {
975
+ start: async (e) => {
976
+ const r = await y("audit.start", e);
977
+ return r.ok && we(r, e), r;
978
+ },
979
+ stop: async () => {
980
+ p.terminalReport || await y("audit.stop");
981
+ },
982
+ status: () => p.terminalReport ? Promise.resolve({ phase: "failed", sessionId: p.terminalSessionId }) : y("audit.status"),
983
+ report: () => p.terminalReport ? Promise.resolve(p.terminalReport) : y("audit.report"),
984
+ setPolicy: async (e) => {
985
+ await y("audit.setPolicy", e);
986
+ }
987
+ },
988
+ invoke: y,
989
+ on(e, r) {
990
+ let a = h.get(e);
991
+ return a || (a = /* @__PURE__ */ new Set(), h.set(e, a)), a.add(r), () => a?.delete(r);
992
+ },
993
+ destroy(e) {
994
+ if (S) return;
995
+ S = !0, N?.destroy(), N = void 0, T?.();
996
+ const r = p.sessionId;
997
+ r && ($("miniapp_audit_session", r, [
998
+ { name: "interrupted", stage: "interrupted", result: "session_interrupted" }
999
+ ]), $(
1000
+ "miniapp_audit_result",
1001
+ r,
1002
+ [{ name: "total_score", result: "loadFailed", message: "SESSION_INTERRUPTED" }],
1003
+ !0
1004
+ ), X.add(r), ee("auditFailed", {
1005
+ sessionId: r,
1006
+ code: "SESSION_INTERRUPTED",
1007
+ message: "评测会话中断:宿主已销毁模拟器会话"
1008
+ })), K(), ce(), Tt(E.port1, P, ++M, e), x(new Error("remote simulator has been destroyed"));
1009
+ for (const a of R.values())
1010
+ window.clearTimeout(a.timer), a.reject(new Error("remote simulator has been destroyed"));
1011
+ R.clear();
1012
+ for (const a of _.values()) a.abort();
1013
+ _.clear(), E.port1.close(), k.flush(), s.remove(), h.clear();
1014
+ }
1015
+ };
1016
+ function ne() {
1017
+ return y("hostApi.sync", Se(b), Re(b));
1018
+ }
1019
+ function ve() {
1020
+ N?.destroy(), N = void 0, T?.(), T = void 0;
1021
+ for (const a of _.values()) a.abort();
1022
+ if (_.clear(), E) {
1023
+ const a = new Error("remote simulator runtime navigated");
1024
+ x(a);
1025
+ for (const l of R.values())
1026
+ window.clearTimeout(l.timer), l.reject(a);
1027
+ R.clear(), E.port1.close(), P = Ae();
1028
+ }
1029
+ M = 0, E = new MessageChannel(), m = new Promise((a, l) => {
1030
+ B = a, x = l;
1031
+ }), m.catch(() => {
1032
+ });
1033
+ const e = E, r = m;
1034
+ N = et(
1035
+ s,
1036
+ (a) => {
1037
+ !S && e === E && e.port1.postMessage(a);
1038
+ },
1039
+ async () => {
1040
+ const a = await r;
1041
+ if (S || e !== E || !f)
1042
+ throw new Error("remote simulator session ended");
1043
+ if (!a.capabilities.includes(Ie))
1044
+ throw new Error("remote simulator keyboard panel is unavailable");
1045
+ const d = await import(
1046
+ /* @vite-ignore */
1047
+ ft(a, f).href
1048
+ );
1049
+ if (typeof d.createKeyboardPanelView != "function" || typeof d.keyboardPanelCommandNeedsGameFocus != "function")
1050
+ throw new Error("remote runtime UI exports are invalid");
1051
+ return d;
1052
+ },
1053
+ (a) => console.error("[miniapp-simulator] 键位面板加载失败", a)
1054
+ ), e.port1.onmessage = (a) => {
1055
+ if (e !== E) return;
1056
+ const l = a.data;
1057
+ if (l?.type === "keyboard-panel-state") {
1058
+ N?.receive(l);
1059
+ return;
1060
+ }
1061
+ if (l?.type === "ready") {
1062
+ if (l.protocolVersion !== G) {
1063
+ const d = new Error(
1064
+ `unsupported remote simulator protocol: ${l.protocolVersion} (client=${G})`
1065
+ );
1066
+ k.report("runtime_handshake", {
1067
+ result: "protocol_mismatch",
1068
+ duration: L(I),
1069
+ runtime_version: l.runtimeVersion
1070
+ }), k.flush(), x(d), u || (u = !0, K(), Q(d));
1071
+ return;
1072
+ }
1073
+ H = l.runtimeVersion, T?.(), T = Ge(s, (d) => {
1074
+ e.port1.postMessage({ type: "worker-visibility", visible: d });
1075
+ }), k.report("runtime_handshake", {
1076
+ result: "success",
1077
+ duration: L(I),
1078
+ runtime_version: H
1079
+ }), k.report("client_ready", {
1080
+ result: "success",
1081
+ duration: L(w),
1082
+ runtime_version: H
1083
+ }), B(l), K(), u || (u = !0, pe(l));
1084
+ return;
1085
+ }
1086
+ if (l?.type === "response") {
1087
+ Pe(l);
1088
+ return;
1089
+ }
1090
+ if (l?.type === "host-api-request") {
1091
+ Oe(l, e.port1);
1092
+ return;
1093
+ }
1094
+ if (l?.type === "host-request") {
1095
+ Ne(l, e.port1);
1096
+ return;
1097
+ }
1098
+ if (l?.type === "host-request-abort") {
1099
+ xe(l);
1100
+ return;
1101
+ }
1102
+ l?.type === "event" && Fe(l);
1103
+ }, e.port1.start();
1104
+ }
1105
+ function ee(e, r) {
1106
+ for (const a of [e, "*"])
1107
+ for (const l of h.get(a) ?? []) l(r);
1108
+ }
1109
+ }
1110
+ function ut(t) {
1111
+ if (!t) return;
1112
+ const i = {};
1113
+ for (const [n, o] of Object.entries(t)) {
1114
+ if (typeof o != "string" || !o.trim())
1115
+ throw new Error(`remote simulator gateway.${n} must be a non-empty HTTPS URL`);
1116
+ const s = o.trim().replace(/\/+$/, "");
1117
+ let v;
1118
+ try {
1119
+ v = new URL(s);
1120
+ } catch {
1121
+ throw new Error(`remote simulator gateway.${n} must be an absolute HTTPS URL`);
1122
+ }
1123
+ if (!lt(v))
1124
+ throw new Error(
1125
+ `remote simulator gateway.${n} must use HTTPS (HTTP is allowed only for loopback development)`
1126
+ );
1127
+ i[n] = s;
1128
+ }
1129
+ if (!i.edith)
1130
+ throw new Error("remote simulator gateway.edith is required");
1131
+ if (!i.www)
1132
+ throw new Error("remote simulator gateway.www is required");
1133
+ return i;
1134
+ }
1135
+ function lt(t) {
1136
+ return t.protocol === "https:" ? !0 : t.protocol === "http:" && (t.hostname === "localhost" || t.hostname === "127.0.0.1" || t.hostname === "[::1]");
1137
+ }
1138
+ function Se(t) {
1139
+ return [...t].filter(([, i]) => typeof i == "function").map(([i]) => i);
1140
+ }
1141
+ async function dt(t) {
1142
+ const i = t.get("getUserInfo");
1143
+ if (typeof i == "function")
1144
+ try {
1145
+ const n = await i({
1146
+ event: "getUserInfo",
1147
+ message: {},
1148
+ callbackId: ""
1149
+ });
1150
+ return n && typeof n == "object" ? n : void 0;
1151
+ } catch {
1152
+ return;
1153
+ }
1154
+ }
1155
+ function Re(t) {
1156
+ return Object.fromEntries(
1157
+ [...t].filter((i) => {
1158
+ const n = i[1];
1159
+ return typeof n != "function" && typeof n.toast == "string";
1160
+ })
1161
+ );
1162
+ }
1163
+ function ft(t, i) {
1164
+ const n = t.runtimeModuleUrl;
1165
+ if (typeof n != "string" || !n)
1166
+ throw new Error("remote runtime module URL is unavailable");
1167
+ const o = new URL(n), s = o.protocol === "http:" && o.origin === i.origin && ["localhost", "127.0.0.1", "[::1]"].includes(o.hostname);
1168
+ if (o.protocol !== "https:" && !s || o.username || o.password || o.hash)
1169
+ throw new Error("unsupported remote runtime module URL");
1170
+ return o;
1171
+ }
1172
+ class j extends Error {
1173
+ constructor(i, n, o, s) {
1174
+ super(i), this.kind = n, this.retryable = o, this.status = s, this.name = "ManifestRequestError";
1175
+ }
1176
+ }
1177
+ async function pt(t, i) {
1178
+ const n = [], o = new Set(t.map((s) => s.href));
1179
+ for (let s = 1; s <= ke; s += 1) {
1180
+ for (const [v, h] of t.entries()) {
1181
+ if (s > 1 && !o.has(h.href)) continue;
1182
+ const O = z();
1183
+ try {
1184
+ const b = await mt(h), _ = qe(h);
1185
+ return Me(i, "runtime_manifest", _.href, {
1186
+ result: "success",
1187
+ duration: L(O),
1188
+ type: v === 0 ? "primary" : "fallback",
1189
+ count: s
1190
+ }), b;
1191
+ } catch (b) {
1192
+ const _ = ht(b);
1193
+ i.report("runtime_manifest", {
1194
+ result: "fail",
1195
+ duration: L(O),
1196
+ type: v === 0 ? "primary" : "fallback",
1197
+ count: s,
1198
+ ..._.status === void 0 ? { error_name: _.kind } : { code: _.status },
1199
+ message: _.message.slice(0, 512)
1200
+ }), n.push(`${h.href} attempt ${s}: ${_.message}`), _.retryable || o.delete(h.href);
1201
+ }
1202
+ }
1203
+ if (s >= ke || o.size === 0) break;
1204
+ await yt();
1205
+ }
1206
+ throw new Error(`remote simulator services unavailable: ${n.join("; ")}`);
1207
+ }
1208
+ async function mt(t) {
1209
+ const i = qe(t);
1210
+ i.searchParams.set("protocolVersion", String(G));
1211
+ let n;
1212
+ try {
1213
+ n = await fetch(i, {
1214
+ method: "GET",
1215
+ credentials: "omit",
1216
+ cache: "no-store"
1217
+ });
1218
+ } catch (v) {
1219
+ throw new j(
1220
+ `remote simulator manifest network error: ${re(v)}`,
1221
+ "MANIFEST_NETWORK_ERROR",
1222
+ !0
1223
+ );
1224
+ }
1225
+ if (!n.ok)
1226
+ throw new j(
1227
+ `remote simulator manifest request failed: HTTP ${n.status}`,
1228
+ "MANIFEST_HTTP_ERROR",
1229
+ !0,
1230
+ n.status
1231
+ );
1232
+ let o;
1233
+ try {
1234
+ o = await n.json();
1235
+ } catch (v) {
1236
+ throw new j(
1237
+ `remote simulator manifest JSON is invalid: ${re(v)}`,
1238
+ "MANIFEST_INVALID_JSON",
1239
+ !0
1240
+ );
1241
+ }
1242
+ if (typeof o.buildId != "string" || !o.buildId || typeof o.documentUrl != "string" || !o.documentUrl)
1243
+ throw new j(
1244
+ "remote simulator manifest response is invalid",
1245
+ "MANIFEST_INVALID_RESPONSE",
1246
+ !1
1247
+ );
1248
+ if (o.protocolVersion !== G)
1249
+ throw new j(
1250
+ `unsupported remote simulator protocol: ${String(o.protocolVersion)} (client=${G})`,
1251
+ "MANIFEST_PROTOCOL_MISMATCH",
1252
+ !1
1253
+ );
1254
+ const s = new URL(o.documentUrl, i);
1255
+ if (s.origin !== t.origin)
1256
+ throw new j(
1257
+ `remote simulator document origin mismatch: ${s.origin} (service=${t.origin})`,
1258
+ "MANIFEST_ORIGIN_MISMATCH",
1259
+ !1
1260
+ );
1261
+ return s;
1262
+ }
1263
+ function ht(t) {
1264
+ return t instanceof j ? t : new j(re(t), "MANIFEST_UNKNOWN_ERROR", !1);
1265
+ }
1266
+ function yt() {
1267
+ return new Promise((t) => window.setTimeout(t, ct));
1268
+ }
1269
+ function qe(t) {
1270
+ const i = t.href.endsWith("/") ? t : new URL(`${t.href}/`), n = new URL("runtime-manifest", i);
1271
+ return n.searchParams.set("protocolVersion", String(G)), n;
1272
+ }
1273
+ function wt(t) {
1274
+ const i = /* @__PURE__ */ new Set(), n = [];
1275
+ for (const o of t) {
1276
+ const s = new URL(o, window.location.href), v = s.href.endsWith("/") ? s : new URL(`${s.href}/`);
1277
+ i.has(v.href) || (i.add(v.href), n.push(v));
1278
+ }
1279
+ return n;
1280
+ }
1281
+ function re(t) {
1282
+ return t instanceof Error ? t.message : String(t);
1283
+ }
1284
+ function gt(t) {
1285
+ const i = typeof t == "string" ? document.querySelector(t) : t;
1286
+ if (!i) throw new Error("remote simulator mount element not found");
1287
+ return i;
1288
+ }
1289
+ function Le(t) {
1290
+ if (t instanceof Blob) return t;
1291
+ const i = t instanceof ArrayBuffer ? t : Uint8Array.from(t).buffer;
1292
+ return new Blob([i]);
1293
+ }
1294
+ function vt(t) {
1295
+ const i = /* @__PURE__ */ new Set(), n = (o) => {
1296
+ if (o instanceof ArrayBuffer) {
1297
+ i.add(o);
1298
+ return;
1299
+ }
1300
+ if (ArrayBuffer.isView(o)) {
1301
+ i.add(o.buffer);
1302
+ return;
1303
+ }
1304
+ if (!(!o || typeof o != "object")) {
1305
+ if (Array.isArray(o)) {
1306
+ o.forEach(n);
1307
+ return;
1308
+ }
1309
+ Object.values(o).forEach(n);
1310
+ }
1311
+ };
1312
+ return n(t), [...i];
1313
+ }
1314
+ async function _t(t) {
1315
+ return Object.fromEntries(
1316
+ await Promise.all(
1317
+ Object.entries(t).map(async ([i, n]) => [
1318
+ i,
1319
+ typeof n == "string" ? n : await Le(n).arrayBuffer()
1320
+ ])
1321
+ )
1322
+ );
1323
+ }
1324
+ function bt(t) {
1325
+ try {
1326
+ const i = new TextEncoder();
1327
+ return Object.values(t).reduce((n, o) => typeof o == "string" ? n + i.encode(o).byteLength : o instanceof ArrayBuffer || ArrayBuffer.isView(o) ? n + o.byteLength : n, 0);
1328
+ } catch {
1329
+ return;
1330
+ }
1331
+ }
1332
+ async function Et(t) {
1333
+ try {
1334
+ const i = [];
1335
+ for (const [n, o] of Object.entries(t).sort(([s], [v]) => s.localeCompare(v))) {
1336
+ const s = typeof o == "string" ? new TextEncoder().encode(o).byteLength : (o instanceof ArrayBuffer, o.byteLength);
1337
+ i.push(`${n.length}:${n}:${s}:`, o);
1338
+ }
1339
+ return Ce(await new Blob(i).arrayBuffer());
1340
+ } catch {
1341
+ return;
1342
+ }
1343
+ }
1344
+ async function Ce(t) {
1345
+ try {
1346
+ if (typeof crypto > "u" || !crypto.subtle) return;
1347
+ const i = await crypto.subtle.digest("SHA-256", t);
1348
+ return [...new Uint8Array(i)].map((n) => n.toString(16).padStart(2, "0")).join("");
1349
+ } catch {
1350
+ return;
1351
+ }
1352
+ }
1353
+ function Tt(t, i, n, o) {
1354
+ try {
1355
+ t.postMessage({
1356
+ type: "request",
1357
+ requestId: `${i}-${n}`,
1358
+ method: "destroy",
1359
+ args: [o]
1360
+ });
1361
+ } catch {
1362
+ }
1363
+ }
1364
+ function Ae() {
1365
+ return typeof crypto.randomUUID == "function" ? crypto.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
1366
+ }
1367
+ export {
1368
+ kt as R,
1369
+ G as a,
1370
+ St as c
1371
+ };