Skip to content

Commit

Permalink
feat: add MessageSender of chrome runtime to request context
Browse files Browse the repository at this point in the history
  • Loading branch information
tanlethanh committed Jul 27, 2024
1 parent cbf13dc commit dda9bde
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
10 changes: 9 additions & 1 deletion src/chrome/kernel.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Request } from '../core';
import { Kernel } from '../core/kernel';

/**
Expand All @@ -19,7 +20,14 @@ export class ChromeKernel<
chrome.runtime.onConnect.addListener((port) => {
const channelId = port.name as ChannelId;
port.onMessage.addListener((message, port) => {
this.execute(channelId, message, (payload) => {
let payload: Request<EventType>;
if (typeof message === 'object') {
payload = { ...message, context: port.sender };
} else {
payload = message;
}

this.execute(channelId, payload, (payload) => {
port.postMessage(payload);
});
});
Expand Down
17 changes: 13 additions & 4 deletions src/core/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Middleware<EventType = any, RequestPayload = any> = (
request: Request<EventType, RequestPayload>,
/* eslint-disable @typescript-eslint/no-explicit-any */

export type Middleware<EventType = any, RequestPayload = any, Context = any> = (
request: Request<EventType, RequestPayload, Context>,
respond: (response: RawResponse) => void,
next?: (request: Request<EventType, RequestPayload>) => void,
) => Promise<void> | void;
Expand All @@ -9,13 +10,21 @@ export type RawRequest<Type = string, Payload = Record<string, unknown>> = {
type: Type;
} & Payload;

export type Request<Type = string, Payload = Record<string, unknown>> = {
export type Request<
Type = string,
Payload = Record<string, unknown>,
Context = any,
> = {
id: string;
/**
* timeout is always passed in the request,
* any timeout-aware middleware can use this one to prevent unexpected retrying/looping
*/
timeout: number;
/**
* Source Context request, e.g. MessageSender for chrome runtime
*/
context?: Context;
} & RawRequest<Type, Payload>;

export type RawResponse<Payload = Record<string, unknown>> = {
Expand Down

0 comments on commit dda9bde

Please sign in to comment.