@stacksjs/storage 0.75.551 → 0.75.555

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 CHANGED
@@ -61,6 +61,53 @@ expiry has passed. A bare signature has no known expiry. When capacity is full,
61
61
  revocation throws explicitly and preserves existing revocations; rotate
62
62
  `APP_KEY` or supply a durable application revocation store before retrying.
63
63
 
64
+ ## Recoverable local rename
65
+
66
+ `rename` and `move` return a Result. Inspect an error result before using the
67
+ destination:
68
+
69
+ ```ts
70
+ import { rename, StorageRenameRecoveryError } from '@stacksjs/storage/move'
71
+
72
+ const result = await rename(preparedDirectory, outputDirectory, { overwrite: true })
73
+ if (result.isErr) {
74
+ if (result.error instanceof StorageRenameRecoveryError)
75
+ console.error(result.error.phase, result.error.lock, result.error.backup)
76
+ throw result.error
77
+ }
78
+ ```
79
+
80
+ Overlapping source/destination trees are rejected, including existing parent
81
+ aliases. Ordinary files and empty directories use native rename directly. If
82
+ the OS refuses a directory/type replacement, the existing destination moves
83
+ into an owned sibling backup before installation. Installation failure restores
84
+ the previous entry and returns the original error. Successful replacement
85
+ replaces the entire entry, so stale output files do not survive.
86
+
87
+ An exclusive destination lock serializes cooperating callers. Existing locks
88
+ fail closed, including those retained after interruption. Common case/Unicode
89
+ aliases share a conservative lock; distinct case-sensitive names can therefore
90
+ contend. `StorageRenameRecoveryError` has `code`, `source`, `destination`, `lock`,
91
+ `backup`, `phase`, `installed`, `cause` and optional `recoveryError` fields. A
92
+ rollback or cleanup failure preserves remaining backup/lock state for inspection.
93
+ `installed: true` means installation completed before cleanup failed; it does
94
+ not mean rollback occurred. A lock error may also mean that the lock could not
95
+ be created, as identified by its original filesystem cause.
96
+
97
+ The private lock's `operation.json` records planned paths and entry identities.
98
+ After process interruption, stop the operation's owner and inspect those paths
99
+ and actual payloads before recovery. The record is diagnostic state, not an
100
+ authorization to delete a directory, and age alone never authorizes cleanup.
101
+ The function does not automatically resume an interrupted operation.
102
+
103
+ Callers authorize and control source/destination parents and validate their
104
+ content before replacement. Operations are synchronous inside the async Result
105
+ API. The two-step directory path has a temporary missing-destination window.
106
+ The lock and identity checks coordinate this API's callers; they do not sandbox
107
+ hostile same-user replacement, provide content authentication, or establish
108
+ hardware power-loss durability. Prepared-artifact publication below retains its
109
+ separate new-directory completion contract.
110
+
64
111
  ## Bounded local text reads
65
112
 
66
113
  Use the standalone entrypoint for local text supplied by a user or worker:
package/dist/move.d.ts CHANGED
@@ -11,9 +11,25 @@ export declare function move(src: string | string[], dest: string, options?: Mov
11
11
  * Renaming a file onto itself is a no-op, or a change of case on a
12
12
  * case-insensitive disk. With `overwrite` it used to delete the destination
13
13
  * first, which was the source: the file was gone before the rename ran.
14
+ * Overwrite now keeps native replacement where supported and restores a
15
+ * directory backup after failed installation. Recovery errors preserve state
16
+ * for inspection; the two-step directory path has no atomic visibility claim.
14
17
  */
15
18
  export declare function rename(from: string, to: string, options?: MoveOptions): Promise<Result<{ message: string }, Error>>;
16
19
  declare interface MoveOptions {
17
20
  overwrite?: boolean
18
21
  }
22
+ /** A preserved replacement needs inspection before this destination is reused. */
23
+ export declare class StorageRenameRecoveryError extends Error {
24
+ /** @defaultValue 'ERR_STORAGE_RENAME_RECOVERY' */
25
+ readonly code: string;
26
+ readonly source: string;
27
+ readonly destination: string;
28
+ readonly lock: string;
29
+ readonly backup: string | undefined;
30
+ readonly phase: 'lock' | 'rollback' | 'cleanup';
31
+ readonly installed: boolean;
32
+ readonly recoveryError?: unknown;
33
+ constructor(source: string, destination: string, lock: string, backup: string | undefined, phase: 'lock' | 'rollback' | 'cleanup', installed: boolean, cause: unknown, recoveryError?: unknown);
34
+ }
19
35
  export {};
package/dist/move.js CHANGED
@@ -1,3 +1,4 @@
1
- import{err,handleError,ok}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";import{path}from"@stacksjs/path";import{fs}from"./fs";export async function move(src,dest,options){try{if(Array.isArray(src)){const errors=[];const operations=src.map(async(file)=>{const from=file;const to=path.resolve(dest,path.basename(file));const result=await rename(from,to,options);if(result.isErr){log.error(result.error);errors.push(result.error)}});await Promise.all(operations);if(errors.length>0)return err(handleError(errors[0]));return ok({message:"Files moved successfully"})}const from=src;const to=dest;const result=await rename(from,to,options);if(result.isErr){log.error(result.error);return err(handleError(result.error))}return ok({message:"File moved successfully"})}catch(error){return err(handleError(error))}}export async function rename(from,to,options){try{if(!fs.existsSync(from))return err(new Error(`File or directory does not exist: ${from}`));const dir=path.dirname(to);if(!fs.existsSync(dir))fs.mkdirSync(dir,{recursive:true});if(fs.existsSync(to)&&!isSameEntry(from,to)){if(!options?.overwrite)return err(new Error(`File or directory already exists: ${to}`));fs.rmSync(to,{recursive:true,force:true})}fs.renameSync(from,to);return ok({message:"File moved successfully"})}catch(error){if(error?.code==="ENOENT")log.error(`File or directory does not exist
1
+ import{createHash}from"node:crypto";import{isAbsolute,relative,sep}from"node:path";import{err,handleError,ok}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";import{path}from"@stacksjs/path";import{fs}from"./fs";export class StorageRenameRecoveryError extends Error{source;destination;lock;backup;phase;installed;recoveryError;code="ERR_STORAGE_RENAME_RECOVERY";constructor(source,destination,lock,backup,phase,installed,cause,recoveryError){super(`Storage rename ${phase} requires inspection at ${lock}${backup?`; previous entry: ${backup}`:""}`,{cause});this.source=source;this.destination=destination;this.lock=lock;this.backup=backup;this.phase=phase;this.installed=installed;this.recoveryError=recoveryError;this.name="StorageRenameRecoveryError"}}export async function move(src,dest,options){try{if(Array.isArray(src)){const errors=[];const operations=src.map(async(file)=>{const from=file;const to=path.resolve(dest,path.basename(file));const result=await rename(from,to,options);if(result.isErr){log.error(result.error);errors.push(result.error)}});await Promise.all(operations);if(errors.length>0)return err(errors[0]);return ok({message:"Files moved successfully"})}const from=src;const to=dest;const result=await rename(from,to,options);if(result.isErr){log.error(result.error);return err(result.error)}return ok({message:"File moved successfully"})}catch(error){return err(handleError(error))}}export async function rename(from,to,options){try{if(!fs.existsSync(from))return err(new Error(`File or directory does not exist: ${from}`));const source=canonicalEntry(from),destination=canonicalEntry(to);const sourceIdentity=identity(source),destinationIdentity=identity(destination);const sameEntry=source===destination||matches(sourceIdentity,destinationIdentity);if(!sameEntry){if(beneath(source,destination)||beneath(destination,source)||directoryContainsEntry(sourceIdentity,destination)||directoryContainsEntry(destinationIdentity,source))return err(new Error("Source and destination must not overlap"))}const dir=path.dirname(to);if(!fs.existsSync(dir))fs.mkdirSync(dir,{recursive:true});if(canonicalEntry(from)!==source||canonicalEntry(to)!==destination)throw new Error("The source or destination parent changed");replaceEntry(source,destination,options?.overwrite===true);return ok({message:"File moved successfully"})}catch(error){if(error?.code==="ENOENT")log.error(`File or directory does not exist
2
2
 
3
- `,error);else log.error(error);return err(error instanceof Error?error:new Error(String(error)))}}function isSameEntry(a,b){if(path.resolve(a)===path.resolve(b))return true;try{const left=fs.statSync(a);const right=fs.statSync(b);return left.dev===right.dev&&left.ino===right.ino}catch{return false}}
3
+ `,error);else log.error(error);return err(error instanceof Error?error:new Error(String(error)))}}function identity(file){try{const stat=fs.lstatSync(file,{bigint:true});return{device:stat.dev,inode:stat.ino,directory:stat.isDirectory()}}catch(error){if(error instanceof Error&&"code"in error&&error.code==="ENOENT")return;throw error}}function matches(left,right){return left?.device===right?.device&&left?.inode===right?.inode&&left?.directory===right?.directory}function replaceEntry(source,destination,overwrite){const parent=path.dirname(destination),sourceParent=path.dirname(source);const parentIdentity=identity(parent),sourceParentIdentity=identity(sourceParent),sourceIdentity=identity(source);const lock=path.join(parent,`.stacks-rename-${createHash("sha256").update(destination.normalize("NFC").toLowerCase()).digest("hex")}`);try{fs.mkdirSync(lock,{mode:448})}catch(error){throw new StorageRenameRecoveryError(source,destination,lock,undefined,"lock",false,error)}let lockIdentity;try{const observed=identity(lock);if(!observed?.directory)throw new Error("The acquired storage rename lock changed");lockIdentity=observed}catch(error){throw new StorageRenameRecoveryError(source,destination,lock,undefined,"lock",false,error)}const backup=path.join(lock,"previous"),journal=path.join(lock,"operation.json");let moved=false,installed=false,previous;const unchanged=()=>{if(!matches(parentIdentity,identity(parent))||!matches(sourceParentIdentity,identity(sourceParent))||!matches(lockIdentity,identity(lock)))throw new Error("A storage rename parent or lock changed")};const unlock=()=>{unchanged();if(identity(journal))fs.unlinkSync(journal);fs.rmdirSync(lock)};try{unchanged();if(!sourceIdentity||!matches(sourceIdentity,identity(source)))throw new Error("The source entry changed");previous=identity(destination);const sameEntry=matches(sourceIdentity,previous);if(previous&&!sameEntry&&!overwrite)throw new Error(`File or directory already exists: ${destination}`);fs.writeFileSync(journal,`${JSON.stringify({version:1,source,destination,backup,sourceIdentity,previous},(_,value)=>typeof value==="bigint"?String(value):value)}
4
+ `,{flag:"wx",mode:384});unchanged();if(!matches(previous,identity(destination)))throw new Error("The destination entry changed");try{fs.renameSync(source,destination);installed=true}catch(nativeError){const refusal=nativeError instanceof Error&&"code"in nativeError&&["ENOTEMPTY","EEXIST","EISDIR","ENOTDIR","EPERM"].includes(String(nativeError.code));if(!refusal||!previous||sameEntry||!previous.directory&&!sourceIdentity.directory)throw nativeError;unchanged();if(!matches(previous,identity(destination))||!matches(sourceIdentity,identity(source)))throw new Error("A storage rename entry changed before replacement",{cause:nativeError});fs.renameSync(destination,backup);moved=true;unchanged();if(!matches(previous,identity(backup))||identity(destination)||!matches(sourceIdentity,identity(source)))throw new Error("A storage rename entry changed before installation");fs.renameSync(source,destination);installed=true}}catch(error){if(moved){try{unchanged();if(identity(destination)||!matches(previous,identity(backup)))throw new Error("Cannot restore over changed replacement entries");fs.renameSync(backup,destination)}catch(recoveryError){throw new StorageRenameRecoveryError(source,destination,lock,backup,"rollback",false,error,recoveryError)}}try{unlock()}catch(recoveryError){throw new StorageRenameRecoveryError(source,destination,lock,undefined,"cleanup",false,error,recoveryError)}throw error}try{unchanged();if(!matches(sourceIdentity,identity(destination)))throw new Error("The installed destination entry changed");if(moved){if(!matches(previous,identity(backup)))throw new Error("The previous destination entry changed");fs.rmSync(backup,{recursive:true})}unlock()}catch(error){throw new StorageRenameRecoveryError(source,destination,lock,moved?backup:undefined,"cleanup",installed,error)}}function canonicalEntry(file){const absolute=path.resolve(file);let parent=path.dirname(absolute);const pending=[];while(!fs.existsSync(parent)){pending.unshift(path.basename(parent));const next=path.dirname(parent);if(next===parent)throw new Error(`Cannot resolve the parent of ${file}`);parent=next}return path.join(fs.realpathSync(parent),...pending,path.basename(absolute))}function beneath(child,parent){const route=relative(parent,child);return route!==""&&route!==".."&&!route.startsWith(`..${sep}`)&&!isAbsolute(route)}function directoryContainsEntry(directory,entry){if(!directory?.directory)return false;let parent=path.dirname(entry);for(;;){if(matches(directory,identity(parent)))return true;const next=path.dirname(parent);if(next===parent)return false;parent=next}}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/storage",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.75.551",
5
+ "version": "0.75.555",
6
6
  "description": "The Stacks file system.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -61,20 +61,20 @@
61
61
  "prepublishOnly": "bun run build"
62
62
  },
63
63
  "dependencies": {
64
- "@stacksjs/arrays": "0.75.551",
65
- "@stacksjs/cli": "0.75.551",
66
- "@stacksjs/config": "0.75.551",
67
- "@stacksjs/env": "0.75.551",
68
- "@stacksjs/error-handling": "0.75.551",
69
- "@stacksjs/logging": "0.75.551",
70
- "@stacksjs/path": "0.75.551",
71
- "@stacksjs/strings": "0.75.551",
64
+ "@stacksjs/arrays": "0.75.555",
65
+ "@stacksjs/cli": "0.75.555",
66
+ "@stacksjs/config": "0.75.555",
67
+ "@stacksjs/env": "0.75.555",
68
+ "@stacksjs/error-handling": "0.75.555",
69
+ "@stacksjs/logging": "0.75.555",
70
+ "@stacksjs/path": "0.75.555",
71
+ "@stacksjs/strings": "0.75.555",
72
72
  "@stacksjs/ts-cloud": "^0.16.125",
73
73
  "@stacksjs/ts-xml": "^0.1.0",
74
74
  "ts-images": "https://registry.pantry.dev/ts-images@22073a9"
75
75
  },
76
76
  "devDependencies": {
77
- "@stacksjs/types": "0.75.551",
77
+ "@stacksjs/types": "0.75.555",
78
78
  "better-dx": "^0.2.24"
79
79
  }
80
80
  }