2026-07-12 21:12:18 +00:00
import { createHash } from "node:crypto" ;
import { constants } from "node:fs" ;
2026-09-08 10:59:13 +08:00
import {
mkdir ,
open ,
2026-10-10 15:21:16 +08:00
readdir ,
2026-09-08 10:59:13 +08:00
realpath ,
type FileHandle ,
} from "node:fs/promises" ;
2026-07-12 21:12:18 +00:00
import { basename , dirname , isAbsolute , join , resolve } from "node:path" ;
import type { Readable } from "node:stream" ;
2026-10-11 05:16:30 +08:00
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js" ;
2026-07-12 21:12:18 +00:00
import { streamChunkToBuffer } from "./StreamBytes.js" ;
import {
ArtifactPathRegistry ,
2026-10-10 15:21:16 +08:00
destinationCaseCollisionMessage ,
2026-07-12 21:12:18 +00:00
normalizeArtifactPath ,
} from "./ArtifactPaths.js" ;
2026-09-29 12:15:49 +08:00
import { ArtifactReaderFailure } from "./ArtifactReader.js" ;
2026-10-11 05:16:30 +08:00
import { SafeOutputTreeCreationFailure } from "./SafeOutputTreeCreationFailure.js" ;
import { hashOutputFile } from "./SafeOutputTreeReadback.js" ;
2026-10-11 03:14:18 +08:00
import { removeOwnedTree } from "./SafeOutputTreeCleanup.js" ;
import {
assertHandleIdentity ,
assertFilePathIdentity ,
assertPathIdentity ,
isAbsent ,
readDirectoryIdentity ,
readFileIdentity ,
replacedDirectory ,
type DirectoryIdentity ,
type FileIdentity ,
} from "./SafeOutputTreeIdentity.js" ;
2026-07-12 21:12:18 +00:00
2026-07-12 21:45:26 +00:00
/** One file durably written to an operation-owned output tree. */
2026-07-12 21:12:18 +00:00
export interface SafeOutputFile {
readonly relativePath : string ;
readonly sha256 : string ;
readonly bytesWritten : number ;
}
2026-08-10 02:28:11 +08:00
/** Cleanup state established while rolling back an uncommitted tree. */
export type SafeOutputCleanup =
| { readonly status : "not-required" }
| { readonly status : "complete" ; readonly residualPaths : readonly [] }
| {
readonly status : "incomplete" ;
readonly residualPaths : readonly [ string , ... string []];
};
2026-07-12 21:12:18 +00:00
2026-10-11 03:14:18 +08:00
/**
* Materialize files in a tree created by this operation.
*
* Path identities are revalidated around operations, but Node has no portable
* descriptor-relative traversal; a syscall-boundary pathname race remains.
*/
2026-07-12 21:12:18 +00:00
export class SafeOutputTree {
readonly # registry = new ArtifactPathRegistry ();
readonly # outputRoot : string ;
2026-10-11 05:16:30 +08:00
# rootIdentity : DirectoryIdentity | undefined ;
2026-10-11 03:14:18 +08:00
readonly # nestedDirectories = new Map < string , DirectoryIdentity >();
2026-10-11 05:16:30 +08:00
readonly # unknownDirectories = new Set < string >();
2026-10-11 03:14:18 +08:00
readonly # ownedFiles = new Map < string , FileIdentity >();
2026-10-11 05:16:30 +08:00
readonly # openFiles = new Map < string , OwnedFileHandle >();
readonly # openHandles = new Set < OwnedFileHandle >();
2026-07-12 21:12:18 +00:00
# published = false ;
# cleanup : SafeOutputCleanup = {
2026-08-10 02:28:11 +08:00
status : "not-required" ,
2026-07-12 21:12:18 +00:00
};
2026-10-07 00:46:52 +07:00
private constructor (
outputRoot : string ,
private readonly platform : NodeJS.Platform ,
) {
2026-07-12 21:12:18 +00:00
this . # outputRoot = outputRoot ;
}
2026-10-07 00:46:52 +07:00
/**
* Exclusively create the absent destination as this operation's owned tree.
*
* POSIX mode bits and directory `fchmod`/`fsync` have no Windows equivalent:
* `mkdir` already applies the requested mode, so the redundant handle
* `chmod` is skipped there to avoid an `EPERM` on the directory descriptor.
*/
static async create (
outputRoot : string ,
platform : NodeJS.Platform = process . platform ,
) : Promise < SafeOutputTree > {
2026-07-12 21:12:18 +00:00
if ( ! isAbsolute ( outputRoot ))
throw new ArtifactReaderFailure (
"path" ,
"Extraction output root must be absolute" ,
);
const requested = resolve ( outputRoot );
const name = basename ( requested );
if ( name === "." || name === ".." )
throw new ArtifactReaderFailure ( "path" , "Invalid extraction output root" );
const parent = await realpath ( dirname ( requested )). catch (
( cause : unknown ) => {
throw new ArtifactReaderFailure (
"unavailable" ,
"Extraction output parent is unavailable" ,
{ cause },
);
},
);
const canonicalOutput = join ( parent , name );
await mkdir ( canonicalOutput , { mode : 0o700 }). catch (( cause : unknown ) => {
if ( isAlreadyExists ( cause ))
throw new ArtifactReaderFailure (
"path" ,
"Extraction output root already exists" ,
{ cause },
);
throw cause ;
});
2026-10-11 05:16:30 +08:00
const tree = new SafeOutputTree ( canonicalOutput , platform );
2026-07-12 21:12:18 +00:00
try {
2026-10-11 05:16:30 +08:00
const rootIdentity = await readDirectoryIdentity ( canonicalOutput );
tree . # rootIdentity = rootIdentity ;
2026-10-07 00:46:52 +07:00
if ( platform !== "win32" ) {
2026-10-11 05:16:30 +08:00
const stagingHandle = tree . # trackHandle (
await open (
canonicalOutput ,
constants . O_RDONLY | constants . O_DIRECTORY ,
),
2026-10-07 00:46:52 +07:00
);
2026-10-11 05:16:30 +08:00
let setup :
| { readonly kind : "ready" }
| {
readonly kind : "failed" ;
readonly cause : unknown ;
} = { kind : "ready" };
2026-10-07 00:46:52 +07:00
try {
2026-10-11 03:14:18 +08:00
await assertHandleIdentity (
2026-10-11 05:16:30 +08:00
stagingHandle . handle ,
2026-10-11 03:14:18 +08:00
rootIdentity ,
canonicalOutput ,
);
2026-10-11 05:16:30 +08:00
await stagingHandle . handle . chmod ( 0 o700 );
} catch ( cause : unknown ) {
setup = { kind : "failed" , cause };
2026-10-07 00:46:52 +07:00
}
2026-10-11 05:16:30 +08:00
try {
await tree . # closeHandle ( stagingHandle );
} catch ( closeCause : unknown ) {
if ( setup . kind === "failed" )
throw ArtifactReaderFailure . withCleanup (
setup . cause ,
ArtifactReaderFailure . cleanupObservation (
closeCause ,
canonicalOutput ,
),
);
throw closeCause ;
}
if ( setup . kind === "failed" ) throw setup . cause ;
2026-07-12 21:12:18 +00:00
}
2026-10-11 03:14:18 +08:00
await assertPathIdentity ( canonicalOutput , rootIdentity );
2026-10-11 05:16:30 +08:00
return tree ;
2026-07-12 21:12:18 +00:00
} catch ( cause : unknown ) {
2026-10-11 05:16:30 +08:00
throw new SafeOutputTreeCreationFailure ( cause , tree );
2026-07-12 21:12:18 +00:00
}
}
get outputRoot () : string {
return this . # outputRoot ;
}
2026-10-11 05:16:30 +08:00
/** The output was durably committed, even if descriptor cleanup later failed. */
get published () : boolean {
return this . # published ;
}
2026-07-12 21:12:18 +00:00
get cleanup () : SafeOutputCleanup {
2026-07-14 14:39:02 +08:00
return structuredClone ( this . # cleanup );
2026-07-12 21:12:18 +00:00
}
2026-09-29 12:15:49 +08:00
/** Stream one regular file with exact byte and digest verification. */
2026-07-12 21:12:18 +00:00
async write (
relativePath : string ,
source : Readable ,
2026-10-11 00:03:18 +08:00
expected : { readonly sha256 : string ; readonly bytes : number },
2026-07-12 21:12:18 +00:00
signal? : AbortSignal ,
) : Promise < SafeOutputFile > {
try {
2026-10-11 00:03:18 +08:00
this . # assertWritable ();
if ( ! Number . isSafeInteger ( expected . bytes ) || expected . bytes < 0 )
2026-07-12 21:12:18 +00:00
throw new ArtifactReaderFailure (
2026-10-11 00:03:18 +08:00
"format" ,
`Invalid expected extraction size for ${ relativePath } ` ,
);
2026-10-11 07:10:45 +08:00
const path = normalizeDestinationPath ( relativePath , this . platform );
2026-10-11 00:03:18 +08:00
this . # registry . add ( path , "file" );
2026-10-11 03:14:18 +08:00
const lineage = await this . # prepareParent ( path );
const parent = lineage . at ( - 1 );
if ( parent === undefined ) throw replacedDirectory ( this . # outputRoot );
const fileName = path . slice ( path . lastIndexOf ( "/" ) + 1 );
const destination = join ( parent . path , fileName );
2026-10-11 00:03:18 +08:00
const handle = await open (
destination ,
constants . O_CREAT |
constants . O_EXCL |
constants . O_WRONLY |
constants . O_NOFOLLOW ,
0 o600 ,
). catch ( async ( cause : unknown ) => {
2026-10-11 03:14:18 +08:00
await throwIfDestinationCaseCollision ( parent . path , path , cause );
2026-07-12 21:12:18 +00:00
throw new ArtifactReaderFailure (
2026-10-11 00:03:18 +08:00
"path" ,
`Could not exclusively create extraction path: ${ path } ` ,
{ cause },
2026-07-12 21:12:18 +00:00
);
2026-10-11 00:03:18 +08:00
});
2026-10-11 05:16:30 +08:00
const ownedHandle = this . # trackHandle ( handle );
this . # openFiles . set ( destination , ownedHandle );
const fileIdentity = await readFileIdentity (
ownedHandle . handle ,
destination ,
2026-10-11 03:14:18 +08:00
);
2026-10-11 05:16:30 +08:00
await assertFilePathIdentity ( destination , fileIdentity );
2026-10-11 03:14:18 +08:00
this . # ownedFiles . set ( destination , fileIdentity );
2026-10-11 00:03:18 +08:00
const hash = createHash ( "sha256" );
let bytes = 0 ;
2026-10-11 05:16:30 +08:00
await this . # assertLineage ( lineage );
for await ( const raw of source ) {
abortIfNeeded ( signal );
const chunk = streamChunkToBuffer ( raw );
if ( chunk . length > expected . bytes - bytes )
2026-10-11 00:03:18 +08:00
throw new ArtifactReaderFailure (
"integrity" ,
2026-10-11 05:16:30 +08:00
`Extracted content exceeds the inventoried size: ${ path } ` ,
2026-10-11 00:03:18 +08:00
);
2026-10-11 05:16:30 +08:00
bytes += chunk . length ;
hash . update ( chunk );
await writeAll ( ownedHandle . handle , chunk );
2026-10-11 00:03:18 +08:00
}
2026-10-11 05:16:30 +08:00
if ( bytes !== expected . bytes )
throw new ArtifactReaderFailure (
"integrity" ,
`Extracted content size disagrees with inventory: ${ path } ` ,
);
const sha256 = hash . digest ( "hex" );
if ( sha256 !== expected . sha256 )
throw new ArtifactReaderFailure (
"integrity" ,
`Extracted content disagrees with inventory: ${ path } ` ,
);
await this . # assertLineage ( lineage );
await assertFilePathIdentity ( destination , fileIdentity );
await ownedHandle . handle . sync ();
await this . # closeFileHandle ( destination , ownedHandle );
const readbackHandle = this . # trackHandle (
await open ( destination , constants . O_RDONLY | constants . O_NOFOLLOW ),
);
const readback = await hashOutputFile (
readbackHandle ,
destination ,
fileIdentity ,
{ maximum : bytes , signal },
);
await this . # closeHandle ( readbackHandle );
await this . # assertLineage ( lineage );
await assertFilePathIdentity ( destination , fileIdentity );
if ( readback . sha256 !== sha256 || readback . bytes !== bytes )
throw new ArtifactReaderFailure (
"integrity" ,
`Durable readback verification failed: ${ path } ` ,
);
return { relativePath : path , sha256 , bytesWritten : bytes };
2026-07-12 21:12:18 +00:00
} catch ( cause : unknown ) {
2026-10-11 00:03:18 +08:00
try {
source . destroy ();
} catch {
// Preserve the write refusal or failure as the caller-visible error.
}
2026-07-12 21:12:18 +00:00
throw cause ;
}
}
2026-07-12 21:45:26 +00:00
/** Sync the owned output tree and prevent further writes through this instance. */
2026-10-13 15:12:17 +08:00
async commit ( signal? : AbortSignal ) : Promise < void > {
2026-07-12 21:12:18 +00:00
this . # assertWritable ();
2026-10-13 15:12:17 +08:00
abortIfNeeded ( signal );
2026-10-11 03:14:18 +08:00
await this . # assertOwnedDirectories ();
2026-10-13 15:12:17 +08:00
abortIfNeeded ( signal );
2026-10-07 00:46:52 +07:00
// Windows has no directory fsync; file contents are already synced in write().
if ( this . platform === "win32" ) {
this . # published = true ;
return ;
}
2026-10-11 05:16:30 +08:00
const parent = this . # trackHandle (
await open (
dirname ( this . # outputRoot ),
constants . O_RDONLY | constants . O_DIRECTORY ,
),
2026-07-12 21:12:18 +00:00
);
2026-10-11 05:16:30 +08:00
let output : OwnedFileHandle | undefined ;
let sync :
| { readonly kind : "synced" }
| {
readonly kind : "failed" ;
readonly cause : unknown ;
} = { kind : "synced" };
2026-07-12 21:12:18 +00:00
try {
2026-10-11 05:16:30 +08:00
output = this . # trackHandle (
await open (
this . # outputRoot ,
constants . O_RDONLY | constants . O_DIRECTORY ,
),
);
await assertHandleIdentity (
output . handle ,
this . # requireRootIdentity (),
2026-09-08 10:59:13 +08:00
this . # outputRoot ,
);
2026-10-11 05:16:30 +08:00
await output . handle . sync ();
await parent . handle . sync ();
2026-10-13 15:12:17 +08:00
abortIfNeeded ( signal );
2026-07-12 21:12:18 +00:00
this . # published = true ;
} catch ( cause : unknown ) {
2026-10-11 05:16:30 +08:00
sync = { kind : "failed" , cause };
}
const closeResults = await Promise . allSettled (
[ parent , output ]
. filter ( isDefined )
. map (( handle ) => this . # closeHandle ( handle )),
);
const closeFailures = closeResults
. filter ( isRejected )
. map (({ reason }) => reason );
if ( closeFailures . length > 0 ) {
const closeFailure = new AggregateError (
closeFailures ,
"Extraction output directory handles could not be closed" ,
);
const cleanup = ArtifactReaderFailure . cleanupObservation (
closeFailure ,
this . # outputRoot ,
);
2026-10-13 15:12:17 +08:00
if ( sync . kind === "failed" ) {
const primary = isCancellationFailure ( sync . cause )
? sync.cause
: new ArtifactReaderFailure (
"path" ,
"Could not durably sync extraction output" ,
{ cause : sync.cause },
);
throw ArtifactReaderFailure . withCleanup ( primary , cleanup );
}
2026-10-11 05:16:30 +08:00
throw ArtifactReaderFailure . withCleanup ( closeFailure , cleanup );
}
2026-10-13 15:12:17 +08:00
if ( sync . kind === "failed" ) {
if ( isCancellationFailure ( sync . cause )) throw sync . cause ;
2026-07-12 21:12:18 +00:00
throw new ArtifactReaderFailure (
"path" ,
2026-07-12 21:45:26 +00:00
"Could not durably sync extraction output" ,
2026-10-11 05:16:30 +08:00
{ cause : sync.cause },
2026-07-12 21:12:18 +00:00
);
2026-10-13 15:12:17 +08:00
}
2026-07-12 21:12:18 +00:00
}
2026-07-12 21:45:26 +00:00
/** Remove only this operation's unsealed tree and verify absence. */
2026-07-12 21:12:18 +00:00
async rollback () : Promise < SafeOutputCleanup > {
2026-10-11 05:16:30 +08:00
if ( this . # published ) {
await this . # closePendingHandles ();
return structuredClone ( this . # cleanup );
}
if ( this . # cleanup . status === "complete" )
2026-10-11 03:14:18 +08:00
return structuredClone ( this . # cleanup );
this . # cleanup = {
status : "incomplete" ,
residualPaths : [ basename ( this . # outputRoot )],
};
2026-10-09 21:01:52 +08:00
let removalFailure : unknown ;
try {
2026-10-11 05:16:30 +08:00
await this . # admitPendingFiles ();
await this . # closePendingHandles ();
2026-10-11 03:14:18 +08:00
await this . # assertOwnedDirectories ();
await removeOwnedTree ({
outputRoot : this. # outputRoot ,
2026-10-11 05:16:30 +08:00
rootIdentity : this. # requireRootIdentity (),
2026-10-11 03:14:18 +08:00
directories : this. # nestedDirectories ,
files : this. # ownedFiles ,
});
2026-10-09 21:01:52 +08:00
} catch ( cause : unknown ) {
removalFailure = cause ;
}
2026-10-11 03:14:18 +08:00
const absent =
removalFailure === undefined && ( await isAbsent ( this . # outputRoot ));
2026-08-10 02:28:11 +08:00
this . # cleanup = absent
? { status : "complete" , residualPaths : [] }
: {
status : "incomplete" ,
2026-09-08 10:59:13 +08:00
residualPaths : [ basename ( this . # outputRoot )],
2026-08-10 02:28:11 +08:00
};
2026-07-12 21:12:18 +00:00
if ( ! absent )
throw new ArtifactReaderFailure (
"integrity" ,
2026-10-09 21:01:52 +08:00
`Extraction output cleanup could not be verified ${ removalFailure === undefined ? "" : `: ${ removalFailure instanceof Error ? removalFailure.message : String ( removalFailure ) } ` } ` ,
{
cause : removalFailure ,
cleanup : {
reason :
removalFailure instanceof Error
? removalFailure . message
: "Extraction output root remains after rollback" ,
resources : [ this . # outputRoot ],
},
},
2026-07-12 21:12:18 +00:00
);
2026-07-14 14:39:02 +08:00
return structuredClone ( this . # cleanup );
2026-07-12 21:12:18 +00:00
}
2026-10-11 03:14:18 +08:00
async # prepareParent (
relativePath : string ,
) : Promise < readonly DirectoryLineageEntry [] > {
2026-07-12 21:12:18 +00:00
const parts = relativePath . split ( "/" );
2026-10-11 03:14:18 +08:00
if ( parts . pop () === undefined )
2026-07-12 21:12:18 +00:00
throw new ArtifactReaderFailure ( "path" , "Invalid extraction path" );
2026-09-08 10:59:13 +08:00
let current = this . # outputRoot ;
2026-10-10 15:21:16 +08:00
let logicalParent = "" ;
2026-10-11 03:14:18 +08:00
const lineage : DirectoryLineageEntry [] = [
2026-10-11 05:16:30 +08:00
{ path : this. # outputRoot , identity : this. # requireRootIdentity () },
2026-10-11 03:14:18 +08:00
];
if ( parts . length === 0 )
2026-10-11 05:16:30 +08:00
await assertPathIdentity ( this . # outputRoot , this . # requireRootIdentity ());
2026-07-12 21:12:18 +00:00
for ( const part of parts ) {
2026-10-11 03:14:18 +08:00
const parent = lineage . at ( - 1 );
if ( parent === undefined ) throw replacedDirectory ( this . # outputRoot );
2026-10-10 15:21:16 +08:00
const logicalPath =
logicalParent . length === 0 ? part : ` ${ logicalParent } / ${ part } ` ;
2026-07-12 21:12:18 +00:00
current = join ( current , part );
2026-10-11 03:14:18 +08:00
await assertPathIdentity ( parent . path , parent . identity );
2026-10-10 15:21:16 +08:00
let created = true ;
2026-07-12 21:12:18 +00:00
await mkdir ( current , { mode : 0o700 }). catch (( cause : unknown ) => {
if ( ! isAlreadyExists ( cause )) throw cause ;
2026-10-10 15:21:16 +08:00
created = false ;
2026-07-12 21:12:18 +00:00
});
2026-10-11 03:14:18 +08:00
if ( ! created ) {
await throwIfDestinationCaseCollision ( parent . path , logicalPath );
const identity = this . # nestedDirectories . get ( current );
if ( identity === undefined ) throw replacedDirectory ( current );
await assertPathIdentity ( current , identity );
} else {
2026-10-11 05:16:30 +08:00
try {
const identity = await readDirectoryIdentity ( current );
this . # nestedDirectories . set ( current , identity );
} catch ( cause : unknown ) {
this . # unknownDirectories . add ( current );
throw cause ;
}
2026-10-10 15:21:16 +08:00
}
2026-10-11 03:14:18 +08:00
await assertPathIdentity ( parent . path , parent . identity );
const identity = this . # nestedDirectories . get ( current );
if ( identity === undefined ) throw replacedDirectory ( current );
await assertPathIdentity ( current , identity );
lineage . push ({ path : current , identity });
2026-10-10 15:21:16 +08:00
logicalParent = logicalPath ;
2026-07-12 21:12:18 +00:00
}
2026-10-11 03:14:18 +08:00
return lineage ;
}
async # assertLineage (
lineage : readonly DirectoryLineageEntry [],
) : Promise < void > {
for ( const { path , identity } of lineage )
await assertPathIdentity ( path , identity );
}
async # assertOwnedDirectories () : Promise < void > {
2026-10-11 05:16:30 +08:00
const rootIdentity = this . # requireRootIdentity ();
await assertPathIdentity ( this . # outputRoot , rootIdentity );
2026-10-11 03:14:18 +08:00
for ( const [ path , identity ] of this . # nestedDirectories )
await assertPathIdentity ( path , identity );
2026-10-11 05:16:30 +08:00
if ( this . # unknownDirectories . size > 0 )
throw new ArtifactReaderFailure (
"path" ,
`Extraction directory ownership is unknown: ${ [... this . # unknownDirectories ]. join ( ", " ) } ` ,
);
}
# requireRootIdentity () : DirectoryIdentity {
if ( this . # rootIdentity === undefined )
throw new ArtifactReaderFailure (
"path" ,
`Extraction output root identity is unknown: ${ this . # outputRoot } ` ,
);
return this . # rootIdentity ;
2026-07-12 21:12:18 +00:00
}
# assertWritable () : void {
if ( this . # published )
throw new ArtifactReaderFailure (
"integrity" ,
"Extraction tree is already committed" ,
);
2026-10-11 03:14:18 +08:00
if ( this . # cleanup . status !== "not-required" )
throw new ArtifactReaderFailure (
"integrity" ,
"Extraction tree cleanup has already started" ,
);
2026-07-12 21:12:18 +00:00
}
2026-10-11 05:16:30 +08:00
# trackHandle ( handle : FileHandle ) : OwnedFileHandle {
const owner = new OwnedFileHandle ( handle );
this . # openHandles . add ( owner );
return owner ;
}
async # closeHandle ( owner : OwnedFileHandle ) : Promise < void > {
await owner . close ();
this . # openHandles . delete ( owner );
}
async # closePendingHandles () : Promise < void > {
const failures : unknown [] = [];
for ( const owner of this . # openHandles ) {
try {
await this . # closeHandle ( owner );
} catch ( cause : unknown ) {
failures . push ( cause );
}
}
if ( failures . length > 0 )
throw new AggregateError ( failures , "Output tree handles remain open" );
}
async # closeFileHandle ( path : string , owner : OwnedFileHandle ) : Promise < void > {
await this . # closeHandle ( owner );
this . # openFiles . delete ( path );
}
async # admitPendingFiles () : Promise < void > {
for ( const [ path , owner ] of this . # openFiles ) {
let identity = this . # ownedFiles . get ( path );
if ( identity === undefined ) {
identity = await readFileIdentity ( owner . handle , path );
await assertFilePathIdentity ( path , identity );
this . # ownedFiles . set ( path , identity );
}
}
}
2026-07-12 21:12:18 +00:00
}
2026-10-11 05:16:30 +08:00
const isDefined = < T >( value : T | undefined ) : value is T => value !== undefined ;
const isRejected = (
result : PromiseSettledResult < void >,
) : result is PromiseRejectedResult => result . status === "rejected" ;
2026-10-11 03:14:18 +08:00
type DirectoryLineageEntry = {
readonly path : string ;
readonly identity : DirectoryIdentity ;
};
2026-07-12 21:12:18 +00:00
const writeAll = async (
handle : Awaited < ReturnType < typeof open >>,
chunk : Buffer ,
) : Promise < void > => {
let offset = 0 ;
while ( offset < chunk . length ) {
const { bytesWritten } = await handle . write (
chunk ,
offset ,
chunk . length - offset ,
);
if ( bytesWritten === 0 )
throw new ArtifactReaderFailure (
"unavailable" ,
"Extraction output stopped accepting bytes" ,
);
offset += bytesWritten ;
}
};
2026-10-11 07:10:45 +08:00
const normalizeDestinationPath = (
relativePath : string ,
platform : NodeJS.Platform ,
) : string => {
const path = normalizeArtifactPath ( relativePath );
2026-10-14 08:31:03 +08:00
if ( platform === "win32" && path . includes ( "\\" ))
throw new ArtifactReaderFailure (
"path" ,
`Windows destination cannot materialize artifact path: ${ JSON . stringify ( path ) } ; backslashes denote path separators.` ,
);
2026-10-11 07:10:45 +08:00
if ( platform === "win32" && path . includes ( ":" ))
throw new ArtifactReaderFailure (
"path" ,
`Windows destination cannot materialize artifact path as a regular file: ${ path } ; ':' denotes alternate data stream syntax.` ,
);
2026-10-13 06:05:20 -04:00
if ( platform === "win32" && /[\u0001-\u001f]/u.test(path))
throw new ArtifactReaderFailure (
"path" ,
`Windows destination cannot materialize artifact path: ${ JSON . stringify ( path ) } ; Windows names cannot contain U+0001-U+001F.` ,
);
2026-10-11 07:10:45 +08:00
return path ;
};
2026-10-11 05:16:30 +08:00
const abortIfNeeded = ( signal? : AbortSignal ) : void => {
if ( signal ? . aborted === true )
throw new ArtifactReaderFailure (
"cancelled" ,
"Artifact extraction cancelled" ,
);
};
2026-10-13 15:12:17 +08:00
const isCancellationFailure = (
cause : unknown ,
) : cause is ArtifactReaderFailure =>
cause instanceof ArtifactReaderFailure && cause . reason === "cancelled" ;
2026-07-12 21:12:18 +00:00
const isAlreadyExists = ( cause : unknown ) : boolean =>
cause instanceof Error && "code" in cause && cause . code === "EEXIST" ;
2026-10-10 15:21:16 +08:00
/** Fail when this directory already holds another spelling of the requested segment. */
const throwIfDestinationCaseCollision = async (
parentDirectory : string ,
logicalPath : string ,
cause? : unknown ,
) : Promise < void > => {
const names = await readdir ( parentDirectory ). catch (() => undefined );
if ( names === undefined ) return ;
const message = destinationCaseCollisionMessage ( logicalPath , names );
if ( message === undefined ) return ;
throw new ArtifactReaderFailure (
"path" ,
message ,
cause === undefined ? undefined : { cause },
);
};