@codemem/core 0.50.0-beta.1 → 0.50.0-beta.2

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.
Files changed (68) hide show
  1. package/dist/coordinator-actions.d.ts +2 -0
  2. package/dist/coordinator-actions.d.ts.map +1 -1
  3. package/dist/coordinator-device-removal-list.d.ts +3 -1
  4. package/dist/coordinator-device-removal-list.d.ts.map +1 -1
  5. package/dist/{coordinator-runtime-ynLTJI6d.js → coordinator-runtime-ChgCIqfx.js} +400 -396
  6. package/dist/coordinator-runtime-ChgCIqfx.js.map +1 -0
  7. package/dist/device-identity-inventory.d.ts.map +1 -1
  8. package/dist/index.d.ts +2 -2
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +10146 -9920
  11. package/dist/index.js.map +1 -1
  12. package/dist/ingest-events.d.ts.map +1 -1
  13. package/dist/internal/cloudflare-coordinator.js +2 -2
  14. package/dist/internal/relay-runtime.js +10 -10
  15. package/dist/legacy-team-setup-completion-manifest.d.ts +41 -0
  16. package/dist/legacy-team-setup-completion-manifest.d.ts.map +1 -1
  17. package/dist/legacy-team-setup-errors.d.ts +1 -1
  18. package/dist/legacy-team-setup-errors.d.ts.map +1 -1
  19. package/dist/{owner-enrollment-start-D8QzF1Ar.js → owner-enrollment-start-CD7R8wy3.js} +2 -2
  20. package/dist/{owner-enrollment-start-D8QzF1Ar.js.map → owner-enrollment-start-CD7R8wy3.js.map} +1 -1
  21. package/dist/pairing-removal.d.ts +2 -1
  22. package/dist/pairing-removal.d.ts.map +1 -1
  23. package/dist/pi-hooks.d.ts +1 -5
  24. package/dist/pi-hooks.d.ts.map +1 -1
  25. package/dist/project-scope-settings.d.ts +14 -1
  26. package/dist/project-scope-settings.d.ts.map +1 -1
  27. package/dist/raw-event-flush.d.ts.map +1 -1
  28. package/dist/{relay-peer-client-w7WdS1AP.js → relay-peer-client-CrFrhN_q.js} +1953 -1949
  29. package/dist/relay-peer-client-CrFrhN_q.js.map +1 -0
  30. package/dist/removed-device-local-ids.d.ts +16 -0
  31. package/dist/removed-device-local-ids.d.ts.map +1 -0
  32. package/dist/scope-membership-cache-read.d.ts +28 -1
  33. package/dist/scope-membership-cache-read.d.ts.map +1 -1
  34. package/dist/scope-membership-cache-test-fixtures.d.ts +1 -0
  35. package/dist/scope-membership-cache-test-fixtures.d.ts.map +1 -1
  36. package/dist/scope-membership-cache.d.ts +1 -1
  37. package/dist/scope-membership-cache.d.ts.map +1 -1
  38. package/dist/scope-membership-evidence.d.ts +17 -1
  39. package/dist/scope-membership-evidence.d.ts.map +1 -1
  40. package/dist/{scope-resolution-B7FK15hx.js → scope-resolution-DXzf4k16.js} +1353 -1313
  41. package/dist/{scope-resolution-B7FK15hx.js.map → scope-resolution-DXzf4k16.js.map} +1 -1
  42. package/dist/semantic-worker-entry.js +1 -1
  43. package/dist/{semantic-worker-job-BjujlM4-.js → semantic-worker-job-DjfAtX64.js} +3 -3
  44. package/dist/{semantic-worker-job-BjujlM4-.js.map → semantic-worker-job-DjfAtX64.js.map} +1 -1
  45. package/dist/{semantic-worker-ranking-WaUCapnY.js → semantic-worker-ranking-CZCemeb4.js} +26 -26
  46. package/dist/{semantic-worker-ranking-WaUCapnY.js.map → semantic-worker-ranking-CZCemeb4.js.map} +1 -1
  47. package/dist/{sync-auth-constants-DNUSV-Tn.js → sync-auth-constants-CifCg69d.js} +16 -14
  48. package/dist/{sync-auth-constants-DNUSV-Tn.js.map → sync-auth-constants-CifCg69d.js.map} +1 -1
  49. package/dist/sync-channel-pass.d.ts.map +1 -1
  50. package/dist/sync-pass.d.ts +2 -0
  51. package/dist/sync-pass.d.ts.map +1 -1
  52. package/dist/sync-reachability-pass-BFTEIkZH.js +2 -0
  53. package/dist/{sync-reachability-pass-DKEORTbs.js → sync-reachability-pass-vOvswNNG.js} +2738 -2591
  54. package/dist/sync-reachability-pass-vOvswNNG.js.map +1 -0
  55. package/dist/sync-replication.d.ts +5 -0
  56. package/dist/sync-replication.d.ts.map +1 -1
  57. package/dist/sync-status-test-fixtures.d.ts +1 -1
  58. package/dist/sync-status-test-fixtures.d.ts.map +1 -1
  59. package/dist/test-utils.d.ts +4 -1
  60. package/dist/test-utils.d.ts.map +1 -1
  61. package/dist/{validated-vector-index-audit-BtUovYuM.js → validated-vector-index-audit-CFSIbYIn.js} +33 -33
  62. package/dist/{validated-vector-index-audit-BtUovYuM.js.map → validated-vector-index-audit-CFSIbYIn.js.map} +1 -1
  63. package/dist/viewer-device-removal-commit.d.ts.map +1 -1
  64. package/package.json +3 -3
  65. package/dist/coordinator-runtime-ynLTJI6d.js.map +0 -1
  66. package/dist/relay-peer-client-w7WdS1AP.js.map +0 -1
  67. package/dist/sync-reachability-pass-BpTtRqcV.js +0 -2
  68. package/dist/sync-reachability-pass-DKEORTbs.js.map +0 -1
@@ -1,9 +1,9 @@
1
- import { Qt as e, Vt as t, Xt as n, Zt as r, l as i } from "./scope-resolution-B7FK15hx.js";
2
- import { _ as a, h as o } from "./workspace-identity-C7EPmSZe.js";
3
- import { Na as s, V as c, i as l, io as u, lo as d, r as f } from "./sync-auth-constants-DNUSV-Tn.js";
4
- import { A as p, J as m, M as h, O as g, T as _, V as ee, _ as v, ct as y, ft as te, g as ne, j as b, m as re, v as ie, y as ae } from "./relay-peer-client-w7WdS1AP.js";
5
- import { createHash as oe } from "node:crypto";
6
- import { networkInterfaces as se } from "node:os";
1
+ import { Kt as e, h as t, l as n, nn as r, rn as i, tn as a } from "./scope-resolution-DXzf4k16.js";
2
+ import { _ as o, h as s } from "./workspace-identity-C7EPmSZe.js";
3
+ import { Na as c, V as l, i as u, io as d, lo as f, r as p } from "./sync-auth-constants-CifCg69d.js";
4
+ import { A as m, J as h, M as g, O as ee, T as _, V as te, _ as v, ct as y, ft as ne, g as re, j as b, m as ie, v as ae, y as oe } from "./relay-peer-client-CrFrhN_q.js";
5
+ import { createHash as se } from "node:crypto";
6
+ import { networkInterfaces as ce } from "node:os";
7
7
  //#region src/identity-device-assignment.ts
8
8
  var x = class extends Error {
9
9
  code;
@@ -14,20 +14,20 @@ var x = class extends Error {
14
14
  function S() {
15
15
  throw new x("team_setup_assignment_changed");
16
16
  }
17
- function ce(e) {
17
+ function le(e) {
18
18
  return typeof e == "object" && !!e && "code" in e && e.code === "SQLITE_CONSTRAINT_PRIMARYKEY";
19
19
  }
20
- function le(e, t) {
20
+ function ue(e, t) {
21
21
  return e.prepare("SELECT identity_id, assignment_version, status\n FROM identity_devices\n WHERE device_id = ?").get(t) ?? null;
22
22
  }
23
- function ue(e, t) {
23
+ function de(e, t) {
24
24
  if (t.kind === "absent") {
25
25
  e && S();
26
26
  return;
27
27
  }
28
28
  (e?.status !== "active" || e.identity_id !== t.identityId || e.assignment_version !== t.assignmentVersion) && S();
29
29
  }
30
- function de(e, t, n) {
30
+ function fe(e, t, n) {
31
31
  let r = e.prepare("SELECT d.team_id\n FROM policy_team_device_decisions d\n JOIN policy_teams t ON t.team_id = d.team_id\n WHERE d.device_id = ?\n AND d.decision = 'included'\n AND t.device_eligibility_mode = 'reviewed_allowlist'").all(t), i = e.prepare("UPDATE policy_team_device_decisions\n SET decision = 'unresolved', updated_at = ?\n WHERE device_id = ?\n AND decision = 'included'\n AND team_id IN (\n SELECT team_id FROM policy_teams\n WHERE device_eligibility_mode = 'reviewed_allowlist'\n )").run(n, t);
32
32
  for (let t of r) e.prepare("UPDATE policy_teams\n SET source_fingerprint = NULL, updated_at = ?\n WHERE team_id = ?").run(n, t.team_id);
33
33
  return {
@@ -35,10 +35,10 @@ function de(e, t, n) {
35
35
  invalidatedTeamCount: r.length
36
36
  };
37
37
  }
38
- function fe(e, t) {
38
+ function pe(e, t) {
39
39
  if (!e.inTransaction) throw new x("identity_device_assignment_transaction_required");
40
- let n = le(e, t.deviceId);
41
- if (ue(n, t.expectation), n?.status === "active" && n?.identity_id === t.targetIdentityId) return {
40
+ let n = ue(e, t.deviceId);
41
+ if (de(n, t.expectation), n?.status === "active" && n?.identity_id === t.targetIdentityId) return {
42
42
  assignmentVersion: n.assignment_version,
43
43
  changed: !1,
44
44
  invalidatedDecisionCount: 0,
@@ -61,14 +61,14 @@ function fe(e, t) {
61
61
  try {
62
62
  e.prepare("INSERT INTO identity_devices(\n device_id, identity_id, display_name, status, provenance, revision,\n migration_state, source_fingerprint, idempotency_key, created_at, updated_at\n ) VALUES (?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?)").run(t.deviceId, t.targetIdentityId, n.displayName, n.provenance, n.revision, n.migrationState, n.sourceFingerprint ?? null, n.idempotencyKey, r, r);
63
63
  } catch (e) {
64
- throw ce(e) && S(), e;
64
+ throw le(e) && S(), e;
65
65
  }
66
66
  }
67
- let i = le(e, t.deviceId);
67
+ let i = ue(e, t.deviceId);
68
68
  return (i?.status !== "active" || i.identity_id !== t.targetIdentityId) && S(), n ? {
69
69
  assignmentVersion: i.assignment_version,
70
70
  changed: !0,
71
- ...de(e, t.deviceId, r)
71
+ ...fe(e, t.deviceId, r)
72
72
  } : {
73
73
  assignmentVersion: i.assignment_version,
74
74
  changed: !0,
@@ -78,20 +78,20 @@ function fe(e, t) {
78
78
  }
79
79
  //#endregion
80
80
  //#region src/coordinator-rejoin-timestamp.ts
81
- function pe(e) {
81
+ function me(e) {
82
82
  return typeof e == "number" && Number.isSafeInteger(e) && e >= 0 && e <= 864e13;
83
83
  }
84
84
  //#endregion
85
85
  //#region src/retired-device-aliases.ts
86
86
  function C(e) {
87
87
  if (!e) return null;
88
- let t = a(e);
89
- return t.kind === "ed25519" ? oe("sha256").update(t.blob).digest("hex") : null;
88
+ let t = o(e);
89
+ return t.kind === "ed25519" ? se("sha256").update(t.blob).digest("hex") : null;
90
90
  }
91
- function me(e) {
91
+ function he(e) {
92
92
  e.exec("CREATE TABLE IF NOT EXISTS retired_device_aliases (\n device_id TEXT PRIMARY KEY,\n kind TEXT NOT NULL CHECK(kind IN ('device_id', 'key')),\n fingerprint TEXT NOT NULL,\n key_id TEXT,\n retired_at TEXT NOT NULL\n )");
93
93
  }
94
- function he(e) {
94
+ function w(e) {
95
95
  if (!e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'retired_device_aliases'").get()) return /* @__PURE__ */ new Map();
96
96
  let t = e.prepare("SELECT device_id, kind, fingerprint, key_id FROM retired_device_aliases").all();
97
97
  return new Map(t.map((e) => [e.device_id, {
@@ -100,29 +100,29 @@ function he(e) {
100
100
  keyId: e.key_id
101
101
  }]));
102
102
  }
103
- function w(e, t) {
103
+ function T(e, t) {
104
104
  if (!e) return !1;
105
105
  if (e.kind === "device_id" || !t || !t.publicKey && !t.fingerprint) return !0;
106
106
  let n = C(t.publicKey);
107
107
  return e.keyId && n ? n === e.keyId : t.fingerprint === e.fingerprint;
108
108
  }
109
109
  function ge(e, t) {
110
- me(e);
110
+ he(e);
111
111
  let n = e.prepare("INSERT INTO retired_device_aliases(device_id, kind, fingerprint, key_id, retired_at)\n VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(device_id) DO UPDATE SET\n kind = CASE WHEN retired_device_aliases.kind = 'device_id' THEN 'device_id' ELSE excluded.kind END,\n fingerprint = excluded.fingerprint,\n key_id = excluded.key_id,\n retired_at = excluded.retired_at"), r = (/* @__PURE__ */ new Date()).toISOString();
112
112
  for (let e of t) n.run(e.deviceId, e.kind, e.fingerprint, e.keyId, r);
113
113
  }
114
114
  //#endregion
115
115
  //#region src/device-identity-inventory.ts
116
- var _e = 1, ve = 500, T = 2e3;
117
- function E(e) {
116
+ var _e = 1, ve = 500, E = 2e3;
117
+ function D(e) {
118
118
  return typeof e == "string" && e.trim() ? e.trim() : null;
119
119
  }
120
- function D(e, t) {
120
+ function O(e, t) {
121
121
  if (!e) return {
122
122
  value: t,
123
123
  conflict: !1
124
124
  };
125
- let n = o(e);
125
+ let n = s(e);
126
126
  return t && t !== n ? {
127
127
  value: null,
128
128
  conflict: !0
@@ -132,7 +132,7 @@ function D(e, t) {
132
132
  };
133
133
  }
134
134
  function ye(e) {
135
- let t = D(E(e.publicKey), E(e.fingerprint));
135
+ let t = O(D(e.publicKey), D(e.fingerprint));
136
136
  return {
137
137
  deviceId: e.deviceId,
138
138
  displayName: e.displayName,
@@ -153,7 +153,7 @@ function ye(e) {
153
153
  };
154
154
  }
155
155
  function be(e) {
156
- let t = D(E(e.publicKey), E(e.pinnedFingerprint));
156
+ let t = O(D(e.publicKey), D(e.pinnedFingerprint));
157
157
  return {
158
158
  deviceId: e.deviceId,
159
159
  displayName: e.displayName,
@@ -161,13 +161,13 @@ function be(e) {
161
161
  fingerprint: t.value,
162
162
  fingerprintConflict: t.conflict,
163
163
  isLocal: !1,
164
- suggestedIdentityId: E(e.suggestedIdentityId),
164
+ suggestedIdentityId: D(e.suggestedIdentityId),
165
165
  bindingIdentityId: null,
166
166
  bindingStatus: null,
167
167
  bindingIdentityStatus: null,
168
168
  bindingAuthoritative: !1,
169
169
  enrollmentEnabled: null,
170
- pairingProof: E(e.trustProvenance) !== "coordinator_policy" || e.claimedLocalActor,
170
+ pairingProof: D(e.trustProvenance) !== "coordinator_policy" || e.claimedLocalActor,
171
171
  serviceDevice: !1,
172
172
  revoked: e.retired === !0,
173
173
  rejoinedAtMs: null
@@ -194,15 +194,15 @@ function xe(e) {
194
194
  };
195
195
  }
196
196
  function Se(e) {
197
- let t = D(E(e.public_key), E(e.fingerprint));
197
+ let t = O(D(e.public_key), D(e.fingerprint));
198
198
  return {
199
199
  deviceId: e.device_id,
200
- displayName: E(e.display_name) ?? "",
200
+ displayName: D(e.display_name) ?? "",
201
201
  source: "coordinator_enrollment",
202
202
  fingerprint: t.value,
203
203
  fingerprintConflict: t.conflict,
204
204
  isLocal: !1,
205
- suggestedIdentityId: E(e.identity_id),
205
+ suggestedIdentityId: D(e.identity_id),
206
206
  bindingIdentityId: null,
207
207
  bindingStatus: null,
208
208
  bindingIdentityStatus: null,
@@ -211,7 +211,7 @@ function Se(e) {
211
211
  pairingProof: !1,
212
212
  serviceDevice: e.service_role === "relay_health_probe",
213
213
  revoked: e.revoked === !0,
214
- rejoinedAtMs: e.enabled === 1 && pe(e.rejoined_at_ms) ? e.rejoined_at_ms : null
214
+ rejoinedAtMs: e.enabled === 1 && me(e.rejoined_at_ms) ? e.rejoined_at_ms : null
215
215
  };
216
216
  }
217
217
  function Ce(e) {
@@ -220,7 +220,7 @@ function Ce(e) {
220
220
  ...e.peers.map(be),
221
221
  ...e.bindings.map(xe),
222
222
  ...e.coordinator.availability === "available" ? e.coordinator.enrollments.map(Se) : []
223
- ].filter((e) => E(e.deviceId) != null);
223
+ ].filter((e) => D(e.deviceId) != null);
224
224
  }
225
225
  function we(e) {
226
226
  let t = e.map((e, t) => t), n = (e) => {
@@ -242,7 +242,7 @@ function we(e) {
242
242
  o.set(r, [...o.get(r) ?? [], e]);
243
243
  }), [...o.values()];
244
244
  }
245
- var O = [
245
+ var k = [
246
246
  "local_device",
247
247
  "identity_binding",
248
248
  "sync_peer",
@@ -252,75 +252,78 @@ function Te(e, t) {
252
252
  return e.find((e) => e.source === t) ?? null;
253
253
  }
254
254
  function Ee(e) {
255
- for (let t of O) {
255
+ for (let t of k) {
256
256
  let n = e.filter((e) => e.source === t && e.displayName.length > 0 && !["Canonical device", "Unnamed device"].includes(e.displayName)).toSorted((e, t) => e.deviceId.localeCompare(t.deviceId) || e.displayName.localeCompare(t.displayName))[0];
257
257
  if (n) return n.displayName;
258
258
  }
259
259
  return "Unnamed device";
260
260
  }
261
- function De(e, t) {
261
+ function De(e) {
262
+ return e.some((e) => e.serviceDevice) ? e.every((e) => e.source === "coordinator_enrollment" ? e.serviceDevice : e.source === "sync_peer" && !e.pairingProof) : !1;
263
+ }
264
+ function Oe(e, t) {
262
265
  if (e.some((e) => e.revoked)) return "retired";
263
266
  if (t.conflicted) return "conflicted";
264
- if (e.every((e) => e.source === "coordinator_enrollment" && e.serviceDevice)) return "service";
267
+ if (De(e)) return "service";
265
268
  if (t.activeBindings.length > 0) return "configured";
266
269
  let n = e.some((e) => e.pairingProof);
267
270
  return e.some((e) => e.source === "coordinator_enrollment" || e.source === "sync_peer" && !e.pairingProof) && !n ? "pairing_required" : "setup_required";
268
271
  }
269
- function Oe(e, t, n) {
272
+ function ke(e, t, n) {
270
273
  return e === "service" || e === "retired" || t.length > 0 ? null : n.size === 1 ? [...n][0] ?? null : null;
271
274
  }
272
- function ke(e) {
275
+ function Ae(e) {
273
276
  return e.source === "identity_binding" && e.bindingAuthoritative && e.bindingStatus !== "active" && e.bindingStatus !== "removed";
274
277
  }
275
- function Ae(e) {
278
+ function je(e) {
276
279
  return e.flatMap((e) => e.rejoinedAtMs === null ? [] : [{
277
280
  deviceId: e.deviceId,
278
281
  rejoinedAtMs: e.rejoinedAtMs
279
282
  }]).toSorted((e, t) => t.rejoinedAtMs - e.rejoinedAtMs || e.deviceId.localeCompare(t.deviceId))[0] ?? null;
280
283
  }
281
- function je(e, t) {
284
+ function Me(e, t) {
282
285
  if (e.isLocal || [
283
286
  "retired",
284
287
  "service",
285
288
  "conflicted"
286
289
  ].includes(e.state)) return e;
287
- let n = Ae(t);
290
+ let n = je(t);
288
291
  return n ? {
289
292
  ...e,
290
293
  rejoin: n
291
294
  } : e;
292
295
  }
293
- function Me(e) {
296
+ function Ne(e) {
294
297
  return new Set(e.flatMap((e) => e.fingerprint && !e.fingerprintConflict ? [e.fingerprint] : []));
295
298
  }
296
- function Ne(e) {
297
- let t = [...new Set(e.map((e) => e.deviceId))].toSorted(), n = Me(e), r = e.filter((e) => e.source === "identity_binding" && e.bindingAuthoritative && e.bindingStatus === "active"), i = new Set(r.flatMap((e) => e.bindingIdentityId ? [e.bindingIdentityId] : [])), a = new Set(e.flatMap((e) => e.suggestedIdentityId ? [e.suggestedIdentityId] : [])), o = [
299
+ function Pe(e) {
300
+ let t = [...new Set(e.map((e) => e.deviceId))].toSorted(), n = Ne(e), r = e.filter((e) => e.source === "identity_binding" && e.bindingAuthoritative && e.bindingStatus === "active"), i = new Set(r.flatMap((e) => e.bindingIdentityId ? [e.bindingIdentityId] : [])), a = new Set(e.flatMap((e) => e.suggestedIdentityId ? [e.suggestedIdentityId] : [])), o = [
298
301
  e.some((e) => e.fingerprintConflict) ? "fingerprint_invalid" : null,
299
302
  n.size > 1 ? "fingerprint_conflict" : null,
300
303
  i.size > 1 ? "identity_binding_conflict" : null,
301
304
  e.some((e) => e.source === "identity_binding" && e.bindingAuthoritative && e.bindingStatus === "active" && e.bindingIdentityStatus !== "active") ? "identity_inactive" : null,
302
- e.some(ke) ? "identity_binding_revoked" : null,
305
+ e.some(Ae) ? "identity_binding_revoked" : null,
303
306
  e.some((e) => e.source === "coordinator_enrollment" && e.enrollmentEnabled === !1) ? "coordinator_enrollment_disabled" : null
304
- ].filter((e) => e != null), s = De(e, {
307
+ ].filter((e) => e != null), s = Oe(e, {
305
308
  conflicted: o.length > 0,
306
309
  activeBindings: r
307
- }), c = O.map((t) => Te(e, t)).find((e) => e != null), l = O.filter((t) => e.some((e) => e.source === t));
308
- return je({
310
+ }), c = k.map((t) => Te(e, t)).find((e) => e != null), l = k.filter((t) => e.some((e) => e.source === t));
311
+ return Me({
309
312
  version: 1,
310
313
  deviceId: c?.deviceId ?? t[0] ?? "",
311
314
  evidenceDeviceIds: t,
312
315
  displayName: Ee(e),
313
316
  state: s,
314
317
  identityId: s === "configured" && i.size === 1 ? [...i][0] ?? null : null,
315
- suggestedIdentityId: Oe(s, r, a),
318
+ suggestedIdentityId: ke(s, r, a),
316
319
  validatedFingerprint: n.size === 1 ? [...n][0] ?? null : null,
317
320
  isLocal: e.some((e) => e.isLocal),
318
321
  sources: l,
319
322
  conflictCodes: [...new Set(o)].toSorted()
320
323
  }, e);
321
324
  }
322
- function Pe(e, t = {}) {
323
- let n = Math.max(1, Math.min(t.limit ?? 500, 2e3)), r = we(Ce(e)).map(Ne).toSorted((e, t) => Number(t.isLocal) - Number(e.isLocal) || e.displayName.localeCompare(t.displayName) || e.deviceId.localeCompare(t.deviceId));
325
+ function Fe(e, t = {}) {
326
+ let n = Math.max(1, Math.min(t.limit ?? 500, 2e3)), r = we(Ce(e)).map(Pe).toSorted((e, t) => Number(t.isLocal) - Number(e.isLocal) || e.displayName.localeCompare(t.displayName) || e.deviceId.localeCompare(t.deviceId));
324
327
  return {
325
328
  version: 1,
326
329
  items: r.slice(0, n),
@@ -331,48 +334,48 @@ function Pe(e, t = {}) {
331
334
  truncated: e.localEvidenceTruncated === !0 || r.length > n
332
335
  };
333
336
  }
334
- function Fe(e) {
335
- let t = E(e.display_name) ?? "";
337
+ function Ie(e) {
338
+ let t = D(e.display_name) ?? "";
336
339
  return e.provenance === "coordinator_enrollment" && t === "Enrolled device" || ["managed_exact_project", "review_resolution"].includes(String(e.provenance)) && t === "Peer device" ? "" : t;
337
340
  }
338
- function Ie(e, t) {
341
+ function Le(e, t) {
339
342
  let n = String(e.device_id ?? "");
340
343
  return {
341
344
  deviceId: n,
342
- displayName: Fe(e),
345
+ displayName: Ie(e),
343
346
  identityId: String(e.identity_id ?? ""),
344
347
  status: String(e.status ?? ""),
345
- identityStatus: E(e.identity_status),
348
+ identityStatus: D(e.identity_status),
346
349
  retired: t(n)
347
350
  };
348
351
  }
349
- function Le(e, t) {
350
- return e.slice(0, 2001).map((e) => Ie(e, t)).filter((e) => e.status !== "removed" || e.retired);
351
- }
352
352
  function Re(e, t) {
353
- let n = he(e), r = new Map(t.map((e) => [e.deviceId, {
353
+ return e.slice(0, 2001).map((e) => Le(e, t)).filter((e) => e.status !== "removed" || e.retired);
354
+ }
355
+ function ze(e, t) {
356
+ let n = w(e), r = new Map(t.map((e) => [e.deviceId, {
354
357
  publicKey: e.publicKey,
355
358
  fingerprint: e.pinnedFingerprint
356
359
  }]));
357
- return (e) => w(n.get(e), r.get(e) ?? null);
360
+ return (e) => T(n.get(e), r.get(e) ?? null);
358
361
  }
359
- function ze(e, t) {
360
- let n = e.prepare("SELECT device_id, public_key, fingerprint FROM sync_device\n WHERE device_id = ? LIMIT 1").get(t.localDeviceId), r = e.prepare("SELECT peer_device_id, name, public_key, pinned_fingerprint, actor_id,\n trust_provenance, claimed_local_actor\n FROM sync_peers ORDER BY peer_device_id LIMIT ?").all(2001), i = r.slice(0, T).map((e) => {
362
+ function Be(e, t) {
363
+ let n = e.prepare("SELECT device_id, public_key, fingerprint FROM sync_device\n WHERE device_id = ? LIMIT 1").get(t.localDeviceId), r = e.prepare("SELECT peer_device_id, name, public_key, pinned_fingerprint, actor_id,\n trust_provenance, claimed_local_actor\n FROM sync_peers ORDER BY peer_device_id LIMIT ?").all(2001), i = r.slice(0, E).map((e) => {
361
364
  let t = e;
362
365
  return {
363
366
  deviceId: String(t.peer_device_id ?? ""),
364
- displayName: E(t.name) ?? "",
365
- publicKey: E(t.public_key),
366
- pinnedFingerprint: E(t.pinned_fingerprint),
367
- suggestedIdentityId: E(t.actor_id),
368
- trustProvenance: E(t.trust_provenance),
367
+ displayName: D(t.name) ?? "",
368
+ publicKey: D(t.public_key),
369
+ pinnedFingerprint: D(t.pinned_fingerprint),
370
+ suggestedIdentityId: D(t.actor_id),
371
+ trustProvenance: D(t.trust_provenance),
369
372
  claimedLocalActor: t.claimed_local_actor === 1
370
373
  };
371
- }), a = e.prepare("SELECT device.device_id, device.display_name, device.identity_id, device.status, device.provenance,\n actor.status AS identity_status\n FROM identity_devices device\n LEFT JOIN actors actor ON actor.actor_id = device.identity_id\n ORDER BY CASE\n WHEN device.device_id = ? THEN 0\n WHEN device.device_id IN (\n SELECT peer_device_id FROM sync_peers ORDER BY peer_device_id LIMIT ?\n ) THEN 1\n ELSE 2\n END, device.device_id LIMIT ?").all(t.localDeviceId, T, 2002), o = Re(e, i), s = Le(a, o);
374
+ }), a = e.prepare("SELECT device.device_id, device.display_name, device.identity_id, device.status, device.provenance,\n actor.status AS identity_status\n FROM identity_devices device\n LEFT JOIN actors actor ON actor.actor_id = device.identity_id\n ORDER BY CASE\n WHEN device.device_id = ? THEN 0\n WHEN device.device_id IN (\n SELECT peer_device_id FROM sync_peers ORDER BY peer_device_id LIMIT ?\n ) THEN 1\n ELSE 2\n END, device.device_id LIMIT ?").all(t.localDeviceId, E, 2002), o = ze(e, i), s = Re(a, o);
372
375
  return {
373
376
  localDevice: n ? {
374
377
  deviceId: n.device_id,
375
- displayName: E(t.localDisplayName) ?? "",
378
+ displayName: D(t.localDisplayName) ?? "",
376
379
  publicKey: n.public_key,
377
380
  fingerprint: n.fingerprint
378
381
  } : null,
@@ -382,18 +385,18 @@ function ze(e, t) {
382
385
  })),
383
386
  bindings: s,
384
387
  coordinator: t.coordinator,
385
- localEvidenceTruncated: r.length > T || a.length > 2001
388
+ localEvidenceTruncated: r.length > E || a.length > 2001
386
389
  };
387
390
  }
388
- function k(e, t, n = {}) {
389
- return Pe(ze(e, t), n);
391
+ function A(e, t, n = {}) {
392
+ return Fe(Be(e, t), n);
390
393
  }
391
394
  //#endregion
392
395
  //#region src/recipient-policy-actor-eligibility.ts
393
- function A(e) {
396
+ function Ve(e) {
394
397
  return e?.status === "active" && e.mergedIntoActorId === null;
395
398
  }
396
- function Be(e, t) {
399
+ function He(e, t) {
397
400
  let n = e.prepare("SELECT is_local, status, merged_into_actor_id FROM actors WHERE actor_id = ? LIMIT 1").get(t);
398
401
  return n ? {
399
402
  isLocal: n.is_local === 1,
@@ -402,36 +405,36 @@ function Be(e, t) {
402
405
  } : null;
403
406
  }
404
407
  function j(e, t) {
405
- return A(Be(e, t));
408
+ return Ve(He(e, t));
406
409
  }
407
410
  function M(e, t) {
408
- let n = Be(e, t);
409
- return n?.isLocal === !0 && A(n);
411
+ let n = He(e, t);
412
+ return n?.isLocal === !0 && Ve(n);
410
413
  }
411
- function Ve(e) {
414
+ function Ue(e) {
412
415
  return e.prepare("SELECT actor_id FROM actors WHERE status = 'active' AND merged_into_actor_id IS NULL ORDER BY actor_id").pluck().all();
413
416
  }
414
- function He(e, t) {
417
+ function We(e, t) {
415
418
  let n = [...new Set(t)];
416
419
  return n.length === 0 ? [] : e.prepare(`SELECT actor_id FROM actors
417
420
  WHERE actor_id IN (${n.map(() => "?").join(", ")})
418
421
  AND status = 'active' AND merged_into_actor_id IS NULL
419
422
  ORDER BY actor_id`).pluck().all(...n);
420
423
  }
421
- function Ue(e, t, n) {
424
+ function Ge(e, t, n) {
422
425
  return M(e, t) ? t : n !== t && M(e, n) ? n : e.prepare("SELECT actor_id FROM actors\n WHERE is_local = 1 AND status = 'active' AND merged_into_actor_id IS NULL\n ORDER BY actor_id LIMIT 1").pluck().get() ?? null;
423
426
  }
424
427
  //#endregion
425
428
  //#region src/device-identity-binding.ts
426
- var We = 1, Ge = 100, N = class extends Error {
429
+ var Ke = 1, qe = 100, N = class extends Error {
427
430
  status;
428
431
  errorCode;
429
432
  constructor(e, t) {
430
433
  super(t), this.status = e, this.errorCode = t;
431
434
  }
432
- }, Ke = u, P = d;
433
- function qe(e) {
434
- return Ke({ bindings: e.bindings.map((e) => ({
435
+ }, Je = d, P = f;
436
+ function Ye(e) {
437
+ return Je({ bindings: e.bindings.map((e) => ({
435
438
  deviceId: e.deviceId,
436
439
  targetIdentityId: e.targetIdentityId,
437
440
  confirmed: e.confirmed,
@@ -448,10 +451,10 @@ function F(e, t) {
448
451
  writeCount: 0
449
452
  };
450
453
  }
451
- function Je(e) {
454
+ function Xe(e) {
452
455
  return typeof e?.deviceId == "string" && e.deviceId.trim() === e.deviceId && e.deviceId.length > 0 && typeof e.targetIdentityId == "string" && e.targetIdentityId.trim() === e.targetIdentityId && e.targetIdentityId.length > 0 && e.confirmed === !0 && (e.allowRebind === void 0 || typeof e.allowRebind == "boolean");
453
456
  }
454
- function Ye(e, t, n) {
457
+ function Ze(e, t, n) {
455
458
  return e.state === "service" ? F("conflict", "device_service_role") : e.state === "retired" ? F("conflict", "device_retired") : e.state === "pairing_required" ? F("conflict", "device_pairing_required") : e.state === "conflicted" ? F("conflict", "device_evidence_conflict") : e.state === "configured" && e.identityId !== t.targetIdentityId ? t.allowRebind === !0 ? {
456
459
  deviceId: n,
457
460
  displayName: e.displayName,
@@ -468,7 +471,7 @@ function Ye(e, t, n) {
468
471
  isLocal: e.isLocal
469
472
  };
470
473
  }
471
- function Xe(e) {
474
+ function Qe(e) {
472
475
  return {
473
476
  deviceId: e.deviceId,
474
477
  evidenceDeviceIds: e.evidenceDeviceIds,
@@ -480,7 +483,7 @@ function Xe(e) {
480
483
  conflictCodes: e.conflictCodes
481
484
  };
482
485
  }
483
- function Ze(e, t) {
486
+ function $e(e, t) {
484
487
  let n = e.prepare("SELECT status, updated_at FROM identity_devices WHERE device_id = ? AND status = 'removed'");
485
488
  return [...new Set(t.flatMap((e) => e.evidenceDeviceIds))].toSorted().flatMap((e) => {
486
489
  let t = n.get(e);
@@ -491,21 +494,21 @@ function Ze(e, t) {
491
494
  }] : [];
492
495
  });
493
496
  }
494
- function Qe(e, t) {
495
- let n = Ze(e, t.selectedItems);
497
+ function et(e, t) {
498
+ let n = $e(e, t.selectedItems);
496
499
  return P("device-identity-binding-preview-v1", {
497
- selectedItems: t.selectedItems.map(Xe),
500
+ selectedItems: t.selectedItems.map(Qe),
498
501
  coordinatorAvailability: t.inventory.coordinatorEvidence.availability,
499
502
  inventoryTruncated: t.inventory.truncated,
500
- request: JSON.parse(qe(t.request)),
503
+ request: JSON.parse(Ye(t.request)),
501
504
  ...n.length > 0 ? { endedBindings: n } : {}
502
505
  });
503
506
  }
504
507
  function I(e, t, n) {
505
- if (!n || !Array.isArray(n.bindings) || n.bindings.length === 0 || n.bindings.length > Ge || n.bindings.some((e) => !Je(e))) return F("invalid", "binding_request_invalid");
508
+ if (!n || !Array.isArray(n.bindings) || n.bindings.length === 0 || n.bindings.length > qe || n.bindings.some((e) => !Xe(e))) return F("invalid", "binding_request_invalid");
506
509
  let r = n.bindings.map((e) => e.deviceId);
507
510
  if (new Set(r).size !== r.length) return F("invalid", "duplicate_device_id");
508
- let i = k(e, t);
511
+ let i = A(e, t);
509
512
  if (i.truncated) return F("conflict", "device_inventory_truncated");
510
513
  let a = new Map(i.items.map((e) => [e.deviceId, e])), o = [];
511
514
  for (let e of n.bindings) {
@@ -525,14 +528,14 @@ function I(e, t, n) {
525
528
  if (t.length !== 1) return F("conflict", "device_evidence_conflict");
526
529
  i = t[0] ?? n.deviceId;
527
530
  }
528
- let a = Ye(n, r, i);
531
+ let a = Ze(n, r, i);
529
532
  if ("status" in a) return a;
530
533
  s.push(a);
531
534
  }
532
535
  return {
533
536
  version: 1,
534
537
  status: "ready",
535
- reviewedInventoryDigest: Qe(e, {
538
+ reviewedInventoryDigest: et(e, {
536
539
  selectedItems: o,
537
540
  inventory: i,
538
541
  request: n
@@ -545,7 +548,7 @@ function I(e, t, n) {
545
548
  function L(e, t) {
546
549
  return e.prepare("SELECT identity_id, status, assignment_version FROM identity_devices\n WHERE device_id = ?").get(t);
547
550
  }
548
- function $e(e, t, n, r, i) {
551
+ function tt(e, t, n, r, i) {
549
552
  let a = e.prepare("SELECT request_json, outcomes_json, write_count\n FROM device_identity_binding_commits WHERE commit_digest = ?").get(n);
550
553
  if (!a) return null;
551
554
  if (a.request_json !== r) return {
@@ -591,21 +594,21 @@ function $e(e, t, n, r, i) {
591
594
  idempotent: !0
592
595
  };
593
596
  }
594
- function et(e, t) {
597
+ function nt(e, t) {
595
598
  if (!e.inTransaction) throw Error("binding_reactivation_transaction_required");
596
599
  let n = L(e, t.deviceId);
597
600
  if (n?.status !== "removed") return null;
598
- e.prepare("UPDATE identity_devices SET identity_id = ?, display_name = ?, status = 'active',\n provenance = ?, revision = ?, migration_state = ?, source_fingerprint = ?,\n idempotency_key = ?, updated_at = ?\n WHERE device_id = ? AND status = 'removed'").run(t.targetIdentityId, t.displayName, t.provenance, t.revision, t.migrationState, t.sourceFingerprint, t.idempotencyKey, t.now, t.deviceId), n.identity_id !== t.targetIdentityId && de(e, t.deviceId, t.now);
601
+ e.prepare("UPDATE identity_devices SET identity_id = ?, display_name = ?, status = 'active',\n provenance = ?, revision = ?, migration_state = ?, source_fingerprint = ?,\n idempotency_key = ?, updated_at = ?\n WHERE device_id = ? AND status = 'removed'").run(t.targetIdentityId, t.displayName, t.provenance, t.revision, t.migrationState, t.sourceFingerprint, t.idempotencyKey, t.now, t.deviceId), n.identity_id !== t.targetIdentityId && fe(e, t.deviceId, t.now);
599
602
  let r = L(e, t.deviceId)?.assignment_version ?? 0;
600
603
  return R(e, [n.identity_id, t.targetIdentityId], t.now), {
601
604
  assignmentVersion: r,
602
605
  previousIdentityId: n.identity_id
603
606
  };
604
607
  }
605
- function tt(e, t, n, r) {
608
+ function rt(e, t, n, r) {
606
609
  if (n && n.status !== "removed") throw new N("conflict", "binding_write_conflict");
607
610
  if (n) {
608
- if (!et(e, {
611
+ if (!nt(e, {
609
612
  deviceId: t.deviceId,
610
613
  targetIdentityId: t.targetIdentityId,
611
614
  displayName: t.displayName,
@@ -620,14 +623,14 @@ function tt(e, t, n, r) {
620
623
  }
621
624
  e.prepare("INSERT INTO identity_devices(\n device_id, identity_id, display_name, status, provenance, revision, migration_state,\n source_fingerprint, idempotency_key, created_at, updated_at\n ) VALUES (?, ?, ?, 'active', 'user_confirmed_identity_setup', ?, 'user_managed', ?, ?, ?, ?)").run(t.deviceId, t.targetIdentityId, t.displayName, r.revision, r.commitDigest, r.idempotencyKey, r.now, r.now);
622
625
  }
623
- function nt(e, t, n, r, i) {
626
+ function it(e, t, n, r, i) {
624
627
  let a = L(e, r.deviceId);
625
628
  if (r.action === "rebind" && (a?.status !== "active" || a.identity_id !== r.previousIdentityId)) throw new N("stale", "binding_rebind_stale");
626
629
  if (r.action === "unchanged" && (a?.status !== "active" || a.identity_id !== r.targetIdentityId)) throw new N("stale", "binding_unchanged_stale");
627
630
  let o = P("device-identity-binding-revision-v1", [n, r.deviceId]), s = P("device-identity-binding-row-v1", [n, r.deviceId]);
628
631
  if (r.action === "rebind") {
629
632
  if (e.prepare("UPDATE identity_devices SET identity_id = ?, status = 'active',\n provenance = 'user_confirmed_identity_setup', revision = ?, migration_state = 'user_managed',\n source_fingerprint = ?, idempotency_key = ?, updated_at = ?\n WHERE device_id = ? AND identity_id = ? AND status = 'active'").run(r.targetIdentityId, o, n, s, i, r.deviceId, r.previousIdentityId).changes !== 1) throw new N("stale", "binding_rebind_stale");
630
- } else r.action === "bind" && tt(e, r, a, {
633
+ } else r.action === "bind" && rt(e, r, a, {
631
634
  revision: o,
632
635
  commitDigest: n,
633
636
  idempotencyKey: s,
@@ -640,32 +643,32 @@ function nt(e, t, n, r, i) {
640
643
  function R(e, t, n) {
641
644
  let r = e.prepare("SELECT DISTINCT recipient.canonical_project_identity\n FROM project_recipients recipient\n WHERE recipient.status = 'active'\n AND (\n (recipient.recipient_kind = 'identity' AND recipient.recipient_id = ?)\n OR (recipient.recipient_kind = 'team' AND recipient.recipient_id IN (\n SELECT membership.team_id\n FROM policy_team_memberships membership\n JOIN policy_teams team ON team.team_id = membership.team_id\n WHERE membership.identity_id = ? AND team.status = 'active'\n AND (\n (team.device_eligibility_mode = 'person_all_devices' AND membership.status = 'active')\n OR (team.device_eligibility_mode = 'reviewed_allowlist'\n AND membership.status = 'reviewed_active')\n )\n ))\n )"), i = /* @__PURE__ */ new Set();
642
645
  for (let e of new Set(t)) for (let t of r.pluck().all(e, e)) i.add(t);
643
- rt(e, i, n);
646
+ at(e, i, n);
644
647
  }
645
- function rt(e, t, n) {
648
+ function at(e, t, n) {
646
649
  let r = [...t];
647
650
  if (r.length === 0) return;
648
- let i = ee(e), a = new Set(r.map((e) => h(i, e))), o = e.prepare("SELECT canonical_project_identity FROM recipient_policy_authority_states").pluck().all(), s = e.prepare("UPDATE recipient_policy_authority_states\n SET last_attempt_at = NULL, wake_epoch = wake_epoch + 1\n WHERE canonical_project_identity = ?");
651
+ let i = te(e), a = new Set(r.map((e) => g(i, e))), o = e.prepare("SELECT canonical_project_identity FROM recipient_policy_authority_states").pluck().all(), s = e.prepare("UPDATE recipient_policy_authority_states\n SET last_attempt_at = NULL, wake_epoch = wake_epoch + 1\n WHERE canonical_project_identity = ?");
649
652
  for (let e of o) {
650
- let t = h(i, e);
653
+ let t = g(i, e);
651
654
  a.has(t) && s.run(e);
652
655
  }
653
656
  }
654
- function it(e, t, n) {
657
+ function ot(e, t, n) {
655
658
  let r = /* @__PURE__ */ new Set();
656
659
  for (let e of t) e.action !== "unchanged" && (e.previousIdentityId && r.add(e.previousIdentityId), r.add(e.targetIdentityId));
657
660
  R(e, r, n);
658
661
  }
659
- function at(e, t, n, r) {
662
+ function st(e, t, n, r) {
660
663
  if (typeof r.reviewedInventoryDigest != "string" || !r.reviewedInventoryDigest) return {
661
664
  ...F("invalid", "reviewed_inventory_digest_required"),
662
665
  status: "invalid",
663
666
  idempotent: !1
664
667
  };
665
- let i = qe(r), a = P("device-identity-binding-commit-v1", {
668
+ let i = Ye(r), a = P("device-identity-binding-commit-v1", {
666
669
  request: JSON.parse(i),
667
670
  reviewedInventoryDigest: r.reviewedInventoryDigest
668
- }), o = $e(e, n, a, i, r);
671
+ }), o = tt(e, n, a, i, r);
669
672
  if (o) return o;
670
673
  let s = I(e, n, r);
671
674
  if (s.status !== "ready") return {
@@ -688,17 +691,17 @@ function at(e, t, n, r) {
688
691
  idempotent: !1
689
692
  };
690
693
  let c = (t.now ?? (() => (/* @__PURE__ */ new Date()).toISOString()))();
691
- e.prepare("INSERT INTO device_identity_binding_commits(\n commit_digest, reviewed_inventory_digest, request_json, outcomes_json, write_count,\n decided_by_identity_id, decided_by_device_id, created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(a, r.reviewedInventoryDigest, i, Ke(s.outcomes), s.writeCount, t.localActorId, t.localDeviceId, c);
692
- for (let n of s.outcomes) nt(e, t, a, n, c);
693
- return it(e, s.outcomes, c), {
694
+ e.prepare("INSERT INTO device_identity_binding_commits(\n commit_digest, reviewed_inventory_digest, request_json, outcomes_json, write_count,\n decided_by_identity_id, decided_by_device_id, created_at\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)").run(a, r.reviewedInventoryDigest, i, Je(s.outcomes), s.writeCount, t.localActorId, t.localDeviceId, c);
695
+ for (let n of s.outcomes) it(e, t, a, n, c);
696
+ return ot(e, s.outcomes, c), {
694
697
  ...s,
695
698
  status: "applied",
696
699
  idempotent: !1
697
700
  };
698
701
  }
699
- function ot(e, t, n, r) {
702
+ function ct(e, t, n, r) {
700
703
  try {
701
- return e.transaction(() => at(e, t, n, r)).immediate();
704
+ return e.transaction(() => st(e, t, n, r)).immediate();
702
705
  } catch (e) {
703
706
  if (e instanceof N) return {
704
707
  version: 1,
@@ -720,45 +723,45 @@ function ot(e, t, n, r) {
720
723
  }
721
724
  //#endregion
722
725
  //#region src/coordinator-peer-revocation.ts
723
- var st = 25, ct = class extends Error {
726
+ var lt = 25, ut = class extends Error {
724
727
  status;
725
728
  constructor(e) {
726
729
  super(`peer revocation check failed (${e})`), this.status = e;
727
730
  }
728
731
  };
729
- function lt(e) {
732
+ function dt(e) {
730
733
  if (typeof e == "string" && e.trim() !== "") return e.length <= 4096 && !e.includes("\0") ? e : void 0;
731
734
  }
732
- function ut(e, t) {
733
- let n = lt(t);
735
+ function ft(e, t) {
736
+ let n = dt(t);
734
737
  return n === void 0 ? { device_id: e } : {
735
738
  device_id: e,
736
739
  public_key: n
737
740
  };
738
741
  }
739
- function dt(e, t) {
740
- let n = e.prepare("SELECT peer_device_id, public_key FROM sync_peers\n WHERE peer_device_id IS NOT ? ORDER BY peer_device_id").all(t), r = new Map(n.map((e) => [e.peer_device_id, e.public_key])), i = e.prepare("SELECT device_id FROM identity_devices\n WHERE status = 'active' AND device_id IS NOT ? ORDER BY device_id").pluck().all(t), a = [...r.keys(), ...i.filter((e) => !r.has(e))], o = a.filter((e) => s(e)).map((e) => ut(e, r.get(e)));
742
+ function pt(e, t) {
743
+ let n = e.prepare("SELECT peer_device_id, public_key FROM sync_peers\n WHERE peer_device_id IS NOT ? ORDER BY peer_device_id").all(t), r = new Map(n.map((e) => [e.peer_device_id, e.public_key])), i = e.prepare("SELECT device_id FROM identity_devices\n WHERE status = 'active' AND device_id IS NOT ? ORDER BY device_id").pluck().all(t), a = [...r.keys(), ...i.filter((e) => !r.has(e))], o = a.filter((e) => c(e)).map((e) => ft(e, r.get(e)));
741
744
  return {
742
745
  entries: o,
743
746
  omitted: o.length !== a.length
744
747
  };
745
748
  }
746
- function z(e, t) {
749
+ function mt(e, t) {
747
750
  return e.filter((e) => typeof e == "string" && t.has(e));
748
751
  }
749
- function ft(e, t) {
752
+ function ht(e, t) {
750
753
  let { version: n, revoked: r, removed: i, enrolled: a, removal_seq: o } = e ?? {};
751
754
  if (n !== 1 || !Array.isArray(r) || !Array.isArray(i) || !Array.isArray(a) || !Number.isSafeInteger(o) || o < 0) throw Error("peer_revocation_response_invalid");
752
- let s = new Set(t.map((e) => e.device_id)), c = z(r, s);
755
+ let s = new Set(t.map((e) => e.device_id)), c = mt(r, s);
753
756
  return {
754
757
  revoked: c,
755
- removed: z(i, s).filter((e) => !c.includes(e)),
756
- enrolled: z(a, s),
758
+ removed: mt(i, s).filter((e) => !c.includes(e)),
759
+ enrolled: mt(a, s),
757
760
  removalSeq: o
758
761
  };
759
762
  }
760
- async function pt(e, t, n, r) {
761
- let i = { peers: r }, a = Buffer.from(JSON.stringify(i), "utf8"), o = `${p(t.syncCoordinatorUrl)}/v1/peers/revocations?group_id=${encodeURIComponent(n.groupId)}`, s = m({
763
+ async function gt(e, t, n, r) {
764
+ let i = { peers: r }, a = Buffer.from(JSON.stringify(i), "utf8"), o = `${m(t.syncCoordinatorUrl)}/v1/peers/revocations?group_id=${encodeURIComponent(n.groupId)}`, s = h({
762
765
  deviceId: n.localDeviceId,
763
766
  dbPath: e.dbPath,
764
767
  method: "POST",
@@ -771,37 +774,37 @@ async function pt(e, t, n, r) {
771
774
  bodyBytes: a,
772
775
  timeoutS: Math.max(1, t.syncCoordinatorTimeoutS)
773
776
  });
774
- if (c === 403 && l?.error === "device_removed" && n.removedFromGroups?.push(n.groupId), c !== 200) throw new ct(c);
775
- return ft(l, r);
777
+ if (c === 403 && l?.error === "device_removed" && n.removedFromGroups?.push(n.groupId), c !== 200) throw new ut(c);
778
+ return ht(l, r);
776
779
  }
777
- function mt(e) {
778
- return e instanceof ct ? e.status === 404 ? "unsupported" : e.status !== 401 && e.status !== 403 && e.status !== 409 ? "failed" : "refused" : "failed";
780
+ function _t(e) {
781
+ return e instanceof ut ? e.status === 404 ? "unsupported" : e.status !== 401 && e.status !== 403 && e.status !== 409 ? "failed" : "refused" : "failed";
779
782
  }
780
- async function ht(e, t, n, r, i) {
783
+ async function vt(e, t, n, r, i) {
781
784
  for (let a of t.syncCoordinatorGroups) try {
782
785
  return {
783
786
  kind: "answered",
784
787
  groupId: a,
785
- reply: await pt(e, t, {
788
+ reply: await gt(e, t, {
786
789
  ...n,
787
790
  groupId: a,
788
791
  removedFromGroups: i
789
792
  }, r)
790
793
  };
791
794
  } catch (e) {
792
- let t = mt(e);
795
+ let t = _t(e);
793
796
  if (t === "failed") throw e;
794
797
  if (t === "unsupported") return { kind: "unsupported" };
795
798
  }
796
799
  return { kind: "refused" };
797
800
  }
798
- function gt(e) {
801
+ function yt(e) {
799
802
  if (e.length === 0) return [[]];
800
803
  let t = [];
801
- for (let n = 0; n < e.length; n += st) t.push(e.slice(n, n + st));
804
+ for (let n = 0; n < e.length; n += lt) t.push(e.slice(n, n + lt));
802
805
  return t;
803
806
  }
804
- function B(e, t, n = []) {
807
+ function z(e, t, n = []) {
805
808
  return {
806
809
  status: e,
807
810
  revoked: [],
@@ -812,21 +815,21 @@ function B(e, t, n = []) {
812
815
  removedFromGroups: n
813
816
  };
814
817
  }
815
- async function _t(e, t, n) {
818
+ async function bt(e, t, n) {
816
819
  let { entries: i, omitted: a, generation: o } = e.db.transaction(() => ({
817
- ...dt(e.db, n.localDeviceId),
820
+ ...pt(e.db, n.localDeviceId),
818
821
  generation: r(e.db)?.generation ?? null
819
822
  }))(), s = [];
820
823
  try {
821
- let [r = [], ...c] = gt(i), l = await ht(e, t, n, r, s);
822
- if (l.kind === "unsupported") return B("unsupported", o, s);
823
- if (l.kind === "refused") return B("failed", o, s);
824
+ let [r = [], ...c] = yt(i), l = await vt(e, t, n, r, s);
825
+ if (l.kind === "unsupported") return z("unsupported", o, s);
826
+ if (l.kind === "refused") return z("failed", o, s);
824
827
  let u = [l.reply], d = {
825
828
  ...n,
826
829
  groupId: l.groupId,
827
830
  removedFromGroups: s
828
831
  };
829
- for (let n of c) u.push(await pt(e, t, d, n));
832
+ for (let n of c) u.push(await gt(e, t, d, n));
830
833
  return {
831
834
  status: "checked",
832
835
  revoked: u.flatMap((e) => e.revoked),
@@ -837,15 +840,15 @@ async function _t(e, t, n) {
837
840
  removedFromGroups: []
838
841
  };
839
842
  } catch {
840
- return B("failed", o, s);
843
+ return z("failed", o, s);
841
844
  }
842
845
  }
843
- async function vt(e, t, n) {
844
- let r = n.publicKey !== void 0 && lt(n.publicKey) === void 0;
845
- if (!s(n.deviceId) || r) return { answered: !1 };
846
- let i = ut(n.deviceId, n.publicKey);
846
+ async function xt(e, t, n) {
847
+ let r = n.publicKey !== void 0 && dt(n.publicKey) === void 0;
848
+ if (!c(n.deviceId) || r) return { answered: !1 };
849
+ let i = ft(n.deviceId, n.publicKey);
847
850
  try {
848
- let r = await ht(e, t, n, [i]);
851
+ let r = await vt(e, t, n, [i]);
849
852
  return r.kind === "answered" ? {
850
853
  answered: !0,
851
854
  enrolled: r.reply.enrolled.includes(n.deviceId),
@@ -858,31 +861,31 @@ async function vt(e, t, n) {
858
861
  }
859
862
  //#endregion
860
863
  //#region src/coordinator-removal-notice.ts
861
- var V = "sync_coordinator_device_removed";
862
- function yt(e) {
863
- return e.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?").get(V) !== void 0;
864
+ var B = "sync_coordinator_device_removed";
865
+ function St(e) {
866
+ return e.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?").get(B) !== void 0;
864
867
  }
865
- function bt(e, t) {
868
+ function Ct(e, t) {
866
869
  t.groupIds.length !== 0 && e.transaction(() => {
867
- e.exec(`CREATE TABLE IF NOT EXISTS ${V} (
870
+ e.exec(`CREATE TABLE IF NOT EXISTS ${B} (
868
871
  coordinator_id TEXT NOT NULL,
869
872
  group_id TEXT NOT NULL,
870
873
  noticed_at TEXT NOT NULL,
871
874
  PRIMARY KEY (coordinator_id, group_id)
872
875
  )`);
873
- let n = e.prepare(`INSERT OR IGNORE INTO ${V}(coordinator_id, group_id, noticed_at) VALUES (?, ?, ?)`), r = t.now ?? (/* @__PURE__ */ new Date()).toISOString();
876
+ let n = e.prepare(`INSERT OR IGNORE INTO ${B}(coordinator_id, group_id, noticed_at) VALUES (?, ?, ?)`), r = t.now ?? (/* @__PURE__ */ new Date()).toISOString();
874
877
  for (let e of t.groupIds) n.run(t.coordinatorId, e, r);
875
878
  }).immediate();
876
879
  }
877
- function xt(e, t) {
878
- yt(e) && e.prepare(`DELETE FROM ${V} WHERE coordinator_id = ?`).run(t);
880
+ function wt(e, t) {
881
+ St(e) && e.prepare(`DELETE FROM ${B} WHERE coordinator_id = ?`).run(t);
879
882
  }
880
- function St(e, t) {
881
- if (!yt(e)) return {
883
+ function Tt(e, t) {
884
+ if (!St(e)) return {
882
885
  removed: !1,
883
886
  removedFromGroups: []
884
887
  };
885
- let n = new Set(e.prepare(`SELECT group_id FROM ${V} WHERE coordinator_id = ?`).pluck().all(t.coordinatorId)), r = t.groupIds.filter((e) => n.has(e));
888
+ let n = new Set(e.prepare(`SELECT group_id FROM ${B} WHERE coordinator_id = ?`).pluck().all(t.coordinatorId)), r = t.groupIds.filter((e) => n.has(e));
886
889
  return {
887
890
  removed: t.groupIds.length > 0 && r.length === t.groupIds.length,
888
891
  removedFromGroups: r
@@ -890,77 +893,78 @@ function St(e, t) {
890
893
  }
891
894
  //#endregion
892
895
  //#region src/memory-retirement-trust.ts
893
- function Ct(e) {
894
- return !!(e?.public_key && e.pinned_fingerprint && o(e.public_key) === e.pinned_fingerprint);
896
+ function Et(e) {
897
+ return !!(e?.public_key && e.pinned_fingerprint && s(e.public_key) === e.pinned_fingerprint);
895
898
  }
896
- function H(e, t) {
899
+ function V(e, t) {
897
900
  if (!e.inTransaction) throw Error("retirement_trust_transaction_required");
898
901
  let n = e.prepare("SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?").get(t.peerDeviceId);
899
- Ct(n) && e.prepare("INSERT OR IGNORE INTO memory_retirement_peer_trust\n (local_device_id, peer_device_id, public_key, pinned_fingerprint) VALUES (?, ?, ?, ?)").run(t.localDeviceId, t.peerDeviceId, n.public_key, n.pinned_fingerprint);
902
+ Et(n) && e.prepare("INSERT OR IGNORE INTO memory_retirement_peer_trust\n (local_device_id, peer_device_id, public_key, pinned_fingerprint) VALUES (?, ?, ?, ?)").run(t.localDeviceId, t.peerDeviceId, n.public_key, n.pinned_fingerprint);
900
903
  }
901
904
  //#endregion
902
905
  //#region src/pairing-removal.ts
903
- function wt(e, t) {
906
+ function Dt(e, t) {
904
907
  let n = e.prepare("SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?").get(t);
905
- return !n?.public_key || !n.pinned_fingerprint || o(n.public_key) !== n.pinned_fingerprint ? [] : [{
908
+ return !n?.public_key || !n.pinned_fingerprint || s(n.public_key) !== n.pinned_fingerprint ? [] : [{
906
909
  deviceId: t,
907
910
  kind: "key",
908
911
  fingerprint: n.pinned_fingerprint,
909
912
  keyId: C(n.public_key)
910
913
  }];
911
914
  }
912
- function Tt(e, t) {
915
+ function Ot(e, t) {
913
916
  return e.prepare("DELETE FROM sync_peers WHERE peer_device_id = ?").run(t).changes;
914
917
  }
915
- function Et(e, t) {
918
+ function kt(e, t) {
916
919
  return e.prepare("DELETE FROM sync_peers\n WHERE peer_device_id = ? AND claimed_local_actor = 0\n AND actor_id IS NULL AND pending_bootstrap_grant_id IS NULL\n AND trust_provenance = 'coordinator_policy'\n AND discovered_via_coordinator_id = ? AND discovered_via_group_id = ?").run(t.deviceId, t.coordinatorId, t.groupId).changes;
917
920
  }
918
- function Dt(e, n) {
921
+ function At(t, n) {
919
922
  return {
920
- replicationCursors: e.prepare("DELETE FROM replication_cursors WHERE peer_device_id = ?").run(n).changes,
921
- replicationCursorsV2: e.prepare("DELETE FROM replication_cursors_v2 WHERE peer_device_id = ?").run(n).changes,
922
- syncChannelProgress: t(e, n)
923
+ replicationCursors: t.prepare("DELETE FROM replication_cursors WHERE peer_device_id = ?").run(n).changes,
924
+ replicationCursorsV2: t.prepare("DELETE FROM replication_cursors_v2 WHERE peer_device_id = ?").run(n).changes,
925
+ syncChannelProgress: e(t, n)
923
926
  };
924
927
  }
925
- function Ot(e, t, n) {
928
+ function jt(e, t, n) {
926
929
  return e.prepare("UPDATE identity_devices SET status = 'removed', updated_at = ?\n WHERE device_id = ? AND status = 'active' RETURNING identity_id").get(n, t)?.identity_id ?? null;
927
930
  }
928
- function kt(e, t) {
931
+ function Mt(e, t) {
929
932
  e.syncPeers += t.syncPeers, e.replicationCursors += t.replicationCursors, e.replicationCursorsV2 += t.replicationCursorsV2, e.syncChannelProgress += t.syncChannelProgress;
930
933
  }
931
- function At(e, t, n) {
932
- let r = Mt();
934
+ function Nt(e, t, n) {
935
+ let r = Ft();
933
936
  for (let i of n) {
934
- H(e, {
937
+ V(e, {
935
938
  localDeviceId: t,
936
939
  peerDeviceId: i.deviceId
937
940
  });
938
- let n = Et(e, i);
939
- n !== 0 && kt(r, {
941
+ let n = kt(e, i);
942
+ n !== 0 && Mt(r, {
940
943
  syncPeers: n,
941
- ...Dt(e, i.deviceId)
944
+ ...At(e, i.deviceId)
942
945
  });
943
946
  }
944
947
  return r;
945
948
  }
946
- function jt(e, t) {
947
- let n = Mt(), r = [...new Set(t.deviceIds)];
948
- t.reason === "revoked" && ge(e, t.retiredAliases ?? r.flatMap((t) => wt(e, t)));
949
- let i = (/* @__PURE__ */ new Date()).toISOString(), a = /* @__PURE__ */ new Set();
950
- for (let o of r) {
951
- if (H(e, {
952
- localDeviceId: t.localDeviceId,
953
- peerDeviceId: o
954
- }), kt(n, {
955
- syncPeers: Tt(e, o),
956
- ...Dt(e, o)
957
- }), t.reason === "disconnect" || o === t.localDeviceId) continue;
958
- let r = Ot(e, o, i);
959
- r && (n.identityDevices += 1, a.add(r));
949
+ function Pt(e, n) {
950
+ let r = Ft(), i = [...new Set(n.deviceIds)];
951
+ n.reason === "revoked" && ge(e, n.retiredAliases ?? i.flatMap((t) => Dt(e, t)));
952
+ let a = (/* @__PURE__ */ new Date()).toISOString(), o = /* @__PURE__ */ new Set();
953
+ n.reason !== "disconnect" && t(e, i.filter((e) => e !== n.localDeviceId));
954
+ for (let t of i) {
955
+ if (V(e, {
956
+ localDeviceId: n.localDeviceId,
957
+ peerDeviceId: t
958
+ }), Mt(r, {
959
+ syncPeers: Ot(e, t),
960
+ ...At(e, t)
961
+ }), n.reason === "disconnect" || t === n.localDeviceId) continue;
962
+ let i = jt(e, t, a);
963
+ i && (r.identityDevices += 1, o.add(i));
960
964
  }
961
- return a.size === 0 || R(e, a, i), n;
965
+ return o.size === 0 || R(e, o, a), r;
962
966
  }
963
- function Mt() {
967
+ function Ft() {
964
968
  return {
965
969
  syncPeers: 0,
966
970
  replicationCursors: 0,
@@ -969,18 +973,18 @@ function Mt() {
969
973
  identityDevices: 0
970
974
  };
971
975
  }
972
- function U(e, t) {
973
- return e.transaction(() => t.reason === "policy" ? At(e, t.localDeviceId, t.pairings) : jt(e, t)).immediate();
976
+ function H(e, t) {
977
+ return e.transaction(() => t.reason === "policy" ? Nt(e, t.localDeviceId, t.pairings) : Pt(e, t)).immediate();
974
978
  }
975
979
  //#endregion
976
980
  //#region src/device-retirement.ts
977
- var Nt = /* @__PURE__ */ new Set(["fingerprint_conflict", "fingerprint_invalid"]);
978
- function Pt(e, t) {
981
+ var It = /* @__PURE__ */ new Set(["fingerprint_conflict", "fingerprint_invalid"]);
982
+ function Lt(e, t) {
979
983
  let n = e.prepare("SELECT device_id, public_key, fingerprint FROM sync_device").all(), [r] = n;
980
- return n.length !== 1 || !r || r.device_id !== t || !r.public_key || r.fingerprint !== o(r.public_key) ? null : C(r.public_key);
984
+ return n.length !== 1 || !r || r.device_id !== t || !r.public_key || r.fingerprint !== s(r.public_key) ? null : C(r.public_key);
981
985
  }
982
- function Ft(e, t) {
983
- let n = k(e, {
986
+ function Rt(e, t) {
987
+ let n = A(e, {
984
988
  localDeviceId: t.localDeviceId,
985
989
  coordinator: {
986
990
  availability: "available",
@@ -990,42 +994,42 @@ function Ft(e, t) {
990
994
  }, { limit: 2e3 });
991
995
  return n.truncated ? "device_evidence_incomplete" : n.items.find((e) => e.evidenceDeviceIds.includes(t.deviceId)) ?? "device_not_enrolled";
992
996
  }
993
- function It(e) {
994
- return e.isLocal ? "cannot_retire_this_device" : e.state === "retired" ? "device_already_retired" : e.conflictCodes.some((e) => Nt.has(e)) || !e.validatedFingerprint ? "device_enrollment_conflict" : null;
997
+ function zt(e) {
998
+ return e.isLocal ? "cannot_retire_this_device" : e.state === "retired" ? "device_already_retired" : e.conflictCodes.some((e) => It.has(e)) || !e.validatedFingerprint ? "device_enrollment_conflict" : null;
995
999
  }
996
- function Lt(e) {
1000
+ function Bt(e) {
997
1001
  return e.prepare("SELECT peer_device_id, public_key, pinned_fingerprint FROM sync_peers WHERE public_key IS NOT NULL").all().map((e) => ({
998
1002
  deviceId: e.peer_device_id,
999
1003
  publicKey: e.public_key,
1000
1004
  fingerprint: e.pinned_fingerprint?.trim() || null
1001
1005
  }));
1002
1006
  }
1003
- function Rt(e, t, n, r) {
1007
+ function Vt(e, t, n, r) {
1004
1008
  return [...t.enrollments.map((e) => ({
1005
1009
  deviceId: e.device_id,
1006
1010
  publicKey: e.public_key
1007
- })), ...Lt(e)].filter((e) => !n.has(e.deviceId)).some((e) => C(e.publicKey) === r);
1011
+ })), ...Bt(e)].filter((e) => !n.has(e.deviceId)).some((e) => C(e.publicKey) === r);
1008
1012
  }
1009
- function zt(e, t) {
1010
- let n = he(e), r = new Map(Lt(e).map((e) => [e.deviceId, e]));
1011
- return t.some((e) => w(n.get(e), r.get(e) ?? null));
1013
+ function Ht(e, t) {
1014
+ let n = w(e), r = new Map(Bt(e).map((e) => [e.deviceId, e]));
1015
+ return t.some((e) => T(n.get(e), r.get(e) ?? null));
1012
1016
  }
1013
- function Bt(e, t, n) {
1017
+ function Ut(e, t, n) {
1014
1018
  return e.enrollments.filter((e) => t.evidenceDeviceIds.includes(e.device_id) && e.fingerprint === n).toSorted((e, t) => e.group_id.localeCompare(t.group_id) || e.device_id.localeCompare(t.device_id))[0];
1015
1019
  }
1016
- function Vt(e, t) {
1017
- let n = Pt(e, t.localDeviceId);
1020
+ function Wt(e, t) {
1021
+ let n = Lt(e, t.localDeviceId);
1018
1022
  if (!n) return "local_identity_unverified";
1019
1023
  if (t.deviceId === t.localDeviceId) return "cannot_retire_this_device";
1020
- let r = Ft(e, t);
1024
+ let r = Rt(e, t);
1021
1025
  if (typeof r == "string") return r;
1022
- let i = It(r);
1026
+ let i = zt(r);
1023
1027
  if (i) return i;
1024
- if (zt(e, r.evidenceDeviceIds)) return "device_already_retired";
1025
- let a = r.validatedFingerprint, o = Bt(t, r, a);
1028
+ if (Ht(e, r.evidenceDeviceIds)) return "device_already_retired";
1029
+ let a = r.validatedFingerprint, o = Ut(t, r, a);
1026
1030
  if (!o) return "device_not_enrolled";
1027
1031
  let s = C(o.public_key);
1028
- return s ? s === n ? "cannot_retire_this_device" : Rt(e, t, new Set(r.evidenceDeviceIds), s) ? "device_enrollment_conflict" : {
1032
+ return s ? s === n ? "cannot_retire_this_device" : Vt(e, t, new Set(r.evidenceDeviceIds), s) ? "device_enrollment_conflict" : {
1029
1033
  aliasDeviceIds: r.evidenceDeviceIds.filter((e) => e !== t.localDeviceId),
1030
1034
  displayName: r.displayName,
1031
1035
  fingerprint: a,
@@ -1034,17 +1038,17 @@ function Vt(e, t) {
1034
1038
  enrollmentDeviceId: o.device_id
1035
1039
  } : "device_key_unrecognized";
1036
1040
  }
1037
- function Ht(e, t, n) {
1041
+ function Gt(e, t, n) {
1038
1042
  let r = n.filter((e) => e !== t);
1039
- return r.length === 0 ? 0 : U(e, {
1043
+ return r.length === 0 ? 0 : H(e, {
1040
1044
  localDeviceId: t,
1041
1045
  reason: "revoked",
1042
1046
  deviceIds: r
1043
1047
  }).syncPeers;
1044
1048
  }
1045
- function Ut(e, t, n) {
1049
+ function Kt(e, t, n) {
1046
1050
  let r = e.prepare("SELECT public_key, pinned_fingerprint FROM sync_peers WHERE peer_device_id = ?").get(t);
1047
- return !r || w({
1051
+ return !r || T({
1048
1052
  kind: "key",
1049
1053
  fingerprint: n.fingerprint,
1050
1054
  keyId: n.keyId
@@ -1053,10 +1057,10 @@ function Ut(e, t, n) {
1053
1057
  fingerprint: r.pinned_fingerprint
1054
1058
  });
1055
1059
  }
1056
- function Wt(e, t, n) {
1060
+ function qt(e, t, n) {
1057
1061
  return e.transaction(() => {
1058
- let r = n.aliasDeviceIds.filter((r) => r !== t && (r === n.enrollmentDeviceId || Ut(e, r, n)));
1059
- return U(e, {
1062
+ let r = n.aliasDeviceIds.filter((r) => r !== t && (r === n.enrollmentDeviceId || Kt(e, r, n)));
1063
+ return H(e, {
1060
1064
  localDeviceId: t,
1061
1065
  reason: "revoked",
1062
1066
  deviceIds: r,
@@ -1071,10 +1075,10 @@ function Wt(e, t, n) {
1071
1075
  }
1072
1076
  //#endregion
1073
1077
  //#region src/coordinator-runtime.ts
1074
- function W(e) {
1078
+ function U(e) {
1075
1079
  return typeof e == "string" ? e.trim() : "";
1076
1080
  }
1077
- function Gt(e, t) {
1081
+ function Jt(e, t) {
1078
1082
  let n = [], r = /* @__PURE__ */ new Set();
1079
1083
  for (let i of [...e, ...t]) {
1080
1084
  let e = i.trim();
@@ -1082,16 +1086,16 @@ function Gt(e, t) {
1082
1086
  }
1083
1087
  return n;
1084
1088
  }
1085
- function Kt(e, t) {
1086
- let n = Date.parse(W(e)), r = Date.parse(W(t));
1089
+ function Yt(e, t) {
1090
+ let n = Date.parse(U(e)), r = Date.parse(U(t));
1087
1091
  return Number.isFinite(n) ? Number.isFinite(r) && r < n ? t : e : Number.isFinite(r) ? t : e;
1088
1092
  }
1089
- var G = /* @__PURE__ */ new Map(), K = /* @__PURE__ */ new Map(), q = /* @__PURE__ */ new Map(), qt = 3e4;
1090
- function Jt(e, t) {
1091
- let n = e + qt;
1093
+ var W = /* @__PURE__ */ new Map(), G = /* @__PURE__ */ new Map(), K = /* @__PURE__ */ new Map(), Xt = 3e4;
1094
+ function Zt(e, t) {
1095
+ let n = e + Xt;
1092
1096
  for (let r of t) {
1093
1097
  if (r.stale) continue;
1094
- let t = Date.parse(W(r.expires_at));
1098
+ let t = Date.parse(U(r.expires_at));
1095
1099
  if (Number.isFinite(t)) {
1096
1100
  if (t <= e) return e;
1097
1101
  n = Math.min(n, t);
@@ -1099,23 +1103,23 @@ function Jt(e, t) {
1099
1103
  }
1100
1104
  return n;
1101
1105
  }
1102
- function J(e) {
1103
- K.delete(e), q.set(e, (q.get(e) ?? 0) + 1);
1106
+ function q(e) {
1107
+ G.delete(e), K.set(e, (K.get(e) ?? 0) + 1);
1104
1108
  }
1105
- function Yt(e, t) {
1109
+ function Qt(e, t) {
1106
1110
  let n = [...t.syncCoordinatorGroups].sort().join(",");
1107
1111
  return [
1108
1112
  e.dbPath,
1109
1113
  t.syncCoordinatorUrl,
1110
1114
  n,
1111
- Xt(e),
1115
+ $t(e),
1112
1116
  t.syncHost,
1113
1117
  t.syncPort,
1114
1118
  t.syncAdvertise,
1115
1119
  t.syncCoordinatorPresenceTtlS
1116
1120
  ].join("|");
1117
1121
  }
1118
- function Xt(e) {
1122
+ function $t(e) {
1119
1123
  let t = process.env.CODEMEM_KEYS_DIR?.trim() || "";
1120
1124
  try {
1121
1125
  let n = e.db.prepare("SELECT device_id, fingerprint FROM sync_device LIMIT 1").get();
@@ -1124,9 +1128,9 @@ function Xt(e) {
1124
1128
  return t;
1125
1129
  }
1126
1130
  }
1127
- function Y(e, t) {
1131
+ function J(e, t) {
1128
1132
  return [
1129
- Yt(e, t),
1133
+ Qt(e, t),
1130
1134
  t.syncEnabled ? "sync-enabled" : "sync-disabled",
1131
1135
  t.syncHost,
1132
1136
  t.syncPort,
@@ -1134,33 +1138,33 @@ function Y(e, t) {
1134
1138
  t.syncCoordinatorPresenceTtlS
1135
1139
  ].join("|");
1136
1140
  }
1137
- function Zt(e) {
1141
+ function Y(e) {
1138
1142
  return Number(e.db.prepare("SELECT COUNT(1) AS total FROM sync_peers").get()?.total ?? 0);
1139
1143
  }
1140
- function Qt(e) {
1144
+ function en(e) {
1141
1145
  let t = Math.max(1, e.syncCoordinatorPresenceTtlS), n = Math.floor(t / 2);
1142
1146
  return Math.max(5, Math.min(60, n > 0 ? n : 1)) * 1e3;
1143
1147
  }
1144
- function $t() {
1148
+ function tn() {
1145
1149
  return 3e4;
1146
1150
  }
1147
- async function en(e, t, n, r) {
1148
- let i = Yt(e, t), a = G.get(i);
1151
+ async function nn(e, t, n, r) {
1152
+ let i = Qt(e, t), a = W.get(i);
1149
1153
  if (a && r < a.nextRefreshAtMs) {
1150
1154
  n.presence_status = a.status, n.presence_error = a.error, n.advertised_addresses = a.advertisedAddresses;
1151
1155
  return;
1152
1156
  }
1153
1157
  try {
1154
- let a = (await nn(e, t))?.responses?.[0], o = a && typeof a == "object" ? a.addresses ?? [] : [];
1155
- n.presence_status = "posted", n.presence_error = null, n.advertised_addresses = o, G.set(i, {
1158
+ let a = (await an(e, t))?.responses?.[0], o = a && typeof a == "object" ? a.addresses ?? [] : [];
1159
+ n.presence_status = "posted", n.presence_error = null, n.advertised_addresses = o, W.set(i, {
1156
1160
  status: "posted",
1157
1161
  error: null,
1158
1162
  advertisedAddresses: o,
1159
- nextRefreshAtMs: r + Qt(t)
1163
+ nextRefreshAtMs: r + en(t)
1160
1164
  });
1161
1165
  } catch (e) {
1162
- let t = e instanceof Error ? e.message : String(e), a = t.includes("unknown_device") ? "not_enrolled" : "error", o = a === "not_enrolled" ? r : r + $t();
1163
- n.presence_status = a, n.presence_error = t, n.advertised_addresses = [], G.set(i, {
1166
+ let t = e instanceof Error ? e.message : String(e), a = t.includes("unknown_device") ? "not_enrolled" : "error", o = a === "not_enrolled" ? r : r + tn();
1167
+ n.presence_status = a, n.presence_error = t, n.advertised_addresses = [], W.set(i, {
1164
1168
  status: a,
1165
1169
  error: t,
1166
1170
  advertisedAddresses: [],
@@ -1168,42 +1172,42 @@ async function en(e, t, n, r) {
1168
1172
  });
1169
1173
  }
1170
1174
  }
1171
- function tn(e) {
1175
+ function rn(e) {
1172
1176
  let t = e.syncAdvertise.toLowerCase();
1173
1177
  if (t && t !== "auto" && t !== "default") return v([], t.split(",").map((e) => e.trim()).filter(Boolean), { defaultHttpPort: e.syncPort });
1174
- if (e.syncHost && e.syncHost !== "0.0.0.0") return [ae(ne(e.syncHost, e.syncPort))].filter(Boolean);
1175
- let n = Object.values(se()).flatMap((e) => e ?? []).filter((e) => !e.internal).map((e) => e.address).filter((e) => e && e !== "127.0.0.1" && e !== "::1").map((t) => ae(ne(t, e.syncPort))).filter(Boolean);
1178
+ if (e.syncHost && e.syncHost !== "0.0.0.0") return [oe(re(e.syncHost, e.syncPort))].filter(Boolean);
1179
+ let n = Object.values(ce()).flatMap((e) => e ?? []).filter((e) => !e.internal).map((e) => e.address).filter((e) => e && e !== "127.0.0.1" && e !== "::1").map((t) => oe(re(t, e.syncPort))).filter(Boolean);
1176
1180
  return [...new Set(n)];
1177
1181
  }
1178
- async function nn(e, t, r) {
1182
+ async function an(e, t, n) {
1179
1183
  if (!_(t)) return null;
1180
- let i = r?.keysDir ?? (process.env.CODEMEM_KEYS_DIR?.trim() || void 0), [a, o] = y(e.db, { keysDir: i }), s = te(i);
1184
+ let r = n?.keysDir ?? (process.env.CODEMEM_KEYS_DIR?.trim() || void 0), [i, o] = y(e.db, { keysDir: r }), s = ne(r);
1181
1185
  if (!s) throw Error("public key missing");
1182
- let c = p(t.syncCoordinatorUrl), u = {
1186
+ let c = m(t.syncCoordinatorUrl), l = {
1183
1187
  fingerprint: o,
1184
1188
  public_key: s,
1185
- addresses: tn(t),
1189
+ addresses: rn(t),
1186
1190
  ttl_s: Math.max(1, t.syncCoordinatorPresenceTtlS),
1187
1191
  capabilities: {
1188
- sync_capability: f,
1189
- sync_features: l,
1190
- applied_removal_seq: n(e.db)
1192
+ sync_capability: p,
1193
+ sync_features: u,
1194
+ applied_removal_seq: a(e.db)
1191
1195
  }
1192
1196
  }, d = [];
1193
1197
  for (let n of t.syncCoordinatorGroups) {
1194
- let r = {
1195
- ...u,
1198
+ let a = {
1199
+ ...l,
1196
1200
  group_id: n
1197
- }, o = Buffer.from(JSON.stringify(r), "utf8"), s = `${c}/v1/presence`, l = m({
1198
- deviceId: a,
1201
+ }, o = Buffer.from(JSON.stringify(a), "utf8"), s = `${c}/v1/presence`, u = h({
1202
+ deviceId: i,
1199
1203
  dbPath: e.dbPath,
1200
1204
  method: "POST",
1201
1205
  url: s,
1202
1206
  bodyBytes: o,
1203
- keysDir: i
1207
+ keysDir: r
1204
1208
  }), [f, p] = await b("POST", s, {
1205
- headers: l,
1206
- body: r,
1209
+ headers: u,
1210
+ body: a,
1207
1211
  bodyBytes: o,
1208
1212
  timeoutS: Math.max(1, t.syncCoordinatorTimeoutS)
1209
1213
  });
@@ -1220,9 +1224,9 @@ async function nn(e, t, r) {
1220
1224
  }
1221
1225
  async function X(e, t, n) {
1222
1226
  if (!_(t)) return [];
1223
- let r = n?.keysDir ?? (process.env.CODEMEM_KEYS_DIR?.trim() || void 0), [i] = y(e.db, { keysDir: r }), a = p(t.syncCoordinatorUrl), o = /* @__PURE__ */ new Map();
1227
+ let r = n?.keysDir ?? (process.env.CODEMEM_KEYS_DIR?.trim() || void 0), [i] = y(e.db, { keysDir: r }), a = m(t.syncCoordinatorUrl), o = /* @__PURE__ */ new Map();
1224
1228
  for (let n of t.syncCoordinatorGroups) {
1225
- let s = `${a}/v1/peers?group_id=${encodeURIComponent(n)}`, c = m({
1229
+ let s = `${a}/v1/peers?group_id=${encodeURIComponent(n)}`, c = h({
1226
1230
  deviceId: i,
1227
1231
  dbPath: e.dbPath,
1228
1232
  method: "GET",
@@ -1240,7 +1244,7 @@ async function X(e, t, n) {
1240
1244
  let d = Array.isArray(u.items) ? u.items : [];
1241
1245
  for (let e of d) {
1242
1246
  if (!e || typeof e != "object") continue;
1243
- let t = e, r = W(t.device_id), i = W(t.fingerprint);
1247
+ let t = e, r = U(t.device_id), i = U(t.fingerprint);
1244
1248
  if (!r) continue;
1245
1249
  let s = t.stale ? [] : Array.isArray(t.addresses) ? t.addresses.filter((e) => typeof e == "string") : [], c = `${r}:${i}`, l = o.get(c);
1246
1250
  if (!l) {
@@ -1253,22 +1257,22 @@ async function X(e, t, n) {
1253
1257
  });
1254
1258
  continue;
1255
1259
  }
1256
- rn(l, t, n, s);
1260
+ on(l, t, n, s);
1257
1261
  }
1258
1262
  }
1259
1263
  return [...o.values()];
1260
1264
  }
1261
- function rn(e, t, n, r) {
1262
- e.addresses = v(Z(e.addresses), r), e.groups = Gt(Z(e.groups), [n]);
1265
+ function on(e, t, n, r) {
1266
+ e.addresses = v(Z(e.addresses), r), e.groups = Jt(Z(e.groups), [n]);
1263
1267
  let i = !!e.stale, a = !!t.stale;
1264
- e.fresh_groups = Gt(Z(e.fresh_groups), a ? [] : [n]), e.stale = i && a;
1265
- let o = W(t.last_seen_at) > W(e.last_seen_at) || i && !a;
1266
- o && (!a || i) && (e.last_seen_at = t.last_seen_at), a ? i && o && (e.expires_at = t.expires_at) : e.expires_at = i ? t.expires_at : Kt(e.expires_at, t.expires_at);
1268
+ e.fresh_groups = Jt(Z(e.fresh_groups), a ? [] : [n]), e.stale = i && a;
1269
+ let o = U(t.last_seen_at) > U(e.last_seen_at) || i && !a;
1270
+ o && (!a || i) && (e.last_seen_at = t.last_seen_at), a ? i && o && (e.expires_at = t.expires_at) : e.expires_at = i ? t.expires_at : Yt(e.expires_at, t.expires_at);
1267
1271
  }
1268
1272
  function Z(e) {
1269
1273
  return Array.isArray(e) ? e.filter((e) => typeof e == "string" && e.trim().length > 0) : [];
1270
1274
  }
1271
- function an(e) {
1275
+ function sn(e) {
1272
1276
  if (!Array.isArray(e) || e.length === 0) return null;
1273
1277
  let t = [];
1274
1278
  for (let n of e) {
@@ -1277,7 +1281,7 @@ function an(e) {
1277
1281
  }
1278
1282
  return t;
1279
1283
  }
1280
- function on(e) {
1284
+ function cn(e) {
1281
1285
  if (typeof e != "string" || e.trim().length === 0) return [];
1282
1286
  try {
1283
1287
  return Z(JSON.parse(e));
@@ -1285,19 +1289,19 @@ function on(e) {
1285
1289
  return [];
1286
1290
  }
1287
1291
  }
1288
- function sn(e, t, n) {
1289
- let r = W(e.peer_device_id), i = W(e.pinned_fingerprint);
1292
+ function ln(e, t, n) {
1293
+ let r = U(e.peer_device_id), i = U(e.pinned_fingerprint);
1290
1294
  if (!r || !i) return !1;
1291
1295
  let a = t.get(`${r}:${i}`);
1292
1296
  if (!a?.length) return !1;
1293
- let o = v(on(e.addresses_json), []), s = e.manual_addresses_json == null ? o : on(e.manual_addresses_json), c = ie(o, a, s, { successfulAddress: e.last_success_address ?? void 0 });
1297
+ let o = v(cn(e.addresses_json), []), s = e.manual_addresses_json == null ? o : cn(e.manual_addresses_json), c = ae(o, a, s, { successfulAddress: e.last_success_address ?? void 0 });
1294
1298
  return JSON.stringify(c) === JSON.stringify(o) && e.manual_addresses_json != null ? !1 : (n(JSON.stringify(c), JSON.stringify(s), r, i), !0);
1295
1299
  }
1296
- function cn(e, t) {
1300
+ function Q(e, t) {
1297
1301
  let n = /* @__PURE__ */ new Map();
1298
1302
  for (let e of t) {
1299
1303
  if (e.stale) continue;
1300
- let t = W(e.device_id), r = W(e.fingerprint);
1304
+ let t = U(e.device_id), r = U(e.fingerprint);
1301
1305
  if (!t || !r) continue;
1302
1306
  let i = Z(e.addresses);
1303
1307
  if (i.length === 0) continue;
@@ -1309,11 +1313,11 @@ function cn(e, t) {
1309
1313
  i.run(e, t, n, r);
1310
1314
  }, o = 0;
1311
1315
  return e.transaction(() => {
1312
- for (let e of r) sn(e, n, a) && (o += 1);
1316
+ for (let e of r) ln(e, n, a) && (o += 1);
1313
1317
  }).immediate(), o;
1314
1318
  }
1315
- function ln(e, t) {
1316
- let { localDeviceId: n, peerDeviceId: r, coordinatorId: a, peerGroupIds: o, peerPublicKey: s } = t, c = t.kinds?.length ? t.kinds : ["managed_project"], l = e.prepare("SELECT public_key FROM sync_device WHERE device_id = ?").pluck().get(n), u = e.prepare(`SELECT scope.scope_id, scope.coordinator_id, scope.group_id
1319
+ function un(e, t) {
1320
+ let { localDeviceId: r, peerDeviceId: i, coordinatorId: a, peerGroupIds: o, peerPublicKey: s } = t, c = t.kinds?.length ? t.kinds : ["managed_project"], l = e.prepare("SELECT public_key FROM sync_device WHERE device_id = ?").pluck().get(r), u = e.prepare(`SELECT scope.scope_id, scope.coordinator_id, scope.group_id
1317
1321
  FROM scope_memberships local_member
1318
1322
  JOIN scope_memberships peer_member
1319
1323
  ON peer_member.scope_id = local_member.scope_id
@@ -1324,20 +1328,20 @@ function ln(e, t) {
1324
1328
  AND scope.status = 'active'
1325
1329
  AND scope.kind IN (${c.map(() => "?").join(", ")})
1326
1330
  AND scope.authority_type = 'coordinator'
1327
- ORDER BY scope.scope_id`).all(n, r, ...c), d = [], f = !1;
1331
+ ORDER BY scope.scope_id`).all(r, i, ...c), d = [], f = !1;
1328
1332
  for (let t of u) {
1329
- let c = W(t.scope_id), u = W(t.group_id);
1330
- if (!c || W(t.coordinator_id) !== a || !u || o !== null && !o.includes(u)) continue;
1333
+ let c = U(t.scope_id), u = U(t.group_id);
1334
+ if (!c || U(t.coordinator_id) !== a || !u || o !== null && !o.includes(u)) continue;
1331
1335
  let p = {
1332
1336
  coordinatorId: a,
1333
1337
  groupId: u
1334
- }, m = i(e, {
1335
- deviceId: n,
1338
+ }, m = n(e, {
1339
+ deviceId: r,
1336
1340
  scopeId: c,
1337
1341
  authority: p,
1338
1342
  expectedPublicKey: l ?? ""
1339
- }), h = i(e, {
1340
- deviceId: r,
1343
+ }), h = n(e, {
1344
+ deviceId: i,
1341
1345
  scopeId: c,
1342
1346
  authority: p,
1343
1347
  expectedPublicKey: s
@@ -1358,8 +1362,8 @@ function ln(e, t) {
1358
1362
  indeterminate: f
1359
1363
  };
1360
1364
  }
1361
- function Q(e, t, n, r, i, a) {
1362
- let { scopes: o, indeterminate: s } = ln(e, {
1365
+ function $(e, t, n, r, i, a) {
1366
+ let { scopes: o, indeterminate: s } = un(e, {
1363
1367
  localDeviceId: t,
1364
1368
  peerDeviceId: n,
1365
1369
  coordinatorId: r,
@@ -1371,41 +1375,41 @@ function Q(e, t, n, r, i, a) {
1371
1375
  groupId: c.groupId
1372
1376
  } : { state: s ? "indeterminate" : "not_authorized" };
1373
1377
  }
1374
- function un(e, t, n, r, i) {
1378
+ function dn(e, t, n, r, i) {
1375
1379
  let a = n.stale ? [] : Z(n.addresses);
1376
- re(e, t, a, {
1377
- name: W(n.display_name) || void 0,
1380
+ ie(e, t, a, {
1381
+ name: U(n.display_name) || void 0,
1378
1382
  pinnedFingerprint: r,
1379
1383
  publicKey: i,
1380
1384
  coordinatorCandidates: !0
1381
1385
  });
1382
1386
  }
1383
- function dn(e, t, n) {
1387
+ function fn(e, t, n) {
1384
1388
  let r = 0;
1385
1389
  for (let i of n) {
1386
- let n = W(i.device_id), a = W(i.public_key), o = W(i.fingerprint), s = W(i.coordinator_id), c = an(i.groups);
1387
- if (!n || n === t || !a || !o || !s || !c || !fn(a, o)) continue;
1388
- let l = Q(e, t, n, s, c, a);
1390
+ let n = U(i.device_id), a = U(i.public_key), o = U(i.fingerprint), s = U(i.coordinator_id), c = sn(i.groups);
1391
+ if (!n || n === t || !a || !o || !s || !c || !pn(a, o)) continue;
1392
+ let l = $(e, t, n, s, c, a);
1389
1393
  if (l.state !== "authorized") continue;
1390
1394
  let u = e.prepare("SELECT pinned_fingerprint, public_key, claimed_local_actor, actor_id,\n pending_bootstrap_grant_id, trust_provenance\n FROM sync_peers WHERE peer_device_id = ? LIMIT 1").get(n);
1391
- if (u && (u.claimed_local_actor === 1 || W(u.pinned_fingerprint) && W(u.pinned_fingerprint) !== o || W(u.public_key) && W(u.public_key) !== a)) continue;
1392
- let d = !!(W(u?.pinned_fingerprint) || W(u?.public_key)), f = !u || u.claimed_local_actor === 0 && u.actor_id == null && u.pending_bootstrap_grant_id == null && (!d || u.trust_provenance === "coordinator_policy");
1393
- un(e, n, i, o, a), f && e.prepare("UPDATE sync_peers SET discovered_via_coordinator_id = ?,\n discovered_via_group_id = ?, trust_provenance = 'coordinator_policy'\n WHERE peer_device_id = ?\n AND claimed_local_actor = 0 AND actor_id IS NULL\n AND pending_bootstrap_grant_id IS NULL").run(s, l.groupId, n), r += 1;
1395
+ if (u && (u.claimed_local_actor === 1 || U(u.pinned_fingerprint) && U(u.pinned_fingerprint) !== o || U(u.public_key) && U(u.public_key) !== a)) continue;
1396
+ let d = !!(U(u?.pinned_fingerprint) || U(u?.public_key)), f = !u || u.claimed_local_actor === 0 && u.actor_id == null && u.pending_bootstrap_grant_id == null && (!d || u.trust_provenance === "coordinator_policy");
1397
+ dn(e, n, i, o, a), f && e.prepare("UPDATE sync_peers SET discovered_via_coordinator_id = ?,\n discovered_via_group_id = ?, trust_provenance = 'coordinator_policy'\n WHERE peer_device_id = ?\n AND claimed_local_actor = 0 AND actor_id IS NULL\n AND pending_bootstrap_grant_id IS NULL").run(s, l.groupId, n), r += 1;
1394
1398
  }
1395
1399
  return r;
1396
1400
  }
1397
- function fn(e, t) {
1401
+ function pn(e, t) {
1398
1402
  try {
1399
- return o(e) === t;
1403
+ return s(e) === t;
1400
1404
  } catch {
1401
1405
  return !1;
1402
1406
  }
1403
1407
  }
1404
- function pn(e, t) {
1408
+ function mn(e, t) {
1405
1409
  let n = e.prepare("SELECT peer_device_id, public_key, discovered_via_coordinator_id, discovered_via_group_id\n FROM sync_peers\n WHERE claimed_local_actor = 0\n AND actor_id IS NULL\n AND pending_bootstrap_grant_id IS NULL\n AND trust_provenance = 'coordinator_policy'\n AND discovered_via_coordinator_id IS NOT NULL\n AND discovered_via_group_id IS NOT NULL\n AND (pinned_fingerprint IS NOT NULL OR public_key IS NOT NULL)").all(), r = 0;
1406
1410
  for (let i of n) {
1407
- let n = W(i.peer_device_id), a = W(i.discovered_via_coordinator_id), o = W(i.discovered_via_group_id);
1408
- !n || !a || !o || Q(e, t, n, a, null, W(i.public_key)).state === "not_authorized" && (r += U(e, {
1411
+ let n = U(i.peer_device_id), a = U(i.discovered_via_coordinator_id), o = U(i.discovered_via_group_id);
1412
+ !n || !a || !o || $(e, t, n, a, null, U(i.public_key)).state === "not_authorized" && (r += H(e, {
1409
1413
  localDeviceId: t,
1410
1414
  reason: "policy",
1411
1415
  pairings: [{
@@ -1417,16 +1421,16 @@ function pn(e, t) {
1417
1421
  }
1418
1422
  return r;
1419
1423
  }
1420
- function mn(e, t, n) {
1424
+ function hn(e, t, n) {
1421
1425
  return e.prepare("SELECT public_key, pinned_fingerprint FROM sync_peers\n WHERE peer_device_id = ? AND discovered_via_coordinator_id = ?\n AND trust_provenance = 'coordinator_policy'\n AND claimed_local_actor = 0 AND actor_id IS NULL\n AND pending_bootstrap_grant_id IS NULL").get(t, n);
1422
1426
  }
1423
- function hn(e, t, n) {
1424
- let r = W(n.device_id), i = W(n.coordinator_id), a = W(n.public_key), o = W(n.fingerprint), s = an(n.groups);
1425
- if (!r || r === t || !i || !s || !fn(a, o)) return null;
1426
- let c = mn(e, r, i);
1427
- if (!c?.public_key || !c.pinned_fingerprint || !fn(c.public_key, c.pinned_fingerprint)) return null;
1428
- let l = Q(e, t, r, i, s, a);
1429
- return l.state !== "authorized" || Q(e, t, r, i, null, c.public_key).state !== "not_authorized" ? null : {
1427
+ function gn(e, t, n) {
1428
+ let r = U(n.device_id), i = U(n.coordinator_id), a = U(n.public_key), o = U(n.fingerprint), s = sn(n.groups);
1429
+ if (!r || r === t || !i || !s || !pn(a, o)) return null;
1430
+ let c = hn(e, r, i);
1431
+ if (!c?.public_key || !c.pinned_fingerprint || !pn(c.public_key, c.pinned_fingerprint)) return null;
1432
+ let l = $(e, t, r, i, s, a);
1433
+ return l.state !== "authorized" || $(e, t, r, i, null, c.public_key).state !== "not_authorized" ? null : {
1430
1434
  peerDeviceId: r,
1431
1435
  coordinatorId: i,
1432
1436
  groupId: l.groupId,
@@ -1436,126 +1440,126 @@ function hn(e, t, n) {
1436
1440
  previousFingerprint: c.pinned_fingerprint
1437
1441
  };
1438
1442
  }
1439
- function gn(e, t, n) {
1440
- H(e, {
1443
+ function _n(e, t, n) {
1444
+ V(e, {
1441
1445
  localDeviceId: t,
1442
1446
  peerDeviceId: n.peerDeviceId
1443
1447
  }), e.prepare("UPDATE sync_peers SET public_key = ?, pinned_fingerprint = ?, discovered_via_group_id = ?\n WHERE peer_device_id = ? AND discovered_via_coordinator_id = ?\n AND public_key = ? AND pinned_fingerprint = ?\n AND trust_provenance = 'coordinator_policy'\n AND claimed_local_actor = 0 AND actor_id IS NULL\n AND pending_bootstrap_grant_id IS NULL").run(n.publicKey, n.fingerprint, n.groupId, n.peerDeviceId, n.coordinatorId, n.previousPublicKey, n.previousFingerprint);
1444
1448
  }
1445
- function _n(e, t, n) {
1449
+ function vn(e, t, n) {
1446
1450
  return e.transaction(() => {
1447
1451
  let r = /* @__PURE__ */ new Set();
1448
1452
  for (let i of n) {
1449
- let n = hn(e, t, i);
1450
- n && (gn(e, t, n), vn(e, n, i), r.add(n.peerDeviceId));
1453
+ let n = gn(e, t, i);
1454
+ n && (_n(e, t, n), yn(e, n, i), r.add(n.peerDeviceId));
1451
1455
  }
1452
- pn(e, t);
1453
- let i = n.filter((e) => !r.has(W(e.device_id)));
1454
- return r.size + dn(e, t, i);
1456
+ mn(e, t);
1457
+ let i = n.filter((e) => !r.has(U(e.device_id)));
1458
+ return r.size + fn(e, t, i);
1455
1459
  }).immediate();
1456
1460
  }
1457
- function vn(e, t, n) {
1458
- n.stale || sn(e.prepare("SELECT peer_device_id, pinned_fingerprint, addresses_json, manual_addresses_json,\n last_success_address FROM sync_peers WHERE peer_device_id = ?").get(t.peerDeviceId), /* @__PURE__ */ new Map([[`${t.peerDeviceId}:${t.fingerprint}`, Z(n.addresses)]]), (t, n, r, i) => {
1461
+ function yn(e, t, n) {
1462
+ n.stale || ln(e.prepare("SELECT peer_device_id, pinned_fingerprint, addresses_json, manual_addresses_json,\n last_success_address FROM sync_peers WHERE peer_device_id = ?").get(t.peerDeviceId), /* @__PURE__ */ new Map([[`${t.peerDeviceId}:${t.fingerprint}`, Z(n.addresses)]]), (t, n, r, i) => {
1459
1463
  e.prepare("UPDATE sync_peers SET addresses_json = ?,\n manual_addresses_json = COALESCE(manual_addresses_json, ?)\n WHERE peer_device_id = ? AND pinned_fingerprint = ?").run(t, n, r, i);
1460
1464
  });
1461
1465
  }
1462
- async function yn(e, t, n) {
1466
+ async function bn(e, t, n) {
1463
1467
  if (!_(t)) return {
1464
1468
  peers: [],
1465
1469
  trusted: 0
1466
1470
  };
1467
1471
  let r = n?.keysDir ?? (process.env.CODEMEM_KEYS_DIR?.trim() || void 0), [i] = y(e.db, { keysDir: r }), a = await X(e, t, { keysDir: r });
1468
- return cn(e.db, a), {
1472
+ return Q(e.db, a), {
1469
1473
  peers: a,
1470
- trusted: _n(e.db, i, a)
1474
+ trusted: vn(e.db, i, a)
1471
1475
  };
1472
1476
  }
1473
- function bn(e, t, n) {
1477
+ function xn(e, t, n) {
1474
1478
  if (n.status === "checked") {
1475
- xt(e, t);
1479
+ wt(e, t);
1476
1480
  return;
1477
1481
  }
1478
- bt(e, {
1482
+ Ct(e, {
1479
1483
  coordinatorId: t,
1480
1484
  groupIds: n.removedFromGroups
1481
1485
  });
1482
1486
  }
1483
- async function xn(t, n, i) {
1484
- if (!_(n)) return {
1487
+ async function Sn(e, t, n) {
1488
+ if (!_(t)) return {
1485
1489
  revoked: 0,
1486
1490
  removed: 0,
1487
1491
  enrolled: [],
1488
1492
  status: "unsupported"
1489
1493
  };
1490
- let a = i?.keysDir ?? (process.env.CODEMEM_KEYS_DIR?.trim() || void 0), [o] = y(t.db, { keysDir: a }), s = await _t(t, n, {
1494
+ let a = n?.keysDir ?? (process.env.CODEMEM_KEYS_DIR?.trim() || void 0), [o] = y(e.db, { keysDir: a }), s = await bt(e, t, {
1491
1495
  localDeviceId: o,
1492
1496
  keysDir: a
1493
- }), c = t.db, l = p(n.syncCoordinatorUrl);
1497
+ }), c = e.db, l = m(t.syncCoordinatorUrl);
1494
1498
  return s.status === "checked" ? c.transaction(() => {
1495
- let t = s.generation;
1496
- if (t === null || r(c)?.generation !== t) return {
1499
+ let e = s.generation;
1500
+ if (e === null || r(c)?.generation !== e) return {
1497
1501
  revoked: 0,
1498
1502
  removed: 0,
1499
1503
  enrolled: [],
1500
1504
  status: "failed"
1501
1505
  };
1502
- bn(c, l, s);
1503
- let n = Ht(c, o, s.revoked), i = U(c, {
1506
+ xn(c, l, s);
1507
+ let t = Gt(c, o, s.revoked), n = H(c, {
1504
1508
  localDeviceId: o,
1505
1509
  reason: "removed",
1506
1510
  deviceIds: s.removed.filter((e) => e !== o)
1507
1511
  }).syncPeers;
1508
- return s.removalSeq !== null && e(c, {
1509
- generation: t,
1512
+ return s.removalSeq !== null && i(c, {
1513
+ generation: e,
1510
1514
  removalSeq: s.removalSeq
1511
1515
  }), {
1512
- revoked: n,
1513
- removed: i,
1516
+ revoked: t,
1517
+ removed: n,
1514
1518
  enrolled: s.enrolled,
1515
1519
  status: s.status
1516
1520
  };
1517
- }).immediate() : (bn(c, l, s), {
1521
+ }).immediate() : (xn(c, l, s), {
1518
1522
  revoked: 0,
1519
1523
  removed: 0,
1520
1524
  enrolled: [],
1521
1525
  status: s.status
1522
1526
  });
1523
1527
  }
1524
- async function Sn(e, t, n, r) {
1525
- if (r?.peers) return Cn(r.peers);
1526
- let i = g();
1528
+ async function Cn(e, t, n, r) {
1529
+ if (r?.peers) return wn(r.peers);
1530
+ let i = ee();
1527
1531
  if (!_(i)) return /* @__PURE__ */ new Set();
1528
1532
  try {
1529
1533
  let r = await X({
1530
1534
  db: e,
1531
1535
  dbPath: t
1532
1536
  }, i, { keysDir: n });
1533
- return cn(e, r), Cn(r);
1537
+ return Q(e, r), wn(r);
1534
1538
  } catch {
1535
1539
  return /* @__PURE__ */ new Set();
1536
1540
  }
1537
1541
  }
1538
- function Cn(e) {
1542
+ function wn(e) {
1539
1543
  let t = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Set(), r = /* @__PURE__ */ new Set(), i = /* @__PURE__ */ new Set();
1540
1544
  for (let a of e) {
1541
- let e = W(a.device_id);
1545
+ let e = U(a.device_id);
1542
1546
  if (!e) continue;
1543
- let o = W(a.fingerprint), s = o ? `${e}:${o}` : "";
1547
+ let o = U(a.fingerprint), s = o ? `${e}:${o}` : "";
1544
1548
  a.stale ? (n.add(e), s && i.add(s)) : (t.add(e), s && r.add(s));
1545
1549
  }
1546
1550
  for (let e of t) n.delete(e);
1547
1551
  for (let e of r) i.delete(e);
1548
1552
  return /* @__PURE__ */ new Set([...n, ...i]);
1549
1553
  }
1550
- async function $(e, t, n) {
1554
+ async function Tn(e, t, n) {
1551
1555
  if (!_(t)) return [];
1552
- let r = process.env.CODEMEM_KEYS_DIR?.trim() || void 0, [i] = y(e.db, { keysDir: r }), a = p(t.syncCoordinatorUrl), o = /* @__PURE__ */ new Map();
1556
+ let r = process.env.CODEMEM_KEYS_DIR?.trim() || void 0, [i] = y(e.db, { keysDir: r }), a = m(t.syncCoordinatorUrl), o = /* @__PURE__ */ new Map();
1553
1557
  for (let s of t.syncCoordinatorGroups) {
1554
1558
  let c = `${a}/v1/reciprocal-approvals?${new URLSearchParams({
1555
1559
  group_id: s,
1556
1560
  direction: n.direction,
1557
1561
  status: n.status?.trim() || "pending"
1558
- }).toString()}`, l = m({
1562
+ }).toString()}`, l = h({
1559
1563
  deviceId: i,
1560
1564
  dbPath: e.dbPath,
1561
1565
  method: "GET",
@@ -1573,50 +1577,50 @@ async function $(e, t, n) {
1573
1577
  let f = Array.isArray(d.items) ? d.items : [];
1574
1578
  for (let e of f) {
1575
1579
  if (!e || typeof e != "object") continue;
1576
- let t = e, n = W(t.request_id);
1580
+ let t = e, n = U(t.request_id);
1577
1581
  n && o.set(n, t);
1578
1582
  }
1579
1583
  }
1580
1584
  return [...o.values()];
1581
1585
  }
1582
- async function wn(e, t, n) {
1586
+ async function En(e, t, n) {
1583
1587
  if (!_(t)) throw Error("Coordinator not configured.");
1584
1588
  let r = n.groupId.trim(), i = n.requestedDeviceId.trim(), a = n.expectedIncomingRequestId?.trim();
1585
1589
  if (!r || !i) throw Error("groupId and requestedDeviceId are required.");
1586
1590
  if (n.expectedIncomingRequestId !== void 0 && !a) throw Error("expectedIncomingRequestId must not be empty when provided.");
1587
- let o = process.env.CODEMEM_KEYS_DIR?.trim() || void 0, [s] = y(e.db, { keysDir: o }), l = `${p(t.syncCoordinatorUrl)}/v1/reciprocal-approvals`, u = {
1591
+ let o = process.env.CODEMEM_KEYS_DIR?.trim() || void 0, [s] = y(e.db, { keysDir: o }), c = `${m(t.syncCoordinatorUrl)}/v1/reciprocal-approvals`, u = {
1588
1592
  group_id: r,
1589
1593
  requested_device_id: i,
1590
1594
  ...a === void 0 ? {} : { expected_incoming_request_id: a }
1591
- }, d = Buffer.from(JSON.stringify(u), "utf8"), f = m({
1595
+ }, d = Buffer.from(JSON.stringify(u), "utf8"), f = h({
1592
1596
  deviceId: s,
1593
1597
  dbPath: e.dbPath,
1594
1598
  method: "POST",
1595
- url: l,
1599
+ url: c,
1596
1600
  bodyBytes: d,
1597
1601
  keysDir: o
1598
- }), [h, g] = await b("POST", l, {
1602
+ }), [p, g] = await b("POST", c, {
1599
1603
  headers: f,
1600
1604
  body: u,
1601
1605
  bodyBytes: d,
1602
1606
  timeoutS: Math.max(1, t.syncCoordinatorTimeoutS)
1603
1607
  });
1604
- if (h !== 200 || !g || !g.request || typeof g.request != "object") {
1608
+ if (p !== 200 || !g || !g.request || typeof g.request != "object") {
1605
1609
  let n = typeof g?.error == "string" ? g.error : "unknown";
1606
- throw h === 409 && n === "reciprocal_approval_request_changed" ? (J(Y(e, t)), new c()) : Error(`coordinator reciprocal approval create failed (${h}: ${n})`);
1610
+ throw p === 409 && n === "reciprocal_approval_request_changed" ? (q(J(e, t)), new l()) : Error(`coordinator reciprocal approval create failed (${p}: ${n})`);
1607
1611
  }
1608
- return J(Y(e, t)), g.request;
1612
+ return q(J(e, t)), g.request;
1609
1613
  }
1610
- function Tn(e, t) {
1614
+ function Dn(e, t) {
1611
1615
  let n = /* @__PURE__ */ new Map();
1612
1616
  for (let r of e) {
1613
- let e = W(r[t]);
1617
+ let e = U(r[t]);
1614
1618
  e && n.set(e, r);
1615
1619
  }
1616
1620
  return n;
1617
1621
  }
1618
- async function En(e, t) {
1619
- let n = Zt(e);
1622
+ async function On(e, t) {
1623
+ let n = Y(e);
1620
1624
  if (!_(t)) return {
1621
1625
  enabled: !1,
1622
1626
  configured: !1,
@@ -1625,19 +1629,19 @@ async function En(e, t) {
1625
1629
  groups: t.syncCoordinatorGroups,
1626
1630
  paired_peer_count: n
1627
1631
  };
1628
- let r = process.env.CODEMEM_KEYS_DIR?.trim() || void 0, [i] = y(e.db, { keysDir: r }), a = Y(e, t), o = q.get(a) ?? 0, s = Date.now(), c = K.get(a);
1632
+ let r = process.env.CODEMEM_KEYS_DIR?.trim() || void 0, [i] = y(e.db, { keysDir: r }), a = J(e, t), o = K.get(a) ?? 0, s = Date.now(), c = G.get(a);
1629
1633
  if (c && s < c.nextRefreshAtMs) {
1630
1634
  let n = structuredClone(c.snapshot);
1631
- if (await en(e, t, n, s), s = Date.now(), n.presence_status === "not_enrolled") return J(a), n.fresh_peer_count = 0, n.stale_peer_count = 0, n.discovered_peer_count = 0, n.discovered_devices = [], n.reciprocal_approvals = {
1635
+ if (await nn(e, t, n, s), s = Date.now(), n.presence_status === "not_enrolled") return q(a), n.fresh_peer_count = 0, n.stale_peer_count = 0, n.discovered_peer_count = 0, n.discovered_devices = [], n.reciprocal_approvals = {
1632
1636
  incoming: [],
1633
1637
  outgoing: []
1634
1638
  }, {
1635
1639
  ...n,
1636
- paired_peer_count: Zt(e)
1640
+ paired_peer_count: Y(e)
1637
1641
  };
1638
- if (s < c.nextRefreshAtMs) return _n(e.db, i, c.discoveredPeers), {
1642
+ if (s < c.nextRefreshAtMs) return vn(e.db, i, c.discoveredPeers), {
1639
1643
  ...n,
1640
- paired_peer_count: Zt(e)
1644
+ paired_peer_count: Y(e)
1641
1645
  };
1642
1646
  }
1643
1647
  let l = {
@@ -1655,33 +1659,33 @@ async function En(e, t) {
1655
1659
  discovered_peer_count: 0,
1656
1660
  discovered_devices: []
1657
1661
  };
1658
- await en(e, t, l, s);
1662
+ await nn(e, t, l, s);
1659
1663
  let u = [];
1660
1664
  try {
1661
- let { peers: n } = await yn(e, t, { keysDir: r });
1665
+ let { peers: n } = await bn(e, t, { keysDir: r });
1662
1666
  u = structuredClone(n);
1663
1667
  let i = [], a = [];
1664
1668
  try {
1665
- i = await $(e, t, { direction: "incoming" }), a = await $(e, t, { direction: "outgoing" });
1669
+ i = await Tn(e, t, { direction: "incoming" }), a = await Tn(e, t, { direction: "outgoing" });
1666
1670
  } catch (e) {
1667
1671
  l.reciprocal_approval_error = e instanceof Error ? e.message : String(e);
1668
1672
  }
1669
- let o = Tn(i, "requesting_device_id"), s = Tn(a, "requested_device_id");
1673
+ let o = Dn(i, "requesting_device_id"), s = Dn(a, "requested_device_id");
1670
1674
  l.discovered_peer_count = n.length, l.fresh_peer_count = n.filter((e) => !e.stale).length, l.stale_peer_count = n.filter((e) => !!e.stale).length, l.reciprocal_approvals = {
1671
1675
  incoming: i,
1672
1676
  outgoing: a
1673
- }, l.discovered_devices = n.map((e) => Dn(e, o, s));
1677
+ }, l.discovered_devices = n.map((e) => kn(e, o, s));
1674
1678
  } catch (e) {
1675
1679
  l.lookup_error = e instanceof Error ? e.message : String(e);
1676
1680
  }
1677
- return l.presence_status !== "not_enrolled" && !l.lookup_error && !l.reciprocal_approval_error && (q.get(a) ?? 0) === o && K.set(a, {
1681
+ return l.presence_status !== "not_enrolled" && !l.lookup_error && !l.reciprocal_approval_error && (K.get(a) ?? 0) === o && G.set(a, {
1678
1682
  snapshot: structuredClone(l),
1679
1683
  discoveredPeers: u,
1680
- nextRefreshAtMs: Jt(Date.now(), u)
1684
+ nextRefreshAtMs: Zt(Date.now(), u)
1681
1685
  }), l;
1682
1686
  }
1683
- function Dn(e, t, n) {
1684
- let r = t.get(W(e.device_id)), i = n.get(W(e.device_id));
1687
+ function kn(e, t, n) {
1688
+ let r = t.get(U(e.device_id)), i = n.get(U(e.device_id));
1685
1689
  return {
1686
1690
  device_id: e.device_id,
1687
1691
  display_name: e.display_name ?? null,
@@ -1697,16 +1701,16 @@ function Dn(e, t, n) {
1697
1701
  outgoing_reciprocal_request_id: i?.request_id ?? null
1698
1702
  };
1699
1703
  }
1700
- async function On(e) {
1704
+ async function An(e) {
1701
1705
  let t = e.syncCoordinatorGroup || e.syncCoordinatorGroups[0] || "";
1702
1706
  if (!t || !e.syncCoordinatorUrl || !e.syncCoordinatorAdminSecret) return [];
1703
- let n = `${p(e.syncCoordinatorUrl)}/v1/admin/join-requests?group_id=${encodeURIComponent(t)}`, [r, i] = await b("GET", n, {
1707
+ let n = `${m(e.syncCoordinatorUrl)}/v1/admin/join-requests?group_id=${encodeURIComponent(t)}`, [r, i] = await b("GET", n, {
1704
1708
  headers: { "X-Codemem-Coordinator-Admin": e.syncCoordinatorAdminSecret },
1705
1709
  timeoutS: Math.max(1, e.syncCoordinatorTimeoutS)
1706
1710
  });
1707
1711
  return r !== 200 || !i ? [] : Array.isArray(i.items) ? i.items.filter((e) => !!e && typeof e == "object") : [];
1708
1712
  }
1709
1713
  //#endregion
1710
- export { M as A, pe as B, et as C, He as D, Ve as E, ze as F, fe as H, Pe as I, C as L, ve as M, _e as N, j as O, k as P, he as R, I as S, rt as T, x as V, U as _, $ as a, We as b, cn as c, ln as d, dn as f, Pt as g, Wt as h, On as i, Ue as j, A as k, nn as l, Vt as m, wn as n, X as o, Ht as p, Sn as r, yn as s, En as t, xn as u, St as v, R as w, ot as x, vt as y, w as z };
1714
+ export { Ve as A, T as B, I as C, Ue as D, at as E, A as F, x as H, Be as I, Fe as L, Ge as M, ve as N, We as O, _e as P, C as R, ct as S, R as T, pe as U, me as V, H as _, Tn as a, xt as b, Q as c, un as d, fn as f, Lt as g, qt as h, An as i, M as j, j as k, an as l, Wt as m, En as n, X as o, Gt as p, Cn as r, bn as s, On as t, Sn as u, Tt as v, nt as w, Ke as x, bt as y, w as z };
1711
1715
 
1712
- //# sourceMappingURL=coordinator-runtime-ynLTJI6d.js.map
1716
+ //# sourceMappingURL=coordinator-runtime-ChgCIqfx.js.map