@copio/sdk 0.1.5 → 0.1.7

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 (116) hide show
  1. package/THIRD_PARTY_NOTICES.md +34 -0
  2. package/dist/adapters/edge/index.js +2 -0
  3. package/dist/adapters/edge/index.js.map +7 -0
  4. package/dist/adapters/edge/null-edge-detector-adapter.js +2 -0
  5. package/dist/adapters/edge/null-edge-detector-adapter.js.map +7 -0
  6. package/dist/adapters/edge/scanic-wasm-adapter.js +2 -0
  7. package/dist/adapters/edge/scanic-wasm-adapter.js.map +7 -0
  8. package/dist/adapters/image/canvas2d-adapter.js +1 -1
  9. package/dist/adapters/image/index.js +1 -1
  10. package/dist/adapters/image/null-image-processor-adapter.js +1 -1
  11. package/dist/adapters/index.js +1 -1
  12. package/dist/adapters/indexeddb-adapter.js +1 -1
  13. package/dist/adapters/memory-adapter.js +1 -1
  14. package/dist/adapters/ocr/index.js +1 -1
  15. package/dist/adapters/ocr/null-ocr-adapter.js +1 -1
  16. package/dist/adapters/ocr/tesseract-wasm-adapter.js +1 -1
  17. package/dist/adapters/pdf/index.js +1 -1
  18. package/dist/adapters/pdf/null-pdf-adapter.js +1 -1
  19. package/dist/adapters/pdf/pdfkit-adapter.js +1 -1
  20. package/dist/adapters/storage/index.js +1 -1
  21. package/dist/adapters/storage/indexeddb-adapter.js +1 -1
  22. package/dist/adapters/storage/memory-adapter.js +1 -1
  23. package/dist/adapters/sync/index.js +1 -1
  24. package/dist/adapters/sync/null-sync-adapter.js +1 -1
  25. package/dist/adapters/sync/peerjs-adapter.js +1 -1
  26. package/dist/canvas-GKLGWNAJ.js +2 -0
  27. package/dist/cdn.js +189 -1409
  28. package/dist/chunk-25WAHT3G.js +2 -0
  29. package/dist/chunk-2VH2NPXW.js +175 -0
  30. package/dist/{chunk-DIU5BGU5.js → chunk-4D6GC55I.js} +2 -2
  31. package/dist/chunk-6QK7337A.js +2 -0
  32. package/dist/chunk-GLY5CGCY.js +2 -0
  33. package/dist/chunk-GU6OQMYK.js +4 -0
  34. package/dist/chunk-HCCNUPKB.js +2 -0
  35. package/dist/chunk-JIPKWRBK.js +2 -0
  36. package/dist/{chunk-GGERQ3CJ.js → chunk-NM4YYZYB.js} +3 -3
  37. package/dist/chunk-NNSM2I5L.js +2 -0
  38. package/dist/chunk-PBF7V4Z6.js +2 -0
  39. package/dist/chunk-PSGIWIRH.js +2 -0
  40. package/dist/chunk-Q7SOUI6D.js +2 -0
  41. package/dist/chunk-R6Q4OXDG.js +2 -0
  42. package/dist/chunk-SZHKZARU.js +2 -0
  43. package/dist/{chunk-J7HWZNIP.js → chunk-T5CPA7B2.js} +2 -2
  44. package/dist/chunk-V2D55DVU.js +1 -0
  45. package/dist/chunk-VPSUKD6F.js +2 -0
  46. package/dist/chunk-WZZ7FNDX.js +2 -0
  47. package/dist/chunk-ZILTJGT2.js +2 -0
  48. package/dist/core.js +1 -1
  49. package/dist/custom-elements.json +2358 -177
  50. package/dist/export.js +1 -1
  51. package/dist/fs-Y7NMZRBK.js +2 -0
  52. package/dist/handoff-transport-7YFK4RYL.js +2 -0
  53. package/dist/handoff.js +2 -0
  54. package/dist/http-CYZIMVXQ.js +2 -0
  55. package/dist/https-OLG7KUSR.js +2 -0
  56. package/dist/index.js +11 -11
  57. package/dist/ocr.js +1 -1
  58. package/dist/path2d-HD3LU76S.js +2 -0
  59. package/dist/scanic-mlDetector-BCSVQYFV.js +2 -0
  60. package/dist/scanic-ort.wasm.min-MU4NYSP2.js +2 -0
  61. package/dist/scanner.js +3 -1396
  62. package/dist/sync.js +1 -1
  63. package/dist/types/js/adapters/edge/edge-detector-port.d.ts +183 -0
  64. package/dist/types/js/adapters/edge/index.d.ts +3 -0
  65. package/dist/types/js/adapters/edge/null-edge-detector-adapter.d.ts +35 -0
  66. package/dist/types/js/adapters/edge/scanic-wasm-adapter.d.ts +54 -0
  67. package/dist/types/js/adapters/storage/indexeddb-adapter.d.ts +11 -0
  68. package/dist/types/js/adapters/storage/memory-adapter.d.ts +11 -0
  69. package/dist/types/js/adapters/storage/opfs-adapter.d.ts +11 -0
  70. package/dist/types/js/adapters/storage/storage-port.d.ts +27 -0
  71. package/dist/types/js/services/doc-repository.d.ts +6 -1
  72. package/dist/types/js/services/handoff-crypto.d.ts +84 -0
  73. package/dist/types/js/services/handoff-session.d.ts +257 -0
  74. package/dist/types/js/services/handoff-transport.d.ts +51 -0
  75. package/dist/types/js/services/ice-servers.d.ts +33 -1
  76. package/dist/types/js/services/migration-runner.d.ts +100 -0
  77. package/dist/types/js/utils/perspective.d.ts +70 -0
  78. package/dist/types/js/utils/utils.d.ts +19 -1
  79. package/dist/types/sdk/core.d.ts +52 -6
  80. package/dist/types/sdk/elements.d.ts +2 -0
  81. package/dist/types/sdk/events.d.ts +42 -0
  82. package/dist/types/sdk/handoff-session.d.ts +4 -0
  83. package/dist/types/sdk/handoff-styles.d.ts +9 -0
  84. package/dist/types/sdk/handoff.d.ts +108 -0
  85. package/dist/types/sdk/index.d.ts +5 -1
  86. package/dist/types/sdk/models.d.ts +248 -1
  87. package/dist/types/sdk/scanner.d.ts +94 -1
  88. package/dist/types/sdk/styles.d.ts +1 -1
  89. package/dist/types/sdk/version.d.ts +1 -1
  90. package/dist/url-NYR4TEJV.js +2 -0
  91. package/package.json +10 -3
  92. package/sdk/core.js +226 -13
  93. package/sdk/events.js +14 -0
  94. package/sdk/handoff-session.js +26 -0
  95. package/sdk/handoff-styles.js +531 -0
  96. package/sdk/handoff.js +1079 -0
  97. package/sdk/index.js +38 -1
  98. package/sdk/models.js +116 -4
  99. package/sdk/scanner.js +1517 -151
  100. package/sdk/styles.js +305 -22
  101. package/sdk/version.js +1 -1
  102. package/dist/canvas-FAXPLPXN.js +0 -2
  103. package/dist/chunk-4C666HHU.js +0 -2
  104. package/dist/chunk-FQRADJY6.js +0 -2
  105. package/dist/chunk-G5EUMLYT.js +0 -4
  106. package/dist/chunk-K4NR6OAC.js +0 -2
  107. package/dist/chunk-L4OVZN23.js +0 -2
  108. package/dist/chunk-MEE2NNYB.js +0 -2
  109. package/dist/chunk-O7IV7A6O.js +0 -2
  110. package/dist/chunk-Q7XPZMZA.js +0 -1395
  111. package/dist/chunk-WETG2JD7.js +0 -2
  112. package/dist/fs-HJ6WWW73.js +0 -2
  113. package/dist/http-FKJJMT2N.js +0 -2
  114. package/dist/https-MUBFLDZM.js +0 -2
  115. package/dist/path2d-QWN6DFCC.js +0 -2
  116. package/dist/url-ABJ6S2Y6.js +0 -2
package/sdk/handoff.js ADDED
@@ -0,0 +1,1079 @@
1
+ // SPDX-License-Identifier: AGPL-3.0
2
+ /**
3
+ * Copio Phone-to-Desktop Handoff Web Component (<copio-handoff>) (CPO-091 / ADR 0002)
4
+ *
5
+ * Encapsulated Shadow DOM widget providing optical QR handoff, live streaming progress,
6
+ * and local file upload fallback.
7
+ */
8
+
9
+ import { COPIO_EVENTS, dispatchCopioEvent } from './events.js';
10
+ import { loadQrCode } from '../js/utils/module-loader.js';
11
+ import {
12
+ HandoffSession,
13
+ LoopbackTransport,
14
+ randomHandoffId,
15
+ encodeSessionToken,
16
+ decodeSessionToken,
17
+ buildHandoffUrl,
18
+ parseHandoffUrl,
19
+ HANDOFF_DEFAULT_CHUNK_SIZE,
20
+ HANDOFF_DEFAULT_TTL_MS,
21
+ } from '../js/services/handoff-session.js';
22
+ import {
23
+ generateEcdhKeyPair,
24
+ exportPublicKey,
25
+ importPublicKey,
26
+ deriveSharedKey,
27
+ encryptPayload,
28
+ decryptPayload,
29
+ } from '../js/services/handoff-crypto.js';
30
+ import { handoffCss, getHandoffStyleSheet, adoptHandoffStyles } from './handoff-styles.js';
31
+
32
+ /** @type {typeof HTMLElement} */
33
+ const BaseElement = typeof HTMLElement !== 'undefined' ? HTMLElement : /** @type {any} */ (class {});
34
+
35
+ /**
36
+ * Generates an SVG QR code from a target URL string.
37
+ * @param {string} url
38
+ * @returns {Promise<string>}
39
+ */
40
+ async function generateQrSvg(url) {
41
+ try {
42
+ const qrcode = await loadQrCode();
43
+ if (qrcode) {
44
+ const qr = qrcode(0, 'M');
45
+ qr.addData(url);
46
+ qr.make();
47
+ return qr.createSvgTag({ scalable: true, margin: 4 });
48
+ }
49
+ } catch (err) {
50
+ console.warn('[CopioHandoff] loadQrCode failed, using SVG fallback:', err);
51
+ }
52
+
53
+ // Pure SVG fallback if qrcode script is unavailable
54
+ return `<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
55
+ <rect width="100" height="100" fill="#ffffff" />
56
+ <rect x="8" y="8" width="28" height="28" fill="#0b0f17" rx="3" />
57
+ <rect x="13" y="13" width="18" height="18" fill="#ffffff" rx="2" />
58
+ <rect x="17" y="17" width="10" height="10" fill="#0b0f17" rx="1" />
59
+ <rect x="64" y="8" width="28" height="28" fill="#0b0f17" rx="3" />
60
+ <rect x="69" y="13" width="18" height="18" fill="#ffffff" rx="2" />
61
+ <rect x="73" y="17" width="10" height="10" fill="#0b0f17" rx="1" />
62
+ <rect x="8" y="64" width="28" height="28" fill="#0b0f17" rx="3" />
63
+ <rect x="13" y="69" width="18" height="18" fill="#ffffff" rx="2" />
64
+ <rect x="17" y="73" width="10" height="10" fill="#0b0f17" rx="1" />
65
+ <rect x="42" y="12" width="6" height="6" fill="#0284c7" />
66
+ <rect x="52" y="20" width="6" height="6" fill="#0284c7" />
67
+ <rect x="42" y="42" width="16" height="16" fill="#0284c7" rx="2" />
68
+ <rect x="68" y="48" width="6" height="6" fill="#0b0f17" />
69
+ <rect x="78" y="58" width="6" height="6" fill="#0b0f17" />
70
+ <rect x="48" y="68" width="6" height="6" fill="#0b0f17" />
71
+ <rect x="64" y="74" width="12" height="6" fill="#0b0f17" />
72
+ </svg>`;
73
+ }
74
+
75
+ export class CopioHandoff extends BaseElement {
76
+ #session = null;
77
+ #state = 'waiting'; // 'waiting' | 'connected' | 'receiving' | 'complete' | 'error' | 'expired'
78
+ #token = null;
79
+ #url = '';
80
+ #qrSvg = null;
81
+ #pages = [];
82
+ #activeProgress = null;
83
+ #errorMessage = '';
84
+ #remainingSeconds = 600;
85
+ #countdownInterval = null;
86
+ #sessionDocId = null;
87
+ #unsubs = [];
88
+ #autoStart = true;
89
+ #relayUrl = '';
90
+ #signalingUrl = '';
91
+ #iceServers = null;
92
+ #iceTransportPolicy = 'all';
93
+ #customTransport = null;
94
+ #connectionInfo = null;
95
+
96
+ static get observedAttributes() {
97
+ return [
98
+ 'state',
99
+ 'receiver-url',
100
+ 'doc-id',
101
+ 'theme',
102
+ 'ttl',
103
+ 'mode',
104
+ 'aspect',
105
+ 'relay-url',
106
+ 'ice-servers',
107
+ 'signaling-url',
108
+ 'ice-transport-policy',
109
+ 'transport',
110
+ ];
111
+ }
112
+
113
+ constructor() {
114
+ super();
115
+ if (typeof this.attachShadow === 'function') {
116
+ this.attachShadow({ mode: 'open' });
117
+ }
118
+ }
119
+
120
+ get #targetDocId() {
121
+ if (this.docId) return this.docId;
122
+ if (!this.#sessionDocId) {
123
+ this.#sessionDocId = randomHandoffId('doc_');
124
+ }
125
+ return this.#sessionDocId;
126
+ }
127
+
128
+ connectedCallback() {
129
+ if (this.shadowRoot) {
130
+ adoptHandoffStyles(this.shadowRoot);
131
+ this.#render();
132
+ }
133
+
134
+ if (this.#autoStart && !this.#session) {
135
+ this.start().catch((err) => {
136
+ this.#fail(err);
137
+ });
138
+ }
139
+ }
140
+
141
+ disconnectedCallback() {
142
+ this.#stopCountdown();
143
+ this.#cleanupSession();
144
+ }
145
+
146
+ attributeChangedCallback(name, oldVal, newVal) {
147
+ if (oldVal === newVal) return;
148
+ if (name === 'state' && newVal && newVal !== this.#state) {
149
+ this.#state = newVal;
150
+ this.#render();
151
+ } else if (name === 'theme' && this.shadowRoot) {
152
+ this.#render();
153
+ }
154
+ }
155
+
156
+ // --- Properties ---
157
+
158
+ get state() {
159
+ return this.#state;
160
+ }
161
+
162
+ set state(val) {
163
+ if (this.#state === val) return;
164
+ this.#state = val;
165
+ if (typeof this.setAttribute === 'function') {
166
+ this.setAttribute('state', val);
167
+ }
168
+ this.#render();
169
+ }
170
+
171
+ get session() {
172
+ return this.#session;
173
+ }
174
+
175
+ set session(sess) {
176
+ if (sess) {
177
+ this.attachSession(sess);
178
+ }
179
+ }
180
+
181
+ get receiverUrl() {
182
+ return typeof this.getAttribute === 'function' ? this.getAttribute('receiver-url') || '' : '';
183
+ }
184
+
185
+ set receiverUrl(val) {
186
+ if (typeof this.setAttribute === 'function') {
187
+ if (val) this.setAttribute('receiver-url', val);
188
+ else this.removeAttribute('receiver-url');
189
+ }
190
+ }
191
+
192
+ get docId() {
193
+ return typeof this.getAttribute === 'function' ? this.getAttribute('doc-id') || null : null;
194
+ }
195
+
196
+ set docId(val) {
197
+ if (typeof this.setAttribute === 'function') {
198
+ if (val) this.setAttribute('doc-id', val);
199
+ else this.removeAttribute('doc-id');
200
+ }
201
+ }
202
+
203
+ get theme() {
204
+ return typeof this.getAttribute === 'function' ? this.getAttribute('theme') || 'dark' : 'dark';
205
+ }
206
+
207
+ set theme(val) {
208
+ if (typeof this.setAttribute === 'function') {
209
+ if (val) this.setAttribute('theme', val);
210
+ else this.removeAttribute('theme');
211
+ }
212
+ }
213
+
214
+ get ttlMs() {
215
+ const raw = typeof this.getAttribute === 'function' ? this.getAttribute('ttl') : null;
216
+ return raw ? parseInt(raw, 10) : HANDOFF_DEFAULT_TTL_MS;
217
+ }
218
+
219
+ set ttlMs(val) {
220
+ if (typeof this.setAttribute === 'function') {
221
+ this.setAttribute('ttl', String(val));
222
+ }
223
+ }
224
+
225
+ get mode() {
226
+ return typeof this.getAttribute === 'function' ? this.getAttribute('mode') || 'batch' : 'batch';
227
+ }
228
+
229
+ set mode(val) {
230
+ if (typeof this.setAttribute === 'function') {
231
+ this.setAttribute('mode', val);
232
+ }
233
+ }
234
+
235
+ get aspect() {
236
+ return typeof this.getAttribute === 'function' ? this.getAttribute('aspect') || 'auto' : 'auto';
237
+ }
238
+
239
+ set aspect(val) {
240
+ if (typeof this.setAttribute === 'function') {
241
+ this.setAttribute('aspect', val);
242
+ }
243
+ }
244
+
245
+ get pages() {
246
+ return [...this.#pages];
247
+ }
248
+
249
+ get token() {
250
+ return this.#token;
251
+ }
252
+
253
+ get url() {
254
+ return this.#url;
255
+ }
256
+
257
+ get relayUrl() {
258
+ return this.#relayUrl || (typeof this.getAttribute === 'function' ? this.getAttribute('relay-url') || '' : '');
259
+ }
260
+
261
+ set relayUrl(val) {
262
+ this.#relayUrl = val || '';
263
+ if (typeof this.setAttribute === 'function') {
264
+ if (val) this.setAttribute('relay-url', val);
265
+ else this.removeAttribute('relay-url');
266
+ }
267
+ }
268
+
269
+ get signalingUrl() {
270
+ return (
271
+ this.#signalingUrl ||
272
+ (typeof this.getAttribute === 'function' ? this.getAttribute('signaling-url') || '' : '')
273
+ );
274
+ }
275
+
276
+ set signalingUrl(val) {
277
+ this.#signalingUrl = val || '';
278
+ if (typeof this.setAttribute === 'function') {
279
+ if (val) this.setAttribute('signaling-url', val);
280
+ else this.removeAttribute('signaling-url');
281
+ }
282
+ }
283
+
284
+ get iceServers() {
285
+ if (this.#iceServers) return this.#iceServers;
286
+ const attr = typeof this.getAttribute === 'function' ? this.getAttribute('ice-servers') : null;
287
+ if (attr) {
288
+ try {
289
+ const parsed = JSON.parse(attr);
290
+ if (Array.isArray(parsed)) return parsed;
291
+ } catch {
292
+ return attr.split(',').map((u) => ({ urls: u.trim() }));
293
+ }
294
+ }
295
+ return null;
296
+ }
297
+
298
+ set iceServers(val) {
299
+ if (Array.isArray(val)) {
300
+ this.#iceServers = val;
301
+ } else if (typeof val === 'string') {
302
+ try {
303
+ this.#iceServers = JSON.parse(val);
304
+ } catch {
305
+ this.#iceServers = val ? [{ urls: val }] : null;
306
+ }
307
+ } else {
308
+ this.#iceServers = null;
309
+ }
310
+ if (typeof this.setAttribute === 'function') {
311
+ if (Array.isArray(val)) this.setAttribute('ice-servers', JSON.stringify(val));
312
+ else if (val) this.setAttribute('ice-servers', String(val));
313
+ else this.removeAttribute('ice-servers');
314
+ }
315
+ }
316
+
317
+ get iceTransportPolicy() {
318
+ return typeof this.getAttribute === 'function'
319
+ ? this.getAttribute('ice-transport-policy') || this.#iceTransportPolicy || 'all'
320
+ : this.#iceTransportPolicy || 'all';
321
+ }
322
+
323
+ set iceTransportPolicy(val) {
324
+ this.#iceTransportPolicy = val || 'all';
325
+ if (typeof this.setAttribute === 'function') {
326
+ if (val) this.setAttribute('ice-transport-policy', val);
327
+ else this.removeAttribute('ice-transport-policy');
328
+ }
329
+ }
330
+
331
+ get transport() {
332
+ if (this.#customTransport) return this.#customTransport;
333
+ return typeof this.getAttribute === 'function'
334
+ ? this.getAttribute('transport') || 'auto'
335
+ : 'auto';
336
+ }
337
+
338
+ set transport(val) {
339
+ if (typeof val === 'string') {
340
+ if (typeof this.setAttribute === 'function') {
341
+ this.setAttribute('transport', val);
342
+ }
343
+ } else {
344
+ this.#customTransport = val;
345
+ }
346
+ }
347
+
348
+ get connectionInfo() {
349
+ return (
350
+ this.#connectionInfo || {
351
+ transport: /** @type {'direct'|'turn'} */ (
352
+ this.iceTransportPolicy === 'relay' ? 'turn' : 'direct'
353
+ ),
354
+ rttMs: 0,
355
+ }
356
+ );
357
+ }
358
+
359
+ /**
360
+ * Retrieves connection diagnostics for the active session.
361
+ * @returns {Promise<{ transport: 'direct'|'turn', rttMs: number }>}
362
+ */
363
+ async getConnectionInfo() {
364
+ if (this.#session && typeof this.#session.getConnectionInfo === 'function') {
365
+ const info = await this.#session.getConnectionInfo();
366
+ this.#connectionInfo = info;
367
+ return info;
368
+ }
369
+ return this.connectionInfo;
370
+ }
371
+
372
+ // --- Public Methods ---
373
+
374
+ /**
375
+ * Starts a new host session and generates a fresh optical QR token.
376
+ * @param {Object} [options]
377
+ * @param {string} [options.baseUrl]
378
+ * @param {string} [options.peerId]
379
+ * @param {boolean} [options.peer]
380
+ * @param {Object} [options.transport]
381
+ * @returns {Promise<{ token: Object, url: string }>}
382
+ */
383
+ async start(options = {}) {
384
+ this.#cleanupSession();
385
+ this.#pages = [];
386
+ this.#activeProgress = null;
387
+ this.#errorMessage = '';
388
+
389
+ let transport = options.transport || this.#customTransport;
390
+
391
+ if (!transport) {
392
+ const wantsPeer =
393
+ Boolean(options.peer) ||
394
+ this.getAttribute('transport') === 'peer' ||
395
+ Boolean(this.relayUrl) ||
396
+ Boolean(this.signalingUrl) ||
397
+ Boolean(this.iceServers);
398
+
399
+ const peerId =
400
+ options.peerId ||
401
+ (wantsPeer ? randomHandoffId('copio-hnd-') : randomHandoffId('peer_'));
402
+ options.peerId = peerId;
403
+
404
+ if (wantsPeer) {
405
+ try {
406
+ const { HandoffPeerTransport } = await import('../js/services/handoff-transport.js');
407
+ transport = new HandoffPeerTransport({
408
+ role: 'host',
409
+ peerId,
410
+ relayUrl: this.relayUrl,
411
+ signalingUrl: this.signalingUrl,
412
+ iceServers: this.iceServers,
413
+ iceTransportPolicy: /** @type {'all'|'relay'} */ (this.iceTransportPolicy),
414
+ });
415
+ } catch (err) {
416
+ console.warn('[CopioHandoff] Failed to initialize HandoffPeerTransport, falling back to loopback:', err);
417
+ transport = new LoopbackTransport();
418
+ }
419
+ } else {
420
+ const loopback = new LoopbackTransport();
421
+ if (this.iceTransportPolicy === 'relay') {
422
+ loopback.forceRelay = true;
423
+ loopback.iceTransportPolicy = 'relay';
424
+ }
425
+ transport = loopback;
426
+ }
427
+ }
428
+
429
+ const session = new HandoffSession({
430
+ role: 'host',
431
+ ttlMs: this.ttlMs,
432
+ transport,
433
+ });
434
+
435
+ this.#session = session;
436
+ this.#bindSessionEvents(session);
437
+
438
+ const baseUrl = options.baseUrl || this.receiverUrl || this.#getDefaultBaseUrl();
439
+ const { token, url } = await session.startHost({
440
+ baseUrl,
441
+ peerId: options.peerId,
442
+ relayUrl: this.relayUrl,
443
+ signalingUrl: this.signalingUrl,
444
+ iceServers: this.iceServers,
445
+ });
446
+
447
+ if (transport instanceof LoopbackTransport && token?.peerId) {
448
+ LoopbackTransport.register(token.peerId, transport);
449
+ }
450
+
451
+ this.#token = token;
452
+ this.#url = url;
453
+ this.#remainingSeconds = Math.max(0, Math.ceil((token.expiresAt - Date.now()) / 1000));
454
+ this.#startCountdown(token.expiresAt);
455
+
456
+ this.state = 'waiting';
457
+
458
+ // Generate QR SVG
459
+ this.#qrSvg = null;
460
+ this.#render();
461
+ try {
462
+ this.#qrSvg = await generateQrSvg(url);
463
+ if (this.#state === 'waiting') {
464
+ this.#render();
465
+ }
466
+ } catch (err) {
467
+ console.warn('[CopioHandoff] QR code generation error:', err);
468
+ }
469
+
470
+ return { token, url };
471
+ }
472
+
473
+ /**
474
+ * Attaches an existing HandoffSession (e.g. LoopbackTransport in automated tests).
475
+ * @param {HandoffSession} session
476
+ * @param {Object} [token]
477
+ */
478
+ attachSession(session, token = null) {
479
+ if (!session) return;
480
+ this.#cleanupSession();
481
+ this.#session = session;
482
+ this.#token = token || session.token;
483
+ if (this.#token?.expiresAt) {
484
+ this.#remainingSeconds = Math.max(0, Math.ceil((this.#token.expiresAt - Date.now()) / 1000));
485
+ this.#startCountdown(this.#token.expiresAt);
486
+ }
487
+ this.#bindSessionEvents(session);
488
+ this.state = session.state === 'idle' ? 'waiting' : session.state;
489
+ }
490
+
491
+ /**
492
+ * Regenerates a new QR code and session.
493
+ */
494
+ async refresh() {
495
+ return this.start();
496
+ }
497
+
498
+ /**
499
+ * Clears all received pages and resets back to waiting.
500
+ */
501
+ async clear() {
502
+ this.#pages = [];
503
+ this.#activeProgress = null;
504
+ return this.start();
505
+ }
506
+
507
+ /**
508
+ * Returns copy of received page entities.
509
+ * @returns {Array<Object>}
510
+ */
511
+ getPages() {
512
+ return [...this.#pages];
513
+ }
514
+
515
+ /**
516
+ * Dispatches a public Copio event.
517
+ * @param {string} eventName
518
+ * @param {Object} [detail]
519
+ */
520
+ dispatch(eventName, detail = {}) {
521
+ return dispatchCopioEvent(this, eventName, detail);
522
+ }
523
+
524
+ // --- Private Helpers ---
525
+
526
+ #getDefaultBaseUrl() {
527
+ if (typeof location !== 'undefined' && location.href) {
528
+ return `${location.origin}${location.pathname}`;
529
+ }
530
+ return 'https://copio.netlify.app/scan';
531
+ }
532
+
533
+ #bindSessionEvents(session) {
534
+ this.#unsubs.push(
535
+ session.on('stateChange', (newState) => {
536
+ if (newState === 'closed') return;
537
+ this.state = newState;
538
+ if (newState === 'connected') {
539
+ this.dispatch(COPIO_EVENTS.HANDOFF_CONNECTED, {
540
+ sessionId: this.#token?.sessionId || '',
541
+ peerId: this.#token?.peerId || '',
542
+ });
543
+ session.getConnectionInfo().then((info) => {
544
+ this.#connectionInfo = info;
545
+ this.dispatch(COPIO_EVENTS.CONNECTION_INFO, info);
546
+ }).catch(() => {});
547
+ }
548
+ }),
549
+
550
+ session.on('connectionInfo', (info) => {
551
+ this.#connectionInfo = info;
552
+ this.dispatch(COPIO_EVENTS.CONNECTION_INFO, info);
553
+ }),
554
+
555
+ session.on('progress', (progress) => {
556
+ this.#activeProgress = progress;
557
+ if (this.#state !== 'receiving') {
558
+ this.state = 'receiving';
559
+ } else {
560
+ this.#updateProgressDom();
561
+ }
562
+ }),
563
+
564
+ session.on('page', (pageData) => {
565
+ this.#handleIncomingPage(pageData);
566
+ }),
567
+
568
+ session.on('complete', (summary) => {
569
+ this.#handleSessionComplete(summary);
570
+ }),
571
+
572
+ session.on('error', (err) => {
573
+ this.#fail(err);
574
+ })
575
+ );
576
+ }
577
+
578
+ #handleIncomingPage(pageData) {
579
+ let src = '';
580
+ if (pageData.blob && typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function') {
581
+ try {
582
+ src = URL.createObjectURL(pageData.blob);
583
+ } catch {
584
+ src = '';
585
+ }
586
+ }
587
+
588
+ const pageIndex = typeof pageData.pageIndex === 'number' ? pageData.pageIndex : this.#pages.length;
589
+ const pageNumber = this.#pages.length + 1;
590
+ const page = {
591
+ id: pageData.id || randomHandoffId('page_'),
592
+ pageIndex,
593
+ pageNumber,
594
+ label: `Page ${pageNumber}`,
595
+ mimeType: pageData.mimeType || 'image/jpeg',
596
+ blob: pageData.blob,
597
+ src,
598
+ originalSrc: src,
599
+ originalPreserved: true,
600
+ dimensions: pageData.metadata?.width
601
+ ? { width: pageData.metadata.width, height: pageData.metadata.height }
602
+ : { width: 0, height: 0 },
603
+ edits: { crop: { x: 0, y: 0, w: 1, h: 1 }, rotate: 0, filter: 'none' },
604
+ ocrText: null,
605
+ };
606
+
607
+ this.#pages.push(page);
608
+ this.#activeProgress = null;
609
+
610
+ this.dispatch(COPIO_EVENTS.PAGE_ADDED, {
611
+ page,
612
+ pageNumber: page.pageNumber,
613
+ docId: this.docId || this.#targetDocId,
614
+ source: 'handoff',
615
+ });
616
+
617
+ if (this.#state === 'receiving') {
618
+ this.state = 'connected';
619
+ } else {
620
+ this.#render();
621
+ }
622
+ }
623
+
624
+ #handleSessionComplete(details = {}) {
625
+ this.#stopCountdown();
626
+ this.state = 'complete';
627
+
628
+ const payload = {
629
+ mode: this.mode,
630
+ aspect: this.aspect,
631
+ docId: this.docId || details.docId || this.#targetDocId,
632
+ pageCount: this.#pages.length,
633
+ pages: [...this.#pages],
634
+ summary: details.summary || {},
635
+ };
636
+
637
+ this.dispatch(COPIO_EVENTS.SCAN_COMPLETE, payload);
638
+ }
639
+
640
+ #fail(err) {
641
+ this.#stopCountdown();
642
+ this.#errorMessage = err?.message || String(err);
643
+ this.state = 'error';
644
+ this.dispatch(COPIO_EVENTS.ERROR, {
645
+ code: 'HANDOFF_ERROR',
646
+ message: this.#errorMessage,
647
+ error: err,
648
+ });
649
+ }
650
+
651
+ #startCountdown(expiresAt) {
652
+ this.#stopCountdown();
653
+ this.#countdownInterval = setInterval(() => {
654
+ const remaining = Math.max(0, Math.ceil((expiresAt - Date.now()) / 1000));
655
+ this.#remainingSeconds = remaining;
656
+ if (remaining <= 0) {
657
+ this.#stopCountdown();
658
+ this.state = 'expired';
659
+ } else {
660
+ const timerEl = this.shadowRoot?.querySelector('.copio-handoff-countdown');
661
+ if (timerEl) {
662
+ timerEl.textContent = this.#formatTime(remaining);
663
+ }
664
+ }
665
+ }, 1000);
666
+ }
667
+
668
+ #stopCountdown() {
669
+ if (this.#countdownInterval) {
670
+ clearInterval(this.#countdownInterval);
671
+ this.#countdownInterval = null;
672
+ }
673
+ }
674
+
675
+ #cleanupSession() {
676
+ for (const unsub of this.#unsubs) {
677
+ try {
678
+ unsub();
679
+ } catch {
680
+ // ignore
681
+ }
682
+ }
683
+ this.#unsubs = [];
684
+ if (this.#session) {
685
+ try {
686
+ this.#session.close();
687
+ } catch {
688
+ // ignore
689
+ }
690
+ this.#session = null;
691
+ }
692
+ }
693
+
694
+ #formatTime(totalSec) {
695
+ const mins = Math.floor(totalSec / 60);
696
+ const secs = totalSec % 60;
697
+ return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
698
+ }
699
+
700
+ // --- File Fallback Handler ---
701
+
702
+ async #handleLocalFileUpload(files) {
703
+ if (!files || files.length === 0) return;
704
+
705
+ for (let i = 0; i < files.length; i++) {
706
+ const file = files[i];
707
+ let src = '';
708
+ if (typeof URL !== 'undefined' && typeof URL.createObjectURL === 'function') {
709
+ try {
710
+ src = URL.createObjectURL(file);
711
+ } catch {
712
+ src = '';
713
+ }
714
+ }
715
+
716
+ const pageIndex = this.#pages.length;
717
+ const pageNumber = pageIndex + 1;
718
+ const page = {
719
+ id: randomHandoffId('page_'),
720
+ pageIndex,
721
+ pageNumber,
722
+ label: file.name || `Page ${pageNumber}`,
723
+ mimeType: file.type || 'image/jpeg',
724
+ blob: file,
725
+ src,
726
+ originalSrc: src,
727
+ originalPreserved: true,
728
+ dimensions: { width: 0, height: 0 },
729
+ edits: { crop: { x: 0, y: 0, w: 1, h: 1 }, rotate: 0, filter: 'none' },
730
+ ocrText: null,
731
+ };
732
+
733
+ this.#pages.push(page);
734
+
735
+ this.dispatch(COPIO_EVENTS.PAGE_ADDED, {
736
+ page,
737
+ pageNumber,
738
+ docId: this.docId || this.#targetDocId,
739
+ source: 'file',
740
+ });
741
+ }
742
+
743
+ this.state = 'complete';
744
+
745
+ const payload = {
746
+ mode: this.mode,
747
+ aspect: this.aspect,
748
+ docId: this.docId || this.#targetDocId,
749
+ pageCount: this.#pages.length,
750
+ pages: [...this.#pages],
751
+ source: 'file',
752
+ summary: { source: 'local_upload', count: files.length },
753
+ };
754
+
755
+ this.dispatch(COPIO_EVENTS.SCAN_COMPLETE, payload);
756
+ }
757
+
758
+ // --- Rendering ---
759
+
760
+ #updateProgressDom() {
761
+ if (!this.shadowRoot) return;
762
+ const fillEl = /** @type {HTMLElement|null} */ (this.shadowRoot.querySelector('.copio-handoff-progress-fill'));
763
+ const labelEl = this.shadowRoot.querySelector('.copio-handoff-progress-pct');
764
+ if (fillEl && this.#activeProgress) {
765
+ fillEl.style.width = `${this.#activeProgress.percent || 0}%`;
766
+ }
767
+ if (labelEl && this.#activeProgress) {
768
+ labelEl.textContent = `${this.#activeProgress.percent || 0}%`;
769
+ }
770
+ }
771
+
772
+ #render() {
773
+ if (!this.shadowRoot) return;
774
+
775
+ let content = '';
776
+ switch (this.#state) {
777
+ case 'waiting':
778
+ content = this.#renderWaitingState();
779
+ break;
780
+ case 'connected':
781
+ content = this.#renderConnectedState();
782
+ break;
783
+ case 'receiving':
784
+ content = this.#renderReceivingState();
785
+ break;
786
+ case 'complete':
787
+ content = this.#renderCompleteState();
788
+ break;
789
+ case 'expired':
790
+ content = this.#renderExpiredState();
791
+ break;
792
+ case 'error':
793
+ content = this.#renderErrorState();
794
+ break;
795
+ default:
796
+ content = this.#renderWaitingState();
797
+ }
798
+
799
+ this.shadowRoot.innerHTML = `
800
+ <div class="copio-handoff-root">
801
+ <div class="copio-handoff-card">
802
+ ${content}
803
+ </div>
804
+ </div>
805
+ `;
806
+
807
+ this.#attachListeners();
808
+ }
809
+
810
+ #renderWaitingState() {
811
+ const formatted = this.#formatTime(this.#remainingSeconds);
812
+ const qrDisplay = this.#qrSvg
813
+ ? this.#qrSvg
814
+ : `
815
+ <div class="copio-handoff-qr-loading">
816
+ <div class="copio-handoff-spinner"></div>
817
+ <span>Generating QR code…</span>
818
+ </div>
819
+ `;
820
+
821
+ return `
822
+ <h2 class="copio-handoff-title">Scan with your phone camera</h2>
823
+ <p class="copio-handoff-desc">Point your smartphone camera at the code below to snap document pages with zero app install.</p>
824
+
825
+ <div class="copio-handoff-qr-box" data-testid="qr-container">
826
+ ${qrDisplay}
827
+ </div>
828
+
829
+ <div class="copio-handoff-meta-row">
830
+ <span class="copio-handoff-timer-badge" title="Session time remaining">
831
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
832
+ <circle cx="12" cy="12" r="10"></circle>
833
+ <polyline points="12 6 12 12 16 14"></polyline>
834
+ </svg>
835
+ Expires in <span class="copio-handoff-countdown">${formatted}</span>
836
+ </span>
837
+ <button class="copio-handoff-icon-btn copio-handoff-refresh-btn" type="button" title="Refresh QR code">
838
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
839
+ <polyline points="23 4 23 10 17 10"></polyline>
840
+ <polyline points="1 20 1 14 7 14"></polyline>
841
+ <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path>
842
+ </svg>
843
+ </button>
844
+ </div>
845
+
846
+ <div class="copio-handoff-divider">
847
+ <span>OR</span>
848
+ </div>
849
+
850
+ <button class="copio-handoff-btn copio-handoff-btn-secondary copio-handoff-upload-btn" type="button">
851
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
852
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
853
+ <polyline points="17 8 12 3 7 8"></polyline>
854
+ <line x1="12" y1="3" x2="12" y2="15"></line>
855
+ </svg>
856
+ Or upload file on this computer
857
+ </button>
858
+ <input type="file" class="copio-handoff-file-input" accept="image/*,application/pdf" multiple style="display:none">
859
+ `;
860
+ }
861
+
862
+ #renderConnectedState() {
863
+ const pageCount = this.#pages.length;
864
+ const badgeText = pageCount === 1 ? '1 page snapped' : `${pageCount} pages snapped`;
865
+
866
+ return `
867
+ <div class="copio-handoff-status-pill">
868
+ <span class="copio-handoff-pulse-dot"></span>
869
+ <span>Phone connected — scanning in progress…</span>
870
+ </div>
871
+
872
+ <h2 class="copio-handoff-title">Ready for Captures</h2>
873
+ <p class="copio-handoff-desc">Snap pages or receipts on your phone. They will transfer securely with end-to-end encryption.</p>
874
+
875
+ <div class="copio-handoff-badge" data-testid="page-count-badge">${badgeText}</div>
876
+
877
+ ${this.#renderThumbnails(false)}
878
+ `;
879
+ }
880
+
881
+ #renderReceivingState() {
882
+ const p = this.#activeProgress || { percent: 0, pageIndex: this.#pages.length };
883
+ const pageNum = (p.pageIndex || this.#pages.length) + 1;
884
+ const percent = p.percent || 0;
885
+
886
+ return `
887
+ <div class="copio-handoff-status-pill">
888
+ <div class="copio-handoff-spinner" style="width:12px;height:12px;border-width:2px;margin-right:4px;"></div>
889
+ <span>Receiving page ${pageNum}…</span>
890
+ </div>
891
+
892
+ <h2 class="copio-handoff-title">Streaming Page ${pageNum}</h2>
893
+ <p class="copio-handoff-desc">Decrypting 64 KB binary chunks directly in memory.</p>
894
+
895
+ <div class="copio-handoff-progress-wrap">
896
+ <div class="copio-handoff-progress-bar">
897
+ <div class="copio-handoff-progress-fill" style="width: ${percent}%;"></div>
898
+ </div>
899
+ <div class="copio-handoff-progress-label">
900
+ <span>Receiving page ${pageNum}</span>
901
+ <span class="copio-handoff-progress-pct">${percent}%</span>
902
+ </div>
903
+ </div>
904
+
905
+ ${this.#renderThumbnails(true)}
906
+ `;
907
+ }
908
+
909
+ #renderCompleteState() {
910
+ const count = this.#pages.length;
911
+ const pageDesc = count === 1 ? '1 page received' : `${count} pages received`;
912
+
913
+ return `
914
+ <div class="copio-handoff-success-icon">
915
+ <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
916
+ <polyline points="20 6 9 17 4 12"></polyline>
917
+ </svg>
918
+ </div>
919
+
920
+ <h2 class="copio-handoff-title">Scan Complete</h2>
921
+ <p class="copio-handoff-desc">${pageDesc} successfully transferred to this computer.</p>
922
+
923
+ ${this.#renderThumbnails(false)}
924
+
925
+ <button class="copio-handoff-btn copio-handoff-btn-primary copio-handoff-reset-btn" type="button">
926
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
927
+ <line x1="12" y1="5" x2="12" y2="19"></line>
928
+ <line x1="5" y1="12" x2="19" y2="12"></line>
929
+ </svg>
930
+ New Scan
931
+ </button>
932
+ `;
933
+ }
934
+
935
+ #renderExpiredState() {
936
+ return `
937
+ <div class="copio-handoff-alert">
938
+ <div class="copio-handoff-alert-icon warning">
939
+ <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
940
+ <circle cx="12" cy="12" r="10"></circle>
941
+ <polyline points="12 6 12 12 16 14"></polyline>
942
+ </svg>
943
+ </div>
944
+ <h2 class="copio-handoff-title">QR Code Expired</h2>
945
+ <p class="copio-handoff-desc">For security, handoff QR codes are single-use and expire after 10 minutes.</p>
946
+ </div>
947
+
948
+ <button class="copio-handoff-btn copio-handoff-btn-primary copio-handoff-retry-btn" type="button">
949
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
950
+ <polyline points="23 4 23 10 17 10"></polyline>
951
+ <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path>
952
+ </svg>
953
+ Generate new QR code
954
+ </button>
955
+ `;
956
+ }
957
+
958
+ #renderErrorState() {
959
+ return `
960
+ <div class="copio-handoff-alert">
961
+ <div class="copio-handoff-alert-icon danger">
962
+ <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
963
+ <circle cx="12" cy="12" r="10"></circle>
964
+ <line x1="12" y1="8" x2="12" y2="12"></line>
965
+ <line x1="12" y1="16" x2="12.01" y2="16"></line>
966
+ </svg>
967
+ </div>
968
+ <h2 class="copio-handoff-title">Connection Error</h2>
969
+ <p class="copio-handoff-desc">${this.#errorMessage || 'Unable to establish secure peer connection.'}</p>
970
+ </div>
971
+
972
+ <button class="copio-handoff-btn copio-handoff-btn-primary copio-handoff-retry-btn" type="button">
973
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
974
+ <polyline points="23 4 23 10 17 10"></polyline>
975
+ <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path>
976
+ </svg>
977
+ Generate new QR code
978
+ </button>
979
+ `;
980
+ }
981
+
982
+ #renderThumbnails(showShimmerPlaceholder = false) {
983
+ if (this.#pages.length === 0 && !showShimmerPlaceholder) {
984
+ return '';
985
+ }
986
+
987
+ const cards = this.#pages.map((p, idx) => `
988
+ <div class="copio-handoff-thumb-card" data-page-id="${p.id}">
989
+ ${p.src ? `<img class="copio-handoff-thumb-img" src="${p.src}" alt="${p.label || `Page ${idx + 1}`}">` : ''}
990
+ <span class="copio-handoff-thumb-label">P${idx + 1}</span>
991
+ </div>
992
+ `).join('');
993
+
994
+ const shimmerCard = showShimmerPlaceholder
995
+ ? `
996
+ <div class="copio-handoff-thumb-card">
997
+ <div class="copio-handoff-thumb-shimmer">
998
+ <div class="copio-handoff-spinner" style="width:14px;height:14px;border-width:2px;"></div>
999
+ </div>
1000
+ </div>
1001
+ `
1002
+ : '';
1003
+
1004
+ return `
1005
+ <div class="copio-handoff-thumbnails" data-testid="thumbnail-grid">
1006
+ ${cards}
1007
+ ${shimmerCard}
1008
+ </div>
1009
+ `;
1010
+ }
1011
+
1012
+ #attachListeners() {
1013
+ if (!this.shadowRoot) return;
1014
+
1015
+ // Refresh / Retry button
1016
+ const refreshBtn = this.shadowRoot.querySelector('.copio-handoff-refresh-btn');
1017
+ if (refreshBtn) {
1018
+ refreshBtn.addEventListener('click', () => {
1019
+ this.refresh();
1020
+ });
1021
+ }
1022
+
1023
+ const retryBtn = this.shadowRoot.querySelector('.copio-handoff-retry-btn');
1024
+ if (retryBtn) {
1025
+ retryBtn.addEventListener('click', () => {
1026
+ this.refresh();
1027
+ });
1028
+ }
1029
+
1030
+ const resetBtn = this.shadowRoot.querySelector('.copio-handoff-reset-btn');
1031
+ if (resetBtn) {
1032
+ resetBtn.addEventListener('click', () => {
1033
+ this.clear();
1034
+ });
1035
+ }
1036
+
1037
+ // File Upload Fallback
1038
+ const uploadBtn = this.shadowRoot.querySelector('.copio-handoff-upload-btn');
1039
+ const fileInput = /** @type {HTMLInputElement|null} */ (this.shadowRoot.querySelector('.copio-handoff-file-input'));
1040
+ if (uploadBtn && fileInput) {
1041
+ uploadBtn.addEventListener('click', () => {
1042
+ fileInput.click();
1043
+ });
1044
+ fileInput.addEventListener('change', (e) => {
1045
+ const target = /** @type {HTMLInputElement} */ (e.target);
1046
+ if (target.files && target.files.length > 0) {
1047
+ this.#handleLocalFileUpload(Array.from(target.files));
1048
+ }
1049
+ });
1050
+ }
1051
+ }
1052
+ }
1053
+
1054
+ if (typeof customElements !== 'undefined' && !customElements.get('copio-handoff')) {
1055
+ customElements.define('copio-handoff', CopioHandoff);
1056
+ }
1057
+
1058
+ export {
1059
+ COPIO_EVENTS,
1060
+ dispatchCopioEvent,
1061
+ handoffCss,
1062
+ getHandoffStyleSheet,
1063
+ adoptHandoffStyles,
1064
+ HandoffSession,
1065
+ LoopbackTransport,
1066
+ randomHandoffId,
1067
+ encodeSessionToken,
1068
+ decodeSessionToken,
1069
+ buildHandoffUrl,
1070
+ parseHandoffUrl,
1071
+ HANDOFF_DEFAULT_CHUNK_SIZE,
1072
+ HANDOFF_DEFAULT_TTL_MS,
1073
+ generateEcdhKeyPair,
1074
+ exportPublicKey,
1075
+ importPublicKey,
1076
+ deriveSharedKey,
1077
+ encryptPayload,
1078
+ decryptPayload,
1079
+ };