tywrap 0.1.1 → 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.
Files changed (63) hide show
  1. package/README.md +32 -5
  2. package/dist/cli.js +70 -3
  3. package/dist/cli.js.map +1 -1
  4. package/dist/config/index.d.ts.map +1 -1
  5. package/dist/config/index.js +47 -11
  6. package/dist/config/index.js.map +1 -1
  7. package/dist/core/generator.d.ts.map +1 -1
  8. package/dist/core/generator.js +6 -2
  9. package/dist/core/generator.js.map +1 -1
  10. package/dist/core/mapper.d.ts.map +1 -1
  11. package/dist/core/mapper.js +16 -4
  12. package/dist/core/mapper.js.map +1 -1
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +2 -2
  16. package/dist/index.js.map +1 -1
  17. package/dist/runtime/bridge-core.d.ts +64 -0
  18. package/dist/runtime/bridge-core.d.ts.map +1 -0
  19. package/dist/runtime/bridge-core.js +344 -0
  20. package/dist/runtime/bridge-core.js.map +1 -0
  21. package/dist/runtime/node.d.ts +161 -15
  22. package/dist/runtime/node.d.ts.map +1 -1
  23. package/dist/runtime/node.js +542 -218
  24. package/dist/runtime/node.js.map +1 -1
  25. package/dist/runtime/optimized-node.d.ts +19 -128
  26. package/dist/runtime/optimized-node.d.ts.map +1 -1
  27. package/dist/runtime/optimized-node.js +19 -627
  28. package/dist/runtime/optimized-node.js.map +1 -1
  29. package/dist/runtime/timed-out-request-tracker.d.ts +20 -0
  30. package/dist/runtime/timed-out-request-tracker.d.ts.map +1 -0
  31. package/dist/runtime/timed-out-request-tracker.js +48 -0
  32. package/dist/runtime/timed-out-request-tracker.js.map +1 -0
  33. package/dist/types/index.d.ts +3 -0
  34. package/dist/types/index.d.ts.map +1 -1
  35. package/dist/tywrap.d.ts +17 -4
  36. package/dist/tywrap.d.ts.map +1 -1
  37. package/dist/tywrap.js +68 -35
  38. package/dist/tywrap.js.map +1 -1
  39. package/dist/utils/codec.d.ts +22 -0
  40. package/dist/utils/codec.d.ts.map +1 -1
  41. package/dist/utils/codec.js +245 -55
  42. package/dist/utils/codec.js.map +1 -1
  43. package/dist/utils/logger.d.ts.map +1 -1
  44. package/dist/utils/logger.js +1 -0
  45. package/dist/utils/logger.js.map +1 -1
  46. package/dist/utils/python.d.ts.map +1 -1
  47. package/dist/utils/python.js.map +1 -1
  48. package/package.json +11 -2
  49. package/runtime/python_bridge.py +450 -69
  50. package/src/cli.ts +75 -3
  51. package/src/config/index.ts +58 -15
  52. package/src/core/generator.ts +6 -2
  53. package/src/core/mapper.ts +16 -4
  54. package/src/index.ts +2 -1
  55. package/src/runtime/bridge-core.ts +454 -0
  56. package/src/runtime/node.ts +725 -253
  57. package/src/runtime/optimized-node.ts +19 -844
  58. package/src/runtime/timed-out-request-tracker.ts +58 -0
  59. package/src/types/index.ts +3 -0
  60. package/src/tywrap.ts +91 -36
  61. package/src/utils/codec.ts +299 -82
  62. package/src/utils/logger.ts +1 -0
  63. package/src/utils/python.ts +0 -1
@@ -0,0 +1,454 @@
1
+ import type { BridgeInfo } from '../types/index.js';
2
+
3
+ import { BridgeExecutionError, BridgeProtocolError, BridgeTimeoutError } from './errors.js';
4
+ import { TYWRAP_PROTOCOL, TYWRAP_PROTOCOL_VERSION } from './protocol.js';
5
+ import { TimedOutRequestTracker } from './timed-out-request-tracker.js';
6
+
7
+ export type RpcMethod = 'call' | 'instantiate' | 'call_method' | 'dispose_instance' | 'meta';
8
+
9
+ export interface RpcRequest {
10
+ id: number;
11
+ protocol: string;
12
+ method: RpcMethod;
13
+ params: unknown;
14
+ }
15
+
16
+ export interface RpcResponse<T = unknown> {
17
+ id: number;
18
+ protocol: string;
19
+ result?: T;
20
+ error?: { type: string; message: string; traceback?: string };
21
+ }
22
+
23
+ export interface BridgeCoreTransport {
24
+ write: (data: string) => void;
25
+ }
26
+
27
+ export interface BridgeCoreOptions {
28
+ timeoutMs: number;
29
+ maxLineLength?: number;
30
+ maxStderrBytes?: number;
31
+ protocol?: string;
32
+ protocolVersion?: number;
33
+ decodeValue?: (value: unknown) => Promise<unknown>;
34
+ onFatalError?: (error: BridgeProtocolError) => void;
35
+ onTimeout?: (error: BridgeTimeoutError) => void;
36
+ }
37
+
38
+ interface PendingRequest {
39
+ resolve: (value: unknown) => void;
40
+ reject: (error: unknown) => void;
41
+ timer?: NodeJS.Timeout;
42
+ }
43
+
44
+ // Why: keep stdout lines bounded to prevent unbounded memory growth on malformed output.
45
+ const DEFAULT_MAX_LINE_LENGTH = 1024 * 1024; // 1MB
46
+ // Why: keep stderr snapshots small but useful for diagnostics on timeouts/exits.
47
+ const DEFAULT_MAX_STDERR_BYTES = 8 * 1024; // 8KB
48
+
49
+ const defaultDecodeValue = async (value: unknown): Promise<unknown> => value;
50
+ const noop = (): void => {};
51
+ const ANSI_ESCAPE_RE = new RegExp('\\u001b\\[[0-9;]*[A-Za-z]', 'g');
52
+ const CONTROL_CHARS_RE = new RegExp(
53
+ '[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F\\u0080-\\u009F]',
54
+ 'g'
55
+ );
56
+ const sanitizeStderr = (value: string): string =>
57
+ value.replace(ANSI_ESCAPE_RE, '').replace(CONTROL_CHARS_RE, '');
58
+
59
+ export class BridgeCore {
60
+ private readonly transport: BridgeCoreTransport;
61
+ private readonly options: Required<BridgeCoreOptions>;
62
+ private readonly timedOutRequests: TimedOutRequestTracker;
63
+ private readonly pending = new Map<number, PendingRequest>();
64
+ private nextId = 1;
65
+ private stdoutBuffer = '';
66
+ private stderrBuffer = '';
67
+ private protocolError = false;
68
+
69
+ constructor(transport: BridgeCoreTransport, options: BridgeCoreOptions) {
70
+ this.transport = transport;
71
+ this.options = {
72
+ timeoutMs: options.timeoutMs,
73
+ maxLineLength: options.maxLineLength ?? DEFAULT_MAX_LINE_LENGTH,
74
+ maxStderrBytes: options.maxStderrBytes ?? DEFAULT_MAX_STDERR_BYTES,
75
+ protocol: options.protocol ?? TYWRAP_PROTOCOL,
76
+ protocolVersion: options.protocolVersion ?? TYWRAP_PROTOCOL_VERSION,
77
+ decodeValue: options.decodeValue ?? defaultDecodeValue,
78
+ onFatalError: options.onFatalError ?? noop,
79
+ onTimeout: options.onTimeout ?? noop,
80
+ };
81
+ this.timedOutRequests = new TimedOutRequestTracker({
82
+ ttlMs: Math.max(1000, this.options.timeoutMs * 2),
83
+ });
84
+ }
85
+
86
+ getStderrTail(): string {
87
+ return this.stderrBuffer.trim();
88
+ }
89
+
90
+ getPendingCount(): number {
91
+ return this.pending.size;
92
+ }
93
+
94
+ clear(): void {
95
+ for (const [, pending] of this.pending) {
96
+ if (pending.timer) {
97
+ clearTimeout(pending.timer);
98
+ }
99
+ }
100
+ this.pending.clear();
101
+ this.timedOutRequests.clear();
102
+ this.stdoutBuffer = '';
103
+ this.stderrBuffer = '';
104
+ this.protocolError = false;
105
+ }
106
+
107
+ async send<T>(payload: Omit<RpcRequest, 'id' | 'protocol'>): Promise<T> {
108
+ const id = this.nextId++;
109
+ const message: RpcRequest = { ...payload, id, protocol: this.options.protocol } as RpcRequest;
110
+ let text: string;
111
+ try {
112
+ text = JSON.stringify(message);
113
+ } catch (err) {
114
+ throw new BridgeProtocolError(
115
+ `Failed to serialize request: ${err instanceof Error ? err.message : String(err)}`
116
+ );
117
+ }
118
+
119
+ let timer: NodeJS.Timeout | undefined;
120
+ const promise = new Promise<T>((resolve, reject) => {
121
+ timer = setTimeout(() => {
122
+ this.pending.delete(id);
123
+ this.timedOutRequests.mark(id);
124
+ const stderrTail = this.getStderrTail();
125
+ const msg = stderrTail
126
+ ? `Python call timed out. Recent stderr from Python:\n${stderrTail}`
127
+ : 'Python call timed out';
128
+ const timeoutError = new BridgeTimeoutError(msg);
129
+ reject(timeoutError);
130
+ this.options.onTimeout(timeoutError);
131
+ }, this.options.timeoutMs);
132
+
133
+ const resolveWrapped = (value: unknown): void => {
134
+ resolve(value as T);
135
+ };
136
+ this.pending.set(id, { resolve: resolveWrapped, reject, timer });
137
+ });
138
+
139
+ try {
140
+ this.transport.write(`${text}\n`);
141
+ } catch (err) {
142
+ const failure = new BridgeProtocolError(
143
+ `IPC failure: ${err instanceof Error ? err.message : String(err)}`
144
+ );
145
+ this.failRequest(id, failure);
146
+ this.handleFatalError(failure);
147
+ }
148
+
149
+ return promise;
150
+ }
151
+
152
+ handleStdoutData(chunk: Buffer | string): void {
153
+ this.stdoutBuffer += chunk.toString();
154
+
155
+ if (
156
+ this.stdoutBuffer.length > this.options.maxLineLength &&
157
+ !this.stdoutBuffer.includes('\n')
158
+ ) {
159
+ const snippet = this.stdoutBuffer.slice(0, this.options.maxLineLength);
160
+ this.stdoutBuffer = '';
161
+ this.handleProtocolError(
162
+ `Response line exceeded ${this.options.maxLineLength} bytes`,
163
+ snippet
164
+ );
165
+ return;
166
+ }
167
+
168
+ let idx: number;
169
+ while ((idx = this.stdoutBuffer.indexOf('\n')) !== -1) {
170
+ const line = this.stdoutBuffer.slice(0, idx);
171
+ this.stdoutBuffer = this.stdoutBuffer.slice(idx + 1);
172
+
173
+ if (!line.trim()) {
174
+ continue;
175
+ }
176
+
177
+ if (line.length > this.options.maxLineLength) {
178
+ const snippet = line.slice(0, this.options.maxLineLength);
179
+ this.handleProtocolError(
180
+ `Response line exceeded ${this.options.maxLineLength} bytes`,
181
+ snippet
182
+ );
183
+ return;
184
+ }
185
+
186
+ this.handleResponseLine(line);
187
+ }
188
+ }
189
+
190
+ handleStderrData(chunk: Buffer | string): void {
191
+ try {
192
+ this.stderrBuffer += sanitizeStderr(chunk.toString());
193
+ if (this.stderrBuffer.length > this.options.maxStderrBytes) {
194
+ this.stderrBuffer = this.stderrBuffer.slice(
195
+ this.stderrBuffer.length - this.options.maxStderrBytes
196
+ );
197
+ }
198
+ } catch {
199
+ // Ignore stderr buffering errors
200
+ }
201
+ }
202
+
203
+ handleProcessExit(): void {
204
+ const stderrTail = this.getStderrTail();
205
+ const msg = stderrTail
206
+ ? `Python process exited. Stderr:\n${stderrTail}`
207
+ : 'Python process exited';
208
+ this.rejectAll(new BridgeProtocolError(msg));
209
+ }
210
+
211
+ handleProcessError(err: Error): void {
212
+ const msg = `Python process error: ${err.message}`;
213
+ const error = new BridgeProtocolError(msg);
214
+ this.rejectAll(error);
215
+ this.handleFatalError(error);
216
+ }
217
+
218
+ private handleResponseLine(line: string): void {
219
+ let msg: RpcResponse;
220
+ try {
221
+ const parsed = JSON.parse(line) as unknown;
222
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
223
+ this.handleProtocolError('Invalid response payload', line);
224
+ return;
225
+ }
226
+ msg = parsed as RpcResponse;
227
+ } catch (err) {
228
+ const parseMessage = err instanceof Error ? err.message : String(err);
229
+ this.handleProtocolError(`Invalid JSON: ${parseMessage}`, line);
230
+ return;
231
+ }
232
+
233
+ if (msg.protocol !== this.options.protocol) {
234
+ this.handleProtocolError(
235
+ `Invalid protocol. Expected ${this.options.protocol} but received ${String(msg.protocol)}`,
236
+ line
237
+ );
238
+ return;
239
+ }
240
+
241
+ if (typeof msg.id !== 'number') {
242
+ this.handleProtocolError('Invalid response id', line);
243
+ return;
244
+ }
245
+
246
+ const pending = this.pending.get(msg.id);
247
+ if (!pending) {
248
+ if (this.timedOutRequests.consume(msg.id)) {
249
+ return;
250
+ }
251
+ this.handleProtocolError(`Unexpected response id ${msg.id}`, line);
252
+ return;
253
+ }
254
+
255
+ this.pending.delete(msg.id);
256
+ if (pending.timer) {
257
+ clearTimeout(pending.timer);
258
+ }
259
+
260
+ if ('error' in msg) {
261
+ const errorPayload = this.normalizeErrorPayload(msg.error);
262
+ pending.reject(this.errorFrom(errorPayload));
263
+ return;
264
+ }
265
+
266
+ Promise.resolve(this.options.decodeValue(msg.result))
267
+ .then(decoded => pending.resolve(decoded))
268
+ .catch(err => {
269
+ pending.reject(
270
+ new BridgeProtocolError(
271
+ `Failed to decode Python response: ${err instanceof Error ? err.message : String(err)}`
272
+ )
273
+ );
274
+ });
275
+ }
276
+
277
+ private errorFrom(err: { type: string; message: string; traceback?: string }): Error {
278
+ const error = new BridgeExecutionError(`${err.type}: ${err.message}`);
279
+ error.traceback = err.traceback;
280
+ return error;
281
+ }
282
+
283
+ private normalizeErrorPayload(err: unknown): { type: string; message: string; traceback?: string } {
284
+ if (err && typeof err === 'object') {
285
+ const candidate = err as { type?: unknown; message?: unknown; traceback?: unknown };
286
+ if (typeof candidate.type === 'string' && typeof candidate.message === 'string') {
287
+ const normalized: { type: string; message: string; traceback?: string } = {
288
+ type: candidate.type,
289
+ message: candidate.message,
290
+ };
291
+ if (typeof candidate.traceback === 'string') {
292
+ normalized.traceback = candidate.traceback;
293
+ }
294
+ return normalized;
295
+ }
296
+ }
297
+ return { type: 'UnknownError', message: String(err) };
298
+ }
299
+
300
+ private failRequest(id: number, error: Error): void {
301
+ const pending = this.pending.get(id);
302
+ if (!pending) {
303
+ return;
304
+ }
305
+ this.pending.delete(id);
306
+ if (pending.timer) {
307
+ clearTimeout(pending.timer);
308
+ }
309
+ pending.reject(error);
310
+ }
311
+
312
+ private rejectAll(error: Error): void {
313
+ for (const [, pending] of this.pending) {
314
+ if (pending.timer) {
315
+ clearTimeout(pending.timer);
316
+ }
317
+ pending.reject(error);
318
+ }
319
+ this.pending.clear();
320
+ this.timedOutRequests.clear();
321
+ }
322
+
323
+ private handleProtocolError(details: string, line?: string): void {
324
+ if (this.protocolError) {
325
+ return;
326
+ }
327
+ this.protocolError = true;
328
+ const snippet = line ? (line.length > 500 ? `${line.slice(0, 500)}...` : line) : undefined;
329
+ const hint =
330
+ 'Ensure your Python code does not print to stdout and that the bridge outputs only JSON lines.';
331
+ const msg = snippet
332
+ ? `Protocol error from Python bridge. ${details}\n${hint}\nOffending line: ${snippet}`
333
+ : `Protocol error from Python bridge. ${details}\n${hint}`;
334
+ const error = new BridgeProtocolError(msg);
335
+ this.rejectAll(error);
336
+ this.handleFatalError(error);
337
+ }
338
+
339
+ private handleFatalError(error: BridgeProtocolError): void {
340
+ try {
341
+ this.options.onFatalError(error);
342
+ } catch {
343
+ // Ignore callback failures
344
+ }
345
+ }
346
+ }
347
+
348
+ export function validateBridgeInfo(info: unknown): void {
349
+ if (!info || typeof info !== 'object') {
350
+ throw new BridgeProtocolError('Invalid bridge info payload');
351
+ }
352
+ const candidate = info as BridgeInfo;
353
+ if (
354
+ candidate.protocol !== TYWRAP_PROTOCOL ||
355
+ candidate.protocolVersion !== TYWRAP_PROTOCOL_VERSION
356
+ ) {
357
+ throw new BridgeProtocolError('Invalid bridge info payload');
358
+ }
359
+ if (candidate.bridge !== 'python-subprocess') {
360
+ throw new BridgeProtocolError(`Unexpected bridge identifier: ${candidate.bridge}`);
361
+ }
362
+ }
363
+
364
+ export function getPathKey(...envs: Array<Record<string, string | undefined>>): string {
365
+ for (const env of envs) {
366
+ const key = findPathKey(env);
367
+ if (key) {
368
+ return key;
369
+ }
370
+ }
371
+ return 'PATH';
372
+ }
373
+
374
+ export function ensurePythonEncoding(env: NodeJS.ProcessEnv): void {
375
+ if (env.PYTHONUTF8 === undefined || env.PYTHONUTF8 === null || env.PYTHONUTF8 === '') {
376
+ env.PYTHONUTF8 = '1';
377
+ }
378
+ if (
379
+ env.PYTHONIOENCODING === undefined ||
380
+ env.PYTHONIOENCODING === null ||
381
+ env.PYTHONIOENCODING === ''
382
+ ) {
383
+ env.PYTHONIOENCODING = 'UTF-8';
384
+ }
385
+ }
386
+
387
+ export function ensureJsonFallback(env: NodeJS.ProcessEnv, enabled: boolean): void {
388
+ if (enabled && !env.TYWRAP_CODEC_FALLBACK) {
389
+ env.TYWRAP_CODEC_FALLBACK = 'json';
390
+ }
391
+ }
392
+
393
+ export function getMaxLineLengthFromEnv(env: NodeJS.ProcessEnv): number | undefined {
394
+ const raw = env.TYWRAP_CODEC_MAX_BYTES?.trim();
395
+ if (!raw) {
396
+ return undefined;
397
+ }
398
+ if (!/^\d+$/.test(raw)) {
399
+ return undefined;
400
+ }
401
+ const parsed = Number(raw);
402
+ if (!Number.isFinite(parsed) || parsed <= 0) {
403
+ return undefined;
404
+ }
405
+ return parsed;
406
+ }
407
+
408
+ export function normalizeEnv(
409
+ baseEnv: Record<string, string | undefined>,
410
+ overrides: Record<string, string | undefined>
411
+ ): NodeJS.ProcessEnv {
412
+ // Why: normalize PATH casing (Windows) and drop undefined values to avoid spawn surprises.
413
+ const overridePathKey = findPathKey(overrides);
414
+ const basePathKey = findPathKey(baseEnv);
415
+ const pathKey = basePathKey ?? overridePathKey ?? 'PATH';
416
+ let pathValue: string | undefined;
417
+ if (overridePathKey !== null) {
418
+ // eslint-disable-next-line security/detect-object-injection -- env keys are dynamic by design
419
+ pathValue = overrides[overridePathKey];
420
+ } else if (basePathKey) {
421
+ // eslint-disable-next-line security/detect-object-injection -- env keys are dynamic by design
422
+ pathValue = baseEnv[basePathKey];
423
+ }
424
+ const merged: Record<string, string | undefined> = { ...baseEnv, ...overrides };
425
+
426
+ const result: NodeJS.ProcessEnv = {};
427
+
428
+ if (pathValue !== undefined) {
429
+ // eslint-disable-next-line security/detect-object-injection -- env keys are dynamic by design
430
+ result[pathKey] = pathValue;
431
+ }
432
+
433
+ for (const [key, value] of Object.entries(merged)) {
434
+ if (value === undefined) {
435
+ continue;
436
+ }
437
+ if (key.toLowerCase() === 'path') {
438
+ continue;
439
+ }
440
+ // eslint-disable-next-line security/detect-object-injection -- env keys are dynamic by design
441
+ result[key] = value;
442
+ }
443
+
444
+ return result;
445
+ }
446
+
447
+ function findPathKey(env: Record<string, string | undefined>): string | null {
448
+ for (const key of Object.keys(env)) {
449
+ if (key.toLowerCase() === 'path') {
450
+ return key;
451
+ }
452
+ }
453
+ return null;
454
+ }