@shivaedev/contract 0.31.0 → 0.32.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 (146) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +81 -12
  3. package/dist/CommandGuard.d.ts +10 -0
  4. package/dist/CommandGuard.d.ts.map +1 -0
  5. package/dist/CommandGuard.js +20 -0
  6. package/dist/CommandGuard.js.map +1 -0
  7. package/dist/LiveServer.d.ts +6 -4
  8. package/dist/LiveServer.d.ts.map +1 -1
  9. package/dist/LiveServer.js +10 -5
  10. package/dist/LiveServer.js.map +1 -1
  11. package/dist/ReadPolicyGuard.d.ts +19 -0
  12. package/dist/ReadPolicyGuard.d.ts.map +1 -0
  13. package/dist/ReadPolicyGuard.js +23 -0
  14. package/dist/ReadPolicyGuard.js.map +1 -0
  15. package/dist/adapters/activityState.d.ts +9 -0
  16. package/dist/adapters/activityState.d.ts.map +1 -0
  17. package/dist/adapters/activityState.js +11 -0
  18. package/dist/adapters/activityState.js.map +1 -0
  19. package/dist/{internal → adapters}/bindingOwner.d.ts +1 -1
  20. package/dist/{internal → adapters}/bindingOwner.d.ts.map +1 -1
  21. package/dist/{internal → adapters}/bindingOwner.js +2 -1
  22. package/dist/adapters/bindingOwner.js.map +1 -0
  23. package/dist/adapters/clientId.d.ts +2 -0
  24. package/dist/adapters/clientId.d.ts.map +1 -0
  25. package/dist/adapters/clientId.js +4 -0
  26. package/dist/adapters/clientId.js.map +1 -0
  27. package/dist/automaticLive.d.ts +1 -1
  28. package/dist/automaticLive.d.ts.map +1 -1
  29. package/dist/automaticLive.js +7 -2
  30. package/dist/automaticLive.js.map +1 -1
  31. package/dist/bind.d.ts.map +1 -1
  32. package/dist/bind.js +1 -1
  33. package/dist/bind.js.map +1 -1
  34. package/dist/changesHandlerLayer.d.ts +19 -0
  35. package/dist/changesHandlerLayer.d.ts.map +1 -0
  36. package/dist/changesHandlerLayer.js +15 -0
  37. package/dist/changesHandlerLayer.js.map +1 -0
  38. package/dist/clientActivity.d.ts +10 -1
  39. package/dist/clientActivity.d.ts.map +1 -1
  40. package/dist/clientActivity.js +7 -0
  41. package/dist/clientActivity.js.map +1 -1
  42. package/dist/clientKeys.d.ts +7 -0
  43. package/dist/clientKeys.d.ts.map +1 -0
  44. package/dist/clientKeys.js +11 -0
  45. package/dist/clientKeys.js.map +1 -0
  46. package/dist/composeBindings.d.ts +8 -0
  47. package/dist/composeBindings.d.ts.map +1 -0
  48. package/dist/composeBindings.js +18 -0
  49. package/dist/composeBindings.js.map +1 -0
  50. package/dist/contract.d.ts +5 -8
  51. package/dist/contract.d.ts.map +1 -1
  52. package/dist/contract.js +11 -7
  53. package/dist/contract.js.map +1 -1
  54. package/dist/internal/automaticQuery.d.ts +3 -1
  55. package/dist/internal/automaticQuery.d.ts.map +1 -1
  56. package/dist/internal/automaticQuery.js +9 -2
  57. package/dist/internal/automaticQuery.js.map +1 -1
  58. package/dist/internal/changesSuccess.d.ts +5 -1
  59. package/dist/internal/changesSuccess.d.ts.map +1 -1
  60. package/dist/internal/changesSuccess.js +10 -6
  61. package/dist/internal/changesSuccess.js.map +1 -1
  62. package/dist/internal/clientActivity.d.ts +5 -6
  63. package/dist/internal/clientActivity.d.ts.map +1 -1
  64. package/dist/internal/clientActivity.js +6 -18
  65. package/dist/internal/clientActivity.js.map +1 -1
  66. package/dist/internal/clientOperations.d.ts +1 -1
  67. package/dist/internal/clientOperations.d.ts.map +1 -1
  68. package/dist/internal/clientOperations.js +7 -4
  69. package/dist/internal/clientOperations.js.map +1 -1
  70. package/dist/internal/compareQueries.d.ts +2 -1
  71. package/dist/internal/compareQueries.d.ts.map +1 -1
  72. package/dist/internal/compareQueries.js +5 -7
  73. package/dist/internal/compareQueries.js.map +1 -1
  74. package/dist/internal/declarationError.d.ts +7 -1
  75. package/dist/internal/declarationError.d.ts.map +1 -1
  76. package/dist/internal/declarationError.js.map +1 -1
  77. package/dist/internal/prependMiddleware.d.ts +10 -0
  78. package/dist/internal/prependMiddleware.d.ts.map +1 -0
  79. package/dist/internal/prependMiddleware.js +12 -0
  80. package/dist/internal/prependMiddleware.js.map +1 -0
  81. package/dist/internal/queryDelivery.d.ts +2 -1
  82. package/dist/internal/queryDelivery.d.ts.map +1 -1
  83. package/dist/internal/queryDelivery.js +8 -1
  84. package/dist/internal/queryDelivery.js.map +1 -1
  85. package/dist/internal/queryReactivity.d.ts.map +1 -1
  86. package/dist/internal/queryReactivity.js +3 -11
  87. package/dist/internal/queryReactivity.js.map +1 -1
  88. package/dist/internal/querySignals.d.ts +8 -0
  89. package/dist/internal/querySignals.d.ts.map +1 -0
  90. package/dist/internal/querySignals.js +42 -0
  91. package/dist/internal/querySignals.js.map +1 -0
  92. package/dist/internal/wrapAtom.d.ts +3 -0
  93. package/dist/internal/wrapAtom.d.ts.map +1 -0
  94. package/dist/internal/wrapAtom.js +15 -0
  95. package/dist/internal/wrapAtom.js.map +1 -0
  96. package/dist/live.d.ts +2 -1
  97. package/dist/live.d.ts.map +1 -1
  98. package/dist/live.js +5 -4
  99. package/dist/live.js.map +1 -1
  100. package/dist/makeLiveServer.d.ts +22 -5
  101. package/dist/makeLiveServer.d.ts.map +1 -1
  102. package/dist/makeLiveServer.js +39 -24
  103. package/dist/makeLiveServer.js.map +1 -1
  104. package/dist/publicConfig.d.ts +19 -3
  105. package/dist/publicConfig.d.ts.map +1 -1
  106. package/dist/querySignals.d.ts +9 -0
  107. package/dist/querySignals.d.ts.map +1 -0
  108. package/dist/querySignals.js +14 -0
  109. package/dist/querySignals.js.map +1 -0
  110. package/dist/querySubscription.d.ts +1 -1
  111. package/dist/querySubscription.d.ts.map +1 -1
  112. package/dist/querySubscription.js +7 -4
  113. package/dist/querySubscription.js.map +1 -1
  114. package/dist/queryUpdate.d.ts +5 -1
  115. package/dist/queryUpdate.d.ts.map +1 -1
  116. package/package.json +10 -10
  117. package/src/CommandGuard.ts +25 -0
  118. package/src/LiveServer.ts +18 -9
  119. package/src/ReadPolicyGuard.ts +31 -0
  120. package/src/adapters/activityState.ts +12 -0
  121. package/src/{internal → adapters}/bindingOwner.ts +3 -2
  122. package/src/adapters/clientId.ts +3 -0
  123. package/src/automaticLive.ts +8 -3
  124. package/src/bind.ts +1 -1
  125. package/src/changesHandlerLayer.ts +51 -0
  126. package/src/clientActivity.ts +8 -1
  127. package/src/clientKeys.ts +17 -0
  128. package/src/composeBindings.ts +27 -0
  129. package/src/contract.ts +14 -20
  130. package/src/internal/automaticQuery.ts +11 -1
  131. package/src/internal/changesSuccess.ts +13 -8
  132. package/src/internal/clientActivity.ts +37 -52
  133. package/src/internal/clientOperations.ts +9 -5
  134. package/src/internal/compareQueries.ts +6 -8
  135. package/src/internal/declarationError.ts +12 -1
  136. package/src/internal/prependMiddleware.ts +15 -0
  137. package/src/internal/queryDelivery.ts +9 -0
  138. package/src/internal/queryReactivity.ts +4 -11
  139. package/src/internal/querySignals.ts +46 -0
  140. package/src/internal/wrapAtom.ts +14 -0
  141. package/src/live.ts +5 -4
  142. package/src/makeLiveServer.ts +64 -57
  143. package/src/querySignals.ts +22 -0
  144. package/src/querySubscription.ts +8 -7
  145. package/src/queryUpdate.ts +5 -1
  146. package/dist/internal/bindingOwner.js.map +0 -1
@@ -0,0 +1,27 @@
1
+ import { type LiveBound, LiveConnection } from "#automaticLive.ts";
2
+
3
+ export const ComposedBindings = Symbol.for("@shivaedev/contract/ComposedBindings");
4
+
5
+ export interface BindingComposition {
6
+ readonly [ComposedBindings]: readonly LiveBound[];
7
+ }
8
+
9
+ export function composeBindings<TClient extends object>(client: TClient, bindings: readonly LiveBound[]): TClient & BindingComposition {
10
+ return { ...client, [ComposedBindings]: bindings };
11
+ }
12
+
13
+ function isComposition(client: object): client is BindingComposition {
14
+ return ComposedBindings in client;
15
+ }
16
+
17
+ 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];
23
+ }
24
+ return [client, ...Object.values(client)].filter(
25
+ (value): value is LiveBound => typeof value === "object" && value !== null && LiveConnection in value,
26
+ );
27
+ }
package/src/contract.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { Schema } from "effect";
2
2
  import { Rpc, RpcGroup, type RpcMiddleware, type RpcSchema } from "effect/rpc";
3
- import { declarationError } from "#internal/declarationError.ts";
3
+ import { declarationError, type Unique } from "#internal/declarationError.ts";
4
4
  import type { CommandShape, OperationShape, QueryShape, StreamShape } from "#operation.ts";
5
+ import { ReadPolicyGuard } from "#ReadPolicyGuard.ts";
5
6
  import { QueryReadDenied } from "#readPolicyErrors.ts";
6
7
  import { changesRpc, KeyScope, operationAnnotations } from "#serverMetadata.ts";
7
8
 
@@ -21,7 +22,7 @@ export type OperationRpc<TContract extends string, TOperation> = TOperation exte
21
22
  TOperation["payload"],
22
23
  TOperation["success"],
23
24
  OperationError<TOperation>,
24
- never,
25
+ TOperation extends QueryShape ? typeof ReadPolicyGuard : never,
25
26
  QueryServices<TOperation>
26
27
  >
27
28
  : never;
@@ -44,7 +45,9 @@ export interface Contract<
44
45
  TName extends string,
45
46
  TQueries extends readonly QueryShape[],
46
47
  TCommands extends readonly CommandShape[],
47
- TRpcs extends Rpc.Any = OperationRpc<TName, TQueries[number] | TCommands[number]> | ReturnType<typeof changesRpc<TName, TQueries>>,
48
+ TRpcs extends Rpc.Any =
49
+ | OperationRpc<TName, TQueries[number] | TCommands[number]>
50
+ | Rpc.AddMiddleware<ReturnType<typeof changesRpc<TName, TQueries>>, typeof ReadPolicyGuard>,
48
51
  TStreams extends readonly StreamShape[] = readonly [],
49
52
  TScope extends "session" | undefined = undefined,
50
53
  > extends RpcGroup.RpcGroup<TRpcs> {
@@ -55,17 +58,6 @@ export interface Contract<
55
58
  ) => Contract<TName, TQueries, TCommands, Rpc.AddMiddleware<TRpcs, TM>, TStreams, TScope>;
56
59
  }
57
60
 
58
- type Duplicated<TOperations extends readonly OperationShape[], TSeen extends string = never> = TOperations extends readonly [
59
- infer THead extends OperationShape,
60
- ...infer TTail extends readonly OperationShape[],
61
- ]
62
- ? (THead["name"] extends TSeen ? THead["name"] : never) | Duplicated<TTail, TSeen | THead["name"]>
63
- : never;
64
-
65
- type Unique<TOperations extends readonly OperationShape[]> = [Duplicated<TOperations>] extends [never]
66
- ? unknown
67
- : `Operation names must be unique; duplicated: ${Duplicated<TOperations>}`;
68
-
69
61
  function assertValid(name: string, operations: readonly (QueryShape | CommandShape | StreamShape)[]) {
70
62
  const error = declarationError(name, operations);
71
63
  if (error !== undefined) {
@@ -112,7 +104,8 @@ export function contract<
112
104
  TName,
113
105
  TQueries,
114
106
  TCommands,
115
- OperationRpc<TName, TQueries[number] | TCommands[number] | TStreams[number]> | ReturnType<typeof changesRpc<TName, TQueries>>,
107
+ | OperationRpc<TName, TQueries[number] | TCommands[number] | TStreams[number]>
108
+ | Rpc.AddMiddleware<ReturnType<typeof changesRpc<TName, TQueries>>, typeof ReadPolicyGuard>,
116
109
  TStreams,
117
110
  TScope
118
111
  >;
@@ -127,16 +120,17 @@ export function contract(
127
120
  ): DeclaredGroup {
128
121
  const { queries = [], commands = [], streams = [], keyScope } = operations;
129
122
  assertValid(name, [...queries, ...commands, ...streams]);
130
- const rpcs = [...queries, ...commands, ...streams].map((operation) =>
131
- Rpc.make(`${name}.${operation.name}`, {
123
+ const rpcs = [...queries, ...commands, ...streams].map((operation) => {
124
+ const rpc = Rpc.make(`${name}.${operation.name}`, {
132
125
  error: operation.kind === "query" ? Schema.Union([operation.error, QueryReadDenied]) : operation.error,
133
126
  payload: operation.payload,
134
127
  stream: operation.kind === "stream",
135
128
  success: operation.success,
136
- }).annotateMerge(operationAnnotations(operation, keyScope)),
137
- );
129
+ }).annotateMerge(operationAnnotations(operation, keyScope));
130
+ return operation.kind === "query" ? rpc.middleware(ReadPolicyGuard) : rpc;
131
+ });
138
132
  const application = RpcGroup.make(...rpcs);
139
- const changes = changesRpc(name, queries);
133
+ const changes = changesRpc(name, queries).middleware(ReadPolicyGuard);
140
134
  return withDeclaration(application.add(keyScope === undefined ? changes : changes.annotate(KeyScope, keyScope)), application, {
141
135
  commands,
142
136
  keyScope,
@@ -4,8 +4,10 @@ import * as Atom from "effect/reactivity/Atom";
4
4
  import type { LiveBound, LiveConnection } from "#automaticLive.ts";
5
5
  import { queryFailure } from "#internal/queryFailure.ts";
6
6
  import { queryResult } from "#internal/queryResult.ts";
7
+ import { recordCompletion, recordSubscription } from "#internal/querySignals.ts";
7
8
  import type { LiveStatus } from "#live.ts";
8
9
  import { queryCoalesceWindow } from "#queryCoalesceWindow.ts";
10
+ import type { QuerySignals } from "#querySignals.ts";
9
11
 
10
12
  interface GateOptions<A, E> {
11
13
  readonly assertOwner: (get: Atom.AtomContext) => void;
@@ -16,6 +18,7 @@ interface GateOptions<A, E> {
16
18
  readonly pushed: boolean;
17
19
  readonly ready: Atom.Writable<boolean>;
18
20
  readonly signal: Atom.Atom<unknown>;
21
+ readonly signals: Atom.Writable<QuerySignals>;
19
22
  readonly source: Atom.Atom<AsyncResult.AsyncResult<A, E>>;
20
23
  readonly statuses: Atom.Writable<ReadonlyMap<object, LiveStatus<unknown>>>;
21
24
  readonly subscription: LiveBound[typeof LiveConnection];
@@ -29,6 +32,7 @@ export function automaticQuery<A, E>({
29
32
  pushed,
30
33
  ready,
31
34
  signal,
35
+ signals,
32
36
  source,
33
37
  statuses,
34
38
  subscription,
@@ -36,17 +40,20 @@ export function automaticQuery<A, E>({
36
40
  const gated = Atom.readable(
37
41
  (get) => {
38
42
  assertOwner(get);
43
+ get.mount(signals);
39
44
  const registry = get.registry;
40
45
  const dispatcher = registry.schedulerAsync.makeDispatcher();
41
46
  let denied = false;
42
47
  let stopSource: (() => void) | undefined;
43
48
  get.addFinalizer(() => stopSource?.());
44
49
  get.set(ready, false);
50
+ get.set(signals, { ...get.once(signals), pending: true, subscription: "opening" });
45
51
  get.once(queryCoalesceWindow(gated));
46
52
  get.subscribe(queryCoalesceWindow(gated), (value) => get.set(queryCoalesceWindow(atom), value), { immediate: true });
47
53
  const token = {};
48
54
  let active = true;
49
55
  function observe(value: LiveStatus<unknown>) {
56
+ get.set(signals, recordSubscription(get.once(signals), value));
50
57
  dispatcher.scheduleTask(() => {
51
58
  if (active) {
52
59
  registry.update(statuses, (current) => new Map([...current, [token, value]]));
@@ -81,6 +88,7 @@ export function automaticQuery<A, E>({
81
88
  const publish = queryResult<A, E>(equivalent, (value) => {
82
89
  if (!denied) {
83
90
  get.setSelf(value);
91
+ get.set(signals, recordCompletion(get.once(signals), value));
84
92
  }
85
93
  });
86
94
  stopSource = registry.subscribe(source, publish);
@@ -101,7 +109,9 @@ export function automaticQuery<A, E>({
101
109
  stopSource?.();
102
110
  stopSource = undefined;
103
111
  }
104
- get.setSelf(AsyncResult.failure(cause));
112
+ const result = AsyncResult.failure(cause);
113
+ get.setSelf(result);
114
+ get.set(signals, recordCompletion(get.once(signals), result));
105
115
  },
106
116
  );
107
117
  get.subscribe(subscription.status, failed);
@@ -3,14 +3,18 @@ import { LiveHint } from "#live.ts";
3
3
  import type { QueryShape } from "#operation.ts";
4
4
  import { QueryReadDenied } from "#readPolicyErrors.ts";
5
5
 
6
+ export const QueryUnchanged = Schema.Struct({ _tag: Schema.Literal("Unchanged"), queryIndex: Schema.Number });
7
+
6
8
  type Rerun<TQuery extends QueryShape> = TQuery extends QueryShape ? ("rerun-and-compare" extends TQuery["live"] ? TQuery : never) : never;
7
9
  type ResultSchema<TQuery extends QueryShape> = TQuery extends QueryShape
8
- ? Schema.Struct<{
9
- _tag: Schema.Literal<"Result">;
10
- query: Schema.Literal<TQuery["name"]>;
11
- queryIndex: Schema.Number;
12
- value: TQuery["success"];
13
- }>
10
+ ?
11
+ | Schema.Struct<{
12
+ _tag: Schema.Literal<"Result">;
13
+ query: Schema.Literal<TQuery["name"]>;
14
+ queryIndex: Schema.Number;
15
+ value: TQuery["success"];
16
+ }>
17
+ | typeof QueryUnchanged
14
18
  : never;
15
19
 
16
20
  export function changesSuccess<const TQueries extends readonly QueryShape[]>(
@@ -22,13 +26,14 @@ export function changesSuccess(queries: readonly QueryShape[]) {
22
26
  QueryReadDenied,
23
27
  ...queries
24
28
  .filter((query) => query.live === "rerun-and-compare")
25
- .map((query) =>
29
+ .flatMap((query) => [
30
+ QueryUnchanged,
26
31
  Schema.Struct({
27
32
  _tag: Schema.Literal("Result"),
28
33
  query: Schema.Literal(query.name),
29
34
  queryIndex: Schema.Number,
30
35
  value: query.success,
31
36
  }),
32
- ),
37
+ ]),
33
38
  ]);
34
39
  }
@@ -1,18 +1,15 @@
1
- import { Effect, SubscriptionRef } from "effect";
1
+ import { Effect } from "effect";
2
2
  import * as AsyncResult from "effect/reactivity/AsyncResult";
3
- import * as Atom from "effect/reactivity/Atom";
4
- import type { ClientActivityState } from "#clientActivity.ts";
3
+ import type * as Atom from "effect/reactivity/Atom";
4
+ import { activityState } from "#adapters/activityState.ts";
5
5
  import { queryCoalesceWindow } from "#queryCoalesceWindow.ts";
6
+ import { wrapAtom } from "./wrapAtom.ts";
6
7
 
7
8
  type ActivityTracker = ReturnType<typeof makeActivity>;
8
9
  export const clientActivities = new WeakMap<object, ActivityTracker>();
9
10
 
10
11
  export function makeActivity() {
11
- const state = Effect.runSync(SubscriptionRef.make<ClientActivityState>({ liveHints: 0, liveInvalidations: 0, refreshingAtoms: 0, rpcCalls: 0 }));
12
- const activity = Object.assign(SubscriptionRef.changes(state), { current: SubscriptionRef.get(state) });
13
- function change(key: keyof ClientActivityState, delta: number) {
14
- Effect.runSync(SubscriptionRef.update(state, (current) => ({ ...current, [key]: current[key] + delta })));
15
- }
12
+ const { activity, change } = activityState();
16
13
  function begin(key: "rpcCalls" | "liveInvalidations") {
17
14
  change(key, 1);
18
15
  return () => change(key, -1);
@@ -25,53 +22,41 @@ export function makeActivity() {
25
22
  );
26
23
  }
27
24
  function watch<A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) {
28
- let watched = Atom.transform(
29
- atom,
30
- (get) => {
31
- get.once(queryCoalesceWindow(watched));
32
- get.subscribe(queryCoalesceWindow(watched), (duration) => get.set(queryCoalesceWindow(atom), duration), { immediate: true });
33
- let busy = false;
34
- let active = true;
35
- let published = false;
36
- function observe(result: AsyncResult.AsyncResult<A, E>) {
37
- if (!active) {
38
- return;
39
- }
40
- const next = result.waiting || AsyncResult.isInitial(result);
41
- if (busy !== next) {
42
- busy = next;
43
- change("refreshingAtoms", next ? 1 : -1);
44
- }
25
+ const watched = wrapAtom(atom, (get) => {
26
+ get.once(queryCoalesceWindow(watched));
27
+ get.subscribe(queryCoalesceWindow(watched), (duration) => get.set(queryCoalesceWindow(atom), duration), { immediate: true });
28
+ let busy = false;
29
+ let active = true;
30
+ let published = false;
31
+ function observe(result: AsyncResult.AsyncResult<A, E>) {
32
+ if (!active) {
33
+ return;
45
34
  }
46
- get.addFinalizer(() => {
47
- active = false;
48
- if (busy) {
49
- change("refreshingAtoms", -1);
50
- }
51
- });
52
- function publish(result: AsyncResult.AsyncResult<A, E>) {
53
- published = true;
54
- observe(result);
55
- get.setSelf(result);
35
+ const next = result.waiting || AsyncResult.isInitial(result);
36
+ if (busy !== next) {
37
+ busy = next;
38
+ change("refreshingAtoms", next ? 1 : -1);
56
39
  }
57
- // An extra query listener would make abandoned screen work look observed.
58
- const context = new Proxy(get, { get: (target, key, receiver) => (key === "setSelf" ? publish : Reflect.get(target, key, receiver)) });
59
- const value = atom.read(context);
60
- if (!published) {
61
- observe(value);
40
+ }
41
+ get.addFinalizer(() => {
42
+ active = false;
43
+ if (busy) {
44
+ change("refreshingAtoms", -1);
62
45
  }
63
- return value;
64
- },
65
- { initialValueTarget: atom },
66
- );
67
- if (atom.keepAlive) {
68
- watched = Atom.keepAlive(watched);
69
- } else if (atom.idleTTL !== undefined) {
70
- watched = Atom.setIdleTTL(watched, atom.idleTTL);
71
- }
72
- if (Atom.isSerializable(atom)) {
73
- Object.assign(watched, { [Atom.SerializableTypeId]: atom[Atom.SerializableTypeId] });
74
- }
46
+ });
47
+ function publish(result: AsyncResult.AsyncResult<A, E>) {
48
+ published = true;
49
+ observe(result);
50
+ get.setSelf(result);
51
+ }
52
+ // An extra query listener would make abandoned screen work look observed.
53
+ const context = new Proxy(get, { get: (target, key, receiver) => (key === "setSelf" ? publish : Reflect.get(target, key, receiver)) });
54
+ const value = atom.read(context);
55
+ if (!published) {
56
+ observe(value);
57
+ }
58
+ return value;
59
+ });
75
60
  return watched;
76
61
  }
77
62
  return { activity, hint: () => change("liveHints", 1), queued: () => begin("liveInvalidations"), track, watch };
@@ -4,11 +4,14 @@ 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
6
  import type { Rpc, RpcSchema } from "effect/rpc";
7
- import { invalidationKeys, type Key, readKeys } from "@shivaedev/changes/keys.ts";
7
+ import type { Key } from "@shivaedev/changes/keys.ts";
8
+ import type { BindingOwner } from "#adapters/bindingOwner.ts";
9
+ import { clientId } from "#adapters/clientId.ts";
8
10
  import type { automaticLive } from "#automaticLive.ts";
9
11
  import type { QueryOptions } from "#bind.ts";
12
+ import { clientInvalidationKeys, clientReadKeys } from "#clientKeys.ts";
10
13
  import type { CommandShape, QueryShape } from "#operation.ts";
11
- import type { BindingOwner } from "./bindingOwner.ts";
14
+ import { shareQuerySignals } from "#querySignals.ts";
12
15
  import { clientActivities } from "./clientActivity.ts";
13
16
  import { queryReactivity } from "./queryReactivity.ts";
14
17
 
@@ -35,12 +38,12 @@ function boundQuery(service: ErasedClient, tag: string, query: QueryShape, autom
35
38
  return existing;
36
39
  }
37
40
  const local = query.reads(payload, Option.none());
38
- const keys = [...local, { _tag: "List" as const, collection: `@query/${tag}/${crypto.randomUUID()}` }];
41
+ const keys = [...local, { _tag: "List" as const, collection: `@query/${tag}/${clientId()}` }];
39
42
  const dependencies =
40
43
  local.length === 0 ? [...keys, { _tag: "List" as const, collection: `@query/${tag.slice(0, tag.lastIndexOf("."))}` }] : keys;
41
44
  const reference = { payload, query: query.name };
42
45
  const result = automatic.query(
43
- reactive(atom, readKeys(dependencies, owner?.context), owner?.registry),
46
+ reactive(atom, clientReadKeys(dependencies, owner?.context), owner?.registry),
44
47
  reference,
45
48
  keys,
46
49
  Schema.toEquivalence(query.success),
@@ -48,6 +51,7 @@ function boundQuery(service: ErasedClient, tag: string, query: QueryShape, autom
48
51
  options.headers,
49
52
  );
50
53
  const tracked = clientActivities.get(service)?.watch(result) ?? result;
54
+ shareQuerySignals(tracked, result);
51
55
  cached.set(atom, tracked);
52
56
  return tracked;
53
57
  },
@@ -66,7 +70,7 @@ function boundCommand(service: ErasedClient, tag: string, command: CommandShape,
66
70
  ...command.invalidates(payload, result),
67
71
  { _tag: "List", collection: `@query/${tag.slice(0, tag.lastIndexOf("."))}` },
68
72
  ];
69
- return Reactivity.invalidate(invalidationKeys(keys, owner?.context));
73
+ return Reactivity.invalidate(clientInvalidationKeys(keys, owner?.context));
70
74
  }
71
75
  return {
72
76
  run: (payload: unknown) =>
@@ -4,7 +4,7 @@ import type { Key } from "@shivaedev/changes/keys.ts";
4
4
  import { changedHint } from "#internal/queryHints.ts";
5
5
  import type { LiveHint } from "#live.ts";
6
6
  import type { QueryRerun, QuerySubscription } from "#querySubscription.ts";
7
- import type { QueryResult, QueryUpdate } from "#queryUpdate.ts";
7
+ import type { QueryResult, QueryUnchanged, QueryUpdate } from "#queryUpdate.ts";
8
8
  import type { QueryRequest } from "#serverMetadata.ts";
9
9
 
10
10
  function hintsFor(hint: LiveHint, subscription: QuerySubscription<unknown, unknown>): readonly LiveHint[] {
@@ -40,14 +40,14 @@ export function compareQueries<E, R>(subscription: QuerySubscription<unknown, un
40
40
  const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(JSON.stringify(encoded))).pipe(Effect.orDie);
41
41
  const hash = Hex.encode(digest);
42
42
  if (hash === hashes.get(index)) {
43
- return undefined;
43
+ return { _tag: "Unchanged", queryIndex: index } satisfies QueryUnchanged;
44
44
  }
45
45
  hashes.set(index, hash);
46
46
  return { _tag: "Result", query: request.query.name, queryIndex: index, value } satisfies QueryResult;
47
47
  });
48
- return Effect.fnUntraced(function* (hint: LiveHint) {
48
+ return Effect.fnUntraced(function* (hint: LiveHint, scopes: readonly (readonly Key[])[] = subscription.scopes) {
49
49
  const updates: QueryUpdate[] = [];
50
- const affected = hint._tag === "Resync" ? undefined : changedHint(hint.keys, subscription.scopes);
50
+ const affected = hint._tag === "Resync" ? undefined : changedHint(hint.keys, scopes);
51
51
  const matching = queries
52
52
  .map((request, index) => ({ index, request }))
53
53
  .filter(
@@ -56,10 +56,8 @@ export function compareQueries<E, R>(subscription: QuerySubscription<unknown, un
56
56
  );
57
57
  for (const { index, request } of matching) {
58
58
  const result = yield* resultFor(request, index);
59
- if (result !== undefined) {
60
- updates.push(result);
61
- }
59
+ updates.push(result);
62
60
  }
63
- return [...updates, ...hintsFor(hint, subscription)];
61
+ return [...updates, ...hintsFor(hint, { ...subscription, scopes })];
64
62
  });
65
63
  }
@@ -1,6 +1,17 @@
1
- import type { CommandShape, QueryShape, StreamShape } from "#operation.ts";
1
+ import type { CommandShape, OperationShape, QueryShape, StreamShape } from "#operation.ts";
2
2
  import { isPermissionReadPolicy } from "#permissionReadPolicy.ts";
3
3
 
4
+ type Duplicated<TOperations extends readonly OperationShape[], TSeen extends string = never> = TOperations extends readonly [
5
+ infer THead extends OperationShape,
6
+ ...infer TTail extends readonly OperationShape[],
7
+ ]
8
+ ? (THead["name"] extends TSeen ? THead["name"] : never) | Duplicated<TTail, TSeen | THead["name"]>
9
+ : never;
10
+
11
+ export type Unique<TOperations extends readonly OperationShape[]> = [Duplicated<TOperations>] extends [never]
12
+ ? unknown
13
+ : `Operation names must be unique; duplicated: ${Duplicated<TOperations>}`;
14
+
4
15
  export function declarationError(contractName: string, operations: readonly (QueryShape | CommandShape | StreamShape)[]): string | undefined {
5
16
  if (operations.some(({ name }) => name === "$changes")) {
6
17
  return `Operation name $changes is reserved for the built-in changes stream on contract ${contractName}`;
@@ -0,0 +1,15 @@
1
+ import { Effect } from "effect";
2
+ import type { Rpc, RpcGroup } from "effect/rpc";
3
+
4
+ type WithMiddlewares = Rpc.Any & { readonly middlewares: ReadonlySet<{ readonly key: string }> };
5
+
6
+ export const prependMiddleware = Effect.fnUntraced(function* <R extends WithMiddlewares>(group: RpcGroup.RpcGroup<R>, key: string) {
7
+ return yield* Effect.sync(() => {
8
+ // Native middleware runs in reverse order; identity must supply the viewer before this guard runs.
9
+ for (const rpc of group.requests.values()) {
10
+ const middlewares = [...rpc.middlewares].sort((left, right) => Number(right.key === key) - Number(left.key === key));
11
+ Object.assign(rpc, { middlewares: new Set(middlewares) });
12
+ }
13
+ return group;
14
+ });
15
+ });
@@ -2,15 +2,24 @@ import { Effect, Stream } from "effect";
2
2
  import * as AsyncResult from "effect/reactivity/AsyncResult";
3
3
  import * as Atom from "effect/reactivity/Atom";
4
4
  import * as AtomRegistry from "effect/reactivity/AtomRegistry";
5
+ import type { QuerySignals } from "#querySignals.ts";
5
6
  import type { QueryUpdate, SubscriptionHint } from "#queryUpdate.ts";
6
7
 
7
8
  export function queryDelivery<A, E>(
8
9
  atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
9
10
  decode: ((value: unknown) => A) | undefined,
10
11
  paused: Atom.Atom<boolean>,
12
+ signals: Atom.Writable<QuerySignals>,
11
13
  ) {
12
14
  const pushed = Atom.make<AsyncResult.AsyncResult<A, E>>(AsyncResult.initial());
13
15
  const deliver = Effect.fnUntraced(function* (update: QueryUpdate): Effect.fn.Return<SubscriptionHint, never, AtomRegistry.AtomRegistry> {
16
+ if (update._tag === "Unchanged") {
17
+ const registry = yield* AtomRegistry.AtomRegistry;
18
+ if (!registry.get(paused)) {
19
+ registry.update(signals, (current) => ({ ...current, completed: current.completed + 1, pending: false }));
20
+ }
21
+ return { _tag: "Changed", keys: [], queryIndexes: [] };
22
+ }
14
23
  if (update._tag !== "Result") {
15
24
  return update;
16
25
  }
@@ -5,6 +5,7 @@ import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
5
5
  import * as Reactivity from "effect/reactivity/Reactivity";
6
6
  import { queryCoalesceWindow } from "#queryCoalesceWindow.ts";
7
7
  import { liveBatches, liveKeys } from "./liveInvalidation.ts";
8
+ import { wrapAtom } from "./wrapAtom.ts";
8
9
 
9
10
  export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: () => () => void) {
10
11
  const service = runtime.atom(Effect.service(Reactivity.Reactivity));
@@ -19,8 +20,8 @@ export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: (
19
20
  Atom.readable((get) => atom.read(get), atom.refresh),
20
21
  0,
21
22
  );
22
- let wrapped = Atom.transform(
23
- source,
23
+ const wrapped = wrapAtom(
24
+ atom,
24
25
  (get) => {
25
26
  if (owner !== undefined && owner !== get.registry) {
26
27
  throw new Error("A session-scoped query belongs to its binding registry");
@@ -116,16 +117,8 @@ export function queryReactivity<R, E>(runtime: Atom.AtomRuntime<R, E>, queue?: (
116
117
  });
117
118
  return get.once(source);
118
119
  },
119
- { initialValueTarget: source },
120
+ source,
120
121
  );
121
- if (atom.keepAlive) {
122
- wrapped = Atom.keepAlive(wrapped);
123
- } else if (atom.idleTTL !== undefined) {
124
- wrapped = Atom.setIdleTTL(wrapped, atom.idleTTL);
125
- }
126
- if (Atom.isSerializable(atom)) {
127
- Object.assign(wrapped, { [Atom.SerializableTypeId]: atom[Atom.SerializableTypeId] });
128
- }
129
122
  cached.set(atom, wrapped);
130
123
  return wrapped;
131
124
  };
@@ -0,0 +1,46 @@
1
+ import * as AsyncResult from "effect/reactivity/AsyncResult";
2
+ import type * as Atom from "effect/reactivity/Atom";
3
+ import type { LiveStatus } from "#live.ts";
4
+ import { queryCoalesceWindow } from "#queryCoalesceWindow.ts";
5
+ import { type QuerySignals, querySignals, shareQuerySignals } from "#querySignals.ts";
6
+ import { wrapAtom } from "./wrapAtom.ts";
7
+
8
+ export function queryProgress<A, E>(atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>) {
9
+ const signals = querySignals(atom);
10
+ const tracked = wrapAtom(atom, (get) => {
11
+ get.mount(signals);
12
+ get.once(queryCoalesceWindow(tracked));
13
+ get.subscribe(queryCoalesceWindow(tracked), (duration) => get.set(queryCoalesceWindow(atom), duration), { immediate: true });
14
+ let published = false;
15
+ function publish(result: AsyncResult.AsyncResult<A, E>) {
16
+ published = true;
17
+ get.setSelf(result);
18
+ get.set(signals, recordCompletion(get.once(signals), result));
19
+ }
20
+ const context = new Proxy(get, { get: (target, key, receiver) => (key === "setSelf" ? publish : Reflect.get(target, key, receiver)) });
21
+ const value = atom.read(context);
22
+ if (!published) {
23
+ get.set(signals, recordCompletion(get.once(signals), value));
24
+ }
25
+ return value;
26
+ });
27
+ shareQuerySignals(tracked, atom);
28
+ return tracked;
29
+ }
30
+
31
+ export function recordCompletion<A, E>(current: QuerySignals, result: AsyncResult.AsyncResult<A, E>): QuerySignals {
32
+ const pending = AsyncResult.isInitial(result) || result.waiting;
33
+ return { ...current, completed: current.completed + (pending ? 0 : 1), pending };
34
+ }
35
+
36
+ export function recordSubscription(current: QuerySignals, status: LiveStatus<unknown>): QuerySignals {
37
+ switch (status.connection) {
38
+ case "live":
39
+ return { ...current, subscription: "open" };
40
+ case "failed":
41
+ return { ...current, subscription: "refused" };
42
+ case "connecting":
43
+ case "reconnecting":
44
+ return { ...current, subscription: "opening" };
45
+ }
46
+ }
@@ -0,0 +1,14 @@
1
+ import * as Atom from "effect/reactivity/Atom";
2
+
3
+ export function wrapAtom<A>(atom: Atom.Atom<A>, read: (get: Atom.AtomContext) => A, source: Atom.Atom<A> = atom): Atom.Atom<A> {
4
+ let wrapped = Atom.transform(source, read, { initialValueTarget: source });
5
+ if (atom.keepAlive) {
6
+ wrapped = Atom.keepAlive(wrapped);
7
+ } else if (atom.idleTTL !== undefined) {
8
+ wrapped = Atom.setIdleTTL(wrapped, atom.idleTTL);
9
+ }
10
+ if (Atom.isSerializable(atom)) {
11
+ Object.assign(wrapped, { [Atom.SerializableTypeId]: atom[Atom.SerializableTypeId] });
12
+ }
13
+ return wrapped;
14
+ }
package/src/live.ts CHANGED
@@ -2,7 +2,8 @@ import { Cause, Duration, Effect, Option, Schema, type Stream } from "effect";
2
2
  import * as Atom from "effect/reactivity/Atom";
3
3
  import type * as AtomRegistry from "effect/reactivity/AtomRegistry";
4
4
  import * as Reactivity from "effect/reactivity/Reactivity";
5
- import { invalidationKeys, Key, type KeyContext, readKeys } from "@shivaedev/changes/keys.ts";
5
+ import { Key } from "@shivaedev/changes/keys.ts";
6
+ import { clientInvalidationKeys, clientReadKeys, type KeyContext } from "#clientKeys.ts";
6
7
  import { liveAttempt } from "#internal/liveAttempt.ts";
7
8
  import { invalidateLive } from "#internal/liveInvalidation.ts";
8
9
  import { livePending } from "#internal/livePending.ts";
@@ -45,7 +46,7 @@ export function live<R, E, TRuntimeError>(runtime: Atom.AtomRuntime<R, TRuntimeE
45
46
  get.mount(status);
46
47
  const reactivity = yield* Reactivity.Reactivity;
47
48
  const retryKeys = options.retryKeys ?? (typeof options.resyncKeys === "function" ? options.resyncKeys(get.registry) : options.resyncKeys);
48
- yield* retryOnChange(status, readKeys(retryKeys, options.keyContext), () => get.refreshSelf());
49
+ yield* retryOnChange(status, clientReadKeys(retryKeys, options.keyContext), () => get.refreshSelf());
49
50
  function update(value: Partial<LiveStatus<E>>) {
50
51
  get.set(status, { ...get.once(status), ...value });
51
52
  }
@@ -71,7 +72,7 @@ export function live<R, E, TRuntimeError>(runtime: Atom.AtomRuntime<R, TRuntimeE
71
72
  });
72
73
  function changed(changedKeys: readonly Key[]) {
73
74
  const window = get.once(coalesceWindow);
74
- const keys = invalidationKeys(changedKeys, options.keyContext);
75
+ const keys = clientInvalidationKeys(changedKeys, options.keyContext);
75
76
  invalidateLive(reactivity, keys, () => active && !get.once(paused), window);
76
77
  const delay = Duration.toMillis(Duration.fromInputUnsafe(window));
77
78
  if (delay === 0) {
@@ -90,7 +91,7 @@ export function live<R, E, TRuntimeError>(runtime: Atom.AtomRuntime<R, TRuntimeE
90
91
  return;
91
92
  }
92
93
  const keys = typeof options.resyncKeys === "function" ? options.resyncKeys(get.registry) : options.resyncKeys;
93
- reactivity.invalidateUnsafe(keys.map((key) => readKeys([key], options.keyContext)[0] ?? ""));
94
+ reactivity.invalidateUnsafe(keys.map((key) => clientReadKeys([key], options.keyContext)[0] ?? ""));
94
95
  update({ needsResync: false, pending: 0 });
95
96
  }
96
97
  // A subscription alone does not build the flag, so its first read would otherwise announce a change.