@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.
- package/README.md +69 -6
- package/amend-host.mjs +48 -0
- package/branch-create-host.mjs +42 -0
- package/branch-create-preview.mjs +196 -0
- package/branch-delete-preview.mjs +214 -0
- package/branch-switch-host.mjs +13 -33
- package/commit-host.mjs +49 -0
- package/commit-object-publish.mjs +123 -0
- package/commit-preview.mjs +335 -0
- package/confirmed-operation.mjs +50 -0
- package/dist/client.js +2 -2
- package/dist/frontend.json +1 -1
- package/dist/interface.js +2 -2
- package/docs/RELEASING.md +7 -5
- package/git-blob-store.mjs +151 -0
- package/git-branch-create.mjs +156 -0
- package/git-branch-delete.mjs +175 -0
- package/git-lightweight-tag-create.mjs +181 -0
- package/git-object-store.mjs +162 -0
- package/git-ref-cas.mjs +119 -0
- package/git-tag-create.mjs +186 -0
- package/index-change-host.mjs +19 -0
- package/index-change.mjs +418 -0
- package/index-lock.mjs +231 -0
- package/index-stage-host.mjs +19 -0
- package/index.mjs +301 -4
- package/latest-commit.mjs +109 -0
- package/lightweight-tag-host.mjs +42 -0
- package/lightweight-tag-preview.mjs +183 -0
- package/line-index-host.mjs +58 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +48 -3
- package/partial-stage-host.mjs +52 -0
- package/partial-unstage-host.mjs +52 -0
- package/src/amend-plan.mjs +74 -0
- package/src/branch-delete-plan.mjs +113 -0
- package/src/commit-plan.mjs +78 -0
- package/src/git-commit-object.mjs +99 -0
- package/src/git-index.mjs +113 -0
- package/src/git-tag-object.mjs +110 -0
- package/src/index-tree.mjs +77 -0
- package/src/lightweight-tag-plan.mjs +64 -0
- package/src/line-index.mjs +168 -0
- package/src/partial-index.mjs +199 -0
- package/src/reflog.mjs +33 -0
- package/src/settled-reads.mjs +5 -0
- package/src/verified-branch-delete-plan.mjs +95 -0
- package/src/verified-commit-metadata.mjs +57 -0
- package/src/verified-commit-plan.mjs +49 -0
- package/src/verified-commit.mjs +84 -0
- package/src/verified-tag-plan.mjs +72 -0
- package/tag-create-host.mjs +31 -0
- package/tag-create-preview.mjs +215 -0
- package/tag-object-publish.mjs +49 -0
- package/vcs.mjs +29 -0
package/index-change.mjs
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
// Internal server adapter only. A future host must resolve an authorized change ID;
|
|
2
|
+
// accepting a safe path here does NOT authorize a browser-supplied path.
|
|
3
|
+
import * as fs from 'node:fs/promises';
|
|
4
|
+
import {constants} from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import {createHash} from 'node:crypto';
|
|
8
|
+
import {inflateSync} from 'node:zlib';
|
|
9
|
+
import {git} from './local-command.mjs';
|
|
10
|
+
import {parseGitIndex,replaceGitIndexEntry} from './src/git-index.mjs';
|
|
11
|
+
import {storeCapturedBlob} from './git-blob-store.mjs';
|
|
12
|
+
import {withOwnedIndexLock} from './index-lock.mjs';
|
|
13
|
+
import {currentOperationBudget} from './src/operation-budget.mjs';
|
|
14
|
+
import {createPartialIndexPlan,applyPartialIndexSelection,MAX_PARTIAL_INDEX_BYTES} from './src/partial-index.mjs';
|
|
15
|
+
import {createLineIndexPlan,applyLineIndexSelection} from './src/line-index.mjs';
|
|
16
|
+
|
|
17
|
+
const MAX_FILE=2*1024*1024, MAX_TOTAL=16*1024*1024, MAX_NODES=20000;
|
|
18
|
+
const issued=new WeakMap(), stagedIssued=new WeakMap(), partialIssued=new WeakMap(), partialUnstageIssued=new WeakMap(), unstagedPartialIssued=new WeakMap();
|
|
19
|
+
// LINE plans and candidates are never accepted by whole/BLOCK or opposite-direction APIs.
|
|
20
|
+
const lineStagePlans=new WeakMap(), lineUnstagePlans=new WeakMap(), lineStageIssued=new WeakMap(), lineUnstageIssued=new WeakMap();
|
|
21
|
+
const fail=(kind,message)=>Object.assign(new Error(message),{code:'vcs/index-'+kind});
|
|
22
|
+
const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
|
|
23
|
+
const json=value=>JSON.stringify(value);
|
|
24
|
+
const check=signal=>{signal?.throwIfAborted();currentOperationBudget()?.throwIfExpired();};
|
|
25
|
+
const identity=s=>[s.dev,s.ino,s.birthtimeNs].map(String);
|
|
26
|
+
const version=s=>[...identity(s),s.size,s.mtimeNs,s.ctimeNs,s.mode].map(String);
|
|
27
|
+
const plain=s=>s.isFile()&&!s.isSymbolicLink()&&s.nlink===1n;
|
|
28
|
+
const decode=b=>new TextDecoder('utf-8',{fatal:true}).decode(b);
|
|
29
|
+
// Join every launched read before exposing any result/error. Callers consume in
|
|
30
|
+
// the original validation order, not completion order (including synchronous throws).
|
|
31
|
+
async function settledReads(tasks){
|
|
32
|
+
const results=await Promise.allSettled(tasks.map(task=>Promise.resolve().then(task)));
|
|
33
|
+
return results.map(result=>()=>{if(result.status==='rejected')throw result.reason;return result.value;});
|
|
34
|
+
}
|
|
35
|
+
function safePath(value){
|
|
36
|
+
if(typeof value!=='string'||!value||Buffer.byteLength(value)>4096||/[\u0000-\u001f\u007f\\:<>"|?*]/u.test(value))throw fail('unsafe','Unsafe exact repository path.');
|
|
37
|
+
for(const part of value.split('/'))if(!part||part==='.'||part==='..'||part.toLowerCase()==='.git'||/[. ]$/.test(part)||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part))throw fail('unsafe','Unsafe exact repository path.');
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
async function exists(file){try{await fs.lstat(file);return true;}catch(e){if(e.code==='ENOENT')return false;throw e;}}
|
|
41
|
+
async function readPlain(file,max,signal){
|
|
42
|
+
check(signal);const before=await fs.lstat(file,{bigint:true});
|
|
43
|
+
if(!plain(before)||before.size>BigInt(max))throw fail('unsupported','Expected bounded single-link regular file: '+file);
|
|
44
|
+
const handle=await fs.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW||0));
|
|
45
|
+
try{
|
|
46
|
+
const opened=await handle.stat({bigint:true});
|
|
47
|
+
if(!plain(opened)||json(version(before))!==json(version(opened)))throw fail('stale','File changed while opening.');
|
|
48
|
+
const buffer=Buffer.alloc(max+1);let length=0;
|
|
49
|
+
while(length<buffer.length){check(signal);const {bytesRead}=await handle.read(buffer,length,buffer.length-length,length);if(!bytesRead)break;length+=bytesRead;}
|
|
50
|
+
const after=await handle.stat({bigint:true}),current=await fs.lstat(file,{bigint:true});
|
|
51
|
+
if(length>max||!plain(current)||json(version(opened))!==json(version(after))||json(version(after))!==json(version(current))||BigInt(length)!==after.size)throw fail('stale','File changed while reading.');
|
|
52
|
+
return {bytes:Buffer.from(buffer.subarray(0,length)),identity:version(after)};
|
|
53
|
+
}finally{await handle.close();}
|
|
54
|
+
}
|
|
55
|
+
// Check all metadata links/state before asking Git to inspect objects. Directory
|
|
56
|
+
// timestamps deliberately are NOT compared: creating our own lock changes them.
|
|
57
|
+
async function metadata(directory,allowLock,signal){
|
|
58
|
+
const rows=[];let count=0;
|
|
59
|
+
const forbidden=new Set(['commondir','gitdir','shallow','config.worktree','MERGE_HEAD','MERGE_MSG','CHERRY_PICK_HEAD','REVERT_HEAD','REBASE_HEAD','BISECT_LOG','BISECT_START','rebase-merge','rebase-apply','sequencer','info/sparse-checkout','info/attributes','objects/info/alternates','objects/info/http-alternates'].map(value=>value.toLowerCase()));
|
|
60
|
+
async function visit(file,relative){
|
|
61
|
+
check(signal);if(++count>MAX_NODES)throw fail('unsupported','Metadata inspection limit exceeded.');
|
|
62
|
+
const guard=relative.toLowerCase(); // Conservative on every platform; preserves physical spelling below.
|
|
63
|
+
if(guard==='index.lock'&&relative==='index.lock'&&allowLock)return; // only withOwnedIndexLock checks ownership
|
|
64
|
+
if(forbidden.has(guard)||guard.endsWith('.lock')||guard.endsWith('.promisor'))throw fail('unsupported','Repository operation, lock or unsupported metadata: '+relative);
|
|
65
|
+
if(guard.startsWith('hooks/')&&!guard.endsWith('.sample'))throw fail('unsupported','Active hooks are unsupported.');
|
|
66
|
+
const s=await fs.lstat(file,{bigint:true});
|
|
67
|
+
if(s.isSymbolicLink()||(!s.isDirectory()&&!plain(s))||await fs.realpath(file)!==file)throw fail('unsafe','Redirected or special metadata.');
|
|
68
|
+
if(relative==='index')return;
|
|
69
|
+
rows.push([relative,s.isDirectory()?identity(s):version(s)]);
|
|
70
|
+
if(s.isDirectory())for(const name of (await fs.readdir(file)).sort())await visit(path.join(file,name),relative?relative+'/'+name:name);
|
|
71
|
+
}
|
|
72
|
+
await visit(directory,'');return rows;
|
|
73
|
+
}
|
|
74
|
+
async function workPaths(root,signal){
|
|
75
|
+
const files=[],directories=[];let nodes=0;
|
|
76
|
+
async function visit(dir,relative){
|
|
77
|
+
check(signal);if(++nodes>MAX_NODES)throw fail('unsupported','Working tree inspection limit exceeded.');
|
|
78
|
+
const s=await fs.lstat(dir,{bigint:true});
|
|
79
|
+
if(!s.isDirectory()||s.isSymbolicLink()||await fs.realpath(dir)!==dir)throw fail('unsafe','Working directories must be canonical.');
|
|
80
|
+
directories.push([relative,identity(s)]);
|
|
81
|
+
for(const name of (await fs.readdir(dir)).sort()){
|
|
82
|
+
if(!relative&&name==='.git')continue;
|
|
83
|
+
const rel=relative?relative+'/'+name:name;safePath(rel);
|
|
84
|
+
if(name.toLowerCase()==='.gitattributes'||name.toLowerCase()==='.gitmodules')throw fail('unsupported','Attributes and submodules are unsupported.');
|
|
85
|
+
const target=path.join(dir,name),stat=await fs.lstat(target,{bigint:true});
|
|
86
|
+
if(stat.isDirectory()&&!stat.isSymbolicLink())await visit(target,rel);
|
|
87
|
+
else {if(++nodes>MAX_NODES||!plain(stat))throw fail('unsupported','Links and special working files are unsupported.');files.push(rel);}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
await visit(root,'');return {files,directories};
|
|
91
|
+
}
|
|
92
|
+
// Never stored in snapshots/grants or accepted through public arguments. Ref syntax
|
|
93
|
+
// is pure and may be reused for the exact validated string within one public call.
|
|
94
|
+
// Fixed object reads require the complete metadata fingerprint (including every
|
|
95
|
+
// object file; excluding the separately checked Index) to remain equal.
|
|
96
|
+
async function capture(repo,selected,signal,{allowLock=false,published=false,id,operation='unstage',partialMM=false}={},context){
|
|
97
|
+
check(signal);if(id===undefined)safePath(selected);
|
|
98
|
+
else if(typeof id!=='string'||!/^[a-f0-9]{64}$/.test(id))throw fail('stale','Invalid staged selection ID.');
|
|
99
|
+
if(repo?.type!=='git'||typeof repo.root!=='string'||!path.isAbsolute(repo.root))throw fail('unsupported','An absolute canonical Git root is required.');
|
|
100
|
+
const root=path.resolve(repo.root);
|
|
101
|
+
if(await fs.realpath(root)!==root)throw fail('unsafe','Repository root must be canonical.');
|
|
102
|
+
const rootStat=await fs.lstat(root,{bigint:true}),directory=path.join(root,'.git');
|
|
103
|
+
const metadataRows=await metadata(directory,allowLock,signal),metadataHash=hash(json(metadataRows));
|
|
104
|
+
const run=(args,max=MAX_FILE)=>{check(signal);return git(root,args,max,{signal});};
|
|
105
|
+
for(const file of [path.join(process.env.XDG_CONFIG_HOME||path.join(os.homedir(),'.config'),'git','attributes'),path.join(os.homedir(),'.gitattributes')])if(await exists(file))throw fail('unsupported','Global attributes are unsupported.');
|
|
106
|
+
const config=await run(['config','--null','--list']);
|
|
107
|
+
const configRows=new Map();
|
|
108
|
+
for(const row of decode(config).split('\0').filter(Boolean))configRows.set(row.split('\n',1)[0].toLowerCase(),row);
|
|
109
|
+
for(const row of configRows.values()){
|
|
110
|
+
const split=row.indexOf('\n'),key=(split<0?row:row.slice(0,split)).toLowerCase(),value=split<0?'':row.slice(split+1).toLowerCase();
|
|
111
|
+
if(key.startsWith('filter.')||key.startsWith('hook.')||key.startsWith('include')||key.startsWith('submodule.')||key.startsWith('extensions.')&&key!=='extensions.objectformat'||['core.worktree','core.hookspath','core.attributesfile','core.fsmonitor','core.sparsecheckout','core.sparsecheckoutcone','index.sparse','core.splitindex','core.untrackedcache','core.symlinks'].includes(key)&&!['false','no','0'].includes(value)||/^remote\..*\.(promisor|partialclonefilter)$/.test(key))throw fail('unsupported','Unsupported repository configuration: '+key);
|
|
112
|
+
if(['core.autocrlf','core.safecrlf'].includes(key)&&!['false','no','0'].includes(value))throw fail('unsupported','Content conversions are unsupported.');
|
|
113
|
+
}
|
|
114
|
+
// Only read-only tasks overlap, after metadata/config guards. Mutable facts
|
|
115
|
+
// stay fresh and their results are validated in the original order.
|
|
116
|
+
const [readFacts,readIndex,readHead]=await settledReads([
|
|
117
|
+
()=>run(['rev-parse','--absolute-git-dir','--git-common-dir','--show-toplevel','--is-bare-repository','--show-object-format','--verify','HEAD^{commit}']),
|
|
118
|
+
()=>readPlain(path.join(directory,'index'),8*1024*1024,signal),
|
|
119
|
+
()=>readPlain(path.join(directory,'HEAD'),4096,signal)
|
|
120
|
+
]);
|
|
121
|
+
let facts;try{facts=decode(readFacts()).split('\n');}catch(e){if(e.code==='VCS_COMMAND')throw fail('unsupported','Born HEAD in an embedded repository is required.');throw e;}
|
|
122
|
+
if(facts.length!==7||facts[6]!==''||facts.slice(0,3).some(value=>!value||/[\r\0]/.test(value))||path.resolve(root,facts[0])!==directory||path.resolve(root,facts[1])!==directory||path.resolve(facts[2])!==root||facts[3]!=='false')throw fail('unsupported','Only embedded non-bare repositories are supported.');
|
|
123
|
+
const objectFormat=facts[4],commit=facts[5];
|
|
124
|
+
const index=readIndex();
|
|
125
|
+
const parsed=parseGitIndex(index.bytes,{objectFormat});
|
|
126
|
+
if(parsed.extensions.some(e=>!['TREE','EOIE','IEOT'].includes(e.signature)))throw fail('unsupported','Unsupported Index extension.');
|
|
127
|
+
const headFile=readHead();
|
|
128
|
+
const headText=decode(headFile.bytes);
|
|
129
|
+
if(!/^ref: refs\/heads\/[^\r\n]+\n?$/.test(headText))throw fail('unsupported','Born symbolic HEAD is required.');
|
|
130
|
+
const ref=headText.trim().slice(5);
|
|
131
|
+
const objectKey=json([root,objectFormat,commit,metadataHash]);
|
|
132
|
+
const [checkRef,readTree]=await settledReads([
|
|
133
|
+
()=>{check(signal);if(context.validatedRef===ref)return;return run(['check-ref-format',ref]);},
|
|
134
|
+
async()=>{
|
|
135
|
+
if(!['sha1','sha256'].includes(objectFormat)||!(objectFormat==='sha1'?/^[a-f0-9]{40}$/:/^[a-f0-9]{64}$/).test(commit))throw fail('unsupported','Invalid fixed HEAD object identity.');
|
|
136
|
+
check(signal);
|
|
137
|
+
if(context.key===objectKey&&context.headEntries)return context.headEntries;
|
|
138
|
+
const tree=decode(await run(['ls-tree','-r','-z','--full-tree',commit],8*1024*1024)),entries=[];
|
|
139
|
+
for(const row of tree.split('\0').filter(Boolean)){
|
|
140
|
+
const match=/^(100644|100755) blob ([a-f0-9]{40}|[a-f0-9]{64}) (.+)$/.exec(row);
|
|
141
|
+
if(!match)throw fail('unsupported','Special HEAD tree entries are unsupported.');
|
|
142
|
+
safePath(match[3]);entries.push({path:match[3],oid:match[2],mode:match[1]});
|
|
143
|
+
}
|
|
144
|
+
return entries;
|
|
145
|
+
}
|
|
146
|
+
]);
|
|
147
|
+
// All siblings have settled before recording a successful syntax check. A
|
|
148
|
+
// failed checker never warms the context; mutable HEAD/ref facts stay fresh.
|
|
149
|
+
checkRef();context.validatedRef=ref;const headEntries=readTree();
|
|
150
|
+
// Publish only complete successful results, never an in-flight/rejected read.
|
|
151
|
+
if(context.key!==objectKey){context.key=objectKey;context.blob=undefined;}
|
|
152
|
+
context.headEntries=headEntries;
|
|
153
|
+
for(const entry of [...headEntries,...parsed.entries])if(entry.path.split('/').some(p=>['.gitattributes','.gitmodules'].includes(p.toLowerCase())))throw fail('unsupported','Tracked attributes/submodules are unsupported.');
|
|
154
|
+
const folded=new Set();for(const entry of parsed.entries){const key=entry.path.toLowerCase();if(folded.has(key))throw fail('unsupported','Case-ambiguous paths are unsupported.');folded.add(key);}
|
|
155
|
+
if(id!==undefined){
|
|
156
|
+
const indexStatuses=partialMM&&operation==='stage'?[' ','M']:[operation==='stage'?' ':'M'];
|
|
157
|
+
const workStatuses=operation==='stage'?['M']:partialMM?[' ','M']:[' '];
|
|
158
|
+
const matches=parsed.entries.filter(entry=>indexStatuses.some(indexStatus=>workStatuses.some(workStatus=>createHash('sha256').update(json([operation==='stage'?'unstaged':'staged',entry.path,undefined,'modified',indexStatus,workStatus,undefined,undefined,undefined])).digest('hex')===id)));
|
|
159
|
+
if(matches.length!==1)throw fail('stale','Staged selection changed; refresh.');
|
|
160
|
+
selected=matches[0].path;
|
|
161
|
+
}
|
|
162
|
+
const selectedIndex=parsed.entries.find(e=>e.path===selected),head=headEntries.find(e=>e.path===selected);
|
|
163
|
+
if(!selectedIndex||!head||!published&&(operation==='stage'?((!partialMM&&selectedIndex.oid!==head.oid)||selectedIndex.mode!==head.mode):(selectedIndex.oid===head.oid&&selectedIndex.mode===head.mode)))throw fail('unsupported','Select an existing tracked staged modified regular file.');
|
|
164
|
+
if(partialMM&&selectedIndex.mode!==head.mode)throw fail('unsupported','Partial changes require unchanged regular file modes.');
|
|
165
|
+
check(signal);
|
|
166
|
+
const [readType,readAttributes]=await settledReads([
|
|
167
|
+
async()=>{if(context.blob!==head.oid&&decode(await run(['cat-file','-t',head.oid])).trim()!=='blob')throw fail('unsupported','Pinned HEAD entry must resolve to an existing blob.');},
|
|
168
|
+
// Also refuse implicit/system attributes, without invoking any content filter.
|
|
169
|
+
()=>run(['check-attr','--all','-z','--',selected])
|
|
170
|
+
]);
|
|
171
|
+
readType();context.blob=head.oid;
|
|
172
|
+
if(readAttributes().length)throw fail('unsupported','Selected path has Git attributes.');
|
|
173
|
+
// No status or working bytes are inspected until config, state, flags, trees,
|
|
174
|
+
// links and attributes have all been refused.
|
|
175
|
+
const paths=await workPaths(root,signal);let total=0,capturedBytes;const work=[];
|
|
176
|
+
for(const file of paths.files){const item=await readPlain(path.join(root,...file.split('/')),MAX_FILE,signal);total+=item.bytes.length;if(total>MAX_TOTAL)throw fail('unsupported','Working content exceeds 16MiB.');work.push({path:file,identity:item.identity,digest:hash(item.bytes)});
|
|
177
|
+
if(file===selected){capturedBytes=item.bytes;}
|
|
178
|
+
if(file===selected&&!published){const oid=createHash(objectFormat).update(Buffer.from('blob '+item.bytes.length+'\0')).update(item.bytes).digest('hex');if((operation==='stage'?oid===selectedIndex.oid:!partialMM&&oid!==selectedIndex.oid)||process.platform!=='win32'&&Boolean(Number(item.identity.at(-1))&0o111)!==(selectedIndex.mode==='100755'))throw fail('unsupported','Selected working bytes/mode must match the Index; partial staging is unsupported.');}
|
|
179
|
+
}
|
|
180
|
+
if(!work.some(e=>e.path===selected))throw fail('unsupported','Selected working file is missing.');
|
|
181
|
+
// Resolve the exact existing vcs identity only after all capture guards. The
|
|
182
|
+
// provisional lookup above permits locating attributes without running status.
|
|
183
|
+
if(id!==undefined&&partialMM){
|
|
184
|
+
const indexStatus=selectedIndex.oid===head.oid?' ':'M',workStatus=createHash(objectFormat).update(Buffer.from('blob '+capturedBytes.length+'\0')).update(capturedBytes).digest('hex')===selectedIndex.oid?' ':'M';
|
|
185
|
+
const exact=createHash('sha256').update(json([operation==='stage'?'unstaged':'staged',selected,undefined,'modified',indexStatus,workStatus,undefined,undefined,undefined])).digest('hex');
|
|
186
|
+
if(exact!==id)throw fail('stale','Exact selection changed; refresh.');
|
|
187
|
+
}
|
|
188
|
+
check(signal);
|
|
189
|
+
return {root,directory,rootIdentity:identity(rootStat),metadataRows,metadataHash,config:hash(config),headFile:{identity:headFile.identity,digest:hash(headFile.bytes)},ref,commit,objectFormat,index:{identity:index.identity,digest:hash(index.bytes)},entries:parsed.entries,head,selected:selectedIndex,work,directories:paths.directories,bytes:index.bytes,capturedBytes};
|
|
190
|
+
}
|
|
191
|
+
const fingerprint=s=>hash(json({...s,bytes:undefined,capturedBytes:undefined}));
|
|
192
|
+
function candidate(state,selected){return replaceGitIndexEntry(state.bytes,{path:selected,expectedOid:state.selected.oid,expectedMode:state.selected.mode,oid:state.head.oid,mode:state.head.mode,objectFormat:state.objectFormat});}
|
|
193
|
+
|
|
194
|
+
/** Returns an opaque, process-local server snapshot (not JSON-round-trippable).
|
|
195
|
+
* Bounds: Index 8MiB/100000 entries; <=20000 nodes per scan; each working file
|
|
196
|
+
* <=2MiB, total <=16MiB (including ignored/untracked). Repeated FS checks and a
|
|
197
|
+
* real index.lock are conservative CAS, NOT global filesystem atomicity.
|
|
198
|
+
* Unsupported: additions/deletions, selected MM/partial staging or conversions,
|
|
199
|
+
* detached/unborn HEAD, external/linked/bare metadata, operation state, locks,
|
|
200
|
+
* attributes/filters/hooks, sparse/partial/split indexes, special entries/flags,
|
|
201
|
+
* case aliases, symlinks/hardlinks anywhere scanned. Unrelated dirty files are OK.
|
|
202
|
+
* RPC/UI use the guarded opaque-ID selector. Whole unstage never creates objects;
|
|
203
|
+
* stage and internal partial unstage can append one exact raw candidate blob.
|
|
204
|
+
*/
|
|
205
|
+
export async function prepareSelectedIndexUnstage(repo,{id,signal}={}){
|
|
206
|
+
return prepareIndexUnstage(repo,{id,signal});
|
|
207
|
+
}
|
|
208
|
+
export async function prepareIndexUnstage(repo,{path:selected,id,signal}={}){
|
|
209
|
+
const context={};
|
|
210
|
+
const state=await capture(repo,selected,signal,{id},context);selected=state.selected.path;candidate(state,selected);
|
|
211
|
+
const again=await capture(repo,selected,signal,{},context);
|
|
212
|
+
if(fingerprint(state)!==fingerprint(again))throw fail('stale','Repository changed during preparation.');
|
|
213
|
+
const snapshot=Object.freeze({path:selected,head:state.commit,index:Object.freeze({oid:state.selected.oid,mode:state.selected.mode}),target:Object.freeze({oid:state.head.oid,mode:state.head.mode}),fingerprint:fingerprint(state)});
|
|
214
|
+
issued.set(snapshot,{state,selected});return snapshot;
|
|
215
|
+
}
|
|
216
|
+
/** Publishes only a pure one-entry replacement; no Git mutation/object writes.
|
|
217
|
+
* Returns {path, head:commitOID, index:{oid,mode}}. Every error after onStart
|
|
218
|
+
* (including cancellation/authorization/deadline or verification) is outcome-unknown.
|
|
219
|
+
*/
|
|
220
|
+
export async function applyIndexUnstage(repo,{snapshot,signal,assertAuthorized,onStart}={}){
|
|
221
|
+
const context={};let started=false;
|
|
222
|
+
try{
|
|
223
|
+
const saved=snapshot&&issued.get(snapshot);
|
|
224
|
+
if(!saved||typeof assertAuthorized!=='function'||typeof onStart!=='function')throw fail('stale','A server-issued snapshot and authorization/start callbacks are required.');
|
|
225
|
+
const {state,selected}=saved;check(signal);await assertAuthorized();check(signal);
|
|
226
|
+
const revalidate=async()=>{const fresh=await capture(repo,selected,signal,{allowLock:true},context);if(fingerprint(fresh)!==fingerprint(state))throw fail('stale','Repository snapshot changed.');return fresh;};
|
|
227
|
+
const fresh=await capture(repo,selected,signal,{},context);
|
|
228
|
+
if(fingerprint(fresh)!==fingerprint(state))throw fail('stale','Repository snapshot changed.');
|
|
229
|
+
const expected=candidate(state,selected);
|
|
230
|
+
const result=await withOwnedIndexLock({gitDirectory:state.directory,expectedIndexDigest:state.index.digest,signal},async lock=>{
|
|
231
|
+
const live=await lock.readIndex();if(!live.equals(state.bytes))throw fail('stale','Raw Index changed.');
|
|
232
|
+
await lock.writeCandidate(expected);
|
|
233
|
+
await lock.publish({assertAuthorized:async()=>{check(signal);await assertAuthorized();check(signal);if(!started)await revalidate();},beforePublish:async()=>{const current=await revalidate();if(!candidate(current,selected).equals(expected))throw fail('stale','Candidate changed.');},onStart:()=>{started=true;check(signal);return onStart();}});
|
|
234
|
+
const after=await capture(repo,selected,signal,{published:true},context);
|
|
235
|
+
const expectedEntries=parseGitIndex(expected,{objectFormat:state.objectFormat}).entries;
|
|
236
|
+
if(!after.bytes.equals(expected)||json(after.entries)!==json(expectedEntries)||json(after.work)!==json(state.work)||json(after.directories)!==json(state.directories)||after.commit!==state.commit||after.ref!==state.ref||after.metadataHash!==state.metadataHash||after.config!==state.config||json(after.rootIdentity)!==json(state.rootIdentity)||json(after.headFile)!==json(state.headFile)||json(after.head)!==json(state.head))throw fail('stale','Post-publication verification failed.');
|
|
237
|
+
await assertAuthorized();check(signal);
|
|
238
|
+
return {path:selected,head:state.commit,index:{oid:state.head.oid,mode:state.head.mode}};
|
|
239
|
+
});
|
|
240
|
+
check(signal);return result;
|
|
241
|
+
}catch(error){if(!started)throw error;throw Object.assign(fail('outcome-unknown','Index publication may have occurred; refresh state and do not retry blindly.'),{outcomeUnknown:true,cause:error});}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// Whole unstage, stage and reverse-partial grants have separate capability namespaces.
|
|
245
|
+
// Direction and MM policy are selected only by internal entry points/WeakMaps.
|
|
246
|
+
const stageCandidate=(state,selected,target)=>replaceGitIndexEntry(state.bytes,{path:selected,expectedOid:state.selected.oid,expectedMode:state.selected.mode,...target,objectFormat:state.objectFormat});
|
|
247
|
+
export async function prepareSelectedIndexStage(repo,{id,signal}={}){
|
|
248
|
+
return prepareIndexStage(repo,{id,signal});
|
|
249
|
+
}
|
|
250
|
+
export async function prepareIndexStage(repo,{path:selected,id,signal}={}){
|
|
251
|
+
const context={};
|
|
252
|
+
const state=await capture(repo,selected,signal,{id,operation:'stage'},context);selected=state.selected.path;
|
|
253
|
+
const bytes=Buffer.from(state.capturedBytes);
|
|
254
|
+
const target=Object.freeze({oid:createHash(state.objectFormat).update(Buffer.from('blob '+bytes.length+'\0')).update(bytes).digest('hex'),mode:state.selected.mode});
|
|
255
|
+
stageCandidate(state,selected,target);
|
|
256
|
+
const again=await capture(repo,selected,signal,{operation:'stage'},context);
|
|
257
|
+
if(fingerprint(state)!==fingerprint(again))throw fail('stale','Repository changed during preparation.');
|
|
258
|
+
const snapshot=Object.freeze({path:selected,head:state.commit,index:Object.freeze({oid:state.selected.oid,mode:state.selected.mode}),target,fingerprint:fingerprint(state)});
|
|
259
|
+
stagedIssued.set(snapshot,{state,selected,bytes,target});return snapshot;
|
|
260
|
+
}
|
|
261
|
+
/** Internal only: a process-local plan pins the ENTIRE repository capture.
|
|
262
|
+
* Only partial plans permit selected MM; modes and all other guards stay pinned.
|
|
263
|
+
* The model exposes frozen display data, never retained source/candidate buffers.
|
|
264
|
+
*/
|
|
265
|
+
export async function preparePartialIndexStage(repo,options={}){return preparePartialIndex(repo,options,'stage');}
|
|
266
|
+
export async function preparePartialIndexUnstage(repo,options={}){return preparePartialIndex(repo,options,'unstage');}
|
|
267
|
+
export async function prepareLineIndexStage(repo,options={}){return preparePartialIndex(repo,options,'stage',true);}
|
|
268
|
+
export async function prepareLineIndexUnstage(repo,options={}){return preparePartialIndex(repo,options,'unstage',true);}
|
|
269
|
+
async function preparePartialIndex(repo,{id,signal},operation,line=false){
|
|
270
|
+
if(typeof id!=='string'||!/^[a-f0-9]{64}$/.test(id))throw fail('stale','An exact '+(operation==='stage'?'unstaged':'staged')+' selection ID is required.');
|
|
271
|
+
const context={};
|
|
272
|
+
const partialMM=true; // Private policy: never sourced from public arguments/snapshots.
|
|
273
|
+
const state=await capture(repo,undefined,signal,{id,operation,partialMM},context),selected=state.selected.path;
|
|
274
|
+
check(signal);
|
|
275
|
+
// Fixed OID only: safe Git disables replacements, lazy fetch and inherited overrides.
|
|
276
|
+
// Read one extra byte to reject rather than truncate at the exact model bound.
|
|
277
|
+
const before=await git(state.root,['cat-file','blob',state.selected.oid],MAX_PARTIAL_INDEX_BYTES+1,{signal});
|
|
278
|
+
check(signal);
|
|
279
|
+
if(before.length>MAX_PARTIAL_INDEX_BYTES)throw fail('unsupported','Index blob exceeds 256KiB.');
|
|
280
|
+
const oid=createHash(state.objectFormat).update(Buffer.from('blob '+before.length+'\0')).update(before).digest('hex');
|
|
281
|
+
if(oid!==state.selected.oid)throw fail('stale','Fixed Index blob identity changed.');
|
|
282
|
+
let after;
|
|
283
|
+
if(operation==='unstage'){
|
|
284
|
+
after=await git(state.root,['cat-file','blob',state.head.oid],MAX_PARTIAL_INDEX_BYTES+1,{signal});check(signal);
|
|
285
|
+
if(after.length>MAX_PARTIAL_INDEX_BYTES)throw fail('unsupported','HEAD blob exceeds 256KiB.');
|
|
286
|
+
if(createHash(state.objectFormat).update(Buffer.from('blob '+after.length+'\0')).update(after).digest('hex')!==state.head.oid)throw fail('stale','Fixed HEAD blob identity changed.');
|
|
287
|
+
}else after=Buffer.from(state.capturedBytes);
|
|
288
|
+
const plan=(line?createLineIndexPlan:createPartialIndexPlan)(before,after,{signal});
|
|
289
|
+
if(!plan.units.length)throw fail('unsupported','Partial '+operation+' has no changes.');
|
|
290
|
+
const again=await capture(repo,selected,signal,{operation,partialMM},context);
|
|
291
|
+
if(fingerprint(state)!==fingerprint(again))throw fail('stale','Repository changed during preparation.');
|
|
292
|
+
check(signal);
|
|
293
|
+
const snapshot=Object.freeze({path:selected,head:state.commit,index:Object.freeze({oid:state.selected.oid,mode:state.selected.mode}),plan,fingerprint:fingerprint(state)});
|
|
294
|
+
const grants=line?(operation==='stage'?lineStagePlans:lineUnstagePlans):(operation==='stage'?partialIssued:partialUnstageIssued);
|
|
295
|
+
grants.set(snapshot,{state,selected,before:Buffer.from(before),after,plan,partialMM});return snapshot;
|
|
296
|
+
}
|
|
297
|
+
/** Single-use selection; only this exact frozen plan grant can issue a direction-specific grant.
|
|
298
|
+
* Capture remains the original FULL work, while only private candidate bytes are
|
|
299
|
+
* passed to the shared append-only publisher and its target postchecks.
|
|
300
|
+
*/
|
|
301
|
+
export async function selectPartialIndexStage(repo,options={}){return selectPartialIndex(repo,options,'stage');}
|
|
302
|
+
export async function selectPartialIndexUnstage(repo,options={}){return selectPartialIndex(repo,options,'unstage');}
|
|
303
|
+
async function selectPartialIndex(repo,{snapshot,unitIds,signal},operation){
|
|
304
|
+
const grants=operation==='stage'?partialIssued:partialUnstageIssued;
|
|
305
|
+
const saved=snapshot&&grants.get(snapshot);
|
|
306
|
+
if(!saved)throw fail('stale','A server-issued partial plan snapshot is required.');
|
|
307
|
+
grants.delete(snapshot);
|
|
308
|
+
const {state,selected,before,after,plan,partialMM}=saved;
|
|
309
|
+
check(signal);
|
|
310
|
+
if(!Object.isFrozen(snapshot)||snapshot.plan!==plan||!Object.isFrozen(plan))throw fail('stale','Partial plan binding changed.');
|
|
311
|
+
if(!Array.isArray(unitIds)||!unitIds.length||unitIds.length>plan.units.length)throw fail('invalid','Select nonempty unique known unit IDs.');
|
|
312
|
+
// Copy before the first await; later caller edits cannot alter this selection.
|
|
313
|
+
const ids=[];
|
|
314
|
+
for(let i=0;i<unitIds.length;i++){
|
|
315
|
+
const descriptor=Object.getOwnPropertyDescriptor(unitIds,String(i));
|
|
316
|
+
if(!descriptor||!Object.hasOwn(descriptor,'value')||typeof descriptor.value!=='string')throw fail('invalid','Invalid unit IDs.');
|
|
317
|
+
ids.push(descriptor.value);
|
|
318
|
+
}
|
|
319
|
+
const known=new Set(plan.units.map(unit=>unit.id));
|
|
320
|
+
if(new Set(ids).size!==ids.length||ids.some(id=>!known.has(id)))throw fail('invalid','Unknown or duplicate unit IDs.');
|
|
321
|
+
const fresh=await capture(repo,selected,signal,{operation,partialMM},{});
|
|
322
|
+
if(fingerprint(fresh)!==fingerprint(state))throw fail('stale','Repository snapshot changed.');
|
|
323
|
+
const bytes=applyPartialIndexSelection(before,after,plan,ids,{signal});
|
|
324
|
+
if(bytes.equals(before))throw fail('unsupported','Partial '+operation+' selection is a no-op.');
|
|
325
|
+
const target=Object.freeze({oid:createHash(state.objectFormat).update(Buffer.from('blob '+bytes.length+'\0')).update(bytes).digest('hex'),mode:state.selected.mode});
|
|
326
|
+
stageCandidate(state,selected,target);check(signal);
|
|
327
|
+
const selectedIds=Object.freeze([...ids]);
|
|
328
|
+
const result=Object.freeze({path:selected,head:state.commit,index:snapshot.index,target,planId:plan.id,unitIds:selectedIds,fingerprint:fingerprint(state)});
|
|
329
|
+
(operation==='stage'?stagedIssued:unstagedPartialIssued).set(result,{state,selected,bytes,target,partialMM});return result;
|
|
330
|
+
}
|
|
331
|
+
/** LINE uses the same exact capture and publisher, but isolated capabilities. */
|
|
332
|
+
export async function selectLineIndexStage(repo,options={}){return selectLineIndex(repo,options,'stage');}
|
|
333
|
+
export async function selectLineIndexUnstage(repo,options={}){return selectLineIndex(repo,options,'unstage');}
|
|
334
|
+
async function selectLineIndex(repo,{snapshot,operationIds,signal},operation){
|
|
335
|
+
const grants=operation==='stage'?lineStagePlans:lineUnstagePlans;
|
|
336
|
+
const saved=snapshot&&grants.get(snapshot);
|
|
337
|
+
if(!saved)throw fail('stale','A server-issued line plan snapshot is required.');
|
|
338
|
+
grants.delete(snapshot); // Even a rejected selection consumes the plan.
|
|
339
|
+
const {state,selected,before,after,plan,partialMM}=saved;
|
|
340
|
+
check(signal);
|
|
341
|
+
if(!Object.isFrozen(snapshot)||snapshot.plan!==plan||!Object.isFrozen(plan))throw fail('stale','Line plan binding changed.');
|
|
342
|
+
if(!Array.isArray(operationIds)||Object.getPrototypeOf(operationIds)!==Array.prototype)throw fail('invalid','Select nonempty unique known operation IDs.');
|
|
343
|
+
const length=Object.getOwnPropertyDescriptor(operationIds,'length').value;
|
|
344
|
+
if(!length||length>plan.operations.length||Reflect.ownKeys(operationIds).length!==length+1)throw fail('invalid','Invalid operation IDs.');
|
|
345
|
+
// Own data only, copied before the first await (never run caller getters).
|
|
346
|
+
const ids=[],known=new Set(plan.operations.map(item=>item.id));
|
|
347
|
+
for(let i=0;i<length;i++){
|
|
348
|
+
const descriptor=Object.getOwnPropertyDescriptor(operationIds,String(i));
|
|
349
|
+
if(!descriptor||!Object.hasOwn(descriptor,'value')||!descriptor.enumerable||typeof descriptor.value!=='string'||!known.has(descriptor.value))throw fail('invalid','Unknown operation ID.');
|
|
350
|
+
ids.push(descriptor.value);
|
|
351
|
+
}
|
|
352
|
+
if(new Set(ids).size!==ids.length)throw fail('invalid','Duplicate operation IDs.');
|
|
353
|
+
const fresh=await capture(repo,selected,signal,{operation,partialMM},{});
|
|
354
|
+
if(fingerprint(fresh)!==fingerprint(state))throw fail('stale','Repository snapshot changed.');
|
|
355
|
+
const bytes=applyLineIndexSelection(before,after,plan,ids,{signal});
|
|
356
|
+
if(bytes.equals(before))throw fail('unsupported','Line '+operation+' selection is a no-op.');
|
|
357
|
+
const target=Object.freeze({oid:createHash(state.objectFormat).update(Buffer.from('blob '+bytes.length+'\0')).update(bytes).digest('hex'),mode:state.selected.mode});
|
|
358
|
+
stageCandidate(state,selected,target);check(signal);
|
|
359
|
+
const result=Object.freeze({path:selected,head:state.commit,index:snapshot.index,target,planId:plan.id,operationIds:Object.freeze([...ids]),fingerprint:fingerprint(state)});
|
|
360
|
+
(operation==='stage'?lineStageIssued:lineUnstageIssued).set(result,{state,selected,bytes,target,partialMM});return result;
|
|
361
|
+
}
|
|
362
|
+
export async function applyLineIndexStage(repo,options={}){return publishCapturedIndex(repo,options,lineStageIssued,'stage');}
|
|
363
|
+
export async function applyLineIndexUnstage(repo,options={}){return publishCapturedIndex(repo,options,lineUnstageIssued,'unstage');}
|
|
364
|
+
/** Append the captured raw blob, then publish a one-tuple Index CAS. After onStart,
|
|
365
|
+
* any failure is unknown: an append-only object can remain even if Index is unchanged.
|
|
366
|
+
* Same conservative bounds/configuration refusals as unstage. No rollback or GC.
|
|
367
|
+
*/
|
|
368
|
+
export async function applyIndexStage(repo,options={}){return publishCapturedIndex(repo,options,stagedIssued,'stage');}
|
|
369
|
+
export async function applyPartialIndexUnstage(repo,options={}){return publishCapturedIndex(repo,options,unstagedPartialIssued,'unstage');}
|
|
370
|
+
async function publishCapturedIndex(repo,{snapshot,signal,assertAuthorized,onStart},grants,operation){
|
|
371
|
+
const context={};let started=false;
|
|
372
|
+
const start=()=>{if(!started){started=true;check(signal);const result=onStart();if(result&&typeof result.then==='function'){Promise.resolve(result).catch(()=>{});throw fail('invalid','onStart must be synchronous.');}}};
|
|
373
|
+
try{
|
|
374
|
+
const saved=snapshot&&grants.get(snapshot);
|
|
375
|
+
if(!saved||typeof assertAuthorized!=='function'||typeof onStart!=='function')throw fail('stale','A server-issued '+operation+' snapshot and callbacks are required.');
|
|
376
|
+
const {state,selected,bytes,target,partialMM=false}=saved;
|
|
377
|
+
const authorize=async()=>{check(signal);await assertAuthorized();check(signal);};
|
|
378
|
+
await authorize();
|
|
379
|
+
let baseline=state;
|
|
380
|
+
const revalidate=async(allowLock=true)=>{const fresh=await capture(repo,selected,signal,{allowLock,operation,partialMM},context);if(fingerprint(fresh)!==fingerprint(baseline))throw fail('stale','Repository snapshot changed.');return fresh;};
|
|
381
|
+
await revalidate(false);
|
|
382
|
+
const expected=stageCandidate(state,selected,target);
|
|
383
|
+
const result=await withOwnedIndexLock({gitDirectory:state.directory,expectedIndexDigest:state.index.digest,signal},async lock=>{
|
|
384
|
+
if(!(await lock.readIndex()).equals(state.bytes))throw fail('stale','Raw Index changed.');
|
|
385
|
+
await revalidate();await authorize();await revalidate();
|
|
386
|
+
// Do not capture metadata from store callbacks: the primitive temporarily owns
|
|
387
|
+
// a temp path and a second hardlink. Inspect the complete tree after cleanup.
|
|
388
|
+
const stored=await storeCapturedBlob({gitDirectory:state.directory,objectFormat:state.objectFormat,bytes,signal,assertAuthorized:authorize,onStart:start});
|
|
389
|
+
if(stored.oid!==target.oid)throw fail('stale','Captured blob identity changed.');
|
|
390
|
+
// Existing correct objects do not notify the store callback. Notify before
|
|
391
|
+
// final full-state validation so callback mutations cannot evade the CAS.
|
|
392
|
+
start();check(signal);
|
|
393
|
+
const fresh=await capture(repo,selected,signal,{allowLock:true,operation,partialMM},context);
|
|
394
|
+
const old=new Map(state.metadataRows),fanout='objects/'+target.oid.slice(0,2),object=fanout+'/'+target.oid.slice(2);
|
|
395
|
+
const permitted=new Set(stored.created?[fanout,object]:[]);
|
|
396
|
+
// Only absent exact target/fanout rows may be added. All old rows, including
|
|
397
|
+
// every other object, remain pinned. Never wholesale rebaseline objects.
|
|
398
|
+
const retained=fresh.metadataRows.filter(([name])=>old.has(name)||!permitted.has(name));
|
|
399
|
+
if(json(retained)!==json(state.metadataRows))throw fail('stale','Foreign repository metadata mutation during blob append.');
|
|
400
|
+
const loose=await readPlain(path.join(state.directory,...object.split('/')),MAX_FILE+65536,signal);
|
|
401
|
+
const raw=Buffer.concat([Buffer.from('blob '+bytes.length+'\0'),bytes]);
|
|
402
|
+
const inflated=inflateSync(loose.bytes,{maxOutputLength:raw.length,info:true});
|
|
403
|
+
if(inflated.engine.bytesWritten!==loose.bytes.length||!inflated.buffer.equals(raw)||!fresh.metadataRows.some(([name,row])=>name===object&&json(row)===json(loose.identity)))throw fail('stale','Stored target blob changed.');
|
|
404
|
+
const metadataRows=fresh.metadataRows,metadataHash=hash(json(metadataRows));
|
|
405
|
+
baseline={...state,metadataRows,metadataHash};
|
|
406
|
+
if(fingerprint(fresh)!==fingerprint(baseline))throw fail('stale','Repository changed during blob append.');
|
|
407
|
+
await lock.writeCandidate(expected);
|
|
408
|
+
let indexPublishStarted=false;
|
|
409
|
+
await lock.publish({assertAuthorized:async()=>{await authorize();if(!indexPublishStarted)await revalidate();},beforePublish:async()=>{await revalidate();},onStart:()=>{indexPublishStarted=true;return start();}});
|
|
410
|
+
const after=await capture(repo,selected,signal,{published:true,operation,partialMM},context);
|
|
411
|
+
const entries=parseGitIndex(expected,{objectFormat:state.objectFormat}).entries;
|
|
412
|
+
const published={...baseline,index:after.index,entries,selected:entries.find(e=>e.path===selected)};
|
|
413
|
+
if(!after.bytes.equals(expected)||fingerprint(after)!==fingerprint(published))throw fail('stale','Post-publication verification failed.');
|
|
414
|
+
await authorize();return {path:selected,head:state.commit,index:{...target}};
|
|
415
|
+
});
|
|
416
|
+
check(signal);return result;
|
|
417
|
+
}catch(error){if(!started)throw error;throw Object.assign(fail('outcome-unknown','Append-only object may remain and Index publication may have occurred; refresh and do not retry blindly.'),{outcomeUnknown:true,appendOnly:true,cause:error});}
|
|
418
|
+
}
|