swarpc 0.7.0 → 0.8.0

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.
Files changed (46) hide show
  1. package/dist/client.d.ts +39 -0
  2. package/dist/client.d.ts.map +1 -0
  3. package/dist/{src/client.js → client.js} +11 -3
  4. package/dist/{src/index.d.ts → index.d.ts} +4 -0
  5. package/dist/index.d.ts.map +1 -0
  6. package/dist/{src/index.js → index.js} +4 -0
  7. package/dist/log.d.ts +28 -0
  8. package/dist/log.d.ts.map +1 -0
  9. package/dist/log.js +55 -0
  10. package/dist/server.d.ts +32 -0
  11. package/dist/server.d.ts.map +1 -0
  12. package/dist/{src/server.js → server.js} +18 -10
  13. package/dist/{src/types.d.ts → types.d.ts} +44 -23
  14. package/dist/types.d.ts.map +1 -0
  15. package/dist/{src/types.js → types.js} +17 -0
  16. package/dist/utils.d.ts.map +1 -0
  17. package/package.json +18 -5
  18. package/src/client.ts +22 -4
  19. package/src/index.ts +5 -0
  20. package/src/log.ts +68 -12
  21. package/src/server.ts +37 -16
  22. package/src/types.ts +43 -31
  23. package/dist/src/client.d.ts +0 -22
  24. package/dist/src/client.d.ts.map +0 -1
  25. package/dist/src/index.d.ts.map +0 -1
  26. package/dist/src/log.d.ts +0 -20
  27. package/dist/src/log.d.ts.map +0 -1
  28. package/dist/src/log.js +0 -45
  29. package/dist/src/server.d.ts +0 -15
  30. package/dist/src/server.d.ts.map +0 -1
  31. package/dist/src/types.d.ts.map +0 -1
  32. package/dist/src/utils.d.ts.map +0 -1
  33. package/dist/tests/core.procedures.d.ts +0 -45
  34. package/dist/tests/core.procedures.d.ts.map +0 -1
  35. package/dist/tests/core.procedures.js +0 -49
  36. package/dist/tests/core.test.d.ts +0 -2
  37. package/dist/tests/core.test.d.ts.map +0 -1
  38. package/dist/tests/core.test.js +0 -100
  39. package/dist/tests/core.worker.d.ts +0 -2
  40. package/dist/tests/core.worker.d.ts.map +0 -1
  41. package/dist/tests/core.worker.js +0 -30
  42. package/dist/vite.config.d.ts +0 -3
  43. package/dist/vite.config.d.ts.map +0 -1
  44. package/dist/vite.config.js +0 -7
  45. /package/dist/{src/utils.d.ts → utils.d.ts} +0 -0
  46. /package/dist/{src/utils.js → utils.js} +0 -0
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @module
3
+ * @mergeModuleWith <project>
4
+ */
5
+ import { type LogLevel } from "./log.js";
6
+ import { ClientMethod, Hooks, zProcedures, type ProceduresMap } from "./types.js";
7
+ /**
8
+ * The sw&rpc client instance, which provides {@link ClientMethod | methods to call procedures}.
9
+ * Each property of the procedures map will be a method, that accepts an input, an optional onProgress callback and an optional request ID.
10
+ * If you want to be able to cancel the request, you can set the request's ID yourself, and call `.abort(requestId, reason)` on the client instance to cancel it.
11
+ */
12
+ export type SwarpcClient<Procedures extends ProceduresMap> = {
13
+ [zProcedures]: Procedures;
14
+ } & {
15
+ [F in keyof Procedures]: ClientMethod<Procedures[F]>;
16
+ };
17
+ /**
18
+ *
19
+ * @param procedures procedures the client will be able to call, see {@link ProceduresMap}
20
+ * @param options various options
21
+ * @param options.worker if provided, the client will use this worker to post messages.
22
+ * @param options.hooks hooks to run on messages received from the server
23
+ * @returns a sw&rpc client instance. Each property of the procedures map will be a method, that accepts an input and an optional onProgress callback, see {@link ClientMethod}
24
+ *
25
+ * An example of defining and using a client:
26
+ * {@includeCode ../example/src/routes/+page.svelte}
27
+ */
28
+ export declare function Client<Procedures extends ProceduresMap>(procedures: Procedures, { worker, loglevel, hooks, }?: {
29
+ worker?: Worker;
30
+ hooks?: Hooks<Procedures>;
31
+ loglevel?: LogLevel;
32
+ }): SwarpcClient<Procedures>;
33
+ /**
34
+ * Generate a random request ID, used to identify requests between client and server.
35
+ * @source
36
+ * @returns a 6-character hexadecimal string
37
+ */
38
+ export declare function makeRequestId(): string;
39
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAA6B,KAAK,QAAQ,EAAE,MAAM,UAAU,CAAA;AACnE,OAAO,EACL,YAAY,EACZ,KAAK,EAGL,WAAW,EACX,KAAK,aAAa,EACnB,MAAM,YAAY,CAAA;AAGnB;;;;GAIG;AACH,MAAM,MAAM,YAAY,CAAC,UAAU,SAAS,aAAa,IAAI;IAC3D,CAAC,WAAW,CAAC,EAAE,UAAU,CAAA;CAC1B,GAAG;KACD,CAAC,IAAI,MAAM,UAAU,GAAG,YAAY,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;CACrD,CAAA;AAkBD;;;;;;;;;;GAUG;AACH,wBAAgB,MAAM,CAAC,UAAU,SAAS,aAAa,EACrD,UAAU,EAAE,UAAU,EACtB,EACE,MAAM,EACN,QAAkB,EAClB,KAAU,GACX,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;IAAC,QAAQ,CAAC,EAAE,QAAQ,CAAA;CAAO,GAC1E,YAAY,CAAC,UAAU,CAAC,CA+F1B;AAmGD;;;;GAIG;AACH,wBAAgB,aAAa,IAAI,MAAM,CAEtC"}
@@ -1,5 +1,9 @@
1
+ /**
2
+ * @module
3
+ * @mergeModuleWith <project>
4
+ */
1
5
  import { createLogger } from "./log.js";
2
- import { zProcedures } from "./types.js";
6
+ import { zProcedures, } from "./types.js";
3
7
  import { findTransferables } from "./utils.js";
4
8
  /**
5
9
  * Pending requests are stored in a map, where the key is the request ID.
@@ -11,11 +15,14 @@ const pendingRequests = new Map();
11
15
  let _clientListenerStarted = false;
12
16
  /**
13
17
  *
14
- * @param procedures procedures the client will be able to call
18
+ * @param procedures procedures the client will be able to call, see {@link ProceduresMap}
15
19
  * @param options various options
16
20
  * @param options.worker if provided, the client will use this worker to post messages.
17
21
  * @param options.hooks hooks to run on messages received from the server
18
- * @returns a sw&rpc client instance. Each property of the procedures map will be a method, that accepts an input and an optional onProgress callback.
22
+ * @returns a sw&rpc client instance. Each property of the procedures map will be a method, that accepts an input and an optional onProgress callback, see {@link ClientMethod}
23
+ *
24
+ * An example of defining and using a client:
25
+ * {@includeCode ../example/src/routes/+page.svelte}
19
26
  */
20
27
  export function Client(procedures, { worker, loglevel = "debug", hooks = {}, } = {}) {
21
28
  const l = createLogger("client", loglevel);
@@ -152,6 +159,7 @@ async function startClientListener(l, worker, hooks = {}) {
152
159
  }
153
160
  /**
154
161
  * Generate a random request ID, used to identify requests between client and server.
162
+ * @source
155
163
  * @returns a 6-character hexadecimal string
156
164
  */
157
165
  export function makeRequestId() {
@@ -1,3 +1,7 @@
1
+ /**
2
+ * @module
3
+ * @mergeModuleWith <project>
4
+ */
1
5
  export * from "./client.js";
2
6
  export * from "./server.js";
3
7
  export type { ProceduresMap, CancelablePromise } from "./types.js";
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,cAAc,aAAa,CAAA;AAC3B,cAAc,aAAa,CAAA;AAC3B,YAAY,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA"}
@@ -1,2 +1,6 @@
1
+ /**
2
+ * @module
3
+ * @mergeModuleWith <project>
4
+ */
1
5
  export * from "./client.js";
2
6
  export * from "./server.js";
package/dist/log.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @module
3
+ * @mergeModuleWith <project>
4
+ */
5
+ /**
6
+ * @ignore
7
+ */
8
+ export declare function createLogger(side: "server" | "client", level: LogLevel): Logger;
9
+ export declare function createLogger(side: "server" | "client", level: LogLevel, rqid: string): RequestBoundLogger;
10
+ /**
11
+ * @ignore
12
+ */
13
+ export type Logger = {
14
+ debug: (rqid: string | null, message: string, ...args: any[]) => void;
15
+ info: (rqid: string | null, message: string, ...args: any[]) => void;
16
+ warn: (rqid: string | null, message: string, ...args: any[]) => void;
17
+ error: (rqid: string | null, message: string, ...args: any[]) => void;
18
+ };
19
+ export type RequestBoundLogger = {
20
+ debug: (message: string, ...args: any[]) => void;
21
+ info: (message: string, ...args: any[]) => void;
22
+ warn: (message: string, ...args: any[]) => void;
23
+ error: (message: string, ...args: any[]) => void;
24
+ };
25
+ /** @source */
26
+ export declare const LOG_LEVELS: readonly ["debug", "info", "warn", "error"];
27
+ export type LogLevel = (typeof LOG_LEVELS)[number];
28
+ //# sourceMappingURL=log.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log.d.ts","sourceRoot":"","sources":["../src/log.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;GAEG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,QAAQ,GAAG,QAAQ,EAAE,KAAK,EAAE,QAAQ,GAAG,MAAM,CAAA;AAChF,wBAAgB,YAAY,CAC1B,IAAI,EAAE,QAAQ,GAAG,QAAQ,EACzB,KAAK,EAAE,QAAQ,EACf,IAAI,EAAE,MAAM,GACX,kBAAkB,CAAA;AAyBrB;;GAEG;AACH,MAAM,MAAM,MAAM,GAAG;IACnB,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAA;IACrE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAA;IACpE,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAA;IACpE,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAA;CACtE,CAAA;AAED,MAAM,MAAM,kBAAkB,GAAG;IAC/B,KAAK,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAA;IAChD,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAA;IAC/C,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAA;IAC/C,KAAK,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,CAAA;CACjD,CAAA;AAED,cAAc;AACd,eAAO,MAAM,UAAU,6CAA8C,CAAA;AAErE,MAAM,MAAM,QAAQ,GAAG,CAAC,OAAO,UAAU,CAAC,CAAC,MAAM,CAAC,CAAA"}
package/dist/log.js ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @module
3
+ * @mergeModuleWith <project>
4
+ */
5
+ export function createLogger(side, level = "debug", rqid) {
6
+ const lvls = LOG_LEVELS.slice(LOG_LEVELS.indexOf(level));
7
+ if (rqid) {
8
+ return {
9
+ debug: lvls.includes("debug") ? logger("debug", side, rqid) : () => { },
10
+ info: lvls.includes("info") ? logger("info", side, rqid) : () => { },
11
+ warn: lvls.includes("warn") ? logger("warn", side, rqid) : () => { },
12
+ error: lvls.includes("error") ? logger("error", side, rqid) : () => { },
13
+ };
14
+ }
15
+ return {
16
+ debug: lvls.includes("debug") ? logger("debug", side) : () => { },
17
+ info: lvls.includes("info") ? logger("info", side) : () => { },
18
+ warn: lvls.includes("warn") ? logger("warn", side) : () => { },
19
+ error: lvls.includes("error") ? logger("error", side) : () => { },
20
+ };
21
+ }
22
+ /** @source */
23
+ export const LOG_LEVELS = ["debug", "info", "warn", "error"];
24
+ function logger(severity, side, rqid) {
25
+ if (rqid === undefined) {
26
+ return (rqid, message, ...args) => log(severity, side, rqid, message, ...args);
27
+ }
28
+ return (message, ...args) => log(severity, side, rqid, message, ...args);
29
+ }
30
+ /**
31
+ * Send log messages to the console, with a helpful prefix.
32
+ * @param severity
33
+ * @param side
34
+ * @param rqid request ID
35
+ * @param message
36
+ * @param args passed to console methods directly
37
+ */
38
+ function log(severity, side, rqid, message, ...args) {
39
+ const prefix = "[" +
40
+ ["SWARPC", side, rqid ? `%c${rqid}%c` : ""].filter(Boolean).join(" ") +
41
+ "]";
42
+ const prefixStyles = rqid ? ["color: cyan;", "color: inherit;"] : [];
43
+ if (severity === "debug") {
44
+ console.debug(prefix, ...prefixStyles, message, ...args);
45
+ }
46
+ else if (severity === "info") {
47
+ console.info(prefix, ...prefixStyles, message, ...args);
48
+ }
49
+ else if (severity === "warn") {
50
+ console.warn(prefix, ...prefixStyles, message, ...args);
51
+ }
52
+ else if (severity === "error") {
53
+ console.error(prefix, ...prefixStyles, message, ...args);
54
+ }
55
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * @module
3
+ * @mergeModuleWith <project>
4
+ */
5
+ import { type LogLevel } from "./log.js";
6
+ import { ImplementationsMap, ProcedureImplementation, zImplementations, zProcedures, type ProceduresMap } from "./types.js";
7
+ /**
8
+ * The sw&rpc server instance, which provides methods to register {@link ProcedureImplementation | procedure implementations},
9
+ * and listens for incoming messages that call those procedures
10
+ */
11
+ export type SwarpcServer<Procedures extends ProceduresMap> = {
12
+ [zProcedures]: Procedures;
13
+ [zImplementations]: ImplementationsMap<Procedures>;
14
+ start(self: Window | Worker): void;
15
+ } & {
16
+ [F in keyof Procedures]: (impl: ProcedureImplementation<Procedures[F]["input"], Procedures[F]["progress"], Procedures[F]["success"]>) => void;
17
+ };
18
+ /**
19
+ * Creates a sw&rpc server instance.
20
+ * @param procedures procedures the server will implement, see {@link ProceduresMap}
21
+ * @param options various options
22
+ * @param options.worker if provided, the server will use this worker to post messages, instead of sending it to all clients
23
+ * @returns a SwarpcServer instance. Each property of the procedures map will be a method, that accepts a function implementing the procedure (see {@link ProcedureImplementation}). There is also .start(), to be called after implementing all procedures.
24
+ *
25
+ * An example of defining a server:
26
+ * {@includeCode ../example/src/service-worker.ts}
27
+ */
28
+ export declare function Server<Procedures extends ProceduresMap>(procedures: Procedures, { worker, loglevel }?: {
29
+ worker?: Worker;
30
+ loglevel?: LogLevel;
31
+ }): SwarpcServer<Procedures>;
32
+ //# sourceMappingURL=server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAgB,KAAK,QAAQ,EAAE,MAAM,UAAU,CAAA;AACtD,OAAO,EACL,kBAAkB,EAKlB,uBAAuB,EACvB,gBAAgB,EAChB,WAAW,EACX,KAAK,aAAa,EACnB,MAAM,YAAY,CAAA;AAGnB;;;GAGG;AACH,MAAM,MAAM,YAAY,CAAC,UAAU,SAAS,aAAa,IAAI;IAC3D,CAAC,WAAW,CAAC,EAAE,UAAU,CAAA;IACzB,CAAC,gBAAgB,CAAC,EAAE,kBAAkB,CAAC,UAAU,CAAC,CAAA;IAClD,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAA;CACnC,GAAG;KACD,CAAC,IAAI,MAAM,UAAU,GAAG,CACvB,IAAI,EAAE,uBAAuB,CAC3B,UAAU,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,EACtB,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,EACzB,UAAU,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CACzB,KACE,IAAI;CACV,CAAA;AAKD;;;;;;;;;GASG;AACH,wBAAgB,MAAM,CAAC,UAAU,SAAS,aAAa,EACrD,UAAU,EAAE,UAAU,EACtB,EAAE,MAAM,EAAE,QAAkB,EAAE,GAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,QAAQ,CAAA;CAAO,GAC5E,YAAY,CAAC,UAAU,CAAC,CA+J1B"}
@@ -1,3 +1,7 @@
1
+ /**
2
+ * @module
3
+ * @mergeModuleWith <project>
4
+ */
1
5
  import { type } from "arktype";
2
6
  import { createLogger } from "./log.js";
3
7
  import { PayloadHeaderSchema, PayloadSchema, zImplementations, zProcedures, } from "./types.js";
@@ -6,10 +10,13 @@ const abortControllers = new Map();
6
10
  const abortedRequests = new Set();
7
11
  /**
8
12
  * Creates a sw&rpc server instance.
9
- * @param procedures procedures the server will implement
13
+ * @param procedures procedures the server will implement, see {@link ProceduresMap}
10
14
  * @param options various options
11
15
  * @param options.worker if provided, the server will use this worker to post messages, instead of sending it to all clients
12
- * @returns a SwarpcServer instance. Each property of the procedures map will be a method, that accepts a function implementing the procedure. There is also .start(), to be called after implementing all procedures.
16
+ * @returns a SwarpcServer instance. Each property of the procedures map will be a method, that accepts a function implementing the procedure (see {@link ProcedureImplementation}). There is also .start(), to be called after implementing all procedures.
17
+ *
18
+ * An example of defining a server:
19
+ * {@includeCode ../example/src/service-worker.ts}
13
20
  */
14
21
  export function Server(procedures, { worker, loglevel = "debug" } = {}) {
15
22
  const l = createLogger("server", loglevel);
@@ -27,17 +34,15 @@ export function Server(procedures, { worker, loglevel = "debug" } = {}) {
27
34
  if (!instance[zProcedures][functionName]) {
28
35
  throw new Error(`No procedure found for function name: ${functionName}`);
29
36
  }
30
- instance[zImplementations][functionName] = (input, onProgress, abortSignal) => {
31
- abortSignal?.throwIfAborted();
37
+ instance[zImplementations][functionName] = (input, onProgress, tools) => {
38
+ tools.abortSignal?.throwIfAborted();
32
39
  return new Promise((resolve, reject) => {
33
- abortSignal?.addEventListener("abort", () => {
34
- let { requestId, reason } = abortSignal?.reason;
40
+ tools.abortSignal?.addEventListener("abort", () => {
41
+ let { requestId, reason } = tools.abortSignal?.reason;
35
42
  l.debug(requestId, `Aborted ${functionName} request: ${reason}`);
36
43
  reject({ aborted: reason });
37
44
  });
38
- implementation(input, onProgress, abortSignal)
39
- .then(resolve)
40
- .catch(reject);
45
+ implementation(input, onProgress, tools).then(resolve).catch(reject);
41
46
  });
42
47
  };
43
48
  });
@@ -105,7 +110,10 @@ export function Server(procedures, { worker, loglevel = "debug" } = {}) {
105
110
  await implementation(payload.input, async (progress) => {
106
111
  l.debug(requestId, `Progress for ${functionName}`, progress);
107
112
  await postMsg({ progress });
108
- }, abortControllers.get(requestId)?.signal)
113
+ }, {
114
+ abortSignal: abortControllers.get(requestId)?.signal,
115
+ logger: createLogger("server", loglevel, requestId),
116
+ })
109
117
  // Send errors
110
118
  .catch(async (error) => {
111
119
  // Handle errors caused by abortions
@@ -1,4 +1,9 @@
1
+ /**
2
+ * @module
3
+ * @mergeModuleWith <project>
4
+ */
1
5
  import { type Type } from "arktype";
6
+ import { RequestBoundLogger } from "./log.js";
2
7
  /**
3
8
  * A procedure declaration
4
9
  */
@@ -37,7 +42,7 @@ export type Procedure<I extends Type, P extends Type, S extends Type> = {
37
42
  * const result = await request
38
43
  * ```
39
44
  */
40
- export type CancelablePromise<T> = {
45
+ export type CancelablePromise<T = unknown> = {
41
46
  request: Promise<T>;
42
47
  /**
43
48
  * Abort the request.
@@ -48,9 +53,33 @@ export type CancelablePromise<T> = {
48
53
  /**
49
54
  * An implementation of a procedure
50
55
  */
51
- export type ProcedureImplementation<I extends Type, P extends Type, S extends Type> = (input: I["inferOut"], onProgress: (progress: P["inferIn"]) => void, abortSignal?: AbortSignal) => Promise<S["inferIn"]>;
56
+ export type ProcedureImplementation<I extends Type, P extends Type, S extends Type> = (
57
+ /**
58
+ * Input data for the procedure
59
+ */
60
+ input: I["inferOut"],
61
+ /**
62
+ * Callback to call with progress updates.
63
+ */
64
+ onProgress: (progress: P["inferIn"]) => void,
65
+ /**
66
+ * Additional tools useful when implementing the procedure.
67
+ */
68
+ tools: {
69
+ /**
70
+ * AbortSignal that can be used to handle request cancellation -- see [Make cancellable requests](https://gwennlbh.github.io/swarpc/docs/#make-cancelable-requests)
71
+ */
72
+ abortSignal?: AbortSignal;
73
+ /**
74
+ * Logger instance to use for logging messages related to this procedure call, using the same format as SWARPC's built-in logging.
75
+ */
76
+ logger: RequestBoundLogger;
77
+ }) => Promise<S["inferIn"]>;
52
78
  /**
53
79
  * Declarations of procedures by name.
80
+ *
81
+ * An example of declaring procedures:
82
+ * {@includeCode ../example/src/lib/procedures.ts}
54
83
  */
55
84
  export type ProceduresMap = Record<string, Procedure<Type, Type, Type>>;
56
85
  /**
@@ -76,6 +105,9 @@ export type Hooks<Procedures extends ProceduresMap> = {
76
105
  */
77
106
  progress?: <Procedure extends keyof ProceduresMap>(procedure: Procedure, data: Procedures[Procedure]["progress"]["inferOut"]) => void;
78
107
  };
108
+ /**
109
+ * @source
110
+ */
79
111
  export declare const PayloadHeaderSchema: import("arktype").Generic<[["Name", string]], {
80
112
  readonly by: "\"sw&rpc\"";
81
113
  readonly functionName: "Name";
@@ -86,6 +118,9 @@ export type PayloadHeader<PM extends ProceduresMap, Name extends keyof PM = keyo
86
118
  functionName: Name & string;
87
119
  requestId: string;
88
120
  };
121
+ /**
122
+ * @source
123
+ */
89
124
  export declare const PayloadCoreSchema: import("arktype").Generic<[["I", unknown], ["P", unknown], ["S", unknown]], {
90
125
  readonly "input?": "I";
91
126
  readonly "progress?": "P";
@@ -112,6 +147,9 @@ export type PayloadCore<PM extends ProceduresMap, Name extends keyof PM = keyof
112
147
  message: string;
113
148
  };
114
149
  };
150
+ /**
151
+ * @source
152
+ */
115
153
  export declare const PayloadSchema: import("arktype").Generic<[["Name", string], ["I", unknown], ["P", unknown], ["S", unknown]], readonly ["PayloadHeaderSchema<Name>", "&", "PayloadCoreSchema<I, P, S>"], {
116
154
  PayloadCoreSchema: import("arktype/internal/scope.ts").bindGenericToScope<import("@ark/schema").GenericAst<[["I", unknown], ["P", unknown], ["S", unknown]], {
117
155
  readonly "input?": "I";
@@ -230,31 +268,14 @@ export type ClientMethod<P extends Procedure<Type, Type, Type>> = ((input: P["in
230
268
  };
231
269
  /**
232
270
  * Symbol used as the key for the procedures map on the server instance
271
+ * @internal
272
+ * @source
233
273
  */
234
274
  export declare const zImplementations: unique symbol;
235
275
  /**
236
276
  * Symbol used as the key for the procedures map on instances
277
+ * @internal
278
+ * @source
237
279
  */
238
280
  export declare const zProcedures: unique symbol;
239
- /**
240
- * The sw&rpc client instance, which provides methods to call procedures.
241
- * Each property of the procedures map will be a method, that accepts an input, an optional onProgress callback and an optional request ID.
242
- * If you want to be able to cancel the request, you can set the request's ID yourself, and call `.abort(requestId, reason)` on the client instance to cancel it.
243
- */
244
- export type SwarpcClient<Procedures extends ProceduresMap> = {
245
- [zProcedures]: Procedures;
246
- } & {
247
- [F in keyof Procedures]: ClientMethod<Procedures[F]>;
248
- };
249
- /**
250
- * The sw&rpc server instance, which provides methods to register procedure implementations,
251
- * and listens for incoming messages that call those procedures
252
- */
253
- export type SwarpcServer<Procedures extends ProceduresMap> = {
254
- [zProcedures]: Procedures;
255
- [zImplementations]: ImplementationsMap<Procedures>;
256
- start(self: Window | Worker): void;
257
- } & {
258
- [F in keyof Procedures]: (impl: ProcedureImplementation<Procedures[F]["input"], Procedures[F]["progress"], Procedures[F]["success"]>) => void;
259
- };
260
281
  //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAQ,KAAK,IAAI,EAAE,MAAM,SAAS,CAAA;AACzC,OAAO,EAAU,kBAAkB,EAAE,MAAM,UAAU,CAAA;AAErD;;GAEG;AACH,MAAM,MAAM,SAAS,CAAC,CAAC,SAAS,IAAI,EAAE,CAAC,SAAS,IAAI,EAAE,CAAC,SAAS,IAAI,IAAI;IACtE;;OAEG;IACH,KAAK,EAAE,CAAC,CAAA;IACR;;;OAGG;IACH,QAAQ,EAAE,CAAC,CAAA;IACX;;OAEG;IACH,OAAO,EAAE,CAAC,CAAA;IACV;;;;;;;;;OASG;IACH,YAAY,CAAC,EAAE,QAAQ,G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
@@ -1,9 +1,19 @@
1
+ /**
2
+ * @module
3
+ * @mergeModuleWith <project>
4
+ */
1
5
  import { type } from "arktype";
6
+ /**
7
+ * @source
8
+ */
2
9
  export const PayloadHeaderSchema = type("<Name extends string>", {
3
10
  by: '"sw&rpc"',
4
11
  functionName: "Name",
5
12
  requestId: "string >= 1",
6
13
  });
14
+ /**
15
+ * @source
16
+ */
7
17
  export const PayloadCoreSchema = type("<I, P, S>", {
8
18
  "input?": "I",
9
19
  "progress?": "P",
@@ -11,6 +21,9 @@ export const PayloadCoreSchema = type("<I, P, S>", {
11
21
  "abort?": { reason: "string" },
12
22
  "error?": { message: "string" },
13
23
  });
24
+ /**
25
+ * @source
26
+ */
14
27
  export const PayloadSchema = type
15
28
  .scope({ PayloadCoreSchema, PayloadHeaderSchema })
16
29
  .type("<Name extends string, I, P, S>", [
@@ -20,9 +33,13 @@ export const PayloadSchema = type
20
33
  ]);
21
34
  /**
22
35
  * Symbol used as the key for the procedures map on the server instance
36
+ * @internal
37
+ * @source
23
38
  */
24
39
  export const zImplementations = Symbol("SWARPC implementations");
25
40
  /**
26
41
  * Symbol used as the key for the procedures map on instances
42
+ * @internal
43
+ * @source
27
44
  */
28
45
  export const zProcedures = Symbol("SWARPC procedures");
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAWA,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,GAAG,GAAG,YAAY,EAAE,CAsB5D"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "swarpc",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Full type-safe RPC library for service worker -- move things off of the UI thread with ease!",
5
5
  "keywords": [
6
6
  "service-workers",
@@ -31,18 +31,31 @@
31
31
  "dev": "tsc --watch",
32
32
  "typecheck": "tsc --noEmit",
33
33
  "test": "vitest",
34
- "typedoc": "typedoc src/index.ts src/types.ts --readme README.md",
35
- "version": "kacl release && prettier -w CHANGELOG.md && git add CHANGELOG.md"
34
+ "typedoc": "typedoc",
35
+ "version": "kacl release && prettier -w CHANGELOG.md && git add CHANGELOG.md",
36
+ "typedoc:dev": "nodemon --watch src --watch README.md --watch typedoc.json --watch typedoc.css --exec npm run typedoc:withplugins",
37
+ "typedoc:serve": "npx sirv-cli --dev docs",
38
+ "typedoc:plugins": "node -e \"const fs=require('fs');const p=JSON.parse(fs.readFileSync('typedoc.json')).plugin||[];if(p.length)require('child_process').execSync('npm add --legacy-peer-deps -D '+p.join(' '),{stdio:'inherit'});else console.log('No plugins found');\"",
39
+ "typedoc:withplugins": "npm run typedoc:plugins && npm run typedoc"
36
40
  },
37
41
  "dependencies": {
38
42
  "arktype": "^2.1.20"
39
43
  },
40
44
  "devDependencies": {
45
+ "@8hobbies/typedoc-plugin-plausible": "^2.2.0",
41
46
  "@vitest/web-worker": "^3.2.4",
42
47
  "kacl": "^1.1.1",
48
+ "nodemon": "^3.1.10",
43
49
  "prettier": "^3.6.2",
44
- "typedoc": "^0.28.7",
45
- "typescript": "^5.8.3",
50
+ "sirv-cli": "^3.0.1",
51
+ "typedoc": "^0.28.9",
52
+ "typedoc-material-theme": "^1.4.0",
53
+ "typedoc-plugin-dt-links": "^2.0.12",
54
+ "typedoc-plugin-extras": "^4.0.1",
55
+ "typedoc-plugin-inline-sources": "^1.3.0",
56
+ "typedoc-plugin-mdn-links": "^5.0.6",
57
+ "typedoc-plugin-redirect": "^1.2.0",
58
+ "typescript": "^5.9.2",
46
59
  "vite": "^7.0.6",
47
60
  "vitest": "^3.2.4"
48
61
  }
package/src/client.ts CHANGED
@@ -1,15 +1,29 @@
1
+ /**
2
+ * @module
3
+ * @mergeModuleWith <project>
4
+ */
5
+
1
6
  import { createLogger, type Logger, type LogLevel } from "./log.js"
2
7
  import {
8
+ ClientMethod,
3
9
  Hooks,
4
10
  Payload,
5
11
  PayloadCore,
6
12
  zProcedures,
7
13
  type ProceduresMap,
8
- type SwarpcClient
9
14
  } from "./types.js"
10
15
  import { findTransferables } from "./utils.js"
11
16
 
12
- export type { SwarpcClient } from "./types.js"
17
+ /**
18
+ * The sw&rpc client instance, which provides {@link ClientMethod | methods to call procedures}.
19
+ * Each property of the procedures map will be a method, that accepts an input, an optional onProgress callback and an optional request ID.
20
+ * If you want to be able to cancel the request, you can set the request's ID yourself, and call `.abort(requestId, reason)` on the client instance to cancel it.
21
+ */
22
+ export type SwarpcClient<Procedures extends ProceduresMap> = {
23
+ [zProcedures]: Procedures
24
+ } & {
25
+ [F in keyof Procedures]: ClientMethod<Procedures[F]>
26
+ }
13
27
 
14
28
  /**
15
29
  * Pending requests are stored in a map, where the key is the request ID.
@@ -29,11 +43,14 @@ let _clientListenerStarted = false
29
43
 
30
44
  /**
31
45
  *
32
- * @param procedures procedures the client will be able to call
46
+ * @param procedures procedures the client will be able to call, see {@link ProceduresMap}
33
47
  * @param options various options
34
48
  * @param options.worker if provided, the client will use this worker to post messages.
35
49
  * @param options.hooks hooks to run on messages received from the server
36
- * @returns a sw&rpc client instance. Each property of the procedures map will be a method, that accepts an input and an optional onProgress callback.
50
+ * @returns a sw&rpc client instance. Each property of the procedures map will be a method, that accepts an input and an optional onProgress callback, see {@link ClientMethod}
51
+ *
52
+ * An example of defining and using a client:
53
+ * {@includeCode ../example/src/routes/+page.svelte}
37
54
  */
38
55
  export function Client<Procedures extends ProceduresMap>(
39
56
  procedures: Procedures,
@@ -238,6 +255,7 @@ async function startClientListener<Procedures extends ProceduresMap>(
238
255
 
239
256
  /**
240
257
  * Generate a random request ID, used to identify requests between client and server.
258
+ * @source
241
259
  * @returns a 6-character hexadecimal string
242
260
  */
243
261
  export function makeRequestId(): string {
package/src/index.ts CHANGED
@@ -1,3 +1,8 @@
1
+ /**
2
+ * @module
3
+ * @mergeModuleWith <project>
4
+ */
5
+
1
6
  export * from "./client.js"
2
7
  export * from "./server.js"
3
8
  export type { ProceduresMap, CancelablePromise } from "./types.js"