Pierre Git Storage SDK for TypeScript/JavaScript applications.
End-to-End Smoke Test
node packages/git-storage-sdk/tests/full-workflow.js -e production -s pierre -k /home/ian/pierre-prod-key.pem
Drives
the Pierre workflow via the SDK: creates a repository, writes commits, fetches
branch and diff data, and confirms storage APIs. Swap in your own private key
path when running outside this workstation and adjust -e/-s for
non-production environments.
Installation
npm install @pierre/storage
Usage
Basic Setup
import { GitStorage } from '@pierre/storage';// Initialize the client with your name and keyconst store = new GitStorage({ name: 'your-name', // e.g., 'v0' key:
'your-key'
,
// Your API key
});
You can also supply a pre-minted JWT instead of a key. The client then sends
that token on every request rather than signing a fresh one per call. The
token's own claims (repo, scopes, expiry) govern what the client can do, so
per-call options like permissions, ttl, and refPolicies are ignored.
const store = new GitStorage({ name: 'your-name', token: 'your-pre-minted-jwt', // e.g., issued by your backend for an end user});
Custom Fetch and Retries
Pass an optional fetch implementation to configure HTTP behavior for one client.
It must have the same signature as globalThis.fetch. The SDK uses it for all
HTTP requests, including file/archive downloads and streaming commit uploads.
createClient and CodeStorage accept the same option. If omitted, the SDK uses
the global fetch implementation and does not retry requests automatically.
For example, this wrapper retries a read once on HTTP 503:
Choose retry limits, backoff, and Retry-After handling for your application.
Preserve request headers, body, and abort signal in your wrapper. A failed write
can have succeeded on the server, so do not retry writes unless replay is safe.
Streaming bodies used by createCommit().send() and createCommitFromDiff() are
one-shot: a retry wrapper must not reuse a consumed body. The SDK does not buffer
or replay uploads. This option does not affect Git CLI traffic to generated remote
URLs.
Creating a Repository
// Create a new repository with auto-generated IDconst repo = await store.createRepo();console.log(repo.id); // e.g., '123e4567-e89b-12d3-a456-426614174000'// Create a repository with custom IDconst customRepo = await store.createRepo({ id: 'my-custom-repo' });console.log(customRepo.id); // 'my-custom-repo'// Create a repository by forking an existing repoconst forkedRepo = await store.createRepo({ id: 'my-fork', // optional baseRepo: { id: 'my-template-id', ref: 'main', // optional },});// If defaultBranch is omitted, the SDK returns "main".// Create a repo synced to a public GitHub repository without app authconst publicSyncRepo = await store.createRepo({ baseRepo: { owner: 'octocat', name: 'Hello-World', auth: { authType: 'public' }, },});
deploy creates and polls until the deployment reaches ready (2s interval,
10m end-to-end timeout by default). It throws DeploymentFailedError on
error or canceled, and a DOMException named TimeoutError when the
budget expires. createDeployment returns immediately with the current
state. Reuse the same idempotency key when retrying a create request. The SDK
mints the required repository and deployment scopes automatically.
Manage the production domain separately from the deployment list:
const domain = await repo.getDeploymentDomain();console.log(domain.effectiveUrl);const pending = await repo.setDeploymentDomain({ hostname: 'www.example.com' });console.log(pending.records); // Publish and retain these DNS records.const updated = await repo.getDeploymentDomain(); // Check status after configuring DNS.// To remove the custom hostname:const managed = await repo.deleteDeploymentDomain();
Domain methods use /api/repos/{repo_name}/domain. Reads require
deployment:read; set/delete require deployment:write. Setting returns
202 while verification proceeds. Status is pending_verification,
pending_dns, ready, error, or unknown; future values pass through.
effectiveUrl is the custom URL once ready, otherwise the managed
https://<project>-<tenant>.code.host URL, which remains available.
DNS records contain type, name (relative to the apex zone), and value.
getDeploymentDomain returns an ApiError with status 404 if no hosting
project exists. If deletion returns 503, retry deletion after the
Retry-After delay in error.headers; cleanup has not finished.
All domain methods accept ttl and an abort signal.
Getting Remote URLs
The SDK generates secure URLs with JWT authentication for Git operations:
// Get URL with default permissions (git:write, git:read) and 1-year TTLconst url = await repo.getRemoteURL();// Returns: https://t:JWT@your-name.code.storage/repo-id.git// Configure the Git remoteconsole.log(`Run: git remote add origin ${url}`);// Get URL with custom permissions and TTLconst readOnlyUrl = await repo.getRemoteURL({ permissions: ['git:read'], // Read-only access ttl: 3600, // 1 hour in seconds});// Available permissions:// - 'git:read' - Read access to Git repository// - 'git:write' - Write access to Git repository// - 'repo:write' - Create a repository
Ephemeral Branches
For working with ephemeral branches (temporary branches isolated from the main
repository), use getEphemeralRemoteURL():
// Get ephemeral namespace remote URLconst ephemeralUrl = await repo.getEphemeralRemoteURL();// Returns: https://t:JWT@your-name.code.storage/repo-id+ephemeral.git// Configure separate remotes for default and ephemeral branchesconsole.log(`Run: git remote add origin ${await repo.getRemoteURL()}`);console.log( `Run: git remote add ephemeral ${await repo.getEphemeralRemoteURL()}`);// Push ephemeral branch// git push ephemeral feature-branch// The ephemeral remote supports all the same options and permission as regular remotes
Import Remote
For write-only history imports, use getImportRemoteURL():
// Get import remote URLconst importUrl = await repo.getImportRemoteURL();// Returns: https://t:JWT@your-name.code.storage/repo-id+import.gitconsole.log(`Run: git remote add import ${importUrl}`);// Push imported history through the import remote// git push import main// Reads are disabled on +import remotes; use the repository remote for clone/fetch
Working with Repository Content
Once you have a repository instance, you can perform various Git operations:
const repo = await store.createRepo();// orconst repo = await store.findOne({ id: 'existing-repo-id' });// List repositories for the orgconst repos = await store.listRepos({ limit: 20 });console.log(repos.repos);// Get file content (streaming)const resp = await repo.getFileStream({ path: 'README.md', ref: 'main', // optional, defaults to default branch});const text = await resp.text();console.log(text);// Fetch metadata or validate cached/ranged content without a bodyconst meta = await repo.headFile({ path: 'README.md', ref: 'main', headers: { ifNoneMatch: '"b10b5ha"', range: 'bytes=0-1023', },});console.log(meta.status, meta.etag, meta.contentRange);// Download repository archive (streaming tar.gz)const archiveResp = await repo.getArchiveStream({ ref: 'main', includeGlobs: ['README.md'], excludeGlobs: ['vendor/**'], maxBlobSize: 1024 * 1024, // optional max file size in bytes archivePrefix: 'repo/',});const archiveBytes = new Uint8Array(await archiveResp.arrayBuffer());console.log(archiveBytes.length);// List all files in the repositoryconst files = await repo.listFiles({ ref: 'main', // optional, defaults to default branch});console.log(files.paths); // Array of file paths// List files with mode/size and last commit metadataconst metadata = await repo.listFilesWithMetadata({ ref: 'main',});console.log(metadata.files[0].lastCommitSha);console.log(metadata.commits[metadata.files[0].lastCommitSha].author);// List branchesconst branches = await repo.listBranches({ limit: 10, cursor: undefined, // for pagination});console.log(branches.branches);// List tagsconst tags = await repo.listTags({ limit: 10, cursor: undefined, // for pagination});console.log(tags.tags);// Create a lightweight tag at a commit SHAconst createdTag = await repo.createTag({ name: 'v1.0.0', target: '0123456789abcdef0123456789abcdef01234567',});console.log(createdTag.message);// Delete a tagconst deletedTag = await repo.deleteTag({ name: 'v1.0.0' });console.log(deletedTag.message);// List commitsconst commits = await repo.listCommits({ branch: 'main', // optional limit: 20, cursor: undefined, // for pagination});console.log(commits.commits);console.log(commits.commits[0]?.parentShas); // Git parent order; [] for a root commit// Get a single commit's metadata (no diff)const { commit } = await repo.getCommit({ sha: 'abc123...' });console.log(commit.message, commit.authorName, commit.parentShas);// Signed commits also expose the armored signature plus the exact signed// payload (raw commit object minus the gpgsig header) so you can verify it// yourself. Both are undefined for unsigned commits.if (commit.signature) { console.log(commit.signature, commit.payload);}// Blame a file (per-line authorship). The top-level `commitSha` is the SHA the// `ref` resolved to; each entry in `lines` carries its own author/committer// metadata inline.const blame = await repo.getBlame({ path: 'src/main.go', ref: 'main', ranges: ['10,30'], detectMoves: true,});for (const line of blame.lines) { console.log(`${line.lineNumber} (${line.commitSha.slice(0, 7)}): ${line.authorName} — ${line.summary}`);}// Read a git note for a commitconst note = await repo.getNote({ sha: 'abc123...' });console.log(note.note);// Add a git noteconst noteResult = await repo.createNote({ sha: 'abc123...', note: 'Release QA approved', author: { name: 'Release Bot', email: 'release@example.com' },});console.log(noteResult.newRefSha);// Append to an existing git noteawait repo.appendNote({ sha: 'abc123...', note: 'Follow-up review complete',});// Delete a git noteawait repo.deleteNote({ sha: 'abc123...' });// Notes default to refs/notes/commits. Pass `ref` to target another notes ref;// a bare name like `reviews` is placed under refs/notes/ (a fully-qualified// refs/notes/* ref also works). Custom refs must be enabled server-side.await repo.createNote({ sha: 'abc123...', note: 'LGTM', ref: 'reviews',});const reviewNote = await repo.getNote({ sha: 'abc123...', ref: 'reviews' });// Discover custom notes namespaces with cursor pagination. Requires the custom// notes refs feature to be enabled server-side.const notesRefs = await repo.listNotesRefs({ prefix: 'reviews/', limit: 20 });for (const entry of notesRefs.refs) { console.log(entry.ref, entry.sha);}if (notesRefs.hasMore) { await repo.listNotesRefs({ prefix: 'reviews/', cursor: notesRefs.nextCursor });}// Get branch diffconst branchDiff = await repo.getBranchDiff({ branch: 'feature-branch', base: 'main', // optional, defaults to main});console.log(branchDiff.stats);console.log(branchDiff.files);console.log(branchDiff.mergeBaseSha);// Get commit diffconst commitDiff = await repo.getCommitDiff({ sha: 'abc123...', baseSha: 'def456...', // optional base commit gitApplyCompatible: true, // generate raw diffs for use with git apply});console.log(commitDiff.stats);console.log(commitDiff.files);console.log(commitDiff.sha, commitDiff.baseSha, commitDiff.mergeBaseSha);// Create a new branch from an existing refconst branch = await repo.createBranch({ baseRef: 'refs/heads/main', targetBranch: 'feature/demo', // baseIsEphemeral: true, // targetIsEphemeral: true,});console.log(branch.targetBranch, branch.commitSha);// Delete a branch (default branch deletion is rejected)const deletedBranch = await repo.deleteBranch({ name: 'feature/demo' });console.log(deletedBranch.message);// Pass `ephemeral: true` to delete a branch from the ephemeral namespaceconst ephemeralDelete = await repo.deleteBranch({ name: 'merge/123e4567-e89b-12d3-a456-426614174000', ephemeral: true,});console.log(ephemeralDelete.ephemeral); // true// `baseBranch` is still accepted for backwards compatibility, but deprecated.// Prefer `baseRef` for new code.// Preview whether a source branch can merge into a target branch without// creating commits or updating refs. Pass includeContent to receive bounded// conflict blob content when the preview is conflicted.const preview = await repo.previewMerge({ sourceBranch: 'feature/demo', targetBranch: 'main', includeContent: true,});console.log(preview.status, preview.result);console.log(preview.conflictPaths, preview.conflicts, preview.filteredConflicts);// Merge one branch into another. Source and target can independently be// ephemeral branches.const mergeResult = await repo.merge({ sourceBranch: 'feature/demo', sourceIsEphemeral: true, targetBranch: 'main', targetIsEphemeral: false, expectedTargetSha: '0123456789abcdef0123456789abcdef01234567', // optional; 409 if target moved strategy: 'merge', // 'merge' | 'ff_only' | 'ff_prefer' commitMessage: 'Merge feature/demo', // optional author: { name: 'Merge Bot', email: 'merge@example.com' }, // optional committer: { name: 'Merge Bot', email: 'merge@example.com' }, // optional allowUnrelatedHistories: false, // optional squash: false, // optional; incompatible with ff_only});console.log(mergeResult.result); // 'merge_commit', 'fast_forward', 'no_op', 'squash', or 'unknown'console.log(mergeResult.commitSha, mergeResult.target.newSha);// repo.merge() requires sourceBranch, targetBranch, and strategy. It returns// camelCase metadata for the source tip, target update, merge base (when// reported), and number of promoted commits. A backend conflict response// (HTTP 409) is surfaced as an API error with the response body preserved for// callers that need conflict_paths or merge_base_sha.// Target-tip modes:// - Provide expectedTargetSha when targetBranch must still point at that commit.// - Omit expectedTargetSha to merge into the current target tip. For native// Code Storage targets, the gateway may retry stale target/repository// movement internally while keeping the resolved source commit pinned.// Create a commit using the streaming helperconst fs = await import('node:fs/promises');const result = await repo .createCommit({ targetBranch: 'main', commitMessage: 'Update docs', author: { name: 'Docs Bot', email: 'docs@example.com' }, }) .addFileFromString('docs/changelog.md', '# v2.0.2\n- add streaming SDK\n') .addFile('docs/readme.md', await fs.readFile('README.md')) .deletePath('docs/legacy.txt') .send();console.log(result.commitSha);console.log(result.refUpdate.newSha);console.log(result.refUpdate.oldSha); // All zeroes when the ref is created
The builder exposes:
addFile(path, source, options) to attach bytes from strings, typed arrays,
ArrayBuffers, Blob or File objects, ReadableStreams, or
iterable/async-iterable sources.
addFileFromString(path, contents, options) for text helpers (defaults to
UTF-8 and accepts any Node.js BufferEncoding).
deletePath(path) to remove files or folders.
send() to finalize the commit and receive metadata about the new commit.
send() resolves to an object with the new commit metadata plus the ref update:
type CommitResult = { commitSha: string; treeSha: string; targetBranch: string; packBytes: number; blobCount: number; refUpdate: { branch: string; oldSha: string; // All zeroes when the ref is created newSha: string; };};
If the backend reports a failure (for example, the branch advanced past
expectedHeadSha) the builder throws a RefUpdateError containing the status,
reason, and ref details.
Options
targetBranch (required): Branch name (for example main) that will receive
the commit.
expectedHeadSha (optional): Commit SHA that must match the remote tip; omit
to fast-forward unconditionally.
baseBranch (optional): Mirrors the base_branch metadata and names an
existing branch whose tip should seed targetBranch if it does not exist.
Leave expectedHeadSha empty when creating a new branch from baseBranch;
when both are provided and the branch already exists, expectedHeadSha
continues to enforce the fast-forward guard.
commitMessage (required): The commit message.
author (required): Include name and email for the commit author.
committer (optional): Include name and email. If omitted, the author
identity is reused.
signal (optional): Abort an in-flight upload with AbortController.
targetRef (deprecated, optional): Fully qualified ref (for example
refs/heads/main). Prefer targetBranch, which now accepts plain branch
names.
Files are chunked into 4 MiB segments under the hood, so you can stream large
assets without buffering them entirely in memory. File paths are normalized
relative to the repository root.
The targetBranch must already exist on the remote repository unless you
provide baseBranch (or the repository has no refs). To seed an empty
repository, point to the default branch and omit expectedHeadSha. To create
a missing branch within an existing repository, set baseBranch to the source
branch and omit expectedHeadSha so the service clones that tip before
applying your changes.
Apply a pre-generated diff
If you already have a patch (for example, the output of git diff --binary) you
can stream it to the gateway with a single call. The SDK handles chunking and
NDJSON streaming just like it does for regular commits:
The diff field accepts a string, Uint8Array, ArrayBuffer, Blob,
File, ReadableStream, iterable, or async iterable of byte chunks—the same
sources supported by the standard commit builder. createCommitFromDiff returns
a Promise<CommitResult> and throws a RefUpdateError when the server rejects
the diff (for example, if the branch tip changed).
Streaming Large Files
The commit builder accepts any async iterable of bytes, so you can stream large
assets without buffering:
The SDK uses JWT (JSON Web Tokens) for authentication. When you call
getRemoteURL(), it:
Creates a JWT with your name, repository ID, and requested permissions
Signs it with your key
Embeds it in the Git remote URL as the password
The generated URLs are compatible with standard Git clients and include all
necessary authentication.
Error Handling
The SDK validates inputs and provides helpful error messages:
try { const store = new GitStorage({ name: '', key: 'key' });} catch (error) { // Error: GitStorage name must be a non-empty string.}try { const store = new GitStorage({ name: 'v0', key: '' });} catch (error) { // Error: GitStorage key must be a non-empty string.}-
Mutating operations (commit builder, restoreCommit) throw RefUpdateError
when the backend reports a ref failure. Inspect error.status,
error.reason, error.message, and error.refUpdate for details.