buckyos 0.7.205 → 0.7.208

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.
Files changed (94) hide show
  1. package/cli/dist/cli.mjs +1 -1
  2. package/cli/dist/cli.mjs.map +1 -1
  3. package/cli/version.ts +1 -1
  4. package/dist/{aiws_write-eeea8ed3.js → aiws_write-825bb6ba.js} +3 -3
  5. package/dist/aiws_write-825bb6ba.js.map +1 -0
  6. package/dist/{aiws_write-47c90e76.mjs → aiws_write-83ddc6cc.mjs} +30 -2
  7. package/dist/aiws_write-83ddc6cc.mjs.map +1 -0
  8. package/dist/app-frame.cjs +1 -1
  9. package/dist/app-frame.cjs.map +1 -1
  10. package/dist/app-frame.d.ts +221 -2
  11. package/dist/app-frame.d.ts.map +1 -1
  12. package/dist/app-frame.mjs +531 -15
  13. package/dist/app-frame.mjs.map +1 -1
  14. package/dist/browser.cjs +1 -1
  15. package/dist/browser.cjs.map +1 -1
  16. package/dist/browser.d.ts +4 -0
  17. package/dist/browser.d.ts.map +1 -1
  18. package/dist/browser.mjs +11 -6
  19. package/dist/browser.mjs.map +1 -1
  20. package/dist/content.cjs +1 -1
  21. package/dist/content.cjs.map +1 -1
  22. package/dist/content.d.ts +2 -0
  23. package/dist/content.d.ts.map +1 -1
  24. package/dist/content.mjs +14 -7
  25. package/dist/content.mjs.map +1 -1
  26. package/dist/{content_objid-0a095cbd.mjs → content_objid-76434848.mjs} +2 -2
  27. package/dist/{content_objid-0a095cbd.mjs.map → content_objid-76434848.mjs.map} +1 -1
  28. package/dist/{content_objid-4742308a.js → content_objid-addf9e2b.js} +2 -2
  29. package/dist/{content_objid-4742308a.js.map → content_objid-addf9e2b.js.map} +1 -1
  30. package/dist/index.cjs +1 -1
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.ts +4 -0
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.mjs +11 -6
  35. package/dist/index.mjs.map +1 -1
  36. package/dist/internal/html_tokens.d.ts +13 -0
  37. package/dist/internal/html_tokens.d.ts.map +1 -0
  38. package/dist/node.cjs +1 -1
  39. package/dist/node.cjs.map +1 -1
  40. package/dist/node.d.ts +4 -0
  41. package/dist/node.d.ts.map +1 -1
  42. package/dist/node.mjs +10 -5
  43. package/dist/node.mjs.map +1 -1
  44. package/dist/sdk_core.d.ts +18 -0
  45. package/dist/sdk_core.d.ts.map +1 -1
  46. package/dist/{site_manager-91b4d899.mjs → site_manager-604ee369.mjs} +207 -141
  47. package/dist/site_manager-604ee369.mjs.map +1 -0
  48. package/dist/site_manager-70710895.js +2 -0
  49. package/dist/site_manager-70710895.js.map +1 -0
  50. package/dist/transfer.cjs +2 -0
  51. package/dist/transfer.cjs.map +1 -0
  52. package/dist/transfer.d.ts +148 -0
  53. package/dist/transfer.d.ts.map +1 -0
  54. package/dist/transfer.mjs +655 -0
  55. package/dist/transfer.mjs.map +1 -0
  56. package/dist/user_preferences-1d49850a.mjs +158 -0
  57. package/dist/user_preferences-1d49850a.mjs.map +1 -0
  58. package/dist/user_preferences-7288c989.js +2 -0
  59. package/dist/user_preferences-7288c989.js.map +1 -0
  60. package/dist/user_preferences.d.ts +50 -0
  61. package/dist/user_preferences.d.ts.map +1 -0
  62. package/dist/xllm/core/loop.d.ts.map +1 -1
  63. package/dist/xllm/core/types.d.ts +0 -2
  64. package/dist/xllm/core/types.d.ts.map +1 -1
  65. package/dist/xllm/hosts/deno/native_runtime.d.ts.map +1 -1
  66. package/dist/xllm/hosts/deno/native_tools.d.ts +2 -1
  67. package/dist/xllm/hosts/deno/native_tools.d.ts.map +1 -1
  68. package/dist/xllm/index.d.ts +3 -2
  69. package/dist/xllm/index.d.ts.map +1 -1
  70. package/dist/xllm/runtime/hints.d.ts +9 -4
  71. package/dist/xllm/runtime/hints.d.ts.map +1 -1
  72. package/dist/xllm/runtime/step_renderer.d.ts +4 -4
  73. package/dist/xllm/runtime/step_renderer.d.ts.map +1 -1
  74. package/dist/xllm/runtime/text_budget.d.ts +5 -0
  75. package/dist/xllm/runtime/text_budget.d.ts.map +1 -0
  76. package/dist/xllm/runtime/tool_result.d.ts +14 -1
  77. package/dist/xllm/runtime/tool_result.d.ts.map +1 -1
  78. package/dist/xllm.cjs +1 -1
  79. package/dist/xllm.cjs.map +1 -1
  80. package/dist/xllm.mjs +35 -29
  81. package/dist/xllm_deno.cjs +1 -1
  82. package/dist/xllm_deno.cjs.map +1 -1
  83. package/dist/xllm_deno.mjs +123 -42
  84. package/dist/xllm_deno.mjs.map +1 -1
  85. package/package.json +6 -1
  86. package/dist/aiws_write-47c90e76.mjs.map +0 -1
  87. package/dist/aiws_write-eeea8ed3.js.map +0 -1
  88. package/dist/runtime_env-39e4df98.mjs +0 -44
  89. package/dist/runtime_env-39e4df98.mjs.map +0 -1
  90. package/dist/runtime_env-6396e1eb.js +0 -2
  91. package/dist/runtime_env-6396e1eb.js.map +0 -1
  92. package/dist/site_manager-716a2cf5.js +0 -2
  93. package/dist/site_manager-716a2cf5.js.map +0 -1
  94. package/dist/site_manager-91b4d899.mjs.map +0 -1
@@ -1,6 +1,7 @@
1
- import { SystemDialogError, isOpenRequest, readContentHints, readSelectDialogResult, systemOpenUrl, SELECT_DIALOG_PATH, isTransferableRef, isTransferableSession, SYSTEM_DIALOG_ERROR_CODES } from "./content.mjs";
1
+ import { readZoneContent, SystemDialogError, isOpenRequest, readContentHints, readSelectDialogResult, systemOpenUrl, SELECT_DIALOG_PATH, isTransferableRef, isTransferableSession, SYSTEM_DIALOG_ERROR_CODES } from "./content.mjs";
2
2
  import { readAppOpenRequest, systemOpenAppUrl } from "./open-app.mjs";
3
- import { g as getBuckyApi } from "./runtime_env-39e4df98.mjs";
3
+ import { g as getBuckyApi, s as setFrameAppearance } from "./user_preferences-1d49850a.mjs";
4
+ import { MAX_CONTENT_REFS, CONTENT_REFS_FORMAT, readContentRefs, newOfferId } from "./transfer.mjs";
4
5
  import "./object_url-20e94b67.mjs";
5
6
  import "./ndn_types-0fac2499.mjs";
6
7
  const dialogErrorCode = (value) => SYSTEM_DIALOG_ERROR_CODES.includes(value) ? value : "protocol";
@@ -37,15 +38,15 @@ function readHeader(p) {
37
38
  }
38
39
  function windowTransport(peer, origin) {
39
40
  return {
40
- post: (message) => {
41
+ post: (message, transfer) => {
41
42
  var _a;
42
- return (_a = peer()) == null ? void 0 : _a.postMessage(message, origin);
43
+ return (_a = peer()) == null ? void 0 : _a.postMessage(message, origin, transfer ?? []);
43
44
  },
44
45
  onMessage: (cb) => {
45
46
  const own = window;
46
47
  const listener = (event) => {
47
48
  if (event.source === peer() && event.origin === origin)
48
- cb(event.data);
49
+ cb(event.data, event.ports);
49
50
  };
50
51
  own.addEventListener("message", listener);
51
52
  return () => own.removeEventListener("message", listener);
@@ -68,6 +69,219 @@ const isMessage = (value) => {
68
69
  const v = value;
69
70
  return v.protocol === "buckyos.app-frame" && v.version === 1 && typeof v.type === "string" && !!v.payload && typeof v.payload === "object";
70
71
  };
72
+ const TRANSFER_CAPABILITY = "transfer.v1";
73
+ const TRANSFER_ERROR_CODES = ["unsupported", "stale", "denied"];
74
+ class TransferError extends Error {
75
+ constructor(code, message) {
76
+ super(message ?? `Transfer: ${code}`);
77
+ this.code = code;
78
+ this.name = "TransferError";
79
+ }
80
+ }
81
+ const TRANSFER_ID = /^[A-Za-z0-9_-]{16,128}$/;
82
+ const DOCUMENT_ID = /^[A-Za-z0-9_-]{8,128}$/;
83
+ const FORMAT_NAME = /^(?:files|[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126})$/;
84
+ const ITEM_KINDS = ["zone-file", "zone-folder", "local-file", "text", "object"];
85
+ const OPERATIONS = ["copy", "move", "link"];
86
+ const ITEM_STATUSES = ["done", "accepted", "skipped", "failed", "cancelled"];
87
+ const MAX_FORMATS = 32;
88
+ const MAX_INLINE = 1024 * 1024;
89
+ const MAX_STRING_VALUE = 16 * 1024 * 1024;
90
+ const TRANSFER_TIMEOUT = { offer: 5e3, probe: 1500, read: 1e4, deliver: 15e3, status: 3e3 };
91
+ const isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
92
+ const isTransferId = (v) => typeof v === "string" && TRANSFER_ID.test(v);
93
+ const isItemKey = (v) => typeof v === "string" && /^(0|[1-9]\d{0,5})$/.test(v);
94
+ const isFormat = (v) => typeof v === "string" && FORMAT_NAME.test(v);
95
+ const readOperations = (v) => {
96
+ if (!Array.isArray(v) || !v.length || v.length > 3 || !v.every((o) => OPERATIONS.includes(o)))
97
+ return void 0;
98
+ return [...new Set(v)];
99
+ };
100
+ const readFormats = (v) => Array.isArray(v) && v.length && v.length <= MAX_FORMATS && v.every(isFormat) ? [...new Set(v)] : void 0;
101
+ const readPoint = (v) => {
102
+ if (v === "focus")
103
+ return "focus";
104
+ return isObject(v) && Number.isFinite(v.x) && Number.isFinite(v.y) ? { x: v.x, y: v.y } : void 0;
105
+ };
106
+ const readStringMap = (v, maxEntries, maxLength) => {
107
+ if (!isObject(v))
108
+ return void 0;
109
+ const entries = Object.entries(v);
110
+ if (entries.length > maxEntries || !entries.every(([key, value]) => key.length <= 128 && typeof value === "string" && value.length <= maxLength))
111
+ return void 0;
112
+ return Object.fromEntries(entries);
113
+ };
114
+ const transferCode = (v) => TRANSFER_ERROR_CODES.includes(v) ? v : "unsupported";
115
+ function readTransferOffer(value) {
116
+ if (!isObject(value) || !isTransferId(value.offerId) || !["copy", "cut", "drag"].includes(value.purpose))
117
+ return void 0;
118
+ if (!Number.isSafeInteger(value.generation) || value.generation < 0)
119
+ return void 0;
120
+ if (!Array.isArray(value.items) || !value.items.length || value.items.length > MAX_CONTENT_REFS)
121
+ return void 0;
122
+ let inlineSize = 0;
123
+ const items = [];
124
+ for (const raw of value.items) {
125
+ if (!isObject(raw) || !ITEM_KINDS.includes(raw.kind))
126
+ return void 0;
127
+ const formats = readFormats(raw.formats), operations = readOperations(raw.operations);
128
+ if (!formats || !operations)
129
+ return void 0;
130
+ const item = { kind: raw.kind, formats, operations };
131
+ if (raw.inline !== void 0) {
132
+ const inline = readStringMap(raw.inline, MAX_FORMATS, MAX_INLINE);
133
+ if (!inline || !Object.keys(inline).every((f) => formats.includes(f)))
134
+ return void 0;
135
+ inlineSize += Object.values(inline).reduce((n, s) => n + s.length, 0);
136
+ if (inlineSize > MAX_INLINE)
137
+ return void 0;
138
+ item.inline = inline;
139
+ }
140
+ items.push(item);
141
+ }
142
+ const offer = { offerId: value.offerId, purpose: value.purpose, generation: value.generation, items };
143
+ if (value.scope !== void 0) {
144
+ const scope = readStringMap(value.scope, 8, 512);
145
+ if (!scope)
146
+ return void 0;
147
+ offer.scope = scope;
148
+ }
149
+ return offer;
150
+ }
151
+ function readProbeItems(value) {
152
+ if (!Array.isArray(value) || !value.length || value.length > MAX_CONTENT_REFS)
153
+ return void 0;
154
+ const items = [];
155
+ for (const raw of value) {
156
+ if (!isObject(raw) || !isItemKey(raw.itemKey) || !ITEM_KINDS.includes(raw.kind))
157
+ return void 0;
158
+ const formats = readFormats(raw.formats), operations = readOperations(raw.operations);
159
+ if (!formats || !operations)
160
+ return void 0;
161
+ items.push({ itemKey: raw.itemKey, kind: raw.kind, formats, operations });
162
+ }
163
+ return items;
164
+ }
165
+ function readTransferProbe(value) {
166
+ if (!isObject(value) || !isTransferId(value.operationId) || !Number.isSafeInteger(value.seq))
167
+ return void 0;
168
+ const items = readProbeItems(value.items), at = readPoint(value.at);
169
+ return items && at ? { operationId: value.operationId, seq: value.seq, items, at } : void 0;
170
+ }
171
+ function readTransferProbeAnswer(value, probe) {
172
+ if (!isObject(value) || typeof value.targetId !== "string" || !value.targetId || value.targetId.length > 256 || !Array.isArray(value.accept))
173
+ return null;
174
+ const shown = new Map(probe.items.map((item) => [item.itemKey, item]));
175
+ const seen = /* @__PURE__ */ new Set();
176
+ const accept = [];
177
+ for (const raw of value.accept) {
178
+ if (!isObject(raw) || typeof raw.itemKey !== "string" || seen.has(raw.itemKey))
179
+ continue;
180
+ const item = shown.get(raw.itemKey);
181
+ if (!item || !item.formats.includes(raw.format) || !item.operations.includes(raw.operation))
182
+ continue;
183
+ seen.add(raw.itemKey);
184
+ accept.push({ itemKey: raw.itemKey, format: raw.format, operation: raw.operation });
185
+ }
186
+ if (!accept.length)
187
+ return null;
188
+ return { targetId: value.targetId, accept, action: typeof value.action === "string" ? value.action.slice(0, 200) : "" };
189
+ }
190
+ function readTransferReadRequest(value) {
191
+ if (!isObject(value) || !isTransferId(value.operationId) || !isTransferId(value.offerId) || !Number.isSafeInteger(value.generation))
192
+ return void 0;
193
+ if (!Array.isArray(value.items) || !value.items.length || value.items.length > MAX_CONTENT_REFS)
194
+ return void 0;
195
+ const items = [];
196
+ for (const raw of value.items) {
197
+ if (!isObject(raw) || !isItemKey(raw.itemKey) || !isFormat(raw.format))
198
+ return void 0;
199
+ items.push({ itemKey: raw.itemKey, format: raw.format });
200
+ }
201
+ return { operationId: value.operationId, offerId: value.offerId, generation: value.generation, items };
202
+ }
203
+ const isFileValue = (v) => typeof File !== "undefined" && v instanceof File;
204
+ const isBlobValue = (v) => typeof Blob !== "undefined" && v instanceof Blob;
205
+ function readTransferValue(format, value) {
206
+ if (format === CONTENT_REFS_FORMAT) {
207
+ if (typeof value === "string") {
208
+ const items = readContentRefs(value);
209
+ return (items == null ? void 0 : items.length) === 1 ? items[0] : void 0;
210
+ }
211
+ return readZoneContent(value);
212
+ }
213
+ if (format === "files")
214
+ return isFileValue(value) ? value : void 0;
215
+ if (typeof value === "string")
216
+ return value.length <= MAX_STRING_VALUE ? value : void 0;
217
+ return isBlobValue(value) && !format.startsWith("text/") ? value : void 0;
218
+ }
219
+ function readDeliveryItems(value) {
220
+ if (!Array.isArray(value) || !value.length || value.length > MAX_CONTENT_REFS)
221
+ return void 0;
222
+ const items = [];
223
+ for (const raw of value) {
224
+ if (!isObject(raw) || !isItemKey(raw.itemKey) || !isFormat(raw.format))
225
+ return void 0;
226
+ const clean = readTransferValue(raw.format, raw.value);
227
+ if (clean === void 0)
228
+ return void 0;
229
+ items.push({ itemKey: raw.itemKey, format: raw.format, value: clean });
230
+ }
231
+ return items;
232
+ }
233
+ function readTransferDelivery(value) {
234
+ if (!isObject(value) || !isTransferId(value.operationId) || typeof value.targetId !== "string" || !value.targetId || value.targetId.length > 256)
235
+ return void 0;
236
+ if (!OPERATIONS.includes(value.operation))
237
+ return void 0;
238
+ const at = readPoint(value.at), items = readDeliveryItems(value.items);
239
+ return at && items ? { operationId: value.operationId, targetId: value.targetId, operation: value.operation, at, items } : void 0;
240
+ }
241
+ function readTransferDeliveryResult(value, delivered) {
242
+ if (!isObject(value) || !["done", "accepted", "cancelled", "failed"].includes(value.status) || !Array.isArray(value.items))
243
+ return void 0;
244
+ const given = /* @__PURE__ */ new Map();
245
+ for (const raw of value.items) {
246
+ if (!isObject(raw) || typeof raw.itemKey !== "string" || !ITEM_STATUSES.includes(raw.status))
247
+ continue;
248
+ given.set(raw.itemKey, { status: raw.status, ...typeof raw.error === "string" ? { error: raw.error.slice(0, 200) } : {} });
249
+ }
250
+ return {
251
+ status: value.status,
252
+ items: delivered.map(({ itemKey }) => ({ itemKey, ...given.get(itemKey) ?? { status: "failed", error: "no_result" } }))
253
+ };
254
+ }
255
+ function readTransferReadValues(value, request, options) {
256
+ const given = /* @__PURE__ */ new Map();
257
+ if (Array.isArray(value))
258
+ for (const raw of value) {
259
+ if (isObject(raw) && typeof raw.itemKey === "string" && typeof raw.format === "string")
260
+ given.set(`${raw.itemKey}
261
+ ${raw.format}`, raw);
262
+ }
263
+ return request.items.map(({ itemKey, format }) => {
264
+ const raw = given.get(`${itemKey}
265
+ ${format}`);
266
+ if (!raw)
267
+ return { itemKey, format, error: "failed" };
268
+ if ("error" in raw && raw.error !== void 0)
269
+ return { itemKey, format, error: raw.error === "failed" ? "failed" : transferCode(raw.error) };
270
+ if (format === "files" && !options.files)
271
+ return { itemKey, format, error: "unsupported" };
272
+ const clean = readTransferValue(format, raw.value);
273
+ return clean === void 0 ? { itemKey, format, error: "failed" } : { itemKey, format, value: clean };
274
+ });
275
+ }
276
+ const portLink = (documentId, port, receive) => {
277
+ var _a;
278
+ port.onmessage = (event) => receive(event.data);
279
+ (_a = port.start) == null ? void 0 : _a.call(port);
280
+ return { documentId, post: (message) => port.postMessage(message), close: () => {
281
+ port.onmessage = null;
282
+ port.close();
283
+ } };
284
+ };
71
285
  const FRAME_NAME_PREFIX = "buckyos.app-frame:";
72
286
  function appFrameName(nonce) {
73
287
  return FRAME_NAME_PREFIX + nonce;
@@ -81,11 +295,17 @@ class AppFrameHost {
81
295
  this.pending = /* @__PURE__ */ new Map();
82
296
  this.opens = /* @__PURE__ */ new Map();
83
297
  this.dialogOpen = false;
298
+ this.transferPending = /* @__PURE__ */ new Map();
84
299
  this.callbacks = options;
85
300
  this.framed = !options.transport;
86
301
  this.init = options.transport ? { ...options.init, nonce: "" } : options.init;
87
302
  this.channel = options.transport ?? windowTransport(options.target, options.origin);
88
- this.detach = this.channel.onMessage((message) => this.receive(message));
303
+ this.detach = this.channel.onMessage((message, ports) => this.receive(message, ports));
304
+ }
305
+ /** The App document whose transfer link is bound (`transfer.v1`); undefined when none is. */
306
+ get transferDocument() {
307
+ var _a;
308
+ return (_a = this.transferLink) == null ? void 0 : _a.documentId;
89
309
  }
90
310
  limited(type) {
91
311
  const recent = (this.opens.get(type) ?? []).filter((t) => t > Date.now() - 1e4);
@@ -129,7 +349,7 @@ class AppFrameHost {
129
349
  this.dialogOpen = false;
130
350
  }
131
351
  }
132
- receive(m) {
352
+ receive(m, ports) {
133
353
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
134
354
  if (!isMessage(m))
135
355
  return;
@@ -143,10 +363,14 @@ class AppFrameHost {
143
363
  } else {
144
364
  if (typeof p.nonce !== "string" || !p.nonce || p.nonce.length > 128)
145
365
  return;
146
- if (p.nonce !== this.init.nonce)
366
+ if (p.nonce !== this.init.nonce) {
147
367
  this.failPending("App frame reloaded");
368
+ this.dropTransfer();
369
+ }
148
370
  this.init = { ...this.init, nonce: p.nonce };
149
371
  }
372
+ if (this.transferLink && this.transferLink.documentId !== p.documentId)
373
+ this.dropTransfer();
150
374
  this.ready = true;
151
375
  this.capabilities = p.appCapabilities.filter((c) => typeof c === "string");
152
376
  this.send("frame.init", this.init);
@@ -161,6 +385,15 @@ class AppFrameHost {
161
385
  }
162
386
  if (!this.ready)
163
387
  return;
388
+ if (m.type === "transfer.connect") {
389
+ this.connectTransfer(p, ports);
390
+ return;
391
+ }
392
+ if (m.type.startsWith("transfer.")) {
393
+ if (!this.framed && this.transferLink)
394
+ this.receiveTransfer(m, this.transferLink);
395
+ return;
396
+ }
164
397
  if (m.replyTo) {
165
398
  const pending = this.pending.get(m.replyTo);
166
399
  if (pending && m.type === pending.type + "Result") {
@@ -243,12 +476,132 @@ class AppFrameHost {
243
476
  });
244
477
  this.pending.clear();
245
478
  }
479
+ /** Binds the transfer link of the document that just shook hands: its port (framed) or the bridge. */
480
+ connectTransfer(p, ports) {
481
+ var _a, _b;
482
+ const port = (ports == null ? void 0 : ports.length) === 1 ? ports[0] : void 0;
483
+ const refuse = () => ports == null ? void 0 : ports.forEach((x) => x.close());
484
+ if (!this.init.shellCapabilities.includes(TRANSFER_CAPABILITY) || !this.capabilities.includes(TRANSFER_CAPABILITY))
485
+ return refuse();
486
+ if (typeof p.documentId !== "string" || !DOCUMENT_ID.test(p.documentId) || (this.framed ? !port : !!(ports == null ? void 0 : ports.length)))
487
+ return refuse();
488
+ this.dropTransfer();
489
+ const documentId = p.documentId;
490
+ let link;
491
+ if (port)
492
+ link = portLink(documentId, port, (message) => {
493
+ if (this.transferLink === link)
494
+ this.receiveTransfer(message, link);
495
+ });
496
+ else
497
+ link = { documentId, post: (message) => this.channel.post(message), close: () => {
498
+ } };
499
+ this.transferLink = link;
500
+ (_b = (_a = this.callbacks).onTransferConnect) == null ? void 0 : _b.call(_a, documentId);
501
+ }
502
+ /** Drops the transfer link: every request waiting on it fails `stale`, its offers are void. */
503
+ dropTransfer() {
504
+ var _a, _b;
505
+ const link = this.transferLink;
506
+ if (!link)
507
+ return;
508
+ this.transferLink = void 0;
509
+ link.close();
510
+ this.transferPending.forEach((p) => {
511
+ clearTimeout(p.timer);
512
+ p.reject(new TransferError("stale", "The App document changed"));
513
+ });
514
+ this.transferPending.clear();
515
+ (_b = (_a = this.callbacks).onTransferDisconnect) == null ? void 0 : _b.call(_a, link.documentId);
516
+ }
517
+ receiveTransfer(m, link) {
518
+ var _a, _b;
519
+ if (!isMessage(m))
520
+ return;
521
+ const p = m.payload;
522
+ if (m.replyTo) {
523
+ const pending = this.transferPending.get(m.replyTo);
524
+ if (pending && m.type === pending.type + "Result") {
525
+ clearTimeout(pending.timer);
526
+ this.transferPending.delete(m.replyTo);
527
+ pending.resolve(m.payload);
528
+ }
529
+ return;
530
+ }
531
+ if (m.type === "transfer.offer" && typeof m.id === "string") {
532
+ const id = m.id;
533
+ const reply = (payload) => {
534
+ if (this.transferLink === link)
535
+ link.post(envelope("transfer.offerResult", payload, { replyTo: id }));
536
+ };
537
+ const offer = readTransferOffer(p);
538
+ if (!offer)
539
+ return reply({ ok: false, code: "unsupported" });
540
+ if (!this.callbacks.onTransferOffer)
541
+ return reply({ ok: false, code: "unsupported" });
542
+ void Promise.resolve().then(() => this.callbacks.onTransferOffer(offer, link.documentId)).then((result) => reply(result.ok ? { ok: true } : { ok: false, code: transferCode(result.code) }), () => reply({ ok: false, code: "denied" }));
543
+ return;
544
+ }
545
+ if (m.type === "transfer.cancel" && isTransferId(p.offerId))
546
+ (_b = (_a = this.callbacks).onTransferWithdraw) == null ? void 0 : _b.call(_a, p.offerId, link.documentId);
547
+ }
548
+ transferRequest(type, payload, timeout) {
549
+ const link = this.transferLink;
550
+ if (!this.ready || !link)
551
+ return Promise.reject(new TransferError("stale", "No transfer link"));
552
+ const id = crypto.randomUUID();
553
+ return new Promise((resolve, reject) => {
554
+ const timer = setTimeout(() => {
555
+ this.transferPending.delete(id);
556
+ reject(new TransferError("timeout"));
557
+ }, timeout);
558
+ this.transferPending.set(id, { resolve, reject, timer, type });
559
+ link.post(envelope(type, payload, { id }));
560
+ }).then((reply) => {
561
+ const r = isObject(reply) ? reply : {};
562
+ if (r.ok !== true)
563
+ throw new TransferError(transferCode(r.code));
564
+ return r;
565
+ });
566
+ }
567
+ /** Asks the App what it would do with these items at a point of its page or at its focus; null when nothing. */
568
+ async transferProbe(probe, timeout = TRANSFER_TIMEOUT.probe) {
569
+ const r = await this.transferRequest("transfer.probe", probe, timeout);
570
+ return r.answer === null ? null : readTransferProbeAnswer(r.answer, probe);
571
+ }
572
+ /** Reads representations of a selection the App offered. Each value is checked by its format. */
573
+ async transferRead(read, timeout = TRANSFER_TIMEOUT.read) {
574
+ const r = await this.transferRequest("transfer.read", read, timeout);
575
+ return readTransferReadValues(r.items, read, { files: this.framed });
576
+ }
577
+ /** Hands the chosen representations to the App; a retry with the same `operationId` must not commit twice. */
578
+ async transferDeliver(delivery, timeout = TRANSFER_TIMEOUT.deliver) {
579
+ if (!this.framed && delivery.items.some((item) => item.format === "files"))
580
+ throw new TransferError("unsupported", "Local files cannot cross the bridge");
581
+ const r = await this.transferRequest("transfer.deliver", delivery, timeout);
582
+ const result = readTransferDeliveryResult(r.result, delivery.items);
583
+ if (!result)
584
+ throw new TransferError("unsupported", "Invalid delivery result");
585
+ return result;
586
+ }
587
+ /** The final result of a delivery, by its `operationId`; null when the App does not know it. */
588
+ async transferStatus(operationId, delivered, timeout = TRANSFER_TIMEOUT.status) {
589
+ const r = await this.transferRequest("transfer.status", { operationId }, timeout);
590
+ return r.result === null ? null : readTransferDeliveryResult(r.result, delivered) ?? null;
591
+ }
592
+ /** Tells the App an operation it took part in was dropped before it committed. */
593
+ transferCancel(operationId) {
594
+ var _a;
595
+ (_a = this.transferLink) == null ? void 0 : _a.post(envelope("transfer.cancel", { operationId }));
596
+ }
246
597
  dispose() {
247
598
  this.detach();
248
599
  this.failPending("App frame disposed");
600
+ this.dropTransfer();
249
601
  this.ready = false;
250
602
  }
251
603
  }
604
+ const DELIVERY_MEMORY = 64;
252
605
  function embedderOrigin(accept) {
253
606
  var _a;
254
607
  if (window.parent === window)
@@ -280,6 +633,10 @@ class AppFrameClient {
280
633
  this.header = {};
281
634
  this.dialogs = /* @__PURE__ */ new Map();
282
635
  this.appOpens = /* @__PURE__ */ new Map();
636
+ this.documentId = newOfferId();
637
+ this.transferPending = /* @__PURE__ */ new Map();
638
+ this.deliveries = /* @__PURE__ */ new Map();
639
+ this.generation = 0;
283
640
  const origin = new URL(options.shellOrigin).origin;
284
641
  const bridge = window.parent === window ? getBuckyApi() : void 0;
285
642
  this.native = !!bridge;
@@ -293,8 +650,9 @@ class AppFrameClient {
293
650
  const hello = () => this.channel.post(envelope("frame.hello", { nonce: this.nonce, appCapabilities: [
294
651
  ...options.onOpen ? ["open"] : [],
295
652
  ...options.onBeforeClose ? ["beforeClose"] : [],
296
- ...options.onBack ? ["back"] : []
297
- ] }));
653
+ ...options.onBack ? ["back"] : [],
654
+ ...options.transfer ? [TRANSFER_CAPABILITY] : []
655
+ ], ...options.transfer ? { documentId: this.documentId } : {} }));
298
656
  hello();
299
657
  this.helloTimer = setInterval(hello, 250);
300
658
  this.helloDeadline = setTimeout(() => clearInterval(this.helloTimer), bridge ? 1e4 : 1500);
@@ -311,11 +669,18 @@ class AppFrameClient {
311
669
  clearInterval(this.helloTimer);
312
670
  clearTimeout(this.helloDeadline);
313
671
  this.init = p;
672
+ this.showAppearance({ theme: this.init.theme.mode === "dark" ? "dark" : "light", accent: this.init.theme.accent ?? null, locale: this.init.locale });
314
673
  this.title = void 0;
315
674
  this.focused = void 0;
316
675
  if (Object.keys(this.header).length)
317
676
  this.send("header.set", this.header);
318
677
  (_b = (_a = this.options).onInit) == null ? void 0 : _b.call(_a, this.init);
678
+ this.connectTransfer();
679
+ return;
680
+ }
681
+ if (m.type.startsWith("transfer.")) {
682
+ if (this.native && this.transferLink)
683
+ void this.receiveTransfer(m, this.transferLink);
319
684
  return;
320
685
  }
321
686
  if (!this.init)
@@ -354,10 +719,14 @@ class AppFrameClient {
354
719
  reply({ decision: await ((_i = (_h = this.options).onBeforeClose) == null ? void 0 : _i.call(_h, p.reason)) ?? "allow" });
355
720
  if (m.type === "frame.back")
356
721
  reply({ handled: await ((_k = (_j = this.options).onBack) == null ? void 0 : _k.call(_j)) ?? false });
357
- if (m.type === "frame.themeChanged" && (p.mode === "dark" || p.mode === "light"))
722
+ if (m.type === "frame.themeChanged" && (p.mode === "dark" || p.mode === "light")) {
723
+ this.showAppearance({ ...this.appearance, theme: p.mode, accent: typeof p.accent === "string" ? p.accent : null });
358
724
  (_m = (_l = this.options).onTheme) == null ? void 0 : _m.call(_l, p);
359
- if (m.type === "frame.localeChanged" && typeof p.locale === "string")
725
+ }
726
+ if (m.type === "frame.localeChanged" && typeof p.locale === "string") {
727
+ this.showAppearance({ ...this.appearance, locale: p.locale });
360
728
  (_o = (_n = this.options).onLocale) == null ? void 0 : _o.call(_n, p.locale);
729
+ }
361
730
  if (m.type === "frame.focusChanged" && this.focused !== (p.focused === true)) {
362
731
  this.focused = p.focused === true;
363
732
  (_q = (_p = this.options).onFocus) == null ? void 0 : _q.call(_p, this.focused);
@@ -462,15 +831,152 @@ class AppFrameClient {
462
831
  abort.abort();
463
832
  return openSelectEmbed(this.options.systemOrigin, params, { ...options, signal: abort.signal });
464
833
  }
465
- dispose() {
834
+ /** Whether the Shell takes offers from this document (`transfer.v1` on both sides, link connected). */
835
+ get transferAvailable() {
836
+ return !!this.transferLink;
837
+ }
838
+ /** Once per document, after the first `frame.init` that lists `transfer.v1`: one port, to the exact Shell origin. */
839
+ connectTransfer() {
840
+ var _a, _b, _c;
841
+ if (!this.options.transfer || this.transferLink || !((_a = this.init) == null ? void 0 : _a.shellCapabilities.includes(TRANSFER_CAPABILITY)))
842
+ return;
843
+ let link;
844
+ if (this.native) {
845
+ link = { documentId: this.documentId, post: (message) => this.channel.post(message), close: () => {
846
+ } };
847
+ this.channel.post(envelope("transfer.connect", { documentId: this.documentId }));
848
+ } else {
849
+ const channel = new MessageChannel();
850
+ link = portLink(this.documentId, channel.port1, (message) => {
851
+ void this.receiveTransfer(message, link);
852
+ });
853
+ this.channel.post(envelope("transfer.connect", { documentId: this.documentId }), [channel.port2]);
854
+ }
855
+ this.transferLink = link;
856
+ try {
857
+ (_c = (_b = this.options.transfer).onAvailable) == null ? void 0 : _c.call(_b, true);
858
+ } catch {
859
+ }
860
+ }
861
+ async receiveTransfer(m, link) {
466
862
  var _a;
863
+ if (!isMessage(m) || this.transferLink !== link)
864
+ return;
865
+ const p = m.payload;
866
+ if (m.replyTo) {
867
+ const pending = this.transferPending.get(m.replyTo);
868
+ if (pending && m.type === "transfer.offerResult") {
869
+ clearTimeout(pending.timer);
870
+ this.transferPending.delete(m.replyTo);
871
+ pending.resolve(m.payload);
872
+ }
873
+ return;
874
+ }
875
+ const handlers = this.options.transfer ?? {};
876
+ if (m.type === "transfer.cancel") {
877
+ if (isTransferId(p.operationId))
878
+ (_a = handlers.onCancel) == null ? void 0 : _a.call(handlers, p.operationId);
879
+ return;
880
+ }
881
+ if (typeof m.id !== "string")
882
+ return;
883
+ const reply = (payload) => {
884
+ if (this.transferLink === link)
885
+ link.post(envelope(m.type + "Result", payload, { replyTo: m.id }));
886
+ };
887
+ const fail = (error) => reply({ ok: false, code: error instanceof TransferError && error.code !== "timeout" ? error.code : "denied" });
888
+ try {
889
+ if (m.type === "transfer.probe") {
890
+ const probe = readTransferProbe(p);
891
+ if (!probe || !handlers.onProbe)
892
+ return reply({ ok: false, code: "unsupported" });
893
+ const answer = await handlers.onProbe(probe);
894
+ return reply({ ok: true, answer: answer ? readTransferProbeAnswer(answer, probe) : null });
895
+ }
896
+ if (m.type === "transfer.read") {
897
+ const read = readTransferReadRequest(p);
898
+ if (!read || !handlers.onRead)
899
+ return reply({ ok: false, code: "unsupported" });
900
+ return reply({ ok: true, items: readTransferReadValues(await handlers.onRead(read), read, { files: !this.native }) });
901
+ }
902
+ if (m.type === "transfer.deliver") {
903
+ const delivery = readTransferDelivery(p);
904
+ if (!delivery || !handlers.onDeliver)
905
+ return reply({ ok: false, code: "unsupported" });
906
+ let result = this.deliveries.get(delivery.operationId);
907
+ if (!result) {
908
+ const onDeliver = handlers.onDeliver;
909
+ result = Promise.resolve().then(() => onDeliver(delivery));
910
+ this.deliveries.set(delivery.operationId, result);
911
+ result.catch(() => this.deliveries.delete(delivery.operationId));
912
+ for (const key of [...this.deliveries.keys()].slice(0, Math.max(0, this.deliveries.size - DELIVERY_MEMORY)))
913
+ this.deliveries.delete(key);
914
+ }
915
+ return reply({ ok: true, result: readTransferDeliveryResult(await result, delivery.items) });
916
+ }
917
+ if (m.type === "transfer.status") {
918
+ if (!isTransferId(p.operationId))
919
+ return reply({ ok: false, code: "unsupported" });
920
+ const result = this.deliveries.get(p.operationId);
921
+ return reply({ ok: true, result: result ? await result : null });
922
+ }
923
+ reply({ ok: false, code: "unsupported" });
924
+ } catch (error) {
925
+ fail(error);
926
+ }
927
+ }
928
+ /**
929
+ * Registers a selection with the Shell so another App can receive it (the Shell's drag handle, "Paste desktop
930
+ * object…"). The offer id is generated here; withdraw it when the selection goes away. Never rejects.
931
+ */
932
+ offerTransfer(offer) {
933
+ const link = this.transferLink;
934
+ if (!link)
935
+ return Promise.resolve({ ok: false, code: "unsupported" });
936
+ const message = readTransferOffer({ ...offer, offerId: newOfferId(), generation: offer.generation ?? ++this.generation });
937
+ if (!message)
938
+ return Promise.resolve({ ok: false, code: "unsupported" });
939
+ const id = crypto.randomUUID();
940
+ return new Promise((resolve) => {
941
+ const timer = setTimeout(() => {
942
+ this.transferPending.delete(id);
943
+ resolve({ ok: false, code: "unsupported" });
944
+ }, TRANSFER_TIMEOUT.offer);
945
+ this.transferPending.set(id, { timer, resolve: (reply) => {
946
+ const r = isObject(reply) ? reply : {};
947
+ resolve(r.ok === true ? { ok: true, offerId: message.offerId } : { ok: false, code: transferCode(r.code) });
948
+ } });
949
+ link.post(envelope("transfer.offer", message, { id }));
950
+ });
951
+ }
952
+ /** Withdraws a selection offered with `offerTransfer`. */
953
+ withdrawTransfer(offerId) {
954
+ var _a;
955
+ if (isTransferId(offerId))
956
+ (_a = this.transferLink) == null ? void 0 : _a.post(envelope("transfer.cancel", { offerId }));
957
+ }
958
+ showAppearance(appearance) {
959
+ this.appearance = appearance;
960
+ setFrameAppearance(appearance);
961
+ }
962
+ dispose() {
963
+ var _a, _b;
467
964
  clearInterval(this.helloTimer);
468
965
  clearTimeout(this.helloDeadline);
469
966
  this.detach();
967
+ if (this.appearance)
968
+ setFrameAppearance(null);
969
+ (_a = this.transferLink) == null ? void 0 : _a.close();
970
+ this.transferLink = void 0;
971
+ this.transferPending.forEach((p) => {
972
+ clearTimeout(p.timer);
973
+ p.resolve({ ok: false, code: "stale" });
974
+ });
975
+ this.transferPending.clear();
470
976
  this.appOpens.forEach((settle) => settle({ ok: false, code: "unsupported" }));
471
977
  this.dialogs.forEach((pending) => pending.reject(new SystemDialogError("closed")));
472
978
  this.dialogs.clear();
473
- (_a = this.embedAbort) == null ? void 0 : _a.abort();
979
+ (_b = this.embedAbort) == null ? void 0 : _b.abort();
474
980
  }
475
981
  }
476
982
  const PREVIEW_EMBED = "buckyos.preview-embed";
@@ -974,9 +1480,19 @@ export {
974
1480
  PreviewEmbedHost,
975
1481
  SELECT_EMBED_PATH,
976
1482
  SelectEmbedHost,
1483
+ TRANSFER_CAPABILITY,
1484
+ TRANSFER_ERROR_CODES,
1485
+ TransferError,
977
1486
  appFrameName,
978
1487
  embedderOrigin,
979
1488
  openSelectEmbed,
980
- originInZone
1489
+ originInZone,
1490
+ readTransferDelivery,
1491
+ readTransferDeliveryResult,
1492
+ readTransferOffer,
1493
+ readTransferProbe,
1494
+ readTransferProbeAnswer,
1495
+ readTransferReadRequest,
1496
+ readTransferValue
981
1497
  };
982
1498
  //# sourceMappingURL=app-frame.mjs.map