@shivaedev/contract 0.56.0 → 0.58.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 (80) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +24 -23
  3. package/dist/AutomaticQueryOptions.d.ts +1 -1
  4. package/dist/AutomaticQueryOptions.d.ts.map +1 -1
  5. package/dist/{bind.d.ts → Bound.d.ts} +1 -19
  6. package/dist/Bound.d.ts.map +1 -0
  7. package/dist/Bound.js +2 -0
  8. package/dist/Bound.js.map +1 -0
  9. package/dist/ClientOptions.d.ts +2 -2
  10. package/dist/ClientOptions.d.ts.map +1 -1
  11. package/dist/automaticLive.d.ts +2 -1
  12. package/dist/automaticLive.d.ts.map +1 -1
  13. package/dist/automaticLive.js +4 -9
  14. package/dist/automaticLive.js.map +1 -1
  15. package/dist/automaticQuery.js +2 -2
  16. package/dist/automaticQuery.js.map +1 -1
  17. package/dist/clientActivities.d.ts +1 -15
  18. package/dist/clientActivities.d.ts.map +1 -1
  19. package/dist/clientActivities.js +0 -1
  20. package/dist/clientActivities.js.map +1 -1
  21. package/dist/clientContract.d.ts +2 -15
  22. package/dist/clientContract.d.ts.map +1 -1
  23. package/dist/clientContract.js +6 -11
  24. package/dist/clientContract.js.map +1 -1
  25. package/dist/clientOperations.d.ts +3 -2
  26. package/dist/clientOperations.d.ts.map +1 -1
  27. package/dist/clientOperations.js +3 -4
  28. package/dist/clientOperations.js.map +1 -1
  29. package/dist/makeClient.d.ts +1 -1
  30. package/dist/makeClient.d.ts.map +1 -1
  31. package/dist/makeClient.js +3 -3
  32. package/dist/makeClient.js.map +1 -1
  33. package/dist/queryDelivery.d.ts +1 -1
  34. package/dist/queryDelivery.d.ts.map +1 -1
  35. package/dist/queryDelivery.js.map +1 -1
  36. package/dist/reflectCommand.d.ts.map +1 -1
  37. package/dist/reflectCommand.js +7 -18
  38. package/dist/reflectCommand.js.map +1 -1
  39. package/dist/reflectedStream.d.ts +3 -3
  40. package/dist/reflectedStream.d.ts.map +1 -1
  41. package/dist/reflectedStream.js +4 -5
  42. package/dist/reflectedStream.js.map +1 -1
  43. package/dist/reflection.d.ts +4 -0
  44. package/dist/reflection.d.ts.map +1 -1
  45. package/dist/reflection.js +4 -0
  46. package/dist/reflection.js.map +1 -1
  47. package/dist/rpcClient.d.ts +29 -12
  48. package/dist/rpcClient.d.ts.map +1 -1
  49. package/dist/rpcClient.js +2 -3
  50. package/dist/rpcClient.js.map +1 -1
  51. package/dist/servedHandlers.d.ts.map +1 -1
  52. package/dist/servedHandlers.js +3 -2
  53. package/dist/servedHandlers.js.map +1 -1
  54. package/dist/socketAuthentication.d.ts +1 -11
  55. package/dist/socketAuthentication.d.ts.map +1 -1
  56. package/dist/socketAuthentication.js +15 -7
  57. package/dist/socketAuthentication.js.map +1 -1
  58. package/dist/socketProtocol.js +4 -8
  59. package/dist/socketProtocol.js.map +1 -1
  60. package/package.json +6 -6
  61. package/src/AutomaticQueryOptions.ts +1 -1
  62. package/src/{bind.ts → Bound.ts} +0 -46
  63. package/src/ClientOptions.ts +2 -2
  64. package/src/automaticLive.ts +9 -10
  65. package/src/automaticQuery.ts +2 -2
  66. package/src/clientActivities.ts +1 -2
  67. package/src/clientContract.ts +12 -27
  68. package/src/clientOperations.ts +5 -4
  69. package/src/makeClient.ts +4 -4
  70. package/src/queryDelivery.ts +2 -2
  71. package/src/reflectCommand.ts +7 -18
  72. package/src/reflectedStream.ts +5 -5
  73. package/src/reflection.ts +5 -0
  74. package/src/rpcClient.ts +2 -3
  75. package/src/servedHandlers.ts +5 -4
  76. package/src/socketAuthentication.ts +22 -7
  77. package/src/socketProtocol.ts +5 -10
  78. package/dist/bind.d.ts.map +0 -1
  79. package/dist/bind.js +0 -11
  80. package/dist/bind.js.map +0 -1
@@ -4,24 +4,32 @@ export const SocketAuthentication = Schema.Struct({
4
4
  _tag: Schema.Literal("Authenticate"),
5
5
  token: Schema.String.check(Schema.isPattern(/^[\x21-\x7e]+$/u)),
6
6
  });
7
- export const authenticateSocket = Effect.fnUntraced(function* (token) {
8
- const socket = yield* Socket.Socket;
7
+ // Each connection reads the credential once, so a reconnect sends the one stored now and asks for a frame only when one follows.
8
+ export const authenticateSocket = Effect.fnUntraced(function* (url, credential, headers) {
9
+ const framed = new URL(url);
10
+ framed.searchParams.set("auth", "frame");
11
+ let token = null;
12
+ const socket = yield* Socket.makeWebSocket(Effect.map(credential, (current) => {
13
+ token = current;
14
+ return current === null ? url : framed.toString();
15
+ }), { headers });
9
16
  const ready = yield* Latch.make(false);
10
17
  const writer = yield* Effect.map(socket.writer, (nativeWriter) => ({
11
18
  write: (chunk) => ready.await.pipe(Effect.andThen(nativeWriter.write(chunk))),
12
19
  writeAll: (chunks) => ready.await.pipe(Effect.andThen(nativeWriter.writeAll(chunks))),
13
20
  }));
14
- return {
15
- ...socket,
21
+ return Socket.make({
16
22
  reader: Effect.gen(function* () {
17
23
  yield* ready.close;
18
24
  const reader = yield* socket.reader;
19
- const raw = yield* socket.writer;
20
- yield* raw.write(JSON.stringify({ _tag: "Authenticate", token }));
25
+ if (token !== null) {
26
+ const raw = yield* socket.writer;
27
+ yield* raw.write(JSON.stringify({ _tag: "Authenticate", token }));
28
+ }
21
29
  yield* ready.open;
22
30
  return { ...reader, pull: reader.pull.pipe(Effect.onError(() => ready.close)) };
23
31
  }),
24
32
  writer: Effect.succeed(writer),
25
- };
33
+ });
26
34
  });
27
35
  //# sourceMappingURL=socketAuthentication.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"socketAuthentication.js","sourceRoot":"","sources":["../src/socketAuthentication.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC/C,OAAO,KAAK,MAAM,MAAM,sBAAsB,CAAC;AAE/C,MAAM,CAAC,MAAM,oBAAoB,GAAG,MAAM,CAAC,MAAM,CAAC;IACjD,IAAI,EAAE,MAAM,CAAC,OAAO,C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M,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC;QACjF,CAAC,CAAC;QACF,MAAM,EAAE,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;KAC9B,CAAC,CAAC;AACJ,CAAC,CAAC,CAAC"}
@@ -18,14 +18,10 @@ export function socketProtocol(options) {
18
18
  return protocols({ ...options, resumeWindow: reference });
19
19
  }
20
20
  const protocols = Atom.family((options) => {
21
- let url = options.url;
22
- if (options.bearerToken !== undefined) {
23
- const address = new URL(url);
24
- address.searchParams.set("auth", "frame");
25
- url = address.toString();
26
- }
27
- const raw = Socket.layerWebSocket(url, { headers: options.headers });
28
- const authenticated = (options.bearerToken === undefined ? raw : Layer.effect(Socket.Socket, authenticateSocket(options.bearerToken)).pipe(Layer.provide(raw))).pipe(Layer.provide(options.webSocketConstructor ?? Socket.layerWebSocketConstructorGlobal));
21
+ const opened = options.bearerToken === undefined
22
+ ? Socket.layerWebSocket(options.url, { headers: options.headers })
23
+ : Layer.effect(Socket.Socket, authenticateSocket(options.url, options.bearerToken, options.headers));
24
+ const authenticated = opened.pipe(Layer.provide(options.webSocketConstructor ?? Socket.layerWebSocketConstructorGlobal));
29
25
  const socket = Layer.effect(Socket.Socket, resumeSocket({
30
26
  ...(options.resumeWindow === undefined ? {} : { window: options.resumeWindow.target }),
31
27
  ...(options.resume === undefined ? {} : { native: options.resume }),
@@ -1 +1 @@
1
- {"version":3,"file":"socketProtocol.js","sourceRoot":"","sources":["../src/socketProtocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,QAAQ,CAAC;AAC/D,OAAO,KAAK,IAAI,MAAM,wBAAwB,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,YAA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,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACxB,IAAI,GAAG,KAAK,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC;YAChC,cAAc,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QACjC,CAAC;QACD,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;QAChF,OAAO,KAAK,CAAC,CAAC,KAAK,CAAC,gBAAgB,CAAC,QAAQ,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC3E,CAAC,CAAC,CACF,CAAC;AACH,CAAC,CACD,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shivaedev/contract",
3
- "version": "0.56.0",
3
+ "version": "0.58.0",
4
4
  "description": "Typed query and command contracts over native Effect RPC and reactivity",
5
5
  "keywords": [
6
6
  "effect"
@@ -51,13 +51,13 @@
51
51
  "devDependencies": {
52
52
  "@effect/platform-node": "4.1.4",
53
53
  "@effect/vitest": "4.1.4",
54
- "@shivaedev/identity": "0.38.2",
55
- "@shivaedev/quality": "0.83.1",
56
- "@shivaedev/server": "0.41.1",
54
+ "@shivaedev/identity": "0.39.0",
55
+ "@shivaedev/quality": "0.83.3",
56
+ "@shivaedev/server": "0.42.0",
57
57
  "@shivaedev/sql": "0.54.0",
58
- "@shivaedev/test-kits": "0.16.2",
58
+ "@shivaedev/test-kits": "0.16.4",
59
59
  "@shivaedev/test-sql": "0.26.0",
60
- "@shivaedev/test-story": "0.52.2",
60
+ "@shivaedev/test-story": "0.52.4",
61
61
  "@types/node": "24.19.2",
62
62
  "effect": "4.1.4",
63
63
  "fake-indexeddb": "6.2.8",
@@ -7,7 +7,7 @@ import type { StreamAnchor } from "#reflectedStream.ts";
7
7
 
8
8
  export interface AutomaticQueryOptions<A, E> {
9
9
  readonly anchor: (registry: object) => StreamAnchor;
10
- readonly clientStatuses: Atom.Writable<ReadonlyMap<object, LiveStatus<unknown>>> | undefined;
10
+ readonly clientStatuses: Atom.Writable<ReadonlyMap<object, LiveStatus<unknown>>>;
11
11
  readonly equivalent: (left: A, right: A) => boolean;
12
12
  readonly paused: Atom.Writable<boolean>;
13
13
  readonly ready: Atom.Writable<boolean>;
@@ -2,19 +2,11 @@ import type { Effect, Stream } from "effect";
2
2
  import type { Headers } from "effect/http";
3
3
  import type * as AsyncResult from "effect/reactivity/AsyncResult";
4
4
  import type * as Atom from "effect/reactivity/Atom";
5
- import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
6
- import type * as AtomRpc from "effect/reactivity/AtomRpc";
7
5
  import type * as Reactivity from "effect/reactivity/Reactivity";
8
6
  import type { Rpc } from "effect/rpc";
9
7
  import type { RpcClientError } from "effect/rpc/RpcClientError";
10
- import { bindingOwner } from "#adapters/bindingOwner.ts";
11
- import { automaticLive, type LiveBound } from "#automaticLive.ts";
12
- import { bindOperations } from "#bindOperations.ts";
13
- import { clientOperations } from "#clientOperations.ts";
14
- import type { Contract, Declared } from "#contract.ts";
15
8
  import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
16
9
  import type { Tag } from "#operationRpc.ts";
17
- import type { ResumeSource, ResumeWindow } from "#resume.ts";
18
10
 
19
11
  // Like Effect's own `Rpc` helpers, these take any type: `Rpc.ExtractTag` of a generic group is not provably an `Rpc.Any`.
20
12
  export type Failure<R> =
@@ -73,41 +65,3 @@ export type Bound<
73
65
  } & {
74
66
  readonly [TStream in TStreams[number] as TStream["name"]]: BoundStream<Rpc.ExtractTag<TRpcs, Tag<TName, TStream["name"]>>, TSelf>;
75
67
  };
76
-
77
- type MatchingClient<TRpcs extends Rpc.Any, TClientRpcs extends Rpc.Any> = [TRpcs] extends [Extract<TClientRpcs, { readonly _tag: TRpcs["_tag"] }>]
78
- ? [Extract<TClientRpcs, { readonly _tag: TRpcs["_tag"] }>] extends [TRpcs]
79
- ? unknown
80
- : "Client must preserve the contract RPC types"
81
- : "Client must implement the contract RPCs";
82
-
83
- interface BindOptions {
84
- readonly registry?: AtomRegistry.AtomRegistry;
85
- readonly resume?: ResumeSource;
86
- readonly resumeWindow?: ResumeWindow;
87
- }
88
-
89
- export function bind<
90
- TName extends string,
91
- TQueries extends readonly QueryShape[],
92
- TCommands extends readonly CommandShape[],
93
- TRpcs extends Rpc.Any,
94
- TSelf,
95
- TId extends string,
96
- TClientRpcs extends Rpc.Any,
97
- TStreams extends readonly StreamShape[],
98
- TScope extends "session" | undefined,
99
- >(
100
- contract: Contract<TName, TQueries, TCommands, TRpcs, TStreams, TScope>,
101
- service: AtomRpc.AtomRpcClient<TSelf, TId, TClientRpcs> & MatchingClient<NoInfer<TRpcs>, TClientRpcs>,
102
- ...options: "session" extends TScope ? [options: BindOptions & { readonly registry: AtomRegistry.AtomRegistry }] : [options?: BindOptions]
103
- ): Bound<TName, TQueries, TCommands, TRpcs, TSelf, TStreams> & LiveBound;
104
- export function bind(
105
- contract: { readonly declaration: Declared<string, readonly QueryShape[], readonly CommandShape[], readonly StreamShape[], "session" | undefined> },
106
- service: AtomRpc.AtomRpcClient<unknown, string, Rpc.Any>,
107
- options?: BindOptions,
108
- ): unknown {
109
- const { name, keyScope } = contract.declaration;
110
- const owner = bindingOwner(keyScope, options?.registry);
111
- const automatic = automaticLive(service, name, owner, options?.resume, options?.resumeWindow);
112
- return bindOperations(contract.declaration, clientOperations(service, automatic, owner), automatic.subscription);
113
- }
@@ -1,4 +1,4 @@
1
- import type { Layer } from "effect";
1
+ import type { Effect, Layer } from "effect";
2
2
  import type * as Atom from "effect/reactivity/Atom";
3
3
  import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
4
4
  import type { RpcClient } from "effect/rpc";
@@ -6,7 +6,7 @@ import type * as Socket from "effect/socket/Socket";
6
6
  import type { ResumeSource, ResumeWindow } from "#resume.ts";
7
7
 
8
8
  export interface ClientOptions {
9
- readonly bearerToken?: string;
9
+ readonly bearerToken?: Effect.Effect<string | null>;
10
10
  readonly headers?: Readonly<Record<string, string>>;
11
11
  readonly protocol?: Layer.Layer<RpcClient.Protocol> | ((identity: string | undefined) => Layer.Layer<RpcClient.Protocol>);
12
12
  readonly registry?: AtomRegistry.AtomRegistry;
@@ -9,7 +9,7 @@ import type { BindingOwner } from "#adapters/bindingOwner.ts";
9
9
  import { changesClient } from "#adapters/erasedClient.ts";
10
10
  import { aggregateLiveStatus } from "#aggregateLiveStatus.ts";
11
11
  import { automaticQuery } from "#automaticQuery.ts";
12
- import { clientActivities } from "#clientActivities.ts";
12
+ import type { ActivityTracker } from "#clientActivities.ts";
13
13
  import { type LiveStatus, live } from "#live.ts";
14
14
  import { queryDelivery } from "#queryDelivery.ts";
15
15
  import { querySignals, shareQuerySignals } from "#querySignals.ts";
@@ -34,6 +34,7 @@ const pausedByRuntime = Atom.family((_runtime: object) => Atom.keepAlive(Atom.ma
34
34
 
35
35
  export function automaticLive(
36
36
  operations: AtomRpc.AtomRpcClient<unknown, string, Rpc.Any>,
37
+ activity: ActivityTracker,
37
38
  name: string,
38
39
  owner?: BindingOwner,
39
40
  resume?: ResumeSource,
@@ -81,20 +82,18 @@ export function automaticLive(
81
82
  resume: signal,
82
83
  stream: Stream.unwrap(
83
84
  service.use((client) =>
84
- Effect.map(AtomRegistry.AtomRegistry, (registry) => {
85
- const reflected = followReflection(client, anchor(registry));
86
- if (reflected === undefined) {
87
- return delivery.stream(client(`${name}.$changes`, { queries: [reference] }, { headers }));
88
- }
89
- const opened = client(`${name}.$changes`, { queries: [reference] }, { headers: reflected.headers(headers) });
90
- return delivery.stream(reflected.lifetime(opened), reflected.follower);
91
- }),
85
+ Effect.flatMap(AtomRegistry.AtomRegistry, (registry) =>
86
+ Effect.map(followReflection(client, anchor(registry)), (reflected) => {
87
+ const opened = client(`${name}.$changes`, { queries: [reference] }, { headers: reflected.headers(headers) });
88
+ return delivery.stream(reflected.lifetime(opened), reflected.follower);
89
+ }),
90
+ ),
92
91
  ),
93
92
  ),
94
93
  });
95
94
  const gated = automaticQuery({
96
95
  anchor,
97
- clientStatuses: clientActivities.get(service)?.statuses,
96
+ clientStatuses: activity.statuses,
98
97
  equivalent,
99
98
  ownerFailure,
100
99
  paused,
@@ -51,7 +51,7 @@ export function automaticQuery<A, E>({
51
51
  get.set(signals, recordSubscription(get.once(signals), value));
52
52
  dispatcher.scheduleTask(() => {
53
53
  if (active) {
54
- for (const state of clientStatuses === undefined ? [statuses] : [statuses, clientStatuses]) {
54
+ for (const state of [statuses, clientStatuses]) {
55
55
  registry.update(state, (current) => new Map([...current, [token, value]]));
56
56
  }
57
57
  }
@@ -63,7 +63,7 @@ export function automaticQuery<A, E>({
63
63
  }
64
64
  get.addFinalizer(() => {
65
65
  active = false;
66
- for (const state of clientStatuses === undefined ? [statuses] : [statuses, clientStatuses]) {
66
+ for (const state of [statuses, clientStatuses]) {
67
67
  if (registry.getNodes().has(state)) {
68
68
  registry.update(state, (current) => {
69
69
  const next = new Map(current);
@@ -6,8 +6,7 @@ import { clientConnection } from "#adapters/clientConnection.ts";
6
6
  import { querySignals, shareQuerySignals } from "#querySignals.ts";
7
7
  import { wrapAtom } from "#wrapAtom.ts";
8
8
 
9
- type ActivityTracker = ReturnType<typeof makeActivity>;
10
- export const clientActivities = new WeakMap<object, ActivityTracker>();
9
+ export type ActivityTracker = ReturnType<typeof makeActivity>;
11
10
 
12
11
  export function makeActivity(factory: Atom.RuntimeFactory) {
13
12
  const { activity, change, excuse, hold, rendered, setConnection } = activityState();
@@ -21,15 +21,6 @@ type Payloads<TWire> = { readonly [TOperation in keyof TWire]?: Schema.Top | Sch
21
21
  type PayloadOf<TPayloads, TOperation> = PayloadSchema<TOperation extends keyof TPayloads ? NonNullable<TPayloads[TOperation]> : Schema.Void>;
22
22
  type EntryOf<TWire, TOperation> = TOperation extends keyof TWire ? (TWire[TOperation] extends WireEntry ? TWire[TOperation] : never) : never;
23
23
 
24
- interface QueryKeys<TPayload> {
25
- readonly reads: (payload: TPayload, viewer: Option.Option<Viewer>) => readonly Key[];
26
- readonly readsCollections?: readonly { readonly name: string }[];
27
- }
28
-
29
- interface CommandKeys<TPayload> {
30
- readonly invalidates?: (payload: TPayload, viewer?: Option.Option<Viewer>) => readonly Key[];
31
- }
32
-
33
24
  type ClientQueries<TWire, TPayloads, TQueries extends string> = {
34
25
  readonly [TOperation in TQueries]: ClientQuery<
35
26
  TOperation,
@@ -58,19 +49,21 @@ export interface ClientContractDefinition<
58
49
  TSubject extends SubjectDeclaration | undefined,
59
50
  TScope extends "session" | undefined,
60
51
  > {
61
- readonly commands?: {
62
- readonly [TOperation in TCommands]: CommandKeys<PayloadOf<TPayloads, TOperation>["Type"]>;
63
- };
52
+ readonly commands?: readonly TCommands[];
64
53
  readonly keyScope?: TScope;
65
54
  readonly middleware?: TMiddleware;
66
55
  readonly name: TName;
67
56
  readonly payloads?: TPayloads;
68
- readonly queries?: { readonly [TOperation in TQueries]: QueryKeys<PayloadOf<TPayloads, TOperation>["Type"]> };
57
+ readonly queries?: readonly TQueries[];
69
58
  readonly subject?: TSubject;
70
59
  readonly wire: TWire;
71
60
  }
72
61
 
73
- // Written by the generator: what the browser needs of a module as values, without its run, read policy or services.
62
+ function noKeys(): readonly Key[] {
63
+ return [];
64
+ }
65
+
66
+ // Written by the generator: what the browser needs of a module as values, without its run, read policy, keys or services.
74
67
  export function clientContract<
75
68
  const TName extends string,
76
69
  const TWire extends Wire,
@@ -90,12 +83,12 @@ export function clientContract<
90
83
  TScope
91
84
  >;
92
85
  export function clientContract(definition: {
93
- readonly commands?: { readonly [operation: string]: CommandKeys<unknown> };
86
+ readonly commands?: readonly string[];
94
87
  readonly keyScope?: "session";
95
88
  readonly middleware?: RpcMiddleware.AnyService;
96
89
  readonly name: string;
97
90
  readonly payloads?: { readonly [operation: string]: Schema.Top | Schema.Struct.Fields | undefined };
98
- readonly queries?: { readonly [operation: string]: QueryKeys<unknown> };
91
+ readonly queries?: readonly string[];
99
92
  readonly subject?: SubjectDeclaration;
100
93
  readonly wire: Wire;
101
94
  }): unknown {
@@ -107,17 +100,9 @@ export function clientContract(definition: {
107
100
  ...(entry === undefined ? {} : { rejections: wireRejections(entry.rejections), success: entry.success }),
108
101
  };
109
102
  }
110
- const queries = Object.entries(definition.queries ?? {}).map(([name, { reads, readsCollections = [] }]) => {
111
- const collections: readonly Key[] = readsCollections.map((collection) => ({ _tag: "List", collection: collection.name }));
112
- return {
113
- ...operation("query", name, declared(name)),
114
- reads: (payload: unknown, viewer: Option.Option<Viewer>) => [...reads(payload, viewer), ...collections],
115
- };
116
- });
117
- const commands = Object.entries(definition.commands ?? {}).map(([name, { invalidates }]) => ({
118
- ...operation("command", name, declared(name)),
119
- invalidates: (payload: unknown, _result: unknown, viewer?: Option.Option<Viewer>) => invalidates?.(payload, viewer) ?? [],
120
- }));
103
+ // The server's module declares the keys and announces the changes; an operation's shape still names them, so the browser's are empty.
104
+ const queries = (definition.queries ?? []).map((name) => ({ ...operation("query", name, declared(name)), reads: noKeys }));
105
+ const commands = (definition.commands ?? []).map((name) => ({ ...operation("command", name, declared(name)), invalidates: noKeys }));
121
106
  const group = declaredGroup(definition.name, {
122
107
  commands,
123
108
  queries,
@@ -7,8 +7,8 @@ import type { Rpc } from "effect/rpc";
7
7
  import type { BindingOwner } from "#adapters/bindingOwner.ts";
8
8
  import { streamingClient, unaryClient } from "#adapters/erasedClient.ts";
9
9
  import type { automaticLive } from "#automaticLive.ts";
10
- import type { QueryOptions, RunOptions } from "#bind.ts";
11
- import { clientActivities } from "#clientActivities.ts";
10
+ import type { QueryOptions, RunOptions } from "#Bound.ts";
11
+ import type { ActivityTracker } from "#clientActivities.ts";
12
12
  import { commandPayload } from "#commandPayload.ts";
13
13
  import { COMMAND_REFLECTED } from "#commandReflected.ts";
14
14
  import { CommandSignal, untilReflected } from "#commandSignal.ts";
@@ -28,6 +28,7 @@ function runSubject(options: unknown): string | undefined {
28
28
 
29
29
  export function clientOperations(
30
30
  service: AtomRpc.AtomRpcClient<unknown, string, Rpc.Any>,
31
+ activity: ActivityTracker,
31
32
  automatic: ReturnType<typeof automaticLive>,
32
33
  owner?: BindingOwner,
33
34
  ) {
@@ -42,7 +43,7 @@ export function clientOperations(
42
43
  const reactivity = yield* Reactivity.Reactivity;
43
44
  return yield* Effect.sync(
44
45
  (): CommandObserver => ({
45
- pending: () => clientActivities.get(ordinaryClient)?.reflecting() ?? (() => undefined),
46
+ pending: activity.reflecting,
46
47
  signal: (state) => {
47
48
  signal(state);
48
49
  if (state === "reflected") {
@@ -79,7 +80,7 @@ export function clientOperations(
79
80
  function warm(get: Atom.AtomContext): boolean {
80
81
  return get.once(warmQueries).has(tracked);
81
82
  }
82
- const watched = clientActivities.get(ordinaryClient)?.watch(result, warm) ?? result;
83
+ const watched = activity.watch(result, warm);
83
84
  const tracked = retainQuery(ordinaryClient.runtime, watched, stored(payload, inputSubject(headers)));
84
85
  cached.set(atom, tracked);
85
86
  return tracked;
package/src/makeClient.ts CHANGED
@@ -6,7 +6,7 @@ import type { Rpc, RpcClient, RpcGroup } from "effect/rpc";
6
6
  import type { RpcClientError } from "effect/rpc/RpcClientError";
7
7
  import { bindingOwner } from "#adapters/bindingOwner.ts";
8
8
  import { automaticLive, type LiveBound } from "#automaticLive.ts";
9
- import type { Bound } from "#bind.ts";
9
+ import type { Bound } from "#Bound.ts";
10
10
  import { bindOperations } from "#bindOperations.ts";
11
11
  import type { ClientOptions } from "#ClientOptions.ts";
12
12
  import type { ActiveClient } from "#clientActivity.ts";
@@ -64,12 +64,12 @@ export function makeClient(contracts: Contracts, options: ClientOptions = {}): L
64
64
  annotations: Context.mergeAll(...list.map((contract) => contract.annotations)),
65
65
  requests: new Map(list.flatMap((contract) => [...contract.requests])),
66
66
  };
67
- const connection = rpcClient("@shivaedev/contract/Contracts", source, options);
67
+ const { activity, connection } = rpcClient("@shivaedev/contract/Contracts", source, options);
68
68
  const { registry, resume, resumeWindow } = options;
69
69
  const bound = Object.entries(contracts).map(([key, { declaration }]) => {
70
70
  const owner = bindingOwner(declaration.keyScope, registry);
71
- const automatic = automaticLive(connection.Client, declaration.name, owner, resume, resumeWindow);
72
- const operations = clientOperations(connection.Client, automatic, owner);
71
+ const automatic = automaticLive(connection.Client, activity, declaration.name, owner, resume, resumeWindow);
72
+ const operations = clientOperations(connection.Client, activity, automatic, owner);
73
73
  return { api: [key, bindOperations(declaration, operations, automatic.subscription)] as const, owner, sync: operations.sync };
74
74
  });
75
75
  // A sync runs through the session's registry when the record holds a session-scoped contract, as that contract's own calls do.
@@ -19,7 +19,7 @@ export function queryDelivery<A, E>(decode: (value: unknown) => A, paused: Atom.
19
19
  const pushed = Atom.make<AsyncResult.AsyncResult<A, E>>(AsyncResult.initial(true));
20
20
  const deliver = Effect.fnUntraced(function* (
21
21
  update: QueryUpdate,
22
- follower: ReflectionFollower | undefined,
22
+ follower: ReflectionFollower,
23
23
  ): Effect.fn.Return<SubscriptionEvent | undefined, never, AtomRegistry.AtomRegistry> {
24
24
  const registry = yield* AtomRegistry.AtomRegistry;
25
25
  const showing = !registry.get(paused);
@@ -47,7 +47,7 @@ export function queryDelivery<A, E>(decode: (value: unknown) => A, paused: Atom.
47
47
  });
48
48
  return {
49
49
  atom: pushed,
50
- stream: <TError, R>(stream: Stream.Stream<QueryUpdate, TError, R>, follower?: ReflectionFollower) =>
50
+ stream: <TError, R>(stream: Stream.Stream<QueryUpdate, TError, R>, follower: ReflectionFollower) =>
51
51
  stream.pipe(
52
52
  Stream.mapEffect((update) => deliver(update, follower)),
53
53
  Stream.filter((event) => event !== undefined),
@@ -1,6 +1,6 @@
1
1
  import { Effect, Exit } from "effect";
2
2
  import type { CommandState } from "#commandSignal.ts";
3
- import { reflections } from "#reflection.ts";
3
+ import { reflectionScope } from "#reflection.ts";
4
4
  import { commandSyncHeaders } from "#syncHeader.ts";
5
5
 
6
6
  export interface CommandObserver {
@@ -14,34 +14,23 @@ export function reflectCommand<A, E, R>(
14
14
  send: (options?: { readonly headers: Record<string, string> }) => Effect.Effect<A, E, R>,
15
15
  standalone = false,
16
16
  ): Effect.Effect<A, E, R> {
17
- return Effect.suspend(() => {
18
- const scope = reflections.get(client);
19
- const reflection = scope?.reflection;
20
- let own: number | undefined;
21
- if (scope !== undefined) {
22
- own = standalone ? scope.reflection.flight() : scope.reflection.send(scope.piggyback);
23
- }
17
+ return Effect.flatMap(reflectionScope(client), ({ piggyback, reflection }) => {
18
+ const own = standalone ? reflection.flight() : reflection.send(piggyback);
24
19
  const finish = observer.pending();
25
20
  observer.signal("sent");
26
- const sent =
27
- reflection === undefined || own === undefined ? send() : send({ headers: commandSyncHeaders({ client: reflection.client, id: own }) });
21
+ const sent = own === undefined ? send() : send({ headers: commandSyncHeaders({ client: reflection.client, id: own }) });
28
22
  return Effect.onExit(sent, (exit) =>
29
23
  Effect.sync(() => {
30
24
  if (Exit.isFailure(exit)) {
31
- reflection?.failed(own);
25
+ reflection.failed(own);
32
26
  finish();
33
27
  return;
34
28
  }
35
29
  observer.signal("accepted");
36
- function reflected() {
30
+ reflection.accepted(own, () => {
37
31
  finish();
38
32
  observer.signal("reflected");
39
- }
40
- if (reflection === undefined) {
41
- reflected();
42
- } else {
43
- reflection.accepted(own, reflected);
44
- }
33
+ });
45
34
  }),
46
35
  );
47
36
  });
@@ -1,7 +1,7 @@
1
1
  import { Effect, Exit, Stream } from "effect";
2
2
  import { Headers } from "effect/http";
3
3
  import { retriesLive } from "#liveRetry.ts";
4
- import { type FollowedStream, type Reflection, reflections } from "#reflection.ts";
4
+ import { type FollowedStream, type Reflection, reflectionScope } from "#reflection.ts";
5
5
  import { streamSyncHeaders } from "#syncHeader.ts";
6
6
 
7
7
  export interface StreamAnchor extends FollowedStream {
@@ -17,10 +17,10 @@ export interface ReflectionFollower {
17
17
 
18
18
  // A mounted query keeps one place in its connection's waits across attempts; it leaves only when it unmounts or stops retrying.
19
19
  export function followReflection(client: object, anchor: StreamAnchor) {
20
- const reflection = reflections.get(client)?.reflection;
21
- if (reflection === undefined) {
22
- return undefined;
23
- }
20
+ return Effect.map(reflectionScope(client), ({ reflection }) => follow(reflection, anchor));
21
+ }
22
+
23
+ function follow(reflection: Reflection, anchor: StreamAnchor) {
24
24
  const follower: ReflectionFollower = {
25
25
  armed: () => reflection.armed(anchor),
26
26
  confirmed: (ids) => reflection.confirmed(anchor, ids),
package/src/reflection.ts CHANGED
@@ -110,3 +110,8 @@ export const makeReflection = Effect.flatMap(Queue.sliding<void>(1), (catchUps)
110
110
  export type Reflection = Effect.Success<typeof makeReflection>;
111
111
 
112
112
  export const reflections = new WeakMap<object, { readonly piggyback: boolean; readonly reflection: Reflection }>();
113
+
114
+ export function reflectionScope(client: object) {
115
+ const scope = reflections.get(client);
116
+ return scope === undefined ? Effect.die(new Error("A client made by makeClient carries its connection's reflection")) : Effect.succeed(scope);
117
+ }
package/src/rpcClient.ts CHANGED
@@ -5,7 +5,7 @@ import { type Rpc, RpcClient, RpcGroup } from "effect/rpc";
5
5
  import type { RpcClientError } from "effect/rpc/RpcClientError";
6
6
  import type { ClientOptions } from "#ClientOptions.ts";
7
7
  import { catchUp } from "#catchUp.ts";
8
- import { clientActivities, makeActivity } from "#clientActivities.ts";
8
+ import { makeActivity } from "#clientActivities.ts";
9
9
  import { Activity } from "#clientActivity.ts";
10
10
  import { ConnectionScope, connectionProtocol } from "#connectionProtocol.ts";
11
11
  import { commandConnections } from "#connectionReadiness.ts";
@@ -86,14 +86,13 @@ export function rpcClient(name: string, source: RpcSource, options: ClientOption
86
86
  protocol: typeof options.protocol === "object" ? protocol : (get) => protocolFor(get(socketIdentity)),
87
87
  runtime: options.runtime,
88
88
  });
89
- clientActivities.set(Client, activity);
90
89
  const directClient = withClientProtocol(protocol, make).pipe(
91
90
  Effect.map((flat) =>
92
91
  Object.fromEntries([...group.requests.keys()].map((tag) => [tag, (payload: never, callOptions: never) => flat(tag, payload, callOptions)])),
93
92
  ),
94
93
  );
95
94
  const layer = Layer.effect(Client, make).pipe(Layer.provide(protocol));
96
- return Object.assign(layer, { [Activity]: activity.activity, Client, client: directClient, runtime: Client.runtime });
95
+ return { activity, connection: Object.assign(layer, { [Activity]: activity.activity, Client, client: directClient, runtime: Client.runtime }) };
97
96
  }
98
97
 
99
98
  function pageRpcUrl() {
@@ -1,11 +1,11 @@
1
- import { Effect, Layer, type Schema } from "effect";
1
+ import { Effect, Layer, type Option, type Schema } from "effect";
2
2
  import { Rpc, RpcGroup, RpcSchema } from "effect/rpc";
3
3
  import { ReadRecorder } from "@shivaedev/changes/readRecorder.ts";
4
4
  import { rpcBoundary } from "@shivaedev/errors/boundary.ts";
5
5
  import { InternalServerError } from "@shivaedev/errors/taxonomy.ts";
6
6
  import type { Declared } from "#contract.ts";
7
7
  import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
8
- import { CurrentViewer, checkPolicy, type QueryReadPolicy } from "#readPolicy.ts";
8
+ import { CurrentViewer, checkPolicy, type QueryReadPolicy, type Viewer } from "#readPolicy.ts";
9
9
  import { ServedReadPolicy } from "#servedReadPolicy.ts";
10
10
 
11
11
  type Runnable = (payload: unknown) => Effect.Effect<unknown, unknown, unknown>;
@@ -36,10 +36,11 @@ function served(rpc: Rpc.AnyWithProps, operation: QueryShape | CommandShape, run
36
36
  }).pipe(Effect.withSpan(span), boundary);
37
37
  }
38
38
 
39
- // Live subscriptions check the policy outside the handler, so the policy carries the handler's failure mapping.
39
+ // Live subscriptions check the policy outside the handler, so the policy carries the handler's failure mapping. It keeps the
40
+ // policy's own properties, such as the mark of a permission policy that collection reads require.
40
41
  function servedPolicy(rpc: Rpc.AnyWithProps, policy: QueryReadPolicy<unknown, unknown, unknown>): QueryReadPolicy<unknown, unknown, unknown> {
41
42
  const boundary = guarded(rpc);
42
- return (payload, viewer) => boundary(Effect.suspend(() => policy(payload, viewer)));
43
+ return Object.assign((payload: unknown, viewer: Option.Option<Viewer>) => boundary(Effect.suspend(() => policy(payload, viewer))), policy);
43
44
  }
44
45
 
45
46
  type EffectRpc = Rpc.Rpc<string, Schema.Top, Schema.Top, Schema.Top>;
@@ -6,23 +6,38 @@ export const SocketAuthentication = Schema.Struct({
6
6
  token: Schema.String.check(Schema.isPattern(/^[\x21-\x7e]+$/u)),
7
7
  });
8
8
 
9
- export const authenticateSocket = Effect.fnUntraced(function* (token: string) {
10
- const socket = yield* Socket.Socket;
9
+ // Each connection reads the credential once, so a reconnect sends the one stored now and asks for a frame only when one follows.
10
+ export const authenticateSocket = Effect.fnUntraced(function* (
11
+ url: string,
12
+ credential: Effect.Effect<string | null>,
13
+ headers?: Readonly<Record<string, string>>,
14
+ ) {
15
+ const framed = new URL(url);
16
+ framed.searchParams.set("auth", "frame");
17
+ let token: string | null = null;
18
+ const socket = yield* Socket.makeWebSocket(
19
+ Effect.map(credential, (current) => {
20
+ token = current;
21
+ return current === null ? url : framed.toString();
22
+ }),
23
+ { headers },
24
+ );
11
25
  const ready = yield* Latch.make(false);
12
26
  const writer = yield* Effect.map(socket.writer, (nativeWriter) => ({
13
27
  write: (chunk: Parameters<typeof nativeWriter.write>[0]) => ready.await.pipe(Effect.andThen(nativeWriter.write(chunk))),
14
28
  writeAll: (chunks: Parameters<typeof nativeWriter.writeAll>[0]) => ready.await.pipe(Effect.andThen(nativeWriter.writeAll(chunks))),
15
29
  }));
16
- return {
17
- ...socket,
30
+ return Socket.make({
18
31
  reader: Effect.gen(function* () {
19
32
  yield* ready.close;
20
33
  const reader = yield* socket.reader;
21
- const raw = yield* socket.writer;
22
- yield* raw.write(JSON.stringify({ _tag: "Authenticate", token }));
34
+ if (token !== null) {
35
+ const raw = yield* socket.writer;
36
+ yield* raw.write(JSON.stringify({ _tag: "Authenticate", token }));
37
+ }
23
38
  yield* ready.open;
24
39
  return { ...reader, pull: reader.pull.pipe(Effect.onError(() => ready.close)) };
25
40
  }),
26
41
  writer: Effect.succeed(writer),
27
- };
42
+ });
28
43
  });