Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DO NOT MERGE] Experiment with devtools link 2-way communication #12101

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions src/link/devtools/devtoolsLink.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import type { Observable } from "zen-observable-ts";
import type { FetchResult, NextLink, Operation } from "../core/index.js";
import { ApolloLink } from "../core/index.js";
import type { DefaultContext } from "../../core/types.js";
import { createDevtoolsActor } from "./messages.js";
import type { DevtoolsActor } from "./messages.js";

export class DevtoolsLink extends ApolloLink {
private debugConnectorsRequests = false;
private actor: DevtoolsActor;

constructor() {
super();

this.actor = createDevtoolsActor();
this.subscribeToDevtoolsMessages();
}

public request(
operation: Operation,
forward: NextLink
): Observable<FetchResult> | null {
if (this.debugConnectorsRequests) {
operation.setContext((context: DefaultContext) => ({
headers: {
...context.headers,
"Apollo-Connectors-Debugging": "true",
},
}));
}

return forward(operation);
}

private subscribeToDevtoolsMessages() {
this.actor.on("toggleConnectorsDebugging", ({ enabled }) => {
this.debugConnectorsRequests = enabled;
});
}
}
Empty file added src/link/devtools/index.ts
Empty file.
119 changes: 119 additions & 0 deletions src/link/devtools/messages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
type DevtoolsMessage = {
type: "toggleConnectorsDebugging";
enabled: boolean;
};

export interface DevtoolsActor {
on: <TName extends DevtoolsMessage["type"]>(
name: TName,
callback: Extract<DevtoolsMessage, { type: TName }> extends infer Message ?
(message: Message) => void
: never
) => () => void;
send: (message: DevtoolsMessage) => void;
}

export function createDevtoolsActor(): DevtoolsActor {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reminder to self to handle non-browser environments

let removeListener: (() => void) | null = null;
const messageListeners = new Map<
DevtoolsMessage["type"],
Set<(message: DevtoolsMessage) => void>
>();

function handleMessage(event: MessageEvent) {
const message = event.data;
if (!isDevtoolsMessage(message)) {
return;
}

const listeners = messageListeners.get(message.message.type);

if (listeners) {
listeners.forEach((listener) => {
listener(message.message);
});
}
}

function startListening() {
if (!removeListener) {
window.addEventListener("message", handleMessage);
removeListener = () => {
window.removeEventListener("message", handleMessage);
};
}
}

function stopListening() {
if (removeListener) {
removeListener();
removeListener = null;
}
}

const on: DevtoolsActor["on"] = (name, callback, options = {}) => {
let listeners = messageListeners.get(name) as Set<typeof callback>;

if (!listeners) {
listeners = new Set();
messageListeners.set(name, listeners);
}

listeners.add(callback);
startListening();

const cleanup = () => {
listeners!.delete(callback);

if (listeners.size === 0) {
messageListeners.delete(name);
}

if (messageListeners.size === 0) {
stopListening();
}
};
return cleanup;
};

return {
on,
send: (message) => {
window.postMessage({
id: createId(),
source: "apollo-client",
type: "actor",
message,
});
},
};
}

export type ApolloClientDevtoolsMessage = {
id: string;
source: "apollo-client-devtools";
type: "actor";
message: DevtoolsMessage;
};

function isDevtoolsMessage(
message: unknown
): message is ApolloClientDevtoolsMessage {
return (
typeof message === "object" &&
message !== null &&
"source" in message &&
"type" in message &&
message.source === "apollo-client-devtools" &&
message.type === "actor"
);
}
export function createId() {
const chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

return new Array(10)
.fill(null)
.map(() => chars[Math.floor(Math.random() * chars.length)])
.join("");
}
Loading