@ai-matrx/kit 0.12.1 → 0.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1323 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/content-transfer.ts
31
+ var content_transfer_exports = {};
32
+ __export(content_transfer_exports, {
33
+ ContentTransferError: () => ContentTransferError,
34
+ applySectionSelection: () => applySectionSelection,
35
+ applyTransferLimits: () => applyTransferLimits,
36
+ buildAgentPayload: () => buildAgentPayload,
37
+ capture: () => capture,
38
+ collectAllMatching: () => collectAllMatching,
39
+ createBrowserTransport: () => createBrowserTransport,
40
+ createDraft: () => createDraft,
41
+ createSurfaceTransferHandle: () => createSurfaceTransferHandle,
42
+ directSource: () => directSource,
43
+ editDraft: () => editDraft,
44
+ fenceJsonBlock: () => fenceJsonBlock,
45
+ normalizeTransferJson: () => normalizeTransferJson,
46
+ projectSnapshot: () => projectSnapshot,
47
+ readTransferCell: () => readTransferCell,
48
+ reduceJson: () => reduceJson,
49
+ refreshDraft: () => refreshDraft,
50
+ renderMarkdownHtml: () => renderMarkdownHtml,
51
+ resetDraft: () => resetDraft,
52
+ resolveTransferPreferences: () => resolveTransferPreferences,
53
+ resolveTransferRegistry: () => resolveTransferRegistry,
54
+ sealTransferArtifact: () => sealTransferArtifact,
55
+ serialize: () => serialize,
56
+ serializeMarkdownRich: () => serializeMarkdownRich,
57
+ sourceChanged: () => sourceChanged,
58
+ transformRows: () => transformRows,
59
+ undoDraft: () => undoDraft
60
+ });
61
+ module.exports = __toCommonJS(content_transfer_exports);
62
+
63
+ // src/json-format/json-value.ts
64
+ function isJsonObject(value) {
65
+ return typeof value === "object" && value !== null && !Array.isArray(value);
66
+ }
67
+ function isJsonArray(value) {
68
+ return Array.isArray(value);
69
+ }
70
+
71
+ // src/json-format/format.ts
72
+ var DEFAULT_JSON_INDENT = 2;
73
+ var DEFAULT_JSON_WIDTH = 100;
74
+ function orderedKeys(obj, sortKeys) {
75
+ const keys = Object.keys(obj).filter((k) => obj[k] !== void 0);
76
+ return sortKeys ? [...keys].sort((a, b) => a.localeCompare(b)) : keys;
77
+ }
78
+ function writeScalar(value) {
79
+ return JSON.stringify(value) ?? "null";
80
+ }
81
+ function flatten(value, cfg) {
82
+ if (isJsonArray(value)) {
83
+ if (value.length === 0) return "[]";
84
+ const parts = value.map((v) => flatten(v ?? null, cfg));
85
+ return cfg.spaced ? `[${parts.join(", ")}]` : `[${parts.join(",")}]`;
86
+ }
87
+ if (isJsonObject(value)) {
88
+ const keys = orderedKeys(value, cfg.sortKeys);
89
+ if (keys.length === 0) return "{}";
90
+ const colon = cfg.spaced ? ": " : ":";
91
+ const parts = keys.map(
92
+ (k) => `${JSON.stringify(k)}${colon}${flatten(value[k] ?? null, cfg)}`
93
+ );
94
+ return cfg.spaced ? `{ ${parts.join(", ")} }` : `{${parts.join(",")}}`;
95
+ }
96
+ return writeScalar(value);
97
+ }
98
+ function layoutEntries(entries, pad, cfg) {
99
+ if (!cfg.pack) return entries.map((e) => pad + e);
100
+ const lines = [];
101
+ let current = "";
102
+ for (let i = 0; i < entries.length; i++) {
103
+ const entry = entries[i] ?? "";
104
+ const isLast = i === entries.length - 1;
105
+ const piece = isLast ? entry : `${entry},`;
106
+ if (entry.includes("\n")) {
107
+ if (current !== "") {
108
+ lines.push(pad + current);
109
+ current = "";
110
+ }
111
+ lines.push(pad + piece);
112
+ continue;
113
+ }
114
+ if (current === "") {
115
+ current = piece;
116
+ continue;
117
+ }
118
+ const merged = `${current} ${piece}`;
119
+ if (pad.length + merged.length <= cfg.width) {
120
+ current = merged;
121
+ } else {
122
+ lines.push(pad + current);
123
+ current = piece;
124
+ }
125
+ }
126
+ if (current !== "") lines.push(pad + current);
127
+ return lines;
128
+ }
129
+ function renderNode(value, level, used, cfg) {
130
+ const isContainer = isJsonArray(value) || isJsonObject(value);
131
+ if (!isContainer) return writeScalar(value);
132
+ const flat = flatten(value, cfg);
133
+ if (flat === "[]" || flat === "{}") return flat;
134
+ if (cfg.width >= 0 && used + flat.length <= cfg.width) return flat;
135
+ const pad = " ".repeat((level + 1) * cfg.indent);
136
+ const closePad = " ".repeat(level * cfg.indent);
137
+ if (isJsonArray(value)) {
138
+ const entries2 = value.map(
139
+ (v) => renderNode(v ?? null, level + 1, pad.length, cfg)
140
+ );
141
+ const body2 = layoutEntries(entries2, pad, cfg);
142
+ const joined2 = cfg.pack ? body2.join("\n") : body2.join(",\n");
143
+ return `[
144
+ ${joined2}
145
+ ${closePad}]`;
146
+ }
147
+ const keys = orderedKeys(value, cfg.sortKeys);
148
+ const entries = keys.map((k) => {
149
+ const prefix = `${JSON.stringify(k)}: `;
150
+ const rendered = renderNode(
151
+ value[k] ?? null,
152
+ level + 1,
153
+ pad.length + prefix.length,
154
+ cfg
155
+ );
156
+ return prefix + rendered;
157
+ });
158
+ const body = layoutEntries(entries, pad, cfg);
159
+ const joined = cfg.pack ? body.join("\n") : body.join(",\n");
160
+ return `{
161
+ ${joined}
162
+ ${closePad}}`;
163
+ }
164
+ function stringifyJson(value, options) {
165
+ const indent = options.indent ?? DEFAULT_JSON_INDENT;
166
+ const sortKeys = options.sortKeys ?? false;
167
+ if (options.style === "minify") {
168
+ return flatten(value, { indent, width: -1, pack: false, spaced: false, sortKeys });
169
+ }
170
+ const cfg = {
171
+ indent,
172
+ width: options.style === "pretty" ? -1 : options.width ?? DEFAULT_JSON_WIDTH,
173
+ pack: options.style === "compact",
174
+ spaced: true,
175
+ sortKeys
176
+ };
177
+ return renderNode(value, 0, 0, cfg);
178
+ }
179
+
180
+ // src/html-escape.ts
181
+ var HTML_ESCAPES = {
182
+ "&": "&amp;",
183
+ "<": "&lt;",
184
+ ">": "&gt;",
185
+ '"': "&quot;",
186
+ "'": "&#39;"
187
+ };
188
+ var HTML_ESCAPE_RE = /[&<>"']/g;
189
+ function escapeHtml(value) {
190
+ if (typeof value !== "string") return "";
191
+ return value.replace(HTML_ESCAPE_RE, (char) => HTML_ESCAPES[char] ?? char);
192
+ }
193
+
194
+ // src/content-transfer/agent-payload.ts
195
+ var escapeXml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
196
+ var xmlName = (name) => {
197
+ if (!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(name)) throw new Error(`Invalid AI envelope name: ${name}`);
198
+ return name;
199
+ };
200
+ var presentEntries = (values) => Object.entries(values ?? {}).filter(([, value]) => value !== null && value !== void 0 && value !== "");
201
+ function fenceJsonBlock(json) {
202
+ const runs = json.match(/`+/g) ?? [];
203
+ const fence = "`".repeat(Math.max(3, ...runs.map((run) => run.length + 1)));
204
+ return `${fence}json
205
+ ${json.trimEnd()}
206
+ ${fence}`;
207
+ }
208
+ function buildAgentPayload(input, environment = {}) {
209
+ const kind = xmlName(input.kind);
210
+ const url = environment.url ?? (typeof window === "undefined" ? "" : window.location.href);
211
+ const route = environment.route ?? (typeof window === "undefined" ? "" : window.location.pathname);
212
+ const attrs = presentEntries(input.attributes).map(([key, value]) => ` ${xmlName(key)}="${escapeXml(String(value))}"`).join("");
213
+ const entries = [
214
+ ["location", input.location],
215
+ ...url ? [["url", url]] : [],
216
+ ...route ? [["route", route]] : [],
217
+ ["copied", input.description],
218
+ ["copied-at", environment.capturedAt ?? (/* @__PURE__ */ new Date()).toISOString()],
219
+ ...presentEntries(input.context).map(([key, value]) => [xmlName(key), String(value)])
220
+ ];
221
+ const json = JSON.stringify(input.data, null, 2);
222
+ if (json === void 0) throw new Error("AI envelope data must be JSON serializable.");
223
+ const safeJson = json.replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026");
224
+ const context = entries.map(([key, value]) => `<${key}>${escapeXml(value)}</${key}>`).join("\n");
225
+ const summary = input.summary ? `<summary>
226
+ ${escapeXml(input.summary)}
227
+ </summary>
228
+ ` : "";
229
+ return `<${kind}${attrs}>
230
+ <context>
231
+ ${context}
232
+ </context>
233
+ ${summary}<data format="json">
234
+ ${fenceJsonBlock(safeJson)}
235
+ </data>
236
+ </${kind}>`;
237
+ }
238
+
239
+ // src/content-transfer.ts
240
+ var ContentTransferError = class extends Error {
241
+ code;
242
+ path;
243
+ constructor(code, message, path) {
244
+ super(message);
245
+ this.code = code;
246
+ this.path = path;
247
+ }
248
+ };
249
+ var bound = /* @__PURE__ */ Symbol("bound-all-matching");
250
+ var stop = (s) => {
251
+ if (s.aborted) throw new DOMException("Cancelled", "AbortError");
252
+ };
253
+ var enc = (x) => x.replace(/~/g, "~0").replace(/\//g, "~1");
254
+ var dec = (x) => x.replace(/~1/g, "/").replace(/~0/g, "~");
255
+ function clone(v, path = "", seen = /* @__PURE__ */ new WeakSet()) {
256
+ if (v === null || typeof v === "string" || typeof v === "boolean") return v;
257
+ if (typeof v === "number") {
258
+ if (!Number.isFinite(v))
259
+ throw new ContentTransferError(
260
+ "unsupported-value",
261
+ "Only finite numbers are transferable",
262
+ path
263
+ );
264
+ return v;
265
+ }
266
+ if (typeof v !== "object")
267
+ throw new ContentTransferError(
268
+ "unsupported-value",
269
+ "Unsupported value",
270
+ path
271
+ );
272
+ if (seen.has(v))
273
+ throw new ContentTransferError(
274
+ "circular-value",
275
+ "Circular values cannot be transferred",
276
+ path
277
+ );
278
+ if (!Array.isArray(v) && Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null)
279
+ throw new ContentTransferError(
280
+ "unsupported-value",
281
+ "Only plain JSON objects are transferable",
282
+ path
283
+ );
284
+ seen.add(v);
285
+ if (Array.isArray(v)) {
286
+ for (let index = 0; index < v.length; index += 1)
287
+ if (!Object.hasOwn(v, index))
288
+ throw new ContentTransferError(
289
+ "unsupported-value",
290
+ "Sparse arrays cannot be transferred",
291
+ `${path}/${index}`
292
+ );
293
+ }
294
+ const out = Array.isArray(v) ? v.map((x, i) => clone(x, `${path}/${i}`, seen)) : Object.fromEntries(
295
+ Object.entries(v).map(([k, x]) => [
296
+ k,
297
+ clone(x, `${path}/${enc(k)}`, seen)
298
+ ])
299
+ );
300
+ seen.delete(v);
301
+ return out;
302
+ }
303
+ function normalizeTransferJson(value) {
304
+ return clone(value);
305
+ }
306
+ function deepFreeze(v) {
307
+ if (ArrayBuffer.isView(v)) return v;
308
+ if (v && typeof v === "object" && !Object.isFrozen(v)) {
309
+ Object.freeze(v);
310
+ for (const x of Object.values(v)) deepFreeze(x);
311
+ }
312
+ return v;
313
+ }
314
+ function at(v, path) {
315
+ validatePointer(path);
316
+ if (path === "") return v;
317
+ if (!path.startsWith("/"))
318
+ throw new ContentTransferError(
319
+ "invalid-path",
320
+ "Expected RFC 6901 pointer",
321
+ path
322
+ );
323
+ let cur = v;
324
+ for (const part of path.slice(1).split("/").map(dec)) {
325
+ if (Array.isArray(cur)) cur = cur[Number(part)];
326
+ else if (cur && typeof cur === "object")
327
+ cur = Object.hasOwn(cur, part) ? cur[part] : void 0;
328
+ else return void 0;
329
+ }
330
+ return cur;
331
+ }
332
+ function validatePointer(path) {
333
+ if (path !== "" && !path.startsWith("/") || /~(?![01])/u.test(path))
334
+ throw new ContentTransferError(
335
+ "invalid-path",
336
+ "Expected an RFC 6901 JSON pointer",
337
+ path
338
+ );
339
+ }
340
+ function readTransferCell(row, column) {
341
+ return at(row, column.path);
342
+ }
343
+ function without(v, paths, omit, path = "") {
344
+ if (paths.includes(path)) {
345
+ omit.push({ path, reason: "excluded" });
346
+ return void 0;
347
+ }
348
+ if (Array.isArray(v))
349
+ return v.map((x, i) => without(x, paths, omit, `${path}/${i}`)).filter((x) => x !== void 0);
350
+ if (v && typeof v === "object") {
351
+ const out = /* @__PURE__ */ Object.create(null);
352
+ for (const [k, x] of Object.entries(v)) {
353
+ const y = without(x, paths, omit, `${path}/${enc(k)}`);
354
+ if (y !== void 0) out[k] = y;
355
+ }
356
+ return out;
357
+ }
358
+ return v;
359
+ }
360
+ function projectValue(v, rules, target, omit) {
361
+ rules.forEach((rule) => validatePointer(rule.path));
362
+ return without(
363
+ clone(v),
364
+ rules.filter(
365
+ (r) => r.target === target && (!r.exportable || r.classification !== "ordinary")
366
+ ).map((r) => r.path),
367
+ omit
368
+ ) ?? null;
369
+ }
370
+ function normalize(p, projection, omit) {
371
+ if (p.kind === "text" || p.kind === "markdown") {
372
+ if (typeof p.text !== "string")
373
+ throw new ContentTransferError(
374
+ "unsupported-value",
375
+ "Text payload must contain a string",
376
+ "/text"
377
+ );
378
+ const value = projectValue(p.text, projection.rules, "payload", omit);
379
+ return { kind: p.kind, text: typeof value === "string" ? value : "" };
380
+ }
381
+ if (p.kind === "json")
382
+ return {
383
+ kind: "json",
384
+ value: projectValue(p.value, projection.rules, "payload", omit)
385
+ };
386
+ if (p.kind === "registered")
387
+ return {
388
+ kind: "registered",
389
+ format: p.format,
390
+ value: projectValue(p.value, projection.rules, "payload", omit)
391
+ };
392
+ const rowsPayload = p;
393
+ if (p.kind !== "rows")
394
+ throw new ContentTransferError(
395
+ "invalid-payload",
396
+ "Unsupported payload kind"
397
+ );
398
+ const columns = rowsPayload.columns.map((c) => ({ ...c }));
399
+ resolveTransferRegistry(columns);
400
+ columns.forEach((column) => validatePointer(column.path));
401
+ const rules = [
402
+ ...projection.rules,
403
+ ...columns.filter(
404
+ (c) => c.exportable === false || c.classification === "secret" || c.classification === "credential"
405
+ ).map((c) => ({
406
+ target: "row",
407
+ path: c.path,
408
+ exportable: c.exportable ?? true,
409
+ classification: c.classification ?? "ordinary"
410
+ }))
411
+ ];
412
+ return {
413
+ kind: "rows",
414
+ columns,
415
+ rows: rowsPayload.rows.map((row, index) => {
416
+ if (!row || typeof row !== "object" || Array.isArray(row))
417
+ throw new ContentTransferError(
418
+ "invalid-row",
419
+ "A table row must be a JSON object",
420
+ `/rows/${index}`
421
+ );
422
+ const projected = projectValue(row, rules, "row", omit);
423
+ return projected === null ? {} : projected;
424
+ })
425
+ };
426
+ }
427
+ function projectSnapshot(raw, projection) {
428
+ const omissions = raw.omissions.map((o) => ({ ...o }));
429
+ const normalized = normalize(raw.payload, projection, omissions);
430
+ const payload = raw.limits ? limitPayload(normalized, raw.limits, omissions) : normalized;
431
+ const included = payload.kind === "rows" ? payload.rows.length : raw.coverage.included;
432
+ return deepFreeze({
433
+ ...raw,
434
+ payload,
435
+ coverage: {
436
+ ...raw.coverage,
437
+ included,
438
+ ...included < raw.coverage.included ? { status: "partial", reason: "Source export limit applied" } : {}
439
+ },
440
+ omissions,
441
+ sections: raw.sections.filter(
442
+ (section) => !projection.rules.some(
443
+ (rule) => rule.target === "payload" && (!rule.exportable || rule.classification !== "ordinary") && (section.path === rule.path || section.path.startsWith(`${rule.path}/`))
444
+ )
445
+ ).map((x) => ({ ...x })),
446
+ ...raw.limits ? { limits: { ...raw.limits } } : {}
447
+ });
448
+ }
449
+ var uid = () => globalThis.crypto?.randomUUID?.() ?? `capture-${Date.now()}-${Math.random()}`;
450
+ function directSource(payload, options = {}) {
451
+ const id = options.id ?? uid();
452
+ return {
453
+ projection: options.projection ?? { rules: [] },
454
+ snapshot: {
455
+ id,
456
+ sourceId: options.sourceId ?? id,
457
+ revision: options.revision ?? uid(),
458
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
459
+ label: options.label ?? "Content",
460
+ payload,
461
+ coverage: options.coverage ?? {
462
+ status: "complete",
463
+ included: payload.kind === "rows" ? payload.rows.length : 1,
464
+ total: payload.kind === "rows" ? payload.rows.length : 1
465
+ },
466
+ unsavedChanges: options.unsavedChanges ?? false,
467
+ omissions: [],
468
+ sections: options.sections ?? [],
469
+ ...options.limits ? { limits: { ...options.limits } } : {}
470
+ }
471
+ };
472
+ }
473
+ async function capture(source, signal, scope = "target") {
474
+ stop(signal);
475
+ const captured = "kind" in source ? directSource(source) : await source.capture({ scope, signal });
476
+ stop(signal);
477
+ const all = captured.allMatching;
478
+ if (all && (all.query.sourceId !== captured.snapshot.sourceId || all.query.revision !== captured.snapshot.revision || all.query.order.length === 0))
479
+ throw new ContentTransferError(
480
+ "query-mismatch",
481
+ "All-matching query must be captured with stable ordering"
482
+ );
483
+ const snapshot = projectSnapshot(captured.snapshot, captured.projection);
484
+ if (!all) return { snapshot };
485
+ return {
486
+ snapshot,
487
+ allMatching: deepFreeze({
488
+ [bound]: true,
489
+ source: {
490
+ ...all,
491
+ query: {
492
+ ...all.query,
493
+ query: clone(all.query.query),
494
+ order: all.query.order.map((x) => ({ ...x }))
495
+ }
496
+ },
497
+ projection: { rules: captured.projection.rules.map((x) => ({ ...x })) },
498
+ columns: snapshot.payload.kind === "rows" ? snapshot.payload.columns : [],
499
+ ...snapshot.limits ? { limits: { ...snapshot.limits } } : {}
500
+ })
501
+ };
502
+ }
503
+ function createDraft(s) {
504
+ return deepFreeze({
505
+ snapshotId: s.id,
506
+ sourceId: s.sourceId,
507
+ sourceRevision: s.revision,
508
+ revision: 0,
509
+ payload: normalize(s.payload, { rules: [] }, []),
510
+ omissions: [...s.omissions],
511
+ manuallyEdited: false,
512
+ provenance: [{ kind: "original", description: "Captured source snapshot" }]
513
+ });
514
+ }
515
+ function revise(d, p, o, description, manual = d.manuallyEdited, kind = "deterministic", baseOmissions = d.omissions) {
516
+ const { history: _history, ...previous } = d;
517
+ return deepFreeze({
518
+ ...d,
519
+ revision: d.revision + 1,
520
+ payload: normalize(p, { rules: [] }, []),
521
+ omissions: [...baseOmissions, ...o],
522
+ manuallyEdited: manual,
523
+ provenance: [...d.provenance, { kind, description }],
524
+ history: [...d.history ?? [], previous]
525
+ });
526
+ }
527
+ var editDraft = (d, p) => revise(d, p, [], "Manual edit", true, "manual");
528
+ var resetDraft = (s) => createDraft(s);
529
+ var sourceChanged = (d, s) => d.sourceId !== s.sourceId || d.sourceRevision !== s.revision;
530
+ function undoDraft(d) {
531
+ const previous = d.history?.at(-1);
532
+ if (!previous) return d;
533
+ return deepFreeze({
534
+ ...previous,
535
+ revision: d.revision + 1,
536
+ history: d.history.slice(0, -1)
537
+ });
538
+ }
539
+ function refreshDraft(draft, snapshot, choice) {
540
+ return choice === "keep" ? draft : createDraft(snapshot);
541
+ }
542
+ function applySectionSelection(d, s, ids) {
543
+ if (d.snapshotId !== s.id || d.sourceId !== s.sourceId || d.sourceRevision !== s.revision)
544
+ throw new ContentTransferError(
545
+ "snapshot-mismatch",
546
+ "Section selection requires the draft's captured source snapshot"
547
+ );
548
+ const selected = new Set(ids), omit = [], paths = s.sections.filter((x) => !selected.has(x.id)).map((x) => {
549
+ omit.push({ path: x.path, reason: "excluded" });
550
+ return x.path;
551
+ }), baseOmissions = s.omissions;
552
+ if (s.payload.kind === "json")
553
+ return revise(
554
+ d,
555
+ { kind: "json", value: without(s.payload.value, paths, []) ?? null },
556
+ omit,
557
+ "Selected sections",
558
+ d.manuallyEdited,
559
+ "deterministic",
560
+ baseOmissions
561
+ );
562
+ if (s.payload.kind === "registered")
563
+ return revise(
564
+ d,
565
+ {
566
+ kind: "registered",
567
+ format: s.payload.format,
568
+ value: without(s.payload.value, paths, []) ?? null
569
+ },
570
+ omit,
571
+ "Selected sections",
572
+ d.manuallyEdited,
573
+ "deterministic",
574
+ baseOmissions
575
+ );
576
+ return revise(
577
+ d,
578
+ s.payload,
579
+ omit,
580
+ "Selected sections",
581
+ d.manuallyEdited,
582
+ "deterministic",
583
+ baseOmissions
584
+ );
585
+ }
586
+ function transformRows(d, o) {
587
+ if (d.payload.kind !== "rows") return d;
588
+ if (o.top != null) assertLimit(o.top, "maxRows");
589
+ const cols = o.visibleColumns ? o.visibleColumns.map(
590
+ (id) => d.payload.kind === "rows" ? d.payload.columns.find((c) => c.id === id) : void 0
591
+ ).filter((c) => Boolean(c)) : d.payload.columns.filter((c) => c.visible);
592
+ const get = readTransferCell;
593
+ let rows = [...d.payload.rows], omit = [];
594
+ const before = rows.length;
595
+ if (o.selectedIndices !== void 0) {
596
+ const selected = /* @__PURE__ */ new Set();
597
+ for (const index of o.selectedIndices) {
598
+ if (!Number.isSafeInteger(index) || index < 0 || index >= d.payload.rows.length)
599
+ throw new ContentTransferError(
600
+ "invalid-selection-index",
601
+ "Selected row indexes must be non-negative positions in the input draft rows"
602
+ );
603
+ selected.add(index);
604
+ }
605
+ rows = d.payload.rows.filter((_, index) => selected.has(index));
606
+ }
607
+ if (o.selectedIds && o.idColumn) {
608
+ const set = new Set(o.selectedIds);
609
+ const idColumn = d.payload.columns.find((c) => c.id === o.idColumn);
610
+ rows = rows.filter(
611
+ (r) => set.has(String(idColumn ? get(r, idColumn) : r[o.idColumn]))
612
+ );
613
+ }
614
+ if (o.search) {
615
+ const q = o.search.toLowerCase();
616
+ rows = rows.filter(
617
+ (r) => cols.some(
618
+ (c) => String(get(r, c) ?? "").toLowerCase().includes(q)
619
+ )
620
+ );
621
+ }
622
+ for (const [id, q] of Object.entries(o.filters ?? {})) {
623
+ const c = cols.find((x) => x.id === id);
624
+ if (c)
625
+ rows = rows.filter(
626
+ (r) => String(get(r, c) ?? "").toLowerCase().includes(q.toLowerCase())
627
+ );
628
+ }
629
+ if (rows.length !== before)
630
+ omit.push({
631
+ path: "/rows",
632
+ reason: "filtered",
633
+ count: before - rows.length
634
+ });
635
+ if (o.sort) {
636
+ const c = cols.find((x) => x.id === o.sort.column);
637
+ if (c)
638
+ rows.sort((a, b) => {
639
+ const left = get(a, c);
640
+ const right = get(b, c);
641
+ const compare = typeof left === "number" && typeof right === "number" ? left - right : String(left ?? "").localeCompare(String(right ?? ""));
642
+ return compare * (o.sort.direction === "asc" ? 1 : -1);
643
+ });
644
+ }
645
+ if (o.top != null && rows.length > o.top) {
646
+ omit.push({
647
+ path: "/rows",
648
+ reason: "truncated",
649
+ count: rows.length - o.top
650
+ });
651
+ rows = rows.slice(0, o.top);
652
+ }
653
+ if (o.structuredProjection === "visible") {
654
+ rows = rows.map(
655
+ (r) => Object.fromEntries(cols.map((c) => [c.id, get(r, c) ?? null]))
656
+ );
657
+ omit.push({
658
+ path: "/columns",
659
+ reason: "excluded",
660
+ count: d.payload.columns.length - cols.length
661
+ });
662
+ }
663
+ return revise(
664
+ d,
665
+ {
666
+ kind: "rows",
667
+ rows,
668
+ columns: cols.map((c) => ({
669
+ ...c,
670
+ visible: true,
671
+ ...o.structuredProjection === "visible" ? { path: `/${enc(c.id)}` } : {}
672
+ }))
673
+ },
674
+ omit,
675
+ "Prepared row subset"
676
+ );
677
+ }
678
+ function reduceJson(draft, options) {
679
+ if (draft.payload.kind !== "json" && draft.payload.kind !== "registered")
680
+ return draft;
681
+ const omissions = [];
682
+ options.exclude?.forEach(validatePointer);
683
+ const filtered = without(clone(draft.payload.value), options.exclude ?? [], omissions) ?? null;
684
+ const payload = limitPayload(
685
+ { ...draft.payload, value: filtered },
686
+ options,
687
+ omissions
688
+ );
689
+ return revise(draft, payload, omissions, "Reduced JSON");
690
+ }
691
+ async function collectAllMatching(c, signal) {
692
+ const rows = [], omissions = [], ids = /* @__PURE__ */ new Set(), cursors = /* @__PURE__ */ new Set();
693
+ let cursor = null, token, last = {
694
+ status: "unknown",
695
+ included: 0,
696
+ total: null
697
+ };
698
+ let certifiedTotal;
699
+ const maxRows = c.limits?.maxRows;
700
+ if (maxRows != null) assertLimit(maxRows, "maxRows");
701
+ const finishAtLimit = (total, knownOmitted) => ({
702
+ rows: deepFreeze(rows),
703
+ omissions: deepFreeze([
704
+ ...omissions,
705
+ {
706
+ path: "/rows",
707
+ reason: "truncated",
708
+ ...knownOmitted === void 0 || knownOmitted <= 0 ? {} : { count: knownOmitted }
709
+ }
710
+ ]),
711
+ coverage: deepFreeze({
712
+ status: "partial",
713
+ included: rows.length,
714
+ total,
715
+ reason: "Source export limit applied"
716
+ })
717
+ });
718
+ try {
719
+ if (maxRows === 0) return finishAtLimit(null);
720
+ do {
721
+ stop(signal);
722
+ const page = await c.source.page({
723
+ query: c.source.query,
724
+ cursor,
725
+ consistencyToken: token ?? null,
726
+ signal
727
+ });
728
+ stop(signal);
729
+ if (token === void 0) token = page.consistencyToken;
730
+ else if (page.consistencyToken !== token)
731
+ throw new ContentTransferError(
732
+ "consistency-token-changed",
733
+ "All-matching export changed during collection"
734
+ );
735
+ if (page.coverage.included !== page.rows.length)
736
+ throw new ContentTransferError(
737
+ "invalid-page-coverage",
738
+ "Page count does not match returned rows"
739
+ );
740
+ if (page.coverage.total !== null && (!Number.isSafeInteger(page.coverage.total) || page.coverage.total < 0))
741
+ throw new ContentTransferError(
742
+ "invalid-page-coverage",
743
+ "Page total must be a non-negative integer or null"
744
+ );
745
+ if (certifiedTotal === void 0) certifiedTotal = page.coverage.total;
746
+ else if (page.coverage.total !== certifiedTotal)
747
+ throw new ContentTransferError(
748
+ "inconsistent-total",
749
+ "All-matching source changed its reported total during collection"
750
+ );
751
+ const projected = normalize(
752
+ { kind: "rows", rows: page.rows, columns: [...c.columns] },
753
+ c.projection,
754
+ omissions
755
+ ).rows;
756
+ let uniqueBeyondLimit = 0;
757
+ for (const row of projected) {
758
+ const id = c.source.getRowId(row);
759
+ if (!id)
760
+ throw new ContentTransferError(
761
+ "invalid-row-id",
762
+ "All-matching source returned empty projected ID"
763
+ );
764
+ if (!ids.has(id)) {
765
+ ids.add(id);
766
+ if (maxRows == null || rows.length < maxRows)
767
+ rows.push(
768
+ limitPayload(
769
+ { kind: "rows", rows: [row], columns: [...c.columns] },
770
+ { ...c.limits, maxRows: null },
771
+ omissions
772
+ ).rows[0]
773
+ );
774
+ else uniqueBeyondLimit += 1;
775
+ } else omissions.push({ path: `/rows/${enc(id)}`, reason: "duplicate" });
776
+ }
777
+ if (page.coverage.total !== null && page.coverage.total < ids.size)
778
+ throw new ContentTransferError(
779
+ "invalid-page-coverage",
780
+ "Page total is smaller than the accumulated unique row count"
781
+ );
782
+ last = page.coverage;
783
+ if (maxRows != null && rows.length >= maxRows && (uniqueBeyondLimit > 0 || page.nextCursor !== null))
784
+ return finishAtLimit(
785
+ page.coverage.total,
786
+ page.nextCursor === null ? uniqueBeyondLimit : page.coverage.total != null && page.coverage.total > rows.length ? page.coverage.total - rows.length : void 0
787
+ );
788
+ cursor = page.nextCursor;
789
+ if (cursor !== null && (!cursor || cursors.has(cursor)))
790
+ throw new ContentTransferError(
791
+ "non-advancing-cursor",
792
+ "All-matching source repeated a cursor"
793
+ );
794
+ if (cursor) cursors.add(cursor);
795
+ } while (cursor !== null);
796
+ const complete = c.source.stableSnapshot === true && last.status === "complete" && last.total === rows.length && token !== void 0;
797
+ return {
798
+ rows: deepFreeze(rows),
799
+ omissions: deepFreeze(omissions),
800
+ coverage: deepFreeze(
801
+ complete ? { ...last, included: rows.length } : {
802
+ ...last,
803
+ status: "partial",
804
+ included: rows.length,
805
+ reason: last.reason ?? "Source did not certify a stable complete snapshot"
806
+ }
807
+ )
808
+ };
809
+ } catch (e) {
810
+ const error = e instanceof ContentTransferError ? e : new ContentTransferError(
811
+ signal.aborted ? "cancelled" : "page-failed",
812
+ e instanceof Error ? e.message : "Page collection failed"
813
+ );
814
+ return {
815
+ rows: deepFreeze(rows),
816
+ omissions: deepFreeze(omissions),
817
+ coverage: deepFreeze({
818
+ status: "partial",
819
+ included: rows.length,
820
+ total: last.total,
821
+ reason: error.message
822
+ }),
823
+ error
824
+ };
825
+ }
826
+ }
827
+ var textValue = (value) => value === void 0 ? "" : typeof value === "string" ? value : stringifyJson(value, { style: "compact" });
828
+ function sealTransferArtifact(artifact) {
829
+ if (!artifact.file)
830
+ return deepFreeze({
831
+ ...artifact,
832
+ omissions: artifact.omissions.map((o) => ({ ...o }))
833
+ });
834
+ const bytes = artifact.file.bytes.slice();
835
+ const file = {
836
+ filename: artifact.file.filename,
837
+ mime: artifact.file.mime,
838
+ get bytes() {
839
+ return bytes.slice();
840
+ }
841
+ };
842
+ return deepFreeze({
843
+ ...artifact,
844
+ file,
845
+ omissions: artifact.omissions.map((o) => ({ ...o }))
846
+ });
847
+ }
848
+ function serialize(draft, format, options = {}) {
849
+ const payload = draft.payload;
850
+ const omissions = draft.omissions.map((o) => ({ ...o }));
851
+ let plainText = "", html;
852
+ let mime = "text/plain;charset=utf-8", extension = "txt";
853
+ const columnCell = (row, column) => textValue(readTransferCell(row, column));
854
+ if ((format === "csv" || format === "tsv") && payload.kind !== "rows") {
855
+ throw new ContentTransferError(
856
+ "unsupported-format",
857
+ `${format.toUpperCase()} requires tabular data`
858
+ );
859
+ }
860
+ if (format === "json" || format === "compact-json") {
861
+ const value = payload.kind === "rows" ? payload.rows : payload.kind === "text" || payload.kind === "markdown" ? payload.text : payload.value;
862
+ plainText = stringifyJson(value, {
863
+ style: format === "json" ? "pretty" : "compact"
864
+ });
865
+ mime = "application/json;charset=utf-8";
866
+ extension = "json";
867
+ } else if (payload.kind === "rows") {
868
+ const columns = payload.columns.filter(
869
+ (c) => c.visible && c.exportable !== false && c.classification !== "secret" && c.classification !== "credential"
870
+ );
871
+ if (format === "markdown") {
872
+ const escapeCell = (value) => escapeHtml(value).replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\r\n|\r|\n/g, "<br>");
873
+ plainText = [
874
+ `| ${columns.map((c) => escapeCell(c.label)).join(" | ")} |`,
875
+ `| ${columns.map(() => "---").join(" | ")} |`,
876
+ ...payload.rows.map(
877
+ (row) => `| ${columns.map((c) => escapeCell(columnCell(row, c))).join(" | ")} |`
878
+ )
879
+ ].join("\n");
880
+ mime = "text/markdown;charset=utf-8";
881
+ extension = "md";
882
+ } else {
883
+ const delimiter = format === "csv" ? "," : " ";
884
+ const safe = options.spreadsheetSafe ?? format === "tsv";
885
+ const encode = (value, path, isString = true) => {
886
+ let text = value;
887
+ if (safe && isString && /^[\t\r\n ]*[=+\-@]/.test(text)) {
888
+ text = `'${text}`;
889
+ omissions.push({ path, reason: "escaped", count: 1 });
890
+ }
891
+ return text.includes(delimiter) || /["\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
892
+ };
893
+ plainText = [
894
+ columns.map((c) => encode(c.label, `/columns/${enc(c.id)}`)).join(delimiter),
895
+ ...payload.rows.map(
896
+ (row, index) => columns.map(
897
+ (c) => encode(
898
+ columnCell(row, c),
899
+ `/rows/${index}${c.path}`,
900
+ typeof readTransferCell(row, c) === "string"
901
+ )
902
+ ).join(delimiter)
903
+ )
904
+ ].join("\n");
905
+ if (format === "csv") {
906
+ mime = "text/csv;charset=utf-8";
907
+ extension = "csv";
908
+ }
909
+ if (format === "tsv") {
910
+ mime = "text/tab-separated-values;charset=utf-8";
911
+ extension = "tsv";
912
+ }
913
+ }
914
+ if (format === "html")
915
+ html = `<table><thead><tr>${columns.map((c) => `<th>${escapeHtml(c.label)}</th>`).join("")}</tr></thead><tbody>${payload.rows.map((row) => `<tr>${columns.map((c) => `<td>${escapeHtml(columnCell(row, c)).replace(/\r\n|\r|\n/g, "<br>")}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
916
+ } else {
917
+ plainText = payload.kind === "text" || payload.kind === "markdown" ? payload.text : stringifyJson(payload.value, { style: "pretty" });
918
+ if (format === "markdown") {
919
+ mime = "text/markdown;charset=utf-8";
920
+ extension = "md";
921
+ }
922
+ if (format === "html") html = `<pre>${escapeHtml(plainText)}</pre>`;
923
+ }
924
+ if (format === "html") {
925
+ mime = "text/html;charset=utf-8";
926
+ extension = "html";
927
+ }
928
+ return sealTransferArtifact({
929
+ snapshotId: draft.snapshotId,
930
+ draftRevision: draft.revision,
931
+ format,
932
+ plainText,
933
+ ...html === void 0 ? {} : { html },
934
+ file: {
935
+ filename: options.filename ?? `export.${extension}`,
936
+ mime,
937
+ bytes: new TextEncoder().encode(
938
+ format === "html" ? html ?? plainText : plainText
939
+ )
940
+ },
941
+ omissions
942
+ });
943
+ }
944
+ async function renderMarkdownHtml(markdown) {
945
+ const [{ marked }, purify] = await Promise.all([
946
+ import("marked"),
947
+ import("dompurify")
948
+ ]);
949
+ const html = await marked.parse(markdown);
950
+ const api = purify.default;
951
+ if (typeof api === "function" && typeof window !== "undefined") {
952
+ const purifier = api(window);
953
+ if (typeof purifier?.sanitize === "function") return purifier.sanitize(html);
954
+ }
955
+ if (typeof api.sanitize === "function")
956
+ return api.sanitize(html);
957
+ throw new ContentTransferError(
958
+ "rich-html-unavailable",
959
+ "Rich Markdown HTML requires a DOMPurify DOM adapter"
960
+ );
961
+ }
962
+ async function serializeMarkdownRich(d, filename = "export.html") {
963
+ if (d.payload.kind !== "markdown")
964
+ throw new ContentTransferError(
965
+ "unsupported-format",
966
+ "Rich Markdown requires Markdown payload"
967
+ );
968
+ const html = await renderMarkdownHtml(d.payload.text);
969
+ return sealTransferArtifact({
970
+ snapshotId: d.snapshotId,
971
+ draftRevision: d.revision,
972
+ format: "html",
973
+ plainText: d.payload.text,
974
+ html,
975
+ file: {
976
+ filename,
977
+ mime: "text/html;charset=utf-8",
978
+ bytes: new TextEncoder().encode(html)
979
+ },
980
+ omissions: [...d.omissions]
981
+ });
982
+ }
983
+ function createBrowserTransport() {
984
+ return {
985
+ async copy(a, signal) {
986
+ const cancelled = () => signal.aborted ? { status: "cancelled" } : void 0;
987
+ try {
988
+ if (cancelled()) return cancelled();
989
+ const c = globalThis.navigator?.clipboard;
990
+ if (!c?.write && !c?.writeText)
991
+ return {
992
+ status: "error",
993
+ code: "clipboard-unavailable",
994
+ message: "Clipboard writing is unavailable",
995
+ retryable: false
996
+ };
997
+ if (a.html && c.write && typeof globalThis.ClipboardItem === "function") {
998
+ try {
999
+ await c.write([
1000
+ new ClipboardItem({
1001
+ "text/plain": new Blob([a.plainText], { type: "text/plain" }),
1002
+ "text/html": new Blob([a.html], { type: "text/html" })
1003
+ })
1004
+ ]);
1005
+ if (cancelled()) return cancelled();
1006
+ return {
1007
+ status: "success",
1008
+ delivered: "clipboard",
1009
+ mimeTypes: ["text/plain", "text/html"]
1010
+ };
1011
+ } catch {
1012
+ if (cancelled()) return cancelled();
1013
+ }
1014
+ }
1015
+ if (c.writeText) {
1016
+ await c.writeText(a.plainText);
1017
+ if (cancelled()) return cancelled();
1018
+ return a.html ? {
1019
+ status: "degraded",
1020
+ delivered: "plain-text",
1021
+ reason: "Rich clipboard write was unavailable or rejected"
1022
+ } : {
1023
+ status: "success",
1024
+ delivered: "clipboard",
1025
+ mimeTypes: ["text/plain"]
1026
+ };
1027
+ }
1028
+ return {
1029
+ status: "error",
1030
+ code: "clipboard-rejected",
1031
+ message: "Clipboard rejected the write",
1032
+ retryable: true
1033
+ };
1034
+ } catch (e) {
1035
+ return cancelled() ?? {
1036
+ status: "error",
1037
+ code: "clipboard-rejected",
1038
+ message: e instanceof Error ? e.message : "Clipboard rejected the write",
1039
+ retryable: true
1040
+ };
1041
+ }
1042
+ },
1043
+ async download(a, signal) {
1044
+ if (signal.aborted) return { status: "cancelled" };
1045
+ if (!a.file || typeof document === "undefined" || !URL?.createObjectURL)
1046
+ return {
1047
+ status: "error",
1048
+ code: "download-unavailable",
1049
+ message: "Download is unavailable",
1050
+ retryable: false
1051
+ };
1052
+ let url;
1053
+ try {
1054
+ url = URL.createObjectURL(
1055
+ new Blob([a.file.bytes.slice().buffer], {
1056
+ type: a.file.mime
1057
+ })
1058
+ );
1059
+ const link = document.createElement("a");
1060
+ link.href = url;
1061
+ link.download = a.file.filename;
1062
+ link.click();
1063
+ return signal.aborted ? { status: "cancelled" } : {
1064
+ status: "success",
1065
+ delivered: "download-started",
1066
+ mimeTypes: [a.file.mime]
1067
+ };
1068
+ } catch (e) {
1069
+ return signal.aborted ? { status: "cancelled" } : {
1070
+ status: "error",
1071
+ code: "download-failed",
1072
+ message: e instanceof Error ? e.message : "Download failed",
1073
+ retryable: true
1074
+ };
1075
+ } finally {
1076
+ if (url) setTimeout(() => URL.revokeObjectURL(url), 0);
1077
+ }
1078
+ }
1079
+ };
1080
+ }
1081
+ function assertLimit(value, name) {
1082
+ if (value != null && (!Number.isSafeInteger(value) || value < 0)) {
1083
+ throw new ContentTransferError(
1084
+ "invalid-limit",
1085
+ `${name} must be a non-negative safe integer or null`
1086
+ );
1087
+ }
1088
+ }
1089
+ var limitKeys = [
1090
+ "maxRows",
1091
+ "maxStringChars",
1092
+ "maxDepth",
1093
+ "maxArrayItems",
1094
+ "targetTokens"
1095
+ ];
1096
+ function resolveTransferPreferences(provider = {}, menu = {}, sourceLimits = {}) {
1097
+ const limits = {
1098
+ maxRows: null,
1099
+ maxStringChars: null,
1100
+ maxDepth: null,
1101
+ maxArrayItems: null,
1102
+ targetTokens: null
1103
+ };
1104
+ for (const key of limitKeys) {
1105
+ const candidates = [
1106
+ provider.limits?.[key],
1107
+ menu.limits?.[key],
1108
+ sourceLimits[key]
1109
+ ];
1110
+ candidates.forEach((value) => assertLimit(value, key));
1111
+ const finite = candidates.filter((value) => value != null);
1112
+ limits[key] = finite.length ? Math.min(...finite) : null;
1113
+ }
1114
+ return deepFreeze({
1115
+ initialFormat: menu.initialFormat ?? provider.initialFormat ?? "plain",
1116
+ initialPreset: menu.initialPreset ?? provider.initialPreset ?? "full",
1117
+ limits
1118
+ });
1119
+ }
1120
+ function cloneTransferRegistration(value, path = "registration", seen = /* @__PURE__ */ new WeakSet()) {
1121
+ if (value === null || typeof value !== "object" && typeof value !== "function")
1122
+ return value;
1123
+ if (typeof value === "function") return value;
1124
+ if (seen.has(value))
1125
+ throw new ContentTransferError(
1126
+ "unsupported-registration-metadata",
1127
+ "Circular transfer registration metadata is unsupported",
1128
+ path
1129
+ );
1130
+ seen.add(value);
1131
+ if (Array.isArray(value)) {
1132
+ const copy2 = value.map(
1133
+ (item, index) => cloneTransferRegistration(item, `${path}/${index}`, seen)
1134
+ );
1135
+ seen.delete(value);
1136
+ return Object.freeze(copy2);
1137
+ }
1138
+ const prototype = Object.getPrototypeOf(value);
1139
+ if (prototype !== Object.prototype && prototype !== null)
1140
+ throw new ContentTransferError(
1141
+ "unsupported-registration-metadata",
1142
+ "Transfer registration metadata must use plain objects and arrays",
1143
+ path
1144
+ );
1145
+ const copy = Object.create(prototype);
1146
+ for (const key of Reflect.ownKeys(value)) {
1147
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
1148
+ if (!("value" in descriptor))
1149
+ throw new ContentTransferError(
1150
+ "unsupported-registration-metadata",
1151
+ "Transfer registration metadata cannot use accessors",
1152
+ `${path}/${String(key)}`
1153
+ );
1154
+ Object.defineProperty(copy, key, {
1155
+ value: cloneTransferRegistration(
1156
+ descriptor.value,
1157
+ `${path}/${String(key)}`,
1158
+ seen
1159
+ ),
1160
+ enumerable: descriptor.enumerable === true,
1161
+ writable: false,
1162
+ configurable: false
1163
+ });
1164
+ }
1165
+ seen.delete(value);
1166
+ return Object.freeze(copy);
1167
+ }
1168
+ function resolveTransferRegistry(...groups) {
1169
+ const ids = /* @__PURE__ */ new Set();
1170
+ const result = [];
1171
+ for (const group of groups)
1172
+ for (const item of group) {
1173
+ const copy = cloneTransferRegistration(item);
1174
+ if (!copy.id.trim() || ids.has(copy.id))
1175
+ throw new ContentTransferError(
1176
+ "duplicate-registration",
1177
+ `Transfer id ${JSON.stringify(copy.id)} is empty or registered more than once`
1178
+ );
1179
+ ids.add(copy.id);
1180
+ result.push(copy);
1181
+ }
1182
+ return Object.freeze(result);
1183
+ }
1184
+ function createSurfaceTransferHandle(options) {
1185
+ const declarations = resolveTransferRegistry(
1186
+ options.manifest.values.map((value) => ({ ...value, id: value.name }))
1187
+ );
1188
+ return {
1189
+ instanceId: options.instanceId,
1190
+ surfaceName: options.manifest.surfaceName,
1191
+ isMounted: options.isMounted,
1192
+ async capture(signal) {
1193
+ stop(signal);
1194
+ if (!options.isMounted())
1195
+ throw new ContentTransferError(
1196
+ "surface-unmounted",
1197
+ "The captured surface is no longer mounted"
1198
+ );
1199
+ const revisionBefore = options.getRevision?.();
1200
+ const scope = await options.getScope();
1201
+ stop(signal);
1202
+ if (!options.isMounted())
1203
+ throw new ContentTransferError(
1204
+ "surface-unmounted",
1205
+ "The surface closed during capture"
1206
+ );
1207
+ if (revisionBefore !== void 0 && options.getRevision?.() !== revisionBefore)
1208
+ throw new ContentTransferError(
1209
+ "surface-changed",
1210
+ "The surface changed during capture; capture again"
1211
+ );
1212
+ const value = {};
1213
+ for (const declaration of declarations) {
1214
+ if (Object.hasOwn(scope, declaration.name) && scope[declaration.name] !== void 0) {
1215
+ Object.defineProperty(value, declaration.name, {
1216
+ value: clone(
1217
+ scope[declaration.name],
1218
+ `/${enc(declaration.name)}`
1219
+ ),
1220
+ enumerable: true,
1221
+ writable: true,
1222
+ configurable: true
1223
+ });
1224
+ }
1225
+ }
1226
+ return directSource(
1227
+ { kind: "json", value },
1228
+ {
1229
+ sourceId: options.instanceId,
1230
+ revision: revisionBefore ?? uid(),
1231
+ label: options.manifest.label ?? options.manifest.surfaceName,
1232
+ unsavedChanges: options.unsavedChanges?.() ?? false,
1233
+ sections: declarations.filter((d) => Object.hasOwn(value, d.name)).map((d) => ({
1234
+ id: d.name,
1235
+ label: d.label,
1236
+ path: `/${enc(d.name)}`,
1237
+ includedByDefault: d.includedByDefault ?? true
1238
+ })),
1239
+ projection: {
1240
+ rules: [
1241
+ ...options.projection?.rules ?? [],
1242
+ ...declarations.map((d) => ({
1243
+ target: "payload",
1244
+ path: `/${enc(d.name)}`,
1245
+ exportable: d.exportable ?? true,
1246
+ classification: d.classification ?? "ordinary"
1247
+ }))
1248
+ ]
1249
+ },
1250
+ ...options.limits ? { limits: options.limits } : {}
1251
+ }
1252
+ );
1253
+ }
1254
+ };
1255
+ }
1256
+ function limitJson(value, limits, omissions, path = "", depth = 0) {
1257
+ if (limits.maxDepth != null && depth > limits.maxDepth) {
1258
+ omissions.push({ path, reason: "truncated" });
1259
+ return null;
1260
+ }
1261
+ if (typeof value === "string" && limits.maxStringChars != null && Array.from(value).length > limits.maxStringChars) {
1262
+ const chars = Array.from(value);
1263
+ omissions.push({
1264
+ path,
1265
+ reason: "truncated",
1266
+ count: chars.length - limits.maxStringChars
1267
+ });
1268
+ return chars.slice(0, limits.maxStringChars).join("");
1269
+ }
1270
+ if (Array.isArray(value)) {
1271
+ const count = Math.min(value.length, limits.maxArrayItems ?? value.length);
1272
+ if (count < value.length)
1273
+ omissions.push({
1274
+ path,
1275
+ reason: "truncated",
1276
+ count: value.length - count
1277
+ });
1278
+ return value.slice(0, count).map(
1279
+ (item, index) => limitJson(item, limits, omissions, `${path}/${index}`, depth + 1)
1280
+ );
1281
+ }
1282
+ if (value && typeof value === "object")
1283
+ return Object.fromEntries(
1284
+ Object.entries(value).map(([key, item]) => [
1285
+ key,
1286
+ limitJson(item, limits, omissions, `${path}/${enc(key)}`, depth + 1)
1287
+ ])
1288
+ );
1289
+ return value;
1290
+ }
1291
+ function limitPayload(payload, limits, omissions) {
1292
+ limitKeys.forEach((key) => assertLimit(limits[key], key));
1293
+ if (payload.kind === "rows") {
1294
+ const count = Math.min(
1295
+ payload.rows.length,
1296
+ limits.maxRows ?? payload.rows.length
1297
+ );
1298
+ if (count < payload.rows.length)
1299
+ omissions.push({
1300
+ path: "/rows",
1301
+ reason: "truncated",
1302
+ count: payload.rows.length - count
1303
+ });
1304
+ return {
1305
+ ...payload,
1306
+ rows: payload.rows.slice(0, count).map(
1307
+ (row, index) => limitJson(row, limits, omissions, `/rows/${index}`)
1308
+ )
1309
+ };
1310
+ }
1311
+ if (payload.kind === "json" || payload.kind === "registered")
1312
+ return { ...payload, value: limitJson(payload.value, limits, omissions) };
1313
+ return {
1314
+ ...payload,
1315
+ text: limitJson(payload.text, limits, omissions)
1316
+ };
1317
+ }
1318
+ function applyTransferLimits(draft, limits) {
1319
+ const omissions = [];
1320
+ const payload = limitPayload(draft.payload, limits, omissions);
1321
+ return omissions.length ? revise(draft, payload, omissions, "Applied preparation limits") : draft;
1322
+ }
1323
+ //# sourceMappingURL=content-transfer.cjs.map