@shipstatic/ship 0.9.3 → 0.9.5

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/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var He=Object.create;var z=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Ve=Object.prototype.hasOwnProperty;var I=(n,t)=>()=>(n&&(t=n(n=0)),t);var Re=(n,t)=>{for(var e in t)z(n,e,{get:t[e],enumerable:!0})},ve=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ke(t))!Ve.call(n,r)&&r!==e&&z(n,r,{get:()=>t[r],enumerable:!(i=ze(t,r))||i.enumerable});return n};var C=(n,t,e)=>(e=n!=null?He(Ge(n)):{},ve(t||!n||!n.__esModule?z(e,"default",{value:n,enumerable:!0}):e,n)),je=n=>ve(z({},"__esModule",{value:!0}),n);function L(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function $(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return xe.has(e)}function ee(n){return Ie.test(n)}function U(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>K.has(e))}function Qe(n){if(!n.startsWith(R.PREFIX))throw a.validation(`API key must start with "${R.PREFIX}"`);if(n.length!==R.TOTAL_LENGTH)throw a.validation(`API key must be ${R.TOTAL_LENGTH} characters total (${R.PREFIX} + ${R.HEX_LENGTH} hex chars)`);let t=n.slice(R.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`API key must contain ${R.HEX_LENGTH} hexadecimal characters after "${R.PREFIX}" prefix`)}function Ze(n){if(!n.startsWith(v.PREFIX))throw a.validation(`Deploy token must start with "${v.PREFIX}"`);if(n.length!==v.TOTAL_LENGTH)throw a.validation(`Deploy token must be ${v.TOTAL_LENGTH} characters total (${v.PREFIX} + ${v.HEX_LENGTH} hex chars)`);let t=n.slice(v.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`Deploy token must contain ${v.HEX_LENGTH} hexadecimal characters after "${v.PREFIX}" prefix`)}function et(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 L(t)?t:a.validation("API URL must be a valid URL")}}function tt(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function ne(n,t){return n.endsWith(`.${t}`)}function nt(n,t){return!ne(n,t)}function it(n,t){return ne(n,t)?n.slice(0,-(t.length+1)):null}function rt(n){return`https://${n}`}function st(n){return`https://${n}`}function ot(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 qe,Xe,Ye,d,Z,We,a,xe,Ie,K,R,v,Je,G,te,_,g,P,ie,F,E=I(()=>{"use strict";qe={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Xe={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Ye={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},d={Validation:"validation_failed",NotFound:"not_found",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},Z={client:new Set([d.Business,d.Config,d.File,d.Validation]),network:new Set([d.Network]),auth:new Set([d.Authentication])},We=new Set(Object.values(d).filter(n=>n!==d.Network&&n!==d.Cancelled)),a=class n extends Error{type;status;details;constructor(t,e,i,r){super(e),this.type=t,this.status=i,this.details=r,this.name="ShipError"}toResponse(){let t=this.type===d.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:t}}static async fromHttpResponse(t,e){let i,r,s;try{if(t.headers.get("content-type")?.includes("application/json")){let o=await t.json();if(o&&typeof o=="object"){let l=o;typeof l.message=="string"?i=l.message:typeof l.error=="string"&&(i=l.error),r=l.details,typeof l.error=="string"&&We.has(l.error)&&(s=l.error)}}else{let o=await t.text();o&&(i=o)}}catch{}i=i||e||`Request failed with status ${t.status}`;let p=s??(t.status===401?d.Authentication:t.status===429?d.RateLimit:d.Api);return new n(p,i,t.status,r)}static fromFetchError(t,e){if(L(t))return t;let i=e||"Request";return t instanceof Error?t.name==="AbortError"?n.cancelled(`${i} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?n.network(`${i} failed: ${t.message}`,t):new n(d.Api,`${i} failed: ${t.message}`):new n(d.Api,`${i} failed: Unknown error`)}static validation(t,e){return new n(d.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(d.NotFound,i,404)}static rateLimit(t="Too many requests"){return new n(d.RateLimit,t,429)}static authentication(t="Authentication required",e){return new n(d.Authentication,t,401,e)}static business(t,e=400){return new n(d.Business,t,e)}static network(t,e){return new n(d.Network,t,void 0,{cause:e})}static cancelled(t){return new n(d.Cancelled,t)}static file(t,e){return new n(d.File,t,void 0,{filePath:e})}static config(t,e){return new n(d.Config,t,void 0,e)}static api(t,e=500){return new n(d.Api,t,e)}get filePath(){return this.details?.filePath}isClientError(){return Z.client.has(this.type)}isNetworkError(){return Z.network.has(this.type)}isAuthError(){return Z.auth.has(this.type)}isValidationError(){return this.type===d.Validation}isFileError(){return this.type===d.File}isConfigError(){return this.type===d.Config}isType(t){return this.type===t}};xe=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"]);Ie=/[\x00-\x1f\x7f#?%\\<>"]/;K=new Set(["node_modules","package.json"]);R={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},v={PREFIX:"token-",HEX_LENGTH:64,TOTAL_LENGTH:70},Je={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},G="ship.json",te={rewrites:[{source:"/(.*)",destination:"/index.html"}]};_="https://api.shipstatic.com",g={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};P={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},ie=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;F={MIN_LENGTH:6,MAX_LENGTH:128}});function pt(n){oe=n}function ct(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function b(){return oe||ct()}var oe,O=I(()=>{"use strict";oe=null});async function ut(n){let t=(await import("spark-md5")).default;return new Promise((e,i)=>{let s=Math.ceil(n.size/2097152),p=0,c=new t.ArrayBuffer,o=new FileReader,l=()=>{let u=p*2097152,h=Math.min(u+2097152,n.size);o.readAsArrayBuffer(n.slice(u,h))};o.onload=u=>{let h=u.target?.result;if(!h){i(a.business("Failed to read file chunk"));return}c.append(h),p++,p<s?l():e({md5:c.end()})},o.onerror=()=>{i(a.business("Failed to calculate MD5: FileReader error"))},l()})}async function dt(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,r)=>{let s=t.createHash("md5"),p=e.createReadStream(n);p.on("error",c=>r(a.business(`Failed to read file for MD5: ${c.message}`))),p.on("data",c=>s.update(c)),p.on("end",()=>i({md5:s.digest("hex")}))})}async function H(n){let t=b();if(t==="browser"){if(!(n instanceof Blob))throw a.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return ut(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 dt(n)}throw a.business("Unknown or unsupported execution environment for MD5 calculation.")}var j=I(()=>{"use strict";O();E()});function de(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&U(i)))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 r=i[i.length-1];if((0,Fe.isJunk)(r))return!1;for(let p of i)if(p!==".well-known"&&(p.startsWith(".")||p.length>255))return!1;let s=i.slice(0,-1);for(let p of s)if(Oe.some(c=>p.toLowerCase()===c.toLowerCase()))return!1;return!0})}var Fe,Oe,me=I(()=>{"use strict";Fe=require("junk");E();Oe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function ke(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=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r;s++){let p=e[0][s];if(e.every(c=>c[s]===p))i.push(p);else break}return i.join("/")}function Y(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var fe=I(()=>{"use strict"});function ye(n,t={}){if(t.flatten===!1)return n.map(i=>({path:Y(i),name:he(i)}));let e=gt(n);return n.map(i=>{let r=Y(i);if(e){let s=e.endsWith("/")?e:`${e}/`;r.startsWith(s)&&(r=r.substring(s.length))}return r||(r=he(i)),{path:r,name:he(i)}})}function gt(n){if(!n.length)return"";let e=n.map(s=>Y(s)).map(s=>s.split("/")),i=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r-1;s++){let p=e[0][s];if(e.every(c=>c[s]===p))i.push(p);else break}return i.join("/")}function he(n){return n.split(/[/\\]/).pop()||n}var ge=I(()=>{"use strict";fe()});function W(n,t=1){if(n===0)return"0 Bytes";let e=1024,i=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,r)).toFixed(t))+" "+i[r]}function J(n){if(ee(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 Et(n,t){let e=[],i=[],r=[];if(n.length===0){let o={file:"(no files)",message:"At least one file must be provided"};return e.push(o),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let o of n)if(U(o.name))return e.push({file:o.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(l=>({...l,status:g.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let o={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(o),{files:n.map(l=>({...l,status:g.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let o of n){let l=g.READY,u="Ready for upload",h=o.name?J(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===g.PROCESSING_ERROR)l=g.VALIDATION_FAILED,u=o.statusMessage||"File failed during processing",e.push({file:o.name,message:u});else if(o.size===0){l=g.EXCLUDED,u="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:u}),r.push({...o,status:l,statusMessage:u});continue}else o.size<0?(l=g.VALIDATION_FAILED,u="File size must be positive",e.push({file:o.name,message:u})):!o.name||o.name.trim().length===0?(l=g.VALIDATION_FAILED,u="File name cannot be empty",e.push({file:o.name||"(empty)",message:u})):o.name.includes("\0")?(l=g.VALIDATION_FAILED,u="File name contains invalid characters (null byte)",e.push({file:o.name,message:u})):h.valid?$(o.name)?(l=g.VALIDATION_FAILED,u=`File extension not allowed: "${o.name}"`,e.push({file:o.name,message:u})):o.size>t.maxFileSize?(l=g.VALIDATION_FAILED,u=`File size (${W(o.size)}) exceeds limit of ${W(t.maxFileSize)}`,e.push({file:o.name,message:u})):(s+=o.size,s>t.maxTotalSize&&(l=g.VALIDATION_FAILED,u=`Total size would exceed limit of ${W(t.maxTotalSize)}`,e.push({file:o.name,message:u}))):(l=g.VALIDATION_FAILED,u=h.reason||"Invalid file name",e.push({file:o.name,message:u}));r.push({...o,status:l,statusMessage:u})}e.length>0&&(r=r.map(o=>o.status===g.EXCLUDED?o:{...o,status:g.VALIDATION_FAILED,statusMessage:o.status===g.VALIDATION_FAILED?o.statusMessage:"Deployment failed due to validation errors in bundle"}));let p=e.length===0?r.filter(o=>o.status===g.READY):[],c=e.length===0;return{files:r,validFiles:p,errors:e,warnings:i,canDeploy:c}}function $e(n){return n.filter(t=>t.status===g.READY)}function Dt(n){return $e(n).length>0}var Ee=I(()=>{"use strict";E()});function De(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 Se(n,t){let e=J(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if($(n))throw a.business(`File extension not allowed: "${t}"`)}var Te=I(()=>{"use strict";E();Ee()});var _e={};Re(_e,{processFilesForNode:()=>Ae});function Ue(n,t=new Set){let e=[],i=S.realpathSync(n);if(t.has(i))return e;t.add(i);let r=S.readdirSync(n);for(let s of r){let p=T.join(n,s),c=S.statSync(p);if(c.isDirectory()){let o=Ue(p,t);e.push(...o)}else c.isFile()&&e.push(p)}return e}async function Ae(n,t={},e){if(b()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let m of n){let y=T.resolve(m);try{if(S.statSync(y).isDirectory()){let A=S.readdirSync(y).find(w=>K.has(w));if(A)throw a.business(`"${A}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(A){if(L(A))throw A}}let i=n.flatMap(m=>{let y=T.resolve(m);try{return S.statSync(y).isDirectory()?Ue(y):[y]}catch{throw a.file(`Path does not exist: ${m}`,m)}}),r=[...new Set(i)],s=n.map(m=>T.resolve(m)),p=ke(s.map(m=>{try{return S.statSync(m).isDirectory()?m:T.dirname(m)}catch{return T.dirname(m)}})),c=r.map(m=>{if(p&&p.length>0){let y=T.relative(p,m);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return T.basename(m)}),l=ye(c,{flatten:t.pathDetect!==!1}).map(m=>m.path),u=new Set(de(l));if(u.size===0)return[];let h=[],N=[];for(let m=0;m<r.length;m++)u.has(l[m])&&(h.push(r[m]),N.push(l[m]));let x=[],D=0;if(!e)throw a.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let m=0;m<h.length;m++){let y=h[m],A=N[m];try{De(A,y);let w=S.statSync(y);if(w.size===0)continue;if(Se(A,y),w.size>e.maxFileSize)throw a.business(`File ${y} is too large. Maximum allowed size is ${e.maxFileSize/(1024*1024)}MB.`);if(D+=w.size,D>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let k=S.readFileSync(y),{md5:Be}=await H(k);x.push({path:A,content:k,size:k.length,md5:Be})}catch(w){if(L(w))throw w;let k=w instanceof Error?w.message:String(w);throw a.file(`Failed to read file "${y}": ${k}`,y)}}if(x.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return x}var S,T,we=I(()=>{"use strict";O();j();me();Te();E();ge();fe();S=C(require("fs"),1),T=C(require("path"),1)});var St={};Re(St,{API_KEY:()=>R,AccountPlan:()=>Ye,ApiHttp:()=>B,AuthMethod:()=>Je,BLOCKED_EXTENSIONS:()=>xe,DEFAULT_API:()=>_,DEPLOYMENT_CONFIG_FILENAME:()=>G,DEPLOY_TOKEN:()=>v,DeploymentStatus:()=>qe,DomainStatus:()=>Xe,ErrorType:()=>d,FILE_VALIDATION_STATUS:()=>g,FileValidationStatus:()=>g,JUNK_DIRECTORIES:()=>Oe,LABEL_CONSTRAINTS:()=>P,LABEL_PATTERN:()=>ie,PASSWORD_CONSTRAINTS:()=>F,SPA_DEFAULT_CONFIG:()=>te,Ship:()=>Q,ShipError:()=>a,UNBUILT_PROJECT_MARKERS:()=>K,UNSAFE_FILENAME_CHARS:()=>Ie,__setTestEnvironment:()=>pt,allValidFilesReady:()=>Dt,calculateMD5:()=>H,createAccountResource:()=>pe,createDeploymentResource:()=>ae,createDomainResource:()=>le,createTokenResource:()=>ce,default:()=>Me,deserializeLabels:()=>at,extractSubdomain:()=>it,filterJunk:()=>de,formatFileSize:()=>W,generateDeploymentUrl:()=>rt,generateDomainUrl:()=>st,getENV:()=>b,getValidFiles:()=>$e,hasUnbuiltMarker:()=>U,hasUnsafeChars:()=>ee,isBlockedExtension:()=>$,isCustomDomain:()=>nt,isDeployment:()=>tt,isPlatformDomain:()=>ne,isShipError:()=>L,mergeDeployOptions:()=>se,optimizeDeployPaths:()=>ye,pluralize:()=>yt,processFilesForNode:()=>Ae,resolveConfig:()=>re,serializeLabels:()=>ot,validateApiKey:()=>Qe,validateApiUrl:()=>et,validateDeployFile:()=>Se,validateDeployPath:()=>De,validateDeployToken:()=>Ze,validateFileName:()=>J,validateFiles:()=>Et});module.exports=je(St);E();E();var V=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 r=Array.from(i);for(let s of r)try{s(...e)}catch(p){i.delete(s),t!=="error"&&setTimeout(()=>{let c=p instanceof Error?p:new Error(String(p));this.emit("error",c,String(t))},0)}}};E();function Pe(n){if(n!=null){if(typeof n!="string")throw a.validation("Password must be a string");if(n.length<F.MIN_LENGTH||n.length>F.MAX_LENGTH)throw a.validation(`Password must be between ${F.MIN_LENGTH} and ${F.MAX_LENGTH} characters`)}}function M(n){if(n==null)return;if(n.length===0)return n;if(n.length>P.MAX_COUNT)throw a.validation(`Maximum ${P.MAX_COUNT} labels allowed`);let t=n.map((i,r)=>{if(typeof i!="string")throw a.validation(`Label at index ${r} must be a string`);let s=i.trim().toLowerCase();if(s.length<P.MIN_LENGTH)throw a.validation(`Labels must be at least ${P.MIN_LENGTH} characters long`);if(s.length>P.MAX_LENGTH)throw a.validation(`Labels must be no more than ${P.MAX_LENGTH} characters long`);if(!ie.test(s))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${P.SEPARATORS}) between segments`);return s}),e=[...new Set(t)];if(e.length!==t.length)throw a.validation("Duplicate labels are not allowed");return e}var f={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},lt=3e4,B=class extends V{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||_,this.getAuthHeadersCallback=e.getAuthHeaders,this.useCredentials=e.useCredentials??!1,this.timeout=e.timeout??lt,this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||f.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}async executeRequest(e,i,r){let s=this.mergeHeaders(i.headers),{signal:p,cleanup:c}=this.createTimeoutSignal(i.signal),o={...i,headers:s,credentials:this.useCredentials&&!s.Authorization?"include":void 0,signal:p};this.emit("request",e,o);try{let l=await fetch(e,o);if(c(),!l.ok)throw await a.fromHttpResponse(l,`${r} failed`);return this.emit("response",this.safeClone(l),e),{data:await this.parseResponse(this.safeClone(l)),status:l.status}}catch(l){c();let u=a.fromFetchError(l,r);throw this.emit("error",u,e),u}}async request(e,i,r){let{data:s}=await this.executeRequest(e,i,r);return s}async requestWithStatus(e,i,r){return this.executeRequest(e,i,r)}mergeHeaders(e={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...e}}createTimeoutSignal(e){let i=new AbortController,r=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(r)}}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 deploy(e,i={}){if(!e.length)throw a.business("No files to deploy");for(let l of e)if(!l.md5)throw a.file(`MD5 checksum missing for file: ${l.path}`,l.path);Pe(i.password);let r=M(i.labels),s=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:p,headers:c}=await this.createDeployBody(e,{labels:r,via:i.via,password:i.password,flags:s}),o={};return i.deployToken?o.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(o.Authorization=`Bearer ${i.apiKey}`),i.caller&&(o["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:p,headers:{...c,...o},signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){let r=M(i);return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:r})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,r){let s=M(r),p={};i&&(p.deployment=i),s!==void 0&&(p.labels=s);let{data:c,status:o}=await this.requestWithStatus(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)},"Set domain");return{...c,isCreate:o===201}}async listDomains(){return this.request(`${this.apiUrl}${f.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,i){let r=M(i),s={};return e!==void 0&&(s.ttl=e),r!==void 0&&(s.labels=r),this.request(`${this.apiUrl}${f.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${f.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${f.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async fetchAgentToken(){return this.request(`${this.apiUrl}${f.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent token")}async getAccount(){return this.request(`${this.apiUrl}${f.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${f.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return(await this.request(`${this.apiUrl}${f.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e,i={}){let r=e.find(l=>l.path==="index.html"||l.path==="/index.html");if(!r||r.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(r.content))s=r.content.toString("utf-8");else if(typeof Blob<"u"&&r.content instanceof Blob)s=await r.content.text();else if(typeof File<"u"&&r.content instanceof File)s=await r.content.text();else return!1;let p={"Content-Type":"application/json"};i.deployToken?p.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(p.Authorization=`Bearer ${i.apiKey}`);let c={files:e.map(l=>l.path),index:s};return(await this.request(`${this.apiUrl}${f.SPA_CHECK}`,{method:"POST",headers:p,body:JSON.stringify(c)},"SPA check")).isSPA}};E();function re(n={}){let t={apiUrl:n.apiUrl||_};return n.apiKey!==void 0&&(t.apiKey=n.apiKey),n.deployToken!==void 0&&(t.deployToken=n.deployToken),t}function se(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}E();E();j();async function mt(){let n=JSON.stringify(te,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await H(t);return{path:G,content:t,size:n.length,md5:e}}async function be(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===G))return n;try{if(await t.checkSPA(n,e)){let r=await mt();return[...n,r]}}catch{}return n}function ae(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:r,hasAuth:s}=n;return{upload:async(p,c={})=>{await e();let o=r?se(c,r):c;if(s&&!s()&&!o.deployToken&&!o.apiKey)try{let h=t(),{secret:N}=await h.fetchAgentToken();o.deployToken=N}catch(h){throw L(h)&&h.type===d.RateLimit?a.rateLimit("public deploy rate limit exceeded, try again later or run 'ship config' for a free account with higher limits"):h}if(!i)throw a.config("processInput function is not provided.");let l=t(),u=await i(p,o);return u=await be(u,l,o),l.deploy(u,o)},list:async()=>(await e(),t().listDeployments()),get:async p=>(await e(),t().getDeployment(p)),set:async(p,c)=>(await e(),t().updateDeploymentLabels(p,c.labels)),remove:async p=>{await e(),await t().removeDeployment(p)}}}function le(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,r={})=>(await e(),t().setDomain(i,r.deployment,r.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 pe(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function ce(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 q=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.auth=null;t={...t,apiUrl:t.apiUrl||void 0,apiKey:t.apiKey||void 0,deployToken:t.deployToken||void 0},this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.http=new B({...t,...re(t),getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=ae({...e,processInput:(i,r)=>this.processInput(i,r),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this.domains=le(e),this.account=pe(e),this.tokens=ce(e)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(t){throw this.initPromise=null,t}}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()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}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}};E();O();var ue=require("zod");E();O();var X=require("zod"),Le={apiUrl:X.z.string().url().optional(),apiKey:X.z.string().min(1).optional(),deployToken:X.z.string().min(1).optional()};var ft=ue.z.object(Le).strict(),ht={apiUrl:"SHIP_API_URL",apiKey:"SHIP_API_KEY",deployToken:"SHIP_DEPLOY_TOKEN"};function Ne(){if(b()!=="node")return{};let n={apiUrl:process.env.SHIP_API_URL||void 0,apiKey:process.env.SHIP_API_KEY||void 0,deployToken:process.env.SHIP_DEPLOY_TOKEN||void 0};try{return ft.parse(n)}catch(t){if(t instanceof ue.z.ZodError){let e=t.issues[0],i=e.path[0],r=(i&&ht[i])??"SHIP environment configuration";throw a.config(`Invalid ${r}: ${e.message}`)}throw a.config("Invalid environment configuration")}}E();async function Ce(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),{labels:s,via:p,password:c,flags:o}=t,l=new e,u=[];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 i([D.content],D.path,{type:"application/octet-stream"});l.append("files[]",m),u.push(D.md5)}l.append("checksums",JSON.stringify(u)),s&&s.length>0&&l.append("labels",JSON.stringify(s)),p&&l.append("via",p),c&&l.append("password",c),o?.build&&l.append("build","true"),o?.prerender&&l.append("prerender","true"),o?.spa&&l.append("spa","true");let h=new r(l),N=[];for await(let D of h.encode())N.push(Buffer.from(D));let x=Buffer.concat(N);return{body:x.buffer.slice(x.byteOffset,x.byteOffset+x.byteLength),headers:{"Content-Type":h.contentType,"Content-Length":Buffer.byteLength(x).toString()}}}j();function yt(n,t,e,i=!0){let r=n===1?t:e;return i?`${n} ${r}`:r}me();ge();O();Ee();Te();E();we();var Q=class extends q{constructor(t={}){if(b()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=Ne();super({...t,apiUrl:t.apiUrl||e.apiUrl,apiKey:t.apiKey||e.apiKey,deployToken:t.deployToken||e.deployToken})}async deploy(t,e){return super.deploy(t,e)}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:r}=await Promise.resolve().then(()=>(we(),_e));return r(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return Ce}},Me=Q;0&&(module.exports={API_KEY,AccountPlan,ApiHttp,AuthMethod,BLOCKED_EXTENSIONS,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_TOKEN,DeploymentStatus,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,PASSWORD_CONSTRAINTS,SPA_DEFAULT_CONFIG,Ship,ShipError,UNBUILT_PROJECT_MARKERS,UNSAFE_FILENAME_CHARS,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getENV,getValidFiles,hasUnbuiltMarker,hasUnsafeChars,isBlockedExtension,isCustomDomain,isDeployment,isPlatformDomain,isShipError,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,serializeLabels,validateApiKey,validateApiUrl,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles});
1
+ "use strict";var He=Object.create;var z=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var Ke=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Ve=Object.prototype.hasOwnProperty;var I=(n,t)=>()=>(n&&(t=n(n=0)),t);var Re=(n,t)=>{for(var e in t)z(n,e,{get:t[e],enumerable:!0})},ve=(n,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ke(t))!Ve.call(n,r)&&r!==e&&z(n,r,{get:()=>t[r],enumerable:!(i=ze(t,r))||i.enumerable});return n};var C=(n,t,e)=>(e=n!=null?He(Ge(n)):{},ve(t||!n||!n.__esModule?z(e,"default",{value:n,enumerable:!0}):e,n)),je=n=>ve(z({},"__esModule",{value:!0}),n);function L(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function $(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return xe.has(e)}function ee(n){return Ie.test(n)}function U(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>K.has(e))}function Ze(n){if(!n.startsWith(R.PREFIX))throw a.validation(`API key must start with "${R.PREFIX}"`);if(n.length!==R.TOTAL_LENGTH)throw a.validation(`API key must be ${R.TOTAL_LENGTH} characters total (${R.PREFIX} + ${R.HEX_LENGTH} hex chars)`);let t=n.slice(R.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`API key must contain ${R.HEX_LENGTH} hexadecimal characters after "${R.PREFIX}" prefix`)}function et(n){if(!n.startsWith(v.PREFIX))throw a.validation(`Deploy token must start with "${v.PREFIX}"`);if(n.length!==v.TOTAL_LENGTH)throw a.validation(`Deploy token must be ${v.TOTAL_LENGTH} characters total (${v.PREFIX} + ${v.HEX_LENGTH} hex chars)`);let t=n.slice(v.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`Deploy token must contain ${v.HEX_LENGTH} hexadecimal characters after "${v.PREFIX}" prefix`)}function tt(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 L(t)?t:a.validation("API URL must be a valid URL")}}function nt(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function ne(n,t){return n.endsWith(`.${t}`)}function it(n,t){return!ne(n,t)}function rt(n,t){return ne(n,t)?n.slice(0,-(t.length+1)):null}function st(n){return`https://${n}`}function ot(n){return`https://${n}`}function at(n){return!n||n.length===0?null:JSON.stringify(n)}function lt(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}var qe,Xe,Ye,d,We,Z,Je,a,xe,Ie,K,R,v,Qe,G,te,_,g,b,ie,F,E=I(()=>{"use strict";qe={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Xe={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Ye={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},d={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},We=new Set([d.Network,d.Cancelled,d.File,d.Config]),Z={client:new Set([d.Business,d.Config,d.File,d.Forbidden,d.Validation]),network:new Set([d.Network]),auth:new Set([d.Authentication])},Je=new Set(Object.values(d).filter(n=>!We.has(n))),a=class n extends Error{type;status;details;constructor(t,e,i,r){super(e),this.type=t,this.status=i,this.details=r,this.name="ShipError"}toResponse(){let t=this.details,e=this.type===d.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static async fromHttpResponse(t,e){let i,r,s;try{if(t.headers.get("content-type")?.includes("application/json")){let o=await t.json();if(o&&typeof o=="object"){let l=o;typeof l.message=="string"?i=l.message:typeof l.error=="string"&&(i=l.error),r=l.details,typeof l.error=="string"&&Je.has(l.error)&&(s=l.error)}}else{let o=await t.text();o&&(i=o)}}catch{}i=i||`${e||"Request"} failed with status ${t.status}`;let p=s??(t.status===401?d.Authentication:t.status===403?d.Forbidden:t.status===429?d.RateLimit:d.Api);return new n(p,i,t.status,r)}static fromFetchError(t,e){if(L(t))return t;let i=e||"Request";return t instanceof Error?t.name==="AbortError"?n.cancelled(`${i} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?n.network(`${i} failed: ${t.message}`,{cause:t}):new n(d.Api,`${i} failed: ${t.message}`):new n(d.Api,`${i} failed: Unknown error`)}static validation(t,e){return new n(d.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(d.NotFound,i,404)}static forbidden(t,e){return new n(d.Forbidden,t,403,e)}static rateLimit(t="Too many requests",e){return new n(d.RateLimit,t,429,e)}static authentication(t="Authentication required",e){return new n(d.Authentication,t,401,e)}static business(t,e=400,i){return new n(d.Business,t,e,i)}static network(t,e){return new n(d.Network,t,void 0,e)}static cancelled(t,e){return new n(d.Cancelled,t,void 0,e)}static file(t,e){return new n(d.File,t,void 0,e)}static config(t,e){return new n(d.Config,t,void 0,e)}static api(t,e=500,i){return new n(d.Api,t,e,i)}isClientError(){return Z.client.has(this.type)}isNetworkError(){return Z.network.has(this.type)}isAuthError(){return Z.auth.has(this.type)}isType(t){return this.type===t}};xe=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"]);Ie=/[\x00-\x1f\x7f#?%\\<>"]/;K=new Set(["node_modules","package.json"]);R={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},v={PREFIX:"token-",HEX_LENGTH:64,TOTAL_LENGTH:70},Qe={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},G="ship.json",te={rewrites:[{source:"/(.*)",destination:"/index.html"}]};_="https://api.shipstatic.com",g={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};b={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},ie=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;F={MIN_LENGTH:6,MAX_LENGTH:128}});function ct(n){oe=n}function ut(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function P(){return oe||ut()}var oe,O=I(()=>{"use strict";oe=null});async function dt(n){let t=(await import("spark-md5")).default;return new Promise((e,i)=>{let s=Math.ceil(n.size/2097152),p=0,c=new t.ArrayBuffer,o=new FileReader,l=()=>{let u=p*2097152,h=Math.min(u+2097152,n.size);o.readAsArrayBuffer(n.slice(u,h))};o.onload=u=>{let h=u.target?.result;if(!h){i(a.business("Failed to read file chunk"));return}c.append(h),p++,p<s?l():e({md5:c.end()})},o.onerror=()=>{i(a.business("Failed to calculate MD5: FileReader error"))},l()})}async function mt(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,r)=>{let s=t.createHash("md5"),p=e.createReadStream(n);p.on("error",c=>r(a.business(`Failed to read file for MD5: ${c.message}`))),p.on("data",c=>s.update(c)),p.on("end",()=>i({md5:s.digest("hex")}))})}async function H(n){let t=P();if(t==="browser"){if(!(n instanceof Blob))throw a.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return dt(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 mt(n)}throw a.business("Unknown or unsupported execution environment for MD5 calculation.")}var j=I(()=>{"use strict";O();E()});function de(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&U(i)))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 r=i[i.length-1];if((0,Fe.isJunk)(r))return!1;for(let p of i)if(p!==".well-known"&&(p.startsWith(".")||p.length>255))return!1;let s=i.slice(0,-1);for(let p of s)if(Oe.some(c=>p.toLowerCase()===c.toLowerCase()))return!1;return!0})}var Fe,Oe,me=I(()=>{"use strict";Fe=require("junk");E();Oe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function ke(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=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r;s++){let p=e[0][s];if(e.every(c=>c[s]===p))i.push(p);else break}return i.join("/")}function Y(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var fe=I(()=>{"use strict"});function ye(n,t={}){if(t.flatten===!1)return n.map(i=>({path:Y(i),name:he(i)}));let e=Et(n);return n.map(i=>{let r=Y(i);if(e){let s=e.endsWith("/")?e:`${e}/`;r.startsWith(s)&&(r=r.substring(s.length))}return r||(r=he(i)),{path:r,name:he(i)}})}function Et(n){if(!n.length)return"";let e=n.map(s=>Y(s)).map(s=>s.split("/")),i=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r-1;s++){let p=e[0][s];if(e.every(c=>c[s]===p))i.push(p);else break}return i.join("/")}function he(n){return n.split(/[/\\]/).pop()||n}var ge=I(()=>{"use strict";fe()});function W(n,t=1){if(n===0)return"0 Bytes";let e=1024,i=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,r)).toFixed(t))+" "+i[r]}function J(n){if(ee(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 Dt(n,t){let e=[],i=[],r=[];if(n.length===0){let o={file:"(no files)",message:"At least one file must be provided"};return e.push(o),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let o of n)if(U(o.name))return e.push({file:o.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(l=>({...l,status:g.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let o={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(o),{files:n.map(l=>({...l,status:g.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let o of n){let l=g.READY,u="Ready for upload",h=o.name?J(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===g.PROCESSING_ERROR)l=g.VALIDATION_FAILED,u=o.statusMessage||"File failed during processing",e.push({file:o.name,message:u});else if(o.size===0){l=g.EXCLUDED,u="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:u}),r.push({...o,status:l,statusMessage:u});continue}else o.size<0?(l=g.VALIDATION_FAILED,u="File size must be positive",e.push({file:o.name,message:u})):!o.name||o.name.trim().length===0?(l=g.VALIDATION_FAILED,u="File name cannot be empty",e.push({file:o.name||"(empty)",message:u})):o.name.includes("\0")?(l=g.VALIDATION_FAILED,u="File name contains invalid characters (null byte)",e.push({file:o.name,message:u})):h.valid?$(o.name)?(l=g.VALIDATION_FAILED,u=`File extension not allowed: "${o.name}"`,e.push({file:o.name,message:u})):o.size>t.maxFileSize?(l=g.VALIDATION_FAILED,u=`File size (${W(o.size)}) exceeds limit of ${W(t.maxFileSize)}`,e.push({file:o.name,message:u})):(s+=o.size,s>t.maxTotalSize&&(l=g.VALIDATION_FAILED,u=`Total size would exceed limit of ${W(t.maxTotalSize)}`,e.push({file:o.name,message:u}))):(l=g.VALIDATION_FAILED,u=h.reason||"Invalid file name",e.push({file:o.name,message:u}));r.push({...o,status:l,statusMessage:u})}e.length>0&&(r=r.map(o=>o.status===g.EXCLUDED?o:{...o,status:g.VALIDATION_FAILED,statusMessage:o.status===g.VALIDATION_FAILED?o.statusMessage:"Deployment failed due to validation errors in bundle"}));let p=e.length===0?r.filter(o=>o.status===g.READY):[],c=e.length===0;return{files:r,validFiles:p,errors:e,warnings:i,canDeploy:c}}function $e(n){return n.filter(t=>t.status===g.READY)}function St(n){return $e(n).length>0}var Ee=I(()=>{"use strict";E()});function De(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 Se(n,t){let e=J(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if($(n))throw a.business(`File extension not allowed: "${t}"`)}var Te=I(()=>{"use strict";E();Ee()});var _e={};Re(_e,{processFilesForNode:()=>Ae});function Ue(n,t=new Set){let e=[],i=S.realpathSync(n);if(t.has(i))return e;t.add(i);let r=S.readdirSync(n);for(let s of r){let p=T.join(n,s),c=S.statSync(p);if(c.isDirectory()){let o=Ue(p,t);e.push(...o)}else c.isFile()&&e.push(p)}return e}async function Ae(n,t={},e){if(P()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let m of n){let y=T.resolve(m);try{if(S.statSync(y).isDirectory()){let A=S.readdirSync(y).find(w=>K.has(w));if(A)throw a.business(`"${A}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(A){if(L(A))throw A}}let i=n.flatMap(m=>{let y=T.resolve(m);try{return S.statSync(y).isDirectory()?Ue(y):[y]}catch{throw a.file(`Path does not exist: ${m}`,{filePath:m})}}),r=[...new Set(i)],s=n.map(m=>T.resolve(m)),p=ke(s.map(m=>{try{return S.statSync(m).isDirectory()?m:T.dirname(m)}catch{return T.dirname(m)}})),c=r.map(m=>{if(p&&p.length>0){let y=T.relative(p,m);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return T.basename(m)}),l=ye(c,{flatten:t.pathDetect!==!1}).map(m=>m.path),u=new Set(de(l));if(u.size===0)return[];let h=[],N=[];for(let m=0;m<r.length;m++)u.has(l[m])&&(h.push(r[m]),N.push(l[m]));let x=[],D=0;if(!e)throw a.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let m=0;m<h.length;m++){let y=h[m],A=N[m];try{De(A,y);let w=S.statSync(y);if(w.size===0)continue;if(Se(A,y),w.size>e.maxFileSize)throw a.business(`File ${y} is too large. Maximum allowed size is ${e.maxFileSize/(1024*1024)}MB.`);if(D+=w.size,D>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let k=S.readFileSync(y),{md5:Be}=await H(k);x.push({path:A,content:k,size:k.length,md5:Be})}catch(w){if(L(w))throw w;let k=w instanceof Error?w.message:String(w);throw a.file(`Failed to read file "${y}": ${k}`,{filePath:y})}}if(x.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return x}var S,T,we=I(()=>{"use strict";O();j();me();Te();E();ge();fe();S=C(require("fs"),1),T=C(require("path"),1)});var Tt={};Re(Tt,{API_KEY:()=>R,AccountPlan:()=>Ye,ApiHttp:()=>B,AuthMethod:()=>Qe,BLOCKED_EXTENSIONS:()=>xe,DEFAULT_API:()=>_,DEPLOYMENT_CONFIG_FILENAME:()=>G,DEPLOY_TOKEN:()=>v,DeploymentStatus:()=>qe,DomainStatus:()=>Xe,ErrorType:()=>d,FILE_VALIDATION_STATUS:()=>g,FileValidationStatus:()=>g,JUNK_DIRECTORIES:()=>Oe,LABEL_CONSTRAINTS:()=>b,LABEL_PATTERN:()=>ie,PASSWORD_CONSTRAINTS:()=>F,SPA_DEFAULT_CONFIG:()=>te,Ship:()=>Q,ShipError:()=>a,UNBUILT_PROJECT_MARKERS:()=>K,UNSAFE_FILENAME_CHARS:()=>Ie,__setTestEnvironment:()=>ct,allValidFilesReady:()=>St,calculateMD5:()=>H,createAccountResource:()=>pe,createDeploymentResource:()=>ae,createDomainResource:()=>le,createTokenResource:()=>ce,default:()=>Me,deserializeLabels:()=>lt,extractSubdomain:()=>rt,filterJunk:()=>de,formatFileSize:()=>W,generateDeploymentUrl:()=>st,generateDomainUrl:()=>ot,getENV:()=>P,getValidFiles:()=>$e,hasUnbuiltMarker:()=>U,hasUnsafeChars:()=>ee,isBlockedExtension:()=>$,isCustomDomain:()=>it,isDeployment:()=>nt,isPlatformDomain:()=>ne,isShipError:()=>L,mergeDeployOptions:()=>se,optimizeDeployPaths:()=>ye,pluralize:()=>gt,processFilesForNode:()=>Ae,resolveConfig:()=>re,serializeLabels:()=>at,validateApiKey:()=>Ze,validateApiUrl:()=>tt,validateDeployFile:()=>Se,validateDeployPath:()=>De,validateDeployToken:()=>et,validateFileName:()=>J,validateFiles:()=>Dt});module.exports=je(Tt);E();E();var V=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 r=Array.from(i);for(let s of r)try{s(...e)}catch(p){i.delete(s),t!=="error"&&setTimeout(()=>{let c=p instanceof Error?p:new Error(String(p));this.emit("error",c,String(t))},0)}}};E();function be(n){if(n!=null){if(typeof n!="string")throw a.validation("Password must be a string");if(n.length<F.MIN_LENGTH||n.length>F.MAX_LENGTH)throw a.validation(`Password must be between ${F.MIN_LENGTH} and ${F.MAX_LENGTH} characters`)}}function M(n){if(n==null)return;if(n.length===0)return n;if(n.length>b.MAX_COUNT)throw a.validation(`Maximum ${b.MAX_COUNT} labels allowed`);let t=n.map((i,r)=>{if(typeof i!="string")throw a.validation(`Label at index ${r} must be a string`);let s=i.trim().toLowerCase();if(s.length<b.MIN_LENGTH)throw a.validation(`Labels must be at least ${b.MIN_LENGTH} characters long`);if(s.length>b.MAX_LENGTH)throw a.validation(`Labels must be no more than ${b.MAX_LENGTH} characters long`);if(!ie.test(s))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${b.SEPARATORS}) between segments`);return s}),e=[...new Set(t)];if(e.length!==t.length)throw a.validation("Duplicate labels are not allowed");return e}var f={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},pt=3e4,B=class extends V{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||_,this.getAuthHeadersCallback=e.getAuthHeaders,this.useCredentials=e.useCredentials??!1,this.timeout=e.timeout??pt,this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||f.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}async executeRequest(e,i,r){let s=this.mergeHeaders(i.headers),{signal:p,cleanup:c}=this.createTimeoutSignal(i.signal),o={...i,headers:s,credentials:this.useCredentials&&!s.Authorization?"include":void 0,signal:p};this.emit("request",e,o);try{let l=await fetch(e,o);if(c(),!l.ok)throw await a.fromHttpResponse(l,r);return this.emit("response",this.safeClone(l),e),{data:await this.parseResponse(this.safeClone(l)),status:l.status}}catch(l){c();let u=a.fromFetchError(l,r);throw this.emit("error",u,e),u}}async request(e,i,r){let{data:s}=await this.executeRequest(e,i,r);return s}async requestWithStatus(e,i,r){return this.executeRequest(e,i,r)}mergeHeaders(e={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...e}}createTimeoutSignal(e){let i=new AbortController,r=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(r)}}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 deploy(e,i={}){if(!e.length)throw a.business("No files to deploy");for(let l of e)if(!l.md5)throw a.file(`MD5 checksum missing for file: ${l.path}`,{filePath:l.path});be(i.password);let r=M(i.labels),s=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:p,headers:c}=await this.createDeployBody(e,{labels:r,via:i.via,password:i.password,flags:s}),o={};return i.deployToken?o.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(o.Authorization=`Bearer ${i.apiKey}`),i.caller&&(o["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:p,headers:{...c,...o},signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){let r=M(i);return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:r})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,r){let s=M(r),p={};i&&(p.deployment=i),s!==void 0&&(p.labels=s);let{data:c,status:o}=await this.requestWithStatus(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)},"Set domain");return{...c,isCreate:o===201}}async listDomains(){return this.request(`${this.apiUrl}${f.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,i){let r=M(i),s={};return e!==void 0&&(s.ttl=e),r!==void 0&&(s.labels=r),this.request(`${this.apiUrl}${f.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${f.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${f.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async fetchAgentToken(){return this.request(`${this.apiUrl}${f.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent token")}async getAccount(){return this.request(`${this.apiUrl}${f.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${f.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return(await this.request(`${this.apiUrl}${f.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e,i={}){let r=e.find(l=>l.path==="index.html"||l.path==="/index.html");if(!r||r.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(r.content))s=r.content.toString("utf-8");else if(typeof Blob<"u"&&r.content instanceof Blob)s=await r.content.text();else if(typeof File<"u"&&r.content instanceof File)s=await r.content.text();else return!1;let p={"Content-Type":"application/json"};i.deployToken?p.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(p.Authorization=`Bearer ${i.apiKey}`);let c={files:e.map(l=>l.path),index:s};return(await this.request(`${this.apiUrl}${f.SPA_CHECK}`,{method:"POST",headers:p,body:JSON.stringify(c)},"SPA check")).isSPA}};E();function re(n={}){let t={apiUrl:n.apiUrl||_};return n.apiKey!==void 0&&(t.apiKey=n.apiKey),n.deployToken!==void 0&&(t.deployToken=n.deployToken),t}function se(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}E();E();j();async function ft(){let n=JSON.stringify(te,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await H(t);return{path:G,content:t,size:n.length,md5:e}}async function Pe(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===G))return n;try{if(await t.checkSPA(n,e)){let r=await ft();return[...n,r]}}catch{}return n}function ae(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:r,hasAuth:s}=n;return{upload:async(p,c={})=>{await e();let o=r?se(c,r):c;if(s&&!s()&&!o.deployToken&&!o.apiKey)try{let h=t(),{secret:N}=await h.fetchAgentToken();o.deployToken=N}catch(h){throw L(h)&&h.type===d.RateLimit?a.rateLimit("public deploy rate limit exceeded, try again later or run 'ship config' for a free account with higher limits"):h}if(!i)throw a.config("processInput function is not provided.");let l=t(),u=await i(p,o);return u=await Pe(u,l,o),l.deploy(u,o)},list:async()=>(await e(),t().listDeployments()),get:async p=>(await e(),t().getDeployment(p)),set:async(p,c)=>(await e(),t().updateDeploymentLabels(p,c.labels)),remove:async p=>{await e(),await t().removeDeployment(p)}}}function le(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,r={})=>(await e(),t().setDomain(i,r.deployment,r.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 pe(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function ce(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 q=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.auth=null;t={...t,apiUrl:t.apiUrl||void 0,apiKey:t.apiKey||void 0,deployToken:t.deployToken||void 0},this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.http=new B({...t,...re(t),getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=ae({...e,processInput:(i,r)=>this.processInput(i,r),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this.domains=le(e),this.account=pe(e),this.tokens=ce(e)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(t){throw this.initPromise=null,t}}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()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}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}};E();O();var ue=require("zod");E();O();var X=require("zod"),Le={apiUrl:X.z.string().url().optional(),apiKey:X.z.string().min(1).optional(),deployToken:X.z.string().min(1).optional()};var ht=ue.z.object(Le).strict(),yt={apiUrl:"SHIP_API_URL",apiKey:"SHIP_API_KEY",deployToken:"SHIP_DEPLOY_TOKEN"};function Ne(){if(P()!=="node")return{};let n={apiUrl:process.env.SHIP_API_URL||void 0,apiKey:process.env.SHIP_API_KEY||void 0,deployToken:process.env.SHIP_DEPLOY_TOKEN||void 0};try{return ht.parse(n)}catch(t){if(t instanceof ue.z.ZodError){let e=t.issues[0],i=e.path[0],r=(i&&yt[i])??"SHIP environment configuration";throw a.config(`Invalid ${r}: ${e.message}`)}throw a.config("Invalid environment configuration")}}E();async function Ce(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),{labels:s,via:p,password:c,flags:o}=t,l=new e,u=[];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}`,{filePath:D.path});if(!D.md5)throw a.file(`File missing md5 checksum: ${D.path}`,{filePath:D.path});let m=new i([D.content],D.path,{type:"application/octet-stream"});l.append("files[]",m),u.push(D.md5)}l.append("checksums",JSON.stringify(u)),s&&s.length>0&&l.append("labels",JSON.stringify(s)),p&&l.append("via",p),c&&l.append("password",c),o?.build&&l.append("build","true"),o?.prerender&&l.append("prerender","true"),o?.spa&&l.append("spa","true");let h=new r(l),N=[];for await(let D of h.encode())N.push(Buffer.from(D));let x=Buffer.concat(N);return{body:x.buffer.slice(x.byteOffset,x.byteOffset+x.byteLength),headers:{"Content-Type":h.contentType,"Content-Length":Buffer.byteLength(x).toString()}}}j();function gt(n,t,e,i=!0){let r=n===1?t:e;return i?`${n} ${r}`:r}me();ge();O();Ee();Te();E();we();var Q=class extends q{constructor(t={}){if(P()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=Ne();super({...t,apiUrl:t.apiUrl||e.apiUrl,apiKey:t.apiKey||e.apiKey,deployToken:t.deployToken||e.deployToken})}async deploy(t,e){return super.deploy(t,e)}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:r}=await Promise.resolve().then(()=>(we(),_e));return r(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return Ce}},Me=Q;0&&(module.exports={API_KEY,AccountPlan,ApiHttp,AuthMethod,BLOCKED_EXTENSIONS,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_TOKEN,DeploymentStatus,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,PASSWORD_CONSTRAINTS,SPA_DEFAULT_CONFIG,Ship,ShipError,UNBUILT_PROJECT_MARKERS,UNSAFE_FILENAME_CHARS,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getENV,getValidFiles,hasUnbuiltMarker,hasUnsafeChars,isBlockedExtension,isCustomDomain,isDeployment,isPlatformDomain,isShipError,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,serializeLabels,validateApiKey,validateApiUrl,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles});
2
2
 
3
3
  // Ship SDK: Enable axios-style CommonJS imports
4
4
  const originalExports = module.exports;