@nebulahome/integration-sdk 1.0.0 → 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.
@@ -117,7 +117,7 @@ const ENTITY_DOMAINS = [
117
117
  * validation. Identifiers reach the database as primary lookups and NATS as subject tokens, so
118
118
  * an unvalidated one does not fail where it was created - it fails somewhere else, later.
119
119
  */
120
- const entityIdSchema = z.string().regex(/^[a-z][a-z0-9_]{0,31}\.[a-z][a-z0-9_]{0,63}$/, "Must be <domain>.<object_id>, lower case, letters digits underscore").brand();
120
+ const entityIdSchema = z.string().regex(/^[a-z][a-z0-9_]{0,31}\.[a-z0-9][a-z0-9_]{0,63}$/, "Must be <domain>.<object_id>, lower case, letters digits underscore").brand();
121
121
  /**
122
122
  * Parses a string into an entity identifier.
123
123
  *
@@ -166,6 +166,39 @@ function composeEntityId(domain, deviceId, objectId) {
166
166
  return formatEntityId(domain, `${slugify(deviceId).slice(0, room)}${suffix}`);
167
167
  }
168
168
  //#endregion
169
+ //#region ../contracts/dist/package-id.js
170
+ /**
171
+ * A package's identifier, apart from the manifest: the integrations' instance ids share its
172
+ * pattern, and the modules that need only the pattern must not pull the manifest's whole grammar
173
+ * - and what that imports - in with it.
174
+ */
175
+ /**
176
+ * A package identifier: `mqtt`, `nvr`, `3d-home`. It may start with a digit; its entities' object
177
+ * ids then do too (`sensor.3d_home_kitchen_temperature`).
178
+ *
179
+ * Mirrors `packages_id_format` in DATABASE.md. It shares one namespace with the integrations'
180
+ * instance ids, since both answer `svc.<id>.command`.
181
+ */
182
+ const PACKAGE_ID_PATTERN = /^[a-z0-9][a-z0-9-]{1,63}$/;
183
+ /** The reserved ids, for a quick look-up. */
184
+ const RESERVED = /* @__PURE__ */ new Set([
185
+ "api",
186
+ "backup",
187
+ "core",
188
+ "derived",
189
+ "hub",
190
+ "logger",
191
+ "nebula",
192
+ "packet-manager",
193
+ "platform",
194
+ "proxy",
195
+ "supervisor",
196
+ "system",
197
+ "web-ui"
198
+ ]);
199
+ /** Validates a package identifier. */
200
+ const packageIdSchema = z.string().regex(PACKAGE_ID_PATTERN, "Must be a package id").refine((id) => !RESERVED.has(id), { message: "Is the name of a part of the platform, which no package may take" });
201
+ //#endregion
169
202
  //#region ../contracts/dist/capabilities.js
170
203
  /**
171
204
  * Capabilities: what an entity can do and what it reports.
@@ -651,7 +684,7 @@ const customStateSchema = z.object({ values: z.record(customKeySchema, customVal
651
684
  /** Which package's entity type an entity is. */
652
685
  const customParamsSchema = z.object({
653
686
  /** The package, by its id (the pattern of `packageIdSchema`). */
654
- packageId: z.string().regex(/^[a-z][a-z0-9-]{1,63}$/),
687
+ packageId: z.string().regex(PACKAGE_ID_PATTERN),
655
688
  /** The entity type, one of the package's `entityTypes`. */
656
689
  type: z.string().regex(/^[a-z][a-z0-9_-]{0,31}$/)
657
690
  });
@@ -914,7 +947,7 @@ const changeContextSchema = z.object({
914
947
  const sourceRefSchema = z.union([
915
948
  z.literal("derived"),
916
949
  z.literal("system"),
917
- z.string().regex(/^[a-z][a-z0-9-]{1,63}$/, "Must be a package id")
950
+ z.string().regex(PACKAGE_ID_PATTERN, "Must be a package id")
918
951
  ]);
919
952
  /** The complete state of one entity. */
920
953
  const entityStateSchema = z.object({
@@ -1561,38 +1594,6 @@ function pollIntervalMsOf(options) {
1561
1594
  return typeof seconds === "number" && Number.isFinite(seconds) && seconds >= 1 ? seconds * 1e3 : void 0;
1562
1595
  }
1563
1596
  //#endregion
1564
- //#region ../contracts/dist/package-id.js
1565
- /**
1566
- * A package's identifier, apart from the manifest: the integrations' instance ids share its
1567
- * pattern, and the modules that need only the pattern must not pull the manifest's whole grammar
1568
- * - and what that imports - in with it.
1569
- */
1570
- /**
1571
- * A package identifier: `mqtt`, `nvr`.
1572
- *
1573
- * Mirrors `packages_id_format` in DATABASE.md. It shares one namespace with the integrations'
1574
- * instance ids, since both answer `svc.<id>.command`.
1575
- */
1576
- const PACKAGE_ID_PATTERN = /^[a-z][a-z0-9-]{1,63}$/;
1577
- /** The reserved ids, for a quick look-up. */
1578
- const RESERVED = /* @__PURE__ */ new Set([
1579
- "api",
1580
- "backup",
1581
- "core",
1582
- "derived",
1583
- "hub",
1584
- "logger",
1585
- "nebula",
1586
- "packet-manager",
1587
- "platform",
1588
- "proxy",
1589
- "supervisor",
1590
- "system",
1591
- "web-ui"
1592
- ]);
1593
- /** Validates a package identifier. */
1594
- const packageIdSchema = z.string().regex(PACKAGE_ID_PATTERN, "Must be a package id").refine((id) => !RESERVED.has(id), { message: "Is the name of a part of the platform, which no package may take" });
1595
- //#endregion
1596
1597
  //#region ../contracts/dist/package-requires.js
1597
1598
  /**
1598
1599
  * What a package - or a vendor, in its `manifest.json` - needs besides itself (PACKAGES.md 7).
@@ -1754,7 +1755,8 @@ const transportIdSchema = z.string().regex(/^(?:[a-z][a-z0-9-]{1,63}\/)?[a-z][a-
1754
1755
  /**
1755
1756
  * The wires the interface names on a vendor's card: what a person recognises on the box, whatever
1756
1757
  * transport of the platform's or of the vendor's own carries it. `udp` is a device's own protocol
1757
- * over plain datagrams on the network (Govee's LAN API), `modbus` Modbus TCP.
1758
+ * over plain datagrams on the network (Govee's LAN API), `modbus` Modbus TCP, `matter` the
1759
+ * house's Matter fabric.
1758
1760
  */
1759
1761
  const TRANSPORT_WIRES = [
1760
1762
  "http",
@@ -1762,14 +1764,20 @@ const TRANSPORT_WIRES = [
1762
1764
  "ble",
1763
1765
  "zigbee",
1764
1766
  "udp",
1765
- "modbus"
1767
+ "modbus",
1768
+ "matter"
1766
1769
  ];
1767
1770
  /**
1768
- * How a device can be heard announcing itself: the platform's mDNS browser, or a vendor's own
1769
- * listener. Declared here rather than beside the discovered devices, because a vendor lists the
1770
- * ways it can be found and the discovery module already reads this file.
1771
+ * How a device can be heard announcing itself: the platform's mDNS browser, a vendor's own
1772
+ * listener, or the house's Matter fabric - a node commissioned and not yet added. Declared here
1773
+ * rather than beside the discovered devices, because a vendor lists the ways it can be found and
1774
+ * the discovery module already reads this file.
1771
1775
  */
1772
- const DISCOVERY_SOURCES = ["mdns", "module"];
1776
+ const DISCOVERY_SOURCES = [
1777
+ "mdns",
1778
+ "module",
1779
+ "matter"
1780
+ ];
1773
1781
  /**
1774
1782
  * Who adds a device discovery found: the owner, from its card - the ordinary way - or the
1775
1783
  * platform, as soon as it is heard. Automatic for a vendor whose devices were already chosen
@@ -1804,10 +1812,15 @@ const integrationStateSchema = z.enum([
1804
1812
  z.strictObject({ vendorId: z.string().regex(VENDOR_ID_PATTERN$1) });
1805
1813
  z.object({ isLoaded: z.boolean() });
1806
1814
  /**
1807
- * Which of the two places `hub` read a vendor from: the data directory, where the platform
1808
- * installs vendors, or a directory of bundles under development, read outside production.
1815
+ * Where `hub` read a vendor from: the data directory, where the platform installs vendors, a
1816
+ * directory of bundles under development, read outside production - or nowhere, for the one vendor
1817
+ * the platform is itself: `matter`, the Matter devices no integration claims.
1809
1818
  */
1810
- const BUNDLE_ORIGINS = ["installed", "development"];
1819
+ const BUNDLE_ORIGINS = [
1820
+ "installed",
1821
+ "development",
1822
+ "platform"
1823
+ ];
1811
1824
  /**
1812
1825
  * How the platform installed a vendor: the contents of the marker beside its builds,
1813
1826
  * `hub/integrations/<vendor>/.nebula-install.json`, which names the build `hub` loads.
@@ -4287,6 +4300,161 @@ z.object({
4287
4300
  entityIds: z.array(entityIdSchema)
4288
4301
  });
4289
4302
  //#endregion
4303
+ //#region ../contracts/dist/matter.js
4304
+ /**
4305
+ * The house's Matter fabric, as the hub runs it and the Brokers page shows it.
4306
+ *
4307
+ * Matter is one of the platform's brokers: the hub holds the controller - one fabric for the
4308
+ * house - and every Matter device is reached through it. A node is commissioned once, with the
4309
+ * code another app (the maker's, Google Home, Apple Home, Alexa) shares, and is then a device of
4310
+ * the house: of the integration whose `discovery.json` recognises it, or of the platform's own
4311
+ * `matter` vendor when none does. A bridge is one node with a device per bridged endpoint.
4312
+ *
4313
+ * The identity a node is recognised by is {@link matterIdentitySchema}: what its Basic Information
4314
+ * (or, for a bridged device, its Bridged Device Basic Information), General Diagnostics and
4315
+ * Descriptor clusters say, read by an integration's rules the way an mDNS announcement is.
4316
+ */
4317
+ /** The platform transport every Matter device is reached through. */
4318
+ const MATTER_TRANSPORT = "matter";
4319
+ /** The platform's own vendor: the Matter devices no integration claims. */
4320
+ const MATTER_VENDOR = "matter";
4321
+ /** A node id, in decimal: a 64-bit number, which JSON cannot carry as a number. */
4322
+ const matterNodeIdSchema = z.string().regex(/^[0-9]{1,20}$/u, "Must be a node id");
4323
+ /**
4324
+ * A pairing code, as another app shares it: the manual code - 11 or 21 digits, often written in
4325
+ * groups - or the QR code's text, `MT:` and base-38. Spaces and dashes are dropped from a manual
4326
+ * code, so `3497-011-2332` is `34970112332`.
4327
+ */
4328
+ const matterPairingCodeSchema = z.string().trim().max(128).transform((code) => code.startsWith("MT:") ? code : code.replaceAll(/[\s-]/gu, "")).pipe(z.string().regex(/^(?:[0-9]{11}|[0-9]{21}|MT:[0-9A-Z.-]{19,})$/u, "Must be the 11 or 21 digits of a pairing code, or the text of its QR code (MT:…)"));
4329
+ /** How many items a list in an identity holds at most. */
4330
+ const MAXIMUM_LIST = 64;
4331
+ /**
4332
+ * Who a Matter device says it is: what an integration's rules match and the Brokers page shows.
4333
+ *
4334
+ * Every field is null when the device does not say it - most leave a product label or a serial
4335
+ * out - so a rule reads `null` rather than a missing key. `endpoint` is null for the node itself
4336
+ * and the endpoint's number for a device behind a bridge, whose names are its own.
4337
+ */
4338
+ const matterIdentitySchema = z.object({
4339
+ nodeId: matterNodeIdSchema,
4340
+ endpoint: z.int().min(0).max(65535).nullable(),
4341
+ vendorId: z.int().min(0).max(65535).nullable(),
4342
+ productId: z.int().min(0).max(65535).nullable(),
4343
+ vendorName: z.string().max(256).nullable(),
4344
+ productName: z.string().max(256).nullable(),
4345
+ productLabel: z.string().max(256).nullable(),
4346
+ nodeLabel: z.string().max(256).nullable(),
4347
+ serialNumber: z.string().max(256).nullable(),
4348
+ uniqueId: z.string().max(256).nullable(),
4349
+ hardwareVersion: z.int().min(0).nullable(),
4350
+ hardwareVersionString: z.string().max(256).nullable(),
4351
+ softwareVersion: z.int().min(0).nullable(),
4352
+ softwareVersionString: z.string().max(256).nullable(),
4353
+ /** The hardware addresses of its network interfaces, lower-case and colon-separated. */
4354
+ macAddresses: z.array(z.string().max(64)).max(MAXIMUM_LIST),
4355
+ /** The Matter device types it declares, by number: `256` an on/off light. */
4356
+ deviceTypes: z.array(z.int().min(0)).max(MAXIMUM_LIST),
4357
+ /** The clusters its endpoints serve, by number, each once. */
4358
+ clusters: z.array(z.int().min(0)).max(256),
4359
+ /** Whether the node is a bridge, with devices of its own behind it. */
4360
+ isBridge: z.boolean(),
4361
+ /** Whether this is a device behind a bridge. */
4362
+ isBridged: z.boolean()
4363
+ });
4364
+ /** How the controller stands. */
4365
+ const MATTER_CONTROLLER_STATES = [
4366
+ "starting",
4367
+ "running",
4368
+ "failed",
4369
+ "disabled"
4370
+ ];
4371
+ /**
4372
+ * One commissioning: started by a pairing code, done once the node is on the fabric. A node takes
4373
+ * from seconds to a minute or two, longer than one request may wait, so the page reads the job
4374
+ * until it ends.
4375
+ */
4376
+ const matterCommissioningSchema = z.object({
4377
+ id: z.string().min(1).max(64),
4378
+ state: z.enum([
4379
+ "running",
4380
+ "succeeded",
4381
+ "failed"
4382
+ ]),
4383
+ startedAt: timestampSchema,
4384
+ finishedAt: timestampSchema.nullable(),
4385
+ /** The node it made; null until it succeeded. */
4386
+ nodeId: matterNodeIdSchema.nullable(),
4387
+ /** Why it failed, in a sentence; null unless it did. */
4388
+ error: z.string().max(2048).nullable()
4389
+ });
4390
+ z.object({
4391
+ state: z.enum(MATTER_CONTROLLER_STATES),
4392
+ /** Why it failed or is off, in a sentence; null while it runs. */
4393
+ error: z.string().max(2048).nullable(),
4394
+ /** The fabric's id, in hex; null before the controller has one. */
4395
+ fabricId: z.string().max(32).nullable(),
4396
+ /**
4397
+ * Whether the hub hears the house's network. Matter finds its nodes over mDNS and IPv6, which a
4398
+ * container on a bridge network does not carry: there the controller runs and reaches nothing.
4399
+ */
4400
+ isLanReachable: z.boolean(),
4401
+ nodes: z.object({
4402
+ total: z.int().min(0),
4403
+ online: z.int().min(0)
4404
+ }),
4405
+ /** The last commissioning; null when none was started since the hub started. */
4406
+ commissioning: matterCommissioningSchema.nullable()
4407
+ });
4408
+ /** One device a node is in the house: the node itself, or one endpoint behind a bridge. */
4409
+ const matterNodeDeviceSchema = z.object({
4410
+ identity: matterIdentitySchema,
4411
+ /** The clusters the platform turns into entities, and those it does not, by number. */
4412
+ mappedClusters: z.array(z.int().min(0)).max(256),
4413
+ unmappedClusters: z.array(z.int().min(0)).max(256),
4414
+ /** The device added for it; null while it is not, or after it was removed from the house. */
4415
+ deviceId: integrationIdSchema.nullable(),
4416
+ /** The driver it was added as; null while it is not added. */
4417
+ kind: integrationKindIdSchema.nullable(),
4418
+ /**
4419
+ * The integrations whose rules all take it, when there are several: it is then added as the
4420
+ * platform's own, and the page says who else wants it. Empty otherwise.
4421
+ */
4422
+ claimedBy: z.array(z.string().regex(VENDOR_ID_PATTERN$1)).max(16),
4423
+ /** Removed from the house, its node still on the fabric: the page offers it back. */
4424
+ isRemoved: z.boolean()
4425
+ });
4426
+ /** One node of the fabric. */
4427
+ const matterNodeSchema = z.object({
4428
+ nodeId: matterNodeIdSchema,
4429
+ isAvailable: z.boolean(),
4430
+ /** The node itself first, then each device behind it when it is a bridge. */
4431
+ devices: z.array(matterNodeDeviceSchema).min(1).max(256)
4432
+ });
4433
+ z.object({});
4434
+ z.object({});
4435
+ z.object({ items: z.array(matterNodeSchema) });
4436
+ z.object({ code: matterPairingCodeSchema });
4437
+ z.object({ nodeId: matterNodeIdSchema });
4438
+ z.object({ isRemoved: z.boolean() });
4439
+ z.object({
4440
+ nodeId: matterNodeIdSchema,
4441
+ endpoint: z.int().min(0).max(65535).nullable()
4442
+ });
4443
+ z.object({ isRestored: z.boolean() });
4444
+ /** The brokers the platform runs, as the Brokers page lists them. */
4445
+ const BROKER_IDS = [MATTER_VENDOR];
4446
+ /** One broker, for its card. */
4447
+ const brokerSummarySchema = z.object({
4448
+ id: z.enum(BROKER_IDS),
4449
+ state: z.enum(MATTER_CONTROLLER_STATES),
4450
+ /** The devices the house has through it, and how many of them answer. */
4451
+ devices: z.object({
4452
+ total: z.int().min(0),
4453
+ online: z.int().min(0)
4454
+ })
4455
+ });
4456
+ z.object({ items: z.array(brokerSummarySchema) });
4457
+ //#endregion
4290
4458
  //#region ../package-runtime/dist/containers.js
4291
4459
  /** A vendor setting a value is filled from: `{setup.serialPath}`. */
4292
4460
  const SETTING_PLACEHOLDER = /\{setup\.([a-zA-Z][a-zA-Z0-9]*)\}/g;
@@ -4350,8 +4518,15 @@ function containerDependencyProblems(deps, setup) {
4350
4518
  * JavaScript, and reaches a catalogue only after the manual approval ARCHITECTURE.md 10 already
4351
4519
  * requires of executable content.
4352
4520
  */
4353
- /** Bundle kind, which is both how it is written and how far it is trusted. */
4354
- const BUNDLE_KINDS = ["declarative", "code"];
4521
+ /**
4522
+ * Bundle kind, which is both how it is written and how far it is trusted. `matter` is a driver
4523
+ * the platform's Matter mapping runs: no profile and no code, so as far trusted as a profile.
4524
+ */
4525
+ const BUNDLE_KINDS = [
4526
+ "declarative",
4527
+ "code",
4528
+ "matter"
4529
+ ];
4355
4530
  /** Validates a vendor id. */
4356
4531
  const vendorIdSchema = z.string().regex(/^[a-z][a-z0-9-]{1,63}$/, "Must be a vendor id");
4357
4532
  /** Validates a driver id. */
@@ -4551,6 +4726,19 @@ const driverShape = {
4551
4726
  * @param ctx - Where to record what is wrong.
4552
4727
  */
4553
4728
  function checkKindFiles(manifest, ctx) {
4729
+ if (manifest.kind === "matter") {
4730
+ for (const named of ["profile", "entry"]) if (manifest[named] !== void 0) ctx.addIssue({
4731
+ code: "custom",
4732
+ path: [named],
4733
+ message: `A matter driver must not name an ${named}`
4734
+ });
4735
+ if (manifest.transport !== "matter") ctx.addIssue({
4736
+ code: "custom",
4737
+ path: ["transport"],
4738
+ message: `A matter driver runs on the ${MATTER_TRANSPORT} transport`
4739
+ });
4740
+ return;
4741
+ }
4554
4742
  const expected = manifest.kind === "declarative" ? "profile" : "entry";
4555
4743
  const forbidden = manifest.kind === "declarative" ? "entry" : "profile";
4556
4744
  if (manifest[expected] === void 0) ctx.addIssue({
@@ -4856,8 +5044,8 @@ function walk(payload, segments) {
4856
5044
  /**
4857
5045
  * Decides whether one condition holds.
4858
5046
  *
4859
- * The same four forms wherever a condition is written - a driver's claim, a vendor's match on
4860
- * an announcement - so there is one reading of each.
5047
+ * The same forms wherever a condition is written - a driver's claim, a vendor's match on an
5048
+ * announcement or on a Matter device - so there is one reading of each.
4861
5049
  *
4862
5050
  * @param condition - What to check.
4863
5051
  * @param payload - What the scan, the probe or the announcement said.
@@ -4868,7 +5056,14 @@ function conditionHolds(condition, payload) {
4868
5056
  if ("exists" in condition) return value !== void 0 && value !== null;
4869
5057
  if ("oneOf" in condition) return condition.oneOf.some((candidate) => candidate === value);
4870
5058
  if ("startsWith" in condition) return typeof value === "string" && value.toLowerCase().startsWith(condition.startsWith.toLowerCase());
4871
- return value === condition.equals;
5059
+ if ("endsWith" in condition) return typeof value === "string" && value.toLowerCase().endsWith(condition.endsWith.toLowerCase());
5060
+ if ("contains" in condition) {
5061
+ const wanted = condition.contains;
5062
+ if (Array.isArray(value)) return value.includes(wanted);
5063
+ return typeof value === "string" && typeof wanted === "string" && value.toLowerCase().includes(wanted.toLowerCase());
5064
+ }
5065
+ if ("equals" in condition) return value === condition.equals;
5066
+ return typeof value === "number" && (condition.min === void 0 || value >= condition.min) && (condition.max === void 0 || value <= condition.max);
4872
5067
  }
4873
5068
  //#endregion
4874
5069
  //#region ../package-runtime/dist/declarative.js
@@ -4999,7 +5194,7 @@ function readStateSource(value, payload) {
4999
5194
  if (typeof value === "string") return resolvePath(payload, value);
5000
5195
  if ("present" in value) return resolvePresence(payload, value.path);
5001
5196
  const resolved = resolvePath(payload, value.path);
5002
- const found = resolved === void 0 || value.bits === void 0 && value.base === void 0 ? resolved : numberOf(resolved, value.bits, value.base ?? 10);
5197
+ const found = resolved === void 0 || value.bits === void 0 && value.base === void 0 ? resolved : numberOf$1(resolved, value.bits, value.base ?? 10);
5003
5198
  if (found === void 0) return;
5004
5199
  if ("map" in value) {
5005
5200
  const key = typeof found === "string" || typeof found === "number" || typeof found === "boolean" ? String(found) : void 0;
@@ -5017,7 +5212,7 @@ function readStateSource(value, payload) {
5017
5212
  * @returns The number, or its bits unsigned; undefined when the value is no number, or no integer
5018
5213
  * where bits are read.
5019
5214
  */
5020
- function numberOf(value, bits, base) {
5215
+ function numberOf$1(value, bits, base) {
5021
5216
  const text = typeof value === "string" ? value.trim() : void 0;
5022
5217
  const number = typeof value === "number" ? value : text === void 0 || text === "" ? NaN : base === 16 ? /^[0-9a-f]+$/iu.test(text) ? Number.parseInt(text, 16) : NaN : Number(text);
5023
5218
  if (!Number.isFinite(number)) return;
@@ -5379,9 +5574,17 @@ const scalarSchema = z.union([
5379
5574
  * and not an `or` between paths: the list is still all-of, and a claim needing boolean
5380
5575
  * algebra is still a claim whose integration should be code.
5381
5576
  *
5382
- * `startsWith` is a prefix of a text, compared without regard to case: what a name a device
5383
- * gives itself on the network looks like - `shellyplus1-a8032ab1`, `ShellyDimmerG3-…` - when
5384
- * the rest of it is the device's own.
5577
+ * `startsWith` and `endsWith` are a prefix and a suffix of a text, compared without regard to
5578
+ * case: what a name a device gives itself on the network looks like - `shellyplus1-a8032ab1`,
5579
+ * `ShellyDimmerG3-…` - when the rest of it is the device's own, and a MAC address's maker by its
5580
+ * first three bytes.
5581
+ *
5582
+ * `contains` is a part of a text, without regard to case, or one item of a list - a Matter
5583
+ * device's `deviceTypes`, its `clusters`. `min` and `max` bound a number, both ends included: a
5584
+ * firmware version from which a driver takes the device.
5585
+ *
5586
+ * There is no regular expression on purpose: one written badly takes the hub's thread for as long
5587
+ * as it backtracks, and the grammar is what keeps a declarative bundle from doing that.
5385
5588
  */
5386
5589
  const claimConditionSchema = z.union([
5387
5590
  z.strictObject({
@@ -5399,7 +5602,20 @@ const claimConditionSchema = z.union([
5399
5602
  z.strictObject({
5400
5603
  path: pathSchema,
5401
5604
  startsWith: z.string().min(1).max(64)
5402
- })
5605
+ }),
5606
+ z.strictObject({
5607
+ path: pathSchema,
5608
+ endsWith: z.string().min(1).max(64)
5609
+ }),
5610
+ z.strictObject({
5611
+ path: pathSchema,
5612
+ contains: scalarSchema
5613
+ }),
5614
+ z.strictObject({
5615
+ path: pathSchema,
5616
+ min: z.number().optional(),
5617
+ max: z.number().optional()
5618
+ }).refine((condition) => condition.min !== void 0 || condition.max !== void 0, "A range needs min, max or both")
5403
5619
  ]);
5404
5620
  /** Part of a number: `[shift, width]`, the lowest bit first. */
5405
5621
  const bitsSchema = z.tuple([z.int().min(0).max(31), z.int().min(1).max(32)]).refine(([shift, width]) => shift + width <= 32, "The bits must fit in 32");
@@ -5738,13 +5954,30 @@ const discoveryProbeSchema = z.strictObject({
5738
5954
  args: jsonObjectSchema.default({}),
5739
5955
  timeoutMs: z.int().min(500).max(3e4).optional()
5740
5956
  });
5957
+ /**
5958
+ * Which of the house's Matter devices are the vendor's: rules on who each says it is - its
5959
+ * `vendorId`, `productName`, `macAddresses`, `deviceTypes`, every field of the platform's
5960
+ * `MatterIdentity` - and where it says its model, looked up in the `modelCodes` of the vendor's
5961
+ * drivers that say `"kind": "matter"`.
5962
+ *
5963
+ * A device is commissioned into the house by the owner, so it is added at once to the one vendor
5964
+ * whose rules all hold, or to the platform's own `matter` vendor when none - or more than one - do.
5965
+ */
5966
+ const matterDiscoverySchema = z.strictObject({
5967
+ /** Every condition must hold. All-of, and at least one: a vendor does not take every device. */
5968
+ match: z.array(claimConditionSchema).min(1).max(MAXIMUM_MATCH),
5969
+ /** Where the device says its model; its product id when not said. */
5970
+ model: identityPathSchema.default("productId")
5971
+ });
5741
5972
  /** Validates a whole `discovery.json`. */
5742
5973
  const vendorDiscoverySchema = z.strictObject({
5743
- listen: z.array(listenSourceSchema).min(1).max(MAXIMUM_SOURCES),
5974
+ /** Where the vendor's devices announce themselves; none for one found only through Matter. */
5975
+ listen: z.array(listenSourceSchema).max(MAXIMUM_SOURCES).default([]),
5744
5976
  /** Every condition must hold of an announcement for it to be the vendor's. All-of. */
5745
5977
  match: z.array(claimConditionSchema).max(MAXIMUM_MATCH).default([]),
5746
5978
  probe: discoveryProbeSchema.optional(),
5747
- identity: discoveryIdentitySchema,
5979
+ identity: discoveryIdentitySchema.default({}),
5980
+ matter: matterDiscoverySchema.optional(),
5748
5981
  /**
5749
5982
  * Who adds a device found. `owner` - the default - proposes it on the vendor's
5750
5983
  * page; `automatic` adds it as soon as it is heard, for devices the owner already chose
@@ -5765,7 +5998,12 @@ const vendorDiscoverySchema = z.strictObject({
5765
5998
  state: z.string().min(1).max(64)
5766
5999
  }).optional()
5767
6000
  }).superRefine((discovery, ctx) => {
5768
- if (discovery.probe === void 0 && discovery.identity.model === void 0) ctx.addIssue({
6001
+ if (discovery.listen.length === 0 && discovery.matter === void 0) ctx.addIssue({
6002
+ code: "custom",
6003
+ path: ["listen"],
6004
+ message: "A vendor listens somewhere, or says which Matter devices are its own, or both"
6005
+ });
6006
+ if (discovery.listen.length > 0 && discovery.probe === void 0 && discovery.identity.model === void 0) ctx.addIssue({
5769
6007
  code: "custom",
5770
6008
  path: ["identity", "model"],
5771
6009
  message: "A vendor that does not probe must say where the announcement names the model"
@@ -5874,7 +6112,8 @@ function choicesOf(driver) {
5874
6112
  * @returns The association, or null when no driver of the vendor takes the device.
5875
6113
  */
5876
6114
  function associateModel(plan, modelCode, claimedBy) {
5877
- const coded = modelCode === null ? [] : plan.codes.get(modelCode) ?? [];
6115
+ const reached = new Set(plan.drivers.filter((driver) => driver.transport !== MATTER_TRANSPORT).map(({ id }) => id));
6116
+ const coded = modelCode === null ? [] : (plan.codes.get(modelCode) ?? []).filter((entry) => reached.has(entry.driverId));
5878
6117
  if (coded.length > 0) {
5879
6118
  const found = claimedBy === void 0 ? coded.length === 1 ? coded[0] : void 0 : coded.find((entry) => claimedBy(entry.driverId));
5880
6119
  return found === void 0 ? null : {
@@ -5884,7 +6123,7 @@ function associateModel(plan, modelCode, claimedBy) {
5884
6123
  };
5885
6124
  }
5886
6125
  if (claimedBy === void 0) return null;
5887
- const driver = plan.drivers.find((candidate) => claimedBy(candidate.id));
6126
+ const driver = plan.drivers.find((candidate) => reached.has(candidate.id) && claimedBy(candidate.id));
5888
6127
  if (driver === void 0) return null;
5889
6128
  const choices = choicesOf(driver);
5890
6129
  const named = modelCode !== null && choices.includes(modelCode) ? modelCode : null;
@@ -5894,6 +6133,44 @@ function associateModel(plan, modelCode, claimedBy) {
5894
6133
  modelChoices: choices
5895
6134
  };
5896
6135
  }
6136
+ /**
6137
+ * Whether a Matter device is the vendor's, by the rules of its `matter` block.
6138
+ *
6139
+ * @param plan - The vendor's discovery.
6140
+ * @param identity - Who the device says it is.
6141
+ * @returns True when the vendor has a `matter` block and every one of its conditions holds.
6142
+ */
6143
+ function matchesMatter(plan, identity) {
6144
+ return plan.discovery.matter?.match.every((condition) => conditionHolds(condition, identity)) ?? false;
6145
+ }
6146
+ /**
6147
+ * Finds the driver of the vendor's that runs a Matter device of its, and its model.
6148
+ *
6149
+ * The model the device says is looked up in the `modelCodes` of the vendor's Matter drivers; one
6150
+ * it does not map goes to the vendor's Matter driver when it has only one.
6151
+ *
6152
+ * @param plan - The vendor's discovery.
6153
+ * @param identity - Who the device says it is.
6154
+ * @returns The association, or null when no Matter driver of the vendor takes it.
6155
+ */
6156
+ function associateMatter(plan, identity) {
6157
+ const drivers = plan.drivers.filter((driver) => driver.transport === MATTER_TRANSPORT);
6158
+ const modelCode = textAt(identity, plan.discovery.matter?.model ?? "productId");
6159
+ const [first] = modelCode === null ? [] : (plan.codes.get(modelCode) ?? []).filter((entry) => drivers.some((driver) => driver.id === entry.driverId));
6160
+ if (first !== void 0) return {
6161
+ driverId: first.driverId,
6162
+ model: first.models.length === 1 ? first.models[0] ?? null : null,
6163
+ modelChoices: first.models
6164
+ };
6165
+ const [only, other] = drivers;
6166
+ if (only === void 0 || other !== void 0) return null;
6167
+ const choices = choicesOf(only);
6168
+ return {
6169
+ driverId: only.id,
6170
+ model: modelCode !== null && choices.includes(modelCode) ? modelCode : choices.length === 1 ? choices[0] ?? null : null,
6171
+ modelChoices: choices
6172
+ };
6173
+ }
5897
6174
  //#endregion
5898
6175
  //#region ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js
5899
6176
  var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
@@ -7293,6 +7570,1111 @@ var require_semver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7293
7570
  };
7294
7571
  }));
7295
7572
  //#endregion
7573
+ //#region ../package-runtime/dist/matter-node.js
7574
+ var import_semver = /* @__PURE__ */ __toESM(require_semver(), 1);
7575
+ /** The clusters this module reads by number, and the platform maps. */
7576
+ const CLUSTER = {
7577
+ identify: 3,
7578
+ onOff: 6,
7579
+ levelControl: 8,
7580
+ descriptor: 29,
7581
+ basicInformation: 40,
7582
+ otaRequestor: 42,
7583
+ powerSource: 47,
7584
+ generalDiagnostics: 51,
7585
+ bridgedBasicInformation: 57,
7586
+ booleanState: 69,
7587
+ electricalPowerMeasurement: 144,
7588
+ electricalEnergyMeasurement: 145,
7589
+ doorLock: 257,
7590
+ windowCovering: 258,
7591
+ thermostat: 513,
7592
+ colorControl: 768,
7593
+ illuminanceMeasurement: 1024,
7594
+ temperatureMeasurement: 1026,
7595
+ pressureMeasurement: 1027,
7596
+ relativeHumidityMeasurement: 1029,
7597
+ occupancySensing: 1030,
7598
+ carbonDioxideMeasurement: 1037
7599
+ };
7600
+ /** The device types this module tells apart, by number. */
7601
+ const DEVICE_TYPE = {
7602
+ aggregator: 14,
7603
+ bridgedNode: 19,
7604
+ contactSensor: 21,
7605
+ waterLeakDetector: 67,
7606
+ onOffLight: 256,
7607
+ dimmableLight: 257,
7608
+ onOffPlugInUnit: 266,
7609
+ dimmablePlugInUnit: 267,
7610
+ colorTemperatureLight: 268,
7611
+ extendedColorLight: 269,
7612
+ mountedDimmableLoadControl: 272
7613
+ };
7614
+ /** The Descriptor's attributes. */
7615
+ const DESCRIPTOR = {
7616
+ deviceTypeList: 0,
7617
+ serverList: 1,
7618
+ partsList: 3
7619
+ };
7620
+ /**
7621
+ * The key of one attribute.
7622
+ *
7623
+ * @param endpoint - The endpoint.
7624
+ * @param cluster - The cluster.
7625
+ * @param attribute - The attribute.
7626
+ * @returns `<endpoint>/<cluster>/<attribute>`.
7627
+ */
7628
+ function attributePath(endpoint, cluster, attribute) {
7629
+ return `${String(endpoint)}/${String(cluster)}/${String(attribute)}`;
7630
+ }
7631
+ /**
7632
+ * Reads one attribute.
7633
+ *
7634
+ * @param attributes - The node's.
7635
+ * @param endpoint - The endpoint.
7636
+ * @param cluster - The cluster.
7637
+ * @param attribute - The attribute.
7638
+ * @returns Its value, or undefined when the node has none there.
7639
+ */
7640
+ function attributeOf(attributes, endpoint, cluster, attribute) {
7641
+ return attributes[attributePath(endpoint, cluster, attribute)];
7642
+ }
7643
+ /**
7644
+ * Splits an attribute's key.
7645
+ *
7646
+ * @param path - `<endpoint>/<cluster>/<attribute>`.
7647
+ * @returns Its three numbers, or undefined for a key of another shape.
7648
+ */
7649
+ function splitPath(path) {
7650
+ const [endpoint, cluster, attribute, rest] = path.split("/").map(Number);
7651
+ return rest === void 0 && Number.isInteger(endpoint) && Number.isInteger(cluster) && Number.isInteger(attribute) ? {
7652
+ endpoint: endpoint ?? 0,
7653
+ cluster: cluster ?? 0,
7654
+ attribute: attribute ?? 0
7655
+ } : void 0;
7656
+ }
7657
+ /**
7658
+ * The numbers in a list attribute.
7659
+ *
7660
+ * @param value - The attribute.
7661
+ * @returns Its numbers; none for anything that is not a list of numbers.
7662
+ */
7663
+ function numbersOf(value) {
7664
+ return Array.isArray(value) ? value.filter((item) => typeof item === "number") : [];
7665
+ }
7666
+ /**
7667
+ * The device types an endpoint declares.
7668
+ *
7669
+ * @param attributes - The node's.
7670
+ * @param endpoint - The endpoint.
7671
+ * @returns Their numbers.
7672
+ */
7673
+ function deviceTypesOf(attributes, endpoint) {
7674
+ const list = attributeOf(attributes, endpoint, CLUSTER.descriptor, DESCRIPTOR.deviceTypeList);
7675
+ return Array.isArray(list) ? list.flatMap((entry) => {
7676
+ const type = entry?.["0"];
7677
+ return typeof type === "number" ? [type] : [];
7678
+ }) : [];
7679
+ }
7680
+ /**
7681
+ * The clusters an endpoint serves.
7682
+ *
7683
+ * @param attributes - The node's.
7684
+ * @param endpoint - The endpoint.
7685
+ * @returns Their numbers, from its Descriptor's server list - or, when that was not read, from the
7686
+ * clusters it has attributes of.
7687
+ */
7688
+ function clustersOf(attributes, endpoint) {
7689
+ const listed = numbersOf(attributeOf(attributes, endpoint, CLUSTER.descriptor, DESCRIPTOR.serverList));
7690
+ if (listed.length > 0) return listed;
7691
+ const found = /* @__PURE__ */ new Set();
7692
+ for (const path of Object.keys(attributes)) {
7693
+ const split = splitPath(path);
7694
+ if (split?.endpoint === endpoint) found.add(split.cluster);
7695
+ }
7696
+ return [...found];
7697
+ }
7698
+ /**
7699
+ * Whether an endpoint serves a cluster.
7700
+ *
7701
+ * @param attributes - The node's.
7702
+ * @param endpoint - The endpoint.
7703
+ * @param cluster - The cluster.
7704
+ * @returns True when it does.
7705
+ */
7706
+ function serves(attributes, endpoint, cluster) {
7707
+ return clustersOf(attributes, endpoint).includes(cluster);
7708
+ }
7709
+ /**
7710
+ * The key the transport and the driver agree a device is reached by.
7711
+ *
7712
+ * @param nodeId - The node.
7713
+ * @param endpoint - The bridged endpoint, or null for the node itself.
7714
+ * @returns `<node>` or `<node>:<endpoint>`.
7715
+ */
7716
+ function matterDeviceKey(nodeId, endpoint) {
7717
+ return endpoint === null ? nodeId : `${nodeId}:${String(endpoint)}`;
7718
+ }
7719
+ /**
7720
+ * The name a device of a node is offered under.
7721
+ *
7722
+ * @param identity - Who it says it is.
7723
+ * @returns What the owner named it in the app it came from, then what it is sold as.
7724
+ */
7725
+ function nameOf$1(identity) {
7726
+ return identity.nodeLabel ?? identity.productLabel ?? identity.productName ?? `Matter device ${identity.endpoint === null ? identity.nodeId : `${identity.nodeId}:${String(identity.endpoint)}`}`;
7727
+ }
7728
+ //#endregion
7729
+ //#region ../package-runtime/dist/matter-mapping.js
7730
+ /**
7731
+ * The platform's mapping of a Matter device onto entities: the one driver every Matter device can
7732
+ * be run by, whoever's integration it is.
7733
+ *
7734
+ * Matter describes itself - device types and clusters on numbered endpoints - so one mapping
7735
+ * covers what any maker ships, and a vendor whose `driver.json` says `"kind": "matter"` gets it
7736
+ * without writing code: its devices are its own, on its page, and mapped here.
7737
+ *
7738
+ * **What is mapped.** Per endpoint: on/off, level and colour (hue and saturation, temperature) as
7739
+ * a light or a switch; a window covering; a door lock; a thermostat; temperature, humidity,
7740
+ * illuminance, pressure and CO₂; occupancy, contact and leak; the battery; power, voltage, current
7741
+ * and energy; and, for the node itself, its firmware. What else a device serves is listed on the
7742
+ * Brokers page as not mapped.
7743
+ *
7744
+ * **Pure throughout**, like every integration: what the transport hands over is the device's
7745
+ * whole attribute record and the paths that changed, so a state is always computed from every
7746
+ * field it needs - a colour's hue with its saturation, a thermostat's setpoint with its mode.
7747
+ */
7748
+ /** The global attribute every cluster carries its features in. */
7749
+ const FEATURE_MAP = 65532;
7750
+ /** How long a lock is given to answer a timed command. */
7751
+ const TIMED_COMMAND_MS = 1e4;
7752
+ CLUSTER.onOff, CLUSTER.levelControl, CLUSTER.colorControl, CLUSTER.windowCovering, CLUSTER.doorLock, CLUSTER.thermostat, CLUSTER.temperatureMeasurement, CLUSTER.relativeHumidityMeasurement, CLUSTER.illuminanceMeasurement, CLUSTER.pressureMeasurement, CLUSTER.carbonDioxideMeasurement, CLUSTER.occupancySensing, CLUSTER.booleanState, CLUSTER.powerSource, CLUSTER.electricalPowerMeasurement, CLUSTER.electricalEnergyMeasurement, CLUSTER.otaRequestor;
7753
+ /**
7754
+ * A number attribute.
7755
+ *
7756
+ * @param value - The attribute.
7757
+ * @returns It, or undefined when it is not a finite number - null included.
7758
+ */
7759
+ function numberOf(value) {
7760
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
7761
+ }
7762
+ /**
7763
+ * A value held to a range.
7764
+ *
7765
+ * @param value - The value.
7766
+ * @param min - The least.
7767
+ * @param max - The most.
7768
+ * @returns It, within the range.
7769
+ */
7770
+ function clamp(value, min, max) {
7771
+ return Math.min(max, Math.max(min, value));
7772
+ }
7773
+ /**
7774
+ * A fade in Matter's tenths of a second.
7775
+ *
7776
+ * @param transitionMs - The fade the command asks for, if any.
7777
+ * @returns Tenths of a second; 0 for at once.
7778
+ */
7779
+ function tenthsOf(transitionMs) {
7780
+ return typeof transitionMs === "number" ? Math.round(transitionMs / 100) : 0;
7781
+ }
7782
+ /**
7783
+ * A command invoked on a cluster.
7784
+ *
7785
+ * @param endpoint - The endpoint.
7786
+ * @param cluster - The cluster.
7787
+ * @param command - The command, as matter.js names it.
7788
+ * @param payload - Its fields.
7789
+ * @param timedMs - How long a timed command is given, for one that must be timed.
7790
+ * @returns The request.
7791
+ */
7792
+ function invoke(endpoint, cluster, command, payload = {}, timedMs) {
7793
+ return {
7794
+ op: "invoke",
7795
+ args: {
7796
+ endpoint,
7797
+ cluster,
7798
+ command,
7799
+ payload,
7800
+ ...timedMs === void 0 ? {} : { timedMs }
7801
+ }
7802
+ };
7803
+ }
7804
+ /** What every fade-capable command of the lighting clusters carries besides its own fields. */
7805
+ const NO_OPTIONS = {
7806
+ optionsMask: 0,
7807
+ optionsOverride: 0
7808
+ };
7809
+ /**
7810
+ * The light, or switch, an endpoint with On/Off is.
7811
+ *
7812
+ * @param attributes - The device's.
7813
+ * @param endpoint - The endpoint.
7814
+ * @returns The entity.
7815
+ */
7816
+ function onOffEntity(attributes, endpoint) {
7817
+ const types = deviceTypesOf(attributes, endpoint);
7818
+ const isLight = [
7819
+ DEVICE_TYPE.onOffLight,
7820
+ DEVICE_TYPE.dimmableLight,
7821
+ DEVICE_TYPE.colorTemperatureLight,
7822
+ DEVICE_TYPE.extendedColorLight,
7823
+ DEVICE_TYPE.dimmablePlugInUnit,
7824
+ DEVICE_TYPE.mountedDimmableLoadControl
7825
+ ].some((type) => types.includes(type));
7826
+ const hasLevel = isLight && serves(attributes, endpoint, CLUSTER.levelControl);
7827
+ const colorFeatures = serves(attributes, endpoint, CLUSTER.colorControl) ? numberOf(attributeOf(attributes, endpoint, CLUSTER.colorControl, FEATURE_MAP)) ?? 0 : 0;
7828
+ const hasHs = isLight && (colorFeatures & 1) !== 0;
7829
+ const hasTemperature = isLight && (colorFeatures & 16) !== 0;
7830
+ const minMireds = clamp(numberOf(attributeOf(attributes, endpoint, CLUSTER.colorControl, 16395)) ?? 153, 1, 1e3);
7831
+ const maxMireds = clamp(numberOf(attributeOf(attributes, endpoint, CLUSTER.colorControl, 16396)) ?? 500, minMireds, 1e3);
7832
+ const capabilities = {
7833
+ on_off: { hasTransition: false },
7834
+ ...hasLevel ? { level: { hasTransition: true } } : {},
7835
+ ...hasHs ? { color_hs: { hasTransition: true } } : {},
7836
+ ...hasTemperature ? { color_temp: {
7837
+ minMireds,
7838
+ maxMireds,
7839
+ hasTransition: true
7840
+ } } : {}
7841
+ };
7842
+ return {
7843
+ key: isLight ? "light" : "switch",
7844
+ endpoint,
7845
+ clusters: [
7846
+ CLUSTER.onOff,
7847
+ CLUSTER.levelControl,
7848
+ CLUSTER.colorControl
7849
+ ],
7850
+ descriptor: {
7851
+ domain: isLight ? "light" : "switch",
7852
+ name: isLight ? "Light" : "Switch",
7853
+ capabilities
7854
+ },
7855
+ /**
7856
+ * Reads the entity's state.
7857
+ *
7858
+ * @param read - The device's attributes.
7859
+ * @returns The state, or undefined while the device has not said enough.
7860
+ */
7861
+ stateOf: (read) => {
7862
+ const isOn = attributeOf(read, endpoint, CLUSTER.onOff, 0);
7863
+ if (typeof isOn !== "boolean") return;
7864
+ const level = numberOf(attributeOf(read, endpoint, CLUSTER.levelControl, 0));
7865
+ const hue = numberOf(attributeOf(read, endpoint, CLUSTER.colorControl, 0));
7866
+ const saturation = numberOf(attributeOf(read, endpoint, CLUSTER.colorControl, 1));
7867
+ const mireds = numberOf(attributeOf(read, endpoint, CLUSTER.colorControl, 7));
7868
+ return {
7869
+ on_off: { isOn },
7870
+ ...hasLevel && level !== void 0 ? { level: { level: clamp(Math.round(level / 254 * 100), 0, 100) } } : {},
7871
+ ...hasHs && hue !== void 0 && saturation !== void 0 ? { color_hs: {
7872
+ hue: clamp(Math.round(hue / 254 * 360), 0, 360),
7873
+ saturation: clamp(Math.round(saturation / 254 * 100), 0, 100)
7874
+ } } : {},
7875
+ ...hasTemperature && mireds !== void 0 ? { color_temp: { mireds: clamp(Math.round(mireds), 1, 1e3) } } : {}
7876
+ };
7877
+ },
7878
+ /**
7879
+ * Turns a command into a request.
7880
+ *
7881
+ * @param target - The command.
7882
+ * @returns The request, or undefined for a command it does not take.
7883
+ */
7884
+ commandOf: (target) => {
7885
+ const { command } = target;
7886
+ switch (command["command"]) {
7887
+ case "turn_on": return invoke(endpoint, CLUSTER.onOff, "on");
7888
+ case "turn_off": return invoke(endpoint, CLUSTER.onOff, "off");
7889
+ case "toggle": return invoke(endpoint, CLUSTER.onOff, "toggle");
7890
+ case "set_level": {
7891
+ const level = numberOf(command["level"]) ?? 0;
7892
+ return level <= 0 ? invoke(endpoint, CLUSTER.onOff, "off") : invoke(endpoint, CLUSTER.levelControl, "moveToLevelWithOnOff", {
7893
+ level: clamp(Math.round(level / 100 * 254), 1, 254),
7894
+ transitionTime: tenthsOf(command["transitionMs"]),
7895
+ ...NO_OPTIONS
7896
+ });
7897
+ }
7898
+ case "set_color": return invoke(endpoint, CLUSTER.colorControl, "moveToHueAndSaturation", {
7899
+ hue: clamp(Math.round((numberOf(command["hue"]) ?? 0) / 360 * 254), 0, 254),
7900
+ saturation: clamp(Math.round((numberOf(command["saturation"]) ?? 0) / 100 * 254), 0, 254),
7901
+ transitionTime: tenthsOf(command["transitionMs"]),
7902
+ ...NO_OPTIONS
7903
+ });
7904
+ case "set_color_temp": return invoke(endpoint, CLUSTER.colorControl, "moveToColorTemperature", {
7905
+ colorTemperatureMireds: clamp(Math.round(numberOf(command["mireds"]) ?? minMireds), minMireds, maxMireds),
7906
+ transitionTime: tenthsOf(command["transitionMs"]),
7907
+ ...NO_OPTIONS
7908
+ });
7909
+ default: return;
7910
+ }
7911
+ }
7912
+ };
7913
+ }
7914
+ /**
7915
+ * The cover a Window Covering endpoint is. Matter counts how far it is closed, in hundredths of a
7916
+ * percent; the platform counts how far it is open.
7917
+ *
7918
+ * @param attributes - The device's.
7919
+ * @param endpoint - The endpoint.
7920
+ * @returns The entity.
7921
+ */
7922
+ function coverEntity(attributes, endpoint) {
7923
+ const features = numberOf(attributeOf(attributes, endpoint, CLUSTER.windowCovering, FEATURE_MAP)) ?? 0;
7924
+ const hasPosition = (features & 4) !== 0;
7925
+ const hasTilt = (features & 2) !== 0 && (features & 16) !== 0;
7926
+ /**
7927
+ * How far open, from how far closed.
7928
+ *
7929
+ * @param closed - Hundredths of a percent closed.
7930
+ * @returns The percentage open.
7931
+ */
7932
+ const openOf = (closed) => clamp(Math.round(100 - closed / 100), 0, 100);
7933
+ return {
7934
+ key: "cover",
7935
+ endpoint,
7936
+ clusters: [CLUSTER.windowCovering],
7937
+ descriptor: {
7938
+ domain: "cover",
7939
+ name: "Cover",
7940
+ capabilities: { cover: {
7941
+ hasPosition,
7942
+ hasTilt
7943
+ } }
7944
+ },
7945
+ /**
7946
+ * Reads the entity's state.
7947
+ *
7948
+ * @param read - The device's attributes.
7949
+ * @returns The state, or undefined while the device has not said enough.
7950
+ */
7951
+ stateOf: (read) => {
7952
+ const closed = numberOf(attributeOf(read, endpoint, CLUSTER.windowCovering, 14));
7953
+ const tilt = numberOf(attributeOf(read, endpoint, CLUSTER.windowCovering, 15));
7954
+ const status = (numberOf(attributeOf(read, endpoint, CLUSTER.windowCovering, 10)) ?? 0) & 3;
7955
+ if (closed === void 0) return;
7956
+ return { cover: {
7957
+ position: openOf(closed),
7958
+ ...hasTilt && tilt !== void 0 ? { tilt: openOf(tilt) } : {},
7959
+ motion: status === 1 ? "opening" : status === 2 ? "closing" : "stopped"
7960
+ } };
7961
+ },
7962
+ /**
7963
+ * Turns a command into a request.
7964
+ *
7965
+ * @param target - The command.
7966
+ * @returns The request, or undefined for a command it does not take.
7967
+ */
7968
+ commandOf: (target) => {
7969
+ const { command } = target;
7970
+ switch (command["command"]) {
7971
+ case "open": return invoke(endpoint, CLUSTER.windowCovering, "upOrOpen");
7972
+ case "close": return invoke(endpoint, CLUSTER.windowCovering, "downOrClose");
7973
+ case "stop": return invoke(endpoint, CLUSTER.windowCovering, "stopMotion");
7974
+ case "set_position": return invoke(endpoint, CLUSTER.windowCovering, "goToLiftPercentage", { liftPercent100thsValue: Math.round((100 - (numberOf(command["position"]) ?? 0)) * 100) });
7975
+ case "set_tilt": return invoke(endpoint, CLUSTER.windowCovering, "goToTiltPercentage", { tiltPercent100thsValue: Math.round((100 - (numberOf(command["tilt"]) ?? 0)) * 100) });
7976
+ default: return;
7977
+ }
7978
+ }
7979
+ };
7980
+ }
7981
+ /**
7982
+ * The lock a Door Lock endpoint is.
7983
+ *
7984
+ * @param endpoint - The endpoint.
7985
+ * @returns The entity.
7986
+ */
7987
+ function lockEntity(endpoint) {
7988
+ return {
7989
+ key: "lock",
7990
+ endpoint,
7991
+ clusters: [CLUSTER.doorLock],
7992
+ descriptor: {
7993
+ domain: "lock",
7994
+ name: "Lock",
7995
+ capabilities: { lock: { hasCode: false } }
7996
+ },
7997
+ /**
7998
+ * Reads the entity's state.
7999
+ *
8000
+ * @param read - The device's attributes.
8001
+ * @returns The state, or undefined while the device has not said enough.
8002
+ */
8003
+ stateOf: (read) => {
8004
+ switch (numberOf(attributeOf(read, endpoint, CLUSTER.doorLock, 0))) {
8005
+ case 0: return { lock: { lockState: "jammed" } };
8006
+ case 1: return { lock: { lockState: "locked" } };
8007
+ case 2:
8008
+ case 3: return { lock: { lockState: "unlocked" } };
8009
+ default: return;
8010
+ }
8011
+ },
8012
+ /**
8013
+ * Turns a command into a request.
8014
+ *
8015
+ * @param target - The command.
8016
+ * @returns The request, or undefined for a command it does not take.
8017
+ */
8018
+ commandOf: (target) => {
8019
+ const { command } = target;
8020
+ switch (command["command"]) {
8021
+ case "lock": return invoke(endpoint, CLUSTER.doorLock, "lockDoor", {}, TIMED_COMMAND_MS);
8022
+ case "unlock": return invoke(endpoint, CLUSTER.doorLock, "unlockDoor", {}, TIMED_COMMAND_MS);
8023
+ default: return;
8024
+ }
8025
+ }
8026
+ };
8027
+ }
8028
+ /** Matter's system modes, as the platform's thermostat modes. */
8029
+ const SYSTEM_MODES = {
8030
+ 0: "off",
8031
+ 1: "auto",
8032
+ 3: "cool",
8033
+ 4: "heat",
8034
+ 5: "heat",
8035
+ 6: "cool",
8036
+ 7: "fan_only",
8037
+ 8: "dry",
8038
+ 9: "auto"
8039
+ };
8040
+ /** The platform's thermostat modes, as the system mode written for each. */
8041
+ const MODE_VALUES = {
8042
+ off: 0,
8043
+ auto: 1,
8044
+ cool: 3,
8045
+ heat: 4,
8046
+ fan_only: 7,
8047
+ dry: 8
8048
+ };
8049
+ /**
8050
+ * The thermostat a Thermostat endpoint is, its humidity beside it when the endpoint measures it.
8051
+ *
8052
+ * @param attributes - The device's.
8053
+ * @param endpoint - The endpoint.
8054
+ * @returns The entity.
8055
+ */
8056
+ function thermostatEntity(attributes, endpoint) {
8057
+ const features = numberOf(attributeOf(attributes, endpoint, CLUSTER.thermostat, FEATURE_MAP)) ?? 1;
8058
+ const canHeat = (features & 1) !== 0;
8059
+ const canCool = (features & 2) !== 0;
8060
+ const hasAuto = (features & 32) !== 0;
8061
+ /**
8062
+ * A temperature attribute, in degrees.
8063
+ *
8064
+ * @param read - The device's attributes.
8065
+ * @param attribute - The attribute, in hundredths of a degree.
8066
+ * @returns The degrees, or undefined.
8067
+ */
8068
+ const degreesOf = (read, attribute) => {
8069
+ const value = numberOf(attributeOf(read, endpoint, CLUSTER.thermostat, attribute));
8070
+ return value === void 0 ? void 0 : value / 100;
8071
+ };
8072
+ const min = degreesOf(attributes, canHeat ? 21 : 23) ?? 7;
8073
+ const max = degreesOf(attributes, canHeat ? 22 : 24) ?? 30;
8074
+ return {
8075
+ key: "thermostat",
8076
+ endpoint,
8077
+ clusters: [CLUSTER.thermostat, CLUSTER.relativeHumidityMeasurement],
8078
+ descriptor: {
8079
+ domain: "climate",
8080
+ name: "Thermostat",
8081
+ capabilities: { thermostat: {
8082
+ supportedModes: [
8083
+ "off",
8084
+ ...canHeat ? ["heat"] : [],
8085
+ ...canCool ? ["cool"] : [],
8086
+ ...hasAuto ? ["auto"] : []
8087
+ ],
8088
+ minTemperature: Math.min(min, max),
8089
+ maxTemperature: Math.max(min, max),
8090
+ temperatureStep: .5
8091
+ } }
8092
+ },
8093
+ /**
8094
+ * Reads the entity's state.
8095
+ *
8096
+ * @param read - The device's attributes.
8097
+ * @returns The state, or undefined while the device has not said enough.
8098
+ */
8099
+ stateOf: (read) => {
8100
+ const current = degreesOf(read, 0);
8101
+ const mode = SYSTEM_MODES[numberOf(attributeOf(read, endpoint, CLUSTER.thermostat, 28)) ?? 0];
8102
+ const target = degreesOf(read, mode === "cool" ? 17 : 18) ?? degreesOf(read, 17);
8103
+ const running = numberOf(attributeOf(read, endpoint, CLUSTER.thermostat, 41)) ?? 0;
8104
+ const humidity = numberOf(attributeOf(read, endpoint, CLUSTER.relativeHumidityMeasurement, 0));
8105
+ if (current === void 0 || target === void 0 || mode === void 0) return;
8106
+ return { thermostat: {
8107
+ currentTemperature: current,
8108
+ targetTemperature: target,
8109
+ mode,
8110
+ action: mode === "off" ? "off" : (running & 9) !== 0 ? "heating" : (running & 18) !== 0 ? "cooling" : (running & 100) !== 0 ? "fan" : "idle",
8111
+ ...humidity === void 0 ? {} : { humidity: clamp(humidity / 100, 0, 100) }
8112
+ } };
8113
+ },
8114
+ /**
8115
+ * Turns a command into a request.
8116
+ *
8117
+ * @param target - The command.
8118
+ * @param last - The entity's last state.
8119
+ * @returns The request, or undefined for a command it does not take.
8120
+ */
8121
+ commandOf: (target, last) => {
8122
+ const { command } = target;
8123
+ if (command["command"] === "set_target") {
8124
+ const isCooling = last?.thermostat?.mode === "cool" || !canHeat;
8125
+ return {
8126
+ op: "write",
8127
+ args: {
8128
+ endpoint,
8129
+ cluster: CLUSTER.thermostat,
8130
+ attribute: isCooling ? 17 : 18,
8131
+ value: Math.round((numberOf(command["temperature"]) ?? 0) * 100)
8132
+ }
8133
+ };
8134
+ }
8135
+ const mode = command["mode"];
8136
+ const value = command["command"] === "set_mode" && typeof mode === "string" && mode in MODE_VALUES ? MODE_VALUES[mode] : void 0;
8137
+ return value === void 0 ? void 0 : {
8138
+ op: "write",
8139
+ args: {
8140
+ endpoint,
8141
+ cluster: CLUSTER.thermostat,
8142
+ attribute: 28,
8143
+ value
8144
+ }
8145
+ };
8146
+ }
8147
+ };
8148
+ }
8149
+ /**
8150
+ * Hundredths, as a number.
8151
+ *
8152
+ * @param value - The attribute.
8153
+ * @returns It divided by 100.
8154
+ */
8155
+ function hundredths(value) {
8156
+ const number = numberOf(value);
8157
+ return number === void 0 ? void 0 : number / 100;
8158
+ }
8159
+ /** The sensors read as one value of one attribute. */
8160
+ const NUMERIC_SENSORS = [
8161
+ {
8162
+ key: "temperature",
8163
+ name: "Temperature",
8164
+ cluster: CLUSTER.temperatureMeasurement,
8165
+ attribute: 0,
8166
+ deviceClass: "temperature",
8167
+ unit: "°C",
8168
+ displayPrecision: 1,
8169
+ scale: hundredths
8170
+ },
8171
+ {
8172
+ key: "humidity",
8173
+ name: "Humidity",
8174
+ cluster: CLUSTER.relativeHumidityMeasurement,
8175
+ attribute: 0,
8176
+ deviceClass: "humidity",
8177
+ unit: "%",
8178
+ displayPrecision: 0,
8179
+ scale: hundredths
8180
+ },
8181
+ {
8182
+ key: "illuminance",
8183
+ name: "Illuminance",
8184
+ cluster: CLUSTER.illuminanceMeasurement,
8185
+ attribute: 0,
8186
+ deviceClass: "illuminance",
8187
+ unit: "lx",
8188
+ displayPrecision: 0,
8189
+ /**
8190
+ * Reads the attribute.
8191
+ *
8192
+ * @param value - The attribute.
8193
+ * @returns The number, or undefined.
8194
+ */
8195
+ scale: (value) => {
8196
+ const measured = numberOf(value);
8197
+ return measured === void 0 ? void 0 : measured === 0 ? 0 : 10 ** ((measured - 1) / 1e4);
8198
+ }
8199
+ },
8200
+ {
8201
+ key: "pressure",
8202
+ name: "Pressure",
8203
+ cluster: CLUSTER.pressureMeasurement,
8204
+ attribute: 0,
8205
+ deviceClass: "atmospheric_pressure",
8206
+ unit: "hPa",
8207
+ displayPrecision: 0,
8208
+ scale: numberOf
8209
+ },
8210
+ {
8211
+ key: "carbon_dioxide",
8212
+ name: "Carbon dioxide",
8213
+ cluster: CLUSTER.carbonDioxideMeasurement,
8214
+ attribute: 0,
8215
+ deviceClass: "carbon_dioxide",
8216
+ unit: "ppm",
8217
+ displayPrecision: 0,
8218
+ scale: numberOf
8219
+ },
8220
+ {
8221
+ key: "battery",
8222
+ name: "Battery",
8223
+ cluster: CLUSTER.powerSource,
8224
+ attribute: 12,
8225
+ deviceClass: "battery",
8226
+ unit: "%",
8227
+ displayPrecision: 0,
8228
+ /**
8229
+ * Reads the attribute.
8230
+ *
8231
+ * @param value - The attribute.
8232
+ * @returns The number, or undefined.
8233
+ */
8234
+ scale: (value) => {
8235
+ const halves = numberOf(value);
8236
+ return halves === void 0 ? void 0 : clamp(halves / 2, 0, 100);
8237
+ }
8238
+ },
8239
+ {
8240
+ key: "power",
8241
+ name: "Power",
8242
+ cluster: CLUSTER.electricalPowerMeasurement,
8243
+ attribute: 8,
8244
+ deviceClass: "power",
8245
+ unit: "mW",
8246
+ displayPrecision: 1,
8247
+ scale: numberOf
8248
+ },
8249
+ {
8250
+ key: "voltage",
8251
+ name: "Voltage",
8252
+ cluster: CLUSTER.electricalPowerMeasurement,
8253
+ attribute: 4,
8254
+ deviceClass: "voltage",
8255
+ unit: "mV",
8256
+ displayPrecision: 1,
8257
+ scale: numberOf
8258
+ },
8259
+ {
8260
+ key: "current",
8261
+ name: "Current",
8262
+ cluster: CLUSTER.electricalPowerMeasurement,
8263
+ attribute: 5,
8264
+ deviceClass: "current",
8265
+ unit: "mA",
8266
+ displayPrecision: 2,
8267
+ scale: numberOf
8268
+ },
8269
+ {
8270
+ key: "energy",
8271
+ name: "Energy",
8272
+ cluster: CLUSTER.electricalEnergyMeasurement,
8273
+ attribute: 1,
8274
+ deviceClass: "energy",
8275
+ unit: "mWh",
8276
+ stateClass: "total_increasing",
8277
+ displayPrecision: 2,
8278
+ /**
8279
+ * Reads the attribute.
8280
+ *
8281
+ * @param value - The attribute.
8282
+ * @returns The number, or undefined.
8283
+ */
8284
+ scale: (value) => numberOf(value?.["0"])
8285
+ }
8286
+ ];
8287
+ /**
8288
+ * A numeric sensor of one endpoint.
8289
+ *
8290
+ * @param sensor - Which.
8291
+ * @param endpoint - The endpoint.
8292
+ * @returns The entity, reporting in the class's canonical unit.
8293
+ */
8294
+ function numericEntity(sensor, endpoint) {
8295
+ const unitOfMeasurement = resolveCanonicalUnit(sensor.deviceClass) ?? sensor.unit;
8296
+ const stateClass = resolveStateClass(sensor.deviceClass, sensor.stateClass);
8297
+ return {
8298
+ key: sensor.key,
8299
+ endpoint,
8300
+ clusters: [sensor.cluster],
8301
+ attribute: sensor.attribute,
8302
+ descriptor: {
8303
+ domain: "sensor",
8304
+ name: sensor.name,
8305
+ capabilities: { sensor_numeric: {} },
8306
+ unitOfMeasurement,
8307
+ deviceClass: sensor.deviceClass,
8308
+ ...stateClass === void 0 ? {} : { stateClass },
8309
+ ...sensor.displayPrecision === void 0 ? {} : { displayPrecision: sensor.displayPrecision }
8310
+ },
8311
+ /**
8312
+ * Reads the entity's state.
8313
+ *
8314
+ * @param read - The device's attributes.
8315
+ * @returns The state, or undefined while the device has not said enough.
8316
+ */
8317
+ stateOf: (read) => {
8318
+ const value = sensor.scale(attributeOf(read, endpoint, sensor.cluster, sensor.attribute));
8319
+ const canonical = value === void 0 ? void 0 : toCanonical(sensor.deviceClass, value, sensor.unit);
8320
+ return canonical === void 0 ? void 0 : { sensor_numeric: { value: canonical } };
8321
+ }
8322
+ };
8323
+ }
8324
+ /**
8325
+ * A binary sensor of one endpoint.
8326
+ *
8327
+ * @param endpoint - The endpoint.
8328
+ * @param spec - What it is.
8329
+ * @param spec.key - Its kind.
8330
+ * @param spec.name - Its name.
8331
+ * @param spec.icon - Its icon.
8332
+ * @param spec.cluster - The cluster it reads.
8333
+ * @param spec.isOn - How the attribute reads as on.
8334
+ * @returns The entity.
8335
+ */
8336
+ function binaryEntity(endpoint, spec) {
8337
+ return {
8338
+ key: spec.key,
8339
+ endpoint,
8340
+ clusters: [spec.cluster],
8341
+ descriptor: {
8342
+ domain: "binary_sensor",
8343
+ name: spec.name,
8344
+ icon: spec.icon,
8345
+ capabilities: { sensor_binary: {} }
8346
+ },
8347
+ /**
8348
+ * Reads the entity's state.
8349
+ *
8350
+ * @param read - The device's attributes.
8351
+ * @returns The state, or undefined while the device has not said enough.
8352
+ */
8353
+ stateOf: (read) => {
8354
+ const isOn = spec.isOn(attributeOf(read, endpoint, spec.cluster, 0));
8355
+ return isOn === void 0 ? void 0 : { sensor_binary: { isOn } };
8356
+ }
8357
+ };
8358
+ }
8359
+ /**
8360
+ * A boolean, as it is.
8361
+ *
8362
+ * @param value - The attribute.
8363
+ * @returns It, or undefined when it is not one.
8364
+ */
8365
+ function booleanOf(value) {
8366
+ return typeof value === "boolean" ? value : void 0;
8367
+ }
8368
+ /**
8369
+ * The firmware of the node itself.
8370
+ *
8371
+ * @returns The entity, reading what the node runs, what is on offer and how an install goes.
8372
+ */
8373
+ function firmwareEntity() {
8374
+ return {
8375
+ key: "firmware",
8376
+ endpoint: 0,
8377
+ clusters: [CLUSTER.basicInformation, CLUSTER.otaRequestor],
8378
+ descriptor: {
8379
+ domain: "update",
8380
+ name: "Firmware",
8381
+ capabilities: { update: {
8382
+ canInstall: true,
8383
+ hasProgress: true
8384
+ } }
8385
+ },
8386
+ /**
8387
+ * Reads the entity's state.
8388
+ *
8389
+ * @param read - The device's attributes.
8390
+ * @param update - The firmware on offer.
8391
+ * @returns The state.
8392
+ */
8393
+ stateOf: (read, update) => {
8394
+ const text = attributeOf(read, 0, CLUSTER.basicInformation, 10);
8395
+ const number = numberOf(attributeOf(read, 0, CLUSTER.basicInformation, 9));
8396
+ const installed = typeof text === "string" && text !== "" ? text : number === void 0 ? null : String(number);
8397
+ const updating = numberOf(attributeOf(read, 0, CLUSTER.otaRequestor, 2));
8398
+ const progress = numberOf(attributeOf(read, 0, CLUSTER.otaRequestor, 3));
8399
+ const isInstalling = updating === 4 || updating === 5;
8400
+ return { update: {
8401
+ installedVersion: installed?.slice(0, 64) ?? null,
8402
+ latestVersion: update?.softwareVersionString.slice(0, 64) ?? null,
8403
+ isInstalling,
8404
+ progress: isInstalling && progress !== void 0 ? clamp(progress, 0, 100) : null
8405
+ } };
8406
+ },
8407
+ /**
8408
+ * Turns a command into a request.
8409
+ *
8410
+ * @param target - The command.
8411
+ * @returns The request, or undefined for a command it does not take.
8412
+ */
8413
+ commandOf: (target) => target.command["command"] === "install" ? {
8414
+ op: "update",
8415
+ args: {}
8416
+ } : void 0
8417
+ };
8418
+ }
8419
+ /**
8420
+ * The entities one endpoint serves.
8421
+ *
8422
+ * @param attributes - The device's.
8423
+ * @param endpoint - The endpoint.
8424
+ * @returns Its entities, before their object ids are settled.
8425
+ */
8426
+ function draftsOf(attributes, endpoint) {
8427
+ /**
8428
+ * Whether the endpoint serves a cluster.
8429
+ *
8430
+ * @param cluster - The cluster.
8431
+ * @returns True when it does.
8432
+ */
8433
+ const has = (cluster) => serves(attributes, endpoint, cluster);
8434
+ const types = deviceTypesOf(attributes, endpoint);
8435
+ const drafts = [];
8436
+ if (has(CLUSTER.onOff)) drafts.push(onOffEntity(attributes, endpoint));
8437
+ if (has(CLUSTER.windowCovering)) drafts.push(coverEntity(attributes, endpoint));
8438
+ if (has(CLUSTER.doorLock)) drafts.push(lockEntity(endpoint));
8439
+ const hasThermostat = has(CLUSTER.thermostat);
8440
+ if (hasThermostat) drafts.push(thermostatEntity(attributes, endpoint));
8441
+ for (const sensor of NUMERIC_SENSORS) {
8442
+ const isThermostatHumidity = hasThermostat && sensor.cluster === CLUSTER.relativeHumidityMeasurement;
8443
+ if (has(sensor.cluster) && !isThermostatHumidity && attributeOf(attributes, endpoint, sensor.cluster, sensor.attribute) !== void 0) drafts.push(numericEntity(sensor, endpoint));
8444
+ }
8445
+ if (has(CLUSTER.occupancySensing)) drafts.push(binaryEntity(endpoint, {
8446
+ key: "motion",
8447
+ name: "Motion",
8448
+ icon: "motion",
8449
+ cluster: CLUSTER.occupancySensing,
8450
+ /**
8451
+ * Reads the attribute as on or off.
8452
+ *
8453
+ * @param value - The attribute.
8454
+ * @returns Whether it is on, or undefined.
8455
+ */
8456
+ isOn: (value) => {
8457
+ const bits = numberOf(value);
8458
+ return bits === void 0 ? void 0 : (bits & 1) !== 0;
8459
+ }
8460
+ }));
8461
+ if (has(CLUSTER.booleanState)) {
8462
+ const isContact = types.includes(DEVICE_TYPE.contactSensor);
8463
+ const isLeak = types.includes(DEVICE_TYPE.waterLeakDetector);
8464
+ drafts.push(binaryEntity(endpoint, {
8465
+ key: isContact ? "contact" : isLeak ? "leak" : "state",
8466
+ name: isContact ? "Contact" : isLeak ? "Leak" : "State",
8467
+ icon: isContact ? "door" : isLeak ? "water" : "sensor",
8468
+ cluster: CLUSTER.booleanState,
8469
+ /**
8470
+ * Reads the attribute as on or off.
8471
+ *
8472
+ * @param value - The attribute.
8473
+ * @returns Whether it is on, or undefined.
8474
+ */
8475
+ isOn: (value) => {
8476
+ const state = booleanOf(value);
8477
+ return state === void 0 ? void 0 : isContact ? !state : state;
8478
+ }
8479
+ }));
8480
+ }
8481
+ return drafts;
8482
+ }
8483
+ /**
8484
+ * The entities of one device of a node.
8485
+ *
8486
+ * Object ids are the entity's kind - `light`, `temperature` - with the endpoint's number after it
8487
+ * when the kind is on more than one endpoint: `switch_1`, `switch_2`. They follow from the device's
8488
+ * structure alone, so they are the same at every start.
8489
+ *
8490
+ * @param device - The device.
8491
+ * @returns Its entities.
8492
+ */
8493
+ function matterEntitiesOf(device) {
8494
+ const drafts = device.endpoints.flatMap((endpoint) => draftsOf(device.attributes, endpoint));
8495
+ if (device.endpoint === null && serves(device.attributes, 0, CLUSTER.otaRequestor)) drafts.push(firmwareEntity());
8496
+ const counts = /* @__PURE__ */ new Map();
8497
+ for (const draft of drafts) counts.set(draft.key, (counts.get(draft.key) ?? 0) + 1);
8498
+ return drafts.map(({ key, descriptor, ...rest }) => {
8499
+ const isShared = (counts.get(key) ?? 0) > 1;
8500
+ const objectId = isShared ? `${key}_${String(rest.endpoint)}` : key;
8501
+ return {
8502
+ ...rest,
8503
+ objectId,
8504
+ descriptor: {
8505
+ ...descriptor,
8506
+ objectId,
8507
+ name: isShared ? `${descriptor.name} ${String(rest.endpoint)}` : descriptor.name
8508
+ }
8509
+ };
8510
+ });
8511
+ }
8512
+ /** Reads a device handed over by the transport, refusing anything else. */
8513
+ const deviceSnapshotSchema = z.object({
8514
+ nodeId: z.string().min(1),
8515
+ endpoint: z.int().min(0).nullable(),
8516
+ endpoints: z.array(z.int().min(0)),
8517
+ isAvailable: z.boolean(),
8518
+ identity: matterIdentitySchema,
8519
+ attributes: z.record(z.string(), z.unknown())
8520
+ });
8521
+ /** Reads what the transport delivers. */
8522
+ const inboundSchema = z.object({
8523
+ device: deviceSnapshotSchema,
8524
+ changed: z.array(z.string()).nullable(),
8525
+ update: z.object({
8526
+ softwareVersion: z.number(),
8527
+ softwareVersionString: z.string()
8528
+ }).nullable().optional()
8529
+ });
8530
+ /**
8531
+ * A device, read from what identification or a claim holds.
8532
+ *
8533
+ * @param value - What it holds.
8534
+ * @returns The device, or undefined when it is not one.
8535
+ */
8536
+ function deviceOf(value) {
8537
+ const parsed = deviceSnapshotSchema.safeParse(value);
8538
+ return parsed.success ? parsed.data : void 0;
8539
+ }
8540
+ /**
8541
+ * Whether an entity is computed from one of the paths that changed.
8542
+ *
8543
+ * @param entity - The entity.
8544
+ * @param changed - The paths, or null for everything.
8545
+ * @returns True when it should be read again.
8546
+ */
8547
+ function isTouched(entity, changed) {
8548
+ return changed === null || changed.some((path) => {
8549
+ const split = splitPath(path);
8550
+ return split?.endpoint === entity.endpoint && entity.clusters.includes(split.cluster) && (entity.attribute === void 0 || split.attribute === entity.attribute);
8551
+ });
8552
+ }
8553
+ /**
8554
+ * Builds the Matter driver of a vendor: the platform's own, or one whose `driver.json` says
8555
+ * `"kind": "matter"`.
8556
+ *
8557
+ * @param manifest - The driver's.
8558
+ * @param manifest.id - Its kind, `vendor/driver`.
8559
+ * @returns The integration.
8560
+ */
8561
+ function createMatterIntegration(manifest) {
8562
+ /**
8563
+ * The device a claim was made for.
8564
+ *
8565
+ * @param context - The instance's mapping context.
8566
+ * @returns The device.
8567
+ * @throws {ValidationError} When the claim holds no device - which identification never makes.
8568
+ */
8569
+ const claimed = (context) => {
8570
+ const device = deviceOf(context.claim.descriptor);
8571
+ if (device === void 0) throw new ValidationError(`${manifest.id} holds a claim that is not a Matter device`, { details: { integration: manifest.id } });
8572
+ return device;
8573
+ };
8574
+ return {
8575
+ id: manifest.id,
8576
+ transport: MATTER_TRANSPORT,
8577
+ optionsSchema: jsonObjectSchema,
8578
+ discovery: {},
8579
+ /**
8580
+ * Claims a Matter device identification found.
8581
+ *
8582
+ * @param discovered - What the transport handed over.
8583
+ * @returns The claim, or null for anything that is not a Matter device.
8584
+ */
8585
+ claim: (discovered) => {
8586
+ const device = deviceOf(discovered.payload);
8587
+ return device === void 0 ? null : {
8588
+ deviceKey: discovered.deviceKey,
8589
+ externalId: matterDeviceKey(device.nodeId, device.endpoint),
8590
+ descriptor: device
8591
+ };
8592
+ },
8593
+ /**
8594
+ * Subscribes to nothing: the controller already follows every attribute of every node.
8595
+ *
8596
+ * @returns Nothing.
8597
+ */
8598
+ subscriptions: () => [],
8599
+ /**
8600
+ * Describes the device and its entities.
8601
+ *
8602
+ * @param claim - The claim.
8603
+ * @returns The device.
8604
+ * @throws {ValidationError} When the claim holds no Matter device.
8605
+ */
8606
+ describe: (claim) => {
8607
+ const device = deviceOf(claim.descriptor);
8608
+ if (device === void 0) throw new ValidationError(`${manifest.id} cannot describe a claim with no Matter device`, { details: { integration: manifest.id } });
8609
+ const { identity } = device;
8610
+ return {
8611
+ externalId: claim.externalId,
8612
+ name: nameOf$1(identity).slice(0, 128),
8613
+ ...identity.vendorName === null ? {} : { manufacturer: identity.vendorName },
8614
+ ...identity.productName === null ? {} : { model: identity.productName },
8615
+ ...identity.softwareVersionString === null ? {} : { swVersion: identity.softwareVersionString.slice(0, 64) },
8616
+ ...identity.hardwareVersionString === null ? {} : { hwVersion: identity.hardwareVersionString.slice(0, 64) },
8617
+ ...device.endpoint === null ? {} : { viaExternalId: device.nodeId },
8618
+ entities: matterEntitiesOf(device).map((entity) => entity.descriptor)
8619
+ };
8620
+ },
8621
+ /**
8622
+ * Turns what changed into reports, one per entity it is about.
8623
+ *
8624
+ * @param message - What the transport delivered.
8625
+ * @param context - The identifiers the hub assigned.
8626
+ * @returns The reports.
8627
+ */
8628
+ toState: (message, context) => {
8629
+ const parsed = inboundSchema.safeParse(message.payload);
8630
+ if (!parsed.success) return [];
8631
+ const { device, changed, update } = parsed.data;
8632
+ return matterEntitiesOf(device).flatMap((entity) => {
8633
+ const entityId = context.entities.get(entity.objectId);
8634
+ if (entityId === void 0 || !isTouched(entity, changed)) return [];
8635
+ const state = entity.stateOf(device.attributes, update);
8636
+ return state === void 0 ? [] : [{
8637
+ entityId,
8638
+ state,
8639
+ attributes: {},
8640
+ isAvailable: device.isAvailable
8641
+ }];
8642
+ });
8643
+ },
8644
+ /**
8645
+ * Turns a command into a request.
8646
+ *
8647
+ * @param target - The entity, the capability and the command.
8648
+ * @param context - The claim and the last states.
8649
+ * @returns The request.
8650
+ * @throws {ValidationError} When the entity does not take the command.
8651
+ */
8652
+ toCommand: (target, context) => {
8653
+ const request = matterEntitiesOf(claimed(context)).find((candidate) => context.entities.get(candidate.objectId) === target.entityId)?.commandOf?.(target, context.lastState(target.entityId));
8654
+ if (request === void 0) throw new ValidationError(`${manifest.id} does not take ${target.capability}.${JSON.stringify(target.command["command"])} on ${target.entityId}`, { details: {
8655
+ integration: manifest.id,
8656
+ entityId: target.entityId
8657
+ } });
8658
+ return {
8659
+ deviceKey: context.claim.deviceKey,
8660
+ op: request.op,
8661
+ args: request.args
8662
+ };
8663
+ },
8664
+ /**
8665
+ * Reads the firmware the device runs now.
8666
+ *
8667
+ * @param message - What the transport delivered.
8668
+ * @returns The version, when the device says it.
8669
+ */
8670
+ deviceInfo: (message) => {
8671
+ const parsed = inboundSchema.safeParse(message.payload);
8672
+ const version = parsed.success ? parsed.data.device.identity.softwareVersionString : null;
8673
+ return version === null ? void 0 : { swVersion: version.slice(0, 64) };
8674
+ }
8675
+ };
8676
+ }
8677
+ //#endregion
7296
8678
  //#region ../package-runtime/dist/loader.js
7297
8679
  /**
7298
8680
  * Reading integrations off disk: the loader `hub` runs and the integration SDK checks a bundle
@@ -7319,7 +8701,6 @@ var require_semver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7319
8701
  * The same goes one level down for a vendor's `discovery.json`: discovery is a convenience on top
7320
8702
  * of adding a device by address, so a broken one is reported and the vendor loads without it.
7321
8703
  */
7322
- var import_semver = /* @__PURE__ */ __toESM(require_semver(), 1);
7323
8704
  /** The file every vendor is recognised by. */
7324
8705
  const MANIFEST_FILE = "manifest.json";
7325
8706
  /** The file every driver is recognised by. */
@@ -7537,6 +8918,7 @@ async function readDriver(vendor, directory, resolve) {
7537
8918
  profile
7538
8919
  };
7539
8920
  }
8921
+ if (manifest.kind === "matter") return identity;
7540
8922
  return {
7541
8923
  ...identity,
7542
8924
  entry: await moduleOf(resolve, directory, manifest.entry ?? "", manifest.id)
@@ -7576,6 +8958,7 @@ function planDiscovery(vendor, discovery, drivers) {
7576
8958
  const plan = resolveDiscovery(vendor.id, discovery, drivers.map((driver) => ({
7577
8959
  id: driver.driverId,
7578
8960
  name: driver.driverName,
8961
+ transport: driver.manifest.transport,
7579
8962
  models: driver.manifest.models,
7580
8963
  modelCodes: driver.manifest.modelCodes
7581
8964
  })));
@@ -7719,6 +9102,10 @@ async function instantiateDriver(driver, sdk, options) {
7719
9102
  ...identity,
7720
9103
  integration: createDeclarativeIntegration(driver.manifest, profile)
7721
9104
  };
9105
+ if (driver.manifest.kind === "matter") return {
9106
+ ...identity,
9107
+ integration: createMatterIntegration(driver.manifest)
9108
+ };
7722
9109
  const exported = await defaultOf(options.importModule ?? importFile, entry ?? "");
7723
9110
  const integration = typeof exported === "function" ? exported(sdk) : exported;
7724
9111
  if (integration === null || typeof integration !== "object") throw new Error(`${driver.manifest.id} does not default-export an integration`);
@@ -7863,4 +9250,4 @@ async function instantiateVendor(declaration, options) {
7863
9250
  };
7864
9251
  }
7865
9252
  //#endregion
7866
- export { identifySighting as a, integrationProfileSchema as c, driverManifestSchema as d, vendorManifestSchema as f, associateModel as i, accountDeclarationSchema as l, composeEntityId as m, readVendorDirectory as n, matchesAnnouncement as o, integrationSetupSchema as p, require_semver as r, vendorDiscoverySchema as s, instantiateVendor as t, defineAccount as u };
9253
+ export { associateModel as a, matchesMatter as c, accountDeclarationSchema as d, defineAccount as f, composeEntityId as g, integrationSetupSchema as h, associateMatter as i, vendorDiscoverySchema as l, vendorManifestSchema as m, readVendorDirectory as n, identifySighting as o, driverManifestSchema as p, require_semver as r, matchesAnnouncement as s, instantiateVendor as t, integrationProfileSchema as u };