@draht/chord 2026.10.20 → 2026.10.23

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 (220) hide show
  1. package/dist/cell.d.ts +122 -0
  2. package/dist/cell.d.ts.map +1 -0
  3. package/dist/cell.js +356 -0
  4. package/dist/cell.js.map +1 -0
  5. package/dist/cluster.d.ts +27 -0
  6. package/dist/cluster.d.ts.map +1 -0
  7. package/dist/cluster.js +230 -0
  8. package/dist/cluster.js.map +1 -0
  9. package/dist/connection.d.ts +270 -0
  10. package/dist/connection.d.ts.map +1 -0
  11. package/dist/connection.js +1216 -0
  12. package/dist/connection.js.map +1 -0
  13. package/dist/context/index.d.ts +20 -1
  14. package/dist/context/index.d.ts.map +1 -1
  15. package/dist/context/index.js +15 -0
  16. package/dist/context/index.js.map +1 -1
  17. package/dist/contract.d.ts +208 -0
  18. package/dist/contract.d.ts.map +1 -0
  19. package/dist/contract.js +246 -0
  20. package/dist/contract.js.map +1 -0
  21. package/dist/declare.d.ts +33 -0
  22. package/dist/declare.d.ts.map +1 -0
  23. package/dist/declare.js +2 -0
  24. package/dist/declare.js.map +1 -0
  25. package/dist/delta/apply-immutable-trusted.js.map +1 -1
  26. package/dist/delta/diff.d.ts +1 -1
  27. package/dist/delta/diff.d.ts.map +1 -1
  28. package/dist/delta/diff.js.map +1 -1
  29. package/dist/delta/index.d.ts +4 -3
  30. package/dist/delta/index.d.ts.map +1 -1
  31. package/dist/delta/index.js +45 -0
  32. package/dist/delta/index.js.map +1 -1
  33. package/dist/delta/revision-validator.d.ts +1 -1
  34. package/dist/delta/revision-validator.d.ts.map +1 -1
  35. package/dist/delta/revision-validator.js.map +1 -1
  36. package/dist/delta/tracker.d.ts +1 -1
  37. package/dist/delta/tracker.d.ts.map +1 -1
  38. package/dist/delta/tracker.js +40 -4
  39. package/dist/delta/tracker.js.map +1 -1
  40. package/dist/errors.d.ts +28 -0
  41. package/dist/errors.d.ts.map +1 -0
  42. package/dist/errors.js +59 -0
  43. package/dist/errors.js.map +1 -0
  44. package/dist/host.d.ts +348 -0
  45. package/dist/host.d.ts.map +1 -0
  46. package/dist/host.js +1000 -0
  47. package/dist/host.js.map +1 -0
  48. package/dist/index.d.ts +17 -10
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +8 -8
  51. package/dist/index.js.map +1 -1
  52. package/dist/json.d.ts +9 -1
  53. package/dist/json.d.ts.map +1 -1
  54. package/dist/json.js.map +1 -1
  55. package/dist/link.d.ts +109 -0
  56. package/dist/link.d.ts.map +1 -0
  57. package/dist/link.js +375 -0
  58. package/dist/link.js.map +1 -0
  59. package/dist/loader.d.ts +4 -0
  60. package/dist/loader.d.ts.map +1 -0
  61. package/dist/loader.js +73 -0
  62. package/dist/loader.js.map +1 -0
  63. package/dist/manager.d.ts +115 -0
  64. package/dist/manager.d.ts.map +1 -0
  65. package/dist/manager.js +345 -0
  66. package/dist/manager.js.map +1 -0
  67. package/dist/node.d.ts +3 -4
  68. package/dist/node.d.ts.map +1 -1
  69. package/dist/node.js +3 -2
  70. package/dist/node.js.map +1 -1
  71. package/dist/object.d.ts +438 -0
  72. package/dist/object.d.ts.map +1 -0
  73. package/dist/object.js +1571 -0
  74. package/dist/object.js.map +1 -0
  75. package/dist/output.d.ts +91 -0
  76. package/dist/output.d.ts.map +1 -0
  77. package/dist/output.js +360 -0
  78. package/dist/output.js.map +1 -0
  79. package/dist/publish.d.ts +5 -0
  80. package/dist/publish.d.ts.map +1 -0
  81. package/dist/publish.js +40 -0
  82. package/dist/publish.js.map +1 -0
  83. package/dist/registry.d.ts +25 -0
  84. package/dist/registry.d.ts.map +1 -0
  85. package/dist/registry.js +6 -0
  86. package/dist/registry.js.map +1 -0
  87. package/dist/reload.d.ts +126 -0
  88. package/dist/reload.d.ts.map +1 -0
  89. package/dist/reload.js +653 -0
  90. package/dist/reload.js.map +1 -0
  91. package/dist/remote.d.ts +165 -0
  92. package/dist/remote.d.ts.map +1 -0
  93. package/dist/remote.js +612 -0
  94. package/dist/remote.js.map +1 -0
  95. package/dist/schema.d.ts +21 -0
  96. package/dist/schema.d.ts.map +1 -0
  97. package/dist/schema.js +228 -0
  98. package/dist/schema.js.map +1 -0
  99. package/dist/sqlite/cloudflare.d.ts +52 -0
  100. package/dist/sqlite/cloudflare.d.ts.map +1 -0
  101. package/dist/sqlite/cloudflare.js +134 -0
  102. package/dist/sqlite/cloudflare.js.map +1 -0
  103. package/dist/sqlite/database.d.ts +37 -0
  104. package/dist/sqlite/database.d.ts.map +1 -0
  105. package/dist/sqlite/database.js +2 -0
  106. package/dist/sqlite/database.js.map +1 -0
  107. package/dist/sqlite/index.d.ts +4 -0
  108. package/dist/sqlite/index.d.ts.map +1 -0
  109. package/dist/sqlite/index.js +3 -0
  110. package/dist/sqlite/index.js.map +1 -0
  111. package/dist/sqlite/migrations.d.ts +10 -0
  112. package/dist/sqlite/migrations.d.ts.map +1 -0
  113. package/dist/sqlite/migrations.js +33 -0
  114. package/dist/sqlite/migrations.js.map +1 -0
  115. package/dist/sqlite/node.d.ts +38 -0
  116. package/dist/sqlite/node.d.ts.map +1 -0
  117. package/dist/sqlite/node.js +174 -0
  118. package/dist/sqlite/node.js.map +1 -0
  119. package/dist/sqlite/schema.d.ts +3 -0
  120. package/dist/sqlite/schema.d.ts.map +1 -0
  121. package/dist/sqlite/schema.js +10 -0
  122. package/dist/sqlite/schema.js.map +1 -0
  123. package/dist/state.d.ts +92 -0
  124. package/dist/state.d.ts.map +1 -0
  125. package/dist/{services/state.js → state.js} +28 -138
  126. package/dist/state.js.map +1 -0
  127. package/dist/telemetry-sqlite/index.d.ts +24 -0
  128. package/dist/telemetry-sqlite/index.d.ts.map +1 -0
  129. package/dist/telemetry-sqlite/index.js +273 -0
  130. package/dist/telemetry-sqlite/index.js.map +1 -0
  131. package/dist/telemetry-sqlite/store.d.ts +9 -0
  132. package/dist/telemetry-sqlite/store.d.ts.map +1 -0
  133. package/dist/telemetry-sqlite/store.js +110 -0
  134. package/dist/telemetry-sqlite/store.js.map +1 -0
  135. package/dist/types.d.ts +69 -254
  136. package/dist/types.d.ts.map +1 -1
  137. package/dist/types.js.map +1 -1
  138. package/dist/websocket.d.ts +15 -0
  139. package/dist/websocket.d.ts.map +1 -0
  140. package/dist/websocket.js +16 -0
  141. package/dist/websocket.js.map +1 -0
  142. package/dist/wire.d.ts +216 -0
  143. package/dist/wire.d.ts.map +1 -0
  144. package/dist/wire.js +165 -0
  145. package/dist/wire.js.map +1 -0
  146. package/docs/guide.md +814 -0
  147. package/docs/spec.md +288 -0
  148. package/docs/tutorial.md +931 -0
  149. package/package.json +36 -12
  150. package/dist/api.d.ts +0 -20
  151. package/dist/api.d.ts.map +0 -1
  152. package/dist/api.js +0 -77
  153. package/dist/api.js.map +0 -1
  154. package/dist/bundler.d.ts +0 -6
  155. package/dist/bundler.d.ts.map +0 -1
  156. package/dist/bundler.js +0 -3
  157. package/dist/bundler.js.map +0 -1
  158. package/dist/facets/host.d.ts +0 -12
  159. package/dist/facets/host.d.ts.map +0 -1
  160. package/dist/facets/host.js +0 -763
  161. package/dist/facets/host.js.map +0 -1
  162. package/dist/facets/loader.d.ts +0 -3
  163. package/dist/facets/loader.d.ts.map +0 -1
  164. package/dist/facets/loader.js +0 -5
  165. package/dist/facets/loader.js.map +0 -1
  166. package/dist/node/bundle-loader.d.ts +0 -30
  167. package/dist/node/bundle-loader.d.ts.map +0 -1
  168. package/dist/node/bundle-loader.js +0 -377
  169. package/dist/node/bundle-loader.js.map +0 -1
  170. package/dist/node/bundle.d.ts +0 -26
  171. package/dist/node/bundle.d.ts.map +0 -1
  172. package/dist/node/bundle.js +0 -183
  173. package/dist/node/bundle.js.map +0 -1
  174. package/dist/node/manifest.d.ts +0 -36
  175. package/dist/node/manifest.d.ts.map +0 -1
  176. package/dist/node/manifest.js +0 -6
  177. package/dist/node/manifest.js.map +0 -1
  178. package/dist/node/package.d.ts +0 -15
  179. package/dist/node/package.d.ts.map +0 -1
  180. package/dist/node/package.js +0 -199
  181. package/dist/node/package.js.map +0 -1
  182. package/dist/services/consumer.d.ts +0 -11
  183. package/dist/services/consumer.d.ts.map +0 -1
  184. package/dist/services/consumer.js +0 -585
  185. package/dist/services/consumer.js.map +0 -1
  186. package/dist/services/errors.d.ts +0 -8
  187. package/dist/services/errors.d.ts.map +0 -1
  188. package/dist/services/errors.js +0 -22
  189. package/dist/services/errors.js.map +0 -1
  190. package/dist/services/handle.d.ts +0 -15
  191. package/dist/services/handle.d.ts.map +0 -1
  192. package/dist/services/handle.js +0 -101
  193. package/dist/services/handle.js.map +0 -1
  194. package/dist/services/instances.d.ts +0 -26
  195. package/dist/services/instances.d.ts.map +0 -1
  196. package/dist/services/instances.js +0 -140
  197. package/dist/services/instances.js.map +0 -1
  198. package/dist/services/loopback.d.ts +0 -5
  199. package/dist/services/loopback.d.ts.map +0 -1
  200. package/dist/services/loopback.js +0 -15
  201. package/dist/services/loopback.js.map +0 -1
  202. package/dist/services/provider.d.ts +0 -37
  203. package/dist/services/provider.d.ts.map +0 -1
  204. package/dist/services/provider.js +0 -521
  205. package/dist/services/provider.js.map +0 -1
  206. package/dist/services/state-codec.d.ts +0 -15
  207. package/dist/services/state-codec.d.ts.map +0 -1
  208. package/dist/services/state-codec.js +0 -133
  209. package/dist/services/state-codec.js.map +0 -1
  210. package/dist/services/state-internals.d.ts +0 -13
  211. package/dist/services/state-internals.d.ts.map +0 -1
  212. package/dist/services/state-internals.js +0 -10
  213. package/dist/services/state-internals.js.map +0 -1
  214. package/dist/services/state.d.ts +0 -28
  215. package/dist/services/state.d.ts.map +0 -1
  216. package/dist/services/state.js.map +0 -1
  217. package/dist/services/wire.d.ts +0 -63
  218. package/dist/services/wire.d.ts.map +0 -1
  219. package/dist/services/wire.js +0 -186
  220. package/dist/services/wire.js.map +0 -1
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Draft, Op } from \"./delta/index.ts\";\nimport type { RemoteServiceProvider } from \"./services/provider.ts\";\n\nexport type { RemoteServiceError } from \"./services/errors.ts\";\nexport type { RemoteServiceProvider } from \"./services/provider.ts\";\n\n/** Typed identity for one value carried by a {@link Context}. */\nexport interface ContextKey<T> {\n\treadonly token: symbol;\n\t/** Type-only marker that prevents keys with different value types from being interchangeable. */\n\treadonly valueType?: (value: T) => T;\n}\n\n/** Immutable invocation-scoped values passed explicitly through operations. */\nexport interface Context {\n\treadonly abortSignal: AbortSignal | undefined;\n\tvalue<T>(key: ContextKey<T>): T | undefined;\n\ttoString(): string;\n}\n\nexport type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };\n\ntype IsAny<T> = 0 extends 1 & T ? true : false;\n\n/** Strict-JSON representation of an application data type. Unknown payloads become JsonValue. */\nexport type JsonRepresentation<T> = IsAny<T> extends true\n\t? JsonValue\n\t: unknown extends T\n\t\t? JsonValue\n\t\t: T extends null | boolean | number | string\n\t\t\t? T\n\t\t\t: T extends readonly (infer TItem)[]\n\t\t\t\t? JsonRepresentation<TItem>[]\n\t\t\t\t: T extends object\n\t\t\t\t\t? { [TKey in keyof T]: JsonRepresentation<T[TKey]> }\n\t\t\t\t\t: never;\n\nexport interface ReplicatedStateDelivery {\n\treadonly kind: \"hydrate\" | \"update\";\n\treadonly sequence: number;\n}\n\nexport interface ReplicatedState<T> {\n\t/**\n\t * Contract-immutable value, or undefined until hydration. It is not frozen and may share containers with an\n\t * in-process provider; consumers must not mutate it. Later updates do not mutate previously returned values.\n\t */\n\treadonly value: T | undefined;\n\t/**\n\t * Each subscription serializes callbacks, awaiting hydration before updates. Values are immutable and may\n\t * share unchanged revision data. At most 100 deliveries wait behind the running callback; overflow keeps\n\t * only the newest pending value/context/delivery, so update sequences may skip. Failures are reported in\n\t * isolation and delivery continues. Unsubscribe discards pending work without aborting or joining a callback.\n\t */\n\tsubscribe(listener: (value: T, context: Context, delivery: ReplicatedStateDelivery) => Promise<void>): () => void;\n\tsubscribe(listener: (value: T, context: Context, delivery: ReplicatedStateDelivery) => void): () => void;\n}\n\nexport interface MutableReplicatedState<T extends object> extends ReplicatedState<T> {\n\treadonly value: T;\n\t/**\n\t * Atomically publish one synchronous overlay mutation. Draft handles are unusable after the callback returns.\n\t * Values placed through the draft are cloned by value; assigning `undefined` to an object property deletes it.\n\t */\n\tchange(context: Context, mutate: (draft: Draft<T>) => void): void;\n\t/**\n\t * Atomically take immutable ownership of an alias-free strict-JSON replacement.\n\t * The caller must not mutate the transferred root after this call.\n\t */\n\treplace(context: Context, value: T): void;\n}\n\n/** One immutable authoritative revision committed after an attachment snapshot. */\nexport interface ReplicatedStateSourceFrame<T> {\n\t/** Monotonic source cursor. The first frame after a snapshot must be `snapshot.cursor + 1`. */\n\treadonly cursor: number;\n\t/** The exact immutable value produced by this commit. */\n\treadonly value: T;\n\t/** The exact immutable operation batch that produced `value` from the preceding source revision. */\n\treadonly ops: readonly Op[];\n\treadonly context: Context;\n}\n\nexport interface ReplicatedStateSourceAttachment<T> {\n\t/** Fixed immutable snapshot captured at the atomic attachment boundary. */\n\treadonly snapshot: { readonly value: T; readonly cursor: number };\n\t/**\n\t * Install the sole listener and synchronously drain every buffered frame in source commit order.\n\t * This method is single-use. After it begins, every new committed frame must also be delivered in order\n\t * until disposal, including commits made reentrantly while a prior frame is being delivered.\n\t */\n\tactivate(listener: (frame: ReplicatedStateSourceFrame<T>) => void): void;\n\t/** Stop delivery and release source resources. Disposal must be idempotent. */\n\tdispose(): void;\n}\n\n/**\n * An authoritative immutable revision source.\n *\n * `attach()` must synchronously and atomically capture one snapshot and register the returned attachment to buffer\n * every later committed frame. The snapshot must include every commit before that boundary; buffered frames must\n * include every commit after it, with no overlap or gap. Snapshot values, frame values, and operation batches are\n * immutable and remain valid after delivery. Chord only publishes these references; it never applies or re-diffs them.\n */\nexport interface ReplicatedStateSource<T> {\n\tattach(): ReplicatedStateSourceAttachment<T>;\n}\n\nexport interface ReplicatedStateSourceOptions {\n\t/** Receives source-contract and publication-listener failures without throwing them into the source. */\n\treadonly onError?: (error: Error) => void;\n}\n\n/** A synchronously hydrated publication-only state backed by one source attachment. */\nexport interface AttachedReplicatedState<T> extends ReplicatedState<T> {\n\treadonly value: T;\n\t/** Idempotently release the source attachment. The last published value remains readable. */\n\tdispose(): void;\n}\n\ndeclare const SERVICE_TYPE: unique symbol;\n\nexport type ServiceMode = \"singleton\" | \"keyed\";\n\n/** Stable identity for one shared TypeScript service contract. */\nexport interface Service<T> {\n\treadonly id: string;\n\t/** Process-local services accept unrestricted object contracts and are never published remotely. */\n\treadonly local: boolean;\n\treadonly [SERVICE_TYPE]?: (value: T) => T;\n}\n\ntype InvalidJsonPart<T> = IsAny<T> extends true\n\t? T\n\t: unknown extends T\n\t\t? never\n\t\t: [T] extends [JsonValue]\n\t\t\t? [JsonValue] extends [T]\n\t\t\t\t? never\n\t\t\t\t: InvalidJsonStructure<T>\n\t\t\t: InvalidJsonStructure<T>;\n\ntype InvalidJsonProperty<T> = [Exclude<T, undefined>] extends [never] ? T : InvalidJsonPart<Exclude<T, undefined>>;\n\ntype InvalidJsonStructure<T> = T extends null | boolean | number | string\n\t? never\n\t: T extends readonly (infer TItem)[]\n\t\t? InvalidJsonPart<TItem>\n\t\t: T extends (...args: never[]) => unknown\n\t\t\t? T\n\t\t\t: T extends object\n\t\t\t\t? { [TKey in keyof T]-?: InvalidJsonProperty<T[TKey]> }[keyof T]\n\t\t\t\t: T;\n\ntype InvalidRemoteMember<T> = T extends ReplicatedState<infer TValue>\n\t? InvalidJsonPart<TValue> extends never\n\t\t? never\n\t\t: \"state value is not JSON\"\n\t: T extends (...args: [...infer TArgs, Context]) => Promise<infer TResult>\n\t\t? InvalidJsonPart<TArgs[number]> extends never\n\t\t\t? TResult extends void\n\t\t\t\t? never\n\t\t\t\t: InvalidJsonPart<TResult> extends never\n\t\t\t\t\t? never\n\t\t\t\t\t: \"method result is not JSON or void\"\n\t\t\t: \"method argument is not JSON\"\n\t\t: \"member is not a remote method or ReplicatedState\";\n\ntype InvalidRemoteMemberNames<T> = {\n\t[TKey in keyof T]-?: InvalidRemoteMember<T[TKey]> extends never ? never : TKey;\n}[keyof T];\n\nexport type RemoteServiceContract<T> = InvalidRemoteMemberNames<T> extends never ? T : never;\n\nexport interface ServiceSpawner<T> {\n\tspawn(key: string, implementation: T): () => void;\n}\n\nexport interface RemoteServices {\n\tuse<T>(service: Service<T>): T;\n\tobserve<T>(service: Service<T>, handler: (service: T, context: Context) => void | Promise<void>): () => void;\n\t/** Wait until every currently acquired service has installed its initial snapshot. */\n\tready(context: Context): Promise<void>;\n\tdispose(context: Context): Promise<void>;\n}\n\nexport type ServiceCatalogueEntry = {\n\treadonly serviceId: string;\n\treadonly mode: ServiceMode;\n};\n\nexport type ServiceInstanceAddress = {\n\treadonly key: string;\n\treadonly generation: number;\n};\n\nexport type ServiceMemberSnapshot =\n\t| { readonly name: string; readonly kind: \"method\" }\n\t| { readonly name: string; readonly kind: \"state\"; readonly sequence: number; readonly ops: readonly Op[] };\n\nexport type ServiceInstanceSnapshot = {\n\treadonly instance?: ServiceInstanceAddress;\n\treadonly members: readonly ServiceMemberSnapshot[];\n};\n\nexport type ServiceSubscriptionSnapshot = {\n\treadonly serviceId: string;\n\treadonly mode: ServiceMode;\n\treadonly instances: readonly ServiceInstanceSnapshot[];\n};\n\nexport type ServiceProviderUpdate =\n\t| {\n\t\t\treadonly type: \"state\";\n\t\t\treadonly instance?: ServiceInstanceAddress;\n\t\t\treadonly member: string;\n\t\t\treadonly sequence: number;\n\t\t\treadonly ops: readonly Op[];\n\t }\n\t/** Full subscription rebaseline after overflow; every state is a root replacement at its new sequence. */\n\t| { readonly type: \"reset\"; readonly snapshot: ServiceSubscriptionSnapshot }\n\t| { readonly type: \"unavailable\" }\n\t| { readonly type: \"replaced\"; readonly snapshot: ServiceInstanceSnapshot }\n\t| { readonly type: \"spawned\"; readonly instance: ServiceInstanceSnapshot }\n\t| { readonly type: \"closed\"; readonly instance: ServiceInstanceAddress };\n\nexport type ServiceCall = {\n\treadonly serviceId: string;\n\treadonly instance?: ServiceInstanceAddress;\n\treadonly member: string;\n\t/** Borrowed immutable values. Chord validates but does not clone them. */\n\treadonly args: readonly JsonValue[];\n};\n\nexport interface ServiceSubscription {\n\t/** Atomic baseline. Later updates buffer until activation, with a full reset on pending delivery 101. */\n\treadonly snapshot: ServiceSubscriptionSnapshot;\n\tactivate(): void;\n\tclose(context?: Context): void | Promise<void>;\n}\n\n/**\n * Pluggable wire boundary consumed by a remote service binding.\n *\n * Implementations choose transport, framing, routing, and envelope encoding. Values crossing this\n * boundary must remain strict JSON. Chord does not clone values or require a particular application wire protocol;\n * adapters own serialization and any isolation copies they require.\n *\n */\nexport interface RemoteServiceTransport {\n\tinvoke(call: ServiceCall, context: Context): Promise<JsonValue | undefined>;\n\tsubscribe(\n\t\tserviceId: string,\n\t\tmode: ServiceMode,\n\t\tlistener: (update: ServiceProviderUpdate, context: Context) => void,\n\t\tcontext: Context,\n\t): Promise<ServiceSubscription>;\n}\n\nexport interface RemoteServiceBindingOptions {\n\treadonly services: readonly { readonly id: string }[];\n\treadonly transport: RemoteServiceTransport;\n\treadonly bound?: boolean;\n\treadonly onError?: (error: Error) => void;\n\treadonly assertAccess?: () => void;\n}\n\nexport interface RemoteServiceBinding extends RemoteServices {\n\trebind(bound: boolean, context: Context): Promise<void>;\n}\n\nexport interface FacetEnvironment {\n\t/** Declare a hard dependency on one singleton service and return its stable handle. */\n\tuse<T>(service: Service<T>): T;\n\t/** Declare a hard dependency on a keyed service and observe each live instance. */\n\tobserve<T>(service: Service<T>, handler: (service: T, context: Context) => void | Promise<void>): void;\n\t/** Declare and install this facet's singleton implementation of a service. */\n\tprovide<T>(service: Service<T>, implementation: NoInfer<T>): void;\n\t/** Declare ownership of a multi-instance service and return its deferred spawning capability. */\n\tprovideMany<T>(service: Service<T>): ServiceSpawner<T>;\n\t/**\n\t * Create initialized mutable state by taking immutable ownership of an alias-free strict-JSON root.\n\t * The caller must not mutate `initial` after this call.\n\t */\n\treplicatedState<T extends object>(initial: T): MutableReplicatedState<T>;\n\t/** Give the facet ownership of a resource cleanup function. */\n\town(disposal: () => void | Promise<void>): void;\n\t/** Register asynchronous initialization after dependencies are bound and ready. */\n\tonActivate(callback: () => void | Promise<void>): void;\n\t/** Register final facet teardown. */\n\tonDeactivate(callback: () => void | Promise<void>): void;\n}\n\nexport interface Facet {\n\treadonly id: string;\n\tsetup(env: FacetEnvironment): void;\n}\n\nexport interface RemoteServiceSource {\n\t/** Whether this currently unavailable source may provisionally own absent requirements. */\n\treadonly acceptsUnavailableServices: boolean;\n\tcatalogue(context: Context): Promise<readonly ServiceCatalogueEntry[]>;\n\topen(options: {\n\t\treadonly services: readonly { readonly id: string }[];\n\t\tassertAccess(): void;\n\t\tonError(error: Error): void;\n\t}): RemoteServices;\n}\n\nexport interface FacetOptions {\n\treadonly facets: readonly Facet[];\n\treadonly serviceSources?: readonly RemoteServiceSource[];\n\treadonly onError?: (error: Error) => void;\n}\n\nexport interface FacetHost {\n\treadonly services: RemoteServiceProvider;\n\t/** Activate and replace facets with matching IDs without disconnecting consumer service handles. */\n\treload(facets: readonly Facet[]): Promise<void>;\n\tdispose(): Promise<void>;\n}\n\nexport interface LoadedFacets {\n\treadonly facets: readonly Facet[];\n\tdispose(): Promise<void>;\n}\n\nexport interface FacetLoader {\n\tload(): Promise<LoadedFacets>;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { AnyContract, InputOf, Ref } from \"./contract.ts\";\nimport type { Op } from \"./delta/index.ts\";\n\n/**\n * Options of `get`. `P` is the app's principal type: a JSON-serializable identity of a caller, mapped to an object key\n * by `createHost({ principalKey })`.\n */\nexport interface GetOptions<P = unknown> {\n\t/** Principal the object is created for. Defaults to the host's own principal (`createHost({ self })`). */\n\treadonly principal?: P;\n\t/**\n\t * False: a method-only reference. It receives no state (unless another reference to the same object wants it), and\n\t * is ready once its object is live.\n\t */\n\treadonly state?: boolean;\n}\n\n/**\n * The explicit call context of one root (a short Chord call tree). Calls made with it carry its root id and code\n * version; `get` references are released when the call that received this ctx settles.\n */\nexport interface Ctx<P = unknown> {\n\treadonly signal: AbortSignal;\n\treadonly rootId: string;\n\treadonly codeVersion: number;\n\t/** Who the root acts as: the caller at ingress, the host's own principal inside objects. */\n\treadonly principal: P;\n\t/**\n\t * A reference for this call, released when the call settles. Resolves once it is ready: live, with every state\n\t * member of its variant (unless `state: false`). Rejects with the activation error, `aborted` when the ctx is\n\t * aborted or the call settles first, or `unavailable/ready_timeout` after the host's `readyTimeout`; the reference\n\t * is released then.\n\t */\n\tget<C extends AnyContract>(type: C, input: InputOf<C>, options?: GetOptions<P>): Promise<Ref<C>>;\n}\n\nexport type StateEvent<T> =\n\t| { readonly type: \"snap\"; readonly value: T }\n\t| { readonly type: \"ops\"; readonly ops: readonly Op[]; readonly value: T }\n\t| { readonly type: \"reset\"; readonly value: T };\n\n/** A readable state source: a cell, a derivation, or a reference's state member. Values are immutable by contract. */\nexport interface Readable<T> {\n\treadonly value: T;\n\t/** Called with the current value immediately, then with every new value. */\n\tsubscribe(listener: (value: T) => void): () => void;\n\t/** Delta stream: a snapshot immediately, then ops, or a reset after a migration or rebind. */\n\tevents(listener: (event: StateEvent<T>) => void): () => void;\n}\n\n/**\n * What an implementation may expose as a state member: a cell, a derivation, or a held object's state member (an\n * object goes live only once the members it exposes have their values).\n */\nexport type StateSource<T> = Readable<T>;\n\ndeclare const EXPOSED: unique symbol;\n\n/** A local member backed by a resource (`self.expose(res.x)`): references read the resource's value once live. */\nexport interface Exposed<T> {\n\treadonly [EXPOSED]: T;\n}\n\nexport type RefStatus = \"loading\" | \"live\" | \"released\" | \"gone\";\n\nexport interface Shape {\n\treadonly variant: string | undefined;\n\treadonly members: readonly string[];\n\t/** Fingerprint of the provider contract. */\n\treadonly contract: string;\n}\n\nexport interface RefBase<C extends AnyContract> {\n\t/** The consumer contract token this reference was bound with. */\n\treadonly contract: C;\n\treadonly status: RefStatus;\n\treadonly ready: Promise<void>;\n\treadonly variant: string | undefined;\n\treadonly shape: Shape | undefined;\n\t/** Why the reference is gone, if it is. */\n\treadonly error: unknown;\n\tonShape(listener: (shape: Shape) => void): () => void;\n\t/**\n\t * Called after every status change (`loading` → `live`, `live` → `loading` while a link reconnects, `released`,\n\t * `gone` with `error`). A UI watches for `gone` to `get` again.\n\t */\n\tonStatus(listener: (status: RefStatus, error: unknown) => void): () => void;\n\trelease(): void;\n}\n"]}
@@ -0,0 +1,15 @@
1
+ import type { AcceptOptions } from "./connection.ts";
2
+ import type { Host } from "./host.ts";
3
+ import { type WebSocketLike } from "./link.ts";
4
+ /** A WebSocket server (e.g. `ws`'s `WebSocketServer`), structurally: Chord does not depend on `ws`. */
5
+ export interface WebSocketServerLike<Request> {
6
+ on(event: "connection", listener: (socket: WebSocketLike, request: Request) => void): unknown;
7
+ }
8
+ /** WebSocket peers are always accepted as clients: no roots, no code versions, no reload votes, not addressable. */
9
+ export interface WebSocketAcceptOptions<Request, P = unknown> extends Omit<AcceptOptions<P>, "principal" | "kind" | "name"> {
10
+ /** The authenticator: the principal of the connecting client, or undefined to refuse it. */
11
+ principal(request: Request): P | undefined | Promise<P | undefined>;
12
+ }
13
+ /** Accepts every connection of `server` on `host` as a client link stamped with the authenticated principal. */
14
+ export declare function acceptWebSockets<Request, P = unknown>(server: WebSocketServerLike<Request>, host: Host<P>, options: WebSocketAcceptOptions<Request, P>): void;
15
+ //# sourceMappingURL=websocket.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../src/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,KAAK,aAAa,EAAiB,MAAM,WAAW,CAAC;AAE9D,uGAAuG;AACvG,MAAM,WAAW,mBAAmB,CAAC,OAAO;IAC3C,EAAE,CAAC,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,CAAC,MAAM,EAAE,aAAa,EAAE,OAAO,EAAE,OAAO,KAAK,IAAI,GAAG,OAAO,CAAC;CAC9F;AAED,oHAAoH;AACpH,MAAM,WAAW,sBAAsB,CAAC,OAAO,EAAE,CAAC,GAAG,OAAO,CAC3D,SAAQ,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,EAAE,WAAW,GAAG,MAAM,GAAG,MAAM,CAAC;IAC7D,4FAA4F;IAC5F,SAAS,CAAC,OAAO,EAAE,OAAO,GAAG,CAAC,GAAG,SAAS,GAAG,OAAO,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;CACpE;AAED,gHAAgH;AAChH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,CAAC,GAAG,OAAO,EACpD,MAAM,EAAE,mBAAmB,CAAC,OAAO,CAAC,EACpC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,EACb,OAAO,EAAE,sBAAsB,CAAC,OAAO,EAAE,CAAC,CAAC,GACzC,IAAI,CAaN"}
@@ -0,0 +1,16 @@
1
+ import { webSocketLink } from "./link.js";
2
+ /** Accepts every connection of `server` on `host` as a client link stamped with the authenticated principal. */
3
+ export function acceptWebSockets(server, host, options) {
4
+ server.on("connection", (socket, request) => {
5
+ // Wrap at once so frames sent while authenticating are queued, not lost. Large payloads go out deflated; clients
6
+ // may not send packed frames (a small message could inflate to anything).
7
+ const link = webSocketLink(socket, { compress: true, acceptPacked: false });
8
+ Promise.resolve(options.principal(request)).then((principal) => {
9
+ if (principal === undefined)
10
+ link.close("unauthorized");
11
+ else
12
+ host.accept(link, { ...options, principal, kind: "client" });
13
+ }, () => link.close("authentication failed"));
14
+ });
15
+ }
16
+ //# sourceMappingURL=websocket.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket.js","sourceRoot":"","sources":["../src/websocket.ts"],"names":[],"mappings":"AAEA,OAAO,EAAsB,aAAa,EAAE,MAAM,WAAW,CAAC;AAc9D,gHAAgH;AAChH,MAAM,UAAU,gBAAgB,CAC/B,MAAoC,EACpC,IAAa,EACb,OAA2C;IAE3C,MAAM,CAAC,EAAE,CAAC,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE;QAC3C,iHAAiH;QACjH,0EAA0E;QAC1E,MAAM,IAAI,GAAG,aAAa,CAAC,MAAM,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC;QAC5E,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAC/C,CAAC,SAAS,EAAE,EAAE;YACb,IAAI,SAAS,KAAK,SAAS;gBAAE,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;;gBACnD,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,EAAE,GAAG,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC,CAAC;QACnE,CAAC,EACD,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,uBAAuB,CAAC,CACzC,CAAC;IACH,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { AcceptOptions } from \"./connection.ts\";\nimport type { Host } from \"./host.ts\";\nimport { type WebSocketLike, webSocketLink } from \"./link.ts\";\n\n/** A WebSocket server (e.g. `ws`'s `WebSocketServer`), structurally: Chord does not depend on `ws`. */\nexport interface WebSocketServerLike<Request> {\n\ton(event: \"connection\", listener: (socket: WebSocketLike, request: Request) => void): unknown;\n}\n\n/** WebSocket peers are always accepted as clients: no roots, no code versions, no reload votes, not addressable. */\nexport interface WebSocketAcceptOptions<Request, P = unknown>\n\textends Omit<AcceptOptions<P>, \"principal\" | \"kind\" | \"name\"> {\n\t/** The authenticator: the principal of the connecting client, or undefined to refuse it. */\n\tprincipal(request: Request): P | undefined | Promise<P | undefined>;\n}\n\n/** Accepts every connection of `server` on `host` as a client link stamped with the authenticated principal. */\nexport function acceptWebSockets<Request, P = unknown>(\n\tserver: WebSocketServerLike<Request>,\n\thost: Host<P>,\n\toptions: WebSocketAcceptOptions<Request, P>,\n): void {\n\tserver.on(\"connection\", (socket, request) => {\n\t\t// Wrap at once so frames sent while authenticating are queued, not lost. Large payloads go out deflated; clients\n\t\t// may not send packed frames (a small message could inflate to anything).\n\t\tconst link = webSocketLink(socket, { compress: true, acceptPacked: false });\n\t\tPromise.resolve(options.principal(request)).then(\n\t\t\t(principal) => {\n\t\t\t\tif (principal === undefined) link.close(\"unauthorized\");\n\t\t\t\telse host.accept(link, { ...options, principal, kind: \"client\" });\n\t\t\t},\n\t\t\t() => link.close(\"authentication failed\"),\n\t\t);\n\t});\n}\n"]}
package/dist/wire.d.ts ADDED
@@ -0,0 +1,216 @@
1
+ import { type Static, type TSchema, Type } from "typebox";
2
+ import { ChordError } from "./errors.ts";
3
+ /**
4
+ * The link protocol version, announced in `hello`. Peers of different versions do not talk: the side that notices
5
+ * closes the link with reason `protocol-version <its version>`, so the other side learns it too
6
+ * (`LinkOptions.onProtocolMismatch`).
7
+ */
8
+ export declare const PROTOCOL_VERSION = 4;
9
+ declare const RootRefSchema: Type.TObject<{
10
+ rootId: Type.TString;
11
+ codeVersion: Type.TInteger;
12
+ }>;
13
+ export type RootRef = Static<typeof RootRefSchema>;
14
+ declare const WireErrorSchema: Type.TObject<{
15
+ code: Type.TEnum<["aborted", "contract_mismatch", "forbidden", "gone", "invalid", "not_in_variant", "not_ready", "released", "superseded", "unavailable", "upgrade_conflict", "upgrade_required"]>;
16
+ message: Type.TString;
17
+ reason: Type.TOptional<Type.TString>;
18
+ }>;
19
+ export type WireError = Static<typeof WireErrorSchema>;
20
+ declare const WireReloadOptionsSchema: Type.TObject<{
21
+ remove: Type.TOptional<Type.TImmutable<Type.TArray<Type.TString>>>;
22
+ gateDeadline: Type.TOptional<Type.TNumber>;
23
+ retireDeadline: Type.TOptional<Type.TNumber>;
24
+ }>;
25
+ export type WireReloadOptions = Static<typeof WireReloadOptionsSchema>;
26
+ /** A child's prepared reload, sent with its vote (same fields as `ReloadReport`, without children). */
27
+ declare const WireReloadReportSchema: Type.TObject<{
28
+ codeVersion: Type.TInteger;
29
+ previous: Type.TInteger;
30
+ changed: Type.TImmutable<Type.TArray<Type.TString>>;
31
+ removed: Type.TImmutable<Type.TArray<Type.TString>>;
32
+ prepared: Type.TImmutable<Type.TArray<Type.TString>>;
33
+ gated: Type.TImmutable<Type.TArray<Type.TString>>;
34
+ }>;
35
+ export type WireReloadReport = Static<typeof WireReloadReportSchema>;
36
+ declare const FrameSchema: Type.TUnion<[Type.TObject<{
37
+ t: Type.TLiteral<"hello">;
38
+ /** The link protocol version (`PROTOCOL_VERSION`; absent: 1). Peers of another version close the link. */
39
+ protocol: Type.TOptional<Type.TInteger>;
40
+ name: Type.TString;
41
+ kind: Type.TUnion<[Type.TLiteral<"host">, Type.TLiteral<"client">]>;
42
+ codeVersion: Type.TInteger;
43
+ /** The sender acknowledges what it receives (`ack`). Flow control applies only when both hellos say so. */
44
+ acks: Type.TOptional<Type.TBoolean>;
45
+ }>, Type.TObject<{
46
+ t: Type.TLiteral<"ack">;
47
+ n: Type.TInteger;
48
+ }>, Type.TObject<{
49
+ t: Type.TLiteral<"hold">;
50
+ id: Type.TInteger;
51
+ /**
52
+ * Target host name, resolved by the consumer from the token's `host` and `input`. Relays route on it after
53
+ * checking it against both; the target refuses an input its own contract places elsewhere.
54
+ */
55
+ at: Type.TString;
56
+ /** The consumer's contract token; the provider checks that it covers it. Remote tokens carry `host`. */
57
+ token: Type.TObject<{
58
+ name: Type.TString;
59
+ scope: Type.TUnion<[Type.TLiteral<"remote">, Type.TLiteral<"local">]>;
60
+ version: Type.TInteger;
61
+ input: Type.TUnsafe<TSchema>;
62
+ host: Type.TOptional<Type.TUnion<[Type.TObject<{
63
+ name: Type.TString;
64
+ }>, Type.TObject<{
65
+ prefix: Type.TString;
66
+ key: Type.TString;
67
+ }>]>>;
68
+ variants: Type.TRecord<"^.*$", Type.TRecord<"^.*$", Type.TUnion<[Type.TObject<{
69
+ kind: Type.TLiteral<"method">;
70
+ args: Type.TOptional<Type.TUnsafe<TSchema>>;
71
+ result: Type.TOptional<Type.TUnsafe<TSchema>>;
72
+ }>, Type.TObject<{
73
+ kind: Type.TLiteral<"state">;
74
+ schema: Type.TUnsafe<TSchema>;
75
+ }>, Type.TObject<{
76
+ kind: Type.TLiteral<"opaque">;
77
+ id: Type.TString;
78
+ }>]>>>;
79
+ }>;
80
+ /** Normalized with the consumer's contract. */
81
+ input: Type.TUnknown;
82
+ /** A forwarded principal. Honored only on frames from the parent link. */
83
+ principal: Type.TOptional<Type.TUnknown>;
84
+ /**
85
+ * The client connection the hold comes from: an opaque id the server assigned to it, forwarded by relays. Honored
86
+ * only on frames from the parent link; present means the hold is a client's (not a reload participant).
87
+ */
88
+ origin: Type.TOptional<Type.TString>;
89
+ /** False: no state for this hold until `sub` (a method-only binding). */
90
+ state: Type.TOptional<Type.TLiteral<false>>;
91
+ /** The consumer already has values (a re-hold after a link loss): its unit is not urgent. */
92
+ again: Type.TOptional<Type.TLiteral<true>>;
93
+ }>, Type.TObject<{
94
+ t: Type.TLiteral<"release">;
95
+ id: Type.TInteger;
96
+ }>, Type.TObject<{
97
+ t: Type.TLiteral<"shape">;
98
+ id: Type.TInteger;
99
+ variant: Type.TOptional<Type.TString>;
100
+ members: Type.TImmutable<Type.TArray<Type.TString>>;
101
+ contract: Type.TString;
102
+ /** The state members whose snapshots follow this frame; the consumer applies the shape once they are here. */
103
+ state: Type.TImmutable<Type.TArray<Type.TString>>;
104
+ }>, Type.TObject<{
105
+ t: Type.TLiteral<"gone">;
106
+ id: Type.TInteger;
107
+ error: Type.TObject<{
108
+ code: Type.TEnum<["aborted", "contract_mismatch", "forbidden", "gone", "invalid", "not_in_variant", "not_ready", "released", "superseded", "unavailable", "upgrade_conflict", "upgrade_required"]>;
109
+ message: Type.TString;
110
+ reason: Type.TOptional<Type.TString>;
111
+ }>;
112
+ }>, Type.TObject<{
113
+ t: Type.TLiteral<"call">;
114
+ id: Type.TInteger;
115
+ hold: Type.TInteger;
116
+ member: Type.TString;
117
+ args: Type.TOptional<Type.TUnknown>;
118
+ /** Absent: the receiving host starts a root (browsers never carry roots). */
119
+ root: Type.TOptional<Type.TObject<{
120
+ rootId: Type.TString;
121
+ codeVersion: Type.TInteger;
122
+ }>>;
123
+ }>, Type.TObject<{
124
+ t: Type.TLiteral<"result">;
125
+ id: Type.TInteger;
126
+ value: Type.TOptional<Type.TUnknown>;
127
+ error: Type.TOptional<Type.TObject<{
128
+ code: Type.TEnum<["aborted", "contract_mismatch", "forbidden", "gone", "invalid", "not_in_variant", "not_ready", "released", "superseded", "unavailable", "upgrade_conflict", "upgrade_required"]>;
129
+ message: Type.TString;
130
+ reason: Type.TOptional<Type.TString>;
131
+ }>>;
132
+ }>, Type.TObject<{
133
+ t: Type.TLiteral<"cancel">;
134
+ id: Type.TInteger;
135
+ }>, Type.TObject<{
136
+ t: Type.TLiteral<"sub">;
137
+ hold: Type.TInteger;
138
+ }>, Type.TObject<{
139
+ t: Type.TLiteral<"unsub">;
140
+ hold: Type.TInteger;
141
+ }>, Type.TObject<{
142
+ t: Type.TLiteral<"resync">;
143
+ hold: Type.TInteger;
144
+ m: Type.TString;
145
+ }>, Type.TObject<{
146
+ t: Type.TLiteral<"state">;
147
+ hold: Type.TInteger;
148
+ m: Type.TString;
149
+ /** `snap`/`reset` without `value`: the value is `undefined`. */
150
+ as: Type.TUnion<[Type.TLiteral<"snap">, Type.TLiteral<"reset">, Type.TLiteral<"ops">, Type.TLiteral<"error">]>;
151
+ value: Type.TOptional<Type.TUnknown>;
152
+ /** Encoded with the stream's delta encoder; the decoder validates each op. */
153
+ ops: Type.TOptional<Type.TImmutable<Type.TArray<Type.TImmutable<Type.TArray<Type.TUnknown>>>>>;
154
+ error: Type.TOptional<Type.TObject<{
155
+ code: Type.TEnum<["aborted", "contract_mismatch", "forbidden", "gone", "invalid", "not_in_variant", "not_ready", "released", "superseded", "unavailable", "upgrade_conflict", "upgrade_required"]>;
156
+ message: Type.TString;
157
+ reason: Type.TOptional<Type.TString>;
158
+ }>>;
159
+ }>, Type.TObject<{
160
+ t: Type.TLiteral<"ping">;
161
+ n: Type.TInteger;
162
+ }>, Type.TObject<{
163
+ t: Type.TLiteral<"pong">;
164
+ n: Type.TInteger;
165
+ }>, Type.TObject<{
166
+ t: Type.TLiteral<"bye">;
167
+ reason: Type.TOptional<Type.TString>;
168
+ }>, Type.TObject<{
169
+ t: Type.TLiteral<"root_end">;
170
+ rootId: Type.TString;
171
+ }>, Type.TObject<{
172
+ t: Type.TLiteral<"invalidate">;
173
+ pattern: Type.TRecord<"^.*$", Type.TUnknown>;
174
+ }>, Type.TObject<{
175
+ t: Type.TLiteral<"prepare">;
176
+ reload: Type.TInteger;
177
+ codeVersion: Type.TInteger;
178
+ plugins: Type.TImmutable<Type.TArray<Type.TString>>;
179
+ options: Type.TObject<{
180
+ remove: Type.TOptional<Type.TImmutable<Type.TArray<Type.TString>>>;
181
+ gateDeadline: Type.TOptional<Type.TNumber>;
182
+ retireDeadline: Type.TOptional<Type.TNumber>;
183
+ }>;
184
+ }>, Type.TObject<{
185
+ t: Type.TLiteral<"vote">;
186
+ reload: Type.TInteger;
187
+ error: Type.TOptional<Type.TObject<{
188
+ code: Type.TEnum<["aborted", "contract_mismatch", "forbidden", "gone", "invalid", "not_in_variant", "not_ready", "released", "superseded", "unavailable", "upgrade_conflict", "upgrade_required"]>;
189
+ message: Type.TString;
190
+ reason: Type.TOptional<Type.TString>;
191
+ }>>;
192
+ report: Type.TOptional<Type.TObject<{
193
+ codeVersion: Type.TInteger;
194
+ previous: Type.TInteger;
195
+ changed: Type.TImmutable<Type.TArray<Type.TString>>;
196
+ removed: Type.TImmutable<Type.TArray<Type.TString>>;
197
+ prepared: Type.TImmutable<Type.TArray<Type.TString>>;
198
+ gated: Type.TImmutable<Type.TArray<Type.TString>>;
199
+ }>>;
200
+ }>, Type.TObject<{
201
+ t: Type.TLiteral<"commit">;
202
+ reload: Type.TInteger;
203
+ }>, Type.TObject<{
204
+ t: Type.TLiteral<"retire">;
205
+ codeVersion: Type.TInteger;
206
+ }>, Type.TObject<{
207
+ t: Type.TLiteral<"abort">;
208
+ reload: Type.TInteger;
209
+ }>]>;
210
+ export type Frame = Static<typeof FrameSchema>;
211
+ /** A frame that passes validation; anything else is a protocol violation. */
212
+ export declare const isFrame: (value: unknown) => value is Frame;
213
+ export declare function toWireError(error: unknown): WireError;
214
+ export declare const fromWireError: (error: WireError) => ChordError;
215
+ export {};
216
+ //# sourceMappingURL=wire.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire.d.ts","sourceRoot":"","sources":["../src/wire.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,KAAK,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAG1D,OAAO,EAAqB,UAAU,EAAE,MAAM,aAAa,CAAC;AAe5D;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAQlC,QAAA,MAAM,aAAa;;;EAA2E,CAAC;AAC/F,MAAM,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,aAAa,CAAC,CAAC;AAEnD,QAAA,MAAM,eAAe;;;;EAInB,CAAC;AACH,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,OAAO,eAAe,CAAC,CAAC;AAEvD,QAAA,MAAM,uBAAuB;;;;EAI3B,CAAC;AACH,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC,OAAO,uBAAuB,CAAC,CAAC;AAEvE,uGAAuG;AACvG,QAAA,MAAM,sBAAsB;;;;;;;EAO1B,CAAC;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,CAAC,OAAO,sBAAsB,CAAC,CAAC;AAErE,QAAA,MAAM,WAAW;;IAGf,0GAA0G;;;;;IAK1G,2GAA2G;;;;;;;;IAQ3G;;;OAGG;;IAEH,wGAAwG;;;;;;;;;;;;;;;;;;;;;;;;IAExG,+CAA+C;;IAE/C,0EAA0E;;IAE1E;;;OAGG;;IAEH,yEAAyE;;IAEzE,6FAA6F;;;;;;;;;;;IAU7F,8GAA8G;;;;;;;;;;;;;;;;IAU9G,6EAA6E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAoB7E,gEAAgE;;;IAGhE,8EAA8E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA4B9E,CAAC;AACH,MAAM,MAAM,KAAK,GAAG,MAAM,CAAC,OAAO,WAAW,CAAC,CAAC;AAE/C,6EAA6E;AAC7E,eAAO,MAAM,OAAO,UAAW,OAAO,KAAG,KAAK,IAAI,KAAwC,CAAC;AAE3F,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,SAAS,CAOrD;AAED,eAAO,MAAM,aAAa,UAAW,SAAS,KAAG,UACyD,CAAC"}
package/dist/wire.js ADDED
@@ -0,0 +1,165 @@
1
+ import { Type } from "typebox";
2
+ import { Value } from "typebox/value";
3
+ import { DescriptionSchema } from "./contract.js";
4
+ import { CHORD_ERROR_CODES, ChordError } from "./errors.js";
5
+ // JSON frames between two hosts (or a host and a client). Ids are chosen by the side that creates the hold, call or
6
+ // subscription; every frame type has one direction, so ids never collide:
7
+ // consumer → provider: hold, release, call, cancel, sub, unsub, resync
8
+ // provider → consumer: shape, gone, result, state
9
+ // State is addressed by (hold id, member): a hold implies the state of its variant, sent as units (a shape followed by
10
+ // a snapshot of each member the consumer lacks; see Connection).
11
+ // both: hello, ping, pong, bye, root_end, ack; parent → child: invalidate, prepare, commit, abort, retire;
12
+ // child → parent: vote
13
+ //
14
+ // Each frame is declared once, as the schema every received frame is checked against (`isFrame`); the types are derived
15
+ // from it. Payloads (hold inputs, call args, results, snapshots) stay `unknown`: they are validated where they are
16
+ // used, against the contract. State ops are checked op by op by the delta decoder.
17
+ /**
18
+ * The link protocol version, announced in `hello`. Peers of different versions do not talk: the side that notices
19
+ * closes the link with reason `protocol-version <its version>`, so the other side learns it too
20
+ * (`LinkOptions.onProtocolMismatch`).
21
+ */
22
+ export const PROTOCOL_VERSION = 4;
23
+ const Id = Type.Integer({ minimum: 1 });
24
+ const Name = Type.String({ minLength: 1 });
25
+ const Reload = Type.Integer({ minimum: 1 });
26
+ /** Arrays a sender may pass as readonly. */
27
+ const List = (item) => Type.Immutable(Type.Array(item));
28
+ const RootRefSchema = Type.Object({ rootId: Name, codeVersion: Type.Integer({ minimum: 1 }) });
29
+ const WireErrorSchema = Type.Object({
30
+ code: Type.Enum(CHORD_ERROR_CODES),
31
+ message: Type.String(),
32
+ reason: Type.Optional(Type.String()),
33
+ });
34
+ const WireReloadOptionsSchema = Type.Object({
35
+ remove: Type.Optional(List(Type.String())),
36
+ gateDeadline: Type.Optional(Type.Number()),
37
+ retireDeadline: Type.Optional(Type.Number()),
38
+ });
39
+ /** A child's prepared reload, sent with its vote (same fields as `ReloadReport`, without children). */
40
+ const WireReloadReportSchema = Type.Object({
41
+ codeVersion: Type.Integer(),
42
+ previous: Type.Integer(),
43
+ changed: List(Type.String()),
44
+ removed: List(Type.String()),
45
+ prepared: List(Type.String()),
46
+ gated: List(Type.String()),
47
+ });
48
+ const FrameSchema = Type.Union([
49
+ Type.Object({
50
+ t: Type.Literal("hello"),
51
+ /** The link protocol version (`PROTOCOL_VERSION`; absent: 1). Peers of another version close the link. */
52
+ protocol: Type.Optional(Type.Integer({ minimum: 1 })),
53
+ name: Name,
54
+ kind: Type.Union([Type.Literal("host"), Type.Literal("client")]),
55
+ codeVersion: Type.Integer({ minimum: 0 }),
56
+ /** The sender acknowledges what it receives (`ack`). Flow control applies only when both hellos say so. */
57
+ acks: Type.Optional(Type.Boolean()),
58
+ }),
59
+ /** Every frame received so far except `ack` frames, counted from the link's start, once processed. */
60
+ Type.Object({ t: Type.Literal("ack"), n: Type.Integer({ minimum: 1 }) }),
61
+ Type.Object({
62
+ t: Type.Literal("hold"),
63
+ id: Id,
64
+ /**
65
+ * Target host name, resolved by the consumer from the token's `host` and `input`. Relays route on it after
66
+ * checking it against both; the target refuses an input its own contract places elsewhere.
67
+ */
68
+ at: Name,
69
+ /** The consumer's contract token; the provider checks that it covers it. Remote tokens carry `host`. */
70
+ token: DescriptionSchema,
71
+ /** Normalized with the consumer's contract. */
72
+ input: Type.Unknown(),
73
+ /** A forwarded principal. Honored only on frames from the parent link. */
74
+ principal: Type.Optional(Type.Unknown()),
75
+ /**
76
+ * The client connection the hold comes from: an opaque id the server assigned to it, forwarded by relays. Honored
77
+ * only on frames from the parent link; present means the hold is a client's (not a reload participant).
78
+ */
79
+ origin: Type.Optional(Name),
80
+ /** False: no state for this hold until `sub` (a method-only binding). */
81
+ state: Type.Optional(Type.Literal(false)),
82
+ /** The consumer already has values (a re-hold after a link loss): its unit is not urgent. */
83
+ again: Type.Optional(Type.Literal(true)),
84
+ }),
85
+ Type.Object({ t: Type.Literal("release"), id: Id }),
86
+ Type.Object({
87
+ t: Type.Literal("shape"),
88
+ id: Id,
89
+ variant: Type.Optional(Type.String()),
90
+ members: List(Type.String()),
91
+ contract: Type.String(),
92
+ /** The state members whose snapshots follow this frame; the consumer applies the shape once they are here. */
93
+ state: List(Name),
94
+ }),
95
+ Type.Object({ t: Type.Literal("gone"), id: Id, error: WireErrorSchema }),
96
+ Type.Object({
97
+ t: Type.Literal("call"),
98
+ id: Id,
99
+ hold: Id,
100
+ member: Name,
101
+ args: Type.Optional(Type.Unknown()),
102
+ /** Absent: the receiving host starts a root (browsers never carry roots). */
103
+ root: Type.Optional(RootRefSchema),
104
+ }),
105
+ Type.Object({
106
+ t: Type.Literal("result"),
107
+ id: Id,
108
+ value: Type.Optional(Type.Unknown()),
109
+ error: Type.Optional(WireErrorSchema),
110
+ }),
111
+ Type.Object({ t: Type.Literal("cancel"), id: Id }),
112
+ /** Starts the state of a hold opened with `state: false` (answered with a unit). */
113
+ Type.Object({ t: Type.Literal("sub"), hold: Id }),
114
+ /** Stops the state of a hold. */
115
+ Type.Object({ t: Type.Literal("unsub"), hold: Id }),
116
+ /** Sends member `m` again as a reset (a relay that had to drop what waited for it). */
117
+ Type.Object({ t: Type.Literal("resync"), hold: Id, m: Name }),
118
+ Type.Object({
119
+ t: Type.Literal("state"),
120
+ hold: Id,
121
+ m: Name,
122
+ /** `snap`/`reset` without `value`: the value is `undefined`. */
123
+ as: Type.Union([Type.Literal("snap"), Type.Literal("reset"), Type.Literal("ops"), Type.Literal("error")]),
124
+ value: Type.Optional(Type.Unknown()),
125
+ /** Encoded with the stream's delta encoder; the decoder validates each op. */
126
+ ops: Type.Optional(List(List(Type.Unknown()))),
127
+ error: Type.Optional(WireErrorSchema),
128
+ }),
129
+ Type.Object({ t: Type.Literal("ping"), n: Type.Integer() }),
130
+ Type.Object({ t: Type.Literal("pong"), n: Type.Integer() }),
131
+ /** Ends the link (consumed by the link itself). `reason: "protocol-version <n>"`: the sender speaks version n. */
132
+ Type.Object({ t: Type.Literal("bye"), reason: Type.Optional(Type.String()) }),
133
+ /** The root ended at its origin: its leases on objects end (sent on every link the root's calls used). */
134
+ Type.Object({ t: Type.Literal("root_end"), rootId: Name }),
135
+ Type.Object({ t: Type.Literal("invalidate"), pattern: Type.Record(Type.String(), Type.Unknown()) }),
136
+ Type.Object({
137
+ t: Type.Literal("prepare"),
138
+ reload: Reload,
139
+ codeVersion: Type.Integer({ minimum: 1 }),
140
+ plugins: List(Type.String()),
141
+ options: WireReloadOptionsSchema,
142
+ }),
143
+ Type.Object({
144
+ t: Type.Literal("vote"),
145
+ reload: Reload,
146
+ error: Type.Optional(WireErrorSchema),
147
+ report: Type.Optional(WireReloadReportSchema),
148
+ }),
149
+ Type.Object({ t: Type.Literal("commit"), reload: Reload }),
150
+ /** The parent dropped `codeVersion`: roots of it may still come from there no longer. */
151
+ Type.Object({ t: Type.Literal("retire"), codeVersion: Type.Integer({ minimum: 1 }) }),
152
+ Type.Object({ t: Type.Literal("abort"), reload: Reload }),
153
+ ]);
154
+ /** A frame that passes validation; anything else is a protocol violation. */
155
+ export const isFrame = (value) => Value.Check(FrameSchema, value);
156
+ export function toWireError(error) {
157
+ if (error instanceof ChordError) {
158
+ return error.reason === undefined
159
+ ? { code: error.code, message: error.message }
160
+ : { code: error.code, message: error.message, reason: error.reason };
161
+ }
162
+ return { code: "unavailable", message: error instanceof Error ? error.message : String(error) };
163
+ }
164
+ export const fromWireError = (error) => new ChordError(error.code, error.message.replace(/^[a-z_]+(\/[a-z_]+)?: /, ""), { reason: error.reason });
165
+ //# sourceMappingURL=wire.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wire.js","sourceRoot":"","sources":["../src/wire.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6B,IAAI,EAAE,MAAM,SAAS,CAAC;AAC1D,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE5D,oHAAoH;AACpH,0EAA0E;AAC1E,yEAAyE;AACzE,oDAAoD;AACpD,uHAAuH;AACvH,iEAAiE;AACjE,6GAA6G;AAC7G,yBAAyB;AACzB,EAAE;AACF,wHAAwH;AACxH,mHAAmH;AACnH,mFAAmF;AAEnF;;;;GAIG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAElC,MAAM,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC;AACxC,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC,CAAC;AAC3C,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,CAAC;A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CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;AACjG,CAAC;AAED,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,KAAgB,EAAc,EAAE,CAC7D,IAAI,UAAU,CAAC,KAAK,CAAC,IAAI,EAAE,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,wBAAwB,EAAE,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC","sourcesContent":["import { type Static, type TSchema, Type } from \"typebox\";\nimport { Value } from \"typebox/value\";\nimport { DescriptionSchema } from \"./contract.ts\";\nimport { CHORD_ERROR_CODES, ChordError } from \"./errors.ts\";\n\n// JSON frames between two hosts (or a host and a client). Ids are chosen by the side that creates the hold, call or\n// subscription; every frame type has one direction, so ids never collide:\n// consumer → provider: hold, release, call, cancel, sub, unsub, resync\n// provider → consumer: shape, gone, result, state\n// State is addressed by (hold id, member): a hold implies the state of its variant, sent as units (a shape followed by\n// a snapshot of each member the consumer lacks; see Connection).\n// both: hello, ping, pong, bye, root_end, ack; parent → child: invalidate, prepare, commit, abort, retire;\n// child → parent: vote\n//\n// Each frame is declared once, as the schema every received frame is checked against (`isFrame`); the types are derived\n// from it. Payloads (hold inputs, call args, results, snapshots) stay `unknown`: they are validated where they are\n// used, against the contract. State ops are checked op by op by the delta decoder.\n\n/**\n * The link protocol version, announced in `hello`. Peers of different versions do not talk: the side that notices\n * closes the link with reason `protocol-version <its version>`, so the other side learns it too\n * (`LinkOptions.onProtocolMismatch`).\n */\nexport const PROTOCOL_VERSION = 4;\n\nconst Id = Type.Integer({ minimum: 1 });\nconst Name = Type.String({ minLength: 1 });\nconst Reload = Type.Integer({ minimum: 1 });\n/** Arrays a sender may pass as readonly. */\nconst List = <T extends TSchema>(item: T) => Type.Immutable(Type.Array(item));\n\nconst RootRefSchema = Type.Object({ rootId: Name, codeVersion: Type.Integer({ minimum: 1 }) });\nexport type RootRef = Static<typeof RootRefSchema>;\n\nconst WireErrorSchema = Type.Object({\n\tcode: Type.Enum(CHORD_ERROR_CODES),\n\tmessage: Type.String(),\n\treason: Type.Optional(Type.String()),\n});\nexport type WireError = Static<typeof WireErrorSchema>;\n\nconst WireReloadOptionsSchema = Type.Object({\n\tremove: Type.Optional(List(Type.String())),\n\tgateDeadline: Type.Optional(Type.Number()),\n\tretireDeadline: Type.Optional(Type.Number()),\n});\nexport type WireReloadOptions = Static<typeof WireReloadOptionsSchema>;\n\n/** A child's prepared reload, sent with its vote (same fields as `ReloadReport`, without children). */\nconst WireReloadReportSchema = Type.Object({\n\tcodeVersion: Type.Integer(),\n\tprevious: Type.Integer(),\n\tchanged: List(Type.String()),\n\tremoved: List(Type.String()),\n\tprepared: List(Type.String()),\n\tgated: List(Type.String()),\n});\nexport type WireReloadReport = Static<typeof WireReloadReportSchema>;\n\nconst FrameSchema = Type.Union([\n\tType.Object({\n\t\tt: Type.Literal(\"hello\"),\n\t\t/** The link protocol version (`PROTOCOL_VERSION`; absent: 1). Peers of another version close the link. */\n\t\tprotocol: Type.Optional(Type.Integer({ minimum: 1 })),\n\t\tname: Name,\n\t\tkind: Type.Union([Type.Literal(\"host\"), Type.Literal(\"client\")]),\n\t\tcodeVersion: Type.Integer({ minimum: 0 }),\n\t\t/** The sender acknowledges what it receives (`ack`). Flow control applies only when both hellos say so. */\n\t\tacks: Type.Optional(Type.Boolean()),\n\t}),\n\t/** Every frame received so far except `ack` frames, counted from the link's start, once processed. */\n\tType.Object({ t: Type.Literal(\"ack\"), n: Type.Integer({ minimum: 1 }) }),\n\tType.Object({\n\t\tt: Type.Literal(\"hold\"),\n\t\tid: Id,\n\t\t/**\n\t\t * Target host name, resolved by the consumer from the token's `host` and `input`. Relays route on it after\n\t\t * checking it against both; the target refuses an input its own contract places elsewhere.\n\t\t */\n\t\tat: Name,\n\t\t/** The consumer's contract token; the provider checks that it covers it. Remote tokens carry `host`. */\n\t\ttoken: DescriptionSchema,\n\t\t/** Normalized with the consumer's contract. */\n\t\tinput: Type.Unknown(),\n\t\t/** A forwarded principal. Honored only on frames from the parent link. */\n\t\tprincipal: Type.Optional(Type.Unknown()),\n\t\t/**\n\t\t * The client connection the hold comes from: an opaque id the server assigned to it, forwarded by relays. Honored\n\t\t * only on frames from the parent link; present means the hold is a client's (not a reload participant).\n\t\t */\n\t\torigin: Type.Optional(Name),\n\t\t/** False: no state for this hold until `sub` (a method-only binding). */\n\t\tstate: Type.Optional(Type.Literal(false)),\n\t\t/** The consumer already has values (a re-hold after a link loss): its unit is not urgent. */\n\t\tagain: Type.Optional(Type.Literal(true)),\n\t}),\n\tType.Object({ t: Type.Literal(\"release\"), id: Id }),\n\tType.Object({\n\t\tt: Type.Literal(\"shape\"),\n\t\tid: Id,\n\t\tvariant: Type.Optional(Type.String()),\n\t\tmembers: List(Type.String()),\n\t\tcontract: Type.String(),\n\t\t/** The state members whose snapshots follow this frame; the consumer applies the shape once they are here. */\n\t\tstate: List(Name),\n\t}),\n\tType.Object({ t: Type.Literal(\"gone\"), id: Id, error: WireErrorSchema }),\n\tType.Object({\n\t\tt: Type.Literal(\"call\"),\n\t\tid: Id,\n\t\thold: Id,\n\t\tmember: Name,\n\t\targs: Type.Optional(Type.Unknown()),\n\t\t/** Absent: the receiving host starts a root (browsers never carry roots). */\n\t\troot: Type.Optional(RootRefSchema),\n\t}),\n\tType.Object({\n\t\tt: Type.Literal(\"result\"),\n\t\tid: Id,\n\t\tvalue: Type.Optional(Type.Unknown()),\n\t\terror: Type.Optional(WireErrorSchema),\n\t}),\n\tType.Object({ t: Type.Literal(\"cancel\"), id: Id }),\n\t/** Starts the state of a hold opened with `state: false` (answered with a unit). */\n\tType.Object({ t: Type.Literal(\"sub\"), hold: Id }),\n\t/** Stops the state of a hold. */\n\tType.Object({ t: Type.Literal(\"unsub\"), hold: Id }),\n\t/** Sends member `m` again as a reset (a relay that had to drop what waited for it). */\n\tType.Object({ t: Type.Literal(\"resync\"), hold: Id, m: Name }),\n\tType.Object({\n\t\tt: Type.Literal(\"state\"),\n\t\thold: Id,\n\t\tm: Name,\n\t\t/** `snap`/`reset` without `value`: the value is `undefined`. */\n\t\tas: Type.Union([Type.Literal(\"snap\"), Type.Literal(\"reset\"), Type.Literal(\"ops\"), Type.Literal(\"error\")]),\n\t\tvalue: Type.Optional(Type.Unknown()),\n\t\t/** Encoded with the stream's delta encoder; the decoder validates each op. */\n\t\tops: Type.Optional(List(List(Type.Unknown()))),\n\t\terror: Type.Optional(WireErrorSchema),\n\t}),\n\tType.Object({ t: Type.Literal(\"ping\"), n: Type.Integer() }),\n\tType.Object({ t: Type.Literal(\"pong\"), n: Type.Integer() }),\n\t/** Ends the link (consumed by the link itself). `reason: \"protocol-version <n>\"`: the sender speaks version n. */\n\tType.Object({ t: Type.Literal(\"bye\"), reason: Type.Optional(Type.String()) }),\n\t/** The root ended at its origin: its leases on objects end (sent on every link the root's calls used). */\n\tType.Object({ t: Type.Literal(\"root_end\"), rootId: Name }),\n\tType.Object({ t: Type.Literal(\"invalidate\"), pattern: Type.Record(Type.String(), Type.Unknown()) }),\n\tType.Object({\n\t\tt: Type.Literal(\"prepare\"),\n\t\treload: Reload,\n\t\tcodeVersion: Type.Integer({ minimum: 1 }),\n\t\tplugins: List(Type.String()),\n\t\toptions: WireReloadOptionsSchema,\n\t}),\n\tType.Object({\n\t\tt: Type.Literal(\"vote\"),\n\t\treload: Reload,\n\t\terror: Type.Optional(WireErrorSchema),\n\t\treport: Type.Optional(WireReloadReportSchema),\n\t}),\n\tType.Object({ t: Type.Literal(\"commit\"), reload: Reload }),\n\t/** The parent dropped `codeVersion`: roots of it may still come from there no longer. */\n\tType.Object({ t: Type.Literal(\"retire\"), codeVersion: Type.Integer({ minimum: 1 }) }),\n\tType.Object({ t: Type.Literal(\"abort\"), reload: Reload }),\n]);\nexport type Frame = Static<typeof FrameSchema>;\n\n/** A frame that passes validation; anything else is a protocol violation. */\nexport const isFrame = (value: unknown): value is Frame => Value.Check(FrameSchema, value);\n\nexport function toWireError(error: unknown): WireError {\n\tif (error instanceof ChordError) {\n\t\treturn error.reason === undefined\n\t\t\t? { code: error.code, message: error.message }\n\t\t\t: { code: error.code, message: error.message, reason: error.reason };\n\t}\n\treturn { code: \"unavailable\", message: error instanceof Error ? error.message : String(error) };\n}\n\nexport const fromWireError = (error: WireError): ChordError =>\n\tnew ChordError(error.code, error.message.replace(/^[a-z_]+(\\/[a-z_]+)?: /, \"\"), { reason: error.reason });\n"]}