@git-stunts/git-cas 2.0.0 → 3.1.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.
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Animated progress bar for store/restore operations.
3
+ * Wires CasService EventEmitter events to a bijou progress bar on stderr.
4
+ */
5
+
6
+ import { statSync } from 'node:fs';
7
+ import { createAnimatedProgressBar } from '@flyingrobots/bijou';
8
+ import { getCliContext } from './context.js';
9
+
10
+ /**
11
+ * Format bytes as human-readable string.
12
+ */
13
+ function formatBytes(bytes) {
14
+ if (bytes < 1024) {
15
+ return `${bytes} B`;
16
+ }
17
+ if (bytes < 1024 * 1024) {
18
+ return `${(bytes / 1024).toFixed(1)} KiB`;
19
+ }
20
+ if (bytes < 1024 * 1024 * 1024) {
21
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
22
+ }
23
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GiB`;
24
+ }
25
+
26
+ /**
27
+ * Create a progress tracker for store operations.
28
+ *
29
+ * @param {Object} options
30
+ * @param {string} options.filePath - Path to the file being stored.
31
+ * @param {number} options.chunkSize - Chunk size in bytes.
32
+ * @param {boolean} [options.quiet] - Suppress all progress output.
33
+ * @returns {{ attach(service: EventEmitter): void, detach(): void }}
34
+ */
35
+ export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: providedSize }) {
36
+ if (quiet) {
37
+ return { attach() {}, detach() {} };
38
+ }
39
+
40
+ const ctx = getCliContext();
41
+ if (ctx.mode === 'pipe') {
42
+ return { attach() {}, detach() {} };
43
+ }
44
+
45
+ const fileSize = providedSize ?? statSync(filePath).size;
46
+ const totalChunks = fileSize === 0 ? 0 : Math.ceil(fileSize / chunkSize);
47
+
48
+ if (totalChunks === 0) {
49
+ return { attach() {}, detach() {} };
50
+ }
51
+
52
+ return createProgressTracker({ ctx, totalChunks, event: 'chunk:stored', label: 'Storing' });
53
+ }
54
+
55
+ /**
56
+ * Create a progress tracker for restore operations.
57
+ *
58
+ * @param {Object} options
59
+ * @param {number} options.totalChunks - Number of chunks to restore.
60
+ * @param {boolean} [options.quiet] - Suppress all progress output.
61
+ * @returns {{ attach(service: EventEmitter): void, detach(): void }}
62
+ */
63
+ export function createRestoreProgress({ totalChunks, quiet }) {
64
+ if (quiet || totalChunks === 0) {
65
+ return { attach() {}, detach() {} };
66
+ }
67
+
68
+ const ctx = getCliContext();
69
+ if (ctx.mode === 'pipe') {
70
+ return { attach() {}, detach() {} };
71
+ }
72
+
73
+ return createProgressTracker({ ctx, totalChunks, event: 'chunk:restored', label: 'Restoring' });
74
+ }
75
+
76
+ /**
77
+ * Internal: builds the progress tracker object.
78
+ */
79
+ function createProgressTracker({ ctx, totalChunks, event, label }) {
80
+ const width = Math.min(40, (ctx.runtime.columns || 80) - 30);
81
+ const bar = createAnimatedProgressBar({ width, showPercent: false, ctx });
82
+
83
+ let chunksProcessed = 0;
84
+ let bytesProcessed = 0;
85
+ let startTime = null;
86
+ let service = null;
87
+ let handler = null;
88
+
89
+ function onChunk({ size }) {
90
+ if (!startTime) {
91
+ startTime = Date.now();
92
+ }
93
+ chunksProcessed++;
94
+ bytesProcessed += size;
95
+
96
+ const pct = (chunksProcessed / totalChunks) * 100;
97
+ const elapsed = (Date.now() - startTime) / 1000;
98
+ const throughput = elapsed > 0 ? bytesProcessed / elapsed : 0;
99
+
100
+ if (ctx.mode === 'interactive') {
101
+ const status = ` ${label} ${chunksProcessed}/${totalChunks} ${formatBytes(throughput)}/s `;
102
+ process.stderr.write(`\r\x1b[K${status}`);
103
+ bar.update(pct);
104
+ } else if (chunksProcessed === 1 || chunksProcessed === totalChunks || chunksProcessed % 10 === 0) {
105
+ ctx.io.write(`${label} ${chunksProcessed}/${totalChunks} ${Math.round(pct)}%\n`);
106
+ }
107
+ }
108
+
109
+ return {
110
+ attach(svc) {
111
+ service = svc;
112
+ handler = onChunk;
113
+ bar.start();
114
+ service.on(event, handler);
115
+ },
116
+ detach() {
117
+ if (service && handler) {
118
+ service.removeListener(event, handler);
119
+ }
120
+ const elapsed = startTime ? (Date.now() - startTime) / 1000 : 0;
121
+ const throughput = elapsed > 0 ? bytesProcessed / elapsed : 0;
122
+ const msg = ` ${label} ${chunksProcessed}/${totalChunks} done ${formatBytes(throughput)}/s`;
123
+ bar.stop(msg);
124
+ },
125
+ };
126
+ }
package/index.d.ts CHANGED
@@ -45,11 +45,32 @@ export declare class GitPersistencePortBase {
45
45
  ): Promise<Array<{ mode: string; type: string; oid: string; name: string }>>;
46
46
  }
47
47
 
48
+ /** Abstract port for Git ref and commit operations. */
49
+ export declare class GitRefPortBase {
50
+ resolveRef(ref: string): Promise<string>;
51
+ resolveTree(commitOid: string): Promise<string>;
52
+ createCommit(options: {
53
+ treeOid: string;
54
+ parentOid?: string | null;
55
+ message: string;
56
+ }): Promise<string>;
57
+ updateRef(options: {
58
+ ref: string;
59
+ newOid: string;
60
+ expectedOldOid?: string | null;
61
+ }): Promise<void>;
62
+ }
63
+
48
64
  /** Git-backed implementation of the persistence port. */
49
65
  export declare class GitPersistenceAdapter extends GitPersistencePortBase {
50
66
  constructor(options: { plumbing: unknown; policy?: unknown });
51
67
  }
52
68
 
69
+ /** Git-backed implementation of the ref port. */
70
+ export declare class GitRefAdapter extends GitRefPortBase {
71
+ constructor(options: { plumbing: unknown; policy?: unknown });
72
+ }
73
+
53
74
  /** Node.js crypto implementation of CryptoPort. */
54
75
  export declare class NodeCryptoAdapter extends CryptoPortBase {
55
76
  constructor();
@@ -82,11 +103,95 @@ export interface ContentAddressableStoreOptions {
82
103
  merkleThreshold?: number;
83
104
  }
84
105
 
106
+ /** A single vault entry. */
107
+ export interface VaultEntry {
108
+ slug: string;
109
+ treeOid: string;
110
+ }
111
+
112
+ /** Vault metadata stored in .vault.json. */
113
+ export interface VaultMetadata {
114
+ version: number;
115
+ encryption?: {
116
+ cipher: string;
117
+ kdf: {
118
+ algorithm: string;
119
+ salt: string;
120
+ iterations?: number;
121
+ cost?: number;
122
+ blockSize?: number;
123
+ parallelization?: number;
124
+ keyLength: number;
125
+ };
126
+ };
127
+ }
128
+
129
+ /** Internal vault state returned by VaultService.readState(). */
130
+ export interface VaultState {
131
+ entries: Map<string, string>;
132
+ parentCommitOid: string | null;
133
+ metadata: VaultMetadata | null;
134
+ }
135
+
136
+ /**
137
+ * Domain service for vault (GC-safe ref-based asset index) operations.
138
+ */
139
+ export declare class VaultService {
140
+ static VAULT_REF: string;
141
+
142
+ constructor(options: {
143
+ persistence: GitPersistencePortBase;
144
+ ref: GitRefPortBase;
145
+ crypto: CryptoPortBase;
146
+ });
147
+
148
+ /** Validates a vault slug. Throws CasError with code INVALID_SLUG on failure. */
149
+ validateSlug(slug: string): void;
150
+
151
+ /** Reads the current vault state from refs/cas/vault. */
152
+ readState(): Promise<VaultState>;
153
+
154
+ /** Writes a new vault commit and updates the ref atomically. */
155
+ writeCommit(options: {
156
+ entries: Map<string, string>;
157
+ metadata: VaultMetadata;
158
+ parentCommitOid: string | null;
159
+ message: string;
160
+ }): Promise<{ commitOid: string }>;
161
+
162
+ /** Initializes the vault, optionally with encryption. */
163
+ initVault(options?: {
164
+ passphrase?: string;
165
+ kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
166
+ }): Promise<{ commitOid: string }>;
167
+
168
+ /** Adds or updates an entry in the vault. */
169
+ addToVault(options: {
170
+ slug: string;
171
+ treeOid: string;
172
+ force?: boolean;
173
+ }): Promise<{ commitOid: string }>;
174
+
175
+ /** Lists all vault entries sorted by slug. */
176
+ listVault(): Promise<VaultEntry[]>;
177
+
178
+ /** Removes an entry from the vault. */
179
+ removeFromVault(options: {
180
+ slug: string;
181
+ }): Promise<{ commitOid: string; removedTreeOid: string }>;
182
+
183
+ /** Resolves a vault entry slug to its tree OID. */
184
+ resolveVaultEntry(options: { slug: string }): Promise<string>;
185
+
186
+ /** Returns the vault metadata, or null if no vault exists. */
187
+ getVaultMetadata(): Promise<VaultMetadata | null>;
188
+ }
189
+
85
190
  /**
86
191
  * High-level facade for the Content Addressable Store library.
87
192
  *
88
- * Wraps CasService with lazy initialization, runtime-adaptive crypto
89
- * selection, and convenience helpers for file I/O.
193
+ * Wraps CasService and VaultService with lazy initialization, runtime-adaptive
194
+ * crypto selection, and convenience helpers for file I/O.
90
195
  */
91
196
  export default class ContentAddressableStore {
92
197
  constructor(options: ContentAddressableStoreOptions);
@@ -94,6 +199,7 @@ export default class ContentAddressableStore {
94
199
  get chunkSize(): number;
95
200
 
96
201
  getService(): Promise<CasService>;
202
+ getVaultService(): Promise<VaultService>;
97
203
 
98
204
  static createJson(options: {
99
205
  plumbing: unknown;
@@ -166,4 +272,29 @@ export default class ContentAddressableStore {
166
272
  }): Promise<{ referenced: Set<string>; total: number }>;
167
273
 
168
274
  deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;
275
+
276
+ // Vault — delegates to VaultService
277
+
278
+ static VAULT_REF: string;
279
+
280
+ initVault(options?: {
281
+ passphrase?: string;
282
+ kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
283
+ }): Promise<{ commitOid: string }>;
284
+
285
+ addToVault(options: {
286
+ slug: string;
287
+ treeOid: string;
288
+ force?: boolean;
289
+ }): Promise<{ commitOid: string }>;
290
+
291
+ listVault(): Promise<VaultEntry[]>;
292
+
293
+ removeFromVault(options: {
294
+ slug: string;
295
+ }): Promise<{ commitOid: string; removedTreeOid: string }>;
296
+
297
+ resolveVaultEntry(options: { slug: string }): Promise<string>;
298
+
299
+ getVaultMetadata(): Promise<VaultMetadata | null>;
169
300
  }
package/index.js CHANGED
@@ -6,7 +6,9 @@
6
6
  import { createReadStream, writeFileSync } from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import CasService from './src/domain/services/CasService.js';
9
+ import VaultService from './src/domain/services/VaultService.js';
9
10
  import GitPersistenceAdapter from './src/infrastructure/adapters/GitPersistenceAdapter.js';
11
+ import GitRefAdapter from './src/infrastructure/adapters/GitRefAdapter.js';
10
12
  import NodeCryptoAdapter from './src/infrastructure/adapters/NodeCryptoAdapter.js';
11
13
  import Manifest from './src/domain/value-objects/Manifest.js';
12
14
  import Chunk from './src/domain/value-objects/Chunk.js';
@@ -16,7 +18,9 @@ import CborCodec from './src/infrastructure/codecs/CborCodec.js';
16
18
 
17
19
  export {
18
20
  CasService,
21
+ VaultService,
19
22
  GitPersistenceAdapter,
23
+ GitRefAdapter,
20
24
  NodeCryptoAdapter,
21
25
  CryptoPort,
22
26
  Manifest,
@@ -44,8 +48,8 @@ async function getDefaultCryptoAdapter() {
44
48
  /**
45
49
  * High-level facade for the Content Addressable Store library.
46
50
  *
47
- * Wraps {@link CasService} with lazy initialization, runtime-adaptive crypto
48
- * selection, and convenience helpers for file I/O.
51
+ * Wraps {@link CasService} and {@link VaultService} with lazy initialization,
52
+ * runtime-adaptive crypto selection, and convenience helpers for file I/O.
49
53
  */
50
54
  export default class ContentAddressableStore {
51
55
  /**
@@ -68,6 +72,8 @@ export default class ContentAddressableStore {
68
72
  this.#servicePromise = null;
69
73
  }
70
74
 
75
+ /** @type {VaultService|null} */
76
+ #vault = null;
71
77
  #servicePromise = null;
72
78
 
73
79
  /**
@@ -83,7 +89,7 @@ export default class ContentAddressableStore {
83
89
  }
84
90
 
85
91
  /**
86
- * Constructs the persistence adapter, resolves crypto, and creates the CasService.
92
+ * Constructs adapters, resolves crypto, and creates CasService + VaultService.
87
93
  * @private
88
94
  * @returns {Promise<CasService>}
89
95
  */
@@ -100,9 +106,26 @@ export default class ContentAddressableStore {
100
106
  crypto,
101
107
  merkleThreshold: this.merkleThresholdConfig,
102
108
  });
109
+
110
+ const ref = new GitRefAdapter({
111
+ plumbing: this.plumbing,
112
+ policy: this.policyConfig,
113
+ });
114
+ this.#vault = new VaultService({ persistence, ref, crypto });
115
+
103
116
  return this.service;
104
117
  }
105
118
 
119
+ /**
120
+ * Lazily initializes and returns the underlying {@link VaultService}.
121
+ * @private
122
+ * @returns {Promise<VaultService>}
123
+ */
124
+ async #getVault() {
125
+ await this.#getService();
126
+ return this.#vault;
127
+ }
128
+
106
129
  /**
107
130
  * Lazily initializes and returns the underlying {@link CasService}.
108
131
  * @returns {Promise<CasService>}
@@ -111,6 +134,14 @@ export default class ContentAddressableStore {
111
134
  return await this.#getService();
112
135
  }
113
136
 
137
+ /**
138
+ * Lazily initializes and returns the underlying {@link VaultService}.
139
+ * @returns {Promise<VaultService>}
140
+ */
141
+ async getVaultService() {
142
+ return await this.#getVault();
143
+ }
144
+
114
145
  /**
115
146
  * Factory to create a CAS with JSON codec.
116
147
  * @param {Object} options
@@ -170,10 +201,6 @@ export default class ContentAddressableStore {
170
201
 
171
202
  /**
172
203
  * Reads a file from disk and stores it in Git as chunked blobs.
173
- *
174
- * Convenience wrapper that opens a read stream and delegates to
175
- * {@link CasService#store}.
176
- *
177
204
  * @param {Object} options
178
205
  * @param {string} options.filePath - Absolute or relative path to the file.
179
206
  * @param {string} options.slug - Logical identifier for the stored asset.
@@ -282,7 +309,6 @@ export default class ContentAddressableStore {
282
309
 
283
310
  /**
284
311
  * Returns deletion metadata for an asset stored in a Git tree.
285
- * Does not perform any destructive Git operations.
286
312
  * @param {Object} options
287
313
  * @param {string} options.treeOid - Git tree OID of the asset.
288
314
  * @returns {Promise<{ slug: string, chunksOrphaned: number }>}
@@ -294,7 +320,6 @@ export default class ContentAddressableStore {
294
320
 
295
321
  /**
296
322
  * Aggregates referenced chunk blob OIDs across multiple stored assets.
297
- * Analysis only — does not delete or modify anything.
298
323
  * @param {Object} options
299
324
  * @param {string[]} options.treeOids - Git tree OIDs to analyze.
300
325
  * @returns {Promise<{ referenced: Set<string>, total: number }>}
@@ -321,4 +346,46 @@ export default class ContentAddressableStore {
321
346
  const service = await this.#getService();
322
347
  return await service.deriveKey(options);
323
348
  }
349
+
350
+ // ---------------------------------------------------------------------------
351
+ // Vault — delegates to VaultService
352
+ // ---------------------------------------------------------------------------
353
+
354
+ static VAULT_REF = VaultService.VAULT_REF;
355
+
356
+ /** @see VaultService#initVault */
357
+ async initVault(options) {
358
+ const vault = await this.#getVault();
359
+ return vault.initVault(options);
360
+ }
361
+
362
+ /** @see VaultService#addToVault */
363
+ async addToVault(options) {
364
+ const vault = await this.#getVault();
365
+ return vault.addToVault(options);
366
+ }
367
+
368
+ /** @see VaultService#listVault */
369
+ async listVault() {
370
+ const vault = await this.#getVault();
371
+ return vault.listVault();
372
+ }
373
+
374
+ /** @see VaultService#removeFromVault */
375
+ async removeFromVault(options) {
376
+ const vault = await this.#getVault();
377
+ return vault.removeFromVault(options);
378
+ }
379
+
380
+ /** @see VaultService#resolveVaultEntry */
381
+ async resolveVaultEntry(options) {
382
+ const vault = await this.#getVault();
383
+ return vault.resolveVaultEntry(options);
384
+ }
385
+
386
+ /** @see VaultService#getVaultMetadata */
387
+ async getVaultMetadata() {
388
+ const vault = await this.#getVault();
389
+ return vault.getVaultMetadata();
390
+ }
324
391
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "2.0.0",
3
+ "version": "3.1.0",
4
4
  "description": "Content-addressed storage backed by Git's object database, with optional encryption and pluggable codecs",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -66,12 +66,21 @@
66
66
  "format": "prettier --write ."
67
67
  },
68
68
  "dependencies": {
69
+ "@flyingrobots/bijou": "^0.2.0",
70
+ "@flyingrobots/bijou-node": "^0.2.0",
71
+ "@flyingrobots/bijou-tui": "^0.2.0",
69
72
  "@git-stunts/alfred": "^0.10.0",
70
73
  "@git-stunts/plumbing": "^2.8.0",
71
74
  "cbor-x": "^1.6.0",
72
75
  "commander": "^14.0.3",
73
76
  "zod": "^3.24.1"
74
77
  },
78
+ "pnpm": {
79
+ "onlyBuiltDependencies": [
80
+ "cbor-extract",
81
+ "esbuild"
82
+ ]
83
+ },
75
84
  "devDependencies": {
76
85
  "@eslint/js": "^9.17.0",
77
86
  "eslint": "^9.17.0",