@shipstatic/ship 0.7.7 → 0.7.9
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/browser.d.ts +10 -9
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +19 -19
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -9
- package/dist/index.d.ts +11 -9
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.d.cts
CHANGED
|
@@ -560,15 +560,16 @@ declare function getENV(): ExecutionEnvironment;
|
|
|
560
560
|
declare function formatFileSize(bytes: number, decimals?: number): string;
|
|
561
561
|
/**
|
|
562
562
|
* Validate filename for deployment safety
|
|
563
|
-
* Rejects filenames that would cause issues in URLs, filesystems, or shells
|
|
564
563
|
*
|
|
565
|
-
*
|
|
566
|
-
* -
|
|
567
|
-
* - Path
|
|
568
|
-
* -
|
|
569
|
-
* - Control characters
|
|
570
|
-
*
|
|
571
|
-
* -
|
|
564
|
+
* Blocks only characters that genuinely break the upload→serve round-trip:
|
|
565
|
+
* - # ? % URL round-trip breakers (fragment, query, encoding ambiguity)
|
|
566
|
+
* - \ Path separator confusion (buildFileKey splits on backslash)
|
|
567
|
+
* - < > " XSS vectors with zero legitimate use in filenames
|
|
568
|
+
* - \x00-\x1f \x7f Control characters (header injection, display corruption)
|
|
569
|
+
*
|
|
570
|
+
* Everything else is allowed — browser percent-encodes, Worker decodes, R2 matches.
|
|
571
|
+
*
|
|
572
|
+
* Additional checks: path traversal, reserved names, leading/trailing dots or spaces.
|
|
572
573
|
*/
|
|
573
574
|
declare function validateFileName(filename: string): {
|
|
574
575
|
valid: boolean;
|
|
@@ -677,7 +678,8 @@ declare function getCurrentConfig(): ConfigResponse;
|
|
|
677
678
|
|
|
678
679
|
/**
|
|
679
680
|
* Processes Node.js file and directory paths into an array of StaticFile objects ready for deploy.
|
|
680
|
-
*
|
|
681
|
+
* Computes content paths relative to the upload root before filtering, so only the deployed
|
|
682
|
+
* directory structure is evaluated — not the user's filesystem above it.
|
|
681
683
|
*
|
|
682
684
|
* @param paths - File or directory paths to scan and process.
|
|
683
685
|
* @param options - Processing options (pathDetect, etc.).
|
package/dist/index.d.ts
CHANGED
|
@@ -560,15 +560,16 @@ declare function getENV(): ExecutionEnvironment;
|
|
|
560
560
|
declare function formatFileSize(bytes: number, decimals?: number): string;
|
|
561
561
|
/**
|
|
562
562
|
* Validate filename for deployment safety
|
|
563
|
-
* Rejects filenames that would cause issues in URLs, filesystems, or shells
|
|
564
563
|
*
|
|
565
|
-
*
|
|
566
|
-
* -
|
|
567
|
-
* - Path
|
|
568
|
-
* -
|
|
569
|
-
* - Control characters
|
|
570
|
-
*
|
|
571
|
-
* -
|
|
564
|
+
* Blocks only characters that genuinely break the upload→serve round-trip:
|
|
565
|
+
* - # ? % URL round-trip breakers (fragment, query, encoding ambiguity)
|
|
566
|
+
* - \ Path separator confusion (buildFileKey splits on backslash)
|
|
567
|
+
* - < > " XSS vectors with zero legitimate use in filenames
|
|
568
|
+
* - \x00-\x1f \x7f Control characters (header injection, display corruption)
|
|
569
|
+
*
|
|
570
|
+
* Everything else is allowed — browser percent-encodes, Worker decodes, R2 matches.
|
|
571
|
+
*
|
|
572
|
+
* Additional checks: path traversal, reserved names, leading/trailing dots or spaces.
|
|
572
573
|
*/
|
|
573
574
|
declare function validateFileName(filename: string): {
|
|
574
575
|
valid: boolean;
|
|
@@ -677,7 +678,8 @@ declare function getCurrentConfig(): ConfigResponse;
|
|
|
677
678
|
|
|
678
679
|
/**
|
|
679
680
|
* Processes Node.js file and directory paths into an array of StaticFile objects ready for deploy.
|
|
680
|
-
*
|
|
681
|
+
* Computes content paths relative to the upload root before filtering, so only the deployed
|
|
682
|
+
* directory structure is evaluated — not the user's filesystem above it.
|
|
681
683
|
*
|
|
682
684
|
* @param paths - File or directory paths to scan and process.
|
|
683
685
|
* @param options - Processing options (pathDetect, etc.).
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var be=Object.defineProperty;var C=(n,t)=>()=>(n&&(t=n(n=0)),t);var Pe=(n,t)=>{for(var e in t)be(n,e,{get:t[e],enumerable:!0})};function R(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function N(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return Fe.has(e)}function $(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>V.has(e))}function Je(n){if(!n.startsWith(T))throw a.validation(`API key must start with "${T}"`);if(n.length!==pe)throw a.validation(`API key must be ${pe} characters total (${T} + ${z} hex chars)`);let t=n.slice(T.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`API key must contain ${z} hexadecimal characters after "${T}" prefix`)}function Xe(n){if(!n.startsWith(x))throw a.validation(`Deploy token must start with "${x}"`);if(n.length!==ce)throw a.validation(`Deploy token must be ${ce} characters total (${x} + ${j} hex chars)`);let t=n.slice(x.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`Deploy token must contain ${j} hexadecimal characters after "${x}" prefix`)}function Qe(n){try{let t=new URL(n);if(!["http:","https:"].includes(t.protocol))throw a.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw a.validation("API URL must not contain a path");if(t.search||t.hash)throw a.validation("API URL must not contain query parameters or fragments")}catch(t){throw R(t)?t:a.validation("API URL must be a valid URL")}}function Ze(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(n)}function ue(n,t){return n.endsWith(`.${t}`)}function et(n,t){return!ue(n,t)}function tt(n,t){return ue(n,t)?n.slice(0,-(t.length+1)):null}function nt(n,t){return`https://${n}.${t||"shipstatic.com"}`}function it(n){return`https://${n}`}function rt(n){return!n||n.length===0?null:JSON.stringify(n)}function at(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}var Ve,Ge,qe,f,H,a,Fe,V,T,z,pe,Ye,x,j,ce,We,G,L,g,ot,st,D=C(()=>{"use strict";Ve={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Ge={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},qe={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"};(function(n){n.Validation="validation_failed",n.NotFound="not_found",n.RateLimit="rate_limit_exceeded",n.Authentication="authentication_failed",n.Business="business_logic_error",n.Api="internal_server_error",n.Network="network_error",n.Cancelled="operation_cancelled",n.File="file_error",n.Config="config_error"})(f||(f={}));H={client:new Set([f.Business,f.Config,f.File,f.Validation]),network:new Set([f.Network]),auth:new Set([f.Authentication])},a=class n extends Error{type;status;details;constructor(t,e,i,o){super(e),this.type=t,this.status=i,this.details=o,this.name="ShipError"}toResponse(){let t=this.type===f.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:t}}static fromResponse(t){return new n(t.error,t.message,t.status,t.details)}static validation(t,e){return new n(f.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(f.NotFound,i,404)}static rateLimit(t="Too many requests"){return new n(f.RateLimit,t,429)}static authentication(t="Authentication required",e){return new n(f.Authentication,t,401,e)}static business(t,e=400){return new n(f.Business,t,e)}static network(t,e){return new n(f.Network,t,void 0,{cause:e})}static cancelled(t){return new n(f.Cancelled,t)}static file(t,e){return new n(f.File,t,void 0,{filePath:e})}static config(t,e){return new n(f.Config,t,void 0,e)}static api(t,e=500){return new n(f.Api,t,e)}static database(t,e=500){return new n(f.Api,t,e)}static storage(t,e=500){return new n(f.Api,t,e)}get filePath(){return this.details?.filePath}isClientError(){return H.client.has(this.type)}isNetworkError(){return H.network.has(this.type)}isAuthError(){return H.auth.has(this.type)}isValidationError(){return this.type===f.Validation}isFileError(){return this.type===f.File}isConfigError(){return this.type===f.Config}isType(t){return this.type===t}};Fe=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);V=new Set(["node_modules","package.json"]);T="ship-",z=64,pe=T.length+z,Ye=4,x="token-",j=64,ce=x.length+j,We={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},G="ship.json";L="https://api.shipstatic.com",g={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};ot={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},st=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function Y(n){q=n}function F(){if(q===null)throw a.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return q}var q,O=C(()=>{"use strict";D();q=null});function gt(n){J=n}function ke(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function w(){return J||ke()}var J,b=C(()=>{"use strict";J=null});async function Ne(n){let t=(await import("spark-md5")).default;return new Promise((e,i)=>{let s=Math.ceil(n.size/2097152),l=0,p=new t.ArrayBuffer,r=new FileReader,u=()=>{let c=l*2097152,d=Math.min(c+2097152,n.size);r.readAsArrayBuffer(n.slice(c,d))};r.onload=c=>{let d=c.target?.result;if(!d){i(a.business("Failed to read file chunk"));return}p.append(d),l++,l<s?u():e({md5:p.end()})},r.onerror=()=>{i(a.business("Failed to calculate MD5: FileReader error"))},u()})}async function $e(n){let t=await import("crypto");if(Buffer.isBuffer(n)){let i=t.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let e=await import("fs");return new Promise((i,o)=>{let s=t.createHash("md5"),l=e.createReadStream(n);l.on("error",p=>o(a.business(`Failed to read file for MD5: ${p.message}`))),l.on("data",p=>s.update(p)),l.on("end",()=>i({md5:s.digest("hex")}))})}async function _(n){let t=w();if(t==="browser"){if(!(n instanceof Blob))throw a.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Ne(n)}if(t==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw a.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return $e(n)}throw a.business("Unknown or unsupported execution environment for MD5 calculation.")}var B=C(()=>{"use strict";b();D()});import{isJunk as Be}from"junk";function Ee(n){if(!n||n.length===0)return[];if(n.find(e=>e&&$(e)))throw a.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return n.filter(e=>{if(!e)return!1;let i=e.replace(/\\/g,"/").split("/").filter(Boolean);if(i.length===0)return!0;let o=i[i.length-1];if(Be(o))return!1;for(let l of i)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let s=i.slice(0,-1);for(let l of s)if(Me.some(p=>l.toLowerCase()===p.toLowerCase()))return!1;return!0})}var Me,Z=C(()=>{"use strict";D();Me=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ae(n){if(!n||n.length===0)return"";let t=n.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let e=t.map(s=>s.split("/").filter(Boolean)),i=[],o=Math.min(...e.map(s=>s.length));for(let s=0;s<o;s++){let l=e[0][s];if(e.every(p=>p[s]===l))i.push(l);else break}return i.join("/")}function K(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ee=C(()=>{"use strict"});function ve(n,t={}){if(t.flatten===!1)return n.map(i=>({path:K(i),name:te(i)}));let e=Ke(n);return n.map(i=>{let o=K(i);if(e){let s=e.endsWith("/")?e:`${e}/`;o.startsWith(s)&&(o=o.substring(s.length))}return o||(o=te(i)),{path:o,name:te(i)}})}function Ke(n){if(!n.length)return"";let e=n.map(s=>K(s)).map(s=>s.split("/")),i=[],o=Math.min(...e.map(s=>s.length));for(let s=0;s<o-1;s++){let l=e[0][s];if(e.every(p=>p[s]===l))i.push(l);else break}return i.join("/")}function te(n){return n.split(/[/\\]/).pop()||n}var ne=C(()=>{"use strict";ee()});function ie(n,t=1){if(n===0)return"0 Bytes";let e=1024,i=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,o)).toFixed(t))+" "+i[o]}function oe(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let e=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,i=n.split("/").pop()||n;return e.test(i)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function Wt(n,t){let e=[],i=[],o=[];if(n.length===0){let r={file:"(no files)",message:"At least one file must be provided"};return e.push(r),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let r of n)if($(r.name))return e.push({file:r.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(u=>({...u,status:g.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let r={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(r),{files:n.map(u=>({...u,status:g.VALIDATION_FAILED,statusMessage:r.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let r of n){let u=g.READY,c="Ready for upload",d=r.name?oe(r.name):{valid:!1,reason:"File name cannot be empty"};if(r.status===g.PROCESSING_ERROR)u=g.VALIDATION_FAILED,c=r.statusMessage||"File failed during processing",e.push({file:r.name,message:c});else if(r.size===0){u=g.EXCLUDED,c="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:r.name,message:c}),o.push({...r,status:u,statusMessage:c});continue}else r.size<0?(u=g.VALIDATION_FAILED,c="File size must be positive",e.push({file:r.name,message:c})):!r.name||r.name.trim().length===0?(u=g.VALIDATION_FAILED,c="File name cannot be empty",e.push({file:r.name||"(empty)",message:c})):r.name.includes("\0")?(u=g.VALIDATION_FAILED,c="File name contains invalid characters (null byte)",e.push({file:r.name,message:c})):d.valid?N(r.name)?(u=g.VALIDATION_FAILED,c=`File extension not allowed: "${r.name}"`,e.push({file:r.name,message:c})):r.size>t.maxFileSize?(u=g.VALIDATION_FAILED,c=`File size (${ie(r.size)}) exceeds limit of ${ie(t.maxFileSize)}`,e.push({file:r.name,message:c})):(s+=r.size,s>t.maxTotalSize&&(u=g.VALIDATION_FAILED,c=`Total size would exceed limit of ${ie(t.maxTotalSize)}`,e.push({file:r.name,message:c}))):(u=g.VALIDATION_FAILED,c=d.reason||"Invalid file name",e.push({file:r.name,message:c}));o.push({...r,status:u,statusMessage:c})}e.length>0&&(o=o.map(r=>r.status===g.EXCLUDED?r:{...r,status:g.VALIDATION_FAILED,statusMessage:r.status===g.VALIDATION_FAILED?r.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=e.length===0?o.filter(r=>r.status===g.READY):[],p=e.length===0;return{files:o,validFiles:l,errors:e,warnings:i,canDeploy:p}}function He(n){return n.filter(t=>t.status===g.READY)}function Jt(n){return He(n).length>0}var se=C(()=>{"use strict";D()});function Ce(n,t){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw a.business(`Security error: Unsafe file path "${n}" for file: ${t}`)}function we(n,t){let e=oe(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if(N(n))throw a.business(`File extension not allowed: "${t}"`)}var re=C(()=>{"use strict";D();se()});var xe={};Pe(xe,{processFilesForNode:()=>Te});import*as S from"fs";import*as E from"path";function Re(n,t=new Set){let e=[],i=S.realpathSync(n);if(t.has(i))return e;t.add(i);let o=S.readdirSync(n);for(let s of o){let l=E.join(n,s),p=S.statSync(l);if(p.isDirectory()){let r=Re(l,t);e.push(...r)}else p.isFile()&&e.push(l)}return e}async function Te(n,t={}){if(w()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let m of n){let y=E.resolve(m);try{if(S.statSync(y).isDirectory()){let A=S.readdirSync(y).find(v=>V.has(v));if(A)throw a.business(`"${A}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(A){if(R(A))throw A}}let e=n.flatMap(m=>{let y=E.resolve(m);try{return S.statSync(y).isDirectory()?Re(y):[y]}catch{throw a.file(`Path does not exist: ${m}`,m)}}),i=[...new Set(e)],o=Ee(i);if(o.length===0)return[];let s=n.map(m=>E.resolve(m)),l=Ae(s.map(m=>{try{return S.statSync(m).isDirectory()?m:E.dirname(m)}catch{return E.dirname(m)}})),p=o.map(m=>{if(l&&l.length>0){let y=E.relative(l,m);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return E.basename(m)}),r=ve(p,{flatten:t.pathDetect!==!1}),u=[],c=0,d=F();for(let m=0;m<o.length;m++){let y=o[m],A=r[m].path;try{Ce(A,y);let v=S.statSync(y);if(v.size===0)continue;if(we(A,y),v.size>d.maxFileSize)throw a.business(`File ${y} is too large. Maximum allowed size is ${d.maxFileSize/(1024*1024)}MB.`);if(c+=v.size,c>d.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${d.maxTotalSize/(1024*1024)}MB.`);let P=S.readFileSync(y),{md5:Ie}=await _(P);u.push({path:A,content:P,size:P.length,md5:Ie})}catch(v){if(R(v))throw v;let P=v instanceof Error?v.message:String(v);throw a.file(`Failed to read file "${y}": ${P}`,y)}}if(u.length>d.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return u}var ae=C(()=>{"use strict";b();B();Z();re();D();O();ne();ee()});D();var U=class{constructor(){this.handlers=new Map}on(t,e){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e)}off(t,e){let i=this.handlers.get(t);i&&(i.delete(e),i.size===0&&this.handlers.delete(t))}emit(t,...e){let i=this.handlers.get(t);if(!i)return;let o=Array.from(i);for(let s of o)try{s(...e)}catch(l){i.delete(s),t!=="error"&&setTimeout(()=>{l instanceof Error?this.emit("error",l,String(t)):this.emit("error",new Error(String(l)),String(t))},0)}}transfer(t){this.handlers.forEach((e,i)=>{e.forEach(o=>{t.on(i,o)})})}clear(){this.handlers.clear()}};var h={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Oe=3e4,I=class extends U{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||L,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Oe,this.createDeployBody=e.createDeployBody}setGlobalHeaders(e){this.globalHeaders=e}transferEventsTo(e){this.transfer(e)}async executeRequest(e,i,o){let s=this.mergeHeaders(i.headers),{signal:l,cleanup:p}=this.createTimeoutSignal(i.signal),r={...i,headers:s,credentials:s.Authorization?void 0:"include",signal:l};this.emit("request",e,r);try{let u=await fetch(e,r);return p(),u.ok||await this.handleResponseError(u,o),this.emit("response",this.safeClone(u),e),{data:await this.parseResponse(this.safeClone(u)),status:u.status}}catch(u){p();let c=u instanceof Error?u:new Error(String(u));this.emit("error",c,e),this.handleFetchError(u,o)}}async request(e,i,o){let{data:s}=await this.executeRequest(e,i,o);return s}async requestWithStatus(e,i,o){return this.executeRequest(e,i,o)}mergeHeaders(e={}){return{...this.globalHeaders,...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let i=new AbortController,o=setTimeout(()=>i.abort(),this.timeout);if(e){let s=()=>i.abort();e.addEventListener("abort",s),e.aborted&&i.abort()}return{signal:i.signal,cleanup:()=>clearTimeout(o)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,i){let o={};try{if(e.headers.get("content-type")?.includes("application/json")){let p=await e.json();if(p&&typeof p=="object"){let r=p;typeof r.message=="string"&&(o.message=r.message),typeof r.error=="string"&&(o.error=r.error)}}else o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}let s=o.message||o.error||`${i} failed`;throw e.status===401?a.authentication(s):a.api(s,e.status)}handleFetchError(e,i){throw R(e)?e:e instanceof Error&&e.name==="AbortError"?a.cancelled(`${i} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?a.network(`${i} failed: ${e.message}`,e):e instanceof Error?a.business(`${i} failed: ${e.message}`):a.business(`${i} failed: Unknown error`)}async deploy(e,i={}){if(!e.length)throw a.business("No files to deploy");for(let p of e)if(!p.md5)throw a.file(`MD5 checksum missing for file: ${p.path}`,p.path);let{body:o,headers:s}=await this.createDeployBody(e,i.labels,i.via),l={};return i.deployToken?l.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(l.Authorization=`Bearer ${i.apiKey}`),i.caller&&(l["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${h.DEPLOYMENTS}`,{method:"POST",body:o,headers:{...s,...l},signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:i})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,o){let s={};i&&(s.deployment=i),o!==void 0&&(s.labels=o);let{data:l,status:p}=await this.requestWithStatus(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Set domain");return{...l,isCreate:p===201}}async listDomains(){return this.request(`${this.apiUrl}${h.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,i){let o={};return e!==void 0&&(o.ttl=e),i!==void 0&&(o.labels=i),this.request(`${this.apiUrl}${h.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${h.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${h.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${h.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${h.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${h.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e){let i=e.find(p=>p.path==="index.html"||p.path==="/index.html");if(!i||i.size>100*1024)return!1;let o;if(typeof Buffer<"u"&&Buffer.isBuffer(i.content))o=i.content.toString("utf-8");else if(typeof Blob<"u"&&i.content instanceof Blob)o=await i.content.text();else if(typeof File<"u"&&i.content instanceof File)o=await i.content.text();else return!1;let s={files:e.map(p=>p.path),index:o};return(await this.request(`${this.apiUrl}${h.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA check")).isSPA}};D();O();D();D();function W(n={},t={}){let e={apiUrl:n.apiUrl||t.apiUrl||L,apiKey:n.apiKey!==void 0?n.apiKey:t.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:t.deployToken},i={apiUrl:e.apiUrl};return e.apiKey!==void 0&&(i.apiKey=e.apiKey),e.deployToken!==void 0&&(i.deployToken=e.deployToken),i}function de(n,t){let e={...n};return e.apiUrl===void 0&&t.apiUrl!==void 0&&(e.apiUrl=t.apiUrl),e.apiKey===void 0&&t.apiKey!==void 0&&(e.apiKey=t.apiKey),e.deployToken===void 0&&t.deployToken!==void 0&&(e.deployToken=t.deployToken),e.timeout===void 0&&t.timeout!==void 0&&(e.timeout=t.timeout),e.maxConcurrency===void 0&&t.maxConcurrency!==void 0&&(e.maxConcurrency=t.maxConcurrency),e.onProgress===void 0&&t.onProgress!==void 0&&(e.onProgress=t.onProgress),e.caller===void 0&&t.caller!==void 0&&(e.caller=t.caller),e}D();B();async function Le(){let t=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),e;typeof Buffer<"u"?e=Buffer.from(t,"utf-8"):e=new Blob([t],{type:"application/json"});let{md5:i}=await _(e);return{path:G,content:e,size:t.length,md5:i}}async function fe(n,t,e){if(e.spaDetect===!1||n.some(i=>i.path===G))return n;try{if(await t.checkSPA(n)){let o=await Le();return[...n,o]}}catch{}return n}function me(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:o,hasAuth:s}=n;return{upload:async(l,p={})=>{await e();let r=o?de(p,o):p;if(s&&!s()&&!r.deployToken&&!r.apiKey)throw a.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!i)throw a.config("processInput function is not provided.");let u=t(),c=await i(l,r);return c=await fe(c,u,r),u.deploy(c,r)},list:async()=>(await e(),t().listDeployments()),get:async l=>(await e(),t().getDeployment(l)),set:async(l,p)=>(await e(),t().updateDeploymentLabels(l,p.labels)),remove:async l=>{await e(),await t().removeDeployment(l)}}}function he(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,o={})=>(await e(),t().setDomain(i,o.deployment,o.labels)),list:async()=>(await e(),t().listDomains()),get:async i=>(await e(),t().getDomain(i)),remove:async i=>{await e(),await t().removeDomain(i)},verify:async i=>(await e(),t().verifyDomain(i)),validate:async i=>(await e(),t().validateDomain(i)),dns:async i=>(await e(),t().getDomainDns(i)),records:async i=>(await e(),t().getDomainRecords(i)),share:async i=>(await e(),t().getDomainShare(i))}}function ye(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function ge(n){let{getApi:t,ensureInit:e}=n;return{create:async(i={})=>(await e(),t().createToken(i.ttl,i.labels)),list:async()=>(await e(),t().listTokens()),remove:async i=>{await e(),await t().removeToken(i)}}}var M=class{constructor(t={}){this.initPromise=null;this._config=null;this.auth=null;this.customHeaders={};this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let e=this.resolveInitialConfig(t);this.http=new I({...t,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=me({...i,processInput:(o,s)=>this.processInput(o,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=he(i),this._account=ye(i),this._tokens=ge(i)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,e){return this.deployments.upload(t,e)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=F(),this._config)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.customHeaders=t,this.http.setGlobalHeaders(t)}clearHeaders(){this.customHeaders={},this.http.setGlobalHeaders({})}replaceHttpClient(t){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(t)}catch(e){console.warn("Event transfer failed during client replacement:",e)}this.http=t,Object.keys(this.customHeaders).length>0&&this.http.setGlobalHeaders(this.customHeaders)}setDeployToken(t){if(!t||typeof t!="string")throw a.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:t}}setApiKey(t){if(!t||typeof t!="string")throw a.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:t}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};D();b();D();b();import{z as k}from"zod";var X="ship",Ue=k.object({apiUrl:k.string().url().optional(),apiKey:k.string().optional(),deployToken:k.string().optional()}).strict();function De(n){try{return Ue.parse(n)}catch(t){if(t instanceof k.ZodError){let e=t.issues[0],i=e.path.length>0?` at ${e.path.join(".")}`:"";throw a.config(`Configuration validation failed${i}: ${e.message}`)}throw a.config("Configuration validation failed")}}async function _e(n){try{if(w()!=="node")return{};let{cosmiconfigSync:t}=await import("cosmiconfig"),e=await import("os"),i=t(X,{searchPlaces:[`.${X}rc`,"package.json",`${e.homedir()}/.${X}rc`],stopDir:e.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return De(o.config)}catch(t){if(R(t))throw t}return{}}async function Q(n){if(w()!=="node")return{};let t={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},e=await _e(n),i={apiUrl:t.apiUrl??e.apiUrl,apiKey:t.apiKey??e.apiKey,deployToken:t.deployToken??e.deployToken};return De(i)}O();D();async function Se(n,t,e){let{FormData:i,File:o}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),l=new i,p=[];for(let d of n){if(!Buffer.isBuffer(d.content)&&!(typeof Blob<"u"&&d.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${d.path}`,d.path);if(!d.md5)throw a.file(`File missing md5 checksum: ${d.path}`,d.path);let m=new o([d.content],d.path,{type:"application/octet-stream"});l.append("files[]",m),p.push(d.md5)}l.append("checksums",JSON.stringify(p)),t&&t.length>0&&l.append("labels",JSON.stringify(t)),e&&l.append("via",e);let r=new s(l),u=[];for await(let d of r.encode())u.push(Buffer.from(d));let c=Buffer.concat(u);return{body:c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength),headers:{"Content-Type":r.contentType,"Content-Length":Buffer.byteLength(c).toString()}}}B();function Mt(n,t,e,i=!0){let o=n===1?t:e;return i?`${n} ${o}`:o}Z();ne();b();se();re();D();O();ae();var le=class extends M{constructor(t={}){if(w()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");super(t)}resolveInitialConfig(t){return W(t,{})}async loadFullConfig(){try{let t=await Q(this.clientOptions.configFile),e=W(this.clientOptions,t);e.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(e.deployToken):e.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(e.apiKey);let i=new I({...this.clientOptions,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();Y(o)}catch(t){throw this.initPromise=null,t}}async processInput(t,e){let i=typeof t=="string"?[t]:t;if(!Array.isArray(i)||!i.every(s=>typeof s=="string"))throw a.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw a.business("No files to deploy.");let{processFilesForNode:o}=await Promise.resolve().then(()=>(ae(),xe));return o(i,e)}getDeployBodyCreator(){return Se}},ze=le;export{z as API_KEY_HEX_LENGTH,Ye as API_KEY_HINT_LENGTH,T as API_KEY_PREFIX,pe as API_KEY_TOTAL_LENGTH,qe as AccountPlan,I as ApiHttp,We as AuthMethod,Fe as BLOCKED_EXTENSIONS,L as DEFAULT_API,G as DEPLOYMENT_CONFIG_FILENAME,j as DEPLOY_TOKEN_HEX_LENGTH,x as DEPLOY_TOKEN_PREFIX,ce as DEPLOY_TOKEN_TOTAL_LENGTH,Ve as DeploymentStatus,Ge as DomainStatus,f as ErrorType,g as FILE_VALIDATION_STATUS,g as FileValidationStatus,Me as JUNK_DIRECTORIES,ot as LABEL_CONSTRAINTS,st as LABEL_PATTERN,le as Ship,a as ShipError,V as UNBUILT_PROJECT_MARKERS,gt as __setTestEnvironment,Jt as allValidFilesReady,_ as calculateMD5,ye as createAccountResource,me as createDeploymentResource,he as createDomainResource,ge as createTokenResource,ze as default,at as deserializeLabels,tt as extractSubdomain,Ee as filterJunk,ie as formatFileSize,nt as generateDeploymentUrl,it as generateDomainUrl,F as getCurrentConfig,w as getENV,He as getValidFiles,$ as hasUnbuiltMarker,N as isBlockedExtension,et as isCustomDomain,Ze as isDeployment,ue as isPlatformDomain,R as isShipError,Q as loadConfig,de as mergeDeployOptions,ve as optimizeDeployPaths,Mt as pluralize,Te as processFilesForNode,W as resolveConfig,rt as serializeLabels,Y as setPlatformConfig,Je as validateApiKey,Qe as validateApiUrl,we as validateDeployFile,Ce as validateDeployPath,Xe as validateDeployToken,oe as validateFileName,Wt as validateFiles};
|
|
1
|
+
var Oe=Object.defineProperty;var C=(n,t)=>()=>(n&&(t=n(n=0)),t);var ke=(n,t)=>{for(var e in t)Oe(n,e,{get:t[e],enumerable:!0})};function x(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function L(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return Ne.has(e)}function fe(n){return $e.test(n)}function U(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>q.has(e))}function et(n){if(!n.startsWith(T))throw a.validation(`API key must start with "${T}"`);if(n.length!==ue)throw a.validation(`API key must be ${ue} characters total (${T} + ${V} hex chars)`);let t=n.slice(T.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`API key must contain ${V} hexadecimal characters after "${T}" prefix`)}function tt(n){if(!n.startsWith(I))throw a.validation(`Deploy token must start with "${I}"`);if(n.length!==de)throw a.validation(`Deploy token must be ${de} characters total (${I} + ${G} hex chars)`);let t=n.slice(I.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`Deploy token must contain ${G} hexadecimal characters after "${I}" prefix`)}function nt(n){try{let t=new URL(n);if(!["http:","https:"].includes(t.protocol))throw a.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw a.validation("API URL must not contain a path");if(t.search||t.hash)throw a.validation("API URL must not contain query parameters or fragments")}catch(t){throw x(t)?t:a.validation("API URL must be a valid URL")}}function it(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(n)}function me(n,t){return n.endsWith(`.${t}`)}function ot(n,t){return!me(n,t)}function st(n,t){return me(n,t)?n.slice(0,-(t.length+1)):null}function rt(n,t){return`https://${n}.${t||"shipstatic.com"}`}function at(n){return`https://${n}`}function ct(n){return!n||n.length===0?null:JSON.stringify(n)}function ut(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}var We,Je,Xe,f,j,a,Ne,$e,q,T,V,ue,Qe,I,G,de,Ze,Y,_,g,lt,pt,D=C(()=>{"use strict";We={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Je={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Xe={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"};(function(n){n.Validation="validation_failed",n.NotFound="not_found",n.RateLimit="rate_limit_exceeded",n.Authentication="authentication_failed",n.Business="business_logic_error",n.Api="internal_server_error",n.Network="network_error",n.Cancelled="operation_cancelled",n.File="file_error",n.Config="config_error"})(f||(f={}));j={client:new Set([f.Business,f.Config,f.File,f.Validation]),network:new Set([f.Network]),auth:new Set([f.Authentication])},a=class n extends Error{type;status;details;constructor(t,e,i,o){super(e),this.type=t,this.status=i,this.details=o,this.name="ShipError"}toResponse(){let t=this.type===f.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:t}}static fromResponse(t){return new n(t.error,t.message,t.status,t.details)}static validation(t,e){return new n(f.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(f.NotFound,i,404)}static rateLimit(t="Too many requests"){return new n(f.RateLimit,t,429)}static authentication(t="Authentication required",e){return new n(f.Authentication,t,401,e)}static business(t,e=400){return new n(f.Business,t,e)}static network(t,e){return new n(f.Network,t,void 0,{cause:e})}static cancelled(t){return new n(f.Cancelled,t)}static file(t,e){return new n(f.File,t,void 0,{filePath:e})}static config(t,e){return new n(f.Config,t,void 0,e)}static api(t,e=500){return new n(f.Api,t,e)}static database(t,e=500){return new n(f.Api,t,e)}static storage(t,e=500){return new n(f.Api,t,e)}get filePath(){return this.details?.filePath}isClientError(){return j.client.has(this.type)}isNetworkError(){return j.network.has(this.type)}isAuthError(){return j.auth.has(this.type)}isValidationError(){return this.type===f.Validation}isFileError(){return this.type===f.File}isConfigError(){return this.type===f.Config}isType(t){return this.type===t}};Ne=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);$e=/[\x00-\x1f\x7f#?%\\<>"]/;q=new Set(["node_modules","package.json"]);T="ship-",V=64,ue=T.length+V,Qe=4,I="token-",G=64,de=I.length+G,Ze={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},Y="ship.json";_="https://api.shipstatic.com",g={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};lt={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},pt=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function J(n){W=n}function O(){if(W===null)throw a.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return W}var W,k=C(()=>{"use strict";D();W=null});function At(n){Q=n}function Ue(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function w(){return Q||Ue()}var Q,P=C(()=>{"use strict";Q=null});async function _e(n){let t=(await import("spark-md5")).default;return new Promise((e,i)=>{let s=Math.ceil(n.size/2097152),l=0,p=new t.ArrayBuffer,r=new FileReader,u=()=>{let c=l*2097152,m=Math.min(c+2097152,n.size);r.readAsArrayBuffer(n.slice(c,m))};r.onload=c=>{let m=c.target?.result;if(!m){i(a.business("Failed to read file chunk"));return}p.append(m),l++,l<s?u():e({md5:p.end()})},r.onerror=()=>{i(a.business("Failed to calculate MD5: FileReader error"))},u()})}async function Be(n){let t=await import("crypto");if(Buffer.isBuffer(n)){let i=t.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let e=await import("fs");return new Promise((i,o)=>{let s=t.createHash("md5"),l=e.createReadStream(n);l.on("error",p=>o(a.business(`Failed to read file for MD5: ${p.message}`))),l.on("data",p=>s.update(p)),l.on("end",()=>i({md5:s.digest("hex")}))})}async function M(n){let t=w();if(t==="browser"){if(!(n instanceof Blob))throw a.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return _e(n)}if(t==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw a.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Be(n)}throw a.business("Unknown or unsupported execution environment for MD5 calculation.")}var K=C(()=>{"use strict";P();D()});import{isJunk as ze}from"junk";function Ce(n){if(!n||n.length===0)return[];if(n.find(e=>e&&U(e)))throw a.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return n.filter(e=>{if(!e)return!1;let i=e.replace(/\\/g,"/").split("/").filter(Boolean);if(i.length===0)return!0;let o=i[i.length-1];if(ze(o))return!1;for(let l of i)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let s=i.slice(0,-1);for(let l of s)if(je.some(p=>l.toLowerCase()===p.toLowerCase()))return!1;return!0})}var je,te=C(()=>{"use strict";D();je=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function we(n){if(!n||n.length===0)return"";let t=n.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let e=t.map(s=>s.split("/").filter(Boolean)),i=[],o=Math.min(...e.map(s=>s.length));for(let s=0;s<o;s++){let l=e[0][s];if(e.every(p=>p[s]===l))i.push(l);else break}return i.join("/")}function z(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ne=C(()=>{"use strict"});function xe(n,t={}){if(t.flatten===!1)return n.map(i=>({path:z(i),name:ie(i)}));let e=Ve(n);return n.map(i=>{let o=z(i);if(e){let s=e.endsWith("/")?e:`${e}/`;o.startsWith(s)&&(o=o.substring(s.length))}return o||(o=ie(i)),{path:o,name:ie(i)}})}function Ve(n){if(!n.length)return"";let e=n.map(s=>z(s)).map(s=>s.split("/")),i=[],o=Math.min(...e.map(s=>s.length));for(let s=0;s<o-1;s++){let l=e[0][s];if(e.every(p=>p[s]===l))i.push(l);else break}return i.join("/")}function ie(n){return n.split(/[/\\]/).pop()||n}var oe=C(()=>{"use strict";ne()});function se(n,t=1){if(n===0)return"0 Bytes";let e=1024,i=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,o)).toFixed(t))+" "+i[o]}function re(n){if(fe(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,e=n.split("/").pop()||n;return t.test(e)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function Zt(n,t){let e=[],i=[],o=[];if(n.length===0){let r={file:"(no files)",message:"At least one file must be provided"};return e.push(r),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let r of n)if(U(r.name))return e.push({file:r.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(u=>({...u,status:g.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let r={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(r),{files:n.map(u=>({...u,status:g.VALIDATION_FAILED,statusMessage:r.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let r of n){let u=g.READY,c="Ready for upload",m=r.name?re(r.name):{valid:!1,reason:"File name cannot be empty"};if(r.status===g.PROCESSING_ERROR)u=g.VALIDATION_FAILED,c=r.statusMessage||"File failed during processing",e.push({file:r.name,message:c});else if(r.size===0){u=g.EXCLUDED,c="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:r.name,message:c}),o.push({...r,status:u,statusMessage:c});continue}else r.size<0?(u=g.VALIDATION_FAILED,c="File size must be positive",e.push({file:r.name,message:c})):!r.name||r.name.trim().length===0?(u=g.VALIDATION_FAILED,c="File name cannot be empty",e.push({file:r.name||"(empty)",message:c})):r.name.includes("\0")?(u=g.VALIDATION_FAILED,c="File name contains invalid characters (null byte)",e.push({file:r.name,message:c})):m.valid?L(r.name)?(u=g.VALIDATION_FAILED,c=`File extension not allowed: "${r.name}"`,e.push({file:r.name,message:c})):r.size>t.maxFileSize?(u=g.VALIDATION_FAILED,c=`File size (${se(r.size)}) exceeds limit of ${se(t.maxFileSize)}`,e.push({file:r.name,message:c})):(s+=r.size,s>t.maxTotalSize&&(u=g.VALIDATION_FAILED,c=`Total size would exceed limit of ${se(t.maxTotalSize)}`,e.push({file:r.name,message:c}))):(u=g.VALIDATION_FAILED,c=m.reason||"Invalid file name",e.push({file:r.name,message:c}));o.push({...r,status:u,statusMessage:c})}e.length>0&&(o=o.map(r=>r.status===g.EXCLUDED?r:{...r,status:g.VALIDATION_FAILED,statusMessage:r.status===g.VALIDATION_FAILED?r.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=e.length===0?o.filter(r=>r.status===g.READY):[],p=e.length===0;return{files:o,validFiles:l,errors:e,warnings:i,canDeploy:p}}function Ge(n){return n.filter(t=>t.status===g.READY)}function en(n){return Ge(n).length>0}var ae=C(()=>{"use strict";D()});function Re(n,t){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw a.business(`Security error: Unsafe file path "${n}" for file: ${t}`)}function Te(n,t){let e=re(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if(L(n))throw a.business(`File extension not allowed: "${t}"`)}var le=C(()=>{"use strict";D();ae()});var Pe={};ke(Pe,{processFilesForNode:()=>be});import*as S from"fs";import*as E from"path";function Ie(n,t=new Set){let e=[],i=S.realpathSync(n);if(t.has(i))return e;t.add(i);let o=S.readdirSync(n);for(let s of o){let l=E.join(n,s),p=S.statSync(l);if(p.isDirectory()){let r=Ie(l,t);e.push(...r)}else p.isFile()&&e.push(l)}return e}async function be(n,t={}){if(w()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let d of n){let y=E.resolve(d);try{if(S.statSync(y).isDirectory()){let A=S.readdirSync(y).find(v=>q.has(v));if(A)throw a.business(`"${A}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(A){if(x(A))throw A}}let e=n.flatMap(d=>{let y=E.resolve(d);try{return S.statSync(y).isDirectory()?Ie(y):[y]}catch{throw a.file(`Path does not exist: ${d}`,d)}}),i=[...new Set(e)],o=n.map(d=>E.resolve(d)),s=we(o.map(d=>{try{return S.statSync(d).isDirectory()?d:E.dirname(d)}catch{return E.dirname(d)}})),l=i.map(d=>{if(s&&s.length>0){let y=E.relative(s,d);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return E.basename(d)}),p=new Set(Ce(l));if(p.size===0)return[];let r=[],u=[];for(let d=0;d<i.length;d++)p.has(l[d])&&(r.push(i[d]),u.push(l[d]));let c=xe(u,{flatten:t.pathDetect!==!1}),m=[],$=0,R=O();for(let d=0;d<r.length;d++){let y=r[d],A=c[d].path;try{Re(A,y);let v=S.statSync(y);if(v.size===0)continue;if(Te(A,y),v.size>R.maxFileSize)throw a.business(`File ${y} is too large. Maximum allowed size is ${R.maxFileSize/(1024*1024)}MB.`);if($+=v.size,$>R.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${R.maxTotalSize/(1024*1024)}MB.`);let F=S.readFileSync(y),{md5:Fe}=await M(F);m.push({path:A,content:F,size:F.length,md5:Fe})}catch(v){if(x(v))throw v;let F=v instanceof Error?v.message:String(v);throw a.file(`Failed to read file "${y}": ${F}`,y)}}if(m.length>R.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${R.maxFilesCount} files.`);return m}var pe=C(()=>{"use strict";P();K();te();le();D();k();oe();ne()});D();var B=class{constructor(){this.handlers=new Map}on(t,e){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e)}off(t,e){let i=this.handlers.get(t);i&&(i.delete(e),i.size===0&&this.handlers.delete(t))}emit(t,...e){let i=this.handlers.get(t);if(!i)return;let o=Array.from(i);for(let s of o)try{s(...e)}catch(l){i.delete(s),t!=="error"&&setTimeout(()=>{l instanceof Error?this.emit("error",l,String(t)):this.emit("error",new Error(String(l)),String(t))},0)}}transfer(t){this.handlers.forEach((e,i)=>{e.forEach(o=>{t.on(i,o)})})}clear(){this.handlers.clear()}};var h={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Le=3e4,b=class extends B{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||_,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Le,this.createDeployBody=e.createDeployBody}setGlobalHeaders(e){this.globalHeaders=e}transferEventsTo(e){this.transfer(e)}async executeRequest(e,i,o){let s=this.mergeHeaders(i.headers),{signal:l,cleanup:p}=this.createTimeoutSignal(i.signal),r={...i,headers:s,credentials:s.Authorization?void 0:"include",signal:l};this.emit("request",e,r);try{let u=await fetch(e,r);return p(),u.ok||await this.handleResponseError(u,o),this.emit("response",this.safeClone(u),e),{data:await this.parseResponse(this.safeClone(u)),status:u.status}}catch(u){p();let c=u instanceof Error?u:new Error(String(u));this.emit("error",c,e),this.handleFetchError(u,o)}}async request(e,i,o){let{data:s}=await this.executeRequest(e,i,o);return s}async requestWithStatus(e,i,o){return this.executeRequest(e,i,o)}mergeHeaders(e={}){return{...this.globalHeaders,...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let i=new AbortController,o=setTimeout(()=>i.abort(),this.timeout);if(e){let s=()=>i.abort();e.addEventListener("abort",s),e.aborted&&i.abort()}return{signal:i.signal,cleanup:()=>clearTimeout(o)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,i){let o={};try{if(e.headers.get("content-type")?.includes("application/json")){let p=await e.json();if(p&&typeof p=="object"){let r=p;typeof r.message=="string"&&(o.message=r.message),typeof r.error=="string"&&(o.error=r.error)}}else o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}let s=o.message||o.error||`${i} failed`;throw e.status===401?a.authentication(s):a.api(s,e.status)}handleFetchError(e,i){throw x(e)?e:e instanceof Error&&e.name==="AbortError"?a.cancelled(`${i} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?a.network(`${i} failed: ${e.message}`,e):e instanceof Error?a.business(`${i} failed: ${e.message}`):a.business(`${i} failed: Unknown error`)}async deploy(e,i={}){if(!e.length)throw a.business("No files to deploy");for(let p of e)if(!p.md5)throw a.file(`MD5 checksum missing for file: ${p.path}`,p.path);let{body:o,headers:s}=await this.createDeployBody(e,i.labels,i.via),l={};return i.deployToken?l.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(l.Authorization=`Bearer ${i.apiKey}`),i.caller&&(l["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${h.DEPLOYMENTS}`,{method:"POST",body:o,headers:{...s,...l},signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:i})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,o){let s={};i&&(s.deployment=i),o!==void 0&&(s.labels=o);let{data:l,status:p}=await this.requestWithStatus(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Set domain");return{...l,isCreate:p===201}}async listDomains(){return this.request(`${this.apiUrl}${h.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,i){let o={};return e!==void 0&&(o.ttl=e),i!==void 0&&(o.labels=i),this.request(`${this.apiUrl}${h.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${h.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${h.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${h.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${h.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${h.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e){let i=e.find(p=>p.path==="index.html"||p.path==="/index.html");if(!i||i.size>100*1024)return!1;let o;if(typeof Buffer<"u"&&Buffer.isBuffer(i.content))o=i.content.toString("utf-8");else if(typeof Blob<"u"&&i.content instanceof Blob)o=await i.content.text();else if(typeof File<"u"&&i.content instanceof File)o=await i.content.text();else return!1;let s={files:e.map(p=>p.path),index:o};return(await this.request(`${this.apiUrl}${h.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA check")).isSPA}};D();k();D();D();function X(n={},t={}){let e={apiUrl:n.apiUrl||t.apiUrl||_,apiKey:n.apiKey!==void 0?n.apiKey:t.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:t.deployToken},i={apiUrl:e.apiUrl};return e.apiKey!==void 0&&(i.apiKey=e.apiKey),e.deployToken!==void 0&&(i.deployToken=e.deployToken),i}function he(n,t){let e={...n};return e.apiUrl===void 0&&t.apiUrl!==void 0&&(e.apiUrl=t.apiUrl),e.apiKey===void 0&&t.apiKey!==void 0&&(e.apiKey=t.apiKey),e.deployToken===void 0&&t.deployToken!==void 0&&(e.deployToken=t.deployToken),e.timeout===void 0&&t.timeout!==void 0&&(e.timeout=t.timeout),e.maxConcurrency===void 0&&t.maxConcurrency!==void 0&&(e.maxConcurrency=t.maxConcurrency),e.onProgress===void 0&&t.onProgress!==void 0&&(e.onProgress=t.onProgress),e.caller===void 0&&t.caller!==void 0&&(e.caller=t.caller),e}D();K();async function Me(){let t=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),e;typeof Buffer<"u"?e=Buffer.from(t,"utf-8"):e=new Blob([t],{type:"application/json"});let{md5:i}=await M(e);return{path:Y,content:e,size:t.length,md5:i}}async function ye(n,t,e){if(e.spaDetect===!1||n.some(i=>i.path===Y))return n;try{if(await t.checkSPA(n)){let o=await Me();return[...n,o]}}catch{}return n}function ge(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:o,hasAuth:s}=n;return{upload:async(l,p={})=>{await e();let r=o?he(p,o):p;if(s&&!s()&&!r.deployToken&&!r.apiKey)throw a.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!i)throw a.config("processInput function is not provided.");let u=t(),c=await i(l,r);return c=await ye(c,u,r),u.deploy(c,r)},list:async()=>(await e(),t().listDeployments()),get:async l=>(await e(),t().getDeployment(l)),set:async(l,p)=>(await e(),t().updateDeploymentLabels(l,p.labels)),remove:async l=>{await e(),await t().removeDeployment(l)}}}function De(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,o={})=>(await e(),t().setDomain(i,o.deployment,o.labels)),list:async()=>(await e(),t().listDomains()),get:async i=>(await e(),t().getDomain(i)),remove:async i=>{await e(),await t().removeDomain(i)},verify:async i=>(await e(),t().verifyDomain(i)),validate:async i=>(await e(),t().validateDomain(i)),dns:async i=>(await e(),t().getDomainDns(i)),records:async i=>(await e(),t().getDomainRecords(i)),share:async i=>(await e(),t().getDomainShare(i))}}function Se(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function Ee(n){let{getApi:t,ensureInit:e}=n;return{create:async(i={})=>(await e(),t().createToken(i.ttl,i.labels)),list:async()=>(await e(),t().listTokens()),remove:async i=>{await e(),await t().removeToken(i)}}}var H=class{constructor(t={}){this.initPromise=null;this._config=null;this.auth=null;this.customHeaders={};this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let e=this.resolveInitialConfig(t);this.http=new b({...t,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=ge({...i,processInput:(o,s)=>this.processInput(o,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=De(i),this._account=Se(i),this._tokens=Ee(i)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,e){return this.deployments.upload(t,e)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=O(),this._config)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.customHeaders=t,this.http.setGlobalHeaders(t)}clearHeaders(){this.customHeaders={},this.http.setGlobalHeaders({})}replaceHttpClient(t){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(t)}catch(e){console.warn("Event transfer failed during client replacement:",e)}this.http=t,Object.keys(this.customHeaders).length>0&&this.http.setGlobalHeaders(this.customHeaders)}setDeployToken(t){if(!t||typeof t!="string")throw a.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:t}}setApiKey(t){if(!t||typeof t!="string")throw a.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:t}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};D();P();D();P();import{z as N}from"zod";var Z="ship",Ke=N.object({apiUrl:N.string().url().optional(),apiKey:N.string().optional(),deployToken:N.string().optional()}).strict();function Ae(n){try{return Ke.parse(n)}catch(t){if(t instanceof N.ZodError){let e=t.issues[0],i=e.path.length>0?` at ${e.path.join(".")}`:"";throw a.config(`Configuration validation failed${i}: ${e.message}`)}throw a.config("Configuration validation failed")}}async function He(n){try{if(w()!=="node")return{};let{cosmiconfigSync:t}=await import("cosmiconfig"),e=await import("os"),i=t(Z,{searchPlaces:[`.${Z}rc`,"package.json",`${e.homedir()}/.${Z}rc`],stopDir:e.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return Ae(o.config)}catch(t){if(x(t))throw t}return{}}async function ee(n){if(w()!=="node")return{};let t={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},e=await He(n),i={apiUrl:t.apiUrl??e.apiUrl,apiKey:t.apiKey??e.apiKey,deployToken:t.deployToken??e.deployToken};return Ae(i)}k();D();async function ve(n,t,e){let{FormData:i,File:o}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),l=new i,p=[];for(let m of n){if(!Buffer.isBuffer(m.content)&&!(typeof Blob<"u"&&m.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${m.path}`,m.path);if(!m.md5)throw a.file(`File missing md5 checksum: ${m.path}`,m.path);let $=new o([m.content],m.path,{type:"application/octet-stream"});l.append("files[]",$),p.push(m.md5)}l.append("checksums",JSON.stringify(p)),t&&t.length>0&&l.append("labels",JSON.stringify(t)),e&&l.append("via",e);let r=new s(l),u=[];for await(let m of r.encode())u.push(Buffer.from(m));let c=Buffer.concat(u);return{body:c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength),headers:{"Content-Type":r.contentType,"Content-Length":Buffer.byteLength(c).toString()}}}K();function jt(n,t,e,i=!0){let o=n===1?t:e;return i?`${n} ${o}`:o}te();oe();P();ae();le();D();k();pe();var ce=class extends H{constructor(t={}){if(w()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");super(t)}resolveInitialConfig(t){return X(t,{})}async loadFullConfig(){try{let t=await ee(this.clientOptions.configFile),e=X(this.clientOptions,t);e.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(e.deployToken):e.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(e.apiKey);let i=new b({...this.clientOptions,...e,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();J(o)}catch(t){throw this.initPromise=null,t}}async processInput(t,e){let i=typeof t=="string"?[t]:t;if(!Array.isArray(i)||!i.every(s=>typeof s=="string"))throw a.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw a.business("No files to deploy.");let{processFilesForNode:o}=await Promise.resolve().then(()=>(pe(),Pe));return o(i,e)}getDeployBodyCreator(){return ve}},qe=ce;export{V as API_KEY_HEX_LENGTH,Qe as API_KEY_HINT_LENGTH,T as API_KEY_PREFIX,ue as API_KEY_TOTAL_LENGTH,Xe as AccountPlan,b as ApiHttp,Ze as AuthMethod,Ne as BLOCKED_EXTENSIONS,_ as DEFAULT_API,Y as DEPLOYMENT_CONFIG_FILENAME,G as DEPLOY_TOKEN_HEX_LENGTH,I as DEPLOY_TOKEN_PREFIX,de as DEPLOY_TOKEN_TOTAL_LENGTH,We as DeploymentStatus,Je as DomainStatus,f as ErrorType,g as FILE_VALIDATION_STATUS,g as FileValidationStatus,je as JUNK_DIRECTORIES,lt as LABEL_CONSTRAINTS,pt as LABEL_PATTERN,ce as Ship,a as ShipError,q as UNBUILT_PROJECT_MARKERS,$e as UNSAFE_FILENAME_CHARS,At as __setTestEnvironment,en as allValidFilesReady,M as calculateMD5,Se as createAccountResource,ge as createDeploymentResource,De as createDomainResource,Ee as createTokenResource,qe as default,ut as deserializeLabels,st as extractSubdomain,Ce as filterJunk,se as formatFileSize,rt as generateDeploymentUrl,at as generateDomainUrl,O as getCurrentConfig,w as getENV,Ge as getValidFiles,U as hasUnbuiltMarker,fe as hasUnsafeChars,L as isBlockedExtension,ot as isCustomDomain,it as isDeployment,me as isPlatformDomain,x as isShipError,ee as loadConfig,he as mergeDeployOptions,xe as optimizeDeployPaths,jt as pluralize,be as processFilesForNode,X as resolveConfig,ct as serializeLabels,J as setPlatformConfig,et as validateApiKey,nt as validateApiUrl,Te as validateDeployFile,Re as validateDeployPath,tt as validateDeployToken,re as validateFileName,Zt as validateFiles};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|