@camstack/types 1.2.275 → 1.2.276

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/dist/index.js CHANGED
@@ -9790,6 +9790,935 @@ var CompositionBlockStateSchema = zod.z.object({
9790
9790
  fields: zod.z.array(CompositionFieldStateSchema)
9791
9791
  });
9792
9792
  //#endregion
9793
+ //#region src/composition/plan-result.ts
9794
+ function problem(code, path, message) {
9795
+ return {
9796
+ code,
9797
+ path,
9798
+ message
9799
+ };
9800
+ }
9801
+ function refused(...problems) {
9802
+ return {
9803
+ problems,
9804
+ fields: [],
9805
+ features: [],
9806
+ events: []
9807
+ };
9808
+ }
9809
+ /** Where a planned field sits in the composition: `features[N].fields.<path>` or `features[N].items.<key>.fields.<path>`. */
9810
+ function compositionFieldAt(field) {
9811
+ const inner = field.item === void 0 ? "fields" : `items.${field.item.key}.fields`;
9812
+ return `features[${field.featureIndex}].${inner}.${field.path}`;
9813
+ }
9814
+ //#endregion
9815
+ //#region src/composition/expression-kinds.ts
9816
+ var NUMBER = {
9817
+ kind: "fixed",
9818
+ result: ["number"]
9819
+ };
9820
+ var BOOLEAN = {
9821
+ kind: "fixed",
9822
+ result: ["boolean"]
9823
+ };
9824
+ /** One rule per builtin. `expression-kinds.spec.ts` fails for a builtin missing here. */
9825
+ var BUILTIN_RESULT_KINDS = Object.freeze({
9826
+ min: NUMBER,
9827
+ max: NUMBER,
9828
+ abs: NUMBER,
9829
+ floor: NUMBER,
9830
+ ceil: NUMBER,
9831
+ sqrt: NUMBER,
9832
+ round: NUMBER,
9833
+ pow: NUMBER,
9834
+ clamp: NUMBER,
9835
+ avg: NUMBER,
9836
+ sum: NUMBER,
9837
+ age: NUMBER,
9838
+ convert: NUMBER,
9839
+ coalesce: { kind: "coalesce" },
9840
+ any: BOOLEAN,
9841
+ all: BOOLEAN,
9842
+ within: BOOLEAN,
9843
+ latest: {
9844
+ kind: "fixed",
9845
+ result: ["number", "null"]
9846
+ },
9847
+ number: {
9848
+ kind: "fixed",
9849
+ result: ["number", "null"]
9850
+ },
9851
+ rose: {
9852
+ kind: "fixed",
9853
+ result: ["number", "null"]
9854
+ },
9855
+ count: NUMBER
9856
+ });
9857
+ var KindInferenceError = class extends Error {};
9858
+ function kindOfValue(value) {
9859
+ if (value === null) return "null";
9860
+ if (typeof value === "number") return "number";
9861
+ if (typeof value === "string") return "string";
9862
+ return "boolean";
9863
+ }
9864
+ function only(kind) {
9865
+ return new Set([kind]);
9866
+ }
9867
+ function union(...sets) {
9868
+ return new Set(sets.flatMap((s) => [...s]));
9869
+ }
9870
+ function withoutNull(set) {
9871
+ return new Set([...set].filter((k) => k !== "null"));
9872
+ }
9873
+ function binaryKinds(op, left, right) {
9874
+ if (op === "+") {
9875
+ const all = [...left, ...right];
9876
+ if (all.every((k) => k === "string")) return only("string");
9877
+ if (all.every((k) => k === "number")) return only("number");
9878
+ return new Set(["number", "string"]);
9879
+ }
9880
+ if (op === "-" || op === "*" || op === "/" || op === "%") return only("number");
9881
+ return only("boolean");
9882
+ }
9883
+ /** "exactly N" / "at least N" / "N–M", for an arity refusal that says what IS allowed. */
9884
+ function arityRange(builtin) {
9885
+ if (builtin.minArgs === builtin.maxArgs) return `exactly ${builtin.minArgs}`;
9886
+ if (builtin.maxArgs === Number.POSITIVE_INFINITY) return `at least ${builtin.minArgs}`;
9887
+ return `${builtin.minArgs}–${builtin.maxArgs}`;
9888
+ }
9889
+ function callKinds(callee, args) {
9890
+ const builtin = require_composition.EXPRESSION_BUILTINS[callee];
9891
+ if (builtin !== void 0 && (args.length < builtin.minArgs || args.length > builtin.maxArgs)) throw new KindInferenceError(`${callee}: wrong number of arguments (${args.length}); expected ${arityRange(builtin)}`);
9892
+ const rule = BUILTIN_RESULT_KINDS[callee];
9893
+ if (rule === void 0) throw new KindInferenceError(`no result-kind rule for builtin '${callee}'`);
9894
+ if (rule.kind === "fixed") return new Set(rule.result);
9895
+ const nonNull = union(...args.map(withoutNull));
9896
+ return args.every((a) => a.has("null")) ? union(nonNull, only("null")) : nonNull;
9897
+ }
9898
+ function kindsOf(node, bindings) {
9899
+ switch (node.kind) {
9900
+ case "literal": return only(kindOfValue(node.value));
9901
+ case "identifier": {
9902
+ if (node.name === "now") return only("number");
9903
+ const bound = bindings.get(node.name);
9904
+ if (bound === void 0) throw new KindInferenceError(`unbound identifier '${node.name}'`);
9905
+ return bound;
9906
+ }
9907
+ case "unary": return only(node.op === "!" ? "boolean" : "number");
9908
+ case "binary": return binaryKinds(node.op, kindsOf(node.left, bindings), kindsOf(node.right, bindings));
9909
+ case "logical": return union(kindsOf(node.left, bindings), kindsOf(node.right, bindings));
9910
+ case "conditional": return union(kindsOf(node.consequent, bindings), kindsOf(node.alternate, bindings));
9911
+ case "call": return callKinds(node.callee, node.args.map((a) => kindsOf(a, bindings)));
9912
+ }
9913
+ }
9914
+ function nodeContainsCall(node, callee) {
9915
+ switch (node.kind) {
9916
+ case "literal":
9917
+ case "identifier": return false;
9918
+ case "unary": return nodeContainsCall(node.operand, callee);
9919
+ case "binary":
9920
+ case "logical": return nodeContainsCall(node.left, callee) || nodeContainsCall(node.right, callee);
9921
+ case "conditional": return nodeContainsCall(node.test, callee) || nodeContainsCall(node.consequent, callee) || nodeContainsCall(node.alternate, callee);
9922
+ case "call": return node.callee === callee || node.args.some((arg) => nodeContainsCall(arg, callee));
9923
+ }
9924
+ }
9925
+ function expressionContainsBuiltinCall(expr, callee) {
9926
+ const compiled = require_composition.compileExpressionSafe(expr);
9927
+ return compiled.ok && nodeContainsCall(compiled.parsed.ast, callee);
9928
+ }
9929
+ function inferExpressionKinds(input) {
9930
+ const compiled = require_composition.compileExpressionSafe(input.expr);
9931
+ if (!compiled.ok) return {
9932
+ ok: false,
9933
+ error: compiled.error
9934
+ };
9935
+ try {
9936
+ return {
9937
+ ok: true,
9938
+ kinds: kindsOf(compiled.parsed.ast, input.bindingKinds)
9939
+ };
9940
+ } catch (err) {
9941
+ if (err instanceof KindInferenceError) return {
9942
+ ok: false,
9943
+ error: err.message
9944
+ };
9945
+ throw err;
9946
+ }
9947
+ }
9948
+ //#endregion
9949
+ //#region src/composition/field-kinds.ts
9950
+ /**
9951
+ * The kind half of planning a composition field (D659): which kinds a source
9952
+ * can produce, whether they fit a target field, and the field's role.
9953
+ * Shared by the top-level planner (`validate-composition.ts`) and the item
9954
+ * planner (`composition-items.ts`). Internal to the composition module — NOT
9955
+ * in the barrel: these are planner internals, not a published contract.
9956
+ */
9957
+ function readKinds(read, lookupCap) {
9958
+ const def = lookupCap(read.cap);
9959
+ const schema = def?.runtimeState ?? def?.status?.schema;
9960
+ if (def === null || schema === void 0) return {
9961
+ ok: false,
9962
+ code: "source-field-unknown",
9963
+ message: `no capability \`${read.cap}\` with state to read`
9964
+ };
9965
+ const field = describeStateField(schema, read.fieldPath);
9966
+ if (field === null) return {
9967
+ ok: false,
9968
+ code: "source-field-unknown",
9969
+ message: `\`${read.cap}\` has no field \`${read.fieldPath}\``
9970
+ };
9971
+ const base = field.kind === "enum" ? "string" : field.kind;
9972
+ return {
9973
+ ok: true,
9974
+ kinds: new Set(field.nullable ? [base, "null"] : [base])
9975
+ };
9976
+ }
9977
+ function sourceKinds(source, lookupCap) {
9978
+ if (source.kind === "from") return readKinds(source, lookupCap);
9979
+ if (source.kind === "code") return {
9980
+ ok: false,
9981
+ code: "reserved-variant",
9982
+ message: "code fields arrive in slice 4"
9983
+ };
9984
+ const bindingKinds = /* @__PURE__ */ new Map();
9985
+ for (const [name, binding] of Object.entries(source.bindings)) {
9986
+ if (binding.kind === "literal") {
9987
+ bindingKinds.set(name, new Set([kindOfValue(binding.value)]));
9988
+ continue;
9989
+ }
9990
+ const kinds = readKinds(binding, lookupCap);
9991
+ if (!kinds.ok) return {
9992
+ ...kinds,
9993
+ message: `binding \`${name}\`: ${kinds.message}`
9994
+ };
9995
+ bindingKinds.set(name, kinds.kinds);
9996
+ }
9997
+ const inferred = inferExpressionKinds({
9998
+ expr: source.expr,
9999
+ bindingKinds
10000
+ });
10001
+ return inferred.ok ? {
10002
+ ok: true,
10003
+ kinds: inferred.kinds
10004
+ } : {
10005
+ ok: false,
10006
+ code: "expression-invalid",
10007
+ message: inferred.error
10008
+ };
10009
+ }
10010
+ function compatibility(cap, target, kinds, at) {
10011
+ const allowed = target.kind === "enum" ? "string" : target.kind;
10012
+ const offending = [...kinds].filter((k) => k !== "null" && k !== allowed);
10013
+ const problems = [];
10014
+ if (offending.length > 0) problems.push(problem("kind-mismatch", at, `\`${cap}.${target.path}\` is a ${target.kind}; this source can produce ${offending.join(" or ")}`));
10015
+ if (kinds.has("null") && !target.nullable) problems.push(problem("may-be-null", at, `\`${cap}.${target.path}\` cannot be null and this source can produce null — wrap it in coalesce(…) or pick a non-null source`));
10016
+ return problems;
10017
+ }
10018
+ /**
10019
+ * A string a source produces WITHOUT reading any device — a field-level
10020
+ * `expression` source whose compiled AST is a bare string literal (`"red"`,
10021
+ * never `a` or `a + "x"`). Anything else that can only produce `'string'` at
10022
+ * the kind level (a `from` read of an enum-typed source field, a computed
10023
+ * expression) is NOT checked against the target's `enumValues` here: the
10024
+ * kind inference already collapsed it to the coarse `'string'` kind, losing
10025
+ * whichever enum it actually came from, so membership can only be judged at
10026
+ * write time against the runtime-state schema. Known limitation — see the
10027
+ * fix report for Task 6 round 1.
10028
+ */
10029
+ function literalStringValue(source) {
10030
+ if (source.kind !== "expression") return null;
10031
+ const compiled = require_composition.compileExpressionSafe(source.expr);
10032
+ if (!compiled.ok) return null;
10033
+ const ast = compiled.parsed.ast;
10034
+ return ast.kind === "literal" && typeof ast.value === "string" ? ast.value : null;
10035
+ }
10036
+ /**
10037
+ * An enum target whose source is a save-time-KNOWN string literal outside its
10038
+ * `enumValues` is refused now rather than left to fail the write later. A
10039
+ * dynamic source (a `from` read, a non-literal expression) is left to
10040
+ * runtime — see {@link literalStringValue}.
10041
+ */
10042
+ function enumLiteralProblem(cap, target, source, at) {
10043
+ if (target.kind !== "enum" || target.enumValues === void 0) return null;
10044
+ const value = literalStringValue(source);
10045
+ if (value === null || target.enumValues.includes(value)) return null;
10046
+ const allowed = target.enumValues.map((v) => `\`${v}\``).join(", ");
10047
+ return problem("kind-mismatch", at, `\`${cap}.${target.path}\` accepts only ${allowed}; this source is the literal \`${value}\``);
10048
+ }
10049
+ function roleOf(source) {
10050
+ if (source.kind !== "expression") return "derived";
10051
+ if (expressionContainsBuiltinCall(source.expr, "count")) return "accumulator";
10052
+ if (require_composition.fieldReads(source).length > 0) return "derived";
10053
+ const compiled = require_composition.compileExpressionSafe(source.expr);
10054
+ return compiled.ok && compiled.parsed.identifiers.has("now") ? "clock" : "constant";
10055
+ }
10056
+ /**
10057
+ * How a planned field says "unavailable", per feature mode and AFTER `roleOf`
10058
+ * (D393, D663 rulings S1 + S1b). The composer cannot take a device it does not
10059
+ * own offline, and D393 forbids a stale number, so on an existing target a
10060
+ * field that READS a source never gets `offline`.
10061
+ */
10062
+ function unavailableFor(tf, role, mode, cap, at) {
10063
+ if (mode === "replace" && (role === "derived" || role === "accumulator")) return {
10064
+ ok: true,
10065
+ unavailable: "release"
10066
+ };
10067
+ if (mode === "new" || role !== "derived") return {
10068
+ ok: true,
10069
+ unavailable: tf.nullable ? "null" : "offline"
10070
+ };
10071
+ if (tf.nullable) return {
10072
+ ok: true,
10073
+ unavailable: "null"
10074
+ };
10075
+ if (tf.enumValues?.includes("unknown") === true) return {
10076
+ ok: true,
10077
+ unavailable: "unknown"
10078
+ };
10079
+ return {
10080
+ ok: false,
10081
+ problem: problem("not-replaceable", at, `\`${cap}.${tf.path}\` reads a source but can say neither null nor 'unknown', and an ADDED capability has no native reading to fall back to (D393, D663)`)
10082
+ };
10083
+ }
10084
+ //#endregion
10085
+ //#region src/composition/composition-items.ts
10086
+ /** Item fields the composer writes itself, with the value it writes. */
10087
+ var COMPOSED_ITEM_FIXED_FIELDS = { resettable: false };
10088
+ function reservedItemFields(itemArray) {
10089
+ return new Set([
10090
+ itemArray.keyField,
10091
+ ...itemArray.labelField === void 0 ? [] : [itemArray.labelField],
10092
+ ...Object.keys(COMPOSED_ITEM_FIXED_FIELDS)
10093
+ ]);
10094
+ }
10095
+ /** A required leaf under an optional parent is required only once something writes that parent. */
10096
+ function leafRequired(itemArray, path, written) {
10097
+ const described = describeStateField(itemArray.itemSchema, path);
10098
+ if (described === null || !described.required) return false;
10099
+ return optionalAncestors(itemArray.itemSchema, path).every((parent) => written.some((w) => w.startsWith(`${parent}.`)));
10100
+ }
10101
+ function missingLeaves({ capName, itemArray, reserved }, item, at) {
10102
+ const written = Object.keys(item.fields);
10103
+ return enumerateSchemaFields(itemArray.itemSchema).flatMap((leaf) => {
10104
+ if (reserved.has(leaf.path) || leaf.path in item.fields) return [];
10105
+ if (!leafRequired(itemArray, leaf.path, written)) return [];
10106
+ const described = describeStateField(itemArray.itemSchema, leaf.path);
10107
+ if (described === null || described.nullable) return [];
10108
+ return [problem("missing-field", `${at}.fields.${leaf.path}`, `\`${capName}.${itemArray.path}[].${leaf.path}\` is required and has no source`)];
10109
+ });
10110
+ }
10111
+ function planItemField(ctx, leaf) {
10112
+ const { capName, itemArray, featureIndex, lookupCap } = ctx;
10113
+ const { key, label, path, source } = leaf;
10114
+ const at = `features[${featureIndex}].items.${key}.fields.${path}`;
10115
+ if (ctx.reserved.has(path)) return refused(problem("item-field-reserved", at, `\`${capName}.${itemArray.path}[].${path}\` is set by the composer itself — it takes no source`));
10116
+ const tf = describeStateField(itemArray.itemSchema, path);
10117
+ if (tf === null) return refused(problem("unknown-field", at, `a \`${capName}\` item has no field \`${path}\``));
10118
+ const kinds = sourceKinds(source, lookupCap);
10119
+ if (!kinds.ok) return refused(problem(kinds.code, at, kinds.message));
10120
+ const role = roleOf(source);
10121
+ const unavailable = unavailableFor(tf, role, ctx.mode, capName, at);
10122
+ if (!unavailable.ok) return refused(unavailable.problem);
10123
+ const plan = {
10124
+ cap: capName,
10125
+ path,
10126
+ item: {
10127
+ arrayPath: itemArray.path,
10128
+ key,
10129
+ label
10130
+ },
10131
+ featureIndex,
10132
+ kind: tf.kind,
10133
+ nullable: tf.nullable,
10134
+ required: tf.required,
10135
+ unavailable: unavailable.unavailable,
10136
+ role,
10137
+ source,
10138
+ reads: [...require_composition.fieldReads(source)]
10139
+ };
10140
+ const enumProblem = enumLiteralProblem(capName, tf, source, at);
10141
+ return {
10142
+ problems: [...compatibility(capName, tf, kinds.kinds, at), ...enumProblem === null ? [] : [enumProblem]],
10143
+ fields: [plan],
10144
+ features: [],
10145
+ events: []
10146
+ };
10147
+ }
10148
+ function planItems(def, feature, featureIndex, lookupCap, mode = "new") {
10149
+ const at = `features[${featureIndex}].items`;
10150
+ const itemArray = def.status?.itemArray;
10151
+ if (itemArray === void 0) return refused(problem("not-item-array", at, `\`${def.name}\` has no item array — it takes no \`items\``));
10152
+ if (itemArray.path !== "items") return refused(problem("not-item-array", at, `\`${def.name}\`'s item array is at \`${itemArray.path}\`, not \`${require_composition.COMPOSITION_ITEM_ARRAY_PATH}\` — not composable yet`));
10153
+ const ctx = {
10154
+ capName: def.name,
10155
+ itemArray,
10156
+ reserved: reservedItemFields(itemArray),
10157
+ featureIndex,
10158
+ lookupCap,
10159
+ mode
10160
+ };
10161
+ const results = Object.entries(feature.items ?? {}).flatMap(([key, item]) => [{
10162
+ problems: missingLeaves(ctx, item, `${at}.${key}`),
10163
+ fields: [],
10164
+ features: [],
10165
+ events: []
10166
+ }, ...Object.entries(item.fields).map(([path, source]) => planItemField(ctx, {
10167
+ key,
10168
+ label: item.label,
10169
+ path,
10170
+ source
10171
+ }))]);
10172
+ return {
10173
+ problems: results.flatMap((r) => r.problems),
10174
+ fields: results.flatMap((r) => r.fields),
10175
+ features: [],
10176
+ events: []
10177
+ };
10178
+ }
10179
+ //#endregion
10180
+ //#region src/composition/composition-graph.ts
10181
+ /**
10182
+ * The field graph across every composition, and the cycles in it (D659).
10183
+ *
10184
+ * A node is ONE field of ONE device (`<addon>/<stableId>#<cap>.<field>`); an
10185
+ * edge points from a composed field to each field it reads. A cycle, direct or
10186
+ * through another composition, is refused at save by name (spec §2).
10187
+ *
10188
+ * The graph is built for ONE save: the CANDIDATE composition (the one being
10189
+ * validated) plus every STORED composition. The candidate replaces its own old
10190
+ * version, identified BY BLOCK ID wherever it sits in `stored` — whether a save
10191
+ * introduces or removes a cycle must never depend on array order. A DIFFERENT
10192
+ * block targeting the candidate's device is refused by name: one composition
10193
+ * per device (D663). Two different stored peers that (wrongly) target the same
10194
+ * device are corrupted state, not a cycle to resolve by picking one silently;
10195
+ * that is refused by name too (D391).
10196
+ *
10197
+ * A customization of an EXISTING device reads that device's NATIVE value for a
10198
+ * field it replaces or does not write ("Invert state" reads the `on` it
10199
+ * replaces): such a self-read is no edge, so it is never a cycle (D663).
10200
+ * Another composition reading that field reads the customizer's output.
10201
+ *
10202
+ * `findCompositionCycles` reports at least one cycle per cycle-SET (the DFS
10203
+ * marks a node `done` after its first expansion) — not every elementary cycle
10204
+ * through a shared node, so the path it names may AVOID the candidate while
10205
+ * one through it goes unreported. What a save refuses is therefore decided per
10206
+ * strongly connected component (`findCandidateCycles`, C-1). A dotted
10207
+ * `fieldPath` is matched only as an exact string: a write to `state.value` and
10208
+ * a read of `state` would not connect (no nested field writes exist yet).
10209
+ *
10210
+ * An item leaf is its own node, `…#consumables.items[desiccant].status`
10211
+ * (`featureFieldEntries`), so two items sharing an inner path never merge. No
10212
+ * READ can name an array element (`describeStateField` never describes one),
10213
+ * so an item node is write-only: its edges to sources are what the check needs.
10214
+ */
10215
+ /** Two blocks' compositions target the same device — refused by name, never silently resolved. */
10216
+ var CompositionGraphError = class extends Error {};
10217
+ /** `"cap.field"` of every field a peer writes — the same spelling as `compositionFieldKey`. */
10218
+ function writtenFields(peer) {
10219
+ return new Set(peer.composition.features.flatMap((feature) => !require_composition.compositionFeatureEnabled(feature) || feature.kind !== "fields" ? [] : require_composition.featureFieldEntries(feature).map(({ fieldPath }) => `${feature.cap}.${fieldPath}`)));
10220
+ }
10221
+ /** A read of the peer's OWN device is an edge only when it reads the peer's own output (rule 5, D663). */
10222
+ function readsComposedValue(peer, written, read) {
10223
+ if (require_composition.compositionSourceKey(read.source) !== require_composition.compositionSourceKey(peer.target)) return true;
10224
+ const field = `${read.cap}.${read.fieldPath}`;
10225
+ return written.has(field) && peer.replaced?.has(field) !== true;
10226
+ }
10227
+ function peerEdges(peer) {
10228
+ const written = writtenFields(peer);
10229
+ return peer.composition.features.flatMap((feature) => !require_composition.compositionFeatureEnabled(feature) || feature.kind !== "fields" ? [] : require_composition.featureFieldEntries(feature).map(({ fieldPath, source }) => [require_composition.compositionReadKey({
10230
+ source: peer.target,
10231
+ cap: feature.cap,
10232
+ fieldPath
10233
+ }), require_composition.fieldReads(source).filter((read) => readsComposedValue(peer, written, read)).map(require_composition.compositionReadKey)]));
10234
+ }
10235
+ /**
10236
+ * Every peer that actually takes part in the graph: each stored peer minus the
10237
+ * candidate's own old version (same block id — the drop happens before any
10238
+ * edge is built, so its old edges never enter the map), plus the candidate
10239
+ * itself, exactly once. Throws {@link CompositionGraphError} when a DIFFERENT
10240
+ * block targets the candidate's device, or two stored peers share a device.
10241
+ */
10242
+ function resolvedPeers(candidate, stored) {
10243
+ const candidateKey = require_composition.compositionSourceKey(candidate.target);
10244
+ const survivors = /* @__PURE__ */ new Map();
10245
+ for (const peer of stored) {
10246
+ if (peer.blockId === candidate.blockId) continue;
10247
+ const key = require_composition.compositionSourceKey(peer.target);
10248
+ if (key === candidateKey) throw new CompositionGraphError(`block \`${peer.blockId}\` and block \`${candidate.blockId}\` both target device \`${key}\` — one composition per device; delete or edit the existing one`);
10249
+ const clash = survivors.get(key);
10250
+ if (clash !== void 0) throw new CompositionGraphError(`two stored compositions (\`${clash.blockId}\`, \`${peer.blockId}\`) both target device \`${key}\` — refusing to build the field graph`);
10251
+ survivors.set(key, peer);
10252
+ }
10253
+ return [...survivors.values(), candidate];
10254
+ }
10255
+ function compositionEdges(candidate, stored) {
10256
+ const edges = resolvedPeers(candidate, stored).flatMap(peerEdges);
10257
+ return new Map(edges);
10258
+ }
10259
+ function findCompositionCycles(candidate, stored) {
10260
+ const edges = compositionEdges(candidate, stored);
10261
+ const marks = /* @__PURE__ */ new Map();
10262
+ const found = /* @__PURE__ */ new Map();
10263
+ const visit = (node, stack) => {
10264
+ const mark = marks.get(node);
10265
+ if (mark === "done") return;
10266
+ if (mark === "visiting") {
10267
+ const path = [...stack.slice(stack.indexOf(node)), node];
10268
+ const id = [...new Set(path)].toSorted().join("|");
10269
+ if (!found.has(id)) found.set(id, { path });
10270
+ return;
10271
+ }
10272
+ marks.set(node, "visiting");
10273
+ for (const next of edges.get(node) ?? []) visit(next, [...stack, node]);
10274
+ marks.set(node, "done");
10275
+ };
10276
+ for (const node of edges.keys()) visit(node, []);
10277
+ return [...found.values()];
10278
+ }
10279
+ /** Tarjan's strongly connected components over every node of the graph (sources included). */
10280
+ function stronglyConnected(edges) {
10281
+ const index = /* @__PURE__ */ new Map();
10282
+ const low = /* @__PURE__ */ new Map();
10283
+ const onStack = /* @__PURE__ */ new Set();
10284
+ const stack = [];
10285
+ const components = [];
10286
+ const connect = (node) => {
10287
+ index.set(node, index.size);
10288
+ low.set(node, index.get(node) ?? 0);
10289
+ stack.push(node);
10290
+ onStack.add(node);
10291
+ for (const next of edges.get(node) ?? []) if (!index.has(next)) {
10292
+ connect(next);
10293
+ low.set(node, Math.min(low.get(node) ?? 0, low.get(next) ?? 0));
10294
+ } else if (onStack.has(next)) low.set(node, Math.min(low.get(node) ?? 0, index.get(next) ?? 0));
10295
+ if (low.get(node) !== index.get(node)) return;
10296
+ const component = [];
10297
+ for (let member = stack.pop(); member !== void 0; member = stack.pop()) {
10298
+ onStack.delete(member);
10299
+ component.push(member);
10300
+ if (member === node) break;
10301
+ }
10302
+ components.push(component);
10303
+ };
10304
+ for (const node of edges.keys()) if (!index.has(node)) connect(node);
10305
+ return components;
10306
+ }
10307
+ /** The shortest walk from `start` back to itself inside `component` (one exists: the component has a cycle). */
10308
+ function cycleThrough(start, component, edges) {
10309
+ const parent = /* @__PURE__ */ new Map();
10310
+ const queue = [start];
10311
+ for (let head = 0; head < queue.length; head += 1) {
10312
+ const node = queue[head];
10313
+ if (node === void 0) break;
10314
+ for (const next of edges.get(node) ?? []) {
10315
+ if (next === start) {
10316
+ const chain = [];
10317
+ for (let at = node; at !== void 0 && at !== start; at = parent.get(at)) chain.push(at);
10318
+ return [
10319
+ start,
10320
+ ...chain.reverse(),
10321
+ start
10322
+ ];
10323
+ }
10324
+ if (!component.has(next) || parent.has(next)) continue;
10325
+ parent.set(next, node);
10326
+ queue.push(next);
10327
+ }
10328
+ }
10329
+ return [start, start];
10330
+ }
10331
+ /**
10332
+ * The cycles THIS save closes, decided per strongly connected component — never
10333
+ * per reported DFS path, which names one back-edge per revisit and can report a
10334
+ * component's cycle by a path that avoids the candidate while the one through it
10335
+ * goes unreported. A component refuses when it holds a candidate node and a
10336
+ * cycle (more than one node, or a self-loop). Components without a candidate
10337
+ * node are not this save's cycles.
10338
+ */
10339
+ function findCandidateCycles(candidate, stored) {
10340
+ const edges = compositionEdges(candidate, stored);
10341
+ const prefix = `${require_composition.compositionSourceKey(candidate.target)}#`;
10342
+ return stronglyConnected(edges).flatMap((members) => {
10343
+ const start = members.find((n) => n.startsWith(prefix));
10344
+ if (start === void 0) return [];
10345
+ const component = new Set(members);
10346
+ const selfLoop = members.length === 1 && (edges.get(start) ?? []).includes(start);
10347
+ if (members.length === 1 && !selfLoop) return [];
10348
+ return [{
10349
+ path: cycleThrough(start, component, edges),
10350
+ component
10351
+ }];
10352
+ });
10353
+ }
10354
+ //#endregion
10355
+ //#region src/composition/validate-composition.ts
10356
+ function buildCapabilityLookup(defs) {
10357
+ const byName = new Map(defs.map((d) => [d.name, d]));
10358
+ return (capName) => byName.get(capName) ?? null;
10359
+ }
10360
+ /** Caps every `BaseDevice` registers on itself; a second registration throws. */
10361
+ var BASE_DEVICE_CAPS = new Set(["device-status", "feature-probe"]);
10362
+ var PENDING_SELF = {
10363
+ addonId: require_composition.COMPOSER_ADDON_ID,
10364
+ stableId: `${require_composition.COMPOSED_DEVICE_STABLE_ID_PREFIX}(unsaved)`
10365
+ };
10366
+ /** The candidate's block id before its first save. Stored block ids are `randomUUID()`, so none can carry it. */
10367
+ var PENDING_BLOCK_ID = "(unsaved)";
10368
+ function composableCap(feature, at, lookupCap) {
10369
+ const def = lookupCap(feature.cap);
10370
+ if (def === null) return problem("unknown-capability", `${at}.cap`, `no capability is named \`${feature.cap}\``);
10371
+ if (BASE_DEVICE_CAPS.has(def.name)) return problem("not-composable", `${at}.cap`, `\`${def.name}\` is registered by every device itself — it cannot be composed`);
10372
+ const state = def.runtimeState;
10373
+ if (def.scope !== "device" || state === void 0) return problem("not-composable", `${at}.cap`, `\`${def.name}\` has no per-device state to compose`);
10374
+ return {
10375
+ def,
10376
+ state,
10377
+ fields: describeTopLevelStateFields(state)
10378
+ };
10379
+ }
10380
+ /**
10381
+ * A capability BUILT by the composition (a new device, or one ADDED to an
10382
+ * existing device) must fit the device type, serve no command, and have every
10383
+ * required field. A REPLACE needs none of it: the cap is bound (a fact), the
10384
+ * native keeps serving its methods, and only the named fields are owned (D663).
10385
+ */
10386
+ function builtCapProblems({ def, state, fields: targetFields }, feature, at, deviceType) {
10387
+ const problems = [];
10388
+ if (def.deviceTypes !== void 0 && !def.deviceTypes.includes(deviceType)) problems.push(problem("wrong-device-type", `${at}.cap`, `\`${def.name}\` is not offered on a \`${deviceType}\` device (it allows ${def.deviceTypes.join(", ")})`));
10389
+ const served = Object.entries(def.methods).filter(([name, m]) => m.systemOnly !== true && def.composedMethods?.[name] === void 0).map(([name]) => `\`${name}\``);
10390
+ if (served.length > 0) problems.push(problem("has-commands", `${at}.cap`, `\`${def.name}\` has ${served.join(", ")}, which a composed device cannot serve until commands arrive (slice 3)`));
10391
+ const itemArrayPath = feature.items === void 0 ? null : def.status?.itemArray?.path ?? null;
10392
+ for (const key of requiredTopLevelKeys(state)) {
10393
+ if (key === itemArrayPath) continue;
10394
+ if (!targetFields.has(key)) problems.push(problem("not-composable", `${at}.fields`, `\`${def.name}.${key}\` is not a scalar — nested fields arrive in a later slice`));
10395
+ else if (!(key in feature.fields)) problems.push(problem("missing-field", `${at}.fields.${key}`, `\`${def.name}.${key}\` is required and has no source`));
10396
+ }
10397
+ return problems;
10398
+ }
10399
+ function planTopLevelField({ def, fields }, field, mode, lookupCap) {
10400
+ const { featureIndex, path, source } = field;
10401
+ const fieldAt = `features[${featureIndex}].fields.${path}`;
10402
+ if (path.includes(".")) return refused(problem("nested-field", fieldAt, `\`${path}\` is nested — nested fields arrive in a later slice`));
10403
+ const tf = fields.get(path);
10404
+ if (tf === void 0) return refused(problem("unknown-field", fieldAt, `\`${def.name}\` has no field \`${path}\``));
10405
+ const kinds = sourceKinds(source, lookupCap);
10406
+ if (!kinds.ok) return refused(problem(kinds.code, fieldAt, kinds.message));
10407
+ const role = roleOf(source);
10408
+ const unavailable = unavailableFor(tf, role, mode, def.name, fieldAt);
10409
+ if (!unavailable.ok) return refused(unavailable.problem);
10410
+ const plan = {
10411
+ cap: def.name,
10412
+ path,
10413
+ featureIndex,
10414
+ kind: tf.kind,
10415
+ nullable: tf.nullable,
10416
+ required: tf.required,
10417
+ unavailable: unavailable.unavailable,
10418
+ role,
10419
+ source,
10420
+ reads: [...require_composition.fieldReads(source)]
10421
+ };
10422
+ const enumProblem = enumLiteralProblem(def.name, tf, source, fieldAt);
10423
+ return {
10424
+ problems: [...compatibility(def.name, tf, kinds.kinds, fieldAt), ...enumProblem === null ? [] : [enumProblem]],
10425
+ fields: [plan],
10426
+ features: [],
10427
+ events: []
10428
+ };
10429
+ }
10430
+ function planFeature(feature, featureIndex, target, lookupCap) {
10431
+ const at = `features[${featureIndex}]`;
10432
+ const cap = composableCap(feature, at, lookupCap);
10433
+ if ("code" in cap) return refused(cap);
10434
+ const capProblems = target.mode === "replace" ? [] : [...builtCapProblems(cap, feature, at, target.deviceType)];
10435
+ if (feature.commands !== void 0 && Object.keys(feature.commands).length > 0) capProblems.push(problem("reserved-variant", `${at}.commands`, "commands (`forward`) arrive in slice 3"));
10436
+ const perField = Object.entries(feature.fields).map(([path, source]) => planTopLevelField(cap, {
10437
+ featureIndex,
10438
+ path,
10439
+ source
10440
+ }, target.mode, lookupCap));
10441
+ const items = feature.items === void 0 ? [] : [planItems(cap.def, feature, featureIndex, lookupCap, target.mode)];
10442
+ const all = [...perField, ...items];
10443
+ const fields = all.flatMap((result) => result.fields);
10444
+ const featurePlan = {
10445
+ featureIndex,
10446
+ cap: cap.def.name,
10447
+ mode: target.mode
10448
+ };
10449
+ const eventPlan = planCompositionEvents(cap.def, featurePlan, fields);
10450
+ return {
10451
+ problems: [
10452
+ ...capProblems,
10453
+ ...all.flatMap((r) => r.problems),
10454
+ ...eventPlan.problems
10455
+ ],
10456
+ fields,
10457
+ features: [featurePlan],
10458
+ events: eventPlan.events
10459
+ };
10460
+ }
10461
+ /** A cap the device serves itself; one the composer grafted (an earlier ADD) is not native. */
10462
+ function isNativeCap(target, cap) {
10463
+ const owner = target.nativeCaps.get(cap);
10464
+ return owner !== void 0 && owner !== "composer";
10465
+ }
10466
+ /** The target read, or the refusal that replaces the whole plan when it could not be (D391). */
10467
+ function planTargetOf(composition, target) {
10468
+ if (composition.target.kind === "new") return {
10469
+ kind: "new",
10470
+ type: composition.target.type
10471
+ };
10472
+ const key = require_composition.compositionSourceKey(composition.target.device);
10473
+ if (target === void 0) return problem("target-unreadable", "target", `target device \`${key}\` was not read — the save is refused rather than stored unchecked`);
10474
+ if (target.kind === "absent") return problem("target-missing", "target", `target device \`${key}\` does not exist`);
10475
+ if (target.kind === "unreadable") return problem("target-unreadable", "target", `could not read target device \`${key}\` (${target.error}) — the save is refused rather than stored unchecked`);
10476
+ return {
10477
+ kind: "existing",
10478
+ found: target
10479
+ };
10480
+ }
10481
+ function featureTargetOf(target, cap) {
10482
+ if (target.kind === "new") return {
10483
+ mode: "new",
10484
+ deviceType: target.type
10485
+ };
10486
+ return {
10487
+ mode: isNativeCap(target.found, cap) ? "replace" : "add",
10488
+ deviceType: target.found.type
10489
+ };
10490
+ }
10491
+ /**
10492
+ * The static plan. `target` describes an EXISTING target device (one read);
10493
+ * it is ignored for a new one. On an existing target each feature REPLACES a
10494
+ * cap the device has natively, else ADDS it (D663).
10495
+ */
10496
+ function planComposition(composition, lookupCap, target) {
10497
+ const planTarget = planTargetOf(composition, target);
10498
+ if ("code" in planTarget) return refused(planTarget);
10499
+ const results = composition.features.map((feature, index) => {
10500
+ const result = feature.kind === "passthrough" ? refused(problem("reserved-variant", `features[${index}]`, `whole-capability passthrough of \`${feature.cap}\` arrives in slice 3`)) : planFeature(feature, index, featureTargetOf(planTarget, feature.cap), lookupCap);
10501
+ return require_composition.compositionFeatureEnabled(feature) ? result : {
10502
+ problems: result.problems,
10503
+ fields: [],
10504
+ features: [],
10505
+ events: []
10506
+ };
10507
+ });
10508
+ return {
10509
+ problems: results.flatMap((r) => r.problems),
10510
+ fields: results.flatMap((r) => r.fields),
10511
+ features: results.flatMap((r) => r.features),
10512
+ events: results.flatMap((r) => r.events)
10513
+ };
10514
+ }
10515
+ function compositionSourceRefs(composition) {
10516
+ const refs = composition.features.flatMap((f) => require_composition.compositionFeatureEnabled(f) && f.kind === "fields" ? require_composition.featureSources(f).flatMap(require_composition.fieldReads).map((r) => r.source) : []);
10517
+ return [...new Map(refs.map((r) => [require_composition.compositionSourceKey(r), r])).values()];
10518
+ }
10519
+ /**
10520
+ * The candidate's device: the existing target itself, else `self`, else a
10521
+ * placeholder that cannot collide with a stored target. An existing target is
10522
+ * known even on create, so a second customization of it is refused on create too.
10523
+ */
10524
+ function candidateSelf(composition, ctx, plan) {
10525
+ return {
10526
+ ref: composition.target.kind === "existing" ? composition.target.device : ctx.self ?? PENDING_SELF,
10527
+ native: composition.target.kind === "existing" && ctx.target?.kind === "found" ? ctx.target : null,
10528
+ replaced: replacedFieldKeys(plan)
10529
+ };
10530
+ }
10531
+ /**
10532
+ * `compositionFieldKey` of every field a REPLACE feature of `plan` owns — the
10533
+ * candidate's own, and a stored peer's `CompositionPeer.replaced` (D663): one
10534
+ * derivation, so the graph reads both the same way.
10535
+ */
10536
+ function replacedFieldKeys(plan) {
10537
+ const replacing = new Set(plan.features.filter((f) => f.mode === "replace").map((f) => f.featureIndex));
10538
+ return new Set(plan.fields.filter((f) => replacing.has(f.featureIndex)).map(compositionFieldKey));
10539
+ }
10540
+ /**
10541
+ * A read of the candidate's own device. Its own composed output (a new device's
10542
+ * field, an ADDED field) is the slice-1 own-field rule; on an existing target
10543
+ * every other field — replaced, or not composed at all — is the NATIVE value,
10544
+ * valid when the device serves that cap natively (D663, rule 5).
10545
+ */
10546
+ function selfReadProblems(read, at, fields, self) {
10547
+ const readKey = `${read.cap}.${read.fieldPath}`;
10548
+ if (fields.some((f) => compositionFieldKey(f) === readKey && !self.replaced.has(readKey))) return [];
10549
+ if (self.native === null) return [problem("source-field-unknown", at, `this device has no composed field \`${read.cap}.${read.fieldPath}\``)];
10550
+ if (isNativeCap(self.native, read.cap)) return [];
10551
+ return [problem("source-capability-missing", at, `the target device (device ${self.native.deviceId}) has no native \`${read.cap}\``)];
10552
+ }
10553
+ function sourceProblems(fields, ctx, self) {
10554
+ const selfKey = require_composition.compositionSourceKey(self.ref);
10555
+ return fields.flatMap((field) => field.reads.flatMap((read) => {
10556
+ const at = compositionFieldAt(field);
10557
+ const key = require_composition.compositionSourceKey(read.source);
10558
+ if (key === selfKey) return selfReadProblems(read, at, fields, self);
10559
+ const desc = ctx.sources.get(key);
10560
+ if (desc === void 0 || desc.kind === "unreadable") return [problem("source-unreadable", at, `could not read source \`${key}\` (${desc === void 0 ? "it was not read" : desc.error}) — the save is refused rather than stored unchecked`)];
10561
+ if (desc.kind === "absent") return [problem("source-missing", at, `source \`${key}\` does not exist`)];
10562
+ if (!desc.caps.has(read.cap)) return [problem("source-capability-missing", at, `source \`${key}\` (device ${desc.deviceId}) has no \`${read.cap}\``)];
10563
+ return [];
10564
+ }));
10565
+ }
10566
+ /**
10567
+ * A cycle's node keys are `compositionReadKey` strings:
10568
+ * `<addonId>/<stableId>#<cap>.<fieldPath>`. When a node belongs to the
10569
+ * CANDIDATE itself (this composition being saved), pull its `cap`/`fieldPath`
10570
+ * back out so the refusal can point at that exact field, matching the
10571
+ * documented `features[N].fields.<path>` convention. A cap name has no `.`,
10572
+ * so splitting `rest` on the FIRST `.` is exact; an item leaf's remainder
10573
+ * (`items[desiccant].status`) is matched through `compositionFieldKey`.
10574
+ */
10575
+ function candidateFieldOfNode(nodeKey, candidateKey) {
10576
+ const prefix = `${candidateKey}#`;
10577
+ if (!nodeKey.startsWith(prefix)) return null;
10578
+ const rest = nodeKey.slice(prefix.length);
10579
+ const dot = rest.indexOf(".");
10580
+ if (dot === -1) return null;
10581
+ return {
10582
+ cap: rest.slice(0, dot),
10583
+ fieldPath: rest.slice(dot + 1)
10584
+ };
10585
+ }
10586
+ /** The first node of a cycle's path that is one of THIS composition's own
10587
+ * planned fields, as a documented-convention path; `'features'` when the
10588
+ * cycle runs entirely through other stored compositions. */
10589
+ function cyclePath(nodePath, candidateKey, fields) {
10590
+ for (const nodeKey of nodePath) {
10591
+ const hit = candidateFieldOfNode(nodeKey, candidateKey);
10592
+ if (hit === null) continue;
10593
+ const hitKey = `${hit.cap}.${hit.fieldPath}`;
10594
+ const field = fields.find((f) => compositionFieldKey(f) === hitKey);
10595
+ if (field !== void 0) return compositionFieldAt(field);
10596
+ }
10597
+ return "features";
10598
+ }
10599
+ /** The first unread device any of `nodes` belongs to; null when none does. */
10600
+ function unreadDeviceOf(nodes, unread) {
10601
+ for (const [key, error] of unread) if (nodes.some((node) => node.startsWith(`${key}#`))) return {
10602
+ key,
10603
+ error
10604
+ };
10605
+ return null;
10606
+ }
10607
+ /**
10608
+ * Cycle check runs against the CANDIDATE (this composition, as block
10609
+ * `ctx.blockId`, writing `self.ref`) plus every OTHER stored composition,
10610
+ * decided per strongly connected component (`findCandidateCycles`): a cyclic
10611
+ * component holding a candidate node refuses, with one representative cycle
10612
+ * through it; one without is not this save's cycle. A
10613
+ * stored composition of the same block is its old version; another block on
10614
+ * the same device, or two stored peers sharing a device, make
10615
+ * `compositionEdges` throw `CompositionGraphError` — refused BY NAME as
10616
+ * `duplicate-target` (D391, D663) instead of escaping as an uncaught throw.
10617
+ */
10618
+ function cycleProblems(composition, ctx, fields, self) {
10619
+ const candidate = {
10620
+ blockId: ctx.blockId ?? "(unsaved)",
10621
+ target: self.ref,
10622
+ composition,
10623
+ replaced: self.replaced
10624
+ };
10625
+ const candidateKey = require_composition.compositionSourceKey(candidate.target);
10626
+ const unread = ctx.unreadTargets ?? /* @__PURE__ */ new Map();
10627
+ try {
10628
+ return findCandidateCycles(candidate, ctx.peers).map((c) => {
10629
+ const at = cyclePath(c.path, candidateKey, fields);
10630
+ const through = unreadDeviceOf([...c.component], unread);
10631
+ return through === null ? problem("cycle", at, `a field reads itself: ${c.path.join(" → ")}`) : problem("cycle", at, `possible cycle through \`${through.key}\` — its state could not be read (${through.error}): ${c.path.join(" → ")}`);
10632
+ });
10633
+ } catch (err) {
10634
+ if (err instanceof CompositionGraphError) return [problem("duplicate-target", "features", err.message)];
10635
+ throw err;
10636
+ }
10637
+ }
10638
+ function validateComposition(composition, ctx) {
10639
+ const plan = planComposition(composition, ctx.lookupCap, ctx.target ?? void 0);
10640
+ const self = candidateSelf(composition, ctx, plan);
10641
+ const cycles = cycleProblems(composition, ctx, plan.fields, self);
10642
+ const problems = [
10643
+ ...plan.problems,
10644
+ ...sourceProblems(plan.fields, ctx, self),
10645
+ ...cycles
10646
+ ];
10647
+ return {
10648
+ ok: problems.length === 0,
10649
+ problems,
10650
+ fields: [...plan.fields],
10651
+ features: [...plan.features],
10652
+ events: [...plan.events]
10653
+ };
10654
+ }
10655
+ //#endregion
10656
+ //#region src/composition/composable-caps.ts
10657
+ /**
10658
+ * What a composition may BUILD on a device type (G2, D676): the caps a new
10659
+ * device of that type, or an existing one that lacks them, can be given. The
10660
+ * blockers are the validator's own refusal codes, and a spec compares this
10661
+ * listing with `planComposition` for every capability — the editor can never
10662
+ * offer a feature the save would refuse for the same reason.
10663
+ */
10664
+ var ComposableFieldSchema = zod.z.object({
10665
+ path: zod.z.string(),
10666
+ kind: CompositionFieldKindSchema,
10667
+ nullable: zod.z.boolean(),
10668
+ required: zod.z.boolean(),
10669
+ enumValues: zod.z.array(zod.z.string()).optional()
10670
+ });
10671
+ var ComposableCapabilitySchema = zod.z.object({
10672
+ cap: zod.z.string(),
10673
+ fields: zod.z.array(ComposableFieldSchema),
10674
+ /** Present for an item-array cap (`consumables.items`). */
10675
+ itemArray: zod.z.object({
10676
+ path: zod.z.string(),
10677
+ keyField: zod.z.string()
10678
+ }).optional()
10679
+ });
10680
+ var ComposableCapabilitiesSchema = zod.z.object({ caps: zod.z.array(ComposableCapabilitySchema) });
10681
+ /** Why a cap cannot be BUILT (new device, or added to an existing one) on `deviceType`; [] = it can. */
10682
+ function builtCapabilityBlockers(def, deviceType) {
10683
+ if (BASE_DEVICE_CAPS.has(def.name)) return ["not-composable"];
10684
+ const state = def.runtimeState;
10685
+ if (def.scope !== "device" || state === void 0) return ["not-composable"];
10686
+ const blockers = [];
10687
+ if (def.deviceTypes !== void 0 && !def.deviceTypes.includes(deviceType)) blockers.push("wrong-device-type");
10688
+ if (Object.entries(def.methods).filter(([name, m]) => m.systemOnly !== true && def.composedMethods?.[name] === void 0).length > 0) blockers.push("has-commands");
10689
+ const fields = describeTopLevelStateFields(state);
10690
+ const itemArrayPath = def.status?.itemArray?.path ?? null;
10691
+ if (requiredTopLevelKeys(state).some((key) => key !== itemArrayPath && !fields.has(key))) blockers.push("not-composable");
10692
+ if (planCompositionEvents(def, {
10693
+ featureIndex: 0,
10694
+ cap: def.name,
10695
+ mode: "new"
10696
+ }, []).problems.some((p) => p.code === "not-composable") && !blockers.includes("not-composable")) blockers.push("not-composable");
10697
+ return blockers;
10698
+ }
10699
+ /** Every cap with no blocker, sorted by name. */
10700
+ function describeComposableCaps(defs, deviceType) {
10701
+ return defs.filter((def) => builtCapabilityBlockers(def, deviceType).length === 0).map((def) => {
10702
+ const state = def.runtimeState;
10703
+ const fields = state === void 0 ? [] : [...describeTopLevelStateFields(state).values()];
10704
+ const itemArray = def.status?.itemArray;
10705
+ return {
10706
+ cap: def.name,
10707
+ fields: fields.map((f) => ({
10708
+ path: f.path,
10709
+ kind: f.kind,
10710
+ nullable: f.nullable,
10711
+ required: f.required,
10712
+ ...f.enumValues === void 0 ? {} : { enumValues: [...f.enumValues] }
10713
+ })),
10714
+ ...itemArray === void 0 ? {} : { itemArray: {
10715
+ path: itemArray.path,
10716
+ keyField: itemArray.keyField
10717
+ } }
10718
+ };
10719
+ }).toSorted((a, b) => a.cap.localeCompare(b.cap));
10720
+ }
10721
+ //#endregion
9793
10722
  //#region src/capabilities/core-blocks.cap.ts
9794
10723
  /**
9795
10724
  * core-blocks — user-authored TypeScript, stored in the kernel and executed in
@@ -10087,6 +11016,14 @@ var coreBlocksCapability = {
10087
11016
  stableId: zod.z.string().min(1)
10088
11017
  }), CompositionCustomizationReadSchema, { auth: "admin" }),
10089
11018
  /**
11019
+ * The capabilities a composition may BUILD on a device of `deviceType`
11020
+ * (a new device, or added to an existing one), with their fields — the
11021
+ * editor's feature list and the presets' availability (G2, D676). Built
11022
+ * from the validator's own blockers; a replace of a BOUND cap is not
11023
+ * listed here (the device's bindings say what it has).
11024
+ */
11025
+ listComposableCaps: require_sleep.method(zod.z.object({ deviceType: zod.z.enum(require_err_msg.DeviceType) }), ComposableCapabilitiesSchema, { auth: "admin" }),
11026
+ /**
10090
11027
  * Validate without saving — the same verdict the save reaches. A mutation
10091
11028
  * for its body size; it writes nothing, so its access is `view`.
10092
11029
  */
@@ -26310,6 +27247,16 @@ var NodeInferenceDevicesSchema = zod.z.object({
26310
27247
  * Strictly the control plane: never sees a frame, never calls inference,
26311
27248
  * never drains queues. The runner does that work locally on each agent.
26312
27249
  */
27250
+ /**
27251
+ * The input of `setCameraSensors` (G5, D676): the ONE typed write path of a
27252
+ * camera's attached sensors (D672). `config: null` removes the attachment —
27253
+ * the camera reads `not-configured` again, never `unreadable`.
27254
+ */
27255
+ var SetCameraSensorsInputSchema = zod.z.object({
27256
+ deviceId: zod.z.number().int().nonnegative(),
27257
+ /** `null` removes the attachment: the camera goes back to `not-configured`. */
27258
+ config: CameraSensorsConfigSchema.nullable()
27259
+ });
26313
27260
  var pipelineOrchestratorCapability = {
26314
27261
  name: "pipeline-orchestrator",
26315
27262
  scope: "system",
@@ -26775,6 +27722,18 @@ var pipelineOrchestratorCapability = {
26775
27722
  */
26776
27723
  getCameraStatuses: require_sleep.method(zod.z.object({ deviceIds: zod.z.array(zod.z.number()).optional() }), zod.z.array(CameraStatusSchema).readonly()),
26777
27724
  /**
27725
+ * Attach sensors to a camera, or detach them with `config: null` (D672
27726
+ * configuration, G5/D676). Written to the orchestrator's per-device store
27727
+ * under the same key `applyDeviceSettingsPatch` writes, and announced as a
27728
+ * settings change so the camera-sensors bridge refreshes. Refused by name
27729
+ * — nothing written — for a device that cannot be read, does not exist,
27730
+ * is not a camera, or names itself as its own sensor.
27731
+ */
27732
+ setCameraSensors: require_sleep.method(SetCameraSensorsInputSchema, zod.z.object({ success: zod.z.literal(true) }), {
27733
+ kind: "mutation",
27734
+ auth: "admin"
27735
+ }),
27736
+ /**
26778
27737
  * Disk-wins fleet reconcile after a recordings wipe. Starts the walk in
26779
27738
  * the addon process and returns immediately with the job snapshot — the
26780
27739
  * work outlives the tRPC/UDS 60s timeout. Poll `getReconcileFromDiskStatus`.
@@ -44680,569 +45639,366 @@ function createDeviceExtensionProvider(options) {
44680
45639
  };
44681
45640
  }
44682
45641
  //#endregion
44683
- //#region src/composition/composition-graph.ts
44684
- /**
44685
- * The field graph across every composition, and the cycles in it (D659).
44686
- *
44687
- * A node is ONE field of ONE device (`<addon>/<stableId>#<cap>.<field>`); an
44688
- * edge points from a composed field to each field it reads. A cycle, direct or
44689
- * through another composition, is refused at save by name (spec §2).
44690
- *
44691
- * The graph is built for ONE save: the CANDIDATE composition (the one being
44692
- * validated) plus every STORED composition. The candidate replaces its own old
44693
- * version, identified BY BLOCK ID wherever it sits in `stored` — whether a save
44694
- * introduces or removes a cycle must never depend on array order. A DIFFERENT
44695
- * block targeting the candidate's device is refused by name: one composition
44696
- * per device (D663). Two different stored peers that (wrongly) target the same
44697
- * device are corrupted state, not a cycle to resolve by picking one silently;
44698
- * that is refused by name too (D391).
44699
- *
44700
- * A customization of an EXISTING device reads that device's NATIVE value for a
44701
- * field it replaces or does not write ("Invert state" reads the `on` it
44702
- * replaces): such a self-read is no edge, so it is never a cycle (D663).
44703
- * Another composition reading that field reads the customizer's output.
44704
- *
44705
- * `findCompositionCycles` reports at least one cycle per cycle-SET (the DFS
44706
- * marks a node `done` after its first expansion) — not every elementary cycle
44707
- * through a shared node, so the path it names may AVOID the candidate while
44708
- * one through it goes unreported. What a save refuses is therefore decided per
44709
- * strongly connected component (`findCandidateCycles`, C-1). A dotted
44710
- * `fieldPath` is matched only as an exact string: a write to `state.value` and
44711
- * a read of `state` would not connect (no nested field writes exist yet).
44712
- *
44713
- * An item leaf is its own node, `…#consumables.items[desiccant].status`
44714
- * (`featureFieldEntries`), so two items sharing an inner path never merge. No
44715
- * READ can name an array element (`describeStateField` never describes one),
44716
- * so an item node is write-only: its edges to sources are what the check needs.
44717
- */
44718
- /** Two blocks' compositions target the same device — refused by name, never silently resolved. */
44719
- var CompositionGraphError = class extends Error {};
44720
- /** `"cap.field"` of every field a peer writes — the same spelling as `compositionFieldKey`. */
44721
- function writtenFields(peer) {
44722
- return new Set(peer.composition.features.flatMap((feature) => !require_composition.compositionFeatureEnabled(feature) || feature.kind !== "fields" ? [] : require_composition.featureFieldEntries(feature).map(({ fieldPath }) => `${feature.cap}.${fieldPath}`)));
44723
- }
44724
- /** A read of the peer's OWN device is an edge only when it reads the peer's own output (rule 5, D663). */
44725
- function readsComposedValue(peer, written, read) {
44726
- if (require_composition.compositionSourceKey(read.source) !== require_composition.compositionSourceKey(peer.target)) return true;
44727
- const field = `${read.cap}.${read.fieldPath}`;
44728
- return written.has(field) && peer.replaced?.has(field) !== true;
44729
- }
44730
- function peerEdges(peer) {
44731
- const written = writtenFields(peer);
44732
- return peer.composition.features.flatMap((feature) => !require_composition.compositionFeatureEnabled(feature) || feature.kind !== "fields" ? [] : require_composition.featureFieldEntries(feature).map(({ fieldPath, source }) => [require_composition.compositionReadKey({
44733
- source: peer.target,
44734
- cap: feature.cap,
44735
- fieldPath
44736
- }), require_composition.fieldReads(source).filter((read) => readsComposedValue(peer, written, read)).map(require_composition.compositionReadKey)]));
44737
- }
44738
- /**
44739
- * Every peer that actually takes part in the graph: each stored peer minus the
44740
- * candidate's own old version (same block id — the drop happens before any
44741
- * edge is built, so its old edges never enter the map), plus the candidate
44742
- * itself, exactly once. Throws {@link CompositionGraphError} when a DIFFERENT
44743
- * block targets the candidate's device, or two stored peers share a device.
44744
- */
44745
- function resolvedPeers(candidate, stored) {
44746
- const candidateKey = require_composition.compositionSourceKey(candidate.target);
44747
- const survivors = /* @__PURE__ */ new Map();
44748
- for (const peer of stored) {
44749
- if (peer.blockId === candidate.blockId) continue;
44750
- const key = require_composition.compositionSourceKey(peer.target);
44751
- if (key === candidateKey) throw new CompositionGraphError(`block \`${peer.blockId}\` and block \`${candidate.blockId}\` both target device \`${key}\` — one composition per device; delete or edit the existing one`);
44752
- const clash = survivors.get(key);
44753
- if (clash !== void 0) throw new CompositionGraphError(`two stored compositions (\`${clash.blockId}\`, \`${peer.blockId}\`) both target device \`${key}\` — refusing to build the field graph`);
44754
- survivors.set(key, peer);
44755
- }
44756
- return [...survivors.values(), candidate];
44757
- }
44758
- function compositionEdges(candidate, stored) {
44759
- const edges = resolvedPeers(candidate, stored).flatMap(peerEdges);
44760
- return new Map(edges);
44761
- }
44762
- function findCompositionCycles(candidate, stored) {
44763
- const edges = compositionEdges(candidate, stored);
44764
- const marks = /* @__PURE__ */ new Map();
44765
- const found = /* @__PURE__ */ new Map();
44766
- const visit = (node, stack) => {
44767
- const mark = marks.get(node);
44768
- if (mark === "done") return;
44769
- if (mark === "visiting") {
44770
- const path = [...stack.slice(stack.indexOf(node)), node];
44771
- const id = [...new Set(path)].toSorted().join("|");
44772
- if (!found.has(id)) found.set(id, { path });
44773
- return;
44774
- }
44775
- marks.set(node, "visiting");
44776
- for (const next of edges.get(node) ?? []) visit(next, [...stack, node]);
44777
- marks.set(node, "done");
44778
- };
44779
- for (const node of edges.keys()) visit(node, []);
44780
- return [...found.values()];
44781
- }
44782
- /** Tarjan's strongly connected components over every node of the graph (sources included). */
44783
- function stronglyConnected(edges) {
44784
- const index = /* @__PURE__ */ new Map();
44785
- const low = /* @__PURE__ */ new Map();
44786
- const onStack = /* @__PURE__ */ new Set();
44787
- const stack = [];
44788
- const components = [];
44789
- const connect = (node) => {
44790
- index.set(node, index.size);
44791
- low.set(node, index.get(node) ?? 0);
44792
- stack.push(node);
44793
- onStack.add(node);
44794
- for (const next of edges.get(node) ?? []) if (!index.has(next)) {
44795
- connect(next);
44796
- low.set(node, Math.min(low.get(node) ?? 0, low.get(next) ?? 0));
44797
- } else if (onStack.has(next)) low.set(node, Math.min(low.get(node) ?? 0, index.get(next) ?? 0));
44798
- if (low.get(node) !== index.get(node)) return;
44799
- const component = [];
44800
- for (let member = stack.pop(); member !== void 0; member = stack.pop()) {
44801
- onStack.delete(member);
44802
- component.push(member);
44803
- if (member === node) break;
44804
- }
44805
- components.push(component);
44806
- };
44807
- for (const node of edges.keys()) if (!index.has(node)) connect(node);
44808
- return components;
44809
- }
44810
- /** The shortest walk from `start` back to itself inside `component` (one exists: the component has a cycle). */
44811
- function cycleThrough(start, component, edges) {
44812
- const parent = /* @__PURE__ */ new Map();
44813
- const queue = [start];
44814
- for (let head = 0; head < queue.length; head += 1) {
44815
- const node = queue[head];
44816
- if (node === void 0) break;
44817
- for (const next of edges.get(node) ?? []) {
44818
- if (next === start) {
44819
- const chain = [];
44820
- for (let at = node; at !== void 0 && at !== start; at = parent.get(at)) chain.push(at);
44821
- return [
44822
- start,
44823
- ...chain.reverse(),
44824
- start
44825
- ];
44826
- }
44827
- if (!component.has(next) || parent.has(next)) continue;
44828
- parent.set(next, node);
44829
- queue.push(next);
44830
- }
44831
- }
44832
- return [start, start];
44833
- }
45642
+ //#region src/units/unit-table.ts
44834
45643
  /**
44835
- * The cycles THIS save closes, decided per strongly connected component — never
44836
- * per reported DFS path, which names one back-edge per revisit and can report a
44837
- * component's cycle by a path that avoids the candidate while the one through it
44838
- * goes unreported. A component refuses when it holds a candidate node and a
44839
- * cycle (more than one node, or a self-loop). Components without a candidate
44840
- * node are not this save's cycles.
45644
+ * Frozen unit → spec table. `•` in the doc marks each dimension's canonical
45645
+ * unit (`factor: 1, offset: 0`). °F derives from `°C = (°F − 32) × 5/9` ⇒
45646
+ * `factor = 5/9`, `offset = -160/9` (kept as exact expressions, not rounded
45647
+ * decimals). K derives from `°C = K − 273.15`.
44841
45648
  */
44842
- function findCandidateCycles(candidate, stored) {
44843
- const edges = compositionEdges(candidate, stored);
44844
- const prefix = `${require_composition.compositionSourceKey(candidate.target)}#`;
44845
- return stronglyConnected(edges).flatMap((members) => {
44846
- const start = members.find((n) => n.startsWith(prefix));
44847
- if (start === void 0) return [];
44848
- const component = new Set(members);
44849
- const selfLoop = members.length === 1 && (edges.get(start) ?? []).includes(start);
44850
- if (members.length === 1 && !selfLoop) return [];
44851
- return [{
44852
- path: cycleThrough(start, component, edges),
44853
- component
44854
- }];
44855
- });
44856
- }
44857
- //#endregion
44858
- //#region src/composition/plan-result.ts
44859
- function problem(code, path, message) {
44860
- return {
44861
- code,
44862
- path,
44863
- message
44864
- };
44865
- }
44866
- function refused(...problems) {
44867
- return {
44868
- problems,
44869
- fields: [],
44870
- features: [],
44871
- events: []
44872
- };
44873
- }
44874
- /** Where a planned field sits in the composition: `features[N].fields.<path>` or `features[N].items.<key>.fields.<path>`. */
44875
- function compositionFieldAt(field) {
44876
- const inner = field.item === void 0 ? "fields" : `items.${field.item.key}.fields`;
44877
- return `features[${field.featureIndex}].${inner}.${field.path}`;
44878
- }
44879
- //#endregion
44880
- //#region src/composition/expression-kinds.ts
44881
- var NUMBER = {
44882
- kind: "fixed",
44883
- result: ["number"]
44884
- };
44885
- var BOOLEAN = {
44886
- kind: "fixed",
44887
- result: ["boolean"]
44888
- };
44889
- /** One rule per builtin. `expression-kinds.spec.ts` fails for a builtin missing here. */
44890
- var BUILTIN_RESULT_KINDS = Object.freeze({
44891
- min: NUMBER,
44892
- max: NUMBER,
44893
- abs: NUMBER,
44894
- floor: NUMBER,
44895
- ceil: NUMBER,
44896
- sqrt: NUMBER,
44897
- round: NUMBER,
44898
- pow: NUMBER,
44899
- clamp: NUMBER,
44900
- avg: NUMBER,
44901
- sum: NUMBER,
44902
- age: NUMBER,
44903
- convert: NUMBER,
44904
- coalesce: { kind: "coalesce" },
44905
- any: BOOLEAN,
44906
- all: BOOLEAN,
44907
- within: BOOLEAN,
44908
- latest: {
44909
- kind: "fixed",
44910
- result: ["number", "null"]
45649
+ var UNIT_TABLE = {
45650
+ "°C": {
45651
+ dimension: "temperature",
45652
+ factor: 1,
45653
+ offset: 0
45654
+ },
45655
+ "°F": {
45656
+ dimension: "temperature",
45657
+ factor: 5 / 9,
45658
+ offset: -160 / 9
45659
+ },
45660
+ K: {
45661
+ dimension: "temperature",
45662
+ factor: 1,
45663
+ offset: -273.15
45664
+ },
45665
+ hPa: {
45666
+ dimension: "pressure",
45667
+ factor: 1,
45668
+ offset: 0
45669
+ },
45670
+ kPa: {
45671
+ dimension: "pressure",
45672
+ factor: 10,
45673
+ offset: 0
45674
+ },
45675
+ Pa: {
45676
+ dimension: "pressure",
45677
+ factor: .01,
45678
+ offset: 0
45679
+ },
45680
+ mbar: {
45681
+ dimension: "pressure",
45682
+ factor: 1,
45683
+ offset: 0
45684
+ },
45685
+ bar: {
45686
+ dimension: "pressure",
45687
+ factor: 1e3,
45688
+ offset: 0
45689
+ },
45690
+ inHg: {
45691
+ dimension: "pressure",
45692
+ factor: 33.8639,
45693
+ offset: 0
45694
+ },
45695
+ mmHg: {
45696
+ dimension: "pressure",
45697
+ factor: 1.33322,
45698
+ offset: 0
45699
+ },
45700
+ psi: {
45701
+ dimension: "pressure",
45702
+ factor: 68.9476,
45703
+ offset: 0
45704
+ },
45705
+ "m/s": {
45706
+ dimension: "speed",
45707
+ factor: 1,
45708
+ offset: 0
45709
+ },
45710
+ "km/h": {
45711
+ dimension: "speed",
45712
+ factor: 1 / 3.6,
45713
+ offset: 0
45714
+ },
45715
+ mph: {
45716
+ dimension: "speed",
45717
+ factor: .44704,
45718
+ offset: 0
45719
+ },
45720
+ kn: {
45721
+ dimension: "speed",
45722
+ factor: .514444,
45723
+ offset: 0
45724
+ },
45725
+ "mm/h": {
45726
+ dimension: "precipitation-rate",
45727
+ factor: 1,
45728
+ offset: 0
45729
+ },
45730
+ "in/h": {
45731
+ dimension: "precipitation-rate",
45732
+ factor: 25.4,
45733
+ offset: 0
45734
+ },
45735
+ m: {
45736
+ dimension: "length",
45737
+ factor: 1,
45738
+ offset: 0
45739
+ },
45740
+ mm: {
45741
+ dimension: "length",
45742
+ factor: .001,
45743
+ offset: 0
45744
+ },
45745
+ cm: {
45746
+ dimension: "length",
45747
+ factor: .01,
45748
+ offset: 0
45749
+ },
45750
+ km: {
45751
+ dimension: "length",
45752
+ factor: 1e3,
45753
+ offset: 0
44911
45754
  },
44912
- number: {
44913
- kind: "fixed",
44914
- result: ["number", "null"]
45755
+ in: {
45756
+ dimension: "length",
45757
+ factor: .0254,
45758
+ offset: 0
44915
45759
  },
44916
- rose: {
44917
- kind: "fixed",
44918
- result: ["number", "null"]
45760
+ ft: {
45761
+ dimension: "length",
45762
+ factor: .3048,
45763
+ offset: 0
44919
45764
  },
44920
- count: NUMBER
44921
- });
44922
- var KindInferenceError = class extends Error {};
44923
- function kindOfValue(value) {
44924
- if (value === null) return "null";
44925
- if (typeof value === "number") return "number";
44926
- if (typeof value === "string") return "string";
44927
- return "boolean";
44928
- }
44929
- function only(kind) {
44930
- return new Set([kind]);
44931
- }
44932
- function union(...sets) {
44933
- return new Set(sets.flatMap((s) => [...s]));
44934
- }
44935
- function withoutNull(set) {
44936
- return new Set([...set].filter((k) => k !== "null"));
44937
- }
44938
- function binaryKinds(op, left, right) {
44939
- if (op === "+") {
44940
- const all = [...left, ...right];
44941
- if (all.every((k) => k === "string")) return only("string");
44942
- if (all.every((k) => k === "number")) return only("number");
44943
- return new Set(["number", "string"]);
45765
+ mi: {
45766
+ dimension: "length",
45767
+ factor: 1609.344,
45768
+ offset: 0
45769
+ },
45770
+ lx: {
45771
+ dimension: "illuminance",
45772
+ factor: 1,
45773
+ offset: 0
45774
+ },
45775
+ "W/m²": {
45776
+ dimension: "irradiance",
45777
+ factor: 1,
45778
+ offset: 0
45779
+ },
45780
+ W: {
45781
+ dimension: "power",
45782
+ factor: 1,
45783
+ offset: 0
45784
+ },
45785
+ kW: {
45786
+ dimension: "power",
45787
+ factor: 1e3,
45788
+ offset: 0
45789
+ },
45790
+ VA: {
45791
+ dimension: "apparent-power",
45792
+ factor: 1,
45793
+ offset: 0
45794
+ },
45795
+ Wh: {
45796
+ dimension: "energy",
45797
+ factor: 1,
45798
+ offset: 0
45799
+ },
45800
+ kWh: {
45801
+ dimension: "energy",
45802
+ factor: 1e3,
45803
+ offset: 0
45804
+ },
45805
+ MWh: {
45806
+ dimension: "energy",
45807
+ factor: 1e6,
45808
+ offset: 0
45809
+ },
45810
+ V: {
45811
+ dimension: "voltage",
45812
+ factor: 1,
45813
+ offset: 0
45814
+ },
45815
+ mV: {
45816
+ dimension: "voltage",
45817
+ factor: .001,
45818
+ offset: 0
45819
+ },
45820
+ A: {
45821
+ dimension: "current",
45822
+ factor: 1,
45823
+ offset: 0
45824
+ },
45825
+ mA: {
45826
+ dimension: "current",
45827
+ factor: .001,
45828
+ offset: 0
45829
+ },
45830
+ ppm: {
45831
+ dimension: "concentration-volume",
45832
+ factor: 1,
45833
+ offset: 0
45834
+ },
45835
+ ppb: {
45836
+ dimension: "concentration-volume",
45837
+ factor: .001,
45838
+ offset: 0
45839
+ },
45840
+ "µg/m³": {
45841
+ dimension: "concentration-mass",
45842
+ factor: 1,
45843
+ offset: 0
45844
+ },
45845
+ "mg/m³": {
45846
+ dimension: "concentration-mass",
45847
+ factor: 1e3,
45848
+ offset: 0
45849
+ },
45850
+ kg: {
45851
+ dimension: "mass",
45852
+ factor: 1,
45853
+ offset: 0
45854
+ },
45855
+ g: {
45856
+ dimension: "mass",
45857
+ factor: .001,
45858
+ offset: 0
45859
+ },
45860
+ lb: {
45861
+ dimension: "mass",
45862
+ factor: .453592,
45863
+ offset: 0
45864
+ },
45865
+ oz: {
45866
+ dimension: "mass",
45867
+ factor: .0283495,
45868
+ offset: 0
45869
+ },
45870
+ "%": {
45871
+ dimension: "percentage",
45872
+ factor: 1,
45873
+ offset: 0
44944
45874
  }
44945
- if (op === "-" || op === "*" || op === "/" || op === "%") return only("number");
44946
- return only("boolean");
44947
- }
44948
- /** "exactly N" / "at least N" / "N–M", for an arity refusal that says what IS allowed. */
44949
- function arityRange(builtin) {
44950
- if (builtin.minArgs === builtin.maxArgs) return `exactly ${builtin.minArgs}`;
44951
- if (builtin.maxArgs === Number.POSITIVE_INFINITY) return `at least ${builtin.minArgs}`;
44952
- return `${builtin.minArgs}–${builtin.maxArgs}`;
44953
- }
44954
- function callKinds(callee, args) {
44955
- const builtin = require_composition.EXPRESSION_BUILTINS[callee];
44956
- if (builtin !== void 0 && (args.length < builtin.minArgs || args.length > builtin.maxArgs)) throw new KindInferenceError(`${callee}: wrong number of arguments (${args.length}); expected ${arityRange(builtin)}`);
44957
- const rule = BUILTIN_RESULT_KINDS[callee];
44958
- if (rule === void 0) throw new KindInferenceError(`no result-kind rule for builtin '${callee}'`);
44959
- if (rule.kind === "fixed") return new Set(rule.result);
44960
- const nonNull = union(...args.map(withoutNull));
44961
- return args.every((a) => a.has("null")) ? union(nonNull, only("null")) : nonNull;
44962
- }
44963
- function kindsOf(node, bindings) {
44964
- switch (node.kind) {
44965
- case "literal": return only(kindOfValue(node.value));
44966
- case "identifier": {
44967
- if (node.name === "now") return only("number");
44968
- const bound = bindings.get(node.name);
44969
- if (bound === void 0) throw new KindInferenceError(`unbound identifier '${node.name}'`);
44970
- return bound;
44971
- }
44972
- case "unary": return only(node.op === "!" ? "boolean" : "number");
44973
- case "binary": return binaryKinds(node.op, kindsOf(node.left, bindings), kindsOf(node.right, bindings));
44974
- case "logical": return union(kindsOf(node.left, bindings), kindsOf(node.right, bindings));
44975
- case "conditional": return union(kindsOf(node.consequent, bindings), kindsOf(node.alternate, bindings));
44976
- case "call": return callKinds(node.callee, node.args.map((a) => kindsOf(a, bindings)));
45875
+ };
45876
+ //#endregion
45877
+ //#region src/units/convert.ts
45878
+ /**
45879
+ * Pure unit-conversion API over `UNIT_TABLE`. No dependencies, no side effects.
45880
+ *
45881
+ * Conversion is refused (throws `UnitConversionError`, or returns `undefined`
45882
+ * from the `try*` variant) whenever a unit is unknown or the two units belong
45883
+ * to different dimensions — cross-dimension conversion is deliberately
45884
+ * impossible so a render override can never make the value and its unit label
45885
+ * disagree.
45886
+ *
45887
+ * Callers pass units through `normalizeUnit` (`../device/source-info.ts`) BEFORE
45888
+ * calling here — the table keys only canonical spellings.
45889
+ */
45890
+ /** Thrown by `convertUnit` when a conversion is refused. Carries the offending
45891
+ * units + a machine-readable `reason` for callers that branch on the cause. */
45892
+ var UnitConversionError = class extends Error {
45893
+ from;
45894
+ to;
45895
+ reason;
45896
+ constructor(from, to, reason) {
45897
+ super(`[units] cannot convert '${from}' → '${to}': ${reason}`);
45898
+ this.name = "UnitConversionError";
45899
+ this.from = from;
45900
+ this.to = to;
45901
+ this.reason = reason;
44977
45902
  }
45903
+ };
45904
+ /** Resolve a unit's `UnitSpec`, or `undefined` when the spelling is unknown. */
45905
+ function specFor(unit) {
45906
+ return Object.hasOwn(UNIT_TABLE, unit) ? UNIT_TABLE[unit] : void 0;
44978
45907
  }
44979
- function nodeContainsCall(node, callee) {
44980
- switch (node.kind) {
44981
- case "literal":
44982
- case "identifier": return false;
44983
- case "unary": return nodeContainsCall(node.operand, callee);
44984
- case "binary":
44985
- case "logical": return nodeContainsCall(node.left, callee) || nodeContainsCall(node.right, callee);
44986
- case "conditional": return nodeContainsCall(node.test, callee) || nodeContainsCall(node.consequent, callee) || nodeContainsCall(node.alternate, callee);
44987
- case "call": return node.callee === callee || node.args.some((arg) => nodeContainsCall(arg, callee));
44988
- }
45908
+ /** The dimension a unit belongs to, or `undefined` for an unknown unit. */
45909
+ function unitDimension(unit) {
45910
+ return specFor(unit)?.dimension;
44989
45911
  }
44990
- function expressionContainsBuiltinCall(expr, callee) {
44991
- const compiled = require_composition.compileExpressionSafe(expr);
44992
- return compiled.ok && nodeContainsCall(compiled.parsed.ast, callee);
45912
+ /** Value in `spec`'s unit → its dimension's canonical unit. */
45913
+ function toCanonical(value, spec) {
45914
+ return value * spec.factor + spec.offset;
44993
45915
  }
44994
- function inferExpressionKinds(input) {
44995
- const compiled = require_composition.compileExpressionSafe(input.expr);
44996
- if (!compiled.ok) return {
44997
- ok: false,
44998
- error: compiled.error
44999
- };
45000
- try {
45001
- return {
45002
- ok: true,
45003
- kinds: kindsOf(compiled.parsed.ast, input.bindingKinds)
45004
- };
45005
- } catch (err) {
45006
- if (err instanceof KindInferenceError) return {
45007
- ok: false,
45008
- error: err.message
45009
- };
45010
- throw err;
45011
- }
45916
+ /** Canonical-unit value → the unit described by `spec`. */
45917
+ function fromCanonical(canonical, spec) {
45918
+ return (canonical - spec.offset) / spec.factor;
45012
45919
  }
45013
- //#endregion
45014
- //#region src/composition/field-kinds.ts
45015
45920
  /**
45016
- * The kind half of planning a composition field (D659): which kinds a source
45017
- * can produce, whether they fit a target field, and the field's role.
45018
- * Shared by the top-level planner (`validate-composition.ts`) and the item
45019
- * planner (`composition-items.ts`). Internal to the composition module — NOT
45020
- * in the barrel: these are planner internals, not a published contract.
45921
+ * Convert `value` from unit `from` to unit `to`. Identity when `from === to`.
45922
+ * Throws `UnitConversionError` when either unit is unknown or the units belong
45923
+ * to different dimensions.
45021
45924
  */
45022
- function readKinds(read, lookupCap) {
45023
- const def = lookupCap(read.cap);
45024
- const schema = def?.runtimeState ?? def?.status?.schema;
45025
- if (def === null || schema === void 0) return {
45026
- ok: false,
45027
- code: "source-field-unknown",
45028
- message: `no capability \`${read.cap}\` with state to read`
45029
- };
45030
- const field = describeStateField(schema, read.fieldPath);
45031
- if (field === null) return {
45032
- ok: false,
45033
- code: "source-field-unknown",
45034
- message: `\`${read.cap}\` has no field \`${read.fieldPath}\``
45035
- };
45036
- const base = field.kind === "enum" ? "string" : field.kind;
45037
- return {
45038
- ok: true,
45039
- kinds: new Set(field.nullable ? [base, "null"] : [base])
45040
- };
45041
- }
45042
- function sourceKinds(source, lookupCap) {
45043
- if (source.kind === "from") return readKinds(source, lookupCap);
45044
- if (source.kind === "code") return {
45045
- ok: false,
45046
- code: "reserved-variant",
45047
- message: "code fields arrive in slice 4"
45048
- };
45049
- const bindingKinds = /* @__PURE__ */ new Map();
45050
- for (const [name, binding] of Object.entries(source.bindings)) {
45051
- if (binding.kind === "literal") {
45052
- bindingKinds.set(name, new Set([kindOfValue(binding.value)]));
45053
- continue;
45054
- }
45055
- const kinds = readKinds(binding, lookupCap);
45056
- if (!kinds.ok) return {
45057
- ...kinds,
45058
- message: `binding \`${name}\`: ${kinds.message}`
45059
- };
45060
- bindingKinds.set(name, kinds.kinds);
45061
- }
45062
- const inferred = inferExpressionKinds({
45063
- expr: source.expr,
45064
- bindingKinds
45065
- });
45066
- return inferred.ok ? {
45067
- ok: true,
45068
- kinds: inferred.kinds
45069
- } : {
45070
- ok: false,
45071
- code: "expression-invalid",
45072
- message: inferred.error
45073
- };
45074
- }
45075
- function compatibility(cap, target, kinds, at) {
45076
- const allowed = target.kind === "enum" ? "string" : target.kind;
45077
- const offending = [...kinds].filter((k) => k !== "null" && k !== allowed);
45078
- const problems = [];
45079
- if (offending.length > 0) problems.push(problem("kind-mismatch", at, `\`${cap}.${target.path}\` is a ${target.kind}; this source can produce ${offending.join(" or ")}`));
45080
- if (kinds.has("null") && !target.nullable) problems.push(problem("may-be-null", at, `\`${cap}.${target.path}\` cannot be null and this source can produce null — wrap it in coalesce(…) or pick a non-null source`));
45081
- return problems;
45925
+ function convertUnit(value, from, to) {
45926
+ if (from === to) return value;
45927
+ const fromSpec = specFor(from);
45928
+ if (!fromSpec) throw new UnitConversionError(from, to, "unknown-from");
45929
+ const toSpec = specFor(to);
45930
+ if (!toSpec) throw new UnitConversionError(from, to, "unknown-to");
45931
+ if (fromSpec.dimension !== toSpec.dimension) throw new UnitConversionError(from, to, "cross-dimension");
45932
+ return fromCanonical(toCanonical(value, fromSpec), toSpec);
45082
45933
  }
45083
45934
  /**
45084
- * A string a source produces WITHOUT reading any device — a field-level
45085
- * `expression` source whose compiled AST is a bare string literal (`"red"`,
45086
- * never `a` or `a + "x"`). Anything else that can only produce `'string'` at
45087
- * the kind level (a `from` read of an enum-typed source field, a computed
45088
- * expression) is NOT checked against the target's `enumValues` here: the
45089
- * kind inference already collapsed it to the coarse `'string'` kind, losing
45090
- * whichever enum it actually came from, so membership can only be judged at
45091
- * write time against the runtime-state schema. Known limitation — see the
45092
- * fix report for Task 6 round 1.
45935
+ * Graceful variant for the render path: returns the converted value, or
45936
+ * `undefined` when the conversion is refused (unknown unit / cross-dimension).
45937
+ * Never throws — a render caller falls back to the raw value + source unit.
45093
45938
  */
45094
- function literalStringValue(source) {
45095
- if (source.kind !== "expression") return null;
45096
- const compiled = require_composition.compileExpressionSafe(source.expr);
45097
- if (!compiled.ok) return null;
45098
- const ast = compiled.parsed.ast;
45099
- return ast.kind === "literal" && typeof ast.value === "string" ? ast.value : null;
45939
+ function tryConvertUnit(value, from, to) {
45940
+ if (from === to) return value;
45941
+ const fromSpec = specFor(from);
45942
+ if (!fromSpec) return void 0;
45943
+ const toSpec = specFor(to);
45944
+ if (!toSpec) return void 0;
45945
+ if (fromSpec.dimension !== toSpec.dimension) return void 0;
45946
+ return fromCanonical(toCanonical(value, fromSpec), toSpec);
45100
45947
  }
45101
45948
  /**
45102
- * An enum target whose source is a save-time-KNOWN string literal outside its
45103
- * `enumValues` is refused now rather than left to fail the write later. A
45104
- * dynamic source (a `from` read, a non-literal expression) is left to
45105
- * runtime — see {@link literalStringValue}.
45949
+ * Whether `value` can be converted between `from` and `to` (same dimension,
45950
+ * both known). Cheap boolean probe for the UI's same-dimension unit picker and
45951
+ * the resolver's convertibility branch — compute ONCE so a unit label and its
45952
+ * value math can never disagree.
45106
45953
  */
45107
- function enumLiteralProblem(cap, target, source, at) {
45108
- if (target.kind !== "enum" || target.enumValues === void 0) return null;
45109
- const value = literalStringValue(source);
45110
- if (value === null || target.enumValues.includes(value)) return null;
45111
- const allowed = target.enumValues.map((v) => `\`${v}\``).join(", ");
45112
- return problem("kind-mismatch", at, `\`${cap}.${target.path}\` accepts only ${allowed}; this source is the literal \`${value}\``);
45113
- }
45114
- function roleOf(source) {
45115
- if (source.kind !== "expression") return "derived";
45116
- if (expressionContainsBuiltinCall(source.expr, "count")) return "accumulator";
45117
- if (require_composition.fieldReads(source).length > 0) return "derived";
45118
- const compiled = require_composition.compileExpressionSafe(source.expr);
45119
- return compiled.ok && compiled.parsed.identifiers.has("now") ? "clock" : "constant";
45954
+ function canConvertUnit(from, to) {
45955
+ if (from === to) return true;
45956
+ const fromDim = unitDimension(from);
45957
+ if (fromDim === void 0) return false;
45958
+ return fromDim === unitDimension(to);
45120
45959
  }
45121
45960
  /**
45122
- * How a planned field says "unavailable", per feature mode and AFTER `roleOf`
45123
- * (D393, D663 rulings S1 + S1b). The composer cannot take a device it does not
45124
- * own offline, and D393 forbids a stale number, so on an existing target a
45125
- * field that READS a source never gets `offline`.
45961
+ * Every known unit spelling in a dimension (table insertion order — canonical
45962
+ * unit first). Powers the UI's same-dimension unit picker.
45126
45963
  */
45127
- function unavailableFor(tf, role, mode, cap, at) {
45128
- if (mode === "replace" && (role === "derived" || role === "accumulator")) return {
45129
- ok: true,
45130
- unavailable: "release"
45131
- };
45132
- if (mode === "new" || role !== "derived") return {
45133
- ok: true,
45134
- unavailable: tf.nullable ? "null" : "offline"
45135
- };
45136
- if (tf.nullable) return {
45137
- ok: true,
45138
- unavailable: "null"
45139
- };
45140
- if (tf.enumValues?.includes("unknown") === true) return {
45141
- ok: true,
45142
- unavailable: "unknown"
45143
- };
45144
- return {
45145
- ok: false,
45146
- problem: problem("not-replaceable", at, `\`${cap}.${tf.path}\` reads a source but can say neither null nor 'unknown', and an ADDED capability has no native reading to fall back to (D393, D663)`)
45147
- };
45148
- }
45149
- //#endregion
45150
- //#region src/composition/composition-items.ts
45151
- /** Item fields the composer writes itself, with the value it writes. */
45152
- var COMPOSED_ITEM_FIXED_FIELDS = { resettable: false };
45153
- function reservedItemFields(itemArray) {
45154
- return new Set([
45155
- itemArray.keyField,
45156
- ...itemArray.labelField === void 0 ? [] : [itemArray.labelField],
45157
- ...Object.keys(COMPOSED_ITEM_FIXED_FIELDS)
45158
- ]);
45159
- }
45160
- /** A required leaf under an optional parent is required only once something writes that parent. */
45161
- function leafRequired(itemArray, path, written) {
45162
- const described = describeStateField(itemArray.itemSchema, path);
45163
- if (described === null || !described.required) return false;
45164
- return optionalAncestors(itemArray.itemSchema, path).every((parent) => written.some((w) => w.startsWith(`${parent}.`)));
45165
- }
45166
- function missingLeaves({ capName, itemArray, reserved }, item, at) {
45167
- const written = Object.keys(item.fields);
45168
- return enumerateSchemaFields(itemArray.itemSchema).flatMap((leaf) => {
45169
- if (reserved.has(leaf.path) || leaf.path in item.fields) return [];
45170
- if (!leafRequired(itemArray, leaf.path, written)) return [];
45171
- const described = describeStateField(itemArray.itemSchema, leaf.path);
45172
- if (described === null || described.nullable) return [];
45173
- return [problem("missing-field", `${at}.fields.${leaf.path}`, `\`${capName}.${itemArray.path}[].${leaf.path}\` is required and has no source`)];
45174
- });
45175
- }
45176
- function planItemField(ctx, leaf) {
45177
- const { capName, itemArray, featureIndex, lookupCap } = ctx;
45178
- const { key, label, path, source } = leaf;
45179
- const at = `features[${featureIndex}].items.${key}.fields.${path}`;
45180
- if (ctx.reserved.has(path)) return refused(problem("item-field-reserved", at, `\`${capName}.${itemArray.path}[].${path}\` is set by the composer itself — it takes no source`));
45181
- const tf = describeStateField(itemArray.itemSchema, path);
45182
- if (tf === null) return refused(problem("unknown-field", at, `a \`${capName}\` item has no field \`${path}\``));
45183
- const kinds = sourceKinds(source, lookupCap);
45184
- if (!kinds.ok) return refused(problem(kinds.code, at, kinds.message));
45185
- const role = roleOf(source);
45186
- const unavailable = unavailableFor(tf, role, ctx.mode, capName, at);
45187
- if (!unavailable.ok) return refused(unavailable.problem);
45188
- const plan = {
45189
- cap: capName,
45190
- path,
45191
- item: {
45192
- arrayPath: itemArray.path,
45193
- key,
45194
- label
45195
- },
45196
- featureIndex,
45197
- kind: tf.kind,
45198
- nullable: tf.nullable,
45199
- required: tf.required,
45200
- unavailable: unavailable.unavailable,
45201
- role,
45202
- source,
45203
- reads: [...require_composition.fieldReads(source)]
45204
- };
45205
- const enumProblem = enumLiteralProblem(capName, tf, source, at);
45206
- return {
45207
- problems: [...compatibility(capName, tf, kinds.kinds, at), ...enumProblem === null ? [] : [enumProblem]],
45208
- fields: [plan],
45209
- features: [],
45210
- events: []
45211
- };
45212
- }
45213
- function planItems(def, feature, featureIndex, lookupCap, mode = "new") {
45214
- const at = `features[${featureIndex}].items`;
45215
- const itemArray = def.status?.itemArray;
45216
- if (itemArray === void 0) return refused(problem("not-item-array", at, `\`${def.name}\` has no item array — it takes no \`items\``));
45217
- if (itemArray.path !== "items") return refused(problem("not-item-array", at, `\`${def.name}\`'s item array is at \`${itemArray.path}\`, not \`${require_composition.COMPOSITION_ITEM_ARRAY_PATH}\` — not composable yet`));
45218
- const ctx = {
45219
- capName: def.name,
45220
- itemArray,
45221
- reserved: reservedItemFields(itemArray),
45222
- featureIndex,
45223
- lookupCap,
45224
- mode
45225
- };
45226
- const results = Object.entries(feature.items ?? {}).flatMap(([key, item]) => [{
45227
- problems: missingLeaves(ctx, item, `${at}.${key}`),
45228
- fields: [],
45229
- features: [],
45230
- events: []
45231
- }, ...Object.entries(item.fields).map(([path, source]) => planItemField(ctx, {
45232
- key,
45233
- label: item.label,
45234
- path,
45235
- source
45236
- }))]);
45237
- return {
45238
- problems: results.flatMap((r) => r.problems),
45239
- fields: results.flatMap((r) => r.fields),
45240
- features: [],
45241
- events: []
45242
- };
45964
+ function unitsForDimension(dimension) {
45965
+ const out = [];
45966
+ for (const [unit, spec] of Object.entries(UNIT_TABLE)) if (spec.dimension === dimension) out.push(unit);
45967
+ return out;
45243
45968
  }
45244
45969
  //#endregion
45245
45970
  //#region src/composition/evaluate-field.ts
45971
+ /**
45972
+ * One composed field, evaluated from what its sources say NOW (D659).
45973
+ *
45974
+ * Pure. The composer calls it on every source change, and the slice-5 editor
45975
+ * will call it for its live preview, so both see the same answer.
45976
+ *
45977
+ * The rules (spec §2):
45978
+ * - a source that is offline or unreadable keeps its last value and is marked
45979
+ * STALE; the field is stale and keeps computing (D49);
45980
+ * - a source that is GONE makes the field UNAVAILABLE, `fatal`, and never a
45981
+ * plausible number (D393);
45982
+ * - a source that is unavailable but NOT gone (e.g. a cap unregistered at
45983
+ * runtime, R7b) makes the field UNAVAILABLE, non-fatal, `value: null`: it
45984
+ * may come back on its own, no block failure is raised for it;
45985
+ * - an expression that fails on a value makes the field unavailable for that
45986
+ * value, and NOT fatal: the next value may compute.
45987
+ *
45988
+ * `confirmed` (D663, D49): whether a NON-fatal unavailability is an ANSWER — a
45989
+ * cap the provider unregistered and a re-read agreed, a field the source
45990
+ * reported without, an expression that failed on a value — or only the
45991
+ * absence of one (a failed read, a first or empty read, a source not tracked
45992
+ * yet). Only a confirmed unavailability may hand a `release`-mode field back
45993
+ * to the native provider; an unconfirmed one holds it on its last value.
45994
+ * Absent means NOT confirmed. Fatal is always confirmed.
45995
+ *
45996
+ * When an expression has more than one unavailable binding, a FATAL one always
45997
+ * wins the outcome, regardless of position: every binding is scanned before
45998
+ * the field is judged, so an earlier non-fatal binding (e.g. a cap that is
45999
+ * momentarily unregistered) can never hide a later fatal one (a deleted
46000
+ * source) behind an early return.
46001
+ */
45246
46002
  function describeRead(read) {
45247
46003
  return `${require_composition.compositionSourceKey(read.source)} ${read.cap}.${read.fieldPath}`;
45248
46004
  }
@@ -45309,7 +46065,10 @@ function expressionOutcome(source, read, now, stateful) {
45309
46065
  }
45310
46066
  const deadlines = [];
45311
46067
  const result = require_composition.evaluateExpressionSource(source.expr, values, now, {
45312
- hooks: { noteDeadline: (at) => deadlines.push(at) },
46068
+ hooks: {
46069
+ noteDeadline: (at) => deadlines.push(at),
46070
+ convert: (value, from, to) => tryConvertUnit(value, normalizeUnit(from) ?? from, normalizeUnit(to) ?? to) ?? null
46071
+ },
45313
46072
  ...stateful === void 0 ? {} : { invokeStateful: (invocation) => require_composition.evaluateStatefulExpressionCall(stateful.callPathPrefix === void 0 ? invocation : {
45314
46073
  ...invocation,
45315
46074
  path: `${stateful.callPathPrefix}@${invocation.path}`
@@ -45548,304 +46307,71 @@ function feederCustomizationExample(sources) {
45548
46307
  });
45549
46308
  }
45550
46309
  //#endregion
45551
- //#region src/composition/validate-composition.ts
45552
- function buildCapabilityLookup(defs) {
45553
- const byName = new Map(defs.map((d) => [d.name, d]));
45554
- return (capName) => byName.get(capName) ?? null;
45555
- }
45556
- /** Caps every `BaseDevice` registers on itself; a second registration throws. */
45557
- var BASE_DEVICE_CAPS = new Set(["device-status", "feature-probe"]);
45558
- var PENDING_SELF = {
45559
- addonId: require_composition.COMPOSER_ADDON_ID,
45560
- stableId: `${require_composition.COMPOSED_DEVICE_STABLE_ID_PREFIX}(unsaved)`
45561
- };
45562
- /** The candidate's block id before its first save. Stored block ids are `randomUUID()`, so none can carry it. */
45563
- var PENDING_BLOCK_ID = "(unsaved)";
45564
- function composableCap(feature, at, lookupCap) {
45565
- const def = lookupCap(feature.cap);
45566
- if (def === null) return problem("unknown-capability", `${at}.cap`, `no capability is named \`${feature.cap}\``);
45567
- if (BASE_DEVICE_CAPS.has(def.name)) return problem("not-composable", `${at}.cap`, `\`${def.name}\` is registered by every device itself — it cannot be composed`);
45568
- const state = def.runtimeState;
45569
- if (def.scope !== "device" || state === void 0) return problem("not-composable", `${at}.cap`, `\`${def.name}\` has no per-device state to compose`);
45570
- return {
45571
- def,
45572
- state,
45573
- fields: describeTopLevelStateFields(state)
45574
- };
45575
- }
45576
- /**
45577
- * A capability BUILT by the composition (a new device, or one ADDED to an
45578
- * existing device) must fit the device type, serve no command, and have every
45579
- * required field. A REPLACE needs none of it: the cap is bound (a fact), the
45580
- * native keeps serving its methods, and only the named fields are owned (D663).
45581
- */
45582
- function builtCapProblems({ def, state, fields: targetFields }, feature, at, deviceType) {
45583
- const problems = [];
45584
- if (def.deviceTypes !== void 0 && !def.deviceTypes.includes(deviceType)) problems.push(problem("wrong-device-type", `${at}.cap`, `\`${def.name}\` is not offered on a \`${deviceType}\` device (it allows ${def.deviceTypes.join(", ")})`));
45585
- const served = Object.entries(def.methods).filter(([name, m]) => m.systemOnly !== true && def.composedMethods?.[name] === void 0).map(([name]) => `\`${name}\``);
45586
- if (served.length > 0) problems.push(problem("has-commands", `${at}.cap`, `\`${def.name}\` has ${served.join(", ")}, which a composed device cannot serve until commands arrive (slice 3)`));
45587
- const itemArrayPath = feature.items === void 0 ? null : def.status?.itemArray?.path ?? null;
45588
- for (const key of requiredTopLevelKeys(state)) {
45589
- if (key === itemArrayPath) continue;
45590
- if (!targetFields.has(key)) problems.push(problem("not-composable", `${at}.fields`, `\`${def.name}.${key}\` is not a scalar — nested fields arrive in a later slice`));
45591
- else if (!(key in feature.fields)) problems.push(problem("missing-field", `${at}.fields.${key}`, `\`${def.name}.${key}\` is required and has no source`));
45592
- }
45593
- return problems;
45594
- }
45595
- function planTopLevelField({ def, fields }, field, mode, lookupCap) {
45596
- const { featureIndex, path, source } = field;
45597
- const fieldAt = `features[${featureIndex}].fields.${path}`;
45598
- if (path.includes(".")) return refused(problem("nested-field", fieldAt, `\`${path}\` is nested — nested fields arrive in a later slice`));
45599
- const tf = fields.get(path);
45600
- if (tf === void 0) return refused(problem("unknown-field", fieldAt, `\`${def.name}\` has no field \`${path}\``));
45601
- const kinds = sourceKinds(source, lookupCap);
45602
- if (!kinds.ok) return refused(problem(kinds.code, fieldAt, kinds.message));
45603
- const role = roleOf(source);
45604
- const unavailable = unavailableFor(tf, role, mode, def.name, fieldAt);
45605
- if (!unavailable.ok) return refused(unavailable.problem);
45606
- const plan = {
45607
- cap: def.name,
45608
- path,
45609
- featureIndex,
45610
- kind: tf.kind,
45611
- nullable: tf.nullable,
45612
- required: tf.required,
45613
- unavailable: unavailable.unavailable,
45614
- role,
45615
- source,
45616
- reads: [...require_composition.fieldReads(source)]
45617
- };
45618
- const enumProblem = enumLiteralProblem(def.name, tf, source, fieldAt);
45619
- return {
45620
- problems: [...compatibility(def.name, tf, kinds.kinds, fieldAt), ...enumProblem === null ? [] : [enumProblem]],
45621
- fields: [plan],
45622
- features: [],
45623
- events: []
45624
- };
45625
- }
45626
- function planFeature(feature, featureIndex, target, lookupCap) {
45627
- const at = `features[${featureIndex}]`;
45628
- const cap = composableCap(feature, at, lookupCap);
45629
- if ("code" in cap) return refused(cap);
45630
- const capProblems = target.mode === "replace" ? [] : [...builtCapProblems(cap, feature, at, target.deviceType)];
45631
- if (feature.commands !== void 0 && Object.keys(feature.commands).length > 0) capProblems.push(problem("reserved-variant", `${at}.commands`, "commands (`forward`) arrive in slice 3"));
45632
- const perField = Object.entries(feature.fields).map(([path, source]) => planTopLevelField(cap, {
45633
- featureIndex,
45634
- path,
45635
- source
45636
- }, target.mode, lookupCap));
45637
- const items = feature.items === void 0 ? [] : [planItems(cap.def, feature, featureIndex, lookupCap, target.mode)];
45638
- const all = [...perField, ...items];
45639
- const fields = all.flatMap((result) => result.fields);
45640
- const featurePlan = {
45641
- featureIndex,
45642
- cap: cap.def.name,
45643
- mode: target.mode
45644
- };
45645
- const eventPlan = planCompositionEvents(cap.def, featurePlan, fields);
45646
- return {
45647
- problems: [
45648
- ...capProblems,
45649
- ...all.flatMap((r) => r.problems),
45650
- ...eventPlan.problems
45651
- ],
45652
- fields,
45653
- features: [featurePlan],
45654
- events: eventPlan.events
45655
- };
45656
- }
45657
- /** A cap the device serves itself; one the composer grafted (an earlier ADD) is not native. */
45658
- function isNativeCap(target, cap) {
45659
- const owner = target.nativeCaps.get(cap);
45660
- return owner !== void 0 && owner !== "composer";
45661
- }
45662
- /** The target read, or the refusal that replaces the whole plan when it could not be (D391). */
45663
- function planTargetOf(composition, target) {
45664
- if (composition.target.kind === "new") return {
45665
- kind: "new",
45666
- type: composition.target.type
45667
- };
45668
- const key = require_composition.compositionSourceKey(composition.target.device);
45669
- if (target === void 0) return problem("target-unreadable", "target", `target device \`${key}\` was not read — the save is refused rather than stored unchecked`);
45670
- if (target.kind === "absent") return problem("target-missing", "target", `target device \`${key}\` does not exist`);
45671
- if (target.kind === "unreadable") return problem("target-unreadable", "target", `could not read target device \`${key}\` (${target.error}) — the save is refused rather than stored unchecked`);
45672
- return {
45673
- kind: "existing",
45674
- found: target
45675
- };
45676
- }
45677
- function featureTargetOf(target, cap) {
45678
- if (target.kind === "new") return {
45679
- mode: "new",
45680
- deviceType: target.type
45681
- };
45682
- return {
45683
- mode: isNativeCap(target.found, cap) ? "replace" : "add",
45684
- deviceType: target.found.type
45685
- };
46310
+ //#region src/composition/presets/doorbell-feature.ts
46311
+ /**
46312
+ * The doorbell of a camera as a customization (D671). ONE builder: the
46313
+ * virtual-doorbell migration and the admin UI's "Use as doorbell" preset both
46314
+ * call it, so a preset can never write a shape the migration would refuse as
46315
+ * "an unrelated existing block".
46316
+ */
46317
+ /** A rise closer than this to the previous one is the same press (D671). */
46318
+ var DOORBELL_RISE_DEBOUNCE_MS = 2e3;
46319
+ /** Every source cap of `source` that `SOURCE_CAP_ACTIVE_FIELD` knows AND the device has bound. */
46320
+ function doorbellFeatureSources(source, boundCaps) {
46321
+ return Object.keys(require_composition.SOURCE_CAP_ACTIVE_FIELD).filter((cap) => Object.hasOwn(require_composition.SOURCE_CAP_CHANGED_AT_FIELD, cap) && boundCaps.includes(cap)).toSorted().flatMap((cap) => {
46322
+ const activeField = require_composition.SOURCE_CAP_ACTIVE_FIELD[cap];
46323
+ const changedAtField = require_composition.SOURCE_CAP_CHANGED_AT_FIELD[cap];
46324
+ return activeField === void 0 || changedAtField === void 0 ? [] : [{
46325
+ source,
46326
+ cap,
46327
+ activeField,
46328
+ changedAtField
46329
+ }];
46330
+ });
45686
46331
  }
45687
- /**
45688
- * The static plan. `target` describes an EXISTING target device (one read);
45689
- * it is ignored for a new one. On an existing target each feature REPLACES a
45690
- * cap the device has natively, else ADDS it (D663).
45691
- */
45692
- function planComposition(composition, lookupCap, target) {
45693
- const planTarget = planTargetOf(composition, target);
45694
- if ("code" in planTarget) return refused(planTarget);
45695
- const results = composition.features.map((feature, index) => {
45696
- const result = feature.kind === "passthrough" ? refused(problem("reserved-variant", `features[${index}]`, `whole-capability passthrough of \`${feature.cap}\` arrives in slice 3`)) : planFeature(feature, index, featureTargetOf(planTarget, feature.cap), lookupCap);
45697
- return require_composition.compositionFeatureEnabled(feature) ? result : {
45698
- problems: result.problems,
45699
- fields: [],
45700
- features: [],
45701
- events: []
46332
+ /** The D671 feature, byte for byte what the migration writes. Throws on zero sources. */
46333
+ function buildDoorbellCompositionFeature(input) {
46334
+ const sources = [...input.sources].toSorted((a, b) => `${a.source.addonId}/${a.source.stableId}#${a.cap}`.localeCompare(`${b.source.addonId}/${b.source.stableId}#${b.cap}`));
46335
+ if (sources.length === 0) throw new Error("doorbell composition needs at least one source");
46336
+ const edgeBindings = {};
46337
+ sources.forEach((entry, index) => {
46338
+ edgeBindings[`active${index}`] = {
46339
+ kind: "from",
46340
+ source: entry.source,
46341
+ cap: entry.cap,
46342
+ fieldPath: entry.activeField
46343
+ };
46344
+ edgeBindings[`changed${index}`] = {
46345
+ kind: "from",
46346
+ source: entry.source,
46347
+ cap: entry.cap,
46348
+ fieldPath: entry.changedAtField
45702
46349
  };
45703
46350
  });
45704
46351
  return {
45705
- problems: results.flatMap((r) => r.problems),
45706
- fields: results.flatMap((r) => r.fields),
45707
- features: results.flatMap((r) => r.features),
45708
- events: results.flatMap((r) => r.events)
45709
- };
45710
- }
45711
- function compositionSourceRefs(composition) {
45712
- const refs = composition.features.flatMap((f) => require_composition.compositionFeatureEnabled(f) && f.kind === "fields" ? require_composition.featureSources(f).flatMap(require_composition.fieldReads).map((r) => r.source) : []);
45713
- return [...new Map(refs.map((r) => [require_composition.compositionSourceKey(r), r])).values()];
45714
- }
45715
- /**
45716
- * The candidate's device: the existing target itself, else `self`, else a
45717
- * placeholder that cannot collide with a stored target. An existing target is
45718
- * known even on create, so a second customization of it is refused on create too.
45719
- */
45720
- function candidateSelf(composition, ctx, plan) {
45721
- return {
45722
- ref: composition.target.kind === "existing" ? composition.target.device : ctx.self ?? PENDING_SELF,
45723
- native: composition.target.kind === "existing" && ctx.target?.kind === "found" ? ctx.target : null,
45724
- replaced: replacedFieldKeys(plan)
45725
- };
45726
- }
45727
- /**
45728
- * `compositionFieldKey` of every field a REPLACE feature of `plan` owns — the
45729
- * candidate's own, and a stored peer's `CompositionPeer.replaced` (D663): one
45730
- * derivation, so the graph reads both the same way.
45731
- */
45732
- function replacedFieldKeys(plan) {
45733
- const replacing = new Set(plan.features.filter((f) => f.mode === "replace").map((f) => f.featureIndex));
45734
- return new Set(plan.fields.filter((f) => replacing.has(f.featureIndex)).map(compositionFieldKey));
45735
- }
45736
- /**
45737
- * A read of the candidate's own device. Its own composed output (a new device's
45738
- * field, an ADDED field) is the slice-1 own-field rule; on an existing target
45739
- * every other field — replaced, or not composed at all — is the NATIVE value,
45740
- * valid when the device serves that cap natively (D663, rule 5).
45741
- */
45742
- function selfReadProblems(read, at, fields, self) {
45743
- const readKey = `${read.cap}.${read.fieldPath}`;
45744
- if (fields.some((f) => compositionFieldKey(f) === readKey && !self.replaced.has(readKey))) return [];
45745
- if (self.native === null) return [problem("source-field-unknown", at, `this device has no composed field \`${read.cap}.${read.fieldPath}\``)];
45746
- if (isNativeCap(self.native, read.cap)) return [];
45747
- return [problem("source-capability-missing", at, `the target device (device ${self.native.deviceId}) has no native \`${read.cap}\``)];
45748
- }
45749
- function sourceProblems(fields, ctx, self) {
45750
- const selfKey = require_composition.compositionSourceKey(self.ref);
45751
- return fields.flatMap((field) => field.reads.flatMap((read) => {
45752
- const at = compositionFieldAt(field);
45753
- const key = require_composition.compositionSourceKey(read.source);
45754
- if (key === selfKey) return selfReadProblems(read, at, fields, self);
45755
- const desc = ctx.sources.get(key);
45756
- if (desc === void 0 || desc.kind === "unreadable") return [problem("source-unreadable", at, `could not read source \`${key}\` (${desc === void 0 ? "it was not read" : desc.error}) — the save is refused rather than stored unchecked`)];
45757
- if (desc.kind === "absent") return [problem("source-missing", at, `source \`${key}\` does not exist`)];
45758
- if (!desc.caps.has(read.cap)) return [problem("source-capability-missing", at, `source \`${key}\` (device ${desc.deviceId}) has no \`${read.cap}\``)];
45759
- return [];
45760
- }));
45761
- }
45762
- /**
45763
- * A cycle's node keys are `compositionReadKey` strings:
45764
- * `<addonId>/<stableId>#<cap>.<fieldPath>`. When a node belongs to the
45765
- * CANDIDATE itself (this composition being saved), pull its `cap`/`fieldPath`
45766
- * back out so the refusal can point at that exact field, matching the
45767
- * documented `features[N].fields.<path>` convention. A cap name has no `.`,
45768
- * so splitting `rest` on the FIRST `.` is exact; an item leaf's remainder
45769
- * (`items[desiccant].status`) is matched through `compositionFieldKey`.
45770
- */
45771
- function candidateFieldOfNode(nodeKey, candidateKey) {
45772
- const prefix = `${candidateKey}#`;
45773
- if (!nodeKey.startsWith(prefix)) return null;
45774
- const rest = nodeKey.slice(prefix.length);
45775
- const dot = rest.indexOf(".");
45776
- if (dot === -1) return null;
45777
- return {
45778
- cap: rest.slice(0, dot),
45779
- fieldPath: rest.slice(dot + 1)
45780
- };
45781
- }
45782
- /** The first node of a cycle's path that is one of THIS composition's own
45783
- * planned fields, as a documented-convention path; `'features'` when the
45784
- * cycle runs entirely through other stored compositions. */
45785
- function cyclePath(nodePath, candidateKey, fields) {
45786
- for (const nodeKey of nodePath) {
45787
- const hit = candidateFieldOfNode(nodeKey, candidateKey);
45788
- if (hit === null) continue;
45789
- const hitKey = `${hit.cap}.${hit.fieldPath}`;
45790
- const field = fields.find((f) => compositionFieldKey(f) === hitKey);
45791
- if (field !== void 0) return compositionFieldAt(field);
45792
- }
45793
- return "features";
45794
- }
45795
- /** The first unread device any of `nodes` belongs to; null when none does. */
45796
- function unreadDeviceOf(nodes, unread) {
45797
- for (const [key, error] of unread) if (nodes.some((node) => node.startsWith(`${key}#`))) return {
45798
- key,
45799
- error
45800
- };
45801
- return null;
45802
- }
45803
- /**
45804
- * Cycle check runs against the CANDIDATE (this composition, as block
45805
- * `ctx.blockId`, writing `self.ref`) plus every OTHER stored composition,
45806
- * decided per strongly connected component (`findCandidateCycles`): a cyclic
45807
- * component holding a candidate node refuses, with one representative cycle
45808
- * through it; one without is not this save's cycle. A
45809
- * stored composition of the same block is its old version; another block on
45810
- * the same device, or two stored peers sharing a device, make
45811
- * `compositionEdges` throw `CompositionGraphError` — refused BY NAME as
45812
- * `duplicate-target` (D391, D663) instead of escaping as an uncaught throw.
45813
- */
45814
- function cycleProblems(composition, ctx, fields, self) {
45815
- const candidate = {
45816
- blockId: ctx.blockId ?? "(unsaved)",
45817
- target: self.ref,
45818
- composition,
45819
- replaced: self.replaced
45820
- };
45821
- const candidateKey = require_composition.compositionSourceKey(candidate.target);
45822
- const unread = ctx.unreadTargets ?? /* @__PURE__ */ new Map();
45823
- try {
45824
- return findCandidateCycles(candidate, ctx.peers).map((c) => {
45825
- const at = cyclePath(c.path, candidateKey, fields);
45826
- const through = unreadDeviceOf([...c.component], unread);
45827
- return through === null ? problem("cycle", at, `a field reads itself: ${c.path.join(" → ")}`) : problem("cycle", at, `possible cycle through \`${through.key}\` — its state could not be read (${through.error}): ${c.path.join(" → ")}`);
45828
- });
45829
- } catch (err) {
45830
- if (err instanceof CompositionGraphError) return [problem("duplicate-target", "features", err.message)];
45831
- throw err;
45832
- }
45833
- }
45834
- function validateComposition(composition, ctx) {
45835
- const plan = planComposition(composition, ctx.lookupCap, ctx.target ?? void 0);
45836
- const self = candidateSelf(composition, ctx, plan);
45837
- const cycles = cycleProblems(composition, ctx, plan.fields, self);
45838
- const problems = [
45839
- ...plan.problems,
45840
- ...sourceProblems(plan.fields, ctx, self),
45841
- ...cycles
45842
- ];
45843
- return {
45844
- ok: problems.length === 0,
45845
- problems,
45846
- fields: [...plan.fields],
45847
- features: [...plan.features],
45848
- events: [...plan.events]
46352
+ kind: "fields",
46353
+ cap: "doorbell",
46354
+ enabled: input.enabled,
46355
+ fields: {
46356
+ lastPressedAt: {
46357
+ kind: "expression",
46358
+ expr: `latest(${sources.map((_, index) => `rose(active${index}, changed${index}, ${DOORBELL_RISE_DEBOUNCE_MS})`).join(", ")})`,
46359
+ bindings: edgeBindings
46360
+ },
46361
+ pressCountSinceStart: {
46362
+ kind: "expression",
46363
+ expr: "count(lastPressedAt)",
46364
+ bindings: { lastPressedAt: {
46365
+ kind: "from",
46366
+ source: {
46367
+ addonId: input.camera.addonId,
46368
+ stableId: input.camera.stableId
46369
+ },
46370
+ cap: "doorbell",
46371
+ fieldPath: "lastPressedAt"
46372
+ } }
46373
+ }
46374
+ }
45849
46375
  };
45850
46376
  }
45851
46377
  //#endregion
@@ -52971,6 +53497,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
52971
53497
  addonId: null,
52972
53498
  access: "view"
52973
53499
  },
53500
+ "coreBlocks.listComposableCaps": {
53501
+ capName: "core-blocks",
53502
+ capScope: "system",
53503
+ addonId: null,
53504
+ access: "view"
53505
+ },
52974
53506
  "coreBlocks.listCompositions": {
52975
53507
  capName: "core-blocks",
52976
53508
  capScope: "system",
@@ -56655,6 +57187,12 @@ var METHOD_ACCESS_MAP = Object.freeze({
56655
57187
  addonId: null,
56656
57188
  access: "create"
56657
57189
  },
57190
+ "pipelineOrchestrator.setCameraSensors": {
57191
+ capName: "pipeline-orchestrator",
57192
+ capScope: "system",
57193
+ addonId: null,
57194
+ access: "create"
57195
+ },
56658
57196
  "pipelineOrchestrator.setCameraStepOverride": {
56659
57197
  capName: "pipeline-orchestrator",
56660
57198
  capScope: "system",
@@ -60700,6 +61238,11 @@ var METHOD_DEVICE_SELECTORS = Object.freeze({
60700
61238
  form: "single",
60701
61239
  optional: false
60702
61240
  }],
61241
+ "pipelineOrchestrator.setCameraSensors": [{
61242
+ name: "deviceId",
61243
+ form: "single",
61244
+ optional: false
61245
+ }],
60703
61246
  "pipelineOrchestrator.setCameraStepOverride": [{
60704
61247
  name: "deviceId",
60705
61248
  form: "single",
@@ -61522,6 +62065,7 @@ var SYSTEM_SCOPE_DEVICE_METHODS = [
61522
62065
  "pipelineOrchestrator.getPipelineDevicePin",
61523
62066
  "pipelineOrchestrator.resolvePipeline",
61524
62067
  "pipelineOrchestrator.setCameraPipelineForAgent",
62068
+ "pipelineOrchestrator.setCameraSensors",
61525
62069
  "pipelineOrchestrator.setCameraStepOverride",
61526
62070
  "pipelineOrchestrator.setCameraStepToggle",
61527
62071
  "pipelineOrchestrator.setCameraSwitch",
@@ -62174,6 +62718,7 @@ function createSystemProxy(api) {
62174
62718
  getComposition: (input) => dispatch("coreBlocks", "getComposition", "query", input),
62175
62719
  listCompositions: (input) => dispatch("coreBlocks", "listCompositions", "query", input),
62176
62720
  getCustomization: (input) => dispatch("coreBlocks", "getCustomization", "query", input),
62721
+ listComposableCaps: (input) => dispatch("coreBlocks", "listComposableCaps", "query", input),
62177
62722
  validateComposition: (input) => dispatch("coreBlocks", "validateComposition", "mutation", input)
62178
62723
  },
62179
62724
  decoder: {
@@ -62505,6 +63050,7 @@ function createSystemProxy(api) {
62505
63050
  getNodeInferenceDevices: (input) => dispatch("pipelineOrchestrator", "getNodeInferenceDevices", "query", input),
62506
63051
  resetNodePipelineDefaults: (input) => dispatch("pipelineOrchestrator", "resetNodePipelineDefaults", "mutation", input),
62507
63052
  getCameraStatuses: (input) => dispatch("pipelineOrchestrator", "getCameraStatuses", "query", input),
63053
+ setCameraSensors: (input) => dispatch("pipelineOrchestrator", "setCameraSensors", "mutation", input),
62508
63054
  reconcileFromDisk: (input) => dispatch("pipelineOrchestrator", "reconcileFromDisk", "mutation", input),
62509
63055
  getReconcileFromDiskStatus: (input) => dispatch("pipelineOrchestrator", "getReconcileFromDiskStatus", "query", input),
62510
63056
  listTemplates: (input) => dispatch("pipelineOrchestrator", "listTemplates", "query", input),
@@ -66699,334 +67245,6 @@ var DEVICE_TYPE_INFO = { ["camera"]: {
66699
67245
  icon: "camera"
66700
67246
  } };
66701
67247
  //#endregion
66702
- //#region src/units/unit-table.ts
66703
- /**
66704
- * Frozen unit → spec table. `•` in the doc marks each dimension's canonical
66705
- * unit (`factor: 1, offset: 0`). °F derives from `°C = (°F − 32) × 5/9` ⇒
66706
- * `factor = 5/9`, `offset = -160/9` (kept as exact expressions, not rounded
66707
- * decimals). K derives from `°C = K − 273.15`.
66708
- */
66709
- var UNIT_TABLE = {
66710
- "°C": {
66711
- dimension: "temperature",
66712
- factor: 1,
66713
- offset: 0
66714
- },
66715
- "°F": {
66716
- dimension: "temperature",
66717
- factor: 5 / 9,
66718
- offset: -160 / 9
66719
- },
66720
- K: {
66721
- dimension: "temperature",
66722
- factor: 1,
66723
- offset: -273.15
66724
- },
66725
- hPa: {
66726
- dimension: "pressure",
66727
- factor: 1,
66728
- offset: 0
66729
- },
66730
- kPa: {
66731
- dimension: "pressure",
66732
- factor: 10,
66733
- offset: 0
66734
- },
66735
- Pa: {
66736
- dimension: "pressure",
66737
- factor: .01,
66738
- offset: 0
66739
- },
66740
- mbar: {
66741
- dimension: "pressure",
66742
- factor: 1,
66743
- offset: 0
66744
- },
66745
- bar: {
66746
- dimension: "pressure",
66747
- factor: 1e3,
66748
- offset: 0
66749
- },
66750
- inHg: {
66751
- dimension: "pressure",
66752
- factor: 33.8639,
66753
- offset: 0
66754
- },
66755
- mmHg: {
66756
- dimension: "pressure",
66757
- factor: 1.33322,
66758
- offset: 0
66759
- },
66760
- psi: {
66761
- dimension: "pressure",
66762
- factor: 68.9476,
66763
- offset: 0
66764
- },
66765
- "m/s": {
66766
- dimension: "speed",
66767
- factor: 1,
66768
- offset: 0
66769
- },
66770
- "km/h": {
66771
- dimension: "speed",
66772
- factor: 1 / 3.6,
66773
- offset: 0
66774
- },
66775
- mph: {
66776
- dimension: "speed",
66777
- factor: .44704,
66778
- offset: 0
66779
- },
66780
- kn: {
66781
- dimension: "speed",
66782
- factor: .514444,
66783
- offset: 0
66784
- },
66785
- "mm/h": {
66786
- dimension: "precipitation-rate",
66787
- factor: 1,
66788
- offset: 0
66789
- },
66790
- "in/h": {
66791
- dimension: "precipitation-rate",
66792
- factor: 25.4,
66793
- offset: 0
66794
- },
66795
- m: {
66796
- dimension: "length",
66797
- factor: 1,
66798
- offset: 0
66799
- },
66800
- mm: {
66801
- dimension: "length",
66802
- factor: .001,
66803
- offset: 0
66804
- },
66805
- cm: {
66806
- dimension: "length",
66807
- factor: .01,
66808
- offset: 0
66809
- },
66810
- km: {
66811
- dimension: "length",
66812
- factor: 1e3,
66813
- offset: 0
66814
- },
66815
- in: {
66816
- dimension: "length",
66817
- factor: .0254,
66818
- offset: 0
66819
- },
66820
- ft: {
66821
- dimension: "length",
66822
- factor: .3048,
66823
- offset: 0
66824
- },
66825
- mi: {
66826
- dimension: "length",
66827
- factor: 1609.344,
66828
- offset: 0
66829
- },
66830
- lx: {
66831
- dimension: "illuminance",
66832
- factor: 1,
66833
- offset: 0
66834
- },
66835
- "W/m²": {
66836
- dimension: "irradiance",
66837
- factor: 1,
66838
- offset: 0
66839
- },
66840
- W: {
66841
- dimension: "power",
66842
- factor: 1,
66843
- offset: 0
66844
- },
66845
- kW: {
66846
- dimension: "power",
66847
- factor: 1e3,
66848
- offset: 0
66849
- },
66850
- VA: {
66851
- dimension: "apparent-power",
66852
- factor: 1,
66853
- offset: 0
66854
- },
66855
- Wh: {
66856
- dimension: "energy",
66857
- factor: 1,
66858
- offset: 0
66859
- },
66860
- kWh: {
66861
- dimension: "energy",
66862
- factor: 1e3,
66863
- offset: 0
66864
- },
66865
- MWh: {
66866
- dimension: "energy",
66867
- factor: 1e6,
66868
- offset: 0
66869
- },
66870
- V: {
66871
- dimension: "voltage",
66872
- factor: 1,
66873
- offset: 0
66874
- },
66875
- mV: {
66876
- dimension: "voltage",
66877
- factor: .001,
66878
- offset: 0
66879
- },
66880
- A: {
66881
- dimension: "current",
66882
- factor: 1,
66883
- offset: 0
66884
- },
66885
- mA: {
66886
- dimension: "current",
66887
- factor: .001,
66888
- offset: 0
66889
- },
66890
- ppm: {
66891
- dimension: "concentration-volume",
66892
- factor: 1,
66893
- offset: 0
66894
- },
66895
- ppb: {
66896
- dimension: "concentration-volume",
66897
- factor: .001,
66898
- offset: 0
66899
- },
66900
- "µg/m³": {
66901
- dimension: "concentration-mass",
66902
- factor: 1,
66903
- offset: 0
66904
- },
66905
- "mg/m³": {
66906
- dimension: "concentration-mass",
66907
- factor: 1e3,
66908
- offset: 0
66909
- },
66910
- kg: {
66911
- dimension: "mass",
66912
- factor: 1,
66913
- offset: 0
66914
- },
66915
- g: {
66916
- dimension: "mass",
66917
- factor: .001,
66918
- offset: 0
66919
- },
66920
- lb: {
66921
- dimension: "mass",
66922
- factor: .453592,
66923
- offset: 0
66924
- },
66925
- oz: {
66926
- dimension: "mass",
66927
- factor: .0283495,
66928
- offset: 0
66929
- },
66930
- "%": {
66931
- dimension: "percentage",
66932
- factor: 1,
66933
- offset: 0
66934
- }
66935
- };
66936
- //#endregion
66937
- //#region src/units/convert.ts
66938
- /**
66939
- * Pure unit-conversion API over `UNIT_TABLE`. No dependencies, no side effects.
66940
- *
66941
- * Conversion is refused (throws `UnitConversionError`, or returns `undefined`
66942
- * from the `try*` variant) whenever a unit is unknown or the two units belong
66943
- * to different dimensions — cross-dimension conversion is deliberately
66944
- * impossible so a render override can never make the value and its unit label
66945
- * disagree.
66946
- *
66947
- * Callers pass units through `normalizeUnit` (`../device/source-info.ts`) BEFORE
66948
- * calling here — the table keys only canonical spellings.
66949
- */
66950
- /** Thrown by `convertUnit` when a conversion is refused. Carries the offending
66951
- * units + a machine-readable `reason` for callers that branch on the cause. */
66952
- var UnitConversionError = class extends Error {
66953
- from;
66954
- to;
66955
- reason;
66956
- constructor(from, to, reason) {
66957
- super(`[units] cannot convert '${from}' → '${to}': ${reason}`);
66958
- this.name = "UnitConversionError";
66959
- this.from = from;
66960
- this.to = to;
66961
- this.reason = reason;
66962
- }
66963
- };
66964
- /** Resolve a unit's `UnitSpec`, or `undefined` when the spelling is unknown. */
66965
- function specFor(unit) {
66966
- return Object.hasOwn(UNIT_TABLE, unit) ? UNIT_TABLE[unit] : void 0;
66967
- }
66968
- /** The dimension a unit belongs to, or `undefined` for an unknown unit. */
66969
- function unitDimension(unit) {
66970
- return specFor(unit)?.dimension;
66971
- }
66972
- /** Value in `spec`'s unit → its dimension's canonical unit. */
66973
- function toCanonical(value, spec) {
66974
- return value * spec.factor + spec.offset;
66975
- }
66976
- /** Canonical-unit value → the unit described by `spec`. */
66977
- function fromCanonical(canonical, spec) {
66978
- return (canonical - spec.offset) / spec.factor;
66979
- }
66980
- /**
66981
- * Convert `value` from unit `from` to unit `to`. Identity when `from === to`.
66982
- * Throws `UnitConversionError` when either unit is unknown or the units belong
66983
- * to different dimensions.
66984
- */
66985
- function convertUnit(value, from, to) {
66986
- if (from === to) return value;
66987
- const fromSpec = specFor(from);
66988
- if (!fromSpec) throw new UnitConversionError(from, to, "unknown-from");
66989
- const toSpec = specFor(to);
66990
- if (!toSpec) throw new UnitConversionError(from, to, "unknown-to");
66991
- if (fromSpec.dimension !== toSpec.dimension) throw new UnitConversionError(from, to, "cross-dimension");
66992
- return fromCanonical(toCanonical(value, fromSpec), toSpec);
66993
- }
66994
- /**
66995
- * Graceful variant for the render path: returns the converted value, or
66996
- * `undefined` when the conversion is refused (unknown unit / cross-dimension).
66997
- * Never throws — a render caller falls back to the raw value + source unit.
66998
- */
66999
- function tryConvertUnit(value, from, to) {
67000
- if (from === to) return value;
67001
- const fromSpec = specFor(from);
67002
- if (!fromSpec) return void 0;
67003
- const toSpec = specFor(to);
67004
- if (!toSpec) return void 0;
67005
- if (fromSpec.dimension !== toSpec.dimension) return void 0;
67006
- return fromCanonical(toCanonical(value, fromSpec), toSpec);
67007
- }
67008
- /**
67009
- * Whether `value` can be converted between `from` and `to` (same dimension,
67010
- * both known). Cheap boolean probe for the UI's same-dimension unit picker and
67011
- * the resolver's convertibility branch — compute ONCE so a unit label and its
67012
- * value math can never disagree.
67013
- */
67014
- function canConvertUnit(from, to) {
67015
- if (from === to) return true;
67016
- const fromDim = unitDimension(from);
67017
- if (fromDim === void 0) return false;
67018
- return fromDim === unitDimension(to);
67019
- }
67020
- /**
67021
- * Every known unit spelling in a dimension (table insertion order — canonical
67022
- * unit first). Powers the UI's same-dimension unit picker.
67023
- */
67024
- function unitsForDimension(dimension) {
67025
- const out = [];
67026
- for (const [unit, spec] of Object.entries(UNIT_TABLE)) if (spec.dimension === dimension) out.push(unit);
67027
- return out;
67028
- }
67029
- //#endregion
67030
67248
  //#region src/util/location-match.ts
67031
67249
  /**
67032
67250
  * Pure fuzzy matcher for adoption location import. Normalized
@@ -68575,6 +68793,9 @@ exports.ClusterModelChoiceSchema = ClusterModelChoiceSchema;
68575
68793
  exports.CollectionColumnSchema = CollectionColumnSchema;
68576
68794
  exports.CollectionIndexSchema = CollectionIndexSchema;
68577
68795
  exports.ColorStatusSchema = ColorStatusSchema;
68796
+ exports.ComposableCapabilitiesSchema = ComposableCapabilitiesSchema;
68797
+ exports.ComposableCapabilitySchema = ComposableCapabilitySchema;
68798
+ exports.ComposableFieldSchema = ComposableFieldSchema;
68578
68799
  exports.ComposerApplyInputSchema = ComposerApplyInputSchema;
68579
68800
  exports.ComposerApplyResultSchema = ComposerApplyResultSchema;
68580
68801
  exports.ComposerBlockSchema = ComposerBlockSchema;
@@ -68700,6 +68921,7 @@ exports.DISPLAY_ICON_GROUPS = DISPLAY_ICON_GROUPS;
68700
68921
  exports.DISPLAY_ICON_KEYS = DISPLAY_ICON_KEYS;
68701
68922
  exports.DISPLAY_ICON_OFFERED_KEYS = DISPLAY_ICON_OFFERED_KEYS;
68702
68923
  exports.DISPLAY_ICON_VOCABULARY = DISPLAY_ICON_VOCABULARY;
68924
+ exports.DOORBELL_RISE_DEBOUNCE_MS = DOORBELL_RISE_DEBOUNCE_MS;
68703
68925
  exports.DOORBELL_SOURCE_SLOT = DOORBELL_SOURCE_SLOT;
68704
68926
  exports.DataStoreEngineInfoSchema = EngineInfoSchema;
68705
68927
  exports.DayNightModeSchema = DayNightModeSchema;
@@ -69506,6 +69728,7 @@ exports.ServerUpdateActionResultSchema = ServerUpdateActionResultSchema;
69506
69728
  exports.ServerUpdateCheckResultSchema = ServerUpdateCheckResultSchema;
69507
69729
  exports.ServerUpdateOutcomeSchema = ServerUpdateOutcomeSchema;
69508
69730
  exports.ServerUpdateStateSchema = ServerUpdateStateSchema;
69731
+ exports.SetCameraSensorsInputSchema = SetCameraSensorsInputSchema;
69509
69732
  exports.SetLoggingSettingsInputSchema = SetLoggingSettingsInputSchema;
69510
69733
  exports.SetSiteLocationInputSchema = SetSiteLocationInputSchema;
69511
69734
  exports.SettingsPatchSchema = SettingsPatchSchema;
@@ -69754,6 +69977,7 @@ exports.buildAddonRouteProvider = buildAddonRouteProvider;
69754
69977
  exports.buildAudioArgs = require_composition.buildAudioArgs;
69755
69978
  exports.buildCapabilityLookup = buildCapabilityLookup;
69756
69979
  exports.buildDeviceAdminUrl = buildDeviceAdminUrl;
69980
+ exports.buildDoorbellCompositionFeature = buildDoorbellCompositionFeature;
69757
69981
  exports.buildEventKindDescriptor = buildEventKindDescriptor;
69758
69982
  exports.buildFfmpegArgs = require_composition.buildFfmpegArgs;
69759
69983
  exports.buildInputArgs = require_composition.buildInputArgs;
@@ -69762,6 +69986,7 @@ exports.buildNcTaxonomy = buildNcTaxonomy;
69762
69986
  exports.buildRoleScopes = buildRoleScopes;
69763
69987
  exports.buildStreamParamsConfigSchema = buildStreamParamsConfigSchema;
69764
69988
  exports.buildVideoArgs = require_composition.buildVideoArgs;
69989
+ exports.builtCapabilityBlockers = builtCapabilityBlockers;
69765
69990
  exports.buttonCapability = buttonCapability;
69766
69991
  exports.cameraCredentialsCapability = cameraCredentialsCapability;
69767
69992
  exports.cameraGridLayoutCapability = cameraGridLayoutCapability;
@@ -69854,6 +70079,7 @@ exports.deriveBatteryPresence = deriveBatteryPresence;
69854
70079
  exports.deriveCameraSwitches = deriveCameraSwitches;
69855
70080
  exports.deriveDetailCropRect = deriveDetailCropRect;
69856
70081
  exports.deriveRecordingMode = deriveRecordingMode;
70082
+ exports.describeComposableCaps = describeComposableCaps;
69857
70083
  exports.describeCustomActions = require_sleep.describeCustomActions;
69858
70084
  exports.describeModelVariant = describeModelVariant;
69859
70085
  exports.describeOnboardClamp = describeOnboardClamp;
@@ -69881,6 +70107,7 @@ exports.deviceStatusCapability = deviceStatusCapability;
69881
70107
  exports.displayIconEntry = displayIconEntry;
69882
70108
  exports.displayIconsInGroup = displayIconsInGroup;
69883
70109
  exports.doorbellCapability = doorbellCapability;
70110
+ exports.doorbellFeatureSources = doorbellFeatureSources;
69884
70111
  exports.droppedConditionsForKind = droppedConditionsForKind;
69885
70112
  exports.egressTranscodeSharingKey = egressTranscodeSharingKey;
69886
70113
  exports.egressTransportFromRequest = egressTransportFromRequest;