@nebulahome/integration-sdk 1.0.0 → 1.2.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).
@@ -1725,6 +1726,8 @@ z.object({ vendorId: z.string().min(1).max(64) });
1725
1726
  *
1726
1727
  * Defined in ARCHITECTURE.md 8.
1727
1728
  */
1729
+ /** What an integration may say makes two of its devices one: the same MAC, the same serial. */
1730
+ const TWIN_FACTS = ["mac", "serial"];
1728
1731
  /**
1729
1732
  * Integration instance identifier.
1730
1733
  *
@@ -1754,7 +1757,8 @@ const transportIdSchema = z.string().regex(/^(?:[a-z][a-z0-9-]{1,63}\/)?[a-z][a-
1754
1757
  /**
1755
1758
  * The wires the interface names on a vendor's card: what a person recognises on the box, whatever
1756
1759
  * 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.
1760
+ * over plain datagrams on the network (Govee's LAN API), `modbus` Modbus TCP, `matter` the
1761
+ * house's Matter fabric.
1758
1762
  */
1759
1763
  const TRANSPORT_WIRES = [
1760
1764
  "http",
@@ -1762,14 +1766,20 @@ const TRANSPORT_WIRES = [
1762
1766
  "ble",
1763
1767
  "zigbee",
1764
1768
  "udp",
1765
- "modbus"
1769
+ "modbus",
1770
+ "matter"
1766
1771
  ];
1767
1772
  /**
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.
1773
+ * How a device can be heard announcing itself: the platform's mDNS browser, a vendor's own
1774
+ * listener, or the house's Matter fabric - a node commissioned and not yet added. Declared here
1775
+ * rather than beside the discovered devices, because a vendor lists the ways it can be found and
1776
+ * the discovery module already reads this file.
1771
1777
  */
1772
- const DISCOVERY_SOURCES = ["mdns", "module"];
1778
+ const DISCOVERY_SOURCES = [
1779
+ "mdns",
1780
+ "module",
1781
+ "matter"
1782
+ ];
1773
1783
  /**
1774
1784
  * Who adds a device discovery found: the owner, from its card - the ordinary way - or the
1775
1785
  * platform, as soon as it is heard. Automatic for a vendor whose devices were already chosen
@@ -1792,22 +1802,35 @@ const vendorPairingSchema = z.object({
1792
1802
  });
1793
1803
  /** What a logo may be served as: an image the interface can put straight into an `img`. */
1794
1804
  const LOGO_DATA_URL_PATTERN = /^data:image\/(?:svg\+xml|png);base64,[A-Za-z0-9+/]+=*$/;
1795
- /** Validates an instance lifecycle state. */
1796
- const integrationStateSchema = z.enum([
1805
+ /**
1806
+ * The lifecycle states `hub` records for a configured instance.
1807
+ *
1808
+ * `identifying` sits between `starting` and `running`: the transport is open, and the instance
1809
+ * is waiting to hear from the one device it was added for. A device that has been identified
1810
+ * before starts straight into `running`, bound from what the registry kept about it.
1811
+ */
1812
+ const INTEGRATION_STATES = [
1797
1813
  "stopped",
1798
1814
  "starting",
1799
1815
  "identifying",
1800
1816
  "running",
1801
1817
  "failed",
1802
1818
  "disabled"
1803
- ]);
1819
+ ];
1820
+ /** Validates an instance lifecycle state. */
1821
+ const integrationStateSchema = z.enum(INTEGRATION_STATES);
1804
1822
  z.strictObject({ vendorId: z.string().regex(VENDOR_ID_PATTERN$1) });
1805
1823
  z.object({ isLoaded: z.boolean() });
1806
1824
  /**
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.
1825
+ * Where `hub` read a vendor from: the data directory, where the platform installs vendors, a
1826
+ * directory of bundles under development, read outside production - or nowhere, for the one vendor
1827
+ * the platform is itself: `matter`, the Matter devices no integration claims.
1809
1828
  */
1810
- const BUNDLE_ORIGINS = ["installed", "development"];
1829
+ const BUNDLE_ORIGINS = [
1830
+ "installed",
1831
+ "development",
1832
+ "platform"
1833
+ ];
1811
1834
  /**
1812
1835
  * How the platform installed a vendor: the contents of the marker beside its builds,
1813
1836
  * `hub/integrations/<vendor>/.nebula-install.json`, which names the build `hub` loads.
@@ -1987,6 +2010,11 @@ const integrationVendorSchema = z.object({
1987
2010
  discoverySources: z.array(z.enum(DISCOVERY_SOURCES)).default([]),
1988
2011
  /** Who adds what discovery finds: the owner, or the platform on its own. */
1989
2012
  adoption: z.enum(DEVICE_ADOPTIONS).default("owner"),
2013
+ /**
2014
+ * What makes two of its devices one device reached two ways - the same MAC, the same serial -
2015
+ * as its manifest's `twins` says. Empty for a vendor that offers no links.
2016
+ */
2017
+ twins: z.array(z.enum(TWIN_FACTS)).max(TWIN_FACTS.length).default([]),
1990
2018
  /** The entities pairing is run by, for a vendor whose devices are paired through one of its own. */
1991
2019
  pairing: vendorPairingSchema.nullable().default(null),
1992
2020
  drivers: z.array(integrationKindSchema$1),
@@ -4181,6 +4209,26 @@ const declaredCapabilitiesSchema = z.partialRecord(capabilityNameSchema, jsonObj
4181
4209
  message: `Parameters do not match the ${capability} capability`
4182
4210
  });
4183
4211
  });
4212
+ /**
4213
+ * Where a reading sits in Matter's terms: the endpoint, the cluster and the attribute. A Matter
4214
+ * entity carries its own; an entity of another transport may carry the one that reads the same
4215
+ * thing, so the two are linked when the device is reached both ways.
4216
+ */
4217
+ const matterReferenceSchema = z.strictObject({
4218
+ endpoint: z.int().min(0).max(65535),
4219
+ cluster: z.int().min(0),
4220
+ attribute: z.int().min(0)
4221
+ });
4222
+ /**
4223
+ * What lets an entity be told apart from the same reading reached another way: its own key in its
4224
+ * transport's terms - `switch:0` on a Shelly - and where it sits in Matter.
4225
+ */
4226
+ const entityLinkHintSchema = z.strictObject({
4227
+ /** The entity's key in its transport, as its page shows it beside the transport's name. */
4228
+ key: z.string().min(1).max(64).optional(),
4229
+ /** Where it sits in Matter: its own place, or, for another transport, its Matter twin's. */
4230
+ matter: matterReferenceSchema.optional()
4231
+ });
4184
4232
  /** One entity a device exposes. */
4185
4233
  const entityRegistrationSchema = z.object({
4186
4234
  entityId: entityIdSchema,
@@ -4191,7 +4239,9 @@ const entityRegistrationSchema = z.object({
4191
4239
  unitOfMeasurement: z.string().max(32).optional(),
4192
4240
  deviceClass: z.string().max(64).optional(),
4193
4241
  stateClass: z.enum(ENTITY_STATE_CLASSES).optional(),
4194
- displayPrecision: z.int().min(0).max(6).optional()
4242
+ displayPrecision: z.int().min(0).max(6).optional(),
4243
+ /** Kept in the entity's `config.link`: what links it to its twin on another transport. */
4244
+ link: entityLinkHintSchema.optional()
4195
4245
  }).superRefine((entity, ctx) => {
4196
4246
  const issue = sensorRegistrationIssue(entity);
4197
4247
  if (issue !== void 0) ctx.addIssue({
@@ -4216,6 +4266,10 @@ z.strictObject({
4216
4266
  model: z.string().max(128).optional(),
4217
4267
  swVersion: z.string().max(64).optional(),
4218
4268
  hwVersion: z.string().max(64).optional(),
4269
+ /** The hardware's MAC address, as {@link normalizeMac} writes it, when it says one. */
4270
+ mac: z.string().min(1).max(64).optional(),
4271
+ /** The hardware's serial number, when it says one. */
4272
+ serialNumber: z.string().min(1).max(256).optional(),
4219
4273
  /**
4220
4274
  * What the owner needs to find the device again after a restart.
4221
4275
  *
@@ -4276,6 +4330,16 @@ z.strictObject({
4276
4330
  z.object({ isChanged: z.boolean() });
4277
4331
  z.strictObject({ entityId: entityIdSchema });
4278
4332
  z.object({ isLoaded: z.boolean() });
4333
+ z.strictObject({ entityRowIds: z.array(z.uuid()).min(1).max(1024) });
4334
+ z.object({ synced: z.int().min(0) });
4335
+ z.strictObject({ entityId: entityIdSchema });
4336
+ z.object({ items: z.array(z.object({
4337
+ entityId: entityIdSchema,
4338
+ /** The instance it comes through. */
4339
+ source: z.string(),
4340
+ isActive: z.boolean(),
4341
+ state: entityStateSchema.nullable()
4342
+ })) });
4279
4343
  z.strictObject({ entityId: entityIdSchema });
4280
4344
  z.object({ entityId: entityIdSchema });
4281
4345
  z.object({
@@ -4287,6 +4351,421 @@ z.object({
4287
4351
  entityIds: z.array(entityIdSchema)
4288
4352
  });
4289
4353
  //#endregion
4354
+ //#region ../contracts/dist/links.js
4355
+ /**
4356
+ * One device reached two ways, and the readings it gives both ways linked into one.
4357
+ *
4358
+ * A Shelly added over its own RPC and again over Matter is the same plug. The house keeps one
4359
+ * device for it and one entity for each thing it reads, each with a **source** per transport:
4360
+ * readings come from the preferred one, and the other takes over while it is silent.
4361
+ *
4362
+ * **The longer history leads.** Linking adds no row. Of two devices, the one the house had first
4363
+ * is the one it shows, and the other names it in `linked_to`; of two entities, the one with the
4364
+ * longer history is the linked entity, keeps its address and goes on recording, and the other
4365
+ * names it and stops. Every address and row of a linked entity means the one it names - to an
4366
+ * automation, a scene, a card - so nothing that used either is rewritten, and unlinking gives each
4367
+ * back its own.
4368
+ */
4369
+ /** How a pair of entities was linked: declared by the integration, read alike, or by the owner. */
4370
+ const LINK_ORIGINS = [
4371
+ "declared",
4372
+ "auto",
4373
+ "manual"
4374
+ ];
4375
+ /** One thing two devices have alike, and its value. */
4376
+ const linkReasonSchema = z.object({
4377
+ kind: z.enum([
4378
+ "mac",
4379
+ "serial",
4380
+ "model"
4381
+ ]),
4382
+ value: z.string().max(256)
4383
+ });
4384
+ /**
4385
+ * A MAC address the way the house compares them: six bytes, lower case, colons.
4386
+ *
4387
+ * Devices write theirs every way - Shelly `08F9E0124C7A`, Matter `08:f9:e0:12:4c:7a` - and a
4388
+ * Thread radio's eight-byte address is not a MAC anybody else reports.
4389
+ *
4390
+ * @param raw - The address as the device said it.
4391
+ * @returns It, normalised; null when it is not a six-byte address.
4392
+ */
4393
+ function normalizeMac(raw) {
4394
+ const hex = (raw ?? "").replaceAll(/[^0-9a-f]/giu, "").toLowerCase();
4395
+ if (hex.length !== 12 || (raw ?? "").replaceAll(/[0-9a-f:.\-\s]/giu, "") !== "") return null;
4396
+ return hex.replaceAll(/(..)(?!$)/gu, "$1:");
4397
+ }
4398
+ /** One way into a linked device: the instance, its transport and how it stands. */
4399
+ const deviceWaySchema = z.object({
4400
+ /** The instance, which is the way's own device id. */
4401
+ deviceId: integrationIdSchema,
4402
+ kind: z.string(),
4403
+ vendorId: z.string(),
4404
+ transport: z.string(),
4405
+ driverName: z.string(),
4406
+ state: z.enum(INTEGRATION_STATES),
4407
+ /** Whether its entities answer now. */
4408
+ isAvailable: z.boolean(),
4409
+ /** Whether readings come this way first. */
4410
+ isPreferred: z.boolean(),
4411
+ externalId: z.string().nullable(),
4412
+ /** Where it is reached, when its transport names a host: `192.168.178.112`. */
4413
+ address: z.string().nullable(),
4414
+ /** The Matter node, for a way through the Matter broker. */
4415
+ nodeId: z.string().nullable(),
4416
+ swVersion: z.string().nullable(),
4417
+ lastUpdatedAt: timestampSchema.nullable(),
4418
+ createdAt: timestampSchema
4419
+ });
4420
+ z.object({
4421
+ ways: z.array(deviceWaySchema).min(2),
4422
+ /** The instance its entities are read through first. */
4423
+ preferred: integrationIdSchema
4424
+ });
4425
+ /** One source of a linked entity: the same reading through one way in. */
4426
+ const entitySourceSchema = z.object({
4427
+ entityId: entityIdSchema,
4428
+ /** The way in, by its instance. */
4429
+ deviceId: integrationIdSchema,
4430
+ vendorId: z.string(),
4431
+ transport: z.string(),
4432
+ /** Its key in its transport, `switch:0`, when the integration names one. */
4433
+ key: z.string().nullable(),
4434
+ /** Where it sits in Matter, for a Matter source. */
4435
+ matter: matterReferenceSchema.nullable(),
4436
+ /** Whether readings come from it now. */
4437
+ isActive: z.boolean(),
4438
+ isAvailable: z.boolean(),
4439
+ /** What it last said, whether or not it is the one read. */
4440
+ state: jsonObjectSchema.nullable(),
4441
+ lastUpdated: timestampSchema.nullable(),
4442
+ /** How it was linked; null for the entity that leads. */
4443
+ origin: z.enum(LINK_ORIGINS).nullable()
4444
+ });
4445
+ z.object({
4446
+ /** Every source, the one that leads first. */
4447
+ sources: z.array(entitySourceSchema).min(2),
4448
+ /** The instance this entity is read through first, overriding its device; null follows it. */
4449
+ transport: integrationIdSchema.nullable(),
4450
+ /** The instance the device is read through first. */
4451
+ preferred: integrationIdSchema,
4452
+ /** The instance it is read through now; null while no source answers. */
4453
+ active: integrationIdSchema.nullable()
4454
+ });
4455
+ z.object({ entityIds: z.tuple([entityIdSchema, entityIdSchema]) });
4456
+ z.object({ with: integrationIdSchema });
4457
+ z.object({ with: entityIdSchema });
4458
+ z.object({ preview: z.stringbool().default(false) });
4459
+ /** What uses an address: what follows an entity when it is linked or unlinked. */
4460
+ const linkUseSchema = z.object({
4461
+ automations: z.array(z.string()),
4462
+ scenes: z.array(z.string()),
4463
+ aliases: z.array(z.string()),
4464
+ /** Cards, by dashboard. */
4465
+ cards: z.array(z.object({
4466
+ dashboard: z.string(),
4467
+ count: z.int().min(1)
4468
+ }))
4469
+ });
4470
+ /** One entity in a link's account. */
4471
+ const linkSideSchema = z.object({
4472
+ entityId: entityIdSchema,
4473
+ name: z.string(),
4474
+ deviceId: integrationIdSchema,
4475
+ vendorId: z.string(),
4476
+ transport: z.string(),
4477
+ usedBy: linkUseSchema
4478
+ });
4479
+ /** Entities that are, or would be, one: the one that leads, and those that read through it. */
4480
+ const linkPairSchema = z.object({
4481
+ holder: linkSideSchema,
4482
+ others: z.array(linkSideSchema).min(1),
4483
+ origin: z.enum(LINK_ORIGINS)
4484
+ });
4485
+ /** A device in a link's account. */
4486
+ const linkDeviceSchema = z.object({
4487
+ id: integrationIdSchema,
4488
+ name: z.string(),
4489
+ model: z.string().nullable(),
4490
+ vendorId: z.string(),
4491
+ transport: z.string(),
4492
+ areaName: z.string().nullable()
4493
+ });
4494
+ z.object({
4495
+ action: z.enum(["link", "unlink"]),
4496
+ scope: z.enum(["device", "entity"]),
4497
+ /** The device the house shows, and the other way into it; null for an entity's link. */
4498
+ device: linkDeviceSchema.nullable(),
4499
+ other: linkDeviceSchema.nullable(),
4500
+ /** What is linked, or unlinked. */
4501
+ pairs: z.array(linkPairSchema),
4502
+ /** What a device's link leaves read one way. */
4503
+ single: z.array(linkSideSchema),
4504
+ /** The way read first, after a link; the way the leading entity keeps, after an unlink. */
4505
+ preferred: z.object({
4506
+ deviceId: integrationIdSchema,
4507
+ vendorId: z.string(),
4508
+ transport: z.string()
4509
+ }),
4510
+ /** Since when the entities were linked, for an unlink. */
4511
+ linkedSince: timestampSchema.nullable()
4512
+ });
4513
+ /** One device in a suggestion. */
4514
+ const suggestedDeviceSchema = z.object({
4515
+ id: integrationIdSchema,
4516
+ name: z.string(),
4517
+ model: z.string().nullable(),
4518
+ vendorId: z.string(),
4519
+ transport: z.string(),
4520
+ createdAt: timestampSchema
4521
+ });
4522
+ /**
4523
+ * Two devices that look like one, offered to link: the one the house had first, and the newer
4524
+ * way in.
4525
+ */
4526
+ const linkSuggestionViewSchema = z.object({
4527
+ id: z.uuid(),
4528
+ vendorId: z.string().regex(VENDOR_ID_PATTERN$1),
4529
+ device: suggestedDeviceSchema,
4530
+ twin: suggestedDeviceSchema,
4531
+ reasons: z.array(linkReasonSchema),
4532
+ /** When the owner set it aside; null while it is offered. */
4533
+ dismissedAt: timestampSchema.nullable(),
4534
+ createdAt: timestampSchema
4535
+ });
4536
+ z.object({ items: z.array(linkSuggestionViewSchema) });
4537
+ z.object({ isDismissed: z.boolean() });
4538
+ //#endregion
4539
+ //#region ../contracts/dist/matter.js
4540
+ /**
4541
+ * The house's Matter fabric, as the hub runs it and the Brokers page shows it.
4542
+ *
4543
+ * Matter is one of the platform's brokers: the hub holds the controller - one fabric for the
4544
+ * house - and every Matter device is reached through it. A node is commissioned once, with the
4545
+ * code another app (the maker's, Google Home, Apple Home, Alexa) shares, and is then a device of
4546
+ * the house: of the integration whose `discovery.json` recognises it, or of the platform's own
4547
+ * `matter` vendor when none does. A bridge is one node with a device per bridged endpoint.
4548
+ *
4549
+ * The identity a node is recognised by is {@link matterIdentitySchema}: what its Basic Information
4550
+ * (or, for a bridged device, its Bridged Device Basic Information), General Diagnostics and
4551
+ * Descriptor clusters say, read by an integration's rules the way an mDNS announcement is.
4552
+ */
4553
+ /** The platform transport every Matter device is reached through. */
4554
+ const MATTER_TRANSPORT = "matter";
4555
+ /** The platform's own vendor: the Matter devices no integration claims. */
4556
+ const MATTER_VENDOR = "matter";
4557
+ /** The UDP port the controller listens on, which the engine does not let anyone change. */
4558
+ const MATTER_PORT = 5540;
4559
+ /** A node id, in decimal: a 64-bit number, which JSON cannot carry as a number. */
4560
+ const matterNodeIdSchema = z.string().regex(/^[0-9]{1,20}$/u, "Must be a node id");
4561
+ /**
4562
+ * A pairing code, as another app shares it: the manual code - 11 or 21 digits, often written in
4563
+ * groups - or the QR code's text, `MT:` and base-38. Spaces and dashes are dropped from a manual
4564
+ * code, so `3497-011-2332` is `34970112332`.
4565
+ */
4566
+ 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:…)"));
4567
+ /** How many items a list in an identity holds at most. */
4568
+ const MAXIMUM_LIST = 64;
4569
+ /**
4570
+ * Who a Matter device says it is: what an integration's rules match and the Brokers page shows.
4571
+ *
4572
+ * Every field is null when the device does not say it - most leave a product label or a serial
4573
+ * out - so a rule reads `null` rather than a missing key. `endpoint` is null for the node itself
4574
+ * and the endpoint's number for a device behind a bridge, whose names are its own.
4575
+ */
4576
+ const matterIdentitySchema = z.object({
4577
+ nodeId: matterNodeIdSchema,
4578
+ endpoint: z.int().min(0).max(65535).nullable(),
4579
+ vendorId: z.int().min(0).max(65535).nullable(),
4580
+ productId: z.int().min(0).max(65535).nullable(),
4581
+ vendorName: z.string().max(256).nullable(),
4582
+ productName: z.string().max(256).nullable(),
4583
+ productLabel: z.string().max(256).nullable(),
4584
+ nodeLabel: z.string().max(256).nullable(),
4585
+ serialNumber: z.string().max(256).nullable(),
4586
+ uniqueId: z.string().max(256).nullable(),
4587
+ hardwareVersion: z.int().min(0).nullable(),
4588
+ hardwareVersionString: z.string().max(256).nullable(),
4589
+ softwareVersion: z.int().min(0).nullable(),
4590
+ softwareVersionString: z.string().max(256).nullable(),
4591
+ /** The hardware addresses of its network interfaces, lower-case and colon-separated. */
4592
+ macAddresses: z.array(z.string().max(64)).max(MAXIMUM_LIST),
4593
+ /** The Matter device types it declares, by number: `256` an on/off light. */
4594
+ deviceTypes: z.array(z.int().min(0)).max(MAXIMUM_LIST),
4595
+ /** The clusters its endpoints serve, by number, each once. */
4596
+ clusters: z.array(z.int().min(0)).max(256),
4597
+ /** Whether the node is a bridge, with devices of its own behind it. */
4598
+ isBridge: z.boolean(),
4599
+ /** Whether this is a device behind a bridge. */
4600
+ isBridged: z.boolean()
4601
+ });
4602
+ /** How the controller stands. */
4603
+ const MATTER_CONTROLLER_STATES = [
4604
+ "starting",
4605
+ "running",
4606
+ "failed",
4607
+ "disabled"
4608
+ ];
4609
+ /**
4610
+ * How a commissioning goes. `needs-answer` is a job that stopped before the node joined and waits
4611
+ * for the owner: a device whose certificate is a test one, added only when they say so.
4612
+ */
4613
+ const MATTER_COMMISSIONING_STATES = [
4614
+ "running",
4615
+ "needs-answer",
4616
+ "succeeded",
4617
+ "failed"
4618
+ ];
4619
+ /**
4620
+ * The steps of a commissioning, in order: the code read, the device found on the network, its
4621
+ * certificate checked against the DCL, joining the fabric, reading what it can do, and the device
4622
+ * in the house.
4623
+ */
4624
+ const MATTER_COMMISSIONING_STEPS = [
4625
+ "code",
4626
+ "found",
4627
+ "certificate",
4628
+ "joining",
4629
+ "reading",
4630
+ "in-house"
4631
+ ];
4632
+ /** One step of a commissioning, and what it found. */
4633
+ const matterCommissioningStepSchema = z.object({
4634
+ id: z.enum(MATTER_COMMISSIONING_STEPS),
4635
+ state: z.enum([
4636
+ "pending",
4637
+ "running",
4638
+ "done",
4639
+ "warning",
4640
+ "failed"
4641
+ ]),
4642
+ /**
4643
+ * What the step found, as facts the page words itself: the discriminator a code carries, the
4644
+ * address and product a device answered with, the vendor and product a test certificate names.
4645
+ */
4646
+ detail: z.object({
4647
+ discriminator: z.int().min(0).max(4095).nullable().default(null),
4648
+ isQrCode: z.boolean().default(false),
4649
+ address: z.string().max(256).nullable().default(null),
4650
+ product: z.string().max(256).nullable().default(null),
4651
+ vendorId: z.int().min(0).max(65535).nullable().default(null),
4652
+ productId: z.int().min(0).max(65535).nullable().default(null)
4653
+ }).default({
4654
+ discriminator: null,
4655
+ isQrCode: false,
4656
+ address: null,
4657
+ product: null,
4658
+ vendorId: null,
4659
+ productId: null
4660
+ })
4661
+ });
4662
+ /**
4663
+ * One commissioning: started by a pairing code, done once the device is in the house. A node takes
4664
+ * from seconds to a minute or two, longer than one request may wait, so the page reads the job
4665
+ * until it ends.
4666
+ */
4667
+ const matterCommissioningSchema = z.object({
4668
+ id: z.string().min(1).max(64),
4669
+ state: z.enum(MATTER_COMMISSIONING_STATES),
4670
+ startedAt: timestampSchema,
4671
+ finishedAt: timestampSchema.nullable(),
4672
+ /** The node it made; null until it is on the fabric. */
4673
+ nodeId: matterNodeIdSchema.nullable(),
4674
+ /** Why it failed, in a sentence; null unless it did. */
4675
+ error: z.string().max(2048).nullable(),
4676
+ /** Each step in order, with how it stands. */
4677
+ steps: z.array(matterCommissioningStepSchema).max(MATTER_COMMISSIONING_STEPS.length).default([]),
4678
+ /** The device it became in the house; null until it is in. */
4679
+ deviceId: integrationIdSchema.nullable().default(null)
4680
+ });
4681
+ z.object({
4682
+ state: z.enum(MATTER_CONTROLLER_STATES),
4683
+ /** Why it failed or is off, in a sentence; null while it runs. */
4684
+ error: z.string().max(2048).nullable(),
4685
+ /** The fabric's id, in hex; null before the controller has one. */
4686
+ fabricId: z.string().max(32).nullable(),
4687
+ /**
4688
+ * Whether the hub hears the house's network. Matter finds its nodes over mDNS and IPv6, which a
4689
+ * container on a bridge network does not carry: there the controller runs and reaches nothing.
4690
+ */
4691
+ isLanReachable: z.boolean(),
4692
+ nodes: z.object({
4693
+ total: z.int().min(0),
4694
+ online: z.int().min(0)
4695
+ }),
4696
+ /** The last commissioning; null when none was started since the hub started. */
4697
+ commissioning: matterCommissioningSchema.nullable(),
4698
+ /** When the controller last started; null while it is not running. */
4699
+ startedAt: timestampSchema.nullable().default(null),
4700
+ /** The engine under the controller, as `matter.js 0.17`. */
4701
+ controllerVersion: z.string().max(64).nullable().default(null),
4702
+ /** The UDP port the controller listens on. */
4703
+ port: z.int().min(1).max(65535).default(MATTER_PORT),
4704
+ /** When this hub made the fabric; null for one made before the hub kept the date. */
4705
+ fabricCreatedAt: timestampSchema.nullable().default(null)
4706
+ });
4707
+ /** One device a node is in the house: the node itself, or one endpoint behind a bridge. */
4708
+ const matterNodeDeviceSchema = z.object({
4709
+ identity: matterIdentitySchema,
4710
+ /** The clusters the platform turns into entities, and those it does not, by number. */
4711
+ mappedClusters: z.array(z.int().min(0)).max(256),
4712
+ unmappedClusters: z.array(z.int().min(0)).max(256),
4713
+ /** The device added for it; null while it is not, or after it was removed from the house. */
4714
+ deviceId: integrationIdSchema.nullable(),
4715
+ /** The driver it was added as; null while it is not added. */
4716
+ kind: integrationKindIdSchema.nullable(),
4717
+ /**
4718
+ * The integrations whose rules all take it. One is the integration it belongs to; several, and it
4719
+ * is added as the platform's own and the page says who else wants it. Empty when none takes it.
4720
+ */
4721
+ claimedBy: z.array(z.string().regex(VENDOR_ID_PATTERN$1)).max(16),
4722
+ /** Removed from the house, its node still on the fabric: the page offers it back. */
4723
+ isRemoved: z.boolean()
4724
+ });
4725
+ /** One node of the fabric. */
4726
+ const matterNodeSchema = z.object({
4727
+ nodeId: matterNodeIdSchema,
4728
+ isAvailable: z.boolean(),
4729
+ /** When it joined the fabric, as the controller recorded it; null when it did not say. */
4730
+ commissionedAt: timestampSchema.nullable().default(null),
4731
+ /** Since when it has not answered, as far as this hub saw; null while it answers. */
4732
+ offlineSince: timestampSchema.nullable().default(null),
4733
+ /** The node itself first, then each device behind it when it is a bridge. */
4734
+ devices: z.array(matterNodeDeviceSchema).min(1).max(256)
4735
+ });
4736
+ z.object({});
4737
+ z.object({});
4738
+ z.object({ items: z.array(matterNodeSchema) });
4739
+ z.object({ code: matterPairingCodeSchema });
4740
+ z.object({ nodeId: matterNodeIdSchema });
4741
+ z.object({ isRemoved: z.boolean() });
4742
+ z.object({
4743
+ nodeId: matterNodeIdSchema,
4744
+ endpoint: z.int().min(0).max(65535).nullable()
4745
+ });
4746
+ z.object({ isRestored: z.boolean() });
4747
+ z.object({
4748
+ jobId: z.string().min(1).max(64),
4749
+ isAccepted: z.boolean()
4750
+ });
4751
+ /** The brokers the platform runs, as the Brokers page lists them. */
4752
+ const BROKER_IDS = [MATTER_VENDOR];
4753
+ /** One broker, for its card. */
4754
+ const brokerSummarySchema = z.object({
4755
+ id: z.enum(BROKER_IDS),
4756
+ state: z.enum(MATTER_CONTROLLER_STATES),
4757
+ /**
4758
+ * The devices the house has through it, how many of them answer, and how many are also
4759
+ * reached another way.
4760
+ */
4761
+ devices: z.object({
4762
+ total: z.int().min(0),
4763
+ online: z.int().min(0),
4764
+ linked: z.int().min(0).default(0)
4765
+ })
4766
+ });
4767
+ z.object({ items: z.array(brokerSummarySchema) });
4768
+ //#endregion
4290
4769
  //#region ../package-runtime/dist/containers.js
4291
4770
  /** A vendor setting a value is filled from: `{setup.serialPath}`. */
4292
4771
  const SETTING_PLACEHOLDER = /\{setup\.([a-zA-Z][a-zA-Z0-9]*)\}/g;
@@ -4350,8 +4829,15 @@ function containerDependencyProblems(deps, setup) {
4350
4829
  * JavaScript, and reaches a catalogue only after the manual approval ARCHITECTURE.md 10 already
4351
4830
  * requires of executable content.
4352
4831
  */
4353
- /** Bundle kind, which is both how it is written and how far it is trusted. */
4354
- const BUNDLE_KINDS = ["declarative", "code"];
4832
+ /**
4833
+ * Bundle kind, which is both how it is written and how far it is trusted. `matter` is a driver
4834
+ * the platform's Matter mapping runs: no profile and no code, so as far trusted as a profile.
4835
+ */
4836
+ const BUNDLE_KINDS = [
4837
+ "declarative",
4838
+ "code",
4839
+ "matter"
4840
+ ];
4355
4841
  /** Validates a vendor id. */
4356
4842
  const vendorIdSchema = z.string().regex(/^[a-z][a-z0-9-]{1,63}$/, "Must be a vendor id");
4357
4843
  /** Validates a driver id. */
@@ -4418,6 +4904,12 @@ const vendorManifestSchema = z.strictObject({
4418
4904
  /** Whether the devices stop working when the internet does. Shown as a warning on the card. */
4419
4905
  internetRequired: z.boolean().default(false),
4420
4906
  /**
4907
+ * What makes two of the vendor's devices one device reached two ways - over its own transport
4908
+ * and through the Matter broker, say: `["mac"]`, or `["mac", "serial"]` for both to agree.
4909
+ * The house then offers to link them. Absent, it never does.
4910
+ */
4911
+ twins: z.array(z.enum(TWIN_FACTS)).min(1).max(TWIN_FACTS.length).optional(),
4912
+ /**
4421
4913
  * Path to a `setup.json` of settings every device of this vendor shares - a cloud API key,
4422
4914
  * an account - relative to the bundle. Absent for the vendors whose devices are reached
4423
4915
  * directly, which is most of them.
@@ -4551,6 +5043,19 @@ const driverShape = {
4551
5043
  * @param ctx - Where to record what is wrong.
4552
5044
  */
4553
5045
  function checkKindFiles(manifest, ctx) {
5046
+ if (manifest.kind === "matter") {
5047
+ for (const named of ["profile", "entry"]) if (manifest[named] !== void 0) ctx.addIssue({
5048
+ code: "custom",
5049
+ path: [named],
5050
+ message: `A matter driver must not name an ${named}`
5051
+ });
5052
+ if (manifest.transport !== "matter") ctx.addIssue({
5053
+ code: "custom",
5054
+ path: ["transport"],
5055
+ message: `A matter driver runs on the ${MATTER_TRANSPORT} transport`
5056
+ });
5057
+ return;
5058
+ }
4554
5059
  const expected = manifest.kind === "declarative" ? "profile" : "entry";
4555
5060
  const forbidden = manifest.kind === "declarative" ? "entry" : "profile";
4556
5061
  if (manifest[expected] === void 0) ctx.addIssue({
@@ -4856,8 +5361,8 @@ function walk(payload, segments) {
4856
5361
  /**
4857
5362
  * Decides whether one condition holds.
4858
5363
  *
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.
5364
+ * The same forms wherever a condition is written - a driver's claim, a vendor's match on an
5365
+ * announcement or on a Matter device - so there is one reading of each.
4861
5366
  *
4862
5367
  * @param condition - What to check.
4863
5368
  * @param payload - What the scan, the probe or the announcement said.
@@ -4868,7 +5373,14 @@ function conditionHolds(condition, payload) {
4868
5373
  if ("exists" in condition) return value !== void 0 && value !== null;
4869
5374
  if ("oneOf" in condition) return condition.oneOf.some((candidate) => candidate === value);
4870
5375
  if ("startsWith" in condition) return typeof value === "string" && value.toLowerCase().startsWith(condition.startsWith.toLowerCase());
4871
- return value === condition.equals;
5376
+ if ("endsWith" in condition) return typeof value === "string" && value.toLowerCase().endsWith(condition.endsWith.toLowerCase());
5377
+ if ("contains" in condition) {
5378
+ const wanted = condition.contains;
5379
+ if (Array.isArray(value)) return value.includes(wanted);
5380
+ return typeof value === "string" && typeof wanted === "string" && value.toLowerCase().includes(wanted.toLowerCase());
5381
+ }
5382
+ if ("equals" in condition) return value === condition.equals;
5383
+ return typeof value === "number" && (condition.min === void 0 || value >= condition.min) && (condition.max === void 0 || value <= condition.max);
4872
5384
  }
4873
5385
  //#endregion
4874
5386
  //#region ../package-runtime/dist/declarative.js
@@ -4999,7 +5511,7 @@ function readStateSource(value, payload) {
4999
5511
  if (typeof value === "string") return resolvePath(payload, value);
5000
5512
  if ("present" in value) return resolvePresence(payload, value.path);
5001
5513
  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);
5514
+ const found = resolved === void 0 || value.bits === void 0 && value.base === void 0 ? resolved : numberOf$1(resolved, value.bits, value.base ?? 10);
5003
5515
  if (found === void 0) return;
5004
5516
  if ("map" in value) {
5005
5517
  const key = typeof found === "string" || typeof found === "number" || typeof found === "boolean" ? String(found) : void 0;
@@ -5017,7 +5529,7 @@ function readStateSource(value, payload) {
5017
5529
  * @returns The number, or its bits unsigned; undefined when the value is no number, or no integer
5018
5530
  * where bits are read.
5019
5531
  */
5020
- function numberOf(value, bits, base) {
5532
+ function numberOf$1(value, bits, base) {
5021
5533
  const text = typeof value === "string" ? value.trim() : void 0;
5022
5534
  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
5535
  if (!Number.isFinite(number)) return;
@@ -5215,6 +5727,8 @@ function createDeclarativeIntegration(manifest, profile) {
5215
5727
  const model = text(identity.model);
5216
5728
  const swVersion = text(identity.swVersion);
5217
5729
  const hwVersion = text(identity.hwVersion);
5730
+ const mac = normalizeMac(text(identity.mac)) ?? void 0;
5731
+ const serialNumber = text(identity.serialNumber);
5218
5732
  const entities = profile.entities.map((entity) => {
5219
5733
  const measurement = registeredMeasurement(entity);
5220
5734
  return {
@@ -5224,7 +5738,8 @@ function createDeclarativeIntegration(manifest, profile) {
5224
5738
  ...entity.icon === void 0 ? {} : { icon: entity.icon },
5225
5739
  capabilities: entity.capabilities,
5226
5740
  ...measurement,
5227
- ...entity.displayPrecision === void 0 ? {} : { displayPrecision: entity.displayPrecision }
5741
+ ...entity.displayPrecision === void 0 ? {} : { displayPrecision: entity.displayPrecision },
5742
+ ...entity.link === void 0 ? {} : { link: entity.link }
5228
5743
  };
5229
5744
  });
5230
5745
  return {
@@ -5234,6 +5749,8 @@ function createDeclarativeIntegration(manifest, profile) {
5234
5749
  ...model === void 0 ? {} : { model },
5235
5750
  ...swVersion === void 0 ? {} : { swVersion },
5236
5751
  ...hwVersion === void 0 ? {} : { hwVersion },
5752
+ ...mac === void 0 ? {} : { mac },
5753
+ ...serialNumber === void 0 ? {} : { serialNumber },
5237
5754
  entities
5238
5755
  };
5239
5756
  },
@@ -5379,9 +5896,17 @@ const scalarSchema = z.union([
5379
5896
  * and not an `or` between paths: the list is still all-of, and a claim needing boolean
5380
5897
  * algebra is still a claim whose integration should be code.
5381
5898
  *
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.
5899
+ * `startsWith` and `endsWith` are a prefix and a suffix of a text, compared without regard to
5900
+ * case: what a name a device gives itself on the network looks like - `shellyplus1-a8032ab1`,
5901
+ * `ShellyDimmerG3-…` - when the rest of it is the device's own, and a MAC address's maker by its
5902
+ * first three bytes.
5903
+ *
5904
+ * `contains` is a part of a text, without regard to case, or one item of a list - a Matter
5905
+ * device's `deviceTypes`, its `clusters`. `min` and `max` bound a number, both ends included: a
5906
+ * firmware version from which a driver takes the device.
5907
+ *
5908
+ * There is no regular expression on purpose: one written badly takes the hub's thread for as long
5909
+ * as it backtracks, and the grammar is what keeps a declarative bundle from doing that.
5385
5910
  */
5386
5911
  const claimConditionSchema = z.union([
5387
5912
  z.strictObject({
@@ -5399,7 +5924,20 @@ const claimConditionSchema = z.union([
5399
5924
  z.strictObject({
5400
5925
  path: pathSchema,
5401
5926
  startsWith: z.string().min(1).max(64)
5402
- })
5927
+ }),
5928
+ z.strictObject({
5929
+ path: pathSchema,
5930
+ endsWith: z.string().min(1).max(64)
5931
+ }),
5932
+ z.strictObject({
5933
+ path: pathSchema,
5934
+ contains: scalarSchema
5935
+ }),
5936
+ z.strictObject({
5937
+ path: pathSchema,
5938
+ min: z.number().optional(),
5939
+ max: z.number().optional()
5940
+ }).refine((condition) => condition.min !== void 0 || condition.max !== void 0, "A range needs min, max or both")
5403
5941
  ]);
5404
5942
  /** Part of a number: `[shift, width]`, the lowest bit first. */
5405
5943
  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");
@@ -5474,7 +6012,13 @@ const identityMappingSchema = z.strictObject({
5474
6012
  manufacturer: pathSchema.optional(),
5475
6013
  model: pathSchema.optional(),
5476
6014
  swVersion: pathSchema.optional(),
5477
- hwVersion: pathSchema.optional()
6015
+ hwVersion: pathSchema.optional(),
6016
+ /**
6017
+ * The hardware's MAC address, written any way - `08F9E0124C7A`, `08:f9:e0:12:4c:7a` - so the
6018
+ * house can tell this device from the same one reached another way.
6019
+ */
6020
+ mac: pathSchema.optional(),
6021
+ serialNumber: pathSchema.optional()
5478
6022
  });
5479
6023
  /**
5480
6024
  * A path into the command, with what to do to what it names.
@@ -5570,6 +6114,13 @@ const entityProfileSchema = z.strictObject({
5570
6114
  stateClass: z.enum(ENTITY_STATE_CLASSES).optional(),
5571
6115
  displayPrecision: z.int().min(0).max(6).optional(),
5572
6116
  /**
6117
+ * What links it to the same reading reached another way: its key in the transport's terms
6118
+ * (`switch:0`), shown beside the transport's name, and where that reading sits in Matter
6119
+ * (`{ "endpoint": 1, "cluster": 6, "attribute": 0 }`), for a device the house also reaches
6120
+ * through the Matter broker.
6121
+ */
6122
+ link: entityLinkHintSchema.optional(),
6123
+ /**
5573
6124
  * For a camera: the stream source that reads its picture, `<vendor>/<name>`, and what it is
5574
6125
  * told to read. The source is handed the instance's transport settings as well.
5575
6126
  */
@@ -5719,7 +6270,15 @@ const discoveryIdentitySchema = z.strictObject({
5719
6270
  /** What makes the device the same device next time: the same value identification reads. */
5720
6271
  externalId: identityPathSchema.optional(),
5721
6272
  name: identityPathSchema.optional(),
5722
- swVersion: identityPathSchema.optional()
6273
+ swVersion: identityPathSchema.optional(),
6274
+ /** Its MAC address, written any way the device writes it: what tells it from its twin. */
6275
+ mac: identityPathSchema.optional(),
6276
+ serialNumber: identityPathSchema.optional(),
6277
+ /**
6278
+ * Where the device says it is behind a password - `auth_en` on a Shelly - so its row says so
6279
+ * before anyone tries to add it. True there means a password is needed.
6280
+ */
6281
+ auth: identityPathSchema.optional()
5723
6282
  });
5724
6283
  /**
5725
6284
  * What to ask an announced address.
@@ -5738,13 +6297,30 @@ const discoveryProbeSchema = z.strictObject({
5738
6297
  args: jsonObjectSchema.default({}),
5739
6298
  timeoutMs: z.int().min(500).max(3e4).optional()
5740
6299
  });
6300
+ /**
6301
+ * Which of the house's Matter devices are the vendor's: rules on who each says it is - its
6302
+ * `vendorId`, `productName`, `macAddresses`, `deviceTypes`, every field of the platform's
6303
+ * `MatterIdentity` - and where it says its model, looked up in the `modelCodes` of the vendor's
6304
+ * drivers that say `"kind": "matter"`.
6305
+ *
6306
+ * A device is commissioned into the house by the owner, so it is added at once to the one vendor
6307
+ * whose rules all hold, or to the platform's own `matter` vendor when none - or more than one - do.
6308
+ */
6309
+ const matterDiscoverySchema = z.strictObject({
6310
+ /** Every condition must hold. All-of, and at least one: a vendor does not take every device. */
6311
+ match: z.array(claimConditionSchema).min(1).max(MAXIMUM_MATCH),
6312
+ /** Where the device says its model; its product id when not said. */
6313
+ model: identityPathSchema.default("productId")
6314
+ });
5741
6315
  /** Validates a whole `discovery.json`. */
5742
6316
  const vendorDiscoverySchema = z.strictObject({
5743
- listen: z.array(listenSourceSchema).min(1).max(MAXIMUM_SOURCES),
6317
+ /** Where the vendor's devices announce themselves; none for one found only through Matter. */
6318
+ listen: z.array(listenSourceSchema).max(MAXIMUM_SOURCES).default([]),
5744
6319
  /** Every condition must hold of an announcement for it to be the vendor's. All-of. */
5745
6320
  match: z.array(claimConditionSchema).max(MAXIMUM_MATCH).default([]),
5746
6321
  probe: discoveryProbeSchema.optional(),
5747
- identity: discoveryIdentitySchema,
6322
+ identity: discoveryIdentitySchema.default({}),
6323
+ matter: matterDiscoverySchema.optional(),
5748
6324
  /**
5749
6325
  * Who adds a device found. `owner` - the default - proposes it on the vendor's
5750
6326
  * page; `automatic` adds it as soon as it is heard, for devices the owner already chose
@@ -5765,7 +6341,12 @@ const vendorDiscoverySchema = z.strictObject({
5765
6341
  state: z.string().min(1).max(64)
5766
6342
  }).optional()
5767
6343
  }).superRefine((discovery, ctx) => {
5768
- if (discovery.probe === void 0 && discovery.identity.model === void 0) ctx.addIssue({
6344
+ if (discovery.listen.length === 0 && discovery.matter === void 0) ctx.addIssue({
6345
+ code: "custom",
6346
+ path: ["listen"],
6347
+ message: "A vendor listens somewhere, or says which Matter devices are its own, or both"
6348
+ });
6349
+ if (discovery.listen.length > 0 && discovery.probe === void 0 && discovery.identity.model === void 0) ctx.addIssue({
5769
6350
  code: "custom",
5770
6351
  path: ["identity", "model"],
5771
6352
  message: "A vendor that does not probe must say where the announcement names the model"
@@ -5842,11 +6423,15 @@ function textAt(payload, path) {
5842
6423
  */
5843
6424
  function identifySighting(plan, payload) {
5844
6425
  const { identity } = plan.discovery;
6426
+ const auth = identity.auth === void 0 ? [] : [identity.auth].flat();
5845
6427
  return {
5846
6428
  externalId: textAt(payload, identity.externalId),
5847
6429
  name: textAt(payload, identity.name),
5848
6430
  modelCode: textAt(payload, identity.model),
5849
- swVersion: textAt(payload, identity.swVersion)
6431
+ swVersion: textAt(payload, identity.swVersion),
6432
+ mac: normalizeMac(textAt(payload, identity.mac)),
6433
+ serialNumber: textAt(payload, identity.serialNumber),
6434
+ needsPassword: auth.some((path) => resolvePath(payload, path) === true)
5850
6435
  };
5851
6436
  }
5852
6437
  /**
@@ -5874,7 +6459,8 @@ function choicesOf(driver) {
5874
6459
  * @returns The association, or null when no driver of the vendor takes the device.
5875
6460
  */
5876
6461
  function associateModel(plan, modelCode, claimedBy) {
5877
- const coded = modelCode === null ? [] : plan.codes.get(modelCode) ?? [];
6462
+ const reached = new Set(plan.drivers.filter((driver) => driver.transport !== MATTER_TRANSPORT).map(({ id }) => id));
6463
+ const coded = modelCode === null ? [] : (plan.codes.get(modelCode) ?? []).filter((entry) => reached.has(entry.driverId));
5878
6464
  if (coded.length > 0) {
5879
6465
  const found = claimedBy === void 0 ? coded.length === 1 ? coded[0] : void 0 : coded.find((entry) => claimedBy(entry.driverId));
5880
6466
  return found === void 0 ? null : {
@@ -5884,7 +6470,7 @@ function associateModel(plan, modelCode, claimedBy) {
5884
6470
  };
5885
6471
  }
5886
6472
  if (claimedBy === void 0) return null;
5887
- const driver = plan.drivers.find((candidate) => claimedBy(candidate.id));
6473
+ const driver = plan.drivers.find((candidate) => reached.has(candidate.id) && claimedBy(candidate.id));
5888
6474
  if (driver === void 0) return null;
5889
6475
  const choices = choicesOf(driver);
5890
6476
  const named = modelCode !== null && choices.includes(modelCode) ? modelCode : null;
@@ -5894,6 +6480,44 @@ function associateModel(plan, modelCode, claimedBy) {
5894
6480
  modelChoices: choices
5895
6481
  };
5896
6482
  }
6483
+ /**
6484
+ * Whether a Matter device is the vendor's, by the rules of its `matter` block.
6485
+ *
6486
+ * @param plan - The vendor's discovery.
6487
+ * @param identity - Who the device says it is.
6488
+ * @returns True when the vendor has a `matter` block and every one of its conditions holds.
6489
+ */
6490
+ function matchesMatter(plan, identity) {
6491
+ return plan.discovery.matter?.match.every((condition) => conditionHolds(condition, identity)) ?? false;
6492
+ }
6493
+ /**
6494
+ * Finds the driver of the vendor's that runs a Matter device of its, and its model.
6495
+ *
6496
+ * The model the device says is looked up in the `modelCodes` of the vendor's Matter drivers; one
6497
+ * it does not map goes to the vendor's Matter driver when it has only one.
6498
+ *
6499
+ * @param plan - The vendor's discovery.
6500
+ * @param identity - Who the device says it is.
6501
+ * @returns The association, or null when no Matter driver of the vendor takes it.
6502
+ */
6503
+ function associateMatter(plan, identity) {
6504
+ const drivers = plan.drivers.filter((driver) => driver.transport === MATTER_TRANSPORT);
6505
+ const modelCode = textAt(identity, plan.discovery.matter?.model ?? "productId");
6506
+ const [first] = modelCode === null ? [] : (plan.codes.get(modelCode) ?? []).filter((entry) => drivers.some((driver) => driver.id === entry.driverId));
6507
+ if (first !== void 0) return {
6508
+ driverId: first.driverId,
6509
+ model: first.models.length === 1 ? first.models[0] ?? null : null,
6510
+ modelChoices: first.models
6511
+ };
6512
+ const [only, other] = drivers;
6513
+ if (only === void 0 || other !== void 0) return null;
6514
+ const choices = choicesOf(only);
6515
+ return {
6516
+ driverId: only.id,
6517
+ model: modelCode !== null && choices.includes(modelCode) ? modelCode : choices.length === 1 ? choices[0] ?? null : null,
6518
+ modelChoices: choices
6519
+ };
6520
+ }
5897
6521
  //#endregion
5898
6522
  //#region ../../node_modules/.pnpm/semver@7.8.5/node_modules/semver/internal/constants.js
5899
6523
  var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
@@ -7293,45 +7917,1157 @@ var require_semver = /* @__PURE__ */ __commonJSMin(((exports, module) => {
7293
7917
  };
7294
7918
  }));
7295
7919
  //#endregion
7296
- //#region ../package-runtime/dist/loader.js
7920
+ //#region ../package-runtime/dist/matter-node.js
7921
+ var import_semver = /* @__PURE__ */ __toESM(require_semver(), 1);
7922
+ /** The clusters this module reads by number, and the platform maps. */
7923
+ const CLUSTER = {
7924
+ identify: 3,
7925
+ onOff: 6,
7926
+ levelControl: 8,
7927
+ descriptor: 29,
7928
+ basicInformation: 40,
7929
+ otaRequestor: 42,
7930
+ powerSource: 47,
7931
+ generalDiagnostics: 51,
7932
+ bridgedBasicInformation: 57,
7933
+ booleanState: 69,
7934
+ electricalPowerMeasurement: 144,
7935
+ electricalEnergyMeasurement: 145,
7936
+ doorLock: 257,
7937
+ windowCovering: 258,
7938
+ thermostat: 513,
7939
+ colorControl: 768,
7940
+ illuminanceMeasurement: 1024,
7941
+ temperatureMeasurement: 1026,
7942
+ pressureMeasurement: 1027,
7943
+ relativeHumidityMeasurement: 1029,
7944
+ occupancySensing: 1030,
7945
+ carbonDioxideMeasurement: 1037
7946
+ };
7947
+ /** The device types this module tells apart, by number. */
7948
+ const DEVICE_TYPE = {
7949
+ aggregator: 14,
7950
+ bridgedNode: 19,
7951
+ contactSensor: 21,
7952
+ waterLeakDetector: 67,
7953
+ onOffLight: 256,
7954
+ dimmableLight: 257,
7955
+ onOffPlugInUnit: 266,
7956
+ dimmablePlugInUnit: 267,
7957
+ colorTemperatureLight: 268,
7958
+ extendedColorLight: 269,
7959
+ mountedDimmableLoadControl: 272
7960
+ };
7961
+ /** The Descriptor's attributes. */
7962
+ const DESCRIPTOR = {
7963
+ deviceTypeList: 0,
7964
+ serverList: 1,
7965
+ partsList: 3
7966
+ };
7297
7967
  /**
7298
- * Reading integrations off disk: the loader `hub` runs and the integration SDK checks a bundle
7299
- * with, so that what passes `nebulahome-integration validate` is what `hub` loads.
7968
+ * The key of one attribute.
7300
7969
  *
7301
- * A bundle is a vendor directory - `manifest.json`, a logo, optionally a `setup.json` of what
7302
- * every device of the vendor shares - holding one driver directory per profile or entry point,
7303
- * each with `driver.json`, its own `setup.json` and the profile or code. It is read in two steps:
7970
+ * @param endpoint - The endpoint.
7971
+ * @param cluster - The cluster.
7972
+ * @param attribute - The attribute.
7973
+ * @returns `<endpoint>/<cluster>/<attribute>`.
7974
+ */
7975
+ function attributePath(endpoint, cluster, attribute) {
7976
+ return `${String(endpoint)}/${String(cluster)}/${String(attribute)}`;
7977
+ }
7978
+ /**
7979
+ * Reads one attribute.
7304
7980
  *
7305
- * 1. {@link readVendorDirectory} reads and checks every file - the schemas, the ids against the
7306
- * folders, the runtime range, the logo, the containers, that every module named is there -
7307
- * and imports nothing. It is all a source tree needs to be checked.
7308
- * 2. {@link instantiateVendor} imports the code and hands it the {@link BundleSdk}: the vendor's
7309
- * own transports, stream sources and account, each driver, and the discovery modules. Who
7310
- * builds the SDK is the caller's - `hub` hands the real one, the SDK's tests a fake.
7981
+ * @param attributes - The node's.
7982
+ * @param endpoint - The endpoint.
7983
+ * @param cluster - The cluster.
7984
+ * @param attribute - The attribute.
7985
+ * @returns Its value, or undefined when the node has none there.
7986
+ */
7987
+ function attributeOf(attributes, endpoint, cluster, attribute) {
7988
+ return attributes[attributePath(endpoint, cluster, attribute)];
7989
+ }
7990
+ /**
7991
+ * Splits an attribute's key.
7311
7992
  *
7312
- * **It is also the seam the catalogue arrives through.** `verify` and `verifyVendor` are called
7313
- * before code is imported, and nothing passes them today. When the catalogue stamps a signature on
7314
- * an approved code bundle, the verifier that checks it is injected there and nothing else changes.
7993
+ * @param path - `<endpoint>/<cluster>/<attribute>`.
7994
+ * @returns Its three numbers, or undefined for a key of another shape.
7995
+ */
7996
+ function splitPath(path) {
7997
+ const [endpoint, cluster, attribute, rest] = path.split("/").map(Number);
7998
+ return rest === void 0 && Number.isInteger(endpoint) && Number.isInteger(cluster) && Number.isInteger(attribute) ? {
7999
+ endpoint: endpoint ?? 0,
8000
+ cluster: cluster ?? 0,
8001
+ attribute: attribute ?? 0
8002
+ } : void 0;
8003
+ }
8004
+ /**
8005
+ * The numbers in a list attribute.
7315
8006
  *
7316
- * One broken driver never stops its siblings, and one broken vendor never stops the others. A
7317
- * failure is collected and reported so the interface can say which directory and why, because
7318
- * the alternative - refusing to start - means one bad download takes the whole house offline.
7319
- * The same goes one level down for a vendor's `discovery.json`: discovery is a convenience on top
7320
- * of adding a device by address, so a broken one is reported and the vendor loads without it.
8007
+ * @param value - The attribute.
8008
+ * @returns Its numbers; none for anything that is not a list of numbers.
7321
8009
  */
7322
- var import_semver = /* @__PURE__ */ __toESM(require_semver(), 1);
7323
- /** The file every vendor is recognised by. */
7324
- const MANIFEST_FILE = "manifest.json";
7325
- /** The file every driver is recognised by. */
7326
- const DRIVER_FILE = "driver.json";
7327
- /** The file a discoverable vendor says how its devices are found in. */
7328
- const DISCOVERY_FILE = "discovery.json";
8010
+ function numbersOf(value) {
8011
+ return Array.isArray(value) ? value.filter((item) => typeof item === "number") : [];
8012
+ }
7329
8013
  /**
7330
- * The most a logo may weigh.
8014
+ * The device types an endpoint declares.
7331
8015
  *
7332
- * It rides inside every catalogue reply, base64-encoded, so a large one slows every page that
7333
- * lists vendors. Generous for an SVG mark or a small PNG, and found at startup rather than on
7334
- * somebody's page.
8016
+ * @param attributes - The node's.
8017
+ * @param endpoint - The endpoint.
8018
+ * @returns Their numbers.
8019
+ */
8020
+ function deviceTypesOf(attributes, endpoint) {
8021
+ const list = attributeOf(attributes, endpoint, CLUSTER.descriptor, DESCRIPTOR.deviceTypeList);
8022
+ return Array.isArray(list) ? list.flatMap((entry) => {
8023
+ const type = entry?.["0"];
8024
+ return typeof type === "number" ? [type] : [];
8025
+ }) : [];
8026
+ }
8027
+ /**
8028
+ * The clusters an endpoint serves.
8029
+ *
8030
+ * @param attributes - The node's.
8031
+ * @param endpoint - The endpoint.
8032
+ * @returns Their numbers, from its Descriptor's server list - or, when that was not read, from the
8033
+ * clusters it has attributes of.
8034
+ */
8035
+ function clustersOf(attributes, endpoint) {
8036
+ const listed = numbersOf(attributeOf(attributes, endpoint, CLUSTER.descriptor, DESCRIPTOR.serverList));
8037
+ if (listed.length > 0) return listed;
8038
+ const found = /* @__PURE__ */ new Set();
8039
+ for (const path of Object.keys(attributes)) {
8040
+ const split = splitPath(path);
8041
+ if (split?.endpoint === endpoint) found.add(split.cluster);
8042
+ }
8043
+ return [...found];
8044
+ }
8045
+ /**
8046
+ * Whether an endpoint serves a cluster.
8047
+ *
8048
+ * @param attributes - The node's.
8049
+ * @param endpoint - The endpoint.
8050
+ * @param cluster - The cluster.
8051
+ * @returns True when it does.
8052
+ */
8053
+ function serves(attributes, endpoint, cluster) {
8054
+ return clustersOf(attributes, endpoint).includes(cluster);
8055
+ }
8056
+ /**
8057
+ * The key the transport and the driver agree a device is reached by.
8058
+ *
8059
+ * @param nodeId - The node.
8060
+ * @param endpoint - The bridged endpoint, or null for the node itself.
8061
+ * @returns `<node>` or `<node>:<endpoint>`.
8062
+ */
8063
+ function matterDeviceKey(nodeId, endpoint) {
8064
+ return endpoint === null ? nodeId : `${nodeId}:${String(endpoint)}`;
8065
+ }
8066
+ /**
8067
+ * The name a device of a node is offered under.
8068
+ *
8069
+ * @param identity - Who it says it is.
8070
+ * @returns What the owner named it in the app it came from, then what it is sold as.
8071
+ */
8072
+ function nameOf$1(identity) {
8073
+ return identity.nodeLabel ?? identity.productLabel ?? identity.productName ?? `Matter device ${identity.endpoint === null ? identity.nodeId : `${identity.nodeId}:${String(identity.endpoint)}`}`;
8074
+ }
8075
+ //#endregion
8076
+ //#region ../package-runtime/dist/matter-mapping.js
8077
+ /**
8078
+ * The platform's mapping of a Matter device onto entities: the one driver every Matter device can
8079
+ * be run by, whoever's integration it is.
8080
+ *
8081
+ * Matter describes itself - device types and clusters on numbered endpoints - so one mapping
8082
+ * covers what any maker ships, and a vendor whose `driver.json` says `"kind": "matter"` gets it
8083
+ * without writing code: its devices are its own, on its page, and mapped here.
8084
+ *
8085
+ * **What is mapped.** Per endpoint: on/off, level and colour (hue and saturation, temperature) as
8086
+ * a light or a switch; a window covering; a door lock; a thermostat; temperature, humidity,
8087
+ * illuminance, pressure and CO₂; occupancy, contact and leak; the battery; power, voltage, current
8088
+ * and energy; and, for the node itself, its firmware. What else a device serves is listed on the
8089
+ * Brokers page as not mapped.
8090
+ *
8091
+ * **Pure throughout**, like every integration: what the transport hands over is the device's
8092
+ * whole attribute record and the paths that changed, so a state is always computed from every
8093
+ * field it needs - a colour's hue with its saturation, a thermostat's setpoint with its mode.
8094
+ */
8095
+ /** The global attribute every cluster carries its features in. */
8096
+ const FEATURE_MAP = 65532;
8097
+ /** How long a lock is given to answer a timed command. */
8098
+ const TIMED_COMMAND_MS = 1e4;
8099
+ 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;
8100
+ /**
8101
+ * A number attribute.
8102
+ *
8103
+ * @param value - The attribute.
8104
+ * @returns It, or undefined when it is not a finite number - null included.
8105
+ */
8106
+ function numberOf(value) {
8107
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
8108
+ }
8109
+ /**
8110
+ * A value held to a range.
8111
+ *
8112
+ * @param value - The value.
8113
+ * @param min - The least.
8114
+ * @param max - The most.
8115
+ * @returns It, within the range.
8116
+ */
8117
+ function clamp(value, min, max) {
8118
+ return Math.min(max, Math.max(min, value));
8119
+ }
8120
+ /**
8121
+ * A fade in Matter's tenths of a second.
8122
+ *
8123
+ * @param transitionMs - The fade the command asks for, if any.
8124
+ * @returns Tenths of a second; 0 for at once.
8125
+ */
8126
+ function tenthsOf(transitionMs) {
8127
+ return typeof transitionMs === "number" ? Math.round(transitionMs / 100) : 0;
8128
+ }
8129
+ /**
8130
+ * A command invoked on a cluster.
8131
+ *
8132
+ * @param endpoint - The endpoint.
8133
+ * @param cluster - The cluster.
8134
+ * @param command - The command, as matter.js names it.
8135
+ * @param payload - Its fields.
8136
+ * @param timedMs - How long a timed command is given, for one that must be timed.
8137
+ * @returns The request.
8138
+ */
8139
+ function invoke(endpoint, cluster, command, payload = {}, timedMs) {
8140
+ return {
8141
+ op: "invoke",
8142
+ args: {
8143
+ endpoint,
8144
+ cluster,
8145
+ command,
8146
+ payload,
8147
+ ...timedMs === void 0 ? {} : { timedMs }
8148
+ }
8149
+ };
8150
+ }
8151
+ /** What every fade-capable command of the lighting clusters carries besides its own fields. */
8152
+ const NO_OPTIONS = {
8153
+ optionsMask: 0,
8154
+ optionsOverride: 0
8155
+ };
8156
+ /**
8157
+ * The light, or switch, an endpoint with On/Off is.
8158
+ *
8159
+ * @param attributes - The device's.
8160
+ * @param endpoint - The endpoint.
8161
+ * @returns The entity.
8162
+ */
8163
+ function onOffEntity(attributes, endpoint) {
8164
+ const types = deviceTypesOf(attributes, endpoint);
8165
+ const isLight = [
8166
+ DEVICE_TYPE.onOffLight,
8167
+ DEVICE_TYPE.dimmableLight,
8168
+ DEVICE_TYPE.colorTemperatureLight,
8169
+ DEVICE_TYPE.extendedColorLight,
8170
+ DEVICE_TYPE.dimmablePlugInUnit,
8171
+ DEVICE_TYPE.mountedDimmableLoadControl
8172
+ ].some((type) => types.includes(type));
8173
+ const hasLevel = isLight && serves(attributes, endpoint, CLUSTER.levelControl);
8174
+ const colorFeatures = serves(attributes, endpoint, CLUSTER.colorControl) ? numberOf(attributeOf(attributes, endpoint, CLUSTER.colorControl, FEATURE_MAP)) ?? 0 : 0;
8175
+ const hasHs = isLight && (colorFeatures & 1) !== 0;
8176
+ const hasTemperature = isLight && (colorFeatures & 16) !== 0;
8177
+ const minMireds = clamp(numberOf(attributeOf(attributes, endpoint, CLUSTER.colorControl, 16395)) ?? 153, 1, 1e3);
8178
+ const maxMireds = clamp(numberOf(attributeOf(attributes, endpoint, CLUSTER.colorControl, 16396)) ?? 500, minMireds, 1e3);
8179
+ const capabilities = {
8180
+ on_off: { hasTransition: false },
8181
+ ...hasLevel ? { level: { hasTransition: true } } : {},
8182
+ ...hasHs ? { color_hs: { hasTransition: true } } : {},
8183
+ ...hasTemperature ? { color_temp: {
8184
+ minMireds,
8185
+ maxMireds,
8186
+ hasTransition: true
8187
+ } } : {}
8188
+ };
8189
+ return {
8190
+ key: isLight ? "light" : "switch",
8191
+ endpoint,
8192
+ clusters: [
8193
+ CLUSTER.onOff,
8194
+ CLUSTER.levelControl,
8195
+ CLUSTER.colorControl
8196
+ ],
8197
+ descriptor: {
8198
+ domain: isLight ? "light" : "switch",
8199
+ name: isLight ? "Light" : "Switch",
8200
+ capabilities
8201
+ },
8202
+ /**
8203
+ * Reads the entity's state.
8204
+ *
8205
+ * @param read - The device's attributes.
8206
+ * @returns The state, or undefined while the device has not said enough.
8207
+ */
8208
+ stateOf: (read) => {
8209
+ const isOn = attributeOf(read, endpoint, CLUSTER.onOff, 0);
8210
+ if (typeof isOn !== "boolean") return;
8211
+ const level = numberOf(attributeOf(read, endpoint, CLUSTER.levelControl, 0));
8212
+ const hue = numberOf(attributeOf(read, endpoint, CLUSTER.colorControl, 0));
8213
+ const saturation = numberOf(attributeOf(read, endpoint, CLUSTER.colorControl, 1));
8214
+ const mireds = numberOf(attributeOf(read, endpoint, CLUSTER.colorControl, 7));
8215
+ return {
8216
+ on_off: { isOn },
8217
+ ...hasLevel && level !== void 0 ? { level: { level: clamp(Math.round(level / 254 * 100), 0, 100) } } : {},
8218
+ ...hasHs && hue !== void 0 && saturation !== void 0 ? { color_hs: {
8219
+ hue: clamp(Math.round(hue / 254 * 360), 0, 360),
8220
+ saturation: clamp(Math.round(saturation / 254 * 100), 0, 100)
8221
+ } } : {},
8222
+ ...hasTemperature && mireds !== void 0 ? { color_temp: { mireds: clamp(Math.round(mireds), 1, 1e3) } } : {}
8223
+ };
8224
+ },
8225
+ /**
8226
+ * Turns a command into a request.
8227
+ *
8228
+ * @param target - The command.
8229
+ * @returns The request, or undefined for a command it does not take.
8230
+ */
8231
+ commandOf: (target) => {
8232
+ const { command } = target;
8233
+ switch (command["command"]) {
8234
+ case "turn_on": return invoke(endpoint, CLUSTER.onOff, "on");
8235
+ case "turn_off": return invoke(endpoint, CLUSTER.onOff, "off");
8236
+ case "toggle": return invoke(endpoint, CLUSTER.onOff, "toggle");
8237
+ case "set_level": {
8238
+ const level = numberOf(command["level"]) ?? 0;
8239
+ return level <= 0 ? invoke(endpoint, CLUSTER.onOff, "off") : invoke(endpoint, CLUSTER.levelControl, "moveToLevelWithOnOff", {
8240
+ level: clamp(Math.round(level / 100 * 254), 1, 254),
8241
+ transitionTime: tenthsOf(command["transitionMs"]),
8242
+ ...NO_OPTIONS
8243
+ });
8244
+ }
8245
+ case "set_color": return invoke(endpoint, CLUSTER.colorControl, "moveToHueAndSaturation", {
8246
+ hue: clamp(Math.round((numberOf(command["hue"]) ?? 0) / 360 * 254), 0, 254),
8247
+ saturation: clamp(Math.round((numberOf(command["saturation"]) ?? 0) / 100 * 254), 0, 254),
8248
+ transitionTime: tenthsOf(command["transitionMs"]),
8249
+ ...NO_OPTIONS
8250
+ });
8251
+ case "set_color_temp": return invoke(endpoint, CLUSTER.colorControl, "moveToColorTemperature", {
8252
+ colorTemperatureMireds: clamp(Math.round(numberOf(command["mireds"]) ?? minMireds), minMireds, maxMireds),
8253
+ transitionTime: tenthsOf(command["transitionMs"]),
8254
+ ...NO_OPTIONS
8255
+ });
8256
+ default: return;
8257
+ }
8258
+ }
8259
+ };
8260
+ }
8261
+ /**
8262
+ * The cover a Window Covering endpoint is. Matter counts how far it is closed, in hundredths of a
8263
+ * percent; the platform counts how far it is open.
8264
+ *
8265
+ * @param attributes - The device's.
8266
+ * @param endpoint - The endpoint.
8267
+ * @returns The entity.
8268
+ */
8269
+ function coverEntity(attributes, endpoint) {
8270
+ const features = numberOf(attributeOf(attributes, endpoint, CLUSTER.windowCovering, FEATURE_MAP)) ?? 0;
8271
+ const hasPosition = (features & 4) !== 0;
8272
+ const hasTilt = (features & 2) !== 0 && (features & 16) !== 0;
8273
+ /**
8274
+ * How far open, from how far closed.
8275
+ *
8276
+ * @param closed - Hundredths of a percent closed.
8277
+ * @returns The percentage open.
8278
+ */
8279
+ const openOf = (closed) => clamp(Math.round(100 - closed / 100), 0, 100);
8280
+ return {
8281
+ key: "cover",
8282
+ endpoint,
8283
+ clusters: [CLUSTER.windowCovering],
8284
+ descriptor: {
8285
+ domain: "cover",
8286
+ name: "Cover",
8287
+ capabilities: { cover: {
8288
+ hasPosition,
8289
+ hasTilt
8290
+ } }
8291
+ },
8292
+ /**
8293
+ * Reads the entity's state.
8294
+ *
8295
+ * @param read - The device's attributes.
8296
+ * @returns The state, or undefined while the device has not said enough.
8297
+ */
8298
+ stateOf: (read) => {
8299
+ const closed = numberOf(attributeOf(read, endpoint, CLUSTER.windowCovering, 14));
8300
+ const tilt = numberOf(attributeOf(read, endpoint, CLUSTER.windowCovering, 15));
8301
+ const status = (numberOf(attributeOf(read, endpoint, CLUSTER.windowCovering, 10)) ?? 0) & 3;
8302
+ if (closed === void 0) return;
8303
+ return { cover: {
8304
+ position: openOf(closed),
8305
+ ...hasTilt && tilt !== void 0 ? { tilt: openOf(tilt) } : {},
8306
+ motion: status === 1 ? "opening" : status === 2 ? "closing" : "stopped"
8307
+ } };
8308
+ },
8309
+ /**
8310
+ * Turns a command into a request.
8311
+ *
8312
+ * @param target - The command.
8313
+ * @returns The request, or undefined for a command it does not take.
8314
+ */
8315
+ commandOf: (target) => {
8316
+ const { command } = target;
8317
+ switch (command["command"]) {
8318
+ case "open": return invoke(endpoint, CLUSTER.windowCovering, "upOrOpen");
8319
+ case "close": return invoke(endpoint, CLUSTER.windowCovering, "downOrClose");
8320
+ case "stop": return invoke(endpoint, CLUSTER.windowCovering, "stopMotion");
8321
+ case "set_position": return invoke(endpoint, CLUSTER.windowCovering, "goToLiftPercentage", { liftPercent100thsValue: Math.round((100 - (numberOf(command["position"]) ?? 0)) * 100) });
8322
+ case "set_tilt": return invoke(endpoint, CLUSTER.windowCovering, "goToTiltPercentage", { tiltPercent100thsValue: Math.round((100 - (numberOf(command["tilt"]) ?? 0)) * 100) });
8323
+ default: return;
8324
+ }
8325
+ }
8326
+ };
8327
+ }
8328
+ /**
8329
+ * The lock a Door Lock endpoint is.
8330
+ *
8331
+ * @param endpoint - The endpoint.
8332
+ * @returns The entity.
8333
+ */
8334
+ function lockEntity(endpoint) {
8335
+ return {
8336
+ key: "lock",
8337
+ endpoint,
8338
+ clusters: [CLUSTER.doorLock],
8339
+ descriptor: {
8340
+ domain: "lock",
8341
+ name: "Lock",
8342
+ capabilities: { lock: { hasCode: false } }
8343
+ },
8344
+ /**
8345
+ * Reads the entity's state.
8346
+ *
8347
+ * @param read - The device's attributes.
8348
+ * @returns The state, or undefined while the device has not said enough.
8349
+ */
8350
+ stateOf: (read) => {
8351
+ switch (numberOf(attributeOf(read, endpoint, CLUSTER.doorLock, 0))) {
8352
+ case 0: return { lock: { lockState: "jammed" } };
8353
+ case 1: return { lock: { lockState: "locked" } };
8354
+ case 2:
8355
+ case 3: return { lock: { lockState: "unlocked" } };
8356
+ default: return;
8357
+ }
8358
+ },
8359
+ /**
8360
+ * Turns a command into a request.
8361
+ *
8362
+ * @param target - The command.
8363
+ * @returns The request, or undefined for a command it does not take.
8364
+ */
8365
+ commandOf: (target) => {
8366
+ const { command } = target;
8367
+ switch (command["command"]) {
8368
+ case "lock": return invoke(endpoint, CLUSTER.doorLock, "lockDoor", {}, TIMED_COMMAND_MS);
8369
+ case "unlock": return invoke(endpoint, CLUSTER.doorLock, "unlockDoor", {}, TIMED_COMMAND_MS);
8370
+ default: return;
8371
+ }
8372
+ }
8373
+ };
8374
+ }
8375
+ /** Matter's system modes, as the platform's thermostat modes. */
8376
+ const SYSTEM_MODES = {
8377
+ 0: "off",
8378
+ 1: "auto",
8379
+ 3: "cool",
8380
+ 4: "heat",
8381
+ 5: "heat",
8382
+ 6: "cool",
8383
+ 7: "fan_only",
8384
+ 8: "dry",
8385
+ 9: "auto"
8386
+ };
8387
+ /** The platform's thermostat modes, as the system mode written for each. */
8388
+ const MODE_VALUES = {
8389
+ off: 0,
8390
+ auto: 1,
8391
+ cool: 3,
8392
+ heat: 4,
8393
+ fan_only: 7,
8394
+ dry: 8
8395
+ };
8396
+ /**
8397
+ * The thermostat a Thermostat endpoint is, its humidity beside it when the endpoint measures it.
8398
+ *
8399
+ * @param attributes - The device's.
8400
+ * @param endpoint - The endpoint.
8401
+ * @returns The entity.
8402
+ */
8403
+ function thermostatEntity(attributes, endpoint) {
8404
+ const features = numberOf(attributeOf(attributes, endpoint, CLUSTER.thermostat, FEATURE_MAP)) ?? 1;
8405
+ const canHeat = (features & 1) !== 0;
8406
+ const canCool = (features & 2) !== 0;
8407
+ const hasAuto = (features & 32) !== 0;
8408
+ /**
8409
+ * A temperature attribute, in degrees.
8410
+ *
8411
+ * @param read - The device's attributes.
8412
+ * @param attribute - The attribute, in hundredths of a degree.
8413
+ * @returns The degrees, or undefined.
8414
+ */
8415
+ const degreesOf = (read, attribute) => {
8416
+ const value = numberOf(attributeOf(read, endpoint, CLUSTER.thermostat, attribute));
8417
+ return value === void 0 ? void 0 : value / 100;
8418
+ };
8419
+ const min = degreesOf(attributes, canHeat ? 21 : 23) ?? 7;
8420
+ const max = degreesOf(attributes, canHeat ? 22 : 24) ?? 30;
8421
+ return {
8422
+ key: "thermostat",
8423
+ endpoint,
8424
+ clusters: [CLUSTER.thermostat, CLUSTER.relativeHumidityMeasurement],
8425
+ descriptor: {
8426
+ domain: "climate",
8427
+ name: "Thermostat",
8428
+ capabilities: { thermostat: {
8429
+ supportedModes: [
8430
+ "off",
8431
+ ...canHeat ? ["heat"] : [],
8432
+ ...canCool ? ["cool"] : [],
8433
+ ...hasAuto ? ["auto"] : []
8434
+ ],
8435
+ minTemperature: Math.min(min, max),
8436
+ maxTemperature: Math.max(min, max),
8437
+ temperatureStep: .5
8438
+ } }
8439
+ },
8440
+ /**
8441
+ * Reads the entity's state.
8442
+ *
8443
+ * @param read - The device's attributes.
8444
+ * @returns The state, or undefined while the device has not said enough.
8445
+ */
8446
+ stateOf: (read) => {
8447
+ const current = degreesOf(read, 0);
8448
+ const mode = SYSTEM_MODES[numberOf(attributeOf(read, endpoint, CLUSTER.thermostat, 28)) ?? 0];
8449
+ const target = degreesOf(read, mode === "cool" ? 17 : 18) ?? degreesOf(read, 17);
8450
+ const running = numberOf(attributeOf(read, endpoint, CLUSTER.thermostat, 41)) ?? 0;
8451
+ const humidity = numberOf(attributeOf(read, endpoint, CLUSTER.relativeHumidityMeasurement, 0));
8452
+ if (current === void 0 || target === void 0 || mode === void 0) return;
8453
+ return { thermostat: {
8454
+ currentTemperature: current,
8455
+ targetTemperature: target,
8456
+ mode,
8457
+ action: mode === "off" ? "off" : (running & 9) !== 0 ? "heating" : (running & 18) !== 0 ? "cooling" : (running & 100) !== 0 ? "fan" : "idle",
8458
+ ...humidity === void 0 ? {} : { humidity: clamp(humidity / 100, 0, 100) }
8459
+ } };
8460
+ },
8461
+ /**
8462
+ * Turns a command into a request.
8463
+ *
8464
+ * @param target - The command.
8465
+ * @param last - The entity's last state.
8466
+ * @returns The request, or undefined for a command it does not take.
8467
+ */
8468
+ commandOf: (target, last) => {
8469
+ const { command } = target;
8470
+ if (command["command"] === "set_target") {
8471
+ const isCooling = last?.thermostat?.mode === "cool" || !canHeat;
8472
+ return {
8473
+ op: "write",
8474
+ args: {
8475
+ endpoint,
8476
+ cluster: CLUSTER.thermostat,
8477
+ attribute: isCooling ? 17 : 18,
8478
+ value: Math.round((numberOf(command["temperature"]) ?? 0) * 100)
8479
+ }
8480
+ };
8481
+ }
8482
+ const mode = command["mode"];
8483
+ const value = command["command"] === "set_mode" && typeof mode === "string" && mode in MODE_VALUES ? MODE_VALUES[mode] : void 0;
8484
+ return value === void 0 ? void 0 : {
8485
+ op: "write",
8486
+ args: {
8487
+ endpoint,
8488
+ cluster: CLUSTER.thermostat,
8489
+ attribute: 28,
8490
+ value
8491
+ }
8492
+ };
8493
+ }
8494
+ };
8495
+ }
8496
+ /**
8497
+ * Hundredths, as a number.
8498
+ *
8499
+ * @param value - The attribute.
8500
+ * @returns It divided by 100.
8501
+ */
8502
+ function hundredths(value) {
8503
+ const number = numberOf(value);
8504
+ return number === void 0 ? void 0 : number / 100;
8505
+ }
8506
+ /** The sensors read as one value of one attribute. */
8507
+ const NUMERIC_SENSORS = [
8508
+ {
8509
+ key: "temperature",
8510
+ name: "Temperature",
8511
+ cluster: CLUSTER.temperatureMeasurement,
8512
+ attribute: 0,
8513
+ deviceClass: "temperature",
8514
+ unit: "°C",
8515
+ displayPrecision: 1,
8516
+ scale: hundredths
8517
+ },
8518
+ {
8519
+ key: "humidity",
8520
+ name: "Humidity",
8521
+ cluster: CLUSTER.relativeHumidityMeasurement,
8522
+ attribute: 0,
8523
+ deviceClass: "humidity",
8524
+ unit: "%",
8525
+ displayPrecision: 0,
8526
+ scale: hundredths
8527
+ },
8528
+ {
8529
+ key: "illuminance",
8530
+ name: "Illuminance",
8531
+ cluster: CLUSTER.illuminanceMeasurement,
8532
+ attribute: 0,
8533
+ deviceClass: "illuminance",
8534
+ unit: "lx",
8535
+ displayPrecision: 0,
8536
+ /**
8537
+ * Reads the attribute.
8538
+ *
8539
+ * @param value - The attribute.
8540
+ * @returns The number, or undefined.
8541
+ */
8542
+ scale: (value) => {
8543
+ const measured = numberOf(value);
8544
+ return measured === void 0 ? void 0 : measured === 0 ? 0 : 10 ** ((measured - 1) / 1e4);
8545
+ }
8546
+ },
8547
+ {
8548
+ key: "pressure",
8549
+ name: "Pressure",
8550
+ cluster: CLUSTER.pressureMeasurement,
8551
+ attribute: 0,
8552
+ deviceClass: "atmospheric_pressure",
8553
+ unit: "hPa",
8554
+ displayPrecision: 0,
8555
+ scale: numberOf
8556
+ },
8557
+ {
8558
+ key: "carbon_dioxide",
8559
+ name: "Carbon dioxide",
8560
+ cluster: CLUSTER.carbonDioxideMeasurement,
8561
+ attribute: 0,
8562
+ deviceClass: "carbon_dioxide",
8563
+ unit: "ppm",
8564
+ displayPrecision: 0,
8565
+ scale: numberOf
8566
+ },
8567
+ {
8568
+ key: "battery",
8569
+ name: "Battery",
8570
+ cluster: CLUSTER.powerSource,
8571
+ attribute: 12,
8572
+ deviceClass: "battery",
8573
+ unit: "%",
8574
+ displayPrecision: 0,
8575
+ /**
8576
+ * Reads the attribute.
8577
+ *
8578
+ * @param value - The attribute.
8579
+ * @returns The number, or undefined.
8580
+ */
8581
+ scale: (value) => {
8582
+ const halves = numberOf(value);
8583
+ return halves === void 0 ? void 0 : clamp(halves / 2, 0, 100);
8584
+ }
8585
+ },
8586
+ {
8587
+ key: "power",
8588
+ name: "Power",
8589
+ cluster: CLUSTER.electricalPowerMeasurement,
8590
+ attribute: 8,
8591
+ deviceClass: "power",
8592
+ unit: "mW",
8593
+ displayPrecision: 1,
8594
+ scale: numberOf
8595
+ },
8596
+ {
8597
+ key: "voltage",
8598
+ name: "Voltage",
8599
+ cluster: CLUSTER.electricalPowerMeasurement,
8600
+ attribute: 4,
8601
+ deviceClass: "voltage",
8602
+ unit: "mV",
8603
+ displayPrecision: 1,
8604
+ scale: numberOf
8605
+ },
8606
+ {
8607
+ key: "current",
8608
+ name: "Current",
8609
+ cluster: CLUSTER.electricalPowerMeasurement,
8610
+ attribute: 5,
8611
+ deviceClass: "current",
8612
+ unit: "mA",
8613
+ displayPrecision: 2,
8614
+ scale: numberOf
8615
+ },
8616
+ {
8617
+ key: "energy",
8618
+ name: "Energy",
8619
+ cluster: CLUSTER.electricalEnergyMeasurement,
8620
+ attribute: 1,
8621
+ deviceClass: "energy",
8622
+ unit: "mWh",
8623
+ stateClass: "total_increasing",
8624
+ displayPrecision: 2,
8625
+ /**
8626
+ * Reads the attribute.
8627
+ *
8628
+ * @param value - The attribute.
8629
+ * @returns The number, or undefined.
8630
+ */
8631
+ scale: (value) => numberOf(value?.["0"])
8632
+ }
8633
+ ];
8634
+ /**
8635
+ * A numeric sensor of one endpoint.
8636
+ *
8637
+ * @param sensor - Which.
8638
+ * @param endpoint - The endpoint.
8639
+ * @returns The entity, reporting in the class's canonical unit.
8640
+ */
8641
+ function numericEntity(sensor, endpoint) {
8642
+ const unitOfMeasurement = resolveCanonicalUnit(sensor.deviceClass) ?? sensor.unit;
8643
+ const stateClass = resolveStateClass(sensor.deviceClass, sensor.stateClass);
8644
+ return {
8645
+ key: sensor.key,
8646
+ endpoint,
8647
+ clusters: [sensor.cluster],
8648
+ attribute: sensor.attribute,
8649
+ descriptor: {
8650
+ domain: "sensor",
8651
+ name: sensor.name,
8652
+ capabilities: { sensor_numeric: {} },
8653
+ unitOfMeasurement,
8654
+ deviceClass: sensor.deviceClass,
8655
+ ...stateClass === void 0 ? {} : { stateClass },
8656
+ ...sensor.displayPrecision === void 0 ? {} : { displayPrecision: sensor.displayPrecision }
8657
+ },
8658
+ /**
8659
+ * Reads the entity's state.
8660
+ *
8661
+ * @param read - The device's attributes.
8662
+ * @returns The state, or undefined while the device has not said enough.
8663
+ */
8664
+ stateOf: (read) => {
8665
+ const value = sensor.scale(attributeOf(read, endpoint, sensor.cluster, sensor.attribute));
8666
+ const canonical = value === void 0 ? void 0 : toCanonical(sensor.deviceClass, value, sensor.unit);
8667
+ return canonical === void 0 ? void 0 : { sensor_numeric: { value: canonical } };
8668
+ }
8669
+ };
8670
+ }
8671
+ /**
8672
+ * A binary sensor of one endpoint.
8673
+ *
8674
+ * @param endpoint - The endpoint.
8675
+ * @param spec - What it is.
8676
+ * @param spec.key - Its kind.
8677
+ * @param spec.name - Its name.
8678
+ * @param spec.icon - Its icon.
8679
+ * @param spec.cluster - The cluster it reads.
8680
+ * @param spec.isOn - How the attribute reads as on.
8681
+ * @returns The entity.
8682
+ */
8683
+ function binaryEntity(endpoint, spec) {
8684
+ return {
8685
+ key: spec.key,
8686
+ endpoint,
8687
+ clusters: [spec.cluster],
8688
+ descriptor: {
8689
+ domain: "binary_sensor",
8690
+ name: spec.name,
8691
+ icon: spec.icon,
8692
+ capabilities: { sensor_binary: {} }
8693
+ },
8694
+ /**
8695
+ * Reads the entity's state.
8696
+ *
8697
+ * @param read - The device's attributes.
8698
+ * @returns The state, or undefined while the device has not said enough.
8699
+ */
8700
+ stateOf: (read) => {
8701
+ const isOn = spec.isOn(attributeOf(read, endpoint, spec.cluster, 0));
8702
+ return isOn === void 0 ? void 0 : { sensor_binary: { isOn } };
8703
+ }
8704
+ };
8705
+ }
8706
+ /**
8707
+ * A boolean, as it is.
8708
+ *
8709
+ * @param value - The attribute.
8710
+ * @returns It, or undefined when it is not one.
8711
+ */
8712
+ function booleanOf(value) {
8713
+ return typeof value === "boolean" ? value : void 0;
8714
+ }
8715
+ /**
8716
+ * The firmware of the node itself.
8717
+ *
8718
+ * @returns The entity, reading what the node runs, what is on offer and how an install goes.
8719
+ */
8720
+ function firmwareEntity() {
8721
+ return {
8722
+ key: "firmware",
8723
+ endpoint: 0,
8724
+ clusters: [CLUSTER.basicInformation, CLUSTER.otaRequestor],
8725
+ descriptor: {
8726
+ domain: "update",
8727
+ name: "Firmware",
8728
+ capabilities: { update: {
8729
+ canInstall: true,
8730
+ hasProgress: true
8731
+ } }
8732
+ },
8733
+ /**
8734
+ * Reads the entity's state.
8735
+ *
8736
+ * @param read - The device's attributes.
8737
+ * @param update - The firmware on offer.
8738
+ * @returns The state.
8739
+ */
8740
+ stateOf: (read, update) => {
8741
+ const text = attributeOf(read, 0, CLUSTER.basicInformation, 10);
8742
+ const number = numberOf(attributeOf(read, 0, CLUSTER.basicInformation, 9));
8743
+ const installed = typeof text === "string" && text !== "" ? text : number === void 0 ? null : String(number);
8744
+ const updating = numberOf(attributeOf(read, 0, CLUSTER.otaRequestor, 2));
8745
+ const progress = numberOf(attributeOf(read, 0, CLUSTER.otaRequestor, 3));
8746
+ const isInstalling = updating === 4 || updating === 5;
8747
+ return { update: {
8748
+ installedVersion: installed?.slice(0, 64) ?? null,
8749
+ latestVersion: update?.softwareVersionString.slice(0, 64) ?? null,
8750
+ isInstalling,
8751
+ progress: isInstalling && progress !== void 0 ? clamp(progress, 0, 100) : null
8752
+ } };
8753
+ },
8754
+ /**
8755
+ * Turns a command into a request.
8756
+ *
8757
+ * @param target - The command.
8758
+ * @returns The request, or undefined for a command it does not take.
8759
+ */
8760
+ commandOf: (target) => target.command["command"] === "install" ? {
8761
+ op: "update",
8762
+ args: {}
8763
+ } : void 0
8764
+ };
8765
+ }
8766
+ /**
8767
+ * The entities one endpoint serves.
8768
+ *
8769
+ * @param attributes - The device's.
8770
+ * @param endpoint - The endpoint.
8771
+ * @returns Its entities, before their object ids are settled.
8772
+ */
8773
+ function draftsOf(attributes, endpoint) {
8774
+ /**
8775
+ * Whether the endpoint serves a cluster.
8776
+ *
8777
+ * @param cluster - The cluster.
8778
+ * @returns True when it does.
8779
+ */
8780
+ const has = (cluster) => serves(attributes, endpoint, cluster);
8781
+ const types = deviceTypesOf(attributes, endpoint);
8782
+ const drafts = [];
8783
+ if (has(CLUSTER.onOff)) drafts.push(onOffEntity(attributes, endpoint));
8784
+ if (has(CLUSTER.windowCovering)) drafts.push(coverEntity(attributes, endpoint));
8785
+ if (has(CLUSTER.doorLock)) drafts.push(lockEntity(endpoint));
8786
+ const hasThermostat = has(CLUSTER.thermostat);
8787
+ if (hasThermostat) drafts.push(thermostatEntity(attributes, endpoint));
8788
+ for (const sensor of NUMERIC_SENSORS) {
8789
+ const isThermostatHumidity = hasThermostat && sensor.cluster === CLUSTER.relativeHumidityMeasurement;
8790
+ if (has(sensor.cluster) && !isThermostatHumidity && attributeOf(attributes, endpoint, sensor.cluster, sensor.attribute) !== void 0) drafts.push(numericEntity(sensor, endpoint));
8791
+ }
8792
+ if (has(CLUSTER.occupancySensing)) drafts.push(binaryEntity(endpoint, {
8793
+ key: "motion",
8794
+ name: "Motion",
8795
+ icon: "motion",
8796
+ cluster: CLUSTER.occupancySensing,
8797
+ /**
8798
+ * Reads the attribute as on or off.
8799
+ *
8800
+ * @param value - The attribute.
8801
+ * @returns Whether it is on, or undefined.
8802
+ */
8803
+ isOn: (value) => {
8804
+ const bits = numberOf(value);
8805
+ return bits === void 0 ? void 0 : (bits & 1) !== 0;
8806
+ }
8807
+ }));
8808
+ if (has(CLUSTER.booleanState)) {
8809
+ const isContact = types.includes(DEVICE_TYPE.contactSensor);
8810
+ const isLeak = types.includes(DEVICE_TYPE.waterLeakDetector);
8811
+ drafts.push(binaryEntity(endpoint, {
8812
+ key: isContact ? "contact" : isLeak ? "leak" : "state",
8813
+ name: isContact ? "Contact" : isLeak ? "Leak" : "State",
8814
+ icon: isContact ? "door" : isLeak ? "water" : "sensor",
8815
+ cluster: CLUSTER.booleanState,
8816
+ /**
8817
+ * Reads the attribute as on or off.
8818
+ *
8819
+ * @param value - The attribute.
8820
+ * @returns Whether it is on, or undefined.
8821
+ */
8822
+ isOn: (value) => {
8823
+ const state = booleanOf(value);
8824
+ return state === void 0 ? void 0 : isContact ? !state : state;
8825
+ }
8826
+ }));
8827
+ }
8828
+ return drafts;
8829
+ }
8830
+ /**
8831
+ * The entities of one device of a node.
8832
+ *
8833
+ * Object ids are the entity's kind - `light`, `temperature` - with the endpoint's number after it
8834
+ * when the kind is on more than one endpoint: `switch_1`, `switch_2`. They follow from the device's
8835
+ * structure alone, so they are the same at every start.
8836
+ *
8837
+ * @param device - The device.
8838
+ * @returns Its entities.
8839
+ */
8840
+ function matterEntitiesOf(device) {
8841
+ const drafts = device.endpoints.flatMap((endpoint) => draftsOf(device.attributes, endpoint));
8842
+ if (device.endpoint === null && serves(device.attributes, 0, CLUSTER.otaRequestor)) drafts.push(firmwareEntity());
8843
+ const counts = /* @__PURE__ */ new Map();
8844
+ for (const draft of drafts) counts.set(draft.key, (counts.get(draft.key) ?? 0) + 1);
8845
+ return drafts.map(({ key, descriptor, ...rest }) => {
8846
+ const isShared = (counts.get(key) ?? 0) > 1;
8847
+ const objectId = isShared ? `${key}_${String(rest.endpoint)}` : key;
8848
+ return {
8849
+ ...rest,
8850
+ objectId,
8851
+ descriptor: {
8852
+ ...descriptor,
8853
+ objectId,
8854
+ name: isShared ? `${descriptor.name} ${String(rest.endpoint)}` : descriptor.name,
8855
+ link: { matter: {
8856
+ endpoint: rest.endpoint,
8857
+ cluster: rest.clusters[0] ?? 0,
8858
+ attribute: rest.attribute ?? 0
8859
+ } }
8860
+ }
8861
+ };
8862
+ });
8863
+ }
8864
+ /** Reads a device handed over by the transport, refusing anything else. */
8865
+ const deviceSnapshotSchema = z.object({
8866
+ nodeId: z.string().min(1),
8867
+ endpoint: z.int().min(0).nullable(),
8868
+ endpoints: z.array(z.int().min(0)),
8869
+ isAvailable: z.boolean(),
8870
+ identity: matterIdentitySchema,
8871
+ attributes: z.record(z.string(), z.unknown())
8872
+ });
8873
+ /** Reads what the transport delivers. */
8874
+ const inboundSchema = z.object({
8875
+ device: deviceSnapshotSchema,
8876
+ changed: z.array(z.string()).nullable(),
8877
+ update: z.object({
8878
+ softwareVersion: z.number(),
8879
+ softwareVersionString: z.string()
8880
+ }).nullable().optional()
8881
+ });
8882
+ /**
8883
+ * A device, read from what identification or a claim holds.
8884
+ *
8885
+ * @param value - What it holds.
8886
+ * @returns The device, or undefined when it is not one.
8887
+ */
8888
+ function deviceOf(value) {
8889
+ const parsed = deviceSnapshotSchema.safeParse(value);
8890
+ return parsed.success ? parsed.data : void 0;
8891
+ }
8892
+ /**
8893
+ * Whether an entity is computed from one of the paths that changed.
8894
+ *
8895
+ * @param entity - The entity.
8896
+ * @param changed - The paths, or null for everything.
8897
+ * @returns True when it should be read again.
8898
+ */
8899
+ function isTouched(entity, changed) {
8900
+ return changed === null || changed.some((path) => {
8901
+ const split = splitPath(path);
8902
+ return split?.endpoint === entity.endpoint && entity.clusters.includes(split.cluster) && (entity.attribute === void 0 || split.attribute === entity.attribute);
8903
+ });
8904
+ }
8905
+ /**
8906
+ * Builds the Matter driver of a vendor: the platform's own, or one whose `driver.json` says
8907
+ * `"kind": "matter"`.
8908
+ *
8909
+ * @param manifest - The driver's.
8910
+ * @param manifest.id - Its kind, `vendor/driver`.
8911
+ * @returns The integration.
8912
+ */
8913
+ function createMatterIntegration(manifest) {
8914
+ /**
8915
+ * The device a claim was made for.
8916
+ *
8917
+ * @param context - The instance's mapping context.
8918
+ * @returns The device.
8919
+ * @throws {ValidationError} When the claim holds no device - which identification never makes.
8920
+ */
8921
+ const claimed = (context) => {
8922
+ const device = deviceOf(context.claim.descriptor);
8923
+ if (device === void 0) throw new ValidationError(`${manifest.id} holds a claim that is not a Matter device`, { details: { integration: manifest.id } });
8924
+ return device;
8925
+ };
8926
+ return {
8927
+ id: manifest.id,
8928
+ transport: MATTER_TRANSPORT,
8929
+ optionsSchema: jsonObjectSchema,
8930
+ discovery: {},
8931
+ /**
8932
+ * Claims a Matter device identification found.
8933
+ *
8934
+ * @param discovered - What the transport handed over.
8935
+ * @returns The claim, or null for anything that is not a Matter device.
8936
+ */
8937
+ claim: (discovered) => {
8938
+ const device = deviceOf(discovered.payload);
8939
+ return device === void 0 ? null : {
8940
+ deviceKey: discovered.deviceKey,
8941
+ externalId: matterDeviceKey(device.nodeId, device.endpoint),
8942
+ descriptor: device
8943
+ };
8944
+ },
8945
+ /**
8946
+ * Subscribes to nothing: the controller already follows every attribute of every node.
8947
+ *
8948
+ * @returns Nothing.
8949
+ */
8950
+ subscriptions: () => [],
8951
+ /**
8952
+ * Describes the device and its entities.
8953
+ *
8954
+ * @param claim - The claim.
8955
+ * @returns The device.
8956
+ * @throws {ValidationError} When the claim holds no Matter device.
8957
+ */
8958
+ describe: (claim) => {
8959
+ const device = deviceOf(claim.descriptor);
8960
+ if (device === void 0) throw new ValidationError(`${manifest.id} cannot describe a claim with no Matter device`, { details: { integration: manifest.id } });
8961
+ const { identity } = device;
8962
+ const mac = identity.macAddresses.map(normalizeMac).find((each) => each !== null);
8963
+ return {
8964
+ externalId: claim.externalId,
8965
+ name: nameOf$1(identity).slice(0, 128),
8966
+ ...mac === void 0 ? {} : { mac },
8967
+ ...identity.serialNumber === null ? {} : { serialNumber: identity.serialNumber },
8968
+ ...identity.vendorName === null ? {} : { manufacturer: identity.vendorName },
8969
+ ...identity.productName === null ? {} : { model: identity.productName },
8970
+ ...identity.softwareVersionString === null ? {} : { swVersion: identity.softwareVersionString.slice(0, 64) },
8971
+ ...identity.hardwareVersionString === null ? {} : { hwVersion: identity.hardwareVersionString.slice(0, 64) },
8972
+ ...device.endpoint === null ? {} : { viaExternalId: device.nodeId },
8973
+ entities: matterEntitiesOf(device).map((entity) => entity.descriptor)
8974
+ };
8975
+ },
8976
+ /**
8977
+ * Turns what changed into reports, one per entity it is about.
8978
+ *
8979
+ * @param message - What the transport delivered.
8980
+ * @param context - The identifiers the hub assigned.
8981
+ * @returns The reports.
8982
+ */
8983
+ toState: (message, context) => {
8984
+ const parsed = inboundSchema.safeParse(message.payload);
8985
+ if (!parsed.success) return [];
8986
+ const { device, changed, update } = parsed.data;
8987
+ return matterEntitiesOf(device).flatMap((entity) => {
8988
+ const entityId = context.entities.get(entity.objectId);
8989
+ if (entityId === void 0 || !isTouched(entity, changed)) return [];
8990
+ const state = entity.stateOf(device.attributes, update);
8991
+ return state === void 0 ? [] : [{
8992
+ entityId,
8993
+ state,
8994
+ attributes: {},
8995
+ isAvailable: device.isAvailable
8996
+ }];
8997
+ });
8998
+ },
8999
+ /**
9000
+ * Turns a command into a request.
9001
+ *
9002
+ * @param target - The entity, the capability and the command.
9003
+ * @param context - The claim and the last states.
9004
+ * @returns The request.
9005
+ * @throws {ValidationError} When the entity does not take the command.
9006
+ */
9007
+ toCommand: (target, context) => {
9008
+ const request = matterEntitiesOf(claimed(context)).find((candidate) => context.entities.get(candidate.objectId) === target.entityId)?.commandOf?.(target, context.lastState(target.entityId));
9009
+ if (request === void 0) throw new ValidationError(`${manifest.id} does not take ${target.capability}.${JSON.stringify(target.command["command"])} on ${target.entityId}`, { details: {
9010
+ integration: manifest.id,
9011
+ entityId: target.entityId
9012
+ } });
9013
+ return {
9014
+ deviceKey: context.claim.deviceKey,
9015
+ op: request.op,
9016
+ args: request.args
9017
+ };
9018
+ },
9019
+ /**
9020
+ * Reads the firmware the device runs now.
9021
+ *
9022
+ * @param message - What the transport delivered.
9023
+ * @returns The version, when the device says it.
9024
+ */
9025
+ deviceInfo: (message) => {
9026
+ const parsed = inboundSchema.safeParse(message.payload);
9027
+ const version = parsed.success ? parsed.data.device.identity.softwareVersionString : null;
9028
+ return version === null ? void 0 : { swVersion: version.slice(0, 64) };
9029
+ }
9030
+ };
9031
+ }
9032
+ //#endregion
9033
+ //#region ../package-runtime/dist/loader.js
9034
+ /**
9035
+ * Reading integrations off disk: the loader `hub` runs and the integration SDK checks a bundle
9036
+ * with, so that what passes `nebulahome-integration validate` is what `hub` loads.
9037
+ *
9038
+ * A bundle is a vendor directory - `manifest.json`, a logo, optionally a `setup.json` of what
9039
+ * every device of the vendor shares - holding one driver directory per profile or entry point,
9040
+ * each with `driver.json`, its own `setup.json` and the profile or code. It is read in two steps:
9041
+ *
9042
+ * 1. {@link readVendorDirectory} reads and checks every file - the schemas, the ids against the
9043
+ * folders, the runtime range, the logo, the containers, that every module named is there -
9044
+ * and imports nothing. It is all a source tree needs to be checked.
9045
+ * 2. {@link instantiateVendor} imports the code and hands it the {@link BundleSdk}: the vendor's
9046
+ * own transports, stream sources and account, each driver, and the discovery modules. Who
9047
+ * builds the SDK is the caller's - `hub` hands the real one, the SDK's tests a fake.
9048
+ *
9049
+ * **It is also the seam the catalogue arrives through.** `verify` and `verifyVendor` are called
9050
+ * before code is imported, and nothing passes them today. When the catalogue stamps a signature on
9051
+ * an approved code bundle, the verifier that checks it is injected there and nothing else changes.
9052
+ *
9053
+ * One broken driver never stops its siblings, and one broken vendor never stops the others. A
9054
+ * failure is collected and reported so the interface can say which directory and why, because
9055
+ * the alternative - refusing to start - means one bad download takes the whole house offline.
9056
+ * The same goes one level down for a vendor's `discovery.json`: discovery is a convenience on top
9057
+ * of adding a device by address, so a broken one is reported and the vendor loads without it.
9058
+ */
9059
+ /** The file every vendor is recognised by. */
9060
+ const MANIFEST_FILE = "manifest.json";
9061
+ /** The file every driver is recognised by. */
9062
+ const DRIVER_FILE = "driver.json";
9063
+ /** The file a discoverable vendor says how its devices are found in. */
9064
+ const DISCOVERY_FILE = "discovery.json";
9065
+ /**
9066
+ * The most a logo may weigh.
9067
+ *
9068
+ * It rides inside every catalogue reply, base64-encoded, so a large one slows every page that
9069
+ * lists vendors. Generous for an SVG mark or a small PNG, and found at startup rather than on
9070
+ * somebody's page.
7335
9071
  */
7336
9072
  const LOGO_MAXIMUM_BYTES = 65536;
7337
9073
  /** The image types a logo may be, by the extension the manifest names. */
@@ -7537,6 +9273,7 @@ async function readDriver(vendor, directory, resolve) {
7537
9273
  profile
7538
9274
  };
7539
9275
  }
9276
+ if (manifest.kind === "matter") return identity;
7540
9277
  return {
7541
9278
  ...identity,
7542
9279
  entry: await moduleOf(resolve, directory, manifest.entry ?? "", manifest.id)
@@ -7576,6 +9313,7 @@ function planDiscovery(vendor, discovery, drivers) {
7576
9313
  const plan = resolveDiscovery(vendor.id, discovery, drivers.map((driver) => ({
7577
9314
  id: driver.driverId,
7578
9315
  name: driver.driverName,
9316
+ transport: driver.manifest.transport,
7579
9317
  models: driver.manifest.models,
7580
9318
  modelCodes: driver.manifest.modelCodes
7581
9319
  })));
@@ -7719,6 +9457,10 @@ async function instantiateDriver(driver, sdk, options) {
7719
9457
  ...identity,
7720
9458
  integration: createDeclarativeIntegration(driver.manifest, profile)
7721
9459
  };
9460
+ if (driver.manifest.kind === "matter") return {
9461
+ ...identity,
9462
+ integration: createMatterIntegration(driver.manifest)
9463
+ };
7722
9464
  const exported = await defaultOf(options.importModule ?? importFile, entry ?? "");
7723
9465
  const integration = typeof exported === "function" ? exported(sdk) : exported;
7724
9466
  if (integration === null || typeof integration !== "object") throw new Error(`${driver.manifest.id} does not default-export an integration`);
@@ -7863,4 +9605,4 @@ async function instantiateVendor(declaration, options) {
7863
9605
  };
7864
9606
  }
7865
9607
  //#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 };
9608
+ 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 };