@kuafucloud/developer 0.0.0-stage → 0.1.9-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin/admin/extension.zip +0 -0
- package/dist/admin/index.d.ts +2 -0
- package/dist/admin/index.js +2 -0
- package/dist/admin/meta/admin.json +59 -0
- package/dist/admin/meta/extension-manifest.json +794 -0
- package/dist/facade/index.d.ts +241 -0
- package/dist/facade/index.js +11 -0
- package/dist/monitor/runtime-services/app/index.js +660 -0
- package/dist/monitor/runtime-services/app/service-module.config.json +16 -0
- package/dist/monitor/runtime-services/app-simulator/index.js +648 -0
- package/dist/monitor/runtime-services/app-simulator/service-module.config.json +12 -0
- package/dist/monitor/runtime-services/mini-program/index.js +653 -0
- package/dist/monitor/runtime-services/mini-program/service-module.config.json +12 -0
- package/dist/monitor/runtime-services/mini-program-simulator/index.js +648 -0
- package/dist/monitor/runtime-services/mini-program-simulator/service-module.config.json +12 -0
- package/dist/monitor/runtime-services/site/index.js +648 -0
- package/dist/monitor/runtime-services/site/service-module.config.json +12 -0
- package/dist/public/monitor/index.js +6 -0
- package/dist/public/monitor/runtime-services/core/index.js +552 -0
- package/dist/public/realtime/host/index.js +4550 -0
- package/dist/public/realtime/index.js +3180 -0
- package/dist/public/realtime/native-preview-http/index.js +148 -0
- package/dist/simulation/artifact/meta/database.json +43 -0
- package/dist/simulation/artifact/meta/manifest.json +170 -0
- package/dist/simulation/artifact/meta/runtime-meta.json +28 -0
- package/dist/simulation/artifact/meta/schema.json +41 -0
- package/dist/simulation/artifact/server/worker/index.js +39 -0
- package/dist/simulation/artifact/server/worker/monitoring-contract.json +7 -0
- package/dist/simulation/index.d.ts +1 -0
- package/dist/simulation/index.js +1 -0
- package/dist/types/monitor/client/index.d.ts +4 -0
- package/dist/types/monitor/runtime-services/app/index.d.ts +4 -0
- package/dist/types/monitor/runtime-services/app-simulator/index.d.ts +4 -0
- package/dist/types/monitor/runtime-services/core/index.d.ts +1 -0
- package/dist/types/monitor/runtime-services/core/monitor-browser-service.d.ts +25 -0
- package/dist/types/monitor/runtime-services/core/monitor-mini-program-service.d.ts +25 -0
- package/dist/types/monitor/runtime-services/core/monitor-native-service.d.ts +25 -0
- package/dist/types/monitor/runtime-services/core/monitor-service.d.ts +35 -0
- package/dist/types/monitor/runtime-services/mini-program/index.d.ts +4 -0
- package/dist/types/monitor/runtime-services/mini-program-simulator/index.d.ts +4 -0
- package/dist/types/monitor/runtime-services/site/index.d.ts +4 -0
- package/dist/types/realtime/agent-chat-model.d.ts +216 -0
- package/dist/types/realtime/agent-question.d.ts +24 -0
- package/dist/types/realtime/developer-realtime.d.ts +158 -0
- package/dist/types/realtime/host/index.d.ts +28 -0
- package/dist/types/realtime/host-channels.d.ts +52 -0
- package/dist/types/realtime/host-connection.d.ts +131 -0
- package/dist/types/realtime/native-preview-http/index.d.ts +6 -0
- package/dist/types/realtime/native-source-codec.d.ts +21 -0
- package/dist/types/realtime/payload-fragments.d.ts +21 -0
- package/dist/types/realtime/preview-device.d.ts +9 -0
- package/dist/types/realtime/product-preview-cache.d.ts +69 -0
- package/dist/types/realtime/product-preview-clients.d.ts +7 -0
- package/dist/types/realtime/product-preview-host.d.ts +50 -0
- package/dist/types/realtime/product-preview-http-runtime.d.ts +9 -0
- package/dist/types/realtime/product-preview-protocol.d.ts +167 -0
- package/dist/types/realtime/product-preview-socket-source.d.ts +24 -0
- package/dist/types/realtime/product-preview-viewer-http.d.ts +41 -0
- package/dist/types/realtime/product-preview-viewer.d.ts +44 -0
- package/dist/types/realtime/project-workspaces.d.ts +43 -0
- package/dist/types/realtime/viewer/index.d.ts +22 -0
- package/dist/types/realtime/websocket-transport.d.ts +12 -0
- package/dist/types/realtime/workspace-agent-history.d.ts +46 -0
- package/dist/types/realtime/workspace-agent-input.d.ts +38 -0
- package/dist/types/realtime/workspace-agent-member.d.ts +15 -0
- package/dist/types/realtime/workspace-agent-view.d.ts +22 -0
- package/dist/types/realtime/workspace-cache-store.d.ts +38 -0
- package/dist/types/realtime/workspace-cache.d.ts +72 -0
- package/dist/types/realtime/workspace-chat-stream.d.ts +6 -0
- package/dist/types/realtime/workspace-file-view.d.ts +9 -0
- package/dist/types/realtime/workspace-status-view.d.ts +8 -0
- package/dist/types/realtime/workspace-viewer.d.ts +100 -0
- package/extension-manifest.json +457 -0
- package/package.json +112 -4
- package/README.md +0 -3
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
// index.ts
|
|
2
|
+
import { Monitor } from "@kuafucloud/developer/monitor";
|
|
3
|
+
|
|
4
|
+
// ../core/monitor-service.ts
|
|
5
|
+
import {
|
|
6
|
+
assertMonitorDeliveryActive,
|
|
7
|
+
createMonitorErrorDelivery,
|
|
8
|
+
createMonitorTraceDelivery,
|
|
9
|
+
monitorDeliveryCreatedAt,
|
|
10
|
+
sanitizeMonitorText,
|
|
11
|
+
MONITOR_DELIVERY_RETRY_WINDOW_MS,
|
|
12
|
+
monitorUtf8ByteLength
|
|
13
|
+
} from "@kuafucloud/product-runtime-protocol";
|
|
14
|
+
var OUTBOX_KEY = "state";
|
|
15
|
+
var MAX_ITEMS = 1e3;
|
|
16
|
+
var MAX_GROUPS = 64;
|
|
17
|
+
var MAX_STATE_BYTES = 5 * 1024 * 1024;
|
|
18
|
+
var KEY = /^[a-zA-Z][a-zA-Z0-9_.-]{0,47}$/u;
|
|
19
|
+
var STABLE = /^[a-zA-Z][a-zA-Z0-9_.:-]{0,127}$/u;
|
|
20
|
+
var FORBIDDEN = /token|password|secret|authorization|cookie|headers|body|sql|params/iu;
|
|
21
|
+
var CoreError = class extends Error {
|
|
22
|
+
constructor(code) {
|
|
23
|
+
super(code);
|
|
24
|
+
this.code = code;
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
function createMonitorService(context) {
|
|
28
|
+
const store = context.storage.durable("monitor.outbox.v1"), backend = context.backend;
|
|
29
|
+
const pending = /* @__PURE__ */ new Map();
|
|
30
|
+
const controllers = /* @__PURE__ */ new Set();
|
|
31
|
+
const rootPromises = /* @__PURE__ */ new WeakMap();
|
|
32
|
+
let state = { schemaVersion: 1, groups: [] }, updates = Promise.resolve(), sends = Promise.resolve(), closed = false;
|
|
33
|
+
let started = false, draining = false, retryMs = 1e3;
|
|
34
|
+
let wakeTimer, background;
|
|
35
|
+
const diagnostic = (code) => {
|
|
36
|
+
try {
|
|
37
|
+
context.diagnostics.write({ code });
|
|
38
|
+
} catch {
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
const serialize = (run) => {
|
|
42
|
+
const result = updates.then(run, run);
|
|
43
|
+
updates = result.then(() => void 0, () => void 0);
|
|
44
|
+
return result;
|
|
45
|
+
};
|
|
46
|
+
const mutate = (run) => serialize(() => backend.withOutboxLock(async () => {
|
|
47
|
+
state = restore(await store.get(OUTBOX_KEY));
|
|
48
|
+
return run();
|
|
49
|
+
}));
|
|
50
|
+
async function persist(next) {
|
|
51
|
+
if (bytes(next) > MAX_STATE_BYTES) throw new CoreError("monitor.outbox_full");
|
|
52
|
+
await store.set(OUTBOX_KEY, clone(next));
|
|
53
|
+
state = next;
|
|
54
|
+
}
|
|
55
|
+
const track = (id, task) => {
|
|
56
|
+
pending.set(task, id);
|
|
57
|
+
void task.then(() => pending.delete(task), () => pending.delete(task));
|
|
58
|
+
return task;
|
|
59
|
+
};
|
|
60
|
+
function occurrence() {
|
|
61
|
+
try {
|
|
62
|
+
return validateOccurrence(backend.occurrence());
|
|
63
|
+
} catch {
|
|
64
|
+
throw new CoreError("monitor.source_unavailable");
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function append(item, snapshot) {
|
|
68
|
+
if (bytes(item) > 64 * 1024) throw new CoreError("monitor.payload_too_large");
|
|
69
|
+
return mutate(async () => {
|
|
70
|
+
if (closed) throw new CoreError("monitor.unavailable");
|
|
71
|
+
if (!(await backend.validateScope(snapshot)).active) throw new CoreError("monitor.source_unavailable");
|
|
72
|
+
if (closed) throw new CoreError("monitor.unavailable");
|
|
73
|
+
const existingGroup = state.groups.find((g) => g.items.some((candidate) => memberId(candidate) === memberId(item)));
|
|
74
|
+
if (existingGroup) {
|
|
75
|
+
const previous = existingGroup.items.find((candidate) => memberId(candidate) === memberId(item));
|
|
76
|
+
if (!sameAuthority(existingGroup, snapshot) || JSON.stringify(previous) !== JSON.stringify(item)) throw new CoreError("monitor.protocol_rejected");
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (count(state) >= MAX_ITEMS) throw new CoreError("monitor.outbox_full");
|
|
80
|
+
const next = clone(state), channel = item.kind === "error" ? "errors" : "traces";
|
|
81
|
+
let group = next.groups.find((g) => g.channel === channel && sameAuthority(g, snapshot));
|
|
82
|
+
if (!group) {
|
|
83
|
+
if (next.groups.length >= MAX_GROUPS) throw new CoreError("monitor.outbox_full");
|
|
84
|
+
group = { authorityScopeKey: snapshot.authorityScopeKey, channel, items: [] };
|
|
85
|
+
next.groups.push(group);
|
|
86
|
+
}
|
|
87
|
+
group.items.push(clone(item));
|
|
88
|
+
await persist(next);
|
|
89
|
+
schedule();
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
function capture(error, input = {}, mechanism = "handled", root, spanId = null, previous) {
|
|
93
|
+
if (closed || root?.closed) return Promise.resolve(failure("monitor.unavailable"));
|
|
94
|
+
let eventContext;
|
|
95
|
+
try {
|
|
96
|
+
eventContext = snapshotContext(input);
|
|
97
|
+
} catch {
|
|
98
|
+
return Promise.resolve(failure("monitor.context_invalid"));
|
|
99
|
+
}
|
|
100
|
+
const object = error !== null && typeof error === "object" ? error : null;
|
|
101
|
+
let entry = previous ?? (object && root ? root.errors.get(object) : void 0);
|
|
102
|
+
if (entry?.pending) return entry.pending;
|
|
103
|
+
if (entry?.queued) return Promise.resolve(entry.queued);
|
|
104
|
+
if (!entry) {
|
|
105
|
+
let snapshot;
|
|
106
|
+
try {
|
|
107
|
+
snapshot = root ? root.occurrence : occurrence();
|
|
108
|
+
} catch {
|
|
109
|
+
return Promise.resolve(failure("monitor.source_unavailable"));
|
|
110
|
+
}
|
|
111
|
+
if (!snapshot) return Promise.resolve(failure("monitor.source_unavailable"));
|
|
112
|
+
entry = { snapshot, event: clone({
|
|
113
|
+
schemaVersion: 1,
|
|
114
|
+
kind: "error",
|
|
115
|
+
eventId: crypto.randomUUID(),
|
|
116
|
+
occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
117
|
+
source: snapshot.source,
|
|
118
|
+
mechanism,
|
|
119
|
+
error: normalizeError(error),
|
|
120
|
+
context: eventContext,
|
|
121
|
+
traceId: root?.traceId ?? null,
|
|
122
|
+
spanId: root?.traceId ? spanId : null
|
|
123
|
+
}) };
|
|
124
|
+
if (object && root) root.errors.set(object, entry);
|
|
125
|
+
}
|
|
126
|
+
const occurrenceEntry = entry;
|
|
127
|
+
const task = (async () => {
|
|
128
|
+
try {
|
|
129
|
+
await append(occurrenceEntry.event, occurrenceEntry.snapshot);
|
|
130
|
+
const receipt = { ok: true, data: { state: "queued", eventId: occurrenceEntry.event.eventId } };
|
|
131
|
+
occurrenceEntry.queued = receipt;
|
|
132
|
+
return receipt;
|
|
133
|
+
} catch (error2) {
|
|
134
|
+
diagnostic("monitor.capture_failed");
|
|
135
|
+
return failure(error2 instanceof CoreError ? error2.code : "monitor.capture_failed");
|
|
136
|
+
}
|
|
137
|
+
})();
|
|
138
|
+
occurrenceEntry.pending = task;
|
|
139
|
+
void task.then(() => {
|
|
140
|
+
if (occurrenceEntry.pending === task) delete occurrenceEntry.pending;
|
|
141
|
+
});
|
|
142
|
+
return track(occurrenceEntry.event.eventId, task);
|
|
143
|
+
}
|
|
144
|
+
async function runSpan(root, parentSpanId, name, run, options) {
|
|
145
|
+
let active = true;
|
|
146
|
+
const valid = typeof name === "string" && /^[\p{L}][\p{L}\p{N}_. -]{0,95}$/u.test(name);
|
|
147
|
+
let span;
|
|
148
|
+
if (root.traceId && !root.closed && !closed) {
|
|
149
|
+
if (!valid || root.spans.length >= 100) root.droppedSpans += 1;
|
|
150
|
+
else {
|
|
151
|
+
const attributes = snapshotAttributes(options);
|
|
152
|
+
span = {
|
|
153
|
+
spanId: hex(8),
|
|
154
|
+
parentSpanId,
|
|
155
|
+
name,
|
|
156
|
+
kind: "business",
|
|
157
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
158
|
+
durationMs: null,
|
|
159
|
+
state: "running",
|
|
160
|
+
status: "ok",
|
|
161
|
+
attributes: attributes.values,
|
|
162
|
+
droppedAttributes: attributes.dropped
|
|
163
|
+
};
|
|
164
|
+
root.spans.push(span);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const handle = Object.freeze({
|
|
168
|
+
captureException: (error, input) => active && !root.closed ? capture(error, input, "handled", root, span?.spanId ?? parentSpanId) : Promise.resolve(failure("monitor.unavailable")),
|
|
169
|
+
withSpan: (childName, childRun, childOptions) => {
|
|
170
|
+
if (!active || root.closed) {
|
|
171
|
+
diagnostic("monitor.span_outside_callback");
|
|
172
|
+
return runSpan({ ...root, traceId: null, occurrence: null, closed: true }, null, childName, childRun, childOptions);
|
|
173
|
+
}
|
|
174
|
+
return runSpan(root, span?.spanId ?? parentSpanId, childName, childRun, childOptions);
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
const start = performance.now();
|
|
178
|
+
try {
|
|
179
|
+
return await run(handle);
|
|
180
|
+
} catch (error) {
|
|
181
|
+
if (span) span.status = "error";
|
|
182
|
+
throw error;
|
|
183
|
+
} finally {
|
|
184
|
+
active = false;
|
|
185
|
+
if (span) {
|
|
186
|
+
span.durationMs = Math.min(864e5, Math.max(0, performance.now() - start));
|
|
187
|
+
span.state = "finished";
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
function withSpan(name, run, options) {
|
|
192
|
+
let snapshot = null;
|
|
193
|
+
if (!closed) {
|
|
194
|
+
try {
|
|
195
|
+
snapshot = occurrence();
|
|
196
|
+
} catch {
|
|
197
|
+
diagnostic("monitor.span_source_unavailable");
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const root = {
|
|
201
|
+
occurrence: snapshot,
|
|
202
|
+
traceId: snapshot && sample(snapshot.traceSampleRate) ? hex(16) : null,
|
|
203
|
+
spans: [],
|
|
204
|
+
droppedSpans: 0,
|
|
205
|
+
closed: false,
|
|
206
|
+
errors: /* @__PURE__ */ new WeakMap()
|
|
207
|
+
};
|
|
208
|
+
const task = (async () => {
|
|
209
|
+
try {
|
|
210
|
+
return await runSpan(root, null, name, run, options);
|
|
211
|
+
} finally {
|
|
212
|
+
root.closed = true;
|
|
213
|
+
if (snapshot && root.traceId && root.spans.length && !closed) {
|
|
214
|
+
const trace = clone({
|
|
215
|
+
schemaVersion: 1,
|
|
216
|
+
kind: "trace",
|
|
217
|
+
traceId: root.traceId,
|
|
218
|
+
source: snapshot.source,
|
|
219
|
+
sampling: { unit: "trace", rule: "head-random", probability: snapshot.traceSampleRate, ruleVersion: 1 },
|
|
220
|
+
spans: root.spans,
|
|
221
|
+
droppedSpans: root.droppedSpans
|
|
222
|
+
});
|
|
223
|
+
track(root.traceId, append(trace, snapshot).catch(() => {
|
|
224
|
+
diagnostic("monitor.trace_append_failed");
|
|
225
|
+
}));
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
})();
|
|
229
|
+
rootPromises.set(task, root);
|
|
230
|
+
return task;
|
|
231
|
+
}
|
|
232
|
+
async function release(ids, deliveryId) {
|
|
233
|
+
const next = clone(state);
|
|
234
|
+
for (const group of next.groups) {
|
|
235
|
+
group.items = group.items.filter((item) => !ids.has(memberId(item)));
|
|
236
|
+
if (group.delivery && group.delivery.deliveryId === deliveryId) delete group.delivery;
|
|
237
|
+
}
|
|
238
|
+
next.groups = next.groups.filter((group) => group.items.length > 0);
|
|
239
|
+
await persist(next);
|
|
240
|
+
}
|
|
241
|
+
const flush = (input, options) => {
|
|
242
|
+
if (closed) return Promise.resolve(failure("monitor.unavailable"));
|
|
243
|
+
const timeoutMs = input?.timeoutMs ?? 1e4;
|
|
244
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs < 1 || timeoutMs > 6e4) return Promise.resolve(failure("monitor.context_invalid"));
|
|
245
|
+
const controller = new AbortController(), abort = () => controller.abort("cancelled");
|
|
246
|
+
controllers.add(controller);
|
|
247
|
+
if (options?.signal?.aborted) abort();
|
|
248
|
+
else options?.signal?.addEventListener("abort", abort, { once: true });
|
|
249
|
+
const timeout = setTimeout(() => controller.abort("timeout"), timeoutMs);
|
|
250
|
+
const waiting = [...pending], initial = mutate(async () => state.groups.flatMap((g) => g.items.map(memberId)));
|
|
251
|
+
void initial.catch(() => void 0);
|
|
252
|
+
const execute = async () => {
|
|
253
|
+
const outcomes = [];
|
|
254
|
+
try {
|
|
255
|
+
const boundary = new Set(await abortable(initial, controller.signal));
|
|
256
|
+
await abortable(Promise.all(waiting.map(([task2]) => task2)), controller.signal);
|
|
257
|
+
waiting.forEach(([, id]) => boundary.add(id));
|
|
258
|
+
while (true) {
|
|
259
|
+
checkAbort(controller.signal);
|
|
260
|
+
const work = await mutate(async () => {
|
|
261
|
+
checkAbort(controller.signal);
|
|
262
|
+
const group = state.groups.find((g) => g.items.some((item) => boundary.has(memberId(item))));
|
|
263
|
+
if (!group) return { kind: "done", remaining: count(state) };
|
|
264
|
+
const validity = await backend.validateScope(group);
|
|
265
|
+
checkAbort(controller.signal);
|
|
266
|
+
if (!validity.active) {
|
|
267
|
+
const ids2 = new Set(group.items.filter((item) => boundary.has(memberId(item))).map(memberId));
|
|
268
|
+
if (group.delivery) deliveryItems(group.delivery).forEach((item) => ids2.add(memberId(item)));
|
|
269
|
+
await release(ids2, group.delivery?.deliveryId);
|
|
270
|
+
return { kind: "terminal", outcomes: [...ids2].map((eventId) => ({ eventId, status: "rejected", reason: validity.reason })) };
|
|
271
|
+
}
|
|
272
|
+
if (!group.delivery) {
|
|
273
|
+
const expired = new Set(group.items.filter((item) => boundary.has(memberId(item)) && occurrenceExpired(item)).map(memberId));
|
|
274
|
+
if (expired.size) {
|
|
275
|
+
await release(expired);
|
|
276
|
+
return { kind: "terminal", outcomes: [...expired].map((eventId) => ({ eventId, status: "rejected", reason: "occurrence_window_expired" })) };
|
|
277
|
+
}
|
|
278
|
+
const next = clone(state), target = next.groups.find((g) => g === group || sameGroup(g, group));
|
|
279
|
+
target.delivery = freezeBatch(group.items.filter((item) => boundary.has(memberId(item))), group.channel);
|
|
280
|
+
await persist(next);
|
|
281
|
+
}
|
|
282
|
+
const current = state.groups.find((g) => sameGroup(g, group)), delivery = current.delivery;
|
|
283
|
+
try {
|
|
284
|
+
assertMonitorDeliveryActive(delivery.deliveryId, Date.now());
|
|
285
|
+
} catch (error) {
|
|
286
|
+
if (!(error instanceof Error) || !("code" in error) || error.code !== "monitor.delivery_expired") throw new CoreError("monitor.protocol_rejected");
|
|
287
|
+
const ids2 = new Set(deliveryItems(delivery).map(memberId));
|
|
288
|
+
await release(ids2, delivery.deliveryId);
|
|
289
|
+
return { kind: "terminal", outcomes: [...ids2].map((eventId) => ({ eventId, status: "rejected", reason: "retry_window_expired" })) };
|
|
290
|
+
}
|
|
291
|
+
if (deliveryItems(delivery).some(occurrenceExpired)) {
|
|
292
|
+
const ids2 = new Set(deliveryItems(delivery).map(memberId));
|
|
293
|
+
await release(ids2, delivery.deliveryId);
|
|
294
|
+
return { kind: "terminal", outcomes: [...ids2].map((eventId) => ({ eventId, status: "rejected", reason: "occurrence_window_expired" })) };
|
|
295
|
+
}
|
|
296
|
+
return { kind: "batch", input: clone({ authorityScopeKey: current.authorityScopeKey, delivery }) };
|
|
297
|
+
});
|
|
298
|
+
if (work.kind === "done") return { ok: true, data: { completed: true, remaining: work.remaining, outcomes } };
|
|
299
|
+
if (work.kind === "terminal") {
|
|
300
|
+
outcomes.push(...work.outcomes.filter((o) => boundary.has(o.eventId)));
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
checkAbort(controller.signal);
|
|
304
|
+
const batch = deepFreeze(work.input), ids = new Set(deliveryItems(batch.delivery).map(memberId));
|
|
305
|
+
const receipt = await abortable(backend.send(batch, { signal: controller.signal }), controller.signal);
|
|
306
|
+
if (receipt.deliveryId !== batch.delivery.deliveryId || !["accepted", "duplicate"].includes(receipt.status) || receipt.memberCount !== ids.size || !Number.isFinite(Date.parse(receipt.receivedAt))) throw new CoreError("monitor.protocol_rejected");
|
|
307
|
+
checkAbort(controller.signal);
|
|
308
|
+
await mutate(async () => {
|
|
309
|
+
checkAbort(controller.signal);
|
|
310
|
+
await release(ids, batch.delivery.deliveryId);
|
|
311
|
+
});
|
|
312
|
+
for (const eventId of ids) if (boundary.has(eventId)) outcomes.push({ eventId, status: receipt.status });
|
|
313
|
+
}
|
|
314
|
+
} catch (error) {
|
|
315
|
+
diagnostic("monitor.flush_failed");
|
|
316
|
+
return failure(controller.signal.aborted ? controller.signal.reason === "timeout" ? "request.timeout" : "request.cancelled" : error instanceof CoreError ? error.code : "network.failed");
|
|
317
|
+
} finally {
|
|
318
|
+
controllers.delete(controller);
|
|
319
|
+
clearTimeout(timeout);
|
|
320
|
+
options?.signal?.removeEventListener("abort", abort);
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
const task = sends.then(execute, execute);
|
|
324
|
+
sends = task.then(() => void 0, () => void 0);
|
|
325
|
+
return abortable(task, controller.signal).catch(() => failure(controller.signal.reason === "timeout" ? "request.timeout" : "request.cancelled")).finally(() => {
|
|
326
|
+
controllers.delete(controller);
|
|
327
|
+
clearTimeout(timeout);
|
|
328
|
+
options?.signal?.removeEventListener("abort", abort);
|
|
329
|
+
});
|
|
330
|
+
};
|
|
331
|
+
const api = Object.freeze({ captureException: (error, input) => capture(error, input), withSpan, flush });
|
|
332
|
+
function cancelWake() {
|
|
333
|
+
if (wakeTimer !== void 0) clearTimeout(wakeTimer);
|
|
334
|
+
wakeTimer = void 0;
|
|
335
|
+
}
|
|
336
|
+
function schedule(delay = 1e3) {
|
|
337
|
+
if (!started || closed || draining || wakeTimer !== void 0 || background) return;
|
|
338
|
+
wakeTimer = setTimeout(() => {
|
|
339
|
+
wakeTimer = void 0;
|
|
340
|
+
if (closed || draining) return;
|
|
341
|
+
background = (async () => {
|
|
342
|
+
const result = await flush();
|
|
343
|
+
background = void 0;
|
|
344
|
+
if (closed || draining) return;
|
|
345
|
+
if (result.ok) {
|
|
346
|
+
retryMs = 1e3;
|
|
347
|
+
if (result.data.remaining > 0 || count(state) > 0 || pending.size > 0) schedule();
|
|
348
|
+
} else if (result.error.retryable) {
|
|
349
|
+
schedule(retryMs);
|
|
350
|
+
retryMs = Math.min(6e4, retryMs * 2);
|
|
351
|
+
}
|
|
352
|
+
})().catch(() => {
|
|
353
|
+
background = void 0;
|
|
354
|
+
diagnostic("monitor.background_flush_failed");
|
|
355
|
+
});
|
|
356
|
+
}, delay);
|
|
357
|
+
}
|
|
358
|
+
return {
|
|
359
|
+
api,
|
|
360
|
+
start: async (input) => {
|
|
361
|
+
if (closed || input.signal.aborted) throw new CoreError("monitor.unavailable");
|
|
362
|
+
if (started) return;
|
|
363
|
+
started = true;
|
|
364
|
+
schedule(0);
|
|
365
|
+
},
|
|
366
|
+
/** 生命周期和连通性只唤醒既有 Outbox,不给业务暴露传输配置。 */
|
|
367
|
+
wake: () => {
|
|
368
|
+
retryMs = 1e3;
|
|
369
|
+
cancelWake();
|
|
370
|
+
schedule(0);
|
|
371
|
+
},
|
|
372
|
+
/** Runtime 自动适配入口,不作为业务 API 导出。 */
|
|
373
|
+
captureAutomatic: (error, mechanism = "unhandled", correlation) => {
|
|
374
|
+
const root = correlation ? rootPromises.get(correlation) : void 0;
|
|
375
|
+
const previous = error && typeof error === "object" ? root?.errors.get(error) : void 0;
|
|
376
|
+
return capture(error, {}, mechanism, void 0, null, previous);
|
|
377
|
+
},
|
|
378
|
+
drain: async (input) => {
|
|
379
|
+
draining = true;
|
|
380
|
+
cancelWake();
|
|
381
|
+
const result = await flush({ timeoutMs: Math.max(1, Math.min(6e4, input.deadline - Date.now())) }, { signal: input.signal });
|
|
382
|
+
if (!result.ok) throw new CoreError(result.error.code);
|
|
383
|
+
},
|
|
384
|
+
stop: async (_input) => {
|
|
385
|
+
closed = true;
|
|
386
|
+
cancelWake();
|
|
387
|
+
for (const controller of controllers) controller.abort("cancelled");
|
|
388
|
+
await updates;
|
|
389
|
+
await background;
|
|
390
|
+
}
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
function failure(code) {
|
|
394
|
+
return { ok: false, error: { code, message: "Monitor \u64CD\u4F5C\u672A\u5B8C\u6210\u3002", retryable: !["monitor.context_invalid", "monitor.protocol_rejected", "request.cancelled", "monitor.payload_too_large"].includes(code) } };
|
|
395
|
+
}
|
|
396
|
+
function clone(value) {
|
|
397
|
+
return JSON.parse(JSON.stringify(value));
|
|
398
|
+
}
|
|
399
|
+
function deepFreeze(value) {
|
|
400
|
+
if (value && typeof value === "object") {
|
|
401
|
+
Object.values(value).forEach(deepFreeze);
|
|
402
|
+
Object.freeze(value);
|
|
403
|
+
}
|
|
404
|
+
return value;
|
|
405
|
+
}
|
|
406
|
+
function bytes(value) {
|
|
407
|
+
return monitorUtf8ByteLength(JSON.stringify(value));
|
|
408
|
+
}
|
|
409
|
+
function memberId(item) {
|
|
410
|
+
return item.kind === "error" ? item.eventId : item.traceId;
|
|
411
|
+
}
|
|
412
|
+
function occurrenceExpired(item) {
|
|
413
|
+
const times = item.kind === "error" ? [Date.parse(item.occurredAt)] : item.spans.map((span) => Date.parse(span.startedAt));
|
|
414
|
+
return times.some((time) => !Number.isSafeInteger(time) || Date.now() >= time + MONITOR_DELIVERY_RETRY_WINDOW_MS);
|
|
415
|
+
}
|
|
416
|
+
function deliveryItems(delivery) {
|
|
417
|
+
return delivery.channel === "errors" ? delivery.events : delivery.traces;
|
|
418
|
+
}
|
|
419
|
+
function count(state) {
|
|
420
|
+
return state.groups.reduce((sum, g) => sum + g.items.length, 0);
|
|
421
|
+
}
|
|
422
|
+
function sameAuthority(a, b) {
|
|
423
|
+
return a.authorityScopeKey === b.authorityScopeKey;
|
|
424
|
+
}
|
|
425
|
+
function sameGroup(a, b) {
|
|
426
|
+
return a.channel === b.channel && sameAuthority(a, b);
|
|
427
|
+
}
|
|
428
|
+
function freezeBatch(items, channel) {
|
|
429
|
+
const selected = [];
|
|
430
|
+
let delivery;
|
|
431
|
+
for (const item of items.slice(0, channel === "errors" ? 100 : 20)) {
|
|
432
|
+
try {
|
|
433
|
+
const candidate = [...selected, item];
|
|
434
|
+
delivery = channel === "errors" ? createMonitorErrorDelivery(candidate) : createMonitorTraceDelivery(candidate);
|
|
435
|
+
selected.push(item);
|
|
436
|
+
} catch {
|
|
437
|
+
if (!delivery) throw new CoreError("monitor.payload_too_large");
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
if (!delivery) throw new CoreError("monitor.protocol_rejected");
|
|
442
|
+
return delivery;
|
|
443
|
+
}
|
|
444
|
+
function sample(rate) {
|
|
445
|
+
return rate === 1 || rate > 0 && crypto.getRandomValues(new Uint32Array(1))[0] / 4294967296 < rate;
|
|
446
|
+
}
|
|
447
|
+
function hex(length) {
|
|
448
|
+
const result = [...crypto.getRandomValues(new Uint8Array(length))].map((x) => x.toString(16).padStart(2, "0")).join("");
|
|
449
|
+
return /^0+$/u.test(result) ? `${result.slice(0, -1)}1` : result;
|
|
450
|
+
}
|
|
451
|
+
function read(value, key) {
|
|
452
|
+
try {
|
|
453
|
+
return value && typeof value === "object" ? Reflect.get(value, key) : void 0;
|
|
454
|
+
} catch {
|
|
455
|
+
return void 0;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
function normalizeError(value) {
|
|
459
|
+
const name = read(value, "name"), message = read(value, "message"), stack = read(value, "stack");
|
|
460
|
+
return {
|
|
461
|
+
name: typeof name === "string" && /^[a-zA-Z][a-zA-Z0-9_.]{0,95}$/u.test(name) ? name : "Error",
|
|
462
|
+
message: sanitizeMonitorText(typeof message === "string" ? message : typeof value === "string" ? value : "Non-Error exception", 2048),
|
|
463
|
+
stack: typeof stack === "string" ? sanitizeMonitorText(stack, 16384) : null
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
function snapshotContext(value) {
|
|
467
|
+
const result = {};
|
|
468
|
+
if (!value || typeof value !== "object" || Object.keys(value).some((k) => !["code", "groupingKey", "tags"].includes(k))) throw new Error("invalid");
|
|
469
|
+
for (const key of ["code", "groupingKey"]) {
|
|
470
|
+
const item = value[key];
|
|
471
|
+
if (item !== void 0) {
|
|
472
|
+
if (typeof item !== "string" || !STABLE.test(item)) throw new Error("invalid");
|
|
473
|
+
result[key] = item;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
if (value.tags !== void 0) {
|
|
477
|
+
if (!value.tags || typeof value.tags !== "object" || Array.isArray(value.tags) || Object.keys(value.tags).length > 16) throw new Error("invalid");
|
|
478
|
+
result.tags = {};
|
|
479
|
+
for (const [key, item] of Object.entries(value.tags)) {
|
|
480
|
+
if (!KEY.test(key) || FORBIDDEN.test(key) || typeof item !== "string" || item.length > 128) throw new Error("invalid");
|
|
481
|
+
result.tags[key] = sanitizeMonitorText(item, 128);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
return result;
|
|
485
|
+
}
|
|
486
|
+
function snapshotAttributes(options) {
|
|
487
|
+
const values = {};
|
|
488
|
+
let dropped = 0;
|
|
489
|
+
try {
|
|
490
|
+
for (const [key, item] of Object.entries(options?.attributes ?? {})) {
|
|
491
|
+
if (!KEY.test(key) || FORBIDDEN.test(key) || Object.keys(values).length >= 16 || !["string", "number", "boolean"].includes(typeof item) || typeof item === "number" && !Number.isFinite(item)) {
|
|
492
|
+
dropped++;
|
|
493
|
+
continue;
|
|
494
|
+
}
|
|
495
|
+
values[key] = typeof item === "string" ? sanitizeMonitorText(item, 128) : item;
|
|
496
|
+
}
|
|
497
|
+
} catch {
|
|
498
|
+
dropped++;
|
|
499
|
+
}
|
|
500
|
+
return { values, dropped };
|
|
501
|
+
}
|
|
502
|
+
function validateOccurrence(value) {
|
|
503
|
+
const snapshot = clone(value), source = snapshot.source;
|
|
504
|
+
const sourceFields = ["projectId", "projectEnvKey", "productId", "productRelease", "runtime", "requestId", "routeTemplate", "pagePattern", "userId", "did", "sessionId"];
|
|
505
|
+
if (!source || typeof snapshot.authorityScopeKey !== "string" || !snapshot.authorityScopeKey || snapshot.authorityScopeKey.length > 2048 || !Number.isFinite(snapshot.traceSampleRate) || snapshot.traceSampleRate < 0 || snapshot.traceSampleRate > 1 || typeof source.projectId !== "string" || !/^[1-9]\d{0,15}$/u.test(source.projectId) || typeof source.projectEnvKey !== "string" || !/^[a-z0-9][a-z0-9_-]{0,62}$/u.test(source.projectEnvKey) || typeof source.productId !== "string" || !/^[a-z][a-z0-9-]{0,63}$/u.test(source.productId) || typeof source.productRelease !== "string" || !source.productRelease || source.productRelease.length > 128 || source.userId === void 0 || source.requestId === void 0 || source.routeTemplate === void 0 || source.requestId !== null && (typeof source.requestId !== "string" || !source.requestId || source.requestId.length > 128) || Object.keys(source).some((key) => !sourceFields.includes(key)) || !["web", "app", "mini-program", "extension-admin"].includes(source.runtime)) throw new CoreError("monitor.source_unavailable");
|
|
506
|
+
for (const field of [source.routeTemplate, source.pagePattern]) if (field !== null && field !== void 0 && (typeof field !== "string" || field.length > 512 || /[?\u0000-\u001f\u007f]/u.test(field))) throw new CoreError("monitor.source_unavailable");
|
|
507
|
+
for (const field of [source.userId, source.did, source.sessionId]) if (field !== null && field !== void 0 && (typeof field !== "string" || !field || field.length > 512)) throw new CoreError("monitor.source_unavailable");
|
|
508
|
+
return snapshot;
|
|
509
|
+
}
|
|
510
|
+
function restore(value) {
|
|
511
|
+
if (value === null) return { schemaVersion: 1, groups: [] };
|
|
512
|
+
try {
|
|
513
|
+
if (bytes(value) > MAX_STATE_BYTES) throw new Error("size");
|
|
514
|
+
const state = clone(value);
|
|
515
|
+
if (state.schemaVersion !== 1 || !Array.isArray(state.groups) || state.groups.length > MAX_GROUPS || count(state) > MAX_ITEMS) throw new Error("shape");
|
|
516
|
+
const seen = /* @__PURE__ */ new Set(), groups = /* @__PURE__ */ new Set();
|
|
517
|
+
for (const group of state.groups) {
|
|
518
|
+
if (!group || Object.keys(group).some((key2) => !["authorityScopeKey", "channel", "items", "delivery"].includes(key2)) || !["errors", "traces"].includes(group.channel) || !Array.isArray(group.items) || !group.items.length) throw new Error("group");
|
|
519
|
+
const key = JSON.stringify([group.authorityScopeKey, group.channel]);
|
|
520
|
+
if (groups.has(key)) throw new Error("duplicate group");
|
|
521
|
+
groups.add(key);
|
|
522
|
+
for (const item of group.items) {
|
|
523
|
+
validateOccurrence({ ...group, source: item.source, traceSampleRate: 0 });
|
|
524
|
+
const id = memberId(item);
|
|
525
|
+
if (item.schemaVersion !== 1 || typeof id !== "string" || !id || seen.has(id) || bytes(item) > 64 * 1024) throw new Error("item");
|
|
526
|
+
seen.add(id);
|
|
527
|
+
if (group.channel === "errors" ? item.kind !== "error" || !item.error || !Number.isFinite(Date.parse(item.occurredAt)) : item.kind !== "trace" || !Array.isArray(item.spans) || item.spans.length < 1 || item.spans.length > 100) throw new Error("channel");
|
|
528
|
+
}
|
|
529
|
+
if (group.delivery) {
|
|
530
|
+
const delivery = group.delivery;
|
|
531
|
+
monitorDeliveryCreatedAt(delivery.deliveryId);
|
|
532
|
+
if (delivery.schemaVersion !== 1 || delivery.channel !== group.channel || bytes(delivery) > 256 * 1024) throw new Error("delivery");
|
|
533
|
+
const members = deliveryItems(delivery), ids = new Set(members.map(memberId));
|
|
534
|
+
if (!members.length || members.length > (group.channel === "errors" ? 100 : 20) || ids.size !== members.length || members.some((item) => !group.items.some((stored) => memberId(stored) === memberId(item) && JSON.stringify(stored) === JSON.stringify(item)))) throw new Error("membership");
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
return state;
|
|
538
|
+
} catch {
|
|
539
|
+
throw new CoreError("internal.failed");
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
function checkAbort(signal) {
|
|
543
|
+
if (signal.aborted) throw new CoreError("request.cancelled");
|
|
544
|
+
}
|
|
545
|
+
async function abortable(promise, signal) {
|
|
546
|
+
return new Promise((resolve, reject) => {
|
|
547
|
+
const abort = () => reject(new CoreError("request.cancelled"));
|
|
548
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
549
|
+
void promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
550
|
+
if (signal.aborted) abort();
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
// ../core/monitor-mini-program-service.ts
|
|
555
|
+
var REGISTRY = Symbol.for("kuafu.runtime.monitor.wechat-observer.v1");
|
|
556
|
+
function createMiniProgramMonitorService(context) {
|
|
557
|
+
const core = createMonitorService(context);
|
|
558
|
+
let detach, stopped = false;
|
|
559
|
+
const diagnostic = (code) => {
|
|
560
|
+
try {
|
|
561
|
+
context.diagnostics.write({ code });
|
|
562
|
+
} catch {
|
|
563
|
+
}
|
|
564
|
+
};
|
|
565
|
+
const observer = {
|
|
566
|
+
capture(error, correlation) {
|
|
567
|
+
void core.captureAutomatic(error, "unhandled", correlation).then((result) => {
|
|
568
|
+
if (!result.ok) diagnostic("monitor.automatic_capture_failed");
|
|
569
|
+
}).catch(() => diagnostic("monitor.automatic_capture_failed"));
|
|
570
|
+
},
|
|
571
|
+
ambiguous: () => diagnostic("monitor.automatic_owner_ambiguous")
|
|
572
|
+
};
|
|
573
|
+
return {
|
|
574
|
+
...core,
|
|
575
|
+
async start(input) {
|
|
576
|
+
const wx = globalThis.wx;
|
|
577
|
+
if (!wx || [wx.onError, wx.offError, wx.onUnhandledRejection, wx.offUnhandledRejection].some((fn) => typeof fn !== "function")) {
|
|
578
|
+
throw new Error("monitor.wechat_observer_unavailable");
|
|
579
|
+
}
|
|
580
|
+
await core.start(input);
|
|
581
|
+
if (stopped || input.signal.aborted) {
|
|
582
|
+
await core.stop();
|
|
583
|
+
throw new Error("monitor.unavailable");
|
|
584
|
+
}
|
|
585
|
+
try {
|
|
586
|
+
detach ??= attach(wx, observer);
|
|
587
|
+
} catch (error) {
|
|
588
|
+
await core.stop();
|
|
589
|
+
throw error;
|
|
590
|
+
}
|
|
591
|
+
},
|
|
592
|
+
async stop(input) {
|
|
593
|
+
stopped = true;
|
|
594
|
+
try {
|
|
595
|
+
detach?.();
|
|
596
|
+
} finally {
|
|
597
|
+
detach = void 0;
|
|
598
|
+
await core.stop(input);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
function attach(target, observer) {
|
|
604
|
+
const owner = globalThis;
|
|
605
|
+
let registry = owner[REGISTRY];
|
|
606
|
+
if (registry && (registry.target !== target || !(registry.observers instanceof Set))) throw new Error("monitor.wechat_observer_conflict");
|
|
607
|
+
if (!registry) {
|
|
608
|
+
const observers = /* @__PURE__ */ new Set();
|
|
609
|
+
const capture = (error, correlation) => {
|
|
610
|
+
if (observers.size !== 1) {
|
|
611
|
+
observers.forEach((item) => item.ambiguous());
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
614
|
+
observers.values().next().value?.capture(error, correlation);
|
|
615
|
+
};
|
|
616
|
+
const onError = (error) => capture({ name: "Error", message: error, stack: null });
|
|
617
|
+
const onRejection = (event) => capture(event.reason, event.promise);
|
|
618
|
+
target.onError(onError);
|
|
619
|
+
try {
|
|
620
|
+
target.onUnhandledRejection(onRejection);
|
|
621
|
+
} catch (error) {
|
|
622
|
+
target.offError(onError);
|
|
623
|
+
throw error;
|
|
624
|
+
}
|
|
625
|
+
registry = { target, observers, dispose() {
|
|
626
|
+
try {
|
|
627
|
+
target.offError(onError);
|
|
628
|
+
} finally {
|
|
629
|
+
target.offUnhandledRejection(onRejection);
|
|
630
|
+
}
|
|
631
|
+
} };
|
|
632
|
+
owner[REGISTRY] = registry;
|
|
633
|
+
}
|
|
634
|
+
const current = registry;
|
|
635
|
+
current.observers.add(observer);
|
|
636
|
+
return () => {
|
|
637
|
+
current.observers.delete(observer);
|
|
638
|
+
if (current.observers.size === 0) {
|
|
639
|
+
try {
|
|
640
|
+
current.dispose();
|
|
641
|
+
} finally {
|
|
642
|
+
if (owner[REGISTRY] === current) delete owner[REGISTRY];
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
// index.ts
|
|
649
|
+
import { defineMonitorBackendV1, defineServiceModule } from "@kuafucloud/mini-program-runtime/module-author";
|
|
650
|
+
var index_default = defineServiceModule({ service: Monitor, backend: defineMonitorBackendV1(), create: createMiniProgramMonitorService });
|
|
651
|
+
export {
|
|
652
|
+
index_default as default
|
|
653
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schemaVersion": 1,
|
|
3
|
+
"serviceId": "monitor",
|
|
4
|
+
"runtimeApi": 1,
|
|
5
|
+
"moduleApi": 2,
|
|
6
|
+
"runtimeId": "mini-program",
|
|
7
|
+
"buildVariant": "wechat",
|
|
8
|
+
"entry": "./entry.mjs",
|
|
9
|
+
"capabilities": [],
|
|
10
|
+
"sourceEntry": "./index.js",
|
|
11
|
+
"clientExportPath": "./monitor"
|
|
12
|
+
}
|