@tvpipe/sdk 0.0.0-stage → 0.2.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 +202 -0
- package/README.md +231 -2
- package/bin/tvpipe.js +29 -0
- package/dist/api.d.ts +189 -0
- package/dist/api.d.ts.map +1 -0
- package/dist/api.js +348 -0
- package/dist/api.js.map +1 -0
- package/dist/binary.d.ts +21 -0
- package/dist/binary.d.ts.map +1 -0
- package/dist/binary.js +73 -0
- package/dist/binary.js.map +1 -0
- package/dist/canvas.d.ts +21 -0
- package/dist/canvas.d.ts.map +1 -0
- package/dist/canvas.js +14 -0
- package/dist/canvas.js.map +1 -0
- package/dist/errors.d.ts +33 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +23 -0
- package/dist/errors.js.map +1 -0
- package/dist/events.d.ts +172 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +55 -0
- package/dist/events.js.map +1 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/process.d.ts +78 -0
- package/dist/process.d.ts.map +1 -0
- package/dist/process.js +248 -0
- package/dist/process.js.map +1 -0
- package/dist/session.d.ts +93 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +192 -0
- package/dist/session.js.map +1 -0
- package/dist/slrw.d.ts +40 -0
- package/dist/slrw.d.ts.map +1 -0
- package/dist/slrw.js +86 -0
- package/dist/slrw.js.map +1 -0
- package/dist/stream.d.ts +109 -0
- package/dist/stream.d.ts.map +1 -0
- package/dist/stream.js +230 -0
- package/dist/stream.js.map +1 -0
- package/package.json +52 -4
- package/src/api.ts +540 -0
- package/src/binary.ts +92 -0
- package/src/canvas.ts +30 -0
- package/src/errors.ts +77 -0
- package/src/events.ts +258 -0
- package/src/index.ts +50 -0
- package/src/process.ts +283 -0
- package/src/session.ts +262 -0
- package/src/slrw.ts +99 -0
- package/src/stream.ts +297 -0
package/src/errors.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Errors of the SDK. Every failure is a {@link TvpipeError} with a human
|
|
3
|
+
* message and a stable `code` to branch on.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Stable error codes. The binary's codes (docs/machine.md) plus the SDK's
|
|
8
|
+
* own; unknown failures use the binary's error kind (`io`, `auth`, …).
|
|
9
|
+
*/
|
|
10
|
+
export type TvpipeErrorCode =
|
|
11
|
+
// The binary's (docs/machine.md).
|
|
12
|
+
| "pairing-required"
|
|
13
|
+
| "no-receiver"
|
|
14
|
+
| "input-not-found"
|
|
15
|
+
| "ffmpeg-missing"
|
|
16
|
+
| "pin-missing"
|
|
17
|
+
| "bad-input"
|
|
18
|
+
| "fairplay-required"
|
|
19
|
+
| "feature-disabled"
|
|
20
|
+
// The SDK's.
|
|
21
|
+
| "binary-missing"
|
|
22
|
+
| "unsupported-platform"
|
|
23
|
+
| "protocol-mismatch"
|
|
24
|
+
| "no-receivers"
|
|
25
|
+
| "ambiguous-receiver"
|
|
26
|
+
| "pairing-failed"
|
|
27
|
+
| "aborted"
|
|
28
|
+
| "exited"
|
|
29
|
+
| "invalid-argument"
|
|
30
|
+
| "closed"
|
|
31
|
+
// The binary's error kinds, when there is no more specific code.
|
|
32
|
+
| "io"
|
|
33
|
+
| "malformed"
|
|
34
|
+
| "protocol"
|
|
35
|
+
| "crypto"
|
|
36
|
+
| "auth"
|
|
37
|
+
| "unsupported"
|
|
38
|
+
| "timeout"
|
|
39
|
+
| "not-found"
|
|
40
|
+
| "process"
|
|
41
|
+
| "usage"
|
|
42
|
+
| "unimplemented"
|
|
43
|
+
| (string & {});
|
|
44
|
+
|
|
45
|
+
export interface TvpipeErrorOptions {
|
|
46
|
+
/** The binary's error kind (`auth`, `not-found`, …), when it reported one. */
|
|
47
|
+
kind?: string;
|
|
48
|
+
/** The receiver the error is about. */
|
|
49
|
+
device?: string;
|
|
50
|
+
/** The process's exit code, when it exited. */
|
|
51
|
+
exitCode?: number | null;
|
|
52
|
+
/** The last log lines and stderr output of the process. */
|
|
53
|
+
log?: string[];
|
|
54
|
+
cause?: unknown;
|
|
55
|
+
/** Extra data, e.g. the receivers found for `ambiguous-receiver`. */
|
|
56
|
+
details?: Record<string, unknown>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export class TvpipeError extends Error {
|
|
60
|
+
override name = "TvpipeError";
|
|
61
|
+
readonly code: TvpipeErrorCode;
|
|
62
|
+
readonly kind: string | undefined;
|
|
63
|
+
readonly device: string | undefined;
|
|
64
|
+
readonly exitCode: number | null | undefined;
|
|
65
|
+
readonly log: string[];
|
|
66
|
+
readonly details: Record<string, unknown>;
|
|
67
|
+
|
|
68
|
+
constructor(code: TvpipeErrorCode, message: string, options: TvpipeErrorOptions = {}) {
|
|
69
|
+
super(message, options.cause === undefined ? undefined : { cause: options.cause });
|
|
70
|
+
this.code = code;
|
|
71
|
+
this.kind = options.kind;
|
|
72
|
+
this.device = options.device;
|
|
73
|
+
this.exitCode = options.exitCode;
|
|
74
|
+
this.log = options.log ?? [];
|
|
75
|
+
this.details = options.details ?? {};
|
|
76
|
+
}
|
|
77
|
+
}
|
package/src/events.ts
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The machine interface's events (docs/machine.md), with camelCase fields.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
export type ReceiverProtocol = "cast" | "airplay" | "browser";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* - `connected`: ready to play.
|
|
9
|
+
* - `failed`: could not resolve, connect or start, or failed mid-stream.
|
|
10
|
+
* - `lost`: the connection broke; reconnecting (`reconnect` seconds).
|
|
11
|
+
* - `reconnected`: back after `lost`.
|
|
12
|
+
* - `gave-up`: reconnecting failed.
|
|
13
|
+
* - `ended`: the receiver's user ended the session.
|
|
14
|
+
* - `stopped`: stopped by tvpipe (the session ended).
|
|
15
|
+
*/
|
|
16
|
+
export type ReceiverState =
|
|
17
|
+
| "connected"
|
|
18
|
+
| "failed"
|
|
19
|
+
| "lost"
|
|
20
|
+
| "reconnected"
|
|
21
|
+
| "gave-up"
|
|
22
|
+
| "ended"
|
|
23
|
+
| "stopped";
|
|
24
|
+
|
|
25
|
+
export interface HelloEvent {
|
|
26
|
+
type: "hello";
|
|
27
|
+
protocol: number;
|
|
28
|
+
version: string;
|
|
29
|
+
command: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface LogEvent {
|
|
33
|
+
type: "log";
|
|
34
|
+
level: "error" | "warn" | "info" | "debug" | "trace";
|
|
35
|
+
module: string;
|
|
36
|
+
message: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface ReceiverEvent {
|
|
40
|
+
type: "receiver";
|
|
41
|
+
name: string;
|
|
42
|
+
/** Known on `connected` and on `failed` while connecting. */
|
|
43
|
+
protocol?: ReceiverProtocol;
|
|
44
|
+
state: ReceiverState;
|
|
45
|
+
error?: string;
|
|
46
|
+
/** A stable code, e.g. `pairing-required`. */
|
|
47
|
+
code?: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface PlayerEvent {
|
|
51
|
+
type: "player";
|
|
52
|
+
name: string;
|
|
53
|
+
/** The page of a `browser` receiver: open it in a browser to watch. */
|
|
54
|
+
url: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface ViewerEvent {
|
|
58
|
+
type: "viewer";
|
|
59
|
+
name: string;
|
|
60
|
+
tab: number;
|
|
61
|
+
state: "connected" | "disconnected";
|
|
62
|
+
/** It came over the public link. */
|
|
63
|
+
public?: boolean;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface SharePageEvent {
|
|
67
|
+
type: "share-page";
|
|
68
|
+
url: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** `tunnel` (or `player.tunnel`): the public link works. */
|
|
72
|
+
export interface TunnelEvent {
|
|
73
|
+
type: "tunnel";
|
|
74
|
+
page: "player" | "share";
|
|
75
|
+
/** The player's name (`page: "player"`). */
|
|
76
|
+
name?: string;
|
|
77
|
+
provider: TunnelProvider;
|
|
78
|
+
/** The link, with its token. */
|
|
79
|
+
url: string;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Who carries a public link: Cloudflare (the default) or OpenTunnel. */
|
|
83
|
+
export type TunnelProvider = "cloudflare" | "opentunnel";
|
|
84
|
+
|
|
85
|
+
export interface ConnectedEvent {
|
|
86
|
+
type: "connected";
|
|
87
|
+
receivers: string[];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface StartedEvent {
|
|
91
|
+
type: "started";
|
|
92
|
+
route: "passthrough" | "ffmpeg" | "builtin" | "encoded" | "browser";
|
|
93
|
+
video: { codec: string; width: number; height: number; fps: number };
|
|
94
|
+
audio: { codec: string; sampleRate: number; channels: number }[];
|
|
95
|
+
latencyMs: number;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export interface KeyframeEvent {
|
|
99
|
+
type: "keyframe";
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface ReceiverStats {
|
|
103
|
+
name: string;
|
|
104
|
+
pushed: number;
|
|
105
|
+
dropped: number;
|
|
106
|
+
droppedFull: number;
|
|
107
|
+
droppedWaiting: number;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface StatsEvent {
|
|
111
|
+
type: "stats";
|
|
112
|
+
elapsedMs: number;
|
|
113
|
+
videoFrames: number;
|
|
114
|
+
audioFrames: number;
|
|
115
|
+
receivers: ReceiverStats[];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export interface PinRequiredEvent {
|
|
119
|
+
type: "pin-required";
|
|
120
|
+
name: string;
|
|
121
|
+
address: string;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export interface PairedEvent {
|
|
125
|
+
type: "paired";
|
|
126
|
+
name: string;
|
|
127
|
+
model?: string;
|
|
128
|
+
/** The credentials file (the CLI's always has one). */
|
|
129
|
+
file?: string;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export interface UnpairedEvent {
|
|
133
|
+
type: "unpaired";
|
|
134
|
+
name: string;
|
|
135
|
+
id: string;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export interface DevicesEvent {
|
|
139
|
+
type: "devices";
|
|
140
|
+
devices: RawDevice[];
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export interface ReceiverEnd extends ReceiverStats {
|
|
144
|
+
end: "stopped" | "ended" | "failed";
|
|
145
|
+
error?: string;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export interface EndEvent {
|
|
149
|
+
type: "end";
|
|
150
|
+
reason: "eof" | "stopped" | "receivers-gone" | "error" | "done";
|
|
151
|
+
receivers?: ReceiverEnd[];
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export interface ErrorEvent {
|
|
155
|
+
type: "error";
|
|
156
|
+
kind: string;
|
|
157
|
+
code?: string;
|
|
158
|
+
message: string;
|
|
159
|
+
device?: string;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** `share` or `screen`: the browser started sharing. */
|
|
163
|
+
export interface CaptureEvent {
|
|
164
|
+
type: "capture";
|
|
165
|
+
/** `monitor`, `window` or `browser`, if the browser says. */
|
|
166
|
+
surface?: string;
|
|
167
|
+
/** A screen or window title, if the browser says. */
|
|
168
|
+
label?: string;
|
|
169
|
+
width: number;
|
|
170
|
+
height: number;
|
|
171
|
+
/** Whether the capture has sound. */
|
|
172
|
+
audio: boolean;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** A device as `discover` reports it (camelCased). */
|
|
176
|
+
export interface RawDevice {
|
|
177
|
+
name: string;
|
|
178
|
+
addresses: string[];
|
|
179
|
+
model?: string;
|
|
180
|
+
airplay?: Record<string, unknown>;
|
|
181
|
+
raop?: Record<string, unknown>;
|
|
182
|
+
cast?: Record<string, unknown>;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export type TvpipeEvent =
|
|
186
|
+
| HelloEvent
|
|
187
|
+
| LogEvent
|
|
188
|
+
| ReceiverEvent
|
|
189
|
+
| PlayerEvent
|
|
190
|
+
| ViewerEvent
|
|
191
|
+
| SharePageEvent
|
|
192
|
+
| TunnelEvent
|
|
193
|
+
| CaptureEvent
|
|
194
|
+
| ConnectedEvent
|
|
195
|
+
| StartedEvent
|
|
196
|
+
| KeyframeEvent
|
|
197
|
+
| StatsEvent
|
|
198
|
+
| PinRequiredEvent
|
|
199
|
+
| PairedEvent
|
|
200
|
+
| UnpairedEvent
|
|
201
|
+
| DevicesEvent
|
|
202
|
+
| EndEvent
|
|
203
|
+
| ErrorEvent;
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Every event `type`, as a value (the golden vectors in
|
|
207
|
+
* crates/tvpipe/tests/vectors/machine/ are checked against it).
|
|
208
|
+
*/
|
|
209
|
+
export const EVENT_TYPES = [
|
|
210
|
+
"hello",
|
|
211
|
+
"log",
|
|
212
|
+
"receiver",
|
|
213
|
+
"player",
|
|
214
|
+
"viewer",
|
|
215
|
+
"share-page",
|
|
216
|
+
"tunnel",
|
|
217
|
+
"capture",
|
|
218
|
+
"connected",
|
|
219
|
+
"started",
|
|
220
|
+
"keyframe",
|
|
221
|
+
"stats",
|
|
222
|
+
"pin-required",
|
|
223
|
+
"paired",
|
|
224
|
+
"unpaired",
|
|
225
|
+
"devices",
|
|
226
|
+
"end",
|
|
227
|
+
"error",
|
|
228
|
+
] as const;
|
|
229
|
+
|
|
230
|
+
// EVENT_TYPES and the TvpipeEvent union name the same types (a compile error
|
|
231
|
+
// otherwise).
|
|
232
|
+
type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
|
|
233
|
+
const sameTypes: Same<(typeof EVENT_TYPES)[number], TvpipeEvent["type"]> = true;
|
|
234
|
+
void sameTypes;
|
|
235
|
+
|
|
236
|
+
/** snake_case keys to camelCase, recursively. */
|
|
237
|
+
export function camelize(value: unknown): unknown {
|
|
238
|
+
if (Array.isArray(value)) return value.map(camelize);
|
|
239
|
+
if (value !== null && typeof value === "object") {
|
|
240
|
+
const out: Record<string, unknown> = {};
|
|
241
|
+
for (const [k, v] of Object.entries(value)) {
|
|
242
|
+
out[k.replace(/_([a-z0-9])/g, (_, c: string) => c.toUpperCase())] = camelize(v);
|
|
243
|
+
}
|
|
244
|
+
return out;
|
|
245
|
+
}
|
|
246
|
+
return value;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Parses one stdout line; `undefined` for anything that is not an event. */
|
|
250
|
+
export function parseEvent(line: string): TvpipeEvent | undefined {
|
|
251
|
+
if (!line.startsWith("{")) return undefined;
|
|
252
|
+
try {
|
|
253
|
+
const v = camelize(JSON.parse(line)) as { type?: unknown };
|
|
254
|
+
return typeof v.type === "string" ? (v as TvpipeEvent) : undefined;
|
|
255
|
+
} catch {
|
|
256
|
+
return undefined;
|
|
257
|
+
}
|
|
258
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tvpipe for Node: stream video and audio to AirPlay and Google Cast
|
|
3
|
+
* receivers and browser tabs. See README.md.
|
|
4
|
+
*
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export {
|
|
9
|
+
discover,
|
|
10
|
+
pair,
|
|
11
|
+
unpair,
|
|
12
|
+
play,
|
|
13
|
+
testPattern,
|
|
14
|
+
preview,
|
|
15
|
+
share,
|
|
16
|
+
stream,
|
|
17
|
+
version,
|
|
18
|
+
type Device,
|
|
19
|
+
type DiscoverOptions,
|
|
20
|
+
type PairOptions,
|
|
21
|
+
type PairResult,
|
|
22
|
+
type PinCallback,
|
|
23
|
+
type PinRequest,
|
|
24
|
+
type Target,
|
|
25
|
+
type PlayerOptions,
|
|
26
|
+
type CommonOptions,
|
|
27
|
+
type PlayOptions,
|
|
28
|
+
type ShareOptions,
|
|
29
|
+
type StreamOptions,
|
|
30
|
+
type Encoder,
|
|
31
|
+
type Input,
|
|
32
|
+
} from "./api.ts";
|
|
33
|
+
export { resolveBinary, platformPackage, PLATFORMS, BINARY_ENV, type Platform, type BinaryOptions } from "./binary.ts";
|
|
34
|
+
export type { CanvasLike, Context2DLike, ImageDataLike } from "./canvas.ts";
|
|
35
|
+
export { TvpipeError, type TvpipeErrorCode, type TvpipeErrorOptions } from "./errors.ts";
|
|
36
|
+
export type * from "./events.ts";
|
|
37
|
+
export { PROTOCOL, type ProcessOptions } from "./process.ts";
|
|
38
|
+
export { Session, type EndInfo, type ReceiverInfo, type SessionEvents, type SessionOptions, type StartedInfo } from "./session.ts";
|
|
39
|
+
export {
|
|
40
|
+
StreamSession,
|
|
41
|
+
type AudioSpec,
|
|
42
|
+
type EncodedVideoChunkLike,
|
|
43
|
+
type EncodedVideoChunkMetadataLike,
|
|
44
|
+
type EncodedVideoSpec,
|
|
45
|
+
type PixelFormat,
|
|
46
|
+
type Pts,
|
|
47
|
+
type RawVideoSpec,
|
|
48
|
+
type StreamSessionOptions,
|
|
49
|
+
type VideoSpec,
|
|
50
|
+
} from "./stream.ts";
|
package/src/process.ts
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One tvpipe process speaking the machine interface: spawn, events from
|
|
3
|
+
* stdout, records to stdin, and a stop that escalates.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
7
|
+
import { EventEmitter } from "node:events";
|
|
8
|
+
import { createInterface } from "node:readline";
|
|
9
|
+
|
|
10
|
+
import { resolveBinary } from "./binary.ts";
|
|
11
|
+
import { TvpipeError } from "./errors.ts";
|
|
12
|
+
import { parseEvent, type ErrorEvent, type HelloEvent, type LogEvent, type TvpipeEvent } from "./events.ts";
|
|
13
|
+
import * as slrw from "./slrw.ts";
|
|
14
|
+
|
|
15
|
+
/** The machine-interface version this SDK speaks. */
|
|
16
|
+
export const PROTOCOL = 1;
|
|
17
|
+
|
|
18
|
+
/** How many log lines a process keeps for error messages. */
|
|
19
|
+
const LOG_TAIL = 50;
|
|
20
|
+
|
|
21
|
+
export interface ProcessOptions {
|
|
22
|
+
/** Path of the tvpipe binary (default: `$TVPIPE_BINARY`, then the platform package). */
|
|
23
|
+
binary?: string | undefined;
|
|
24
|
+
/**
|
|
25
|
+
* Where tvpipe keeps AirPlay pairings and the player page's token
|
|
26
|
+
* (`TVPIPE_CONFIG_DIR`; default: the CLI's config directory, so the CLI
|
|
27
|
+
* and the SDK share pairings).
|
|
28
|
+
*/
|
|
29
|
+
configDir?: string | undefined;
|
|
30
|
+
/** Extra environment variables for the process. */
|
|
31
|
+
env?: Record<string, string | undefined> | undefined;
|
|
32
|
+
/** Debug logs (`-v`); `"trace"` for protocol traces (`--debug`). */
|
|
33
|
+
verbose?: boolean | "trace" | undefined;
|
|
34
|
+
/**
|
|
35
|
+
* Mirror tvpipe's log to stderr (`true`, or the lowest level: `"info"`
|
|
36
|
+
* by default with `true`), or hand each line to a function. Logs are
|
|
37
|
+
* also `log` events either way.
|
|
38
|
+
*/
|
|
39
|
+
logs?: boolean | LogEvent["level"] | ((event: LogEvent) => void) | undefined;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface Exit {
|
|
43
|
+
code: number | null;
|
|
44
|
+
signal: NodeJS.Signals | null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const LEVELS = ["error", "warn", "info", "debug", "trace"] as const;
|
|
48
|
+
|
|
49
|
+
function logPrinter(logs: ProcessOptions["logs"]): ((e: LogEvent) => void) | undefined {
|
|
50
|
+
if (typeof logs === "function") return logs;
|
|
51
|
+
if (!logs) return undefined;
|
|
52
|
+
const max = LEVELS.indexOf(logs === true ? "info" : logs);
|
|
53
|
+
return (e) => {
|
|
54
|
+
if (LEVELS.indexOf(e.level) <= max) {
|
|
55
|
+
process.stderr.write(`tvpipe ${e.level.toUpperCase().padEnd(5)} ${e.module}: ${e.message}\n`);
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* A running tvpipe. Emits `event` (every {@link TvpipeEvent}) and `exit`.
|
|
62
|
+
*/
|
|
63
|
+
export class TvpipeProcess extends EventEmitter<{ event: [TvpipeEvent]; exit: [Exit] }> {
|
|
64
|
+
readonly child: ChildProcess;
|
|
65
|
+
readonly exited: Promise<Exit>;
|
|
66
|
+
hello: HelloEvent | undefined;
|
|
67
|
+
/** The last error event, if the command failed. */
|
|
68
|
+
failure: ErrorEvent | undefined;
|
|
69
|
+
/** Whether an `end` event arrived. */
|
|
70
|
+
ended = false;
|
|
71
|
+
#log: string[] = [];
|
|
72
|
+
#stderr: string[] = [];
|
|
73
|
+
#exit: Exit | undefined;
|
|
74
|
+
#spawnError: Error | undefined;
|
|
75
|
+
#inputOpen = true;
|
|
76
|
+
|
|
77
|
+
constructor(args: string[], options: ProcessOptions = {}) {
|
|
78
|
+
super();
|
|
79
|
+
const binary = resolveBinary(options);
|
|
80
|
+
const flags = ["--machine"];
|
|
81
|
+
if (options.verbose === "trace") flags.push("--debug");
|
|
82
|
+
else if (options.verbose) flags.push("-v");
|
|
83
|
+
const env: Record<string, string | undefined> = { ...process.env, ...options.env };
|
|
84
|
+
if (options.configDir) env["TVPIPE_CONFIG_DIR"] = options.configDir;
|
|
85
|
+
this.child = spawn(binary, [...flags, ...args], {
|
|
86
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
87
|
+
windowsHide: true,
|
|
88
|
+
env,
|
|
89
|
+
});
|
|
90
|
+
const printer = logPrinter(options.logs);
|
|
91
|
+
this.exited = new Promise((resolve) => {
|
|
92
|
+
this.child.once("error", (err) => {
|
|
93
|
+
this.#spawnError = err;
|
|
94
|
+
// `close` does not follow a failed spawn.
|
|
95
|
+
if (this.child.pid === undefined) {
|
|
96
|
+
this.#exit = { code: null, signal: null };
|
|
97
|
+
this.emit("exit", this.#exit);
|
|
98
|
+
resolve(this.#exit);
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
// `close`: the process exited and its stdio is drained, so every
|
|
102
|
+
// event was read.
|
|
103
|
+
this.child.once("close", (code, signal) => {
|
|
104
|
+
this.#exit = { code, signal };
|
|
105
|
+
this.emit("exit", this.#exit);
|
|
106
|
+
resolve(this.#exit);
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
// A closed pipe (tvpipe exited) is reported through `exit`.
|
|
110
|
+
this.child.stdin?.on("error", () => {
|
|
111
|
+
this.#inputOpen = false;
|
|
112
|
+
});
|
|
113
|
+
this.child.stdin?.write(slrw.MAGIC);
|
|
114
|
+
const lines = createInterface({ input: this.child.stdout!, crlfDelay: Infinity });
|
|
115
|
+
lines.on("line", (line) => {
|
|
116
|
+
const ev = parseEvent(line);
|
|
117
|
+
if (!ev) {
|
|
118
|
+
this.#remember(line);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
switch (ev.type) {
|
|
122
|
+
case "hello":
|
|
123
|
+
this.hello = ev;
|
|
124
|
+
if (ev.protocol !== PROTOCOL) {
|
|
125
|
+
this.failure = {
|
|
126
|
+
type: "error",
|
|
127
|
+
kind: "usage",
|
|
128
|
+
code: "protocol-mismatch",
|
|
129
|
+
message:
|
|
130
|
+
`tvpipe ${ev.version} speaks machine protocol ${ev.protocol}, this SDK ${PROTOCOL}; ` +
|
|
131
|
+
`install matching versions of @tvpipe/sdk and its binary`,
|
|
132
|
+
};
|
|
133
|
+
this.kill();
|
|
134
|
+
}
|
|
135
|
+
break;
|
|
136
|
+
case "log":
|
|
137
|
+
this.#remember(`${ev.level}: ${ev.message}`);
|
|
138
|
+
printer?.(ev);
|
|
139
|
+
break;
|
|
140
|
+
case "error":
|
|
141
|
+
this.failure ??= ev;
|
|
142
|
+
break;
|
|
143
|
+
case "end":
|
|
144
|
+
this.ended = true;
|
|
145
|
+
break;
|
|
146
|
+
}
|
|
147
|
+
this.emit("event", ev);
|
|
148
|
+
});
|
|
149
|
+
const stderr = createInterface({ input: this.child.stderr!, crlfDelay: Infinity });
|
|
150
|
+
stderr.on("line", (line) => {
|
|
151
|
+
if (line.trim()) {
|
|
152
|
+
this.#remember(line);
|
|
153
|
+
this.#stderr.push(line);
|
|
154
|
+
}
|
|
155
|
+
printer?.({ type: "log", level: "error", module: "stderr", message: line });
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
#remember(line: string): void {
|
|
160
|
+
this.#log.push(line);
|
|
161
|
+
if (this.#log.length > LOG_TAIL) this.#log.shift();
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** The last log lines and stderr output. */
|
|
165
|
+
get log(): string[] {
|
|
166
|
+
return [...this.#log];
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
get exit(): Exit | undefined {
|
|
170
|
+
return this.#exit;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
get running(): boolean {
|
|
174
|
+
return this.#exit === undefined;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
get pid(): number | undefined {
|
|
178
|
+
return this.child.pid;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Whether stdin still takes records. */
|
|
182
|
+
get inputOpen(): boolean {
|
|
183
|
+
return this.#inputOpen && this.running && !!this.child.stdin?.writable;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Bytes written to stdin that the pipe did not take yet. */
|
|
187
|
+
get queuedBytes(): number {
|
|
188
|
+
return this.child.stdin?.writableLength ?? 0;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Writes to stdin; `false` when the pipe is backed up (or closed). */
|
|
192
|
+
write(data: Uint8Array): boolean {
|
|
193
|
+
if (!this.inputOpen) return false;
|
|
194
|
+
return this.child.stdin!.write(data);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Sends a command record (`stop`, `pin`). */
|
|
198
|
+
command(cmd: Record<string, unknown>): boolean {
|
|
199
|
+
return this.write(slrw.command(cmd));
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Closes stdin: the end of an SLRW stream, else a stop request. */
|
|
203
|
+
endInput(): void {
|
|
204
|
+
if (this.#inputOpen) {
|
|
205
|
+
this.#inputOpen = false;
|
|
206
|
+
this.child.stdin?.end();
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Resolves once stdin took everything written. */
|
|
211
|
+
drain(): Promise<void> {
|
|
212
|
+
const stdin = this.child.stdin;
|
|
213
|
+
if (!stdin || !this.inputOpen || stdin.writableLength === 0) return Promise.resolve();
|
|
214
|
+
return new Promise((resolve) => {
|
|
215
|
+
const done = () => {
|
|
216
|
+
stdin.off("drain", done);
|
|
217
|
+
this.off("exit", done);
|
|
218
|
+
resolve();
|
|
219
|
+
};
|
|
220
|
+
stdin.on("drain", done);
|
|
221
|
+
this.once("exit", done);
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
kill(signal: NodeJS.Signals = "SIGKILL"): void {
|
|
226
|
+
if (this.running) this.child.kill(signal);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Stops: the `stop` command, stdin closed; after `timeoutMs` SIGTERM
|
|
231
|
+
* (tvpipe still tears down; on Windows this terminates at once), after
|
|
232
|
+
* 2 s more SIGKILL.
|
|
233
|
+
*/
|
|
234
|
+
async stop(timeoutMs = 5000, graceful: "stop" | "end" = "stop"): Promise<Exit> {
|
|
235
|
+
if (!this.running) return this.exited;
|
|
236
|
+
if (graceful === "stop") this.command({ type: "stop" });
|
|
237
|
+
else this.write(slrw.record(slrw.Kind.end, 0, new Uint8Array(0)));
|
|
238
|
+
this.endInput();
|
|
239
|
+
const timer = (ms: number) =>
|
|
240
|
+
new Promise<"timeout">((resolve) => setTimeout(resolve, ms, "timeout").unref());
|
|
241
|
+
if ((await Promise.race([this.exited, timer(timeoutMs)])) !== "timeout") return this.exited;
|
|
242
|
+
this.kill(process.platform === "win32" ? "SIGKILL" : "SIGTERM");
|
|
243
|
+
if ((await Promise.race([this.exited, timer(2000)])) !== "timeout") return this.exited;
|
|
244
|
+
this.kill("SIGKILL");
|
|
245
|
+
return this.exited;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** The error for a process that failed (or exited without saying why). */
|
|
249
|
+
error(fallback = "tvpipe exited unexpectedly"): TvpipeError {
|
|
250
|
+
const exitCode = this.#exit?.code;
|
|
251
|
+
if (this.#spawnError) {
|
|
252
|
+
return new TvpipeError("binary-missing", `cannot run tvpipe: ${this.#spawnError.message}`, {
|
|
253
|
+
cause: this.#spawnError,
|
|
254
|
+
log: this.log,
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
const f = this.failure;
|
|
258
|
+
if (f) {
|
|
259
|
+
return new TvpipeError(f.code ?? f.kind, f.message, {
|
|
260
|
+
kind: f.kind,
|
|
261
|
+
device: f.device,
|
|
262
|
+
exitCode,
|
|
263
|
+
log: this.log,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
// The argument parser's errors: `error: ...` on stderr, status 2.
|
|
267
|
+
const parseError = this.#stderr.find((l) => l.startsWith("error:"));
|
|
268
|
+
if (exitCode === 2 && parseError) {
|
|
269
|
+
return new TvpipeError("usage", `tvpipe rejected the arguments: ${parseError.slice(6).trim()}`, {
|
|
270
|
+
kind: "usage",
|
|
271
|
+
exitCode,
|
|
272
|
+
log: this.log,
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
const detail = this.#log.filter((l) => !l.startsWith("info:") && !l.startsWith("debug:"));
|
|
276
|
+
const last = detail.at(-1);
|
|
277
|
+
const how = this.#exit?.signal ? `signal ${this.#exit.signal}` : `exit code ${exitCode}`;
|
|
278
|
+
return new TvpipeError("exited", `${fallback} (${how})${last ? `: ${last}` : ""}`, {
|
|
279
|
+
exitCode,
|
|
280
|
+
log: this.log,
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
}
|