@powerhousedao/reactor-browser 6.2.3 → 6.3.0-dev.1
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.
- package/dist/{attachment-service-But1Xljo.d.ts → attachment-service-B-AmTrs2.d.ts} +605 -56
- package/dist/attachment-service-B-AmTrs2.d.ts.map +1 -0
- package/dist/auth-DRbzRdeC.d.ts +32 -0
- package/dist/auth-DRbzRdeC.d.ts.map +1 -0
- package/dist/{client-BiJAJ9dW.js → client-BFnMV-EO.js} +39 -22
- package/dist/client-BFnMV-EO.js.map +1 -0
- package/dist/{client-CngU4mtn.d.ts → client-BP0hXjqq.d.ts} +3 -2
- package/dist/client-BP0hXjqq.d.ts.map +1 -0
- package/dist/client-wwavHFfs.js +135 -0
- package/dist/client-wwavHFfs.js.map +1 -0
- package/dist/{dispatch-qRXS70fh.js → dispatch-Cylwl2Dk.js} +363 -44
- package/dist/dispatch-Cylwl2Dk.js.map +1 -0
- package/dist/{document-by-id-B_8DA4yZ.js → document-by-id-DdvqanGR.js} +2 -2
- package/dist/{document-by-id-B_8DA4yZ.js.map → document-by-id-DdvqanGR.js.map} +1 -1
- package/dist/document-model-modules-BG-61uke.js +710 -0
- package/dist/document-model-modules-BG-61uke.js.map +1 -0
- package/dist/{document-operations-Bt-1-ThH.js → document-operations-DRMMwmGZ.js} +2160 -181
- package/dist/document-operations-DRMMwmGZ.js.map +1 -0
- package/dist/global-iARBhxNI.d.ts +612 -0
- package/dist/global-iARBhxNI.d.ts.map +1 -0
- package/dist/{index-BABMK8cO.d.ts → index-CNS_9THu.d.ts} +14 -4
- package/dist/index-CNS_9THu.d.ts.map +1 -0
- package/dist/index.d.ts +560 -79
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +790 -317
- package/dist/index.js.map +1 -1
- package/dist/inspector-proxy-DODqs15F.d.ts +25 -0
- package/dist/inspector-proxy-DODqs15F.d.ts.map +1 -0
- package/dist/make-ph-event-functions-B5GU5xcR.js +180 -0
- package/dist/make-ph-event-functions-B5GU5xcR.js.map +1 -0
- package/dist/{relational-ChC_AWAK.js → relational-DZuyKp2y.js} +65 -5
- package/dist/relational-DZuyKp2y.js.map +1 -0
- package/dist/{renown-C9pYZRqf.js → renown-B3MUaiq7.js} +56 -25
- package/dist/renown-B3MUaiq7.js.map +1 -0
- package/dist/renown-CBoTdGrg.js +394 -0
- package/dist/renown-CBoTdGrg.js.map +1 -0
- package/dist/{client-VV9M73s_.js → schema-B5lftDPf.js} +295 -195
- package/dist/schema-B5lftDPf.js.map +1 -0
- package/dist/{types-B7-_l_wE.d.ts → schema-C6ECceaN.d.ts} +272 -82
- package/dist/schema-C6ECceaN.d.ts.map +1 -0
- package/dist/src/ai/index.d.ts +269 -24
- package/dist/src/ai/index.d.ts.map +1 -1
- package/dist/src/ai/index.js +1028 -168
- package/dist/src/ai/index.js.map +1 -1
- package/dist/src/analytics/index.js +3 -3
- package/dist/src/graphql/client.d.ts +2 -2
- package/dist/src/graphql/client.js +1 -1
- package/dist/src/graphql-client/entry.d.ts +6 -4
- package/dist/src/graphql-client/entry.js +4 -4
- package/dist/src/relational/index.d.ts +8 -1
- package/dist/src/relational/index.d.ts.map +1 -1
- package/dist/src/relational/index.js +1 -1
- package/dist/src/renown/index.d.ts +2 -2
- package/dist/src/renown/index.js +3 -3
- package/dist/src/rpc/index.d.ts +201 -144
- package/dist/src/rpc/index.d.ts.map +1 -1
- package/dist/src/rpc/index.js +562 -634
- package/dist/src/rpc/index.js.map +1 -1
- package/dist/switchboard-directory-vH6qtkh-.js +435 -0
- package/dist/switchboard-directory-vH6qtkh-.js.map +1 -0
- package/dist/switchboards-D-_JBUbF.d.ts +75 -0
- package/dist/switchboards-D-_JBUbF.d.ts.map +1 -0
- package/dist/types-BWx6FPO4.d.ts +63 -0
- package/dist/types-BWx6FPO4.d.ts.map +1 -0
- package/package.json +19 -17
- package/dist/attachment-service-But1Xljo.d.ts.map +0 -1
- package/dist/client-BiJAJ9dW.js.map +0 -1
- package/dist/client-CngU4mtn.d.ts.map +0 -1
- package/dist/client-VV9M73s_.js.map +0 -1
- package/dist/dispatch-qRXS70fh.js.map +0 -1
- package/dist/document-model-modules-D6I-UUXq.js +0 -386
- package/dist/document-model-modules-D6I-UUXq.js.map +0 -1
- package/dist/document-operations-Bt-1-ThH.js.map +0 -1
- package/dist/global-fql2bmb0.d.ts +0 -438
- package/dist/global-fql2bmb0.d.ts.map +0 -1
- package/dist/index-BABMK8cO.d.ts.map +0 -1
- package/dist/inspector-proxy-DCowaeeH.d.ts +0 -264
- package/dist/inspector-proxy-DCowaeeH.d.ts.map +0 -1
- package/dist/make-ph-event-functions-FzpvQtj6.js +0 -53
- package/dist/make-ph-event-functions-FzpvQtj6.js.map +0 -1
- package/dist/relational-ChC_AWAK.js.map +0 -1
- package/dist/renown-C9pYZRqf.js.map +0 -1
- package/dist/renown-Def5iO8k.js +0 -97
- package/dist/renown-Def5iO8k.js.map +0 -1
- package/dist/switchboard-CFyD_5_e.js +0 -323
- package/dist/switchboard-CFyD_5_e.js.map +0 -1
- package/dist/types-B7-_l_wE.d.ts.map +0 -1
|
@@ -1,18 +1,61 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
1
|
+
import { c as getPHStore, f as usePHStore, t as makePHEventFunctions } from "./make-ph-event-functions-B5GU5xcR.js";
|
|
2
|
+
import { A as DocumentModelNotFoundError, D as queueActions, O as queueOperations, P as UnsupportedDocumentTypeError, b as DOCUMENT_CHANGE_TYPE, f as DocumentCache, h as IDLE_OPERATIONS_ENTRY, i as setDocumentCache, k as uploadOperations, o as useDocumentCache, r as addDocumentCacheEventHandler, v as isOperationCache } from "./dispatch-Cylwl2Dk.js";
|
|
3
|
+
import { B as addFullReactorClientEventHandler, D as setSelectedNodeId, H as addReactorClientModuleEventHandler, K as setReactorClient, N as addDrivesEventHandler, S as addSelectedNodeIdEventHandler, U as addReactorHalvesEventHandler, V as addReactorClientEventHandler, W as getFullReactorClient, Z as useReactorClient, _t as ambientRenownTokenProvider, a as setVetraPackageManager, at as invalidateDriveNodes, c as addSwitchboardsEventHandler, d as addSelectedDriveIdEventHandler, h as setSelectedDriveId, ht as listAllDriveNodes, it as getDriveNode, nt as addDriveNodesEventHandler, p as selectDrive, r as addVetraPackageManagerEventHandler, rt as dropDriveNode, st as markLocalDriveWrite, v as useSelectedDriveId, vt as makeAuthMiddleware, x as addResetSelectedNodeEventHandler } from "./document-model-modules-BG-61uke.js";
|
|
4
|
+
import { A as openTargetWith, C as getCurrentPathname, E as hasHostNavigation, G as extractNodeIdFromSlug, I as searchToRecord, J as findDriveBySlug, K as extractNodeSlugFromPath, L as setBrowserOpenSync, N as recordToSearch, U as extractDriveSlugFromPath, f as addLoadingEventHandler, k as openTarget, t as addRenownEventHandler, w as getPHNavigation, z as targetPathname } from "./renown-CBoTdGrg.js";
|
|
5
|
+
import { a as JobChangesDocument, o as PhDocumentFieldsFragmentDoc, t as DocumentChangesDocument } from "./schema-B5lftDPf.js";
|
|
6
|
+
import { t as createClient$1 } from "./client-wwavHFfs.js";
|
|
7
|
+
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
|
8
|
+
import { Fragment, jsx } from "react/jsx-runtime";
|
|
6
9
|
import { logger } from "document-model";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
10
|
+
import { FLAGS_FOR_EVERY_VERSION, PEER_CAPABILITIES, UnsupportedDocumentModelVersionError, actionSignerIdentity, actionSigningTarget, actions, assertAuthPreservedOnDuplicate, baseLoadFromInput, baseLoadFromInputVersioned, baseSaveToFileHandle, capSelection, capabilitiesOf, createCopyHeader, createPresignedHeader, createZip, creationState, deserializeSignature, documentModelDocumentType, fitCreateBaseReducer, generateId, hasDerivedDocumentId, hashDocumentStateForScope, headNewDocument, isSignaturePolicy, localSupports, normalizeDocumentModelVersion, replayDocumentVersioned, resolveBaseReducerVersion, selectDocumentModelModule, serializeByKey, setName, setPreferredEditor, signaturePolicyOf, toTransportAction, undoCapabilitiesOf, undoNeedsTargets, undoRedoActions, undoRedoAvailabilityOf, withSignaturePolicy } from "@powerhousedao/shared/document-model";
|
|
11
|
+
import { addFolder, copyNode, driveDocumentModelModule, generateNodesCopy, handleTargetNameCollisions, isFileNode, isFolderNode, moveNode, updateNode } from "@powerhousedao/shared/document-drive";
|
|
9
12
|
import { allPass, conditional, constant, forEachObj, funnel, isDefined, isNot, isStrictEqual, isString, isTruthy, once } from "remeda";
|
|
10
|
-
import {
|
|
11
|
-
import { GraphQLClient } from "graphql-request";
|
|
13
|
+
import { DRIVE_CHILD_RELATIONSHIP_TYPE } from "@powerhousedao/reactor-drive";
|
|
12
14
|
import { gql } from "graphql-tag";
|
|
13
15
|
import { Kind, print } from "graphql";
|
|
16
|
+
import { GraphQLClient } from "graphql-request";
|
|
14
17
|
import { createClient } from "graphql-ws/client";
|
|
15
|
-
|
|
18
|
+
//#region src/hooks/url-state.ts
|
|
19
|
+
/** The nearest store's navigation, else the bound store's, else the browser's.
|
|
20
|
+
* Hosts set it once, so hook order holds. */
|
|
21
|
+
function usePHNavigation() {
|
|
22
|
+
return usePHStore()?.navigation ?? getPHNavigation();
|
|
23
|
+
}
|
|
24
|
+
/** The current query params. */
|
|
25
|
+
function useSearchParams() {
|
|
26
|
+
return usePHNavigation().useSearchParams();
|
|
27
|
+
}
|
|
28
|
+
/** Sets query params: an object merges into them, a function returns them all. */
|
|
29
|
+
function useSetSearchParams() {
|
|
30
|
+
return usePHNavigation().useSetSearchParams();
|
|
31
|
+
}
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/hooks/link-props.ts
|
|
34
|
+
/** A plain primary click; modified and other-button clicks stay the browser's. */
|
|
35
|
+
function isPlainClick(event) {
|
|
36
|
+
return !event.defaultPrevented && event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey;
|
|
37
|
+
}
|
|
38
|
+
/** Props for an `<a>` that opens `target` in the app on a plain click, and
|
|
39
|
+
* leaves new tabs and windows to the browser; acts on the store in context. */
|
|
40
|
+
function useLinkProps(target, open) {
|
|
41
|
+
const navigation = usePHNavigation();
|
|
42
|
+
const href = navigation.hrefFor?.(target) ?? targetPathname(target);
|
|
43
|
+
const isCurrent = navigation.useIsCurrent?.(target) ?? false;
|
|
44
|
+
const preload = () => navigation.preload?.(target);
|
|
45
|
+
const openTarget = open ?? (() => openTargetWith(navigation, target));
|
|
46
|
+
return {
|
|
47
|
+
href,
|
|
48
|
+
onClick: (event) => {
|
|
49
|
+
if (!isPlainClick(event)) return;
|
|
50
|
+
event.preventDefault();
|
|
51
|
+
openTarget();
|
|
52
|
+
},
|
|
53
|
+
onMouseEnter: preload,
|
|
54
|
+
onFocus: preload,
|
|
55
|
+
"aria-current": isCurrent ? "page" : void 0
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
//#endregion
|
|
16
59
|
//#region src/hooks/modals.ts
|
|
17
60
|
const modalEventFunctions = makePHEventFunctions("modal");
|
|
18
61
|
/** Returns the current modal */
|
|
@@ -21,17 +64,123 @@ const usePHModal = modalEventFunctions.useValue;
|
|
|
21
64
|
const setPHModal = modalEventFunctions.setValue;
|
|
22
65
|
/** Adds an event handler for the modal */
|
|
23
66
|
const addModalEventHandler = modalEventFunctions.addEventHandler;
|
|
24
|
-
/**
|
|
67
|
+
/** The query param that names a routed modal. */
|
|
68
|
+
const MODAL_SEARCH_PARAM = "modal";
|
|
69
|
+
const MODAL_ROUTES = {
|
|
70
|
+
createDocument: {
|
|
71
|
+
id: "create-document",
|
|
72
|
+
toSearch: ({ documentType, documentModelVersion, driveId }) => ({
|
|
73
|
+
documentType,
|
|
74
|
+
...documentModelVersion !== void 0 && { documentModelVersion: String(documentModelVersion) },
|
|
75
|
+
...driveId && { driveId }
|
|
76
|
+
}),
|
|
77
|
+
fromSearch: (search) => ({
|
|
78
|
+
documentType: search.documentType ?? "",
|
|
79
|
+
...search.documentModelVersion && { documentModelVersion: Number(search.documentModelVersion) },
|
|
80
|
+
...search.driveId && { driveId: search.driveId }
|
|
81
|
+
})
|
|
82
|
+
},
|
|
83
|
+
login: { id: "login" },
|
|
84
|
+
addDrive: { id: "add-drive" },
|
|
85
|
+
driveSettings: {
|
|
86
|
+
id: "drive-settings",
|
|
87
|
+
toSearch: ({ driveId }) => ({ driveId }),
|
|
88
|
+
fromSearch: (search) => ({ driveId: search.driveId ?? "" })
|
|
89
|
+
},
|
|
90
|
+
debugSettings: { id: "debug-settings" },
|
|
91
|
+
inspector: { id: "inspector" },
|
|
92
|
+
disclaimer: { id: "disclaimer" },
|
|
93
|
+
cookiesPolicy: { id: "cookies-policy" }
|
|
94
|
+
};
|
|
95
|
+
const routeOf = (type) => MODAL_ROUTES[type];
|
|
96
|
+
/** Whether `modal` lives in the URL rather than the store. */
|
|
97
|
+
function isRoutedModal(modal) {
|
|
98
|
+
return !!modal && !!routeOf(modal.type);
|
|
99
|
+
}
|
|
100
|
+
/** The query params that open `modal`; undefined for one the store holds. */
|
|
101
|
+
function modalSearch(modal) {
|
|
102
|
+
const route = routeOf(modal.type);
|
|
103
|
+
if (!route) return void 0;
|
|
104
|
+
return {
|
|
105
|
+
[MODAL_SEARCH_PARAM]: route.id,
|
|
106
|
+
...route.toSearch?.(modal)
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/** The routed modal `search` opens, if any. */
|
|
110
|
+
function modalFromSearch(search) {
|
|
111
|
+
const id = search[MODAL_SEARCH_PARAM];
|
|
112
|
+
if (typeof id !== "string") return void 0;
|
|
113
|
+
const strings = Object.fromEntries(Object.entries(search).map(([key, value]) => [key, String(value)]));
|
|
114
|
+
for (const [type, route] of Object.entries(MODAL_ROUTES)) {
|
|
115
|
+
if (route.id !== id) continue;
|
|
116
|
+
return {
|
|
117
|
+
type,
|
|
118
|
+
...route.fromSearch?.(strings)
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** `search` without a routed modal's params. */
|
|
123
|
+
function withoutModalSearch(search) {
|
|
124
|
+
const modal = modalFromSearch(search);
|
|
125
|
+
const own = modal ? Object.keys(modalSearch(modal) ?? {}) : [];
|
|
126
|
+
return Object.fromEntries(Object.entries(search).filter(([key]) => !own.includes(key)));
|
|
127
|
+
}
|
|
128
|
+
/** Shows a modal. With a host navigation, a routed one opens in the URL, in
|
|
129
|
+
* place of the current entry, and "settings" opens the settings page. */
|
|
25
130
|
function showPHModal(modal) {
|
|
131
|
+
if (modal.type === "settings" && hasHostNavigation()) {
|
|
132
|
+
openTarget({ settings: true });
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
const search = modalSearch(modal);
|
|
136
|
+
if (search && hasHostNavigation()) {
|
|
137
|
+
if (!isRoutedModal(modalEventFunctions.getSnapshot())) setPHModal(void 0);
|
|
138
|
+
getPHNavigation().setSearch((prev) => ({
|
|
139
|
+
...withoutModalSearch(prev),
|
|
140
|
+
...search
|
|
141
|
+
}), { replace: true });
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
26
144
|
setPHModal(modal);
|
|
27
145
|
}
|
|
28
|
-
/** Closes the current modal
|
|
146
|
+
/** Closes the current modal; a routed one leaves the URL in place of the entry,
|
|
147
|
+
* and a confirmation opened over it closes with it. */
|
|
29
148
|
function closePHModal() {
|
|
149
|
+
if (hasHostNavigation()) {
|
|
150
|
+
const navigation = getPHNavigation();
|
|
151
|
+
if (modalFromSearch(searchToRecord(navigation.location().search))) {
|
|
152
|
+
navigation.setSearch((prev) => withoutModalSearch(prev), { replace: true });
|
|
153
|
+
if (!isRoutedModal(modalEventFunctions.getSnapshot())) setPHModal(void 0);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
30
157
|
setPHModal(void 0);
|
|
31
158
|
}
|
|
159
|
+
/** The href that opens `modal` over the current page. */
|
|
160
|
+
function modalHref(modal) {
|
|
161
|
+
const { pathname, search } = getPHNavigation().location();
|
|
162
|
+
const next = {
|
|
163
|
+
...withoutModalSearch(searchToRecord(search)),
|
|
164
|
+
...modalSearch(modal)
|
|
165
|
+
};
|
|
166
|
+
return `${pathname}${recordToSearch(next)}`;
|
|
167
|
+
}
|
|
168
|
+
/** Props for an `<a>` that opens a routed `modal` over the current page on a
|
|
169
|
+
* plain click; new tabs and copied links get its URL. */
|
|
170
|
+
function useModalLinkProps(modal) {
|
|
171
|
+
useSearchParams();
|
|
172
|
+
return {
|
|
173
|
+
href: modalHref(modal),
|
|
174
|
+
onClick: (event) => {
|
|
175
|
+
if (!isPlainClick(event)) return;
|
|
176
|
+
event.preventDefault();
|
|
177
|
+
showPHModal(modal);
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
}
|
|
32
181
|
/** Shows the create document modal */
|
|
33
182
|
function showCreateDocumentModal(documentType, documentModelVersion) {
|
|
34
|
-
|
|
183
|
+
showPHModal({
|
|
35
184
|
type: "createDocument",
|
|
36
185
|
documentType,
|
|
37
186
|
...documentModelVersion !== void 0 && { documentModelVersion }
|
|
@@ -64,8 +213,8 @@ function isDocumentTypeSupported(documentType, supportedDocuments) {
|
|
|
64
213
|
//#endregion
|
|
65
214
|
//#region src/utils/user.ts
|
|
66
215
|
function getUserPermissions() {
|
|
67
|
-
const user =
|
|
68
|
-
const allowList =
|
|
216
|
+
const user = getPHStore()?.renown?.user;
|
|
217
|
+
const allowList = getPHStore()?.allowList;
|
|
69
218
|
if (!allowList) return {
|
|
70
219
|
isAllowedToCreateDocuments: true,
|
|
71
220
|
isAllowedToEditDocuments: true
|
|
@@ -78,16 +227,26 @@ function getUserPermissions() {
|
|
|
78
227
|
//#endregion
|
|
79
228
|
//#region src/actions/document.ts
|
|
80
229
|
const NON_DOMAIN_SCOPES = /* @__PURE__ */ new Set(["auth", "document"]);
|
|
230
|
+
/** Puts a node this tab just wrote into its drive's cache, so hooks show it
|
|
231
|
+
* before the drive change that follows the write is processed. Best effort:
|
|
232
|
+
* a client without a node reader is left to that change. */
|
|
233
|
+
async function rememberDriveNode(driveId, nodeId) {
|
|
234
|
+
try {
|
|
235
|
+
await getDriveNode(driveId, nodeId, { refresh: true });
|
|
236
|
+
} catch (error) {
|
|
237
|
+
logger.verbose("Caching the written node @id failed: @error", nodeId, error);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
81
240
|
/** An unreadable drive cannot be shown to hold no duplicate, so reads throw. */
|
|
82
241
|
async function isDocumentInLocation(reactorClient, document, driveId, parentFolder) {
|
|
83
|
-
const
|
|
84
|
-
const nodeById =
|
|
85
|
-
if (nodeById
|
|
242
|
+
const siblings = await listAllDriveNodes(reactorClient.drives, driveId, { parentFolder: parentFolder ?? null });
|
|
243
|
+
const nodeById = siblings.find((node) => node.id === document.header.id);
|
|
244
|
+
if (nodeById) return {
|
|
86
245
|
isDuplicate: true,
|
|
87
246
|
duplicateType: "id",
|
|
88
247
|
nodeId: nodeById.id
|
|
89
248
|
};
|
|
90
|
-
const nodeByNameAndType =
|
|
249
|
+
const nodeByNameAndType = siblings.find((node) => isFileNode(node) && node.name === document.header.name && node.documentType === document.header.documentType);
|
|
91
250
|
if (nodeByNameAndType) return {
|
|
92
251
|
isDuplicate: true,
|
|
93
252
|
duplicateType: "name",
|
|
@@ -132,9 +291,9 @@ async function getDocumentExtension(document) {
|
|
|
132
291
|
let rawExtension;
|
|
133
292
|
if (documentType === documentModelDocumentType) rawExtension = document.state.global?.extension;
|
|
134
293
|
else {
|
|
135
|
-
const reactorClient =
|
|
294
|
+
const reactorClient = getFullReactorClient();
|
|
136
295
|
if (reactorClient) {
|
|
137
|
-
const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
|
|
296
|
+
const { results: documentModelModules } = await reactorClient.read.getDocumentModelModules();
|
|
138
297
|
rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
|
|
139
298
|
}
|
|
140
299
|
}
|
|
@@ -164,12 +323,9 @@ async function fetchDocumentOperations(reactorClient, document, pageSize = 100)
|
|
|
164
323
|
return operations;
|
|
165
324
|
}
|
|
166
325
|
function extractInitialState(documentScopeOps) {
|
|
167
|
-
const
|
|
168
|
-
if (
|
|
169
|
-
|
|
170
|
-
const initialState = input.initialState ?? input.state;
|
|
171
|
-
if (!initialState) throw new Error("UPGRADE_DOCUMENT operation has no initialState — document is invalid");
|
|
172
|
-
return initialState;
|
|
326
|
+
const initialState = creationState(documentScopeOps);
|
|
327
|
+
if (initialState) return initialState;
|
|
328
|
+
throw new Error(documentScopeOps.some((op) => op.action.type === "UPGRADE_DOCUMENT") ? "UPGRADE_DOCUMENT operation has no initialState — document is invalid" : "No UPGRADE_DOCUMENT operation found — document is invalid");
|
|
173
329
|
}
|
|
174
330
|
function filterDomainOperations(operations) {
|
|
175
331
|
return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
|
|
@@ -236,9 +392,9 @@ function boundary(upgrade, scope, ops) {
|
|
|
236
392
|
return ops.length;
|
|
237
393
|
}
|
|
238
394
|
async function exportFile(document, suggestedName) {
|
|
239
|
-
const reactorClient =
|
|
395
|
+
const reactorClient = getPHStore()?.reactorClient;
|
|
240
396
|
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
241
|
-
const operations = await fetchDocumentOperations(reactorClient, document);
|
|
397
|
+
const operations = await fetchDocumentOperations(reactorClient.read, document);
|
|
242
398
|
const initialState = extractInitialState(operations["document"] ?? []);
|
|
243
399
|
const documentWithOps = {
|
|
244
400
|
...document,
|
|
@@ -264,15 +420,15 @@ async function exportFile(document, suggestedName) {
|
|
|
264
420
|
*/
|
|
265
421
|
async function loadFile(path) {
|
|
266
422
|
const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
|
|
267
|
-
const reactorClient =
|
|
423
|
+
const reactorClient = getFullReactorClient();
|
|
268
424
|
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
269
425
|
const documentType = baseDocument.header.documentType;
|
|
270
|
-
const { results: documentModelModules } = await reactorClient.getDocumentModelModules();
|
|
426
|
+
const { results: documentModelModules } = await reactorClient.read.getDocumentModelModules();
|
|
271
427
|
const modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);
|
|
272
428
|
if (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);
|
|
273
429
|
const reducers = {};
|
|
274
430
|
for (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;
|
|
275
|
-
const registry =
|
|
431
|
+
const registry = getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;
|
|
276
432
|
let upgradeManifest;
|
|
277
433
|
if (registry) try {
|
|
278
434
|
upgradeManifest = registry.getUpgradeManifest(documentType);
|
|
@@ -285,29 +441,27 @@ async function loadFile(path) {
|
|
|
285
441
|
async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor, documentModelVersion) {
|
|
286
442
|
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
287
443
|
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
|
|
288
|
-
const reactorClient =
|
|
444
|
+
const reactorClient = getFullReactorClient();
|
|
289
445
|
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
if (!module) throw new Error(`Document model not found for type: ${documentType} with version: ${documentModelVersion}`);
|
|
295
|
-
documentModelModule = module;
|
|
296
|
-
} else documentModelModule = await reactorClient.getDocumentModelModule(documentType);
|
|
297
|
-
const newDocument = document ?? withSignaturePolicy(documentModelModule.utils.createDocument(), await reactorClient.getCreateSignaturePolicy());
|
|
298
|
-
if (!document) newDocument.state.document.version = documentModelModule.version ?? 1;
|
|
446
|
+
const newDocument = document ?? await reactorClient.read.newDocument(documentType, {
|
|
447
|
+
parentIdentifier: driveId,
|
|
448
|
+
documentModelVersion
|
|
449
|
+
});
|
|
299
450
|
newDocument.header.name = name;
|
|
300
451
|
if (preferredEditor) newDocument.header.meta = {
|
|
301
452
|
...newDocument.header.meta,
|
|
302
453
|
preferredEditor
|
|
303
454
|
};
|
|
455
|
+
markLocalDriveWrite(driveId);
|
|
304
456
|
let newDoc;
|
|
305
457
|
try {
|
|
306
|
-
newDoc = await reactorClient.drives.addFile(driveId, newDocument, parentFolder);
|
|
458
|
+
newDoc = await (await reactorClient.write.drives.addFile(driveId, newDocument, parentFolder)).document();
|
|
307
459
|
} catch (e) {
|
|
308
460
|
logger.error("Error adding document: @error", e);
|
|
309
461
|
throw new Error("There was an error adding document", { cause: e });
|
|
310
462
|
}
|
|
463
|
+
await rememberDriveNode(driveId, newDoc.header.id);
|
|
464
|
+
await getDriveNode(driveId, newDoc.header.id, { refresh: true }).catch(() => void 0);
|
|
311
465
|
return {
|
|
312
466
|
id: newDoc.header.id,
|
|
313
467
|
name: newDoc.header.name,
|
|
@@ -341,13 +495,13 @@ function isDocumentAlreadyExists(error) {
|
|
|
341
495
|
* under the same id and is resolved by minting another one. A create that
|
|
342
496
|
* fails leaves the drive untouched, so a retry has nothing to clean up.
|
|
343
497
|
*/
|
|
344
|
-
async function createImportedDocument(
|
|
498
|
+
async function createImportedDocument(write, document, driveId, name, parentFolder) {
|
|
345
499
|
const v2Required = signaturePolicyOf(document.header) === "v2-required";
|
|
346
|
-
const keepsId = (!v2Required || hasDerivedDocumentId(document.header)) && !await
|
|
500
|
+
const keepsId = (!v2Required || hasDerivedDocumentId(document.header)) && !await write.isDocumentIdTaken(document.header.id);
|
|
347
501
|
let documentId = keepsId ? document.header.id : generateId();
|
|
348
502
|
for (let attempt = 1;; attempt++) {
|
|
349
503
|
let header;
|
|
350
|
-
if (!v2Required) header = createPresignedHeader(documentId, document.header.documentType);
|
|
504
|
+
if (!v2Required) header = createPresignedHeader(documentId, document.header.documentType, document.header.protocolVersions);
|
|
351
505
|
else if (keepsId && attempt === 1) {
|
|
352
506
|
header = createPresignedHeader(documentId, document.header.documentType);
|
|
353
507
|
header.createdAtUtcIso = document.header.createdAtUtcIso;
|
|
@@ -388,7 +542,7 @@ async function createImportedDocument(reactor, document, driveId, name, parentFo
|
|
|
388
542
|
}
|
|
389
543
|
async function addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
|
|
390
544
|
logger.verbose(`addFileWithProgress(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
|
|
391
|
-
const reactor =
|
|
545
|
+
const reactor = getFullReactorClient();
|
|
392
546
|
if (!reactor) {
|
|
393
547
|
onProgress?.({
|
|
394
548
|
stage: "failed",
|
|
@@ -422,7 +576,7 @@ async function addFileWithProgress(file, driveId, name, parentFolder, onProgress
|
|
|
422
576
|
});
|
|
423
577
|
return;
|
|
424
578
|
}
|
|
425
|
-
const discoveryService =
|
|
579
|
+
const discoveryService = getPHStore()?.packageDiscoveryService;
|
|
426
580
|
if (discoveryService && DocumentModelNotFoundError.isError(loadError)) {
|
|
427
581
|
retryAfterDiscovery(discoveryService, loadError.documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict).catch((retryError) => {
|
|
428
582
|
logger.error("Import retry after discovery failed: @error", retryError);
|
|
@@ -436,7 +590,7 @@ async function addFileWithProgress(file, driveId, name, parentFolder, onProgress
|
|
|
436
590
|
}
|
|
437
591
|
throw loadError;
|
|
438
592
|
}
|
|
439
|
-
const duplicateCheck = await isDocumentInLocation(reactor, document, driveId, parentFolder);
|
|
593
|
+
const duplicateCheck = await isDocumentInLocation(reactor.read, document, driveId, parentFolder);
|
|
440
594
|
if (duplicateCheck.isDuplicate && !resolveConflict) {
|
|
441
595
|
onProgress?.({
|
|
442
596
|
stage: "conflict",
|
|
@@ -463,19 +617,21 @@ async function addFileWithProgress(file, driveId, name, parentFolder, onProgress
|
|
|
463
617
|
});
|
|
464
618
|
throw new UnsupportedDocumentTypeError(document.header.documentType);
|
|
465
619
|
}
|
|
466
|
-
await reactor.getDocumentModelModule(document.header.documentType);
|
|
620
|
+
await reactor.read.getDocumentModelModule(document.header.documentType);
|
|
467
621
|
onProgress?.({
|
|
468
622
|
stage: "initializing",
|
|
469
623
|
progress: 10
|
|
470
624
|
});
|
|
471
|
-
|
|
625
|
+
markLocalDriveWrite(driveId);
|
|
626
|
+
const created = await createImportedDocument(reactor.write, document, driveId, name, parentFolder);
|
|
472
627
|
const documentId = created.documentId;
|
|
473
628
|
const fileNode = created.fileNode;
|
|
629
|
+
await rememberDriveNode(driveId, documentId);
|
|
474
630
|
onProgress?.({
|
|
475
631
|
stage: "initializing",
|
|
476
632
|
progress: 20
|
|
477
633
|
});
|
|
478
|
-
await reactor.get(documentId);
|
|
634
|
+
await reactor.read.get(documentId);
|
|
479
635
|
console.log("Document created, starting upload of operations");
|
|
480
636
|
const segments = splitAtUpgradeBoundaries(document.operations);
|
|
481
637
|
const totalOperations = segments.reduce((total, segment) => total + countOperations(segment.operations), 0);
|
|
@@ -493,7 +649,7 @@ async function addFileWithProgress(file, driveId, name, parentFolder, onProgress
|
|
|
493
649
|
});
|
|
494
650
|
} });
|
|
495
651
|
uploadedBefore += countOperations(segment.operations);
|
|
496
|
-
if (segment.upgradeTo !== void 0) await reactor.upgradeDocument(documentId, segment.upgradeTo);
|
|
652
|
+
if (segment.upgradeTo !== void 0) await (await reactor.write.upgradeDocument(documentId, segment.upgradeTo)).document();
|
|
497
653
|
}
|
|
498
654
|
onProgress?.({
|
|
499
655
|
stage: "complete",
|
|
@@ -530,80 +686,93 @@ async function retryAfterDiscovery(discoveryService, documentType, file, driveId
|
|
|
530
686
|
async function addFolder$1(driveId, name, parentFolder) {
|
|
531
687
|
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
532
688
|
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
|
|
533
|
-
const reactorClient =
|
|
689
|
+
const reactorClient = getPHStore()?.reactorClient;
|
|
534
690
|
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
535
|
-
await reactorClient.get(driveId);
|
|
691
|
+
await reactorClient.read.get(driveId);
|
|
536
692
|
const folderId = generateId();
|
|
537
|
-
|
|
693
|
+
markLocalDriveWrite(driveId);
|
|
694
|
+
await (await reactorClient.write.execute(driveId, "main", [addFolder({
|
|
538
695
|
id: folderId,
|
|
539
696
|
name,
|
|
540
697
|
parentFolder
|
|
541
|
-
})])).
|
|
698
|
+
})])).readable;
|
|
699
|
+
const node = await getDriveNode(driveId, folderId, { refresh: true });
|
|
542
700
|
if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
|
|
543
701
|
return node;
|
|
544
702
|
}
|
|
545
703
|
async function deleteNode(driveId, nodeId) {
|
|
546
704
|
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
547
705
|
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to delete documents");
|
|
548
|
-
const reactorClient =
|
|
706
|
+
const reactorClient = getFullReactorClient();
|
|
549
707
|
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
550
|
-
|
|
708
|
+
markLocalDriveWrite(driveId);
|
|
709
|
+
await (await reactorClient.write.drives.removeNode(driveId, nodeId)).readable;
|
|
710
|
+
dropDriveNode(driveId, nodeId);
|
|
551
711
|
}
|
|
552
712
|
async function renameNode(driveId, nodeId, name) {
|
|
553
713
|
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
554
714
|
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
|
|
555
|
-
const reactorClient =
|
|
715
|
+
const reactorClient = getPHStore()?.reactorClient;
|
|
556
716
|
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
557
|
-
if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
|
|
558
|
-
|
|
717
|
+
if ((await (await reactorClient.write.execute(nodeId, "main", [setName({ name })])).document()).header.name !== name) throw new Error("There was an error renaming the node");
|
|
718
|
+
markLocalDriveWrite(driveId);
|
|
719
|
+
await (await reactorClient.write.execute(driveId, "main", [updateNode({
|
|
559
720
|
id: nodeId,
|
|
560
721
|
name
|
|
561
|
-
})])).
|
|
722
|
+
})])).readable;
|
|
723
|
+
const node = await getDriveNode(driveId, nodeId, { refresh: true });
|
|
562
724
|
if (!node) throw new Error("There was an error renaming node in the drive");
|
|
563
725
|
return node;
|
|
564
726
|
}
|
|
565
727
|
async function renameDriveNode(driveId, nodeId, name) {
|
|
566
728
|
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
567
729
|
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
|
|
568
|
-
const reactorClient =
|
|
730
|
+
const reactorClient = getPHStore()?.reactorClient;
|
|
569
731
|
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
570
|
-
if ((await reactorClient.execute(nodeId, "main", [setName({ name })])).header.name !== name) throw new Error("There was an error renaming the node");
|
|
571
|
-
|
|
732
|
+
if ((await (await reactorClient.write.execute(nodeId, "main", [setName({ name })])).document()).header.name !== name) throw new Error("There was an error renaming the node");
|
|
733
|
+
markLocalDriveWrite(driveId);
|
|
734
|
+
await (await reactorClient.write.execute(driveId, "main", [updateNode({
|
|
572
735
|
id: nodeId,
|
|
573
736
|
name
|
|
574
|
-
})]);
|
|
575
|
-
return (
|
|
737
|
+
})])).readable;
|
|
738
|
+
return getDriveNode(driveId, nodeId, { refresh: true });
|
|
576
739
|
}
|
|
577
740
|
async function setPreferredEditorOnNode(nodeId, preferredEditor) {
|
|
578
741
|
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
579
742
|
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to modify documents");
|
|
580
|
-
const reactorClient =
|
|
743
|
+
const reactorClient = getPHStore()?.reactorClient;
|
|
581
744
|
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
582
|
-
return reactorClient.execute(nodeId, "main", [setPreferredEditor(preferredEditor)]);
|
|
745
|
+
return (await reactorClient.write.execute(nodeId, "main", [setPreferredEditor(preferredEditor)])).document();
|
|
583
746
|
}
|
|
584
747
|
async function moveNodeById(args) {
|
|
585
748
|
const { driveId, srcId, targetId } = args;
|
|
586
749
|
if (!driveId || !srcId) return;
|
|
587
750
|
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
588
751
|
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
|
|
589
|
-
const reactorClient =
|
|
752
|
+
const reactorClient = getPHStore()?.reactorClient;
|
|
590
753
|
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
591
754
|
const targetParentFolder = conditional(targetId, [isNot(isDefined), constant(void 0)], [isStrictEqual(driveId), constant(void 0)], constant(targetId));
|
|
592
755
|
if (isStrictEqual(targetParentFolder, srcId)) return;
|
|
593
|
-
|
|
756
|
+
markLocalDriveWrite(driveId);
|
|
757
|
+
const moved = await (await reactorClient.write.execute(driveId, "main", [moveNode({
|
|
594
758
|
srcFolder: srcId,
|
|
595
759
|
targetParentFolder
|
|
596
|
-
})]);
|
|
760
|
+
})])).document();
|
|
761
|
+
await rememberDriveNode(driveId, srcId);
|
|
762
|
+
return moved;
|
|
597
763
|
}
|
|
598
764
|
async function moveNode$1(driveId, src, target) {
|
|
599
765
|
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
600
766
|
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
|
|
601
|
-
const reactorClient =
|
|
767
|
+
const reactorClient = getPHStore()?.reactorClient;
|
|
602
768
|
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
603
|
-
|
|
769
|
+
markLocalDriveWrite(driveId);
|
|
770
|
+
const moved = await (await reactorClient.write.execute(driveId, "main", [moveNode({
|
|
604
771
|
srcFolder: src.id,
|
|
605
772
|
targetParentFolder: target?.id
|
|
606
|
-
})]);
|
|
773
|
+
})])).document();
|
|
774
|
+
await rememberDriveNode(driveId, src.id);
|
|
775
|
+
return moved;
|
|
607
776
|
}
|
|
608
777
|
/**
|
|
609
778
|
* Duplicates a document under a new id using version-aware replay.
|
|
@@ -616,7 +785,7 @@ async function _duplicateDocument(reactor, document, newId = generateId(), drive
|
|
|
616
785
|
const reducers = {};
|
|
617
786
|
for (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;
|
|
618
787
|
if (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);
|
|
619
|
-
const registry =
|
|
788
|
+
const registry = getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;
|
|
620
789
|
let upgradeManifest;
|
|
621
790
|
if (registry) try {
|
|
622
791
|
upgradeManifest = registry.getUpgradeManifest(documentType);
|
|
@@ -625,7 +794,10 @@ async function _duplicateDocument(reactor, document, newId = generateId(), drive
|
|
|
625
794
|
reducers,
|
|
626
795
|
upgradeManifest
|
|
627
796
|
};
|
|
628
|
-
const selected = await reactor.getCreateProtocolVersions(
|
|
797
|
+
const selected = await reactor.getCreateProtocolVersions({
|
|
798
|
+
documentType: document.header.documentType,
|
|
799
|
+
parentIdentifier: driveId
|
|
800
|
+
});
|
|
629
801
|
const header = createCopyHeader({
|
|
630
802
|
documentType: document.header.documentType,
|
|
631
803
|
protocolVersions: document.header.protocolVersions ? {
|
|
@@ -638,22 +810,23 @@ async function _duplicateDocument(reactor, document, newId = generateId(), drive
|
|
|
638
810
|
return duplicated;
|
|
639
811
|
}
|
|
640
812
|
async function copyNode$1(driveId, src, target) {
|
|
641
|
-
const reactor =
|
|
813
|
+
const reactor = getFullReactorClient();
|
|
642
814
|
if (!reactor) return;
|
|
643
815
|
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
644
816
|
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
|
|
645
|
-
const drive = await reactor.get(driveId);
|
|
817
|
+
const drive = await reactor.read.get(driveId);
|
|
818
|
+
const driveNodes = await listAllDriveNodes(reactor.read.drives, driveId);
|
|
646
819
|
const copyNodesInput = generateNodesCopy({
|
|
647
820
|
srcId: src.id,
|
|
648
821
|
targetParentFolder: target?.id,
|
|
649
822
|
targetName: src.name
|
|
650
|
-
}, () => generateId(),
|
|
823
|
+
}, () => generateId(), driveNodes);
|
|
651
824
|
const resolvedNamesMap = /* @__PURE__ */ new Map();
|
|
652
825
|
for (const copyNodeInput of copyNodesInput) {
|
|
653
|
-
const node =
|
|
826
|
+
const node = driveNodes.find((n) => n.id === copyNodeInput.srcId);
|
|
654
827
|
if (node) {
|
|
655
828
|
const resolvedName = handleTargetNameCollisions({
|
|
656
|
-
nodes:
|
|
829
|
+
nodes: driveNodes,
|
|
657
830
|
srcName: copyNodeInput.targetName || node.name,
|
|
658
831
|
srcKind: isFileNode(node) ? "file" : "folder",
|
|
659
832
|
targetParentFolder: copyNodeInput.targetParentFolder || null
|
|
@@ -662,30 +835,126 @@ async function copyNode$1(driveId, src, target) {
|
|
|
662
835
|
}
|
|
663
836
|
}
|
|
664
837
|
const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
|
|
665
|
-
const node =
|
|
838
|
+
const node = driveNodes.find((node) => node.id === copyNodeInput.srcId);
|
|
666
839
|
return node !== void 0 && isFileNode(node);
|
|
667
840
|
});
|
|
841
|
+
markLocalDriveWrite(driveId);
|
|
668
842
|
for (const fileNodeToCopy of fileNodesToCopy) try {
|
|
669
|
-
const
|
|
843
|
+
const document = await reactor.read.get(fileNodeToCopy.srcId);
|
|
844
|
+
const duplicatedDocument = await _duplicateDocument(reactor.read, document, fileNodeToCopy.targetId, driveId);
|
|
670
845
|
const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
|
|
671
846
|
if (resolvedName) duplicatedDocument.header.name = resolvedName;
|
|
672
847
|
fileNodeToCopy.targetId = duplicatedDocument.header.id;
|
|
673
|
-
await reactor.drives.addFile(driveId, duplicatedDocument, target?.id);
|
|
848
|
+
await (await reactor.write.drives.addFile(driveId, duplicatedDocument, target?.id)).readable;
|
|
674
849
|
} catch (e) {
|
|
675
850
|
logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
|
|
676
851
|
}
|
|
677
852
|
const copyActions = copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput));
|
|
678
|
-
|
|
853
|
+
markLocalDriveWrite(driveId);
|
|
854
|
+
const copied = await queueActions(drive, copyActions);
|
|
855
|
+
invalidateDriveNodes(driveId);
|
|
856
|
+
return copied;
|
|
679
857
|
}
|
|
680
858
|
/**
|
|
681
859
|
* Upgrades a document to a newer document model version. Defaults to the
|
|
682
860
|
* latest registered version for the document's type.
|
|
683
861
|
*/
|
|
684
862
|
async function upgradeDocument(documentId, toVersion) {
|
|
685
|
-
const reactorClient =
|
|
863
|
+
const reactorClient = getFullReactorClient();
|
|
686
864
|
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
687
|
-
return reactorClient.upgradeDocument(documentId, toVersion);
|
|
865
|
+
return (await reactorClient.write.upgradeDocument(documentId, toVersion)).document();
|
|
866
|
+
}
|
|
867
|
+
//#endregion
|
|
868
|
+
//#region src/graphql-client/errors.ts
|
|
869
|
+
/** A call the Switchboard GraphQL surface cannot express. */
|
|
870
|
+
var GraphQLOperationNotSupportedError = class extends Error {
|
|
871
|
+
name = "GraphQLOperationNotSupportedError";
|
|
872
|
+
operation;
|
|
873
|
+
constructor(operation, reason) {
|
|
874
|
+
super(`GraphQLReactorClient.${operation} is not supported: ${reason}`);
|
|
875
|
+
this.operation = operation;
|
|
876
|
+
}
|
|
877
|
+
static isError(error) {
|
|
878
|
+
return Error.isError(error) && error.name === "GraphQLOperationNotSupportedError";
|
|
879
|
+
}
|
|
880
|
+
};
|
|
881
|
+
/**
|
|
882
|
+
* The Switchboard refused a request with 421 Misdirected Request: the
|
|
883
|
+
* `Drive-Id` it carried names a drive that Switchboard does not own.
|
|
884
|
+
*/
|
|
885
|
+
var GraphQLWrongBackendError = class extends Error {
|
|
886
|
+
name = "GraphQLWrongBackendError";
|
|
887
|
+
status = 421;
|
|
888
|
+
/** The drive the Switchboard refused, or `""` when its answer names none. */
|
|
889
|
+
driveId;
|
|
890
|
+
/** The response body, parsed when it is JSON. */
|
|
891
|
+
payload;
|
|
892
|
+
constructor(driveId, payload, options) {
|
|
893
|
+
super(`The Switchboard does not serve drive ${driveId === "" ? "(unnamed)" : driveId}: 421 Misdirected Request`, options);
|
|
894
|
+
this.driveId = driveId;
|
|
895
|
+
this.payload = payload;
|
|
896
|
+
}
|
|
897
|
+
static isError(error) {
|
|
898
|
+
return Error.isError(error) && error.name === "GraphQLWrongBackendError" && typeof error.driveId === "string";
|
|
899
|
+
}
|
|
900
|
+
};
|
|
901
|
+
/**
|
|
902
|
+
* The reactor's `BatchJobFailedError`, rebuilt from a batch result; this entry
|
|
903
|
+
* imports the reactor for types only. The shared name lets either `isError`
|
|
904
|
+
* recognise it.
|
|
905
|
+
*/
|
|
906
|
+
var BatchJobFailedError = class extends Error {
|
|
907
|
+
name = "BatchJobFailedError";
|
|
908
|
+
key;
|
|
909
|
+
jobs;
|
|
910
|
+
constructor(key, jobs) {
|
|
911
|
+
const failure = jobs[key].error;
|
|
912
|
+
const cause = new Error(failure?.message ?? "Job failed");
|
|
913
|
+
cause.name = failure?.name ?? "Error";
|
|
914
|
+
super(failure?.message ?? "Job failed", { cause });
|
|
915
|
+
this.key = key;
|
|
916
|
+
this.jobs = jobs;
|
|
917
|
+
}
|
|
918
|
+
static isError(error) {
|
|
919
|
+
return Error.isError(error) && error.name === "BatchJobFailedError" && typeof error.key === "string" && typeof error.jobs === "object";
|
|
920
|
+
}
|
|
921
|
+
};
|
|
922
|
+
/** A validation error naming root field `field` unknown: a host from before it. */
|
|
923
|
+
function queriesUnknownField(error, field) {
|
|
924
|
+
return hasErrorStarting(error, `Cannot query field "${field}" on type "`);
|
|
688
925
|
}
|
|
926
|
+
/** A validation error naming `argument` unknown: a host from before it. */
|
|
927
|
+
function queriesUnknownArgument(error, argument) {
|
|
928
|
+
return hasErrorStarting(error, `Unknown argument "${argument}" on field "`);
|
|
929
|
+
}
|
|
930
|
+
function hasErrorStarting(error, prefix) {
|
|
931
|
+
const errors = error?.response?.errors;
|
|
932
|
+
if (!Array.isArray(errors)) return false;
|
|
933
|
+
return errors.some((entry) => typeof entry?.message === "string" && entry.message.startsWith(prefix));
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* The reactor's `JobFailedError`, rebuilt from a job the Switchboard reported
|
|
937
|
+
* FAILED; this entry imports the reactor for types only. A write handle's
|
|
938
|
+
* stage rejects with it. The message is the job error's message, as the
|
|
939
|
+
* reactor's is.
|
|
940
|
+
*/
|
|
941
|
+
var JobFailedError = class extends Error {
|
|
942
|
+
name = "JobFailedError";
|
|
943
|
+
job;
|
|
944
|
+
constructor(job) {
|
|
945
|
+
super(job.error?.message);
|
|
946
|
+
this.job = job;
|
|
947
|
+
}
|
|
948
|
+
static isError(error) {
|
|
949
|
+
return Error.isError(error) && error.name === "JobFailedError" && typeof error.job === "object";
|
|
950
|
+
}
|
|
951
|
+
};
|
|
952
|
+
//#endregion
|
|
953
|
+
//#region src/constants.ts
|
|
954
|
+
const DEFAULT_DRIVE_EDITOR_ID = "powerhouse/generic-drive-explorer";
|
|
955
|
+
const COMMON_PACKAGE_ID = "powerhouse/common";
|
|
956
|
+
/** Document types that represent a "drive": a container of nodes. */
|
|
957
|
+
const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
|
|
689
958
|
//#endregion
|
|
690
959
|
//#region src/remote-controller/utils.ts
|
|
691
960
|
/** Convert SCREAMING_SNAKE_CASE to camelCase (e.g. "SET_MODEL_NAME" → "setModelName"). */
|
|
@@ -738,7 +1007,11 @@ function convertRemoteOperations(operationsByScope) {
|
|
|
738
1007
|
for (const [scope, remoteOps] of Object.entries(operationsByScope)) operations[scope] = remoteOps.map((op) => remoteOperationToLocal(op));
|
|
739
1008
|
return operations;
|
|
740
1009
|
}
|
|
741
|
-
/**
|
|
1010
|
+
/**
|
|
1011
|
+
* Reconstruct a PHDocument from remote document data and operations; the
|
|
1012
|
+
* header carries the remote protocol versions. `initialDoc` supplies the rest
|
|
1013
|
+
* of the header, and the initial state when the operations do not record one.
|
|
1014
|
+
*/
|
|
742
1015
|
function buildPulledDocument(remoteDoc, operations, initialDoc, branch) {
|
|
743
1016
|
return {
|
|
744
1017
|
header: {
|
|
@@ -750,14 +1023,34 @@ function buildPulledDocument(remoteDoc, operations, initialDoc, branch) {
|
|
|
750
1023
|
createdAtUtcIso: typeof remoteDoc.createdAtUtcIso === "string" ? remoteDoc.createdAtUtcIso : remoteDoc.createdAtUtcIso.toISOString(),
|
|
751
1024
|
lastModifiedAtUtcIso: typeof remoteDoc.lastModifiedAtUtcIso === "string" ? remoteDoc.lastModifiedAtUtcIso : remoteDoc.lastModifiedAtUtcIso.toISOString(),
|
|
752
1025
|
revision: Object.fromEntries(remoteDoc.revisionsList.map((r) => [r.scope, r.revision])),
|
|
753
|
-
branch
|
|
1026
|
+
branch,
|
|
1027
|
+
...remoteDoc.protocolVersions != null ? { protocolVersions: remoteDoc.protocolVersions } : {}
|
|
754
1028
|
},
|
|
755
1029
|
state: remoteDoc.state,
|
|
756
|
-
initialState: initialDoc.initialState,
|
|
1030
|
+
initialState: creationState(operations.document ?? []) ?? initialDoc.initialState,
|
|
757
1031
|
operations,
|
|
758
1032
|
clipboard: []
|
|
759
1033
|
};
|
|
760
1034
|
}
|
|
1035
|
+
/** `document` as created: its header and initial state, without scope operations. */
|
|
1036
|
+
function uncreatedDocument(document) {
|
|
1037
|
+
const { header, initialState } = structuredClone({
|
|
1038
|
+
header: document.header,
|
|
1039
|
+
initialState: document.initialState
|
|
1040
|
+
});
|
|
1041
|
+
return {
|
|
1042
|
+
header,
|
|
1043
|
+
state: initialState,
|
|
1044
|
+
initialState,
|
|
1045
|
+
operations: {},
|
|
1046
|
+
clipboard: []
|
|
1047
|
+
};
|
|
1048
|
+
}
|
|
1049
|
+
/** An uncreated `document` under `policy`; a legacy one keeps its id. */
|
|
1050
|
+
function underSignaturePolicy(document, policy) {
|
|
1051
|
+
if (signaturePolicyOf(document.header) === policy) return document;
|
|
1052
|
+
return withSignaturePolicy(document, policy, { id: document.header.id });
|
|
1053
|
+
}
|
|
761
1054
|
/** Extract revision map from a remote document's revisionsList. */
|
|
762
1055
|
function extractRevisionMap(revisionsList) {
|
|
763
1056
|
return Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));
|
|
@@ -784,8 +1077,8 @@ function hasRevisionConflict(currentRevision, knownRevision, scopes) {
|
|
|
784
1077
|
* `createPresignedHeader`: the creation signature is not fetchable over
|
|
785
1078
|
* GraphQL and is not part of the operation signing payload.
|
|
786
1079
|
*
|
|
787
|
-
* The read path never fetches operation history, so `operations`
|
|
788
|
-
* the document's
|
|
1080
|
+
* The read path never fetches operation history, so `operations` maps each
|
|
1081
|
+
* scope of the document's state and revisions to an empty array.
|
|
789
1082
|
*
|
|
790
1083
|
* `branch` is the branch the document was read from. The GraphQL type does not
|
|
791
1084
|
* carry it, so it has to be passed back in by the caller; it defaults to the
|
|
@@ -797,7 +1090,7 @@ function phDocumentFromGetDocument(document, branch) {
|
|
|
797
1090
|
header: phDocumentHeaderFromGetDocument(document, branch),
|
|
798
1091
|
state,
|
|
799
1092
|
initialState: state,
|
|
800
|
-
operations: emptyOperationsForScopes(document.revisionsList),
|
|
1093
|
+
operations: emptyOperationsForScopes(state, document.revisionsList),
|
|
801
1094
|
clipboard: []
|
|
802
1095
|
};
|
|
803
1096
|
}
|
|
@@ -840,17 +1133,256 @@ function phDocumentHeaderFromGetDocument(document, branch) {
|
|
|
840
1133
|
name: document.name,
|
|
841
1134
|
branch: branch ?? defaultBranch,
|
|
842
1135
|
revision: revisionMapFromRevisionsList(document.revisionsList),
|
|
843
|
-
lastModifiedAtUtcIso: isoStringFromDateTime(document.lastModifiedAtUtcIso)
|
|
1136
|
+
lastModifiedAtUtcIso: isoStringFromDateTime(document.lastModifiedAtUtcIso),
|
|
1137
|
+
...document.meta != null ? { meta: document.meta } : {},
|
|
1138
|
+
...document.protocolVersions != null ? { protocolVersions: document.protocolVersions } : {}
|
|
844
1139
|
};
|
|
845
1140
|
}
|
|
846
|
-
function emptyOperationsForScopes(revisionsList) {
|
|
847
|
-
|
|
1141
|
+
function emptyOperationsForScopes(state, revisionsList) {
|
|
1142
|
+
const scopes = /* @__PURE__ */ new Set([...Object.keys(state), ...revisionsList.map((r) => r.scope)]);
|
|
1143
|
+
return Object.fromEntries([...scopes].map((scope) => [scope, []]));
|
|
848
1144
|
}
|
|
849
1145
|
/** The `DateTime` scalar deserializes as either an ISO string or a `Date`. */
|
|
850
1146
|
function isoStringFromDateTime(value) {
|
|
851
1147
|
return value instanceof Date ? value.toISOString() : value;
|
|
852
1148
|
}
|
|
853
1149
|
//#endregion
|
|
1150
|
+
//#region src/graphql-client/drive-nodes.ts
|
|
1151
|
+
/** Page size {@link GraphQLDriveNodeSource.listAll} reads a drive in. */
|
|
1152
|
+
const LIST_ALL_PAGE_LIMIT = 1e3;
|
|
1153
|
+
const DEFAULT_LIMIT$1 = 100;
|
|
1154
|
+
/**
|
|
1155
|
+
* The reactor subgraph's type-neutral node queries (`driveNodes`, `driveNode`,
|
|
1156
|
+
* `driveDescendants`) as an {@link IDriveNodeSource}, so a browser reads a
|
|
1157
|
+
* legacy drive and a reactor-drive alike. The Switchboard serves only the
|
|
1158
|
+
* nodes the caller may read. Drive ids must be canonical ids, not slugs.
|
|
1159
|
+
*/
|
|
1160
|
+
var GraphQLDriveNodeSource = class {
|
|
1161
|
+
queries;
|
|
1162
|
+
headersFor;
|
|
1163
|
+
constructor(queries, headersFor = () => void 0) {
|
|
1164
|
+
this.queries = queries;
|
|
1165
|
+
this.headersFor = headersFor;
|
|
1166
|
+
}
|
|
1167
|
+
async getNode(driveId, nodeId, signal) {
|
|
1168
|
+
const result = await this.queries.GetDriveNode({
|
|
1169
|
+
driveId,
|
|
1170
|
+
id: nodeId
|
|
1171
|
+
}, this.headersFor(driveId), signal);
|
|
1172
|
+
return result.driveNode ? toRecord(result.driveNode) : void 0;
|
|
1173
|
+
}
|
|
1174
|
+
async listChildren(driveId, parentFolder, paging, signal, kind) {
|
|
1175
|
+
const cursor = startCursor(paging?.cursor);
|
|
1176
|
+
const page = (await this.queries.GetDriveNodes({
|
|
1177
|
+
driveId,
|
|
1178
|
+
...parentFolder === void 0 ? {} : { parentFolder },
|
|
1179
|
+
paging: paging ? {
|
|
1180
|
+
cursor,
|
|
1181
|
+
limit: paging.limit
|
|
1182
|
+
} : void 0,
|
|
1183
|
+
kind: kind === void 0 ? void 0 : kind === "file" ? "FILE" : "FOLDER"
|
|
1184
|
+
}, this.headersFor(driveId), signal)).driveNodes;
|
|
1185
|
+
const nextCursor = page.hasMore ? page.nextCursor ?? void 0 : void 0;
|
|
1186
|
+
return {
|
|
1187
|
+
results: page.results.map(toRecord),
|
|
1188
|
+
options: {
|
|
1189
|
+
cursor,
|
|
1190
|
+
limit: paging?.limit ?? DEFAULT_LIMIT$1
|
|
1191
|
+
},
|
|
1192
|
+
...nextCursor !== void 0 ? { nextCursor } : {}
|
|
1193
|
+
};
|
|
1194
|
+
}
|
|
1195
|
+
async getDescendants(driveId, root, signal) {
|
|
1196
|
+
return (await this.queries.GetDriveDescendants({
|
|
1197
|
+
driveId,
|
|
1198
|
+
root
|
|
1199
|
+
}, this.headersFor(driveId), signal)).driveDescendants.map(toRecord);
|
|
1200
|
+
}
|
|
1201
|
+
async listAll(driveId, signal) {
|
|
1202
|
+
const nodes = [];
|
|
1203
|
+
let cursor = "";
|
|
1204
|
+
for (;;) {
|
|
1205
|
+
const page = await this.listChildren(driveId, void 0, {
|
|
1206
|
+
cursor,
|
|
1207
|
+
limit: LIST_ALL_PAGE_LIMIT
|
|
1208
|
+
}, signal);
|
|
1209
|
+
nodes.push(...page.results);
|
|
1210
|
+
if (page.nextCursor === void 0 || page.nextCursor === cursor) return nodes;
|
|
1211
|
+
cursor = page.nextCursor;
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
};
|
|
1215
|
+
/**
|
|
1216
|
+
* `read.drives` over a node source: the reactor's {@link IDriveReadClient},
|
|
1217
|
+
* answering in the legacy `Node` shape for every drive type.
|
|
1218
|
+
*/
|
|
1219
|
+
var GraphQLDriveReadClient = class {
|
|
1220
|
+
nodes;
|
|
1221
|
+
constructor(nodes) {
|
|
1222
|
+
this.nodes = nodes;
|
|
1223
|
+
}
|
|
1224
|
+
async getNode(driveIdentifier, nodeId, signal) {
|
|
1225
|
+
const record = await this.nodes.getNode(driveIdentifier, nodeId, signal);
|
|
1226
|
+
if (!record) throw new Error(`Node ${nodeId} not found in drive ${driveIdentifier}`);
|
|
1227
|
+
return toLegacyNode(record);
|
|
1228
|
+
}
|
|
1229
|
+
async listNodes(driveIdentifier, parentFolder, paging, signal) {
|
|
1230
|
+
const page = await this.nodes.listChildren(driveIdentifier, parentFolder, paging, signal);
|
|
1231
|
+
const nextCursor = page.nextCursor;
|
|
1232
|
+
return {
|
|
1233
|
+
results: page.results.map(toLegacyNode),
|
|
1234
|
+
options: page.options,
|
|
1235
|
+
...nextCursor !== void 0 ? {
|
|
1236
|
+
nextCursor,
|
|
1237
|
+
next: () => this.listNodes(driveIdentifier, parentFolder, {
|
|
1238
|
+
cursor: nextCursor,
|
|
1239
|
+
limit: page.options.limit
|
|
1240
|
+
}, signal)
|
|
1241
|
+
} : {}
|
|
1242
|
+
};
|
|
1243
|
+
}
|
|
1244
|
+
};
|
|
1245
|
+
/** A node record in the legacy `Node` shape. */
|
|
1246
|
+
function toLegacyNode(node) {
|
|
1247
|
+
if (node.kind === "file") return {
|
|
1248
|
+
id: node.id,
|
|
1249
|
+
kind: "file",
|
|
1250
|
+
name: node.name,
|
|
1251
|
+
parentFolder: node.parentFolder,
|
|
1252
|
+
documentType: node.documentType ?? ""
|
|
1253
|
+
};
|
|
1254
|
+
return {
|
|
1255
|
+
id: node.id,
|
|
1256
|
+
kind: "folder",
|
|
1257
|
+
name: node.name,
|
|
1258
|
+
parentFolder: node.parentFolder
|
|
1259
|
+
};
|
|
1260
|
+
}
|
|
1261
|
+
function toRecord(node) {
|
|
1262
|
+
const base = {
|
|
1263
|
+
id: node.id,
|
|
1264
|
+
driveId: node.driveId,
|
|
1265
|
+
name: node.name,
|
|
1266
|
+
parentFolder: node.parentFolder ?? null
|
|
1267
|
+
};
|
|
1268
|
+
return "documentType" in node ? {
|
|
1269
|
+
...base,
|
|
1270
|
+
kind: "file",
|
|
1271
|
+
documentType: node.documentType
|
|
1272
|
+
} : {
|
|
1273
|
+
...base,
|
|
1274
|
+
kind: "folder"
|
|
1275
|
+
};
|
|
1276
|
+
}
|
|
1277
|
+
/** The offset-style "0" other listings start from means the first page here too. */
|
|
1278
|
+
function startCursor(cursor) {
|
|
1279
|
+
return cursor === void 0 || cursor === "0" ? "" : cursor;
|
|
1280
|
+
}
|
|
1281
|
+
//#endregion
|
|
1282
|
+
//#region src/graphql-client/transport.ts
|
|
1283
|
+
/** The global `fetch`, read per call so a later replacement is honoured. */
|
|
1284
|
+
const globalFetch = (input, init) => globalThis.fetch(input, init);
|
|
1285
|
+
/**
|
|
1286
|
+
* Whether `fetch` here is Node's (undici), which resends a request answered
|
|
1287
|
+
* 421 and can fail the resend of a buffered body. A page, Electron's renderer
|
|
1288
|
+
* included, has a `document`.
|
|
1289
|
+
*/
|
|
1290
|
+
function isNodeFetch() {
|
|
1291
|
+
const scope = globalThis;
|
|
1292
|
+
return typeof scope.process?.versions?.node === "string" && scope.document === void 0;
|
|
1293
|
+
}
|
|
1294
|
+
/**
|
|
1295
|
+
* Sends a string body as a stream, which fetch never resends, so a 421 comes
|
|
1296
|
+
* back as itself. Browsers keep buffered bodies: Chrome streams an upload only
|
|
1297
|
+
* over HTTP/2.
|
|
1298
|
+
*/
|
|
1299
|
+
function withStreamedBodies(inner = globalFetch) {
|
|
1300
|
+
return (input, init) => {
|
|
1301
|
+
const body = init?.body;
|
|
1302
|
+
if (typeof body !== "string") return inner(input, init);
|
|
1303
|
+
const bytes = new TextEncoder().encode(body);
|
|
1304
|
+
return inner(input, {
|
|
1305
|
+
...init,
|
|
1306
|
+
body: new ReadableStream({ start(controller) {
|
|
1307
|
+
controller.enqueue(bytes);
|
|
1308
|
+
controller.close();
|
|
1309
|
+
} }),
|
|
1310
|
+
duplex: "half"
|
|
1311
|
+
});
|
|
1312
|
+
};
|
|
1313
|
+
}
|
|
1314
|
+
const streamedGlobalFetch = withStreamedBodies(globalFetch);
|
|
1315
|
+
/** A Switchboard backend's default transport: streamed bodies under Node only. */
|
|
1316
|
+
const switchboardFetch = (input, init) => isNodeFetch() ? streamedGlobalFetch(input, init) : globalFetch(input, init);
|
|
1317
|
+
/** Bounds each request, headers through body; rejects with a `TimeoutError`. */
|
|
1318
|
+
function withRequestDeadline(timeoutMs, inner = globalFetch) {
|
|
1319
|
+
return (input, init) => {
|
|
1320
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
1321
|
+
const signal = init?.signal ? AbortSignal.any([init.signal, deadline]) : deadline;
|
|
1322
|
+
return inner(input, {
|
|
1323
|
+
...init,
|
|
1324
|
+
signal
|
|
1325
|
+
});
|
|
1326
|
+
};
|
|
1327
|
+
}
|
|
1328
|
+
/**
|
|
1329
|
+
* Whether a request failed at a deadline rather than by its caller's abort:
|
|
1330
|
+
* this transport's own (`TimeoutError`, a DOMException) or the router's probe
|
|
1331
|
+
* deadline (`ProbeTimeoutError`, reactor-router's dispatcher.ts).
|
|
1332
|
+
*/
|
|
1333
|
+
function isDeadlineError(error) {
|
|
1334
|
+
const name = error?.name;
|
|
1335
|
+
return name === "TimeoutError" || name === "ProbeTimeoutError";
|
|
1336
|
+
}
|
|
1337
|
+
//#endregion
|
|
1338
|
+
//#region src/graphql-client/create-defaults.ts
|
|
1339
|
+
/** The host's policy for a new document; a host without `createDefaults` is refused, as a guess could under-sign. */
|
|
1340
|
+
async function readCreateSignaturePolicy(sdk, signal) {
|
|
1341
|
+
const defaults = await readCreateDefaults(sdk, void 0, signal);
|
|
1342
|
+
if (defaults === void 0) throw new GraphQLOperationNotSupportedError("getCreateSignaturePolicy", "the Switchboard predates the createDefaults query");
|
|
1343
|
+
const { signaturePolicy } = defaults;
|
|
1344
|
+
if (!isSignaturePolicy(signaturePolicy)) throw new Error(`The Switchboard answered an unknown create signature policy: ${signaturePolicy}`);
|
|
1345
|
+
return signaturePolicy;
|
|
1346
|
+
}
|
|
1347
|
+
/** The host's per-type selection, capped at what this build runs and fitted to `modules`; baseline from an old host. */
|
|
1348
|
+
async function readCreateProtocolVersions(sdk, { documentType, parentIdentifier }, modules, signal) {
|
|
1349
|
+
const host = await hostCreateProtocolVersions(sdk, documentType, parentIdentifier, signal);
|
|
1350
|
+
const selected = capSelection(host, PEER_CAPABILITIES, localSupports(PEER_CAPABILITIES, FLAGS_FOR_EVERY_VERSION));
|
|
1351
|
+
return fitCreateBaseReducer(selected, documentType, modules, logger);
|
|
1352
|
+
}
|
|
1353
|
+
/** The Switchboard's selection; undefined from a host without `createDefaults`. */
|
|
1354
|
+
async function hostCreateProtocolVersions(sdk, documentType, parentIdentifier, signal) {
|
|
1355
|
+
if (documentType !== void 0) try {
|
|
1356
|
+
return protocolVersionsFrom((await sdk.GetCreateProtocolVersions({
|
|
1357
|
+
documentType,
|
|
1358
|
+
parentIdOrSlug: parentIdentifier
|
|
1359
|
+
}, void 0, signal)).createDefaults.protocolVersions);
|
|
1360
|
+
} catch (error) {
|
|
1361
|
+
if (queriesUnknownField(error, "createDefaults")) return void 0;
|
|
1362
|
+
if (!queriesUnknownArgument(error, "documentType")) throw error;
|
|
1363
|
+
}
|
|
1364
|
+
const defaults = await readCreateDefaults(sdk, parentIdentifier, signal);
|
|
1365
|
+
return defaults && protocolVersionsFrom(defaults.protocolVersions);
|
|
1366
|
+
}
|
|
1367
|
+
/** The reactor-wide `createDefaults`; undefined from a host without the query. */
|
|
1368
|
+
async function readCreateDefaults(sdk, parentIdentifier, signal) {
|
|
1369
|
+
try {
|
|
1370
|
+
return (await sdk.GetCreateDefaults({ parentIdOrSlug: parentIdentifier }, void 0, signal)).createDefaults;
|
|
1371
|
+
} catch (error) {
|
|
1372
|
+
if (queriesUnknownField(error, "createDefaults")) return;
|
|
1373
|
+
throw error;
|
|
1374
|
+
}
|
|
1375
|
+
}
|
|
1376
|
+
function protocolVersionsFrom(value) {
|
|
1377
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("The Switchboard answered malformed create protocol versions");
|
|
1378
|
+
const versions = {};
|
|
1379
|
+
for (const [protocol, version] of Object.entries(value)) {
|
|
1380
|
+
if (typeof version !== "number" || !Number.isInteger(version)) throw new Error(`The Switchboard answered a malformed version for protocol ${protocol}`);
|
|
1381
|
+
versions[protocol] = version;
|
|
1382
|
+
}
|
|
1383
|
+
return versions;
|
|
1384
|
+
}
|
|
1385
|
+
//#endregion
|
|
854
1386
|
//#region src/graphql-client/operations.ts
|
|
855
1387
|
/**
|
|
856
1388
|
* The operation selection of `GetDocumentOperations`, lifted into a fragment so
|
|
@@ -911,14 +1443,14 @@ const ReactorOperationFieldsFragmentDoc = gql`
|
|
|
911
1443
|
*/
|
|
912
1444
|
const MutateDocumentWithOperationsDocument = gql`
|
|
913
1445
|
mutation MutateDocumentWithOperations(
|
|
914
|
-
$
|
|
1446
|
+
$documentIdOrSlug: String!
|
|
915
1447
|
$actions: [ActionInput!]!
|
|
916
1448
|
$sinceRevision: Int
|
|
917
1449
|
$scopes: [String!]
|
|
918
1450
|
$branch: String
|
|
919
1451
|
) {
|
|
920
1452
|
mutateDocument: execute(
|
|
921
|
-
|
|
1453
|
+
documentIdOrSlug: $documentIdOrSlug
|
|
922
1454
|
actions: $actions
|
|
923
1455
|
branch: $branch
|
|
924
1456
|
) {
|
|
@@ -939,6 +1471,27 @@ const MutateDocumentWithOperationsDocument = gql`
|
|
|
939
1471
|
${PhDocumentFieldsFragmentDoc}
|
|
940
1472
|
${ReactorOperationFieldsFragmentDoc}
|
|
941
1473
|
`;
|
|
1474
|
+
/**
|
|
1475
|
+
* `document`, bounded by a consistency token: the read waits until the
|
|
1476
|
+
* Switchboard's read models hold every operation the token names. The
|
|
1477
|
+
* `consistency` argument is additive on the Switchboard; one without it refuses
|
|
1478
|
+
* this document, and the client falls back to the plain `GetDocument`.
|
|
1479
|
+
*/
|
|
1480
|
+
const GetDocumentAtConsistencyDocument = gql`
|
|
1481
|
+
query GetDocumentAtConsistency(
|
|
1482
|
+
$idOrSlug: String!
|
|
1483
|
+
$view: ViewFilterInput
|
|
1484
|
+
$consistency: ConsistencyTokenInput
|
|
1485
|
+
) {
|
|
1486
|
+
document(idOrSlug: $idOrSlug, view: $view, consistency: $consistency) {
|
|
1487
|
+
document {
|
|
1488
|
+
...PHDocumentFields
|
|
1489
|
+
}
|
|
1490
|
+
childIds
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
${PhDocumentFieldsFragmentDoc}
|
|
1494
|
+
`;
|
|
942
1495
|
//#endregion
|
|
943
1496
|
//#region src/graphql-client/signing.ts
|
|
944
1497
|
/**
|
|
@@ -995,7 +1548,8 @@ function snapshotTarget(action, snapshot) {
|
|
|
995
1548
|
*
|
|
996
1549
|
* `UNDO` and `REDO` rewrite history the light read path never fetched (and
|
|
997
1550
|
* the reducer appends no operation for them); `NOOP` is only ever produced
|
|
998
|
-
* by an undo chain;
|
|
1551
|
+
* by an undo chain; a `RETRACT` names a target in that unfetched history; the
|
|
1552
|
+
* document-scope actions run through the reactor's
|
|
999
1553
|
* document-action handler rather than a document-model reducer
|
|
1000
1554
|
* (`DOCUMENT_SCOPE_ACTIONS` in packages/reactor/src/executor/util.ts) and
|
|
1001
1555
|
* `UPGRADE_DOCUMENT` changes which reducer applies mid-batch.
|
|
@@ -1004,6 +1558,7 @@ const unsupportedBatchActions = /* @__PURE__ */ new Set([
|
|
|
1004
1558
|
"UNDO",
|
|
1005
1559
|
"REDO",
|
|
1006
1560
|
"NOOP",
|
|
1561
|
+
"RETRACT",
|
|
1007
1562
|
"CREATE_DOCUMENT",
|
|
1008
1563
|
"DELETE_DOCUMENT",
|
|
1009
1564
|
"UPGRADE_DOCUMENT",
|
|
@@ -1016,10 +1571,10 @@ const unsupportedBatchActions = /* @__PURE__ */ new Set([
|
|
|
1016
1571
|
* carries none.
|
|
1017
1572
|
*
|
|
1018
1573
|
* `baseReducer` reads `baseReducerVersion(document.header)` for every action and
|
|
1019
|
-
* throws when the header has no `protocolVersions
|
|
1020
|
-
* {@link phDocumentFromGetDocument}
|
|
1021
|
-
*
|
|
1022
|
-
*
|
|
1574
|
+
* throws when the header has no `protocolVersions`, which a header built by
|
|
1575
|
+
* {@link phDocumentFromGetDocument} lacks when the server sends none. The
|
|
1576
|
+
* version only selects how UNDO, REDO and RETRACT apply, and every action
|
|
1577
|
+
* reaching the prediction loop is an
|
|
1023
1578
|
* ordinary append-only one, so it cannot change the predicted state here; it is
|
|
1024
1579
|
* passed purely so the lookup does not throw.
|
|
1025
1580
|
*/
|
|
@@ -1066,7 +1621,7 @@ async function prepareSignedActions(actions, snapshot, signer, module, signal) {
|
|
|
1066
1621
|
const before = scopeOperationCount(working, scope);
|
|
1067
1622
|
let next;
|
|
1068
1623
|
try {
|
|
1069
|
-
next = module.reducer(working, signedAction, void 0, { protocolVersion: working.header.protocolVersions
|
|
1624
|
+
next = module.reducer(working, signedAction, void 0, { protocolVersion: resolveBaseReducerVersion(working.header.protocolVersions) ?? predictionProtocolVersion });
|
|
1070
1625
|
} catch (error) {
|
|
1071
1626
|
throw new Error(`cannot sign action ${index} (${action.type}): the ${snapshot.header.documentType} reducer rejected it, so the rest of the batch cannot be predicted`, { cause: error });
|
|
1072
1627
|
}
|
|
@@ -1275,10 +1830,12 @@ function describeGraphQLDocument(document) {
|
|
|
1275
1830
|
var SubgraphSdkRegistry = class {
|
|
1276
1831
|
url;
|
|
1277
1832
|
middleware;
|
|
1833
|
+
fetch;
|
|
1278
1834
|
bindings = /* @__PURE__ */ new Map();
|
|
1279
|
-
constructor(url, middleware) {
|
|
1835
|
+
constructor(url, middleware, fetch) {
|
|
1280
1836
|
this.url = url;
|
|
1281
1837
|
this.middleware = middleware;
|
|
1838
|
+
this.fetch = fetch;
|
|
1282
1839
|
}
|
|
1283
1840
|
/**
|
|
1284
1841
|
* Returns the subgraph's SDK, building it on first use.
|
|
@@ -1303,7 +1860,7 @@ var SubgraphSdkRegistry = class {
|
|
|
1303
1860
|
binding(name) {
|
|
1304
1861
|
const existing = this.bindings.get(name);
|
|
1305
1862
|
if (existing) return existing;
|
|
1306
|
-
const binding = { transport: new GraphQLClient(this.urlFor(name)) };
|
|
1863
|
+
const binding = { transport: new GraphQLClient(this.urlFor(name), { fetch: this.fetch }) };
|
|
1307
1864
|
this.bindings.set(name, binding);
|
|
1308
1865
|
return binding;
|
|
1309
1866
|
}
|
|
@@ -1370,6 +1927,45 @@ function startDocumentChangesSubscription(options) {
|
|
|
1370
1927
|
};
|
|
1371
1928
|
}
|
|
1372
1929
|
/**
|
|
1930
|
+
* Opens the socket write handles wait on. `graphql-ws` multiplexes every
|
|
1931
|
+
* watched job over it and closes it once the last watch stops.
|
|
1932
|
+
*/
|
|
1933
|
+
function createJobChangesSocket(options) {
|
|
1934
|
+
let client;
|
|
1935
|
+
const clientOf = () => client ??= createClient({
|
|
1936
|
+
url: options.wsUrl,
|
|
1937
|
+
connectionParams: options.connectionParams,
|
|
1938
|
+
shouldRetry: (errOrCloseEvent) => isLikeCloseEvent(errOrCloseEvent) && !isAuthRefusalClose(errOrCloseEvent)
|
|
1939
|
+
});
|
|
1940
|
+
return {
|
|
1941
|
+
watch(jobId, onEvent, onError) {
|
|
1942
|
+
const unsubscribe = clientOf().subscribe({
|
|
1943
|
+
operationName: "JobChanges",
|
|
1944
|
+
query: print(JobChangesDocument),
|
|
1945
|
+
variables: { jobId }
|
|
1946
|
+
}, {
|
|
1947
|
+
next: (result) => {
|
|
1948
|
+
const event = result.data?.jobChanges;
|
|
1949
|
+
if (event) onEvent(event);
|
|
1950
|
+
},
|
|
1951
|
+
error: (error) => onError(error),
|
|
1952
|
+
complete: () => void 0
|
|
1953
|
+
});
|
|
1954
|
+
let stopped = false;
|
|
1955
|
+
return () => {
|
|
1956
|
+
if (stopped) return;
|
|
1957
|
+
stopped = true;
|
|
1958
|
+
unsubscribe();
|
|
1959
|
+
};
|
|
1960
|
+
},
|
|
1961
|
+
dispose() {
|
|
1962
|
+
const current = client;
|
|
1963
|
+
client = void 0;
|
|
1964
|
+
current?.dispose();
|
|
1965
|
+
}
|
|
1966
|
+
};
|
|
1967
|
+
}
|
|
1968
|
+
/**
|
|
1373
1969
|
* Derives the websocket endpoint from the GraphQL http endpoint.
|
|
1374
1970
|
*
|
|
1375
1971
|
* `http://host/graphql` becomes `ws://host/graphql/subscriptions`, which is
|
|
@@ -1395,12 +1991,159 @@ function makeAuthConnectionParams(tokenProvider) {
|
|
|
1395
1991
|
};
|
|
1396
1992
|
}
|
|
1397
1993
|
//#endregion
|
|
1994
|
+
//#region src/graphql-client/write-handles.ts
|
|
1995
|
+
/** Whether a job status has reached a stage, FAILED counting as settled. */
|
|
1996
|
+
function settlesGraphQLJobStage(status, stage) {
|
|
1997
|
+
const value = status;
|
|
1998
|
+
if (value === "FAILED" || value === "READ_READY") return true;
|
|
1999
|
+
return stage === "written" && value === "WRITE_READY";
|
|
2000
|
+
}
|
|
2001
|
+
function emptyToken() {
|
|
2002
|
+
return {
|
|
2003
|
+
version: 1,
|
|
2004
|
+
createdAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2005
|
+
coordinates: []
|
|
2006
|
+
};
|
|
2007
|
+
}
|
|
2008
|
+
function abortError(signal) {
|
|
2009
|
+
const reason = signal.reason;
|
|
2010
|
+
return reason instanceof Error ? reason : new Error(String(reason));
|
|
2011
|
+
}
|
|
2012
|
+
/** `promise`, rejected early when `signal` aborts. */
|
|
2013
|
+
function bounded(promise, signal) {
|
|
2014
|
+
if (!signal) return promise;
|
|
2015
|
+
if (signal.aborted) return Promise.reject(abortError(signal));
|
|
2016
|
+
return new Promise((resolve, reject) => {
|
|
2017
|
+
const onAbort = () => reject(abortError(signal));
|
|
2018
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2019
|
+
promise.then((value) => {
|
|
2020
|
+
signal.removeEventListener("abort", onAbort);
|
|
2021
|
+
resolve(value);
|
|
2022
|
+
}, (error) => {
|
|
2023
|
+
signal.removeEventListener("abort", onAbort);
|
|
2024
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
2025
|
+
});
|
|
2026
|
+
});
|
|
2027
|
+
}
|
|
2028
|
+
/**
|
|
2029
|
+
* A write handle over a job the Switchboard accepted (`executeAsync`).
|
|
2030
|
+
*
|
|
2031
|
+
* Each stage is the waiter's: `jobStatus`, woken early by the `jobChanges`
|
|
2032
|
+
* subscription when the client has realtime. Stage promises are created on
|
|
2033
|
+
* first access, so a fire-and-forget caller never owns a rejection. A FAILED
|
|
2034
|
+
* job rejects a stage with {@link JobFailedError}.
|
|
2035
|
+
*
|
|
2036
|
+
* `document()` with no view is read once and shared, so the client's own
|
|
2037
|
+
* change announcement and the caller's read-back cost one request.
|
|
2038
|
+
*/
|
|
2039
|
+
var GraphQLJobWriteHandle = class {
|
|
2040
|
+
job;
|
|
2041
|
+
jobId;
|
|
2042
|
+
documentId;
|
|
2043
|
+
branch;
|
|
2044
|
+
wait;
|
|
2045
|
+
reader;
|
|
2046
|
+
signal;
|
|
2047
|
+
writtenReceipt;
|
|
2048
|
+
readableReceipt;
|
|
2049
|
+
defaultDocument;
|
|
2050
|
+
constructor(job, documentId, branch, wait, reader, signal) {
|
|
2051
|
+
this.job = job;
|
|
2052
|
+
this.jobId = job.id;
|
|
2053
|
+
this.documentId = documentId;
|
|
2054
|
+
this.branch = branch;
|
|
2055
|
+
this.wait = wait;
|
|
2056
|
+
this.reader = reader;
|
|
2057
|
+
this.signal = signal;
|
|
2058
|
+
}
|
|
2059
|
+
get written() {
|
|
2060
|
+
this.writtenReceipt ??= this.receiptAt("written");
|
|
2061
|
+
return this.writtenReceipt;
|
|
2062
|
+
}
|
|
2063
|
+
get readable() {
|
|
2064
|
+
this.readableReceipt ??= this.receiptAt("readable");
|
|
2065
|
+
return this.readableReceipt;
|
|
2066
|
+
}
|
|
2067
|
+
async document(view, signal) {
|
|
2068
|
+
if (view !== void 0) {
|
|
2069
|
+
const receipt = await bounded(this.readable, signal);
|
|
2070
|
+
return this.reader(receipt, view, signal);
|
|
2071
|
+
}
|
|
2072
|
+
this.defaultDocument ??= this.readable.then((receipt) => this.reader(receipt, void 0, void 0));
|
|
2073
|
+
return bounded(this.defaultDocument, signal);
|
|
2074
|
+
}
|
|
2075
|
+
async receiptAt(stage) {
|
|
2076
|
+
const job = await this.wait(this.jobId, stage, this.signal);
|
|
2077
|
+
if (job.status === "FAILED") throw new JobFailedError(job);
|
|
2078
|
+
return {
|
|
2079
|
+
job,
|
|
2080
|
+
token: job.consistencyToken,
|
|
2081
|
+
documentId: this.documentId,
|
|
2082
|
+
branch: this.branch
|
|
2083
|
+
};
|
|
2084
|
+
}
|
|
2085
|
+
};
|
|
2086
|
+
/**
|
|
2087
|
+
* A write handle for a write the Switchboard applied before answering: the
|
|
2088
|
+
* synchronous `createDocument` and `deleteDocument` mutations name no job. Both
|
|
2089
|
+
* stages are settled; `jobId` is empty and the receipt's job is a READ_READY
|
|
2090
|
+
* placeholder with an empty token, as the reactor's own settled handle has.
|
|
2091
|
+
*/
|
|
2092
|
+
var GraphQLSettledWriteHandle = class {
|
|
2093
|
+
jobId = "";
|
|
2094
|
+
documentId;
|
|
2095
|
+
branch;
|
|
2096
|
+
receipt;
|
|
2097
|
+
reader;
|
|
2098
|
+
constructor(documentId, branch, reader) {
|
|
2099
|
+
this.documentId = documentId;
|
|
2100
|
+
this.branch = branch;
|
|
2101
|
+
this.reader = reader;
|
|
2102
|
+
const token = emptyToken();
|
|
2103
|
+
this.receipt = {
|
|
2104
|
+
job: {
|
|
2105
|
+
id: "",
|
|
2106
|
+
documentId,
|
|
2107
|
+
status: "READ_READY",
|
|
2108
|
+
createdAtUtcIso: token.createdAtUtcIso,
|
|
2109
|
+
consistencyToken: token,
|
|
2110
|
+
meta: {
|
|
2111
|
+
batchId: "",
|
|
2112
|
+
batchJobIds: []
|
|
2113
|
+
}
|
|
2114
|
+
},
|
|
2115
|
+
token,
|
|
2116
|
+
documentId,
|
|
2117
|
+
branch
|
|
2118
|
+
};
|
|
2119
|
+
}
|
|
2120
|
+
get written() {
|
|
2121
|
+
return Promise.resolve(this.receipt);
|
|
2122
|
+
}
|
|
2123
|
+
get readable() {
|
|
2124
|
+
return Promise.resolve(this.receipt);
|
|
2125
|
+
}
|
|
2126
|
+
document(view, signal) {
|
|
2127
|
+
return this.reader(this.receipt, view, signal);
|
|
2128
|
+
}
|
|
2129
|
+
};
|
|
2130
|
+
//#endregion
|
|
1398
2131
|
//#region src/graphql-client/graphql-reactor-client.ts
|
|
2132
|
+
const BUILT_IN_MODELS = [driveDocumentModelModule];
|
|
1399
2133
|
/** Paging defaults, matching the reactor's own client. */
|
|
1400
2134
|
const defaultPaging = {
|
|
1401
2135
|
cursor: "0",
|
|
1402
2136
|
limit: 100
|
|
1403
2137
|
};
|
|
2138
|
+
const JOB_POLL_INTERVAL_MS = 250;
|
|
2139
|
+
/** The first `jobStatus` poll of a write handle's stage wait, doubling from here. */
|
|
2140
|
+
const STAGE_POLL_START_MS = 25;
|
|
2141
|
+
/**
|
|
2142
|
+
* The longest a stage wait sleeps between `jobStatus` polls while the
|
|
2143
|
+
* `jobChanges` subscription is up: the subscription wakes it early, and the
|
|
2144
|
+
* poll is the safety net for an event that raced the subscription.
|
|
2145
|
+
*/
|
|
2146
|
+
const STAGE_POLL_REALTIME_MAX_MS = 1e3;
|
|
1404
2147
|
/**
|
|
1405
2148
|
* The marker {@link isGraphQLReactorClient} looks for.
|
|
1406
2149
|
*
|
|
@@ -1421,40 +2164,169 @@ var GraphQLReactorClient = class {
|
|
|
1421
2164
|
/** See {@link isGraphQLReactorClient}. */
|
|
1422
2165
|
[graphQLReactorClientBrand] = true;
|
|
1423
2166
|
sdk;
|
|
2167
|
+
/** For `executeBatch`, the one write a request waits for: see {@link batchRequestTimeoutMs}. */
|
|
2168
|
+
batchSdk;
|
|
1424
2169
|
subgraphs;
|
|
1425
2170
|
listeners = [];
|
|
1426
2171
|
tokenProvider;
|
|
1427
2172
|
subscriptionsUrl;
|
|
1428
2173
|
documentModels;
|
|
1429
|
-
|
|
2174
|
+
resolveSigner;
|
|
2175
|
+
driveIdFor;
|
|
2176
|
+
undoRedoChains = /* @__PURE__ */ new Map();
|
|
1430
2177
|
stopRealtime;
|
|
1431
2178
|
realtimeStarted = false;
|
|
1432
2179
|
realtimeGeneration = 0;
|
|
1433
2180
|
realtimeErrorLogged = false;
|
|
1434
2181
|
/** Whether the last socket died because the Switchboard refused its credentials. */
|
|
1435
2182
|
realtimeRefusedCredentials = false;
|
|
2183
|
+
/** The socket write handles wait on; opened by the first stage wait. */
|
|
2184
|
+
jobSocket;
|
|
2185
|
+
/** Set once the `jobChanges` subscription failed; stage waits then only poll. */
|
|
2186
|
+
jobRealtimeBroken = false;
|
|
2187
|
+
/** Set once the Switchboard refused the `document` query's `consistency` argument. */
|
|
2188
|
+
consistencyUnsupported = false;
|
|
2189
|
+
driveNodes;
|
|
2190
|
+
/**
|
|
2191
|
+
* The read half: the reads the hooks make. Every method is this client's
|
|
2192
|
+
* own; nothing that writes is reachable from it.
|
|
2193
|
+
*/
|
|
2194
|
+
read;
|
|
2195
|
+
/**
|
|
2196
|
+
* The write half. `execute` submits through `executeAsync` and hands back a
|
|
2197
|
+
* handle whose `written` and `readable` resolve from `jobStatus`, woken by
|
|
2198
|
+
* the `jobChanges` subscription when realtime is on, and whose `document()`
|
|
2199
|
+
* runs the `document` query bounded by the receipt's token. `create` and
|
|
2200
|
+
* `deleteDocument` have no asynchronous mutation: they run the synchronous
|
|
2201
|
+
* ones and hand back a settled handle.
|
|
2202
|
+
*/
|
|
2203
|
+
write;
|
|
1436
2204
|
constructor(options) {
|
|
1437
2205
|
this.tokenProvider = options.tokenProvider ?? ambientRenownTokenProvider;
|
|
1438
|
-
|
|
1439
|
-
this.
|
|
2206
|
+
const models = options.documentModels;
|
|
2207
|
+
if (typeof models === "function") this.documentModels = models;
|
|
2208
|
+
else {
|
|
2209
|
+
const copied = [...models ?? []];
|
|
2210
|
+
this.documentModels = () => copied;
|
|
2211
|
+
}
|
|
2212
|
+
const signer = options.signer;
|
|
2213
|
+
this.resolveSigner = typeof signer === "function" ? signer : signer ? () => signer : ambientRenownSigner;
|
|
2214
|
+
this.driveIdFor = options.driveIdFor;
|
|
1440
2215
|
this.subscriptionsUrl = options.realtime === false ? void 0 : options.subscriptionsUrl ?? subscriptionsUrlFromGraphqlUrl(options.url);
|
|
1441
|
-
const middleware = makeAuthMiddleware(this.tokenProvider);
|
|
1442
|
-
|
|
1443
|
-
this.
|
|
2216
|
+
const middleware = withWrongBackendErrors(makeAuthMiddleware(this.tokenProvider));
|
|
2217
|
+
const fetch = options.requestTimeoutMs === void 0 ? options.fetch : withRequestDeadline(options.requestTimeoutMs, options.fetch);
|
|
2218
|
+
this.sdk = options.graphqlClient ?? createClient$1(new GraphQLClient(options.url, { fetch }), middleware);
|
|
2219
|
+
this.batchSdk = options.graphqlClient !== void 0 || options.batchRequestTimeoutMs === void 0 ? this.sdk : createClient$1(new GraphQLClient(options.url, { fetch: withRequestDeadline(options.batchRequestTimeoutMs, options.fetch) }), middleware);
|
|
2220
|
+
this.subgraphs = new SubgraphSdkRegistry(options.url, middleware, fetch);
|
|
2221
|
+
this.driveNodes = new GraphQLDriveNodeSource(this.sdk, driveIdHeaders);
|
|
2222
|
+
this.read = new GraphQLReadHalf(this, this.driveNodes);
|
|
2223
|
+
this.write = {
|
|
2224
|
+
execute: (documentIdentifier, branch, actions, signal) => this.submitExecute(documentIdentifier, branch, actions, signal),
|
|
2225
|
+
create: (document, parentIdentifier, signal) => this.submitCreate(document, parentIdentifier, signal),
|
|
2226
|
+
deleteDocument: (identifier, propagate, signal) => this.submitDeleteDocument(identifier, propagate, signal)
|
|
2227
|
+
};
|
|
2228
|
+
}
|
|
2229
|
+
/**
|
|
2230
|
+
* The Switchboard's drive node queries as a node source, for every drive
|
|
2231
|
+
* type. `read.drives` answers from it.
|
|
2232
|
+
*/
|
|
2233
|
+
nodeSource() {
|
|
2234
|
+
return this.driveNodes;
|
|
1444
2235
|
}
|
|
1445
|
-
|
|
2236
|
+
/**
|
|
2237
|
+
* Reads a document. With a consistency token that names any coordinate, the
|
|
2238
|
+
* Switchboard waits until its read models hold them; one without the
|
|
2239
|
+
* `document` query's `consistency` argument is read without it, which after
|
|
2240
|
+
* a write's `readable` stage still sees the write on a single node.
|
|
2241
|
+
*/
|
|
2242
|
+
async get(identifier, view, signal, consistencyToken) {
|
|
1446
2243
|
const viewInput = viewFilterInputFromViewFilter(view);
|
|
1447
|
-
const document = (await this.sdk.GetDocument({
|
|
1448
|
-
identifier,
|
|
2244
|
+
const document = (consistencyToken && consistencyToken.coordinates.length > 0 ? await this.getDocumentAtConsistency(identifier, viewInput, consistencyToken, signal) : await this.sdk.GetDocument({
|
|
2245
|
+
idOrSlug: identifier,
|
|
1449
2246
|
view: viewInput
|
|
1450
2247
|
}, void 0, signal)).document;
|
|
1451
2248
|
if (!document) throw new Error(`Document not found: ${identifier}`);
|
|
1452
2249
|
return phDocumentFromGetDocument(document.document, view?.branch);
|
|
1453
2250
|
}
|
|
2251
|
+
/**
|
|
2252
|
+
* Reads documents by id, in the order given; throws if any is missing. Each
|
|
2253
|
+
* chunk of {@link GET_MANY_CHUNK_SIZE} ids is one request holding an aliased
|
|
2254
|
+
* `document` field per id, with the selection and arguments `get` sends.
|
|
2255
|
+
*/
|
|
2256
|
+
async getMany(documentIds, view, signal, consistencyToken) {
|
|
2257
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2258
|
+
const token = consistencyToken && consistencyToken.coordinates.length > 0 ? consistencyToken : void 0;
|
|
2259
|
+
const chunks = [];
|
|
2260
|
+
for (let i = 0; i < documentIds.length; i += GET_MANY_CHUNK_SIZE) chunks.push(documentIds.slice(i, i + GET_MANY_CHUNK_SIZE));
|
|
2261
|
+
return (await Promise.all(chunks.map((chunk) => this.getDocumentChunk(chunk, viewInput, token, signal)))).flat().map((document) => phDocumentFromGetDocument(document, view?.branch));
|
|
2262
|
+
}
|
|
2263
|
+
/** One chunk of `getMany`, with the `consistency` argument while the Switchboard accepts it. */
|
|
2264
|
+
async getDocumentChunk(identifiers, view, token, signal) {
|
|
2265
|
+
if (token && !this.consistencyUnsupported) try {
|
|
2266
|
+
return await this.runGetDocuments(identifiers, view, consistencyInputFromToken(token), signal);
|
|
2267
|
+
} catch (error) {
|
|
2268
|
+
if (!refusesConsistencyArgument(error)) throw error;
|
|
2269
|
+
this.consistencyUnsupported = true;
|
|
2270
|
+
}
|
|
2271
|
+
return this.runGetDocuments(identifiers, view, void 0, signal);
|
|
2272
|
+
}
|
|
2273
|
+
async runGetDocuments(identifiers, view, consistency, signal) {
|
|
2274
|
+
const variables = { view };
|
|
2275
|
+
const definitions = ["$view: ViewFilterInput"];
|
|
2276
|
+
let consistencyArgument = "";
|
|
2277
|
+
if (consistency) {
|
|
2278
|
+
variables.consistency = consistency;
|
|
2279
|
+
definitions.push("$consistency: ConsistencyTokenInput");
|
|
2280
|
+
consistencyArgument = ", consistency: $consistency";
|
|
2281
|
+
}
|
|
2282
|
+
const fields = identifiers.map((identifier, i) => {
|
|
2283
|
+
variables[`id${i}`] = identifier;
|
|
2284
|
+
definitions.push(`$id${i}: String!`);
|
|
2285
|
+
return `d${i}: document(idOrSlug: $id${i}, view: $view${consistencyArgument}) { document { ...PHDocumentFields } childIds }`;
|
|
2286
|
+
});
|
|
2287
|
+
const query = [
|
|
2288
|
+
`query GetDocuments(${definitions.join(", ")}) {`,
|
|
2289
|
+
...fields,
|
|
2290
|
+
"}",
|
|
2291
|
+
PH_DOCUMENT_FIELDS_SOURCE
|
|
2292
|
+
].join("\n");
|
|
2293
|
+
const data = await this.sdk.RunDocument({
|
|
2294
|
+
operationName: "GetDocuments",
|
|
2295
|
+
operationType: "query",
|
|
2296
|
+
document: query,
|
|
2297
|
+
variables,
|
|
2298
|
+
signal
|
|
2299
|
+
});
|
|
2300
|
+
return identifiers.map((identifier, i) => {
|
|
2301
|
+
const result = data[`d${i}`];
|
|
2302
|
+
if (!result) throw new Error(`Document not found: ${identifier}`);
|
|
2303
|
+
return result.document;
|
|
2304
|
+
});
|
|
2305
|
+
}
|
|
2306
|
+
/**
|
|
2307
|
+
* Whether the Switchboard would serve the document to this client's caller,
|
|
2308
|
+
* from its `documentServed` query: the same read gate `find` passes. Absent
|
|
2309
|
+
* or withheld is `false`; a failure to decide throws.
|
|
2310
|
+
*
|
|
2311
|
+
* A point-in-time view throws {@link GraphQLOperationNotSupportedError}, as
|
|
2312
|
+
* does a Switchboard without the query.
|
|
2313
|
+
*/
|
|
2314
|
+
async isServed(identifier, view, signal) {
|
|
2315
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2316
|
+
try {
|
|
2317
|
+
return (await this.sdk.GetDocumentServed({
|
|
2318
|
+
idOrSlug: identifier,
|
|
2319
|
+
view: viewInput
|
|
2320
|
+
}, void 0, signal)).documentServed;
|
|
2321
|
+
} catch (error) {
|
|
2322
|
+
if (queriesUnknownField(error, "documentServed")) throw new GraphQLOperationNotSupportedError("isServed", "the Switchboard predates the documentServed query");
|
|
2323
|
+
throw error;
|
|
2324
|
+
}
|
|
2325
|
+
}
|
|
1454
2326
|
async getOperations(documentIdentifier, view, filter, paging, signal) {
|
|
1455
2327
|
const viewInput = viewFilterInputFromViewFilter(view);
|
|
1456
2328
|
const operationsFilter = {
|
|
1457
|
-
|
|
2329
|
+
documentIdOrSlug: documentIdentifier,
|
|
1458
2330
|
branch: viewInput?.branch,
|
|
1459
2331
|
scopes: viewInput?.scopes,
|
|
1460
2332
|
actionTypes: filter?.actionTypes,
|
|
@@ -1478,11 +2350,99 @@ var GraphQLReactorClient = class {
|
|
|
1478
2350
|
}, signal) : void 0
|
|
1479
2351
|
};
|
|
1480
2352
|
}
|
|
2353
|
+
/**
|
|
2354
|
+
* Filters documents by criteria over the Switchboard's `findDocuments` query.
|
|
2355
|
+
*
|
|
2356
|
+
* The query filters by `type` and `parentId` only, at head. A search naming
|
|
2357
|
+
* `ids` or `slugs` (present, whatever its length) and a point-in-time view are
|
|
2358
|
+
* each by-contract limitations the query cannot express -- running it anyway
|
|
2359
|
+
* would return every document instead of the named ones, or head instead of
|
|
2360
|
+
* the asked-for revision, a silently wrong answer. {@link findIsServableOverGraphQL}
|
|
2361
|
+
* is the single predicate that decides this, and an unservable `find` throws
|
|
2362
|
+
* {@link GraphQLOperationNotSupportedError}. Drive enumeration itself filters
|
|
2363
|
+
* by `type` at head, which is served.
|
|
2364
|
+
*/
|
|
2365
|
+
async find(search, view, paging, signal) {
|
|
2366
|
+
if (!findIsServableOverGraphQL(search, view)) throw new GraphQLOperationNotSupportedError("find", searchNamesIdentifiers(search) ? "it cannot filter by ids or slugs: the Switchboard findDocuments query filters only by type and parentId" : "point-in-time views are not supported by GraphQLReactorClient");
|
|
2367
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2368
|
+
const effectivePaging = paging ?? defaultPaging;
|
|
2369
|
+
const result = await this.sdk.FindDocuments({
|
|
2370
|
+
search: {
|
|
2371
|
+
type: search.type,
|
|
2372
|
+
parentId: search.parentId
|
|
2373
|
+
},
|
|
2374
|
+
view: viewInput,
|
|
2375
|
+
paging: pagingInputFromPaging(effectivePaging)
|
|
2376
|
+
}, search.parentId === void 0 ? void 0 : this.driveIdHeaders({
|
|
2377
|
+
method: "find",
|
|
2378
|
+
parentId: search.parentId
|
|
2379
|
+
}), signal);
|
|
2380
|
+
return this.toDocumentResults(result.findDocuments, effectivePaging, view?.branch, (cursor, limit) => this.find(search, view, {
|
|
2381
|
+
cursor,
|
|
2382
|
+
limit
|
|
2383
|
+
}, signal));
|
|
2384
|
+
}
|
|
2385
|
+
async getOutgoingRelationships(sourceIdentifier, relationshipType, view, paging, signal) {
|
|
2386
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2387
|
+
const result = await this.sdk.GetDocumentOutgoingRelationships({
|
|
2388
|
+
sourceIdOrSlug: sourceIdentifier,
|
|
2389
|
+
relationshipType,
|
|
2390
|
+
view: viewInput,
|
|
2391
|
+
paging: pagingInputFromPaging(paging)
|
|
2392
|
+
}, void 0, signal);
|
|
2393
|
+
return this.toDocumentResults(result.documentOutgoingRelationships, paging ?? defaultPaging, view?.branch, (cursor, limit) => this.getOutgoingRelationships(sourceIdentifier, relationshipType, view, {
|
|
2394
|
+
cursor,
|
|
2395
|
+
limit
|
|
2396
|
+
}, signal));
|
|
2397
|
+
}
|
|
2398
|
+
async getIncomingRelationships(targetIdentifier, relationshipType, view, paging, signal) {
|
|
2399
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2400
|
+
const result = await this.sdk.GetDocumentIncomingRelationships({
|
|
2401
|
+
targetIdOrSlug: targetIdentifier,
|
|
2402
|
+
relationshipType,
|
|
2403
|
+
view: viewInput,
|
|
2404
|
+
paging: pagingInputFromPaging(paging)
|
|
2405
|
+
}, void 0, signal);
|
|
2406
|
+
return this.toDocumentResults(result.documentIncomingRelationships, paging ?? defaultPaging, view?.branch, (cursor, limit) => this.getIncomingRelationships(targetIdentifier, relationshipType, view, {
|
|
2407
|
+
cursor,
|
|
2408
|
+
limit
|
|
2409
|
+
}, signal));
|
|
2410
|
+
}
|
|
2411
|
+
async getOutgoingRelationshipEdges(sourceIdentifier, relationshipType, view, paging, signal) {
|
|
2412
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2413
|
+
const result = await this.sdk.GetDocumentOutgoingRelationshipEdges({
|
|
2414
|
+
sourceIdOrSlug: sourceIdentifier,
|
|
2415
|
+
relationshipType,
|
|
2416
|
+
view: viewInput,
|
|
2417
|
+
paging: pagingInputFromPaging(paging)
|
|
2418
|
+
}, void 0, signal);
|
|
2419
|
+
return this.toRelationshipResults(result.documentOutgoingRelationshipEdges, paging ?? defaultPaging, (cursor, limit) => this.getOutgoingRelationshipEdges(sourceIdentifier, relationshipType, view, {
|
|
2420
|
+
cursor,
|
|
2421
|
+
limit
|
|
2422
|
+
}, signal));
|
|
2423
|
+
}
|
|
2424
|
+
async getIncomingRelationshipEdges(targetIdentifier, relationshipType, view, paging, signal) {
|
|
2425
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2426
|
+
const result = await this.sdk.GetDocumentIncomingRelationshipEdges({
|
|
2427
|
+
targetIdOrSlug: targetIdentifier,
|
|
2428
|
+
relationshipType,
|
|
2429
|
+
view: viewInput,
|
|
2430
|
+
paging: pagingInputFromPaging(paging)
|
|
2431
|
+
}, void 0, signal);
|
|
2432
|
+
return this.toRelationshipResults(result.documentIncomingRelationshipEdges, paging ?? defaultPaging, (cursor, limit) => this.getIncomingRelationshipEdges(targetIdentifier, relationshipType, view, {
|
|
2433
|
+
cursor,
|
|
2434
|
+
limit
|
|
2435
|
+
}, signal));
|
|
2436
|
+
}
|
|
1481
2437
|
async create(document, parentIdentifier, signal) {
|
|
1482
2438
|
const created = phDocumentFromGetDocument((await this.sdk.CreateDocument({
|
|
1483
2439
|
document,
|
|
1484
|
-
parentIdentifier
|
|
1485
|
-
},
|
|
2440
|
+
parentIdOrSlug: parentIdentifier
|
|
2441
|
+
}, this.driveIdHeaders({
|
|
2442
|
+
method: "create",
|
|
2443
|
+
documentId: document.header.id || void 0,
|
|
2444
|
+
parentId: parentIdentifier
|
|
2445
|
+
}, isDrive(document) && parentIdentifier === void 0 ? document.header.id : void 0), signal)).createDocument);
|
|
1486
2446
|
this.emitChange({
|
|
1487
2447
|
type: DOCUMENT_CHANGE_TYPE.Created,
|
|
1488
2448
|
documents: [created]
|
|
@@ -1509,8 +2469,8 @@ var GraphQLReactorClient = class {
|
|
|
1509
2469
|
async execute(documentIdentifier, branch, actions, signal) {
|
|
1510
2470
|
const document = await this.get(documentIdentifier, { branch }, signal);
|
|
1511
2471
|
const variables = {
|
|
1512
|
-
documentIdentifier,
|
|
1513
|
-
actions: (await prepareActionsForPush(actions, document, this.documentModels, this.
|
|
2472
|
+
documentIdOrSlug: documentIdentifier,
|
|
2473
|
+
actions: (await prepareActionsForPush(actions, document, this.documentModels(), this.resolveSigner(), signal)).map(toTransportAction),
|
|
1514
2474
|
sinceRevision: sinceRevisionForActions(document, actions),
|
|
1515
2475
|
scopes: scopesForActions(actions),
|
|
1516
2476
|
branch
|
|
@@ -1520,6 +2480,10 @@ var GraphQLReactorClient = class {
|
|
|
1520
2480
|
operationType: "mutation",
|
|
1521
2481
|
document: MutateDocumentWithOperationsDocument,
|
|
1522
2482
|
variables,
|
|
2483
|
+
requestHeaders: this.driveIdHeaders({
|
|
2484
|
+
method: "execute",
|
|
2485
|
+
documentId: documentIdentifier
|
|
2486
|
+
}, isDrive(document) ? document.header.id : void 0),
|
|
1523
2487
|
signal
|
|
1524
2488
|
})).mutateDocument;
|
|
1525
2489
|
const updated = phDocumentFromMutation(mutated, mutated.operations?.items ?? [], branch);
|
|
@@ -1530,6 +2494,281 @@ var GraphQLReactorClient = class {
|
|
|
1530
2494
|
return updated;
|
|
1531
2495
|
}
|
|
1532
2496
|
/**
|
|
2497
|
+
* What `execute` writes, without waiting: returns the job once the Switchboard
|
|
2498
|
+
* holds it, so a write slower than one request's deadline still lands and is
|
|
2499
|
+
* reported. It is announced as the write half's `execute` announces it.
|
|
2500
|
+
*/
|
|
2501
|
+
async executeAsync(documentIdentifier, branch, actions, signal) {
|
|
2502
|
+
return (await this.submitExecute(documentIdentifier, branch, actions, signal)).job;
|
|
2503
|
+
}
|
|
2504
|
+
/**
|
|
2505
|
+
* Undoes the last applied operation of `scope` under this client's own
|
|
2506
|
+
* signature: UNDO below base-reducer 3; on it, a RETRACT of the target the
|
|
2507
|
+
* Switchboard resolves with {@link undoRedoTargets}. One at a time per
|
|
2508
|
+
* document, scope and branch. A stale target is refused, not re-resolved.
|
|
2509
|
+
*/
|
|
2510
|
+
undo(documentIdentifier, scope = "global", branch = "main", signal) {
|
|
2511
|
+
return this.undoOrRedo("UNDO", documentIdentifier, scope, branch, signal);
|
|
2512
|
+
}
|
|
2513
|
+
/** Redoes the last undo of `scope`; see {@link undo}. */
|
|
2514
|
+
redo(documentIdentifier, scope = "global", branch = "main", signal) {
|
|
2515
|
+
return this.undoOrRedo("REDO", documentIdentifier, scope, branch, signal);
|
|
2516
|
+
}
|
|
2517
|
+
/** Exact on base-reducer 3, from the targets the Switchboard resolves. */
|
|
2518
|
+
async undoRedoAvailability(documentIdentifier, scope = "global", branch = "main", signal) {
|
|
2519
|
+
const { caps, document } = await this.undoCapabilities(documentIdentifier, branch, signal);
|
|
2520
|
+
const targets = undoNeedsTargets(caps) ? await this.undoRedoTargets(documentIdentifier, scope, { branch }, signal) : void 0;
|
|
2521
|
+
return undoRedoAvailabilityOf(caps, targets, document.header.revision[scope] ?? 0, scope in document.state);
|
|
2522
|
+
}
|
|
2523
|
+
/**
|
|
2524
|
+
* The rows a base-reducer 3 undo and redo would retract, resolved by the
|
|
2525
|
+
* Switchboard as the caller. A Switchboard without the query is refused
|
|
2526
|
+
* with {@link GraphQLOperationNotSupportedError}. `view.subject` is not
|
|
2527
|
+
* sent: the Switchboard reads the caller from the bearer.
|
|
2528
|
+
*/
|
|
2529
|
+
async undoRedoTargets(documentIdentifier, scope = "global", view, signal) {
|
|
2530
|
+
try {
|
|
2531
|
+
const { undoRedoTargets } = await this.sdk.GetUndoRedoTargets({
|
|
2532
|
+
documentIdOrSlug: documentIdentifier,
|
|
2533
|
+
scope,
|
|
2534
|
+
branch: view?.branch
|
|
2535
|
+
}, void 0, signal);
|
|
2536
|
+
return {
|
|
2537
|
+
...undoRedoTargets.undoTarget ? { undoTarget: undoRedoTargets.undoTarget } : {},
|
|
2538
|
+
...undoRedoTargets.redoTarget ? { redoTarget: undoRedoTargets.redoTarget } : {}
|
|
2539
|
+
};
|
|
2540
|
+
} catch (error) {
|
|
2541
|
+
if (queriesUnknownField(error, "undoRedoTargets")) throw new GraphQLOperationNotSupportedError("undoRedoTargets", "the Switchboard predates the undoRedoTargets query");
|
|
2542
|
+
throw error;
|
|
2543
|
+
}
|
|
2544
|
+
}
|
|
2545
|
+
undoOrRedo(type, documentIdentifier, scope, branch, signal) {
|
|
2546
|
+
return serializeByKey(this.undoRedoChains, JSON.stringify([
|
|
2547
|
+
documentIdentifier,
|
|
2548
|
+
scope,
|
|
2549
|
+
branch
|
|
2550
|
+
]), async () => {
|
|
2551
|
+
const { caps } = await this.undoCapabilities(documentIdentifier, branch, signal);
|
|
2552
|
+
const targets = undoNeedsTargets(caps) ? await this.undoRedoTargets(documentIdentifier, scope, { branch }, signal) : void 0;
|
|
2553
|
+
return this.execute(documentIdentifier, branch, undoRedoActions(caps, type, scope, targets), signal);
|
|
2554
|
+
}, signal);
|
|
2555
|
+
}
|
|
2556
|
+
/** An older Switchboard serves no header versions; then CREATE_DOCUMENT names them, else it is 1. */
|
|
2557
|
+
async undoCapabilities(documentIdentifier, branch, signal) {
|
|
2558
|
+
const document = await this.get(documentIdentifier, { branch }, signal);
|
|
2559
|
+
const { header } = document;
|
|
2560
|
+
const fromHeader = undoCapabilitiesOf(header);
|
|
2561
|
+
if (fromHeader) return {
|
|
2562
|
+
caps: fromHeader,
|
|
2563
|
+
document
|
|
2564
|
+
};
|
|
2565
|
+
const create = (await this.getOperations(documentIdentifier, {
|
|
2566
|
+
branch,
|
|
2567
|
+
scopes: ["document"]
|
|
2568
|
+
}, void 0, {
|
|
2569
|
+
cursor: "0",
|
|
2570
|
+
limit: 1
|
|
2571
|
+
}, signal)).results.at(0)?.action;
|
|
2572
|
+
const input = create?.type === "CREATE_DOCUMENT" ? create.input : void 0;
|
|
2573
|
+
return {
|
|
2574
|
+
caps: undoCapabilitiesOf(header, input) ?? capabilitiesOf(1),
|
|
2575
|
+
document
|
|
2576
|
+
};
|
|
2577
|
+
}
|
|
2578
|
+
/**
|
|
2579
|
+
* Runs multiple mutation jobs in dependency order over the Switchboard's
|
|
2580
|
+
* `executeBatch` mutation and waits for all to settle, returning the result
|
|
2581
|
+
* shaped like `IReactor.executeBatch`'s so the reference `DriveClient`
|
|
2582
|
+
* consumes it unchanged.
|
|
2583
|
+
*
|
|
2584
|
+
* Not atomic: each job commits on its own and a failed job still releases
|
|
2585
|
+
* its dependents. A FAILED job throws {@link BatchJobFailedError}, naming the
|
|
2586
|
+
* first failed plan key and carrying every job's final state.
|
|
2587
|
+
*
|
|
2588
|
+
* Each job's actions are signed independently for the job's own
|
|
2589
|
+
* `(documentId, branch)` target -- the per-action signing the reactor's own
|
|
2590
|
+
* `signActions` does, not the batch state-prediction `execute` uses for a
|
|
2591
|
+
* multi-action push. A drive job such as `addFile`'s is `CREATE_DOCUMENT` +
|
|
2592
|
+
* `UPGRADE_DOCUMENT` + `ADD_RELATIONSHIP`, which the prediction path rejects
|
|
2593
|
+
* outright and which has no fetchable baseline to stamp against. The reactor
|
|
2594
|
+
* records but does not verify the stamped previous-state head, so signing
|
|
2595
|
+
* each action bare is exactly what the in-process `DriveClient` relies on.
|
|
2596
|
+
*
|
|
2597
|
+
* The mutation is synchronous server-side: a job it returns is already
|
|
2598
|
+
* settled, so {@link waitForJob} resolves from it without polling.
|
|
2599
|
+
*/
|
|
2600
|
+
async executeBatch(request, signal) {
|
|
2601
|
+
const signer = this.resolveSigner();
|
|
2602
|
+
const jobInputs = await Promise.all(request.jobs.map(async (job, index) => {
|
|
2603
|
+
const documentId = await this.batchWriteTarget(job, request.jobs.slice(0, index), signer, signal);
|
|
2604
|
+
const actions = await this.signBatchJobActions({
|
|
2605
|
+
...job,
|
|
2606
|
+
documentId
|
|
2607
|
+
}, signer, signal);
|
|
2608
|
+
return {
|
|
2609
|
+
key: job.key,
|
|
2610
|
+
documentIdOrSlug: documentId,
|
|
2611
|
+
scope: job.scope,
|
|
2612
|
+
branch: job.branch,
|
|
2613
|
+
actions: actions.map(toTransportAction),
|
|
2614
|
+
dependsOn: job.dependsOn
|
|
2615
|
+
};
|
|
2616
|
+
}));
|
|
2617
|
+
const result = await this.batchSdk.ExecuteBatch({ jobs: jobInputs }, this.driveIdHeaders({
|
|
2618
|
+
method: "executeBatch",
|
|
2619
|
+
jobs: jobInputs.map((job) => ({ documentId: job.documentIdOrSlug }))
|
|
2620
|
+
}), signal);
|
|
2621
|
+
const jobs = {};
|
|
2622
|
+
for (const entry of result.executeBatch.jobs) jobs[entry.key] = jobInfoFromGql(entry.job);
|
|
2623
|
+
await this.announceBatch(request, jobs, signal);
|
|
2624
|
+
const failed = request.jobs.find((job) => jobs[job.key]?.status === "FAILED");
|
|
2625
|
+
if (failed) throw new BatchJobFailedError(failed.key, jobs);
|
|
2626
|
+
return { jobs };
|
|
2627
|
+
}
|
|
2628
|
+
/** The job as `jobStatus` reports it now; `undefined` when it reports none. */
|
|
2629
|
+
async getJob(jobId, signal) {
|
|
2630
|
+
const result = await this.sdk.GetJobStatus({ jobId }, void 0, signal);
|
|
2631
|
+
return result.jobStatus ? jobInfoFromGql(result.jobStatus) : void 0;
|
|
2632
|
+
}
|
|
2633
|
+
/** The job as `jobStatus` reports it now; throws when it reports none. */
|
|
2634
|
+
async getJobStatus(jobId, signal) {
|
|
2635
|
+
const job = await this.getJob(jobId, signal);
|
|
2636
|
+
if (!job) throw new Error(`Job not found: ${jobId}`);
|
|
2637
|
+
return job;
|
|
2638
|
+
}
|
|
2639
|
+
/** Polls `jobStatus` until the job is READ_READY or FAILED. */
|
|
2640
|
+
async waitForJob(jobOrId, signal) {
|
|
2641
|
+
if (typeof jobOrId !== "string" && isSettled(jobOrId)) return jobOrId;
|
|
2642
|
+
const jobId = typeof jobOrId === "string" ? jobOrId : jobOrId.id;
|
|
2643
|
+
for (;;) {
|
|
2644
|
+
const result = await this.sdk.GetJobStatus({ jobId }, void 0, signal);
|
|
2645
|
+
if (!result.jobStatus) throw new Error(`Job not found: ${jobId}`);
|
|
2646
|
+
const job = jobInfoFromGql(result.jobStatus);
|
|
2647
|
+
if (isSettled(job)) return job;
|
|
2648
|
+
await delay(JOB_POLL_INTERVAL_MS, signal);
|
|
2649
|
+
}
|
|
2650
|
+
}
|
|
2651
|
+
/** See {@link readCreateSignaturePolicy}. */
|
|
2652
|
+
getCreateSignaturePolicy() {
|
|
2653
|
+
return readCreateSignaturePolicy(this.sdk);
|
|
2654
|
+
}
|
|
2655
|
+
/** See {@link readCreateProtocolVersions}; fitted to `documentModels`. */
|
|
2656
|
+
getCreateProtocolVersions(options, signal) {
|
|
2657
|
+
return readCreateProtocolVersions(this.sdk, options, this.documentModels(), signal);
|
|
2658
|
+
}
|
|
2659
|
+
/** See {@link IReactorClient.newDocument}; the module comes from `documentModels`. */
|
|
2660
|
+
async newDocument(documentType, options, signal) {
|
|
2661
|
+
const module = selectDocumentModelModule([...this.documentModels(), ...BUILT_IN_MODELS], documentType, options?.documentModelVersion);
|
|
2662
|
+
const [policy, versions] = await Promise.all([options?.signaturePolicy ?? this.getCreateSignaturePolicy(), this.getCreateProtocolVersions({
|
|
2663
|
+
documentType,
|
|
2664
|
+
parentIdentifier: options?.parentIdentifier
|
|
2665
|
+
}, signal)]);
|
|
2666
|
+
return headNewDocument(module, options, policy, versions);
|
|
2667
|
+
}
|
|
2668
|
+
/**
|
|
2669
|
+
* Sets or, with `null`, clears the preferred editor as a client-signed
|
|
2670
|
+
* action, as the in-process client does.
|
|
2671
|
+
*/
|
|
2672
|
+
setPreferredEditor(documentIdentifier, preferredEditor, branch = "main", signal) {
|
|
2673
|
+
return this.execute(documentIdentifier, branch, [actions.setPreferredEditor(preferredEditor)], signal);
|
|
2674
|
+
}
|
|
2675
|
+
/** The `Drive-Id` header for a call: the client's own proof, else the hook's. */
|
|
2676
|
+
driveIdHeaders(call, proven) {
|
|
2677
|
+
const hinted = this.driveIdFor?.(call);
|
|
2678
|
+
if (proven) {
|
|
2679
|
+
if (hinted && hinted !== proven) logger.warn("GraphQLReactorClient: driveIdFor named @hinted for @method, which belongs to drive @proven; sending the proven drive", hinted, call.method, proven);
|
|
2680
|
+
return driveIdHeaders(proven);
|
|
2681
|
+
}
|
|
2682
|
+
return hinted ? driveIdHeaders(hinted) : void 0;
|
|
2683
|
+
}
|
|
2684
|
+
/**
|
|
2685
|
+
* Emits the changes the batch's settled jobs made, as `create` and `execute`
|
|
2686
|
+
* do, so a cache is invalidated without a realtime socket. The documents a
|
|
2687
|
+
* job wrote to are its own and those its consistency token names.
|
|
2688
|
+
*/
|
|
2689
|
+
async announceBatch(request, jobs, signal) {
|
|
2690
|
+
if (this.listeners.length === 0) return;
|
|
2691
|
+
const deleted = /* @__PURE__ */ new Set();
|
|
2692
|
+
const created = /* @__PURE__ */ new Map();
|
|
2693
|
+
const touched = /* @__PURE__ */ new Map();
|
|
2694
|
+
const keyOf = (written) => `${written.branch}\u0000${written.documentId}`;
|
|
2695
|
+
for (const job of request.jobs) {
|
|
2696
|
+
const info = jobs[job.key];
|
|
2697
|
+
if (!info || info.status !== "READ_READY") continue;
|
|
2698
|
+
const types = new Set(job.actions.map((action) => action.type));
|
|
2699
|
+
if (types.has("DELETE_DOCUMENT")) {
|
|
2700
|
+
deleted.add(info.documentId);
|
|
2701
|
+
continue;
|
|
2702
|
+
}
|
|
2703
|
+
const own = {
|
|
2704
|
+
documentId: info.documentId,
|
|
2705
|
+
branch: job.branch
|
|
2706
|
+
};
|
|
2707
|
+
if (types.has("CREATE_DOCUMENT")) created.set(keyOf(own), own);
|
|
2708
|
+
touched.set(keyOf(own), own);
|
|
2709
|
+
for (const { documentId, branch } of info.consistencyToken.coordinates) touched.set(keyOf({
|
|
2710
|
+
documentId,
|
|
2711
|
+
branch
|
|
2712
|
+
}), {
|
|
2713
|
+
documentId,
|
|
2714
|
+
branch
|
|
2715
|
+
});
|
|
2716
|
+
}
|
|
2717
|
+
for (const documentId of deleted) this.emitChange({
|
|
2718
|
+
type: DOCUMENT_CHANGE_TYPE.Deleted,
|
|
2719
|
+
documents: [],
|
|
2720
|
+
context: { childId: documentId }
|
|
2721
|
+
});
|
|
2722
|
+
const read = async ({ documentId, branch }) => {
|
|
2723
|
+
try {
|
|
2724
|
+
return await this.get(documentId, { branch }, signal);
|
|
2725
|
+
} catch (error) {
|
|
2726
|
+
logger.warn("GraphQLReactorClient: could not read @documentId on @branch to announce a batch change: @error", documentId, branch, error);
|
|
2727
|
+
return;
|
|
2728
|
+
}
|
|
2729
|
+
};
|
|
2730
|
+
const readAll = async (written) => (await Promise.all(written.map(read))).filter((document) => document !== void 0);
|
|
2731
|
+
const [createdDocuments, updatedDocuments] = await Promise.all([readAll([...created.values()].filter((w) => !deleted.has(w.documentId))), readAll([...touched.entries()].filter(([key, w]) => !deleted.has(w.documentId) && !created.has(key)).map(([, w]) => w))]);
|
|
2732
|
+
if (createdDocuments.length > 0) this.emitChange({
|
|
2733
|
+
type: DOCUMENT_CHANGE_TYPE.Created,
|
|
2734
|
+
documents: createdDocuments
|
|
2735
|
+
});
|
|
2736
|
+
if (updatedDocuments.length > 0) this.emitChange({
|
|
2737
|
+
type: DOCUMENT_CHANGE_TYPE.Updated,
|
|
2738
|
+
documents: updatedDocuments
|
|
2739
|
+
});
|
|
2740
|
+
}
|
|
2741
|
+
/**
|
|
2742
|
+
* The id a job's actions are signed for: a signature covers the document id,
|
|
2743
|
+
* and the server resolves a slug before verifying. A document created by this
|
|
2744
|
+
* job or an earlier one is named by its id. When the server has no such
|
|
2745
|
+
* document the identifier is used as given, and the server decides; any
|
|
2746
|
+
* other failure to read it throws, so nothing is signed for a slug.
|
|
2747
|
+
*/
|
|
2748
|
+
async batchWriteTarget(job, earlier, signer, signal) {
|
|
2749
|
+
const creates = (plan) => plan.documentId === job.documentId && plan.actions.some((action) => action.type === "CREATE_DOCUMENT");
|
|
2750
|
+
if (!signer || job.actions.every(isActionSigned) || creates(job) || earlier.some(creates)) return job.documentId;
|
|
2751
|
+
return (await this.sdk.GetDocument({
|
|
2752
|
+
idOrSlug: job.documentId,
|
|
2753
|
+
view: viewFilterInputFromViewFilter({ branch: job.branch })
|
|
2754
|
+
}, void 0, signal)).document?.document.id ?? job.documentId;
|
|
2755
|
+
}
|
|
2756
|
+
/**
|
|
2757
|
+
* Signs one batch job's actions for the job's own log.
|
|
2758
|
+
*
|
|
2759
|
+
* Each action is signed on its own for `(documentId, branch)`, the same
|
|
2760
|
+
* per-action signing the reactor's `signActions` does: no state prediction
|
|
2761
|
+
* across the job, so a job carrying a `CREATE_DOCUMENT` the push-prediction
|
|
2762
|
+
* path rejects still signs. An action already signed under a key is left
|
|
2763
|
+
* as it is: the reference `DriveClient` signs its jobs before handing them
|
|
2764
|
+
* here. With no signer the actions pass through unsigned, matching
|
|
2765
|
+
* {@link execute}.
|
|
2766
|
+
*/
|
|
2767
|
+
async signBatchJobActions(job, signer, signal) {
|
|
2768
|
+
if (!signer) return job.actions;
|
|
2769
|
+
return Promise.all(job.actions.map((action) => isActionSigned(action) ? Promise.resolve(action) : signStampedAction(action, signer, actionSigningTarget(action, job.documentId, job.branch), signal)));
|
|
2770
|
+
}
|
|
2771
|
+
/**
|
|
1533
2772
|
* Deletes a document and announces it as a `Deleted` event.
|
|
1534
2773
|
*
|
|
1535
2774
|
* Pass a document id. The server resolves a slug just as happily, but
|
|
@@ -1540,9 +2779,12 @@ var GraphQLReactorClient = class {
|
|
|
1540
2779
|
*/
|
|
1541
2780
|
async deleteDocument(identifier, propagate, signal) {
|
|
1542
2781
|
await this.sdk.DeleteDocument({
|
|
1543
|
-
identifier,
|
|
2782
|
+
idOrSlug: identifier,
|
|
1544
2783
|
propagate: propagationModeInput(propagate)
|
|
1545
|
-
},
|
|
2784
|
+
}, this.driveIdHeaders({
|
|
2785
|
+
method: "deleteDocument",
|
|
2786
|
+
documentId: identifier
|
|
2787
|
+
}), signal);
|
|
1546
2788
|
this.emitChange({
|
|
1547
2789
|
type: DOCUMENT_CHANGE_TYPE.Deleted,
|
|
1548
2790
|
documents: [],
|
|
@@ -1600,6 +2842,8 @@ var GraphQLReactorClient = class {
|
|
|
1600
2842
|
*/
|
|
1601
2843
|
dispose() {
|
|
1602
2844
|
this.teardownRealtime();
|
|
2845
|
+
this.jobSocket?.dispose();
|
|
2846
|
+
this.jobSocket = void 0;
|
|
1603
2847
|
}
|
|
1604
2848
|
/**
|
|
1605
2849
|
* Binds a project's generated SDK to this client's transport and auth.
|
|
@@ -1638,6 +2882,157 @@ var GraphQLReactorClient = class {
|
|
|
1638
2882
|
});
|
|
1639
2883
|
}
|
|
1640
2884
|
/**
|
|
2885
|
+
* Shapes a document result page into the reactor's {@link PagedResults}.
|
|
2886
|
+
*
|
|
2887
|
+
* The items carry the same `PHDocumentFields` fragment as `get`, so the same
|
|
2888
|
+
* adapter rebuilds each one. `hasNextPage` gates the cursor exactly as
|
|
2889
|
+
* `getOperations` does: no cursor means no `next`.
|
|
2890
|
+
*/
|
|
2891
|
+
toDocumentResults(page, effectivePaging, branch, next) {
|
|
2892
|
+
const nextCursor = page.hasNextPage ? page.cursor ?? void 0 : void 0;
|
|
2893
|
+
return {
|
|
2894
|
+
results: page.items.map((item) => phDocumentFromGetDocument(item, branch)),
|
|
2895
|
+
options: effectivePaging,
|
|
2896
|
+
nextCursor,
|
|
2897
|
+
next: nextCursor ? () => next(nextCursor, effectivePaging.limit) : void 0
|
|
2898
|
+
};
|
|
2899
|
+
}
|
|
2900
|
+
/**
|
|
2901
|
+
* Shapes a relationship-edge result page into the reactor's
|
|
2902
|
+
* {@link PagedResults}, restoring each edge's `Date` fields.
|
|
2903
|
+
*/
|
|
2904
|
+
toRelationshipResults(page, effectivePaging, next) {
|
|
2905
|
+
const nextCursor = page.hasNextPage ? page.cursor ?? void 0 : void 0;
|
|
2906
|
+
return {
|
|
2907
|
+
results: page.items.map((edge) => documentRelationshipFromEdge(edge)),
|
|
2908
|
+
options: effectivePaging,
|
|
2909
|
+
nextCursor,
|
|
2910
|
+
next: nextCursor ? () => next(nextCursor, effectivePaging.limit) : void 0
|
|
2911
|
+
};
|
|
2912
|
+
}
|
|
2913
|
+
/**
|
|
2914
|
+
* The write half's `execute`: signs as the facade's `execute` does, submits
|
|
2915
|
+
* through `executeAsync` and returns once the job is accepted. When anyone
|
|
2916
|
+
* subscribes, the document is read back once the job is readable and
|
|
2917
|
+
* announced as `Updated`, as the facade's `execute` announces it; the handle
|
|
2918
|
+
* shares that read with its own `document()`.
|
|
2919
|
+
*/
|
|
2920
|
+
async submitExecute(documentIdentifier, branch, actions, signal) {
|
|
2921
|
+
const document = await this.get(documentIdentifier, { branch }, signal);
|
|
2922
|
+
const preparedActions = await prepareActionsForPush(actions, document, this.documentModels(), this.resolveSigner(), signal);
|
|
2923
|
+
const handle = new GraphQLJobWriteHandle(jobInfoFromGql((await this.sdk.MutateDocumentAsync({
|
|
2924
|
+
documentIdOrSlug: documentIdentifier,
|
|
2925
|
+
actions: preparedActions.map(toTransportAction),
|
|
2926
|
+
branch
|
|
2927
|
+
}, this.driveIdHeaders({
|
|
2928
|
+
method: "execute",
|
|
2929
|
+
documentId: documentIdentifier
|
|
2930
|
+
}, isDrive(document) ? document.header.id : void 0), signal)).mutateDocumentAsync), document.header.id, branch, (jobId, stage, stageSignal) => this.waitForStage(jobId, stage, stageSignal), this.handleReader(document.header.id), signal);
|
|
2931
|
+
if (this.listeners.length > 0) this.announceWrite(handle);
|
|
2932
|
+
return handle;
|
|
2933
|
+
}
|
|
2934
|
+
/** The write half's `create`: the synchronous mutation, a settled handle. */
|
|
2935
|
+
async submitCreate(document, parentIdentifier, signal) {
|
|
2936
|
+
const created = await this.create(document, parentIdentifier, signal);
|
|
2937
|
+
return new GraphQLSettledWriteHandle(created.header.id, created.header.branch || "main", this.handleReader(created.header.id));
|
|
2938
|
+
}
|
|
2939
|
+
/** The write half's `deleteDocument`: the synchronous mutation, a settled handle. */
|
|
2940
|
+
async submitDeleteDocument(identifier, propagate, signal) {
|
|
2941
|
+
await this.deleteDocument(identifier, propagate, signal);
|
|
2942
|
+
return new GraphQLSettledWriteHandle(identifier, "main", this.handleReader(identifier));
|
|
2943
|
+
}
|
|
2944
|
+
/** Reads a write's document back, bounded by its receipt's token. */
|
|
2945
|
+
handleReader(documentId) {
|
|
2946
|
+
return (receipt, view, signal) => this.get(documentId, {
|
|
2947
|
+
...view,
|
|
2948
|
+
branch: receipt.branch
|
|
2949
|
+
}, signal, receipt.token);
|
|
2950
|
+
}
|
|
2951
|
+
/** Announces a write's document as `Updated` once it is readable. */
|
|
2952
|
+
async announceWrite(handle) {
|
|
2953
|
+
let document;
|
|
2954
|
+
try {
|
|
2955
|
+
document = await handle.document();
|
|
2956
|
+
} catch (error) {
|
|
2957
|
+
logger.warn("GraphQLReactorClient: could not read @documentId back to announce a write: @error", handle.documentId, error);
|
|
2958
|
+
return;
|
|
2959
|
+
}
|
|
2960
|
+
this.emitChange({
|
|
2961
|
+
type: DOCUMENT_CHANGE_TYPE.Updated,
|
|
2962
|
+
documents: [document]
|
|
2963
|
+
});
|
|
2964
|
+
}
|
|
2965
|
+
/**
|
|
2966
|
+
* Waits for a job to settle a stage, resolving with a FAILED job too. Polls
|
|
2967
|
+
* `jobStatus` with a doubling interval; with realtime on, a `jobChanges`
|
|
2968
|
+
* event for the job wakes the wait early and the interval is only a safety
|
|
2969
|
+
* net. A failed subscription is logged once and the wait keeps polling.
|
|
2970
|
+
*/
|
|
2971
|
+
async waitForStage(jobId, stage, signal) {
|
|
2972
|
+
const wakers = /* @__PURE__ */ new Set();
|
|
2973
|
+
const stopWatching = this.watchJob(jobId, () => {
|
|
2974
|
+
for (const wake of [...wakers]) wake();
|
|
2975
|
+
});
|
|
2976
|
+
try {
|
|
2977
|
+
let interval = STAGE_POLL_START_MS;
|
|
2978
|
+
for (;;) {
|
|
2979
|
+
const job = await this.getJobStatus(jobId, signal);
|
|
2980
|
+
if (settlesGraphQLJobStage(job.status, stage)) return job;
|
|
2981
|
+
await sleepUntilWoken(interval, wakers, signal);
|
|
2982
|
+
const max = stopWatching && !this.jobRealtimeBroken ? STAGE_POLL_REALTIME_MAX_MS : JOB_POLL_INTERVAL_MS;
|
|
2983
|
+
interval = Math.min(interval * 2, max);
|
|
2984
|
+
}
|
|
2985
|
+
} finally {
|
|
2986
|
+
stopWatching?.();
|
|
2987
|
+
}
|
|
2988
|
+
}
|
|
2989
|
+
/**
|
|
2990
|
+
* Subscribes to one job's `jobChanges` when realtime is on and the
|
|
2991
|
+
* subscription has not failed before. Returns the stop function, or
|
|
2992
|
+
* undefined when nothing was subscribed.
|
|
2993
|
+
*/
|
|
2994
|
+
watchJob(jobId, onChange) {
|
|
2995
|
+
if (!this.subscriptionsUrl || this.jobRealtimeBroken) return;
|
|
2996
|
+
this.jobSocket ??= createJobChangesSocket({
|
|
2997
|
+
wsUrl: this.subscriptionsUrl,
|
|
2998
|
+
connectionParams: makeAuthConnectionParams(this.tokenProvider)
|
|
2999
|
+
});
|
|
3000
|
+
return this.jobSocket.watch(jobId, () => onChange(), (error) => {
|
|
3001
|
+
if (this.jobRealtimeBroken) return;
|
|
3002
|
+
this.jobRealtimeBroken = true;
|
|
3003
|
+
logger.warn("GraphQLReactorClient: realtime job changes are unavailable, write handles fall back to polling jobStatus", error);
|
|
3004
|
+
});
|
|
3005
|
+
}
|
|
3006
|
+
/**
|
|
3007
|
+
* The `document` query with the `consistency` argument, or without it once
|
|
3008
|
+
* the Switchboard has refused the argument.
|
|
3009
|
+
*/
|
|
3010
|
+
async getDocumentAtConsistency(identifier, view, token, signal) {
|
|
3011
|
+
if (!this.consistencyUnsupported) {
|
|
3012
|
+
const variables = {
|
|
3013
|
+
idOrSlug: identifier,
|
|
3014
|
+
view,
|
|
3015
|
+
consistency: consistencyInputFromToken(token)
|
|
3016
|
+
};
|
|
3017
|
+
try {
|
|
3018
|
+
return await this.sdk.RunDocument({
|
|
3019
|
+
operationName: "GetDocumentAtConsistency",
|
|
3020
|
+
operationType: "query",
|
|
3021
|
+
document: GetDocumentAtConsistencyDocument,
|
|
3022
|
+
variables,
|
|
3023
|
+
signal
|
|
3024
|
+
});
|
|
3025
|
+
} catch (error) {
|
|
3026
|
+
if (!refusesConsistencyArgument(error)) throw error;
|
|
3027
|
+
this.consistencyUnsupported = true;
|
|
3028
|
+
}
|
|
3029
|
+
}
|
|
3030
|
+
return this.sdk.GetDocument({
|
|
3031
|
+
idOrSlug: identifier,
|
|
3032
|
+
view
|
|
3033
|
+
}, void 0, signal);
|
|
3034
|
+
}
|
|
3035
|
+
/**
|
|
1641
3036
|
* Opens the realtime socket on the first subscriber.
|
|
1642
3037
|
*
|
|
1643
3038
|
* The subscription is a firehose - no `search` argument - and this client
|
|
@@ -1756,6 +3151,98 @@ var GraphQLReactorClient = class {
|
|
|
1756
3151
|
}
|
|
1757
3152
|
};
|
|
1758
3153
|
/**
|
|
3154
|
+
* The read half of {@link GraphQLReactorClient}: every read is the client's
|
|
3155
|
+
* own, and nothing that writes is reachable from it.
|
|
3156
|
+
*/
|
|
3157
|
+
var GraphQLReadHalf = class {
|
|
3158
|
+
client;
|
|
3159
|
+
drives;
|
|
3160
|
+
constructor(client, nodes) {
|
|
3161
|
+
this.client = client;
|
|
3162
|
+
this.drives = new GraphQLDriveReadClient(nodes);
|
|
3163
|
+
}
|
|
3164
|
+
get(identifier, view, signal, consistencyToken) {
|
|
3165
|
+
return this.client.get(identifier, view, signal, consistencyToken);
|
|
3166
|
+
}
|
|
3167
|
+
getMany(documentIds, view, signal, consistencyToken) {
|
|
3168
|
+
return this.client.getMany(documentIds, view, signal, consistencyToken);
|
|
3169
|
+
}
|
|
3170
|
+
find(search, view, paging, signal) {
|
|
3171
|
+
return this.client.find(search, view, paging, signal);
|
|
3172
|
+
}
|
|
3173
|
+
getOperations(documentIdentifier, view, filter, paging, signal) {
|
|
3174
|
+
return this.client.getOperations(documentIdentifier, view, filter, paging, signal);
|
|
3175
|
+
}
|
|
3176
|
+
subscribe(search, callback, view) {
|
|
3177
|
+
return this.client.subscribe(search, callback, view);
|
|
3178
|
+
}
|
|
3179
|
+
waitForJob(jobId, signal) {
|
|
3180
|
+
return this.client.waitForJob(jobId, signal);
|
|
3181
|
+
}
|
|
3182
|
+
getJobStatus(jobId, signal) {
|
|
3183
|
+
return this.client.getJobStatus(jobId, signal);
|
|
3184
|
+
}
|
|
3185
|
+
};
|
|
3186
|
+
/**
|
|
3187
|
+
* Sleeps for `ms`, or less when a waker in `wakers` fires first. Each sleep
|
|
3188
|
+
* adds its own waker and removes it when it ends.
|
|
3189
|
+
*/
|
|
3190
|
+
function sleepUntilWoken(ms, wakers, signal) {
|
|
3191
|
+
return new Promise((resolve, reject) => {
|
|
3192
|
+
if (signal?.aborted) {
|
|
3193
|
+
reject(abortReason(signal));
|
|
3194
|
+
return;
|
|
3195
|
+
}
|
|
3196
|
+
const finish = () => {
|
|
3197
|
+
clearTimeout(timer);
|
|
3198
|
+
wakers.delete(finish);
|
|
3199
|
+
signal?.removeEventListener("abort", onAbort);
|
|
3200
|
+
};
|
|
3201
|
+
const wake = () => {
|
|
3202
|
+
finish();
|
|
3203
|
+
resolve();
|
|
3204
|
+
};
|
|
3205
|
+
const onAbort = () => {
|
|
3206
|
+
finish();
|
|
3207
|
+
if (signal) reject(abortReason(signal));
|
|
3208
|
+
};
|
|
3209
|
+
const timer = setTimeout(wake, ms);
|
|
3210
|
+
wakers.add(wake);
|
|
3211
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3212
|
+
});
|
|
3213
|
+
}
|
|
3214
|
+
/**
|
|
3215
|
+
* Whether a request failed because the Switchboard's `document` query has no
|
|
3216
|
+
* `consistency` argument, or its schema no `ConsistencyTokenInput`.
|
|
3217
|
+
*/
|
|
3218
|
+
/** The most ids one `getMany` request reads. */
|
|
3219
|
+
const GET_MANY_CHUNK_SIZE = 50;
|
|
3220
|
+
const PH_DOCUMENT_FIELDS_SOURCE = print(PhDocumentFieldsFragmentDoc);
|
|
3221
|
+
function consistencyInputFromToken(token) {
|
|
3222
|
+
return {
|
|
3223
|
+
version: token.version,
|
|
3224
|
+
createdAtUtcIso: token.createdAtUtcIso,
|
|
3225
|
+
coordinates: token.coordinates.map((coordinate) => ({
|
|
3226
|
+
documentId: coordinate.documentId,
|
|
3227
|
+
scope: coordinate.scope,
|
|
3228
|
+
branch: coordinate.branch,
|
|
3229
|
+
operationIndex: coordinate.operationIndex
|
|
3230
|
+
}))
|
|
3231
|
+
};
|
|
3232
|
+
}
|
|
3233
|
+
function refusesConsistencyArgument(error) {
|
|
3234
|
+
const errors = error?.response?.errors;
|
|
3235
|
+
if (!Array.isArray(errors)) return false;
|
|
3236
|
+
return errors.some((entry) => {
|
|
3237
|
+
const message = entry?.message;
|
|
3238
|
+
return typeof message === "string" && (message.includes("\"consistency\"") || message.includes("\"ConsistencyTokenInput\""));
|
|
3239
|
+
});
|
|
3240
|
+
}
|
|
3241
|
+
/** {@link GraphQLReactorClient.nodeSource}, as a function. */
|
|
3242
|
+
function createGraphQLDriveNodeSource(client) {
|
|
3243
|
+
return client.nodeSource();
|
|
3244
|
+
}
|
|
3245
|
+
/**
|
|
1759
3246
|
* Whether a value is a {@link GraphQLReactorClient}, including one built by
|
|
1760
3247
|
* another copy of this module.
|
|
1761
3248
|
*
|
|
@@ -1809,7 +3296,7 @@ function eventMatchesSearch(event, search) {
|
|
|
1809
3296
|
*/
|
|
1810
3297
|
function viewFilterInputFromViewFilter(view) {
|
|
1811
3298
|
if (!view) return;
|
|
1812
|
-
if (view
|
|
3299
|
+
if (viewIsPointInTime(view)) throw new GraphQLOperationNotSupportedError("view", "point-in-time views are not supported by GraphQLReactorClient");
|
|
1813
3300
|
if (view.branch === void 0 && view.scopes === void 0) return;
|
|
1814
3301
|
return {
|
|
1815
3302
|
branch: view.branch,
|
|
@@ -1824,6 +3311,71 @@ function pagingInputFromPaging(paging) {
|
|
|
1824
3311
|
};
|
|
1825
3312
|
}
|
|
1826
3313
|
/**
|
|
3314
|
+
* Whether a search names `ids` or `slugs`, which the Switchboard `findDocuments`
|
|
3315
|
+
* query cannot honour (it filters by `type` and `parentId`).
|
|
3316
|
+
*
|
|
3317
|
+
* The test is PRESENCE, not length: the reactor `find` contract
|
|
3318
|
+
* (`packages/reactor/src/core/reactor.ts`) dispatches on `search.ids` /
|
|
3319
|
+
* `search.slugs` being present, so `find({ ids: [] })` is an identifier search
|
|
3320
|
+
* that must yield the empty set -- not a plain type query over every document.
|
|
3321
|
+
* The GraphQL surface cannot express an identifier search at all, so a present
|
|
3322
|
+
* (even empty) `ids`/`slugs` is refused rather than served as the wrong query.
|
|
3323
|
+
*/
|
|
3324
|
+
function searchNamesIdentifiers(search) {
|
|
3325
|
+
return search.ids !== void 0 || search.slugs !== void 0;
|
|
3326
|
+
}
|
|
3327
|
+
/** Whether a view asks for a point-in-time read the GraphQL surface cannot express. */
|
|
3328
|
+
function viewIsPointInTime(view) {
|
|
3329
|
+
return view?.revision !== void 0;
|
|
3330
|
+
}
|
|
3331
|
+
/**
|
|
3332
|
+
* The single source of truth for whether the Switchboard `findDocuments` query
|
|
3333
|
+
* can serve a `find`. It is servable iff the search names neither `ids` nor
|
|
3334
|
+
* `slugs` (present, regardless of length) AND the view is not point-in-time:
|
|
3335
|
+
* each is a by-contract limitation of a surface that filters only by
|
|
3336
|
+
* `type`/`parentId` at head. Exported so a caller can route around an
|
|
3337
|
+
* unservable search instead of catching the error `find` throws for it.
|
|
3338
|
+
*/
|
|
3339
|
+
function findIsServableOverGraphQL(search, view) {
|
|
3340
|
+
return !searchNamesIdentifiers(search) && !viewIsPointInTime(view);
|
|
3341
|
+
}
|
|
3342
|
+
/** Rebuilds a relationship edge from its GraphQL fields. */
|
|
3343
|
+
function documentRelationshipFromEdge(edge) {
|
|
3344
|
+
const relationship = {
|
|
3345
|
+
sourceId: edge.sourceId,
|
|
3346
|
+
targetId: edge.targetId,
|
|
3347
|
+
relationshipType: edge.relationshipType,
|
|
3348
|
+
createdAt: dateFromDateTime(edge.createdAt),
|
|
3349
|
+
updatedAt: dateFromDateTime(edge.updatedAt)
|
|
3350
|
+
};
|
|
3351
|
+
const metadata = edge.metadata;
|
|
3352
|
+
if (isPlainObject(metadata)) relationship.metadata = metadata;
|
|
3353
|
+
return relationship;
|
|
3354
|
+
}
|
|
3355
|
+
/**
|
|
3356
|
+
* Restores a `Date` from the `DateTime` scalar, which deserializes as either an
|
|
3357
|
+
* ISO string or a `Date`, reusing the get-path's {@link isoStringFromDateTime}.
|
|
3358
|
+
*
|
|
3359
|
+
* A null, absent or unparseable value is a malformed timestamp from the server,
|
|
3360
|
+
* not something to coerce to the epoch or an `Invalid Date`: it throws, so the
|
|
3361
|
+
* malformed edge surfaces as a genuine failure rather than a silently-wrong
|
|
3362
|
+
* `DocumentRelationship`.
|
|
3363
|
+
*/
|
|
3364
|
+
function dateFromDateTime(value) {
|
|
3365
|
+
if (value === null || value === void 0) throw new Error("relationship edge is missing a required DateTime timestamp");
|
|
3366
|
+
const date = new Date(isoStringFromDateTime(value));
|
|
3367
|
+
if (Number.isNaN(date.getTime())) throw new Error(`relationship edge carries an unparseable DateTime timestamp: ${String(value)}`);
|
|
3368
|
+
return date;
|
|
3369
|
+
}
|
|
3370
|
+
/**
|
|
3371
|
+
* Whether a JSON value is a plain object, so relationship `metadata` is assigned
|
|
3372
|
+
* only when it is one. A non-object JSON scalar (string, number, array, null)
|
|
3373
|
+
* is dropped exactly as a null is, rather than cast to `Record` and trusted.
|
|
3374
|
+
*/
|
|
3375
|
+
function isPlainObject(value) {
|
|
3376
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3377
|
+
}
|
|
3378
|
+
/**
|
|
1827
3379
|
* The reactor and the GraphQL schema disagree on the enum: the reactor's
|
|
1828
3380
|
* `None` is the schema's `ORPHAN`. This is the inverse of the server's
|
|
1829
3381
|
* `toReactorPropagationMode`.
|
|
@@ -1848,8 +3400,7 @@ function propagationModeInput(propagate) {
|
|
|
1848
3400
|
* action needing history - throws here, before the mutation. Sending it
|
|
1849
3401
|
* unsigned instead would silently drop the signatures the caller asked for.
|
|
1850
3402
|
*/
|
|
1851
|
-
async function prepareActionsForPush(actions, document, documentModels,
|
|
1852
|
-
const signer = explicitSigner ?? resolveAmbientSigner();
|
|
3403
|
+
async function prepareActionsForPush(actions, document, documentModels, signer, signal) {
|
|
1853
3404
|
if (!signer || actions.length === 0) return actions;
|
|
1854
3405
|
return prepareSignedActions(actions, document, signer, actions.length > 1 ? resolveDocumentModelModule(documentModels, document.header.documentType, documentModelVersion(document)) : void 0, signal);
|
|
1855
3406
|
}
|
|
@@ -1866,10 +3417,107 @@ function documentModelVersion(document) {
|
|
|
1866
3417
|
const documentScope = document.state.document;
|
|
1867
3418
|
return normalizeDocumentModelVersion(documentScope?.version);
|
|
1868
3419
|
}
|
|
3420
|
+
/**
|
|
3421
|
+
* Rebuilds a reactor {@link JobInfo} from what the server reported. An unknown
|
|
3422
|
+
* job arrives as the reactor's own: FAILED with an empty `documentId`.
|
|
3423
|
+
*/
|
|
3424
|
+
function jobInfoFromGql(job) {
|
|
3425
|
+
const token = job.consistencyToken;
|
|
3426
|
+
if (token.version !== 1) throw new Error(`Job ${job.id} carries consistency token version ${token.version}, which this client cannot read`);
|
|
3427
|
+
const info = {
|
|
3428
|
+
id: job.id,
|
|
3429
|
+
documentId: job.documentId,
|
|
3430
|
+
status: job.status,
|
|
3431
|
+
createdAtUtcIso: isoStringFromDateTime(job.createdAt),
|
|
3432
|
+
consistencyToken: {
|
|
3433
|
+
version: 1,
|
|
3434
|
+
createdAtUtcIso: token.createdAtUtcIso,
|
|
3435
|
+
coordinates: token.coordinates.map((coordinate) => ({ ...coordinate }))
|
|
3436
|
+
},
|
|
3437
|
+
meta: {
|
|
3438
|
+
batchId: job.meta.batchId,
|
|
3439
|
+
batchJobIds: [...job.meta.batchJobIds]
|
|
3440
|
+
}
|
|
3441
|
+
};
|
|
3442
|
+
if (job.completedAt != null) info.completedAtUtcIso = isoStringFromDateTime(job.completedAt);
|
|
3443
|
+
if (job.result != null) info.result = job.result;
|
|
3444
|
+
if (job.error != null) info.error = {
|
|
3445
|
+
name: job.errorName ?? "Error",
|
|
3446
|
+
message: job.error,
|
|
3447
|
+
stack: ""
|
|
3448
|
+
};
|
|
3449
|
+
return info;
|
|
3450
|
+
}
|
|
3451
|
+
/**
|
|
3452
|
+
* The header a Switchboard's drive middleware and load balancer key on. A
|
|
3453
|
+
* request carries it only when it is known to belong to that one drive: the
|
|
3454
|
+
* server answers any drive it does not own with 421.
|
|
3455
|
+
*/
|
|
3456
|
+
const DRIVE_ID_HEADER = "Drive-Id";
|
|
3457
|
+
function driveIdHeaders(driveId) {
|
|
3458
|
+
return driveId === "" ? void 0 : { [DRIVE_ID_HEADER]: driveId };
|
|
3459
|
+
}
|
|
3460
|
+
function isDrive(document) {
|
|
3461
|
+
return DRIVE_DOCUMENT_TYPES.includes(document.header.documentType);
|
|
3462
|
+
}
|
|
3463
|
+
/**
|
|
3464
|
+
* Surfaces a 421 from the Switchboard's drive middleware, which graphql-request
|
|
3465
|
+
* reports as a `ClientError`, as {@link GraphQLWrongBackendError}.
|
|
3466
|
+
*/
|
|
3467
|
+
function withWrongBackendErrors(middleware) {
|
|
3468
|
+
return async (action, ...rest) => {
|
|
3469
|
+
try {
|
|
3470
|
+
return await middleware(action, ...rest);
|
|
3471
|
+
} catch (error) {
|
|
3472
|
+
throw wrongBackendErrorOf(error) ?? error;
|
|
3473
|
+
}
|
|
3474
|
+
};
|
|
3475
|
+
}
|
|
3476
|
+
function wrongBackendErrorOf(error) {
|
|
3477
|
+
const response = error?.response;
|
|
3478
|
+
if (response?.status !== 421) return;
|
|
3479
|
+
let payload = response.body;
|
|
3480
|
+
if (typeof payload === "string") try {
|
|
3481
|
+
payload = JSON.parse(payload);
|
|
3482
|
+
} catch {}
|
|
3483
|
+
const driveId = payload?.driveId;
|
|
3484
|
+
return new GraphQLWrongBackendError(typeof driveId === "string" ? driveId : "", payload, { cause: error });
|
|
3485
|
+
}
|
|
3486
|
+
function isSettled(job) {
|
|
3487
|
+
const status = job.status;
|
|
3488
|
+
return status === "READ_READY" || status === "FAILED";
|
|
3489
|
+
}
|
|
3490
|
+
function abortReason(signal) {
|
|
3491
|
+
const reason = signal.reason;
|
|
3492
|
+
return reason instanceof Error ? reason : new Error(String(reason));
|
|
3493
|
+
}
|
|
3494
|
+
function delay(ms, signal) {
|
|
3495
|
+
return new Promise((resolve, reject) => {
|
|
3496
|
+
if (signal?.aborted) {
|
|
3497
|
+
reject(abortReason(signal));
|
|
3498
|
+
return;
|
|
3499
|
+
}
|
|
3500
|
+
const onAbort = () => {
|
|
3501
|
+
clearTimeout(timer);
|
|
3502
|
+
if (signal) reject(abortReason(signal));
|
|
3503
|
+
};
|
|
3504
|
+
const timer = setTimeout(() => {
|
|
3505
|
+
signal?.removeEventListener("abort", onAbort);
|
|
3506
|
+
resolve();
|
|
3507
|
+
}, ms);
|
|
3508
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3509
|
+
});
|
|
3510
|
+
}
|
|
3511
|
+
/** As the reactor's `signAction` reads it: the last tuple names a key. */
|
|
3512
|
+
function isActionSigned(action) {
|
|
3513
|
+
const signer = action.context?.signer;
|
|
3514
|
+
return Boolean(signer?.app?.key && signer.signatures.at(-1)?.[1]);
|
|
3515
|
+
}
|
|
1869
3516
|
/** Resolves the signer of the logged-in user, if there is one. */
|
|
1870
|
-
|
|
3517
|
+
/** The logged-in Renown user's signer, read per call; none when nobody is. */
|
|
3518
|
+
function ambientRenownSigner() {
|
|
1871
3519
|
if (typeof window === "undefined") return;
|
|
1872
|
-
const renown =
|
|
3520
|
+
const renown = getPHStore()?.renown;
|
|
1873
3521
|
return renown?.user ? renown.signer : void 0;
|
|
1874
3522
|
}
|
|
1875
3523
|
/**
|
|
@@ -1890,6 +3538,68 @@ function scopesForActions(actions) {
|
|
|
1890
3538
|
return [...new Set(actions.map((action) => action.scope))];
|
|
1891
3539
|
}
|
|
1892
3540
|
//#endregion
|
|
3541
|
+
//#region src/hooks/backend-auth.ts
|
|
3542
|
+
const backendAuthEventFunctions = makePHEventFunctions("backendAuth");
|
|
3543
|
+
/** Whether the app's backend refused this tab's caller, and how. */
|
|
3544
|
+
const useBackendAuth = backendAuthEventFunctions.useValue;
|
|
3545
|
+
/** Records (or clears, with `undefined`) a backend's refusal of the caller. */
|
|
3546
|
+
const setBackendAuth = backendAuthEventFunctions.setValue;
|
|
3547
|
+
const addBackendAuthEventHandler = backendAuthEventFunctions.addEventHandler;
|
|
3548
|
+
const STATUS_IN_MESSAGE = /\(Code: (401|403)\)/;
|
|
3549
|
+
/**
|
|
3550
|
+
* The messages a Switchboard's GraphQL layer refuses with, without an HTTP
|
|
3551
|
+
* status (the sync layer's `DRIVE_AUTH_ERROR_MESSAGES`). Inlined: this file
|
|
3552
|
+
* is reachable from the browser entry, which must not import the reactor
|
|
3553
|
+
* package as a value.
|
|
3554
|
+
*/
|
|
3555
|
+
const GRAPHQL_REFUSALS = [
|
|
3556
|
+
"Forbidden: insufficient permissions",
|
|
3557
|
+
"Forbidden: authentication required",
|
|
3558
|
+
"Authentication required"
|
|
3559
|
+
];
|
|
3560
|
+
/**
|
|
3561
|
+
* The HTTP status with which a backend refused the caller, or null when the
|
|
3562
|
+
* error is something else.
|
|
3563
|
+
*
|
|
3564
|
+
* Covers every shape a refusal reaches the browser in: the sync layer's
|
|
3565
|
+
* errors (`isDriveAuthError`), graphql-request's `ClientError` from the
|
|
3566
|
+
* remote GraphQL client (`response.status`, and "(Code: 401)" in its
|
|
3567
|
+
* message), and the router's partial-failure error that wraps one such
|
|
3568
|
+
* failure per backend.
|
|
3569
|
+
*/
|
|
3570
|
+
function backendAuthStatusOf(error) {
|
|
3571
|
+
if (!error || typeof error !== "object") return null;
|
|
3572
|
+
const e = error;
|
|
3573
|
+
const direct = [e.response?.status, e.statusCode].find((s) => s === 401 || s === 403);
|
|
3574
|
+
if (direct === 401 || direct === 403) return direct;
|
|
3575
|
+
if (typeof e.message === "string") {
|
|
3576
|
+
const m = STATUS_IN_MESSAGE.exec(e.message);
|
|
3577
|
+
if (m) return m[1] === "401" ? 401 : 403;
|
|
3578
|
+
}
|
|
3579
|
+
if (Array.isArray(e.failures)) for (const failure of e.failures) {
|
|
3580
|
+
const status = backendAuthStatusOf(failure.error);
|
|
3581
|
+
if (status) return status;
|
|
3582
|
+
}
|
|
3583
|
+
if (typeof e.message === "string" && GRAPHQL_REFUSALS.some((m) => e.message.includes(m))) return /authentication required/i.test(e.message) ? 401 : 403;
|
|
3584
|
+
return null;
|
|
3585
|
+
}
|
|
3586
|
+
/** True when a backend refused the caller as unauthenticated or unauthorized. */
|
|
3587
|
+
function isBackendAuthError(error) {
|
|
3588
|
+
return backendAuthStatusOf(error) !== null;
|
|
3589
|
+
}
|
|
3590
|
+
/** Records the refusal `error` carries, if it is one; returns whether it was. */
|
|
3591
|
+
function recordBackendAuthError(error, backend) {
|
|
3592
|
+
const status = backendAuthStatusOf(error);
|
|
3593
|
+
if (status === null) return false;
|
|
3594
|
+
setBackendAuth({
|
|
3595
|
+
requiresAuth: true,
|
|
3596
|
+
status,
|
|
3597
|
+
backend,
|
|
3598
|
+
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
3599
|
+
});
|
|
3600
|
+
return true;
|
|
3601
|
+
}
|
|
3602
|
+
//#endregion
|
|
1893
3603
|
//#region src/hooks/config/editor.ts
|
|
1894
3604
|
const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
|
|
1895
3605
|
/** Sets whether external controls are enabled for a given editor. */
|
|
@@ -1910,7 +3620,7 @@ const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocument
|
|
|
1910
3620
|
const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
|
|
1911
3621
|
/** Defines the document types a drive supports.
|
|
1912
3622
|
*
|
|
1913
|
-
*
|
|
3623
|
+
* Unset or empty, it means every document type registered in the reactor.
|
|
1914
3624
|
*/
|
|
1915
3625
|
function useAllowedDocumentTypes() {
|
|
1916
3626
|
return allowedDocumentTypesEventFunctions.useValue();
|
|
@@ -2290,51 +4000,46 @@ const usePackageDiscoveryService = packageDiscoveryFunctions.useValue;
|
|
|
2290
4000
|
const setPackageDiscoveryService = packageDiscoveryFunctions.setValue;
|
|
2291
4001
|
const addPackageDiscoveryServiceEventHandler = packageDiscoveryFunctions.addEventHandler;
|
|
2292
4002
|
//#endregion
|
|
2293
|
-
//#region src/hooks/
|
|
2294
|
-
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
const
|
|
2298
|
-
|
|
2299
|
-
const
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
const
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
const
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
}
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
/** Adds event handler for revision history visibility */
|
|
2329
|
-
const addRevisionHistoryVisibleEventHandler = revisionHistoryEventFunctions.addEventHandler;
|
|
2330
|
-
/** Shows the revision history */
|
|
2331
|
-
function showRevisionHistory() {
|
|
2332
|
-
setRevisionHistoryVisible(true);
|
|
2333
|
-
}
|
|
2334
|
-
/** Hides the revision history */
|
|
2335
|
-
function hideRevisionHistory() {
|
|
2336
|
-
setRevisionHistoryVisible(false);
|
|
4003
|
+
//#region src/hooks/sync-selection.ts
|
|
4004
|
+
/** Applies a path's selection without writing the URL; idempotent.
|
|
4005
|
+
* @deprecated Set the store's `navigation`; its route loaders write the selection. */
|
|
4006
|
+
function syncSelectionFromPath(pathname = getCurrentPathname()) {
|
|
4007
|
+
const drives = getPHStore()?.drives;
|
|
4008
|
+
if (!drives) return;
|
|
4009
|
+
const driveSlug = extractDriveSlugFromPath(pathname);
|
|
4010
|
+
const selectedDriveId = getPHStore()?.selectedDriveId;
|
|
4011
|
+
if (!driveSlug) {
|
|
4012
|
+
if (selectedDriveId) selectDrive(void 0);
|
|
4013
|
+
return;
|
|
4014
|
+
}
|
|
4015
|
+
const drive = findDriveBySlug(drives, driveSlug);
|
|
4016
|
+
const selectedIsUnlisted = !!selectedDriveId && !drives.some((d) => d.header.id === selectedDriveId);
|
|
4017
|
+
if (drive) {
|
|
4018
|
+
if (drive.header.id !== selectedDriveId) setSelectedDriveId(drive.header.id);
|
|
4019
|
+
} else if (!selectedIsUnlisted) {
|
|
4020
|
+
selectDrive(driveSlug);
|
|
4021
|
+
return;
|
|
4022
|
+
}
|
|
4023
|
+
const nodeId = extractNodeIdFromSlug(extractNodeSlugFromPath(pathname));
|
|
4024
|
+
if (nodeId !== getPHStore()?.selectedNodeId) setSelectedNodeId(nodeId);
|
|
4025
|
+
}
|
|
4026
|
+
setBrowserOpenSync(() => syncSelectionFromPath());
|
|
4027
|
+
function syncOnPopState() {
|
|
4028
|
+
if (hasHostNavigation()) return;
|
|
4029
|
+
syncSelectionFromPath(window.location.pathname);
|
|
4030
|
+
}
|
|
4031
|
+
let popStateHandlerAdded = false;
|
|
4032
|
+
/** Syncs the selection on back/forward when no host navigation is set.
|
|
4033
|
+
* @deprecated Set the store's `navigation`; its router handles back/forward. */
|
|
4034
|
+
function addSyncSelectionOnPopStateEventHandler() {
|
|
4035
|
+
if (popStateHandlerAdded) return;
|
|
4036
|
+
popStateHandlerAdded = true;
|
|
4037
|
+
window.addEventListener("popstate", syncOnPopState);
|
|
2337
4038
|
}
|
|
4039
|
+
/** @deprecated Set the store's `navigation`; its router handles back/forward. */
|
|
4040
|
+
const addSetSelectedDriveOnPopStateEventHandler = addSyncSelectionOnPopStateEventHandler;
|
|
4041
|
+
/** @deprecated Set the store's `navigation`; its router handles back/forward. */
|
|
4042
|
+
const addSetSelectedNodeOnPopStateEventHandler = addSyncSelectionOnPopStateEventHandler;
|
|
2338
4043
|
//#endregion
|
|
2339
4044
|
//#region src/hooks/selected-timeline-item.ts
|
|
2340
4045
|
const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
|
|
@@ -2367,14 +4072,15 @@ const addToastEventHandler = toastEventFunctions.addEventHandler;
|
|
|
2367
4072
|
const commonGlobalEventHandlerFunctions = {
|
|
2368
4073
|
loading: addLoadingEventHandler,
|
|
2369
4074
|
drives: addDrivesEventHandler,
|
|
4075
|
+
backendAuth: addBackendAuthEventHandler,
|
|
4076
|
+
driveNodes: addDriveNodesEventHandler,
|
|
2370
4077
|
selectedDriveId: () => {
|
|
2371
4078
|
addSelectedDriveIdEventHandler();
|
|
2372
|
-
|
|
4079
|
+
addSyncSelectionOnPopStateEventHandler();
|
|
2373
4080
|
addResetSelectedNodeEventHandler();
|
|
2374
4081
|
},
|
|
2375
4082
|
selectedNodeId: () => {
|
|
2376
4083
|
addSelectedNodeIdEventHandler();
|
|
2377
|
-
addSetSelectedNodeOnPopStateEventHandler();
|
|
2378
4084
|
},
|
|
2379
4085
|
documentCache: addDocumentCacheEventHandler,
|
|
2380
4086
|
reactorGraphQLClient: addGraphQLReactorClientEventHandler,
|
|
@@ -2384,14 +4090,16 @@ const phGlobalEventHandlerRegisterFunctions = {
|
|
|
2384
4090
|
...commonGlobalEventHandlerFunctions,
|
|
2385
4091
|
reactorClientModule: addReactorClientModuleEventHandler,
|
|
2386
4092
|
reactorClient: addReactorClientEventHandler,
|
|
4093
|
+
reactor: addReactorHalvesEventHandler,
|
|
4094
|
+
fullReactorClient: addFullReactorClientEventHandler,
|
|
2387
4095
|
attachmentService: addAttachmentServiceEventHandler,
|
|
4096
|
+
switchboards: addSwitchboardsEventHandler,
|
|
2388
4097
|
features: addFeaturesEventHandler,
|
|
2389
4098
|
modal: addModalEventHandler,
|
|
2390
4099
|
renown: addRenownEventHandler,
|
|
2391
4100
|
vetraPackageManager: addVetraPackageManagerEventHandler,
|
|
2392
4101
|
packageDiscoveryService: addPackageDiscoveryServiceEventHandler,
|
|
2393
4102
|
selectedTimelineRevision: addSelectedTimelineRevisionEventHandler,
|
|
2394
|
-
revisionHistoryVisible: addRevisionHistoryVisibleEventHandler,
|
|
2395
4103
|
selectedTimelineItem: addSelectedTimelineItemEventHandler,
|
|
2396
4104
|
routerBasename: addRouterBasenameEventHandler,
|
|
2397
4105
|
version: addVersionEventHandler,
|
|
@@ -2444,7 +4152,9 @@ const phGlobalEventHandlerRegisterFunctions = {
|
|
|
2444
4152
|
isSentryTracingEnabled: addIsSentryTracingEnabledEventHandler,
|
|
2445
4153
|
isExternalProcessorsEnabled: addIsExternalProcessorsEnabledEventHandler,
|
|
2446
4154
|
isExternalPackagesEnabled: addIsExternalPackagesEnabledEventHandler,
|
|
2447
|
-
toast: addToastEventHandler
|
|
4155
|
+
toast: addToastEventHandler,
|
|
4156
|
+
navigation: () => {},
|
|
4157
|
+
aiTools: () => {}
|
|
2448
4158
|
};
|
|
2449
4159
|
function addPHEventHandlers() {
|
|
2450
4160
|
callEventHandlerRegisterFunctions(phGlobalEventHandlerRegisterFunctions);
|
|
@@ -2539,6 +4249,274 @@ function useSwitchboardClient() {
|
|
|
2539
4249
|
return isGraphQLReactorClient(client) ? client : void 0;
|
|
2540
4250
|
}
|
|
2541
4251
|
//#endregion
|
|
4252
|
+
//#region src/graphql-client/switchboard-backend.ts
|
|
4253
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
|
|
4254
|
+
const DEFAULT_BATCH_REQUEST_TIMEOUT_MS = 12e4;
|
|
4255
|
+
const DEFAULT_BREAKER = Object.freeze({
|
|
4256
|
+
failures: 3,
|
|
4257
|
+
openMs: 3e4
|
|
4258
|
+
});
|
|
4259
|
+
function breakerSettings(breaker) {
|
|
4260
|
+
if (breaker === false) return {
|
|
4261
|
+
failures: Infinity,
|
|
4262
|
+
openMs: 0
|
|
4263
|
+
};
|
|
4264
|
+
return {
|
|
4265
|
+
...DEFAULT_BREAKER,
|
|
4266
|
+
...breaker
|
|
4267
|
+
};
|
|
4268
|
+
}
|
|
4269
|
+
const FACTS_QUERY = `
|
|
4270
|
+
query SwitchboardFacts {
|
|
4271
|
+
inspection {
|
|
4272
|
+
info {
|
|
4273
|
+
storage {
|
|
4274
|
+
engine
|
|
4275
|
+
persistence
|
|
4276
|
+
durable
|
|
4277
|
+
selfHeal
|
|
4278
|
+
}
|
|
4279
|
+
workflows
|
|
4280
|
+
syncChannels
|
|
4281
|
+
access {
|
|
4282
|
+
admin
|
|
4283
|
+
sql
|
|
4284
|
+
}
|
|
4285
|
+
}
|
|
4286
|
+
documentModels {
|
|
4287
|
+
documentType
|
|
4288
|
+
}
|
|
4289
|
+
}
|
|
4290
|
+
queries: __type(name: "Query") {
|
|
4291
|
+
fields {
|
|
4292
|
+
name
|
|
4293
|
+
}
|
|
4294
|
+
}
|
|
4295
|
+
inspectionFields: __type(name: "ReactorInspection") {
|
|
4296
|
+
fields {
|
|
4297
|
+
name
|
|
4298
|
+
}
|
|
4299
|
+
}
|
|
4300
|
+
}
|
|
4301
|
+
`;
|
|
4302
|
+
const MODEL_LOADING_QUERY = `
|
|
4303
|
+
query SwitchboardModelLoading {
|
|
4304
|
+
inspection {
|
|
4305
|
+
loadsModelsOnDemand
|
|
4306
|
+
}
|
|
4307
|
+
}
|
|
4308
|
+
`;
|
|
4309
|
+
/** Queries this backend sends that a Switchboard serves only from some version. */
|
|
4310
|
+
const REQUIRED_QUERIES = [
|
|
4311
|
+
"documentServed",
|
|
4312
|
+
"createDefaults",
|
|
4313
|
+
"inspection"
|
|
4314
|
+
];
|
|
4315
|
+
/** The Switchboard's circuit is open: nothing was sent. */
|
|
4316
|
+
var SwitchboardUnreachableError = class extends Error {
|
|
4317
|
+
backend;
|
|
4318
|
+
retryAt;
|
|
4319
|
+
name = "SwitchboardUnreachableError";
|
|
4320
|
+
constructor(backend, retryAt) {
|
|
4321
|
+
super(`Switchboard backend ${JSON.stringify(backend)} is unreachable; nothing is sent until ${new Date(retryAt).toISOString()}`);
|
|
4322
|
+
this.backend = backend;
|
|
4323
|
+
this.retryAt = retryAt;
|
|
4324
|
+
}
|
|
4325
|
+
};
|
|
4326
|
+
/**
|
|
4327
|
+
* Opens after `failures` transport failures in a row (a network error, a
|
|
4328
|
+
* deadline or a 5xx) and sends nothing for `openMs`. Any other answer, a
|
|
4329
|
+
* GraphQL error included, closes it. The first request after `openMs` goes
|
|
4330
|
+
* through; one more failure opens it again.
|
|
4331
|
+
*/
|
|
4332
|
+
var Breaker = class {
|
|
4333
|
+
backend;
|
|
4334
|
+
settings;
|
|
4335
|
+
consecutive = 0;
|
|
4336
|
+
openUntil;
|
|
4337
|
+
constructor(backend, settings) {
|
|
4338
|
+
this.backend = backend;
|
|
4339
|
+
this.settings = settings;
|
|
4340
|
+
}
|
|
4341
|
+
health() {
|
|
4342
|
+
return this.isOpen() ? "down" : "up";
|
|
4343
|
+
}
|
|
4344
|
+
wrap(inner) {
|
|
4345
|
+
return async (input, init) => {
|
|
4346
|
+
const openUntil = this.openUntil;
|
|
4347
|
+
if (openUntil !== void 0 && Date.now() < openUntil) throw new SwitchboardUnreachableError(this.backend, openUntil);
|
|
4348
|
+
let response;
|
|
4349
|
+
try {
|
|
4350
|
+
response = await inner(input, init);
|
|
4351
|
+
} catch (error) {
|
|
4352
|
+
if (!abortedByCaller(init?.signal)) this.fail();
|
|
4353
|
+
throw error;
|
|
4354
|
+
}
|
|
4355
|
+
if (response.status >= 500) this.fail();
|
|
4356
|
+
else {
|
|
4357
|
+
this.consecutive = 0;
|
|
4358
|
+
this.openUntil = void 0;
|
|
4359
|
+
}
|
|
4360
|
+
return response;
|
|
4361
|
+
};
|
|
4362
|
+
}
|
|
4363
|
+
isOpen() {
|
|
4364
|
+
return this.openUntil !== void 0 && Date.now() < this.openUntil;
|
|
4365
|
+
}
|
|
4366
|
+
fail() {
|
|
4367
|
+
this.consecutive += 1;
|
|
4368
|
+
if (this.consecutive >= this.settings.failures) this.openUntil = Date.now() + this.settings.openMs;
|
|
4369
|
+
}
|
|
4370
|
+
};
|
|
4371
|
+
function abortedByCaller(signal) {
|
|
4372
|
+
return Boolean(signal?.aborted) && !isDeadlineError(signal?.reason);
|
|
4373
|
+
}
|
|
4374
|
+
const NO_ACCESS = Object.freeze({
|
|
4375
|
+
admin: false,
|
|
4376
|
+
sql: false
|
|
4377
|
+
});
|
|
4378
|
+
/** Ids and slugs of documents this backend answered as drives, by drive id. */
|
|
4379
|
+
var KnownDrives = class {
|
|
4380
|
+
ids = /* @__PURE__ */ new Map();
|
|
4381
|
+
learn(document) {
|
|
4382
|
+
const { id, slug, documentType } = document.header;
|
|
4383
|
+
if (DRIVE_DOCUMENT_TYPES.includes(documentType)) {
|
|
4384
|
+
this.ids.set(id, id);
|
|
4385
|
+
if (slug) this.ids.set(slug, id);
|
|
4386
|
+
}
|
|
4387
|
+
return document;
|
|
4388
|
+
}
|
|
4389
|
+
learnPage(page) {
|
|
4390
|
+
for (const document of page.results) this.learn(document);
|
|
4391
|
+
return page;
|
|
4392
|
+
}
|
|
4393
|
+
/** Drops a drive the Switchboard refused, by id and by slug. */
|
|
4394
|
+
forget(driveId) {
|
|
4395
|
+
for (const [identifier, id] of this.ids) if (id === driveId) this.ids.delete(identifier);
|
|
4396
|
+
}
|
|
4397
|
+
driveOf(identifier) {
|
|
4398
|
+
return identifier === void 0 ? void 0 : this.ids.get(identifier);
|
|
4399
|
+
}
|
|
4400
|
+
/** Names a drive only when this backend proved it is one. */
|
|
4401
|
+
driveIdFor = (call) => {
|
|
4402
|
+
switch (call.method) {
|
|
4403
|
+
case "create":
|
|
4404
|
+
case "find": return this.driveOf(call.parentId);
|
|
4405
|
+
case "execute":
|
|
4406
|
+
case "deleteDocument": return this.driveOf(call.documentId);
|
|
4407
|
+
case "executeBatch":
|
|
4408
|
+
for (const job of call.jobs ?? []) {
|
|
4409
|
+
const drive = this.driveOf(job.documentId);
|
|
4410
|
+
if (drive !== void 0) return drive;
|
|
4411
|
+
}
|
|
4412
|
+
return;
|
|
4413
|
+
}
|
|
4414
|
+
};
|
|
4415
|
+
/** Runs a call that may carry `Drive-Id`; a 421 forgets the drive it named. */
|
|
4416
|
+
async refusable(call) {
|
|
4417
|
+
try {
|
|
4418
|
+
return await call;
|
|
4419
|
+
} catch (error) {
|
|
4420
|
+
if (GraphQLWrongBackendError.isError(error)) this.forget(error.driveId);
|
|
4421
|
+
throw error;
|
|
4422
|
+
}
|
|
4423
|
+
}
|
|
4424
|
+
};
|
|
4425
|
+
function isUnknownJob(job) {
|
|
4426
|
+
return job.status === "FAILED" && job.error?.name === "JobNotFoundError";
|
|
4427
|
+
}
|
|
4428
|
+
/** A Switchboard as a router backend; members GraphQL cannot serve are absent. */
|
|
4429
|
+
function createSwitchboardBackend(descriptor) {
|
|
4430
|
+
const drives = new KnownDrives();
|
|
4431
|
+
const breaker = new Breaker(descriptor.name, breakerSettings(descriptor.breaker));
|
|
4432
|
+
const signer = descriptor.signer;
|
|
4433
|
+
const gql = new GraphQLReactorClient({
|
|
4434
|
+
url: descriptor.url,
|
|
4435
|
+
tokenProvider: descriptor.tokenProvider,
|
|
4436
|
+
signer: typeof signer === "function" ? signer : () => signer,
|
|
4437
|
+
documentModels: descriptor.documentModels,
|
|
4438
|
+
realtime: descriptor.realtime,
|
|
4439
|
+
driveIdFor: drives.driveIdFor,
|
|
4440
|
+
requestTimeoutMs: descriptor.requestTimeoutMs ?? 3e4,
|
|
4441
|
+
batchRequestTimeoutMs: descriptor.batchRequestTimeoutMs ?? 12e4,
|
|
4442
|
+
fetch: breaker.wrap(descriptor.fetch ?? switchboardFetch)
|
|
4443
|
+
});
|
|
4444
|
+
const backend = {
|
|
4445
|
+
supports: {
|
|
4446
|
+
find: findIsServableOverGraphQL,
|
|
4447
|
+
pointInTimeViews: false
|
|
4448
|
+
},
|
|
4449
|
+
health: () => breaker.health(),
|
|
4450
|
+
drives: gql.read.drives,
|
|
4451
|
+
driveNodes: gql.nodeSource(),
|
|
4452
|
+
driveFileLinkTypes: ["child", DRIVE_CHILD_RELATIONSHIP_TYPE],
|
|
4453
|
+
submit: { execute: (identifier, branch, actions, signal) => drives.refusable(gql.executeAsync(identifier, branch, actions, signal)) },
|
|
4454
|
+
get: async (identifier, view, signal, consistencyToken) => drives.learn(await gql.get(identifier, view, signal, consistencyToken)),
|
|
4455
|
+
getMany: async (ids, view, signal) => (await gql.getMany(ids, view, signal)).map((document) => drives.learn(document)),
|
|
4456
|
+
getOperations: (identifier, view, filter, paging, signal) => gql.getOperations(identifier, view, filter, paging, signal),
|
|
4457
|
+
find: async (search, view, paging, signal) => drives.learnPage(await drives.refusable(gql.find(search, view, paging, signal))),
|
|
4458
|
+
isServed: (identifier, view, signal) => gql.isServed(identifier, view, signal),
|
|
4459
|
+
getOutgoingRelationships: (source, type, view, paging, signal) => gql.getOutgoingRelationships(source, type, view, paging, signal),
|
|
4460
|
+
getIncomingRelationships: (target, type, view, paging, signal) => gql.getIncomingRelationships(target, type, view, paging, signal),
|
|
4461
|
+
getOutgoingRelationshipEdges: (source, type, view, paging, signal) => gql.getOutgoingRelationshipEdges(source, type, view, paging, signal),
|
|
4462
|
+
getIncomingRelationshipEdges: (target, type, view, paging, signal) => gql.getIncomingRelationshipEdges(target, type, view, paging, signal),
|
|
4463
|
+
subscribe: (search, callback, view) => gql.subscribe(search, callback, view),
|
|
4464
|
+
getCreateSignaturePolicy: () => gql.getCreateSignaturePolicy(),
|
|
4465
|
+
getCreateProtocolVersions: (options, signal) => gql.getCreateProtocolVersions(options, signal),
|
|
4466
|
+
create: async (document, parent, signal) => drives.learn(await drives.refusable(gql.create(document, parent, signal))),
|
|
4467
|
+
execute: async (identifier, branch, actions, signal) => drives.learn(await drives.refusable(gql.execute(identifier, branch, actions, signal))),
|
|
4468
|
+
executeBatch: (request, signal) => drives.refusable(gql.executeBatch(request, signal)),
|
|
4469
|
+
deleteDocument: (identifier, propagate, signal) => drives.refusable(gql.deleteDocument(identifier, propagate, signal)),
|
|
4470
|
+
setPreferredEditor: (identifier, editor, branch, signal) => gql.setPreferredEditor(identifier, editor, branch, signal),
|
|
4471
|
+
getJob: async (jobId, signal) => {
|
|
4472
|
+
const job = await gql.getJob(jobId, signal);
|
|
4473
|
+
return job && isUnknownJob(job) ? void 0 : job;
|
|
4474
|
+
},
|
|
4475
|
+
waitForJob: (job, signal) => gql.waitForJob(job, signal),
|
|
4476
|
+
undo: async (identifier, scope, branch, signal) => drives.learn(await drives.refusable(gql.undo(identifier, scope, branch, signal))),
|
|
4477
|
+
redo: async (identifier, scope, branch, signal) => drives.learn(await drives.refusable(gql.redo(identifier, scope, branch, signal))),
|
|
4478
|
+
undoRedoTargets: (identifier, scope, view, signal) => gql.undoRedoTargets(identifier, scope, view, signal),
|
|
4479
|
+
undoRedoAvailability: (identifier, scope, branch, signal) => gql.undoRedoAvailability(identifier, scope, branch, signal)
|
|
4480
|
+
};
|
|
4481
|
+
let reading;
|
|
4482
|
+
const read = () => reading ??= readFacts(gql, descriptor.url).finally(() => {
|
|
4483
|
+
reading = void 0;
|
|
4484
|
+
});
|
|
4485
|
+
return {
|
|
4486
|
+
config: {
|
|
4487
|
+
name: descriptor.name,
|
|
4488
|
+
backend,
|
|
4489
|
+
facts: async () => (await read()).info,
|
|
4490
|
+
documentTypes: async () => (await read()).documentTypes,
|
|
4491
|
+
reach: {
|
|
4492
|
+
hosting: "remote",
|
|
4493
|
+
inspection: descriptor.inspection ?? "rpc"
|
|
4494
|
+
},
|
|
4495
|
+
refusesMisroutes: false
|
|
4496
|
+
},
|
|
4497
|
+
notifyCredentialsChanged: () => gql.notifyCredentialsChanged(),
|
|
4498
|
+
dispose: () => gql.dispose()
|
|
4499
|
+
};
|
|
4500
|
+
}
|
|
4501
|
+
function fieldNames(type) {
|
|
4502
|
+
return new Set(type?.fields?.map((field) => field.name));
|
|
4503
|
+
}
|
|
4504
|
+
async function readFacts(gql, url) {
|
|
4505
|
+
const answer = await gql.request(FACTS_QUERY);
|
|
4506
|
+
const served = fieldNames(answer.queries);
|
|
4507
|
+
const missing = REQUIRED_QUERIES.filter((query) => !served.has(query));
|
|
4508
|
+
if (missing.length > 0) throw new Error(`The Switchboard at ${url} does not serve ${missing.join(", ")}; it is older than this client`);
|
|
4509
|
+
const { info, documentModels } = answer.inspection;
|
|
4510
|
+
const closed = fieldNames(answer.inspectionFields).has("loadsModelsOnDemand") && !(await gql.request(MODEL_LOADING_QUERY)).inspection.loadsModelsOnDemand;
|
|
4511
|
+
return {
|
|
4512
|
+
info: {
|
|
4513
|
+
...info,
|
|
4514
|
+
access: info.access ?? NO_ACCESS
|
|
4515
|
+
},
|
|
4516
|
+
documentTypes: closed ? documentModels.map((model) => model.documentType) : void 0
|
|
4517
|
+
};
|
|
4518
|
+
}
|
|
4519
|
+
//#endregion
|
|
2542
4520
|
//#region src/hooks/document-operations.ts
|
|
2543
4521
|
const DEFAULT_LIMIT = 100;
|
|
2544
4522
|
function toError(reason) {
|
|
@@ -2550,7 +4528,8 @@ function useScopeOperations(documentId, scope, options = {}) {
|
|
|
2550
4528
|
const documentCache = useDocumentCache();
|
|
2551
4529
|
const cache = documentCache && isOperationCache(documentCache) ? documentCache : void 0;
|
|
2552
4530
|
const activeId = enabled && cache && documentId ? documentId : void 0;
|
|
2553
|
-
const
|
|
4531
|
+
const getEntry = () => activeId && cache ? cache.getOperationsState(activeId, scope) : IDLE_OPERATIONS_ENTRY;
|
|
4532
|
+
const entry = useSyncExternalStore((onChange) => activeId && cache ? cache.subscribeOperations(activeId, onChange) : () => {}, getEntry, getEntry);
|
|
2554
4533
|
useEffect(() => {
|
|
2555
4534
|
if (activeId && cache && entry.status === "idle") cache.loadOperations(activeId, scope, limit);
|
|
2556
4535
|
}, [
|
|
@@ -2625,6 +4604,6 @@ function useDocumentOperations(documentId, scope, options = {}) {
|
|
|
2625
4604
|
return legacy ? legacyResult : primary;
|
|
2626
4605
|
}
|
|
2627
4606
|
//#endregion
|
|
2628
|
-
export {
|
|
4607
|
+
export { addIsAddDriveEnabledEventHandler as $, copyNode$1 as $i, useIsDeleteLocalDrivesEnabled as $n, isGraphQLReactorClient as $r, setIsAnalyticsDatabaseWorkerEnabled as $t, setGraphQLReactorClient as A, useSearchParams as Aa, phDocumentFromGetDocument as Ai, setSwitchboardUrl as An, addIsDragAndDropEnabledEventHandler as Ar, addSentryEnvEventHandler as At, setAttachmentService as B, underSignaturePolicy as Bi, useDrivesPreserveStrategy as Bn, useAllowedDocumentTypes as Br, setAnalyticsDatabaseName as Bt, addSetSelectedNodeOnPopStateEventHandler as C, showPHModal as Ca, switchboardFetch as Ci, setRenownUrl as Cn, useSentryRelease as Cr, addRenownAdaptersEventHandler as Ct, setPackageDiscoveryService as D, isPlainClick as Da, GraphQLDriveReadClient as Di, setSentryEnv as Dn, useVersionCheckInterval as Dr, addRequiresHardRefreshEventHandler as Dt, addPackageDiscoveryServiceEventHandler as E, withoutModalSearch as Ea, GraphQLDriveNodeSource as Ei, setSentryDsn as En, useVersion as Er, addRenownUrlEventHandler as Et, useDropTarget as F, convertRemoteOperations as Fi, useAnalyticsDatabaseName as Fn, phDocumentEditorConfigHooks as Fr, addVersionEventHandler as Ft, addCliVersionEventHandler as G, GraphQLOperationNotSupportedError as Gi, useIsAddDriveEnabled as Gn, isBackendAuthError as Gr, setDrivesPreserveStrategy as Gt, addAllowListEventHandler as H, DEFAULT_DRIVE_EDITOR_ID as Hi, useFileUploadOperationsChunkSize as Hn, useIsExternalControlsEnabled as Hr, setCliVersion as Ht, addFeaturesEventHandler as I, extractRevisionMap as Ii, useBasePath as In, phDocumentEditorConfigSetters as Ir, addWarnOutdatedAppEventHandler as It, addDrivesPreserveStrategyEventHandler as J, queriesUnknownArgument as Ji, useIsAnalyticsDatabaseWorkerEnabled as Jn, useBackendAuth as Jr, setGaTrackingId as Jt, addDefaultDrivesUrlEventHandler as K, GraphQLWrongBackendError as Ki, useIsAddLocalDrivesEnabled as Kn, recordBackendAuthError as Kr, setEnabledEditors as Kt, setFeatures as L, hasRevisionConflict as Li, useCliVersion as Ln, setAllowedDocumentTypes as Lr, phGlobalConfigHooks as Lt, addDraggingNodeEventHandler as M, revisionMapFromRevisionsList as Mi, setVersionCheckInterval as Mn, isExternalControlsEnabledEventFunctions as Mr, addStudioModeEventHandler as Mt, useDragNode as N, ConflictError as Ni, setWarnOutdatedApp as Nn, phAppConfigHooks as Nr, addSwitchboardUrlEventHandler as Nt, usePackageDiscoveryService as O, useLinkProps as Oa, toLegacyNode as Oi, setSentryRelease as On, useWarnOutdatedApp as Or, addRouterBasenameEventHandler as Ot, useDropNode as P, buildPulledDocument as Pi, useAllowList as Pn, phAppConfigSetters as Pr, addVersionCheckIntervalEventHandler as Pt, addIsAddCloudDrivesEnabledEventHandler as Q, addFolder$1 as Qi, useIsDeleteCloudDrivesEnabled as Qn, findIsServableOverGraphQL as Qr, setIsAddPublicDrivesEnabled as Qt, useFeatures as R, screamingSnakeToCamel as Ri, useDefaultDrivesUrl as Rn, setIsDragAndDropEnabled as Rr, phGlobalConfigSetters as Rt, addSetSelectedDriveOnPopStateEventHandler as S, showDeleteNodeModal as Sa, isNodeFetch as Si, setRenownNetworkId as Sn, useSentryEnv as Sr, addLogLevelEventHandler as St, syncSelectionFromPath as T, usePHModal as Ta, withStreamedBodies as Ti, setRouterBasename as Tn, useSwitchboardUrl as Tr, addRenownNetworkIdEventHandler as Tt, addAnalyticsDatabaseNameEventHandler as U, DRIVE_DOCUMENT_TYPES as Ui, useGaTrackingId as Un, addBackendAuthEventHandler as Ur, setDefaultDrivesUrl as Ut, useAttachmentService as V, COMMON_PACKAGE_ID as Vi, useEnabledEditors as Vn, useIsDragAndDropEnabled as Vr, setBasePath as Vt, addBasePathEventHandler as W, BatchJobFailedError as Wi, useIsAddCloudDrivesEnabled as Wn, backendAuthStatusOf as Wr, setDisabledEditors as Wt, addFileUploadOperationsChunkSizeEventHandler as X, addDocument as Xi, useIsAnalyticsExternalProcessorsEnabled as Xn, ambientRenownSigner as Xr, setIsAddDriveEnabled as Xt, addEnabledEditorsEventHandler as Y, queriesUnknownField as Yi, useIsAnalyticsEnabled as Yn, GraphQLReactorClient as Yr, setIsAddCloudDrivesEnabled as Yt, addGaTrackingIdEventHandler as Z, addFileWithProgress as Zi, useIsCloudDrivesEnabled as Zn, createGraphQLDriveNodeSource as Zr, setIsAddLocalDrivesEnabled as Zt, setSelectedTimelineRevision as _, modalFromSearch as _a, ReactorOperationFieldsFragmentDoc as _i, setIsSentryTracingEnabled as _n, useRenownNetworkId as _r, addIsLocalDrivesEnabledEventHandler as _t, SwitchboardUnreachableError as a, loadFile as aa, subscriptionsUrlFromGraphqlUrl as ai, setIsDeletePublicDrivesEnabled as an, useIsEditorReadModeEnabled as ar, addIsCloudDrivesEnabledEventHandler as at, setSelectedTimelineItem as b, setPHModal as ba, globalFetch as bi, setRenownAdapters as bn, useRouterBasename as br, addIsSentryTracingEnabledEventHandler as bt, ensurePHEventHandlers as c, renameNode as ca, subgraphUrlFromGraphqlUrl as ci, setIsDriveAnalyticsEnabled as cn, useIsExternalRelationalProcessorsEnabled as cr, addIsDeletePublicDrivesEnabledEventHandler as ct, callEventHandlerRegisterFunctions as d, getUserPermissions as da, resolveDocumentModelModule as di, setIsExternalPackagesEnabled as dn, useIsRelationalProcessorsEnabled as dr, addIsDriveAnalyticsEnabledEventHandler as dt, deleteNode as ea, viewFilterInputFromViewFilter as ei, setIsAnalyticsEnabled as en, useIsDeletePublicDrivesEnabled as er, addIsAddLocalDrivesEnabledEventHandler as et, commonGlobalEventHandlerFunctions as f, isDocumentTypeSupported as fa, prepareSignedActions as fi, setIsExternalProcessorsEnabled as fn, useIsSentryTracingEnabled as fr, addIsEditorDebugModeEnabledEventHandler as ft, addSelectedTimelineRevisionEventHandler as g, isRoutedModal as ga, MutateDocumentWithOperationsDocument as gi, setIsRelationalProcessorsEnabled as gn, useRenownChainId as gr, addIsExternalRelationalProcessorsEnabledEventHandler as gt, usePHToast as h, closePHModal as ha, GetDocumentAtConsistencyDocument as hi, setIsPublicDrivesEnabled as hn, useRenownAdapters as hr, addIsExternalProcessorsEnabledEventHandler as ht, DEFAULT_REQUEST_TIMEOUT_MS as i, getDocumentExtension as ia, startDocumentChangesSubscription as ii, setIsDeleteLocalDrivesEnabled as in, useIsEditorDebugModeEnabled as ir, addIsAnalyticsExternalProcessorsEnabledEventHandler as it, useGraphQLReactorClient as j, useSetSearchParams as ja, phDocumentFromMutation as ji, setVersion as jn, addIsExternalControlsEnabledEventHandler as jr, addSentryReleaseEventHandler as jt, addGraphQLReactorClientEventHandler as k, usePHNavigation as ka, isoStringFromDateTime as ki, setStudioMode as kn, addAllowedDocumentTypesEventHandler as kr, addSentryDsnEventHandler as kt, useSwitchboardClient as l, setPreferredEditorOnNode as la, StaticPackageManager as li, setIsEditorDebugModeEnabled as ln, useIsLocalDrivesEnabled as lr, addIsDiffAnalyticsEnabledEventHandler as lt, setPHToast as m, addModalEventHandler as ma, stampAction as mi, setIsLocalDrivesEnabled as mn, useLogLevel as mr, addIsExternalPackagesEnabledEventHandler as mt, DEFAULT_BATCH_REQUEST_TIMEOUT_MS as n, extractInitialState as na, isAuthRefusalClose as ni, setIsCloudDrivesEnabled as nn, useIsDocumentModelSelectionSettingsEnabled as nr, addIsAnalyticsDatabaseWorkerEnabledEventHandler as nt, createSwitchboardBackend as o, moveNode$1 as oa, SubgraphSdkRegistry as oi, setIsDiffAnalyticsEnabled as on, useIsExternalPackagesEnabled as or, addIsDeleteCloudDrivesEnabledEventHandler as ot, addToastEventHandler as p, MODAL_SEARCH_PARAM as pa, signStampedAction as pi, setIsExternalRelationalProcessorsEnabled as pn, useLocalDrivesEnabled as pr, addIsEditorReadModeEnabledEventHandler as pt, addDisabledEditorsEventHandler as q, JobFailedError as qi, useIsAddPublicDrivesEnabled as qn, setBackendAuth as qr, setFileUploadOperationsChunkSize as qt, DEFAULT_BREAKER as r, fetchDocumentOperations as ra, makeAuthConnectionParams as ri, setIsDeleteCloudDrivesEnabled as rn, useIsDriveAnalyticsEnabled as rr, addIsAnalyticsEnabledEventHandler as rt, GraphQLReactorProvider as s, renameDriveNode as sa, describeGraphQLDocument as si, setIsDocumentModelSelectionSettingsEnabled as sn, useIsExternalProcessorsEnabled as sr, addIsDeleteLocalDrivesEnabledEventHandler as st, useDocumentOperations as t, exportFile as ta, createJobChangesSocket as ti, setIsAnalyticsExternalProcessorsEnabled as tn, useIsDiffAnalyticsEnabled as tr, addIsAddPublicDrivesEnabledEventHandler as tt, addPHEventHandlers as u, upgradeDocument as ua, packageFromDocumentModels as ui, setIsEditorReadModeEnabled as un, useIsPublicDrivesEnabled as ur, addIsDocumentModelSelectionSettingsEnabledEventHandler as ut, useSelectedTimelineRevision as v, modalHref as va, readCreateProtocolVersions as vi, setLocalDrivesEnabled as vn, useRenownUrl as vr, addIsPublicDrivesEnabledEventHandler as vt, addSyncSelectionOnPopStateEventHandler as w, useModalLinkProps as wa, withRequestDeadline as wi, setRequiresHardRefresh as wn, useStudioMode as wr, addRenownChainIdEventHandler as wt, useSelectedTimelineItem as x, showCreateDocumentModal as xa, isDeadlineError as xi, setRenownChainId as xn, useSentryDsn as xr, addLocalDrivesEnabledEventHandler as xt, addSelectedTimelineItemEventHandler as y, modalSearch as ya, readCreateSignaturePolicy as yi, setLogLevel as yn, useRequiresHardRefresh as yr, addIsRelationalProcessorsEnabledEventHandler as yt, addAttachmentServiceEventHandler as z, uncreatedDocument as zi, useDisabledEditors as zn, setIsExternalControlsEnabled as zr, setAllowList as zt };
|
|
2629
4608
|
|
|
2630
|
-
//# sourceMappingURL=document-operations-
|
|
4609
|
+
//# sourceMappingURL=document-operations-DRMMwmGZ.js.map
|