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