@stacksjs/storage 0.75.515 → 0.75.519
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/dist/adapters/azure.js +2 -2
- package/dist/adapters/bun.js +1 -1
- package/dist/adapters/local.js +1 -1
- package/dist/adapters/memory.js +1 -1
- package/dist/adapters/s3.js +1 -1
- package/dist/adapters/scoped.js +1 -1
- package/dist/azure-signing.js +5 -5
- package/dist/bounded-text-file.js +1 -1
- package/dist/completed-artifact-directory.js +1 -1
- package/dist/copy.js +1 -1
- package/dist/delete.js +1 -1
- package/dist/directory-page.js +1 -1
- package/dist/drivers/aws.js +1 -1
- package/dist/drivers/bun.js +1 -1
- package/dist/drivers/local.js +1 -1
- package/dist/drivers/memory.js +1 -1
- package/dist/facade.js +1 -1
- package/dist/file-info.js +1 -1
- package/dist/files.js +1 -1
- package/dist/filesystem-common.js +1 -1
- package/dist/folders.js +1 -1
- package/dist/glob.js +1 -1
- package/dist/hash.js +1 -1
- package/dist/helpers.js +1 -1
- package/dist/image.js +1 -1
- package/dist/mime-verify.js +1 -1
- package/dist/move.js +2 -2
- package/dist/path-sanitize.js +1 -1
- package/dist/prepared-completed-artifact-directory.js +1 -1
- package/dist/provision.js +1 -1
- package/dist/put-file.js +1 -1
- package/dist/s3-presigned-post.js +1 -1
- package/dist/signed-url.js +1 -1
- package/dist/static-serve.js +1 -1
- package/dist/temporary-workspaces.js +3 -3
- package/dist/types/filesystem.js +1 -1
- package/dist/types.js +1 -1
- package/dist/uploaded-file.js +1 -1
- package/dist/zip.js +1 -1
- package/package.json +10 -10
package/dist/adapters/azure.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Buffer}from"node:buffer";import{createHash}from"node:crypto";import{REST_VERSION,serviceSasQuery,sharedKeyAuthorization}from"../azure-signing";import{extensionForContentType,mimeFromExtension}from"../mime-from-extension";import{sanitizePresignedDir,sanitizePresignedFilename}from"../path-sanitize";import{normalizeExpiryToMilliseconds}from"../types";const MAX_SINGLE_PUT_BYTES=
|
|
2
|
-
`)[0];throw Error(`[storage/azure] ${method} ${target.pathname} failed with ${response.status}
|
|
1
|
+
import{Buffer}from"node:buffer";import{createHash}from"node:crypto";import{REST_VERSION,serviceSasQuery,sharedKeyAuthorization}from"../azure-signing";import{extensionForContentType,mimeFromExtension}from"../mime-from-extension";import{sanitizePresignedDir,sanitizePresignedFilename}from"../path-sanitize";import{normalizeExpiryToMilliseconds}from"../types";const MAX_SINGLE_PUT_BYTES=256*1024*1024;const DEFAULT_BLOCK_BYTES=4*1024*1024;const MAX_BLOCKS=50000;const MIN_EXPIRY_SECONDS=60;const MAX_EXPIRY_SECONDS=7*24*60*60;export class AzureBlobStorageAdapter{account;accountKey;sasToken;container;prefix;endpoint;publicBaseUrl;constructor(config){if(!config.account)throw new Error("[storage/azure] a storage account name is required");if(!config.container)throw new Error("[storage/azure] a container name is required");if(!config.accountKey&&!config.sasToken){throw new Error("[storage/azure] one of `accountKey` or `sasToken` is required - "+"there is no anonymous write path, and a read-only disk still has to authorize its reads.")}this.account=config.account;this.accountKey=config.accountKey;this.sasToken=config.sasToken?.replace(/^\?/,"");this.container=config.container;this.prefix=config.prefix?.replace(/^\/+|\/+$/g,"")??"";this.endpoint=(config.endpoint??`https://${config.account}.blob.core.windows.net`).replace(/\/+$/,"");this.publicBaseUrl=config.url?.replace(/\/+$/,"")}blobName(path){const clean=path.replace(/^\/+/,"");return this.prefix?`${this.prefix}/${clean}`.replace(/\/{2,}/g,"/"):clean}stripPrefix(blob){if(!this.prefix)return blob;const withSlash=`${this.prefix}/`;return blob.startsWith(withSlash)?blob.slice(withSlash.length):blob}blobUrl(blob,query={}){const segments=blob?blob.split("/").map(encodeURIComponent).join("/"):"";const url=new URL(`${this.endpoint}/${this.container}${segments?`/${segments}`:""}`);for(const[name,value]of Object.entries(query))url.searchParams.set(name,value);return url}async request(method,url,options={}){const headers={"x-ms-date":new Date().toUTCString(),"x-ms-version":REST_VERSION,...options.headers};if(options.body!==undefined)headers["Content-Length"]=String(options.body.byteLength);const target=new URL(url);if(this.accountKey){headers.Authorization=sharedKeyAuthorization({account:this.account,accountKey:this.accountKey},{method,url:target,headers})}else if(this.sasToken){for(const[name,value]of new URLSearchParams(this.sasToken))target.searchParams.set(name,value)}const response=await fetch(target,{method,headers,body:options.body?new Uint8Array(options.body):undefined});const body=await response.arrayBuffer();const expected=options.expect??[200,201,202,204,206];if(!expected.includes(response.status)){const text=new TextDecoder().decode(body);const code=text.match(/<Code>([^<]+)<\/Code>/)?.[1];const message=text.match(/<Message>([^<]+)<\/Message>/)?.[1]?.split(`
|
|
2
|
+
`)[0];throw new Error(`[storage/azure] ${method} ${target.pathname} failed with ${response.status}`+`${code?` (${code})`:""}${message?`: ${message}`:""}`)}return{status:response.status,headers:response.headers,body}}async contentsToBuffer(contents){if(typeof contents==="string")return Buffer.from(contents,"utf8");if(contents instanceof Buffer)return contents;if(contents instanceof Uint8Array)return Buffer.from(contents);const maybeStream=contents;if(typeof maybeStream.getReader!=="function"){throw new TypeError("[storage/azure] contents must be a web-standard ReadableStream "+"(with .getReader()), not a Node stream.Readable. "+"Convert via Readable.toWeb(nodeStream) before passing.")}return Buffer.concat(await collect(contents))}async write(path,contents){const body=await this.contentsToBuffer(contents);const contentType=mimeFromExtension(path);if(body.byteLength>MAX_SINGLE_PUT_BYTES){return await this.putStream(path,streamOf(body),{contentType})}const response=await this.request("PUT",this.blobUrl(this.blobName(path)),{headers:{"x-ms-blob-type":"BlockBlob","Content-Type":contentType},body,expect:[201]});return{path,size:body.byteLength,contentType,etag:response.headers.get("etag")??undefined,lastModified:lastModifiedFrom(response.headers)}}async read(path){const response=await this.request("GET",this.blobUrl(this.blobName(path)),{expect:[200,206]});return Buffer.from(response.body)}async readToString(path){return(await this.readToBuffer(path)).toString("utf8")}async readToBuffer(path){return Buffer.from(await this.read(path))}async readToUint8Array(path){return new Uint8Array(await this.readToBuffer(path))}async getStream(path,options){const headers={"x-ms-date":new Date().toUTCString(),"x-ms-version":REST_VERSION};const url=this.blobUrl(this.blobName(path));if(this.accountKey){headers.Authorization=sharedKeyAuthorization({account:this.account,accountKey:this.accountKey},{method:"GET",url,headers})}else if(this.sasToken){for(const[name,value]of new URLSearchParams(this.sasToken))url.searchParams.set(name,value)}const response=await fetch(url,{method:"GET",headers,signal:options?.signal});if(!response.ok||!response.body)throw new Error(`[storage/azure] failed to open a stream for ${path}: ${response.status}`);return response.body}async putStream(path,stream,options){const blob=this.blobName(path);const contentType=options?.contentType??mimeFromExtension(path);const blockSize=Math.max(1,Math.min(options?.partSize??DEFAULT_BLOCK_BYTES,4000*1024*1024));const reader=stream.getReader();const blockIds=[];let pending=[];let pendingBytes=0;let total=0;const flush=async()=>{if(pendingBytes===0)return;if(blockIds.length>=MAX_BLOCKS){throw new RangeError(`[storage/azure] a block blob holds at most ${MAX_BLOCKS} blocks; `+`raise \`partSize\` above ${blockSize} bytes for an upload this large.`)}const id=Buffer.from(String(blockIds.length).padStart(6,"0")).toString("base64");const body=Buffer.concat(pending);pending=[];pendingBytes=0;await this.request("PUT",this.blobUrl(blob,{comp:"block",blockid:id}),{body,expect:[201]});blockIds.push(id)};try{while(true){options?.signal?.throwIfAborted();const{done,value}=await reader.read();if(done)break;if(!value?.length)continue;total+=value.length;pending.push(Buffer.from(value));pendingBytes+=value.length;if(pendingBytes>=blockSize)await flush()}await flush()}finally{reader.releaseLock()}const list=`<?xml version="1.0" encoding="utf-8"?><BlockList>${blockIds.map((id)=>`<Latest>${id}</Latest>`).join("")}</BlockList>`;const response=await this.request("PUT",this.blobUrl(blob,{comp:"blocklist"}),{headers:{"Content-Type":"application/xml","x-ms-blob-content-type":contentType},body:Buffer.from(list,"utf8"),expect:[201]});return{path,size:total,contentType,etag:response.headers.get("etag")??undefined,lastModified:lastModifiedFrom(response.headers)}}async deleteFile(path){await this.request("DELETE",this.blobUrl(this.blobName(path)),{expect:[202]})}async deleteDirectory(path){for await(const entry of this.list(path,{deep:true}))await this.deleteFile(entry.path)}async createDirectory(_path){}async moveFile(from,to){await this.copyFile(from,to);await this.deleteFile(from)}async copyFile(from,to){const source=this.blobUrl(this.blobName(from));const response=await this.request("PUT",this.blobUrl(this.blobName(to)),{headers:{"x-ms-copy-source":source.toString()},expect:[202]});const status=response.headers.get("x-ms-copy-status");if(status&&status!=="success")throw new Error(`[storage/azure] copy of ${from} to ${to} did not complete synchronously (status: ${status})`)}async stat(path){const response=await this.request("HEAD",this.blobUrl(this.blobName(path)),{expect:[200]});return{path,type:"file",visibility:await this.visibility(path),size:Number(response.headers.get("content-length")??0),lastModified:lastModifiedFrom(response.headers),mimeType:response.headers.get("content-type")??undefined}}list(path,options={}){return this.listBlobs(path,options.deep??false)}async*listBlobs(path,deep){const{XMLParser}=await import("@stacksjs/ts-xml");const parser=new XMLParser({ignoreAttributes:true,parseTagValue:false,trimValues:true});const scoped=this.blobName(path.replace(/\/+$/,""));const prefix=scoped?`${scoped}/`:"";let marker;do{const query={restype:"container",comp:"list"};if(prefix)query.prefix=prefix;if(!deep)query.delimiter="/";if(marker)query.marker=marker;const response=await this.request("GET",this.blobUrl(undefined,query),{expect:[200]});const parsed=parser.parse(new TextDecoder().decode(response.body));const blobs=parsed?.EnumerationResults?.Blobs;for(const blob of asArray(blobs?.Blob)){if(!blob?.Name)continue;yield{path:this.stripPrefix(blob.Name),type:"file"}}for(const folder of asArray(blobs?.BlobPrefix)){if(!folder?.Name)continue;yield{path:this.stripPrefix(folder.Name.replace(/\/+$/,"")),type:"directory"}}marker=parsed?.EnumerationResults?.NextMarker||undefined}while(marker)}async changeVisibility(_path,_visibility){throw new Error("[storage/azure] visibility is a property of the container, not the blob - Azure has no per-blob ACL. Set the container's public access level in Azure, or hand out a time-limited URL with `signedUrl()`.")}async visibility(_path){const response=await this.request("GET",this.blobUrl(undefined,{restype:"container",comp:"acl"}),{expect:[200]});const level=response.headers.get("x-ms-blob-public-access");return level==="container"||level==="blob"?"public":"private"}async fileExists(path){try{await this.request("HEAD",this.blobUrl(this.blobName(path)),{expect:[200]});return true}catch{return false}}async directoryExists(path){for await(const _entry of this.list(path,{deep:true}))return true;return false}async publicUrl(path,options={}){const blob=this.blobName(path);const base=options.domain?.replace(/\/+$/,"")??this.publicBaseUrl;if(base)return`${base}/${blob}`;return this.blobUrl(blob).toString()}async temporaryUrl(path,options){return this.signUrl(path,Math.floor(normalizeExpiryToMilliseconds(options.expiresIn)/1000),"r")}async signedUrl(path,options){return this.signUrl(path,Math.floor(normalizeExpiryToMilliseconds(options.expiresIn)/1000),"r")}async presignedUploadUrl(options){if(!options.contentType)throw new Error("[storage/azure] presignedUploadUrl requires `contentType` - the SAS signs against it.");const safeDir=sanitizePresignedDir(options.dir);const safeFilename=options.filename!==undefined?sanitizePresignedFilename(options.filename):`${crypto.randomUUID().replace(/-/g,"")}${extensionForContentType(options.contentType)}`;const path=safeDir?`${safeDir}/${safeFilename}`:safeFilename;const url=await this.signUrl(path,Math.floor(options.expiresIn),"cw",options.contentType);return{url,path,key:this.blobName(path),contentType:options.contentType,maxBytes:options.maxBytes}}async signUrl(path,expiresIn,permissions,contentType){if(!this.accountKey){throw new Error("[storage/azure] signing a URL needs the account key. This disk is configured with a SAS token, and re-serving that token would hand out its full grant rather than a scoped one.")}if(!Number.isFinite(expiresIn)||expiresIn<MIN_EXPIRY_SECONDS||expiresIn>MAX_EXPIRY_SECONDS)throw new RangeError(`[storage/azure] expiresIn must be between 60s and 7 days (got ${expiresIn}s)`);const query=serviceSasQuery({account:this.account,accountKey:this.accountKey},{container:this.container,blob:this.blobName(path),permissions,expiresAt:new Date(Date.now()+expiresIn*1000),contentType});return`${this.blobUrl(this.blobName(path)).toString()}?${query}`}async checksum(path,options={}){const contents=await this.readToBuffer(path);return createHash(options.algorithm||"sha256").update(contents).digest("hex")}async mimeType(path,_options={}){const stats=await this.stat(path);return stats.mimeType??mimeFromExtension(path)}async lastModified(path){return(await this.stat(path)).lastModified}async fileSize(path){return(await this.stat(path)).size}}function asArray(value){if(value===undefined||value===null)return[];return Array.isArray(value)?value:[value]}function lastModifiedFrom(headers){const raw=headers.get("last-modified");const parsed=raw?Date.parse(raw):Number.NaN;return Number.isNaN(parsed)?Date.now():parsed}async function collect(stream){const reader=stream.getReader();const chunks=[];while(true){const{done,value}=await reader.read();if(done)break;if(value)chunks.push(Buffer.from(value))}return chunks}function streamOf(body){return new ReadableStream({start(controller){controller.enqueue(new Uint8Array(body));controller.close()}})}export function createAzureStorage(config){return new AzureBlobStorageAdapter(config)}
|
package/dist/adapters/bun.js
CHANGED
|
@@ -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)){if(typeof
|
|
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)}
|
package/dist/adapters/local.js
CHANGED
|
@@ -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")
|
|
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)}
|
package/dist/adapters/memory.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Buffer}from"node:buffer";import{mimeFromExtension}from"../mime-from-extension";import{createDirectoryListing,normalizeExpiryToDate}from"../types";export class InMemoryStorageAdapter{files;directories;constructor(){this.files=new Map;this.directories=new Set;this.directories.add("")}normalizePath(path){return path.replace(/^\/+/,"").replace(/\/+$/,"")}getDirectoryPath(path){const parts=path.split("/").filter(Boolean);parts.pop();return parts.join("/")}async contentsToUint8Array(contents,signal){signal?.throwIfAborted();if(typeof contents==="string")return new TextEncoder().encode(contents)
|
|
1
|
+
import{Buffer}from"node:buffer";import{mimeFromExtension}from"../mime-from-extension";import{createDirectoryListing,normalizeExpiryToDate}from"../types";export class InMemoryStorageAdapter{files;directories;constructor(){this.files=new Map;this.directories=new Set;this.directories.add("")}normalizePath(path){return path.replace(/^\/+/,"").replace(/\/+$/,"")}getDirectoryPath(path){const parts=path.split("/").filter(Boolean);parts.pop();return parts.join("/")}async contentsToUint8Array(contents,signal){signal?.throwIfAborted();if(typeof contents==="string"){return new TextEncoder().encode(contents)}else if(contents instanceof Buffer){return new Uint8Array(contents)}else if(contents instanceof Uint8Array){return new Uint8Array(contents)}else{const stream=contents;if(typeof stream.getReader!=="function"){throw new TypeError("[storage/memory] contents must be a web-standard ReadableStream "+"(with .getReader()), not a Node stream.Readable. "+"Convert via Readable.toWeb(nodeStream) before passing.")}const reader=contents.getReader();const chunks=[];const abort=()=>{reader.cancel(signal?.reason).catch(()=>{})};signal?.addEventListener("abort",abort,{once:true});try{if(signal?.aborted)abort();while(true){signal?.throwIfAborted();const{done,value}=await reader.read();signal?.throwIfAborted();if(done)break;if(value)chunks.push(new Uint8Array(value))}}finally{signal?.removeEventListener("abort",abort);reader.releaseLock()}const totalLength=chunks.reduce((sum,chunk)=>sum+chunk.length,0);const result=new Uint8Array(totalLength);let offset=0;for(const chunk of chunks){result.set(chunk,offset);offset+=chunk.length}return result}}async write(path,contents){const normalized=this.normalizePath(path);const dirPath=this.getDirectoryPath(normalized);if(dirPath){await this.createDirectory(dirPath)}const data=await this.contentsToUint8Array(contents);const lastModified=Date.now();const mimeType=this.detectMimeType(normalized);this.files.set(normalized,{contents:data,visibility:"private",mimeType,lastModified});return{path:normalized,size:data.length,contentType:mimeType,lastModified}}async read(path){const normalized=this.normalizePath(path);const file=this.files.get(normalized);if(!file){throw new Error(`File not found: ${path}`)}return new Uint8Array(file.contents)}async getStream(path,_options){const normalized=this.normalizePath(path);const file=this.files.get(normalized);if(!file)throw new Error(`File not found: ${path}`);const bytes=new Uint8Array(file.contents);return new ReadableStream({start(controller){controller.enqueue(bytes);controller.close()}})}async putStream(path,stream,options){const normalized=this.normalizePath(path);const dirPath=this.getDirectoryPath(normalized);if(dirPath)await this.createDirectory(dirPath);const data=await this.contentsToUint8Array(stream,options?.signal);options?.signal?.throwIfAborted();const lastModified=Date.now();const mimeType=options?.contentType??this.detectMimeType(normalized);this.files.set(normalized,{contents:data,visibility:"private",mimeType,lastModified});return{path:normalized,size:data.length,contentType:mimeType,lastModified}}async readToString(path){const data=await this.read(path);return new TextDecoder().decode(data)}async readToBuffer(path){const data=await this.read(path);return Buffer.from(data)}async readToUint8Array(path){const data=await this.read(path);return data}async deleteFile(path){this.files.delete(this.normalizePath(path))}async deleteDirectory(path){const normalized=this.normalizePath(path);const prefix=normalized?`${normalized}/`:"";for(const filePath of this.files.keys()){if(filePath===normalized||filePath.startsWith(prefix)){this.files.delete(filePath)}}for(const dir of this.directories){if(dir===normalized||dir.startsWith(prefix)){this.directories.delete(dir)}}}async createDirectory(path){const normalized=this.normalizePath(path);if(!normalized)return;const parts=normalized.split("/").filter(Boolean);let current="";for(const part of parts){current=current?`${current}/${part}`:part;this.directories.add(current)}}async moveFile(from,to){const normalizedFrom=this.normalizePath(from);const normalizedTo=this.normalizePath(to);const file=this.files.get(normalizedFrom);if(!file){throw new Error(`File not found: ${from}`)}if(normalizedFrom===normalizedTo)return;const toDir=this.getDirectoryPath(normalizedTo);if(toDir){await this.createDirectory(toDir)}this.files.set(normalizedTo,{...file,lastModified:Date.now()});this.files.delete(normalizedFrom)}async copyFile(from,to){const normalizedFrom=this.normalizePath(from);const normalizedTo=this.normalizePath(to);const file=this.files.get(normalizedFrom);if(!file){throw new Error(`File not found: ${from}`)}const toDir=this.getDirectoryPath(normalizedTo);if(toDir){await this.createDirectory(toDir)}const contentsCopy=new Uint8Array(file.contents);this.files.set(normalizedTo,{...file,contents:contentsCopy,lastModified:Date.now()})}async stat(path){const normalized=this.normalizePath(path);const file=this.files.get(normalized);if(file){return{path:normalized,type:"file",visibility:file.visibility,size:file.contents.length,lastModified:file.lastModified,mimeType:file.mimeType}}if(this.directories.has(normalized)||normalized===""){return{path:normalized,type:"directory",visibility:"private",size:0,lastModified:Date.now()}}throw new Error(`Path not found: ${path}`)}list(path,options={}){return this.createAsyncIterator(path,options.deep||false)}async*createAsyncIterator(path,deep){const normalized=this.normalizePath(path);const prefix=normalized?`${normalized}/`:"";const entries=[];const seen=new Set;for(const[filePath]of this.files){if(filePath.startsWith(prefix)||prefix===""){const relativePath=prefix?filePath.slice(prefix.length):filePath;if(!deep){const parts=relativePath.split("/").filter(Boolean);if(parts.length===1){entries.push({path:filePath,type:"file"})}}else{entries.push({path:filePath,type:"file"})}}}for(const dir of this.directories){if((dir.startsWith(prefix)||prefix==="")&&dir!==normalized){const relativePath=prefix?dir.slice(prefix.length):dir;if(!deep){const parts=relativePath.split("/").filter(Boolean);if(parts.length===1&&!seen.has(dir)){entries.push({path:dir,type:"directory"});seen.add(dir)}}else if(!seen.has(dir)){entries.push({path:dir,type:"directory"});seen.add(dir)}}}yield*createDirectoryListing(entries)}async changeVisibility(path,visibility){const normalized=this.normalizePath(path);const file=this.files.get(normalized);if(!file){throw new Error(`File not found: ${path}`)}file.visibility=visibility}async visibility(path){const normalized=this.normalizePath(path);const file=this.files.get(normalized);if(!file){throw new Error(`File not found: ${path}`)}return file.visibility}async fileExists(path){const normalized=this.normalizePath(path);return this.files.has(normalized)}async directoryExists(path){const normalized=this.normalizePath(path);return this.directories.has(normalized)||normalized===""}async publicUrl(path,options={}){const base=(options.domain||process.env.APP_URL||"http://localhost").replace(/\/$/,"");return`${base}/${this.normalizePath(path)}`}async temporaryUrl(path,options){const expiry=normalizeExpiryToDate(options.expiresIn);const token=Buffer.from(`${path}:${expiry.getTime()}`).toString("base64url");return`http://localhost/temp/${token}`}async signedUrl(_path,_options){throw new Error("[storage/memory] signedUrl is not supported on the in-memory adapter - switch to local or s3 disk for signed URL generation.")}async checksum(path,options={}){const algorithm=options.algorithm||"sha256";const data=await this.readToUint8Array(path);const hasher=new Bun.CryptoHasher(algorithm);hasher.update(data);return hasher.digest("hex")}async mimeType(path,_options={}){const normalized=this.normalizePath(path);const file=this.files.get(normalized);if(!file){throw new Error(`File not found: ${path}`)}return file.mimeType}detectMimeType(path){return mimeFromExtension(path)}async lastModified(path){const stats=await this.stat(path);return stats.lastModified}async fileSize(path){const stats=await this.stat(path);return stats.size}clear(){this.files.clear();this.directories.clear();this.directories.add("")}}export function createMemoryStorage(){return new InMemoryStorageAdapter}
|
package/dist/adapters/s3.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{directoryPageSize}from"../directory-page";import{Buffer}from"node:buffer";import{extensionForContentType,mimeFromExtension}from"../mime-from-extension";import{normalizeExpiryToMilliseconds}from"../types";import{sanitizePresignedDir,sanitizePresignedFilename}from"../path-sanitize";import{signS3PresignedPost}from"../s3-presigned-post";import process from"node:process";const S3_MIN_PART_SIZE=5242880,S3_MAX_PART_SIZE=5368709120;function clampPartSize(requested){if(!Number.isFinite(requested))return S3_MIN_PART_SIZE;return Math.max(S3_MIN_PART_SIZE,Math.min(Math.floor(requested),S3_MAX_PART_SIZE))}class ChunkBuffer{chunks=[];total=0;constructor(_partSize){}get length(){return this.total}push(c){this.chunks.push(c);this.total+=c.length}take(n){const out=new Uint8Array(n);let written=0;while(written<n&&this.chunks.length>0){const head=this.chunks[0],need=n-written;if(head.length<=need){out.set(head,written);written+=head.length;this.chunks.shift()}else{out.set(head.subarray(0,need),written);this.chunks[0]=head.subarray(need);written+=need}}this.total-=n;return out}flush(){const out=new Uint8Array(this.total);let off=0;for(const c of this.chunks){out.set(c,off);off+=c.length}this.chunks=[];this.total=0;return out}}async function isSettled(p){const sentinel=Symbol("pending");return await Promise.race([p.then(()=>"settled",()=>"settled"),Promise.resolve(sentinel)])!==sentinel}export function resolveS3ClientOptions(config){const options={};if(config.endpoint)options.endpoint=config.endpoint.replace(/^https:\/\//i,"").replace(/\/+$/,"");if(config.usePathStyleEndpoint)options.forcePathStyle=!0;if(config.credentials)options.credentials=config.credentials;return Object.keys(options).length>0?options:void 0}export class S3StorageAdapter{_client;_clientPromise=null;bucket;prefix;region;endpoint;usePathStyleEndpoint;publicBaseUrl;credentials;constructor(client,config){this._client=client;this.bucket=config.bucket||"";this.prefix=config.prefix||"";this.region=config.region||"us-east-1";this.credentials=config.credentials;this.endpoint=config.endpoint;this.usePathStyleEndpoint=config.usePathStyleEndpoint;this.publicBaseUrl=config.url?.replace(/\/+$/,"");if(!this.bucket)throw Error("S3 bucket name is required")}async getClient(){if(this._client)return this._client;if(!this._clientPromise)this._clientPromise=import("@stacksjs/ts-cloud").then((cloud)=>{this._client=new cloud.S3Client(this.region,void 0,resolveS3ClientOptions({endpoint:this.endpoint,usePathStyleEndpoint:this.usePathStyleEndpoint,credentials:this.credentials}));return this._client});return this._clientPromise}resolveCredentials(){if(this.credentials?.accessKeyId&&this.credentials.secretAccessKey)return this.credentials;const accessKeyId=process.env.AWS_ACCESS_KEY_ID,secretAccessKey=process.env.AWS_SECRET_ACCESS_KEY,sessionToken=process.env.AWS_SESSION_TOKEN;if(!accessKeyId||!secretAccessKey)throw Error("[storage/s3] presignedUploadPolicy requires AWS credentials - pass them via S3DiskConfig.credentials or set AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY.");return{accessKeyId,secretAccessKey,sessionToken}}prefixPath(path){if(!this.prefix)return path;return`${this.prefix}/${path}`.replace(/\/+/g,"/")}stripPrefix(path){if(!this.prefix)return path;const prefixWithSlash=`${this.prefix}/`;return path.startsWith(prefixWithSlash)?path.slice(prefixWithSlash.length):path}async contentsToBuffer(contents){if(typeof contents==="string")return Buffer.from(contents,"utf8");else if(contents instanceof Buffer)return contents;else if(contents instanceof Uint8Array)return Buffer.from(contents);else{if(typeof contents.getReader!=="function")throw TypeError("[storage/s3] contents must be a web-standard ReadableStream (with .getReader()), not a Node stream.Readable. Convert via Readable.toWeb(nodeStream) before passing.");const reader=contents.getReader(),chunks=[];while(!0){const{done,value}=await reader.read();if(done)break;if(value)chunks.push(value)}return Buffer.concat(chunks.map((c)=>Buffer.from(c)))}}async write(path,contents){const key=this.prefixPath(path),body=await this.contentsToBuffer(contents),contentType=this.detectMimeType(path);await(await this.getClient()).putObject({bucket:this.bucket,key,body,contentType});return{path,size:body.length,contentType,lastModified:Date.now()}}async read(path){const key=this.prefixPath(path),response=await(await this.getClient()).getObjectBytes(this.bucket,key);if(!response?.body)throw Error(`Failed to read file: ${path}`);return Buffer.from(response.body)}async getStream(path,_options){const key=this.prefixPath(path),buf=await(await this.getClient()).getObjectBuffer(this.bucket,key);if(!buf)throw Error(`Failed to read file: ${path}`);const bytes=new Uint8Array(buf);return new ReadableStream({start(controller){controller.enqueue(bytes);controller.close()}})}async putStream(path,stream,options){const key=this.prefixPath(path),contentType=options?.contentType??this.detectMimeType(path),partSize=clampPartSize(options?.partSize??5242880),concurrency=Math.max(1,Math.min(options?.concurrency??4,100)),maxRetries=Math.max(0,options?.maxRetries??3),signal=options?.signal,reader=stream.getReader();let firstChunk=null,firstDone=!1;{const buf=new ChunkBuffer(partSize);while(!firstDone&&buf.length<partSize){if(signal?.aborted){try{reader.releaseLock()}catch{}throw Error("aborted")}const{value,done}=await reader.read();if(done){firstDone=!0;break}if(value)buf.push(value)}firstChunk=buf.flush()}if(firstDone){try{reader.releaseLock()}catch{}await(await this.getClient()).putObject({bucket:this.bucket,key,body:Buffer.from(firstChunk),contentType});return{path,size:firstChunk.length,contentType,lastModified:Date.now()}}const{UploadId:uploadId}=await(await this.getClient()).createMultipartUpload(this.bucket,key,{contentType}),completedParts=[];let totalBytes=0,partNumber=1;const inflight=[],uploadOne=async(body,n)=>{let attempt=0;while(!0){if(signal?.aborted)throw Error("aborted");try{const{ETag}=await(await this.getClient()).uploadPart(this.bucket,key,uploadId,n,Buffer.from(body));completedParts.push({PartNumber:n,ETag});totalBytes+=body.length;return}catch(err){if(attempt>=maxRetries)throw err;attempt+=1}}};try{inflight.push(uploadOne(firstChunk,partNumber++));firstChunk=null;const buf=new ChunkBuffer(partSize);while(!0){if(signal?.aborted)throw Error("aborted");const{value,done}=await reader.read();if(done)break;if(value)buf.push(value);while(buf.length>=partSize){const part=buf.take(partSize);if(inflight.length>=concurrency){await Promise.race(inflight.map((p,i)=>p.then(()=>i)));for(let i=inflight.length-1;i>=0;i--)if(await isSettled(inflight[i]))inflight.splice(i,1)}inflight.push(uploadOne(part,partNumber++))}}try{reader.releaseLock()}catch{}const tail=buf.flush();if(tail.length>0)inflight.push(uploadOne(tail,partNumber++));await Promise.all(inflight);completedParts.sort((a,b)=>a.PartNumber-b.PartNumber);await(await this.getClient()).completeMultipartUpload(this.bucket,key,uploadId,completedParts);return{path,size:totalBytes,contentType,lastModified:Date.now()}}catch(err){try{await(await this.getClient()).abortMultipartUpload(this.bucket,key,uploadId)}catch{}throw err}}async readToString(path){const key=this.prefixPath(path),response=await(await this.getClient()).getObject(this.bucket,key);if(!response)throw Error(`Failed to read file: ${path}`);return response}async readToBuffer(path){return await this.read(path)}async readToUint8Array(path){const buffer=await this.readToBuffer(path);return new Uint8Array(buffer)}async deleteFile(path){const key=this.prefixPath(path);await(await this.getClient()).deleteObject(this.bucket,key)}async deleteDirectory(path){const prefix=this.prefixPath(path).replace(/\/+$/,""),normalizedPrefix=prefix?`${prefix}/`:void 0,keys=(await(await this.getClient()).listAllObjects({bucket:this.bucket,prefix:normalizedPrefix})).map((obj)=>obj.Key).filter((k)=>typeof k==="string");if(keys.length===0)return;await(await this.getClient()).deleteObjects(this.bucket,keys)}async createDirectory(_path){}async moveFile(from,to){await this.copyFile(from,to);await this.deleteFile(from)}async copyFile(from,to){const fromKey=this.prefixPath(from),toKey=this.prefixPath(to);await(await this.getClient()).copyObject({sourceBucket:this.bucket,sourceKey:fromKey,destinationBucket:this.bucket,destinationKey:toKey})}async stat(path){const key=this.prefixPath(path),result=await(await this.getClient()).headObject(this.bucket,key);if(!result)throw Error(`File not found: ${path}`);return{path,type:"file",visibility:"private",size:result.ContentLength||0,lastModified:result.LastModified?new Date(result.LastModified).getTime():Date.now(),mimeType:result.ContentType}}async listPage(path,options={}){const prefix=this.prefixPath(path).replace(/\/+$/,""),result=await(await this.getClient()).listObjects({bucket:this.bucket,prefix:prefix?`${prefix}/`:void 0,delimiter:"/",maxKeys:directoryPageSize(options),continuationToken:options.cursor||void 0});return{entries:[...(result.objects||[]).filter((obj)=>obj.Key!==`${prefix}/`).map((obj)=>({path:this.stripPrefix(obj.Key),type:"file"})),...(result.commonPrefixes||[]).map((folder)=>({path:this.stripPrefix(folder.replace(/\/$/,"")),type:"directory"}))],nextCursor:result.nextContinuationToken||null}}list(path,options={}){return this.createAsyncIterator(path,options.deep||!1)}async*createAsyncIterator(path,deep){const prefix=this.prefixPath(path).replace(/\/+$/,""),normalizedPrefix=prefix?`${prefix}/`:void 0;if(deep){const objects=await(await this.getClient()).listAllObjects({bucket:this.bucket,prefix:normalizedPrefix});for(const obj of objects)yield{path:this.stripPrefix(obj.Key),type:"file"}}else{let continuationToken;do{const result=await(await this.getClient()).listObjects({bucket:this.bucket,prefix:normalizedPrefix,delimiter:"/",continuationToken});for(const obj of result.objects||[]){if(obj.Key===normalizedPrefix)continue;yield{path:this.stripPrefix(obj.Key),type:"file"}}for(const folder of result.commonPrefixes||[])yield{path:this.stripPrefix(folder.replace(/\/$/,"")),type:"directory"};continuationToken=result.nextContinuationToken}while(continuationToken)}}async changeVisibility(path,vis){const key=this.prefixPath(path),acl=vis==="public"?"public-read":"private";await(await this.getClient()).putObjectAcl(this.bucket,key,acl)}async visibility(path){const key=this.prefixPath(path),grant=(await(await this.getClient()).getObjectAcl(this.bucket,key))?.AccessControlList?.Grant;return(grant===void 0?[]:Array.isArray(grant)?grant:[grant]).some((g)=>g.Grantee?.URI==="http://acs.amazonaws.com/groups/global/AllUsers"&&(g.Permission==="READ"||g.Permission==="FULL_CONTROL"))?"public":"private"}async fileExists(path){const key=this.prefixPath(path);try{return!!await(await this.getClient()).headObject(this.bucket,key)}catch(error){if(!error.message?.includes("404")&&!error.message?.includes("NoSuchKey")&&!error.message?.includes("NotFound"))console.debug(`[s3] Unexpected error checking file existence for ${path}: ${error.message}`);return!1}}async directoryExists(path){const prefix=this.prefixPath(path);return((await(await this.getClient()).listObjects({bucket:this.bucket,prefix:`${prefix}/`,maxKeys:1})).objects||[]).length>0}async publicUrl(path,options={}){const key=this.prefixPath(path),base=options.domain?.replace(/\/+$/,"")??this.publicBaseUrl;if(base)return`${base}/${key}`;if(this.endpoint)return`${this.endpointBaseUrl()}/${key}`;return`https://${this.bucket}.s3.${this.region}.amazonaws.com/${key}`}endpointBaseUrl(){const endpoint=this.endpoint.replace(/\/+$/,""),withScheme=/^https?:\/\//.test(endpoint)?endpoint:`https://${endpoint}`;if(this.usePathStyleEndpoint)return`${withScheme}/${this.bucket}`;const url=new URL(withScheme);url.hostname=`${this.bucket}.${url.hostname}`;return url.origin}async temporaryUrl(path,options){const key=this.prefixPath(path),expiresIn=Math.floor(normalizeExpiryToMilliseconds(options.expiresIn)/1000),MIN_EXPIRY=60,MAX_EXPIRY=604800;if(!Number.isFinite(expiresIn)||expiresIn<MIN_EXPIRY||expiresIn>MAX_EXPIRY)throw RangeError(`[storage/s3] temporaryUrl expiresIn must be between 60s and 7 days (got ${expiresIn}s)`);return await(await this.getClient()).getSignedUrl({bucket:this.bucket,key,expiresIn,operation:"getObject"})}async signedUrl(path,options){return this.temporaryUrl(path,{expiresIn:options.expiresIn})}async presignedUploadUrl(options){if(!options.contentType)throw Error("[storage/s3] presignedUploadUrl requires `contentType` - S3 signs against the exact header.");const expiresIn=Math.floor(options.expiresIn),MIN_EXPIRY=60,MAX_EXPIRY=604800;if(!Number.isFinite(expiresIn)||expiresIn<MIN_EXPIRY||expiresIn>MAX_EXPIRY)throw RangeError(`[storage/s3] presignedUploadUrl expiresIn must be between 60s and 7 days (got ${expiresIn}s)`);const safeDir=sanitizePresignedDir(options.dir),safeFilename=options.filename!==void 0?sanitizePresignedFilename(options.filename):`${crypto.randomUUID().replace(/-/g,"")}${this.extensionForContentType(options.contentType)}`,path=safeDir?`${safeDir}/${safeFilename}`:safeFilename,key=this.prefixPath(path);return{url:await(await this.getClient()).getSignedUrl({bucket:this.bucket,key,expiresIn,operation:"putObject"}),path,key,contentType:options.contentType,maxBytes:options.maxBytes}}async presignedUploadPolicy(options){const credentials=this.resolveCredentials(),scopedKey=typeof options.key==="string"?this.prefixPath(options.key):{startsWith:this.prefixPath(options.key.startsWith)};return signS3PresignedPost({bucket:this.bucket,region:this.region,credentials,key:scopedKey,contentType:options.contentType,contentLengthRange:options.contentLengthRange,acl:options.acl,expiresIn:options.expiresIn,fields:options.fields})}extensionForContentType(contentType){return extensionForContentType(contentType)}async checksum(path,options={}){const algorithm=options.algorithm||"sha256",content=await this.readToUint8Array(path),hasher=new Bun.CryptoHasher(algorithm);hasher.update(content);return hasher.digest("hex")}async mimeType(path,_options={}){return(await this.stat(path)).mimeType||this.detectMimeType(path)}detectMimeType(path){return mimeFromExtension(path)}async lastModified(path){return(await this.stat(path)).lastModified}async fileSize(path){return(await this.stat(path)).size}}export function createS3Storage(client,config){return new S3StorageAdapter(client,config)}
|
|
1
|
+
import{directoryPageSize}from"../directory-page";import{Buffer}from"node:buffer";import{extensionForContentType,mimeFromExtension}from"../mime-from-extension";import{normalizeExpiryToMilliseconds}from"../types";import{sanitizePresignedDir,sanitizePresignedFilename}from"../path-sanitize";import{signS3PresignedPost}from"../s3-presigned-post";import process from"node:process";const S3_MIN_PART_SIZE=5*1024*1024;const S3_MAX_PART_SIZE=5*1024*1024*1024;function clampPartSize(requested){if(!Number.isFinite(requested))return S3_MIN_PART_SIZE;return Math.max(S3_MIN_PART_SIZE,Math.min(Math.floor(requested),S3_MAX_PART_SIZE))}class ChunkBuffer{chunks=[];total=0;constructor(_partSize){}get length(){return this.total}push(c){this.chunks.push(c);this.total+=c.length}take(n){const out=new Uint8Array(n);let written=0;while(written<n&&this.chunks.length>0){const head=this.chunks[0];const need=n-written;if(head.length<=need){out.set(head,written);written+=head.length;this.chunks.shift()}else{out.set(head.subarray(0,need),written);this.chunks[0]=head.subarray(need);written+=need}}this.total-=n;return out}flush(){const out=new Uint8Array(this.total);let off=0;for(const c of this.chunks){out.set(c,off);off+=c.length}this.chunks=[];this.total=0;return out}}async function isSettled(p){const sentinel=Symbol("pending");const result=await Promise.race([p.then(()=>"settled",()=>"settled"),Promise.resolve(sentinel)]);return result!==sentinel}export function resolveS3ClientOptions(config){const options={};if(config.endpoint){options.endpoint=config.endpoint.replace(/^https:\/\//i,"").replace(/\/+$/,"")}if(config.usePathStyleEndpoint)options.forcePathStyle=true;if(config.credentials)options.credentials=config.credentials;return Object.keys(options).length>0?options:undefined}export class S3StorageAdapter{_client;_clientPromise=null;bucket;prefix;region;endpoint;usePathStyleEndpoint;publicBaseUrl;credentials;constructor(client,config){this._client=client;this.bucket=config.bucket||"";this.prefix=config.prefix||"";this.region=config.region||"us-east-1";this.credentials=config.credentials;this.endpoint=config.endpoint;this.usePathStyleEndpoint=config.usePathStyleEndpoint;this.publicBaseUrl=config.url?.replace(/\/+$/,"");if(!this.bucket){throw new Error("S3 bucket name is required")}}async getClient(){if(this._client)return this._client;if(!this._clientPromise){this._clientPromise=import("@stacksjs/ts-cloud").then((cloud)=>{this._client=new cloud.S3Client(this.region,undefined,resolveS3ClientOptions({endpoint:this.endpoint,usePathStyleEndpoint:this.usePathStyleEndpoint,credentials:this.credentials}));return this._client})}return this._clientPromise}resolveCredentials(){if(this.credentials?.accessKeyId&&this.credentials.secretAccessKey)return this.credentials;const accessKeyId=process.env.AWS_ACCESS_KEY_ID;const secretAccessKey=process.env.AWS_SECRET_ACCESS_KEY;const sessionToken=process.env.AWS_SESSION_TOKEN;if(!accessKeyId||!secretAccessKey){throw new Error("[storage/s3] presignedUploadPolicy requires AWS credentials - pass them via S3DiskConfig.credentials or set AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY.")}return{accessKeyId,secretAccessKey,sessionToken}}prefixPath(path){if(!this.prefix)return path;return`${this.prefix}/${path}`.replace(/\/+/g,"/")}stripPrefix(path){if(!this.prefix)return path;const prefixWithSlash=`${this.prefix}/`;return path.startsWith(prefixWithSlash)?path.slice(prefixWithSlash.length):path}async contentsToBuffer(contents){if(typeof contents==="string"){return Buffer.from(contents,"utf8")}else if(contents instanceof Buffer){return contents}else if(contents instanceof Uint8Array){return Buffer.from(contents)}else{const stream=contents;if(typeof stream.getReader!=="function"){throw new TypeError("[storage/s3] contents must be a web-standard ReadableStream (with .getReader()), not a Node stream.Readable. Convert via Readable.toWeb(nodeStream) before passing.")}const reader=contents.getReader();const chunks=[];while(true){const{done,value}=await reader.read();if(done)break;if(value)chunks.push(value)}return Buffer.concat(chunks.map((c)=>Buffer.from(c)))}}async write(path,contents){const key=this.prefixPath(path);const body=await this.contentsToBuffer(contents);const contentType=this.detectMimeType(path);await(await this.getClient()).putObject({bucket:this.bucket,key,body,contentType});return{path,size:body.length,contentType,lastModified:Date.now()}}async read(path){const key=this.prefixPath(path);const response=await(await this.getClient()).getObjectBytes(this.bucket,key);if(!response?.body){throw new Error(`Failed to read file: ${path}`)}return Buffer.from(response.body)}async getStream(path,_options){const key=this.prefixPath(path);const buf=await(await this.getClient()).getObjectBuffer(this.bucket,key);if(!buf)throw new Error(`Failed to read file: ${path}`);const bytes=new Uint8Array(buf);return new ReadableStream({start(controller){controller.enqueue(bytes);controller.close()}})}async putStream(path,stream,options){const key=this.prefixPath(path);const contentType=options?.contentType??this.detectMimeType(path);const partSize=clampPartSize(options?.partSize??5242880);const concurrency=Math.max(1,Math.min(options?.concurrency??4,100));const maxRetries=Math.max(0,options?.maxRetries??3);const signal=options?.signal;const reader=stream.getReader();let firstChunk=null;let firstDone=false;{const buf=new ChunkBuffer(partSize);while(!firstDone&&buf.length<partSize){if(signal?.aborted){try{reader.releaseLock()}catch{}throw new Error("aborted")}const{value,done}=await reader.read();if(done){firstDone=true;break}if(value)buf.push(value)}firstChunk=buf.flush()}if(firstDone){try{reader.releaseLock()}catch{}await(await this.getClient()).putObject({bucket:this.bucket,key,body:Buffer.from(firstChunk),contentType});return{path,size:firstChunk.length,contentType,lastModified:Date.now()}}const{UploadId:uploadId}=await(await this.getClient()).createMultipartUpload(this.bucket,key,{contentType});const completedParts=[];let totalBytes=0;let partNumber=1;const inflight=[];const uploadOne=async(body,n)=>{let attempt=0;while(true){if(signal?.aborted)throw new Error("aborted");try{const{ETag}=await(await this.getClient()).uploadPart(this.bucket,key,uploadId,n,Buffer.from(body));completedParts.push({PartNumber:n,ETag});totalBytes+=body.length;return}catch(err){if(attempt>=maxRetries)throw err;attempt+=1}}};try{inflight.push(uploadOne(firstChunk,partNumber++));firstChunk=null;const buf=new ChunkBuffer(partSize);while(true){if(signal?.aborted)throw new Error("aborted");const{value,done}=await reader.read();if(done)break;if(value)buf.push(value);while(buf.length>=partSize){const part=buf.take(partSize);if(inflight.length>=concurrency){await Promise.race(inflight.map((p,i)=>p.then(()=>i)));for(let i=inflight.length-1;i>=0;i--){if(await isSettled(inflight[i]))inflight.splice(i,1)}}inflight.push(uploadOne(part,partNumber++))}}try{reader.releaseLock()}catch{}const tail=buf.flush();if(tail.length>0)inflight.push(uploadOne(tail,partNumber++));await Promise.all(inflight);completedParts.sort((a,b)=>a.PartNumber-b.PartNumber);await(await this.getClient()).completeMultipartUpload(this.bucket,key,uploadId,completedParts);return{path,size:totalBytes,contentType,lastModified:Date.now()}}catch(err){try{await(await this.getClient()).abortMultipartUpload(this.bucket,key,uploadId)}catch{}throw err}}async readToString(path){const key=this.prefixPath(path);const response=await(await this.getClient()).getObject(this.bucket,key);if(!response){throw new Error(`Failed to read file: ${path}`)}return response}async readToBuffer(path){const contents=await this.read(path);return contents}async readToUint8Array(path){const buffer=await this.readToBuffer(path);return new Uint8Array(buffer)}async deleteFile(path){const key=this.prefixPath(path);await(await this.getClient()).deleteObject(this.bucket,key)}async deleteDirectory(path){const prefix=this.prefixPath(path).replace(/\/+$/,"");const normalizedPrefix=prefix?`${prefix}/`:undefined;const objects=await(await this.getClient()).listAllObjects({bucket:this.bucket,prefix:normalizedPrefix});const keys=objects.map((obj)=>obj.Key).filter((k)=>typeof k==="string");if(keys.length===0){return}await(await this.getClient()).deleteObjects(this.bucket,keys)}async createDirectory(_path){}async moveFile(from,to){await this.copyFile(from,to);await this.deleteFile(from)}async copyFile(from,to){const fromKey=this.prefixPath(from);const toKey=this.prefixPath(to);await(await this.getClient()).copyObject({sourceBucket:this.bucket,sourceKey:fromKey,destinationBucket:this.bucket,destinationKey:toKey})}async stat(path){const key=this.prefixPath(path);const result=await(await this.getClient()).headObject(this.bucket,key);if(!result){throw new Error(`File not found: ${path}`)}return{path,type:"file",visibility:"private",size:result.ContentLength||0,lastModified:result.LastModified?new Date(result.LastModified).getTime():Date.now(),mimeType:result.ContentType}}async listPage(path,options={}){const prefix=this.prefixPath(path).replace(/\/+$/,"");const result=await(await this.getClient()).listObjects({bucket:this.bucket,prefix:prefix?`${prefix}/`:undefined,delimiter:"/",maxKeys:directoryPageSize(options),continuationToken:options.cursor||undefined});return{entries:[...(result.objects||[]).filter((obj)=>obj.Key!==`${prefix}/`).map((obj)=>({path:this.stripPrefix(obj.Key),type:"file"})),...(result.commonPrefixes||[]).map((folder)=>({path:this.stripPrefix(folder.replace(/\/$/,"")),type:"directory"}))],nextCursor:result.nextContinuationToken||null}}list(path,options={}){return this.createAsyncIterator(path,options.deep||false)}async*createAsyncIterator(path,deep){const prefix=this.prefixPath(path).replace(/\/+$/,"");const normalizedPrefix=prefix?`${prefix}/`:undefined;if(deep){const objects=await(await this.getClient()).listAllObjects({bucket:this.bucket,prefix:normalizedPrefix});for(const obj of objects){yield{path:this.stripPrefix(obj.Key),type:"file"}}}else{let continuationToken;do{const result=await(await this.getClient()).listObjects({bucket:this.bucket,prefix:normalizedPrefix,delimiter:"/",continuationToken});for(const obj of result.objects||[]){if(obj.Key===normalizedPrefix)continue;yield{path:this.stripPrefix(obj.Key),type:"file"}}for(const folder of result.commonPrefixes||[]){yield{path:this.stripPrefix(folder.replace(/\/$/,"")),type:"directory"}}continuationToken=result.nextContinuationToken}while(continuationToken)}}async changeVisibility(path,vis){const key=this.prefixPath(path);const acl=vis==="public"?"public-read":"private";await(await this.getClient()).putObjectAcl(this.bucket,key,acl)}async visibility(path){const key=this.prefixPath(path);const acl=await(await this.getClient()).getObjectAcl(this.bucket,key);const grant=acl?.AccessControlList?.Grant;const grants=grant===undefined?[]:Array.isArray(grant)?grant:[grant];const isPublic=grants.some((g)=>g.Grantee?.URI==="http://acs.amazonaws.com/groups/global/AllUsers"&&(g.Permission==="READ"||g.Permission==="FULL_CONTROL"));return isPublic?"public":"private"}async fileExists(path){const key=this.prefixPath(path);try{const result=await(await this.getClient()).headObject(this.bucket,key);return!!result}catch(error){if(!error.message?.includes("404")&&!error.message?.includes("NoSuchKey")&&!error.message?.includes("NotFound")){console.debug(`[s3] Unexpected error checking file existence for ${path}: ${error.message}`)}return false}}async directoryExists(path){const prefix=this.prefixPath(path);const result=await(await this.getClient()).listObjects({bucket:this.bucket,prefix:`${prefix}/`,maxKeys:1});return(result.objects||[]).length>0}async publicUrl(path,options={}){const key=this.prefixPath(path);const base=options.domain?.replace(/\/+$/,"")??this.publicBaseUrl;if(base)return`${base}/${key}`;if(this.endpoint)return`${this.endpointBaseUrl()}/${key}`;return`https://${this.bucket}.s3.${this.region}.amazonaws.com/${key}`}endpointBaseUrl(){const endpoint=this.endpoint.replace(/\/+$/,"");const withScheme=/^https?:\/\//.test(endpoint)?endpoint:`https://${endpoint}`;if(this.usePathStyleEndpoint)return`${withScheme}/${this.bucket}`;const url=new URL(withScheme);url.hostname=`${this.bucket}.${url.hostname}`;return url.origin}async temporaryUrl(path,options){const key=this.prefixPath(path);const expiresIn=Math.floor(normalizeExpiryToMilliseconds(options.expiresIn)/1000);const MIN_EXPIRY=60;const MAX_EXPIRY=604800;if(!Number.isFinite(expiresIn)||expiresIn<MIN_EXPIRY||expiresIn>MAX_EXPIRY){throw new RangeError(`[storage/s3] temporaryUrl expiresIn must be between 60s and 7 days (got ${expiresIn}s)`)}return await(await this.getClient()).getSignedUrl({bucket:this.bucket,key,expiresIn,operation:"getObject"})}async signedUrl(path,options){return this.temporaryUrl(path,{expiresIn:options.expiresIn})}async presignedUploadUrl(options){if(!options.contentType)throw new Error("[storage/s3] presignedUploadUrl requires `contentType` - S3 signs against the exact header.");const expiresIn=Math.floor(options.expiresIn);const MIN_EXPIRY=60;const MAX_EXPIRY=604800;if(!Number.isFinite(expiresIn)||expiresIn<MIN_EXPIRY||expiresIn>MAX_EXPIRY){throw new RangeError(`[storage/s3] presignedUploadUrl expiresIn must be between 60s and 7 days (got ${expiresIn}s)`)}const safeDir=sanitizePresignedDir(options.dir);const safeFilename=options.filename!==undefined?sanitizePresignedFilename(options.filename):`${crypto.randomUUID().replace(/-/g,"")}${this.extensionForContentType(options.contentType)}`;const path=safeDir?`${safeDir}/${safeFilename}`:safeFilename;const key=this.prefixPath(path);const url=await(await this.getClient()).getSignedUrl({bucket:this.bucket,key,expiresIn,operation:"putObject"});return{url,path,key,contentType:options.contentType,maxBytes:options.maxBytes}}async presignedUploadPolicy(options){const credentials=this.resolveCredentials();const scopedKey=typeof options.key==="string"?this.prefixPath(options.key):{startsWith:this.prefixPath(options.key.startsWith)};return signS3PresignedPost({bucket:this.bucket,region:this.region,credentials,key:scopedKey,contentType:options.contentType,contentLengthRange:options.contentLengthRange,acl:options.acl,expiresIn:options.expiresIn,fields:options.fields})}extensionForContentType(contentType){return extensionForContentType(contentType)}async checksum(path,options={}){const algorithm=options.algorithm||"sha256";const content=await this.readToUint8Array(path);const hasher=new Bun.CryptoHasher(algorithm);hasher.update(content);return hasher.digest("hex")}async mimeType(path,_options={}){const stats=await this.stat(path);return stats.mimeType||this.detectMimeType(path)}detectMimeType(path){return mimeFromExtension(path)}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 createS3Storage(client,config){return new S3StorageAdapter(client,config)}
|
package/dist/adapters/scoped.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const DEFAULT_SCOPE_PATTERN=/^[a-z0-9_-]+$/i;export class ScopedStorageAdapter{inner;scope;scopeWithSlash;constructor(inner,options){const pattern=options.scopePattern??DEFAULT_SCOPE_PATTERN
|
|
1
|
+
const DEFAULT_SCOPE_PATTERN=/^[a-z0-9_-]+$/i;export class ScopedStorageAdapter{inner;scope;scopeWithSlash;constructor(inner,options){const pattern=options.scopePattern??DEFAULT_SCOPE_PATTERN;const cleaned=String(options.scope).replace(/^\/+|\/+$/g,"");if(!cleaned)throw new Error("[storage/scoped] scope is required");if(!pattern.test(cleaned))throw new Error(`[storage/scoped] scope '${cleaned}' contains disallowed characters`);if(cleaned.includes("..")||cleaned.includes("/"))throw new Error(`[storage/scoped] scope '${cleaned}' cannot contain path separators or traversal`);this.inner=inner;this.scope=cleaned;this.scopeWithSlash=`${cleaned}/`}scopePath(path){if(typeof path!=="string")throw new Error("[storage/scoped] path must be a string");if(path.length===0)return this.scope;if(path.includes("\x00"))throw new Error("[storage/scoped] path contains a null byte");if(path.startsWith("/")||/^[A-Za-z]:[\\/]/.test(path))throw new Error(`[storage/scoped] path '${path}' is absolute - refusing to escape scope`);const segments=path.split(/[/\\]/);if(segments.some((s)=>s===".."))throw new Error(`[storage/scoped] path '${path}' contains a '..' segment - refusing to escape scope`);return`${this.scope}/${path.replace(/^\/+/,"")}`}unscopePath(path){if(path===this.scope)return"";if(path.startsWith(this.scopeWithSlash))return path.slice(this.scopeWithSlash.length);return path}async write(path,contents){const result=await this.inner.write(this.scopePath(path),contents);return{...result,path:this.unscopePath(result.path)}}async read(path){return this.inner.read(this.scopePath(path))}async readToString(path){return this.inner.readToString(this.scopePath(path))}async readToBuffer(path){return this.inner.readToBuffer(this.scopePath(path))}async readToUint8Array(path){return this.inner.readToUint8Array(this.scopePath(path))}async deleteFile(path){return this.inner.deleteFile(this.scopePath(path))}async deleteDirectory(path){return this.inner.deleteDirectory(this.scopePath(path))}async createDirectory(path){return this.inner.createDirectory(this.scopePath(path))}async moveFile(from,to){return this.inner.moveFile(this.scopePath(from),this.scopePath(to))}async copyFile(from,to){return this.inner.copyFile(this.scopePath(from),this.scopePath(to))}async stat(path){const entry=await this.inner.stat(this.scopePath(path));return{...entry,path:this.unscopePath(entry.path)}}list(path,options){const inner=this.inner.list(this.scopePath(path),options);const unscope=this.unscopePath.bind(this);return async function*(){for await(const entry of inner){yield{...entry,path:unscope(entry.path)}}}()}async changeVisibility(path,visibility){return this.inner.changeVisibility(this.scopePath(path),visibility)}async visibility(path){return this.inner.visibility(this.scopePath(path))}async fileExists(path){return this.inner.fileExists(this.scopePath(path))}async directoryExists(path){return this.inner.directoryExists(this.scopePath(path))}async publicUrl(path,options){return this.inner.publicUrl(this.scopePath(path),options)}async temporaryUrl(path,options){return this.inner.temporaryUrl(this.scopePath(path),options)}async signedUrl(path,options){if(typeof this.inner.signedUrl!=="function")throw new Error("[storage/scoped] wrapped adapter does not support signedUrl");return this.inner.signedUrl(this.scopePath(path),options)}async presignedUploadUrl(options){if(typeof this.inner.presignedUploadUrl!=="function")throw new Error("[storage/scoped] wrapped adapter does not support presignedUploadUrl");const scopedDir=options.dir?`${this.scope}/${options.dir.replace(/^\/+/,"")}`:this.scope;const result=await this.inner.presignedUploadUrl({...options,dir:scopedDir});return{...result,path:this.unscopePath(result.path),key:this.unscopePath(result.key)}}async presignedUploadPolicy(options){if(typeof this.inner.presignedUploadPolicy!=="function")throw new Error("[storage/scoped] wrapped adapter does not support presignedUploadPolicy");const scopedKey=typeof options.key==="string"?this.scopePath(options.key):{startsWith:options.key.startsWith===""?this.scopeWithSlash:this.scopePath(options.key.startsWith)};const result=await this.inner.presignedUploadPolicy({...options,key:scopedKey});return{...result,key:this.unscopePath(result.key)}}async getStream(path,options){if(typeof this.inner.getStream!=="function")throw new Error("[storage/scoped] wrapped adapter does not support getStream");return this.inner.getStream(this.scopePath(path),options)}async putStream(path,stream,options){if(typeof this.inner.putStream!=="function")throw new Error("[storage/scoped] wrapped adapter does not support putStream");const result=await this.inner.putStream(this.scopePath(path),stream,options);return{...result,path:this.unscopePath(result.path)}}async checksum(path,options){return this.inner.checksum(this.scopePath(path),options)}async mimeType(path,options){return this.inner.mimeType(this.scopePath(path),options)}async lastModified(path){return this.inner.lastModified(this.scopePath(path))}async fileSize(path){return this.inner.fileSize(this.scopePath(path))}}export function scoped(inner,options){return new ScopedStorageAdapter(inner,options)}
|
package/dist/azure-signing.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{Buffer}from"node:buffer";import{createHmac}from"node:crypto";export const SAS_VERSION="2020-12-06"
|
|
2
|
-
`).join("")}export function canonicalizedResource(account,url){const parsed=typeof url==="string"?new URL(url):url
|
|
3
|
-
`)}export function sharedKeyStringToSign(account,request){const{headers}=request
|
|
1
|
+
import{Buffer}from"node:buffer";import{createHmac}from"node:crypto";export const SAS_VERSION="2020-12-06";export const REST_VERSION="2021-08-06";function hmacBase64(keyBase64,data){return createHmac("sha256",Buffer.from(keyBase64,"base64")).update(data,"utf8").digest("base64")}function header(headers,name){const wanted=name.toLowerCase();for(const[key,value]of Object.entries(headers)){if(key.toLowerCase()===wanted)return value??""}return""}export function canonicalizedHeaders(headers){const entries=Object.entries(headers).filter(([name,value])=>name.toLowerCase().startsWith("x-ms-")&&value!==undefined&&value!=="").map(([name,value])=>[name.toLowerCase(),String(value).replace(/\s+/g," ").trim()]).sort((a,b)=>a[0]<b[0]?-1:a[0]>b[0]?1:0);return entries.map(([name,value])=>`${name}:${value}
|
|
2
|
+
`).join("")}export function canonicalizedResource(account,url){const parsed=typeof url==="string"?new URL(url):url;const grouped=new Map;for(const[name,value]of parsed.searchParams){const key=name.toLowerCase();const existing=grouped.get(key);if(existing)existing.push(value);else grouped.set(key,[value])}const lines=[...grouped.entries()].sort((a,b)=>a[0]<b[0]?-1:a[0]>b[0]?1:0).map(([name,values])=>`${name}:${values.slice().sort().join(",")}`);return[`/${account}${parsed.pathname}`,...lines].join(`
|
|
3
|
+
`)}export function sharedKeyStringToSign(account,request){const{headers}=request;const contentLength=header(headers,"content-length");return[request.method.toUpperCase(),header(headers,"content-encoding"),header(headers,"content-language"),contentLength==="0"?"":contentLength,header(headers,"content-md5"),header(headers,"content-type"),header(headers,"date"),header(headers,"if-modified-since"),header(headers,"if-match"),header(headers,"if-none-match"),header(headers,"if-unmodified-since"),header(headers,"range")].join(`
|
|
4
4
|
`)+`
|
|
5
|
-
${canonicalizedHeaders(headers)}${canonicalizedResource(account,request.url)}`}export function sharedKeyAuthorization(credential,request){const signature=hmacBase64(credential.accountKey,sharedKeyStringToSign(credential.account,request));return`SharedKey ${credential.account}:${signature}`}const SAS_PERMISSION_ORDER="racwdxltmeop";export function orderSasPermissions(permissions){const wanted=new Set(permissions.toLowerCase());return[...SAS_PERMISSION_ORDER].filter((letter)=>wanted.has(letter)).join("")}export function sasTimestamp(date){return`${date.toISOString().slice(0,19)}Z`}export function serviceSasQuery(credential,options){const permissions=orderSasPermissions(options.permissions)
|
|
6
|
-
`)
|
|
5
|
+
${canonicalizedHeaders(headers)}${canonicalizedResource(account,request.url)}`}export function sharedKeyAuthorization(credential,request){const signature=hmacBase64(credential.accountKey,sharedKeyStringToSign(credential.account,request));return`SharedKey ${credential.account}:${signature}`}const SAS_PERMISSION_ORDER="racwdxltmeop";export function orderSasPermissions(permissions){const wanted=new Set(permissions.toLowerCase());return[...SAS_PERMISSION_ORDER].filter((letter)=>wanted.has(letter)).join("")}export function sasTimestamp(date){return`${date.toISOString().slice(0,19)}Z`}export function serviceSasQuery(credential,options){const permissions=orderSasPermissions(options.permissions);const start=options.startsAt?sasTimestamp(options.startsAt):"";const expiry=sasTimestamp(options.expiresAt);const protocol=options.protocol??"https";const resource=options.blob?"b":"c";const ip=options.ip??"";const path=options.blob?`/blob/${credential.account}/${options.container}/${options.blob}`:`/blob/${credential.account}/${options.container}`;const stringToSign=[permissions,start,expiry,path,"",ip,protocol,SAS_VERSION,resource,"","","",options.contentDisposition??"","","",options.contentType??""].join(`
|
|
6
|
+
`);const signature=hmacBase64(credential.accountKey,stringToSign);const query=new URLSearchParams;query.set("sv",SAS_VERSION);query.set("sr",resource);query.set("sp",permissions);if(start)query.set("st",start);query.set("se",expiry);query.set("spr",protocol);if(ip)query.set("sip",ip);if(options.contentDisposition)query.set("rscd",options.contentDisposition);if(options.contentType)query.set("rsct",options.contentType);query.set("sig",signature);return query.toString()}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{constants as bufferConstants}from"node:buffer";import{constants}from"node:fs";import{open}from"node:fs/promises";export class BoundedTextFileError extends Error{code;constructor(code,message,options){super(message,options);this.name="BoundedTextFileError";this.code=code}}export async function readBoundedTextFile(path,options){const{maxBytes}=options;if(!Number.isSafeInteger(maxBytes)||maxBytes<0||maxBytes>=bufferConstants.MAX_LENGTH)throw RangeError(`maxBytes must be an integer between 0 and ${bufferConstants.MAX_LENGTH-1}`);if(!constants.O_NOFOLLOW||!constants.O_NONBLOCK)throw new BoundedTextFileError("UNSUPPORTED_PLATFORM","Bounded text reads require O_NOFOLLOW and O_NONBLOCK support");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await file.stat();if(!stat.isFile())throw new BoundedTextFileError("NOT_REGULAR_FILE","Text input must be a regular file");if(stat.size>maxBytes)throw new BoundedTextFileError("FILE_TOO_LARGE",`Text file exceeds ${maxBytes} bytes`);const bytes=new Uint8Array(maxBytes+1);let length=0;while(length<bytes.length){const{bytesRead}=await file.read(bytes,length,bytes.length-length,null);if(bytesRead===0)break;length+=bytesRead}if(length>maxBytes)throw new BoundedTextFileError("FILE_TOO_LARGE",`Text file exceeds ${maxBytes} bytes`);try{return new TextDecoder("utf-8",{fatal
|
|
1
|
+
import{constants as bufferConstants}from"node:buffer";import{constants}from"node:fs";import{open}from"node:fs/promises";export class BoundedTextFileError extends Error{code;constructor(code,message,options){super(message,options);this.name="BoundedTextFileError";this.code=code}}export async function readBoundedTextFile(path,options){const{maxBytes}=options;if(!Number.isSafeInteger(maxBytes)||maxBytes<0||maxBytes>=bufferConstants.MAX_LENGTH)throw new RangeError(`maxBytes must be an integer between 0 and ${bufferConstants.MAX_LENGTH-1}`);if(!constants.O_NOFOLLOW||!constants.O_NONBLOCK)throw new BoundedTextFileError("UNSUPPORTED_PLATFORM","Bounded text reads require O_NOFOLLOW and O_NONBLOCK support");const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);try{const stat=await file.stat();if(!stat.isFile())throw new BoundedTextFileError("NOT_REGULAR_FILE","Text input must be a regular file");if(stat.size>maxBytes)throw new BoundedTextFileError("FILE_TOO_LARGE",`Text file exceeds ${maxBytes} bytes`);const bytes=new Uint8Array(maxBytes+1);let length=0;while(length<bytes.length){const{bytesRead}=await file.read(bytes,length,bytes.length-length,null);if(bytesRead===0)break;length+=bytesRead}if(length>maxBytes)throw new BoundedTextFileError("FILE_TOO_LARGE",`Text file exceeds ${maxBytes} bytes`);try{return new TextDecoder("utf-8",{fatal:true}).decode(bytes.subarray(0,length))}catch(cause){throw new BoundedTextFileError("INVALID_UTF8","Text file must contain valid UTF-8",{cause})}}finally{await file.close()}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{link,mkdir,open,unlink}from"node:fs/promises";import{dirname,join,resolve}from"node:path";import{Buffer}from"node:buffer";export{prepareCompletedArtifactDirectorySync}from"./prepared-completed-artifact-directory";export const completedArtifactLimits=Object.freeze({files:1024,bytes:
|
|
1
|
+
import{link,mkdir,open,unlink}from"node:fs/promises";import{dirname,join,resolve}from"node:path";import{Buffer}from"node:buffer";export{prepareCompletedArtifactDirectorySync}from"./prepared-completed-artifact-directory";export const completedArtifactLimits=Object.freeze({files:1024,bytes:128*1024*1024,manifestBytes:16*1024*1024,depth:4});export async function writeCompletedArtifact(directory,entries,manifestJson,options={}){if(typeof directory!=="string"||directory.length<1||directory.length>4096||directory.includes("\x00"))throw new TypeError("Invalid artifact directory");if(!Array.isArray(entries)||entries.length>completedArtifactLimits.files||typeof manifestJson!=="string"||manifestJson.length>completedArtifactLimits.manifestBytes)throw new RangeError("Artifact resource limit");const manifestSize=Buffer.byteLength(manifestJson,"utf8");if(manifestSize>completedArtifactLimits.manifestBytes)throw new RangeError("Completion manifest byte limit");let manifest;try{manifest=JSON.parse(manifestJson)}catch{throw new TypeError("Invalid completion manifest JSON")}if(!manifest||typeof manifest!=="object"||Array.isArray(manifest))throw new TypeError("Completion manifest must be a JSON object");let total=manifestSize;const paths=new Set(["manifest.json","manifest.pending.json"]);function validatePath(path){if(typeof path!=="string"||path.length>240||!/^[a-z0-9._/-]+$/i.test(path))throw new TypeError("Invalid artifact entry path");const parts=path.split("/");if(parts.length>completedArtifactLimits.depth||parts.some((part)=>!part||part==="."||part===".."||part.length>128))throw new TypeError("Unsafe artifact entry path")}const files=entries.map((entry)=>{if(!entry||typeof entry!=="object"||Object.keys(entry).length!==2||!Object.hasOwn(entry,"path")||!Object.hasOwn(entry,"contents"))throw new TypeError("Invalid artifact entry");validatePath(entry.path);const key=entry.path.toLowerCase();if(paths.has(key))throw new TypeError("Duplicate or reserved artifact path");paths.add(key);let size;if(typeof entry.contents==="string"){size=Buffer.byteLength(entry.contents,"utf8")}else if(entry.contents instanceof Uint8Array&&!(typeof SharedArrayBuffer!=="undefined"&&entry.contents.buffer instanceof SharedArrayBuffer))size=entry.contents.length;else throw new TypeError("Artifact contents must be text or unshared bytes");total+=size;if(total>completedArtifactLimits.bytes)throw new RangeError("Artifact byte limit");return{path:entry.path,contents:entry.contents}});if(!options||typeof options!=="object"||Object.keys(options).some((key)=>key!=="directories")||options.directories!==undefined&&(!Array.isArray(options.directories)||options.directories.length>completedArtifactLimits.files))throw new TypeError("Invalid artifact directory options");const directorySpellings=new Map;function registerDirectories(path,includeLeaf){const parts=path.split("/");for(let depth=1;depth<=parts.length-(includeLeaf?0:1);depth++){const parent=parts.slice(0,depth).join("/");const key=parent.toLowerCase();if(paths.has(key))throw new TypeError("Artifact directory and file collision");const spelling=directorySpellings.get(key);if(spelling!==undefined&&spelling!==parent)throw new TypeError("Artifact directory case alias collision");directorySpellings.set(key,parent)}}for(const path of options.directories??[]){validatePath(path);registerDirectories(path,true)}for(const file of files)registerDirectories(file.path,false);const manifestBytes=new TextEncoder().encode(manifestJson);const snapshot=files.map((file)=>({path:file.path,bytes:typeof file.contents==="string"?new TextEncoder().encode(file.contents):new Uint8Array(file.contents)}));const target=resolve(directory);const directories=[...directorySpellings.values()];async function writeSynced(path,data){const file=await open(path,"wx",384);try{await file.writeFile(data);await file.sync()}finally{await file.close()}}async function syncDirectory(path){const folder=await open(path,"r");try{await folder.sync()}finally{await folder.close()}}await mkdir(target,{mode:448});for(const path of[...directories].sort((a,b)=>a.split("/").length-b.split("/").length))await mkdir(join(target,path),{mode:448});for(const file of snapshot)await writeSynced(join(target,file.path),file.bytes);for(const path of[...directories].sort((a,b)=>b.split("/").length-a.split("/").length))await syncDirectory(join(target,path));await syncDirectory(target);await syncDirectory(dirname(target));const pending=join(target,"manifest.pending.json"),completed=join(target,"manifest.json");await writeSynced(pending,manifestBytes);await link(pending,completed);await syncDirectory(target);await unlink(pending);await syncDirectory(target);return{directory:target,manifest:completed}}
|
package/dist/copy.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{contains}from"@stacksjs/arrays";import{join}from"@stacksjs/path";import{fs}from"./fs";export function copy(src,dest,exclude=[]){if(Array.isArray(src))src.forEach((file)=>{copy(file,dest,exclude)})
|
|
1
|
+
import{contains}from"@stacksjs/arrays";import{join}from"@stacksjs/path";import{fs}from"./fs";export function copy(src,dest,exclude=[]){if(Array.isArray(src)){src.forEach((file)=>{copy(file,dest,exclude)})}else{if(fs.statSync(src).isDirectory())copyFolder(src,dest,exclude);else copyFile(src,dest)}}export function copyFile(src,dest){fs.copyFileSync(src,dest)}export function copyFolder(src,dest,exclude=[]){if(!fs.existsSync(dest))fs.mkdirSync(dest,{recursive:true});if(fs.existsSync(src)){fs.readdirSync(src).forEach((file)=>{if(!contains(join(src,file),exclude)){const srcPath=join(src,file);const destPath=join(dest,file);if(fs.statSync(srcPath).isDirectory())copyFolder(srcPath,destPath,exclude);else fs.copyFileSync(srcPath,destPath)}})}}
|
package/dist/delete.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{italic,log}from"@stacksjs/cli";import{err,handleError,ok}from"@stacksjs/error-handling";import{join}from"@stacksjs/path";import{isFolder}from"./folders";import{fs}from"./fs";import{glob}from"./glob";export function deleteFolder(path){return new Promise((resolve)=>{try{if(isFolder(path)){fs.rmSync(path,{recursive
|
|
1
|
+
import{italic,log}from"@stacksjs/cli";import{err,handleError,ok}from"@stacksjs/error-handling";import{join}from"@stacksjs/path";import{isFolder}from"./folders";import{fs}from"./fs";import{glob}from"./glob";export function deleteFolder(path){return new Promise((resolve)=>{try{if(isFolder(path)){fs.rmSync(path,{recursive:true,force:true});return resolve(ok(`Deleted ${path}`))}return resolve(ok(`Path ${path} was not a directory`))}catch(error){return resolve(err(error instanceof Error?error:new Error(String(error))))}})}export async function isDirectoryEmpty(path){return new Promise((resolve)=>{try{if(fs.statSync(path).isDirectory()){if(fs.readdirSync(path).length===0)return resolve(ok(true));return resolve(ok(false))}return resolve(ok(false))}catch(error){return resolve(err(error instanceof Error?error:new Error(String(error))))}})}export async function deleteEmptyFolder(path){return new Promise((resolve)=>{try{if(fs.statSync(path).isDirectory()){if(fs.readdirSync(path).length===0){fs.rmSync(path,{recursive:true,force:true});return resolve(ok(`Deleted ${path}`))}return resolve(ok(`Path ${path} was not empty`))}return resolve(ok(`Path ${path} was not a directory`))}catch(error){return resolve(err(error instanceof Error?error:new Error(String(error))))}})}export async function deleteEmptyFolders(dir){try{if(!fs.existsSync(dir))return ok(`Path ${dir} does not exist`);const files=fs.readdirSync(dir);for(const file of files){const p=join(dir,file);if(isFolder(p)){if(fs.readdirSync(p).length===0)fs.rmSync(p,{recursive:true,force:true});else await deleteEmptyFolders(p)}}return ok(`Deleted empty folders located in ${dir}`)}catch(error){return err(error)}}export function deleteFile(path){return new Promise((resolve)=>{try{if(fs.statSync(path).isFile()){fs.rmSync(path,{recursive:true,force:true});return resolve(ok(`Deleted ${path}`))}return resolve(ok(`Path ${path} was not a file`))}catch(error){return resolve(err(error instanceof Error?error:new Error(String(error))))}})}export async function deleteGlob(path){if(!path.includes("*"))return err(handleError(`Path ${path} does not contain a glob`));const matches=(await glob([path],{onlyFiles:false,dot:true})).sort((a,b)=>a.split("/").length-b.split("/").length||a.localeCompare(b));let deleted=0;for(const match of matches){if(!fs.existsSync(match))continue;try{fs.rmSync(match,{recursive:true,force:true})}catch(error){const failure=new Error(`Could not delete ${match}: ${error instanceof Error?error.message:String(error)}`,{cause:error});log.error(failure);return err(failure)}deleted++;log.info(`Deleted ${italic(match)}`)}return ok(`Deleted ${deleted} ${deleted===1?"entry":"entries"} matching ${path}`)}export async function del(path){if(fs.existsSync(path)&&fs.statSync(path).isFile())return await deleteFile(path);if(isFolder(path))return await deleteFolder(path);if(path.includes("*"))return await deleteGlob(path);return err(handleError(`Path ${path} cannot be deleted due to an unhandled condition. Please report this issue.`))}
|
package/dist/directory-page.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stat}from"node:fs/promises";import{join}from"node:path";import{Buffer}from"node:buffer";export class DirectoryListingChangedError extends Error{constructor(){super("The directory changed during inventory. Restart this directory with a fresh cursor.");this.name="DirectoryListingChangedError"}}export function directoryPageSize(options){const size=options.limit??100;if(!Number.isInteger(size)||size<1||size>1000)throw TypeError("A directory page limit must be an integer from 1 to 1000");return size}export async function localDirectoryPage(fullPath,path,options={}){const limit=directoryPageSize(options);if(process.platform!=="darwin"&&process.platform!=="linux")throw Error("Durable local directory pages require a POSIX host");let before;try{before=await stat(fullPath,{bigint
|
|
1
|
+
import{stat}from"node:fs/promises";import{join}from"node:path";import{Buffer}from"node:buffer";export class DirectoryListingChangedError extends Error{constructor(){super("The directory changed during inventory. Restart this directory with a fresh cursor.");this.name="DirectoryListingChangedError"}}export function directoryPageSize(options){const size=options.limit??100;if(!Number.isInteger(size)||size<1||size>1000)throw new TypeError("A directory page limit must be an integer from 1 to 1000");return size}export async function localDirectoryPage(fullPath,path,options={}){const limit=directoryPageSize(options);if(process.platform!=="darwin"&&process.platform!=="linux")throw new Error("Durable local directory pages require a POSIX host");let before;try{before=await stat(fullPath,{bigint:true})}catch(error){if(error.code==="ENOENT"&&!options.cursor)return{entries:[],nextCursor:null};if(error.code==="ENOENT")throw new DirectoryListingChangedError;throw error}if(!before.isDirectory())throw new Error("Directory pages require a directory");const identity=[fullPath,before.dev,before.ino,before.mtimeNs,before.ctimeNs].join(":");let block=0n;let skip=0;if(options.cursor){let decoded;try{if(options.cursor.length>8192)throw new TypeError("Invalid directory cursor");decoded=JSON.parse(Buffer.from(options.cursor,"base64url").toString())}catch{throw new TypeError("Invalid directory cursor")}if(decoded?.v!==1||typeof decoded.block!=="string"||!/^\d{1,19}$/.test(decoded.block)||BigInt(decoded.block)>9223372036854775807n||!Number.isInteger(decoded.skip)||decoded.skip<0||decoded.skip>32768)throw new TypeError("Invalid directory cursor");if(decoded.identity!==identity)throw new DirectoryListingChangedError;block=BigInt(decoded.block);skip=decoded.skip}const{dlopen,FFIType,toArrayBuffer}=await import("bun:ffi");const darwin=process.platform==="darwin";const errnoName=darwin?"__error":"__errno_location";const readName=darwin?"__getdirentries64":"getdents64";const libc=dlopen(darwin?"/usr/lib/libSystem.B.dylib":"libc.so.6",{open:{args:[FFIType.cstring,FFIType.i32],returns:FFIType.i32},lseek:{args:[FFIType.i32,FFIType.i64,FFIType.i32],returns:FFIType.i64},[readName]:{args:darwin?[FFIType.i32,FFIType.ptr,FFIType.u64,FFIType.ptr]:[FFIType.i32,FFIType.ptr,FFIType.u64],returns:FFIType.i64},close:{args:[FFIType.i32],returns:FFIType.i32},[errnoName]:{args:[],returns:FFIType.ptr}});const api=libc.symbols;let descriptor=-1;try{const errno=new Int32Array(toArrayBuffer(api[errnoName](),0,4));descriptor=api.open(Buffer.from(`${fullPath}\x00`),0);if(descriptor<0)throw new Error(`Cannot open directory for inventory (errno ${errno[0]})`);if(BigInt(api.lseek(descriptor,block,0))<0n)throw new Error(`Cannot resume directory inventory (errno ${errno[0]})`);const entries=[];const buffer=new Uint8Array(32768);const view=new DataView(buffer.buffer);const base=new BigInt64Array(1);let ended=false;let scanned=0;while(scanned<limit){const size=Number(darwin?api[readName](descriptor,buffer,buffer.length,base):api[readName](descriptor,buffer,buffer.length));if(size<0)throw new Error(`Cannot read directory for inventory (errno ${errno[0]})`);if(skip>size||!size&&skip)throw new TypeError("Invalid directory cursor boundary");if(!size){ended=true;break}let offset=0;while(offset<size&&scanned<limit){const length=view.getUint16(offset+16,true);const nameOffset=darwin?21:19;if(length<=nameOffset||offset+length>size)throw new Error("Invalid native directory entry");const next=offset+length;if(offset<skip){if(next>skip)throw new TypeError("Invalid directory cursor boundary");offset=next;continue}scanned++;const nameBytes=buffer.subarray(offset+nameOffset,next);const end=nameBytes.indexOf(0);if(end<0)throw new Error("Invalid native directory name");const name=Buffer.from(nameBytes.subarray(0,end)).toString();const kind=buffer[offset+(darwin?20:18)];offset=next;if(name==="."||name==="..")continue;if(kind===4||kind===8)entries.push({path:join(path,name),type:kind===4?"directory":"file"});else if(kind===0){const{lstat}=await import("node:fs/promises");const info=await lstat(join(fullPath,name));if(info.isFile()||info.isDirectory())entries.push({path:join(path,name),type:info.isDirectory()?"directory":"file"})}}skip=offset;if(offset===size){block=BigInt(api.lseek(descriptor,0n,1));if(block<0n)throw new Error(`Cannot checkpoint directory inventory (errno ${errno[0]})`);skip=0}}const after=await stat(fullPath,{bigint:true});if([fullPath,after.dev,after.ino,after.mtimeNs,after.ctimeNs].join(":")!==identity)throw new DirectoryListingChangedError;return{entries,nextCursor:ended?null:Buffer.from(JSON.stringify({v:1,identity,block:String(block),skip})).toString("base64url")}}finally{if(descriptor>=0)api.close(descriptor);libc.close()}}
|
package/dist/drivers/aws.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createS3Storage}from"../adapters/s3";let _adapterPromise=null;async function loadConfig(){try{const{filesystems}=await import("@stacksjs/config")
|
|
1
|
+
import{createS3Storage}from"../adapters/s3";let _adapterPromise=null;async function loadConfig(){try{const{filesystems}=await import("@stacksjs/config");const s3Config=filesystems.s3;return createS3Storage(null,{bucket:s3Config?.bucket||"stacks",prefix:s3Config?.prefix||"stx",region:s3Config?.region||"us-east-1",endpoint:s3Config?.endpoint,usePathStyleEndpoint:s3Config?.usePathStyleEndpoint,credentials:s3Config?.credentials})}catch{const{env}=await import("@stacksjs/env");return createS3Storage(null,{bucket:env.AWS_S3_BUCKET||"stacks",prefix:env.AWS_S3_PREFIX||"stx",region:env.AWS_REGION||"us-east-1",endpoint:env.AWS_ENDPOINT?String(env.AWS_ENDPOINT):undefined,usePathStyleEndpoint:env.AWS_USE_PATH_STYLE_ENDPOINT===true,credentials:env.AWS_ACCESS_KEY_ID&&env.AWS_SECRET_ACCESS_KEY?{accessKeyId:env.AWS_ACCESS_KEY_ID,secretAccessKey:env.AWS_SECRET_ACCESS_KEY}:undefined})}}async function getAdapter(){if(!_adapterPromise){_adapterPromise=loadConfig()}return _adapterPromise}export async function getAwsStorage(){return getAdapter()}export const aws={async write(path,contents){const adapter=await getAdapter();await adapter.write(path,contents)},async deleteFile(path){const adapter=await getAdapter();await adapter.deleteFile(path)},async createDirectory(path){const adapter=await getAdapter();await adapter.createDirectory(path)},async moveFile(from,to){const adapter=await getAdapter();await adapter.moveFile(from,to)},async copyFile(from,to){const adapter=await getAdapter();await adapter.copyFile(from,to)},async stat(path){const adapter=await getAdapter();return await adapter.stat(path)},list(path,options={deep:false}){return async function*(){const adapter=await getAdapter();yield*adapter.list(path,options)}()},async changeVisibility(path,visibility){const adapter=await getAdapter();await adapter.changeVisibility(path,visibility)},async visibility(path){const adapter=await getAdapter();return await adapter.visibility(path)},async fileExists(path){const adapter=await getAdapter();return await adapter.fileExists(path)},async directoryExists(path){const adapter=await getAdapter();return await adapter.directoryExists(path)},async publicUrl(path,options){const adapter=await getAdapter();return await adapter.publicUrl(path,options)},async temporaryUrl(path,options){const adapter=await getAdapter();return await adapter.temporaryUrl(path,options)},async checksum(path,options){const adapter=await getAdapter();return await adapter.checksum(path,options)},async mimeType(path,options){const adapter=await getAdapter();return await adapter.mimeType(path,options)},async lastModified(path){const adapter=await getAdapter();return await adapter.lastModified(path)},async fileSize(path){const adapter=await getAdapter();return await adapter.fileSize(path)},async read(path){const adapter=await getAdapter();return await adapter.read(path)},async readToString(path){const adapter=await getAdapter();return await adapter.readToString(path)},async readToBuffer(path){const adapter=await getAdapter();return await adapter.readToBuffer(path)},async readToUint8Array(path){const adapter=await getAdapter();return await adapter.readToUint8Array(path)}};
|
package/dist/drivers/bun.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolve}from"node:path";import process from"node:process";import{createBunStorage}from"../adapters/bun";let _adapterPromise=null;async function loadConfig(){try{const{filesystems}=await import("@stacksjs/config")
|
|
1
|
+
import{resolve}from"node:path";import process from"node:process";import{createBunStorage}from"../adapters/bun";let _adapterPromise=null;async function loadConfig(){try{const{filesystems}=await import("@stacksjs/config");const rootDirectory=resolve(filesystems.root||process.cwd());return createBunStorage({root:rootDirectory})}catch{const rootDirectory=resolve(process.cwd());return createBunStorage({root:rootDirectory})}}async function getAdapter(){if(!_adapterPromise){_adapterPromise=loadConfig()}return _adapterPromise}export async function getBunStorage(){return getAdapter()}export const bun={async write(path,contents){const adapter=await getAdapter();await adapter.write(path,contents)},async deleteFile(path){const adapter=await getAdapter();await adapter.deleteFile(path)},async createDirectory(path){const adapter=await getAdapter();await adapter.createDirectory(path)},async moveFile(from,to){const adapter=await getAdapter();await adapter.moveFile(from,to)},async copyFile(from,to){const adapter=await getAdapter();await adapter.copyFile(from,to)},async stat(path){const adapter=await getAdapter();return await adapter.stat(path)},list(path,options={deep:false}){return async function*(){const adapter=await getAdapter();yield*adapter.list(path,options)}()},async changeVisibility(path,visibility){const adapter=await getAdapter();await adapter.changeVisibility(path,visibility)},async visibility(path){const adapter=await getAdapter();return await adapter.visibility(path)},async fileExists(path){const adapter=await getAdapter();return await adapter.fileExists(path)},async directoryExists(path){const adapter=await getAdapter();return await adapter.directoryExists(path)},async publicUrl(path,options){const adapter=await getAdapter();return await adapter.publicUrl(path,options)},async temporaryUrl(path,options){const adapter=await getAdapter();return await adapter.temporaryUrl(path,options)},async checksum(path,options){const adapter=await getAdapter();return await adapter.checksum(path,options)},async mimeType(path,options){const adapter=await getAdapter();return await adapter.mimeType(path,options)},async lastModified(path){const adapter=await getAdapter();return await adapter.lastModified(path)},async fileSize(path){const adapter=await getAdapter();return await adapter.fileSize(path)},async read(path){const adapter=await getAdapter();return await adapter.read(path)},async readToString(path){const adapter=await getAdapter();return await adapter.readToString(path)},async readToBuffer(path){const adapter=await getAdapter();return await adapter.readToBuffer(path)},async readToUint8Array(path){const adapter=await getAdapter();return await adapter.readToUint8Array(path)}};
|
package/dist/drivers/local.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolve}from"node:path";import process from"node:process";import{createLocalStorage}from"../adapters/local";let _adapterPromise=null;async function loadConfig(){try{const{filesystems}=await import("@stacksjs/config")
|
|
1
|
+
import{resolve}from"node:path";import process from"node:process";import{createLocalStorage}from"../adapters/local";let _adapterPromise=null;async function loadConfig(){try{const{filesystems}=await import("@stacksjs/config");const rootDirectory=resolve(filesystems.root||process.cwd());return createLocalStorage({root:rootDirectory})}catch{const rootDirectory=resolve(process.cwd());return createLocalStorage({root:rootDirectory})}}async function getAdapter(){if(!_adapterPromise){_adapterPromise=loadConfig()}return _adapterPromise}export async function getLocalStorage(){return getAdapter()}export const local={async write(path,contents){const adapter=await getAdapter();await adapter.write(path,contents)},async deleteFile(path){const adapter=await getAdapter();await adapter.deleteFile(path)},async createDirectory(path){const adapter=await getAdapter();await adapter.createDirectory(path)},async moveFile(from,to){const adapter=await getAdapter();await adapter.moveFile(from,to)},async copyFile(from,to){const adapter=await getAdapter();await adapter.copyFile(from,to)},async stat(path){const adapter=await getAdapter();return await adapter.stat(path)},list(path,options={deep:false}){return async function*(){const adapter=await getAdapter();yield*adapter.list(path,options)}()},async changeVisibility(path,visibility){const adapter=await getAdapter();await adapter.changeVisibility(path,visibility)},async visibility(path){const adapter=await getAdapter();return await adapter.visibility(path)},async fileExists(path){const adapter=await getAdapter();return await adapter.fileExists(path)},async directoryExists(path){const adapter=await getAdapter();return await adapter.directoryExists(path)},async publicUrl(path,options){const adapter=await getAdapter();return await adapter.publicUrl(path,options)},async temporaryUrl(path,options){const adapter=await getAdapter();return await adapter.temporaryUrl(path,options)},async checksum(path,options){const adapter=await getAdapter();return await adapter.checksum(path,options)},async mimeType(path,options){const adapter=await getAdapter();return await adapter.mimeType(path,options)},async lastModified(path){const adapter=await getAdapter();return await adapter.lastModified(path)},async fileSize(path){const adapter=await getAdapter();return await adapter.fileSize(path)},async read(path){const adapter=await getAdapter();return await adapter.read(path)},async readToString(path){const adapter=await getAdapter();return await adapter.readToString(path)},async readToBuffer(path){const adapter=await getAdapter();return await adapter.readToBuffer(path)},async readToUint8Array(path){const adapter=await getAdapter();return await adapter.readToUint8Array(path)}};
|
package/dist/drivers/memory.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createMemoryStorage}from"../adapters/memory";const adapter=createMemoryStorage();export const memoryStorage=adapter
|
|
1
|
+
import{createMemoryStorage}from"../adapters/memory";const adapter=createMemoryStorage();export const memoryStorage=adapter;export const memory={async write(path,contents){await adapter.write(path,contents)},async deleteFile(path){await adapter.deleteFile(path)},async createDirectory(path){await adapter.createDirectory(path)},async moveFile(from,to){await adapter.moveFile(from,to)},async copyFile(from,to){await adapter.copyFile(from,to)},async stat(path){return await adapter.stat(path)},list(path,options={deep:false}){return adapter.list(path,options)},async changeVisibility(path,visibility){await adapter.changeVisibility(path,visibility)},async visibility(path){return await adapter.visibility(path)},async fileExists(path){return await adapter.fileExists(path)},async directoryExists(path){return await adapter.directoryExists(path)},async publicUrl(path,options){return await adapter.publicUrl(path,options)},async temporaryUrl(path,options){return await adapter.temporaryUrl(path,options)},async checksum(path,options){return await adapter.checksum(path,options)},async mimeType(path,options){return await adapter.mimeType(path,options)},async lastModified(path){return await adapter.lastModified(path)},async fileSize(path){return await adapter.fileSize(path)},async read(path){return await adapter.read(path)},async readToString(path){return await adapter.readToString(path)},async readToBuffer(path){return await adapter.readToBuffer(path)},async readToUint8Array(path){return await adapter.readToUint8Array(path)}};
|
package/dist/facade.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{posix,resolve}from"node:path";import process from"node:process";import{filesystems,app as appConfig}from"@stacksjs/config";import{AzureBlobStorageAdapter}from"./adapters/azure";import{createLocalStorage}from"./adapters/local";import{S3StorageAdapter}from"./adapters/s3";import{parseDiskPath}from"./path-sanitize";import{putUploadedFile}from"./put-file";function buildConfig(){const cwd=process.cwd()
|
|
1
|
+
import{posix,resolve}from"node:path";import process from"node:process";import{filesystems,app as appConfig}from"@stacksjs/config";import{AzureBlobStorageAdapter}from"./adapters/azure";import{createLocalStorage}from"./adapters/local";import{S3StorageAdapter}from"./adapters/s3";import{parseDiskPath}from"./path-sanitize";import{putUploadedFile}from"./put-file";function buildConfig(){const cwd=process.cwd();const rootDir=filesystems.root||cwd;const s3Config=filesystems.s3;const appUrl=(appConfig?.url||"").replace(/\/$/,"");const config={default:filesystems.driver||"local",disks:{local:{driver:"local",root:resolve(rootDir,"storage/app"),visibility:filesystems.defaultVisibility||"private"},public:{driver:"local",root:resolve(rootDir,"public"),url:appUrl||"/",visibility:"public"}}};if(s3Config?.bucket){config.disks.s3={driver:"s3",bucket:s3Config.bucket,region:s3Config.region||"us-east-1",prefix:s3Config.prefix,endpoint:s3Config.endpoint,url:filesystems.publicUrl?.domain,usePathStyleEndpoint:s3Config.usePathStyleEndpoint??!!s3Config.endpoint,visibility:filesystems.defaultVisibility||"private",credentials:s3Config.credentials?{key:s3Config.credentials.accessKeyId,secret:s3Config.credentials.secretAccessKey}:undefined}}return config}function sameStoragePath(a,b){return posix.normalize(a.replace(/\\/g,"/"))===posix.normalize(b.replace(/\\/g,"/"))}class StorageManager{_config=null;disks=new Map;customConfig=null;get config(){if(!this._config){const builtConfig=buildConfig();this._config=this.customConfig?{default:this.customConfig.default||builtConfig.default,disks:{...builtConfig.disks,...this.customConfig.disks}}:builtConfig}return this._config}init(config){this.customConfig=config;this._config=null;this.disks.clear();return this}disk(name){const diskName=name||this.config.default;if(this.disks.has(diskName)){return this.disks.get(diskName)}const diskConfig=this.config.disks[diskName];if(!diskConfig){const available=Object.keys(this.config.disks).join(", ");const hint=diskName==="s3"?" Set `filesystems.s3.bucket` in config/filesystems.ts - the s3 disk is only built once a bucket is configured.":name===undefined?" This is the DEFAULT disk, from `filesystems.driver`; it has to name one of the disks above.":"";throw new Error(`Disk [${diskName}] is not configured. Available: ${available}.${hint}`)}const adapter=this.createAdapter(diskName,diskConfig);this.disks.set(diskName,adapter);return adapter}createAdapter(name,config){switch(config.driver){case"local":return this.createLocalAdapter(name,config);case"s3":return this.createS3Adapter(name,config);case"azure":return this.createAzureAdapter(config);default:throw new Error(`Unsupported driver: ${config.driver}`)}}createLocalAdapter(name,config){return createLocalStorage({root:config.root,url:config.url,disk:name})}createS3Adapter(_name,config){return new S3StorageAdapter(null,{bucket:config.bucket,region:config.region,prefix:config.prefix,endpoint:config.endpoint,usePathStyleEndpoint:config.usePathStyleEndpoint,url:config.url,credentials:config.credentials?{accessKeyId:config.credentials.key,secretAccessKey:config.credentials.secret}:undefined})}createAzureAdapter(config){return new AzureBlobStorageAdapter({account:config.account,accountKey:config.accountKey,sasToken:config.sasToken,container:config.container,prefix:config.prefix,url:config.url,endpoint:config.endpoint})}async put(pathOrFile,contentsOrOpts){if(typeof pathOrFile==="string"){return this.disk().write(pathOrFile,contentsOrOpts)}const opts=contentsOrOpts??{};return putUploadedFile(this,pathOrFile,opts)}async stat(path){return this.disk().stat(path)}async getStream(path,options){const adapter=this.disk();if(typeof adapter.getStream!=="function"){throw new Error(`[storage] disk '${this.config.default}' does not support getStream - adapter is missing the optional method`)}return adapter.getStream(path,options)}async putStream(path,stream,options){const adapter=this.disk();if(typeof adapter.putStream!=="function"){throw new Error(`[storage] disk '${this.config.default}' does not support putStream - adapter is missing the optional method`)}return adapter.putStream(path,stream,options)}async copyAcross(source,dest){const src=parseDiskPath(source);const dst=parseDiskPath(dest);if(src.disk===dst.disk){const adapter=this.disk(src.disk);if(!sameStoragePath(src.path,dst.path))await adapter.copyFile(src.path,dst.path);return adapter.stat(dst.path).then((entry)=>({path:dst.path,size:entry.size,contentType:entry.mimeType,lastModified:entry.lastModified}))}const contents=await this.disk(src.disk).read(src.path);return this.disk(dst.disk).write(dst.path,contents)}async moveAcross(source,dest){const src=parseDiskPath(source);const dst=parseDiskPath(dest);if(src.disk===dst.disk){const adapter=this.disk(src.disk);if(!sameStoragePath(src.path,dst.path))await adapter.moveFile(src.path,dst.path);const entry=await adapter.stat(dst.path);return{path:dst.path,size:entry.size,contentType:entry.mimeType,lastModified:entry.lastModified}}const result=await this.copyAcross(source,dest);await this.disk(src.disk).deleteFile(src.path);return result}async get(path){return this.disk().readToString(path)}async exists(path){return this.disk().fileExists(path)}async missing(path){return!await this.exists(path)}async delete(path){return this.disk().deleteFile(path)}async copy(from,to){return this.disk().copyFile(from,to)}async move(from,to){return this.disk().moveFile(from,to)}async url(path){return this.disk().publicUrl(path)}async signedUrl(path,options){const adapter=this.disk();if(typeof adapter.signedUrl!=="function"){throw new Error(`[storage] disk '${this.config.default}' does not support signedUrl`)}return adapter.signedUrl(path,options)}async presignedUploadUrl(options){const adapter=this.disk();if(typeof adapter.presignedUploadUrl!=="function"){throw new Error(`[storage] disk '${this.config.default}' does not support presignedUploadUrl - only S3-style adapters do. Use \`Storage.put(file, opts)\` for local/proxied uploads.`)}return adapter.presignedUploadUrl(options)}async presignedUploadPolicy(options){const adapter=this.disk();if(typeof adapter.presignedUploadPolicy!=="function"){throw new Error(`[storage] disk '${this.config.default}' does not support presignedUploadPolicy - S3-only. Use \`presignedUploadUrl\` for the PUT-form, or \`Storage.put(file, opts)\` for server-proxied uploads.`)}return adapter.presignedUploadPolicy(options)}async size(path){return this.disk().fileSize(path)}async lastModified(path){return this.disk().lastModified(path)}async mimeType(path){return this.disk().mimeType(path)}async checksum(path,algorithm){return this.disk().checksum(path,{algorithm})}async makeDirectory(path){return this.disk().createDirectory(path)}async deleteDirectory(path){return this.disk().deleteDirectory(path)}files(path=""){return this.disk().list(path)}allFiles(path=""){return this.disk().list(path,{deep:true})}configure(name,config){const currentConfig=this.config;currentConfig.disks[name]=config;this.disks.delete(name);return this}setDefaultDisk(name){if(!this.config.disks[name]){throw new Error(`Disk [${name}] is not configured`)}this.config.default=name;return this}getDiskConfig(name){return this.config.disks[name||this.config.default]}getConfiguredDisks(){return Object.keys(this.config.disks)}getDefaultDisk(){return this.config.default}reset(){this._config=null;this.customConfig=null;this.disks.clear();return this}}export const Storage=new StorageManager;export{StorageManager};
|
package/dist/file-info.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{extname}from"node:path";import{detectMimeFromMagicBytes}from"./mime-verify";const EXTENSION_MIME={".txt":"text/plain",".md":"text/markdown",".csv":"text/csv",".json":"application/json",".xml":"application/xml",".svg":"image/svg+xml",".html":"text/html",".css":"text/css",".js":"text/javascript",".ts":"text/typescript",".yaml":"application/yaml",".yml":"application/yaml"}
|
|
1
|
+
import{extname}from"node:path";import{detectMimeFromMagicBytes}from"./mime-verify";const EXTENSION_MIME={".txt":"text/plain",".md":"text/markdown",".csv":"text/csv",".json":"application/json",".xml":"application/xml",".svg":"image/svg+xml",".html":"text/html",".css":"text/css",".js":"text/javascript",".ts":"text/typescript",".yaml":"application/yaml",".yml":"application/yaml"};const KIND_BY_TYPE=[[/^image\//,"image"],[/^video\//,"video"],[/^audio\//,"audio"],[/^font\/|^application\/(?:x-)?font/,"font"],[/^application\/pdf$/,"pdf"],[/^application\/(?:zip|x-tar|gzip|x-7z|x-rar|x-bzip)/,"archive"],[/^text\/|^application\/(?:json|xml|yaml|javascript|typescript)/,"text"]];export function fileKind(mime){for(const[pattern,kind]of KIND_BY_TYPE){if(pattern.test(mime))return kind}return"other"}export function isPreviewable(mime){if(mime==="image/svg+xml")return false;return fileKind(mime)==="image"||fileKind(mime)==="text"}export function resolveMime(bytes,name){const sniffed=detectMimeFromMagicBytes(bytes);if(sniffed)return{mime:sniffed,source:"magic-bytes"};if(name){const byExtension=EXTENSION_MIME[extname(name).toLowerCase()];if(byExtension)return{mime:byExtension,source:"extension"}}return{mime:"application/octet-stream",source:"fallback"}}export async function fileInfoFromBytes(bytes,name){const{mime,source}=resolveMime(bytes,name);const kind=fileKind(mime);const info={mime,mimeSource:source,size:bytes.byteLength,kind,previewable:isPreviewable(mime)};if(kind==="image"&&mime!=="image/svg+xml"){try{const{getMetadata}=await import("ts-images");info.image=await getMetadata(bytes)}catch{}}return info}export async function fileInfo(path){const file=Bun.file(path);const bytes=new Uint8Array(await file.arrayBuffer());return fileInfoFromBytes(bytes,path)}
|
package/dist/files.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{contains}from"@stacksjs/arrays";import{log}from"@stacksjs/logging";import{path as p}from"@stacksjs/path";import{dirname,join,resolve,relative,isAbsolute,parse,sep}from"node:path";import{tmpdir}from"node:os";import process from"node:process";import{detectIndent,detectNewline}from"@stacksjs/strings";import{createFolder,isFolder}from"./folders";import{existsSync,fs}from"./fs";export async function readJsonFile(name,cwd){const file=await readTextFile(name,cwd);let data;try{data=JSON.parse(file.data)}catch(error){throw Error(`Failed to parse JSON file "${name}": ${error.message}`)}const indent=detectIndent(file.data).indent
|
|
1
|
+
import{contains}from"@stacksjs/arrays";import{log}from"@stacksjs/logging";import{path as p}from"@stacksjs/path";import{dirname,join,resolve,relative,isAbsolute,parse,sep}from"node:path";import{tmpdir}from"node:os";import process from"node:process";import{detectIndent,detectNewline}from"@stacksjs/strings";import{createFolder,isFolder}from"./folders";import{existsSync,fs}from"./fs";export async function readJsonFile(name,cwd){const file=await readTextFile(name,cwd);let data;try{data=JSON.parse(file.data)}catch(error){throw new Error(`Failed to parse JSON file "${name}": ${error.message}`)}const indent=detectIndent(file.data).indent;const newline=detectNewline(file.data);return{...file,data,indent,newline}}export async function readPackageJson(name,cwd){const file=await readJsonFile(name,cwd);return file.data}export async function writeFile(path,data){if(typeof path==="string"){const dirPath=dirname(path);if(!await existsSync(dirPath))await createFolder(dirPath);return await Bun.write(Bun.file(path),data)}return await Bun.write(path,data)}export async function writeJsonFile(file){let json=JSON.stringify(file.data,undefined,file.indent);if(file.newline)json+=file.newline;return writeTextFile({...file,data:json})}export function readTextFile(name,cwd){return new Promise((resolve,reject)=>{let filePath;if(cwd)filePath=join(cwd,name);else filePath=name;fs.readFile(filePath,"utf8",(err,text)=>{if(err){reject(err)}else{resolve({path:filePath,data:text})}})})}export async function writeTextFile(file){return await Bun.write(file.path,file.data)}function isFile(path){return fs.existsSync(path)}export function doesExist(path){return isFile(path)||isFolder(path)}export function doesNotExist(path){return!isFile(path)&&!isFolder(path)}export function hasFiles(folder){try{return fs.readdirSync(folder).length>0}catch(err){log.debug(`Error reading folder: ${folder}`,err);return false}}export function hasComponents(){return hasFiles(p.componentsPath())}export function hasFunctions(){return hasFiles(p.functionsPath())}function traversalRoot(directory){const root=resolve(directory);const anchors=[process.cwd(),tmpdir(),...process.platform==="win32"?[]:["/tmp"]];const candidates=anchors.flatMap((anchor)=>{try{return[resolve(anchor),fs.realpathSync(anchor)]}catch{return[resolve(anchor)]}});const contained=(anchor)=>{const part=relative(anchor,root);return part===""||!isAbsolute(part)&&part!==".."&&!part.startsWith(`..${sep}`)};const anchor=candidates.filter(contained).sort((a,b)=>b.length-a.length)[0]??parse(root).root;let current=anchor;for(const part of root===anchor?[]:relative(anchor,dirname(root)).split(sep).filter(Boolean)){current=join(current,part);if(fs.lstatSync(current).isSymbolicLink())throw new Error(`Cannot traverse a symlink ancestor: ${current}`)}return root}export function deleteFiles(dir,exclude=[]){if(contains(dir,exclude))return;let root;try{root=traversalRoot(dir)}catch(error){if(error.code==="ENOENT")return;throw error}const walk=(path,display)=>{if(contains(display,exclude))return;let stat;try{stat=fs.lstatSync(path)}catch(error){if(error.code==="ENOENT")return;throw error}if(!stat.isDirectory()){fs.unlinkSync(path);return}for(const name of fs.readdirSync(path)){const entry=join(path,name),shown=join(display,name);if(contains(shown,exclude))continue;const child=fs.lstatSync(entry);if(child.isDirectory()&&fs.readdirSync(entry).length===0)fs.rmdirSync(entry);else walk(entry,shown)}};walk(root,dir)}export function getFiles(dir,exclude=[]){const root=traversalRoot(dir);if(fs.lstatSync(root).isSymbolicLink()||contains(dir,exclude))return[];const results=[];const walk=(path,display)=>{for(const name of fs.readdirSync(path)){const file=join(path,name),shown=join(display,name);if(contains(shown,exclude))continue;const stat=fs.lstatSync(file);if(stat.isSymbolicLink())continue;if(stat.isDirectory())walk(file,shown);else if(stat.isFile())results.push(shown)}};walk(root,dir);return results}export function put(path,contents){const dirPath=dirname(path);if(!fs.existsSync(dirPath))fs.mkdirSync(dirPath,{recursive:true});fs.writeFileSync(path,contents,"utf-8")}export async function get(path){return Bun.file(path).text()}export const files={readJsonFile,readPackageJson,readTextFile,writeJsonFile,writeTextFile,hasFiles,hasComponents,hasFunctions,deleteFiles,getFiles,put,get};
|
|
@@ -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)
|
|
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}`}
|
package/dist/folders.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join}from"@stacksjs/path";import{fs}from"./fs";export function isFolder(path){try{return fs.statSync(path).isDirectory()}catch{return
|
|
1
|
+
import{join}from"@stacksjs/path";import{fs}from"./fs";export function isFolder(path){try{return fs.statSync(path).isDirectory()}catch{return false}}export function isDir(path){return isFolder(path)}export function doesFolderExist(path){return fs.existsSync(path)}export function createFolder(dir){return new Promise((resolve,reject)=>{try{fs.mkdirSync(dir,{recursive:true});resolve()}catch(err){reject(err)}})}export function getFolders(dir){return fs.readdirSync(dir).filter((file)=>{return fs.statSync(join(dir,file)).isDirectory()})}export const folders={isFolder,doesFolderExist,createFolder,getFolders};
|
package/dist/glob.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Glob as BunGlob}from"bun";import{statSync}from"node:fs";import{isAbsolute,join,relative,sep}from"node:path";import process from"node:process";function isEnoent(err){return!!err&&typeof err==="object"&&err.code==="ENOENT"}const globCharacters=/[*?[\]{}!]/;function baseOf(pattern){const segments=pattern.split("/")
|
|
1
|
+
import{Glob as BunGlob}from"bun";import{statSync}from"node:fs";import{isAbsolute,join,relative,sep}from"node:path";import process from"node:process";function isEnoent(err){return!!err&&typeof err==="object"&&err.code==="ENOENT"}const globCharacters=/[*?[\]{}!]/;function baseOf(pattern){const segments=pattern.split("/");const literal=[];for(const segment of segments.slice(0,-1)){if(globCharacters.test(segment))break;literal.push(segment)}return literal.join("/")||(pattern.startsWith("/")?"/":"")}function isDirectory(path){try{return statSync(path).isDirectory()}catch{return false}}function plan(pattern,options={}){const cwd=options.cwd??process.cwd();let effective=pattern;if(options.expandDirectories&&!globCharacters.test(pattern)&&isDirectory(isAbsolute(pattern)?pattern:join(cwd,pattern)))effective=`${pattern.replace(/\/+$/,"")}/**`;const onlyDirectories=options.onlyDirectories===true;const onlyFiles=!onlyDirectories&&options.onlyFiles!==false;const ignore=(options.ignore??[]).map((ignored)=>new BunGlob(ignored));const base=baseOf(effective);const baseDirectory=isAbsolute(base)?base:join(cwd,base);const keep=(match)=>{const onDisk=isAbsolute(match)?match:join(cwd,match);const fromCwd=relative(cwd,onDisk).split(sep).join("/");if(ignore.some((ignored)=>ignored.match(match)||ignored.match(fromCwd)))return false;if(options.deep!==undefined){const below=relative(baseDirectory,onDisk).split(sep).filter(Boolean).length-1;if(below>options.deep)return false}if(onlyDirectories&&!isDirectory(onDisk))return false;return true};return{pattern:effective,scan:{cwd:options.cwd,absolute:options.absolute,dot:options.dot,onlyFiles},keep}}export function globSync(patterns,options){const patternArray=typeof patterns==="string"?[patterns]:patterns;const results=new Set;for(const pattern of patternArray){const{pattern:effective,scan,keep}=plan(pattern,options);try{for(const match of new BunGlob(effective).scanSync(scan)){if(keep(match))results.add(match)}}catch(err){if(!isEnoent(err))throw err}}return[...results]}export async function glob(patterns,options){const patternArray=typeof patterns==="string"?[patterns]:patterns;const results=new Set;for(const pattern of patternArray){const{pattern:effective,scan,keep}=plan(pattern,options);try{for await(const match of new BunGlob(effective).scan(scan)){if(keep(match))results.add(match)}}catch(err){if(!isEnoent(err))throw err}}return[...results]}
|
package/dist/hash.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Buffer}from"node:buffer";import{createHash}from"node:crypto";import{path as p}from"@stacksjs/path";import{fs}from"./fs";export function hashFileOrDirectory(path,hash){hashEntry(path,".",hash)}function record(hash,...fields){for(const field of fields){const text=String(field);hash.update(`${Buffer.byteLength(text)}:`);hash.update(text)}}function hashEntry(path,name,hash){let stat;try{stat=fs.lstatSync(path)}catch(error){if(error.code!=="ENOENT")throw error;record(hash,"missing",name);return}if(stat.isSymbolicLink()){record(hash,"link",name,fs.readlinkSync(path));return}if(stat.isDirectory()){record(hash,"directory",name);const entries=fs.readdirSync(path).sort((a,b)=>a<b?-1:a>b?1:0);for(const entry of entries)hashEntry(p.join(path,entry),name==="."?entry:`${name}/${entry}`,hash);return}const contents=fs.readFileSync(path);record(hash,"file",name,contents.length);hash.update(contents)}export function hashDirectory(directory){return hashPath(directory)}export function hashPath(path){const hash=createHash("sha256");hashFileOrDirectory(path,hash);return hash.digest("hex")}export function hashPaths(paths){const hash=createHash("sha256");
|
|
1
|
+
import{Buffer}from"node:buffer";import{createHash}from"node:crypto";import{path as p}from"@stacksjs/path";import{fs}from"./fs";export function hashFileOrDirectory(path,hash){hashEntry(path,".",hash)}function record(hash,...fields){for(const field of fields){const text=String(field);hash.update(`${Buffer.byteLength(text)}:`);hash.update(text)}}function hashEntry(path,name,hash){let stat;try{stat=fs.lstatSync(path)}catch(error){if(error.code!=="ENOENT")throw error;record(hash,"missing",name);return}if(stat.isSymbolicLink()){record(hash,"link",name,fs.readlinkSync(path));return}if(stat.isDirectory()){record(hash,"directory",name);const entries=fs.readdirSync(path).sort((a,b)=>a<b?-1:a>b?1:0);for(const entry of entries)hashEntry(p.join(path,entry),name==="."?entry:`${name}/${entry}`,hash);return}const contents=fs.readFileSync(path);record(hash,"file",name,contents.length);hash.update(contents)}export function hashDirectory(directory){return hashPath(directory)}export function hashPath(path){const hash=createHash("sha256");hashFileOrDirectory(path,hash);return hash.digest("hex")}export function hashPaths(paths){const hash=createHash("sha256");const pathsArray=Array.isArray(paths)?paths:[paths];pathsArray.forEach((path,index)=>{record(hash,"root",index);hashFileOrDirectory(path,hash)});return hash.digest("hex")}
|
package/dist/helpers.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var __dirname="";import{fileURLToPath}from"node:url";import{dirname}from"@stacksjs/path";import{fs}from"./fs";export const _dirname=typeof __dirname
|
|
1
|
+
var __dirname="";import{fileURLToPath}from"node:url";import{dirname}from"@stacksjs/path";import{fs}from"./fs";export const _dirname=typeof __dirname!=="undefined"?__dirname:dirname(fileURLToPath(import.meta.url));export function updateConfigFile(filePath,newConfig){return new Promise((resolve,reject)=>{let config;try{config=JSON.parse(fs.readFileSync(filePath,"utf8"))}catch(error){reject(new Error(`Failed to parse config file "${filePath}": ${error.message}`));return}for(const[key,value]of Object.entries(newConfig))Object.defineProperty(config,key,{value,enumerable:true,writable:true,configurable:true});try{fs.writeFileSync(filePath,JSON.stringify(config,null,2));resolve()}catch(error){reject(error)}})}export const helpers={_dirname,updateConfigFile};
|
package/dist/image.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{blur as applyBlur,decode,encode,resize as applyResize,rotate as applyRotate}from"ts-images";class Pipeline{input;operations=[];format="webp";options={quality:80};constructor(input){this.input=input}resize(width,height,options={}){if(width!==
|
|
1
|
+
import{blur as applyBlur,decode,encode,resize as applyResize,rotate as applyRotate}from"ts-images";class Pipeline{input;operations=[];format="webp";options={quality:80};constructor(input){this.input=input}resize(width,height,options={}){if(width!==undefined&&(!Number.isInteger(width)||width<=0))throw new TypeError("Image width must be positive");if(height!==undefined&&(!Number.isInteger(height)||height<=0))throw new TypeError("Image height must be positive");if(width===undefined&&height===undefined)throw new TypeError("Image resize requires a width or height");this.operations.push((image)=>{if(options.withoutEnlargement!==false&&(width===undefined||width>=image.width)&&(height===undefined||height>=image.height))return image;return applyResize(image,{width,height,fit:options.fit??"inside"})});return this}jpeg(options={}){return this.output("jpeg",options)}png(options={}){return this.output("png",options)}webp(options={}){return this.output("webp",options)}avif(options={}){return this.output("avif",options)}rotate(degrees=90){if(!Number.isFinite(degrees))throw new TypeError("Image rotation must be finite");this.operations.push((image)=>applyRotate(image,degrees));return this}blur(sigma=1){if(!Number.isFinite(sigma)||sigma<=0)throw new TypeError("Image blur sigma must be positive");this.operations.push((image)=>applyBlur(image,sigma));return this}withMetadata(){throw new Error("Native image transforms strip metadata for privacy")}async toBuffer(){let image=await decode(this.input);for(const operation of this.operations)image=operation(image);return Buffer.from(await encode(image,this.format,this.options))}output(format,options){const quality=options.quality??80;if(!Number.isFinite(quality)||quality<1||quality>100)throw new TypeError("Image quality must be between 1 and 100");this.format=format;this.options={...options,quality};return this}}export function transform(pipeline){return async(input)=>{const bytes=input instanceof ArrayBuffer?new Uint8Array(input):new Uint8Array(input.buffer,input.byteOffset,input.byteLength);return(await pipeline(new Pipeline(bytes))).toBuffer()}}export function avatar(size=512,quality=85){return transform((image)=>image.resize(size,size,{fit:"cover"}).webp({quality}))}export function resize(width,height,fit="inside"){return transform((image)=>image.resize(width,height,{fit}).webp())}export function stripMetadata(format="webp"){return transform((image)=>image[format]())}
|
package/dist/mime-verify.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function detectMimeFromMagicBytes(bytes){const view=bytes instanceof Uint8Array?bytes:new Uint8Array(bytes);if(view.length<4)return null;if(view[0]===137&&view[1]===80&&view[2]===78&&view[3]===71&&view[4]===13&&view[5]===10&&view[6]===26&&view[7]===10)return"image/png";if(view[0]===255&&view[1]===216&&view[2]===255)return"image/jpeg";if(view[0]===71&&view[1]===73&&view[2]===70&&view[3]===56)return"image/gif";if(view[0]===82&&view[1]===73&&view[2]===70&&view[3]===70&&view.length>=12){if(view[8]===87&&view[9]===69&&view[10]===66&&view[11]===80)return"image/webp";if(view[8]===87&&view[9]===65&&view[10]===86&&view[11]===69)return"audio/wav"}if(view[0]===37&&view[1]===80&&view[2]===68&&view[3]===70)return"application/pdf";if(view[0]===80&&view[1]===75&&(view[2]===3||view[2]===5)&&(view[3]===4||view[3]===6))return"application/zip";if(view.length>=12&&view[4]===102&&view[5]===116&&view[6]===121&&view[7]===112){const brand=String.fromCharCode(view[8]??0,view[9]??0,view[10]??0,view[11]??0);if(brand==="avif"||brand==="avis")return"image/avif";if(brand==="heic"||brand==="heix"||brand==="mif1")return"image/heic";return"video/mp4"}if(view[0]===26&&view[1]===69&&view[2]===223&&view[3]===163)return"video/webm";if(view[0]===73&&view[1]===68&&view[2]===51)return"audio/mpeg";if(view[0]===255&&(view[1]??0)>=224)return"audio/mpeg";return null}function normalizeContentType(contentType){return contentType.split(";")[0]?.trim().toLowerCase()??""}export async function verifyUploadedMime(path,expectedContentType,options={}){const{Storage}=await import("./facade")
|
|
1
|
+
export function detectMimeFromMagicBytes(bytes){const view=bytes instanceof Uint8Array?bytes:new Uint8Array(bytes);if(view.length<4)return null;if(view[0]===137&&view[1]===80&&view[2]===78&&view[3]===71&&view[4]===13&&view[5]===10&&view[6]===26&&view[7]===10)return"image/png";if(view[0]===255&&view[1]===216&&view[2]===255)return"image/jpeg";if(view[0]===71&&view[1]===73&&view[2]===70&&view[3]===56)return"image/gif";if(view[0]===82&&view[1]===73&&view[2]===70&&view[3]===70&&view.length>=12){if(view[8]===87&&view[9]===69&&view[10]===66&&view[11]===80)return"image/webp";if(view[8]===87&&view[9]===65&&view[10]===86&&view[11]===69)return"audio/wav"}if(view[0]===37&&view[1]===80&&view[2]===68&&view[3]===70)return"application/pdf";if(view[0]===80&&view[1]===75&&(view[2]===3||view[2]===5)&&(view[3]===4||view[3]===6))return"application/zip";if(view.length>=12&&view[4]===102&&view[5]===116&&view[6]===121&&view[7]===112){const brand=String.fromCharCode(view[8]??0,view[9]??0,view[10]??0,view[11]??0);if(brand==="avif"||brand==="avis")return"image/avif";if(brand==="heic"||brand==="heix"||brand==="mif1")return"image/heic";return"video/mp4"}if(view[0]===26&&view[1]===69&&view[2]===223&&view[3]===163)return"video/webm";if(view[0]===73&&view[1]===68&&view[2]===51)return"audio/mpeg";if(view[0]===255&&(view[1]??0)>=224)return"audio/mpeg";return null}function normalizeContentType(contentType){return contentType.split(";")[0]?.trim().toLowerCase()??""}export async function verifyUploadedMime(path,expectedContentType,options={}){const{Storage}=await import("./facade");const disk=Storage.disk(options.disk);const bytes=await disk.readToUint8Array(path);const expected=normalizeContentType(expectedContentType);const detected=detectMimeFromMagicBytes(bytes.slice(0,32));const matches=detected===expected||detected==="image/jpeg"&&(expected==="image/jpg"||expected==="image/pjpeg");return{ok:matches,expected,detected}}
|
package/dist/move.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
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=[]
|
|
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
|
|
2
2
|
|
|
3
|
-
`,error);else log.error(error);return err(error instanceof Error?error:Error(String(error)))}}function isSameEntry(a,b){if(path.resolve(a)===path.resolve(b))return
|
|
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}}
|
package/dist/path-sanitize.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export class PathSanitizeError extends Error{reason;constructor(message,reason){super(message);this.name="PathSanitizeError";this.reason=reason}}const MAX_COMPONENT_LENGTH=255
|
|
1
|
+
export class PathSanitizeError extends Error{reason;constructor(message,reason){super(message);this.name="PathSanitizeError";this.reason=reason}}const MAX_COMPONENT_LENGTH=255;const ALLOWED_DIR_CHAR=/^[A-Za-z0-9._-]+$/;const ALLOWED_FILENAME_CHAR=/^[A-Za-z0-9._-]+$/;const ALLOWED_EXTENSION=/^[a-z0-9]+$/;export function sanitizePresignedDir(dir){if(dir===undefined||dir==="")return"";if(typeof dir!=="string")throw new PathSanitizeError(`dir must be a string, got ${typeof dir}`,"not-string");const trimmed=dir.replace(/^\/+/,"").replace(/\/+$/,"");if(dir.startsWith("/"))throw new PathSanitizeError(`dir must not be absolute: '${dir}'`,"absolute-path");if(trimmed==="")return"";if(trimmed.includes("\x00"))throw new PathSanitizeError(`dir contains null byte`,"null-byte");if(/[\x00-\x1F\x7F]/.test(trimmed))throw new PathSanitizeError(`dir contains control character`,"control-char");const segments=trimmed.split("/");for(const segment of segments){if(segment===""||segment==="."||segment==="..")throw new PathSanitizeError(`dir contains traversal or empty segment: '${dir}'`,"traversal");if(segment.length>MAX_COMPONENT_LENGTH)throw new PathSanitizeError(`dir segment exceeds ${MAX_COMPONENT_LENGTH} chars`,"too-long");if(!ALLOWED_DIR_CHAR.test(segment))throw new PathSanitizeError(`dir segment contains disallowed character: '${segment}'`,"invalid-char")}return segments.join("/")}export function sanitizePresignedFilename(filename){if(typeof filename!=="string")throw new PathSanitizeError(`filename must be a string, got ${typeof filename}`,"not-string");if(filename==="")throw new PathSanitizeError(`filename must not be empty`,"empty");if(filename.length>MAX_COMPONENT_LENGTH)throw new PathSanitizeError(`filename exceeds ${MAX_COMPONENT_LENGTH} chars`,"too-long");if(filename.includes("\x00"))throw new PathSanitizeError(`filename contains null byte`,"null-byte");if(/[\x00-\x1F\x7F]/.test(filename))throw new PathSanitizeError(`filename contains control character`,"control-char");if(filename.includes("/")||filename.includes("\\"))throw new PathSanitizeError(`filename must not contain path separators: '${filename}'`,"traversal");if(filename==="."||filename===".."||filename.startsWith("../")||filename.includes("/.."))throw new PathSanitizeError(`filename contains traversal token: '${filename}'`,"traversal");if(!ALLOWED_FILENAME_CHAR.test(filename))throw new PathSanitizeError(`filename contains disallowed character: '${filename}'`,"invalid-char");const dotIdx=filename.lastIndexOf(".");if(dotIdx>0&&dotIdx<filename.length-1){const ext=filename.slice(dotIdx+1).toLowerCase();if(!ALLOWED_EXTENSION.test(ext))throw new PathSanitizeError(`filename has invalid extension: '.${ext}'`,"invalid-extension")}return filename}const DISK_NAME_RE=/^[a-z0-9_-]+$/i;export function parseDiskPath(input){if(typeof input!=="string"||input.length===0){throw new PathSanitizeError("disk-path reference is empty","empty")}if(input.includes("\x00")){throw new PathSanitizeError("disk-path reference contains a null byte","null-byte")}const colonIdx=input.indexOf(":");if(colonIdx<=0||colonIdx===input.length-1){throw new PathSanitizeError(`disk-path reference must use '<disk>:<path>' format, got '${input}'`,"invalid-char")}const disk=input.slice(0,colonIdx);const path=input.slice(colonIdx+1);if(!DISK_NAME_RE.test(disk)){throw new PathSanitizeError(`disk name '${disk}' is invalid (alphanumeric + '-' / '_' only)`,"invalid-char")}if(path.startsWith("/")||/^[A-Za-z]:[\\/]/.test(path)){throw new PathSanitizeError(`disk-path '${path}' is absolute`,"absolute-path")}if(path.includes("\x00")){throw new PathSanitizeError("disk-path contains a null byte","null-byte")}for(let i=0;i<path.length;i++){const code=path.charCodeAt(i);if(code<32||code===127){throw new PathSanitizeError(`disk-path contains a control character at index ${i}`,"control-char")}}const segments=path.split(/[/\\]/);if(segments.some((seg)=>seg==="..")){throw new PathSanitizeError(`disk-path '${path}' contains a '..' segment`,"traversal")}return{disk,path}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Buffer}from"node:buffer";import{createHash}from"node:crypto";import{closeSync,constants,fstatSync,fsyncSync,linkSync,lstatSync,mkdirSync,openSync,readdirSync,readSync,realpathSync,unlinkSync,writeSync}from"node:fs";import{basename,dirname,join,resolve}from"node:path";import{types}from"node:util";import{completedArtifactLimits}from"./completed-artifact-directory";const typedPrototype=Object.getPrototypeOf(Uint8Array.prototype),byteBuffer=Object.getOwnPropertyDescriptor(typedPrototype,"buffer").get,byteOffset=Object.getOwnPropertyDescriptor(typedPrototype,"byteOffset").get,byteLength=Object.getOwnPropertyDescriptor(typedPrototype,"byteLength").get,setBytes=Uint8Array.prototype.set;function dataRecord(value,allowed){if(!value||typeof value!=="object"||types.isProxy(value))throw TypeError("Artifact input must be plain data");const prototype=Object.getPrototypeOf(value);if(prototype!==Object.prototype&&prototype!==null)throw TypeError("Artifact input must be plain data");const descriptors=Object.getOwnPropertyDescriptors(value);for(const key of Reflect.ownKeys(descriptors)){const descriptor=typeof key==="string"?descriptors[key]:void 0;if(typeof key!=="string"||!allowed.includes(key)||!descriptor?.enumerable||!Object.hasOwn(descriptor,"value"))throw TypeError("Artifact input must have only declared data fields")}return descriptors}function dataList(value){if(!value||typeof value!=="object"||types.isProxy(value)||!Array.isArray(value)||Object.getPrototypeOf(value)!==Array.prototype)throw TypeError("Artifact input must be a plain list");const length=Object.getOwnPropertyDescriptor(value,"length")?.value;if(!Number.isSafeInteger(length)||length>completedArtifactLimits.files)throw RangeError("Artifact resource limit");const descriptors=Object.getOwnPropertyDescriptors(value);if(Reflect.ownKeys(descriptors).length!==length+1)throw TypeError("Artifact list cannot have holes or aliases");const result=[];for(let index=0;index<length;index++){const descriptor=descriptors[String(index)];if(!descriptor?.enumerable||!Object.hasOwn(descriptor,"value"))throw TypeError("Artifact list must contain data");result.push(descriptor.value)}return result}function entryPath(value){if(typeof value!=="string"||value.length>240||!/^[a-z0-9._/-]+$/i.test(value))throw TypeError("Invalid artifact entry path");const parts=value.split("/");if(parts.length>completedArtifactLimits.depth||parts.some((part)=>!part||part==="."||part===".."||part.length>128))throw TypeError("Unsafe artifact entry path")}function detach(entries,manifestJson,options){const list=dataList(entries);if(typeof manifestJson!=="string"||manifestJson.length>completedArtifactLimits.manifestBytes)throw RangeError("Artifact resource limit");const manifestSize=Buffer.byteLength(manifestJson,"utf8");if(manifestSize>completedArtifactLimits.manifestBytes)throw RangeError("Completion manifest byte limit");let parsed;try{parsed=JSON.parse(manifestJson)}catch{throw TypeError("Invalid completion manifest JSON")}if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))throw TypeError("Completion manifest must be a JSON object");const optionFields=dataRecord(options,["directories"]),explicit=optionFields.directories?.value===void 0?[]:dataList(optionFields.directories.value),paths=new Set(["manifest.json","manifest.pending.json"]),directories=new Map;let total=manifestSize;const inputs=[];for(const entry of list){const fields=dataRecord(entry,["path","contents"]);if(!Object.hasOwn(fields,"path")||!Object.hasOwn(fields,"contents"))throw TypeError("Invalid artifact entry");const path=fields.path.value;entryPath(path);const key=path.toLowerCase();if(paths.has(key))throw TypeError("Duplicate or reserved artifact path");paths.add(key);const contents=fields.contents.value;if(typeof contents==="string"){total+=Buffer.byteLength(contents,"utf8");inputs.push({path,contents})}else{if(!contents||typeof contents!=="object"||types.isProxy(contents)||!types.isUint8Array(contents))throw TypeError("Artifact contents must be text or unshared bytes");const buffer=byteBuffer.call(contents);if(types.isSharedArrayBuffer(buffer))throw TypeError("Artifact contents must be text or unshared bytes");const offset=byteOffset.call(contents),length=byteLength.call(contents);new Uint8Array(buffer,offset,length);total+=length;inputs.push({path,contents:{buffer,offset,length}})}if(total>completedArtifactLimits.bytes)throw RangeError("Artifact byte limit")}function register(path,includeLeaf){const parts=path.split("/");for(let depth=1;depth<=parts.length-(includeLeaf?0:1);depth++){const parent=parts.slice(0,depth).join("/"),key=parent.toLowerCase();if(paths.has(key))throw TypeError("Artifact directory and file collision");if(directories.has(key)&&directories.get(key)!==parent)throw TypeError("Artifact directory case alias collision");directories.set(key,parent)}}for(const path of explicit){entryPath(path);register(path,!0)}for(const input of inputs)register(input.path,!1);const files=inputs.map(({path,contents})=>{const bytes=typeof contents==="string"?new TextEncoder().encode(contents):new Uint8Array(contents.length);if(typeof contents!=="string")setBytes.call(bytes,new Uint8Array(contents.buffer,contents.offset,contents.length));return Object.seal({path,bytes})});return Object.seal({files,directories:[...directories.values()].sort((a,b)=>a.split("/").length-b.split("/").length),manifest:new TextEncoder().encode(manifestJson)})}function identity(path,stat,type){if(!(type==="file"?stat.isFile():stat.isDirectory()))throw Error("Artifact identity has an unexpected type");return Object.freeze({path,type,dev:stat.dev.toString(),ino:stat.ino.toString(),uid:stat.uid.toString(),birthtimeNs:stat.birthtimeNs.toString(),nlink:stat.nlink.toString(),mode:Number(stat.mode&0o7777n)})}function sameIdentity(expected,stat,links=expected.nlink){const actual=identity(expected.path,stat,expected.type);if(actual.dev!==expected.dev||actual.ino!==expected.ino||actual.uid!==expected.uid||actual.birthtimeNs!==expected.birthtimeNs||actual.mode!==expected.mode||actual.nlink!==links)throw Error("Artifact identity changed")}function openObserved(path,type,flags,inspect){const before=lstatSync(path,{bigint:!0}),observed=identity(path,before,type),fd=openSync(path,flags|constants.O_NOFOLLOW|constants.O_NONBLOCK|(type==="directory"?constants.O_DIRECTORY:0));try{const stat=fstatSync(fd,{bigint:!0});sameIdentity(observed,stat);sameIdentity(observed,lstatSync(path,{bigint:!0}));inspect(fd,stat);return observed}finally{closeSync(fd)}}function assertPrivate(observed,uid,device){if(observed.uid!==uid||observed.dev!==device||observed.mode!==(observed.type==="file"?384:448)||observed.type==="file"&&observed.nlink!=="1")throw Error("Artifact must retain private ownership, mode and links")}function verifyWrittenHash(fd,expected){const hash=createHash("sha256"),scratch=new Uint8Array(Math.min(65536,expected.bytes));let offset=0;while(offset<expected.bytes){const read=readSync(fd,scratch,0,Math.min(scratch.byteLength,expected.bytes-offset),offset);if(read<=0)throw Error("Artifact readback made no progress");hash.update(scratch.subarray(0,read));offset+=read}if(hash.digest("hex")!==expected.sha256)throw Error("Artifact written hash changed");if(fstatSync(fd,{bigint:!0}).size!==BigInt(expected.bytes))throw Error("Artifact written length changed")}export function prepareCompletedArtifactDirectorySync(directory,entries,manifestJson,options={}){if(typeof directory!=="string"||directory.length<1||directory.length>4096||directory.includes("\x00"))throw TypeError("Invalid artifact directory");const layout=detach(entries,manifestJson,options);if(!constants.O_NOFOLLOW||!constants.O_NONBLOCK||!constants.O_DIRECTORY||!process.getuid)throw Error("Prepared artifacts require POSIX no-follow, nonblocking and directory opens");const uid=String(process.getuid()),lexicalDirectory=resolve(directory),parentPath=realpathSync(dirname(lexicalDirectory)),target=join(parentPath,basename(lexicalDirectory)),parentBefore=openObserved(parentPath,"directory",constants.O_RDONLY,()=>{});if(parentBefore.uid!==uid)throw Error("Artifact parent must belong to the operator");const device=parentBefore.dev;mkdirSync(target,{mode:448});const createdDirectories=new Map;function captureDirectory(path){const observed=openObserved(path,"directory",constants.O_RDONLY,(fd,stat)=>{assertPrivate(identity(path,stat,"directory"),uid,device);const created=createdDirectories.get(path);if(created)sameIdentity(created,stat,stat.nlink.toString());fsyncSync(fd)});createdDirectories.set(path,observed);return observed}captureDirectory(target);for(const path of layout.directories){captureDirectory(dirname(join(target,path)));mkdirSync(join(target,path),{mode:448});captureDirectory(join(target,path))}function preallocate(path,bytes){captureDirectory(dirname(path));const fd=openSync(path,constants.O_CREAT|constants.O_EXCL|constants.O_RDWR|constants.O_NOFOLLOW|constants.O_NONBLOCK,384);let observed,preparationCtimeNs;try{const stat=fstatSync(fd,{bigint:!0});observed=identity(path,stat,"file");assertPrivate(observed,uid,device);sameIdentity(observed,lstatSync(path,{bigint:!0}));if(stat.size!==0n)throw Error("Artifact preallocation must be empty");fsyncSync(fd);preparationCtimeNs=fstatSync(fd,{bigint:!0}).ctimeNs.toString()}finally{closeSync(fd)}return Object.freeze({...observed,preparationCtimeNs,bytes:bytes.byteLength,sha256:createHash("sha256").update(bytes).digest("hex")})}captureDirectory(target);const files=layout.files.map((file)=>preallocate(join(target,file.path),file.bytes)),pendingManifest=preallocate(join(target,"manifest.pending.json"),layout.manifest),directories=layout.directories.map((path)=>captureDirectory(join(target,path))),root=captureDirectory(target),parent=openObserved(parentPath,"directory",constants.O_RDONLY,(fd,stat)=>{sameIdentity(parentBefore,stat,stat.nlink.toString());fsyncSync(fd)}),completedManifest=join(target,"manifest.json"),receipt=Object.freeze({directory:target,lexicalDirectory,parent,root,directories:Object.freeze(directories),files:Object.freeze(files),pendingManifest,completedManifest});let consumed=!1;function verifyDirectory(expected,changingLinks=!1){openObserved(expected.path,"directory",constants.O_RDONLY,(fd,stat)=>{sameIdentity(expected,stat,changingLinks?stat.nlink.toString():expected.nlink);fsyncSync(fd)})}function verifyFile(expected,size,links="1"){openObserved(expected.path,"file",constants.O_RDONLY,(fd,stat)=>{sameIdentity(expected,stat,links);if(stat.size!==BigInt(size))throw Error("Artifact preallocation length changed");if(size===0&&links==="1"&&stat.ctimeNs.toString()!==expected.preparationCtimeNs)throw Error("Artifact empty preallocation changed");if(size>0)verifyWrittenHash(fd,expected)})}function verifyEmptyTree(){if(realpathSync(dirname(lexicalDirectory))!==parentPath)throw Error("Artifact configured parent changed");verifyDirectory(parent,!0);verifyDirectory(root);for(const directory of directories)verifyDirectory(directory);const expectedChildren=new Map([root,...directories].map((item)=>[item.path,[]]));for(const item of[...directories,...files,pendingManifest])expectedChildren.get(dirname(item.path)).push(basename(item.path));for(const[path,children]of expectedChildren){const actual=readdirSync(path).sort(),expected=children.sort();if(actual.length!==expected.length||actual.some((name,index)=>name!==expected[index]))throw Error("Artifact directory entries changed")}for(const file of files)verifyFile(file,0);verifyFile(pendingManifest,0)}function writeDetached(expected,bytes){openObserved(expected.path,"file",constants.O_RDWR,(fd,stat)=>{sameIdentity(expected,stat);if(stat.size!==0n)throw Error("Artifact preallocation length changed");if(stat.ctimeNs.toString()!==expected.preparationCtimeNs)throw Error("Artifact empty preallocation changed");let offset=0;while(offset<bytes.byteLength){const written=writeSync(fd,bytes,offset,bytes.byteLength-offset,offset);if(written<=0)throw Error("Artifact write made no progress");offset+=written}fsyncSync(fd);sameIdentity(expected,fstatSync(fd,{bigint:!0}));if(fstatSync(fd,{bigint:!0}).size!==BigInt(expected.bytes))throw Error("Artifact write length changed");verifyWrittenHash(fd,expected)})}return Object.freeze({receipt,publishSync:()=>{if(consumed)throw Error("Prepared artifact handle is consumed");consumed=!0;try{verifyEmptyTree();for(let index=0;index<files.length;index++)writeDetached(files[index],layout.files[index].bytes);for(const directory of[...directories].reverse())verifyDirectory(directory);verifyDirectory(root);verifyDirectory(parent,!0);writeDetached(pendingManifest,layout.manifest);linkSync(pendingManifest.path,completedManifest);verifyFile(pendingManifest,pendingManifest.bytes,"2");verifyFile({...pendingManifest,path:completedManifest},pendingManifest.bytes,"2");verifyDirectory(root,!0);unlinkSync(pendingManifest.path);verifyFile({...pendingManifest,path:completedManifest},pendingManifest.bytes);verifyDirectory(root);return{directory:target,manifest:completedManifest}}finally{for(const file of layout.files)file.bytes=new Uint8Array(0);layout.manifest=new Uint8Array(0)}}})}
|
|
1
|
+
import{Buffer}from"node:buffer";import{createHash}from"node:crypto";import{closeSync,constants,fstatSync,fsyncSync,linkSync,lstatSync,mkdirSync,openSync,readdirSync,readSync,realpathSync,unlinkSync,writeSync}from"node:fs";import{basename,dirname,join,resolve}from"node:path";import{types}from"node:util";import{completedArtifactLimits}from"./completed-artifact-directory";const typedPrototype=Object.getPrototypeOf(Uint8Array.prototype);const byteBuffer=Object.getOwnPropertyDescriptor(typedPrototype,"buffer").get;const byteOffset=Object.getOwnPropertyDescriptor(typedPrototype,"byteOffset").get;const byteLength=Object.getOwnPropertyDescriptor(typedPrototype,"byteLength").get;const setBytes=Uint8Array.prototype.set;function dataRecord(value,allowed){if(!value||typeof value!=="object"||types.isProxy(value))throw new TypeError("Artifact input must be plain data");const prototype=Object.getPrototypeOf(value);if(prototype!==Object.prototype&&prototype!==null)throw new TypeError("Artifact input must be plain data");const descriptors=Object.getOwnPropertyDescriptors(value);for(const key of Reflect.ownKeys(descriptors)){const descriptor=typeof key==="string"?descriptors[key]:undefined;if(typeof key!=="string"||!allowed.includes(key)||!descriptor?.enumerable||!Object.hasOwn(descriptor,"value"))throw new TypeError("Artifact input must have only declared data fields")}return descriptors}function dataList(value){if(!value||typeof value!=="object"||types.isProxy(value)||!Array.isArray(value)||Object.getPrototypeOf(value)!==Array.prototype)throw new TypeError("Artifact input must be a plain list");const length=Object.getOwnPropertyDescriptor(value,"length")?.value;if(!Number.isSafeInteger(length)||length>completedArtifactLimits.files)throw new RangeError("Artifact resource limit");const descriptors=Object.getOwnPropertyDescriptors(value);if(Reflect.ownKeys(descriptors).length!==length+1)throw new TypeError("Artifact list cannot have holes or aliases");const result=[];for(let index=0;index<length;index++){const descriptor=descriptors[String(index)];if(!descriptor?.enumerable||!Object.hasOwn(descriptor,"value"))throw new TypeError("Artifact list must contain data");result.push(descriptor.value)}return result}function entryPath(value){if(typeof value!=="string"||value.length>240||!/^[a-z0-9._/-]+$/i.test(value))throw new TypeError("Invalid artifact entry path");const parts=value.split("/");if(parts.length>completedArtifactLimits.depth||parts.some((part)=>!part||part==="."||part===".."||part.length>128))throw new TypeError("Unsafe artifact entry path")}function detach(entries,manifestJson,options){const list=dataList(entries);if(typeof manifestJson!=="string"||manifestJson.length>completedArtifactLimits.manifestBytes)throw new RangeError("Artifact resource limit");const manifestSize=Buffer.byteLength(manifestJson,"utf8");if(manifestSize>completedArtifactLimits.manifestBytes)throw new RangeError("Completion manifest byte limit");let parsed;try{parsed=JSON.parse(manifestJson)}catch{throw new TypeError("Invalid completion manifest JSON")}if(!parsed||typeof parsed!=="object"||Array.isArray(parsed))throw new TypeError("Completion manifest must be a JSON object");const optionFields=dataRecord(options,["directories"]);const explicit=optionFields.directories?.value===undefined?[]:dataList(optionFields.directories.value);const paths=new Set(["manifest.json","manifest.pending.json"]);const directories=new Map;let total=manifestSize;const inputs=[];for(const entry of list){const fields=dataRecord(entry,["path","contents"]);if(!Object.hasOwn(fields,"path")||!Object.hasOwn(fields,"contents"))throw new TypeError("Invalid artifact entry");const path=fields.path.value;entryPath(path);const key=path.toLowerCase();if(paths.has(key))throw new TypeError("Duplicate or reserved artifact path");paths.add(key);const contents=fields.contents.value;if(typeof contents==="string"){total+=Buffer.byteLength(contents,"utf8");inputs.push({path,contents})}else{if(!contents||typeof contents!=="object"||types.isProxy(contents)||!types.isUint8Array(contents))throw new TypeError("Artifact contents must be text or unshared bytes");const buffer=byteBuffer.call(contents);if(types.isSharedArrayBuffer(buffer))throw new TypeError("Artifact contents must be text or unshared bytes");const offset=byteOffset.call(contents),length=byteLength.call(contents);new Uint8Array(buffer,offset,length);total+=length;inputs.push({path,contents:{buffer,offset,length}})}if(total>completedArtifactLimits.bytes)throw new RangeError("Artifact byte limit")}function register(path,includeLeaf){const parts=path.split("/");for(let depth=1;depth<=parts.length-(includeLeaf?0:1);depth++){const parent=parts.slice(0,depth).join("/"),key=parent.toLowerCase();if(paths.has(key))throw new TypeError("Artifact directory and file collision");if(directories.has(key)&&directories.get(key)!==parent)throw new TypeError("Artifact directory case alias collision");directories.set(key,parent)}}for(const path of explicit){entryPath(path);register(path,true)}for(const input of inputs)register(input.path,false);const files=inputs.map(({path,contents})=>{const bytes=typeof contents==="string"?new TextEncoder().encode(contents):new Uint8Array(contents.length);if(typeof contents!=="string")setBytes.call(bytes,new Uint8Array(contents.buffer,contents.offset,contents.length));return Object.seal({path,bytes})});return Object.seal({files,directories:[...directories.values()].sort((a,b)=>a.split("/").length-b.split("/").length),manifest:new TextEncoder().encode(manifestJson)})}function identity(path,stat,type){if(!(type==="file"?stat.isFile():stat.isDirectory()))throw new Error("Artifact identity has an unexpected type");return Object.freeze({path,type,dev:stat.dev.toString(),ino:stat.ino.toString(),uid:stat.uid.toString(),birthtimeNs:stat.birthtimeNs.toString(),nlink:stat.nlink.toString(),mode:Number(stat.mode&0o7777n)})}function sameIdentity(expected,stat,links=expected.nlink){const actual=identity(expected.path,stat,expected.type);if(actual.dev!==expected.dev||actual.ino!==expected.ino||actual.uid!==expected.uid||actual.birthtimeNs!==expected.birthtimeNs||actual.mode!==expected.mode||actual.nlink!==links)throw new Error("Artifact identity changed")}function openObserved(path,type,flags,inspect){const before=lstatSync(path,{bigint:true});const observed=identity(path,before,type);const fd=openSync(path,flags|constants.O_NOFOLLOW|constants.O_NONBLOCK|(type==="directory"?constants.O_DIRECTORY:0));try{const stat=fstatSync(fd,{bigint:true});sameIdentity(observed,stat);sameIdentity(observed,lstatSync(path,{bigint:true}));inspect(fd,stat);return observed}finally{closeSync(fd)}}function assertPrivate(observed,uid,device){if(observed.uid!==uid||observed.dev!==device||observed.mode!==(observed.type==="file"?384:448)||observed.type==="file"&&observed.nlink!=="1")throw new Error("Artifact must retain private ownership, mode and links")}function verifyWrittenHash(fd,expected){const hash=createHash("sha256"),scratch=new Uint8Array(Math.min(64*1024,expected.bytes));let offset=0;while(offset<expected.bytes){const read=readSync(fd,scratch,0,Math.min(scratch.byteLength,expected.bytes-offset),offset);if(read<=0)throw new Error("Artifact readback made no progress");hash.update(scratch.subarray(0,read));offset+=read}if(hash.digest("hex")!==expected.sha256)throw new Error("Artifact written hash changed");const stat=fstatSync(fd,{bigint:true});if(stat.size!==BigInt(expected.bytes))throw new Error("Artifact written length changed")}export function prepareCompletedArtifactDirectorySync(directory,entries,manifestJson,options={}){if(typeof directory!=="string"||directory.length<1||directory.length>4096||directory.includes("\x00"))throw new TypeError("Invalid artifact directory");const layout=detach(entries,manifestJson,options);if(!constants.O_NOFOLLOW||!constants.O_NONBLOCK||!constants.O_DIRECTORY||!process.getuid)throw new Error("Prepared artifacts require POSIX no-follow, nonblocking and directory opens");const uid=String(process.getuid());const lexicalDirectory=resolve(directory);const parentPath=realpathSync(dirname(lexicalDirectory));const target=join(parentPath,basename(lexicalDirectory));const parentBefore=openObserved(parentPath,"directory",constants.O_RDONLY,()=>{});if(parentBefore.uid!==uid)throw new Error("Artifact parent must belong to the operator");const device=parentBefore.dev;mkdirSync(target,{mode:448});const createdDirectories=new Map;function captureDirectory(path){const observed=openObserved(path,"directory",constants.O_RDONLY,(fd,stat)=>{assertPrivate(identity(path,stat,"directory"),uid,device);const created=createdDirectories.get(path);if(created)sameIdentity(created,stat,stat.nlink.toString());fsyncSync(fd)});createdDirectories.set(path,observed);return observed}captureDirectory(target);for(const path of layout.directories){captureDirectory(dirname(join(target,path)));mkdirSync(join(target,path),{mode:448});captureDirectory(join(target,path))}function preallocate(path,bytes){captureDirectory(dirname(path));const fd=openSync(path,constants.O_CREAT|constants.O_EXCL|constants.O_RDWR|constants.O_NOFOLLOW|constants.O_NONBLOCK,384);let observed;let preparationCtimeNs;try{const stat=fstatSync(fd,{bigint:true});observed=identity(path,stat,"file");assertPrivate(observed,uid,device);sameIdentity(observed,lstatSync(path,{bigint:true}));if(stat.size!==0n)throw new Error("Artifact preallocation must be empty");fsyncSync(fd);preparationCtimeNs=fstatSync(fd,{bigint:true}).ctimeNs.toString()}finally{closeSync(fd)}return Object.freeze({...observed,preparationCtimeNs,bytes:bytes.byteLength,sha256:createHash("sha256").update(bytes).digest("hex")})}captureDirectory(target);const files=layout.files.map((file)=>preallocate(join(target,file.path),file.bytes));const pendingManifest=preallocate(join(target,"manifest.pending.json"),layout.manifest);const directories=layout.directories.map((path)=>captureDirectory(join(target,path)));const root=captureDirectory(target);const parent=openObserved(parentPath,"directory",constants.O_RDONLY,(fd,stat)=>{sameIdentity(parentBefore,stat,stat.nlink.toString());fsyncSync(fd)});const completedManifest=join(target,"manifest.json");const receipt=Object.freeze({directory:target,lexicalDirectory,parent,root,directories:Object.freeze(directories),files:Object.freeze(files),pendingManifest,completedManifest});let consumed=false;function verifyDirectory(expected,changingLinks=false){openObserved(expected.path,"directory",constants.O_RDONLY,(fd,stat)=>{sameIdentity(expected,stat,changingLinks?stat.nlink.toString():expected.nlink);fsyncSync(fd)})}function verifyFile(expected,size,links="1"){openObserved(expected.path,"file",constants.O_RDONLY,(fd,stat)=>{sameIdentity(expected,stat,links);if(stat.size!==BigInt(size))throw new Error("Artifact preallocation length changed");if(size===0&&links==="1"&&stat.ctimeNs.toString()!==expected.preparationCtimeNs)throw new Error("Artifact empty preallocation changed");if(size>0)verifyWrittenHash(fd,expected)})}function verifyEmptyTree(){if(realpathSync(dirname(lexicalDirectory))!==parentPath)throw new Error("Artifact configured parent changed");verifyDirectory(parent,true);verifyDirectory(root);for(const directory of directories)verifyDirectory(directory);const expectedChildren=new Map([root,...directories].map((item)=>[item.path,[]]));for(const item of[...directories,...files,pendingManifest])expectedChildren.get(dirname(item.path)).push(basename(item.path));for(const[path,children]of expectedChildren){const actual=readdirSync(path).sort();const expected=children.sort();if(actual.length!==expected.length||actual.some((name,index)=>name!==expected[index]))throw new Error("Artifact directory entries changed")}for(const file of files)verifyFile(file,0);verifyFile(pendingManifest,0)}function writeDetached(expected,bytes){openObserved(expected.path,"file",constants.O_RDWR,(fd,stat)=>{sameIdentity(expected,stat);if(stat.size!==0n)throw new Error("Artifact preallocation length changed");if(stat.ctimeNs.toString()!==expected.preparationCtimeNs)throw new Error("Artifact empty preallocation changed");let offset=0;while(offset<bytes.byteLength){const written=writeSync(fd,bytes,offset,bytes.byteLength-offset,offset);if(written<=0)throw new Error("Artifact write made no progress");offset+=written}fsyncSync(fd);sameIdentity(expected,fstatSync(fd,{bigint:true}));if(fstatSync(fd,{bigint:true}).size!==BigInt(expected.bytes))throw new Error("Artifact write length changed");verifyWrittenHash(fd,expected)})}const publishSync=()=>{if(consumed)throw new Error("Prepared artifact handle is consumed");consumed=true;try{verifyEmptyTree();for(let index=0;index<files.length;index++)writeDetached(files[index],layout.files[index].bytes);for(const directory of[...directories].reverse())verifyDirectory(directory);verifyDirectory(root);verifyDirectory(parent,true);writeDetached(pendingManifest,layout.manifest);linkSync(pendingManifest.path,completedManifest);verifyFile(pendingManifest,pendingManifest.bytes,"2");verifyFile({...pendingManifest,path:completedManifest},pendingManifest.bytes,"2");verifyDirectory(root,true);unlinkSync(pendingManifest.path);verifyFile({...pendingManifest,path:completedManifest},pendingManifest.bytes);verifyDirectory(root);return{directory:target,manifest:completedManifest}}finally{for(const file of layout.files)file.bytes=new Uint8Array(0);layout.manifest=new Uint8Array(0)}};return Object.freeze({receipt,publishSync})}
|
package/dist/provision.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export async function ensureBucket(bucket,options={}){if(!bucket)throw Error("ensureBucket requires a bucket name.");const{createObjectStorageClient,resolveObjectStorage}=await import("@stacksjs/ts-cloud")
|
|
1
|
+
export async function ensureBucket(bucket,options={}){if(!bucket)throw new Error("ensureBucket requires a bucket name.");const{createObjectStorageClient,resolveObjectStorage}=await import("@stacksjs/ts-cloud");const resolved=resolveObjectStorage(options);const client=createObjectStorageClient(options);const base={bucket,provider:resolved.provider,region:resolved.region,endpoint:resolved.endpoint,publicUrl:resolved.publicBaseUrl(bucket)};if(await client.bucketExists(bucket))return{...base,status:"exists"};try{await client.createBucket(bucket,{acl:options.acl??"private"});return{...base,status:"created"}}catch(error){const message=error instanceof Error?error.message:String(error);if(/BucketAlreadyOwnedByYou|BucketAlreadyExists|already exists/i.test(message))return{...base,status:"exists"};throw new Error(`Could not create bucket "${bucket}" on ${resolved.provider}: ${message}`)}}export async function ensureConfiguredBuckets(options={}){const{filesystems}=await import("@stacksjs/config");const names=new Set;if(filesystems?.s3?.bucket)names.add(filesystems.s3.bucket);for(const disk of Object.values(filesystems?.disks??{})){const candidate=disk;if(candidate?.driver==="s3"&&candidate.bucket)names.add(candidate.bucket)}if(names.size===0)return[];const results=[];for(const name of names)results.push(await ensureBucket(name,options));return results}
|
package/dist/put-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const MIME_TO_EXT={"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/webp":"webp","image/gif":"gif","image/svg+xml":"svg","image/avif":"avif","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/octet-stream":"bin","text/plain":"txt","text/csv":"csv","text/html":"html","video/mp4":"mp4","video/webm":"webm","audio/mpeg":"mp3","audio/wav":"wav"};function extFromOriginalName(name){if(!name)return null;const idx=name.lastIndexOf(".");if(idx<=0||idx===name.length-1)return null;const ext=name.slice(idx+1).toLowerCase();if(!/^[a-z0-9]+$/.test(ext))return null;return ext}function originalNameOf(file){return file.originalName??file.name}function mimetypeOf(file){return file.mimetype??file.mimeType}function deriveExtension(file){const mime=mimetypeOf(file);return extFromOriginalName(originalNameOf(file))??(mime&&MIME_TO_EXT[mime.toLowerCase()])??null}async function readBytes(file){if(file.buffer!==
|
|
1
|
+
const MIME_TO_EXT={"image/jpeg":"jpg","image/jpg":"jpg","image/png":"png","image/webp":"webp","image/gif":"gif","image/svg+xml":"svg","image/avif":"avif","application/pdf":"pdf","application/json":"json","application/zip":"zip","application/octet-stream":"bin","text/plain":"txt","text/csv":"csv","text/html":"html","video/mp4":"mp4","video/webm":"webm","audio/mpeg":"mp3","audio/wav":"wav"};function extFromOriginalName(name){if(!name)return null;const idx=name.lastIndexOf(".");if(idx<=0||idx===name.length-1)return null;const ext=name.slice(idx+1).toLowerCase();if(!/^[a-z0-9]+$/.test(ext))return null;return ext}function originalNameOf(file){return file.originalName??file.name}function mimetypeOf(file){return file.mimetype??file.mimeType}function deriveExtension(file){const mime=mimetypeOf(file);return extFromOriginalName(originalNameOf(file))??(mime&&MIME_TO_EXT[mime.toLowerCase()])??null}async function readBytes(file){if(file.buffer!==undefined)return file.buffer;if(typeof file.bytes==="function")return await file.bytes();if(typeof file.arrayBuffer==="function")return await file.arrayBuffer();throw new Error("UploadedFile is missing both `buffer` and `bytes()`/`arrayBuffer()` accessors - cannot read file contents.")}function bufferLikeToHash(buffer){const view=buffer instanceof ArrayBuffer?new Uint8Array(buffer):buffer;const hasher=new Bun.CryptoHasher("sha256");hasher.update(view);return hasher.digest("hex").slice(0,32)}function sanitizeOriginalName(name){const stripped=name.replace(/[/\\]/g,"_").replace(/\.{2,}/g,"_");return stripped.replace(/[^A-Za-z0-9._-]/g,"_").replace(/_+/g,"_")}async function resolveFilename(file,strategy){if(typeof strategy==="function")return strategy(file);switch(strategy){case"uuid":return crypto.randomUUID().replace(/-/g,"");case"hash":{const bytes=await readBytes(file);return bufferLikeToHash(bytes)}case"original":{const name=originalNameOf(file);return name?sanitizeOriginalName(name):crypto.randomUUID().replace(/-/g,"")}}}function joinPath(...parts){return parts.filter(Boolean).map((p,i)=>i===0?p.replace(/\/+$/,""):p.replace(/^\/+/,"").replace(/\/+$/,"")).filter(Boolean).join("/")}export async function putUploadedFile(manager,file,opts){const disk=manager.disk(opts.disk);const baseName=await resolveFilename(file,opts.filename??"uuid");const wantExt=opts.preserveExtension!==false;const baseHasExt=/\.[A-Za-z0-9]+$/.test(baseName);const ext=wantExt&&!baseHasExt?deriveExtension(file):null;const finalName=ext?`${baseName}.${ext}`:baseName;const fullPath=joinPath(opts.dir??"",finalName);if(opts.overwrite===false&&await disk.fileExists(fullPath))throw new Error(`File already exists: ${fullPath}`);const raw=await readBytes(file);let contents=raw instanceof ArrayBuffer?new Uint8Array(raw):raw;if(opts.transform){contents=await opts.transform(contents)}const written=await disk.write(fullPath,contents);const url=await disk.publicUrl(fullPath);return{...written,path:fullPath,url}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHmac}from"node:crypto";import{Buffer}from"node:buffer";const ALGORITHM="AWS4-HMAC-SHA256"
|
|
1
|
+
import{createHmac}from"node:crypto";import{Buffer}from"node:buffer";const ALGORITHM="AWS4-HMAC-SHA256";const MIN_EXPIRY=60;const MAX_EXPIRY=7*24*60*60;function hmac(key,data){return createHmac("sha256",key).update(data,"utf8").digest()}function deriveSigningKey(secretAccessKey,dateStamp,region){const kDate=hmac(`AWS4${secretAccessKey}`,dateStamp);const kRegion=hmac(kDate,region);const kService=hmac(kRegion,"s3");const kSigning=hmac(kService,"aws4_request");return kSigning}function isoDate(now){const amzDate=now.toISOString().replace(/[:-]|\.\d{3}/g,"");const dateStamp=amzDate.slice(0,8);return{amzDate,dateStamp}}export function signS3PresignedPost(input){const expiresIn=Math.floor(input.expiresIn);if(!Number.isFinite(expiresIn)||expiresIn<MIN_EXPIRY||expiresIn>MAX_EXPIRY){throw new RangeError(`[storage/s3-post] expiresIn must be between ${MIN_EXPIRY}s and ${MAX_EXPIRY}s (got ${expiresIn}s)`)}if(!input.bucket)throw new Error("[storage/s3-post] bucket is required");if(!input.credentials?.accessKeyId||!input.credentials?.secretAccessKey){throw new Error("[storage/s3-post] credentials.accessKeyId and credentials.secretAccessKey are required")}const now=new Date;const{amzDate,dateStamp}=isoDate(now);const credentialScope=`${dateStamp}/${input.region}/s3/aws4_request`;const credentialField=`${input.credentials.accessKeyId}/${credentialScope}`;const expirationDate=new Date(now.getTime()+expiresIn*1000).toISOString().replace(/\.\d{3}Z$/,"Z");const conditions=[];conditions.push({bucket:input.bucket});if(typeof input.key==="string"){conditions.push({key:input.key})}else{conditions.push(["starts-with","$key",input.key.startsWith])}const acl=input.acl??"private";conditions.push({acl});if(typeof input.contentType==="string"){conditions.push({"Content-Type":input.contentType})}else{conditions.push(["starts-with","$Content-Type",input.contentType.startsWith])}if(input.contentLengthRange){if(!Number.isFinite(input.contentLengthRange.min)||input.contentLengthRange.min<0||!Number.isFinite(input.contentLengthRange.max)||input.contentLengthRange.max<input.contentLengthRange.min){throw new RangeError("[storage/s3-post] contentLengthRange must satisfy 0 <= min <= max")}conditions.push(["content-length-range",input.contentLengthRange.min,input.contentLengthRange.max])}if(input.fields){for(const[k,v]of Object.entries(input.fields)){conditions.push({[k]:v})}}conditions.push({"x-amz-credential":credentialField});conditions.push({"x-amz-algorithm":ALGORITHM});conditions.push({"x-amz-date":amzDate});if(input.credentials.sessionToken){conditions.push({"x-amz-security-token":input.credentials.sessionToken})}const policy={expiration:expirationDate,conditions};const policyBase64=Buffer.from(JSON.stringify(policy),"utf8").toString("base64");const signingKey=deriveSigningKey(input.credentials.secretAccessKey,dateStamp,input.region);const signature=createHmac("sha256",signingKey).update(policyBase64,"utf8").digest("hex");const fields={key:typeof input.key==="string"?input.key:`${input.key.startsWith}\${filename}`,acl,"Content-Type":typeof input.contentType==="string"?input.contentType:input.contentType.startsWith,"x-amz-credential":credentialField,"x-amz-algorithm":ALGORITHM,"x-amz-date":amzDate,policy:policyBase64,"x-amz-signature":signature,...input.credentials.sessionToken?{"x-amz-security-token":input.credentials.sessionToken}:{},...input.fields??{}};return{url:`https://${input.bucket}.s3.${input.region}.amazonaws.com/`,fields,key:typeof input.key==="string"?input.key:input.key.startsWith}}
|
package/dist/signed-url.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Buffer}from"node:buffer";import{createHmac,timingSafeEqual}from"node:crypto";import process from"node:process";const ALG="HS256";function getAppKey(){const k=process.env.APP_KEY;if(!k||k.length<16){if(process.env.APP_ENV==="production"||process.env.NODE_ENV==="production")throw Error("[storage/signed-url] APP_KEY is missing or too short (need
|
|
1
|
+
import{Buffer}from"node:buffer";import{createHmac,timingSafeEqual}from"node:crypto";import process from"node:process";const ALG="HS256";function getAppKey(){const k=process.env.APP_KEY;if(!k||k.length<16){if(process.env.APP_ENV==="production"||process.env.NODE_ENV==="production"){throw new Error("[storage/signed-url] APP_KEY is missing or too short (need ≥16 chars). Cannot sign URL.")}}return k||"stacks-default-key-dev-only-do-not-use-prod"}function base64UrlEncode(buf){return buf.toString("base64url")}function base64UrlDecode(str){return Buffer.from(str,"base64url")}function normalizeExpiry(expiresIn){if(expiresIn instanceof Date)return Math.floor(expiresIn.getTime()/1000);return Math.floor(Date.now()/1000)+Math.floor(expiresIn)}export function createSignedStorageToken(path,options){const exp=normalizeExpiry(options.expiresIn);const iat=Math.floor(Date.now()/1000);const header={alg:ALG,typ:"JWT"};const payload={iss:options.issuer||"stacks",iat,exp,path,...options.disk?{disk:options.disk}:{}};const headerPart=base64UrlEncode(Buffer.from(JSON.stringify(header)));const payloadPart=base64UrlEncode(Buffer.from(JSON.stringify(payload)));const signingInput=`${headerPart}.${payloadPart}`;const sig=base64UrlEncode(createHmac("sha256",getAppKey()).update(signingInput).digest());return`${signingInput}.${sig}`}const REVOCATION_LIMIT=1e5;const revokedSignatures=new Map;function rememberRevoked(sigPart,expiresAt){if(revokedSignatures.has(sigPart))return;if(revokedSignatures.size>=REVOCATION_LIMIT){const now=Math.floor(Date.now()/1000);for(const[signature,expiry]of revokedSignatures){if(expiry!==undefined&&expiry<=now)revokedSignatures.delete(signature)}}if(revokedSignatures.size>=REVOCATION_LIMIT)throw new Error("[storage/signed-url] Revocation capacity reached. Rotate APP_KEY or use a durable revocation store.");revokedSignatures.set(sigPart,expiresAt)}export function revokeSignedStorageToken(token){if(typeof token!=="string"||token.length===0)return;const parts=token.split(".");const sig=parts.length===3?parts[2]:token;if(!sig)return;let expiresAt;if(parts.length===3){try{const payload=JSON.parse(base64UrlDecode(parts[1]).toString("utf8"));if(typeof payload?.path==="string"){const verified=verifySignedStorageToken(token,payload.path);if(verified.valid&&Number.isFinite(verified.claims?.exp))expiresAt=verified.claims.exp}}catch{}}rememberRevoked(base64UrlEncode(base64UrlDecode(sig)),expiresAt)}export function isSignedStorageTokenRevoked(sigPart){return revokedSignatures.has(base64UrlEncode(base64UrlDecode(sigPart)))}export function clearRevokedSignedStorageTokens(){revokedSignatures.clear()}export function verifySignedStorageToken(token,requestedPath){if(typeof token!=="string"){return{valid:false,reason:"malformed"}}const parts=token.split(".");if(parts.length!==3){return{valid:false,reason:"malformed"}}const headerPart=parts[0];const payloadPart=parts[1];const sigPart=parts[2];const signingInput=`${headerPart}.${payloadPart}`;const expectedSig=createHmac("sha256",getAppKey()).update(signingInput).digest();let providedSig;try{providedSig=base64UrlDecode(sigPart)}catch{return{valid:false,reason:"malformed"}}if(providedSig.length!==expectedSig.length||!timingSafeEqual(providedSig,expectedSig)){return{valid:false,reason:"bad_signature"}}if(revokedSignatures.has(base64UrlEncode(providedSig))){return{valid:false,reason:"revoked"}}let claims;try{claims=JSON.parse(base64UrlDecode(payloadPart).toString("utf8"))}catch{return{valid:false,reason:"malformed"}}const now=Math.floor(Date.now()/1000);if(typeof claims.exp!=="number"||now>=claims.exp){return{valid:false,reason:"expired"}}if(claims.path!==requestedPath){return{valid:false,reason:"path_mismatch"}}return{valid:true,claims}}
|
package/dist/static-serve.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{extname}from"node:path";const etagCache=new Map
|
|
1
|
+
import{createHash}from"node:crypto";import{extname}from"node:path";const etagCache=new Map;const ETAG_CACHE_MAX=5000;const FINGERPRINTED=/\.[a-f0-9]{8,}\./;export async function serveFile(req,filePath,options={}){const file=Bun.file(filePath);const exists=await file.exists();if(!exists)return new Response("Not Found",{status:404});const stat=await file.stat();const mtimeMs=Math.floor(typeof stat.mtimeMs==="number"?stat.mtimeMs:stat.mtime?.getTime()??Date.now());const lastModified=new Date(mtimeMs).toUTCString();const contentType=options.contentType||file.type||guessMime(filePath);let etag;if(options.etag!==false){const version=[stat.dev,stat.ino,stat.size,stat.mtimeMs,stat.ctimeMs].join(":");etag=await computeEtag(filePath,version,file)}if(req.method==="GET"||req.method==="HEAD"){const headers=()=>buildHeaders({etag,lastModified,contentType,filePath,options,omitContentType:true});const ifNoneMatch=req.headers.get("if-none-match");if(ifNoneMatch!==null){if(noneMatchHits(ifNoneMatch,etag))return new Response(null,{status:304,headers:headers()})}else{const ifModifiedSince=req.headers.get("if-modified-since");const sinceMs=ifModifiedSince?Date.parse(ifModifiedSince):Number.NaN;if(!Number.isNaN(sinceMs)&&Math.floor(mtimeMs/1000)*1000<=sinceMs)return new Response(null,{status:304,headers:headers()})}}return new Response(file,{status:200,headers:buildHeaders({etag,lastModified,contentType,filePath,options})})}function buildHeaders(input){const h=new Headers;if(!input.omitContentType)h.set("Content-Type",input.contentType);h.set("Last-Modified",input.lastModified);if(input.etag)h.set("ETag",`"${input.etag}"`);h.set("Cache-Control",input.options.cacheControl||pickCacheControl(input.filePath,input.options));h.set("Vary","Accept-Encoding");return h}function pickCacheControl(filePath,options){if(FINGERPRINTED.test(filePath))return"public, max-age=31536000, immutable";const maxAge=options.defaultMaxAge??300;return`public, max-age=${maxAge}, must-revalidate`}async function computeEtag(filePath,version,file){const cached=etagCache.get(filePath);if(cached&&cached.version===version)return cached.etag;const buf=await file.arrayBuffer();const etag=createHash("sha256").update(new Uint8Array(buf)).digest("hex").slice(0,16);if(etagCache.size>=ETAG_CACHE_MAX){const firstKey=etagCache.keys().next().value;if(firstKey!==undefined)etagCache.delete(firstKey)}etagCache.set(filePath,{version,etag});return etag}function noneMatchHits(header,etag){const value=header.trim();if(value==="*")return true;if(!etag)return false;return value.split(",").some((entry)=>{let tag=entry.trim();if(tag.startsWith("W/"))tag=tag.slice(2);if(tag.startsWith('"')&&tag.endsWith('"'))tag=tag.slice(1,-1);return tag===etag})}function guessMime(filePath){const ext=extname(filePath).toLowerCase();switch(ext){case".js":case".mjs":case".cjs":return"application/javascript; charset=utf-8";case".css":return"text/css; charset=utf-8";case".html":case".htm":return"text/html; charset=utf-8";case".json":return"application/json; charset=utf-8";case".svg":return"image/svg+xml";case".webp":return"image/webp";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";case".gif":return"image/gif";case".ico":return"image/x-icon";case".woff":return"font/woff";case".woff2":return"font/woff2";case".ttf":return"font/ttf";case".txt":return"text/plain; charset=utf-8";case".wasm":return"application/wasm";case".map":return"application/json; charset=utf-8";default:return"application/octet-stream"}}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import{existsSync,lstatSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,readlinkSync,realpathSync,renameSync,rmSync,writeFileSync}from"node:fs";import{basename,dirname,join,resolve}from"node:path";import process from"node:process";function vanished(error){return error instanceof Error&&"code"in error&&(error.code==="ENOENT"||error.code==="ESRCH")}function beneath(path,root){const clean=path.replace(/ \(deleted\)$/,"");return clean===root||clean.startsWith(`${root}/`)}function mountedWorkspace(table,path){return table.split(`
|
|
2
|
-
`).some((line)=>{const fields=line.split(" ");return[fields[3],fields[4]].some((field)=>field&&beneath(field.replace(/\\([0-7]{3})/g,(_match,octal)=>String.fromCharCode(Number.parseInt(octal,8))),path))})}function inspectWorkspaceMounts(path){try{if(process.platform==="linux"){const table=readFileSync("/proc/self/mountinfo","utf8");if(!table.trim())return{unused
|
|
3
|
-
`).some((line)=>{const target=/ on (.+) \(/.exec(line)?.[1];return target!==
|
|
4
|
-
`)){const mapped=/^\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+(.+)$/.exec(line)?.[1];if(mapped)references.push(mapped)}if(references.some((reference)=>beneath(reference,path)))return{unused
|
|
2
|
+
`).some((line)=>{const fields=line.split(" ");return[fields[3],fields[4]].some((field)=>field&&beneath(field.replace(/\\([0-7]{3})/g,(_match,octal)=>String.fromCharCode(Number.parseInt(octal,8))),path))})}function inspectWorkspaceMounts(path){try{if(process.platform==="linux"){const table=readFileSync("/proc/self/mountinfo","utf8");if(!table.trim())return{unused:false,reason:"inspection-unavailable",operation:"mounts"};const mounted=mountedWorkspace(table,path);return{unused:!mounted,reason:mounted?"mounted":"unused"}}if(process.platform==="darwin"){const mounts=Bun.spawnSync(["mount"],{stdout:"pipe",stderr:"pipe"});if(mounts.exitCode!==0||mounts.stderr.length>0||mounts.stdout.length===0)return{unused:false,reason:"inspection-unavailable",operation:"mounts"};const mounted=mounts.stdout.toString().split(`
|
|
3
|
+
`).some((line)=>{const target=/ on (.+) \(/.exec(line)?.[1];return target!==undefined&&beneath(target,path)});return{unused:!mounted,reason:mounted?"mounted":"unused"}}}catch(error){return{unused:false,reason:"inspection-unavailable",operation:"mounts",code:error instanceof Error&&"code"in error?String(error.code):undefined}}return{unused:false,reason:"unsupported-platform"}}export function inspectDirectoryMounts(path){try{if(typeof path!=="string"||path.length===0||path.length>4096||path.includes("\x00")||realpathSync(path)!==path||!lstatSync(path).isDirectory())return{unmounted:false,reason:"inspection-unavailable",operation:"path",code:"INVALID_DIRECTORY"}}catch(error){return{unmounted:false,reason:"inspection-unavailable",operation:"path",code:error instanceof Error&&"code"in error?String(error.code):undefined}}const result=inspectWorkspaceMounts(path);if(result.reason==="unused")return{unmounted:true,reason:"unmounted"};if(result.reason==="mounted")return{unmounted:false,reason:"mounted"};if(result.reason==="unsupported-platform")return{unmounted:false,reason:"unsupported-platform"};return{unmounted:false,reason:"inspection-unavailable",operation:"mounts",code:result.code}}export function inspectTemporaryWorkspace(path){let operation="mounts";try{const mounts=inspectWorkspaceMounts(path);if(!mounts.unused)return mounts;if(process.platform==="linux"){const uid=process.getuid?.();for(const pid of readdirSync("/proc").filter((name)=>/^\d+$/.test(name))){const directory=`/proc/${pid}`;try{operation="process-owner";const identities=/^Uid:\s+(.+)$/m.exec(readFileSync(`${directory}/status`,"utf8"))?.[1]?.trim().split(/\s+/).map(Number);if(!identities?.length)return{unused:false,reason:"inspection-unavailable",pid:Number(pid),operation};if(uid!==0&&!identities.includes(Number(uid)))continue;operation="process-mounts";if(mountedWorkspace(readFileSync(`${directory}/mountinfo`,"utf8"),path))return{unused:false,reason:"mounted",pid:Number(pid)};operation="process-paths";const references=[readlinkSync(`${directory}/cwd`),readlinkSync(`${directory}/exe`)];operation="process-files";for(const fd of readdirSync(`${directory}/fd`)){try{references.push(readlinkSync(`${directory}/fd/${fd}`))}catch(error){if(!vanished(error))throw error}}operation="process-maps";for(const line of readFileSync(`${directory}/maps`,"utf8").split(`
|
|
4
|
+
`)){const mapped=/^\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+(.+)$/.exec(line)?.[1];if(mapped)references.push(mapped)}if(references.some((reference)=>beneath(reference,path)))return{unused:false,reason:"process-reference",pid:Number(pid)}}catch(error){if(!vanished(error))return{unused:false,reason:"inspection-unavailable",pid:Number(pid),operation,code:error instanceof Error&&"code"in error?String(error.code):undefined}}}return{unused:true,reason:"unused"}}if(process.platform==="darwin"){const uid=process.getuid?.();if(uid===undefined)return{unused:false,reason:"inspection-unavailable",operation:"process-owner"};operation="process-files";const files=Bun.spawnSync(["lsof","-nP","-F0n",...uid===0?[]:["-u",String(uid)]],{stdout:"pipe",stderr:"pipe"});if(files.exitCode!==0||files.stderr.length>0)return{unused:false,reason:"inspection-unavailable",operation};const used=files.stdout.toString().split("\x00").some((field)=>field.startsWith("n")&&beneath(field.slice(1),path));return{unused:!used,reason:used?"process-reference":"unused"}}}catch(error){return{unused:false,reason:"inspection-unavailable",operation,code:error instanceof Error&&"code"in error?String(error.code):undefined}}return{unused:false,reason:"unsupported-platform"}}export function temporaryWorkspaceIsUnused(path){return inspectTemporaryWorkspace(path).unused}export class TemporaryWorkspaceJournal{directory;temporaryRoot;prefix;ownerUid;active=new Map;rootInode;rootDevice;journalInode;journalDevice;constructor(options){if(typeof options.prefix!=="string"||!/^[a-z0-9_-]+$/i.test(options.prefix))throw new TypeError("Invalid temporary workspace prefix");const currentUid=process.getuid?.();const ownerUid=options.ownerUid??currentUid;if(currentUid===undefined||ownerUid===undefined||!Number.isSafeInteger(ownerUid)||ownerUid<0)throw new Error("Workspace ownership requires a POSIX user identity");if(ownerUid!==currentUid&¤tUid!==0)throw new Error("Only root may maintain another user's workspace journal");if(ownerUid!==currentUid&&!existsSync(options.directory))throw new Error("Another user's journal must already exist");mkdirSync(options.directory,{recursive:true,mode:448});const journal=lstatSync(options.directory);if(!journal.isDirectory()||journal.isSymbolicLink()||journal.uid!==ownerUid||(journal.mode&63)!==0)throw new Error("A workspace journal must be a private directory owned by its declared user");this.ownerUid=ownerUid;this.directory=realpathSync(options.directory);this.temporaryRoot=realpathSync(options.temporaryRoot);if(this.directory===this.temporaryRoot)throw new Error("The journal cannot be the temporary root");this.prefix=options.prefix;const root=lstatSync(this.temporaryRoot,{bigint:true});const journalIdentity=lstatSync(this.directory,{bigint:true});this.rootInode=String(root.ino);this.rootDevice=String(root.dev);this.journalInode=String(journalIdentity.ino);this.journalDevice=String(journalIdentity.dev)}create(key){if(typeof key!=="string"||!/^[a-z0-9_-]{1,80}$/i.test(key))throw new TypeError("Invalid workspace key");if(this.ownerUid!==process.getuid?.())throw new Error("Maintenance cannot create workspaces for another user");if(!this.rootsUnchanged())throw new Error("The workspace or journal root changed");const path=mkdtempSync(join(this.temporaryRoot,`${this.prefix}${key}-`));const identity=lstatSync(path,{bigint:true});const record=Object.freeze({id:crypto.randomUUID(),key,path,inode:String(identity.ino),device:String(identity.dev),uid:String(identity.uid)});const file=join(this.directory,`${record.id}.json`);try{writeFileSync(`${file}.tmp`,JSON.stringify(record),{flag:"wx",mode:384});renameSync(`${file}.tmp`,file);this.active.set(record.id,record);return record}catch(error){rmSync(path,{recursive:true,force:true});rmSync(`${file}.tmp`,{force:true});throw error}}list(){if(!this.rootsUnchanged())return[];const records=[];for(const entry of readdirSync(this.directory).slice(0,1000)){if(!entry.endsWith(".json"))continue;const record=this.read(entry.slice(0,-5));if(record)records.push(record)}return records}complete(record){if(!record||this.active.get(record.id)!==record)return false;if(!this.remove(record))return false;this.active.delete(record.id);return true}async retire(id,mayRetire){const verdict=await this.inspectRetirement(id,mayRetire);if(!verdict.ready||!verdict.record||!this.remove(verdict.record))return false;this.active.delete(verdict.record.id);return true}async inspectRetirement(id,mayRetire){const record=this.read(id);if(!record)return{ready:false,reason:"record-invalid"};if(await mayRetire(record)!==true)return{ready:false,reason:"not-authorized",record};if(!this.rootsUnchanged())return{ready:false,reason:"identity-changed",record};const identity=this.identity(record);if(identity==="changed"||identity==="unavailable")return{ready:false,reason:"identity-changed",record};if(identity==="missing")return{ready:true,reason:"ready",record};const usage=inspectTemporaryWorkspace(record.path);return{ready:usage.unused,reason:usage.unused?"ready":usage.reason,record,usage}}identity(record){try{const identity=lstatSync(record.path,{bigint:true});const same=identity.isDirectory()&&!identity.isSymbolicLink()&&String(identity.uid)===record.uid&&String(identity.uid)===String(this.ownerUid)&&String(identity.ino)===record.inode&&String(identity.dev)===record.device;return same?"same":"changed"}catch(error){return vanished(error)?"missing":"unavailable"}}remove(record){try{if(!this.rootsUnchanged())return false;const identity=this.identity(record);if(identity==="changed"||identity==="unavailable")return false;if(identity==="same"){if(!inspectWorkspaceMounts(record.path).unused)return false;rmSync(record.path,{recursive:true})}}catch(error){if(!vanished(error)||this.identity(record)!=="missing")return false}rmSync(join(this.directory,`${record.id}.json`),{force:true});return true}read(id){if(typeof id!=="string"||!/^[0-9a-f-]{36}$/.test(id))return null;if(!this.rootsUnchanged())return null;try{const file=join(this.directory,`${id}.json`);const identity=lstatSync(file);if(!identity.isFile()||identity.isSymbolicLink()||identity.uid!==this.ownerUid||(identity.mode&63)!==0||identity.size>4096)return null;const value=JSON.parse(readFileSync(file,"utf8"));if(!value||value.id!==id||typeof value.key!=="string"||!/^[a-z0-9_-]{1,80}$/i.test(value.key)||typeof value.path!=="string"||resolve(value.path)!==value.path||dirname(value.path)!==this.temporaryRoot||!basename(value.path).startsWith(`${this.prefix}${value.key}-`)||!["inode","device","uid"].every((key)=>typeof value[key]==="string"&&/^\d+$/.test(value[key])))return null;return Object.freeze(value)}catch{return null}}rootsUnchanged(){try{const root=lstatSync(this.temporaryRoot,{bigint:true});const journal=lstatSync(this.directory,{bigint:true});return root.isDirectory()&&!root.isSymbolicLink()&&String(root.ino)===this.rootInode&&String(root.dev)===this.rootDevice&&journal.isDirectory()&&!journal.isSymbolicLink()&&String(journal.ino)===this.journalInode&&String(journal.dev)===this.journalDevice&&String(journal.uid)===String(this.ownerUid)&&(journal.mode&0o077n)===0n}catch{return false}}}
|
package/dist/types/filesystem.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function localDisk(root,options){return{driver:"local",root,visibility:"private",...options}}export function s3Disk(bucket,options){return{driver:"s3",bucket,region:process.env.AWS_DEFAULT_REGION||"us-east-1",visibility:"private",...options}}export function filebaseDisk(bucket,options){return{driver:"s3",bucket,region:"us-east-1",endpoint:"https://s3.filebase.com",visibility:"private",...options}}export function backblazeDisk(bucket,region,options){return{driver:"s3",bucket,region,endpoint:`https://s3.${region}.backblazeb2.com`,visibility:"private",...options}}export function r2Disk(bucket,accountId,options){return{driver:"s3",bucket,region:"auto",endpoint:`https://${accountId}.r2.cloudflarestorage.com`,visibility:"private",...options}}export function gcsDisk(bucket,options){return{driver:"s3",bucket,region:"auto",endpoint:"https://storage.googleapis.com",visibility:"private",...options}}export function hetznerDisk(bucket,location="fsn1",options){return{driver:"s3",bucket,region:location,endpoint:`https://${location}.your-objectstorage.com`,usePathStyleEndpoint
|
|
1
|
+
export function localDisk(root,options){return{driver:"local",root,visibility:"private",...options}}export function s3Disk(bucket,options){return{driver:"s3",bucket,region:process.env.AWS_DEFAULT_REGION||"us-east-1",visibility:"private",...options}}export function filebaseDisk(bucket,options){return{driver:"s3",bucket,region:"us-east-1",endpoint:"https://s3.filebase.com",visibility:"private",...options}}export function backblazeDisk(bucket,region,options){return{driver:"s3",bucket,region,endpoint:`https://s3.${region}.backblazeb2.com`,visibility:"private",...options}}export function r2Disk(bucket,accountId,options){return{driver:"s3",bucket,region:"auto",endpoint:`https://${accountId}.r2.cloudflarestorage.com`,visibility:"private",...options}}export function gcsDisk(bucket,options){return{driver:"s3",bucket,region:"auto",endpoint:"https://storage.googleapis.com",visibility:"private",...options}}export function hetznerDisk(bucket,location="fsn1",options){return{driver:"s3",bucket,region:location,endpoint:`https://${location}.your-objectstorage.com`,usePathStyleEndpoint:true,visibility:"private",...options}}export function azureDisk(container,account,options){return{driver:"azure",account,container,accountKey:process.env.AZURE_STORAGE_ACCOUNT_KEY,visibility:"private",...options}}export function configFromEnv(base={}){const env=process.env;return{default:env.FILESYSTEM_DISK||base.default||"local",disks:{...base.disks,...env.AWS_ACCESS_KEY_ID&&env.AWS_BUCKET?{s3:{driver:"s3",bucket:env.AWS_BUCKET,region:env.AWS_DEFAULT_REGION||"us-east-1",endpoint:env.AWS_ENDPOINT,url:env.AWS_URL,usePathStyleEndpoint:env.AWS_USE_PATH_STYLE_ENDPOINT==="true",credentials:{key:env.AWS_ACCESS_KEY_ID,secret:env.AWS_SECRET_ACCESS_KEY||""}}}:{}}}}
|
package/dist/types.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export var Visibility;((Visibility)=>{Visibility
|
|
1
|
+
export var Visibility;((Visibility)=>{Visibility["PUBLIC"]="public";Visibility["PRIVATE"]="private"})(Visibility||={});export async function*createDirectoryListing(entries){for(const entry of entries){yield entry}}export function normalizeExpiryToMilliseconds(expiry){if(expiry instanceof Date){return expiry.getTime()-Date.now()}return expiry*1000}export function normalizeExpiryToDate(expiry){if(expiry instanceof Date){return expiry}return new Date(Date.now()+expiry*1000)}export function isFile(entry){return entry.type==="file"}export function isDirectory(entry){return entry.type==="directory"}
|
package/dist/uploaded-file.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{basename,extname,join}from"node:path";export class UploadedFile{_file;_hashName=null;constructor(file){this._file=file}get name(){return this._file.name}get extension(){return extname(this._file.name).slice(1).toLowerCase()}get mimeType(){return this._file.type}get size(){return this._file.size}get file(){return this._file}hashName(extension){if(!this._hashName){const hash=crypto.randomUUID().replace(/-/g,"").slice(0,32)
|
|
1
|
+
import{basename,extname,join}from"node:path";export class UploadedFile{_file;_hashName=null;constructor(file){this._file=file}get name(){return this._file.name}get extension(){return extname(this._file.name).slice(1).toLowerCase()}get mimeType(){return this._file.type}get size(){return this._file.size}get file(){return this._file}hashName(extension){if(!this._hashName){const hash=crypto.randomUUID().replace(/-/g,"").slice(0,32);const ext=extension||this.extension;this._hashName=ext?`${hash}.${ext}`:hash}return this._hashName}async arrayBuffer(){return this._file.arrayBuffer()}async bytes(){const buffer=await this._file.arrayBuffer();return new Uint8Array(buffer)}async text(){return this._file.text()}isValid(){return this._file.size>0}async store(path="",disk="local"){const filename=this.hashName();const fullPath=path?join(path,filename):filename;const contents=await this.bytes();const{Storage}=await import("./facade");await Storage.disk(disk).write(fullPath,contents);return fullPath}async storeAs(path,name,disk="local"){if(name.includes("..")||name.includes("/")||name.includes("\\")){throw new Error("Invalid filename: path traversal or directory separator detected")}const sanitizedName=basename(name);const fullPath=path?join(path,sanitizedName):sanitizedName;const contents=await this.bytes();const{Storage}=await import("./facade");await Storage.disk(disk).write(fullPath,contents);return fullPath}async storePublicly(path=""){return this.store(path,"public")}async storePubliclyAs(path,name){return this.storeAs(path,name,"public")}async move(path,disk="local"){const contents=await this.bytes();const{Storage}=await import("./facade");await Storage.disk(disk).write(path,contents);return path}getClientOriginalName(){return basename(this._file.name,extname(this._file.name))}getClientOriginalExtension(){return this.extension}getClientMimeType(){return this._file.type}getSize(){const bytes=this._file.size;if(bytes<1024)return`${bytes} B`;if(bytes<1048576)return`${(bytes/1024).toFixed(2)} KB`;if(bytes<1073741824)return`${(bytes/1048576).toFixed(2)} MB`;return`${(bytes/1073741824).toFixed(2)} GB`}isOneOf(mimeTypes){return mimeTypes.some((type)=>{if(type.endsWith("/*")){const category=type.slice(0,-2);return this._file.type.startsWith(`${category}/`)}return this._file.type===type})}isImage(){return this._file.type.startsWith("image/")}isVideo(){return this._file.type.startsWith("video/")}isAudio(){return this._file.type.startsWith("audio/")}isPdf(){return this._file.type==="application/pdf"}}export function uploadedFile(file){return new UploadedFile(file)}export function uploadedFiles(files){return files.map((f)=>new UploadedFile(f))}
|
package/dist/zip.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{runCommand}from"@stacksjs/cli";export async function zip(from,to,options){const toPath=to||"archive.zip"
|
|
1
|
+
import{runCommand}from"@stacksjs/cli";export async function zip(from,to,options){const toPath=to||"archive.zip";const sources=Array.isArray(from)?from:[from];return runCommand(["zip","-r",toPath,...sources],options)}export async function unzip(paths,options){const[first,...rest]=Array.isArray(paths)?paths:[paths];if(first===undefined)throw new Error("unzip() needs at least one archive");let result=await runCommand(["unzip","-o",first],options);for(const source of rest){if(result.isErr)break;result=await runCommand(["unzip","-o",source],options)}return result}export function archive(paths,to,options){return zip(paths,to,options)}export function unarchive(paths,options){return unzip(paths,options)}export function compress(paths,to,options){return zip(paths,to,options)}export function decompress(paths,options){return unzip(paths,options)}export function gzipSync(data,options){return Bun.gzipSync(data,options)}export function gunzipSync(data){return Bun.gunzipSync(data)}export function deflateSync(data,options){return Bun.deflateSync(data,options)}export function inflateSync(data){return Bun.inflateSync(data)}const ZIP32_LIMIT=4294967295;const zipText=new TextEncoder;function dosDateTime(at){if(Number.isNaN(at.getTime()))throw new Error("zipEntries(): an entry has an invalid date");if(at.getFullYear()<1980)return{date:1<<5|1,time:0};if(at.getFullYear()>2107)return{date:127<<9|12<<5|31,time:23<<11|59<<5|29};return{date:at.getFullYear()-1980<<9|at.getMonth()+1<<5|at.getDate(),time:at.getHours()<<11|at.getMinutes()<<5|at.getSeconds()>>1}}function zipEntryName(name){const path=String(name??"").replace(/\\/g,"/");if(!path||path.startsWith("/")||/^[a-z]:/i.test(path)||path.includes("\x00")||path.split("/").some((part)=>part===""||part==="."||part===".."))throw new Error(`zipEntries(): "${name}" is not a safe file name inside a ZIP (relative, forward slashes, no empty, "." or ".." parts)`);return path}export function zipEntries(entries,options={}){if(entries.length>65535)throw new Error(`zipEntries(): ${entries.length} entries is more than the 65,535 a ZIP without ZIP64 holds`);const level=options.level??6;if(!Number.isInteger(level)||level<0||level>9)throw new Error(`zipEntries(): level must be an integer from 0 to 9, got ${level}`);const tooBig=(what)=>new Error(`zipEntries(): ${what} is past the 4 GB a ZIP without ZIP64 holds`);const fallbackDate=options.date??new Date;const seen=new Set;const parts=[];const centrals=[];let offset=0;for(const entry of entries){const path=zipEntryName(entry.name);if(seen.has(path))throw new Error(`zipEntries(): two entries are named "${path}"`);seen.add(path);const name=zipText.encode(path);if(name.length>65535)throw new Error(`zipEntries(): the name "${path.slice(0,40)}..." is longer than 65,535 bytes`);const raw=typeof entry.data==="string"?zipText.encode(entry.data):entry.data;if(raw.length>=ZIP32_LIMIT)throw tooBig(`"${path}" (${raw.length} bytes)`);if(offset>=ZIP32_LIMIT)throw tooBig(`the archive before "${path}"`);const crc=Bun.hash.crc32(raw)>>>0;const deflated=level>0&&raw.length>0?deflateSync(raw,{level}):undefined;const method=deflated&&deflated.length<raw.length?8:0;const data=method===8?deflated:raw;const{date,time}=dosDateTime(entry.date??fallbackDate);const local=new Uint8Array(30+name.length);const head=new DataView(local.buffer);head.setUint32(0,67324752,true);head.setUint16(4,20,true);head.setUint16(6,2048,true);head.setUint16(8,method,true);head.setUint16(10,time,true);head.setUint16(12,date,true);head.setUint32(14,crc,true);head.setUint32(18,data.length,true);head.setUint32(22,raw.length,true);head.setUint16(26,name.length,true);head.setUint16(28,0,true);local.set(name,30);const central=new Uint8Array(46+name.length);const dir=new DataView(central.buffer);dir.setUint32(0,33639248,true);dir.setUint16(4,788,true);dir.setUint16(6,20,true);dir.setUint16(8,2048,true);dir.setUint16(10,method,true);dir.setUint16(12,time,true);dir.setUint16(14,date,true);dir.setUint32(16,crc,true);dir.setUint32(20,data.length,true);dir.setUint32(24,raw.length,true);dir.setUint16(28,name.length,true);dir.setUint32(38,33188<<16>>>0,true);dir.setUint32(42,offset,true);central.set(name,46);parts.push(local,data);centrals.push(central);offset+=local.length+data.length}const directorySize=centrals.reduce((total,part)=>total+part.length,0);if(offset>=ZIP32_LIMIT||offset+directorySize+22>ZIP32_LIMIT)throw tooBig("the archive");const end=new Uint8Array(22);const tail=new DataView(end.buffer);tail.setUint32(0,101010256,true);tail.setUint16(8,entries.length,true);tail.setUint16(10,entries.length,true);tail.setUint32(12,directorySize,true);tail.setUint32(16,offset,true);const out=new Uint8Array(offset+directorySize+end.length);let at=0;for(const part of[...parts,...centrals,end]){out.set(part,at);at+=part.length}return out}
|
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.
|
|
5
|
+
"version": "0.75.519",
|
|
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.
|
|
65
|
-
"@stacksjs/cli": "0.75.
|
|
66
|
-
"@stacksjs/config": "0.75.
|
|
67
|
-
"@stacksjs/env": "0.75.
|
|
68
|
-
"@stacksjs/error-handling": "0.75.
|
|
69
|
-
"@stacksjs/logging": "0.75.
|
|
70
|
-
"@stacksjs/path": "0.75.
|
|
71
|
-
"@stacksjs/strings": "0.75.
|
|
64
|
+
"@stacksjs/arrays": "0.75.519",
|
|
65
|
+
"@stacksjs/cli": "0.75.519",
|
|
66
|
+
"@stacksjs/config": "0.75.519",
|
|
67
|
+
"@stacksjs/env": "0.75.519",
|
|
68
|
+
"@stacksjs/error-handling": "0.75.519",
|
|
69
|
+
"@stacksjs/logging": "0.75.519",
|
|
70
|
+
"@stacksjs/path": "0.75.519",
|
|
71
|
+
"@stacksjs/strings": "0.75.519",
|
|
72
72
|
"@stacksjs/ts-cloud": "^0.16.109",
|
|
73
73
|
"@stacksjs/ts-xml": "^0.1.0",
|
|
74
74
|
"ts-images": "^0.2.33"
|
|
75
75
|
},
|
|
76
76
|
"devDependencies": {
|
|
77
|
-
"@stacksjs/types": "0.75.
|
|
77
|
+
"@stacksjs/types": "0.75.519",
|
|
78
78
|
"better-dx": "^0.2.24"
|
|
79
79
|
}
|
|
80
80
|
}
|