-
Notifications
You must be signed in to change notification settings - Fork 162
/
hook.ts
executable file
·298 lines (261 loc) · 8.56 KB
/
hook.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import type { ApolloClient, ApolloError } from "@apollo/client";
// Note that we are intentionally not using Apollo Client's gql and
// Observable exports, as we don't want Apollo Client and its dependencies
// to be loaded into each browser tab, when this hook triggered.
import Observable from "zen-observable";
import type { DefinitionNode } from "graphql/language";
type Writable<T> = { -readonly [P in keyof T]: T[P] };
// All manifests should contain the same version number so it shouldn't matter
// which one we import from.
import * as manifest from "../chrome/manifest.json";
const { version: devtoolsVersion } = manifest;
import type { QueryInfo } from "./helpers";
import {
getQueries,
getQueriesLegacy,
getMutations,
getMainDefinition,
} from "./helpers";
import type { QueryResult } from "../../types";
import { getPrivateAccess } from "../../privateAccess";
import type { JSONObject } from "../../application/types/json";
import { createWindowActor } from "../actor";
import type { ClientMessage, DevtoolsRPCMessage } from "../messages";
import { createWindowMessageAdapter } from "../messageAdapters";
import { createRpcClient, createRpcHandler } from "../rpc";
import type { ErrorCodesHandler } from "../background/errorcodes";
import { loadErrorCodes } from "./loadErrorCodes";
declare global {
type TCache = any;
interface Window {
__APOLLO_CLIENT__?: ApolloClient<TCache>;
[DEVTOOLS_KEY]?: {
push(client: ApolloClient<any>): void;
};
}
}
type Hook = {
ApolloClient: ApolloClient<any> | undefined;
version: string;
getQueries: () => QueryInfo[];
getMutations: () => QueryInfo[];
getCache: () => JSONObject;
};
const DEVTOOLS_KEY = Symbol.for("apollo.devtools");
const tab = createWindowActor<ClientMessage>(window);
const messageAdapter = createWindowMessageAdapter(window);
const handleRpc = createRpcHandler<DevtoolsRPCMessage>(messageAdapter);
const rpcClient = createRpcClient<ErrorCodesHandler>(messageAdapter);
const knownClients = new Set<ApolloClient<any>>();
const hook: Hook = {
ApolloClient: undefined,
version: devtoolsVersion,
getQueries() {
const ac = getPrivateAccess(hook.ApolloClient);
if (ac?.queryManager.getObservableQueries) {
return getQueries(ac.queryManager.getObservableQueries("active"));
} else {
return getQueriesLegacy(ac?.queryManager["queries"]);
}
},
getMutations: () => {
const ac = getPrivateAccess(hook.ApolloClient);
return getMutations(
(ac?.queryManager.mutationStore?.getStore
? // @ts-expect-error Apollo Client 3.0 - 3.2
ac.queryManager.mutationStore?.getStore()
: // Apollo Client 3.3
ac?.queryManager.mutationStore) ?? {}
);
},
getCache: () => hook.ApolloClient?.cache.extract(true) ?? {},
};
Object.defineProperty(window, "__APOLLO_DEVTOOLS_GLOBAL_HOOK__", {
get() {
return hook;
},
configurable: true,
});
// Listen for tab refreshes
window.onbeforeunload = () => {
tab.send({ type: "disconnectFromDevtools" });
};
window.addEventListener("load", () => {
if (hook.ApolloClient) {
sendHookDataToDevTools("connectToDevtools");
}
});
function getClientData() {
// We need to JSON stringify the data here in case the cache contains
// references to irregular data such as `URL` instances which are not
// cloneable via `structuredClone` (which `window.postMessage` uses to
// send messages). `JSON.stringify` does however serialize `URL`s into
// strings properly, so this should ensure that the cache data will be
// sent without errors.
//
// https://github.com/apollographql/apollo-client-devtools/issues/1258
return JSON.parse(
JSON.stringify({
queries: hook.getQueries(),
mutations: hook.getMutations(),
cache: hook.getCache(),
})
) as { queries: QueryInfo[]; mutations: QueryInfo[]; cache: JSONObject };
}
handleRpc("getClientOperations", getClientData);
function sendHookDataToDevTools(eventName: "connectToDevtools") {
tab.send({
type: eventName,
payload: getClientData(),
});
}
tab.on("connectToClient", () => {
if (hook.ApolloClient) {
sendHookDataToDevTools("connectToDevtools");
} else {
findClient();
}
});
tab.on("explorerRequest", (message) => {
const {
operation: queryAst,
operationName,
fetchPolicy,
variables,
} = message.payload;
const clonedQueryAst = structuredClone(queryAst) as Writable<typeof queryAst>;
const filteredDefinitions = clonedQueryAst.definitions.reduce(
(acumm: DefinitionNode[], curr) => {
if (
(curr.kind === "OperationDefinition" &&
curr.name?.value === operationName) ||
curr.kind !== "OperationDefinition"
) {
acumm.push(curr);
}
return acumm;
},
[]
);
clonedQueryAst.definitions = filteredDefinitions;
const definition = getMainDefinition(clonedQueryAst);
const operation = (() => {
if (
definition.kind === "OperationDefinition" &&
definition.operation === "mutation"
) {
return new Observable<QueryResult>((observer) => {
hook.ApolloClient?.mutate({
mutation: clonedQueryAst,
variables,
}).then((result) => {
observer.next(result as QueryResult);
});
});
} else {
return hook.ApolloClient?.watchQuery({
query: clonedQueryAst,
variables,
fetchPolicy,
});
}
})();
const operationObservable = operation?.subscribe(
(response: QueryResult) => {
tab.send({
type: "explorerResponse",
payload: { operationName, response },
});
},
(error: ApolloError) => {
tab.send({
type: "explorerResponse",
payload: {
operationName,
response: {
errors: error.graphQLErrors.length
? error.graphQLErrors
: error.networkError && "result" in error.networkError
? typeof error.networkError?.result === "string"
? error.networkError?.result
: error.networkError?.result.errors ?? []
: [],
error: error,
data: null,
loading: false,
networkStatus: 8, // NetworkStatus.error - we want to prevent importing the enum here
},
},
});
}
);
if (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
) {
tab.on("explorerSubscriptionTermination", () => {
operationObservable?.unsubscribe();
});
}
});
/**
* Attempt to find the client on a 1-second interval for 10 seconds max
*/
let interval: NodeJS.Timeout;
function findClient() {
let count = 0;
function initializeDevtoolsHook() {
if (count++ > 10) {
clearInterval(interval);
tab.send({ type: "clientNotFound" });
}
if (window.__APOLLO_CLIENT__) {
registerClient(window.__APOLLO_CLIENT__);
}
}
clearInterval(interval);
interval = setInterval(initializeDevtoolsHook, 1000);
initializeDevtoolsHook(); // call immediately to reduce lag if devtools are already available
}
function watchForClientTermination(client: ApolloClient<any>) {
const originalStop = client.stop;
client.stop = () => {
knownClients.delete(client);
if (window.__APOLLO_CLIENT__ === client) {
window.__APOLLO_CLIENT__ = undefined;
}
if (hook.ApolloClient === client) {
hook.ApolloClient = undefined;
}
tab.send({ type: "disconnectFromDevtools" });
originalStop.call(client);
};
}
function registerClient(client: ApolloClient<any>) {
if (!knownClients.has(client)) {
knownClients.add(client);
watchForClientTermination(client);
}
hook.ApolloClient = client;
// TODO: Repurpose this callback. The message it sent was not listened by
// anything, so the broadcast was useless. Currently the devtools rely on
// polling the client every second for updates, rather than relying on
// this callback to update the devtools state.
// client.__actionHookForDevTools(() => {
// if (client !== hook.ApolloClient) {
// // if the client has changed, don't send the action hook
// return;
// }
// });
clearInterval(interval);
// incase initial update was missed because the client wasn't ready, send the create devtools event.
// devtools checks to see if it's already created, so this won't create duplicate tabs
sendHookDataToDevTools("connectToDevtools");
loadErrorCodes(rpcClient, client.version);
}
const preExisting = window[DEVTOOLS_KEY];
window[DEVTOOLS_KEY] = { push: registerClient };
if (Array.isArray(preExisting)) {
(preExisting as Array<ApolloClient<any>>).forEach(registerClient);
}
findClient();