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