rx-postmessenger 2.0.1 → 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.
Files changed (110) hide show
  1. package/LICENSE +2 -2
  2. package/README.md +83 -63
  3. package/{esm → dist}/MessageFactory.d.ts +1 -3
  4. package/dist/MessageFactory.js +34 -0
  5. package/{cjs → dist}/MessageIDGenerator.d.ts +1 -1
  6. package/dist/MessageIDGenerator.js +19 -0
  7. package/{cjs → dist}/MessageValidator.d.ts +3 -4
  8. package/{esm → dist}/MessageValidator.js +19 -20
  9. package/dist/Messenger.d.ts +52 -0
  10. package/dist/Messenger.js +79 -0
  11. package/{cjs → dist}/PostmessageAdapter.d.ts +1 -2
  12. package/dist/PostmessageAdapter.js +11 -0
  13. package/dist/RxPostmessengerRequest.d.ts +11 -0
  14. package/dist/RxPostmessengerRequest.js +23 -0
  15. package/dist/functions/GUIDGenerator.d.ts +1 -0
  16. package/dist/functions/GUIDGenerator.js +10 -0
  17. package/dist/index.d.ts +4 -0
  18. package/dist/index.js +14 -0
  19. package/dist/public-api.d.ts +55 -0
  20. package/dist/public-api.js +1 -0
  21. package/dist/types.d.ts +58 -0
  22. package/dist/types.js +1 -0
  23. package/package.json +39 -47
  24. package/CHANGELOG.md +0 -159
  25. package/cjs/MessageFactory.d.ts +0 -11
  26. package/cjs/MessageFactory.js +0 -38
  27. package/cjs/MessageFactory.js.map +0 -1
  28. package/cjs/MessageIDGenerator.js +0 -24
  29. package/cjs/MessageIDGenerator.js.map +0 -1
  30. package/cjs/MessageValidator.js +0 -44
  31. package/cjs/MessageValidator.js.map +0 -1
  32. package/cjs/Messenger.d.ts +0 -99
  33. package/cjs/Messenger.js +0 -116
  34. package/cjs/Messenger.js.map +0 -1
  35. package/cjs/PostmessageAdapter.js +0 -14
  36. package/cjs/PostmessageAdapter.js.map +0 -1
  37. package/cjs/RxPostmessengerRequest.d.ts +0 -10
  38. package/cjs/RxPostmessengerRequest.js +0 -23
  39. package/cjs/RxPostmessengerRequest.js.map +0 -1
  40. package/cjs/functions/GUIDGenerator.d.ts +0 -1
  41. package/cjs/functions/GUIDGenerator.js +0 -59
  42. package/cjs/functions/GUIDGenerator.js.map +0 -1
  43. package/cjs/index.d.ts +0 -4
  44. package/cjs/index.js +0 -20
  45. package/cjs/index.js.map +0 -1
  46. package/cjs/interface/id-generator.d.ts +0 -11
  47. package/cjs/interface/id-generator.js +0 -3
  48. package/cjs/interface/id-generator.js.map +0 -1
  49. package/cjs/interface/message-factory.d.ts +0 -7
  50. package/cjs/interface/message-factory.js +0 -3
  51. package/cjs/interface/message-factory.js.map +0 -1
  52. package/cjs/interface/message-objects.d.ts +0 -30
  53. package/cjs/interface/message-objects.js +0 -3
  54. package/cjs/interface/message-objects.js.map +0 -1
  55. package/cjs/interface/message-validator.d.ts +0 -7
  56. package/cjs/interface/message-validator.js +0 -3
  57. package/cjs/interface/message-validator.js.map +0 -1
  58. package/cjs/interface/postmessage-adapter.d.ts +0 -6
  59. package/cjs/interface/postmessage-adapter.js +0 -3
  60. package/cjs/interface/postmessage-adapter.js.map +0 -1
  61. package/cjs/interface/public-interface.d.ts +0 -4
  62. package/cjs/interface/public-interface.js +0 -3
  63. package/cjs/interface/public-interface.js.map +0 -1
  64. package/esm/MessageFactory.js +0 -36
  65. package/esm/MessageFactory.js.map +0 -1
  66. package/esm/MessageIDGenerator.d.ts +0 -8
  67. package/esm/MessageIDGenerator.js +0 -22
  68. package/esm/MessageIDGenerator.js.map +0 -1
  69. package/esm/MessageValidator.d.ts +0 -30
  70. package/esm/MessageValidator.js.map +0 -1
  71. package/esm/Messenger.d.ts +0 -99
  72. package/esm/Messenger.js +0 -114
  73. package/esm/Messenger.js.map +0 -1
  74. package/esm/PostmessageAdapter.d.ts +0 -8
  75. package/esm/PostmessageAdapter.js +0 -12
  76. package/esm/PostmessageAdapter.js.map +0 -1
  77. package/esm/RxPostmessengerRequest.d.ts +0 -10
  78. package/esm/RxPostmessengerRequest.js +0 -21
  79. package/esm/RxPostmessengerRequest.js.map +0 -1
  80. package/esm/functions/GUIDGenerator.d.ts +0 -1
  81. package/esm/functions/GUIDGenerator.js +0 -56
  82. package/esm/functions/GUIDGenerator.js.map +0 -1
  83. package/esm/index.d.ts +0 -4
  84. package/esm/index.js +0 -17
  85. package/esm/index.js.map +0 -1
  86. package/esm/interface/id-generator.d.ts +0 -11
  87. package/esm/interface/id-generator.js +0 -1
  88. package/esm/interface/id-generator.js.map +0 -1
  89. package/esm/interface/message-factory.d.ts +0 -7
  90. package/esm/interface/message-factory.js +0 -1
  91. package/esm/interface/message-factory.js.map +0 -1
  92. package/esm/interface/message-objects.d.ts +0 -30
  93. package/esm/interface/message-objects.js +0 -1
  94. package/esm/interface/message-objects.js.map +0 -1
  95. package/esm/interface/message-validator.d.ts +0 -7
  96. package/esm/interface/message-validator.js +0 -1
  97. package/esm/interface/message-validator.js.map +0 -1
  98. package/esm/interface/postmessage-adapter.d.ts +0 -6
  99. package/esm/interface/postmessage-adapter.js +0 -1
  100. package/esm/interface/postmessage-adapter.js.map +0 -1
  101. package/esm/interface/public-interface.d.ts +0 -4
  102. package/esm/interface/public-interface.js +0 -1
  103. package/esm/interface/public-interface.js.map +0 -1
  104. package/karma.conf.js +0 -99
  105. package/rx-postmessenger.d.ts +0 -74
  106. package/umd/rx-postmessenger.js +0 -10827
  107. package/umd/rx-postmessenger.js.map +0 -1
  108. package/umd/rx-postmessenger.min.js +0 -17
  109. package/umd/rx-postmessenger.min.js.map +0 -1
  110. package/yarn-error.log +0 -4522
package/LICENSE CHANGED
@@ -1,4 +1,4 @@
1
- Copyright (c) 2018 Jeffrey Westerkamp
1
+ Copyright (c) 2017-2021 Jeffrey Westerkamp
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person
4
4
  obtaining a copy of this software and associated documentation
@@ -19,4 +19,4 @@
19
19
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20
20
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21
21
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
- OTHER DEALINGS IN THE SOFTWARE.
22
+ OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # rx-postmessenger
2
+
2
3
  [![npm version](https://badge.fury.io/js/rx-postmessenger.svg)](https://badge.fury.io/js/rx-postmessenger)
3
- [![Build Status](https://travis-ci.com/JJWesterkamp/rx-postmessenger.svg?branch=master)](https://travis-ci.com/JJWesterkamp/rx-postmessenger)
4
- [![Coverage Status](https://coveralls.io/repos/github/JJWesterkamp/rx-postmessenger/badge.svg?branch=master)](https://coveralls.io/github/JJWesterkamp/rx-postmessenger?branch=master)
4
+ [![CI](https://github.com/JJWesterkamp/rx-postmessenger/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/JJWesterkamp/rx-postmessenger/actions/workflows/ci.yml)
5
5
 
6
6
  Minimal [RxJS][rxgh] adapter for the [`Window # postMessage`][postmessage] API for request-response streams and notification streams across frame windows.
7
7
 
@@ -13,12 +13,14 @@ Each instance targets _one single_ `Window` object. It propagates incoming `Mess
13
13
 
14
14
  ## RxJS Interoperability
15
15
 
16
- | | RxPostmessenger v1.x | RxPostmessenger v2.x |
17
- |----------- |:--------------------: |:--------------------: |
18
- | RxJS v5.x | ✅ | ❌ |
19
- | RxJS v6.x | ❌ | ✅ |
16
+ | | RxPostmessenger v1.x | RxPostmessenger v2.x | RxPostmessenger v3.x |
17
+ | --------- | :------------------: | :------------------: | :------------------: |
18
+ | RxJS v5.x | ✅ | ❌ | ❌ |
19
+ | RxJS v6.x | ❌ | ✅ | ✅ |
20
+ | RxJS v7.x | ❌ | ❌ | ✅ |
20
21
 
21
22
  [View changelog.][changelog]
23
+
22
24
  ## Installation
23
25
 
24
26
  ```bash
@@ -29,31 +31,31 @@ $ npm install rx-postmessenger --save
29
31
 
30
32
  **Static methods**
31
33
 
32
- |Method|Description|
33
- |:-|:-|
34
- |[`connect()`](#connecting-2-window-objects)|Connect `Window` objects by creating messenger instances.|
34
+ | Method | Description |
35
+ | :------------------------------------------ | :-------------------------------------------------------- |
36
+ | [`connect()`](#connecting-2-window-objects) | Connect `Window` objects by creating messenger instances. |
35
37
 
36
38
  **`Messenger` Instance methods**
37
39
 
38
- |Method|Description|
39
- |:-|:-|
40
- |[`notify()`](#sending-notifications)|Send notifications to the connected window.|
41
- |[`notifications()`](#listening-for-inbound-notifications)|Listen for inbound notifications.|
42
- |[`request()`](#sending-requests)|Send requests to the connected window.|
43
- |[`requests()`](#listening-for-inbound-requests)|Listen for inbound requests.|
40
+ | Method | Description |
41
+ | :-------------------------------------------------------- | :------------------------------------------ |
42
+ | [`notify()`](#sending-notifications) | Send notifications to the connected window. |
43
+ | [`notifications()`](#listening-for-inbound-notifications) | Listen for inbound notifications. |
44
+ | [`request()`](#sending-requests) | Send requests to the connected window. |
45
+ | [`requests()`](#listening-for-inbound-requests) | Listen for inbound requests. |
44
46
 
45
47
  **`Request` Instance methods**
46
48
 
47
- |Method|Description|
48
- |:-|:-|
49
- |[`respond()`](#sending-request-responses)|Respond to the request with a certain payload.
49
+ | Method | Description |
50
+ | :---------------------------------------- | :--------------------------------------------- |
51
+ | [`respond()`](#sending-request-responses) | Respond to the request with a certain payload. |
50
52
 
51
53
  ---
52
54
 
53
55
  ## Usage
54
56
 
55
57
  ```javascript
56
- import RxPostmessenger from 'rx-postmessenger';
58
+ import RxPostmessenger from 'rx-postmessenger'
57
59
  ```
58
60
 
59
61
  ### Static methods
@@ -69,54 +71,53 @@ Both ends of the connection should implement this package. One in a _parent_ pro
69
71
  _At parent window - `https://parent-project.com`_
70
72
 
71
73
  ```javascript
72
- const childMessenger = RxPostmessenger.connect(
73
- someIFrame.contentWindow,
74
- 'https://child-project.com'
75
- );
74
+ const childMessenger = RxPostmessenger.connect(someIFrame.contentWindow, 'https://child-project.com')
76
75
  ```
77
76
 
78
77
  _At child window - `https://child-project.com`_
79
78
 
80
79
  ```javascript
81
- const parentMessenger = RxPostmessenger.connect(
82
- window.parent,
83
- 'https://parent-project.com'
84
- );
80
+ const parentMessenger = RxPostmessenger.connect(window.parent, 'https://parent-project.com')
85
81
  ```
86
82
 
87
83
  ### `Messenger` Instance methods
88
84
 
89
85
  #### Sending notifications
86
+
90
87
  > ```typescript
91
88
  > Messenger.notify<T>(channel: string, payload?: T): void
92
89
  > ```
93
90
 
94
- The messenger instances give you a way to send notifications to the other `Window` through the `notify()` method.
95
- The notify method is void -- notifications are fire-and-forget.
91
+ The messenger instances give you a way to send notifications to the other `Window` through the `notify()` method.
92
+ The notify method is void -- notifications are fire-and-forget.
96
93
  Use [`request()`](#sending-requests) instead if you require data back.
97
94
  Consider an example where we want to notify a child window of price changes:
98
95
 
99
96
  ```javascript
100
97
  childMessenger.notify('price-changed', {
101
- oldPrice: 12.50,
102
- newPrice: 14.50,
103
- });
98
+ oldPrice: 12.5,
99
+ newPrice: 14.5,
100
+ })
104
101
  ```
105
102
 
106
103
  #### Listening for inbound notifications
104
+
107
105
  > ```typescript
108
106
  > Messenger.notifications<T = any>(channel: string): Observable<T>
109
107
  > ```
110
108
 
111
- The child project can request an Observable stream for a certain notification channel.
112
- In this case we're interested in `'price-changed'` events, but only the ones where the price increased.
109
+ The child project can request an Observable stream for a certain notification channel.
110
+ In this case we're interested in `'price-changed'` events, but only the ones where the price increased.
113
111
  The ability to use RxJS operators can help us out:
114
112
 
115
113
  ```javascript
116
- parentMessenger.notifications('price-changed').pipe(
114
+ parentMessenger
115
+ .notifications('price-changed')
116
+ .pipe(
117
117
  filter(({ oldPrice, newPrice }) => newPrice > oldPrice),
118
118
  map(({ oldPrice, newPrice }) => newPrice - oldPrice),
119
- ).subscribe((increase) => console.log(`Price increased with €${increase}!`));
119
+ )
120
+ .subscribe((increase) => console.log(`Price increased with €${increase}!`))
120
121
 
121
122
  // > 'Price increased with €2!'
122
123
  ```
@@ -127,46 +128,43 @@ parentMessenger.notifications('price-changed').pipe(
127
128
  > Messenger.request<T = any, U = any>(channel: string, payload?: T): Observable<U>
128
129
  > ```
129
130
 
130
- RxPostmessenger also supports request - response communication.
131
- At the requester side a request is initiated by calling the `request()` method with 1 or 2 arguments.
131
+ RxPostmessenger also supports request - response communication.
132
+ At the requester side a request is initiated by calling the `request()` method with 1 or 2 arguments.
132
133
  The first is a request alias (actually just another channel) of our choice.
133
134
 
134
135
  _A notification-channel and a request-channel can both have the same channel name without any problem._
135
136
 
136
- An observable is returned that emits the response when arrived, and then completes.
137
+ An observable is returned that emits the response when arrived, and then completes.
137
138
  Let's request a greeting from the child window, and tell it to localize the response to `'en'`:
138
139
 
139
140
  ```javascript
140
141
  const greetingResponse$ = childMessenger.request('greeting', {
141
- language: 'en',
142
- });
142
+ language: 'en',
143
+ })
143
144
  ```
144
145
 
145
146
  We can then subscribe to the greeting response stream.
146
147
  Provided that the greeting says something nice, we'll log it for everyone to see:
147
148
 
148
149
  ```javascript
149
- greetingResponse$.pipe(
150
- filter((greeting) => isNiceGreeting(greeting)),
151
- ).subscribe(console.log);
150
+ greetingResponse$.pipe(filter((greeting) => isNiceGreeting(greeting))).subscribe(console.log)
152
151
 
153
152
  // > 'Hi parent!'
154
153
  ```
155
154
 
156
155
  #### Listening for inbound requests
156
+
157
157
  > ```typescript
158
158
  > Messenger.requests<T = any, U = any>(channel: string): Observable<RxPostmessenger.Request<T, U>>
159
159
  > ```
160
160
 
161
- No greeting would ever be received by `parentMessenger` when the child project does not listen
162
- for requests to handle and respond to. Let's not be rude and create a request stream for
163
- `'greeting'` requests, and subscribe to it. We'll pass the `RxPostmessenger.Request` objects
161
+ No greeting would ever be received by `parentMessenger` when the child project does not listen
162
+ for requests to handle and respond to. Let's not be rude and create a request stream for
163
+ `'greeting'` requests, and subscribe to it. We'll pass the `RxPostmessenger.Request` objects
164
164
  that the subscription receives into a function `handleGreetingRequest()`:
165
165
 
166
166
  ```javascript
167
- parentMessenger
168
- .requests('greeting')
169
- .subscribe(handleGreetingRequest);
167
+ parentMessenger.requests('greeting').subscribe(handleGreetingRequest)
170
168
  ```
171
169
 
172
170
  ---
@@ -179,28 +177,50 @@ parentMessenger
179
177
  > RxPostmessenger.Request<T, U> ~ respond(payload: U): void
180
178
  > ```
181
179
 
182
- The `requests` method returns an observable of `RxPostmessenger.Request` objects.
183
- They provide a single method `respond` that accepts one argument: the response payload.
180
+ The `requests` method returns an observable of `RxPostmessenger.Request` objects.
181
+ They provide a single method `respond` that accepts one argument: the response payload.
184
182
  Let's use the method on the requests we give to `handleGreetingRequest`:
185
183
 
186
184
  ```javascript
187
185
  const handleGreetingRequest = (request) => {
186
+ // The data that was sent along with the request
187
+ const requestPayload = request.payload
188
188
 
189
- // The data that was sent along with the request
190
- const requestPayload = request.payload;
191
-
192
- // A hypothetical greeting translator
193
- const localizedGreeting = translateGreeting(
194
- 'Hi parent!',
195
- requestPayload.language
196
- );
189
+ // A hypothetical greeting translator
190
+ const localizedGreeting = translateGreeting('Hi parent!', requestPayload.language)
197
191
 
198
- // Eventually respond to the request with some data (payload)
199
- request.respond(localizedGreeting);
200
- };
192
+ // Eventually respond to the request with some data (payload)
193
+ request.respond(localizedGreeting)
194
+ }
201
195
  ```
202
196
 
197
+ ## License
198
+
199
+ The MIT License (MIT). See [license file] for more information.
200
+
201
+ [license file]: https://github.com/JJWesterkamp/rx-postmessenger/blob/master/LICENSE
203
202
  [rxjs-imports]: https://github.com/JJWesterkamp/rx-postmessenger/tree/master/src/vendor/rxjs/index.ts
204
203
  [changelog]: https://github.com/JJWesterkamp/rx-postmessenger/tree/master/CHANGELOG.md
205
204
  [postmessage]: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
206
205
  [rxgh]: https://github.com/ReactiveX/RxJS
206
+
207
+ ## Development
208
+
209
+ Use Node.js 24.15+ (`nvm use`) and install dependencies with `npm ci`.
210
+
211
+ - `npm run build` compiles `src` with `tsconfig.app.json` into `dist`, including declarations.
212
+ - `npm run dev` watches the library sources.
213
+ - `npm run check` checks both the app and spec TypeScript configs without emitting files.
214
+ - `npm test` runs the browser API tests in Vitest with jsdom.
215
+ - `npm run fmt` checks formatting; `npm run lint` runs type-aware Oxlint.
216
+ - `npm run lint:fix` formats files and applies available lint fixes.
217
+ - `npm run test:watch` watches tests; `npm run test:coverage` generates coverage reports.
218
+
219
+ The package ships ESM only, with generated types exposed through the package exports.
220
+
221
+ CI runs on GitHub Actions for pushes and pull requests in three stages:
222
+ static analysis (formatting, lint, types, and build), coverage tests with artifacts retained
223
+ for one week, and a non-blocking production dependency audit.
224
+
225
+ Vitest requires 100% statement, branch, function, and line coverage. CI publishes a
226
+ coverage table in the workflow summary, including when tests or coverage thresholds fail.
@@ -1,6 +1,4 @@
1
- import { IMessageIDGenerator } from './interface/id-generator';
2
- import { IMessageFactory } from './interface/message-factory';
3
- import { INotificationObject, IRequestObject, IResponseObject } from './interface/message-objects';
1
+ import type { IMessageFactory, IMessageIDGenerator, INotificationObject, IRequestObject, IResponseObject } from './types.js';
4
2
  export declare class MessageFactory implements IMessageFactory {
5
3
  protected readonly IDGenerator: IMessageIDGenerator;
6
4
  constructor(IDGenerator: IMessageIDGenerator);
@@ -0,0 +1,34 @@
1
+ export class MessageFactory {
2
+ IDGenerator;
3
+ constructor(IDGenerator) {
4
+ this.IDGenerator = IDGenerator;
5
+ }
6
+ makeNotification(channel, payload) {
7
+ return {
8
+ channel,
9
+ id: this.IDGenerator.generateID(),
10
+ payload,
11
+ type: 'notification',
12
+ };
13
+ }
14
+ makeRequest(channel, payload) {
15
+ return {
16
+ channel,
17
+ id: this.IDGenerator.generateID(),
18
+ payload,
19
+ type: 'request',
20
+ };
21
+ }
22
+ makeResponse(requestId, channel, payload) {
23
+ return {
24
+ channel,
25
+ id: this.IDGenerator.generateID(),
26
+ payload,
27
+ requestId,
28
+ type: 'response',
29
+ };
30
+ }
31
+ invalidateID(id) {
32
+ this.IDGenerator.invalidateID(id);
33
+ }
34
+ }
@@ -1,4 +1,4 @@
1
- import { IMessageIDGenerator } from './interface/id-generator';
1
+ import type { IMessageIDGenerator } from './types.js';
2
2
  export declare class MessageIDGenerator implements IMessageIDGenerator {
3
3
  protected readonly gen: Iterator<string>;
4
4
  protected readonly usedIDValues: string[];
@@ -0,0 +1,19 @@
1
+ import { GUIDGenerator } from './functions/GUIDGenerator.js';
2
+ export class MessageIDGenerator {
3
+ gen;
4
+ usedIDValues = [];
5
+ constructor(gen = GUIDGenerator()) {
6
+ this.gen = gen;
7
+ }
8
+ generateID() {
9
+ let newID;
10
+ do {
11
+ newID = this.gen.next().value;
12
+ } while (this.usedIDValues.indexOf(newID) >= 0);
13
+ this.invalidateID(newID);
14
+ return newID;
15
+ }
16
+ invalidateID(id) {
17
+ this.usedIDValues.push(id);
18
+ }
19
+ }
@@ -1,5 +1,4 @@
1
- import { AnyMessage } from './interface/message-objects';
2
- import { IMessageValidator, IOwnMessageEvent } from './interface/message-validator';
1
+ import type { AnyMessage, IMessageValidator, IOwnMessageEvent } from './types.js';
3
2
  export declare class MessageValidator implements IMessageValidator {
4
3
  protected acceptedSource: Window;
5
4
  protected acceptedOrigin: string;
@@ -23,8 +22,8 @@ export declare class MessageValidator implements IMessageValidator {
23
22
  * object. This serves as runtime data format validation. If messages do not
24
23
  * comply to the AnyMessage compound interface, the entire event is ignored.
25
24
  *
26
- * @param {*} message
27
- * @return {boolean}
25
+ * @param {any} message
26
+ * @returns {boolean}
28
27
  */
29
28
  isWellFormedMessage(message: any): message is AnyMessage;
30
29
  }
@@ -1,5 +1,7 @@
1
- var MessageValidator = /** @class */ (function () {
2
- function MessageValidator(acceptedSource, acceptedOrigin) {
1
+ export class MessageValidator {
2
+ acceptedSource;
3
+ acceptedOrigin;
4
+ constructor(acceptedSource, acceptedOrigin) {
3
5
  this.acceptedSource = acceptedSource;
4
6
  this.acceptedOrigin = acceptedOrigin;
5
7
  }
@@ -16,27 +18,24 @@ var MessageValidator = /** @class */ (function () {
16
18
  * same remoteOrigin, and still being able to distinguish between messages from
17
19
  * such frames.
18
20
  */
19
- MessageValidator.prototype.validate = function (message) {
20
- return message instanceof MessageEvent
21
- && message.origin === this.acceptedOrigin
22
- && message.source === this.acceptedSource
23
- && this.isWellFormedMessage(message.data);
24
- };
21
+ validate(message) {
22
+ return (message instanceof MessageEvent &&
23
+ message.origin === this.acceptedOrigin &&
24
+ message.source === this.acceptedSource &&
25
+ this.isWellFormedMessage(message.data));
26
+ }
25
27
  /**
26
28
  * Tests whether the data sent through postMessage is a well-formed message
27
29
  * object. This serves as runtime data format validation. If messages do not
28
30
  * comply to the AnyMessage compound interface, the entire event is ignored.
29
31
  *
30
- * @param {*} message
31
- * @return {boolean}
32
+ * @param {any} message
33
+ * @returns {boolean}
32
34
  */
33
- MessageValidator.prototype.isWellFormedMessage = function (message) {
34
- return (typeof message.id === 'string')
35
- && (['request', 'response', 'notification'].indexOf(message.type) >= 0)
36
- && (typeof message.channel === 'string')
37
- && (message.type !== 'response' || (typeof message.requestId === 'string'));
38
- };
39
- return MessageValidator;
40
- }());
41
- export { MessageValidator };
42
- //# sourceMappingURL=MessageValidator.js.map
35
+ isWellFormedMessage(message) {
36
+ return (typeof message.id === 'string' &&
37
+ ['request', 'response', 'notification'].indexOf(message.type) >= 0 &&
38
+ typeof message.channel === 'string' &&
39
+ (message.type !== 'response' || typeof message.requestId === 'string'));
40
+ }
41
+ }
@@ -0,0 +1,52 @@
1
+ import type { Messenger as IMessenger, Request } from './public-api.js';
2
+ import type { AnyMessage, INotificationObject, IRequestObject, IResponseObject, MappedMessage, MessageType, IMessageFactory, IMessageValidator, IPostmessageAdapter } from './types.js';
3
+ import type { Observable } from 'rxjs';
4
+ export declare class Messenger implements IMessenger {
5
+ protected readonly messageFactory: IMessageFactory;
6
+ protected readonly messageValidator: IMessageValidator;
7
+ protected readonly adapter: IPostmessageAdapter;
8
+ /**
9
+ * Observable stream of all incoming messages that originate from remoteWindow with a
10
+ * remoteOrigin url matching this.remoteOrigin.
11
+ */
12
+ readonly inboundMessages$: Observable<AnyMessage>;
13
+ /**
14
+ * Filtered subset of inboundMessages$, emitting all messages of type 'notification'
15
+ */
16
+ readonly notifications$: Observable<INotificationObject>;
17
+ /**
18
+ * Filtered subset of inboundMessages$, emitting all messages of type 'request'
19
+ */
20
+ readonly requests$: Observable<IRequestObject>;
21
+ /**
22
+ * Filtered subset of inboundMessages$, emitting all messages of type 'response'
23
+ */
24
+ readonly responses$: Observable<IResponseObject>;
25
+ /**
26
+ * @param {IMessageFactory} messageFactory - Factory instance for scalar message objects.
27
+ * @param {IMessageValidator} messageValidator - Validator instance for incoming messages.
28
+ * @param {IPostmessageAdapter} adapter - Adapter for interacting with the postMessage API
29
+ */
30
+ constructor(messageFactory: IMessageFactory, messageValidator: IMessageValidator, adapter: IPostmessageAdapter);
31
+ request<T = any, U = any>(channel: string, payload?: T): Observable<U>;
32
+ notify<T>(channel: string, payload?: T): void;
33
+ requests<T = any, U = any>(channel: string): Observable<Request<T, U>>;
34
+ notifications<T = any>(channel: string): Observable<T>;
35
+ /**
36
+ * Sends a response through given channel to the remote window, carrying given payload.
37
+ */
38
+ protected respond<T>(requestId: string, channel: string, payload: T): this;
39
+ /**
40
+ * Creates an Observable that completes after a single emission of the MessageEvent
41
+ * response for request of given requestId. If no matching response is ever received,
42
+ * the Observable never completes.
43
+ */
44
+ protected createResponseObservable<T>(requestId: string): Observable<T>;
45
+ /**
46
+ * Returns an Observable emitting all inbound messages` of given type.
47
+ * Returns an Observable emitting a subset of MessageEvent objects emitted
48
+ * by this.inboundMessages$, passing through all MessageEvent objects whose
49
+ * data.type property matches given type.
50
+ */
51
+ protected messagesOfType<T extends MessageType>(type: T): Observable<MappedMessage<T>>;
52
+ }
@@ -0,0 +1,79 @@
1
+ import { fromEvent, share } from 'rxjs';
2
+ import { filter, map, pluck, take } from 'rxjs/operators';
3
+ import { RxPostmessengerRequest } from './RxPostmessengerRequest.js';
4
+ export class Messenger {
5
+ messageFactory;
6
+ messageValidator;
7
+ adapter;
8
+ /**
9
+ * Observable stream of all incoming messages that originate from remoteWindow with a
10
+ * remoteOrigin url matching this.remoteOrigin.
11
+ */
12
+ inboundMessages$;
13
+ /**
14
+ * Filtered subset of inboundMessages$, emitting all messages of type 'notification'
15
+ */
16
+ notifications$;
17
+ /**
18
+ * Filtered subset of inboundMessages$, emitting all messages of type 'request'
19
+ */
20
+ requests$;
21
+ /**
22
+ * Filtered subset of inboundMessages$, emitting all messages of type 'response'
23
+ */
24
+ responses$;
25
+ /**
26
+ * @param {IMessageFactory} messageFactory - Factory instance for scalar message objects.
27
+ * @param {IMessageValidator} messageValidator - Validator instance for incoming messages.
28
+ * @param {IPostmessageAdapter} adapter - Adapter for interacting with the postMessage API
29
+ */
30
+ constructor(messageFactory, messageValidator, adapter) {
31
+ this.messageFactory = messageFactory;
32
+ this.messageValidator = messageValidator;
33
+ this.adapter = adapter;
34
+ this.inboundMessages$ = fromEvent(window, 'message').pipe(filter((message) => this.messageValidator.validate(message)), pluck('data'), share());
35
+ this.requests$ = this.messagesOfType('request');
36
+ this.responses$ = this.messagesOfType('response');
37
+ this.notifications$ = this.messagesOfType('notification');
38
+ this.inboundMessages$.subscribe(({ id }) => this.messageFactory.invalidateID(id));
39
+ }
40
+ request(channel, payload) {
41
+ const request = this.messageFactory.makeRequest(channel, payload);
42
+ const responseObservable = this.createResponseObservable(request.id);
43
+ this.adapter.postMessage(request);
44
+ return responseObservable;
45
+ }
46
+ notify(channel, payload) {
47
+ this.adapter.postMessage(this.messageFactory.makeNotification(channel, payload));
48
+ }
49
+ requests(channel) {
50
+ return this.requests$.pipe(filter((request) => request.channel === channel), map((request) => new RxPostmessengerRequest(request.id, request.channel, request.payload, (payload) => this.respond(request.id, channel, payload))));
51
+ }
52
+ notifications(channel) {
53
+ return this.notifications$.pipe(filter((notification) => notification.channel === channel), pluck('payload'));
54
+ }
55
+ /**
56
+ * Sends a response through given channel to the remote window, carrying given payload.
57
+ */
58
+ respond(requestId, channel, payload) {
59
+ this.adapter.postMessage(this.messageFactory.makeResponse(requestId, channel, payload));
60
+ return this;
61
+ }
62
+ /**
63
+ * Creates an Observable that completes after a single emission of the MessageEvent
64
+ * response for request of given requestId. If no matching response is ever received,
65
+ * the Observable never completes.
66
+ */
67
+ createResponseObservable(requestId) {
68
+ return this.responses$.pipe(filter((response) => response.requestId === requestId), pluck('payload'), take(1));
69
+ }
70
+ /**
71
+ * Returns an Observable emitting all inbound messages` of given type.
72
+ * Returns an Observable emitting a subset of MessageEvent objects emitted
73
+ * by this.inboundMessages$, passing through all MessageEvent objects whose
74
+ * data.type property matches given type.
75
+ */
76
+ messagesOfType(type) {
77
+ return this.inboundMessages$.pipe(filter((message) => message.type === type));
78
+ }
79
+ }
@@ -1,5 +1,4 @@
1
- import { AnyMessage } from './interface/message-objects';
2
- import { IPostmessageAdapter } from './interface/postmessage-adapter';
1
+ import type { AnyMessage, IPostmessageAdapter } from './types.js';
3
2
  export declare class PostmessageAdapter implements IPostmessageAdapter {
4
3
  readonly targetWindow: Window;
5
4
  readonly targetOrigin: string;
@@ -0,0 +1,11 @@
1
+ export class PostmessageAdapter {
2
+ targetWindow;
3
+ targetOrigin;
4
+ constructor(targetWindow, targetOrigin) {
5
+ this.targetWindow = targetWindow;
6
+ this.targetOrigin = targetOrigin;
7
+ }
8
+ postMessage(data) {
9
+ this.targetWindow.postMessage(data, this.targetOrigin);
10
+ }
11
+ }
@@ -0,0 +1,11 @@
1
+ import type { Request } from './public-api.js';
2
+ export declare class RxPostmessengerRequest<T, U> implements Request<T, U> {
3
+ readonly id: string;
4
+ readonly channel: string;
5
+ readonly payload: T;
6
+ private readonly injectResponse;
7
+ private handled;
8
+ constructor(id: string, channel: string, payload: T, injectResponse: (data: U) => void);
9
+ get isHandled(): boolean;
10
+ respond(data: U): void;
11
+ }
@@ -0,0 +1,23 @@
1
+ export class RxPostmessengerRequest {
2
+ id;
3
+ channel;
4
+ payload;
5
+ injectResponse;
6
+ handled = false;
7
+ constructor(id, channel, payload, injectResponse) {
8
+ this.id = id;
9
+ this.channel = channel;
10
+ this.payload = payload;
11
+ this.injectResponse = injectResponse;
12
+ }
13
+ get isHandled() {
14
+ return this.handled;
15
+ }
16
+ respond(data) {
17
+ if (this.handled) {
18
+ return;
19
+ }
20
+ this.injectResponse(data);
21
+ this.handled = true;
22
+ }
23
+ }
@@ -0,0 +1 @@
1
+ export declare function GUIDGenerator(): Generator<string, void, unknown>;
@@ -0,0 +1,10 @@
1
+ export function* GUIDGenerator() {
2
+ const s4 = () => Math.floor((1 + Math.random()) * 0x10000)
3
+ .toString(16)
4
+ .substring(1);
5
+ const IDSegment = (size = 1) => Array(size).fill(null).map(s4).join('');
6
+ const guid = () => [IDSegment(2), IDSegment(), IDSegment(), IDSegment(), IDSegment(3)].join('-');
7
+ while (true) {
8
+ yield guid();
9
+ }
10
+ }
@@ -0,0 +1,4 @@
1
+ import type { Static } from './public-api.js';
2
+ declare const defaultNamespace: Static;
3
+ export default defaultNamespace;
4
+ export type { Messenger, Request, Static } from './public-api.js';
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ import { MessageFactory } from './MessageFactory.js';
2
+ import { MessageIDGenerator } from './MessageIDGenerator.js';
3
+ import { MessageValidator } from './MessageValidator.js';
4
+ import { Messenger } from './Messenger.js';
5
+ import { PostmessageAdapter } from './PostmessageAdapter.js';
6
+ const defaultNamespace = {
7
+ connect(remoteWindow, remoteOrigin) {
8
+ if (window === remoteWindow) {
9
+ throw new Error('Remote window can not be the same as the local window environment');
10
+ }
11
+ return new Messenger(new MessageFactory(new MessageIDGenerator()), new MessageValidator(remoteWindow, remoteOrigin), new PostmessageAdapter(remoteWindow, remoteOrigin));
12
+ },
13
+ };
14
+ export default defaultNamespace;