@aloma.io/integration-sdk 3.8.69 → 3.8.71

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 (117) hide show
  1. package/README.md +15 -2
  2. package/build/internal/connector/server/on-connect/make-oauth.mjs +27 -6
  3. package/build/internal/fetcher/fetcher.d.mts +22 -1
  4. package/build/internal/fetcher/fetcher.mjs +99 -14
  5. package/build/internal/fetcher/oauth-fetcher.d.mts +15 -2
  6. package/build/internal/fetcher/oauth-fetcher.mjs +72 -27
  7. package/build/internal/util/index.d.mts +8 -0
  8. package/build/internal/util/index.mjs +13 -1
  9. package/build/internal/util/jwe/index.mjs +3 -1
  10. package/build/openapi-to-connector.mjs +5 -2
  11. package/package.json +9 -4
  12. package/.prettierrc.cjs +0 -8
  13. package/MULTI_RESOURCE_GUIDE.md +0 -220
  14. package/OPENAPI_TO_CONNECTOR.md +0 -346
  15. package/examples/hello-world/package.json +0 -25
  16. package/examples/hello-world/src/controller/index.mts +0 -12
  17. package/examples/hello-world/src/index.mts +0 -6
  18. package/examples/hello-world/tsconfig.json +0 -27
  19. package/examples/sample-api.json +0 -325
  20. package/examples/sample-api.yaml +0 -222
  21. package/examples/simple-api.json +0 -39
  22. package/index.js +0 -4
  23. package/src/builder/index.mts +0 -274
  24. package/src/builder/runtime-context.mts +0 -129
  25. package/src/cli.mts +0 -533
  26. package/src/controller/index.mts +0 -278
  27. package/src/index.mts +0 -2
  28. package/src/internal/connector/config.mts +0 -59
  29. package/src/internal/connector/index.mts +0 -53
  30. package/src/internal/connector/metrics.mts +0 -34
  31. package/src/internal/connector/server/index.mts +0 -51
  32. package/src/internal/connector/server/on-connect/decrypt-config.mts +0 -27
  33. package/src/internal/connector/server/on-connect/finish-oauth.mts +0 -109
  34. package/src/internal/connector/server/on-connect/index.mts +0 -162
  35. package/src/internal/connector/server/on-connect/make-oauth.mts +0 -97
  36. package/src/internal/connector/server/on-connect/start-oauth.mts +0 -24
  37. package/src/internal/connector/server/on-message.mts +0 -13
  38. package/src/internal/dispatcher/index.mts +0 -231
  39. package/src/internal/fetcher/fetcher.mts +0 -166
  40. package/src/internal/fetcher/oauth-fetcher.mts +0 -153
  41. package/src/internal/index.mts +0 -3
  42. package/src/internal/util/index.mts +0 -52
  43. package/src/internal/util/jwe/cli.mts +0 -12
  44. package/src/internal/util/jwe/index.mts +0 -72
  45. package/src/internal/websocket/config.mjs +0 -109
  46. package/src/internal/websocket/connection/constants.mjs +0 -25
  47. package/src/internal/websocket/connection/index.mjs +0 -71
  48. package/src/internal/websocket/connection/registration.mjs +0 -42
  49. package/src/internal/websocket/index.mjs +0 -46
  50. package/src/internal/websocket/transport/durable.mjs +0 -71
  51. package/src/internal/websocket/transport/index.mjs +0 -194
  52. package/src/internal/websocket/transport/packet.mjs +0 -54
  53. package/src/internal/websocket/transport/processor.mjs +0 -66
  54. package/src/openapi-to-connector.mts +0 -1644
  55. package/src/testing/fake-aloma.mts +0 -306
  56. package/src/testing/harness.mts +0 -172
  57. package/src/testing/index.mts +0 -15
  58. package/src/testing/keys.mts +0 -19
  59. package/src/testing/network-guard.mts +0 -57
  60. package/src/testing/runtime-connector.mts +0 -50
  61. package/src/testing/vendor-mock.mts +0 -166
  62. package/src/transform/index.mts +0 -544
  63. package/test/MUTATION-entry.md +0 -21
  64. package/test/MUTATION.md +0 -43
  65. package/test/dispatcher-ctx-forwarding.test.mjs +0 -161
  66. package/test/fixtures/transform/basic/expected.json +0 -9
  67. package/test/fixtures/transform/basic/src/controller/abstract.mts +0 -5
  68. package/test/fixtures/transform/basic/src/controller/index.mts +0 -30
  69. package/test/fixtures/transform/basic/tsconfig.json +0 -1
  70. package/test/fixtures/transform/interface-param/src/controller/abstract.mts +0 -5
  71. package/test/fixtures/transform/interface-param/src/controller/index.mts +0 -12
  72. package/test/fixtures/transform/interface-param/tsconfig.json +0 -1
  73. package/test/fixtures/transform/overloads/expected.json +0 -6
  74. package/test/fixtures/transform/overloads/src/controller/abstract.mts +0 -5
  75. package/test/fixtures/transform/overloads/src/controller/index.mts +0 -11
  76. package/test/fixtures/transform/overloads/tsconfig.json +0 -1
  77. package/test/fixtures/transform/tdd-stub/expected.json +0 -8
  78. package/test/fixtures/transform/tdd-stub/src/controller/abstract.mts +0 -6
  79. package/test/fixtures/transform/tdd-stub/src/controller/index.mts +0 -204
  80. package/test/fixtures/transform/tdd-stub/tsconfig.json +0 -1
  81. package/test/fixtures/transform/two-exports/src/controller/abstract.mts +0 -5
  82. package/test/fixtures/transform/two-exports/src/controller/index.mts +0 -9
  83. package/test/fixtures/transform/two-exports/tsconfig.json +0 -1
  84. package/test/fixtures/transform/type-error/src/controller/abstract.mts +0 -5
  85. package/test/fixtures/transform/type-error/src/controller/index.mts +0 -7
  86. package/test/fixtures/transform/type-error/tsconfig.json +0 -1
  87. package/test/fixtures/transform/typed/expected.json +0 -8
  88. package/test/fixtures/transform/typed/src/controller/abstract.mts +0 -5
  89. package/test/fixtures/transform/typed/src/controller/index.mts +0 -13
  90. package/test/fixtures/transform/typed/tsconfig.json +0 -1
  91. package/test/fixtures/transform/visibility/expected.json +0 -9
  92. package/test/fixtures/transform/visibility/src/controller/abstract.mts +0 -5
  93. package/test/fixtures/transform/visibility/src/controller/index.mts +0 -19
  94. package/test/fixtures/transform/visibility/tsconfig.json +0 -1
  95. package/test/harness-connector-smoke.test.mjs +0 -72
  96. package/test/harness.test.mjs +0 -375
  97. package/test/nested-resolver.test.mjs +0 -184
  98. package/test/openapi-generator-bugs.test.mjs +0 -248
  99. package/test/openapi-identifier-sanitise.test.mjs +0 -69
  100. package/test/openapi-nested-paths.test.mjs +0 -100
  101. package/test/openapi-to-connector.test.mts +0 -225
  102. package/test/openapi-ts-compilation.test.mjs +0 -178
  103. package/test/scenarios/README.md +0 -148
  104. package/test/scenarios/complex/expected/controller.mts +0 -271
  105. package/test/scenarios/complex/expected/orders-resource.mts +0 -262
  106. package/test/scenarios/complex/expected/products-resource.mts +0 -237
  107. package/test/scenarios/complex/specs/orders.json +0 -362
  108. package/test/scenarios/complex/specs/products.json +0 -308
  109. package/test/scenarios/simple/expected-controller.mts +0 -60
  110. package/test/scenarios/simple/simple-api.json +0 -39
  111. package/test/scenarios.test.mts +0 -294
  112. package/test/transform.test.mjs +0 -68
  113. package/test/verify-scenarios.mjs +0 -298
  114. package/tools/mutation-run-entry.mjs +0 -52
  115. package/tools/mutation-run.mjs +0 -120
  116. package/tools/run-tests.mjs +0 -64
  117. package/tsconfig.json +0 -27
@@ -1,153 +0,0 @@
1
- import Fetcher from './fetcher.mjs';
2
-
3
- class OAuthFetcher extends Fetcher {
4
- oauth: any;
5
- _getToken: any;
6
- used: boolean = false;
7
- constructor({oauth, retry = 5, getToken, baseUrl, onResponse, customize}) {
8
- super({retry, baseUrl, onResponse, customize});
9
-
10
- this.oauth = oauth;
11
- this._getToken = getToken;
12
- }
13
-
14
- async __healthCheck() {
15
- if (this.used && !this.oauth.accessToken()) throw new Error('no access token');
16
- }
17
-
18
- async getToken(force) {
19
- var local = this,
20
- oauth = local.oauth;
21
-
22
- this.used = true;
23
-
24
- if (local._getToken) return local._getToken(force);
25
-
26
- if (!force && oauth.accessToken()) return oauth.accessToken();
27
-
28
- const refreshToken = oauth.refreshToken();
29
-
30
- try {
31
- if (!refreshToken) {
32
- throw new Error('have no access_token and no refresh_token');
33
- }
34
-
35
- const ret = await oauth.obtainViaRefreshToken(oauth.refreshToken());
36
-
37
- if (ret.access_token) {
38
- oauth.update(ret.access_token, ret.refresh_token);
39
-
40
- return ret.access_token;
41
- } else {
42
- throw new Error('could not obtain access token via refresh token');
43
- }
44
- } catch (e) {
45
- oauth.invalidate(e);
46
-
47
- throw e;
48
- }
49
- }
50
-
51
- async onError(e, url, options, retries, args, rateLimit) {
52
- var local = this;
53
-
54
- return new Promise((resolve, reject) => {
55
- setTimeout(
56
- async () => {
57
- try {
58
- resolve(
59
- await local.fetch(url, options, retries, {
60
- forceTokenRefresh: e.status === 401,
61
- })
62
- );
63
- } catch (e) {
64
- reject(e);
65
- }
66
- },
67
- rateLimit ? 10000 : 500
68
- );
69
- });
70
- }
71
-
72
- async periodicRefresh() {
73
- const local = this,
74
- oauth = local.oauth;
75
-
76
- console.log('refreshing oauth token, have token', !!oauth.refreshToken());
77
- if (!oauth.refreshToken()) return;
78
-
79
- await local.getToken(true);
80
-
81
- console.log('refreshed oauth token');
82
- }
83
-
84
- async customize(options: any, args: any = {}) {
85
- const local = this;
86
-
87
- if (this.customize0) await this.customize0(options, args);
88
-
89
- const token = await local.getToken(args.forceTokenRefresh);
90
-
91
- options.headers = {
92
- ...options.headers,
93
- Authorization: `Bearer ${token}`,
94
- };
95
- }
96
- }
97
-
98
- export class OAuth {
99
- _data: any;
100
- saveOAuthResult: any;
101
- obtainViaRefreshToken: any;
102
- clients: any[];
103
- constructor(data, saveOAuthResult, getRefreshToken) {
104
- this._data = data || {};
105
- this.saveOAuthResult = saveOAuthResult;
106
- this.obtainViaRefreshToken = getRefreshToken;
107
- this.clients = [];
108
- }
109
-
110
- data() {
111
- return this._data;
112
- }
113
-
114
- accessToken() {
115
- return this._data.access_token;
116
- }
117
-
118
- refreshToken() {
119
- return this._data.refresh_token;
120
- }
121
-
122
- async update(accessToken, refreshToken) {
123
- this._data.access_token = accessToken;
124
-
125
- if (refreshToken) {
126
- this._data.refresh_token = refreshToken;
127
- }
128
-
129
- await this.saveOAuthResult(this._data);
130
- }
131
-
132
- async periodicRefresh() {
133
- const clients = this.clients;
134
-
135
- console.log('refreshing oauth clients', clients.length);
136
-
137
- for (let i = 0; i < clients.length; ++i) {
138
- const client = clients[0];
139
-
140
- await client.periodicRefresh();
141
- }
142
- }
143
-
144
- async invalidate(err) {
145
- this._data.access_token = null;
146
- }
147
-
148
- getClient(arg: any = {}) {
149
- const client = new OAuthFetcher({...arg, oauth: this});
150
- this.clients.push(client);
151
- return client;
152
- }
153
- }
@@ -1,3 +0,0 @@
1
- import {Connector} from './connector/index.mjs';
2
-
3
- export {Connector};
@@ -1,52 +0,0 @@
1
- export const handlePacketError = (packet, e, transport) => {
2
- if (!packet.cb()) {
3
- console.dir({msg: 'packet error', e, packet}, {depth: null});
4
- return;
5
- }
6
-
7
- transport.send(transport.newPacket({c: packet.cb(), a: {error: '' + e}}));
8
- };
9
-
10
- export const reply = (arg, packet, transport) => {
11
- if (!packet.cb()) {
12
- console.dir({msg: 'cannot reply to packet without cb', arg, packet}, {depth: null});
13
- return;
14
- }
15
-
16
- transport.send(transport.newPacket({c: packet.cb(), a: {...arg}}));
17
- };
18
-
19
- export const unwrap0 = (ret, body, options) => {
20
- if (options?.bodyOnly === false) {
21
- return {status: ret.status, headers: ret.headers, body};
22
- } else {
23
- return body;
24
- }
25
- };
26
-
27
- export const unwrap = async (ret, options) => {
28
- if (options?.text) return unwrap0(ret, await ret.text(), options);
29
- if (options?.base64) {
30
- const base64 = Buffer.from(await ret.arrayBuffer()).toString('base64');
31
-
32
- return unwrap0(ret, base64, options);
33
- }
34
-
35
- if (options?.skipResponseBody) {
36
- return {status: ret.status, headers: ret.headers};
37
- }
38
-
39
- const text = await ret.text();
40
-
41
- try {
42
- return unwrap0(ret, JSON.parse(text), options);
43
- } catch (e) {
44
- throw e + ' ' + text;
45
- }
46
- };
47
-
48
- export const notEmpty = (what, name) => {
49
- if (!what?.trim()) throw new Error(`${name} cannot be empty`);
50
-
51
- return what;
52
- };
@@ -1,12 +0,0 @@
1
- import JWE from './index.mjs';
2
-
3
- const main = async () => {
4
- const jwe = new JWE({});
5
- await jwe.newPair();
6
-
7
- console.log('PRIVATE_KEY=' + (await jwe.exportPrivateAsBase64()));
8
- console.log('PUBLIC_KEY=' + (await jwe.exportPublicAsBase64()));
9
- };
10
-
11
- setTimeout(() => null, 100);
12
- main();
@@ -1,72 +0,0 @@
1
- import * as jose from 'jose';
2
-
3
- class JWE {
4
- issuer: string;
5
- algorithm: string;
6
- pair?: jose.GenerateKeyPairResult<jose.KeyLike>;
7
- constructor({algorithm = 'PS256'}) {
8
- this.issuer = 'home.aloma.io';
9
- this.algorithm = algorithm;
10
- }
11
-
12
- async newPair() {
13
- this.pair = await jose.generateKeyPair(this.algorithm);
14
- }
15
-
16
- async exportPair() {
17
- return {
18
- publicKey: await jose.exportSPKI(this.pair!.publicKey),
19
- privateKey: await jose.exportPKCS8(this.pair!.privateKey),
20
- };
21
- }
22
-
23
- async exportPrivateAsBase64() {
24
- const pair = await this.exportPair();
25
-
26
- return Buffer.from(pair.privateKey).toString('base64');
27
- }
28
-
29
- async exportPublicAsBase64() {
30
- const pair = await this.exportPair();
31
-
32
- return Buffer.from(pair.publicKey).toString('base64');
33
- }
34
-
35
- async importPair({publicKey, privateKey, algorithm}) {
36
- this.pair = {
37
- publicKey: await jose.importSPKI(publicKey, algorithm),
38
- privateKey: await jose.importPKCS8(privateKey, algorithm),
39
- };
40
- }
41
-
42
- async importBase64Pair({publicKey, privateKey, algorithm}) {
43
- this.importPair({
44
- publicKey: Buffer.from(publicKey, 'base64').toString(),
45
- privateKey: Buffer.from(privateKey, 'base64').toString(),
46
- algorithm,
47
- });
48
- }
49
-
50
- async encrypt(what, expiration = '7d', audience, algorithm = 'RSA-OAEP-256') {
51
- const item = new jose.EncryptJWT({_data: {...what}})
52
- .setProtectedHeader({alg: algorithm, enc: 'A256GCM'})
53
- .setIssuedAt()
54
- .setIssuer(this.issuer)
55
- .setAudience(audience);
56
-
57
- if (expiration && expiration !== 'none') item.setExpirationTime(expiration);
58
-
59
- return await item.encrypt(this.pair!.publicKey);
60
- }
61
-
62
- async decrypt(what, audience) {
63
- const {payload, protectedHeader} = await jose.jwtDecrypt(what, this.pair!.privateKey, {
64
- issuer: this.issuer,
65
- audience,
66
- });
67
-
68
- return payload._data;
69
- }
70
- }
71
-
72
- export default JWE;
@@ -1,109 +0,0 @@
1
- import C from './connection/constants.mjs';
2
- import JWE from '../util/jwe/index.mjs';
3
-
4
- class Config {
5
- constructor({
6
- registrationToken,
7
- version,
8
- name,
9
- id,
10
- endpoint,
11
- wsEndpoint,
12
- privateKey,
13
- publicKey,
14
- introspect,
15
- configSchema,
16
- icon,
17
- }) {
18
- this._token = null;
19
- this._registrationToken = registrationToken;
20
- this._version = version;
21
- this._name = name;
22
- this._endpoint = endpoint;
23
- this._wsEndpoint = wsEndpoint;
24
- this._id = id;
25
- this._data = {};
26
- this._privateKey = privateKey;
27
- this._publicKey = publicKey;
28
- this._jwe = new JWE({});
29
- this._introspect = introspect;
30
- this._configSchema = configSchema;
31
- this._icon = icon;
32
-
33
- if (!registrationToken) throw new Error('empty registration token (set env.REGISTRATION_TOKEN)');
34
- if (!endpoint) throw new Error('empty endpoint (set env.DEVICE_ENDPOINT)');
35
- if (!wsEndpoint) throw new Error('empty registration token (set env.WEBSOCKET_ENDPOINT)');
36
-
37
- if (!this._id || !this._version) throw new Error('need connector id and version');
38
- }
39
-
40
- async validateKeys(algorithm) {
41
- if (!this._privateKey || !this._publicKey) throw new Error('need private and public key');
42
-
43
- await this._jwe.importBase64Pair({
44
- publicKey: this._publicKey,
45
- privateKey: this._privateKey,
46
- algorithm,
47
- });
48
-
49
- return this._jwe;
50
- }
51
-
52
- data(what) {
53
- if (what) {
54
- this._data = what;
55
- }
56
-
57
- return this._data;
58
- }
59
-
60
- introspect() {
61
- return this._introspect();
62
- }
63
-
64
- configSchema() {
65
- return this._configSchema();
66
- }
67
-
68
- publicKey() {
69
- return this._publicKey;
70
- }
71
-
72
- id() {
73
- return this._id;
74
- }
75
-
76
- version() {
77
- return this._version;
78
- }
79
-
80
- name() {
81
- return this._name;
82
- }
83
-
84
- url() {
85
- return this._endpoint;
86
- }
87
-
88
- wsUrl() {
89
- return this._wsEndpoint;
90
- }
91
-
92
- registrationToken() {
93
- return this._registrationToken;
94
- }
95
-
96
- token() {
97
- return this._token;
98
- }
99
-
100
- icon() {
101
- return this._icon;
102
- }
103
-
104
- setToken(what) {
105
- this._token = what;
106
- }
107
- }
108
-
109
- export {Config};
@@ -1,25 +0,0 @@
1
- const AUTHORIZATION = 'Authorization';
2
-
3
- export default {
4
- augmentRequest: (what, config) => {
5
- what.headers = {
6
- ...what.headers,
7
- 'User-Agent': config.id() + '/' + config.version(),
8
- };
9
-
10
- what.headers[AUTHORIZATION] = `Connector ${config.token()}`;
11
-
12
- return what;
13
- },
14
-
15
- augmentRegistration: (what, config) => {
16
- what.headers = {
17
- ...what.headers,
18
- 'User-Agent': config.id() + '/' + config.version(),
19
- };
20
-
21
- what.headers[AUTHORIZATION] = `Connector ${config.registrationToken()}`;
22
-
23
- return what;
24
- },
25
- };
@@ -1,71 +0,0 @@
1
- import {Registration} from './registration.mjs';
2
- import C from './constants.mjs';
3
-
4
- class Connection {
5
- constructor({config, onStart}) {
6
- this.config = config;
7
- this.onStart = onStart;
8
- }
9
-
10
- async start() {
11
- var local = this,
12
- config = local.config;
13
-
14
- try {
15
- const response = await fetch(
16
- config.url() + 'connect',
17
- C.augmentRequest(
18
- {
19
- method: 'POST',
20
- body: JSON.stringify({}),
21
- headers: {'Content-Type': 'application/json'},
22
- signal: AbortSignal.timeout(60 * 1000),
23
- },
24
- config
25
- )
26
- );
27
-
28
- if (response.status === 401) {
29
- config.setToken(await new Registration(local.config).run());
30
-
31
- return await local.start();
32
- } else if (response.status === 200) {
33
- config.data(await response.json());
34
-
35
- await local.onStart(() => local.onDisconnect());
36
- } else {
37
- setTimeout(() => local.start(), 5000);
38
- }
39
- } catch (e) {
40
- console.log(e);
41
- setTimeout(() => local.start(), 5000);
42
- }
43
- }
44
-
45
- onDisconnect() {
46
- var local = this;
47
-
48
- setTimeout(() => local.start(), 5000);
49
- }
50
-
51
- async close() {
52
- try {
53
- await fetch(
54
- this.config.url() + 'disconnect',
55
- C.augmentRequest(
56
- {
57
- method: 'POST',
58
- body: JSON.stringify({}),
59
- headers: {'Content-Type': 'application/json'},
60
- signal: AbortSignal.timeout(60 * 1000),
61
- },
62
- this.config
63
- )
64
- );
65
- } catch (e) {
66
- // blank
67
- }
68
- }
69
- }
70
-
71
- export {Connection};
@@ -1,42 +0,0 @@
1
- import C from './constants.mjs';
2
-
3
- class Registration {
4
- constructor(config) {
5
- this.config = config;
6
- }
7
-
8
- async run() {
9
- var local = this;
10
- const config = this.config;
11
- const configSchema = config.configSchema();
12
- const intro = await config.introspect();
13
- const icon = config.icon();
14
-
15
- const response = await fetch(
16
- config.url() + 'register',
17
- C.augmentRegistration(
18
- {
19
- method: 'POST',
20
- body: JSON.stringify({
21
- deployment: process.env.DEPLOYMENT || '',
22
- name: config.name(),
23
- version: config.version(),
24
- id: config.id(),
25
- publicKey: config.publicKey(),
26
- schema: {configSchema, introspect: intro},
27
- icon,
28
- }),
29
- headers: {'Content-Type': 'application/json'},
30
- signal: AbortSignal.timeout(60 * 1000),
31
- },
32
- config
33
- )
34
- );
35
-
36
- if (response.status === 200) return (await response.json()).key;
37
-
38
- throw new Error('authentication failed');
39
- }
40
- }
41
-
42
- export {Registration};
@@ -1,46 +0,0 @@
1
- import WebSocket from 'ws';
2
- import {Connection} from './connection/index.mjs';
3
- import {Transport} from './transport/index.mjs';
4
-
5
- class WebsocketConnector {
6
- constructor({config, onMessage, onConnect}) {
7
- var local = this;
8
- this.config = config;
9
- this.transport = new Transport({config, onMessage, onConnect});
10
- }
11
-
12
- async start() {
13
- var local = this;
14
- const config = this.config;
15
-
16
- local.connection = new Connection({
17
- config,
18
- onStart: () => {
19
- local.transport.start(() => setTimeout(() => local.start(), 1000));
20
- },
21
- });
22
-
23
- await local.connection.start();
24
- }
25
-
26
- send(message) {
27
- if (!message) return;
28
-
29
- this.transport.send(this.transport.newPacket(message));
30
- }
31
-
32
- async close() {
33
- var local = this;
34
-
35
- if (local.transport) await local.transport.close();
36
- }
37
-
38
- async leaving() {
39
- var local = this;
40
-
41
- if (local.transport) await local.transport.leaving();
42
- if (local.connection) await local.connection.close();
43
- }
44
- }
45
-
46
- export {WebsocketConnector};
@@ -1,71 +0,0 @@
1
- import WebSocket from 'ws';
2
-
3
- class DurableWebsocket {
4
- constructor({endpoint, secret, onConnect, onMessage}) {
5
- this.endpoint = endpoint;
6
- this.secret = secret;
7
- this.onConnect = onConnect;
8
- this.onMessage = onMessage;
9
- this.failed = [];
10
- this.fails = 0;
11
- this.start();
12
- }
13
-
14
- async send(what) {
15
- try {
16
- return await this.ws.send(JSON.stringify(what));
17
- } catch (e) {
18
- this.failed.push(what);
19
- }
20
- }
21
-
22
- start() {
23
- var local = this;
24
-
25
- if (local.connecting || local.closed) return;
26
- local.connecting = true;
27
-
28
- const ws = (local.ws = new WebSocket(local.endpoint, [], {
29
- rejectUnauthorized: false,
30
- headers: {Authorization: `Bearer ${local.secret}`},
31
- }));
32
-
33
- ws.on('open', () => {
34
- local.connecting = false;
35
- local.fails = 0;
36
-
37
- var item;
38
-
39
- while ((item = local.failed.shift())) {
40
- local.send(item);
41
- }
42
-
43
- local.onConnect(local);
44
- });
45
-
46
- ws.on('message', (message) => {
47
- setImmediate(() => local.onMessage(JSON.parse(message)));
48
- });
49
-
50
- ws.on('error', (message) => {
51
- if (local.fails > 50) console.log('error:', message.message);
52
-
53
- ++local.fails;
54
- });
55
-
56
- ws.on('close', (message) => {
57
- local.connecting = false;
58
-
59
- if (!local.closed) setTimeout(() => local.start(), 5000);
60
- });
61
- }
62
-
63
- async close() {
64
- if (this.closed) return;
65
- this.closed = true;
66
-
67
- await this.ws?.close();
68
- }
69
- }
70
-
71
- export {DurableWebsocket};