@inflatable-cookie/longhorn 0.6.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 (133) 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/selection.ts +10 -8
  6. package/src/agent-control/shim.ts +149 -77
  7. package/src/bridge/generated/fields.ts +1 -1
  8. package/src/bridge/generated/protocol.ts +55 -4
  9. package/src/bridge/generated/variant-fields.ts +1 -1
  10. package/src/bridge/job.ts +49 -2
  11. package/src/bridge/runtime/connection.ts +11 -14
  12. package/src/bridge/stream/connection.ts +14 -23
  13. package/src/bridge/stream/tracker.ts +5 -0
  14. package/src/bridge/supervision.ts +102 -80
  15. package/src/bridge/validation/base.ts +7 -27
  16. package/src/bridge/validation/negotiation.ts +1 -6
  17. package/src/bridge/validation/operations.ts +2 -14
  18. package/src/commands/client.ts +16 -2
  19. package/src/commands/controller.ts +96 -58
  20. package/src/commands/generated/fields.ts +4 -4
  21. package/src/commands/generated/protocol.ts +24 -1
  22. package/src/commands/generated/variant-fields.ts +1 -1
  23. package/src/commands/keyboard.ts +4 -13
  24. package/src/commands/physical-code.ts +11 -0
  25. package/src/commands/ports.ts +2 -1
  26. package/src/commands/projectors.ts +52 -29
  27. package/src/commands/validation.ts +408 -188
  28. package/src/config/client.ts +3 -3
  29. package/src/config/generated/base.ts +22 -6
  30. package/src/config/generated/fields.ts +2 -1
  31. package/src/config/generated/label-template.ts +1 -1
  32. package/src/config/generated/labels.ts +1 -1
  33. package/src/config/generated/protocol.ts +1 -1
  34. package/src/config/generated/restore.ts +35 -12
  35. package/src/config/generated/variant-fields.ts +1 -1
  36. package/src/config/validation/commands.ts +11 -13
  37. package/src/config/validation/outcomes.ts +147 -46
  38. package/src/config/validation/primitives.ts +11 -39
  39. package/src/config/validation/projection.ts +44 -44
  40. package/src/core/connection.ts +124 -29
  41. package/src/core/controller-lifecycle.ts +144 -0
  42. package/src/core/generated/identifiers.ts +4 -0
  43. package/src/core/identifiers.ts +40 -0
  44. package/src/core/index.ts +10 -1
  45. package/src/core/json-value.ts +58 -0
  46. package/src/core/listeners.ts +35 -0
  47. package/src/core/record.ts +76 -0
  48. package/src/core/transport.ts +10 -1
  49. package/src/core/wire-copy.ts +1 -0
  50. package/src/history/client.ts +11 -7
  51. package/src/history/controller.ts +72 -74
  52. package/src/history/generated/fields.ts +2 -1
  53. package/src/history/generated/protocol.ts +8 -5
  54. package/src/history/generated/variant-fields.ts +1 -1
  55. package/src/history/ports.ts +7 -2
  56. package/src/history/validation.ts +15 -37
  57. package/src/history-tree/client.ts +15 -13
  58. package/src/history-tree/controller.ts +131 -90
  59. package/src/history-tree/generated/fields.ts +3 -1
  60. package/src/history-tree/generated/protocol.ts +43 -7
  61. package/src/history-tree/generated/variant-fields.ts +7 -1
  62. package/src/history-tree/ports.ts +9 -4
  63. package/src/history-tree/validation.ts +44 -35
  64. package/src/layout/generated/protocol.ts +2 -1
  65. package/src/layout/generated/variant-fields.ts +47 -0
  66. package/src/layout/index.ts +1 -1
  67. package/src/layout/ratio.ts +9 -2
  68. package/src/layout/validation.ts +88 -13
  69. package/src/licence/client.ts +11 -7
  70. package/src/licence/controller.ts +64 -43
  71. package/src/licence/generated/fields.ts +2 -1
  72. package/src/licence/generated/protocol.ts +8 -4
  73. package/src/licence/generated/variant-fields.ts +1 -1
  74. package/src/licence/key.ts +2 -6
  75. package/src/licence/ports.ts +7 -2
  76. package/src/licence/validation.ts +27 -20
  77. package/src/native-content/client.ts +32 -1
  78. package/src/native-content/generated/fields.ts +4 -4
  79. package/src/native-content/generated/protocol.ts +16 -5
  80. package/src/native-content/generated/variant-fields.ts +1 -1
  81. package/src/native-content/ports.ts +2 -1
  82. package/src/native-content/validation/base.ts +16 -46
  83. package/src/native-content/validation/messages.ts +3 -0
  84. package/src/notifications/client.ts +17 -39
  85. package/src/notifications/controller.ts +266 -165
  86. package/src/notifications/generated/fields.ts +2 -1
  87. package/src/notifications/generated/labels.ts +1 -1
  88. package/src/notifications/generated/protocol.ts +5 -1
  89. package/src/notifications/generated/variant-fields.ts +1 -1
  90. package/src/notifications/ports.ts +2 -1
  91. package/src/notifications/tone.ts +1 -1
  92. package/src/notifications/validation.ts +41 -51
  93. package/src/operation/bridge.ts +79 -19
  94. package/src/operation/client.ts +17 -45
  95. package/src/operation/controller.ts +38 -59
  96. package/src/operation/generated/fields.ts +2 -1
  97. package/src/operation/generated/labels.ts +1 -1
  98. package/src/operation/generated/protocol.ts +5 -1
  99. package/src/operation/generated/variant-fields.ts +1 -1
  100. package/src/operation/ports.ts +2 -1
  101. package/src/operation/validation.ts +48 -50
  102. package/src/settings/connection.ts +10 -14
  103. package/src/settings/generated/fields.ts +2 -1
  104. package/src/settings/generated/protocol.ts +5 -1
  105. package/src/settings/generated/variant-fields.ts +1 -1
  106. package/src/settings/validation/authority.ts +2 -2
  107. package/src/settings/validation/command.ts +5 -4
  108. package/src/settings/validation/primitives.ts +32 -67
  109. package/src/settings/validation/registry.ts +13 -11
  110. package/src/surface-transfer/generated/fields.ts +1 -1
  111. package/src/surface-transfer/generated/protocol.ts +3 -3
  112. package/src/surface-transfer/generated/variant-fields.ts +1 -1
  113. package/src/surface-transfer/validation.ts +76 -53
  114. package/src/surfaces/client.ts +26 -38
  115. package/src/surfaces/generated/fields.ts +1 -1
  116. package/src/surfaces/generated/protocol.ts +1 -1
  117. package/src/surfaces/generated/variant-fields.ts +1 -1
  118. package/src/surfaces/validation.ts +198 -61
  119. package/src/transfer/connection.ts +25 -39
  120. package/src/transfer/generated/fields.ts +2 -1
  121. package/src/transfer/generated/protocol.ts +9 -1
  122. package/src/transfer/generated/variant-fields.ts +1 -1
  123. package/src/transfer/index.ts +8 -1
  124. package/src/transfer/payload.ts +12 -9
  125. package/src/transfer/validation.ts +146 -60
  126. package/src/update/client.ts +43 -16
  127. package/src/update/controller.ts +187 -104
  128. package/src/update/generated/fields.ts +2 -1
  129. package/src/update/generated/protocol.ts +19 -7
  130. package/src/update/generated/variant-fields.ts +3 -2
  131. package/src/update/ports.ts +11 -7
  132. package/src/update/serialized.ts +8 -6
  133. package/src/update/validation.ts +18 -28
@@ -1,4 +1,5 @@
1
- import { isRecord } from "../core/record.ts";
1
+ import { isOpaqueId } from "../core/identifiers.ts";
2
+ import { checkWireFields, readWireRecord, wireVariantFields } from "../core/record.ts";
2
3
  import {
3
4
  HISTORY_TREE_VARIANT_FIELDS,
4
5
  HISTORY_TREE_VARIANT_FIELDS_DISCRIMINANTS,
@@ -12,6 +13,8 @@ import {
12
13
  FORK_HISTORY_PATH_FLOORS,
13
14
  FORK_HISTORY_PATH_TARGETS,
14
15
  FORK_HISTORY_PRUNE_STATUSES,
16
+ FORK_HISTORY_DELETE_STATUSES,
17
+ FORK_HISTORY_RETENTION_REJECTION_CODES,
15
18
  FORK_HISTORY_PROTOCOL_VERSION,
16
19
  MAXIMUM_FORK_HISTORY_PAGE_SIZE,
17
20
  } from "./generated/protocol.ts";
@@ -23,6 +26,7 @@ import type {
23
26
  ForkDeleteContinuationCommand,
24
27
  ForkPruneCommand,
25
28
  ForkPruneResult,
29
+ ForkDeleteResult,
26
30
  ForkRemovalReceiptProjection,
27
31
  ForkChangedEvent,
28
32
  ForkNavigationCommand,
@@ -94,8 +98,7 @@ export function assertForkPathPage(value: unknown): asserts value is ForkPathPag
94
98
  optionalId(root.branchId, "$.branchId");
95
99
  optionalId(root.headEntryId, "$.headEntryId");
96
100
  integer(root.precedingContinuationCount, "$.precedingContinuationCount");
97
- // Card 191. The floor tells a renderer whether to draw an origin row; a
98
- // nested run says `anchor` and means "draw nothing, it is already above".
101
+ // An anchor floor refers to the entry already drawn above a nested run.
99
102
  const floor = object(root.floor, "$.floor");
100
103
  oneOf(floor.kind, "$.floor.kind", FORK_HISTORY_PATH_FLOORS);
101
104
  exact(floor, "$.floor", variantFields("ForkPathFloorProjection", floor, "$.floor"));
@@ -258,10 +261,8 @@ function noPayload(value: unknown): void {
258
261
  visit(value, "$");
259
262
  }
260
263
  function object(value: unknown, path: string): Record<string, unknown> {
261
- if (!isRecord(value)) {
262
- fail(path, "expected object");
263
- }
264
- return value;
264
+ const result = readWireRecord(value, () => fail(path, "expected object"));
265
+ return result;
265
266
  }
266
267
  function array(value: unknown, path: string): Array<unknown> {
267
268
  if (!Array.isArray(value)) {
@@ -274,11 +275,9 @@ function exact(
274
275
  path: string,
275
276
  expected: ReadonlyArray<string>,
276
277
  ): void {
277
- const actual = Object.keys(value).sort();
278
- const wanted = [...expected].sort();
279
- if (actual.length !== wanted.length || actual.some((key, index) => key !== wanted[index])) {
280
- fail(path, `unexpected keys: ${actual.join(",")}`);
281
- }
278
+ checkWireFields(value, expected, () =>
279
+ fail(path, `unexpected keys: ${Object.keys(value).sort().join(",")}`),
280
+ );
282
281
  }
283
282
  function protocol(value: unknown, path: string): void {
284
283
  if (value !== FORK_HISTORY_PROTOCOL_VERSION) {
@@ -302,9 +301,8 @@ function string(value: unknown, path: string): asserts value is string {
302
301
  }
303
302
  }
304
303
  function id(value: unknown, path: string): void {
305
- string(value, path);
306
- if (value.length === 0) {
307
- fail(path, "expected non-empty id");
304
+ if (!isOpaqueId(value)) {
305
+ fail(path, "expected bounded lowercase opaque id");
308
306
  }
309
307
  }
310
308
  function optionalId(value: unknown, path: string): void {
@@ -428,8 +426,28 @@ export function assertForkPruneCommand(value: unknown): asserts value is ForkPru
428
426
  integer(root.expectedRevision, "$.expectedRevision");
429
427
  // The budget bounds the unprotected share, and a zero budget is rejected by
430
428
  // the authority rather than treated as "remove everything unprotected".
431
- positive(root.maximumEntries, "$.maximumEntries");
432
- positive(root.maximumEncodedWeight, "$.maximumEncodedWeight");
429
+ integer(root.maximumEntries, "$.maximumEntries");
430
+ integer(root.maximumEncodedWeight, "$.maximumEncodedWeight");
431
+ }
432
+
433
+ function assertRetentionRejection(value: unknown): void {
434
+ const rejection = object(value, "$.rejection");
435
+ exact(rejection, "$.rejection", HISTORY_TREE_FIELDS.ForkRetentionRejectionProjection);
436
+ oneOf(rejection.code, "$.rejection.code", FORK_HISTORY_RETENTION_REJECTION_CODES);
437
+ string(rejection.detail, "$.rejection.detail");
438
+ boolean(rejection.refreshRequired, "$.rejection.refreshRequired");
439
+ }
440
+
441
+ export function assertForkDeleteResult(value: unknown): asserts value is ForkDeleteResult {
442
+ noPayload(value);
443
+ const root = object(value, "$");
444
+ oneOf(root.status, "$.status", FORK_HISTORY_DELETE_STATUSES);
445
+ exact(root, "$", variantFields("ForkDeleteResult", root, "$"));
446
+ if (root.status === "deleted") {
447
+ assertForkRemovalReceipt(root.receipt);
448
+ } else {
449
+ assertRetentionRejection(root.rejection);
450
+ }
433
451
  }
434
452
 
435
453
  export function assertForkPruneResult(value: unknown): asserts value is ForkPruneResult {
@@ -439,30 +457,21 @@ export function assertForkPruneResult(value: unknown): asserts value is ForkPrun
439
457
  exact(root, "$", variantFields("ForkPruneResult", root, "$"));
440
458
  if (root.status === "pruned") {
441
459
  assertForkRemovalReceipt(root.receipt);
460
+ } else if (root.status === "rejected") {
461
+ assertRetentionRejection(root.rejection);
442
462
  }
443
463
  }
444
464
 
445
- /**
446
- * Allowed keys for one variant, from the generated map.
447
- *
448
- * A missing entry means the generator failed to read the union, not that a
449
- * consumer sent something odd — every caller runs `oneOf` over the
450
- * discriminant first, so an unknown one is already rejected by then. Failing
451
- * loudly beats defaulting to a key list, which is how `checkoutBranchRoot`
452
- * shipped rejecting its own `branchId`.
453
- */
454
465
  function variantFields(
455
466
  type: string,
456
467
  object: Record<string, unknown>,
457
468
  path: string,
458
469
  ): ReadonlyArray<string> {
459
- const discriminant = object[HISTORY_TREE_VARIANT_FIELDS_DISCRIMINANTS[type] ?? "kind"];
460
- const fields =
461
- typeof discriminant === "string"
462
- ? HISTORY_TREE_VARIANT_FIELDS[type]?.[discriminant]
463
- : undefined;
464
- if (fields === undefined) {
465
- fail(path, `no generated fields for ${type}.${String(discriminant)}`);
466
- }
467
- return fields;
470
+ return wireVariantFields(
471
+ HISTORY_TREE_VARIANT_FIELDS,
472
+ HISTORY_TREE_VARIANT_FIELDS_DISCRIMINANTS,
473
+ type,
474
+ object,
475
+ (discriminant) => fail(path, `no generated fields for ${type}.${String(discriminant)}`),
476
+ );
468
477
  }
@@ -1,6 +1,7 @@
1
- // @generated by `effigy generate:layout`; do not edit.
1
+ // @generated by `effigy generate:bindings`; do not edit.
2
2
  // Rust serde types are the wire authority.
3
3
 
4
+ export const LAYOUT_RATIO_ONE_MILLIONTHS = 1000000 as const;
4
5
  export const LAYOUT_PROTOCOL_VERSION = 1 as const;
5
6
  export const LAYOUT_MUTATION_COMMAND_KINDS = ["create_panel","close_panel","activate_panel","reorder_region","move_panel","set_sizing_slot","set_region_collapsed"] as const;
6
7
  export const LAYOUT_MUTATION_OUTCOME_KINDS = ["panel_created","panel_closed","panel_activated","region_reordered","panel_moved","sizing_slot_set","region_collapsed_set"] as const;
@@ -0,0 +1,47 @@
1
+ // @generated by `effigy generate:bindings`; do not edit.
2
+ // Allowed field names per tagged-union variant, from the Rust enums.
3
+ // Keyed by type, then by discriminant. The discriminant itself is in
4
+ // each list, because `exact()` compares every key.
5
+
6
+ export const LAYOUT_VARIANT_FIELDS: Record<string, Record<string, readonly string[]>> = {
7
+ "PlacementSelector": {
8
+ "region": ["kind", "id"],
9
+ "family": ["kind", "id"],
10
+ },
11
+ "PanelInstancePolicy": {
12
+ "singleton": ["kind"],
13
+ "one_per_surface": ["kind"],
14
+ "bounded": ["kind", "maximum_per_document", "maximum_per_surface"],
15
+ "multiple": ["kind"],
16
+ },
17
+ "SurfacePresentation": {
18
+ "regional": ["kind"],
19
+ "focused_panel": ["kind", "panel_definition_id"],
20
+ },
21
+ "LayoutMutationCommand": {
22
+ "create_panel": ["kind", "panel_instance_id", "panel_definition_id", "surface_id", "region_id", "insertion_index"],
23
+ "close_panel": ["kind", "panel_instance_id"],
24
+ "activate_panel": ["kind", "panel_instance_id"],
25
+ "reorder_region": ["kind", "surface_id", "region_id", "panel_instance_ids"],
26
+ "move_panel": ["kind", "panel_instance_id", "target_surface_id", "target_region_id", "insertion_index"],
27
+ "set_sizing_slot": ["kind", "surface_id", "sizing_slot_id", "ratio"],
28
+ "set_region_collapsed": ["kind", "surface_id", "region_id", "collapsed"],
29
+ },
30
+ "LayoutMutationOutcome": {
31
+ "panel_created": ["kind", "panel_instance_id", "surface_id", "region_id", "insertion_index"],
32
+ "panel_closed": ["kind", "panel_instance_id", "surface_id", "region_id", "former_index"],
33
+ "panel_activated": ["kind", "panel_instance_id", "surface_id", "region_id", "previous_active_panel_instance_id"],
34
+ "region_reordered": ["kind", "surface_id", "region_id", "panel_instance_ids"],
35
+ "panel_moved": ["kind", "panel_instance_id", "source_surface_id", "source_region_id", "former_index", "target_surface_id", "target_region_id", "insertion_index"],
36
+ "sizing_slot_set": ["kind", "surface_id", "sizing_slot_id", "previous_ratio", "committed_ratio"],
37
+ "region_collapsed_set": ["kind", "surface_id", "region_id", "previous_collapsed", "committed_collapsed"],
38
+ },
39
+ };
40
+
41
+ export const LAYOUT_VARIANT_FIELDS_DISCRIMINANTS: Record<string, string> = {
42
+ "PlacementSelector": "kind",
43
+ "PanelInstancePolicy": "kind",
44
+ "SurfacePresentation": "kind",
45
+ "LayoutMutationCommand": "kind",
46
+ "LayoutMutationOutcome": "kind",
47
+ };
@@ -1,4 +1,4 @@
1
1
  export * from "./generated/protocol.ts";
2
2
  export * from "./validation.ts";
3
- export * from "./ratio.ts";
3
+ export { layoutRatioFromMillionths, layoutRatioToUnitInterval } from "./ratio.ts";
4
4
  export * from "./visibility.ts";
@@ -1,9 +1,12 @@
1
+ import { LAYOUT_RATIO_ONE_MILLIONTHS } from "./generated/protocol.ts";
1
2
  import type { LayoutRatio } from "./generated/protocol.ts";
2
3
 
3
- export const LAYOUT_RATIO_ONE_MILLIONTHS = 1_000_000;
4
+ export function isLayoutRatio(value: unknown): value is LayoutRatio {
5
+ return typeof value === "number" && ratioInRange(value);
6
+ }
4
7
 
5
8
  export function layoutRatioFromMillionths(value: number): LayoutRatio {
6
- if (!Number.isSafeInteger(value) || value < 0 || value > LAYOUT_RATIO_ONE_MILLIONTHS) {
9
+ if (!ratioInRange(value)) {
7
10
  throw new RangeError(
8
11
  `layout ratio must be an integer from 0 through ${LAYOUT_RATIO_ONE_MILLIONTHS}; received ${String(value)}`,
9
12
  );
@@ -14,3 +17,7 @@ export function layoutRatioFromMillionths(value: number): LayoutRatio {
14
17
  export function layoutRatioToUnitInterval(value: LayoutRatio): number {
15
18
  return layoutRatioFromMillionths(value) / LAYOUT_RATIO_ONE_MILLIONTHS;
16
19
  }
20
+
21
+ function ratioInRange(value: number): boolean {
22
+ return Number.isSafeInteger(value) && value >= 0 && value <= LAYOUT_RATIO_ONE_MILLIONTHS;
23
+ }
@@ -1,3 +1,9 @@
1
+ import { checkWireFields, isRecord, unsigned32, wireVariantFields } from "../core/record.ts";
2
+ import {
3
+ LAYOUT_VARIANT_FIELDS,
4
+ LAYOUT_VARIANT_FIELDS_DISCRIMINANTS,
5
+ } from "./generated/variant-fields.ts";
6
+ import { isLayoutRatio } from "./ratio.ts";
1
7
  import {
2
8
  LAYOUT_MUTATION_COMMAND_KINDS,
3
9
  LAYOUT_MUTATION_OUTCOME_KINDS,
@@ -20,8 +26,8 @@ export class LayoutProtocolValidationError extends Error {
20
26
  readonly code: LayoutProtocolValidationCode;
21
27
  readonly received: unknown;
22
28
 
23
- constructor(code: LayoutProtocolValidationCode, received: unknown) {
24
- super(message(code, received));
29
+ constructor(code: LayoutProtocolValidationCode, received: unknown, detail?: string) {
30
+ super(detail ?? message(code, received));
25
31
  this.name = "LayoutProtocolValidationError";
26
32
  this.code = code;
27
33
  this.received = received;
@@ -39,13 +45,23 @@ export function assertLayoutProtocolVersion(
39
45
  export function assertValidLayoutMutationCommand(
40
46
  value: unknown,
41
47
  ): asserts value is LayoutMutationCommand {
42
- assertKnownKind(value, LAYOUT_MUTATION_COMMAND_KINDS, "unknown_command");
48
+ validateMutation(
49
+ value,
50
+ LAYOUT_MUTATION_COMMAND_KINDS,
51
+ "LayoutMutationCommand",
52
+ "unknown_command",
53
+ );
43
54
  }
44
55
 
45
56
  export function assertValidLayoutMutationOutcome(
46
57
  value: unknown,
47
58
  ): asserts value is LayoutMutationOutcome {
48
- assertKnownKind(value, LAYOUT_MUTATION_OUTCOME_KINDS, "unknown_outcome");
59
+ validateMutation(
60
+ value,
61
+ LAYOUT_MUTATION_OUTCOME_KINDS,
62
+ "LayoutMutationOutcome",
63
+ "unknown_outcome",
64
+ );
49
65
  }
50
66
 
51
67
  export function assertValidLayoutMutationRejectionCode(
@@ -59,20 +75,79 @@ export function assertValidLayoutMutationRejectionCode(
59
75
  }
60
76
  }
61
77
 
62
- function assertKnownKind(
78
+ type MutationFields<Variant> = Variant extends { kind: string }
79
+ ? Exclude<keyof Variant, "kind">
80
+ : never;
81
+
82
+ const mutationFields = {
83
+ panel_instance_id: isString,
84
+ panel_definition_id: isString,
85
+ surface_id: isString,
86
+ region_id: isString,
87
+ target_surface_id: isString,
88
+ target_region_id: isString,
89
+ source_surface_id: isString,
90
+ source_region_id: isString,
91
+ sizing_slot_id: isString,
92
+ insertion_index: unsigned32,
93
+ former_index: unsigned32,
94
+ panel_instance_ids: (value) => Array.isArray(value) && isStringList(value),
95
+ ratio: isLayoutRatio,
96
+ previous_ratio: isLayoutRatio,
97
+ committed_ratio: isLayoutRatio,
98
+ previous_active_panel_instance_id: (value) => value === null || isString(value),
99
+ collapsed: isBoolean,
100
+ previous_collapsed: isBoolean,
101
+ committed_collapsed: isBoolean,
102
+ } satisfies Record<
103
+ MutationFields<LayoutMutationCommand | LayoutMutationOutcome>,
104
+ (value: unknown) => boolean
105
+ >;
106
+
107
+ function validateMutation(
63
108
  value: unknown,
64
109
  known: ReadonlyArray<string>,
110
+ type: "LayoutMutationCommand" | "LayoutMutationOutcome",
65
111
  code: "unknown_command" | "unknown_outcome",
66
- ): asserts value is Record<"kind", string> {
67
- if (
68
- typeof value !== "object" ||
69
- value === null ||
70
- !("kind" in value) ||
71
- typeof value.kind !== "string" ||
72
- !known.includes(value.kind)
73
- ) {
112
+ ): void {
113
+ if (!isRecord(value) || typeof value.kind !== "string" || !known.includes(value.kind)) {
74
114
  throw new LayoutProtocolValidationError(code, value);
75
115
  }
116
+ const keys = wireVariantFields(
117
+ LAYOUT_VARIANT_FIELDS,
118
+ LAYOUT_VARIANT_FIELDS_DISCRIMINANTS,
119
+ type,
120
+ value,
121
+ () => {
122
+ throw new LayoutProtocolValidationError(code, value);
123
+ },
124
+ );
125
+ checkWireFields(value, keys, (issue, field) => {
126
+ const detail = issue === "unknown_field" ? "unknown field" : "missing field";
127
+ throw new LayoutProtocolValidationError(code, value, `${type}.${field}: ${detail}`);
128
+ });
129
+ for (const [field, validate] of Object.entries(mutationFields)) {
130
+ if (keys.includes(field) && !validate(value[field])) {
131
+ throw new LayoutProtocolValidationError(code, value, `${type}.${field}: invalid value`);
132
+ }
133
+ }
134
+ }
135
+
136
+ function isString(value: unknown): value is string {
137
+ return typeof value === "string";
138
+ }
139
+
140
+ function isBoolean(value: unknown): value is boolean {
141
+ return typeof value === "boolean";
142
+ }
143
+
144
+ function isStringList(value: ReadonlyArray<unknown>): boolean {
145
+ for (const item of value) {
146
+ if (!isString(item)) {
147
+ return false;
148
+ }
149
+ }
150
+ return true;
76
151
  }
77
152
 
78
153
  function message(code: LayoutProtocolValidationCode, received: unknown): string {
@@ -1,3 +1,5 @@
1
+ import { listenChecked } from "../core/connection.ts";
2
+ import type { ConnectionFailureReporter } from "../core/connection.ts";
1
3
  import type {
2
4
  LicenceActivateCommand,
3
5
  LicenceChangedEvent,
@@ -57,13 +59,15 @@ export class LicenceClient implements CheckedLicencePort {
57
59
  assertLicenceOutcome(value);
58
60
  return value;
59
61
  }
60
- async listen(listener: (event: LicenceChangedEvent) => void): Promise<LicenceUnlisten> {
61
- if (this.port.listen === undefined) {
62
- return () => {};
63
- }
64
- return this.port.listen((value) => {
65
- assertLicenceChangedEvent(value);
66
- listener(value);
62
+ listen(
63
+ listener: (event: LicenceChangedEvent) => void,
64
+ onFailure?: ConnectionFailureReporter,
65
+ ): Promise<LicenceUnlisten> {
66
+ return listenChecked({
67
+ listen: (receive) => this.port.listen?.(receive) ?? (() => {}),
68
+ validate: assertLicenceChangedEvent,
69
+ listener,
70
+ onFailure,
67
71
  });
68
72
  }
69
73
  }
@@ -1,3 +1,4 @@
1
+ import { ControllerLifecycle } from "../core/controller-lifecycle.ts";
1
2
  import { LicenceClient } from "./client.ts";
2
3
  import { LICENCE_PROTOCOL_VERSION } from "./generated/protocol.ts";
3
4
  import type {
@@ -10,7 +11,7 @@ import type {
10
11
  LicenceTrustBasisProjection,
11
12
  LicenceUsabilityProjection,
12
13
  } from "./generated/protocol.ts";
13
- import type { LicencePort, LicenceUnlisten } from "./ports.ts";
14
+ import type { LicencePort } from "./ports.ts";
14
15
 
15
16
  export type LicenceControllerStatus =
16
17
  | { readonly kind: "idle" }
@@ -60,18 +61,17 @@ export class LicenceController {
60
61
  #status: LicenceControllerStatus = { kind: "idle" };
61
62
  #snapshot?: LicenceSnapshot;
62
63
  #lastRejection: LicenceRejectionCode | undefined;
63
- #started = false;
64
- #lifecycle = 0;
64
+ readonly #lifecycle = new ControllerLifecycle();
65
65
  #commandSequence = 0;
66
+ #refreshRevision = 0;
66
67
  #pending = false;
67
- #unlisten: Array<LicenceUnlisten> = [];
68
68
 
69
69
  constructor(options: LicenceControllerOptions) {
70
70
  this.#client = new LicenceClient(options.port);
71
71
  }
72
72
 
73
73
  get status(): LicenceControllerStatus {
74
- return this.#status;
74
+ return this.#lifecycle.eventFailure ?? this.#status;
75
75
  }
76
76
  get snapshot(): LicenceSnapshot | undefined {
77
77
  return this.#snapshot;
@@ -174,50 +174,57 @@ export class LicenceController {
174
174
  return () => this.#observers.delete(observer);
175
175
  }
176
176
 
177
- async start(): Promise<void> {
178
- if (this.#started) {
179
- return;
180
- }
181
- this.#started = true;
182
- const lifecycle = ++this.#lifecycle;
183
- this.#setStatus({ kind: "loading" });
184
- try {
185
- const unlisten = await this.#client.listen(() => void this.refresh());
186
- if (!this.#started || lifecycle !== this.#lifecycle) {
187
- await unlisten();
188
- return;
189
- }
190
- this.#unlisten.push(unlisten);
191
- await this.refresh();
192
- } catch (error) {
193
- if (this.#started && lifecycle === this.#lifecycle) {
194
- this.#setStatus({ kind: "failed", error });
195
- }
196
- }
177
+ start(): Promise<void> {
178
+ return this.#lifecycle.start({
179
+ loading: () => this.#setStatus({ kind: "loading" }),
180
+ connect: async ({ isCurrent, own, reportFailure }) => {
181
+ const unlisten = await this.#client.listen(() => {
182
+ if (isCurrent()) {
183
+ void this.refresh();
184
+ }
185
+ }, reportFailure);
186
+ await own(unlisten);
187
+ if (isCurrent()) {
188
+ await this.refresh();
189
+ }
190
+ },
191
+ failed: (error) => this.#setStatus({ kind: "failed", error }),
192
+ });
197
193
  }
198
194
 
199
- async stop(): Promise<void> {
200
- this.#started = false;
201
- this.#lifecycle += 1;
202
- const unlisten = this.#unlisten;
203
- this.#unlisten = [];
204
- for (const stop of unlisten) {
205
- await stop();
206
- }
207
- this.#setStatus({ kind: "idle" });
195
+ /** Replaces the current subscription, including after a reported failure. */
196
+ restart(): Promise<void> {
197
+ return this.#lifecycle.restart(
198
+ this.status,
199
+ () => this.stop(),
200
+ () => this.start(),
201
+ );
202
+ }
203
+
204
+ stop(): Promise<void> {
205
+ return this.#lifecycle.stop(() => {
206
+ this.#pending = false;
207
+ this.#setStatus({ kind: "idle" });
208
+ });
208
209
  }
209
210
 
210
211
  async refresh(): Promise<void> {
211
- const lifecycle = this.#lifecycle;
212
+ if (!this.#lifecycle.active) {
213
+ return;
214
+ }
215
+ const lifecycle = this.#lifecycle.revision;
216
+ const revision = ++this.#refreshRevision;
217
+ const isCurrent = () =>
218
+ this.#lifecycle.isCurrent(lifecycle) && revision === this.#refreshRevision;
212
219
  try {
213
220
  const snapshot = await this.#client.snapshot();
214
- if (lifecycle !== this.#lifecycle) {
221
+ if (!isCurrent()) {
215
222
  return;
216
223
  }
217
224
  this.#snapshot = snapshot;
218
225
  this.#setStatus({ kind: "ready" });
219
226
  } catch (error) {
220
- if (lifecycle === this.#lifecycle) {
227
+ if (isCurrent()) {
221
228
  this.#setStatus({ kind: "failed", error });
222
229
  }
223
230
  }
@@ -239,7 +246,7 @@ export class LicenceController {
239
246
  }
240
247
 
241
248
  /**
242
- * Presents a credential. One command for all three routes, as Card 193 set.
249
+ * Presents a credential for any supported activation route.
243
250
  *
244
251
  * `label` is what the customer calls this machine in the seat list, asked
245
252
  * for at the only moment it can be without inventing a settings screen.
@@ -309,7 +316,10 @@ export class LicenceController {
309
316
  async #command(
310
317
  run: (client: LicenceClient, epoch: number) => Promise<LicenceOutcomeProjection>,
311
318
  ): Promise<LicenceCommandOutcome> {
312
- const commandSequence = ++this.#commandSequence;
319
+ if (!this.#lifecycle.active) {
320
+ // Nothing is sent and nothing is written: a stopped controller stays idle.
321
+ return { status: "failed", error: new LicenceControllerUnavailableError() };
322
+ }
313
323
  this.#lastRejection = undefined;
314
324
  const epoch = this.#snapshot?.authorityEpoch;
315
325
  if (epoch === undefined) {
@@ -319,7 +329,8 @@ export class LicenceController {
319
329
  this.#setStatus({ kind: "failed", error });
320
330
  return { status: "failed", error };
321
331
  }
322
- const lifecycle = this.#lifecycle;
332
+ const commandSequence = ++this.#commandSequence;
333
+ const lifecycle = this.#lifecycle.revision;
323
334
  this.#pending = true;
324
335
  this.#notify();
325
336
  try {
@@ -328,19 +339,21 @@ export class LicenceController {
328
339
  outcome.status === "rejected"
329
340
  ? { status: "rejected", snapshot: outcome.snapshot, code: outcome.code }
330
341
  : { status: "committed", snapshot: outcome.snapshot };
331
- if (lifecycle === this.#lifecycle && commandSequence === this.#commandSequence) {
342
+ if (lifecycle === this.#lifecycle.revision && commandSequence === this.#commandSequence) {
343
+ this.#refreshRevision += 1;
332
344
  this.#snapshot = outcome.snapshot;
333
345
  this.#lastRejection = result.status === "rejected" ? result.code : undefined;
334
346
  this.#setStatus({ kind: "ready" });
335
347
  }
336
348
  return result;
337
349
  } catch (error) {
338
- if (lifecycle === this.#lifecycle && commandSequence === this.#commandSequence) {
350
+ if (lifecycle === this.#lifecycle.revision && commandSequence === this.#commandSequence) {
351
+ this.#refreshRevision += 1;
339
352
  this.#setStatus({ kind: "failed", error });
340
353
  }
341
354
  return { status: "failed", error };
342
355
  } finally {
343
- if (lifecycle === this.#lifecycle && commandSequence === this.#commandSequence) {
356
+ if (lifecycle === this.#lifecycle.revision && commandSequence === this.#commandSequence) {
344
357
  this.#pending = false;
345
358
  this.#notify();
346
359
  }
@@ -358,3 +371,11 @@ export class LicenceController {
358
371
  }
359
372
  }
360
373
  }
374
+
375
+ /** A command was issued outside a started lifetime. */
376
+ export class LicenceControllerUnavailableError extends Error {
377
+ constructor() {
378
+ super("licence controller is not started");
379
+ this.name = "LicenceControllerUnavailableError";
380
+ }
381
+ }
@@ -1,4 +1,4 @@
1
- // @generated by `effigy generate:licence`; do not edit.
1
+ // @generated by `effigy generate:bindings`; do not edit.
2
2
  // Allowed field names per protocol type, from the Rust structs.
3
3
  // A `record()` given one of these rejects unknown and missing keys —
4
4
  // contract 010's Boundary Validation Target.
@@ -14,4 +14,5 @@ export const LICENCE_FIELDS = {
14
14
  "LicenceReleaseSeatCommand": ["protocolVersion", "authorityEpoch", "machineId"],
15
15
  "LicenceRenameSeatCommand": ["protocolVersion", "authorityEpoch", "machineId", "label"],
16
16
  "LicenceChangedEvent": ["protocolVersion", "authorityEpoch", "kind"],
17
+ "LicenceHostError": ["code", "message", "retryable"],
17
18
  } as const;
@@ -1,4 +1,4 @@
1
- // @generated by `effigy generate:licence`; do not edit.
1
+ // @generated by `effigy generate:bindings`; do not edit.
2
2
  // Rust serde types are the wire authority. Entitlements are opaque
3
3
  // ids: Longhorn answers "entitled?" and enumerates no features.
4
4
 
@@ -8,7 +8,7 @@ export const LICENCE_TRUST_BASIS_KINDS = ["offlineSignature","remoteAssertion"]
8
8
  export const LICENCE_CREDENTIAL_KINDS = ["key","accountToken","licenceFile"] as const;
9
9
  export const LICENCE_REJECTION_CODES = ["malformed","notRecognised","noSeatsFree","revoked","clockRefused","staleAuthority","seatNotFound","unreachable"] as const;
10
10
  export const LICENCE_OUTCOME_STATUSES = ["committed","rejected"] as const;
11
- export const LICENCE_CHANGED_KINDS = ["activated","deactivated","seatRelabelled","refreshed","usabilityChanged"] as const;
11
+ export const LICENCE_CHANGED_KINDS = ["activated","deactivated","seatReleased","seatRelabelled","refreshed","usabilityChanged"] as const;
12
12
 
13
13
  export type LicenceProtocolVersion = number;
14
14
 
@@ -138,7 +138,7 @@ key: string, } | { "kind": "accountToken",
138
138
  */
139
139
  token: string, } | { "kind": "licenceFile",
140
140
  /**
141
- * The file's bytes, base64. A `Vec<u8>` would arrive as an array of
141
+ * The file's bytes, padded RFC 4648 standard base64. A `Vec<u8>` would arrive as an array of
142
142
  * numbers, which is a poor way to move a file across a boundary.
143
143
  */
144
144
  contentsBase64: string, };
@@ -232,7 +232,7 @@ code: LicenceRejectionCode,
232
232
  */
233
233
  snapshot: LicenceSnapshot, };
234
234
 
235
- export type LicenceChangedKind = "activated" | "deactivated" | "seatRelabelled" | "refreshed" | "usabilityChanged";
235
+ export type LicenceChangedKind = "activated" | "deactivated" | "seatReleased" | "seatRelabelled" | "refreshed" | "usabilityChanged";
236
236
 
237
237
  export type LicenceChangedEvent = {
238
238
  /**
@@ -247,3 +247,7 @@ authorityEpoch: number,
247
247
  * Coarse invalidation category.
248
248
  */
249
249
  kind: LicenceChangedKind, };
250
+
251
+ export type LicenceHostErrorCode = "authorityUnavailable" | "stateUnavailable" | "eventPublication";
252
+
253
+ export type LicenceHostError = { "code": LicenceHostErrorCode, "message": string, "retryable": boolean, };
@@ -1,4 +1,4 @@
1
- // @generated by `effigy generate:licence`; do not edit.
1
+ // @generated by `effigy generate:bindings`; do not edit.
2
2
  // Allowed field names per tagged-union variant, from the Rust enums.
3
3
  // Keyed by type, then by discriminant. The discriminant itself is in
4
4
  // each list, because `exact()` compares every key.
@@ -1,12 +1,8 @@
1
1
  /**
2
2
  * The licence key format, in TypeScript.
3
3
  *
4
- * A second implementation of a format that already exists in Rust, which is
5
- * normally a mistake. It is here because Card 158 requires key entry to fail
6
- * locally: a mistyped key must never produce a message implying the key is
7
- * invalid, and telling those apart after a round trip is too late — the
8
- * authority answers `notRecognised`, which sends a customer to check their
9
- * purchase when they should check their typing.
4
+ * Check the format locally so a mistyped key can be corrected before the
5
+ * authority answers `notRecognised`.
10
6
  *
11
7
  * The two implementations are bound by `key-conformance.json`, generated from
12
8
  * the Rust and asserted against here. Neither can change the format without