@powerhousedao/reactor-browser 6.2.3-dev.9 → 6.2.3-dev.91
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{attachment-service-D3EhiAJ7.d.ts → attachment-service-10Qn5nIw.d.ts} +766 -108
- package/dist/attachment-service-10Qn5nIw.d.ts.map +1 -0
- package/dist/auth-DzIYxeEJ.d.ts +32 -0
- package/dist/auth-DzIYxeEJ.d.ts.map +1 -0
- package/dist/{client-DjK30EQ-.js → client-BFnMV-EO.js} +39 -22
- package/dist/client-BFnMV-EO.js.map +1 -0
- package/dist/{client-D66jVnot.js → client-BNMyQ_Z2.js} +372 -33
- package/dist/client-BNMyQ_Z2.js.map +1 -0
- package/dist/{client-BIHN_UyR.d.ts → client-C-NgSjoc.d.ts} +4 -3
- package/dist/client-C-NgSjoc.d.ts.map +1 -0
- package/dist/dispatch-Cylwl2Dk.js +1173 -0
- package/dist/dispatch-Cylwl2Dk.js.map +1 -0
- package/dist/document-by-id-DdvqanGR.js +16 -0
- package/dist/document-by-id-DdvqanGR.js.map +1 -0
- package/dist/document-model-modules-ChmfyIxT.js +644 -0
- package/dist/document-model-modules-ChmfyIxT.js.map +1 -0
- package/dist/document-operations-QtU34A52.js +4664 -0
- package/dist/document-operations-QtU34A52.js.map +1 -0
- package/dist/global-bbfp3_1x.d.ts +649 -0
- package/dist/global-bbfp3_1x.d.ts.map +1 -0
- package/dist/{index-B33TKEqp.d.ts → index-Bfr_cWdi.d.ts} +31 -100
- package/dist/index-Bfr_cWdi.d.ts.map +1 -0
- package/dist/{index-BIVDXw3K.d.ts → index-rtDmzViP.d.ts} +3 -3
- package/dist/index-rtDmzViP.d.ts.map +1 -0
- package/dist/index.d.ts +837 -411
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +851 -129
- 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/{pglite-CntadC_p-9NDG14dS.d.ts → pglite-CntadC_p-DTkdF8sr.d.ts} +11 -33
- package/dist/pglite-CntadC_p-DTkdF8sr.d.ts.map +1 -0
- package/dist/{relational-D1RB45sA.js → relational-DZuyKp2y.js} +66 -5
- package/dist/relational-DZuyKp2y.js.map +1 -0
- package/dist/{renown-rqK8sokh.js → renown-B3MUaiq7.js} +61 -31
- 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/{types-Dcv1ZLoW.d.ts → schema-Bn6L3QR1.d.ts} +324 -64
- package/dist/schema-Bn6L3QR1.d.ts.map +1 -0
- package/dist/src/ai/index.d.ts +276 -75
- package/dist/src/ai/index.d.ts.map +1 -1
- package/dist/src/ai/index.js +733 -172
- package/dist/src/ai/index.js.map +1 -1
- package/dist/src/analytics/index.d.ts +36 -44
- package/dist/src/analytics/index.d.ts.map +1 -1
- package/dist/src/analytics/index.js +4 -4
- package/dist/src/analytics/index.js.map +1 -1
- package/dist/src/document-model.d.ts +3 -4
- package/dist/src/document-model.d.ts.map +1 -1
- package/dist/src/document-model.js.map +1 -1
- package/dist/src/graphql/client.d.ts +4 -3
- 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 +15 -9
- 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 +3 -2
- package/dist/src/renown/index.js +3 -3
- package/dist/src/rpc/index.d.ts +217 -140
- package/dist/src/rpc/index.d.ts.map +1 -1
- package/dist/src/rpc/index.js +600 -623
- package/dist/src/rpc/index.js.map +1 -1
- package/dist/{store-BJYcr_FL.js → store-DInXcjal.js} +1 -1
- package/dist/{store-BJYcr_FL.js.map → store-DInXcjal.js.map} +1 -1
- package/dist/{switchboard-CaXQ4-5Q.js → switchboard-B640iT1L.js} +61 -11
- package/dist/switchboard-B640iT1L.js.map +1 -0
- package/dist/{types-6vDzbRRS.d.ts → types-520nWrB3.d.ts} +2 -2
- package/dist/types-520nWrB3.d.ts.map +1 -0
- package/dist/types-CT44EMmw.d.ts +59 -0
- package/dist/types-CT44EMmw.d.ts.map +1 -0
- package/package.json +24 -23
- package/dist/attachment-service-D3EhiAJ7.d.ts.map +0 -1
- package/dist/client-BIHN_UyR.d.ts.map +0 -1
- package/dist/client-D66jVnot.js.map +0 -1
- package/dist/client-DjK30EQ-.js.map +0 -1
- package/dist/document-by-id-B4FIzG1w.js +0 -519
- package/dist/document-by-id-B4FIzG1w.js.map +0 -1
- package/dist/document-model-modules-bTP87nyr.js +0 -419
- package/dist/document-model-modules-bTP87nyr.js.map +0 -1
- package/dist/document-operations-WeE6wIDt.js +0 -2603
- package/dist/document-operations-WeE6wIDt.js.map +0 -1
- package/dist/global-OuINvEGT.d.ts +0 -401
- package/dist/global-OuINvEGT.d.ts.map +0 -1
- package/dist/index-B33TKEqp.d.ts.map +0 -1
- package/dist/index-BIVDXw3K.d.ts.map +0 -1
- package/dist/inspector-proxy-6h5VKAwt.d.ts +0 -257
- package/dist/inspector-proxy-6h5VKAwt.d.ts.map +0 -1
- package/dist/make-ph-event-functions-DBq3iWYn.js +0 -53
- package/dist/make-ph-event-functions-DBq3iWYn.js.map +0 -1
- package/dist/pglite-CntadC_p-9NDG14dS.d.ts.map +0 -1
- package/dist/relational-D1RB45sA.js.map +0 -1
- package/dist/renown-BHxwP7xU.js +0 -97
- package/dist/renown-BHxwP7xU.js.map +0 -1
- package/dist/renown-rqK8sokh.js.map +0 -1
- package/dist/switchboard-CaXQ4-5Q.js.map +0 -1
- package/dist/types-6vDzbRRS.d.ts.map +0 -1
- package/dist/types-Dcv1ZLoW.d.ts.map +0 -1
|
@@ -0,0 +1,4664 @@
|
|
|
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 { $ as makeAuthMiddleware, A as addDrivesEventHandler, B as invalidateDriveNodes, H as markLocalDriveWrite, L as addDriveNodesEventHandler, Q as ambientRenownTokenProvider, R as dropDriveNode, X as listAllDriveNodes, a as setVetraPackageManager, c as addSelectedDriveIdEventHandler, f as setSelectedDriveId, h as useSelectedDriveId, r as addVetraPackageManagerEventHandler, u as selectDrive, v as addResetSelectedNodeEventHandler, w as setSelectedNodeId, y as addSelectedNodeIdEventHandler, z as getDriveNode } from "./document-model-modules-ChmfyIxT.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 PhDocumentFieldsFragmentDoc, i as JobChangesDocument, n as DocumentChangesDocument, t as createClient$1 } from "./client-BNMyQ_Z2.js";
|
|
6
|
+
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
|
7
|
+
import { Fragment, jsx } from "react/jsx-runtime";
|
|
8
|
+
import { logger } from "document-model";
|
|
9
|
+
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";
|
|
10
|
+
import { addFolder, copyNode, driveDocumentModelModule, generateNodesCopy, handleTargetNameCollisions, isFileNode, isFolderNode, moveNode, updateNode } from "@powerhousedao/shared/document-drive";
|
|
11
|
+
import { allPass, conditional, constant, forEachObj, funnel, isDefined, isNot, isStrictEqual, isString, isTruthy, once } from "remeda";
|
|
12
|
+
import { DRIVE_CHILD_RELATIONSHIP_TYPE } from "@powerhousedao/reactor-drive";
|
|
13
|
+
import { gql } from "graphql-tag";
|
|
14
|
+
import { Kind, print } from "graphql";
|
|
15
|
+
import { GraphQLClient } from "graphql-request";
|
|
16
|
+
import { createClient } from "graphql-ws/client";
|
|
17
|
+
//#region src/hooks/url-state.ts
|
|
18
|
+
/** The nearest store's navigation, else the bound store's, else the browser's.
|
|
19
|
+
* Hosts set it once, so hook order holds. */
|
|
20
|
+
function usePHNavigation() {
|
|
21
|
+
return usePHStore()?.navigation ?? getPHNavigation();
|
|
22
|
+
}
|
|
23
|
+
/** The current query params. */
|
|
24
|
+
function useSearchParams() {
|
|
25
|
+
return usePHNavigation().useSearchParams();
|
|
26
|
+
}
|
|
27
|
+
/** Sets query params: an object merges into them, a function returns them all. */
|
|
28
|
+
function useSetSearchParams() {
|
|
29
|
+
return usePHNavigation().useSetSearchParams();
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
//#region src/hooks/link-props.ts
|
|
33
|
+
/** A plain primary click; modified and other-button clicks stay the browser's. */
|
|
34
|
+
function isPlainClick(event) {
|
|
35
|
+
return !event.defaultPrevented && event.button === 0 && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey;
|
|
36
|
+
}
|
|
37
|
+
/** Props for an `<a>` that opens `target` in the app on a plain click, and
|
|
38
|
+
* leaves new tabs and windows to the browser; acts on the store in context. */
|
|
39
|
+
function useLinkProps(target, open) {
|
|
40
|
+
const navigation = usePHNavigation();
|
|
41
|
+
const href = navigation.hrefFor?.(target) ?? targetPathname(target);
|
|
42
|
+
const isCurrent = navigation.useIsCurrent?.(target) ?? false;
|
|
43
|
+
const preload = () => navigation.preload?.(target);
|
|
44
|
+
const openTarget = open ?? (() => openTargetWith(navigation, target));
|
|
45
|
+
return {
|
|
46
|
+
href,
|
|
47
|
+
onClick: (event) => {
|
|
48
|
+
if (!isPlainClick(event)) return;
|
|
49
|
+
event.preventDefault();
|
|
50
|
+
openTarget();
|
|
51
|
+
},
|
|
52
|
+
onMouseEnter: preload,
|
|
53
|
+
onFocus: preload,
|
|
54
|
+
"aria-current": isCurrent ? "page" : void 0
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
//#endregion
|
|
58
|
+
//#region src/hooks/modals.ts
|
|
59
|
+
const modalEventFunctions = makePHEventFunctions("modal");
|
|
60
|
+
/** Returns the current modal */
|
|
61
|
+
const usePHModal = modalEventFunctions.useValue;
|
|
62
|
+
/** Sets the current modal */
|
|
63
|
+
const setPHModal = modalEventFunctions.setValue;
|
|
64
|
+
/** Adds an event handler for the modal */
|
|
65
|
+
const addModalEventHandler = modalEventFunctions.addEventHandler;
|
|
66
|
+
/** The query param that names a routed modal. */
|
|
67
|
+
const MODAL_SEARCH_PARAM = "modal";
|
|
68
|
+
const MODAL_ROUTES = {
|
|
69
|
+
createDocument: {
|
|
70
|
+
id: "create-document",
|
|
71
|
+
toSearch: ({ documentType, documentModelVersion, driveId }) => ({
|
|
72
|
+
documentType,
|
|
73
|
+
...documentModelVersion !== void 0 && { documentModelVersion: String(documentModelVersion) },
|
|
74
|
+
...driveId && { driveId }
|
|
75
|
+
}),
|
|
76
|
+
fromSearch: (search) => ({
|
|
77
|
+
documentType: search.documentType ?? "",
|
|
78
|
+
...search.documentModelVersion && { documentModelVersion: Number(search.documentModelVersion) },
|
|
79
|
+
...search.driveId && { driveId: search.driveId }
|
|
80
|
+
})
|
|
81
|
+
},
|
|
82
|
+
login: { id: "login" },
|
|
83
|
+
addDrive: { id: "add-drive" },
|
|
84
|
+
driveSettings: {
|
|
85
|
+
id: "drive-settings",
|
|
86
|
+
toSearch: ({ driveId }) => ({ driveId }),
|
|
87
|
+
fromSearch: (search) => ({ driveId: search.driveId ?? "" })
|
|
88
|
+
},
|
|
89
|
+
debugSettings: { id: "debug-settings" },
|
|
90
|
+
inspector: { id: "inspector" },
|
|
91
|
+
disclaimer: { id: "disclaimer" },
|
|
92
|
+
cookiesPolicy: { id: "cookies-policy" }
|
|
93
|
+
};
|
|
94
|
+
const routeOf = (type) => MODAL_ROUTES[type];
|
|
95
|
+
/** Whether `modal` lives in the URL rather than the store. */
|
|
96
|
+
function isRoutedModal(modal) {
|
|
97
|
+
return !!modal && !!routeOf(modal.type);
|
|
98
|
+
}
|
|
99
|
+
/** The query params that open `modal`; undefined for one the store holds. */
|
|
100
|
+
function modalSearch(modal) {
|
|
101
|
+
const route = routeOf(modal.type);
|
|
102
|
+
if (!route) return void 0;
|
|
103
|
+
return {
|
|
104
|
+
[MODAL_SEARCH_PARAM]: route.id,
|
|
105
|
+
...route.toSearch?.(modal)
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
/** The routed modal `search` opens, if any. */
|
|
109
|
+
function modalFromSearch(search) {
|
|
110
|
+
const id = search[MODAL_SEARCH_PARAM];
|
|
111
|
+
if (typeof id !== "string") return void 0;
|
|
112
|
+
const strings = Object.fromEntries(Object.entries(search).map(([key, value]) => [key, String(value)]));
|
|
113
|
+
for (const [type, route] of Object.entries(MODAL_ROUTES)) {
|
|
114
|
+
if (route.id !== id) continue;
|
|
115
|
+
return {
|
|
116
|
+
type,
|
|
117
|
+
...route.fromSearch?.(strings)
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/** `search` without a routed modal's params. */
|
|
122
|
+
function withoutModalSearch(search) {
|
|
123
|
+
const modal = modalFromSearch(search);
|
|
124
|
+
const own = modal ? Object.keys(modalSearch(modal) ?? {}) : [];
|
|
125
|
+
return Object.fromEntries(Object.entries(search).filter(([key]) => !own.includes(key)));
|
|
126
|
+
}
|
|
127
|
+
/** Shows a modal. With a host navigation, a routed one opens in the URL, in
|
|
128
|
+
* place of the current entry, and "settings" opens the settings page. */
|
|
129
|
+
function showPHModal(modal) {
|
|
130
|
+
if (modal.type === "settings" && hasHostNavigation()) {
|
|
131
|
+
openTarget({ settings: true });
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
const search = modalSearch(modal);
|
|
135
|
+
if (search && hasHostNavigation()) {
|
|
136
|
+
if (!isRoutedModal(modalEventFunctions.getSnapshot())) setPHModal(void 0);
|
|
137
|
+
getPHNavigation().setSearch((prev) => ({
|
|
138
|
+
...withoutModalSearch(prev),
|
|
139
|
+
...search
|
|
140
|
+
}), { replace: true });
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
setPHModal(modal);
|
|
144
|
+
}
|
|
145
|
+
/** Closes the current modal; a routed one leaves the URL in place of the entry,
|
|
146
|
+
* and a confirmation opened over it closes with it. */
|
|
147
|
+
function closePHModal() {
|
|
148
|
+
if (hasHostNavigation()) {
|
|
149
|
+
const navigation = getPHNavigation();
|
|
150
|
+
if (modalFromSearch(searchToRecord(navigation.location().search))) {
|
|
151
|
+
navigation.setSearch((prev) => withoutModalSearch(prev), { replace: true });
|
|
152
|
+
if (!isRoutedModal(modalEventFunctions.getSnapshot())) setPHModal(void 0);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
setPHModal(void 0);
|
|
157
|
+
}
|
|
158
|
+
/** The href that opens `modal` over the current page. */
|
|
159
|
+
function modalHref(modal) {
|
|
160
|
+
const { pathname, search } = getPHNavigation().location();
|
|
161
|
+
const next = {
|
|
162
|
+
...withoutModalSearch(searchToRecord(search)),
|
|
163
|
+
...modalSearch(modal)
|
|
164
|
+
};
|
|
165
|
+
return `${pathname}${recordToSearch(next)}`;
|
|
166
|
+
}
|
|
167
|
+
/** Props for an `<a>` that opens a routed `modal` over the current page on a
|
|
168
|
+
* plain click; new tabs and copied links get its URL. */
|
|
169
|
+
function useModalLinkProps(modal) {
|
|
170
|
+
useSearchParams();
|
|
171
|
+
return {
|
|
172
|
+
href: modalHref(modal),
|
|
173
|
+
onClick: (event) => {
|
|
174
|
+
if (!isPlainClick(event)) return;
|
|
175
|
+
event.preventDefault();
|
|
176
|
+
showPHModal(modal);
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
/** Shows the create document modal */
|
|
181
|
+
function showCreateDocumentModal(documentType, documentModelVersion) {
|
|
182
|
+
showPHModal({
|
|
183
|
+
type: "createDocument",
|
|
184
|
+
documentType,
|
|
185
|
+
...documentModelVersion !== void 0 && { documentModelVersion }
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
/** Shows the delete node modal */
|
|
189
|
+
function showDeleteNodeModal(nodeOrId) {
|
|
190
|
+
const id = typeof nodeOrId === "string" ? nodeOrId : nodeOrId.id;
|
|
191
|
+
setPHModal({
|
|
192
|
+
type: "deleteItem",
|
|
193
|
+
id
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
//#endregion
|
|
197
|
+
//#region src/hooks/reactor.ts
|
|
198
|
+
const reactorClientModuleEventFunctions = makePHEventFunctions("reactorClientModule");
|
|
199
|
+
const reactorClientEventFunctions = makePHEventFunctions("reactorClient");
|
|
200
|
+
const reactorHalvesEventFunctions = makePHEventFunctions("reactor");
|
|
201
|
+
const fullReactorClientEventFunctions = makePHEventFunctions("fullReactorClient");
|
|
202
|
+
/** Returns the reactor client module (in-process or worker-backed) */
|
|
203
|
+
const useReactorClientModule = reactorClientModuleEventFunctions.useValue;
|
|
204
|
+
/** Sets the reactor client module */
|
|
205
|
+
const setReactorClientModule = reactorClientModuleEventFunctions.setValue;
|
|
206
|
+
/** Adds an event handler for the reactor client module */
|
|
207
|
+
const addReactorClientModuleEventHandler = reactorClientModuleEventFunctions.addEventHandler;
|
|
208
|
+
/** Returns the reactor client */
|
|
209
|
+
const useReactorClient = reactorClientEventFunctions.useValue;
|
|
210
|
+
/**
|
|
211
|
+
* Sets the reactor client, and `window.ph.reactor` to its read and write
|
|
212
|
+
* halves. A client without halves leaves `reactor` unset.
|
|
213
|
+
*/
|
|
214
|
+
const setReactorClient = (client) => {
|
|
215
|
+
reactorClientEventFunctions.setValue(client);
|
|
216
|
+
reactorHalvesEventFunctions.setValue(halvesOf(client));
|
|
217
|
+
};
|
|
218
|
+
/** Returns the reactor client's read and write halves */
|
|
219
|
+
const useReactorHalves = reactorHalvesEventFunctions.useValue;
|
|
220
|
+
/** Adds an event handler for the reactor client's halves */
|
|
221
|
+
const addReactorHalvesEventHandler = reactorHalvesEventFunctions.addEventHandler;
|
|
222
|
+
function halvesOf(client) {
|
|
223
|
+
const read = client?.read;
|
|
224
|
+
const write = client?.write;
|
|
225
|
+
return read && write ? {
|
|
226
|
+
read,
|
|
227
|
+
write
|
|
228
|
+
} : void 0;
|
|
229
|
+
}
|
|
230
|
+
/** Adds an event handler for the reactor client */
|
|
231
|
+
const addReactorClientEventHandler = reactorClientEventFunctions.addEventHandler;
|
|
232
|
+
/** Sets the client full-client actions use instead of the module's */
|
|
233
|
+
const setFullReactorClient = fullReactorClientEventFunctions.setValue;
|
|
234
|
+
/** Adds an event handler for the full reactor client */
|
|
235
|
+
const addFullReactorClientEventHandler = fullReactorClientEventFunctions.addEventHandler;
|
|
236
|
+
/** The client full-client actions use: the one set, else the module's. */
|
|
237
|
+
function getFullReactorClient() {
|
|
238
|
+
return getPHStore()?.fullReactorClient ?? getPHStore()?.reactorClientModule?.client;
|
|
239
|
+
}
|
|
240
|
+
const useSync = () => useReactorClientModule()?.reactorModule?.syncModule?.syncManager;
|
|
241
|
+
const useSyncList = () => {
|
|
242
|
+
return useSync()?.list() ?? [];
|
|
243
|
+
};
|
|
244
|
+
const useModelRegistry = () => useReactorClientModule()?.reactorModule?.documentModelRegistry;
|
|
245
|
+
const useDatabase = () => {
|
|
246
|
+
const module = useReactorClientModule();
|
|
247
|
+
return module?.kind === "browser" ? module.reactorModule?.database : void 0;
|
|
248
|
+
};
|
|
249
|
+
const usePGlite = () => {
|
|
250
|
+
const module = useReactorClientModule();
|
|
251
|
+
return module?.kind === "browser" ? module.reactorModule?.pg : void 0;
|
|
252
|
+
};
|
|
253
|
+
//#endregion
|
|
254
|
+
//#region src/utils/documents.ts
|
|
255
|
+
function isDocumentTypeSupported(documentType, supportedDocuments) {
|
|
256
|
+
if (!supportedDocuments?.length) return true;
|
|
257
|
+
return supportedDocuments.some((pattern) => {
|
|
258
|
+
if (pattern.endsWith("/*")) {
|
|
259
|
+
const prefix = pattern.slice(0, -2);
|
|
260
|
+
return documentType.startsWith(prefix + "/");
|
|
261
|
+
}
|
|
262
|
+
if (pattern.endsWith("*") && !pattern.endsWith("/*")) {
|
|
263
|
+
const prefix = pattern.slice(0, -1);
|
|
264
|
+
return documentType.startsWith(prefix);
|
|
265
|
+
}
|
|
266
|
+
return pattern === documentType;
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
//#endregion
|
|
270
|
+
//#region src/utils/user.ts
|
|
271
|
+
function getUserPermissions() {
|
|
272
|
+
const user = getPHStore()?.renown?.user;
|
|
273
|
+
const allowList = getPHStore()?.allowList;
|
|
274
|
+
if (!allowList) return {
|
|
275
|
+
isAllowedToCreateDocuments: true,
|
|
276
|
+
isAllowedToEditDocuments: true
|
|
277
|
+
};
|
|
278
|
+
return {
|
|
279
|
+
isAllowedToCreateDocuments: allowList.includes(user?.address ?? ""),
|
|
280
|
+
isAllowedToEditDocuments: allowList.includes(user?.address ?? "")
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
//#endregion
|
|
284
|
+
//#region src/actions/document.ts
|
|
285
|
+
const NON_DOMAIN_SCOPES = /* @__PURE__ */ new Set(["auth", "document"]);
|
|
286
|
+
/** Puts a node this tab just wrote into its drive's cache, so hooks show it
|
|
287
|
+
* before the drive change that follows the write is processed. Best effort:
|
|
288
|
+
* a client without a node reader is left to that change. */
|
|
289
|
+
async function rememberDriveNode(driveId, nodeId) {
|
|
290
|
+
try {
|
|
291
|
+
await getDriveNode(driveId, nodeId, { refresh: true });
|
|
292
|
+
} catch (error) {
|
|
293
|
+
logger.verbose("Caching the written node @id failed: @error", nodeId, error);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
/** An unreadable drive cannot be shown to hold no duplicate, so reads throw. */
|
|
297
|
+
async function isDocumentInLocation(reactorClient, document, driveId, parentFolder) {
|
|
298
|
+
const siblings = await listAllDriveNodes(reactorClient.drives, driveId, { parentFolder: parentFolder ?? null });
|
|
299
|
+
const nodeById = siblings.find((node) => node.id === document.header.id);
|
|
300
|
+
if (nodeById) return {
|
|
301
|
+
isDuplicate: true,
|
|
302
|
+
duplicateType: "id",
|
|
303
|
+
nodeId: nodeById.id
|
|
304
|
+
};
|
|
305
|
+
const nodeByNameAndType = siblings.find((node) => isFileNode(node) && node.name === document.header.name && node.documentType === document.header.documentType);
|
|
306
|
+
if (nodeByNameAndType) return {
|
|
307
|
+
isDuplicate: true,
|
|
308
|
+
duplicateType: "name",
|
|
309
|
+
nodeId: nodeByNameAndType.id
|
|
310
|
+
};
|
|
311
|
+
return { isDuplicate: false };
|
|
312
|
+
}
|
|
313
|
+
function getDocumentTypeIcon(document) {
|
|
314
|
+
switch (document.header.documentType) {
|
|
315
|
+
case "powerhouse/document-model": return "document-model";
|
|
316
|
+
case "powerhouse/app": return "app";
|
|
317
|
+
case "powerhouse/document-editor": return "editor";
|
|
318
|
+
case "powerhouse/subgraph": return "subgraph";
|
|
319
|
+
case "powerhouse/package": return "package";
|
|
320
|
+
case "powerhouse/processor": {
|
|
321
|
+
const processorType = document.state.global?.type;
|
|
322
|
+
if (processorType === "analytics") return "analytics-processor";
|
|
323
|
+
if (processorType === "relational") return "relational-processor";
|
|
324
|
+
if (processorType === "codegen") return "codegen-processor";
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
default: return;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
async function downloadFile(document, fileName) {
|
|
331
|
+
try {
|
|
332
|
+
const data = await createZip(document);
|
|
333
|
+
const blob = new Blob([new Uint8Array(data)], { type: "application/zip" });
|
|
334
|
+
const link = window.document.createElement("a");
|
|
335
|
+
link.style.display = "none";
|
|
336
|
+
link.href = URL.createObjectURL(blob);
|
|
337
|
+
link.download = fileName;
|
|
338
|
+
window.document.body.appendChild(link);
|
|
339
|
+
link.click();
|
|
340
|
+
window.document.body.removeChild(link);
|
|
341
|
+
} catch (e) {
|
|
342
|
+
logger.error(e instanceof Error ? e.message : String(e));
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
async function getDocumentExtension(document) {
|
|
346
|
+
const documentType = document.header.documentType;
|
|
347
|
+
let rawExtension;
|
|
348
|
+
if (documentType === documentModelDocumentType) rawExtension = document.state.global?.extension;
|
|
349
|
+
else {
|
|
350
|
+
const reactorClient = getFullReactorClient();
|
|
351
|
+
if (reactorClient) {
|
|
352
|
+
const { results: documentModelModules } = await reactorClient.read.getDocumentModelModules();
|
|
353
|
+
rawExtension = documentModelModules.find((m) => m.documentModel.global.id === documentType)?.utils.fileExtension;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
return (rawExtension ?? "").replace(/^\.+|\.+$/g, "");
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Fetches all operations for a document using cursor-based pagination.
|
|
360
|
+
* The reactor client handles multi-scope cursors transparently via
|
|
361
|
+
* composite cursors, so all scopes are fetched in a single paginated stream.
|
|
362
|
+
*/
|
|
363
|
+
async function fetchDocumentOperations(reactorClient, document, pageSize = 100) {
|
|
364
|
+
const scopes = Object.keys(document.state);
|
|
365
|
+
const operations = {};
|
|
366
|
+
for (const scope of scopes) operations[scope] = [];
|
|
367
|
+
let cursor = "";
|
|
368
|
+
do {
|
|
369
|
+
const page = await reactorClient.getOperations(document.header.id, { scopes }, void 0, {
|
|
370
|
+
cursor,
|
|
371
|
+
limit: pageSize
|
|
372
|
+
});
|
|
373
|
+
for (const op of page.results) {
|
|
374
|
+
const scope = op.action.scope ?? "global";
|
|
375
|
+
if (operations[scope]) operations[scope].push(op);
|
|
376
|
+
}
|
|
377
|
+
cursor = page.nextCursor ?? "";
|
|
378
|
+
} while (cursor);
|
|
379
|
+
return operations;
|
|
380
|
+
}
|
|
381
|
+
function extractInitialState(documentScopeOps) {
|
|
382
|
+
const initialState = creationState(documentScopeOps);
|
|
383
|
+
if (initialState) return initialState;
|
|
384
|
+
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");
|
|
385
|
+
}
|
|
386
|
+
function filterDomainOperations(operations) {
|
|
387
|
+
return Object.fromEntries(Object.entries(operations).filter(([scope]) => !NON_DOMAIN_SCOPES.has(scope)));
|
|
388
|
+
}
|
|
389
|
+
function countOperations(operations) {
|
|
390
|
+
let total = 0;
|
|
391
|
+
for (const ops of Object.values(operations)) total += ops?.length ?? 0;
|
|
392
|
+
return total;
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Split an imported document's domain operations at its mid-history upgrade
|
|
396
|
+
* boundaries, so the caller can re-dispatch each upgrade between segments.
|
|
397
|
+
*
|
|
398
|
+
* The seed's CREATE_DOCUMENT and 0 -> N upgrade are replayed by the creation
|
|
399
|
+
* path and must not be repeated. A later upgrade must be: it is where the
|
|
400
|
+
* reducer version changes, and dropping it replays everything after it through
|
|
401
|
+
* the module the document was created with.
|
|
402
|
+
*/
|
|
403
|
+
function splitAtUpgradeBoundaries(operations) {
|
|
404
|
+
const upgrades = (operations.document ?? []).filter((op) => op.action.type === "UPGRADE_DOCUMENT").filter((op) => op.action.input.fromVersion > 0).sort((a, b) => a.index - b.index);
|
|
405
|
+
const domain = filterDomainOperations(operations);
|
|
406
|
+
if (upgrades.length === 0) return [{ operations: domain }];
|
|
407
|
+
const segments = [];
|
|
408
|
+
const consumed = /* @__PURE__ */ new Map();
|
|
409
|
+
const take = (until) => {
|
|
410
|
+
const slice = {};
|
|
411
|
+
for (const [scope, ops] of Object.entries(domain)) {
|
|
412
|
+
if (!ops) continue;
|
|
413
|
+
const from = consumed.get(scope) ?? 0;
|
|
414
|
+
const stop = Math.max(from, until(scope, ops));
|
|
415
|
+
const chunk = ops.slice(from, stop);
|
|
416
|
+
if (chunk.length > 0) slice[scope] = chunk;
|
|
417
|
+
consumed.set(scope, stop);
|
|
418
|
+
}
|
|
419
|
+
return slice;
|
|
420
|
+
};
|
|
421
|
+
for (const upgrade of upgrades) {
|
|
422
|
+
const input = upgrade.action.input;
|
|
423
|
+
const slice = take((scope, ops) => boundary(upgrade, scope, ops));
|
|
424
|
+
segments.push({
|
|
425
|
+
operations: slice,
|
|
426
|
+
upgradeTo: input.toVersion
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
const tail = take((_scope, ops) => ops.length);
|
|
430
|
+
if (countOperations(tail) > 0) segments.push({ operations: tail });
|
|
431
|
+
return segments;
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* How many of a scope's operations precede an upgrade. Must stay identical to
|
|
435
|
+
* the boundary computation in `replayDocumentVersioned` — snapshots compare
|
|
436
|
+
* against operation indices, not array positions, and the timestamp fallback
|
|
437
|
+
* excludes the upgrade's own instant.
|
|
438
|
+
*/
|
|
439
|
+
function boundary(upgrade, scope, ops) {
|
|
440
|
+
const snapshot = upgrade.action.input.revision;
|
|
441
|
+
if (snapshot !== void 0) {
|
|
442
|
+
const revision = snapshot[scope] ?? 0;
|
|
443
|
+
let count = 0;
|
|
444
|
+
for (let i = 0; i < ops.length; i++) if (ops[i].index < revision) count = i + 1;
|
|
445
|
+
return count;
|
|
446
|
+
}
|
|
447
|
+
for (let i = 0; i < ops.length; i++) if (ops[i].timestampUtcMs >= upgrade.timestampUtcMs) return i;
|
|
448
|
+
return ops.length;
|
|
449
|
+
}
|
|
450
|
+
async function exportFile(document, suggestedName) {
|
|
451
|
+
const reactorClient = getPHStore()?.reactorClient;
|
|
452
|
+
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
453
|
+
const operations = await fetchDocumentOperations(reactorClient.read, document);
|
|
454
|
+
const initialState = extractInitialState(operations["document"] ?? []);
|
|
455
|
+
const documentWithOps = {
|
|
456
|
+
...document,
|
|
457
|
+
operations,
|
|
458
|
+
initialState
|
|
459
|
+
};
|
|
460
|
+
const extension = await getDocumentExtension(documentWithOps);
|
|
461
|
+
const baseName = suggestedName || documentWithOps.header.name || "Untitled";
|
|
462
|
+
const name = extension ? `${baseName}.${extension}.phd` : `${baseName}.phd`;
|
|
463
|
+
if (!window.showSaveFilePicker) return await downloadFile(documentWithOps, name);
|
|
464
|
+
try {
|
|
465
|
+
const fileHandle = await window.showSaveFilePicker({ suggestedName: name });
|
|
466
|
+
await baseSaveToFileHandle(documentWithOps, fileHandle);
|
|
467
|
+
return fileHandle;
|
|
468
|
+
} catch (e) {
|
|
469
|
+
if (!(e instanceof DOMException && e.name === "AbortError")) throw e;
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
/**
|
|
473
|
+
* Loads a document file and replays it with version-aware reducers from the registry.
|
|
474
|
+
* Falls back to single-version legacy replay when no upgrade manifest is registered for
|
|
475
|
+
* the document type.
|
|
476
|
+
*/
|
|
477
|
+
async function loadFile(path) {
|
|
478
|
+
const baseDocument = await baseLoadFromInput(path, (state) => state, { checkHashes: true });
|
|
479
|
+
const reactorClient = getFullReactorClient();
|
|
480
|
+
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
481
|
+
const documentType = baseDocument.header.documentType;
|
|
482
|
+
const { results: documentModelModules } = await reactorClient.read.getDocumentModelModules();
|
|
483
|
+
const modulesForType = documentModelModules.filter((module) => module.documentModel.global.id === documentType);
|
|
484
|
+
if (modulesForType.length === 0) throw new DocumentModelNotFoundError(documentType);
|
|
485
|
+
const reducers = {};
|
|
486
|
+
for (const module of modulesForType) reducers[module.version ?? 1] = module.reducer;
|
|
487
|
+
const registry = getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;
|
|
488
|
+
let upgradeManifest;
|
|
489
|
+
if (registry) try {
|
|
490
|
+
upgradeManifest = registry.getUpgradeManifest(documentType);
|
|
491
|
+
} catch {}
|
|
492
|
+
return baseLoadFromInputVersioned(path, {
|
|
493
|
+
reducers,
|
|
494
|
+
upgradeManifest
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
async function addDocument(driveId, name, documentType, parentFolder, document, id, preferredEditor, documentModelVersion) {
|
|
498
|
+
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
499
|
+
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create documents");
|
|
500
|
+
const reactorClient = getFullReactorClient();
|
|
501
|
+
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
502
|
+
const newDocument = document ?? await reactorClient.read.newDocument(documentType, {
|
|
503
|
+
parentIdentifier: driveId,
|
|
504
|
+
documentModelVersion
|
|
505
|
+
});
|
|
506
|
+
newDocument.header.name = name;
|
|
507
|
+
if (preferredEditor) newDocument.header.meta = {
|
|
508
|
+
...newDocument.header.meta,
|
|
509
|
+
preferredEditor
|
|
510
|
+
};
|
|
511
|
+
markLocalDriveWrite(driveId);
|
|
512
|
+
let newDoc;
|
|
513
|
+
try {
|
|
514
|
+
newDoc = await (await reactorClient.write.drives.addFile(driveId, newDocument, parentFolder)).document();
|
|
515
|
+
} catch (e) {
|
|
516
|
+
logger.error("Error adding document: @error", e);
|
|
517
|
+
throw new Error("There was an error adding document", { cause: e });
|
|
518
|
+
}
|
|
519
|
+
await rememberDriveNode(driveId, newDoc.header.id);
|
|
520
|
+
await getDriveNode(driveId, newDoc.header.id, { refresh: true }).catch(() => void 0);
|
|
521
|
+
return {
|
|
522
|
+
id: newDoc.header.id,
|
|
523
|
+
name: newDoc.header.name,
|
|
524
|
+
documentType,
|
|
525
|
+
parentFolder: parentFolder ?? null,
|
|
526
|
+
kind: "file"
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* How many ids an import will try before giving up. The check before the create
|
|
531
|
+
* catches an id that is already taken; this bound covers the window between the
|
|
532
|
+
* two, where a create can still lose to a claim made in the meantime.
|
|
533
|
+
*/
|
|
534
|
+
const IMPORT_ID_ATTEMPTS = 3;
|
|
535
|
+
/** True when this error, or anything it wraps, is a taken document id. */
|
|
536
|
+
function isDocumentAlreadyExists(error) {
|
|
537
|
+
let current = error;
|
|
538
|
+
while (current instanceof Error) {
|
|
539
|
+
if (current.name === "DocumentAlreadyExistsError") return true;
|
|
540
|
+
current = current.cause;
|
|
541
|
+
}
|
|
542
|
+
return false;
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Creates the imported document under an id that is free, retrying on a
|
|
546
|
+
* collision.
|
|
547
|
+
*
|
|
548
|
+
* The check cannot stand on its own: it answers for the moment it ran, and the
|
|
549
|
+
* create that follows can still land on an id claimed in between. The store
|
|
550
|
+
* rejects that create as DocumentAlreadyExistsError, which is not retryable
|
|
551
|
+
* under the same id and is resolved by minting another one. A create that
|
|
552
|
+
* fails leaves the drive untouched, so a retry has nothing to clean up.
|
|
553
|
+
*/
|
|
554
|
+
async function createImportedDocument(write, document, driveId, name, parentFolder) {
|
|
555
|
+
const v2Required = signaturePolicyOf(document.header) === "v2-required";
|
|
556
|
+
const keepsId = (!v2Required || hasDerivedDocumentId(document.header)) && !await write.isDocumentIdTaken(document.header.id);
|
|
557
|
+
let documentId = keepsId ? document.header.id : generateId();
|
|
558
|
+
for (let attempt = 1;; attempt++) {
|
|
559
|
+
let header;
|
|
560
|
+
if (!v2Required) header = createPresignedHeader(documentId, document.header.documentType, document.header.protocolVersions);
|
|
561
|
+
else if (keepsId && attempt === 1) {
|
|
562
|
+
header = createPresignedHeader(documentId, document.header.documentType);
|
|
563
|
+
header.createdAtUtcIso = document.header.createdAtUtcIso;
|
|
564
|
+
header.sig = {
|
|
565
|
+
...header.sig,
|
|
566
|
+
nonce: document.header.sig.nonce
|
|
567
|
+
};
|
|
568
|
+
header.protocolVersions = { ...document.header.protocolVersions };
|
|
569
|
+
} else {
|
|
570
|
+
header = createCopyHeader(document.header);
|
|
571
|
+
documentId = header.id;
|
|
572
|
+
}
|
|
573
|
+
header.lastModifiedAtUtcIso = document.header.createdAtUtcIso;
|
|
574
|
+
header.meta = document.header.meta;
|
|
575
|
+
header.name = name || document.header.name;
|
|
576
|
+
const initialDocument = {
|
|
577
|
+
...document,
|
|
578
|
+
header,
|
|
579
|
+
state: document.initialState,
|
|
580
|
+
operations: Object.keys(document.operations).reduce((acc, key) => {
|
|
581
|
+
acc[key] = [];
|
|
582
|
+
return acc;
|
|
583
|
+
}, {})
|
|
584
|
+
};
|
|
585
|
+
try {
|
|
586
|
+
const fileNode = await addDocument(driveId, name || document.header.name, document.header.documentType, parentFolder, initialDocument, documentId, document.header.meta?.preferredEditor);
|
|
587
|
+
if (!fileNode) throw new Error("There was an error adding file");
|
|
588
|
+
return {
|
|
589
|
+
documentId,
|
|
590
|
+
fileNode
|
|
591
|
+
};
|
|
592
|
+
} catch (error) {
|
|
593
|
+
if (!isDocumentAlreadyExists(error) || attempt === IMPORT_ID_ATTEMPTS) throw error;
|
|
594
|
+
logger.warn(`Document id ${documentId} was taken between the check and the create; importing under a new id`);
|
|
595
|
+
documentId = generateId();
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
async function addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
|
|
600
|
+
logger.verbose(`addFileWithProgress(drive: ${driveId}, name: ${name}, folder: ${parentFolder})`);
|
|
601
|
+
const reactor = getFullReactorClient();
|
|
602
|
+
if (!reactor) {
|
|
603
|
+
onProgress?.({
|
|
604
|
+
stage: "failed",
|
|
605
|
+
progress: 100,
|
|
606
|
+
error: "ReactorClient not initialized"
|
|
607
|
+
});
|
|
608
|
+
throw new Error("ReactorClient not initialized");
|
|
609
|
+
}
|
|
610
|
+
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
611
|
+
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create files");
|
|
612
|
+
try {
|
|
613
|
+
onProgress?.({
|
|
614
|
+
stage: "loading",
|
|
615
|
+
progress: 0
|
|
616
|
+
});
|
|
617
|
+
let document;
|
|
618
|
+
try {
|
|
619
|
+
document = await loadFile(file);
|
|
620
|
+
} catch (loadError) {
|
|
621
|
+
if (UnsupportedDocumentModelVersionError.isError(loadError)) {
|
|
622
|
+
showPHModal({
|
|
623
|
+
type: "documentVersionUnsupported",
|
|
624
|
+
documentType: loadError.documentType,
|
|
625
|
+
requiredVersion: loadError.requiredVersion,
|
|
626
|
+
availableVersions: loadError.availableVersions
|
|
627
|
+
});
|
|
628
|
+
onProgress?.({
|
|
629
|
+
stage: "failed",
|
|
630
|
+
progress: 100,
|
|
631
|
+
error: loadError.message
|
|
632
|
+
});
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
const discoveryService = getPHStore()?.packageDiscoveryService;
|
|
636
|
+
if (discoveryService && DocumentModelNotFoundError.isError(loadError)) {
|
|
637
|
+
retryAfterDiscovery(discoveryService, loadError.documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict).catch((retryError) => {
|
|
638
|
+
logger.error("Import retry after discovery failed: @error", retryError);
|
|
639
|
+
onProgress?.({
|
|
640
|
+
stage: "failed",
|
|
641
|
+
progress: 100,
|
|
642
|
+
error: retryError instanceof Error ? retryError.message : String(retryError)
|
|
643
|
+
});
|
|
644
|
+
});
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
throw loadError;
|
|
648
|
+
}
|
|
649
|
+
const duplicateCheck = await isDocumentInLocation(reactor.read, document, driveId, parentFolder);
|
|
650
|
+
if (duplicateCheck.isDuplicate && !resolveConflict) {
|
|
651
|
+
onProgress?.({
|
|
652
|
+
stage: "conflict",
|
|
653
|
+
progress: 0,
|
|
654
|
+
duplicateType: duplicateCheck.duplicateType
|
|
655
|
+
});
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
const documentType = getDocumentTypeIcon(document);
|
|
659
|
+
if (documentType) onProgress?.({
|
|
660
|
+
stage: "loading",
|
|
661
|
+
progress: 10,
|
|
662
|
+
documentType
|
|
663
|
+
});
|
|
664
|
+
else onProgress?.({
|
|
665
|
+
stage: "loading",
|
|
666
|
+
progress: 10
|
|
667
|
+
});
|
|
668
|
+
if (!isDocumentTypeSupported(document.header.documentType, documentTypes)) {
|
|
669
|
+
onProgress?.({
|
|
670
|
+
stage: "unsupported-document-type",
|
|
671
|
+
progress: 100,
|
|
672
|
+
error: `Document type ${document.header.documentType} is not supported`
|
|
673
|
+
});
|
|
674
|
+
throw new UnsupportedDocumentTypeError(document.header.documentType);
|
|
675
|
+
}
|
|
676
|
+
await reactor.read.getDocumentModelModule(document.header.documentType);
|
|
677
|
+
onProgress?.({
|
|
678
|
+
stage: "initializing",
|
|
679
|
+
progress: 10
|
|
680
|
+
});
|
|
681
|
+
markLocalDriveWrite(driveId);
|
|
682
|
+
const created = await createImportedDocument(reactor.write, document, driveId, name, parentFolder);
|
|
683
|
+
const documentId = created.documentId;
|
|
684
|
+
const fileNode = created.fileNode;
|
|
685
|
+
await rememberDriveNode(driveId, documentId);
|
|
686
|
+
onProgress?.({
|
|
687
|
+
stage: "initializing",
|
|
688
|
+
progress: 20
|
|
689
|
+
});
|
|
690
|
+
await reactor.read.get(documentId);
|
|
691
|
+
console.log("Document created, starting upload of operations");
|
|
692
|
+
const segments = splitAtUpgradeBoundaries(document.operations);
|
|
693
|
+
const totalOperations = segments.reduce((total, segment) => total + countOperations(segment.operations), 0);
|
|
694
|
+
let uploadedBefore = 0;
|
|
695
|
+
for (const segment of segments) {
|
|
696
|
+
await uploadOperations(documentId, segment.operations, queueOperations, { onProgress: (uploadProgress) => {
|
|
697
|
+
if (uploadProgress.uploadedOperations === void 0) return;
|
|
698
|
+
const uploaded = uploadedBefore + uploadProgress.uploadedOperations;
|
|
699
|
+
const uploadPercent = totalOperations > 0 ? uploaded / totalOperations : 0;
|
|
700
|
+
onProgress?.({
|
|
701
|
+
stage: "uploading",
|
|
702
|
+
progress: 20 + Math.round(uploadPercent * 80),
|
|
703
|
+
totalOperations,
|
|
704
|
+
uploadedOperations: uploaded
|
|
705
|
+
});
|
|
706
|
+
} });
|
|
707
|
+
uploadedBefore += countOperations(segment.operations);
|
|
708
|
+
if (segment.upgradeTo !== void 0) await reactor.upgradeDocument(documentId, segment.upgradeTo);
|
|
709
|
+
}
|
|
710
|
+
onProgress?.({
|
|
711
|
+
stage: "complete",
|
|
712
|
+
progress: 100,
|
|
713
|
+
fileNode
|
|
714
|
+
});
|
|
715
|
+
return fileNode;
|
|
716
|
+
} catch (error) {
|
|
717
|
+
if (!UnsupportedDocumentTypeError.isError(error)) {
|
|
718
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
|
|
719
|
+
onProgress?.({
|
|
720
|
+
stage: "failed",
|
|
721
|
+
progress: 100,
|
|
722
|
+
error: errorMessage
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
throw error;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
async function retryAfterDiscovery(discoveryService, documentType, file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict) {
|
|
729
|
+
if (!discoveryService) return;
|
|
730
|
+
try {
|
|
731
|
+
await discoveryService.load(documentType);
|
|
732
|
+
} catch {
|
|
733
|
+
onProgress?.({
|
|
734
|
+
stage: "unsupported-document-type",
|
|
735
|
+
progress: 100,
|
|
736
|
+
error: `Document type ${documentType} is not supported`
|
|
737
|
+
});
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
await addFileWithProgress(file, driveId, name, parentFolder, onProgress, documentTypes, resolveConflict);
|
|
741
|
+
}
|
|
742
|
+
async function addFolder$1(driveId, name, parentFolder) {
|
|
743
|
+
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
744
|
+
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to create folders");
|
|
745
|
+
const reactorClient = getPHStore()?.reactorClient;
|
|
746
|
+
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
747
|
+
await reactorClient.read.get(driveId);
|
|
748
|
+
const folderId = generateId();
|
|
749
|
+
markLocalDriveWrite(driveId);
|
|
750
|
+
await (await reactorClient.write.execute(driveId, "main", [addFolder({
|
|
751
|
+
id: folderId,
|
|
752
|
+
name,
|
|
753
|
+
parentFolder
|
|
754
|
+
})])).readable;
|
|
755
|
+
const node = await getDriveNode(driveId, folderId, { refresh: true });
|
|
756
|
+
if (!node || !isFolderNode(node)) throw new Error("There was an error adding folder");
|
|
757
|
+
return node;
|
|
758
|
+
}
|
|
759
|
+
async function deleteNode(driveId, nodeId) {
|
|
760
|
+
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
761
|
+
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to delete documents");
|
|
762
|
+
const reactorClient = getFullReactorClient();
|
|
763
|
+
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
764
|
+
markLocalDriveWrite(driveId);
|
|
765
|
+
await (await reactorClient.write.drives.removeNode(driveId, nodeId)).readable;
|
|
766
|
+
dropDriveNode(driveId, nodeId);
|
|
767
|
+
}
|
|
768
|
+
async function renameNode(driveId, nodeId, name) {
|
|
769
|
+
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
770
|
+
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
|
|
771
|
+
const reactorClient = getPHStore()?.reactorClient;
|
|
772
|
+
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
773
|
+
if ((await (await reactorClient.write.execute(nodeId, "main", [setName({ name })])).document()).header.name !== name) throw new Error("There was an error renaming the node");
|
|
774
|
+
markLocalDriveWrite(driveId);
|
|
775
|
+
await (await reactorClient.write.execute(driveId, "main", [updateNode({
|
|
776
|
+
id: nodeId,
|
|
777
|
+
name
|
|
778
|
+
})])).readable;
|
|
779
|
+
const node = await getDriveNode(driveId, nodeId, { refresh: true });
|
|
780
|
+
if (!node) throw new Error("There was an error renaming node in the drive");
|
|
781
|
+
return node;
|
|
782
|
+
}
|
|
783
|
+
async function renameDriveNode(driveId, nodeId, name) {
|
|
784
|
+
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
785
|
+
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to rename documents");
|
|
786
|
+
const reactorClient = getPHStore()?.reactorClient;
|
|
787
|
+
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
788
|
+
if ((await (await reactorClient.write.execute(nodeId, "main", [setName({ name })])).document()).header.name !== name) throw new Error("There was an error renaming the node");
|
|
789
|
+
markLocalDriveWrite(driveId);
|
|
790
|
+
await (await reactorClient.write.execute(driveId, "main", [updateNode({
|
|
791
|
+
id: nodeId,
|
|
792
|
+
name
|
|
793
|
+
})])).readable;
|
|
794
|
+
return getDriveNode(driveId, nodeId, { refresh: true });
|
|
795
|
+
}
|
|
796
|
+
async function setPreferredEditorOnNode(nodeId, preferredEditor) {
|
|
797
|
+
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
798
|
+
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to modify documents");
|
|
799
|
+
const reactorClient = getPHStore()?.reactorClient;
|
|
800
|
+
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
801
|
+
return (await reactorClient.write.execute(nodeId, "main", [setPreferredEditor(preferredEditor)])).document();
|
|
802
|
+
}
|
|
803
|
+
async function moveNodeById(args) {
|
|
804
|
+
const { driveId, srcId, targetId } = args;
|
|
805
|
+
if (!driveId || !srcId) return;
|
|
806
|
+
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
807
|
+
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
|
|
808
|
+
const reactorClient = getPHStore()?.reactorClient;
|
|
809
|
+
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
810
|
+
const targetParentFolder = conditional(targetId, [isNot(isDefined), constant(void 0)], [isStrictEqual(driveId), constant(void 0)], constant(targetId));
|
|
811
|
+
if (isStrictEqual(targetParentFolder, srcId)) return;
|
|
812
|
+
markLocalDriveWrite(driveId);
|
|
813
|
+
const moved = await (await reactorClient.write.execute(driveId, "main", [moveNode({
|
|
814
|
+
srcFolder: srcId,
|
|
815
|
+
targetParentFolder
|
|
816
|
+
})])).document();
|
|
817
|
+
await rememberDriveNode(driveId, srcId);
|
|
818
|
+
return moved;
|
|
819
|
+
}
|
|
820
|
+
async function moveNode$1(driveId, src, target) {
|
|
821
|
+
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
822
|
+
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to move documents");
|
|
823
|
+
const reactorClient = getPHStore()?.reactorClient;
|
|
824
|
+
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
825
|
+
markLocalDriveWrite(driveId);
|
|
826
|
+
const moved = await (await reactorClient.write.execute(driveId, "main", [moveNode({
|
|
827
|
+
srcFolder: src.id,
|
|
828
|
+
targetParentFolder: target?.id
|
|
829
|
+
})])).document();
|
|
830
|
+
await rememberDriveNode(driveId, src.id);
|
|
831
|
+
return moved;
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Duplicates a document under a new id using version-aware replay.
|
|
835
|
+
* Falls back gracefully when no upgrade manifest is registered for the document type.
|
|
836
|
+
*/
|
|
837
|
+
async function _duplicateDocument(reactor, document, newId = generateId(), driveId) {
|
|
838
|
+
const documentType = document.header.documentType;
|
|
839
|
+
const { results: allModules } = await reactor.getDocumentModelModules();
|
|
840
|
+
const modulesForType = allModules.filter((m) => m.documentModel.global.id === documentType);
|
|
841
|
+
const reducers = {};
|
|
842
|
+
for (const m of modulesForType) reducers[m.version ?? 1] = m.reducer;
|
|
843
|
+
if (Object.keys(reducers).length === 0) throw new Error(`Document model module not found for type: ${documentType}`);
|
|
844
|
+
const registry = getPHStore()?.reactorClientModule?.reactorModule?.documentModelRegistry;
|
|
845
|
+
let upgradeManifest;
|
|
846
|
+
if (registry) try {
|
|
847
|
+
upgradeManifest = registry.getUpgradeManifest(documentType);
|
|
848
|
+
} catch {}
|
|
849
|
+
const config = {
|
|
850
|
+
reducers,
|
|
851
|
+
upgradeManifest
|
|
852
|
+
};
|
|
853
|
+
const selected = await reactor.getCreateProtocolVersions({
|
|
854
|
+
documentType: document.header.documentType,
|
|
855
|
+
parentIdentifier: driveId
|
|
856
|
+
});
|
|
857
|
+
const header = createCopyHeader({
|
|
858
|
+
documentType: document.header.documentType,
|
|
859
|
+
protocolVersions: document.header.protocolVersions ? {
|
|
860
|
+
...selected,
|
|
861
|
+
...document.header.protocolVersions
|
|
862
|
+
} : void 0
|
|
863
|
+
}, newId, await reactor.getCreateSignaturePolicy());
|
|
864
|
+
const duplicated = replayDocumentVersioned(document.initialState, document.operations, config, header);
|
|
865
|
+
assertAuthPreservedOnDuplicate(document.header.id, document.state.auth, duplicated.state.auth);
|
|
866
|
+
return duplicated;
|
|
867
|
+
}
|
|
868
|
+
async function copyNode$1(driveId, src, target) {
|
|
869
|
+
const reactor = getFullReactorClient();
|
|
870
|
+
if (!reactor) return;
|
|
871
|
+
const { isAllowedToCreateDocuments } = getUserPermissions();
|
|
872
|
+
if (!isAllowedToCreateDocuments) throw new Error("User is not allowed to copy documents");
|
|
873
|
+
const drive = await reactor.read.get(driveId);
|
|
874
|
+
const driveNodes = await listAllDriveNodes(reactor.read.drives, driveId);
|
|
875
|
+
const copyNodesInput = generateNodesCopy({
|
|
876
|
+
srcId: src.id,
|
|
877
|
+
targetParentFolder: target?.id,
|
|
878
|
+
targetName: src.name
|
|
879
|
+
}, () => generateId(), driveNodes);
|
|
880
|
+
const resolvedNamesMap = /* @__PURE__ */ new Map();
|
|
881
|
+
for (const copyNodeInput of copyNodesInput) {
|
|
882
|
+
const node = driveNodes.find((n) => n.id === copyNodeInput.srcId);
|
|
883
|
+
if (node) {
|
|
884
|
+
const resolvedName = handleTargetNameCollisions({
|
|
885
|
+
nodes: driveNodes,
|
|
886
|
+
srcName: copyNodeInput.targetName || node.name,
|
|
887
|
+
srcKind: isFileNode(node) ? "file" : "folder",
|
|
888
|
+
targetParentFolder: copyNodeInput.targetParentFolder || null
|
|
889
|
+
});
|
|
890
|
+
resolvedNamesMap.set(copyNodeInput.targetId, resolvedName);
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
const fileNodesToCopy = copyNodesInput.filter((copyNodeInput) => {
|
|
894
|
+
const node = driveNodes.find((node) => node.id === copyNodeInput.srcId);
|
|
895
|
+
return node !== void 0 && isFileNode(node);
|
|
896
|
+
});
|
|
897
|
+
markLocalDriveWrite(driveId);
|
|
898
|
+
for (const fileNodeToCopy of fileNodesToCopy) try {
|
|
899
|
+
const document = await reactor.read.get(fileNodeToCopy.srcId);
|
|
900
|
+
const duplicatedDocument = await _duplicateDocument(reactor.read, document, fileNodeToCopy.targetId, driveId);
|
|
901
|
+
const resolvedName = resolvedNamesMap.get(fileNodeToCopy.targetId);
|
|
902
|
+
if (resolvedName) duplicatedDocument.header.name = resolvedName;
|
|
903
|
+
fileNodeToCopy.targetId = duplicatedDocument.header.id;
|
|
904
|
+
await (await reactor.write.drives.addFile(driveId, duplicatedDocument, target?.id)).readable;
|
|
905
|
+
} catch (e) {
|
|
906
|
+
logger.error(`Error copying document ${fileNodeToCopy.srcId}: ${String(e)}`);
|
|
907
|
+
}
|
|
908
|
+
const copyActions = copyNodesInput.map((copyNodeInput) => copyNode(copyNodeInput));
|
|
909
|
+
markLocalDriveWrite(driveId);
|
|
910
|
+
const copied = await queueActions(drive, copyActions);
|
|
911
|
+
invalidateDriveNodes(driveId);
|
|
912
|
+
return copied;
|
|
913
|
+
}
|
|
914
|
+
/**
|
|
915
|
+
* Upgrades a document to a newer document model version. Defaults to the
|
|
916
|
+
* latest registered version for the document's type.
|
|
917
|
+
*/
|
|
918
|
+
async function upgradeDocument(documentId, toVersion) {
|
|
919
|
+
const reactorClient = getFullReactorClient();
|
|
920
|
+
if (!reactorClient) throw new Error("ReactorClient not initialized");
|
|
921
|
+
return (await reactorClient.write.upgradeDocument(documentId, toVersion)).document();
|
|
922
|
+
}
|
|
923
|
+
//#endregion
|
|
924
|
+
//#region src/graphql-client/errors.ts
|
|
925
|
+
/** A call the Switchboard GraphQL surface cannot express. */
|
|
926
|
+
var GraphQLOperationNotSupportedError = class extends Error {
|
|
927
|
+
name = "GraphQLOperationNotSupportedError";
|
|
928
|
+
operation;
|
|
929
|
+
constructor(operation, reason) {
|
|
930
|
+
super(`GraphQLReactorClient.${operation} is not supported: ${reason}`);
|
|
931
|
+
this.operation = operation;
|
|
932
|
+
}
|
|
933
|
+
static isError(error) {
|
|
934
|
+
return Error.isError(error) && error.name === "GraphQLOperationNotSupportedError";
|
|
935
|
+
}
|
|
936
|
+
};
|
|
937
|
+
/**
|
|
938
|
+
* The Switchboard refused a request with 421 Misdirected Request: the
|
|
939
|
+
* `Drive-Id` it carried names a drive that Switchboard does not own.
|
|
940
|
+
*/
|
|
941
|
+
var GraphQLWrongBackendError = class extends Error {
|
|
942
|
+
name = "GraphQLWrongBackendError";
|
|
943
|
+
status = 421;
|
|
944
|
+
/** The drive the Switchboard refused, or `""` when its answer names none. */
|
|
945
|
+
driveId;
|
|
946
|
+
/** The response body, parsed when it is JSON. */
|
|
947
|
+
payload;
|
|
948
|
+
constructor(driveId, payload, options) {
|
|
949
|
+
super(`The Switchboard does not serve drive ${driveId === "" ? "(unnamed)" : driveId}: 421 Misdirected Request`, options);
|
|
950
|
+
this.driveId = driveId;
|
|
951
|
+
this.payload = payload;
|
|
952
|
+
}
|
|
953
|
+
static isError(error) {
|
|
954
|
+
return Error.isError(error) && error.name === "GraphQLWrongBackendError" && typeof error.driveId === "string";
|
|
955
|
+
}
|
|
956
|
+
};
|
|
957
|
+
/**
|
|
958
|
+
* The reactor's `BatchJobFailedError`, rebuilt from a batch result; this entry
|
|
959
|
+
* imports the reactor for types only. The shared name lets either `isError`
|
|
960
|
+
* recognise it.
|
|
961
|
+
*/
|
|
962
|
+
var BatchJobFailedError = class extends Error {
|
|
963
|
+
name = "BatchJobFailedError";
|
|
964
|
+
key;
|
|
965
|
+
jobs;
|
|
966
|
+
constructor(key, jobs) {
|
|
967
|
+
const failure = jobs[key].error;
|
|
968
|
+
const cause = new Error(failure?.message ?? "Job failed");
|
|
969
|
+
cause.name = failure?.name ?? "Error";
|
|
970
|
+
super(failure?.message ?? "Job failed", { cause });
|
|
971
|
+
this.key = key;
|
|
972
|
+
this.jobs = jobs;
|
|
973
|
+
}
|
|
974
|
+
static isError(error) {
|
|
975
|
+
return Error.isError(error) && error.name === "BatchJobFailedError" && typeof error.key === "string" && typeof error.jobs === "object";
|
|
976
|
+
}
|
|
977
|
+
};
|
|
978
|
+
/** A validation error naming root field `field` unknown: a host from before it. */
|
|
979
|
+
function queriesUnknownField(error, field) {
|
|
980
|
+
return hasErrorStarting(error, `Cannot query field "${field}" on type "`);
|
|
981
|
+
}
|
|
982
|
+
/** A validation error naming `argument` unknown: a host from before it. */
|
|
983
|
+
function queriesUnknownArgument(error, argument) {
|
|
984
|
+
return hasErrorStarting(error, `Unknown argument "${argument}" on field "`);
|
|
985
|
+
}
|
|
986
|
+
function hasErrorStarting(error, prefix) {
|
|
987
|
+
const errors = error?.response?.errors;
|
|
988
|
+
if (!Array.isArray(errors)) return false;
|
|
989
|
+
return errors.some((entry) => typeof entry?.message === "string" && entry.message.startsWith(prefix));
|
|
990
|
+
}
|
|
991
|
+
/**
|
|
992
|
+
* The reactor's `JobFailedError`, rebuilt from a job the Switchboard reported
|
|
993
|
+
* FAILED; this entry imports the reactor for types only. A write handle's
|
|
994
|
+
* stage rejects with it. The message is the job error's message, as the
|
|
995
|
+
* reactor's is.
|
|
996
|
+
*/
|
|
997
|
+
var JobFailedError = class extends Error {
|
|
998
|
+
name = "JobFailedError";
|
|
999
|
+
job;
|
|
1000
|
+
constructor(job) {
|
|
1001
|
+
super(job.error?.message);
|
|
1002
|
+
this.job = job;
|
|
1003
|
+
}
|
|
1004
|
+
static isError(error) {
|
|
1005
|
+
return Error.isError(error) && error.name === "JobFailedError" && typeof error.job === "object";
|
|
1006
|
+
}
|
|
1007
|
+
};
|
|
1008
|
+
//#endregion
|
|
1009
|
+
//#region src/constants.ts
|
|
1010
|
+
const DEFAULT_DRIVE_EDITOR_ID = "powerhouse/generic-drive-explorer";
|
|
1011
|
+
const COMMON_PACKAGE_ID = "powerhouse/common";
|
|
1012
|
+
/** Document types that represent a "drive": a container of nodes. */
|
|
1013
|
+
const DRIVE_DOCUMENT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
|
|
1014
|
+
//#endregion
|
|
1015
|
+
//#region src/remote-controller/utils.ts
|
|
1016
|
+
/** Convert SCREAMING_SNAKE_CASE to camelCase (e.g. "SET_MODEL_NAME" → "setModelName"). */
|
|
1017
|
+
function screamingSnakeToCamel(s) {
|
|
1018
|
+
return s.toLowerCase().replace(/_([a-z])/g, (_, c) => c.toUpperCase());
|
|
1019
|
+
}
|
|
1020
|
+
/** Error thrown when a push conflict is detected with the "reject" strategy. */
|
|
1021
|
+
var ConflictError = class extends Error {
|
|
1022
|
+
conflict;
|
|
1023
|
+
constructor(conflict) {
|
|
1024
|
+
super("Push conflict: remote has new operations since last pull");
|
|
1025
|
+
this.conflict = conflict;
|
|
1026
|
+
this.name = "ConflictError";
|
|
1027
|
+
}
|
|
1028
|
+
};
|
|
1029
|
+
/** Convert a remote operation to the local Operation type. */
|
|
1030
|
+
function remoteOperationToLocal(remote) {
|
|
1031
|
+
return {
|
|
1032
|
+
id: remote.id ?? "",
|
|
1033
|
+
index: remote.index,
|
|
1034
|
+
skip: remote.skip,
|
|
1035
|
+
timestampUtcMs: remote.timestampUtcMs,
|
|
1036
|
+
hash: remote.hash,
|
|
1037
|
+
error: remote.error ?? void 0,
|
|
1038
|
+
deniedReason: remote.deniedReason ?? void 0,
|
|
1039
|
+
action: {
|
|
1040
|
+
id: remote.action.id,
|
|
1041
|
+
type: remote.action.type,
|
|
1042
|
+
timestampUtcMs: remote.action.timestampUtcMs,
|
|
1043
|
+
input: remote.action.input,
|
|
1044
|
+
scope: remote.action.scope,
|
|
1045
|
+
context: remote.action.context?.signer ? { signer: {
|
|
1046
|
+
user: remote.action.context.signer.user ?? {
|
|
1047
|
+
address: "",
|
|
1048
|
+
networkId: "",
|
|
1049
|
+
chainId: 0
|
|
1050
|
+
},
|
|
1051
|
+
app: remote.action.context.signer.app ?? {
|
|
1052
|
+
name: "",
|
|
1053
|
+
key: ""
|
|
1054
|
+
},
|
|
1055
|
+
signatures: remote.action.context.signer.signatures.map((s) => deserializeSignature(s))
|
|
1056
|
+
} } : void 0
|
|
1057
|
+
}
|
|
1058
|
+
};
|
|
1059
|
+
}
|
|
1060
|
+
/** Convert remote operations to local DocumentOperations format. */
|
|
1061
|
+
function convertRemoteOperations(operationsByScope) {
|
|
1062
|
+
const operations = {};
|
|
1063
|
+
for (const [scope, remoteOps] of Object.entries(operationsByScope)) operations[scope] = remoteOps.map((op) => remoteOperationToLocal(op));
|
|
1064
|
+
return operations;
|
|
1065
|
+
}
|
|
1066
|
+
/**
|
|
1067
|
+
* Reconstruct a PHDocument from remote document data and operations; the
|
|
1068
|
+
* header carries the remote protocol versions. `initialDoc` supplies the rest
|
|
1069
|
+
* of the header, and the initial state when the operations do not record one.
|
|
1070
|
+
*/
|
|
1071
|
+
function buildPulledDocument(remoteDoc, operations, initialDoc, branch) {
|
|
1072
|
+
return {
|
|
1073
|
+
header: {
|
|
1074
|
+
...initialDoc.header,
|
|
1075
|
+
id: remoteDoc.id,
|
|
1076
|
+
name: remoteDoc.name,
|
|
1077
|
+
slug: remoteDoc.slug ?? "",
|
|
1078
|
+
documentType: remoteDoc.documentType,
|
|
1079
|
+
createdAtUtcIso: typeof remoteDoc.createdAtUtcIso === "string" ? remoteDoc.createdAtUtcIso : remoteDoc.createdAtUtcIso.toISOString(),
|
|
1080
|
+
lastModifiedAtUtcIso: typeof remoteDoc.lastModifiedAtUtcIso === "string" ? remoteDoc.lastModifiedAtUtcIso : remoteDoc.lastModifiedAtUtcIso.toISOString(),
|
|
1081
|
+
revision: Object.fromEntries(remoteDoc.revisionsList.map((r) => [r.scope, r.revision])),
|
|
1082
|
+
branch,
|
|
1083
|
+
...remoteDoc.protocolVersions != null ? { protocolVersions: remoteDoc.protocolVersions } : {}
|
|
1084
|
+
},
|
|
1085
|
+
state: remoteDoc.state,
|
|
1086
|
+
initialState: creationState(operations.document ?? []) ?? initialDoc.initialState,
|
|
1087
|
+
operations,
|
|
1088
|
+
clipboard: []
|
|
1089
|
+
};
|
|
1090
|
+
}
|
|
1091
|
+
/** `document` as created: its header and initial state, without scope operations. */
|
|
1092
|
+
function uncreatedDocument(document) {
|
|
1093
|
+
const { header, initialState } = structuredClone({
|
|
1094
|
+
header: document.header,
|
|
1095
|
+
initialState: document.initialState
|
|
1096
|
+
});
|
|
1097
|
+
return {
|
|
1098
|
+
header,
|
|
1099
|
+
state: initialState,
|
|
1100
|
+
initialState,
|
|
1101
|
+
operations: {},
|
|
1102
|
+
clipboard: []
|
|
1103
|
+
};
|
|
1104
|
+
}
|
|
1105
|
+
/** An uncreated `document` under `policy`; a legacy one keeps its id. */
|
|
1106
|
+
function underSignaturePolicy(document, policy) {
|
|
1107
|
+
if (signaturePolicyOf(document.header) === policy) return document;
|
|
1108
|
+
return withSignaturePolicy(document, policy, { id: document.header.id });
|
|
1109
|
+
}
|
|
1110
|
+
/** Extract revision map from a remote document's revisionsList. */
|
|
1111
|
+
function extractRevisionMap(revisionsList) {
|
|
1112
|
+
return Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));
|
|
1113
|
+
}
|
|
1114
|
+
/**
|
|
1115
|
+
* Check if any scope in currentRevision is ahead of knownRevision.
|
|
1116
|
+
* When `scopes` is provided, only those scopes are checked.
|
|
1117
|
+
*/
|
|
1118
|
+
function hasRevisionConflict(currentRevision, knownRevision, scopes) {
|
|
1119
|
+
for (const scope in currentRevision) {
|
|
1120
|
+
if (scopes && !scopes.has(scope)) continue;
|
|
1121
|
+
if ((currentRevision[scope] ?? 0) > (knownRevision[scope] ?? 0)) return true;
|
|
1122
|
+
}
|
|
1123
|
+
return false;
|
|
1124
|
+
}
|
|
1125
|
+
//#endregion
|
|
1126
|
+
//#region src/graphql-client/adapter.ts
|
|
1127
|
+
/**
|
|
1128
|
+
* Converts a `GetDocument` result into a `PHDocument`.
|
|
1129
|
+
*
|
|
1130
|
+
* Unlike the legacy `src/graphql/adapters.ts` this preserves the per-scope
|
|
1131
|
+
* revision map, which the write path needs to compute the `prevOpIndex` of a
|
|
1132
|
+
* signed action. `sig` is filled with the empty shape used by
|
|
1133
|
+
* `createPresignedHeader`: the creation signature is not fetchable over
|
|
1134
|
+
* GraphQL and is not part of the operation signing payload.
|
|
1135
|
+
*
|
|
1136
|
+
* The read path never fetches operation history, so `operations` maps each
|
|
1137
|
+
* scope of the document's state and revisions to an empty array.
|
|
1138
|
+
*
|
|
1139
|
+
* `branch` is the branch the document was read from. The GraphQL type does not
|
|
1140
|
+
* carry it, so it has to be passed back in by the caller; it defaults to the
|
|
1141
|
+
* server's own default branch.
|
|
1142
|
+
*/
|
|
1143
|
+
function phDocumentFromGetDocument(document, branch) {
|
|
1144
|
+
const state = document.state;
|
|
1145
|
+
return {
|
|
1146
|
+
header: phDocumentHeaderFromGetDocument(document, branch),
|
|
1147
|
+
state,
|
|
1148
|
+
initialState: state,
|
|
1149
|
+
operations: emptyOperationsForScopes(state, document.revisionsList),
|
|
1150
|
+
clipboard: []
|
|
1151
|
+
};
|
|
1152
|
+
}
|
|
1153
|
+
/**
|
|
1154
|
+
* Converts a mutation result into a `PHDocument`, carrying the operations the
|
|
1155
|
+
* mutation produced.
|
|
1156
|
+
*
|
|
1157
|
+
* `dispatchActions` reads per-action failures out of `operations[scope]`, so
|
|
1158
|
+
* unlike the read path this one must not return empty operation lists.
|
|
1159
|
+
*/
|
|
1160
|
+
function phDocumentFromMutation(document, operations, branch) {
|
|
1161
|
+
const phDocument = phDocumentFromGetDocument(document, branch);
|
|
1162
|
+
const operationsByScope = { ...phDocument.operations };
|
|
1163
|
+
for (const remote of operations) {
|
|
1164
|
+
const operation = remoteOperationToLocal(remote);
|
|
1165
|
+
const scope = operation.action.scope;
|
|
1166
|
+
const scopeOperations = operationsByScope[scope] ?? [];
|
|
1167
|
+
scopeOperations.push(operation);
|
|
1168
|
+
operationsByScope[scope] = scopeOperations;
|
|
1169
|
+
}
|
|
1170
|
+
phDocument.operations = operationsByScope;
|
|
1171
|
+
return phDocument;
|
|
1172
|
+
}
|
|
1173
|
+
/** Turns a `revisionsList` selection into the header's per-scope revision map. */
|
|
1174
|
+
function revisionMapFromRevisionsList(revisionsList) {
|
|
1175
|
+
return Object.fromEntries(revisionsList.map((r) => [r.scope, r.revision]));
|
|
1176
|
+
}
|
|
1177
|
+
/** The branch the server reads and writes when none is asked for. */
|
|
1178
|
+
const defaultBranch = "main";
|
|
1179
|
+
function phDocumentHeaderFromGetDocument(document, branch) {
|
|
1180
|
+
return {
|
|
1181
|
+
id: document.id,
|
|
1182
|
+
sig: {
|
|
1183
|
+
publicKey: {},
|
|
1184
|
+
nonce: ""
|
|
1185
|
+
},
|
|
1186
|
+
documentType: document.documentType,
|
|
1187
|
+
createdAtUtcIso: isoStringFromDateTime(document.createdAtUtcIso),
|
|
1188
|
+
slug: document.slug ?? "",
|
|
1189
|
+
name: document.name,
|
|
1190
|
+
branch: branch ?? defaultBranch,
|
|
1191
|
+
revision: revisionMapFromRevisionsList(document.revisionsList),
|
|
1192
|
+
lastModifiedAtUtcIso: isoStringFromDateTime(document.lastModifiedAtUtcIso),
|
|
1193
|
+
...document.meta != null ? { meta: document.meta } : {},
|
|
1194
|
+
...document.protocolVersions != null ? { protocolVersions: document.protocolVersions } : {}
|
|
1195
|
+
};
|
|
1196
|
+
}
|
|
1197
|
+
function emptyOperationsForScopes(state, revisionsList) {
|
|
1198
|
+
const scopes = /* @__PURE__ */ new Set([...Object.keys(state), ...revisionsList.map((r) => r.scope)]);
|
|
1199
|
+
return Object.fromEntries([...scopes].map((scope) => [scope, []]));
|
|
1200
|
+
}
|
|
1201
|
+
/** The `DateTime` scalar deserializes as either an ISO string or a `Date`. */
|
|
1202
|
+
function isoStringFromDateTime(value) {
|
|
1203
|
+
return value instanceof Date ? value.toISOString() : value;
|
|
1204
|
+
}
|
|
1205
|
+
//#endregion
|
|
1206
|
+
//#region src/graphql-client/drive-nodes.ts
|
|
1207
|
+
/** Page size {@link GraphQLDriveNodeSource.listAll} reads a drive in. */
|
|
1208
|
+
const LIST_ALL_PAGE_LIMIT = 1e3;
|
|
1209
|
+
const DEFAULT_LIMIT$1 = 100;
|
|
1210
|
+
/**
|
|
1211
|
+
* The reactor subgraph's type-neutral node queries (`driveNodes`, `driveNode`,
|
|
1212
|
+
* `driveDescendants`) as an {@link IDriveNodeSource}, so a browser reads a
|
|
1213
|
+
* legacy drive and a reactor-drive alike. The Switchboard serves only the
|
|
1214
|
+
* nodes the caller may read. Drive ids must be canonical ids, not slugs.
|
|
1215
|
+
*/
|
|
1216
|
+
var GraphQLDriveNodeSource = class {
|
|
1217
|
+
queries;
|
|
1218
|
+
headersFor;
|
|
1219
|
+
constructor(queries, headersFor = () => void 0) {
|
|
1220
|
+
this.queries = queries;
|
|
1221
|
+
this.headersFor = headersFor;
|
|
1222
|
+
}
|
|
1223
|
+
async getNode(driveId, nodeId, signal) {
|
|
1224
|
+
const result = await this.queries.GetDriveNode({
|
|
1225
|
+
driveId,
|
|
1226
|
+
id: nodeId
|
|
1227
|
+
}, this.headersFor(driveId), signal);
|
|
1228
|
+
return result.driveNode ? toRecord(result.driveNode) : void 0;
|
|
1229
|
+
}
|
|
1230
|
+
async listChildren(driveId, parentFolder, paging, signal, kind) {
|
|
1231
|
+
const cursor = startCursor(paging?.cursor);
|
|
1232
|
+
const page = (await this.queries.GetDriveNodes({
|
|
1233
|
+
driveId,
|
|
1234
|
+
...parentFolder === void 0 ? {} : { parentFolder },
|
|
1235
|
+
paging: paging ? {
|
|
1236
|
+
cursor,
|
|
1237
|
+
limit: paging.limit
|
|
1238
|
+
} : void 0,
|
|
1239
|
+
kind: kind === void 0 ? void 0 : kind === "file" ? "FILE" : "FOLDER"
|
|
1240
|
+
}, this.headersFor(driveId), signal)).driveNodes;
|
|
1241
|
+
const nextCursor = page.hasMore ? page.nextCursor ?? void 0 : void 0;
|
|
1242
|
+
return {
|
|
1243
|
+
results: page.results.map(toRecord),
|
|
1244
|
+
options: {
|
|
1245
|
+
cursor,
|
|
1246
|
+
limit: paging?.limit ?? DEFAULT_LIMIT$1
|
|
1247
|
+
},
|
|
1248
|
+
...nextCursor !== void 0 ? { nextCursor } : {}
|
|
1249
|
+
};
|
|
1250
|
+
}
|
|
1251
|
+
async getDescendants(driveId, root, signal) {
|
|
1252
|
+
return (await this.queries.GetDriveDescendants({
|
|
1253
|
+
driveId,
|
|
1254
|
+
root
|
|
1255
|
+
}, this.headersFor(driveId), signal)).driveDescendants.map(toRecord);
|
|
1256
|
+
}
|
|
1257
|
+
async listAll(driveId, signal) {
|
|
1258
|
+
const nodes = [];
|
|
1259
|
+
let cursor = "";
|
|
1260
|
+
for (;;) {
|
|
1261
|
+
const page = await this.listChildren(driveId, void 0, {
|
|
1262
|
+
cursor,
|
|
1263
|
+
limit: LIST_ALL_PAGE_LIMIT
|
|
1264
|
+
}, signal);
|
|
1265
|
+
nodes.push(...page.results);
|
|
1266
|
+
if (page.nextCursor === void 0 || page.nextCursor === cursor) return nodes;
|
|
1267
|
+
cursor = page.nextCursor;
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
};
|
|
1271
|
+
/**
|
|
1272
|
+
* `read.drives` over a node source: the reactor's {@link IDriveReadClient},
|
|
1273
|
+
* answering in the legacy `Node` shape for every drive type.
|
|
1274
|
+
*/
|
|
1275
|
+
var GraphQLDriveReadClient = class {
|
|
1276
|
+
nodes;
|
|
1277
|
+
constructor(nodes) {
|
|
1278
|
+
this.nodes = nodes;
|
|
1279
|
+
}
|
|
1280
|
+
async getNode(driveIdentifier, nodeId, signal) {
|
|
1281
|
+
const record = await this.nodes.getNode(driveIdentifier, nodeId, signal);
|
|
1282
|
+
if (!record) throw new Error(`Node ${nodeId} not found in drive ${driveIdentifier}`);
|
|
1283
|
+
return toLegacyNode(record);
|
|
1284
|
+
}
|
|
1285
|
+
async listNodes(driveIdentifier, parentFolder, paging, signal) {
|
|
1286
|
+
const page = await this.nodes.listChildren(driveIdentifier, parentFolder, paging, signal);
|
|
1287
|
+
const nextCursor = page.nextCursor;
|
|
1288
|
+
return {
|
|
1289
|
+
results: page.results.map(toLegacyNode),
|
|
1290
|
+
options: page.options,
|
|
1291
|
+
...nextCursor !== void 0 ? {
|
|
1292
|
+
nextCursor,
|
|
1293
|
+
next: () => this.listNodes(driveIdentifier, parentFolder, {
|
|
1294
|
+
cursor: nextCursor,
|
|
1295
|
+
limit: page.options.limit
|
|
1296
|
+
}, signal)
|
|
1297
|
+
} : {}
|
|
1298
|
+
};
|
|
1299
|
+
}
|
|
1300
|
+
};
|
|
1301
|
+
/** A node record in the legacy `Node` shape. */
|
|
1302
|
+
function toLegacyNode(node) {
|
|
1303
|
+
if (node.kind === "file") return {
|
|
1304
|
+
id: node.id,
|
|
1305
|
+
kind: "file",
|
|
1306
|
+
name: node.name,
|
|
1307
|
+
parentFolder: node.parentFolder,
|
|
1308
|
+
documentType: node.documentType ?? ""
|
|
1309
|
+
};
|
|
1310
|
+
return {
|
|
1311
|
+
id: node.id,
|
|
1312
|
+
kind: "folder",
|
|
1313
|
+
name: node.name,
|
|
1314
|
+
parentFolder: node.parentFolder
|
|
1315
|
+
};
|
|
1316
|
+
}
|
|
1317
|
+
function toRecord(node) {
|
|
1318
|
+
const base = {
|
|
1319
|
+
id: node.id,
|
|
1320
|
+
driveId: node.driveId,
|
|
1321
|
+
name: node.name,
|
|
1322
|
+
parentFolder: node.parentFolder ?? null
|
|
1323
|
+
};
|
|
1324
|
+
return "documentType" in node ? {
|
|
1325
|
+
...base,
|
|
1326
|
+
kind: "file",
|
|
1327
|
+
documentType: node.documentType
|
|
1328
|
+
} : {
|
|
1329
|
+
...base,
|
|
1330
|
+
kind: "folder"
|
|
1331
|
+
};
|
|
1332
|
+
}
|
|
1333
|
+
/** The offset-style "0" other listings start from means the first page here too. */
|
|
1334
|
+
function startCursor(cursor) {
|
|
1335
|
+
return cursor === void 0 || cursor === "0" ? "" : cursor;
|
|
1336
|
+
}
|
|
1337
|
+
//#endregion
|
|
1338
|
+
//#region src/graphql-client/transport.ts
|
|
1339
|
+
/** The global `fetch`, read per call so a later replacement is honoured. */
|
|
1340
|
+
const globalFetch = (input, init) => globalThis.fetch(input, init);
|
|
1341
|
+
/**
|
|
1342
|
+
* Whether `fetch` here is Node's (undici), which resends a request answered
|
|
1343
|
+
* 421 and can fail the resend of a buffered body. A page, Electron's renderer
|
|
1344
|
+
* included, has a `document`.
|
|
1345
|
+
*/
|
|
1346
|
+
function isNodeFetch() {
|
|
1347
|
+
const scope = globalThis;
|
|
1348
|
+
return typeof scope.process?.versions?.node === "string" && scope.document === void 0;
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Sends a string body as a stream, which fetch never resends, so a 421 comes
|
|
1352
|
+
* back as itself. Browsers keep buffered bodies: Chrome streams an upload only
|
|
1353
|
+
* over HTTP/2.
|
|
1354
|
+
*/
|
|
1355
|
+
function withStreamedBodies(inner = globalFetch) {
|
|
1356
|
+
return (input, init) => {
|
|
1357
|
+
const body = init?.body;
|
|
1358
|
+
if (typeof body !== "string") return inner(input, init);
|
|
1359
|
+
const bytes = new TextEncoder().encode(body);
|
|
1360
|
+
return inner(input, {
|
|
1361
|
+
...init,
|
|
1362
|
+
body: new ReadableStream({ start(controller) {
|
|
1363
|
+
controller.enqueue(bytes);
|
|
1364
|
+
controller.close();
|
|
1365
|
+
} }),
|
|
1366
|
+
duplex: "half"
|
|
1367
|
+
});
|
|
1368
|
+
};
|
|
1369
|
+
}
|
|
1370
|
+
const streamedGlobalFetch = withStreamedBodies(globalFetch);
|
|
1371
|
+
/** A Switchboard backend's default transport: streamed bodies under Node only. */
|
|
1372
|
+
const switchboardFetch = (input, init) => isNodeFetch() ? streamedGlobalFetch(input, init) : globalFetch(input, init);
|
|
1373
|
+
/** Bounds each request, headers through body; rejects with a `TimeoutError`. */
|
|
1374
|
+
function withRequestDeadline(timeoutMs, inner = globalFetch) {
|
|
1375
|
+
return (input, init) => {
|
|
1376
|
+
const deadline = AbortSignal.timeout(timeoutMs);
|
|
1377
|
+
const signal = init?.signal ? AbortSignal.any([init.signal, deadline]) : deadline;
|
|
1378
|
+
return inner(input, {
|
|
1379
|
+
...init,
|
|
1380
|
+
signal
|
|
1381
|
+
});
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
/**
|
|
1385
|
+
* Whether a request failed at a deadline rather than by its caller's abort:
|
|
1386
|
+
* this transport's own (`TimeoutError`, a DOMException) or the router's probe
|
|
1387
|
+
* deadline (`ProbeTimeoutError`, reactor-router's dispatcher.ts).
|
|
1388
|
+
*/
|
|
1389
|
+
function isDeadlineError(error) {
|
|
1390
|
+
const name = error?.name;
|
|
1391
|
+
return name === "TimeoutError" || name === "ProbeTimeoutError";
|
|
1392
|
+
}
|
|
1393
|
+
//#endregion
|
|
1394
|
+
//#region src/graphql-client/create-defaults.ts
|
|
1395
|
+
/** The host's policy for a new document; a host without `createDefaults` is refused, as a guess could under-sign. */
|
|
1396
|
+
async function readCreateSignaturePolicy(sdk, signal) {
|
|
1397
|
+
const defaults = await readCreateDefaults(sdk, void 0, signal);
|
|
1398
|
+
if (defaults === void 0) throw new GraphQLOperationNotSupportedError("getCreateSignaturePolicy", "the Switchboard predates the createDefaults query");
|
|
1399
|
+
const { signaturePolicy } = defaults;
|
|
1400
|
+
if (!isSignaturePolicy(signaturePolicy)) throw new Error(`The Switchboard answered an unknown create signature policy: ${signaturePolicy}`);
|
|
1401
|
+
return signaturePolicy;
|
|
1402
|
+
}
|
|
1403
|
+
/** The host's per-type selection, capped at what this build runs and fitted to `modules`; baseline from an old host. */
|
|
1404
|
+
async function readCreateProtocolVersions(sdk, { documentType, parentIdentifier }, modules, signal) {
|
|
1405
|
+
const host = await hostCreateProtocolVersions(sdk, documentType, parentIdentifier, signal);
|
|
1406
|
+
const selected = capSelection(host, PEER_CAPABILITIES, localSupports(PEER_CAPABILITIES, FLAGS_FOR_EVERY_VERSION));
|
|
1407
|
+
return fitCreateBaseReducer(selected, documentType, modules, logger);
|
|
1408
|
+
}
|
|
1409
|
+
/** The Switchboard's selection; undefined from a host without `createDefaults`. */
|
|
1410
|
+
async function hostCreateProtocolVersions(sdk, documentType, parentIdentifier, signal) {
|
|
1411
|
+
if (documentType !== void 0) try {
|
|
1412
|
+
return protocolVersionsFrom((await sdk.GetCreateProtocolVersions({
|
|
1413
|
+
documentType,
|
|
1414
|
+
parentIdOrSlug: parentIdentifier
|
|
1415
|
+
}, void 0, signal)).createDefaults.protocolVersions);
|
|
1416
|
+
} catch (error) {
|
|
1417
|
+
if (queriesUnknownField(error, "createDefaults")) return void 0;
|
|
1418
|
+
if (!queriesUnknownArgument(error, "documentType")) throw error;
|
|
1419
|
+
}
|
|
1420
|
+
const defaults = await readCreateDefaults(sdk, parentIdentifier, signal);
|
|
1421
|
+
return defaults && protocolVersionsFrom(defaults.protocolVersions);
|
|
1422
|
+
}
|
|
1423
|
+
/** The reactor-wide `createDefaults`; undefined from a host without the query. */
|
|
1424
|
+
async function readCreateDefaults(sdk, parentIdentifier, signal) {
|
|
1425
|
+
try {
|
|
1426
|
+
return (await sdk.GetCreateDefaults({ parentIdOrSlug: parentIdentifier }, void 0, signal)).createDefaults;
|
|
1427
|
+
} catch (error) {
|
|
1428
|
+
if (queriesUnknownField(error, "createDefaults")) return;
|
|
1429
|
+
throw error;
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
function protocolVersionsFrom(value) {
|
|
1433
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("The Switchboard answered malformed create protocol versions");
|
|
1434
|
+
const versions = {};
|
|
1435
|
+
for (const [protocol, version] of Object.entries(value)) {
|
|
1436
|
+
if (typeof version !== "number" || !Number.isInteger(version)) throw new Error(`The Switchboard answered a malformed version for protocol ${protocol}`);
|
|
1437
|
+
versions[protocol] = version;
|
|
1438
|
+
}
|
|
1439
|
+
return versions;
|
|
1440
|
+
}
|
|
1441
|
+
//#endregion
|
|
1442
|
+
//#region src/graphql-client/operations.ts
|
|
1443
|
+
/**
|
|
1444
|
+
* The operation selection of `GetDocumentOperations`, lifted into a fragment so
|
|
1445
|
+
* the write path can reuse `remoteOperationToLocal` on the items it selects.
|
|
1446
|
+
*/
|
|
1447
|
+
const ReactorOperationFieldsFragmentDoc = gql`
|
|
1448
|
+
fragment ReactorOperationFields on ReactorOperation {
|
|
1449
|
+
index
|
|
1450
|
+
timestampUtcMs
|
|
1451
|
+
hash
|
|
1452
|
+
skip
|
|
1453
|
+
error
|
|
1454
|
+
deniedReason
|
|
1455
|
+
id
|
|
1456
|
+
action {
|
|
1457
|
+
id
|
|
1458
|
+
type
|
|
1459
|
+
timestampUtcMs
|
|
1460
|
+
input
|
|
1461
|
+
scope
|
|
1462
|
+
context {
|
|
1463
|
+
signer {
|
|
1464
|
+
user {
|
|
1465
|
+
address
|
|
1466
|
+
networkId
|
|
1467
|
+
chainId
|
|
1468
|
+
}
|
|
1469
|
+
app {
|
|
1470
|
+
name
|
|
1471
|
+
key
|
|
1472
|
+
}
|
|
1473
|
+
signatures
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
`;
|
|
1479
|
+
/**
|
|
1480
|
+
* `mutateDocument` plus the operations the mutation produced.
|
|
1481
|
+
*
|
|
1482
|
+
* The generated `MutateDocument` only selects the document fields, but
|
|
1483
|
+
* `dispatchActions` reads per-action failures out of `result.operations[scope]`
|
|
1484
|
+
* (`src/actions/dispatch.ts`), so the reducer-level errors would be lost.
|
|
1485
|
+
*
|
|
1486
|
+
* The operations filter keeps the extra selection to the operations this call
|
|
1487
|
+
* could have appended rather than the whole history. All three of its fields
|
|
1488
|
+
* matter:
|
|
1489
|
+
* - `sinceRevision` is the lowest head revision across the targeted scopes, so
|
|
1490
|
+
* it is only a safe window when the selection is scope-limited as well;
|
|
1491
|
+
* - `scopes` limits the response to the scopes the pushed actions target,
|
|
1492
|
+
* without it the server walks every scope of the document
|
|
1493
|
+
* (`packages/reactor/src/core/reactor.ts` `getOperations`);
|
|
1494
|
+
* - `branch` selects the branch the operations are read from, and is the same
|
|
1495
|
+
* variable the mutation writes to. It used to be two - the write went through
|
|
1496
|
+
* a `view`, the filter took its own `branch` - and they had to be kept equal
|
|
1497
|
+
* by hand or the operations came from `main` while the actions were applied
|
|
1498
|
+
* elsewhere. One variable cannot disagree with itself.
|
|
1499
|
+
*/
|
|
1500
|
+
const MutateDocumentWithOperationsDocument = gql`
|
|
1501
|
+
mutation MutateDocumentWithOperations(
|
|
1502
|
+
$documentIdentifier: String!
|
|
1503
|
+
$actions: [ActionInput!]!
|
|
1504
|
+
$sinceRevision: Int
|
|
1505
|
+
$scopes: [String!]
|
|
1506
|
+
$branch: String
|
|
1507
|
+
) {
|
|
1508
|
+
mutateDocument: execute(
|
|
1509
|
+
documentIdentifier: $documentIdentifier
|
|
1510
|
+
actions: $actions
|
|
1511
|
+
branch: $branch
|
|
1512
|
+
) {
|
|
1513
|
+
...PHDocumentFields
|
|
1514
|
+
operations(
|
|
1515
|
+
filter: {
|
|
1516
|
+
sinceRevision: $sinceRevision
|
|
1517
|
+
scopes: $scopes
|
|
1518
|
+
branch: $branch
|
|
1519
|
+
}
|
|
1520
|
+
) {
|
|
1521
|
+
items {
|
|
1522
|
+
...ReactorOperationFields
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
${PhDocumentFieldsFragmentDoc}
|
|
1528
|
+
${ReactorOperationFieldsFragmentDoc}
|
|
1529
|
+
`;
|
|
1530
|
+
/**
|
|
1531
|
+
* `document`, bounded by a consistency token: the read waits until the
|
|
1532
|
+
* Switchboard's read models hold every operation the token names. The
|
|
1533
|
+
* `consistency` argument is additive on the Switchboard; one without it refuses
|
|
1534
|
+
* this document, and the client falls back to the plain `GetDocument`.
|
|
1535
|
+
*/
|
|
1536
|
+
const GetDocumentAtConsistencyDocument = gql`
|
|
1537
|
+
query GetDocumentAtConsistency(
|
|
1538
|
+
$identifier: String!
|
|
1539
|
+
$view: ViewFilterInput
|
|
1540
|
+
$consistency: ConsistencyTokenInput
|
|
1541
|
+
) {
|
|
1542
|
+
document(identifier: $identifier, view: $view, consistency: $consistency) {
|
|
1543
|
+
document {
|
|
1544
|
+
...PHDocumentFields
|
|
1545
|
+
}
|
|
1546
|
+
childIds
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
${PhDocumentFieldsFragmentDoc}
|
|
1550
|
+
`;
|
|
1551
|
+
//#endregion
|
|
1552
|
+
//#region src/graphql-client/signing.ts
|
|
1553
|
+
/**
|
|
1554
|
+
* Stamps an action with the head of the scope it targets.
|
|
1555
|
+
*
|
|
1556
|
+
* `prevOpHash` is the hash of the scope state the action is meant to apply to;
|
|
1557
|
+
* for a document at head that is the hash of the last operation in the scope,
|
|
1558
|
+
* which the read path cannot fetch, so it is recomputed from the state.
|
|
1559
|
+
* `prevOpIndex` is the index of that last operation: revisions count
|
|
1560
|
+
* operations and indices are zero based, so an empty scope stamps `-1`, which
|
|
1561
|
+
* matches what the remote controller records.
|
|
1562
|
+
*
|
|
1563
|
+
* `revision` overrides the scope revision the index is derived from. Only a
|
|
1564
|
+
* batch needs it - {@link prepareSignedActions} stamps action N at the revision
|
|
1565
|
+
* the N actions before it will have produced, which the document itself does
|
|
1566
|
+
* not know yet. `prevOpHash` always comes from the supplied document's state.
|
|
1567
|
+
*/
|
|
1568
|
+
function stampAction(action, document, revision = document.header.revision[action.scope] ?? 0) {
|
|
1569
|
+
return {
|
|
1570
|
+
...action,
|
|
1571
|
+
context: {
|
|
1572
|
+
...action.context,
|
|
1573
|
+
prevOpHash: hashDocumentStateForScope(document, action.scope),
|
|
1574
|
+
prevOpIndex: revision - 1
|
|
1575
|
+
}
|
|
1576
|
+
};
|
|
1577
|
+
}
|
|
1578
|
+
/**
|
|
1579
|
+
* Signs a stamped action for `target`, keeping any signatures it already
|
|
1580
|
+
* carries. The signer reads `context.prevOpHash`, so this runs after
|
|
1581
|
+
* {@link stampAction}. A v2 tuple covers the signer's identity, so the context
|
|
1582
|
+
* takes the signer's user and app even when the action named others.
|
|
1583
|
+
*/
|
|
1584
|
+
async function signStampedAction(action, signer, target, signal) {
|
|
1585
|
+
if (!signer.user || !signer.app) throw new Error("cannot sign an action: the signer has no user or app identity");
|
|
1586
|
+
const signature = await signer.signAction(action, target, signal);
|
|
1587
|
+
return {
|
|
1588
|
+
...action,
|
|
1589
|
+
context: {
|
|
1590
|
+
...action.context,
|
|
1591
|
+
signer: {
|
|
1592
|
+
...actionSignerIdentity(signer),
|
|
1593
|
+
signatures: [...action.context?.signer?.signatures ?? [], signature]
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
};
|
|
1597
|
+
}
|
|
1598
|
+
/** The log a snapshot's action is written to; the snapshot names the branch read. */
|
|
1599
|
+
function snapshotTarget(action, snapshot) {
|
|
1600
|
+
return actionSigningTarget(action, snapshot.header.id, snapshot.header.branch || "main");
|
|
1601
|
+
}
|
|
1602
|
+
/**
|
|
1603
|
+
* Actions a snapshot batch cannot predict the next state for.
|
|
1604
|
+
*
|
|
1605
|
+
* `UNDO` and `REDO` rewrite history the light read path never fetched (and
|
|
1606
|
+
* the reducer appends no operation for them); `NOOP` is only ever produced
|
|
1607
|
+
* by an undo chain; a `RETRACT` names a target in that unfetched history; the
|
|
1608
|
+
* document-scope actions run through the reactor's
|
|
1609
|
+
* document-action handler rather than a document-model reducer
|
|
1610
|
+
* (`DOCUMENT_SCOPE_ACTIONS` in packages/reactor/src/executor/util.ts) and
|
|
1611
|
+
* `UPGRADE_DOCUMENT` changes which reducer applies mid-batch.
|
|
1612
|
+
*/
|
|
1613
|
+
const unsupportedBatchActions = /* @__PURE__ */ new Set([
|
|
1614
|
+
"UNDO",
|
|
1615
|
+
"REDO",
|
|
1616
|
+
"NOOP",
|
|
1617
|
+
"RETRACT",
|
|
1618
|
+
"CREATE_DOCUMENT",
|
|
1619
|
+
"DELETE_DOCUMENT",
|
|
1620
|
+
"UPGRADE_DOCUMENT",
|
|
1621
|
+
"ADD_RELATIONSHIP",
|
|
1622
|
+
"REMOVE_RELATIONSHIP",
|
|
1623
|
+
"UPDATE_RELATIONSHIP"
|
|
1624
|
+
]);
|
|
1625
|
+
/**
|
|
1626
|
+
* The base-reducer protocol version to predict with when the snapshot's header
|
|
1627
|
+
* carries none.
|
|
1628
|
+
*
|
|
1629
|
+
* `baseReducer` reads `baseReducerVersion(document.header)` for every action and
|
|
1630
|
+
* throws when the header has no `protocolVersions`, which a header built by
|
|
1631
|
+
* {@link phDocumentFromGetDocument} lacks when the server sends none. The
|
|
1632
|
+
* version only selects how UNDO, REDO and RETRACT apply, and every action
|
|
1633
|
+
* reaching the prediction loop is an
|
|
1634
|
+
* ordinary append-only one, so it cannot change the predicted state here; it is
|
|
1635
|
+
* passed purely so the lookup does not throw.
|
|
1636
|
+
*/
|
|
1637
|
+
const predictionProtocolVersion = 2;
|
|
1638
|
+
/**
|
|
1639
|
+
* Stamps and signs a batch of actions against one document snapshot, so every
|
|
1640
|
+
* action carries the head its predecessor will leave behind.
|
|
1641
|
+
*
|
|
1642
|
+
* The server executes the array in order, each action against the state the one
|
|
1643
|
+
* before it produced. The snapshot the light client reads has correct state and
|
|
1644
|
+
* per-scope revisions but NO operation history (see `adapter.ts`), so the chain
|
|
1645
|
+
* is predicted here: reduce action N over the working document to get the state
|
|
1646
|
+
* action N+1 hashes, and carry a virtual revision alongside it. The revision has
|
|
1647
|
+
* to be tracked separately because the reducer derives operation indices from
|
|
1648
|
+
* the last stored operation, and with an empty history that counts from zero
|
|
1649
|
+
* rather than from the document's real revision.
|
|
1650
|
+
*
|
|
1651
|
+
* A single action needs no prediction and therefore no `module`, which keeps
|
|
1652
|
+
* today's callers working unchanged. Two or more require the document's exact
|
|
1653
|
+
* reducer, one shared scope (the reactor rejects mixed-scope jobs) and only
|
|
1654
|
+
* append-only actions. Anything else rejects: a batch that cannot be predicted
|
|
1655
|
+
* must fail before the mutation, never be downgraded to unsigned.
|
|
1656
|
+
*/
|
|
1657
|
+
async function prepareSignedActions(actions, snapshot, signer, module, signal) {
|
|
1658
|
+
if (actions.length === 0) return [];
|
|
1659
|
+
if (actions.length === 1) return [await signStampedAction(stampAction(actions[0], snapshot), signer, snapshotTarget(actions[0], snapshot), signal)];
|
|
1660
|
+
const scope = sharedScope(actions);
|
|
1661
|
+
assertSupportedBatch(actions);
|
|
1662
|
+
if (!module) throw new Error(`cannot sign ${actions.length} actions: no document model module for ${snapshot.header.documentType} was supplied, so the batch state cannot be predicted`);
|
|
1663
|
+
let working = {
|
|
1664
|
+
...snapshot,
|
|
1665
|
+
operations: {
|
|
1666
|
+
...snapshot.operations,
|
|
1667
|
+
[scope]: [...snapshot.operations[scope] ?? []]
|
|
1668
|
+
}
|
|
1669
|
+
};
|
|
1670
|
+
let revision = snapshot.header.revision[scope] ?? 0;
|
|
1671
|
+
const signed = [];
|
|
1672
|
+
for (const [index, action] of actions.entries()) {
|
|
1673
|
+
throwIfAborted(signal, index);
|
|
1674
|
+
const stamped = stampAction(action, working, revision);
|
|
1675
|
+
const signedAction = await signStampedAction(stamped, signer, snapshotTarget(stamped, snapshot), signal);
|
|
1676
|
+
signed.push(signedAction);
|
|
1677
|
+
const before = scopeOperationCount(working, scope);
|
|
1678
|
+
let next;
|
|
1679
|
+
try {
|
|
1680
|
+
next = module.reducer(working, signedAction, void 0, { protocolVersion: resolveBaseReducerVersion(working.header.protocolVersions) ?? predictionProtocolVersion });
|
|
1681
|
+
} catch (error) {
|
|
1682
|
+
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 });
|
|
1683
|
+
}
|
|
1684
|
+
const after = scopeOperationCount(next, scope);
|
|
1685
|
+
if (after !== before + 1) throw new Error(`cannot sign action ${index} (${action.type}): the reducer appended ${after - before} operations to ${scope}, expected exactly 1`);
|
|
1686
|
+
working = next;
|
|
1687
|
+
revision += 1;
|
|
1688
|
+
}
|
|
1689
|
+
return signed;
|
|
1690
|
+
}
|
|
1691
|
+
/**
|
|
1692
|
+
* How many operations a scope holds.
|
|
1693
|
+
*
|
|
1694
|
+
* The index signature types the array as always present, but a module's reducer
|
|
1695
|
+
* is arbitrary code: one that hands back a document without the scope should
|
|
1696
|
+
* produce the actionable error above, not a `TypeError` on `.length`.
|
|
1697
|
+
*/
|
|
1698
|
+
function scopeOperationCount(document, scope) {
|
|
1699
|
+
return document.operations[scope]?.length ?? 0;
|
|
1700
|
+
}
|
|
1701
|
+
/** The one scope a reactor job may span (`getSharedActionScope`). */
|
|
1702
|
+
function sharedScope(actions) {
|
|
1703
|
+
const scope = actions[0].scope;
|
|
1704
|
+
const mixed = actions.find((action) => action.scope !== scope);
|
|
1705
|
+
if (mixed) throw new Error(`cannot sign a batch spanning scopes "${scope}" and "${mixed.scope}": every action in one request must share a scope`);
|
|
1706
|
+
return scope;
|
|
1707
|
+
}
|
|
1708
|
+
function assertSupportedBatch(actions) {
|
|
1709
|
+
const unsupported = actions.find((action) => unsupportedBatchActions.has(action.type));
|
|
1710
|
+
if (unsupported) throw new Error(`cannot sign a batch containing ${unsupported.type}: it needs operation history or an alternate executor path, so send it as a single action`);
|
|
1711
|
+
}
|
|
1712
|
+
function throwIfAborted(signal, index) {
|
|
1713
|
+
if (signal?.aborted) throw new Error(`signing aborted before action ${index}`, { cause: signal.reason });
|
|
1714
|
+
}
|
|
1715
|
+
//#endregion
|
|
1716
|
+
//#region src/graphql-client/static-package-manager.ts
|
|
1717
|
+
/**
|
|
1718
|
+
* A fixed set of packages presented through the `IPackageManager` interface,
|
|
1719
|
+
* so the package-derived hooks - `useDocumentModelModules`,
|
|
1720
|
+
* `useDocumentModelModuleById`, `useEditorModules`, `useVetraPackages` - work
|
|
1721
|
+
* below `GraphQLReactorProvider` exactly as they do below Connect.
|
|
1722
|
+
*
|
|
1723
|
+
* Connect's package manager installs, updates and removes packages at runtime.
|
|
1724
|
+
* A light app instead declares its packages once, as code it imports itself
|
|
1725
|
+
* (every generated package root exports `manifest`, `documentModels`, `editors`
|
|
1726
|
+
* and `upgradeManifests` by name), so every mutating member throws and
|
|
1727
|
+
* `subscribe` never emits. For hand-picked modules without package artifacts,
|
|
1728
|
+
* {@link packageFromDocumentModels} wraps them in one synthetic package.
|
|
1729
|
+
*/
|
|
1730
|
+
var StaticPackageManager = class {
|
|
1731
|
+
registryUrl = null;
|
|
1732
|
+
packages;
|
|
1733
|
+
constructor(packages) {
|
|
1734
|
+
this.packages = [...packages];
|
|
1735
|
+
}
|
|
1736
|
+
/**
|
|
1737
|
+
* Resolves a module by document type across all packages. Mirrors the
|
|
1738
|
+
* registry's semantics (`IDocumentModelRegistry.getModule`): the LATEST
|
|
1739
|
+
* version wins, with `version ?? 1` as each module's default.
|
|
1740
|
+
*/
|
|
1741
|
+
load(documentType) {
|
|
1742
|
+
const modules = this.packages.flatMap((pkg) => pkg.documentModels);
|
|
1743
|
+
try {
|
|
1744
|
+
return Promise.resolve(resolveDocumentModelModule(modules, documentType));
|
|
1745
|
+
} catch (error) {
|
|
1746
|
+
return Promise.reject(error);
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
subscribe(_handler) {
|
|
1750
|
+
return () => {};
|
|
1751
|
+
}
|
|
1752
|
+
getPackageSource(_packageName) {
|
|
1753
|
+
return null;
|
|
1754
|
+
}
|
|
1755
|
+
getPackageVersion(_packageName) {}
|
|
1756
|
+
getPackageSpec(_packageName) {}
|
|
1757
|
+
getRegistryPackages() {
|
|
1758
|
+
return [];
|
|
1759
|
+
}
|
|
1760
|
+
addPackage(_packageName) {
|
|
1761
|
+
throw staticPackageManagerError("addPackage");
|
|
1762
|
+
}
|
|
1763
|
+
addPackages(_packageNames) {
|
|
1764
|
+
throw staticPackageManagerError("addPackages");
|
|
1765
|
+
}
|
|
1766
|
+
removePackage(_name) {
|
|
1767
|
+
throw staticPackageManagerError("removePackage");
|
|
1768
|
+
}
|
|
1769
|
+
updateLocalPackage(_pkg, _version) {
|
|
1770
|
+
throw staticPackageManagerError("updateLocalPackage");
|
|
1771
|
+
}
|
|
1772
|
+
addLocalPackage(_name, _loadedPackage, _version) {
|
|
1773
|
+
throw staticPackageManagerError("addLocalPackage");
|
|
1774
|
+
}
|
|
1775
|
+
};
|
|
1776
|
+
/**
|
|
1777
|
+
* Resolves one document-model module out of a flat module list, with the same
|
|
1778
|
+
* rule the reactor registry uses (`IDocumentModelRegistry.getModule`, at
|
|
1779
|
+
* packages/reactor/src/registry/implementation.ts): with a `version`, only an
|
|
1780
|
+
* EXACT `version ?? 1` match resolves; without one, the LATEST version wins.
|
|
1781
|
+
*
|
|
1782
|
+
* Signing an existing document needs the exact rule. A document carries the
|
|
1783
|
+
* model version it was written with in `state.document.version`, and its
|
|
1784
|
+
* reducer is the only one whose operations that document's history can accept -
|
|
1785
|
+
* so "latest" is correct only when no version is asked for.
|
|
1786
|
+
*
|
|
1787
|
+
* Pure and dependency-free on purpose: this is reachable from the browser
|
|
1788
|
+
* entry, so it must not pull the reactor registry in as a value.
|
|
1789
|
+
*/
|
|
1790
|
+
function resolveDocumentModelModule(modules, documentType, version) {
|
|
1791
|
+
let latestModule;
|
|
1792
|
+
let latestVersion = -1;
|
|
1793
|
+
for (const module of modules) {
|
|
1794
|
+
if (module.documentModel.global.id !== documentType) continue;
|
|
1795
|
+
const moduleVersion = module.version ?? 1;
|
|
1796
|
+
if (version !== void 0 && moduleVersion === version) return module;
|
|
1797
|
+
if (moduleVersion > latestVersion) {
|
|
1798
|
+
latestVersion = moduleVersion;
|
|
1799
|
+
latestModule = module;
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
if (version === void 0 && latestModule) return latestModule;
|
|
1803
|
+
throw new Error(version === void 0 ? `Unknown document type: ${documentType}` : `Unknown document model version: ${documentType} v${version}` + (latestModule ? ` (available: ${availableVersions(modules, documentType).join(", ")})` : " (no module for this document type)"));
|
|
1804
|
+
}
|
|
1805
|
+
function availableVersions(modules, documentType) {
|
|
1806
|
+
return modules.filter((module) => module.documentModel.global.id === documentType).map((module) => module.version ?? 1).sort((a, b) => a - b);
|
|
1807
|
+
}
|
|
1808
|
+
function staticPackageManagerError(member) {
|
|
1809
|
+
return /* @__PURE__ */ new Error(`${member} is not supported: StaticPackageManager holds a fixed set of packages`);
|
|
1810
|
+
}
|
|
1811
|
+
/**
|
|
1812
|
+
* Wraps hand-picked modules in one synthetic `DocumentModelLib`, for apps that
|
|
1813
|
+
* assemble their model list from mixed sources instead of passing whole
|
|
1814
|
+
* packages. The manifest is fabricated - loose modules carry none - so prefer
|
|
1815
|
+
* the `packages` prop with the real package exports when you have them: a real
|
|
1816
|
+
* package also carries `editors`, which makes the editor hooks work.
|
|
1817
|
+
*/
|
|
1818
|
+
function packageFromDocumentModels(documentModels) {
|
|
1819
|
+
return {
|
|
1820
|
+
manifest: {
|
|
1821
|
+
name: "graphql-reactor-provider",
|
|
1822
|
+
description: "Document models passed to GraphQLReactorProvider"
|
|
1823
|
+
},
|
|
1824
|
+
documentModels,
|
|
1825
|
+
editors: []
|
|
1826
|
+
};
|
|
1827
|
+
}
|
|
1828
|
+
//#endregion
|
|
1829
|
+
//#region src/graphql-client/subgraph.ts
|
|
1830
|
+
/** What {@link describeGraphQLDocument} could not read off a document. */
|
|
1831
|
+
const unnamedOperation = "AnonymousOperation";
|
|
1832
|
+
const defaultOperationType = "query";
|
|
1833
|
+
/**
|
|
1834
|
+
* Derives a subgraph's endpoint from the Switchboard's GraphQL endpoint.
|
|
1835
|
+
*
|
|
1836
|
+
* Subgraphs are served next to the supergraph, at `<graphql base>/<name>`, so
|
|
1837
|
+
* `http://localhost:4001/graphql` plus `statements` is
|
|
1838
|
+
* `http://localhost:4001/graphql/statements`.
|
|
1839
|
+
*/
|
|
1840
|
+
function subgraphUrlFromGraphqlUrl(url, name) {
|
|
1841
|
+
const trimmed = name.trim();
|
|
1842
|
+
if (trimmed === "") throw new Error("a subgraph name is required");
|
|
1843
|
+
return `${url.replace(/\/+$/, "")}/${trimmed}`;
|
|
1844
|
+
}
|
|
1845
|
+
/**
|
|
1846
|
+
* Reads the operation name and type off a document, for the middleware.
|
|
1847
|
+
*
|
|
1848
|
+
* Nothing depends on getting this right - it is reported to the middleware, not
|
|
1849
|
+
* sent to the server - so an unreadable document falls back to an anonymous
|
|
1850
|
+
* query rather than throwing.
|
|
1851
|
+
*/
|
|
1852
|
+
function describeGraphQLDocument(document) {
|
|
1853
|
+
if (typeof document !== "string") {
|
|
1854
|
+
const operation = document.definitions.find((definition) => definition.kind === Kind.OPERATION_DEFINITION);
|
|
1855
|
+
if (!operation || operation.kind !== Kind.OPERATION_DEFINITION) return {
|
|
1856
|
+
operationName: unnamedOperation,
|
|
1857
|
+
operationType: defaultOperationType
|
|
1858
|
+
};
|
|
1859
|
+
return {
|
|
1860
|
+
operationName: operation.name?.value ?? unnamedOperation,
|
|
1861
|
+
operationType: operation.operation
|
|
1862
|
+
};
|
|
1863
|
+
}
|
|
1864
|
+
const match = /\b(query|mutation|subscription)\s+([_A-Za-z][_0-9A-Za-z]*)/.exec(document);
|
|
1865
|
+
if (!match) return {
|
|
1866
|
+
operationName: unnamedOperation,
|
|
1867
|
+
operationType: /\bmutation\b/.test(document) ? "mutation" : defaultOperationType
|
|
1868
|
+
};
|
|
1869
|
+
return {
|
|
1870
|
+
operationName: match[2],
|
|
1871
|
+
operationType: match[1]
|
|
1872
|
+
};
|
|
1873
|
+
}
|
|
1874
|
+
/**
|
|
1875
|
+
* Binds typed subgraph SDKs to one Switchboard's transport and auth.
|
|
1876
|
+
*
|
|
1877
|
+
* Every capability a Switchboard exposes lives behind the same base URL, so an
|
|
1878
|
+
* app should not have to build a second client - with a second copy of the auth
|
|
1879
|
+
* configuration - to reach a project's own subgraph. The registry derives the
|
|
1880
|
+
* endpoint, reuses one transport per subgraph and hands the code generator's
|
|
1881
|
+
* `getSdk` the very middleware the reactor operations already go through.
|
|
1882
|
+
*
|
|
1883
|
+
* Transport and typing only: subgraph results are not cached and produce no
|
|
1884
|
+
* change events.
|
|
1885
|
+
*/
|
|
1886
|
+
var SubgraphSdkRegistry = class {
|
|
1887
|
+
url;
|
|
1888
|
+
middleware;
|
|
1889
|
+
fetch;
|
|
1890
|
+
bindings = /* @__PURE__ */ new Map();
|
|
1891
|
+
constructor(url, middleware, fetch) {
|
|
1892
|
+
this.url = url;
|
|
1893
|
+
this.middleware = middleware;
|
|
1894
|
+
this.fetch = fetch;
|
|
1895
|
+
}
|
|
1896
|
+
/**
|
|
1897
|
+
* Returns the subgraph's SDK, building it on first use.
|
|
1898
|
+
*
|
|
1899
|
+
* The transport is kept per subgraph name, so repeated calls do not rebuild
|
|
1900
|
+
* it. The SDK itself is only reused when the same factory is passed again -
|
|
1901
|
+
* two different generated SDKs over one subgraph each get their own, rather
|
|
1902
|
+
* than the second call being handed the first one's methods.
|
|
1903
|
+
*/
|
|
1904
|
+
get(name, getSdk) {
|
|
1905
|
+
const binding = this.binding(name);
|
|
1906
|
+
if (binding.factory === getSdk) return binding.sdk;
|
|
1907
|
+
const sdk = getSdk(binding.transport, this.middleware);
|
|
1908
|
+
binding.factory = getSdk;
|
|
1909
|
+
binding.sdk = sdk;
|
|
1910
|
+
return sdk;
|
|
1911
|
+
}
|
|
1912
|
+
/** Returns the subgraph's endpoint, for diagnostics and tests. */
|
|
1913
|
+
urlFor(name) {
|
|
1914
|
+
return subgraphUrlFromGraphqlUrl(this.url, name);
|
|
1915
|
+
}
|
|
1916
|
+
binding(name) {
|
|
1917
|
+
const existing = this.bindings.get(name);
|
|
1918
|
+
if (existing) return existing;
|
|
1919
|
+
const binding = { transport: new GraphQLClient(this.urlFor(name), { fetch: this.fetch }) };
|
|
1920
|
+
this.bindings.set(name, binding);
|
|
1921
|
+
return binding;
|
|
1922
|
+
}
|
|
1923
|
+
};
|
|
1924
|
+
//#endregion
|
|
1925
|
+
//#region src/graphql-client/subscriptions.ts
|
|
1926
|
+
/**
|
|
1927
|
+
* The 4403 close reasons a Switchboard refuses a handshake with.
|
|
1928
|
+
*
|
|
1929
|
+
* Mirrors `WS_AUTH_CLOSE_REASONS` in `@powerhousedao/reactor-api`
|
|
1930
|
+
* (`src/graphql/gateway/types.ts`). This package does not depend on that one,
|
|
1931
|
+
* so the strings are duplicated and are a wire contract: change them on both
|
|
1932
|
+
* sides or not at all.
|
|
1933
|
+
*/
|
|
1934
|
+
const authCloseReasons = ["authentication-required", "bearer-rejected"];
|
|
1935
|
+
/** graphql-ws's own `isLikeCloseEvent`, which it does not export. */
|
|
1936
|
+
function isLikeCloseEvent(value) {
|
|
1937
|
+
return typeof value === "object" && value !== null && "code" in value && "reason" in value;
|
|
1938
|
+
}
|
|
1939
|
+
/**
|
|
1940
|
+
* Whether a socket failure is the Switchboard refusing the credentials sent.
|
|
1941
|
+
*
|
|
1942
|
+
* Keyed on the close reason, not the code: both refusals close 4403, because
|
|
1943
|
+
* `connectionParams` is resolved per connect and a reconnect carrying a fresh
|
|
1944
|
+
* token genuinely succeeds. What the reason adds is that *this* attempt cannot
|
|
1945
|
+
* be fixed by repeating it.
|
|
1946
|
+
*/
|
|
1947
|
+
function isAuthRefusalClose(error) {
|
|
1948
|
+
return isLikeCloseEvent(error) && authCloseReasons.includes(error.reason);
|
|
1949
|
+
}
|
|
1950
|
+
/**
|
|
1951
|
+
* Opens one `documentChanges` subscription and feeds every event to `onEvent`.
|
|
1952
|
+
*
|
|
1953
|
+
* The subscription is a firehose: no `search` argument, so the server sends
|
|
1954
|
+
* every change the connection is allowed to see and the caller filters. This is
|
|
1955
|
+
* the only module that knows about `graphql-ws`.
|
|
1956
|
+
*
|
|
1957
|
+
* Returns the stop function, which cancels the subscription and closes the
|
|
1958
|
+
* socket. It is safe to call more than once.
|
|
1959
|
+
*/
|
|
1960
|
+
function startDocumentChangesSubscription(options) {
|
|
1961
|
+
const client = createClient({
|
|
1962
|
+
url: options.wsUrl,
|
|
1963
|
+
connectionParams: options.connectionParams,
|
|
1964
|
+
shouldRetry: (errOrCloseEvent) => isLikeCloseEvent(errOrCloseEvent) && !isAuthRefusalClose(errOrCloseEvent)
|
|
1965
|
+
});
|
|
1966
|
+
const unsubscribe = client.subscribe({
|
|
1967
|
+
operationName: "DocumentChanges",
|
|
1968
|
+
query: print(DocumentChangesDocument)
|
|
1969
|
+
}, {
|
|
1970
|
+
next: (result) => {
|
|
1971
|
+
const event = result.data?.documentChanges;
|
|
1972
|
+
if (event) options.onEvent(event);
|
|
1973
|
+
},
|
|
1974
|
+
error: (error) => options.onError(error),
|
|
1975
|
+
complete: () => void 0
|
|
1976
|
+
});
|
|
1977
|
+
let stopped = false;
|
|
1978
|
+
return () => {
|
|
1979
|
+
if (stopped) return;
|
|
1980
|
+
stopped = true;
|
|
1981
|
+
unsubscribe();
|
|
1982
|
+
client.dispose();
|
|
1983
|
+
};
|
|
1984
|
+
}
|
|
1985
|
+
/**
|
|
1986
|
+
* Opens the socket write handles wait on. `graphql-ws` multiplexes every
|
|
1987
|
+
* watched job over it and closes it once the last watch stops.
|
|
1988
|
+
*/
|
|
1989
|
+
function createJobChangesSocket(options) {
|
|
1990
|
+
let client;
|
|
1991
|
+
const clientOf = () => client ??= createClient({
|
|
1992
|
+
url: options.wsUrl,
|
|
1993
|
+
connectionParams: options.connectionParams,
|
|
1994
|
+
shouldRetry: (errOrCloseEvent) => isLikeCloseEvent(errOrCloseEvent) && !isAuthRefusalClose(errOrCloseEvent)
|
|
1995
|
+
});
|
|
1996
|
+
return {
|
|
1997
|
+
watch(jobId, onEvent, onError) {
|
|
1998
|
+
const unsubscribe = clientOf().subscribe({
|
|
1999
|
+
operationName: "JobChanges",
|
|
2000
|
+
query: print(JobChangesDocument),
|
|
2001
|
+
variables: { jobId }
|
|
2002
|
+
}, {
|
|
2003
|
+
next: (result) => {
|
|
2004
|
+
const event = result.data?.jobChanges;
|
|
2005
|
+
if (event) onEvent(event);
|
|
2006
|
+
},
|
|
2007
|
+
error: (error) => onError(error),
|
|
2008
|
+
complete: () => void 0
|
|
2009
|
+
});
|
|
2010
|
+
let stopped = false;
|
|
2011
|
+
return () => {
|
|
2012
|
+
if (stopped) return;
|
|
2013
|
+
stopped = true;
|
|
2014
|
+
unsubscribe();
|
|
2015
|
+
};
|
|
2016
|
+
},
|
|
2017
|
+
dispose() {
|
|
2018
|
+
const current = client;
|
|
2019
|
+
client = void 0;
|
|
2020
|
+
current?.dispose();
|
|
2021
|
+
}
|
|
2022
|
+
};
|
|
2023
|
+
}
|
|
2024
|
+
/**
|
|
2025
|
+
* Derives the websocket endpoint from the GraphQL http endpoint.
|
|
2026
|
+
*
|
|
2027
|
+
* `http://host/graphql` becomes `ws://host/graphql/subscriptions`, which is
|
|
2028
|
+
* where the Switchboard mounts its websocket server (`packages/reactor-api`
|
|
2029
|
+
* `startServer`). A URL that already speaks `ws`/`wss` only gets the path.
|
|
2030
|
+
*/
|
|
2031
|
+
function subscriptionsUrlFromGraphqlUrl(url) {
|
|
2032
|
+
const trimmed = url.replace(/\/+$/, "");
|
|
2033
|
+
return `${trimmed.startsWith("https://") ? `wss://${trimmed.slice(8)}` : trimmed.startsWith("http://") ? `ws://${trimmed.slice(7)}` : trimmed}/subscriptions`;
|
|
2034
|
+
}
|
|
2035
|
+
/**
|
|
2036
|
+
* Turns a bearer token provider into `connectionParams`.
|
|
2037
|
+
*
|
|
2038
|
+
* The header key is the lowercase `authorization` the Switchboard's websocket
|
|
2039
|
+
* context factory reads. Without a token the payload is empty: an open
|
|
2040
|
+
* Switchboard serves anonymous subscribers.
|
|
2041
|
+
*/
|
|
2042
|
+
function makeAuthConnectionParams(tokenProvider) {
|
|
2043
|
+
return async () => {
|
|
2044
|
+
const token = await tokenProvider();
|
|
2045
|
+
if (!token) return {};
|
|
2046
|
+
return { authorization: `Bearer ${token}` };
|
|
2047
|
+
};
|
|
2048
|
+
}
|
|
2049
|
+
//#endregion
|
|
2050
|
+
//#region src/graphql-client/write-handles.ts
|
|
2051
|
+
/** Whether a job status has reached a stage, FAILED counting as settled. */
|
|
2052
|
+
function settlesGraphQLJobStage(status, stage) {
|
|
2053
|
+
const value = status;
|
|
2054
|
+
if (value === "FAILED" || value === "READ_READY") return true;
|
|
2055
|
+
return stage === "written" && value === "WRITE_READY";
|
|
2056
|
+
}
|
|
2057
|
+
function emptyToken() {
|
|
2058
|
+
return {
|
|
2059
|
+
version: 1,
|
|
2060
|
+
createdAtUtcIso: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2061
|
+
coordinates: []
|
|
2062
|
+
};
|
|
2063
|
+
}
|
|
2064
|
+
function abortError(signal) {
|
|
2065
|
+
const reason = signal.reason;
|
|
2066
|
+
return reason instanceof Error ? reason : new Error(String(reason));
|
|
2067
|
+
}
|
|
2068
|
+
/** `promise`, rejected early when `signal` aborts. */
|
|
2069
|
+
function bounded(promise, signal) {
|
|
2070
|
+
if (!signal) return promise;
|
|
2071
|
+
if (signal.aborted) return Promise.reject(abortError(signal));
|
|
2072
|
+
return new Promise((resolve, reject) => {
|
|
2073
|
+
const onAbort = () => reject(abortError(signal));
|
|
2074
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2075
|
+
promise.then((value) => {
|
|
2076
|
+
signal.removeEventListener("abort", onAbort);
|
|
2077
|
+
resolve(value);
|
|
2078
|
+
}, (error) => {
|
|
2079
|
+
signal.removeEventListener("abort", onAbort);
|
|
2080
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
2081
|
+
});
|
|
2082
|
+
});
|
|
2083
|
+
}
|
|
2084
|
+
/**
|
|
2085
|
+
* A write handle over a job the Switchboard accepted (`executeAsync`).
|
|
2086
|
+
*
|
|
2087
|
+
* Each stage is the waiter's: `jobStatus`, woken early by the `jobChanges`
|
|
2088
|
+
* subscription when the client has realtime. Stage promises are created on
|
|
2089
|
+
* first access, so a fire-and-forget caller never owns a rejection. A FAILED
|
|
2090
|
+
* job rejects a stage with {@link JobFailedError}.
|
|
2091
|
+
*
|
|
2092
|
+
* `document()` with no view is read once and shared, so the client's own
|
|
2093
|
+
* change announcement and the caller's read-back cost one request.
|
|
2094
|
+
*/
|
|
2095
|
+
var GraphQLJobWriteHandle = class {
|
|
2096
|
+
job;
|
|
2097
|
+
jobId;
|
|
2098
|
+
documentId;
|
|
2099
|
+
branch;
|
|
2100
|
+
wait;
|
|
2101
|
+
reader;
|
|
2102
|
+
signal;
|
|
2103
|
+
writtenReceipt;
|
|
2104
|
+
readableReceipt;
|
|
2105
|
+
defaultDocument;
|
|
2106
|
+
constructor(job, documentId, branch, wait, reader, signal) {
|
|
2107
|
+
this.job = job;
|
|
2108
|
+
this.jobId = job.id;
|
|
2109
|
+
this.documentId = documentId;
|
|
2110
|
+
this.branch = branch;
|
|
2111
|
+
this.wait = wait;
|
|
2112
|
+
this.reader = reader;
|
|
2113
|
+
this.signal = signal;
|
|
2114
|
+
}
|
|
2115
|
+
get written() {
|
|
2116
|
+
this.writtenReceipt ??= this.receiptAt("written");
|
|
2117
|
+
return this.writtenReceipt;
|
|
2118
|
+
}
|
|
2119
|
+
get readable() {
|
|
2120
|
+
this.readableReceipt ??= this.receiptAt("readable");
|
|
2121
|
+
return this.readableReceipt;
|
|
2122
|
+
}
|
|
2123
|
+
async document(view, signal) {
|
|
2124
|
+
if (view !== void 0) {
|
|
2125
|
+
const receipt = await bounded(this.readable, signal);
|
|
2126
|
+
return this.reader(receipt, view, signal);
|
|
2127
|
+
}
|
|
2128
|
+
this.defaultDocument ??= this.readable.then((receipt) => this.reader(receipt, void 0, void 0));
|
|
2129
|
+
return bounded(this.defaultDocument, signal);
|
|
2130
|
+
}
|
|
2131
|
+
async receiptAt(stage) {
|
|
2132
|
+
const job = await this.wait(this.jobId, stage, this.signal);
|
|
2133
|
+
if (job.status === "FAILED") throw new JobFailedError(job);
|
|
2134
|
+
return {
|
|
2135
|
+
job,
|
|
2136
|
+
token: job.consistencyToken,
|
|
2137
|
+
documentId: this.documentId,
|
|
2138
|
+
branch: this.branch
|
|
2139
|
+
};
|
|
2140
|
+
}
|
|
2141
|
+
};
|
|
2142
|
+
/**
|
|
2143
|
+
* A write handle for a write the Switchboard applied before answering: the
|
|
2144
|
+
* synchronous `createDocument` and `deleteDocument` mutations name no job. Both
|
|
2145
|
+
* stages are settled; `jobId` is empty and the receipt's job is a READ_READY
|
|
2146
|
+
* placeholder with an empty token, as the reactor's own settled handle has.
|
|
2147
|
+
*/
|
|
2148
|
+
var GraphQLSettledWriteHandle = class {
|
|
2149
|
+
jobId = "";
|
|
2150
|
+
documentId;
|
|
2151
|
+
branch;
|
|
2152
|
+
receipt;
|
|
2153
|
+
reader;
|
|
2154
|
+
constructor(documentId, branch, reader) {
|
|
2155
|
+
this.documentId = documentId;
|
|
2156
|
+
this.branch = branch;
|
|
2157
|
+
this.reader = reader;
|
|
2158
|
+
const token = emptyToken();
|
|
2159
|
+
this.receipt = {
|
|
2160
|
+
job: {
|
|
2161
|
+
id: "",
|
|
2162
|
+
documentId,
|
|
2163
|
+
status: "READ_READY",
|
|
2164
|
+
createdAtUtcIso: token.createdAtUtcIso,
|
|
2165
|
+
consistencyToken: token,
|
|
2166
|
+
meta: {
|
|
2167
|
+
batchId: "",
|
|
2168
|
+
batchJobIds: []
|
|
2169
|
+
}
|
|
2170
|
+
},
|
|
2171
|
+
token,
|
|
2172
|
+
documentId,
|
|
2173
|
+
branch
|
|
2174
|
+
};
|
|
2175
|
+
}
|
|
2176
|
+
get written() {
|
|
2177
|
+
return Promise.resolve(this.receipt);
|
|
2178
|
+
}
|
|
2179
|
+
get readable() {
|
|
2180
|
+
return Promise.resolve(this.receipt);
|
|
2181
|
+
}
|
|
2182
|
+
document(view, signal) {
|
|
2183
|
+
return this.reader(this.receipt, view, signal);
|
|
2184
|
+
}
|
|
2185
|
+
};
|
|
2186
|
+
//#endregion
|
|
2187
|
+
//#region src/graphql-client/graphql-reactor-client.ts
|
|
2188
|
+
const BUILT_IN_MODELS = [driveDocumentModelModule];
|
|
2189
|
+
/** Paging defaults, matching the reactor's own client. */
|
|
2190
|
+
const defaultPaging = {
|
|
2191
|
+
cursor: "0",
|
|
2192
|
+
limit: 100
|
|
2193
|
+
};
|
|
2194
|
+
const JOB_POLL_INTERVAL_MS = 250;
|
|
2195
|
+
/** The first `jobStatus` poll of a write handle's stage wait, doubling from here. */
|
|
2196
|
+
const STAGE_POLL_START_MS = 25;
|
|
2197
|
+
/**
|
|
2198
|
+
* The longest a stage wait sleeps between `jobStatus` polls while the
|
|
2199
|
+
* `jobChanges` subscription is up: the subscription wakes it early, and the
|
|
2200
|
+
* poll is the safety net for an event that raced the subscription.
|
|
2201
|
+
*/
|
|
2202
|
+
const STAGE_POLL_REALTIME_MAX_MS = 1e3;
|
|
2203
|
+
/**
|
|
2204
|
+
* The marker {@link isGraphQLReactorClient} looks for.
|
|
2205
|
+
*
|
|
2206
|
+
* A page can end up with two copies of this module - an app that bundles a
|
|
2207
|
+
* package carrying its own copy, or a dev server that hot-replaced it - and
|
|
2208
|
+
* then `instanceof` compares an instance against the other copy's class object
|
|
2209
|
+
* and answers `false`. A branded property survives both.
|
|
2210
|
+
*/
|
|
2211
|
+
const graphQLReactorClientBrand = "__powerhouseGraphQLReactorClient";
|
|
2212
|
+
/**
|
|
2213
|
+
* A light implementation of {@link IReactorBrowserClient} that talks plain
|
|
2214
|
+
* GraphQL to a Switchboard, with no reactor in the bundle.
|
|
2215
|
+
*
|
|
2216
|
+
* It fills the same `window.ph` slots the full in-browser reactor client fills,
|
|
2217
|
+
* so the reactor-browser hooks cannot tell the two apart.
|
|
2218
|
+
*/
|
|
2219
|
+
var GraphQLReactorClient = class {
|
|
2220
|
+
/** See {@link isGraphQLReactorClient}. */
|
|
2221
|
+
[graphQLReactorClientBrand] = true;
|
|
2222
|
+
sdk;
|
|
2223
|
+
/** For `executeBatch`, the one write a request waits for: see {@link batchRequestTimeoutMs}. */
|
|
2224
|
+
batchSdk;
|
|
2225
|
+
subgraphs;
|
|
2226
|
+
listeners = [];
|
|
2227
|
+
tokenProvider;
|
|
2228
|
+
subscriptionsUrl;
|
|
2229
|
+
documentModels;
|
|
2230
|
+
resolveSigner;
|
|
2231
|
+
driveIdFor;
|
|
2232
|
+
undoRedoChains = /* @__PURE__ */ new Map();
|
|
2233
|
+
stopRealtime;
|
|
2234
|
+
realtimeStarted = false;
|
|
2235
|
+
realtimeGeneration = 0;
|
|
2236
|
+
realtimeErrorLogged = false;
|
|
2237
|
+
/** Whether the last socket died because the Switchboard refused its credentials. */
|
|
2238
|
+
realtimeRefusedCredentials = false;
|
|
2239
|
+
/** The socket write handles wait on; opened by the first stage wait. */
|
|
2240
|
+
jobSocket;
|
|
2241
|
+
/** Set once the `jobChanges` subscription failed; stage waits then only poll. */
|
|
2242
|
+
jobRealtimeBroken = false;
|
|
2243
|
+
/** Set once the Switchboard refused the `document` query's `consistency` argument. */
|
|
2244
|
+
consistencyUnsupported = false;
|
|
2245
|
+
driveNodes;
|
|
2246
|
+
/**
|
|
2247
|
+
* The read half: the reads the hooks make. Every method is this client's
|
|
2248
|
+
* own; nothing that writes is reachable from it.
|
|
2249
|
+
*/
|
|
2250
|
+
read;
|
|
2251
|
+
/**
|
|
2252
|
+
* The write half. `execute` submits through `executeAsync` and hands back a
|
|
2253
|
+
* handle whose `written` and `readable` resolve from `jobStatus`, woken by
|
|
2254
|
+
* the `jobChanges` subscription when realtime is on, and whose `document()`
|
|
2255
|
+
* runs the `document` query bounded by the receipt's token. `create` and
|
|
2256
|
+
* `deleteDocument` have no asynchronous mutation: they run the synchronous
|
|
2257
|
+
* ones and hand back a settled handle.
|
|
2258
|
+
*/
|
|
2259
|
+
write;
|
|
2260
|
+
constructor(options) {
|
|
2261
|
+
this.tokenProvider = options.tokenProvider ?? ambientRenownTokenProvider;
|
|
2262
|
+
const models = options.documentModels;
|
|
2263
|
+
if (typeof models === "function") this.documentModels = models;
|
|
2264
|
+
else {
|
|
2265
|
+
const copied = [...models ?? []];
|
|
2266
|
+
this.documentModels = () => copied;
|
|
2267
|
+
}
|
|
2268
|
+
const signer = options.signer;
|
|
2269
|
+
this.resolveSigner = typeof signer === "function" ? signer : signer ? () => signer : ambientRenownSigner;
|
|
2270
|
+
this.driveIdFor = options.driveIdFor;
|
|
2271
|
+
this.subscriptionsUrl = options.realtime === false ? void 0 : options.subscriptionsUrl ?? subscriptionsUrlFromGraphqlUrl(options.url);
|
|
2272
|
+
const middleware = withWrongBackendErrors(makeAuthMiddleware(this.tokenProvider));
|
|
2273
|
+
const fetch = options.requestTimeoutMs === void 0 ? options.fetch : withRequestDeadline(options.requestTimeoutMs, options.fetch);
|
|
2274
|
+
this.sdk = options.graphqlClient ?? createClient$1(new GraphQLClient(options.url, { fetch }), middleware);
|
|
2275
|
+
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);
|
|
2276
|
+
this.subgraphs = new SubgraphSdkRegistry(options.url, middleware, fetch);
|
|
2277
|
+
this.driveNodes = new GraphQLDriveNodeSource(this.sdk, driveIdHeaders);
|
|
2278
|
+
this.read = new GraphQLReadHalf(this, this.driveNodes);
|
|
2279
|
+
this.write = {
|
|
2280
|
+
execute: (documentIdentifier, branch, actions, signal) => this.submitExecute(documentIdentifier, branch, actions, signal),
|
|
2281
|
+
create: (document, parentIdentifier, signal) => this.submitCreate(document, parentIdentifier, signal),
|
|
2282
|
+
deleteDocument: (identifier, propagate, signal) => this.submitDeleteDocument(identifier, propagate, signal)
|
|
2283
|
+
};
|
|
2284
|
+
}
|
|
2285
|
+
/**
|
|
2286
|
+
* The Switchboard's drive node queries as a node source, for every drive
|
|
2287
|
+
* type. `read.drives` answers from it.
|
|
2288
|
+
*/
|
|
2289
|
+
nodeSource() {
|
|
2290
|
+
return this.driveNodes;
|
|
2291
|
+
}
|
|
2292
|
+
/**
|
|
2293
|
+
* Reads a document. With a consistency token that names any coordinate, the
|
|
2294
|
+
* Switchboard waits until its read models hold them; one without the
|
|
2295
|
+
* `document` query's `consistency` argument is read without it, which after
|
|
2296
|
+
* a write's `readable` stage still sees the write on a single node.
|
|
2297
|
+
*/
|
|
2298
|
+
async get(identifier, view, signal, consistencyToken) {
|
|
2299
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2300
|
+
const document = (consistencyToken && consistencyToken.coordinates.length > 0 ? await this.getDocumentAtConsistency(identifier, viewInput, consistencyToken, signal) : await this.sdk.GetDocument({
|
|
2301
|
+
identifier,
|
|
2302
|
+
view: viewInput
|
|
2303
|
+
}, void 0, signal)).document;
|
|
2304
|
+
if (!document) throw new Error(`Document not found: ${identifier}`);
|
|
2305
|
+
return phDocumentFromGetDocument(document.document, view?.branch);
|
|
2306
|
+
}
|
|
2307
|
+
/**
|
|
2308
|
+
* Reads documents by id, in the order given; throws if any is missing. Each
|
|
2309
|
+
* chunk of {@link GET_MANY_CHUNK_SIZE} ids is one request holding an aliased
|
|
2310
|
+
* `document` field per id, with the selection and arguments `get` sends.
|
|
2311
|
+
*/
|
|
2312
|
+
async getMany(documentIds, view, signal, consistencyToken) {
|
|
2313
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2314
|
+
const token = consistencyToken && consistencyToken.coordinates.length > 0 ? consistencyToken : void 0;
|
|
2315
|
+
const chunks = [];
|
|
2316
|
+
for (let i = 0; i < documentIds.length; i += GET_MANY_CHUNK_SIZE) chunks.push(documentIds.slice(i, i + GET_MANY_CHUNK_SIZE));
|
|
2317
|
+
return (await Promise.all(chunks.map((chunk) => this.getDocumentChunk(chunk, viewInput, token, signal)))).flat().map((document) => phDocumentFromGetDocument(document, view?.branch));
|
|
2318
|
+
}
|
|
2319
|
+
/** One chunk of `getMany`, with the `consistency` argument while the Switchboard accepts it. */
|
|
2320
|
+
async getDocumentChunk(identifiers, view, token, signal) {
|
|
2321
|
+
if (token && !this.consistencyUnsupported) try {
|
|
2322
|
+
return await this.runGetDocuments(identifiers, view, consistencyInputFromToken(token), signal);
|
|
2323
|
+
} catch (error) {
|
|
2324
|
+
if (!refusesConsistencyArgument(error)) throw error;
|
|
2325
|
+
this.consistencyUnsupported = true;
|
|
2326
|
+
}
|
|
2327
|
+
return this.runGetDocuments(identifiers, view, void 0, signal);
|
|
2328
|
+
}
|
|
2329
|
+
async runGetDocuments(identifiers, view, consistency, signal) {
|
|
2330
|
+
const variables = { view };
|
|
2331
|
+
const definitions = ["$view: ViewFilterInput"];
|
|
2332
|
+
let consistencyArgument = "";
|
|
2333
|
+
if (consistency) {
|
|
2334
|
+
variables.consistency = consistency;
|
|
2335
|
+
definitions.push("$consistency: ConsistencyTokenInput");
|
|
2336
|
+
consistencyArgument = ", consistency: $consistency";
|
|
2337
|
+
}
|
|
2338
|
+
const fields = identifiers.map((identifier, i) => {
|
|
2339
|
+
variables[`id${i}`] = identifier;
|
|
2340
|
+
definitions.push(`$id${i}: String!`);
|
|
2341
|
+
return `d${i}: document(identifier: $id${i}, view: $view${consistencyArgument}) { document { ...PHDocumentFields } childIds }`;
|
|
2342
|
+
});
|
|
2343
|
+
const query = [
|
|
2344
|
+
`query GetDocuments(${definitions.join(", ")}) {`,
|
|
2345
|
+
...fields,
|
|
2346
|
+
"}",
|
|
2347
|
+
PH_DOCUMENT_FIELDS_SOURCE
|
|
2348
|
+
].join("\n");
|
|
2349
|
+
const data = await this.sdk.RunDocument({
|
|
2350
|
+
operationName: "GetDocuments",
|
|
2351
|
+
operationType: "query",
|
|
2352
|
+
document: query,
|
|
2353
|
+
variables,
|
|
2354
|
+
signal
|
|
2355
|
+
});
|
|
2356
|
+
return identifiers.map((identifier, i) => {
|
|
2357
|
+
const result = data[`d${i}`];
|
|
2358
|
+
if (!result) throw new Error(`Document not found: ${identifier}`);
|
|
2359
|
+
return result.document;
|
|
2360
|
+
});
|
|
2361
|
+
}
|
|
2362
|
+
/**
|
|
2363
|
+
* Whether the Switchboard would serve the document to this client's caller,
|
|
2364
|
+
* from its `documentServed` query: the same read gate `find` passes. Absent
|
|
2365
|
+
* or withheld is `false`; a failure to decide throws.
|
|
2366
|
+
*
|
|
2367
|
+
* A point-in-time view throws {@link GraphQLOperationNotSupportedError}, as
|
|
2368
|
+
* does a Switchboard without the query.
|
|
2369
|
+
*/
|
|
2370
|
+
async isServed(identifier, view, signal) {
|
|
2371
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2372
|
+
try {
|
|
2373
|
+
return (await this.sdk.GetDocumentServed({
|
|
2374
|
+
idOrSlug: identifier,
|
|
2375
|
+
view: viewInput
|
|
2376
|
+
}, void 0, signal)).documentServed;
|
|
2377
|
+
} catch (error) {
|
|
2378
|
+
if (queriesUnknownField(error, "documentServed")) throw new GraphQLOperationNotSupportedError("isServed", "the Switchboard predates the documentServed query");
|
|
2379
|
+
throw error;
|
|
2380
|
+
}
|
|
2381
|
+
}
|
|
2382
|
+
async getOperations(documentIdentifier, view, filter, paging, signal) {
|
|
2383
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2384
|
+
const operationsFilter = {
|
|
2385
|
+
documentId: documentIdentifier,
|
|
2386
|
+
branch: viewInput?.branch,
|
|
2387
|
+
scopes: viewInput?.scopes,
|
|
2388
|
+
actionTypes: filter?.actionTypes,
|
|
2389
|
+
timestampFrom: filter?.timestampFrom,
|
|
2390
|
+
timestampTo: filter?.timestampTo,
|
|
2391
|
+
sinceRevision: filter?.sinceRevision
|
|
2392
|
+
};
|
|
2393
|
+
const page = (await this.sdk.GetDocumentOperations({
|
|
2394
|
+
filter: operationsFilter,
|
|
2395
|
+
paging: pagingInputFromPaging(paging)
|
|
2396
|
+
}, void 0, signal)).documentOperations;
|
|
2397
|
+
const nextCursor = page.hasNextPage ? page.cursor ?? void 0 : void 0;
|
|
2398
|
+
const effectivePaging = paging ?? defaultPaging;
|
|
2399
|
+
return {
|
|
2400
|
+
results: page.items.map((item) => remoteOperationToLocal(item)),
|
|
2401
|
+
options: effectivePaging,
|
|
2402
|
+
nextCursor,
|
|
2403
|
+
next: nextCursor ? () => this.getOperations(documentIdentifier, view, filter, {
|
|
2404
|
+
cursor: nextCursor,
|
|
2405
|
+
limit: effectivePaging.limit
|
|
2406
|
+
}, signal) : void 0
|
|
2407
|
+
};
|
|
2408
|
+
}
|
|
2409
|
+
/**
|
|
2410
|
+
* Filters documents by criteria over the Switchboard's `findDocuments` query.
|
|
2411
|
+
*
|
|
2412
|
+
* The query filters by `type` and `parentId` only, at head. A search naming
|
|
2413
|
+
* `ids` or `slugs` (present, whatever its length) and a point-in-time view are
|
|
2414
|
+
* each by-contract limitations the query cannot express -- running it anyway
|
|
2415
|
+
* would return every document instead of the named ones, or head instead of
|
|
2416
|
+
* the asked-for revision, a silently wrong answer. {@link findIsServableOverGraphQL}
|
|
2417
|
+
* is the single predicate that decides this, and an unservable `find` throws
|
|
2418
|
+
* {@link GraphQLOperationNotSupportedError}. Drive enumeration itself filters
|
|
2419
|
+
* by `type` at head, which is served.
|
|
2420
|
+
*/
|
|
2421
|
+
async find(search, view, paging, signal) {
|
|
2422
|
+
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");
|
|
2423
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2424
|
+
const effectivePaging = paging ?? defaultPaging;
|
|
2425
|
+
const result = await this.sdk.FindDocuments({
|
|
2426
|
+
search: {
|
|
2427
|
+
type: search.type,
|
|
2428
|
+
parentId: search.parentId
|
|
2429
|
+
},
|
|
2430
|
+
view: viewInput,
|
|
2431
|
+
paging: pagingInputFromPaging(effectivePaging)
|
|
2432
|
+
}, search.parentId === void 0 ? void 0 : this.driveIdHeaders({
|
|
2433
|
+
method: "find",
|
|
2434
|
+
parentId: search.parentId
|
|
2435
|
+
}), signal);
|
|
2436
|
+
return this.toDocumentResults(result.findDocuments, effectivePaging, view?.branch, (cursor, limit) => this.find(search, view, {
|
|
2437
|
+
cursor,
|
|
2438
|
+
limit
|
|
2439
|
+
}, signal));
|
|
2440
|
+
}
|
|
2441
|
+
async getOutgoingRelationships(sourceIdentifier, relationshipType, view, paging, signal) {
|
|
2442
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2443
|
+
const result = await this.sdk.GetDocumentOutgoingRelationships({
|
|
2444
|
+
sourceIdentifier,
|
|
2445
|
+
relationshipType,
|
|
2446
|
+
view: viewInput,
|
|
2447
|
+
paging: pagingInputFromPaging(paging)
|
|
2448
|
+
}, void 0, signal);
|
|
2449
|
+
return this.toDocumentResults(result.documentOutgoingRelationships, paging ?? defaultPaging, view?.branch, (cursor, limit) => this.getOutgoingRelationships(sourceIdentifier, relationshipType, view, {
|
|
2450
|
+
cursor,
|
|
2451
|
+
limit
|
|
2452
|
+
}, signal));
|
|
2453
|
+
}
|
|
2454
|
+
async getIncomingRelationships(targetIdentifier, relationshipType, view, paging, signal) {
|
|
2455
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2456
|
+
const result = await this.sdk.GetDocumentIncomingRelationships({
|
|
2457
|
+
targetIdentifier,
|
|
2458
|
+
relationshipType,
|
|
2459
|
+
view: viewInput,
|
|
2460
|
+
paging: pagingInputFromPaging(paging)
|
|
2461
|
+
}, void 0, signal);
|
|
2462
|
+
return this.toDocumentResults(result.documentIncomingRelationships, paging ?? defaultPaging, view?.branch, (cursor, limit) => this.getIncomingRelationships(targetIdentifier, relationshipType, view, {
|
|
2463
|
+
cursor,
|
|
2464
|
+
limit
|
|
2465
|
+
}, signal));
|
|
2466
|
+
}
|
|
2467
|
+
async getOutgoingRelationshipEdges(sourceIdentifier, relationshipType, view, paging, signal) {
|
|
2468
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2469
|
+
const result = await this.sdk.GetDocumentOutgoingRelationshipEdges({
|
|
2470
|
+
sourceIdentifier,
|
|
2471
|
+
relationshipType,
|
|
2472
|
+
view: viewInput,
|
|
2473
|
+
paging: pagingInputFromPaging(paging)
|
|
2474
|
+
}, void 0, signal);
|
|
2475
|
+
return this.toRelationshipResults(result.documentOutgoingRelationshipEdges, paging ?? defaultPaging, (cursor, limit) => this.getOutgoingRelationshipEdges(sourceIdentifier, relationshipType, view, {
|
|
2476
|
+
cursor,
|
|
2477
|
+
limit
|
|
2478
|
+
}, signal));
|
|
2479
|
+
}
|
|
2480
|
+
async getIncomingRelationshipEdges(targetIdentifier, relationshipType, view, paging, signal) {
|
|
2481
|
+
const viewInput = viewFilterInputFromViewFilter(view);
|
|
2482
|
+
const result = await this.sdk.GetDocumentIncomingRelationshipEdges({
|
|
2483
|
+
targetIdentifier,
|
|
2484
|
+
relationshipType,
|
|
2485
|
+
view: viewInput,
|
|
2486
|
+
paging: pagingInputFromPaging(paging)
|
|
2487
|
+
}, void 0, signal);
|
|
2488
|
+
return this.toRelationshipResults(result.documentIncomingRelationshipEdges, paging ?? defaultPaging, (cursor, limit) => this.getIncomingRelationshipEdges(targetIdentifier, relationshipType, view, {
|
|
2489
|
+
cursor,
|
|
2490
|
+
limit
|
|
2491
|
+
}, signal));
|
|
2492
|
+
}
|
|
2493
|
+
async create(document, parentIdentifier, signal) {
|
|
2494
|
+
const created = phDocumentFromGetDocument((await this.sdk.CreateDocument({
|
|
2495
|
+
document,
|
|
2496
|
+
parentIdentifier
|
|
2497
|
+
}, this.driveIdHeaders({
|
|
2498
|
+
method: "create",
|
|
2499
|
+
documentId: document.header.id || void 0,
|
|
2500
|
+
parentId: parentIdentifier
|
|
2501
|
+
}, isDrive(document) && parentIdentifier === void 0 ? document.header.id : void 0), signal)).createDocument);
|
|
2502
|
+
this.emitChange({
|
|
2503
|
+
type: DOCUMENT_CHANGE_TYPE.Created,
|
|
2504
|
+
documents: [created]
|
|
2505
|
+
});
|
|
2506
|
+
return created;
|
|
2507
|
+
}
|
|
2508
|
+
/**
|
|
2509
|
+
* Pushes actions to the Switchboard and returns the updated document.
|
|
2510
|
+
*
|
|
2511
|
+
* The document is fetched first: the response is the baseline for the
|
|
2512
|
+
* `sinceRevision` filter that narrows the returned operations to the ones
|
|
2513
|
+
* this call appended, and it carries the state hash a signed action is
|
|
2514
|
+
* stamped with.
|
|
2515
|
+
*
|
|
2516
|
+
* The emitted `Updated` event carries the document's id, never the
|
|
2517
|
+
* identifier this was called with: subscribers - including `DocumentCache` -
|
|
2518
|
+
* work in id space.
|
|
2519
|
+
*
|
|
2520
|
+
* `IReactorClient.execute`'s trailing `subject` is deliberately not accepted
|
|
2521
|
+
* here. It names the subject a local read gate answers as, and this client
|
|
2522
|
+
* runs no gate: the Switchboard decides what to serve from the bearer on the
|
|
2523
|
+
* request. Declaring it would suggest a per-call choice that does not exist.
|
|
2524
|
+
*/
|
|
2525
|
+
async execute(documentIdentifier, branch, actions, signal) {
|
|
2526
|
+
const document = await this.get(documentIdentifier, { branch }, signal);
|
|
2527
|
+
const variables = {
|
|
2528
|
+
documentIdentifier,
|
|
2529
|
+
actions: (await prepareActionsForPush(actions, document, this.documentModels(), this.resolveSigner(), signal)).map(toTransportAction),
|
|
2530
|
+
sinceRevision: sinceRevisionForActions(document, actions),
|
|
2531
|
+
scopes: scopesForActions(actions),
|
|
2532
|
+
branch
|
|
2533
|
+
};
|
|
2534
|
+
const mutated = (await this.sdk.RunDocument({
|
|
2535
|
+
operationName: "MutateDocumentWithOperations",
|
|
2536
|
+
operationType: "mutation",
|
|
2537
|
+
document: MutateDocumentWithOperationsDocument,
|
|
2538
|
+
variables,
|
|
2539
|
+
requestHeaders: this.driveIdHeaders({
|
|
2540
|
+
method: "execute",
|
|
2541
|
+
documentId: documentIdentifier
|
|
2542
|
+
}, isDrive(document) ? document.header.id : void 0),
|
|
2543
|
+
signal
|
|
2544
|
+
})).mutateDocument;
|
|
2545
|
+
const updated = phDocumentFromMutation(mutated, mutated.operations?.items ?? [], branch);
|
|
2546
|
+
this.emitChange({
|
|
2547
|
+
type: DOCUMENT_CHANGE_TYPE.Updated,
|
|
2548
|
+
documents: [updated]
|
|
2549
|
+
});
|
|
2550
|
+
return updated;
|
|
2551
|
+
}
|
|
2552
|
+
/**
|
|
2553
|
+
* What `execute` writes, without waiting: returns the job once the Switchboard
|
|
2554
|
+
* holds it, so a write slower than one request's deadline still lands and is
|
|
2555
|
+
* reported. It is announced as the write half's `execute` announces it.
|
|
2556
|
+
*/
|
|
2557
|
+
async executeAsync(documentIdentifier, branch, actions, signal) {
|
|
2558
|
+
return (await this.submitExecute(documentIdentifier, branch, actions, signal)).job;
|
|
2559
|
+
}
|
|
2560
|
+
/**
|
|
2561
|
+
* Undoes the last applied operation of `scope` under this client's own
|
|
2562
|
+
* signature: UNDO below base-reducer 3; on it, a RETRACT of the target the
|
|
2563
|
+
* Switchboard resolves with {@link undoRedoTargets}. One at a time per
|
|
2564
|
+
* document, scope and branch. A stale target is refused, not re-resolved.
|
|
2565
|
+
*/
|
|
2566
|
+
undo(documentIdentifier, scope = "global", branch = "main", signal) {
|
|
2567
|
+
return this.undoOrRedo("UNDO", documentIdentifier, scope, branch, signal);
|
|
2568
|
+
}
|
|
2569
|
+
/** Redoes the last undo of `scope`; see {@link undo}. */
|
|
2570
|
+
redo(documentIdentifier, scope = "global", branch = "main", signal) {
|
|
2571
|
+
return this.undoOrRedo("REDO", documentIdentifier, scope, branch, signal);
|
|
2572
|
+
}
|
|
2573
|
+
/** Exact on base-reducer 3, from the targets the Switchboard resolves. */
|
|
2574
|
+
async undoRedoAvailability(documentIdentifier, scope = "global", branch = "main", signal) {
|
|
2575
|
+
const { caps, document } = await this.undoCapabilities(documentIdentifier, branch, signal);
|
|
2576
|
+
const targets = undoNeedsTargets(caps) ? await this.undoRedoTargets(documentIdentifier, scope, { branch }, signal) : void 0;
|
|
2577
|
+
return undoRedoAvailabilityOf(caps, targets, document.header.revision[scope] ?? 0, scope in document.state);
|
|
2578
|
+
}
|
|
2579
|
+
/**
|
|
2580
|
+
* The rows a base-reducer 3 undo and redo would retract, resolved by the
|
|
2581
|
+
* Switchboard as the caller. A Switchboard without the query is refused
|
|
2582
|
+
* with {@link GraphQLOperationNotSupportedError}. `view.subject` is not
|
|
2583
|
+
* sent: the Switchboard reads the caller from the bearer.
|
|
2584
|
+
*/
|
|
2585
|
+
async undoRedoTargets(documentIdentifier, scope = "global", view, signal) {
|
|
2586
|
+
try {
|
|
2587
|
+
const { undoRedoTargets } = await this.sdk.GetUndoRedoTargets({
|
|
2588
|
+
documentIdOrSlug: documentIdentifier,
|
|
2589
|
+
scope,
|
|
2590
|
+
branch: view?.branch
|
|
2591
|
+
}, void 0, signal);
|
|
2592
|
+
return {
|
|
2593
|
+
...undoRedoTargets.undoTarget ? { undoTarget: undoRedoTargets.undoTarget } : {},
|
|
2594
|
+
...undoRedoTargets.redoTarget ? { redoTarget: undoRedoTargets.redoTarget } : {}
|
|
2595
|
+
};
|
|
2596
|
+
} catch (error) {
|
|
2597
|
+
if (queriesUnknownField(error, "undoRedoTargets")) throw new GraphQLOperationNotSupportedError("undoRedoTargets", "the Switchboard predates the undoRedoTargets query");
|
|
2598
|
+
throw error;
|
|
2599
|
+
}
|
|
2600
|
+
}
|
|
2601
|
+
undoOrRedo(type, documentIdentifier, scope, branch, signal) {
|
|
2602
|
+
return serializeByKey(this.undoRedoChains, JSON.stringify([
|
|
2603
|
+
documentIdentifier,
|
|
2604
|
+
scope,
|
|
2605
|
+
branch
|
|
2606
|
+
]), async () => {
|
|
2607
|
+
const { caps } = await this.undoCapabilities(documentIdentifier, branch, signal);
|
|
2608
|
+
const targets = undoNeedsTargets(caps) ? await this.undoRedoTargets(documentIdentifier, scope, { branch }, signal) : void 0;
|
|
2609
|
+
return this.execute(documentIdentifier, branch, undoRedoActions(caps, type, scope, targets), signal);
|
|
2610
|
+
}, signal);
|
|
2611
|
+
}
|
|
2612
|
+
/** An older Switchboard serves no header versions; then CREATE_DOCUMENT names them, else it is 1. */
|
|
2613
|
+
async undoCapabilities(documentIdentifier, branch, signal) {
|
|
2614
|
+
const document = await this.get(documentIdentifier, { branch }, signal);
|
|
2615
|
+
const { header } = document;
|
|
2616
|
+
const fromHeader = undoCapabilitiesOf(header);
|
|
2617
|
+
if (fromHeader) return {
|
|
2618
|
+
caps: fromHeader,
|
|
2619
|
+
document
|
|
2620
|
+
};
|
|
2621
|
+
const create = (await this.getOperations(documentIdentifier, {
|
|
2622
|
+
branch,
|
|
2623
|
+
scopes: ["document"]
|
|
2624
|
+
}, void 0, {
|
|
2625
|
+
cursor: "0",
|
|
2626
|
+
limit: 1
|
|
2627
|
+
}, signal)).results.at(0)?.action;
|
|
2628
|
+
const input = create?.type === "CREATE_DOCUMENT" ? create.input : void 0;
|
|
2629
|
+
return {
|
|
2630
|
+
caps: undoCapabilitiesOf(header, input) ?? capabilitiesOf(1),
|
|
2631
|
+
document
|
|
2632
|
+
};
|
|
2633
|
+
}
|
|
2634
|
+
/**
|
|
2635
|
+
* Runs multiple mutation jobs in dependency order over the Switchboard's
|
|
2636
|
+
* `executeBatch` mutation and waits for all to settle, returning the result
|
|
2637
|
+
* shaped like `IReactor.executeBatch`'s so the reference `DriveClient`
|
|
2638
|
+
* consumes it unchanged.
|
|
2639
|
+
*
|
|
2640
|
+
* Not atomic: each job commits on its own and a failed job still releases
|
|
2641
|
+
* its dependents. A FAILED job throws {@link BatchJobFailedError}, naming the
|
|
2642
|
+
* first failed plan key and carrying every job's final state.
|
|
2643
|
+
*
|
|
2644
|
+
* Each job's actions are signed independently for the job's own
|
|
2645
|
+
* `(documentId, branch)` target -- the per-action signing the reactor's own
|
|
2646
|
+
* `signActions` does, not the batch state-prediction `execute` uses for a
|
|
2647
|
+
* multi-action push. A drive job such as `addFile`'s is `CREATE_DOCUMENT` +
|
|
2648
|
+
* `UPGRADE_DOCUMENT` + `ADD_RELATIONSHIP`, which the prediction path rejects
|
|
2649
|
+
* outright and which has no fetchable baseline to stamp against. The reactor
|
|
2650
|
+
* records but does not verify the stamped previous-state head, so signing
|
|
2651
|
+
* each action bare is exactly what the in-process `DriveClient` relies on.
|
|
2652
|
+
*
|
|
2653
|
+
* The mutation is synchronous server-side: a job it returns is already
|
|
2654
|
+
* settled, so {@link waitForJob} resolves from it without polling.
|
|
2655
|
+
*/
|
|
2656
|
+
async executeBatch(request, signal) {
|
|
2657
|
+
const signer = this.resolveSigner();
|
|
2658
|
+
const jobInputs = await Promise.all(request.jobs.map(async (job, index) => {
|
|
2659
|
+
const documentId = await this.batchWriteTarget(job, request.jobs.slice(0, index), signer, signal);
|
|
2660
|
+
const actions = await this.signBatchJobActions({
|
|
2661
|
+
...job,
|
|
2662
|
+
documentId
|
|
2663
|
+
}, signer, signal);
|
|
2664
|
+
return {
|
|
2665
|
+
key: job.key,
|
|
2666
|
+
documentIdOrSlug: documentId,
|
|
2667
|
+
scope: job.scope,
|
|
2668
|
+
branch: job.branch,
|
|
2669
|
+
actions: actions.map(toTransportAction),
|
|
2670
|
+
dependsOn: job.dependsOn
|
|
2671
|
+
};
|
|
2672
|
+
}));
|
|
2673
|
+
const result = await this.batchSdk.ExecuteBatch({ jobs: jobInputs }, this.driveIdHeaders({
|
|
2674
|
+
method: "executeBatch",
|
|
2675
|
+
jobs: jobInputs.map((job) => ({ documentId: job.documentIdOrSlug }))
|
|
2676
|
+
}), signal);
|
|
2677
|
+
const jobs = {};
|
|
2678
|
+
for (const entry of result.executeBatch.jobs) jobs[entry.key] = jobInfoFromGql(entry.job);
|
|
2679
|
+
await this.announceBatch(request, jobs, signal);
|
|
2680
|
+
const failed = request.jobs.find((job) => jobs[job.key]?.status === "FAILED");
|
|
2681
|
+
if (failed) throw new BatchJobFailedError(failed.key, jobs);
|
|
2682
|
+
return { jobs };
|
|
2683
|
+
}
|
|
2684
|
+
/** The job as `jobStatus` reports it now; `undefined` when it reports none. */
|
|
2685
|
+
async getJob(jobId, signal) {
|
|
2686
|
+
const result = await this.sdk.GetJobStatus({ jobId }, void 0, signal);
|
|
2687
|
+
return result.jobStatus ? jobInfoFromGql(result.jobStatus) : void 0;
|
|
2688
|
+
}
|
|
2689
|
+
/** The job as `jobStatus` reports it now; throws when it reports none. */
|
|
2690
|
+
async getJobStatus(jobId, signal) {
|
|
2691
|
+
const job = await this.getJob(jobId, signal);
|
|
2692
|
+
if (!job) throw new Error(`Job not found: ${jobId}`);
|
|
2693
|
+
return job;
|
|
2694
|
+
}
|
|
2695
|
+
/** Polls `jobStatus` until the job is READ_READY or FAILED. */
|
|
2696
|
+
async waitForJob(jobOrId, signal) {
|
|
2697
|
+
if (typeof jobOrId !== "string" && isSettled(jobOrId)) return jobOrId;
|
|
2698
|
+
const jobId = typeof jobOrId === "string" ? jobOrId : jobOrId.id;
|
|
2699
|
+
for (;;) {
|
|
2700
|
+
const result = await this.sdk.GetJobStatus({ jobId }, void 0, signal);
|
|
2701
|
+
if (!result.jobStatus) throw new Error(`Job not found: ${jobId}`);
|
|
2702
|
+
const job = jobInfoFromGql(result.jobStatus);
|
|
2703
|
+
if (isSettled(job)) return job;
|
|
2704
|
+
await delay(JOB_POLL_INTERVAL_MS, signal);
|
|
2705
|
+
}
|
|
2706
|
+
}
|
|
2707
|
+
/** See {@link readCreateSignaturePolicy}. */
|
|
2708
|
+
getCreateSignaturePolicy() {
|
|
2709
|
+
return readCreateSignaturePolicy(this.sdk);
|
|
2710
|
+
}
|
|
2711
|
+
/** See {@link readCreateProtocolVersions}; fitted to `documentModels`. */
|
|
2712
|
+
getCreateProtocolVersions(options, signal) {
|
|
2713
|
+
return readCreateProtocolVersions(this.sdk, options, this.documentModels(), signal);
|
|
2714
|
+
}
|
|
2715
|
+
/** See {@link IReactorClient.newDocument}; the module comes from `documentModels`. */
|
|
2716
|
+
async newDocument(documentType, options, signal) {
|
|
2717
|
+
const module = selectDocumentModelModule([...this.documentModels(), ...BUILT_IN_MODELS], documentType, options?.documentModelVersion);
|
|
2718
|
+
const [policy, versions] = await Promise.all([options?.signaturePolicy ?? this.getCreateSignaturePolicy(), this.getCreateProtocolVersions({
|
|
2719
|
+
documentType,
|
|
2720
|
+
parentIdentifier: options?.parentIdentifier
|
|
2721
|
+
}, signal)]);
|
|
2722
|
+
return headNewDocument(module, options, policy, versions);
|
|
2723
|
+
}
|
|
2724
|
+
/**
|
|
2725
|
+
* Sets or, with `null`, clears the preferred editor as a client-signed
|
|
2726
|
+
* action, as the in-process client does.
|
|
2727
|
+
*/
|
|
2728
|
+
setPreferredEditor(documentIdentifier, preferredEditor, branch = "main", signal) {
|
|
2729
|
+
return this.execute(documentIdentifier, branch, [actions.setPreferredEditor(preferredEditor)], signal);
|
|
2730
|
+
}
|
|
2731
|
+
/** The `Drive-Id` header for a call: the client's own proof, else the hook's. */
|
|
2732
|
+
driveIdHeaders(call, proven) {
|
|
2733
|
+
const hinted = this.driveIdFor?.(call);
|
|
2734
|
+
if (proven) {
|
|
2735
|
+
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);
|
|
2736
|
+
return driveIdHeaders(proven);
|
|
2737
|
+
}
|
|
2738
|
+
return hinted ? driveIdHeaders(hinted) : void 0;
|
|
2739
|
+
}
|
|
2740
|
+
/**
|
|
2741
|
+
* Emits the changes the batch's settled jobs made, as `create` and `execute`
|
|
2742
|
+
* do, so a cache is invalidated without a realtime socket. The documents a
|
|
2743
|
+
* job wrote to are its own and those its consistency token names.
|
|
2744
|
+
*/
|
|
2745
|
+
async announceBatch(request, jobs, signal) {
|
|
2746
|
+
if (this.listeners.length === 0) return;
|
|
2747
|
+
const deleted = /* @__PURE__ */ new Set();
|
|
2748
|
+
const created = /* @__PURE__ */ new Map();
|
|
2749
|
+
const touched = /* @__PURE__ */ new Map();
|
|
2750
|
+
const keyOf = (written) => `${written.branch}\u0000${written.documentId}`;
|
|
2751
|
+
for (const job of request.jobs) {
|
|
2752
|
+
const info = jobs[job.key];
|
|
2753
|
+
if (!info || info.status !== "READ_READY") continue;
|
|
2754
|
+
const types = new Set(job.actions.map((action) => action.type));
|
|
2755
|
+
if (types.has("DELETE_DOCUMENT")) {
|
|
2756
|
+
deleted.add(info.documentId);
|
|
2757
|
+
continue;
|
|
2758
|
+
}
|
|
2759
|
+
const own = {
|
|
2760
|
+
documentId: info.documentId,
|
|
2761
|
+
branch: job.branch
|
|
2762
|
+
};
|
|
2763
|
+
if (types.has("CREATE_DOCUMENT")) created.set(keyOf(own), own);
|
|
2764
|
+
touched.set(keyOf(own), own);
|
|
2765
|
+
for (const { documentId, branch } of info.consistencyToken.coordinates) touched.set(keyOf({
|
|
2766
|
+
documentId,
|
|
2767
|
+
branch
|
|
2768
|
+
}), {
|
|
2769
|
+
documentId,
|
|
2770
|
+
branch
|
|
2771
|
+
});
|
|
2772
|
+
}
|
|
2773
|
+
for (const documentId of deleted) this.emitChange({
|
|
2774
|
+
type: DOCUMENT_CHANGE_TYPE.Deleted,
|
|
2775
|
+
documents: [],
|
|
2776
|
+
context: { childId: documentId }
|
|
2777
|
+
});
|
|
2778
|
+
const read = async ({ documentId, branch }) => {
|
|
2779
|
+
try {
|
|
2780
|
+
return await this.get(documentId, { branch }, signal);
|
|
2781
|
+
} catch (error) {
|
|
2782
|
+
logger.warn("GraphQLReactorClient: could not read @documentId on @branch to announce a batch change: @error", documentId, branch, error);
|
|
2783
|
+
return;
|
|
2784
|
+
}
|
|
2785
|
+
};
|
|
2786
|
+
const readAll = async (written) => (await Promise.all(written.map(read))).filter((document) => document !== void 0);
|
|
2787
|
+
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))]);
|
|
2788
|
+
if (createdDocuments.length > 0) this.emitChange({
|
|
2789
|
+
type: DOCUMENT_CHANGE_TYPE.Created,
|
|
2790
|
+
documents: createdDocuments
|
|
2791
|
+
});
|
|
2792
|
+
if (updatedDocuments.length > 0) this.emitChange({
|
|
2793
|
+
type: DOCUMENT_CHANGE_TYPE.Updated,
|
|
2794
|
+
documents: updatedDocuments
|
|
2795
|
+
});
|
|
2796
|
+
}
|
|
2797
|
+
/**
|
|
2798
|
+
* The id a job's actions are signed for: a signature covers the document id,
|
|
2799
|
+
* and the server resolves a slug before verifying. A document created by this
|
|
2800
|
+
* job or an earlier one is named by its id. When the server has no such
|
|
2801
|
+
* document the identifier is used as given, and the server decides; any
|
|
2802
|
+
* other failure to read it throws, so nothing is signed for a slug.
|
|
2803
|
+
*/
|
|
2804
|
+
async batchWriteTarget(job, earlier, signer, signal) {
|
|
2805
|
+
const creates = (plan) => plan.documentId === job.documentId && plan.actions.some((action) => action.type === "CREATE_DOCUMENT");
|
|
2806
|
+
if (!signer || job.actions.every(isActionSigned) || creates(job) || earlier.some(creates)) return job.documentId;
|
|
2807
|
+
return (await this.sdk.GetDocument({
|
|
2808
|
+
identifier: job.documentId,
|
|
2809
|
+
view: viewFilterInputFromViewFilter({ branch: job.branch })
|
|
2810
|
+
}, void 0, signal)).document?.document.id ?? job.documentId;
|
|
2811
|
+
}
|
|
2812
|
+
/**
|
|
2813
|
+
* Signs one batch job's actions for the job's own log.
|
|
2814
|
+
*
|
|
2815
|
+
* Each action is signed on its own for `(documentId, branch)`, the same
|
|
2816
|
+
* per-action signing the reactor's `signActions` does: no state prediction
|
|
2817
|
+
* across the job, so a job carrying a `CREATE_DOCUMENT` the push-prediction
|
|
2818
|
+
* path rejects still signs. An action already signed under a key is left
|
|
2819
|
+
* as it is: the reference `DriveClient` signs its jobs before handing them
|
|
2820
|
+
* here. With no signer the actions pass through unsigned, matching
|
|
2821
|
+
* {@link execute}.
|
|
2822
|
+
*/
|
|
2823
|
+
async signBatchJobActions(job, signer, signal) {
|
|
2824
|
+
if (!signer) return job.actions;
|
|
2825
|
+
return Promise.all(job.actions.map((action) => isActionSigned(action) ? Promise.resolve(action) : signStampedAction(action, signer, actionSigningTarget(action, job.documentId, job.branch), signal)));
|
|
2826
|
+
}
|
|
2827
|
+
/**
|
|
2828
|
+
* Deletes a document and announces it as a `Deleted` event.
|
|
2829
|
+
*
|
|
2830
|
+
* Pass a document id. The server resolves a slug just as happily, but
|
|
2831
|
+
* `deleteDocument` returns a boolean - there is no document left to read an
|
|
2832
|
+
* id off - so the identifier is announced verbatim on `context.childId`. A
|
|
2833
|
+
* subscriber keyed by id, `DocumentCache` included, therefore only reacts to
|
|
2834
|
+
* a delete by id.
|
|
2835
|
+
*/
|
|
2836
|
+
async deleteDocument(identifier, propagate, signal) {
|
|
2837
|
+
await this.sdk.DeleteDocument({
|
|
2838
|
+
identifier,
|
|
2839
|
+
propagate: propagationModeInput(propagate)
|
|
2840
|
+
}, this.driveIdHeaders({
|
|
2841
|
+
method: "deleteDocument",
|
|
2842
|
+
documentId: identifier
|
|
2843
|
+
}), signal);
|
|
2844
|
+
this.emitChange({
|
|
2845
|
+
type: DOCUMENT_CHANGE_TYPE.Deleted,
|
|
2846
|
+
documents: [],
|
|
2847
|
+
context: { childId: identifier }
|
|
2848
|
+
});
|
|
2849
|
+
}
|
|
2850
|
+
/**
|
|
2851
|
+
* Registers a change subscriber and returns its unsubscribe function.
|
|
2852
|
+
*
|
|
2853
|
+
* Two things produce the events delivered here. Every successful `create`,
|
|
2854
|
+
* `execute` and `deleteDocument` emits one, which is what makes a
|
|
2855
|
+
* `DocumentCache` built on this client invalidate after a dispatch. And,
|
|
2856
|
+
* unless realtime is switched off, the first call to this method opens a
|
|
2857
|
+
* websocket to the Switchboard and every change it reports - from another
|
|
2858
|
+
* user, another tab or a server-side processor - is emitted too. A write of
|
|
2859
|
+
* this client's own is therefore announced twice, once locally and once by
|
|
2860
|
+
* the server; the cache refetches twice, which is harmless.
|
|
2861
|
+
*
|
|
2862
|
+
* A websocket that cannot be opened or is refused is logged once and then
|
|
2863
|
+
* ignored: realtime is an enhancement, never a dependency. The failed socket
|
|
2864
|
+
* is closed, so the next subscriber to arrive tries again.
|
|
2865
|
+
*
|
|
2866
|
+
* `view` is accepted for interface compatibility and ignored: the emitted
|
|
2867
|
+
* documents are whatever the write returned, so there is nothing to re-scope.
|
|
2868
|
+
*
|
|
2869
|
+
* Events live in id space: `search.ids` is matched against the resolved
|
|
2870
|
+
* document id, never against the identifier the write was issued with. The
|
|
2871
|
+
* one exception is `deleteDocument`, which has no document to resolve an id
|
|
2872
|
+
* from - see its own note. A `DocumentCache` on this client must therefore
|
|
2873
|
+
* be read by id: a slug-keyed entry is never invalidated.
|
|
2874
|
+
*/
|
|
2875
|
+
subscribe(search, callback, view) {
|
|
2876
|
+
const listener = {
|
|
2877
|
+
search,
|
|
2878
|
+
callback
|
|
2879
|
+
};
|
|
2880
|
+
this.listeners.push(listener);
|
|
2881
|
+
this.startRealtime();
|
|
2882
|
+
return () => {
|
|
2883
|
+
const index = this.listeners.indexOf(listener);
|
|
2884
|
+
if (index !== -1) this.listeners.splice(index, 1);
|
|
2885
|
+
};
|
|
2886
|
+
}
|
|
2887
|
+
/**
|
|
2888
|
+
* Closes the realtime socket, if one was opened.
|
|
2889
|
+
*
|
|
2890
|
+
* Registered subscribers are left in place: they still receive the events
|
|
2891
|
+
* this client produces itself.
|
|
2892
|
+
*
|
|
2893
|
+
* Disposing is NOT final - a later `subscribe` opens a new socket. React
|
|
2894
|
+
* remounts a tree by running an effect's cleanup and then the effect again,
|
|
2895
|
+
* on the same client, and `StrictMode` does exactly that on every mount; a
|
|
2896
|
+
* terminal flag here would leave those pages without realtime for good, with
|
|
2897
|
+
* nothing logged.
|
|
2898
|
+
*/
|
|
2899
|
+
dispose() {
|
|
2900
|
+
this.teardownRealtime();
|
|
2901
|
+
this.jobSocket?.dispose();
|
|
2902
|
+
this.jobSocket = void 0;
|
|
2903
|
+
}
|
|
2904
|
+
/**
|
|
2905
|
+
* Binds a project's generated SDK to this client's transport and auth.
|
|
2906
|
+
*
|
|
2907
|
+
* Subgraphs are served next to the reactor's own supergraph, so the endpoint
|
|
2908
|
+
* is derived from the client's `url` by appending the name, and the SDK is
|
|
2909
|
+
* handed the same auth middleware every reactor call goes through. An app
|
|
2910
|
+
* therefore configures one URL and one token provider, and reaches every
|
|
2911
|
+
* capability of its Switchboard through this one client.
|
|
2912
|
+
*
|
|
2913
|
+
* `getSdk` is the function a GraphQL code generator emits for the subgraph's
|
|
2914
|
+
* schema - see the README in this folder for the codegen recipe.
|
|
2915
|
+
*
|
|
2916
|
+
* Transport and typing only. Subgraph results are not cached, produce no
|
|
2917
|
+
* change events and never reach `useDocument`.
|
|
2918
|
+
*/
|
|
2919
|
+
subgraph(name, getSdk) {
|
|
2920
|
+
return this.subgraphs.get(name, getSdk);
|
|
2921
|
+
}
|
|
2922
|
+
/**
|
|
2923
|
+
* Runs a one-off GraphQL document against the Switchboard's own endpoint,
|
|
2924
|
+
* through the same transport and auth as everything else.
|
|
2925
|
+
*
|
|
2926
|
+
* The escape hatch for an operation not worth generating an SDK for. Pass a
|
|
2927
|
+
* document a code generator typed and the result type follows; pass a plain
|
|
2928
|
+
* `gql` document or a string and name the result type at the call site.
|
|
2929
|
+
*/
|
|
2930
|
+
async request(document, variables, options) {
|
|
2931
|
+
const described = describeGraphQLDocument(document);
|
|
2932
|
+
return this.sdk.RunDocument({
|
|
2933
|
+
operationName: options?.operationName ?? described.operationName,
|
|
2934
|
+
operationType: options?.operationType ?? described.operationType,
|
|
2935
|
+
document,
|
|
2936
|
+
variables,
|
|
2937
|
+
signal: options?.signal
|
|
2938
|
+
});
|
|
2939
|
+
}
|
|
2940
|
+
/**
|
|
2941
|
+
* Shapes a document result page into the reactor's {@link PagedResults}.
|
|
2942
|
+
*
|
|
2943
|
+
* The items carry the same `PHDocumentFields` fragment as `get`, so the same
|
|
2944
|
+
* adapter rebuilds each one. `hasNextPage` gates the cursor exactly as
|
|
2945
|
+
* `getOperations` does: no cursor means no `next`.
|
|
2946
|
+
*/
|
|
2947
|
+
toDocumentResults(page, effectivePaging, branch, next) {
|
|
2948
|
+
const nextCursor = page.hasNextPage ? page.cursor ?? void 0 : void 0;
|
|
2949
|
+
return {
|
|
2950
|
+
results: page.items.map((item) => phDocumentFromGetDocument(item, branch)),
|
|
2951
|
+
options: effectivePaging,
|
|
2952
|
+
nextCursor,
|
|
2953
|
+
next: nextCursor ? () => next(nextCursor, effectivePaging.limit) : void 0
|
|
2954
|
+
};
|
|
2955
|
+
}
|
|
2956
|
+
/**
|
|
2957
|
+
* Shapes a relationship-edge result page into the reactor's
|
|
2958
|
+
* {@link PagedResults}, restoring each edge's `Date` fields.
|
|
2959
|
+
*/
|
|
2960
|
+
toRelationshipResults(page, effectivePaging, next) {
|
|
2961
|
+
const nextCursor = page.hasNextPage ? page.cursor ?? void 0 : void 0;
|
|
2962
|
+
return {
|
|
2963
|
+
results: page.items.map((edge) => documentRelationshipFromEdge(edge)),
|
|
2964
|
+
options: effectivePaging,
|
|
2965
|
+
nextCursor,
|
|
2966
|
+
next: nextCursor ? () => next(nextCursor, effectivePaging.limit) : void 0
|
|
2967
|
+
};
|
|
2968
|
+
}
|
|
2969
|
+
/**
|
|
2970
|
+
* The write half's `execute`: signs as the facade's `execute` does, submits
|
|
2971
|
+
* through `executeAsync` and returns once the job is accepted. When anyone
|
|
2972
|
+
* subscribes, the document is read back once the job is readable and
|
|
2973
|
+
* announced as `Updated`, as the facade's `execute` announces it; the handle
|
|
2974
|
+
* shares that read with its own `document()`.
|
|
2975
|
+
*/
|
|
2976
|
+
async submitExecute(documentIdentifier, branch, actions, signal) {
|
|
2977
|
+
const document = await this.get(documentIdentifier, { branch }, signal);
|
|
2978
|
+
const preparedActions = await prepareActionsForPush(actions, document, this.documentModels(), this.resolveSigner(), signal);
|
|
2979
|
+
const handle = new GraphQLJobWriteHandle(jobInfoFromGql((await this.sdk.MutateDocumentAsync({
|
|
2980
|
+
documentIdentifier,
|
|
2981
|
+
actions: preparedActions.map(toTransportAction),
|
|
2982
|
+
branch
|
|
2983
|
+
}, this.driveIdHeaders({
|
|
2984
|
+
method: "execute",
|
|
2985
|
+
documentId: documentIdentifier
|
|
2986
|
+
}, 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);
|
|
2987
|
+
if (this.listeners.length > 0) this.announceWrite(handle);
|
|
2988
|
+
return handle;
|
|
2989
|
+
}
|
|
2990
|
+
/** The write half's `create`: the synchronous mutation, a settled handle. */
|
|
2991
|
+
async submitCreate(document, parentIdentifier, signal) {
|
|
2992
|
+
const created = await this.create(document, parentIdentifier, signal);
|
|
2993
|
+
return new GraphQLSettledWriteHandle(created.header.id, created.header.branch || "main", this.handleReader(created.header.id));
|
|
2994
|
+
}
|
|
2995
|
+
/** The write half's `deleteDocument`: the synchronous mutation, a settled handle. */
|
|
2996
|
+
async submitDeleteDocument(identifier, propagate, signal) {
|
|
2997
|
+
await this.deleteDocument(identifier, propagate, signal);
|
|
2998
|
+
return new GraphQLSettledWriteHandle(identifier, "main", this.handleReader(identifier));
|
|
2999
|
+
}
|
|
3000
|
+
/** Reads a write's document back, bounded by its receipt's token. */
|
|
3001
|
+
handleReader(documentId) {
|
|
3002
|
+
return (receipt, view, signal) => this.get(documentId, {
|
|
3003
|
+
...view,
|
|
3004
|
+
branch: receipt.branch
|
|
3005
|
+
}, signal, receipt.token);
|
|
3006
|
+
}
|
|
3007
|
+
/** Announces a write's document as `Updated` once it is readable. */
|
|
3008
|
+
async announceWrite(handle) {
|
|
3009
|
+
let document;
|
|
3010
|
+
try {
|
|
3011
|
+
document = await handle.document();
|
|
3012
|
+
} catch (error) {
|
|
3013
|
+
logger.warn("GraphQLReactorClient: could not read @documentId back to announce a write: @error", handle.documentId, error);
|
|
3014
|
+
return;
|
|
3015
|
+
}
|
|
3016
|
+
this.emitChange({
|
|
3017
|
+
type: DOCUMENT_CHANGE_TYPE.Updated,
|
|
3018
|
+
documents: [document]
|
|
3019
|
+
});
|
|
3020
|
+
}
|
|
3021
|
+
/**
|
|
3022
|
+
* Waits for a job to settle a stage, resolving with a FAILED job too. Polls
|
|
3023
|
+
* `jobStatus` with a doubling interval; with realtime on, a `jobChanges`
|
|
3024
|
+
* event for the job wakes the wait early and the interval is only a safety
|
|
3025
|
+
* net. A failed subscription is logged once and the wait keeps polling.
|
|
3026
|
+
*/
|
|
3027
|
+
async waitForStage(jobId, stage, signal) {
|
|
3028
|
+
const wakers = /* @__PURE__ */ new Set();
|
|
3029
|
+
const stopWatching = this.watchJob(jobId, () => {
|
|
3030
|
+
for (const wake of [...wakers]) wake();
|
|
3031
|
+
});
|
|
3032
|
+
try {
|
|
3033
|
+
let interval = STAGE_POLL_START_MS;
|
|
3034
|
+
for (;;) {
|
|
3035
|
+
const job = await this.getJobStatus(jobId, signal);
|
|
3036
|
+
if (settlesGraphQLJobStage(job.status, stage)) return job;
|
|
3037
|
+
await sleepUntilWoken(interval, wakers, signal);
|
|
3038
|
+
const max = stopWatching && !this.jobRealtimeBroken ? STAGE_POLL_REALTIME_MAX_MS : JOB_POLL_INTERVAL_MS;
|
|
3039
|
+
interval = Math.min(interval * 2, max);
|
|
3040
|
+
}
|
|
3041
|
+
} finally {
|
|
3042
|
+
stopWatching?.();
|
|
3043
|
+
}
|
|
3044
|
+
}
|
|
3045
|
+
/**
|
|
3046
|
+
* Subscribes to one job's `jobChanges` when realtime is on and the
|
|
3047
|
+
* subscription has not failed before. Returns the stop function, or
|
|
3048
|
+
* undefined when nothing was subscribed.
|
|
3049
|
+
*/
|
|
3050
|
+
watchJob(jobId, onChange) {
|
|
3051
|
+
if (!this.subscriptionsUrl || this.jobRealtimeBroken) return;
|
|
3052
|
+
this.jobSocket ??= createJobChangesSocket({
|
|
3053
|
+
wsUrl: this.subscriptionsUrl,
|
|
3054
|
+
connectionParams: makeAuthConnectionParams(this.tokenProvider)
|
|
3055
|
+
});
|
|
3056
|
+
return this.jobSocket.watch(jobId, () => onChange(), (error) => {
|
|
3057
|
+
if (this.jobRealtimeBroken) return;
|
|
3058
|
+
this.jobRealtimeBroken = true;
|
|
3059
|
+
logger.warn("GraphQLReactorClient: realtime job changes are unavailable, write handles fall back to polling jobStatus", error);
|
|
3060
|
+
});
|
|
3061
|
+
}
|
|
3062
|
+
/**
|
|
3063
|
+
* The `document` query with the `consistency` argument, or without it once
|
|
3064
|
+
* the Switchboard has refused the argument.
|
|
3065
|
+
*/
|
|
3066
|
+
async getDocumentAtConsistency(identifier, view, token, signal) {
|
|
3067
|
+
if (!this.consistencyUnsupported) {
|
|
3068
|
+
const variables = {
|
|
3069
|
+
identifier,
|
|
3070
|
+
view,
|
|
3071
|
+
consistency: consistencyInputFromToken(token)
|
|
3072
|
+
};
|
|
3073
|
+
try {
|
|
3074
|
+
return await this.sdk.RunDocument({
|
|
3075
|
+
operationName: "GetDocumentAtConsistency",
|
|
3076
|
+
operationType: "query",
|
|
3077
|
+
document: GetDocumentAtConsistencyDocument,
|
|
3078
|
+
variables,
|
|
3079
|
+
signal
|
|
3080
|
+
});
|
|
3081
|
+
} catch (error) {
|
|
3082
|
+
if (!refusesConsistencyArgument(error)) throw error;
|
|
3083
|
+
this.consistencyUnsupported = true;
|
|
3084
|
+
}
|
|
3085
|
+
}
|
|
3086
|
+
return this.sdk.GetDocument({
|
|
3087
|
+
identifier,
|
|
3088
|
+
view
|
|
3089
|
+
}, void 0, signal);
|
|
3090
|
+
}
|
|
3091
|
+
/**
|
|
3092
|
+
* Opens the realtime socket on the first subscriber.
|
|
3093
|
+
*
|
|
3094
|
+
* The subscription is a firehose - no `search` argument - and this client
|
|
3095
|
+
* applies each subscriber's own filter on the way out, exactly as it does for
|
|
3096
|
+
* its own emissions.
|
|
3097
|
+
*/
|
|
3098
|
+
startRealtime() {
|
|
3099
|
+
if (!this.subscriptionsUrl || this.realtimeStarted) return;
|
|
3100
|
+
this.realtimeStarted = true;
|
|
3101
|
+
const generation = this.realtimeGeneration;
|
|
3102
|
+
const stop = startDocumentChangesSubscription({
|
|
3103
|
+
wsUrl: this.subscriptionsUrl,
|
|
3104
|
+
connectionParams: makeAuthConnectionParams(this.tokenProvider),
|
|
3105
|
+
onEvent: (event) => this.emitServerEvent(event),
|
|
3106
|
+
onError: (error) => this.handleRealtimeFailure(generation, error)
|
|
3107
|
+
});
|
|
3108
|
+
if (this.realtimeGeneration !== generation) {
|
|
3109
|
+
stop();
|
|
3110
|
+
return;
|
|
3111
|
+
}
|
|
3112
|
+
this.stopRealtime = stop;
|
|
3113
|
+
}
|
|
3114
|
+
/**
|
|
3115
|
+
* Gives up on a failed socket so that a later subscriber can try again.
|
|
3116
|
+
*
|
|
3117
|
+
* `graphql-ws` retries on its own and only reports here once it has given up,
|
|
3118
|
+
* or once the Switchboard refused the credentials the socket carried - which
|
|
3119
|
+
* `shouldRetry` declines to retry at all. Keeping the dead stop function
|
|
3120
|
+
* would make every later `subscribe` a no-op, so realtime would stay off for
|
|
3121
|
+
* the life of the page even after the user signs in.
|
|
3122
|
+
*
|
|
3123
|
+
* Why it died is recorded: a refusal is undone by a credential change and
|
|
3124
|
+
* nothing else, and {@link notifyCredentialsChanged} acts only on that.
|
|
3125
|
+
*
|
|
3126
|
+
* The generation stamp discards a report from a socket that has already been
|
|
3127
|
+
* replaced or disposed.
|
|
3128
|
+
*/
|
|
3129
|
+
handleRealtimeFailure(generation, error) {
|
|
3130
|
+
if (generation !== this.realtimeGeneration) return;
|
|
3131
|
+
this.teardownRealtime();
|
|
3132
|
+
this.realtimeRefusedCredentials = isAuthRefusalClose(error);
|
|
3133
|
+
this.logRealtimeError(error);
|
|
3134
|
+
}
|
|
3135
|
+
/**
|
|
3136
|
+
* Reopens realtime after a sign-in, a sign-out or a token swap.
|
|
3137
|
+
*
|
|
3138
|
+
* Call it whenever the credentials this client authenticates with change.
|
|
3139
|
+
*
|
|
3140
|
+
* A live socket is replaced. `connectionParams` are resolved once, when the
|
|
3141
|
+
* socket opens, so a socket keeps presenting the credentials it was opened
|
|
3142
|
+
* with until something closes it - and a sign-out closes nothing. That left
|
|
3143
|
+
* a signed-out tab still receiving the previous identity's document changes,
|
|
3144
|
+
* on a shared machine, for as long as the socket happened to survive.
|
|
3145
|
+
*
|
|
3146
|
+
* A refused socket is reopened, for the same reason from the other side:
|
|
3147
|
+
* otherwise it stays closed until an unrelated component happens to
|
|
3148
|
+
* `subscribe`, so signing in leaves realtime off with nothing said - the
|
|
3149
|
+
* state `handleRealtimeFailure` resets to avoid.
|
|
3150
|
+
*
|
|
3151
|
+
* A socket that died for any other reason is left alone: a network failure
|
|
3152
|
+
* is not something a new token fixes, and reopening one here would turn a
|
|
3153
|
+
* credential change into a reconnect loop.
|
|
3154
|
+
*/
|
|
3155
|
+
notifyCredentialsChanged() {
|
|
3156
|
+
if (!this.realtimeStarted && !this.realtimeRefusedCredentials) return;
|
|
3157
|
+
this.teardownRealtime();
|
|
3158
|
+
if (this.listeners.length === 0) return;
|
|
3159
|
+
this.startRealtime();
|
|
3160
|
+
}
|
|
3161
|
+
/** Closes the socket and lets a later subscriber open a new one. */
|
|
3162
|
+
teardownRealtime() {
|
|
3163
|
+
this.realtimeGeneration += 1;
|
|
3164
|
+
this.realtimeStarted = false;
|
|
3165
|
+
this.realtimeRefusedCredentials = false;
|
|
3166
|
+
this.stopRealtime?.();
|
|
3167
|
+
this.stopRealtime = void 0;
|
|
3168
|
+
}
|
|
3169
|
+
/** Maps a server event onto the client-side event and emits it. */
|
|
3170
|
+
emitServerEvent(event) {
|
|
3171
|
+
this.emitChange({
|
|
3172
|
+
type: documentChangeTypes[event.type],
|
|
3173
|
+
documents: event.documents.map((document) => phDocumentFromGetDocument(document)),
|
|
3174
|
+
context: event.context ? {
|
|
3175
|
+
parentId: event.context.parentId ?? void 0,
|
|
3176
|
+
childId: event.context.childId ?? void 0
|
|
3177
|
+
} : void 0
|
|
3178
|
+
});
|
|
3179
|
+
}
|
|
3180
|
+
/**
|
|
3181
|
+
* Reports a broken realtime socket once per client, however many sockets it
|
|
3182
|
+
* goes through.
|
|
3183
|
+
*
|
|
3184
|
+
* `graphql-ws` retries on its own, and a Switchboard without a websocket
|
|
3185
|
+
* endpoint would otherwise fill the console for as long as the page is open.
|
|
3186
|
+
*/
|
|
3187
|
+
logRealtimeError(error) {
|
|
3188
|
+
if (this.realtimeErrorLogged) return;
|
|
3189
|
+
this.realtimeErrorLogged = true;
|
|
3190
|
+
logger.warn("GraphQLReactorClient: realtime document changes are unavailable, falling back to local change events", error);
|
|
3191
|
+
}
|
|
3192
|
+
/**
|
|
3193
|
+
* Delivers an event to every matching subscriber.
|
|
3194
|
+
*
|
|
3195
|
+
* A subscriber that throws is logged and skipped so one bad listener cannot
|
|
3196
|
+
* stop the others from being notified.
|
|
3197
|
+
*/
|
|
3198
|
+
emitChange(event) {
|
|
3199
|
+
for (const listener of [...this.listeners]) {
|
|
3200
|
+
if (!eventMatchesSearch(event, listener.search)) continue;
|
|
3201
|
+
try {
|
|
3202
|
+
listener.callback(event);
|
|
3203
|
+
} catch (error) {
|
|
3204
|
+
logger.error("GraphQLReactorClient: a document change subscriber threw", error);
|
|
3205
|
+
}
|
|
3206
|
+
}
|
|
3207
|
+
}
|
|
3208
|
+
};
|
|
3209
|
+
/**
|
|
3210
|
+
* The read half of {@link GraphQLReactorClient}: every read is the client's
|
|
3211
|
+
* own, and nothing that writes is reachable from it.
|
|
3212
|
+
*/
|
|
3213
|
+
var GraphQLReadHalf = class {
|
|
3214
|
+
client;
|
|
3215
|
+
drives;
|
|
3216
|
+
constructor(client, nodes) {
|
|
3217
|
+
this.client = client;
|
|
3218
|
+
this.drives = new GraphQLDriveReadClient(nodes);
|
|
3219
|
+
}
|
|
3220
|
+
get(identifier, view, signal, consistencyToken) {
|
|
3221
|
+
return this.client.get(identifier, view, signal, consistencyToken);
|
|
3222
|
+
}
|
|
3223
|
+
getMany(documentIds, view, signal, consistencyToken) {
|
|
3224
|
+
return this.client.getMany(documentIds, view, signal, consistencyToken);
|
|
3225
|
+
}
|
|
3226
|
+
find(search, view, paging, signal) {
|
|
3227
|
+
return this.client.find(search, view, paging, signal);
|
|
3228
|
+
}
|
|
3229
|
+
getOperations(documentIdentifier, view, filter, paging, signal) {
|
|
3230
|
+
return this.client.getOperations(documentIdentifier, view, filter, paging, signal);
|
|
3231
|
+
}
|
|
3232
|
+
subscribe(search, callback, view) {
|
|
3233
|
+
return this.client.subscribe(search, callback, view);
|
|
3234
|
+
}
|
|
3235
|
+
waitForJob(jobId, signal) {
|
|
3236
|
+
return this.client.waitForJob(jobId, signal);
|
|
3237
|
+
}
|
|
3238
|
+
getJobStatus(jobId, signal) {
|
|
3239
|
+
return this.client.getJobStatus(jobId, signal);
|
|
3240
|
+
}
|
|
3241
|
+
};
|
|
3242
|
+
/**
|
|
3243
|
+
* Sleeps for `ms`, or less when a waker in `wakers` fires first. Each sleep
|
|
3244
|
+
* adds its own waker and removes it when it ends.
|
|
3245
|
+
*/
|
|
3246
|
+
function sleepUntilWoken(ms, wakers, signal) {
|
|
3247
|
+
return new Promise((resolve, reject) => {
|
|
3248
|
+
if (signal?.aborted) {
|
|
3249
|
+
reject(abortReason(signal));
|
|
3250
|
+
return;
|
|
3251
|
+
}
|
|
3252
|
+
const finish = () => {
|
|
3253
|
+
clearTimeout(timer);
|
|
3254
|
+
wakers.delete(finish);
|
|
3255
|
+
signal?.removeEventListener("abort", onAbort);
|
|
3256
|
+
};
|
|
3257
|
+
const wake = () => {
|
|
3258
|
+
finish();
|
|
3259
|
+
resolve();
|
|
3260
|
+
};
|
|
3261
|
+
const onAbort = () => {
|
|
3262
|
+
finish();
|
|
3263
|
+
if (signal) reject(abortReason(signal));
|
|
3264
|
+
};
|
|
3265
|
+
const timer = setTimeout(wake, ms);
|
|
3266
|
+
wakers.add(wake);
|
|
3267
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3268
|
+
});
|
|
3269
|
+
}
|
|
3270
|
+
/**
|
|
3271
|
+
* Whether a request failed because the Switchboard's `document` query has no
|
|
3272
|
+
* `consistency` argument, or its schema no `ConsistencyTokenInput`.
|
|
3273
|
+
*/
|
|
3274
|
+
/** The most ids one `getMany` request reads. */
|
|
3275
|
+
const GET_MANY_CHUNK_SIZE = 50;
|
|
3276
|
+
const PH_DOCUMENT_FIELDS_SOURCE = print(PhDocumentFieldsFragmentDoc);
|
|
3277
|
+
function consistencyInputFromToken(token) {
|
|
3278
|
+
return {
|
|
3279
|
+
version: token.version,
|
|
3280
|
+
createdAtUtcIso: token.createdAtUtcIso,
|
|
3281
|
+
coordinates: token.coordinates.map((coordinate) => ({
|
|
3282
|
+
documentId: coordinate.documentId,
|
|
3283
|
+
scope: coordinate.scope,
|
|
3284
|
+
branch: coordinate.branch,
|
|
3285
|
+
operationIndex: coordinate.operationIndex
|
|
3286
|
+
}))
|
|
3287
|
+
};
|
|
3288
|
+
}
|
|
3289
|
+
function refusesConsistencyArgument(error) {
|
|
3290
|
+
const errors = error?.response?.errors;
|
|
3291
|
+
if (!Array.isArray(errors)) return false;
|
|
3292
|
+
return errors.some((entry) => {
|
|
3293
|
+
const message = entry?.message;
|
|
3294
|
+
return typeof message === "string" && (message.includes("\"consistency\"") || message.includes("\"ConsistencyTokenInput\""));
|
|
3295
|
+
});
|
|
3296
|
+
}
|
|
3297
|
+
/** {@link GraphQLReactorClient.nodeSource}, as a function. */
|
|
3298
|
+
function createGraphQLDriveNodeSource(client) {
|
|
3299
|
+
return client.nodeSource();
|
|
3300
|
+
}
|
|
3301
|
+
/**
|
|
3302
|
+
* Whether a value is a {@link GraphQLReactorClient}, including one built by
|
|
3303
|
+
* another copy of this module.
|
|
3304
|
+
*
|
|
3305
|
+
* Use this rather than `instanceof`: the brand it tests for is shared by every
|
|
3306
|
+
* copy of the class, so a client built by a hot-replaced module or by a package
|
|
3307
|
+
* that bundled its own copy is still recognised.
|
|
3308
|
+
*/
|
|
3309
|
+
function isGraphQLReactorClient(client) {
|
|
3310
|
+
return client?.[graphQLReactorClientBrand] === true;
|
|
3311
|
+
}
|
|
3312
|
+
/** The schema's change types, mapped onto the reactor's. */
|
|
3313
|
+
const documentChangeTypes = {
|
|
3314
|
+
["CREATED"]: DOCUMENT_CHANGE_TYPE.Created,
|
|
3315
|
+
["DELETED"]: DOCUMENT_CHANGE_TYPE.Deleted,
|
|
3316
|
+
["UPDATED"]: DOCUMENT_CHANGE_TYPE.Updated,
|
|
3317
|
+
["PARENT_ADDED"]: DOCUMENT_CHANGE_TYPE.ParentAdded,
|
|
3318
|
+
["PARENT_REMOVED"]: DOCUMENT_CHANGE_TYPE.ParentRemoved,
|
|
3319
|
+
["CHILD_ADDED"]: DOCUMENT_CHANGE_TYPE.ChildAdded,
|
|
3320
|
+
["CHILD_REMOVED"]: DOCUMENT_CHANGE_TYPE.ChildRemoved
|
|
3321
|
+
};
|
|
3322
|
+
/**
|
|
3323
|
+
* Decides whether an event reaches a subscriber.
|
|
3324
|
+
*
|
|
3325
|
+
* Every populated field of the search filter is an AND condition, matching the
|
|
3326
|
+
* reactor's own subscription manager - which also treats an empty array as a
|
|
3327
|
+
* filter that nothing satisfies. `parentId` is a drive concept and is ignored.
|
|
3328
|
+
*
|
|
3329
|
+
* A `Deleted` event carries no documents, so it is matched on its
|
|
3330
|
+
* `context.childId` for identifier filters and delivered unconditionally to
|
|
3331
|
+
* type and slug filters: there is no document left to check them against.
|
|
3332
|
+
*/
|
|
3333
|
+
function eventMatchesSearch(event, search) {
|
|
3334
|
+
const deleted = event.type === DOCUMENT_CHANGE_TYPE.Deleted;
|
|
3335
|
+
const { ids, slugs, type } = search;
|
|
3336
|
+
if (ids) {
|
|
3337
|
+
if (!(deleted ? [event.context?.childId] : event.documents.map((document) => document.header.id)).some((id) => id !== void 0 && ids.includes(id))) return false;
|
|
3338
|
+
}
|
|
3339
|
+
if (slugs && !deleted) {
|
|
3340
|
+
if (!event.documents.map((document) => document.header.slug).some((slug) => slugs.includes(slug))) return false;
|
|
3341
|
+
}
|
|
3342
|
+
if (type && !deleted) {
|
|
3343
|
+
if (!event.documents.map((document) => document.header.documentType).includes(type)) return false;
|
|
3344
|
+
}
|
|
3345
|
+
return true;
|
|
3346
|
+
}
|
|
3347
|
+
/**
|
|
3348
|
+
* Maps a reactor `ViewFilter` onto the GraphQL `ViewFilterInput`.
|
|
3349
|
+
*
|
|
3350
|
+
* Point-in-time reads are rejected: the Switchboard read API has no revision
|
|
3351
|
+
* argument, so silently returning the head state would be wrong.
|
|
3352
|
+
*/
|
|
3353
|
+
function viewFilterInputFromViewFilter(view) {
|
|
3354
|
+
if (!view) return;
|
|
3355
|
+
if (viewIsPointInTime(view)) throw new GraphQLOperationNotSupportedError("view", "point-in-time views are not supported by GraphQLReactorClient");
|
|
3356
|
+
if (view.branch === void 0 && view.scopes === void 0) return;
|
|
3357
|
+
return {
|
|
3358
|
+
branch: view.branch,
|
|
3359
|
+
scopes: view.scopes
|
|
3360
|
+
};
|
|
3361
|
+
}
|
|
3362
|
+
function pagingInputFromPaging(paging) {
|
|
3363
|
+
if (!paging) return;
|
|
3364
|
+
return {
|
|
3365
|
+
cursor: paging.cursor,
|
|
3366
|
+
limit: paging.limit
|
|
3367
|
+
};
|
|
3368
|
+
}
|
|
3369
|
+
/**
|
|
3370
|
+
* Whether a search names `ids` or `slugs`, which the Switchboard `findDocuments`
|
|
3371
|
+
* query cannot honour (it filters by `type` and `parentId`).
|
|
3372
|
+
*
|
|
3373
|
+
* The test is PRESENCE, not length: the reactor `find` contract
|
|
3374
|
+
* (`packages/reactor/src/core/reactor.ts`) dispatches on `search.ids` /
|
|
3375
|
+
* `search.slugs` being present, so `find({ ids: [] })` is an identifier search
|
|
3376
|
+
* that must yield the empty set -- not a plain type query over every document.
|
|
3377
|
+
* The GraphQL surface cannot express an identifier search at all, so a present
|
|
3378
|
+
* (even empty) `ids`/`slugs` is refused rather than served as the wrong query.
|
|
3379
|
+
*/
|
|
3380
|
+
function searchNamesIdentifiers(search) {
|
|
3381
|
+
return search.ids !== void 0 || search.slugs !== void 0;
|
|
3382
|
+
}
|
|
3383
|
+
/** Whether a view asks for a point-in-time read the GraphQL surface cannot express. */
|
|
3384
|
+
function viewIsPointInTime(view) {
|
|
3385
|
+
return view?.revision !== void 0;
|
|
3386
|
+
}
|
|
3387
|
+
/**
|
|
3388
|
+
* The single source of truth for whether the Switchboard `findDocuments` query
|
|
3389
|
+
* can serve a `find`. It is servable iff the search names neither `ids` nor
|
|
3390
|
+
* `slugs` (present, regardless of length) AND the view is not point-in-time:
|
|
3391
|
+
* each is a by-contract limitation of a surface that filters only by
|
|
3392
|
+
* `type`/`parentId` at head. Exported so a caller can route around an
|
|
3393
|
+
* unservable search instead of catching the error `find` throws for it.
|
|
3394
|
+
*/
|
|
3395
|
+
function findIsServableOverGraphQL(search, view) {
|
|
3396
|
+
return !searchNamesIdentifiers(search) && !viewIsPointInTime(view);
|
|
3397
|
+
}
|
|
3398
|
+
/** Rebuilds a relationship edge from its GraphQL fields. */
|
|
3399
|
+
function documentRelationshipFromEdge(edge) {
|
|
3400
|
+
const relationship = {
|
|
3401
|
+
sourceId: edge.sourceId,
|
|
3402
|
+
targetId: edge.targetId,
|
|
3403
|
+
relationshipType: edge.relationshipType,
|
|
3404
|
+
createdAt: dateFromDateTime(edge.createdAt),
|
|
3405
|
+
updatedAt: dateFromDateTime(edge.updatedAt)
|
|
3406
|
+
};
|
|
3407
|
+
const metadata = edge.metadata;
|
|
3408
|
+
if (isPlainObject(metadata)) relationship.metadata = metadata;
|
|
3409
|
+
return relationship;
|
|
3410
|
+
}
|
|
3411
|
+
/**
|
|
3412
|
+
* Restores a `Date` from the `DateTime` scalar, which deserializes as either an
|
|
3413
|
+
* ISO string or a `Date`, reusing the get-path's {@link isoStringFromDateTime}.
|
|
3414
|
+
*
|
|
3415
|
+
* A null, absent or unparseable value is a malformed timestamp from the server,
|
|
3416
|
+
* not something to coerce to the epoch or an `Invalid Date`: it throws, so the
|
|
3417
|
+
* malformed edge surfaces as a genuine failure rather than a silently-wrong
|
|
3418
|
+
* `DocumentRelationship`.
|
|
3419
|
+
*/
|
|
3420
|
+
function dateFromDateTime(value) {
|
|
3421
|
+
if (value === null || value === void 0) throw new Error("relationship edge is missing a required DateTime timestamp");
|
|
3422
|
+
const date = new Date(isoStringFromDateTime(value));
|
|
3423
|
+
if (Number.isNaN(date.getTime())) throw new Error(`relationship edge carries an unparseable DateTime timestamp: ${String(value)}`);
|
|
3424
|
+
return date;
|
|
3425
|
+
}
|
|
3426
|
+
/**
|
|
3427
|
+
* Whether a JSON value is a plain object, so relationship `metadata` is assigned
|
|
3428
|
+
* only when it is one. A non-object JSON scalar (string, number, array, null)
|
|
3429
|
+
* is dropped exactly as a null is, rather than cast to `Record` and trusted.
|
|
3430
|
+
*/
|
|
3431
|
+
function isPlainObject(value) {
|
|
3432
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3433
|
+
}
|
|
3434
|
+
/**
|
|
3435
|
+
* The reactor and the GraphQL schema disagree on the enum: the reactor's
|
|
3436
|
+
* `None` is the schema's `ORPHAN`. This is the inverse of the server's
|
|
3437
|
+
* `toReactorPropagationMode`.
|
|
3438
|
+
*/
|
|
3439
|
+
const propagationModeInputs = {
|
|
3440
|
+
cascade: "CASCADE",
|
|
3441
|
+
none: "ORPHAN"
|
|
3442
|
+
};
|
|
3443
|
+
function propagationModeInput(propagate) {
|
|
3444
|
+
return propagate === void 0 ? void 0 : propagationModeInputs[propagate];
|
|
3445
|
+
}
|
|
3446
|
+
/**
|
|
3447
|
+
* Stamps and signs the actions about to be pushed.
|
|
3448
|
+
*
|
|
3449
|
+
* With no signer the actions go out exactly as given, batch or not - this
|
|
3450
|
+
* client does not require signatures. With one, every action is signed:
|
|
3451
|
+
* {@link prepareSignedActions} predicts the chain a batch will produce by
|
|
3452
|
+
* running the document's own reducer between signatures, which is why a batch
|
|
3453
|
+
* needs the module matching the document's type and exact version.
|
|
3454
|
+
*
|
|
3455
|
+
* A batch that cannot be predicted - no matching module, mixed scopes, an
|
|
3456
|
+
* action needing history - throws here, before the mutation. Sending it
|
|
3457
|
+
* unsigned instead would silently drop the signatures the caller asked for.
|
|
3458
|
+
*/
|
|
3459
|
+
async function prepareActionsForPush(actions, document, documentModels, signer, signal) {
|
|
3460
|
+
if (!signer || actions.length === 0) return actions;
|
|
3461
|
+
return prepareSignedActions(actions, document, signer, actions.length > 1 ? resolveDocumentModelModule(documentModels, document.header.documentType, documentModelVersion(document)) : void 0, signal);
|
|
3462
|
+
}
|
|
3463
|
+
/**
|
|
3464
|
+
* The document-model version the document's actions must be reduced with.
|
|
3465
|
+
*
|
|
3466
|
+
* `state` arrives as JSON over GraphQL, so its `document` scope is only as
|
|
3467
|
+
* reliable as the server that sent it - one written before that scope existed
|
|
3468
|
+
* carries no version at all. `normalizeDocumentModelVersion` maps that, and 0,
|
|
3469
|
+
* to 1: the same rule `SimpleJobExecutor` applies before asking the registry
|
|
3470
|
+
* for a module, so client and server cannot resolve different reducers.
|
|
3471
|
+
*/
|
|
3472
|
+
function documentModelVersion(document) {
|
|
3473
|
+
const documentScope = document.state.document;
|
|
3474
|
+
return normalizeDocumentModelVersion(documentScope?.version);
|
|
3475
|
+
}
|
|
3476
|
+
/**
|
|
3477
|
+
* Rebuilds a reactor {@link JobInfo} from what the server reported. An unknown
|
|
3478
|
+
* job arrives as the reactor's own: FAILED with an empty `documentId`.
|
|
3479
|
+
*/
|
|
3480
|
+
function jobInfoFromGql(job) {
|
|
3481
|
+
const token = job.consistencyToken;
|
|
3482
|
+
if (token.version !== 1) throw new Error(`Job ${job.id} carries consistency token version ${token.version}, which this client cannot read`);
|
|
3483
|
+
const info = {
|
|
3484
|
+
id: job.id,
|
|
3485
|
+
documentId: job.documentId,
|
|
3486
|
+
status: job.status,
|
|
3487
|
+
createdAtUtcIso: isoStringFromDateTime(job.createdAt),
|
|
3488
|
+
consistencyToken: {
|
|
3489
|
+
version: 1,
|
|
3490
|
+
createdAtUtcIso: token.createdAtUtcIso,
|
|
3491
|
+
coordinates: token.coordinates.map((coordinate) => ({ ...coordinate }))
|
|
3492
|
+
},
|
|
3493
|
+
meta: {
|
|
3494
|
+
batchId: job.meta.batchId,
|
|
3495
|
+
batchJobIds: [...job.meta.batchJobIds]
|
|
3496
|
+
}
|
|
3497
|
+
};
|
|
3498
|
+
if (job.completedAt != null) info.completedAtUtcIso = isoStringFromDateTime(job.completedAt);
|
|
3499
|
+
if (job.result != null) info.result = job.result;
|
|
3500
|
+
if (job.error != null) info.error = {
|
|
3501
|
+
name: job.errorName ?? "Error",
|
|
3502
|
+
message: job.error,
|
|
3503
|
+
stack: ""
|
|
3504
|
+
};
|
|
3505
|
+
return info;
|
|
3506
|
+
}
|
|
3507
|
+
/**
|
|
3508
|
+
* The header a Switchboard's drive middleware and load balancer key on. A
|
|
3509
|
+
* request carries it only when it is known to belong to that one drive: the
|
|
3510
|
+
* server answers any drive it does not own with 421.
|
|
3511
|
+
*/
|
|
3512
|
+
const DRIVE_ID_HEADER = "Drive-Id";
|
|
3513
|
+
function driveIdHeaders(driveId) {
|
|
3514
|
+
return driveId === "" ? void 0 : { [DRIVE_ID_HEADER]: driveId };
|
|
3515
|
+
}
|
|
3516
|
+
function isDrive(document) {
|
|
3517
|
+
return DRIVE_DOCUMENT_TYPES.includes(document.header.documentType);
|
|
3518
|
+
}
|
|
3519
|
+
/**
|
|
3520
|
+
* Surfaces a 421 from the Switchboard's drive middleware, which graphql-request
|
|
3521
|
+
* reports as a `ClientError`, as {@link GraphQLWrongBackendError}.
|
|
3522
|
+
*/
|
|
3523
|
+
function withWrongBackendErrors(middleware) {
|
|
3524
|
+
return async (action, ...rest) => {
|
|
3525
|
+
try {
|
|
3526
|
+
return await middleware(action, ...rest);
|
|
3527
|
+
} catch (error) {
|
|
3528
|
+
throw wrongBackendErrorOf(error) ?? error;
|
|
3529
|
+
}
|
|
3530
|
+
};
|
|
3531
|
+
}
|
|
3532
|
+
function wrongBackendErrorOf(error) {
|
|
3533
|
+
const response = error?.response;
|
|
3534
|
+
if (response?.status !== 421) return;
|
|
3535
|
+
let payload = response.body;
|
|
3536
|
+
if (typeof payload === "string") try {
|
|
3537
|
+
payload = JSON.parse(payload);
|
|
3538
|
+
} catch {}
|
|
3539
|
+
const driveId = payload?.driveId;
|
|
3540
|
+
return new GraphQLWrongBackendError(typeof driveId === "string" ? driveId : "", payload, { cause: error });
|
|
3541
|
+
}
|
|
3542
|
+
function isSettled(job) {
|
|
3543
|
+
const status = job.status;
|
|
3544
|
+
return status === "READ_READY" || status === "FAILED";
|
|
3545
|
+
}
|
|
3546
|
+
function abortReason(signal) {
|
|
3547
|
+
const reason = signal.reason;
|
|
3548
|
+
return reason instanceof Error ? reason : new Error(String(reason));
|
|
3549
|
+
}
|
|
3550
|
+
function delay(ms, signal) {
|
|
3551
|
+
return new Promise((resolve, reject) => {
|
|
3552
|
+
if (signal?.aborted) {
|
|
3553
|
+
reject(abortReason(signal));
|
|
3554
|
+
return;
|
|
3555
|
+
}
|
|
3556
|
+
const onAbort = () => {
|
|
3557
|
+
clearTimeout(timer);
|
|
3558
|
+
if (signal) reject(abortReason(signal));
|
|
3559
|
+
};
|
|
3560
|
+
const timer = setTimeout(() => {
|
|
3561
|
+
signal?.removeEventListener("abort", onAbort);
|
|
3562
|
+
resolve();
|
|
3563
|
+
}, ms);
|
|
3564
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3565
|
+
});
|
|
3566
|
+
}
|
|
3567
|
+
/** As the reactor's `signAction` reads it: the last tuple names a key. */
|
|
3568
|
+
function isActionSigned(action) {
|
|
3569
|
+
const signer = action.context?.signer;
|
|
3570
|
+
return Boolean(signer?.app?.key && signer.signatures.at(-1)?.[1]);
|
|
3571
|
+
}
|
|
3572
|
+
/** Resolves the signer of the logged-in user, if there is one. */
|
|
3573
|
+
/** The logged-in Renown user's signer, read per call; none when nobody is. */
|
|
3574
|
+
function ambientRenownSigner() {
|
|
3575
|
+
if (typeof window === "undefined") return;
|
|
3576
|
+
const renown = getPHStore()?.renown;
|
|
3577
|
+
return renown?.user ? renown.signer : void 0;
|
|
3578
|
+
}
|
|
3579
|
+
/**
|
|
3580
|
+
* The revision the pushed operations start from: the lowest head revision
|
|
3581
|
+
* across the scopes the actions target.
|
|
3582
|
+
*
|
|
3583
|
+
* The baseline is only meaningful together with {@link scopesForActions}: a
|
|
3584
|
+
* batch that touches a scope at revision 1 and one at revision 5000 would
|
|
3585
|
+
* otherwise re-download the whole history of every scope of the document.
|
|
3586
|
+
*/
|
|
3587
|
+
function sinceRevisionForActions(document, actions) {
|
|
3588
|
+
const revisions = actions.map((action) => document.header.revision[action.scope] ?? 0);
|
|
3589
|
+
return revisions.length > 0 ? Math.min(...revisions) : 0;
|
|
3590
|
+
}
|
|
3591
|
+
/** The distinct scopes the pushed actions target, in first-seen order. */
|
|
3592
|
+
function scopesForActions(actions) {
|
|
3593
|
+
if (actions.length === 0) return;
|
|
3594
|
+
return [...new Set(actions.map((action) => action.scope))];
|
|
3595
|
+
}
|
|
3596
|
+
//#endregion
|
|
3597
|
+
//#region src/hooks/backend-auth.ts
|
|
3598
|
+
const backendAuthEventFunctions = makePHEventFunctions("backendAuth");
|
|
3599
|
+
/** Whether the app's backend refused this tab's caller, and how. */
|
|
3600
|
+
const useBackendAuth = backendAuthEventFunctions.useValue;
|
|
3601
|
+
/** Records (or clears, with `undefined`) a backend's refusal of the caller. */
|
|
3602
|
+
const setBackendAuth = backendAuthEventFunctions.setValue;
|
|
3603
|
+
const addBackendAuthEventHandler = backendAuthEventFunctions.addEventHandler;
|
|
3604
|
+
const STATUS_IN_MESSAGE = /\(Code: (401|403)\)/;
|
|
3605
|
+
/**
|
|
3606
|
+
* The messages a Switchboard's GraphQL layer refuses with, without an HTTP
|
|
3607
|
+
* status (the sync layer's `DRIVE_AUTH_ERROR_MESSAGES`). Inlined: this file
|
|
3608
|
+
* is reachable from the browser entry, which must not import the reactor
|
|
3609
|
+
* package as a value.
|
|
3610
|
+
*/
|
|
3611
|
+
const GRAPHQL_REFUSALS = [
|
|
3612
|
+
"Forbidden: insufficient permissions",
|
|
3613
|
+
"Forbidden: authentication required",
|
|
3614
|
+
"Authentication required"
|
|
3615
|
+
];
|
|
3616
|
+
/**
|
|
3617
|
+
* The HTTP status with which a backend refused the caller, or null when the
|
|
3618
|
+
* error is something else.
|
|
3619
|
+
*
|
|
3620
|
+
* Covers every shape a refusal reaches the browser in: the sync layer's
|
|
3621
|
+
* errors (`isDriveAuthError`), graphql-request's `ClientError` from the
|
|
3622
|
+
* remote GraphQL client (`response.status`, and "(Code: 401)" in its
|
|
3623
|
+
* message), and the router's partial-failure error that wraps one such
|
|
3624
|
+
* failure per backend.
|
|
3625
|
+
*/
|
|
3626
|
+
function backendAuthStatusOf(error) {
|
|
3627
|
+
if (!error || typeof error !== "object") return null;
|
|
3628
|
+
const e = error;
|
|
3629
|
+
const direct = [e.response?.status, e.statusCode].find((s) => s === 401 || s === 403);
|
|
3630
|
+
if (direct === 401 || direct === 403) return direct;
|
|
3631
|
+
if (typeof e.message === "string") {
|
|
3632
|
+
const m = STATUS_IN_MESSAGE.exec(e.message);
|
|
3633
|
+
if (m) return m[1] === "401" ? 401 : 403;
|
|
3634
|
+
}
|
|
3635
|
+
if (Array.isArray(e.failures)) for (const failure of e.failures) {
|
|
3636
|
+
const status = backendAuthStatusOf(failure.error);
|
|
3637
|
+
if (status) return status;
|
|
3638
|
+
}
|
|
3639
|
+
if (typeof e.message === "string" && GRAPHQL_REFUSALS.some((m) => e.message.includes(m))) return /authentication required/i.test(e.message) ? 401 : 403;
|
|
3640
|
+
return null;
|
|
3641
|
+
}
|
|
3642
|
+
/** True when a backend refused the caller as unauthenticated or unauthorized. */
|
|
3643
|
+
function isBackendAuthError(error) {
|
|
3644
|
+
return backendAuthStatusOf(error) !== null;
|
|
3645
|
+
}
|
|
3646
|
+
/** Records the refusal `error` carries, if it is one; returns whether it was. */
|
|
3647
|
+
function recordBackendAuthError(error, backend) {
|
|
3648
|
+
const status = backendAuthStatusOf(error);
|
|
3649
|
+
if (status === null) return false;
|
|
3650
|
+
setBackendAuth({
|
|
3651
|
+
requiresAuth: true,
|
|
3652
|
+
status,
|
|
3653
|
+
backend,
|
|
3654
|
+
at: (/* @__PURE__ */ new Date()).toISOString()
|
|
3655
|
+
});
|
|
3656
|
+
return true;
|
|
3657
|
+
}
|
|
3658
|
+
//#endregion
|
|
3659
|
+
//#region src/hooks/config/editor.ts
|
|
3660
|
+
const isExternalControlsEnabledEventFunctions = makePHEventFunctions("isExternalControlsEnabled");
|
|
3661
|
+
/** Sets whether external controls are enabled for a given editor. */
|
|
3662
|
+
const setIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.setValue;
|
|
3663
|
+
/** Gets whether external controls are enabled for a given editor. */
|
|
3664
|
+
const useIsExternalControlsEnabled = isExternalControlsEnabledEventFunctions.useValue;
|
|
3665
|
+
/** Adds an event handler for when the external controls enabled state changes. */
|
|
3666
|
+
const addIsExternalControlsEnabledEventHandler = isExternalControlsEnabledEventFunctions.addEventHandler;
|
|
3667
|
+
const isDragAndDropEnabledEventFunctions = makePHEventFunctions("isDragAndDropEnabled");
|
|
3668
|
+
/** Sets whether drag and drop is enabled for a given app. */
|
|
3669
|
+
const setIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.setValue;
|
|
3670
|
+
/** Gets whether drag and drop is enabled for a given app. */
|
|
3671
|
+
const useIsDragAndDropEnabled = isDragAndDropEnabledEventFunctions.useValue;
|
|
3672
|
+
/** Adds an event handler for when the drag and drop enabled state changes. */
|
|
3673
|
+
const addIsDragAndDropEnabledEventHandler = isDragAndDropEnabledEventFunctions.addEventHandler;
|
|
3674
|
+
const allowedDocumentTypesEventFunctions = makePHEventFunctions("allowedDocumentTypes");
|
|
3675
|
+
/** Sets the allowed document types for a given app. */
|
|
3676
|
+
const setAllowedDocumentTypes = allowedDocumentTypesEventFunctions.setValue;
|
|
3677
|
+
/** Defines the document types a drive supports.
|
|
3678
|
+
*
|
|
3679
|
+
* Unset or empty, it means every document type registered in the reactor.
|
|
3680
|
+
*/
|
|
3681
|
+
function useAllowedDocumentTypes() {
|
|
3682
|
+
return allowedDocumentTypesEventFunctions.useValue();
|
|
3683
|
+
}
|
|
3684
|
+
/** Adds an event handler for when the allowed document types for a given app changes. */
|
|
3685
|
+
const addAllowedDocumentTypesEventHandler = allowedDocumentTypesEventFunctions.addEventHandler;
|
|
3686
|
+
const phAppConfigSetters = {
|
|
3687
|
+
allowedDocumentTypes: setAllowedDocumentTypes,
|
|
3688
|
+
isDragAndDropEnabled: setIsDragAndDropEnabled
|
|
3689
|
+
};
|
|
3690
|
+
const phDocumentEditorConfigSetters = { isExternalControlsEnabled: setIsExternalControlsEnabled };
|
|
3691
|
+
const phAppConfigHooks = {
|
|
3692
|
+
allowedDocumentTypes: useAllowedDocumentTypes,
|
|
3693
|
+
isDragAndDropEnabled: useIsDragAndDropEnabled
|
|
3694
|
+
};
|
|
3695
|
+
const phDocumentEditorConfigHooks = { isExternalControlsEnabled: useIsExternalControlsEnabled };
|
|
3696
|
+
//#endregion
|
|
3697
|
+
//#region src/hooks/config/connect.ts
|
|
3698
|
+
const { useValue: useRouterBasename, setValue: setRouterBasename, addEventHandler: addRouterBasenameEventHandler } = makePHEventFunctions("routerBasename");
|
|
3699
|
+
const { useValue: useVersion, setValue: setVersion, addEventHandler: addVersionEventHandler } = makePHEventFunctions("version");
|
|
3700
|
+
const { useValue: useRequiresHardRefresh, setValue: setRequiresHardRefresh, addEventHandler: addRequiresHardRefreshEventHandler } = makePHEventFunctions("requiresHardRefresh");
|
|
3701
|
+
const { useValue: useWarnOutdatedApp, setValue: setWarnOutdatedApp, addEventHandler: addWarnOutdatedAppEventHandler } = makePHEventFunctions("warnOutdatedApp");
|
|
3702
|
+
const { useValue: useStudioMode, setValue: setStudioMode, addEventHandler: addStudioModeEventHandler } = makePHEventFunctions("studioMode");
|
|
3703
|
+
const { useValue: useBasePath, setValue: setBasePath, addEventHandler: addBasePathEventHandler } = makePHEventFunctions("basePath");
|
|
3704
|
+
const { useValue: useVersionCheckInterval, setValue: setVersionCheckInterval, addEventHandler: addVersionCheckIntervalEventHandler } = makePHEventFunctions("versionCheckInterval");
|
|
3705
|
+
const { useValue: useCliVersion, setValue: setCliVersion, addEventHandler: addCliVersionEventHandler } = makePHEventFunctions("cliVersion");
|
|
3706
|
+
const { useValue: useFileUploadOperationsChunkSize, setValue: setFileUploadOperationsChunkSize, addEventHandler: addFileUploadOperationsChunkSizeEventHandler } = makePHEventFunctions("fileUploadOperationsChunkSize");
|
|
3707
|
+
const { useValue: useIsDocumentModelSelectionSettingsEnabled, setValue: setIsDocumentModelSelectionSettingsEnabled, addEventHandler: addIsDocumentModelSelectionSettingsEnabledEventHandler } = makePHEventFunctions("isDocumentModelSelectionSettingsEnabled");
|
|
3708
|
+
const { useValue: useGaTrackingId, setValue: setGaTrackingId, addEventHandler: addGaTrackingIdEventHandler } = makePHEventFunctions("gaTrackingId");
|
|
3709
|
+
const { useValue: useDefaultDrivesUrl, setValue: setDefaultDrivesUrl, addEventHandler: addDefaultDrivesUrlEventHandler } = makePHEventFunctions("defaultDrivesUrl");
|
|
3710
|
+
const { useValue: useDrivesPreserveStrategy, setValue: setDrivesPreserveStrategy, addEventHandler: addDrivesPreserveStrategyEventHandler } = makePHEventFunctions("drivesPreserveStrategy");
|
|
3711
|
+
const { useValue: useIsLocalDrivesEnabled, setValue: setIsLocalDrivesEnabled, addEventHandler: addIsLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
|
|
3712
|
+
const { useValue: useIsAddDriveEnabled, setValue: setIsAddDriveEnabled, addEventHandler: addIsAddDriveEnabledEventHandler } = makePHEventFunctions("isAddDriveEnabled");
|
|
3713
|
+
const { useValue: useIsPublicDrivesEnabled, setValue: setIsPublicDrivesEnabled, addEventHandler: addIsPublicDrivesEnabledEventHandler } = makePHEventFunctions("isPublicDrivesEnabled");
|
|
3714
|
+
const { useValue: useIsAddPublicDrivesEnabled, setValue: setIsAddPublicDrivesEnabled, addEventHandler: addIsAddPublicDrivesEnabledEventHandler } = makePHEventFunctions("isAddPublicDrivesEnabled");
|
|
3715
|
+
const { useValue: useIsDeletePublicDrivesEnabled, setValue: setIsDeletePublicDrivesEnabled, addEventHandler: addIsDeletePublicDrivesEnabledEventHandler } = makePHEventFunctions("isDeletePublicDrivesEnabled");
|
|
3716
|
+
const { useValue: useIsCloudDrivesEnabled, setValue: setIsCloudDrivesEnabled, addEventHandler: addIsCloudDrivesEnabledEventHandler } = makePHEventFunctions("isCloudDrivesEnabled");
|
|
3717
|
+
const { useValue: useIsAddCloudDrivesEnabled, setValue: setIsAddCloudDrivesEnabled, addEventHandler: addIsAddCloudDrivesEnabledEventHandler } = makePHEventFunctions("isAddCloudDrivesEnabled");
|
|
3718
|
+
const { useValue: useIsDeleteCloudDrivesEnabled, setValue: setIsDeleteCloudDrivesEnabled, addEventHandler: addIsDeleteCloudDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteCloudDrivesEnabled");
|
|
3719
|
+
const { useValue: useLocalDrivesEnabled, setValue: setLocalDrivesEnabled, addEventHandler: addLocalDrivesEnabledEventHandler } = makePHEventFunctions("isLocalDrivesEnabled");
|
|
3720
|
+
const { useValue: useIsAddLocalDrivesEnabled, setValue: setIsAddLocalDrivesEnabled, addEventHandler: addIsAddLocalDrivesEnabledEventHandler } = makePHEventFunctions("isAddLocalDrivesEnabled");
|
|
3721
|
+
const { useValue: useIsDeleteLocalDrivesEnabled, setValue: setIsDeleteLocalDrivesEnabled, addEventHandler: addIsDeleteLocalDrivesEnabledEventHandler } = makePHEventFunctions("isDeleteLocalDrivesEnabled");
|
|
3722
|
+
const { useValue: useIsEditorDebugModeEnabled, setValue: setIsEditorDebugModeEnabled, addEventHandler: addIsEditorDebugModeEnabledEventHandler } = makePHEventFunctions("isEditorDebugModeEnabled");
|
|
3723
|
+
const { useValue: useIsEditorReadModeEnabled, setValue: setIsEditorReadModeEnabled, addEventHandler: addIsEditorReadModeEnabledEventHandler } = makePHEventFunctions("isEditorReadModeEnabled");
|
|
3724
|
+
const { useValue: useIsAnalyticsDatabaseWorkerEnabled, setValue: setIsAnalyticsDatabaseWorkerEnabled, addEventHandler: addIsAnalyticsDatabaseWorkerEnabledEventHandler } = makePHEventFunctions("isAnalyticsDatabaseWorkerEnabled");
|
|
3725
|
+
const { useValue: useIsDiffAnalyticsEnabled, setValue: setIsDiffAnalyticsEnabled, addEventHandler: addIsDiffAnalyticsEnabledEventHandler } = makePHEventFunctions("isDiffAnalyticsEnabled");
|
|
3726
|
+
const { useValue: useIsDriveAnalyticsEnabled, setValue: setIsDriveAnalyticsEnabled, addEventHandler: addIsDriveAnalyticsEnabledEventHandler } = makePHEventFunctions("isDriveAnalyticsEnabled");
|
|
3727
|
+
const { useValue: useRenownUrl, setValue: setRenownUrl, addEventHandler: addRenownUrlEventHandler } = makePHEventFunctions("renownUrl");
|
|
3728
|
+
const { useValue: useRenownNetworkId, setValue: setRenownNetworkId, addEventHandler: addRenownNetworkIdEventHandler } = makePHEventFunctions("renownNetworkId");
|
|
3729
|
+
const { useValue: useRenownChainId, setValue: setRenownChainId, addEventHandler: addRenownChainIdEventHandler } = makePHEventFunctions("renownChainId");
|
|
3730
|
+
const { useValue: useSwitchboardUrl, setValue: setSwitchboardUrl, addEventHandler: addSwitchboardUrlEventHandler } = makePHEventFunctions("switchboardUrl");
|
|
3731
|
+
const { useValue: useRenownAdapters, setValue: setRenownAdapters, addEventHandler: addRenownAdaptersEventHandler } = makePHEventFunctions("renownAdapters");
|
|
3732
|
+
const { useValue: useSentryRelease, setValue: setSentryRelease, addEventHandler: addSentryReleaseEventHandler } = makePHEventFunctions("sentryRelease");
|
|
3733
|
+
const { useValue: useSentryDsn, setValue: setSentryDsn, addEventHandler: addSentryDsnEventHandler } = makePHEventFunctions("sentryDsn");
|
|
3734
|
+
const { useValue: useSentryEnv, setValue: setSentryEnv, addEventHandler: addSentryEnvEventHandler } = makePHEventFunctions("sentryEnv");
|
|
3735
|
+
const { useValue: useIsSentryTracingEnabled, setValue: setIsSentryTracingEnabled, addEventHandler: addIsSentryTracingEnabledEventHandler } = makePHEventFunctions("isSentryTracingEnabled");
|
|
3736
|
+
const { useValue: useIsExternalProcessorsEnabled, setValue: setIsExternalProcessorsEnabled, addEventHandler: addIsExternalProcessorsEnabledEventHandler } = makePHEventFunctions("isExternalProcessorsEnabled");
|
|
3737
|
+
const { useValue: useIsExternalPackagesEnabled, setValue: setIsExternalPackagesEnabled, addEventHandler: addIsExternalPackagesEnabledEventHandler } = makePHEventFunctions("isExternalPackagesEnabled");
|
|
3738
|
+
const enabledEditorsEventFunctions = makePHEventFunctions("enabledEditors");
|
|
3739
|
+
/** Sets the enabled editors for Connect. */
|
|
3740
|
+
const setEnabledEditors = enabledEditorsEventFunctions.setValue;
|
|
3741
|
+
/** Gets the enabled editors for Connect. */
|
|
3742
|
+
const useEnabledEditors = enabledEditorsEventFunctions.useValue;
|
|
3743
|
+
/** Adds an event handler for when the enabled editors for Connect changes. */
|
|
3744
|
+
const addEnabledEditorsEventHandler = enabledEditorsEventFunctions.addEventHandler;
|
|
3745
|
+
const disabledEditorsEventFunctions = makePHEventFunctions("disabledEditors");
|
|
3746
|
+
/** Sets the disabled editors for Connect. */
|
|
3747
|
+
const setDisabledEditors = disabledEditorsEventFunctions.setValue;
|
|
3748
|
+
/** Gets the disabled editors for Connect. */
|
|
3749
|
+
const useDisabledEditors = disabledEditorsEventFunctions.useValue;
|
|
3750
|
+
/** Adds an event handler for when the disabled editors for Connect changes. */
|
|
3751
|
+
const addDisabledEditorsEventHandler = disabledEditorsEventFunctions.addEventHandler;
|
|
3752
|
+
const isRelationalProcessorsEnabled = makePHEventFunctions("isRelationalProcessorsEnabled");
|
|
3753
|
+
/** Sets the isRelationalProcessorsEnabled for Connect. */
|
|
3754
|
+
const setIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.setValue;
|
|
3755
|
+
/** Gets the isRelationalProcessorsEnabled for Connect. */
|
|
3756
|
+
const useIsRelationalProcessorsEnabled = isRelationalProcessorsEnabled.useValue;
|
|
3757
|
+
/** Adds an event handler for when the isRelationalProcessorsEnabled for Connect changes. */
|
|
3758
|
+
const addIsRelationalProcessorsEnabledEventHandler = isRelationalProcessorsEnabled.addEventHandler;
|
|
3759
|
+
const isExternalRelationalProcessorsEnabled = makePHEventFunctions("isExternalRelationalProcessorsEnabled");
|
|
3760
|
+
/** Sets the isExternalRelationalProcessorsEnabled for Connect. */
|
|
3761
|
+
const setIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.setValue;
|
|
3762
|
+
/** Gets the isExternalRelationalProcessorsEnabled for Connect. */
|
|
3763
|
+
const useIsExternalRelationalProcessorsEnabled = isExternalRelationalProcessorsEnabled.useValue;
|
|
3764
|
+
/** Adds an event handler for when the isExternalRelationalProcessorsEnabled for Connect changes. */
|
|
3765
|
+
const addIsExternalRelationalProcessorsEnabledEventHandler = isExternalRelationalProcessorsEnabled.addEventHandler;
|
|
3766
|
+
const isAnalyticsEnabledEventFunctions = makePHEventFunctions("isAnalyticsEnabled");
|
|
3767
|
+
/** Sets the isAnalyticsEnabled for Connect. */
|
|
3768
|
+
const setIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.setValue;
|
|
3769
|
+
/** Gets the isAnalyticsEnabled for Connect. */
|
|
3770
|
+
const useIsAnalyticsEnabled = isAnalyticsEnabledEventFunctions.useValue;
|
|
3771
|
+
/** Adds an event handler for when the isAnalyticsEnabled for Connect changes. */
|
|
3772
|
+
const addIsAnalyticsEnabledEventHandler = isAnalyticsEnabledEventFunctions.addEventHandler;
|
|
3773
|
+
const isAnalyticsExternalProcessorsEnabled = makePHEventFunctions("isAnalyticsExternalProcessorsEnabled");
|
|
3774
|
+
/** Sets the isAnalyticsExternalProcessorsEnabled for Connect. */
|
|
3775
|
+
const setIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.setValue;
|
|
3776
|
+
/** Gets the isAnalyticsExternalProcessorsEnabled for Connect. */
|
|
3777
|
+
const useIsAnalyticsExternalProcessorsEnabled = isAnalyticsExternalProcessorsEnabled.useValue;
|
|
3778
|
+
/** Adds an event handler for when the isAnalyticsExternalProcessorsEnabled for Connect changes. */
|
|
3779
|
+
const addIsAnalyticsExternalProcessorsEnabledEventHandler = isAnalyticsExternalProcessorsEnabled.addEventHandler;
|
|
3780
|
+
const analyticsDatabaseNameEventFunctions = makePHEventFunctions("analyticsDatabaseName");
|
|
3781
|
+
/** Sets the analytics database name for Connect. */
|
|
3782
|
+
const setAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.setValue;
|
|
3783
|
+
/** Gets the analytics database name for Connect. */
|
|
3784
|
+
const useAnalyticsDatabaseName = analyticsDatabaseNameEventFunctions.useValue;
|
|
3785
|
+
/** Adds an event handler for when the analytics database name for Connect changes. */
|
|
3786
|
+
const addAnalyticsDatabaseNameEventHandler = analyticsDatabaseNameEventFunctions.addEventHandler;
|
|
3787
|
+
const logLevelEventFunctions = makePHEventFunctions("logLevel");
|
|
3788
|
+
/** Sets the log level for Connect. */
|
|
3789
|
+
const setLogLevel = logLevelEventFunctions.setValue;
|
|
3790
|
+
/** Gets the log level for Connect. */
|
|
3791
|
+
const useLogLevel = logLevelEventFunctions.useValue;
|
|
3792
|
+
/** Adds an event handler for when the log level for Connect changes. */
|
|
3793
|
+
const addLogLevelEventHandler = logLevelEventFunctions.addEventHandler;
|
|
3794
|
+
const allowListEventFunctions = makePHEventFunctions("allowList");
|
|
3795
|
+
/** Sets the allow list for Connect. */
|
|
3796
|
+
const setAllowList = allowListEventFunctions.setValue;
|
|
3797
|
+
/** Gets the allow list for Connect. */
|
|
3798
|
+
const useAllowList = allowListEventFunctions.useValue;
|
|
3799
|
+
/** Adds an event handler for when the allow list for Connect changes. */
|
|
3800
|
+
const addAllowListEventHandler = allowListEventFunctions.addEventHandler;
|
|
3801
|
+
const nonUserConfigSetters = {
|
|
3802
|
+
routerBasename: setRouterBasename,
|
|
3803
|
+
version: setVersion,
|
|
3804
|
+
requiresHardRefresh: setRequiresHardRefresh,
|
|
3805
|
+
warnOutdatedApp: setWarnOutdatedApp,
|
|
3806
|
+
studioMode: setStudioMode,
|
|
3807
|
+
basePath: setBasePath,
|
|
3808
|
+
versionCheckInterval: setVersionCheckInterval,
|
|
3809
|
+
cliVersion: setCliVersion,
|
|
3810
|
+
fileUploadOperationsChunkSize: setFileUploadOperationsChunkSize,
|
|
3811
|
+
isDocumentModelSelectionSettingsEnabled: setIsDocumentModelSelectionSettingsEnabled,
|
|
3812
|
+
gaTrackingId: setGaTrackingId,
|
|
3813
|
+
defaultDrivesUrl: setDefaultDrivesUrl,
|
|
3814
|
+
drivesPreserveStrategy: setDrivesPreserveStrategy,
|
|
3815
|
+
isLocalDrivesEnabled: setIsLocalDrivesEnabled,
|
|
3816
|
+
isAddDriveEnabled: setIsAddDriveEnabled,
|
|
3817
|
+
isPublicDrivesEnabled: setIsPublicDrivesEnabled,
|
|
3818
|
+
isAddPublicDrivesEnabled: setIsAddPublicDrivesEnabled,
|
|
3819
|
+
isDeletePublicDrivesEnabled: setIsDeletePublicDrivesEnabled,
|
|
3820
|
+
isCloudDrivesEnabled: setIsCloudDrivesEnabled,
|
|
3821
|
+
isAddCloudDrivesEnabled: setIsAddCloudDrivesEnabled,
|
|
3822
|
+
isDeleteCloudDrivesEnabled: setIsDeleteCloudDrivesEnabled,
|
|
3823
|
+
isAddLocalDrivesEnabled: setIsAddLocalDrivesEnabled,
|
|
3824
|
+
isDeleteLocalDrivesEnabled: setIsDeleteLocalDrivesEnabled,
|
|
3825
|
+
isEditorDebugModeEnabled: setIsEditorDebugModeEnabled,
|
|
3826
|
+
isEditorReadModeEnabled: setIsEditorReadModeEnabled,
|
|
3827
|
+
isRelationalProcessorsEnabled: setIsRelationalProcessorsEnabled,
|
|
3828
|
+
isExternalRelationalProcessorsEnabled: setIsExternalRelationalProcessorsEnabled,
|
|
3829
|
+
isAnalyticsEnabled: setIsAnalyticsEnabled,
|
|
3830
|
+
analyticsDatabaseName: setAnalyticsDatabaseName,
|
|
3831
|
+
isAnalyticsExternalProcessorsEnabled: setIsAnalyticsExternalProcessorsEnabled,
|
|
3832
|
+
isAnalyticsDatabaseWorkerEnabled: setIsAnalyticsDatabaseWorkerEnabled,
|
|
3833
|
+
isDiffAnalyticsEnabled: setIsDiffAnalyticsEnabled,
|
|
3834
|
+
isDriveAnalyticsEnabled: setIsDriveAnalyticsEnabled,
|
|
3835
|
+
renownUrl: setRenownUrl,
|
|
3836
|
+
renownNetworkId: setRenownNetworkId,
|
|
3837
|
+
renownChainId: setRenownChainId,
|
|
3838
|
+
switchboardUrl: setSwitchboardUrl,
|
|
3839
|
+
renownAdapters: setRenownAdapters,
|
|
3840
|
+
sentryRelease: setSentryRelease,
|
|
3841
|
+
sentryDsn: setSentryDsn,
|
|
3842
|
+
sentryEnv: setSentryEnv,
|
|
3843
|
+
isSentryTracingEnabled: setIsSentryTracingEnabled,
|
|
3844
|
+
isExternalProcessorsEnabled: setIsExternalProcessorsEnabled,
|
|
3845
|
+
isExternalPackagesEnabled: setIsExternalPackagesEnabled,
|
|
3846
|
+
allowList: setAllowList,
|
|
3847
|
+
logLevel: setLogLevel,
|
|
3848
|
+
disabledEditors: setDisabledEditors,
|
|
3849
|
+
enabledEditors: setEnabledEditors
|
|
3850
|
+
};
|
|
3851
|
+
const phGlobalConfigSetters = {
|
|
3852
|
+
...phAppConfigSetters,
|
|
3853
|
+
...phDocumentEditorConfigSetters,
|
|
3854
|
+
...nonUserConfigSetters
|
|
3855
|
+
};
|
|
3856
|
+
const nonUserConfigHooks = {
|
|
3857
|
+
routerBasename: useRouterBasename,
|
|
3858
|
+
version: useVersion,
|
|
3859
|
+
requiresHardRefresh: useRequiresHardRefresh,
|
|
3860
|
+
warnOutdatedApp: useWarnOutdatedApp,
|
|
3861
|
+
studioMode: useStudioMode,
|
|
3862
|
+
basePath: useBasePath,
|
|
3863
|
+
versionCheckInterval: useVersionCheckInterval,
|
|
3864
|
+
cliVersion: useCliVersion,
|
|
3865
|
+
fileUploadOperationsChunkSize: useFileUploadOperationsChunkSize,
|
|
3866
|
+
isDocumentModelSelectionSettingsEnabled: useIsDocumentModelSelectionSettingsEnabled,
|
|
3867
|
+
gaTrackingId: useGaTrackingId,
|
|
3868
|
+
defaultDrivesUrl: useDefaultDrivesUrl,
|
|
3869
|
+
drivesPreserveStrategy: useDrivesPreserveStrategy,
|
|
3870
|
+
isAddDriveEnabled: useIsAddDriveEnabled,
|
|
3871
|
+
isPublicDrivesEnabled: useIsPublicDrivesEnabled,
|
|
3872
|
+
isAddPublicDrivesEnabled: useIsAddPublicDrivesEnabled,
|
|
3873
|
+
isDeletePublicDrivesEnabled: useIsDeletePublicDrivesEnabled,
|
|
3874
|
+
isCloudDrivesEnabled: useIsCloudDrivesEnabled,
|
|
3875
|
+
isAddCloudDrivesEnabled: useIsAddCloudDrivesEnabled,
|
|
3876
|
+
isDeleteCloudDrivesEnabled: useIsDeleteCloudDrivesEnabled,
|
|
3877
|
+
isLocalDrivesEnabled: useIsLocalDrivesEnabled,
|
|
3878
|
+
isAddLocalDrivesEnabled: useIsAddLocalDrivesEnabled,
|
|
3879
|
+
isDeleteLocalDrivesEnabled: useIsDeleteLocalDrivesEnabled,
|
|
3880
|
+
isEditorDebugModeEnabled: useIsEditorDebugModeEnabled,
|
|
3881
|
+
isEditorReadModeEnabled: useIsEditorReadModeEnabled,
|
|
3882
|
+
isAnalyticsDatabaseWorkerEnabled: useIsAnalyticsDatabaseWorkerEnabled,
|
|
3883
|
+
isDiffAnalyticsEnabled: useIsDiffAnalyticsEnabled,
|
|
3884
|
+
isDriveAnalyticsEnabled: useIsDriveAnalyticsEnabled,
|
|
3885
|
+
renownUrl: useRenownUrl,
|
|
3886
|
+
renownNetworkId: useRenownNetworkId,
|
|
3887
|
+
renownChainId: useRenownChainId,
|
|
3888
|
+
switchboardUrl: useSwitchboardUrl,
|
|
3889
|
+
renownAdapters: useRenownAdapters,
|
|
3890
|
+
sentryRelease: useSentryRelease,
|
|
3891
|
+
sentryDsn: useSentryDsn,
|
|
3892
|
+
sentryEnv: useSentryEnv,
|
|
3893
|
+
isSentryTracingEnabled: useIsSentryTracingEnabled,
|
|
3894
|
+
isExternalProcessorsEnabled: useIsExternalProcessorsEnabled,
|
|
3895
|
+
isExternalPackagesEnabled: useIsExternalPackagesEnabled,
|
|
3896
|
+
allowList: useAllowList,
|
|
3897
|
+
isAnalyticsEnabled: useIsAnalyticsEnabled,
|
|
3898
|
+
isAnalyticsExternalProcessorsEnabled: useIsAnalyticsExternalProcessorsEnabled,
|
|
3899
|
+
isRelationalProcessorsEnabled: useIsRelationalProcessorsEnabled,
|
|
3900
|
+
isExternalRelationalProcessorsEnabled: useIsExternalRelationalProcessorsEnabled,
|
|
3901
|
+
analyticsDatabaseName: useAnalyticsDatabaseName,
|
|
3902
|
+
logLevel: useLogLevel,
|
|
3903
|
+
disabledEditors: useDisabledEditors,
|
|
3904
|
+
enabledEditors: useEnabledEditors
|
|
3905
|
+
};
|
|
3906
|
+
const phGlobalConfigHooks = {
|
|
3907
|
+
...phAppConfigHooks,
|
|
3908
|
+
...phDocumentEditorConfigHooks,
|
|
3909
|
+
...nonUserConfigHooks
|
|
3910
|
+
};
|
|
3911
|
+
//#endregion
|
|
3912
|
+
//#region src/hooks/attachment-service.ts
|
|
3913
|
+
const attachmentServiceEventFunctions = makePHEventFunctions("attachmentService");
|
|
3914
|
+
/** Returns the attachment service from window.ph */
|
|
3915
|
+
const useAttachmentService = attachmentServiceEventFunctions.useValue;
|
|
3916
|
+
/** Sets the attachment service on window.ph */
|
|
3917
|
+
const setAttachmentService = attachmentServiceEventFunctions.setValue;
|
|
3918
|
+
/** Registers the attachmentService window event handler */
|
|
3919
|
+
const addAttachmentServiceEventHandler = attachmentServiceEventFunctions.addEventHandler;
|
|
3920
|
+
//#endregion
|
|
3921
|
+
//#region src/hooks/features.ts
|
|
3922
|
+
const featuresEventFunctions = makePHEventFunctions("features");
|
|
3923
|
+
const useFeatures = featuresEventFunctions.useValue;
|
|
3924
|
+
const setFeatures = featuresEventFunctions.setValue;
|
|
3925
|
+
const addFeaturesEventHandler = featuresEventFunctions.addEventHandler;
|
|
3926
|
+
//#endregion
|
|
3927
|
+
//#region src/hooks/use-drop-target.ts
|
|
3928
|
+
function useDropTarget() {
|
|
3929
|
+
const [isDropTarget, setIsDropTarget] = useState(false);
|
|
3930
|
+
const isDragAndDropEnabled = useIsDragAndDropEnabled();
|
|
3931
|
+
const targetSetter = funnel(() => setIsDropTarget(true), {
|
|
3932
|
+
triggerAt: "start",
|
|
3933
|
+
minQuietPeriodMs: 100
|
|
3934
|
+
});
|
|
3935
|
+
const targetUnsetter = funnel(() => setIsDropTarget(false), {
|
|
3936
|
+
triggerAt: "start",
|
|
3937
|
+
minQuietPeriodMs: 100
|
|
3938
|
+
});
|
|
3939
|
+
function setTarget() {
|
|
3940
|
+
if (!isDragAndDropEnabled) return;
|
|
3941
|
+
targetUnsetter.cancel();
|
|
3942
|
+
targetSetter.call();
|
|
3943
|
+
}
|
|
3944
|
+
function unsetTarget() {
|
|
3945
|
+
if (!isDragAndDropEnabled) return;
|
|
3946
|
+
targetSetter.cancel();
|
|
3947
|
+
targetUnsetter.call();
|
|
3948
|
+
}
|
|
3949
|
+
return {
|
|
3950
|
+
isDropTarget,
|
|
3951
|
+
setTarget,
|
|
3952
|
+
unsetTarget
|
|
3953
|
+
};
|
|
3954
|
+
}
|
|
3955
|
+
//#endregion
|
|
3956
|
+
//#region src/hooks/node-drag-and-drop.ts
|
|
3957
|
+
const draggingNodeEventFunctions = makePHEventFunctions("draggingNode");
|
|
3958
|
+
const useDraggingNode = draggingNodeEventFunctions.useValue;
|
|
3959
|
+
const setDraggingNode = draggingNodeEventFunctions.setValue;
|
|
3960
|
+
const addDraggingNodeEventHandler = draggingNodeEventFunctions.addEventHandler;
|
|
3961
|
+
const draggingNodeSetter = funnel((node) => setDraggingNode(node), {
|
|
3962
|
+
reducer: (_, newNode) => newNode,
|
|
3963
|
+
triggerAt: "start",
|
|
3964
|
+
minQuietPeriodMs: 100
|
|
3965
|
+
});
|
|
3966
|
+
const draggingNodeUnsetter = funnel(() => setDraggingNode(void 0), {
|
|
3967
|
+
triggerAt: "start",
|
|
3968
|
+
minQuietPeriodMs: 100
|
|
3969
|
+
});
|
|
3970
|
+
function setDragging(node) {
|
|
3971
|
+
draggingNodeUnsetter.cancel();
|
|
3972
|
+
draggingNodeSetter.call(node);
|
|
3973
|
+
}
|
|
3974
|
+
function unsetDragging() {
|
|
3975
|
+
draggingNodeSetter.cancel();
|
|
3976
|
+
draggingNodeUnsetter.call();
|
|
3977
|
+
}
|
|
3978
|
+
const isNodeDrag = (params) => conditional(params, [({ srcId }) => isNot(isTruthy)(srcId), constant(false)], [({ driveId }) => isNot(isTruthy)(driveId), constant(false)], [({ driveId, srcId }) => isStrictEqual(driveId, srcId), constant(false)], constant(true));
|
|
3979
|
+
function useDragNode(args) {
|
|
3980
|
+
const { srcId, parentId } = args;
|
|
3981
|
+
const driveId = useSelectedDriveId();
|
|
3982
|
+
const draggingNodeId = useDraggingNode()?.srcId;
|
|
3983
|
+
const params = {
|
|
3984
|
+
driveId,
|
|
3985
|
+
srcId,
|
|
3986
|
+
parentId
|
|
3987
|
+
};
|
|
3988
|
+
const draggable = isNodeDrag(params);
|
|
3989
|
+
const isDragging = allPass({
|
|
3990
|
+
srcId,
|
|
3991
|
+
draggingNodeId
|
|
3992
|
+
}, [
|
|
3993
|
+
() => draggable,
|
|
3994
|
+
({ srcId }) => isString(srcId),
|
|
3995
|
+
({ draggingNodeId }) => isString(draggingNodeId),
|
|
3996
|
+
({ srcId, draggingNodeId }) => isStrictEqual(srcId, draggingNodeId)
|
|
3997
|
+
]);
|
|
3998
|
+
const onDragStart = () => {
|
|
3999
|
+
if (!draggable) return;
|
|
4000
|
+
setDragging(params);
|
|
4001
|
+
};
|
|
4002
|
+
const onDragEnd = () => {
|
|
4003
|
+
if (!draggable) return;
|
|
4004
|
+
unsetDragging();
|
|
4005
|
+
};
|
|
4006
|
+
return {
|
|
4007
|
+
isDragging,
|
|
4008
|
+
draggable,
|
|
4009
|
+
onDragStart,
|
|
4010
|
+
onDragEnd
|
|
4011
|
+
};
|
|
4012
|
+
}
|
|
4013
|
+
const isNodeDrop = (params) => conditional(params, [({ srcId }) => isNot(isTruthy)(srcId), constant(false)], [({ driveId }) => isNot(isDefined)(driveId), constant(false)], [({ srcId, targetId }) => isStrictEqual(srcId, targetId), constant(false)], [({ driveId, parentId, targetId }) => isNot(isTruthy)(parentId) && isStrictEqual(targetId, driveId), constant(false)], [({ targetId, parentId }) => isStrictEqual(targetId, parentId), constant(false)], constant(true));
|
|
4014
|
+
function useDropNode(targetId) {
|
|
4015
|
+
const driveId = useSelectedDriveId();
|
|
4016
|
+
const { srcId, parentId } = useDraggingNode() ?? {};
|
|
4017
|
+
const { isDropTarget, setTarget, unsetTarget } = useDropTarget();
|
|
4018
|
+
const params = {
|
|
4019
|
+
driveId,
|
|
4020
|
+
parentId,
|
|
4021
|
+
targetId,
|
|
4022
|
+
srcId
|
|
4023
|
+
};
|
|
4024
|
+
function handleNodeDrop(event, cb) {
|
|
4025
|
+
if (!isNodeDrop(params)) return;
|
|
4026
|
+
event.preventDefault();
|
|
4027
|
+
event.stopPropagation();
|
|
4028
|
+
cb?.();
|
|
4029
|
+
}
|
|
4030
|
+
const onDragEnter = (event) => handleNodeDrop(event);
|
|
4031
|
+
const onDragOver = (event) => handleNodeDrop(event, once(setTarget));
|
|
4032
|
+
const onDragLeave = (event) => handleNodeDrop(event, once(unsetTarget));
|
|
4033
|
+
const onDrop = (event) => handleNodeDrop(event, once(() => {
|
|
4034
|
+
unsetDragging();
|
|
4035
|
+
unsetTarget();
|
|
4036
|
+
moveNodeById(params).catch(console.error);
|
|
4037
|
+
}));
|
|
4038
|
+
return {
|
|
4039
|
+
isDropTarget,
|
|
4040
|
+
onDragEnter,
|
|
4041
|
+
onDragOver,
|
|
4042
|
+
onDragLeave,
|
|
4043
|
+
onDrop
|
|
4044
|
+
};
|
|
4045
|
+
}
|
|
4046
|
+
//#endregion
|
|
4047
|
+
//#region src/hooks/graphql-reactor-client.ts
|
|
4048
|
+
const graphQLReactorClientEventFunctions = makePHEventFunctions("reactorGraphQLClient");
|
|
4049
|
+
const useGraphQLReactorClient = graphQLReactorClientEventFunctions.useValue;
|
|
4050
|
+
const setGraphQLReactorClient = graphQLReactorClientEventFunctions.setValue;
|
|
4051
|
+
const addGraphQLReactorClientEventHandler = graphQLReactorClientEventFunctions.addEventHandler;
|
|
4052
|
+
//#endregion
|
|
4053
|
+
//#region src/hooks/package-discovery.ts
|
|
4054
|
+
const packageDiscoveryFunctions = makePHEventFunctions("packageDiscoveryService");
|
|
4055
|
+
const usePackageDiscoveryService = packageDiscoveryFunctions.useValue;
|
|
4056
|
+
const setPackageDiscoveryService = packageDiscoveryFunctions.setValue;
|
|
4057
|
+
const addPackageDiscoveryServiceEventHandler = packageDiscoveryFunctions.addEventHandler;
|
|
4058
|
+
//#endregion
|
|
4059
|
+
//#region src/hooks/sync-selection.ts
|
|
4060
|
+
/** Applies a path's selection without writing the URL; idempotent.
|
|
4061
|
+
* @deprecated Set the store's `navigation`; its route loaders write the selection. */
|
|
4062
|
+
function syncSelectionFromPath(pathname = getCurrentPathname()) {
|
|
4063
|
+
const drives = getPHStore()?.drives;
|
|
4064
|
+
if (!drives) return;
|
|
4065
|
+
const driveSlug = extractDriveSlugFromPath(pathname);
|
|
4066
|
+
const selectedDriveId = getPHStore()?.selectedDriveId;
|
|
4067
|
+
if (!driveSlug) {
|
|
4068
|
+
if (selectedDriveId) selectDrive(void 0);
|
|
4069
|
+
return;
|
|
4070
|
+
}
|
|
4071
|
+
const drive = findDriveBySlug(drives, driveSlug);
|
|
4072
|
+
const selectedIsUnlisted = !!selectedDriveId && !drives.some((d) => d.header.id === selectedDriveId);
|
|
4073
|
+
if (drive) {
|
|
4074
|
+
if (drive.header.id !== selectedDriveId) setSelectedDriveId(drive.header.id);
|
|
4075
|
+
} else if (!selectedIsUnlisted) {
|
|
4076
|
+
selectDrive(driveSlug);
|
|
4077
|
+
return;
|
|
4078
|
+
}
|
|
4079
|
+
const nodeId = extractNodeIdFromSlug(extractNodeSlugFromPath(pathname));
|
|
4080
|
+
if (nodeId !== getPHStore()?.selectedNodeId) setSelectedNodeId(nodeId);
|
|
4081
|
+
}
|
|
4082
|
+
setBrowserOpenSync(() => syncSelectionFromPath());
|
|
4083
|
+
function syncOnPopState() {
|
|
4084
|
+
if (hasHostNavigation()) return;
|
|
4085
|
+
syncSelectionFromPath(window.location.pathname);
|
|
4086
|
+
}
|
|
4087
|
+
let popStateHandlerAdded = false;
|
|
4088
|
+
/** Syncs the selection on back/forward when no host navigation is set.
|
|
4089
|
+
* @deprecated Set the store's `navigation`; its router handles back/forward. */
|
|
4090
|
+
function addSyncSelectionOnPopStateEventHandler() {
|
|
4091
|
+
if (popStateHandlerAdded) return;
|
|
4092
|
+
popStateHandlerAdded = true;
|
|
4093
|
+
window.addEventListener("popstate", syncOnPopState);
|
|
4094
|
+
}
|
|
4095
|
+
/** @deprecated Set the store's `navigation`; its router handles back/forward. */
|
|
4096
|
+
const addSetSelectedDriveOnPopStateEventHandler = addSyncSelectionOnPopStateEventHandler;
|
|
4097
|
+
/** @deprecated Set the store's `navigation`; its router handles back/forward. */
|
|
4098
|
+
const addSetSelectedNodeOnPopStateEventHandler = addSyncSelectionOnPopStateEventHandler;
|
|
4099
|
+
//#endregion
|
|
4100
|
+
//#region src/hooks/selected-timeline-item.ts
|
|
4101
|
+
const selectedTimelineItemEventFunctions = makePHEventFunctions("selectedTimelineItem");
|
|
4102
|
+
/** Returns the selected timeline item */
|
|
4103
|
+
const useSelectedTimelineItem = selectedTimelineItemEventFunctions.useValue;
|
|
4104
|
+
/** Sets the selected timeline item */
|
|
4105
|
+
const setSelectedTimelineItem = selectedTimelineItemEventFunctions.setValue;
|
|
4106
|
+
/** Adds event handler for selected timeline item */
|
|
4107
|
+
const addSelectedTimelineItemEventHandler = selectedTimelineItemEventFunctions.addEventHandler;
|
|
4108
|
+
//#endregion
|
|
4109
|
+
//#region src/hooks/timeline-revision.ts
|
|
4110
|
+
const selectedTimelineRevisionEventFunctions = makePHEventFunctions("selectedTimelineRevision");
|
|
4111
|
+
/** Returns the selected timeline revision. */
|
|
4112
|
+
const useSelectedTimelineRevision = selectedTimelineRevisionEventFunctions.useValue;
|
|
4113
|
+
/** Sets the selected timeline revision. */
|
|
4114
|
+
const setSelectedTimelineRevision = selectedTimelineRevisionEventFunctions.setValue;
|
|
4115
|
+
/** Adds an event handler for the selected timeline revision. */
|
|
4116
|
+
const addSelectedTimelineRevisionEventHandler = selectedTimelineRevisionEventFunctions.addEventHandler;
|
|
4117
|
+
//#endregion
|
|
4118
|
+
//#region src/hooks/toast.ts
|
|
4119
|
+
const toastEventFunctions = makePHEventFunctions("toast");
|
|
4120
|
+
/** Returns the toast function */
|
|
4121
|
+
const usePHToast = toastEventFunctions.useValue;
|
|
4122
|
+
/** Sets the toast function */
|
|
4123
|
+
const setPHToast = toastEventFunctions.setValue;
|
|
4124
|
+
/** Adds an event handler for the toast */
|
|
4125
|
+
const addToastEventHandler = toastEventFunctions.addEventHandler;
|
|
4126
|
+
//#endregion
|
|
4127
|
+
//#region src/hooks/add-ph-event-handlers.ts
|
|
4128
|
+
const commonGlobalEventHandlerFunctions = {
|
|
4129
|
+
loading: addLoadingEventHandler,
|
|
4130
|
+
drives: addDrivesEventHandler,
|
|
4131
|
+
backendAuth: addBackendAuthEventHandler,
|
|
4132
|
+
driveNodes: addDriveNodesEventHandler,
|
|
4133
|
+
selectedDriveId: () => {
|
|
4134
|
+
addSelectedDriveIdEventHandler();
|
|
4135
|
+
addSyncSelectionOnPopStateEventHandler();
|
|
4136
|
+
addResetSelectedNodeEventHandler();
|
|
4137
|
+
},
|
|
4138
|
+
selectedNodeId: () => {
|
|
4139
|
+
addSelectedNodeIdEventHandler();
|
|
4140
|
+
},
|
|
4141
|
+
documentCache: addDocumentCacheEventHandler,
|
|
4142
|
+
reactorGraphQLClient: addGraphQLReactorClientEventHandler,
|
|
4143
|
+
draggingNode: addDraggingNodeEventHandler
|
|
4144
|
+
};
|
|
4145
|
+
const phGlobalEventHandlerRegisterFunctions = {
|
|
4146
|
+
...commonGlobalEventHandlerFunctions,
|
|
4147
|
+
reactorClientModule: addReactorClientModuleEventHandler,
|
|
4148
|
+
reactorClient: addReactorClientEventHandler,
|
|
4149
|
+
reactor: addReactorHalvesEventHandler,
|
|
4150
|
+
fullReactorClient: addFullReactorClientEventHandler,
|
|
4151
|
+
attachmentService: addAttachmentServiceEventHandler,
|
|
4152
|
+
features: addFeaturesEventHandler,
|
|
4153
|
+
modal: addModalEventHandler,
|
|
4154
|
+
renown: addRenownEventHandler,
|
|
4155
|
+
vetraPackageManager: addVetraPackageManagerEventHandler,
|
|
4156
|
+
packageDiscoveryService: addPackageDiscoveryServiceEventHandler,
|
|
4157
|
+
selectedTimelineRevision: addSelectedTimelineRevisionEventHandler,
|
|
4158
|
+
selectedTimelineItem: addSelectedTimelineItemEventHandler,
|
|
4159
|
+
routerBasename: addRouterBasenameEventHandler,
|
|
4160
|
+
version: addVersionEventHandler,
|
|
4161
|
+
logLevel: addLogLevelEventHandler,
|
|
4162
|
+
requiresHardRefresh: addRequiresHardRefreshEventHandler,
|
|
4163
|
+
warnOutdatedApp: addWarnOutdatedAppEventHandler,
|
|
4164
|
+
studioMode: addStudioModeEventHandler,
|
|
4165
|
+
basePath: addBasePathEventHandler,
|
|
4166
|
+
versionCheckInterval: addVersionCheckIntervalEventHandler,
|
|
4167
|
+
cliVersion: addCliVersionEventHandler,
|
|
4168
|
+
fileUploadOperationsChunkSize: addFileUploadOperationsChunkSizeEventHandler,
|
|
4169
|
+
isDocumentModelSelectionSettingsEnabled: addIsDocumentModelSelectionSettingsEnabledEventHandler,
|
|
4170
|
+
gaTrackingId: addGaTrackingIdEventHandler,
|
|
4171
|
+
allowList: addAllowListEventHandler,
|
|
4172
|
+
defaultDrivesUrl: addDefaultDrivesUrlEventHandler,
|
|
4173
|
+
drivesPreserveStrategy: addDrivesPreserveStrategyEventHandler,
|
|
4174
|
+
allowedDocumentTypes: addAllowedDocumentTypesEventHandler,
|
|
4175
|
+
enabledEditors: addEnabledEditorsEventHandler,
|
|
4176
|
+
disabledEditors: addDisabledEditorsEventHandler,
|
|
4177
|
+
isAddDriveEnabled: addIsAddDriveEnabledEventHandler,
|
|
4178
|
+
isLocalDrivesEnabled: addIsLocalDrivesEnabledEventHandler,
|
|
4179
|
+
isPublicDrivesEnabled: addIsPublicDrivesEnabledEventHandler,
|
|
4180
|
+
isAddPublicDrivesEnabled: addIsAddPublicDrivesEnabledEventHandler,
|
|
4181
|
+
isDeletePublicDrivesEnabled: addIsDeletePublicDrivesEnabledEventHandler,
|
|
4182
|
+
isCloudDrivesEnabled: addIsCloudDrivesEnabledEventHandler,
|
|
4183
|
+
isAddCloudDrivesEnabled: addIsAddCloudDrivesEnabledEventHandler,
|
|
4184
|
+
isDeleteCloudDrivesEnabled: addIsDeleteCloudDrivesEnabledEventHandler,
|
|
4185
|
+
isAddLocalDrivesEnabled: addIsAddLocalDrivesEnabledEventHandler,
|
|
4186
|
+
isDeleteLocalDrivesEnabled: addIsDeleteLocalDrivesEnabledEventHandler,
|
|
4187
|
+
isDragAndDropEnabled: addIsDragAndDropEnabledEventHandler,
|
|
4188
|
+
isExternalControlsEnabled: addIsExternalControlsEnabledEventHandler,
|
|
4189
|
+
isEditorDebugModeEnabled: addIsEditorDebugModeEnabledEventHandler,
|
|
4190
|
+
isEditorReadModeEnabled: addIsEditorReadModeEnabledEventHandler,
|
|
4191
|
+
isRelationalProcessorsEnabled: addIsRelationalProcessorsEnabledEventHandler,
|
|
4192
|
+
isExternalRelationalProcessorsEnabled: addIsExternalRelationalProcessorsEnabledEventHandler,
|
|
4193
|
+
isAnalyticsEnabled: addIsAnalyticsEnabledEventHandler,
|
|
4194
|
+
isAnalyticsExternalProcessorsEnabled: addIsAnalyticsExternalProcessorsEnabledEventHandler,
|
|
4195
|
+
analyticsDatabaseName: addAnalyticsDatabaseNameEventHandler,
|
|
4196
|
+
isAnalyticsDatabaseWorkerEnabled: addIsAnalyticsDatabaseWorkerEnabledEventHandler,
|
|
4197
|
+
isDiffAnalyticsEnabled: addIsDiffAnalyticsEnabledEventHandler,
|
|
4198
|
+
isDriveAnalyticsEnabled: addIsDriveAnalyticsEnabledEventHandler,
|
|
4199
|
+
renownUrl: addRenownUrlEventHandler,
|
|
4200
|
+
renownNetworkId: addRenownNetworkIdEventHandler,
|
|
4201
|
+
renownChainId: addRenownChainIdEventHandler,
|
|
4202
|
+
switchboardUrl: addSwitchboardUrlEventHandler,
|
|
4203
|
+
renownAdapters: addRenownAdaptersEventHandler,
|
|
4204
|
+
sentryRelease: addSentryReleaseEventHandler,
|
|
4205
|
+
sentryDsn: addSentryDsnEventHandler,
|
|
4206
|
+
sentryEnv: addSentryEnvEventHandler,
|
|
4207
|
+
isSentryTracingEnabled: addIsSentryTracingEnabledEventHandler,
|
|
4208
|
+
isExternalProcessorsEnabled: addIsExternalProcessorsEnabledEventHandler,
|
|
4209
|
+
isExternalPackagesEnabled: addIsExternalPackagesEnabledEventHandler,
|
|
4210
|
+
toast: addToastEventHandler,
|
|
4211
|
+
navigation: () => {},
|
|
4212
|
+
aiTools: () => {}
|
|
4213
|
+
};
|
|
4214
|
+
function addPHEventHandlers() {
|
|
4215
|
+
callEventHandlerRegisterFunctions(phGlobalEventHandlerRegisterFunctions);
|
|
4216
|
+
}
|
|
4217
|
+
function callEventHandlerRegisterFunctions(registerFunctions) {
|
|
4218
|
+
forEachObj(registerFunctions, (fn) => fn());
|
|
4219
|
+
}
|
|
4220
|
+
//#endregion
|
|
4221
|
+
//#region src/graphql-client/graphql-reactor-provider.tsx
|
|
4222
|
+
/**
|
|
4223
|
+
* Registers the `window.ph` event handlers once per page.
|
|
4224
|
+
*
|
|
4225
|
+
* The `set*` helpers only dispatch CustomEvents - nothing writes `window.ph`
|
|
4226
|
+
* until `addPHEventHandlers` has registered the listeners that do. Registration
|
|
4227
|
+
* is guarded by a marker on `window` rather than a module-level flag so that a
|
|
4228
|
+
* hot module replacement, or two copies of this module, still register once.
|
|
4229
|
+
*/
|
|
4230
|
+
function ensurePHEventHandlers() {
|
|
4231
|
+
if (typeof window === "undefined" || window.__phEventHandlersRegistered) return;
|
|
4232
|
+
addPHEventHandlers();
|
|
4233
|
+
window.__phEventHandlersRegistered = true;
|
|
4234
|
+
}
|
|
4235
|
+
/**
|
|
4236
|
+
* Mounts a {@link GraphQLReactorClient} into the `window.ph` slots the
|
|
4237
|
+
* reactor-browser hooks read, so `useDocument`, `useDispatch` and
|
|
4238
|
+
* `useReactorClient` work below it against a Switchboard, with no reactor in
|
|
4239
|
+
* the bundle.
|
|
4240
|
+
*
|
|
4241
|
+
* It fills the document slots, plus `window.ph.vetraPackageManager` when
|
|
4242
|
+
* `documentModels` is given (a fixed {@link StaticPackageManager}, which makes
|
|
4243
|
+
* the document-model hooks work). The same modules go to the client itself, so
|
|
4244
|
+
* a dispatch of two or more actions is signed rather than refused.
|
|
4245
|
+
* `window.ph.reactorClientModule` always stays empty, so full-reactor surfaces
|
|
4246
|
+
* (drives, jobs, editor auto-discovery) find nothing - an app below this
|
|
4247
|
+
* provider renders components it imports itself.
|
|
4248
|
+
*
|
|
4249
|
+
* The client is built on the client only: on the server the slots stay empty
|
|
4250
|
+
* and the hooks report their normal loading states. The props are read once,
|
|
4251
|
+
* when the client is built - changing `url` afterwards does not rebuild it.
|
|
4252
|
+
*
|
|
4253
|
+
* The effect's cleanup disposes the cache and the client's socket, and the
|
|
4254
|
+
* effect rebuilds both if it runs again on the same client - which is what a
|
|
4255
|
+
* `StrictMode` mount does.
|
|
4256
|
+
*/
|
|
4257
|
+
function GraphQLReactorProvider({ url, tokenProvider, subscriptionsUrl, realtime, attachmentService, documentModels, children }) {
|
|
4258
|
+
const [client] = useState(() => typeof window === "undefined" ? void 0 : new GraphQLReactorClient({
|
|
4259
|
+
url,
|
|
4260
|
+
tokenProvider,
|
|
4261
|
+
subscriptionsUrl,
|
|
4262
|
+
realtime,
|
|
4263
|
+
documentModels
|
|
4264
|
+
}));
|
|
4265
|
+
useEffect(() => {
|
|
4266
|
+
if (!client) return;
|
|
4267
|
+
ensurePHEventHandlers();
|
|
4268
|
+
setReactorClient(client);
|
|
4269
|
+
const documentCache = new DocumentCache(client);
|
|
4270
|
+
setDocumentCache(documentCache);
|
|
4271
|
+
return () => {
|
|
4272
|
+
documentCache.dispose();
|
|
4273
|
+
client.dispose();
|
|
4274
|
+
};
|
|
4275
|
+
}, [client]);
|
|
4276
|
+
useEffect(() => {
|
|
4277
|
+
if (!attachmentService) return;
|
|
4278
|
+
ensurePHEventHandlers();
|
|
4279
|
+
setAttachmentService(attachmentService);
|
|
4280
|
+
}, [attachmentService]);
|
|
4281
|
+
useEffect(() => {
|
|
4282
|
+
if (!documentModels || documentModels.length === 0) return;
|
|
4283
|
+
ensurePHEventHandlers();
|
|
4284
|
+
setVetraPackageManager(new StaticPackageManager([packageFromDocumentModels(documentModels)]));
|
|
4285
|
+
}, [documentModels]);
|
|
4286
|
+
return /* @__PURE__ */ jsx(Fragment, { children });
|
|
4287
|
+
}
|
|
4288
|
+
/**
|
|
4289
|
+
* Returns the {@link GraphQLReactorClient} mounted by
|
|
4290
|
+
* {@link GraphQLReactorProvider}, or `undefined` when the slot holds something
|
|
4291
|
+
* else - the full in-browser reactor client, or nothing yet.
|
|
4292
|
+
*
|
|
4293
|
+
* `useReactorClient` is typed as the narrow `IReactorBrowserClient` subset both
|
|
4294
|
+
* implementations share. This is how a component reaches the light client's own
|
|
4295
|
+
* surface, i.e. `subgraph` and `request`.
|
|
4296
|
+
*
|
|
4297
|
+
* The narrowing is by brand, not by `instanceof`: a page can carry two copies
|
|
4298
|
+
* of this module - a bundled package with its own copy, or a hot-replaced one -
|
|
4299
|
+
* and `instanceof` would then answer `false` for a perfectly good client and
|
|
4300
|
+
* leave the component silently without one.
|
|
4301
|
+
*/
|
|
4302
|
+
function useSwitchboardClient() {
|
|
4303
|
+
const client = useReactorClient();
|
|
4304
|
+
return isGraphQLReactorClient(client) ? client : void 0;
|
|
4305
|
+
}
|
|
4306
|
+
//#endregion
|
|
4307
|
+
//#region src/graphql-client/switchboard-backend.ts
|
|
4308
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
|
|
4309
|
+
const DEFAULT_BATCH_REQUEST_TIMEOUT_MS = 12e4;
|
|
4310
|
+
const DEFAULT_BREAKER = Object.freeze({
|
|
4311
|
+
failures: 3,
|
|
4312
|
+
openMs: 3e4
|
|
4313
|
+
});
|
|
4314
|
+
function breakerSettings(breaker) {
|
|
4315
|
+
if (breaker === false) return {
|
|
4316
|
+
failures: Infinity,
|
|
4317
|
+
openMs: 0
|
|
4318
|
+
};
|
|
4319
|
+
return {
|
|
4320
|
+
...DEFAULT_BREAKER,
|
|
4321
|
+
...breaker
|
|
4322
|
+
};
|
|
4323
|
+
}
|
|
4324
|
+
const FACTS_QUERY = `
|
|
4325
|
+
query SwitchboardFacts {
|
|
4326
|
+
inspection {
|
|
4327
|
+
info {
|
|
4328
|
+
storage {
|
|
4329
|
+
engine
|
|
4330
|
+
persistence
|
|
4331
|
+
durable
|
|
4332
|
+
selfHeal
|
|
4333
|
+
}
|
|
4334
|
+
workflows
|
|
4335
|
+
syncChannels
|
|
4336
|
+
access {
|
|
4337
|
+
admin
|
|
4338
|
+
sql
|
|
4339
|
+
}
|
|
4340
|
+
}
|
|
4341
|
+
documentModels {
|
|
4342
|
+
documentType
|
|
4343
|
+
}
|
|
4344
|
+
}
|
|
4345
|
+
queries: __type(name: "Query") {
|
|
4346
|
+
fields {
|
|
4347
|
+
name
|
|
4348
|
+
}
|
|
4349
|
+
}
|
|
4350
|
+
inspectionFields: __type(name: "ReactorInspection") {
|
|
4351
|
+
fields {
|
|
4352
|
+
name
|
|
4353
|
+
}
|
|
4354
|
+
}
|
|
4355
|
+
}
|
|
4356
|
+
`;
|
|
4357
|
+
const MODEL_LOADING_QUERY = `
|
|
4358
|
+
query SwitchboardModelLoading {
|
|
4359
|
+
inspection {
|
|
4360
|
+
loadsModelsOnDemand
|
|
4361
|
+
}
|
|
4362
|
+
}
|
|
4363
|
+
`;
|
|
4364
|
+
/** Queries this backend sends that a Switchboard serves only from some version. */
|
|
4365
|
+
const REQUIRED_QUERIES = [
|
|
4366
|
+
"documentServed",
|
|
4367
|
+
"createDefaults",
|
|
4368
|
+
"inspection"
|
|
4369
|
+
];
|
|
4370
|
+
/** The Switchboard's circuit is open: nothing was sent. */
|
|
4371
|
+
var SwitchboardUnreachableError = class extends Error {
|
|
4372
|
+
backend;
|
|
4373
|
+
retryAt;
|
|
4374
|
+
name = "SwitchboardUnreachableError";
|
|
4375
|
+
constructor(backend, retryAt) {
|
|
4376
|
+
super(`Switchboard backend ${JSON.stringify(backend)} is unreachable; nothing is sent until ${new Date(retryAt).toISOString()}`);
|
|
4377
|
+
this.backend = backend;
|
|
4378
|
+
this.retryAt = retryAt;
|
|
4379
|
+
}
|
|
4380
|
+
};
|
|
4381
|
+
/**
|
|
4382
|
+
* Opens after `failures` transport failures in a row (a network error, a
|
|
4383
|
+
* deadline or a 5xx) and sends nothing for `openMs`. Any other answer, a
|
|
4384
|
+
* GraphQL error included, closes it. The first request after `openMs` goes
|
|
4385
|
+
* through; one more failure opens it again.
|
|
4386
|
+
*/
|
|
4387
|
+
var Breaker = class {
|
|
4388
|
+
backend;
|
|
4389
|
+
settings;
|
|
4390
|
+
consecutive = 0;
|
|
4391
|
+
openUntil;
|
|
4392
|
+
constructor(backend, settings) {
|
|
4393
|
+
this.backend = backend;
|
|
4394
|
+
this.settings = settings;
|
|
4395
|
+
}
|
|
4396
|
+
health() {
|
|
4397
|
+
return this.isOpen() ? "down" : "up";
|
|
4398
|
+
}
|
|
4399
|
+
wrap(inner) {
|
|
4400
|
+
return async (input, init) => {
|
|
4401
|
+
const openUntil = this.openUntil;
|
|
4402
|
+
if (openUntil !== void 0 && Date.now() < openUntil) throw new SwitchboardUnreachableError(this.backend, openUntil);
|
|
4403
|
+
let response;
|
|
4404
|
+
try {
|
|
4405
|
+
response = await inner(input, init);
|
|
4406
|
+
} catch (error) {
|
|
4407
|
+
if (!abortedByCaller(init?.signal)) this.fail();
|
|
4408
|
+
throw error;
|
|
4409
|
+
}
|
|
4410
|
+
if (response.status >= 500) this.fail();
|
|
4411
|
+
else {
|
|
4412
|
+
this.consecutive = 0;
|
|
4413
|
+
this.openUntil = void 0;
|
|
4414
|
+
}
|
|
4415
|
+
return response;
|
|
4416
|
+
};
|
|
4417
|
+
}
|
|
4418
|
+
isOpen() {
|
|
4419
|
+
return this.openUntil !== void 0 && Date.now() < this.openUntil;
|
|
4420
|
+
}
|
|
4421
|
+
fail() {
|
|
4422
|
+
this.consecutive += 1;
|
|
4423
|
+
if (this.consecutive >= this.settings.failures) this.openUntil = Date.now() + this.settings.openMs;
|
|
4424
|
+
}
|
|
4425
|
+
};
|
|
4426
|
+
function abortedByCaller(signal) {
|
|
4427
|
+
return Boolean(signal?.aborted) && !isDeadlineError(signal?.reason);
|
|
4428
|
+
}
|
|
4429
|
+
const NO_ACCESS = Object.freeze({
|
|
4430
|
+
admin: false,
|
|
4431
|
+
sql: false
|
|
4432
|
+
});
|
|
4433
|
+
/** Ids and slugs of documents this backend answered as drives, by drive id. */
|
|
4434
|
+
var KnownDrives = class {
|
|
4435
|
+
ids = /* @__PURE__ */ new Map();
|
|
4436
|
+
learn(document) {
|
|
4437
|
+
const { id, slug, documentType } = document.header;
|
|
4438
|
+
if (DRIVE_DOCUMENT_TYPES.includes(documentType)) {
|
|
4439
|
+
this.ids.set(id, id);
|
|
4440
|
+
if (slug) this.ids.set(slug, id);
|
|
4441
|
+
}
|
|
4442
|
+
return document;
|
|
4443
|
+
}
|
|
4444
|
+
learnPage(page) {
|
|
4445
|
+
for (const document of page.results) this.learn(document);
|
|
4446
|
+
return page;
|
|
4447
|
+
}
|
|
4448
|
+
/** Drops a drive the Switchboard refused, by id and by slug. */
|
|
4449
|
+
forget(driveId) {
|
|
4450
|
+
for (const [identifier, id] of this.ids) if (id === driveId) this.ids.delete(identifier);
|
|
4451
|
+
}
|
|
4452
|
+
driveOf(identifier) {
|
|
4453
|
+
return identifier === void 0 ? void 0 : this.ids.get(identifier);
|
|
4454
|
+
}
|
|
4455
|
+
/** Names a drive only when this backend proved it is one. */
|
|
4456
|
+
driveIdFor = (call) => {
|
|
4457
|
+
switch (call.method) {
|
|
4458
|
+
case "create":
|
|
4459
|
+
case "find": return this.driveOf(call.parentId);
|
|
4460
|
+
case "execute":
|
|
4461
|
+
case "deleteDocument": return this.driveOf(call.documentId);
|
|
4462
|
+
case "executeBatch":
|
|
4463
|
+
for (const job of call.jobs ?? []) {
|
|
4464
|
+
const drive = this.driveOf(job.documentId);
|
|
4465
|
+
if (drive !== void 0) return drive;
|
|
4466
|
+
}
|
|
4467
|
+
return;
|
|
4468
|
+
}
|
|
4469
|
+
};
|
|
4470
|
+
/** Runs a call that may carry `Drive-Id`; a 421 forgets the drive it named. */
|
|
4471
|
+
async refusable(call) {
|
|
4472
|
+
try {
|
|
4473
|
+
return await call;
|
|
4474
|
+
} catch (error) {
|
|
4475
|
+
if (GraphQLWrongBackendError.isError(error)) this.forget(error.driveId);
|
|
4476
|
+
throw error;
|
|
4477
|
+
}
|
|
4478
|
+
}
|
|
4479
|
+
};
|
|
4480
|
+
function isUnknownJob(job) {
|
|
4481
|
+
return job.status === "FAILED" && job.error?.name === "JobNotFoundError";
|
|
4482
|
+
}
|
|
4483
|
+
/** A Switchboard as a router backend; members GraphQL cannot serve are absent. */
|
|
4484
|
+
function createSwitchboardBackend(descriptor) {
|
|
4485
|
+
const drives = new KnownDrives();
|
|
4486
|
+
const breaker = new Breaker(descriptor.name, breakerSettings(descriptor.breaker));
|
|
4487
|
+
const signer = descriptor.signer;
|
|
4488
|
+
const gql = new GraphQLReactorClient({
|
|
4489
|
+
url: descriptor.url,
|
|
4490
|
+
tokenProvider: descriptor.tokenProvider,
|
|
4491
|
+
signer: typeof signer === "function" ? signer : () => signer,
|
|
4492
|
+
documentModels: descriptor.documentModels,
|
|
4493
|
+
realtime: descriptor.realtime,
|
|
4494
|
+
driveIdFor: drives.driveIdFor,
|
|
4495
|
+
requestTimeoutMs: descriptor.requestTimeoutMs ?? 3e4,
|
|
4496
|
+
batchRequestTimeoutMs: descriptor.batchRequestTimeoutMs ?? 12e4,
|
|
4497
|
+
fetch: breaker.wrap(descriptor.fetch ?? switchboardFetch)
|
|
4498
|
+
});
|
|
4499
|
+
const backend = {
|
|
4500
|
+
supports: {
|
|
4501
|
+
find: findIsServableOverGraphQL,
|
|
4502
|
+
pointInTimeViews: false
|
|
4503
|
+
},
|
|
4504
|
+
health: () => breaker.health(),
|
|
4505
|
+
drives: gql.read.drives,
|
|
4506
|
+
driveNodes: gql.nodeSource(),
|
|
4507
|
+
driveFileLinkTypes: ["child", DRIVE_CHILD_RELATIONSHIP_TYPE],
|
|
4508
|
+
submit: { execute: (identifier, branch, actions, signal) => drives.refusable(gql.executeAsync(identifier, branch, actions, signal)) },
|
|
4509
|
+
get: async (identifier, view, signal, consistencyToken) => drives.learn(await gql.get(identifier, view, signal, consistencyToken)),
|
|
4510
|
+
getMany: async (ids, view, signal) => (await gql.getMany(ids, view, signal)).map((document) => drives.learn(document)),
|
|
4511
|
+
getOperations: (identifier, view, filter, paging, signal) => gql.getOperations(identifier, view, filter, paging, signal),
|
|
4512
|
+
find: async (search, view, paging, signal) => drives.learnPage(await drives.refusable(gql.find(search, view, paging, signal))),
|
|
4513
|
+
isServed: (identifier, view, signal) => gql.isServed(identifier, view, signal),
|
|
4514
|
+
getOutgoingRelationships: (source, type, view, paging, signal) => gql.getOutgoingRelationships(source, type, view, paging, signal),
|
|
4515
|
+
getIncomingRelationships: (target, type, view, paging, signal) => gql.getIncomingRelationships(target, type, view, paging, signal),
|
|
4516
|
+
getOutgoingRelationshipEdges: (source, type, view, paging, signal) => gql.getOutgoingRelationshipEdges(source, type, view, paging, signal),
|
|
4517
|
+
getIncomingRelationshipEdges: (target, type, view, paging, signal) => gql.getIncomingRelationshipEdges(target, type, view, paging, signal),
|
|
4518
|
+
subscribe: (search, callback, view) => gql.subscribe(search, callback, view),
|
|
4519
|
+
getCreateSignaturePolicy: () => gql.getCreateSignaturePolicy(),
|
|
4520
|
+
getCreateProtocolVersions: (options, signal) => gql.getCreateProtocolVersions(options, signal),
|
|
4521
|
+
create: async (document, parent, signal) => drives.learn(await drives.refusable(gql.create(document, parent, signal))),
|
|
4522
|
+
execute: async (identifier, branch, actions, signal) => drives.learn(await drives.refusable(gql.execute(identifier, branch, actions, signal))),
|
|
4523
|
+
executeBatch: (request, signal) => drives.refusable(gql.executeBatch(request, signal)),
|
|
4524
|
+
deleteDocument: (identifier, propagate, signal) => drives.refusable(gql.deleteDocument(identifier, propagate, signal)),
|
|
4525
|
+
setPreferredEditor: (identifier, editor, branch, signal) => gql.setPreferredEditor(identifier, editor, branch, signal),
|
|
4526
|
+
getJob: async (jobId, signal) => {
|
|
4527
|
+
const job = await gql.getJob(jobId, signal);
|
|
4528
|
+
return job && isUnknownJob(job) ? void 0 : job;
|
|
4529
|
+
},
|
|
4530
|
+
waitForJob: (job, signal) => gql.waitForJob(job, signal),
|
|
4531
|
+
undo: async (identifier, scope, branch, signal) => drives.learn(await drives.refusable(gql.undo(identifier, scope, branch, signal))),
|
|
4532
|
+
redo: async (identifier, scope, branch, signal) => drives.learn(await drives.refusable(gql.redo(identifier, scope, branch, signal))),
|
|
4533
|
+
undoRedoTargets: (identifier, scope, view, signal) => gql.undoRedoTargets(identifier, scope, view, signal),
|
|
4534
|
+
undoRedoAvailability: (identifier, scope, branch, signal) => gql.undoRedoAvailability(identifier, scope, branch, signal)
|
|
4535
|
+
};
|
|
4536
|
+
let reading;
|
|
4537
|
+
const read = () => reading ??= readFacts(gql, descriptor.url).finally(() => {
|
|
4538
|
+
reading = void 0;
|
|
4539
|
+
});
|
|
4540
|
+
return {
|
|
4541
|
+
config: {
|
|
4542
|
+
name: descriptor.name,
|
|
4543
|
+
backend,
|
|
4544
|
+
facts: async () => (await read()).info,
|
|
4545
|
+
documentTypes: async () => (await read()).documentTypes,
|
|
4546
|
+
reach: {
|
|
4547
|
+
hosting: "remote",
|
|
4548
|
+
inspection: descriptor.inspection ?? "rpc"
|
|
4549
|
+
},
|
|
4550
|
+
refusesMisroutes: false
|
|
4551
|
+
},
|
|
4552
|
+
notifyCredentialsChanged: () => gql.notifyCredentialsChanged(),
|
|
4553
|
+
dispose: () => gql.dispose()
|
|
4554
|
+
};
|
|
4555
|
+
}
|
|
4556
|
+
function fieldNames(type) {
|
|
4557
|
+
return new Set(type?.fields?.map((field) => field.name));
|
|
4558
|
+
}
|
|
4559
|
+
async function readFacts(gql, url) {
|
|
4560
|
+
const answer = await gql.request(FACTS_QUERY);
|
|
4561
|
+
const served = fieldNames(answer.queries);
|
|
4562
|
+
const missing = REQUIRED_QUERIES.filter((query) => !served.has(query));
|
|
4563
|
+
if (missing.length > 0) throw new Error(`The Switchboard at ${url} does not serve ${missing.join(", ")}; it is older than this client`);
|
|
4564
|
+
const { info, documentModels } = answer.inspection;
|
|
4565
|
+
const closed = fieldNames(answer.inspectionFields).has("loadsModelsOnDemand") && !(await gql.request(MODEL_LOADING_QUERY)).inspection.loadsModelsOnDemand;
|
|
4566
|
+
return {
|
|
4567
|
+
info: {
|
|
4568
|
+
...info,
|
|
4569
|
+
access: info.access ?? NO_ACCESS
|
|
4570
|
+
},
|
|
4571
|
+
documentTypes: closed ? documentModels.map((model) => model.documentType) : void 0
|
|
4572
|
+
};
|
|
4573
|
+
}
|
|
4574
|
+
//#endregion
|
|
4575
|
+
//#region src/hooks/document-operations.ts
|
|
4576
|
+
const DEFAULT_LIMIT = 100;
|
|
4577
|
+
function toError(reason) {
|
|
4578
|
+
return reason instanceof Error ? reason : new Error(String(reason));
|
|
4579
|
+
}
|
|
4580
|
+
const EMPTY_OPERATIONS = [];
|
|
4581
|
+
function useScopeOperations(documentId, scope, options = {}) {
|
|
4582
|
+
const { limit = DEFAULT_LIMIT, enabled = true } = options;
|
|
4583
|
+
const documentCache = useDocumentCache();
|
|
4584
|
+
const cache = documentCache && isOperationCache(documentCache) ? documentCache : void 0;
|
|
4585
|
+
const activeId = enabled && cache && documentId ? documentId : void 0;
|
|
4586
|
+
const getEntry = () => activeId && cache ? cache.getOperationsState(activeId, scope) : IDLE_OPERATIONS_ENTRY;
|
|
4587
|
+
const entry = useSyncExternalStore((onChange) => activeId && cache ? cache.subscribeOperations(activeId, onChange) : () => {}, getEntry, getEntry);
|
|
4588
|
+
useEffect(() => {
|
|
4589
|
+
if (activeId && cache && entry.status === "idle") cache.loadOperations(activeId, scope, limit);
|
|
4590
|
+
}, [
|
|
4591
|
+
activeId,
|
|
4592
|
+
cache,
|
|
4593
|
+
scope,
|
|
4594
|
+
limit,
|
|
4595
|
+
entry.status
|
|
4596
|
+
]);
|
|
4597
|
+
const fetchNextPage = useCallback(() => {
|
|
4598
|
+
if (activeId && cache) cache.loadMoreOperations(activeId, scope);
|
|
4599
|
+
}, [
|
|
4600
|
+
activeId,
|
|
4601
|
+
cache,
|
|
4602
|
+
scope
|
|
4603
|
+
]);
|
|
4604
|
+
const refetch = useCallback(() => {
|
|
4605
|
+
if (activeId && cache) cache.invalidateOperations(activeId);
|
|
4606
|
+
}, [activeId, cache]);
|
|
4607
|
+
const error = useMemo(() => entry.status === "error" ? toError(entry.error) : void 0, [entry.status, entry.error]);
|
|
4608
|
+
return {
|
|
4609
|
+
operations: entry.operations,
|
|
4610
|
+
isLoading: entry.status === "pending" || !!activeId && entry.status === "idle",
|
|
4611
|
+
error,
|
|
4612
|
+
hasNextPage: entry.hasNextPage,
|
|
4613
|
+
fetchNextPage,
|
|
4614
|
+
refetch
|
|
4615
|
+
};
|
|
4616
|
+
}
|
|
4617
|
+
/** Keeps paging `result` to completion while `enabled` is true. */
|
|
4618
|
+
function useLoadAllPages(result, enabled) {
|
|
4619
|
+
useEffect(() => {
|
|
4620
|
+
if (!enabled || !result.hasNextPage || result.isLoading) return;
|
|
4621
|
+
const handle = window.setTimeout(result.fetchNextPage, 0);
|
|
4622
|
+
return () => window.clearTimeout(handle);
|
|
4623
|
+
}, [
|
|
4624
|
+
enabled,
|
|
4625
|
+
result.hasNextPage,
|
|
4626
|
+
result.isLoading,
|
|
4627
|
+
result.fetchNextPage
|
|
4628
|
+
]);
|
|
4629
|
+
}
|
|
4630
|
+
function useDocumentOperations(documentId, scope, options = {}) {
|
|
4631
|
+
const legacy = scope === void 0;
|
|
4632
|
+
const primary = useScopeOperations(documentId, legacy ? "global" : scope, legacy ? {} : options);
|
|
4633
|
+
const local = useScopeOperations(documentId, "local", { enabled: legacy });
|
|
4634
|
+
useLoadAllPages(primary, legacy);
|
|
4635
|
+
useLoadAllPages(local, legacy);
|
|
4636
|
+
const globalOperations = useMemo(() => legacy ? [...primary.operations] : EMPTY_OPERATIONS, [legacy, primary.operations]);
|
|
4637
|
+
const localOperations = useMemo(() => legacy ? [...local.operations] : EMPTY_OPERATIONS, [legacy, local.operations]);
|
|
4638
|
+
const refetch = useCallback(() => {
|
|
4639
|
+
primary.refetch();
|
|
4640
|
+
local.refetch();
|
|
4641
|
+
}, [primary.refetch, local.refetch]);
|
|
4642
|
+
const error = primary.error ?? local.error;
|
|
4643
|
+
const legacyResult = useMemo(() => ({
|
|
4644
|
+
globalOperations,
|
|
4645
|
+
localOperations,
|
|
4646
|
+
isLoading: !error && (primary.isLoading || local.isLoading || primary.hasNextPage || local.hasNextPage),
|
|
4647
|
+
error,
|
|
4648
|
+
refetch
|
|
4649
|
+
}), [
|
|
4650
|
+
globalOperations,
|
|
4651
|
+
localOperations,
|
|
4652
|
+
error,
|
|
4653
|
+
primary.isLoading,
|
|
4654
|
+
local.isLoading,
|
|
4655
|
+
primary.hasNextPage,
|
|
4656
|
+
local.hasNextPage,
|
|
4657
|
+
refetch
|
|
4658
|
+
]);
|
|
4659
|
+
return legacy ? legacyResult : primary;
|
|
4660
|
+
}
|
|
4661
|
+
//#endregion
|
|
4662
|
+
export { addIsAddDriveEnabledEventHandler as $, copyNode$1 as $i, useIsDeleteLocalDrivesEnabled as $n, isGraphQLReactorClient as $r, setIsAnalyticsDatabaseWorkerEnabled as $t, setGraphQLReactorClient as A, addModalEventHandler as Aa, phDocumentFromGetDocument as Ai, setSwitchboardUrl as An, addIsDragAndDropEnabledEventHandler as Ar, addSentryEnvEventHandler as At, setAttachmentService as B, useModalLinkProps as Ba, underSignaturePolicy as Bi, useDrivesPreserveStrategy as Bn, useAllowedDocumentTypes as Br, setAnalyticsDatabaseName as Bt, addSetSelectedNodeOnPopStateEventHandler as C, usePGlite as Ca, switchboardFetch as Ci, setRenownUrl as Cn, useSentryRelease as Cr, addRenownAdaptersEventHandler as Ct, setPackageDiscoveryService as D, useSync as Da, GraphQLDriveReadClient as Di, setSentryEnv as Dn, useVersionCheckInterval as Dr, addRequiresHardRefreshEventHandler as Dt, addPackageDiscoveryServiceEventHandler as E, useReactorHalves as Ea, GraphQLDriveNodeSource as Ei, setSentryDsn as En, useVersion as Er, addRenownUrlEventHandler as Et, useDropTarget as F, modalSearch as Fa, convertRemoteOperations as Fi, useAnalyticsDatabaseName as Fn, phDocumentEditorConfigHooks as Fr, addVersionEventHandler as Ft, addCliVersionEventHandler as G, usePHNavigation as Ga, GraphQLOperationNotSupportedError as Gi, useIsAddDriveEnabled as Gn, isBackendAuthError as Gr, setDrivesPreserveStrategy as Gt, addAllowListEventHandler as H, withoutModalSearch as Ha, DEFAULT_DRIVE_EDITOR_ID as Hi, useFileUploadOperationsChunkSize as Hn, useIsExternalControlsEnabled as Hr, setCliVersion as Ht, addFeaturesEventHandler as I, setPHModal as Ia, 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, useSearchParams as Ka, GraphQLWrongBackendError as Ki, useIsAddLocalDrivesEnabled as Kn, recordBackendAuthError as Kr, setEnabledEditors as Kt, setFeatures as L, showCreateDocumentModal as La, hasRevisionConflict as Li, useCliVersion as Ln, setAllowedDocumentTypes as Lr, phGlobalConfigHooks as Lt, addDraggingNodeEventHandler as M, isRoutedModal as Ma, revisionMapFromRevisionsList as Mi, setVersionCheckInterval as Mn, isExternalControlsEnabledEventFunctions as Mr, addStudioModeEventHandler as Mt, useDragNode as N, modalFromSearch as Na, ConflictError as Ni, setWarnOutdatedApp as Nn, phAppConfigHooks as Nr, addSwitchboardUrlEventHandler as Nt, usePackageDiscoveryService as O, useSyncList as Oa, toLegacyNode as Oi, setSentryRelease as On, useWarnOutdatedApp as Or, addRouterBasenameEventHandler as Ot, useDropNode as P, modalHref as Pa, 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, showDeleteNodeModal as Ra, screamingSnakeToCamel as Ri, useDefaultDrivesUrl as Rn, setIsDragAndDropEnabled as Rr, phGlobalConfigSetters as Rt, addSetSelectedDriveOnPopStateEventHandler as S, useModelRegistry as Sa, isNodeFetch as Si, setRenownNetworkId as Sn, useSentryEnv as Sr, addLogLevelEventHandler as St, syncSelectionFromPath as T, useReactorClientModule as Ta, withStreamedBodies as Ti, setRouterBasename as Tn, useSwitchboardUrl as Tr, addRenownNetworkIdEventHandler as Tt, addAnalyticsDatabaseNameEventHandler as U, isPlainClick as Ua, DRIVE_DOCUMENT_TYPES as Ui, useGaTrackingId as Un, addBackendAuthEventHandler as Ur, setDefaultDrivesUrl as Ut, useAttachmentService as V, usePHModal as Va, COMMON_PACKAGE_ID as Vi, useEnabledEditors as Vn, useIsDragAndDropEnabled as Vr, setBasePath as Vt, addBasePathEventHandler as W, useLinkProps as Wa, 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 _, getFullReactorClient 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, setReactorClientModule 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, addReactorHalvesEventHandler as ga, MutateDocumentWithOperationsDocument as gi, setIsRelationalProcessorsEnabled as gn, useRenownChainId as gr, addIsExternalRelationalProcessorsEnabledEventHandler as gt, usePHToast as h, addReactorClientModuleEventHandler 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, closePHModal as ja, phDocumentFromMutation as ji, setVersion as jn, addIsExternalControlsEnabledEventHandler as jr, addSentryReleaseEventHandler as jt, addGraphQLReactorClientEventHandler as k, MODAL_SEARCH_PARAM 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, addReactorClientEventHandler 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, addFullReactorClientEventHandler as pa, signStampedAction as pi, setIsExternalRelationalProcessorsEnabled as pn, useLocalDrivesEnabled as pr, addIsEditorReadModeEnabledEventHandler as pt, addDisabledEditorsEventHandler as q, useSetSearchParams as qa, 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, setFullReactorClient as va, readCreateProtocolVersions as vi, setLocalDrivesEnabled as vn, useRenownUrl as vr, addIsPublicDrivesEnabledEventHandler as vt, addSyncSelectionOnPopStateEventHandler as w, useReactorClient as wa, withRequestDeadline as wi, setRequiresHardRefresh as wn, useStudioMode as wr, addRenownChainIdEventHandler as wt, useSelectedTimelineItem as x, useDatabase as xa, isDeadlineError as xi, setRenownChainId as xn, useSentryDsn as xr, addLocalDrivesEnabledEventHandler as xt, addSelectedTimelineItemEventHandler as y, setReactorClient as ya, readCreateSignaturePolicy as yi, setLogLevel as yn, useRequiresHardRefresh as yr, addIsRelationalProcessorsEnabledEventHandler as yt, addAttachmentServiceEventHandler as z, showPHModal as za, uncreatedDocument as zi, useDisabledEditors as zn, setIsExternalControlsEnabled as zr, setAllowList as zt };
|
|
4663
|
+
|
|
4664
|
+
//# sourceMappingURL=document-operations-QtU34A52.js.map
|