@nebulahome/integration-sdk 1.1.0 → 1.4.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.
@@ -534,9 +534,9 @@ const buttonCommandSchema = z.discriminatedUnion("command", [z.object({ command:
534
534
  /**
535
535
  * A device's firmware: what it runs, what it could run, and whether it is installing it now.
536
536
  *
537
- * One entity for the whole of it, as Home Assistant has, rather than a sensor saying an update
538
- * is there and a button installing it: the installing belongs to the same state as the offer,
539
- * and an automation that installs whatever is offered must be able to see that an install is
537
+ * One entity for the whole of it, rather than a sensor saying an update is there and a button
538
+ * installing it: the installing belongs to the same state as the offer, and an automation that
539
+ * installs whatever is offered must be able to see that an install is
540
540
  * already under way - a device fetching its firmware still offers it until it reboots, and
541
541
  * asked again it may start over.
542
542
  *
@@ -595,7 +595,7 @@ const lawnMowerCommandSchema = z.discriminatedUnion("command", [
595
595
  /**
596
596
  * What a robot vacuum is doing: cleaning, paused in the middle of a job, on its way back to its
597
597
  * station, sitting in it, standing idle out of it, or stopped by a fault it cannot clear on its
598
- * own. Home Assistant's vacuum activities, the mower's words where they mean the same.
598
+ * own: the mower's words where they mean the same.
599
599
  */
600
600
  const VACUUM_ACTIVITIES = [
601
601
  "cleaning",
@@ -958,6 +958,8 @@ const entityStateSchema = z.object({
958
958
  attributes: jsonObjectSchema.default({}),
959
959
  /** False when the owning adapter cannot currently reach the device. */
960
960
  isAvailable: z.boolean().default(true),
961
+ /** True while its package or integration is being updated: the value is the last one known. */
962
+ isUpdating: z.boolean().optional(),
961
963
  /**
962
964
  * When `state` last differed from what it was.
963
965
  *
@@ -1601,7 +1603,7 @@ function pollIntervalMsOf(options) {
1601
1603
  * Apart from the manifest so that the vendors' grammar can name it without pulling the package
1602
1604
  * manifest's whole grammar - and what that imports - in with it.
1603
1605
  */
1604
- /** A service a package provides and others require: `mqtt-broker`, `object-detection`. */
1606
+ /** A service others require: `object-detection`, or `mqtt-broker`, which the platform runs. */
1605
1607
  const packageServiceNameSchema = z.string().regex(/^[a-z][a-z0-9-]{1,63}$/, "Must be a lower-case service name");
1606
1608
  /**
1607
1609
  * What a package - or a vendor, in its `manifest.json` - needs besides itself: the platform, by
@@ -1726,6 +1728,8 @@ z.object({ vendorId: z.string().min(1).max(64) });
1726
1728
  *
1727
1729
  * Defined in ARCHITECTURE.md 8.
1728
1730
  */
1731
+ /** What an integration may say makes two of its devices one: the same MAC, the same serial. */
1732
+ const TWIN_FACTS = ["mac", "serial"];
1729
1733
  /**
1730
1734
  * Integration instance identifier.
1731
1735
  *
@@ -1769,14 +1773,18 @@ const TRANSPORT_WIRES = [
1769
1773
  ];
1770
1774
  /**
1771
1775
  * How a device can be heard announcing itself: the platform's mDNS browser, a vendor's own
1772
- * listener, or the house's Matter fabric - a node commissioned and not yet added. Declared here
1776
+ * listener, the house's Matter fabric - a node commissioned and not yet added - or the house's
1777
+ * MQTT broker - a device that announced itself on it, or that the owner mapped - or the house's
1778
+ * Modbus client - a device the owner added at an address. Declared here
1773
1779
  * rather than beside the discovered devices, because a vendor lists the ways it can be found and
1774
1780
  * the discovery module already reads this file.
1775
1781
  */
1776
1782
  const DISCOVERY_SOURCES = [
1777
1783
  "mdns",
1778
1784
  "module",
1779
- "matter"
1785
+ "matter",
1786
+ "mqtt",
1787
+ "modbus"
1780
1788
  ];
1781
1789
  /**
1782
1790
  * Who adds a device discovery found: the owner, from its card - the ordinary way - or the
@@ -1800,21 +1808,29 @@ const vendorPairingSchema = z.object({
1800
1808
  });
1801
1809
  /** What a logo may be served as: an image the interface can put straight into an `img`. */
1802
1810
  const LOGO_DATA_URL_PATTERN = /^data:image\/(?:svg\+xml|png);base64,[A-Za-z0-9+/]+=*$/;
1803
- /** Validates an instance lifecycle state. */
1804
- const integrationStateSchema = z.enum([
1811
+ /**
1812
+ * The lifecycle states `hub` records for a configured instance.
1813
+ *
1814
+ * `identifying` sits between `starting` and `running`: the transport is open, and the instance
1815
+ * is waiting to hear from the one device it was added for. A device that has been identified
1816
+ * before starts straight into `running`, bound from what the registry kept about it.
1817
+ */
1818
+ const INTEGRATION_STATES = [
1805
1819
  "stopped",
1806
1820
  "starting",
1807
1821
  "identifying",
1808
1822
  "running",
1809
1823
  "failed",
1810
1824
  "disabled"
1811
- ]);
1825
+ ];
1826
+ /** Validates an instance lifecycle state. */
1827
+ const integrationStateSchema = z.enum(INTEGRATION_STATES);
1812
1828
  z.strictObject({ vendorId: z.string().regex(VENDOR_ID_PATTERN$1) });
1813
1829
  z.object({ isLoaded: z.boolean() });
1814
1830
  /**
1815
1831
  * Where `hub` read a vendor from: the data directory, where the platform installs vendors, a
1816
- * directory of bundles under development, read outside production - or nowhere, for the one vendor
1817
- * the platform is itself: `matter`, the Matter devices no integration claims.
1832
+ * directory of bundles under development, read outside production - or nowhere, for the vendors
1833
+ * the platform is itself: `matter` and `mqtt`, the devices of its brokers no integration claims.
1818
1834
  */
1819
1835
  const BUNDLE_ORIGINS = [
1820
1836
  "installed",
@@ -2000,6 +2016,11 @@ const integrationVendorSchema = z.object({
2000
2016
  discoverySources: z.array(z.enum(DISCOVERY_SOURCES)).default([]),
2001
2017
  /** Who adds what discovery finds: the owner, or the platform on its own. */
2002
2018
  adoption: z.enum(DEVICE_ADOPTIONS).default("owner"),
2019
+ /**
2020
+ * What makes two of its devices one device reached two ways - the same MAC, the same serial -
2021
+ * as its manifest's `twins` says. Empty for a vendor that offers no links.
2022
+ */
2023
+ twins: z.array(z.enum(TWIN_FACTS)).max(TWIN_FACTS.length).default([]),
2003
2024
  /** The entities pairing is run by, for a vendor whose devices are paired through one of its own. */
2004
2025
  pairing: vendorPairingSchema.nullable().default(null),
2005
2026
  drivers: z.array(integrationKindSchema$1),
@@ -2009,13 +2030,13 @@ const integrationVendorSchema = z.object({
2009
2030
  */
2010
2031
  containers: z.array(vendorContainerSchema).default([]),
2011
2032
  /**
2012
- * The packages and services its devices need - the MQTT broker, for Zigbee2MQTT - as its
2013
- * manifest's `requires` says. Nothing when it needs none.
2033
+ * The packages and services its devices need - the MQTT broker the platform runs, for
2034
+ * Zigbee2MQTT - as its manifest's `requires` says. Nothing when it needs none.
2014
2035
  */
2015
2036
  requires: packageRequiresSchema,
2016
2037
  /**
2017
- * What of that is not installed or not running, in sentences naming both - "Zigbee2MQTT needs a
2018
- * package that provides mqtt-broker, and none is running". Empty when all of it runs.
2038
+ * What of that is not installed or not running, in sentences naming both - "NVR needs a
2039
+ * package that provides object-detection, and none does". Empty when all of it runs.
2019
2040
  */
2020
2041
  packageProblems: z.array(z.string().max(512)).max(16).default([]),
2021
2042
  /** How the vendor's own listener is getting on; null before it said, or for one without. */
@@ -3861,7 +3882,7 @@ var sensor_classes_default = { classes: [
3861
3882
  * profile wrote.
3862
3883
  */
3863
3884
  /** How history should aggregate a numeric entity - mirrored from registration, kept local to avoid a cycle. */
3864
- const STATE_CLASSES = [
3885
+ const STATE_CLASSES$1 = [
3865
3886
  "measurement",
3866
3887
  "total",
3867
3888
  "total_increasing"
@@ -3903,7 +3924,7 @@ const sensorClassSchema = z.object({
3903
3924
  * Copied onto the entity when the profile omits `stateClass`. Not a second identifier.
3904
3925
  * Absent for date / timestamp / uptime.
3905
3926
  */
3906
- stateClassDefault: z.enum(STATE_CLASSES).optional(),
3927
+ stateClassDefault: z.enum(STATE_CLASSES$1).optional(),
3907
3928
  /** Molar mass (g/mol) for gas density conversions. */
3908
3929
  molarMass: z.number().positive().optional(),
3909
3930
  units: z.array(sensorUnitSchema)
@@ -4194,6 +4215,26 @@ const declaredCapabilitiesSchema = z.partialRecord(capabilityNameSchema, jsonObj
4194
4215
  message: `Parameters do not match the ${capability} capability`
4195
4216
  });
4196
4217
  });
4218
+ /**
4219
+ * Where a reading sits in Matter's terms: the endpoint, the cluster and the attribute. A Matter
4220
+ * entity carries its own; an entity of another transport may carry the one that reads the same
4221
+ * thing, so the two are linked when the device is reached both ways.
4222
+ */
4223
+ const matterReferenceSchema = z.strictObject({
4224
+ endpoint: z.int().min(0).max(65535),
4225
+ cluster: z.int().min(0),
4226
+ attribute: z.int().min(0)
4227
+ });
4228
+ /**
4229
+ * What lets an entity be told apart from the same reading reached another way: its own key in its
4230
+ * transport's terms - `switch:0` on a Shelly - and where it sits in Matter.
4231
+ */
4232
+ const entityLinkHintSchema = z.strictObject({
4233
+ /** The entity's key in its transport, as its page shows it beside the transport's name. */
4234
+ key: z.string().min(1).max(64).optional(),
4235
+ /** Where it sits in Matter: its own place, or, for another transport, its Matter twin's. */
4236
+ matter: matterReferenceSchema.optional()
4237
+ });
4197
4238
  /** One entity a device exposes. */
4198
4239
  const entityRegistrationSchema = z.object({
4199
4240
  entityId: entityIdSchema,
@@ -4204,7 +4245,9 @@ const entityRegistrationSchema = z.object({
4204
4245
  unitOfMeasurement: z.string().max(32).optional(),
4205
4246
  deviceClass: z.string().max(64).optional(),
4206
4247
  stateClass: z.enum(ENTITY_STATE_CLASSES).optional(),
4207
- displayPrecision: z.int().min(0).max(6).optional()
4248
+ displayPrecision: z.int().min(0).max(6).optional(),
4249
+ /** Kept in the entity's `config.link`: what links it to its twin on another transport. */
4250
+ link: entityLinkHintSchema.optional()
4208
4251
  }).superRefine((entity, ctx) => {
4209
4252
  const issue = sensorRegistrationIssue(entity);
4210
4253
  if (issue !== void 0) ctx.addIssue({
@@ -4229,6 +4272,10 @@ z.strictObject({
4229
4272
  model: z.string().max(128).optional(),
4230
4273
  swVersion: z.string().max(64).optional(),
4231
4274
  hwVersion: z.string().max(64).optional(),
4275
+ /** The hardware's MAC address, as {@link normalizeMac} writes it, when it says one. */
4276
+ mac: z.string().min(1).max(64).optional(),
4277
+ /** The hardware's serial number, when it says one. */
4278
+ serialNumber: z.string().min(1).max(256).optional(),
4232
4279
  /**
4233
4280
  * What the owner needs to find the device again after a restart.
4234
4281
  *
@@ -4289,6 +4336,16 @@ z.strictObject({
4289
4336
  z.object({ isChanged: z.boolean() });
4290
4337
  z.strictObject({ entityId: entityIdSchema });
4291
4338
  z.object({ isLoaded: z.boolean() });
4339
+ z.strictObject({ entityRowIds: z.array(z.uuid()).min(1).max(1024) });
4340
+ z.object({ synced: z.int().min(0) });
4341
+ z.strictObject({ entityId: entityIdSchema });
4342
+ z.object({ items: z.array(z.object({
4343
+ entityId: entityIdSchema,
4344
+ /** The instance it comes through. */
4345
+ source: z.string(),
4346
+ isActive: z.boolean(),
4347
+ state: entityStateSchema.nullable()
4348
+ })) });
4292
4349
  z.strictObject({ entityId: entityIdSchema });
4293
4350
  z.object({ entityId: entityIdSchema });
4294
4351
  z.object({
@@ -4300,6 +4357,227 @@ z.object({
4300
4357
  entityIds: z.array(entityIdSchema)
4301
4358
  });
4302
4359
  //#endregion
4360
+ //#region ../contracts/dist/links.js
4361
+ /**
4362
+ * One device reached two ways, and the readings it gives both ways linked into one.
4363
+ *
4364
+ * A Shelly added over its own RPC and again over Matter is the same plug. The house keeps one
4365
+ * device for it and one entity for each thing it reads, each with a **source** per transport:
4366
+ * readings come from the preferred one, and the other takes over while it is silent.
4367
+ *
4368
+ * **The longer history leads.** Linking adds no row. Of two devices, the one the house had first
4369
+ * is the one it shows, and the other names it in `linked_to`; of two entities, the one with the
4370
+ * longer history is the linked entity, keeps its address and goes on recording, and the other
4371
+ * names it and stops. Every address and row of a linked entity means the one it names - to an
4372
+ * automation, a scene, a card - so nothing that used either is rewritten, and unlinking gives each
4373
+ * back its own.
4374
+ */
4375
+ /** How a pair of entities was linked: declared by the integration, read alike, or by the owner. */
4376
+ const LINK_ORIGINS = [
4377
+ "declared",
4378
+ "auto",
4379
+ "manual"
4380
+ ];
4381
+ /** One thing two devices have alike, and its value. */
4382
+ const linkReasonSchema = z.object({
4383
+ kind: z.enum([
4384
+ "mac",
4385
+ "serial",
4386
+ "model"
4387
+ ]),
4388
+ value: z.string().max(256)
4389
+ });
4390
+ /**
4391
+ * A MAC address the way the house compares them: six bytes, lower case, colons.
4392
+ *
4393
+ * Devices write theirs every way - Shelly `08F9E0124C7A`, Matter `08:f9:e0:12:4c:7a` - and a
4394
+ * Thread radio's eight-byte address is not a MAC anybody else reports.
4395
+ *
4396
+ * @param raw - The address as the device said it.
4397
+ * @returns It, normalised; null when it is not a six-byte address.
4398
+ */
4399
+ function normalizeMac(raw) {
4400
+ const hex = (raw ?? "").replaceAll(/[^0-9a-f]/giu, "").toLowerCase();
4401
+ if (hex.length !== 12 || (raw ?? "").replaceAll(/[0-9a-f:.\-\s]/giu, "") !== "") return null;
4402
+ return hex.replaceAll(/(..)(?!$)/gu, "$1:");
4403
+ }
4404
+ /** One way into a linked device: the instance, its transport and how it stands. */
4405
+ const deviceWaySchema = z.object({
4406
+ /** The instance, which is the way's own device id. */
4407
+ deviceId: integrationIdSchema,
4408
+ kind: z.string(),
4409
+ vendorId: z.string(),
4410
+ transport: z.string(),
4411
+ driverName: z.string(),
4412
+ state: z.enum(INTEGRATION_STATES),
4413
+ /** Whether its entities answer now. */
4414
+ isAvailable: z.boolean(),
4415
+ /** Whether readings come this way first. */
4416
+ isPreferred: z.boolean(),
4417
+ externalId: z.string().nullable(),
4418
+ /** Where it is reached, when its transport names a host: `192.168.178.112`. */
4419
+ address: z.string().nullable(),
4420
+ /** The Matter node, for a way through the Matter broker. */
4421
+ nodeId: z.string().nullable(),
4422
+ swVersion: z.string().nullable(),
4423
+ lastUpdatedAt: timestampSchema.nullable(),
4424
+ createdAt: timestampSchema
4425
+ });
4426
+ z.object({
4427
+ ways: z.array(deviceWaySchema).min(2),
4428
+ /** The instance its entities are read through first. */
4429
+ preferred: integrationIdSchema
4430
+ });
4431
+ /** One source of a linked entity: the same reading through one way in. */
4432
+ const entitySourceSchema = z.object({
4433
+ entityId: entityIdSchema,
4434
+ /** The way in, by its instance. */
4435
+ deviceId: integrationIdSchema,
4436
+ vendorId: z.string(),
4437
+ transport: z.string(),
4438
+ /** Its key in its transport, `switch:0`, when the integration names one. */
4439
+ key: z.string().nullable(),
4440
+ /** Where it sits in Matter, for a Matter source. */
4441
+ matter: matterReferenceSchema.nullable(),
4442
+ /** Whether readings come from it now. */
4443
+ isActive: z.boolean(),
4444
+ isAvailable: z.boolean(),
4445
+ /** What it last said, whether or not it is the one read. */
4446
+ state: jsonObjectSchema.nullable(),
4447
+ lastUpdated: timestampSchema.nullable(),
4448
+ /** How it was linked; null for the entity that leads. */
4449
+ origin: z.enum(LINK_ORIGINS).nullable()
4450
+ });
4451
+ z.object({
4452
+ /** Every source, the one that leads first. */
4453
+ sources: z.array(entitySourceSchema).min(2),
4454
+ /** The instance this entity is read through first, overriding its device; null follows it. */
4455
+ transport: integrationIdSchema.nullable(),
4456
+ /** The instance the device is read through first. */
4457
+ preferred: integrationIdSchema,
4458
+ /** The instance it is read through now; null while no source answers. */
4459
+ active: integrationIdSchema.nullable()
4460
+ });
4461
+ z.object({ entityIds: z.tuple([entityIdSchema, entityIdSchema]) });
4462
+ z.object({ with: integrationIdSchema });
4463
+ z.object({ with: entityIdSchema });
4464
+ z.object({ preview: z.stringbool().default(false) });
4465
+ /** What uses an address: what follows an entity when it is linked or unlinked. */
4466
+ const linkUseSchema = z.object({
4467
+ automations: z.array(z.string()),
4468
+ scenes: z.array(z.string()),
4469
+ aliases: z.array(z.string()),
4470
+ /** Cards, by dashboard. */
4471
+ cards: z.array(z.object({
4472
+ dashboard: z.string(),
4473
+ count: z.int().min(1)
4474
+ }))
4475
+ });
4476
+ /** One entity in a link's account. */
4477
+ const linkSideSchema = z.object({
4478
+ entityId: entityIdSchema,
4479
+ name: z.string(),
4480
+ deviceId: integrationIdSchema,
4481
+ vendorId: z.string(),
4482
+ transport: z.string(),
4483
+ usedBy: linkUseSchema
4484
+ });
4485
+ /** Entities that are, or would be, one: the one that leads, and those that read through it. */
4486
+ const linkPairSchema = z.object({
4487
+ holder: linkSideSchema,
4488
+ others: z.array(linkSideSchema).min(1),
4489
+ origin: z.enum(LINK_ORIGINS)
4490
+ });
4491
+ /** A device in a link's account. */
4492
+ const linkDeviceSchema = z.object({
4493
+ id: integrationIdSchema,
4494
+ name: z.string(),
4495
+ model: z.string().nullable(),
4496
+ vendorId: z.string(),
4497
+ transport: z.string(),
4498
+ areaName: z.string().nullable()
4499
+ });
4500
+ z.object({
4501
+ action: z.enum(["link", "unlink"]),
4502
+ scope: z.enum(["device", "entity"]),
4503
+ /** The device the house shows, and the other way into it; null for an entity's link. */
4504
+ device: linkDeviceSchema.nullable(),
4505
+ other: linkDeviceSchema.nullable(),
4506
+ /** What is linked, or unlinked. */
4507
+ pairs: z.array(linkPairSchema),
4508
+ /** What a device's link leaves read one way. */
4509
+ single: z.array(linkSideSchema),
4510
+ /** The way read first, after a link; the way the leading entity keeps, after an unlink. */
4511
+ preferred: z.object({
4512
+ deviceId: integrationIdSchema,
4513
+ vendorId: z.string(),
4514
+ transport: z.string()
4515
+ }),
4516
+ /** Since when the entities were linked, for an unlink. */
4517
+ linkedSince: timestampSchema.nullable()
4518
+ });
4519
+ /** One device in a suggestion. */
4520
+ const suggestedDeviceSchema = z.object({
4521
+ id: integrationIdSchema,
4522
+ name: z.string(),
4523
+ model: z.string().nullable(),
4524
+ vendorId: z.string(),
4525
+ transport: z.string(),
4526
+ createdAt: timestampSchema
4527
+ });
4528
+ /**
4529
+ * Two devices that look like one, offered to link: the one the house had first, and the newer
4530
+ * way in.
4531
+ */
4532
+ const linkSuggestionViewSchema = z.object({
4533
+ id: z.uuid(),
4534
+ vendorId: z.string().regex(VENDOR_ID_PATTERN$1),
4535
+ device: suggestedDeviceSchema,
4536
+ twin: suggestedDeviceSchema,
4537
+ reasons: z.array(linkReasonSchema),
4538
+ /** When the owner set it aside; null while it is offered. */
4539
+ dismissedAt: timestampSchema.nullable(),
4540
+ createdAt: timestampSchema
4541
+ });
4542
+ z.object({ items: z.array(linkSuggestionViewSchema) });
4543
+ z.object({ isDismissed: z.boolean() });
4544
+ //#endregion
4545
+ //#region ../contracts/dist/brokers.js
4546
+ /**
4547
+ * The platform's brokers, as the Brokers page lists them: the house's Matter fabric, its MQTT
4548
+ * broker and its Modbus client, all run by the hub.
4549
+ *
4550
+ * A broker reaches every device of one protocol, whoever makes it. Each has a page of its own -
4551
+ * `matter.ts`, `mqtt.ts` and `modbus.ts` say what it holds - and a card here, which says how it stands and how
4552
+ * many devices the house has through it.
4553
+ */
4554
+ /** How a broker stands: coming up, running, stopped by a failure, or turned off. */
4555
+ const BROKER_STATES = [
4556
+ "starting",
4557
+ "running",
4558
+ "failed",
4559
+ "disabled"
4560
+ ];
4561
+ /** One broker, for its card. */
4562
+ const brokerSummarySchema = z.object({
4563
+ id: z.enum([
4564
+ "matter",
4565
+ "mqtt",
4566
+ "modbus"
4567
+ ]),
4568
+ state: z.enum(BROKER_STATES),
4569
+ /**
4570
+ * The devices the house has through it, how many of them answer, and how many are also
4571
+ * reached another way.
4572
+ */
4573
+ devices: z.object({
4574
+ total: z.int().min(0),
4575
+ online: z.int().min(0),
4576
+ linked: z.int().min(0).default(0)
4577
+ })
4578
+ });
4579
+ z.object({ items: z.array(brokerSummarySchema) });
4580
+ //#endregion
4303
4581
  //#region ../contracts/dist/matter.js
4304
4582
  /**
4305
4583
  * The house's Matter fabric, as the hub runs it and the Brokers page shows it.
@@ -4316,8 +4594,8 @@ z.object({
4316
4594
  */
4317
4595
  /** The platform transport every Matter device is reached through. */
4318
4596
  const MATTER_TRANSPORT = "matter";
4319
- /** The platform's own vendor: the Matter devices no integration claims. */
4320
- const MATTER_VENDOR = "matter";
4597
+ /** The UDP port the controller listens on, which the engine does not let anyone change. */
4598
+ const MATTER_PORT = 5540;
4321
4599
  /** A node id, in decimal: a 64-bit number, which JSON cannot carry as a number. */
4322
4600
  const matterNodeIdSchema = z.string().regex(/^[0-9]{1,20}$/u, "Must be a node id");
4323
4601
  /**
@@ -4327,7 +4605,7 @@ const matterNodeIdSchema = z.string().regex(/^[0-9]{1,20}$/u, "Must be a node id
4327
4605
  */
4328
4606
  const matterPairingCodeSchema = z.string().trim().max(128).transform((code) => code.startsWith("MT:") ? code : code.replaceAll(/[\s-]/gu, "")).pipe(z.string().regex(/^(?:[0-9]{11}|[0-9]{21}|MT:[0-9A-Z.-]{19,})$/u, "Must be the 11 or 21 digits of a pairing code, or the text of its QR code (MT:…)"));
4329
4607
  /** How many items a list in an identity holds at most. */
4330
- const MAXIMUM_LIST = 64;
4608
+ const MAXIMUM_LIST$1 = 64;
4331
4609
  /**
4332
4610
  * Who a Matter device says it is: what an integration's rules match and the Brokers page shows.
4333
4611
  *
@@ -4351,9 +4629,9 @@ const matterIdentitySchema = z.object({
4351
4629
  softwareVersion: z.int().min(0).nullable(),
4352
4630
  softwareVersionString: z.string().max(256).nullable(),
4353
4631
  /** The hardware addresses of its network interfaces, lower-case and colon-separated. */
4354
- macAddresses: z.array(z.string().max(64)).max(MAXIMUM_LIST),
4632
+ macAddresses: z.array(z.string().max(64)).max(MAXIMUM_LIST$1),
4355
4633
  /** The Matter device types it declares, by number: `256` an on/off light. */
4356
- deviceTypes: z.array(z.int().min(0)).max(MAXIMUM_LIST),
4634
+ deviceTypes: z.array(z.int().min(0)).max(MAXIMUM_LIST$1),
4357
4635
  /** The clusters its endpoints serve, by number, each once. */
4358
4636
  clusters: z.array(z.int().min(0)).max(256),
4359
4637
  /** Whether the node is a bridge, with devices of its own behind it. */
@@ -4361,34 +4639,82 @@ const matterIdentitySchema = z.object({
4361
4639
  /** Whether this is a device behind a bridge. */
4362
4640
  isBridged: z.boolean()
4363
4641
  });
4364
- /** How the controller stands. */
4365
- const MATTER_CONTROLLER_STATES = [
4366
- "starting",
4642
+ /**
4643
+ * How a commissioning goes. `needs-answer` is a job that stopped before the node joined and waits
4644
+ * for the owner: a device whose certificate is a test one, added only when they say so.
4645
+ * `cancelled` is a job the owner stopped before the device joined.
4646
+ */
4647
+ const MATTER_COMMISSIONING_STATES = [
4367
4648
  "running",
4649
+ "needs-answer",
4650
+ "succeeded",
4368
4651
  "failed",
4369
- "disabled"
4652
+ "cancelled"
4370
4653
  ];
4371
4654
  /**
4372
- * One commissioning: started by a pairing code, done once the node is on the fabric. A node takes
4373
- * from seconds to a minute or two, longer than one request may wait, so the page reads the job
4374
- * until it ends.
4655
+ * The steps of a commissioning, in order: the code read, the device found on the network, its
4656
+ * certificate checked against the DCL, joining the fabric, reading what it can do, and the device
4657
+ * in the house.
4375
4658
  */
4376
- const matterCommissioningSchema = z.object({
4377
- id: z.string().min(1).max(64),
4659
+ const MATTER_COMMISSIONING_STEPS = [
4660
+ "code",
4661
+ "found",
4662
+ "certificate",
4663
+ "joining",
4664
+ "reading",
4665
+ "in-house"
4666
+ ];
4667
+ /** One step of a commissioning, and what it found. */
4668
+ const matterCommissioningStepSchema = z.object({
4669
+ id: z.enum(MATTER_COMMISSIONING_STEPS),
4378
4670
  state: z.enum([
4671
+ "pending",
4379
4672
  "running",
4380
- "succeeded",
4673
+ "done",
4674
+ "warning",
4381
4675
  "failed"
4382
4676
  ]),
4677
+ /**
4678
+ * What the step found, as facts the page words itself: the discriminator a code carries, the
4679
+ * address and product a device answered with, the vendor and product a test certificate names.
4680
+ */
4681
+ detail: z.object({
4682
+ discriminator: z.int().min(0).max(4095).nullable().default(null),
4683
+ isQrCode: z.boolean().default(false),
4684
+ address: z.string().max(256).nullable().default(null),
4685
+ product: z.string().max(256).nullable().default(null),
4686
+ vendorId: z.int().min(0).max(65535).nullable().default(null),
4687
+ productId: z.int().min(0).max(65535).nullable().default(null)
4688
+ }).default({
4689
+ discriminator: null,
4690
+ isQrCode: false,
4691
+ address: null,
4692
+ product: null,
4693
+ vendorId: null,
4694
+ productId: null
4695
+ })
4696
+ });
4697
+ /**
4698
+ * One commissioning: started by a pairing code, done once the device is in the house. A node takes
4699
+ * from seconds to a minute or two, longer than one request may wait, so the page reads the job
4700
+ * until it ends.
4701
+ */
4702
+ const matterCommissioningSchema = z.object({
4703
+ id: z.string().min(1).max(64),
4704
+ state: z.enum(MATTER_COMMISSIONING_STATES),
4383
4705
  startedAt: timestampSchema,
4384
4706
  finishedAt: timestampSchema.nullable(),
4385
- /** The node it made; null until it succeeded. */
4707
+ /** The node it made; null until it is on the fabric. */
4386
4708
  nodeId: matterNodeIdSchema.nullable(),
4387
4709
  /** Why it failed, in a sentence; null unless it did. */
4388
- error: z.string().max(2048).nullable()
4710
+ error: z.string().max(2048).nullable(),
4711
+ /** Each step in order, with how it stands. */
4712
+ steps: z.array(matterCommissioningStepSchema).max(MATTER_COMMISSIONING_STEPS.length).default([]),
4713
+ /** The device it became in the house; null until it is in. */
4714
+ deviceId: integrationIdSchema.nullable().default(null)
4389
4715
  });
4390
4716
  z.object({
4391
- state: z.enum(MATTER_CONTROLLER_STATES),
4717
+ state: z.enum(BROKER_STATES),
4392
4718
  /** Why it failed or is off, in a sentence; null while it runs. */
4393
4719
  error: z.string().max(2048).nullable(),
4394
4720
  /** The fabric's id, in hex; null before the controller has one. */
@@ -4403,7 +4729,15 @@ z.object({
4403
4729
  online: z.int().min(0)
4404
4730
  }),
4405
4731
  /** The last commissioning; null when none was started since the hub started. */
4406
- commissioning: matterCommissioningSchema.nullable()
4732
+ commissioning: matterCommissioningSchema.nullable(),
4733
+ /** When the controller last started; null while it is not running. */
4734
+ startedAt: timestampSchema.nullable().default(null),
4735
+ /** The engine under the controller, as `matter.js 0.17`. */
4736
+ controllerVersion: z.string().max(64).nullable().default(null),
4737
+ /** The UDP port the controller listens on. */
4738
+ port: z.int().min(1).max(65535).default(MATTER_PORT),
4739
+ /** When this hub made the fabric; null for one made before the hub kept the date. */
4740
+ fabricCreatedAt: timestampSchema.nullable().default(null)
4407
4741
  });
4408
4742
  /** One device a node is in the house: the node itself, or one endpoint behind a bridge. */
4409
4743
  const matterNodeDeviceSchema = z.object({
@@ -4416,8 +4750,8 @@ const matterNodeDeviceSchema = z.object({
4416
4750
  /** The driver it was added as; null while it is not added. */
4417
4751
  kind: integrationKindIdSchema.nullable(),
4418
4752
  /**
4419
- * The integrations whose rules all take it, when there are several: it is then added as the
4420
- * platform's own, and the page says who else wants it. Empty otherwise.
4753
+ * The integrations whose rules all take it. One is the integration it belongs to; several, and it
4754
+ * is added as the platform's own and the page says who else wants it. Empty when none takes it.
4421
4755
  */
4422
4756
  claimedBy: z.array(z.string().regex(VENDOR_ID_PATTERN$1)).max(16),
4423
4757
  /** Removed from the house, its node still on the fabric: the page offers it back. */
@@ -4427,12 +4761,84 @@ const matterNodeDeviceSchema = z.object({
4427
4761
  const matterNodeSchema = z.object({
4428
4762
  nodeId: matterNodeIdSchema,
4429
4763
  isAvailable: z.boolean(),
4764
+ /** When it joined the fabric, as the controller recorded it; null when it did not say. */
4765
+ commissionedAt: timestampSchema.nullable().default(null),
4766
+ /** Since when it has not answered, as far as this hub saw; null while it answers. */
4767
+ offlineSince: timestampSchema.nullable().default(null),
4430
4768
  /** The node itself first, then each device behind it when it is a bridge. */
4431
4769
  devices: z.array(matterNodeDeviceSchema).min(1).max(256)
4432
4770
  });
4433
4771
  z.object({});
4434
4772
  z.object({});
4435
4773
  z.object({ items: z.array(matterNodeSchema) });
4774
+ /**
4775
+ * What a point of the fabric's network is, as the controller works it out: a node of the fabric;
4776
+ * a Thread border router found over mDNS; a Thread device some node hears that is not on this
4777
+ * fabric (a border router too, when the house does not look for them); a Wi-Fi access point, made
4778
+ * up from the BSSID its stations report.
4779
+ */
4780
+ const MATTER_NETWORK_KINDS = [
4781
+ "matter",
4782
+ "border_router",
4783
+ "thread_unknown",
4784
+ "wifi_ap"
4785
+ ];
4786
+ /** How a point reaches the network. */
4787
+ const MATTER_NETWORKS = [
4788
+ "thread",
4789
+ "wifi",
4790
+ "ethernet",
4791
+ "unknown"
4792
+ ];
4793
+ /** How good a link is: Thread by LQI, Wi-Fi by RSSI; `unknown` is a link nobody measured. */
4794
+ const MATTER_LINK_STRENGTHS = [
4795
+ "strong",
4796
+ "medium",
4797
+ "weak",
4798
+ "none",
4799
+ "unknown"
4800
+ ];
4801
+ /** One point of the fabric's network. */
4802
+ const matterNetworkNodeSchema = z.object({
4803
+ /** The controller's id for it: the node id for a node, `ap_<BSSID>`, `unknown_<address>`. */
4804
+ id: z.string().min(1).max(64),
4805
+ kind: z.enum(MATTER_NETWORK_KINDS),
4806
+ network: z.enum(MATTER_NETWORKS),
4807
+ /** The node, for a node of the fabric. */
4808
+ nodeId: matterNodeIdSchema.nullable(),
4809
+ /** Leader, router, end device, sleepy end device, station...; null when it did not say. */
4810
+ role: z.string().max(32).nullable(),
4811
+ /** Whether it answers; null for what is not a node of the fabric. */
4812
+ isAvailable: z.boolean().nullable(),
4813
+ isBridge: z.boolean(),
4814
+ /** The Thread network's name. */
4815
+ networkName: z.string().max(64).nullable(),
4816
+ /** The Thread or Wi-Fi channel. */
4817
+ channel: z.number().int().min(0).max(255).nullable(),
4818
+ /** The Wi-Fi network a station is on, and the access point's address. */
4819
+ ssid: z.string().max(64).nullable(),
4820
+ bssid: z.string().max(32).nullable(),
4821
+ /** The Thread extended address: a Thread point's MAC. */
4822
+ extAddress: z.string().max(32).nullable()
4823
+ });
4824
+ /** One link between two points, as the better of its two ends reported it. */
4825
+ const matterNetworkLinkSchema = z.object({
4826
+ source: z.string().min(1).max(64),
4827
+ target: z.string().min(1).max(64),
4828
+ network: z.enum(["thread", "wifi"]),
4829
+ strength: z.enum(MATTER_LINK_STRENGTHS),
4830
+ /** Thread's link quality, 0 to 3 on OpenThread. */
4831
+ lqi: z.number().int().nullable(),
4832
+ /** The signal, in dBm. */
4833
+ rssi: z.number().int().nullable()
4834
+ });
4835
+ z.object({});
4836
+ z.object({
4837
+ /** When the controller put it together; null while the fabric is not open. */
4838
+ collectedAt: timestampSchema.nullable(),
4839
+ nodes: z.array(matterNetworkNodeSchema).max(2048),
4840
+ links: z.array(matterNetworkLinkSchema).max(8192)
4841
+ });
4436
4842
  z.object({ code: matterPairingCodeSchema });
4437
4843
  z.object({ nodeId: matterNodeIdSchema });
4438
4844
  z.object({ isRemoved: z.boolean() });
@@ -4441,102 +4847,872 @@ z.object({
4441
4847
  endpoint: z.int().min(0).max(65535).nullable()
4442
4848
  });
4443
4849
  z.object({ isRestored: z.boolean() });
4444
- /** The brokers the platform runs, as the Brokers page lists them. */
4445
- const BROKER_IDS = [MATTER_VENDOR];
4446
- /** One broker, for its card. */
4447
- const brokerSummarySchema = z.object({
4448
- id: z.enum(BROKER_IDS),
4449
- state: z.enum(MATTER_CONTROLLER_STATES),
4450
- /** The devices the house has through it, and how many of them answer. */
4451
- devices: z.object({
4452
- total: z.int().min(0),
4453
- online: z.int().min(0)
4454
- })
4850
+ z.object({
4851
+ jobId: z.string().min(1).max(64),
4852
+ isAccepted: z.boolean()
4455
4853
  });
4456
- z.object({ items: z.array(brokerSummarySchema) });
4854
+ z.object({ jobId: z.string().min(1).max(64) });
4855
+ z.object({});
4457
4856
  //#endregion
4458
- //#region ../package-runtime/dist/containers.js
4459
- /** A vendor setting a value is filled from: `{setup.serialPath}`. */
4460
- const SETTING_PLACEHOLDER = /\{setup\.([a-zA-Z][a-zA-Z0-9]*)\}/g;
4857
+ //#region ../contracts/dist/modbus.js
4858
+ /**
4859
+ * The house's Modbus broker, as the hub runs it and the Brokers page shows it.
4860
+ *
4861
+ * Modbus is one of the platform's brokers: the hub is the house's Modbus TCP client. Every
4862
+ * gateway - a Modbus TCP device, or a transparent RS485 adapter carrying RTU frames over TCP - is
4863
+ * reached through one connection, one request at a time, whoever's devices are behind it. A
4864
+ * gateway answers one client; two of them asking at once is how a dongle stops answering both.
4865
+ *
4866
+ * Modbus says nothing about what a register means, so a device is read through a **template**: its
4867
+ * entities, each capability mapped to the register it is read from and the command it is written
4868
+ * with. The owner writes templates of their own; an integration ships its own as drivers of kind
4869
+ * `modbus`. A device is a template at an address - host, port, unit - and becomes a device of the
4870
+ * house through the platform's own `modbus` vendor, or of the integration whose template it is.
4871
+ *
4872
+ * The broker recognises nothing on its own. A server found on the network is named only by an
4873
+ * integration whose `discovery.json` `modbus` rules read it and match.
4874
+ */
4875
+ /** The platform transport every Modbus device is reached through. */
4876
+ const MODBUS_TRANSPORT = "modbus";
4877
+ /** How frames travel: Modbus TCP, or RTU frames carried over TCP by a transparent adapter. */
4878
+ const MODBUS_FRAMINGS = ["tcp", "rtu"];
4879
+ /** How registers hold a value: one or two registers as integers or a float, or ASCII text. */
4880
+ const MODBUS_VALUE_TYPES = [
4881
+ "u16",
4882
+ "s16",
4883
+ "u32",
4884
+ "s32",
4885
+ "f32",
4886
+ "string"
4887
+ ];
4888
+ /** The domains a template's entity can be. */
4889
+ const MODBUS_DOMAINS = [
4890
+ "sensor",
4891
+ "binary_sensor",
4892
+ "switch",
4893
+ "light",
4894
+ "number",
4895
+ "select",
4896
+ "button"
4897
+ ];
4898
+ /** The capabilities a template maps. */
4899
+ const MODBUS_CAPABILITIES = [
4900
+ "sensor_numeric",
4901
+ "sensor_text",
4902
+ "sensor_binary",
4903
+ "on_off",
4904
+ "level",
4905
+ "number",
4906
+ "select",
4907
+ "button"
4908
+ ];
4461
4909
  /**
4462
- * Every setting a declaration reads: its `when` keys and its placeholders.
4910
+ * The capabilities each domain takes: those it must have, and those it may add.
4463
4911
  *
4464
- * @param dep - One declared container.
4465
- * @returns The keys.
4912
+ * A sensor is a number or a text; a light switches and may dim.
4466
4913
  */
4467
- function settingsRead(dep) {
4468
- const keys = /* @__PURE__ */ new Set();
4469
- const texts = [
4470
- ...dep.env.map((entry) => entry.value),
4471
- ...dep.devices.map((device) => device.host),
4472
- ...dep.ports.flatMap((port) => [String(port.container), String(port.host)]),
4473
- ...dep.webPort === void 0 ? [] : [String(dep.webPort)]
4474
- ];
4475
- for (const text of texts) for (const match of text.matchAll(SETTING_PLACEHOLDER)) keys.add(match[1] ?? "");
4476
- const conditions = [
4477
- ...dep.env.map((entry) => entry.when),
4478
- ...dep.devices.map((device) => device.when),
4479
- ...dep.ports.map((port) => port.when),
4480
- dep.webPortWhen
4481
- ];
4482
- for (const condition of conditions) if (condition !== void 0) keys.add(condition.key);
4483
- return keys;
4484
- }
4914
+ const MODBUS_DOMAIN_CAPABILITIES = {
4915
+ sensor: {
4916
+ oneOf: ["sensor_numeric", "sensor_text"],
4917
+ may: []
4918
+ },
4919
+ binary_sensor: {
4920
+ oneOf: ["sensor_binary"],
4921
+ may: []
4922
+ },
4923
+ switch: {
4924
+ oneOf: ["on_off"],
4925
+ may: []
4926
+ },
4927
+ light: {
4928
+ oneOf: ["on_off"],
4929
+ may: ["level"]
4930
+ },
4931
+ number: {
4932
+ oneOf: ["number"],
4933
+ may: []
4934
+ },
4935
+ select: {
4936
+ oneOf: ["select"],
4937
+ may: []
4938
+ },
4939
+ button: {
4940
+ oneOf: ["button"],
4941
+ may: []
4942
+ }
4943
+ };
4944
+ /** The capabilities whose value is on or off, read from a bit. */
4945
+ const BOOLEAN_CAPABILITIES = /* @__PURE__ */ new Set(["sensor_binary", "on_off"]);
4946
+ /** The capabilities only read, never written. */
4947
+ const READ_ONLY_CAPABILITIES = /* @__PURE__ */ new Set([
4948
+ "sensor_numeric",
4949
+ "sensor_text",
4950
+ "sensor_binary"
4951
+ ]);
4952
+ /** A register's address or a 16-bit word: 0 to 65535, or written as `0x` and up to four hex digits. */
4953
+ const modbusWordSchema = z.union([z.int().min(0).max(65535), z.string().regex(/^0x[0-9a-fA-F]{1,4}$/u, "A number from 0 to 65535, or 0x0000 to 0xFFFF")]);
4485
4954
  /**
4486
- * Checks a vendor's declared containers against its own settings, once, at load: every setting
4487
- * a declaration reads must be one the vendor's `setup.json` asks.
4955
+ * The number an address or a word is, however it was written.
4488
4956
  *
4489
- * @param deps - The declared containers.
4490
- * @param setup - The vendor's own setup, or undefined for a vendor with none.
4491
- * @returns What is wrong, one sentence each; empty when nothing is.
4957
+ * @param word - As the template says it.
4958
+ * @returns The number.
4492
4959
  */
4493
- function containerDependencyProblems(deps, setup) {
4494
- const asked = new Set([...setup?.transport.fields ?? [], ...setup?.options.fields ?? []].map((field) => field.key));
4495
- return deps.flatMap((dep) => [...[...settingsRead(dep)].filter((key) => !asked.has(key)).map((key) => `${dep.id} reads the setting ${key}, which the vendor's setup.json does not ask`), ...dep.seed.filter((seed) => !dep.volumes.some((volume) => volume.name === seed.volume)).map((seed) => `${dep.id} seeds ${seed.path} into ${seed.volume}, which it does not declare`)]);
4960
+ function modbusWordOf(word) {
4961
+ return typeof word === "number" ? word : Number.parseInt(word.slice(2), 16);
4496
4962
  }
4497
- //#endregion
4498
- //#region ../package-runtime/dist/bundle.js
4499
4963
  /**
4500
- * The two manifests a bundle is written as, and the one the runtime reads.
4501
- *
4502
- * A bundle is how an integration is distributed: a **vendor** directory - the company that
4503
- * makes the devices, with a logo, a version, and whatever settings every device of theirs
4504
- * shares - holding one **driver** directory per profile or entry point, each listing the
4505
- * models it drives. Two files, because the two levels answer different questions: `manifest.json`
4506
- * is what a catalogue lists and an owner recognises, `driver.json` is what the runtime loads
4507
- * and an instance references. The split is also what ends the duplication the old flat layout
4508
- * had, where every driver of one vendor repeated the vendor's name and description and the
4509
- * three copies drifted.
4964
+ * How many registers a value of a type takes.
4510
4965
  *
4511
- * What the rest of the runtime reads is neither file but their composition, the
4512
- * {@link BundleManifest}: the vendor's identity and version beside the driver's transport and
4513
- * entry point, keyed by the vendor-qualified kind. {@link resolveManifest} is the only place the
4514
- * two are joined, so a field that moves between the files moves in one function.
4966
+ * @param type - How the registers hold it.
4967
+ * @param count - How many a text takes.
4968
+ * @returns Two for 32 bits, `count` for text, one otherwise.
4969
+ */
4970
+ function modbusRegistersOf(type, count = 1) {
4971
+ return type === "string" ? count : type === "u32" || type === "s32" || type === "f32" ? 2 : 1;
4972
+ }
4973
+ /** Where a capability's value is read from, and how it is turned into one. */
4974
+ const modbusReadSchema = z.strictObject({
4975
+ function: z.union([
4976
+ z.literal(1),
4977
+ z.literal(2),
4978
+ z.literal(3),
4979
+ z.literal(4)
4980
+ ]),
4981
+ address: modbusWordSchema,
4982
+ /** How the registers hold it; one unsigned register unless said. Not for coils and inputs. */
4983
+ type: z.enum(MODBUS_VALUE_TYPES).optional(),
4984
+ /** How many registers a text takes. */
4985
+ count: z.int().min(1).max(64).optional(),
4986
+ /** The bit of a register an on/off value is, 0 the lowest. */
4987
+ bit: z.int().min(0).max(15).optional(),
4988
+ /** What the raw number is multiplied by: 0.1 for tenths. */
4989
+ scale: z.number().refine((scale) => scale !== 0, "Not zero").optional(),
4990
+ unit: z.string().trim().max(16).optional(),
4991
+ /** What each raw number means, for a choice or a text: `{ "0": "Off", "1": "Eco" }`. */
4992
+ options: z.record(z.string().regex(/^-?\d{1,10}$/u, "A whole number"), z.string().trim().min(1).max(64)).optional()
4993
+ });
4994
+ /** What a capability's command writes, and within what. */
4995
+ const modbusWriteSchema = z.strictObject({
4996
+ function: z.union([
4997
+ z.literal(5),
4998
+ z.literal(6),
4999
+ z.literal(15),
5000
+ z.literal(16)
5001
+ ]),
5002
+ /** Where; the read's address when left out, if the read's table can be written. */
5003
+ address: modbusWordSchema.optional(),
5004
+ /** The words on and off are written as; 0xFF00 and 0 for a coil, 1 and 0 for a register. */
5005
+ on: modbusWordSchema.optional(),
5006
+ off: modbusWordSchema.optional(),
5007
+ /** The values a number may be set to; a value outside them never reaches the device. */
5008
+ min: z.number().optional(),
5009
+ max: z.number().optional(),
5010
+ step: z.number().positive().optional(),
5011
+ /** The word a button writes when pressed. */
5012
+ value: modbusWordSchema.optional()
5013
+ });
5014
+ /** One capability of an entity: where it is read, and what its command writes. */
5015
+ const modbusCapabilityMapSchema = z.strictObject({
5016
+ read: modbusReadSchema.optional(),
5017
+ write: modbusWriteSchema.optional()
5018
+ });
5019
+ /** An entity's own part of its identifier: what stays when it is renamed. */
5020
+ const MODBUS_ENTITY_ID_PATTERN = /^[a-z0-9][a-z0-9_]{0,39}$/u;
5021
+ /**
5022
+ * The identifier an entity of that name is given: lower case, words joined by `_`.
4515
5023
  *
4516
- * `kind` is a trust boundary as much as a format. A declarative driver is data - it cannot do
4517
- * anything a path cannot express - so a catalogue can publish one directly. A code driver is
4518
- * JavaScript, and reaches a catalogue only after the manual approval ARCHITECTURE.md 10 already
4519
- * requires of executable content.
5024
+ * @param name - The entity's name.
5025
+ * @returns Its identifier, `entity` when the name has no letter or digit.
4520
5026
  */
5027
+ function modbusEntityIdOf(name) {
5028
+ const slug = name.normalize("NFKD").toLowerCase().replaceAll(/[^a-z0-9]+/gu, "_").replaceAll(/^_+|_+$/gu, "").slice(0, 40).replace(/_+$/u, "");
5029
+ return slug === "" ? "entity" : slug;
5030
+ }
5031
+ /** One entity of a template. */
5032
+ const modbusEntitySchema = z.strictObject({
5033
+ /** What it stays when renamed; given from the name when saved. */
5034
+ id: z.string().regex(MODBUS_ENTITY_ID_PATTERN, "Lower-case letters, digits and _").optional(),
5035
+ name: z.string().trim().min(1, "Needed: a name").max(64),
5036
+ domain: z.enum(MODBUS_DOMAINS),
5037
+ capabilities: z.partialRecord(z.enum(MODBUS_CAPABILITIES), modbusCapabilityMapSchema)
5038
+ });
5039
+ /**
5040
+ * A template's fields, before the rules that tie them together: what the editor reads a file with
5041
+ * to show a refused template's problems on its blocks.
5042
+ */
5043
+ const modbusTemplateFieldsSchema = z.strictObject({
5044
+ name: z.string().trim().min(1, "Needed: a name").max(64),
5045
+ /** The device it is for, as its maker names it. */
5046
+ device: z.string().trim().max(128).default(""),
5047
+ /** Where such a device usually listens, offered when one is added. */
5048
+ port: z.int().min(1).max(65535).default(502),
5049
+ unitId: z.int().min(1).max(247).default(1),
5050
+ /** Which register of a 32-bit value holds the high word: the first, or the second. */
5051
+ wordOrder: z.enum(["high", "low"]).default("high"),
5052
+ /** How often the device is read. */
5053
+ pollSeconds: z.int().min(1).max(3600).default(10),
5054
+ entities: z.array(modbusEntitySchema).min(1, "Add at least one entity").max(256)
5055
+ });
5056
+ /**
5057
+ * Says what is wrong with one capability's mapping, or nothing.
5058
+ *
5059
+ * @param capability - The capability.
5060
+ * @param map - Its read and write.
5061
+ * @param add - Reports a problem at a path below the capability.
5062
+ */
5063
+ function checkCapability(capability, map, add) {
5064
+ const { read, write } = map;
5065
+ const isBoolean = BOOLEAN_CAPABILITIES.has(capability);
5066
+ if (read === void 0 && capability !== "button" && capability !== "level") add(["read"], "Needed: where the value is read from");
5067
+ if (read !== void 0) {
5068
+ const isBitTable = read.function === 1 || read.function === 2;
5069
+ if (capability === "button") add(["read"], "A button is only pressed: leave the read out");
5070
+ else if (isBitTable && !isBoolean) add(["read", "function"], capability === "sensor_text" ? "A text is read from registers: use 03 or 04" : "A number is read from registers: use 03 or 04");
5071
+ if (isBitTable && read.type !== void 0) add(["read", "type"], "Coils and inputs are bits: leave the type out");
5072
+ if (read.bit !== void 0 && (isBitTable || !isBoolean)) add(["read", "bit"], "A bit is read from a register, for an on/off value");
5073
+ if (read.type === "string" && read.count === void 0) add(["read", "count"], "Needed: how many registers the text takes");
5074
+ if (read.count !== void 0 && read.type !== "string") add(["read", "count"], "Only a text takes several registers");
5075
+ if (read.type === "string" && capability !== "sensor_text") add(["read", "type"], "Only a text sensor reads a string");
5076
+ if (capability === "sensor_text" && read.type !== "string" && read.options === void 0) add(["read", "type"], "A text is a string, or a number with options");
5077
+ if (capability === "select" && read.options === void 0) add(["read", "options"], "Needed: what each value means");
5078
+ }
5079
+ if (write === void 0) {
5080
+ if (capability === "button" || capability === "number" || capability === "select") add(["write"], "Needed: what the command writes");
5081
+ if (capability === "level" && read === void 0) add(["read"], "Needed: where the value is read from, or what is written");
5082
+ return;
5083
+ }
5084
+ if (READ_ONLY_CAPABILITIES.has(capability)) {
5085
+ add(["write"], "A sensor is only read: leave the write out");
5086
+ return;
5087
+ }
5088
+ const isCoilWrite = write.function === 5 || write.function === 15;
5089
+ if (isCoilWrite && !isBoolean && capability !== "button") add(["write", "function"], "A number is written to registers: use 06 or 16");
5090
+ if (write.address === void 0) {
5091
+ if (read === void 0) add(["write", "address"], "Needed: there is no read to take it from");
5092
+ else if (read.function === 2 || read.function === 4) add(["write", "address"], `Needed: function 0${String(read.function)} reads a table that cannot be written`);
5093
+ else if (read.function === 1 && !isCoilWrite) add(["write", "function"], "The read is a coil: write it with 05 or 15");
5094
+ else if (read.function === 3 && isCoilWrite) add(["write", "function"], "The read is a register: write it with 06 or 16");
5095
+ }
5096
+ const type = read?.type ?? "u16";
5097
+ if (write.function === 6 && modbusRegistersOf(type) === 2) add(["write", "function"], "A 32-bit value takes two registers: use 16");
5098
+ if (capability === "number") {
5099
+ if (write.min === void 0) add(["write", "min"], "Needed: the lowest value");
5100
+ if (write.max === void 0) add(["write", "max"], "Needed: the highest value");
5101
+ if (write.min !== void 0 && write.max !== void 0 && write.min >= write.max) add(["write", "max"], "Must be above min");
5102
+ } else if (write.min !== void 0 && write.max !== void 0 && write.min >= write.max) add(["write", "max"], "Must be above min");
5103
+ }
4521
5104
  /**
4522
- * Bundle kind, which is both how it is written and how far it is trusted. `matter` is a driver
4523
- * the platform's Matter mapping runs: no profile and no code, so as far trusted as a profile.
5105
+ * A template: the device's entities, each capability mapped to the register it is read from and
5106
+ * the command it is written with.
5107
+ *
5108
+ * Every rule that ties fields together is here, so the editor's blocks, its file and the hub
5109
+ * refuse the same templates with the same words.
4524
5110
  */
4525
- const BUNDLE_KINDS = [
4526
- "declarative",
4527
- "code",
4528
- "matter"
4529
- ];
4530
- /** Validates a vendor id. */
4531
- const vendorIdSchema = z.string().regex(/^[a-z][a-z0-9-]{1,63}$/, "Must be a vendor id");
4532
- /** Validates a driver id. */
4533
- const driverIdSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{1,63}$/, "Must be a driver id");
5111
+ const modbusTemplateSchema = modbusTemplateFieldsSchema.superRefine((template, context) => {
5112
+ const ids = /* @__PURE__ */ new Set();
5113
+ template.entities.forEach((entity, index) => {
5114
+ /**
5115
+ * Reports a problem of this entity.
5116
+ *
5117
+ * @param path - Where, below the entity.
5118
+ * @param message - What, in a sentence.
5119
+ */
5120
+ const add = (path, message) => {
5121
+ context.addIssue({
5122
+ code: "custom",
5123
+ path: [
5124
+ "entities",
5125
+ index,
5126
+ ...path
5127
+ ],
5128
+ message
5129
+ });
5130
+ };
5131
+ const id = entity.id ?? modbusEntityIdOf(entity.name);
5132
+ if (ids.has(id)) add([entity.id === void 0 ? "name" : "id"], "Another entity has the same id");
5133
+ ids.add(id);
5134
+ const rule = MODBUS_DOMAIN_CAPABILITIES[entity.domain];
5135
+ const mapped = Object.keys(entity.capabilities);
5136
+ if (mapped.filter((capability) => rule.oneOf.includes(capability)).length !== 1) add(["capabilities"], `A ${entity.domain} has ${rule.oneOf.join(" or ")}`);
5137
+ for (const capability of mapped) {
5138
+ if (!rule.oneOf.includes(capability) && !rule.may.includes(capability)) {
5139
+ add(["capabilities", capability], `A ${entity.domain} has no ${capability}`);
5140
+ continue;
5141
+ }
5142
+ const map = entity.capabilities[capability];
5143
+ if (map !== void 0) checkCapability(capability, map, (path, message) => {
5144
+ add([
5145
+ "capabilities",
5146
+ capability,
5147
+ ...path
5148
+ ], message);
5149
+ });
5150
+ }
5151
+ });
5152
+ });
4534
5153
  /**
4535
- * Validates an integration kind: `shelly/gen2`, `bambulab/printer`.
5154
+ * The template with every entity's id filled in from its name, as it is saved: renaming an entity
5155
+ * afterwards keeps its id, so the entity of the house it is stays the same.
4536
5156
  *
4537
- * Vendor-qualified, so two vendors may each have a `gen2` and an instance row names one of
4538
- * them without ambiguity. Not an instance of one: an instance gets its own id. The pattern is
4539
- * the contracts package's, because the API checks the same string at its boundary.
5157
+ * @param template - The template.
5158
+ * @returns The same, every entity with an id.
5159
+ */
5160
+ function withModbusEntityIds(template) {
5161
+ return {
5162
+ ...template,
5163
+ entities: template.entities.map((entity) => entity.id === void 0 ? {
5164
+ ...entity,
5165
+ id: modbusEntityIdOf(entity.name)
5166
+ } : entity)
5167
+ };
5168
+ }
5169
+ /** The widest network a range may name: a /16. */
5170
+ const NARROWEST_PREFIX = 16;
5171
+ /** The most addresses one range may hold, and all of them together. */
5172
+ const MODBUS_SEARCH_MAXIMUM = 65536;
5173
+ /**
5174
+ * The number an IPv4 address is.
5175
+ *
5176
+ * @param text - Dotted, `192.168.1.7`.
5177
+ * @returns The number, or null for anything that is not an address.
5178
+ */
5179
+ function ipv4Of(text) {
5180
+ const parts = text.trim().split(".");
5181
+ if (parts.length !== 4 || parts.some((part) => !/^\d{1,3}$/u.test(part) || Number(part) > 255)) return null;
5182
+ return parts.reduce((total, part) => total * 256 + Number(part), 0);
5183
+ }
5184
+ /**
5185
+ * The addresses a range the owner wrote names.
5186
+ *
5187
+ * @param text - A network `10.0.0.0/24` (a /16 to a /32), a span `10.0.0.20-10.0.0.40` of at most
5188
+ * 65536 addresses, or one address.
5189
+ * @returns The first and last address as numbers, or null when it is none of those.
5190
+ */
5191
+ function ipv4RangeOf(text) {
5192
+ const trimmed = text.trim();
5193
+ const network = /^([\d.]+)\/(\d{1,2})$/u.exec(trimmed);
5194
+ if (network !== null) {
5195
+ const base = ipv4Of(network[1] ?? "");
5196
+ const prefix = Number(network[2]);
5197
+ if (base === null || prefix < NARROWEST_PREFIX || prefix > 32) return null;
5198
+ const size = 2 ** (32 - prefix);
5199
+ const first = base - base % size;
5200
+ return {
5201
+ first,
5202
+ last: first + size - 1
5203
+ };
5204
+ }
5205
+ const span = /^([\d.]+)\s*-\s*([\d.]+)$/u.exec(trimmed);
5206
+ if (span !== null) {
5207
+ const first = ipv4Of(span[1] ?? "");
5208
+ const last = ipv4Of(span[2] ?? "");
5209
+ return first === null || last === null || last < first || last - first + 1 > 65536 ? null : {
5210
+ first,
5211
+ last
5212
+ };
5213
+ }
5214
+ const single = ipv4Of(trimmed);
5215
+ return single === null ? null : {
5216
+ first: single,
5217
+ last: single
5218
+ };
5219
+ }
5220
+ /** The owner's settings: whether and where the network is searched, and how often. */
5221
+ const modbusSettingsSchema = z.object({
5222
+ isSearchEnabled: z.boolean().default(false),
5223
+ /** Where to search; the networks the hub is on, up to a /22 each, when there is none. */
5224
+ ranges: z.array(z.string().trim().max(64).refine((range) => ipv4RangeOf(range) !== null, "Not a range: write 10.0.0.0/24, 10.0.0.20-10.0.0.40 or 10.0.0.7")).max(16).default([]),
5225
+ intervalMinutes: z.int().min(15).max(1440).default(120)
5226
+ }).refine((settings) => settings.ranges.reduce((total, range) => {
5227
+ const span = ipv4RangeOf(range);
5228
+ return total + (span === null ? 0 : span.last - span.first + 1);
5229
+ }, 0) <= MODBUS_SEARCH_MAXIMUM, {
5230
+ message: `At most ${String(MODBUS_SEARCH_MAXIMUM)} addresses in all`,
5231
+ path: ["ranges"]
5232
+ });
5233
+ /** A host: an IPv4 address or a name. */
5234
+ const hostSchema = z.string().trim().min(1).max(253).regex(/^[A-Za-z0-9.-]+$/u, "An address or a host name");
5235
+ /** One device behind a server: the server, and its unit. */
5236
+ const modbusTargetSchema = z.object({
5237
+ host: hostSchema,
5238
+ port: z.int().min(1).max(65535).default(502),
5239
+ framing: z.enum(MODBUS_FRAMINGS).default("tcp")
5240
+ }).extend({ unitId: z.int().min(1).max(247).default(1) });
5241
+ /** One search of the network, as it ended. */
5242
+ const modbusSearchRunSchema = z.object({
5243
+ at: timestampSchema,
5244
+ durationMs: z.int().min(0),
5245
+ /** How many addresses it knocked on, and how many answered on the port. */
5246
+ addresses: z.int().min(0),
5247
+ answered: z.int().min(0)
5248
+ });
5249
+ z.object({
5250
+ state: z.enum(BROKER_STATES),
5251
+ error: z.string().max(2048).nullable(),
5252
+ startedAt: timestampSchema.nullable(),
5253
+ settings: modbusSettingsSchema,
5254
+ search: z.object({
5255
+ isRunning: z.boolean(),
5256
+ lastRun: modbusSearchRunSchema.nullable(),
5257
+ /** When the next one starts; null while searching is off. */
5258
+ nextAt: timestampSchema.nullable()
5259
+ }),
5260
+ devices: z.object({
5261
+ total: z.int().min(0),
5262
+ online: z.int().min(0)
5263
+ }),
5264
+ /** How many servers the hub holds a connection to. */
5265
+ gateways: z.int().min(0),
5266
+ /** Requests in the last minute, and how long they took on average; null before any. */
5267
+ requestsPerMinute: z.int().min(0),
5268
+ averageMs: z.number().min(0).nullable()
5269
+ });
5270
+ /** A device of the house, with how it answers. */
5271
+ const modbusDeviceSchema = modbusTargetSchema.extend({
5272
+ /** Its id; a new one is given one. */
5273
+ id: z.uuid().optional(),
5274
+ name: z.string().trim().min(1).max(128),
5275
+ /** The template it is read with: one of the owner's, by id, or an integration's driver. */
5276
+ template: z.union([z.uuid(), integrationKindIdSchema]),
5277
+ /** How often it is read, instead of what the template says; null for the template's. */
5278
+ pollSeconds: z.int().min(1).max(3600).nullable().default(null)
5279
+ }).extend({
5280
+ id: z.uuid(),
5281
+ /** The template's name; null when it is gone - an integration removed. */
5282
+ templateName: z.string().max(64).nullable(),
5283
+ /** The integration whose template it is; null for one of the owner's. */
5284
+ vendorId: z.string().regex(VENDOR_ID_PATTERN$1).nullable(),
5285
+ /** How often it is read now. */
5286
+ everySeconds: z.int().min(1),
5287
+ state: z.enum([
5288
+ "online",
5289
+ "offline",
5290
+ "waiting"
5291
+ ]),
5292
+ lastReadAt: timestampSchema.nullable(),
5293
+ /** Why the last read failed, in a sentence; null when it did not. */
5294
+ lastError: z.string().max(512).nullable(),
5295
+ /** The device added for it; null until it is. */
5296
+ deviceId: integrationIdSchema.nullable()
5297
+ });
5298
+ z.object({ items: z.array(modbusDeviceSchema) });
5299
+ z.object({ id: z.uuid() });
5300
+ z.object({ isRemoved: z.boolean() });
5301
+ /** A template, with whose it is and who uses it. */
5302
+ const modbusTemplateRecordSchema = z.object({
5303
+ /** One of the owner's by uuid, or an integration's by its driver: `vendor/driver`. */
5304
+ id: z.string().min(1).max(160),
5305
+ /** The integration that ships it, and its name; null for one of the owner's. */
5306
+ vendorId: z.string().regex(VENDOR_ID_PATTERN$1).nullable(),
5307
+ vendorName: z.string().max(128).nullable(),
5308
+ document: modbusTemplateSchema,
5309
+ /** An integration's is read-only: it is duplicated to be changed. */
5310
+ isReadOnly: z.boolean(),
5311
+ usedBy: z.int().min(0),
5312
+ updatedAt: timestampSchema.nullable()
5313
+ });
5314
+ z.object({ items: z.array(modbusTemplateRecordSchema) });
5315
+ z.object({
5316
+ id: z.uuid().optional(),
5317
+ document: modbusTemplateSchema
5318
+ });
5319
+ /** An integration that recognises a server, and the driver it would read it with. */
5320
+ const modbusClaimSchema = z.object({
5321
+ vendorId: z.string().regex(VENDOR_ID_PATTERN$1),
5322
+ vendorName: z.string().max(128),
5323
+ /** The driver it would be added as; null when the integration has no template for it. */
5324
+ kind: integrationKindIdSchema.nullable(),
5325
+ model: z.string().max(128).nullable(),
5326
+ unitId: z.int().min(1).max(247)
5327
+ });
5328
+ /** A server the network search found that is not a device of the house. */
5329
+ const modbusFoundSchema = z.object({
5330
+ host: z.string().max(253),
5331
+ port: z.int().min(1).max(65535),
5332
+ foundAt: timestampSchema,
5333
+ claims: z.array(modbusClaimSchema).max(16)
5334
+ });
5335
+ /** A server the owner ignores: it is never offered again. */
5336
+ const modbusIgnoredSchema = z.object({
5337
+ host: z.string().max(253),
5338
+ port: z.int().min(1).max(65535),
5339
+ at: timestampSchema
5340
+ });
5341
+ z.object({
5342
+ items: z.array(modbusFoundSchema),
5343
+ ignored: z.array(modbusIgnoredSchema)
5344
+ });
5345
+ z.object({
5346
+ host: hostSchema,
5347
+ port: z.int().min(1).max(65535),
5348
+ isIgnored: z.boolean()
5349
+ });
5350
+ z.object({ count: z.int().min(0) });
5351
+ z.object({ target: modbusTargetSchema });
5352
+ z.object({
5353
+ isAnswering: z.boolean(),
5354
+ ms: z.int().min(0).nullable(),
5355
+ /** Why it did not answer, or the exception it answered with, in a sentence. */
5356
+ error: z.string().max(512).nullable(),
5357
+ claims: z.array(modbusClaimSchema).max(16)
5358
+ });
5359
+ /** What a test read or write sent and got back. */
5360
+ const exchangeShape = {
5361
+ /** The request's PDU, hex: `01 00 00 00 01`. */
5362
+ request: z.string().max(1024),
5363
+ /** The answer's PDU, hex; null when none came. */
5364
+ response: z.string().max(1024).nullable(),
5365
+ /** Why it failed, in a sentence; null when it did not. */
5366
+ error: z.string().max(512).nullable(),
5367
+ ms: z.int().min(0)
5368
+ };
5369
+ /** A value as a test shows it. */
5370
+ const testValueSchema = z.union([
5371
+ z.number(),
5372
+ z.string(),
5373
+ z.boolean()
5374
+ ]).nullable();
5375
+ z.object({
5376
+ target: modbusTargetSchema,
5377
+ wordOrder: z.enum(["high", "low"]).default("high"),
5378
+ read: modbusReadSchema
5379
+ });
5380
+ z.object({
5381
+ ...exchangeShape,
5382
+ raw: z.array(z.int()).max(128).nullable(),
5383
+ value: testValueSchema
5384
+ });
5385
+ z.object({
5386
+ target: modbusTargetSchema,
5387
+ wordOrder: z.enum(["high", "low"]).default("high"),
5388
+ entity: modbusEntitySchema,
5389
+ capability: z.enum(MODBUS_CAPABILITIES),
5390
+ command: z.record(z.string(), z.unknown())
5391
+ });
5392
+ z.object(exchangeShape);
5393
+ z.object({
5394
+ target: modbusTargetSchema,
5395
+ document: modbusTemplateSchema
5396
+ });
5397
+ z.object({
5398
+ at: timestampSchema,
5399
+ ms: z.int().min(0),
5400
+ values: z.array(z.object({
5401
+ entity: z.int().min(0),
5402
+ capability: z.enum(MODBUS_CAPABILITIES),
5403
+ value: testValueSchema,
5404
+ error: z.string().max(512).nullable()
5405
+ }))
5406
+ });
5407
+ //#endregion
5408
+ //#region ../contracts/dist/mqtt.js
5409
+ /**
5410
+ * The house's MQTT broker, as the hub runs it and the Brokers page shows it.
5411
+ *
5412
+ * MQTT is one of the platform's brokers: the hub listens on the house's network - port 1883 - and
5413
+ * every MQTT device and program of the house meets on it. Who may connect is the broker's to say:
5414
+ * the hub, a container the platform runs (Zigbee2MQTT), and each client the owner adds, held to
5415
+ * the topics it was given.
5416
+ *
5417
+ * What it carries becomes devices of the house two ways. A device that announces itself - the
5418
+ * MQTT discovery convention most firmware speaks, a retained JSON document on
5419
+ * `<prefix>/<component>/[<node>/]<object>/config` - is added at once, and so is one the owner
5420
+ * maps by hand from the topic it publishes on. Each is a device of the integration whose
5421
+ * `discovery.json` recognises it from {@link mqttIdentitySchema}, or of the platform's own `mqtt`
5422
+ * vendor when none does.
5423
+ */
5424
+ /** The platform transport every device the broker hears is reached through. */
5425
+ const MQTT_HOUSE_TRANSPORT = "mqtt-house";
5426
+ /** The components of an announcement the broker turns into entities. */
5427
+ const MQTT_COMPONENTS = [
5428
+ "sensor",
5429
+ "binary_sensor",
5430
+ "switch",
5431
+ "light",
5432
+ "cover",
5433
+ "button",
5434
+ "number",
5435
+ "select",
5436
+ "lock"
5437
+ ];
5438
+ /** What the owner maps by hand: a sensor, a binary sensor or a switch. */
5439
+ const MQTT_MAPPING_COMPONENTS = [
5440
+ "sensor",
5441
+ "binary_sensor",
5442
+ "switch"
5443
+ ];
5444
+ /** How many items a list in an identity holds at most. */
5445
+ const MAXIMUM_LIST = 64;
5446
+ /** The owner's settings of the broker. */
5447
+ const mqttSettingsSchema = z.object({
5448
+ /** Whether a client may connect without a username. */
5449
+ allowAnonymous: z.boolean().default(false),
5450
+ /** Whether devices that announce themselves are added. */
5451
+ isDiscoveryEnabled: z.boolean().default(true),
5452
+ /** The topic announcements are published under: what the devices' firmware uses. */
5453
+ discoveryPrefix: z.string().trim().max(64).regex(/^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/u, "Topic levels of letters, digits, - and _").default("homeassistant")
5454
+ });
5455
+ /**
5456
+ * Who a device the broker hears says it is: what an integration's rules match and the Brokers
5457
+ * page shows.
5458
+ *
5459
+ * What an announcement's `device` and `origin` blocks say, each field null when it does not say
5460
+ * it. `deviceKey` is the device's own identifier - its first identifier, or its first connection
5461
+ * - which is also its external id.
5462
+ */
5463
+ const mqttIdentitySchema = z.object({
5464
+ deviceKey: z.string().min(1).max(256),
5465
+ source: z.enum([
5466
+ "announced",
5467
+ "mapped",
5468
+ "broker"
5469
+ ]),
5470
+ name: z.string().max(256),
5471
+ manufacturer: z.string().max(256).nullable(),
5472
+ model: z.string().max(256).nullable(),
5473
+ modelId: z.string().max(256).nullable(),
5474
+ swVersion: z.string().max(256).nullable(),
5475
+ hwVersion: z.string().max(256).nullable(),
5476
+ serialNumber: z.string().max(256).nullable(),
5477
+ /** Every identifier it announces. */
5478
+ identifiers: z.array(z.string().max(256)).max(MAXIMUM_LIST),
5479
+ /** The hardware addresses among its connections, lower-case and colon-separated. */
5480
+ macAddresses: z.array(z.string().max(64)).max(MAXIMUM_LIST),
5481
+ /** The device it is reached through, by that device's identifier. */
5482
+ viaDevice: z.string().max(256).nullable(),
5483
+ /** The firmware or program that announced it - `Tasmota`, `Zigbee2MQTT` - and its version. */
5484
+ originName: z.string().max(256).nullable(),
5485
+ originSwVersion: z.string().max(256).nullable(),
5486
+ /** The components its entities are, each once. */
5487
+ components: z.array(z.enum(MQTT_COMPONENTS)).max(MQTT_COMPONENTS.length)
5488
+ });
5489
+ /** An announcement the broker did not take, and why. */
5490
+ const mqttSkippedSchema = z.object({
5491
+ topic: z.string().max(512),
5492
+ reason: z.string().max(512)
5493
+ });
5494
+ z.object({
5495
+ state: z.enum(BROKER_STATES),
5496
+ /** Why it failed, in a sentence; null while it runs. */
5497
+ error: z.string().max(2048).nullable(),
5498
+ /** The TCP port it listens on, or is to. */
5499
+ port: z.int().min(0).max(65535),
5500
+ /** When it last started listening; null while it is not. */
5501
+ startedAt: timestampSchema.nullable(),
5502
+ settings: mqttSettingsSchema,
5503
+ clientsOnline: z.int().min(0),
5504
+ messagesPerSecond: z.number().min(0),
5505
+ /** What it makes of what it carries: the entities announced and mapped, and their devices. */
5506
+ discovery: z.object({
5507
+ announced: z.int().min(0),
5508
+ mapped: z.int().min(0),
5509
+ devices: z.int().min(0),
5510
+ /** The latest announcements it did not take, the newest last. */
5511
+ skipped: z.array(mqttSkippedSchema).max(50)
5512
+ })
5513
+ });
5514
+ /** One device the broker hears, with the device it is in the house. */
5515
+ const mqttDeviceSchema = z.object({
5516
+ identity: mqttIdentitySchema,
5517
+ /** How many entities it has. */
5518
+ entityCount: z.int().min(0),
5519
+ /** The device added for it; null while it is not, or after it was removed from the house. */
5520
+ deviceId: integrationIdSchema.nullable(),
5521
+ /** The driver it was added as; null while it is not added. */
5522
+ kind: integrationKindIdSchema.nullable(),
5523
+ /**
5524
+ * The integrations whose rules all take it. One is the integration it belongs to; several, and
5525
+ * it is added as the platform's own and the page says who else wants it.
5526
+ */
5527
+ claimedBy: z.array(z.string().regex(VENDOR_ID_PATTERN$1)).max(16),
5528
+ /** Removed from the house while the broker still hears it: the page offers it back. */
5529
+ isRemoved: z.boolean()
5530
+ });
5531
+ z.object({ items: z.array(mqttDeviceSchema) });
5532
+ z.object({ deviceKey: z.string().min(1).max(256) });
5533
+ z.object({ isRestored: z.boolean() });
5534
+ /** Who a username is: the hub, a container the platform runs, or a client the owner added. */
5535
+ const MQTT_PRINCIPAL_KINDS = [
5536
+ "hub",
5537
+ "container",
5538
+ "client"
5539
+ ];
5540
+ /** One connection to the broker. */
5541
+ const mqttSessionSchema = z.object({
5542
+ clientId: z.string().max(256),
5543
+ username: z.string().max(64).nullable(),
5544
+ address: z.string().max(256).nullable(),
5545
+ connectedAt: timestampSchema
5546
+ });
5547
+ /** One username, what it may reach, and its connections now. */
5548
+ const mqttPrincipalSchema = z.object({
5549
+ username: z.string().max(64),
5550
+ kind: z.enum(MQTT_PRINCIPAL_KINDS),
5551
+ label: z.string().max(128),
5552
+ publish: z.array(z.string().max(256)).max(32),
5553
+ subscribe: z.array(z.string().max(256)).max(32),
5554
+ createdAt: timestampSchema,
5555
+ sessions: z.array(mqttSessionSchema)
5556
+ });
5557
+ z.object({
5558
+ items: z.array(mqttPrincipalSchema),
5559
+ anonymous: z.array(mqttSessionSchema)
5560
+ });
5561
+ /** The usernames the platform keeps for itself begin with this. */
5562
+ const MQTT_PLATFORM_PREFIX = "nebula-";
5563
+ z.object({
5564
+ username: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/u, "Lower-case letters, digits, - and _").refine((username) => !username.startsWith(MQTT_PLATFORM_PREFIX), { message: `Usernames beginning with ${MQTT_PLATFORM_PREFIX} are the platform's` }),
5565
+ label: z.string().trim().max(64).default(""),
5566
+ access: z.enum(["prefix", "all"]).default("prefix")
5567
+ });
5568
+ z.object({
5569
+ username: z.string().max(64),
5570
+ password: z.string().min(1)
5571
+ });
5572
+ z.object({ username: z.string().min(1).max(64) });
5573
+ z.object({ isRemoved: z.boolean() });
5574
+ z.object({
5575
+ prefix: z.string().max(256).default(""),
5576
+ limit: z.int().min(1).max(2e3).default(500)
5577
+ });
5578
+ /** One topic, and its last message. */
5579
+ const mqttTopicSchema = z.object({
5580
+ topic: z.string(),
5581
+ /** Its last payload as text, cut; `<n bytes>` for one that is not text. */
5582
+ payload: z.string(),
5583
+ size: z.int().min(0),
5584
+ isRetained: z.boolean(),
5585
+ updatedAt: timestampSchema,
5586
+ /** How many messages it carried since the broker started. */
5587
+ count: z.int().min(0)
5588
+ });
5589
+ z.object({
5590
+ items: z.array(mqttTopicSchema),
5591
+ total: z.int().min(0)
5592
+ });
5593
+ /** A topic a client may publish on: no wildcards, no `$`. */
5594
+ const mappedTopicSchema = z.string().trim().min(1).max(256).regex(/^[^#+$][^#+]*$/u, "A topic, without wildcards");
5595
+ /** A mapping, saved. */
5596
+ const mqttMappingSchema = z.strictObject({
5597
+ /** Its id; a new one is given one. */
5598
+ id: z.string().regex(/^[a-z0-9-]{1,40}$/u).optional(),
5599
+ name: z.string().trim().min(1).max(64),
5600
+ component: z.enum(MQTT_MAPPING_COMPONENTS),
5601
+ stateTopic: mappedTopicSchema,
5602
+ /** Where the value is in a JSON payload, dotted: `AM2301.Temperature`. Empty for the payload. */
5603
+ valuePath: z.string().trim().max(128).regex(/^$|^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*$/u, "Keys separated by dots").default(""),
5604
+ unit: z.string().trim().max(16).default(""),
5605
+ deviceClass: z.string().trim().max(32).default(""),
5606
+ commandTopic: mappedTopicSchema.optional(),
5607
+ payloadOn: z.string().max(64).default("ON"),
5608
+ payloadOff: z.string().max(64).default("OFF")
5609
+ }).extend({ id: z.string().regex(/^[a-z0-9-]{1,40}$/u) });
5610
+ z.object({ items: z.array(mqttMappingSchema) });
5611
+ z.object({ id: z.string().min(1).max(64) });
5612
+ z.object({ isRemoved: z.boolean() });
5613
+ z.strictObject({
5614
+ /** Whose container: `vendor:zigbee2mqtt`, `package:nvr`. */
5615
+ owner: z.string().regex(/^(?:vendor:[a-z]|package:[a-z0-9])[a-z0-9-]{1,63}$/u),
5616
+ /** The topics it may use; every topic when not said. */
5617
+ topics: z.array(z.string().min(1).max(256)).max(16).optional()
5618
+ });
5619
+ z.object({
5620
+ username: z.string().min(1),
5621
+ password: z.string().min(1),
5622
+ port: z.int().min(1).max(65535)
5623
+ });
5624
+ //#endregion
5625
+ //#region ../package-runtime/dist/containers.js
5626
+ /** A vendor setting a value is filled from: `{setup.serialPath}`. */
5627
+ const SETTING_PLACEHOLDER = /\{setup\.([a-zA-Z][a-zA-Z0-9]*)\}/g;
5628
+ /**
5629
+ * Every setting a declaration reads: its `when` keys and its placeholders.
5630
+ *
5631
+ * @param dep - One declared container.
5632
+ * @returns The keys.
5633
+ */
5634
+ function settingsRead(dep) {
5635
+ const keys = /* @__PURE__ */ new Set();
5636
+ const texts = [
5637
+ ...dep.env.map((entry) => entry.value),
5638
+ ...dep.devices.map((device) => device.host),
5639
+ ...dep.ports.flatMap((port) => [String(port.container), String(port.host)]),
5640
+ ...dep.webPort === void 0 ? [] : [String(dep.webPort)]
5641
+ ];
5642
+ for (const text of texts) for (const match of text.matchAll(SETTING_PLACEHOLDER)) keys.add(match[1] ?? "");
5643
+ const conditions = [
5644
+ ...dep.env.map((entry) => entry.when),
5645
+ ...dep.devices.map((device) => device.when),
5646
+ ...dep.ports.map((port) => port.when),
5647
+ dep.webPortWhen
5648
+ ];
5649
+ for (const condition of conditions) if (condition !== void 0) keys.add(condition.key);
5650
+ return keys;
5651
+ }
5652
+ /**
5653
+ * Checks a vendor's declared containers against its own settings, once, at load: every setting
5654
+ * a declaration reads must be one the vendor's `setup.json` asks.
5655
+ *
5656
+ * @param deps - The declared containers.
5657
+ * @param setup - The vendor's own setup, or undefined for a vendor with none.
5658
+ * @returns What is wrong, one sentence each; empty when nothing is.
5659
+ */
5660
+ function containerDependencyProblems(deps, setup) {
5661
+ const asked = new Set([...setup?.transport.fields ?? [], ...setup?.options.fields ?? []].map((field) => field.key));
5662
+ return deps.flatMap((dep) => [...[...settingsRead(dep)].filter((key) => !asked.has(key)).map((key) => `${dep.id} reads the setting ${key}, which the vendor's setup.json does not ask`), ...dep.seed.filter((seed) => !dep.volumes.some((volume) => volume.name === seed.volume)).map((seed) => `${dep.id} seeds ${seed.path} into ${seed.volume}, which it does not declare`)]);
5663
+ }
5664
+ //#endregion
5665
+ //#region ../package-runtime/dist/bundle.js
5666
+ /**
5667
+ * The two manifests a bundle is written as, and the one the runtime reads.
5668
+ *
5669
+ * A bundle is how an integration is distributed: a **vendor** directory - the company that
5670
+ * makes the devices, with a logo, a version, and whatever settings every device of theirs
5671
+ * shares - holding one **driver** directory per profile or entry point, each listing the
5672
+ * models it drives. Two files, because the two levels answer different questions: `manifest.json`
5673
+ * is what a catalogue lists and an owner recognises, `driver.json` is what the runtime loads
5674
+ * and an instance references. The split is also what ends the duplication the old flat layout
5675
+ * had, where every driver of one vendor repeated the vendor's name and description and the
5676
+ * three copies drifted.
5677
+ *
5678
+ * What the rest of the runtime reads is neither file but their composition, the
5679
+ * {@link BundleManifest}: the vendor's identity and version beside the driver's transport and
5680
+ * entry point, keyed by the vendor-qualified kind. {@link resolveManifest} is the only place the
5681
+ * two are joined, so a field that moves between the files moves in one function.
5682
+ *
5683
+ * `kind` is a trust boundary as much as a format. A declarative driver is data - it cannot do
5684
+ * anything a path cannot express - so a catalogue can publish one directly. A code driver is
5685
+ * JavaScript, and reaches a catalogue only after the manual approval ARCHITECTURE.md 10 already
5686
+ * requires of executable content.
5687
+ */
5688
+ /**
5689
+ * Bundle kind, which is both how it is written and how far it is trusted. `matter`, `mqtt` and
5690
+ * `modbus` are drivers one of the platform's broker mappings runs: no profile and no code, so as
5691
+ * far trusted as a profile. A `modbus` driver names its template, which the mapping reads.
5692
+ */
5693
+ const BUNDLE_KINDS = [
5694
+ "declarative",
5695
+ "code",
5696
+ "matter",
5697
+ "mqtt",
5698
+ "modbus"
5699
+ ];
5700
+ /** The transport each kind the platform's mappings run is reached on. */
5701
+ const MAPPED_KINDS = {
5702
+ matter: MATTER_TRANSPORT,
5703
+ mqtt: MQTT_HOUSE_TRANSPORT,
5704
+ modbus: MODBUS_TRANSPORT
5705
+ };
5706
+ /** Validates a vendor id. */
5707
+ const vendorIdSchema = z.string().regex(/^[a-z][a-z0-9-]{1,63}$/, "Must be a vendor id");
5708
+ /** Validates a driver id. */
5709
+ const driverIdSchema = z.string().regex(/^[a-z0-9][a-z0-9-]{1,63}$/, "Must be a driver id");
5710
+ /**
5711
+ * Validates an integration kind: `shelly/gen2`, `bambulab/printer`.
5712
+ *
5713
+ * Vendor-qualified, so two vendors may each have a `gen2` and an instance row names one of
5714
+ * them without ambiguity. Not an instance of one: an instance gets its own id. The pattern is
5715
+ * the contracts package's, because the API checks the same string at its boundary.
4540
5716
  */
4541
5717
  const integrationKindSchema = z.string().regex(INTEGRATION_KIND_PATTERN, "Must be an integration kind, as vendor/driver");
4542
5718
  /** The name a vendor ships a transport under; the vendor's id in front of it makes the id. */
@@ -4593,6 +5769,12 @@ const vendorManifestSchema = z.strictObject({
4593
5769
  /** Whether the devices stop working when the internet does. Shown as a warning on the card. */
4594
5770
  internetRequired: z.boolean().default(false),
4595
5771
  /**
5772
+ * What makes two of the vendor's devices one device reached two ways - over its own transport
5773
+ * and through the Matter broker, say: `["mac"]`, or `["mac", "serial"]` for both to agree.
5774
+ * The house then offers to link them. Absent, it never does.
5775
+ */
5776
+ twins: z.array(z.enum(TWIN_FACTS)).min(1).max(TWIN_FACTS.length).optional(),
5777
+ /**
4596
5778
  * Path to a `setup.json` of settings every device of this vendor shares - a cloud API key,
4597
5779
  * an account - relative to the bundle. Absent for the vendors whose devices are reached
4598
5780
  * directly, which is most of them.
@@ -4633,8 +5815,9 @@ const vendorManifestSchema = z.strictObject({
4633
5815
  /**
4634
5816
  * The packages and services the vendor's devices need, in the grammar a package's
4635
5817
  * manifest names its own with (PACKAGES.md 7) - `{ "services": ["mqtt-broker"] }` for a vendor
4636
- * that talks through the broker. Until what it needs runs, the vendor waits: its devices are
4637
- * not added and its instances are not started, and its page says which package it waits for.
5818
+ * that talks through the house's broker, which the platform runs and is always met. Until what
5819
+ * it needs runs, the vendor waits: its devices are not added and its instances are not started,
5820
+ * and its page says which package it waits for.
4638
5821
  */
4639
5822
  requires: packageRequiresSchema,
4640
5823
  /**
@@ -4711,6 +5894,8 @@ const driverShape = {
4711
5894
  profile: bundlePathSchema.optional(),
4712
5895
  /** Path to the entry point, relative to the driver. Code drivers only. */
4713
5896
  entry: bundlePathSchema.optional(),
5897
+ /** Path to the Modbus template, relative to the driver. Modbus drivers only. */
5898
+ template: bundlePathSchema.optional(),
4714
5899
  /**
4715
5900
  * Path to `setup.json`, relative to the driver: what setting up an instance asks.
4716
5901
  *
@@ -4726,16 +5911,27 @@ const driverShape = {
4726
5911
  * @param ctx - Where to record what is wrong.
4727
5912
  */
4728
5913
  function checkKindFiles(manifest, ctx) {
4729
- if (manifest.kind === "matter") {
5914
+ const mapped = MAPPED_KINDS[manifest.kind];
5915
+ if (manifest.kind === "modbus" && manifest.template === void 0) ctx.addIssue({
5916
+ code: "custom",
5917
+ path: ["template"],
5918
+ message: "A modbus driver must name its template"
5919
+ });
5920
+ if (manifest.kind !== "modbus" && manifest.template !== void 0) ctx.addIssue({
5921
+ code: "custom",
5922
+ path: ["template"],
5923
+ message: `A ${manifest.kind} driver must not name a template`
5924
+ });
5925
+ if (mapped !== void 0) {
4730
5926
  for (const named of ["profile", "entry"]) if (manifest[named] !== void 0) ctx.addIssue({
4731
5927
  code: "custom",
4732
5928
  path: [named],
4733
- message: `A matter driver must not name an ${named}`
5929
+ message: `A ${manifest.kind} driver must not name an ${named}`
4734
5930
  });
4735
- if (manifest.transport !== "matter") ctx.addIssue({
5931
+ if (manifest.transport !== mapped) ctx.addIssue({
4736
5932
  code: "custom",
4737
5933
  path: ["transport"],
4738
- message: `A matter driver runs on the ${MATTER_TRANSPORT} transport`
5934
+ message: `A ${manifest.kind} driver runs on the ${mapped} transport`
4739
5935
  });
4740
5936
  return;
4741
5937
  }
@@ -4850,6 +6046,7 @@ function resolveManifest(vendor, driver) {
4850
6046
  ...driver.webPagePath === void 0 ? {} : { webPagePath: driver.webPagePath },
4851
6047
  ...driver.profile === void 0 ? {} : { profile: driver.profile },
4852
6048
  ...driver.entry === void 0 ? {} : { entry: driver.entry },
6049
+ ...driver.template === void 0 ? {} : { template: driver.template },
4853
6050
  setup: driver.setup
4854
6051
  };
4855
6052
  }
@@ -5194,7 +6391,7 @@ function readStateSource(value, payload) {
5194
6391
  if (typeof value === "string") return resolvePath(payload, value);
5195
6392
  if ("present" in value) return resolvePresence(payload, value.path);
5196
6393
  const resolved = resolvePath(payload, value.path);
5197
- const found = resolved === void 0 || value.bits === void 0 && value.base === void 0 ? resolved : numberOf$1(resolved, value.bits, value.base ?? 10);
6394
+ const found = resolved === void 0 || value.bits === void 0 && value.base === void 0 ? resolved : numberOf$2(resolved, value.bits, value.base ?? 10);
5198
6395
  if (found === void 0) return;
5199
6396
  if ("map" in value) {
5200
6397
  const key = typeof found === "string" || typeof found === "number" || typeof found === "boolean" ? String(found) : void 0;
@@ -5212,7 +6409,7 @@ function readStateSource(value, payload) {
5212
6409
  * @returns The number, or its bits unsigned; undefined when the value is no number, or no integer
5213
6410
  * where bits are read.
5214
6411
  */
5215
- function numberOf$1(value, bits, base) {
6412
+ function numberOf$2(value, bits, base) {
5216
6413
  const text = typeof value === "string" ? value.trim() : void 0;
5217
6414
  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);
5218
6415
  if (!Number.isFinite(number)) return;
@@ -5410,6 +6607,8 @@ function createDeclarativeIntegration(manifest, profile) {
5410
6607
  const model = text(identity.model);
5411
6608
  const swVersion = text(identity.swVersion);
5412
6609
  const hwVersion = text(identity.hwVersion);
6610
+ const mac = normalizeMac(text(identity.mac)) ?? void 0;
6611
+ const serialNumber = text(identity.serialNumber);
5413
6612
  const entities = profile.entities.map((entity) => {
5414
6613
  const measurement = registeredMeasurement(entity);
5415
6614
  return {
@@ -5419,7 +6618,8 @@ function createDeclarativeIntegration(manifest, profile) {
5419
6618
  ...entity.icon === void 0 ? {} : { icon: entity.icon },
5420
6619
  capabilities: entity.capabilities,
5421
6620
  ...measurement,
5422
- ...entity.displayPrecision === void 0 ? {} : { displayPrecision: entity.displayPrecision }
6621
+ ...entity.displayPrecision === void 0 ? {} : { displayPrecision: entity.displayPrecision },
6622
+ ...entity.link === void 0 ? {} : { link: entity.link }
5423
6623
  };
5424
6624
  });
5425
6625
  return {
@@ -5429,6 +6629,8 @@ function createDeclarativeIntegration(manifest, profile) {
5429
6629
  ...model === void 0 ? {} : { model },
5430
6630
  ...swVersion === void 0 ? {} : { swVersion },
5431
6631
  ...hwVersion === void 0 ? {} : { hwVersion },
6632
+ ...mac === void 0 ? {} : { mac },
6633
+ ...serialNumber === void 0 ? {} : { serialNumber },
5432
6634
  entities
5433
6635
  };
5434
6636
  },
@@ -5690,7 +6892,13 @@ const identityMappingSchema = z.strictObject({
5690
6892
  manufacturer: pathSchema.optional(),
5691
6893
  model: pathSchema.optional(),
5692
6894
  swVersion: pathSchema.optional(),
5693
- hwVersion: pathSchema.optional()
6895
+ hwVersion: pathSchema.optional(),
6896
+ /**
6897
+ * The hardware's MAC address, written any way - `08F9E0124C7A`, `08:f9:e0:12:4c:7a` - so the
6898
+ * house can tell this device from the same one reached another way.
6899
+ */
6900
+ mac: pathSchema.optional(),
6901
+ serialNumber: pathSchema.optional()
5694
6902
  });
5695
6903
  /**
5696
6904
  * A path into the command, with what to do to what it names.
@@ -5786,6 +6994,13 @@ const entityProfileSchema = z.strictObject({
5786
6994
  stateClass: z.enum(ENTITY_STATE_CLASSES).optional(),
5787
6995
  displayPrecision: z.int().min(0).max(6).optional(),
5788
6996
  /**
6997
+ * What links it to the same reading reached another way: its key in the transport's terms
6998
+ * (`switch:0`), shown beside the transport's name, and where that reading sits in Matter
6999
+ * (`{ "endpoint": 1, "cluster": 6, "attribute": 0 }`), for a device the house also reaches
7000
+ * through the Matter broker.
7001
+ */
7002
+ link: entityLinkHintSchema.optional(),
7003
+ /**
5789
7004
  * For a camera: the stream source that reads its picture, `<vendor>/<name>`, and what it is
5790
7005
  * told to read. The source is handed the instance's transport settings as well.
5791
7006
  */
@@ -5935,7 +7150,15 @@ const discoveryIdentitySchema = z.strictObject({
5935
7150
  /** What makes the device the same device next time: the same value identification reads. */
5936
7151
  externalId: identityPathSchema.optional(),
5937
7152
  name: identityPathSchema.optional(),
5938
- swVersion: identityPathSchema.optional()
7153
+ swVersion: identityPathSchema.optional(),
7154
+ /** Its MAC address, written any way the device writes it: what tells it from its twin. */
7155
+ mac: identityPathSchema.optional(),
7156
+ serialNumber: identityPathSchema.optional(),
7157
+ /**
7158
+ * Where the device says it is behind a password - `auth_en` on a Shelly - so its row says so
7159
+ * before anyone tries to add it. True there means a password is needed.
7160
+ */
7161
+ auth: identityPathSchema.optional()
5939
7162
  });
5940
7163
  /**
5941
7164
  * What to ask an announced address.
@@ -5955,29 +7178,78 @@ const discoveryProbeSchema = z.strictObject({
5955
7178
  timeoutMs: z.int().min(500).max(3e4).optional()
5956
7179
  });
5957
7180
  /**
5958
- * Which of the house's Matter devices are the vendor's: rules on who each says it is - its
5959
- * `vendorId`, `productName`, `macAddresses`, `deviceTypes`, every field of the platform's
5960
- * `MatterIdentity` - and where it says its model, looked up in the `modelCodes` of the vendor's
5961
- * drivers that say `"kind": "matter"`.
7181
+ * Which of the devices one of the platform's brokers holds are the vendor's: rules on who each
7182
+ * says it is, and where it says its model, looked up in the `modelCodes` of the vendor's drivers
7183
+ * of that broker's kind.
7184
+ *
7185
+ * A device is in the house through the broker already - commissioned by the owner, or announced
7186
+ * on the house's network - so it is added at once to the one vendor whose rules all hold, or to
7187
+ * the platform's own vendor of the broker when none - or more than one - do.
7188
+ *
7189
+ * @param model - Where a device says its model when the vendor does not say.
7190
+ * @returns The schema of one broker's block.
7191
+ */
7192
+ function brokerDiscoverySchema(model) {
7193
+ return z.strictObject({
7194
+ /** Every condition must hold. All-of, and at least one: a vendor does not take every device. */
7195
+ match: z.array(claimConditionSchema).min(1).max(MAXIMUM_MATCH),
7196
+ /** Where the device says its model. */
7197
+ model: identityPathSchema.default(model)
7198
+ });
7199
+ }
7200
+ /**
7201
+ * Which of the house's Matter devices are the vendor's: rules on its `vendorId`, `productName`,
7202
+ * `macAddresses`, `deviceTypes`, every field of the platform's `MatterIdentity`; the model is its
7203
+ * product id unless said, in the drivers that say `"kind": "matter"`.
7204
+ */
7205
+ const matterDiscoverySchema = brokerDiscoverySchema("productId");
7206
+ /**
7207
+ * Which of the devices the house's MQTT broker hears are the vendor's: rules on its
7208
+ * `manufacturer`, `model`, `originName`, `identifiers`, every field of the platform's
7209
+ * `MqttIdentity`; the model is its `model` unless said, in the drivers that say `"kind": "mqtt"`.
7210
+ */
7211
+ const mqttDiscoverySchema = brokerDiscoverySchema("model");
7212
+ /** What a Modbus rule may call a value it reads: `serial`, `model`. */
7213
+ const MODBUS_VALUE_NAME = /^[a-z][a-zA-Z0-9_]{0,31}$/u;
7214
+ /** How many values a Modbus rule may read: every one is a request to a server that is not yet known. */
7215
+ const MAXIMUM_MODBUS_READS = 8;
7216
+ /**
7217
+ * Which of the Modbus servers found on the network are the vendor's: the values to read from
7218
+ * them - registers, as a template reads them - and rules on `values.<name>`, `host`, `port` and
7219
+ * `unitId`; the model is `values.model` unless said, in the drivers that say `"kind": "modbus"`.
5962
7220
  *
5963
- * A device is commissioned into the house by the owner, so it is added at once to the one vendor
5964
- * whose rules all hold, or to the platform's own `matter` vendor when none - or more than one - do.
7221
+ * The platform recognises no server on its own: a server is named only by an integration whose
7222
+ * rules hold.
5965
7223
  */
5966
- const matterDiscoverySchema = z.strictObject({
5967
- /** Every condition must hold. All-of, and at least one: a vendor does not take every device. */
5968
- match: z.array(claimConditionSchema).min(1).max(MAXIMUM_MATCH),
5969
- /** Where the device says its model; its product id when not said. */
5970
- model: identityPathSchema.default("productId")
7224
+ const modbusDiscoverySchema = brokerDiscoverySchema("values.model").extend({
7225
+ /** The unit asked; the one a server answers for on its own unless said. */
7226
+ unitId: z.int().min(1).max(247).default(1),
7227
+ /** What to read, by the name the rules use. */
7228
+ read: z.record(z.string().regex(MODBUS_VALUE_NAME, "A name of letters and digits"), modbusReadSchema).refine((read) => Object.keys(read).length <= MAXIMUM_MODBUS_READS, { message: `At most ${String(MAXIMUM_MODBUS_READS)} values` }).default({})
5971
7229
  });
7230
+ /** The platform's brokers a vendor may take devices of, and the transport each reaches them on. */
7231
+ const BROKER_TRANSPORTS = {
7232
+ matter: MATTER_TRANSPORT,
7233
+ mqtt: MQTT_HOUSE_TRANSPORT,
7234
+ modbus: MODBUS_TRANSPORT
7235
+ };
7236
+ /** Where each broker's device says its model, when the vendor's block does not say. */
7237
+ const BROKER_MODELS = {
7238
+ matter: "productId",
7239
+ mqtt: "model",
7240
+ modbus: "values.model"
7241
+ };
5972
7242
  /** Validates a whole `discovery.json`. */
5973
7243
  const vendorDiscoverySchema = z.strictObject({
5974
- /** Where the vendor's devices announce themselves; none for one found only through Matter. */
7244
+ /** Where the vendor's devices announce themselves; none for one found only through a broker. */
5975
7245
  listen: z.array(listenSourceSchema).max(MAXIMUM_SOURCES).default([]),
5976
7246
  /** Every condition must hold of an announcement for it to be the vendor's. All-of. */
5977
7247
  match: z.array(claimConditionSchema).max(MAXIMUM_MATCH).default([]),
5978
7248
  probe: discoveryProbeSchema.optional(),
5979
7249
  identity: discoveryIdentitySchema.default({}),
5980
7250
  matter: matterDiscoverySchema.optional(),
7251
+ mqtt: mqttDiscoverySchema.optional(),
7252
+ modbus: modbusDiscoverySchema.optional(),
5981
7253
  /**
5982
7254
  * Who adds a device found. `owner` - the default - proposes it on the vendor's
5983
7255
  * page; `automatic` adds it as soon as it is heard, for devices the owner already chose
@@ -5998,10 +7270,10 @@ const vendorDiscoverySchema = z.strictObject({
5998
7270
  state: z.string().min(1).max(64)
5999
7271
  }).optional()
6000
7272
  }).superRefine((discovery, ctx) => {
6001
- if (discovery.listen.length === 0 && discovery.matter === void 0) ctx.addIssue({
7273
+ if (discovery.listen.length === 0 && discovery.matter === void 0 && discovery.mqtt === void 0 && discovery.modbus === void 0) ctx.addIssue({
6002
7274
  code: "custom",
6003
7275
  path: ["listen"],
6004
- message: "A vendor listens somewhere, or says which Matter devices are its own, or both"
7276
+ message: "A vendor listens somewhere, or says which Matter, MQTT or Modbus devices are its own, or both"
6005
7277
  });
6006
7278
  if (discovery.listen.length > 0 && discovery.probe === void 0 && discovery.identity.model === void 0) ctx.addIssue({
6007
7279
  code: "custom",
@@ -6080,11 +7352,15 @@ function textAt(payload, path) {
6080
7352
  */
6081
7353
  function identifySighting(plan, payload) {
6082
7354
  const { identity } = plan.discovery;
7355
+ const auth = identity.auth === void 0 ? [] : [identity.auth].flat();
6083
7356
  return {
6084
7357
  externalId: textAt(payload, identity.externalId),
6085
7358
  name: textAt(payload, identity.name),
6086
7359
  modelCode: textAt(payload, identity.model),
6087
- swVersion: textAt(payload, identity.swVersion)
7360
+ swVersion: textAt(payload, identity.swVersion),
7361
+ mac: normalizeMac(textAt(payload, identity.mac)),
7362
+ serialNumber: textAt(payload, identity.serialNumber),
7363
+ needsPassword: auth.some((path) => resolvePath(payload, path) === true)
6088
7364
  };
6089
7365
  }
6090
7366
  /**
@@ -6112,7 +7388,8 @@ function choicesOf(driver) {
6112
7388
  * @returns The association, or null when no driver of the vendor takes the device.
6113
7389
  */
6114
7390
  function associateModel(plan, modelCode, claimedBy) {
6115
- const reached = new Set(plan.drivers.filter((driver) => driver.transport !== MATTER_TRANSPORT).map(({ id }) => id));
7391
+ const brokers = Object.values(BROKER_TRANSPORTS);
7392
+ const reached = new Set(plan.drivers.filter((driver) => !brokers.includes(driver.transport)).map(({ id }) => id));
6116
7393
  const coded = modelCode === null ? [] : (plan.codes.get(modelCode) ?? []).filter((entry) => reached.has(entry.driverId));
6117
7394
  if (coded.length > 0) {
6118
7395
  const found = claimedBy === void 0 ? coded.length === 1 ? coded[0] : void 0 : coded.find((entry) => claimedBy(entry.driverId));
@@ -6134,28 +7411,31 @@ function associateModel(plan, modelCode, claimedBy) {
6134
7411
  };
6135
7412
  }
6136
7413
  /**
6137
- * Whether a Matter device is the vendor's, by the rules of its `matter` block.
7414
+ * Whether a device of one of the platform's brokers is the vendor's, by the rules of its block.
6138
7415
  *
6139
7416
  * @param plan - The vendor's discovery.
7417
+ * @param broker - Which broker holds the device: `matter`, `mqtt`.
6140
7418
  * @param identity - Who the device says it is.
6141
- * @returns True when the vendor has a `matter` block and every one of its conditions holds.
7419
+ * @returns True when the vendor has the broker's block and every one of its conditions holds.
6142
7420
  */
6143
- function matchesMatter(plan, identity) {
6144
- return plan.discovery.matter?.match.every((condition) => conditionHolds(condition, identity)) ?? false;
7421
+ function matchesBroker(plan, broker, identity) {
7422
+ return plan.discovery[broker]?.match.every((condition) => conditionHolds(condition, identity)) ?? false;
6145
7423
  }
6146
7424
  /**
6147
- * Finds the driver of the vendor's that runs a Matter device of its, and its model.
7425
+ * Finds the driver of the vendor's that runs a device of one of the platform's brokers, and its
7426
+ * model.
6148
7427
  *
6149
- * The model the device says is looked up in the `modelCodes` of the vendor's Matter drivers; one
6150
- * it does not map goes to the vendor's Matter driver when it has only one.
7428
+ * The model the device says is looked up in the `modelCodes` of the vendor's drivers on that
7429
+ * broker's transport; one it does not map goes to the vendor's driver there when it has only one.
6151
7430
  *
6152
7431
  * @param plan - The vendor's discovery.
7432
+ * @param broker - Which broker holds the device: `matter`, `mqtt`.
6153
7433
  * @param identity - Who the device says it is.
6154
- * @returns The association, or null when no Matter driver of the vendor takes it.
7434
+ * @returns The association, or null when no driver of the vendor on the broker takes it.
6155
7435
  */
6156
- function associateMatter(plan, identity) {
6157
- const drivers = plan.drivers.filter((driver) => driver.transport === MATTER_TRANSPORT);
6158
- const modelCode = textAt(identity, plan.discovery.matter?.model ?? "productId");
7436
+ function associateBroker(plan, broker, identity) {
7437
+ const drivers = plan.drivers.filter((driver) => driver.transport === BROKER_TRANSPORTS[broker]);
7438
+ const modelCode = textAt(identity, plan.discovery[broker]?.model ?? BROKER_MODELS[broker]);
6159
7439
  const [first] = modelCode === null ? [] : (plan.codes.get(modelCode) ?? []).filter((entry) => drivers.some((driver) => driver.id === entry.driverId));
6160
7440
  if (first !== void 0) return {
6161
7441
  driverId: first.driverId,
@@ -7756,7 +9036,7 @@ CLUSTER.onOff, CLUSTER.levelControl, CLUSTER.colorControl, CLUSTER.windowCoverin
7756
9036
  * @param value - The attribute.
7757
9037
  * @returns It, or undefined when it is not a finite number - null included.
7758
9038
  */
7759
- function numberOf(value) {
9039
+ function numberOf$1(value) {
7760
9040
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
7761
9041
  }
7762
9042
  /**
@@ -7824,11 +9104,11 @@ function onOffEntity(attributes, endpoint) {
7824
9104
  DEVICE_TYPE.mountedDimmableLoadControl
7825
9105
  ].some((type) => types.includes(type));
7826
9106
  const hasLevel = isLight && serves(attributes, endpoint, CLUSTER.levelControl);
7827
- const colorFeatures = serves(attributes, endpoint, CLUSTER.colorControl) ? numberOf(attributeOf(attributes, endpoint, CLUSTER.colorControl, FEATURE_MAP)) ?? 0 : 0;
9107
+ const colorFeatures = serves(attributes, endpoint, CLUSTER.colorControl) ? numberOf$1(attributeOf(attributes, endpoint, CLUSTER.colorControl, FEATURE_MAP)) ?? 0 : 0;
7828
9108
  const hasHs = isLight && (colorFeatures & 1) !== 0;
7829
9109
  const hasTemperature = isLight && (colorFeatures & 16) !== 0;
7830
- const minMireds = clamp(numberOf(attributeOf(attributes, endpoint, CLUSTER.colorControl, 16395)) ?? 153, 1, 1e3);
7831
- const maxMireds = clamp(numberOf(attributeOf(attributes, endpoint, CLUSTER.colorControl, 16396)) ?? 500, minMireds, 1e3);
9110
+ const minMireds = clamp(numberOf$1(attributeOf(attributes, endpoint, CLUSTER.colorControl, 16395)) ?? 153, 1, 1e3);
9111
+ const maxMireds = clamp(numberOf$1(attributeOf(attributes, endpoint, CLUSTER.colorControl, 16396)) ?? 500, minMireds, 1e3);
7832
9112
  const capabilities = {
7833
9113
  on_off: { hasTransition: false },
7834
9114
  ...hasLevel ? { level: { hasTransition: true } } : {},
@@ -7861,10 +9141,10 @@ function onOffEntity(attributes, endpoint) {
7861
9141
  stateOf: (read) => {
7862
9142
  const isOn = attributeOf(read, endpoint, CLUSTER.onOff, 0);
7863
9143
  if (typeof isOn !== "boolean") return;
7864
- const level = numberOf(attributeOf(read, endpoint, CLUSTER.levelControl, 0));
7865
- const hue = numberOf(attributeOf(read, endpoint, CLUSTER.colorControl, 0));
7866
- const saturation = numberOf(attributeOf(read, endpoint, CLUSTER.colorControl, 1));
7867
- const mireds = numberOf(attributeOf(read, endpoint, CLUSTER.colorControl, 7));
9144
+ const level = numberOf$1(attributeOf(read, endpoint, CLUSTER.levelControl, 0));
9145
+ const hue = numberOf$1(attributeOf(read, endpoint, CLUSTER.colorControl, 0));
9146
+ const saturation = numberOf$1(attributeOf(read, endpoint, CLUSTER.colorControl, 1));
9147
+ const mireds = numberOf$1(attributeOf(read, endpoint, CLUSTER.colorControl, 7));
7868
9148
  return {
7869
9149
  on_off: { isOn },
7870
9150
  ...hasLevel && level !== void 0 ? { level: { level: clamp(Math.round(level / 254 * 100), 0, 100) } } : {},
@@ -7888,7 +9168,7 @@ function onOffEntity(attributes, endpoint) {
7888
9168
  case "turn_off": return invoke(endpoint, CLUSTER.onOff, "off");
7889
9169
  case "toggle": return invoke(endpoint, CLUSTER.onOff, "toggle");
7890
9170
  case "set_level": {
7891
- const level = numberOf(command["level"]) ?? 0;
9171
+ const level = numberOf$1(command["level"]) ?? 0;
7892
9172
  return level <= 0 ? invoke(endpoint, CLUSTER.onOff, "off") : invoke(endpoint, CLUSTER.levelControl, "moveToLevelWithOnOff", {
7893
9173
  level: clamp(Math.round(level / 100 * 254), 1, 254),
7894
9174
  transitionTime: tenthsOf(command["transitionMs"]),
@@ -7896,13 +9176,13 @@ function onOffEntity(attributes, endpoint) {
7896
9176
  });
7897
9177
  }
7898
9178
  case "set_color": return invoke(endpoint, CLUSTER.colorControl, "moveToHueAndSaturation", {
7899
- hue: clamp(Math.round((numberOf(command["hue"]) ?? 0) / 360 * 254), 0, 254),
7900
- saturation: clamp(Math.round((numberOf(command["saturation"]) ?? 0) / 100 * 254), 0, 254),
9179
+ hue: clamp(Math.round((numberOf$1(command["hue"]) ?? 0) / 360 * 254), 0, 254),
9180
+ saturation: clamp(Math.round((numberOf$1(command["saturation"]) ?? 0) / 100 * 254), 0, 254),
7901
9181
  transitionTime: tenthsOf(command["transitionMs"]),
7902
9182
  ...NO_OPTIONS
7903
9183
  });
7904
9184
  case "set_color_temp": return invoke(endpoint, CLUSTER.colorControl, "moveToColorTemperature", {
7905
- colorTemperatureMireds: clamp(Math.round(numberOf(command["mireds"]) ?? minMireds), minMireds, maxMireds),
9185
+ colorTemperatureMireds: clamp(Math.round(numberOf$1(command["mireds"]) ?? minMireds), minMireds, maxMireds),
7906
9186
  transitionTime: tenthsOf(command["transitionMs"]),
7907
9187
  ...NO_OPTIONS
7908
9188
  });
@@ -7920,7 +9200,7 @@ function onOffEntity(attributes, endpoint) {
7920
9200
  * @returns The entity.
7921
9201
  */
7922
9202
  function coverEntity(attributes, endpoint) {
7923
- const features = numberOf(attributeOf(attributes, endpoint, CLUSTER.windowCovering, FEATURE_MAP)) ?? 0;
9203
+ const features = numberOf$1(attributeOf(attributes, endpoint, CLUSTER.windowCovering, FEATURE_MAP)) ?? 0;
7924
9204
  const hasPosition = (features & 4) !== 0;
7925
9205
  const hasTilt = (features & 2) !== 0 && (features & 16) !== 0;
7926
9206
  /**
@@ -7949,9 +9229,9 @@ function coverEntity(attributes, endpoint) {
7949
9229
  * @returns The state, or undefined while the device has not said enough.
7950
9230
  */
7951
9231
  stateOf: (read) => {
7952
- const closed = numberOf(attributeOf(read, endpoint, CLUSTER.windowCovering, 14));
7953
- const tilt = numberOf(attributeOf(read, endpoint, CLUSTER.windowCovering, 15));
7954
- const status = (numberOf(attributeOf(read, endpoint, CLUSTER.windowCovering, 10)) ?? 0) & 3;
9232
+ const closed = numberOf$1(attributeOf(read, endpoint, CLUSTER.windowCovering, 14));
9233
+ const tilt = numberOf$1(attributeOf(read, endpoint, CLUSTER.windowCovering, 15));
9234
+ const status = (numberOf$1(attributeOf(read, endpoint, CLUSTER.windowCovering, 10)) ?? 0) & 3;
7955
9235
  if (closed === void 0) return;
7956
9236
  return { cover: {
7957
9237
  position: openOf(closed),
@@ -7971,8 +9251,8 @@ function coverEntity(attributes, endpoint) {
7971
9251
  case "open": return invoke(endpoint, CLUSTER.windowCovering, "upOrOpen");
7972
9252
  case "close": return invoke(endpoint, CLUSTER.windowCovering, "downOrClose");
7973
9253
  case "stop": return invoke(endpoint, CLUSTER.windowCovering, "stopMotion");
7974
- case "set_position": return invoke(endpoint, CLUSTER.windowCovering, "goToLiftPercentage", { liftPercent100thsValue: Math.round((100 - (numberOf(command["position"]) ?? 0)) * 100) });
7975
- case "set_tilt": return invoke(endpoint, CLUSTER.windowCovering, "goToTiltPercentage", { tiltPercent100thsValue: Math.round((100 - (numberOf(command["tilt"]) ?? 0)) * 100) });
9254
+ case "set_position": return invoke(endpoint, CLUSTER.windowCovering, "goToLiftPercentage", { liftPercent100thsValue: Math.round((100 - (numberOf$1(command["position"]) ?? 0)) * 100) });
9255
+ case "set_tilt": return invoke(endpoint, CLUSTER.windowCovering, "goToTiltPercentage", { tiltPercent100thsValue: Math.round((100 - (numberOf$1(command["tilt"]) ?? 0)) * 100) });
7976
9256
  default: return;
7977
9257
  }
7978
9258
  }
@@ -8001,7 +9281,7 @@ function lockEntity(endpoint) {
8001
9281
  * @returns The state, or undefined while the device has not said enough.
8002
9282
  */
8003
9283
  stateOf: (read) => {
8004
- switch (numberOf(attributeOf(read, endpoint, CLUSTER.doorLock, 0))) {
9284
+ switch (numberOf$1(attributeOf(read, endpoint, CLUSTER.doorLock, 0))) {
8005
9285
  case 0: return { lock: { lockState: "jammed" } };
8006
9286
  case 1: return { lock: { lockState: "locked" } };
8007
9287
  case 2:
@@ -8054,7 +9334,7 @@ const MODE_VALUES = {
8054
9334
  * @returns The entity.
8055
9335
  */
8056
9336
  function thermostatEntity(attributes, endpoint) {
8057
- const features = numberOf(attributeOf(attributes, endpoint, CLUSTER.thermostat, FEATURE_MAP)) ?? 1;
9337
+ const features = numberOf$1(attributeOf(attributes, endpoint, CLUSTER.thermostat, FEATURE_MAP)) ?? 1;
8058
9338
  const canHeat = (features & 1) !== 0;
8059
9339
  const canCool = (features & 2) !== 0;
8060
9340
  const hasAuto = (features & 32) !== 0;
@@ -8066,7 +9346,7 @@ function thermostatEntity(attributes, endpoint) {
8066
9346
  * @returns The degrees, or undefined.
8067
9347
  */
8068
9348
  const degreesOf = (read, attribute) => {
8069
- const value = numberOf(attributeOf(read, endpoint, CLUSTER.thermostat, attribute));
9349
+ const value = numberOf$1(attributeOf(read, endpoint, CLUSTER.thermostat, attribute));
8070
9350
  return value === void 0 ? void 0 : value / 100;
8071
9351
  };
8072
9352
  const min = degreesOf(attributes, canHeat ? 21 : 23) ?? 7;
@@ -8098,10 +9378,10 @@ function thermostatEntity(attributes, endpoint) {
8098
9378
  */
8099
9379
  stateOf: (read) => {
8100
9380
  const current = degreesOf(read, 0);
8101
- const mode = SYSTEM_MODES[numberOf(attributeOf(read, endpoint, CLUSTER.thermostat, 28)) ?? 0];
9381
+ const mode = SYSTEM_MODES[numberOf$1(attributeOf(read, endpoint, CLUSTER.thermostat, 28)) ?? 0];
8102
9382
  const target = degreesOf(read, mode === "cool" ? 17 : 18) ?? degreesOf(read, 17);
8103
- const running = numberOf(attributeOf(read, endpoint, CLUSTER.thermostat, 41)) ?? 0;
8104
- const humidity = numberOf(attributeOf(read, endpoint, CLUSTER.relativeHumidityMeasurement, 0));
9383
+ const running = numberOf$1(attributeOf(read, endpoint, CLUSTER.thermostat, 41)) ?? 0;
9384
+ const humidity = numberOf$1(attributeOf(read, endpoint, CLUSTER.relativeHumidityMeasurement, 0));
8105
9385
  if (current === void 0 || target === void 0 || mode === void 0) return;
8106
9386
  return { thermostat: {
8107
9387
  currentTemperature: current,
@@ -8128,7 +9408,7 @@ function thermostatEntity(attributes, endpoint) {
8128
9408
  endpoint,
8129
9409
  cluster: CLUSTER.thermostat,
8130
9410
  attribute: isCooling ? 17 : 18,
8131
- value: Math.round((numberOf(command["temperature"]) ?? 0) * 100)
9411
+ value: Math.round((numberOf$1(command["temperature"]) ?? 0) * 100)
8132
9412
  }
8133
9413
  };
8134
9414
  }
@@ -8153,7 +9433,7 @@ function thermostatEntity(attributes, endpoint) {
8153
9433
  * @returns It divided by 100.
8154
9434
  */
8155
9435
  function hundredths(value) {
8156
- const number = numberOf(value);
9436
+ const number = numberOf$1(value);
8157
9437
  return number === void 0 ? void 0 : number / 100;
8158
9438
  }
8159
9439
  /** The sensors read as one value of one attribute. */
@@ -8193,7 +9473,7 @@ const NUMERIC_SENSORS = [
8193
9473
  * @returns The number, or undefined.
8194
9474
  */
8195
9475
  scale: (value) => {
8196
- const measured = numberOf(value);
9476
+ const measured = numberOf$1(value);
8197
9477
  return measured === void 0 ? void 0 : measured === 0 ? 0 : 10 ** ((measured - 1) / 1e4);
8198
9478
  }
8199
9479
  },
@@ -8205,7 +9485,7 @@ const NUMERIC_SENSORS = [
8205
9485
  deviceClass: "atmospheric_pressure",
8206
9486
  unit: "hPa",
8207
9487
  displayPrecision: 0,
8208
- scale: numberOf
9488
+ scale: numberOf$1
8209
9489
  },
8210
9490
  {
8211
9491
  key: "carbon_dioxide",
@@ -8215,7 +9495,7 @@ const NUMERIC_SENSORS = [
8215
9495
  deviceClass: "carbon_dioxide",
8216
9496
  unit: "ppm",
8217
9497
  displayPrecision: 0,
8218
- scale: numberOf
9498
+ scale: numberOf$1
8219
9499
  },
8220
9500
  {
8221
9501
  key: "battery",
@@ -8232,7 +9512,7 @@ const NUMERIC_SENSORS = [
8232
9512
  * @returns The number, or undefined.
8233
9513
  */
8234
9514
  scale: (value) => {
8235
- const halves = numberOf(value);
9515
+ const halves = numberOf$1(value);
8236
9516
  return halves === void 0 ? void 0 : clamp(halves / 2, 0, 100);
8237
9517
  }
8238
9518
  },
@@ -8244,7 +9524,7 @@ const NUMERIC_SENSORS = [
8244
9524
  deviceClass: "power",
8245
9525
  unit: "mW",
8246
9526
  displayPrecision: 1,
8247
- scale: numberOf
9527
+ scale: numberOf$1
8248
9528
  },
8249
9529
  {
8250
9530
  key: "voltage",
@@ -8254,7 +9534,7 @@ const NUMERIC_SENSORS = [
8254
9534
  deviceClass: "voltage",
8255
9535
  unit: "mV",
8256
9536
  displayPrecision: 1,
8257
- scale: numberOf
9537
+ scale: numberOf$1
8258
9538
  },
8259
9539
  {
8260
9540
  key: "current",
@@ -8264,7 +9544,7 @@ const NUMERIC_SENSORS = [
8264
9544
  deviceClass: "current",
8265
9545
  unit: "mA",
8266
9546
  displayPrecision: 2,
8267
- scale: numberOf
9547
+ scale: numberOf$1
8268
9548
  },
8269
9549
  {
8270
9550
  key: "energy",
@@ -8281,7 +9561,7 @@ const NUMERIC_SENSORS = [
8281
9561
  * @param value - The attribute.
8282
9562
  * @returns The number, or undefined.
8283
9563
  */
8284
- scale: (value) => numberOf(value?.["0"])
9564
+ scale: (value) => numberOf$1(value?.["0"])
8285
9565
  }
8286
9566
  ];
8287
9567
  /**
@@ -8392,10 +9672,10 @@ function firmwareEntity() {
8392
9672
  */
8393
9673
  stateOf: (read, update) => {
8394
9674
  const text = attributeOf(read, 0, CLUSTER.basicInformation, 10);
8395
- const number = numberOf(attributeOf(read, 0, CLUSTER.basicInformation, 9));
9675
+ const number = numberOf$1(attributeOf(read, 0, CLUSTER.basicInformation, 9));
8396
9676
  const installed = typeof text === "string" && text !== "" ? text : number === void 0 ? null : String(number);
8397
- const updating = numberOf(attributeOf(read, 0, CLUSTER.otaRequestor, 2));
8398
- const progress = numberOf(attributeOf(read, 0, CLUSTER.otaRequestor, 3));
9677
+ const updating = numberOf$1(attributeOf(read, 0, CLUSTER.otaRequestor, 2));
9678
+ const progress = numberOf$1(attributeOf(read, 0, CLUSTER.otaRequestor, 3));
8399
9679
  const isInstalling = updating === 4 || updating === 5;
8400
9680
  return { update: {
8401
9681
  installedVersion: installed?.slice(0, 64) ?? null,
@@ -8454,7 +9734,7 @@ function draftsOf(attributes, endpoint) {
8454
9734
  * @returns Whether it is on, or undefined.
8455
9735
  */
8456
9736
  isOn: (value) => {
8457
- const bits = numberOf(value);
9737
+ const bits = numberOf$1(value);
8458
9738
  return bits === void 0 ? void 0 : (bits & 1) !== 0;
8459
9739
  }
8460
9740
  }));
@@ -8504,7 +9784,12 @@ function matterEntitiesOf(device) {
8504
9784
  descriptor: {
8505
9785
  ...descriptor,
8506
9786
  objectId,
8507
- name: isShared ? `${descriptor.name} ${String(rest.endpoint)}` : descriptor.name
9787
+ name: isShared ? `${descriptor.name} ${String(rest.endpoint)}` : descriptor.name,
9788
+ link: { matter: {
9789
+ endpoint: rest.endpoint,
9790
+ cluster: rest.clusters[0] ?? 0,
9791
+ attribute: rest.attribute ?? 0
9792
+ } }
8508
9793
  }
8509
9794
  };
8510
9795
  });
@@ -8519,7 +9804,7 @@ const deviceSnapshotSchema = z.object({
8519
9804
  attributes: z.record(z.string(), z.unknown())
8520
9805
  });
8521
9806
  /** Reads what the transport delivers. */
8522
- const inboundSchema = z.object({
9807
+ const inboundSchema$2 = z.object({
8523
9808
  device: deviceSnapshotSchema,
8524
9809
  changed: z.array(z.string()).nullable(),
8525
9810
  update: z.object({
@@ -8533,7 +9818,7 @@ const inboundSchema = z.object({
8533
9818
  * @param value - What it holds.
8534
9819
  * @returns The device, or undefined when it is not one.
8535
9820
  */
8536
- function deviceOf(value) {
9821
+ function deviceOf$1(value) {
8537
9822
  const parsed = deviceSnapshotSchema.safeParse(value);
8538
9823
  return parsed.success ? parsed.data : void 0;
8539
9824
  }
@@ -8567,7 +9852,7 @@ function createMatterIntegration(manifest) {
8567
9852
  * @throws {ValidationError} When the claim holds no device - which identification never makes.
8568
9853
  */
8569
9854
  const claimed = (context) => {
8570
- const device = deviceOf(context.claim.descriptor);
9855
+ const device = deviceOf$1(context.claim.descriptor);
8571
9856
  if (device === void 0) throw new ValidationError(`${manifest.id} holds a claim that is not a Matter device`, { details: { integration: manifest.id } });
8572
9857
  return device;
8573
9858
  };
@@ -8583,7 +9868,7 @@ function createMatterIntegration(manifest) {
8583
9868
  * @returns The claim, or null for anything that is not a Matter device.
8584
9869
  */
8585
9870
  claim: (discovered) => {
8586
- const device = deviceOf(discovered.payload);
9871
+ const device = deviceOf$1(discovered.payload);
8587
9872
  return device === void 0 ? null : {
8588
9873
  deviceKey: discovered.deviceKey,
8589
9874
  externalId: matterDeviceKey(device.nodeId, device.endpoint),
@@ -8604,12 +9889,15 @@ function createMatterIntegration(manifest) {
8604
9889
  * @throws {ValidationError} When the claim holds no Matter device.
8605
9890
  */
8606
9891
  describe: (claim) => {
8607
- const device = deviceOf(claim.descriptor);
9892
+ const device = deviceOf$1(claim.descriptor);
8608
9893
  if (device === void 0) throw new ValidationError(`${manifest.id} cannot describe a claim with no Matter device`, { details: { integration: manifest.id } });
8609
9894
  const { identity } = device;
9895
+ const mac = identity.macAddresses.map(normalizeMac).find((each) => each !== null);
8610
9896
  return {
8611
9897
  externalId: claim.externalId,
8612
9898
  name: nameOf$1(identity).slice(0, 128),
9899
+ ...mac === void 0 ? {} : { mac },
9900
+ ...identity.serialNumber === null ? {} : { serialNumber: identity.serialNumber },
8613
9901
  ...identity.vendorName === null ? {} : { manufacturer: identity.vendorName },
8614
9902
  ...identity.productName === null ? {} : { model: identity.productName },
8615
9903
  ...identity.softwareVersionString === null ? {} : { swVersion: identity.softwareVersionString.slice(0, 64) },
@@ -8626,7 +9914,7 @@ function createMatterIntegration(manifest) {
8626
9914
  * @returns The reports.
8627
9915
  */
8628
9916
  toState: (message, context) => {
8629
- const parsed = inboundSchema.safeParse(message.payload);
9917
+ const parsed = inboundSchema$2.safeParse(message.payload);
8630
9918
  if (!parsed.success) return [];
8631
9919
  const { device, changed, update } = parsed.data;
8632
9920
  return matterEntitiesOf(device).flatMap((entity) => {
@@ -8668,35 +9956,1576 @@ function createMatterIntegration(manifest) {
8668
9956
  * @returns The version, when the device says it.
8669
9957
  */
8670
9958
  deviceInfo: (message) => {
8671
- const parsed = inboundSchema.safeParse(message.payload);
9959
+ const parsed = inboundSchema$2.safeParse(message.payload);
8672
9960
  const version = parsed.success ? parsed.data.device.identity.softwareVersionString : null;
8673
9961
  return version === null ? void 0 : { swVersion: version.slice(0, 64) };
8674
9962
  }
8675
9963
  };
8676
9964
  }
8677
9965
  //#endregion
8678
- //#region ../package-runtime/dist/loader.js
9966
+ //#region ../package-runtime/dist/modbus-mapping.js
9967
+ /**
9968
+ * How a Modbus device is read and commanded through its template: pure.
9969
+ *
9970
+ * A template says, for each capability of each entity, the register its value is read from and
9971
+ * the command its changes are written with. This module plans the reads into blocks, turns what
9972
+ * the registers hold into canonical state, and turns a canonical command into the words to
9973
+ * write. It is the one interpreter of templates: the platform's own `modbus/generic` driver and
9974
+ * every integration driver of kind `modbus` are this, so an integration's template and the owner's
9975
+ * mean the same thing.
9976
+ *
9977
+ * The template travels in the claim: the broker hands each device over with its template
9978
+ * resolved, so the blocks a device is polled for and the way they are read are always the same
9979
+ * template's.
9980
+ */
9981
+ /** How many registers or bits one read may ask for. */
9982
+ const MAXIMUM_BLOCK = 100;
9983
+ /** How many unread addresses between two reads still go in one block. */
9984
+ const MAXIMUM_GAP = 16;
9985
+ /** A Modbus device as the broker hands it over: where it is, how often, and its template. */
9986
+ const modbusDeviceSnapshotSchema = z.object({
9987
+ /** The device's external id: `modbus-<row id>`. */
9988
+ deviceKey: z.string().min(1).max(160),
9989
+ /** The driver it is read as: `modbus/generic`, or an integration's. */
9990
+ kind: z.string().min(1).max(160),
9991
+ name: z.string().min(1).max(128),
9992
+ host: z.string().min(1).max(253),
9993
+ port: z.int().min(1).max(65535),
9994
+ unitId: z.int().min(1).max(247),
9995
+ framing: z.enum(MODBUS_FRAMINGS),
9996
+ pollSeconds: z.int().min(1).max(3600),
9997
+ template: modbusTemplateSchema
9998
+ });
8679
9999
  /**
8680
- * Reading integrations off disk: the loader `hub` runs and the integration SDK checks a bundle
8681
- * with, so that what passes `nebulahome-integration validate` is what `hub` loads.
10000
+ * How many registers or bits a read takes.
8682
10001
  *
8683
- * A bundle is a vendor directory - `manifest.json`, a logo, optionally a `setup.json` of what
8684
- * every device of the vendor shares - holding one driver directory per profile or entry point,
8685
- * each with `driver.json`, its own `setup.json` and the profile or code. It is read in two steps:
10002
+ * @param read - The read.
10003
+ * @returns One bit for a coil or an input; the type's registers otherwise.
10004
+ */
10005
+ function modbusSizeOf(read) {
10006
+ return read.function === 1 || read.function === 2 ? 1 : modbusRegistersOf(read.type ?? "u16", read.count);
10007
+ }
10008
+ /**
10009
+ * Every read of a template, each once.
8686
10010
  *
8687
- * 1. {@link readVendorDirectory} reads and checks every file - the schemas, the ids against the
8688
- * folders, the runtime range, the logo, the containers, that every module named is there -
8689
- * and imports nothing. It is all a source tree needs to be checked.
8690
- * 2. {@link instantiateVendor} imports the code and hands it the {@link BundleSdk}: the vendor's
8691
- * own transports, stream sources and account, each driver, and the discovery modules. Who
8692
- * builds the SDK is the caller's - `hub` hands the real one, the SDK's tests a fake.
10011
+ * @param template - The template.
10012
+ * @returns The reads, in the template's order.
10013
+ */
10014
+ function readsOf(template) {
10015
+ return template.entities.flatMap((entity) => Object.values(entity.capabilities).flatMap((map) => map.read === void 0 ? [] : [map.read]));
10016
+ }
10017
+ /**
10018
+ * Plans the reads of a template into as few requests as the device takes.
8693
10019
  *
8694
- * **It is also the seam the catalogue arrives through.** `verify` and `verifyVendor` are called
8695
- * before code is imported, and nothing passes them today. When the catalogue stamps a signature on
8696
- * an approved code bundle, the verifier that checks it is injected there and nothing else changes.
10020
+ * Reads of one table go together while what lies between them is a short run of unread addresses,
10021
+ * and no request asks for more than a hundred units: a gateway that answers 125 registers on paper
10022
+ * often answers fewer.
8697
10023
  *
8698
- * One broken driver never stops its siblings, and one broken vendor never stops the others. A
8699
- * failure is collected and reported so the interface can say which directory and why, because
10024
+ * @param template - The template.
10025
+ * @returns The blocks, each table in address order.
10026
+ */
10027
+ function planModbusBlocks(template) {
10028
+ const spans = readsOf(template).map((read) => ({
10029
+ function: read.function,
10030
+ start: modbusWordOf(read.address),
10031
+ size: modbusSizeOf(read)
10032
+ }));
10033
+ const blocks = [];
10034
+ for (const table of [
10035
+ 1,
10036
+ 2,
10037
+ 3,
10038
+ 4
10039
+ ]) {
10040
+ const sorted = spans.filter((span) => span.function === table).sort((left, right) => left.start - right.start);
10041
+ let start = -1;
10042
+ let end = -1;
10043
+ for (const span of sorted) {
10044
+ const spanEnd = Math.min(span.start + span.size - 1, 65535);
10045
+ if (start >= 0 && span.start - (end + 1) <= MAXIMUM_GAP && Math.max(end, spanEnd) - start + 1 <= MAXIMUM_BLOCK) {
10046
+ end = Math.max(end, spanEnd);
10047
+ continue;
10048
+ }
10049
+ if (start >= 0) blocks.push({
10050
+ function: table,
10051
+ start,
10052
+ count: end - start + 1
10053
+ });
10054
+ start = span.start;
10055
+ end = spanEnd;
10056
+ }
10057
+ if (start >= 0) blocks.push({
10058
+ function: table,
10059
+ start,
10060
+ count: end - start + 1
10061
+ });
10062
+ }
10063
+ return blocks;
10064
+ }
10065
+ /**
10066
+ * Where a unit read lands in what the transport delivers.
10067
+ *
10068
+ * @param fn - The table's read function.
10069
+ * @param address - The address.
10070
+ * @returns `3:16`.
10071
+ */
10072
+ function modbusKeyOf(fn, address) {
10073
+ return `${String(fn)}:${String(address)}`;
10074
+ }
10075
+ /**
10076
+ * What a read's registers hold, before scale and meaning: a bit, a number or a text.
10077
+ *
10078
+ * @param read - The read.
10079
+ * @param wordOrder - Which register of a 32-bit value holds the high word.
10080
+ * @param registers - What the transport read.
10081
+ * @returns The raw value, or undefined when a register it needs was not read.
10082
+ */
10083
+ function modbusRawOf(read, wordOrder, registers) {
10084
+ const address = modbusWordOf(read.address);
10085
+ const words = [];
10086
+ for (let offset = 0; offset < modbusSizeOf(read); offset += 1) {
10087
+ const word = registers[modbusKeyOf(read.function, address + offset)];
10088
+ if (word === void 0) return;
10089
+ words.push(word & 65535);
10090
+ }
10091
+ const [first = 0, second = 0] = words;
10092
+ if (read.function === 1 || read.function === 2) return first !== 0;
10093
+ if (read.bit !== void 0) return (first >> read.bit & 1) === 1;
10094
+ switch (read.type ?? "u16") {
10095
+ case "u16": return first;
10096
+ case "s16": return first >= 32768 ? first - 65536 : first;
10097
+ case "string": return String.fromCharCode(...words.flatMap((word) => [word >> 8, word & 255])).replaceAll("\0", "").trim();
10098
+ default: {
10099
+ const [high, low] = wordOrder === "high" ? [first, second] : [second, first];
10100
+ const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(4));
10101
+ view.setUint16(0, high);
10102
+ view.setUint16(2, low);
10103
+ return read.type === "u32" ? view.getUint32(0) : read.type === "s32" ? view.getInt32(0) : view.getFloat32(0);
10104
+ }
10105
+ }
10106
+ }
10107
+ /**
10108
+ * A raw number times the read's scale, without the float noise the multiplication leaves.
10109
+ *
10110
+ * @param raw - The raw number.
10111
+ * @param read - The read, for its scale.
10112
+ * @returns The value.
10113
+ */
10114
+ function scaled(raw, read) {
10115
+ return Number((raw * (read.scale ?? 1)).toPrecision(12));
10116
+ }
10117
+ /**
10118
+ * The value a capability reads as a test shows it: a number scaled, a choice's or a text's
10119
+ * meaning, on or off.
10120
+ *
10121
+ * @param capability - The capability.
10122
+ * @param map - Its read and write.
10123
+ * @param raw - What {@link modbusRawOf} read.
10124
+ * @returns The value.
10125
+ */
10126
+ function modbusValueOf(capability, map, raw) {
10127
+ const { read } = map;
10128
+ if (read === void 0 || typeof raw === "string") return raw;
10129
+ if (typeof raw === "boolean") return raw;
10130
+ switch (capability) {
10131
+ case "sensor_binary":
10132
+ case "on_off": return map.write?.off === void 0 ? raw !== 0 : raw !== modbusWordOf(map.write.off);
10133
+ case "sensor_text":
10134
+ case "select": return read.options?.[String(raw)] ?? String(raw);
10135
+ default: return scaled(raw, read);
10136
+ }
10137
+ }
10138
+ /**
10139
+ * The range a level is spread over, in the read's units: the write's min and max, 0 to 100 unless
10140
+ * said.
10141
+ *
10142
+ * @param map - The level's read and write.
10143
+ * @returns The lowest and highest value.
10144
+ */
10145
+ function levelRangeOf(map) {
10146
+ return {
10147
+ min: map.write?.min ?? 0,
10148
+ max: map.write?.max ?? 100
10149
+ };
10150
+ }
10151
+ /**
10152
+ * One capability's state from what the registers hold.
10153
+ *
10154
+ * @param capability - The capability.
10155
+ * @param map - Its read and write.
10156
+ * @param wordOrder - Which register of a 32-bit value holds the high word.
10157
+ * @param registers - What the transport read.
10158
+ * @returns The capability's state, or undefined when its registers were not read.
10159
+ */
10160
+ function capabilityStateOf(capability, map, wordOrder, registers) {
10161
+ if (capability === "button") return {};
10162
+ if (map.read === void 0) return;
10163
+ const raw = modbusRawOf(map.read, wordOrder, registers);
10164
+ if (raw === void 0) return;
10165
+ const value = modbusValueOf(capability, map, raw);
10166
+ switch (capability) {
10167
+ case "sensor_binary":
10168
+ case "on_off": return { isOn: value === true };
10169
+ case "sensor_numeric":
10170
+ case "number": return typeof value === "number" ? { value } : void 0;
10171
+ case "sensor_text": return { value: String(value).slice(0, 512) };
10172
+ case "select": return typeof raw === "number" ? { option: String(raw) } : void 0;
10173
+ case "level": {
10174
+ if (typeof value !== "number") return;
10175
+ const { min, max } = levelRangeOf(map);
10176
+ const level = (value - min) / (max - min) * 100;
10177
+ return { level: Math.round(Math.min(100, Math.max(0, level)) * 10) / 10 };
10178
+ }
10179
+ default: return;
10180
+ }
10181
+ }
10182
+ /**
10183
+ * An entity's identifier within its device: what stays when it is renamed.
10184
+ *
10185
+ * @param entity - The entity.
10186
+ * @returns Its id, or the one its name gives.
10187
+ */
10188
+ function modbusObjectIdOf(entity) {
10189
+ return entity.id ?? modbusEntityIdOf(entity.name);
10190
+ }
10191
+ /**
10192
+ * What a capability declares to the house: a number's limits, a choice's options.
10193
+ *
10194
+ * @param capability - The capability.
10195
+ * @param map - Its read and write.
10196
+ * @returns Its params.
10197
+ */
10198
+ function paramsOf(capability, map) {
10199
+ switch (capability) {
10200
+ case "level": return { hasTransition: false };
10201
+ case "on_off": return { hasTransition: false };
10202
+ case "number": return {
10203
+ min: map.write?.min ?? 0,
10204
+ max: map.write?.max ?? 1,
10205
+ step: map.write?.step ?? 1
10206
+ };
10207
+ case "select": return { options: Object.entries(map.read?.options ?? {}).map(([value, label]) => ({
10208
+ value,
10209
+ label
10210
+ })) };
10211
+ default: return {};
10212
+ }
10213
+ }
10214
+ /**
10215
+ * An entity of a template as the house registers it.
10216
+ *
10217
+ * @param entity - The template's entity.
10218
+ * @returns Its descriptor.
10219
+ */
10220
+ function modbusEntityDescriptorOf(entity) {
10221
+ const capabilities = Object.fromEntries(Object.entries(entity.capabilities).map(([capability, map]) => [capability, paramsOf(capability, map)]));
10222
+ const unit = (entity.capabilities.sensor_numeric ?? entity.capabilities.number)?.read?.unit;
10223
+ return {
10224
+ domain: entity.domain,
10225
+ objectId: modbusObjectIdOf(entity),
10226
+ name: entity.name,
10227
+ capabilities,
10228
+ ...unit === void 0 || unit === "" ? {} : { unitOfMeasurement: unit }
10229
+ };
10230
+ }
10231
+ /**
10232
+ * Every capability's state of an entity from what the registers hold.
10233
+ *
10234
+ * A capability whose registers were not read - its block refused - keeps the state it had.
10235
+ *
10236
+ * @param entity - The entity.
10237
+ * @param wordOrder - Which register of a 32-bit value holds the high word.
10238
+ * @param registers - What the transport read.
10239
+ * @param previous - The entity's last state.
10240
+ * @returns Its state, or undefined when nothing of it was read and nothing was known.
10241
+ */
10242
+ function modbusEntityStateOf(entity, wordOrder, registers, previous) {
10243
+ const state = {};
10244
+ let isRead = false;
10245
+ for (const [capability, map] of Object.entries(entity.capabilities)) {
10246
+ const read = capabilityStateOf(capability, map, wordOrder, registers);
10247
+ const kept = previous?.[capability];
10248
+ if (read !== void 0) {
10249
+ state[capability] = read;
10250
+ isRead ||= capability !== "button";
10251
+ } else if (kept !== void 0) state[capability] = kept;
10252
+ }
10253
+ return isRead || previous !== void 0 ? state : void 0;
10254
+ }
10255
+ /**
10256
+ * The words a raw number is written as, in the read's type.
10257
+ *
10258
+ * @param raw - The raw number.
10259
+ * @param type - How the registers hold it.
10260
+ * @param wordOrder - Which register of a 32-bit value holds the high word.
10261
+ * @returns The words.
10262
+ * @throws {ValidationError} When the number does not fit the type.
10263
+ */
10264
+ function wordsOf(raw, type, wordOrder) {
10265
+ const view = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(4));
10266
+ const limits = {
10267
+ u16: [0, 65535],
10268
+ s16: [-32768, 32767],
10269
+ u32: [0, 4294967295],
10270
+ s32: [-2147483648, 2147483647],
10271
+ f32: [-Infinity, Infinity]
10272
+ }[type];
10273
+ if (raw < (limits[0] ?? 0) || raw > (limits[1] ?? 0)) throw new ValidationError(`${String(raw)} does not fit a ${type} register`, { details: {
10274
+ raw,
10275
+ type
10276
+ } });
10277
+ if (type === "u16" || type === "s16") return [raw & 65535];
10278
+ if (type === "f32") view.setFloat32(0, raw);
10279
+ else if (type === "u32") view.setUint32(0, raw);
10280
+ else view.setInt32(0, raw);
10281
+ const high = view.getUint16(0);
10282
+ const low = view.getUint16(2);
10283
+ return wordOrder === "high" ? [high, low] : [low, high];
10284
+ }
10285
+ /**
10286
+ * The words or bits a register write carries, for 05, 06, 15 or 16.
10287
+ *
10288
+ * @param fn - The write function.
10289
+ * @param word - The word: what 05 or 06 writes.
10290
+ * @param words - Every register, for 16.
10291
+ * @returns What goes in the request.
10292
+ */
10293
+ function valuesFor(fn, word, words) {
10294
+ return fn === 15 ? [word === 0 ? 0 : 1] : fn === 16 ? [...words] : [word];
10295
+ }
10296
+ /**
10297
+ * The number a command sets, checked against what the template allows.
10298
+ *
10299
+ * @param value - The value commanded.
10300
+ * @param map - The capability's read and write.
10301
+ * @returns The raw number to write.
10302
+ * @throws {ValidationError} When it is outside min and max.
10303
+ */
10304
+ function rawOfValue(value, map) {
10305
+ const { write, read } = map;
10306
+ if (write?.min !== void 0 && value < write.min || write?.max !== void 0 && value > write.max) throw new ValidationError(`${String(value)} is outside ${String(write.min ?? "-∞")} to ${String(write.max ?? "∞")}`, { details: {
10307
+ value,
10308
+ min: write.min ?? null,
10309
+ max: write.max ?? null
10310
+ } });
10311
+ const raw = value / (read?.scale ?? 1);
10312
+ return read?.type === "f32" ? raw : Math.round(raw);
10313
+ }
10314
+ /**
10315
+ * Turns a canonical command into the write that performs it.
10316
+ *
10317
+ * Refuses a value outside the capability's min and max here, so it never reaches the device.
10318
+ *
10319
+ * @param entity - The entity.
10320
+ * @param capability - The capability commanded.
10321
+ * @param command - The command, already checked against the capability.
10322
+ * @param wordOrder - Which register of a 32-bit value holds the high word.
10323
+ * @param previous - The entity's last state, for a toggle.
10324
+ * @returns The write.
10325
+ * @throws {ValidationError} When the capability is not written, or the value is refused.
10326
+ */
10327
+ function encodeModbusWrite(entity, capability, command, wordOrder, previous) {
10328
+ const map = entity.capabilities[capability];
10329
+ const write = map?.write;
10330
+ if (map === void 0 || write === void 0) throw new ValidationError(`${entity.name} cannot be commanded: ${capability} is only read`, { details: {
10331
+ entity: entity.name,
10332
+ capability
10333
+ } });
10334
+ const fn = write.function;
10335
+ const isCoil = fn === 5 || fn === 15;
10336
+ const address = modbusWordOf(write.address ?? map.read?.address ?? 0);
10337
+ const type = map.read?.type === void 0 || map.read.type === "string" ? "u16" : map.read.type;
10338
+ /**
10339
+ * The write of one raw number, in the type the register holds.
10340
+ *
10341
+ * @param raw - The raw number.
10342
+ * @returns The write.
10343
+ */
10344
+ const ofRaw = (raw) => {
10345
+ const words = wordsOf(raw, fn === 6 ? type === "s16" ? "s16" : "u16" : type, wordOrder);
10346
+ return {
10347
+ function: fn,
10348
+ address,
10349
+ values: valuesFor(fn, words[0] ?? 0, words)
10350
+ };
10351
+ };
10352
+ switch (capability) {
10353
+ case "on_off": {
10354
+ const word = (command["command"] === "toggle" ? previous?.on_off?.isOn !== true : command["command"] === "turn_on") ? modbusWordOf(write.on ?? (fn === 5 ? 65280 : 1)) : modbusWordOf(write.off ?? 0);
10355
+ return {
10356
+ function: fn,
10357
+ address,
10358
+ values: valuesFor(fn, word, [word])
10359
+ };
10360
+ }
10361
+ case "button": {
10362
+ const word = modbusWordOf(write.value ?? (isCoil ? 65280 : 1));
10363
+ return {
10364
+ function: fn,
10365
+ address,
10366
+ values: valuesFor(fn, word, [word])
10367
+ };
10368
+ }
10369
+ case "level": {
10370
+ const { min, max } = levelRangeOf(map);
10371
+ const level = Number(command["level"]);
10372
+ return ofRaw(rawOfValue(min + Math.min(100, Math.max(0, level)) / 100 * (max - min), {
10373
+ ...map,
10374
+ write: {
10375
+ ...write,
10376
+ min,
10377
+ max
10378
+ }
10379
+ }));
10380
+ }
10381
+ case "number": return ofRaw(rawOfValue(Number(command["value"]), map));
10382
+ case "select": {
10383
+ const option = typeof command["option"] === "string" ? command["option"] : "";
10384
+ if (map.read?.options?.[option] === void 0) throw new ValidationError(`${entity.name} has no option ${option}`, { details: {
10385
+ entity: entity.name,
10386
+ option
10387
+ } });
10388
+ return ofRaw(Number(option));
10389
+ }
10390
+ default: throw new ValidationError(`${entity.name} cannot be commanded: ${capability} is only read`, { details: {
10391
+ entity: entity.name,
10392
+ capability
10393
+ } });
10394
+ }
10395
+ }
10396
+ /** What the transport delivers for one poll: the registers read, or why none were. */
10397
+ const inboundSchema$1 = z.union([z.object({ registers: z.record(z.string(), z.number()) }), z.object({ error: z.string() })]);
10398
+ /**
10399
+ * The device a claim was made for.
10400
+ *
10401
+ * @param descriptor - The claim's descriptor.
10402
+ * @returns The device, or undefined for anything that is not one.
10403
+ */
10404
+ function snapshotOf(descriptor) {
10405
+ const parsed = modbusDeviceSnapshotSchema.safeParse(descriptor);
10406
+ return parsed.success ? parsed.data : void 0;
10407
+ }
10408
+ /**
10409
+ * What a poll of a device asks the transport: where it is, how often, and the blocks.
10410
+ *
10411
+ * @param device - The device.
10412
+ * @returns The poll's arguments.
10413
+ */
10414
+ function modbusPollOf(device) {
10415
+ return {
10416
+ deviceKey: device.deviceKey,
10417
+ host: device.host,
10418
+ port: device.port,
10419
+ unitId: device.unitId,
10420
+ framing: device.framing,
10421
+ everyMs: device.pollSeconds * 1e3,
10422
+ blocks: planModbusBlocks(device.template).map((block) => ({ ...block }))
10423
+ };
10424
+ }
10425
+ /**
10426
+ * Builds the Modbus driver of a vendor: the platform's own, or one whose `driver.json` says
10427
+ * `"kind": "modbus"`.
10428
+ *
10429
+ * @param manifest - The driver's.
10430
+ * @param manifest.id - Its kind, `vendor/driver`.
10431
+ * @returns The integration.
10432
+ */
10433
+ function createModbusIntegration(manifest) {
10434
+ /**
10435
+ * The device a claim was made for.
10436
+ *
10437
+ * @param context - The instance's mapping context.
10438
+ * @returns The device.
10439
+ * @throws {ValidationError} When the claim holds no device - which identification never makes.
10440
+ */
10441
+ const claimed = (context) => {
10442
+ const device = snapshotOf(context.claim.descriptor);
10443
+ if (device === void 0) throw new ValidationError(`${manifest.id} holds a claim that is not a Modbus device`, { details: { integration: manifest.id } });
10444
+ return device;
10445
+ };
10446
+ return {
10447
+ id: manifest.id,
10448
+ transport: MODBUS_TRANSPORT,
10449
+ optionsSchema: jsonObjectSchema,
10450
+ discovery: {},
10451
+ /**
10452
+ * Claims a device the broker hands over as this driver's.
10453
+ *
10454
+ * @param discovered - What the transport handed over.
10455
+ * @returns The claim, or null for anything that is not one of this driver's devices.
10456
+ */
10457
+ claim: (discovered) => {
10458
+ const device = snapshotOf(discovered.payload);
10459
+ return device?.kind !== manifest.id ? null : {
10460
+ deviceKey: device.deviceKey,
10461
+ externalId: device.deviceKey,
10462
+ descriptor: device
10463
+ };
10464
+ },
10465
+ /**
10466
+ * Polls each device at its pace, for the blocks its template reads.
10467
+ *
10468
+ * @param claims - The devices.
10469
+ * @returns One poll per device.
10470
+ */
10471
+ subscriptions: (claims) => claims.flatMap((claim) => {
10472
+ const device = snapshotOf(claim.descriptor);
10473
+ return device === void 0 ? [] : [{
10474
+ op: "poll",
10475
+ args: modbusPollOf(device)
10476
+ }];
10477
+ }),
10478
+ /**
10479
+ * Describes the device and its entities, from its template.
10480
+ *
10481
+ * @param claim - The claim.
10482
+ * @returns The device.
10483
+ * @throws {ValidationError} When the claim holds no Modbus device.
10484
+ */
10485
+ describe: (claim) => {
10486
+ const device = snapshotOf(claim.descriptor);
10487
+ if (device === void 0) throw new ValidationError(`${manifest.id} cannot describe a claim with no Modbus device`, { details: { integration: manifest.id } });
10488
+ const { template } = device;
10489
+ return {
10490
+ externalId: claim.externalId,
10491
+ name: device.name,
10492
+ model: (template.device === "" ? template.name : template.device).slice(0, 128),
10493
+ entities: template.entities.map(modbusEntityDescriptorOf)
10494
+ };
10495
+ },
10496
+ /**
10497
+ * Turns what a poll read into reports, one per entity; every entity unavailable when the
10498
+ * device did not answer.
10499
+ *
10500
+ * @param message - What the transport delivered.
10501
+ * @param context - The identifiers the hub assigned, and the last states.
10502
+ * @returns The reports.
10503
+ */
10504
+ toState: (message, context) => {
10505
+ const parsed = inboundSchema$1.safeParse(message.payload);
10506
+ const device = snapshotOf(context.claim.descriptor);
10507
+ if (!parsed.success || device === void 0) return [];
10508
+ return device.template.entities.flatMap((entity) => {
10509
+ const entityId = context.entities.get(modbusObjectIdOf(entity));
10510
+ if (entityId === void 0) return [];
10511
+ const previous = context.lastState(entityId);
10512
+ if ("error" in parsed.data) return [{
10513
+ entityId,
10514
+ state: previous ?? {},
10515
+ attributes: {},
10516
+ isAvailable: false
10517
+ }];
10518
+ const state = modbusEntityStateOf(entity, device.template.wordOrder, parsed.data.registers, previous);
10519
+ return state === void 0 ? [] : [{
10520
+ entityId,
10521
+ state,
10522
+ attributes: {},
10523
+ isAvailable: true
10524
+ }];
10525
+ });
10526
+ },
10527
+ /**
10528
+ * Turns a command into the write that performs it.
10529
+ *
10530
+ * @param target - The entity, the capability and the command.
10531
+ * @param context - The claim and the last states.
10532
+ * @returns The request.
10533
+ * @throws {ValidationError} When the entity does not take the command, or the value is
10534
+ * outside its min and max.
10535
+ */
10536
+ toCommand: (target, context) => {
10537
+ const device = claimed(context);
10538
+ const entity = device.template.entities.find((candidate) => context.entities.get(modbusObjectIdOf(candidate)) === target.entityId);
10539
+ if (entity === void 0) throw new ValidationError(`${manifest.id} has no entity ${target.entityId}`, { details: {
10540
+ integration: manifest.id,
10541
+ entityId: target.entityId
10542
+ } });
10543
+ const write = encodeModbusWrite(entity, target.capability, target.command, device.template.wordOrder, context.lastState(target.entityId));
10544
+ return {
10545
+ deviceKey: device.deviceKey,
10546
+ op: "write",
10547
+ args: {
10548
+ host: device.host,
10549
+ port: device.port,
10550
+ unitId: device.unitId,
10551
+ framing: device.framing,
10552
+ function: write.function,
10553
+ address: write.address,
10554
+ values: [...write.values]
10555
+ }
10556
+ };
10557
+ }
10558
+ };
10559
+ }
10560
+ //#endregion
10561
+ //#region ../package-runtime/dist/mqtt-announcement.js
10562
+ /**
10563
+ * What a device says of itself on the house's MQTT broker, read: the MQTT discovery convention.
10564
+ *
10565
+ * A device announces each of its entities with a retained JSON document on
10566
+ * `<prefix>/<component>/[<node_id>/]<object_id>/config` - its name, the topics it reports and is
10567
+ * commanded on, the device it belongs to, the firmware that sent it - and takes it back with an
10568
+ * empty one. Tasmota, ESPHome, OpenMQTTGateway and most others speak it, under the prefix
10569
+ * `homeassistant` unless told otherwise. This module reads one announcement into an
10570
+ * {@link MqttEntity}: the abbreviations expanded, `~` put in place of the base topic, the device
10571
+ * and its origin found. A device the owner maps by hand is read into the same entity, so one
10572
+ * mapping (`mqtt-mapping.ts`) draws, reads and commands both.
10573
+ *
10574
+ * **Value templates are read as paths.** Announcements carry Jinja templates; the platform does
10575
+ * not render Jinja and does not pretend to. The templates nearly every device announces are a
10576
+ * value itself or one key of its JSON - `{{ value }}`, `{{ value_json.temperature }}`,
10577
+ * `{{ value_json['temperature'] }}`, `{{ value_json.a.b }}` - and those are read as the path they
10578
+ * name. Anything else - a filter, arithmetic, a condition - is skipped, and the Brokers page says
10579
+ * why, rather than showing a wrong value.
10580
+ */
10581
+ /** One step of a path: `.key`, `['key']`, `["key"]` or `[0]`. */
10582
+ const STEP = /^(?:\.([A-Za-z_][A-Za-z0-9_]*)|\[\s*'([^']*)'\s*\]|\[\s*"([^"]*)"\s*\]|\[\s*(\d+)\s*\])/u;
10583
+ /**
10584
+ * Reads a template as a path.
10585
+ *
10586
+ * @param template - The template the device announced; none is the value itself.
10587
+ * @returns The path, or that it is not supported.
10588
+ */
10589
+ function readTemplate(template) {
10590
+ if (template === void 0 || template.trim() === "") return {
10591
+ kind: "path",
10592
+ path: []
10593
+ };
10594
+ const inner = /^\s*\{\{\s*(.*?)\s*\}\}\s*$/su.exec(template)?.[1];
10595
+ if (inner === void 0) return {
10596
+ kind: "unsupported",
10597
+ template
10598
+ };
10599
+ if (inner === "value") return {
10600
+ kind: "path",
10601
+ path: []
10602
+ };
10603
+ if (!inner.startsWith("value_json")) return {
10604
+ kind: "unsupported",
10605
+ template
10606
+ };
10607
+ const path = [];
10608
+ let rest = inner.slice(10);
10609
+ while (rest !== "") {
10610
+ const step = STEP.exec(rest);
10611
+ if (step === null) return {
10612
+ kind: "unsupported",
10613
+ template
10614
+ };
10615
+ path.push(step[1] ?? step[2] ?? step[3] ?? step[4] ?? "");
10616
+ rest = rest.slice(step[0].length);
10617
+ }
10618
+ return path.length === 0 ? {
10619
+ kind: "unsupported",
10620
+ template
10621
+ } : {
10622
+ kind: "path",
10623
+ path
10624
+ };
10625
+ }
10626
+ /**
10627
+ * Reads a value from a payload along a path.
10628
+ *
10629
+ * @param payload - What was published, as text.
10630
+ * @param path - Where the value is; none for the payload itself.
10631
+ * @returns The value, or undefined when the payload has nothing there.
10632
+ */
10633
+ function valueAt(payload, path) {
10634
+ if (path.length === 0) return payload;
10635
+ let value;
10636
+ try {
10637
+ value = JSON.parse(payload);
10638
+ } catch {
10639
+ return;
10640
+ }
10641
+ for (const key of path) {
10642
+ if (typeof value !== "object" || value === null) return;
10643
+ value = value[key];
10644
+ }
10645
+ return value;
10646
+ }
10647
+ /**
10648
+ * A text value, or nothing.
10649
+ *
10650
+ * @param value - The value.
10651
+ * @returns It, when it is non-empty text.
10652
+ */
10653
+ function textOf(value) {
10654
+ return typeof value === "string" && value !== "" ? value : void 0;
10655
+ }
10656
+ /** One entity of a device, as a claim keeps it. */
10657
+ const mqttEntitySnapshotSchema = z.object({
10658
+ key: z.string().min(1),
10659
+ objectId: z.string().min(1).max(64),
10660
+ name: z.string().max(128),
10661
+ component: z.enum(MQTT_COMPONENTS),
10662
+ config: z.record(z.string(), z.unknown())
10663
+ });
10664
+ /**
10665
+ * A device the broker hears, whole: who it says it is and every entity it has. What discovery
10666
+ * proposes, what a claim keeps and what the transport delivers.
10667
+ */
10668
+ const mqttDeviceSnapshotSchema = z.object({
10669
+ deviceKey: z.string().min(1).max(256),
10670
+ identity: mqttIdentitySchema,
10671
+ entities: z.array(mqttEntitySnapshotSchema).max(256)
10672
+ });
10673
+ //#endregion
10674
+ //#region ../package-runtime/dist/mqtt-mapping.js
10675
+ /**
10676
+ * The platform's mapping of a device the house's MQTT broker hears onto entities: the one driver
10677
+ * every announced or mapped device can be run by, whoever's integration it is.
10678
+ *
10679
+ * An announcement describes its entity - a component, the topics it reports and is commanded on,
10680
+ * the payloads it speaks - so one mapping covers what any firmware announces, and a vendor whose
10681
+ * `driver.json` says `"kind": "mqtt"` gets it without writing code: its devices are its own, on
10682
+ * its page, and mapped here.
10683
+ *
10684
+ * **What is mapped.** A sensor (a number when it announces a unit or how its numbers add up,
10685
+ * text otherwise), a binary sensor, a switch, a light (on/off, brightness, white; plain or JSON),
10686
+ * a cover, a button, a number, a select and a lock. A number is registered in its class's unit -
10687
+ * a power in watts, however the device counts it - and converted on the way.
10688
+ *
10689
+ * **Pure throughout**, like every integration: what the transport hands over is the device whole
10690
+ * and the last text of every topic its entities read, with the topics that changed, so a state is
10691
+ * always computed from every topic it needs - a light's brightness with whether it is on, a
10692
+ * cover's position with its motion. An entity with no state topic is read from its command
10693
+ * topic: what the hub last published there is what it was told to be.
10694
+ */
10695
+ /** Reads what the transport delivers. */
10696
+ const inboundSchema = z.object({
10697
+ device: mqttDeviceSnapshotSchema,
10698
+ texts: z.record(z.string(), z.string()),
10699
+ changed: z.array(z.string()).nullable()
10700
+ });
10701
+ /** How a sensor's numbers add up, as an announcement may say it. */
10702
+ const STATE_CLASSES = [
10703
+ "measurement",
10704
+ "total",
10705
+ "total_increasing"
10706
+ ];
10707
+ /**
10708
+ * One of an entity's settings, as text, with a default.
10709
+ *
10710
+ * @param entity - The entity.
10711
+ * @param key - The setting.
10712
+ * @param fallback - What it is when not announced.
10713
+ * @returns It.
10714
+ */
10715
+ function textSetting(entity, key, fallback) {
10716
+ const value = entity.config[key];
10717
+ return typeof value === "string" ? value : typeof value === "number" ? String(value) : fallback;
10718
+ }
10719
+ /**
10720
+ * One of an entity's settings, as a number, with a default.
10721
+ *
10722
+ * @param entity - The entity.
10723
+ * @param key - The setting.
10724
+ * @param fallback - What it is when not announced.
10725
+ * @returns It.
10726
+ */
10727
+ function numberSetting(entity, key, fallback) {
10728
+ const value = entity.config[key];
10729
+ const number = typeof value === "number" ? value : Number(value ?? NaN);
10730
+ return Number.isFinite(number) ? number : fallback;
10731
+ }
10732
+ /**
10733
+ * A topic the entity names.
10734
+ *
10735
+ * @param entity - The entity.
10736
+ * @param key - Which: `state_topic`.
10737
+ * @returns It, when announced.
10738
+ */
10739
+ function topicOf(entity, key) {
10740
+ return textOf(entity.config[key]);
10741
+ }
10742
+ /**
10743
+ * Whether a light speaks JSON.
10744
+ *
10745
+ * @param entity - The light.
10746
+ * @returns True for `schema: json`.
10747
+ */
10748
+ function isJsonLight(entity) {
10749
+ return entity.component === "light" && entity.config["schema"] === "json";
10750
+ }
10751
+ /**
10752
+ * Whether a JSON light announces a feature: `brightness: true`, or a colour mode that has it.
10753
+ *
10754
+ * @param entity - The light.
10755
+ * @param flag - `brightness`, `color_temp`.
10756
+ * @returns True when it does.
10757
+ */
10758
+ function jsonLightHas(entity, flag) {
10759
+ if (entity.config[flag] === true) return true;
10760
+ const modes = entity.config["supported_color_modes"];
10761
+ if (!Array.isArray(modes)) return false;
10762
+ return flag === "color_temp" ? modes.includes("color_temp") : modes.some((mode) => mode !== "onoff");
10763
+ }
10764
+ /**
10765
+ * Whether an entity reports nothing of its own: no state topic, so it is what it was told to be,
10766
+ * read from its command topic.
10767
+ *
10768
+ * @param entity - The entity.
10769
+ * @returns True for one.
10770
+ */
10771
+ function isOptimistic(entity) {
10772
+ return topicOf(entity, "state_topic") === void 0 && entity.component !== "button";
10773
+ }
10774
+ /**
10775
+ * A sensor's measurement, as it is registered: in its class's unit, with the class's default
10776
+ * state class - or without the class, when its unit cannot be brought to the class's.
10777
+ *
10778
+ * @param entity - The sensor.
10779
+ * @returns What it is registered with, and the unit its numbers are converted from.
10780
+ */
10781
+ function measurementOf(entity) {
10782
+ const unit = textOf(entity.config["unit_of_measurement"]);
10783
+ const deviceClass = textOf(entity.config["device_class"]);
10784
+ const said = textOf(entity.config["state_class"]);
10785
+ const stateClass = STATE_CLASSES.find((each) => each === said);
10786
+ const unitOnly = {
10787
+ ...unit === void 0 ? {} : { unitOfMeasurement: unit },
10788
+ ...stateClass === void 0 ? {} : { stateClass }
10789
+ };
10790
+ if (deviceClass === void 0 || getSensorClass(deviceClass)?.valueKind !== "number") return { fields: unitOnly };
10791
+ const canonical = resolveCanonicalUnit(deviceClass);
10792
+ const registered = canonical ?? unit;
10793
+ if (!(unit === void 0 || canonical === void 0 || unit === canonical || toCanonical(deviceClass, 1, unit) !== void 0) || sensorRegistrationIssue({
10794
+ deviceClass,
10795
+ unitOfMeasurement: registered
10796
+ }) !== void 0) return { fields: unitOnly };
10797
+ const resolved = resolveStateClass(deviceClass, stateClass);
10798
+ return {
10799
+ fields: {
10800
+ deviceClass,
10801
+ ...registered === void 0 ? {} : { unitOfMeasurement: registered },
10802
+ ...resolved === void 0 ? {} : { stateClass: resolved }
10803
+ },
10804
+ ...unit !== void 0 && canonical !== void 0 && unit !== canonical ? { conversion: {
10805
+ deviceClass,
10806
+ unit
10807
+ } } : {}
10808
+ };
10809
+ }
10810
+ /**
10811
+ * What one entity is registered as.
10812
+ *
10813
+ * @param entity - The entity.
10814
+ * @returns Its shape.
10815
+ */
10816
+ function mqttShapeOf(entity) {
10817
+ const deviceClass = textOf(entity.config["device_class"]);
10818
+ const withClass = deviceClass === void 0 ? {} : { deviceClass };
10819
+ const precision = entity.config["suggested_display_precision"];
10820
+ const withPrecision = typeof precision === "number" && Number.isInteger(precision) && precision >= 0 ? { displayPrecision: Math.min(precision, 10) } : {};
10821
+ switch (entity.component) {
10822
+ case "sensor": {
10823
+ const { fields } = measurementOf(entity);
10824
+ return fields.unitOfMeasurement === void 0 && fields.stateClass === void 0 ? {
10825
+ domain: "sensor",
10826
+ capabilities: { sensor_text: {} }
10827
+ } : {
10828
+ domain: "sensor",
10829
+ capabilities: { sensor_numeric: {} },
10830
+ ...fields,
10831
+ ...withPrecision
10832
+ };
10833
+ }
10834
+ case "binary_sensor": return {
10835
+ domain: "binary_sensor",
10836
+ capabilities: { sensor_binary: {} },
10837
+ ...withClass
10838
+ };
10839
+ case "switch": return {
10840
+ domain: "switch",
10841
+ capabilities: { on_off: {} },
10842
+ ...withClass
10843
+ };
10844
+ case "light": {
10845
+ const json = isJsonLight(entity);
10846
+ const hasLevel = json ? jsonLightHas(entity, "brightness") : topicOf(entity, "brightness_command_topic") !== void 0;
10847
+ const hasWhite = json ? jsonLightHas(entity, "color_temp") : topicOf(entity, "color_temp_command_topic") !== void 0;
10848
+ return {
10849
+ domain: "light",
10850
+ capabilities: {
10851
+ on_off: {},
10852
+ ...hasLevel ? { level: { hasTransition: false } } : {},
10853
+ ...hasWhite ? { color_temp: {
10854
+ minMireds: Math.round(numberSetting(entity, "min_mireds", 153)),
10855
+ maxMireds: Math.round(numberSetting(entity, "max_mireds", 500))
10856
+ } } : {}
10857
+ }
10858
+ };
10859
+ }
10860
+ case "cover": return {
10861
+ domain: "cover",
10862
+ capabilities: { cover: {
10863
+ hasPosition: topicOf(entity, "position_topic") !== void 0 || topicOf(entity, "set_position_topic") !== void 0,
10864
+ hasTilt: false
10865
+ } },
10866
+ ...withClass
10867
+ };
10868
+ case "button": return {
10869
+ domain: "button",
10870
+ capabilities: { button: {} },
10871
+ ...withClass
10872
+ };
10873
+ case "number": {
10874
+ const min = numberSetting(entity, "min", 1);
10875
+ const max = numberSetting(entity, "max", 100);
10876
+ const unit = textOf(entity.config["unit_of_measurement"]);
10877
+ return {
10878
+ domain: "number",
10879
+ capabilities: { number: {
10880
+ min,
10881
+ max: max > min ? max : min + 1,
10882
+ step: numberSetting(entity, "step", 1)
10883
+ } },
10884
+ ...unit === void 0 ? {} : { unitOfMeasurement: unit }
10885
+ };
10886
+ }
10887
+ case "select": {
10888
+ const options = Array.isArray(entity.config["options"]) ? [...new Set(entity.config["options"].map(String))].filter((option) => option !== "" && option.length <= 64) : [];
10889
+ return {
10890
+ domain: "select",
10891
+ capabilities: { select: { options: (options.length === 0 ? ["—"] : options).slice(0, 64).map((option) => ({
10892
+ value: option,
10893
+ label: option
10894
+ })) } }
10895
+ };
10896
+ }
10897
+ case "lock": return {
10898
+ domain: "lock",
10899
+ capabilities: { lock: { hasCode: false } }
10900
+ };
10901
+ }
10902
+ }
10903
+ /**
10904
+ * The path a template of an entity names.
10905
+ *
10906
+ * @param entity - The entity.
10907
+ * @param key - The template's key.
10908
+ * @returns The path; the payload itself for none, or one that is not read.
10909
+ */
10910
+ function pathOf(entity, key) {
10911
+ const template = readTemplate(textOf(entity.config[key]));
10912
+ return template.kind === "path" ? template.path : [];
10913
+ }
10914
+ /**
10915
+ * Which template reads an entity's state: its value template, a light's state value template, or
10916
+ * its state template, the first it announces.
10917
+ *
10918
+ * @param config - The announcement.
10919
+ * @returns The key.
10920
+ */
10921
+ function stateTemplateKeyOf(config) {
10922
+ return [
10923
+ "value_template",
10924
+ "state_value_template",
10925
+ "state_template"
10926
+ ].find((key) => textOf(config[key]) !== void 0) ?? "value_template";
10927
+ }
10928
+ /**
10929
+ * The availability topics of an entity, with the payloads that say it is and is not there.
10930
+ *
10931
+ * @param entity - The entity.
10932
+ * @returns The topics.
10933
+ */
10934
+ function availabilityOf(entity) {
10935
+ const shared = {
10936
+ available: textSetting(entity, "payload_available", "online"),
10937
+ notAvailable: textSetting(entity, "payload_not_available", "offline")
10938
+ };
10939
+ const single = topicOf(entity, "availability_topic");
10940
+ const topics = (Array.isArray(entity.config["availability"]) ? entity.config["availability"] : []).flatMap((entry) => {
10941
+ if (typeof entry !== "object" || entry === null) return [];
10942
+ const record = entry;
10943
+ const topic = textOf(record["topic"]);
10944
+ const template = readTemplate(textOf(record["value_template"]));
10945
+ return topic === void 0 ? [] : [{
10946
+ topic,
10947
+ available: textOf(record["payload_available"]) ?? shared.available,
10948
+ notAvailable: textOf(record["payload_not_available"]) ?? shared.notAvailable,
10949
+ path: template.kind === "path" ? template.path : []
10950
+ }];
10951
+ });
10952
+ return single === void 0 ? topics : [{
10953
+ topic: single,
10954
+ ...shared,
10955
+ path: pathOf(entity, "availability_template")
10956
+ }, ...topics];
10957
+ }
10958
+ /**
10959
+ * The topics one entity is read from: its state (its command topic, when it has none), its
10960
+ * availability, a plain light's brightness and white, a cover's position.
10961
+ *
10962
+ * @param entity - The entity.
10963
+ * @returns Them, each with what it carries.
10964
+ */
10965
+ function readersOf(entity) {
10966
+ const optimistic = isOptimistic(entity);
10967
+ const readers = [];
10968
+ /**
10969
+ * Notes one topic, when the entity has it.
10970
+ *
10971
+ * @param topic - The topic.
10972
+ * @param reading - What it carries.
10973
+ * @param path - Where the value is.
10974
+ */
10975
+ const add = (topic, reading, path) => {
10976
+ if (topic !== void 0) readers.push({
10977
+ topic,
10978
+ reading,
10979
+ path
10980
+ });
10981
+ };
10982
+ add(topicOf(entity, optimistic ? "command_topic" : "state_topic"), "state", optimistic ? [] : pathOf(entity, stateTemplateKeyOf(entity.config)));
10983
+ for (const availability of availabilityOf(entity)) add(availability.topic, "availability", availability.path);
10984
+ if (entity.component === "light" && !isJsonLight(entity)) {
10985
+ add(topicOf(entity, optimistic ? "brightness_command_topic" : "brightness_state_topic"), "brightness", optimistic ? [] : pathOf(entity, "brightness_value_template"));
10986
+ add(topicOf(entity, optimistic ? "color_temp_command_topic" : "color_temp_state_topic"), "color_temp", optimistic ? [] : pathOf(entity, "color_temp_value_template"));
10987
+ }
10988
+ if (entity.component === "cover" && !optimistic) add(topicOf(entity, "position_topic"), "position", pathOf(entity, "position_template"));
10989
+ return readers;
10990
+ }
10991
+ /**
10992
+ * Every topic an entity is read from.
10993
+ *
10994
+ * @param entity - The entity.
10995
+ * @returns The topics, each once.
10996
+ */
10997
+ function mqttTopicsOf(entity) {
10998
+ return [...new Set(readersOf(entity).map((reader) => reader.topic))];
10999
+ }
11000
+ /**
11001
+ * A number from what a template read.
11002
+ *
11003
+ * @param value - What it read.
11004
+ * @returns The number, or undefined when it is not one.
11005
+ */
11006
+ function numberOf(value) {
11007
+ const number = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
11008
+ return Number.isFinite(number) ? number : void 0;
11009
+ }
11010
+ /**
11011
+ * Text from what a template read.
11012
+ *
11013
+ * @param value - What it read.
11014
+ * @returns The text, or undefined for nothing.
11015
+ */
11016
+ function stringOf(value) {
11017
+ if (typeof value === "string") return value;
11018
+ return typeof value === "number" || typeof value === "boolean" ? String(value) : void 0;
11019
+ }
11020
+ /**
11021
+ * A brightness, as a level out of 100.
11022
+ *
11023
+ * @param value - The brightness, on the device's scale.
11024
+ * @param scale - The scale's top.
11025
+ * @returns The level, or undefined when it is not a number.
11026
+ */
11027
+ function levelOf(value, scale) {
11028
+ const brightness = numberOf(value);
11029
+ return brightness === void 0 || scale <= 0 ? void 0 : Math.max(0, Math.min(100, brightness / scale * 100));
11030
+ }
11031
+ /**
11032
+ * A colour temperature, in mireds the platform takes.
11033
+ *
11034
+ * @param value - The temperature, in mireds.
11035
+ * @returns It, or undefined when it is not a number.
11036
+ */
11037
+ function miredsOf(value) {
11038
+ const mireds = numberOf(value);
11039
+ return mireds === void 0 ? void 0 : Math.max(1, Math.min(1e3, Math.round(mireds)));
11040
+ }
11041
+ /**
11042
+ * Whether a text is the entity's "on" or "off", by its state payloads - or, read from its command
11043
+ * topic, by the payloads it is commanded with.
11044
+ *
11045
+ * @param entity - The entity.
11046
+ * @param text - What its state topic carried.
11047
+ * @returns True, false, or undefined for neither.
11048
+ */
11049
+ function isOnOf(entity, text) {
11050
+ const onPayload = textSetting(entity, "payload_on", "ON");
11051
+ const offPayload = textSetting(entity, "payload_off", "OFF");
11052
+ const on = isOptimistic(entity) ? onPayload : textSetting(entity, "state_on", onPayload);
11053
+ const off = isOptimistic(entity) ? offPayload : textSetting(entity, "state_off", offPayload);
11054
+ return text === on ? true : text === off ? false : void 0;
11055
+ }
11056
+ /**
11057
+ * A JSON light's state, from its state document, what the document leaves out kept as it was.
11058
+ *
11059
+ * @param entity - The light.
11060
+ * @param text - Its state topic's text.
11061
+ * @param previous - What it was.
11062
+ * @returns The capabilities it says, or nothing.
11063
+ */
11064
+ function jsonLightState(entity, text, previous) {
11065
+ let document;
11066
+ try {
11067
+ document = text === void 0 ? void 0 : JSON.parse(text);
11068
+ } catch {
11069
+ return {};
11070
+ }
11071
+ if (typeof document !== "object" || document === null) return {};
11072
+ const record = document;
11073
+ const shape = mqttShapeOf(entity);
11074
+ const state = stringOf(record["state"]);
11075
+ const level = levelOf(record["brightness"], numberSetting(entity, "brightness_scale", 255));
11076
+ const mireds = miredsOf(record["color_temp"]);
11077
+ return {
11078
+ ...state === void 0 ? previous?.on_off === void 0 ? {} : { on_off: previous.on_off } : { on_off: { isOn: state.toUpperCase() === "ON" } },
11079
+ ...shape.capabilities.level === void 0 ? {} : level === void 0 ? previous?.level === void 0 ? {} : { level: previous.level } : { level: { level } },
11080
+ ...shape.capabilities.color_temp === void 0 ? {} : mireds === void 0 ? previous?.color_temp === void 0 ? {} : { color_temp: previous.color_temp } : { color_temp: { mireds } }
11081
+ };
11082
+ }
11083
+ /**
11084
+ * A cover's state: its motion from its state topic, its position from its position topic - or,
11085
+ * for a cover with none, from where its state says it stopped.
11086
+ *
11087
+ * @param entity - The cover.
11088
+ * @param stateText - What its state topic carried.
11089
+ * @param position - What its position topic read, as a value.
11090
+ * @param previous - What it was.
11091
+ * @returns The cover's state.
11092
+ */
11093
+ function coverState(entity, stateText, position, previous) {
11094
+ const current = previous?.cover ?? {
11095
+ position: 0,
11096
+ motion: "stopped"
11097
+ };
11098
+ const states = {
11099
+ [textSetting(entity, "state_open", "open")]: {
11100
+ motion: "stopped",
11101
+ position: 100
11102
+ },
11103
+ [textSetting(entity, "state_closed", "closed")]: {
11104
+ motion: "stopped",
11105
+ position: 0
11106
+ },
11107
+ [textSetting(entity, "state_opening", "opening")]: { motion: "opening" },
11108
+ [textSetting(entity, "state_closing", "closing")]: { motion: "closing" },
11109
+ [textSetting(entity, "state_stopped", "stopped")]: { motion: "stopped" }
11110
+ };
11111
+ const said = stateText === void 0 ? void 0 : states[stateText];
11112
+ const raw = numberOf(position);
11113
+ const open = numberSetting(entity, "position_open", 100);
11114
+ const closed = numberSetting(entity, "position_closed", 0);
11115
+ const reported = raw === void 0 || open === closed ? void 0 : Math.max(0, Math.min(100, (raw - closed) / (open - closed) * 100));
11116
+ const hasPosition = topicOf(entity, "position_topic") !== void 0;
11117
+ return { cover: {
11118
+ position: reported ?? (hasPosition ? current.position : said?.position ?? current.position),
11119
+ motion: said?.motion ?? current.motion
11120
+ } };
11121
+ }
11122
+ /**
11123
+ * What one entity's topics say it is now.
11124
+ *
11125
+ * @param entity - The entity.
11126
+ * @param textOfTopic - The last text a topic carried.
11127
+ * @param previous - What it was last reported as; undefined before it ever was.
11128
+ * @returns Its state and whether it is there, or undefined while it has nothing to say.
11129
+ */
11130
+ function mqttStateOf(entity, textOfTopic, previous) {
11131
+ const readers = readersOf(entity);
11132
+ /**
11133
+ * What one reading's topic carries, at its path.
11134
+ *
11135
+ * @param reading - Which.
11136
+ * @returns The value, or undefined.
11137
+ */
11138
+ const read = (reading) => {
11139
+ const reader = readers.find((each) => each.reading === reading);
11140
+ const text = reader === void 0 ? void 0 : textOfTopic(reader.topic);
11141
+ return reader === void 0 || text === void 0 ? void 0 : valueAt(text, reader.path);
11142
+ };
11143
+ const stateValue = read("state");
11144
+ const stateText = stringOf(stateValue);
11145
+ let state;
11146
+ switch (entity.component) {
11147
+ case "sensor": {
11148
+ if (mqttShapeOf(entity).capabilities.sensor_text !== void 0) {
11149
+ state = stateText === void 0 ? {} : { sensor_text: { value: stateText.slice(0, 512) } };
11150
+ break;
11151
+ }
11152
+ const number = numberOf(stateValue);
11153
+ const { conversion } = measurementOf(entity);
11154
+ const value = number === void 0 || conversion === void 0 ? number : toCanonical(conversion.deviceClass, number, conversion.unit);
11155
+ state = value === void 0 ? {} : { sensor_numeric: { value } };
11156
+ break;
11157
+ }
11158
+ case "binary_sensor": {
11159
+ const isOn = stateText === textSetting(entity, "payload_on", "ON") ? true : stateText === textSetting(entity, "payload_off", "OFF") ? false : void 0;
11160
+ state = isOn === void 0 ? {} : { sensor_binary: { isOn } };
11161
+ break;
11162
+ }
11163
+ case "switch": {
11164
+ const isOn = isOnOf(entity, stateText);
11165
+ state = isOn === void 0 ? {} : { on_off: { isOn } };
11166
+ break;
11167
+ }
11168
+ case "lock": {
11169
+ const states = isOptimistic(entity) ? {
11170
+ [textSetting(entity, "payload_lock", "LOCK")]: "locked",
11171
+ [textSetting(entity, "payload_unlock", "UNLOCK")]: "unlocked"
11172
+ } : {
11173
+ [textSetting(entity, "state_locked", "LOCKED")]: "locked",
11174
+ [textSetting(entity, "state_unlocked", "UNLOCKED")]: "unlocked",
11175
+ [textSetting(entity, "state_jammed", "JAMMED")]: "jammed"
11176
+ };
11177
+ const lockState = stateText === void 0 ? void 0 : states[stateText];
11178
+ state = lockState === void 0 ? {} : { lock: { lockState } };
11179
+ break;
11180
+ }
11181
+ case "select":
11182
+ state = { select: { option: stateText === void 0 || stateText === "" ? null : stateText.slice(0, 64) } };
11183
+ break;
11184
+ case "number":
11185
+ state = { number: { value: numberOf(stateValue) ?? null } };
11186
+ break;
11187
+ case "button":
11188
+ state = { button: {} };
11189
+ break;
11190
+ case "cover":
11191
+ state = coverState(entity, stateText, read("position"), previous);
11192
+ break;
11193
+ case "light": {
11194
+ if (isJsonLight(entity)) {
11195
+ state = jsonLightState(entity, stateText, previous);
11196
+ break;
11197
+ }
11198
+ const shape = mqttShapeOf(entity);
11199
+ const isOn = isOnOf(entity, stateText);
11200
+ const level = levelOf(read("brightness"), numberSetting(entity, "brightness_scale", 255));
11201
+ const mireds = miredsOf(read("color_temp"));
11202
+ state = {
11203
+ ...isOn === void 0 ? {} : { on_off: { isOn } },
11204
+ ...level === void 0 || shape.capabilities.level === void 0 ? {} : { level: { level } },
11205
+ ...mireds === void 0 || shape.capabilities.color_temp === void 0 ? {} : { color_temp: { mireds } }
11206
+ };
11207
+ break;
11208
+ }
11209
+ }
11210
+ if (Object.keys(state).length === 0 || entity.component === "light" && state["on_off"] === void 0) return;
11211
+ const parsed = capabilityStateSchema.safeParse(state);
11212
+ return parsed.success ? {
11213
+ state: parsed.data,
11214
+ isAvailable: isAvailableOf(entity, textOfTopic)
11215
+ } : void 0;
11216
+ }
11217
+ /**
11218
+ * Whether an entity's device says it is there: always, for one with no availability topic;
11219
+ * otherwise once one of its topics said so and none says it is not.
11220
+ *
11221
+ * @param entity - The entity.
11222
+ * @param textOfTopic - The last text a topic carried.
11223
+ * @returns True when it is there.
11224
+ */
11225
+ function isAvailableOf(entity, textOfTopic) {
11226
+ const entries = availabilityOf(entity);
11227
+ if (entries.length === 0) return true;
11228
+ const said = entries.flatMap((entry) => {
11229
+ const text = textOfTopic(entry.topic);
11230
+ const value = text === void 0 ? void 0 : stringOf(valueAt(text, entry.path));
11231
+ return value === entry.available ? [true] : value === entry.notAvailable ? [false] : [];
11232
+ });
11233
+ return said.includes(true) && !said.includes(false);
11234
+ }
11235
+ /**
11236
+ * One field of a command, as text.
11237
+ *
11238
+ * @param value - The field.
11239
+ * @returns It as text; empty for anything that is not a string or a number.
11240
+ */
11241
+ function textOfCommand(value) {
11242
+ return typeof value === "string" ? value : typeof value === "number" ? String(value) : "";
11243
+ }
11244
+ /**
11245
+ * What a command publishes.
11246
+ *
11247
+ * @param entity - The entity.
11248
+ * @param capability - Which capability.
11249
+ * @param command - The command, as the contract has it.
11250
+ * @param current - What the entity is now, for a toggle.
11251
+ * @returns The messages, in order.
11252
+ * @throws {ValidationError} When the entity takes no such command, or fills its payloads with a
11253
+ * template the platform cannot render.
11254
+ */
11255
+ function mqttCommandOf(entity, capability, command, current) {
11256
+ const name = textOfCommand(command["command"]);
11257
+ /**
11258
+ * A refusal.
11259
+ *
11260
+ * @param message - Why.
11261
+ * @returns The error.
11262
+ */
11263
+ const refusal = (message) => new ValidationError(message, { details: {
11264
+ entity: entity.key,
11265
+ capability,
11266
+ command: name
11267
+ } });
11268
+ if (textOf(entity.config["command_template"]) !== void 0) throw refusal(`${entity.name} announces a command template, which the platform cannot fill`);
11269
+ /**
11270
+ * A topic the entity is commanded on.
11271
+ *
11272
+ * @param key - Which.
11273
+ * @param what - What it is, for the refusal.
11274
+ * @returns The topic.
11275
+ * @throws {ValidationError} When the entity announces none.
11276
+ */
11277
+ const commandTopic = (key = "command_topic", what = "command topic") => {
11278
+ const topic = topicOf(entity, key);
11279
+ if (topic === void 0) throw refusal(`${entity.name} announces no ${what}`);
11280
+ return topic;
11281
+ };
11282
+ const isOn = current?.on_off?.isOn === true;
11283
+ if (isJsonLight(entity)) {
11284
+ const scale = numberSetting(entity, "brightness_scale", 255);
11285
+ const document = name === "turn_on" ? { state: "ON" } : name === "turn_off" ? { state: "OFF" } : name === "toggle" ? { state: isOn ? "OFF" : "ON" } : name === "set_level" ? {
11286
+ state: "ON",
11287
+ brightness: Math.round(Number(command["level"]) / 100 * scale)
11288
+ } : name === "set_color_temp" ? {
11289
+ state: "ON",
11290
+ color_temp: Number(command["mireds"])
11291
+ } : void 0;
11292
+ if (document === void 0) throw refusal(`${entity.name} takes no ${name}`);
11293
+ return [{
11294
+ topic: commandTopic(),
11295
+ payload: JSON.stringify(document)
11296
+ }];
11297
+ }
11298
+ switch (capability) {
11299
+ case "on_off": {
11300
+ const wantsOn = name === "turn_on" || name === "toggle" && !isOn;
11301
+ return [{
11302
+ topic: commandTopic(),
11303
+ payload: wantsOn ? textSetting(entity, "payload_on", "ON") : textSetting(entity, "payload_off", "OFF")
11304
+ }];
11305
+ }
11306
+ case "level": {
11307
+ const scale = numberSetting(entity, "brightness_scale", 255);
11308
+ return [{
11309
+ topic: commandTopic("brightness_command_topic", "brightness topic"),
11310
+ payload: String(Math.round(Number(command["level"]) / 100 * scale))
11311
+ }];
11312
+ }
11313
+ case "color_temp": return [{
11314
+ topic: commandTopic("color_temp_command_topic", "colour temperature topic"),
11315
+ payload: String(Math.round(Number(command["mireds"])))
11316
+ }];
11317
+ case "cover": {
11318
+ if (name === "set_position") {
11319
+ const open = numberSetting(entity, "position_open", 100);
11320
+ const closed = numberSetting(entity, "position_closed", 0);
11321
+ return [{
11322
+ topic: commandTopic("set_position_topic", "position topic"),
11323
+ payload: String(Math.round(closed + Number(command["position"]) / 100 * (open - closed)))
11324
+ }];
11325
+ }
11326
+ const payload = {
11327
+ open: textSetting(entity, "payload_open", "OPEN"),
11328
+ close: textSetting(entity, "payload_close", "CLOSE"),
11329
+ stop: textSetting(entity, "payload_stop", "STOP")
11330
+ }[name];
11331
+ if (payload === void 0) throw refusal(`${entity.name} takes no ${name}`);
11332
+ return [{
11333
+ topic: commandTopic(),
11334
+ payload
11335
+ }];
11336
+ }
11337
+ case "button": return [{
11338
+ topic: commandTopic(),
11339
+ payload: textSetting(entity, "payload_press", "PRESS")
11340
+ }];
11341
+ case "number": return [{
11342
+ topic: commandTopic(),
11343
+ payload: textOfCommand(command["value"])
11344
+ }];
11345
+ case "select": return [{
11346
+ topic: commandTopic(),
11347
+ payload: textOfCommand(command["option"])
11348
+ }];
11349
+ case "lock": return [{
11350
+ topic: commandTopic(),
11351
+ payload: name === "lock" ? textSetting(entity, "payload_lock", "LOCK") : textSetting(entity, "payload_unlock", "UNLOCK")
11352
+ }];
11353
+ default: throw refusal(`${entity.name} takes no ${capability} command`);
11354
+ }
11355
+ }
11356
+ /**
11357
+ * A device, read from what identification or a claim holds.
11358
+ *
11359
+ * @param value - What it holds.
11360
+ * @returns The device, or undefined when it is not one.
11361
+ */
11362
+ function deviceOf(value) {
11363
+ const parsed = mqttDeviceSnapshotSchema.safeParse(value);
11364
+ return parsed.success ? parsed.data : void 0;
11365
+ }
11366
+ /**
11367
+ * One entity, as the device describes it.
11368
+ *
11369
+ * @param entity - The entity.
11370
+ * @returns Its descriptor.
11371
+ */
11372
+ function entityDescriptorOf(entity) {
11373
+ return {
11374
+ ...mqttShapeOf(entity),
11375
+ objectId: entity.objectId,
11376
+ name: entity.name
11377
+ };
11378
+ }
11379
+ /**
11380
+ * Builds the MQTT driver of a vendor: the platform's own, or one whose `driver.json` says
11381
+ * `"kind": "mqtt"`.
11382
+ *
11383
+ * @param manifest - The driver's.
11384
+ * @param manifest.id - Its kind, `vendor/driver`.
11385
+ * @returns The integration.
11386
+ */
11387
+ function createMqttIntegration(manifest) {
11388
+ /**
11389
+ * The device a claim was made for.
11390
+ *
11391
+ * @param context - The instance's mapping context.
11392
+ * @returns The device.
11393
+ * @throws {ValidationError} When the claim holds no device - which identification never makes.
11394
+ */
11395
+ const claimed = (context) => {
11396
+ const device = deviceOf(context.claim.descriptor);
11397
+ if (device === void 0) throw new ValidationError(`${manifest.id} holds a claim that is not an MQTT device`, { details: { integration: manifest.id } });
11398
+ return device;
11399
+ };
11400
+ return {
11401
+ id: manifest.id,
11402
+ transport: MQTT_HOUSE_TRANSPORT,
11403
+ optionsSchema: jsonObjectSchema,
11404
+ discovery: {},
11405
+ /**
11406
+ * Claims a device the broker hears.
11407
+ *
11408
+ * @param discovered - What the transport handed over.
11409
+ * @returns The claim, or null for anything that is not one.
11410
+ */
11411
+ claim: (discovered) => {
11412
+ const device = deviceOf(discovered.payload);
11413
+ return device === void 0 ? null : {
11414
+ deviceKey: discovered.deviceKey,
11415
+ externalId: device.deviceKey,
11416
+ descriptor: device
11417
+ };
11418
+ },
11419
+ /**
11420
+ * Subscribes to nothing: the broker hands over every topic its devices read.
11421
+ *
11422
+ * @returns Nothing.
11423
+ */
11424
+ subscriptions: () => [],
11425
+ /**
11426
+ * Describes the device and its entities.
11427
+ *
11428
+ * @param claim - The claim.
11429
+ * @returns The device.
11430
+ * @throws {ValidationError} When the claim holds no MQTT device.
11431
+ */
11432
+ describe: (claim) => {
11433
+ const device = deviceOf(claim.descriptor);
11434
+ if (device === void 0) throw new ValidationError(`${manifest.id} cannot describe a claim with no MQTT device`, { details: { integration: manifest.id } });
11435
+ const { identity } = device;
11436
+ const mac = identity.macAddresses.map(normalizeMac).find((each) => each !== null);
11437
+ return {
11438
+ externalId: claim.externalId,
11439
+ name: identity.name.slice(0, 128),
11440
+ ...mac === void 0 ? {} : { mac },
11441
+ ...identity.serialNumber === null ? {} : { serialNumber: identity.serialNumber },
11442
+ ...identity.manufacturer === null ? {} : { manufacturer: identity.manufacturer },
11443
+ ...identity.model === null ? {} : { model: identity.model },
11444
+ ...identity.swVersion === null ? {} : { swVersion: identity.swVersion.slice(0, 64) },
11445
+ ...identity.hwVersion === null ? {} : { hwVersion: identity.hwVersion.slice(0, 64) },
11446
+ ...identity.viaDevice === null ? {} : { viaExternalId: identity.viaDevice },
11447
+ entities: device.entities.map(entityDescriptorOf)
11448
+ };
11449
+ },
11450
+ /**
11451
+ * Turns what the topics say into reports, one per entity a changed topic is read for.
11452
+ *
11453
+ * @param message - What the transport delivered.
11454
+ * @param context - The identifiers the hub assigned, and the last states.
11455
+ * @returns The reports.
11456
+ */
11457
+ toState: (message, context) => {
11458
+ const parsed = inboundSchema.safeParse(message.payload);
11459
+ if (!parsed.success) return [];
11460
+ const { device, texts, changed } = parsed.data;
11461
+ /**
11462
+ * The last text of a topic.
11463
+ *
11464
+ * @param topic - The topic.
11465
+ * @returns It, if the topic carried text.
11466
+ */
11467
+ const textOfTopic = (topic) => texts[topic];
11468
+ return device.entities.flatMap((entity) => {
11469
+ const entityId = context.entities.get(entity.objectId);
11470
+ if (entityId === void 0 || changed !== null && !mqttTopicsOf(entity).some((topic) => changed.includes(topic))) return [];
11471
+ const read = mqttStateOf(entity, textOfTopic, context.lastState(entityId));
11472
+ return read === void 0 ? [] : [{
11473
+ entityId,
11474
+ state: read.state,
11475
+ attributes: {},
11476
+ isAvailable: read.isAvailable
11477
+ }];
11478
+ });
11479
+ },
11480
+ /**
11481
+ * Turns a command into the messages it publishes.
11482
+ *
11483
+ * @param target - The entity, the capability and the command.
11484
+ * @param context - The claim and the last states.
11485
+ * @returns The request.
11486
+ * @throws {ValidationError} When the entity does not take the command.
11487
+ */
11488
+ toCommand: (target, context) => {
11489
+ const entity = claimed(context).entities.find((candidate) => context.entities.get(candidate.objectId) === target.entityId);
11490
+ if (entity === void 0) throw new ValidationError(`${manifest.id} has no entity ${target.entityId}`, { details: {
11491
+ integration: manifest.id,
11492
+ entityId: target.entityId
11493
+ } });
11494
+ const messages = mqttCommandOf(entity, target.capability, target.command, context.lastState(target.entityId));
11495
+ return {
11496
+ deviceKey: context.claim.deviceKey,
11497
+ op: "publish",
11498
+ args: { messages: messages.map(({ topic, payload }) => ({
11499
+ topic,
11500
+ payload
11501
+ })) }
11502
+ };
11503
+ }
11504
+ };
11505
+ }
11506
+ //#endregion
11507
+ //#region ../package-runtime/dist/loader.js
11508
+ /**
11509
+ * Reading integrations off disk: the loader `hub` runs and the integration SDK checks a bundle
11510
+ * with, so that what passes `nebulahome-integration validate` is what `hub` loads.
11511
+ *
11512
+ * A bundle is a vendor directory - `manifest.json`, a logo, optionally a `setup.json` of what
11513
+ * every device of the vendor shares - holding one driver directory per profile or entry point,
11514
+ * each with `driver.json`, its own `setup.json` and the profile or code. It is read in two steps:
11515
+ *
11516
+ * 1. {@link readVendorDirectory} reads and checks every file - the schemas, the ids against the
11517
+ * folders, the runtime range, the logo, the containers, that every module named is there -
11518
+ * and imports nothing. It is all a source tree needs to be checked.
11519
+ * 2. {@link instantiateVendor} imports the code and hands it the {@link BundleSdk}: the vendor's
11520
+ * own transports, stream sources and account, each driver, and the discovery modules. Who
11521
+ * builds the SDK is the caller's - `hub` hands the real one, the SDK's tests a fake.
11522
+ *
11523
+ * **It is also the seam the catalogue arrives through.** `verify` and `verifyVendor` are called
11524
+ * before code is imported, and nothing passes them today. When the catalogue stamps a signature on
11525
+ * an approved code bundle, the verifier that checks it is injected there and nothing else changes.
11526
+ *
11527
+ * One broken driver never stops its siblings, and one broken vendor never stops the others. A
11528
+ * failure is collected and reported so the interface can say which directory and why, because
8700
11529
  * the alternative - refusing to start - means one bad download takes the whole house offline.
8701
11530
  * The same goes one level down for a vendor's `discovery.json`: discovery is a convenience on top
8702
11531
  * of adding a device by address, so a broken one is reported and the vendor loads without it.
@@ -8918,7 +11747,14 @@ async function readDriver(vendor, directory, resolve) {
8918
11747
  profile
8919
11748
  };
8920
11749
  }
8921
- if (manifest.kind === "matter") return identity;
11750
+ if (manifest.kind === "matter" || manifest.kind === "mqtt") return identity;
11751
+ if (manifest.kind === "modbus") {
11752
+ const template = await readBundleFile(modbusTemplateSchema, directory, manifest.template ?? "");
11753
+ return {
11754
+ ...identity,
11755
+ modbusTemplate: withModbusEntityIds(template)
11756
+ };
11757
+ }
8922
11758
  return {
8923
11759
  ...identity,
8924
11760
  entry: await moduleOf(resolve, directory, manifest.entry ?? "", manifest.id)
@@ -9106,6 +11942,14 @@ async function instantiateDriver(driver, sdk, options) {
9106
11942
  ...identity,
9107
11943
  integration: createMatterIntegration(driver.manifest)
9108
11944
  };
11945
+ if (driver.manifest.kind === "mqtt") return {
11946
+ ...identity,
11947
+ integration: createMqttIntegration(driver.manifest)
11948
+ };
11949
+ if (driver.manifest.kind === "modbus") return {
11950
+ ...identity,
11951
+ integration: createModbusIntegration(driver.manifest)
11952
+ };
9109
11953
  const exported = await defaultOf(options.importModule ?? importFile, entry ?? "");
9110
11954
  const integration = typeof exported === "function" ? exported(sdk) : exported;
9111
11955
  if (integration === null || typeof integration !== "object") throw new Error(`${driver.manifest.id} does not default-export an integration`);
@@ -9250,4 +12094,4 @@ async function instantiateVendor(declaration, options) {
9250
12094
  };
9251
12095
  }
9252
12096
  //#endregion
9253
- export { associateModel as a, matchesMatter as c, accountDeclarationSchema as d, defineAccount as f, composeEntityId as g, integrationSetupSchema as h, associateMatter as i, vendorDiscoverySchema as l, vendorManifestSchema as m, readVendorDirectory as n, identifySighting as o, driverManifestSchema as p, require_semver as r, matchesAnnouncement as s, instantiateVendor as t, integrationProfileSchema as u };
12097
+ export { composeEntityId as _, associateModel as a, matchesBroker as c, accountDeclarationSchema as d, defineAccount as f, integrationSetupSchema as g, modbusTemplateSchema as h, associateBroker 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 };