niimbot-canvas-sdk 1.0.5 → 1.0.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.
@@ -1,1115 +0,0 @@
1
- var me = Object.defineProperty;
2
- var be = (e, n, t) => n in e ? me(e, n, { enumerable: !0, configurable: !0, writable: !0, value: t }) : e[n] = t;
3
- var g = (e, n, t) => (be(e, typeof n != "symbol" ? n + "" : n, t), t), X = (e, n, t) => {
4
- if (!n.has(e))
5
- throw TypeError("Cannot " + t);
6
- };
7
- var h = (e, n, t) => (X(e, n, "read from private field"), t ? t.call(e) : n.get(e)), A = (e, n, t) => {
8
- if (n.has(e))
9
- throw TypeError("Cannot add the same private member more than once");
10
- n instanceof WeakSet ? n.add(e) : n.set(e, t);
11
- }, _ = (e, n, t, s) => (X(e, n, "write to private field"), s ? s.call(e, t) : n.set(e, t), t);
12
- var Ae = class extends Error {
13
- constructor(n, t) {
14
- super(t);
15
- g(this, "code");
16
- this.name = "PenpalError", this.code = n;
17
- }
18
- }, P = Ae, Ee = (e) => ({
19
- name: e.name,
20
- message: e.message,
21
- stack: e.stack,
22
- penpalCode: e instanceof P ? e.code : void 0
23
- }), we = ({
24
- name: e,
25
- message: n,
26
- stack: t,
27
- penpalCode: s
28
- }) => {
29
- const r = s ? new P(s, n) : new Error(n);
30
- return r.name = e, r.stack = t, r;
31
- }, Ie = Symbol("Reply"), G, re, Me = (re = class {
32
- constructor(e, n) {
33
- g(this, "value");
34
- g(this, "transferables");
35
- // Allows TypeScript to distinguish between an actual instance of this
36
- // class versus an object that looks structurally similar.
37
- // eslint-disable-next-line no-unused-private-class-members
38
- A(this, G, Ie);
39
- this.value = e, this.transferables = n == null ? void 0 : n.transferables;
40
- }
41
- }, G = new WeakMap(), re), Pe = Me, M = "penpal", W = (e) => typeof e == "object" && e !== null, ce = (e) => typeof e == "function", Ce = (e) => W(e) && e.namespace === M, V = (e) => e.type === "SYN", Z = (e) => e.type === "ACK1", B = (e) => e.type === "ACK2", de = (e) => e.type === "CALL", he = (e) => e.type === "REPLY", _e = (e) => e.type === "DESTROY", ue = (e, n = []) => {
42
- const t = [];
43
- for (const s of Object.keys(e)) {
44
- const r = e[s];
45
- ce(r) ? t.push([...n, s]) : W(r) && t.push(
46
- ...ue(r, [...n, s])
47
- );
48
- }
49
- return t;
50
- }, Oe = (e, n) => {
51
- const t = e.reduce(
52
- (s, r) => W(s) ? s[r] : void 0,
53
- n
54
- );
55
- return ce(t) ? t : void 0;
56
- }, T = (e) => e.join("."), ee = (e, n, t) => ({
57
- namespace: M,
58
- channel: e,
59
- type: "REPLY",
60
- callId: n,
61
- isError: !0,
62
- ...t instanceof Error ? { value: Ee(t), isSerializedErrorInstance: !0 } : { value: t }
63
- }), Se = (e, n, t, s) => {
64
- let r = !1;
65
- const v = async (u) => {
66
- if (r || !de(u))
67
- return;
68
- s == null || s(`Received ${T(u.methodPath)}() call`, u);
69
- const { methodPath: l, args: c, id: a } = u;
70
- let i, o;
71
- try {
72
- const f = Oe(l, n);
73
- if (!f)
74
- throw new P(
75
- "METHOD_NOT_FOUND",
76
- `Method \`${T(l)}\` is not found.`
77
- );
78
- let p = await f(...c);
79
- p instanceof Pe && (o = p.transferables, p = await p.value), i = {
80
- namespace: M,
81
- channel: t,
82
- type: "REPLY",
83
- callId: a,
84
- value: p
85
- };
86
- } catch (f) {
87
- i = ee(t, a, f);
88
- }
89
- if (!r)
90
- try {
91
- s == null || s(`Sending ${T(l)}() reply`, i), e.sendMessage(i, o);
92
- } catch (f) {
93
- throw f.name === "DataCloneError" && (i = ee(t, a, f), s == null || s(`Sending ${T(l)}() reply`, i), e.sendMessage(i)), f;
94
- }
95
- };
96
- return e.addMessageHandler(v), () => {
97
- r = !0, e.removeMessageHandler(v);
98
- };
99
- }, Re = Se, ie, le = ((ie = crypto.randomUUID) == null ? void 0 : ie.bind(crypto)) ?? (() => new Array(4).fill(0).map(
100
- () => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)
101
- ).join("-")), Te = Symbol("CallOptions"), J, ae, De = (ae = class {
102
- constructor(e) {
103
- g(this, "transferables");
104
- g(this, "timeout");
105
- // Allows TypeScript to distinguish between an actual instance of this
106
- // class versus an object that looks structurally similar.
107
- // eslint-disable-next-line no-unused-private-class-members
108
- A(this, J, Te);
109
- this.transferables = e == null ? void 0 : e.transferables, this.timeout = e == null ? void 0 : e.timeout;
110
- }
111
- }, J = new WeakMap(), ae), Ne = De, ke = /* @__PURE__ */ new Set(["apply", "call", "bind"]), fe = (e, n, t = []) => new Proxy(
112
- t.length ? () => {
113
- } : /* @__PURE__ */ Object.create(null),
114
- {
115
- get(s, r) {
116
- if (r !== "then")
117
- return t.length && ke.has(r) ? Reflect.get(s, r) : fe(e, n, [...t, r]);
118
- },
119
- apply(s, r, v) {
120
- return e(t, v);
121
- }
122
- }
123
- ), te = (e) => new P(
124
- "CONNECTION_DESTROYED",
125
- `Method call ${T(
126
- e
127
- )}() failed due to destroyed connection`
128
- ), Le = (e, n, t) => {
129
- let s = !1;
130
- const r = /* @__PURE__ */ new Map(), v = (c) => {
131
- if (!he(c))
132
- return;
133
- const { callId: a, value: i, isError: o, isSerializedErrorInstance: f } = c, p = r.get(a);
134
- p && (r.delete(a), t == null || t(
135
- `Received ${T(p.methodPath)}() call`,
136
- c
137
- ), o ? p.reject(
138
- f ? we(i) : i
139
- ) : p.resolve(i));
140
- };
141
- return e.addMessageHandler(v), {
142
- remoteProxy: fe((c, a) => {
143
- if (s)
144
- throw te(c);
145
- const i = le(), o = a[a.length - 1], f = o instanceof Ne, { timeout: p, transferables: b } = f ? o : {}, E = f ? a.slice(0, -1) : a;
146
- return new Promise((d, w) => {
147
- const C = p !== void 0 ? window.setTimeout(() => {
148
- r.delete(i), w(
149
- new P(
150
- "METHOD_CALL_TIMEOUT",
151
- `Method call ${T(
152
- c
153
- )}() timed out after ${p}ms`
154
- )
155
- );
156
- }, p) : void 0;
157
- r.set(i, { methodPath: c, resolve: d, reject: w, timeoutId: C });
158
- try {
159
- const y = {
160
- namespace: M,
161
- channel: n,
162
- type: "CALL",
163
- id: i,
164
- methodPath: c,
165
- args: E
166
- };
167
- t == null || t(`Sending ${T(c)}() call`, y), e.sendMessage(y, b);
168
- } catch (y) {
169
- w(
170
- new P("TRANSMISSION_FAILED", y.message)
171
- );
172
- }
173
- });
174
- }, t),
175
- destroy: () => {
176
- s = !0, e.removeMessageHandler(v);
177
- for (const { methodPath: c, reject: a, timeoutId: i } of r.values())
178
- clearTimeout(i), a(te(c));
179
- r.clear();
180
- }
181
- };
182
- }, xe = Le, He = () => {
183
- let e, n;
184
- return {
185
- promise: new Promise((s, r) => {
186
- e = s, n = r;
187
- }),
188
- resolve: e,
189
- reject: n
190
- };
191
- }, Ue = He, $e = class extends Error {
192
- constructor(e) {
193
- super(
194
- `You've hit a bug in Penpal. Please file an issue with the following information: ${e}`
195
- );
196
- }
197
- }, Y = $e, Q = "deprecated-penpal", je = (e) => W(e) && "penpal" in e, qe = (e) => e.split("."), ne = (e) => e.join("."), pe = (e) => new Y(
198
- `Unexpected message to translate: ${JSON.stringify(e)}`
199
- ), Fe = (e) => {
200
- if (e.penpal === "syn")
201
- return {
202
- namespace: M,
203
- channel: void 0,
204
- type: "SYN",
205
- participantId: Q
206
- };
207
- if (e.penpal === "ack")
208
- return {
209
- namespace: M,
210
- channel: void 0,
211
- type: "ACK2"
212
- };
213
- if (e.penpal === "call")
214
- return {
215
- namespace: M,
216
- channel: void 0,
217
- type: "CALL",
218
- // Actually converting the ID to a string would break communication.
219
- id: e.id,
220
- methodPath: qe(e.methodName),
221
- args: e.args
222
- };
223
- if (e.penpal === "reply")
224
- return e.resolution === "fulfilled" ? {
225
- namespace: M,
226
- channel: void 0,
227
- type: "REPLY",
228
- // Actually converting the ID to a string would break communication.
229
- callId: e.id,
230
- value: e.returnValue
231
- } : {
232
- namespace: M,
233
- channel: void 0,
234
- type: "REPLY",
235
- // Actually converting the ID to a string would break communication.
236
- callId: e.id,
237
- isError: !0,
238
- ...e.returnValueIsError ? {
239
- value: e.returnValue,
240
- isSerializedErrorInstance: !0
241
- } : {
242
- value: e.returnValue
243
- }
244
- };
245
- throw pe(e);
246
- }, ze = (e) => {
247
- if (Z(e))
248
- return {
249
- penpal: "synAck",
250
- methodNames: e.methodPaths.map(ne)
251
- };
252
- if (de(e))
253
- return {
254
- penpal: "call",
255
- // Actually converting the ID to a number would break communication.
256
- id: e.id,
257
- methodName: ne(e.methodPath),
258
- args: e.args
259
- };
260
- if (he(e))
261
- return e.isError ? {
262
- penpal: "reply",
263
- // Actually converting the ID to a number would break communication.
264
- id: e.callId,
265
- resolution: "rejected",
266
- ...e.isSerializedErrorInstance ? {
267
- returnValue: e.value,
268
- returnValueIsError: !0
269
- } : { returnValue: e.value }
270
- } : {
271
- penpal: "reply",
272
- // Actually converting the ID to a number would break communication.
273
- id: e.callId,
274
- resolution: "fulfilled",
275
- returnValue: e.value
276
- };
277
- throw pe(e);
278
- }, Ve = ({
279
- messenger: e,
280
- methods: n,
281
- timeout: t,
282
- channel: s,
283
- log: r
284
- }) => {
285
- const v = le();
286
- let u;
287
- const l = [];
288
- let c = !1;
289
- const a = ue(n), { promise: i, resolve: o, reject: f } = Ue(), p = t !== void 0 ? setTimeout(() => {
290
- f(
291
- new P(
292
- "CONNECTION_TIMEOUT",
293
- `Connection timed out after ${t}ms`
294
- )
295
- );
296
- }, t) : void 0, b = () => {
297
- for (const m of l)
298
- m();
299
- }, E = () => {
300
- if (c)
301
- return;
302
- l.push(Re(e, n, s, r));
303
- const { remoteProxy: m, destroy: D } = xe(e, s, r);
304
- l.push(D), clearTimeout(p), c = !0, o({
305
- remoteProxy: m,
306
- destroy: b
307
- });
308
- }, d = () => {
309
- const m = {
310
- namespace: M,
311
- type: "SYN",
312
- channel: s,
313
- participantId: v
314
- };
315
- r == null || r("Sending handshake SYN", m);
316
- try {
317
- e.sendMessage(m);
318
- } catch (D) {
319
- f(new P("TRANSMISSION_FAILED", D.message));
320
- }
321
- }, w = (m) => {
322
- if (r == null || r("Received handshake SYN", m), m.participantId === u && // TODO: Used for backward-compatibility. Remove in next major version.
323
- u !== Q || (u = m.participantId, d(), !(v > u || // TODO: Used for backward-compatibility. Remove in next major version.
324
- u === Q)))
325
- return;
326
- const z = {
327
- namespace: M,
328
- channel: s,
329
- type: "ACK1",
330
- methodPaths: a
331
- };
332
- r == null || r("Sending handshake ACK1", z);
333
- try {
334
- e.sendMessage(z);
335
- } catch (ye) {
336
- f(new P("TRANSMISSION_FAILED", ye.message));
337
- return;
338
- }
339
- }, C = (m) => {
340
- r == null || r("Received handshake ACK1", m);
341
- const D = {
342
- namespace: M,
343
- channel: s,
344
- type: "ACK2"
345
- };
346
- r == null || r("Sending handshake ACK2", D);
347
- try {
348
- e.sendMessage(D);
349
- } catch (z) {
350
- f(new P("TRANSMISSION_FAILED", z.message));
351
- return;
352
- }
353
- E();
354
- }, y = (m) => {
355
- r == null || r("Received handshake ACK2", m), E();
356
- }, F = (m) => {
357
- V(m) && w(m), Z(m) && C(m), B(m) && y(m);
358
- };
359
- return e.addMessageHandler(F), l.push(() => e.removeMessageHandler(F)), d(), i;
360
- }, Ye = Ve, Ke = (e) => {
361
- let n = !1, t;
362
- return (...s) => (n || (n = !0, t = e(...s)), t);
363
- }, We = Ke, se = /* @__PURE__ */ new WeakSet(), Be = ({
364
- messenger: e,
365
- methods: n = {},
366
- timeout: t,
367
- channel: s,
368
- log: r
369
- }) => {
370
- if (!e)
371
- throw new P("INVALID_ARGUMENT", "messenger must be defined");
372
- if (se.has(e))
373
- throw new P(
374
- "INVALID_ARGUMENT",
375
- "A messenger can only be used for a single connection"
376
- );
377
- se.add(e);
378
- const v = [e.destroy], u = We((a) => {
379
- if (a) {
380
- const i = {
381
- namespace: M,
382
- channel: s,
383
- type: "DESTROY"
384
- };
385
- try {
386
- e.sendMessage(i);
387
- } catch {
388
- }
389
- }
390
- for (const i of v)
391
- i();
392
- r == null || r("Connection destroyed");
393
- }), l = (a) => Ce(a) && a.channel === s;
394
- return {
395
- promise: (async () => {
396
- try {
397
- e.initialize({ log: r, validateReceivedMessage: l }), e.addMessageHandler((o) => {
398
- _e(o) && u(!1);
399
- });
400
- const { remoteProxy: a, destroy: i } = await Ye({
401
- messenger: e,
402
- methods: n,
403
- timeout: t,
404
- channel: s,
405
- log: r
406
- });
407
- return v.push(i), a;
408
- } catch (a) {
409
- throw u(!0), a;
410
- }
411
- })(),
412
- // Why we don't reject the connection promise when consumer calls destroy():
413
- // https://github.com/Aaronius/penpal/issues/51
414
- destroy: () => {
415
- u(!0);
416
- }
417
- };
418
- }, Qe = Be, S, N, x, H, k, R, I, L, K, U, j, q, $, oe, Ge = (oe = class {
419
- constructor({ remoteWindow: e, allowedOrigins: n }) {
420
- A(this, S, void 0);
421
- A(this, N, void 0);
422
- A(this, x, void 0);
423
- A(this, H, void 0);
424
- A(this, k, void 0);
425
- A(this, R, /* @__PURE__ */ new Set());
426
- A(this, I, void 0);
427
- // TODO: Used for backward-compatibility. Remove in next major version.
428
- A(this, L, !1);
429
- g(this, "initialize", ({
430
- log: e,
431
- validateReceivedMessage: n
432
- }) => {
433
- _(this, x, e), _(this, H, n), window.addEventListener("message", h(this, q));
434
- });
435
- g(this, "sendMessage", (e, n) => {
436
- if (V(e)) {
437
- const t = h(this, U).call(this, e);
438
- h(this, S).postMessage(e, {
439
- targetOrigin: t,
440
- transfer: n
441
- });
442
- return;
443
- }
444
- if (Z(e) || // If the child is using a previous version of Penpal, we need to
445
- // downgrade the message and send it through the window rather than
446
- // the port because older versions of Penpal don't use MessagePorts.
447
- h(this, L)) {
448
- const t = h(this, L) ? ze(e) : e, s = h(this, U).call(this, e);
449
- h(this, S).postMessage(t, {
450
- targetOrigin: s,
451
- transfer: n
452
- });
453
- return;
454
- }
455
- if (B(e)) {
456
- const { port1: t, port2: s } = new MessageChannel();
457
- _(this, I, t), t.addEventListener("message", h(this, $)), t.start();
458
- const r = [s, ...n || []], v = h(this, U).call(this, e);
459
- h(this, S).postMessage(e, {
460
- targetOrigin: v,
461
- transfer: r
462
- });
463
- return;
464
- }
465
- if (h(this, I)) {
466
- h(this, I).postMessage(e, {
467
- transfer: n
468
- });
469
- return;
470
- }
471
- throw new Y("Port is undefined");
472
- });
473
- g(this, "addMessageHandler", (e) => {
474
- h(this, R).add(e);
475
- });
476
- g(this, "removeMessageHandler", (e) => {
477
- h(this, R).delete(e);
478
- });
479
- g(this, "destroy", () => {
480
- window.removeEventListener("message", h(this, q)), h(this, j).call(this), h(this, R).clear();
481
- });
482
- A(this, K, (e) => h(this, N).some(
483
- (n) => n instanceof RegExp ? n.test(e) : n === e || n === "*"
484
- ));
485
- A(this, U, (e) => {
486
- if (V(e))
487
- return "*";
488
- if (!h(this, k))
489
- throw new Y("Concrete remote origin not set");
490
- return h(this, k) === "null" && h(this, N).includes("*") ? "*" : h(this, k);
491
- });
492
- A(this, j, () => {
493
- var e, n;
494
- (e = h(this, I)) == null || e.removeEventListener("message", h(this, $)), (n = h(this, I)) == null || n.close(), _(this, I, void 0);
495
- });
496
- A(this, q, ({
497
- source: e,
498
- origin: n,
499
- ports: t,
500
- data: s
501
- }) => {
502
- var r, v, u;
503
- if (e === h(this, S) && (je(s) && ((r = h(this, x)) == null || r.call(
504
- this,
505
- "Please upgrade the child window to the latest version of Penpal."
506
- ), _(this, L, !0), s = Fe(s)), !!((v = h(this, H)) != null && v.call(this, s)))) {
507
- if (!h(this, K).call(this, n)) {
508
- (u = h(this, x)) == null || u.call(
509
- this,
510
- `Received a message from origin \`${n}\` which did not match allowed origins \`[${h(this, N).join(", ")}]\``
511
- );
512
- return;
513
- }
514
- if (V(s) && (h(this, j).call(this), _(this, k, n)), B(s) && // Previous versions of Penpal don't use MessagePorts and do all
515
- // communication through the window.
516
- !h(this, L)) {
517
- if (_(this, I, t[0]), !h(this, I))
518
- throw new Y("No port received on ACK2");
519
- h(this, I).addEventListener("message", h(this, $)), h(this, I).start();
520
- }
521
- for (const l of h(this, R))
522
- l(s);
523
- }
524
- });
525
- A(this, $, ({ data: e }) => {
526
- var n;
527
- if ((n = h(this, H)) != null && n.call(this, e))
528
- for (const t of h(this, R))
529
- t(e);
530
- });
531
- if (!e)
532
- throw new P("INVALID_ARGUMENT", "remoteWindow must be defined");
533
- _(this, S, e), _(this, N, n != null && n.length ? n : [window.origin]);
534
- }
535
- }, S = new WeakMap(), N = new WeakMap(), x = new WeakMap(), H = new WeakMap(), k = new WeakMap(), R = new WeakMap(), I = new WeakMap(), L = new WeakMap(), K = new WeakMap(), U = new WeakMap(), j = new WeakMap(), q = new WeakMap(), $ = new WeakMap(), oe), Je = Ge, Ze = (e) => (...n) => {
536
- console.log(`✍️ %c${e}%c`, "font-weight: bold;", "", ...n);
537
- }, Xe = Ze;
538
- function et(e) {
539
- return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, "default") ? e.default : e;
540
- }
541
- var ve = { exports: {} };
542
- (function(e) {
543
- var n = Object.prototype.hasOwnProperty, t = "~";
544
- function s() {
545
- }
546
- Object.create && (s.prototype = /* @__PURE__ */ Object.create(null), new s().__proto__ || (t = !1));
547
- function r(c, a, i) {
548
- this.fn = c, this.context = a, this.once = i || !1;
549
- }
550
- function v(c, a, i, o, f) {
551
- if (typeof i != "function")
552
- throw new TypeError("The listener must be a function");
553
- var p = new r(i, o || c, f), b = t ? t + a : a;
554
- return c._events[b] ? c._events[b].fn ? c._events[b] = [c._events[b], p] : c._events[b].push(p) : (c._events[b] = p, c._eventsCount++), c;
555
- }
556
- function u(c, a) {
557
- --c._eventsCount === 0 ? c._events = new s() : delete c._events[a];
558
- }
559
- function l() {
560
- this._events = new s(), this._eventsCount = 0;
561
- }
562
- l.prototype.eventNames = function() {
563
- var a = [], i, o;
564
- if (this._eventsCount === 0)
565
- return a;
566
- for (o in i = this._events)
567
- n.call(i, o) && a.push(t ? o.slice(1) : o);
568
- return Object.getOwnPropertySymbols ? a.concat(Object.getOwnPropertySymbols(i)) : a;
569
- }, l.prototype.listeners = function(a) {
570
- var i = t ? t + a : a, o = this._events[i];
571
- if (!o)
572
- return [];
573
- if (o.fn)
574
- return [o.fn];
575
- for (var f = 0, p = o.length, b = new Array(p); f < p; f++)
576
- b[f] = o[f].fn;
577
- return b;
578
- }, l.prototype.listenerCount = function(a) {
579
- var i = t ? t + a : a, o = this._events[i];
580
- return o ? o.fn ? 1 : o.length : 0;
581
- }, l.prototype.emit = function(a, i, o, f, p, b) {
582
- var E = t ? t + a : a;
583
- if (!this._events[E])
584
- return !1;
585
- var d = this._events[E], w = arguments.length, C, y;
586
- if (d.fn) {
587
- switch (d.once && this.removeListener(a, d.fn, void 0, !0), w) {
588
- case 1:
589
- return d.fn.call(d.context), !0;
590
- case 2:
591
- return d.fn.call(d.context, i), !0;
592
- case 3:
593
- return d.fn.call(d.context, i, o), !0;
594
- case 4:
595
- return d.fn.call(d.context, i, o, f), !0;
596
- case 5:
597
- return d.fn.call(d.context, i, o, f, p), !0;
598
- case 6:
599
- return d.fn.call(d.context, i, o, f, p, b), !0;
600
- }
601
- for (y = 1, C = new Array(w - 1); y < w; y++)
602
- C[y - 1] = arguments[y];
603
- d.fn.apply(d.context, C);
604
- } else {
605
- var F = d.length, m;
606
- for (y = 0; y < F; y++)
607
- switch (d[y].once && this.removeListener(a, d[y].fn, void 0, !0), w) {
608
- case 1:
609
- d[y].fn.call(d[y].context);
610
- break;
611
- case 2:
612
- d[y].fn.call(d[y].context, i);
613
- break;
614
- case 3:
615
- d[y].fn.call(d[y].context, i, o);
616
- break;
617
- case 4:
618
- d[y].fn.call(d[y].context, i, o, f);
619
- break;
620
- default:
621
- if (!C)
622
- for (m = 1, C = new Array(w - 1); m < w; m++)
623
- C[m - 1] = arguments[m];
624
- d[y].fn.apply(d[y].context, C);
625
- }
626
- }
627
- return !0;
628
- }, l.prototype.on = function(a, i, o) {
629
- return v(this, a, i, o, !1);
630
- }, l.prototype.once = function(a, i, o) {
631
- return v(this, a, i, o, !0);
632
- }, l.prototype.removeListener = function(a, i, o, f) {
633
- var p = t ? t + a : a;
634
- if (!this._events[p])
635
- return this;
636
- if (!i)
637
- return u(this, p), this;
638
- var b = this._events[p];
639
- if (b.fn)
640
- b.fn === i && (!f || b.once) && (!o || b.context === o) && u(this, p);
641
- else {
642
- for (var E = 0, d = [], w = b.length; E < w; E++)
643
- (b[E].fn !== i || f && !b[E].once || o && b[E].context !== o) && d.push(b[E]);
644
- d.length ? this._events[p] = d.length === 1 ? d[0] : d : u(this, p);
645
- }
646
- return this;
647
- }, l.prototype.removeAllListeners = function(a) {
648
- var i;
649
- return a ? (i = t ? t + a : a, this._events[i] && u(this, i)) : (this._events = new s(), this._eventsCount = 0), this;
650
- }, l.prototype.off = l.prototype.removeListener, l.prototype.addListener = l.prototype.on, l.prefixed = t, l.EventEmitter = l, e.exports = l;
651
- })(ve);
652
- var tt = ve.exports;
653
- const nt = /* @__PURE__ */ et(tt);
654
- class ge extends nt {
655
- on(n, t, s) {
656
- return super.on(n, t, s);
657
- }
658
- once(n, t, s) {
659
- return super.once(n, t, s);
660
- }
661
- off(n, t, s) {
662
- return super.off(n, t, s);
663
- }
664
- emit(n, ...t) {
665
- return super.emit(n, ...t);
666
- }
667
- }
668
- class st {
669
- constructor() {
670
- g(this, "queue", []);
671
- g(this, "maxSize", 100);
672
- }
673
- enqueue(n, t = 3) {
674
- this.queue.length >= this.maxSize && this.queue.shift();
675
- const s = {
676
- ...n,
677
- retryCount: 0,
678
- maxRetries: t
679
- };
680
- return this.queue.push(s), n.messageId;
681
- }
682
- dequeue() {
683
- return this.queue.shift();
684
- }
685
- hasMessages() {
686
- return this.queue.length > 0;
687
- }
688
- getMessageById(n) {
689
- return this.queue.find((t) => t.messageId === n);
690
- }
691
- removeMessageById(n) {
692
- const t = this.queue.findIndex((s) => s.messageId === n);
693
- t !== -1 && this.queue.splice(t, 1);
694
- }
695
- clear() {
696
- this.queue = [];
697
- }
698
- }
699
- class rt {
700
- constructor(n, t = !1) {
701
- this.context = n, this.debug = t;
702
- }
703
- formatMessage(n, ...t) {
704
- return [`[${(/* @__PURE__ */ new Date()).toISOString()}] [${this.context}] [${n}]`, ...t];
705
- }
706
- info(...n) {
707
- console.info(...this.formatMessage("INFO", ...n));
708
- }
709
- debug(...n) {
710
- this.debug && console.debug(...this.formatMessage("DEBUG", ...n));
711
- }
712
- warn(...n) {
713
- console.warn(...this.formatMessage("WARN", ...n));
714
- }
715
- error(...n) {
716
- console.error(...this.formatMessage("ERROR", ...n));
717
- }
718
- }
719
- let it = (e) => crypto.getRandomValues(new Uint8Array(e)), at = (e, n, t) => {
720
- let s = (2 << Math.log2(e.length - 1)) - 1, r = -~(1.6 * s * n / e.length);
721
- return (v = n) => {
722
- let u = "";
723
- for (; ; ) {
724
- let l = t(r), c = r | 0;
725
- for (; c--; )
726
- if (u += e[l[c] & s] || "", u.length >= v)
727
- return u;
728
- }
729
- };
730
- }, ot = (e, n = 21) => at(e, n | 0, it);
731
- const ct = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", dt = ot(ct, 12);
732
- class ht extends ge {
733
- constructor(t, s = {}) {
734
- super();
735
- g(this, "connection", null);
736
- g(this, "iframe");
737
- g(this, "options");
738
- g(this, "messageQueue");
739
- g(this, "logger");
740
- g(this, "isConnected", !1);
741
- g(this, "reconnectAttempts", 0);
742
- g(this, "maxReconnectAttempts", 3);
743
- this.iframe = t, this.options = {
744
- timeout: 3e4,
745
- debug: !1,
746
- retryCount: 3,
747
- retryDelay: 1e3,
748
- childOrigin: "*",
749
- ...s
750
- }, this.messageQueue = new st(), this.logger = new rt("PenpalBridge", this.options.debug);
751
- }
752
- /**
753
- * 建立连接
754
- */
755
- async connect(t = {}) {
756
- try {
757
- this.logger.info("正在建立连接...");
758
- const s = new Je({
759
- remoteWindow: this.iframe,
760
- // Defaults to the current origin.
761
- allowedOrigins: ["http://127.0.0.1:3000"]
762
- // Alternatively,
763
- // allowedOrigins: [new Url(iframe.src).origin]
764
- });
765
- this.connection = Qe({
766
- messenger: s,
767
- // Methods the parent window is exposing to the iframe window.
768
- methods: {
769
- add(r, v) {
770
- return r + v;
771
- },
772
- emitEvent: (r, v) => {
773
- this.emit(r, v);
774
- },
775
- // 接收来自画板的请求
776
- ...t
777
- },
778
- timeout: this.options.timeout,
779
- // childOrigin: this.options.childOrigin,
780
- log: Xe("parent")
781
- }), await this.connection.promise, this.isConnected = !0, this.reconnectAttempts = 0, await this.processQueuedMessages(), this.logger.info("连接建立成功"), this.emit("connected");
782
- } catch (s) {
783
- throw this.logger.error("连接失败:", s), await this.handleReconnect(), s;
784
- }
785
- }
786
- /**
787
- * 发送消息到画板
788
- */
789
- async send(t, s) {
790
- var v;
791
- const r = {
792
- action: t,
793
- params: s,
794
- timestamp: Date.now(),
795
- messageId: dt()
796
- };
797
- if (!this.isConnected)
798
- throw this.messageQueue.enqueue(r), new Error("Connection not ready, message queued");
799
- try {
800
- if (this.logger.debug("发送消息:", r), !((v = this.connection) != null && v.child))
801
- throw new Error("连接未就绪");
802
- const u = await this.connection.child.handleMessage(r);
803
- return this.logger.debug("收到响应:", u), this.validateResponse(u);
804
- } catch (u) {
805
- throw this.logger.error("发送消息失败:", u), this.messageQueue.enqueue(r), u;
806
- }
807
- }
808
- /**
809
- * 处理队列中的消息
810
- */
811
- async processQueuedMessages() {
812
- for (; this.messageQueue.hasMessages(); ) {
813
- const t = this.messageQueue.dequeue();
814
- if (t)
815
- try {
816
- await this.send(t.action, t.params);
817
- } catch (s) {
818
- this.logger.warn("队列消息发送失败:", s), this.messageQueue.enqueue(t);
819
- }
820
- }
821
- }
822
- /**
823
- * 重连机制
824
- */
825
- async handleReconnect() {
826
- if (this.reconnectAttempts >= this.maxReconnectAttempts) {
827
- this.logger.error("重连次数达到上限"), this.emit("connection-lost");
828
- return;
829
- }
830
- this.reconnectAttempts++, this.logger.info(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`), await new Promise(
831
- (t) => setTimeout(t, this.options.retryDelay * this.reconnectAttempts)
832
- );
833
- try {
834
- await this.connect();
835
- } catch {
836
- await this.handleReconnect();
837
- }
838
- }
839
- /**
840
- * 验证响应格式
841
- */
842
- validateResponse(t) {
843
- if (!t || t.success === void 0)
844
- throw new Error("Invalid response format");
845
- if (!t.success) {
846
- const s = t.error || { code: "UNKNOWN", message: "Unknown error" };
847
- throw new Error(`${s.code}: ${s.message}`);
848
- }
849
- return t.data;
850
- }
851
- /**
852
- * 断开连接
853
- */
854
- disconnect() {
855
- this.connection && (this.connection.destroy(), this.isConnected = !1, this.emit("disconnected"), this.logger.info("连接已断开"));
856
- }
857
- /**
858
- * 获取连接状态
859
- */
860
- getConnectionStatus() {
861
- return this.isConnected;
862
- }
863
- }
864
- class ut {
865
- constructor(n) {
866
- this.bridge = n;
867
- }
868
- async initialize(n) {
869
- return this.bridge.send("canvas.initialize", n);
870
- }
871
- async setData(n) {
872
- return this.bridge.send("canvas.setData", n);
873
- }
874
- async getData() {
875
- return this.bridge.send("canvas.getData");
876
- }
877
- async clear() {
878
- return this.bridge.send("canvas.clear");
879
- }
880
- async undo() {
881
- return this.bridge.send("canvas.undo");
882
- }
883
- async redo() {
884
- return this.bridge.send("canvas.redo");
885
- }
886
- async export(n) {
887
- return this.bridge.send("canvas.export", { format: n });
888
- }
889
- async save() {
890
- return this.bridge.send("canvas.save");
891
- }
892
- async invoke(n, ...t) {
893
- return this.bridge.send("canvas.invoke", { method: n, args: t });
894
- }
895
- async setZoom(n) {
896
- return this.bridge.send("canvas.setZoom", { zoom: n });
897
- }
898
- async getSnapshot() {
899
- return this.bridge.send("canvas.getSnapshot");
900
- }
901
- }
902
- class lt {
903
- constructor(n) {
904
- this.bridge = n;
905
- }
906
- async setAbilities(n) {
907
- return this.bridge.send("abilities.set", n);
908
- }
909
- async getAbilities() {
910
- return this.bridge.send("abilities.get");
911
- }
912
- async enableAbility(n) {
913
- return this.bridge.send("abilities.enable", { name: n });
914
- }
915
- async disableAbility(n) {
916
- return this.bridge.send("abilities.disable", { name: n });
917
- }
918
- }
919
- class ft {
920
- constructor(n) {
921
- this.bridge = n;
922
- }
923
- async setTheme(n) {
924
- return this.bridge.send("theme.set", { theme: n });
925
- }
926
- async getCurrentTheme() {
927
- return this.bridge.send("theme.get");
928
- }
929
- async updateToken(n) {
930
- return this.bridge.send("theme.updateToken", n);
931
- }
932
- }
933
- class pt {
934
- constructor(n) {
935
- this.bridge = n;
936
- }
937
- async setLocale(n, t) {
938
- return this.bridge.send("i18n.setLocale", { locale: n, messages: t });
939
- }
940
- async getCurrentLocale() {
941
- return this.bridge.send("i18n.getLocale");
942
- }
943
- async updateMessages(n) {
944
- return this.bridge.send("i18n.updateMessages", n);
945
- }
946
- }
947
- class vt {
948
- constructor(n) {
949
- this.bridge = n;
950
- }
951
- async validateToken() {
952
- return this.bridge.send("auth.validateToken");
953
- }
954
- }
955
- const O = {
956
- READY: "ready",
957
- CHANGE: "change",
958
- SAVE: "save",
959
- ERROR: "error",
960
- SELECTION_CHANGED: "selection-changed",
961
- CONNECTED: "connected",
962
- DISCONNECTED: "disconnected",
963
- // 画板生命周期事件
964
- LOADED: "loaded",
965
- BEFORE_UNLOAD: "before-unload",
966
- // 画板操作事件
967
- OBJECT_ADDED: "object-added",
968
- OBJECT_MODIFIED: "object-modified",
969
- OBJECT_REMOVED: "object-removed",
970
- // 用户交互事件
971
- MOUSE_DOWN: "mouse-down",
972
- MOUSE_UP: "mouse-up",
973
- MOUSE_MOVE: "mouse-move",
974
- KEY_DOWN: "key-down",
975
- KEY_UP: "key-up"
976
- };
977
- class gt extends ge {
978
- constructor(t, s) {
979
- super();
980
- g(this, "bridge");
981
- g(this, "canvasAPI");
982
- g(this, "abilityAPI");
983
- g(this, "themeAPI");
984
- g(this, "i18nAPI");
985
- g(this, "authAPI");
986
- g(this, "config");
987
- g(this, "iframe");
988
- g(this, "isInitialized", !1);
989
- this.validateConfig(s), this.config = s, this.iframe = t, this.bridge = new ht(t, {
990
- debug: s.debug || !1,
991
- timeout: 3e4,
992
- childOrigin: this.extractOrigin(t.src)
993
- }), this.canvasAPI = new ut(this.bridge), this.abilityAPI = new lt(this.bridge), this.themeAPI = new ft(this.bridge), this.i18nAPI = new pt(this.bridge), this.authAPI = new vt(this.bridge), this.setupEventHandlers();
994
- }
995
- /**
996
- * 初始化SDK
997
- */
998
- async init() {
999
- if (!this.isInitialized)
1000
- try {
1001
- await this.bridge.connect({
1002
- getConfig: () => this.config,
1003
- log: (t, s) => {
1004
- console.log(`[Canvas ${t.toUpperCase()}]`, s);
1005
- }
1006
- }), await this.canvasAPI.initialize(this.config), this.config.abilities && await this.abilityAPI.setAbilities(this.config.abilities), this.config.theme && await this.themeAPI.setTheme(this.config.theme), this.config.locale && await this.i18nAPI.setLocale(this.config.locale, this.config.messages), this.isInitialized = !0, this.emit(O.READY);
1007
- } catch (t) {
1008
- throw this.emit(O.ERROR, t), t;
1009
- }
1010
- }
1011
- // Canvas 操作方法
1012
- get canvas() {
1013
- return {
1014
- setData: (t) => this.canvasAPI.setData(t),
1015
- getData: () => this.canvasAPI.getData(),
1016
- clear: () => this.canvasAPI.clear(),
1017
- undo: () => this.canvasAPI.undo(),
1018
- redo: () => this.canvasAPI.redo(),
1019
- export: (t = "png") => this.canvasAPI.export(t),
1020
- save: () => this.canvasAPI.save(),
1021
- setZoom: (t) => this.canvasAPI.setZoom(t),
1022
- getSnapshot: () => this.canvasAPI.getSnapshot(),
1023
- invoke: (t, ...s) => this.canvasAPI.invoke(t, ...s)
1024
- };
1025
- }
1026
- // 能力管理
1027
- get abilities() {
1028
- return {
1029
- set: (t) => this.abilityAPI.setAbilities(t),
1030
- get: () => this.abilityAPI.getAbilities(),
1031
- enable: (t) => this.abilityAPI.enableAbility(t),
1032
- disable: (t) => this.abilityAPI.disableAbility(t),
1033
- updateConfig: (t, s) => this.abilityAPI.updateAbilityConfig(t, s)
1034
- };
1035
- }
1036
- // 主题管理
1037
- get theme() {
1038
- return {
1039
- set: (t) => this.themeAPI.setTheme(t),
1040
- get: () => this.themeAPI.getCurrentTheme(),
1041
- updateToken: (t) => this.themeAPI.updateToken(t),
1042
- reset: () => this.themeAPI.resetTheme()
1043
- };
1044
- }
1045
- // 国际化管理
1046
- get i18n() {
1047
- return {
1048
- setLocale: (t, s) => this.i18nAPI.setLocale(t, s),
1049
- getLocale: () => this.i18nAPI.getCurrentLocale(),
1050
- updateMessages: (t) => this.i18nAPI.updateMessages(t),
1051
- getMessages: () => this.i18nAPI.getMessages(),
1052
- getTranslation: (t) => this.i18nAPI.getTranslation(t)
1053
- };
1054
- }
1055
- // 鉴权管理
1056
- get auth() {
1057
- return {
1058
- validateToken: () => this.authAPI.validateToken(),
1059
- refreshToken: (t) => this.authAPI.refreshToken(t),
1060
- getTokenInfo: () => this.authAPI.getTokenInfo()
1061
- };
1062
- }
1063
- // 工具方法
1064
- get utils() {
1065
- return {
1066
- getConnectionStatus: () => this.bridge.getConnectionStatus(),
1067
- disconnect: () => this.bridge.disconnect(),
1068
- reconnect: async () => {
1069
- this.bridge.disconnect(), this.isInitialized = !1, await this.init();
1070
- },
1071
- isInitialized: () => this.isInitialized
1072
- };
1073
- }
1074
- setupEventHandlers() {
1075
- this.bridge.on("canvas-change", (t) => {
1076
- this.emit(O.CHANGE, t);
1077
- }), this.bridge.on("canvas-save", (t) => {
1078
- this.emit(O.SAVE, t);
1079
- }), this.bridge.on("canvas-error", (t) => {
1080
- this.emit(O.ERROR, t);
1081
- }), this.bridge.on("canvas-selection-changed", (t) => {
1082
- this.emit(O.SELECTION_CHANGED, t);
1083
- }), this.bridge.on("connected", () => {
1084
- console.log("链接建立成功"), this.emit(O.CONNECTED);
1085
- }), this.bridge.on("disconnected", () => {
1086
- console.log("链接断开"), this.emit(O.DISCONNECTED);
1087
- });
1088
- }
1089
- validateConfig(t) {
1090
- if (!t.token)
1091
- throw new Error("Token is required");
1092
- if (t.abilities) {
1093
- const s = ["text", "image", "barcode", "multiLayout", "shape", "qrCode"];
1094
- Object.keys(t.abilities).forEach((r) => {
1095
- s.includes(r) || console.warn(`Unknown ability: ${r}`);
1096
- });
1097
- }
1098
- }
1099
- extractOrigin(t) {
1100
- try {
1101
- return new URL(t).origin;
1102
- } catch {
1103
- return "*";
1104
- }
1105
- }
1106
- }
1107
- function mt(e, n) {
1108
- return new gt(e, n);
1109
- }
1110
- export {
1111
- O as CANVAS_EVENTS,
1112
- gt as NiimbotCanvasSDK,
1113
- mt as createCanvas
1114
- };
1115
- //# sourceMappingURL=niimbot-canvas-sdk.es.js.map