tywrap 0.6.0 → 0.6.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.
Files changed (56) hide show
  1. package/dist/core/annotation-parser.d.ts.map +1 -1
  2. package/dist/core/annotation-parser.js +19 -14
  3. package/dist/core/annotation-parser.js.map +1 -1
  4. package/dist/core/discovery.d.ts +17 -0
  5. package/dist/core/discovery.d.ts.map +1 -1
  6. package/dist/core/discovery.js +59 -49
  7. package/dist/core/discovery.js.map +1 -1
  8. package/dist/core/validation.d.ts +23 -0
  9. package/dist/core/validation.d.ts.map +1 -1
  10. package/dist/core/validation.js +52 -48
  11. package/dist/core/validation.js.map +1 -1
  12. package/dist/dev.d.ts.map +1 -1
  13. package/dist/dev.js +175 -133
  14. package/dist/dev.js.map +1 -1
  15. package/dist/runtime/bridge-codec.d.ts +15 -0
  16. package/dist/runtime/bridge-codec.d.ts.map +1 -1
  17. package/dist/runtime/bridge-codec.js +45 -48
  18. package/dist/runtime/bridge-codec.js.map +1 -1
  19. package/dist/runtime/rpc-client.d.ts +18 -0
  20. package/dist/runtime/rpc-client.d.ts.map +1 -1
  21. package/dist/runtime/rpc-client.js +30 -24
  22. package/dist/runtime/rpc-client.js.map +1 -1
  23. package/dist/runtime/subprocess-transport.d.ts +16 -0
  24. package/dist/runtime/subprocess-transport.d.ts.map +1 -1
  25. package/dist/runtime/subprocess-transport.js +54 -35
  26. package/dist/runtime/subprocess-transport.js.map +1 -1
  27. package/dist/tywrap.d.ts +0 -5
  28. package/dist/tywrap.d.ts.map +1 -1
  29. package/dist/tywrap.js +0 -20
  30. package/dist/tywrap.js.map +1 -1
  31. package/dist/utils/cache.d.ts +11 -0
  32. package/dist/utils/cache.d.ts.map +1 -1
  33. package/dist/utils/cache.js +50 -58
  34. package/dist/utils/cache.js.map +1 -1
  35. package/dist/utils/python.d.ts.map +1 -1
  36. package/dist/utils/python.js +28 -17
  37. package/dist/utils/python.js.map +1 -1
  38. package/dist/utils/runtime.d.ts.map +1 -1
  39. package/dist/utils/runtime.js +22 -16
  40. package/dist/utils/runtime.js.map +1 -1
  41. package/dist/version.js +1 -1
  42. package/package.json +1 -1
  43. package/runtime/__pycache__/safe_codec.cpython-311.pyc +0 -0
  44. package/runtime/__pycache__/tywrap_bridge_core.cpython-311.pyc +0 -0
  45. package/src/core/annotation-parser.ts +23 -18
  46. package/src/core/discovery.ts +70 -54
  47. package/src/core/validation.ts +84 -48
  48. package/src/dev.ts +237 -153
  49. package/src/runtime/bridge-codec.ts +58 -70
  50. package/src/runtime/rpc-client.ts +39 -32
  51. package/src/runtime/subprocess-transport.ts +69 -39
  52. package/src/tywrap.ts +0 -24
  53. package/src/utils/cache.ts +59 -61
  54. package/src/utils/python.ts +33 -20
  55. package/src/utils/runtime.ts +24 -13
  56. package/src/version.ts +1 -1
package/src/dev.ts CHANGED
@@ -335,42 +335,44 @@ async function listExistingManagedFiles(outputDir: string): Promise<Set<string>>
335
335
  return managedFiles;
336
336
  }
337
337
 
338
+ async function listChildDirectories(current: string): Promise<string[]> {
339
+ let entries;
340
+ try {
341
+ entries = await readdir(current, { withFileTypes: true });
342
+ } catch {
343
+ return [];
344
+ }
345
+
346
+ return entries
347
+ .filter(entry => entry.isDirectory())
348
+ .map(entry => join(current, entry.name));
349
+ }
350
+
351
+ async function isWatchableDirectory(current: string, ignoredPaths: string[]): Promise<boolean> {
352
+ if (shouldIgnoreWatchPath(current, ignoredPaths)) {
353
+ return false;
354
+ }
355
+
356
+ try {
357
+ const currentStats = await stat(current);
358
+ return currentStats.isDirectory();
359
+ } catch {
360
+ return false;
361
+ }
362
+ }
363
+
338
364
  async function collectWatchDirectories(root: string, ignoredPaths: string[]): Promise<string[]> {
339
365
  const queue = [resolve(root)];
340
366
  const directories: string[] = [];
341
367
 
342
368
  while (queue.length > 0) {
343
369
  const current = queue.shift()!;
344
- if (shouldIgnoreWatchPath(current, ignoredPaths)) {
345
- continue;
346
- }
347
-
348
- let currentStats;
349
- try {
350
- currentStats = await stat(current);
351
- } catch {
352
- continue;
353
- }
354
-
355
- if (!currentStats.isDirectory()) {
370
+ if (!(await isWatchableDirectory(current, ignoredPaths))) {
356
371
  continue;
357
372
  }
358
373
 
359
374
  directories.push(current);
360
-
361
- let entries;
362
- try {
363
- entries = await readdir(current, { withFileTypes: true });
364
- } catch {
365
- continue;
366
- }
367
-
368
- for (const entry of entries) {
369
- if (!entry.isDirectory()) {
370
- continue;
371
- }
372
- queue.push(join(current, entry.name));
373
- }
375
+ queue.push(...(await listChildDirectories(current)));
374
376
  }
375
377
 
376
378
  return normalizePaths(directories);
@@ -444,7 +446,51 @@ async function promoteManagedFiles(
444
446
  }
445
447
  }
446
448
 
447
- async function resolveWatchTargets(config: TywrapOptions): Promise<WatchTarget[]> {
449
+ interface WatchTargetPayload {
450
+ missing?: boolean;
451
+ origin?: string | null;
452
+ locations?: string[];
453
+ has_location?: boolean;
454
+ }
455
+
456
+ interface WatchPythonEnv {
457
+ pythonPath: string;
458
+ env: { PYTHONPATH: string } | undefined;
459
+ timeoutMs: number;
460
+ }
461
+
462
+ const WATCH_TARGET_RESOLUTION_SCRIPT = [
463
+ 'import importlib',
464
+ 'import importlib.util',
465
+ 'import json',
466
+ 'import sys',
467
+ '',
468
+ 'module_name = sys.argv[1]',
469
+ 'spec = importlib.util.find_spec(module_name)',
470
+ 'if spec is None:',
471
+ " print(json.dumps({'missing': True}))",
472
+ ' raise SystemExit(0)',
473
+ '',
474
+ 'module_path = None',
475
+ 'module_origin = spec.origin',
476
+ 'if spec.submodule_search_locations:',
477
+ ' try:',
478
+ ' module = importlib.import_module(module_name)',
479
+ ' except Exception:',
480
+ ' module = None',
481
+ ' if module is not None:',
482
+ ' module_path = getattr(module, "__path__", None)',
483
+ ' module_origin = getattr(module, "__file__", None) or spec.origin',
484
+ 'payload = {',
485
+ " 'missing': False,",
486
+ " 'origin': module_origin,",
487
+ " 'locations': list(module_path) if module_path is not None else list(spec.submodule_search_locations or []),",
488
+ " 'has_location': bool(spec.has_location),",
489
+ '}',
490
+ 'print(json.dumps(payload))',
491
+ ].join('\n');
492
+
493
+ async function resolveWatchPythonEnv(config: TywrapOptions): Promise<WatchPythonEnv> {
448
494
  const pythonPath = await resolvePythonExecutable({
449
495
  pythonPath: config.runtime?.node?.pythonPath,
450
496
  virtualEnv: config.runtime?.node?.virtualEnv,
@@ -460,104 +506,100 @@ async function resolveWatchTargets(config: TywrapOptions): Promise<WatchTarget[]
460
506
  const env = mergedPyPath ? { PYTHONPATH: mergedPyPath } : undefined;
461
507
  const timeoutMs = config.runtime?.node?.timeout ?? 30000;
462
508
 
463
- const watchTargets: WatchTarget[] = [];
464
-
465
- for (const moduleName of Object.keys(config.pythonModules ?? {})) {
466
- const resolutionScript = [
467
- 'import importlib',
468
- 'import importlib.util',
469
- 'import json',
470
- 'import sys',
471
- '',
472
- 'module_name = sys.argv[1]',
473
- 'spec = importlib.util.find_spec(module_name)',
474
- 'if spec is None:',
475
- " print(json.dumps({'missing': True}))",
476
- ' raise SystemExit(0)',
477
- '',
478
- 'module_path = None',
479
- 'module_origin = spec.origin',
480
- 'if spec.submodule_search_locations:',
481
- ' try:',
482
- ' module = importlib.import_module(module_name)',
483
- ' except Exception:',
484
- ' module = None',
485
- ' if module is not None:',
486
- ' module_path = getattr(module, "__path__", None)',
487
- ' module_origin = getattr(module, "__file__", None) or spec.origin',
488
- 'payload = {',
489
- " 'missing': False,",
490
- " 'origin': module_origin,",
491
- " 'locations': list(module_path) if module_path is not None else list(spec.submodule_search_locations or []),",
492
- " 'has_location': bool(spec.has_location),",
493
- '}',
494
- 'print(json.dumps(payload))',
495
- ].join('\n');
496
-
497
- const result = await processUtils.exec(pythonPath, ['-c', resolutionScript, moduleName], {
498
- timeoutMs,
499
- env,
500
- });
509
+ return { pythonPath, env, timeoutMs };
510
+ }
501
511
 
502
- if (result.code !== 0) {
503
- throw new Error(
504
- `Failed to resolve watch target for module "${moduleName}": ${result.stderr.trim() || result.stdout.trim() || 'unknown error'}`
505
- );
512
+ async function resolveWatchTargetPayload(
513
+ moduleName: string,
514
+ pythonEnv: WatchPythonEnv
515
+ ): Promise<WatchTargetPayload> {
516
+ const result = await processUtils.exec(
517
+ pythonEnv.pythonPath,
518
+ ['-c', WATCH_TARGET_RESOLUTION_SCRIPT, moduleName],
519
+ {
520
+ timeoutMs: pythonEnv.timeoutMs,
521
+ env: pythonEnv.env,
506
522
  }
523
+ );
507
524
 
508
- let payload: {
509
- missing?: boolean;
510
- origin?: string | null;
511
- locations?: string[];
512
- has_location?: boolean;
513
- };
514
- try {
515
- payload = JSON.parse(result.stdout) as {
516
- missing?: boolean;
517
- origin?: string | null;
518
- locations?: string[];
519
- has_location?: boolean;
520
- };
521
- } catch (error) {
525
+ if (result.code !== 0) {
526
+ throw new Error(
527
+ `Failed to resolve watch target for module "${moduleName}": ${result.stderr.trim() || result.stdout.trim() || 'unknown error'}`
528
+ );
529
+ }
530
+
531
+ try {
532
+ return JSON.parse(result.stdout) as WatchTargetPayload;
533
+ } catch (error) {
534
+ throw new Error(
535
+ `Failed to parse watch target for module "${moduleName}": ${(error as Error).message}`
536
+ );
537
+ }
538
+ }
539
+
540
+ async function resolvePackageWatchTargets(
541
+ moduleName: string,
542
+ packageLocations: string[]
543
+ ): Promise<WatchTarget[]> {
544
+ const targets: WatchTarget[] = [];
545
+ for (const location of packageLocations) {
546
+ const packageDir = resolve(location);
547
+ const stats = await stat(packageDir);
548
+ if (!stats.isDirectory()) {
522
549
  throw new Error(
523
- `Failed to parse watch target for module "${moduleName}": ${(error as Error).message}`
550
+ `Module "${moduleName}" resolved to "${packageDir}", but it is not a package directory`
524
551
  );
525
552
  }
553
+ targets.push({ moduleName, path: packageDir, kind: 'directory' });
554
+ }
555
+ return targets;
556
+ }
526
557
 
527
- if (payload.missing) {
528
- throw new Error(`Module "${moduleName}" could not be resolved for watching`);
529
- }
558
+ async function resolveFileWatchTarget(
559
+ moduleName: string,
560
+ payload: WatchTargetPayload
561
+ ): Promise<WatchTarget> {
562
+ if (typeof payload.origin !== 'string' || !payload.origin.endsWith('.py')) {
563
+ throw new Error(
564
+ `Module "${moduleName}" is not backed by a local Python source file or package directory and cannot be watched`
565
+ );
566
+ }
530
567
 
531
- const packageLocations = Array.isArray(payload.locations) ? payload.locations : [];
532
- if (packageLocations.length > 0) {
533
- for (const location of packageLocations) {
534
- const packageDir = resolve(location);
535
- const stats = await stat(packageDir);
536
- if (!stats.isDirectory()) {
537
- throw new Error(
538
- `Module "${moduleName}" resolved to "${packageDir}", but it is not a package directory`
539
- );
540
- }
541
- watchTargets.push({ moduleName, path: packageDir, kind: 'directory' });
542
- }
543
- continue;
544
- }
568
+ const modulePath = resolve(payload.origin);
569
+ const stats = await stat(modulePath);
570
+ if (!stats.isFile()) {
571
+ throw new Error(
572
+ `Module "${moduleName}" resolved to "${modulePath}", but it is not a Python source file`
573
+ );
574
+ }
545
575
 
546
- if (typeof payload.origin !== 'string' || !payload.origin.endsWith('.py')) {
547
- throw new Error(
548
- `Module "${moduleName}" is not backed by a local Python source file or package directory and cannot be watched`
549
- );
550
- }
576
+ return { moduleName, path: modulePath, kind: 'file' };
577
+ }
551
578
 
552
- const modulePath = resolve(payload.origin);
553
- const stats = await stat(modulePath);
554
- if (!stats.isFile()) {
555
- throw new Error(
556
- `Module "${moduleName}" resolved to "${modulePath}", but it is not a Python source file`
557
- );
558
- }
579
+ async function resolveModuleWatchTargets(
580
+ moduleName: string,
581
+ pythonEnv: WatchPythonEnv
582
+ ): Promise<WatchTarget[]> {
583
+ const payload = await resolveWatchTargetPayload(moduleName, pythonEnv);
584
+
585
+ if (payload.missing) {
586
+ throw new Error(`Module "${moduleName}" could not be resolved for watching`);
587
+ }
559
588
 
560
- watchTargets.push({ moduleName, path: modulePath, kind: 'file' });
589
+ const packageLocations = Array.isArray(payload.locations) ? payload.locations : [];
590
+ if (packageLocations.length > 0) {
591
+ return resolvePackageWatchTargets(moduleName, packageLocations);
592
+ }
593
+
594
+ return [await resolveFileWatchTarget(moduleName, payload)];
595
+ }
596
+
597
+ async function resolveWatchTargets(config: TywrapOptions): Promise<WatchTarget[]> {
598
+ const pythonEnv = await resolveWatchPythonEnv(config);
599
+
600
+ const watchTargets: WatchTarget[] = [];
601
+ for (const moduleName of Object.keys(config.pythonModules ?? {})) {
602
+ watchTargets.push(...(await resolveModuleWatchTargets(moduleName, pythonEnv)));
561
603
  }
562
604
 
563
605
  return watchTargets;
@@ -786,6 +828,28 @@ export async function startNodeWatchSession<T extends RuntimeExecution & Disposa
786
828
  return watcherRefreshPromise;
787
829
  };
788
830
 
831
+ interface ReloadState {
832
+ stage: StageResult | null;
833
+ nextBridge: T | null;
834
+ preparedWatchers: PreparedWatchers | null;
835
+ }
836
+
837
+ interface PreparedReload {
838
+ stage: StageResult;
839
+ preparedWatchers: PreparedWatchers;
840
+ nextIgnoredPaths: string[];
841
+ watchPaths: string[];
842
+ }
843
+
844
+ const disposeReloadFailure = async (state: ReloadState): Promise<void> => {
845
+ if (state.preparedWatchers) {
846
+ closePreparedWatchers(state.preparedWatchers);
847
+ }
848
+ if (state.nextBridge) {
849
+ await state.nextBridge.dispose().catch(() => {});
850
+ }
851
+ };
852
+
789
853
  const runReload = async (trigger: { path?: string; manual: boolean }): Promise<boolean> => {
790
854
  if (closed) {
791
855
  return false;
@@ -793,20 +857,18 @@ export async function startNodeWatchSession<T extends RuntimeExecution & Disposa
793
857
 
794
858
  emit({ type: 'reload-start', path: trigger.path, manual: trigger.manual });
795
859
 
796
- let stage: StageResult | null = null;
797
- let nextBridge: T | null = null;
798
- let preparedWatchers: PreparedWatchers | null = null;
860
+ const state: ReloadState = { stage: null, nextBridge: null, preparedWatchers: null };
799
861
 
800
862
  const abortReload = async (
801
863
  managerToDispose: ManagedBridgeReloader<T> | null = null
802
864
  ): Promise<boolean> => {
803
- if (preparedWatchers) {
804
- closePreparedWatchers(preparedWatchers);
805
- preparedWatchers = null;
865
+ if (state.preparedWatchers) {
866
+ closePreparedWatchers(state.preparedWatchers);
867
+ state.preparedWatchers = null;
806
868
  }
807
- if (nextBridge) {
808
- await nextBridge.dispose().catch(() => {});
809
- nextBridge = null;
869
+ if (state.nextBridge) {
870
+ await state.nextBridge.dispose().catch(() => {});
871
+ state.nextBridge = null;
810
872
  }
811
873
  if (managerToDispose) {
812
874
  await managerToDispose.dispose().catch(() => {});
@@ -814,10 +876,13 @@ export async function startNodeWatchSession<T extends RuntimeExecution & Disposa
814
876
  return false;
815
877
  };
816
878
 
817
- try {
818
- stage = await generateToStage(configFile);
879
+ // Generate the next stage, prepare watchers, and warm the next bridge.
880
+ // Returns null when the session closed mid-flight (caller aborts).
881
+ const prepareReload = async (): Promise<PreparedReload | null> => {
882
+ const stage = await generateToStage(configFile);
883
+ state.stage = stage;
819
884
  if (closed) {
820
- return abortReload();
885
+ return null;
821
886
  }
822
887
  currentBridgeConfig = stage.config;
823
888
  const nextIgnoredPaths = buildIgnoredPaths(stage.outputDir);
@@ -828,17 +893,50 @@ export async function startNodeWatchSession<T extends RuntimeExecution & Disposa
828
893
  ...extraWatchSources,
829
894
  ]);
830
895
  const watchPaths = normalizePaths(watchSources.map(source => source.path));
831
- preparedWatchers = await prepareWatchers(watchSources, nextIgnoredPaths);
896
+ const preparedWatchers = await prepareWatchers(watchSources, nextIgnoredPaths);
897
+ state.preparedWatchers = preparedWatchers;
832
898
  if (closed) {
833
- return abortReload();
899
+ return null;
834
900
  }
835
901
 
836
902
  if (bridgeManager) {
837
- nextBridge = await bridgeManager.prepareNextBridge();
903
+ state.nextBridge = await bridgeManager.prepareNextBridge();
904
+ if (closed) {
905
+ return null;
906
+ }
907
+ }
908
+
909
+ return { stage, preparedWatchers, nextIgnoredPaths, watchPaths };
910
+ };
911
+
912
+ // Activate (or create) the bridge for the freshly prepared stage.
913
+ // Returns the manager to dispose (or null) when the session closed
914
+ // mid-flight, otherwise null; sets `closedDuringActivation` accordingly.
915
+ let closedDuringActivation = false;
916
+ const activateReloadBridge = async (): Promise<ManagedBridgeReloader<T> | null> => {
917
+ if (bridgeManager && state.nextBridge) {
918
+ await bridgeManager.activatePreparedBridge(state.nextBridge);
919
+ state.nextBridge = null;
920
+ closedDuringActivation = closed;
921
+ return null;
922
+ }
923
+ if (!bridgeManager) {
924
+ const createdBridgeManager = await ManagedBridgeReloader.create(createBridgeForSession);
838
925
  if (closed) {
839
- return abortReload();
926
+ closedDuringActivation = true;
927
+ return createdBridgeManager;
840
928
  }
929
+ bridgeManager = createdBridgeManager;
930
+ }
931
+ return null;
932
+ };
933
+
934
+ try {
935
+ const prepared = await prepareReload();
936
+ if (!prepared) {
937
+ return abortReload();
841
938
  }
939
+ const { stage } = prepared;
842
940
 
843
941
  const previousManagedFiles =
844
942
  activeOutputDir === stage.outputDir
@@ -853,29 +951,20 @@ export async function startNodeWatchSession<T extends RuntimeExecution & Disposa
853
951
  return abortReload();
854
952
  }
855
953
 
856
- if (bridgeManager && nextBridge) {
857
- await bridgeManager.activatePreparedBridge(nextBridge);
858
- nextBridge = null;
859
- if (closed) {
860
- return abortReload();
861
- }
862
- } else if (!bridgeManager) {
863
- const createdBridgeManager = await ManagedBridgeReloader.create(createBridgeForSession);
864
- if (closed) {
865
- return abortReload(createdBridgeManager);
866
- }
867
- bridgeManager = createdBridgeManager;
954
+ const managerToDispose = await activateReloadBridge();
955
+ if (closedDuringActivation) {
956
+ return abortReload(managerToDispose);
868
957
  }
869
958
 
870
959
  managedFiles = promotedManagedFiles;
871
960
  activeOutputDir = stage.outputDir;
872
- ignoredPaths = nextIgnoredPaths;
873
- commitWatchers(preparedWatchers);
961
+ ignoredPaths = prepared.nextIgnoredPaths;
962
+ commitWatchers(prepared.preparedWatchers);
874
963
  emit({
875
964
  type: 'reload-success',
876
965
  path: trigger.path,
877
966
  manual: trigger.manual,
878
- paths: watchPaths,
967
+ paths: prepared.watchPaths,
879
968
  written: [...stage.files.keys()].sort(),
880
969
  warnings: stage.warnings,
881
970
  });
@@ -883,12 +972,7 @@ export async function startNodeWatchSession<T extends RuntimeExecution & Disposa
883
972
  return true;
884
973
  } catch (error) {
885
974
  lastReloadError = error instanceof Error ? error : new Error(String(error));
886
- if (preparedWatchers) {
887
- closePreparedWatchers(preparedWatchers);
888
- }
889
- if (nextBridge) {
890
- await nextBridge.dispose().catch(() => {});
891
- }
975
+ await disposeReloadFailure(state);
892
976
  emit({
893
977
  type: 'reload-error',
894
978
  path: trigger.path,
@@ -897,8 +981,8 @@ export async function startNodeWatchSession<T extends RuntimeExecution & Disposa
897
981
  });
898
982
  return false;
899
983
  } finally {
900
- if (stage) {
901
- await rm(stage.tempDir, { recursive: true, force: true });
984
+ if (state.stage) {
985
+ await rm(state.stage.tempDir, { recursive: true, force: true });
902
986
  }
903
987
  }
904
988
  };
@@ -410,6 +410,60 @@ export class BridgeCodec {
410
410
  return bridgeError;
411
411
  }
412
412
 
413
+ /**
414
+ * Shared prelude for both decode paths: size guard, JSON parse (with bytes
415
+ * revival), protocol-version validation, and RPC-envelope unwrapping.
416
+ *
417
+ * Behavior-preserving extraction of the common head of decodeResponse and
418
+ * decodeResponseAsync; the only divergence between the two is what they do
419
+ * with the returned result (sync returns it as-is, async applies Arrow
420
+ * decoding) and so that divergence stays in the callers.
421
+ */
422
+ private parseResponseResult(payload: string): unknown {
423
+ // Check payload size first
424
+ const payloadBytes = new TextEncoder().encode(payload).length;
425
+ if (payloadBytes > this.maxPayloadBytes) {
426
+ throw new BridgeCodecError(
427
+ `Response payload size ${payloadBytes} bytes exceeds maximum ${this.maxPayloadBytes} bytes`,
428
+ { codecPhase: 'decode', valueType: 'payload' }
429
+ );
430
+ }
431
+
432
+ // Parse JSON
433
+ let parsed: unknown;
434
+ try {
435
+ parsed = JSON.parse(payload, this.reviveValueBound);
436
+ } catch (err) {
437
+ if (err instanceof BridgeCodecError || err instanceof BridgeProtocolError) {
438
+ throw err;
439
+ }
440
+ const errorMessage = err instanceof Error ? err.message : String(err);
441
+ throw new BridgeCodecError(
442
+ `JSON parse failed: ${errorMessage}. Payload snippet: ${summarizePayloadForError(payload)}`,
443
+ { codecPhase: 'decode', valueType: 'json' }
444
+ );
445
+ }
446
+
447
+ // Validate protocol version (if present)
448
+ validateProtocolVersion(parsed);
449
+
450
+ return this.extractResultFromRpcResponse(parsed);
451
+ }
452
+
453
+ /**
454
+ * Post-decode guard: reject non-finite numbers (NaN/Infinity) when enabled.
455
+ * Shared by both decode paths.
456
+ */
457
+ private assertNoSpecialFloats(value: unknown): void {
458
+ if (this.rejectSpecialFloats && containsSpecialFloat(value)) {
459
+ const floatPath = findSpecialFloatPath(value);
460
+ throw new BridgeCodecError(
461
+ `Response contains non-finite number (NaN or Infinity) at ${floatPath}`,
462
+ { codecPhase: 'decode', valueType: 'number' }
463
+ );
464
+ }
465
+ }
466
+
413
467
  private extractResultFromRpcResponse(parsed: unknown): unknown {
414
468
  if (isRpcResponse(parsed)) {
415
469
  const response = parsed;
@@ -526,43 +580,10 @@ export class BridgeCodec {
526
580
  * @throws BridgeExecutionError if response contains a Python error
527
581
  */
528
582
  decodeResponse<T>(payload: string): T {
529
- // Check payload size first
530
- const payloadBytes = new TextEncoder().encode(payload).length;
531
- if (payloadBytes > this.maxPayloadBytes) {
532
- throw new BridgeCodecError(
533
- `Response payload size ${payloadBytes} bytes exceeds maximum ${this.maxPayloadBytes} bytes`,
534
- { codecPhase: 'decode', valueType: 'payload' }
535
- );
536
- }
537
-
538
- // Parse JSON
539
- let parsed: unknown;
540
- try {
541
- parsed = JSON.parse(payload, this.reviveValueBound);
542
- } catch (err) {
543
- if (err instanceof BridgeCodecError || err instanceof BridgeProtocolError) {
544
- throw err;
545
- }
546
- const errorMessage = err instanceof Error ? err.message : String(err);
547
- throw new BridgeCodecError(
548
- `JSON parse failed: ${errorMessage}. Payload snippet: ${summarizePayloadForError(payload)}`,
549
- { codecPhase: 'decode', valueType: 'json' }
550
- );
551
- }
552
-
553
- // Validate protocol version (if present)
554
- validateProtocolVersion(parsed);
555
-
556
- const result = this.extractResultFromRpcResponse(parsed);
583
+ const result = this.parseResponseResult(payload);
557
584
 
558
585
  // Post-decode validation for special floats if enabled
559
- if (this.rejectSpecialFloats && containsSpecialFloat(result)) {
560
- const floatPath = findSpecialFloatPath(result);
561
- throw new BridgeCodecError(
562
- `Response contains non-finite number (NaN or Infinity) at ${floatPath}`,
563
- { codecPhase: 'decode', valueType: 'number' }
564
- );
565
- }
586
+ this.assertNoSpecialFloats(result);
566
587
 
567
588
  return result as T;
568
589
  }
@@ -578,34 +599,7 @@ export class BridgeCodec {
578
599
  * @throws BridgeExecutionError if response contains a Python error
579
600
  */
580
601
  async decodeResponseAsync<T>(payload: string): Promise<T> {
581
- // Check payload size first
582
- const payloadBytes = new TextEncoder().encode(payload).length;
583
- if (payloadBytes > this.maxPayloadBytes) {
584
- throw new BridgeCodecError(
585
- `Response payload size ${payloadBytes} bytes exceeds maximum ${this.maxPayloadBytes} bytes`,
586
- { codecPhase: 'decode', valueType: 'payload' }
587
- );
588
- }
589
-
590
- // Parse JSON
591
- let parsed: unknown;
592
- try {
593
- parsed = JSON.parse(payload, this.reviveValueBound);
594
- } catch (err) {
595
- if (err instanceof BridgeCodecError || err instanceof BridgeProtocolError) {
596
- throw err;
597
- }
598
- const errorMessage = err instanceof Error ? err.message : String(err);
599
- throw new BridgeCodecError(
600
- `JSON parse failed: ${errorMessage}. Payload snippet: ${summarizePayloadForError(payload)}`,
601
- { codecPhase: 'decode', valueType: 'json' }
602
- );
603
- }
604
-
605
- // Validate protocol version (if present)
606
- validateProtocolVersion(parsed);
607
-
608
- const result = this.extractResultFromRpcResponse(parsed);
602
+ const result = this.parseResponseResult(payload);
609
603
 
610
604
  // Apply Arrow decoding to the result
611
605
  let decoded: unknown;
@@ -621,13 +615,7 @@ export class BridgeCodec {
621
615
 
622
616
  // Post-decode validation for special floats if enabled
623
617
  // Note: Arrow decoders can introduce NaN/Infinity from binary representations.
624
- if (this.rejectSpecialFloats && containsSpecialFloat(decoded)) {
625
- const floatPath = findSpecialFloatPath(decoded);
626
- throw new BridgeCodecError(
627
- `Response contains non-finite number (NaN or Infinity) at ${floatPath}`,
628
- { codecPhase: 'decode', valueType: 'number' }
629
- );
630
- }
618
+ this.assertNoSpecialFloats(decoded);
631
619
 
632
620
  return decoded as T;
633
621
  }