@comapeo/ipc 0.16.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Digital Democracy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,85 @@
1
+ # @mapeo/ipc
2
+
3
+ IPC wrappers for [Mapeo Core](https://github.com/digidem/mapeo-core-next). Meant to be used in contexts where there is a communication boundary between the contexts your code runs in e.g. Electron, React Native (with NodeJS Mobile), and NodeJS worker threads. The [channel messaging API](https://developer.mozilla.org/en-US/docs/Web/API/Channel_Messaging_API) is an example where this usage applies.
4
+
5
+ ## Table of Contents
6
+
7
+ - [Installation](#installation)
8
+ - [API](#api)
9
+ - [Usage](#usage)
10
+ - [License](#license)
11
+
12
+ ## Installation
13
+
14
+ Note that [`@mapeo/core`](https://github.com/digidem/mapeo-core-next) is a peer dependency, so you may have to install it manually depending on your package manager.
15
+
16
+ ```sh
17
+ npm install @mapeo/ipc @mapeo/core
18
+ ```
19
+
20
+ ## API
21
+
22
+ ### `createMapeoServer(manager: MapeoManager, messagePort: MessagePortLike): { close: () => void }`
23
+
24
+ Creates the IPC server instance. `manager` is a `@mapeo/core` `MapeoManager` instance and `messagePort` is an interface that resembles a [`MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort).
25
+
26
+ Returns an object with a `close()` method, which removes relevant event listeners from the `messagePort`. Does not close or destroy the `messagePort`.
27
+
28
+ ### `createMapeoClient(messagePort: MessagePortLike, opts?: { timeout?: number }): ClientApi<MapeoManager>`
29
+
30
+ Creates the IPC client instance. `messagePort` is an interface that resembles a [`MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort). `opts.timeout` is an optional timeout used for sending and receiving messages over the channel.
31
+
32
+ Returns a client instance that reflects the interface of the `manager` provided to [`createMapeoServer`](#createmapeoservermanager-mapeomanager-messageport-messageportlike--close---void). Refer to the [`rpc-reflector` docs](https://github.com/digidem/rpc-reflector#const-clientapi--createclientchannel) for additional information about how to use this.
33
+
34
+ ### `closeMapeoClient(mapeoClient: ClientApi<MapeoManager>): void`
35
+
36
+ Closes the IPC client instance. Does not close or destroy the `messagePort` provided to [`createMapeoClient`](#createmapeoclientmessageport-messageportlike-clientapimapeomanager).
37
+
38
+ ## Usage
39
+
40
+ In the server:
41
+
42
+ ```ts
43
+ import { MapeoManager } from '@mapeo/core'
44
+ import { createMapeoServer } from '@mapeo/ipc'
45
+
46
+ // Create Mapeo manager instance
47
+ const manager = new MapeoManager({...})
48
+
49
+ // Create the server instance
50
+ // `messagePort` can vary based on context (e.g. a port from a MessageChannel, a NodeJS Mobile bridge channel, etc.)
51
+ const server = createMapeoServer(manager, messagePort)
52
+
53
+ // Maybe at some point later on...
54
+
55
+ // Close the server
56
+ server.close()
57
+ ```
58
+
59
+ In the client:
60
+
61
+ ```ts
62
+ import { createMapeoClient, closeMapeoClient } from '@mapeo/ipc'
63
+
64
+ // Create the client instance
65
+ // `messagePort` can vary based on context (e.g. a port from a MessageChannel, a NodeJS Mobile bridge channel, etc.)
66
+ const client = createMapeoClient(messagePort)
67
+
68
+ // Use the MapeoManager instance from the server via the client!
69
+ const projectId = await client.createProject({...})
70
+ const project = await client.getProject(projectId)
71
+ const projects = await client.listProjects()
72
+
73
+ client.on('invite-received', (invite) => {
74
+ // ...
75
+ })
76
+
77
+ // Maybe at some point later on...
78
+
79
+ // Close the client
80
+ closeMapeoClient(client)
81
+ ```
82
+
83
+ ## License
84
+
85
+ [MIT](LICENSE)
@@ -0,0 +1,91 @@
1
+ /**
2
+ * @param {import('./lib/sub-channel.js').MessagePortLike} messagePort
3
+ * @param {object} [opts]
4
+ * @param {number} [opts.timeout]
5
+ *
6
+ * @returns {MapeoClientApi}
7
+ */
8
+ export function createMapeoClient(messagePort: import('./lib/sub-channel.js').MessagePortLike, opts?: {
9
+ timeout?: number | undefined;
10
+ } | undefined): MapeoClientApi;
11
+ /**
12
+ * @param {MapeoClientApi} client client created with `createMapeoClient`
13
+ * @returns {Promise<void>}
14
+ */
15
+ export function closeMapeoClient(client: MapeoClientApi): Promise<void>;
16
+ export type MapeoProjectApi = import('rpc-reflector/client.js').ClientApi<import('@mapeo/core/dist/mapeo-project.js').MapeoProject>;
17
+ export type MapeoClientApi = {
18
+ addListener: <U extends "local-peers">(event: U, listener: import("@mapeo/core/dist/mapeo-manager.js").MapeoManagerEvents[U]) => import("@mapeo/core").MapeoManager;
19
+ on: <U_1 extends "local-peers">(event: U_1, listener: import("@mapeo/core/dist/mapeo-manager.js").MapeoManagerEvents[U_1]) => import("@mapeo/core").MapeoManager;
20
+ once: <U_2 extends "local-peers">(event: U_2, listener: import("@mapeo/core/dist/mapeo-manager.js").MapeoManagerEvents[U_2]) => import("@mapeo/core").MapeoManager;
21
+ removeListener: <U_3 extends "local-peers">(event: U_3, listener: import("@mapeo/core/dist/mapeo-manager.js").MapeoManagerEvents[U_3]) => import("@mapeo/core").MapeoManager;
22
+ off: <U_4 extends "local-peers">(event: U_4, listener: import("@mapeo/core/dist/mapeo-manager.js").MapeoManagerEvents[U_4]) => import("@mapeo/core").MapeoManager;
23
+ removeAllListeners: (event?: "local-peers" | undefined) => import("@mapeo/core").MapeoManager;
24
+ listeners: <U_5 extends "local-peers">(type: U_5) => import("@mapeo/core/dist/mapeo-manager.js").MapeoManagerEvents[U_5][];
25
+ rawListeners: <U_6 extends "local-peers">(type: U_6) => import("@mapeo/core/dist/mapeo-manager.js").MapeoManagerEvents[U_6][];
26
+ emit: <U_7 extends "local-peers">(event: U_7, ...args: Parameters<import("@mapeo/core/dist/mapeo-manager.js").MapeoManagerEvents[U_7]>) => boolean;
27
+ listenerCount: (type: "local-peers") => number;
28
+ eventNames: <U_8 extends "local-peers">() => U_8[];
29
+ readonly deviceId: () => Promise<string>;
30
+ createProject: ({ name, configPath }?: {
31
+ name?: string | undefined;
32
+ configPath?: string | undefined;
33
+ } | undefined) => Promise<string>;
34
+ listProjects: () => Promise<(Pick<{
35
+ schemaName: "projectSettings";
36
+ name?: string | undefined;
37
+ defaultPresets?: {
38
+ point: string[];
39
+ area: string[];
40
+ vertex: string[];
41
+ line: string[];
42
+ relation: string[];
43
+ } | undefined;
44
+ configMetadata?: {
45
+ name: string;
46
+ buildDate: string;
47
+ importDate: string;
48
+ fileVersion: string;
49
+ } | undefined;
50
+ }, "name"> & {
51
+ projectId: string;
52
+ createdAt?: string | undefined;
53
+ updatedAt?: string | undefined;
54
+ })[]>;
55
+ addProject: ({ projectKey, encryptionKeys, projectName }: Pick<import("@mapeo/core/dist/generated/rpc.js").ProjectJoinDetails, "projectKey" | "encryptionKeys"> & {
56
+ projectName: string;
57
+ }, { waitForSync }?: {
58
+ waitForSync?: boolean | undefined;
59
+ } | undefined) => Promise<string>;
60
+ setDeviceInfo: <T extends import("type-fest").IsEqual<import("@mapeo/core/dist/schema/client.js").DeviceInfoParam & {
61
+ deviceType?: "device_type_unspecified" | "mobile" | "tablet" | "desktop" | "UNRECOGNIZED" | undefined;
62
+ }, T> extends true ? import("@mapeo/core/dist/schema/client.js").DeviceInfoParam & {
63
+ deviceType?: "device_type_unspecified" | "mobile" | "tablet" | "desktop" | "UNRECOGNIZED" | undefined;
64
+ } : import("type-fest/source/exact.js").ExactObject<import("@mapeo/core/dist/schema/client.js").DeviceInfoParam & {
65
+ deviceType?: "device_type_unspecified" | "mobile" | "tablet" | "desktop" | "UNRECOGNIZED" | undefined;
66
+ }, T>>(deviceInfo: T) => Promise<void>;
67
+ getDeviceInfo: () => Promise<{
68
+ deviceId: string;
69
+ deviceType: "device_type_unspecified" | "mobile" | "tablet" | "desktop" | "selfHostedServer" | "UNRECOGNIZED";
70
+ } & Partial<import("@mapeo/core/dist/schema/client.js").DeviceInfoParam>>;
71
+ readonly invite: import("rpc-reflector/lib/types.js").ClientApi<import("@mapeo/core/dist/invite-api.js").InviteApi> & (() => Promise<import("@mapeo/core/dist/invite-api.js").InviteApi>);
72
+ startLocalPeerDiscoveryServer: () => Promise<{
73
+ name: string;
74
+ port: number;
75
+ }>;
76
+ stopLocalPeerDiscoveryServer: (opts?: {
77
+ force?: boolean | undefined;
78
+ timeout?: number | undefined;
79
+ } | undefined) => Promise<void>;
80
+ connectLocalPeer: (args_0: {
81
+ address: string;
82
+ port: number;
83
+ name: string;
84
+ }) => Promise<void>;
85
+ listLocalPeers: () => Promise<import("@mapeo/core/dist/mapeo-manager.js").PublicPeerInfo[]>;
86
+ onBackgrounded: () => Promise<void>;
87
+ onForegrounded: () => Promise<void>;
88
+ leaveProject: (projectPublicId: string) => Promise<void>;
89
+ getMapStyleJsonUrl: () => Promise<string>;
90
+ getProject: (projectPublicId: string) => Promise<MapeoProjectApi>;
91
+ };
package/dist/client.js ADDED
@@ -0,0 +1,90 @@
1
+ import { createClient } from 'rpc-reflector';
2
+ import pDefer from 'p-defer';
3
+ import { MANAGER_CHANNEL_ID, MAPEO_RPC_ID, SubChannel, } from './lib/sub-channel.js';
4
+ /**
5
+ * @typedef {import('rpc-reflector/client.js').ClientApi<import('@mapeo/core/dist/mapeo-project.js').MapeoProject>} MapeoProjectApi
6
+ */
7
+ /**
8
+ * @typedef {import('rpc-reflector/client.js').ClientApi<
9
+ * Omit<
10
+ * import('@mapeo/core').MapeoManager,
11
+ * 'getProject'
12
+ * > & {
13
+ * getProject: (projectPublicId: string) => Promise<MapeoProjectApi>
14
+ * }
15
+ * >} MapeoClientApi */
16
+ const CLOSE = Symbol('close');
17
+ /**
18
+ * @param {import('./lib/sub-channel.js').MessagePortLike} messagePort
19
+ * @param {object} [opts]
20
+ * @param {number} [opts.timeout]
21
+ *
22
+ * @returns {MapeoClientApi}
23
+ */
24
+ export function createMapeoClient(messagePort, opts = {}) {
25
+ /** @type {Map<string, Promise<import('rpc-reflector/client.js').ClientApi<import('@mapeo/core/dist/mapeo-project.js').MapeoProject>>>} */
26
+ const projectClientPromises = new Map();
27
+ const managerChannel = new SubChannel(messagePort, MANAGER_CHANNEL_ID);
28
+ const mapeoRpcChannel = new SubChannel(messagePort, MAPEO_RPC_ID);
29
+ /** @type {import('rpc-reflector').ClientApi<import('@mapeo/core').MapeoManager>} */
30
+ const managerClient = createClient(managerChannel, opts);
31
+ /** @type {import('rpc-reflector').ClientApi<import('./server.js').MapeoRpcApi>} */
32
+ const mapeoRpcClient = createClient(mapeoRpcChannel, opts);
33
+ mapeoRpcChannel.start();
34
+ managerChannel.start();
35
+ const client = new Proxy(managerClient, {
36
+ get(target, prop, receiver) {
37
+ if (prop === CLOSE) {
38
+ return async () => {
39
+ managerChannel.close();
40
+ createClient.close(managerClient);
41
+ const projectClientResults = await Promise.allSettled(projectClientPromises.values());
42
+ for (const result of projectClientResults) {
43
+ if (result.status === 'fulfilled') {
44
+ createClient.close(result.value);
45
+ }
46
+ }
47
+ };
48
+ }
49
+ if (prop === 'getProject') {
50
+ return createProjectClient;
51
+ }
52
+ return Reflect.get(target, prop, receiver);
53
+ },
54
+ });
55
+ // TS can't know the type of the proxy, so we cast it in the function return
56
+ return /** @type {any} */ (client);
57
+ /**
58
+ * @param {string} projectPublicId
59
+ * @returns {Promise<MapeoProjectApi>}
60
+ */
61
+ async function createProjectClient(projectPublicId) {
62
+ const existingClientPromise = projectClientPromises.get(projectPublicId);
63
+ if (existingClientPromise)
64
+ return existingClientPromise;
65
+ /** @type {import('p-defer').DeferredPromise<import('rpc-reflector/client.js').ClientApi<import('@mapeo/core/dist/mapeo-project.js').MapeoProject>>}*/
66
+ const deferred = pDefer();
67
+ projectClientPromises.set(projectPublicId, deferred.promise);
68
+ try {
69
+ await mapeoRpcClient.assertProjectExists(projectPublicId);
70
+ }
71
+ catch (err) {
72
+ deferred.reject(err);
73
+ throw err;
74
+ }
75
+ const projectChannel = new SubChannel(messagePort, projectPublicId);
76
+ /** @type {import('rpc-reflector').ClientApi<import('@mapeo/core/dist/mapeo-project.js').MapeoProject>} */
77
+ const projectClient = createClient(projectChannel, opts);
78
+ projectChannel.start();
79
+ deferred.resolve(projectClient);
80
+ return projectClient;
81
+ }
82
+ }
83
+ /**
84
+ * @param {MapeoClientApi} client client created with `createMapeoClient`
85
+ * @returns {Promise<void>}
86
+ */
87
+ export async function closeMapeoClient(client) {
88
+ // @ts-expect-error
89
+ return client[CLOSE]();
90
+ }
@@ -0,0 +1,4 @@
1
+ export { createMapeoServer } from "./server.js";
2
+ export type MapeoClientApi = import('./client.js').MapeoClientApi;
3
+ export type MapeoProjectApi = import('./client.js').MapeoProjectApi;
4
+ export { createMapeoClient, closeMapeoClient } from "./client.js";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { createMapeoClient, closeMapeoClient } from './client.js';
2
+ export { createMapeoServer } from './server.js';
3
+ /** @typedef {import('./client.js').MapeoClientApi} MapeoClientApi */
4
+ /** @typedef {import('./client.js').MapeoProjectApi} MapeoProjectApi */
@@ -0,0 +1,38 @@
1
+ export const MAPEO_RPC_ID: "@@mapeo-rpc";
2
+ export const MANAGER_CHANNEL_ID: "@@manager";
3
+ /**
4
+ * @typedef {Object} Events
5
+ * @property {(message: any) => void} message
6
+ */
7
+ /**
8
+ * Node's built-in types for MessagePort are misleading so we opt for this limited type definition
9
+ * that fits our usage and works in both Node and browser contexts
10
+ * @typedef {Pick<EventTarget, 'addEventListener' | 'removeEventListener'> & { postMessage: (message: any) => void }} MessagePortLike
11
+ */
12
+ export class SubChannel extends EventEmitter<string | symbol, any> {
13
+ /**
14
+ * @param {MessagePortLike} messagePort Parent channel to add namespace to
15
+ * @param {string} id ID for the subchannel
16
+ */
17
+ constructor(messagePort: MessagePortLike, id: string);
18
+ get id(): string;
19
+ /**
20
+ * Send messages with the subchannel's ID
21
+ * @param {any} message
22
+ */
23
+ postMessage(message: any): void;
24
+ start(): void;
25
+ close(): void;
26
+ #private;
27
+ }
28
+ export type Events = {
29
+ message: (message: any) => void;
30
+ };
31
+ /**
32
+ * Node's built-in types for MessagePort are misleading so we opt for this limited type definition
33
+ * that fits our usage and works in both Node and browser contexts
34
+ */
35
+ export type MessagePortLike = Pick<EventTarget, "addEventListener" | "removeEventListener"> & {
36
+ postMessage: (message: any) => void;
37
+ };
38
+ import { EventEmitter } from 'eventemitter3';
@@ -0,0 +1,101 @@
1
+ import { EventEmitter } from 'eventemitter3';
2
+ import { extractMessageEventData } from './utils.js';
3
+ // Ideally unique ID used for identifying "global" Mapeo IPC messages
4
+ export const MAPEO_RPC_ID = '@@mapeo-rpc';
5
+ export const MANAGER_CHANNEL_ID = '@@manager';
6
+ /**
7
+ * @typedef {Object} Events
8
+ * @property {(message: any) => void} message
9
+ */
10
+ /**
11
+ * Node's built-in types for MessagePort are misleading so we opt for this limited type definition
12
+ * that fits our usage and works in both Node and browser contexts
13
+ * @typedef {Pick<EventTarget, 'addEventListener' | 'removeEventListener'> & { postMessage: (message: any) => void }} MessagePortLike
14
+ */
15
+ export class SubChannel extends EventEmitter {
16
+ #id;
17
+ #messagePort;
18
+ /** @type {'idle' | 'active' | 'closed'} */
19
+ #state;
20
+ /** @type {Array<{id: string, message: any}>} */
21
+ #queued;
22
+ #handleMessageEvent;
23
+ /**
24
+ * @param {MessagePortLike} messagePort Parent channel to add namespace to
25
+ * @param {string} id ID for the subchannel
26
+ */
27
+ constructor(messagePort, id) {
28
+ super();
29
+ this.#id = id;
30
+ this.#messagePort = messagePort;
31
+ this.#state = 'idle';
32
+ this.#queued = [];
33
+ /**
34
+ * @param {unknown} event
35
+ */
36
+ this.#handleMessageEvent = (event) => {
37
+ const value = extractMessageEventData(event);
38
+ if (!isRelevantEvent(value))
39
+ return;
40
+ const { id, message } = value;
41
+ if (this.#id !== id)
42
+ return;
43
+ switch (this.#state) {
44
+ case 'idle': {
45
+ this.#queued.push(value);
46
+ break;
47
+ }
48
+ case 'active': {
49
+ this.emit('message', message);
50
+ break;
51
+ }
52
+ case 'closed': {
53
+ // no-op if closed (the event listener should be removed anyway)
54
+ break;
55
+ }
56
+ }
57
+ };
58
+ this.#messagePort.addEventListener('message', this.#handleMessageEvent);
59
+ }
60
+ get id() {
61
+ return this.#id;
62
+ }
63
+ /**
64
+ * Send messages with the subchannel's ID
65
+ * @param {any} message
66
+ */
67
+ postMessage(message) {
68
+ this.#messagePort.postMessage({ id: this.#id, message });
69
+ }
70
+ start() {
71
+ if (this.#state !== 'idle')
72
+ return;
73
+ this.#state = 'active';
74
+ /** @type {{id: string, message: any} | undefined} */
75
+ let event;
76
+ while ((event = this.#queued.shift())) {
77
+ this.#handleMessageEvent(event);
78
+ }
79
+ }
80
+ close() {
81
+ if (this.#state === 'closed')
82
+ return;
83
+ this.#state = 'closed';
84
+ this.#queued = [];
85
+ // Node types are incorrect (as of v14, Node's MessagePort should also extend [EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget))
86
+ this.#messagePort.removeEventListener('message', this.#handleMessageEvent);
87
+ }
88
+ }
89
+ /**
90
+ * @param {unknown} event
91
+ * @returns {event is { id: string, message: any }}
92
+ */
93
+ function isRelevantEvent(event) {
94
+ if (!event || typeof event !== 'object')
95
+ return false;
96
+ if (!('id' in event && 'message' in event))
97
+ return false;
98
+ if (typeof event.id !== 'string')
99
+ return false;
100
+ return true;
101
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @template T
3
+ * @param {T} event
4
+ * @returns {T extends { data: infer D } ? D : T}
5
+ */
6
+ export function extractMessageEventData<T>(event: T): T extends {
7
+ data: infer D;
8
+ } ? D : T;
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @template T
3
+ * @param {T} event
4
+ * @returns {T extends { data: infer D } ? D : T}
5
+ */
6
+ export function extractMessageEventData(event) {
7
+ // In browser-like contexts, the actual payload will live in the `event.data` field
8
+ // https://developer.mozilla.org/en-US/docs/Web/API/MessagePort/message_event#event_properties
9
+ if (event && typeof event === 'object' && 'data' in event) {
10
+ return /** @type {any} */ (event.data);
11
+ }
12
+ // In Node the event is the actual data that was sent
13
+ return /** @type {any} */ (event);
14
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * @param {import('@mapeo/core').MapeoManager} manager
3
+ * @param {import('./lib/sub-channel.js').MessagePortLike} messagePort
4
+ */
5
+ export function createMapeoServer(manager: import('@mapeo/core').MapeoManager, messagePort: import('./lib/sub-channel.js').MessagePortLike): {
6
+ close(): void;
7
+ };
8
+ export class MapeoRpcApi {
9
+ /**
10
+ * @param {import('@mapeo/core').MapeoManager} manager
11
+ */
12
+ constructor(manager: import('@mapeo/core').MapeoManager);
13
+ /**
14
+ * @param {string} projectId
15
+ * @returns {Promise<boolean>}
16
+ */
17
+ assertProjectExists(projectId: string): Promise<boolean>;
18
+ #private;
19
+ }
package/dist/server.js ADDED
@@ -0,0 +1,86 @@
1
+ import { createServer } from 'rpc-reflector';
2
+ import { MANAGER_CHANNEL_ID, MAPEO_RPC_ID, SubChannel, } from './lib/sub-channel.js';
3
+ import { extractMessageEventData } from './lib/utils.js';
4
+ /**
5
+ * @param {import('@mapeo/core').MapeoManager} manager
6
+ * @param {import('./lib/sub-channel.js').MessagePortLike} messagePort
7
+ */
8
+ export function createMapeoServer(manager, messagePort) {
9
+ /** @type {Map<string, { close: () => void }>} */
10
+ const existingProjectServers = new Map();
11
+ /** @type {Map<string, SubChannel>} */
12
+ const existingProjectChannels = new Map();
13
+ const mapeoRpcApi = new MapeoRpcApi(manager);
14
+ const managerChannel = new SubChannel(messagePort, MANAGER_CHANNEL_ID);
15
+ const mapeoRpcChannel = new SubChannel(messagePort, MAPEO_RPC_ID);
16
+ const managerServer = createServer(manager, managerChannel);
17
+ const mapeoRpcServer = createServer(mapeoRpcApi, mapeoRpcChannel);
18
+ managerChannel.start();
19
+ mapeoRpcChannel.start();
20
+ messagePort.addEventListener('message', handleMessage);
21
+ return {
22
+ close() {
23
+ messagePort.removeEventListener('message', handleMessage);
24
+ for (const [id, server] of existingProjectServers.entries()) {
25
+ server.close();
26
+ const channel = existingProjectChannels.get(id);
27
+ if (channel) {
28
+ channel.close();
29
+ existingProjectChannels.delete(id);
30
+ }
31
+ existingProjectServers.delete(id);
32
+ }
33
+ managerServer.close();
34
+ managerChannel.close();
35
+ mapeoRpcServer.close();
36
+ mapeoRpcChannel.close();
37
+ },
38
+ };
39
+ /**
40
+ * @param {unknown} payload
41
+ */
42
+ async function handleMessage(payload) {
43
+ const data = extractMessageEventData(payload);
44
+ if (!data || typeof data !== 'object' || !('message' in data))
45
+ return;
46
+ const id = 'id' in data && typeof data.id === 'string' ? data.id : null;
47
+ if (!id || id === MANAGER_CHANNEL_ID || id === MAPEO_RPC_ID)
48
+ return;
49
+ if (existingProjectChannels.has(id))
50
+ return;
51
+ const projectChannel = new SubChannel(messagePort, id);
52
+ existingProjectChannels.set(id, projectChannel);
53
+ let project;
54
+ try {
55
+ project = await manager.getProject(id);
56
+ }
57
+ catch (err) {
58
+ // TODO: how to respond to client so that method errors?
59
+ projectChannel.close();
60
+ existingProjectChannels.delete(id);
61
+ existingProjectServers.delete(id);
62
+ return;
63
+ }
64
+ const { close } = createServer(project, projectChannel);
65
+ existingProjectServers.set(id, { close });
66
+ projectChannel.emit('message', data.message);
67
+ projectChannel.start();
68
+ }
69
+ }
70
+ export class MapeoRpcApi {
71
+ #manager;
72
+ /**
73
+ * @param {import('@mapeo/core').MapeoManager} manager
74
+ */
75
+ constructor(manager) {
76
+ this.#manager = manager;
77
+ }
78
+ /**
79
+ * @param {string} projectId
80
+ * @returns {Promise<boolean>}
81
+ */
82
+ async assertProjectExists(projectId) {
83
+ const project = await this.#manager.getProject(projectId);
84
+ return !!project;
85
+ }
86
+ }
package/package.json ADDED
@@ -0,0 +1,87 @@
1
+ {
2
+ "name": "@comapeo/ipc",
3
+ "version": "0.16.0",
4
+ "description": "IPC wrappers for Mapeo Core",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "engines": {
9
+ "node": ">=18.17.1"
10
+ },
11
+ "scripts": {
12
+ "format": "prettier **/*.{js,md} --write",
13
+ "lint": "eslint . --cache",
14
+ "types": "tsc -p tsconfig.json",
15
+ "test:unit": "node --test tests/*.js",
16
+ "test": "npm-run-all lint types test:unit",
17
+ "bench": "node bench/bench.js",
18
+ "build": "tsc -p tsconfig.npm.json",
19
+ "prepack": "npm run build",
20
+ "prepare": "husky install",
21
+ "release": "standard-version"
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/digidem/mapeo-ipc.git"
29
+ },
30
+ "keywords": [
31
+ "mapeo",
32
+ "ipc"
33
+ ],
34
+ "author": {
35
+ "name": "Andrew Chou"
36
+ },
37
+ "license": "MIT",
38
+ "bugs": {
39
+ "url": "https://github.com/digidem/mapeo-ipc/issues"
40
+ },
41
+ "homepage": "https://github.com/digidem/mapeo-ipc#readme",
42
+ "dependencies": {
43
+ "eventemitter3": "^5.0.1",
44
+ "p-defer": "^4.0.0",
45
+ "rpc-reflector": "^1.3.11"
46
+ },
47
+ "peerDependencies": {
48
+ "@mapeo/core": "9.0.0-alpha.24"
49
+ },
50
+ "devDependencies": {
51
+ "@digidem/types": "^2.1.0",
52
+ "@mapeo/crypto": "^1.0.0-alpha.8",
53
+ "@types/nanobench": "^3.0.0",
54
+ "@types/node": "^20.7.1",
55
+ "@types/tmp": "^0.2.6",
56
+ "eslint": "^8.50.0",
57
+ "fastify": "^4.26.2",
58
+ "husky": "^8.0.0",
59
+ "lint-staged": "^14.0.1",
60
+ "nanobench": "^3.0.0",
61
+ "npm-run-all": "^4.1.5",
62
+ "prettier": "^3.0.3",
63
+ "random-access-memory": "^6.2.0",
64
+ "standard-version": "^9.5.0",
65
+ "tmp": "^0.2.3",
66
+ "typescript": "^5.2.2"
67
+ },
68
+ "prettier": {
69
+ "semi": false,
70
+ "singleQuote": true
71
+ },
72
+ "eslintConfig": {
73
+ "env": {
74
+ "commonjs": true,
75
+ "es2021": true,
76
+ "node": true
77
+ },
78
+ "extends": "eslint:recommended",
79
+ "parserOptions": {
80
+ "ecmaVersion": "latest",
81
+ "sourceType": "module"
82
+ }
83
+ },
84
+ "lint-staged": {
85
+ "*.{js,md}": "prettier . --write"
86
+ }
87
+ }