@shivaedev/contract 0.48.0 → 0.49.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 (90) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +128 -107
  3. package/dist/adapters/erasedClient.d.ts +18 -0
  4. package/dist/adapters/erasedClient.d.ts.map +1 -0
  5. package/dist/adapters/erasedClient.js +10 -0
  6. package/dist/adapters/erasedClient.js.map +1 -0
  7. package/dist/automaticLive.d.ts +2 -10
  8. package/dist/automaticLive.d.ts.map +1 -1
  9. package/dist/automaticLive.js +3 -1
  10. package/dist/automaticLive.js.map +1 -1
  11. package/dist/bind.d.ts +5 -5
  12. package/dist/bind.d.ts.map +1 -1
  13. package/dist/bind.js.map +1 -1
  14. package/dist/catchUp.d.ts +2 -1
  15. package/dist/catchUp.d.ts.map +1 -1
  16. package/dist/catchUp.js.map +1 -1
  17. package/dist/clientContract.d.ts +3 -3
  18. package/dist/clientContract.d.ts.map +1 -1
  19. package/dist/clientContract.js +1 -1
  20. package/dist/clientContract.js.map +1 -1
  21. package/dist/clientOperations.d.ts.map +1 -1
  22. package/dist/clientOperations.js +3 -2
  23. package/dist/clientOperations.js.map +1 -1
  24. package/dist/contract.d.ts +1 -0
  25. package/dist/contract.d.ts.map +1 -1
  26. package/dist/contract.js +1 -0
  27. package/dist/contract.js.map +1 -1
  28. package/dist/defineModule.d.ts +2 -2
  29. package/dist/defineModule.d.ts.map +1 -1
  30. package/dist/defineModule.js +1 -1
  31. package/dist/defineModule.js.map +1 -1
  32. package/dist/liveSyncRequest.d.ts +2 -2
  33. package/dist/liveSyncRequest.d.ts.map +1 -1
  34. package/dist/liveSyncRequest.js +1 -2
  35. package/dist/liveSyncRequest.js.map +1 -1
  36. package/dist/liveSyncRpc.d.ts +1 -0
  37. package/dist/liveSyncRpc.d.ts.map +1 -1
  38. package/dist/moduleProof.d.ts +8 -23
  39. package/dist/moduleProof.d.ts.map +1 -1
  40. package/dist/operation.d.ts +4 -5
  41. package/dist/operation.d.ts.map +1 -1
  42. package/dist/operation.js +2 -2
  43. package/dist/operation.js.map +1 -1
  44. package/dist/operationKind.d.ts +3 -0
  45. package/dist/operationKind.d.ts.map +1 -0
  46. package/dist/operationKind.js +14 -0
  47. package/dist/operationKind.js.map +1 -0
  48. package/dist/rpcClient.d.ts +2 -1
  49. package/dist/rpcClient.d.ts.map +1 -1
  50. package/dist/rpcClient.js.map +1 -1
  51. package/dist/runProof.d.ts +3 -41
  52. package/dist/runProof.d.ts.map +1 -1
  53. package/dist/servedOperation.d.ts +28 -25
  54. package/dist/servedOperation.d.ts.map +1 -1
  55. package/dist/servedOperation.js +9 -3
  56. package/dist/servedOperation.js.map +1 -1
  57. package/dist/subject.d.ts +1 -1
  58. package/dist/subject.d.ts.map +1 -1
  59. package/dist/subjectLayers.d.ts +1 -1
  60. package/dist/subjectLayers.d.ts.map +1 -1
  61. package/dist/subjectLayers.js.map +1 -1
  62. package/dist/wireProof.d.ts +48 -0
  63. package/dist/wireProof.d.ts.map +1 -0
  64. package/dist/wireProof.js +2 -0
  65. package/dist/wireProof.js.map +1 -0
  66. package/package.json +15 -15
  67. package/src/adapters/erasedClient.ts +43 -0
  68. package/src/automaticLive.ts +5 -15
  69. package/src/bind.ts +6 -5
  70. package/src/catchUp.ts +2 -1
  71. package/src/clientContract.ts +5 -5
  72. package/src/clientOperations.ts +4 -10
  73. package/src/contract.ts +2 -0
  74. package/src/defineModule.ts +4 -4
  75. package/src/liveSyncRequest.ts +3 -11
  76. package/src/liveSyncRpc.ts +2 -0
  77. package/src/moduleProof.ts +18 -27
  78. package/src/operation.ts +8 -16
  79. package/src/operationKind.ts +15 -0
  80. package/src/rpcClient.ts +3 -3
  81. package/src/runProof.ts +3 -61
  82. package/src/servedOperation.ts +47 -47
  83. package/src/subject.ts +1 -1
  84. package/src/subjectLayers.ts +6 -2
  85. package/src/wireProof.ts +104 -0
  86. package/dist/successProof.d.ts +0 -51
  87. package/dist/successProof.d.ts.map +0 -1
  88. package/dist/successProof.js +0 -2
  89. package/dist/successProof.js.map +0 -1
  90. package/src/successProof.ts +0 -120
@@ -1,12 +1,13 @@
1
- import { Cause, Effect, Option, type Schema, Stream } from "effect";
1
+ import { Cause, Effect, Option, Stream } from "effect";
2
2
  import type { Headers } from "effect/http";
3
3
  import type * as AsyncResult from "effect/reactivity/AsyncResult";
4
4
  import * as Atom from "effect/reactivity/Atom";
5
5
  import * as AtomRegistry from "effect/reactivity/AtomRegistry";
6
6
  import type * as AtomRpc from "effect/reactivity/AtomRpc";
7
- import type { Rpc, RpcSchema } from "effect/rpc";
7
+ import type { Rpc } from "effect/rpc";
8
8
  import type { Key } from "@shivaedev/changes/keys.ts";
9
9
  import type { BindingOwner } from "#adapters/bindingOwner.ts";
10
+ import { changesClient } from "#adapters/erasedClient.ts";
10
11
  import { aggregateLiveStatus } from "#aggregateLiveStatus.ts";
11
12
  import { automaticQuery } from "#automaticQuery.ts";
12
13
  import { clientActivities } from "#clientActivities.ts";
@@ -14,7 +15,6 @@ import { type LiveStatus, live } from "#live.ts";
14
15
  import { queryDelivery } from "#queryDelivery.ts";
15
16
  import { queryProgress } from "#queryProgress.ts";
16
17
  import { querySignals, shareQuerySignals } from "#querySignals.ts";
17
- import type { QueryUpdate } from "#queryUpdate.ts";
18
18
  import { followReflection, type StreamAnchor } from "#reflectedStream.ts";
19
19
  import { type ResumeSource, type ResumeWindow, resumeSignal } from "#resume.ts";
20
20
  import { socketIdentity } from "#rpcClient.ts";
@@ -34,25 +34,15 @@ export interface LiveBound {
34
34
 
35
35
  const pausedByRuntime = Atom.family((_runtime: object) => Atom.keepAlive(Atom.make(false)));
36
36
 
37
- export type ChangesClient = AtomRpc.AtomRpcClient<
38
- unknown,
39
- string,
40
- Rpc.Rpc<
41
- `${string}.$changes`,
42
- Schema.Struct<{ queries: Schema.$Array<Schema.Struct<{ query: Schema.String; payload: Schema.Unknown }>> }>,
43
- RpcSchema.Stream<Schema.Schema<QueryUpdate>, Schema.Unknown>,
44
- Schema.Never
45
- >
46
- >;
47
-
48
37
  export function automaticLive(
49
- service: ChangesClient,
38
+ operations: AtomRpc.AtomRpcClient<unknown, string, Rpc.Any>,
50
39
  name: string,
51
40
  owner?: BindingOwner,
52
41
  resume?: ResumeSource,
53
42
  enabled = true,
54
43
  resumeWindow?: ResumeWindow,
55
44
  ) {
45
+ const service = changesClient(operations);
56
46
  function ownerFailure(get: Atom.AtomContext) {
57
47
  return owner !== undefined && owner.registry !== get.registry ? new Error("A session-scoped query belongs to its binding registry") : undefined;
58
48
  }
package/src/bind.ts CHANGED
@@ -18,12 +18,13 @@ import type { Tag } from "#operationRpc.ts";
18
18
  import type { ResumeSource, ResumeWindow } from "#resume.ts";
19
19
  import { type RpcSource, rpcClient } from "#rpcClient.ts";
20
20
 
21
- export type Failure<R extends Rpc.Any> =
21
+ // Like Effect's own `Rpc` helpers, these take any type: `Rpc.ExtractTag` of a generic group is not provably an `Rpc.Any`.
22
+ export type Failure<R> =
22
23
  R extends Rpc.Rpc<infer _Tag, infer _Payload, infer _Success, infer _Error, infer TMiddleware, infer _Requires>
23
24
  ? Rpc.ErrorExit<R> | TMiddleware["error"]["Type"] | TMiddleware["~ClientError"] | RpcClientError
24
25
  : never;
25
26
 
26
- export type RunFailure<R extends Rpc.Any> = Failure<R>;
27
+ export type RunFailure<R> = Failure<R>;
27
28
 
28
29
  export interface RunOptions {
29
30
  readonly subject?: string;
@@ -37,16 +38,16 @@ export interface QueryOptions extends RunOptions {
37
38
  // `runtime.fn(api.save.run)` and `useAction(runtime, api.save.run)` call `run` with the atom's function context second, which selects no subject.
38
39
  type Run<TPayload, TResult> = (payload: TPayload, options?: RunOptions | Atom.FnContext) => TResult;
39
40
 
40
- export interface BoundQuery<R extends Rpc.Any, TSelf, TSubscription extends Rpc.Any = never> {
41
+ export interface BoundQuery<R, TSelf, TSubscription = never> {
41
42
  readonly query: (payload: Rpc.Payload<R>, options?: QueryOptions) => Atom.Atom<AsyncResult.AsyncResult<Rpc.Success<R>, Failure<R | TSubscription>>>;
42
43
  readonly run: Run<Rpc.Payload<R>, Effect.Effect<Rpc.Success<R>, RunFailure<R>, TSelf>>;
43
44
  }
44
45
 
45
- export interface BoundCommand<R extends Rpc.Any, TSelf> {
46
+ export interface BoundCommand<R, TSelf> {
46
47
  readonly run: Run<Rpc.Payload<R>, Effect.Effect<Rpc.Success<R>, RunFailure<R>, TSelf | Reactivity.Reactivity>>;
47
48
  }
48
49
 
49
- export interface BoundStream<R extends Rpc.Any, TSelf> {
50
+ export interface BoundStream<R, TSelf> {
50
51
  readonly run: Run<Rpc.Payload<R>, Stream.Stream<Rpc.SuccessChunk<R>, RunFailure<R>, TSelf | Rpc.ServicesClient<R>>>;
51
52
  }
52
53
 
package/src/catchUp.ts CHANGED
@@ -2,12 +2,13 @@ import { Effect, Queue } from "effect";
2
2
  import type { Rpc, RpcClient } from "effect/rpc";
3
3
  import type { RpcClientError } from "effect/rpc/RpcClientError";
4
4
  import { liveSyncRequest } from "#liveSyncRequest.ts";
5
+ import type { LiveSyncRpc } from "#liveSyncRpc.ts";
5
6
  import type { Reflection } from "#reflection.ts";
6
7
 
7
8
  // A stream that may have opened behind a command's token passes a later one, sent on its own once the stream confirms tokens.
8
9
  export function catchUp(
9
10
  reflection: Reflection,
10
- client: RpcClient.RpcClient.Flat<Rpc.Any, RpcClientError>,
11
+ client: RpcClient.RpcClient.Flat<Rpc.Any | LiveSyncRpc, RpcClientError>,
11
12
  connected: Effect.Effect<void, RpcClientError>,
12
13
  ) {
13
14
  return Queue.take(reflection.catchUps).pipe(
@@ -26,8 +26,8 @@ interface QueryKeys<TPayload> {
26
26
  readonly readsCollections?: readonly { readonly name: string }[];
27
27
  }
28
28
 
29
- interface CommandKeys<TPayload, TResult> {
30
- readonly invalidates?: (payload: TPayload, result: TResult, viewer?: Option.Option<Viewer>) => readonly Key[];
29
+ interface CommandKeys<TPayload> {
30
+ readonly invalidates?: (payload: TPayload, viewer?: Option.Option<Viewer>) => readonly Key[];
31
31
  }
32
32
 
33
33
  type ClientQueries<TWire, TPayloads, TQueries extends string> = {
@@ -59,7 +59,7 @@ export interface ClientContractDefinition<
59
59
  TScope extends "session" | undefined,
60
60
  > {
61
61
  readonly commands?: {
62
- readonly [TOperation in TCommands]: CommandKeys<PayloadOf<TPayloads, TOperation>["Type"], EntryOf<TWire, TOperation>["success"]["Type"]>;
62
+ readonly [TOperation in TCommands]: CommandKeys<PayloadOf<TPayloads, TOperation>["Type"]>;
63
63
  };
64
64
  readonly keyScope?: TScope;
65
65
  readonly middleware?: TMiddleware;
@@ -90,7 +90,7 @@ export function clientContract<
90
90
  TScope
91
91
  >;
92
92
  export function clientContract(definition: {
93
- readonly commands?: { readonly [operation: string]: CommandKeys<unknown, unknown> };
93
+ readonly commands?: { readonly [operation: string]: CommandKeys<unknown> };
94
94
  readonly keyScope?: "session";
95
95
  readonly middleware?: RpcMiddleware.AnyService;
96
96
  readonly name: string;
@@ -116,7 +116,7 @@ export function clientContract(definition: {
116
116
  });
117
117
  const commands = Object.entries(definition.commands ?? {}).map(([name, { invalidates }]) => ({
118
118
  ...operation("command", name, declared(name)),
119
- invalidates: invalidates ?? (() => []),
119
+ invalidates: (payload: unknown, _result: unknown, viewer?: Option.Option<Viewer>) => invalidates?.(payload, viewer) ?? [],
120
120
  }));
121
121
  const group = declaredGroup(definition.name, {
122
122
  commands,
@@ -3,10 +3,11 @@ import * as Atom from "effect/reactivity/Atom";
3
3
  import * as AtomRegistry from "effect/reactivity/AtomRegistry";
4
4
  import type * as AtomRpc from "effect/reactivity/AtomRpc";
5
5
  import * as Reactivity from "effect/reactivity/Reactivity";
6
- import type { Rpc, RpcSchema } from "effect/rpc";
6
+ import type { Rpc } from "effect/rpc";
7
7
  import type { Key } from "@shivaedev/changes/keys.ts";
8
8
  import type { BindingOwner } from "#adapters/bindingOwner.ts";
9
9
  import { clientId } from "#adapters/clientId.ts";
10
+ import { streamingClient, unaryClient } from "#adapters/erasedClient.ts";
10
11
  import type { automaticLive } from "#automaticLive.ts";
11
12
  import type { QueryOptions, RunOptions } from "#bind.ts";
12
13
  import { clientActivities } from "#clientActivities.ts";
@@ -21,13 +22,6 @@ import { type CommandObserver, reflectCommand } from "#reflectCommand.ts";
21
22
  import { retainQuery } from "#retainQuery.ts";
22
23
  import { subjectSerializationKey, withSubject } from "#subjectHeader.ts";
23
24
 
24
- type ErasedClient = AtomRpc.AtomRpcClient<unknown, string, Rpc.Rpc<string, Schema.Top, Schema.Top, Schema.Top>>;
25
- type ErasedStreamingClient = AtomRpc.AtomRpcClient<
26
- unknown,
27
- string,
28
- Rpc.Rpc<string, Schema.Top, RpcSchema.Stream<Schema.Top, Schema.Top>, Schema.Never>
29
- >;
30
-
31
25
  // `runtime.fn(api.save.run)` passes its function context as the second argument, so only an options object selects a subject.
32
26
  function runSubject(options: unknown): string | undefined {
33
27
  return typeof options === "object" && options !== null && "subject" in options && typeof options.subject === "string" ? options.subject : undefined;
@@ -38,8 +32,8 @@ export function clientOperations(
38
32
  automatic: ReturnType<typeof automaticLive>,
39
33
  owner?: BindingOwner,
40
34
  ) {
41
- const ordinaryClient: ErasedClient = service;
42
- const streaming: ErasedStreamingClient = service;
35
+ const ordinaryClient = unaryClient(service);
36
+ const streaming = streamingClient(service);
43
37
  function run<A, E>(effect: Effect.Effect<A, E, unknown>) {
44
38
  return owner === undefined ? effect : Effect.suspend(() => AtomRegistry.getResult(owner.registry, ordinaryClient.runtime.atom(effect)));
45
39
  }
package/src/contract.ts CHANGED
@@ -23,6 +23,7 @@ export interface Declared<
23
23
  readonly name: TName;
24
24
  readonly queries: TQueries;
25
25
  readonly streams: TStreams;
26
+ readonly subject?: SubjectDeclaration;
26
27
  }
27
28
 
28
29
  export interface Contract<
@@ -135,5 +136,6 @@ export function declaredGroup(name: string, operations: Operations): DeclaredGro
135
136
  name,
136
137
  queries,
137
138
  streams,
139
+ ...(operations.subject === undefined ? {} : { subject: operations.subject }),
138
140
  });
139
141
  }
@@ -78,17 +78,17 @@ export interface ModuleDefinition<
78
78
  readonly operations: TOperations;
79
79
  readonly requires: TRequirements;
80
80
  readonly subject?: TSubject;
81
- readonly wire?: TWire;
81
+ readonly wire: TWire;
82
82
  }
83
83
 
84
84
  export function defineModule<
85
85
  const TName extends string,
86
86
  const TOperations extends readonly ModuleOperation[],
87
87
  const TRequirements extends RequirementRecord,
88
+ const TWire extends Wire,
88
89
  TMiddleware extends RpcMiddleware.AnyService = never,
89
90
  const TSubject extends SubjectDeclaration | undefined = undefined,
90
91
  const TScope extends "session" | undefined = undefined,
91
- const TWire extends Wire = Record<never, never>,
92
92
  >(
93
93
  definition: ModuleDefinition<TName, TOperations, TRequirements, TMiddleware, TSubject, TScope, TWire>,
94
94
  ): Module<TName, WiredAll<TOperations, TWire> & readonly ModuleOperation[], TRequirements, TMiddleware, TSubject, TScope>;
@@ -98,9 +98,9 @@ export function defineModule(definition: {
98
98
  readonly name: string;
99
99
  readonly operations: readonly ModuleOperation[];
100
100
  readonly subject?: SubjectDeclaration;
101
- readonly wire?: Wire;
101
+ readonly wire: Wire;
102
102
  }): unknown {
103
- const operations = definition.operations.map((operation) => wired(operation, definition.wire?.[operation.name]));
103
+ const operations = definition.operations.map((operation) => wired(operation, definition.wire[operation.name]));
104
104
  const group = declaredGroup(definition.name, {
105
105
  annotations: Context.make(DefinedModule, definition.name),
106
106
  commands: operations.filter((operation) => operation.kind === "command"),
@@ -1,17 +1,9 @@
1
- import type { Effect, Schema } from "effect";
2
1
  import type { Rpc, RpcClient } from "effect/rpc";
3
2
  import type { RpcClientError } from "effect/rpc/RpcClientError";
4
3
  import type { SyncToken } from "@shivaedev/changes/syncToken.ts";
5
- import { LIVE_SYNC } from "#liveSyncRpc.ts";
4
+ import { LIVE_SYNC, type LiveSyncRpc } from "#liveSyncRpc.ts";
6
5
  import { commandSyncHeaders } from "#syncHeader.ts";
7
6
 
8
- type Erased = Rpc.Rpc<string, Schema.Top, Schema.Top, Schema.Top>;
9
-
10
- export function liveSyncRequest(client: RpcClient.RpcClient.Flat<Rpc.Any, RpcClientError>, token: SyncToken): Effect.Effect<void, unknown>;
11
- export function liveSyncRequest(
12
- client: RpcClient.RpcClient.Flat<Rpc.Any, RpcClientError>,
13
- token: SyncToken,
14
- ): Effect.Effect<unknown, unknown, unknown> {
15
- const erased: RpcClient.RpcClient.Flat<Erased, RpcClientError> = client;
16
- return erased(LIVE_SYNC, undefined, { headers: commandSyncHeaders(token) });
7
+ export function liveSyncRequest(client: RpcClient.RpcClient.Flat<Rpc.Any | LiveSyncRpc, RpcClientError>, token: SyncToken) {
8
+ return client(LIVE_SYNC, undefined, { headers: commandSyncHeaders(token) });
17
9
  }
@@ -9,3 +9,5 @@ export const LIVE_SYNC: string = LIVE_SYNC_TAG;
9
9
 
10
10
  // The browser's copy of the sync command: the host's declaration in LiveSync.ts is an operation file, which a browser bundle refuses.
11
11
  export const liveSyncRpc = RpcGroup.make(Rpc.make(LIVE_SYNC_TAG, { success: Schema.Void }).annotate(CommandInvalidation, { invalidates: () => [] }));
12
+
13
+ export type LiveSyncRpc = RpcGroup.Rpcs<typeof liveSyncRpc>;
@@ -1,15 +1,12 @@
1
- import type { Effect, Scope } from "effect";
1
+ import type { Effect, Schema, Scope } from "effect";
2
2
  import type { RpcMiddleware } from "effect/rpc";
3
- import type { InfrastructureFailure } from "@shivaedev/errors/infrastructure.ts";
4
3
  import type { RequirementRecord, RequirementsOf } from "@shivaedev/service/ServiceRequirements.ts";
5
4
  import type { Duplicated } from "#declarationError.ts";
6
5
  import type { OperationShape } from "#operation.ts";
7
- import type { QueryReadDenied } from "#readPolicyErrors.ts";
8
- import type { RejectedBy, RejectionSpecs } from "#rejection.ts";
9
- import type { Raised, RejectionProblem } from "#runProof.ts";
6
+ import type { Raised } from "#runProof.ts";
10
7
  import type { SubjectDeclaration, SubjectProvides } from "#subject.ts";
11
- import type { SuccessProblem } from "#successProof.ts";
12
8
  import type { WireEntry, WireEntryOf } from "#wire.ts";
9
+ import type { RejectionsDiffer, SuccessDiffers } from "#wireProof.ts";
13
10
 
14
11
  export interface OperationNeedsUndeclaredServices<TOperation extends string, TMissing> {
15
12
  readonly missingServices: TMissing;
@@ -17,12 +14,6 @@ export interface OperationNeedsUndeclaredServices<TOperation extends string, TMi
17
14
  readonly problem: "run or readPolicy uses services that the module's requires and middleware do not provide";
18
15
  }
19
16
 
20
- export interface OperationFailsOutsideItsRejections<TOperation extends string, TUndeclared> {
21
- readonly operation: TOperation;
22
- readonly problem: "run or readPolicy fails with errors outside the operation's rejections";
23
- readonly undeclaredFailures: TUndeclared;
24
- }
25
-
26
17
  type Regenerate = "the generated file is stale; run pnpm generate";
27
18
 
28
19
  export interface WireSuccessStale<TOperation extends string, TFix extends Regenerate, TRun, TWire> {
@@ -42,7 +33,7 @@ export interface WireRejectionsStale<TOperation extends string, TFix extends Reg
42
33
  export interface OperationMissingFromWire<TOperation extends string, TFix extends Regenerate> {
43
34
  readonly fix: TFix;
44
35
  readonly operation: TOperation;
45
- readonly problem: "the operation declares no success and the module's wire has no entry for it";
36
+ readonly problem: "run returns a value or fails with a rejection, and the module's wire has no entry for the operation";
46
37
  }
47
38
 
48
39
  export interface OperationNameRepeated<TOperation extends string> {
@@ -57,31 +48,27 @@ type Parts<TOperation> =
57
48
  | (TOperation extends { readonly kind: "query"; readonly readPolicy: infer TPolicy extends Effectful } ? ReturnType<TPolicy> : never);
58
49
 
59
50
  type Returns<TOperation> = TOperation extends { readonly run: infer TRun extends Effectful } ? Effect.Success<ReturnType<TRun>> : never;
60
- type Declared<TOperation> = TOperation extends { readonly rejections: infer TSpecs extends RejectionSpecs } ? RejectedBy<TSpecs> : never;
61
51
  type Tags<E> = E extends { readonly _tag: infer TTag } ? TTag : E;
62
- type Success<TOperation> = TOperation extends { readonly success: infer TSuccess } ? TSuccess : never;
63
52
  type NameOf<TOperation> = TOperation extends { readonly name: infer TName extends string } ? TName : string;
64
53
 
65
54
  type Missing<TOperation, TAllowed> = Exclude<Effect.Services<Parts<TOperation>>, TAllowed | Scope.Scope>;
66
- type Undeclared<TOperation> = Exclude<Effect.Error<Parts<TOperation>>, Declared<TOperation> | InfrastructureFailure | QueryReadDenied>;
67
55
 
68
- // An entry stands in for the operation's own success and rejections, so only the entry is compared with run.
69
- type WireProblem<TOperation, TEntry extends WireEntry> = [SuccessProblem<NameOf<TOperation>, TEntry["success"], Returns<TOperation>>] extends [never]
70
- ? [RejectionProblem<NameOf<TOperation>, TEntry["rejections"], Effect.Error<Parts<TOperation>>>] extends [never]
56
+ type WireProblem<TOperation, TEntry extends WireEntry> = [SuccessDiffers<TEntry["success"], Returns<TOperation>>] extends [never]
57
+ ? [RejectionsDiffer<TEntry["rejections"], Effect.Error<Parts<TOperation>>>] extends [never]
71
58
  ? never
72
59
  : WireRejectionsStale<NameOf<TOperation>, Regenerate, Tags<Raised<Effect.Error<Parts<TOperation>>>>, keyof TEntry["rejections"]>
73
60
  : WireSuccessStale<NameOf<TOperation>, Regenerate, Returns<TOperation>, TEntry["success"]["Type"]>;
74
61
 
75
- type OwnProblem<TOperation> = [Undeclared<TOperation>] extends [never]
76
- ? [SuccessProblem<NameOf<TOperation>, Success<TOperation>, Returns<TOperation>>] extends [never]
77
- ? never
78
- : OperationMissingFromWire<NameOf<TOperation>, Regenerate>
79
- : OperationFailsOutsideItsRejections<NameOf<TOperation>, Tags<Undeclared<TOperation>>>;
62
+ // Without an entry the operation is served with Void and the automatic rejections, which fit only a run that returns nothing
63
+ // and raises nothing else.
64
+ type EntryProblem<TOperation> = [SuccessDiffers<Schema.Void, Returns<TOperation>> | Raised<Effect.Error<Parts<TOperation>>>] extends [never]
65
+ ? never
66
+ : OperationMissingFromWire<NameOf<TOperation>, Regenerate>;
80
67
 
81
68
  type OperationProblem<TOperation, TWire, TAllowed> = [Missing<TOperation, TAllowed>] extends [never]
82
69
  ? WireEntryOf<TWire, NameOf<TOperation>> extends infer TEntry extends WireEntry
83
70
  ? WireProblem<TOperation, TEntry>
84
- : OwnProblem<TOperation>
71
+ : EntryProblem<TOperation>
85
72
  : OperationNeedsUndeclaredServices<NameOf<TOperation>, Missing<TOperation, TAllowed>>;
86
73
 
87
74
  type SubjectServices<TSubject> = TSubject extends SubjectDeclaration ? SubjectProvides<TSubject> : never;
@@ -96,6 +83,10 @@ type Problems<TOperations extends readonly OperationShape[], TWire, TAllowed> =
96
83
  | (Duplicated<TOperations> extends infer TName extends string ? (TName extends string ? OperationNameRepeated<TName> : never) : never);
97
84
 
98
85
  // The proof sits on the module's name, so the first line of the compiler's message names the operation and its problem.
99
- export type NameProof<TOperations extends readonly OperationShape[], TWire, TAllowed> = [Problems<TOperations, TWire, TAllowed>] extends [never]
86
+ // A definition without a wire leaves TWire at its constraint, whose index signature has every name; proving nothing then
87
+ // lets the compiler's own error say that wire is missing.
88
+ export type NameProof<TOperations extends readonly OperationShape[], TWire, TAllowed> = string extends keyof TWire
100
89
  ? unknown
101
- : Problems<TOperations, TWire, TAllowed>;
90
+ : [Problems<TOperations, TWire, TAllowed>] extends [never]
91
+ ? unknown
92
+ : Problems<TOperations, TWire, TAllowed>;
package/src/operation.ts CHANGED
@@ -5,9 +5,8 @@ import { type CommandDeclaration, type Loose, operation, type QueryDeclaration,
5
5
  import type { QueryServerReads } from "#QueryServerReads.ts";
6
6
  import { type QueryReadPolicy, signedIn, type Viewer } from "#readPolicy.ts";
7
7
  import type { Reject, RejectedBy, RejectionSpecs, Rejections, RejectionUnion } from "#rejection.ts";
8
- import type { ClassRejections, Pending, RunEffect, SpecsOf, SuccessSchema } from "#runProof.ts";
9
- import type { LooseCommand, LooseQuery, RunCommandDeclaration, RunQueryDeclaration, ServedCommand, ServedQueryOf } from "#servedOperation.ts";
10
- import { runOf, withAutomatic } from "#servedOperation.ts";
8
+ import type { LooseCommand, LooseQuery, RunCommandDeclaration, RunQueryDeclaration, ServedCommandOf, ServedQueryOf } from "#servedOperation.ts";
9
+ import { invalidatesOf, runOf, withAutomatic } from "#servedOperation.ts";
11
10
 
12
11
  export type PayloadSchema<TPayload extends Schema.Top | Schema.Struct.Fields> = TPayload extends Schema.Struct.Fields
13
12
  ? Schema.Struct<TPayload>
@@ -90,18 +89,16 @@ export function query<
90
89
  export function query<
91
90
  const TName extends string,
92
91
  TYielded extends Effect.Effect<unknown, unknown, unknown> = never,
93
- TReturn = Pending,
92
+ TReturn = unknown,
94
93
  TPayload extends Schema.Top | Schema.Struct.Fields = Schema.Void,
95
- TSuccess extends Schema.Top | undefined = undefined,
96
- const TSpecs extends ClassRejections | undefined = undefined,
97
94
  TPolicyError = never,
98
95
  TPolicyServices = never,
99
96
  TReads extends Effect.Effect<readonly Key[], unknown, unknown> = never,
100
97
  const TCollections extends readonly { readonly name: string }[] | undefined = undefined,
101
98
  >(
102
99
  name: TName,
103
- declaration: RunQueryDeclaration<TName, TPayload, TYielded, TReturn, TSuccess, TSpecs, TPolicyError, TPolicyServices, TReads, TCollections>,
104
- ): NoInfer<ServedQueryOf<TName, TPayload, TYielded, TReturn, TSuccess, TSpecs, TPolicyError, TPolicyServices, TReads>>;
100
+ declaration: RunQueryDeclaration<TName, TPayload, TYielded, TReturn, TPolicyError, TPolicyServices, TReads, TCollections>,
101
+ ): NoInfer<ServedQueryOf<TName, TPayload, TYielded, TReturn, TPolicyError, TPolicyServices, TReads>>;
105
102
  export function query(name: string, declaration: LooseQuery): QueryShape {
106
103
  const collections: readonly Key[] = declaration.readsCollections?.map((collection) => ({ _tag: "List", collection: collection.name })) ?? [];
107
104
  return {
@@ -126,16 +123,11 @@ export function command<
126
123
  export function command<
127
124
  const TName extends string,
128
125
  TYielded extends Effect.Effect<unknown, unknown, unknown> = never,
129
- TReturn = Pending,
126
+ TReturn = unknown,
130
127
  TPayload extends Schema.Top | Schema.Struct.Fields = Schema.Void,
131
- TSuccess extends Schema.Top | undefined = undefined,
132
- const TSpecs extends ClassRejections | undefined = undefined,
133
- >(
134
- name: TName,
135
- declaration: RunCommandDeclaration<TName, TPayload, TYielded, TReturn, TSuccess, TSpecs>,
136
- ): NoInfer<ServedCommand<TName, PayloadSchema<TPayload>, SuccessSchema<TSuccess>, SpecsOf<TSpecs>, RunEffect<TYielded, TReturn>>>;
128
+ >(name: TName, declaration: RunCommandDeclaration<TName, TPayload, TYielded, TReturn>): NoInfer<ServedCommandOf<TName, TPayload, TYielded, TReturn>>;
137
129
  export function command(name: string, declaration: LooseCommand): CommandShape {
138
- return { ...operation("command", name, withAutomatic(declaration)), invalidates: declaration.invalidates ?? (() => []), ...runOf(declaration) };
130
+ return { ...operation("command", name, withAutomatic(declaration)), invalidates: invalidatesOf(declaration), ...runOf(declaration) };
139
131
  }
140
132
 
141
133
  export function stream<
@@ -0,0 +1,15 @@
1
+ import { Context, Option } from "effect";
2
+ import { type Rpc, RpcSchema } from "effect/rpc";
3
+ import { ChangesQueries, CommandInvalidation, QueryDefinition } from "#serverMetadata.ts";
4
+
5
+ // A query, a live query's changes stream and any other stream only read; a command, or an RPC no contract marked, may write.
6
+ export function operationKind(rpc: Pick<Rpc.AnyWithProps, "annotations" | "successSchema">): "read" | "write" {
7
+ if (Option.isSome(Context.getOption(rpc.annotations, CommandInvalidation))) {
8
+ return "write";
9
+ }
10
+ const reads =
11
+ Option.isSome(Context.getOption(rpc.annotations, QueryDefinition))
12
+ || Option.isSome(Context.getOption(rpc.annotations, ChangesQueries))
13
+ || RpcSchema.isStreamSchema(rpc.successSchema);
14
+ return reads ? "read" : "write";
15
+ }
package/src/rpcClient.ts CHANGED
@@ -10,7 +10,7 @@ import { Activity } from "#clientActivity.ts";
10
10
  import type { ClientOptions } from "#clientOptions.ts";
11
11
  import { ConnectionScope, connectionProtocol } from "#connectionProtocol.ts";
12
12
  import { commandConnections } from "#connectionReadiness.ts";
13
- import { liveSyncRpc } from "#liveSyncRpc.ts";
13
+ import { type LiveSyncRpc, liveSyncRpc } from "#liveSyncRpc.ts";
14
14
  import { reflections } from "#reflection.ts";
15
15
  import type { ResumeWindow } from "#resume.ts";
16
16
  import { CommandInvalidation } from "#serverMetadata.ts";
@@ -53,7 +53,7 @@ export function rpcClient(name: string, source: RpcSource, options: ClientOption
53
53
  }
54
54
  const protocolFor = configuredProtocol();
55
55
  const protocol = protocolFor(undefined);
56
- function observeClient(client: RpcClient.RpcClient.Flat<Rpc.Any, RpcClientError>, wait: Effect.Effect<void, RpcClientError>) {
56
+ function observeClient(client: RpcClient.RpcClient.Flat<Rpc.Any | LiveSyncRpc, RpcClientError>, wait: Effect.Effect<void, RpcClientError>) {
57
57
  const observed = new Proxy(client, {
58
58
  apply(target, receiver, args) {
59
59
  const result = Reflect.apply(target, receiver, args);
@@ -72,7 +72,7 @@ export function rpcClient(name: string, source: RpcSource, options: ClientOption
72
72
  const make = Effect.gen(function* () {
73
73
  const { connection, reflection } = yield* ConnectionScope;
74
74
  const wait = Effect.suspend(() => (connection.isReady() ? Effect.void : activity.hold(connection.wait)));
75
- const native = yield* RpcClient.make<Rpc.Any, true>(group, { flatten: true });
75
+ const native = yield* RpcClient.make(group, { flatten: true });
76
76
  const observed = observeClient(native, wait);
77
77
  // Only the shared socket proves a command reaches the host that holds its streams; any other protocol syncs after the reply.
78
78
  reflections.set(observed, { piggyback: options.protocol === undefined, reflection });
package/src/runProof.ts CHANGED
@@ -1,9 +1,8 @@
1
- import type { Effect, Schema } from "effect";
1
+ import type { Effect } from "effect";
2
2
  import type { InfrastructureFailure } from "@shivaedev/errors/infrastructure.ts";
3
3
  import type { InternalServerError, ServiceUnavailable } from "@shivaedev/errors/taxonomy.ts";
4
4
  import type { QueryReadDenied } from "#readPolicyErrors.ts";
5
5
  import type { TaggedRejection } from "#rejection.ts";
6
- import type { Identical, SuccessProblem } from "#successProof.ts";
7
6
 
8
7
  export type RunBody<TPayload, TYielded, A> = (payload: TPayload) => Generator<TYielded, A, never>;
9
8
 
@@ -22,75 +21,18 @@ export interface Automatic {
22
21
 
23
22
  export type Raised<E> = Exclude<E, InfrastructureFailure | QueryReadDenied | InternalServerError | ServiceUnavailable>;
24
23
 
25
- export interface RunFailsOutsideRejections<TOperation extends string, TTags> {
26
- readonly missingRejections: TTags;
27
- readonly operation: TOperation;
28
- }
29
-
30
- export interface RejectionsRunNeverRaises<TOperation extends string, TTags> {
31
- readonly neverRaised: TTags;
32
- readonly operation: TOperation;
33
- }
34
-
35
- export interface RejectionAutomatic<TOperation extends string, TTags> {
36
- readonly automatic: TTags;
37
- readonly operation: TOperation;
38
- }
39
-
40
- export interface RejectionClassDiffers<TOperation extends string, TTags> {
41
- readonly operation: TOperation;
42
- readonly raisedClassDiffers: TTags;
43
- }
44
-
45
24
  export interface RunReturnsAny<TOperation extends string, TFix extends string> {
46
25
  readonly fix: TFix;
47
26
  readonly operation: TOperation;
48
27
  }
49
28
 
50
- type Tags<E> = E extends { readonly _tag: infer TTag extends string } ? TTag : never;
51
29
  type IsAny<T> = 0 extends 1 & T ? true : false;
52
- type Declared<TSpecs> = TSpecs extends ClassRejections ? keyof TSpecs & string : never;
53
- type AutomaticTags = keyof Automatic;
54
-
55
- type DifferentClasses<TSpecs, E> = {
56
- readonly [TTag in Declared<TSpecs>]: TSpecs extends { readonly [TKey in TTag]: new (...args: never) => infer TDeclared }
57
- ? Identical<TDeclared, Extract<Raised<E>, { readonly _tag: TTag }>> extends true
58
- ? never
59
- : TTag
60
- : never;
61
- }[Declared<TSpecs>];
62
-
63
- export type RejectionProblem<TName extends string, TSpecs, E> = TSpecs extends undefined
64
- ? never
65
- : [Extract<Declared<TSpecs>, AutomaticTags>] extends [never]
66
- ? [Exclude<Tags<Raised<E>>, Declared<TSpecs>>] extends [never]
67
- ? [Exclude<Declared<TSpecs>, Tags<Raised<E>>>] extends [never]
68
- ? [DifferentClasses<TSpecs, E>] extends [never]
69
- ? never
70
- : RejectionClassDiffers<TName, DifferentClasses<TSpecs, E>>
71
- : RejectionsRunNeverRaises<TName, Exclude<Declared<TSpecs>, Tags<Raised<E>>>>
72
- : RunFailsOutsideRejections<TName, Exclude<Tags<Raised<E>>, Declared<TSpecs>>>
73
- : RejectionAutomatic<TName, Extract<Declared<TSpecs>, AutomaticTags>>;
74
30
 
75
- type Problems<TName extends string, TSuccess, TSpecs, TReturn, E> = SuccessProblem<TName, TSuccess, TReturn> | RejectionProblem<TName, TSpecs, E>;
76
-
77
- export type SuccessSchema<TSuccess> = TSuccess extends Schema.Top ? TSuccess : Schema.Void;
78
31
  // A mapped type, unlike the Automatic interface, satisfies the index signature of RejectionSpecs.
79
32
  type Flat<T> = { readonly [TKey in keyof T]: T[TKey] };
80
33
  export type SpecsOf<TSpecs> = TSpecs extends ClassRejections ? Flat<TSpecs & Automatic> : Flat<Automatic>;
81
34
 
82
- // TypeScript checks the declaration once with run skipped, before it infers run's types; Pending is the default it sees then.
83
- export interface Pending {
84
- readonly pendingInference: unique symbol;
85
- }
86
-
87
- type IsPending<TReturn> = [TReturn] extends [never] ? false : [TReturn] extends [Pending] ? true : false;
88
-
89
- export type RunCheck<TName extends string, TSuccess, TSpecs, TReturn, E> =
35
+ export type RunCheck<TName extends string, TReturn> =
90
36
  IsAny<TReturn> extends true
91
37
  ? { readonly operationProblem: RunReturnsAny<TName, "decode the value with a schema, or give run's return a type"> }
92
- : IsPending<TReturn> extends true
93
- ? unknown
94
- : [Problems<TName, TSuccess, TSpecs, TReturn, E>] extends [never]
95
- ? unknown
96
- : { readonly operationProblem: Problems<TName, TSuccess, TSpecs, TReturn, E> };
38
+ : unknown;