@fz-firefly/experience 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,236 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_objectSpread2 = require("./objectSpread2-BYC7ck9c.cjs");
3
+ const require_replay = require("./replay.cjs");
4
+ // src/remote.ts
5
+ const SENSITIVE_KEY_RE = /token|password|secret|authorization|auth|session|cookie|api[_-]?key/i;
6
+ /** 控制台日志里常见的 token / 密码做一次兜底脱敏。 */
7
+ function redactConsole(message) {
8
+ return message.replace(/((?:access_token|refresh_token|id_token|token|password|secret|authorization|api[_-]?key)=)[^&\s]+/gi, "$1[REDACTED]").replace(/("(?:access_token|refresh_token|id_token|token|password|secret|authorization|api[_-]?key)"\s*:\s*")[^"]*"/gi, "$1[REDACTED]\"").replace(/(Bearer\s+)[A-Za-z0-9._~-]+/gi, "$1[REDACTED]").replace(/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, "[REDACTED_JWT]");
9
+ }
10
+ function formatArg(value) {
11
+ if (typeof value === "string") return value;
12
+ if (value instanceof Error) return `${value.name}: ${value.message}`;
13
+ try {
14
+ return JSON.stringify(value);
15
+ } catch (_unused) {
16
+ return String(value);
17
+ }
18
+ }
19
+ function snapshotStorage(maxChars) {
20
+ function read(storage) {
21
+ const result = {};
22
+ for (let i = 0; i < storage.length; i += 1) {
23
+ var _storage$getItem;
24
+ const key = storage.key(i);
25
+ if (!key) continue;
26
+ const raw = (_storage$getItem = storage.getItem(key)) !== null && _storage$getItem !== void 0 ? _storage$getItem : "";
27
+ result[key] = SENSITIVE_KEY_RE.test(key) ? "[REDACTED]" : raw.slice(0, maxChars);
28
+ }
29
+ return result;
30
+ }
31
+ return {
32
+ local: read(window.localStorage),
33
+ session: read(window.sessionStorage)
34
+ };
35
+ }
36
+ /**
37
+ * 安装用户连线。
38
+ *
39
+ * SDK 定时轮询服务端指令,收到 console / storage / replay 命令后执行,
40
+ * 结果通过 POST 回传;不建立长连接,避免大量在线用户占用连接数。
41
+ */
42
+ function installRemote(client, options) {
43
+ if (!require_objectSpread2.isBrowser()) return () => {};
44
+ const runtime = client.getRuntimeInfo();
45
+ const endpoint = require_objectSpread2.trimEndpoint(runtime.endpoint);
46
+ const dsn = runtime.dsn;
47
+ let pageSessionId = runtime.pageSession.id;
48
+ let disposed = false;
49
+ let pollTimer = null;
50
+ let consoleTimer = null;
51
+ let consoleActive = false;
52
+ let consoleCursor = 0;
53
+ let consoleBuffer = [];
54
+ const originalConsole = {
55
+ log: console.log,
56
+ info: console.info,
57
+ warn: console.warn,
58
+ error: console.error
59
+ };
60
+ function captureConsole(level, args) {
61
+ consoleBuffer.push({
62
+ level,
63
+ message: redactConsole(args.map(formatArg).join(" ")).slice(0, 4e3),
64
+ timestamp: Date.now()
65
+ });
66
+ if (consoleBuffer.length > options.consoleBufferSize) {
67
+ const removed = consoleBuffer.length - options.consoleBufferSize;
68
+ consoleBuffer = consoleBuffer.slice(removed);
69
+ consoleCursor = Math.max(0, consoleCursor - removed);
70
+ }
71
+ }
72
+ console.log = (...args) => {
73
+ captureConsole("log", args);
74
+ originalConsole.log(...args);
75
+ };
76
+ console.info = (...args) => {
77
+ captureConsole("info", args);
78
+ originalConsole.info(...args);
79
+ };
80
+ console.warn = (...args) => {
81
+ captureConsole("warn", args);
82
+ originalConsole.warn(...args);
83
+ };
84
+ console.error = (...args) => {
85
+ captureConsole("error", args);
86
+ originalConsole.error(...args);
87
+ };
88
+ async function postResult(commandId, ok, result) {
89
+ try {
90
+ await fetch(`${endpoint}/api/ingest/v1/remote/results?key=${encodeURIComponent(dsn)}`, {
91
+ method: "POST",
92
+ headers: { "content-type": "application/json" },
93
+ body: JSON.stringify({
94
+ command_id: commandId,
95
+ page_session_id: pageSessionId,
96
+ ok,
97
+ result
98
+ }),
99
+ keepalive: true
100
+ });
101
+ } catch (_unused2) {}
102
+ }
103
+ async function postConsole(entries) {
104
+ if (entries.length === 0) return;
105
+ try {
106
+ await fetch(`${endpoint}/api/ingest/v1/remote/events?key=${encodeURIComponent(dsn)}`, {
107
+ method: "POST",
108
+ headers: { "content-type": "application/json" },
109
+ body: JSON.stringify({
110
+ page_session_id: pageSessionId,
111
+ type: "console",
112
+ entries
113
+ }),
114
+ keepalive: true
115
+ });
116
+ } catch (_unused3) {}
117
+ }
118
+ function startConsoleTimer() {
119
+ if (consoleTimer !== null) return;
120
+ consoleTimer = window.setInterval(() => {
121
+ if (!consoleActive) return;
122
+ const pending = consoleBuffer.slice(consoleCursor);
123
+ consoleCursor = consoleBuffer.length;
124
+ postConsole(pending);
125
+ }, 1e3);
126
+ }
127
+ function stopConsoleTimer() {
128
+ if (consoleTimer === null) return;
129
+ window.clearInterval(consoleTimer);
130
+ consoleTimer = null;
131
+ }
132
+ async function execute(command) {
133
+ try {
134
+ switch (command.type) {
135
+ case "console.start":
136
+ consoleActive = true;
137
+ consoleCursor = consoleBuffer.length;
138
+ startConsoleTimer();
139
+ await postResult(command.id, true, { active: true });
140
+ return;
141
+ case "console.stop":
142
+ consoleActive = false;
143
+ stopConsoleTimer();
144
+ await postResult(command.id, true, { active: false });
145
+ return;
146
+ case "storage.snapshot":
147
+ await postResult(command.id, true, snapshotStorage(options.maxStorageValueChars));
148
+ return;
149
+ case "storage.clear": {
150
+ var _command$payload;
151
+ if (!options.allowStorageClear) {
152
+ await postResult(command.id, false, { error: "storage.clear disabled" });
153
+ return;
154
+ }
155
+ const payload = (_command$payload = command.payload) !== null && _command$payload !== void 0 ? _command$payload : {};
156
+ const keys = Array.isArray(payload.keys) ? payload.keys.filter((key) => typeof key === "string") : [];
157
+ if (payload.all === true) {
158
+ window.localStorage.clear();
159
+ window.sessionStorage.clear();
160
+ } else for (const key of keys) {
161
+ window.localStorage.removeItem(key);
162
+ window.sessionStorage.removeItem(key);
163
+ }
164
+ await postResult(command.id, true, { cleared: payload.all === true ? "all" : keys });
165
+ return;
166
+ }
167
+ case "replay.start": {
168
+ const controller = require_replay.getReplayController(client);
169
+ if (!controller) {
170
+ await postResult(command.id, false, { error: "replay disabled" });
171
+ return;
172
+ }
173
+ controller.startManual();
174
+ await postResult(command.id, true, { recording: true });
175
+ return;
176
+ }
177
+ case "replay.stop": {
178
+ const controller = require_replay.getReplayController(client);
179
+ if (!controller) {
180
+ await postResult(command.id, false, { error: "replay disabled" });
181
+ return;
182
+ }
183
+ await controller.stop();
184
+ await postResult(command.id, true, { recording: false });
185
+ return;
186
+ }
187
+ default: await postResult(command.id, false, { error: `unknown command: ${command.type}` });
188
+ }
189
+ } catch (error) {
190
+ await postResult(command.id, false, error instanceof Error ? error.message : String(error));
191
+ }
192
+ }
193
+ async function poll() {
194
+ if (disposed) return;
195
+ let delay = options.pollIntervalMs;
196
+ 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);
205
+ }
206
+ } catch (_unused4) {
207
+ delay = Math.max(delay, 3e4);
208
+ }
209
+ if (!disposed) pollTimer = window.setTimeout(() => {
210
+ poll();
211
+ }, delay);
212
+ }
213
+ const unsubscribeSession = client.onPageSessionStart((info) => {
214
+ pageSessionId = info.id;
215
+ consoleCursor = consoleBuffer.length;
216
+ if (pollTimer !== null) {
217
+ window.clearTimeout(pollTimer);
218
+ pollTimer = null;
219
+ }
220
+ poll();
221
+ });
222
+ poll();
223
+ return () => {
224
+ disposed = true;
225
+ if (pollTimer !== null) window.clearTimeout(pollTimer);
226
+ stopConsoleTimer();
227
+ unsubscribeSession();
228
+ console.log = originalConsole.log;
229
+ console.info = originalConsole.info;
230
+ console.warn = originalConsole.warn;
231
+ console.error = originalConsole.error;
232
+ };
233
+ }
234
+ exports.installRemote = installRemote;
235
+
236
+ //# sourceMappingURL=remote.cjs.map
@@ -0,0 +1,10 @@
1
+ import { i as ResolvedRemoteOptions } from "./options-C2iLgUnA.cjs";
2
+ import { FireflyClient } from "@fz-firefly/core";
3
+ /**
4
+ * 安装用户连线。
5
+ *
6
+ * SDK 定时轮询服务端指令,收到 console / storage / replay 命令后执行,
7
+ * 结果通过 POST 回传;不建立长连接,避免大量在线用户占用连接数。
8
+ */
9
+ export declare function installRemote(client: FireflyClient, options: ResolvedRemoteOptions): () => void;
10
+ //# sourceMappingURL=remote.d.cts.map
@@ -0,0 +1,10 @@
1
+ import { i as ResolvedRemoteOptions } from "./options-C2iLgUnA.js";
2
+ import { FireflyClient } from "@fz-firefly/core";
3
+ /**
4
+ * 安装用户连线。
5
+ *
6
+ * SDK 定时轮询服务端指令,收到 console / storage / replay 命令后执行,
7
+ * 结果通过 POST 回传;不建立长连接,避免大量在线用户占用连接数。
8
+ */
9
+ export declare function installRemote(client: FireflyClient, options: ResolvedRemoteOptions): () => void;
10
+ //# sourceMappingURL=remote.d.ts.map
package/dist/remote.js ADDED
@@ -0,0 +1,235 @@
1
+ import { a as trimEndpoint, i as isBrowser } from "./objectSpread2-lWxa9t4g.js";
2
+ import { getReplayController } from "./replay.js";
3
+ // src/remote.ts
4
+ const SENSITIVE_KEY_RE = /token|password|secret|authorization|auth|session|cookie|api[_-]?key/i;
5
+ /** 控制台日志里常见的 token / 密码做一次兜底脱敏。 */
6
+ function redactConsole(message) {
7
+ return message.replace(/((?:access_token|refresh_token|id_token|token|password|secret|authorization|api[_-]?key)=)[^&\s]+/gi, "$1[REDACTED]").replace(/("(?:access_token|refresh_token|id_token|token|password|secret|authorization|api[_-]?key)"\s*:\s*")[^"]*"/gi, "$1[REDACTED]\"").replace(/(Bearer\s+)[A-Za-z0-9._~-]+/gi, "$1[REDACTED]").replace(/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, "[REDACTED_JWT]");
8
+ }
9
+ function formatArg(value) {
10
+ if (typeof value === "string") return value;
11
+ if (value instanceof Error) return `${value.name}: ${value.message}`;
12
+ try {
13
+ return JSON.stringify(value);
14
+ } catch (_unused) {
15
+ return String(value);
16
+ }
17
+ }
18
+ function snapshotStorage(maxChars) {
19
+ function read(storage) {
20
+ const result = {};
21
+ for (let i = 0; i < storage.length; i += 1) {
22
+ var _storage$getItem;
23
+ const key = storage.key(i);
24
+ if (!key) continue;
25
+ const raw = (_storage$getItem = storage.getItem(key)) !== null && _storage$getItem !== void 0 ? _storage$getItem : "";
26
+ result[key] = SENSITIVE_KEY_RE.test(key) ? "[REDACTED]" : raw.slice(0, maxChars);
27
+ }
28
+ return result;
29
+ }
30
+ return {
31
+ local: read(window.localStorage),
32
+ session: read(window.sessionStorage)
33
+ };
34
+ }
35
+ /**
36
+ * 安装用户连线。
37
+ *
38
+ * SDK 定时轮询服务端指令,收到 console / storage / replay 命令后执行,
39
+ * 结果通过 POST 回传;不建立长连接,避免大量在线用户占用连接数。
40
+ */
41
+ function installRemote(client, options) {
42
+ if (!isBrowser()) return () => {};
43
+ const runtime = client.getRuntimeInfo();
44
+ const endpoint = trimEndpoint(runtime.endpoint);
45
+ const dsn = runtime.dsn;
46
+ let pageSessionId = runtime.pageSession.id;
47
+ let disposed = false;
48
+ let pollTimer = null;
49
+ let consoleTimer = null;
50
+ let consoleActive = false;
51
+ let consoleCursor = 0;
52
+ let consoleBuffer = [];
53
+ const originalConsole = {
54
+ log: console.log,
55
+ info: console.info,
56
+ warn: console.warn,
57
+ error: console.error
58
+ };
59
+ function captureConsole(level, args) {
60
+ consoleBuffer.push({
61
+ level,
62
+ message: redactConsole(args.map(formatArg).join(" ")).slice(0, 4e3),
63
+ timestamp: Date.now()
64
+ });
65
+ if (consoleBuffer.length > options.consoleBufferSize) {
66
+ const removed = consoleBuffer.length - options.consoleBufferSize;
67
+ consoleBuffer = consoleBuffer.slice(removed);
68
+ consoleCursor = Math.max(0, consoleCursor - removed);
69
+ }
70
+ }
71
+ console.log = (...args) => {
72
+ captureConsole("log", args);
73
+ originalConsole.log(...args);
74
+ };
75
+ console.info = (...args) => {
76
+ captureConsole("info", args);
77
+ originalConsole.info(...args);
78
+ };
79
+ console.warn = (...args) => {
80
+ captureConsole("warn", args);
81
+ originalConsole.warn(...args);
82
+ };
83
+ console.error = (...args) => {
84
+ captureConsole("error", args);
85
+ originalConsole.error(...args);
86
+ };
87
+ async function postResult(commandId, ok, result) {
88
+ try {
89
+ await fetch(`${endpoint}/api/ingest/v1/remote/results?key=${encodeURIComponent(dsn)}`, {
90
+ method: "POST",
91
+ headers: { "content-type": "application/json" },
92
+ body: JSON.stringify({
93
+ command_id: commandId,
94
+ page_session_id: pageSessionId,
95
+ ok,
96
+ result
97
+ }),
98
+ keepalive: true
99
+ });
100
+ } catch (_unused2) {}
101
+ }
102
+ async function postConsole(entries) {
103
+ if (entries.length === 0) return;
104
+ try {
105
+ await fetch(`${endpoint}/api/ingest/v1/remote/events?key=${encodeURIComponent(dsn)}`, {
106
+ method: "POST",
107
+ headers: { "content-type": "application/json" },
108
+ body: JSON.stringify({
109
+ page_session_id: pageSessionId,
110
+ type: "console",
111
+ entries
112
+ }),
113
+ keepalive: true
114
+ });
115
+ } catch (_unused3) {}
116
+ }
117
+ function startConsoleTimer() {
118
+ if (consoleTimer !== null) return;
119
+ consoleTimer = window.setInterval(() => {
120
+ if (!consoleActive) return;
121
+ const pending = consoleBuffer.slice(consoleCursor);
122
+ consoleCursor = consoleBuffer.length;
123
+ postConsole(pending);
124
+ }, 1e3);
125
+ }
126
+ function stopConsoleTimer() {
127
+ if (consoleTimer === null) return;
128
+ window.clearInterval(consoleTimer);
129
+ consoleTimer = null;
130
+ }
131
+ async function execute(command) {
132
+ try {
133
+ switch (command.type) {
134
+ case "console.start":
135
+ consoleActive = true;
136
+ consoleCursor = consoleBuffer.length;
137
+ startConsoleTimer();
138
+ await postResult(command.id, true, { active: true });
139
+ return;
140
+ case "console.stop":
141
+ consoleActive = false;
142
+ stopConsoleTimer();
143
+ await postResult(command.id, true, { active: false });
144
+ return;
145
+ case "storage.snapshot":
146
+ await postResult(command.id, true, snapshotStorage(options.maxStorageValueChars));
147
+ return;
148
+ case "storage.clear": {
149
+ var _command$payload;
150
+ if (!options.allowStorageClear) {
151
+ await postResult(command.id, false, { error: "storage.clear disabled" });
152
+ return;
153
+ }
154
+ const payload = (_command$payload = command.payload) !== null && _command$payload !== void 0 ? _command$payload : {};
155
+ const keys = Array.isArray(payload.keys) ? payload.keys.filter((key) => typeof key === "string") : [];
156
+ if (payload.all === true) {
157
+ window.localStorage.clear();
158
+ window.sessionStorage.clear();
159
+ } else for (const key of keys) {
160
+ window.localStorage.removeItem(key);
161
+ window.sessionStorage.removeItem(key);
162
+ }
163
+ await postResult(command.id, true, { cleared: payload.all === true ? "all" : keys });
164
+ return;
165
+ }
166
+ case "replay.start": {
167
+ const controller = getReplayController(client);
168
+ if (!controller) {
169
+ await postResult(command.id, false, { error: "replay disabled" });
170
+ return;
171
+ }
172
+ controller.startManual();
173
+ await postResult(command.id, true, { recording: true });
174
+ return;
175
+ }
176
+ case "replay.stop": {
177
+ const controller = getReplayController(client);
178
+ if (!controller) {
179
+ await postResult(command.id, false, { error: "replay disabled" });
180
+ return;
181
+ }
182
+ await controller.stop();
183
+ await postResult(command.id, true, { recording: false });
184
+ return;
185
+ }
186
+ default: await postResult(command.id, false, { error: `unknown command: ${command.type}` });
187
+ }
188
+ } catch (error) {
189
+ await postResult(command.id, false, error instanceof Error ? error.message : String(error));
190
+ }
191
+ }
192
+ async function poll() {
193
+ if (disposed) return;
194
+ let delay = options.pollIntervalMs;
195
+ 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);
204
+ }
205
+ } catch (_unused4) {
206
+ delay = Math.max(delay, 3e4);
207
+ }
208
+ if (!disposed) pollTimer = window.setTimeout(() => {
209
+ poll();
210
+ }, delay);
211
+ }
212
+ const unsubscribeSession = client.onPageSessionStart((info) => {
213
+ pageSessionId = info.id;
214
+ consoleCursor = consoleBuffer.length;
215
+ if (pollTimer !== null) {
216
+ window.clearTimeout(pollTimer);
217
+ pollTimer = null;
218
+ }
219
+ poll();
220
+ });
221
+ poll();
222
+ return () => {
223
+ disposed = true;
224
+ if (pollTimer !== null) window.clearTimeout(pollTimer);
225
+ stopConsoleTimer();
226
+ unsubscribeSession();
227
+ console.log = originalConsole.log;
228
+ console.info = originalConsole.info;
229
+ console.warn = originalConsole.warn;
230
+ console.error = originalConsole.error;
231
+ };
232
+ }
233
+ export { installRemote };
234
+
235
+ //# sourceMappingURL=remote.js.map