@nonstrict/recordkit 0.1.0 → 0.2.1

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.
@@ -1,16 +1,9 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
- import { EventEmitter } from 'events';
3
- export declare class IpcRecordKit extends EventEmitter {
1
+ import { NSRPC } from "./NonstrictRPC.js";
2
+ export declare class IpcRecordKit {
4
3
  private logMessages;
5
4
  private childProcess?;
6
- private responseHandler;
7
- private methodHandler;
8
- initialize(recordKitCliPath: string, logMessages?: boolean): Promise<void>;
5
+ readonly nsrpc: NSRPC;
6
+ constructor();
7
+ initialize(recordKitRpcPath: string, logMessages?: boolean): Promise<void>;
9
8
  private write;
10
- sendRequest(method: string, params: any): Promise<any>;
11
- sendNotification(method: string, params: any): Promise<void>;
12
- registerClosure(prefix: string, handler: (payload: any) => any): string;
13
- registerMethod(method: string, handler: (payload: any) => any): void;
14
- unregisterMethod(method: string): void;
15
9
  }
16
- //# sourceMappingURL=IpcRecordKit.d.ts.map
@@ -1,120 +1,42 @@
1
- import { EventEmitter } from 'events';
2
- import { randomUUID } from 'crypto';
3
1
  import { spawn } from 'node:child_process';
4
2
  import * as readline from 'readline';
5
- export class IpcRecordKit extends EventEmitter {
3
+ import { NSRPC } from "./NonstrictRPC.js";
4
+ export class IpcRecordKit {
5
+ logMessages = false;
6
+ childProcess;
7
+ nsrpc;
6
8
  constructor() {
7
- super(...arguments);
8
- this.logMessages = false;
9
- this.responseHandler = new Map();
10
- this.methodHandler = new Map();
9
+ this.nsrpc = new NSRPC((message) => this.write(message));
11
10
  }
12
- async initialize(recordKitCliPath, logMessages = false) {
11
+ async initialize(recordKitRpcPath, logMessages = false) {
13
12
  if (this.childProcess !== undefined) {
14
- throw new Error('RecordKit CLI: Already initialized.');
13
+ throw new Error('RecordKit RPC: Already initialized.');
15
14
  }
16
15
  this.logMessages = logMessages;
17
16
  this.childProcess = await new Promise((resolve, reject) => {
18
- const childProcess = spawn(recordKitCliPath);
17
+ const childProcess = spawn(recordKitRpcPath);
19
18
  childProcess.on('spawn', () => { resolve(childProcess); });
20
19
  childProcess.on('error', (error) => { reject(error); });
21
20
  });
22
21
  const { stdout } = this.childProcess;
23
22
  if (!stdout) {
24
- throw new Error('RecordKit CLI: No stdout stream on child process.');
23
+ throw new Error('RecordKit RPC: No stdout stream on child process.');
25
24
  }
26
25
  readline.createInterface({ input: stdout }).on('line', (line) => {
27
26
  if (logMessages) {
28
27
  console.log("< ", line.trimEnd());
29
28
  }
30
- const message = JSON.parse(line);
31
- if (message.jsonrpc !== '2.0') {
32
- console.error("Invalid JSON-RPC message: ", line);
33
- return;
34
- }
35
- if (message.result && message.id) {
36
- const responseHandler = this.responseHandler.get(message.id);
37
- if (!responseHandler) {
38
- console.error("Received response for unknown request: ", line);
39
- return;
40
- }
41
- responseHandler?.resolve(message.result);
42
- this.responseHandler.delete(message.id);
43
- }
44
- else if (message.error && message.id) {
45
- const responseHandler = this.responseHandler.get(message.id);
46
- if (!responseHandler) {
47
- console.error("Received response for unknown request: ", line);
48
- return;
49
- }
50
- responseHandler?.reject(message.error);
51
- this.responseHandler.delete(message.id);
52
- }
53
- else if (message.method) {
54
- const methodHandler = this.methodHandler.get(message.method);
55
- if (!methodHandler) {
56
- console.error("No handler installed for method: ", line);
57
- return;
58
- }
59
- try {
60
- const response = methodHandler(message.params); // TODO: Catch the error and send back over JSONRPC
61
- if (message.id && response) {
62
- this.write({ jsonrpc: '2.0', id: message.id, result: response });
63
- }
64
- else if (message.id) {
65
- // Missing response
66
- this.write({ jsonrpc: '2.0', id: message.id, error: { code: -32603, message: 'Method called, but no response produced.' } });
67
- }
68
- else if (response) {
69
- console.error("No response expected, throwing away result: ", response);
70
- }
71
- }
72
- catch (error) {
73
- if (message.id) {
74
- this.write({ jsonrpc: '2.0', id: message.id, error: { code: -32603, message: 'Method threw error.', data: error } });
75
- }
76
- else {
77
- console.error("Handler for notification with method '\(message.method)' threw an error:", error);
78
- }
79
- }
80
- }
81
- else {
82
- console.error("Invalid JSON-RPC message: ", line);
83
- }
29
+ this.nsrpc.receive(line);
84
30
  });
85
31
  }
86
32
  write(message) {
87
33
  const stdin = this.childProcess?.stdin;
88
34
  if (!stdin) {
89
- throw new Error('RecordKit CLI: Missing stdin stream.');
35
+ throw new Error('RecordKit RPC: Missing stdin stream.');
90
36
  }
91
- const stringifiedMessage = JSON.stringify(message);
92
37
  if (this.logMessages) {
93
- console.log("> ", stringifiedMessage);
38
+ console.log("> ", message);
94
39
  }
95
- stdin.write(stringifiedMessage + "\n");
96
- }
97
- async sendRequest(method, params) {
98
- const id = 'request_' + randomUUID();
99
- const response = new Promise((resolve, reject) => { this.responseHandler.set(id, { resolve, reject }); });
100
- this.write({ jsonrpc: '2.0', id, method, params });
101
- return response;
102
- }
103
- async sendNotification(method, params) {
104
- this.write({ jsonrpc: '2.0', method, params });
105
- }
106
- registerClosure(prefix, handler) {
107
- const methodName = prefix + '_' + randomUUID();
108
- this.registerMethod(methodName, handler);
109
- return methodName;
110
- }
111
- registerMethod(method, handler) {
112
- if (this.methodHandler.has(method)) {
113
- throw new Error(`Method already registered: ${method}`);
114
- }
115
- this.methodHandler.set(method, handler);
116
- }
117
- unregisterMethod(method) {
118
- this.methodHandler.delete(method);
40
+ stdin.write(message + "\n");
119
41
  }
120
42
  }
@@ -0,0 +1,39 @@
1
+ export interface NSRPCPerformClosureRequest {
2
+ nsrpc: number;
3
+ id?: string;
4
+ procedure: "perform";
5
+ target: string;
6
+ params?: Record<string, unknown>;
7
+ }
8
+ type ClosureTarget = (params: Record<string, unknown>) => Record<string, unknown> | void;
9
+ export declare class NSRPC {
10
+ private readonly send;
11
+ private responseHandlers;
12
+ private closureTargets;
13
+ constructor(send: (data: string) => void);
14
+ receive(data: string): void;
15
+ private sendMessage;
16
+ private sendResponse;
17
+ private sendRequest;
18
+ private handleRequest;
19
+ private handleClosureRequest;
20
+ initialize(args: {
21
+ target: string;
22
+ type: string;
23
+ params?: Record<string, unknown>;
24
+ lifecycle: Object;
25
+ }): Promise<void>;
26
+ perform(body: {
27
+ type?: string;
28
+ target?: string;
29
+ action?: string;
30
+ params?: Record<string, unknown>;
31
+ }): Promise<unknown>;
32
+ private release;
33
+ registerClosure(options: {
34
+ handler: ClosureTarget;
35
+ lifecycle: Object;
36
+ prefix: string;
37
+ }): string;
38
+ }
39
+ export {};
@@ -0,0 +1,156 @@
1
+ import { randomUUID } from "crypto";
2
+ import { finalizationRegistry } from "./finalizationRegistry.js";
3
+ export class NSRPC {
4
+ send;
5
+ responseHandlers = new Map();
6
+ closureTargets = new Map();
7
+ constructor(send) {
8
+ this.send = send;
9
+ }
10
+ receive(data) {
11
+ // TODO: For now we just assume the message is a valid NSRPC message, but we should:
12
+ // - Handle invalid JSON comming in
13
+ // - Check if the nsrpc property is set to a number in the range of 1..<2
14
+ // - Validate the message against the defined interfaces above
15
+ const message = JSON.parse(data);
16
+ if ("status" in message) {
17
+ // This is a response, dispatch it so it can be handled
18
+ const responseHandler = this.responseHandlers.get(message.id);
19
+ this.responseHandlers.delete(message.id);
20
+ if (responseHandler === undefined) {
21
+ // TODO: Got a response for a request we don't know about, log this
22
+ return;
23
+ }
24
+ if ("error" in message) {
25
+ responseHandler.reject(message.error);
26
+ }
27
+ else {
28
+ responseHandler.resolve(message.result);
29
+ }
30
+ }
31
+ else {
32
+ // This is a request
33
+ const responseBody = this.handleRequest(message);
34
+ if (responseBody !== undefined) {
35
+ this.sendResponse(message.id, responseBody);
36
+ }
37
+ }
38
+ }
39
+ /* Sending helpers */
40
+ sendMessage(message) {
41
+ this.send(JSON.stringify(message));
42
+ }
43
+ sendResponse(id, response) {
44
+ if (id === undefined) {
45
+ return;
46
+ }
47
+ this.sendMessage({ ...response, nsrpc: 1, id });
48
+ }
49
+ async sendRequest(request) {
50
+ const id = "req_" + randomUUID();
51
+ const response = new Promise((resolve, reject) => {
52
+ this.responseHandlers.set(id, { resolve, reject });
53
+ });
54
+ this.sendMessage({ ...request, nsrpc: 1, id });
55
+ return response;
56
+ }
57
+ /* Request handling */
58
+ handleRequest(request) {
59
+ switch (request.procedure) {
60
+ case "init":
61
+ return {
62
+ status: 501,
63
+ error: {
64
+ debugDescription: "Init procedure not implemented.",
65
+ userMessage: "Failed to communicate with external process. (Procedure not implemented)",
66
+ },
67
+ };
68
+ case "perform":
69
+ if ("action" in request) {
70
+ return {
71
+ status: 501,
72
+ error: {
73
+ debugDescription: "Perform procedure for (static) methods not implemented.",
74
+ userMessage: "Failed to communicate with external process. (Procedure not implemented)",
75
+ },
76
+ };
77
+ }
78
+ else {
79
+ return this.handleClosureRequest(request);
80
+ }
81
+ case "release":
82
+ return {
83
+ status: 501,
84
+ error: {
85
+ debugDescription: "Release procedure not implemented.",
86
+ userMessage: "Failed to communicate with external process. (Procedure not implemented)",
87
+ },
88
+ };
89
+ }
90
+ }
91
+ handleClosureRequest(request) {
92
+ const handler = this.closureTargets.get(request.target);
93
+ if (handler === undefined) {
94
+ return {
95
+ status: 404,
96
+ error: {
97
+ debugDescription: `Perform target '${request.target}' not found.`,
98
+ userMessage: "Failed to communicate with external process. (Target not found)",
99
+ },
100
+ };
101
+ }
102
+ try {
103
+ const rawresult = handler(request.params ?? {});
104
+ const result = rawresult === undefined ? undefined : rawresult;
105
+ return {
106
+ status: 200,
107
+ result,
108
+ };
109
+ }
110
+ catch (error) {
111
+ return {
112
+ status: 202,
113
+ // TODO: Would be good to have an error type that we can throw that fills these fields more specifically. (But for now it doesn't matter since this is just communicated back the the CLI and not to the user.)
114
+ error: {
115
+ debugDescription: `${error}`,
116
+ userMessage: "Handler failed to perform request.",
117
+ underlyingError: error,
118
+ },
119
+ };
120
+ }
121
+ }
122
+ /* Perform remote procedures */
123
+ async initialize(args) {
124
+ const target = args.target;
125
+ finalizationRegistry.register(args.lifecycle, async () => {
126
+ await this.release(target);
127
+ });
128
+ await this.sendRequest({
129
+ target: args.target,
130
+ type: args.type,
131
+ params: args.params,
132
+ procedure: "init",
133
+ });
134
+ }
135
+ async perform(body) {
136
+ return await this.sendRequest({
137
+ ...body,
138
+ procedure: "perform",
139
+ });
140
+ }
141
+ async release(target) {
142
+ await this.sendRequest({
143
+ procedure: "release",
144
+ target,
145
+ });
146
+ }
147
+ /* Register locally available targets/actions */
148
+ registerClosure(options) {
149
+ const target = `target_${options.prefix}_${randomUUID()}`;
150
+ this.closureTargets.set(target, options.handler);
151
+ finalizationRegistry.register(options.lifecycle, () => {
152
+ this.closureTargets.delete(target);
153
+ });
154
+ return target;
155
+ }
156
+ }
@@ -1,12 +1,34 @@
1
- import { IpcRecordKit } from "./IpcRecordKit.js";
2
- import { RecordingDiscovery } from "./RecordingDiscovery.js";
3
- import { RecordingSession, RecordingSchema, AbortReason } from "./RecordingSession.js";
1
+ import { RecordingSession, RecordingSchema } from "./RecordingSession.js";
2
+ interface Window {
3
+ id: number;
4
+ title?: string;
5
+ frame: Bounds;
6
+ level: number;
7
+ applicationProcessID?: number;
8
+ applicationName?: string;
9
+ }
10
+ interface Camera {
11
+ id: string;
12
+ localizedName: string;
13
+ modelID: string;
14
+ manufacturer: string;
15
+ availability: DeviceAvailability;
16
+ }
17
+ type Microphone = Camera;
18
+ type DeviceAvailability = 'available' | 'lidClosed' | 'unknownSuspended';
19
+ interface Bounds {
20
+ x: number;
21
+ y: number;
22
+ width: number;
23
+ height: number;
24
+ }
4
25
  declare class RecordKit {
5
- ipcRecordKitCli: IpcRecordKit;
6
- initialize(cliPath: string, logRpcMessages?: boolean): Promise<void>;
7
- RecordingSession(schema: RecordingSchema, onAbort: (reason: AbortReason) => void): Promise<RecordingSession>;
8
- RecordingDiscovery: typeof RecordingDiscovery;
26
+ private ipcRecordKit;
27
+ initialize(rpcBinaryPath: string, logRpcMessages?: boolean): Promise<void>;
28
+ getWindows(): Promise<Window[]>;
29
+ getCameras(): Promise<Camera[]>;
30
+ getMicrophones(): Promise<Microphone[]>;
31
+ createSession(schema: RecordingSchema): Promise<RecordingSession>;
9
32
  }
10
33
  export declare let recordkit: RecordKit;
11
34
  export {};
12
- //# sourceMappingURL=RecordKit.d.ts.map
package/dist/RecordKit.js CHANGED
@@ -1,17 +1,22 @@
1
1
  import { IpcRecordKit } from "./IpcRecordKit.js";
2
- import { RecordingDiscovery } from "./RecordingDiscovery.js";
3
2
  import { RecordingSession } from "./RecordingSession.js";
4
3
  class RecordKit {
5
- constructor() {
6
- this.ipcRecordKitCli = new IpcRecordKit();
7
- this.RecordingDiscovery = RecordingDiscovery;
4
+ ipcRecordKit = new IpcRecordKit();
5
+ async initialize(rpcBinaryPath, logRpcMessages = false) {
6
+ console.log('Initializing with path:', rpcBinaryPath);
7
+ return this.ipcRecordKit.initialize(rpcBinaryPath, logRpcMessages);
8
8
  }
9
- async initialize(cliPath, logRpcMessages = false) {
10
- console.log('Initializing with path:', cliPath);
11
- return this.ipcRecordKitCli.initialize(cliPath, logRpcMessages);
9
+ async getWindows() {
10
+ return await this.ipcRecordKit.nsrpc.perform({ type: 'RecordingSession', action: 'getWindows' });
12
11
  }
13
- async RecordingSession(schema, onAbort) {
14
- return RecordingSession.newInstance(this.ipcRecordKitCli, schema, onAbort);
12
+ async getCameras() {
13
+ return await this.ipcRecordKit.nsrpc.perform({ type: 'RecordingSession', action: 'getCameras' });
14
+ }
15
+ async getMicrophones() {
16
+ return await this.ipcRecordKit.nsrpc.perform({ type: 'RecordingSession', action: 'getMicrophones' });
17
+ }
18
+ async createSession(schema) {
19
+ return RecordingSession.newInstance(this.ipcRecordKit.nsrpc, schema);
15
20
  }
16
21
  }
17
22
  export let recordkit = new RecordKit();
@@ -1,11 +1,24 @@
1
- import { IpcRecordKit } from "./IpcRecordKit.js";
2
- export type RecordingSchema = WindowBasedCropSchema;
3
- export interface WindowBasedCropSchema {
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ /// <reference types="node" resolution-mode="require"/>
3
+ import { NSRPC } from "./NonstrictRPC.js";
4
+ import { EventEmitter } from "stream";
5
+ export interface RecordingSchema {
6
+ outputDirectory?: string;
7
+ recorders: Recorder[];
8
+ }
9
+ export type Recorder = WindowBasedCropRecorder | MovieRecorder;
10
+ export interface MovieRecorder {
11
+ type: 'movie';
12
+ filename?: string;
13
+ microphoneID: string;
14
+ cameraID: string;
15
+ }
16
+ export interface WindowBasedCropRecorder {
4
17
  type: 'windowBasedCrop';
18
+ filename?: string;
5
19
  windowID: number;
6
20
  outputDirectory?: string;
7
21
  bundleName?: string;
8
- filename?: string;
9
22
  }
10
23
  export type AbortReason = {
11
24
  reason: 'userStopped';
@@ -46,13 +59,12 @@ export interface CMTimeRange {
46
59
  start: CMTime;
47
60
  duration: CMTime;
48
61
  }
49
- export declare class RecordingSession {
50
- private readonly ipcRecordKit;
51
- private readonly instance;
52
- static newInstance(ipcRecordKit: IpcRecordKit, schema: RecordingSchema, onAbort: (reason: AbortReason) => void): Promise<RecordingSession>;
53
- constructor(ipcRecordKit: IpcRecordKit, instance: string);
62
+ export declare class RecordingSession extends EventEmitter {
63
+ private readonly rpc;
64
+ private readonly target;
65
+ static newInstance(rpc: NSRPC, schema: RecordingSchema): Promise<RecordingSession>;
66
+ constructor(rpc: NSRPC, target: string);
54
67
  prepare(): Promise<void>;
55
- record(): Promise<void>;
56
- finish(): Promise<RecordingResult>;
68
+ start(): Promise<void>;
69
+ stop(): Promise<RecordingResult>;
57
70
  }
58
- //# sourceMappingURL=RecordingSession.d.ts.map
@@ -1,28 +1,37 @@
1
1
  import { randomUUID } from "crypto";
2
- import { finalizationRegistry } from "./finalizationRegistry.js";
3
- export class RecordingSession {
4
- static async newInstance(ipcRecordKit, schema, onAbort) {
5
- let instance = 'RecordingSession_' + randomUUID();
6
- const onAbortInstance = ipcRecordKit.registerClosure('RecordingSession.onAbort', onAbort);
7
- await ipcRecordKit.sendRequest('RecordingSession.newInstance', { instance, schema, onAbortInstance });
8
- const object = new RecordingSession(ipcRecordKit, instance);
9
- finalizationRegistry.register(object, async () => {
10
- await ipcRecordKit.sendRequest('RecordingSession.releaseInstance', { instance });
11
- ipcRecordKit.unregisterMethod(onAbortInstance);
2
+ import { EventEmitter } from "stream";
3
+ export class RecordingSession extends EventEmitter {
4
+ rpc;
5
+ target;
6
+ static async newInstance(rpc, schema) {
7
+ const target = 'RecordingSession_' + randomUUID();
8
+ const object = new RecordingSession(rpc, target);
9
+ const weakRefObject = new WeakRef(object);
10
+ const onAbortInstance = rpc.registerClosure({
11
+ handler: (params) => { weakRefObject.deref()?.emit('abort', params.reason); },
12
+ prefix: 'RecordingSession.onAbort',
13
+ lifecycle: object
14
+ });
15
+ await rpc.initialize({
16
+ target,
17
+ type: 'RecordingSession',
18
+ params: { schema, onAbortInstance },
19
+ lifecycle: object
12
20
  });
13
21
  return object;
14
22
  }
15
- constructor(ipcRecordKit, instance) {
16
- this.ipcRecordKit = ipcRecordKit;
17
- this.instance = instance;
23
+ constructor(rpc, target) {
24
+ super();
25
+ this.rpc = rpc;
26
+ this.target = target;
18
27
  }
19
28
  async prepare() {
20
- return this.ipcRecordKit.sendRequest('RecordingSession.prepare', { instance: this.instance });
29
+ await this.rpc.perform({ target: this.target, action: 'prepare' });
21
30
  }
22
- async record() {
23
- return this.ipcRecordKit.sendRequest('RecordingSession.record', { instance: this.instance });
31
+ async start() {
32
+ await this.rpc.perform({ target: this.target, action: 'start' });
24
33
  }
25
- async finish() {
26
- return this.ipcRecordKit.sendRequest('RecordingSession.finish', { instance: this.instance });
34
+ async stop() {
35
+ return await this.rpc.perform({ target: this.target, action: 'stop' });
27
36
  }
28
37
  }
@@ -1,4 +1,3 @@
1
1
  type Destructor = () => void;
2
2
  export declare const finalizationRegistry: FinalizationRegistry<Destructor>;
3
3
  export {};
4
- //# sourceMappingURL=finalizationRegistry.d.ts.map
package/dist/index.cjs ADDED
@@ -0,0 +1,281 @@
1
+ 'use strict';
2
+
3
+ var node_child_process = require('node:child_process');
4
+ var readline = require('readline');
5
+ var crypto = require('crypto');
6
+ var stream = require('stream');
7
+
8
+ function _interopNamespaceDefault(e) {
9
+ var n = Object.create(null);
10
+ if (e) {
11
+ Object.keys(e).forEach(function (k) {
12
+ if (k !== 'default') {
13
+ var d = Object.getOwnPropertyDescriptor(e, k);
14
+ Object.defineProperty(n, k, d.get ? d : {
15
+ enumerable: true,
16
+ get: function () { return e[k]; }
17
+ });
18
+ }
19
+ });
20
+ }
21
+ n.default = e;
22
+ return Object.freeze(n);
23
+ }
24
+
25
+ var readline__namespace = /*#__PURE__*/_interopNamespaceDefault(readline);
26
+
27
+ const finalizationRegistry = new FinalizationRegistry(async (destructor) => { await destructor(); });
28
+
29
+ class NSRPC {
30
+ send;
31
+ responseHandlers = new Map();
32
+ closureTargets = new Map();
33
+ constructor(send) {
34
+ this.send = send;
35
+ }
36
+ receive(data) {
37
+ // TODO: For now we just assume the message is a valid NSRPC message, but we should:
38
+ // - Handle invalid JSON comming in
39
+ // - Check if the nsrpc property is set to a number in the range of 1..<2
40
+ // - Validate the message against the defined interfaces above
41
+ const message = JSON.parse(data);
42
+ if ("status" in message) {
43
+ // This is a response, dispatch it so it can be handled
44
+ const responseHandler = this.responseHandlers.get(message.id);
45
+ this.responseHandlers.delete(message.id);
46
+ if (responseHandler === undefined) {
47
+ // TODO: Got a response for a request we don't know about, log this
48
+ return;
49
+ }
50
+ if ("error" in message) {
51
+ responseHandler.reject(message.error);
52
+ }
53
+ else {
54
+ responseHandler.resolve(message.result);
55
+ }
56
+ }
57
+ else {
58
+ // This is a request
59
+ const responseBody = this.handleRequest(message);
60
+ if (responseBody !== undefined) {
61
+ this.sendResponse(message.id, responseBody);
62
+ }
63
+ }
64
+ }
65
+ /* Sending helpers */
66
+ sendMessage(message) {
67
+ this.send(JSON.stringify(message));
68
+ }
69
+ sendResponse(id, response) {
70
+ if (id === undefined) {
71
+ return;
72
+ }
73
+ this.sendMessage({ ...response, nsrpc: 1, id });
74
+ }
75
+ async sendRequest(request) {
76
+ const id = "req_" + crypto.randomUUID();
77
+ const response = new Promise((resolve, reject) => {
78
+ this.responseHandlers.set(id, { resolve, reject });
79
+ });
80
+ this.sendMessage({ ...request, nsrpc: 1, id });
81
+ return response;
82
+ }
83
+ /* Request handling */
84
+ handleRequest(request) {
85
+ switch (request.procedure) {
86
+ case "init":
87
+ return {
88
+ status: 501,
89
+ error: {
90
+ debugDescription: "Init procedure not implemented.",
91
+ userMessage: "Failed to communicate with external process. (Procedure not implemented)",
92
+ },
93
+ };
94
+ case "perform":
95
+ if ("action" in request) {
96
+ return {
97
+ status: 501,
98
+ error: {
99
+ debugDescription: "Perform procedure for (static) methods not implemented.",
100
+ userMessage: "Failed to communicate with external process. (Procedure not implemented)",
101
+ },
102
+ };
103
+ }
104
+ else {
105
+ return this.handleClosureRequest(request);
106
+ }
107
+ case "release":
108
+ return {
109
+ status: 501,
110
+ error: {
111
+ debugDescription: "Release procedure not implemented.",
112
+ userMessage: "Failed to communicate with external process. (Procedure not implemented)",
113
+ },
114
+ };
115
+ }
116
+ }
117
+ handleClosureRequest(request) {
118
+ const handler = this.closureTargets.get(request.target);
119
+ if (handler === undefined) {
120
+ return {
121
+ status: 404,
122
+ error: {
123
+ debugDescription: `Perform target '${request.target}' not found.`,
124
+ userMessage: "Failed to communicate with external process. (Target not found)",
125
+ },
126
+ };
127
+ }
128
+ try {
129
+ const rawresult = handler(request.params ?? {});
130
+ const result = rawresult === undefined ? undefined : rawresult;
131
+ return {
132
+ status: 200,
133
+ result,
134
+ };
135
+ }
136
+ catch (error) {
137
+ return {
138
+ status: 202,
139
+ // TODO: Would be good to have an error type that we can throw that fills these fields more specifically. (But for now it doesn't matter since this is just communicated back the the CLI and not to the user.)
140
+ error: {
141
+ debugDescription: `${error}`,
142
+ userMessage: "Handler failed to perform request.",
143
+ underlyingError: error,
144
+ },
145
+ };
146
+ }
147
+ }
148
+ /* Perform remote procedures */
149
+ async initialize(args) {
150
+ const target = args.target;
151
+ finalizationRegistry.register(args.lifecycle, async () => {
152
+ await this.release(target);
153
+ });
154
+ await this.sendRequest({
155
+ target: args.target,
156
+ type: args.type,
157
+ params: args.params,
158
+ procedure: "init",
159
+ });
160
+ }
161
+ async perform(body) {
162
+ return await this.sendRequest({
163
+ ...body,
164
+ procedure: "perform",
165
+ });
166
+ }
167
+ async release(target) {
168
+ await this.sendRequest({
169
+ procedure: "release",
170
+ target,
171
+ });
172
+ }
173
+ /* Register locally available targets/actions */
174
+ registerClosure(options) {
175
+ const target = `target_${options.prefix}_${crypto.randomUUID()}`;
176
+ this.closureTargets.set(target, options.handler);
177
+ finalizationRegistry.register(options.lifecycle, () => {
178
+ this.closureTargets.delete(target);
179
+ });
180
+ return target;
181
+ }
182
+ }
183
+
184
+ class IpcRecordKit {
185
+ logMessages = false;
186
+ childProcess;
187
+ nsrpc;
188
+ constructor() {
189
+ this.nsrpc = new NSRPC((message) => this.write(message));
190
+ }
191
+ async initialize(recordKitRpcPath, logMessages = false) {
192
+ if (this.childProcess !== undefined) {
193
+ throw new Error('RecordKit RPC: Already initialized.');
194
+ }
195
+ this.logMessages = logMessages;
196
+ this.childProcess = await new Promise((resolve, reject) => {
197
+ const childProcess = node_child_process.spawn(recordKitRpcPath);
198
+ childProcess.on('spawn', () => { resolve(childProcess); });
199
+ childProcess.on('error', (error) => { reject(error); });
200
+ });
201
+ const { stdout } = this.childProcess;
202
+ if (!stdout) {
203
+ throw new Error('RecordKit RPC: No stdout stream on child process.');
204
+ }
205
+ readline__namespace.createInterface({ input: stdout }).on('line', (line) => {
206
+ if (logMessages) {
207
+ console.log("< ", line.trimEnd());
208
+ }
209
+ this.nsrpc.receive(line);
210
+ });
211
+ }
212
+ write(message) {
213
+ const stdin = this.childProcess?.stdin;
214
+ if (!stdin) {
215
+ throw new Error('RecordKit RPC: Missing stdin stream.');
216
+ }
217
+ if (this.logMessages) {
218
+ console.log("> ", message);
219
+ }
220
+ stdin.write(message + "\n");
221
+ }
222
+ }
223
+
224
+ class RecordingSession extends stream.EventEmitter {
225
+ rpc;
226
+ target;
227
+ static async newInstance(rpc, schema) {
228
+ const target = 'RecordingSession_' + crypto.randomUUID();
229
+ const object = new RecordingSession(rpc, target);
230
+ const weakRefObject = new WeakRef(object);
231
+ const onAbortInstance = rpc.registerClosure({
232
+ handler: (params) => { weakRefObject.deref()?.emit('abort', params.reason); },
233
+ prefix: 'RecordingSession.onAbort',
234
+ lifecycle: object
235
+ });
236
+ await rpc.initialize({
237
+ target,
238
+ type: 'RecordingSession',
239
+ params: { schema, onAbortInstance },
240
+ lifecycle: object
241
+ });
242
+ return object;
243
+ }
244
+ constructor(rpc, target) {
245
+ super();
246
+ this.rpc = rpc;
247
+ this.target = target;
248
+ }
249
+ async prepare() {
250
+ await this.rpc.perform({ target: this.target, action: 'prepare' });
251
+ }
252
+ async start() {
253
+ await this.rpc.perform({ target: this.target, action: 'start' });
254
+ }
255
+ async stop() {
256
+ return await this.rpc.perform({ target: this.target, action: 'stop' });
257
+ }
258
+ }
259
+
260
+ class RecordKit {
261
+ ipcRecordKit = new IpcRecordKit();
262
+ async initialize(rpcBinaryPath, logRpcMessages = false) {
263
+ console.log('Initializing with path:', rpcBinaryPath);
264
+ return this.ipcRecordKit.initialize(rpcBinaryPath, logRpcMessages);
265
+ }
266
+ async getWindows() {
267
+ return await this.ipcRecordKit.nsrpc.perform({ type: 'RecordingSession', action: 'getWindows' });
268
+ }
269
+ async getCameras() {
270
+ return await this.ipcRecordKit.nsrpc.perform({ type: 'RecordingSession', action: 'getCameras' });
271
+ }
272
+ async getMicrophones() {
273
+ return await this.ipcRecordKit.nsrpc.perform({ type: 'RecordingSession', action: 'getMicrophones' });
274
+ }
275
+ async createSession(schema) {
276
+ return RecordingSession.newInstance(this.ipcRecordKit.nsrpc, schema);
277
+ }
278
+ }
279
+ let recordkit = new RecordKit();
280
+
281
+ exports.recordkit = recordkit;
package/dist/index.d.ts CHANGED
@@ -1,2 +1 @@
1
1
  export { recordkit } from './RecordKit.js';
2
- //# sourceMappingURL=index.d.ts.map
package/package.json CHANGED
@@ -1,10 +1,14 @@
1
1
  {
2
2
  "name": "@nonstrict/recordkit",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "RecordKit gives you hassle-free recording in Electron apps on macOS.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
8
+ "exports": {
9
+ "import": "./dist/index.js",
10
+ "require": "./dist/index.cjs"
11
+ },
8
12
  "files": [
9
13
  "dist"
10
14
  ],
@@ -12,9 +16,9 @@
12
16
  "node": ">=18.16"
13
17
  },
14
18
  "scripts": {
15
- "build": "tsc",
16
- "clean": "rm -rf dist",
17
- "prepublish": "npm run clean && npm run build"
19
+ "test": "jest",
20
+ "build": "rm -rf dist && tsc && rollup -c",
21
+ "prepublish": "npm run build"
18
22
  },
19
23
  "keywords": [
20
24
  "recording",
@@ -34,7 +38,11 @@
34
38
  },
35
39
  "license": "SEE LICENSE IN License.md",
36
40
  "devDependencies": {
41
+ "@types/jest": "^29.5.12",
37
42
  "@types/node": "18.19.1",
43
+ "jest": "^29.7.0",
44
+ "rollup": "^4.12.0",
45
+ "ts-jest": "^29.1.2",
38
46
  "typescript": "^5.3.3"
39
47
  },
40
48
  "volta": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"IpcRecordKit.d.ts","sourceRoot":"","sources":["../src/IpcRecordKit.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAmBtC,qBAAa,YAAa,SAAQ,YAAY;IAC1C,OAAO,CAAC,WAAW,CAAkB;IACrC,OAAO,CAAC,YAAY,CAAC,CAAe;IAEpC,OAAO,CAAC,eAAe,CAAyC;IAChE,OAAO,CAAC,aAAa,CAAiD;IAEhE,UAAU,CAAC,gBAAgB,EAAE,MAAM,EAAE,WAAW,GAAE,OAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAqEvF,OAAO,CAAC,KAAK;IAYP,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;IAQtD,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC;IAIlE,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,GAAG,GAAG,MAAM;IAMvE,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,GAAG,GAAG,IAAI;IAKpE,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;CAGzC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"RecordKit.d.ts","sourceRoot":"","sources":["../src/RecordKit.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEvF,cAAM,SAAS;IACX,eAAe,eAAqB;IAE9B,UAAU,CAAC,OAAO,EAAE,MAAM,EAAE,cAAc,GAAE,OAAe,GAAG,OAAO,CAAC,IAAI,CAAC;IAK3E,gBAAgB,CAAC,MAAM,EAAE,eAAe,EAAE,OAAO,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,IAAI;IAItF,kBAAkB,4BAAqB;CAC1C;AAED,eAAO,IAAI,SAAS,WAAkB,CAAC"}
@@ -1,19 +0,0 @@
1
- interface Window {
2
- windowID: number;
3
- title?: string;
4
- frame: Bounds;
5
- level: number;
6
- applicationProcessID?: number;
7
- applicationName?: string;
8
- }
9
- interface Bounds {
10
- x: number;
11
- y: number;
12
- width: number;
13
- height: number;
14
- }
15
- export declare class RecordingDiscovery {
16
- static getWindows(): Promise<Window[]>;
17
- }
18
- export {};
19
- //# sourceMappingURL=RecordingDiscovery.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"RecordingDiscovery.d.ts","sourceRoot":"","sources":["../src/RecordingDiscovery.ts"],"names":[],"mappings":"AAEA,UAAU,MAAM;IACZ,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,MAAM,CAAA;IACb,oBAAoB,CAAC,EAAE,MAAM,CAAA;IAC7B,eAAe,CAAC,EAAE,MAAM,CAAA;CAC3B;AAED,UAAU,MAAM;IACZ,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAClB;AAED,qBAAa,kBAAkB;WACd,UAAU,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;CAG/C"}
@@ -1,6 +0,0 @@
1
- import { recordkit } from "./RecordKit.js";
2
- export class RecordingDiscovery {
3
- static async getWindows() {
4
- return recordkit.ipcRecordKitCli.sendRequest('RecordingDiscovery.getWindows', {});
5
- }
6
- }
@@ -1 +0,0 @@
1
- {"version":3,"file":"RecordingSession.d.ts","sourceRoot":"","sources":["../src/RecordingSession.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAGjD,MAAM,MAAM,eAAe,GACvB,qBAAqB,CAAA;AAEzB,MAAM,WAAW,qBAAqB;IAClC,IAAI,EAAE,iBAAiB,CAAA;IACvB,QAAQ,EAAE,MAAM,CAAA;IAEhB,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAA;CACpB;AAED,MAAM,MAAM,WAAW,GACnB;IAAE,MAAM,EAAE,aAAa,CAAC;IAAC,MAAM,EAAE,eAAe,CAAC;CAAE,GACnD;IAAE,MAAM,EAAE,aAAa,CAAC;IAAC,MAAM,EAAE,eAAe,CAAC;IAAC,KAAK,EAAE,OAAO,CAAC;CAAE,GACnE;IAAE,MAAM,EAAE,QAAQ,CAAC;IAAC,KAAK,EAAE,OAAO,CAAC;CAAE,CAAA;AAEzC,MAAM,WAAW,eAAe;IAC5B,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,EAAE,YAAY,CAAA;CACrB;AAED,MAAM,WAAW,OAAO;IACpB,UAAU,EAAE,MAAM,CAAA;IAClB,gBAAgB,EAAE,MAAM,CAAA;IACxB,WAAW,CAAC,EAAE,MAAM,CAAA;CACvB;AAED,MAAM,WAAW,YAAY;IACzB,KAAK,EAAE;QAAE,IAAI,EAAE,OAAO,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,CAAA;IAC5D,UAAU,EAAE,WAAW,EAAE,CAAA;CAC5B;AAED,MAAM,WAAW,MAAM;IACnB,KAAK,EAAE,MAAM,CAAA;IACb,SAAS,EAAE,MAAM,CAAA;IACjB,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,MAAM,CAAA;CAClB;AAED,MAAM,WAAW,WAAW;IACxB,KAAK,EAAE,MAAM,CAAA;IACb,QAAQ,EAAE,MAAM,CAAA;CACnB;AAED,qBAAa,gBAAgB;IACzB,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAe;IAC5C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;WAErB,WAAW,CAAC,YAAY,EAAE,YAAY,EAAE,MAAM,EAAE,eAAe,EAAE,OAAO,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,IAAI,GAAG,OAAO,CAAC,gBAAgB,CAAC;gBAapI,YAAY,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM;IAKlD,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAIxB,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAIvB,MAAM,IAAI,OAAO,CAAC,eAAe,CAAC;CAG3C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"finalizationRegistry.d.ts","sourceRoot":"","sources":["../src/finalizationRegistry.ts"],"names":[],"mappings":"AAAA,KAAK,UAAU,GAAG,MAAM,IAAI,CAAA;AAC5B,eAAO,MAAM,oBAAoB,kCAAqF,CAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC"}