penpal 7.0.3 → 7.0.4

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 (111) hide show
  1. package/dist/penpal.cjs +953 -0
  2. package/dist/penpal.cjs.map +1 -0
  3. package/dist/penpal.d.cts +234 -0
  4. package/dist/penpal.d.ts +234 -0
  5. package/dist/penpal.js +890 -1033
  6. package/dist/penpal.js.map +1 -0
  7. package/dist/penpal.min.js +1 -1
  8. package/dist/penpal.min.js.map +1 -1
  9. package/dist/penpal.mjs +943 -0
  10. package/dist/penpal.mjs.map +1 -0
  11. package/package.json +13 -21
  12. package/cjs/CallOptions.d.ts +0 -10
  13. package/cjs/CallOptions.js +0 -16
  14. package/cjs/ErrorCodeObj.d.ts +0 -9
  15. package/cjs/ErrorCodeObj.js +0 -14
  16. package/cjs/PenpalBugError.d.ts +0 -8
  17. package/cjs/PenpalBugError.js +0 -12
  18. package/cjs/PenpalError.d.ts +0 -6
  19. package/cjs/PenpalError.js +0 -11
  20. package/cjs/Reply.d.ts +0 -9
  21. package/cjs/Reply.js +0 -16
  22. package/cjs/backwardCompatibility.d.ts +0 -56
  23. package/cjs/backwardCompatibility.js +0 -134
  24. package/cjs/connect.d.ts +0 -33
  25. package/cjs/connect.js +0 -78
  26. package/cjs/connectCallHandler.d.ts +0 -8
  27. package/cjs/connectCallHandler.js +0 -90
  28. package/cjs/connectRemoteProxy.d.ts +0 -12
  29. package/cjs/connectRemoteProxy.js +0 -139
  30. package/cjs/debug.d.ts +0 -3
  31. package/cjs/debug.js +0 -8
  32. package/cjs/errorSerialization.d.ts +0 -9
  33. package/cjs/errorSerialization.js +0 -26
  34. package/cjs/generateId.d.ts +0 -8
  35. package/cjs/generateId.js +0 -11
  36. package/cjs/getPromiseWithResolvers.d.ts +0 -6
  37. package/cjs/getPromiseWithResolvers.js +0 -19
  38. package/cjs/guards.d.ts +0 -10
  39. package/cjs/guards.js +0 -40
  40. package/cjs/index.d.ts +0 -12
  41. package/cjs/index.js +0 -21
  42. package/cjs/indexForBundle.d.ts +0 -31
  43. package/cjs/indexForBundle.js +0 -22
  44. package/cjs/messengers/Messenger.d.ts +0 -14
  45. package/cjs/messengers/Messenger.js +0 -2
  46. package/cjs/messengers/PortMessenger.d.ts +0 -21
  47. package/cjs/messengers/PortMessenger.js +0 -47
  48. package/cjs/messengers/WindowMessenger.d.ts +0 -29
  49. package/cjs/messengers/WindowMessenger.js +0 -178
  50. package/cjs/messengers/WorkerMessenger.d.ts +0 -23
  51. package/cjs/messengers/WorkerMessenger.js +0 -86
  52. package/cjs/methodSerialization.d.ts +0 -22
  53. package/cjs/methodSerialization.js +0 -48
  54. package/cjs/namespace.d.ts +0 -2
  55. package/cjs/namespace.js +0 -3
  56. package/cjs/once.d.ts +0 -2
  57. package/cjs/once.js +0 -15
  58. package/cjs/shakeHands.d.ts +0 -76
  59. package/cjs/shakeHands.js +0 -190
  60. package/cjs/types.d.ts +0 -89
  61. package/cjs/types.js +0 -2
  62. package/lib/CallOptions.d.ts +0 -10
  63. package/lib/CallOptions.js +0 -14
  64. package/lib/ErrorCodeObj.d.ts +0 -9
  65. package/lib/ErrorCodeObj.js +0 -12
  66. package/lib/PenpalBugError.d.ts +0 -8
  67. package/lib/PenpalBugError.js +0 -10
  68. package/lib/PenpalError.d.ts +0 -6
  69. package/lib/PenpalError.js +0 -9
  70. package/lib/Reply.d.ts +0 -9
  71. package/lib/Reply.js +0 -14
  72. package/lib/backwardCompatibility.d.ts +0 -56
  73. package/lib/backwardCompatibility.js +0 -128
  74. package/lib/connect.d.ts +0 -33
  75. package/lib/connect.js +0 -76
  76. package/lib/connectCallHandler.d.ts +0 -8
  77. package/lib/connectCallHandler.js +0 -88
  78. package/lib/connectRemoteProxy.d.ts +0 -12
  79. package/lib/connectRemoteProxy.js +0 -137
  80. package/lib/debug.d.ts +0 -3
  81. package/lib/debug.js +0 -6
  82. package/lib/errorSerialization.d.ts +0 -9
  83. package/lib/errorSerialization.js +0 -21
  84. package/lib/generateId.d.ts +0 -8
  85. package/lib/generateId.js +0 -9
  86. package/lib/getPromiseWithResolvers.d.ts +0 -6
  87. package/lib/getPromiseWithResolvers.js +0 -17
  88. package/lib/guards.d.ts +0 -10
  89. package/lib/guards.js +0 -28
  90. package/lib/index.d.ts +0 -12
  91. package/lib/index.js +0 -9
  92. package/lib/indexForBundle.d.ts +0 -31
  93. package/lib/indexForBundle.js +0 -20
  94. package/lib/messengers/Messenger.d.ts +0 -14
  95. package/lib/messengers/Messenger.js +0 -1
  96. package/lib/messengers/PortMessenger.d.ts +0 -21
  97. package/lib/messengers/PortMessenger.js +0 -45
  98. package/lib/messengers/WindowMessenger.d.ts +0 -29
  99. package/lib/messengers/WindowMessenger.js +0 -176
  100. package/lib/messengers/WorkerMessenger.d.ts +0 -23
  101. package/lib/messengers/WorkerMessenger.js +0 -84
  102. package/lib/methodSerialization.d.ts +0 -22
  103. package/lib/methodSerialization.js +0 -42
  104. package/lib/namespace.d.ts +0 -2
  105. package/lib/namespace.js +0 -1
  106. package/lib/once.d.ts +0 -2
  107. package/lib/once.js +0 -13
  108. package/lib/shakeHands.d.ts +0 -76
  109. package/lib/shakeHands.js +0 -188
  110. package/lib/types.d.ts +0 -89
  111. package/lib/types.js +0 -1
@@ -0,0 +1,943 @@
1
+ // src/PenpalError.ts
2
+ var PenpalError = class extends Error {
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.name = "PenpalError";
7
+ this.code = code;
8
+ }
9
+ };
10
+ var PenpalError_default = PenpalError;
11
+
12
+ // src/errorSerialization.ts
13
+ var serializeError = (error) => ({
14
+ name: error.name,
15
+ message: error.message,
16
+ stack: error.stack,
17
+ penpalCode: error instanceof PenpalError_default ? error.code : void 0
18
+ });
19
+ var deserializeError = ({
20
+ name,
21
+ message,
22
+ stack,
23
+ penpalCode
24
+ }) => {
25
+ const deserializedError = penpalCode ? new PenpalError_default(penpalCode, message) : new Error(message);
26
+ deserializedError.name = name;
27
+ deserializedError.stack = stack;
28
+ return deserializedError;
29
+ };
30
+
31
+ // src/Reply.ts
32
+ var brand = Symbol("Reply");
33
+ var Reply = class {
34
+ value;
35
+ transferables;
36
+ // Allows TypeScript to distinguish between an actual instance of this
37
+ // class versus an object that looks structurally similar.
38
+ // eslint-disable-next-line no-unused-private-class-members
39
+ #brand = brand;
40
+ constructor(value, options) {
41
+ this.value = value;
42
+ this.transferables = options?.transferables;
43
+ }
44
+ };
45
+ var Reply_default = Reply;
46
+
47
+ // src/namespace.ts
48
+ var namespace_default = "penpal";
49
+
50
+ // src/guards.ts
51
+ var isObject = (value) => {
52
+ return typeof value === "object" && value !== null;
53
+ };
54
+ var isFunction = (value) => {
55
+ return typeof value === "function";
56
+ };
57
+ var isMessage = (data) => {
58
+ return isObject(data) && data.namespace === namespace_default;
59
+ };
60
+ var isSynMessage = (message) => {
61
+ return message.type === "SYN";
62
+ };
63
+ var isAck1Message = (message) => {
64
+ return message.type === "ACK1";
65
+ };
66
+ var isAck2Message = (message) => {
67
+ return message.type === "ACK2";
68
+ };
69
+ var isCallMessage = (message) => {
70
+ return message.type === "CALL";
71
+ };
72
+ var isReplyMessage = (message) => {
73
+ return message.type === "REPLY";
74
+ };
75
+ var isDestroyMessage = (message) => {
76
+ return message.type === "DESTROY";
77
+ };
78
+
79
+ // src/methodSerialization.ts
80
+ var extractMethodPathsFromMethods = (methods, currentPath = []) => {
81
+ const methodPaths = [];
82
+ for (const key of Object.keys(methods)) {
83
+ const value = methods[key];
84
+ if (isFunction(value)) {
85
+ methodPaths.push([...currentPath, key]);
86
+ } else if (isObject(value)) {
87
+ methodPaths.push(
88
+ ...extractMethodPathsFromMethods(value, [...currentPath, key])
89
+ );
90
+ }
91
+ }
92
+ return methodPaths;
93
+ };
94
+ var getMethodAtMethodPath = (methodPath, methods) => {
95
+ const result = methodPath.reduce(
96
+ (acc, pathSegment) => {
97
+ return isObject(acc) ? acc[pathSegment] : void 0;
98
+ },
99
+ methods
100
+ );
101
+ return isFunction(result) ? result : void 0;
102
+ };
103
+ var formatMethodPath = (methodPath) => {
104
+ return methodPath.join(".");
105
+ };
106
+
107
+ // src/connectCallHandler.ts
108
+ var createErrorReplyMessage = (channel, callId, error) => ({
109
+ namespace: namespace_default,
110
+ channel,
111
+ type: "REPLY",
112
+ callId,
113
+ isError: true,
114
+ ...error instanceof Error ? { value: serializeError(error), isSerializedErrorInstance: true } : { value: error }
115
+ });
116
+ var connectCallHandler = (messenger, methods, channel, log) => {
117
+ let isDestroyed = false;
118
+ const handleMessage = async (message) => {
119
+ if (isDestroyed) {
120
+ return;
121
+ }
122
+ if (!isCallMessage(message)) {
123
+ return;
124
+ }
125
+ log?.(`Received ${formatMethodPath(message.methodPath)}() call`, message);
126
+ const { methodPath, args, id: callId } = message;
127
+ let replyMessage;
128
+ let transferables;
129
+ try {
130
+ const method = getMethodAtMethodPath(methodPath, methods);
131
+ if (!method) {
132
+ throw new PenpalError_default(
133
+ "METHOD_NOT_FOUND",
134
+ `Method \`${formatMethodPath(methodPath)}\` is not found.`
135
+ );
136
+ }
137
+ let value = await method(...args);
138
+ if (value instanceof Reply_default) {
139
+ transferables = value.transferables;
140
+ value = await value.value;
141
+ }
142
+ replyMessage = {
143
+ namespace: namespace_default,
144
+ channel,
145
+ type: "REPLY",
146
+ callId,
147
+ value
148
+ };
149
+ } catch (error) {
150
+ replyMessage = createErrorReplyMessage(channel, callId, error);
151
+ }
152
+ if (isDestroyed) {
153
+ return;
154
+ }
155
+ try {
156
+ log?.(`Sending ${formatMethodPath(methodPath)}() reply`, replyMessage);
157
+ messenger.sendMessage(replyMessage, transferables);
158
+ } catch (error) {
159
+ if (error.name === "DataCloneError") {
160
+ replyMessage = createErrorReplyMessage(channel, callId, error);
161
+ log?.(`Sending ${formatMethodPath(methodPath)}() reply`, replyMessage);
162
+ messenger.sendMessage(replyMessage);
163
+ }
164
+ throw error;
165
+ }
166
+ };
167
+ messenger.addMessageHandler(handleMessage);
168
+ return () => {
169
+ isDestroyed = true;
170
+ messenger.removeMessageHandler(handleMessage);
171
+ };
172
+ };
173
+ var connectCallHandler_default = connectCallHandler;
174
+
175
+ // src/generateId.ts
176
+ var generateId_default = crypto.randomUUID?.bind(crypto) ?? (() => new Array(4).fill(0).map(
177
+ () => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)
178
+ ).join("-"));
179
+
180
+ // src/CallOptions.ts
181
+ var brand2 = Symbol("CallOptions");
182
+ var CallOptions = class {
183
+ transferables;
184
+ timeout;
185
+ // Allows TypeScript to distinguish between an actual instance of this
186
+ // class versus an object that looks structurally similar.
187
+ // eslint-disable-next-line no-unused-private-class-members
188
+ #brand = brand2;
189
+ constructor(options) {
190
+ this.transferables = options?.transferables;
191
+ this.timeout = options?.timeout;
192
+ }
193
+ };
194
+ var CallOptions_default = CallOptions;
195
+
196
+ // src/connectRemoteProxy.ts
197
+ var methodsToTreatAsNative = /* @__PURE__ */ new Set(["apply", "call", "bind"]);
198
+ var createRemoteProxy = (callback, log, path = []) => {
199
+ return new Proxy(
200
+ path.length ? () => {
201
+ } : /* @__PURE__ */ Object.create(null),
202
+ {
203
+ get(target, prop) {
204
+ if (prop === "then") {
205
+ return;
206
+ }
207
+ if (path.length && methodsToTreatAsNative.has(prop)) {
208
+ return Reflect.get(target, prop);
209
+ }
210
+ return createRemoteProxy(callback, log, [...path, prop]);
211
+ },
212
+ apply(target, _thisArg, args) {
213
+ return callback(path, args);
214
+ }
215
+ }
216
+ );
217
+ };
218
+ var getDestroyedConnectionMethodCallError = (methodPath) => {
219
+ return new PenpalError_default(
220
+ "CONNECTION_DESTROYED",
221
+ `Method call ${formatMethodPath(
222
+ methodPath
223
+ )}() failed due to destroyed connection`
224
+ );
225
+ };
226
+ var connectRemoteProxy = (messenger, channel, log) => {
227
+ let isDestroyed = false;
228
+ const replyHandlers = /* @__PURE__ */ new Map();
229
+ const handleMessage = (message) => {
230
+ if (!isReplyMessage(message)) {
231
+ return;
232
+ }
233
+ const { callId, value, isError, isSerializedErrorInstance } = message;
234
+ const replyHandler = replyHandlers.get(callId);
235
+ if (!replyHandler) {
236
+ return;
237
+ }
238
+ replyHandlers.delete(callId);
239
+ log?.(
240
+ `Received ${formatMethodPath(replyHandler.methodPath)}() call`,
241
+ message
242
+ );
243
+ if (isError) {
244
+ replyHandler.reject(
245
+ isSerializedErrorInstance ? deserializeError(value) : value
246
+ );
247
+ } else {
248
+ replyHandler.resolve(value);
249
+ }
250
+ };
251
+ messenger.addMessageHandler(handleMessage);
252
+ const remoteProxy = createRemoteProxy((methodPath, args) => {
253
+ if (isDestroyed) {
254
+ throw getDestroyedConnectionMethodCallError(methodPath);
255
+ }
256
+ const callId = generateId_default();
257
+ const lastArg = args[args.length - 1];
258
+ const lastArgIsOptions = lastArg instanceof CallOptions_default;
259
+ const { timeout, transferables } = lastArgIsOptions ? lastArg : {};
260
+ const argsWithoutOptions = lastArgIsOptions ? args.slice(0, -1) : args;
261
+ return new Promise((resolve, reject) => {
262
+ const timeoutId = timeout !== void 0 ? window.setTimeout(() => {
263
+ replyHandlers.delete(callId);
264
+ reject(
265
+ new PenpalError_default(
266
+ "METHOD_CALL_TIMEOUT",
267
+ `Method call ${formatMethodPath(
268
+ methodPath
269
+ )}() timed out after ${timeout}ms`
270
+ )
271
+ );
272
+ }, timeout) : void 0;
273
+ replyHandlers.set(callId, { methodPath, resolve, reject, timeoutId });
274
+ try {
275
+ const callMessage = {
276
+ namespace: namespace_default,
277
+ channel,
278
+ type: "CALL",
279
+ id: callId,
280
+ methodPath,
281
+ args: argsWithoutOptions
282
+ };
283
+ log?.(`Sending ${formatMethodPath(methodPath)}() call`, callMessage);
284
+ messenger.sendMessage(callMessage, transferables);
285
+ } catch (error) {
286
+ reject(
287
+ new PenpalError_default("TRANSMISSION_FAILED", error.message)
288
+ );
289
+ }
290
+ });
291
+ }, log);
292
+ const destroy = () => {
293
+ isDestroyed = true;
294
+ messenger.removeMessageHandler(handleMessage);
295
+ for (const { methodPath, reject, timeoutId } of replyHandlers.values()) {
296
+ clearTimeout(timeoutId);
297
+ reject(getDestroyedConnectionMethodCallError(methodPath));
298
+ }
299
+ replyHandlers.clear();
300
+ };
301
+ return {
302
+ remoteProxy,
303
+ destroy
304
+ };
305
+ };
306
+ var connectRemoteProxy_default = connectRemoteProxy;
307
+
308
+ // src/getPromiseWithResolvers.ts
309
+ var getPromiseWithResolvers = () => {
310
+ let resolve;
311
+ let reject;
312
+ const promise = new Promise((res, rej) => {
313
+ resolve = res;
314
+ reject = rej;
315
+ });
316
+ return {
317
+ promise,
318
+ resolve,
319
+ reject
320
+ };
321
+ };
322
+ var getPromiseWithResolvers_default = getPromiseWithResolvers;
323
+
324
+ // src/PenpalBugError.ts
325
+ var PenpalBugError = class extends Error {
326
+ constructor(message) {
327
+ super(
328
+ `You've hit a bug in Penpal. Please file an issue with the following information: ${message}`
329
+ );
330
+ }
331
+ };
332
+ var PenpalBugError_default = PenpalBugError;
333
+
334
+ // src/backwardCompatibility.ts
335
+ var DEPRECATED_PENPAL_PARTICIPANT_ID = "deprecated-penpal";
336
+ var isDeprecatedMessage = (data) => {
337
+ return isObject(data) && "penpal" in data;
338
+ };
339
+ var upgradeMethodPath = (methodPath) => methodPath.split(".");
340
+ var downgradeMethodPath = (methodPath) => methodPath.join(".");
341
+ var getUnexpectedMessageError = (message) => {
342
+ return new PenpalBugError_default(
343
+ `Unexpected message to translate: ${JSON.stringify(message)}`
344
+ );
345
+ };
346
+ var upgradeMessage = (message) => {
347
+ if (message.penpal === "syn" /* Syn */) {
348
+ return {
349
+ namespace: namespace_default,
350
+ channel: void 0,
351
+ type: "SYN",
352
+ participantId: DEPRECATED_PENPAL_PARTICIPANT_ID
353
+ };
354
+ }
355
+ if (message.penpal === "ack" /* Ack */) {
356
+ return {
357
+ namespace: namespace_default,
358
+ channel: void 0,
359
+ type: "ACK2"
360
+ };
361
+ }
362
+ if (message.penpal === "call" /* Call */) {
363
+ return {
364
+ namespace: namespace_default,
365
+ channel: void 0,
366
+ type: "CALL",
367
+ // Actually converting the ID to a string would break communication.
368
+ id: message.id,
369
+ methodPath: upgradeMethodPath(message.methodName),
370
+ args: message.args
371
+ };
372
+ }
373
+ if (message.penpal === "reply" /* Reply */) {
374
+ if (message.resolution === "fulfilled" /* Fulfilled */) {
375
+ return {
376
+ namespace: namespace_default,
377
+ channel: void 0,
378
+ type: "REPLY",
379
+ // Actually converting the ID to a string would break communication.
380
+ callId: message.id,
381
+ value: message.returnValue
382
+ };
383
+ } else {
384
+ return {
385
+ namespace: namespace_default,
386
+ channel: void 0,
387
+ type: "REPLY",
388
+ // Actually converting the ID to a string would break communication.
389
+ callId: message.id,
390
+ isError: true,
391
+ ...message.returnValueIsError ? {
392
+ value: message.returnValue,
393
+ isSerializedErrorInstance: true
394
+ } : {
395
+ value: message.returnValue
396
+ }
397
+ };
398
+ }
399
+ }
400
+ throw getUnexpectedMessageError(message);
401
+ };
402
+ var downgradeMessage = (message) => {
403
+ if (isAck1Message(message)) {
404
+ return {
405
+ penpal: "synAck" /* SynAck */,
406
+ methodNames: message.methodPaths.map(downgradeMethodPath)
407
+ };
408
+ }
409
+ if (isCallMessage(message)) {
410
+ return {
411
+ penpal: "call" /* Call */,
412
+ // Actually converting the ID to a number would break communication.
413
+ id: message.id,
414
+ methodName: downgradeMethodPath(message.methodPath),
415
+ args: message.args
416
+ };
417
+ }
418
+ if (isReplyMessage(message)) {
419
+ if (message.isError) {
420
+ return {
421
+ penpal: "reply" /* Reply */,
422
+ // Actually converting the ID to a number would break communication.
423
+ id: message.callId,
424
+ resolution: "rejected" /* Rejected */,
425
+ ...message.isSerializedErrorInstance ? {
426
+ returnValue: message.value,
427
+ returnValueIsError: true
428
+ } : { returnValue: message.value }
429
+ };
430
+ } else {
431
+ return {
432
+ penpal: "reply" /* Reply */,
433
+ // Actually converting the ID to a number would break communication.
434
+ id: message.callId,
435
+ resolution: "fulfilled" /* Fulfilled */,
436
+ returnValue: message.value
437
+ };
438
+ }
439
+ }
440
+ throw getUnexpectedMessageError(message);
441
+ };
442
+
443
+ // src/shakeHands.ts
444
+ var shakeHands = ({
445
+ messenger,
446
+ methods,
447
+ timeout,
448
+ channel,
449
+ log
450
+ }) => {
451
+ const participantId = generateId_default();
452
+ let remoteParticipantId;
453
+ const destroyHandlers = [];
454
+ let isComplete = false;
455
+ const methodPaths = extractMethodPathsFromMethods(methods);
456
+ const { promise, resolve, reject } = getPromiseWithResolvers_default();
457
+ const timeoutId = timeout !== void 0 ? setTimeout(() => {
458
+ reject(
459
+ new PenpalError_default(
460
+ "CONNECTION_TIMEOUT",
461
+ `Connection timed out after ${timeout}ms`
462
+ )
463
+ );
464
+ }, timeout) : void 0;
465
+ const destroy = () => {
466
+ for (const destroyHandler of destroyHandlers) {
467
+ destroyHandler();
468
+ }
469
+ };
470
+ const connectCallHandlerAndMethodProxies = () => {
471
+ if (isComplete) {
472
+ return;
473
+ }
474
+ destroyHandlers.push(connectCallHandler_default(messenger, methods, channel, log));
475
+ const { remoteProxy, destroy: destroyMethodProxies } = connectRemoteProxy_default(messenger, channel, log);
476
+ destroyHandlers.push(destroyMethodProxies);
477
+ clearTimeout(timeoutId);
478
+ isComplete = true;
479
+ resolve({
480
+ remoteProxy,
481
+ destroy
482
+ });
483
+ };
484
+ const sendSynMessage = () => {
485
+ const synMessage = {
486
+ namespace: namespace_default,
487
+ type: "SYN",
488
+ channel,
489
+ participantId
490
+ };
491
+ log?.(`Sending handshake SYN`, synMessage);
492
+ try {
493
+ messenger.sendMessage(synMessage);
494
+ } catch (error) {
495
+ reject(new PenpalError_default("TRANSMISSION_FAILED", error.message));
496
+ }
497
+ };
498
+ const handleSynMessage = (message) => {
499
+ log?.(`Received handshake SYN`, message);
500
+ if (message.participantId === remoteParticipantId && // TODO: Used for backward-compatibility. Remove in next major version.
501
+ remoteParticipantId !== DEPRECATED_PENPAL_PARTICIPANT_ID) {
502
+ return;
503
+ }
504
+ remoteParticipantId = message.participantId;
505
+ sendSynMessage();
506
+ const isHandshakeLeader = participantId > remoteParticipantId || // TODO: Used for backward-compatibility. Remove in next major version.
507
+ remoteParticipantId === DEPRECATED_PENPAL_PARTICIPANT_ID;
508
+ if (!isHandshakeLeader) {
509
+ return;
510
+ }
511
+ const ack1Message = {
512
+ namespace: namespace_default,
513
+ channel,
514
+ type: "ACK1",
515
+ methodPaths
516
+ };
517
+ log?.(`Sending handshake ACK1`, ack1Message);
518
+ try {
519
+ messenger.sendMessage(ack1Message);
520
+ } catch (error) {
521
+ reject(new PenpalError_default("TRANSMISSION_FAILED", error.message));
522
+ return;
523
+ }
524
+ };
525
+ const handleAck1Message = (message) => {
526
+ log?.(`Received handshake ACK1`, message);
527
+ const ack2Message = {
528
+ namespace: namespace_default,
529
+ channel,
530
+ type: "ACK2"
531
+ };
532
+ log?.(`Sending handshake ACK2`, ack2Message);
533
+ try {
534
+ messenger.sendMessage(ack2Message);
535
+ } catch (error) {
536
+ reject(new PenpalError_default("TRANSMISSION_FAILED", error.message));
537
+ return;
538
+ }
539
+ connectCallHandlerAndMethodProxies();
540
+ };
541
+ const handleAck2Message = (message) => {
542
+ log?.(`Received handshake ACK2`, message);
543
+ connectCallHandlerAndMethodProxies();
544
+ };
545
+ const handleMessage = (message) => {
546
+ if (isSynMessage(message)) {
547
+ handleSynMessage(message);
548
+ }
549
+ if (isAck1Message(message)) {
550
+ handleAck1Message(message);
551
+ }
552
+ if (isAck2Message(message)) {
553
+ handleAck2Message(message);
554
+ }
555
+ };
556
+ messenger.addMessageHandler(handleMessage);
557
+ destroyHandlers.push(() => messenger.removeMessageHandler(handleMessage));
558
+ sendSynMessage();
559
+ return promise;
560
+ };
561
+ var shakeHands_default = shakeHands;
562
+
563
+ // src/once.ts
564
+ var once = (fn) => {
565
+ let isCalled = false;
566
+ let result;
567
+ return (...args) => {
568
+ if (!isCalled) {
569
+ isCalled = true;
570
+ result = fn(...args);
571
+ }
572
+ return result;
573
+ };
574
+ };
575
+ var once_default = once;
576
+
577
+ // src/connect.ts
578
+ var usedMessengers = /* @__PURE__ */ new WeakSet();
579
+ var connect = ({
580
+ messenger,
581
+ methods = {},
582
+ timeout,
583
+ channel,
584
+ log
585
+ }) => {
586
+ if (!messenger) {
587
+ throw new PenpalError_default("INVALID_ARGUMENT", "messenger must be defined");
588
+ }
589
+ if (usedMessengers.has(messenger)) {
590
+ throw new PenpalError_default(
591
+ "INVALID_ARGUMENT",
592
+ "A messenger can only be used for a single connection"
593
+ );
594
+ }
595
+ usedMessengers.add(messenger);
596
+ const connectionDestroyedHandlers = [messenger.destroy];
597
+ const destroyConnection = once_default((notifyOtherParticipant) => {
598
+ if (notifyOtherParticipant) {
599
+ const destroyMessage = {
600
+ namespace: namespace_default,
601
+ channel,
602
+ type: "DESTROY"
603
+ };
604
+ try {
605
+ messenger.sendMessage(destroyMessage);
606
+ } catch (_) {
607
+ }
608
+ }
609
+ for (const connectionDestroyedHandler of connectionDestroyedHandlers) {
610
+ connectionDestroyedHandler();
611
+ }
612
+ log?.("Connection destroyed");
613
+ });
614
+ const validateReceivedMessage = (data) => {
615
+ return isMessage(data) && data.channel === channel;
616
+ };
617
+ const promise = (async () => {
618
+ try {
619
+ messenger.initialize({ log, validateReceivedMessage });
620
+ messenger.addMessageHandler((message) => {
621
+ if (isDestroyMessage(message)) {
622
+ destroyConnection(false);
623
+ }
624
+ });
625
+ const { remoteProxy, destroy } = await shakeHands_default({
626
+ messenger,
627
+ methods,
628
+ timeout,
629
+ channel,
630
+ log
631
+ });
632
+ connectionDestroyedHandlers.push(destroy);
633
+ return remoteProxy;
634
+ } catch (error) {
635
+ destroyConnection(true);
636
+ throw error;
637
+ }
638
+ })();
639
+ return {
640
+ promise,
641
+ // Why we don't reject the connection promise when consumer calls destroy():
642
+ // https://github.com/Aaronius/penpal/issues/51
643
+ destroy: () => {
644
+ destroyConnection(true);
645
+ }
646
+ };
647
+ };
648
+ var connect_default = connect;
649
+
650
+ // src/messengers/WindowMessenger.ts
651
+ var WindowMessenger = class {
652
+ #remoteWindow;
653
+ #allowedOrigins;
654
+ #log;
655
+ #validateReceivedMessage;
656
+ #concreteRemoteOrigin;
657
+ #messageCallbacks = /* @__PURE__ */ new Set();
658
+ #port;
659
+ // TODO: Used for backward-compatibility. Remove in next major version.
660
+ #isChildUsingDeprecatedProtocol = false;
661
+ constructor({ remoteWindow, allowedOrigins }) {
662
+ if (!remoteWindow) {
663
+ throw new PenpalError_default("INVALID_ARGUMENT", "remoteWindow must be defined");
664
+ }
665
+ this.#remoteWindow = remoteWindow;
666
+ this.#allowedOrigins = allowedOrigins?.length ? allowedOrigins : [window.origin];
667
+ }
668
+ initialize = ({
669
+ log,
670
+ validateReceivedMessage
671
+ }) => {
672
+ this.#log = log;
673
+ this.#validateReceivedMessage = validateReceivedMessage;
674
+ window.addEventListener("message", this.#handleMessageFromRemoteWindow);
675
+ };
676
+ sendMessage = (message, transferables) => {
677
+ if (isSynMessage(message)) {
678
+ const originForSending = this.#getOriginForSendingMessage(message);
679
+ this.#remoteWindow.postMessage(message, {
680
+ targetOrigin: originForSending,
681
+ transfer: transferables
682
+ });
683
+ return;
684
+ }
685
+ if (isAck1Message(message) || // If the child is using a previous version of Penpal, we need to
686
+ // downgrade the message and send it through the window rather than
687
+ // the port because older versions of Penpal don't use MessagePorts.
688
+ this.#isChildUsingDeprecatedProtocol) {
689
+ const payload = this.#isChildUsingDeprecatedProtocol ? downgradeMessage(message) : message;
690
+ const originForSending = this.#getOriginForSendingMessage(message);
691
+ this.#remoteWindow.postMessage(payload, {
692
+ targetOrigin: originForSending,
693
+ transfer: transferables
694
+ });
695
+ return;
696
+ }
697
+ if (isAck2Message(message)) {
698
+ const { port1, port2 } = new MessageChannel();
699
+ this.#port = port1;
700
+ port1.addEventListener("message", this.#handleMessageFromPort);
701
+ port1.start();
702
+ const transferablesToSend = [port2, ...transferables || []];
703
+ const originForSending = this.#getOriginForSendingMessage(message);
704
+ this.#remoteWindow.postMessage(message, {
705
+ targetOrigin: originForSending,
706
+ transfer: transferablesToSend
707
+ });
708
+ return;
709
+ }
710
+ if (this.#port) {
711
+ this.#port.postMessage(message, {
712
+ transfer: transferables
713
+ });
714
+ return;
715
+ }
716
+ throw new PenpalBugError_default("Port is undefined");
717
+ };
718
+ addMessageHandler = (callback) => {
719
+ this.#messageCallbacks.add(callback);
720
+ };
721
+ removeMessageHandler = (callback) => {
722
+ this.#messageCallbacks.delete(callback);
723
+ };
724
+ destroy = () => {
725
+ window.removeEventListener("message", this.#handleMessageFromRemoteWindow);
726
+ this.#destroyPort();
727
+ this.#messageCallbacks.clear();
728
+ };
729
+ #isAllowedOrigin = (origin) => {
730
+ return this.#allowedOrigins.some(
731
+ (allowedOrigin) => allowedOrigin instanceof RegExp ? allowedOrigin.test(origin) : allowedOrigin === origin || allowedOrigin === "*"
732
+ );
733
+ };
734
+ #getOriginForSendingMessage = (message) => {
735
+ if (isSynMessage(message)) {
736
+ return "*";
737
+ }
738
+ if (!this.#concreteRemoteOrigin) {
739
+ throw new PenpalBugError_default("Concrete remote origin not set");
740
+ }
741
+ return this.#concreteRemoteOrigin === "null" && this.#allowedOrigins.includes("*") ? "*" : this.#concreteRemoteOrigin;
742
+ };
743
+ #destroyPort = () => {
744
+ this.#port?.removeEventListener("message", this.#handleMessageFromPort);
745
+ this.#port?.close();
746
+ this.#port = void 0;
747
+ };
748
+ #handleMessageFromRemoteWindow = ({
749
+ source,
750
+ origin,
751
+ ports,
752
+ data
753
+ }) => {
754
+ if (source !== this.#remoteWindow) {
755
+ return;
756
+ }
757
+ if (isDeprecatedMessage(data)) {
758
+ this.#log?.(
759
+ "Please upgrade the child window to the latest version of Penpal."
760
+ );
761
+ this.#isChildUsingDeprecatedProtocol = true;
762
+ data = upgradeMessage(data);
763
+ }
764
+ if (!this.#validateReceivedMessage?.(data)) {
765
+ return;
766
+ }
767
+ if (!this.#isAllowedOrigin(origin)) {
768
+ this.#log?.(
769
+ `Received a message from origin \`${origin}\` which did not match allowed origins \`[${this.#allowedOrigins.join(", ")}]\``
770
+ );
771
+ return;
772
+ }
773
+ if (isSynMessage(data)) {
774
+ this.#destroyPort();
775
+ this.#concreteRemoteOrigin = origin;
776
+ }
777
+ if (isAck2Message(data) && // Previous versions of Penpal don't use MessagePorts and do all
778
+ // communication through the window.
779
+ !this.#isChildUsingDeprecatedProtocol) {
780
+ this.#port = ports[0];
781
+ if (!this.#port) {
782
+ throw new PenpalBugError_default("No port received on ACK2");
783
+ }
784
+ this.#port.addEventListener("message", this.#handleMessageFromPort);
785
+ this.#port.start();
786
+ }
787
+ for (const callback of this.#messageCallbacks) {
788
+ callback(data);
789
+ }
790
+ };
791
+ #handleMessageFromPort = ({ data }) => {
792
+ if (!this.#validateReceivedMessage?.(data)) {
793
+ return;
794
+ }
795
+ for (const callback of this.#messageCallbacks) {
796
+ callback(data);
797
+ }
798
+ };
799
+ };
800
+ var WindowMessenger_default = WindowMessenger;
801
+
802
+ // src/messengers/WorkerMessenger.ts
803
+ var WorkerMessenger = class {
804
+ #worker;
805
+ #validateReceivedMessage;
806
+ #messageCallbacks = /* @__PURE__ */ new Set();
807
+ #port;
808
+ constructor({ worker }) {
809
+ if (!worker) {
810
+ throw new PenpalError_default("INVALID_ARGUMENT", "worker must be defined");
811
+ }
812
+ this.#worker = worker;
813
+ }
814
+ initialize = ({ validateReceivedMessage }) => {
815
+ this.#validateReceivedMessage = validateReceivedMessage;
816
+ this.#worker.addEventListener("message", this.#handleMessage);
817
+ };
818
+ sendMessage = (message, transferables) => {
819
+ if (isSynMessage(message) || isAck1Message(message)) {
820
+ this.#worker.postMessage(message, { transfer: transferables });
821
+ return;
822
+ }
823
+ if (isAck2Message(message)) {
824
+ const { port1, port2 } = new MessageChannel();
825
+ this.#port = port1;
826
+ port1.addEventListener("message", this.#handleMessage);
827
+ port1.start();
828
+ this.#worker.postMessage(message, {
829
+ transfer: [port2, ...transferables || []]
830
+ });
831
+ return;
832
+ }
833
+ if (this.#port) {
834
+ this.#port.postMessage(message, {
835
+ transfer: transferables
836
+ });
837
+ return;
838
+ }
839
+ throw new PenpalBugError_default("Port is undefined");
840
+ };
841
+ addMessageHandler = (callback) => {
842
+ this.#messageCallbacks.add(callback);
843
+ };
844
+ removeMessageHandler = (callback) => {
845
+ this.#messageCallbacks.delete(callback);
846
+ };
847
+ destroy = () => {
848
+ this.#worker.removeEventListener("message", this.#handleMessage);
849
+ this.#destroyPort();
850
+ this.#messageCallbacks.clear();
851
+ };
852
+ #destroyPort = () => {
853
+ this.#port?.removeEventListener("message", this.#handleMessage);
854
+ this.#port?.close();
855
+ this.#port = void 0;
856
+ };
857
+ #handleMessage = ({ ports, data }) => {
858
+ if (!this.#validateReceivedMessage?.(data)) {
859
+ return;
860
+ }
861
+ if (isSynMessage(data)) {
862
+ this.#destroyPort();
863
+ }
864
+ if (isAck2Message(data)) {
865
+ this.#port = ports[0];
866
+ if (!this.#port) {
867
+ throw new PenpalBugError_default("No port received on ACK2");
868
+ }
869
+ this.#port.addEventListener("message", this.#handleMessage);
870
+ this.#port.start();
871
+ }
872
+ for (const callback of this.#messageCallbacks) {
873
+ callback(data);
874
+ }
875
+ };
876
+ };
877
+ var WorkerMessenger_default = WorkerMessenger;
878
+
879
+ // src/messengers/PortMessenger.ts
880
+ var PortMessenger = class {
881
+ #port;
882
+ #validateReceivedMessage;
883
+ #messageCallbacks = /* @__PURE__ */ new Set();
884
+ constructor({ port }) {
885
+ if (!port) {
886
+ throw new PenpalError_default("INVALID_ARGUMENT", "port must be defined");
887
+ }
888
+ this.#port = port;
889
+ }
890
+ initialize = ({ validateReceivedMessage }) => {
891
+ this.#validateReceivedMessage = validateReceivedMessage;
892
+ this.#port.addEventListener("message", this.#handleMessage);
893
+ this.#port.start();
894
+ };
895
+ sendMessage = (message, transferables) => {
896
+ this.#port?.postMessage(message, {
897
+ transfer: transferables
898
+ });
899
+ };
900
+ addMessageHandler = (callback) => {
901
+ this.#messageCallbacks.add(callback);
902
+ };
903
+ removeMessageHandler = (callback) => {
904
+ this.#messageCallbacks.delete(callback);
905
+ };
906
+ destroy = () => {
907
+ this.#port.removeEventListener("message", this.#handleMessage);
908
+ this.#port.close();
909
+ this.#messageCallbacks.clear();
910
+ };
911
+ #handleMessage = ({ data }) => {
912
+ if (!this.#validateReceivedMessage?.(data)) {
913
+ return;
914
+ }
915
+ for (const callback of this.#messageCallbacks) {
916
+ callback(data);
917
+ }
918
+ };
919
+ };
920
+ var PortMessenger_default = PortMessenger;
921
+
922
+ // src/ErrorCodeObj.ts
923
+ var ErrorCodeObj = {
924
+ ConnectionDestroyed: "CONNECTION_DESTROYED",
925
+ ConnectionTimeout: "CONNECTION_TIMEOUT",
926
+ InvalidArgument: "INVALID_ARGUMENT",
927
+ MethodCallTimeout: "METHOD_CALL_TIMEOUT",
928
+ MethodNotFound: "METHOD_NOT_FOUND",
929
+ TransmissionFailed: "TRANSMISSION_FAILED"
930
+ };
931
+ var ErrorCodeObj_default = ErrorCodeObj;
932
+
933
+ // src/debug.ts
934
+ var debug = (prefix) => {
935
+ return (...args) => {
936
+ console.log(`\u270D\uFE0F %c${prefix}%c`, "font-weight: bold;", "", ...args);
937
+ };
938
+ };
939
+ var debug_default = debug;
940
+
941
+ export { CallOptions_default as CallOptions, ErrorCodeObj_default as ErrorCode, PenpalError_default as PenpalError, PortMessenger_default as PortMessenger, Reply_default as Reply, WindowMessenger_default as WindowMessenger, WorkerMessenger_default as WorkerMessenger, connect_default as connect, debug_default as debug };
942
+ //# sourceMappingURL=penpal.mjs.map
943
+ //# sourceMappingURL=penpal.mjs.map