emr-bridge 1.7.1 → 2.0.1

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 (141) hide show
  1. package/LICENCE +1 -1
  2. package/README.md +173 -366
  3. package/cjs/entries/index.d.ts +1 -0
  4. package/cjs/entries/index.js +6 -0
  5. package/cjs/entries/main.d.ts +2 -0
  6. package/cjs/entries/main.js +27 -0
  7. package/cjs/entries/preload.d.ts +3 -0
  8. package/cjs/entries/preload.js +29 -0
  9. package/cjs/entries/renderer.d.ts +2 -0
  10. package/cjs/entries/renderer.js +27 -0
  11. package/cjs/errors.d.ts +42 -10
  12. package/cjs/errors.js +77 -23
  13. package/cjs/scripts/base-bridge.d.ts +95 -0
  14. package/cjs/scripts/base-bridge.js +128 -0
  15. package/cjs/scripts/helpers/env.d.ts +19 -0
  16. package/cjs/scripts/helpers/env.js +28 -0
  17. package/cjs/scripts/helpers/errors.d.ts +12 -0
  18. package/cjs/scripts/helpers/errors.js +17 -0
  19. package/cjs/scripts/helpers/id.d.ts +9 -0
  20. package/cjs/scripts/helpers/id.js +14 -0
  21. package/cjs/scripts/helpers/index.d.ts +8 -0
  22. package/cjs/scripts/helpers/index.js +22 -0
  23. package/cjs/scripts/helpers/ipc-channel.d.ts +75 -0
  24. package/cjs/scripts/helpers/ipc-channel.js +78 -0
  25. package/cjs/scripts/helpers/ipc-event-in-main.d.ts +24 -0
  26. package/cjs/scripts/helpers/ipc-event-in-main.js +30 -0
  27. package/cjs/scripts/helpers/ipc-result.d.ts +26 -0
  28. package/cjs/scripts/helpers/ipc-result.js +48 -0
  29. package/cjs/scripts/helpers/transfer.d.ts +33 -0
  30. package/cjs/scripts/helpers/transfer.js +57 -0
  31. package/cjs/scripts/helpers/web-contents-events-container.d.ts +51 -0
  32. package/cjs/scripts/helpers/web-contents-events-container.js +75 -0
  33. package/cjs/scripts/main/publish.d.ts +36 -0
  34. package/cjs/scripts/main/publish.js +184 -0
  35. package/cjs/scripts/preload/bridge.d.ts +27 -0
  36. package/cjs/scripts/preload/bridge.js +85 -0
  37. package/cjs/scripts/preload/provider.d.ts +7 -0
  38. package/cjs/scripts/preload/provider.js +89 -0
  39. package/cjs/scripts/renderer/bridge.d.ts +6 -0
  40. package/cjs/scripts/renderer/bridge.js +74 -0
  41. package/cjs/scripts/renderer/tunnels.d.ts +171 -0
  42. package/cjs/scripts/renderer/tunnels.js +205 -0
  43. package/cjs/types.d.ts +189 -64
  44. package/esm/entries/index.d.ts +1 -0
  45. package/esm/entries/index.js +5 -0
  46. package/esm/entries/main.d.ts +2 -0
  47. package/esm/entries/main.js +5 -0
  48. package/esm/entries/preload.d.ts +3 -0
  49. package/esm/entries/preload.js +7 -0
  50. package/esm/entries/renderer.d.ts +2 -0
  51. package/esm/entries/renderer.js +6 -0
  52. package/esm/errors.d.ts +42 -10
  53. package/esm/errors.js +69 -16
  54. package/esm/scripts/base-bridge.d.ts +95 -0
  55. package/esm/scripts/base-bridge.js +125 -0
  56. package/esm/scripts/helpers/env.d.ts +19 -0
  57. package/esm/scripts/helpers/env.js +25 -0
  58. package/esm/scripts/helpers/errors.d.ts +12 -0
  59. package/esm/scripts/helpers/errors.js +14 -0
  60. package/esm/scripts/helpers/id.d.ts +9 -0
  61. package/esm/scripts/helpers/id.js +11 -0
  62. package/esm/scripts/helpers/index.d.ts +8 -0
  63. package/esm/scripts/helpers/index.js +8 -0
  64. package/esm/scripts/helpers/ipc-channel.d.ts +75 -0
  65. package/esm/scripts/helpers/ipc-channel.js +76 -0
  66. package/esm/scripts/helpers/ipc-event-in-main.d.ts +24 -0
  67. package/esm/scripts/helpers/ipc-event-in-main.js +27 -0
  68. package/esm/scripts/helpers/ipc-result.d.ts +26 -0
  69. package/esm/scripts/helpers/ipc-result.js +42 -0
  70. package/esm/scripts/helpers/transfer.d.ts +33 -0
  71. package/esm/scripts/helpers/transfer.js +54 -0
  72. package/esm/scripts/helpers/web-contents-events-container.d.ts +51 -0
  73. package/esm/scripts/helpers/web-contents-events-container.js +72 -0
  74. package/esm/scripts/main/publish.d.ts +36 -0
  75. package/esm/scripts/main/publish.js +177 -0
  76. package/esm/scripts/preload/bridge.d.ts +27 -0
  77. package/esm/scripts/preload/bridge.js +77 -0
  78. package/esm/scripts/preload/provider.d.ts +7 -0
  79. package/esm/scripts/preload/provider.js +84 -0
  80. package/esm/scripts/renderer/bridge.d.ts +6 -0
  81. package/esm/scripts/renderer/bridge.js +69 -0
  82. package/esm/scripts/renderer/tunnels.d.ts +171 -0
  83. package/esm/scripts/renderer/tunnels.js +203 -0
  84. package/esm/types.d.ts +189 -64
  85. package/package.json +23 -41
  86. package/cjs/enums.d.ts +0 -19
  87. package/cjs/enums.js +0 -25
  88. package/cjs/exp.d.ts +0 -4
  89. package/cjs/exp.js +0 -19
  90. package/cjs/index.d.ts +0 -4
  91. package/cjs/index.js +0 -18
  92. package/cjs/main.d.ts +0 -4
  93. package/cjs/main.js +0 -18
  94. package/cjs/preload.d.ts +0 -3
  95. package/cjs/preload.js +0 -10
  96. package/cjs/renderer.d.ts +0 -2
  97. package/cjs/renderer.js +0 -8
  98. package/cjs/scripts/bridge.d.ts +0 -8
  99. package/cjs/scripts/bridge.js +0 -57
  100. package/cjs/scripts/main.d.ts +0 -8
  101. package/cjs/scripts/main.js +0 -72
  102. package/cjs/scripts/new-decorators.d.ts +0 -150
  103. package/cjs/scripts/new-decorators.js +0 -141
  104. package/cjs/scripts/old-decorators.d.ts +0 -185
  105. package/cjs/scripts/old-decorators.js +0 -132
  106. package/cjs/scripts/preload-provider.d.ts +0 -7
  107. package/cjs/scripts/preload-provider.js +0 -96
  108. package/cjs/scripts/provider.d.ts +0 -25
  109. package/cjs/scripts/provider.js +0 -116
  110. package/cjs/scripts/publish.d.ts +0 -40
  111. package/cjs/scripts/publish.js +0 -232
  112. package/cjs/scripts/renderer-tunnels.d.ts +0 -47
  113. package/cjs/scripts/renderer-tunnels.js +0 -115
  114. package/esm/enums.d.ts +0 -19
  115. package/esm/enums.js +0 -22
  116. package/esm/exp.d.ts +0 -4
  117. package/esm/exp.js +0 -3
  118. package/esm/index.d.ts +0 -4
  119. package/esm/index.js +0 -3
  120. package/esm/main.d.ts +0 -4
  121. package/esm/main.js +0 -3
  122. package/esm/preload.d.ts +0 -3
  123. package/esm/preload.js +0 -2
  124. package/esm/renderer.d.ts +0 -2
  125. package/esm/renderer.js +0 -1
  126. package/esm/scripts/bridge.d.ts +0 -8
  127. package/esm/scripts/bridge.js +0 -52
  128. package/esm/scripts/main.d.ts +0 -8
  129. package/esm/scripts/main.js +0 -67
  130. package/esm/scripts/new-decorators.d.ts +0 -150
  131. package/esm/scripts/new-decorators.js +0 -132
  132. package/esm/scripts/old-decorators.d.ts +0 -185
  133. package/esm/scripts/old-decorators.js +0 -122
  134. package/esm/scripts/preload-provider.d.ts +0 -7
  135. package/esm/scripts/preload-provider.js +0 -91
  136. package/esm/scripts/provider.d.ts +0 -25
  137. package/esm/scripts/provider.js +0 -113
  138. package/esm/scripts/publish.d.ts +0 -40
  139. package/esm/scripts/publish.js +0 -220
  140. package/esm/scripts/renderer-tunnels.d.ts +0 -47
  141. package/esm/scripts/renderer-tunnels.js +0 -109
package/LICENCE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2023 VerZsuT
3
+ Copyright (c) 2024 VerZsuT
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,461 +1,268 @@
1
1
  # Electron main-renderer bridge (emr-bridge)
2
2
 
3
- _Only for Electron_
4
- JS library for easily providing access to the **main** from the **renderer** process
5
-
6
- ## Table of contents
7
-
8
- - [Installation](#installation)
9
- - [Usage](#usage)
10
- - [static](#static-methods-and-properties)
11
- - [non-static](#methods-and-properties)
12
- - [functions and variables](#functions-and-variables)
13
- - [scopes](#scopes)
14
- - [access](#restricting-access-to-variables)
15
- - [usage in renderer](#access-from-renderer-and-preload)
16
- - [promises](#promises)
17
- - [events](#events-system)
18
-
19
- ## Installation
20
-
21
- ```text
22
- npm i emr-bridge
23
- ```
3
+ _Только для Electron._
24
4
 
25
- ## Usage
5
+ _Полная поддержка TypeScript._
26
6
 
27
- *If you need CommonJS modules, then use `emr-bridge/cjs`*
7
+ Уменьшает boilerplate при работе с **Electron IPC**:
8
+ - Функционал событий.
9
+ - Лёгкая передача экземпляров классов.
10
+ - Простое использование промисов.
11
+ - Быстрая публикация переменных и функций из `main` в `renderer` / `preload`.
28
12
 
29
- There are three ways to use
13
+ ## Содержание
30
14
 
31
- > In any of the cases, you need to insert this code into preload
15
+ - [Установка](#установка)
16
+ - [Использование](#использование)
17
+ - [публикация](#публикация-функций-и-переменных)
18
+ - [renderer и preload](#использование-в-renderer-и-preload)
19
+ - [промисы](#промисы)
20
+ - [события](#события)
21
+ - [передача экземпляров классов](#передача-экземпляров-классов)
32
22
 
33
- ```js
34
- // Preload process
35
- import { provideFromMain } from 'emr-bridge'
23
+ ## Установка
36
24
 
37
- provideFromMain(true /* context isolation */)
25
+ ```cmd
26
+ npm i emr-bridge@latest
38
27
  ```
39
28
 
40
- > To use experimental non-static decorators, it is required to wrap the creation of a class instance in the `providePublic` function
29
+ Для работы библиотеки требуется вставить следующий код в preload процесс.
41
30
 
42
31
  ```js
43
- // Main process
44
- import { providePublic } from 'emr-bridge/exp'
32
+ import { provideFromMain } from 'emr-bridge/preload'
45
33
 
46
- class MainPublic { /*...*/ }
47
-
48
- const instance = providePublic(new MainPublic())
34
+ provideFromMain(true /* context isolation */)
49
35
  ```
50
36
 
51
- > All experimental decorators can be found in `emr-bridge/exp`
37
+ ## Использование
52
38
 
53
- ### Static methods and properties
39
+ *Если требуется CommonJS, то используем `emr-bridge/cjs`*.
54
40
 
55
- Use **publicMethod**/**publicProperty**/**publicGetter**/**publicSetter**.
41
+ ### Публикация функций и переменных
56
42
 
57
- ```ts
58
- // Main process
59
- import { publicMethod, publicProperty, publicGetter, publicSetter, Access } from 'emr-bridge'
60
-
61
- class User {
62
- private static name = 'Name'
63
- private static age = 20
64
- private static money = 1000
65
-
66
- @publicGetter('userBalance')
67
- static get balance(): string {
68
- return `${this.money}$`
69
- }
70
-
71
- @publicSetter('userBalance')
72
- static set balance(newBalance: string) {
73
- this.money = Number(newBalance.split('$')[0])
74
- }
75
-
76
- @publicGetter({
77
- name: 'userInfo',
78
- access: Access.get
79
- })
80
- static get info(): string {
81
- return `Name: '${this.name}'; Age: '${this.age}'; Money: '${this.money}';`
82
- }
43
+ Для публикации функций и переменных из `main` процесса библиотека предоставляет
44
+ функции `publishFunction` и `publishVariable` из **emr-bridge/main**.
83
45
 
84
- @publicProperty()
85
- static id = 'ID_AJWD3KLW23DK231K'
86
-
87
- @publicMethod()
88
- static setName(newName: string): void {
89
- this.name = newName
90
- }
91
-
92
- @publicMethod('getUserAge')
93
- static getAge(): number {
94
- return this.age
95
- }
96
- }
97
- ```
98
-
99
- ### Methods and properties
100
-
101
- Use **publicMethod**/**publicProperty**/**publicGetter**/**publicSetter**.
102
-
103
- ```ts
46
+ ```js
104
47
  // Main process
105
- import { publicMethod, publicProperty, publicGetter, publicSetter, Access } from 'emr-bridge'
106
-
107
- class User {
108
- private name = 'Name'
109
- private age = 20
110
- private money = 1000
111
-
112
- @publicProperty()
113
- id = 'ID_AJWD3KLW23DK231K'
114
-
115
- @publicGetter()
116
- get balance(): string {
117
- return `${this.money}$`
118
- }
119
-
120
- @publicSetter()
121
- set balance(newBalance: string) {
122
- this.money = Number(newBalance.split('$')[0])
123
- }
124
-
125
- @publicGetter({
126
- name: 'userInfo',
127
- access: Access.get
128
- })
129
- get info(): string {
130
- return `Name: '${this.name}'; Age: '${this.age}'; Money: '${this.money}';`
131
- }
132
-
133
- @publicMethod()
134
- setName(newName: string): void {
135
- this.name = newName
136
- }
137
-
138
- @publicMethod('getUserAge')
139
- getAge(): number {
140
- return this.age
141
- }
142
- }
143
-
144
- const user = new User()
145
- ```
146
-
147
- ### Functions and variables
48
+ import { publishFunction, publishVariable } from 'emr-bridge/main'
148
49
 
149
- Use **publicFunction** and **publicVariable**.
50
+ publishFunction('sayHello', name => {
51
+ return `Hello, ${name}!`
52
+ })
150
53
 
151
- ```ts
152
- // Main process
153
- import { publicFunction, publicVariable } from 'emr-bridge'
154
-
155
- publicFunction('sayHello', sayHello)
156
- publicFunction('getUserName', getName)
157
- publicVariable('count', {
158
- get(): number {
159
- return count
160
- },
161
- set(value: number) {
162
- count = value
54
+ publishFunction('getUser', () => {
55
+ return {
56
+ name: 'Name',
57
+ age: 20
163
58
  }
164
59
  })
165
60
 
166
61
  let count = 0
167
62
 
168
- const user = {
169
- name: 'Name',
170
- age: 20
171
- }
172
-
173
- function sayHello(name: string): string {
174
- return `Hello, ${name}!`
175
- }
176
-
177
- function getName(): string {
178
- return user.name
179
- }
63
+ publishVariable('count', {
64
+ get: () => count,
65
+ set: value => count = value
66
+ })
180
67
  ```
181
68
 
182
- ### Scopes
69
+ ### Использование в renderer и preload
183
70
 
184
- In order to set a specific scope, use the **scope** property.
71
+ Пример использования ранее опубликованных функций и переменных.
185
72
 
186
- Accessing an entity outside the specified scope will result in an error being thrown.
187
-
188
- ```ts
189
- // Main process
190
-
191
- // static and non-static
192
- import { Scope, Access, publicMethod, publicGetter } from 'emr-bridge'
73
+ ```js
74
+ // Renderer process
75
+ import { Bridge } from 'emr-bridge/renderer'
193
76
 
194
- class User {
195
- private static age = 20
196
- private name = 'Name'
197
-
198
- @publicGetter({
199
- scope: Scope.preload,
200
- access: Access.get
201
- })
202
- get count(): number {
203
- return 30
204
- }
205
-
206
- @publicMethod({ scope: Scope.preload })
207
- static getAge(): number {
208
- return this.age
209
- }
210
-
211
- @publicMethod({
212
- name: 'getUserName',
213
- scope: Scope.renderer
214
- })
215
- getName(): string {
216
- return this.name
217
- }
218
- }
77
+ // `as` в TypeScript позволяет кастовать в нужный тип.
78
+ const bridge = Bridge.as()
219
79
 
220
- new User()
221
- ```
80
+ // Выведет текущее значение count из main (0).
81
+ console.log(bridge.count)
222
82
 
223
- ```ts
224
- // Main process
225
- // functions and variables
226
- import { publicFunction, publicVariable, Scope } from 'emr-bridge'
227
-
228
- publicFunction('getName', getName, [Scope.preload])
229
- publicVariable('count', {
230
- get(): number {
231
- return count
232
- },
233
- set(value: number) {
234
- count = value
235
- }
236
- }, [Scope.renderer])
83
+ // Увеличит значение count в main на единицу.
84
+ bridge.count++
237
85
 
238
- let count = 0
86
+ // { name: 'Name', age: 20 }.
87
+ bridge.getUser()
239
88
 
240
- function getName(): string {
241
- return 'Name'
242
- }
89
+ // 'Hello, Aleksandr!'.
90
+ bridge.seyHello('Aleksandr')
243
91
  ```
244
92
 
245
- By default, the entity is available in any scope.
246
- Using an entity outside the specified scope _will cause an error_.
93
+ Для `preload` процесса всё идентично, но требуется импортировать из **emr-bridge/preload**.
247
94
 
248
- ### Restricting access to variables
95
+ ### Промисы
249
96
 
250
- ```ts
251
- // Main process
252
- // static and non-static
253
- import { publicGetter, Access } from 'emr-bridge'
254
-
255
- class User {
256
- private static name = 'Name'
257
- private static surname = 'Surname'
258
-
259
- @publicGetter({ access: Access.get })
260
- static get fullName(): string {
261
- return `${this.name} ${this.surname}`
262
- }
263
-
264
- @publicProperty({
265
- name: 'userAge',
266
- access: Access.get
267
- })
268
- get age(): number {
269
- return 20
270
- }
271
- }
272
-
273
- new User()
274
- ```
97
+ Поддержка промисов реализована "из коробки".
275
98
 
276
- ```ts
99
+ ```js
277
100
  // Main process
278
- // for variables
279
- import { publicVariable } from 'emr-bridge'
280
-
281
- publicVariable('count', {
282
- // get access
283
- get(): number {
284
- return count
285
- },
286
- // set access
287
- set(value: number) {
288
- count = value
289
- }
290
- })
101
+ import { publishFunction } from 'emr-bridge/main'
291
102
 
292
- let count = 0
103
+ publishFunction('after1s', () => {
104
+ return new Promise(resolve => {
105
+ setTimeout(() => resolve('after1s'), 1000)
106
+ })
107
+ })
293
108
  ```
294
109
 
295
- ### Access from renderer and preload
296
-
297
- For _preload_, use **Main**
110
+ ```js
111
+ // Renderer process
112
+ import { Bridge } from 'emr-bridge/renderer'
298
113
 
299
- ```ts
300
- // Preload process
301
- import { Main, provideFromMain } from 'emr-bridge/preload'
114
+ const bridge = Bridge.as()
302
115
 
303
- provideFromMain()
116
+ async function foo() {
117
+ const result = await bridge.after1s()
304
118
 
305
- interface IProvidedPublic {
306
- getUserName(): string
307
- setUserAge(newAge: number): void
308
- count: number
119
+ // Через 1 секунду выведет сообщение 'after1s', полученное из main.
120
+ console.log(result)
309
121
  }
122
+ ```
310
123
 
311
- const main = Main.as<IProvidedPublic>()
124
+ ### События
312
125
 
313
- main.getUserName()
314
- main.count++
315
- main.setUserAge(20)
316
- ```
126
+ Пример обработки события, которое вызывается из `renderer` или `preload`.
317
127
 
318
- For _renderer_, use **Bridge**
128
+ ```js
129
+ // Main process
130
+ import { on, once } from 'emr-bridge/main'
319
131
 
320
- ```ts
132
+ on('message-from-renderer', message => console.log(message))
133
+ // once('message-from-renderer', message => console.log(message))
134
+ ```
135
+
136
+ ```js
321
137
  // Renderer process
322
138
  import { Bridge } from 'emr-bridge/renderer'
323
139
 
324
- interface IProvidedPublic {
325
- getUserName(): string
326
- setUserAge(newAge: number): void
327
- count: number
328
- }
329
-
330
- const bridge = Bridge.as<IProvidedPubic>()
140
+ const bridge = Bridge.as()
331
141
 
332
- bridge.getUserName()
333
- bridge.count--
334
- bridge.setUserAge(30)
142
+ // Вызовет событие и выведет в консоль main процесса 'Hello from renderer'
143
+ bridge.emit('message-from-renderer', 'Hello from renderer')
335
144
  ```
336
145
 
337
- ### Promises
146
+ Пример обработки события, которое вызывается из `main`.
338
147
 
339
- The library also allows you to pass Promises from main to renderer
340
-
341
- ```ts
148
+ ```js
342
149
  // Main process
343
- import { publicFunction } from 'emr-bridge'
150
+ import { emitEvent } from 'emr-bridge/main'
344
151
 
345
- publicFunction('delay1s', () => {
346
- return new Promise<void>(resolve => {
347
- setTimeout(resolve, 1000)
348
- })
349
- })
152
+ // Вызовет событие и выведет в консоль renderer процесса 'Hello from main'
153
+ emitEvent('message-from-main', 'Hello from main')
350
154
  ```
351
155
 
352
- ```ts
156
+ ```js
353
157
  // Renderer process
354
158
  import { Bridge } from 'emr-bridge/renderer'
355
159
 
356
- interface IPublic {
357
- delay1s(): Promise<void>
358
- }
359
-
360
- const bridge = Bridge.as<IPublic>()
160
+ const bridge = Bridge.as()
361
161
 
362
- bridge.delay1s().then(() => console.log('After 1 second'))
162
+ bridge.on('message-from-main', message => console.log(message))
363
163
  ```
364
164
 
365
- ### Events system
165
+ ### Передача экземпляров классов
366
166
 
367
- If the event source is the **main** process
368
-
369
- ```ts
370
- // Main process
371
- import { publicMainEvent, publicClassMainEvent } from 'emr-bridge'
167
+ По умолчанию, передача экземпляров пользовательских классов через IPC невозможна.
372
168
 
373
- const tickWithReceiver = publicMainEvent('tickWithReceiver', () => (new Date().toTimeString()))
374
- setInterval(tickWithReceiver, 1000)
169
+ Библиотека решает эту проблему путём реализации паттерна 'Снимок'.
375
170
 
376
- // Or
377
- const tick = publicMainEvent('tick')
378
- setInterval(() => tick(new Date().toTimeString()), 1000)
171
+ Передаваемый класс должен реализовать функции `getSnapshot` и `updateFromSnapshot`, а также иметь конструктор без параметров.
379
172
 
380
- // The passed function receives the argument passed to the event and returns the value passed to the renderer process
381
- const pay = publicMainEvent('pay', (count: number) => `${count} $`)
382
- pay(200) // Send the string '200 $' to the renderer process
383
-
384
-
385
- // Or with classes
386
- class MainPublicEvents {
387
- @publicClassMainEvent()
388
- tick() {}
173
+ ```js
174
+ // Human.js
175
+ export default class Human {
176
+ name = undefined
177
+ age = undefined
178
+
179
+ constructor(
180
+ name = 'Aleksandr',
181
+ age = 30
182
+ ) {
183
+ this.name = name
184
+ this.age = age
185
+ }
389
186
 
390
- @publicClassMainEvent()
391
- tickWithReceiver() { return new Date().toTimeString() }
187
+ getSnapshot() {
188
+ return {
189
+ name: this.name,
190
+ age: this.age
191
+ }
192
+ }
392
193
 
393
- @publicClassMainEvent()
394
- pay(count: number) { return `${count} $` }
194
+ updateFromSnapshot(snapshot) {
195
+ this.name = snapshot.name
196
+ this.age = snapshot.age
197
+ }
395
198
  }
396
- const events = new MainPublicEvents()
397
- setInterval(events.tickWithReceiver, 1000)
398
- setInterval(() => events.tick(new Date().toTimeString()), 1000)
399
- events.pay(200)
400
199
  ```
401
200
 
402
- ```ts
403
- // Renderer process
404
- import { Bridge, MainEvent } from 'emr-bridge/renderer'
201
+ Для передачи экземпляра класса требуется на **принимающей** стороне передать сам класс в качестве аргумента функции:
405
202
 
406
- interface IPublic {
407
- onTick: MainEvent<string>
408
- onTickWithReceiver: MainEvent<string>
409
- onPay: MainEvent<string>
410
- }
411
-
412
- const bridge = Bridge.as<IPublic>()
413
- // on + Capitalize<EventName>
414
- bridge.onTick(time => `Time from tick: ${console.log(time)}`)
415
- bridge.onTickWithReceiver(time => `Time from receiver: ${console.log(time)}`)
416
- bridge.onPay(count => `Dollars: ${count}`)
203
+ ```js
204
+ // Main process
205
+ import { publishFunction } from 'emr-bridge/main'
206
+ import Human from './Human'
207
+
208
+ // Выводим имя человека, переданного из `preload` или `renderer`.
209
+ publishFunction(
210
+ 'displayName',
211
+ human => console.log(human.name),
212
+ /* Говорим какие классы надо принять.
213
+ Порядок в массиве соответствует порядку таких аргументов в функции.
214
+ Для (human, car, engine) будет [Human, Car, Engine].
215
+ Для (human, surname, car) будет [Human, Car], так как 'surname' имеет стандартный тип String.
216
+ Стандартные типы (String, Number..) указывать не требуется. */
217
+ [Human]
218
+ )
219
+
220
+ /* У событий также есть такой аргумент
221
+ on('displayName', human => console.log(human.name), Human)
222
+ once('displayName', human => console.log(human.name), Human)
223
+ */
417
224
  ```
418
225
 
419
- If the event source is the **renderer** process
226
+ ```js
227
+ // Renderer process
228
+ import { Bridge } from 'emr-bridge/renderer'
229
+ import Human from './Human'
420
230
 
421
- ```ts
422
- // Main process
423
- import { publicRendererEvent, publicClassRendererEvent, RendererEvent } from 'emr-bridge'
231
+ const bridge = Bridge.as()
424
232
 
425
- const onMessage = publicRendererEvent<string>('onMessage'/* or 'message' */)
426
- onMessage(message => console.log(message))
233
+ // Передаст данные через создание снимка.
234
+ bridge.displayName(new Human('Dima', 25))
235
+ ```
427
236
 
428
- // With receiver
429
- const onMessageWithReceiver = publicRendererEvent('onMessageWithReceiver', (message: string) => `Message: ${message}`)
430
- onMessageWithReceiver(message => console.log(message))
237
+ Для получения экземпляра класса из `main` в `renderer` или `preload` нужно использовать `bridge.call`.
431
238
 
239
+ _Такое требование связано со сложностью реализации._
432
240
 
433
- // Classes
434
- class RendererPublicEvents {
435
- @publicClassRendererEvent()
436
- onMessage!: RendererEvent<string>
241
+ ```js
242
+ // Main process
243
+ import { publishFunction } from 'emr-bridge/main'
244
+ import Human from './Human'
437
245
 
438
- @publicClassRendererEvent((message: string) => `Message: ${message}`)
439
- onMessageWithReceiver!: RendererEvent<string>
440
- }
441
- const events = new RendererPublicEvents()
442
- events.onMessage(message => console.log(message))
443
- events.onMessageWithReceiver(message => console.log(message))
246
+ // Передаём человека в `preload` или `renderer` процесс.
247
+ publishFunction('getHuman', () => new Human('Artem', 40))
444
248
  ```
445
249
 
446
- ```ts
250
+ ```js
447
251
  // Renderer process
448
252
  import { Bridge } from 'emr-bridge/renderer'
253
+ import Human from './Human'
449
254
 
450
- interface IPublic {
451
- message(message: string): void
452
- messageWithReceiver(message: string): void
453
- }
255
+ const bridge = Bridge.as()
454
256
 
455
- const bridge = Bridge.as<IPublic>()
456
- // Uncapitalize<EventNameWithoutON>
457
- bridge.message('Message from renderer')
458
- bridge.messageWithReceiver('Hello, main process')
459
- ```
257
+ // Выведет в консоль 25
258
+ console.log(
259
+ bridge.call(bridge.getHuman, Human).name
260
+ )
261
+
262
+ /* Альтернативный вариант
263
+ // Оборачиваем оригинал новой функцией, которая автоматически преобразует ответ в нужный класс.
264
+ bridge.getHuman = bridge.returns(bridge.getHuman, Human)
460
265
 
461
- **NOTE**: The transmitted value can be `Promise`. In this case, the receiving party will wait for it to resolve and only then will call the handler
266
+ console.log(bridge.getHuman().name)
267
+ */
268
+ ```
@@ -0,0 +1 @@
1
+ export type { EventListener, EventUnsubscribe, HasSnapshotClass, IBridge, IHasSnapshot } from '../types.js';
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ /*
3
+ Главная точка входа.
4
+ Экспорт только типов потому что одновременный импорт для разных процессов приводит к ошибке.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,2 @@
1
+ export { emitEvent, on, once, publishFunction, publishVariable } from '../scripts/main/publish.js';
2
+ export * from './index.js';