@ai-matrx/kit 0.12.1 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -31,6 +31,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  // src/index.ts
32
32
  var src_exports = {};
33
33
  __export(src_exports, {
34
+ ContentTransferError: () => ContentTransferError,
34
35
  DBStoreManager: () => DBStoreManager,
35
36
  DEFAULT_JSON_INDENT: () => DEFAULT_JSON_INDENT,
36
37
  DEFAULT_JSON_WIDTH: () => DEFAULT_JSON_WIDTH,
@@ -38,19 +39,30 @@ __export(src_exports, {
38
39
  FeatureStore: () => FeatureStore,
39
40
  PublicStoreManager: () => PublicStoreManager,
40
41
  _resetIdbStoreSingletons: () => _resetIdbStoreSingletons,
42
+ applySectionSelection: () => applySectionSelection,
43
+ applyTransferLimits: () => applyTransferLimits,
41
44
  booleanUrlCodec: () => booleanUrlCodec,
45
+ buildAgentPayload: () => buildAgentPayload,
46
+ capture: () => capture,
42
47
  captureDrafts: () => captureDrafts,
48
+ collectAllMatching: () => collectAllMatching,
43
49
  commitUrlParams: () => commitUrlParams,
44
50
  computeSearchScore: () => computeSearchScore,
51
+ createBrowserTransport: () => createBrowserTransport,
45
52
  createColorNormalizer: () => createColorNormalizer,
53
+ createDraft: () => createDraft,
46
54
  createFormatter: () => createFormatter,
47
55
  createMatrxToast: () => createMatrxToast,
56
+ createSurfaceTransferHandle: () => createSurfaceTransferHandle,
48
57
  decodeQrFromElement: () => decodeQrFromElement,
49
58
  decodeQrFromImageData: () => decodeQrFromImageData,
50
59
  decodeQrFromImageFile: () => decodeQrFromImageFile,
51
60
  detectJson: () => detectJson,
61
+ directSource: () => directSource,
52
62
  discardDraft: () => discardDraft,
63
+ editDraft: () => editDraft,
53
64
  enumUrlCodec: () => enumUrlCodec,
65
+ fenceJsonBlock: () => fenceJsonBlock,
54
66
  filterAndSortBySearch: () => filterAndSortBySearch,
55
67
  findNearestTailwindColor: () => findNearestTailwindColor,
56
68
  fireInvalidation: () => fireInvalidation,
@@ -94,23 +106,38 @@ __export(src_exports, {
94
106
  jsonUrlCodec: () => jsonUrlCodec,
95
107
  listDrafts: () => listDrafts,
96
108
  matchesSearch: () => matchesSearch,
109
+ normalizeTransferJson: () => normalizeTransferJson,
97
110
  onFlushComplete: () => onFlushComplete,
98
111
  parseHexOrRgb: () => parseHexOrRgb,
99
112
  positiveIntegerUrlCodec: () => positiveIntegerUrlCodec,
113
+ projectSnapshot: () => projectSnapshot,
114
+ readTransferCell: () => readTransferCell,
115
+ reduceJson: () => reduceJson,
116
+ refreshDraft: () => refreshDraft,
100
117
  registerDraftSource: () => registerDraftSource,
101
118
  registerIdleTask: () => registerIdleTask,
102
119
  registerInvalidationCallback: () => registerInvalidationCallback,
120
+ renderMarkdownHtml: () => renderMarkdownHtml,
103
121
  reportDelimiterViolations: () => reportDelimiterViolations,
122
+ resetDraft: () => resetDraft,
104
123
  resetScheduler: () => resetScheduler,
124
+ resolveTransferPreferences: () => resolveTransferPreferences,
125
+ resolveTransferRegistry: () => resolveTransferRegistry,
105
126
  rgbDelta: () => rgbDelta,
106
127
  rgbToLab: () => rgbToLab,
107
128
  runWithConcurrency: () => runWithConcurrency,
129
+ sealTransferArtifact: () => sealTransferArtifact,
130
+ serialize: () => serialize,
131
+ serializeMarkdownRich: () => serializeMarkdownRich,
108
132
  setUrlStateRouter: () => setUrlStateRouter,
133
+ sourceChanged: () => sourceChanged,
109
134
  stringUrlCodec: () => stringUrlCodec,
110
135
  stringifyJson: () => stringifyJson,
111
136
  subscribeDrafts: () => subscribeDrafts,
112
137
  tailwindColors: () => tailwindColors,
138
+ transformRows: () => transformRows,
113
139
  treeContainsComponent: () => treeContainsComponent,
140
+ undoDraft: () => undoDraft,
114
141
  useAutosave: () => useAutosave,
115
142
  useClipboard: () => useClipboard,
116
143
  useDurableDraft: () => useDurableDraft,
@@ -930,7 +957,7 @@ function messageText(message, data) {
930
957
  }
931
958
  function createMatrxToast({
932
959
  toast: hostToast,
933
- capture
960
+ capture: capture2
934
961
  }) {
935
962
  if (typeof hostToast !== "function") {
936
963
  throw new Error(
@@ -938,9 +965,9 @@ function createMatrxToast({
938
965
  );
939
966
  }
940
967
  function captureToast(kind, message, data) {
941
- if (!capture) return;
968
+ if (!capture2) return;
942
969
  try {
943
- capture({
970
+ capture2({
944
971
  source: "user-toast",
945
972
  message: `${kind === "warning" ? "[warning] " : ""}${messageText(message, data)}`,
946
973
  userMessage: messageText(message, data),
@@ -2838,4 +2865,1181 @@ async function decodeQrFromImageFile(file) {
2838
2865
  bitmap.close();
2839
2866
  }
2840
2867
  }
2868
+
2869
+ // src/html-escape.ts
2870
+ var HTML_ESCAPES = {
2871
+ "&": "&",
2872
+ "<": "&lt;",
2873
+ ">": "&gt;",
2874
+ '"': "&quot;",
2875
+ "'": "&#39;"
2876
+ };
2877
+ var HTML_ESCAPE_RE = /[&<>"']/g;
2878
+ function escapeHtml(value) {
2879
+ if (typeof value !== "string") return "";
2880
+ return value.replace(HTML_ESCAPE_RE, (char) => HTML_ESCAPES[char] ?? char);
2881
+ }
2882
+
2883
+ // src/content-transfer/agent-payload.ts
2884
+ var escapeXml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
2885
+ var xmlName = (name) => {
2886
+ if (!/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(name)) throw new Error(`Invalid AI envelope name: ${name}`);
2887
+ return name;
2888
+ };
2889
+ var presentEntries = (values) => Object.entries(values ?? {}).filter(([, value]) => value !== null && value !== void 0 && value !== "");
2890
+ function fenceJsonBlock(json) {
2891
+ const runs = json.match(/`+/g) ?? [];
2892
+ const fence = "`".repeat(Math.max(3, ...runs.map((run) => run.length + 1)));
2893
+ return `${fence}json
2894
+ ${json.trimEnd()}
2895
+ ${fence}`;
2896
+ }
2897
+ function buildAgentPayload(input, environment = {}) {
2898
+ const kind = xmlName(input.kind);
2899
+ const url = environment.url ?? (typeof window === "undefined" ? "" : window.location.href);
2900
+ const route = environment.route ?? (typeof window === "undefined" ? "" : window.location.pathname);
2901
+ const attrs = presentEntries(input.attributes).map(([key, value]) => ` ${xmlName(key)}="${escapeXml(String(value))}"`).join("");
2902
+ const entries = [
2903
+ ["location", input.location],
2904
+ ...url ? [["url", url]] : [],
2905
+ ...route ? [["route", route]] : [],
2906
+ ["copied", input.description],
2907
+ ["copied-at", environment.capturedAt ?? (/* @__PURE__ */ new Date()).toISOString()],
2908
+ ...presentEntries(input.context).map(([key, value]) => [xmlName(key), String(value)])
2909
+ ];
2910
+ const json = JSON.stringify(input.data, null, 2);
2911
+ if (json === void 0) throw new Error("AI envelope data must be JSON serializable.");
2912
+ const safeJson = json.replace(/</g, "\\u003c").replace(/>/g, "\\u003e").replace(/&/g, "\\u0026");
2913
+ const context = entries.map(([key, value]) => `<${key}>${escapeXml(value)}</${key}>`).join("\n");
2914
+ const summary = input.summary ? `<summary>
2915
+ ${escapeXml(input.summary)}
2916
+ </summary>
2917
+ ` : "";
2918
+ return `<${kind}${attrs}>
2919
+ <context>
2920
+ ${context}
2921
+ </context>
2922
+ ${summary}<data format="json">
2923
+ ${fenceJsonBlock(safeJson)}
2924
+ </data>
2925
+ </${kind}>`;
2926
+ }
2927
+
2928
+ // src/content-transfer.ts
2929
+ var ContentTransferError = class extends Error {
2930
+ code;
2931
+ path;
2932
+ constructor(code, message, path) {
2933
+ super(message);
2934
+ this.code = code;
2935
+ this.path = path;
2936
+ }
2937
+ };
2938
+ var bound = /* @__PURE__ */ Symbol("bound-all-matching");
2939
+ var stop = (s) => {
2940
+ if (s.aborted) throw new DOMException("Cancelled", "AbortError");
2941
+ };
2942
+ var enc = (x) => x.replace(/~/g, "~0").replace(/\//g, "~1");
2943
+ var dec = (x) => x.replace(/~1/g, "/").replace(/~0/g, "~");
2944
+ function clone(v, path = "", seen = /* @__PURE__ */ new WeakSet(), policy = {}) {
2945
+ if (v === null || typeof v === "string" || typeof v === "boolean") return v;
2946
+ if (typeof v === "number") {
2947
+ if (!Number.isFinite(v))
2948
+ throw new ContentTransferError(
2949
+ "unsupported-value",
2950
+ "Only finite numbers are transferable",
2951
+ path
2952
+ );
2953
+ return v;
2954
+ }
2955
+ if (typeof v !== "object")
2956
+ throw new ContentTransferError(
2957
+ "unsupported-value",
2958
+ "Unsupported value",
2959
+ path
2960
+ );
2961
+ if (seen.has(v))
2962
+ throw new ContentTransferError(
2963
+ "circular-value",
2964
+ "Circular values cannot be transferred",
2965
+ path
2966
+ );
2967
+ if (!Array.isArray(v) && Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null)
2968
+ throw new ContentTransferError(
2969
+ "unsupported-value",
2970
+ "Only plain JSON objects are transferable",
2971
+ path
2972
+ );
2973
+ seen.add(v);
2974
+ if (Array.isArray(v)) {
2975
+ for (let index = 0; index < v.length; index += 1)
2976
+ if (!Object.hasOwn(v, index))
2977
+ throw new ContentTransferError(
2978
+ "unsupported-value",
2979
+ "Sparse arrays cannot be transferred",
2980
+ `${path}/${index}`
2981
+ );
2982
+ }
2983
+ const out = Array.isArray(v) ? v.map((x, i) => clone(x, `${path}/${i}`, seen, policy)) : Object.fromEntries(
2984
+ Object.entries(v).filter(([, x]) => !policy.omitUndefinedObjectProperties || x !== void 0).map(([k, x]) => [
2985
+ k,
2986
+ clone(x, `${path}/${enc(k)}`, seen, policy)
2987
+ ])
2988
+ );
2989
+ seen.delete(v);
2990
+ return out;
2991
+ }
2992
+ var maxSurfacePointerSegmentLength = 64;
2993
+ var maxSurfacePointerLength = 192;
2994
+ var truncateSurfacePointer = (value, maxLength) => {
2995
+ const characters = Array.from(value);
2996
+ return characters.length > maxLength ? `${characters.slice(0, maxLength - 1).join("")}\u2026` : value;
2997
+ };
2998
+ function displaySurfacePointer(path) {
2999
+ if (!path) return "/";
3000
+ const safe = path.split("/").slice(1).map((segment) => {
3001
+ const controlSafe = segment.replace(
3002
+ /[\u0000-\u001F\u007F-\u009F]/g,
3003
+ (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`
3004
+ );
3005
+ return truncateSurfacePointer(controlSafe, maxSurfacePointerSegmentLength);
3006
+ }).join("/");
3007
+ const pointer = `/${safe}`;
3008
+ return truncateSurfacePointer(pointer, maxSurfacePointerLength);
3009
+ }
3010
+ function cloneSurfaceValue(value, path) {
3011
+ try {
3012
+ return clone(value, path, /* @__PURE__ */ new WeakSet(), {
3013
+ omitUndefinedObjectProperties: true
3014
+ });
3015
+ } catch (error) {
3016
+ if (error instanceof ContentTransferError)
3017
+ throw new ContentTransferError(
3018
+ error.code,
3019
+ `Surface capture rejected value at ${displaySurfacePointer(error.path)}: ${error.message}`,
3020
+ error.path
3021
+ );
3022
+ throw error;
3023
+ }
3024
+ }
3025
+ function normalizeTransferJson(value) {
3026
+ return clone(value);
3027
+ }
3028
+ function deepFreeze(v) {
3029
+ if (ArrayBuffer.isView(v)) return v;
3030
+ if (v && typeof v === "object" && !Object.isFrozen(v)) {
3031
+ Object.freeze(v);
3032
+ for (const x of Object.values(v)) deepFreeze(x);
3033
+ }
3034
+ return v;
3035
+ }
3036
+ function at(v, path) {
3037
+ validatePointer(path);
3038
+ if (path === "") return v;
3039
+ if (!path.startsWith("/"))
3040
+ throw new ContentTransferError(
3041
+ "invalid-path",
3042
+ "Expected RFC 6901 pointer",
3043
+ path
3044
+ );
3045
+ let cur = v;
3046
+ for (const part of path.slice(1).split("/").map(dec)) {
3047
+ if (Array.isArray(cur)) cur = cur[Number(part)];
3048
+ else if (cur && typeof cur === "object")
3049
+ cur = Object.hasOwn(cur, part) ? cur[part] : void 0;
3050
+ else return void 0;
3051
+ }
3052
+ return cur;
3053
+ }
3054
+ function validatePointer(path) {
3055
+ if (path !== "" && !path.startsWith("/") || /~(?![01])/u.test(path))
3056
+ throw new ContentTransferError(
3057
+ "invalid-path",
3058
+ "Expected an RFC 6901 JSON pointer",
3059
+ path
3060
+ );
3061
+ }
3062
+ function readTransferCell(row, column) {
3063
+ return at(row, column.path);
3064
+ }
3065
+ function without(v, paths, omit, path = "") {
3066
+ if (paths.includes(path)) {
3067
+ omit.push({ path, reason: "excluded" });
3068
+ return void 0;
3069
+ }
3070
+ if (Array.isArray(v))
3071
+ return v.map((x, i) => without(x, paths, omit, `${path}/${i}`)).filter((x) => x !== void 0);
3072
+ if (v && typeof v === "object") {
3073
+ const out = /* @__PURE__ */ Object.create(null);
3074
+ for (const [k, x] of Object.entries(v)) {
3075
+ const y = without(x, paths, omit, `${path}/${enc(k)}`);
3076
+ if (y !== void 0) out[k] = y;
3077
+ }
3078
+ return out;
3079
+ }
3080
+ return v;
3081
+ }
3082
+ function projectValue(v, rules, target, omit) {
3083
+ rules.forEach((rule) => validatePointer(rule.path));
3084
+ return without(
3085
+ clone(v),
3086
+ rules.filter(
3087
+ (r) => r.target === target && (!r.exportable || r.classification !== "ordinary")
3088
+ ).map((r) => r.path),
3089
+ omit
3090
+ ) ?? null;
3091
+ }
3092
+ function normalize(p, projection, omit) {
3093
+ if (p.kind === "text" || p.kind === "markdown") {
3094
+ if (typeof p.text !== "string")
3095
+ throw new ContentTransferError(
3096
+ "unsupported-value",
3097
+ "Text payload must contain a string",
3098
+ "/text"
3099
+ );
3100
+ const value = projectValue(p.text, projection.rules, "payload", omit);
3101
+ return { kind: p.kind, text: typeof value === "string" ? value : "" };
3102
+ }
3103
+ if (p.kind === "json")
3104
+ return {
3105
+ kind: "json",
3106
+ value: projectValue(p.value, projection.rules, "payload", omit)
3107
+ };
3108
+ if (p.kind === "registered")
3109
+ return {
3110
+ kind: "registered",
3111
+ format: p.format,
3112
+ value: projectValue(p.value, projection.rules, "payload", omit)
3113
+ };
3114
+ const rowsPayload = p;
3115
+ if (p.kind !== "rows")
3116
+ throw new ContentTransferError(
3117
+ "invalid-payload",
3118
+ "Unsupported payload kind"
3119
+ );
3120
+ const columns = rowsPayload.columns.map((c) => ({ ...c }));
3121
+ resolveTransferRegistry(columns);
3122
+ columns.forEach((column) => validatePointer(column.path));
3123
+ const rules = [
3124
+ ...projection.rules,
3125
+ ...columns.filter(
3126
+ (c) => c.exportable === false || c.classification === "secret" || c.classification === "credential"
3127
+ ).map((c) => ({
3128
+ target: "row",
3129
+ path: c.path,
3130
+ exportable: c.exportable ?? true,
3131
+ classification: c.classification ?? "ordinary"
3132
+ }))
3133
+ ];
3134
+ return {
3135
+ kind: "rows",
3136
+ columns,
3137
+ rows: rowsPayload.rows.map((row, index) => {
3138
+ if (!row || typeof row !== "object" || Array.isArray(row))
3139
+ throw new ContentTransferError(
3140
+ "invalid-row",
3141
+ "A table row must be a JSON object",
3142
+ `/rows/${index}`
3143
+ );
3144
+ const projected = projectValue(row, rules, "row", omit);
3145
+ return projected === null ? {} : projected;
3146
+ })
3147
+ };
3148
+ }
3149
+ function projectSnapshot(raw, projection) {
3150
+ const omissions = raw.omissions.map((o) => ({ ...o }));
3151
+ const normalized = normalize(raw.payload, projection, omissions);
3152
+ const payload = raw.limits ? limitPayload(normalized, raw.limits, omissions) : normalized;
3153
+ const included = payload.kind === "rows" ? payload.rows.length : raw.coverage.included;
3154
+ return deepFreeze({
3155
+ ...raw,
3156
+ payload,
3157
+ coverage: {
3158
+ ...raw.coverage,
3159
+ included,
3160
+ ...included < raw.coverage.included ? { status: "partial", reason: "Source export limit applied" } : {}
3161
+ },
3162
+ omissions,
3163
+ sections: raw.sections.filter(
3164
+ (section) => !projection.rules.some(
3165
+ (rule) => rule.target === "payload" && (!rule.exportable || rule.classification !== "ordinary") && (section.path === rule.path || section.path.startsWith(`${rule.path}/`))
3166
+ )
3167
+ ).map((x) => ({ ...x })),
3168
+ ...raw.limits ? { limits: { ...raw.limits } } : {}
3169
+ });
3170
+ }
3171
+ var uid = () => globalThis.crypto?.randomUUID?.() ?? `capture-${Date.now()}-${Math.random()}`;
3172
+ function directSource(payload, options = {}) {
3173
+ const id = options.id ?? uid();
3174
+ return {
3175
+ projection: options.projection ?? { rules: [] },
3176
+ snapshot: {
3177
+ id,
3178
+ sourceId: options.sourceId ?? id,
3179
+ revision: options.revision ?? uid(),
3180
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
3181
+ label: options.label ?? "Content",
3182
+ payload,
3183
+ coverage: options.coverage ?? {
3184
+ status: "complete",
3185
+ included: payload.kind === "rows" ? payload.rows.length : 1,
3186
+ total: payload.kind === "rows" ? payload.rows.length : 1
3187
+ },
3188
+ unsavedChanges: options.unsavedChanges ?? false,
3189
+ omissions: [],
3190
+ sections: options.sections ?? [],
3191
+ ...options.limits ? { limits: { ...options.limits } } : {}
3192
+ }
3193
+ };
3194
+ }
3195
+ async function capture(source, signal, scope = "target") {
3196
+ stop(signal);
3197
+ const captured = "kind" in source ? directSource(source) : await source.capture({ scope, signal });
3198
+ stop(signal);
3199
+ const all = captured.allMatching;
3200
+ if (all && (all.query.sourceId !== captured.snapshot.sourceId || all.query.revision !== captured.snapshot.revision || all.query.order.length === 0))
3201
+ throw new ContentTransferError(
3202
+ "query-mismatch",
3203
+ "All-matching query must be captured with stable ordering"
3204
+ );
3205
+ const snapshot = projectSnapshot(captured.snapshot, captured.projection);
3206
+ if (!all) return { snapshot };
3207
+ return {
3208
+ snapshot,
3209
+ allMatching: deepFreeze({
3210
+ [bound]: true,
3211
+ source: {
3212
+ ...all,
3213
+ query: {
3214
+ ...all.query,
3215
+ query: clone(all.query.query),
3216
+ order: all.query.order.map((x) => ({ ...x }))
3217
+ }
3218
+ },
3219
+ projection: { rules: captured.projection.rules.map((x) => ({ ...x })) },
3220
+ columns: snapshot.payload.kind === "rows" ? snapshot.payload.columns : [],
3221
+ ...snapshot.limits ? { limits: { ...snapshot.limits } } : {}
3222
+ })
3223
+ };
3224
+ }
3225
+ function createDraft(s) {
3226
+ return deepFreeze({
3227
+ snapshotId: s.id,
3228
+ sourceId: s.sourceId,
3229
+ sourceRevision: s.revision,
3230
+ revision: 0,
3231
+ payload: normalize(s.payload, { rules: [] }, []),
3232
+ omissions: [...s.omissions],
3233
+ manuallyEdited: false,
3234
+ provenance: [{ kind: "original", description: "Captured source snapshot" }]
3235
+ });
3236
+ }
3237
+ function revise(d, p, o, description, manual = d.manuallyEdited, kind = "deterministic", baseOmissions = d.omissions) {
3238
+ const { history: _history, ...previous } = d;
3239
+ return deepFreeze({
3240
+ ...d,
3241
+ revision: d.revision + 1,
3242
+ payload: normalize(p, { rules: [] }, []),
3243
+ omissions: [...baseOmissions, ...o],
3244
+ manuallyEdited: manual,
3245
+ provenance: [...d.provenance, { kind, description }],
3246
+ history: [...d.history ?? [], previous]
3247
+ });
3248
+ }
3249
+ var editDraft = (d, p) => revise(d, p, [], "Manual edit", true, "manual");
3250
+ var resetDraft = (s) => createDraft(s);
3251
+ var sourceChanged = (d, s) => d.sourceId !== s.sourceId || d.sourceRevision !== s.revision;
3252
+ function undoDraft(d) {
3253
+ const previous = d.history?.at(-1);
3254
+ if (!previous) return d;
3255
+ return deepFreeze({
3256
+ ...previous,
3257
+ revision: d.revision + 1,
3258
+ history: d.history.slice(0, -1)
3259
+ });
3260
+ }
3261
+ function refreshDraft(draft, snapshot, choice) {
3262
+ return choice === "keep" ? draft : createDraft(snapshot);
3263
+ }
3264
+ function applySectionSelection(d, s, ids) {
3265
+ if (d.snapshotId !== s.id || d.sourceId !== s.sourceId || d.sourceRevision !== s.revision)
3266
+ throw new ContentTransferError(
3267
+ "snapshot-mismatch",
3268
+ "Section selection requires the draft's captured source snapshot"
3269
+ );
3270
+ const selected = new Set(ids), omit = [], paths = s.sections.filter((x) => !selected.has(x.id)).map((x) => {
3271
+ omit.push({ path: x.path, reason: "excluded" });
3272
+ return x.path;
3273
+ }), baseOmissions = s.omissions;
3274
+ if (s.payload.kind === "json")
3275
+ return revise(
3276
+ d,
3277
+ { kind: "json", value: without(s.payload.value, paths, []) ?? null },
3278
+ omit,
3279
+ "Selected sections",
3280
+ d.manuallyEdited,
3281
+ "deterministic",
3282
+ baseOmissions
3283
+ );
3284
+ if (s.payload.kind === "registered")
3285
+ return revise(
3286
+ d,
3287
+ {
3288
+ kind: "registered",
3289
+ format: s.payload.format,
3290
+ value: without(s.payload.value, paths, []) ?? null
3291
+ },
3292
+ omit,
3293
+ "Selected sections",
3294
+ d.manuallyEdited,
3295
+ "deterministic",
3296
+ baseOmissions
3297
+ );
3298
+ return revise(
3299
+ d,
3300
+ s.payload,
3301
+ omit,
3302
+ "Selected sections",
3303
+ d.manuallyEdited,
3304
+ "deterministic",
3305
+ baseOmissions
3306
+ );
3307
+ }
3308
+ function transformRows(d, o) {
3309
+ if (d.payload.kind !== "rows") return d;
3310
+ if (o.top != null) assertLimit(o.top, "maxRows");
3311
+ const cols = o.visibleColumns ? o.visibleColumns.map(
3312
+ (id) => d.payload.kind === "rows" ? d.payload.columns.find((c) => c.id === id) : void 0
3313
+ ).filter((c) => Boolean(c)) : d.payload.columns.filter((c) => c.visible);
3314
+ const get = readTransferCell;
3315
+ let rows = [...d.payload.rows], omit = [];
3316
+ const before = rows.length;
3317
+ if (o.selectedIndices !== void 0) {
3318
+ const selected = /* @__PURE__ */ new Set();
3319
+ for (const index of o.selectedIndices) {
3320
+ if (!Number.isSafeInteger(index) || index < 0 || index >= d.payload.rows.length)
3321
+ throw new ContentTransferError(
3322
+ "invalid-selection-index",
3323
+ "Selected row indexes must be non-negative positions in the input draft rows"
3324
+ );
3325
+ selected.add(index);
3326
+ }
3327
+ rows = d.payload.rows.filter((_, index) => selected.has(index));
3328
+ }
3329
+ if (o.selectedIds && o.idColumn) {
3330
+ const set = new Set(o.selectedIds);
3331
+ const idColumn = d.payload.columns.find((c) => c.id === o.idColumn);
3332
+ rows = rows.filter(
3333
+ (r) => set.has(String(idColumn ? get(r, idColumn) : r[o.idColumn]))
3334
+ );
3335
+ }
3336
+ if (o.search) {
3337
+ const q = o.search.toLowerCase();
3338
+ rows = rows.filter(
3339
+ (r) => cols.some(
3340
+ (c) => String(get(r, c) ?? "").toLowerCase().includes(q)
3341
+ )
3342
+ );
3343
+ }
3344
+ for (const [id, q] of Object.entries(o.filters ?? {})) {
3345
+ const c = cols.find((x) => x.id === id);
3346
+ if (c)
3347
+ rows = rows.filter(
3348
+ (r) => String(get(r, c) ?? "").toLowerCase().includes(q.toLowerCase())
3349
+ );
3350
+ }
3351
+ if (rows.length !== before)
3352
+ omit.push({
3353
+ path: "/rows",
3354
+ reason: "filtered",
3355
+ count: before - rows.length
3356
+ });
3357
+ if (o.sort) {
3358
+ const c = cols.find((x) => x.id === o.sort.column);
3359
+ if (c)
3360
+ rows.sort((a, b) => {
3361
+ const left = get(a, c);
3362
+ const right = get(b, c);
3363
+ const compare = typeof left === "number" && typeof right === "number" ? left - right : String(left ?? "").localeCompare(String(right ?? ""));
3364
+ return compare * (o.sort.direction === "asc" ? 1 : -1);
3365
+ });
3366
+ }
3367
+ if (o.top != null && rows.length > o.top) {
3368
+ omit.push({
3369
+ path: "/rows",
3370
+ reason: "truncated",
3371
+ count: rows.length - o.top
3372
+ });
3373
+ rows = rows.slice(0, o.top);
3374
+ }
3375
+ if (o.structuredProjection === "visible") {
3376
+ rows = rows.map(
3377
+ (r) => Object.fromEntries(cols.map((c) => [c.id, get(r, c) ?? null]))
3378
+ );
3379
+ omit.push({
3380
+ path: "/columns",
3381
+ reason: "excluded",
3382
+ count: d.payload.columns.length - cols.length
3383
+ });
3384
+ }
3385
+ return revise(
3386
+ d,
3387
+ {
3388
+ kind: "rows",
3389
+ rows,
3390
+ columns: cols.map((c) => ({
3391
+ ...c,
3392
+ visible: true,
3393
+ ...o.structuredProjection === "visible" ? { path: `/${enc(c.id)}` } : {}
3394
+ }))
3395
+ },
3396
+ omit,
3397
+ "Prepared row subset"
3398
+ );
3399
+ }
3400
+ function reduceJson(draft, options) {
3401
+ if (draft.payload.kind !== "json" && draft.payload.kind !== "registered")
3402
+ return draft;
3403
+ const omissions = [];
3404
+ options.exclude?.forEach(validatePointer);
3405
+ const filtered = without(clone(draft.payload.value), options.exclude ?? [], omissions) ?? null;
3406
+ const payload = limitPayload(
3407
+ { ...draft.payload, value: filtered },
3408
+ options,
3409
+ omissions
3410
+ );
3411
+ return revise(draft, payload, omissions, "Reduced JSON");
3412
+ }
3413
+ async function collectAllMatching(c, signal) {
3414
+ const rows = [], omissions = [], ids = /* @__PURE__ */ new Set(), cursors = /* @__PURE__ */ new Set();
3415
+ let cursor = null, token, last = {
3416
+ status: "unknown",
3417
+ included: 0,
3418
+ total: null
3419
+ };
3420
+ let certifiedTotal;
3421
+ const maxRows = c.limits?.maxRows;
3422
+ if (maxRows != null) assertLimit(maxRows, "maxRows");
3423
+ const finishAtLimit = (total, knownOmitted) => ({
3424
+ rows: deepFreeze(rows),
3425
+ omissions: deepFreeze([
3426
+ ...omissions,
3427
+ {
3428
+ path: "/rows",
3429
+ reason: "truncated",
3430
+ ...knownOmitted === void 0 || knownOmitted <= 0 ? {} : { count: knownOmitted }
3431
+ }
3432
+ ]),
3433
+ coverage: deepFreeze({
3434
+ status: "partial",
3435
+ included: rows.length,
3436
+ total,
3437
+ reason: "Source export limit applied"
3438
+ })
3439
+ });
3440
+ try {
3441
+ if (maxRows === 0) return finishAtLimit(null);
3442
+ do {
3443
+ stop(signal);
3444
+ const page = await c.source.page({
3445
+ query: c.source.query,
3446
+ cursor,
3447
+ consistencyToken: token ?? null,
3448
+ signal
3449
+ });
3450
+ stop(signal);
3451
+ if (token === void 0) token = page.consistencyToken;
3452
+ else if (page.consistencyToken !== token)
3453
+ throw new ContentTransferError(
3454
+ "consistency-token-changed",
3455
+ "All-matching export changed during collection"
3456
+ );
3457
+ if (page.coverage.included !== page.rows.length)
3458
+ throw new ContentTransferError(
3459
+ "invalid-page-coverage",
3460
+ "Page count does not match returned rows"
3461
+ );
3462
+ if (page.coverage.total !== null && (!Number.isSafeInteger(page.coverage.total) || page.coverage.total < 0))
3463
+ throw new ContentTransferError(
3464
+ "invalid-page-coverage",
3465
+ "Page total must be a non-negative integer or null"
3466
+ );
3467
+ if (certifiedTotal === void 0) certifiedTotal = page.coverage.total;
3468
+ else if (page.coverage.total !== certifiedTotal)
3469
+ throw new ContentTransferError(
3470
+ "inconsistent-total",
3471
+ "All-matching source changed its reported total during collection"
3472
+ );
3473
+ const projected = normalize(
3474
+ { kind: "rows", rows: page.rows, columns: [...c.columns] },
3475
+ c.projection,
3476
+ omissions
3477
+ ).rows;
3478
+ let uniqueBeyondLimit = 0;
3479
+ for (const row of projected) {
3480
+ const id = c.source.getRowId(row);
3481
+ if (!id)
3482
+ throw new ContentTransferError(
3483
+ "invalid-row-id",
3484
+ "All-matching source returned empty projected ID"
3485
+ );
3486
+ if (!ids.has(id)) {
3487
+ ids.add(id);
3488
+ if (maxRows == null || rows.length < maxRows)
3489
+ rows.push(
3490
+ limitPayload(
3491
+ { kind: "rows", rows: [row], columns: [...c.columns] },
3492
+ { ...c.limits, maxRows: null },
3493
+ omissions
3494
+ ).rows[0]
3495
+ );
3496
+ else uniqueBeyondLimit += 1;
3497
+ } else omissions.push({ path: `/rows/${enc(id)}`, reason: "duplicate" });
3498
+ }
3499
+ if (page.coverage.total !== null && page.coverage.total < ids.size)
3500
+ throw new ContentTransferError(
3501
+ "invalid-page-coverage",
3502
+ "Page total is smaller than the accumulated unique row count"
3503
+ );
3504
+ last = page.coverage;
3505
+ if (maxRows != null && rows.length >= maxRows && (uniqueBeyondLimit > 0 || page.nextCursor !== null))
3506
+ return finishAtLimit(
3507
+ page.coverage.total,
3508
+ page.nextCursor === null ? uniqueBeyondLimit : page.coverage.total != null && page.coverage.total > rows.length ? page.coverage.total - rows.length : void 0
3509
+ );
3510
+ cursor = page.nextCursor;
3511
+ if (cursor !== null && (!cursor || cursors.has(cursor)))
3512
+ throw new ContentTransferError(
3513
+ "non-advancing-cursor",
3514
+ "All-matching source repeated a cursor"
3515
+ );
3516
+ if (cursor) cursors.add(cursor);
3517
+ } while (cursor !== null);
3518
+ const complete = c.source.stableSnapshot === true && last.status === "complete" && last.total === rows.length && token !== void 0;
3519
+ return {
3520
+ rows: deepFreeze(rows),
3521
+ omissions: deepFreeze(omissions),
3522
+ coverage: deepFreeze(
3523
+ complete ? { ...last, included: rows.length } : {
3524
+ ...last,
3525
+ status: "partial",
3526
+ included: rows.length,
3527
+ reason: last.reason ?? "Source did not certify a stable complete snapshot"
3528
+ }
3529
+ )
3530
+ };
3531
+ } catch (e) {
3532
+ const error = e instanceof ContentTransferError ? e : new ContentTransferError(
3533
+ signal.aborted ? "cancelled" : "page-failed",
3534
+ e instanceof Error ? e.message : "Page collection failed"
3535
+ );
3536
+ return {
3537
+ rows: deepFreeze(rows),
3538
+ omissions: deepFreeze(omissions),
3539
+ coverage: deepFreeze({
3540
+ status: "partial",
3541
+ included: rows.length,
3542
+ total: last.total,
3543
+ reason: error.message
3544
+ }),
3545
+ error
3546
+ };
3547
+ }
3548
+ }
3549
+ var textValue = (value) => value === void 0 ? "" : typeof value === "string" ? value : stringifyJson(value, { style: "compact" });
3550
+ function sealTransferArtifact(artifact) {
3551
+ if (!artifact.file)
3552
+ return deepFreeze({
3553
+ ...artifact,
3554
+ omissions: artifact.omissions.map((o) => ({ ...o }))
3555
+ });
3556
+ const bytes = artifact.file.bytes.slice();
3557
+ const file = {
3558
+ filename: artifact.file.filename,
3559
+ mime: artifact.file.mime,
3560
+ get bytes() {
3561
+ return bytes.slice();
3562
+ }
3563
+ };
3564
+ return deepFreeze({
3565
+ ...artifact,
3566
+ file,
3567
+ omissions: artifact.omissions.map((o) => ({ ...o }))
3568
+ });
3569
+ }
3570
+ function serialize(draft, format, options = {}) {
3571
+ const payload = draft.payload;
3572
+ const omissions = draft.omissions.map((o) => ({ ...o }));
3573
+ let plainText = "", html;
3574
+ let mime = "text/plain;charset=utf-8", extension = "txt";
3575
+ const columnCell = (row, column) => textValue(readTransferCell(row, column));
3576
+ if ((format === "csv" || format === "tsv") && payload.kind !== "rows") {
3577
+ throw new ContentTransferError(
3578
+ "unsupported-format",
3579
+ `${format.toUpperCase()} requires tabular data`
3580
+ );
3581
+ }
3582
+ if (format === "json" || format === "compact-json") {
3583
+ const value = payload.kind === "rows" ? payload.rows : payload.kind === "text" || payload.kind === "markdown" ? payload.text : payload.value;
3584
+ plainText = stringifyJson(value, {
3585
+ style: format === "json" ? "pretty" : "compact"
3586
+ });
3587
+ mime = "application/json;charset=utf-8";
3588
+ extension = "json";
3589
+ } else if (payload.kind === "rows") {
3590
+ const columns = payload.columns.filter(
3591
+ (c) => c.visible && c.exportable !== false && c.classification !== "secret" && c.classification !== "credential"
3592
+ );
3593
+ if (format === "markdown") {
3594
+ const escapeCell = (value) => escapeHtml(value).replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\r\n|\r|\n/g, "<br>");
3595
+ plainText = [
3596
+ `| ${columns.map((c) => escapeCell(c.label)).join(" | ")} |`,
3597
+ `| ${columns.map(() => "---").join(" | ")} |`,
3598
+ ...payload.rows.map(
3599
+ (row) => `| ${columns.map((c) => escapeCell(columnCell(row, c))).join(" | ")} |`
3600
+ )
3601
+ ].join("\n");
3602
+ mime = "text/markdown;charset=utf-8";
3603
+ extension = "md";
3604
+ } else {
3605
+ const delimiter = format === "csv" ? "," : " ";
3606
+ const safe = options.spreadsheetSafe ?? format === "tsv";
3607
+ const encode = (value, path, isString = true) => {
3608
+ let text = value;
3609
+ if (safe && isString && /^[\t\r\n ]*[=+\-@]/.test(text)) {
3610
+ text = `'${text}`;
3611
+ omissions.push({ path, reason: "escaped", count: 1 });
3612
+ }
3613
+ return text.includes(delimiter) || /["\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
3614
+ };
3615
+ plainText = [
3616
+ columns.map((c) => encode(c.label, `/columns/${enc(c.id)}`)).join(delimiter),
3617
+ ...payload.rows.map(
3618
+ (row, index) => columns.map(
3619
+ (c) => encode(
3620
+ columnCell(row, c),
3621
+ `/rows/${index}${c.path}`,
3622
+ typeof readTransferCell(row, c) === "string"
3623
+ )
3624
+ ).join(delimiter)
3625
+ )
3626
+ ].join("\n");
3627
+ if (format === "csv") {
3628
+ mime = "text/csv;charset=utf-8";
3629
+ extension = "csv";
3630
+ }
3631
+ if (format === "tsv") {
3632
+ mime = "text/tab-separated-values;charset=utf-8";
3633
+ extension = "tsv";
3634
+ }
3635
+ }
3636
+ if (format === "html")
3637
+ 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>`;
3638
+ } else {
3639
+ plainText = payload.kind === "text" || payload.kind === "markdown" ? payload.text : stringifyJson(payload.value, { style: "pretty" });
3640
+ if (format === "markdown") {
3641
+ mime = "text/markdown;charset=utf-8";
3642
+ extension = "md";
3643
+ }
3644
+ if (format === "html") html = `<pre>${escapeHtml(plainText)}</pre>`;
3645
+ }
3646
+ if (format === "html") {
3647
+ mime = "text/html;charset=utf-8";
3648
+ extension = "html";
3649
+ }
3650
+ return sealTransferArtifact({
3651
+ snapshotId: draft.snapshotId,
3652
+ draftRevision: draft.revision,
3653
+ format,
3654
+ plainText,
3655
+ ...html === void 0 ? {} : { html },
3656
+ file: {
3657
+ filename: options.filename ?? `export.${extension}`,
3658
+ mime,
3659
+ bytes: new TextEncoder().encode(
3660
+ format === "html" ? html ?? plainText : plainText
3661
+ )
3662
+ },
3663
+ omissions
3664
+ });
3665
+ }
3666
+ async function renderMarkdownHtml(markdown) {
3667
+ const [{ marked }, purify] = await Promise.all([
3668
+ import("marked"),
3669
+ import("dompurify")
3670
+ ]);
3671
+ const html = await marked.parse(markdown);
3672
+ const api = purify.default;
3673
+ if (typeof api === "function" && typeof window !== "undefined") {
3674
+ const purifier = api(window);
3675
+ if (typeof purifier?.sanitize === "function") return purifier.sanitize(html);
3676
+ }
3677
+ if (typeof api.sanitize === "function")
3678
+ return api.sanitize(html);
3679
+ throw new ContentTransferError(
3680
+ "rich-html-unavailable",
3681
+ "Rich Markdown HTML requires a DOMPurify DOM adapter"
3682
+ );
3683
+ }
3684
+ async function serializeMarkdownRich(d, filename = "export.html") {
3685
+ if (d.payload.kind !== "markdown")
3686
+ throw new ContentTransferError(
3687
+ "unsupported-format",
3688
+ "Rich Markdown requires Markdown payload"
3689
+ );
3690
+ const html = await renderMarkdownHtml(d.payload.text);
3691
+ return sealTransferArtifact({
3692
+ snapshotId: d.snapshotId,
3693
+ draftRevision: d.revision,
3694
+ format: "html",
3695
+ plainText: d.payload.text,
3696
+ html,
3697
+ file: {
3698
+ filename,
3699
+ mime: "text/html;charset=utf-8",
3700
+ bytes: new TextEncoder().encode(html)
3701
+ },
3702
+ omissions: [...d.omissions]
3703
+ });
3704
+ }
3705
+ function createBrowserTransport() {
3706
+ return {
3707
+ async copy(a, signal) {
3708
+ const cancelled = () => signal.aborted ? { status: "cancelled" } : void 0;
3709
+ try {
3710
+ if (cancelled()) return cancelled();
3711
+ const c = globalThis.navigator?.clipboard;
3712
+ if (!c?.write && !c?.writeText)
3713
+ return {
3714
+ status: "error",
3715
+ code: "clipboard-unavailable",
3716
+ message: "Clipboard writing is unavailable",
3717
+ retryable: false
3718
+ };
3719
+ if (a.html && c.write && typeof globalThis.ClipboardItem === "function") {
3720
+ try {
3721
+ await c.write([
3722
+ new ClipboardItem({
3723
+ "text/plain": new Blob([a.plainText], { type: "text/plain" }),
3724
+ "text/html": new Blob([a.html], { type: "text/html" })
3725
+ })
3726
+ ]);
3727
+ if (cancelled()) return cancelled();
3728
+ return {
3729
+ status: "success",
3730
+ delivered: "clipboard",
3731
+ mimeTypes: ["text/plain", "text/html"]
3732
+ };
3733
+ } catch {
3734
+ if (cancelled()) return cancelled();
3735
+ }
3736
+ }
3737
+ if (c.writeText) {
3738
+ await c.writeText(a.plainText);
3739
+ if (cancelled()) return cancelled();
3740
+ return a.html ? {
3741
+ status: "degraded",
3742
+ delivered: "plain-text",
3743
+ reason: "Rich clipboard write was unavailable or rejected"
3744
+ } : {
3745
+ status: "success",
3746
+ delivered: "clipboard",
3747
+ mimeTypes: ["text/plain"]
3748
+ };
3749
+ }
3750
+ return {
3751
+ status: "error",
3752
+ code: "clipboard-rejected",
3753
+ message: "Clipboard rejected the write",
3754
+ retryable: true
3755
+ };
3756
+ } catch (e) {
3757
+ return cancelled() ?? {
3758
+ status: "error",
3759
+ code: "clipboard-rejected",
3760
+ message: e instanceof Error ? e.message : "Clipboard rejected the write",
3761
+ retryable: true
3762
+ };
3763
+ }
3764
+ },
3765
+ async download(a, signal) {
3766
+ if (signal.aborted) return { status: "cancelled" };
3767
+ if (!a.file || typeof document === "undefined" || !URL?.createObjectURL)
3768
+ return {
3769
+ status: "error",
3770
+ code: "download-unavailable",
3771
+ message: "Download is unavailable",
3772
+ retryable: false
3773
+ };
3774
+ let url;
3775
+ try {
3776
+ url = URL.createObjectURL(
3777
+ new Blob([a.file.bytes.slice().buffer], {
3778
+ type: a.file.mime
3779
+ })
3780
+ );
3781
+ const link = document.createElement("a");
3782
+ link.href = url;
3783
+ link.download = a.file.filename;
3784
+ link.click();
3785
+ return signal.aborted ? { status: "cancelled" } : {
3786
+ status: "success",
3787
+ delivered: "download-started",
3788
+ mimeTypes: [a.file.mime]
3789
+ };
3790
+ } catch (e) {
3791
+ return signal.aborted ? { status: "cancelled" } : {
3792
+ status: "error",
3793
+ code: "download-failed",
3794
+ message: e instanceof Error ? e.message : "Download failed",
3795
+ retryable: true
3796
+ };
3797
+ } finally {
3798
+ if (url) setTimeout(() => URL.revokeObjectURL(url), 0);
3799
+ }
3800
+ }
3801
+ };
3802
+ }
3803
+ function assertLimit(value, name) {
3804
+ if (value != null && (!Number.isSafeInteger(value) || value < 0)) {
3805
+ throw new ContentTransferError(
3806
+ "invalid-limit",
3807
+ `${name} must be a non-negative safe integer or null`
3808
+ );
3809
+ }
3810
+ }
3811
+ var limitKeys = [
3812
+ "maxRows",
3813
+ "maxStringChars",
3814
+ "maxDepth",
3815
+ "maxArrayItems",
3816
+ "targetTokens"
3817
+ ];
3818
+ function resolveTransferPreferences(provider = {}, menu = {}, sourceLimits = {}) {
3819
+ const limits = {
3820
+ maxRows: null,
3821
+ maxStringChars: null,
3822
+ maxDepth: null,
3823
+ maxArrayItems: null,
3824
+ targetTokens: null
3825
+ };
3826
+ for (const key of limitKeys) {
3827
+ const candidates = [
3828
+ provider.limits?.[key],
3829
+ menu.limits?.[key],
3830
+ sourceLimits[key]
3831
+ ];
3832
+ candidates.forEach((value) => assertLimit(value, key));
3833
+ const finite = candidates.filter((value) => value != null);
3834
+ limits[key] = finite.length ? Math.min(...finite) : null;
3835
+ }
3836
+ return deepFreeze({
3837
+ initialFormat: menu.initialFormat ?? provider.initialFormat ?? "plain",
3838
+ initialPreset: menu.initialPreset ?? provider.initialPreset ?? "full",
3839
+ limits
3840
+ });
3841
+ }
3842
+ function cloneTransferRegistration(value, path = "registration", seen = /* @__PURE__ */ new WeakSet()) {
3843
+ if (value === null || typeof value !== "object" && typeof value !== "function")
3844
+ return value;
3845
+ if (typeof value === "function") return value;
3846
+ if (seen.has(value))
3847
+ throw new ContentTransferError(
3848
+ "unsupported-registration-metadata",
3849
+ "Circular transfer registration metadata is unsupported",
3850
+ path
3851
+ );
3852
+ seen.add(value);
3853
+ if (Array.isArray(value)) {
3854
+ const copy2 = value.map(
3855
+ (item, index) => cloneTransferRegistration(item, `${path}/${index}`, seen)
3856
+ );
3857
+ seen.delete(value);
3858
+ return Object.freeze(copy2);
3859
+ }
3860
+ const prototype = Object.getPrototypeOf(value);
3861
+ if (prototype !== Object.prototype && prototype !== null)
3862
+ throw new ContentTransferError(
3863
+ "unsupported-registration-metadata",
3864
+ "Transfer registration metadata must use plain objects and arrays",
3865
+ path
3866
+ );
3867
+ const copy = Object.create(prototype);
3868
+ for (const key of Reflect.ownKeys(value)) {
3869
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
3870
+ if (!("value" in descriptor))
3871
+ throw new ContentTransferError(
3872
+ "unsupported-registration-metadata",
3873
+ "Transfer registration metadata cannot use accessors",
3874
+ `${path}/${String(key)}`
3875
+ );
3876
+ Object.defineProperty(copy, key, {
3877
+ value: cloneTransferRegistration(
3878
+ descriptor.value,
3879
+ `${path}/${String(key)}`,
3880
+ seen
3881
+ ),
3882
+ enumerable: descriptor.enumerable === true,
3883
+ writable: false,
3884
+ configurable: false
3885
+ });
3886
+ }
3887
+ seen.delete(value);
3888
+ return Object.freeze(copy);
3889
+ }
3890
+ function resolveTransferRegistry(...groups) {
3891
+ const ids = /* @__PURE__ */ new Set();
3892
+ const result = [];
3893
+ for (const group of groups)
3894
+ for (const item of group) {
3895
+ const copy = cloneTransferRegistration(item);
3896
+ if (!copy.id.trim() || ids.has(copy.id))
3897
+ throw new ContentTransferError(
3898
+ "duplicate-registration",
3899
+ `Transfer id ${JSON.stringify(copy.id)} is empty or registered more than once`
3900
+ );
3901
+ ids.add(copy.id);
3902
+ result.push(copy);
3903
+ }
3904
+ return Object.freeze(result);
3905
+ }
3906
+ function createSurfaceTransferHandle(options) {
3907
+ const declarations = resolveTransferRegistry(
3908
+ options.manifest.values.map((value) => ({ ...value, id: value.name }))
3909
+ );
3910
+ return {
3911
+ instanceId: options.instanceId,
3912
+ surfaceName: options.manifest.surfaceName,
3913
+ isMounted: options.isMounted,
3914
+ async capture(signal) {
3915
+ stop(signal);
3916
+ if (!options.isMounted())
3917
+ throw new ContentTransferError(
3918
+ "surface-unmounted",
3919
+ "The captured surface is no longer mounted"
3920
+ );
3921
+ const revisionBefore = options.getRevision?.();
3922
+ const scope = await options.getScope();
3923
+ stop(signal);
3924
+ if (!options.isMounted())
3925
+ throw new ContentTransferError(
3926
+ "surface-unmounted",
3927
+ "The surface closed during capture"
3928
+ );
3929
+ if (revisionBefore !== void 0 && options.getRevision?.() !== revisionBefore)
3930
+ throw new ContentTransferError(
3931
+ "surface-changed",
3932
+ "The surface changed during capture; capture again"
3933
+ );
3934
+ const value = {};
3935
+ for (const declaration of declarations) {
3936
+ if (Object.hasOwn(scope, declaration.name) && scope[declaration.name] !== void 0) {
3937
+ Object.defineProperty(value, declaration.name, {
3938
+ value: cloneSurfaceValue(
3939
+ scope[declaration.name],
3940
+ `/${enc(declaration.name)}`
3941
+ ),
3942
+ enumerable: true,
3943
+ writable: true,
3944
+ configurable: true
3945
+ });
3946
+ }
3947
+ }
3948
+ return directSource(
3949
+ { kind: "json", value },
3950
+ {
3951
+ sourceId: options.instanceId,
3952
+ revision: revisionBefore ?? uid(),
3953
+ label: options.manifest.label ?? options.manifest.surfaceName,
3954
+ unsavedChanges: options.unsavedChanges?.() ?? false,
3955
+ sections: declarations.filter((d) => Object.hasOwn(value, d.name)).map((d) => ({
3956
+ id: d.name,
3957
+ label: d.label,
3958
+ path: `/${enc(d.name)}`,
3959
+ includedByDefault: d.includedByDefault ?? true
3960
+ })),
3961
+ projection: {
3962
+ rules: [
3963
+ ...options.projection?.rules ?? [],
3964
+ ...declarations.map((d) => ({
3965
+ target: "payload",
3966
+ path: `/${enc(d.name)}`,
3967
+ exportable: d.exportable ?? true,
3968
+ classification: d.classification ?? "ordinary"
3969
+ }))
3970
+ ]
3971
+ },
3972
+ ...options.limits ? { limits: options.limits } : {}
3973
+ }
3974
+ );
3975
+ }
3976
+ };
3977
+ }
3978
+ function limitJson(value, limits, omissions, path = "", depth = 0) {
3979
+ if (limits.maxDepth != null && depth > limits.maxDepth) {
3980
+ omissions.push({ path, reason: "truncated" });
3981
+ return null;
3982
+ }
3983
+ if (typeof value === "string" && limits.maxStringChars != null && Array.from(value).length > limits.maxStringChars) {
3984
+ const chars = Array.from(value);
3985
+ omissions.push({
3986
+ path,
3987
+ reason: "truncated",
3988
+ count: chars.length - limits.maxStringChars
3989
+ });
3990
+ return chars.slice(0, limits.maxStringChars).join("");
3991
+ }
3992
+ if (Array.isArray(value)) {
3993
+ const count = Math.min(value.length, limits.maxArrayItems ?? value.length);
3994
+ if (count < value.length)
3995
+ omissions.push({
3996
+ path,
3997
+ reason: "truncated",
3998
+ count: value.length - count
3999
+ });
4000
+ return value.slice(0, count).map(
4001
+ (item, index) => limitJson(item, limits, omissions, `${path}/${index}`, depth + 1)
4002
+ );
4003
+ }
4004
+ if (value && typeof value === "object")
4005
+ return Object.fromEntries(
4006
+ Object.entries(value).map(([key, item]) => [
4007
+ key,
4008
+ limitJson(item, limits, omissions, `${path}/${enc(key)}`, depth + 1)
4009
+ ])
4010
+ );
4011
+ return value;
4012
+ }
4013
+ function limitPayload(payload, limits, omissions) {
4014
+ limitKeys.forEach((key) => assertLimit(limits[key], key));
4015
+ if (payload.kind === "rows") {
4016
+ const count = Math.min(
4017
+ payload.rows.length,
4018
+ limits.maxRows ?? payload.rows.length
4019
+ );
4020
+ if (count < payload.rows.length)
4021
+ omissions.push({
4022
+ path: "/rows",
4023
+ reason: "truncated",
4024
+ count: payload.rows.length - count
4025
+ });
4026
+ return {
4027
+ ...payload,
4028
+ rows: payload.rows.slice(0, count).map(
4029
+ (row, index) => limitJson(row, limits, omissions, `/rows/${index}`)
4030
+ )
4031
+ };
4032
+ }
4033
+ if (payload.kind === "json" || payload.kind === "registered")
4034
+ return { ...payload, value: limitJson(payload.value, limits, omissions) };
4035
+ return {
4036
+ ...payload,
4037
+ text: limitJson(payload.text, limits, omissions)
4038
+ };
4039
+ }
4040
+ function applyTransferLimits(draft, limits) {
4041
+ const omissions = [];
4042
+ const payload = limitPayload(draft.payload, limits, omissions);
4043
+ return omissions.length ? revise(draft, payload, omissions, "Applied preparation limits") : draft;
4044
+ }
2841
4045
  //# sourceMappingURL=index.cjs.map