@powerhousedao/reactor-browser 6.2.3 → 6.3.0-dev.10

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 (87) hide show
  1. package/dist/{attachment-service-But1Xljo.d.ts → attachment-service-B-AmTrs2.d.ts} +605 -56
  2. package/dist/attachment-service-B-AmTrs2.d.ts.map +1 -0
  3. package/dist/auth-DRbzRdeC.d.ts +32 -0
  4. package/dist/auth-DRbzRdeC.d.ts.map +1 -0
  5. package/dist/{client-BiJAJ9dW.js → client-BFnMV-EO.js} +39 -22
  6. package/dist/client-BFnMV-EO.js.map +1 -0
  7. package/dist/{client-CngU4mtn.d.ts → client-BP0hXjqq.d.ts} +3 -2
  8. package/dist/client-BP0hXjqq.d.ts.map +1 -0
  9. package/dist/client-wwavHFfs.js +135 -0
  10. package/dist/client-wwavHFfs.js.map +1 -0
  11. package/dist/{dispatch-qRXS70fh.js → dispatch-Cylwl2Dk.js} +363 -44
  12. package/dist/dispatch-Cylwl2Dk.js.map +1 -0
  13. package/dist/{document-by-id-B_8DA4yZ.js → document-by-id-DdvqanGR.js} +2 -2
  14. package/dist/{document-by-id-B_8DA4yZ.js.map → document-by-id-DdvqanGR.js.map} +1 -1
  15. package/dist/document-model-modules-BG-61uke.js +710 -0
  16. package/dist/document-model-modules-BG-61uke.js.map +1 -0
  17. package/dist/{document-operations-Bt-1-ThH.js → document-operations-DRMMwmGZ.js} +2160 -181
  18. package/dist/document-operations-DRMMwmGZ.js.map +1 -0
  19. package/dist/global-iARBhxNI.d.ts +612 -0
  20. package/dist/global-iARBhxNI.d.ts.map +1 -0
  21. package/dist/{index-BABMK8cO.d.ts → index-CNS_9THu.d.ts} +14 -4
  22. package/dist/index-CNS_9THu.d.ts.map +1 -0
  23. package/dist/index.d.ts +560 -79
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +790 -317
  26. package/dist/index.js.map +1 -1
  27. package/dist/inspector-proxy-DODqs15F.d.ts +25 -0
  28. package/dist/inspector-proxy-DODqs15F.d.ts.map +1 -0
  29. package/dist/make-ph-event-functions-B5GU5xcR.js +180 -0
  30. package/dist/make-ph-event-functions-B5GU5xcR.js.map +1 -0
  31. package/dist/{relational-ChC_AWAK.js → relational-DZuyKp2y.js} +65 -5
  32. package/dist/relational-DZuyKp2y.js.map +1 -0
  33. package/dist/{renown-C9pYZRqf.js → renown-B3MUaiq7.js} +56 -25
  34. package/dist/renown-B3MUaiq7.js.map +1 -0
  35. package/dist/renown-CBoTdGrg.js +394 -0
  36. package/dist/renown-CBoTdGrg.js.map +1 -0
  37. package/dist/{client-VV9M73s_.js → schema-B5lftDPf.js} +295 -195
  38. package/dist/schema-B5lftDPf.js.map +1 -0
  39. package/dist/{types-B7-_l_wE.d.ts → schema-C6ECceaN.d.ts} +272 -82
  40. package/dist/schema-C6ECceaN.d.ts.map +1 -0
  41. package/dist/src/ai/index.d.ts +269 -24
  42. package/dist/src/ai/index.d.ts.map +1 -1
  43. package/dist/src/ai/index.js +1028 -168
  44. package/dist/src/ai/index.js.map +1 -1
  45. package/dist/src/analytics/index.js +3 -3
  46. package/dist/src/graphql/client.d.ts +2 -2
  47. package/dist/src/graphql/client.js +1 -1
  48. package/dist/src/graphql-client/entry.d.ts +6 -4
  49. package/dist/src/graphql-client/entry.js +4 -4
  50. package/dist/src/relational/index.d.ts +8 -1
  51. package/dist/src/relational/index.d.ts.map +1 -1
  52. package/dist/src/relational/index.js +1 -1
  53. package/dist/src/renown/index.d.ts +2 -2
  54. package/dist/src/renown/index.js +3 -3
  55. package/dist/src/rpc/index.d.ts +201 -144
  56. package/dist/src/rpc/index.d.ts.map +1 -1
  57. package/dist/src/rpc/index.js +562 -634
  58. package/dist/src/rpc/index.js.map +1 -1
  59. package/dist/switchboard-directory-vH6qtkh-.js +435 -0
  60. package/dist/switchboard-directory-vH6qtkh-.js.map +1 -0
  61. package/dist/switchboards-D-_JBUbF.d.ts +75 -0
  62. package/dist/switchboards-D-_JBUbF.d.ts.map +1 -0
  63. package/dist/types-BWx6FPO4.d.ts +63 -0
  64. package/dist/types-BWx6FPO4.d.ts.map +1 -0
  65. package/package.json +19 -17
  66. package/dist/attachment-service-But1Xljo.d.ts.map +0 -1
  67. package/dist/client-BiJAJ9dW.js.map +0 -1
  68. package/dist/client-CngU4mtn.d.ts.map +0 -1
  69. package/dist/client-VV9M73s_.js.map +0 -1
  70. package/dist/dispatch-qRXS70fh.js.map +0 -1
  71. package/dist/document-model-modules-D6I-UUXq.js +0 -386
  72. package/dist/document-model-modules-D6I-UUXq.js.map +0 -1
  73. package/dist/document-operations-Bt-1-ThH.js.map +0 -1
  74. package/dist/global-fql2bmb0.d.ts +0 -438
  75. package/dist/global-fql2bmb0.d.ts.map +0 -1
  76. package/dist/index-BABMK8cO.d.ts.map +0 -1
  77. package/dist/inspector-proxy-DCowaeeH.d.ts +0 -264
  78. package/dist/inspector-proxy-DCowaeeH.d.ts.map +0 -1
  79. package/dist/make-ph-event-functions-FzpvQtj6.js +0 -53
  80. package/dist/make-ph-event-functions-FzpvQtj6.js.map +0 -1
  81. package/dist/relational-ChC_AWAK.js.map +0 -1
  82. package/dist/renown-C9pYZRqf.js.map +0 -1
  83. package/dist/renown-Def5iO8k.js +0 -97
  84. package/dist/renown-Def5iO8k.js.map +0 -1
  85. package/dist/switchboard-CFyD_5_e.js +0 -323
  86. package/dist/switchboard-CFyD_5_e.js.map +0 -1
  87. package/dist/types-B7-_l_wE.d.ts.map +0 -1
@@ -1,37 +1,80 @@
1
- import { a as PHGlobal$1, at as DocumentRefetchState, b as IPackagesListener, ct as IOperationCache, d as UsePHGlobalValue$1, dt as PromiseWithState, lt as OperationsCacheEntry, rt as IReactorBrowserClient$1, st as IDocumentCache, u as SetPHGlobalValue$1, ut as PromiseState, v as IPackageListerUnsubscribe, x as PackageManagerInstallResult, y as IPackageManager } from "./global-fql2bmb0.js";
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-C6ECceaN.js";
2
+ import { t as BearerTokenProvider } from "./auth-DRbzRdeC.js";
3
+ import { $ as IPackageManager, Gt as PromiseState, Ht as IDocumentTypeCache, Kt as PromiseWithState, Q as IPackageListerUnsubscribe, Rt as DocumentRefetchState, Ut as IOperationCache, Vt as IDocumentCache, Wt as OperationsCacheEntry, b as UsePHGlobalValue$1, et as IPackagesListener, s as PHGlobal$1, tt as PackageManagerInstallResult, v as SetPHGlobalValue$1, zt as DocumentsOfTypeEntry } from "./global-iARBhxNI.js";
4
+ import { a as IReactorBrowserReadClient, i as IReactorBrowserClient$1, o as IReactorBrowserWriteClient } from "./switchboards-D-_JBUbF.js";
2
5
  import { t as PGlite } from "./pglite-CntadC_p-DTkdF8sr.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-B7-_l_wE.js";
4
- import { Action, DocumentModelLib, DocumentModelModule, Operation, PHDocument } from "document-model";
5
- import { Database, DocumentChangeEvent, DocumentModelSource, IDocumentModelRegistry, ISyncManager, OperationFilter, PagedResults, PagingOptions, PropagationMode, SearchFilter, ViewFilter } from "@powerhousedao/reactor";
6
- import { Action as Action$1, ActionSigningTarget, DocumentModelModule as DocumentModelModule$1, DocumentOperations, ISigner, Operation as Operation$1, PHBaseState, PHDocument as PHDocument$1, PHDocumentHeader } from "@powerhousedao/shared/document-model";
6
+ import { c as ReactorGraphQLClient } from "./types-BWx6FPO4.js";
7
7
  import { ReactNode } from "react";
8
- import { GraphQLClient, Variables } from "graphql-request";
8
+ import { Action, DocumentModelLib, DocumentModelModule, Operation, PHDocument } from "document-model";
9
+ 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";
10
+ 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";
11
+ import { Node } from "@powerhousedao/shared/document-drive";
9
12
  import { DocumentNode } from "graphql";
13
+ import { GraphQLClient, Variables } from "graphql-request";
10
14
  import { IAttachmentService } from "@powerhousedao/reactor-attachments/client";
11
15
  import { Kysely } from "kysely";
12
- import { AddPHGlobalEventHandler, BrowserReactorClientModule, IReactorBrowserClient, SetPHGlobalValue, UsePHGlobalValue, WorkerReactorClientModule } from "@powerhousedao/reactor-browser";
16
+ import { AddPHGlobalEventHandler, BrowserReactorClientModule, IReactorBrowserClient, ReactorBrowserHalves, SetPHGlobalValue, UsePHGlobalValue, WorkerReactorClientModule } from "@powerhousedao/reactor-browser";
13
17
  import { RegistryPackageSource } from "@powerhousedao/shared";
18
+ import { ReactorReach, RoutableBackendConfig } from "@powerhousedao/reactor-router";
19
+ //#region src/actions/dispatch.d.ts
20
+ /** Called once the write lands; `outcome.rejected` is empty when every action applied. */
21
+ type DispatchSuccessCallback = (result: PHDocument$1, outcome: DispatchOutcome) => void;
22
+ /**
23
+ * Dispatches actions to a document.
24
+ * @param actionOrActions - The action or actions to dispatch.
25
+ * @param document - The document to dispatch actions to.
26
+ * @param onErrors - Callback invoked with an `OperationRejectedError` for each action the
27
+ * document did not apply, or with why nothing was dispatched. Runs before `onSuccess`.
28
+ * @param onSuccess - Callback invoked with the updated document once the write lands, after
29
+ * `onErrors` and also when an action was rejected; `outcome.rejected` lists the rejections.
30
+ * @returns The updated document, or undefined if the dispatch failed.
31
+ */
32
+ 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>;
33
+ /**
34
+ * Dispatches actions to a document.
35
+ * @param actionOrActions - The action or actions to dispatch.
36
+ * @param documentId - The ID of the document to dispatch actions to.
37
+ * @param onErrors - Callback invoked with an `OperationRejectedError` for each action the
38
+ * document did not apply. Runs before `onSuccess`.
39
+ * @param onSuccess - Callback invoked with the updated document once the write lands, after
40
+ * `onErrors` and also when an action was rejected; `outcome.rejected` lists the rejections.
41
+ * @returns The updated document, or undefined if the dispatch failed.
42
+ */
43
+ declare function dispatchActions(actionOrActions: Action$1[] | Action$1 | undefined, documentId: string, onErrors?: (errors: Error[]) => void, onSuccess?: DispatchSuccessCallback): Promise<PHDocument$1 | undefined>;
44
+ //#endregion
14
45
  //#region src/document-refetcher.d.ts
15
46
  /** The refetch snapshot of a document with nothing in flight and no kept failure. */
16
47
  declare const IDLE_REFETCH_STATE: DocumentRefetchState;
17
48
  //#endregion
18
49
  //#region src/document-cache.d.ts
50
+ /**
51
+ * The reads a {@link DocumentCache} makes. `getMany` is optional: without it,
52
+ * a batch reads each uncached id with `get`.
53
+ */
54
+ interface IDocumentCacheReader extends Pick<IReactorBrowserReadClient, "get" | "find" | "getOperations" | "subscribe">, Partial<Pick<IReactorBrowserReadClient, "getMany">> {}
55
+ /** The most ids one `getMany` call is asked for. */
56
+ declare const GET_MANY_CHUNK_SIZE = 100;
19
57
  declare function addPromiseState<T>(promise: Promise<T>): PromiseWithState<T>;
20
58
  declare function readPromiseState<T>(promise: Promise<T> | PromiseWithState<T>): PromiseState<T>;
21
59
  /** The snapshot every uncached document scope reads as. One frozen object, so `useSyncExternalStore` sees a stable value. */
22
60
  declare const IDLE_OPERATIONS_ENTRY: OperationsCacheEntry;
23
61
  /** Whether a document cache also serves operation history. `GraphQLClientDocumentCache` does not. */
24
62
  declare function isOperationCache(cache: unknown): cache is IOperationCache;
63
+ /** The snapshot every unloaded type reads as, frozen so `useSyncExternalStore` sees one value. */
64
+ declare const IDLE_DOCUMENTS_OF_TYPE_ENTRY: DocumentsOfTypeEntry;
65
+ /** Whether a document cache also lists documents by type. */
66
+ declare function isDocumentTypeCache(cache: unknown): cache is IDocumentTypeCache;
25
67
  /**
26
68
  * Document cache implementation that uses the new ReactorClient API.
27
69
  *
28
- * This cache subscribes to document change events via IReactorBrowserClient.subscribe()
70
+ * This cache subscribes to document change events through the client's read half
29
71
  * and automatically updates the cache when documents are created, updated, or deleted.
72
+ * It is built over a browser client, whose `read` half it uses, or over a read
73
+ * half directly.
30
74
  * It also holds paginated operation history per document scope (see `IOperationCache`),
31
75
  * which is dropped for a document whenever a change event for it arrives.
32
76
  */
33
- declare class DocumentCache implements IDocumentCache, IOperationCache {
34
- private client;
77
+ declare class DocumentCache implements IDocumentCache, IOperationCache, IDocumentTypeCache {
35
78
  private documents;
36
79
  private batchPromises;
37
80
  private listeners;
@@ -49,8 +92,13 @@ declare class DocumentCache implements IDocumentCache, IOperationCache {
49
92
  /** In-flight controllers and the next page's cursor/limit, by document id then scope. */
50
93
  private operationRequests;
51
94
  private operationListeners;
95
+ /** Documents by type and page size, keyed by typeKey. */
96
+ private typeEntries;
97
+ private typeRequests;
98
+ private typeListeners;
52
99
  private unsubscribe;
53
- constructor(client: IReactorBrowserClient$1);
100
+ private readonly client;
101
+ constructor(client: IReactorBrowserClient$1 | IDocumentCacheReader);
54
102
  private handleDocumentChange;
55
103
  private handleDocumentDeleted;
56
104
  private handleDocumentUpdated;
@@ -63,6 +111,19 @@ declare class DocumentCache implements IDocumentCache, IOperationCache {
63
111
  get(id: string, refetch?: boolean): Promise<PHDocument$1>;
64
112
  getRefetchState(id: string): DocumentRefetchState;
65
113
  getBatch(ids: string[]): Promise<PHDocument$1[]>;
114
+ /**
115
+ * Reserves an entry for every id not yet cached and fills them from
116
+ * `getMany`, in chunks of {@link GET_MANY_CHUNK_SIZE}. Each id keeps its own
117
+ * entry, settled as `get` would settle it.
118
+ */
119
+ private loadMany;
120
+ /**
121
+ * `getMany` rejects when any id is unavailable, so a failed chunk is split
122
+ * in half and retried; a single id is read with `get`, so it settles exactly
123
+ * as a single read would.
124
+ */
125
+ private settleMany;
126
+ private settleFetched;
66
127
  subscribe(id: string | string[], callback: () => void): () => void;
67
128
  getOperationsState(documentId: string, scope: string): OperationsCacheEntry;
68
129
  loadOperations(documentId: string, scope: string, limit: number): void;
@@ -93,6 +154,17 @@ declare class DocumentCache implements IDocumentCache, IOperationCache {
93
154
  private setOperationsEntry;
94
155
  private setOperationsRequest;
95
156
  private notifyOperationListeners;
157
+ getDocumentsOfTypeState(type: string, limit: number): DocumentsOfTypeEntry;
158
+ loadDocumentsOfType(type: string, limit: number): Promise<void>;
159
+ loadMoreDocumentsOfType(type: string, limit: number): void;
160
+ subscribeDocumentsOfType(type: string, limit: number, callback: () => void): () => void;
161
+ /** Loads one page after `before` and appends it; never rejects, the entry holds the error. */
162
+ private loadTypePage;
163
+ /** Reloads every loaded page of a type a created or deleted document belongs to. */
164
+ private reloadTypesChangedBy;
165
+ private primeDocument;
166
+ private getTypeEntry;
167
+ private setTypeEntry;
96
168
  /**
97
169
  * Disposes of the cache and unsubscribes from document change events.
98
170
  */
@@ -100,7 +172,7 @@ declare class DocumentCache implements IDocumentCache, IOperationCache {
100
172
  }
101
173
  //#endregion
102
174
  //#region src/remote-controller/types.d.ts
103
- type RemoteControllerGraphQLClient = Pick<ReactorGraphQLClient, "GetDocument" | "GetDocumentWithOperations" | "GetDocumentOperations" | "MutateDocument" | "CreateDocument" | "CreateEmptyDocument" | "DeleteDocument" | "BatchGetDocumentOperations" | "BatchGetDocumentWithOperations">;
175
+ type RemoteControllerGraphQLClient = Pick<ReactorGraphQLClient, "GetDocument" | "GetDocumentWithOperations" | "GetDocumentOperations" | "MutateDocument" | "CreateDocument" | "CreateEmptyDocument" | "GetCreateDefaults" | "GetCreateProtocolVersions" | "DeleteDocument" | "BatchGetDocumentOperations" | "BatchGetDocumentWithOperations">;
104
176
  type RemoteDocumentData = PhDocumentFieldsFragment;
105
177
  type RemoteOperation = GetDocumentOperationsQuery["documentOperations"]["items"][number];
106
178
  type RemoteOperationResultPage = GetDocumentOperationsQuery["documentOperations"];
@@ -226,8 +298,8 @@ type RevisionsListSelection = GetDocumentQueryFields["revisionsList"];
226
298
  * `createPresignedHeader`: the creation signature is not fetchable over
227
299
  * GraphQL and is not part of the operation signing payload.
228
300
  *
229
- * The read path never fetches operation history, so `operations` is a map of
230
- * the document's known scopes to empty arrays.
301
+ * The read path never fetches operation history, so `operations` maps each
302
+ * scope of the document's state and revisions to an empty array.
231
303
  *
232
304
  * `branch` is the branch the document was read from. The GraphQL type does not
233
305
  * carry it, so it has to be passed back in by the caller; it defaults to the
@@ -244,34 +316,118 @@ declare function phDocumentFromGetDocument<TDocument extends PHDocument = PHDocu
244
316
  declare function phDocumentFromMutation<TDocument extends PHDocument = PHDocument>(document: GetDocumentQueryFields, operations: readonly RemoteOperation[], branch?: string): TDocument;
245
317
  /** Turns a `revisionsList` selection into the header's per-scope revision map. */
246
318
  declare function revisionMapFromRevisionsList(revisionsList: RevisionsListSelection): Record<string, number>;
319
+ /** The `DateTime` scalar deserializes as either an ISO string or a `Date`. */
320
+ declare function isoStringFromDateTime(value: string | Date): string;
247
321
  //#endregion
248
- //#region src/graphql-client/auth.d.ts
322
+ //#region src/graphql-client/drive-nodes.d.ts
323
+ /** The node queries a {@link GraphQLDriveNodeSource} runs. */
324
+ type DriveNodeQueries = Pick<Sdk, "GetDriveNodes" | "GetDriveNode" | "GetDriveDescendants">;
249
325
  /**
250
- * Resolves the bearer token to send with a request.
251
- *
252
- * Returning `undefined` (or an empty string) means "send this request
253
- * anonymously": open Switchboards must keep serving reads to logged-out users.
326
+ * The reactor subgraph's type-neutral node queries (`driveNodes`, `driveNode`,
327
+ * `driveDescendants`) as an {@link IDriveNodeSource}, so a browser reads a
328
+ * legacy drive and a reactor-drive alike. The Switchboard serves only the
329
+ * nodes the caller may read. Drive ids must be canonical ids, not slugs.
254
330
  */
255
- type BearerTokenProvider = () => Promise<string | undefined>;
331
+ declare class GraphQLDriveNodeSource implements IDriveNodeSource {
332
+ private readonly queries;
333
+ private readonly headersFor;
334
+ constructor(queries: DriveNodeQueries, headersFor?: (driveId: string) => Record<string, string> | undefined);
335
+ getNode(driveId: string, nodeId: string, signal?: AbortSignal): Promise<DriveNodeRecord | undefined>;
336
+ listChildren(driveId: string, parentFolder: string | null | undefined, paging?: PagingOptions, signal?: AbortSignal, kind?: DriveNodeKind): Promise<DriveNodePage>;
337
+ getDescendants(driveId: string, root: string, signal?: AbortSignal): Promise<DriveNodeRecord[]>;
338
+ listAll(driveId: string, signal?: AbortSignal): Promise<DriveNodeRecord[]>;
339
+ }
256
340
  /**
257
- * The default token provider: the token of the currently logged-in Renown user.
258
- *
259
- * It is deliberately resolved from `window.ph` on every call rather than
260
- * captured at construction time, so a client built before login starts sending
261
- * the token as soon as there is one.
262
- *
263
- * The token is requested WITHOUT an `aud` claim - the Switchboard verifier
264
- * rejects tokens that carry an audience.
341
+ * `read.drives` over a node source: the reactor's {@link IDriveReadClient},
342
+ * answering in the legacy `Node` shape for every drive type.
265
343
  */
266
- declare function ambientRenownTokenProvider(): Promise<string | undefined>;
344
+ declare class GraphQLDriveReadClient implements IDriveReadClient {
345
+ private readonly nodes;
346
+ constructor(nodes: IDriveNodeSource);
347
+ getNode(driveIdentifier: string, nodeId: string, signal?: AbortSignal): Promise<Node>;
348
+ listNodes(driveIdentifier: string, parentFolder?: string | null, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Node>>;
349
+ }
350
+ /** A node record in the legacy `Node` shape. */
351
+ declare function toLegacyNode(node: DriveNodeRecord): Node;
352
+ //#endregion
353
+ //#region src/graphql-client/errors.d.ts
354
+ /** A call the Switchboard GraphQL surface cannot express. */
355
+ declare class GraphQLOperationNotSupportedError extends Error {
356
+ readonly name = "GraphQLOperationNotSupportedError";
357
+ readonly operation: string;
358
+ constructor(operation: string, reason: string);
359
+ static isError(error: unknown): error is GraphQLOperationNotSupportedError;
360
+ }
267
361
  /**
268
- * Builds the SDK middleware that authenticates every request.
269
- *
270
- * The token is resolved per request and never cached, so a login, a logout or
271
- * an expiry between two calls is picked up by the next one. When no token is
272
- * available the request goes out unauthenticated.
362
+ * The Switchboard refused a request with 421 Misdirected Request: the
363
+ * `Drive-Id` it carried names a drive that Switchboard does not own.
364
+ */
365
+ declare class GraphQLWrongBackendError extends Error {
366
+ readonly name = "GraphQLWrongBackendError";
367
+ readonly status = 421;
368
+ /** The drive the Switchboard refused, or `""` when its answer names none. */
369
+ readonly driveId: string;
370
+ /** The response body, parsed when it is JSON. */
371
+ readonly payload: unknown;
372
+ constructor(driveId: string, payload: unknown, options?: ErrorOptions);
373
+ static isError(error: unknown): error is GraphQLWrongBackendError;
374
+ }
375
+ /**
376
+ * The reactor's `BatchJobFailedError`, rebuilt from a batch result; this entry
377
+ * imports the reactor for types only. The shared name lets either `isError`
378
+ * recognise it.
379
+ */
380
+ declare class BatchJobFailedError extends Error {
381
+ readonly name = "BatchJobFailedError";
382
+ readonly key: string;
383
+ readonly jobs: Readonly<Record<string, JobInfo>>;
384
+ constructor(key: string, jobs: Record<string, JobInfo>);
385
+ static isError(error: unknown): error is BatchJobFailedError;
386
+ }
387
+ /** A validation error naming root field `field` unknown: a host from before it. */
388
+ declare function queriesUnknownField(error: unknown, field: string): boolean;
389
+ /** A validation error naming `argument` unknown: a host from before it. */
390
+ declare function queriesUnknownArgument(error: unknown, argument: string): boolean;
391
+ /**
392
+ * The reactor's `JobFailedError`, rebuilt from a job the Switchboard reported
393
+ * FAILED; this entry imports the reactor for types only. A write handle's
394
+ * stage rejects with it. The message is the job error's message, as the
395
+ * reactor's is.
396
+ */
397
+ declare class JobFailedError extends Error {
398
+ readonly name = "JobFailedError";
399
+ readonly job: JobInfo;
400
+ constructor(job: JobInfo);
401
+ static isError(error: unknown): error is JobFailedError;
402
+ }
403
+ //#endregion
404
+ //#region src/graphql-client/transport.d.ts
405
+ /** The `fetch` a client's HTTP requests go through. */
406
+ type GraphQLFetch = typeof globalThis.fetch;
407
+ /** The global `fetch`, read per call so a later replacement is honoured. */
408
+ declare const globalFetch: GraphQLFetch;
409
+ /**
410
+ * Whether `fetch` here is Node's (undici), which resends a request answered
411
+ * 421 and can fail the resend of a buffered body. A page, Electron's renderer
412
+ * included, has a `document`.
413
+ */
414
+ declare function isNodeFetch(): boolean;
415
+ /**
416
+ * Sends a string body as a stream, which fetch never resends, so a 421 comes
417
+ * back as itself. Browsers keep buffered bodies: Chrome streams an upload only
418
+ * over HTTP/2.
419
+ */
420
+ declare function withStreamedBodies(inner?: GraphQLFetch): GraphQLFetch;
421
+ /** A Switchboard backend's default transport: streamed bodies under Node only. */
422
+ declare const switchboardFetch: GraphQLFetch;
423
+ /** Bounds each request, headers through body; rejects with a `TimeoutError`. */
424
+ declare function withRequestDeadline(timeoutMs: number, inner?: GraphQLFetch): GraphQLFetch;
425
+ /**
426
+ * Whether a request failed at a deadline rather than by its caller's abort:
427
+ * this transport's own (`TimeoutError`, a DOMException) or the router's probe
428
+ * deadline (`ProbeTimeoutError`, reactor-router's dispatcher.ts).
273
429
  */
274
- declare function makeAuthMiddleware(tokenProvider: BearerTokenProvider): SdkFunctionWrapper;
430
+ declare function isDeadlineError(error: unknown): boolean;
275
431
  //#endregion
276
432
  //#region src/graphql-client/subgraph.d.ts
277
433
  /**
@@ -342,8 +498,9 @@ declare function describeGraphQLDocument(document: string | DocumentNode): {
342
498
  declare class SubgraphSdkRegistry {
343
499
  private readonly url;
344
500
  private readonly middleware;
501
+ private readonly fetch;
345
502
  private readonly bindings;
346
- constructor(url: string, middleware?: SdkFunctionWrapper);
503
+ constructor(url: string, middleware?: SdkFunctionWrapper, fetch?: GraphQLFetch);
347
504
  /**
348
505
  * Returns the subgraph's SDK, building it on first use.
349
506
  *
@@ -359,6 +516,15 @@ declare class SubgraphSdkRegistry {
359
516
  }
360
517
  //#endregion
361
518
  //#region src/graphql-client/graphql-reactor-client.d.ts
519
+ /** A call the client asks {@link GraphQLReactorClientOptions.driveIdFor} about. */
520
+ type DriveIdCall = {
521
+ readonly method: "create" | "execute" | "executeBatch" | "deleteDocument" | "find";
522
+ readonly documentId?: string;
523
+ readonly parentId?: string;
524
+ readonly jobs?: readonly {
525
+ readonly documentId: string;
526
+ }[];
527
+ };
362
528
  type GraphQLReactorClientOptions = {
363
529
  /** The Switchboard GraphQL endpoint, e.g. `http://localhost:4001/graphql`. */
364
530
  url: string;
@@ -366,8 +532,9 @@ type GraphQLReactorClientOptions = {
366
532
  * A pre-built SDK to use instead of the transport derived from `url`.
367
533
  * Mainly a test seam.
368
534
  *
369
- * A client built this way carries no auth middleware: the injected SDK owns
370
- * its own transport, and therefore its own headers.
535
+ * A client built this way carries no auth middleware and no 421 mapping:
536
+ * the injected SDK owns its own transport, and therefore its own headers
537
+ * and transport errors.
371
538
  */
372
539
  graphqlClient?: ReactorGraphQLClient;
373
540
  /**
@@ -405,19 +572,43 @@ type GraphQLReactorClientOptions = {
405
572
  * `state.document.version` is here. One action needs no prediction and is
406
573
  * signed without any of this.
407
574
  *
408
- * Read once, when the client is built. Below `GraphQLReactorProvider` this
409
- * is its `documentModels` prop; a client constructed directly passes its own.
575
+ * An array is read once, when the client is built; a function is called at
576
+ * every batch, for a registry that gains models later. Below
577
+ * `GraphQLReactorProvider` this is its `documentModels` prop; a client
578
+ * constructed directly passes its own.
410
579
  */
411
- documentModels?: readonly DocumentModelModule<any>[];
580
+ documentModels?: readonly DocumentModelModule<any>[] | (() => readonly DocumentModelModule<any>[]);
412
581
  /**
413
582
  * Signs the actions this client pushes, instead of the logged-in Renown user.
414
583
  *
415
584
  * Left out - the normal case - the signer is resolved per push from
416
585
  * `window.ph.renown`, so a page signs as whoever is logged in and pushes
417
586
  * unsigned when nobody is. Set it where there is no Renown to read: tests,
418
- * scripts, and integration suites that must sign deterministically.
587
+ * scripts, and integration suites that must sign deterministically. A
588
+ * function is called per push, and pushes unsigned when it returns
589
+ * `undefined`.
419
590
  */
420
- signer?: ISigner;
591
+ signer?: ISigner | (() => ISigner | undefined);
592
+ /**
593
+ * Names the drive a call belongs to when the client cannot prove it itself,
594
+ * for its `Drive-Id` header; `undefined` sends none. Return only a drive id
595
+ * the caller knows: a Switchboard that does not own it answers 421. Where
596
+ * the client has proof of its own and the two disagree, the proof is sent.
597
+ */
598
+ driveIdFor?: (call: DriveIdCall) => string | undefined;
599
+ /**
600
+ * Bounds each HTTP request, headers through body, in milliseconds; a request
601
+ * past it rejects with a `TimeoutError`. Unset, requests are unbounded.
602
+ */
603
+ requestTimeoutMs?: number;
604
+ /**
605
+ * Bounds an `executeBatch` request in place of `requestTimeoutMs`. The
606
+ * mutation answers once its jobs are readable, and it has no form that does
607
+ * not wait, so one request lasts as long as the write does.
608
+ */
609
+ batchRequestTimeoutMs?: number;
610
+ /** The `fetch` every HTTP request goes through; the global one by default. */
611
+ fetch?: GraphQLFetch;
421
612
  };
422
613
  /**
423
614
  * The marker {@link isGraphQLReactorClient} looks for.
@@ -428,6 +619,11 @@ type GraphQLReactorClientOptions = {
428
619
  * and answers `false`. A branded property survives both.
429
620
  */
430
621
  declare const graphQLReactorClientBrand: "__powerhouseGraphQLReactorClient";
622
+ /** The read half of {@link GraphQLReactorClient}: the hooks' reads plus `drives`. */
623
+ interface GraphQLReactorReadClient extends IReactorBrowserReadClient {
624
+ /** A drive's nodes from the node queries, for every drive type. */
625
+ readonly drives: IDriveReadClient;
626
+ }
431
627
  /**
432
628
  * A light implementation of {@link IReactorBrowserClient} that talks plain
433
629
  * GraphQL to a Switchboard, with no reactor in the bundle.
@@ -439,21 +635,92 @@ declare class GraphQLReactorClient implements IReactorBrowserClient$1 {
439
635
  /** See {@link isGraphQLReactorClient}. */
440
636
  readonly [graphQLReactorClientBrand] = true;
441
637
  private readonly sdk;
638
+ /** For `executeBatch`, the one write a request waits for: see {@link batchRequestTimeoutMs}. */
639
+ private readonly batchSdk;
442
640
  private readonly subgraphs;
443
641
  private readonly listeners;
444
642
  private readonly tokenProvider;
445
643
  private readonly subscriptionsUrl;
446
644
  private readonly documentModels;
447
- private readonly signer;
645
+ private readonly resolveSigner;
646
+ private readonly driveIdFor;
647
+ private readonly undoRedoChains;
448
648
  private stopRealtime;
449
649
  private realtimeStarted;
450
650
  private realtimeGeneration;
451
651
  private realtimeErrorLogged;
452
652
  /** Whether the last socket died because the Switchboard refused its credentials. */
453
653
  private realtimeRefusedCredentials;
654
+ /** The socket write handles wait on; opened by the first stage wait. */
655
+ private jobSocket;
656
+ /** Set once the `jobChanges` subscription failed; stage waits then only poll. */
657
+ private jobRealtimeBroken;
658
+ /** Set once the Switchboard refused the `document` query's `consistency` argument. */
659
+ private consistencyUnsupported;
660
+ private readonly driveNodes;
661
+ /**
662
+ * The read half: the reads the hooks make. Every method is this client's
663
+ * own; nothing that writes is reachable from it.
664
+ */
665
+ readonly read: GraphQLReactorReadClient;
666
+ /**
667
+ * The write half. `execute` submits through `executeAsync` and hands back a
668
+ * handle whose `written` and `readable` resolve from `jobStatus`, woken by
669
+ * the `jobChanges` subscription when realtime is on, and whose `document()`
670
+ * runs the `document` query bounded by the receipt's token. `create` and
671
+ * `deleteDocument` have no asynchronous mutation: they run the synchronous
672
+ * ones and hand back a settled handle.
673
+ */
674
+ readonly write: IReactorBrowserWriteClient;
454
675
  constructor(options: GraphQLReactorClientOptions);
455
- get<TDocument extends PHDocument>(identifier: string, view?: ViewFilter, signal?: AbortSignal): Promise<TDocument>;
676
+ /**
677
+ * The Switchboard's drive node queries as a node source, for every drive
678
+ * type. `read.drives` answers from it.
679
+ */
680
+ nodeSource(): IDriveNodeSource;
681
+ /**
682
+ * Reads a document. With a consistency token that names any coordinate, the
683
+ * Switchboard waits until its read models hold them; one without the
684
+ * `document` query's `consistency` argument is read without it, which after
685
+ * a write's `readable` stage still sees the write on a single node.
686
+ */
687
+ get<TDocument extends PHDocument>(identifier: string, view?: ViewFilter, signal?: AbortSignal, consistencyToken?: ConsistencyToken): Promise<TDocument>;
688
+ /**
689
+ * Reads documents by id, in the order given; throws if any is missing. Each
690
+ * chunk of {@link GET_MANY_CHUNK_SIZE} ids is one request holding an aliased
691
+ * `document` field per id, with the selection and arguments `get` sends.
692
+ */
693
+ getMany<TDocument extends PHDocument>(documentIds: string[], view?: ViewFilter, signal?: AbortSignal, consistencyToken?: ConsistencyToken): Promise<TDocument[]>;
694
+ /** One chunk of `getMany`, with the `consistency` argument while the Switchboard accepts it. */
695
+ private getDocumentChunk;
696
+ private runGetDocuments;
697
+ /**
698
+ * Whether the Switchboard would serve the document to this client's caller,
699
+ * from its `documentServed` query: the same read gate `find` passes. Absent
700
+ * or withheld is `false`; a failure to decide throws.
701
+ *
702
+ * A point-in-time view throws {@link GraphQLOperationNotSupportedError}, as
703
+ * does a Switchboard without the query.
704
+ */
705
+ isServed(identifier: string, view?: ViewFilter, signal?: AbortSignal): Promise<boolean>;
456
706
  getOperations(documentIdentifier: string, view?: ViewFilter, filter?: OperationFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<Operation>>;
707
+ /**
708
+ * Filters documents by criteria over the Switchboard's `findDocuments` query.
709
+ *
710
+ * The query filters by `type` and `parentId` only, at head. A search naming
711
+ * `ids` or `slugs` (present, whatever its length) and a point-in-time view are
712
+ * each by-contract limitations the query cannot express -- running it anyway
713
+ * would return every document instead of the named ones, or head instead of
714
+ * the asked-for revision, a silently wrong answer. {@link findIsServableOverGraphQL}
715
+ * is the single predicate that decides this, and an unservable `find` throws
716
+ * {@link GraphQLOperationNotSupportedError}. Drive enumeration itself filters
717
+ * by `type` at head, which is served.
718
+ */
719
+ find<TDocument extends PHDocument = PHDocument>(search: SearchFilter, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<TDocument>>;
720
+ getOutgoingRelationships(sourceIdentifier: string, relationshipType: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
721
+ getIncomingRelationships(targetIdentifier: string, relationshipType: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<PHDocument>>;
722
+ getOutgoingRelationshipEdges(sourceIdentifier: string, relationshipType?: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
723
+ getIncomingRelationshipEdges(targetIdentifier: string, relationshipType?: string, view?: ViewFilter, paging?: PagingOptions, signal?: AbortSignal): Promise<PagedResults<DocumentRelationship>>;
457
724
  create<TDocument extends PHDocument = PHDocument>(document: PHDocument, parentIdentifier?: string, signal?: AbortSignal): Promise<TDocument>;
458
725
  /**
459
726
  * Pushes actions to the Switchboard and returns the updated document.
@@ -473,6 +740,101 @@ declare class GraphQLReactorClient implements IReactorBrowserClient$1 {
473
740
  * request. Declaring it would suggest a per-call choice that does not exist.
474
741
  */
475
742
  execute<TDocument extends PHDocument>(documentIdentifier: string, branch: string, actions: Action[], signal?: AbortSignal): Promise<TDocument>;
743
+ /**
744
+ * What `execute` writes, without waiting: returns the job once the Switchboard
745
+ * holds it, so a write slower than one request's deadline still lands and is
746
+ * reported. It is announced as the write half's `execute` announces it.
747
+ */
748
+ executeAsync(documentIdentifier: string, branch: string, actions: Action[], signal?: AbortSignal): Promise<JobInfo>;
749
+ /**
750
+ * Undoes the last applied operation of `scope` under this client's own
751
+ * signature: UNDO below base-reducer 3; on it, a RETRACT of the target the
752
+ * Switchboard resolves with {@link undoRedoTargets}. One at a time per
753
+ * document, scope and branch. A stale target is refused, not re-resolved.
754
+ */
755
+ undo<TDocument extends PHDocument = PHDocument>(documentIdentifier: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<TDocument>;
756
+ /** Redoes the last undo of `scope`; see {@link undo}. */
757
+ redo<TDocument extends PHDocument = PHDocument>(documentIdentifier: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<TDocument>;
758
+ /** Exact on base-reducer 3, from the targets the Switchboard resolves. */
759
+ undoRedoAvailability(documentIdentifier: string, scope?: string, branch?: string, signal?: AbortSignal): Promise<UndoRedoAvailability>;
760
+ /**
761
+ * The rows a base-reducer 3 undo and redo would retract, resolved by the
762
+ * Switchboard as the caller. A Switchboard without the query is refused
763
+ * with {@link GraphQLOperationNotSupportedError}. `view.subject` is not
764
+ * sent: the Switchboard reads the caller from the bearer.
765
+ */
766
+ undoRedoTargets(documentIdentifier: string, scope?: string, view?: ViewFilter, signal?: AbortSignal): Promise<UndoRedoTargets>;
767
+ private undoOrRedo;
768
+ /** An older Switchboard serves no header versions; then CREATE_DOCUMENT names them, else it is 1. */
769
+ private undoCapabilities;
770
+ /**
771
+ * Runs multiple mutation jobs in dependency order over the Switchboard's
772
+ * `executeBatch` mutation and waits for all to settle, returning the result
773
+ * shaped like `IReactor.executeBatch`'s so the reference `DriveClient`
774
+ * consumes it unchanged.
775
+ *
776
+ * Not atomic: each job commits on its own and a failed job still releases
777
+ * its dependents. A FAILED job throws {@link BatchJobFailedError}, naming the
778
+ * first failed plan key and carrying every job's final state.
779
+ *
780
+ * Each job's actions are signed independently for the job's own
781
+ * `(documentId, branch)` target -- the per-action signing the reactor's own
782
+ * `signActions` does, not the batch state-prediction `execute` uses for a
783
+ * multi-action push. A drive job such as `addFile`'s is `CREATE_DOCUMENT` +
784
+ * `UPGRADE_DOCUMENT` + `ADD_RELATIONSHIP`, which the prediction path rejects
785
+ * outright and which has no fetchable baseline to stamp against. The reactor
786
+ * records but does not verify the stamped previous-state head, so signing
787
+ * each action bare is exactly what the in-process `DriveClient` relies on.
788
+ *
789
+ * The mutation is synchronous server-side: a job it returns is already
790
+ * settled, so {@link waitForJob} resolves from it without polling.
791
+ */
792
+ executeBatch(request: BatchExecutionRequest, signal?: AbortSignal): Promise<BatchExecutionResult>;
793
+ /** The job as `jobStatus` reports it now; `undefined` when it reports none. */
794
+ getJob(jobId: string, signal?: AbortSignal): Promise<JobInfo | undefined>;
795
+ /** The job as `jobStatus` reports it now; throws when it reports none. */
796
+ getJobStatus(jobId: string, signal?: AbortSignal): Promise<JobInfo>;
797
+ /** Polls `jobStatus` until the job is READ_READY or FAILED. */
798
+ waitForJob(jobOrId: string | JobInfo, signal?: AbortSignal): Promise<JobInfo>;
799
+ /** See {@link readCreateSignaturePolicy}. */
800
+ getCreateSignaturePolicy(): Promise<SignaturePolicy>;
801
+ /** See {@link readCreateProtocolVersions}; fitted to `documentModels`. */
802
+ getCreateProtocolVersions(options: CreateProtocolVersionsOptions, signal?: AbortSignal): Promise<ProtocolVersions>;
803
+ /** See {@link IReactorClient.newDocument}; the module comes from `documentModels`. */
804
+ newDocument<TDocument extends PHDocument = PHDocument>(documentType: string, options?: NewDocumentOptions, signal?: AbortSignal): Promise<TDocument>;
805
+ /**
806
+ * Sets or, with `null`, clears the preferred editor as a client-signed
807
+ * action, as the in-process client does.
808
+ */
809
+ setPreferredEditor(documentIdentifier: string, preferredEditor: string | null, branch?: string, signal?: AbortSignal): Promise<PHDocument>;
810
+ /** The `Drive-Id` header for a call: the client's own proof, else the hook's. */
811
+ private driveIdHeaders;
812
+ /**
813
+ * Emits the changes the batch's settled jobs made, as `create` and `execute`
814
+ * do, so a cache is invalidated without a realtime socket. The documents a
815
+ * job wrote to are its own and those its consistency token names.
816
+ */
817
+ private announceBatch;
818
+ /**
819
+ * The id a job's actions are signed for: a signature covers the document id,
820
+ * and the server resolves a slug before verifying. A document created by this
821
+ * job or an earlier one is named by its id. When the server has no such
822
+ * document the identifier is used as given, and the server decides; any
823
+ * other failure to read it throws, so nothing is signed for a slug.
824
+ */
825
+ private batchWriteTarget;
826
+ /**
827
+ * Signs one batch job's actions for the job's own log.
828
+ *
829
+ * Each action is signed on its own for `(documentId, branch)`, the same
830
+ * per-action signing the reactor's `signActions` does: no state prediction
831
+ * across the job, so a job carrying a `CREATE_DOCUMENT` the push-prediction
832
+ * path rejects still signs. An action already signed under a key is left
833
+ * as it is: the reference `DriveClient` signs its jobs before handing them
834
+ * here. With no signer the actions pass through unsigned, matching
835
+ * {@link execute}.
836
+ */
837
+ private signBatchJobActions;
476
838
  /**
477
839
  * Deletes a document and announces it as a `Deleted` event.
478
840
  *
@@ -547,6 +909,53 @@ declare class GraphQLReactorClient implements IReactorBrowserClient$1 {
547
909
  * `gql` document or a string and name the result type at the call site.
548
910
  */
549
911
  request<TResult = unknown, TVariables extends Variables = Variables>(document: TypedGraphQLDocument<TResult, TVariables> | string, variables?: TVariables, options?: GraphQLRequestOptions): Promise<TResult>;
912
+ /**
913
+ * Shapes a document result page into the reactor's {@link PagedResults}.
914
+ *
915
+ * The items carry the same `PHDocumentFields` fragment as `get`, so the same
916
+ * adapter rebuilds each one. `hasNextPage` gates the cursor exactly as
917
+ * `getOperations` does: no cursor means no `next`.
918
+ */
919
+ private toDocumentResults;
920
+ /**
921
+ * Shapes a relationship-edge result page into the reactor's
922
+ * {@link PagedResults}, restoring each edge's `Date` fields.
923
+ */
924
+ private toRelationshipResults;
925
+ /**
926
+ * The write half's `execute`: signs as the facade's `execute` does, submits
927
+ * through `executeAsync` and returns once the job is accepted. When anyone
928
+ * subscribes, the document is read back once the job is readable and
929
+ * announced as `Updated`, as the facade's `execute` announces it; the handle
930
+ * shares that read with its own `document()`.
931
+ */
932
+ private submitExecute;
933
+ /** The write half's `create`: the synchronous mutation, a settled handle. */
934
+ private submitCreate;
935
+ /** The write half's `deleteDocument`: the synchronous mutation, a settled handle. */
936
+ private submitDeleteDocument;
937
+ /** Reads a write's document back, bounded by its receipt's token. */
938
+ private handleReader;
939
+ /** Announces a write's document as `Updated` once it is readable. */
940
+ private announceWrite;
941
+ /**
942
+ * Waits for a job to settle a stage, resolving with a FAILED job too. Polls
943
+ * `jobStatus` with a doubling interval; with realtime on, a `jobChanges`
944
+ * event for the job wakes the wait early and the interval is only a safety
945
+ * net. A failed subscription is logged once and the wait keeps polling.
946
+ */
947
+ private waitForStage;
948
+ /**
949
+ * Subscribes to one job's `jobChanges` when realtime is on and the
950
+ * subscription has not failed before. Returns the stop function, or
951
+ * undefined when nothing was subscribed.
952
+ */
953
+ private watchJob;
954
+ /**
955
+ * The `document` query with the `consistency` argument, or without it once
956
+ * the Switchboard has refused the argument.
957
+ */
958
+ private getDocumentAtConsistency;
550
959
  /**
551
960
  * Opens the realtime socket on the first subscriber.
552
961
  *
@@ -612,6 +1021,8 @@ declare class GraphQLReactorClient implements IReactorBrowserClient$1 {
612
1021
  */
613
1022
  private emitChange;
614
1023
  }
1024
+ /** {@link GraphQLReactorClient.nodeSource}, as a function. */
1025
+ declare function createGraphQLDriveNodeSource(client: GraphQLReactorClient): IDriveNodeSource;
615
1026
  /**
616
1027
  * Whether a value is a {@link GraphQLReactorClient}, including one built by
617
1028
  * another copy of this module.
@@ -628,6 +1039,18 @@ declare function isGraphQLReactorClient(client: unknown): client is GraphQLReact
628
1039
  * argument, so silently returning the head state would be wrong.
629
1040
  */
630
1041
  declare function viewFilterInputFromViewFilter(view?: ViewFilter): ViewFilterInput | undefined;
1042
+ /**
1043
+ * The single source of truth for whether the Switchboard `findDocuments` query
1044
+ * can serve a `find`. It is servable iff the search names neither `ids` nor
1045
+ * `slugs` (present, regardless of length) AND the view is not point-in-time:
1046
+ * each is a by-contract limitation of a surface that filters only by
1047
+ * `type`/`parentId` at head. Exported so a caller can route around an
1048
+ * unservable search instead of catching the error `find` throws for it.
1049
+ */
1050
+ declare function findIsServableOverGraphQL(search: SearchFilter, view?: ViewFilter): boolean;
1051
+ /** Resolves the signer of the logged-in user, if there is one. */
1052
+ /** The logged-in Renown user's signer, read per call; none when nobody is. */
1053
+ declare function ambientRenownSigner(): ISigner | undefined;
631
1054
  //#endregion
632
1055
  //#region src/graphql-client/graphql-reactor-provider.d.ts
633
1056
  declare global {
@@ -779,7 +1202,7 @@ declare const ReactorOperationFieldsFragmentDoc: import("graphql").DocumentNode;
779
1202
  */
780
1203
  declare const MutateDocumentWithOperationsDocument: import("graphql").DocumentNode;
781
1204
  type MutateDocumentWithOperationsVariables = {
782
- documentIdentifier: Scalars["String"]["input"];
1205
+ documentIdOrSlug: Scalars["String"]["input"];
783
1206
  actions: ReadonlyArray<ActionInput>;
784
1207
  sinceRevision?: Scalars["Int"]["input"];
785
1208
  scopes?: ReadonlyArray<Scalars["String"]["input"]>;
@@ -792,6 +1215,33 @@ type MutateDocumentWithOperationsResult = {
792
1215
  } | null;
793
1216
  };
794
1217
  };
1218
+ /**
1219
+ * `document`, bounded by a consistency token: the read waits until the
1220
+ * Switchboard's read models hold every operation the token names. The
1221
+ * `consistency` argument is additive on the Switchboard; one without it refuses
1222
+ * this document, and the client falls back to the plain `GetDocument`.
1223
+ */
1224
+ declare const GetDocumentAtConsistencyDocument: import("graphql").DocumentNode;
1225
+ type GetDocumentAtConsistencyVariables = {
1226
+ idOrSlug: Scalars["String"]["input"];
1227
+ view?: ViewFilterInput;
1228
+ consistency: {
1229
+ version: number;
1230
+ createdAtUtcIso: string;
1231
+ coordinates: ReadonlyArray<{
1232
+ documentId: string;
1233
+ scope: string;
1234
+ branch: string;
1235
+ operationIndex: number;
1236
+ }>;
1237
+ };
1238
+ };
1239
+ type GetDocumentAtConsistencyResult = {
1240
+ readonly document?: {
1241
+ readonly document: PhDocumentFieldsFragment;
1242
+ readonly childIds: ReadonlyArray<string>;
1243
+ } | null;
1244
+ };
795
1245
  //#endregion
796
1246
  //#region src/graphql-client/signing.d.ts
797
1247
  /**
@@ -943,6 +1393,33 @@ declare function isAuthRefusalClose(error: unknown): boolean;
943
1393
  * socket. It is safe to call more than once.
944
1394
  */
945
1395
  declare function startDocumentChangesSubscription(options: DocumentChangesSubscriptionOptions): () => void;
1396
+ /** The `jobChanges` payload, exactly as the Switchboard sends it. */
1397
+ type JobChangesEventPayload = JobChangesSubscription["jobChanges"];
1398
+ /**
1399
+ * One socket carrying `jobChanges` subscriptions, one per watched job. The
1400
+ * socket opens on the first watch and closes when nothing is watched.
1401
+ */
1402
+ interface IJobChangesSocket {
1403
+ /**
1404
+ * Watches one job. `onEvent` is called per status change the Switchboard
1405
+ * reports; `onError` once if the subscription fails. Returns the stop
1406
+ * function, safe to call more than once.
1407
+ */
1408
+ watch(jobId: string, onEvent: (event: JobChangesEventPayload) => void, onError: (error: unknown) => void): () => void;
1409
+ /** Closes the socket; a later watch opens a new one. */
1410
+ dispose(): void;
1411
+ }
1412
+ type JobChangesSocketOptions = {
1413
+ /** The websocket endpoint, e.g. `ws://localhost:4001/graphql/subscriptions`. */
1414
+ wsUrl: string;
1415
+ /** Resolves the `ConnectionInit` payload, per connect. */
1416
+ connectionParams?: () => Promise<ConnectionParams>;
1417
+ };
1418
+ /**
1419
+ * Opens the socket write handles wait on. `graphql-ws` multiplexes every
1420
+ * watched job over it and closes it once the last watch stops.
1421
+ */
1422
+ declare function createJobChangesSocket(options: JobChangesSocketOptions): IJobChangesSocket;
946
1423
  /**
947
1424
  * Derives the websocket endpoint from the GraphQL http endpoint.
948
1425
  *
@@ -960,6 +1437,59 @@ declare function subscriptionsUrlFromGraphqlUrl(url: string): string;
960
1437
  */
961
1438
  declare function makeAuthConnectionParams(tokenProvider: BearerTokenProvider): () => Promise<ConnectionParams>;
962
1439
  //#endregion
1440
+ //#region src/graphql-client/switchboard-backend.d.ts
1441
+ type SwitchboardBackendDescriptor = {
1442
+ /** Router backend name; unique and stable for the router's life. */
1443
+ readonly name: string;
1444
+ /** `<origin>[/<prefix>]/graphql`. */
1445
+ readonly url: string;
1446
+ /** Resolves the bearer per request and for the realtime socket. */
1447
+ readonly tokenProvider: BearerTokenProvider;
1448
+ /** Read per push when a function; `undefined` pushes unsigned, never ambient. */
1449
+ readonly signer: ISigner | (() => ISigner | undefined) | undefined;
1450
+ /** Models for signing a batch, read per batch. */
1451
+ readonly documentModels: () => readonly DocumentModelModule$1<any>[];
1452
+ readonly realtime?: boolean;
1453
+ /** Default `"rpc"`. */
1454
+ readonly inspection?: ReactorReach["inspection"];
1455
+ /** Bound on one request, headers through body. Default 30_000. */
1456
+ readonly requestTimeoutMs?: number;
1457
+ /** Bound on a batch, which waits for its jobs. Default 120_000. */
1458
+ readonly batchRequestTimeoutMs?: number;
1459
+ /** Unset fields take {@link DEFAULT_BREAKER}; `false` never opens. */
1460
+ readonly breaker?: SwitchboardBreaker;
1461
+ /** The transport under the deadline and the breaker; {@link switchboardFetch} by default. */
1462
+ readonly fetch?: GraphQLFetch;
1463
+ };
1464
+ declare const DEFAULT_REQUEST_TIMEOUT_MS = 30000;
1465
+ declare const DEFAULT_BATCH_REQUEST_TIMEOUT_MS = 120000;
1466
+ declare const DEFAULT_BREAKER: Readonly<{
1467
+ failures: 3;
1468
+ openMs: 30000;
1469
+ }>;
1470
+ /** After `failures` failed requests in a row, send nothing for `openMs`. */
1471
+ type SwitchboardBreaker = false | {
1472
+ readonly failures?: number;
1473
+ readonly openMs?: number;
1474
+ };
1475
+ type SwitchboardBackend = {
1476
+ /** reach `{hosting: "remote", inspection}`; `refusesMisroutes: false`. */
1477
+ readonly config: RoutableBackendConfig;
1478
+ /** Reopens the realtime socket on the new credentials. */
1479
+ notifyCredentialsChanged(): void;
1480
+ /** Closes the realtime socket. */
1481
+ dispose(): void;
1482
+ };
1483
+ /** The Switchboard's circuit is open: nothing was sent. */
1484
+ declare class SwitchboardUnreachableError extends Error {
1485
+ readonly backend: string;
1486
+ readonly retryAt: number;
1487
+ readonly name = "SwitchboardUnreachableError";
1488
+ constructor(backend: string, retryAt: number);
1489
+ }
1490
+ /** A Switchboard as a router backend; members GraphQL cannot serve are absent. */
1491
+ declare function createSwitchboardBackend(descriptor: SwitchboardBackendDescriptor): SwitchboardBackend;
1492
+ //#endregion
963
1493
  //#region src/hooks/document-cache.d.ts
964
1494
  /** Returns all documents in the reactor. */
965
1495
  declare const useDocumentCache: UsePHGlobalValue$1<IDocumentCache>;
@@ -1105,10 +1635,23 @@ declare const setReactorClientModule: SetPHGlobalValue<BrowserReactorClientModul
1105
1635
  declare const addReactorClientModuleEventHandler: AddPHGlobalEventHandler;
1106
1636
  /** Returns the reactor client */
1107
1637
  declare const useReactorClient: UsePHGlobalValue<IReactorBrowserClient>;
1108
- /** Sets the reactor client */
1638
+ /**
1639
+ * Sets the reactor client, and `window.ph.reactor` to its read and write
1640
+ * halves. A client without halves leaves `reactor` unset.
1641
+ */
1109
1642
  declare const setReactorClient: SetPHGlobalValue<IReactorBrowserClient>;
1643
+ /** Returns the reactor client's read and write halves */
1644
+ declare const useReactorHalves: UsePHGlobalValue<ReactorBrowserHalves>;
1645
+ /** Adds an event handler for the reactor client's halves */
1646
+ declare const addReactorHalvesEventHandler: AddPHGlobalEventHandler;
1110
1647
  /** Adds an event handler for the reactor client */
1111
1648
  declare const addReactorClientEventHandler: AddPHGlobalEventHandler;
1649
+ /** Sets the client full-client actions use instead of the module's */
1650
+ declare const setFullReactorClient: SetPHGlobalValue<IReactorClient>;
1651
+ /** Adds an event handler for the full reactor client */
1652
+ declare const addFullReactorClientEventHandler: AddPHGlobalEventHandler;
1653
+ /** The client full-client actions use: the one set, else the module's. */
1654
+ declare function getFullReactorClient(): IReactorClient | undefined;
1112
1655
  declare const useSync: () => ISyncManager | undefined;
1113
1656
  declare const useSyncList: () => import("@powerhousedao/reactor").Remote[];
1114
1657
  declare const useModelRegistry: () => IDocumentModelRegistry | undefined;
@@ -1116,14 +1659,20 @@ declare const useDatabase: () => Kysely<Database> | undefined;
1116
1659
  declare const usePGlite: () => PGlite | undefined;
1117
1660
  //#endregion
1118
1661
  //#region src/hooks/dispatch.d.ts
1119
- /**
1120
- * Returns a dispatch function for dispatching actions to a document.
1121
- * Used internally by other hooks to provide action dispatching capabilities.
1122
- * @param document - The document to dispatch actions to.
1123
- * @returns A tuple containing the document and a dispatch function.
1124
- */
1125
- type DispatchFn<TAction> = (actionOrActions: TAction[] | TAction | undefined, onErrors?: (errors: Error[]) => void, onSuccess?: (result: PHDocument$1) => void) => void;
1662
+ /** Dispatches actions.
1663
+ *
1664
+ * Once the write lands, `onErrors` runs first, with an `OperationRejectedError` per action
1665
+ * the document did not apply; it is skipped when every action applied. Then `onSuccess`
1666
+ * runs with the document and an outcome, whether or not any action was rejected:
1667
+ * `outcome.rejected` holds the same errors, and is empty only when every action applied.
1668
+ * If `onErrors` throws, `onSuccess` does not run.
1669
+ *
1670
+ * When nothing lands (no document, no reactor, a failed write), only `onErrors` runs, with why. */
1671
+ type DispatchFn<TAction> = (actionOrActions: TAction[] | TAction | undefined, onErrors?: (errors: Error[]) => void, onSuccess?: DispatchSuccessCallback) => void;
1126
1672
  type UseDispatchResult<TDocument, TAction> = readonly [TDocument | undefined, DispatchFn<TAction>];
1673
+ /** A dispatch to the document `getDocument` returns when it runs. */
1674
+ declare function createDispatch<TDocument = PHDocument$1, TAction = Action$1>(getDocument: () => TDocument | undefined): DispatchFn<TAction>;
1675
+ /** Returns the document and a dispatch to it; see `DispatchFn` for the callbacks' order. */
1127
1676
  declare function useDispatch<TDocument = PHDocument$1, TAction = Action$1>(document: TDocument | undefined): UseDispatchResult<TDocument, TAction>;
1128
1677
  //#endregion
1129
1678
  //#region src/hooks/document-model-modules.d.ts
@@ -1203,6 +1752,6 @@ declare const setAttachmentService: SetPHGlobalValue<IAttachmentService>;
1203
1752
  /** Registers the attachmentService window event handler */
1204
1753
  declare const addAttachmentServiceEventHandler: AddPHGlobalEventHandler;
1205
1754
  //#endregion
1206
- export { useSwitchboardClient as $, useGetDocument as A, RemoteControllerOptions as At, StaticPackageManager as B, isOperationCache as Bt, useSyncList as C, GetDocumentWithOperationsResult as Ct, useDocumentCache as D, MergeHandler as Dt, useDocument as E, IRemoteController as Et, DocumentChangesSubscriptionOptions as F, SyncStatus$1 as Ft, stampAction as G, resolveDocumentModelModule as H, IDLE_REFETCH_STATE as Ht, isAuthRefusalClose as I, TrackedAction as It, MutateDocumentWithOperationsVariables as J, MutateDocumentWithOperationsDocument as K, makeAuthConnectionParams as L, DocumentCache as Lt, useGetDocuments as M, RemoteDocumentData as Mt, ConnectionParams as N, RemoteOperation as Nt, useDocumentSafe as O, PushResult as Ot, DocumentChangesEventPayload as P, RemoteOperationResultPage as Pt, ensurePHEventHandlers as Q, startDocumentChangesSubscription as R, IDLE_OPERATIONS_ENTRY as Rt, useSync as S, GetDocumentResult as St, setDocumentCache as T, IRemoteClient as Tt, prepareSignedActions as U, packageFromDocumentModels as V, readPromiseState as Vt, signStampedAction as W, GraphQLReactorProvider as X, ReactorOperationFieldsFragmentDoc as Y, GraphQLReactorProviderProps as Z, useDatabase as _, phDocumentFromMutation as _t, DocumentOperationsState as a, SubgraphSdkFactory as at, useReactorClient as b, ConflictStrategy as bt, useDocumentModelModuleById as c, describeGraphQLDocument as ct, UseDispatchResult as d, ambientRenownTokenProvider as dt, GraphQLReactorClient as et, useDispatch as f, makeAuthMiddleware as ft, setReactorClientModule as g, phDocumentFromGetDocument as gt, setReactorClient as h, RevisionsListSelection as ht, DocumentOperationsResult as i, GraphQLRequestOptions as it, useGetDocumentAsync as j, RemoteDocumentChangeEvent as jt, useDocuments as k, RemoteControllerGraphQLClient as kt, useDocumentModelModules as l, subgraphUrlFromGraphqlUrl as lt, addReactorClientModuleEventHandler as m, GetDocumentQueryResult as mt, setAttachmentService as n, isGraphQLReactorClient as nt, UseDocumentOperationsOptions as o, SubgraphSdkRegistry as ot, addReactorClientEventHandler as p, GetDocumentQueryFields as pt, MutateDocumentWithOperationsResult as q, useAttachmentService as r, viewFilterInputFromViewFilter as rt, useDocumentOperations as s, TypedGraphQLDocument as st, addAttachmentServiceEventHandler as t, GraphQLReactorClientOptions as tt, DispatchFn as u, BearerTokenProvider as ut, useModelRegistry as v, revisionMapFromRevisionsList as vt, addDocumentCacheEventHandler as w, GetOperationsResult as wt, useReactorClientModule as x, DocumentChangeListener as xt, usePGlite as y, ConflictInfo as yt, subscriptionsUrlFromGraphqlUrl as z, addPromiseState as zt };
1755
+ 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 };
1207
1756
  export {};
1208
- //# sourceMappingURL=attachment-service-But1Xljo.d.ts.map
1757
+ //# sourceMappingURL=attachment-service-B-AmTrs2.d.ts.map