@faybl/client 4.3.1 → 5.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 CHANGED
@@ -19,19 +19,19 @@ const unsubscribe = client.channel.subscribe(ovens[0].channels.temperature, ({ d
19
19
 
20
20
  Resolves with a client once its MQTT connection is set up; the connection itself completes in the
21
21
  background, which [`connection`](#connection) follows. Rejects when the options name neither a
22
- valid tenant nor the endpoints needed to connect, when `onError` is not a function, or when the MQTT credentials
23
- are refused. While their source does not answer, or answers with a 5xx, it waits for them and tries
22
+ valid tenant nor the endpoints needed to connect, when an option has the wrong shape, or when the MQTT
23
+ credentials are refused or come without a username and a password. While their source does not answer, or answers with a 5xx, it waits for them and tries
24
24
  again every `reconnectPeriod`, reporting each failure as `credentials`.
25
25
 
26
- | Option | Meaning |
27
- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
28
- | `tenantUrl` | Host name of the tenant, such as `atenant.faybl.online`, without scheme or path. Every endpoint defaults to a URL built from it. |
29
- | `confUrl`, `dataHistoryUrl`, `authenticatorUrl`, `mqttUrl` | Override one endpoint. Without a `tenantUrl`, only `mqttUrl` and, when the authenticator hands out the MQTT credentials, `authenticatorUrl` are required; a call that needs an endpoint left out rejects. |
30
- | `noMqtt` | Do not connect to MQTT. The bus-facing methods then throw `MQTT is disabled`, and datasets do not load. |
31
- | `noAuth` | Connect to MQTT without credentials. Without it the client never connects anonymously. |
32
- | `onError(error, { source, topic })` | Receives what goes wrong where no caller is waiting, from the first credentials on. See [Errors](#errors). |
33
- | `authConfig` (Node) | `{ issuerUrl, clientId, clientSecret }` authenticates with the OIDC client credentials grant. With only `clientId`, see below. |
34
- | `useWebsocket` (Node) | Connect to MQTT over WebSocket instead of MQTTS. |
26
+ | Option | Meaning |
27
+ | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
28
+ | `tenantUrl` | Host name of the tenant, such as `atenant.faybl.online`, without scheme or path. Every endpoint defaults to a URL built from it. |
29
+ | `confUrl`, `dataHistoryUrl`, `authenticatorUrl`, `mqttUrl` | Override one endpoint: an http(s) URL, or in the browser also a path such as `/conf`; `mqttUrl` a `ws:` or `wss:` URL in the browser. Trailing slashes are dropped. Without a `tenantUrl`, only `mqttUrl` and, when the authenticator hands out the MQTT credentials, `authenticatorUrl` are required; a call that needs an endpoint left out rejects. |
30
+ | `noMqtt` | `true`: do not connect to MQTT. The bus-facing methods then throw `MQTT is disabled`, and datasets do not load. |
31
+ | `noAuth` | `true`: connect to MQTT without credentials. Without it the client never connects anonymously. |
32
+ | `onError(error, { source, topic })` | Receives what goes wrong where no caller is waiting, from the first credentials on. See [Errors](#errors). |
33
+ | `authConfig` (Node) | `{ issuerUrl, clientId, clientSecret }` authenticates with the OIDC client credentials grant. With only `clientId`, see below. |
34
+ | `useWebsocket` (Node) | Connect to MQTT over WebSocket instead of MQTTS. |
35
35
 
36
36
  Authentication:
37
37
 
@@ -57,14 +57,14 @@ The client writes nothing to the console. What fails where no caller is waiting
57
57
  and is dropped without one. `source` says where it came from, and `topic` is set when one is
58
58
  involved:
59
59
 
60
- | `source` | What failed |
61
- | ------------- | --------------------------------------------------------------------------------------------------------- |
62
- | `mqtt` | The MQTT connection: a refused connection, a keepalive timeout, a missing CONNACK. |
63
- | `session` | A request was refused with 401: the login session is gone. Once until one succeeds. |
64
- | `credentials` | Fetching MQTT credentials. At start the client waits; later it connects with what it has and tries again. |
65
- | `message` | A message that is not JSON. An empty message clears a retained one and is not this. |
66
- | `subscriber` | A subscription's callback threw or rejected. The other subscribers still get it. |
67
- | `procedure` | A request whose request id is not a single topic level. It gets no reply. |
60
+ | `source` | What failed |
61
+ | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
62
+ | `mqtt` | The MQTT connection: a refused connection, a keepalive timeout, a missing CONNACK. |
63
+ | `session` | A request was refused with 401: the login session is gone. Once until one succeeds. |
64
+ | `credentials` | Fetching MQTT credentials. At start the client waits; later it connects with what it has and tries again. |
65
+ | `message` | A message that is not JSON. An empty message clears a retained one and is not this. |
66
+ | `subscriber` | A subscriber threw or rejected: on a topic, `connection`, `session` or a dataset. The others still get it. |
67
+ | `procedure` | A request whose request id is not one topic level or whose body is not a JSON object: it gets no reply. Or a reply that is not `{ ok, rep }`, which the call ignores. |
68
68
 
69
69
  An HTTP call that gets anything but a 2xx rejects with `Request failed: <status> <statusText>`,
70
70
  and the error carries `response: { status, statusText, body }`, with the JSON body the service
@@ -76,7 +76,8 @@ has no `+`, `#` or `/`, and does not start with `$`. The error names the argumen
76
76
 
77
77
  ## `conf`
78
78
 
79
- The data model. Every entity has the same four calls, each posting its argument to conf:
79
+ The data model. Every entity has the same four calls, each posting its argument to conf and
80
+ taking `{ signal }` second, an `AbortSignal` that cancels the request:
80
81
  `asset`, `assettype`, `channel`, `channeltype`, `config`, `configtype`, `procedure`,
81
82
  `proceduretype`, `rule`, `thing`, `thingtype` and `trigger`.
82
83
 
@@ -99,9 +100,9 @@ Changes are published on the bus as they happen:
99
100
  gets `{ entity, operation, rid, record }`, where `record` is the whole record as read after the
100
101
  change, or `{}` for a delete.
101
102
  - `conf.subscribeWithAck(...)` takes the same and returns `{ ready, unsubscribe }`; `ready` resolves
102
- once the broker has acknowledged the subscription, and rejects only if the broker refused it. A
103
+ once the broker has acknowledged the subscription, and rejects if the broker refused it. A
103
104
  connection that closes first is waited out: the subscription is asked for again on the
104
- reconnect.
105
+ reconnect, unless it has been undone or the client closed by then, which rejects `ready`.
105
106
  - `conf.unsubscribe({ entity, operation, rid, callback })`. Without a callback it removes every
106
107
  callback on that subscription.
107
108
 
@@ -109,14 +110,15 @@ Changes are published on the bus as they happen:
109
110
 
110
111
  A channel is a stored series of measurements, addressed by its rid.
111
112
 
112
- - `channel.read({ rid, from, to, limit, ascending, reverse, samplingInterval, downsamplingMethod, timeZone, projection })`
113
+ - `channel.read({ rid, from, to, limit, ascending, reverse, samplingInterval, downsamplingMethod, timeZone, projection }, { signal })`
113
114
  resolves with `{ count, timeZone, data }`, where `data` holds `{ ts, pl }` points. Without
114
115
  `ascending`, data-history reads from the newest end. `reverse` turns the result around after
115
116
  reading. `fetchHistory` in `@faybl/utils` picks both so that a window comes back in ascending
116
117
  time.
117
118
  - `channel.publish(rid, pl, other)` publishes `{ ts, pl, ...other }`, with `ts` the current time
118
119
  unless `other` sets it.
119
- - `channel.subscribe(rid, callback)` returns the function that undoes it. The callback gets
120
+ - `channel.subscribe(rid, callback)` returns the function that undoes it, and only it: a callback
121
+ subscribed twice stays subscribed once. The callback gets
120
122
  `{ rid, data }`, with `data` as published.
121
123
  - `channel.unsubscribe(rid, callback)`. Without a callback it removes every callback on the rid.
122
124
 
@@ -140,10 +142,11 @@ lamp that can be switched on and off. Requests and replies use QoS 1 without ret
140
142
  the function that removes this provider.
141
143
  - `procedure.unprovide(rid, callback)` removes that provider. Without a callback it removes every
142
144
  provider of the rid.
143
- - `procedure.call(rid, args = {}, timeout = 5)` resolves with the provider's reply. It waits for
144
- its reply subscription to be acknowledged before sending the request. It rejects with the
145
- provider's message, with `Timeout while waiting for reply.` after `timeout` seconds, or when MQTT
146
- is disconnected.
145
+ - `procedure.call(rid, args = {}, { timeout = 5, signal })` resolves with the provider's reply. The
146
+ third argument may also be the timeout alone, in seconds. It waits for its reply subscription to
147
+ be acknowledged before sending the request. It rejects with the provider's message, with
148
+ `Timeout while waiting for reply.` after `timeout` seconds, with the signal's reason once it
149
+ aborts, or when MQTT is disconnected. A call whose signal has already aborted sends nothing.
147
150
 
148
151
  MQTT may deliver a request twice. A provider answers a repeated request id with the reply it already
149
152
  gave, but only from memory, so a procedure with lasting side effects should also be idempotent
@@ -154,6 +157,12 @@ across provider restarts. A call made while no provider is connected is not kept
154
157
  - `connection.subscribe(callback)` calls back with `{ connected }` at once, and again whenever the
155
158
  MQTT connection comes up or goes down. Returns the function that undoes it.
156
159
 
160
+ A connection that drops is reconnected by the client, 5 seconds later and with fresh credentials,
161
+ and every subscription is asked for again. A subscription made meanwhile is sent once the
162
+ connection is back, and so are QoS 1 messages published meanwhile or still unacknowledged when it
163
+ dropped. While the login is refused, the client stays disconnected and asks for credentials again
164
+ every 5 seconds. Closing the client during a reconnect cancels it.
165
+
157
166
  ## `session`
158
167
 
159
168
  - `session.subscribe(callback)` calls back with `{ expired }` at once, and again whenever it
@@ -163,7 +172,7 @@ across provider restarts. A call made while no provider is connected is not kept
163
172
 
164
173
  ## `auth`
165
174
 
166
- - `auth.getUserInfo()` resolves with `{ id, firstName, lastName, email }` of whoever the request
175
+ - `auth.getUserInfo({ signal })` resolves with `{ id, firstName, lastName, email }` of whoever the request
167
176
  is authenticated as. For a service, `id` is its client id.
168
177
 
169
178
  ## `mqttClient`
@@ -177,8 +186,7 @@ subscription may be a filter with wildcards.
177
186
  - `mqttClient.subscribe(topic, callback, { qos })` returns the function that undoes it. The
178
187
  callback gets `{ topic, data }`, with `data` parsed from JSON.
179
188
  - `mqttClient.subscribeWithAck(topic, callback, { qos })` returns `{ ready, unsubscribe }`; `ready`
180
- resolves once the broker has granted the QoS asked for, 0 by default, and rejects only if it
181
- refused, as above. Several subscriptions to one topic share one acknowledgement, and the topic
189
+ resolves once the broker has granted the QoS asked for, 0 by default, and rejects as above. Several subscriptions to one topic share one acknowledgement, and the topic
182
190
  keeps the strictest QoS asked for.
183
191
  - `mqttClient.unsubscribe(topic, callback)`. Without a callback it removes every callback on the
184
192
  topic.
@@ -221,7 +229,9 @@ operation that cannot be evaluated outside MongoDB, such as `$text` or `$where`,
221
229
  from loading.
222
230
 
223
231
  A dataset subscribes before it reads, and applies the changes that arrive meanwhile on top of what
224
- it read, so a change made while it loads is not lost. It does not load without MQTT, or when the
232
+ it read, so a change made while it loads is not lost. An `entity` conf does not have stops it from
233
+ loading, as does a read answered with anything but a list of records. Stopping it while it reads
234
+ cancels the request. It does not load without MQTT, or when the
225
235
  broker refuses the subscription. Changes published while the connection is down are not seen.
226
236
 
227
237
  `createDataset(client, spec)` returns:
@@ -229,11 +239,12 @@ broker refuses the subscription. Changes published while the connection is down
229
239
  - `init()`, which resolves once loaded, or rejects with the error that stopped it. Called again
230
240
  after a rejection, it loads again.
231
241
  - `getRecords()`.
232
- - `subscribe(callback)` and `unsubscribe(callback)`, without a callback removing them all. A
233
- callback gets `{ type, rid, record, previous }` after the records have changed, with `type`
242
+ - `subscribe(callback)`, which returns the function that undoes it, and `unsubscribe(callback)`,
243
+ without a callback removing them all. A callback gets `{ type, rid, record, previous }` after the records have changed, with `type`
234
244
  `add`, `update` or `remove`. `record` is missing when a record was deleted, and `previous` when
235
245
  it was added.
236
- - `stop()`, which ends the subscription and drops the callbacks.
246
+ - `stop()`, which ends the subscription and drops the callbacks. A stopped dataset does not start
247
+ again: `init` rejects, and a new dataset is needed.
237
248
  - `machine`, the XState actor underneath.
238
249
 
239
250
  `createDatasetMachine(client, spec, onChange)` is the same as an XState machine, for spawning in a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@faybl/client",
3
- "version": "4.3.1",
3
+ "version": "5.0.0",
4
4
  "description": "Faybl JavaScript Client",
5
5
  "license": "MIT",
6
6
  "author": "Arcturitech",
@@ -27,18 +27,19 @@
27
27
  "format": "prettier . --write",
28
28
  "format:check": "prettier . --check",
29
29
  "itest": "vitest run --project itest --coverage",
30
+ "itest:broker": "vitest run --project itest itest/broker",
30
31
  "lint": "eslint .",
31
32
  "perf": "vitest run --project perf",
32
33
  "prettypackagejson": "prettier-package-json --write ./package.json",
33
34
  "release": "node scripts/release.mjs",
34
35
  "test": "vitest run --project test --coverage",
35
- "verify": "npm run format:check && npm run lint && npm test",
36
+ "verify": "npm run format:check && npm run lint && npm test && npm run itest:broker",
36
37
  "preversion": "npm run verify",
37
38
  "postversion": "node scripts/version-hint.mjs"
38
39
  },
39
40
  "sideEffects": false,
40
41
  "dependencies": {
41
- "@faybl/utils": "^2.3.0",
42
+ "@faybl/utils": "^2.5.1",
42
43
  "@paralleldrive/cuid2": "^3.3.0",
43
44
  "mqtt": "^5.16.1",
44
45
  "mqtt-match": "^3.0.0",
@@ -49,21 +50,26 @@
49
50
  },
50
51
  "devDependencies": {
51
52
  "@eslint/js": "^10.0.1",
52
- "@faybl/eslint-config": "^3.2.0",
53
- "@faybl/prettier-config": "^3.2.0",
54
- "@faybl/tsconfig": "^3.2.0",
55
- "@vitest/coverage-v8": "^5.0.5",
56
- "eslint": "^10.13.0",
57
- "prettier": "^3.9.10",
53
+ "@faybl/eslint-config": "^4.0.0",
54
+ "@faybl/prettier-config": "^4.0.0",
55
+ "@faybl/tsconfig": "^4.0.0",
56
+ "@vitest/coverage-v8": "^5.1.0",
57
+ "eslint": "^10.14.0",
58
+ "prettier": "^3.10.1",
58
59
  "prettier-package-json": "^2.8.0",
59
60
  "typescript": "^6.0.3",
60
- "vite": "^8.3.4",
61
- "vitest": "^5.0.5"
61
+ "vite": "^8.3.8",
62
+ "vitest": "^5.1.0",
63
+ "ws": "^8.23.0"
62
64
  },
63
65
  "engines": {
64
66
  "node": ">=22"
65
67
  },
66
68
  "publishConfig": {
67
69
  "access": "public"
70
+ },
71
+ "overrides": {
72
+ "deepmerge-ts": "^8.0.2",
73
+ "minimatch@^10": "^11.0.8"
68
74
  }
69
75
  }
package/src/auth.js CHANGED
@@ -1,12 +1,13 @@
1
1
  import { fetchCheckedJson, missingEndpoint } from './fetch.js';
2
2
 
3
3
  export const getAuthApi = (authenticatorUrl, http) => {
4
- const getUserInfo = async () => {
4
+ // `signal` cancels the request.
5
+ const getUserInfo = async ({ signal } = {}) => {
5
6
  if (!authenticatorUrl) return missingEndpoint('authenticatorUrl');
6
7
  return fetchCheckedJson(
7
8
  `${authenticatorUrl}/getUserInfo`,
8
9
  // The request is JSON, so it carries a body even without arguments.
9
- { method: 'POST', body: JSON.stringify({}) },
10
+ { method: 'POST', body: JSON.stringify({}), signal },
10
11
  http,
11
12
  );
12
13
  };
package/src/browser.js CHANGED
@@ -1,35 +1,14 @@
1
- import { clientOptionsError, tenantServiceUrl } from './clientOptions.js';
2
- import { createClient as createBrowserClient } from './client.js';
3
- import { createMqttClient } from './mqtt.js';
4
- import { createReporter } from './report.js';
5
- import { createSession } from './session.js';
1
+ import mqtt from 'mqtt';
6
2
 
7
- export { createDataset, createDatasetMachine, datasetLoaded } from './dataset.js';
8
-
9
- export const createClient = async (options = {}) => {
10
- const optionsError = clientOptionsError(options);
11
- if (optionsError) return Promise.reject(optionsError);
12
- const { tenantUrl, confUrl, dataHistoryUrl, mqttUrl, authenticatorUrl, noMqtt, noAuth, onError } =
13
- options;
14
- const report = createReporter(onError);
15
- const session = createSession(report);
3
+ import { createClientFactory } from './clientFactory.js';
16
4
 
17
- const mqttClient = noMqtt
18
- ? undefined
19
- : await createMqttClient({
20
- mqttUrl: mqttUrl || `wss://ws.${tenantUrl}`,
21
- authenticatorUrl: authenticatorUrl || tenantServiceUrl(tenantUrl, '/authenticator'),
22
- noAuth,
23
- report,
24
- session,
25
- });
5
+ export { createDataset, createDatasetMachine, datasetLoaded } from './dataset.js';
26
6
 
27
- return createBrowserClient({
28
- authenticatorUrl: authenticatorUrl || tenantServiceUrl(tenantUrl, '/authenticator'),
29
- confUrl: confUrl || tenantServiceUrl(tenantUrl, '/conf'),
30
- dataHistoryUrl: dataHistoryUrl || tenantServiceUrl(tenantUrl, '/data-history'),
31
- mqttClient,
32
- session,
33
- report,
34
- });
35
- };
7
+ // A browser reaches the broker over WebSocket only, and has no client credentials grant: HTTP
8
+ // requests carry the login session's cookies, and MQTT credentials come from the authenticator.
9
+ export const createClient = createClientFactory({
10
+ connectMqtt: mqtt.connect,
11
+ // Called without a receiver, as a browser requires of fetch, and looked up on each call.
12
+ fetch: (...args) => globalThis.fetch(...args),
13
+ defaultMqttUrl: ({ tenantUrl }) => `wss://ws.${tenantUrl}`,
14
+ });
package/src/channel.js CHANGED
@@ -1,4 +1,4 @@
1
- import { mqttDisabledWarning } from './mqttUtils.js';
1
+ import { mqttDisabled } from './mqttUtils.js';
2
2
  import { assertTopicSegment } from './topicSegment.js';
3
3
  import { fetchCheckedJson, missingEndpoint } from './fetch.js';
4
4
 
@@ -16,20 +16,16 @@ export const getChannelApi = (dataHistoryUrl, mqttClient, http) => {
16
16
  };
17
17
  const topicFor = (rid) => `${baseTopic}/${assertTopicSegment('rid', rid)}`;
18
18
  const unsubscribe = (rid, callback) => mqttClient.unsubscribe(topicFor(rid), callback);
19
- const subscribe = (rid, callback) => {
19
+ const subscribe = (rid, callback) =>
20
20
  mqttClient.subscribe(topicFor(rid), callback, { preCallback });
21
- return () => unsubscribe(rid, callback);
22
- };
23
21
  const publish = (rid, pl, other) => mqttClient.publish(topicFor(rid), createPubMsg(pl, other));
24
22
 
25
- const read = (args) => {
23
+ // `signal` cancels the request.
24
+ const read = (args, { signal } = {}) => {
26
25
  if (!dataHistoryUrl) return missingEndpoint('dataHistoryUrl');
27
26
  return fetchCheckedJson(
28
27
  `${dataHistoryUrl}/read`,
29
- {
30
- body: JSON.stringify(args),
31
- method: 'POST',
32
- },
28
+ { body: JSON.stringify(args), method: 'POST', signal },
33
29
  http,
34
30
  );
35
31
  };
@@ -43,9 +39,9 @@ export const getChannelApi = (dataHistoryUrl, mqttClient, http) => {
43
39
  publish,
44
40
  }
45
41
  : {
46
- subscribe: mqttDisabledWarning,
47
- unsubscribe: mqttDisabledWarning,
48
- publish: mqttDisabledWarning,
42
+ subscribe: mqttDisabled,
43
+ unsubscribe: mqttDisabled,
44
+ publish: mqttDisabled,
49
45
  }),
50
46
  };
51
47
  };
package/src/client.js CHANGED
@@ -4,36 +4,32 @@ import { getChannelApi } from './channel.js';
4
4
  import { getConnectionApi } from './connection.js';
5
5
  import { getProcedureApi } from './procedure.js';
6
6
  import { getPresenceApi } from './presence.js';
7
+ import { REPORTER } from './report.js';
7
8
 
9
+ /**
10
+ * The client's public face, composed from its parts. `http` is what every HTTP call is sent with;
11
+ * `mqttClient` is undefined when MQTT is off.
12
+ */
8
13
  export const createClient = ({
9
14
  authenticatorUrl,
10
15
  confUrl,
11
16
  dataHistoryUrl,
12
17
  mqttClient,
13
- oidcHandler,
14
- session,
18
+ http,
15
19
  report,
16
20
  }) => {
17
- // What every HTTP call is sent with: the token for a service, and where a refused login goes.
18
- const http = { oidcHandler, session };
19
- const auth = getAuthApi(authenticatorUrl, http);
20
- const channel = getChannelApi(dataHistoryUrl, mqttClient, http);
21
- const conf = getConfApi(confUrl, mqttClient, http);
22
- const procedure = getProcedureApi(mqttClient, report);
23
- const presence = getPresenceApi(mqttClient);
24
- const connection = getConnectionApi(mqttClient);
25
-
26
21
  const close = async () => mqttClient?.close();
27
22
 
28
23
  return {
29
- auth,
30
- channel,
31
- conf,
32
- procedure,
33
- presence,
34
- connection,
35
- session: { subscribe: session.subscribe },
24
+ auth: getAuthApi(authenticatorUrl, http),
25
+ channel: getChannelApi(dataHistoryUrl, mqttClient, http),
26
+ conf: getConfApi(confUrl, mqttClient, http),
27
+ procedure: getProcedureApi(mqttClient, report),
28
+ presence: getPresenceApi(mqttClient),
29
+ connection: getConnectionApi(mqttClient, report),
30
+ session: { subscribe: http.session.subscribe },
36
31
  mqttClient,
37
32
  close,
33
+ [REPORTER]: report,
38
34
  };
39
35
  };
@@ -0,0 +1,45 @@
1
+ import { parseClientOptions } from './clientOptions.js';
2
+ import { createClient } from './client.js';
3
+ import { createMqttClient } from './mqtt.js';
4
+ import { createReporter } from './report.js';
5
+ import { createSession } from './session.js';
6
+
7
+ /**
8
+ * Builds an entry point's `createClient` from the effects it runs on: `connectMqtt` (MQTT.js's
9
+ * `connect`), `fetch`, and, outside a browser, `createOidcHandler` for the client credentials grant.
10
+ * `defaultMqttUrl({ tenantUrl, useWebsocket })` is the broker a tenant implies.
11
+ */
12
+ export const createClientFactory = ({ connectMqtt, fetch, createOidcHandler, defaultMqttUrl }) => {
13
+ // The browser entry is the one without the client credentials grant.
14
+ const parseOptions = parseClientOptions({
15
+ browser: createOidcHandler === undefined,
16
+ defaultMqttUrl,
17
+ });
18
+
19
+ const compose = async ({ endpoints, noMqtt, noAuth, authConfig, onError }) => {
20
+ const { confUrl, dataHistoryUrl, authenticatorUrl, mqttUrl } = endpoints;
21
+ const report = createReporter(onError);
22
+ const session = createSession(report);
23
+ const oidcHandler = authConfig?.issuerUrl ? createOidcHandler(authConfig) : undefined;
24
+ // What every HTTP call is sent with: the transport, the token for a service, and where a
25
+ // refused login goes.
26
+ const http = { fetch, oidcHandler, session };
27
+ const mqttClient = noMqtt
28
+ ? undefined
29
+ : await createMqttClient({
30
+ connect: connectMqtt,
31
+ mqttUrl,
32
+ authenticatorUrl,
33
+ authConfig,
34
+ noAuth,
35
+ http,
36
+ report,
37
+ });
38
+ return createClient({ confUrl, dataHistoryUrl, authenticatorUrl, mqttClient, http, report });
39
+ };
40
+
41
+ return async (options = {}) => {
42
+ const { ok, value, error } = parseOptions(options);
43
+ return ok ? compose(value) : Promise.reject(error);
44
+ };
45
+ };
@@ -1,39 +1,178 @@
1
+ import { Err, Ok } from '@faybl/utils';
2
+
3
+ import { describeValue, isNonEmptyString, isPlainObject } from './guards.js';
4
+
1
5
  // A host name with an optional port: every service URL is built by prefixing a
2
6
  // scheme or a subdomain, so a scheme or a path in it would produce a broken URL.
3
7
  const TENANT_HOST = /^[^\s/:]+(:\d+)?$/;
4
8
 
5
- // A service's URL under the tenant, or undefined without one.
6
- export const tenantServiceUrl = (tenantUrl, path) =>
7
- tenantUrl === undefined ? undefined : `https://${tenantUrl}${path}`;
9
+ const HTTP_SCHEMES = ['http:', 'https:'];
10
+ // A browser reaches a broker over WebSocket only.
11
+ const BROWSER_MQTT_SCHEMES = ['ws:', 'wss:'];
12
+ // Every scheme MQTT.js connects over in Node.
13
+ const MQTT_SCHEMES = [
14
+ 'mqtt:',
15
+ 'mqtts:',
16
+ 'tcp:',
17
+ 'ssl:',
18
+ 'tls:',
19
+ 'ws:',
20
+ 'wss:',
21
+ 'wx:',
22
+ 'wxs:',
23
+ 'ali:',
24
+ 'alis:',
25
+ ];
26
+ const HTTP_ENDPOINTS = ['confUrl', 'dataHistoryUrl', 'authenticatorUrl'];
27
+ const FLAGS = ['noMqtt', 'noAuth', 'useWebsocket'];
28
+
29
+ const invalid = (name, value, rule) =>
30
+ Error(`Invalid ${name} ${describeValue(value)}: it must be ${rule}`);
31
+
32
+ const hasScheme = (schemes) => (value) =>
33
+ URL.canParse(value) && schemes.includes(new URL(value).protocol);
34
+ // A path on the page's own origin, as a browser app behind the tenant's proxy may use. Node has
35
+ // no origin to resolve it against.
36
+ const isOriginPath = (value) => value.startsWith('/') && !value.startsWith('//');
37
+
38
+ const isHttpUrl = (value) => isNonEmptyString(value) && hasScheme(HTTP_SCHEMES)(value);
39
+ const isBrowserHttpEndpoint = (value) =>
40
+ isNonEmptyString(value) && (isOriginPath(value) || hasScheme(HTTP_SCHEMES)(value));
41
+
42
+ const withoutTrailingSlashes = (url) => url.replace(/\/+$/, '');
43
+
44
+ // The first rule an option breaks, as the Error createClient rejects with.
45
+ const firstError = (checks) => checks.map((check) => check()).find(Boolean);
46
+
47
+ // An option that may be left out, but must follow `rule` when given.
48
+ const optional = (isValid, rule) => (name, value) =>
49
+ value === undefined || isValid(value) ? undefined : invalid(name, value, rule);
50
+
51
+ const tenantUrlError = optional(
52
+ (value) => typeof value === 'string' && TENANT_HOST.test(value),
53
+ "a host name such as 'tenant.faybl.online', without scheme or path",
54
+ );
55
+ const mqttEndpointRule = (schemes) =>
56
+ optional(
57
+ (value) => isNonEmptyString(value) && hasScheme(schemes)(value),
58
+ `a URL with one of the schemes ${schemes.join(' ')}`,
59
+ );
60
+
61
+ // What an endpoint may be where the client runs: a browser resolves paths against the page.
62
+ const endpointRules = (browser) => ({
63
+ http: browser
64
+ ? optional(isBrowserHttpEndpoint, 'an http(s) URL or a path such as /conf')
65
+ : optional(isHttpUrl, 'an http(s) URL'),
66
+ mqtt: mqttEndpointRule(browser ? BROWSER_MQTT_SCHEMES : MQTT_SCHEMES),
67
+ });
68
+ const flagError = optional((value) => typeof value === 'boolean', 'a boolean');
69
+ const nonEmptyStringError = optional(isNonEmptyString, 'a non-empty string');
70
+ const issuerUrlError = optional(isHttpUrl, 'an http(s) URL');
71
+
72
+ const endpointErrors = (rules, options) => [
73
+ ...HTTP_ENDPOINTS.map((name) => () => rules.http(name, options[name])),
74
+ () => rules.mqtt('mqttUrl', options.mqttUrl),
75
+ ];
76
+
77
+ const flagErrors = (options) => FLAGS.map((name) => () => flagError(name, options[name]));
78
+
79
+ // A service's client credentials. With an issuerUrl the client authenticates itself, so it needs
80
+ // its secret; without one, clientId only names the identity the authenticator issues MQTT
81
+ // credentials for.
82
+ const authConfigError = (authConfig) => {
83
+ if (authConfig === undefined) return undefined;
84
+ if (!isPlainObject(authConfig)) return invalid('authConfig', authConfig, 'an object');
85
+ const { issuerUrl, clientId, clientSecret } = authConfig;
86
+ return firstError([
87
+ () => issuerUrlError('authConfig.issuerUrl', issuerUrl),
88
+ () => nonEmptyStringError('authConfig.clientId', clientId),
89
+ () =>
90
+ issuerUrl !== undefined && !isNonEmptyString(clientId)
91
+ ? Error('Invalid authConfig: an issuerUrl needs a clientId')
92
+ : undefined,
93
+ () =>
94
+ issuerUrl !== undefined && !isNonEmptyString(clientSecret)
95
+ ? Error('Invalid authConfig: an issuerUrl needs a clientSecret')
96
+ : undefined,
97
+ ]);
98
+ };
8
99
 
9
- const tenantUrlError = (tenantUrl) =>
10
- typeof tenantUrl === 'string' && TENANT_HOST.test(tenantUrl)
100
+ const onErrorError = ({ onError }) =>
101
+ onError === undefined || typeof onError === 'function'
11
102
  ? undefined
12
- : Error(
13
- `Invalid tenantUrl ${JSON.stringify(tenantUrl)}: it must be a host name such as 'tenant.faybl.online', without scheme or path`,
14
- );
103
+ : Error('Invalid onError: it must be a function');
104
+
105
+ const tenantEndpoints = (tenantUrl) =>
106
+ tenantUrl === undefined
107
+ ? {}
108
+ : {
109
+ confUrl: `https://${tenantUrl}/conf`,
110
+ dataHistoryUrl: `https://${tenantUrl}/data-history`,
111
+ authenticatorUrl: `https://${tenantUrl}/authenticator`,
112
+ };
113
+
114
+ const definedEntries = (record) =>
115
+ Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined));
116
+
117
+ // Every endpoint the tenant implies, overridden by the ones given, without trailing slashes.
118
+ const resolveEndpoints = (defaultMqttUrl, options) => {
119
+ const { tenantUrl, useWebsocket } = options;
120
+ const given = definedEntries({
121
+ confUrl: options.confUrl,
122
+ dataHistoryUrl: options.dataHistoryUrl,
123
+ authenticatorUrl: options.authenticatorUrl,
124
+ mqttUrl: options.mqttUrl,
125
+ });
126
+ const resolved = {
127
+ ...tenantEndpoints(tenantUrl),
128
+ ...(tenantUrl === undefined ? {} : { mqttUrl: defaultMqttUrl({ tenantUrl, useWebsocket }) }),
129
+ ...given,
130
+ };
131
+ return Object.fromEntries(
132
+ Object.entries(resolved).map(([name, url]) => [name, withoutTrailingSlashes(url)]),
133
+ );
134
+ };
15
135
 
16
136
  // Only what connecting needs is required up front: the broker, and the authenticator when it hands
17
137
  // out the MQTT credentials. Any other endpoint left out fails only the calls that use it, so a
18
138
  // service names the endpoints it talks to and no others.
19
- const requiredEndpoints = ({ noMqtt, noAuth, authConfig }) =>
20
- noMqtt ? [] : ['mqttUrl', ...(noAuth || authConfig?.issuerUrl ? [] : ['authenticatorUrl'])];
21
-
22
- const endpointsError = (options) => {
23
- if (options.tenantUrl !== undefined) return tenantUrlError(options.tenantUrl);
24
- const missing = requiredEndpoints(options).filter((name) => !options[name]);
139
+ const missingEndpointsError = (endpoints, { noMqtt, noAuth, authConfig }) => {
140
+ const required = noMqtt
141
+ ? []
142
+ : ['mqttUrl', ...(noAuth || authConfig?.issuerUrl ? [] : ['authenticatorUrl'])];
143
+ const missing = required.filter((name) => endpoints[name] === undefined);
25
144
  return missing.length === 0
26
145
  ? undefined
27
146
  : Error(`createClient needs a tenantUrl, or else ${missing.join(', ')}`);
28
147
  };
29
148
 
30
- const onErrorError = ({ onError }) =>
31
- onError === undefined || typeof onError === 'function'
32
- ? undefined
33
- : Error('Invalid onError: it must be a function');
34
-
35
149
  /**
36
- * Returns the Error createClient rejects with, or undefined when the options name either a tenant
37
- * or the endpoints the client needs to connect.
150
+ * Parses `createClient`'s options once, at the edge, into what the client is composed from: every
151
+ * endpoint resolved and normalized, and only the options this entry point supports. `browser` says
152
+ * the client runs in a page: endpoints may then be paths on its origin, the broker is reached over
153
+ * WebSocket, and `authConfig` is ignored, as there is no client credentials grant.
154
+ * `defaultMqttUrl({ tenantUrl, useWebsocket })` is the entry point's broker URL for a tenant.
155
+ *
156
+ * Resolves to `Ok(config)`, or `Err(error)` with the Error createClient rejects with.
38
157
  */
39
- export const clientOptionsError = (options) => onErrorError(options) ?? endpointsError(options);
158
+ export const parseClientOptions =
159
+ ({ browser, defaultMqttUrl }) =>
160
+ (options) => {
161
+ const rules = endpointRules(browser);
162
+ if (!isPlainObject(options)) return Err(Error('createClient options must be an object'));
163
+ const { noMqtt = false, noAuth = false, onError } = options;
164
+ const authConfig = browser ? undefined : options.authConfig;
165
+ const shapeError = firstError([
166
+ () => onErrorError(options),
167
+ () => tenantUrlError('tenantUrl', options.tenantUrl),
168
+ ...endpointErrors(rules, options),
169
+ ...flagErrors(options),
170
+ () => authConfigError(authConfig),
171
+ ]);
172
+ if (shapeError) return Err(shapeError);
173
+ const endpoints = resolveEndpoints(defaultMqttUrl, options);
174
+ const missingError = missingEndpointsError(endpoints, { noMqtt, noAuth, authConfig });
175
+ return missingError
176
+ ? Err(missingError)
177
+ : Ok({ endpoints, noMqtt, noAuth, authConfig, onError });
178
+ };