@shivaedev/contract 0.32.0 → 0.34.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 (61) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +25 -7
  3. package/dist/bind.d.ts +2 -1
  4. package/dist/bind.d.ts.map +1 -1
  5. package/dist/bind.js.map +1 -1
  6. package/dist/clientOptions.d.ts +1 -0
  7. package/dist/clientOptions.d.ts.map +1 -1
  8. package/dist/composeBindings.d.ts.map +1 -1
  9. package/dist/composeBindings.js +21 -6
  10. package/dist/composeBindings.js.map +1 -1
  11. package/dist/contract.d.ts +7 -10
  12. package/dist/contract.d.ts.map +1 -1
  13. package/dist/contract.js +6 -2
  14. package/dist/contract.js.map +1 -1
  15. package/dist/internal/clientOperations.d.ts.map +1 -1
  16. package/dist/internal/clientOperations.js +4 -3
  17. package/dist/internal/clientOperations.js.map +1 -1
  18. package/dist/internal/commandPayload.d.ts +4 -0
  19. package/dist/internal/commandPayload.d.ts.map +1 -0
  20. package/dist/internal/commandPayload.js +9 -0
  21. package/dist/internal/commandPayload.js.map +1 -0
  22. package/dist/internal/queryReactivity.d.ts.map +1 -1
  23. package/dist/internal/queryReactivity.js +2 -0
  24. package/dist/internal/queryReactivity.js.map +1 -1
  25. package/dist/internal/rpcClient.d.ts.map +1 -1
  26. package/dist/internal/rpcClient.js +1 -0
  27. package/dist/internal/rpcClient.js.map +1 -1
  28. package/dist/internal/subjectMiddleware.d.ts +16 -0
  29. package/dist/internal/subjectMiddleware.d.ts.map +1 -0
  30. package/dist/internal/subjectMiddleware.js +8 -0
  31. package/dist/internal/subjectMiddleware.js.map +1 -0
  32. package/dist/operationRpc.d.ts +11 -0
  33. package/dist/operationRpc.d.ts.map +1 -0
  34. package/dist/operationRpc.js +2 -0
  35. package/dist/operationRpc.js.map +1 -0
  36. package/dist/subject.d.ts +10 -0
  37. package/dist/subject.d.ts.map +1 -0
  38. package/dist/subject.js +2 -0
  39. package/dist/subject.js.map +1 -0
  40. package/dist/subjectLayers.d.ts +12 -0
  41. package/dist/subjectLayers.d.ts.map +1 -0
  42. package/dist/subjectLayers.js +22 -0
  43. package/dist/subjectLayers.js.map +1 -0
  44. package/package.json +10 -9
  45. package/src/bind.ts +2 -1
  46. package/src/clientOptions.ts +1 -0
  47. package/src/composeBindings.ts +21 -8
  48. package/src/contract.ts +18 -25
  49. package/src/internal/clientOperations.ts +13 -3
  50. package/src/internal/commandPayload.ts +16 -0
  51. package/src/internal/queryReactivity.ts +2 -0
  52. package/src/internal/rpcClient.ts +1 -0
  53. package/src/internal/subjectMiddleware.ts +22 -0
  54. package/src/operationRpc.ts +25 -0
  55. package/src/subject.ts +15 -0
  56. package/src/subjectLayers.ts +33 -0
  57. package/dist/testing.d.ts +0 -17
  58. package/dist/testing.d.ts.map +0 -1
  59. package/dist/testing.js +0 -51
  60. package/dist/testing.js.map +0 -1
  61. package/src/testing.ts +0 -81
@@ -0,0 +1,10 @@
1
+ import type { Effect, Schema } from "effect";
2
+ import type { Rpc, RpcMiddleware } from "effect/rpc";
3
+ import type { subjectMiddleware } from "#internal/subjectMiddleware.ts";
4
+ export interface SubjectDeclaration {
5
+ readonly error: Schema.Top;
6
+ readonly middleware: Effect.Effect<RpcMiddleware.Any, never, unknown>;
7
+ }
8
+ export type SubjectProvides<TSubject extends SubjectDeclaration> = Effect.Success<TSubject["middleware"]> extends RpcMiddleware.RpcMiddleware<infer TProvides, infer _E, infer _R> ? TProvides : never;
9
+ export type WithSubject<TRpcs extends Rpc.Any, TSubject extends SubjectDeclaration | undefined> = TSubject extends SubjectDeclaration ? Rpc.AddMiddleware<TRpcs, ReturnType<typeof subjectMiddleware<TSubject>>> : TRpcs;
10
+ //# sourceMappingURL=subject.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subject.d.ts","sourceRoot":"","sources":["../src/subject.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC7C,OAAO,KAAK,EAAE,GAAG,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAExE,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,CAAC;IAC3B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,GAAG,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;CACtE;AAED,MAAM,MAAM,eAAe,CAAC,QAAQ,SAAS,kBAAkB,IAC9D,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC,SAAS,aAAa,CAAC,aAAa,CAAC,MAAM,SAAS,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,CAAC,GAAG,SAAS,GAAG,KAAK,CAAC;AAErI,MAAM,MAAM,WAAW,CAAC,KAAK,SAAS,GAAG,CAAC,GAAG,EAAE,QAAQ,SAAS,kBAAkB,GAAG,SAAS,IAAI,QAAQ,SAAS,kBAAkB,GAClI,GAAG,CAAC,aAAa,CAAC,KAAK,EAAE,UAAU,CAAC,OAAO,iBAAiB,CAAC,QAAQ,CAAC,CAAC,CAAC,GACxE,KAAK,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=subject.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subject.js","sourceRoot":"","sources":["../src/subject.ts"],"names":[],"mappings":""}
@@ -0,0 +1,12 @@
1
+ import { type Context, type Effect, Layer } from "effect";
2
+ import { Rpc, type RpcGroup } from "effect/rpc";
3
+ import { SUBJECT_TYPE_ID } from "#internal/subjectMiddleware.ts";
4
+ import type { SubjectDeclaration } from "#subject.ts";
5
+ type Middleware<R extends Rpc.Any> = R extends {
6
+ readonly middlewares: ReadonlySet<infer TMiddleware>;
7
+ } ? Extract<TMiddleware, {
8
+ readonly [SUBJECT_TYPE_ID]: SubjectDeclaration;
9
+ }> : never;
10
+ export declare function subjectLayers<R extends Rpc.Any>(group: RpcGroup.RpcGroup<R>): Layer.Layer<Context.Service.Identifier<Middleware<R>>, never, Effect.Services<Middleware<R>[typeof SUBJECT_TYPE_ID]["middleware"]>>;
11
+ export {};
12
+ //# sourceMappingURL=subjectLayers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subjectLayers.d.ts","sourceRoot":"","sources":["../src/subjectLayers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,MAAM,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC1D,OAAO,EAAE,GAAG,EAAE,KAAK,QAAQ,EAAsB,MAAM,YAAY,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEtD,KAAK,UAAU,CAAC,CAAC,SAAS,GAAG,CAAC,GAAG,IAAI,CAAC,SAAS;IAAE,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC,MAAM,WAAW,CAAC,CAAA;CAAE,GACpG,OAAO,CAAC,WAAW,EAAE;IAAE,QAAQ,CAAC,CAAC,eAAe,CAAC,EAAE,kBAAkB,CAAA;CAAE,CAAC,GACxE,KAAK,CAAC;AAQT,wBAAgB,aAAa,CAAC,CAAC,SAAS,GAAG,CAAC,GAAG,EAC9C,KAAK,EAAE,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,GACzB,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,OAAO,eAAe,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC"}
@@ -0,0 +1,22 @@
1
+ import { Layer } from "effect";
2
+ import { Rpc } from "effect/rpc";
3
+ import { SUBJECT_TYPE_ID } from "#internal/subjectMiddleware.ts";
4
+ function isSubject(middleware) {
5
+ return SUBJECT_TYPE_ID in middleware;
6
+ }
7
+ export function subjectLayers(group) {
8
+ const layers = [];
9
+ for (const rpc of group.requests.values()) {
10
+ if (!Rpc.isRpc(rpc)) {
11
+ continue;
12
+ }
13
+ const middlewares = rpc.middlewares;
14
+ for (const middleware of middlewares) {
15
+ if (isSubject(middleware)) {
16
+ layers.push(Layer.effect(middleware, middleware[SUBJECT_TYPE_ID].middleware));
17
+ }
18
+ }
19
+ }
20
+ return Layer.mergeAll(Layer.empty, ...layers);
21
+ }
22
+ //# sourceMappingURL=subjectLayers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"subjectLayers.js","sourceRoot":"","sources":["../src/subjectLayers.ts"],"names":[],"mappings":"AAAA,OAAO,EAA6B,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC1D,OAAO,EAAE,GAAG,EAAqC,MAAM,YAAY,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAOjE,SAAS,SAAS,CAAC,UAA6C;IAG/D,OAAO,eAAe,IAAI,UAAU,CAAC;AACtC,CAAC;AAKD,MAAM,UAAU,aAAa,CAAC,KAAiC;IAC9D,MAAM,MAAM,GAAyC,EAAE,CAAC;IACxD,KAAK,MAAM,GAAG,IAAI,KAAK,CAAC,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC;QAC3C,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;YACrB,SAAS;QACV,CAAC;QACD,MAAM,WAAW,GAAmD,GAAG,CAAC,WAAW,CAAC;QACpF,KAAK,MAAM,UAAU,IAAI,WAAW,EAAE,CAAC;YACtC,IAAI,SAAS,CAAC,UAAU,CAAC,EAAE,CAAC;gBAC3B,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,UAAU,EAAE,UAAU,CAAC,eAAe,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC;YAC/E,CAAC;QACF,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,EAAE,GAAG,MAAM,CAAC,CAAC;AAC/C,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shivaedev/contract",
3
- "version": "0.32.0",
3
+ "version": "0.34.0",
4
4
  "description": "Typed query and command contracts over native Effect RPC and reactivity",
5
5
  "keywords": [
6
6
  "effect"
@@ -44,20 +44,21 @@
44
44
  ],
45
45
  "dependencies": {
46
46
  "@shivaedev/changes": "0.9.0",
47
- "@shivaedev/service": "0.6.1",
47
+ "@shivaedev/service": "0.6.2",
48
48
  "@shivaedev/types": "0.3.0"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@effect/platform-node": "4.0.6",
52
52
  "@effect/vitest": "4.0.6",
53
- "@shivaedev/errors": "0.6.0",
54
- "@shivaedev/identity": "0.20.0",
55
- "@shivaedev/quality": "0.57.0",
56
- "@shivaedev/server": "0.20.0",
57
- "@shivaedev/sql": "0.34.0",
53
+ "@shivaedev/errors": "0.8.0",
54
+ "@shivaedev/identity": "0.23.0",
55
+ "@shivaedev/quality": "0.58.0",
56
+ "@shivaedev/server": "0.22.0",
57
+ "@shivaedev/sql": "0.36.1",
58
58
  "@shivaedev/test": "0.14.0",
59
- "@shivaedev/test-sql": "0.17.0",
60
- "@shivaedev/test-story": "0.35.0",
59
+ "@shivaedev/test-kits": "0.2.1",
60
+ "@shivaedev/test-sql": "0.18.2",
61
+ "@shivaedev/test-story": "0.37.0",
61
62
  "@types/node": "24.19.2",
62
63
  "effect": "4.0.6",
63
64
  "esbuild": "0.28.2",
package/src/bind.ts CHANGED
@@ -10,10 +10,11 @@ import type { RpcClientError } from "effect/rpc/RpcClientError";
10
10
  import { bindingOwner } from "#adapters/bindingOwner.ts";
11
11
  import { automaticLive, type LiveBound, LiveConnection } from "#automaticLive.ts";
12
12
  import type { ClientOptions, MadeClient } from "#clientOptions.ts";
13
- import type { Contract, Declared, Tag } from "#contract.ts";
13
+ import type { Contract, Declared } from "#contract.ts";
14
14
  import { clientOperations } from "#internal/clientOperations.ts";
15
15
  import { type RpcSource, rpcClient } from "#internal/rpcClient.ts";
16
16
  import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
17
+ import type { Tag } from "#operationRpc.ts";
17
18
  import type { ResumeSource, ResumeWindow } from "#resume.ts";
18
19
 
19
20
  export type Failure<R extends Rpc.Any> =
@@ -17,6 +17,7 @@ export interface ClientOptions {
17
17
  readonly protocol?: Layer.Layer<RpcClient.Protocol> | ((identity: string | undefined) => Layer.Layer<RpcClient.Protocol>);
18
18
  readonly resume?: ResumeSource;
19
19
  readonly resumeWindow?: ResumeWindow;
20
+ readonly runtime?: Atom.RuntimeFactory;
20
21
  readonly url: string;
21
22
  readonly webSocketConstructor?: Layer.Layer<Socket.WebSocketConstructor>;
22
23
  }
@@ -10,18 +10,31 @@ export function composeBindings<TClient extends object>(client: TClient, binding
10
10
  return { ...client, [ComposedBindings]: bindings };
11
11
  }
12
12
 
13
+ function isLiveBound(client: object): client is LiveBound {
14
+ return LiveConnection in client;
15
+ }
16
+
13
17
  function isComposition(client: object): client is BindingComposition {
14
18
  return ComposedBindings in client;
15
19
  }
16
20
 
17
21
  export function liveBindings(client: unknown): readonly LiveBound[] {
18
- if (typeof client !== "object" || client === null) {
19
- return [];
20
- }
21
- if (isComposition(client)) {
22
- return client[ComposedBindings];
22
+ const pending = [client];
23
+ const visited = new Set<object>();
24
+ const bindings: LiveBound[] = [];
25
+ for (const value of pending) {
26
+ if (typeof value !== "object" || value === null || visited.has(value)) {
27
+ continue;
28
+ }
29
+ visited.add(value);
30
+ if (isComposition(value)) {
31
+ pending.push(...value[ComposedBindings]);
32
+ } else {
33
+ if (isLiveBound(value)) {
34
+ bindings.push(value);
35
+ }
36
+ pending.push(...Object.values(value));
37
+ }
23
38
  }
24
- return [client, ...Object.values(client)].filter(
25
- (value): value is LiveBound => typeof value === "object" && value !== null && LiveConnection in value,
26
- );
39
+ return bindings;
27
40
  }
package/src/contract.ts CHANGED
@@ -1,32 +1,16 @@
1
1
  import { Schema } from "effect";
2
- import { Rpc, RpcGroup, type RpcMiddleware, type RpcSchema } from "effect/rpc";
2
+ import { Rpc, RpcGroup, type RpcMiddleware } from "effect/rpc";
3
3
  import { declarationError, type Unique } from "#internal/declarationError.ts";
4
- import type { CommandShape, OperationShape, QueryShape, StreamShape } from "#operation.ts";
4
+ import { subjectMiddleware } from "#internal/subjectMiddleware.ts";
5
+ import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
6
+ import type { OperationRpc } from "#operationRpc.ts";
5
7
  import { ReadPolicyGuard } from "#ReadPolicyGuard.ts";
6
8
  import { QueryReadDenied } from "#readPolicyErrors.ts";
7
9
  import { changesRpc, KeyScope, operationAnnotations } from "#serverMetadata.ts";
8
-
9
- export type Tag<TContract extends string, TName extends string> = `${TContract}.${TName}`;
10
+ import type { SubjectDeclaration, WithSubject } from "#subject.ts";
10
11
 
11
12
  export type QueryServices<TQuery> = TQuery extends QueryShape<unknown, infer R> ? R : never;
12
13
 
13
- type OperationError<TOperation extends OperationShape> = TOperation extends QueryShape
14
- ? Schema.Union<readonly [TOperation["error"], typeof QueryReadDenied]>
15
- : TOperation["error"];
16
-
17
- export type OperationRpc<TContract extends string, TOperation> = TOperation extends OperationShape
18
- ? TOperation extends StreamShape
19
- ? Rpc.Rpc<Tag<TContract, TOperation["name"]>, TOperation["payload"], RpcSchema.Stream<TOperation["success"], TOperation["error"]>, Schema.Never>
20
- : Rpc.Rpc<
21
- Tag<TContract, TOperation["name"]>,
22
- TOperation["payload"],
23
- TOperation["success"],
24
- OperationError<TOperation>,
25
- TOperation extends QueryShape ? typeof ReadPolicyGuard : never,
26
- QueryServices<TOperation>
27
- >
28
- : never;
29
-
30
14
  export interface Declared<
31
15
  TName extends string,
32
16
  TQueries extends readonly QueryShape[],
@@ -92,10 +76,12 @@ export function contract<
92
76
  const TCommands extends readonly CommandShape[] = readonly [],
93
77
  const TStreams extends readonly StreamShape[] = readonly [],
94
78
  const TScope extends "session" | undefined = undefined,
79
+ const TSubject extends SubjectDeclaration | undefined = undefined,
95
80
  >(
96
81
  name: TName,
97
82
  operations: {
98
83
  readonly keyScope?: TScope;
84
+ readonly subject?: TSubject;
99
85
  readonly queries?: TQueries & Unique<TQueries>;
100
86
  readonly commands?: TCommands & Unique<[...TQueries, ...TCommands]>;
101
87
  readonly streams?: TStreams & Unique<[...TQueries, ...TCommands, ...TStreams]>;
@@ -104,8 +90,11 @@ export function contract<
104
90
  TName,
105
91
  TQueries,
106
92
  TCommands,
107
- | OperationRpc<TName, TQueries[number] | TCommands[number] | TStreams[number]>
108
- | Rpc.AddMiddleware<ReturnType<typeof changesRpc<TName, TQueries>>, typeof ReadPolicyGuard>,
93
+ WithSubject<
94
+ | OperationRpc<TName, TQueries[number] | TCommands[number] | TStreams[number]>
95
+ | Rpc.AddMiddleware<ReturnType<typeof changesRpc<TName, TQueries>>, typeof ReadPolicyGuard>,
96
+ TSubject
97
+ >,
109
98
  TStreams,
110
99
  TScope
111
100
  >;
@@ -113,6 +102,7 @@ export function contract(
113
102
  name: string,
114
103
  operations: {
115
104
  readonly keyScope?: "session";
105
+ readonly subject?: SubjectDeclaration;
116
106
  readonly queries?: readonly QueryShape[];
117
107
  readonly commands?: readonly CommandShape[];
118
108
  readonly streams?: readonly StreamShape[];
@@ -127,11 +117,14 @@ export function contract(
127
117
  stream: operation.kind === "stream",
128
118
  success: operation.success,
129
119
  }).annotateMerge(operationAnnotations(operation, keyScope));
130
- return operation.kind === "query" ? rpc.middleware(ReadPolicyGuard) : rpc;
120
+ const guarded = operation.kind === "query" ? rpc.middleware(ReadPolicyGuard) : rpc;
121
+ return operations.subject === undefined ? guarded : guarded.middleware(subjectMiddleware(`${name}.${operation.name}`, operations.subject));
131
122
  });
132
123
  const application = RpcGroup.make(...rpcs);
133
124
  const changes = changesRpc(name, queries).middleware(ReadPolicyGuard);
134
- return withDeclaration(application.add(keyScope === undefined ? changes : changes.annotate(KeyScope, keyScope)), application, {
125
+ const subjectChanges = operations.subject === undefined ? changes : changes.middleware(subjectMiddleware(`${name}.$changes`, operations.subject));
126
+ const group = application.add(keyScope === undefined ? subjectChanges : subjectChanges.annotate(KeyScope, keyScope));
127
+ return withDeclaration(group, application, {
135
128
  commands,
136
129
  keyScope,
137
130
  name,
@@ -10,10 +10,11 @@ import { clientId } from "#adapters/clientId.ts";
10
10
  import type { automaticLive } from "#automaticLive.ts";
11
11
  import type { QueryOptions } from "#bind.ts";
12
12
  import { clientInvalidationKeys, clientReadKeys } from "#clientKeys.ts";
13
+ import { clientActivities } from "#internal/clientActivity.ts";
14
+ import { commandPayload } from "#internal/commandPayload.ts";
15
+ import { queryReactivity } from "#internal/queryReactivity.ts";
13
16
  import type { CommandShape, QueryShape } from "#operation.ts";
14
17
  import { shareQuerySignals } from "#querySignals.ts";
15
- import { clientActivities } from "./clientActivity.ts";
16
- import { queryReactivity } from "./queryReactivity.ts";
17
18
 
18
19
  type ErasedClient = AtomRpc.AtomRpcClient<unknown, string, Rpc.Rpc<string, Schema.Top, Schema.Top, Schema.Top>>;
19
20
 
@@ -74,7 +75,16 @@ function boundCommand(service: ErasedClient, tag: string, command: CommandShape,
74
75
  }
75
76
  return {
76
77
  run: (payload: unknown) =>
77
- run(service, service.use((client) => client(tag, payload)).pipe(Effect.tap((result) => invalidate(payload, result))), owner),
78
+ run(
79
+ service,
80
+ service.use((client) =>
81
+ commandPayload(command, payload).pipe(
82
+ Effect.flatMap((validated) => client(tag, validated)),
83
+ Effect.tap((result) => invalidate(payload, result)),
84
+ ),
85
+ ),
86
+ owner,
87
+ ),
78
88
  };
79
89
  }
80
90
 
@@ -0,0 +1,16 @@
1
+ import { Effect, Predicate, Schema } from "effect";
2
+ import type { CommandShape } from "#operation.ts";
3
+
4
+ export function commandPayload(command: CommandShape, payload: unknown) {
5
+ if (!(Predicate.hasProperty(command.Rejection, "BadRequest") && Schema.isSchema(command.Rejection.BadRequest))) {
6
+ return Effect.succeed(payload);
7
+ }
8
+ const rejection = command.Rejection.BadRequest;
9
+ return command.payload.makeEffect(payload).pipe(
10
+ Effect.mapError((issue) => new Schema.SchemaError(issue)),
11
+ Effect.tap(Schema.encodeUnknownEffect(Schema.toCodecJson(command.payload))),
12
+ Effect.catchTag("SchemaError", (error) =>
13
+ Schema.decodeUnknownEffect(rejection)({ _tag: "BadRequest", message: error.message }).pipe(Effect.orDie, Effect.flatMap(Effect.fail)),
14
+ ),
15
+ );
16
+ }
@@ -110,6 +110,8 @@ export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: (
110
110
  const active = pending;
111
111
  pending = undefined;
112
112
  if (active()) {
113
+ get.set(timer, Atom.Interrupt);
114
+ scheduled = false;
113
115
  reread();
114
116
  }
115
117
  dequeue();
@@ -47,6 +47,7 @@ export function rpcClient(name: string, source: RpcSource, options: ClientOption
47
47
  group,
48
48
  makeEffect: make,
49
49
  protocol: typeof customProtocol === "object" ? customProtocol : (get) => protocolFor(get(socketIdentity)),
50
+ runtime: options.runtime,
50
51
  });
51
52
  clientActivities.set(Client, activity);
52
53
  const directClient = Effect.flatMap(Layer.build(protocol), (context) =>
@@ -0,0 +1,22 @@
1
+ import { RpcMiddleware } from "effect/rpc";
2
+ import type { SubjectDeclaration, SubjectProvides } from "#subject.ts";
3
+
4
+ export const SUBJECT_TYPE_ID = "@shivaedev/contract/SubjectDeclaration";
5
+
6
+ interface SubjectMiddleware<TSubject extends SubjectDeclaration> extends RpcMiddleware.AnyId {
7
+ readonly [RpcMiddleware.TypeId]: {
8
+ readonly provides: SubjectProvides<TSubject>;
9
+ readonly requires: never;
10
+ readonly error: TSubject["error"];
11
+ readonly clientError: never;
12
+ };
13
+ }
14
+
15
+ export function subjectMiddleware<TSubject extends SubjectDeclaration>(name: string, subject: TSubject) {
16
+ const error: TSubject["error"] = subject.error;
17
+ const middleware = RpcMiddleware.Service<SubjectMiddleware<TSubject>, { provides: SubjectProvides<TSubject> }>()(
18
+ `@shivaedev/contract/Subject/${name}`,
19
+ { error },
20
+ );
21
+ return Object.assign(middleware, { [SUBJECT_TYPE_ID]: subject });
22
+ }
@@ -0,0 +1,25 @@
1
+ import type { Schema } from "effect";
2
+ import type { Rpc, RpcSchema } from "effect/rpc";
3
+ import type { QueryServices } from "#contract.ts";
4
+ import type { OperationShape, QueryShape, StreamShape } from "#operation.ts";
5
+ import type { ReadPolicyGuard } from "#ReadPolicyGuard.ts";
6
+ import type { QueryReadDenied } from "#readPolicyErrors.ts";
7
+
8
+ export type Tag<TContract extends string, TName extends string> = `${TContract}.${TName}`;
9
+
10
+ type OperationError<TOperation extends OperationShape> = TOperation extends QueryShape
11
+ ? Schema.Union<readonly [TOperation["error"], typeof QueryReadDenied]>
12
+ : TOperation["error"];
13
+
14
+ export type OperationRpc<TContract extends string, TOperation> = TOperation extends OperationShape
15
+ ? TOperation extends StreamShape
16
+ ? Rpc.Rpc<Tag<TContract, TOperation["name"]>, TOperation["payload"], RpcSchema.Stream<TOperation["success"], TOperation["error"]>, Schema.Never>
17
+ : Rpc.Rpc<
18
+ Tag<TContract, TOperation["name"]>,
19
+ TOperation["payload"],
20
+ TOperation["success"],
21
+ OperationError<TOperation>,
22
+ TOperation extends QueryShape ? typeof ReadPolicyGuard : never,
23
+ QueryServices<TOperation>
24
+ >
25
+ : never;
package/src/subject.ts ADDED
@@ -0,0 +1,15 @@
1
+ import type { Effect, Schema } from "effect";
2
+ import type { Rpc, RpcMiddleware } from "effect/rpc";
3
+ import type { subjectMiddleware } from "#internal/subjectMiddleware.ts";
4
+
5
+ export interface SubjectDeclaration {
6
+ readonly error: Schema.Top;
7
+ readonly middleware: Effect.Effect<RpcMiddleware.Any, never, unknown>;
8
+ }
9
+
10
+ export type SubjectProvides<TSubject extends SubjectDeclaration> =
11
+ Effect.Success<TSubject["middleware"]> extends RpcMiddleware.RpcMiddleware<infer TProvides, infer _E, infer _R> ? TProvides : never;
12
+
13
+ export type WithSubject<TRpcs extends Rpc.Any, TSubject extends SubjectDeclaration | undefined> = TSubject extends SubjectDeclaration
14
+ ? Rpc.AddMiddleware<TRpcs, ReturnType<typeof subjectMiddleware<TSubject>>>
15
+ : TRpcs;
@@ -0,0 +1,33 @@
1
+ import { type Context, type Effect, Layer } from "effect";
2
+ import { Rpc, type RpcGroup, type RpcMiddleware } from "effect/rpc";
3
+ import { SUBJECT_TYPE_ID } from "#internal/subjectMiddleware.ts";
4
+ import type { SubjectDeclaration } from "#subject.ts";
5
+
6
+ type Middleware<R extends Rpc.Any> = R extends { readonly middlewares: ReadonlySet<infer TMiddleware> }
7
+ ? Extract<TMiddleware, { readonly [SUBJECT_TYPE_ID]: SubjectDeclaration }>
8
+ : never;
9
+
10
+ function isSubject(middleware: RpcMiddleware.AnyServiceWithProps): middleware is RpcMiddleware.AnyServiceWithProps & {
11
+ readonly [SUBJECT_TYPE_ID]: SubjectDeclaration;
12
+ } {
13
+ return SUBJECT_TYPE_ID in middleware;
14
+ }
15
+
16
+ export function subjectLayers<R extends Rpc.Any>(
17
+ group: RpcGroup.RpcGroup<R>,
18
+ ): Layer.Layer<Context.Service.Identifier<Middleware<R>>, never, Effect.Services<Middleware<R>[typeof SUBJECT_TYPE_ID]["middleware"]>>;
19
+ export function subjectLayers(group: RpcGroup.RpcGroup<Rpc.Any>) {
20
+ const layers: Layer.Layer<never, never, unknown>[] = [];
21
+ for (const rpc of group.requests.values()) {
22
+ if (!Rpc.isRpc(rpc)) {
23
+ continue;
24
+ }
25
+ const middlewares: ReadonlySet<RpcMiddleware.AnyServiceWithProps> = rpc.middlewares;
26
+ for (const middleware of middlewares) {
27
+ if (isSubject(middleware)) {
28
+ layers.push(Layer.effect(middleware, middleware[SUBJECT_TYPE_ID].middleware));
29
+ }
30
+ }
31
+ }
32
+ return Layer.mergeAll(Layer.empty, ...layers);
33
+ }
package/dist/testing.d.ts DELETED
@@ -1,17 +0,0 @@
1
- import { type Duration, Effect, Layer, Stream, SubscriptionRef } from "effect";
2
- import { type Rpc, RpcClient, type RpcGroup, RpcSerialization, RpcServer } from "effect/rpc";
3
- import type { Key } from "@shivaedev/changes/keys.ts";
4
- import type { SubscriptionHint } from "#queryUpdate.ts";
5
- export interface HintViewer<E> {
6
- readonly finished: Effect.Effect<void, E>;
7
- readonly hints: SubscriptionRef.SubscriptionRef<readonly SubscriptionHint[]>;
8
- }
9
- export declare const watchHints: <E, R>(stream: Stream.Stream<SubscriptionHint, E, R>) => Effect.Effect<{
10
- finished: Effect.Effect<void, E, never>;
11
- hints: SubscriptionRef.SubscriptionRef<readonly SubscriptionHint[]>;
12
- }, E, R | import("effect/Scope").Scope>;
13
- export declare const heard: <E>(viewer: HintViewer<E>, keys: readonly Key[], options?: {
14
- readonly within?: Duration.Input;
15
- } | undefined) => Effect.Effect<boolean, E, never>;
16
- export declare function layerMemoryProtocol<TRpcs extends Rpc.Any>(group: RpcGroup.RpcGroup<TRpcs>): Layer.Layer<RpcClient.Protocol, never, Exclude<Exclude<Exclude<Rpc.ServicesServer<TRpcs>, RpcServer.Protocol>, import("effect/Scope").Scope>, RpcSerialization.RpcSerialization> | Exclude<Exclude<Exclude<Rpc.ToHandler<TRpcs>, RpcServer.Protocol>, import("effect/Scope").Scope>, RpcSerialization.RpcSerialization>>;
17
- //# sourceMappingURL=testing.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,KAAK,QAAQ,EAAE,MAAM,EAAS,KAAK,EAAS,MAAM,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AACvG,OAAO,EAAE,KAAK,GAAG,EAAE,SAAS,EAAE,KAAK,QAAQ,EAAmB,gBAAgB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC9G,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,4BAA4B,CAAC;AACtD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAExD,MAAM,WAAW,UAAU,CAAC,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IAC1C,QAAQ,CAAC,KAAK,EAAE,eAAe,CAAC,eAAe,CAAC,SAAS,gBAAgB,EAAE,CAAC,CAAC;CAC7E;AAED,eAAO,MAAM,UAAU,GAA2C,CAAC,EAAE,CAAC;;;uCAYpE,CAAC;AAEH,eAAO,MAAM,KAAK,GAAsC,CAAC;sBAG3B,QAAQ,CAAC,KAAK;kDAU1C,CAAC;AAMH,wBAAgB,mBAAmB,CAAC,KAAK,SAAS,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,QAAQ,CAAC,QAAQ,CAAC,KAAK,CAAC,4TAqCzF"}
package/dist/testing.js DELETED
@@ -1,51 +0,0 @@
1
- import { Deferred, Effect, Fiber, Layer, Queue, Stream, SubscriptionRef } from "effect";
2
- import { RpcClient, RpcSerialization, RpcServer } from "effect/rpc";
3
- export const watchHints = Effect.fn("Live.watchHints")(function* (stream) {
4
- const hints = yield* SubscriptionRef.make([]);
5
- const ready = yield* Deferred.make();
6
- const fiber = yield* stream.pipe(Stream.runForEach((hint) => SubscriptionRef.update(hints, (received) => [...received, hint]).pipe(Effect.andThen(Deferred.succeed(ready, undefined)))), Effect.forkScoped);
7
- const finished = Fiber.join(fiber);
8
- yield* Effect.raceFirst(Deferred.await(ready), finished);
9
- return { finished, hints };
10
- });
11
- export const heard = Effect.fn("Live.heard")(function* (viewer, keys, options = {}) {
12
- const matching = SubscriptionRef.changes(viewer.hints).pipe(Stream.filter((hints) => hints.some((hint) => namesKeys(hint, keys))), Stream.runHead, Effect.as(true));
13
- return yield* Effect.raceFirst(matching, Effect.as(viewer.finished, false)).pipe(Effect.timeoutOrElse({ duration: options.within ?? "1 second", orElse: () => Effect.succeed(false) }));
14
- });
15
- function namesKeys(hint, keys) {
16
- return hint._tag === "Changed" && keys.every((key) => hint.keys.some((actual) => JSON.stringify(actual) === JSON.stringify(key)));
17
- }
18
- export function layerMemoryProtocol(group) {
19
- return Layer.effect(RpcClient.Protocol, Effect.gen(function* () {
20
- const requests = yield* Queue.unbounded();
21
- const disconnects = yield* Queue.unbounded();
22
- const { codecFor } = yield* RpcSerialization.RpcSerialization;
23
- const protocol = yield* RpcClient.Protocol.make((send, clientIds) => Effect.gen(function* () {
24
- const server = RpcServer.Protocol.of({
25
- clientIds: Effect.sync(() => clientIds),
26
- codecFor,
27
- disconnects,
28
- end: () => Effect.void,
29
- initialMessage: Effect.succeedNone,
30
- run: (receive) => Effect.forever(Effect.flatMap(Queue.take(requests), ([id, message]) => receive(id, message))),
31
- send,
32
- supportsAck: true,
33
- supportsNotifications: true,
34
- supportsSpanPropagation: true,
35
- supportsTransferables: false,
36
- });
37
- yield* RpcServer.make(group).pipe(Effect.provideService(RpcServer.Protocol, server), Effect.forkScoped);
38
- return {
39
- codecFor,
40
- send: (clientId, request) => Queue.offer(requests, [clientId, request]).pipe(Effect.asVoid),
41
- supportsAck: true,
42
- supportsTransferables: false,
43
- };
44
- }));
45
- return {
46
- ...protocol,
47
- run: (clientId, receive) => protocol.run(clientId, receive).pipe(Effect.ensuring(Queue.offer(disconnects, clientId))),
48
- };
49
- })).pipe(Layer.provide(RpcSerialization.layerNdjson));
50
- }
51
- //# sourceMappingURL=testing.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"testing.js","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAiB,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,QAAQ,CAAC;AACvG,OAAO,EAAY,SAAS,EAAkC,gBAAgB,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAS9G,MAAM,CAAC,MAAM,UAAU,GAAG,M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AAQ,EAAE,OAAO,EAAE,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC,CAAC;SAC7E,CAAC;IAC3C,CAAC,CAAC,CACF,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,gBAAgB,CAAC,WAAW,CAAC,CAAC,CAAC;AACrD,CAAC"}
package/src/testing.ts DELETED
@@ -1,81 +0,0 @@
1
- import { Deferred, type Duration, Effect, Fiber, Layer, Queue, Stream, SubscriptionRef } from "effect";
2
- import { type Rpc, RpcClient, type RpcGroup, type RpcMessage, RpcSerialization, RpcServer } from "effect/rpc";
3
- import type { Key } from "@shivaedev/changes/keys.ts";
4
- import type { SubscriptionHint } from "#queryUpdate.ts";
5
-
6
- export interface HintViewer<E> {
7
- readonly finished: Effect.Effect<void, E>;
8
- readonly hints: SubscriptionRef.SubscriptionRef<readonly SubscriptionHint[]>;
9
- }
10
-
11
- export const watchHints = Effect.fn("Live.watchHints")(function* <E, R>(stream: Stream.Stream<SubscriptionHint, E, R>) {
12
- const hints = yield* SubscriptionRef.make<readonly SubscriptionHint[]>([]);
13
- const ready = yield* Deferred.make<void>();
14
- const fiber = yield* stream.pipe(
15
- Stream.runForEach((hint) =>
16
- SubscriptionRef.update(hints, (received) => [...received, hint]).pipe(Effect.andThen(Deferred.succeed(ready, undefined))),
17
- ),
18
- Effect.forkScoped,
19
- );
20
- const finished = Fiber.join(fiber);
21
- yield* Effect.raceFirst(Deferred.await(ready), finished);
22
- return { finished, hints } satisfies HintViewer<E>;
23
- });
24
-
25
- export const heard = Effect.fn("Live.heard")(function* <E>(
26
- viewer: HintViewer<E>,
27
- keys: readonly Key[],
28
- options: { readonly within?: Duration.Input } = {},
29
- ) {
30
- const matching = SubscriptionRef.changes(viewer.hints).pipe(
31
- Stream.filter((hints) => hints.some((hint) => namesKeys(hint, keys))),
32
- Stream.runHead,
33
- Effect.as(true),
34
- );
35
- return yield* Effect.raceFirst(matching, Effect.as(viewer.finished, false)).pipe(
36
- Effect.timeoutOrElse({ duration: options.within ?? "1 second", orElse: () => Effect.succeed(false) }),
37
- );
38
- });
39
-
40
- function namesKeys(hint: SubscriptionHint, keys: readonly Key[]): boolean {
41
- return hint._tag === "Changed" && keys.every((key) => hint.keys.some((actual) => JSON.stringify(actual) === JSON.stringify(key)));
42
- }
43
-
44
- export function layerMemoryProtocol<TRpcs extends Rpc.Any>(group: RpcGroup.RpcGroup<TRpcs>) {
45
- return Layer.effect(
46
- RpcClient.Protocol,
47
- Effect.gen(function* () {
48
- const requests = yield* Queue.unbounded<readonly [number, RpcMessage.FromClientEncoded]>();
49
- const disconnects = yield* Queue.unbounded<number>();
50
- const { codecFor } = yield* RpcSerialization.RpcSerialization;
51
- const protocol = yield* RpcClient.Protocol.make((send, clientIds) =>
52
- Effect.gen(function* () {
53
- const server = RpcServer.Protocol.of({
54
- clientIds: Effect.sync(() => clientIds),
55
- codecFor,
56
- disconnects,
57
- end: () => Effect.void,
58
- initialMessage: Effect.succeedNone,
59
- run: (receive) => Effect.forever(Effect.flatMap(Queue.take(requests), ([id, message]) => receive(id, message))),
60
- send,
61
- supportsAck: true,
62
- supportsNotifications: true,
63
- supportsSpanPropagation: true,
64
- supportsTransferables: false,
65
- });
66
- yield* RpcServer.make(group).pipe(Effect.provideService(RpcServer.Protocol, server), Effect.forkScoped);
67
- return {
68
- codecFor,
69
- send: (clientId, request) => Queue.offer(requests, [clientId, request]).pipe(Effect.asVoid),
70
- supportsAck: true,
71
- supportsTransferables: false,
72
- };
73
- }),
74
- );
75
- return {
76
- ...protocol,
77
- run: (clientId, receive) => protocol.run(clientId, receive).pipe(Effect.ensuring(Queue.offer(disconnects, clientId))),
78
- } satisfies RpcClient.Protocol["Service"];
79
- }),
80
- ).pipe(Layer.provide(RpcSerialization.layerNdjson));
81
- }