@inflatable-cookie/longhorn 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -7
  3. package/src/agent-control/generated/protocol.ts +228 -0
  4. package/src/agent-control/index.ts +1 -5
  5. package/src/agent-control/inject.ts +4 -1
  6. package/src/agent-control/selection.ts +42 -25
  7. package/src/agent-control/shim.ts +428 -198
  8. package/src/bridge/direct.ts +1 -1
  9. package/src/bridge/generated/fields.ts +4 -3
  10. package/src/bridge/generated/protocol.ts +62 -7
  11. package/src/bridge/generated/variant-fields.ts +1 -1
  12. package/src/bridge/job.ts +49 -12
  13. package/src/bridge/loopback.ts +7 -25
  14. package/src/bridge/operation.ts +13 -43
  15. package/src/bridge/router.ts +10 -23
  16. package/src/bridge/runtime/connection.ts +78 -109
  17. package/src/bridge/runtime/policy.ts +8 -28
  18. package/src/bridge/runtime/retry.ts +6 -18
  19. package/src/bridge/session.ts +4 -14
  20. package/src/bridge/stream/connection.ts +24 -55
  21. package/src/bridge/stream/source.ts +2 -6
  22. package/src/bridge/stream/tracker.ts +12 -12
  23. package/src/bridge/supervision.ts +104 -97
  24. package/src/bridge/validation/base.ts +21 -63
  25. package/src/bridge/validation/jobs.ts +11 -25
  26. package/src/bridge/validation/negotiation.ts +28 -43
  27. package/src/bridge/validation/operations.ts +29 -65
  28. package/src/bridge/validation/streams.ts +3 -10
  29. package/src/commands/client.ts +37 -28
  30. package/src/commands/controller.ts +119 -96
  31. package/src/commands/generated/fields.ts +7 -6
  32. package/src/commands/generated/protocol.ts +28 -1
  33. package/src/commands/generated/variant-fields.ts +1 -1
  34. package/src/commands/keyboard.ts +94 -100
  35. package/src/commands/physical-code.ts +11 -0
  36. package/src/commands/ports.ts +8 -13
  37. package/src/commands/projectors.ts +100 -75
  38. package/src/commands/validation.ts +434 -241
  39. package/src/config/client.ts +9 -22
  40. package/src/config/generated/base.ts +22 -6
  41. package/src/config/generated/fields.ts +4 -3
  42. package/src/config/generated/label-template.ts +1 -1
  43. package/src/config/generated/labels.ts +1 -1
  44. package/src/config/generated/protocol.ts +1 -1
  45. package/src/config/generated/restore.ts +35 -12
  46. package/src/config/generated/variant-fields.ts +1 -1
  47. package/src/config/names.ts +6 -12
  48. package/src/config/validation/commands.ts +11 -25
  49. package/src/config/validation/outcomes.ts +163 -70
  50. package/src/config/validation/primitives.ts +35 -80
  51. package/src/config/validation/projection.ts +100 -128
  52. package/src/core/connection.ts +187 -83
  53. package/src/core/controller-lifecycle.ts +144 -0
  54. package/src/core/generated/identifiers.ts +4 -0
  55. package/src/core/identifiers.ts +40 -0
  56. package/src/core/index.ts +10 -1
  57. package/src/core/json-value.ts +58 -0
  58. package/src/core/listeners.ts +35 -0
  59. package/src/core/record.ts +80 -0
  60. package/src/core/transport.ts +9 -11
  61. package/src/core/wire-copy.ts +7 -0
  62. package/src/history/client.ts +11 -13
  63. package/src/history/controller.ts +106 -108
  64. package/src/history/direct.ts +1 -3
  65. package/src/history/generated/fields.ts +4 -3
  66. package/src/history/generated/protocol.ts +8 -5
  67. package/src/history/generated/variant-fields.ts +1 -1
  68. package/src/history/ports.ts +7 -4
  69. package/src/history/serialized.ts +9 -13
  70. package/src/history/validation.ts +69 -75
  71. package/src/history-tree/client.ts +89 -11
  72. package/src/history-tree/controller.ts +380 -96
  73. package/src/history-tree/direct.ts +3 -1
  74. package/src/history-tree/generated/fields.ts +5 -3
  75. package/src/history-tree/generated/protocol.ts +43 -7
  76. package/src/history-tree/generated/variant-fields.ts +7 -1
  77. package/src/history-tree/ports.ts +12 -5
  78. package/src/history-tree/serialized.ts +39 -11
  79. package/src/history-tree/validation.ts +286 -78
  80. package/src/layout/generated/protocol.ts +4 -3
  81. package/src/layout/generated/variant-fields.ts +47 -0
  82. package/src/layout/index.ts +1 -1
  83. package/src/layout/ratio.ts +10 -9
  84. package/src/layout/validation.ts +98 -32
  85. package/src/layout/visibility.ts +1 -2
  86. package/src/licence/client.ts +48 -7
  87. package/src/licence/controller.ts +127 -70
  88. package/src/licence/direct.ts +3 -1
  89. package/src/licence/generated/fields.ts +4 -3
  90. package/src/licence/generated/key-conformance.json +28 -0
  91. package/src/licence/generated/protocol.ts +9 -5
  92. package/src/licence/generated/variant-fields.ts +1 -1
  93. package/src/licence/key.ts +42 -18
  94. package/src/licence/ports.ts +10 -3
  95. package/src/licence/serialized.ts +32 -9
  96. package/src/licence/validation.ts +134 -43
  97. package/src/native-content/client.ts +207 -234
  98. package/src/native-content/generated/fields.ts +6 -6
  99. package/src/native-content/generated/protocol.ts +16 -5
  100. package/src/native-content/generated/variant-fields.ts +1 -1
  101. package/src/native-content/ports.ts +11 -16
  102. package/src/native-content/serialized.ts +12 -19
  103. package/src/native-content/validation/base.ts +57 -80
  104. package/src/native-content/validation/messages.ts +24 -35
  105. package/src/native-content/validation/state.ts +31 -33
  106. package/src/notifications/client.ts +85 -51
  107. package/src/notifications/controller.ts +400 -145
  108. package/src/notifications/direct.ts +3 -1
  109. package/src/notifications/generated/fields.ts +4 -3
  110. package/src/notifications/generated/labels.ts +1 -1
  111. package/src/notifications/generated/protocol.ts +5 -1
  112. package/src/notifications/generated/variant-fields.ts +1 -1
  113. package/src/notifications/ports.ts +9 -4
  114. package/src/notifications/serialized.ts +11 -9
  115. package/src/notifications/tone.ts +1 -1
  116. package/src/notifications/validation.ts +165 -71
  117. package/src/operation/bridge.ts +187 -60
  118. package/src/operation/client.ts +48 -62
  119. package/src/operation/controller.ts +67 -97
  120. package/src/operation/direct.ts +1 -3
  121. package/src/operation/generated/fields.ts +4 -3
  122. package/src/operation/generated/labels.ts +1 -1
  123. package/src/operation/generated/protocol.ts +5 -1
  124. package/src/operation/generated/variant-fields.ts +1 -1
  125. package/src/operation/ports.ts +12 -10
  126. package/src/operation/serialized.ts +8 -9
  127. package/src/operation/validation.ts +189 -104
  128. package/src/settings/client.ts +11 -44
  129. package/src/settings/connection.ts +35 -53
  130. package/src/settings/generated/fields.ts +5 -4
  131. package/src/settings/generated/protocol.ts +14 -5
  132. package/src/settings/generated/variant-fields.ts +1 -1
  133. package/src/settings/names.ts +2 -4
  134. package/src/settings/registry.ts +23 -25
  135. package/src/settings/validation/authority.ts +21 -19
  136. package/src/settings/validation/command.ts +22 -41
  137. package/src/settings/validation/error.ts +2 -8
  138. package/src/settings/validation/primitives.ts +46 -97
  139. package/src/settings/validation/projection.ts +8 -24
  140. package/src/settings/validation/registry.ts +33 -79
  141. package/src/surface-transfer/client.ts +6 -18
  142. package/src/surface-transfer/generated/fields.ts +3 -3
  143. package/src/surface-transfer/generated/protocol.ts +3 -3
  144. package/src/surface-transfer/generated/variant-fields.ts +1 -1
  145. package/src/surface-transfer/validation.ts +91 -86
  146. package/src/surfaces/client.ts +33 -55
  147. package/src/surfaces/generated/fields.ts +3 -3
  148. package/src/surfaces/generated/protocol.ts +1 -1
  149. package/src/surfaces/generated/variant-fields.ts +1 -1
  150. package/src/surfaces/validation.ts +227 -99
  151. package/src/transfer/client.ts +26 -60
  152. package/src/transfer/connection.ts +29 -51
  153. package/src/transfer/generated/fields.ts +7 -6
  154. package/src/transfer/generated/protocol.ts +13 -5
  155. package/src/transfer/generated/variant-fields.ts +1 -1
  156. package/src/transfer/index.ts +8 -1
  157. package/src/transfer/payload.ts +20 -35
  158. package/src/transfer/validation.ts +169 -119
  159. package/src/update/client.ts +86 -9
  160. package/src/update/controller.ts +264 -116
  161. package/src/update/direct.ts +3 -1
  162. package/src/update/generated/fields.ts +5 -4
  163. package/src/update/generated/protocol.ts +25 -9
  164. package/src/update/generated/variant-fields.ts +4 -2
  165. package/src/update/ports.ts +14 -6
  166. package/src/update/serialized.ts +36 -10
  167. package/src/update/validation.ts +118 -48
@@ -1,27 +1,55 @@
1
1
  import type {
2
2
  BridgeCredentialRef,
3
3
  BridgeServiceAction,
4
- BridgeServiceFailureCode,
5
4
  BridgeServiceOutcome,
6
5
  BridgeServiceOwnership,
7
6
  BridgeServiceRequest,
8
7
  BridgeServiceState,
9
8
  BridgeServiceTransitionReceipt,
10
9
  } from "./generated/protocol.ts";
11
- import { BRIDGE_SERVICE_OWNERSHIPS } from "./generated/protocol.ts";
10
+ import {
11
+ BRIDGE_SERVICE_ADMISSIONS,
12
+ BRIDGE_SERVICE_ADMITTED_OBSERVATIONS,
13
+ BRIDGE_SERVICE_FAILURE_CODES,
14
+ BRIDGE_SERVICE_FAILURE_STATE,
15
+ BRIDGE_SERVICE_INCARNATION_STATES,
16
+ BRIDGE_SERVICE_OWNERSHIPS,
17
+ BRIDGE_SERVICE_UNIT_OUTCOMES,
18
+ } from "./generated/protocol.ts";
12
19
  import { opaqueId } from "./validation/base.ts";
13
20
 
14
21
  export interface BridgeServiceSupervisorPort {
15
- perform(
16
- request: BridgeServiceRequest,
17
- ): Promise<unknown> | unknown;
22
+ perform(request: BridgeServiceRequest): Promise<unknown> | unknown;
23
+ }
24
+
25
+ /**
26
+ * Monotonic service incarnation.
27
+ *
28
+ * One incarnation covers one service attempt. It advances only when a commit
29
+ * starts an attempt (spawn, attach, restart or reconnect), never for a
30
+ * readiness observation of the running attempt and never for the attempt's
31
+ * end.
32
+ */
33
+ export type BridgeServiceIncarnation = number;
34
+
35
+ /**
36
+ * One admitted supervision action bound to the incarnation that admitted it.
37
+ *
38
+ * A runtime-local token, not a wire shape: `begin` returns it and `commit`
39
+ * accepts its observation only while that incarnation is still current.
40
+ */
41
+ export interface BridgeServiceAdmission {
42
+ readonly incarnation: BridgeServiceIncarnation;
43
+ readonly action: BridgeServiceAction;
18
44
  }
19
45
 
20
46
  export class BridgeSupervisionError extends Error {
21
47
  readonly code:
22
48
  | "lifecycle_not_owned"
49
+ | "invalid_ownership"
23
50
  | "invalid_transition"
24
51
  | "invalid_observation"
52
+ | "stale_observation"
25
53
  | "adapter_failed";
26
54
 
27
55
  constructor(code: BridgeSupervisionError["code"]) {
@@ -35,10 +63,11 @@ export class BridgeServiceRuntime {
35
63
  readonly #ownership: BridgeServiceOwnership;
36
64
  #state: BridgeServiceState = "absent";
37
65
  #generation = 0;
66
+ #incarnation = 0;
38
67
 
39
68
  constructor(ownership: BridgeServiceOwnership) {
40
69
  if (!BRIDGE_SERVICE_OWNERSHIPS.includes(ownership)) {
41
- throw new BridgeSupervisionError("invalid_transition");
70
+ throw new BridgeSupervisionError("invalid_ownership");
42
71
  }
43
72
  this.#ownership = ownership;
44
73
  }
@@ -52,12 +81,10 @@ export class BridgeServiceRuntime {
52
81
  action: BridgeServiceAction,
53
82
  credentialRef?: BridgeCredentialRef,
54
83
  ): Promise<BridgeServiceTransitionReceipt> {
55
- this.#admit(action);
84
+ const admission = this.begin(action);
56
85
  const request: BridgeServiceRequest = {
57
86
  action,
58
- credentialRef: credentialRef === undefined
59
- ? null
60
- : opaqueId(credentialRef),
87
+ credentialRef: credentialRef === undefined ? null : opaqueId(credentialRef),
61
88
  };
62
89
  let rawOutcome: unknown;
63
90
  try {
@@ -65,18 +92,59 @@ export class BridgeServiceRuntime {
65
92
  } catch {
66
93
  throw new BridgeSupervisionError("adapter_failed");
67
94
  }
68
- return this.observe(action, rawOutcome);
95
+ return this.commit(admission, rawOutcome);
69
96
  }
70
97
 
71
- observe(
72
- action: BridgeServiceAction,
73
- value: unknown,
74
- ): BridgeServiceTransitionReceipt {
98
+ /**
99
+ * Admits one action whose observation arrives after the call returns.
100
+ *
101
+ * The returned admission carries the service incarnation that admitted it, so
102
+ * the observation must be committed through `commit`. A commit that starts a
103
+ * new attempt in between supersedes the admission and the delayed observation
104
+ * is rejected instead of being reported for the later service incarnation.
105
+ * Readiness observations of one attempt share its incarnation, so overlapping
106
+ * probes of that attempt all stay committable.
107
+ */
108
+ begin(action: BridgeServiceAction): BridgeServiceAdmission {
75
109
  this.#admit(action);
110
+ return { incarnation: this.#incarnation, action };
111
+ }
112
+
113
+ /**
114
+ * Commits the observation for an action admitted by `begin`.
115
+ *
116
+ * Rejects the observation when a commit started a new service attempt after
117
+ * admission, or when the action is no longer valid in the current state.
118
+ * Neither a readiness observation nor the end of an attempt changes the
119
+ * incarnation, so a probe and a shutdown admitted together both land.
120
+ */
121
+ commit(admission: BridgeServiceAdmission, value: unknown): BridgeServiceTransitionReceipt {
122
+ if (admission.incarnation !== this.#incarnation) {
123
+ throw new BridgeSupervisionError("stale_observation");
124
+ }
125
+ this.#admit(admission.action);
126
+ return this.#apply(admission.action, value);
127
+ }
128
+
129
+ /**
130
+ * Commits an adapter observation that is current when the call is made.
131
+ *
132
+ * This admits and commits in one step, so it cannot carry an observation that
133
+ * started before the call. Use `begin` and `commit` for one that completes
134
+ * later.
135
+ */
136
+ observe(action: BridgeServiceAction, value: unknown): BridgeServiceTransitionReceipt {
137
+ return this.commit(this.begin(action), value);
138
+ }
139
+
140
+ #apply(action: BridgeServiceAction, value: unknown): BridgeServiceTransitionReceipt {
76
141
  const outcome = parseOutcome(value);
77
142
  const current = transitionState(action, outcome);
78
143
  const generation = this.#generation + 1;
79
- if (!Number.isSafeInteger(generation)) {
144
+ const incarnation = BRIDGE_SERVICE_INCARNATION_STATES.includes(current)
145
+ ? this.#incarnation + 1
146
+ : this.#incarnation;
147
+ if (!Number.isSafeInteger(generation) || !Number.isSafeInteger(incarnation)) {
80
148
  throw new BridgeSupervisionError("invalid_transition");
81
149
  }
82
150
  const receipt = {
@@ -88,49 +156,18 @@ export class BridgeServiceRuntime {
88
156
  outcome,
89
157
  };
90
158
  this.#generation = generation;
159
+ this.#incarnation = incarnation;
91
160
  this.#state = current;
92
161
  return receipt;
93
162
  }
94
163
 
95
164
  #admit(action: BridgeServiceAction): void {
96
- const owned = this.#ownership === "ownedLocal";
97
- let admitted = false;
98
- switch (action) {
99
- case "spawn":
100
- admitted = owned &&
101
- ["absent", "stopped", "failed"].includes(this.#state);
102
- break;
103
- case "attach":
104
- admitted = !owned &&
105
- ["absent", "stopped", "failed"].includes(this.#state);
106
- break;
107
- case "checkReadiness":
108
- admitted = [
109
- "starting",
110
- "attaching",
111
- "awaitingReadiness",
112
- "restarting",
113
- "reconnecting",
114
- "ready",
115
- ].includes(this.#state);
116
- break;
117
- case "restart":
118
- admitted = owned && ["ready", "failed"].includes(this.#state);
119
- break;
120
- case "reconnect":
121
- admitted = ["ready", "failed", "stopped"].includes(this.#state);
122
- break;
123
- case "shutdown":
124
- admitted = owned && !["absent", "stopped"].includes(this.#state);
125
- break;
126
- }
127
- if (admitted) {
165
+ const rule = BRIDGE_SERVICE_ADMISSIONS[action];
166
+ const ownershipAdmitted = rule.ownerships.includes(this.#ownership);
167
+ if (ownershipAdmitted && rule.states.includes(this.#state)) {
128
168
  return;
129
169
  }
130
- if (
131
- !owned &&
132
- ["spawn", "restart", "shutdown"].includes(action)
133
- ) {
170
+ if (!ownershipAdmitted && rule.requiresOwnedLifecycle) {
134
171
  throw new BridgeSupervisionError("lifecycle_not_owned");
135
172
  }
136
173
  throw new BridgeSupervisionError("invalid_transition");
@@ -142,63 +179,33 @@ function transitionState(
142
179
  outcome: BridgeServiceOutcome,
143
180
  ): BridgeServiceState {
144
181
  if (typeof outcome === "object") {
145
- return "failed";
146
- }
147
- if (action === "checkReadiness" && outcome === "ready") {
148
- return "ready";
149
- }
150
- if (action === "checkReadiness" && outcome === "notReady") {
151
- return "awaitingReadiness";
182
+ return BRIDGE_SERVICE_FAILURE_STATE;
152
183
  }
153
- if (action === "shutdown" && outcome === "stopped") {
154
- return "stopped";
155
- }
156
- if (outcome === "accepted") {
157
- const accepted: Partial<Record<BridgeServiceAction, BridgeServiceState>> = {
158
- spawn: "starting",
159
- attach: "attaching",
160
- restart: "restarting",
161
- reconnect: "reconnecting",
162
- };
163
- const state = accepted[action];
164
- if (state !== undefined) {
165
- return state;
166
- }
184
+ const admitted = BRIDGE_SERVICE_ADMITTED_OBSERVATIONS.find(
185
+ ([candidate, observation]) => candidate === action && observation === outcome,
186
+ );
187
+ if (admitted === undefined) {
188
+ throw new BridgeSupervisionError("invalid_observation");
167
189
  }
168
- throw new BridgeSupervisionError("invalid_observation");
190
+ return admitted[2];
169
191
  }
170
192
 
171
193
  function parseOutcome(value: unknown): BridgeServiceOutcome {
172
- if (
173
- value === "accepted" ||
174
- value === "ready" ||
175
- value === "notReady" ||
176
- value === "stopped"
177
- ) {
178
- return value;
194
+ const unit = BRIDGE_SERVICE_UNIT_OUTCOMES.find((outcome) => outcome === value);
195
+ if (unit !== undefined) {
196
+ return unit;
179
197
  }
180
198
  if (
181
199
  typeof value === "object" &&
182
200
  value !== null &&
183
201
  !Array.isArray(value) &&
184
202
  Object.keys(value).length === 1 &&
185
- "failed" in value &&
186
- isFailureCode(value.failed)
203
+ "failed" in value
187
204
  ) {
188
- return { failed: value.failed };
205
+ const failed = BRIDGE_SERVICE_FAILURE_CODES.find((code) => code === value.failed);
206
+ if (failed !== undefined) {
207
+ return { failed };
208
+ }
189
209
  }
190
210
  throw new BridgeSupervisionError("invalid_observation");
191
211
  }
192
-
193
- function isFailureCode(value: unknown): value is BridgeServiceFailureCode {
194
- return typeof value === "string" &&
195
- [
196
- "spawnFailed",
197
- "attachFailed",
198
- "readinessFailed",
199
- "serviceExited",
200
- "restartFailed",
201
- "reconnectFailed",
202
- "shutdownFailed",
203
- ].includes(value);
204
- }
@@ -1,4 +1,6 @@
1
- import { BRIDGE_MAXIMUM_OPAQUE_ID_BYTES } from "../generated/protocol.ts";
1
+ import { isOpaqueId, matchesDomainIdRule } from "../../core/identifiers.ts";
2
+ import { checkWireFields, readWireRecord } from "../../core/record.ts";
3
+ import { BRIDGE_DOMAIN_ID_RULE } from "../generated/protocol.ts";
2
4
  export type BridgeProtocolValidationCode =
3
5
  | "unsupported_protocol_version"
4
6
  | "invalid_object"
@@ -34,10 +36,7 @@ export class BridgeProtocolValidationError extends Error {
34
36
  readonly code: BridgeProtocolValidationCode;
35
37
  readonly received: unknown;
36
38
 
37
- constructor(
38
- code: BridgeProtocolValidationCode,
39
- received: unknown,
40
- ) {
39
+ constructor(code: BridgeProtocolValidationCode, received: unknown) {
41
40
  super(`incompatible bridge protocol: ${code}`);
42
41
  this.name = "BridgeProtocolValidationError";
43
42
  this.code = code;
@@ -49,49 +48,28 @@ export interface BridgeCodec<T> {
49
48
  parse(value: unknown): T;
50
49
  }
51
50
 
52
- export function bridgeCodec<T>(
53
- parse: (value: unknown) => T,
54
- ): BridgeCodec<T> {
51
+ export function bridgeCodec<T>(parse: (value: unknown) => T): BridgeCodec<T> {
55
52
  return { parse };
56
53
  }
57
54
 
58
55
  export function record(
59
56
  value: unknown,
60
- required: readonly string[],
61
- optional: readonly string[] = [],
57
+ required: ReadonlyArray<string>,
58
+ optional: ReadonlyArray<string> = [],
62
59
  ): Record<string, unknown> {
63
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
64
- incompatible("invalid_object", value);
65
- }
66
- const result = value as Record<string, unknown>;
67
- const allowed = new Set([...required, ...optional]);
68
- for (const key of Object.keys(result)) {
69
- if (!allowed.has(key)) {
70
- incompatible("unknown_field", { key, value });
71
- }
72
- }
73
- for (const key of required) {
74
- if (!(key in result)) {
75
- incompatible("missing_field", { key, value });
76
- }
77
- }
60
+ const result = readWireRecord(value, () => incompatible("invalid_object", value));
61
+ checkWireFields(result, required, (code, key) => incompatible(code, { key, value }), optional);
78
62
  return result;
79
63
  }
80
64
 
81
- export function array(
82
- value: unknown,
83
- maximum: number,
84
- ): readonly unknown[] {
65
+ export function array(value: unknown, maximum: number): ReadonlyArray<unknown> {
85
66
  if (!Array.isArray(value) || value.length > maximum) {
86
67
  incompatible("invalid_array", value);
87
68
  }
88
69
  return value;
89
70
  }
90
71
 
91
- export function unique<T>(
92
- values: readonly T[],
93
- key: (value: T) => string,
94
- ): void {
72
+ export function unique<T>(values: ReadonlyArray<T>, key: (value: T) => string): void {
95
73
  const seen = new Set<string>();
96
74
  for (const value of values) {
97
75
  const identity = key(value);
@@ -103,36 +81,21 @@ export function unique<T>(
103
81
  }
104
82
 
105
83
  export function opaqueId(value: unknown): string {
106
- if (
107
- typeof value !== "string" ||
108
- new TextEncoder().encode(value).length > BRIDGE_MAXIMUM_OPAQUE_ID_BYTES ||
109
- !/^[a-z0-9._:-]+$/.test(value)
110
- ) {
84
+ if (!isOpaqueId(value)) {
111
85
  incompatible("invalid_id", value);
112
86
  }
113
87
  return value;
114
88
  }
115
89
 
116
90
  export function domainId(value: unknown): string {
117
- if (
118
- typeof value !== "string" ||
119
- new TextEncoder().encode(value).length > BRIDGE_MAXIMUM_OPAQUE_ID_BYTES ||
120
- !/^[a-z][a-z0-9_-]*(\.[a-z][a-z0-9_-]*)*$/.test(value)
121
- ) {
91
+ if (!matchesDomainIdRule(value, BRIDGE_DOMAIN_ID_RULE)) {
122
92
  incompatible("invalid_domain_id", value);
123
93
  }
124
94
  return value;
125
95
  }
126
96
 
127
- export function integer(
128
- value: unknown,
129
- minimum = 0,
130
- ): number {
131
- if (
132
- typeof value !== "number" ||
133
- !Number.isSafeInteger(value) ||
134
- value < minimum
135
- ) {
97
+ export function integer(value: unknown, minimum = 0): number {
98
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum) {
136
99
  incompatible("invalid_number", value);
137
100
  }
138
101
  return value;
@@ -140,25 +103,20 @@ export function integer(
140
103
 
141
104
  export function oneOf<const T extends string>(
142
105
  value: unknown,
143
- values: readonly T[],
106
+ values: ReadonlyArray<T>,
144
107
  code: BridgeProtocolValidationCode,
145
108
  ): T {
146
- if (typeof value !== "string" || !values.includes(value as T)) {
109
+ const match = values.find((candidate) => candidate === value);
110
+ if (match === undefined) {
147
111
  incompatible(code, value);
148
112
  }
149
- return value as T;
113
+ return match;
150
114
  }
151
115
 
152
- export function nullable<T>(
153
- value: unknown,
154
- parse: (value: unknown) => T,
155
- ): T | null {
116
+ export function nullable<T>(value: unknown, parse: (value: unknown) => T): T | null {
156
117
  return value === null ? null : parse(value);
157
118
  }
158
119
 
159
- export function incompatible(
160
- code: BridgeProtocolValidationCode,
161
- received: unknown,
162
- ): never {
120
+ export function incompatible(code: BridgeProtocolValidationCode, received: unknown): never {
163
121
  throw new BridgeProtocolValidationError(code, received);
164
122
  }
@@ -1,15 +1,12 @@
1
+ import { isRecord } from "../../core/record.ts";
1
2
  import { BRIDGE_FIELDS } from "../generated/fields.ts";
2
3
  import type {
3
4
  BridgeCancellationReceipt,
4
5
  BridgeJobTerminalEvent,
5
6
  BridgeProgressEvent,
6
7
  } from "../generated/protocol.ts";
7
- import {
8
- type BridgeCodec,
9
- incompatible,
10
- opaqueId,
11
- record,
12
- } from "./base.ts";
8
+ import { incompatible, opaqueId, record } from "./base.ts";
9
+ import type { BridgeCodec } from "./base.ts";
13
10
  import { parseBridgeFailure } from "./operations.ts";
14
11
 
15
12
  export function parseBridgeProgressEvent<P>(
@@ -58,11 +55,7 @@ function parseTerminalOutcome<S, D>(
58
55
  if (value === "cancelled") {
59
56
  return value;
60
57
  }
61
- const source = singleVariant(
62
- value,
63
- ["succeeded", "failed"],
64
- "unknown_job_outcome",
65
- );
58
+ const source = singleVariant(value, ["succeeded", "failed"], "unknown_job_outcome");
66
59
  if ("succeeded" in source) {
67
60
  return { succeeded: success.parse(source.succeeded) };
68
61
  }
@@ -73,32 +66,25 @@ function parseCancellationOutcome<D>(
73
66
  value: unknown,
74
67
  details: BridgeCodec<D>,
75
68
  ): BridgeCancellationReceipt<D>["outcome"] {
76
- if (
77
- value === "accepted" ||
78
- value === "alreadyTerminal" ||
79
- value === "unknown"
80
- ) {
69
+ if (value === "accepted" || value === "alreadyTerminal" || value === "unknown") {
81
70
  return value;
82
71
  }
83
- const source = singleVariant(
84
- value,
85
- ["rejected"],
86
- "unknown_cancellation_outcome",
87
- );
72
+ const source = singleVariant(value, ["rejected"], "unknown_cancellation_outcome");
88
73
  return { rejected: parseBridgeFailure(source.rejected, details) };
89
74
  }
90
75
 
91
76
  function singleVariant(
92
77
  value: unknown,
93
- keys: readonly string[],
78
+ variants: ReadonlyArray<string>,
94
79
  code: "unknown_job_outcome" | "unknown_cancellation_outcome",
95
80
  ): Record<string, unknown> {
96
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
81
+ if (!isRecord(value)) {
97
82
  incompatible(code, value);
98
83
  }
99
- const source = value as Record<string, unknown>;
84
+ const source = value;
100
85
  const present = Object.keys(source);
101
- if (present.length !== 1 || !keys.includes(present[0]!)) {
86
+ const [key] = present;
87
+ if (present.length !== 1 || key === undefined || !variants.includes(key)) {
102
88
  incompatible(code, value);
103
89
  }
104
90
  return source;
@@ -17,15 +17,17 @@ import {
17
17
  BRIDGE_PROTOCOL_VERSION,
18
18
  BRIDGE_READ_AUTHORITIES,
19
19
  BRIDGE_WRITE_AUTHORITIES,
20
- type BridgeConnectionReason,
21
- type BridgeConnectionState,
22
- type BridgeConnectionStatus,
23
- type BridgeDiagnostic,
24
- type BridgeHelloRequest,
25
- type BridgeHostDescriptor,
26
- type BridgeNegotiationReceipt,
27
- type DomainAuthorityDescriptor,
28
- type DomainCapabilityDescriptor,
20
+ } from "../generated/protocol.ts";
21
+ import type {
22
+ BridgeConnectionReason,
23
+ BridgeConnectionState,
24
+ BridgeConnectionStatus,
25
+ BridgeDiagnostic,
26
+ BridgeHelloRequest,
27
+ BridgeHostDescriptor,
28
+ BridgeNegotiationReceipt,
29
+ DomainAuthorityDescriptor,
30
+ DomainCapabilityDescriptor,
29
31
  } from "../generated/protocol.ts";
30
32
  import {
31
33
  array,
@@ -48,7 +50,9 @@ export function assertBridgeProtocolVersion(value: unknown): asserts value is 1
48
50
  export function parseBridgeHelloRequest(value: unknown): BridgeHelloRequest {
49
51
  const source = record(value, BRIDGE_FIELDS.BridgeHelloRequest);
50
52
  assertBridgeProtocolVersion(source.protocolVersion);
51
- const requestedDomains = array(source.requestedDomains, BRIDGE_MAXIMUM_REQUESTED_DOMAINS).map(domainId);
53
+ const requestedDomains = array(source.requestedDomains, BRIDGE_MAXIMUM_REQUESTED_DOMAINS).map(
54
+ domainId,
55
+ );
52
56
  unique(requestedDomains, String);
53
57
  return {
54
58
  protocolVersion: BRIDGE_PROTOCOL_VERSION,
@@ -80,9 +84,7 @@ export function parseBridgeNegotiationReceipt(
80
84
  unique(authorities, (item) => item.domainId);
81
85
  unique(diagnostics, (item) => item.diagnosticId);
82
86
 
83
- const capabilityDomains = new Set(
84
- capabilities.map((item) => item.domainId),
85
- );
87
+ const capabilityDomains = new Set(capabilities.map((item) => item.domainId));
86
88
  const writerScopes = new Set<string>();
87
89
  for (const authority of authorities) {
88
90
  if (!capabilityDomains.has(authority.domainId)) {
@@ -131,17 +133,9 @@ function parseHost(value: unknown): BridgeHostDescriptor {
131
133
 
132
134
  function parseConnectionStatus(value: unknown): BridgeConnectionStatus {
133
135
  const source = record(value, BRIDGE_FIELDS.BridgeConnectionStatus);
134
- const state = oneOf(
135
- source.state,
136
- BRIDGE_CONNECTION_STATES,
137
- "unknown_connection_state",
138
- );
136
+ const state = oneOf(source.state, BRIDGE_CONNECTION_STATES, "unknown_connection_state");
139
137
  const reason = nullable(source.reason, (candidate) =>
140
- oneOf(
141
- candidate,
142
- BRIDGE_CONNECTION_REASONS,
143
- "invalid_connection_status",
144
- )
138
+ oneOf(candidate, BRIDGE_CONNECTION_REASONS, "invalid_connection_status"),
145
139
  );
146
140
  if (!validConnectionReason(state, reason)) {
147
141
  incompatible("invalid_connection_status", value);
@@ -153,18 +147,15 @@ function validConnectionReason(
153
147
  state: BridgeConnectionState,
154
148
  reason: BridgeConnectionReason | null,
155
149
  ): boolean {
156
- // Generated from `BridgeConnectionStatus::ADMITTED_REASONS`. This used to be
157
- // an eleven-arm literal here, and Card 160 recorded it as the one rule that
158
- // could not be derived because the pairing exists in no type. That was
159
- // wrong: it exists in Rust, in a `matches!` arm, which `ts-rs` cannot carry
160
- // because it is a relation between two enums rather than a type. The two
161
- // copies agreed arm for arm — by maintenance, not by construction.
150
+ // Generated from `BridgeConnectionStatus::ADMITTED_REASONS` in Rust.
162
151
  return BRIDGE_ADMITTED_CONNECTION_REASONS[state].includes(reason);
163
152
  }
164
153
 
165
154
  function parseDomainCapability(value: unknown): DomainCapabilityDescriptor {
166
155
  const source = record(value, BRIDGE_FIELDS.DomainCapabilityDescriptor);
167
- const capabilities = array(source.capabilities, BRIDGE_MAXIMUM_CAPABILITIES_PER_DOMAIN).map(opaqueId);
156
+ const capabilities = array(source.capabilities, BRIDGE_MAXIMUM_CAPABILITIES_PER_DOMAIN).map(
157
+ opaqueId,
158
+ );
168
159
  if (capabilities.length === 0) {
169
160
  incompatible("invalid_array", value);
170
161
  }
@@ -197,18 +188,13 @@ function parseDomainAuthority(value: unknown): DomainAuthorityDescriptor {
197
188
  BRIDGE_EXECUTION_AUTHORITIES,
198
189
  "unknown_execution_authority",
199
190
  );
200
- const authoritativeRevision = nullable(
201
- source.authoritativeRevision,
202
- integer,
203
- );
204
- const ownsAnything = readAuthority !== "none" ||
205
- writeAuthority !== "none" ||
206
- executionAuthority !== "none";
207
- const revisionIsAuthoritative = readAuthority === "authoritative" ||
208
- writeAuthority === "authoritative";
191
+ const authoritativeRevision = nullable(source.authoritativeRevision, integer);
192
+ const ownsAnything =
193
+ readAuthority !== "none" || writeAuthority !== "none" || executionAuthority !== "none";
194
+ const revisionIsAuthoritative =
195
+ readAuthority === "authoritative" || writeAuthority === "authoritative";
209
196
  if (
210
- (availability === "offline" &&
211
- (ownsAnything || authoritativeRevision !== null)) ||
197
+ (availability === "offline" && (ownsAnything || authoritativeRevision !== null)) ||
212
198
  (authoritativeRevision !== null && !revisionIsAuthoritative)
213
199
  ) {
214
200
  incompatible("invalid_authority_descriptor", value);
@@ -230,8 +216,7 @@ function parseDiagnostic(value: unknown): BridgeDiagnostic {
230
216
  if (
231
217
  typeof source.message !== "string" ||
232
218
  source.message.length === 0 ||
233
- new TextEncoder().encode(source.message).length >
234
- BRIDGE_MAXIMUM_DIAGNOSTIC_MESSAGE_BYTES
219
+ new TextEncoder().encode(source.message).length > BRIDGE_MAXIMUM_DIAGNOSTIC_MESSAGE_BYTES
235
220
  ) {
236
221
  incompatible("invalid_message", source.message);
237
222
  }