type-git 0.2.0 → 0.3.0-alpha.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.
@@ -378,6 +378,128 @@ type CredentialConfig = {
378
378
  /** Callback when authentication fails */
379
379
  onAuthFailure?: (error: Error, request: CredentialRequest) => void;
380
380
  };
381
+ /**
382
+ * Audit event fired when a Git command starts execution
383
+ */
384
+ type AuditEventStart = {
385
+ /** Event type discriminator */
386
+ type: 'start';
387
+ /** Timestamp in milliseconds since epoch */
388
+ timestamp: number;
389
+ /** Command arguments (e.g., ['git', '-C', '/path', 'status']) */
390
+ argv: string[];
391
+ /** Execution context (global, worktree, or bare) */
392
+ context: ExecutionContext;
393
+ };
394
+ /**
395
+ * Audit event fired when a Git command completes
396
+ */
397
+ type AuditEventEnd = {
398
+ /** Event type discriminator */
399
+ type: 'end';
400
+ /** Timestamp in milliseconds since epoch */
401
+ timestamp: number;
402
+ /** Command arguments (same as start event) */
403
+ argv: string[];
404
+ /** Execution context (same as start event) */
405
+ context: ExecutionContext;
406
+ /** Standard output from the command */
407
+ stdout: string;
408
+ /** Standard error from the command */
409
+ stderr: string;
410
+ /** Exit code (0 = success) */
411
+ exitCode: number;
412
+ /** Whether command was aborted via AbortSignal */
413
+ aborted: boolean;
414
+ /** Duration in milliseconds */
415
+ duration: number;
416
+ };
417
+ /**
418
+ * Audit event for Git command execution lifecycle
419
+ *
420
+ * Discriminated union based on event type.
421
+ *
422
+ * @example
423
+ * ```typescript
424
+ * const git = await createGit({
425
+ * adapters: createNodeAdapters(),
426
+ * audit: {
427
+ * onAudit: (event) => {
428
+ * if (event.type === 'start') {
429
+ * console.log(`→ ${event.argv.join(' ')}`);
430
+ * } else {
431
+ * console.log(`✓ completed in ${event.duration}ms (exit ${event.exitCode})`);
432
+ * }
433
+ * }
434
+ * }
435
+ * });
436
+ * ```
437
+ */
438
+ type AuditEvent = AuditEventStart | AuditEventEnd;
439
+ /**
440
+ * Trace output from GIT_TRACE environment variable
441
+ *
442
+ * Captures Git's internal debug output when GIT_TRACE is enabled.
443
+ * Automatically enabled when onTrace callback is provided.
444
+ *
445
+ * @example
446
+ * ```typescript
447
+ * const git = await createGit({
448
+ * adapters: createNodeAdapters(),
449
+ * audit: {
450
+ * onTrace: (trace) => {
451
+ * console.log(`[GIT_TRACE] ${trace.line}`);
452
+ * }
453
+ * }
454
+ * });
455
+ * ```
456
+ */
457
+ type TraceEvent = {
458
+ /** Timestamp in milliseconds since epoch */
459
+ timestamp: number;
460
+ /** Raw trace output line from git stderr */
461
+ line: string;
462
+ };
463
+ /**
464
+ * Audit configuration for Git instance
465
+ *
466
+ * Provides hooks for observing Git command execution lifecycle
467
+ * and internal Git trace output.
468
+ *
469
+ * @example
470
+ * ```typescript
471
+ * const git = await createGit({
472
+ * adapters: createNodeAdapters(),
473
+ * audit: {
474
+ * onAudit: (event) => {
475
+ * if (event.type === 'start') {
476
+ * console.log(`[AUDIT] Starting: ${event.argv.join(' ')}`);
477
+ * } else {
478
+ * console.log(`[AUDIT] Completed: exit ${event.exitCode}, ${event.duration}ms`);
479
+ * }
480
+ * },
481
+ * onTrace: (trace) => {
482
+ * console.log(`[TRACE] ${trace.line}`);
483
+ * }
484
+ * }
485
+ * });
486
+ * ```
487
+ */
488
+ type AuditConfig = {
489
+ /**
490
+ * Callback invoked for each Git command lifecycle event
491
+ *
492
+ * Receives 'start' event before command execution and 'end' event after.
493
+ */
494
+ onAudit?: (event: AuditEvent) => void;
495
+ /**
496
+ * Callback invoked for GIT_TRACE output
497
+ *
498
+ * When provided, GIT_TRACE=1 is automatically set.
499
+ * Trace output is parsed from stderr lines.
500
+ */
501
+ onTrace?: (trace: TraceEvent) => void;
502
+ };
381
503
 
382
504
  /**
383
505
  * Runtime adapter interfaces for cross-platform support (Node/Deno/Bun)
@@ -606,4 +728,4 @@ interface RuntimeAdapters {
606
728
  */
607
729
  type AdapterFactory = () => RuntimeAdapters;
608
730
 
609
- export { type AdapterFactory as A, type Capabilities as C, type ExecAdapter as E, type FsAdapter as F, type GitErrorCategory as G, type LfsMode as L, type NonEmptyString as N, type OutputContract as O, type RuntimeAdapters as R, type SpawnOptions as S, type TailOptions as T, type StreamHandler as a, type SpawnResult as b, type SpawnHandle as c, type TailHandle as d, type ExecOpts as e, type RawResult as f, type GitProgress as g, type GitOpenOptions as h, type ExecutionContext as i, GitError as j, isNonEmpty as k, type LfsProgress as l, type GitErrorKind as m, nonEmpty as n, GitArgumentError as o, type Runtime as p, type CommandSpec as q, type CredentialRequest as r, type Credential as s, type CredentialConfig as t };
731
+ export { type AuditConfig as A, type Capabilities as C, type ExecAdapter as E, type FsAdapter as F, type GitErrorCategory as G, type LfsMode as L, type NonEmptyString as N, type OutputContract as O, type RuntimeAdapters as R, type SpawnOptions as S, type TailOptions as T, type StreamHandler as a, type SpawnResult as b, type SpawnHandle as c, type TailHandle as d, type ExecOpts as e, type RawResult as f, type GitProgress as g, type GitOpenOptions as h, type ExecutionContext as i, GitError as j, type AdapterFactory as k, isNonEmpty as l, type LfsProgress as m, nonEmpty as n, type GitErrorKind as o, GitArgumentError as p, type Runtime as q, type CommandSpec as r, type CredentialRequest as s, type Credential as t, type CredentialConfig as u, type AuditEventStart as v, type AuditEventEnd as w, type AuditEvent as x, type TraceEvent as y };
@@ -378,6 +378,128 @@ type CredentialConfig = {
378
378
  /** Callback when authentication fails */
379
379
  onAuthFailure?: (error: Error, request: CredentialRequest) => void;
380
380
  };
381
+ /**
382
+ * Audit event fired when a Git command starts execution
383
+ */
384
+ type AuditEventStart = {
385
+ /** Event type discriminator */
386
+ type: 'start';
387
+ /** Timestamp in milliseconds since epoch */
388
+ timestamp: number;
389
+ /** Command arguments (e.g., ['git', '-C', '/path', 'status']) */
390
+ argv: string[];
391
+ /** Execution context (global, worktree, or bare) */
392
+ context: ExecutionContext;
393
+ };
394
+ /**
395
+ * Audit event fired when a Git command completes
396
+ */
397
+ type AuditEventEnd = {
398
+ /** Event type discriminator */
399
+ type: 'end';
400
+ /** Timestamp in milliseconds since epoch */
401
+ timestamp: number;
402
+ /** Command arguments (same as start event) */
403
+ argv: string[];
404
+ /** Execution context (same as start event) */
405
+ context: ExecutionContext;
406
+ /** Standard output from the command */
407
+ stdout: string;
408
+ /** Standard error from the command */
409
+ stderr: string;
410
+ /** Exit code (0 = success) */
411
+ exitCode: number;
412
+ /** Whether command was aborted via AbortSignal */
413
+ aborted: boolean;
414
+ /** Duration in milliseconds */
415
+ duration: number;
416
+ };
417
+ /**
418
+ * Audit event for Git command execution lifecycle
419
+ *
420
+ * Discriminated union based on event type.
421
+ *
422
+ * @example
423
+ * ```typescript
424
+ * const git = await createGit({
425
+ * adapters: createNodeAdapters(),
426
+ * audit: {
427
+ * onAudit: (event) => {
428
+ * if (event.type === 'start') {
429
+ * console.log(`→ ${event.argv.join(' ')}`);
430
+ * } else {
431
+ * console.log(`✓ completed in ${event.duration}ms (exit ${event.exitCode})`);
432
+ * }
433
+ * }
434
+ * }
435
+ * });
436
+ * ```
437
+ */
438
+ type AuditEvent = AuditEventStart | AuditEventEnd;
439
+ /**
440
+ * Trace output from GIT_TRACE environment variable
441
+ *
442
+ * Captures Git's internal debug output when GIT_TRACE is enabled.
443
+ * Automatically enabled when onTrace callback is provided.
444
+ *
445
+ * @example
446
+ * ```typescript
447
+ * const git = await createGit({
448
+ * adapters: createNodeAdapters(),
449
+ * audit: {
450
+ * onTrace: (trace) => {
451
+ * console.log(`[GIT_TRACE] ${trace.line}`);
452
+ * }
453
+ * }
454
+ * });
455
+ * ```
456
+ */
457
+ type TraceEvent = {
458
+ /** Timestamp in milliseconds since epoch */
459
+ timestamp: number;
460
+ /** Raw trace output line from git stderr */
461
+ line: string;
462
+ };
463
+ /**
464
+ * Audit configuration for Git instance
465
+ *
466
+ * Provides hooks for observing Git command execution lifecycle
467
+ * and internal Git trace output.
468
+ *
469
+ * @example
470
+ * ```typescript
471
+ * const git = await createGit({
472
+ * adapters: createNodeAdapters(),
473
+ * audit: {
474
+ * onAudit: (event) => {
475
+ * if (event.type === 'start') {
476
+ * console.log(`[AUDIT] Starting: ${event.argv.join(' ')}`);
477
+ * } else {
478
+ * console.log(`[AUDIT] Completed: exit ${event.exitCode}, ${event.duration}ms`);
479
+ * }
480
+ * },
481
+ * onTrace: (trace) => {
482
+ * console.log(`[TRACE] ${trace.line}`);
483
+ * }
484
+ * }
485
+ * });
486
+ * ```
487
+ */
488
+ type AuditConfig = {
489
+ /**
490
+ * Callback invoked for each Git command lifecycle event
491
+ *
492
+ * Receives 'start' event before command execution and 'end' event after.
493
+ */
494
+ onAudit?: (event: AuditEvent) => void;
495
+ /**
496
+ * Callback invoked for GIT_TRACE output
497
+ *
498
+ * When provided, GIT_TRACE=1 is automatically set.
499
+ * Trace output is parsed from stderr lines.
500
+ */
501
+ onTrace?: (trace: TraceEvent) => void;
502
+ };
381
503
 
382
504
  /**
383
505
  * Runtime adapter interfaces for cross-platform support (Node/Deno/Bun)
@@ -606,4 +728,4 @@ interface RuntimeAdapters {
606
728
  */
607
729
  type AdapterFactory = () => RuntimeAdapters;
608
730
 
609
- export { type AdapterFactory as A, type Capabilities as C, type ExecAdapter as E, type FsAdapter as F, type GitErrorCategory as G, type LfsMode as L, type NonEmptyString as N, type OutputContract as O, type RuntimeAdapters as R, type SpawnOptions as S, type TailOptions as T, type StreamHandler as a, type SpawnResult as b, type SpawnHandle as c, type TailHandle as d, type ExecOpts as e, type RawResult as f, type GitProgress as g, type GitOpenOptions as h, type ExecutionContext as i, GitError as j, isNonEmpty as k, type LfsProgress as l, type GitErrorKind as m, nonEmpty as n, GitArgumentError as o, type Runtime as p, type CommandSpec as q, type CredentialRequest as r, type Credential as s, type CredentialConfig as t };
731
+ export { type AuditConfig as A, type Capabilities as C, type ExecAdapter as E, type FsAdapter as F, type GitErrorCategory as G, type LfsMode as L, type NonEmptyString as N, type OutputContract as O, type RuntimeAdapters as R, type SpawnOptions as S, type TailOptions as T, type StreamHandler as a, type SpawnResult as b, type SpawnHandle as c, type TailHandle as d, type ExecOpts as e, type RawResult as f, type GitProgress as g, type GitOpenOptions as h, type ExecutionContext as i, GitError as j, type AdapterFactory as k, isNonEmpty as l, type LfsProgress as m, nonEmpty as n, type GitErrorKind as o, GitArgumentError as p, type Runtime as q, type CommandSpec as r, type CredentialRequest as s, type Credential as t, type CredentialConfig as u, type AuditEventStart as v, type AuditEventEnd as w, type AuditEvent as x, type TraceEvent as y };
package/dist/index.cjs CHANGED
@@ -566,6 +566,7 @@ var import_node_process = __toESM(require("process"), 1);
566
566
  var FATAL_ERROR_PATTERN = /fatal:\s*(.+)/i;
567
567
  var ERROR_PATTERN = /error:\s*(.+)/i;
568
568
  var LINE_SEPARATOR_PATTERN = /\r|\n/;
569
+ var GIT_TRACE_PATTERN = /^\d{2}:\d{2}:\d{2}\.\d+\s+(?:trace:|[A-Za-z0-9_.-]+\.c:)/;
569
570
  function toLfsProgress(info) {
570
571
  if (!info) {
571
572
  return null;
@@ -618,6 +619,7 @@ var CliRunner = class _CliRunner {
618
619
  pathPrefix;
619
620
  home;
620
621
  credential;
622
+ audit;
621
623
  constructor(adapters, options) {
622
624
  this.exec = adapters.exec;
623
625
  this.gitBinary = options?.gitBinary ?? "git";
@@ -625,6 +627,7 @@ var CliRunner = class _CliRunner {
625
627
  this.pathPrefix = options?.pathPrefix ?? [];
626
628
  this.home = options?.home;
627
629
  this.credential = options?.credential;
630
+ this.audit = options?.audit;
628
631
  }
629
632
  /**
630
633
  * Create a new CliRunner with additional options merged
@@ -636,6 +639,7 @@ var CliRunner = class _CliRunner {
636
639
  const mergedPathPrefix = [...this.pathPrefix, ...options.pathPrefix ?? []];
637
640
  const home = options.home ?? this.home;
638
641
  const credential = options.credential ?? this.credential;
642
+ const audit = options.audit ?? this.audit;
639
643
  return new _CliRunner(
640
644
  {
641
645
  exec: this.exec,
@@ -652,7 +656,8 @@ var CliRunner = class _CliRunner {
652
656
  env: mergedEnv,
653
657
  pathPrefix: mergedPathPrefix,
654
658
  home,
655
- credential
659
+ credential,
660
+ audit
656
661
  }
657
662
  );
658
663
  }
@@ -700,6 +705,15 @@ var CliRunner = class _CliRunner {
700
705
  const currentPath = import_node_process.default.env.PATH ?? "";
701
706
  env.PATH = [...allPathPrefixes, currentPath].join(separator);
702
707
  }
708
+ if (this.audit?.onTrace) {
709
+ if (env.GIT_TRACE === void 0) {
710
+ env.GIT_TRACE = "1";
711
+ } else if (!env.GIT_TRACE || env.GIT_TRACE === "0") {
712
+ console.warn(
713
+ "type-git: onTrace callback provided but GIT_TRACE is disabled. Trace events will not be emitted."
714
+ );
715
+ }
716
+ }
703
717
  return env;
704
718
  }
705
719
  /**
@@ -723,27 +737,70 @@ var CliRunner = class _CliRunner {
723
737
  if (onLfsProgress) {
724
738
  env.GIT_LFS_FORCE_PROGRESS = "1";
725
739
  }
726
- let stderrBuffer = "";
727
- const result = await this.exec.spawn(
728
- {
740
+ const startTimestamp = Date.now();
741
+ if (this.audit?.onAudit) {
742
+ this.audit.onAudit({
743
+ type: "start",
744
+ timestamp: startTimestamp,
729
745
  argv,
730
- env,
731
- cwd: context.type === "worktree" ? context.workdir : void 0,
732
- signal
733
- },
734
- onProgress || onLfsProgress ? {
735
- onStderr: (chunk) => {
736
- stderrBuffer += chunk;
737
- const lines = stderrBuffer.split(LINE_SEPARATOR_PATTERN);
738
- stderrBuffer = lines.pop() ?? "";
739
- for (const line of lines) {
740
- processProgressLine(line, onProgress, onLfsProgress);
746
+ context
747
+ });
748
+ }
749
+ let stderrBuffer = "";
750
+ const needsStderrStreaming = onProgress || onLfsProgress || this.audit?.onTrace;
751
+ let result;
752
+ try {
753
+ result = await this.exec.spawn(
754
+ {
755
+ argv,
756
+ env,
757
+ cwd: context.type === "worktree" ? context.workdir : void 0,
758
+ signal
759
+ },
760
+ needsStderrStreaming ? {
761
+ onStderr: (chunk) => {
762
+ stderrBuffer += chunk;
763
+ const lines = stderrBuffer.split(LINE_SEPARATOR_PATTERN);
764
+ stderrBuffer = lines.pop() ?? "";
765
+ for (const line of lines) {
766
+ this.processStderrLine(line, onProgress, onLfsProgress);
767
+ }
741
768
  }
742
- }
743
- } : void 0
744
- );
745
- if (stderrBuffer.trim() && (onProgress || onLfsProgress)) {
746
- processProgressLine(stderrBuffer, onProgress, onLfsProgress);
769
+ } : void 0
770
+ );
771
+ if (stderrBuffer.trim() && needsStderrStreaming) {
772
+ this.processStderrLine(stderrBuffer, onProgress, onLfsProgress);
773
+ }
774
+ } catch (error) {
775
+ if (this.audit?.onAudit) {
776
+ const endTimestamp = Date.now();
777
+ this.audit.onAudit({
778
+ type: "end",
779
+ timestamp: endTimestamp,
780
+ argv,
781
+ context,
782
+ stdout: "",
783
+ stderr: error instanceof Error ? error.message : String(error),
784
+ exitCode: -1,
785
+ aborted: signal?.aborted ?? false,
786
+ duration: endTimestamp - startTimestamp
787
+ });
788
+ }
789
+ throw error;
790
+ }
791
+ if (this.audit?.onAudit) {
792
+ const endTimestamp = Date.now();
793
+ this.audit.onAudit({
794
+ type: "end",
795
+ timestamp: endTimestamp,
796
+ argv,
797
+ context,
798
+ stdout: result.stdout,
799
+ stderr: result.stderr,
800
+ exitCode: result.exitCode,
801
+ aborted: result.aborted,
802
+ duration: endTimestamp - startTimestamp
803
+ });
747
804
  }
748
805
  return {
749
806
  stdout: result.stdout,
@@ -752,6 +809,23 @@ var CliRunner = class _CliRunner {
752
809
  aborted: result.aborted
753
810
  };
754
811
  }
812
+ /**
813
+ * Process a single line from stderr for progress and trace callbacks
814
+ */
815
+ processStderrLine(line, onProgress, onLfsProgress) {
816
+ const trimmed = line.trim();
817
+ if (!trimmed) {
818
+ return;
819
+ }
820
+ if (this.audit?.onTrace && GIT_TRACE_PATTERN.test(trimmed)) {
821
+ this.audit.onTrace({
822
+ timestamp: Date.now(),
823
+ line: trimmed
824
+ });
825
+ return;
826
+ }
827
+ processProgressLine(line, onProgress, onLfsProgress);
828
+ }
755
829
  /**
756
830
  * Map Git result to GitError if needed
757
831
  */
@@ -1245,7 +1319,8 @@ var BareRepoImpl = class {
1245
1319
  }
1246
1320
  await this.runner.runOrThrow(this.context, args, {
1247
1321
  signal: opts?.signal,
1248
- onProgress: opts?.onProgress
1322
+ onProgress: opts?.onProgress,
1323
+ onLfsProgress: opts?.onLfsProgress
1249
1324
  });
1250
1325
  }
1251
1326
  // ==========================================================================
@@ -2216,7 +2291,8 @@ var WorktreeRepoImpl = class _WorktreeRepoImpl {
2216
2291
  }
2217
2292
  await this.runner.runOrThrow(this.context, args, {
2218
2293
  signal: opts?.signal,
2219
- onProgress: opts?.onProgress
2294
+ onProgress: opts?.onProgress,
2295
+ onLfsProgress: opts?.onLfsProgress
2220
2296
  });
2221
2297
  }
2222
2298
  /**
@@ -5560,7 +5636,8 @@ var GitImpl = class {
5560
5636
  try {
5561
5637
  await this.runner.runOrThrow({ type: "global" }, args, {
5562
5638
  signal: opts?.signal,
5563
- onProgress: opts?.onProgress
5639
+ onProgress: opts?.onProgress,
5640
+ onLfsProgress: opts?.onLfsProgress
5564
5641
  });
5565
5642
  } catch (error) {
5566
5643
  if (error instanceof GitError && error.kind === "Aborted" && opts?.cleanupOnAbort !== false) {