@powerhousedao/reactor-browser 6.2.3-dev.9 → 6.2.3-dev.91

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 (101) hide show
  1. package/dist/{attachment-service-D3EhiAJ7.d.ts → attachment-service-10Qn5nIw.d.ts} +766 -108
  2. package/dist/attachment-service-10Qn5nIw.d.ts.map +1 -0
  3. package/dist/auth-DzIYxeEJ.d.ts +32 -0
  4. package/dist/auth-DzIYxeEJ.d.ts.map +1 -0
  5. package/dist/{client-DjK30EQ-.js → client-BFnMV-EO.js} +39 -22
  6. package/dist/client-BFnMV-EO.js.map +1 -0
  7. package/dist/{client-D66jVnot.js → client-BNMyQ_Z2.js} +372 -33
  8. package/dist/client-BNMyQ_Z2.js.map +1 -0
  9. package/dist/{client-BIHN_UyR.d.ts → client-C-NgSjoc.d.ts} +4 -3
  10. package/dist/client-C-NgSjoc.d.ts.map +1 -0
  11. package/dist/dispatch-Cylwl2Dk.js +1173 -0
  12. package/dist/dispatch-Cylwl2Dk.js.map +1 -0
  13. package/dist/document-by-id-DdvqanGR.js +16 -0
  14. package/dist/document-by-id-DdvqanGR.js.map +1 -0
  15. package/dist/document-model-modules-ChmfyIxT.js +644 -0
  16. package/dist/document-model-modules-ChmfyIxT.js.map +1 -0
  17. package/dist/document-operations-QtU34A52.js +4664 -0
  18. package/dist/document-operations-QtU34A52.js.map +1 -0
  19. package/dist/global-bbfp3_1x.d.ts +649 -0
  20. package/dist/global-bbfp3_1x.d.ts.map +1 -0
  21. package/dist/{index-B33TKEqp.d.ts → index-Bfr_cWdi.d.ts} +31 -100
  22. package/dist/index-Bfr_cWdi.d.ts.map +1 -0
  23. package/dist/{index-BIVDXw3K.d.ts → index-rtDmzViP.d.ts} +3 -3
  24. package/dist/index-rtDmzViP.d.ts.map +1 -0
  25. package/dist/index.d.ts +837 -411
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +851 -129
  28. package/dist/index.js.map +1 -1
  29. package/dist/inspector-proxy-DODqs15F.d.ts +25 -0
  30. package/dist/inspector-proxy-DODqs15F.d.ts.map +1 -0
  31. package/dist/make-ph-event-functions-B5GU5xcR.js +180 -0
  32. package/dist/make-ph-event-functions-B5GU5xcR.js.map +1 -0
  33. package/dist/{pglite-CntadC_p-9NDG14dS.d.ts → pglite-CntadC_p-DTkdF8sr.d.ts} +11 -33
  34. package/dist/pglite-CntadC_p-DTkdF8sr.d.ts.map +1 -0
  35. package/dist/{relational-D1RB45sA.js → relational-DZuyKp2y.js} +66 -5
  36. package/dist/relational-DZuyKp2y.js.map +1 -0
  37. package/dist/{renown-rqK8sokh.js → renown-B3MUaiq7.js} +61 -31
  38. package/dist/renown-B3MUaiq7.js.map +1 -0
  39. package/dist/renown-CBoTdGrg.js +394 -0
  40. package/dist/renown-CBoTdGrg.js.map +1 -0
  41. package/dist/{types-Dcv1ZLoW.d.ts → schema-Bn6L3QR1.d.ts} +324 -64
  42. package/dist/schema-Bn6L3QR1.d.ts.map +1 -0
  43. package/dist/src/ai/index.d.ts +276 -75
  44. package/dist/src/ai/index.d.ts.map +1 -1
  45. package/dist/src/ai/index.js +733 -172
  46. package/dist/src/ai/index.js.map +1 -1
  47. package/dist/src/analytics/index.d.ts +36 -44
  48. package/dist/src/analytics/index.d.ts.map +1 -1
  49. package/dist/src/analytics/index.js +4 -4
  50. package/dist/src/analytics/index.js.map +1 -1
  51. package/dist/src/document-model.d.ts +3 -4
  52. package/dist/src/document-model.d.ts.map +1 -1
  53. package/dist/src/document-model.js.map +1 -1
  54. package/dist/src/graphql/client.d.ts +4 -3
  55. package/dist/src/graphql/client.js +1 -1
  56. package/dist/src/graphql-client/entry.d.ts +6 -4
  57. package/dist/src/graphql-client/entry.js +4 -4
  58. package/dist/src/relational/index.d.ts +15 -9
  59. package/dist/src/relational/index.d.ts.map +1 -1
  60. package/dist/src/relational/index.js +1 -1
  61. package/dist/src/renown/index.d.ts +3 -2
  62. package/dist/src/renown/index.js +3 -3
  63. package/dist/src/rpc/index.d.ts +217 -140
  64. package/dist/src/rpc/index.d.ts.map +1 -1
  65. package/dist/src/rpc/index.js +600 -623
  66. package/dist/src/rpc/index.js.map +1 -1
  67. package/dist/{store-BJYcr_FL.js → store-DInXcjal.js} +1 -1
  68. package/dist/{store-BJYcr_FL.js.map → store-DInXcjal.js.map} +1 -1
  69. package/dist/{switchboard-CaXQ4-5Q.js → switchboard-B640iT1L.js} +61 -11
  70. package/dist/switchboard-B640iT1L.js.map +1 -0
  71. package/dist/{types-6vDzbRRS.d.ts → types-520nWrB3.d.ts} +2 -2
  72. package/dist/types-520nWrB3.d.ts.map +1 -0
  73. package/dist/types-CT44EMmw.d.ts +59 -0
  74. package/dist/types-CT44EMmw.d.ts.map +1 -0
  75. package/package.json +24 -23
  76. package/dist/attachment-service-D3EhiAJ7.d.ts.map +0 -1
  77. package/dist/client-BIHN_UyR.d.ts.map +0 -1
  78. package/dist/client-D66jVnot.js.map +0 -1
  79. package/dist/client-DjK30EQ-.js.map +0 -1
  80. package/dist/document-by-id-B4FIzG1w.js +0 -519
  81. package/dist/document-by-id-B4FIzG1w.js.map +0 -1
  82. package/dist/document-model-modules-bTP87nyr.js +0 -419
  83. package/dist/document-model-modules-bTP87nyr.js.map +0 -1
  84. package/dist/document-operations-WeE6wIDt.js +0 -2603
  85. package/dist/document-operations-WeE6wIDt.js.map +0 -1
  86. package/dist/global-OuINvEGT.d.ts +0 -401
  87. package/dist/global-OuINvEGT.d.ts.map +0 -1
  88. package/dist/index-B33TKEqp.d.ts.map +0 -1
  89. package/dist/index-BIVDXw3K.d.ts.map +0 -1
  90. package/dist/inspector-proxy-6h5VKAwt.d.ts +0 -257
  91. package/dist/inspector-proxy-6h5VKAwt.d.ts.map +0 -1
  92. package/dist/make-ph-event-functions-DBq3iWYn.js +0 -53
  93. package/dist/make-ph-event-functions-DBq3iWYn.js.map +0 -1
  94. package/dist/pglite-CntadC_p-9NDG14dS.d.ts.map +0 -1
  95. package/dist/relational-D1RB45sA.js.map +0 -1
  96. package/dist/renown-BHxwP7xU.js +0 -97
  97. package/dist/renown-BHxwP7xU.js.map +0 -1
  98. package/dist/renown-rqK8sokh.js.map +0 -1
  99. package/dist/switchboard-CaXQ4-5Q.js.map +0 -1
  100. package/dist/types-6vDzbRRS.d.ts.map +0 -1
  101. package/dist/types-Dcv1ZLoW.d.ts.map +0 -1
@@ -1,34 +1,83 @@
1
- import { a as PHGlobal$1, b as IPackagesListener, ct as PromiseWithState, d as UsePHGlobalValue$1, ot as IDocumentCache, rt as IReactorBrowserClient$1, st as PromiseState, u as SetPHGlobalValue$1, v as IPackageListerUnsubscribe, x as PackageManagerInstallResult, y as IPackageManager } from "./global-OuINvEGT.js";
2
- import { t as PGlite } from "./pglite-CntadC_p-9NDG14dS.js";
3
- import { A as ViewFilterInput, C as GetDocumentQuery, D as PropagationMode$1, E as PhDocumentFieldsFragment, O as Scalars, S as GetDocumentOperationsQuery, b as DocumentChangesSubscription, c as ReactorGraphQLClient, g as ActionInput, k as SdkFunctionWrapper } from "./types-Dcv1ZLoW.js";
4
- import { Action, DocumentModelLib, DocumentModelModule, Operation, PHDocument } from "document-model";
5
- import { Action as Action$1, DocumentModelModule as DocumentModelModule$1, DocumentOperations, ISigner, Operation as Operation$1, PHBaseState, PHDocument as PHDocument$1, PHDocumentHeader } from "@powerhousedao/shared/document-model";
6
- import * as _powerhousedao_reactor0 from "@powerhousedao/reactor";
7
- import { Database, DocumentChangeEvent, DocumentModelSource, IDocumentModelRegistry, ISyncManager, OperationFilter, PagedResults, PagingOptions, PropagationMode, SearchFilter, ViewFilter } from "@powerhousedao/reactor";
1
+ import { _ as Sdk, a as DocumentChangesSubscription, c as GetDocumentQuery, g as Scalars, h as PropagationMode$1, m as PhDocumentFieldsFragment, s as GetDocumentOperationsQuery, t as ActionInput, u as JobChangesSubscription, v as SdkFunctionWrapper, y as ViewFilterInput } from "./schema-Bn6L3QR1.js";
2
+ import { t as BearerTokenProvider } from "./auth-DzIYxeEJ.js";
3
+ import { $ as IPackageManager, Gt as IDocumentCache, Ht as DocumentRefetchState, Jt as OperationsCacheEntry, Kt as IDocumentTypeCache, Lt as IReactorBrowserClient$1, Q as IPackageListerUnsubscribe, Rt as IReactorBrowserReadClient, Ut as DocumentsOfTypeEntry, Xt as PromiseWithState, Yt as PromiseState, b as UsePHGlobalValue$1, et as IPackagesListener, qt as IOperationCache, s as PHGlobal$1, tt as PackageManagerInstallResult, v as SetPHGlobalValue$1, zt as IReactorBrowserWriteClient } from "./global-bbfp3_1x.js";
4
+ import { t as PGlite } from "./pglite-CntadC_p-DTkdF8sr.js";
5
+ import { c as ReactorGraphQLClient } from "./types-CT44EMmw.js";
8
6
  import { ReactNode } from "react";
9
- import { GraphQLClient, Variables } from "graphql-request";
10
- import * as graphql from "graphql";
7
+ import { Action, DocumentModelLib, DocumentModelModule, Operation, PHDocument } from "document-model";
8
+ import { Action as Action$1, ActionSigningTarget, DispatchOutcome, DocumentModelModule as DocumentModelModule$1, DocumentOperations, ISigner, Operation as Operation$1, PHBaseState, PHDocument as PHDocument$1, PHDocumentHeader, ProtocolVersions, SignaturePolicy } from "@powerhousedao/shared/document-model";
9
+ import { BatchExecutionRequest, BatchExecutionResult, ConsistencyToken, CreateProtocolVersionsOptions, Database, DocumentChangeEvent, DocumentModelSource, DocumentRelationship, DriveNodeKind, DriveNodePage, DriveNodeRecord, IDocumentModelRegistry, IDriveNodeSource, IDriveReadClient, IReactorClient, ISyncManager, JobInfo, NewDocumentOptions, OperationFilter, PagedResults, PagingOptions, PropagationMode, SearchFilter, UndoRedoAvailability, UndoRedoTargets, ViewFilter } from "@powerhousedao/reactor";
10
+ import { Node } from "@powerhousedao/shared/document-drive";
11
11
  import { DocumentNode } from "graphql";
12
- import * as react_jsx_runtime0 from "react/jsx-runtime";
12
+ import { GraphQLClient, Variables } from "graphql-request";
13
13
  import { IAttachmentService } from "@powerhousedao/reactor-attachments/client";
14
14
  import { Kysely } from "kysely";
15
- import { AddPHGlobalEventHandler, BrowserReactorClientModule, IReactorBrowserClient, SetPHGlobalValue, UsePHGlobalValue, WorkerReactorClientModule } from "@powerhousedao/reactor-browser";
15
+ import { AddPHGlobalEventHandler, BrowserReactorClientModule, IReactorBrowserClient, ReactorBrowserHalves, SetPHGlobalValue, UsePHGlobalValue, WorkerReactorClientModule } from "@powerhousedao/reactor-browser";
16
16
  import { RegistryPackageSource } from "@powerhousedao/shared";
17
-
17
+ import { ReactorReach, RoutableBackendConfig } from "@powerhousedao/reactor-router";
18
+ //#region src/actions/dispatch.d.ts
19
+ /** Called once the write lands; `outcome.rejected` is empty when every action applied. */
20
+ type DispatchSuccessCallback = (result: PHDocument$1, outcome: DispatchOutcome) => void;
21
+ /**
22
+ * Dispatches actions to a document.
23
+ * @param actionOrActions - The action or actions to dispatch.
24
+ * @param document - The document to dispatch actions to.
25
+ * @param onErrors - Callback invoked with an `OperationRejectedError` for each action the
26
+ * document did not apply, or with why nothing was dispatched. Runs before `onSuccess`.
27
+ * @param onSuccess - Callback invoked with the updated document once the write lands, after
28
+ * `onErrors` and also when an action was rejected; `outcome.rejected` lists the rejections.
29
+ * @returns The updated document, or undefined if the dispatch failed.
30
+ */
31
+ declare function dispatchActions<TDocument = PHDocument$1, TAction = Action$1>(actionOrActions: TAction[] | TAction | undefined, document: TDocument | undefined, onErrors?: (errors: Error[]) => void, onSuccess?: DispatchSuccessCallback): Promise<PHDocument$1 | undefined>;
32
+ /**
33
+ * Dispatches actions to a document.
34
+ * @param actionOrActions - The action or actions to dispatch.
35
+ * @param documentId - The ID of the document to dispatch actions to.
36
+ * @param onErrors - Callback invoked with an `OperationRejectedError` for each action the
37
+ * document did not apply. Runs before `onSuccess`.
38
+ * @param onSuccess - Callback invoked with the updated document once the write lands, after
39
+ * `onErrors` and also when an action was rejected; `outcome.rejected` lists the rejections.
40
+ * @returns The updated document, or undefined if the dispatch failed.
41
+ */
42
+ declare function dispatchActions(actionOrActions: Action$1[] | Action$1 | undefined, documentId: string, onErrors?: (errors: Error[]) => void, onSuccess?: DispatchSuccessCallback): Promise<PHDocument$1 | undefined>;
43
+ //#endregion
44
+ //#region src/document-refetcher.d.ts
45
+ /** The refetch snapshot of a document with nothing in flight and no kept failure. */
46
+ declare const IDLE_REFETCH_STATE: DocumentRefetchState;
47
+ //#endregion
18
48
  //#region src/document-cache.d.ts
49
+ /**
50
+ * The reads a {@link DocumentCache} makes. `getMany` is optional: without it,
51
+ * a batch reads each uncached id with `get`.
52
+ */
53
+ interface IDocumentCacheReader extends Pick<IReactorBrowserReadClient, "get" | "find" | "getOperations" | "subscribe">, Partial<Pick<IReactorBrowserReadClient, "getMany">> {}
54
+ /** The most ids one `getMany` call is asked for. */
55
+ declare const GET_MANY_CHUNK_SIZE = 100;
19
56
  declare function addPromiseState<T>(promise: Promise<T>): PromiseWithState<T>;
20
57
  declare function readPromiseState<T>(promise: Promise<T> | PromiseWithState<T>): PromiseState<T>;
58
+ /** The snapshot every uncached document scope reads as. One frozen object, so `useSyncExternalStore` sees a stable value. */
59
+ declare const IDLE_OPERATIONS_ENTRY: OperationsCacheEntry;
60
+ /** Whether a document cache also serves operation history. `GraphQLClientDocumentCache` does not. */
61
+ declare function isOperationCache(cache: unknown): cache is IOperationCache;
62
+ /** The snapshot every unloaded type reads as, frozen so `useSyncExternalStore` sees one value. */
63
+ declare const IDLE_DOCUMENTS_OF_TYPE_ENTRY: DocumentsOfTypeEntry;
64
+ /** Whether a document cache also lists documents by type. */
65
+ declare function isDocumentTypeCache(cache: unknown): cache is IDocumentTypeCache;
21
66
  /**
22
67
  * Document cache implementation that uses the new ReactorClient API.
23
68
  *
24
- * This cache subscribes to document change events via IReactorBrowserClient.subscribe()
69
+ * This cache subscribes to document change events through the client's read half
25
70
  * and automatically updates the cache when documents are created, updated, or deleted.
71
+ * It is built over a browser client, whose `read` half it uses, or over a read
72
+ * half directly.
73
+ * It also holds paginated operation history per document scope (see `IOperationCache`),
74
+ * which is dropped for a document whenever a change event for it arrives.
26
75
  */
27
- declare class DocumentCache implements IDocumentCache {
28
- private client;
76
+ declare class DocumentCache implements IDocumentCache, IOperationCache, IDocumentTypeCache {
29
77
  private documents;
30
78
  private batchPromises;
31
79
  private listeners;
80
+ private refetcher;
32
81
  /**
33
82
  * Cache keys that fetched a document under a name other than its id --
34
83
  * slugs, which `client.get` resolves. Change events dispatch by `header.id`,
@@ -37,19 +86,84 @@ declare class DocumentCache implements IDocumentCache {
37
86
  * the same document is cached under.
38
87
  */
39
88
  private aliasKeys;
89
+ /** Operations by document id, then scope. Entries are replaced, never mutated. */
90
+ private operationEntries;
91
+ /** In-flight controllers and the next page's cursor/limit, by document id then scope. */
92
+ private operationRequests;
93
+ private operationListeners;
94
+ /** Documents by type and page size, keyed by typeKey. */
95
+ private typeEntries;
96
+ private typeRequests;
97
+ private typeListeners;
40
98
  private unsubscribe;
41
- constructor(client: IReactorBrowserClient$1);
99
+ private readonly client;
100
+ constructor(client: IReactorBrowserClient$1 | IDocumentCacheReader);
42
101
  private handleDocumentChange;
43
102
  private handleDocumentDeleted;
44
103
  private handleDocumentUpdated;
104
+ private notifyListeners;
45
105
  /** The id an event dispatches by, plus every alias the document is cached under. */
46
106
  private cacheKeysFor;
47
107
  /** Records that `key` cached the document change events know as `header.id`. */
48
108
  private recordAlias;
49
109
  private invalidateBatchesContaining;
50
110
  get(id: string, refetch?: boolean): Promise<PHDocument$1>;
111
+ getRefetchState(id: string): DocumentRefetchState;
51
112
  getBatch(ids: string[]): Promise<PHDocument$1[]>;
113
+ /**
114
+ * Reserves an entry for every id not yet cached and fills them from
115
+ * `getMany`, in chunks of {@link GET_MANY_CHUNK_SIZE}. Each id keeps its own
116
+ * entry, settled as `get` would settle it.
117
+ */
118
+ private loadMany;
119
+ /**
120
+ * `getMany` rejects when any id is unavailable, so a failed chunk is split
121
+ * in half and retried; a single id is read with `get`, so it settles exactly
122
+ * as a single read would.
123
+ */
124
+ private settleMany;
125
+ private settleFetched;
52
126
  subscribe(id: string | string[], callback: () => void): () => void;
127
+ getOperationsState(documentId: string, scope: string): OperationsCacheEntry;
128
+ loadOperations(documentId: string, scope: string, limit: number): void;
129
+ loadMoreOperations(documentId: string, scope: string): void;
130
+ /**
131
+ * Bring a document's cached scopes up to date after it changed, without
132
+ * throwing away what is already loaded.
133
+ *
134
+ * The operation stream is append-only: an update adds operations at higher
135
+ * revisions and never rewrites the ones below, so history already paged in
136
+ * is still correct. Dropping it meant a panel showing a fully loaded
137
+ * document re-walked every page on each edit -- the cost of which grows
138
+ * with the document, exactly where it hurts most. Each scope instead asks
139
+ * only for what comes after the newest revision it holds, using the
140
+ * `sinceRevision` filter, and appends the answer.
141
+ *
142
+ * A scope that has not finished paging is dropped as before: it has no
143
+ * meaningful "newest revision" to resume from, since asking for everything
144
+ * past the newest row it happens to hold would skip the pages between that
145
+ * row and the end of the stream.
146
+ */
147
+ private refreshOperations;
148
+ /** Drops one scope of a document, aborting its request if one is in flight. */
149
+ private invalidateOperationsScope;
150
+ invalidateOperations(documentId: string): void;
151
+ subscribeOperations(documentId: string, callback: () => void): () => void;
152
+ private settleOperationsPage;
153
+ private setOperationsEntry;
154
+ private setOperationsRequest;
155
+ private notifyOperationListeners;
156
+ getDocumentsOfTypeState(type: string, limit: number): DocumentsOfTypeEntry;
157
+ loadDocumentsOfType(type: string, limit: number): Promise<void>;
158
+ loadMoreDocumentsOfType(type: string, limit: number): void;
159
+ subscribeDocumentsOfType(type: string, limit: number, callback: () => void): () => void;
160
+ /** Loads one page after `before` and appends it; never rejects, the entry holds the error. */
161
+ private loadTypePage;
162
+ /** Reloads every loaded page of a type a created or deleted document belongs to. */
163
+ private reloadTypesChangedBy;
164
+ private primeDocument;
165
+ private getTypeEntry;
166
+ private setTypeEntry;
53
167
  /**
54
168
  * Disposes of the cache and unsubscribes from document change events.
55
169
  */
@@ -57,7 +171,7 @@ declare class DocumentCache implements IDocumentCache {
57
171
  }
58
172
  //#endregion
59
173
  //#region src/remote-controller/types.d.ts
60
- type RemoteControllerGraphQLClient = Pick<ReactorGraphQLClient, "GetDocument" | "GetDocumentWithOperations" | "GetDocumentOperations" | "MutateDocument" | "CreateDocument" | "CreateEmptyDocument" | "DeleteDocument" | "BatchGetDocumentOperations" | "BatchGetDocumentWithOperations">;
174
+ type RemoteControllerGraphQLClient = Pick<ReactorGraphQLClient, "GetDocument" | "GetDocumentWithOperations" | "GetDocumentOperations" | "MutateDocument" | "CreateDocument" | "CreateEmptyDocument" | "GetCreateDefaults" | "GetCreateProtocolVersions" | "DeleteDocument" | "BatchGetDocumentOperations" | "BatchGetDocumentWithOperations">;
61
175
  type RemoteDocumentData = PhDocumentFieldsFragment;
62
176
  type RemoteOperation = GetDocumentOperationsQuery["documentOperations"]["items"][number];
63
177
  type RemoteOperationResultPage = GetDocumentOperationsQuery["documentOperations"];
@@ -65,14 +179,22 @@ type RemoteOperationResultPage = GetDocumentOperationsQuery["documentOperations"
65
179
  * Options for creating a RemoteDocumentController.
66
180
  */
67
181
  type RemoteControllerOptions = {
68
- client: RemoteControllerGraphQLClient; /** Remote document id. Omit for new documents. */
69
- documentId?: string; /** "batch" requires explicit push(), "streaming" auto-pushes after actions. Defaults to "batch" */
70
- mode?: "batch" | "streaming"; /** Optional signer for action signing. */
71
- signer?: ISigner; /** Branch name, defaults to "main". */
72
- branch?: string; /** Parent document identifier for creating new documents. */
73
- parentIdentifier?: string; /** Conflict resolution strategy when remote has new operations. Default: no check (current behavior). */
74
- onConflict?: ConflictStrategy; /** Called when a streaming-mode push fails. If not provided, errors are silently swallowed. */
75
- onPushError?: (error: unknown) => void; /** Number of operations to fetch per page. Defaults to 100. */
182
+ client: RemoteControllerGraphQLClient;
183
+ /** Remote document id. Omit for new documents. */
184
+ documentId?: string;
185
+ /** "batch" requires explicit push(), "streaming" auto-pushes after actions. Defaults to "batch" */
186
+ mode?: "batch" | "streaming";
187
+ /** Optional signer for action signing. */
188
+ signer?: ISigner;
189
+ /** Branch name, defaults to "main". */
190
+ branch?: string;
191
+ /** Parent document identifier for creating new documents. */
192
+ parentIdentifier?: string;
193
+ /** Conflict resolution strategy when remote has new operations. Default: no check (current behavior). */
194
+ onConflict?: ConflictStrategy;
195
+ /** Called when a streaming-mode push fails. If not provided, errors are silently swallowed. */
196
+ onPushError?: (error: unknown) => void;
197
+ /** Number of operations to fetch per page. Defaults to 100. */
76
198
  operationsPageSize?: number;
77
199
  };
78
200
  /**
@@ -80,7 +202,8 @@ type RemoteControllerOptions = {
80
202
  */
81
203
  type PushResult = {
82
204
  remoteDocument: RemoteDocumentData;
83
- actionCount: number; /** The actions that were sent to the server (after signing, if applicable). */
205
+ actionCount: number;
206
+ /** The actions that were sent to the server (after signing, if applicable). */
84
207
  operations: ReadonlyArray<Action$1>;
85
208
  };
86
209
  /**
@@ -102,9 +225,13 @@ type TrackedAction = {
102
225
  };
103
226
  /** Information about a detected conflict. */
104
227
  type ConflictInfo = {
105
- /** Remote operations added since the last pull, grouped by scope. */remoteOperations: Record<string, RemoteOperation[]>; /** Local actions pending push. */
106
- localActions: TrackedAction[]; /** Remote revision at last pull. */
107
- knownRevision: Record<string, number>; /** Current remote revision. */
228
+ /** Remote operations added since the last pull, grouped by scope. */
229
+ remoteOperations: Record<string, RemoteOperation[]>;
230
+ /** Local actions pending push. */
231
+ localActions: TrackedAction[];
232
+ /** Remote revision at last pull. */
233
+ knownRevision: Record<string, number>;
234
+ /** Current remote revision. */
108
235
  currentRevision: Record<string, number>;
109
236
  };
110
237
  /** Custom merge handler receives conflict info and returns actions to push (or throws to abort). */
@@ -170,8 +297,8 @@ type RevisionsListSelection = GetDocumentQueryFields["revisionsList"];
170
297
  * `createPresignedHeader`: the creation signature is not fetchable over
171
298
  * GraphQL and is not part of the operation signing payload.
172
299
  *
173
- * The read path never fetches operation history, so `operations` is a map of
174
- * the document's known scopes to empty arrays.
300
+ * The read path never fetches operation history, so `operations` maps each
301
+ * scope of the document's state and revisions to an empty array.
175
302
  *
176
303
  * `branch` is the branch the document was read from. The GraphQL type does not
177
304
  * carry it, so it has to be passed back in by the caller; it defaults to the
@@ -188,34 +315,118 @@ declare function phDocumentFromGetDocument<TDocument extends PHDocument = PHDocu
188
315
  declare function phDocumentFromMutation<TDocument extends PHDocument = PHDocument>(document: GetDocumentQueryFields, operations: readonly RemoteOperation[], branch?: string): TDocument;
189
316
  /** Turns a `revisionsList` selection into the header's per-scope revision map. */
190
317
  declare function revisionMapFromRevisionsList(revisionsList: RevisionsListSelection): Record<string, number>;
318
+ /** The `DateTime` scalar deserializes as either an ISO string or a `Date`. */
319
+ declare function isoStringFromDateTime(value: string | Date): string;
191
320
  //#endregion
192
- //#region src/graphql-client/auth.d.ts
321
+ //#region src/graphql-client/drive-nodes.d.ts
322
+ /** The node queries a {@link GraphQLDriveNodeSource} runs. */
323
+ type DriveNodeQueries = Pick<Sdk, "GetDriveNodes" | "GetDriveNode" | "GetDriveDescendants">;
193
324
  /**
194
- * Resolves the bearer token to send with a request.
195
- *
196
- * Returning `undefined` (or an empty string) means "send this request
197
- * anonymously": open Switchboards must keep serving reads to logged-out users.
325
+ * The reactor subgraph's type-neutral node queries (`driveNodes`, `driveNode`,
326
+ * `driveDescendants`) as an {@link IDriveNodeSource}, so a browser reads a
327
+ * legacy drive and a reactor-drive alike. The Switchboard serves only the
328
+ * nodes the caller may read. Drive ids must be canonical ids, not slugs.
198
329
  */
199
- type BearerTokenProvider = () => Promise<string | undefined>;
330
+ declare class GraphQLDriveNodeSource implements IDriveNodeSource {
331
+ private readonly queries;
332
+ private readonly headersFor;
333
+ constructor(queries: DriveNodeQueries, headersFor?: (driveId: string) => Record<string, string> | undefined);
334
+ getNode(driveId: string, nodeId: string, signal?: AbortSignal): Promise<DriveNodeRecord | undefined>;
335
+ listChildren(driveId: string, parentFolder: string | null | undefined, paging?: PagingOptions, signal?: AbortSignal, kind?: DriveNodeKind): Promise<DriveNodePage>;
336
+ getDescendants(driveId: string, root: string, signal?: AbortSignal): Promise<DriveNodeRecord[]>;
337
+ listAll(driveId: string, signal?: AbortSignal): Promise<DriveNodeRecord[]>;
338
+ }
200
339
  /**
201
- * The default token provider: the token of the currently logged-in Renown user.
202
- *
203
- * It is deliberately resolved from `window.ph` on every call rather than
204
- * captured at construction time, so a client built before login starts sending
205
- * the token as soon as there is one.
206
- *
207
- * The token is requested WITHOUT an `aud` claim - the Switchboard verifier
208
- * rejects tokens that carry an audience.
340
+ * `read.drives` over a node source: the reactor's {@link IDriveReadClient},
341
+ * answering in the legacy `Node` shape for every drive type.
209
342
  */
210
- declare function ambientRenownTokenProvider(): Promise<string | undefined>;
343
+ declare class GraphQLDriveReadClient implements IDriveReadClient {
344
+ private readonly nodes;
345
+ constructor(nodes: IDriveNodeSource);
346
+ getNode(driveIdentifier: string, nodeId: string, signal?: AbortSignal): Promise<Node>;
347
+ listNodes(driveIdentifier: string, parentFolder?: string | null, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Node>>;
348
+ }
349
+ /** A node record in the legacy `Node` shape. */
350
+ declare function toLegacyNode(node: DriveNodeRecord): Node;
351
+ //#endregion
352
+ //#region src/graphql-client/errors.d.ts
353
+ /** A call the Switchboard GraphQL surface cannot express. */
354
+ declare class GraphQLOperationNotSupportedError extends Error {
355
+ readonly name = "GraphQLOperationNotSupportedError";
356
+ readonly operation: string;
357
+ constructor(operation: string, reason: string);
358
+ static isError(error: unknown): error is GraphQLOperationNotSupportedError;
359
+ }
211
360
  /**
212
- * Builds the SDK middleware that authenticates every request.
213
- *
214
- * The token is resolved per request and never cached, so a login, a logout or
215
- * an expiry between two calls is picked up by the next one. When no token is
216
- * available the request goes out unauthenticated.
361
+ * The Switchboard refused a request with 421 Misdirected Request: the
362
+ * `Drive-Id` it carried names a drive that Switchboard does not own.
363
+ */
364
+ declare class GraphQLWrongBackendError extends Error {
365
+ readonly name = "GraphQLWrongBackendError";
366
+ readonly status = 421;
367
+ /** The drive the Switchboard refused, or `""` when its answer names none. */
368
+ readonly driveId: string;
369
+ /** The response body, parsed when it is JSON. */
370
+ readonly payload: unknown;
371
+ constructor(driveId: string, payload: unknown, options?: ErrorOptions);
372
+ static isError(error: unknown): error is GraphQLWrongBackendError;
373
+ }
374
+ /**
375
+ * The reactor's `BatchJobFailedError`, rebuilt from a batch result; this entry
376
+ * imports the reactor for types only. The shared name lets either `isError`
377
+ * recognise it.
378
+ */
379
+ declare class BatchJobFailedError extends Error {
380
+ readonly name = "BatchJobFailedError";
381
+ readonly key: string;
382
+ readonly jobs: Readonly<Record<string, JobInfo>>;
383
+ constructor(key: string, jobs: Record<string, JobInfo>);
384
+ static isError(error: unknown): error is BatchJobFailedError;
385
+ }
386
+ /** A validation error naming root field `field` unknown: a host from before it. */
387
+ declare function queriesUnknownField(error: unknown, field: string): boolean;
388
+ /** A validation error naming `argument` unknown: a host from before it. */
389
+ declare function queriesUnknownArgument(error: unknown, argument: string): boolean;
390
+ /**
391
+ * The reactor's `JobFailedError`, rebuilt from a job the Switchboard reported
392
+ * FAILED; this entry imports the reactor for types only. A write handle's
393
+ * stage rejects with it. The message is the job error's message, as the
394
+ * reactor's is.
395
+ */
396
+ declare class JobFailedError extends Error {
397
+ readonly name = "JobFailedError";
398
+ readonly job: JobInfo;
399
+ constructor(job: JobInfo);
400
+ static isError(error: unknown): error is JobFailedError;
401
+ }
402
+ //#endregion
403
+ //#region src/graphql-client/transport.d.ts
404
+ /** The `fetch` a client's HTTP requests go through. */
405
+ type GraphQLFetch = typeof globalThis.fetch;
406
+ /** The global `fetch`, read per call so a later replacement is honoured. */
407
+ declare const globalFetch: GraphQLFetch;
408
+ /**
409
+ * Whether `fetch` here is Node's (undici), which resends a request answered
410
+ * 421 and can fail the resend of a buffered body. A page, Electron's renderer
411
+ * included, has a `document`.
412
+ */
413
+ declare function isNodeFetch(): boolean;
414
+ /**
415
+ * Sends a string body as a stream, which fetch never resends, so a 421 comes
416
+ * back as itself. Browsers keep buffered bodies: Chrome streams an upload only
417
+ * over HTTP/2.
418
+ */
419
+ declare function withStreamedBodies(inner?: GraphQLFetch): GraphQLFetch;
420
+ /** A Switchboard backend's default transport: streamed bodies under Node only. */
421
+ declare const switchboardFetch: GraphQLFetch;
422
+ /** Bounds each request, headers through body; rejects with a `TimeoutError`. */
423
+ declare function withRequestDeadline(timeoutMs: number, inner?: GraphQLFetch): GraphQLFetch;
424
+ /**
425
+ * Whether a request failed at a deadline rather than by its caller's abort:
426
+ * this transport's own (`TimeoutError`, a DOMException) or the router's probe
427
+ * deadline (`ProbeTimeoutError`, reactor-router's dispatcher.ts).
217
428
  */
218
- declare function makeAuthMiddleware(tokenProvider: BearerTokenProvider): SdkFunctionWrapper;
429
+ declare function isDeadlineError(error: unknown): boolean;
219
430
  //#endregion
220
431
  //#region src/graphql-client/subgraph.d.ts
221
432
  /**
@@ -286,8 +497,9 @@ declare function describeGraphQLDocument(document: string | DocumentNode): {
286
497
  declare class SubgraphSdkRegistry {
287
498
  private readonly url;
288
499
  private readonly middleware;
500
+ private readonly fetch;
289
501
  private readonly bindings;
290
- constructor(url: string, middleware?: SdkFunctionWrapper);
502
+ constructor(url: string, middleware?: SdkFunctionWrapper, fetch?: GraphQLFetch);
291
503
  /**
292
504
  * Returns the subgraph's SDK, building it on first use.
293
505
  *
@@ -303,14 +515,25 @@ declare class SubgraphSdkRegistry {
303
515
  }
304
516
  //#endregion
305
517
  //#region src/graphql-client/graphql-reactor-client.d.ts
518
+ /** A call the client asks {@link GraphQLReactorClientOptions.driveIdFor} about. */
519
+ type DriveIdCall = {
520
+ readonly method: "create" | "execute" | "executeBatch" | "deleteDocument" | "find";
521
+ readonly documentId?: string;
522
+ readonly parentId?: string;
523
+ readonly jobs?: readonly {
524
+ readonly documentId: string;
525
+ }[];
526
+ };
306
527
  type GraphQLReactorClientOptions = {
307
- /** The Switchboard GraphQL endpoint, e.g. `http://localhost:4001/graphql`. */url: string;
528
+ /** The Switchboard GraphQL endpoint, e.g. `http://localhost:4001/graphql`. */
529
+ url: string;
308
530
  /**
309
531
  * A pre-built SDK to use instead of the transport derived from `url`.
310
532
  * Mainly a test seam.
311
533
  *
312
- * A client built this way carries no auth middleware: the injected SDK owns
313
- * its own transport, and therefore its own headers.
534
+ * A client built this way carries no auth middleware and no 421 mapping:
535
+ * the injected SDK owns its own transport, and therefore its own headers
536
+ * and transport errors.
314
537
  */
315
538
  graphqlClient?: ReactorGraphQLClient;
316
539
  /**
@@ -348,19 +571,43 @@ type GraphQLReactorClientOptions = {
348
571
  * `state.document.version` is here. One action needs no prediction and is
349
572
  * signed without any of this.
350
573
  *
351
- * Read once, when the client is built. Below `GraphQLReactorProvider` this
352
- * is its `documentModels` prop; a client constructed directly passes its own.
574
+ * An array is read once, when the client is built; a function is called at
575
+ * every batch, for a registry that gains models later. Below
576
+ * `GraphQLReactorProvider` this is its `documentModels` prop; a client
577
+ * constructed directly passes its own.
353
578
  */
354
- documentModels?: readonly DocumentModelModule<any>[];
579
+ documentModels?: readonly DocumentModelModule<any>[] | (() => readonly DocumentModelModule<any>[]);
355
580
  /**
356
581
  * Signs the actions this client pushes, instead of the logged-in Renown user.
357
582
  *
358
583
  * Left out - the normal case - the signer is resolved per push from
359
584
  * `window.ph.renown`, so a page signs as whoever is logged in and pushes
360
585
  * unsigned when nobody is. Set it where there is no Renown to read: tests,
361
- * scripts, and integration suites that must sign deterministically.
586
+ * scripts, and integration suites that must sign deterministically. A
587
+ * function is called per push, and pushes unsigned when it returns
588
+ * `undefined`.
362
589
  */
363
- signer?: ISigner;
590
+ signer?: ISigner | (() => ISigner | undefined);
591
+ /**
592
+ * Names the drive a call belongs to when the client cannot prove it itself,
593
+ * for its `Drive-Id` header; `undefined` sends none. Return only a drive id
594
+ * the caller knows: a Switchboard that does not own it answers 421. Where
595
+ * the client has proof of its own and the two disagree, the proof is sent.
596
+ */
597
+ driveIdFor?: (call: DriveIdCall) => string | undefined;
598
+ /**
599
+ * Bounds each HTTP request, headers through body, in milliseconds; a request
600
+ * past it rejects with a `TimeoutError`. Unset, requests are unbounded.
601
+ */
602
+ requestTimeoutMs?: number;
603
+ /**
604
+ * Bounds an `executeBatch` request in place of `requestTimeoutMs`. The
605
+ * mutation answers once its jobs are readable, and it has no form that does
606
+ * not wait, so one request lasts as long as the write does.
607
+ */
608
+ batchRequestTimeoutMs?: number;
609
+ /** The `fetch` every HTTP request goes through; the global one by default. */
610
+ fetch?: GraphQLFetch;
364
611
  };
365
612
  /**
366
613
  * The marker {@link isGraphQLReactorClient} looks for.
@@ -371,6 +618,11 @@ type GraphQLReactorClientOptions = {
371
618
  * and answers `false`. A branded property survives both.
372
619
  */
373
620
  declare const graphQLReactorClientBrand: "__powerhouseGraphQLReactorClient";
621
+ /** The read half of {@link GraphQLReactorClient}: the hooks' reads plus `drives`. */
622
+ interface GraphQLReactorReadClient extends IReactorBrowserReadClient {
623
+ /** A drive's nodes from the node queries, for every drive type. */
624
+ readonly drives: IDriveReadClient;
625
+ }
374
626
  /**
375
627
  * A light implementation of {@link IReactorBrowserClient} that talks plain
376
628
  * GraphQL to a Switchboard, with no reactor in the bundle.
@@ -382,21 +634,92 @@ declare class GraphQLReactorClient implements IReactorBrowserClient$1 {
382
634
  /** See {@link isGraphQLReactorClient}. */
383
635
  readonly [graphQLReactorClientBrand] = true;
384
636
  private readonly sdk;
637
+ /** For `executeBatch`, the one write a request waits for: see {@link batchRequestTimeoutMs}. */
638
+ private readonly batchSdk;
385
639
  private readonly subgraphs;
386
640
  private readonly listeners;
387
641
  private readonly tokenProvider;
388
642
  private readonly subscriptionsUrl;
389
643
  private readonly documentModels;
390
- private readonly signer;
644
+ private readonly resolveSigner;
645
+ private readonly driveIdFor;
646
+ private readonly undoRedoChains;
391
647
  private stopRealtime;
392
648
  private realtimeStarted;
393
649
  private realtimeGeneration;
394
650
  private realtimeErrorLogged;
395
651
  /** Whether the last socket died because the Switchboard refused its credentials. */
396
652
  private realtimeRefusedCredentials;
653
+ /** The socket write handles wait on; opened by the first stage wait. */
654
+ private jobSocket;
655
+ /** Set once the `jobChanges` subscription failed; stage waits then only poll. */
656
+ private jobRealtimeBroken;
657
+ /** Set once the Switchboard refused the `document` query's `consistency` argument. */
658
+ private consistencyUnsupported;
659
+ private readonly driveNodes;
660
+ /**
661
+ * The read half: the reads the hooks make. Every method is this client's
662
+ * own; nothing that writes is reachable from it.
663
+ */
664
+ readonly read: GraphQLReactorReadClient;
665
+ /**
666
+ * The write half. `execute` submits through `executeAsync` and hands back a
667
+ * handle whose `written` and `readable` resolve from `jobStatus`, woken by
668
+ * the `jobChanges` subscription when realtime is on, and whose `document()`
669
+ * runs the `document` query bounded by the receipt's token. `create` and
670
+ * `deleteDocument` have no asynchronous mutation: they run the synchronous
671
+ * ones and hand back a settled handle.
672
+ */
673
+ readonly write: IReactorBrowserWriteClient;
397
674
  constructor(options: GraphQLReactorClientOptions);
398
- get<TDocument extends PHDocument>(identifier: string, view?: ViewFilter, signal?: AbortSignal): Promise<TDocument>;
675
+ /**
676
+ * The Switchboard's drive node queries as a node source, for every drive
677
+ * type. `read.drives` answers from it.
678
+ */
679
+ nodeSource(): IDriveNodeSource;
680
+ /**
681
+ * Reads a document. With a consistency token that names any coordinate, the
682
+ * Switchboard waits until its read models hold them; one without the
683
+ * `document` query's `consistency` argument is read without it, which after
684
+ * a write's `readable` stage still sees the write on a single node.
685
+ */
686
+ get<TDocument extends PHDocument>(identifier: string, view?: ViewFilter, signal?: AbortSignal, consistencyToken?: ConsistencyToken): Promise<TDocument>;
687
+ /**
688
+ * Reads documents by id, in the order given; throws if any is missing. Each
689
+ * chunk of {@link GET_MANY_CHUNK_SIZE} ids is one request holding an aliased
690
+ * `document` field per id, with the selection and arguments `get` sends.
691
+ */
692
+ getMany<TDocument extends PHDocument>(documentIds: string[], view?: ViewFilter, signal?: AbortSignal, consistencyToken?: ConsistencyToken): Promise<TDocument[]>;
693
+ /** One chunk of `getMany`, with the `consistency` argument while the Switchboard accepts it. */
694
+ private getDocumentChunk;
695
+ private runGetDocuments;
696
+ /**
697
+ * Whether the Switchboard would serve the document to this client's caller,
698
+ * from its `documentServed` query: the same read gate `find` passes. Absent
699
+ * or withheld is `false`; a failure to decide throws.
700
+ *
701
+ * A point-in-time view throws {@link GraphQLOperationNotSupportedError}, as
702
+ * does a Switchboard without the query.
703
+ */
704
+ isServed(identifier: string, view?: ViewFilter, signal?: AbortSignal): Promise<boolean>;
399
705
  getOperations(documentIdentifier: string, view?: ViewFilter, filter?: OperationFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
706
+ /**
707
+ * Filters documents by criteria over the Switchboard's `findDocuments` query.
708
+ *
709
+ * The query filters by `type` and `parentId` only, at head. A search naming
710
+ * `ids` or `slugs` (present, whatever its length) and a point-in-time view are
711
+ * each by-contract limitations the query cannot express -- running it anyway
712
+ * would return every document instead of the named ones, or head instead of
713
+ * the asked-for revision, a silently wrong answer. {@link findIsServableOverGraphQL}
714
+ * is the single predicate that decides this, and an unservable `find` throws
715
+ * {@link GraphQLOperationNotSupportedError}. Drive enumeration itself filters
716
+ * by `type` at head, which is served.
717
+ */
718
+ find<TDocument extends PHDocument = PHDocument>(search: SearchFilter, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<TDocument>>;
719
+ getOutgoingRelationships(sourceIdentifier: string, relationshipType: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
720
+ getIncomingRelationships(targetIdentifier: string, relationshipType: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
721
+ getOutgoingRelationshipEdges(sourceIdentifier: string, relationshipType?: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
722
+ getIncomingRelationshipEdges(targetIdentifier: string, relationshipType?: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
400
723
  create<TDocument extends PHDocument = PHDocument>(document: PHDocument, parentIdentifier?: string, signal?: AbortSignal): Promise<TDocument>;
401
724
  /**
402
725
  * Pushes actions to the Switchboard and returns the updated document.
@@ -416,6 +739,101 @@ declare class GraphQLReactorClient implements IReactorBrowserClient$1 {
416
739
  * request. Declaring it would suggest a per-call choice that does not exist.
417
740
  */
418
741
  execute<TDocument extends PHDocument>(documentIdentifier: string, branch: string, actions: Action[], signal?: AbortSignal): Promise<TDocument>;
742
+ /**
743
+ * What `execute` writes, without waiting: returns the job once the Switchboard
744
+ * holds it, so a write slower than one request's deadline still lands and is
745
+ * reported. It is announced as the write half's `execute` announces it.
746
+ */
747
+ executeAsync(documentIdentifier: string, branch: string, actions: Action[], signal?: AbortSignal): Promise<JobInfo>;
748
+ /**
749
+ * Undoes the last applied operation of `scope` under this client's own
750
+ * signature: UNDO below base-reducer 3; on it, a RETRACT of the target the
751
+ * Switchboard resolves with {@link undoRedoTargets}. One at a time per
752
+ * document, scope and branch. A stale target is refused, not re-resolved.
753
+ */
754
+ undo<TDocument extends PHDocument = PHDocument>(documentIdentifier: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<TDocument>;
755
+ /** Redoes the last undo of `scope`; see {@link undo}. */
756
+ redo<TDocument extends PHDocument = PHDocument>(documentIdentifier: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<TDocument>;
757
+ /** Exact on base-reducer 3, from the targets the Switchboard resolves. */
758
+ undoRedoAvailability(documentIdentifier: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<UndoRedoAvailability>;
759
+ /**
760
+ * The rows a base-reducer 3 undo and redo would retract, resolved by the
761
+ * Switchboard as the caller. A Switchboard without the query is refused
762
+ * with {@link GraphQLOperationNotSupportedError}. `view.subject` is not
763
+ * sent: the Switchboard reads the caller from the bearer.
764
+ */
765
+ undoRedoTargets(documentIdentifier: string, scope?: string, view?: ViewFilter, signal?: AbortSignal): Promise<UndoRedoTargets>;
766
+ private undoOrRedo;
767
+ /** An older Switchboard serves no header versions; then CREATE_DOCUMENT names them, else it is 1. */
768
+ private undoCapabilities;
769
+ /**
770
+ * Runs multiple mutation jobs in dependency order over the Switchboard's
771
+ * `executeBatch` mutation and waits for all to settle, returning the result
772
+ * shaped like `IReactor.executeBatch`'s so the reference `DriveClient`
773
+ * consumes it unchanged.
774
+ *
775
+ * Not atomic: each job commits on its own and a failed job still releases
776
+ * its dependents. A FAILED job throws {@link BatchJobFailedError}, naming the
777
+ * first failed plan key and carrying every job's final state.
778
+ *
779
+ * Each job's actions are signed independently for the job's own
780
+ * `(documentId, branch)` target -- the per-action signing the reactor's own
781
+ * `signActions` does, not the batch state-prediction `execute` uses for a
782
+ * multi-action push. A drive job such as `addFile`'s is `CREATE_DOCUMENT` +
783
+ * `UPGRADE_DOCUMENT` + `ADD_RELATIONSHIP`, which the prediction path rejects
784
+ * outright and which has no fetchable baseline to stamp against. The reactor
785
+ * records but does not verify the stamped previous-state head, so signing
786
+ * each action bare is exactly what the in-process `DriveClient` relies on.
787
+ *
788
+ * The mutation is synchronous server-side: a job it returns is already
789
+ * settled, so {@link waitForJob} resolves from it without polling.
790
+ */
791
+ executeBatch(request: BatchExecutionRequest, signal?: AbortSignal): Promise<BatchExecutionResult>;
792
+ /** The job as `jobStatus` reports it now; `undefined` when it reports none. */
793
+ getJob(jobId: string, signal?: AbortSignal): Promise<JobInfo | undefined>;
794
+ /** The job as `jobStatus` reports it now; throws when it reports none. */
795
+ getJobStatus(jobId: string, signal?: AbortSignal): Promise<JobInfo>;
796
+ /** Polls `jobStatus` until the job is READ_READY or FAILED. */
797
+ waitForJob(jobOrId: string | JobInfo, signal?: AbortSignal): Promise<JobInfo>;
798
+ /** See {@link readCreateSignaturePolicy}. */
799
+ getCreateSignaturePolicy(): Promise<SignaturePolicy>;
800
+ /** See {@link readCreateProtocolVersions}; fitted to `documentModels`. */
801
+ getCreateProtocolVersions(options: CreateProtocolVersionsOptions, signal?: AbortSignal): Promise<ProtocolVersions>;
802
+ /** See {@link IReactorClient.newDocument}; the module comes from `documentModels`. */
803
+ newDocument<TDocument extends PHDocument = PHDocument>(documentType: string, options?: NewDocumentOptions, signal?: AbortSignal): Promise<TDocument>;
804
+ /**
805
+ * Sets or, with `null`, clears the preferred editor as a client-signed
806
+ * action, as the in-process client does.
807
+ */
808
+ setPreferredEditor(documentIdentifier: string, preferredEditor: string | null, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
809
+ /** The `Drive-Id` header for a call: the client's own proof, else the hook's. */
810
+ private driveIdHeaders;
811
+ /**
812
+ * Emits the changes the batch's settled jobs made, as `create` and `execute`
813
+ * do, so a cache is invalidated without a realtime socket. The documents a
814
+ * job wrote to are its own and those its consistency token names.
815
+ */
816
+ private announceBatch;
817
+ /**
818
+ * The id a job's actions are signed for: a signature covers the document id,
819
+ * and the server resolves a slug before verifying. A document created by this
820
+ * job or an earlier one is named by its id. When the server has no such
821
+ * document the identifier is used as given, and the server decides; any
822
+ * other failure to read it throws, so nothing is signed for a slug.
823
+ */
824
+ private batchWriteTarget;
825
+ /**
826
+ * Signs one batch job's actions for the job's own log.
827
+ *
828
+ * Each action is signed on its own for `(documentId, branch)`, the same
829
+ * per-action signing the reactor's `signActions` does: no state prediction
830
+ * across the job, so a job carrying a `CREATE_DOCUMENT` the push-prediction
831
+ * path rejects still signs. An action already signed under a key is left
832
+ * as it is: the reference `DriveClient` signs its jobs before handing them
833
+ * here. With no signer the actions pass through unsigned, matching
834
+ * {@link execute}.
835
+ */
836
+ private signBatchJobActions;
419
837
  /**
420
838
  * Deletes a document and announces it as a `Deleted` event.
421
839
  *
@@ -490,6 +908,53 @@ declare class GraphQLReactorClient implements IReactorBrowserClient$1 {
490
908
  * `gql` document or a string and name the result type at the call site.
491
909
  */
492
910
  request<TResult = unknown, TVariables extends Variables = Variables>(document: TypedGraphQLDocument<TResult, TVariables> | string, variables?: TVariables, options?: GraphQLRequestOptions): Promise<TResult>;
911
+ /**
912
+ * Shapes a document result page into the reactor's {@link PagedResults}.
913
+ *
914
+ * The items carry the same `PHDocumentFields` fragment as `get`, so the same
915
+ * adapter rebuilds each one. `hasNextPage` gates the cursor exactly as
916
+ * `getOperations` does: no cursor means no `next`.
917
+ */
918
+ private toDocumentResults;
919
+ /**
920
+ * Shapes a relationship-edge result page into the reactor's
921
+ * {@link PagedResults}, restoring each edge's `Date` fields.
922
+ */
923
+ private toRelationshipResults;
924
+ /**
925
+ * The write half's `execute`: signs as the facade's `execute` does, submits
926
+ * through `executeAsync` and returns once the job is accepted. When anyone
927
+ * subscribes, the document is read back once the job is readable and
928
+ * announced as `Updated`, as the facade's `execute` announces it; the handle
929
+ * shares that read with its own `document()`.
930
+ */
931
+ private submitExecute;
932
+ /** The write half's `create`: the synchronous mutation, a settled handle. */
933
+ private submitCreate;
934
+ /** The write half's `deleteDocument`: the synchronous mutation, a settled handle. */
935
+ private submitDeleteDocument;
936
+ /** Reads a write's document back, bounded by its receipt's token. */
937
+ private handleReader;
938
+ /** Announces a write's document as `Updated` once it is readable. */
939
+ private announceWrite;
940
+ /**
941
+ * Waits for a job to settle a stage, resolving with a FAILED job too. Polls
942
+ * `jobStatus` with a doubling interval; with realtime on, a `jobChanges`
943
+ * event for the job wakes the wait early and the interval is only a safety
944
+ * net. A failed subscription is logged once and the wait keeps polling.
945
+ */
946
+ private waitForStage;
947
+ /**
948
+ * Subscribes to one job's `jobChanges` when realtime is on and the
949
+ * subscription has not failed before. Returns the stop function, or
950
+ * undefined when nothing was subscribed.
951
+ */
952
+ private watchJob;
953
+ /**
954
+ * The `document` query with the `consistency` argument, or without it once
955
+ * the Switchboard has refused the argument.
956
+ */
957
+ private getDocumentAtConsistency;
493
958
  /**
494
959
  * Opens the realtime socket on the first subscriber.
495
960
  *
@@ -555,6 +1020,8 @@ declare class GraphQLReactorClient implements IReactorBrowserClient$1 {
555
1020
  */
556
1021
  private emitChange;
557
1022
  }
1023
+ /** {@link GraphQLReactorClient.nodeSource}, as a function. */
1024
+ declare function createGraphQLDriveNodeSource(client: GraphQLReactorClient): IDriveNodeSource;
558
1025
  /**
559
1026
  * Whether a value is a {@link GraphQLReactorClient}, including one built by
560
1027
  * another copy of this module.
@@ -571,6 +1038,18 @@ declare function isGraphQLReactorClient(client: unknown): client is GraphQLReact
571
1038
  * argument, so silently returning the head state would be wrong.
572
1039
  */
573
1040
  declare function viewFilterInputFromViewFilter(view?: ViewFilter): ViewFilterInput | undefined;
1041
+ /**
1042
+ * The single source of truth for whether the Switchboard `findDocuments` query
1043
+ * can serve a `find`. It is servable iff the search names neither `ids` nor
1044
+ * `slugs` (present, regardless of length) AND the view is not point-in-time:
1045
+ * each is a by-contract limitation of a surface that filters only by
1046
+ * `type`/`parentId` at head. Exported so a caller can route around an
1047
+ * unservable search instead of catching the error `find` throws for it.
1048
+ */
1049
+ declare function findIsServableOverGraphQL(search: SearchFilter, view?: ViewFilter): boolean;
1050
+ /** Resolves the signer of the logged-in user, if there is one. */
1051
+ /** The logged-in Renown user's signer, read per call; none when nobody is. */
1052
+ declare function ambientRenownSigner(): ISigner | undefined;
574
1053
  //#endregion
575
1054
  //#region src/graphql-client/graphql-reactor-provider.d.ts
576
1055
  declare global {
@@ -589,7 +1068,8 @@ declare global {
589
1068
  */
590
1069
  declare function ensurePHEventHandlers(): void;
591
1070
  type GraphQLReactorProviderProps = {
592
- /** The Switchboard GraphQL endpoint, e.g. `http://localhost:4001/graphql`. */url: string;
1071
+ /** The Switchboard GraphQL endpoint, e.g. `http://localhost:4001/graphql`. */
1072
+ url: string;
593
1073
  /**
594
1074
  * Resolves the bearer token sent with every request, per request. Defaults to
595
1075
  * the token of the logged-in Renown user, or none when nobody is logged in.
@@ -675,15 +1155,7 @@ type GraphQLReactorProviderProps = {
675
1155
  * effect rebuilds both if it runs again on the same client - which is what a
676
1156
  * `StrictMode` mount does.
677
1157
  */
678
- declare function GraphQLReactorProvider({
679
- url,
680
- tokenProvider,
681
- subscriptionsUrl,
682
- realtime,
683
- attachmentService,
684
- documentModels,
685
- children
686
- }: GraphQLReactorProviderProps): react_jsx_runtime0.JSX.Element;
1158
+ declare function GraphQLReactorProvider({ url, tokenProvider, subscriptionsUrl, realtime, attachmentService, documentModels, children }: GraphQLReactorProviderProps): import("react/jsx-runtime").JSX.Element;
687
1159
  /**
688
1160
  * Returns the {@link GraphQLReactorClient} mounted by
689
1161
  * {@link GraphQLReactorProvider}, or `undefined` when the slot holds something
@@ -705,7 +1177,7 @@ declare function useSwitchboardClient(): GraphQLReactorClient | undefined;
705
1177
  * The operation selection of `GetDocumentOperations`, lifted into a fragment so
706
1178
  * the write path can reuse `remoteOperationToLocal` on the items it selects.
707
1179
  */
708
- declare const ReactorOperationFieldsFragmentDoc: graphql.DocumentNode;
1180
+ declare const ReactorOperationFieldsFragmentDoc: import("graphql").DocumentNode;
709
1181
  /**
710
1182
  * `mutateDocument` plus the operations the mutation produced.
711
1183
  *
@@ -727,7 +1199,7 @@ declare const ReactorOperationFieldsFragmentDoc: graphql.DocumentNode;
727
1199
  * by hand or the operations came from `main` while the actions were applied
728
1200
  * elsewhere. One variable cannot disagree with itself.
729
1201
  */
730
- declare const MutateDocumentWithOperationsDocument: graphql.DocumentNode;
1202
+ declare const MutateDocumentWithOperationsDocument: import("graphql").DocumentNode;
731
1203
  type MutateDocumentWithOperationsVariables = {
732
1204
  documentIdentifier: Scalars["String"]["input"];
733
1205
  actions: ReadonlyArray<ActionInput>;
@@ -742,6 +1214,33 @@ type MutateDocumentWithOperationsResult = {
742
1214
  } | null;
743
1215
  };
744
1216
  };
1217
+ /**
1218
+ * `document`, bounded by a consistency token: the read waits until the
1219
+ * Switchboard's read models hold every operation the token names. The
1220
+ * `consistency` argument is additive on the Switchboard; one without it refuses
1221
+ * this document, and the client falls back to the plain `GetDocument`.
1222
+ */
1223
+ declare const GetDocumentAtConsistencyDocument: import("graphql").DocumentNode;
1224
+ type GetDocumentAtConsistencyVariables = {
1225
+ identifier: Scalars["String"]["input"];
1226
+ view?: ViewFilterInput;
1227
+ consistency: {
1228
+ version: number;
1229
+ createdAtUtcIso: string;
1230
+ coordinates: ReadonlyArray<{
1231
+ documentId: string;
1232
+ scope: string;
1233
+ branch: string;
1234
+ operationIndex: number;
1235
+ }>;
1236
+ };
1237
+ };
1238
+ type GetDocumentAtConsistencyResult = {
1239
+ readonly document?: {
1240
+ readonly document: PhDocumentFieldsFragment;
1241
+ readonly childIds: ReadonlyArray<string>;
1242
+ } | null;
1243
+ };
745
1244
  //#endregion
746
1245
  //#region src/graphql-client/signing.d.ts
747
1246
  /**
@@ -761,12 +1260,12 @@ type MutateDocumentWithOperationsResult = {
761
1260
  */
762
1261
  declare function stampAction(action: Action$1, document: PHDocument$1, revision?: number): Action$1;
763
1262
  /**
764
- * Signs a stamped action, preserving any signatures it already carries.
765
- *
766
- * The signer reads `context.prevOpHash` off the action, so this must run after
767
- * {@link stampAction}.
1263
+ * Signs a stamped action for `target`, keeping any signatures it already
1264
+ * carries. The signer reads `context.prevOpHash`, so this runs after
1265
+ * {@link stampAction}. A v2 tuple covers the signer's identity, so the context
1266
+ * takes the signer's user and app even when the action named others.
768
1267
  */
769
- declare function signStampedAction(action: Action$1, signer: ISigner, signal?: AbortSignal): Promise<Action$1>;
1268
+ declare function signStampedAction(action: Action$1, signer: ISigner, target: ActionSigningTarget, signal?: AbortSignal): Promise<Action$1>;
770
1269
  /**
771
1270
  * Stamps and signs a batch of actions against one document snapshot, so every
772
1271
  * action carries the head its predecessor will leave behind.
@@ -856,13 +1355,15 @@ type DocumentChangesEventPayload = DocumentChangesSubscription["documentChanges"
856
1355
  /** The connection payload sent with the `ConnectionInit` message. */
857
1356
  type ConnectionParams = Record<string, string>;
858
1357
  type DocumentChangesSubscriptionOptions = {
859
- /** The websocket endpoint, e.g. `ws://localhost:4001/graphql/subscriptions`. */wsUrl: string;
1358
+ /** The websocket endpoint, e.g. `ws://localhost:4001/graphql/subscriptions`. */
1359
+ wsUrl: string;
860
1360
  /**
861
1361
  * Resolves the `ConnectionInit` payload. Called again on every reconnect, so
862
1362
  * a token that expired while the socket was down is refreshed on the way back
863
1363
  * up.
864
1364
  */
865
- connectionParams?: () => Promise<ConnectionParams>; /** Called once per server event. */
1365
+ connectionParams?: () => Promise<ConnectionParams>;
1366
+ /** Called once per server event. */
866
1367
  onEvent: (event: DocumentChangesEventPayload) => void;
867
1368
  /**
868
1369
  * Called when the socket gives up: the retries built into `graphql-ws` are
@@ -891,6 +1392,33 @@ declare function isAuthRefusalClose(error: unknown): boolean;
891
1392
  * socket. It is safe to call more than once.
892
1393
  */
893
1394
  declare function startDocumentChangesSubscription(options: DocumentChangesSubscriptionOptions): () => void;
1395
+ /** The `jobChanges` payload, exactly as the Switchboard sends it. */
1396
+ type JobChangesEventPayload = JobChangesSubscription["jobChanges"];
1397
+ /**
1398
+ * One socket carrying `jobChanges` subscriptions, one per watched job. The
1399
+ * socket opens on the first watch and closes when nothing is watched.
1400
+ */
1401
+ interface IJobChangesSocket {
1402
+ /**
1403
+ * Watches one job. `onEvent` is called per status change the Switchboard
1404
+ * reports; `onError` once if the subscription fails. Returns the stop
1405
+ * function, safe to call more than once.
1406
+ */
1407
+ watch(jobId: string, onEvent: (event: JobChangesEventPayload) => void, onError: (error: unknown) => void): () => void;
1408
+ /** Closes the socket; a later watch opens a new one. */
1409
+ dispose(): void;
1410
+ }
1411
+ type JobChangesSocketOptions = {
1412
+ /** The websocket endpoint, e.g. `ws://localhost:4001/graphql/subscriptions`. */
1413
+ wsUrl: string;
1414
+ /** Resolves the `ConnectionInit` payload, per connect. */
1415
+ connectionParams?: () => Promise<ConnectionParams>;
1416
+ };
1417
+ /**
1418
+ * Opens the socket write handles wait on. `graphql-ws` multiplexes every
1419
+ * watched job over it and closes it once the last watch stops.
1420
+ */
1421
+ declare function createJobChangesSocket(options: JobChangesSocketOptions): IJobChangesSocket;
894
1422
  /**
895
1423
  * Derives the websocket endpoint from the GraphQL http endpoint.
896
1424
  *
@@ -908,6 +1436,59 @@ declare function subscriptionsUrlFromGraphqlUrl(url: string): string;
908
1436
  */
909
1437
  declare function makeAuthConnectionParams(tokenProvider: BearerTokenProvider): () => Promise<ConnectionParams>;
910
1438
  //#endregion
1439
+ //#region src/graphql-client/switchboard-backend.d.ts
1440
+ type SwitchboardBackendDescriptor = {
1441
+ /** Router backend name; unique and stable for the router's life. */
1442
+ readonly name: string;
1443
+ /** `<origin>[/<prefix>]/graphql`. */
1444
+ readonly url: string;
1445
+ /** Resolves the bearer per request and for the realtime socket. */
1446
+ readonly tokenProvider: BearerTokenProvider;
1447
+ /** Read per push when a function; `undefined` pushes unsigned, never ambient. */
1448
+ readonly signer: ISigner | (() => ISigner | undefined) | undefined;
1449
+ /** Models for signing a batch, read per batch. */
1450
+ readonly documentModels: () => readonly DocumentModelModule$1<any>[];
1451
+ readonly realtime?: boolean;
1452
+ /** Default `"rpc"`. */
1453
+ readonly inspection?: ReactorReach["inspection"];
1454
+ /** Bound on one request, headers through body. Default 30_000. */
1455
+ readonly requestTimeoutMs?: number;
1456
+ /** Bound on a batch, which waits for its jobs. Default 120_000. */
1457
+ readonly batchRequestTimeoutMs?: number;
1458
+ /** Unset fields take {@link DEFAULT_BREAKER}; `false` never opens. */
1459
+ readonly breaker?: SwitchboardBreaker;
1460
+ /** The transport under the deadline and the breaker; {@link switchboardFetch} by default. */
1461
+ readonly fetch?: GraphQLFetch;
1462
+ };
1463
+ declare const DEFAULT_REQUEST_TIMEOUT_MS = 30000;
1464
+ declare const DEFAULT_BATCH_REQUEST_TIMEOUT_MS = 120000;
1465
+ declare const DEFAULT_BREAKER: Readonly<{
1466
+ failures: 3;
1467
+ openMs: 30000;
1468
+ }>;
1469
+ /** After `failures` failed requests in a row, send nothing for `openMs`. */
1470
+ type SwitchboardBreaker = false | {
1471
+ readonly failures?: number;
1472
+ readonly openMs?: number;
1473
+ };
1474
+ type SwitchboardBackend = {
1475
+ /** reach `{hosting: "remote", inspection}`; `refusesMisroutes: false`. */
1476
+ readonly config: RoutableBackendConfig;
1477
+ /** Reopens the realtime socket on the new credentials. */
1478
+ notifyCredentialsChanged(): void;
1479
+ /** Closes the realtime socket. */
1480
+ dispose(): void;
1481
+ };
1482
+ /** The Switchboard's circuit is open: nothing was sent. */
1483
+ declare class SwitchboardUnreachableError extends Error {
1484
+ readonly backend: string;
1485
+ readonly retryAt: number;
1486
+ readonly name = "SwitchboardUnreachableError";
1487
+ constructor(backend: string, retryAt: number);
1488
+ }
1489
+ /** A Switchboard as a router backend; members GraphQL cannot serve are absent. */
1490
+ declare function createSwitchboardBackend(descriptor: SwitchboardBackendDescriptor): SwitchboardBackend;
1491
+ //#endregion
911
1492
  //#region src/hooks/document-cache.d.ts
912
1493
  /** Returns all documents in the reactor. */
913
1494
  declare const useDocumentCache: UsePHGlobalValue$1<IDocumentCache>;
@@ -938,6 +1519,8 @@ declare function useDocument(id: string | null | undefined): PHDocument$1 | unde
938
1519
  * - isPending: Whether the document is currently loading
939
1520
  * - error: Any error that occurred during loading (e.g., document not found)
940
1521
  * - reload: Function to force a refetch, or undefined when no id is supplied
1522
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
1523
+ * - refetchError: The last refetch failure that kept the loaded document
941
1524
  */
942
1525
  declare function useDocumentSafe(id: string | null | undefined): {
943
1526
  readonly status: "initial";
@@ -945,24 +1528,32 @@ declare function useDocumentSafe(id: string | null | undefined): {
945
1528
  readonly error: undefined;
946
1529
  readonly data: undefined;
947
1530
  readonly reload: undefined;
1531
+ readonly isRefetching: false;
1532
+ readonly refetchError: undefined;
948
1533
  } | {
949
- readonly reload: () => Promise<PHDocument$1>;
950
1534
  readonly status: "pending";
951
1535
  readonly isPending: true;
952
1536
  readonly error: undefined;
953
1537
  readonly data: undefined;
954
- } | {
955
1538
  readonly reload: () => Promise<PHDocument$1>;
1539
+ readonly isRefetching: boolean;
1540
+ readonly refetchError: unknown;
1541
+ } | {
956
1542
  readonly status: "success";
957
1543
  readonly isPending: false;
958
1544
  readonly error: undefined;
959
1545
  readonly data: PHDocument$1;
960
- } | {
961
1546
  readonly reload: () => Promise<PHDocument$1>;
1547
+ readonly isRefetching: boolean;
1548
+ readonly refetchError: unknown;
1549
+ } | {
962
1550
  readonly status: "error";
963
1551
  readonly isPending: false;
964
1552
  readonly error: unknown;
965
1553
  readonly data: undefined;
1554
+ readonly reload: () => Promise<PHDocument$1>;
1555
+ readonly isRefetching: boolean;
1556
+ readonly refetchError: unknown;
966
1557
  };
967
1558
  /**
968
1559
  * Retrieves multiple documents from the reactor using React Suspense.
@@ -997,6 +1588,8 @@ declare function useGetDocuments(): (ids: string[]) => Promise<PHDocument$1[]>;
997
1588
  * - isPending: Boolean indicating if the document is currently loading
998
1589
  * - error: Any error that occurred during loading
999
1590
  * - reload: Function to force reload the document from cache
1591
+ * - isRefetching: A loaded document is being refetched; `data` is the loaded one
1592
+ * - refetchError: The last refetch failure that kept the loaded document
1000
1593
  */
1001
1594
  declare function useGetDocumentAsync(id: string | null | undefined): {
1002
1595
  readonly status: "initial";
@@ -1004,24 +1597,32 @@ declare function useGetDocumentAsync(id: string | null | undefined): {
1004
1597
  readonly isPending: false;
1005
1598
  readonly error: undefined;
1006
1599
  readonly reload: undefined;
1600
+ readonly isRefetching: false;
1601
+ readonly refetchError: undefined;
1007
1602
  } | {
1008
- readonly reload: () => Promise<PHDocument$1>;
1009
1603
  readonly status: "pending";
1010
1604
  readonly isPending: true;
1011
1605
  readonly error: undefined;
1012
1606
  readonly data: undefined;
1013
- } | {
1014
1607
  readonly reload: () => Promise<PHDocument$1>;
1608
+ readonly isRefetching: boolean;
1609
+ readonly refetchError: unknown;
1610
+ } | {
1015
1611
  readonly status: "success";
1016
1612
  readonly isPending: false;
1017
1613
  readonly error: undefined;
1018
1614
  readonly data: PHDocument$1;
1019
- } | {
1020
1615
  readonly reload: () => Promise<PHDocument$1>;
1616
+ readonly isRefetching: boolean;
1617
+ readonly refetchError: unknown;
1618
+ } | {
1021
1619
  readonly status: "error";
1022
1620
  readonly isPending: false;
1023
1621
  readonly error: unknown;
1024
1622
  readonly data: undefined;
1623
+ readonly reload: () => Promise<PHDocument$1>;
1624
+ readonly isRefetching: boolean;
1625
+ readonly refetchError: unknown;
1025
1626
  };
1026
1627
  //#endregion
1027
1628
  //#region src/hooks/reactor.d.ts
@@ -1033,25 +1634,44 @@ declare const setReactorClientModule: SetPHGlobalValue<BrowserReactorClientModul
1033
1634
  declare const addReactorClientModuleEventHandler: AddPHGlobalEventHandler;
1034
1635
  /** Returns the reactor client */
1035
1636
  declare const useReactorClient: UsePHGlobalValue<IReactorBrowserClient>;
1036
- /** Sets the reactor client */
1637
+ /**
1638
+ * Sets the reactor client, and `window.ph.reactor` to its read and write
1639
+ * halves. A client without halves leaves `reactor` unset.
1640
+ */
1037
1641
  declare const setReactorClient: SetPHGlobalValue<IReactorBrowserClient>;
1642
+ /** Returns the reactor client's read and write halves */
1643
+ declare const useReactorHalves: UsePHGlobalValue<ReactorBrowserHalves>;
1644
+ /** Adds an event handler for the reactor client's halves */
1645
+ declare const addReactorHalvesEventHandler: AddPHGlobalEventHandler;
1038
1646
  /** Adds an event handler for the reactor client */
1039
1647
  declare const addReactorClientEventHandler: AddPHGlobalEventHandler;
1648
+ /** Sets the client full-client actions use instead of the module's */
1649
+ declare const setFullReactorClient: SetPHGlobalValue<IReactorClient>;
1650
+ /** Adds an event handler for the full reactor client */
1651
+ declare const addFullReactorClientEventHandler: AddPHGlobalEventHandler;
1652
+ /** The client full-client actions use: the one set, else the module's. */
1653
+ declare function getFullReactorClient(): IReactorClient | undefined;
1040
1654
  declare const useSync: () => ISyncManager | undefined;
1041
- declare const useSyncList: () => _powerhousedao_reactor0.Remote[];
1655
+ declare const useSyncList: () => import("@powerhousedao/reactor").Remote[];
1042
1656
  declare const useModelRegistry: () => IDocumentModelRegistry | undefined;
1043
1657
  declare const useDatabase: () => Kysely<Database> | undefined;
1044
1658
  declare const usePGlite: () => PGlite | undefined;
1045
1659
  //#endregion
1046
1660
  //#region src/hooks/dispatch.d.ts
1047
- /**
1048
- * Returns a dispatch function for dispatching actions to a document.
1049
- * Used internally by other hooks to provide action dispatching capabilities.
1050
- * @param document - The document to dispatch actions to.
1051
- * @returns A tuple containing the document and a dispatch function.
1052
- */
1053
- type DispatchFn<TAction> = (actionOrActions: TAction[] | TAction | undefined, onErrors?: (errors: Error[]) => void, onSuccess?: (result: PHDocument$1) => void) => void;
1661
+ /** Dispatches actions.
1662
+ *
1663
+ * Once the write lands, `onErrors` runs first, with an `OperationRejectedError` per action
1664
+ * the document did not apply; it is skipped when every action applied. Then `onSuccess`
1665
+ * runs with the document and an outcome, whether or not any action was rejected:
1666
+ * `outcome.rejected` holds the same errors, and is empty only when every action applied.
1667
+ * If `onErrors` throws, `onSuccess` does not run.
1668
+ *
1669
+ * When nothing lands (no document, no reactor, a failed write), only `onErrors` runs, with why. */
1670
+ type DispatchFn<TAction> = (actionOrActions: TAction[] | TAction | undefined, onErrors?: (errors: Error[]) => void, onSuccess?: DispatchSuccessCallback) => void;
1054
1671
  type UseDispatchResult<TDocument, TAction> = readonly [TDocument | undefined, DispatchFn<TAction>];
1672
+ /** A dispatch to the document `getDocument` returns when it runs. */
1673
+ declare function createDispatch<TDocument = PHDocument$1, TAction = Action$1>(getDocument: () => TDocument | undefined): DispatchFn<TAction>;
1674
+ /** Returns the document and a dispatch to it; see `DispatchFn` for the callbacks' order. */
1055
1675
  declare function useDispatch<TDocument = PHDocument$1, TAction = Action$1>(document: TDocument | undefined): UseDispatchResult<TDocument, TAction>;
1056
1676
  //#endregion
1057
1677
  //#region src/hooks/document-model-modules.d.ts
@@ -1067,24 +1687,61 @@ declare function useDocumentModelModules(): DocumentModelModule[] | undefined;
1067
1687
  declare function useDocumentModelModuleById(id: string | null | undefined, version?: number): DocumentModelModule | undefined;
1068
1688
  //#endregion
1069
1689
  //#region src/hooks/document-operations.d.ts
1070
- type InternalState = {
1690
+ type UseDocumentOperationsOptions = {
1691
+ /**
1692
+ * Operations per page. Default 100. Applies to the next first-page load;
1693
+ * changing it while pages are already loaded has no effect until the next
1694
+ * invalidation or `refetch`.
1695
+ */
1696
+ limit?: number;
1697
+ /** Whether to fetch at all. Default true. Pass false until the operations are needed. */
1698
+ enabled?: boolean;
1699
+ };
1700
+ /** What `useDocumentOperations` returns; exported so consumers can name it. */
1701
+ type DocumentOperationsResult = {
1702
+ /** Every operation of the scope loaded so far, oldest first. */
1703
+ operations: readonly Operation$1[];
1704
+ /** A page is in flight. */
1705
+ isLoading: boolean;
1706
+ /** The last page failed. Operations loaded before it stay available. */
1707
+ error: Error | undefined;
1708
+ /** The last page reported a further page. */
1709
+ hasNextPage: boolean;
1710
+ /** Loads the next page and appends it. No-op while loading or when there is none. */
1711
+ fetchNextPage: () => void;
1712
+ /** Drops the document's cached operations and reloads from the first page. */
1713
+ refetch: () => void;
1714
+ };
1715
+ /**
1716
+ * Legacy result of `useDocumentOperations(documentId)`.
1717
+ * @deprecated Call `useDocumentOperations(documentId, scope, options)` and read `operations`. Removed in the next major.
1718
+ */
1719
+ type DocumentOperationsState = {
1071
1720
  globalOperations: Operation$1[];
1072
1721
  localOperations: Operation$1[];
1073
1722
  isLoading: boolean;
1074
1723
  error: Error | undefined;
1075
- };
1076
- /** What `useDocumentOperations` returns; exported so consumers can name it. */
1077
- type DocumentOperationsState = InternalState & {
1078
1724
  refetch: () => void;
1079
1725
  };
1726
+ /** @deprecated Pass a scope: `useDocumentOperations(documentId, "global")`. The legacy form fetches the whole global and local history eagerly. Removed in the next major. */
1727
+ declare function useDocumentOperations(documentId: string | null | undefined): DocumentOperationsState;
1080
1728
  /**
1081
- * Hook to fetch document operations via the reactor client.
1082
- * Operations are no longer auto-populated on documents and must be fetched explicitly.
1729
+ * Operation history of a document, read from the document cache and kept in
1730
+ * step with it: a change event for the document drops the cached pages and
1731
+ * the hook loads the first page again.
1732
+ *
1733
+ * Pages arrive oldest first. A view that wants the whole history calls
1734
+ * `fetchNextPage` while `hasNextPage` is true.
1083
1735
  *
1084
- * @param documentId - The document ID to fetch operations for
1085
- * @returns Object containing globalOperations, localOperations, isLoading, and error
1736
+ * An empty first page is a final result; there is no retry. When the active
1737
+ * document cache does not serve operations, the result is empty and not
1738
+ * loading.
1739
+ *
1740
+ * @param documentId - The document id, or null/undefined to skip fetching
1741
+ * @param scope - The operation scope, for example "global" or "local"
1742
+ * @param options - Page size and whether fetching is enabled
1086
1743
  */
1087
- declare function useDocumentOperations(documentId: string | null | undefined): DocumentOperationsState;
1744
+ declare function useDocumentOperations(documentId: string | null | undefined, scope: string, options?: UseDocumentOperationsOptions): DocumentOperationsResult;
1088
1745
  //#endregion
1089
1746
  //#region src/hooks/attachment-service.d.ts
1090
1747
  /** Returns the attachment service from window.ph */
@@ -1094,5 +1751,6 @@ declare const setAttachmentService: SetPHGlobalValue<IAttachmentService>;
1094
1751
  /** Registers the attachmentService window event handler */
1095
1752
  declare const addAttachmentServiceEventHandler: AddPHGlobalEventHandler;
1096
1753
  //#endregion
1097
- export { GraphQLReactorClientOptions as $, useGetDocuments as A, RemoteDocumentData as At, resolveDocumentModelModule as B, setDocumentCache as C, IRemoteClient as Ct, useDocuments as D, RemoteControllerGraphQLClient as Dt, useDocumentSafe as E, PushResult as Et, makeAuthConnectionParams as F, DocumentCache as Ft, MutateDocumentWithOperationsResult as G, signStampedAction as H, startDocumentChangesSubscription as I, addPromiseState as It, GraphQLReactorProvider as J, MutateDocumentWithOperationsVariables as K, subscriptionsUrlFromGraphqlUrl as L, readPromiseState as Lt, DocumentChangesEventPayload as M, RemoteOperationResultPage as Mt, DocumentChangesSubscriptionOptions as N, SyncStatus$1 as Nt, useGetDocument as O, RemoteControllerOptions as Ot, isAuthRefusalClose as P, TrackedAction as Pt, GraphQLReactorClient as Q, StaticPackageManager as R, addDocumentCacheEventHandler as S, GetOperationsResult as St, useDocumentCache as T, MergeHandler as Tt, stampAction as U, prepareSignedActions as V, MutateDocumentWithOperationsDocument as W, ensurePHEventHandlers as X, GraphQLReactorProviderProps as Y, useSwitchboardClient as Z, usePGlite as _, ConflictInfo as _t, useDocumentOperations as a, TypedGraphQLDocument as at, useSync as b, GetDocumentResult as bt, DispatchFn as c, BearerTokenProvider as ct, addReactorClientEventHandler as d, GetDocumentQueryFields as dt, isGraphQLReactorClient as et, addReactorClientModuleEventHandler as f, GetDocumentQueryResult as ft, useModelRegistry as g, revisionMapFromRevisionsList as gt, useDatabase as h, phDocumentFromMutation as ht, DocumentOperationsState as i, SubgraphSdkRegistry as it, ConnectionParams as j, RemoteOperation as jt, useGetDocumentAsync as k, RemoteDocumentChangeEvent as kt, UseDispatchResult as l, ambientRenownTokenProvider as lt, setReactorClientModule as m, phDocumentFromGetDocument as mt, setAttachmentService as n, GraphQLRequestOptions as nt, useDocumentModelModuleById as o, describeGraphQLDocument as ot, setReactorClient as p, RevisionsListSelection as pt, ReactorOperationFieldsFragmentDoc as q, useAttachmentService as r, SubgraphSdkFactory as rt, useDocumentModelModules as s, subgraphUrlFromGraphqlUrl as st, addAttachmentServiceEventHandler as t, viewFilterInputFromViewFilter as tt, useDispatch as u, makeAuthMiddleware as ut, useReactorClient as v, ConflictStrategy as vt, useDocument as w, IRemoteController as wt, useSyncList as x, GetDocumentWithOperationsResult as xt, useReactorClientModule as y, DocumentChangeListener as yt, packageFromDocumentModels as z };
1098
- //# sourceMappingURL=attachment-service-D3EhiAJ7.d.ts.map
1754
+ export { createJobChangesSocket as $, GetDocumentQueryFields as $t, addDocumentCacheEventHandler as A, isDocumentTypeCache as An, GraphQLRequestOptions as At, DEFAULT_BREAKER as B, switchboardFetch as Bt, useModelRegistry as C, TrackedAction as Cn, GraphQLReactorClientOptions as Ct, useReactorHalves as D, IDLE_OPERATIONS_ENTRY as Dn, findIsServableOverGraphQL as Dt, useReactorClientModule as E, IDLE_DOCUMENTS_OF_TYPE_ENTRY as En, createGraphQLDriveNodeSource as Et, useDocuments as F, subgraphUrlFromGraphqlUrl as Ft, SwitchboardUnreachableError as G, GraphQLWrongBackendError as Gt, SwitchboardBackend as H, withStreamedBodies as Ht, useGetDocument as I, GraphQLFetch as It, DocumentChangesEventPayload as J, queriesUnknownField as Jt, createSwitchboardBackend as K, JobFailedError as Kt, useGetDocumentAsync as L, globalFetch as Lt, useDocument as M, readPromiseState as Mn, SubgraphSdkRegistry as Mt, useDocumentCache as N, IDLE_REFETCH_STATE as Nn, TypedGraphQLDocument as Nt, useSync as O, IDocumentCacheReader as On, isGraphQLReactorClient as Ot, useDocumentSafe as P, dispatchActions as Pn, describeGraphQLDocument as Pt, JobChangesSocketOptions as Q, toLegacyNode as Qt, useGetDocuments as R, isDeadlineError as Rt, useDatabase as S, SyncStatus$1 as Sn, GraphQLReactorClient as St, useReactorClient as T, GET_MANY_CHUNK_SIZE as Tn, ambientRenownSigner as Tt, SwitchboardBackendDescriptor as U, BatchJobFailedError as Ut, DEFAULT_REQUEST_TIMEOUT_MS as V, withRequestDeadline as Vt, SwitchboardBreaker as W, GraphQLOperationNotSupportedError as Wt, IJobChangesSocket as X, GraphQLDriveNodeSource as Xt, DocumentChangesSubscriptionOptions as Y, DriveNodeQueries as Yt, JobChangesEventPayload as Z, GraphQLDriveReadClient as Zt, addReactorHalvesEventHandler as _, RemoteControllerOptions as _n, GraphQLReactorProvider as _t, DocumentOperationsState as a, revisionMapFromRevisionsList as an, packageFromDocumentModels as at, setReactorClient as b, RemoteOperation as bn, useSwitchboardClient as bt, useDocumentModelModuleById as c, DocumentChangeListener as cn, signStampedAction as ct, UseDispatchResult as d, GetOperationsResult as dn, GetDocumentAtConsistencyResult as dt, GetDocumentQueryResult as en, isAuthRefusalClose as et, createDispatch as f, IRemoteClient as fn, GetDocumentAtConsistencyVariables as ft, addReactorClientModuleEventHandler as g, RemoteControllerGraphQLClient as gn, ReactorOperationFieldsFragmentDoc as gt, addReactorClientEventHandler as h, PushResult as hn, MutateDocumentWithOperationsVariables as ht, DocumentOperationsResult as i, phDocumentFromMutation as in, StaticPackageManager as it, setDocumentCache as j, isOperationCache as jn, SubgraphSdkFactory as jt, useSyncList as k, addPromiseState as kn, viewFilterInputFromViewFilter as kt, useDocumentModelModules as l, GetDocumentResult as ln, stampAction as lt, addFullReactorClientEventHandler as m, MergeHandler as mn, MutateDocumentWithOperationsResult as mt, setAttachmentService as n, isoStringFromDateTime as nn, startDocumentChangesSubscription as nt, UseDocumentOperationsOptions as o, ConflictInfo as on, resolveDocumentModelModule as ot, useDispatch as p, IRemoteController as pn, MutateDocumentWithOperationsDocument as pt, ConnectionParams as q, queriesUnknownArgument as qt, useAttachmentService as r, phDocumentFromGetDocument as rn, subscriptionsUrlFromGraphqlUrl as rt, useDocumentOperations as s, ConflictStrategy as sn, prepareSignedActions as st, addAttachmentServiceEventHandler as t, RevisionsListSelection as tn, makeAuthConnectionParams as tt, DispatchFn as u, GetDocumentWithOperationsResult as un, GetDocumentAtConsistencyDocument as ut, getFullReactorClient as v, RemoteDocumentChangeEvent as vn, GraphQLReactorProviderProps as vt, usePGlite as w, DocumentCache as wn, GraphQLReactorReadClient as wt, setReactorClientModule as x, RemoteOperationResultPage as xn, DriveIdCall as xt, setFullReactorClient as y, RemoteDocumentData as yn, ensurePHEventHandlers as yt, DEFAULT_BATCH_REQUEST_TIMEOUT_MS as z, isNodeFetch as zt };
1755
+ export {};
1756
+ //# sourceMappingURL=attachment-service-10Qn5nIw.d.ts.map