@nebulahome/integration-sdk 0.0.0-stage → 1.1.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.
@@ -0,0 +1,545 @@
1
+ import { n as __toESM } from "./node-rolldown-runtime.js";
2
+ import { f as defineAccount, r as require_semver } from "./node-dist.js";
3
+ import { z } from "zod";
4
+ import { readFile, stat } from "node:fs/promises";
5
+ import path from "node:path";
6
+ //#region ../package-runtime/dist/stream.js
7
+ /**
8
+ * Turns a stream source written against its own configuration into one a registry can hold,
9
+ * validating the settings on the way in as {@link defineTransport} does.
10
+ *
11
+ * @param spec - The source.
12
+ * @returns The same source, its configuration parameter erased.
13
+ */
14
+ function defineStreamSource(spec) {
15
+ return {
16
+ id: spec.id,
17
+ configSchema: spec.configSchema,
18
+ /**
19
+ * Validates the settings, then reads.
20
+ *
21
+ * @param config - The settings.
22
+ * @param args - What to read.
23
+ * @param sink - Where it goes.
24
+ * @param signal - Ends it.
25
+ * @returns A promise that settles when it ended.
26
+ */
27
+ open: async (config, args, sink, signal) => spec.open(spec.configSchema.parse(config), args, sink, signal)
28
+ };
29
+ }
30
+ //#endregion
31
+ //#region ../package-runtime/dist/transport.js
32
+ /**
33
+ * Turns a transport written against its own configuration into one a registry can hold.
34
+ *
35
+ * Validation happens here and only here. Everything above receives whatever an owner put in a
36
+ * `jsonb` column and passes it straight through, so a wrong setting fails once, with the
37
+ * transport's own message, instead of being parsed in every caller that happens to remember to.
38
+ *
39
+ * @param spec - The transport, written against the configuration it understands.
40
+ * @returns The same transport, with its configuration parameter erased.
41
+ */
42
+ function defineTransport(spec) {
43
+ return {
44
+ id: spec.id,
45
+ configSchema: spec.configSchema,
46
+ /**
47
+ * Validates the settings, then asks the transport what they share.
48
+ *
49
+ * @param config - What the owner configured.
50
+ * @returns The connection key.
51
+ */
52
+ connectionKey: (config) => spec.connectionKey(spec.configSchema.parse(config)),
53
+ /**
54
+ * Validates the settings, then opens the connection.
55
+ *
56
+ * @param config - What the owner configured.
57
+ * @param context - Where inbound messages and status changes go.
58
+ * @returns The connection.
59
+ */
60
+ connect: async (config, context) => spec.connect(spec.configSchema.parse(config), context),
61
+ /**
62
+ * Validates the settings, then scans.
63
+ *
64
+ * @param config - What the owner configured.
65
+ * @param scan - The integration's search terms.
66
+ * @param signal - Ends the scan.
67
+ * @param context - The account the configuration names.
68
+ * @returns Candidates as they are found.
69
+ */
70
+ scan: (config, scan, signal, context) => spec.scan(spec.configSchema.parse(config), scan, signal, context),
71
+ /**
72
+ * Validates the settings, then tries them.
73
+ *
74
+ * @param config - What the owner typed.
75
+ * @param signal - Gives up.
76
+ * @param context - The account the configuration names.
77
+ * @returns What the transport said worked.
78
+ */
79
+ probe: async (config, signal, context) => spec.probe(spec.configSchema.parse(config), signal, context)
80
+ };
81
+ }
82
+ //#endregion
83
+ //#region src/version.ts
84
+ /**
85
+ * The SDK's own version, read from its `package.json` when it is built.
86
+ *
87
+ * It is also the version of the integration contract: what `hub` says it implements, and what a
88
+ * bundle's `sdk` range is checked against before the bundle loads (INTEGRATIONS_DOCS.md 11). A
89
+ * bundle built with this SDK says `^<major>.<minor>.0`.
90
+ */
91
+ /** The SDK's own version: `1.0.0`, or a prerelease of it. */
92
+ const SDK_VERSION = "1.1.0";
93
+ /**
94
+ * The runtime range a bundle built with this SDK declares: this version's major and minor, so a
95
+ * platform with the same contract or a later one of the same major loads it.
96
+ *
97
+ * @param version - The SDK's version.
98
+ * @returns The range, `^1.0.0`.
99
+ */
100
+ function sdkRangeOf(version) {
101
+ const [major = "0", minor = "0"] = version.split("-")[0]?.split(".") ?? [];
102
+ return `^${major}.${minor}.0`;
103
+ }
104
+ //#endregion
105
+ //#region src/testing/fake-sdk.ts
106
+ /**
107
+ * A {@link BundleSdk} for tests: the real pieces where they are pure - zod, `defineTransport`,
108
+ * `defineAccount`, `defineStreamSource` - a logger that keeps what it was told, UDP sockets and
109
+ * WebSockets that keep what was sent and take what a test delivers, and nothing else. A WebSocket
110
+ * here connects to nothing: the test opens it, drops it and opens it again, as the network and the
111
+ * hub's reconnection would. An MQTT session, an RTSP stream and the codecs are the hub's; a test
112
+ * that needs one passes its own in `overrides`, and one that reaches for a piece nobody passed is
113
+ * told so by name.
114
+ */
115
+ /** The first port a fake socket says it is bound to, when the bundle asks for none. */
116
+ const FIRST_FREE_PORT = 4e4;
117
+ /**
118
+ * A piece of the SDK no test passed: it says which, and how to pass it.
119
+ *
120
+ * @param name - The piece.
121
+ * @returns A function that throws.
122
+ */
123
+ function notFaked(name) {
124
+ return () => {
125
+ throw new Error(`${name} is not faked: pass your own in createFakeSdk({ overrides: { ${name.split(".")[0] ?? name} } })`);
126
+ };
127
+ }
128
+ /**
129
+ * A logger that keeps what it is told.
130
+ *
131
+ * @param logs - Where it keeps it.
132
+ * @param bound - The fields every line carries.
133
+ * @returns The logger.
134
+ */
135
+ function recordingLogger(logs, bound) {
136
+ /**
137
+ * One level.
138
+ *
139
+ * @param level - Which.
140
+ * @returns What logs at it.
141
+ */
142
+ const at = (level) => (first, message) => {
143
+ logs.push(typeof first === "string" ? {
144
+ level,
145
+ fields: bound,
146
+ message: first
147
+ } : {
148
+ level,
149
+ fields: {
150
+ ...bound,
151
+ ...first
152
+ },
153
+ message
154
+ });
155
+ };
156
+ return {
157
+ trace: at("trace"),
158
+ debug: at("debug"),
159
+ info: at("info"),
160
+ warn: at("warn"),
161
+ error: at("error"),
162
+ fatal: at("fatal"),
163
+ /**
164
+ * A logger whose lines carry more fields.
165
+ *
166
+ * @param fields - The fields.
167
+ * @returns The logger.
168
+ */
169
+ child: (fields) => recordingLogger(logs, {
170
+ ...bound,
171
+ ...fields
172
+ })
173
+ };
174
+ }
175
+ /**
176
+ * Builds a fake SDK.
177
+ *
178
+ * @param options - The platform's services, and the pieces the test supplies.
179
+ * @returns The SDK, and what the bundle does with it.
180
+ */
181
+ function createFakeSdk(options = {}) {
182
+ const logs = [];
183
+ const udpSockets = [];
184
+ const webSockets = [];
185
+ /** Closes each socket opened, for the release. */
186
+ const closers = [];
187
+ /**
188
+ * Opens a fake UDP socket.
189
+ *
190
+ * @param socketOptions - What the bundle asked for.
191
+ * @returns The socket.
192
+ */
193
+ const openUdpSocket = (socketOptions) => {
194
+ const sent = [];
195
+ const port = socketOptions.port ?? FIRST_FREE_PORT + udpSockets.length;
196
+ let isClosed = false;
197
+ const fake = {
198
+ options: socketOptions,
199
+ port,
200
+ sent,
201
+ /**
202
+ * Whether it was closed.
203
+ *
204
+ * @returns True once it was.
205
+ */
206
+ get isClosed() {
207
+ return isClosed;
208
+ },
209
+ /**
210
+ * Hands the bundle a datagram.
211
+ *
212
+ * @param message - What arrived.
213
+ * @param from - Who sent it.
214
+ */
215
+ deliver: (message, from = {
216
+ address: "192.0.2.1",
217
+ port: 4e3
218
+ }) => {
219
+ socketOptions.onMessage(Buffer.from(message), from);
220
+ }
221
+ };
222
+ udpSockets.push(fake);
223
+ closers.push(() => {
224
+ isClosed = true;
225
+ });
226
+ return {
227
+ port,
228
+ /**
229
+ * Keeps a datagram the bundle sends.
230
+ *
231
+ * @param message - What it sends.
232
+ * @param toPort - The port it sends to.
233
+ * @param address - The address it sends to.
234
+ * @returns Once kept.
235
+ * @throws {Error} When the socket is closed.
236
+ */
237
+ send: async (message, toPort, address) => {
238
+ if (isClosed) throw new Error("The socket is closed");
239
+ sent.push({
240
+ message: Buffer.from(message),
241
+ port: toPort,
242
+ address
243
+ });
244
+ return Promise.resolve();
245
+ },
246
+ /**
247
+ * Closes the socket.
248
+ *
249
+ * @returns Once closed.
250
+ */
251
+ close: async () => {
252
+ isClosed = true;
253
+ return Promise.resolve();
254
+ }
255
+ };
256
+ };
257
+ /**
258
+ * Opens a fake WebSocket, connected to nothing until the test opens it.
259
+ *
260
+ * @param socketOptions - What the bundle asked for.
261
+ * @returns The socket, as the bundle sees it.
262
+ */
263
+ const openWebSocket = (socketOptions) => {
264
+ const { url } = socketOptions;
265
+ const sent = [];
266
+ const resets = [];
267
+ let headers;
268
+ let isOpen = false;
269
+ let isClosed = false;
270
+ const fake = {
271
+ options: socketOptions,
272
+ url,
273
+ sent,
274
+ resets,
275
+ /**
276
+ * The headers of the last opening.
277
+ *
278
+ * @returns Them, or undefined before the first.
279
+ */
280
+ get headers() {
281
+ return headers;
282
+ },
283
+ /**
284
+ * Whether it is open.
285
+ *
286
+ * @returns True while it is.
287
+ */
288
+ get isOpen() {
289
+ return isOpen;
290
+ },
291
+ /**
292
+ * Whether it was closed for good.
293
+ *
294
+ * @returns True once it was.
295
+ */
296
+ get isClosed() {
297
+ return isClosed;
298
+ },
299
+ /**
300
+ * Opens it, as a connection that succeeds.
301
+ *
302
+ * @returns Once open.
303
+ * @throws {Error} When it is open already, or closed for good.
304
+ */
305
+ open: async () => {
306
+ if (isClosed) throw new Error(`The socket to ${url} is closed for good`);
307
+ if (isOpen) throw new Error(`The socket to ${url} is open already`);
308
+ const source = socketOptions.headers;
309
+ headers = typeof source === "function" ? await source() : source;
310
+ isOpen = true;
311
+ socketOptions.onOpen();
312
+ },
313
+ /**
314
+ * Hands the bundle a frame.
315
+ *
316
+ * @param text - The frame.
317
+ * @throws {Error} When it is not open.
318
+ */
319
+ deliver: (text) => {
320
+ if (!isOpen) throw new Error(`The socket to ${url} is not open`);
321
+ socketOptions.onMessage(text);
322
+ },
323
+ /**
324
+ * Ends the connection, or refuses an attempt.
325
+ *
326
+ * @param reason - Why.
327
+ * @param details - The close code and the status.
328
+ * @throws {Error} When it is closed for good.
329
+ */
330
+ drop: (reason, details = {}) => {
331
+ if (isClosed) throw new Error(`The socket to ${url} is closed for good`);
332
+ isOpen = false;
333
+ socketOptions.onClose(reason, details);
334
+ }
335
+ };
336
+ webSockets.push(fake);
337
+ closers.push(() => {
338
+ isOpen = false;
339
+ isClosed = true;
340
+ });
341
+ return {
342
+ /**
343
+ * Whether a frame can be sent now.
344
+ *
345
+ * @returns True while the test has it open.
346
+ */
347
+ get isOpen() {
348
+ return isOpen;
349
+ },
350
+ /**
351
+ * Keeps a frame the bundle sends.
352
+ *
353
+ * @param text - The frame.
354
+ * @throws {Error} When it is not open.
355
+ */
356
+ send: (text) => {
357
+ if (!isOpen) throw new Error(`The socket to ${url} is not open`);
358
+ sent.push(text);
359
+ },
360
+ /**
361
+ * Drops the connection and says so, as the hub does; the test opens it again.
362
+ *
363
+ * @param reason - Why.
364
+ */
365
+ reset: (reason) => {
366
+ if (!isOpen) return;
367
+ resets.push(reason);
368
+ isOpen = false;
369
+ socketOptions.onClose(reason, {});
370
+ },
371
+ /**
372
+ * Closes for good.
373
+ *
374
+ * @returns Once closed.
375
+ */
376
+ close: async () => {
377
+ isOpen = false;
378
+ isClosed = true;
379
+ return Promise.resolve();
380
+ }
381
+ };
382
+ };
383
+ return {
384
+ sdk: {
385
+ version: SDK_VERSION,
386
+ z,
387
+ logger: recordingLogger(logs, {}),
388
+ defineTransport,
389
+ defineAccount,
390
+ defineStreamSource,
391
+ openUdpSocket,
392
+ openWebSocket,
393
+ openMqtt: notFaked("openMqtt"),
394
+ openRtsp: notFaked("openRtsp"),
395
+ platform: options.platform ?? { mqtt: null },
396
+ codecs: { lzma: notFaked("codecs.lzma") },
397
+ images: { png: notFaked("images.png") },
398
+ ...options.overrides
399
+ },
400
+ logs,
401
+ udpSockets,
402
+ webSockets,
403
+ /**
404
+ * Closes what the bundle left open.
405
+ *
406
+ * @returns Once closed.
407
+ */
408
+ release: async () => {
409
+ for (const close of closers) close();
410
+ return Promise.resolve();
411
+ }
412
+ };
413
+ }
414
+ //#endregion
415
+ //#region src/project.ts
416
+ /**
417
+ * An integration's repository, as the command and the tests read it (INTEGRATIONS_DOCS.md 3).
418
+ *
419
+ * ```
420
+ * integration-acme/
421
+ * ├── package.json the release's version, and the SDK it is built with
422
+ * ├── src/ the vendor directory, as the hub loads it, its code in TypeScript
423
+ * └── dist/acme/ what the build writes: the vendor directory, its code in JavaScript
424
+ * ```
425
+ *
426
+ * `src/` is the vendor directory itself: `manifest.json`, the logo, one folder per driver. The
427
+ * build writes it to `dist/<vendor>/` - a folder named by the vendor, so that `dist/` is a
428
+ * directory of vendors as `hub` reads one (`HUB_DEV_BUNDLE_DIR`) - with the version and the
429
+ * runtime range written into the manifest and every module compiled.
430
+ */
431
+ var import_semver = /* @__PURE__ */ __toESM(require_semver(), 1);
432
+ /** Where the build writes the vendor directory, under a folder of its id. */
433
+ const OUTPUT_DIRECTORY = "dist";
434
+ /** Every problem found, each a sentence: what the command prints, one per line. */
435
+ var IntegrationError = class extends Error {
436
+ problems;
437
+ /**
438
+ * Makes the error.
439
+ *
440
+ * @param problems - Each problem, in a sentence.
441
+ */
442
+ constructor(problems) {
443
+ super(problems.join("\n"));
444
+ this.name = "IntegrationError";
445
+ this.problems = problems;
446
+ }
447
+ };
448
+ /**
449
+ * Whether a file is there.
450
+ *
451
+ * @param file - The file.
452
+ * @returns True when it is a file.
453
+ */
454
+ async function isFile(file) {
455
+ try {
456
+ return (await stat(file)).isFile();
457
+ } catch {
458
+ return false;
459
+ }
460
+ }
461
+ /**
462
+ * Reads a JSON file of the repository.
463
+ *
464
+ * @param file - The file.
465
+ * @param what - What it is, for the message.
466
+ * @returns What it holds.
467
+ * @throws {IntegrationError} When it cannot be read or is not JSON.
468
+ */
469
+ async function readJson(file, what) {
470
+ try {
471
+ const parsed = JSON.parse(await readFile(file, "utf8"));
472
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
473
+ } catch {}
474
+ throw new IntegrationError([`${what} (${file}) cannot be read as a JSON object`]);
475
+ }
476
+ /**
477
+ * Reads an integration's repository: its version, its vendor, where its sources and its build are.
478
+ *
479
+ * @param root - The repository's folder.
480
+ * @returns The project.
481
+ * @throws {IntegrationError} When `package.json` or `src/manifest.json` is missing, or the
482
+ * version is not a semantic version.
483
+ */
484
+ async function readProject(root) {
485
+ const packageJson = await readJson(path.join(root, "package.json"), "package.json");
486
+ const sourceDirectory = path.join(root, "src");
487
+ const manifest = await readJson(path.join(sourceDirectory, "manifest.json"), `src/manifest.json`);
488
+ const version = packageJson["version"];
489
+ const vendorId = manifest["id"];
490
+ const problems = [];
491
+ if (typeof version !== "string" || import_semver.default.valid(version) === null) problems.push(`package.json's version must be a semantic version, like 1.0.0`);
492
+ if (typeof vendorId !== "string" || !/^[a-z][a-z0-9-]{1,63}$/u.test(vendorId)) problems.push(`src/manifest.json's id must be a vendor id: lower case letters, digits and dashes`);
493
+ if (problems.length > 0 || typeof version !== "string" || typeof vendorId !== "string") throw new IntegrationError(problems);
494
+ const outputRoot = path.join(root, OUTPUT_DIRECTORY);
495
+ return {
496
+ root,
497
+ version,
498
+ vendorId,
499
+ sourceDirectory,
500
+ outputRoot,
501
+ outputDirectory: path.join(outputRoot, vendorId),
502
+ stamp: {
503
+ version,
504
+ sdk: sdkRangeOf(SDK_VERSION)
505
+ }
506
+ };
507
+ }
508
+ /** The extensions a module's source may have, by the extension the bundle names it with. */
509
+ const SOURCE_EXTENSIONS = {
510
+ ".js": [
511
+ ".ts",
512
+ ".mts",
513
+ ".js",
514
+ ".mjs"
515
+ ],
516
+ ".mjs": [".mts", ".mjs"]
517
+ };
518
+ /**
519
+ * Finds a module the bundle names in the sources: `./lan/transport.js` is `lan/transport.ts` -
520
+ * or `.js`, for a module written in JavaScript - since the bundle names what the build writes.
521
+ *
522
+ * @param directory - The folder the name is relative to.
523
+ * @param file - The name, as the bundle writes it.
524
+ * @returns The source's path, or null when there is none.
525
+ */
526
+ const sourceModule = async (directory, file) => {
527
+ const extension = path.extname(file);
528
+ const stem = file.slice(0, file.length - extension.length);
529
+ for (const candidate of SOURCE_EXTENSIONS[extension] ?? [extension]) {
530
+ const found = path.join(directory, `${stem}${candidate}`);
531
+ if (await isFile(found)) return found;
532
+ }
533
+ return null;
534
+ };
535
+ /**
536
+ * The version the runtime is checked against: this SDK's, without a prerelease, which a range
537
+ * would not match.
538
+ *
539
+ * @returns The version.
540
+ */
541
+ function runtimeVersion() {
542
+ return import_semver.default.coerce(SDK_VERSION)?.version ?? SDK_VERSION;
543
+ }
544
+ //#endregion
545
+ export { sourceModule as a, runtimeVersion as i, isFile as n, createFakeSdk as o, readProject as r, IntegrationError as t };
@@ -0,0 +1,24 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
24
+ export { __toESM as n, __commonJSMin as t };
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {}