Skip to content
Open
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
12 changes: 8 additions & 4 deletions src/comlink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,13 @@ type Unpromisify<P> = P extends Promise<infer T> ? T : P;
*/
type RemoteProperty<T> =
// If the value is a method, comlink will proxy it automatically.
// Objects are only proxied if they are marked to be proxied.
// Objects can be either awaited as cloned values or traversed as remote paths.
// Otherwise, the property is converted to a Promise that resolves the cloned value.
T extends Function | ProxyMarked ? Remote<T> : Promisify<T>;
T extends Function | ProxyMarked
? Remote<T>
: T extends object
? Remote<T> & Promisify<T>
: Promisify<T>;

/**
* Takes the raw type of a property as a remote thread would see it through a proxy (e.g. when passed in as a function
Expand Down Expand Up @@ -400,7 +404,7 @@ function closeEndPoint(endpoint: Endpoint) {
}

export function wrap<T>(ep: Endpoint, target?: any): Remote<T> {
const pendingListeners : PendingListenersMap = new Map();
const pendingListeners: PendingListenersMap = new Map();

ep.addEventListener("message", function handleMessage(ev: Event) {
const { data } = ev as MessageEvent;
Expand Down Expand Up @@ -643,7 +647,7 @@ function requestResponseMessage(
ep.start();
}
ep.postMessage({ id, ...msg }, transfers);
});
});
}

function generateUUID(): string {
Expand Down
18 changes: 18 additions & 0 deletions tests/type-checks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,27 @@ async function closureSoICanUseAwait() {
assert<IsAny<typeof b>>(false);
const subproxy = proxy.c;
assert<Has<typeof subproxy, Promise<{ d: number }>>>(true);
assert<Has<typeof subproxy, { d: Promise<number> }>>(true);
assert<IsAny<typeof subproxy>>(false);
const copy = await proxy.c;
assert<Has<typeof copy, { d: number }>>(true);

const nestedValue = proxy.c.d;
assert<Has<typeof nestedValue, Promise<number>>>(true);
}

{
interface WorkerApi {
service: {
method: () => void;
};
}

const proxy = Comlink.wrap<WorkerApi>(0 as any);
const call = proxy.service.method();
assert<Has<typeof call, Promise<void>>>(true);
const service = await proxy.service;
assert<Has<typeof service, { method: () => void }>>(true);
}

{
Expand Down