@feng0531/dsh-vcs 0.7.2 → 0.8.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.
Files changed (56) hide show
  1. package/README.md +69 -6
  2. package/amend-host.mjs +48 -0
  3. package/branch-create-host.mjs +42 -0
  4. package/branch-create-preview.mjs +196 -0
  5. package/branch-delete-preview.mjs +214 -0
  6. package/branch-switch-host.mjs +13 -33
  7. package/commit-host.mjs +49 -0
  8. package/commit-object-publish.mjs +123 -0
  9. package/commit-preview.mjs +335 -0
  10. package/confirmed-operation.mjs +50 -0
  11. package/dist/client.js +2 -2
  12. package/dist/frontend.json +1 -1
  13. package/dist/interface.js +2 -2
  14. package/docs/RELEASING.md +7 -5
  15. package/git-blob-store.mjs +151 -0
  16. package/git-branch-create.mjs +156 -0
  17. package/git-branch-delete.mjs +175 -0
  18. package/git-lightweight-tag-create.mjs +181 -0
  19. package/git-object-store.mjs +162 -0
  20. package/git-ref-cas.mjs +119 -0
  21. package/git-tag-create.mjs +186 -0
  22. package/index-change-host.mjs +19 -0
  23. package/index-change.mjs +418 -0
  24. package/index-lock.mjs +231 -0
  25. package/index-stage-host.mjs +19 -0
  26. package/index.mjs +301 -4
  27. package/latest-commit.mjs +109 -0
  28. package/lightweight-tag-host.mjs +42 -0
  29. package/lightweight-tag-preview.mjs +183 -0
  30. package/line-index-host.mjs +58 -0
  31. package/locale/en.json +1 -1
  32. package/locale/zh.json +1 -1
  33. package/package.json +48 -3
  34. package/partial-stage-host.mjs +52 -0
  35. package/partial-unstage-host.mjs +52 -0
  36. package/src/amend-plan.mjs +74 -0
  37. package/src/branch-delete-plan.mjs +113 -0
  38. package/src/commit-plan.mjs +78 -0
  39. package/src/git-commit-object.mjs +99 -0
  40. package/src/git-index.mjs +113 -0
  41. package/src/git-tag-object.mjs +110 -0
  42. package/src/index-tree.mjs +77 -0
  43. package/src/lightweight-tag-plan.mjs +64 -0
  44. package/src/line-index.mjs +168 -0
  45. package/src/partial-index.mjs +199 -0
  46. package/src/reflog.mjs +33 -0
  47. package/src/settled-reads.mjs +5 -0
  48. package/src/verified-branch-delete-plan.mjs +95 -0
  49. package/src/verified-commit-metadata.mjs +57 -0
  50. package/src/verified-commit-plan.mjs +49 -0
  51. package/src/verified-commit.mjs +84 -0
  52. package/src/verified-tag-plan.mjs +72 -0
  53. package/tag-create-host.mjs +31 -0
  54. package/tag-create-preview.mjs +215 -0
  55. package/tag-object-publish.mjs +49 -0
  56. package/vcs.mjs +29 -0
@@ -0,0 +1,168 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {createPartialIndexPlan, MAX_PARTIAL_INDEX_BYTES} from './partial-index.mjs';
3
+
4
+ export const LINE_INDEX_ALGORITHM = 'raw-line-selection-v1';
5
+
6
+ function checkAbort(signal) {
7
+ if (signal?.aborted) {
8
+ const error = new Error('Line index operation aborted');
9
+ error.name = 'AbortError';
10
+ throw error;
11
+ }
12
+ }
13
+
14
+ const hash = value => createHash('sha256').update(value).digest('hex');
15
+
16
+ /** Pure Buffer model, using partial-index's bounded EXACT raw-line alignment.
17
+ * All coordinates and unitOffset values are zero-based. Operations are ordered
18
+ * by source unit, then deletes in before order, then inserts in after order.
19
+ * IDs bind both complete raw inputs, the complete source unit, direction, and
20
+ * line offset. BOM and terminators are data, never normalized or synthesized.
21
+ * Limits/UTF-8/control policy are exactly those of createPartialIndexPlan.
22
+ * The complete plan (including source units and operations) is deeply frozen.
23
+ */
24
+ export function createLineIndexPlan(before, after, {signal} = {}) {
25
+ const source = createPartialIndexPlan(before, after, {signal});
26
+ const id = hash(JSON.stringify([LINE_INDEX_ALGORITHM, source.id]));
27
+ const operations = [];
28
+ for (const unit of source.units) {
29
+ for (const kind of ['delete', 'insert']) {
30
+ const lines = kind === 'delete' ? unit.before : unit.after;
31
+ for (let unitOffset = 0; unitOffset < lines.length; unitOffset++) {
32
+ checkAbort(signal);
33
+ const line = lines[unitOffset];
34
+ const coordinate = kind === 'delete'
35
+ ? {beforeLine: unit.beforeStart + unitOffset}
36
+ : {afterLine: unit.afterStart + unitOffset};
37
+ operations.push(Object.freeze({
38
+ id: hash(JSON.stringify([id, unit.id, kind, unitOffset])),
39
+ kind, unitId: unit.id, unitOffset, ...coordinate,
40
+ text: line.text, terminator: line.terminator,
41
+ }));
42
+ }
43
+ }
44
+ }
45
+ checkAbort(signal);
46
+ return Object.freeze({...source, id, algorithm: LINE_INDEX_ALGORITHM,
47
+ sourceAlgorithm: source.algorithm, operations: Object.freeze(operations)});
48
+ }
49
+
50
+ // Inspect own data descriptors rather than invoking supplied getters. Accept a
51
+ // plain JSON copy or null-prototype object, not extra/symbol/hidden fields,
52
+ // accessors, sparse arrays, exotic prototypes, or altered canonical values.
53
+ function canonicalEqual(supplied, expected, signal) {
54
+ checkAbort(signal);
55
+ if (expected === null || typeof expected !== 'object') return Object.is(supplied, expected);
56
+ if (supplied === null || typeof supplied !== 'object' || Array.isArray(supplied) !== Array.isArray(expected)) return false;
57
+ const prototype = Object.getPrototypeOf(supplied);
58
+ if (Array.isArray(expected) ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) return false;
59
+ const keys = Reflect.ownKeys(expected);
60
+ if (Reflect.ownKeys(supplied).length !== keys.length) return false;
61
+ return keys.every(key => {
62
+ const descriptor = Object.getOwnPropertyDescriptor(supplied, key);
63
+ return descriptor && Object.hasOwn(descriptor, 'value') &&
64
+ descriptor.enumerable === Object.getOwnPropertyDescriptor(expected, key).enumerable &&
65
+ canonicalEqual(descriptor.value, expected[key], signal);
66
+ });
67
+ }
68
+
69
+ function selectionSet(operationIds, operations, signal) {
70
+ if (!Array.isArray(operationIds) || Object.getPrototypeOf(operationIds) !== Array.prototype) {
71
+ throw new TypeError('Selection must be an array of operation IDs');
72
+ }
73
+ const length = Object.getOwnPropertyDescriptor(operationIds, 'length').value;
74
+ if (length > operations.length || Reflect.ownKeys(operationIds).length !== length + 1) {
75
+ throw new TypeError('Invalid operation selection schema');
76
+ }
77
+ const known = new Set(operations.map(operation => operation.id)), selected = new Set();
78
+ for (let i = 0; i < length; i++) {
79
+ checkAbort(signal);
80
+ const descriptor = Object.getOwnPropertyDescriptor(operationIds, String(i));
81
+ if (!descriptor || !Object.hasOwn(descriptor, 'value') || !descriptor.enumerable) {
82
+ throw new TypeError('Invalid operation selection schema');
83
+ }
84
+ const id = descriptor.value;
85
+ if (typeof id !== 'string' || !known.has(id) || selected.has(id)) {
86
+ throw new TypeError('Unknown or duplicate operation ID');
87
+ }
88
+ selected.add(id);
89
+ }
90
+ return selected;
91
+ }
92
+
93
+ function snapshot(value, label) {
94
+ if (!Buffer.isBuffer(value)) throw new TypeError(label + ' must be a Buffer');
95
+ if (value.length > MAX_PARTIAL_INDEX_BYTES) throw new RangeError(label + ' exceeds 256 KiB');
96
+ return Buffer.from(value);
97
+ }
98
+
99
+ // Validated inputs only. Byte slices preserve equal gaps without re-encoding.
100
+ function rawLines(buffer, signal) {
101
+ const lines = [];
102
+ let start = 0;
103
+ for (let i = 0; i < buffer.length; i++) {
104
+ if ((i & 1023) === 0) checkAbort(signal);
105
+ if (buffer[i] !== 10 && buffer[i] !== 13) continue;
106
+ if (buffer[i] === 13 && buffer[i + 1] === 10) i++;
107
+ lines.push(buffer.subarray(start, i + 1));
108
+ start = i + 1;
109
+ }
110
+ if (start < buffer.length) lines.push(buffer.subarray(start));
111
+ return lines;
112
+ }
113
+
114
+ /** Recompute and validate the WHOLE canonical plan before applying selection.
115
+ * Each selected delete removes only its before token (text AND terminator).
116
+ * Unselected before tokens remain in original order. Selected after tokens are
117
+ * appended, in after order, AFTER those remaining before tokens in that source
118
+ * unit's insertion slot. There is no automatic delete/insert pair coupling.
119
+ * Equal raw gaps remain unchanged. Selection order has no effect.
120
+ *
121
+ * Candidate tokens must reparse to the exact selected raw-line sequence. A
122
+ * retained unterminated token before insertion, or CR + empty LF fusion, is
123
+ * rejected rather than silently merging lines or synthesizing delimiters.
124
+ * Interior BOM stays literal. None returns before; all returns after, exactly.
125
+ * Candidate bytes must still be <=256 KiB and <=4000 actual raw lines (counted
126
+ * AFTER joins), valid UTF-8, with the same control policy as the inputs. Invalid
127
+ * candidates throw explicitly, even when both source inputs meet the limits.
128
+ * Candidate self-validation needs no additional LCS alignment. No I/O or RPC.
129
+ */
130
+ export function applyLineIndexSelection(beforeBuffer, afterBuffer, plan, operationIds, {signal} = {}) {
131
+ checkAbort(signal);
132
+ const before = snapshot(beforeBuffer, 'before'), after = snapshot(afterBuffer, 'after');
133
+ const canonical = createLineIndexPlan(before, after, {signal});
134
+ if (!canonicalEqual(plan, canonical, signal)) throw new TypeError('Invalid or stale line index plan');
135
+ const selected = selectionSet(operationIds, canonical.operations, signal);
136
+ checkAbort(signal);
137
+ if (!selected.size) return Buffer.from(before);
138
+ if (selected.size === canonical.operations.length) return Buffer.from(after);
139
+ const left = rawLines(before, signal), right = rawLines(after, signal), chunks = [];
140
+ let cursor = 0, operationIndex = 0, bytes = 0;
141
+ function append(chunk) {
142
+ checkAbort(signal);
143
+ bytes += chunk.length;
144
+ if (bytes > MAX_PARTIAL_INDEX_BYTES) throw new RangeError('Candidate exceeds 256 KiB');
145
+ chunks.push(chunk);
146
+ }
147
+ for (const unit of canonical.units) {
148
+ while (cursor < unit.beforeStart) append(left[cursor++]);
149
+ for (let offset = 0; offset < unit.beforeCount; offset++) {
150
+ if (!selected.has(canonical.operations[operationIndex++].id)) append(left[cursor]);
151
+ cursor++;
152
+ }
153
+ for (let offset = 0; offset < unit.afterCount; offset++) {
154
+ if (selected.has(canonical.operations[operationIndex++].id)) append(right[unit.afterStart + offset]);
155
+ }
156
+ }
157
+ while (cursor < left.length) append(left[cursor++]);
158
+ const candidate = Buffer.concat(chunks, bytes);
159
+ const parsed = rawLines(candidate, signal);
160
+ if (parsed.length !== chunks.length || parsed.some((line, i) => !line.equals(chunks[i]))) {
161
+ throw new RangeError('Selected lines would merge raw line boundaries');
162
+ }
163
+ // Reuse fatal UTF-8/control/actual raw-line validation, without imposing a
164
+ // second diff-cell bound on synthetic candidates.
165
+ createPartialIndexPlan(candidate, candidate, {signal});
166
+ checkAbort(signal);
167
+ return candidate;
168
+ }
@@ -0,0 +1,199 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {TextDecoder} from 'node:util';
3
+
4
+ export const MAX_PARTIAL_INDEX_BYTES = 256 * 1024;
5
+ export const MAX_PARTIAL_INDEX_LINES = 4000;
6
+ export const MAX_PARTIAL_INDEX_LCS_CELLS = 200000;
7
+ export const PARTIAL_INDEX_ALGORITHM = 'raw-line-lcs-v1';
8
+
9
+ function checkAbort(signal) {
10
+ if (signal?.aborted) {
11
+ const error = new Error('Partial index operation aborted');
12
+ error.name = 'AbortError';
13
+ throw error;
14
+ }
15
+ }
16
+
17
+ function snapshot(value, label) {
18
+ if (!Buffer.isBuffer(value)) throw new TypeError(label + ' must be a Buffer');
19
+ if (value.length > MAX_PARTIAL_INDEX_BYTES) throw new RangeError(label + ' exceeds 256 KiB');
20
+ return Buffer.from(value);
21
+ }
22
+
23
+ function sha256(value) {
24
+ return createHash('sha256').update(value).digest('hex');
25
+ }
26
+
27
+ // No newline normalization, synthetic trailing line, or BOM removal. Strings
28
+ // re-encode losslessly because decoding is fatal and ignoreBOM preserves U+FEFF.
29
+ function tokenize(buffer, signal) {
30
+ for (let i = 0; i < buffer.length; i++) {
31
+ if ((i & 1023) === 0) checkAbort(signal);
32
+ const byte = buffer[i];
33
+ if ((byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) || byte === 127) {
34
+ throw new TypeError('Binary text is unsupported (NUL or ASCII control byte)');
35
+ }
36
+ }
37
+ let text;
38
+ try {
39
+ text = new TextDecoder('utf-8', {fatal: true, ignoreBOM: true}).decode(buffer);
40
+ } catch {
41
+ throw new TypeError('Partial index requires valid UTF-8');
42
+ }
43
+ const lines = [];
44
+ let start = 0;
45
+ function push(end, next, terminator) {
46
+ if (lines.length >= MAX_PARTIAL_INDEX_LINES) throw new RangeError('Input exceeds 4000 lines');
47
+ lines.push(Object.freeze({text: text.slice(start, end), terminator}));
48
+ start = next;
49
+ }
50
+ for (let i = 0; i < text.length; i++) {
51
+ if ((i & 1023) === 0) checkAbort(signal);
52
+ if (text[i] === '\r') {
53
+ const crlf = text[i + 1] === '\n';
54
+ push(i, i + (crlf ? 2 : 1), crlf ? 'CRLF' : 'CR');
55
+ if (crlf) i++;
56
+ } else if (text[i] === '\n') push(i, i + 1, 'LF');
57
+ }
58
+ if (start < text.length) push(text.length, text.length, 'NONE');
59
+ return lines;
60
+ }
61
+
62
+ function sameLine(a, b) {
63
+ return a.text === b.text && a.terminator === b.terminator;
64
+ }
65
+
66
+ function buildPlan(before, after, signal) {
67
+ checkAbort(signal);
68
+ const left = tokenize(before, signal), right = tokenize(after, signal);
69
+ const beforeHash = sha256(before), afterHash = sha256(after);
70
+ const id = sha256(JSON.stringify([PARTIAL_INDEX_ALGORITHM, beforeHash, afterHash]));
71
+ let prefix = 0, suffix = 0;
72
+ while (prefix < left.length && prefix < right.length && sameLine(left[prefix], right[prefix])) {
73
+ checkAbort(signal);
74
+ prefix++;
75
+ }
76
+ while (suffix < left.length - prefix && suffix < right.length - prefix &&
77
+ sameLine(left[left.length - suffix - 1], right[right.length - suffix - 1])) {
78
+ checkAbort(signal);
79
+ suffix++;
80
+ }
81
+ const n = left.length - prefix - suffix, m = right.length - prefix - suffix;
82
+ const lcsCells = n && m ? (n + 1) * (m + 1) : 0;
83
+ if (lcsCells > MAX_PARTIAL_INDEX_LCS_CELLS) throw new RangeError('Exact LCS exceeds 200000 cells');
84
+ const width = m + 1, dp = new Uint16Array(lcsCells);
85
+ for (let i = n - 1; i >= 0 && m; i--) {
86
+ checkAbort(signal);
87
+ for (let j = m - 1; j >= 0; j--) {
88
+ dp[i * width + j] = sameLine(left[prefix + i], right[prefix + j])
89
+ ? dp[(i + 1) * width + j + 1] + 1
90
+ : Math.max(dp[(i + 1) * width + j], dp[i * width + j + 1]);
91
+ }
92
+ }
93
+ const units = [];
94
+ let i = 0, j = 0, run = null;
95
+ function flush() {
96
+ if (!run) return;
97
+ const beforeStart = prefix + run.i, afterStart = prefix + run.j;
98
+ const beforeCount = i - run.i, afterCount = j - run.j;
99
+ const beforeLines = Object.freeze(left.slice(beforeStart, beforeStart + beforeCount));
100
+ const afterLines = Object.freeze(right.slice(afterStart, afterStart + afterCount));
101
+ const coordinates = [beforeStart, beforeCount, afterStart, afterCount];
102
+ const unitId = sha256(JSON.stringify([id, coordinates, beforeLines, afterLines]));
103
+ units.push(Object.freeze({id: unitId, beforeStart, beforeCount, afterStart, afterCount,
104
+ before: beforeLines, after: afterLines}));
105
+ run = null;
106
+ }
107
+ while (i < n || j < m) {
108
+ checkAbort(signal);
109
+ if (i < n && j < m && sameLine(left[prefix + i], right[prefix + j])) {
110
+ flush();
111
+ i++;
112
+ j++;
113
+ } else {
114
+ if (!run) run = {i, j};
115
+ // Deterministic ties delete first. Consecutive deletes/inserts form one
116
+ // atomic replacement; only an equal raw line separates edit units.
117
+ if (i < n && (j === m || dp[(i + 1) * width + j] >= dp[i * width + j + 1])) i++;
118
+ else j++;
119
+ }
120
+ }
121
+ flush();
122
+ checkAbort(signal);
123
+ return Object.freeze({id, algorithm: PARTIAL_INDEX_ALGORITHM, beforeHash, afterHash,
124
+ beforeBytes: before.length, afterBytes: after.length,
125
+ beforeLineCount: left.length, afterLineCount: right.length, lcsCells,
126
+ units: Object.freeze(units)});
127
+ }
128
+
129
+ /** Pure synchronous model; no filesystem, RPC, index mutation, or retained buffers.
130
+ * Starts are zero-based raw-line indices. Each unit's before/after arrays contain
131
+ * frozen {text, terminator: 'LF'|'CRLF'|'CR'|'NONE'} display tokens. A BOM stays
132
+ * in the first text token. Empty input has zero tokens, not a phantom line.
133
+ * Inputs: Buffers, <=256 KiB and <=4000 raw lines each, fatal UTF-8, no ASCII
134
+ * controls except TAB/LF/CR. Exact LCS after common prefix/suffix uses <=200000
135
+ * cells INCLUDING boundaries (zero cells for a one-sided middle); otherwise
136
+ * throws RangeError, never an approximate plan. Returns deeply frozen data.
137
+ */
138
+ export function createPartialIndexPlan(beforeBuffer, afterBuffer, {signal} = {}) {
139
+ const before = snapshot(beforeBuffer, 'before'), after = snapshot(afterBuffer, 'after');
140
+ return buildPlan(before, after, signal);
141
+ }
142
+
143
+ // Compare every own field, including arrays' length, without evaluating supplied
144
+ // getters. A serializable plain-data copy is accepted; extra/symbol/accessor
145
+ // fields, sparse arrays, exotic prototypes, and any changed value are rejected.
146
+ function canonicalEqual(supplied, expected, signal) {
147
+ checkAbort(signal);
148
+ if (expected === null || typeof expected !== 'object') return Object.is(supplied, expected);
149
+ if (supplied === null || typeof supplied !== 'object' || Array.isArray(supplied) !== Array.isArray(expected)) return false;
150
+ const prototype = Object.getPrototypeOf(supplied);
151
+ if (Array.isArray(expected) ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) return false;
152
+ const keys = Reflect.ownKeys(expected), suppliedKeys = Reflect.ownKeys(supplied);
153
+ if (keys.length !== suppliedKeys.length) return false;
154
+ return keys.every(key => {
155
+ const descriptor = Object.getOwnPropertyDescriptor(supplied, key);
156
+ return descriptor && Object.hasOwn(descriptor, 'value') &&
157
+ descriptor.enumerable === Object.getOwnPropertyDescriptor(expected, key).enumerable &&
158
+ canonicalEqual(descriptor.value, expected[key], signal);
159
+ });
160
+ }
161
+
162
+ const endings = Object.freeze({LF: '\n', CRLF: '\r\n', CR: '\r', NONE: ''});
163
+ function encode(lines) {
164
+ return Buffer.from(lines.map(line => line.text + endings[line.terminator]).join(''), 'utf8');
165
+ }
166
+
167
+ /** Recompute and validate the ENTIRE canonical plan before using a selection.
168
+ * selectedIds must be an array of unique known unit IDs (order is irrelevant).
169
+ * None returns an exact fresh copy of before; all an exact fresh copy of after.
170
+ * Subsets splice only canonical target blocks into the original raw bytes;
171
+ * replacements are atomic. No caller-supplied offsets or content are trusted.
172
+ * Throws AbortError on cancellation, TypeError on invalid plans/selections.
173
+ */
174
+ export function applyPartialIndexSelection(beforeBuffer, afterBuffer, plan, selectedIds, {signal} = {}) {
175
+ const before = snapshot(beforeBuffer, 'before'), after = snapshot(afterBuffer, 'after');
176
+ const canonical = buildPlan(before, after, signal);
177
+ if (!canonicalEqual(plan, canonical, signal)) throw new TypeError('Invalid or stale partial index plan');
178
+ if (!Array.isArray(selectedIds)) throw new TypeError('Selection must be an array of unit IDs');
179
+ const known = new Set(canonical.units.map(unit => unit.id)), selected = new Set();
180
+ for (const id of selectedIds) {
181
+ checkAbort(signal);
182
+ if (typeof id !== 'string' || !known.has(id) || selected.has(id)) throw new TypeError('Unknown or duplicate unit ID');
183
+ selected.add(id);
184
+ }
185
+ checkAbort(signal);
186
+ if (!selected.size) return Buffer.from(before);
187
+ if (selected.size === canonical.units.length) return Buffer.from(after);
188
+ const original = tokenize(before, signal), chunks = [];
189
+ let cursor = 0;
190
+ for (const unit of canonical.units) {
191
+ checkAbort(signal);
192
+ if (!selected.has(unit.id)) continue;
193
+ chunks.push(encode(original.slice(cursor, unit.beforeStart)), encode(unit.after));
194
+ cursor = unit.beforeStart + unit.beforeCount;
195
+ }
196
+ chunks.push(encode(original.slice(cursor)));
197
+ checkAbort(signal);
198
+ return Buffer.concat(chunks);
199
+ }
package/src/reflog.mjs ADDED
@@ -0,0 +1,33 @@
1
+ // NUL field and record delimiters: Git -z supplies the final record delimiter.
2
+ export const REFLOG_FORMAT = '%H%x00%gD%x00%gs';
3
+ export const REFLOG_MAX_OUTPUT = 2 * 1024 * 1024;
4
+ const LIMIT = 200;
5
+ const invalid = () => new Error('Invalid HEAD reflog framing or metadata.');
6
+ function validDate(date) {
7
+ if (!Number.isFinite(Date.parse(date))) return false;
8
+ // Date.parse normalizes dates such as February 30; reject those too.
9
+ const calendar=date.slice(0,19);
10
+ if (new Date(calendar+'Z').toISOString().slice(0,19)!==calendar) return false;
11
+ if (date.endsWith('Z')) return true;
12
+ return Number(date.slice(-5,-3))<=23 && Number(date.slice(-2))<=59;
13
+ }
14
+
15
+ /** Strictly parse the entire bounded lookahead, including its last (hidden) entry. */
16
+ export function parseReflog(raw) {
17
+ if (!Buffer.isBuffer(raw) || raw.length > REFLOG_MAX_OUTPUT) throw invalid();
18
+ let text;
19
+ try { text = new TextDecoder('utf-8', {fatal:true}).decode(raw); } catch { throw invalid(); }
20
+ if (!text) return {entries:[],truncated:false};
21
+ if (!text.endsWith('\0')) throw invalid();
22
+ const fields = text.slice(0,-1).split('\0');
23
+ if (fields.length % 3 || fields.length / 3 > LIMIT + 1) throw invalid();
24
+ const entries=[];
25
+ for (let i=0;i<fields.length;i+=3) {
26
+ const [id,selector,message]=fields.slice(i,i+3);
27
+ const match=/^HEAD@\{(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:Z|[+-]\d{2}:\d{2}))\}$/.exec(selector);
28
+ if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(id) || !match || !validDate(match[1]) || /[\r\n]/.test(message)) throw invalid();
29
+ // The date is the reflog event timestamp, not the commit author/committer date.
30
+ entries.push({id,selector,message,date:match[1]});
31
+ }
32
+ return {entries:entries.slice(0,LIMIT),truncated:entries.length>LIMIT};
33
+ }
@@ -0,0 +1,5 @@
1
+ // Start independent reads together, drain ALL siblings, then consume errors in input order.
2
+ export async function settledReads(reads){
3
+ const settled=await Promise.allSettled(reads.map(read=>Promise.resolve().then(read)));
4
+ const values=[];for(const row of settled){if(row.status==='rejected')throw row.reason;values.push(row.value);}return values;
5
+ }
@@ -0,0 +1,95 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {parseVerifiedCommit} from './verified-commit.mjs';
3
+ import {createBranchDeletePlan} from './branch-delete-plan.mjs';
4
+
5
+ const MAX_BODY=2*1024*1024,MAX_TOTAL=16*1024*1024,MAX_NODES=10000;
6
+ const byteLength=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),'byteLength').get;
7
+ const fail=message=>new Error('Verified Git branch delete plan: '+message);
8
+ function record(value,required,optional,label){
9
+ if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw fail('Invalid '+label+' record');
10
+ const out=Object.create(null);
11
+ for(const key of Reflect.ownKeys(value)){
12
+ if(!required.includes(key)&&!optional.includes(key))throw fail('Unsupported '+label+' field');
13
+ const descriptor=Object.getOwnPropertyDescriptor(value,key);
14
+ if(!descriptor||!Object.hasOwn(descriptor,'value'))throw fail(label+' requires own data properties');
15
+ out[key]=descriptor.value;
16
+ }
17
+ for(const key of required)if(!Object.hasOwn(out,key))throw fail('Missing '+label+' '+key);
18
+ return out;
19
+ }
20
+ function array(value){
21
+ if(!Array.isArray(value)||Object.getPrototypeOf(value)!==Array.prototype)throw fail('Invalid objects array');
22
+ const descriptor=Object.getOwnPropertyDescriptor(value,'length');
23
+ if(!descriptor||!Object.hasOwn(descriptor,'value')||!Number.isInteger(descriptor.value)||descriptor.value>MAX_NODES)throw fail('Object count limit exceeded');
24
+ const size=descriptor.value;
25
+ if(Reflect.ownKeys(value).length!==size+1)throw fail('Objects must be dense without extra fields');
26
+ const out=[];
27
+ for(let i=0;i<size;i++){
28
+ const item=Object.getOwnPropertyDescriptor(value,String(i));
29
+ if(!item||!Object.hasOwn(item,'value'))throw fail('Objects require dense own data elements');
30
+ out.push(item.value);
31
+ }
32
+ return out;
33
+ }
34
+ function oid(value,width){
35
+ if(typeof value!=='string'||value.length!==width||/[^0-9a-f]/.test(value)||/^0+$/.test(value))throw fail('Invalid object id');
36
+ return value;
37
+ }
38
+
39
+ // Pure, synchronous hash-authenticated CLOSED commit graph, not ref authentication,
40
+ // repository freshness, worktree/configuration safety, or deletion authorization.
41
+ // Strict supported headers (including signature rejection) come from parseVerifiedCommit;
42
+ // message bytes are opaque. Every supplied object, including disconnected nodes, is
43
+ // verified. Parent edges come only from authenticated raw headers, never assertions.
44
+ // Capture all scalars and bound aggregate bytes BEFORE copying; copy ALL bodies before
45
+ // any signal access. Cooperative callbacks cannot mutate owned bytes or captured tips.
46
+ // Descriptor/prototype traps on proxies may execute during capture: this is NOT an
47
+ // atomic snapshot across adversarial proxies or concurrently modified shared memory.
48
+ // Exact underlying plan shape/ID: verified OIDs bind bodies and ID binds the graph.
49
+ export function createVerifiedBranchDeletePlan(inputs){
50
+ const captured=record(inputs,['current','target','objects'],['objectFormat','signal'],'input');
51
+ const {objectFormat='sha1',signal}=captured;
52
+ if(objectFormat!=='sha1'&&objectFormat!=='sha256')throw fail('Unsupported object format');
53
+ const width=objectFormat==='sha1'?40:64;
54
+ const tip=(value,label)=>{
55
+ const out=record(value,['ref','oid'],[],label);
56
+ if(typeof out.ref!=='string')throw fail('Invalid branch ref');
57
+ return Object.freeze({ref:out.ref,oid:oid(out.oid,width)});
58
+ };
59
+ const current=tip(captured.current,'current'),target=tip(captured.target,'target');
60
+ let total=0;
61
+ const rows=array(captured.objects).map(value=>{
62
+ const row=record(value,['oid','body'],[],'object');
63
+ oid(row.oid,width);
64
+ if(!Buffer.isBuffer(row.body))throw fail('Object body must be a Buffer');
65
+ const size=byteLength.call(row.body);
66
+ if(size>MAX_BODY)throw fail('Object body byte limit exceeded');
67
+ total+=size;
68
+ if(total>MAX_TOTAL)throw fail('Aggregate object body byte limit exceeded');
69
+ return {oid:row.oid,body:row.body,size};
70
+ });
71
+ const snapshots=rows.map(row=>{
72
+ const body=Buffer.alloc(row.size);
73
+ Uint8Array.prototype.set.call(body,row.body);
74
+ return {oid:row.oid,body};
75
+ });
76
+ const check=()=>{
77
+ signal?.throwIfAborted?.();
78
+ if(signal?.aborted){const error=fail('Aborted');error.name='AbortError';throw error;}
79
+ };
80
+ check();
81
+ const commits=snapshots.map(({oid,body})=>{
82
+ check();
83
+ // Independently verify full Git framing before the strict parser authenticates it.
84
+ const actual=createHash(objectFormat).update(Buffer.from('commit '+body.length+'\0','ascii')).update(body).digest('hex');
85
+ if(actual!==oid)throw fail('Git commit object id mismatch');
86
+ check();
87
+ const parsed=parseVerifiedCommit(body,{oid,objectFormat,signal});
88
+ check();
89
+ return {oid:parsed.oid,parents:[...parsed.parents]};
90
+ });
91
+ check();
92
+ const plan=createBranchDeletePlan({objectFormat,current,target,commits,signal});
93
+ check();
94
+ return plan;
95
+ }
@@ -0,0 +1,57 @@
1
+ import {TextDecoder} from 'node:util';
2
+ import {parseVerifiedCommit} from './verified-commit.mjs';
3
+
4
+ const MAX_BODY_BYTES=2*1024*1024,MAX_MESSAGE_BYTES=64*1024,MAX_IDENTITY_FIELD_BYTES=1024;
5
+ const utf8=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true});
6
+ function captureOptions(value){
7
+ if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw Error('Invalid Git commit metadata options record');
8
+ const captured=Object.create(null);
9
+ for(const key of Reflect.ownKeys(value)){
10
+ if(!['oid','objectFormat','signal'].includes(key))throw Error('Unsupported Git commit metadata option');
11
+ const descriptor=Object.getOwnPropertyDescriptor(value,key);
12
+ if(!descriptor||!Object.hasOwn(descriptor,'value'))throw Error('Git commit metadata options must be own data properties');
13
+ captured[key]=descriptor.value;
14
+ }
15
+ return captured;
16
+ }
17
+ function checkAbort(signal){
18
+ if(signal?.aborted){const error=new Error('Git commit metadata read aborted');error.name='AbortError';throw error;}
19
+ }
20
+ function readIdentity(line,role){
21
+ // Header grammar, UTF-8, safe integer range and timezone were authenticated
22
+ // and validated by parseVerifiedCommit. Never trim or normalize these fields.
23
+ const match=/^([^<>]+) <([^<>]+)> (0|[1-9][0-9]*) ([-+][0-9]{4})$/.exec(utf8.decode(line.subarray(role.length+1)));
24
+ if(!match)throw Error('Unsupported Git commit metadata identity');
25
+ const [,name,email,timestamp,timezone]=match;
26
+ if(Buffer.byteLength(name)>MAX_IDENTITY_FIELD_BYTES||Buffer.byteLength(email)>MAX_IDENTITY_FIELD_BYTES)throw Error('Git commit metadata identity field byte limit exceeded');
27
+ return Object.freeze({name,email,timestamp:Number(timestamp),timezone});
28
+ }
29
+
30
+ // Pure, read-only projection of authenticated raw commit BODY bytes. No refs,
31
+ // I/O, object-existence checks, or amend eligibility/authorization are implied.
32
+ // Snapshot before inspecting options (including Proxy traps) or signal callbacks.
33
+ // Inherits the verifier's strict header grammar and 0..16-parent support.
34
+ // Empty/blank messages, BOM, CRLF and missing final LF are preserved exactly;
35
+ // unlike the tree-only parser this projection rejects unsupported message UTF-8
36
+ // and Cc controls except LF/TAB/CR. It does not impose commit-UI write policy.
37
+ // messageBytes is a scalar byte count, never an exposed mutable body Buffer.
38
+ export function readVerifiedCommitMetadata(bytes,options={}){
39
+ if(!Buffer.isBuffer(bytes))throw Error('Git commit bytes must be a Buffer');
40
+ if(bytes.length>MAX_BODY_BYTES)throw Error('Git commit body byte limit exceeded');
41
+ const body=Buffer.alloc(bytes.length);Buffer.prototype.copy.call(bytes,body);
42
+ const captured=captureOptions(options),{signal}=captured;
43
+ const verified=parseVerifiedCommit(body,captured);
44
+ checkAbort(signal);
45
+ const separator=body.indexOf('\n\n'),messageBytes=body.length-separator-2;
46
+ if(messageBytes>MAX_MESSAGE_BYTES)throw Error('Git commit metadata message byte limit exceeded');
47
+ let message;
48
+ try{message=utf8.decode(body.subarray(separator+2));}catch{throw Error('Unsupported Git commit metadata message: strict UTF-8 required');}
49
+ if(/[\p{Cc}]/u.test(message.replace(/[\n\t\r]/g,'')))throw Error('Unsupported Git commit metadata message control character');
50
+ let author,committer;
51
+ for(const line of body.subarray(0,separator).toString('utf8').split('\n')){
52
+ if(line.startsWith('author '))author=readIdentity(Buffer.from(line),'author');
53
+ else if(line.startsWith('committer '))committer=readIdentity(Buffer.from(line),'committer');
54
+ }
55
+ checkAbort(signal);
56
+ return Object.freeze({...verified,author,committer,message,messageBytes});
57
+ }
@@ -0,0 +1,49 @@
1
+ import {parseVerifiedCommit} from './verified-commit.mjs';
2
+ import {createIndexCommitPlan} from './commit-plan.mjs';
3
+
4
+ const MAX_INDEX_BYTES=8*1024*1024,MAX_PARENT_BYTES=2*1024*1024;
5
+ function owned(bytes){const copy=Buffer.alloc(bytes.length);Buffer.prototype.copy.call(bytes,copy);return copy;}
6
+ function dataRecord(value,keys,label){
7
+ if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw Error('Invalid Git commit plan '+label+' record');
8
+ const captured=Object.create(null);
9
+ for(const key of Reflect.ownKeys(value)){
10
+ if(!keys.includes(key))throw Error('Unsupported Git commit plan '+label+' field');
11
+ const descriptor=Object.getOwnPropertyDescriptor(value,key);
12
+ if(!descriptor||!Object.hasOwn(descriptor,'value'))throw Error('Git commit plan '+label+' fields must be own data properties');
13
+ captured[key]=descriptor.value;
14
+ }
15
+ return captured;
16
+ }
17
+ function captureIdentity(value,label){
18
+ const copy=dataRecord(value,['name','email','timestamp','timezone'],label);
19
+ for(const key of ['name','email','timezone'])if(typeof copy[key]!=='string')throw Error('Git identity '+key+' must be a string');
20
+ if(typeof copy.timestamp!=='number')throw Error('Invalid Git identity timestamp');
21
+ return copy;
22
+ }
23
+
24
+ // Pure synchronous assembly: both bounded raw Buffers are copied before inspecting
25
+ // inputs (including descriptor/prototype traps) or calling cancellation callbacks.
26
+ // Inputs and identities follow createIndexCommitPlan's strict own-data policy.
27
+ // Only the authenticated parent's header supplies parentTree; message text cannot.
28
+ // The existing plan ID binds these exact parent bytes through their verified OID.
29
+ // Returned shape/owned mutable bodies match createIndexCommitPlan. This proves no
30
+ // object existence/type, repository freshness or authorization, and performs no I/O.
31
+ export function createVerifiedIndexCommitPlan(indexBuffer,parentBody,inputs={}){
32
+ if(!Buffer.isBuffer(indexBuffer))throw Error('Git index must be a Buffer');
33
+ if(indexBuffer.length>MAX_INDEX_BYTES)throw Error('Git index byte limit exceeded');
34
+ if(!Buffer.isBuffer(parentBody))throw Error('Git parent commit bytes must be a Buffer');
35
+ if(parentBody.length>MAX_PARENT_BYTES)throw Error('Git parent commit body byte limit exceeded');
36
+ const indexSnapshot=owned(indexBuffer),parentSnapshot=owned(parentBody);
37
+ const captured=dataRecord(inputs,['objectFormat','parent','author','committer','message','signal'],'input');
38
+ const {objectFormat='sha1',parent,message,signal}=captured;
39
+ const author=captureIdentity(captured.author,'author'),committer=captureIdentity(captured.committer,'committer');
40
+ if(Buffer.isBuffer(message)&&message.length>64*1024)throw Error('Git commit message byte limit exceeded');
41
+ const messageSnapshot=Buffer.isBuffer(message)?owned(message):message;
42
+ const check=()=>signal?.throwIfAborted();
43
+ check();
44
+ const verified=parseVerifiedCommit(parentSnapshot,{oid:parent,objectFormat,signal});
45
+ check();
46
+ const plan=createIndexCommitPlan(indexSnapshot,{objectFormat,parent:verified.oid,parentTree:verified.tree,author,committer,message:messageSnapshot,signal});
47
+ check();
48
+ return plan;
49
+ }