postalworker-es 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,47 @@
1
+ # PostalWorker
2
+ A JavaScript WebWorker & postMessage library that connects UI elements, Web Workers, & Cross-Site Windows
3
+
4
+ # Installation:
5
+ npm install -save postalworker
6
+
7
+ # npm Commands:
8
+ ```
9
+ npm run build - Runs rollup.js to combine all the modules and dependencies and output the primary library script PostalWorker.js
10
+ npm run build-worker - Builds the worker libraries (SharedWorker and WebWorker scripts are run separately from main library)
11
+ npm run test - Run unit tests
12
+ npm run coverage - Generate code coverage report
13
+ npm run doc - Generate documentation
14
+ npm run demos - Generate demo pages
15
+ npm run relase - Build, generate, run unit tests (basicaly - DO EVERYTHING)
16
+ ```
17
+
18
+ Usage examples
19
+
20
+ ```javascript
21
+ import PostalWorker from "postalworker";
22
+
23
+ // In one window:
24
+ PostalWorker().on('example', (msg) => { window.console.info(msg); });
25
+
26
+ // In another window:
27
+ PostalWorker().fire('example', 'This is an example');
28
+
29
+ // In the above, the first window will print the message passed on message class "example" into the window.console: "This is an example"
30
+
31
+ // To cross launch a new window with the ability to send messages (even if the new window is not on the same host/domain)
32
+ PostalWorker().crossOn(
33
+ 'crossExample',
34
+ function(msg) { window.console.info(msg); },
35
+ 'http://myurl', // This is where you specify the url you want to open to (it must have a copy of PostalWorker hosted too)
36
+ 'MyURL', // This is where you name the new window if you want to interact with it directly with Javascript - limited by cross origin rules of course)
37
+ false // The last argument is optional and it includes more specific window parameters like width, height, etc...
38
+ );
39
+
40
+ // Then to send it a message:
41
+ PostalWorker().crossFire('crossExample', 'This is a message for my url window');
42
+
43
+ // In the above 2 commands, a window will be opened by the primary window, which will point to the url provided in argument 3
44
+ // And the second command will publish the message to the message class "crossExample" which window 2 will invoke the callback in argument 2 of crossOn
45
+
46
+ ```
47
+ # PostalWorker
@@ -0,0 +1,550 @@
1
+ (function () {
2
+ 'use strict';
3
+
4
+ /**
5
+ * PostalWorker String Constants
6
+ * @type {string}
7
+ */
8
+ const POSTAL_WORKER = "PostalWorker";
9
+ const POSTAL_SHARED_WORKER = "PostalSharedWorker";
10
+ const FIRE = "FIRE";
11
+ const WORKERREGISTER = "WORKERREGISTER";
12
+ const REGISTERID = "REGISTERID";
13
+ const UNREGISTERID = "UNREGISTERID";
14
+ const LOAD = "LOAD";
15
+ const POBOX = "POBOX";
16
+ const POST = "POST";
17
+ const COLLECT = "COLLECT";
18
+ const CLOSEBOX = "CLOSEBOX";
19
+ const BOXCLOSED = "BOXCLOSED";
20
+ const PACKAGE = "PACKAGE";
21
+ const PACK = "PACK";
22
+ const DELIVERY = "DELIVERY";
23
+
24
+ var hasProp = Object.prototype.hasOwnProperty;
25
+
26
+ function throwsMessage(err) {
27
+ return '[Throws: ' + (err ? err.message : '?') + ']';
28
+ }
29
+
30
+ function safeGetValueFromPropertyOnObject(obj, property) {
31
+ if (hasProp.call(obj, property)) {
32
+ try {
33
+ return obj[property];
34
+ }
35
+ catch (err) {
36
+ return throwsMessage(err);
37
+ }
38
+ }
39
+
40
+ return obj[property];
41
+ }
42
+
43
+ function ensureProperties(obj) {
44
+ var seen = [ ]; // store references to objects we have seen before
45
+
46
+ function visit(obj) {
47
+ if (obj === null || typeof obj !== 'object') {
48
+ return obj;
49
+ }
50
+
51
+ if (seen.indexOf(obj) !== -1) {
52
+ return '[Circular]';
53
+ }
54
+ seen.push(obj);
55
+
56
+ if (typeof obj.toJSON === 'function') {
57
+ try {
58
+ var fResult = visit(obj.toJSON());
59
+ seen.pop();
60
+ return fResult;
61
+ } catch(err) {
62
+ return throwsMessage(err);
63
+ }
64
+ }
65
+
66
+ if (Array.isArray(obj)) {
67
+ var aResult = obj.map(visit);
68
+ seen.pop();
69
+ return aResult;
70
+ }
71
+
72
+ var result = Object.keys(obj).reduce(function(result, prop) {
73
+ // prevent faulty defined getter properties
74
+ result[prop] = visit(safeGetValueFromPropertyOnObject(obj, prop));
75
+ return result;
76
+ }, {});
77
+ seen.pop();
78
+ return result;
79
+ }
80
+
81
+ return visit(obj);
82
+ }
83
+
84
+ var index = function(data, replacer, space) {
85
+ return JSON.stringify(ensureProperties(data), replacer, space);
86
+ };
87
+
88
+ var ensureProperties_1 = ensureProperties;
89
+
90
+ index.ensureProperties = ensureProperties_1;
91
+
92
+ /**
93
+ * Postal Worker - Shared Worker Thread Engine
94
+ * @Description: Use web worker threading to fork threads and use postMessage to pass serialized data between threads and windows
95
+ * @Author: Russ Stratfull
96
+ * @Contributors: Sakshi Dheer, & Francois Wauquier
97
+ */
98
+
99
+ self._env = {
100
+ _members: {},
101
+ _stringify: index,
102
+ _events: new Map(),
103
+ _scripts: new Map(),
104
+ _channel: new BroadcastChannel(POSTAL_WORKER),
105
+ _subscriptions: new Map(),
106
+ _postBoxes: {},
107
+ _packages: {}
108
+ };
109
+
110
+ /**
111
+ * Load a library (script) into the worker
112
+ * @param {*} msg
113
+ */
114
+ function _loadLibrary(msg) {
115
+ let scrpt = self._env._scripts.get(msg.data);
116
+ // if script already exists, don't reload it
117
+ if (scrpt) {
118
+ // just add window id to it
119
+ if (!scrpt.includes(msg.id)) scrpt.push(msg.id);
120
+ } else {
121
+ try {
122
+ importScripts(msg.data);
123
+ self._env._scripts.set(msg.data, [msg.id]);
124
+ } catch (e) {
125
+ self._env._channel.postMessage(
126
+ self._env._stringify({
127
+ postal: true,
128
+ type: "ERROR",
129
+ data: `PostalWorkerWorker Error: Unable to load file ${msg.data}`
130
+ })
131
+ );
132
+ }
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Add a node to the registry of members
138
+ * @param {*} msg
139
+ */
140
+ function _addNode(msg) {
141
+ const { id, nodeType } = msg;
142
+ self._env._members[id] = nodeType;
143
+ }
144
+
145
+ /**
146
+ * Remove a node from the registry of members
147
+ * @param {*} msg
148
+ */
149
+ function _removeNode(msg) {
150
+ const { id } = msg;
151
+ delete self._env._members[id];
152
+ Object.entries(self._env._postBoxes).forEach(box => {
153
+ const [, node] = box;
154
+ if (node.members.includes(id))
155
+ node.members.splice(node.members.indexOf(id), 1);
156
+ });
157
+ }
158
+
159
+ /**
160
+ *
161
+ * @param {*} msg
162
+ */
163
+ function _registerPObox(msg) {
164
+ const { id, address } = msg;
165
+ let addr = self._env._postBoxes[address];
166
+ if (addr) {
167
+ if (!addr.members.includes(id)) addr.members.push(id);
168
+ } else {
169
+ self._env._postBoxes[address] = {
170
+ members: [id],
171
+ handlers: [],
172
+ value: null
173
+ };
174
+ }
175
+
176
+ const box = Object.entries(self._env._postBoxes).reduce((store, current) => {
177
+ store[current[0]] = current[1].value;
178
+ return store;
179
+ }, {});
180
+
181
+ self.PostalWorker().fire(COLLECT, {
182
+ address: address,
183
+ value: self._env._postBoxes[address].value,
184
+ box
185
+ });
186
+ }
187
+
188
+ /**
189
+ *
190
+ * @param {*} msg
191
+ */
192
+ function _postBox(msg) {
193
+ const { address, value } = msg;
194
+ let addr = self._env._postBoxes[address];
195
+ if (addr) addr.value = value;
196
+ // todo: box not created case?
197
+ const box = Object.entries(self._env._postBoxes).reduce((store, current) => {
198
+ store[current[0]] = current[1].value;
199
+ return store;
200
+ }, {});
201
+ self.PostalWorker().fire(COLLECT, { address, value, box });
202
+ }
203
+
204
+ function _closeBox(msg) {
205
+ const { id, address } = msg;
206
+ let addr = self._env._postBoxes[address];
207
+ if (addr) {
208
+ addr.members = addr.members.filter(m => m !== id);
209
+ if (!addr.members.length) {
210
+ delete self._env._postBoxes[address];
211
+ }
212
+ const value = null;
213
+ const box = Object.entries(self._env._postBoxes).reduce(
214
+ (store, current) => {
215
+ store[current[0]] = current[1].value;
216
+ return store;
217
+ },
218
+ {}
219
+ );
220
+ self.PostalWorker().fire(BOXCLOSED, { id, address, value, box });
221
+ }
222
+ }
223
+
224
+ function _preparePackage(msg) {
225
+ const { id, address } = msg;
226
+ let pack = self._env._packages[address];
227
+ if (pack) {
228
+ if (!pack.members.includes(id)) pack.members.push(id);
229
+ } else
230
+ self._env._packages[address] = {
231
+ members: [id],
232
+ handlers: [],
233
+ content: null
234
+ };
235
+ // const box = Object.entries(self._env._packages).reduce((store, current) => {
236
+ // store[current[0]] = current[1].value;
237
+ // return store;
238
+ // }, {});
239
+ // self.PostalWorker().fire(S.DELIVERY, {
240
+ // address: address,
241
+ // content: self._env._packages[address].content
242
+ // });
243
+ }
244
+
245
+ function _pack(msg) {
246
+ const { address, content } = msg;
247
+ let addr = self._env._packages[address];
248
+ if (addr) addr.content = content;
249
+
250
+ self.PostalWorker().fire(DELIVERY, { address, content });
251
+ }
252
+
253
+ /**
254
+ *
255
+ * @param {*} msg
256
+ */
257
+ function _processChannelMessage(msg) {
258
+ // console.info(msg);
259
+ if (!msg.postal) return;
260
+ // console.info(msg);
261
+ switch (msg.type) {
262
+ case FIRE:
263
+ if (self._env._events.has(msg.data.msgClass)) {
264
+ self._env._events.get(msg.data.msgClass)(msg.data.message, msg.id);
265
+ }
266
+ break;
267
+ case LOAD:
268
+ _loadLibrary(msg);
269
+ break;
270
+ case REGISTERID:
271
+ _addNode(msg);
272
+ break;
273
+ case UNREGISTERID:
274
+ _removeNode(msg);
275
+ break;
276
+ case POBOX:
277
+ _registerPObox(msg);
278
+ break;
279
+ case POST:
280
+ _postBox(msg);
281
+ break;
282
+ case CLOSEBOX:
283
+ _closeBox(msg);
284
+ break;
285
+ case PACKAGE:
286
+ _preparePackage(msg);
287
+ break;
288
+ case PACK:
289
+ _pack(msg);
290
+ }
291
+ }
292
+
293
+ self.PostalWorker = () => ({
294
+ /**
295
+ *
296
+ * @param msgClass
297
+ * @param action
298
+ */
299
+ on: (msgClass, action) => {
300
+ self._env._events.set(msgClass, action);
301
+ },
302
+
303
+ /**
304
+ *
305
+ * @param msgClass
306
+ */
307
+ un: msgClass => {
308
+ self._env._events.delete(msgClass);
309
+ },
310
+
311
+ /**
312
+ *
313
+ * @param msgClass
314
+ * @param msg
315
+ */
316
+ fire: (msgClass, msg) => {
317
+ self._env._channel.postMessage(
318
+ self._env._stringify({
319
+ postal: true,
320
+ type: FIRE,
321
+ id: POSTAL_SHARED_WORKER,
322
+ data: {
323
+ msgClass: msgClass,
324
+ message: msg
325
+ }
326
+ })
327
+ );
328
+ // deprecated
329
+ // self.PostalWorker._postMessenger(
330
+ // S.FIRE,
331
+ // audience,
332
+ // {
333
+ // msgClass: msgClass,
334
+ // message: msg,
335
+ // audience: audience
336
+ // },
337
+ // target
338
+ // );
339
+ },
340
+
341
+ /**
342
+ *
343
+ * @param {*} library
344
+ * @returns
345
+ */
346
+ load: library => _loadLibrary(library),
347
+
348
+ /**
349
+ * Subscribe to Server Sent Events and create event source
350
+ * @param {*} endpoint
351
+ * @param {*} callback
352
+ * @param {*} errorCallback
353
+ */
354
+ subscribe: (endpoint, callback, errorCallback) => {
355
+ if (!self._env._subscriptions.get(endpoint)) {
356
+ self._env._subscriptions.set(endpoint, new EventSource(endpoint));
357
+ self._env._subscriptions.get(endpoint).onmessage = msg => {
358
+ callback(msg);
359
+ };
360
+ if (errorCallback) {
361
+ self._env._subscriptions.get(endpoint).onerror = error => {
362
+ errorCallback(error);
363
+ };
364
+ }
365
+ }
366
+ },
367
+
368
+ PObox: (address, handler) => {
369
+ // todo...
370
+ }
371
+ });
372
+
373
+ /**
374
+ * When windows connect to the worker,
375
+ * register their source and start their messaging session
376
+ */
377
+ onconnect = () => {
378
+ // New messaging method using broadcast channel
379
+ if (!self._env._channel.onmessage)
380
+ self._env._channel.onmessage = event => {
381
+ const data = JSON.parse(event.data);
382
+ _processChannelMessage(data);
383
+ };
384
+
385
+ // Announce alive to broadcast channel
386
+ self._env._channel.postMessage(
387
+ self._env._stringify({
388
+ postal: true,
389
+ type: WORKERREGISTER
390
+ })
391
+ );
392
+ };
393
+
394
+ // from connect:
395
+ // // // Deprecating
396
+ // let address = uniqueNumber();
397
+ // let src = event.source,
398
+ // port = {
399
+ // address: address,
400
+ // session: src,
401
+ // tries: 10
402
+ // };
403
+ // self.PostalWorker.ports.push(port);
404
+ // src.start();
405
+ // // src.addEventListener(S.MESSAGE, event => {
406
+ // // self.PostalWorker._registerMessage(
407
+ // // event,
408
+ // // src,
409
+ // // self.PostalWorker.ports
410
+ // // );
411
+ // // });
412
+ // let startup = {
413
+ // type: S.SET_ADDRESS,
414
+ // data: address
415
+ // };
416
+ // src.postMessage(startup);
417
+
418
+ // from object:
419
+ /**
420
+ * Listen for an event and execute the provided callback
421
+ * Events:
422
+ * remove - remove from messaging community/queue
423
+ *
424
+ * @param event
425
+ * @param callback
426
+ */
427
+ // addListener: (event, callback) => {
428
+ // self.PostalWorker.listeners.set(S.REMOVE, callback);
429
+ // },
430
+ /** Deprecated
431
+ * Register message events
432
+ * @param event
433
+ * @param port
434
+ * @param ports
435
+ * @private
436
+ */
437
+ // _registerMessage: (event, port, ports) => {
438
+ // if (event.data && event.type) {
439
+ // let msg = JSON.parse(event.data),
440
+ // range;
441
+ // switch (msg.type) {
442
+ // // Responses keep the worker aware of which connections are current
443
+ // case S.RESPONSE:
444
+ // if (msg.status) {
445
+ // let lastRequest = self.PostalWorker.ports.find(
446
+ // prt => prt.session === event.currentTarget
447
+ // );
448
+ // if (lastRequest && lastRequest.tries) lastRequest.tries++;
449
+ // }
450
+ // break;
451
+ // case S.ON:
452
+ // // todo: Not ported over from previous version yet
453
+ // // but what do we do with "on" from a window in the worker anyways???
454
+ // break;
455
+ // case S.UN:
456
+ // // todo: Not ported over from previous version yet
457
+ // break;
458
+ // case S.FIRE:
459
+ // console.info("fire worker");
460
+ // // Broadcast to windows/tabs
461
+ // range = msg.data.audience || S.ALL; // public, private, ALL todo: direct port messaging...
462
+ // self.PostalWorker._postMessenger(S.FIRE, range, msg.data, port);
463
+ // // Invoke registered event on this thread
464
+ // if (self.PostalWorker.events.has(msg.data.msgClass)) {
465
+ // let address, index, src;
466
+ // for (let p of self.PostalWorker.ports) {
467
+ // if (p.session === event.currentTarget) {
468
+ // address = p.address;
469
+ // index = self.PostalWorker.ports.indexOf(p);
470
+ // src = p.session;
471
+ // }
472
+ // }
473
+ // self.PostalWorker.events.get(msg.data.msgClass)(
474
+ // msg.data.message,
475
+ // { index: index, address: address, src: src }
476
+ // );
477
+ // }
478
+ // break;
479
+ // // todo...
480
+ // case S.LOAD:
481
+ // if (self.PostalWorker.scripts.has(msg.data)) {
482
+ // return;
483
+ // }
484
+ // // Wrap importScripts in try catch to report errors back to the main window
485
+ // // Attemp to load requested library
486
+ // try {
487
+ // importScripts(msg.data);
488
+ // self.PostalWorker.scripts.add(msg.data);
489
+ // } catch (e) {
490
+ // event.currentTarget.postMessage({
491
+ // type: "ERROR",
492
+ // data: `PostalWorkerWorker Error: Unable to load file ${msg.data}`
493
+ // });
494
+ // }
495
+ // break;
496
+ // case S.SET_ADDRESS: {
497
+ // for (let p of self.PostalWorker.ports) {
498
+ // if (p.session === event.currentTarget) {
499
+ // p.address = msg.data;
500
+ // }
501
+ // }
502
+ // let addressChange = {
503
+ // type: S.SET_ADDRESS,
504
+ // data: msg.data
505
+ // };
506
+ // event.currentTarget.postMessage(addressChange);
507
+ // }
508
+ // }
509
+ // }
510
+ // },
511
+ /**
512
+ * This function invokes a callback whenever a window is removed from the messaging queue
513
+ * To configure the worker to do this, use the "addListener" method and provide the event "remove"
514
+ * as the first argument
515
+ * @param removals
516
+ * @private
517
+ */
518
+ // _invokeRemoveCallback: removals => {
519
+ // for (let r of removals) {
520
+ // self.PostalWorker.listeners.get(S.REMOVE)(r);
521
+ // }
522
+ // },
523
+ /**
524
+ * The messenger method used to post messages to the windows
525
+ * @param type
526
+ * @param audience
527
+ * @param msg
528
+ * @param port
529
+ * @private
530
+ */
531
+ // _postMessenger: (type, audience, msg, port) => {
532
+ // let notification = {
533
+ // type: type,
534
+ // data: msg
535
+ // };
536
+ // switch (audience) {
537
+ // case S.PRIVATE:
538
+ // notification = {type: type,data: msg};
539
+ // _port.tries++;
540
+ // _port.session.postMessage(notification);
541
+ // break;
542
+ // case S.PUBLIC:
543
+ // self.PostalWorker.channel.postMessage(notification);
544
+ // break;
545
+ // default: // ALL
546
+ // self.PostalWorker.channel.postMessage(notification);
547
+ // }
548
+ // }
549
+
550
+ }());
@@ -0,0 +1,386 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * PostalWorker String Constants
4
+ * @type {string}
5
+ */
6
+ function throwsMessage(e){return"[Throws: "+(e?e.message:"?")+"]"}function safeGetValueFromPropertyOnObject(e,s){if(hasProp.call(e,s))try{return e[s]}catch(e){return throwsMessage(e)}return e[s]}function ensureProperties(e){// store references to objects we have seen before
7
+ function s(e){if(null===e||"object"!=typeof e)return e;if(-1!==t.indexOf(e))return"[Circular]";if(t.push(e),"function"==typeof e.toJSON)try{var n=s(e.toJSON());return t.pop(),n}catch(e){return throwsMessage(e)}if(Array.isArray(e)){var o=e.map(s);return t.pop(),o}var r=Object.keys(e).reduce(function(t,n){
8
+ // prevent faulty defined getter properties
9
+ return t[n]=s(safeGetValueFromPropertyOnObject(e,n)),t},{});return t.pop(),r}var t=[];return s(e)}function main(e){return _PostalWorker||(_PostalWorker=new PostalWorker(e,index))}const POSTAL_WORKER="PostalWorker",POSTAL_SHARED_WORKER="PostalSharedWorker",ON="ON",UN="UN",FIRE="FIRE",CROSSFIRE="CROSSFIRE",BACKFIRE="BACKFIRE",CHILDREGISTER="CHILDREGISTER",WORKERREGISTER="WORKERREGISTER",REGISTERID="REGISTERID",UNREGISTERID="UNREGISTERID",BROADCASTNODE="BROADCASTNODE",CROSSNODE="CROSSNODE",ERROR="ERROR",MESSAGE="message",SCRIPT="script",JS="js",LOAD="LOAD",RESPONSE="RESPONSE",SET_ADDRESS="SET_ADDRESS",CONNECT="CONNECT",DISCONNECT="DISCONNECT",POBOX="POBOX",POST="POST",COLLECT="COLLECT",CLOSEBOX="CLOSEBOX",BOXCLOSED="BOXCLOSED",PACKAGE="PACKAGE",PACK="PACK",DELIVERY="DELIVERY",_BLANK="_blank";class Deprecated{static registerWorker(e,s,t,n){e.port.onmessage=(e=>{
10
+ // Handle messages sent from worker by type
11
+ switch(e.data.type){case FIRE:// If the legacy messaging is used, it will still work here
12
+ // Send the message
13
+ e.data.data.msgClass&&t.get(e.data.data.msgClass)&&t.get(e.data.data.msgClass)(e.data.data.message),
14
+ // Let worker know message was received
15
+ e.currentTarget.postMessage(s);break;case SET_ADDRESS:Deprecated.address=e.data.data;break;case ERROR:console.error(e.data.data);break;default:console.warn(e)}})}}/**
16
+ * Postal Helper defines the public API methods and creates window event handlers
17
+ * for the postal worker and add/remove internal postal subscriptions used by the library
18
+ * @author: Russ Stratfull
19
+ */
20
+ class PostalHelper{/**
21
+ * Primary PostalWorker public methods
22
+ * @param {*} module
23
+ */
24
+ static rootMethods(e){e.on=((s,t)=>e._on(s,t)),e.on.example=`PostalWorker().on('example', (msg) => console.info(msg))`,e.un=(s=>e._un(s)),e.un.example=`PostalWorker().un('example')`,e.fire=((s,t,n)=>e._fire(s,t,n)),e.fire.example=`PostalWorker().fire('example', 'Hello world')`,e.crossOn=((s,t,n,o,r)=>e._crossOn(s,t,n,o,r)),e.crossOn.example=`PostalWorker().crossOn('example', (msg) => console.info(msg), 'http://example.com', 'Example Name', )`,e.unCross=((s,t)=>e._unCross(s,t)),e.unCross.example=`PostalWorker().unCross('example', 'http://example.com')`,e.crossFire=((s,t)=>e._crossFire(s,t)),e.crossFire.example=`PostalWorker().crossFire('example', 'message to all windows/tabs cross launched')`,e.fireAll=((s,t)=>e._fireAll(s,t)),e.fireAll.example=`PostalWorker().fireAll('example', 'message to ALL windows/tabs/workers')`,e.load=(s=>e._load(s)),e.load.example=`PostalWorker().load('path/to/script.js')`,e.postBox=((s,t)=>e._postBox(s,t)),e.postBox.example=`PostalWorker().PObox('example', function(value) { console.log(value); })`,e.post=((s,t)=>e._post(s,t)),e.post.example=`PostalWorker().post('example', 'This is an example value')`,e.closeBox=(s=>e._closeBox(s)),e.closeBox.example=`PostalWorker().closeBox("example")`,e.package=((s,t)=>e._package(s,t)),e.package.example=`PostalWorker().package('example', (todo) => {})`,e.pack=((s,t)=>e._pack(s,t)),e.pack.example=`PostalWorker().pack('example', 'url/of/file.jpg')`}/**
25
+ * Special method added when script detects that the current window is an iframe
26
+ * @param {*} module
27
+ */
28
+ static backMethod(e){e.backFire=((s,t)=>e._backFire(s,t)),e.backFire.example=`PostalWorker().backfire('example', 'Message to parent window')`}/**
29
+ * Utility methods which in the future could maybe be removed from public access
30
+ * @param {*} module
31
+ */
32
+ static utilityMethods(e){}/**
33
+ * Attach global window event handlers needed by PostalWorker
34
+ * @param {*} module
35
+ */
36
+ static attachHandlers(e){
37
+ // Beforewindow unloads, announce disconnect to community
38
+ window.addEventListener("beforeunload",()=>{const s=e;s._unmapFromBroadcastNetwork(s.id);s._fireAll(DISCONNECT,{id:s.id,subscriber:s._getSubscriber(window.location.href)})}),
39
+ // When window loads, announce connection to community
40
+ window.addEventListener("load",()=>{const s=e;s._fireAll(CONNECT,{id:s.id,subscriber:s._getSubscriber(window.location.href)})})}/**
41
+ * Establish internal usage of PostalWorker to create connect, disconnect, msgClasses
42
+ * @param {*} module
43
+ */
44
+ static internalSubscriptions(e){
45
+ // Connect
46
+ e._on(CONNECT,s=>{
47
+ // console.info("CONNECT", msg);
48
+ const t=e;t._mapToBroadcastNetwork(s.id)}),e._crossOn(CONNECT,s=>{
49
+ // console.info("crossOn CONNECT", msg);
50
+ const t=e;let n=t._getOpeningWindows();//.get(msg.subscriber);
51
+ let o=[];if(n){
52
+ // wins.size should be 1 but todo: support multiple?
53
+ for(let[e,r]of n)t._mapToWindow(s.id,r,s.subscriber),o.push(e);for(let e of o)t._getOpeningWindows().delete(e)}}),
54
+ // Disconnect
55
+ e._on(DISCONNECT,s=>{
56
+ // console.info("DISCONNECT", msg);
57
+ const t=e;t._unmapFromWindow(s.id)}),e._crossOn(DISCONNECT,s=>{
58
+ // console.info("crossOn: DISCONNECT", msg);
59
+ const t=e;t._unmapFromWindow(s.id)})}/**
60
+ * Subscribe to postbox collection msgClass to get updates
61
+ * @param {*} module
62
+ */
63
+ static registerCollection(e){
64
+ // let last;
65
+ e._on(COLLECT,s=>{const t=e;
66
+ // const serialized = JSON.stringify(msg);
67
+ //if (last !== serialized) {
68
+ t._collectBox(s)})}/**
69
+ * Unregister postbox collection msgClass
70
+ * @param {*} module
71
+ */
72
+ static unregisterCollection(e){e._un(COLLECT)}/**
73
+ * Register for temporary msgClass to get final update when postbox is being closed
74
+ * @param {*} module
75
+ * @param {*} add
76
+ * @param {*} collect
77
+ */
78
+ static registerClosure(e,s,t){const n=t;e._getEvents().get(BOXCLOSED)||e._on(BOXCLOSED,s=>{const t=e;t._clearBox(s)}),e._lastCollection(s,n)}/**
79
+ * Register for msgClass to receive package updates and deliver them
80
+ * @param {*} module
81
+ */
82
+ static registerDelivery(e){e._on(DELIVERY,s=>{const t=e;t._delivery(s)})}}/**
83
+ * PostalWorker Post Messenger Event Bus Module (ES6)
84
+ * @description: Listen for and broadcast out messages by "message class"
85
+ * between windows/tabs & web workers using the postMessage API
86
+ * @Author: Russ Stratfull
87
+ * @Contributors: Sakshi Dheer, & François Wauquier
88
+ */
89
+ let _config=!1,_stringify,_worker=!1,_parentWindow=!1,_subscriptions=new Set,_events=new Map,_crossEvents=new Map,_openingWindows=new Map,_windows=new Map,_broadcastNetwork=new Set,_channel=new BroadcastChannel(POSTAL_WORKER),_queue=[],_POboxes=new Map,_closures=new Map,_packages=new Map;
90
+ // Define the PostalWorker
91
+ class PostalWorker{/**
92
+ * Initialize object with configuration & setup the worker and listeners
93
+ * @param configuration
94
+ * @param safeJsonStringify
95
+ */
96
+ constructor(e,s){this.uniqueNumber=0,this.id=this._uniqueNumber(),this.workerOnline=!1,_config=e||!1,_stringify=s,
97
+ // Public API
98
+ PostalHelper.rootMethods(this),PostalHelper.utilityMethods(this),
99
+ // Attach global handlers
100
+ PostalHelper.attachHandlers(this),
101
+ // Does this window have a parent?
102
+ window.self!==window.top&&(
103
+ // If it does, include additional public methods and then register it
104
+ // and let it know this window is ready to receive messages
105
+ PostalHelper.backMethod(this),_parentWindow=this._getSubscriber(document.referrer),this._backFire(CHILDREGISTER)),
106
+ // Add event listener to incoming messages (from windows) and process with messageController
107
+ window.addEventListener(MESSAGE,this._messageController),
108
+ // Subscribe to internal message classes
109
+ PostalHelper.internalSubscriptions(this),
110
+ // Resolve worker threading
111
+ this._resolveWorker()}/**
112
+ * Get root URL for subscriptions
113
+ * (postMessage treats ALL urls the same off the same root)
114
+ * @param url
115
+ * @return {*}
116
+ * @private
117
+ */
118
+ _getSubscriber(e){let s=e.split("://"),t=s[0];if(void 0!==s[1]){let e=s[1].split("/")[0];return t.concat("://").concat(e)}return e}/**
119
+ * Resolve what type of worker threading is available
120
+ * todo: this is very incomplete
121
+ * at the moment it only sets up the sharedworker - which is the priority in all cases anyways
122
+ * @private
123
+ */
124
+ _resolveWorker(){
125
+ // Browser supports SharedWorker
126
+ let e=!!window.SharedWorker;
127
+ // Fallback on failure
128
+ return e=Boolean(e),e?(_worker=this._startSharedWorker())||(_worker=this._startDedicatedWorker()):_worker=this._startDedicatedWorker(),_worker}/**
129
+ * Attempt to start SharedWorker thread or fail and return false
130
+ * @return {SharedWorker | boolean}
131
+ * @private
132
+ */
133
+ _startSharedWorker(){let e,s=this._getPostalRoute();try{e=new SharedWorker(s.concat("PostalSharedWorker").concat(".").concat(JS),POSTAL_WORKER);/* !!! DEPRECATED messaging route !!! but leaving in place as fallback for older browsers */
134
+ // this stuff is no longer tested and does not work
135
+ // (no more messaging, only the connection is being established here)
136
+ // but leaving it in to polyfill older browsers potentially
137
+ let t=_stringify({postal:!0,type:RESPONSE,id:this.id,status:!0});Deprecated.registerWorker(e,t,_events,this),/* !!! PRIMARY messaging - This should always be used first */
138
+ _channel.onmessage=(e=>{
139
+ // Handle messages sent from worker by type
140
+ const s=JSON.parse(e.data);if(!0!==s.postal)return;// Not a postalWorker message
141
+ switch(s.type){case WORKERREGISTER:if(
142
+ // worker startup
143
+ this.workerOnline=!0,this._mapToBroadcastNetwork(this.id),_queue.length){const e=()=>_queue.length;for(;e();)_queue.shift()()}break;case FIRE:s.data.msgClass&&_events.get(s.data.msgClass)&&_events.get(s.data.msgClass)(s.data.message);break;case ERROR:console.error(s.data)}})}catch(e){
144
+ // todo: Add intelligent error handling, including destination options
145
+ window.console.warn("PostalWorker - Unable to start SharedWorker"),window.console.debug(e)}return e||!1}/**
146
+ * Start a basic web worker (not available at this time)
147
+ * @private
148
+ */
149
+ _startDedicatedWorker(){window.console.info("_startDedicatedWorker... (not complete)")}/**
150
+ * Resolve route to use to find the sharedworker file
151
+ * Priority is:
152
+ * 1. Configuration passed to library
153
+ * 2. Find any script tag in document which is called PostalWorker and then see if PostalRoute is defined in the querystring
154
+ * 3. Assume the file is adjacent to where this script is being run from
155
+ * @return {String}
156
+ * @private
157
+ */
158
+ _getPostalRoute(){let e=Array.from(document.querySelectorAll(SCRIPT)).filter(e=>e.src?e.src.match(POSTAL_WORKER):[]).filter(e=>null!==e);if(
159
+ // What about if more than one postalworker is found?
160
+ // This should be pointed out...
161
+ e.length>1&&window.console.warn('PostalWorker - Discovered more than 1 script tag matching "PostalWorker"'),_config.PostalRoute)return _config.PostalRoute;if(e[0].src.match("PostalRoute")){let s=e[0].src.match(/PostalRoute=.*&/)?e[0].src.match(/PostalRoute=.*&/)[0].replace("&",""):e[0].src.match(/PostalRoute=.*$/)[0];return s.match("PostalRoute=.*$")[0].replace("PostalRoute=","")}
162
+ // Otherwise, look next to where the PostalWorker script is located
163
+ return 1===e.length?e[0].src.replace(/PostalWorker\.min\.js.*$/,"").replace(/PostalWorker\.js.*$/,""):""}/**
164
+ * Process window messaging events "data" by "type"
165
+ * @param e { data: JSON{ id: number, msgClass: string, message: any }, id: number, origin: string, source: port }
166
+ * @private
167
+ */
168
+ _messageController(e){if(!(!e.data||e.data.match&&e.data.match("webpack")||e.data.type&&e.data.type.match("webpack")||e.data.source&&e.data.source.match("react"))){let s=JSON.parse(e.data);if(s.postal&&!0===s.postal)// Not a postalWorker message
169
+ // console.info(msg);
170
+ switch(s.type){case CROSSFIRE:
171
+ // Is this a parent we don't yet know about?
172
+ _windows.has(s.id)||_windows.set(s.id,{win:e.source,subscriber:e.origin}),
173
+ // Is this window known by the module? If not, add it to the registry
174
+ _windows.has(s.id)||(_windows.set(s.id,{win:e.source,subscriber:e.origin}),_subscriptions.add(e.origin)),
175
+ // Is this a cross event?
176
+ _crossEvents.has(s.data.msgClass)&&
177
+ // If so, invoke registered callback against message
178
+ _crossEvents.get(s.data.msgClass)(s.data.message);break;case BACKFIRE:
179
+ // Children register themselves with the parent
180
+ s.data.msgClass===CHILDREGISTER?_windows.has(s.data.id)?(
181
+ // When a duplicate attempts to register, delete the previous resource
182
+ // This accounts for iframe reloading
183
+ _windows.delete(s.id),// _windows.delete(e.source);
184
+ _windows.set(s.id,{win:e.origin,subscriber:e.origin})):(
185
+ // if (!_windows.has(e.source)) {
186
+ _windows.set(s.id,{win:e.source,subscriber:e.origin}),//_windows.set(e.source, e.origin);
187
+ _subscriptions.add(e.origin)):_crossEvents.has(s.data.msgClass)&&
188
+ // Invoke registered callback
189
+ _crossEvents.get(s.data.msgClass)(s.data.message);break;case ERROR:window.console.error(s.data.message);break;default:window.console.error("PostalWorker - Unexpected message event"),window.console.debug({type:"_messageController",event:e})}}}/**
190
+ * Register for events
191
+ * @param msgClass
192
+ * @param action
193
+ * @return {PostalWorker}
194
+ */
195
+ _on(e,s){if(e&&s){
196
+ // Send message to worker thread
197
+ let t=_stringify({postal:!0,type:ON,id:this.id,data:{msgClass:e,action:s}});
198
+ // Update registry
199
+ return _worker?_channel.postMessage(t):_queue.push(()=>_channel.postMessage(t)),_events.set(e,s),this}}/**
200
+ * Unregister event
201
+ * @param msgClass
202
+ * @return {Boolean}
203
+ */
204
+ _un(e){try{
205
+ // Send message to worker thread
206
+ let s=_stringify({postal:!0,type:UN,id:this.id,data:e});_worker?_channel.postMessage(s):_queue.push(()=>_channel.postMessage(s)),
207
+ // Update registry
208
+ _events.delete(e)}catch(e){return window.console.error(e),!1}return!0}/**
209
+ * Fire event
210
+ * @param msgClass
211
+ * @param msg
212
+ * @param audience - not being used currently
213
+ * @return {PostalWorker}
214
+ */
215
+ _fire(e,s,t){let n=_stringify({postal:!0,type:FIRE,id:this.id,data:{msgClass:e,message:s,audience:t}});return this.workerOnline&&_worker?_channel.postMessage(n):_queue.push(()=>_channel.postMessage(n)),!0}/**
216
+ * Register for cross launched windows or iframes messages
217
+ * @param msgClass {string}
218
+ * @param action {function}
219
+ * @param subscriber {string}
220
+ * @param name {string}
221
+ * @param windowparams {WindowParameters}
222
+ * @return {PostalWorker}
223
+ */
224
+ _crossOn(e,s,t,n,o){let r,i,a="",c="";if(t){
225
+ // It also cannot be the parent window as that is already taken
226
+ if(
227
+ // postMessage only needs the root protocol+domain to send messages
228
+ r=this._getSubscriber(t),_parentWindow&&r!==_parentWindow)return window.console.warn("PostalWorker - Unable to crossOn parentWindow"),this;if(
229
+ // Register subscription
230
+ !1===_subscriptions.has(r)&&
231
+ // If subscriber doesn't exist
232
+ _subscriptions.add(r),
233
+ // Open window for subscription
234
+ i=n||_BLANK,o){for(const e of Object.entries(o))c=c.concat(`${a} ${e[0]}=${e[1]}`),""===a&&(a=",");
235
+ // Open window (with extra params)
236
+ // debug: console.info(`window.open(${subscriber}, ${winName}, ${params})`);
237
+ // _windows.set(window.open(subscriber, winName, params), rootSubscriber);
238
+ _openingWindows.set(r,window.open(t,i,c))}else
239
+ // Open window (basic)
240
+ // _windows.set(window.open(subscriber, winName), rootSubscriber);
241
+ _openingWindows.set(r,window.open(t,i));
242
+ // Register associated action in registry
243
+ _crossEvents.set(e,s)}else
244
+ // No subscriber means to ONLY listen but not to open the window reference
245
+ _crossEvents.set(e,s);return this}/**
246
+ * Unregister cross launch/iframes
247
+ * @param msgClass
248
+ * @param subscriber
249
+ * @return {PostalWorker}
250
+ */
251
+ _unCross(e,s){// todo: this should check if any other subscribers are using it...
252
+ if(
253
+ // Remove from cross events registry
254
+ _crossEvents.delete(e),s){
255
+ // Get root subscriber
256
+ let e=this._getSubscriber(s);
257
+ // Remove from subscriptions
258
+ _subscriptions.delete(e);
259
+ // If a reference to a window exists
260
+ let t=[];for(let[e,n]of _windows)n.subscriber===this._getSubscriber(s)&&(n.win.close(),t.push(e));t.forEach(e=>{_windows.delete(e)})}return this}/**
261
+ * Broadcast/fire across the windows/frames
262
+ * @param msgClass
263
+ * @param msg
264
+ * @return {PostalWorker}
265
+ */
266
+ _crossFire(e,s){let t=_stringify({postal:!0,type:CROSSFIRE,id:this.id,data:{msgClass:e,message:s}});if(0===_windows.size&&window.opener&&window.opener.postMessage(t,"*"),
267
+ // Parent window is part of the crossFire group
268
+ _parentWindow&&window.top.postMessage(t,_parentWindow),_windows.size>0)for(let[,e]of _windows)e.win.postMessage(t,e.subscriber);return this}/**
269
+ * Fire to all the things!
270
+ * @param msgClass
271
+ * @param msg
272
+ * @return {PostalWorker}
273
+ */
274
+ _fireAll(e,s){return this._fire(e,s),this._crossFire(e,s),this}/**
275
+ * Special fire type that is specifically from child to parent window
276
+ * @param msgClass
277
+ * @param msg
278
+ * @return {PostalWorker}
279
+ */
280
+ _backFire(e,s){if(_parentWindow&&e){let t=_stringify({postal:!0,type:BACKFIRE,id:this.id,data:{msgClass:e,message:s}});try{window.top.postMessage(t,_parentWindow)}catch(e){window.console.warn("PostalWorker - Unable to backFire"),window.console.debug({msg:t,parentWindow:_parentWindow,error:e})}}return this}/**
281
+ * Load JavaScript library into worker thread
282
+ * todo: @Russ - support for multiple threads...
283
+ * @param library
284
+ */
285
+ _load(e){const s=_stringify({postal:!0,type:LOAD,id:this.id,data:e});this.workerOnline?_worker?
286
+ // Otherwise, send the message to load the library
287
+ _channel.postMessage(s):_queue.push(()=>_channel.postMessage(s)):
288
+ // If the worker has not completed startup yet, queue the message
289
+ _queue.push(()=>{_channel.postMessage(s)})}/**
290
+ *
291
+ * @returns
292
+ */
293
+ _getOpeningWindows(){return _openingWindows}/**
294
+ * Get current window references registered with postal system
295
+ * @return {Map<any, any>}
296
+ */
297
+ _getWindows(){return _windows}/**
298
+ *
299
+ * @return {Map<any, any>}
300
+ */
301
+ _getCrossEvents(){return _crossEvents}/**
302
+ *
303
+ * @return {Set<any>}
304
+ */
305
+ _getSubscriptions(){return _subscriptions}/**
306
+ * @param subscriber
307
+ * @return {boolean | Array}
308
+ */
309
+ _getWindowsBySubscriber(e){let s=[];for(let[,t]of _windows)e===t.subscriber&&s.push(t);return s}/**
310
+ *
311
+ * @return {Map<any, any>}
312
+ */
313
+ _getEvents(){return _events}/**
314
+ * Generate unique number using timestamp + incrementing number
315
+ * @returns number
316
+ */
317
+ _uniqueNumber(){let e=Date.now();return e<=this._uniqueNumber.previous?e=++this._uniqueNumber.previous:this._uniqueNumber.previous=e,e}/**
318
+ * Map window being opened to the window instance which is confirmed by first message
319
+ * @param {number} id
320
+ * @param {*} win
321
+ * @param {string} subscriber
322
+ */
323
+ _mapToWindow(e,s,t){_windows.set(e,{win:s,subscriber:t}),_channel.postMessage(_stringify({postal:!0,type:REGISTERID,id:e,nodeType:CROSSNODE}))}/**
324
+ *
325
+ * @param {number} id
326
+ */
327
+ _unmapFromWindow(e){_windows.delete(e),_channel.postMessage(_stringify({postal:!0,type:UNREGISTERID,id:e}))}/**
328
+ *
329
+ * @param {number} id
330
+ */
331
+ _mapToBroadcastNetwork(e){_broadcastNetwork.add(e),_channel.postMessage(_stringify({postal:!0,type:REGISTERID,id:e,nodeType:BROADCASTNODE}))}/**
332
+ *
333
+ * @param {number} id
334
+ */
335
+ _unmapFromBroadcastNetwork(e){_broadcastNetwork.delete(e),_channel.postMessage(_stringify({postal:!0,type:UNREGISTERID,id:e}))}/**
336
+ *
337
+ * @param {*} address
338
+ * @param {Function} handler - { update, box }
339
+ */
340
+ _postBox(e,s){const t=_stringify({postal:!0,type:POBOX,id:this.id,address:e});this.workerOnline?_worker&&_channel.postMessage(t):_queue.push(()=>_channel.postMessage(t)),_POboxes.size||PostalHelper.registerCollection(this),_POboxes.get(e)||_POboxes.set(e,s)}/**
341
+ *
342
+ * @param {*} address
343
+ */
344
+ _closeBox(e){const s=_POboxes.get(e);PostalHelper.registerClosure(this,e,s),_POboxes.delete(e),_channel.postMessage(_stringify({postal:!0,type:CLOSEBOX,id:this.id,address:e}))}
345
+ // _getPostBoxes() {
346
+ // return _POboxes;
347
+ // }
348
+ /**
349
+ *
350
+ * @param {*} address
351
+ * @param {*} value
352
+ */
353
+ _post(e,s){const t=_stringify({postal:!0,type:POST,id:this.id,address:e,value:s});this.workerOnline&&_worker?_channel.postMessage(t):_queue.push(()=>_channel.postMessage(t))}/**
354
+ *
355
+ * @param {*} drop
356
+ */
357
+ _collectBox(e){const{address:address,value:value,box:box}=e;let s=_POboxes.get(address);s&&s({address:address,value:value,box:box})}/**
358
+ *
359
+ * @param {*} address
360
+ * @param {*} collect
361
+ */
362
+ _lastCollection(e,s){_closures.set(e,s)}/**
363
+ *
364
+ * @param {*} msg
365
+ */
366
+ _clearBox(e){const{id:id,address:address,box:box}=e;if(id===this.id){if(_closures.get(address)){_closures.get(address)({address:address,value:null,box:box}),_closures.delete(address)}_POboxes.delete(address),_closures.size||_POboxes.size||PostalHelper.unregisterCollection(this)}}/**
367
+ *
368
+ * @param {*} address
369
+ * @param {*} content
370
+ * @param {*} handling
371
+ */
372
+ _package(e,s){const t=_stringify({postal:!0,type:PACKAGE,id:this.id,address:e});this.workerOnline?_worker&&_channel.postMessage(t):_queue.push(()=>_channel.postMessage(t)),_packages.size||PostalHelper.registerDelivery(this),_packages.get(e)||_packages.set(e,s)}/**
373
+ *
374
+ * @param {*} address
375
+ * @param {*} content
376
+ */
377
+ _pack(e,s){let t=new XMLHttpRequest,n=this;t.onload=function(){let s=new FileReader;s.onloadend=function(){const t=_stringify({postal:!0,type:PACK,id:n.id,address:e,content:s.result});n.workerOnline?_worker&&_channel.postMessage(t):_queue.push(()=>{_channel.postMessage(t)})},s.readAsDataURL(t.response)},t.open("GET",s),t.responseType="blob",t.send()}/**
378
+ *
379
+ * @param {*} msg
380
+ */
381
+ _delivery(e){const{address:address,content:content}=e;let s=_packages.get(address);s&&s({address:address,content:content})}}var hasProp=Object.prototype.hasOwnProperty,index=function(e,s,t){return JSON.stringify(ensureProperties(e),s,t)},ensureProperties_1=ensureProperties;index.ensureProperties=ensureProperties_1;/**
382
+ * PostalWorker Main Source (ES6 Version - Exports )
383
+ * Build ES6 module version
384
+ * @Author: Russ Stratfull - 2018
385
+ */
386
+ let _PostalWorker;export default main;
@@ -0,0 +1,149 @@
1
+ /* eslint-disable */
2
+ !function(){"use strict";function e(e){return"[Throws: "+(e?e.message:"?")+"]"}function t(t,r){if(S.call(t,r))try{return t[r]}catch(t){return e(t)}return t[r]}function r(r){// store references to objects we have seen before
3
+ function o(r){if(null===r||"object"!=typeof r)return r;if(-1!==a.indexOf(r))return"[Circular]";if(a.push(r),"function"==typeof r.toJSON)try{var n=o(r.toJSON());return a.pop(),n}catch(t){return e(t)}if(Array.isArray(r)){var s=r.map(o);return a.pop(),s}var i=Object.keys(r).reduce(function(e,a){
4
+ // prevent faulty defined getter properties
5
+ return e[a]=o(t(r,a)),e},{});return a.pop(),i}var a=[];return o(r)}/**
6
+ * PostalWorker String Constants
7
+ * @type {string}
8
+ */
9
+ var o="CHILDREGISTER",a="message",n=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},s=function(){function e(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,r,o){return r&&e(t.prototype,r),o&&e(t,o),t}}(),i=function(){function e(e,t){var r=[],o=!0,a=!1,n=void 0;try{for(var s,i=e[Symbol.iterator]();!(o=(s=i.next()).done)&&(r.push(s.value),!t||r.length!==t);o=!0);}catch(e){a=!0,n=e}finally{try{!o&&i.return&&i.return()}finally{if(a)throw n}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),u=function(){function e(){n(this,e)}return s(e,null,[{key:"registerWorker",value:function(t,r,o,a){t.port.onmessage=function(t){
10
+ // Handle messages sent from worker by type
11
+ switch(t.data.type){case"FIRE":
12
+ // If the legacy messaging is used, it will still work here
13
+ // Send the message
14
+ t.data.data.msgClass&&o.get(t.data.data.msgClass)&&o.get(t.data.data.msgClass)(t.data.data.message),
15
+ // Let worker know message was received
16
+ t.currentTarget.postMessage(r);break;case"SET_ADDRESS":e.address=t.data.data;break;case"ERROR":console.error(t.data.data);break;default:console.warn(t)}}}}]),e}(),l=function(){function e(){n(this,e)}return s(e,null,[{key:"rootMethods",/**
17
+ * Primary PostalWorker public methods
18
+ * @param {*} module
19
+ */
20
+ value:function(e){e.on=function(t,r){return e._on(t,r)},e.on.example="PostalWorker().on('example', (msg) => console.info(msg))",e.un=function(t){return e._un(t)},e.un.example="PostalWorker().un('example')",e.fire=function(t,r,o){return e._fire(t,r,o)},e.fire.example="PostalWorker().fire('example', 'Hello world')",e.crossOn=function(t,r,o,a,n){return e._crossOn(t,r,o,a,n)},e.crossOn.example="PostalWorker().crossOn('example', (msg) => console.info(msg), 'http://example.com', 'Example Name', )",e.unCross=function(t,r){return e._unCross(t,r)},e.unCross.example="PostalWorker().unCross('example', 'http://example.com')",e.crossFire=function(t,r){return e._crossFire(t,r)},e.crossFire.example="PostalWorker().crossFire('example', 'message to all windows/tabs cross launched')",e.fireAll=function(t,r){return e._fireAll(t,r)},e.fireAll.example="PostalWorker().fireAll('example', 'message to ALL windows/tabs/workers')",e.load=function(t){return e._load(t)},e.load.example="PostalWorker().load('path/to/script.js')",e.postBox=function(t,r){return e._postBox(t,r)},e.postBox.example="PostalWorker().PObox('example', function(value) { console.log(value); })",e.post=function(t,r){return e._post(t,r)},e.post.example="PostalWorker().post('example', 'This is an example value')",e.closeBox=function(t){return e._closeBox(t)},e.closeBox.example='PostalWorker().closeBox("example")',e.package=function(t,r){return e._package(t,r)},e.package.example="PostalWorker().package('example', (todo) => {})",e.pack=function(t,r){return e._pack(t,r)},e.pack.example="PostalWorker().pack('example', 'url/of/file.jpg')"}},{key:"backMethod",value:function(e){e.backFire=function(t,r){return e._backFire(t,r)},e.backFire.example="PostalWorker().backfire('example', 'Message to parent window')"}},{key:"utilityMethods",value:function(e){}},{key:"attachHandlers",value:function(e){
21
+ // Beforewindow unloads, announce disconnect to community
22
+ window.addEventListener("beforeunload",function(){var t=e;t._unmapFromBroadcastNetwork(t.id),t._fireAll("DISCONNECT",{id:t.id,subscriber:t._getSubscriber(window.location.href)})}),
23
+ // When window loads, announce connection to community
24
+ window.addEventListener("load",function(){var t=e;t._fireAll("CONNECT",{id:t.id,subscriber:t._getSubscriber(window.location.href)})})}},{key:"internalSubscriptions",value:function(e){
25
+ // Connect
26
+ e._on("CONNECT",function(t){e._mapToBroadcastNetwork(t.id)}),e._crossOn("CONNECT",function(t){
27
+ // console.info("crossOn CONNECT", msg);
28
+ var r=e,o=r._getOpeningWindows(),a=[];if(o){
29
+ // wins.size should be 1 but todo: support multiple?
30
+ var n=!0,s=!1,u=void 0;try{for(var l,c=o[Symbol.iterator]();!(n=(l=c.next()).done);n=!0){var d=i(l.value,2),p=d[0],f=d[1];r._mapToWindow(t.id,f,t.subscriber),a.push(p)}}catch(e){s=!0,u=e}finally{try{!n&&c.return&&c.return()}finally{if(s)throw u}}var v=!0,h=!1,g=void 0;try{for(var y,k=a[Symbol.iterator]();!(v=(y=k.next()).done);v=!0){var w=y.value;r._getOpeningWindows().delete(w)}}catch(e){h=!0,g=e}finally{try{!v&&k.return&&k.return()}finally{if(h)throw g}}}}),
31
+ // Disconnect
32
+ e._on("DISCONNECT",function(t){e._unmapFromWindow(t.id)}),e._crossOn("DISCONNECT",function(t){e._unmapFromWindow(t.id)})}},{key:"registerCollection",value:function(e){
33
+ // let last;
34
+ e._on("COLLECT",function(t){
35
+ // const serialized = JSON.stringify(msg);
36
+ //if (last !== serialized) {
37
+ e._collectBox(t)})}},{key:"unregisterCollection",value:function(e){e._un("COLLECT")}},{key:"registerClosure",value:function(e,t,r){var o=r;e._getEvents().get("BOXCLOSED")||e._on("BOXCLOSED",function(t){e._clearBox(t)}),e._lastCollection(t,o)}},{key:"registerDelivery",value:function(e){e._on("DELIVERY",function(t){e._delivery(t)})}}]),e}(),c=!1,d=void 0,p=!1,f=!1,v=new Set,h=new Map,g=new Map,y=new Map,k=new Map,w=new Set,m=new BroadcastChannel("PostalWorker"),b=[],_=new Map,C=new Map,O=new Map,x=function(){/**
38
+ * Initialize object with configuration & setup the worker and listeners
39
+ * @param configuration
40
+ * @param safeJsonStringify
41
+ */
42
+ function e(t,r){n(this,e),this.uniqueNumber=0,this.id=this._uniqueNumber(),this.workerOnline=!1,c=t||!1,d=r,
43
+ // Public API
44
+ l.rootMethods(this),l.utilityMethods(this),
45
+ // Attach global handlers
46
+ l.attachHandlers(this),
47
+ // Does this window have a parent?
48
+ window.self!==window.top&&(
49
+ // If it does, include additional public methods and then register it
50
+ // and let it know this window is ready to receive messages
51
+ l.backMethod(this),f=this._getSubscriber(document.referrer),this._backFire(o)),
52
+ // Add event listener to incoming messages (from windows) and process with messageController
53
+ window.addEventListener(a,this._messageController),
54
+ // Subscribe to internal message classes
55
+ l.internalSubscriptions(this),
56
+ // Resolve worker threading
57
+ this._resolveWorker()}/**
58
+ * Get root URL for subscriptions
59
+ * (postMessage treats ALL urls the same off the same root)
60
+ * @param url
61
+ * @return {*}
62
+ * @private
63
+ */
64
+ return s(e,[{key:"_getSubscriber",value:function(e){var t=e.split("://"),r=t[0];if(void 0!==t[1]){var o=t[1].split("/")[0];return r.concat("://").concat(o)}return e}},{key:"_resolveWorker",value:function(){
65
+ // Browser supports SharedWorker
66
+ var e=!!window.SharedWorker;
67
+ // Fallback on failure
68
+ return e=Boolean(e),e?(p=this._startSharedWorker())||(p=this._startDedicatedWorker()):p=this._startDedicatedWorker(),p}},{key:"_startSharedWorker",value:function(){var e=this,t=void 0,r=this._getPostalRoute();try{t=new SharedWorker(r.concat("PostalSharedWorker").concat(".").concat("js"),"PostalWorker");/* !!! DEPRECATED messaging route !!! but leaving in place as fallback for older browsers */
69
+ // this stuff is no longer tested and does not work
70
+ // (no more messaging, only the connection is being established here)
71
+ // but leaving it in to polyfill older browsers potentially
72
+ var o=d({postal:!0,type:"RESPONSE",id:this.id,status:!0});u.registerWorker(t,o,h,this),/* !!! PRIMARY messaging - This should always be used first */
73
+ m.onmessage=function(t){
74
+ // Handle messages sent from worker by type
75
+ var r=JSON.parse(t.data);if(!0===r.postal)// Not a postalWorker message
76
+ switch(r.type){case"WORKERREGISTER":if(
77
+ // worker startup
78
+ e.workerOnline=!0,e._mapToBroadcastNetwork(e.id),b.length)for(;function(){return b.length}();)b.shift()();break;case"FIRE":r.data.msgClass&&h.get(r.data.msgClass)&&h.get(r.data.msgClass)(r.data.message);break;case"ERROR":console.error(r.data)}}}catch(e){
79
+ // todo: Add intelligent error handling, including destination options
80
+ window.console.warn("PostalWorker - Unable to start SharedWorker"),window.console.debug(e)}return t||!1}},{key:"_startDedicatedWorker",value:function(){window.console.info("_startDedicatedWorker... (not complete)")}},{key:"_getPostalRoute",value:function(){var e=Array.from(document.querySelectorAll("script")).filter(function(e){return e.src?e.src.match("PostalWorker"):[]}).filter(function(e){return null!==e});
81
+ // What about if more than one postalworker is found?
82
+ // This should be pointed out...
83
+ return e.length>1&&window.console.warn('PostalWorker - Discovered more than 1 script tag matching "PostalWorker"'),c.PostalRoute?c.PostalRoute:e[0].src.match("PostalRoute")?(e[0].src.match(/PostalRoute=.*&/)?e[0].src.match(/PostalRoute=.*&/)[0].replace("&",""):e[0].src.match(/PostalRoute=.*$/)[0]).match("PostalRoute=.*$")[0].replace("PostalRoute=",""):1===e.length?e[0].src.replace(/PostalWorker\.min\.js.*$/,"").replace(/PostalWorker\.js.*$/,""):""}},{key:"_messageController",value:function(e){if(!(!e.data||e.data.match&&e.data.match("webpack")||e.data.type&&e.data.type.match("webpack")||e.data.source&&e.data.source.match("react"))){var t=JSON.parse(e.data);if(t.postal&&!0===t.postal)// Not a postalWorker message
84
+ // console.info(msg);
85
+ switch(t.type){case"CROSSFIRE":
86
+ // Is this a parent we don't yet know about?
87
+ k.has(t.id)||k.set(t.id,{win:e.source,subscriber:e.origin}),
88
+ // Is this window known by the module? If not, add it to the registry
89
+ k.has(t.id)||(k.set(t.id,{win:e.source,subscriber:e.origin}),v.add(e.origin)),
90
+ // Is this a cross event?
91
+ g.has(t.data.msgClass)&&
92
+ // If so, invoke registered callback against message
93
+ g.get(t.data.msgClass)(t.data.message);break;case"BACKFIRE":
94
+ // Children register themselves with the parent
95
+ t.data.msgClass===o?k.has(t.data.id)?(
96
+ // When a duplicate attempts to register, delete the previous resource
97
+ // This accounts for iframe reloading
98
+ k.delete(t.id),// _windows.delete(e.source);
99
+ k.set(t.id,{win:e.origin,subscriber:e.origin})):(
100
+ // if (!_windows.has(e.source)) {
101
+ k.set(t.id,{win:e.source,subscriber:e.origin}),//_windows.set(e.source, e.origin);
102
+ v.add(e.origin)):g.has(t.data.msgClass)&&
103
+ // Invoke registered callback
104
+ g.get(t.data.msgClass)(t.data.message);break;case"ERROR":window.console.error(t.data.message);break;default:window.console.error("PostalWorker - Unexpected message event"),window.console.debug({type:"_messageController",event:e})}}}},{key:"_on",value:function(e,t){if(e&&t){
105
+ // Send message to worker thread
106
+ var r=d({postal:!0,type:"ON",id:this.id,data:{msgClass:e,action:t}});
107
+ // Update registry
108
+ return p?m.postMessage(r):b.push(function(){return m.postMessage(r)}),h.set(e,t),this}}},{key:"_un",value:function(e){try{
109
+ // Send message to worker thread
110
+ var t=d({postal:!0,type:"UN",id:this.id,data:e});p?m.postMessage(t):b.push(function(){return m.postMessage(t)}),
111
+ // Update registry
112
+ h.delete(e)}catch(e){return window.console.error(e),!1}return!0}},{key:"_fire",value:function(e,t,r){var o=d({postal:!0,type:"FIRE",id:this.id,data:{msgClass:e,message:t,audience:r}});return this.workerOnline&&p?m.postMessage(o):b.push(function(){return m.postMessage(o)}),!0}},{key:"_crossOn",value:function(e,t,r,o,a){var n=void 0,s=void 0,i="",u="";if(r){
113
+ // It also cannot be the parent window as that is already taken
114
+ if(
115
+ // postMessage only needs the root protocol+domain to send messages
116
+ n=this._getSubscriber(r),f&&n!==f)return window.console.warn("PostalWorker - Unable to crossOn parentWindow"),this;if(
117
+ // Register subscription
118
+ !1===v.has(n)&&
119
+ // If subscriber doesn't exist
120
+ v.add(n),
121
+ // Open window for subscription
122
+ s=o||"_blank",a){var l=!0,c=!1,d=void 0;try{for(var p,h=Object.entries(a)[Symbol.iterator]();!(l=(p=h.next()).done);l=!0){var k=p.value;u=u.concat(i+" "+k[0]+"="+k[1]),""===i&&(i=",")}}catch(e){c=!0,d=e}finally{try{!l&&h.return&&h.return()}finally{if(c)throw d}}y.set(n,window.open(r,s,u))}else
123
+ // Open window (basic)
124
+ // _windows.set(window.open(subscriber, winName), rootSubscriber);
125
+ y.set(n,window.open(r,s));
126
+ // Register associated action in registry
127
+ g.set(e,t)}else
128
+ // No subscriber means to ONLY listen but not to open the window reference
129
+ g.set(e,t);return this}},{key:"_unCross",value:function(e,t){// todo: this should check if any other subscribers are using it...
130
+ if(
131
+ // Remove from cross events registry
132
+ g.delete(e),t){
133
+ // Get root subscriber
134
+ var r=this._getSubscriber(t);
135
+ // Remove from subscriptions
136
+ v.delete(r);
137
+ // If a reference to a window exists
138
+ var o=[],a=!0,n=!1,s=void 0;try{for(var u,l=k[Symbol.iterator]();!(a=(u=l.next()).done);a=!0){var c=i(u.value,2),d=c[0],p=c[1];p.subscriber===this._getSubscriber(t)&&(p.win.close(),o.push(d))}}catch(e){n=!0,s=e}finally{try{!a&&l.return&&l.return()}finally{if(n)throw s}}o.forEach(function(e){k.delete(e)})}return this}},{key:"_crossFire",value:function(e,t){var r=d({postal:!0,type:"CROSSFIRE",id:this.id,data:{msgClass:e,message:t}});if(0===k.size&&window.opener&&window.opener.postMessage(r,"*"),
139
+ // Parent window is part of the crossFire group
140
+ f&&window.top.postMessage(r,f),k.size>0){var o=!0,a=!1,n=void 0;try{for(var s,u=k[Symbol.iterator]();!(o=(s=u.next()).done);o=!0){var l=i(s.value,2)[1];l.win.postMessage(r,l.subscriber)}}catch(e){a=!0,n=e}finally{try{!o&&u.return&&u.return()}finally{if(a)throw n}}}return this}},{key:"_fireAll",value:function(e,t){return this._fire(e,t),this._crossFire(e,t),this}},{key:"_backFire",value:function(e,t){if(f&&e){var r=d({postal:!0,type:"BACKFIRE",id:this.id,data:{msgClass:e,message:t}});try{window.top.postMessage(r,f)}catch(e){window.console.warn("PostalWorker - Unable to backFire"),window.console.debug({msg:r,parentWindow:f,error:e})}}return this}},{key:"_load",value:function(e){var t=d({postal:!0,type:"LOAD",id:this.id,data:e});this.workerOnline?p?
141
+ // Otherwise, send the message to load the library
142
+ m.postMessage(t):b.push(function(){return m.postMessage(t)}):
143
+ // If the worker has not completed startup yet, queue the message
144
+ b.push(function(){m.postMessage(t)})}},{key:"_getOpeningWindows",value:function(){return y}},{key:"_getWindows",value:function(){return k}},{key:"_getCrossEvents",value:function(){return g}},{key:"_getSubscriptions",value:function(){return v}},{key:"_getWindowsBySubscriber",value:function(e){var t=[],r=!0,o=!1,a=void 0;try{for(var n,s=k[Symbol.iterator]();!(r=(n=s.next()).done);r=!0){var u=i(n.value,2)[1];e===u.subscriber&&t.push(u)}}catch(e){o=!0,a=e}finally{try{!r&&s.return&&s.return()}finally{if(o)throw a}}return t}},{key:"_getEvents",value:function(){return h}},{key:"_uniqueNumber",value:function(){var e=Date.now();return e<=this._uniqueNumber.previous?e=++this._uniqueNumber.previous:this._uniqueNumber.previous=e,e}},{key:"_mapToWindow",value:function(e,t,r){k.set(e,{win:t,subscriber:r}),m.postMessage(d({postal:!0,type:"REGISTERID",id:e,nodeType:"CROSSNODE"}))}},{key:"_unmapFromWindow",value:function(e){k.delete(e),m.postMessage(d({postal:!0,type:"UNREGISTERID",id:e}))}},{key:"_mapToBroadcastNetwork",value:function(e){w.add(e),m.postMessage(d({postal:!0,type:"REGISTERID",id:e,nodeType:"BROADCASTNODE"}))}},{key:"_unmapFromBroadcastNetwork",value:function(e){w.delete(e),m.postMessage(d({postal:!0,type:"UNREGISTERID",id:e}))}},{key:"_postBox",value:function(e,t){var r=d({postal:!0,type:"POBOX",id:this.id,address:e});this.workerOnline?p&&m.postMessage(r):b.push(function(){return m.postMessage(r)}),_.size||l.registerCollection(this),_.get(e)||_.set(e,t)}},{key:"_closeBox",value:function(e){var t=_.get(e);l.registerClosure(this,e,t),_.delete(e),m.postMessage(d({postal:!0,type:"CLOSEBOX",id:this.id,address:e}))}},{key:"_post",value:function(e,t){var r=d({postal:!0,type:"POST",id:this.id,address:e,value:t});this.workerOnline&&p?m.postMessage(r):b.push(function(){return m.postMessage(r)})}},{key:"_collectBox",value:function(e){var t=e.address,r=e.value,o=e.box,a=_.get(t);a&&a({address:t,value:r,box:o})}},{key:"_lastCollection",value:function(e,t){C.set(e,t)}},{key:"_clearBox",value:function(e){var t=e.id,r=e.address,o=e.box;if(t===this.id){if(C.get(r)){C.get(r)({address:r,value:null,box:o}),C.delete(r)}_.delete(r),C.size||_.size||l.unregisterCollection(this)}}},{key:"_package",value:function(e,t){var r=d({postal:!0,type:"PACKAGE",id:this.id,address:e});this.workerOnline?p&&m.postMessage(r):b.push(function(){return m.postMessage(r)}),O.size||l.registerDelivery(this),O.get(e)||O.set(e,t)}},{key:"_pack",value:function(e,t){var r=new XMLHttpRequest,o=this;r.onload=function(){var t=new FileReader;t.onloadend=function(){var r=d({postal:!0,type:"PACK",id:o.id,address:e,content:t.result});o.workerOnline?p&&m.postMessage(r):b.push(function(){m.postMessage(r)})},t.readAsDataURL(r.response)},r.open("GET",t),r.responseType="blob",r.send()}},{key:"_delivery",value:function(e){var t=e.address,r=e.content,o=O.get(t);o&&o({address:t,content:r})}}]),e}(),S=Object.prototype.hasOwnProperty,E=function(e,t,o){return JSON.stringify(r(e),t,o)},W=r;E.ensureProperties=W;/**
145
+ * PostalWorker Main Source
146
+ * (Legacy Version - Adds global PostalWorker method to window global scope)
147
+ * @Author: Russ Stratfull - 2018 - 2023
148
+ */
149
+ var R=void 0;!function(){R=new x({},E)}(),window.PostalWorker=function(){return R}}();
package/package.json ADDED
@@ -0,0 +1,90 @@
1
+ {
2
+ "name": "postalworker-es",
3
+ "version": "4.0.0",
4
+ "description": "A JavaScript WebWorker & postMessage library that connects UI elements, Web Workers, & Cross-Site Windows",
5
+ "main": "index.js",
6
+ "module": "dist/PostalWorker.es.js",
7
+ "files": [
8
+ "dist/PostalWorker.es.js",
9
+ "dist/PostalWorker.min.js",
10
+ "dist/PostalSharedWorker.js"
11
+ ],
12
+ "types": "dist/index.d.ts",
13
+ "scripts": {
14
+ "build": "rollup -c rollup.es.config.js && rollup -c rollup.min.config.js",
15
+ "build-worker": "rollup -c rollup.worker.config.js",
16
+ "_transpile-test": "rollup -c rollup.test.js",
17
+ "test": "npm run _transpile-test && mocha",
18
+ "coverage": "cross-env NODE_ENV=test nyc npm test",
19
+ "doc": "jsdoc -c jsdoc.json",
20
+ "demos": "npm run _demo-multipleiframes",
21
+ "_demo-multipleiframes": "rollup -c ./demos/multipleiframes/demo.multipleiframes.rollup.js",
22
+ "_demo-ie11": "rollup -c ./demos/IE11/demo.ie11.rollup.js",
23
+ "_demo-workerstuff": "rollup -c ./demos/workerstuff/rollupconfig.js",
24
+ "_demo-react": "cp dist/PostalWorker.es.js demos/react/src/ && cp dist/PostalSharedWorker.js demos/react/public/",
25
+ "release": "npm run build && npm run build-worker && npm run coverage && npm run doc && npm run demos",
26
+ "dev": "nodemon server.js",
27
+ "start": "node server.js"
28
+ },
29
+ "devDependencies": {
30
+ "babel-plugin-istanbul": "^4.0.0",
31
+ "babel-preset-es2015-rollup": "^3.0.0",
32
+ "babelrc-rollup": "^3.0.0",
33
+ "chai": "^3.5.0",
34
+ "cross-env": "^3.1.4",
35
+ "docdash": "^0.4.0",
36
+ "jsdoc": "^3.5.5",
37
+ "mocha": "^5.2.0",
38
+ "nyc": "^13.0.1",
39
+ "rollup": "^0.52.0",
40
+ "rollup-plugin-babel": "^2.7.1",
41
+ "rollup-plugin-commonjs": "^7.0.0",
42
+ "rollup-plugin-eslint": "^3.0.0",
43
+ "rollup-plugin-json": "^2.3.0",
44
+ "rollup-plugin-multi-entry": "^2.0.2",
45
+ "rollup-plugin-node-resolve": "2.0.0",
46
+ "rollup-plugin-replace": "^1.2.1",
47
+ "rollup-plugin-uglify-es": "0.0.1",
48
+ "sinon": "^1.17.7",
49
+ "sinon-chai": "^2.8.0",
50
+ "nodemon": "^2.0.15"
51
+ },
52
+ "dependencies": {
53
+ "body-parser": "^1.19.1",
54
+ "cookie-parser": "^1.4.6",
55
+ "cors": "^2.8.5",
56
+ "css-element-queries": "^0.4.0",
57
+ "debug": "^4.3.4",
58
+ "express": "^4.17.2",
59
+ "lodash": ">=4.17.12",
60
+ "lowdb": "^3.0.0",
61
+ "multer": "^1.4.4",
62
+ "rollup-plugin-bundle-worker": "^0.1.0",
63
+ "safe-json-stringify": "^1.1.0"
64
+ },
65
+ "repository": {
66
+ "type": "git",
67
+ "url": "git+https://github.com/subtext916/PostalWorker.git"
68
+ },
69
+ "nyc": {
70
+ "reporter": [
71
+ "text",
72
+ "html"
73
+ ]
74
+ },
75
+ "keywords": [
76
+ "postMessage",
77
+ "sharedWorker",
78
+ "eventbus"
79
+ ],
80
+ "author": "Russ Stratfull <russ@russandsonya.com> (http://russandsonya.com/russ)",
81
+ "license": "MIT",
82
+ "bugs": {
83
+ "url": "https://github.com/subtext916/PostalWorker/issues"
84
+ },
85
+ "homepage": "https://github.com/subtext916/PostalWorker#readme",
86
+ "type": "module",
87
+ "directories": {
88
+ "test": "test"
89
+ }
90
+ }