@stacksjs/browser 0.75.674 → 0.75.683
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/utils/uploads.d.ts +25 -0
- package/dist/utils/uploads.js +1 -1
- package/package.json +6 -6
package/dist/utils/uploads.d.ts
CHANGED
|
@@ -10,6 +10,21 @@ export declare function uploadResumeKey(file: Blob & { name?: string, lastModifi
|
|
|
10
10
|
export declare function uploadInParts(file: Blob, options: UploadInPartsOptions): Promise<UploadSession>;
|
|
11
11
|
/** Forgets a remembered session once the application has taken the upload, so the same file can be sent anew. */
|
|
12
12
|
export declare function forgetUpload(resumeKey: string, storage?: Pick<Storage, 'removeItem'> | null): void;
|
|
13
|
+
/**
|
|
14
|
+
* Sends a file to an action, the way that suits its size: a small one whole,
|
|
15
|
+
* in one multipart request; a large one in parts through the upload session
|
|
16
|
+
* routes (`uploadInParts`), then the action is posted the session's id in
|
|
17
|
+
* place of the file. The same file sent again carries on from the parts that
|
|
18
|
+
* arrived. Answers the action's response; a refusal while sending parts is
|
|
19
|
+
* answered as a response too, with the server's status and words, so a
|
|
20
|
+
* caller reads every outcome the same way. Only a cancel or a network failure
|
|
21
|
+
* that outlasts the retries throws.
|
|
22
|
+
*
|
|
23
|
+
* On the server, `receiveUpload` in `@stacksjs/storage` reads either.
|
|
24
|
+
*/
|
|
25
|
+
export declare function sendUpload(path: string, file: unknown, options?: SendUploadOptions): Promise<Response>;
|
|
26
|
+
/** A file up to this size goes in one request: sending it in parts would only add round trips. */
|
|
27
|
+
export declare const DEFAULT_SINGLE_REQUEST_BYTES: number;
|
|
13
28
|
/**
|
|
14
29
|
* Sends a file in parts to an application's upload-session routes
|
|
15
30
|
* (`createUploadSessions` in `@stacksjs/storage`), so a large upload survives
|
|
@@ -60,6 +75,16 @@ export declare interface UploadInPartsOptions {
|
|
|
60
75
|
storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> | null
|
|
61
76
|
retryDelay?: number
|
|
62
77
|
}
|
|
78
|
+
export declare interface SendUploadOptions extends Omit<UploadInPartsOptions, 'endpoint' | 'resumeKey' | 'storage'> {
|
|
79
|
+
endpoint?: string
|
|
80
|
+
field?: string
|
|
81
|
+
sessionField?: string
|
|
82
|
+
fields?: Record<string, string | Blob | undefined | null>
|
|
83
|
+
threshold?: number
|
|
84
|
+
storage?: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'> | null
|
|
85
|
+
purpose?: string
|
|
86
|
+
spent?: (status: number) => boolean
|
|
87
|
+
}
|
|
63
88
|
export type UploadTransport = (path: string, init: RequestInit & { onUploadProgress?: (progress: UploadProgress) => void }) => Promise<Response>;
|
|
64
89
|
/** A refusal the server gave that sending again would not change. */
|
|
65
90
|
export declare class UploadRefused extends Error {
|
package/dist/utils/uploads.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export class UploadRefused extends Error{status;body;constructor(message,status,body){super(message);this.status=status;this.body=body;this.name="UploadRefused"}}export function uploadResumeKey(file,purpose=""){return`upload:${purpose}:${file.name??""}:${file.size}:${file.lastModified??""}`}const defaultTransport=(path,init)=>fetch(path,{credentials:"include",...init});function storageOf(options){if(options.storage!==undefined)return options.storage;try{return typeof localStorage==="undefined"?null:localStorage}catch{return null}}const aborted=(signal)=>{if(signal?.aborted)throw signal.reason??new DOMException("The upload was cancelled.","AbortError")};const isAbort=(error)=>error?.name==="AbortError";function pause(ms,signal){return new Promise((resolve,reject)=>{const done=()=>{signal?.removeEventListener("abort",stop);resolve()};const timer=setTimeout(done,ms);const stop=()=>{clearTimeout(timer);reject(signal.reason??new DOMException("The upload was cancelled.","AbortError"))};signal?.addEventListener("abort",stop,{once:true})})}const transient=(status)=>status===408||status===425||status===429||status>=500;async function refusal(response,fallback){const body=await response.json().catch(()=>null);return new UploadRefused(typeof body?.error==="string"&&body.error?body.error:fallback,response.status,body)}function retryAfter(response){const seconds=Number(response.headers.get("retry-after"));return Number.isFinite(seconds)&&seconds>0?Math.min(seconds,60)*1000:0}export async function uploadInParts(file,options){const transport=options.transport??defaultTransport;const endpoint=options.endpoint.replace(/\/+$/,"");const retries=Math.max(0,options.retries??5);const delay=Math.max(1,options.retryDelay??500);const store=options.resumeKey?storageOf(options):null;const signal=options.signal;aborted(signal);async function attempt(send){let last;for(let tried=0;tried<=retries;tried++){aborted(signal);let wait=Math.min(15000,delay*2**tried);try{const response=await send();if(!transient(response.status))return response;last=await refusal(response,"The upload could not be sent. Try again.");wait=Math.max(wait,retryAfter(response))}catch(error){if(isAbort(error)||signal?.aborted)throw error;last=error}if(tried<retries)await pause(wait+Math.random()*wait*0.25,signal)}throw last}let session=null;const remembered=store?.getItem(options.resumeKey)||null;if(remembered&&/^[a-f0-9]{32}$/.test(remembered)){const response=await attempt(()=>transport(`${endpoint}/${remembered}`,{method:"GET",signal})).catch(()=>null);const found=response?.ok?await response.json().catch(()=>null):null;if(found?.upload?.id===remembered&&found.upload.size===file.size)session=found.upload;else store?.removeItem(options.resumeKey)}if(!session){const name=options.name??file.name??"upload";const response=await attempt(()=>transport(endpoint,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({name,size:file.size,type:file.type||"application/octet-stream",meta:options.meta??{}}),signal}));if(!response.ok)throw await refusal(response,"The upload could not be started.");session=(await response.json().catch(()=>null))?.upload??null;if(!session?.id||!(session.partBytes>0)||!(session.parts>0))throw new UploadRefused("The upload could not be started.",response.status,null);if(options.resumeKey)store?.setItem(options.resumeKey,session.id)}const{id,partBytes,parts}=session;const have=new Set(session.received);const sizeOf=(index)=>Math.min(partBytes,file.size-index*partBytes);const flying=new Map;let settled=0;for(const index of have)settled+=sizeOf(index);let reported=0;const report=()=>{let loaded=settled;for(const bytes of flying.values())loaded+=bytes;reported=Math.max(reported,Math.min(loaded,file.size));options.onProgress?.({loaded:reported,total:file.size})};report();const queue=[];for(let index=0;index<parts;index++){if(!have.has(index))queue.push(index)}async function sendPart(index){const body=file.slice(index*partBytes,index*partBytes+sizeOf(index));const response=await attempt(()=>{flying.set(index,0);return transport(`${endpoint}/${id}/parts/${index}`,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body,signal,...options.transportReportsProgress?{onUploadProgress:(progress)=>{flying.set(index,Math.min(progress.loaded,sizeOf(index)));report()}}:{}})}).catch((error)=>{flying.delete(index);throw error});flying.delete(index);if(!response.ok){if(response.status===404&&options.resumeKey)store?.removeItem(options.resumeKey);throw await refusal(response,"The upload could not be sent. Try again.")}settled+=sizeOf(index);report()}const workers=Array.from({length:Math.max(1,Math.min(options.concurrency??3,queue.length))},async()=>{for(let index=queue.shift();index!==undefined;index=queue.shift())await sendPart(index)});try{await Promise.all(workers)}catch(error){queue.length=0;await Promise.allSettled(workers);if(isAbort(error)||signal?.aborted){if(options.resumeKey)store?.removeItem(options.resumeKey);transport(`${endpoint}/${id}`,{method:"DELETE",keepalive:true}).catch(()=>{})}throw error}return{...session,received:Array.from({length:parts},(_,index)=>index),complete:false}}export function forgetUpload(resumeKey,storage){try{(storage??(typeof localStorage==="undefined"?null:localStorage))?.removeItem(resumeKey)}catch{}}
|
|
1
|
+
export class UploadRefused extends Error{status;body;constructor(message,status,body){super(message);this.status=status;this.body=body;this.name="UploadRefused"}}export function uploadResumeKey(file,purpose=""){return`upload:${purpose}:${file.name??""}:${file.size}:${file.lastModified??""}`}const defaultTransport=(path,init)=>fetch(path,{credentials:"include",...init});function storageOf(options){if(options.storage!==undefined)return options.storage;try{return typeof localStorage==="undefined"?null:localStorage}catch{return null}}const aborted=(signal)=>{if(signal?.aborted)throw signal.reason??new DOMException("The upload was cancelled.","AbortError")};const isAbort=(error)=>error?.name==="AbortError";function pause(ms,signal){return new Promise((resolve,reject)=>{const done=()=>{signal?.removeEventListener("abort",stop);resolve()};const timer=setTimeout(done,ms);const stop=()=>{clearTimeout(timer);reject(signal.reason??new DOMException("The upload was cancelled.","AbortError"))};signal?.addEventListener("abort",stop,{once:true})})}const transient=(status)=>status===408||status===425||status===429||status>=500;async function refusal(response,fallback){const body=await response.json().catch(()=>null);return new UploadRefused(typeof body?.error==="string"&&body.error?body.error:fallback,response.status,body)}function retryAfter(response){const seconds=Number(response.headers.get("retry-after"));return Number.isFinite(seconds)&&seconds>0?Math.min(seconds,60)*1000:0}export async function uploadInParts(file,options){const transport=options.transport??defaultTransport;const endpoint=options.endpoint.replace(/\/+$/,"");const retries=Math.max(0,options.retries??5);const delay=Math.max(1,options.retryDelay??500);const store=options.resumeKey?storageOf(options):null;const signal=options.signal;aborted(signal);async function attempt(send){let last;for(let tried=0;tried<=retries;tried++){aborted(signal);let wait=Math.min(15000,delay*2**tried);try{const response=await send();if(!transient(response.status))return response;last=await refusal(response,"The upload could not be sent. Try again.");wait=Math.max(wait,retryAfter(response))}catch(error){if(isAbort(error)||signal?.aborted)throw error;last=error}if(tried<retries)await pause(wait+Math.random()*wait*0.25,signal)}throw last}let session=null;const remembered=store?.getItem(options.resumeKey)||null;if(remembered&&/^[a-f0-9]{32}$/.test(remembered)){const response=await attempt(()=>transport(`${endpoint}/${remembered}`,{method:"GET",signal})).catch(()=>null);const found=response?.ok?await response.json().catch(()=>null):null;if(found?.upload?.id===remembered&&found.upload.size===file.size)session=found.upload;else store?.removeItem(options.resumeKey)}if(!session){const name=options.name??file.name??"upload";const response=await attempt(()=>transport(endpoint,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({name,size:file.size,type:file.type||"application/octet-stream",meta:options.meta??{}}),signal}));if(!response.ok)throw await refusal(response,"The upload could not be started.");session=(await response.json().catch(()=>null))?.upload??null;if(!session?.id||!(session.partBytes>0)||!(session.parts>0))throw new UploadRefused("The upload could not be started.",response.status,null);if(options.resumeKey)store?.setItem(options.resumeKey,session.id)}const{id,partBytes,parts}=session;const have=new Set(session.received);const sizeOf=(index)=>Math.min(partBytes,file.size-index*partBytes);const flying=new Map;let settled=0;for(const index of have)settled+=sizeOf(index);let reported=0;const report=()=>{let loaded=settled;for(const bytes of flying.values())loaded+=bytes;reported=Math.max(reported,Math.min(loaded,file.size));options.onProgress?.({loaded:reported,total:file.size})};report();const queue=[];for(let index=0;index<parts;index++){if(!have.has(index))queue.push(index)}async function sendPart(index){const body=file.slice(index*partBytes,index*partBytes+sizeOf(index));const response=await attempt(()=>{flying.set(index,0);return transport(`${endpoint}/${id}/parts/${index}`,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body,signal,...options.transportReportsProgress?{onUploadProgress:(progress)=>{flying.set(index,Math.min(progress.loaded,sizeOf(index)));report()}}:{}})}).catch((error)=>{flying.delete(index);throw error});flying.delete(index);if(!response.ok){if(response.status===404&&options.resumeKey)store?.removeItem(options.resumeKey);throw await refusal(response,"The upload could not be sent. Try again.")}settled+=sizeOf(index);report()}const workers=Array.from({length:Math.max(1,Math.min(options.concurrency??3,queue.length))},async()=>{for(let index=queue.shift();index!==undefined;index=queue.shift())await sendPart(index)});try{await Promise.all(workers)}catch(error){queue.length=0;await Promise.allSettled(workers);if(isAbort(error)||signal?.aborted){if(options.resumeKey)store?.removeItem(options.resumeKey);transport(`${endpoint}/${id}`,{method:"DELETE",keepalive:true}).catch(()=>{})}throw error}return{...session,received:Array.from({length:parts},(_,index)=>index),complete:false}}export function forgetUpload(resumeKey,storage){try{(storage??(typeof localStorage==="undefined"?null:localStorage))?.removeItem(resumeKey)}catch{}}export const DEFAULT_SINGLE_REQUEST_BYTES=8*1024*1024;const isBlob=(value)=>typeof Blob!=="undefined"&&value instanceof Blob;function appendField(body,name,value,fallbackName){if(!isBlob(value)){body.append(name,value);return}const given=value.name;if(typeof given==="string"&&given)body.append(name,value);else body.append(name,value,fallbackName)}export async function sendUpload(path,file,options={}){const transport=options.transport??defaultTransport;const field=options.field??"file";const fields=Object.entries(options.fields??{}).filter((entry)=>entry[1]!==undefined&&entry[1]!==null);const name=options.name??file?.name??"upload";const progress=options.onProgress;if(!isBlob(file)||file.size<=(options.threshold??DEFAULT_SINGLE_REQUEST_BYTES)){const body=new FormData;if(isBlob(file))appendField(body,field,file,name);else body.append(field,file);for(const[key,value]of fields)appendField(body,key,value,`${key}.bin`);return transport(path,{method:"POST",body,...options.signal?{signal:options.signal}:{},...progress?{onUploadProgress:progress}:{}})}const picked=file;const resumeKey=uploadResumeKey({name:picked.name??name,size:file.size,lastModified:picked.lastModified??0},options.purpose??path);let session;try{session=await uploadInParts(file,{...options,transport,endpoint:options.endpoint??"/uploads",name,resumeKey})}catch(cause){if(cause instanceof UploadRefused)return Response.json(cause.body&&typeof cause.body==="object"?cause.body:{error:cause.message},{status:cause.status});throw cause}const body=new FormData;body.append(options.sessionField??"upload",session.id);for(const[key,value]of fields)appendField(body,key,value,`${key}.bin`);const response=await transport(path,{method:"POST",body,...options.signal?{signal:options.signal}:{}});const spent=options.spent??((status)=>status<300||status===404||status===422);if(spent(response.status))forgetUpload(resumeKey,options.storage===undefined?undefined:options.storage);return response}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacksjs/browser",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.75.
|
|
4
|
+
"version": "0.75.683",
|
|
5
5
|
"description": "Stacks core frontend/browser functionalities.",
|
|
6
6
|
"author": "Chris Breuer",
|
|
7
7
|
"contributors": [
|
|
@@ -74,10 +74,10 @@
|
|
|
74
74
|
"prepublishOnly": "bun run build"
|
|
75
75
|
},
|
|
76
76
|
"dependencies": {
|
|
77
|
-
"@stacksjs/composables": "0.75.
|
|
78
|
-
"@stacksjs/datetime": "0.75.
|
|
79
|
-
"@stacksjs/strings": "0.75.
|
|
80
|
-
"@stacksjs/stx": "^0.2.
|
|
77
|
+
"@stacksjs/composables": "0.75.683",
|
|
78
|
+
"@stacksjs/datetime": "0.75.683",
|
|
79
|
+
"@stacksjs/strings": "0.75.683",
|
|
80
|
+
"@stacksjs/stx": "^0.2.934",
|
|
81
81
|
"bun-query-builder": "^0.6.4"
|
|
82
82
|
},
|
|
83
83
|
"peerDependencies": {
|
|
@@ -89,7 +89,7 @@
|
|
|
89
89
|
}
|
|
90
90
|
},
|
|
91
91
|
"devDependencies": {
|
|
92
|
-
"@stacksjs/utils": "0.75.
|
|
92
|
+
"@stacksjs/utils": "0.75.683",
|
|
93
93
|
"@stripe/stripe-js": "^10.0.0",
|
|
94
94
|
"better-dx": "^0.2.39"
|
|
95
95
|
}
|