@camstack/addon-export-google 0.1.124 → 0.1.126
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.
- package/CHANGELOG.md +12 -0
- package/dist/export-google.addon.js +1743 -271
- package/dist/export-google.addon.mjs +1743 -271
- package/package.json +5 -2
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
1
2
|
//#region src/google-home/cap-dispatch.ts
|
|
2
3
|
async function dispatchCapCall(api, call) {
|
|
3
4
|
switch (call.kind) {
|
|
@@ -4632,6 +4633,12 @@ var numberProcessor = (schema, ctx, _json, _params) => {
|
|
|
4632
4633
|
var booleanProcessor = (_schema, _ctx, json, _params) => {
|
|
4633
4634
|
json.type = "boolean";
|
|
4634
4635
|
};
|
|
4636
|
+
var bigintProcessor = (_schema, ctx, _json, _params) => {
|
|
4637
|
+
if (ctx.unrepresentable === "throw") throw new Error("BigInt cannot be represented in JSON Schema");
|
|
4638
|
+
};
|
|
4639
|
+
var symbolProcessor = (_schema, ctx, _json, _params) => {
|
|
4640
|
+
if (ctx.unrepresentable === "throw") throw new Error("Symbols cannot be represented in JSON Schema");
|
|
4641
|
+
};
|
|
4635
4642
|
var nullProcessor = (_schema, ctx, json, _params) => {
|
|
4636
4643
|
if (ctx.target === "openapi-3.0") {
|
|
4637
4644
|
json.type = "string";
|
|
@@ -4639,12 +4646,17 @@ var nullProcessor = (_schema, ctx, json, _params) => {
|
|
|
4639
4646
|
json.enum = [null];
|
|
4640
4647
|
} else json.type = "null";
|
|
4641
4648
|
};
|
|
4649
|
+
var undefinedProcessor = (_schema, ctx, _json, _params) => {
|
|
4650
|
+
if (ctx.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema");
|
|
4651
|
+
};
|
|
4642
4652
|
var voidProcessor = (_schema, ctx, _json, _params) => {
|
|
4643
4653
|
if (ctx.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema");
|
|
4644
4654
|
};
|
|
4645
4655
|
var neverProcessor = (_schema, _ctx, json, _params) => {
|
|
4646
4656
|
json.not = {};
|
|
4647
4657
|
};
|
|
4658
|
+
var anyProcessor = (_schema, _ctx, _json, _params) => {};
|
|
4659
|
+
var unknownProcessor = (_schema, _ctx, _json, _params) => {};
|
|
4648
4660
|
var dateProcessor = (_schema, ctx, _json, _params) => {
|
|
4649
4661
|
if (ctx.unrepresentable === "throw") throw new Error("Date cannot be represented in JSON Schema");
|
|
4650
4662
|
};
|
|
@@ -4676,12 +4688,53 @@ var literalProcessor = (schema, ctx, json, _params) => {
|
|
|
4676
4688
|
json.enum = vals;
|
|
4677
4689
|
}
|
|
4678
4690
|
};
|
|
4691
|
+
var nanProcessor = (_schema, ctx, _json, _params) => {
|
|
4692
|
+
if (ctx.unrepresentable === "throw") throw new Error("NaN cannot be represented in JSON Schema");
|
|
4693
|
+
};
|
|
4694
|
+
var templateLiteralProcessor = (schema, _ctx, json, _params) => {
|
|
4695
|
+
const _json = json;
|
|
4696
|
+
const pattern = schema._zod.pattern;
|
|
4697
|
+
if (!pattern) throw new Error("Pattern not found in template literal");
|
|
4698
|
+
_json.type = "string";
|
|
4699
|
+
_json.pattern = pattern.source;
|
|
4700
|
+
};
|
|
4701
|
+
var fileProcessor = (schema, _ctx, json, _params) => {
|
|
4702
|
+
const _json = json;
|
|
4703
|
+
const file = {
|
|
4704
|
+
type: "string",
|
|
4705
|
+
format: "binary",
|
|
4706
|
+
contentEncoding: "binary"
|
|
4707
|
+
};
|
|
4708
|
+
const { minimum, maximum, mime } = schema._zod.bag;
|
|
4709
|
+
if (minimum !== void 0) file.minLength = minimum;
|
|
4710
|
+
if (maximum !== void 0) file.maxLength = maximum;
|
|
4711
|
+
if (mime) if (mime.length === 1) {
|
|
4712
|
+
file.contentMediaType = mime[0];
|
|
4713
|
+
Object.assign(_json, file);
|
|
4714
|
+
} else {
|
|
4715
|
+
Object.assign(_json, file);
|
|
4716
|
+
_json.anyOf = mime.map((m) => ({ contentMediaType: m }));
|
|
4717
|
+
}
|
|
4718
|
+
else Object.assign(_json, file);
|
|
4719
|
+
};
|
|
4720
|
+
var successProcessor = (_schema, _ctx, json, _params) => {
|
|
4721
|
+
json.type = "boolean";
|
|
4722
|
+
};
|
|
4679
4723
|
var customProcessor = (_schema, ctx, _json, _params) => {
|
|
4680
4724
|
if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
|
|
4681
4725
|
};
|
|
4726
|
+
var functionProcessor = (_schema, ctx, _json, _params) => {
|
|
4727
|
+
if (ctx.unrepresentable === "throw") throw new Error("Function types cannot be represented in JSON Schema");
|
|
4728
|
+
};
|
|
4682
4729
|
var transformProcessor = (_schema, ctx, _json, _params) => {
|
|
4683
4730
|
if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
|
|
4684
4731
|
};
|
|
4732
|
+
var mapProcessor = (_schema, ctx, _json, _params) => {
|
|
4733
|
+
if (ctx.unrepresentable === "throw") throw new Error("Map cannot be represented in JSON Schema");
|
|
4734
|
+
};
|
|
4735
|
+
var setProcessor = (_schema, ctx, _json, _params) => {
|
|
4736
|
+
if (ctx.unrepresentable === "throw") throw new Error("Set cannot be represented in JSON Schema");
|
|
4737
|
+
};
|
|
4685
4738
|
var arrayProcessor = (schema, ctx, _json, params) => {
|
|
4686
4739
|
const json = _json;
|
|
4687
4740
|
const def = schema._zod.def;
|
|
@@ -4886,6 +4939,12 @@ var readonlyProcessor = (schema, ctx, json, params) => {
|
|
|
4886
4939
|
seen.ref = def.innerType;
|
|
4887
4940
|
json.readOnly = true;
|
|
4888
4941
|
};
|
|
4942
|
+
var promiseProcessor = (schema, ctx, _json, params) => {
|
|
4943
|
+
const def = schema._zod.def;
|
|
4944
|
+
process(def.innerType, ctx, params);
|
|
4945
|
+
const seen = ctx.seen.get(schema);
|
|
4946
|
+
seen.ref = def.innerType;
|
|
4947
|
+
};
|
|
4889
4948
|
var optionalProcessor = (schema, ctx, _json, params) => {
|
|
4890
4949
|
const def = schema._zod.def;
|
|
4891
4950
|
process(def.innerType, ctx, params);
|
|
@@ -4898,6 +4957,81 @@ var lazyProcessor = (schema, ctx, _json, params) => {
|
|
|
4898
4957
|
const seen = ctx.seen.get(schema);
|
|
4899
4958
|
seen.ref = innerType;
|
|
4900
4959
|
};
|
|
4960
|
+
var allProcessors = {
|
|
4961
|
+
string: stringProcessor,
|
|
4962
|
+
number: numberProcessor,
|
|
4963
|
+
boolean: booleanProcessor,
|
|
4964
|
+
bigint: bigintProcessor,
|
|
4965
|
+
symbol: symbolProcessor,
|
|
4966
|
+
null: nullProcessor,
|
|
4967
|
+
undefined: undefinedProcessor,
|
|
4968
|
+
void: voidProcessor,
|
|
4969
|
+
never: neverProcessor,
|
|
4970
|
+
any: anyProcessor,
|
|
4971
|
+
unknown: unknownProcessor,
|
|
4972
|
+
date: dateProcessor,
|
|
4973
|
+
enum: enumProcessor,
|
|
4974
|
+
literal: literalProcessor,
|
|
4975
|
+
nan: nanProcessor,
|
|
4976
|
+
template_literal: templateLiteralProcessor,
|
|
4977
|
+
file: fileProcessor,
|
|
4978
|
+
success: successProcessor,
|
|
4979
|
+
custom: customProcessor,
|
|
4980
|
+
function: functionProcessor,
|
|
4981
|
+
transform: transformProcessor,
|
|
4982
|
+
map: mapProcessor,
|
|
4983
|
+
set: setProcessor,
|
|
4984
|
+
array: arrayProcessor,
|
|
4985
|
+
object: objectProcessor,
|
|
4986
|
+
union: unionProcessor,
|
|
4987
|
+
intersection: intersectionProcessor,
|
|
4988
|
+
tuple: tupleProcessor,
|
|
4989
|
+
record: recordProcessor,
|
|
4990
|
+
nullable: nullableProcessor,
|
|
4991
|
+
nonoptional: nonoptionalProcessor,
|
|
4992
|
+
default: defaultProcessor,
|
|
4993
|
+
prefault: prefaultProcessor,
|
|
4994
|
+
catch: catchProcessor,
|
|
4995
|
+
pipe: pipeProcessor,
|
|
4996
|
+
readonly: readonlyProcessor,
|
|
4997
|
+
promise: promiseProcessor,
|
|
4998
|
+
optional: optionalProcessor,
|
|
4999
|
+
lazy: lazyProcessor
|
|
5000
|
+
};
|
|
5001
|
+
function toJSONSchema(input, params) {
|
|
5002
|
+
if ("_idmap" in input) {
|
|
5003
|
+
const registry = input;
|
|
5004
|
+
const ctx = initializeContext({
|
|
5005
|
+
...params,
|
|
5006
|
+
processors: allProcessors
|
|
5007
|
+
});
|
|
5008
|
+
const defs = {};
|
|
5009
|
+
for (const entry of registry._idmap.entries()) {
|
|
5010
|
+
const [_, schema] = entry;
|
|
5011
|
+
process(schema, ctx);
|
|
5012
|
+
}
|
|
5013
|
+
const schemas = {};
|
|
5014
|
+
ctx.external = {
|
|
5015
|
+
registry,
|
|
5016
|
+
uri: params?.uri,
|
|
5017
|
+
defs
|
|
5018
|
+
};
|
|
5019
|
+
for (const entry of registry._idmap.entries()) {
|
|
5020
|
+
const [key, schema] = entry;
|
|
5021
|
+
extractDefs(ctx, schema);
|
|
5022
|
+
schemas[key] = finalize(ctx, schema);
|
|
5023
|
+
}
|
|
5024
|
+
if (Object.keys(defs).length > 0) schemas.__shared = { [ctx.target === "draft-2020-12" ? "$defs" : "definitions"]: defs };
|
|
5025
|
+
return { schemas };
|
|
5026
|
+
}
|
|
5027
|
+
const ctx = initializeContext({
|
|
5028
|
+
...params,
|
|
5029
|
+
processors: allProcessors
|
|
5030
|
+
});
|
|
5031
|
+
process(input, ctx);
|
|
5032
|
+
extractDefs(ctx, input);
|
|
5033
|
+
return finalize(ctx, input);
|
|
5034
|
+
}
|
|
4901
5035
|
//#endregion
|
|
4902
5036
|
//#region ../../node_modules/zod/v4/classic/iso.js
|
|
4903
5037
|
var ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
|
|
@@ -5922,7 +6056,7 @@ var ZodIssueCode = {
|
|
|
5922
6056
|
var ZodFirstPartyTypeKind;
|
|
5923
6057
|
ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
|
|
5924
6058
|
//#endregion
|
|
5925
|
-
//#region ../types/dist/sleep-
|
|
6059
|
+
//#region ../types/dist/sleep-D1jjWAr8.mjs
|
|
5926
6060
|
/**
|
|
5927
6061
|
* The audio chunk plane's byte format, and the ONE expansion from a coded
|
|
5928
6062
|
* window to float samples (D455).
|
|
@@ -6070,9 +6204,16 @@ function isSecretMarker(value) {
|
|
|
6070
6204
|
const ref = value["$secret"];
|
|
6071
6205
|
return typeof ref === "string" && ref.length > 0;
|
|
6072
6206
|
}
|
|
6207
|
+
/** Anything carrying a `$secret` key — a stored marker or a UI view of one. */
|
|
6208
|
+
function isSecretMarkerLike(value) {
|
|
6209
|
+
return isRecord$7(value) && Object.prototype.hasOwnProperty.call(value, "$secret");
|
|
6210
|
+
}
|
|
6073
6211
|
function isSecretClear(value) {
|
|
6074
6212
|
return isRecord$7(value) && value["$secretClear"] === true;
|
|
6075
6213
|
}
|
|
6214
|
+
function isSecretFieldView(value) {
|
|
6215
|
+
return isRecord$7(value) && value["set"] === true && isSecretMarkerLike(value);
|
|
6216
|
+
}
|
|
6076
6217
|
/**
|
|
6077
6218
|
* The UI view of a stored secret field value: a marker becomes "set", inline
|
|
6078
6219
|
* plaintext becomes "set (inline)", nothing becomes `null`. A value never
|
|
@@ -6515,7 +6656,7 @@ var NOT_RUN = {
|
|
|
6515
6656
|
* throws: an unreachable or refusing engine is logged and reported `declared: false`,
|
|
6516
6657
|
* because the hub (and this addon's boot) must not hang on a migration.
|
|
6517
6658
|
*/
|
|
6518
|
-
async function runAddonMigrations(host, migrations, logger) {
|
|
6659
|
+
async function runAddonMigrations(host, migrations, logger, options = {}) {
|
|
6519
6660
|
const first = migrations[0];
|
|
6520
6661
|
if (first === void 0) return NOT_RUN;
|
|
6521
6662
|
const owner = first.meta.owner;
|
|
@@ -6544,7 +6685,9 @@ async function runAddonMigrations(host, migrations, logger) {
|
|
|
6544
6685
|
else if (status === "blocked") blocked.push(id);
|
|
6545
6686
|
else skipped.push(id);
|
|
6546
6687
|
};
|
|
6688
|
+
const selected = options.only === void 0 ? null : new Set(options.only);
|
|
6547
6689
|
for (const step of declaration.steps) {
|
|
6690
|
+
if (selected !== null && !selected.has(step.id)) continue;
|
|
6548
6691
|
const bound = byId.get(step.id);
|
|
6549
6692
|
if (bound === void 0 || step.action === "skip") {
|
|
6550
6693
|
skipped.push(step.id);
|
|
@@ -6722,11 +6865,36 @@ function projectStore(store, perNodeKeys, nodeId) {
|
|
|
6722
6865
|
}
|
|
6723
6866
|
return out;
|
|
6724
6867
|
}
|
|
6868
|
+
/**
|
|
6869
|
+
* The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
|
|
6870
|
+
*
|
|
6871
|
+
* A ref is DETERMINISTIC from where the value lives — the owner addon, the
|
|
6872
|
+
* scope (global, one node, one device, one integration, one row of a business
|
|
6873
|
+
* collection) and the field path inside that scope — so saving the same field
|
|
6874
|
+
* twice updates the same ref, and the ref itself says which settings blob
|
|
6875
|
+
* points at it. It is also the AAD of the value's ciphertext: a ciphertext
|
|
6876
|
+
* copied onto another ref does not decrypt.
|
|
6877
|
+
*
|
|
6878
|
+
* Array items are addressed by ITEM ID, never by index
|
|
6879
|
+
* (`providers[authentik].clientSecret`), so reordering a list keeps every ref.
|
|
6880
|
+
*
|
|
6881
|
+
* Pure and browser-safe: no node builtins, no I/O.
|
|
6882
|
+
*/
|
|
6883
|
+
/** The URI scheme of every keychain ref. */
|
|
6884
|
+
var SECRET_REF_SCHEME = "secret://";
|
|
6725
6885
|
var GLOBAL_SCOPE = { kind: "global" };
|
|
6726
6886
|
/** The scope every addon-wide (not per-node, not per-device) setting lives in. */
|
|
6727
6887
|
function globalSecretScope() {
|
|
6728
6888
|
return GLOBAL_SCOPE;
|
|
6729
6889
|
}
|
|
6890
|
+
/**
|
|
6891
|
+
* An addon id as a ref owner. A hub in-process builtin's context id is
|
|
6892
|
+
* `addon:<id>`; the owner of its secrets is `<id>`, exactly as for the same
|
|
6893
|
+
* addon running forked.
|
|
6894
|
+
*/
|
|
6895
|
+
function normalizeSecretOwner(addonId) {
|
|
6896
|
+
return addonId.startsWith("addon:") ? addonId.slice(6) : addonId;
|
|
6897
|
+
}
|
|
6730
6898
|
function encodeSegment(value) {
|
|
6731
6899
|
return encodeURIComponent(value);
|
|
6732
6900
|
}
|
|
@@ -6737,6 +6905,16 @@ function decodeSegment(value) {
|
|
|
6737
6905
|
return null;
|
|
6738
6906
|
}
|
|
6739
6907
|
}
|
|
6908
|
+
/** The scope as it appears inside a ref (`global`, `node/<id>`, …). */
|
|
6909
|
+
function formatSecretScope(scope) {
|
|
6910
|
+
switch (scope.kind) {
|
|
6911
|
+
case "global": return "global";
|
|
6912
|
+
case "node": return `node/${encodeSegment(scope.nodeId)}`;
|
|
6913
|
+
case "device": return `device/${scope.deviceId}`;
|
|
6914
|
+
case "integration": return `integration/${encodeSegment(scope.integrationId)}`;
|
|
6915
|
+
case "row": return `row/${encodeSegment(scope.collection)}/${encodeSegment(scope.rowId)}`;
|
|
6916
|
+
}
|
|
6917
|
+
}
|
|
6740
6918
|
/**
|
|
6741
6919
|
* The field path of a value inside an array item, addressed by the item's id:
|
|
6742
6920
|
* `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
|
|
@@ -6745,6 +6923,13 @@ function decodeSegment(value) {
|
|
|
6745
6923
|
function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
|
|
6746
6924
|
return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
|
|
6747
6925
|
}
|
|
6926
|
+
/** Build a ref. Throws on an empty owner or field path — both are bugs. */
|
|
6927
|
+
function buildSecretRef(parts) {
|
|
6928
|
+
const owner = normalizeSecretOwner(parts.owner);
|
|
6929
|
+
if (owner.length === 0) throw new Error("buildSecretRef: owner is empty");
|
|
6930
|
+
if (parts.fieldPath.length === 0) throw new Error("buildSecretRef: fieldPath is empty");
|
|
6931
|
+
return `${SECRET_REF_SCHEME}${encodeSegment(owner)}/${formatSecretScope(parts.scope)}/${parts.fieldPath}`;
|
|
6932
|
+
}
|
|
6748
6933
|
function parseScope(segments) {
|
|
6749
6934
|
switch (segments[0]) {
|
|
6750
6935
|
case "global": return {
|
|
@@ -6885,7 +7070,7 @@ async function writeMembers(ctx, children, incoming, stored, pathOf) {
|
|
|
6885
7070
|
for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
|
|
6886
7071
|
return out;
|
|
6887
7072
|
}
|
|
6888
|
-
function rowId(row, idKey) {
|
|
7073
|
+
function rowId$1(row, idKey) {
|
|
6889
7074
|
const raw = row[idKey];
|
|
6890
7075
|
if (typeof raw === "string" && raw.length > 0) return raw;
|
|
6891
7076
|
if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
|
|
@@ -6902,7 +7087,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
|
|
|
6902
7087
|
}
|
|
6903
7088
|
const storedById = /* @__PURE__ */ new Map();
|
|
6904
7089
|
for (const row of storedRows) {
|
|
6905
|
-
const id = rowId(row, node.idKey);
|
|
7090
|
+
const id = rowId$1(row, node.idKey);
|
|
6906
7091
|
if (id !== null) storedById.set(id, row);
|
|
6907
7092
|
}
|
|
6908
7093
|
const kept = /* @__PURE__ */ new Set();
|
|
@@ -6912,13 +7097,13 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
|
|
|
6912
7097
|
rows.push(row);
|
|
6913
7098
|
continue;
|
|
6914
7099
|
}
|
|
6915
|
-
const id = rowId(row, node.idKey) ?? ctx.mintId();
|
|
7100
|
+
const id = rowId$1(row, node.idKey) ?? ctx.mintId();
|
|
6916
7101
|
kept.add(id);
|
|
6917
7102
|
const withId = {
|
|
6918
7103
|
...row,
|
|
6919
7104
|
[node.idKey]: row[node.idKey] ?? id
|
|
6920
7105
|
};
|
|
6921
|
-
if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
|
|
7106
|
+
if (rowId$1(withId, node.idKey) === null) withId[node.idKey] = id;
|
|
6922
7107
|
const storedRow = storedById.get(id) ?? {};
|
|
6923
7108
|
rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
|
|
6924
7109
|
}
|
|
@@ -7662,14 +7847,18 @@ var BaseAddon = class {
|
|
|
7662
7847
|
* nothing; the boot continues. A migration that FAILED (or was blocked by one)
|
|
7663
7848
|
* and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
|
|
7664
7849
|
* serve data whose shape it cannot trust; `tolerate` migrations never do.
|
|
7850
|
+
*
|
|
7851
|
+
* ALWAYS pass the whole catalogue; a phase that must run only some of it passes
|
|
7852
|
+
* `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
|
|
7853
|
+
* omitted applied ids "newer").
|
|
7665
7854
|
*/
|
|
7666
|
-
async runMigrations(migrations) {
|
|
7855
|
+
async runMigrations(migrations, options) {
|
|
7667
7856
|
const api = this.ctx.api.migrations;
|
|
7668
7857
|
const report = await runAddonMigrations({
|
|
7669
7858
|
declareOwner: (input) => api.declareOwner.mutate(input),
|
|
7670
7859
|
startMigration: (input) => api.startMigration.mutate(input),
|
|
7671
7860
|
finishMigration: (input) => api.finishMigration.mutate(input)
|
|
7672
|
-
}, migrations, this.ctx.logger);
|
|
7861
|
+
}, migrations, this.ctx.logger, options);
|
|
7673
7862
|
if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
|
|
7674
7863
|
return report;
|
|
7675
7864
|
}
|
|
@@ -8653,6 +8842,45 @@ function normalizeAddonInitResult(result) {
|
|
|
8653
8842
|
if (Array.isArray(result)) return { providers: result };
|
|
8654
8843
|
return result;
|
|
8655
8844
|
}
|
|
8845
|
+
var PREFIX$1 = "records/";
|
|
8846
|
+
/** The base of every records failure. `detail` is the human part of the message. */
|
|
8847
|
+
var RecordsError = class extends Error {
|
|
8848
|
+
code;
|
|
8849
|
+
detail;
|
|
8850
|
+
constructor(code, detail) {
|
|
8851
|
+
super(`${PREFIX$1}${code}: ${detail}`);
|
|
8852
|
+
this.name = "RecordsError";
|
|
8853
|
+
this.code = code;
|
|
8854
|
+
this.detail = detail;
|
|
8855
|
+
}
|
|
8856
|
+
};
|
|
8857
|
+
/** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
|
|
8858
|
+
var RevConflictError = class extends RecordsError {
|
|
8859
|
+
constructor(detail) {
|
|
8860
|
+
super("rev-conflict", detail);
|
|
8861
|
+
this.name = "RevConflictError";
|
|
8862
|
+
}
|
|
8863
|
+
};
|
|
8864
|
+
/** The keychain could not store or serve a value: explicit, never an empty string. */
|
|
8865
|
+
var RecordSecretUnavailableError = class extends RecordsError {
|
|
8866
|
+
constructor(detail) {
|
|
8867
|
+
super("secret-unavailable", detail);
|
|
8868
|
+
this.name = "RecordSecretUnavailableError";
|
|
8869
|
+
}
|
|
8870
|
+
};
|
|
8871
|
+
var InvalidRecordError = class extends RecordsError {
|
|
8872
|
+
constructor(detail) {
|
|
8873
|
+
super("invalid-record", detail);
|
|
8874
|
+
this.name = "InvalidRecordError";
|
|
8875
|
+
}
|
|
8876
|
+
};
|
|
8877
|
+
/** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
|
|
8878
|
+
var DeclarationRefusedError = class extends RecordsError {
|
|
8879
|
+
constructor(detail) {
|
|
8880
|
+
super("declaration-refused", detail);
|
|
8881
|
+
this.name = "DeclarationRefusedError";
|
|
8882
|
+
}
|
|
8883
|
+
};
|
|
8656
8884
|
/** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
|
|
8657
8885
|
/** The files a kind may live in. `history` is device-history's (D850), never records. */
|
|
8658
8886
|
var RECORD_DATABASES = ["settings", "events"];
|
|
@@ -8668,6 +8896,174 @@ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
|
|
|
8668
8896
|
var RECORD_MAX_DATA_BYTES = 1024 * 1024;
|
|
8669
8897
|
var RECORD_BATCH_MAX = 1e3;
|
|
8670
8898
|
var RECORD_QUERY_MAX = 1e3;
|
|
8899
|
+
/** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
|
|
8900
|
+
var RECORD_SETTINGS_MAX_ROWS = 5e4;
|
|
8901
|
+
/** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
|
|
8902
|
+
var RECORD_SECRET_COLLECTION_PREFIX = "records:";
|
|
8903
|
+
/**
|
|
8904
|
+
* Secret fields of a record, addressed the way a Zod schema declares them
|
|
8905
|
+
* (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
|
|
8906
|
+
* (`auth.accessToken`, `headers[].value`).
|
|
8907
|
+
*
|
|
8908
|
+
* `{}` after a key means "each value of this map" (`applianceSecrets{}`): the map's own key
|
|
8909
|
+
* names the value (`applianceSecrets{fridge}`), so no id key is declared and a body that drops a
|
|
8910
|
+
* key releases exactly that key's secret.
|
|
8911
|
+
*
|
|
8912
|
+
* Array elements are matched by a DECLARED id key (`secretArrayKeys`:
|
|
8913
|
+
* `{ headers: 'name' }`), never by index, so reordering a list keeps every
|
|
8914
|
+
* keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
|
|
8915
|
+
* leaf names its element: `headers[X-Api].value`.
|
|
8916
|
+
*
|
|
8917
|
+
* Pure and browser-safe. Nothing here mutates: every transform returns a new value.
|
|
8918
|
+
*/
|
|
8919
|
+
/** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
|
|
8920
|
+
function parseSecretPath(path) {
|
|
8921
|
+
if (path.length === 0) throw new InvalidRecordError("an empty secret path");
|
|
8922
|
+
return path.split(".").map((raw) => {
|
|
8923
|
+
const each = raw.endsWith("[]");
|
|
8924
|
+
const map = raw.endsWith("{}");
|
|
8925
|
+
const key = each || map ? raw.slice(0, -2) : raw;
|
|
8926
|
+
if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
|
|
8927
|
+
return {
|
|
8928
|
+
key,
|
|
8929
|
+
each,
|
|
8930
|
+
map
|
|
8931
|
+
};
|
|
8932
|
+
});
|
|
8933
|
+
}
|
|
8934
|
+
/** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
|
|
8935
|
+
function secretArrayPrefixes(path) {
|
|
8936
|
+
const segments = parseSecretPath(path);
|
|
8937
|
+
const prefixes = [];
|
|
8938
|
+
const walked = [];
|
|
8939
|
+
for (const segment of segments) {
|
|
8940
|
+
walked.push(segment.key);
|
|
8941
|
+
if (segment.each) prefixes.push(walked.join("."));
|
|
8942
|
+
}
|
|
8943
|
+
return prefixes;
|
|
8944
|
+
}
|
|
8945
|
+
function isRecord$4(value) {
|
|
8946
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8947
|
+
}
|
|
8948
|
+
function elementId(element, idKey, declared, prefix) {
|
|
8949
|
+
const id = isRecord$4(element) ? element[idKey] : void 0;
|
|
8950
|
+
if (typeof id !== "string" || id.length === 0) throw new InvalidRecordError(`"${declared}": every element of "${prefix}" needs a non-empty string "${idKey}" to carry a secret`);
|
|
8951
|
+
return id;
|
|
8952
|
+
}
|
|
8953
|
+
/**
|
|
8954
|
+
* Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
|
|
8955
|
+
* visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
|
|
8956
|
+
* result is a new body, `data` is untouched.
|
|
8957
|
+
*/
|
|
8958
|
+
var REMOVE_LEAF = Symbol("remove-leaf");
|
|
8959
|
+
function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
|
|
8960
|
+
if (!isRecord$4(node)) return node;
|
|
8961
|
+
const segment = segments[index];
|
|
8962
|
+
if (segment === void 0) return node;
|
|
8963
|
+
if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
|
|
8964
|
+
const child = node[segment.key];
|
|
8965
|
+
const keys = [...walkedKeys, segment.key];
|
|
8966
|
+
const last = index === segments.length - 1;
|
|
8967
|
+
if (segment.each) {
|
|
8968
|
+
if (!Array.isArray(child)) return node;
|
|
8969
|
+
const prefix = keys.join(".");
|
|
8970
|
+
const idKey = arrayKeys[prefix];
|
|
8971
|
+
if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
|
|
8972
|
+
const mapped = child.map((element) => {
|
|
8973
|
+
const id = elementId(element, idKey, declared, prefix);
|
|
8974
|
+
const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
|
|
8975
|
+
return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
|
|
8976
|
+
});
|
|
8977
|
+
return {
|
|
8978
|
+
...node,
|
|
8979
|
+
[segment.key]: mapped
|
|
8980
|
+
};
|
|
8981
|
+
}
|
|
8982
|
+
if (segment.map) {
|
|
8983
|
+
if (!isRecord$4(child)) return node;
|
|
8984
|
+
const kept = Object.entries(child).map(([mapKey, value]) => {
|
|
8985
|
+
const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
|
|
8986
|
+
if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
|
|
8987
|
+
return [mapKey, visit({
|
|
8988
|
+
declared,
|
|
8989
|
+
concrete,
|
|
8990
|
+
value
|
|
8991
|
+
})];
|
|
8992
|
+
}).filter(([, value]) => value !== REMOVE_LEAF);
|
|
8993
|
+
return {
|
|
8994
|
+
...node,
|
|
8995
|
+
[segment.key]: Object.fromEntries(kept)
|
|
8996
|
+
};
|
|
8997
|
+
}
|
|
8998
|
+
const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
|
|
8999
|
+
if (last) {
|
|
9000
|
+
const replacement = visit({
|
|
9001
|
+
declared,
|
|
9002
|
+
concrete,
|
|
9003
|
+
value: child
|
|
9004
|
+
});
|
|
9005
|
+
if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
|
|
9006
|
+
return {
|
|
9007
|
+
...node,
|
|
9008
|
+
[segment.key]: replacement
|
|
9009
|
+
};
|
|
9010
|
+
}
|
|
9011
|
+
return {
|
|
9012
|
+
...node,
|
|
9013
|
+
[segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
|
|
9014
|
+
};
|
|
9015
|
+
}
|
|
9016
|
+
/** Replace/remove every present secret leaf; returns a NEW body. */
|
|
9017
|
+
function mapSecretLeaves(data, paths, arrayKeys, visit) {
|
|
9018
|
+
let current = data;
|
|
9019
|
+
for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
|
|
9020
|
+
return current;
|
|
9021
|
+
}
|
|
9022
|
+
/**
|
|
9023
|
+
* The keychain collection name a kind's secrets live under. Prefixed so a
|
|
9024
|
+
* record's refs never collide with the refs a legacy collection of the same name
|
|
9025
|
+
* already holds during an adoption.
|
|
9026
|
+
*/
|
|
9027
|
+
function recordSecretCollection(kind) {
|
|
9028
|
+
return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
|
|
9029
|
+
}
|
|
9030
|
+
/** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
|
|
9031
|
+
function recordSecretRef(owner, kind, rowId, concretePath) {
|
|
9032
|
+
return buildSecretRef({
|
|
9033
|
+
owner,
|
|
9034
|
+
scope: {
|
|
9035
|
+
kind: "row",
|
|
9036
|
+
collection: recordSecretCollection(kind),
|
|
9037
|
+
rowId
|
|
9038
|
+
},
|
|
9039
|
+
fieldPath: concretePath
|
|
9040
|
+
});
|
|
9041
|
+
}
|
|
9042
|
+
/**
|
|
9043
|
+
* A stored secret, as an admin read shows it: a VIEW naming the row's own
|
|
9044
|
+
* keychain ref (`set: true`), never the value and no longer the bare redaction
|
|
9045
|
+
* token. The form hands it to the secret field, which reveals the value by ref
|
|
9046
|
+
* through the audited `keychain-admin.reveal`; sent back untouched it keeps the
|
|
9047
|
+
* stored secret (the records door reads a view as KEEP).
|
|
9048
|
+
*
|
|
9049
|
+
* ONE implementation for the entries service and for every addon that serves
|
|
9050
|
+
* its own instances (`RecordIntegrationInstances`).
|
|
9051
|
+
*/
|
|
9052
|
+
function isRecord$3(value) {
|
|
9053
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
9054
|
+
}
|
|
9055
|
+
function secretViewsOf(owner, kind, id, decl, data) {
|
|
9056
|
+
if (decl.secretPaths.length === 0) return data;
|
|
9057
|
+
const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
|
|
9058
|
+
if (leaf.value !== "__camstack_redacted__") return leaf.value;
|
|
9059
|
+
return {
|
|
9060
|
+
$secret: recordSecretRef(owner, kind, id, leaf.concrete),
|
|
9061
|
+
v: 1,
|
|
9062
|
+
set: true
|
|
9063
|
+
};
|
|
9064
|
+
});
|
|
9065
|
+
return isRecord$3(shown) ? shown : data;
|
|
9066
|
+
}
|
|
8671
9067
|
/**
|
|
8672
9068
|
* The share-view scope kinds a share-link token can carry. The hub mints
|
|
8673
9069
|
* and validates them (`ShareViewGrantSchema` builds its
|
|
@@ -8692,6 +9088,75 @@ var PeerBytesTicketSchema = object({
|
|
|
8692
9088
|
*/
|
|
8693
9089
|
declaredBytes: number().int().nonnegative().nullable()
|
|
8694
9090
|
});
|
|
9091
|
+
function defOf(schema) {
|
|
9092
|
+
const zodBag = Reflect.get(schema, "_zod");
|
|
9093
|
+
if (typeof zodBag !== "object" || zodBag === null) return {};
|
|
9094
|
+
const def = Reflect.get(zodBag, "def");
|
|
9095
|
+
if (typeof def !== "object" || def === null) return {};
|
|
9096
|
+
return def;
|
|
9097
|
+
}
|
|
9098
|
+
function declaredHere(schema) {
|
|
9099
|
+
return globalRegistry.get(schema)?.secret === true;
|
|
9100
|
+
}
|
|
9101
|
+
/** Wrapper kinds whose `innerType` is the field itself. */
|
|
9102
|
+
var WRAPPERS = new Set([
|
|
9103
|
+
"optional",
|
|
9104
|
+
"nullable",
|
|
9105
|
+
"default",
|
|
9106
|
+
"prefault",
|
|
9107
|
+
"catch",
|
|
9108
|
+
"readonly",
|
|
9109
|
+
"nonoptional"
|
|
9110
|
+
]);
|
|
9111
|
+
/**
|
|
9112
|
+
* The schema layers that make up ONE field: the schema itself and every
|
|
9113
|
+
* wrapper below it (optional / default / nullable / readonly / catch), plus
|
|
9114
|
+
* both sides of a pipe (`z.preprocess` puts the real schema on `out`,
|
|
9115
|
+
* `.transform` on `in`).
|
|
9116
|
+
*/
|
|
9117
|
+
function layersOf(schema) {
|
|
9118
|
+
const out = [];
|
|
9119
|
+
const queue = [schema];
|
|
9120
|
+
while (queue.length > 0) {
|
|
9121
|
+
const s = queue.shift();
|
|
9122
|
+
if (!s || out.includes(s)) continue;
|
|
9123
|
+
out.push(s);
|
|
9124
|
+
const def = defOf(s);
|
|
9125
|
+
if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
|
|
9126
|
+
if (def.type === "pipe") {
|
|
9127
|
+
if (def.in) queue.push(def.in);
|
|
9128
|
+
if (def.out) queue.push(def.out);
|
|
9129
|
+
}
|
|
9130
|
+
}
|
|
9131
|
+
return out;
|
|
9132
|
+
}
|
|
9133
|
+
/** True when any layer of this field declares `.meta({ secret: true })`. */
|
|
9134
|
+
function isZodSecret(schema) {
|
|
9135
|
+
return layersOf(schema).some(declaredHere);
|
|
9136
|
+
}
|
|
9137
|
+
/**
|
|
9138
|
+
* Every declared secret path in a config schema: dotted keys, `[]` for "each
|
|
9139
|
+
* element of this array" (`connection.password`, `rows[].token`), `{}` for "each value of this
|
|
9140
|
+
* map" (`applianceSecrets{}`). A declared
|
|
9141
|
+
* object or array is reported as one path and not descended into — everything
|
|
9142
|
+
* under it is secret.
|
|
9143
|
+
*/
|
|
9144
|
+
function collectZodSecretPaths(schema, prefix = "") {
|
|
9145
|
+
if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
|
|
9146
|
+
const paths = [];
|
|
9147
|
+
for (const layer of layersOf(schema)) {
|
|
9148
|
+
const def = defOf(layer);
|
|
9149
|
+
if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
|
|
9150
|
+
else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
|
|
9151
|
+
else if (def.type === "record" && def.valueType) paths.push(...collectZodSecretPaths(def.valueType, `${prefix}{}`));
|
|
9152
|
+
else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
|
|
9153
|
+
else if (def.type === "intersection") {
|
|
9154
|
+
if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
|
|
9155
|
+
if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
|
|
9156
|
+
}
|
|
9157
|
+
}
|
|
9158
|
+
return [...new Set(paths)];
|
|
9159
|
+
}
|
|
8695
9160
|
/**
|
|
8696
9161
|
* Record kinds (D881): the declaration an addon makes of one kind of fact, the
|
|
8697
9162
|
* Zod row schema that describes it, and the helper that turns the two into the
|
|
@@ -8758,6 +9223,112 @@ var RecordKindDeclarationSchema = object({
|
|
|
8758
9223
|
}).strict();
|
|
8759
9224
|
/** The kind names: lower-case, dash separated, short enough for an index name. */
|
|
8760
9225
|
var RecordKindNameSchema = string().regex(/^[a-z][a-z0-9-]{0,47}$/);
|
|
9226
|
+
/** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
|
|
9227
|
+
function assertValidDeclaration(name, decl) {
|
|
9228
|
+
const refuse = (why) => {
|
|
9229
|
+
throw new DeclarationRefusedError(`kind "${name}": ${why}`);
|
|
9230
|
+
};
|
|
9231
|
+
if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
|
|
9232
|
+
const seen = /* @__PURE__ */ new Set();
|
|
9233
|
+
for (const index of decl.indexes) {
|
|
9234
|
+
if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
|
|
9235
|
+
seen.add(index.name);
|
|
9236
|
+
}
|
|
9237
|
+
const { retention } = decl;
|
|
9238
|
+
const hasSecrets = decl.secretPaths.length > 0;
|
|
9239
|
+
if ("ttlMs" in retention) {
|
|
9240
|
+
if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
|
|
9241
|
+
if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
|
|
9242
|
+
}
|
|
9243
|
+
if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
|
|
9244
|
+
if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
|
|
9245
|
+
if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
|
|
9246
|
+
if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
|
|
9247
|
+
const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
|
|
9248
|
+
if (decl.database === "settings" && bound > 5e4) refuse(`a row bound above ${RECORD_SETTINGS_MAX_ROWS} belongs in database: "events" (a big delete on the settings thread stalls every configuration read)`);
|
|
9249
|
+
}
|
|
9250
|
+
if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
|
|
9251
|
+
for (const path of decl.secretPaths) for (const prefix of secretArrayPrefixes(path)) if (decl.secretArrayKeys[prefix] === void 0) refuse(`secret path "${path}" crosses the array "${prefix}": declare its id key in secretArrayKeys`);
|
|
9252
|
+
}
|
|
9253
|
+
function bodyFieldsOf(schema) {
|
|
9254
|
+
return { ...toJSONSchema(schema, {
|
|
9255
|
+
unrepresentable: "any",
|
|
9256
|
+
io: "input"
|
|
9257
|
+
}) };
|
|
9258
|
+
}
|
|
9259
|
+
function isRecordLike(value) {
|
|
9260
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
9261
|
+
}
|
|
9262
|
+
/** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
|
|
9263
|
+
function hasNameField(json, field) {
|
|
9264
|
+
const branches = json["oneOf"] ?? json["anyOf"];
|
|
9265
|
+
if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
|
|
9266
|
+
const properties = json["properties"];
|
|
9267
|
+
return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
|
|
9268
|
+
}
|
|
9269
|
+
/**
|
|
9270
|
+
* Declare the kinds of a package. The keys are the kind names. The result is
|
|
9271
|
+
* what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
|
|
9272
|
+
* types its handle from.
|
|
9273
|
+
*/
|
|
9274
|
+
function defineRecordKinds(specs) {
|
|
9275
|
+
const out = {};
|
|
9276
|
+
for (const [name, spec] of Object.entries(specs)) {
|
|
9277
|
+
const secretPaths = collectZodSecretPaths(spec.schema);
|
|
9278
|
+
const nameField = spec.entry?.nameField ?? "name";
|
|
9279
|
+
const fields = bodyFieldsOf(spec.schema);
|
|
9280
|
+
if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
|
|
9281
|
+
const parsed = RecordKindDeclarationSchema.parse({
|
|
9282
|
+
database: spec.database,
|
|
9283
|
+
class: spec.class,
|
|
9284
|
+
writeTrigger: spec.writeTrigger,
|
|
9285
|
+
device: spec.device,
|
|
9286
|
+
at: spec.at,
|
|
9287
|
+
indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
|
|
9288
|
+
retention: spec.retention,
|
|
9289
|
+
deviceRemoval: spec.deviceRemoval,
|
|
9290
|
+
maxDataBytes: spec.maxDataBytes,
|
|
9291
|
+
secretPaths: [...new Set([...secretPaths, ...spec.retiredSecretPaths ?? []])],
|
|
9292
|
+
secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
|
|
9293
|
+
transactFamily: spec.transactFamily,
|
|
9294
|
+
entry: spec.entry === void 0 ? void 0 : {
|
|
9295
|
+
title: spec.entry.title,
|
|
9296
|
+
nameField,
|
|
9297
|
+
fields
|
|
9298
|
+
}
|
|
9299
|
+
});
|
|
9300
|
+
assertValidDeclaration(name, parsed);
|
|
9301
|
+
out[name] = {
|
|
9302
|
+
name,
|
|
9303
|
+
schema: spec.schema,
|
|
9304
|
+
declaration: parsed
|
|
9305
|
+
};
|
|
9306
|
+
}
|
|
9307
|
+
return out;
|
|
9308
|
+
}
|
|
9309
|
+
/**
|
|
9310
|
+
* Declare one entry kind. An entry is configuration: never trimmed by the
|
|
9311
|
+
* engine, never aged, belonging to no device.
|
|
9312
|
+
*/
|
|
9313
|
+
function defineEntryKind(name, spec) {
|
|
9314
|
+
const defined = defineRecordKinds({ [name]: {
|
|
9315
|
+
schema: spec.schema,
|
|
9316
|
+
class: "config",
|
|
9317
|
+
writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
|
|
9318
|
+
retention: { none: "an entry goes only when the operator deletes it" },
|
|
9319
|
+
...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
|
|
9320
|
+
...spec.database === void 0 ? {} : { database: spec.database },
|
|
9321
|
+
...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
|
|
9322
|
+
...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
|
|
9323
|
+
...spec.retiredSecretPaths === void 0 ? {} : { retiredSecretPaths: spec.retiredSecretPaths },
|
|
9324
|
+
entry: {
|
|
9325
|
+
title: spec.title,
|
|
9326
|
+
...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
|
|
9327
|
+
}
|
|
9328
|
+
} })[name];
|
|
9329
|
+
if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
|
|
9330
|
+
return defined;
|
|
9331
|
+
}
|
|
8761
9332
|
object({
|
|
8762
9333
|
field: string().min(1),
|
|
8763
9334
|
on: literal("advance")
|
|
@@ -12875,6 +13446,205 @@ function buildCapturingReply(envelope) {
|
|
|
12875
13446
|
};
|
|
12876
13447
|
return wrapper;
|
|
12877
13448
|
}
|
|
13449
|
+
/**
|
|
13450
|
+
* `RecordIntegrationInstances` - the `integration-instances` provider over ONE
|
|
13451
|
+
* entry kind, so an addon that holds a connection serves it in ~30 lines.
|
|
13452
|
+
*
|
|
13453
|
+
* Every instance is one record of the addon's own kind, keyed by the
|
|
13454
|
+
* `integrations` registry id. The records door does the secret work: a field the
|
|
13455
|
+
* kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
|
|
13456
|
+
* deleting the row deletes the secret, and one row's value is never another's.
|
|
13457
|
+
*
|
|
13458
|
+
* Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
|
|
13459
|
+
* token or the view the form was given KEEP the stored secret;
|
|
13460
|
+
* `{ $secretClear: true }` clears it; any other string replaces it.
|
|
13461
|
+
*/
|
|
13462
|
+
/** The most instances one addon lists (an integrations page, not a table). */
|
|
13463
|
+
var INSTANCES_LIST_MAX = 1e3;
|
|
13464
|
+
/** The keys of the kind's secret fields that sit at the top level of the body. */
|
|
13465
|
+
function topLevelSecretKeys(paths) {
|
|
13466
|
+
return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
|
|
13467
|
+
}
|
|
13468
|
+
/** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
|
|
13469
|
+
function secretMapKeys(paths) {
|
|
13470
|
+
return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
|
|
13471
|
+
}
|
|
13472
|
+
/**
|
|
13473
|
+
* A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
|
|
13474
|
+
* view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
|
|
13475
|
+
* or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
|
|
13476
|
+
*/
|
|
13477
|
+
function secretMapPatch(value) {
|
|
13478
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
|
13479
|
+
const out = {};
|
|
13480
|
+
for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
|
|
13481
|
+
else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
|
|
13482
|
+
return Object.keys(out).length > 0 ? out : null;
|
|
13483
|
+
}
|
|
13484
|
+
/** Does the kind's body schema carry an `enabled` field? */
|
|
13485
|
+
function declaresEnabled(kind) {
|
|
13486
|
+
const json = toJSONSchema(kind.schema, {
|
|
13487
|
+
unrepresentable: "any",
|
|
13488
|
+
io: "input"
|
|
13489
|
+
});
|
|
13490
|
+
const properties = Reflect.get(json, "properties");
|
|
13491
|
+
return typeof properties === "object" && properties !== null && "enabled" in properties;
|
|
13492
|
+
}
|
|
13493
|
+
var RecordIntegrationInstances = class {
|
|
13494
|
+
records;
|
|
13495
|
+
kind;
|
|
13496
|
+
hooks;
|
|
13497
|
+
handle;
|
|
13498
|
+
secretKeys;
|
|
13499
|
+
secretMaps;
|
|
13500
|
+
nameField;
|
|
13501
|
+
/** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
|
|
13502
|
+
registryOwnsEnabled;
|
|
13503
|
+
constructor(records, kind, hooks) {
|
|
13504
|
+
this.records = records;
|
|
13505
|
+
this.kind = kind;
|
|
13506
|
+
this.hooks = hooks;
|
|
13507
|
+
this.handle = records.kind(kind);
|
|
13508
|
+
this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
|
|
13509
|
+
this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
|
|
13510
|
+
this.nameField = kind.declaration.entry?.nameField ?? "name";
|
|
13511
|
+
this.registryOwnsEnabled = hooks.description.role === "devices";
|
|
13512
|
+
if (this.registryOwnsEnabled && declaresEnabled(kind)) throw new Error(`kind "${kind.name}": the integrations registry owns the on/off switch of a role "devices" addon, so the body must not declare "enabled"`);
|
|
13513
|
+
}
|
|
13514
|
+
/**
|
|
13515
|
+
* One instance read for the addon's own runtime; null when absent. When the keychain is
|
|
13516
|
+
* locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
|
|
13517
|
+
* caller can keep what it had instead of reconfiguring with an empty secret (D49).
|
|
13518
|
+
*/
|
|
13519
|
+
async readResolved(id) {
|
|
13520
|
+
try {
|
|
13521
|
+
const record = await this.handle.getResolved(id);
|
|
13522
|
+
return record === null ? null : {
|
|
13523
|
+
id,
|
|
13524
|
+
body: record.data,
|
|
13525
|
+
enabled: record.data.enabled !== false,
|
|
13526
|
+
secrets: "resolved"
|
|
13527
|
+
};
|
|
13528
|
+
} catch (err) {
|
|
13529
|
+
if (!(err instanceof RecordSecretUnavailableError)) throw err;
|
|
13530
|
+
const stored = await this.handle.get(id);
|
|
13531
|
+
if (stored === null) return null;
|
|
13532
|
+
return {
|
|
13533
|
+
id,
|
|
13534
|
+
body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
|
|
13535
|
+
enabled: stored.data.enabled !== false,
|
|
13536
|
+
secrets: "unavailable"
|
|
13537
|
+
};
|
|
13538
|
+
}
|
|
13539
|
+
}
|
|
13540
|
+
/** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
|
|
13541
|
+
async getResolved(id) {
|
|
13542
|
+
return (await this.readResolved(id))?.body ?? null;
|
|
13543
|
+
}
|
|
13544
|
+
/** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
|
|
13545
|
+
async listResolved() {
|
|
13546
|
+
const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
|
|
13547
|
+
const out = [];
|
|
13548
|
+
for (const record of page.records) {
|
|
13549
|
+
const read = await this.readResolved(record.id);
|
|
13550
|
+
if (read !== null) out.push(read);
|
|
13551
|
+
}
|
|
13552
|
+
return out;
|
|
13553
|
+
}
|
|
13554
|
+
viewOf(record) {
|
|
13555
|
+
const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
|
|
13556
|
+
const rawName = record.data[this.nameField];
|
|
13557
|
+
const kind = this.hooks.kindOf?.(record.data);
|
|
13558
|
+
const health = this.hooks.health?.(record.data, record.id);
|
|
13559
|
+
return {
|
|
13560
|
+
id: record.id,
|
|
13561
|
+
name: typeof rawName === "string" ? rawName : record.id,
|
|
13562
|
+
configured: this.hooks.configured(record.data),
|
|
13563
|
+
...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
|
|
13564
|
+
formValues: shown,
|
|
13565
|
+
...kind !== void 0 ? { kind } : {},
|
|
13566
|
+
...health?.status !== void 0 ? { status: health.status } : {},
|
|
13567
|
+
...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
|
|
13568
|
+
};
|
|
13569
|
+
}
|
|
13570
|
+
describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
|
|
13571
|
+
...this.hooks.description,
|
|
13572
|
+
mintsId: true
|
|
13573
|
+
};
|
|
13574
|
+
instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
|
|
13575
|
+
listInstances = async () => {
|
|
13576
|
+
return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
|
|
13577
|
+
};
|
|
13578
|
+
getInstance = async ({ id }) => {
|
|
13579
|
+
const record = await this.handle.get(id);
|
|
13580
|
+
return record === null ? null : this.viewOf(record);
|
|
13581
|
+
};
|
|
13582
|
+
/** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
|
|
13583
|
+
createInstance = async ({ id, name, kind }) => {
|
|
13584
|
+
const minted = id ?? this.hooks.mintId?.({
|
|
13585
|
+
name,
|
|
13586
|
+
...kind !== void 0 ? { kind } : {}
|
|
13587
|
+
});
|
|
13588
|
+
if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
|
|
13589
|
+
await this.handle.put({
|
|
13590
|
+
id: minted,
|
|
13591
|
+
data: this.hooks.initialBody(name, kind)
|
|
13592
|
+
}, { ifRev: 0 });
|
|
13593
|
+
await this.hooks.onChanged?.(minted, "created");
|
|
13594
|
+
return { id: minted };
|
|
13595
|
+
};
|
|
13596
|
+
updateInstance = async ({ id, name, values }) => {
|
|
13597
|
+
const patch = {};
|
|
13598
|
+
for (const [key, value] of Object.entries(values)) {
|
|
13599
|
+
if (value === void 0) continue;
|
|
13600
|
+
if (this.secretMaps.has(key)) {
|
|
13601
|
+
const entries = secretMapPatch(value);
|
|
13602
|
+
if (entries !== null) patch[key] = entries;
|
|
13603
|
+
} else if (!this.secretKeys.has(key)) patch[key] = value;
|
|
13604
|
+
else if (isSecretClear(value)) patch[key] = null;
|
|
13605
|
+
else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
|
|
13606
|
+
}
|
|
13607
|
+
if (name !== void 0) patch[this.nameField] = name;
|
|
13608
|
+
await this.handle.patch(id, patch);
|
|
13609
|
+
await this.hooks.onChanged?.(id, "updated");
|
|
13610
|
+
return { ok: true };
|
|
13611
|
+
};
|
|
13612
|
+
/** The switch lives in the record body; the addon is told so it applies it (D996). */
|
|
13613
|
+
setInstanceEnabled = async ({ id, enabled }) => {
|
|
13614
|
+
if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
|
|
13615
|
+
await this.handle.patch(id, { enabled });
|
|
13616
|
+
await this.hooks.onChanged?.(id, "enabled");
|
|
13617
|
+
return { ok: true };
|
|
13618
|
+
};
|
|
13619
|
+
/** The row and its keychain refs go together (the records door). */
|
|
13620
|
+
deleteInstance = async ({ id }) => {
|
|
13621
|
+
await this.handle.delete(id);
|
|
13622
|
+
await this.hooks.onChanged?.(id, "deleted");
|
|
13623
|
+
return { ok: true };
|
|
13624
|
+
};
|
|
13625
|
+
testInstance = async (input) => {
|
|
13626
|
+
if (this.hooks.test === void 0) return {
|
|
13627
|
+
success: false,
|
|
13628
|
+
status: "unsupported",
|
|
13629
|
+
error: "This integration declares no connection test"
|
|
13630
|
+
};
|
|
13631
|
+
return this.hooks.test(input);
|
|
13632
|
+
};
|
|
13633
|
+
/** The flat provider object to hand to `registerProvider`. */
|
|
13634
|
+
toProvider() {
|
|
13635
|
+
return {
|
|
13636
|
+
describe: this.describe,
|
|
13637
|
+
instanceFormSchema: this.instanceFormSchema,
|
|
13638
|
+
listInstances: this.listInstances,
|
|
13639
|
+
getInstance: this.getInstance,
|
|
13640
|
+
createInstance: this.createInstance,
|
|
13641
|
+
updateInstance: this.updateInstance,
|
|
13642
|
+
setInstanceEnabled: this.setInstanceEnabled,
|
|
13643
|
+
deleteInstance: this.deleteInstance,
|
|
13644
|
+
testInstance: this.testInstance
|
|
13645
|
+
};
|
|
13646
|
+
}
|
|
13647
|
+
};
|
|
12878
13648
|
var EncodeProfileSchema = object({
|
|
12879
13649
|
video: object({
|
|
12880
13650
|
codec: _enum([
|
|
@@ -13920,7 +14690,13 @@ var MigrationLedgerEntrySchema = object({
|
|
|
13920
14690
|
* joined by the engine from the catalogues it knows this boot. Absent when no
|
|
13921
14691
|
* catalogue lists the id (a newer database).
|
|
13922
14692
|
*/
|
|
13923
|
-
meta: MigrationMetaSchema.optional()
|
|
14693
|
+
meta: MigrationMetaSchema.optional(),
|
|
14694
|
+
/**
|
|
14695
|
+
* Set when this is an applied row of an addon owner whose catalogue the answering
|
|
14696
|
+
* process has not loaded (the owner has not declared yet): the row is applied, the
|
|
14697
|
+
* process just cannot judge it. Never `skipped-newer` — that needs the owner loaded.
|
|
14698
|
+
*/
|
|
14699
|
+
ownerNotLoaded: boolean().optional()
|
|
13924
14700
|
});
|
|
13925
14701
|
/** A catalogued migration that is not applied, with where it stands. */
|
|
13926
14702
|
var MigrationPendingEntrySchema = object({
|
|
@@ -49702,13 +50478,6 @@ var ExportInstanceUnknownError = class extends Error {
|
|
|
49702
50478
|
function statusInstanceOf(input) {
|
|
49703
50479
|
return "instanceId" in input ? input.instanceId : void 0;
|
|
49704
50480
|
}
|
|
49705
|
-
/**
|
|
49706
|
-
* A single-instance provider's check: an absent id or its own passes, any other throws
|
|
49707
|
-
* `ExportInstanceUnknownError`.
|
|
49708
|
-
*/
|
|
49709
|
-
function assertOwnExportInstance(addon, own, instanceId) {
|
|
49710
|
-
if (instanceId !== void 0 && instanceId !== own) throw new ExportInstanceUnknownError(addon, instanceId);
|
|
49711
|
-
}
|
|
49712
50481
|
var LinkStateSchema = _enum([
|
|
49713
50482
|
"unlinked",
|
|
49714
50483
|
"linked",
|
|
@@ -53544,6 +54313,12 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
|
|
|
53544
54313
|
}), object({ success: boolean() }), {
|
|
53545
54314
|
kind: "mutation",
|
|
53546
54315
|
auth: "admin"
|
|
54316
|
+
}), method(object({ id: string() }), object({
|
|
54317
|
+
rows: number().int().nonnegative(),
|
|
54318
|
+
secrets: number().int().nonnegative()
|
|
54319
|
+
}), {
|
|
54320
|
+
kind: "mutation",
|
|
54321
|
+
auth: "admin"
|
|
53547
54322
|
}), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
|
|
53548
54323
|
addonId: string(),
|
|
53549
54324
|
settings: record(string(), unknown())
|
|
@@ -53595,6 +54370,21 @@ var IntegrationInstanceKindSchema = object({
|
|
|
53595
54370
|
disconnectPath: string().min(1).optional()
|
|
53596
54371
|
});
|
|
53597
54372
|
var IntegrationInstanceDescriptionSchema = object({
|
|
54373
|
+
/** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
|
|
54374
|
+
role: _enum([
|
|
54375
|
+
"devices",
|
|
54376
|
+
"services",
|
|
54377
|
+
"both"
|
|
54378
|
+
]),
|
|
54379
|
+
/** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
|
|
54380
|
+
discovery: object({
|
|
54381
|
+
mode: _enum([
|
|
54382
|
+
"none",
|
|
54383
|
+
"lan",
|
|
54384
|
+
"account"
|
|
54385
|
+
]),
|
|
54386
|
+
scopedToInstance: boolean()
|
|
54387
|
+
}).optional(),
|
|
53598
54388
|
/** `single`: at most one instance can exist (Loki). `multiple`: an account each. */
|
|
53599
54389
|
instanceMode: IntegrationInstanceModeSchema,
|
|
53600
54390
|
/** What the instance is, for the UI (`destination`, `relay`, `account`). */
|
|
@@ -53634,10 +54424,11 @@ var IntegrationInstanceSchema = object({
|
|
|
53634
54424
|
/** The addon's own rule (an URL is present, a client id is present...). */
|
|
53635
54425
|
configured: boolean(),
|
|
53636
54426
|
/**
|
|
53637
|
-
* The instance's own on/off switch (D996)
|
|
53638
|
-
*
|
|
54427
|
+
* The instance's own on/off switch (D996), derived from the record body (`enabled !== false`,
|
|
54428
|
+
* so a row written before the field existed is on). Absent when the `integrations` registry
|
|
54429
|
+
* owns the switch (`describe().role` is `devices`): read it from the registry row.
|
|
53639
54430
|
*/
|
|
53640
|
-
enabled: boolean(),
|
|
54431
|
+
enabled: boolean().optional(),
|
|
53641
54432
|
/** The kind of this instance (one of `describe().kinds[].id`), when the provider has kinds. */
|
|
53642
54433
|
kind: string().optional(),
|
|
53643
54434
|
/** Values for the instance form; a secret is a `SecretFieldView`, never text. */
|
|
@@ -53652,32 +54443,57 @@ var IntegrationInstancePatchSchema = object({
|
|
|
53652
54443
|
/** Omitted / '' / redaction token keeps a secret; `{ $secretClear: true }` clears it. */
|
|
53653
54444
|
values: record(string(), unknown())
|
|
53654
54445
|
});
|
|
53655
|
-
|
|
53656
|
-
|
|
53657
|
-
|
|
53658
|
-
|
|
53659
|
-
|
|
53660
|
-
|
|
53661
|
-
|
|
53662
|
-
|
|
53663
|
-
|
|
53664
|
-
|
|
53665
|
-
|
|
53666
|
-
|
|
53667
|
-
|
|
53668
|
-
|
|
53669
|
-
|
|
53670
|
-
|
|
53671
|
-
|
|
53672
|
-
|
|
53673
|
-
|
|
53674
|
-
|
|
53675
|
-
|
|
53676
|
-
|
|
53677
|
-
}),
|
|
53678
|
-
|
|
53679
|
-
|
|
53680
|
-
})
|
|
54446
|
+
var integrationInstancesCapability = {
|
|
54447
|
+
name: "integration-instances",
|
|
54448
|
+
scope: "system",
|
|
54449
|
+
mode: "collection",
|
|
54450
|
+
methods: {
|
|
54451
|
+
describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
|
|
54452
|
+
/** The form; `id: null` is the create form. */
|
|
54453
|
+
instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
|
|
54454
|
+
listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
|
|
54455
|
+
getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
|
|
54456
|
+
/**
|
|
54457
|
+
* Insert the typed record. With `id` it is stored under that id (a duplicate id is refused);
|
|
54458
|
+
* without one the PROVIDER mints it and answers it. `kind` picks one of `describe().kinds`.
|
|
54459
|
+
*/
|
|
54460
|
+
createInstance: method(object({
|
|
54461
|
+
id: IntegrationInstanceIdSchema.optional(),
|
|
54462
|
+
name: string().min(1),
|
|
54463
|
+
kind: string().min(1).optional()
|
|
54464
|
+
}), object({ id: string() }), {
|
|
54465
|
+
kind: "mutation",
|
|
54466
|
+
auth: "admin"
|
|
54467
|
+
}),
|
|
54468
|
+
updateInstance: method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
|
|
54469
|
+
kind: "mutation",
|
|
54470
|
+
auth: "admin"
|
|
54471
|
+
}),
|
|
54472
|
+
/**
|
|
54473
|
+
* Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
|
|
54474
|
+
* form patch (D62, D996). An off instance keeps its record and secrets and does no work.
|
|
54475
|
+
*/
|
|
54476
|
+
setInstanceEnabled: method(object({
|
|
54477
|
+
id: IntegrationInstanceIdSchema,
|
|
54478
|
+
enabled: boolean()
|
|
54479
|
+
}), object({ ok: literal(true) }), {
|
|
54480
|
+
kind: "mutation",
|
|
54481
|
+
auth: "admin"
|
|
54482
|
+
}),
|
|
54483
|
+
/** Delete the record and its keychain refs together. */
|
|
54484
|
+
deleteInstance: method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
|
|
54485
|
+
kind: "mutation",
|
|
54486
|
+
auth: "admin"
|
|
54487
|
+
}),
|
|
54488
|
+
testInstance: optionalMethod(object({
|
|
54489
|
+
id: IntegrationInstanceIdSchema.nullable(),
|
|
54490
|
+
values: record(string(), unknown())
|
|
54491
|
+
}), TestConnectionResultSchema$1, {
|
|
54492
|
+
kind: "mutation",
|
|
54493
|
+
auth: "admin"
|
|
54494
|
+
})
|
|
54495
|
+
}
|
|
54496
|
+
};
|
|
53681
54497
|
/**
|
|
53682
54498
|
* Two-way audio / talk-back cap. Clients open a WebRTC audio-only
|
|
53683
54499
|
* session (server-initiated offer pattern, identical to the main
|
|
@@ -79146,6 +79962,13 @@ Object.freeze({
|
|
|
79146
79962
|
access: "create",
|
|
79147
79963
|
role: "admin"
|
|
79148
79964
|
},
|
|
79965
|
+
"integrations.clearSettings": {
|
|
79966
|
+
capName: "integrations",
|
|
79967
|
+
capScope: "system",
|
|
79968
|
+
addonId: null,
|
|
79969
|
+
access: "delete",
|
|
79970
|
+
role: "admin"
|
|
79971
|
+
},
|
|
79149
79972
|
"integrations.create": {
|
|
79150
79973
|
capName: "integrations",
|
|
79151
79974
|
capScope: "system",
|
|
@@ -90658,6 +91481,246 @@ var ActionSceneExports = class {
|
|
|
90658
91481
|
}
|
|
90659
91482
|
};
|
|
90660
91483
|
//#endregion
|
|
91484
|
+
//#region src/export-records.ts
|
|
91485
|
+
/**
|
|
91486
|
+
* What the Google export exposes, as a record (planning#408 P4): ONE `google-exports` record per
|
|
91487
|
+
* instance id (`export-google` today) holds the devices Google syncs and the actions it sees as
|
|
91488
|
+
* scenes. The addon is its only writer; the in-memory copy it loads at boot is what every
|
|
91489
|
+
* fulfillment intent reads.
|
|
91490
|
+
*/
|
|
91491
|
+
/**
|
|
91492
|
+
* The id the first Google Home instance keeps: the one every record and every pasted fulfillment
|
|
91493
|
+
* URL was created under. New instances get minted ids; the legacy `/fulfillment` route answers
|
|
91494
|
+
* for this one.
|
|
91495
|
+
*/
|
|
91496
|
+
var GOOGLE_INSTANCE_ID = "export-google";
|
|
91497
|
+
var ExposedDeviceEntrySchema = object({
|
|
91498
|
+
deviceId: number(),
|
|
91499
|
+
exposedAt: number()
|
|
91500
|
+
});
|
|
91501
|
+
var ActionSceneEntrySchema = object({
|
|
91502
|
+
actionId: string(),
|
|
91503
|
+
displayName: string(),
|
|
91504
|
+
addedAt: number()
|
|
91505
|
+
});
|
|
91506
|
+
var GoogleExportsBodySchema = object({
|
|
91507
|
+
name: string().min(1),
|
|
91508
|
+
devices: array(ExposedDeviceEntrySchema),
|
|
91509
|
+
actions: array(ActionSceneEntrySchema)
|
|
91510
|
+
});
|
|
91511
|
+
var GOOGLE_EXPORTS_KIND_NAME = "google-exports";
|
|
91512
|
+
var GOOGLE_EXPORTS_NAME = "Google exposure";
|
|
91513
|
+
var googleExportsKind = defineEntryKind(GOOGLE_EXPORTS_KIND_NAME, {
|
|
91514
|
+
title: "Google exposure",
|
|
91515
|
+
nameField: "name",
|
|
91516
|
+
schema: GoogleExportsBodySchema
|
|
91517
|
+
});
|
|
91518
|
+
var EMPTY_GOOGLE_EXPORTS = {
|
|
91519
|
+
name: GOOGLE_EXPORTS_NAME,
|
|
91520
|
+
devices: [],
|
|
91521
|
+
actions: []
|
|
91522
|
+
};
|
|
91523
|
+
/** The settings keys that moved into the record; the migrations name them. */
|
|
91524
|
+
var MOVED_EXPOSURE_KEYS = ["exposed", "exposedActions"];
|
|
91525
|
+
var GoogleHomeBodySchema = object({
|
|
91526
|
+
name: string().min(1),
|
|
91527
|
+
enabled: boolean().optional()
|
|
91528
|
+
});
|
|
91529
|
+
var GOOGLE_HOMES_KIND_NAME = "google-homes";
|
|
91530
|
+
var GOOGLE_HOME_NAME = "Google Home";
|
|
91531
|
+
var googleHomesKind = defineEntryKind(GOOGLE_HOMES_KIND_NAME, {
|
|
91532
|
+
title: "Google Home instances",
|
|
91533
|
+
nameField: "name",
|
|
91534
|
+
schema: GoogleHomeBodySchema
|
|
91535
|
+
});
|
|
91536
|
+
var LinkedAccountSchema = object({
|
|
91537
|
+
userId: string(),
|
|
91538
|
+
username: string(),
|
|
91539
|
+
linkedAt: number()
|
|
91540
|
+
});
|
|
91541
|
+
var GoogleLinksBodySchema = object({
|
|
91542
|
+
name: string().min(1),
|
|
91543
|
+
linkedAccounts: array(LinkedAccountSchema)
|
|
91544
|
+
});
|
|
91545
|
+
var GOOGLE_LINKS_KIND_NAME = "google-links";
|
|
91546
|
+
var GOOGLE_LINKS_NAME = "Google links";
|
|
91547
|
+
var googleLinksKind = defineEntryKind(GOOGLE_LINKS_KIND_NAME, {
|
|
91548
|
+
title: "Google linked accounts",
|
|
91549
|
+
nameField: "name",
|
|
91550
|
+
schema: GoogleLinksBodySchema
|
|
91551
|
+
});
|
|
91552
|
+
var EMPTY_GOOGLE_LINKS = {
|
|
91553
|
+
name: GOOGLE_LINKS_NAME,
|
|
91554
|
+
linkedAccounts: []
|
|
91555
|
+
};
|
|
91556
|
+
/** The settings key that moved into the `google-links` record; the migrations name it. */
|
|
91557
|
+
var MOVED_LINKS_KEY = "linkedAccounts";
|
|
91558
|
+
//#endregion
|
|
91559
|
+
//#region src/google-instance.ts
|
|
91560
|
+
/** The most instances one hub lists. */
|
|
91561
|
+
var INSTANCES_MAX = 1e3;
|
|
91562
|
+
var GoogleInstance = class {
|
|
91563
|
+
id;
|
|
91564
|
+
home;
|
|
91565
|
+
exportsRow;
|
|
91566
|
+
linksRow;
|
|
91567
|
+
stores;
|
|
91568
|
+
logger;
|
|
91569
|
+
scenes;
|
|
91570
|
+
tail = Promise.resolve();
|
|
91571
|
+
constructor(id, home, exportsRow, linksRow, stores, logger, makeScenes) {
|
|
91572
|
+
this.id = id;
|
|
91573
|
+
this.home = home;
|
|
91574
|
+
this.exportsRow = exportsRow;
|
|
91575
|
+
this.linksRow = linksRow;
|
|
91576
|
+
this.stores = stores;
|
|
91577
|
+
this.logger = logger;
|
|
91578
|
+
this.scenes = makeScenes((entries) => this.writeExports({ actions: [...entries] }), exportsRow.actions);
|
|
91579
|
+
}
|
|
91580
|
+
get name() {
|
|
91581
|
+
return this.home.name;
|
|
91582
|
+
}
|
|
91583
|
+
get enabled() {
|
|
91584
|
+
return this.home.enabled !== false;
|
|
91585
|
+
}
|
|
91586
|
+
get devices() {
|
|
91587
|
+
return this.exportsRow.devices;
|
|
91588
|
+
}
|
|
91589
|
+
get linkedAccounts() {
|
|
91590
|
+
return this.linksRow.linkedAccounts;
|
|
91591
|
+
}
|
|
91592
|
+
applyHome(home) {
|
|
91593
|
+
this.home = home;
|
|
91594
|
+
}
|
|
91595
|
+
isExposed(deviceId) {
|
|
91596
|
+
return this.exportsRow.devices.some((entry) => entry.deviceId === deviceId);
|
|
91597
|
+
}
|
|
91598
|
+
/** One write at a time per instance: two concurrent changes must not lose each other. */
|
|
91599
|
+
serial(work) {
|
|
91600
|
+
const run = this.tail.then(work, work);
|
|
91601
|
+
this.tail = run.catch(() => void 0);
|
|
91602
|
+
return run;
|
|
91603
|
+
}
|
|
91604
|
+
/** Persist a change of the exposure: the record first, the in-memory copy after it landed. */
|
|
91605
|
+
writeExports(patch) {
|
|
91606
|
+
return this.serial(async () => {
|
|
91607
|
+
const next = {
|
|
91608
|
+
name: this.exportsRow.name,
|
|
91609
|
+
devices: patch.devices ?? this.exportsRow.devices,
|
|
91610
|
+
actions: patch.actions ?? this.exportsRow.actions
|
|
91611
|
+
};
|
|
91612
|
+
await this.stores.exports.put({
|
|
91613
|
+
id: this.id,
|
|
91614
|
+
data: next
|
|
91615
|
+
});
|
|
91616
|
+
this.exportsRow = next;
|
|
91617
|
+
});
|
|
91618
|
+
}
|
|
91619
|
+
/** Google's SYNC is the first thing a completed link does: the only "linked" signal there is. */
|
|
91620
|
+
recordLink(caller) {
|
|
91621
|
+
return this.serial(async () => {
|
|
91622
|
+
if (this.linksRow.linkedAccounts.some((a) => a.userId === caller.userId)) return;
|
|
91623
|
+
const next = {
|
|
91624
|
+
name: this.linksRow.name,
|
|
91625
|
+
linkedAccounts: [...this.linksRow.linkedAccounts, {
|
|
91626
|
+
userId: caller.userId,
|
|
91627
|
+
username: caller.username,
|
|
91628
|
+
linkedAt: Date.now()
|
|
91629
|
+
}]
|
|
91630
|
+
};
|
|
91631
|
+
await this.stores.links.put({
|
|
91632
|
+
id: this.id,
|
|
91633
|
+
data: next
|
|
91634
|
+
});
|
|
91635
|
+
this.linksRow = next;
|
|
91636
|
+
this.logger.info("export-google: recorded linked account", { meta: {
|
|
91637
|
+
instanceId: this.id,
|
|
91638
|
+
userId: caller.userId
|
|
91639
|
+
} });
|
|
91640
|
+
});
|
|
91641
|
+
}
|
|
91642
|
+
removeLink(userId) {
|
|
91643
|
+
return this.serial(async () => {
|
|
91644
|
+
const kept = this.linksRow.linkedAccounts.filter((a) => a.userId !== userId);
|
|
91645
|
+
if (kept.length === this.linksRow.linkedAccounts.length) return;
|
|
91646
|
+
const next = {
|
|
91647
|
+
name: this.linksRow.name,
|
|
91648
|
+
linkedAccounts: kept
|
|
91649
|
+
};
|
|
91650
|
+
await this.stores.links.put({
|
|
91651
|
+
id: this.id,
|
|
91652
|
+
data: next
|
|
91653
|
+
});
|
|
91654
|
+
this.linksRow = next;
|
|
91655
|
+
});
|
|
91656
|
+
}
|
|
91657
|
+
};
|
|
91658
|
+
var GoogleInstanceRegistry = class {
|
|
91659
|
+
stores;
|
|
91660
|
+
logger;
|
|
91661
|
+
makeScenes;
|
|
91662
|
+
loaded = /* @__PURE__ */ new Map();
|
|
91663
|
+
loading = /* @__PURE__ */ new Map();
|
|
91664
|
+
constructor(stores, logger, makeScenes) {
|
|
91665
|
+
this.stores = stores;
|
|
91666
|
+
this.logger = logger;
|
|
91667
|
+
this.makeScenes = makeScenes;
|
|
91668
|
+
}
|
|
91669
|
+
/** The instance, loaded (home, exposure AND links) on first use; null when no such instance. */
|
|
91670
|
+
get(id) {
|
|
91671
|
+
const ready = this.loaded.get(id);
|
|
91672
|
+
if (ready !== void 0) return Promise.resolve(ready);
|
|
91673
|
+
const inFlight = this.loading.get(id);
|
|
91674
|
+
if (inFlight !== void 0) return inFlight;
|
|
91675
|
+
const started = this.load(id).finally(() => {
|
|
91676
|
+
this.loading.delete(id);
|
|
91677
|
+
});
|
|
91678
|
+
this.loading.set(id, started);
|
|
91679
|
+
return started;
|
|
91680
|
+
}
|
|
91681
|
+
/** An instance already loaded; never reads. */
|
|
91682
|
+
peek(id) {
|
|
91683
|
+
return this.loaded.get(id);
|
|
91684
|
+
}
|
|
91685
|
+
async load(id) {
|
|
91686
|
+
const home = await this.stores.homes.get(id);
|
|
91687
|
+
if (home === null) return null;
|
|
91688
|
+
const [exported, links] = await Promise.all([this.stores.exports.get(id), this.stores.links.get(id)]);
|
|
91689
|
+
const instance = new GoogleInstance(id, home.data, exported?.data ?? EMPTY_GOOGLE_EXPORTS, links?.data ?? EMPTY_GOOGLE_LINKS, this.stores, this.logger, this.makeScenes);
|
|
91690
|
+
this.loaded.set(id, instance);
|
|
91691
|
+
return instance;
|
|
91692
|
+
}
|
|
91693
|
+
/** Every instance row, as stored. */
|
|
91694
|
+
async list() {
|
|
91695
|
+
return (await this.stores.homes.query({ limit: INSTANCES_MAX })).records.map((record) => ({
|
|
91696
|
+
id: record.id,
|
|
91697
|
+
body: record.data
|
|
91698
|
+
}));
|
|
91699
|
+
}
|
|
91700
|
+
/** The instance row changed (name, switch): a loaded instance takes it. */
|
|
91701
|
+
async refreshHome(id) {
|
|
91702
|
+
const home = await this.stores.homes.get(id);
|
|
91703
|
+
const instance = this.loaded.get(id);
|
|
91704
|
+
if (home === null) {
|
|
91705
|
+
this.loaded.delete(id);
|
|
91706
|
+
return;
|
|
91707
|
+
}
|
|
91708
|
+
if (instance === void 0) {
|
|
91709
|
+
await this.get(id);
|
|
91710
|
+
return;
|
|
91711
|
+
}
|
|
91712
|
+
instance.applyHome(home.data);
|
|
91713
|
+
}
|
|
91714
|
+
/** The instance is gone: its exposure and links rows go with it, and nothing serves it. */
|
|
91715
|
+
async remove(id) {
|
|
91716
|
+
this.loaded.delete(id);
|
|
91717
|
+
this.loading.delete(id);
|
|
91718
|
+
await this.stores.exports.delete(id);
|
|
91719
|
+
await this.stores.links.delete(id);
|
|
91720
|
+
this.logger.info("export-google: instance deleted with its exposure and links", { meta: { instanceId: id } });
|
|
91721
|
+
}
|
|
91722
|
+
};
|
|
91723
|
+
//#endregion
|
|
90661
91724
|
//#region src/google-home/trait-catalog.ts
|
|
90662
91725
|
/**
|
|
90663
91726
|
* The trait catalog — one ROW per camstack capability, and that row is the
|
|
@@ -91341,11 +92404,17 @@ var OauthVerifiedResultSchema = object({
|
|
|
91341
92404
|
}).nullable();
|
|
91342
92405
|
function buildRoutes(deps) {
|
|
91343
92406
|
return [{
|
|
92407
|
+
method: "POST",
|
|
92408
|
+
path: "/fulfillment/:instanceId",
|
|
92409
|
+
access: "public",
|
|
92410
|
+
description: "Google Home smart-home fulfillment of one instance (SYNC / QUERY / EXECUTE / DISCONNECT)",
|
|
92411
|
+
handler: (req, reply) => handleFulfillmentRequest(req, reply, deps, req.params["instanceId"] ?? "")
|
|
92412
|
+
}, {
|
|
91344
92413
|
method: "POST",
|
|
91345
92414
|
path: "/fulfillment",
|
|
91346
92415
|
access: "public",
|
|
91347
|
-
description:
|
|
91348
|
-
handler: (req, reply) => handleFulfillmentRequest(req, reply, deps)
|
|
92416
|
+
description: `Legacy fulfillment URL: answers for the first instance (${GOOGLE_INSTANCE_ID})`,
|
|
92417
|
+
handler: (req, reply) => handleFulfillmentRequest(req, reply, deps, GOOGLE_INSTANCE_ID)
|
|
91349
92418
|
}];
|
|
91350
92419
|
}
|
|
91351
92420
|
/** Read `Authorization: Bearer <token>` case-insensitively. Node lower-cases
|
|
@@ -91357,7 +92426,7 @@ function readBearer(headers) {
|
|
|
91357
92426
|
}
|
|
91358
92427
|
return null;
|
|
91359
92428
|
}
|
|
91360
|
-
async function handleFulfillmentRequest(request, reply, deps) {
|
|
92429
|
+
async function handleFulfillmentRequest(request, reply, deps, instanceId) {
|
|
91361
92430
|
const bearer = readBearer(request.headers);
|
|
91362
92431
|
if (bearer === null) {
|
|
91363
92432
|
deps.logger.warn("google fulfillment: rejected — no bearer token");
|
|
@@ -91376,10 +92445,305 @@ async function handleFulfillmentRequest(request, reply, deps) {
|
|
|
91376
92445
|
username: verified.data.username,
|
|
91377
92446
|
scopes: verified.data.scopes
|
|
91378
92447
|
};
|
|
91379
|
-
const
|
|
92448
|
+
const lookup = await deps.resolveFulfillment(instanceId);
|
|
92449
|
+
if (!lookup.ok) {
|
|
92450
|
+
deps.logger.warn("google fulfillment: rejected — instance not served", { meta: {
|
|
92451
|
+
instanceId,
|
|
92452
|
+
reason: lookup.code
|
|
92453
|
+
} });
|
|
92454
|
+
reply.code(404).send({ error: lookup.code });
|
|
92455
|
+
return;
|
|
92456
|
+
}
|
|
92457
|
+
const result = await handleFulfillment(request.body, lookup.deps, caller);
|
|
91380
92458
|
reply.code(result.status).send(result.body);
|
|
91381
92459
|
}
|
|
91382
92460
|
//#endregion
|
|
92461
|
+
//#region src/migrations/drop-public-hub-url.ts
|
|
92462
|
+
/**
|
|
92463
|
+
* The hub's public URL is no longer a setting of this addon (D986 §5): Google reads the
|
|
92464
|
+
* `publicEndpoint` role of the local-network palette on every use. The two keys older
|
|
92465
|
+
* versions persisted are deleted. Every other key is left exactly as stored.
|
|
92466
|
+
*
|
|
92467
|
+
* Idempotent: a store without either key yields an empty plan, which writes nothing.
|
|
92468
|
+
*/
|
|
92469
|
+
/** The addon id, the prefix of its rows in the canonical settings table. */
|
|
92470
|
+
var GOOGLE_ADDON_ID = "export-google";
|
|
92471
|
+
/**
|
|
92472
|
+
* Where the addon's global settings live: the canonical `addon-settings` table, one row per
|
|
92473
|
+
* key, id `<addonId>.<key>`, data `{ addonId, key, value }` (never a per-addon scoped table,
|
|
92474
|
+
* which exists only when something lazily declared it).
|
|
92475
|
+
*/
|
|
92476
|
+
var ADDON_SETTINGS_TABLE = "addon-settings";
|
|
92477
|
+
var RETIRED_PUBLIC_URL_KEYS = ["publicHubUrl", "detectedPublicHubUrl"];
|
|
92478
|
+
async function planDropPublicHubUrl(ports) {
|
|
92479
|
+
const stored = await ports.readStored();
|
|
92480
|
+
const present = RETIRED_PUBLIC_URL_KEYS.filter((key) => key in stored);
|
|
92481
|
+
if (present.length === 0) return { edits: [] };
|
|
92482
|
+
const rowId = (key) => `${GOOGLE_ADDON_ID}.${key}`;
|
|
92483
|
+
return { edits: [{
|
|
92484
|
+
op: "deleteKeys",
|
|
92485
|
+
scope: ADDON_SETTINGS_TABLE,
|
|
92486
|
+
keys: present.map(rowId),
|
|
92487
|
+
precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
|
|
92488
|
+
addonId: GOOGLE_ADDON_ID,
|
|
92489
|
+
key,
|
|
92490
|
+
value: stored[key]
|
|
92491
|
+
}])))
|
|
92492
|
+
}] };
|
|
92493
|
+
}
|
|
92494
|
+
//#endregion
|
|
92495
|
+
//#region src/migrations/exposure-to-record.ts
|
|
92496
|
+
/**
|
|
92497
|
+
* The Google exposure lists move into the `google-exports` record (planning#408 P4). Two
|
|
92498
|
+
* migrations, both `block-owner`: the addon must not serve a membership it cannot trust, and
|
|
92499
|
+
* after them nothing reads the old keys.
|
|
92500
|
+
*
|
|
92501
|
+
* 1. `moveExposureToRecord` (procedure): `exposed` and `exposedActions` become the record under
|
|
92502
|
+
* the instance id. An existing record is never overwritten. A record this pass just wrote is
|
|
92503
|
+
* read BACK and must equal what the settings carried, or the pass throws.
|
|
92504
|
+
* 2. `planDropMovedExposure` (plan): the two keys are deleted only while the record holds every
|
|
92505
|
+
* device and action the settings carried; a record that cannot be read leaves them in place.
|
|
92506
|
+
*/
|
|
92507
|
+
function devicesOf(value) {
|
|
92508
|
+
if (!Array.isArray(value)) return [];
|
|
92509
|
+
return value.flatMap((entry) => {
|
|
92510
|
+
const parsed = ExposedDeviceEntrySchema.safeParse(entry);
|
|
92511
|
+
return parsed.success ? [parsed.data] : [];
|
|
92512
|
+
});
|
|
92513
|
+
}
|
|
92514
|
+
function actionsOf(value) {
|
|
92515
|
+
if (!Array.isArray(value)) return [];
|
|
92516
|
+
return value.flatMap((entry) => {
|
|
92517
|
+
const parsed = ActionSceneEntrySchema.safeParse(entry);
|
|
92518
|
+
return parsed.success ? [parsed.data] : [];
|
|
92519
|
+
});
|
|
92520
|
+
}
|
|
92521
|
+
/** Key-order-independent JSON, so "identical" does not depend on how a store orders keys. */
|
|
92522
|
+
function canonical(value) {
|
|
92523
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
92524
|
+
if (typeof value === "object" && value !== null) return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
|
|
92525
|
+
return JSON.stringify(value) ?? "null";
|
|
92526
|
+
}
|
|
92527
|
+
async function moveExposureToRecord(ports) {
|
|
92528
|
+
const stored = await ports.readStored();
|
|
92529
|
+
if (!MOVED_EXPOSURE_KEYS.some((key) => key in stored)) return {
|
|
92530
|
+
outcome: "already-done",
|
|
92531
|
+
summary: { moved: false }
|
|
92532
|
+
};
|
|
92533
|
+
const devices = devicesOf(stored["exposed"]);
|
|
92534
|
+
const actions = actionsOf(stored["exposedActions"]);
|
|
92535
|
+
const dropped = (Array.isArray(stored["exposed"]) ? stored["exposed"].length : 0) - devices.length + ((Array.isArray(stored["exposedActions"]) ? stored["exposedActions"].length : 0) - actions.length);
|
|
92536
|
+
if (dropped > 0) ports.warn(`Google migration: ${dropped} exposure entr(ies) were not understood and are left out`);
|
|
92537
|
+
const body = {
|
|
92538
|
+
name: GOOGLE_EXPORTS_NAME,
|
|
92539
|
+
devices,
|
|
92540
|
+
actions
|
|
92541
|
+
};
|
|
92542
|
+
if (await ports.putExports(body) === "exists") return {
|
|
92543
|
+
outcome: "already-done",
|
|
92544
|
+
summary: { moved: false }
|
|
92545
|
+
};
|
|
92546
|
+
const held = await ports.readExports();
|
|
92547
|
+
if (held === null || canonical(held.devices) !== canonical(devices) || canonical(held.actions) !== canonical(actions)) throw new Error("the Google exposure record does not match the legacy settings; nothing was cleared");
|
|
92548
|
+
return {
|
|
92549
|
+
outcome: "done",
|
|
92550
|
+
summary: {
|
|
92551
|
+
moved: true,
|
|
92552
|
+
devices: devices.length,
|
|
92553
|
+
actions: actions.length
|
|
92554
|
+
}
|
|
92555
|
+
};
|
|
92556
|
+
}
|
|
92557
|
+
var rowId = (key) => `${GOOGLE_INSTANCE_ID}.${key}`;
|
|
92558
|
+
async function planDropMovedExposure(ports) {
|
|
92559
|
+
const stored = await ports.readStored();
|
|
92560
|
+
const present = MOVED_EXPOSURE_KEYS.filter((key) => key in stored);
|
|
92561
|
+
if (present.length === 0) return { edits: [] };
|
|
92562
|
+
const refuse = (reason) => {
|
|
92563
|
+
ports.warn(`Google migration: the legacy exposure keys are kept: ${reason}`);
|
|
92564
|
+
throw new Error(`the legacy Google exposure keys are not deleted: ${reason}`);
|
|
92565
|
+
};
|
|
92566
|
+
const held = await ports.readExports();
|
|
92567
|
+
if (held === null) return refuse("no exposure record exists");
|
|
92568
|
+
const heldDevices = new Set(held.devices.map((d) => d.deviceId));
|
|
92569
|
+
for (const device of devicesOf(stored["exposed"])) if (!heldDevices.has(device.deviceId)) return refuse(`the record lacks the device ${device.deviceId}`);
|
|
92570
|
+
const heldActions = new Set(held.actions.map((a) => a.actionId));
|
|
92571
|
+
for (const action of actionsOf(stored["exposedActions"])) if (!heldActions.has(action.actionId)) return refuse(`the record lacks the action ${action.actionId}`);
|
|
92572
|
+
return { edits: [{
|
|
92573
|
+
op: "deleteKeys",
|
|
92574
|
+
scope: ADDON_SETTINGS_TABLE,
|
|
92575
|
+
keys: present.map(rowId),
|
|
92576
|
+
precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
|
|
92577
|
+
addonId: GOOGLE_INSTANCE_ID,
|
|
92578
|
+
key,
|
|
92579
|
+
value: stored[key]
|
|
92580
|
+
}])))
|
|
92581
|
+
}] };
|
|
92582
|
+
}
|
|
92583
|
+
//#endregion
|
|
92584
|
+
//#region src/migrations/instance-and-links.ts
|
|
92585
|
+
/**
|
|
92586
|
+
* Google becomes a multi-instance exporter (planning#422 P2). Two migrations, both `block-owner`:
|
|
92587
|
+
* the addon must not serve a link ledger it cannot trust, and after them nothing reads the old key.
|
|
92588
|
+
*
|
|
92589
|
+
* 1. `moveInstanceAndLinks` (procedure): the first instance is the `google-homes` row under the
|
|
92590
|
+
* id `export-google`, and the `linkedAccounts` setting becomes the `google-links` row under
|
|
92591
|
+
* the same id. An existing row is never overwritten; a row this pass just wrote is read BACK
|
|
92592
|
+
* and must equal what the settings carried, or the pass throws.
|
|
92593
|
+
* 2. `planDropMovedLinks` (plan): the key is deleted only while the record holds every user the
|
|
92594
|
+
* settings carried; a record that cannot be read leaves the key in place.
|
|
92595
|
+
*/
|
|
92596
|
+
function linksOf(value) {
|
|
92597
|
+
if (!Array.isArray(value)) return [];
|
|
92598
|
+
return value.flatMap((entry) => {
|
|
92599
|
+
const parsed = LinkedAccountSchema.safeParse(entry);
|
|
92600
|
+
return parsed.success ? [parsed.data] : [];
|
|
92601
|
+
});
|
|
92602
|
+
}
|
|
92603
|
+
async function moveInstanceAndLinks(ports) {
|
|
92604
|
+
const stored = await ports.readStored();
|
|
92605
|
+
const hasLinks = MOVED_LINKS_KEY in stored;
|
|
92606
|
+
const linkedAccounts = linksOf(stored[MOVED_LINKS_KEY]);
|
|
92607
|
+
const raw = stored[MOVED_LINKS_KEY];
|
|
92608
|
+
const understood = Array.isArray(raw) ? raw.length : 0;
|
|
92609
|
+
if (understood > linkedAccounts.length) ports.warn(`Google migration: ${understood - linkedAccounts.length} linked account(s) were not understood and are left out`);
|
|
92610
|
+
const home = await ports.putHome({ name: GOOGLE_HOME_NAME });
|
|
92611
|
+
const links = hasLinks ? await ports.putLinks({
|
|
92612
|
+
name: GOOGLE_LINKS_NAME,
|
|
92613
|
+
linkedAccounts
|
|
92614
|
+
}) : "exists";
|
|
92615
|
+
if (await ports.readHome() === null) throw new Error("the Google Home instance row is not there after it was written");
|
|
92616
|
+
if (links === "created") {
|
|
92617
|
+
const held = await ports.readLinks();
|
|
92618
|
+
if (held === null || canonical(held.linkedAccounts) !== canonical(linkedAccounts)) throw new Error("the Google links record does not match the legacy settings; nothing was cleared");
|
|
92619
|
+
}
|
|
92620
|
+
if (home === "exists" && links === "exists") return {
|
|
92621
|
+
outcome: "already-done",
|
|
92622
|
+
summary: { moved: false }
|
|
92623
|
+
};
|
|
92624
|
+
return {
|
|
92625
|
+
outcome: "done",
|
|
92626
|
+
summary: {
|
|
92627
|
+
instance: home === "created",
|
|
92628
|
+
linked: links === "created" ? linkedAccounts.length : 0
|
|
92629
|
+
}
|
|
92630
|
+
};
|
|
92631
|
+
}
|
|
92632
|
+
async function planDropMovedLinks(ports) {
|
|
92633
|
+
const stored = await ports.readStored();
|
|
92634
|
+
if (!("linkedAccounts" in stored)) return { edits: [] };
|
|
92635
|
+
const refuse = (reason) => {
|
|
92636
|
+
ports.warn(`Google migration: the legacy linkedAccounts key is kept: ${reason}`);
|
|
92637
|
+
throw new Error(`the legacy Google linkedAccounts key is not deleted: ${reason}`);
|
|
92638
|
+
};
|
|
92639
|
+
const held = await ports.readLinks();
|
|
92640
|
+
if (held === null) return refuse("no links record exists");
|
|
92641
|
+
const heldUsers = new Set(held.linkedAccounts.map((a) => a.userId));
|
|
92642
|
+
for (const account of linksOf(stored[MOVED_LINKS_KEY])) if (!heldUsers.has(account.userId)) return refuse(`the record lacks the user ${account.userId}`);
|
|
92643
|
+
const id = `${GOOGLE_INSTANCE_ID}.${MOVED_LINKS_KEY}`;
|
|
92644
|
+
return { edits: [{
|
|
92645
|
+
op: "deleteKeys",
|
|
92646
|
+
scope: ADDON_SETTINGS_TABLE,
|
|
92647
|
+
keys: [id],
|
|
92648
|
+
precondition: preconditionOf({ [id]: {
|
|
92649
|
+
addonId: GOOGLE_INSTANCE_ID,
|
|
92650
|
+
key: MOVED_LINKS_KEY,
|
|
92651
|
+
value: stored[MOVED_LINKS_KEY]
|
|
92652
|
+
} })
|
|
92653
|
+
}] };
|
|
92654
|
+
}
|
|
92655
|
+
//#endregion
|
|
92656
|
+
//#region src/migrations/index.ts
|
|
92657
|
+
var DROP_PUBLIC_HUB_URL_ID = "export-google/2026-11-02-drop-public-hub-url";
|
|
92658
|
+
var EXPOSURE_TO_RECORD_ID = "export-google/2026-11-04-exposure-to-record";
|
|
92659
|
+
var DROP_MOVED_EXPOSURE_ID = "export-google/2026-11-04-drop-moved-exposure";
|
|
92660
|
+
var INSTANCE_AND_LINKS_ID = "export-google/2026-11-04-instance-and-links";
|
|
92661
|
+
var DROP_MOVED_LINKS_ID = "export-google/2026-11-04-drop-moved-links";
|
|
92662
|
+
var FIXTURE_MARK = "the linked account list the migration does not know";
|
|
92663
|
+
/** The `export-google` catalogue (D987): offered to the engine when the addon initialises. */
|
|
92664
|
+
var ADDON_MIGRATIONS = [
|
|
92665
|
+
{
|
|
92666
|
+
meta: {
|
|
92667
|
+
id: DROP_PUBLIC_HUB_URL_ID,
|
|
92668
|
+
owner: "export-google",
|
|
92669
|
+
level: "addon-state",
|
|
92670
|
+
seq: 1,
|
|
92671
|
+
dependsOn: [],
|
|
92672
|
+
store: "settings",
|
|
92673
|
+
scope: "cluster",
|
|
92674
|
+
onFailure: "tolerate",
|
|
92675
|
+
bodyKind: "plan",
|
|
92676
|
+
description: "Delete the retired publicHubUrl and detectedPublicHubUrl settings; the public URL is the publicEndpoint role",
|
|
92677
|
+
fixtureMark: FIXTURE_MARK
|
|
92678
|
+
},
|
|
92679
|
+
plan: planDropPublicHubUrl
|
|
92680
|
+
},
|
|
92681
|
+
{
|
|
92682
|
+
meta: {
|
|
92683
|
+
id: EXPOSURE_TO_RECORD_ID,
|
|
92684
|
+
owner: "export-google",
|
|
92685
|
+
level: "addon-state",
|
|
92686
|
+
seq: 2,
|
|
92687
|
+
dependsOn: [],
|
|
92688
|
+
store: "settings",
|
|
92689
|
+
scope: "cluster",
|
|
92690
|
+
onFailure: "block-owner",
|
|
92691
|
+
bodyKind: "procedure",
|
|
92692
|
+
description: "Move the exposed devices and actions into the google-exports record; the record is read back before anything is deleted",
|
|
92693
|
+
fixtureMark: FIXTURE_MARK
|
|
92694
|
+
},
|
|
92695
|
+
procedure: moveExposureToRecord
|
|
92696
|
+
},
|
|
92697
|
+
{
|
|
92698
|
+
meta: {
|
|
92699
|
+
id: DROP_MOVED_EXPOSURE_ID,
|
|
92700
|
+
owner: "export-google",
|
|
92701
|
+
level: "addon-state",
|
|
92702
|
+
seq: 3,
|
|
92703
|
+
dependsOn: [EXPOSURE_TO_RECORD_ID],
|
|
92704
|
+
store: "settings",
|
|
92705
|
+
scope: "cluster",
|
|
92706
|
+
onFailure: "block-owner",
|
|
92707
|
+
bodyKind: "plan",
|
|
92708
|
+
description: "Delete the exposed and exposedActions settings keys once the record holds what they carried",
|
|
92709
|
+
fixtureMark: FIXTURE_MARK
|
|
92710
|
+
},
|
|
92711
|
+
plan: planDropMovedExposure
|
|
92712
|
+
},
|
|
92713
|
+
{
|
|
92714
|
+
meta: {
|
|
92715
|
+
id: INSTANCE_AND_LINKS_ID,
|
|
92716
|
+
owner: "export-google",
|
|
92717
|
+
level: "addon-state",
|
|
92718
|
+
seq: 4,
|
|
92719
|
+
dependsOn: [],
|
|
92720
|
+
store: "settings",
|
|
92721
|
+
scope: "cluster",
|
|
92722
|
+
onFailure: "block-owner",
|
|
92723
|
+
bodyKind: "procedure",
|
|
92724
|
+
description: "Create the first Google Home instance under the id export-google and move the linked accounts into its google-links record; both rows are read back before anything is deleted",
|
|
92725
|
+
fixtureMark: FIXTURE_MARK
|
|
92726
|
+
},
|
|
92727
|
+
procedure: moveInstanceAndLinks
|
|
92728
|
+
},
|
|
92729
|
+
{
|
|
92730
|
+
meta: {
|
|
92731
|
+
id: DROP_MOVED_LINKS_ID,
|
|
92732
|
+
owner: "export-google",
|
|
92733
|
+
level: "addon-state",
|
|
92734
|
+
seq: 5,
|
|
92735
|
+
dependsOn: [INSTANCE_AND_LINKS_ID],
|
|
92736
|
+
store: "settings",
|
|
92737
|
+
scope: "cluster",
|
|
92738
|
+
onFailure: "block-owner",
|
|
92739
|
+
bodyKind: "plan",
|
|
92740
|
+
description: "Delete the linkedAccounts settings key once the google-links record holds what it carried",
|
|
92741
|
+
fixtureMark: FIXTURE_MARK
|
|
92742
|
+
},
|
|
92743
|
+
plan: planDropMovedLinks
|
|
92744
|
+
}
|
|
92745
|
+
];
|
|
92746
|
+
//#endregion
|
|
91383
92747
|
//#region src/oauth-integration.ts
|
|
91384
92748
|
/**
|
|
91385
92749
|
* The `export-google` OAuth client — the descriptor behind
|
|
@@ -91454,59 +92818,6 @@ function buildGoogleOauthIntegration() {
|
|
|
91454
92818
|
};
|
|
91455
92819
|
}
|
|
91456
92820
|
//#endregion
|
|
91457
|
-
//#region src/migrations/drop-public-hub-url.ts
|
|
91458
|
-
/**
|
|
91459
|
-
* The hub's public URL is no longer a setting of this addon (D986 §5): Google reads the
|
|
91460
|
-
* `publicEndpoint` role of the local-network palette on every use. The two keys older
|
|
91461
|
-
* versions persisted are deleted. Every other key is left exactly as stored.
|
|
91462
|
-
*
|
|
91463
|
-
* Idempotent: a store without either key yields an empty plan, which writes nothing.
|
|
91464
|
-
*/
|
|
91465
|
-
/** The addon id, the prefix of its rows in the canonical settings table. */
|
|
91466
|
-
var GOOGLE_ADDON_ID = "export-google";
|
|
91467
|
-
/**
|
|
91468
|
-
* Where the addon's global settings live: the canonical `addon-settings` table, one row per
|
|
91469
|
-
* key, id `<addonId>.<key>`, data `{ addonId, key, value }` (never a per-addon scoped table,
|
|
91470
|
-
* which exists only when something lazily declared it).
|
|
91471
|
-
*/
|
|
91472
|
-
var ADDON_SETTINGS_TABLE = "addon-settings";
|
|
91473
|
-
var RETIRED_PUBLIC_URL_KEYS = ["publicHubUrl", "detectedPublicHubUrl"];
|
|
91474
|
-
async function planDropPublicHubUrl(ports) {
|
|
91475
|
-
const stored = await ports.readStored();
|
|
91476
|
-
const present = RETIRED_PUBLIC_URL_KEYS.filter((key) => key in stored);
|
|
91477
|
-
if (present.length === 0) return { edits: [] };
|
|
91478
|
-
const rowId = (key) => `${GOOGLE_ADDON_ID}.${key}`;
|
|
91479
|
-
return { edits: [{
|
|
91480
|
-
op: "deleteKeys",
|
|
91481
|
-
scope: ADDON_SETTINGS_TABLE,
|
|
91482
|
-
keys: present.map(rowId),
|
|
91483
|
-
precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
|
|
91484
|
-
addonId: GOOGLE_ADDON_ID,
|
|
91485
|
-
key,
|
|
91486
|
-
value: stored[key]
|
|
91487
|
-
}])))
|
|
91488
|
-
}] };
|
|
91489
|
-
}
|
|
91490
|
-
//#endregion
|
|
91491
|
-
//#region src/migrations/index.ts
|
|
91492
|
-
/** The `export-google` catalogue (D987): offered to the engine when the addon initialises. */
|
|
91493
|
-
var ADDON_MIGRATIONS = [{
|
|
91494
|
-
meta: {
|
|
91495
|
-
id: "export-google/2026-11-02-drop-public-hub-url",
|
|
91496
|
-
owner: "export-google",
|
|
91497
|
-
level: "addon-state",
|
|
91498
|
-
seq: 1,
|
|
91499
|
-
dependsOn: [],
|
|
91500
|
-
store: "settings",
|
|
91501
|
-
scope: "cluster",
|
|
91502
|
-
onFailure: "tolerate",
|
|
91503
|
-
bodyKind: "plan",
|
|
91504
|
-
description: "Delete the retired publicHubUrl and detectedPublicHubUrl settings; the public URL is the publicEndpoint role",
|
|
91505
|
-
fixtureMark: "the exposed device list the migration does not know"
|
|
91506
|
-
},
|
|
91507
|
-
plan: planDropPublicHubUrl
|
|
91508
|
-
}];
|
|
91509
|
-
//#endregion
|
|
91510
92821
|
//#region src/public-endpoint.ts
|
|
91511
92822
|
/** The typed refusal when the role resolves to nothing. */
|
|
91512
92823
|
var NO_PUBLIC_ENDPOINT_REASON = {
|
|
@@ -91546,6 +92857,7 @@ var buildConsoleSetupFromRole = async (input) => {
|
|
|
91546
92857
|
}]
|
|
91547
92858
|
};
|
|
91548
92859
|
const origin = result.origin;
|
|
92860
|
+
const fulfillmentPath = input.instanceId === void 0 ? `/addon/${input.addonId}/fulfillment` : `/addon/${input.addonId}/fulfillment/${input.instanceId}`;
|
|
91549
92861
|
return {
|
|
91550
92862
|
note: [
|
|
91551
92863
|
"In the Google Home Developer Console create a cloud-to-cloud integration, then paste these three URLs.",
|
|
@@ -91556,7 +92868,7 @@ var buildConsoleSetupFromRole = async (input) => {
|
|
|
91556
92868
|
fields: [
|
|
91557
92869
|
{
|
|
91558
92870
|
label: "Fulfillment URL",
|
|
91559
|
-
value: `${origin}
|
|
92871
|
+
value: `${origin}${fulfillmentPath}`
|
|
91560
92872
|
},
|
|
91561
92873
|
{
|
|
91562
92874
|
label: "Authorization URL",
|
|
@@ -91575,11 +92887,7 @@ var buildConsoleSetupFromRole = async (input) => {
|
|
|
91575
92887
|
};
|
|
91576
92888
|
//#endregion
|
|
91577
92889
|
//#region src/types.ts
|
|
91578
|
-
var DEFAULT_SETTINGS = {
|
|
91579
|
-
exposed: [],
|
|
91580
|
-
exposedActions: [],
|
|
91581
|
-
linkedAccounts: []
|
|
91582
|
-
};
|
|
92890
|
+
var DEFAULT_SETTINGS = {};
|
|
91583
92891
|
//#endregion
|
|
91584
92892
|
//#region src/export-google.addon.ts
|
|
91585
92893
|
/**
|
|
@@ -91587,9 +92895,14 @@ var DEFAULT_SETTINGS = {
|
|
|
91587
92895
|
*
|
|
91588
92896
|
* Architecture:
|
|
91589
92897
|
*
|
|
91590
|
-
* Google Home / Assistant --HTTPS--> POST /addon/export-google/fulfillment
|
|
92898
|
+
* Google Home / Assistant --HTTPS--> POST /addon/export-google/fulfillment/<instanceId>
|
|
91591
92899
|
* (hub Fastify → addon-routes cap)
|
|
91592
92900
|
*
|
|
92901
|
+
* The addon is MULTI-instance (planning#422): every Actions-console project is one
|
|
92902
|
+
* `integration-instances` row of the `google-homes` kind with its own exposure and its own
|
|
92903
|
+
* link ledger. The first instance keeps the id `export-google`, so the legacy
|
|
92904
|
+
* `/fulfillment` URL still answers for it. One OAuth client serves every instance.
|
|
92905
|
+
*
|
|
91593
92906
|
* There is no cloud function in the middle. Google's smart-home platform calls
|
|
91594
92907
|
* the fulfillment URL the operator configured, so the hub answers directly —
|
|
91595
92908
|
* a shorter path than Alexa's, which needs an operator-owned Lambda because
|
|
@@ -91597,7 +92910,8 @@ var DEFAULT_SETTINGS = {
|
|
|
91597
92910
|
*
|
|
91598
92911
|
* Capabilities registered:
|
|
91599
92912
|
* - `device-export` — the operator picks which devices Google sees.
|
|
91600
|
-
* - `addon-routes` — mounts `/addon/export-google/fulfillment`.
|
|
92913
|
+
* - `addon-routes` — mounts `/addon/export-google/fulfillment[/<instanceId>]`.
|
|
92914
|
+
* - `integration-instances` — the Google Home instances (role `services`).
|
|
91601
92915
|
* - `oauth-integration` — declares this addon a linkable client of the
|
|
91602
92916
|
* hub's core `/api/oauth2/*` server.
|
|
91603
92917
|
*
|
|
@@ -91619,117 +92933,152 @@ var DEFAULT_SETTINGS = {
|
|
|
91619
92933
|
* decides, so widening scope is one row.
|
|
91620
92934
|
*/
|
|
91621
92935
|
var ADDON_ID = "export-google";
|
|
92936
|
+
/** The per-device toggle key: `google:<instanceId>:<deviceId>:enabled`. */
|
|
92937
|
+
var DEVICE_KEY = /^google:([^:]+):(\d+):enabled$/;
|
|
92938
|
+
var deviceKey = (instanceId, deviceId) => `google:${instanceId}:${deviceId}:enabled`;
|
|
91622
92939
|
var ExportGoogleAddon = class extends BaseAddon {
|
|
91623
92940
|
gateway = null;
|
|
92941
|
+
registry = null;
|
|
92942
|
+
instances = null;
|
|
92943
|
+
fulfillments = /* @__PURE__ */ new WeakMap();
|
|
91624
92944
|
constructor() {
|
|
91625
92945
|
super({ ...DEFAULT_SETTINGS });
|
|
91626
92946
|
}
|
|
92947
|
+
requireRegistry() {
|
|
92948
|
+
if (this.registry === null) throw new Error("export-google: addon not initialized");
|
|
92949
|
+
return this.registry;
|
|
92950
|
+
}
|
|
92951
|
+
/** The instance or a typed refusal naming it: a device-export call never guesses one. */
|
|
92952
|
+
async requireInstance(instanceId) {
|
|
92953
|
+
const instance = await this.requireRegistry().get(instanceId);
|
|
92954
|
+
if (instance === null) throw new ExportInstanceUnknownError(ADDON_ID, instanceId);
|
|
92955
|
+
return instance;
|
|
92956
|
+
}
|
|
91627
92957
|
async onInitialize() {
|
|
91628
92958
|
const gateway = createApiDeviceGateway({
|
|
91629
92959
|
api: this.ctx.api,
|
|
91630
92960
|
logger: this.ctx.logger
|
|
91631
92961
|
});
|
|
91632
92962
|
this.gateway = gateway;
|
|
91633
|
-
|
|
91634
|
-
|
|
92963
|
+
const records = this.ctx.records;
|
|
92964
|
+
if (records === void 0) throw new Error("export-google needs ctx.records — check execution.placement (hub-only)");
|
|
92965
|
+
await records.declare({
|
|
92966
|
+
"google-homes": googleHomesKind,
|
|
92967
|
+
"google-exports": googleExportsKind,
|
|
92968
|
+
"google-links": googleLinksKind
|
|
92969
|
+
});
|
|
92970
|
+
const stores = {
|
|
92971
|
+
homes: records.kind(googleHomesKind),
|
|
92972
|
+
exports: records.kind(googleExportsKind),
|
|
92973
|
+
links: records.kind(googleLinksKind)
|
|
92974
|
+
};
|
|
92975
|
+
const registry = new GoogleInstanceRegistry(stores, this.ctx.logger, (persist, initial) => new ActionSceneExports({
|
|
91635
92976
|
api: this.ctx.api,
|
|
91636
92977
|
logger: this.ctx.logger,
|
|
91637
92978
|
isAdminUser: async (userId) => {
|
|
91638
92979
|
return (await this.ctx.api.userManagement.listUsers.query()).some((u) => u.id === userId && u.isAdmin);
|
|
91639
92980
|
},
|
|
91640
|
-
persist
|
|
91641
|
-
},
|
|
91642
|
-
|
|
91643
|
-
|
|
91644
|
-
|
|
91645
|
-
|
|
91646
|
-
|
|
91647
|
-
|
|
91648
|
-
|
|
91649
|
-
return {
|
|
91650
|
-
linkState: this.config.linkedAccounts.length > 0 ? "linked" : "unlinked",
|
|
91651
|
-
exposedDeviceCount: this.config.exposed.length,
|
|
91652
|
-
setup: await this.buildSetupBlock()
|
|
91653
|
-
};
|
|
92981
|
+
persist
|
|
92982
|
+
}, initial));
|
|
92983
|
+
this.registry = registry;
|
|
92984
|
+
this.instances = new RecordIntegrationInstances(records, googleHomesKind, {
|
|
92985
|
+
description: {
|
|
92986
|
+
role: "services",
|
|
92987
|
+
instanceMode: "multiple",
|
|
92988
|
+
kind: "homes",
|
|
92989
|
+
canTest: false
|
|
91654
92990
|
},
|
|
91655
|
-
|
|
91656
|
-
|
|
91657
|
-
|
|
91658
|
-
|
|
91659
|
-
|
|
91660
|
-
|
|
91661
|
-
|
|
91662
|
-
|
|
91663
|
-
|
|
91664
|
-
|
|
91665
|
-
|
|
91666
|
-
|
|
91667
|
-
|
|
92991
|
+
formSchema: (id) => this.homeForm(id),
|
|
92992
|
+
initialBody: (name) => ({ name }),
|
|
92993
|
+
mintId: () => `google-home-${randomUUID().slice(0, 8)}`,
|
|
92994
|
+
health: (body, id) => {
|
|
92995
|
+
if (body.enabled === false) return { status: {
|
|
92996
|
+
state: "off",
|
|
92997
|
+
label: "Off"
|
|
92998
|
+
} };
|
|
92999
|
+
const linked = registry.peek(id)?.linkedAccounts.length;
|
|
93000
|
+
if (linked === void 0) return { status: { state: "unknown" } };
|
|
93001
|
+
return linked > 0 ? { status: {
|
|
93002
|
+
state: "ok",
|
|
93003
|
+
label: `${linked} linked account(s)`
|
|
93004
|
+
} } : { status: {
|
|
93005
|
+
state: "unknown",
|
|
93006
|
+
label: "Not linked yet"
|
|
93007
|
+
} };
|
|
91668
93008
|
},
|
|
91669
|
-
|
|
91670
|
-
|
|
91671
|
-
|
|
91672
|
-
|
|
91673
|
-
|
|
91674
|
-
|
|
91675
|
-
|
|
93009
|
+
configured: () => true,
|
|
93010
|
+
onChanged: (id, change) => this.onInstanceChanged(id, change)
|
|
93011
|
+
});
|
|
93012
|
+
await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, {
|
|
93013
|
+
readStored: async () => this.resolveGlobalStore(),
|
|
93014
|
+
warn: (message) => {
|
|
93015
|
+
this.ctx.logger.warn(message, { tags: {
|
|
93016
|
+
topic: "export-google",
|
|
93017
|
+
phase: "migration"
|
|
93018
|
+
} });
|
|
91676
93019
|
},
|
|
91677
|
-
|
|
91678
|
-
|
|
91679
|
-
|
|
91680
|
-
|
|
91681
|
-
|
|
91682
|
-
|
|
91683
|
-
|
|
91684
|
-
}
|
|
93020
|
+
putExports: async (body) => {
|
|
93021
|
+
if (await stores.exports.get("export-google") !== null) return "exists";
|
|
93022
|
+
try {
|
|
93023
|
+
await stores.exports.put({
|
|
93024
|
+
id: GOOGLE_INSTANCE_ID,
|
|
93025
|
+
data: body
|
|
93026
|
+
}, { ifRev: 0 });
|
|
93027
|
+
} catch (err) {
|
|
93028
|
+
if (err instanceof RevConflictError) return "exists";
|
|
93029
|
+
throw err;
|
|
93030
|
+
}
|
|
93031
|
+
return "created";
|
|
91685
93032
|
},
|
|
91686
|
-
|
|
91687
|
-
|
|
91688
|
-
if (
|
|
91689
|
-
|
|
91690
|
-
|
|
93033
|
+
readExports: async () => (await stores.exports.get("export-google"))?.data ?? null,
|
|
93034
|
+
putHome: async (body) => {
|
|
93035
|
+
if (await stores.homes.get("export-google") !== null) return "exists";
|
|
93036
|
+
try {
|
|
93037
|
+
await stores.homes.put({
|
|
93038
|
+
id: GOOGLE_INSTANCE_ID,
|
|
93039
|
+
data: body
|
|
93040
|
+
}, { ifRev: 0 });
|
|
93041
|
+
} catch (err) {
|
|
93042
|
+
if (err instanceof RevConflictError) return "exists";
|
|
93043
|
+
throw err;
|
|
93044
|
+
}
|
|
93045
|
+
return "created";
|
|
91691
93046
|
},
|
|
91692
|
-
|
|
91693
|
-
|
|
91694
|
-
|
|
91695
|
-
|
|
91696
|
-
|
|
93047
|
+
putLinks: async (body) => {
|
|
93048
|
+
if (await stores.links.get("export-google") !== null) return "exists";
|
|
93049
|
+
try {
|
|
93050
|
+
await stores.links.put({
|
|
93051
|
+
id: GOOGLE_INSTANCE_ID,
|
|
93052
|
+
data: body
|
|
93053
|
+
}, { ifRev: 0 });
|
|
93054
|
+
} catch (err) {
|
|
93055
|
+
if (err instanceof RevConflictError) return "exists";
|
|
93056
|
+
throw err;
|
|
93057
|
+
}
|
|
93058
|
+
return "created";
|
|
91697
93059
|
},
|
|
91698
|
-
|
|
91699
|
-
|
|
91700
|
-
|
|
91701
|
-
|
|
93060
|
+
readHome: async () => (await stores.homes.get("export-google"))?.data ?? null,
|
|
93061
|
+
readLinks: async () => (await stores.links.get("export-google"))?.data ?? null
|
|
93062
|
+
}));
|
|
93063
|
+
for (const row of await registry.list()) {
|
|
93064
|
+
const instance = await registry.get(row.id);
|
|
93065
|
+
if (instance === null) continue;
|
|
93066
|
+
instance.scenes.reconcile().catch((err) => {
|
|
93067
|
+
this.ctx.logger.warn("export-google: action scene reconcile at boot failed", { meta: {
|
|
93068
|
+
instanceId: instance.id,
|
|
93069
|
+
error: errMsg$1(err)
|
|
93070
|
+
} });
|
|
93071
|
+
});
|
|
93072
|
+
}
|
|
93073
|
+
const deviceExportProvider = this.buildDeviceExportProvider();
|
|
91702
93074
|
const routeProvider = buildAddonRouteProvider(ADDON_ID, buildRoutes({
|
|
91703
93075
|
ctx: this.ctx,
|
|
91704
93076
|
logger: this.ctx.logger,
|
|
91705
|
-
|
|
91706
|
-
logger: this.ctx.logger,
|
|
91707
|
-
sync: {
|
|
91708
|
-
gateway,
|
|
91709
|
-
logger: this.ctx.logger,
|
|
91710
|
-
listExposed: () => this.config.exposed.map((entry) => entry.deviceId),
|
|
91711
|
-
actions: actionScenes
|
|
91712
|
-
},
|
|
91713
|
-
query: {
|
|
91714
|
-
gateway,
|
|
91715
|
-
logger: this.ctx.logger,
|
|
91716
|
-
isExposed: (deviceId) => this.isExposed(deviceId),
|
|
91717
|
-
actions: actionScenes
|
|
91718
|
-
},
|
|
91719
|
-
execute: {
|
|
91720
|
-
gateway,
|
|
91721
|
-
logger: this.ctx.logger,
|
|
91722
|
-
isExposed: (deviceId) => this.isExposed(deviceId),
|
|
91723
|
-
actions: actionScenes
|
|
91724
|
-
},
|
|
91725
|
-
recordLink: (caller) => this.recordLink(caller),
|
|
91726
|
-
removeLink: (userId) => this.removeLink(userId)
|
|
91727
|
-
}
|
|
93077
|
+
resolveFulfillment: (instanceId) => this.resolveFulfillment(instanceId)
|
|
91728
93078
|
}));
|
|
91729
93079
|
const oauthIntegrationProvider = { getDescriptor: async () => buildGoogleOauthIntegration() };
|
|
91730
93080
|
this.ctx.logger.info("export-google: initialized", { meta: {
|
|
91731
|
-
|
|
91732
|
-
linkedAccounts: this.config.linkedAccounts.length,
|
|
93081
|
+
instances: (await registry.list()).length,
|
|
91733
93082
|
willReportState: false
|
|
91734
93083
|
} });
|
|
91735
93084
|
return [
|
|
@@ -91744,16 +93093,151 @@ var ExportGoogleAddon = class extends BaseAddon {
|
|
|
91744
93093
|
{
|
|
91745
93094
|
capability: oauthIntegrationCapability,
|
|
91746
93095
|
provider: oauthIntegrationProvider
|
|
93096
|
+
},
|
|
93097
|
+
{
|
|
93098
|
+
capability: integrationInstancesCapability,
|
|
93099
|
+
provider: this.instances.toProvider()
|
|
91747
93100
|
}
|
|
91748
93101
|
];
|
|
91749
93102
|
}
|
|
91750
93103
|
async onShutdown() {
|
|
91751
93104
|
this.gateway = null;
|
|
93105
|
+
this.registry = null;
|
|
91752
93106
|
}
|
|
91753
|
-
|
|
91754
|
-
|
|
93107
|
+
async onInstanceChanged(id, change) {
|
|
93108
|
+
const registry = this.requireRegistry();
|
|
93109
|
+
if (change === "deleted") await registry.remove(id);
|
|
93110
|
+
else if (change === "created") await registry.get(id);
|
|
93111
|
+
else await registry.refreshHome(id);
|
|
93112
|
+
}
|
|
93113
|
+
homeForm(id) {
|
|
93114
|
+
const target = id === null ? "<instance id>" : id;
|
|
93115
|
+
return this.schema({ sections: [{
|
|
93116
|
+
id: ADDON_ID,
|
|
93117
|
+
title: "Connection",
|
|
93118
|
+
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.",
|
|
93119
|
+
columns: 1,
|
|
93120
|
+
fields: [{
|
|
93121
|
+
type: "info",
|
|
93122
|
+
key: "__google-setup-banner",
|
|
93123
|
+
label: "Setup overview",
|
|
93124
|
+
variant: "info",
|
|
93125
|
+
content: [
|
|
93126
|
+
"This hub must be reachable from the public internet over HTTPS (Cloudflare Tunnel, Tailscale Funnel, …) — Google calls the fulfillment URL from its own cloud.",
|
|
93127
|
+
`Create a cloud-to-cloud integration in the Google Home Developer Console, paste the three URLs from the Export panel (the fulfillment URL ends in /fulfillment/${target}), and link your account from the Home app.`,
|
|
93128
|
+
"Each Google Home instance is one Actions-console project with its own devices and linked accounts.",
|
|
93129
|
+
"Cameras are not exported, and state is not pushed: Google polls. Ask \"Hey Google, sync my devices\" after exposing something new."
|
|
93130
|
+
].join("\n")
|
|
93131
|
+
}]
|
|
93132
|
+
}] });
|
|
93133
|
+
}
|
|
93134
|
+
async resolveFulfillment(instanceId) {
|
|
93135
|
+
const instance = await this.requireRegistry().get(instanceId);
|
|
93136
|
+
if (instance === null) return {
|
|
93137
|
+
ok: false,
|
|
93138
|
+
code: "unknown_instance"
|
|
93139
|
+
};
|
|
93140
|
+
if (!instance.enabled) return {
|
|
93141
|
+
ok: false,
|
|
93142
|
+
code: "instance_disabled"
|
|
93143
|
+
};
|
|
93144
|
+
return {
|
|
93145
|
+
ok: true,
|
|
93146
|
+
deps: this.fulfillmentFor(instance)
|
|
93147
|
+
};
|
|
93148
|
+
}
|
|
93149
|
+
/** The fulfillment wiring of ONE instance: its exposure, its links, nobody else's. */
|
|
93150
|
+
fulfillmentFor(instance) {
|
|
93151
|
+
const cached = this.fulfillments.get(instance);
|
|
93152
|
+
if (cached !== void 0) return cached;
|
|
93153
|
+
const gateway = this.requireGateway();
|
|
93154
|
+
const logger = this.ctx.logger;
|
|
93155
|
+
const deps = {
|
|
93156
|
+
logger,
|
|
93157
|
+
sync: {
|
|
93158
|
+
gateway,
|
|
93159
|
+
logger,
|
|
93160
|
+
listExposed: () => instance.devices.map((entry) => entry.deviceId),
|
|
93161
|
+
actions: instance.scenes
|
|
93162
|
+
},
|
|
93163
|
+
query: {
|
|
93164
|
+
gateway,
|
|
93165
|
+
logger,
|
|
93166
|
+
isExposed: (deviceId) => instance.isExposed(deviceId),
|
|
93167
|
+
actions: instance.scenes
|
|
93168
|
+
},
|
|
93169
|
+
execute: {
|
|
93170
|
+
gateway,
|
|
93171
|
+
logger,
|
|
93172
|
+
isExposed: (deviceId) => instance.isExposed(deviceId),
|
|
93173
|
+
actions: instance.scenes
|
|
93174
|
+
},
|
|
93175
|
+
recordLink: (caller) => instance.recordLink(caller),
|
|
93176
|
+
removeLink: (userId) => instance.removeLink(userId)
|
|
93177
|
+
};
|
|
93178
|
+
this.fulfillments.set(instance, deps);
|
|
93179
|
+
return deps;
|
|
93180
|
+
}
|
|
93181
|
+
buildDeviceExportProvider() {
|
|
93182
|
+
return {
|
|
93183
|
+
getStatus: async (input) => {
|
|
93184
|
+
const requested = statusInstanceOf(input);
|
|
93185
|
+
const rows = await this.requireRegistry().list();
|
|
93186
|
+
const target = requested ?? rows[0]?.id;
|
|
93187
|
+
if (target === void 0) return {
|
|
93188
|
+
linkState: "unlinked",
|
|
93189
|
+
exposedDeviceCount: 0,
|
|
93190
|
+
setup: await this.buildSetupBlock(void 0, 0)
|
|
93191
|
+
};
|
|
93192
|
+
const instance = await this.requireInstance(target);
|
|
93193
|
+
return {
|
|
93194
|
+
linkState: instance.linkedAccounts.length > 0 ? "linked" : "unlinked",
|
|
93195
|
+
exposedDeviceCount: instance.devices.length,
|
|
93196
|
+
setup: await this.buildSetupBlock(instance.id, instance.linkedAccounts.length)
|
|
93197
|
+
};
|
|
93198
|
+
},
|
|
93199
|
+
listInstances: async () => (await this.requireRegistry().list()).map((row) => ({
|
|
93200
|
+
instanceId: row.id,
|
|
93201
|
+
name: row.body.name,
|
|
93202
|
+
enabled: row.body.enabled !== false,
|
|
93203
|
+
kind: "google-home"
|
|
93204
|
+
})),
|
|
93205
|
+
listSupportedDeviceKinds: async ({ instanceId }) => {
|
|
93206
|
+
await this.requireInstance(instanceId ?? "export-google");
|
|
93207
|
+
return [...SUPPORTED_DEVICE_KINDS];
|
|
93208
|
+
},
|
|
93209
|
+
listExposedDevices: async ({ instanceId }) => {
|
|
93210
|
+
return (await this.requireInstance(instanceId ?? "export-google")).devices.map((entry) => ({ deviceId: String(entry.deviceId) }));
|
|
93211
|
+
},
|
|
93212
|
+
exposeDevice: async ({ instanceId, deviceId }) => this.exposeDevice(await this.requireInstance(instanceId ?? "export-google"), deviceId),
|
|
93213
|
+
unexposeDevice: async ({ instanceId, deviceId }) => this.unexposeDevice(await this.requireInstance(instanceId ?? "export-google"), deviceId),
|
|
93214
|
+
listSupportedEntityKinds: async () => ["device", "action"],
|
|
93215
|
+
listExposedEntities: async ({ instanceId }) => {
|
|
93216
|
+
const instance = await this.requireInstance(instanceId ?? "export-google");
|
|
93217
|
+
await instance.scenes.reconcile();
|
|
93218
|
+
return [...instance.devices.map((entry) => ({ entity: {
|
|
93219
|
+
kind: "device",
|
|
93220
|
+
deviceId: String(entry.deviceId)
|
|
93221
|
+
} })), ...instance.scenes.list()];
|
|
93222
|
+
},
|
|
93223
|
+
exposeEntity: async ({ instanceId, entity }) => {
|
|
93224
|
+
const instance = await this.requireInstance(instanceId ?? "export-google");
|
|
93225
|
+
if (entity.kind === "device") return this.exposeDevice(instance, entity.deviceId);
|
|
93226
|
+
if (entity.kind === "action") return instance.scenes.expose(entity.actionId);
|
|
93227
|
+
throw new Error("export-google: a notification target cannot be exported to Google Home");
|
|
93228
|
+
},
|
|
93229
|
+
unexposeEntity: async ({ instanceId, entity }) => {
|
|
93230
|
+
const instance = await this.requireInstance(instanceId ?? "export-google");
|
|
93231
|
+
if (entity.kind === "device") return this.unexposeDevice(instance, entity.deviceId);
|
|
93232
|
+
if (entity.kind === "action") return instance.scenes.unexpose(entity.actionId);
|
|
93233
|
+
throw new Error("export-google: a notification target cannot be exported to Google Home");
|
|
93234
|
+
},
|
|
93235
|
+
getDeviceSettingsContribution: (input) => this.buildDeviceSettingsContribution(Number(input.deviceId)),
|
|
93236
|
+
getDeviceLiveContribution: async () => null,
|
|
93237
|
+
applyDeviceSettingsPatch: (input) => this.applyDeviceSettingsPatch(Number(input.deviceId), input.patch)
|
|
93238
|
+
};
|
|
91755
93239
|
}
|
|
91756
|
-
async exposeDevice(deviceIdRaw) {
|
|
93240
|
+
async exposeDevice(instance, deviceIdRaw) {
|
|
91757
93241
|
const deviceId = Number.parseInt(deviceIdRaw, 10);
|
|
91758
93242
|
if (!Number.isFinite(deviceId)) throw new Error(`export-google: deviceId must be numeric — got "${deviceIdRaw}"`);
|
|
91759
93243
|
const facts = await this.requireGateway().loadFacts(deviceId).catch((err) => {
|
|
@@ -91764,47 +93248,38 @@ var ExportGoogleAddon = class extends BaseAddon {
|
|
|
91764
93248
|
this.ctx.logger.warn("export-google: refused to expose — no exported capability", {
|
|
91765
93249
|
tags: { deviceId },
|
|
91766
93250
|
meta: {
|
|
93251
|
+
instanceId: instance.id,
|
|
91767
93252
|
deviceType: facts.deviceType,
|
|
91768
93253
|
capNames: facts.capNames
|
|
91769
93254
|
}
|
|
91770
93255
|
});
|
|
91771
93256
|
throw new Error(`export-google: device ${deviceId} has no capability this addon exports (bound: ${facts.capNames.join(", ") || "none"})`);
|
|
91772
93257
|
}
|
|
91773
|
-
const next =
|
|
91774
|
-
|
|
93258
|
+
const next = instance.devices.filter((e) => e.deviceId !== deviceId);
|
|
93259
|
+
await instance.writeExports({ devices: [...next, {
|
|
91775
93260
|
deviceId,
|
|
91776
93261
|
exposedAt: Date.now()
|
|
93262
|
+
}] });
|
|
93263
|
+
this.ctx.logger.info("export-google: exposed device — visible after the next Google SYNC (\"Hey Google, sync my devices\")", {
|
|
93264
|
+
tags: { deviceId },
|
|
93265
|
+
meta: { instanceId: instance.id }
|
|
91777
93266
|
});
|
|
91778
|
-
await this.updateGlobalSettings({ exposed: next });
|
|
91779
|
-
this.ctx.logger.info("export-google: exposed device — visible after the next Google SYNC (\"Hey Google, sync my devices\")", { tags: { deviceId } });
|
|
91780
93267
|
}
|
|
91781
|
-
async unexposeDevice(deviceIdRaw) {
|
|
93268
|
+
async unexposeDevice(instance, deviceIdRaw) {
|
|
91782
93269
|
const deviceId = Number.parseInt(deviceIdRaw, 10);
|
|
91783
93270
|
if (!Number.isFinite(deviceId)) return;
|
|
91784
|
-
const next =
|
|
91785
|
-
if (next.length ===
|
|
91786
|
-
await
|
|
91787
|
-
this.ctx.logger.info("export-google: unexposed device — removed from Google on its next SYNC", {
|
|
93271
|
+
const next = instance.devices.filter((e) => e.deviceId !== deviceId);
|
|
93272
|
+
if (next.length === instance.devices.length) return;
|
|
93273
|
+
await instance.writeExports({ devices: next });
|
|
93274
|
+
this.ctx.logger.info("export-google: unexposed device — removed from Google on its next SYNC", {
|
|
93275
|
+
tags: { deviceId },
|
|
93276
|
+
meta: { instanceId: instance.id }
|
|
93277
|
+
});
|
|
91788
93278
|
}
|
|
91789
93279
|
requireGateway() {
|
|
91790
93280
|
if (this.gateway === null) throw new Error("export-google: addon not initialized");
|
|
91791
93281
|
return this.gateway;
|
|
91792
93282
|
}
|
|
91793
|
-
async recordLink(caller) {
|
|
91794
|
-
if (this.config.linkedAccounts.some((account) => account.userId === caller.userId)) return;
|
|
91795
|
-
const next = [...this.config.linkedAccounts, {
|
|
91796
|
-
userId: caller.userId,
|
|
91797
|
-
username: caller.username,
|
|
91798
|
-
linkedAt: Date.now()
|
|
91799
|
-
}];
|
|
91800
|
-
await this.updateGlobalSettings({ linkedAccounts: next });
|
|
91801
|
-
this.ctx.logger.info("export-google: recorded linked account", { meta: { userId: caller.userId } });
|
|
91802
|
-
}
|
|
91803
|
-
async removeLink(userId) {
|
|
91804
|
-
const next = this.config.linkedAccounts.filter((account) => account.userId !== userId);
|
|
91805
|
-
if (next.length === this.config.linkedAccounts.length) return;
|
|
91806
|
-
await this.updateGlobalSettings({ linkedAccounts: next });
|
|
91807
|
-
}
|
|
91808
93283
|
/**
|
|
91809
93284
|
* The three URLs the operator pastes into the Actions console, plus the
|
|
91810
93285
|
* linked-account count.
|
|
@@ -91814,88 +93289,85 @@ var ExportGoogleAddon = class extends BaseAddon {
|
|
|
91814
93289
|
* value still travels in the `getStatus` response — so it would be the wrong
|
|
91815
93290
|
* tool for a real credential anyway (docs/decisions/adr-0269-a-google-export-that-holds-no-google-credential.md).
|
|
91816
93291
|
*/
|
|
91817
|
-
async buildSetupBlock() {
|
|
93292
|
+
async buildSetupBlock(instanceId, linkedAccounts) {
|
|
91818
93293
|
return buildConsoleSetupFromRole({
|
|
91819
93294
|
addonId: ADDON_ID,
|
|
91820
|
-
|
|
93295
|
+
...instanceId !== void 0 ? { instanceId } : {},
|
|
93296
|
+
linkedAccounts,
|
|
91821
93297
|
read: () => this.ctx.api.localNetwork.getAddresses.query()
|
|
91822
93298
|
});
|
|
91823
93299
|
}
|
|
91824
|
-
globalSettingsSchema() {
|
|
91825
|
-
return this.schema({ sections: [{
|
|
91826
|
-
id: ADDON_ID,
|
|
91827
|
-
title: "Connection",
|
|
91828
|
-
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.",
|
|
91829
|
-
columns: 1,
|
|
91830
|
-
fields: [{
|
|
91831
|
-
type: "info",
|
|
91832
|
-
key: "__google-setup-banner",
|
|
91833
|
-
label: "Setup overview",
|
|
91834
|
-
variant: "info",
|
|
91835
|
-
content: [
|
|
91836
|
-
"This hub must be reachable from the public internet over HTTPS (Cloudflare Tunnel, Tailscale Funnel, …) — Google calls the fulfillment URL from its own cloud.",
|
|
91837
|
-
"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.",
|
|
91838
|
-
"Cameras are not exported, and state is not pushed: Google polls. Ask \"Hey Google, sync my devices\" after exposing something new."
|
|
91839
|
-
].join("\n")
|
|
91840
|
-
}]
|
|
91841
|
-
}] });
|
|
91842
|
-
}
|
|
91843
93300
|
/**
|
|
91844
|
-
* Per-device "Export" panel. Offered only for devices this
|
|
91845
|
-
* represent — a toggle on a camera would be a switch that promises
|
|
91846
|
-
* `buildSyncDevice` then refuses.
|
|
93301
|
+
* Per-device "Export" panel: one section per enabled instance. Offered only for devices this
|
|
93302
|
+
* addon can actually represent — a toggle on a camera would be a switch that promises
|
|
93303
|
+
* something `buildSyncDevice` then refuses.
|
|
91847
93304
|
*/
|
|
91848
93305
|
async buildDeviceSettingsContribution(deviceId) {
|
|
91849
93306
|
const facts = await this.requireGateway().loadFacts(deviceId).catch(() => null);
|
|
91850
93307
|
if (facts === null) return null;
|
|
91851
93308
|
const descriptors = traitsForCaps(facts.capNames);
|
|
91852
93309
|
if (descriptors.length === 0) return null;
|
|
91853
|
-
const
|
|
91854
|
-
const
|
|
91855
|
-
const
|
|
91856
|
-
|
|
91857
|
-
|
|
91858
|
-
|
|
91859
|
-
|
|
91860
|
-
|
|
91861
|
-
|
|
91862
|
-
|
|
91863
|
-
|
|
91864
|
-
|
|
91865
|
-
title: "Google Home Export",
|
|
93310
|
+
const registry = this.requireRegistry();
|
|
93311
|
+
const rows = (await registry.list()).filter((row) => row.body.enabled !== false);
|
|
93312
|
+
const sections = [];
|
|
93313
|
+
for (const row of rows) {
|
|
93314
|
+
const instance = await registry.get(row.id);
|
|
93315
|
+
if (instance === null) continue;
|
|
93316
|
+
const enabled = instance.isExposed(deviceId);
|
|
93317
|
+
const linked = instance.linkedAccounts.length;
|
|
93318
|
+
const statusLabel = enabled ? `Exposed as ${descriptors.map((d) => d.trait.replace("action.devices.traits.", "")).join(" + ")}${linked > 0 ? `, ${linked} linked Google account(s)` : " (no linked Google account yet)"}` : "Not exposed";
|
|
93319
|
+
sections.push({
|
|
93320
|
+
id: `${ADDON_ID}:${instance.id}`,
|
|
93321
|
+
title: rows.length === 1 ? "Google Home Export" : `Google Home Export — ${instance.name}`,
|
|
91866
93322
|
description: "Surface this device to the linked Google Home account.",
|
|
91867
93323
|
tab: "export",
|
|
91868
93324
|
columns: 1,
|
|
91869
|
-
order: 30,
|
|
93325
|
+
order: 30 + sections.length,
|
|
91870
93326
|
fields: [{
|
|
91871
93327
|
type: "info",
|
|
91872
|
-
key:
|
|
93328
|
+
key: `__google-status:${instance.id}`,
|
|
91873
93329
|
label: "Status",
|
|
91874
|
-
content:
|
|
93330
|
+
content: statusLabel,
|
|
91875
93331
|
variant: "info"
|
|
91876
93332
|
}, {
|
|
91877
93333
|
type: "boolean",
|
|
91878
|
-
key:
|
|
93334
|
+
key: deviceKey(instance.id, deviceId),
|
|
91879
93335
|
label: "Expose to Google Home",
|
|
91880
93336
|
description: "Google picks the change up on its next sync — say \"Hey Google, sync my devices\" to force one.",
|
|
91881
93337
|
style: "switch",
|
|
91882
93338
|
value: enabled,
|
|
91883
93339
|
immediate: true
|
|
91884
93340
|
}]
|
|
91885
|
-
}
|
|
93341
|
+
});
|
|
93342
|
+
}
|
|
93343
|
+
if (sections.length === 0) return null;
|
|
93344
|
+
return {
|
|
93345
|
+
tabs: [{
|
|
93346
|
+
id: "export",
|
|
93347
|
+
label: "Export",
|
|
93348
|
+
icon: "share-2",
|
|
93349
|
+
order: 80
|
|
93350
|
+
}],
|
|
93351
|
+
sections
|
|
91886
93352
|
};
|
|
91887
93353
|
}
|
|
91888
93354
|
async applyDeviceSettingsPatch(deviceId, patch) {
|
|
91889
|
-
const
|
|
91890
|
-
|
|
91891
|
-
|
|
91892
|
-
|
|
91893
|
-
|
|
91894
|
-
|
|
93355
|
+
for (const [key, next] of Object.entries(patch)) {
|
|
93356
|
+
const match = DEVICE_KEY.exec(key);
|
|
93357
|
+
if (match === null || Number(match[2]) !== deviceId) continue;
|
|
93358
|
+
const instanceId = match[1] ?? "";
|
|
93359
|
+
if (typeof next !== "boolean") {
|
|
93360
|
+
this.ctx.logger.warn("export-google: ignored export toggle — value was not a boolean", {
|
|
93361
|
+
tags: { deviceId },
|
|
93362
|
+
meta: { instanceId }
|
|
93363
|
+
});
|
|
93364
|
+
continue;
|
|
93365
|
+
}
|
|
93366
|
+
const instance = await this.requireInstance(instanceId);
|
|
93367
|
+
if (next === instance.isExposed(deviceId)) continue;
|
|
93368
|
+
if (next) await this.exposeDevice(instance, String(deviceId));
|
|
93369
|
+
else await this.unexposeDevice(instance, String(deviceId));
|
|
91895
93370
|
}
|
|
91896
|
-
if (next === this.isExposed(deviceId)) return { success: true };
|
|
91897
|
-
if (next) await this.exposeDevice(String(deviceId));
|
|
91898
|
-
else await this.unexposeDevice(String(deviceId));
|
|
91899
93371
|
return { success: true };
|
|
91900
93372
|
}
|
|
91901
93373
|
};
|