swarpc 0.10.0 → 0.12.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.
package/dist/server.js CHANGED
@@ -5,21 +5,18 @@
5
5
  /// <reference lib="webworker" />
6
6
  import { type } from "arktype";
7
7
  import { createLogger } from "./log.js";
8
- import { PayloadHeaderSchema, PayloadSchema, zImplementations, zProcedures, } from "./types.js";
8
+ import { PayloadHeaderSchema, PayloadInitializeSchema, PayloadSchema, zImplementations, zProcedures, } from "./types.js";
9
9
  import { findTransferables } from "./utils.js";
10
- class MockedWorkerGlobalScope {
11
- constructor() { }
12
- }
13
- const SharedWorkerGlobalScope = globalThis.SharedWorkerGlobalScope ?? MockedWorkerGlobalScope;
14
- const DedicatedWorkerGlobalScope = globalThis.DedicatedWorkerGlobalScope ?? MockedWorkerGlobalScope;
15
- const ServiceWorkerGlobalScope = globalThis.ServiceWorkerGlobalScope ?? MockedWorkerGlobalScope;
10
+ import { FauxLocalStorage } from "./localstorage.js";
11
+ import { scopeIsDedicated, scopeIsShared, scopeIsService } from "./scopes.js";
12
+ import { nodeIdFromScope } from "./nodes.js";
16
13
  const abortControllers = new Map();
17
14
  const abortedRequests = new Set();
18
15
  /**
19
16
  * Creates a sw&rpc server instance.
20
17
  * @param procedures procedures the server will implement, see {@link ProceduresMap}
21
18
  * @param options various options
22
- * @param options.worker The worker scope to use, defaults to the `self` of the file where Server() is called.
19
+ * @param options.scope The worker scope to use, defaults to the `self` of the file where Server() is called.
23
20
  * @param options.loglevel Maximum log level to use, defaults to "debug" (shows everything). "info" will not show debug messages, "warn" will only show warnings and errors, "error" will only show errors.
24
21
  * @param options._scopeType @internal Don't touch, this is used in testing environments because the mock is subpar. Manually overrides worker scope type detection.
25
22
  * @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.
@@ -28,19 +25,12 @@ const abortedRequests = new Set();
28
25
  * {@includeCode ../example/src/service-worker.ts}
29
26
  */
30
27
  export function Server(procedures, { loglevel = "debug", scope, _scopeType, } = {}) {
31
- const l = createLogger("server", loglevel);
32
28
  // If scope is not provided, use the global scope
33
29
  // This function is meant to be used in a worker, so `self` is a WorkerGlobalScope
34
30
  scope ??= self;
35
- function scopeIsShared(scope) {
36
- return scope instanceof SharedWorkerGlobalScope || _scopeType === "shared";
37
- }
38
- function scopeIsDedicated(scope) {
39
- return (scope instanceof DedicatedWorkerGlobalScope || _scopeType === "dedicated");
40
- }
41
- function scopeIsService(scope) {
42
- return scope instanceof ServiceWorkerGlobalScope || _scopeType === "service";
43
- }
31
+ // Service workers don't have a name, but it's fine anyways cuz we don't have multiple nodes when running with a SW
32
+ const nodeId = nodeIdFromScope(scope, _scopeType);
33
+ const l = createLogger("server", loglevel, nodeId);
44
34
  // Initialize the instance.
45
35
  // Procedures and implementations are stored on properties with symbol keys,
46
36
  // to avoid any conflicts with procedure names, and also discourage direct access to them.
@@ -59,7 +49,7 @@ export function Server(procedures, { loglevel = "debug", scope, _scopeType, } =
59
49
  tools.abortSignal?.throwIfAborted();
60
50
  return new Promise((resolve, reject) => {
61
51
  tools.abortSignal?.addEventListener("abort", () => {
62
- let { requestId, reason } = tools.abortSignal?.reason;
52
+ let { requestId, reason } = tools.abortSignal.reason;
63
53
  l.debug(requestId, `Aborted ${functionName} request: ${reason}`);
64
54
  reject({ aborted: reason });
65
55
  });
@@ -70,11 +60,11 @@ export function Server(procedures, { loglevel = "debug", scope, _scopeType, } =
70
60
  }
71
61
  instance.start = async () => {
72
62
  const port = await new Promise((resolve) => {
73
- if (!scopeIsShared(scope))
63
+ if (!scopeIsShared(scope, _scopeType))
74
64
  return resolve(undefined);
75
- console.log("Awaiting shared worker connection...");
65
+ l.debug(null, "Awaiting shared worker connection...");
76
66
  scope.addEventListener("connect", ({ ports: [port] }) => {
77
- console.log("Shared worker connected with port", port);
67
+ l.debug(null, "Shared worker connected with port", port);
78
68
  resolve(port);
79
69
  });
80
70
  });
@@ -84,16 +74,22 @@ export function Server(procedures, { loglevel = "debug", scope, _scopeType, } =
84
74
  if (port) {
85
75
  port.postMessage(data, { transfer });
86
76
  }
87
- else if (scopeIsDedicated(scope)) {
77
+ else if (scopeIsDedicated(scope, _scopeType)) {
88
78
  scope.postMessage(data, { transfer });
89
79
  }
90
- else if (scopeIsService(scope)) {
80
+ else if (scopeIsService(scope, _scopeType)) {
91
81
  await scope.clients.matchAll().then((clients) => {
92
82
  clients.forEach((client) => client.postMessage(data, { transfer }));
93
83
  });
94
84
  }
95
85
  };
96
86
  const listener = async (event) => {
87
+ if (PayloadInitializeSchema.allows(event.data)) {
88
+ const { localStorageData } = event.data;
89
+ l.debug(null, "Setting up faux localStorage", localStorageData);
90
+ new FauxLocalStorage(localStorageData).register(scope);
91
+ return;
92
+ }
97
93
  // Decode the payload
98
94
  const { requestId, functionName } = PayloadHeaderSchema(type.enumerated(...Object.keys(procedures))).assert(event.data);
99
95
  l.debug(requestId, `Received request for ${functionName}`, event.data);
@@ -124,6 +120,8 @@ export function Server(procedures, { loglevel = "debug", scope, _scopeType, } =
124
120
  }
125
121
  // Define payload schema for incoming messages
126
122
  const payload = PayloadSchema(type(`"${functionName}"`), schemas.input, schemas.progress, schemas.success).assert(event.data);
123
+ if ("localStorageData" in payload)
124
+ throw "Unreachable: #initialize request payload should've been handled already";
127
125
  // Handle abortion requests (pro-choice ftw!!)
128
126
  if (payload.abort) {
129
127
  const controller = abortControllers.get(requestId);
@@ -141,11 +139,11 @@ export function Server(procedures, { loglevel = "debug", scope, _scopeType, } =
141
139
  try {
142
140
  // Call the implementation with the input and a progress callback
143
141
  const result = await implementation(payload.input, async (progress) => {
144
- l.debug(requestId, `Progress for ${functionName}`, progress);
142
+ // l.debug(requestId, `Progress for ${functionName}`, progress);
145
143
  await postMsg({ progress });
146
144
  }, {
147
145
  abortSignal: abortControllers.get(requestId)?.signal,
148
- logger: createLogger("server", loglevel, requestId),
146
+ logger: createLogger("server", loglevel, nodeId, requestId),
149
147
  });
150
148
  // Send results
151
149
  l.debug(requestId, `Result for ${functionName}`, result);
@@ -168,17 +166,17 @@ export function Server(procedures, { loglevel = "debug", scope, _scopeType, } =
168
166
  }
169
167
  };
170
168
  // Listen for messages from the client
171
- if (scopeIsShared(scope)) {
169
+ if (scopeIsShared(scope, _scopeType)) {
172
170
  if (!port)
173
171
  throw new Error("SharedWorker port not initialized");
174
- console.log("Listening for shared worker messages on port", port);
172
+ l.info(null, "Listening for shared worker messages on port", port);
175
173
  port.addEventListener("message", listener);
176
174
  port.start();
177
175
  }
178
- else if (scopeIsDedicated(scope)) {
176
+ else if (scopeIsDedicated(scope, _scopeType)) {
179
177
  scope.addEventListener("message", listener);
180
178
  }
181
- else if (scopeIsService(scope)) {
179
+ else if (scopeIsService(scope, _scopeType)) {
182
180
  scope.addEventListener("message", listener);
183
181
  }
184
182
  else {
package/dist/types.d.ts CHANGED
@@ -105,6 +105,12 @@ export type Hooks<Procedures extends ProceduresMap> = {
105
105
  */
106
106
  progress?: <Procedure extends keyof ProceduresMap>(procedure: Procedure, data: Procedures[Procedure]["progress"]["inferOut"]) => void;
107
107
  };
108
+ export declare const PayloadInitializeSchema: import("arktype/internal/methods/object.ts").ObjectType<{
109
+ by: "sw&rpc";
110
+ functionName: "#initialize";
111
+ localStorageData: Record<string, unknown>;
112
+ }, {}>;
113
+ export type PayloadInitialize = typeof PayloadInitializeSchema.infer;
108
114
  /**
109
115
  * @source
110
116
  */
@@ -150,7 +156,7 @@ export type PayloadCore<PM extends ProceduresMap, Name extends keyof PM = keyof
150
156
  /**
151
157
  * @source
152
158
  */
153
- export declare const PayloadSchema: import("arktype").Generic<[["Name", string], ["I", unknown], ["P", unknown], ["S", unknown]], readonly ["PayloadHeaderSchema<Name>", "&", "PayloadCoreSchema<I, P, S>"], {
159
+ export declare const PayloadSchema: import("arktype").Generic<[["Name", string], ["I", unknown], ["P", unknown], ["S", unknown]], readonly [readonly ["PayloadHeaderSchema<Name>", "&", "PayloadCoreSchema<I, P, S>"], "|", "PayloadInitializeSchema"], {
154
160
  PayloadCoreSchema: import("arktype/internal/scope.ts").bindGenericToScope<import("@ark/schema").GenericAst<[["I", unknown], ["P", unknown], ["S", unknown]], {
155
161
  readonly "input?": "I";
156
162
  readonly "progress?": "P";
@@ -178,6 +184,17 @@ export declare const PayloadSchema: import("arktype").Generic<[["Name", string],
178
184
  readonly functionName: "Name";
179
185
  readonly requestId: "string >= 1";
180
186
  }, {}, {}>;
187
+ PayloadInitializeSchema: import("arktype/internal/methods/object.ts").ObjectType<{
188
+ by: "sw&rpc";
189
+ functionName: "#initialize";
190
+ localStorageData: Record<string, unknown>;
191
+ }, {}> & {
192
+ readonly " brand": [import("arktype/internal/methods/object.ts").ObjectType<{
193
+ by: "sw&rpc";
194
+ functionName: "#initialize";
195
+ localStorageData: Record<string, unknown>;
196
+ }, {}>, "unparsed"];
197
+ };
181
198
  } & {}>;
182
199
  PayloadHeaderSchema: import("arktype/internal/scope.ts").bindGenericToScope<import("@ark/schema").GenericAst<[["Name", string]], {
183
200
  readonly by: "\"sw&rpc\"";
@@ -200,7 +217,23 @@ export declare const PayloadSchema: import("arktype").Generic<[["Name", string],
200
217
  readonly functionName: "Name";
201
218
  readonly requestId: "string >= 1";
202
219
  }, {}, {}>;
220
+ PayloadInitializeSchema: import("arktype/internal/methods/object.ts").ObjectType<{
221
+ by: "sw&rpc";
222
+ functionName: "#initialize";
223
+ localStorageData: Record<string, unknown>;
224
+ }, {}> & {
225
+ readonly " brand": [import("arktype/internal/methods/object.ts").ObjectType<{
226
+ by: "sw&rpc";
227
+ functionName: "#initialize";
228
+ localStorageData: Record<string, unknown>;
229
+ }, {}>, "unparsed"];
230
+ };
203
231
  } & {}>;
232
+ PayloadInitializeSchema: {
233
+ by: "sw&rpc";
234
+ functionName: "#initialize";
235
+ localStorageData: Record<string, unknown>;
236
+ };
204
237
  }, {
205
238
  PayloadCoreSchema: import("arktype/internal/scope.ts").bindGenericToScope<import("@ark/schema").GenericAst<[["I", unknown], ["P", unknown], ["S", unknown]], {
206
239
  readonly "input?": "I";
@@ -229,6 +262,17 @@ export declare const PayloadSchema: import("arktype").Generic<[["Name", string],
229
262
  readonly functionName: "Name";
230
263
  readonly requestId: "string >= 1";
231
264
  }, {}, {}>;
265
+ PayloadInitializeSchema: import("arktype/internal/methods/object.ts").ObjectType<{
266
+ by: "sw&rpc";
267
+ functionName: "#initialize";
268
+ localStorageData: Record<string, unknown>;
269
+ }, {}> & {
270
+ readonly " brand": [import("arktype/internal/methods/object.ts").ObjectType<{
271
+ by: "sw&rpc";
272
+ functionName: "#initialize";
273
+ localStorageData: Record<string, unknown>;
274
+ }, {}>, "unparsed"];
275
+ };
232
276
  } & {}>;
233
277
  PayloadHeaderSchema: import("arktype/internal/scope.ts").bindGenericToScope<import("@ark/schema").GenericAst<[["Name", string]], {
234
278
  readonly by: "\"sw&rpc\"";
@@ -251,12 +295,28 @@ export declare const PayloadSchema: import("arktype").Generic<[["Name", string],
251
295
  readonly functionName: "Name";
252
296
  readonly requestId: "string >= 1";
253
297
  }, {}, {}>;
298
+ PayloadInitializeSchema: import("arktype/internal/methods/object.ts").ObjectType<{
299
+ by: "sw&rpc";
300
+ functionName: "#initialize";
301
+ localStorageData: Record<string, unknown>;
302
+ }, {}> & {
303
+ readonly " brand": [import("arktype/internal/methods/object.ts").ObjectType<{
304
+ by: "sw&rpc";
305
+ functionName: "#initialize";
306
+ localStorageData: Record<string, unknown>;
307
+ }, {}>, "unparsed"];
308
+ };
254
309
  } & {}>;
310
+ PayloadInitializeSchema: {
311
+ by: "sw&rpc";
312
+ functionName: "#initialize";
313
+ localStorageData: Record<string, unknown>;
314
+ };
255
315
  }>;
256
316
  /**
257
317
  * The effective payload as sent by the server to the client
258
318
  */
259
- export type Payload<PM extends ProceduresMap, Name extends keyof PM = keyof PM> = PayloadHeader<PM, Name> & PayloadCore<PM, Name>;
319
+ export type Payload<PM extends ProceduresMap, Name extends keyof PM = keyof PM> = (PayloadHeader<PM, Name> & PayloadCore<PM, Name>) | PayloadInitialize;
260
320
  /**
261
321
  * A procedure's corresponding method on the client instance -- used to call the procedure. If you want to be able to cancel the request, you can use the `cancelable` method instead of running the procedure directly.
262
322
  */
@@ -265,6 +325,16 @@ export type ClientMethod<P extends Procedure<Type, Type, Type>> = ((input: P["in
265
325
  * A method that returns a `CancelablePromise`. Cancel it by calling `.cancel(reason)` on it, and wait for the request to resolve by awaiting the `request` property on the returned object.
266
326
  */
267
327
  cancelable: (input: P["input"]["inferIn"], onProgress?: (progress: P["progress"]["inferOut"]) => void, requestId?: string) => CancelablePromise<P["success"]["inferOut"]>;
328
+ /**
329
+ * Send the request to specific nodes, or all nodes.
330
+ * Returns an array of results, one for each node the request was sent to.
331
+ * Each result is a {@link PromiseSettledResult}, with also an additional property, the node ID of the request
332
+ */
333
+ broadcast: (input: P["input"]["inferIn"], onProgress?: (progress: P["progress"]["inferOut"]) => void,
334
+ /** Number of nodes to send the request to. Leave undefined to send to all nodes */
335
+ nodes?: number) => Promise<Array<PromiseSettledResult<P["success"]["inferOut"]> & {
336
+ node: string;
337
+ }>>;
268
338
  };
269
339
  /**
270
340
  * Symbol used as the key for the procedures map on the server instance
@@ -278,4 +348,9 @@ export declare const zImplementations: unique symbol;
278
348
  * @source
279
349
  */
280
350
  export declare const zProcedures: unique symbol;
351
+ export type WorkerConstructor<T extends Worker | SharedWorker = Worker | SharedWorker> = {
352
+ new (opts?: {
353
+ name?: string;
354
+ }): T;
355
+ };
281
356
  //# sourceMappingURL=types.d.ts.map
@@ -1 +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,CA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M,WAAW,eAA8B,CAAC;AAEvD,MAAM,MAAM,iBAAiB,CAC3B,CAAC,SAAS,MAAM,GAAG,YAAY,GAAG,MAAM,GAAG,YAAY,IACrD;IACF,KAAK,IAAI,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,CAAC,CAAC;CACnC,CAAC"}
package/dist/types.js CHANGED
@@ -3,6 +3,11 @@
3
3
  * @mergeModuleWith <project>
4
4
  */
5
5
  import { type } from "arktype";
6
+ export const PayloadInitializeSchema = type({
7
+ by: '"sw&rpc"',
8
+ functionName: '"#initialize"',
9
+ localStorageData: "Record<string, unknown>",
10
+ });
6
11
  /**
7
12
  * @source
8
13
  */
@@ -25,11 +30,11 @@ export const PayloadCoreSchema = type("<I, P, S>", {
25
30
  * @source
26
31
  */
27
32
  export const PayloadSchema = type
28
- .scope({ PayloadCoreSchema, PayloadHeaderSchema })
33
+ .scope({ PayloadCoreSchema, PayloadHeaderSchema, PayloadInitializeSchema })
29
34
  .type("<Name extends string, I, P, S>", [
30
- "PayloadHeaderSchema<Name>",
31
- "&",
32
- "PayloadCoreSchema<I, P, S>",
35
+ ["PayloadHeaderSchema<Name>", "&", "PayloadCoreSchema<I, P, S>"],
36
+ "|",
37
+ "PayloadInitializeSchema",
33
38
  ]);
34
39
  /**
35
40
  * Symbol used as the key for the procedures map on the server instance
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "swarpc",
3
- "version": "0.10.0",
3
+ "version": "0.12.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,36 +31,49 @@
31
31
  "dev": "tsc --watch",
32
32
  "typecheck": "tsc --noEmit",
33
33
  "test": "vitest",
34
+ "check": "oxlint",
34
35
  "typedoc": "typedoc",
35
36
  "version": "kacl release && prettier -w CHANGELOG.md && git add CHANGELOG.md",
36
37
  "typedoc:dev": "nodemon --watch src --watch README.md --watch typedoc.json --watch typedoc.css --exec npm run typedoc:withplugins",
37
38
  "typedoc:serve": "npx sirv-cli --dev docs",
38
39
  "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"
40
+ "typedoc:withplugins": "npm run typedoc:plugins && npm run typedoc",
41
+ "prepare": "husky"
40
42
  },
41
43
  "dependencies": {
42
- "arktype": "^2.1.20"
44
+ "arktype": "^2.1.22"
43
45
  },
44
46
  "devDependencies": {
45
47
  "@8hobbies/typedoc-plugin-plausible": "^2.2.0",
46
48
  "@vitest/web-worker": "^3.2.4",
49
+ "husky": "^9.1.7",
47
50
  "kacl": "^1.1.1",
51
+ "knip": "^5.63.1",
52
+ "lint-staged": "^16.1.6",
48
53
  "nodemon": "^3.1.10",
54
+ "oxlint": "^1.14.0",
55
+ "pkg-pr-new": "^0.0.59",
49
56
  "prettier": "^3.6.2",
50
57
  "sirv-cli": "^3.0.1",
51
- "typedoc": "^0.28.9",
58
+ "typedoc": "^0.28.12",
52
59
  "typedoc-material-theme": "^1.4.0",
53
- "typedoc-plugin-dt-links": "^2.0.13",
60
+ "typedoc-plugin-dt-links": "^2.0.18",
54
61
  "typedoc-plugin-extras": "^4.0.1",
55
62
  "typedoc-plugin-inline-sources": "^1.3.0",
56
- "typedoc-plugin-mdn-links": "^5.0.7",
63
+ "typedoc-plugin-mdn-links": "^5.0.9",
57
64
  "typedoc-plugin-redirect": "^1.2.0",
58
65
  "typescript": "^5.9.2",
59
- "vite": "^7.0.6",
66
+ "vite": "^7.1.4",
60
67
  "vitest": "^3.2.4"
61
68
  },
62
69
  "volta": {
63
- "node": "22.18.0",
64
- "npm": "11.5.2"
70
+ "node": "24.7.0",
71
+ "npm": "11.6.0"
72
+ },
73
+ "lint-staged": {
74
+ "*.{ts,js,md,json,yaml,yml}": [
75
+ "oxlint --fix",
76
+ "prettier --write"
77
+ ]
65
78
  }
66
79
  }