@gitkraken/shared-tools

中文文档
0.3.0发布于 2026/10/07SEE LICENSE IN LICENSETypeScriptES Module零依赖近 30 天下载 7457

Port interfaces, shared types, and undo-manifest machinery for @gitkraken core-tools.

原始使用文档
文档目录18 节
  1. Ports
  2. GitPort
  3. AiModelPort
  4. StoragePort
  5. TelemetryPort
  6. FileSystemPort
  7. Implementing the ports
  8. Example: GitPort adapter
  9. Example: AiModelPort adapter
  10. Undo manifests
  11. capturePreOperationState(git, options?)
  12. UndoStore
  13. generateUndoId()
  14. undoOperation(input) and validateUndo(input)
  15. Exports
  16. Runtime environment
  17. Contributing
  18. Design constraints for changes to ports

@gitkraken/shared-tools

Port interfaces, shared types, and undo-manifest machinery for the core-tools monorepo. Domain packages (like @gitkraken/compose-tools) depend on this package; consumers implement its ports with their own git and AI providers.

Ports

GitPort

Raw git command execution. Throws on non-zero exit code.

interface GitPort {
    exec(args: string[], options?: GitExecOptions): Promise<string>;
}

interface GitExecOptions {
    env?: Record<string, string>;
    stdin?: string;
    signal?: AbortSignal;
}

All higher-level git operations (diffing, commit building, ref management, rebase orchestration, etc.) are utility functions in domain packages that compose calls to exec(). Consumers never implement higher-level operations on this interface — see ComposeGitPort in @gitkraken/compose-tools for the optional higher-level op surface specific to that domain.

signal is forwarded from every domain workflow that accepts an AbortSignal. Adapters should wire it into their git-process execution so cancellation terminates the process.

AiModelPort

Stateless text generation. Callers pass the full message history each call — session threading is the caller's responsibility, not the model's.

interface AiModelPort {
    generate(params: AiGenerateParams): Promise<AiGenerateResult>;
}

interface AiGenerateParams {
    system?: string;
    messages: AiMessage[];
    maxTokens?: number;
    temperature?: number;
    signal?: AbortSignal;
}

interface AiGenerateResult {
    text: string;
    usage?: AiTokenUsage;
}

signal is forwarded from every AI workflow. Adapters should wire it into the underlying LLM request so in-flight calls cancel.

StoragePort

Async key/value store for a library's own state, already scoped by the host. No TTL; get returns null for an absent key. createMemoryStorage() is a non-durable Map-backed implementation for tests.

interface StoragePort {
    get(key: string): Promise<string | null>;
    set(key: string, value: string): Promise<void>;
    delete(key: string): Promise<void>;
}

TelemetryPort

Fire-and-forget telemetry sink; implementations must not throw. noopTelemetry is the default when the host injects nothing. Callers pass attributes that can hold URLs or error text through redactUrlCredentials.

interface TelemetryPort {
    event(name: string, attributes?: TelemetryAttributes): void;
    exception(error: unknown, attributes?: TelemetryAttributes): void;
}

FileSystemPort

Filesystem access over absolute, host-supplied paths. Absence is null; remove is a no-op when missing and throws on a non-empty directory unless recursive is set; mode is a POSIX permission that non-POSIX hosts ignore.

interface FileSystemPort {
    readFile(path: string): Promise<string | null>;
    writeFile(path: string, content: string, options?: { mode?: number }): Promise<void>;
    remove(path: string, options?: { recursive?: boolean }): Promise<void>;
    readDir(path: string): Promise<string[] | null>;
}

Implementing the ports

Consumers wrap their own git and AI providers as adapters. Adapters can layer telemetry, caching, error handling, cancellation, priority queuing, or any other behavior — all invisible to the domain packages.

Example: GitPort adapter

import type { GitPort } from '@gitkraken/shared-tools';

const git: GitPort = {
    exec: async (args, options) => {
        const result = await myGitProvider.run(args, {
            cwd: '/path/to/repo',
            env: options?.env,
            stdin: options?.stdin,
            signal: options?.signal,
        });
        return result.stdout;
    },
};

Example: AiModelPort adapter

import type { AiModelPort } from '@gitkraken/shared-tools';

const ai: AiModelPort = {
    generate: async (params) => {
        const response = await myAiProvider.chat(params.messages, {
            system: params.system,
            maxTokens: params.maxTokens,
            temperature: params.temperature,
            signal: params.signal,
        });
        return {
            text: response.text,
            usage: { inputTokens: response.inputTokens, outputTokens: response.outputTokens },
        };
    },
};

Undo manifests

Domain packages use these primitives to record every git mutation an operation performs and later replay the inverse. The machinery is shared because its shape is general — any operation that moves refs or changes the workdir can build a manifest out of it.

capturePreOperationState(git, options?)

Snapshots the pre-operation state before the workflow touches anything:

  • Current HEAD SHA and branch name.
  • A detached stash commit of the current workdir (via git stash create) when the workdir is dirty — stored as a loose object, not added to the stash list.

Undo uses this snapshot to restore HEAD and the workdir. The capture helper is careful not to mutate the real git index when it builds the stash — it uses a temp index via GIT_INDEX_FILE so the consumer's staged state is never perturbed.

UndoStore

Reads and writes UndoManifest objects into the repo's object database under refs/undo/<id>. Manifests survive branch operations and are removed automatically when undo runs. Provides save(manifest), load(id), list(), delete(id).

generateUndoId()

Emits a stable UUID for a new undo manifest.

undoOperation(input) and validateUndo(input)

The core undo execution and dry-run validator. Domain packages (like compose) wrap these with their own input types — undoCompose in compose-tools delegates to undoOperation after translating.

Exports

Values:

  • createMemoryStorage
  • noopTelemetry
  • redactUrlCredentials
  • capturePreOperationState
  • generateUndoId
  • UndoStore
  • undoOperation
  • validateUndo

Types:

  • GitPort, GitExecOptions
  • AiModelPort, AiGenerateParams, AiGenerateResult, AiMessage, AiTokenUsage
  • StoragePort, TelemetryPort, TelemetryAttributes, FileSystemPort
  • AiCreditUsage, GetAiCreditUsage
  • PreOperationState, UndoManifest, UndoId
  • RefKind, RefIdentity, RefSnapshot, RefMovement
  • UndoBlocker, UndoWarning, UndoValidation
  • UndoInput, UndoForceOptions, UndoResult, ValidateUndoInput

Also exported: refKindToFullRefname(kind, name) for resolving a kind-tagged identity to a full refname.

Runtime environment

This package uses Node.js built-ins (node:crypto, node:fs, node:os, node:path) in the undo machinery. Type-only imports are safe in any environment; runtime usage of UndoStore, capturePreOperationState, generateUndoId, undoOperation, validateUndo requires a Node.js runtime.

Contributing

This package follows the monorepo's standard tooling — see the root CONTRIBUTING.md. Local commands:

pnpm --filter @gitkraken/shared-tools build
pnpm --filter @gitkraken/shared-tools typecheck
pnpm --filter @gitkraken/shared-tools test

Design constraints for changes to ports

The ports are intentionally minimal and stable. Adding methods to GitPort or AiModelPort is a breaking change for every consumer — every implementation must be updated. Before proposing a new method:

  1. Confirm the operation cannot be expressed as a utility function built on top of exec() or generate().
  2. Confirm the operation is needed by multiple domain packages (not just one).
  3. Confirm no consumer can reasonably implement it differently in their adapter.

A new port may land ahead of its consumers when a stacked change needs the contract in place before the packages that use it.

In practice, new methods should be rare. The default answer to "should this go in the port?" is no — put it in a domain package as a utility that calls exec() / generate() internally, or in a domain-specific port interface (see ComposeGitPort in compose-tools).

版本与发布记录

@gitkraken/shared-tools 共发布 6 个版本,首次发布于 2026/04/24;过去 12 个月发布了 6 个版本。

版本发布日期距今
0.3.0latest2026/10/071 个月前
0.2.1-beta.2next2026/07/034 个月前
0.2.1-beta.12026/07/034 个月前
0.2.02026/05/146 个月前
0.1.12026/05/126 个月前
0.1.02026/04/246 个月前

关于 @gitkraken/shared-tools 的常见问题

@gitkraken/shared-tools 是什么?

Port interfaces, shared types, and undo-manifest machinery for @gitkraken core-tools.

如何安装 @gitkraken/shared-tools?

在项目目录运行 npm install @gitkraken/shared-tools,或使用 pnpm add / yarn add / bun add。

@gitkraken/shared-tools 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gitkraken/shared-tools 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@gitkraken/shared-tools 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= 22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@gitkraken/shared-tools 可以商用吗?

@gitkraken/shared-tools 使用 SEE LICENSE IN LICENSE 许可。许可条款写在包内的独立文件中,请阅读该文件确认可否商用。以上为概括,不构成法律意见,请以许可原文为准。

@gitkraken/shared-tools 的下载量有多少?

根据 npm 官方下载统计,@gitkraken/shared-tools 在 2026/10/17 – 2026/11/15 这 30 天内被下载 7,457 次,日均约 249 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gitkraken/shared-tools 还在维护吗?

最新版本 0.3.0 发布于 2026/10/07(1 个月前);至今共发布 6 个版本,其中过去 12 个月发布了 6 个;首次发布于 2026/04/24。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。