@fz-firefly/experience 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,25 +10,34 @@ pnpm add @fz-firefly/experience
10
10
 
11
11
  `rrweb` 和 `modern-screenshot` 已作为本包依赖自动安装;它们只在开启回放 / 截图时动态加载,不进入主包。
12
12
 
13
- ## 初始化
14
-
15
- 先初始化核心 SDK,再显式安装体验增强:
13
+ ## 初始化(Sentry 风格)
16
14
 
17
15
  ```ts
18
16
  import { initFirefly } from '@fz-firefly/vue'
19
- import { installExperience } from '@fz-firefly/experience'
17
+ import { experienceIntegration } from '@fz-firefly/experience'
20
18
 
21
19
  const firefly = initFirefly({
22
20
  dsn: '...',
23
21
  endpoint: '...',
24
22
  environment: 'production',
23
+ integrations: [
24
+ experienceIntegration({
25
+ whiteScreen: { screenshot: true },
26
+ replay: { mode: 'on-error' },
27
+ remote: true,
28
+ }),
29
+ ],
25
30
  })
31
+ ```
32
+
33
+ ## 登录后或运行时安装
34
+
35
+ 需要延迟安装时,可以直接使用低阶入口:
36
+
37
+ ```ts
38
+ import { installExperience } from '@fz-firefly/experience'
26
39
 
27
40
  const disposeExperience = installExperience(firefly.client, {
28
- whiteScreen: { screenshot: true },
29
- // 生产推荐 on-error:报错时上传最近一段录屏。
30
- replay: { mode: 'on-error' },
31
- // 用户连线:远程 console / storage / 录屏开关。
32
41
  remote: true,
33
42
  })
34
43
 
@@ -38,6 +47,6 @@ const disposeExperience = installExperience(firefly.client, {
38
47
 
39
48
  ## 说明
40
49
 
41
- - 不调用 `installExperience` 时,不会加载任何体验增强代码。
50
+ - 不 import / 不传入 `experienceIntegration` 时,不会加载任何体验增强代码。
42
51
  - 只有配置开启的能力会动态加载对应模块。
43
52
  - uni-app / Taro 的小程序环境没有 DOM,白屏、回放、用户连线仅适用于 Web / H5。
package/dist/index.cjs CHANGED
@@ -76,9 +76,11 @@ function normalizeExperienceOptions(value) {
76
76
  }
77
77
  // src/install.ts
78
78
  /**
79
- * 安装可选体验增强。
79
+ * 低阶安装入口。
80
+ *
81
+ * 常规接入推荐 `initFirefly({ integrations: [experienceIntegration(...)] })`;
82
+ * 需要在登录后或运行时动态安装时,再直接调用 installExperience。
80
83
  *
81
- * 与核心 SDK 解耦:先 initFirefly 创建 client,再按需安装体验能力。
82
84
  * 只有开启的能力会被动态加载,主入口不会静态引入 rrweb / modern-screenshot。
83
85
  *
84
86
  * ```ts
@@ -116,6 +118,22 @@ function installExperience(client, options) {
116
118
  for (const dispose of disposers.splice(0)) dispose();
117
119
  };
118
120
  }
121
+ /**
122
+ * Sentry 风格的体验增强 integration。
123
+ *
124
+ * ```ts
125
+ * initFirefly({
126
+ * integrations: [experienceIntegration({ remote: true })],
127
+ * })
128
+ * ```
129
+ */
130
+ function experienceIntegration(options) {
131
+ return {
132
+ name: "experience",
133
+ setup: (client) => installExperience(client, options)
134
+ };
135
+ }
136
+ exports.experienceIntegration = experienceIntegration;
119
137
  exports.installExperience = installExperience;
120
138
  exports.normalizeExperienceOptions = normalizeExperienceOptions;
121
139
 
package/dist/index.d.cts CHANGED
@@ -1,9 +1,11 @@
1
1
  import { c as normalizeExperienceOptions, n as RemoteOptions, r as ReplayOptions, s as WhiteScreenOptions, t as ExperienceOptions } from "./options-C2iLgUnA.cjs";
2
- import { FireflyClient } from "@fz-firefly/core";
2
+ import { FireflyClient, FireflyIntegration } from "@fz-firefly/core";
3
3
  /**
4
- * 安装可选体验增强。
4
+ * 低阶安装入口。
5
+ *
6
+ * 常规接入推荐 `initFirefly({ integrations: [experienceIntegration(...)] })`;
7
+ * 需要在登录后或运行时动态安装时,再直接调用 installExperience。
5
8
  *
6
- * 与核心 SDK 解耦:先 initFirefly 创建 client,再按需安装体验能力。
7
9
  * 只有开启的能力会被动态加载,主入口不会静态引入 rrweb / modern-screenshot。
8
10
  *
9
11
  * ```ts
@@ -15,5 +17,15 @@ import { FireflyClient } from "@fz-firefly/core";
15
17
  * ```
16
18
  */
17
19
  export declare function installExperience(client: FireflyClient, options?: ExperienceOptions): () => void;
20
+ /**
21
+ * Sentry 风格的体验增强 integration。
22
+ *
23
+ * ```ts
24
+ * initFirefly({
25
+ * integrations: [experienceIntegration({ remote: true })],
26
+ * })
27
+ * ```
28
+ */
29
+ export declare function experienceIntegration(options?: ExperienceOptions): FireflyIntegration;
18
30
  export { type ExperienceOptions, type RemoteOptions, type ReplayOptions, type WhiteScreenOptions, normalizeExperienceOptions };
19
31
  //# sourceMappingURL=index.d.cts.map
package/dist/index.d.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import { c as normalizeExperienceOptions, n as RemoteOptions, r as ReplayOptions, s as WhiteScreenOptions, t as ExperienceOptions } from "./options-C2iLgUnA.js";
2
- import { FireflyClient } from "@fz-firefly/core";
2
+ import { FireflyClient, FireflyIntegration } from "@fz-firefly/core";
3
3
  /**
4
- * 安装可选体验增强。
4
+ * 低阶安装入口。
5
+ *
6
+ * 常规接入推荐 `initFirefly({ integrations: [experienceIntegration(...)] })`;
7
+ * 需要在登录后或运行时动态安装时,再直接调用 installExperience。
5
8
  *
6
- * 与核心 SDK 解耦:先 initFirefly 创建 client,再按需安装体验能力。
7
9
  * 只有开启的能力会被动态加载,主入口不会静态引入 rrweb / modern-screenshot。
8
10
  *
9
11
  * ```ts
@@ -15,5 +17,15 @@ import { FireflyClient } from "@fz-firefly/core";
15
17
  * ```
16
18
  */
17
19
  export declare function installExperience(client: FireflyClient, options?: ExperienceOptions): () => void;
20
+ /**
21
+ * Sentry 风格的体验增强 integration。
22
+ *
23
+ * ```ts
24
+ * initFirefly({
25
+ * integrations: [experienceIntegration({ remote: true })],
26
+ * })
27
+ * ```
28
+ */
29
+ export declare function experienceIntegration(options?: ExperienceOptions): FireflyIntegration;
18
30
  export { type ExperienceOptions, type RemoteOptions, type ReplayOptions, type WhiteScreenOptions, normalizeExperienceOptions };
19
31
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -75,9 +75,11 @@ function normalizeExperienceOptions(value) {
75
75
  }
76
76
  // src/install.ts
77
77
  /**
78
- * 安装可选体验增强。
78
+ * 低阶安装入口。
79
+ *
80
+ * 常规接入推荐 `initFirefly({ integrations: [experienceIntegration(...)] })`;
81
+ * 需要在登录后或运行时动态安装时,再直接调用 installExperience。
79
82
  *
80
- * 与核心 SDK 解耦:先 initFirefly 创建 client,再按需安装体验能力。
81
83
  * 只有开启的能力会被动态加载,主入口不会静态引入 rrweb / modern-screenshot。
82
84
  *
83
85
  * ```ts
@@ -115,6 +117,21 @@ function installExperience(client, options) {
115
117
  for (const dispose of disposers.splice(0)) dispose();
116
118
  };
117
119
  }
118
- export { installExperience, normalizeExperienceOptions };
120
+ /**
121
+ * Sentry 风格的体验增强 integration。
122
+ *
123
+ * ```ts
124
+ * initFirefly({
125
+ * integrations: [experienceIntegration({ remote: true })],
126
+ * })
127
+ * ```
128
+ */
129
+ function experienceIntegration(options) {
130
+ return {
131
+ name: "experience",
132
+ setup: (client) => installExperience(client, options)
133
+ };
134
+ }
135
+ export { experienceIntegration, installExperience, normalizeExperienceOptions };
119
136
 
120
137
  //# sourceMappingURL=index.js.map
package/dist/remote.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_objectSpread2 = require("./objectSpread2-BYC7ck9c.cjs");
2
+ const require_utils = require("./utils-Ccpv5DV3.cjs");
3
3
  const require_replay = require("./replay.cjs");
4
4
  // src/remote.ts
5
5
  const SENSITIVE_KEY_RE = /token|password|secret|authorization|auth|session|cookie|api[_-]?key/i;
@@ -40,17 +40,63 @@ function snapshotStorage(maxChars) {
40
40
  * 结果通过 POST 回传;不建立长连接,避免大量在线用户占用连接数。
41
41
  */
42
42
  function installRemote(client, options) {
43
- if (!require_objectSpread2.isBrowser()) return () => {};
43
+ if (!require_utils.isBrowser()) return () => {};
44
44
  const runtime = client.getRuntimeInfo();
45
- const endpoint = require_objectSpread2.trimEndpoint(runtime.endpoint);
45
+ const endpoint = require_utils.trimEndpoint(runtime.endpoint);
46
46
  const dsn = runtime.dsn;
47
47
  let pageSessionId = runtime.pageSession.id;
48
48
  let disposed = false;
49
49
  let pollTimer = null;
50
+ let pollInFlight = false;
50
51
  let consoleTimer = null;
51
52
  let consoleActive = false;
53
+ let consolePageSessionId = null;
52
54
  let consoleCursor = 0;
53
55
  let consoleBuffer = [];
56
+ let commandStream = null;
57
+ let streamOpen = false;
58
+ const executedCommands = /* @__PURE__ */ new Set();
59
+ const PAGE_SESSION_STORE_KEY = `firefly-remote-page-sessions:${dsn}`;
60
+ const PAGE_SESSION_TTL_MS = 9e5;
61
+ const MAX_PAGE_SESSIONS = 5;
62
+ /** SPA 路由切换会换 page session;保留旧 id 继续轮询,连线才不会断。 */
63
+ function loadPageSessions(currentId) {
64
+ const refs = /* @__PURE__ */ new Map();
65
+ try {
66
+ const raw = window.sessionStorage.getItem(PAGE_SESSION_STORE_KEY);
67
+ const stored = raw ? JSON.parse(raw) : [];
68
+ if (Array.isArray(stored)) {
69
+ for (const item of stored) if (item && typeof item === "object" && typeof item.id === "string" && typeof item.seenAt === "number") refs.set(item.id, item.seenAt);
70
+ }
71
+ } catch (_unused2) {}
72
+ refs.set(currentId, Date.now());
73
+ return [...refs].map(([id, seenAt]) => ({
74
+ id,
75
+ seenAt
76
+ })).sort((left, right) => right.seenAt - left.seenAt).slice(0, MAX_PAGE_SESSIONS);
77
+ }
78
+ let remotePageSessions = loadPageSessions(pageSessionId);
79
+ function persistPageSessions() {
80
+ try {
81
+ window.sessionStorage.setItem(PAGE_SESSION_STORE_KEY, JSON.stringify(remotePageSessions));
82
+ } catch (_unused3) {}
83
+ }
84
+ function prunePageSessions() {
85
+ const cutoff = Date.now() - PAGE_SESSION_TTL_MS;
86
+ remotePageSessions = remotePageSessions.filter((item) => item.seenAt >= cutoff).slice(0, MAX_PAGE_SESSIONS);
87
+ persistPageSessions();
88
+ }
89
+ function touchPageSession(id) {
90
+ const now = Date.now();
91
+ const existing = remotePageSessions.find((item) => item.id === id);
92
+ if (existing) existing.seenAt = now;
93
+ else remotePageSessions.unshift({
94
+ id,
95
+ seenAt: now
96
+ });
97
+ prunePageSessions();
98
+ }
99
+ prunePageSessions();
54
100
  const originalConsole = {
55
101
  log: console.log,
56
102
  info: console.info,
@@ -85,35 +131,36 @@ function installRemote(client, options) {
85
131
  captureConsole("error", args);
86
132
  originalConsole.error(...args);
87
133
  };
88
- async function postResult(commandId, ok, result) {
134
+ async function postResult(commandId, ok, result, sourcePageSessionId = pageSessionId) {
89
135
  try {
90
- await fetch(`${endpoint}/api/ingest/v1/remote/results?key=${encodeURIComponent(dsn)}`, {
136
+ await require_utils.fetchWithTimeout(`${endpoint}/api/ingest/v1/remote/results?key=${encodeURIComponent(dsn)}`, {
91
137
  method: "POST",
92
138
  headers: { "content-type": "application/json" },
93
139
  body: JSON.stringify({
94
140
  command_id: commandId,
95
- page_session_id: pageSessionId,
141
+ page_session_id: sourcePageSessionId,
96
142
  ok,
97
143
  result
98
144
  }),
99
145
  keepalive: true
100
- });
101
- } catch (_unused2) {}
146
+ }, 1e4);
147
+ } catch (_unused4) {}
102
148
  }
103
149
  async function postConsole(entries) {
104
150
  if (entries.length === 0) return;
105
151
  try {
106
- await fetch(`${endpoint}/api/ingest/v1/remote/events?key=${encodeURIComponent(dsn)}`, {
152
+ var _consolePageSessionId;
153
+ await require_utils.fetchWithTimeout(`${endpoint}/api/ingest/v1/remote/events?key=${encodeURIComponent(dsn)}`, {
107
154
  method: "POST",
108
155
  headers: { "content-type": "application/json" },
109
156
  body: JSON.stringify({
110
- page_session_id: pageSessionId,
157
+ page_session_id: (_consolePageSessionId = consolePageSessionId) !== null && _consolePageSessionId !== void 0 ? _consolePageSessionId : pageSessionId,
111
158
  type: "console",
112
159
  entries
113
160
  }),
114
161
  keepalive: true
115
- });
116
- } catch (_unused3) {}
162
+ }, 1e4);
163
+ } catch (_unused5) {}
117
164
  }
118
165
  function startConsoleTimer() {
119
166
  if (consoleTimer !== null) return;
@@ -129,19 +176,27 @@ function installRemote(client, options) {
129
176
  window.clearInterval(consoleTimer);
130
177
  consoleTimer = null;
131
178
  }
132
- async function execute(command) {
179
+ async function execute(command, sourcePageSessionId) {
180
+ if (executedCommands.has(command.id)) return;
181
+ executedCommands.add(command.id);
182
+ if (executedCommands.size > 500) {
183
+ const oldest = executedCommands.values().next().value;
184
+ if (oldest) executedCommands.delete(oldest);
185
+ }
133
186
  try {
134
187
  switch (command.type) {
135
188
  case "console.start":
136
189
  consoleActive = true;
190
+ consolePageSessionId = sourcePageSessionId;
137
191
  consoleCursor = consoleBuffer.length;
138
192
  startConsoleTimer();
139
- await postResult(command.id, true, { active: true });
193
+ await postResult(command.id, true, { active: true }, sourcePageSessionId);
140
194
  return;
141
195
  case "console.stop":
142
196
  consoleActive = false;
197
+ consolePageSessionId = null;
143
198
  stopConsoleTimer();
144
- await postResult(command.id, true, { active: false });
199
+ await postResult(command.id, true, { active: false }, sourcePageSessionId);
145
200
  return;
146
201
  case "storage.snapshot":
147
202
  await postResult(command.id, true, snapshotStorage(options.maxStorageValueChars));
@@ -190,39 +245,134 @@ function installRemote(client, options) {
190
245
  await postResult(command.id, false, error instanceof Error ? error.message : String(error));
191
246
  }
192
247
  }
193
- async function poll() {
248
+ function closeStream() {
249
+ streamOpen = false;
250
+ commandStream === null || commandStream === void 0 || commandStream.close();
251
+ commandStream = null;
252
+ }
253
+ /** SSE 断开期间退回短轮询,恢复后自动停掉。 */
254
+ function scheduleFallbackPoll(delay = 0) {
255
+ if (disposed || streamOpen || pollTimer !== null || pollInFlight) return;
256
+ pollTimer = window.setTimeout(() => {
257
+ pollTimer = null;
258
+ poll();
259
+ }, delay);
260
+ }
261
+ function openStream() {
194
262
  if (disposed) return;
263
+ closeStream();
264
+ if (typeof EventSource === "undefined") {
265
+ scheduleFallbackPoll();
266
+ return;
267
+ }
268
+ const pageSessionIds = remotePageSessions.map((item) => item.id);
269
+ const url = `${endpoint}/api/ingest/v1/remote/stream?key=${encodeURIComponent(dsn)}&page_session_ids=${encodeURIComponent(pageSessionIds.join(","))}`;
270
+ let source;
271
+ try {
272
+ source = new EventSource(url);
273
+ } catch (_unused6) {
274
+ scheduleFallbackPoll();
275
+ return;
276
+ }
277
+ commandStream = source;
278
+ source.addEventListener("command", (event) => {
279
+ try {
280
+ var _command$pageSessionI;
281
+ const command = JSON.parse(event.data);
282
+ execute(command, (_command$pageSessionI = command.pageSessionId) !== null && _command$pageSessionI !== void 0 ? _command$pageSessionI : pageSessionId);
283
+ } catch (_unused7) {}
284
+ });
285
+ source.onopen = () => {
286
+ streamOpen = true;
287
+ if (pollTimer !== null) {
288
+ window.clearTimeout(pollTimer);
289
+ pollTimer = null;
290
+ }
291
+ };
292
+ source.onerror = () => {
293
+ if (disposed) return;
294
+ streamOpen = false;
295
+ scheduleFallbackPoll(1e3);
296
+ };
297
+ }
298
+ async function poll() {
299
+ if (disposed || pollInFlight || streamOpen) return;
300
+ pollInFlight = true;
301
+ touchPageSession(pageSessionId);
195
302
  let delay = options.pollIntervalMs;
303
+ let failed = 0;
196
304
  try {
197
- const response = await fetch(`${endpoint}/api/ingest/v1/remote/poll?key=${encodeURIComponent(dsn)}&page_session_id=${encodeURIComponent(pageSessionId)}`, {
198
- method: "GET",
199
- keepalive: true
200
- });
201
- if (response.ok) {
202
- var _data$commands;
203
- const data = await response.json().catch(() => ({}));
204
- for (const command of (_data$commands = data.commands) !== null && _data$commands !== void 0 ? _data$commands : []) await execute(command);
305
+ const targets = remotePageSessions.map((item) => item.id);
306
+ const results = await Promise.all(targets.map(async (targetPageSessionId) => {
307
+ try {
308
+ var _data$commands;
309
+ const response = await require_utils.fetchWithTimeout(`${endpoint}/api/ingest/v1/remote/poll?key=${encodeURIComponent(dsn)}&page_session_id=${encodeURIComponent(targetPageSessionId)}`, {
310
+ method: "GET",
311
+ keepalive: true
312
+ }, 12e3);
313
+ if (!response.ok) {
314
+ failed += 1;
315
+ return {
316
+ id: targetPageSessionId,
317
+ commands: []
318
+ };
319
+ }
320
+ return {
321
+ id: targetPageSessionId,
322
+ commands: (_data$commands = (await response.json().catch(() => ({}))).commands) !== null && _data$commands !== void 0 ? _data$commands : []
323
+ };
324
+ } catch (_unused8) {
325
+ failed += 1;
326
+ return {
327
+ id: targetPageSessionId,
328
+ commands: []
329
+ };
330
+ }
331
+ }));
332
+ const seen = /* @__PURE__ */ new Set();
333
+ for (const result of results) for (const command of result.commands) {
334
+ if (seen.has(command.id)) continue;
335
+ seen.add(command.id);
336
+ await execute(command, result.id);
205
337
  }
206
- } catch (_unused4) {
207
- delay = Math.max(delay, 3e4);
338
+ if (failed > 0 && failed === targets.length) delay = Math.max(delay, 3e4);
339
+ } finally {
340
+ pollInFlight = false;
208
341
  }
209
342
  if (!disposed) pollTimer = window.setTimeout(() => {
210
343
  poll();
211
344
  }, delay);
212
345
  }
346
+ /** 页面重新可见或恢复网络时立即补一次轮询,避免后台节流导致指令长时间 pending。 */
347
+ function wakePoll() {
348
+ if (disposed || streamOpen || document.visibilityState === "hidden") return;
349
+ if (pollTimer !== null) {
350
+ window.clearTimeout(pollTimer);
351
+ pollTimer = null;
352
+ }
353
+ poll();
354
+ }
355
+ document.addEventListener("visibilitychange", wakePoll);
356
+ window.addEventListener("focus", wakePoll);
357
+ window.addEventListener("online", wakePoll);
213
358
  const unsubscribeSession = client.onPageSessionStart((info) => {
214
359
  pageSessionId = info.id;
215
- consoleCursor = consoleBuffer.length;
360
+ touchPageSession(info.id);
361
+ if (!consoleActive) consoleCursor = consoleBuffer.length;
216
362
  if (pollTimer !== null) {
217
363
  window.clearTimeout(pollTimer);
218
364
  pollTimer = null;
219
365
  }
220
- poll();
366
+ openStream();
221
367
  });
222
- poll();
368
+ openStream();
223
369
  return () => {
224
370
  disposed = true;
225
371
  if (pollTimer !== null) window.clearTimeout(pollTimer);
372
+ closeStream();
373
+ document.removeEventListener("visibilitychange", wakePoll);
374
+ window.removeEventListener("focus", wakePoll);
375
+ window.removeEventListener("online", wakePoll);
226
376
  stopConsoleTimer();
227
377
  unsubscribeSession();
228
378
  console.log = originalConsole.log;
package/dist/remote.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as trimEndpoint, i as isBrowser } from "./objectSpread2-lWxa9t4g.js";
1
+ import { i as trimEndpoint, r as isBrowser, t as fetchWithTimeout } from "./utils-Gj7Ms2LC.js";
2
2
  import { getReplayController } from "./replay.js";
3
3
  // src/remote.ts
4
4
  const SENSITIVE_KEY_RE = /token|password|secret|authorization|auth|session|cookie|api[_-]?key/i;
@@ -46,10 +46,56 @@ function installRemote(client, options) {
46
46
  let pageSessionId = runtime.pageSession.id;
47
47
  let disposed = false;
48
48
  let pollTimer = null;
49
+ let pollInFlight = false;
49
50
  let consoleTimer = null;
50
51
  let consoleActive = false;
52
+ let consolePageSessionId = null;
51
53
  let consoleCursor = 0;
52
54
  let consoleBuffer = [];
55
+ let commandStream = null;
56
+ let streamOpen = false;
57
+ const executedCommands = /* @__PURE__ */ new Set();
58
+ const PAGE_SESSION_STORE_KEY = `firefly-remote-page-sessions:${dsn}`;
59
+ const PAGE_SESSION_TTL_MS = 9e5;
60
+ const MAX_PAGE_SESSIONS = 5;
61
+ /** SPA 路由切换会换 page session;保留旧 id 继续轮询,连线才不会断。 */
62
+ function loadPageSessions(currentId) {
63
+ const refs = /* @__PURE__ */ new Map();
64
+ try {
65
+ const raw = window.sessionStorage.getItem(PAGE_SESSION_STORE_KEY);
66
+ const stored = raw ? JSON.parse(raw) : [];
67
+ if (Array.isArray(stored)) {
68
+ for (const item of stored) if (item && typeof item === "object" && typeof item.id === "string" && typeof item.seenAt === "number") refs.set(item.id, item.seenAt);
69
+ }
70
+ } catch (_unused2) {}
71
+ refs.set(currentId, Date.now());
72
+ return [...refs].map(([id, seenAt]) => ({
73
+ id,
74
+ seenAt
75
+ })).sort((left, right) => right.seenAt - left.seenAt).slice(0, MAX_PAGE_SESSIONS);
76
+ }
77
+ let remotePageSessions = loadPageSessions(pageSessionId);
78
+ function persistPageSessions() {
79
+ try {
80
+ window.sessionStorage.setItem(PAGE_SESSION_STORE_KEY, JSON.stringify(remotePageSessions));
81
+ } catch (_unused3) {}
82
+ }
83
+ function prunePageSessions() {
84
+ const cutoff = Date.now() - PAGE_SESSION_TTL_MS;
85
+ remotePageSessions = remotePageSessions.filter((item) => item.seenAt >= cutoff).slice(0, MAX_PAGE_SESSIONS);
86
+ persistPageSessions();
87
+ }
88
+ function touchPageSession(id) {
89
+ const now = Date.now();
90
+ const existing = remotePageSessions.find((item) => item.id === id);
91
+ if (existing) existing.seenAt = now;
92
+ else remotePageSessions.unshift({
93
+ id,
94
+ seenAt: now
95
+ });
96
+ prunePageSessions();
97
+ }
98
+ prunePageSessions();
53
99
  const originalConsole = {
54
100
  log: console.log,
55
101
  info: console.info,
@@ -84,35 +130,36 @@ function installRemote(client, options) {
84
130
  captureConsole("error", args);
85
131
  originalConsole.error(...args);
86
132
  };
87
- async function postResult(commandId, ok, result) {
133
+ async function postResult(commandId, ok, result, sourcePageSessionId = pageSessionId) {
88
134
  try {
89
- await fetch(`${endpoint}/api/ingest/v1/remote/results?key=${encodeURIComponent(dsn)}`, {
135
+ await fetchWithTimeout(`${endpoint}/api/ingest/v1/remote/results?key=${encodeURIComponent(dsn)}`, {
90
136
  method: "POST",
91
137
  headers: { "content-type": "application/json" },
92
138
  body: JSON.stringify({
93
139
  command_id: commandId,
94
- page_session_id: pageSessionId,
140
+ page_session_id: sourcePageSessionId,
95
141
  ok,
96
142
  result
97
143
  }),
98
144
  keepalive: true
99
- });
100
- } catch (_unused2) {}
145
+ }, 1e4);
146
+ } catch (_unused4) {}
101
147
  }
102
148
  async function postConsole(entries) {
103
149
  if (entries.length === 0) return;
104
150
  try {
105
- await fetch(`${endpoint}/api/ingest/v1/remote/events?key=${encodeURIComponent(dsn)}`, {
151
+ var _consolePageSessionId;
152
+ await fetchWithTimeout(`${endpoint}/api/ingest/v1/remote/events?key=${encodeURIComponent(dsn)}`, {
106
153
  method: "POST",
107
154
  headers: { "content-type": "application/json" },
108
155
  body: JSON.stringify({
109
- page_session_id: pageSessionId,
156
+ page_session_id: (_consolePageSessionId = consolePageSessionId) !== null && _consolePageSessionId !== void 0 ? _consolePageSessionId : pageSessionId,
110
157
  type: "console",
111
158
  entries
112
159
  }),
113
160
  keepalive: true
114
- });
115
- } catch (_unused3) {}
161
+ }, 1e4);
162
+ } catch (_unused5) {}
116
163
  }
117
164
  function startConsoleTimer() {
118
165
  if (consoleTimer !== null) return;
@@ -128,19 +175,27 @@ function installRemote(client, options) {
128
175
  window.clearInterval(consoleTimer);
129
176
  consoleTimer = null;
130
177
  }
131
- async function execute(command) {
178
+ async function execute(command, sourcePageSessionId) {
179
+ if (executedCommands.has(command.id)) return;
180
+ executedCommands.add(command.id);
181
+ if (executedCommands.size > 500) {
182
+ const oldest = executedCommands.values().next().value;
183
+ if (oldest) executedCommands.delete(oldest);
184
+ }
132
185
  try {
133
186
  switch (command.type) {
134
187
  case "console.start":
135
188
  consoleActive = true;
189
+ consolePageSessionId = sourcePageSessionId;
136
190
  consoleCursor = consoleBuffer.length;
137
191
  startConsoleTimer();
138
- await postResult(command.id, true, { active: true });
192
+ await postResult(command.id, true, { active: true }, sourcePageSessionId);
139
193
  return;
140
194
  case "console.stop":
141
195
  consoleActive = false;
196
+ consolePageSessionId = null;
142
197
  stopConsoleTimer();
143
- await postResult(command.id, true, { active: false });
198
+ await postResult(command.id, true, { active: false }, sourcePageSessionId);
144
199
  return;
145
200
  case "storage.snapshot":
146
201
  await postResult(command.id, true, snapshotStorage(options.maxStorageValueChars));
@@ -189,39 +244,134 @@ function installRemote(client, options) {
189
244
  await postResult(command.id, false, error instanceof Error ? error.message : String(error));
190
245
  }
191
246
  }
192
- async function poll() {
247
+ function closeStream() {
248
+ streamOpen = false;
249
+ commandStream === null || commandStream === void 0 || commandStream.close();
250
+ commandStream = null;
251
+ }
252
+ /** SSE 断开期间退回短轮询,恢复后自动停掉。 */
253
+ function scheduleFallbackPoll(delay = 0) {
254
+ if (disposed || streamOpen || pollTimer !== null || pollInFlight) return;
255
+ pollTimer = window.setTimeout(() => {
256
+ pollTimer = null;
257
+ poll();
258
+ }, delay);
259
+ }
260
+ function openStream() {
193
261
  if (disposed) return;
262
+ closeStream();
263
+ if (typeof EventSource === "undefined") {
264
+ scheduleFallbackPoll();
265
+ return;
266
+ }
267
+ const pageSessionIds = remotePageSessions.map((item) => item.id);
268
+ const url = `${endpoint}/api/ingest/v1/remote/stream?key=${encodeURIComponent(dsn)}&page_session_ids=${encodeURIComponent(pageSessionIds.join(","))}`;
269
+ let source;
270
+ try {
271
+ source = new EventSource(url);
272
+ } catch (_unused6) {
273
+ scheduleFallbackPoll();
274
+ return;
275
+ }
276
+ commandStream = source;
277
+ source.addEventListener("command", (event) => {
278
+ try {
279
+ var _command$pageSessionI;
280
+ const command = JSON.parse(event.data);
281
+ execute(command, (_command$pageSessionI = command.pageSessionId) !== null && _command$pageSessionI !== void 0 ? _command$pageSessionI : pageSessionId);
282
+ } catch (_unused7) {}
283
+ });
284
+ source.onopen = () => {
285
+ streamOpen = true;
286
+ if (pollTimer !== null) {
287
+ window.clearTimeout(pollTimer);
288
+ pollTimer = null;
289
+ }
290
+ };
291
+ source.onerror = () => {
292
+ if (disposed) return;
293
+ streamOpen = false;
294
+ scheduleFallbackPoll(1e3);
295
+ };
296
+ }
297
+ async function poll() {
298
+ if (disposed || pollInFlight || streamOpen) return;
299
+ pollInFlight = true;
300
+ touchPageSession(pageSessionId);
194
301
  let delay = options.pollIntervalMs;
302
+ let failed = 0;
195
303
  try {
196
- const response = await fetch(`${endpoint}/api/ingest/v1/remote/poll?key=${encodeURIComponent(dsn)}&page_session_id=${encodeURIComponent(pageSessionId)}`, {
197
- method: "GET",
198
- keepalive: true
199
- });
200
- if (response.ok) {
201
- var _data$commands;
202
- const data = await response.json().catch(() => ({}));
203
- for (const command of (_data$commands = data.commands) !== null && _data$commands !== void 0 ? _data$commands : []) await execute(command);
304
+ const targets = remotePageSessions.map((item) => item.id);
305
+ const results = await Promise.all(targets.map(async (targetPageSessionId) => {
306
+ try {
307
+ var _data$commands;
308
+ const response = await fetchWithTimeout(`${endpoint}/api/ingest/v1/remote/poll?key=${encodeURIComponent(dsn)}&page_session_id=${encodeURIComponent(targetPageSessionId)}`, {
309
+ method: "GET",
310
+ keepalive: true
311
+ }, 12e3);
312
+ if (!response.ok) {
313
+ failed += 1;
314
+ return {
315
+ id: targetPageSessionId,
316
+ commands: []
317
+ };
318
+ }
319
+ return {
320
+ id: targetPageSessionId,
321
+ commands: (_data$commands = (await response.json().catch(() => ({}))).commands) !== null && _data$commands !== void 0 ? _data$commands : []
322
+ };
323
+ } catch (_unused8) {
324
+ failed += 1;
325
+ return {
326
+ id: targetPageSessionId,
327
+ commands: []
328
+ };
329
+ }
330
+ }));
331
+ const seen = /* @__PURE__ */ new Set();
332
+ for (const result of results) for (const command of result.commands) {
333
+ if (seen.has(command.id)) continue;
334
+ seen.add(command.id);
335
+ await execute(command, result.id);
204
336
  }
205
- } catch (_unused4) {
206
- delay = Math.max(delay, 3e4);
337
+ if (failed > 0 && failed === targets.length) delay = Math.max(delay, 3e4);
338
+ } finally {
339
+ pollInFlight = false;
207
340
  }
208
341
  if (!disposed) pollTimer = window.setTimeout(() => {
209
342
  poll();
210
343
  }, delay);
211
344
  }
345
+ /** 页面重新可见或恢复网络时立即补一次轮询,避免后台节流导致指令长时间 pending。 */
346
+ function wakePoll() {
347
+ if (disposed || streamOpen || document.visibilityState === "hidden") return;
348
+ if (pollTimer !== null) {
349
+ window.clearTimeout(pollTimer);
350
+ pollTimer = null;
351
+ }
352
+ poll();
353
+ }
354
+ document.addEventListener("visibilitychange", wakePoll);
355
+ window.addEventListener("focus", wakePoll);
356
+ window.addEventListener("online", wakePoll);
212
357
  const unsubscribeSession = client.onPageSessionStart((info) => {
213
358
  pageSessionId = info.id;
214
- consoleCursor = consoleBuffer.length;
359
+ touchPageSession(info.id);
360
+ if (!consoleActive) consoleCursor = consoleBuffer.length;
215
361
  if (pollTimer !== null) {
216
362
  window.clearTimeout(pollTimer);
217
363
  pollTimer = null;
218
364
  }
219
- poll();
365
+ openStream();
220
366
  });
221
- poll();
367
+ openStream();
222
368
  return () => {
223
369
  disposed = true;
224
370
  if (pollTimer !== null) window.clearTimeout(pollTimer);
371
+ closeStream();
372
+ document.removeEventListener("visibilitychange", wakePoll);
373
+ window.removeEventListener("focus", wakePoll);
374
+ window.removeEventListener("online", wakePoll);
225
375
  stopConsoleTimer();
226
376
  unsubscribeSession();
227
377
  console.log = originalConsole.log;
package/dist/replay.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_objectSpread2 = require("./objectSpread2-BYC7ck9c.cjs");
2
+ const require_utils = require("./utils-Ccpv5DV3.cjs");
3
3
  // src/replay.ts
4
4
  const controllers = /* @__PURE__ */ new WeakMap();
5
5
  /** 读取某个客户端上的回放控制器;用户连线需要按需开始/停止录屏。 */
@@ -47,14 +47,14 @@ function findReplayStart(events, cutoff) {
47
47
  }
48
48
  async function createReplaySession(client, meta) {
49
49
  const runtime = client.getRuntimeInfo();
50
- const url = `${require_objectSpread2.trimEndpoint(runtime.endpoint)}/api/ingest/v1/replays?key=${encodeURIComponent(runtime.dsn)}`;
50
+ const url = `${require_utils.trimEndpoint(runtime.endpoint)}/api/ingest/v1/replays?key=${encodeURIComponent(runtime.dsn)}`;
51
51
  try {
52
- const response = await fetch(url, {
52
+ const response = await require_utils.fetchWithTimeout(url, {
53
53
  method: "POST",
54
54
  headers: { "content-type": "application/json" },
55
55
  body: JSON.stringify(meta),
56
56
  keepalive: true
57
- });
57
+ }, 1e4);
58
58
  if (!response.ok) return null;
59
59
  const data = await response.json().catch(() => ({}));
60
60
  return typeof data.id === "string" ? data.id : null;
@@ -64,31 +64,31 @@ async function createReplaySession(client, meta) {
64
64
  }
65
65
  async function uploadReplayChunk(client, replayId, seq, events) {
66
66
  const runtime = client.getRuntimeInfo();
67
- const url = `${require_objectSpread2.trimEndpoint(runtime.endpoint)}/api/ingest/v1/replays/${encodeURIComponent(replayId)}/chunks/${seq}?key=${encodeURIComponent(runtime.dsn)}`;
67
+ const url = `${require_utils.trimEndpoint(runtime.endpoint)}/api/ingest/v1/replays/${encodeURIComponent(replayId)}/chunks/${seq}?key=${encodeURIComponent(runtime.dsn)}`;
68
68
  const raw = new TextEncoder().encode(JSON.stringify(events));
69
- const compressed = await require_objectSpread2.gzipBytes(raw);
69
+ const compressed = await require_utils.gzipBytes(raw);
70
70
  const body = compressed !== null && compressed !== void 0 ? compressed : raw;
71
71
  try {
72
- return (await fetch(url, {
72
+ return (await require_utils.fetchWithTimeout(url, {
73
73
  method: "PUT",
74
- headers: require_objectSpread2._objectSpread2({ "content-type": "application/x-firefly-replay" }, compressed ? { "content-encoding": "gzip" } : {}),
74
+ headers: require_utils._objectSpread2({ "content-type": "application/x-firefly-replay" }, compressed ? { "content-encoding": "gzip" } : {}),
75
75
  body,
76
76
  keepalive: body.byteLength < 61440
77
- })).ok;
77
+ }, 2e4)).ok;
78
78
  } catch (_unused3) {
79
79
  return false;
80
80
  }
81
81
  }
82
82
  async function completeReplaySession(client, replayId, meta) {
83
83
  const runtime = client.getRuntimeInfo();
84
- const url = `${require_objectSpread2.trimEndpoint(runtime.endpoint)}/api/ingest/v1/replays/${encodeURIComponent(replayId)}/complete?key=${encodeURIComponent(runtime.dsn)}`;
84
+ const url = `${require_utils.trimEndpoint(runtime.endpoint)}/api/ingest/v1/replays/${encodeURIComponent(replayId)}/complete?key=${encodeURIComponent(runtime.dsn)}`;
85
85
  try {
86
- await fetch(url, {
86
+ await require_utils.fetchWithTimeout(url, {
87
87
  method: "POST",
88
88
  headers: { "content-type": "application/json" },
89
89
  body: JSON.stringify(meta),
90
90
  keepalive: true
91
- });
91
+ }, 1e4);
92
92
  } catch (_unused4) {}
93
93
  }
94
94
  /**
@@ -98,7 +98,7 @@ async function completeReplaySession(client, replayId, meta) {
98
98
  * always:按采样率持续分片上传;manual:用户连线时再开始。
99
99
  */
100
100
  function installReplay(client, options) {
101
- if (!require_objectSpread2.isBrowser()) return () => {};
101
+ if (!require_utils.isBrowser()) return () => {};
102
102
  const controller = new ReplayRecorder(client, options);
103
103
  controllers.set(client, controller);
104
104
  controller.start();
@@ -118,22 +118,22 @@ function installReplay(client, options) {
118
118
  }
119
119
  var ReplayRecorder = class {
120
120
  constructor(client, options) {
121
- require_objectSpread2._defineProperty(this, "client", void 0);
122
- require_objectSpread2._defineProperty(this, "options", void 0);
123
- require_objectSpread2._defineProperty(this, "sampled", void 0);
124
- require_objectSpread2._defineProperty(this, "manualRequested", false);
125
- require_objectSpread2._defineProperty(this, "manualCapture", false);
126
- require_objectSpread2._defineProperty(this, "recording", false);
127
- require_objectSpread2._defineProperty(this, "stopRecord", null);
128
- require_objectSpread2._defineProperty(this, "buffer", []);
129
- require_objectSpread2._defineProperty(this, "uploadedCount", 0);
130
- require_objectSpread2._defineProperty(this, "sessionId", null);
131
- require_objectSpread2._defineProperty(this, "chunkSeq", 0);
132
- require_objectSpread2._defineProperty(this, "startedAt", 0);
133
- require_objectSpread2._defineProperty(this, "postRollUntil", 0);
134
- require_objectSpread2._defineProperty(this, "errorEventId", "");
135
- require_objectSpread2._defineProperty(this, "timer", null);
136
- require_objectSpread2._defineProperty(this, "uploadQueue", Promise.resolve());
121
+ require_utils._defineProperty(this, "client", void 0);
122
+ require_utils._defineProperty(this, "options", void 0);
123
+ require_utils._defineProperty(this, "sampled", void 0);
124
+ require_utils._defineProperty(this, "manualRequested", false);
125
+ require_utils._defineProperty(this, "manualCapture", false);
126
+ require_utils._defineProperty(this, "recording", false);
127
+ require_utils._defineProperty(this, "stopRecord", null);
128
+ require_utils._defineProperty(this, "buffer", []);
129
+ require_utils._defineProperty(this, "uploadedCount", 0);
130
+ require_utils._defineProperty(this, "sessionId", null);
131
+ require_utils._defineProperty(this, "chunkSeq", 0);
132
+ require_utils._defineProperty(this, "startedAt", 0);
133
+ require_utils._defineProperty(this, "postRollUntil", 0);
134
+ require_utils._defineProperty(this, "errorEventId", "");
135
+ require_utils._defineProperty(this, "timer", null);
136
+ require_utils._defineProperty(this, "uploadQueue", Promise.resolve());
137
137
  this.client = client;
138
138
  this.options = options;
139
139
  this.sampled = Math.random() < options.sampleRate;
@@ -255,7 +255,7 @@ var ReplayRecorder = class {
255
255
  async ensureSession() {
256
256
  if (this.sessionId) return this.sessionId;
257
257
  const runtime = this.client.getRuntimeInfo();
258
- const meta = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({
258
+ const meta = require_utils._objectSpread2(require_utils._objectSpread2(require_utils._objectSpread2({
259
259
  pageSessionId: runtime.pageSession.id,
260
260
  startedAt: new Date(this.startedAt || Date.now()).toISOString()
261
261
  }, runtime.pageSession.path ? { route: runtime.pageSession.path } : {}), typeof window !== "undefined" ? { url: window.location.href } : {}), this.errorEventId ? { errorEventId: this.errorEventId } : {});
@@ -278,7 +278,7 @@ var ReplayRecorder = class {
278
278
  }
279
279
  if (!final) return;
280
280
  const runtime = this.client.getRuntimeInfo();
281
- await completeReplaySession(this.client, sessionId, require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({
281
+ await completeReplaySession(this.client, sessionId, require_utils._objectSpread2(require_utils._objectSpread2(require_utils._objectSpread2(require_utils._objectSpread2({
282
282
  pageSessionId: runtime.pageSession.id,
283
283
  startedAt: new Date(this.startedAt || Date.now()).toISOString(),
284
284
  endedAt: (/* @__PURE__ */ new Date()).toISOString()
package/dist/replay.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as trimEndpoint, i as isBrowser, n as _defineProperty, r as gzipBytes, t as _objectSpread2 } from "./objectSpread2-lWxa9t4g.js";
1
+ import { a as _objectSpread2, i as trimEndpoint, n as gzipBytes, o as _defineProperty, r as isBrowser, t as fetchWithTimeout } from "./utils-Gj7Ms2LC.js";
2
2
  // src/replay.ts
3
3
  const controllers = /* @__PURE__ */ new WeakMap();
4
4
  /** 读取某个客户端上的回放控制器;用户连线需要按需开始/停止录屏。 */
@@ -48,12 +48,12 @@ async function createReplaySession(client, meta) {
48
48
  const runtime = client.getRuntimeInfo();
49
49
  const url = `${trimEndpoint(runtime.endpoint)}/api/ingest/v1/replays?key=${encodeURIComponent(runtime.dsn)}`;
50
50
  try {
51
- const response = await fetch(url, {
51
+ const response = await fetchWithTimeout(url, {
52
52
  method: "POST",
53
53
  headers: { "content-type": "application/json" },
54
54
  body: JSON.stringify(meta),
55
55
  keepalive: true
56
- });
56
+ }, 1e4);
57
57
  if (!response.ok) return null;
58
58
  const data = await response.json().catch(() => ({}));
59
59
  return typeof data.id === "string" ? data.id : null;
@@ -68,12 +68,12 @@ async function uploadReplayChunk(client, replayId, seq, events) {
68
68
  const compressed = await gzipBytes(raw);
69
69
  const body = compressed !== null && compressed !== void 0 ? compressed : raw;
70
70
  try {
71
- return (await fetch(url, {
71
+ return (await fetchWithTimeout(url, {
72
72
  method: "PUT",
73
73
  headers: _objectSpread2({ "content-type": "application/x-firefly-replay" }, compressed ? { "content-encoding": "gzip" } : {}),
74
74
  body,
75
75
  keepalive: body.byteLength < 61440
76
- })).ok;
76
+ }, 2e4)).ok;
77
77
  } catch (_unused3) {
78
78
  return false;
79
79
  }
@@ -82,12 +82,12 @@ async function completeReplaySession(client, replayId, meta) {
82
82
  const runtime = client.getRuntimeInfo();
83
83
  const url = `${trimEndpoint(runtime.endpoint)}/api/ingest/v1/replays/${encodeURIComponent(replayId)}/complete?key=${encodeURIComponent(runtime.dsn)}`;
84
84
  try {
85
- await fetch(url, {
85
+ await fetchWithTimeout(url, {
86
86
  method: "POST",
87
87
  headers: { "content-type": "application/json" },
88
88
  body: JSON.stringify(meta),
89
89
  keepalive: true
90
- });
90
+ }, 1e4);
91
91
  } catch (_unused4) {}
92
92
  }
93
93
  /**
@@ -1,22 +1,3 @@
1
- // src/utils.ts
2
- /** 去掉 endpoint 末尾的斜杠。 */
3
- function trimEndpoint(endpoint) {
4
- return endpoint.replace(/\/+$/, "");
5
- }
6
- /** 当前是否在浏览器环境。 */
7
- function isBrowser() {
8
- return typeof window !== "undefined" && typeof document !== "undefined";
9
- }
10
- /** 浏览器支持时用 gzip 压缩;不支持返回 null,由服务端按原始字节处理。 */
11
- async function gzipBytes(data) {
12
- if (typeof CompressionStream === "undefined") return null;
13
- try {
14
- const stream = new Blob([data]).stream().pipeThrough(new CompressionStream("gzip"));
15
- return new Uint8Array(await new Response(stream).arrayBuffer());
16
- } catch (_unused) {
17
- return null;
18
- }
19
- }
20
1
  // \0@oxc-project+runtime@0.155.0/helpers/esm/typeof.js
21
2
  function _typeof(o) {
22
3
  "@babel/helpers - typeof";
@@ -73,6 +54,41 @@ function _objectSpread2(e) {
73
54
  }
74
55
  return e;
75
56
  }
57
+ // src/utils.ts
58
+ /** 去掉 endpoint 末尾的斜杠。 */
59
+ function trimEndpoint(endpoint) {
60
+ return endpoint.replace(/\/+$/, "");
61
+ }
62
+ /** 当前是否在浏览器环境。 */
63
+ function isBrowser() {
64
+ return typeof window !== "undefined" && typeof document !== "undefined";
65
+ }
66
+ /**
67
+ * 带超时的 fetch。
68
+ *
69
+ * 用户连线、回放上传都走 best-effort 网络请求;如果请求一直挂起,
70
+ * 轮询队列会被堵住,后台指令就会长期停在 pending。超时后让调用方
71
+ * 走正常的失败分支,保证后续指令还能继续处理。
72
+ */
73
+ async function fetchWithTimeout(input, init = {}, timeoutMs = 1e4) {
74
+ const controller = new AbortController();
75
+ const timer = globalThis.setTimeout(() => controller.abort(), timeoutMs);
76
+ try {
77
+ return await fetch(input, _objectSpread2(_objectSpread2({}, init), {}, { signal: controller.signal }));
78
+ } finally {
79
+ globalThis.clearTimeout(timer);
80
+ }
81
+ }
82
+ /** 浏览器支持时用 gzip 压缩;不支持返回 null,由服务端按原始字节处理。 */
83
+ async function gzipBytes(data) {
84
+ if (typeof CompressionStream === "undefined") return null;
85
+ try {
86
+ const stream = new Blob([data]).stream().pipeThrough(new CompressionStream("gzip"));
87
+ return new Uint8Array(await new Response(stream).arrayBuffer());
88
+ } catch (_unused) {
89
+ return null;
90
+ }
91
+ }
76
92
  Object.defineProperty(exports, "_defineProperty", {
77
93
  enumerable: true,
78
94
  get: function() {
@@ -85,6 +101,12 @@ Object.defineProperty(exports, "_objectSpread2", {
85
101
  return _objectSpread2;
86
102
  }
87
103
  });
104
+ Object.defineProperty(exports, "fetchWithTimeout", {
105
+ enumerable: true,
106
+ get: function() {
107
+ return fetchWithTimeout;
108
+ }
109
+ });
88
110
  Object.defineProperty(exports, "gzipBytes", {
89
111
  enumerable: true,
90
112
  get: function() {
@@ -104,4 +126,4 @@ Object.defineProperty(exports, "trimEndpoint", {
104
126
  }
105
127
  });
106
128
 
107
- //# sourceMappingURL=objectSpread2-BYC7ck9c.cjs.map
129
+ //# sourceMappingURL=utils-Ccpv5DV3.cjs.map
@@ -1,22 +1,3 @@
1
- // src/utils.ts
2
- /** 去掉 endpoint 末尾的斜杠。 */
3
- function trimEndpoint(endpoint) {
4
- return endpoint.replace(/\/+$/, "");
5
- }
6
- /** 当前是否在浏览器环境。 */
7
- function isBrowser() {
8
- return typeof window !== "undefined" && typeof document !== "undefined";
9
- }
10
- /** 浏览器支持时用 gzip 压缩;不支持返回 null,由服务端按原始字节处理。 */
11
- async function gzipBytes(data) {
12
- if (typeof CompressionStream === "undefined") return null;
13
- try {
14
- const stream = new Blob([data]).stream().pipeThrough(new CompressionStream("gzip"));
15
- return new Uint8Array(await new Response(stream).arrayBuffer());
16
- } catch (_unused) {
17
- return null;
18
- }
19
- }
20
1
  // \0@oxc-project+runtime@0.155.0/helpers/esm/typeof.js
21
2
  function _typeof(o) {
22
3
  "@babel/helpers - typeof";
@@ -73,6 +54,41 @@ function _objectSpread2(e) {
73
54
  }
74
55
  return e;
75
56
  }
76
- export { trimEndpoint as a, isBrowser as i, _defineProperty as n, gzipBytes as r, _objectSpread2 as t };
57
+ // src/utils.ts
58
+ /** 去掉 endpoint 末尾的斜杠。 */
59
+ function trimEndpoint(endpoint) {
60
+ return endpoint.replace(/\/+$/, "");
61
+ }
62
+ /** 当前是否在浏览器环境。 */
63
+ function isBrowser() {
64
+ return typeof window !== "undefined" && typeof document !== "undefined";
65
+ }
66
+ /**
67
+ * 带超时的 fetch。
68
+ *
69
+ * 用户连线、回放上传都走 best-effort 网络请求;如果请求一直挂起,
70
+ * 轮询队列会被堵住,后台指令就会长期停在 pending。超时后让调用方
71
+ * 走正常的失败分支,保证后续指令还能继续处理。
72
+ */
73
+ async function fetchWithTimeout(input, init = {}, timeoutMs = 1e4) {
74
+ const controller = new AbortController();
75
+ const timer = globalThis.setTimeout(() => controller.abort(), timeoutMs);
76
+ try {
77
+ return await fetch(input, _objectSpread2(_objectSpread2({}, init), {}, { signal: controller.signal }));
78
+ } finally {
79
+ globalThis.clearTimeout(timer);
80
+ }
81
+ }
82
+ /** 浏览器支持时用 gzip 压缩;不支持返回 null,由服务端按原始字节处理。 */
83
+ async function gzipBytes(data) {
84
+ if (typeof CompressionStream === "undefined") return null;
85
+ try {
86
+ const stream = new Blob([data]).stream().pipeThrough(new CompressionStream("gzip"));
87
+ return new Uint8Array(await new Response(stream).arrayBuffer());
88
+ } catch (_unused) {
89
+ return null;
90
+ }
91
+ }
92
+ export { _objectSpread2 as a, trimEndpoint as i, gzipBytes as n, _defineProperty as o, isBrowser as r, fetchWithTimeout as t };
77
93
 
78
- //# sourceMappingURL=objectSpread2-lWxa9t4g.js.map
94
+ //# sourceMappingURL=utils-Gj7Ms2LC.js.map
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_objectSpread2 = require("./objectSpread2-BYC7ck9c.cjs");
2
+ const require_utils = require("./utils-Ccpv5DV3.cjs");
3
3
  // src/attachment.ts
4
4
  /**
5
5
  * 上传白屏截图等附件。
@@ -8,7 +8,7 @@ const require_objectSpread2 = require("./objectSpread2-BYC7ck9c.cjs");
8
8
  * 服务端按 DSN 鉴权,返回附件 id,事件里用 contexts.white_screen.attachment_id 关联。
9
9
  */
10
10
  async function uploadAttachment(options) {
11
- const url = `${require_objectSpread2.trimEndpoint(options.endpoint)}/api/ingest/v1/attachments?key=${encodeURIComponent(options.dsn)}`;
11
+ const url = `${require_utils.trimEndpoint(options.endpoint)}/api/ingest/v1/attachments?key=${encodeURIComponent(options.dsn)}`;
12
12
  const headers = {
13
13
  "content-type": options.mime,
14
14
  "x-firefly-kind": options.kind
@@ -29,7 +29,7 @@ async function uploadAttachment(options) {
29
29
  error: `HTTP ${response.status}`
30
30
  };
31
31
  const data = await response.json().catch(() => ({}));
32
- return require_objectSpread2._objectSpread2({ ok: true }, typeof data.id === "string" ? { id: data.id } : {});
32
+ return require_utils._objectSpread2({ ok: true }, typeof data.id === "string" ? { id: data.id } : {});
33
33
  } catch (error) {
34
34
  return {
35
35
  ok: false,
@@ -181,7 +181,7 @@ async function captureScreenshot(client, eventId, sessionId, options, score) {
181
181
  * 截图作为附件按 event_id 关联,不塞进事件信封。
182
182
  */
183
183
  function installWhiteScreen(client, options) {
184
- if (!require_objectSpread2.isBrowser()) return () => {};
184
+ if (!require_utils.isBrowser()) return () => {};
185
185
  let timer = null;
186
186
  let loadHandler = null;
187
187
  let reportedSessionId = "";
@@ -251,7 +251,7 @@ function installWhiteScreen(client, options) {
251
251
  white_screen: "true",
252
252
  white_screen_score: snapshot.score
253
253
  },
254
- contexts: { white_screen: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, snapshot), {}, {
254
+ contexts: { white_screen: require_utils._objectSpread2(require_utils._objectSpread2({}, snapshot), {}, {
255
255
  url: window.location.href,
256
256
  route: window.location.pathname
257
257
  }) }
@@ -1,4 +1,4 @@
1
- import { a as trimEndpoint, i as isBrowser, t as _objectSpread2 } from "./objectSpread2-lWxa9t4g.js";
1
+ import { a as _objectSpread2, i as trimEndpoint, r as isBrowser } from "./utils-Gj7Ms2LC.js";
2
2
  // src/attachment.ts
3
3
  /**
4
4
  * 上传白屏截图等附件。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fz-firefly/experience",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
4
4
  "description": "萤火虫 SDK 的可选体验增强:白屏检测、会话回放、用户连线。",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -38,7 +38,7 @@
38
38
  "access": "public"
39
39
  },
40
40
  "dependencies": {
41
- "@fz-firefly/core": "0.7.0",
41
+ "@fz-firefly/core": "0.7.2",
42
42
  "modern-screenshot": "^4.7.0",
43
43
  "rrweb": "^2.2.2"
44
44
  },