@faybl/client 0.0.0-stage → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-2026 Arcturitech
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,247 @@
1
- # Temporary Holding Version
1
+ # Faybl Client JS
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The JavaScript client for a Faybl tenant: the data model in conf, channel history in data-history,
4
+ and the bus — channels, presence and procedures — over MQTT. It runs in Node and in the browser.
5
+
6
+ The package is ESM only and needs Node 22 or later.
7
+
8
+ ```javascript
9
+ import { createClient } from '@faybl/client/browser'; // in Node: from '@faybl/client'
10
+
11
+ const client = await createClient({ tenantUrl: 'atenant.faybl.online', onError: reportError });
12
+ const ovens = await client.conf.asset.read({ filter: { type: 'oven' } });
13
+ const unsubscribe = client.channel.subscribe(ovens[0].channels.temperature, ({ data }) =>
14
+ draw(data.ts, data.pl),
15
+ );
16
+ ```
17
+
18
+ ## `createClient(options)`
19
+
20
+ Resolves with a client once its MQTT connection is set up; the connection itself completes in the
21
+ background, which [`connection`](#connection) follows. Rejects when the options name neither a
22
+ valid tenant nor every endpoint, or when `onError` is not a function.
23
+
24
+ | Option | Meaning |
25
+ | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
26
+ | `tenantUrl` | Host name of the tenant, such as `atenant.faybl.online`, without scheme or path. Every endpoint defaults to a URL built from it. |
27
+ | `confUrl`, `dataHistoryUrl`, `authenticatorUrl`, `mqttUrl` | Override one endpoint. Without a `tenantUrl`, all of them are required (`mqttUrl` only when MQTT is on). |
28
+ | `noMqtt` | Do not connect to MQTT. The bus-facing methods then throw `MQTT is disabled`, and datasets do not load. |
29
+ | `noAuth` | Connect to MQTT without credentials. |
30
+ | `onError(error, { source, topic })` | Receives what goes wrong after `createClient` has resolved. See [Errors](#errors). |
31
+ | `authConfig` (Node) | `{ issuerUrl, clientId, clientSecret }` authenticates with the OIDC client credentials grant. With only `clientId`, see below. |
32
+ | `useWebsocket` (Node) | Connect to MQTT over WebSocket instead of MQTTS. |
33
+
34
+ Authentication:
35
+
36
+ - With an `issuerUrl`, every HTTP request carries the client's access token, and the MQTT
37
+ connection uses the client id and the token as username and password.
38
+ - Otherwise HTTP requests go with the browser's cookies, and MQTT credentials come from the
39
+ authenticator, as the session's identity, or as `authConfig.clientId` when it is given. Without
40
+ an identity the MQTT connection is anonymous.
41
+ - Every reconnect fetches fresh credentials, so an expired token does not keep the client out.
42
+
43
+ ## Errors
44
+
45
+ The client writes nothing to the console. What fails where no caller is waiting goes to `onError`,
46
+ and is dropped without one. `source` says where it came from, and `topic` is set when one is
47
+ involved:
48
+
49
+ | `source` | What failed |
50
+ | ------------- | ----------------------------------------------------------------------------------- |
51
+ | `mqtt` | The MQTT connection: a refused connection, a keepalive timeout, a missing CONNACK. |
52
+ | `credentials` | Fetching MQTT credentials. The client connects with what it has and tries again. |
53
+ | `message` | A message that is not JSON. An empty message clears a retained one and is not this. |
54
+ | `subscriber` | A subscription's callback threw or rejected. The other subscribers still get it. |
55
+ | `procedure` | A request whose request id is not a single topic level. It gets no reply. |
56
+
57
+ An HTTP call that gets anything but a 2xx rejects with `Request failed: <status> <statusText>`,
58
+ and the error carries `response: { status, statusText, body }`, with the JSON body the service
59
+ sent, or `{}`.
60
+
61
+ The bus-facing methods throw at once, before anything is sent or subscribed, when MQTT is off or
62
+ when an identifier that becomes part of a topic is not one topic level: a string that is not empty,
63
+ has no `+`, `#` or `/`, and does not start with `$`. The error names the argument and the value.
64
+
65
+ ## `conf`
66
+
67
+ The data model. Every entity has the same four calls, each posting its argument to conf:
68
+ `asset`, `assettype`, `channel`, `channeltype`, `config`, `configtype`, `procedure`,
69
+ `proceduretype`, `rule`, `thing`, `thingtype` and `trigger`.
70
+
71
+ - `conf.<entity>.create(record)` resolves with the new record's rid.
72
+ - `conf.<entity>.read({ rids, filter, projection, sort, limit, expandType })` resolves with the
73
+ records. `filter` and `projection` are MongoDB's; `sort` is a list such as `['name', 'ts.desc']`.
74
+ A record's `type` is the type's id, or the whole type record with `expandType`.
75
+ - `conf.<entity>.update({ rids, filter, ... })` resolves with how many records changed. It takes
76
+ one of three forms:
77
+ - `record`: replaces the whole record, keeping only properties whose names start with `_`.
78
+ Everything not sent is gone.
79
+ - `shallowMerge`: sets the given top-level properties and leaves the rest.
80
+ - `patch`: a list of operations such as `{ op: 'remove', path: '/channels/temp' }`.
81
+ - `conf.<entity>.delete({ rids, filter })` resolves with how many records were deleted.
82
+
83
+ Changes are published on the bus as they happen:
84
+
85
+ - `conf.subscribe({ entity, operation, rid, callback })` returns the function that undoes it. A
86
+ part left out matches every value; `operation` is `create`, `update` or `delete`. The callback
87
+ gets `{ entity, operation, rid, record }`, where `record` is the whole record as read after the
88
+ change, or `{}` for a delete.
89
+ - `conf.subscribeWithAck(...)` takes the same and returns `{ ready, unsubscribe }`; `ready` resolves
90
+ once the broker has acknowledged the subscription, and rejects if it refused.
91
+ - `conf.unsubscribe({ entity, operation, rid, callback })`. Without a callback it removes every
92
+ callback on that subscription.
93
+
94
+ ## `channel`
95
+
96
+ A channel is a stored series of measurements, addressed by its rid.
97
+
98
+ - `channel.read({ rid, from, to, limit, ascending, reverse, samplingInterval, downsamplingMethod, timeZone, projection })`
99
+ resolves with `{ count, timeZone, data }`, where `data` holds `{ ts, pl }` points. Without
100
+ `ascending`, data-history reads from the newest end. `reverse` turns the result around after
101
+ reading. `fetchHistory` in `@faybl/utils` picks both so that a window comes back in ascending
102
+ time.
103
+ - `channel.publish(rid, pl, other)` publishes `{ ts, pl, ...other }`, with `ts` the current time
104
+ unless `other` sets it.
105
+ - `channel.subscribe(rid, callback)` returns the function that undoes it. The callback gets
106
+ `{ rid, data }`, with `data` as published.
107
+ - `channel.unsubscribe(rid, callback)`. Without a callback it removes every callback on the rid.
108
+
109
+ ## `presence`
110
+
111
+ Whether an identity — a person or a machine — is connected to the broker. The presence service
112
+ keeps the latest state retained, so a subscription gets the current state at once.
113
+
114
+ - `presence.subscribe(identityIds, callback)` takes one identity id or a non-empty list, and
115
+ returns the function that undoes all of it. The callback gets `{ identityId, data }`, with
116
+ `data` as `{ ts, connected }`. Every id is checked before anything is subscribed.
117
+ - `presence.unsubscribe(identityIds, callback)`.
118
+
119
+ ## `procedure`
120
+
121
+ A call to something on the bus, typically a gateway that has no endpoint of its own, such as a
122
+ lamp that can be switched on and off. Requests and replies use QoS 1 without retained messages.
123
+
124
+ - `procedure.provide(rid, callback)` answers calls to `rid` with what `callback(args)` returns or
125
+ resolves to. When it throws or rejects, the caller's promise rejects with its message. Returns
126
+ the function that removes this provider.
127
+ - `procedure.unprovide(rid, callback)` removes that provider. Without a callback it removes every
128
+ provider of the rid.
129
+ - `procedure.call(rid, args = {}, timeout = 5)` resolves with the provider's reply. It waits for
130
+ its reply subscription to be acknowledged before sending the request. It rejects with the
131
+ provider's message, with `Timeout while waiting for reply.` after `timeout` seconds, or when MQTT
132
+ is disconnected.
133
+
134
+ MQTT may deliver a request twice. A provider answers a repeated request id with the reply it already
135
+ gave, but only from memory, so a procedure with lasting side effects should also be idempotent
136
+ across provider restarts. A call made while no provider is connected is not kept.
137
+
138
+ ## `connection`
139
+
140
+ - `connection.subscribe(callback)` calls back with `{ connected }` at once, and again whenever the
141
+ MQTT connection comes up or goes down. Returns the function that undoes it.
142
+
143
+ ## `auth`
144
+
145
+ - `auth.getUserInfo()` resolves with `{ id, firstName, lastName, email }` of whoever the request
146
+ is authenticated as. For a service, `id` is its client id.
147
+
148
+ ## `mqttClient`
149
+
150
+ The client's own MQTT connection, for topics of your own. Topics are used as they are given, so a
151
+ subscription may be a filter with wildcards.
152
+
153
+ - `mqttClient.publish(topic, message, options)` sends a string or binary data as it is, nothing as
154
+ an empty message, which clears a retained one, and anything else as JSON. `options` are
155
+ MQTT.js's, such as `{ qos, retain }`.
156
+ - `mqttClient.subscribe(topic, callback, { qos })` returns the function that undoes it. The
157
+ callback gets `{ topic, data }`, with `data` parsed from JSON.
158
+ - `mqttClient.subscribeWithAck(topic, callback, { qos })` returns `{ ready, unsubscribe }`.
159
+ - `mqttClient.unsubscribe(topic, callback)`. Without a callback it removes every callback on the
160
+ topic.
161
+
162
+ `mqttClient.client` is the MQTT.js client underneath. It is reachable, but not part of what this
163
+ package promises.
164
+
165
+ ## `close()`
166
+
167
+ Ends the MQTT connection and resolves once it has ended.
168
+
169
+ ## Datasets
170
+
171
+ ```javascript
172
+ import { createDataset } from '@faybl/client';
173
+
174
+ const ovens = createDataset(client, {
175
+ entity: 'asset',
176
+ filter: { type: 'oven' },
177
+ projection: { id: 1, name: 1, channels: 1 },
178
+ });
179
+ await ovens.init();
180
+ ovens.subscribe(({ type, rid, record, previous }) => redraw());
181
+ ```
182
+
183
+ A dataset holds the records of one entity that its spec describes, and follows conf's changes.
184
+
185
+ | Spec | Meaning |
186
+ | ----------------- | ------------------------------------------------------------------- |
187
+ | `entity` | The entity, such as `asset`. |
188
+ | `rids` | Only these records. |
189
+ | `filter` | A MongoDB filter. |
190
+ | `projection` | A MongoDB projection. `rid` is always included. |
191
+ | `recordTransform` | Applied to every record the dataset takes in, after the projection. |
192
+ | anything else | Passed on to `conf.<entity>.read`, such as `sort`. |
193
+
194
+ `rids` and `filter` apply to every change as they do to the read: a changed record is matched with
195
+ the filter as a whole, before the projection, and is added, replaced or removed accordingly. An
196
+ operation that cannot be evaluated outside MongoDB, such as `$text` or `$where`, stops the dataset
197
+ from loading.
198
+
199
+ A dataset subscribes before it reads, and applies the changes that arrive meanwhile on top of what
200
+ it read, so a change made while it loads is not lost. It does not load without MQTT, or when the
201
+ broker refuses the subscription. Changes published while the connection is down are not seen.
202
+
203
+ `createDataset(client, spec)` returns:
204
+
205
+ - `init()`, which resolves once loaded, or rejects with the error that stopped it.
206
+ - `getRecords()`.
207
+ - `subscribe(callback)` and `unsubscribe(callback)`, without a callback removing them all. A
208
+ callback gets `{ type, rid, record, previous }` after the records have changed, with `type`
209
+ `add`, `update` or `remove`. `record` is missing when a record was deleted, and `previous` when
210
+ it was added.
211
+ - `stop()`, which ends the subscription and drops the callbacks.
212
+ - `machine`, the XState actor underneath.
213
+
214
+ `createDatasetMachine(client, spec, onChange)` is the same as an XState machine, for spawning in a
215
+ machine of your own. It is in `Init` while it loads, then `Idle`, or `Error` with the error in
216
+ `context.error`, where a `retry` event starts it over. Its records are in `context.records`.
217
+ `datasetLoaded(actorRef)` resolves with the records once it is `Idle`, and rejects with the error
218
+ when it ends in `Error`.
219
+
220
+ ## Releasing
221
+
222
+ ```
223
+ npm version patch # or minor, major, or an exact version
224
+ npm version prerelease --preid=rc
225
+ ```
226
+
227
+ `.npmrc` sets `tag-version-prefix=version/`, so the tag is `version/4.0.0`. `preversion` runs
228
+ `npm run verify`, and `postversion` says what to do next; nothing is pushed or published on its
229
+ own. Then either publish from here:
230
+
231
+ ```
232
+ npm run release
233
+ ```
234
+
235
+ or push the tag, and CI publishes it through npm trusted publishing:
236
+
237
+ ```
238
+ git push --follow-tags
239
+ ```
240
+
241
+ `npm run release` refuses to upload unless the working tree is clean, HEAD carries the tag of the
242
+ current version and there is an npm login or a CI token. A version already on the registry is
243
+ skipped, so publishing locally and then pushing the tag is a no-op in CI.
244
+
245
+ ## License
246
+
247
+ MIT, see [LICENSE](LICENSE).
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "@faybl/client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.0.0",
4
+ "description": "Faybl JavaScript Client",
5
+ "license": "MIT",
6
+ "author": "Arcturitech",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://gitlab.com/arcturitech/faybl/faybl-client-js.git"
10
+ },
11
+ "type": "module",
12
+ "exports": {
13
+ ".": {
14
+ "import": "./src/index.js"
15
+ },
16
+ "./browser": {
17
+ "import": "./src/browser.js"
18
+ }
19
+ },
20
+ "main": "src/index.js",
21
+ "module": "src/index.js",
22
+ "files": [
23
+ "src"
24
+ ],
25
+ "scripts": {
26
+ "checkExports": "node --input-type=module -e \"import('./src/index.js').then(m=>console.log(Object.keys(m)))\"",
27
+ "format": "prettier . --write",
28
+ "format:check": "prettier . --check",
29
+ "itest": "vitest run --project itest --coverage",
30
+ "lint": "eslint .",
31
+ "perf": "vitest run --project perf",
32
+ "prettypackagejson": "prettier-package-json --write ./package.json",
33
+ "release": "node scripts/release.mjs",
34
+ "test": "vitest run --project test --coverage",
35
+ "verify": "npm run format:check && npm run lint && npm test",
36
+ "preversion": "npm run verify",
37
+ "postversion": "node scripts/version-hint.mjs"
38
+ },
39
+ "sideEffects": false,
40
+ "dependencies": {
41
+ "@paralleldrive/cuid2": "^3.3.0",
42
+ "mqtt": "^5.16.1",
43
+ "mqtt-match": "^3.0.0",
44
+ "openid-client": "^6.8.8",
45
+ "ramda": "^0.32.0",
46
+ "sift": "^17.1.4",
47
+ "tri-fp": "^4.2.0",
48
+ "xstate": "^5.33.3"
49
+ },
50
+ "devDependencies": {
51
+ "@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",
58
+ "prettier-package-json": "^2.8.0",
59
+ "typescript": "^6.0.3",
60
+ "vite": "^8.3.4",
61
+ "vitest": "^5.0.5"
62
+ },
63
+ "engines": {
64
+ "node": ">=22"
65
+ },
66
+ "publishConfig": {
67
+ "access": "public"
68
+ }
69
+ }
package/src/auth.js ADDED
@@ -0,0 +1,15 @@
1
+ import { fetchCheckedJson } from './fetch.js';
2
+
3
+ export const getAuthApi = (authenticatorUrl, oidcHandler) => {
4
+ const getUserInfo = async () => {
5
+ return fetchCheckedJson(
6
+ `${authenticatorUrl}/getUserInfo`,
7
+ {
8
+ method: 'POST',
9
+ },
10
+ oidcHandler,
11
+ );
12
+ };
13
+
14
+ return { getUserInfo };
15
+ };
package/src/browser.js ADDED
@@ -0,0 +1,31 @@
1
+ import { clientOptionsError } from './clientOptions.js';
2
+ import { createClient as createBrowserClient } from './client.js';
3
+ import { createMqttClient } from './mqtt.js';
4
+ import { createReporter } from './report.js';
5
+
6
+ export { createDataset, createDatasetMachine, datasetLoaded } from './dataset.js';
7
+
8
+ export const createClient = async (options = {}) => {
9
+ const optionsError = clientOptionsError(options);
10
+ if (optionsError) return Promise.reject(optionsError);
11
+ const { tenantUrl, confUrl, dataHistoryUrl, mqttUrl, authenticatorUrl, noMqtt, noAuth, onError } =
12
+ options;
13
+ const report = createReporter(onError);
14
+
15
+ const mqttClient = noMqtt
16
+ ? undefined
17
+ : await createMqttClient({
18
+ mqttUrl: mqttUrl || `wss://ws.${tenantUrl}`,
19
+ authenticatorUrl: authenticatorUrl || `https://${tenantUrl}/authenticator`,
20
+ noAuth,
21
+ report,
22
+ });
23
+
24
+ return createBrowserClient({
25
+ authenticatorUrl: authenticatorUrl || `https://${tenantUrl}/authenticator`,
26
+ confUrl: confUrl || `https://${tenantUrl}/conf`,
27
+ dataHistoryUrl: dataHistoryUrl || `https://${tenantUrl}/data-history`,
28
+ mqttClient,
29
+ report,
30
+ });
31
+ };
package/src/channel.js ADDED
@@ -0,0 +1,50 @@
1
+ import { mqttDisabledWarning } from './mqttUtils.js';
2
+ import { assertTopicSegment } from './topicSegment.js';
3
+ import { fetchCheckedJson } from './fetch.js';
4
+
5
+ const baseTopic = 'channel';
6
+
7
+ const createPubMsg = (pl, other = {}) => ({
8
+ ts: new Date().toISOString(),
9
+ pl,
10
+ ...other,
11
+ });
12
+
13
+ export const getChannelApi = (dataHistoryUrl, mqttClient, oidcHandler) => {
14
+ const preCallback = ({ topic, data }) => {
15
+ return { rid: topic.replace(`${baseTopic}/`, ''), data };
16
+ };
17
+ const topicFor = (rid) => `${baseTopic}/${assertTopicSegment('rid', rid)}`;
18
+ const unsubscribe = (rid, callback) => mqttClient.unsubscribe(topicFor(rid), callback);
19
+ const subscribe = (rid, callback) => {
20
+ mqttClient.subscribe(topicFor(rid), callback, { preCallback });
21
+ return () => unsubscribe(rid, callback);
22
+ };
23
+ const publish = (rid, pl, other) => mqttClient.publish(topicFor(rid), createPubMsg(pl, other));
24
+
25
+ const read = (args) => {
26
+ return fetchCheckedJson(
27
+ `${dataHistoryUrl}/read`,
28
+ {
29
+ body: JSON.stringify(args),
30
+ method: 'POST',
31
+ },
32
+ oidcHandler,
33
+ );
34
+ };
35
+
36
+ return {
37
+ read,
38
+ ...(mqttClient
39
+ ? {
40
+ subscribe,
41
+ unsubscribe,
42
+ publish,
43
+ }
44
+ : {
45
+ subscribe: mqttDisabledWarning,
46
+ unsubscribe: mqttDisabledWarning,
47
+ publish: mqttDisabledWarning,
48
+ }),
49
+ };
50
+ };
package/src/client.js ADDED
@@ -0,0 +1,35 @@
1
+ import { getAuthApi } from './auth.js';
2
+ import { getConfApi } from './conf.js';
3
+ import { getChannelApi } from './channel.js';
4
+ import { getConnectionApi } from './connection.js';
5
+ import { getProcedureApi } from './procedure.js';
6
+ import { getPresenceApi } from './presence.js';
7
+
8
+ export const createClient = ({
9
+ authenticatorUrl,
10
+ confUrl,
11
+ dataHistoryUrl,
12
+ mqttClient,
13
+ oidcHandler,
14
+ report,
15
+ }) => {
16
+ const auth = getAuthApi(authenticatorUrl, oidcHandler);
17
+ const channel = getChannelApi(dataHistoryUrl, mqttClient, oidcHandler);
18
+ const conf = getConfApi(confUrl, mqttClient, oidcHandler);
19
+ const procedure = getProcedureApi(mqttClient, report);
20
+ const presence = getPresenceApi(mqttClient);
21
+ const connection = getConnectionApi(mqttClient);
22
+
23
+ const close = async () => mqttClient?.close();
24
+
25
+ return {
26
+ auth,
27
+ channel,
28
+ conf,
29
+ procedure,
30
+ presence,
31
+ connection,
32
+ mqttClient,
33
+ close,
34
+ };
35
+ };
@@ -0,0 +1,36 @@
1
+ // A host name with an optional port: every service URL is built by prefixing a
2
+ // scheme or a subdomain, so a scheme or a path in it would produce a broken URL.
3
+ const TENANT_HOST = /^[^\s/:]+(:\d+)?$/;
4
+
5
+ const tenantUrlError = (tenantUrl) =>
6
+ typeof tenantUrl === 'string' && TENANT_HOST.test(tenantUrl)
7
+ ? undefined
8
+ : Error(
9
+ `Invalid tenantUrl ${JSON.stringify(tenantUrl)}: it must be a host name such as 'tenant.faybl.online', without scheme or path`,
10
+ );
11
+
12
+ const requiredEndpoints = ({ noMqtt }) => [
13
+ 'confUrl',
14
+ 'dataHistoryUrl',
15
+ 'authenticatorUrl',
16
+ ...(noMqtt ? [] : ['mqttUrl']),
17
+ ];
18
+
19
+ const endpointsError = (options) => {
20
+ if (options.tenantUrl !== undefined) return tenantUrlError(options.tenantUrl);
21
+ const missing = requiredEndpoints(options).filter((name) => !options[name]);
22
+ return missing.length === 0
23
+ ? undefined
24
+ : Error(`createClient needs a tenantUrl, or else ${missing.join(', ')}`);
25
+ };
26
+
27
+ const onErrorError = ({ onError }) =>
28
+ onError === undefined || typeof onError === 'function'
29
+ ? undefined
30
+ : Error('Invalid onError: it must be a function');
31
+
32
+ /**
33
+ * Returns the Error createClient rejects with, or undefined when the options name
34
+ * either a tenant or every endpoint the client will use.
35
+ */
36
+ export const clientOptionsError = (options) => onErrorError(options) ?? endpointsError(options);
package/src/conf.js ADDED
@@ -0,0 +1,82 @@
1
+ import * as R from 'ramda';
2
+
3
+ import { mqttDisabledWarning } from './mqttUtils.js';
4
+ import { fetchCheckedJson } from './fetch.js';
5
+ import { assertTopicSegment, assertTopicSegmentOneOf } from './topicSegment.js';
6
+
7
+ const ENTITIES = [
8
+ 'asset',
9
+ 'assettype',
10
+ 'channel',
11
+ 'channeltype',
12
+ 'config',
13
+ 'configtype',
14
+ 'procedure',
15
+ 'proceduretype',
16
+ 'rule',
17
+ 'thing',
18
+ 'thingtype',
19
+ 'trigger',
20
+ ];
21
+ const CRUD_OPERATIONS = ['create', 'read', 'update', 'delete'];
22
+ const PUBLISHED_OPERATIONS = ['create', 'update', 'delete'];
23
+
24
+ // A part left out is a wildcard, which is what subscribing to every entity or operation means.
25
+ const topicPart = (check) => (value) => (value === undefined ? '+' : check(value));
26
+
27
+ const lowerCased = (value) => (typeof value === 'string' ? value.toLowerCase() : value);
28
+
29
+ const entityPart = topicPart((entity) =>
30
+ assertTopicSegmentOneOf('entity', lowerCased(entity), ENTITIES),
31
+ );
32
+ const operationPart = topicPart((operation) =>
33
+ assertTopicSegmentOneOf('operation', lowerCased(operation), PUBLISHED_OPERATIONS),
34
+ );
35
+ const ridPart = topicPart((rid) => assertTopicSegment('rid', rid));
36
+
37
+ const getConfTopic = (entity, operation, rid) =>
38
+ `conf/${entityPart(entity)}/${operationPart(operation)}/${ridPart(rid)}`;
39
+
40
+ export const getConfApi = (confUrl, mqttClient, oidcHandler) => {
41
+ const crudEntity = (entityClass, operation) => (args) => {
42
+ return fetchCheckedJson(
43
+ `${confUrl}/${entityClass}/${operation}`,
44
+ {
45
+ body: JSON.stringify(args),
46
+ method: 'POST',
47
+ },
48
+ oidcHandler,
49
+ );
50
+ };
51
+
52
+ const entityApi = (entityClass) =>
53
+ R.fromPairs(
54
+ CRUD_OPERATIONS.map((operation) => [operation, crudEntity(entityClass, operation)]),
55
+ );
56
+ const confApi = R.fromPairs(ENTITIES.map((entityClass) => [entityClass, entityApi(entityClass)]));
57
+
58
+ const confPreCallback = ({ topic, data: record }) => {
59
+ const topicRoute = topic.split('/');
60
+ return { entity: topicRoute[1], operation: topicRoute[2], rid: topicRoute[3], record };
61
+ };
62
+ const subscribeConf = ({ entity, operation, rid, callback }) => {
63
+ const topic = getConfTopic(entity, operation, rid);
64
+ return mqttClient.subscribe(topic, callback, { preCallback: confPreCallback });
65
+ };
66
+ // Resolves `ready` once the broker has acknowledged the subscription.
67
+ const subscribeConfWithAck = ({ entity, operation, rid, callback }) => {
68
+ const topic = getConfTopic(entity, operation, rid);
69
+ return mqttClient.subscribeWithAck(topic, callback, { qos: 0, preCallback: confPreCallback });
70
+ };
71
+ const unsubscribeConf = ({ entity, operation, rid, callback }) => {
72
+ const topic = getConfTopic(entity, operation, rid);
73
+ mqttClient.unsubscribe(topic, callback);
74
+ };
75
+
76
+ return {
77
+ subscribe: mqttClient ? subscribeConf : mqttDisabledWarning,
78
+ subscribeWithAck: mqttClient ? subscribeConfWithAck : mqttDisabledWarning,
79
+ unsubscribe: mqttClient ? unsubscribeConf : mqttDisabledWarning,
80
+ ...confApi,
81
+ };
82
+ };
@@ -0,0 +1,29 @@
1
+ import { mqttDisabledWarning } from './mqttUtils.js';
2
+
3
+ const CONNECTED_BY_EVENT = { connect: true, offline: false, close: false };
4
+ const EVENTS = Object.keys(CONNECTED_BY_EVENT);
5
+
6
+ /**
7
+ * Follows the MQTT connection. The callback gets `{ connected }` at once with the current state, and
8
+ * again whenever it changes; the repeated `close` events of a reconnect loop are not passed on.
9
+ */
10
+ export const getConnectionApi = (mqttClient) => {
11
+ const subscribe = (callback) => {
12
+ const { client } = mqttClient;
13
+ // eslint-disable-next-line functional/no-let -- Each subscription remembers what it last passed on, across events MQTT.js emits independently.
14
+ let connected = client.connected === true;
15
+ const listeners = EVENTS.map((event) => [
16
+ event,
17
+ () => {
18
+ if (CONNECTED_BY_EVENT[event] === connected) return;
19
+ connected = CONNECTED_BY_EVENT[event];
20
+ callback({ connected });
21
+ },
22
+ ]);
23
+ listeners.forEach(([event, listener]) => client.on(event, listener));
24
+ callback({ connected });
25
+ return () => listeners.forEach(([event, listener]) => client.off(event, listener));
26
+ };
27
+
28
+ return { subscribe: mqttClient ? subscribe : mqttDisabledWarning };
29
+ };