@stacksjs/storage 0.75.544 → 0.75.551

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.
@@ -1 +1 @@
1
- import{localDirectoryPage}from"../directory-page";import{Buffer}from"node:buffer";import{file,write as bunWrite}from"bun";import{chmod,copyFile,lstat,mkdir,rename,rm,unlink}from"node:fs/promises";import{dirname,join,relative}from"node:path";import{createDirectoryListing}from"../types";import{createSignedStorageToken}from"../signed-url";import{publicUrlFor,resolveStoragePath,signedUrlBase,writeAtomically}from"../filesystem-common";export class BunStorageAdapter{root;url;disk;constructor(config={}){this.root=config.root||process.cwd();this.url=config.url;this.disk=config.disk}resolvePath(path){return resolveStoragePath(this.root,path)}async write(path,contents){const fullPath=this.resolvePath(path);if(!(typeof contents==="string"||contents instanceof Uint8Array)){const stream=contents;if(typeof stream.getReader!=="function"){throw new TypeError("[storage/bun] contents must be a web-standard ReadableStream "+"(with .getReader()), not a Node stream.Readable. "+"Convert via Readable.toWeb(nodeStream) before passing.")}}await writeAtomically(fullPath,async(temporary)=>{if(typeof contents==="string"||contents instanceof Uint8Array)await bunWrite(temporary,contents);else await bunWrite(temporary,new Response(contents))});const written=file(fullPath);return{path,size:written.size,lastModified:written.lastModified}}async read(path){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists()){throw new Error(`File not found: ${path}`)}return await bunFile.arrayBuffer().then((buf)=>new Uint8Array(buf))}async getStream(path,_options){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists())throw new Error(`File not found: ${path}`);return bunFile.stream()}async putStream(path,stream,options){const fullPath=this.resolvePath(path);const signal=options?.signal;signal?.throwIfAborted();await writeAtomically(fullPath,async(temporary)=>{const source=signal?stream.pipeThrough(new TransformStream,{signal}):stream;await bunWrite(temporary,new Response(source))});const written=file(fullPath);return{path,size:written.size,contentType:options?.contentType,lastModified:written.lastModified}}async readToString(path){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists()){throw new Error(`File not found: ${path}`)}return await bunFile.text()}async readToBuffer(path){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists()){throw new Error(`File not found: ${path}`)}const arrayBuffer=await bunFile.arrayBuffer();return Buffer.from(arrayBuffer)}async readToUint8Array(path){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists()){throw new Error(`File not found: ${path}`)}const arrayBuffer=await bunFile.arrayBuffer();return new Uint8Array(arrayBuffer)}async deleteFile(path){const fullPath=this.resolvePath(path);await unlink(fullPath).catch((error)=>{if(error.code!=="ENOENT")throw error})}async deleteDirectory(path){const fullPath=this.resolvePath(path);await rm(fullPath,{recursive:true,force:true})}async createDirectory(path){const fullPath=this.resolvePath(path);await mkdir(fullPath,{recursive:true})}async moveFile(from,to){const fromPath=this.resolvePath(from);const toPath=this.resolvePath(to);await mkdir(dirname(toPath),{recursive:true});await rename(fromPath,toPath)}async copyFile(from,to){const fromPath=this.resolvePath(from);const toPath=this.resolvePath(to);await mkdir(dirname(toPath),{recursive:true});await copyFile(fromPath,toPath)}async stat(path){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists()){throw new Error(`File not found: ${path}`)}const stats=await Bun.file(fullPath).stat();const isDir=stats.isDirectory();return{path,type:isDir?"directory":"file",visibility:await this.visibility(path),size:isDir?0:stats.size,lastModified:stats.mtime?.getTime()||Date.now(),mimeType:isDir?undefined:bunFile.type}}listPage(path,options={}){return localDirectoryPage(this.resolvePath(path),path,options)}list(path,options={}){const fullPath=this.resolvePath(path);return this.createAsyncIterator(fullPath,options.deep||false)}async*createAsyncIterator(dirPath,deep){const entries=[];try{const glob=new Bun.Glob(deep?"**/*":"*");for await(const entry of glob.scan({cwd:dirPath,onlyFiles:false})){const fullEntryPath=join(dirPath,entry);const stats=await Bun.file(fullEntryPath).stat();entries.push({path:relative(this.root,fullEntryPath),type:stats.isDirectory()?"directory":"file"})}}catch(error){return}yield*createDirectoryListing(entries)}async changeVisibility(path,vis){const fullPath=this.resolvePath(path);const stats=await lstat(fullPath);const isDir=stats.isDirectory();const mode=vis==="public"?isDir?493:420:isDir?448:384;await chmod(fullPath,mode)}async visibility(path){const fullPath=this.resolvePath(path);const stats=await lstat(fullPath);const perms=stats.mode&511;return perms&4?"public":"private"}async fileExists(path){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);return await bunFile.exists()}async directoryExists(path){const fullPath=this.resolvePath(path);try{const stats=await Bun.file(fullPath).stat();return stats.isDirectory()}catch{return false}}async publicUrl(path,options={}){return publicUrlFor(path,{domain:options.domain,diskUrl:this.url})}async temporaryUrl(path,options){return await this.signedUrl(path,{expiresIn:options.expiresIn})}async signedUrl(path,options){const token=createSignedStorageToken(path,{...options,disk:options.disk??this.disk});return`${signedUrlBase(options.baseUrl)}/__storage/${encodeURIComponent(path)}?token=${token}`}async checksum(path,options={}){const algorithm=options.algorithm||"sha256";const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists()){throw new Error(`File not found: ${path}`)}const hasher=new Bun.CryptoHasher(algorithm);const arrayBuffer=await bunFile.arrayBuffer();hasher.update(new Uint8Array(arrayBuffer));return hasher.digest("hex")}async mimeType(path,_options={}){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists()){throw new Error(`File not found: ${path}`)}return bunFile.type||"application/octet-stream"}async lastModified(path){const stats=await this.stat(path);return stats.lastModified}async fileSize(path){const stats=await this.stat(path);return stats.size}}export function createBunStorage(config={}){return new BunStorageAdapter(config)}
1
+ import{localDirectoryPage}from"../directory-page";import{Buffer}from"node:buffer";import{file,write as bunWrite}from"bun";import{chmod,copyFile,lstat,mkdir,rename,rm,unlink}from"node:fs/promises";import{dirname,join,relative}from"node:path";import{createDirectoryListing}from"../types";import{createSignedStorageToken}from"../signed-url";import{publicUrlFor,resolveStoragePath,signedUrlBase,writeAtomically,writeStreamToFile}from"../filesystem-common";export class BunStorageAdapter{root;url;disk;constructor(config={}){this.root=config.root||process.cwd();this.url=config.url;this.disk=config.disk}resolvePath(path){return resolveStoragePath(this.root,path)}async write(path,contents){const fullPath=this.resolvePath(path);if(!(typeof contents==="string"||contents instanceof Uint8Array)){const stream=contents;if(typeof stream.getReader!=="function"){throw new TypeError("[storage/bun] contents must be a web-standard ReadableStream "+"(with .getReader()), not a Node stream.Readable. "+"Convert via Readable.toWeb(nodeStream) before passing.")}}await writeAtomically(fullPath,async(temporary)=>{if(typeof contents==="string"||contents instanceof Uint8Array)await bunWrite(temporary,contents);else await writeStreamToFile(temporary,contents)});const written=file(fullPath);return{path,size:written.size,lastModified:written.lastModified}}async read(path){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists()){throw new Error(`File not found: ${path}`)}return await bunFile.arrayBuffer().then((buf)=>new Uint8Array(buf))}async getStream(path,_options){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists())throw new Error(`File not found: ${path}`);return bunFile.stream()}async putStream(path,stream,options){const fullPath=this.resolvePath(path);const signal=options?.signal;signal?.throwIfAborted();await writeAtomically(fullPath,async(temporary)=>{await writeStreamToFile(temporary,stream,signal)});const written=file(fullPath);return{path,size:written.size,contentType:options?.contentType,lastModified:written.lastModified}}async readToString(path){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists()){throw new Error(`File not found: ${path}`)}return await bunFile.text()}async readToBuffer(path){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists()){throw new Error(`File not found: ${path}`)}const arrayBuffer=await bunFile.arrayBuffer();return Buffer.from(arrayBuffer)}async readToUint8Array(path){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists()){throw new Error(`File not found: ${path}`)}const arrayBuffer=await bunFile.arrayBuffer();return new Uint8Array(arrayBuffer)}async deleteFile(path){const fullPath=this.resolvePath(path);await unlink(fullPath).catch((error)=>{if(error.code!=="ENOENT")throw error})}async deleteDirectory(path){const fullPath=this.resolvePath(path);await rm(fullPath,{recursive:true,force:true})}async createDirectory(path){const fullPath=this.resolvePath(path);await mkdir(fullPath,{recursive:true})}async moveFile(from,to){const fromPath=this.resolvePath(from);const toPath=this.resolvePath(to);await mkdir(dirname(toPath),{recursive:true});await rename(fromPath,toPath)}async copyFile(from,to){const fromPath=this.resolvePath(from);const toPath=this.resolvePath(to);await mkdir(dirname(toPath),{recursive:true});await copyFile(fromPath,toPath)}async stat(path){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists()){throw new Error(`File not found: ${path}`)}const stats=await Bun.file(fullPath).stat();const isDir=stats.isDirectory();return{path,type:isDir?"directory":"file",visibility:await this.visibility(path),size:isDir?0:stats.size,lastModified:stats.mtime?.getTime()||Date.now(),mimeType:isDir?undefined:bunFile.type}}listPage(path,options={}){return localDirectoryPage(this.resolvePath(path),path,options)}list(path,options={}){const fullPath=this.resolvePath(path);return this.createAsyncIterator(fullPath,options.deep||false)}async*createAsyncIterator(dirPath,deep){const entries=[];try{const glob=new Bun.Glob(deep?"**/*":"*");for await(const entry of glob.scan({cwd:dirPath,onlyFiles:false})){const fullEntryPath=join(dirPath,entry);const stats=await Bun.file(fullEntryPath).stat();entries.push({path:relative(this.root,fullEntryPath),type:stats.isDirectory()?"directory":"file"})}}catch(error){return}yield*createDirectoryListing(entries)}async changeVisibility(path,vis){const fullPath=this.resolvePath(path);const stats=await lstat(fullPath);const isDir=stats.isDirectory();const mode=vis==="public"?isDir?493:420:isDir?448:384;await chmod(fullPath,mode)}async visibility(path){const fullPath=this.resolvePath(path);const stats=await lstat(fullPath);const perms=stats.mode&511;return perms&4?"public":"private"}async fileExists(path){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);return await bunFile.exists()}async directoryExists(path){const fullPath=this.resolvePath(path);try{const stats=await Bun.file(fullPath).stat();return stats.isDirectory()}catch{return false}}async publicUrl(path,options={}){return publicUrlFor(path,{domain:options.domain,diskUrl:this.url})}async temporaryUrl(path,options){return await this.signedUrl(path,{expiresIn:options.expiresIn})}async signedUrl(path,options){const token=createSignedStorageToken(path,{...options,disk:options.disk??this.disk});return`${signedUrlBase(options.baseUrl)}/__storage/${encodeURIComponent(path)}?token=${token}`}async checksum(path,options={}){const algorithm=options.algorithm||"sha256";const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists()){throw new Error(`File not found: ${path}`)}const hasher=new Bun.CryptoHasher(algorithm);const arrayBuffer=await bunFile.arrayBuffer();hasher.update(new Uint8Array(arrayBuffer));return hasher.digest("hex")}async mimeType(path,_options={}){const fullPath=this.resolvePath(path);const bunFile=file(fullPath);if(!await bunFile.exists()){throw new Error(`File not found: ${path}`)}return bunFile.type||"application/octet-stream"}async lastModified(path){const stats=await this.stat(path);return stats.lastModified}async fileSize(path){const stats=await this.stat(path);return stats.size}}export function createBunStorage(config={}){return new BunStorageAdapter(config)}
@@ -1 +1 @@
1
- import{localDirectoryPage}from"../directory-page";import{Buffer}from"node:buffer";import{createReadStream,createWriteStream}from"node:fs";import{access,chmod,constants,copyFile,lstat,mkdir,readdir,readFile,rename,rm,stat,unlink,writeFile}from"node:fs/promises";import{basename,dirname,join,relative}from"node:path";import{Readable}from"node:stream";import{pipeline}from"node:stream/promises";import{createDirectoryListing}from"../types";import{createSignedStorageToken}from"../signed-url";import{publicUrlFor,resolveStoragePath,signedUrlBase,writeAtomically}from"../filesystem-common";export class LocalStorageAdapter{root;url;disk;constructor(config={}){this.root=config.root||process.cwd();this.url=config.url;this.disk=config.disk}resolvePath(path){return resolveStoragePath(this.root,path)}async write(path,contents){const fullPath=this.resolvePath(path);await writeAtomically(fullPath,async(temporary)=>{if(typeof contents==="string"){await writeFile(temporary,contents,"utf8")}else if(contents instanceof Uint8Array){await writeFile(temporary,contents)}else{const nodeReadable=Readable.fromWeb(contents);await pipeline(nodeReadable,createWriteStream(temporary))}});const st=await stat(fullPath);return{path,size:st.size,lastModified:st.mtimeMs}}async read(path){const fullPath=this.resolvePath(path);return await readFile(fullPath)}async getStream(path,options){const fullPath=this.resolvePath(path);await access(fullPath,constants.R_OK);const nodeStream=createReadStream(fullPath,{signal:options?.signal});return Readable.toWeb(nodeStream)}async putStream(path,stream,options){const fullPath=this.resolvePath(path);await writeAtomically(fullPath,async(temporary)=>{const nodeReadable=Readable.fromWeb(stream);await pipeline(nodeReadable,createWriteStream(temporary),{signal:options?.signal})});const st=await stat(fullPath);return{path,size:st.size,contentType:options?.contentType,lastModified:st.mtimeMs}}async readToString(path){const fullPath=this.resolvePath(path);return await readFile(fullPath,"utf8")}async readToBuffer(path){const fullPath=this.resolvePath(path);return await readFile(fullPath)}async readToUint8Array(path){const fullPath=this.resolvePath(path);const buffer=await readFile(fullPath);return new Uint8Array(buffer)}async deleteFile(path){const fullPath=this.resolvePath(path);await unlink(fullPath).catch((error)=>{if(error.code!=="ENOENT")throw error})}async deleteDirectory(path){const fullPath=this.resolvePath(path);await rm(fullPath,{recursive:true,force:true})}async createDirectory(path){const fullPath=this.resolvePath(path);await mkdir(fullPath,{recursive:true})}async moveFile(from,to){const fromPath=this.resolvePath(from);const toPath=this.resolvePath(to);const toDir=dirname(toPath);await mkdir(toDir,{recursive:true});await rename(fromPath,toPath)}async copyFile(from,to){const fromPath=this.resolvePath(from);const toPath=this.resolvePath(to);const toDir=dirname(toPath);await mkdir(toDir,{recursive:true});await copyFile(fromPath,toPath)}async stat(path){const fullPath=this.resolvePath(path);const stats=await lstat(fullPath);return{path,type:stats.isDirectory()?"directory":"file",visibility:await this.visibility(path),size:stats.size,lastModified:stats.mtimeMs,mimeType:stats.isFile()?await this.detectMimeType(fullPath):undefined}}listPage(path,options={}){return localDirectoryPage(this.resolvePath(path),path,options)}list(path,options={}){return this.createAsyncIterator(path,options.deep||false)}async*createAsyncIterator(path,deep){const fullPath=this.resolvePath(path);try{await access(fullPath,constants.R_OK)}catch{return}const entries=await this.readDirectoryRecursive(fullPath,deep);yield*createDirectoryListing(entries)}async readDirectoryRecursive(dirPath,deep){const entries=[];try{const items=await readdir(dirPath,{withFileTypes:true});for(const item of items){const itemPath=join(dirPath,item.name);const relativePath=relative(this.root,itemPath);entries.push({path:relativePath,type:item.isDirectory()?"directory":"file"});if(deep&&item.isDirectory()){const subEntries=await this.readDirectoryRecursive(itemPath,true);entries.push(...subEntries)}}}catch(error){if(error?.code!=="EACCES"&&error?.code!=="EPERM"){throw error}}return entries}async changeVisibility(path,vis){const fullPath=this.resolvePath(path);const stats=await lstat(fullPath);const isDir=stats.isDirectory();const mode=vis==="public"?isDir?493:420:isDir?448:384;await chmod(fullPath,mode)}async visibility(path){const fullPath=this.resolvePath(path);const stats=await lstat(fullPath);const perms=stats.mode&511;return perms&4?"public":"private"}async fileExists(path){const fullPath=this.resolvePath(path);try{const stats=await lstat(fullPath);return stats.isFile()}catch{return false}}async directoryExists(path){const fullPath=this.resolvePath(path);try{const stats=await lstat(fullPath);return stats.isDirectory()}catch{return false}}async publicUrl(path,options={}){return publicUrlFor(path,{domain:options.domain,diskUrl:this.url})}async temporaryUrl(path,options){return await this.signedUrl(path,{expiresIn:options.expiresIn})}async signedUrl(path,options){const token=createSignedStorageToken(path,{...options,disk:options.disk??this.disk});return`${signedUrlBase(options.baseUrl)}/__storage/${encodeURIComponent(path)}?token=${token}`}async checksum(path,options={}){const algorithm=options.algorithm||"sha256";const fullPath=this.resolvePath(path);const content=await readFile(fullPath);const hasher=new Bun.CryptoHasher(algorithm);hasher.update(content);return hasher.digest("hex")}async mimeType(path,options={}){const fullPath=this.resolvePath(path);return await this.detectMimeType(fullPath)}async detectMimeType(filePath){const ext=basename(filePath).split(".").pop()?.toLowerCase();const mimeTypes={txt:"text/plain",html:"text/html",css:"text/css",js:"application/javascript",json:"application/json",xml:"application/xml",pdf:"application/pdf",zip:"application/zip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",svg:"image/svg+xml",mp4:"video/mp4",mp3:"audio/mpeg",wav:"audio/wav"};return mimeTypes[ext||""]||"application/octet-stream"}async lastModified(path){const stats=await this.stat(path);return stats.lastModified}async fileSize(path){const stats=await this.stat(path);return stats.size}}export function createLocalStorage(config={}){return new LocalStorageAdapter(config)}
1
+ import{localDirectoryPage}from"../directory-page";import{Buffer}from"node:buffer";import{createReadStream}from"node:fs";import{access,chmod,constants,copyFile,lstat,mkdir,readdir,readFile,rename,rm,stat,unlink,writeFile}from"node:fs/promises";import{basename,dirname,join,relative}from"node:path";import{Readable}from"node:stream";import{createDirectoryListing}from"../types";import{createSignedStorageToken}from"../signed-url";import{publicUrlFor,resolveStoragePath,signedUrlBase,writeAtomically,writeStreamToFile}from"../filesystem-common";export class LocalStorageAdapter{root;url;disk;constructor(config={}){this.root=config.root||process.cwd();this.url=config.url;this.disk=config.disk}resolvePath(path){return resolveStoragePath(this.root,path)}async write(path,contents){const fullPath=this.resolvePath(path);await writeAtomically(fullPath,async(temporary)=>{if(typeof contents==="string"){await writeFile(temporary,contents,"utf8")}else if(contents instanceof Uint8Array){await writeFile(temporary,contents)}else{await writeStreamToFile(temporary,contents)}});const st=await stat(fullPath);return{path,size:st.size,lastModified:st.mtimeMs}}async read(path){const fullPath=this.resolvePath(path);return await readFile(fullPath)}async getStream(path,options){const fullPath=this.resolvePath(path);await access(fullPath,constants.R_OK);const nodeStream=createReadStream(fullPath,{signal:options?.signal});return Readable.toWeb(nodeStream)}async putStream(path,stream,options){const fullPath=this.resolvePath(path);await writeAtomically(fullPath,async(temporary)=>{await writeStreamToFile(temporary,stream,options?.signal)});const st=await stat(fullPath);return{path,size:st.size,contentType:options?.contentType,lastModified:st.mtimeMs}}async readToString(path){const fullPath=this.resolvePath(path);return await readFile(fullPath,"utf8")}async readToBuffer(path){const fullPath=this.resolvePath(path);return await readFile(fullPath)}async readToUint8Array(path){const fullPath=this.resolvePath(path);const buffer=await readFile(fullPath);return new Uint8Array(buffer)}async deleteFile(path){const fullPath=this.resolvePath(path);await unlink(fullPath).catch((error)=>{if(error.code!=="ENOENT")throw error})}async deleteDirectory(path){const fullPath=this.resolvePath(path);await rm(fullPath,{recursive:true,force:true})}async createDirectory(path){const fullPath=this.resolvePath(path);await mkdir(fullPath,{recursive:true})}async moveFile(from,to){const fromPath=this.resolvePath(from);const toPath=this.resolvePath(to);const toDir=dirname(toPath);await mkdir(toDir,{recursive:true});await rename(fromPath,toPath)}async copyFile(from,to){const fromPath=this.resolvePath(from);const toPath=this.resolvePath(to);const toDir=dirname(toPath);await mkdir(toDir,{recursive:true});await copyFile(fromPath,toPath)}async stat(path){const fullPath=this.resolvePath(path);const stats=await lstat(fullPath);return{path,type:stats.isDirectory()?"directory":"file",visibility:await this.visibility(path),size:stats.size,lastModified:stats.mtimeMs,mimeType:stats.isFile()?await this.detectMimeType(fullPath):undefined}}listPage(path,options={}){return localDirectoryPage(this.resolvePath(path),path,options)}list(path,options={}){return this.createAsyncIterator(path,options.deep||false)}async*createAsyncIterator(path,deep){const fullPath=this.resolvePath(path);try{await access(fullPath,constants.R_OK)}catch{return}const entries=await this.readDirectoryRecursive(fullPath,deep);yield*createDirectoryListing(entries)}async readDirectoryRecursive(dirPath,deep){const entries=[];try{const items=await readdir(dirPath,{withFileTypes:true});for(const item of items){const itemPath=join(dirPath,item.name);const relativePath=relative(this.root,itemPath);entries.push({path:relativePath,type:item.isDirectory()?"directory":"file"});if(deep&&item.isDirectory()){const subEntries=await this.readDirectoryRecursive(itemPath,true);entries.push(...subEntries)}}}catch(error){if(error?.code!=="EACCES"&&error?.code!=="EPERM"){throw error}}return entries}async changeVisibility(path,vis){const fullPath=this.resolvePath(path);const stats=await lstat(fullPath);const isDir=stats.isDirectory();const mode=vis==="public"?isDir?493:420:isDir?448:384;await chmod(fullPath,mode)}async visibility(path){const fullPath=this.resolvePath(path);const stats=await lstat(fullPath);const perms=stats.mode&511;return perms&4?"public":"private"}async fileExists(path){const fullPath=this.resolvePath(path);try{const stats=await lstat(fullPath);return stats.isFile()}catch{return false}}async directoryExists(path){const fullPath=this.resolvePath(path);try{const stats=await lstat(fullPath);return stats.isDirectory()}catch{return false}}async publicUrl(path,options={}){return publicUrlFor(path,{domain:options.domain,diskUrl:this.url})}async temporaryUrl(path,options){return await this.signedUrl(path,{expiresIn:options.expiresIn})}async signedUrl(path,options){const token=createSignedStorageToken(path,{...options,disk:options.disk??this.disk});return`${signedUrlBase(options.baseUrl)}/__storage/${encodeURIComponent(path)}?token=${token}`}async checksum(path,options={}){const algorithm=options.algorithm||"sha256";const fullPath=this.resolvePath(path);const content=await readFile(fullPath);const hasher=new Bun.CryptoHasher(algorithm);hasher.update(content);return hasher.digest("hex")}async mimeType(path,options={}){const fullPath=this.resolvePath(path);return await this.detectMimeType(fullPath)}async detectMimeType(filePath){const ext=basename(filePath).split(".").pop()?.toLowerCase();const mimeTypes={txt:"text/plain",html:"text/html",css:"text/css",js:"application/javascript",json:"application/json",xml:"application/xml",pdf:"application/pdf",zip:"application/zip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",svg:"image/svg+xml",mp4:"video/mp4",mp3:"audio/mpeg",wav:"audio/wav"};return mimeTypes[ext||""]||"application/octet-stream"}async lastModified(path){const stats=await this.stat(path);return stats.lastModified}async fileSize(path){const stats=await this.stat(path);return stats.size}}export function createLocalStorage(config={}){return new LocalStorageAdapter(config)}
@@ -19,6 +19,22 @@ export declare function resolveStoragePath(root: string, path: string): string;
19
19
  * over, so a private file stays private.
20
20
  */
21
21
  export declare function writeAtomically(fullPath: string, write: (temporary: string) => Promise<void>): Promise<void>;
22
+ /**
23
+ * Write a web stream to `path`, a chunk at a time.
24
+ *
25
+ * A plain read-and-write loop, because neither shortcut survives Bun 1.3.
26
+ * `Bun.write(path, new Response(stream))`, which the Bun adapter used, never
27
+ * resolves there for any stream of any size, so an upload hung the request
28
+ * that made it. Node's `pipeline(Readable.fromWeb(stream), ...)`, which the
29
+ * local adapter used, completes but never rejects when the stream errors, so
30
+ * a failed upload hung instead of failing. Each write is awaited before the
31
+ * next read, which is all the backpressure there is to get wrong: a 512 MB
32
+ * stream peaks under 60 MB resident on Bun 1.3.0, 1.3.14 and 1.4.4.
33
+ *
34
+ * `signal` aborts the copy, between chunks or while waiting for one, and
35
+ * rejects with the signal's reason. The caller owns removing the partial file.
36
+ */
37
+ export declare function writeStreamToFile(path: string, stream: ReadableStream<Uint8Array>, signal?: AbortSignal): Promise<void>;
22
38
  /**
23
39
  * Percent-encode each segment of a storage path, keeping its slashes: a file
24
40
  * called `my photo #1.jpg` becomes `my%20photo%20%231.jpg`. Unencoded, the
@@ -1 +1 @@
1
- import{randomBytes}from"node:crypto";import{lstatSync}from"node:fs";import{chmod,mkdir,rename,rm,stat}from"node:fs/promises";import{basename,dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import process from"node:process";export function resolveStoragePath(root,path){const base=resolve(root);const target=join(base,path);const rel=relative(base,target);if(rel===".."||rel.startsWith(`..${sep}`)||isAbsolute(rel))throw new Error(`Path traversal detected: '${path}' resolves outside storage root`);let current=base;for(const segment of rel.split(sep).filter(Boolean)){current=join(current,segment);try{if(lstatSync(current).isSymbolicLink())throw new Error(`Storage path '${path}' contains a symlink`)}catch(error){if(error.code==="ENOENT")break;throw error}}return target}export async function writeAtomically(fullPath,write){await mkdir(dirname(fullPath),{recursive:true});const temporary=join(dirname(fullPath),`.${basename(fullPath)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);try{await write(temporary);const previous=await stat(fullPath).catch(()=>null);if(previous)await chmod(temporary,previous.mode&4095);await rename(temporary,fullPath)}catch(error){await rm(temporary,{force:true}).catch(()=>{});throw error}}export function encodeStoragePath(path){return path.split("/").map((segment)=>encodeURIComponent(segment)).join("/")}export function publicUrlFor(path,options){const base=withScheme(options.domain??options.diskUrl??process.env.APP_URL??"http://localhost");return`${base.replace(/\/+$/,"")}/${encodeStoragePath(path.replace(/^\/+/,""))}`}export function signedUrlBase(baseUrl){return withScheme(baseUrl||process.env.APP_URL||"http://localhost").replace(/\/+$/,"")}function withScheme(base){if(base===""||base.startsWith("/")||/^[a-z][a-z0-9+.-]*:\/\//i.test(base))return base;return`https://${base}`}
1
+ import{randomBytes}from"node:crypto";import{lstatSync}from"node:fs";import{chmod,mkdir,open,rename,rm,stat}from"node:fs/promises";import{basename,dirname,isAbsolute,join,relative,resolve,sep}from"node:path";import process from"node:process";export function resolveStoragePath(root,path){const base=resolve(root);const target=join(base,path);const rel=relative(base,target);if(rel===".."||rel.startsWith(`..${sep}`)||isAbsolute(rel))throw new Error(`Path traversal detected: '${path}' resolves outside storage root`);let current=base;for(const segment of rel.split(sep).filter(Boolean)){current=join(current,segment);try{if(lstatSync(current).isSymbolicLink())throw new Error(`Storage path '${path}' contains a symlink`)}catch(error){if(error.code==="ENOENT")break;throw error}}return target}export async function writeAtomically(fullPath,write){await mkdir(dirname(fullPath),{recursive:true});const temporary=join(dirname(fullPath),`.${basename(fullPath)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);try{await write(temporary);const previous=await stat(fullPath).catch(()=>null);if(previous)await chmod(temporary,previous.mode&4095);await rename(temporary,fullPath)}catch(error){await rm(temporary,{force:true}).catch(()=>{});throw error}}export async function writeStreamToFile(path,stream,signal){signal?.throwIfAborted();let stop;const aborted=signal&&new Promise((_resolve,reject)=>{stop=()=>reject(signal.reason??new DOMException("The operation was aborted.","AbortError"));signal.addEventListener("abort",stop,{once:true})});aborted?.catch(()=>{});const reader=stream.getReader();const handle=await open(path,"w");try{for(;;){const next=await(aborted?Promise.race([reader.read(),aborted]):reader.read());if(next.done)break;for(let offset=0;offset<next.value.length;)offset+=(await handle.write(next.value,offset)).bytesWritten}}catch(error){reader.cancel(error).catch(()=>{});throw error}finally{if(stop)signal?.removeEventListener("abort",stop);await handle.close()}}export function encodeStoragePath(path){return path.split("/").map((segment)=>encodeURIComponent(segment)).join("/")}export function publicUrlFor(path,options){const base=withScheme(options.domain??options.diskUrl??process.env.APP_URL??"http://localhost");return`${base.replace(/\/+$/,"")}/${encodeStoragePath(path.replace(/^\/+/,""))}`}export function signedUrlBase(baseUrl){return withScheme(baseUrl||process.env.APP_URL||"http://localhost").replace(/\/+$/,"")}function withScheme(base){if(base===""||base.startsWith("/")||/^[a-z][a-z0-9+.-]*:\/\//i.test(base))return base;return`https://${base}`}
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.544",
5
+ "version": "0.75.551",
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.544",
65
- "@stacksjs/cli": "0.75.544",
66
- "@stacksjs/config": "0.75.544",
67
- "@stacksjs/env": "0.75.544",
68
- "@stacksjs/error-handling": "0.75.544",
69
- "@stacksjs/logging": "0.75.544",
70
- "@stacksjs/path": "0.75.544",
71
- "@stacksjs/strings": "0.75.544",
72
- "@stacksjs/ts-cloud": "^0.16.109",
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",
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.544",
77
+ "@stacksjs/types": "0.75.551",
78
78
  "better-dx": "^0.2.24"
79
79
  }
80
80
  }