@camstack/addon-export-google 0.1.121 → 0.1.122

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.
@@ -5917,7 +5917,7 @@ var ZodIssueCode = {
5917
5917
  var ZodFirstPartyTypeKind;
5918
5918
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5919
5919
  //#endregion
5920
- //#region ../types/dist/sleep-B-vp7x15.mjs
5920
+ //#region ../types/dist/sleep-Bei295Bz.mjs
5921
5921
  /**
5922
5922
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5923
5923
  * window to float samples (D455).
@@ -6433,6 +6433,53 @@ function emitReadiness(bus, params) {
6433
6433
  ts
6434
6434
  }));
6435
6435
  }
6436
+ /** Why a catalogue entry is not a runnable body of its declared kind. */
6437
+ var AddonMigrationDefinitionError = class extends Error {
6438
+ id;
6439
+ constructor(id, message) {
6440
+ super(`${id}: ${message}`);
6441
+ this.id = id;
6442
+ this.name = "AddonMigrationDefinitionError";
6443
+ }
6444
+ };
6445
+ /**
6446
+ * Bind a catalogue to the addon's ports. Throws {@link AddonMigrationDefinitionError} when
6447
+ * an entry's `bodyKind` does not match the body it carries, or is `sql` (a hub-only
6448
+ * body). A throwing body never escapes `execute`: it is reported as a failed result.
6449
+ */
6450
+ function defineAddonMigrations(catalogue, ports) {
6451
+ return catalogue.map((entry) => {
6452
+ const { meta } = entry;
6453
+ if ("plan" in entry) {
6454
+ if (meta.bodyKind !== "plan") throw new AddonMigrationDefinitionError(meta.id, `carries a plan body but declares "${meta.bodyKind}"`);
6455
+ return {
6456
+ meta,
6457
+ execute: () => guarded(async () => ({
6458
+ kind: "plan",
6459
+ plan: await entry.plan(ports)
6460
+ }))
6461
+ };
6462
+ }
6463
+ if (meta.bodyKind !== "procedure") throw new AddonMigrationDefinitionError(meta.id, `carries a procedure body but declares "${meta.bodyKind}"`);
6464
+ return {
6465
+ meta,
6466
+ execute: () => guarded(async () => ({
6467
+ kind: "procedure",
6468
+ result: await entry.procedure(ports)
6469
+ }))
6470
+ };
6471
+ });
6472
+ }
6473
+ async function guarded(work) {
6474
+ try {
6475
+ return await work();
6476
+ } catch (err) {
6477
+ return {
6478
+ kind: "failed",
6479
+ error: errMsg$1(err)
6480
+ };
6481
+ }
6482
+ }
6436
6483
  var NOT_RUN = {
6437
6484
  declared: false,
6438
6485
  snapshot: null,
@@ -9273,28 +9320,6 @@ var PipelineRunResultBridge = custom();
9273
9320
  var StaticDirOutputSchema = object({ staticDir: string() });
9274
9321
  var VersionOutputSchema = object({ version: string() });
9275
9322
  method(_void(), StaticDirOutputSchema, { auth: "admin" }), method(_void(), VersionOutputSchema, { auth: "admin" });
9276
- /**
9277
- * Identity — preserves literal types for downstream inference.
9278
- *
9279
- * The constraint is `Record<string, unknown>` (not `CustomActionsSpec`) so
9280
- * TypeScript does not widen each entry's literal `kind`/`auth` fields to
9281
- * the broader unions declared on `CustomActionSpec`'s default generics.
9282
- * Shape validity is enforced separately by the `customAction(...)` helper
9283
- * whose return type is already a `CustomActionSpec<...>`.
9284
- */
9285
- function defineCustomActions(spec) {
9286
- return spec;
9287
- }
9288
- function customAction(input, output, options) {
9289
- return {
9290
- input,
9291
- output,
9292
- kind: options?.kind ?? "query",
9293
- auth: options?.auth ?? "protected",
9294
- scope: options?.scope ?? { kind: "system" },
9295
- ...options?.caller ? { caller: "required" } : {}
9296
- };
9297
- }
9298
9323
  Object.freeze({ "doorbell": "lastPressedAt" });
9299
9324
  /** Every capability name, so addon code can check a name without the schema graph. */
9300
9325
  var CAP_NAMES = Object.freeze([
@@ -13743,6 +13768,16 @@ var MigrationPlanSchema = object({ edits: array(discriminatedUnion("op", [
13743
13768
  precondition: PreconditionSchema
13744
13769
  })
13745
13770
  ])) });
13771
+ /** `JSON.stringify` with object keys sorted, so equal values spell the same. */
13772
+ function canonicalJson(value) {
13773
+ if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(",")}]`;
13774
+ if (typeof value === "object" && value !== null) return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(",")}}`;
13775
+ return JSON.stringify(value) ?? "null";
13776
+ }
13777
+ /** The precondition string for a value a plan read (`null` when it read nothing). */
13778
+ function preconditionOf(value) {
13779
+ return canonicalJson(value ?? null);
13780
+ }
13746
13781
  /**
13747
13782
  * What a `procedure` body reports. `already-done` means the rerun observed the
13748
13783
  * work finished (a crash between the work and the ledger row, or a manual fix)
@@ -15691,8 +15726,18 @@ var LogChannelDescriptorSchema = object({
15691
15726
  * the operator narrows to one camera, sees nothing, and concludes the code
15692
15727
  * path was never taken.
15693
15728
  */
15694
- perDevice: boolean()
15695
- });
15729
+ perDevice: boolean(),
15730
+ /**
15731
+ * What the channel is FOR, so the UI can list the channels an addon offers.
15732
+ *
15733
+ * - `diagnostic` (the default): a per-component diagnostic armed from the
15734
+ * Levels page, emitted at its declared level.
15735
+ * - `debug`: a `debug.<channel>` dump watched live for a short window
15736
+ * (`ctx.debug`). Always per-device, and its lines are denied by the log
15737
+ * ring unless somebody is watching that device.
15738
+ */
15739
+ kind: _enum(["diagnostic", "debug"]).default("diagnostic")
15740
+ }).refine((d) => d.kind !== "debug" || d.name.startsWith("debug.") && d.perDevice, { message: "a debug channel is named debug.<channel> and is per-device" });
15696
15741
  /**
15697
15742
  * An armed window over one channel, as the document hands it to a mirror.
15698
15743
  *
@@ -49521,6 +49566,45 @@ method(_void(), _void(), { kind: "mutation" }), method(_void(), _void(), { kind:
49521
49566
  auth: "admin"
49522
49567
  });
49523
49568
  /**
49569
+ * What the passive listener of `local-network` saw on the wire, before any
49570
+ * provider classified it. Device-manager turns an observation into the hits
49571
+ * of the providers whose declared discovery modes it matches.
49572
+ */
49573
+ var DiscoveryObservationSchema = discriminatedUnion("kind", [object({
49574
+ kind: literal("mdns"),
49575
+ /** Normalised DNS-SD service type, e.g. `_esphomelib._tcp`. */
49576
+ serviceType: string(),
49577
+ instance: string(),
49578
+ host: string(),
49579
+ /** The A record address when the announcement carried one. */
49580
+ address: string().nullable(),
49581
+ port: number().int(),
49582
+ txt: record(string(), string())
49583
+ }), object({
49584
+ kind: literal("ssdp"),
49585
+ /** Sender address of the datagram. */
49586
+ host: string(),
49587
+ port: number().int(),
49588
+ /** `NT` of a NOTIFY, `ST` of a search response. */
49589
+ target: string(),
49590
+ headers: record(string(), string())
49591
+ })]);
49592
+ object({
49593
+ addonId: string(),
49594
+ candidate: DiscoveryCandidateSchema,
49595
+ firstSeenAt: number(),
49596
+ lastSeenAt: number(),
49597
+ dismissed: boolean()
49598
+ });
49599
+ var DiscoveryProposalSchema = object({
49600
+ id: string(),
49601
+ addonId: string(),
49602
+ candidate: DiscoveryCandidateSchema,
49603
+ firstSeenAt: number(),
49604
+ lastSeenAt: number(),
49605
+ dismissed: boolean()
49606
+ });
49607
+ /**
49524
49608
  * Device Manager capability — hub-side singleton that unifies device persistence,
49525
49609
  * live registry access, and all management operations into a single tRPC surface.
49526
49610
  *
@@ -50249,6 +50333,19 @@ method(object({
50249
50333
  }), object({ candidates: array(DiscoveryCandidateSchema).readonly() }), {
50250
50334
  kind: "mutation",
50251
50335
  auth: "admin"
50336
+ }), method(object({}), object({ proposals: array(DiscoveryProposalSchema).readonly() }), { auth: "admin" }), method(object({ id: string() }), object({ dismissed: boolean() }), {
50337
+ kind: "mutation",
50338
+ auth: "admin"
50339
+ }), method(object({ observations: array(DiscoveryObservationSchema).max(512) }), object({ proposed: number().int() }), {
50340
+ kind: "mutation",
50341
+ auth: "admin"
50342
+ }), method(object({}), object({
50343
+ providers: number().int(),
50344
+ proposed: number().int()
50345
+ }), {
50346
+ kind: "mutation",
50347
+ auth: "admin",
50348
+ timeoutMs: 12e4
50252
50349
  }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
50253
50350
  deviceId: number(),
50254
50351
  key: string(),
@@ -72058,6 +72155,40 @@ var LoggingSettingsStateSchema = object({
72058
72155
  opsLogRetentionDays: number().int().min(0),
72059
72156
  persisted: boolean()
72060
72157
  });
72158
+ /**
72159
+ * Debug WATCH — a short, per-device window over `debug.<channel>` lines.
72160
+ *
72161
+ * `start` opens (or re-arms) a 10 minute window; `rearm` extends a LIVE one
72162
+ * and never revives a lapsed one; `stop` closes it; `list` only reads. No
72163
+ * chain of re-arms outlives 60 minutes from the first start. The hub holds the
72164
+ * watches in memory and pushes the interest to every node, so a watch lapses
72165
+ * by itself and survives nothing — a restart is a stop.
72166
+ */
72167
+ var DebugWatchInputSchema = object({
72168
+ action: _enum([
72169
+ "list",
72170
+ "start",
72171
+ "rearm",
72172
+ "stop"
72173
+ ]),
72174
+ /** Full channel names, `debug.<channel>`, each declared with `kind: 'debug'`. */
72175
+ channels: array(string().min(1)).readonly().default([]),
72176
+ /** Numeric device ids. Required (non-empty) for `start`. */
72177
+ deviceIds: array(number().int()).readonly().default([])
72178
+ });
72179
+ var DebugWatchStateSchema = object({
72180
+ channel: string(),
72181
+ deviceIds: array(number().int()).readonly(),
72182
+ startedAtMs: number(),
72183
+ untilMs: number(),
72184
+ capAtMs: number()
72185
+ });
72186
+ var DebugWatchResultSchema = object({
72187
+ nowMs: number(),
72188
+ watches: array(DebugWatchStateSchema).readonly(),
72189
+ /** Channels a `rearm` found already lapsed: nothing was revived. */
72190
+ lapsed: array(string()).readonly()
72191
+ });
72061
72192
  method(_void(), SystemInfoSchema), method(_void(), HealthStatusSchema), method(_void(), FeatureManifestSchema), method(_void(), array(NetworkAddressSchema).readonly()), method(_void(), unknown().nullable(), { auth: "admin" }), method(record(string(), unknown()), _null(), {
72062
72193
  kind: "mutation",
72063
72194
  auth: "admin"
@@ -72073,6 +72204,9 @@ method(_void(), SystemInfoSchema), method(_void(), HealthStatusSchema), method(_
72073
72204
  }), method(_void(), RequestCensusStatusSchema, { auth: "admin" }), method(_void(), array(ReportedLoadContributionSchema).readonly(), { auth: "admin" }), method(_void(), array(ReportedFailureContributionSchema).readonly(), { auth: "admin" }), method(GetLoggingSettingsInputSchema, LoggingSettingsStateSchema, { auth: "admin" }), method(SetLoggingSettingsInputSchema, LoggingSettingsStateSchema, {
72074
72205
  kind: "mutation",
72075
72206
  auth: "admin"
72207
+ }), method(DebugWatchInputSchema, DebugWatchResultSchema, {
72208
+ kind: "mutation",
72209
+ auth: "admin"
72076
72210
  });
72077
72211
  object({
72078
72212
  /** True when the device's tamper switch / case-open contact is
@@ -76946,6 +77080,13 @@ Object.freeze({
76946
77080
  access: "view",
76947
77081
  role: "admin"
76948
77082
  },
77083
+ "deviceManager.dismissDiscoveryProposal": {
77084
+ capName: "device-manager",
77085
+ capScope: "system",
77086
+ addonId: null,
77087
+ access: "create",
77088
+ role: "admin"
77089
+ },
76949
77090
  "deviceManager.enable": {
76950
77091
  capName: "device-manager",
76951
77092
  capScope: "system",
@@ -77128,6 +77269,13 @@ Object.freeze({
77128
77269
  access: "view",
77129
77270
  role: "viewer"
77130
77271
  },
77272
+ "deviceManager.listDiscoveryProposals": {
77273
+ capName: "device-manager",
77274
+ capScope: "system",
77275
+ addonId: null,
77276
+ access: "view",
77277
+ role: "admin"
77278
+ },
77131
77279
  "deviceManager.listLocationDescriptions": {
77132
77280
  capName: "device-manager",
77133
77281
  capScope: "system",
@@ -77282,6 +77430,13 @@ Object.freeze({
77282
77430
  access: "create",
77283
77431
  role: "admin"
77284
77432
  },
77433
+ "deviceManager.reportDiscoveryObservations": {
77434
+ capName: "device-manager",
77435
+ capScope: "system",
77436
+ addonId: null,
77437
+ access: "create",
77438
+ role: "admin"
77439
+ },
77285
77440
  "deviceManager.runDeviceAction": {
77286
77441
  capName: "device-manager",
77287
77442
  capScope: "system",
@@ -77289,6 +77444,13 @@ Object.freeze({
77289
77444
  access: "create",
77290
77445
  role: "admin"
77291
77446
  },
77447
+ "deviceManager.runDiscoverySweep": {
77448
+ capName: "device-manager",
77449
+ capScope: "system",
77450
+ addonId: null,
77451
+ access: "create",
77452
+ role: "admin"
77453
+ },
77292
77454
  "deviceManager.setChildLayout": {
77293
77455
  capName: "device-manager",
77294
77456
  capScope: "system",
@@ -83876,6 +84038,13 @@ Object.freeze({
83876
84038
  access: "create",
83877
84039
  role: "viewer"
83878
84040
  },
84041
+ "system.debugWatch": {
84042
+ capName: "system",
84043
+ capScope: "system",
84044
+ addonId: null,
84045
+ access: "create",
84046
+ role: "admin"
84047
+ },
83879
84048
  "system.detectSiteLocation": {
83880
84049
  capName: "system",
83881
84050
  capScope: "system",
@@ -87819,6 +87988,11 @@ Object.freeze({
87819
87988
  form: "single",
87820
87989
  optional: false
87821
87990
  }],
87991
+ "system.debugWatch": [{
87992
+ name: "deviceIds",
87993
+ form: "array",
87994
+ optional: true
87995
+ }],
87822
87996
  "tamper.getStatus": [{
87823
87997
  name: "deviceId",
87824
87998
  form: "single",
@@ -89711,38 +89885,6 @@ var ActionSceneExports = class {
89711
89885
  }
89712
89886
  };
89713
89887
  //#endregion
89714
- //#region src/custom-actions.ts
89715
- /**
89716
- * Google Home Export — customActions catalog.
89717
- *
89718
- * One entry. The settings form's `addon-action-button` dispatches through the
89719
- * generic `api.addons.custom.mutate({ addonId, action, input })` channel and
89720
- * shows the result under the button, so a button here costs no capability, no
89721
- * codegen and no framework publish train — the catalog travels inside this
89722
- * addon's own bundle. Admin-only: it writes this addon's settings.
89723
- */
89724
- var exportGoogleActions = defineCustomActions({
89725
- /**
89726
- * Re-scan the connected `network-access` providers and refresh the address
89727
- * shown under the field.
89728
- *
89729
- * Deliberately NOT the same contract as `export-alexa`'s action of the same
89730
- * shape: that one replaces a manual override when it is no longer detected,
89731
- * because Alexa ROUTES on the value. Nothing routes on this one — it is what
89732
- * the operator already pasted into Google's console — so this only fills the
89733
- * field when it is empty. `filled` says whether it did.
89734
- */
89735
- detectPublicHubUrl: customAction(object({}).optional(), object({
89736
- publicHubUrl: string(),
89737
- detectedPublicHubUrl: string(),
89738
- filled: boolean(),
89739
- /** One sentence saying what happened, for the button. */
89740
- summary: string()
89741
- }), {
89742
- kind: "mutation",
89743
- auth: "admin"
89744
- }) });
89745
- //#endregion
89746
89888
  //#region src/google-home/trait-catalog.ts
89747
89889
  /**
89748
89890
  * The trait catalog — one ROW per camstack capability, and that row is the
@@ -90539,217 +90681,93 @@ function buildGoogleOauthIntegration() {
90539
90681
  };
90540
90682
  }
90541
90683
  //#endregion
90542
- //#region src/public-hub-url.ts
90543
- /**
90544
- * The hub's public HTTPS origin — detected, never invented.
90545
- *
90546
- * `publicHubUrl` is the single operator-facing value in this addon, and the
90547
- * three URLs pasted into the Google Home Developer Console (fulfillment,
90548
- * authorization, token) are all rendered from it. Nothing ROUTES on it: Google
90549
- * calls the fulfillment URL it was configured with. A wrong value therefore
90550
- * fails at paste time, in the console, hours before anything here notices —
90551
- * which is exactly why the field has to say where its content came from.
90552
- *
90553
- * ## Where the URL comes from
90554
- *
90555
- * The `network-access` capability, same source `addon-export-alexa` uses. It is
90556
- * a codegen'd collection cap with `scope: 'system'`, so it is reachable
90557
- * cross-process through `ctx.api` — unlike the `addons` core router, which a
90558
- * forked addon calling `ctx.api.addons.*` would wait on forever.
90559
- *
90560
- * **Not** the hub's own address from `local-network` (`getAddresses().roles`). That
90561
- * answers a different question — which address an agent or a browser on the
90562
- * LAN reaches — and it is routinely a LAN address; the backend's
90563
- * `publicHubUrl()` fallback is localhost in dev. Google calls from its own
90564
- * cloud, so a LAN answer here is worse than no answer — it produces three
90565
- * console URLs that look complete and can never be reached.
90566
- *
90567
- * ## Why this is a second copy of Alexa's mechanism
90568
- *
90569
- * Alexa's lives in `packages/addon-export-alexa/src/export-alexa.addon.ts` as
90570
- * private methods, and addons never import each other. The only shared home
90571
- * would be `@camstack/types` or `@camstack/server/system` — both stay host-resolved in
90572
- * an addon bundle (`tools/build/vite-lib.preset.ts`), so putting it there would
90573
- * put this addon on the framework publish train and destroy the one property
90574
- * that makes it attractive: `camstack deploy packages/addon-export-google` and
90575
- * nothing else. The SOURCE and the POLICY are Alexa's; two behaviours diverge
90576
- * on purpose and both are named below.
90577
- *
90578
- * ## Two deliberate divergences from Alexa
90579
- *
90580
- * 1. **Refresh never clobbers.** Alexa's `redetectPublicHubUrl` replaces a
90581
- * manual override whenever it is not among the detected endpoints — sound
90582
- * there, because the URL is baked into every Alexa-bound JWT as a routing
90583
- * claim and a stale one breaks routing. Here the value is what the operator
90584
- * already pasted into Google's console; silently rewriting it would leave
90585
- * the console and the hub disagreeing with no visible cause. Detection fills
90586
- * an EMPTY field and does nothing else.
90587
- * 2. **A non-routable origin is dropped.** Alexa forwards whatever the cap
90588
- * reports. See {@link isPubliclyRoutableOrigin}.
90589
- */
90590
- /** Trailing slashes off, surrounding space off. Nothing else is rewritten. */
90591
- var normalisePublicHubUrl = (raw) => raw.trim().replace(/\/+$/, "");
90592
- var LOOPBACK_HOSTS = [
90593
- "localhost",
90594
- "127.0.0.1",
90595
- "::1",
90596
- "[::1]",
90597
- "0.0.0.0"
90598
- ];
90599
- /**
90600
- * Whether Google's cloud could plausibly reach this origin.
90601
- *
90602
- * The `network-access` providers this hub ships (Cloudflare Tunnel, Tailscale
90603
- * Funnel) publish public FQDNs, but the cap does not promise it: a provider is
90604
- * free to report an HTTPS ingress on a private address. Defaulting the field to
90605
- * one of those would hand the operator three console URLs that look finished
90606
- * and can never answer — strictly worse than an empty field, because an empty
90607
- * field is visibly unfinished.
90608
- *
90609
- * Conservative on purpose: only loopback, RFC1918, link-local, `.local` and
90610
- * dotless hostnames are refused. A public tunnel hostname always has a dot.
90611
- */
90612
- var isPubliclyRoutableOrigin = (origin) => {
90613
- let host;
90614
- try {
90615
- host = new URL(origin).hostname.toLowerCase();
90616
- } catch {
90617
- return false;
90618
- }
90619
- if (host.length === 0) return false;
90620
- if (LOOPBACK_HOSTS.includes(host)) return false;
90621
- if (host.startsWith("127.") || host.startsWith("169.254.")) return false;
90622
- if (host.startsWith("10.") || host.startsWith("192.168.")) return false;
90623
- if (/^172\.(1[6-9]|2\d|3[01])\./.test(host)) return false;
90624
- if (host.endsWith(".local") || host.endsWith(".internal") || host.endsWith(".lan")) return false;
90625
- if (!host.includes(".")) return false;
90626
- return true;
90627
- };
90628
- /**
90629
- * Every publicly routable HTTPS origin the `network-access` cap reports, in the
90630
- * cap's own order, deduped. Empty when there is none — the caller leaves the
90631
- * field alone rather than inventing a value.
90632
- */
90633
- var detectPublicHubOrigins = async (deps) => {
90634
- const fromList = await originsFromListEndpoints(deps);
90635
- if (fromList.length > 0) return fromList;
90636
- const fromStatus = await originFromGetStatus(deps);
90637
- if (fromStatus.length > 0) return [fromStatus];
90638
- deps.logger.warn("export-google: no connected HTTPS external address — the public hub URL cannot be derived, so the Google console URLs stay unrendered. Set up remote access (Cloudflare Tunnel, Tailscale Funnel, …) and press \"Detect external address\", or type the URL on the settings form.");
90639
- return [];
90640
- };
90641
- var usableOrigins = (candidates, logger) => {
90642
- const out = /* @__PURE__ */ new Set();
90643
- for (const candidate of candidates) {
90644
- if (candidate.protocol !== "https" || candidate.url.length === 0) continue;
90645
- const origin = normalisePublicHubUrl(candidate.url);
90646
- if (!isPubliclyRoutableOrigin(origin)) {
90647
- logger.info("export-google: ignored an external address that is not reachable from the internet — Google calls the fulfillment URL from its own cloud", { meta: { origin } });
90648
- continue;
90649
- }
90650
- out.add(origin);
90651
- }
90652
- return [...out];
90653
- };
90654
- var originsFromListEndpoints = async (deps) => {
90655
- try {
90656
- return usableOrigins(await deps.network.listEndpoints(), deps.logger);
90657
- } catch (err) {
90658
- deps.logger.debug("export-google: networkAccess.listEndpoints failed", { meta: { error: errMsg$1(err) } });
90659
- return [];
90660
- }
90661
- };
90662
- var originFromGetStatus = async (deps) => {
90663
- try {
90664
- const status = await deps.network.getStatus();
90665
- if (status === null || !status.connected || status.endpoint === null) return "";
90666
- return usableOrigins([status.endpoint], deps.logger)[0] ?? "";
90667
- } catch (err) {
90668
- deps.logger.debug("export-google: networkAccess.getStatus failed", { meta: { error: errMsg$1(err) } });
90669
- return "";
90670
- }
90684
+ //#region src/migrations/drop-public-hub-url.ts
90685
+ /**
90686
+ * The hub's public URL is no longer a setting of this addon (D986 §5): Google reads the
90687
+ * `publicEndpoint` role of the local-network palette on every use. The two keys older
90688
+ * versions persisted are deleted. Every other key is left exactly as stored.
90689
+ *
90690
+ * Idempotent: a store without either key yields an empty plan, which writes nothing.
90691
+ */
90692
+ /** The settings scope of this addon (`<addonId>:addon-settings`). */
90693
+ var GOOGLE_SETTINGS_SCOPE = "export-google:addon-settings";
90694
+ var RETIRED_PUBLIC_URL_KEYS = ["publicHubUrl", "detectedPublicHubUrl"];
90695
+ async function planDropPublicHubUrl(ports) {
90696
+ const stored = await ports.readStored();
90697
+ const present = RETIRED_PUBLIC_URL_KEYS.filter((key) => key in stored);
90698
+ if (present.length === 0) return { edits: [] };
90699
+ return { edits: [{
90700
+ op: "deleteKeys",
90701
+ scope: GOOGLE_SETTINGS_SCOPE,
90702
+ keys: [...present],
90703
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [key, stored[key]])))
90704
+ }] };
90705
+ }
90706
+ //#endregion
90707
+ //#region src/migrations/index.ts
90708
+ /** The `export-google` catalogue (D987): offered to the engine when the addon initialises. */
90709
+ var ADDON_MIGRATIONS = [{
90710
+ meta: {
90711
+ id: "export-google/2026-11-02-drop-public-hub-url",
90712
+ owner: "export-google",
90713
+ level: "addon-state",
90714
+ seq: 1,
90715
+ dependsOn: [],
90716
+ store: "settings",
90717
+ scope: "cluster",
90718
+ onFailure: "tolerate",
90719
+ bodyKind: "plan",
90720
+ description: "Delete the retired publicHubUrl and detectedPublicHubUrl settings; the public URL is the publicEndpoint role",
90721
+ fixtureMark: "the exposed device list the migration does not know"
90722
+ },
90723
+ plan: planDropPublicHubUrl
90724
+ }];
90725
+ //#endregion
90726
+ //#region src/public-endpoint.ts
90727
+ /** The typed refusal when the role resolves to nothing. */
90728
+ var NO_PUBLIC_ENDPOINT_REASON = {
90729
+ code: "no-public-endpoint",
90730
+ message: "The hub has no public endpoint. Set up remote access (a tunnel) and flag an address as \"Public endpoint\" on the Network page; Google calls this hub from its own cloud."
90671
90731
  };
90672
- /**
90673
- * Apply the default-not-override policy.
90674
- *
90675
- * The operator's value is never in the returned patch. Detection's own answer
90676
- * always is, because the settings panel needs it to say "you set this one, and
90677
- * a different one is detected".
90678
- */
90679
- var resolvePublicHubUrl = (current, detected) => {
90680
- const detectedPublicHubUrl = detected[0] ?? "";
90681
- if (current.length > 0) return {
90682
- patch: { detectedPublicHubUrl },
90683
- publicHubUrl: current,
90684
- detectedPublicHubUrl,
90685
- defaulted: false
90686
- };
90687
- if (detectedPublicHubUrl.length === 0) return {
90688
- patch: { detectedPublicHubUrl },
90689
- publicHubUrl: "",
90690
- detectedPublicHubUrl,
90691
- defaulted: false
90732
+ /** Trailing slashes off, surrounding space off. Nothing else is rewritten. */
90733
+ var normaliseOrigin = (raw) => raw.trim().replace(/\/+$/, "");
90734
+ var resolvePublicEndpoint = (book) => {
90735
+ const resolved = book.roles.publicEndpoint.resolved;
90736
+ const origin = resolved === null ? "" : normaliseOrigin(resolved);
90737
+ if (origin.length === 0) return {
90738
+ ok: false,
90739
+ reason: NO_PUBLIC_ENDPOINT_REASON
90692
90740
  };
90693
90741
  return {
90694
- patch: {
90695
- publicHubUrl: detectedPublicHubUrl,
90696
- detectedPublicHubUrl
90697
- },
90698
- publicHubUrl: detectedPublicHubUrl,
90699
- detectedPublicHubUrl,
90700
- defaulted: true
90742
+ ok: true,
90743
+ origin
90701
90744
  };
90702
90745
  };
90703
- /** Which of the two authored the value currently in the field. */
90704
- var publicHubUrlSource = (state) => {
90705
- if (state.publicHubUrl.length === 0) return "unset";
90706
- if (state.detectedPublicHubUrl.length > 0 && state.publicHubUrl === state.detectedPublicHubUrl) return "derived";
90707
- return "operator-set";
90708
- };
90709
- /**
90710
- * The line under the field. A URL that appeared by itself with no provenance is
90711
- * worse than a blank field: the operator cannot tell whether it is right.
90712
- */
90713
- var buildPublicHubUrlNotice = (state) => {
90714
- switch (publicHubUrlSource(state)) {
90715
- case "derived": return {
90716
- variant: "info",
90717
- content: `Derived from remote access — ${state.publicHubUrl} is the first HTTPS address the network-access capability reports. Edit the field to override it; nothing here ever overwrites a value you set.`
90718
- };
90719
- case "operator-set": return {
90720
- variant: "info",
90721
- content: state.detectedPublicHubUrl.length > 0 ? `Set by you — ${state.publicHubUrl}. The address currently detected from remote access is ${state.detectedPublicHubUrl}; paste it in yourself if you want to switch, detection will not do it for you.` : `Set by you — ${state.publicHubUrl}. No external HTTPS address is detected right now, so nothing is corroborating it.`
90722
- };
90723
- case "unset": return state.detectedPublicHubUrl.length > 0 ? {
90724
- variant: "info",
90725
- content: `Detected external address: ${state.detectedPublicHubUrl}. Press "Detect external address" to fill the field with it.`
90726
- } : {
90727
- variant: "warning",
90728
- content: "No public HTTPS address detected — no network-access provider on this hub reports a connected HTTPS endpoint, so there is nothing to derive from. Set up remote access (Cloudflare Tunnel, Tailscale Funnel, …) and press \"Detect external address\", or type the URL yourself. An address on your own network will not do: Google calls this URL from its own cloud."
90729
- };
90730
- }
90731
- };
90732
90746
  /**
90733
90747
  * The `device-export` setup block: the three console URLs plus the
90734
- * linked-account count. All three come off the SAME origin, so they can never
90735
- * disagree with each other.
90748
+ * linked-account count, all off the SAME origin so they cannot disagree.
90749
+ * A read that fails is the same refusal as a role that resolves to nothing.
90736
90750
  */
90737
- var buildConsoleSetup = (input) => {
90738
- const origin = normalisePublicHubUrl(input.publicHubUrl);
90751
+ var buildConsoleSetupFromRole = async (input) => {
90739
90752
  const linked = String(input.linkedAccounts);
90740
- if (origin.length === 0) return {
90741
- note: ["Set the public hub URL on the settings form first — every URL Google needs is derived from it.", buildPublicHubUrlNotice(input).content].join("\n"),
90753
+ const result = await input.read().then(resolvePublicEndpoint).catch(() => ({
90754
+ ok: false,
90755
+ reason: NO_PUBLIC_ENDPOINT_REASON
90756
+ }));
90757
+ if (!result.ok) return {
90758
+ note: `Refused (${result.reason.code}): ${result.reason.message}`,
90742
90759
  fields: [{
90743
90760
  label: "Linked Google accounts",
90744
90761
  value: linked
90745
90762
  }]
90746
90763
  };
90764
+ const origin = result.origin;
90747
90765
  return {
90748
90766
  note: [
90749
90767
  "In the Google Home Developer Console create a cloud-to-cloud integration, then paste these three URLs.",
90750
90768
  "The integration stays in test mode: publishing requires Google certification, which a private hub cannot obtain.",
90751
90769
  "This hub pushes nothing to Google — state is read by polling, so a change made outside the Home app appears on the next query, not instantly.",
90752
- buildPublicHubUrlNotice(input).content
90770
+ `The URLs follow the "Public endpoint" role on the Network page (${origin}).`
90753
90771
  ].join("\n"),
90754
90772
  fields: [
90755
90773
  {
@@ -90771,37 +90789,9 @@ var buildConsoleSetup = (input) => {
90771
90789
  ]
90772
90790
  };
90773
90791
  };
90774
- /**
90775
- * Detect, apply the policy, persist, and say out loud what happened.
90776
- *
90777
- * Every branch here logs: a fill names the URL it picked and the source it came
90778
- * from, and a miss that leaves the field empty says so rather than passing for
90779
- * "never ran".
90780
- */
90781
- var refreshPublicHubUrl = async (deps) => {
90782
- const detected = await deps.detect();
90783
- const resolution = resolvePublicHubUrl(deps.current().publicHubUrl, detected);
90784
- await deps.persist(resolution.patch);
90785
- if (resolution.defaulted) deps.logger.info("export-google: defaulted public hub URL to the detected external address", { meta: {
90786
- publicHubUrl: resolution.publicHubUrl,
90787
- source: "network-access"
90788
- } });
90789
- else if (resolution.publicHubUrl.length === 0) deps.logger.warn("export-google: public hub URL still unset after detection — the Google console URLs cannot be rendered until one is available", { meta: { detectedCount: detected.length } });
90790
- return resolution;
90791
- };
90792
- /** What "Detect external address" did, in one sentence for the button. */
90793
- function describeDetectResult(result) {
90794
- const { publicHubUrl, detectedPublicHubUrl, filled } = result;
90795
- if (filled) return `Filled in ${publicHubUrl}.`;
90796
- if (detectedPublicHubUrl.length === 0) return publicHubUrl.length > 0 ? `No public HTTPS address detected; your value ${publicHubUrl} was kept.` : "No public HTTPS address detected. Set up remote access first.";
90797
- if (detectedPublicHubUrl === publicHubUrl) return `Detected ${publicHubUrl}, already in use.`;
90798
- return `Detected ${detectedPublicHubUrl}; your value ${publicHubUrl} was kept.`;
90799
- }
90800
90792
  //#endregion
90801
90793
  //#region src/types.ts
90802
90794
  var DEFAULT_SETTINGS = {
90803
- publicHubUrl: "",
90804
- detectedPublicHubUrl: "",
90805
90795
  exposed: [],
90806
90796
  exposedActions: [],
90807
90797
  linkedAccounts: []
@@ -90856,9 +90846,7 @@ var ExportGoogleAddon = class extends BaseAddon {
90856
90846
  logger: this.ctx.logger
90857
90847
  });
90858
90848
  this.gateway = gateway;
90859
- this.detectPublicHubUrl().catch((err) => {
90860
- this.ctx.logger.warn("export-google: public hub URL auto-detect failed", { meta: { error: errMsg$1(err) } });
90861
- });
90849
+ await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, { readStored: async () => this.resolveGlobalStore() }));
90862
90850
  const actionScenes = new ActionSceneExports({
90863
90851
  api: this.ctx.api,
90864
90852
  logger: this.ctx.logger,
@@ -90874,7 +90862,7 @@ var ExportGoogleAddon = class extends BaseAddon {
90874
90862
  getStatus: async () => ({
90875
90863
  linkState: this.config.linkedAccounts.length > 0 ? "linked" : "unlinked",
90876
90864
  exposedDeviceCount: this.config.exposed.length,
90877
- setup: this.buildSetupBlock()
90865
+ setup: await this.buildSetupBlock()
90878
90866
  }),
90879
90867
  listSupportedDeviceKinds: async () => [...SUPPORTED_DEVICE_KINDS],
90880
90868
  listExposedDevices: async () => this.config.exposed.map((entry) => ({ deviceId: String(entry.deviceId) })),
@@ -90930,97 +90918,25 @@ var ExportGoogleAddon = class extends BaseAddon {
90930
90918
  }
90931
90919
  }));
90932
90920
  const oauthIntegrationProvider = { getDescriptor: async () => buildGoogleOauthIntegration() };
90933
- const offTunnelStarted = this.ctx.eventBus.subscribe({ category: EventCategory.NetworkTunnelStarted }, () => {
90934
- this.detectPublicHubUrl().catch((err) => {
90935
- this.ctx.logger.warn("export-google: public hub URL detect after tunnel connect failed", { meta: { error: errMsg$1(err) } });
90936
- });
90937
- });
90938
- this.ctx.addDisposer(async () => offTunnelStarted());
90939
90921
  this.ctx.logger.info("export-google: initialized", { meta: {
90940
90922
  exposedCount: this.config.exposed.length,
90941
90923
  linkedAccounts: this.config.linkedAccounts.length,
90942
- publicHubUrlSet: this.config.publicHubUrl.length > 0,
90943
90924
  willReportState: false
90944
90925
  } });
90945
- return {
90946
- providers: [
90947
- {
90948
- capability: deviceExportCapability,
90949
- provider: deviceExportProvider
90950
- },
90951
- {
90952
- capability: addonRoutesCapability,
90953
- provider: routeProvider
90954
- },
90955
- {
90956
- capability: oauthIntegrationCapability,
90957
- provider: oauthIntegrationProvider
90958
- }
90959
- ],
90960
- customActions: exportGoogleActions,
90961
- actionHandlers: { detectPublicHubUrl: async () => this.detectPublicHubUrl() }
90962
- };
90963
- }
90964
- /** This addon's slice of `PublicHubUrlState`. */
90965
- publicHubUrlState() {
90966
- return {
90967
- publicHubUrl: this.config.publicHubUrl,
90968
- detectedPublicHubUrl: this.config.detectedPublicHubUrl
90969
- };
90970
- }
90971
- /**
90972
- * Adapter from the codegen'd `network-access` router onto the narrow reader
90973
- * `public-hub-url.ts` consumes. Fields are copied one by one rather than
90974
- * passed through, so the module never depends on the cap's wider shape and a
90975
- * test double for it needs no cast.
90976
- */
90977
- networkAccessReader() {
90978
- return {
90979
- listEndpoints: async () => {
90980
- return (await this.ctx.api.networkAccess.listEndpoints.query({})).map((entry) => ({
90981
- url: entry.url,
90982
- protocol: entry.protocol
90983
- }));
90926
+ return [
90927
+ {
90928
+ capability: deviceExportCapability,
90929
+ provider: deviceExportProvider
90984
90930
  },
90985
- getStatus: async () => {
90986
- const status = await this.ctx.api.networkAccess.getStatus.query({});
90987
- return {
90988
- connected: status.connected,
90989
- endpoint: status.endpoint === null ? null : {
90990
- url: status.endpoint.url,
90991
- protocol: status.endpoint.protocol
90992
- }
90993
- };
90931
+ {
90932
+ capability: addonRoutesCapability,
90933
+ provider: routeProvider
90934
+ },
90935
+ {
90936
+ capability: oauthIntegrationCapability,
90937
+ provider: oauthIntegrationProvider
90994
90938
  }
90995
- };
90996
- }
90997
- /**
90998
- * Refresh the detected address and DEFAULT the field to it when it is empty.
90999
- * Backs both the boot-time detect and the "Detect external address" button.
91000
- *
91001
- * Never replaces a value the operator set — that value is what they already
91002
- * pasted into the Google console, and rewriting it here would leave the two
91003
- * sides disagreeing with nothing on screen to say so.
91004
- */
91005
- async detectPublicHubUrl() {
91006
- const resolution = await refreshPublicHubUrl({
91007
- current: () => this.publicHubUrlState(),
91008
- detect: () => detectPublicHubOrigins({
91009
- network: this.networkAccessReader(),
91010
- logger: this.ctx.logger
91011
- }),
91012
- persist: (patch) => this.updateGlobalSettings(patch),
91013
- logger: this.ctx.logger
91014
- });
91015
- const result = {
91016
- publicHubUrl: resolution.publicHubUrl,
91017
- detectedPublicHubUrl: resolution.detectedPublicHubUrl,
91018
- filled: resolution.defaulted
91019
- };
91020
- return {
91021
- ...result,
91022
- summary: describeDetectResult(result)
91023
- };
90939
+ ];
91024
90940
  }
91025
90941
  async onShutdown() {
91026
90942
  this.gateway = null;
@@ -91089,11 +91005,11 @@ var ExportGoogleAddon = class extends BaseAddon {
91089
91005
  * value still travels in the `getStatus` response — so it would be the wrong
91090
91006
  * tool for a real credential anyway (docs/decisions/adr-0269-a-google-export-that-holds-no-google-credential.md).
91091
91007
  */
91092
- buildSetupBlock() {
91093
- return buildConsoleSetup({
91008
+ async buildSetupBlock() {
91009
+ return buildConsoleSetupFromRole({
91094
91010
  addonId: ADDON_ID,
91095
- ...this.publicHubUrlState(),
91096
- linkedAccounts: this.config.linkedAccounts.length
91011
+ linkedAccounts: this.config.linkedAccounts.length,
91012
+ read: () => this.ctx.api.localNetwork.getAddresses.query()
91097
91013
  });
91098
91014
  }
91099
91015
  globalSettingsSchema() {
@@ -91102,44 +91018,17 @@ var ExportGoogleAddon = class extends BaseAddon {
91102
91018
  title: "Connection",
91103
91019
  description: "Publishes switches, dimmable lights, locks and covers to Google Home. The hub answers Google directly — no cloud function, and no Google credential is stored here.",
91104
91020
  columns: 1,
91105
- fields: [
91106
- {
91107
- type: "info",
91108
- key: "__google-setup-banner",
91109
- label: "Setup overview",
91110
- variant: "info",
91111
- content: [
91112
- "This hub must be reachable from the public internet over HTTPS (Cloudflare Tunnel, Tailscale Funnel, …) — Google calls the fulfillment URL from its own cloud.",
91113
- "Create a cloud-to-cloud integration in the Google Home Developer Console, paste the three URLs from the Export panel, and link your account from the Home app.",
91114
- "Cameras are not exported, and state is not pushed: Google polls. Ask \"Hey Google, sync my devices\" after exposing something new."
91115
- ].join("\n")
91116
- },
91117
- this.field({
91118
- type: "text",
91119
- key: "publicHubUrl",
91120
- label: "Public hub URL",
91121
- description: "HTTPS origin Google reaches this hub on, e.g. https://hub.example.com. Used to render the URLs you paste into the Google console. Left empty, it defaults to the first external address remote access reports; once it holds a value, nothing overwrites it.",
91122
- placeholder: "https://hub.example.com",
91123
- default: DEFAULT_SETTINGS.publicHubUrl
91124
- }),
91125
- {
91126
- type: "info",
91127
- key: "__public-hub-url-source",
91128
- label: "Where this came from",
91129
- ...buildPublicHubUrlNotice(this.publicHubUrlState())
91130
- },
91131
- {
91132
- type: "addon-action-button",
91133
- addonId: ADDON_ID,
91134
- key: "__detect-public-hub-url",
91135
- label: "External address",
91136
- description: "Re-scan the connected remote-access providers. Fills the field above when it is empty; a value you set is left exactly as it is.",
91137
- buttonLabel: "Detect external address",
91138
- action: "detectPublicHubUrl",
91139
- variant: "default",
91140
- successMessage: "{summary}"
91141
- }
91142
- ]
91021
+ fields: [{
91022
+ type: "info",
91023
+ key: "__google-setup-banner",
91024
+ label: "Setup overview",
91025
+ variant: "info",
91026
+ content: [
91027
+ "This hub must be reachable from the public internet over HTTPS (Cloudflare Tunnel, Tailscale Funnel, …) — Google calls the fulfillment URL from its own cloud.",
91028
+ "Create a cloud-to-cloud integration in the Google Home Developer Console, paste the three URLs from the Export panel, and link your account from the Home app.",
91029
+ "Cameras are not exported, and state is not pushed: Google polls. Ask \"Hey Google, sync my devices\" after exposing something new."
91030
+ ].join("\n")
91031
+ }]
91143
91032
  }] });
91144
91033
  }
91145
91034
  /**