@shipstatic/ship 2.3.2 → 2.3.4-beta.1
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/README.md +7 -7
- package/THIRD-PARTY-LICENSES.md +1 -1
- package/dist/browser.d.ts +53 -9
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- 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 +54 -10
- package/dist/index.d.ts +54 -10
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var st=Object.create;var G=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var pt=Object.getPrototypeOf,ct=Object.prototype.hasOwnProperty;var S=(e,t)=>()=>(e&&(t=e(e=0)),t);var ke=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})},Ue=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of lt(t))!ct.call(e,i)&&i!==n&&G(e,i,{get:()=>t[i],enumerable:!(r=at(t,i))||r.enumerable});return e};var P=(e,t,n)=>(n=e!=null?st(pt(e)):{},Ue(t||!e||!e.__esModule?G(n,"default",{value:e,enumerable:!0}):n,e)),ut=e=>Ue(G({},"__esModule",{value:!0}),e);function ft(e){if(!e||typeof e!="string")return;let t=e.trim().toLowerCase();return Object.values(He).includes(t)?t:void 0}function ie(e){if(e==null)return;if(typeof e!="string")throw s.validation("Idempotency key must be a string.");let t=e.trim();if(!t)throw s.validation("Idempotency key must not be empty.");if(t.length>L.MAX_LENGTH)throw s.validation(`Idempotency key must be at most ${L.MAX_LENGTH} characters.`);return t}function Tt(e){let t=e.code;return t==="ERR_INVALID_URL"?!1:typeof t=="string"?!0:e instanceof TypeError?!/\burl\b/i.test(e.message):!1}function v(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function St(e){let t=e.replace(/\\/g,"/").split("/").pop()??"",n=t.lastIndexOf(".");return n<=0||n===t.length-1?null:t.slice(n+1).toLowerCase()}function oe(e,t){let n=St(e);return n===null?!1:Array.isArray(t)?t.includes(n):t.has(n)}function se(e){return $e.test(e)}function C(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>z.has(n))}function Ge(e){return e.startsWith(ae.PREFIX)?D.API_KEY:e.startsWith(le.PREFIX)?D.DEPLOY_TOKEN:e.startsWith(pe.PREFIX)?D.OAUTH:D.OPAQUE}function It(e){return e.slice(0,re.length).toLowerCase()!==re?null:e.slice(re.length)||null}function ue(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n;try{n=JSON.parse(t)}catch(r){throw s.config(`invalid JSON format in config: ${r.message}`,{filePath:A})}if(n===null||typeof n!="object"||Array.isArray(n))throw s.config(`${A} must contain a JSON object`,{filePath:A})}function de(e,t,n){if(!e.startsWith(t.PREFIX))throw s.validation(`${n} must start with "${t.PREFIX}"`);if(e.length!==t.TOTAL_LENGTH)throw s.validation(`${n} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let r=e.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(r))throw s.validation(`${n} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function Be(e){de(e,ae,"API key")}function ze(e){de(e,le,"Deploy token")}function Ke(e){de(e,pe,"OAuth access token")}function K(e){switch(Ge(e)){case D.API_KEY:Be(e);return;case D.DEPLOY_TOKEN:ze(e);return;case D.OAUTH:Ke(e);return;case D.OPAQUE:if(!e)throw s.validation("Token must be a non-empty string")}}function me(e){if(!e||e.length>b.MAX_LENGTH||!b.PATTERN.test(e))throw s.validation(`Caller must be 1-${b.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function Nt(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw s.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw s.validation("API URL must not contain a path");if(t.search||t.hash)throw s.validation("API URL must not contain query parameters or fragments")}catch(t){throw v(t)?t:s.validation("API URL must be a valid URL")}}function Pt(e){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(e)}function V(e){if(e!=null){if(typeof e!="number"||!Number.isFinite(e))throw s.validation("TTL must be a number of seconds");if(!Number.isInteger(e))throw s.validation("TTL must be a whole number of seconds");if(e<w.MIN_SECONDS||e>w.MAX_SECONDS)throw s.validation(`TTL must be between ${w.MIN_SECONDS} and ${w.MAX_SECONDS} seconds`);return e}}function fe(e,t){return e.endsWith(`.${t}`)}function Ot(e,t){return!fe(e,t)}function wt(e,t){return fe(e,t)?e.slice(0,-(t.length+1)):null}function _t(e){return`https://${e}`}function vt(e){return`https://${e}`}function Ct(e){return!e||e.length===0?null:JSON.stringify(e)}function Ft(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Y(e){if(e==null)return;if(typeof e!="string")throw s.validation("Password must be a string");let t=e.trim();if(t.length<_.MIN_LENGTH||t.length>_.MAX_LENGTH)throw s.validation(`Password must be between ${_.MIN_LENGTH} and ${_.MAX_LENGTH} characters`);return t}var dt,He,mt,L,ht,m,g,d,yt,ne,Et,gt,s,At,Dt,$e,z,Rt,B,ae,le,pe,b,D,re,Lt,A,ce,F,w,q,x,bt,xt,h,R,he,_,f=S(()=>{"use strict";dt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},He={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc",CLD:"cld",CRS:"crs",API:"api"},mt={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},L={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};ht={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},m={DEPLOYMENTS:"/deployments",DEPLOYMENT:e=>`/deployments/${e}`,DEPLOYMENT_CONFIG:e=>`/deployments/${e}/config`,DOMAINS:"/domains",DOMAIN:e=>`/domains/${e}`,DOMAIN_VERIFY:e=>`/domains/${e}/verify`,DOMAIN_DNS:e=>`/domains/${e}/dns`,DOMAIN_RECORDS:e=>`/domains/${e}/records`,DOMAIN_SHARE:e=>`/domains/${e}/share`,DOMAIN_PROPAGATION:e=>`/domains/${e}/propagation`,DOMAINS_VALIDATE:"/domains/validate",TOKENS:"/tokens",TOKEN:e=>`/tokens/${e}`,ACCOUNT:"/account",ACCOUNT_KEY:"/account/key",ACCOUNT_CLAIM:"/account/claim",ACTIVITIES:"/activities",LABELS:"/labels",LIMITS:"/limits",PING:"/ping",SETUP:"/setup",SPA_CHECK:"/spa-check",UPLOAD:"/upload"},g={FILES:"files[]",CHECKSUMS:"checksums",LABELS:"labels",VIA:"via",PASSWORD:"password",TTL:"ttl",BUILD:"build",PRERENDER:"prerender",SPA:"spa",CAPTCHA:"captcha"},d={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Maintenance:"maintenance",Network:"network_error",Timeout:"timeout_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},yt=new Set([d.Network,d.Timeout,d.Cancelled,d.File,d.Config]),ne={client:new Set([d.Business,d.Cancelled,d.Config,d.File,d.Forbidden,d.NotFound,d.RateLimit,d.Validation]),network:new Set([d.Network,d.Timeout]),auth:new Set([d.Authentication])},Et=new Set(Object.values(d).filter(e=>!yt.has(e))),gt=200;s=class e extends Error{type;status;details;constructor(t,n,r,i){super(n),this.type=t,this.status=r,this.details=i,this.name="ShipError"}toResponse(){let t=this.details,n=this.type===d.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:n}}static async fromHttpResponse(t,n){let r,i,o;try{if(t.headers.get("content-type")?.includes("application/json")){let u=await t.json();if(u&&typeof u=="object"){let p=u;typeof p.message=="string"?r=p.message:typeof p.error=="string"&&(r=p.error),i=p.details,typeof p.error=="string"&&Et.has(p.error)&&(o=p.error)}}else{let u=(await t.text()).trim();u&&!u.startsWith("<")&&u.length<=gt&&(r=u)}}catch{}let l=t.headers.get("retry-after");if(l!==null){let a=l.trim(),u=/^\d+$/.test(a)?Number(a):Math.ceil((Date.parse(a)-Date.now())/1e3);if(Number.isFinite(u)&&u>=0){let p=i&&typeof i=="object"?i:{};p.retryAfter===void 0&&(i={...p,retryAfter:u})}}r=r||`${n||"Request"} failed with status ${t.status}`;let c=o??(t.status===401?d.Authentication:t.status===403?d.Forbidden:t.status===429?d.RateLimit:d.Api);return new e(c,r,t.status,i)}static fromFetchError(t,n){if(v(t))return t;let r=n||"Request",i=t?.name;return i==="AbortError"?e.cancelled(`${r} was cancelled`):i==="TimeoutError"?e.timeout(`${r} timed out`,{cause:t}):t instanceof Error?Tt(t)?e.network(`${r} failed: ${t.message}`,{cause:t}):new e(d.Api,`${r} failed: ${t.message}`):new e(d.Api,`${r} failed: Unknown error`)}static validation(t,n){return new e(d.Validation,t,400,n)}static notFound(t,n){let r=n?`${t} ${n} not found`:`${t} not found`;return new e(d.NotFound,r,404)}static forbidden(t,n){return new e(d.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(d.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(d.Authentication,t,401,n)}static business(t,n=400,r){return new e(d.Business,t,n,r)}static network(t,n){return new e(d.Network,t,void 0,n)}static timeout(t,n){return new e(d.Timeout,t,void 0,n)}static cancelled(t,n){return new e(d.Cancelled,t,void 0,n)}static file(t,n){return new e(d.File,t,void 0,n)}static config(t,n){return new e(d.Config,t,void 0,n)}static api(t,n=500,r){return new e(d.Api,t,n,r)}static maintenance(t,n){return new e(d.Maintenance,t,503,n)}isClientError(){return ne.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return ne.network.has(this.type)}isAuthError(){return ne.auth.has(this.type)}isType(t){return this.type===t}};At=["html","htm","xhtml","xml","txt","md","markdown","pdf","csv","json","jsonc","webmanifest","map","toml","yaml","yml","rss","atom","css","scss","sass","less","js","mjs","cjs","jsx","ts","tsx","wasm","vue","svelte","png","jpg","jpeg","gif","webp","avif","svg","ico","bmp","tif","tiff","heic","heif","woff","woff2","ttf","otf","eot","mp3","wav","ogg","oga","opus","m4a","aac","flac","weba","mp4","webm","ogv","mov","m4v","avi","glb","gltf","usdz","vtt","srt","zip"],Dt=At.map(e=>`.${e}`).join(","),$e=/[\x00-\x1f\x7f#?%\\<>"]/;z=new Set(["node_modules","package.json"]);Rt="/auth",B={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},ae={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},le={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},pe={PREFIX:"oauth-",HEX_LENGTH:32,TOTAL_LENGTH:38},b={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},D={API_KEY:B.API_KEY,DEPLOY_TOKEN:B.TOKEN,OAUTH:B.OAUTH,OPAQUE:"opaque"};re="bearer ";Lt={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},A="ship.json",ce={rewrites:[{source:"/(.*)",destination:"/index.html"}]},F={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};w={MIN_SECONDS:1,MAX_SECONDS:365*24*60*60};q="https://api.shipstatic.com",x={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},bt="https://my.shipstatic.com/api-key",xt=4320*60,h={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};R={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},he=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;_={MIN_LENGTH:6,MAX_LENGTH:128}});async function Kt(e){let t=(await import("spark-md5")).default,n=new t.ArrayBuffer,r=2097152;for(let i=0;i<e.size;i+=r){let o=Math.min(i+r,e.size);n.append(await e.slice(i,o).arrayBuffer())}return{md5:n.end()}}async function Vt(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function qt(e){let{createHash:t}=await import("crypto"),{createReadStream:n}=await import("fs");return new Promise((r,i)=>{let o=t("md5"),l=n(e);l.on("error",c=>i(s.file(`Failed to read file for MD5: ${c.message}`,{filePath:e}))),l.on("data",c=>o.update(c)),l.on("end",()=>r({md5:o.digest("hex")}))})}async function k(e){if(e instanceof Blob)return Kt(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return Vt(e);if(typeof e=="string")return qt(e);throw s.business("Invalid input for MD5 calculation")}var X=S(()=>{"use strict";f()});function Wt(e){Ae=e}function Jt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function N(){return Ae||Jt()}var Ae,H=S(()=>{"use strict";Ae=null});function Je(e){if(!e||e.length===0)return"";let t=e.filter(o=>o&&typeof o=="string").map(o=>o.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(o=>o.split("/").filter(Boolean)),r=[],i=Math.min(...n.map(o=>o.length));for(let o=0;o<i;o++){let l=n[0][o];if(n.every(c=>c[o]===l))r.push(l);else break}return r.join("/")}function Q(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Ie=S(()=>{"use strict"});function Ne(e,t={}){if(t.flatten===!1)return e.map(r=>({path:Q(r),name:Le(r)}));let n=en(e);return e.map(r=>{let i=Q(r);if(n){let o=n.endsWith("/")?n:`${n}/`;i.startsWith(o)&&(i=i.substring(o.length))}return i||(i=Le(r)),{path:i,name:Le(r)}})}function en(e){if(!e.length)return"";let n=e.map(o=>Q(o)).map(o=>o.split("/")),r=[],i=Math.min(...n.map(o=>o.length));for(let o=0;o<i-1;o++){let l=n[0][o];if(n.every(c=>c[o]===l))r.push(l);else break}return r.join("/")}function Le(e){return e.split(/[/\\]/).pop()||e}var Pe=S(()=>{"use strict";Ie()});function ee(e,t){return tn.find(n=>n.broken(e,t))}var tn,be=S(()=>{"use strict";f();xe();tn=[{name:"name",broken:({path:e})=>!Z(e).valid,sentence:({path:e})=>Z(e).reason??"Invalid file name"},{name:"extension",broken:({path:e},t)=>oe(e,t.blockedExtensions??[]),sentence:({path:e})=>`File extension not allowed: "${e}"`},{name:"fileSize",broken:({size:e},t)=>e>t.maxFileSize,sentence:({path:e},t)=>`File "${e}" too large. Maximum ${$(t.maxFileSize)} allowed`},{name:"totalSize",broken:({totalSize:e},t)=>e>t.maxTotalSize,sentence:({totalSize:e},t)=>`Total upload size too large. ${$(e)} exceeds maximum of ${$(t.maxTotalSize)}`}]});function $(e,t=1){if(e===0)return"0 Bytes";let n=1024,r=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(e)/Math.log(n));return`${parseFloat((e/n**i).toFixed(t))} ${r[i]}`}function Z(e){if(se(e))return{valid:!1,reason:"File name contains unsafe characters"};if(e.startsWith(" ")||e.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(e.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,n=e.split("/").pop()||e;return t.test(n)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function nn(e,t){let n=[],r=[],i=[];if(e.length===0){let a={file:"(no files)",message:"At least one file must be provided"};return n.push(a),{files:[],validFiles:[],errors:n,warnings:[],canDeploy:!1}}for(let a of e)if(C(a.name))return n.push({file:a.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:e.map(u=>({...u,status:h.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:n,warnings:[],canDeploy:!1};if(e.length>t.maxFilesCount){let a={file:`(${e.length} files)`,message:`File count (${e.length}) exceeds limit of ${t.maxFilesCount}`};return n.push(a),{files:e.map(u=>({...u,status:h.VALIDATION_FAILED,statusMessage:a.message})),validFiles:[],errors:n,warnings:[],canDeploy:!1}}let o=0;for(let a of e){let u=h.READY,p="Ready for upload";if(a.status===h.PROCESSING_ERROR)u=h.VALIDATION_FAILED,p=a.statusMessage||"File failed during processing",n.push({file:a.name,message:p});else if(a.size===0){u=h.EXCLUDED,p="File is empty (0 bytes) and cannot be deployed due to storage limitations",r.push({file:a.name,message:p}),i.push({...a,status:u,statusMessage:p});continue}else if(a.size<0)u=h.VALIDATION_FAILED,p="File size must be positive",n.push({file:a.name,message:p});else if(!a.name||a.name.trim().length===0)u=h.VALIDATION_FAILED,p="File name cannot be empty",n.push({file:a.name||"(empty)",message:p});else if(a.name.includes("\0"))u=h.VALIDATION_FAILED,p="File name contains invalid characters (null byte)",n.push({file:a.name,message:p});else{let y={path:a.name,size:a.size,totalSize:o+a.size},I=ee(y,t);I?(u=h.VALIDATION_FAILED,p=I.sentence(y,t),n.push({file:I.name==="totalSize"?`(${e.length} files)`:a.name,message:p})):o=y.totalSize}i.push({...a,status:u,statusMessage:p})}n.length>0&&(i=i.map(a=>a.status===h.EXCLUDED?a:{...a,status:h.VALIDATION_FAILED,statusMessage:a.status===h.VALIDATION_FAILED?a.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=n.length===0?i.filter(a=>a.status===h.READY):[],c=n.length===0;return{files:i,validFiles:l,errors:n,warnings:r,canDeploy:c}}function Qe(e){return e.filter(t=>t.status===h.READY)}function rn(e){return Qe(e).length>0}var xe=S(()=>{"use strict";f();be()});function Oe(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(r=>r&&C(r)))throw s.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(n=>{if(!n)return!1;let r=n.replace(/\\/g,"/").split("/").filter(Boolean);if(r.length===0)return!0;let i=r[r.length-1];if((0,Ze.isJunk)(i))return!1;for(let l of r)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let o=r.slice(0,-1);for(let l of o)if(et.some(c=>l.toLowerCase()===c.toLowerCase()))return!1;return!0})}var Ze,et,we=S(()=>{"use strict";f();Ze=require("junk"),et=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function _e(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw s.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function ve(e,t){let n=ee(e,t);if(n)throw s.business(n.sentence(e,t))}var Ce=S(()=>{"use strict";f();be()});async function tt(e,t={},n){let r=!!(t.build||t.prerender),i=Ne(e.map(p=>p.path),{flatten:t.pathDetect!==!1}).map(p=>p.path),o=new Set(Oe(i,{allowUnbuilt:r})),l=e.map((p,y)=>({source:p,deployPath:i[y]})).filter(({deployPath:p})=>o.has(p));if(l.length===0)return[];let c=r?null:sn(n),a=[],u=0;for(let{source:p,deployPath:y}of l){if(c&&_e(y,p.origin),p.size===0)continue;c&&(u+=p.size,ve({path:y,size:p.size,totalSize:u},c));let I=await p.read(),{md5:O}=await k(I);a.push({path:y,content:I,size:p.size,md5:O})}if(c&&a.length>c.maxFilesCount)throw s.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return a}function sn(e){if(!e)throw s.config("Platform limits not provided. Deploy-mode validation requires the limits argument \u2014 pass `ship.getLimits()` result.");return e}var nt=S(()=>{"use strict";f();Pe();we();X();Ce()});var it={};ke(it,{processFilesForNode:()=>Fe});function rt(e,t=new Set){let n=[],r=T.realpathSync(e);if(t.has(r))return n;t.add(r);for(let i of T.readdirSync(e)){let o=E.join(e,i),l=T.statSync(o);l.isDirectory()?n.push(...rt(o,t)):l.isFile()&&n.push({absPath:o,size:l.size})}return n}async function an(e){try{return T.readFileSync(e)}catch(t){let n=t instanceof Error?t.message:String(t);throw s.file(`Failed to read file "${e}": ${n}`,{filePath:e})}}function ln(e){for(let t of e){let n=E.resolve(t);try{if(T.statSync(n).isDirectory()){let r=T.readdirSync(n).find(i=>z.has(i));if(r)throw s.business(`"${r}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(r){if(v(r))throw r}}}async function Fe(e,t={},n){if(N()!=="node")throw s.business("processFilesForNode can only be called in Node.js environment.");ln(e);let r=e.flatMap(c=>{let a=E.resolve(c);try{let u=T.statSync(a);return u.isDirectory()?rt(a):[{absPath:a,size:u.size}]}catch{throw s.file(`Path does not exist: ${c}`,{filePath:c})}}),i=new Map(r.map(c=>[c.absPath,c.size])),o=Je(e.map(c=>E.resolve(c)).map(c=>{try{return T.statSync(c).isDirectory()?c:E.dirname(c)}catch{return E.dirname(c)}})),l=[...i].map(([c,a])=>({path:pn(c,o),origin:c,size:a,read:()=>an(c)}));return tt(l,t,n)}function pn(e,t){if(t&&t.length>0){let n=E.relative(t,e);if(n&&typeof n=="string"&&!n.startsWith(".."))return n.replace(/\\/g,"/")}return E.basename(e)}var T,E,Me=S(()=>{"use strict";T=P(require("fs"),1),E=P(require("path"),1);f();nt();H();Ie()});var cn={};ke(cn,{API_KEY:()=>ae,API_PATHS:()=>m,AUTH_BASE_PATH:()=>Rt,AccountPlan:()=>ht,ApiHttp:()=>M,AuthMethod:()=>B,CALLER:()=>b,DEFAULT_API:()=>q,DEPLOYMENT_CONFIG_FILENAME:()=>A,DEPLOY_FIELDS:()=>g,DEPLOY_TOKEN:()=>le,DeploymentStatus:()=>dt,DeploymentVia:()=>He,DomainStatus:()=>mt,ErrorType:()=>d,FILE_VALIDATION_STATUS:()=>h,FileValidationStatus:()=>h,IDEMPOTENCY_KEY_CONSTRAINTS:()=>L,JUNK_DIRECTORIES:()=>et,LABEL_CONSTRAINTS:()=>R,LABEL_PATTERN:()=>he,MY_API_KEY_URL:()=>bt,OAUTH_TOKEN:()=>pe,OAuthScope:()=>Lt,PASSWORD_CONSTRAINTS:()=>_,PUBLIC_DEPLOYMENT_TTL_SECONDS:()=>xt,SHIP_ENV:()=>x,SPA_CHECK_CONSTRAINTS:()=>F,SPA_DEFAULT_CONFIG:()=>ce,Ship:()=>te,ShipError:()=>s,TTL_CONSTRAINTS:()=>w,TokenKind:()=>D,UNBUILT_PROJECT_MARKERS:()=>z,UNSAFE_FILENAME_CHARS:()=>$e,WEB_FILE_ACCEPT:()=>Dt,__setTestEnvironment:()=>Wt,allValidFilesReady:()=>rn,assertShipJsonSyntax:()=>ue,calculateMD5:()=>k,classifyToken:()=>Ge,createAccountResource:()=>Te,createDeploymentResource:()=>Ee,createDomainResource:()=>ge,createTokenResource:()=>Se,default:()=>ot,deserializeLabels:()=>Ft,extractSubdomain:()=>wt,filterJunk:()=>Oe,formatFileSize:()=>$,generateDeploymentUrl:()=>_t,generateDomainUrl:()=>vt,getENV:()=>N,getValidFiles:()=>Qe,hasUnbuiltMarker:()=>C,hasUnsafeChars:()=>se,isBlockedExtension:()=>oe,isCustomDomain:()=>Ot,isDeployment:()=>Pt,isPlatformDomain:()=>fe,isShipError:()=>v,normalizeVia:()=>ft,optimizeDeployPaths:()=>Ne,pluralize:()=>on,processFilesForNode:()=>Fe,readBearerValue:()=>It,serializeLabels:()=>Ct,validateApiKey:()=>Be,validateApiUrl:()=>Nt,validateCaller:()=>me,validateDeployFile:()=>ve,validateDeployPath:()=>_e,validateDeployToken:()=>ze,validateFileName:()=>Z,validateFiles:()=>nn,validateIdempotencyKey:()=>ie,validateOAuthToken:()=>Ke,validatePassword:()=>Y,validateToken:()=>K,validateTtl:()=>V});module.exports=ut(cn);f();f();f();var j=class{constructor(){this.handlers=new Map}on(t,n){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(n)}off(t,n){let r=this.handlers.get(t);r&&(r.delete(n),r.size===0&&this.handlers.delete(t))}emit(t,...n){let r=this.handlers.get(t);if(!r)return;let i=Array.from(r);for(let o of i)try{o(...n)}catch(l){r.delete(o),t!=="error"&&setTimeout(()=>{let c=l instanceof Error?l:new Error(String(l));this.emit("error",c,String(t))},0)}}};var Mt=3e4,kt=2,Ut=300,Ht=2e3,$t=new Set([500,502,503,504]);function Gt(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let i=()=>{clearTimeout(l),t?.removeEventListener("abort",o)},o=()=>{i(),r(t?.reason)},l=setTimeout(()=>{i(),n()},e);t?.addEventListener("abort",o)})}var Ve=3e5,Bt=3e5,zt=Ve+Bt,M=class extends j{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||q,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??Mt,this.maxRetries=Math.max(0,n.maxRetries??kt),this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.deploy={endpoint:n.deployEndpoint||m.DEPLOYMENTS,timeout:n.timeout??Ve,buildTimeout:n.timeout??zt}}setGlobalHeaders(n){this.globalHeaders=n}async executeRequest(n,r,i,o=this.timeout){for(let l=0;;l++)try{return await this.attemptOnce(n,r,i,o)}catch(c){let a=s.fromFetchError(c,i);if(l>=this.maxRetries||!this.isRetryable(a,r))throw this.emit("error",a,n),a;this.emit("retry",a,n,l+1);let u=Math.min(Ht,Ut*2**l);try{await Gt(Math.random()*u,r.signal)}catch(p){let y=s.fromFetchError(p,i);throw this.emit("error",y,n),y}}}isRetryable(n,r){if(r.signal?.aborted||n.isType(d.Maintenance)||n.isType(d.Cancelled)||!(n.isNetworkError()||n.status!==void 0&&$t.has(n.status)))return!1;let o=(r.method??"GET").toUpperCase();return o==="GET"||o==="HEAD"?!0:o==="PUT"||o==="DELETE"?!1:this.hasIdempotencyKey(r.headers)}hasIdempotencyKey(n){if(!n)return!1;let r=L.HEADER.toLowerCase();return Object.keys(n).some(i=>i.toLowerCase()===r)}async attemptOnce(n,r,i,o=this.timeout){let l=()=>{};try{let c=await this.mergeHeaders(r.headers),a=this.createTimeoutSignal(r.signal,o);l=a.cleanup;let u={...r,headers:c,credentials:this.session&&!c.Authorization?"include":void 0,signal:a.signal};this.emit("request",n,u);let p=await this.fetch(n,u);if(l(),!p.ok)throw await s.fromHttpResponse(p,i);return this.emit("response",this.safeClone(p),n),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(c){throw l(),s.fromFetchError(c,i)}}async request(n,r,i,o){let{data:l}=await this.executeRequest(`${this.apiUrl}${n}`,r,i,o);return l}async requestWithStatus(n,r,i){return this.executeRequest(`${this.apiUrl}${n}`,r,i)}async mergeHeaders(n={}){return{...this.globalHeaders,...this.caller?{[b.HEADER]:this.caller}:{},...await this.getAuthHeadersCallback(),...n}}createTimeoutSignal(n,r=this.timeout){let i=new AbortController,o=setTimeout(()=>i.abort(new DOMException(`Timed out after ${r}ms`,"TimeoutError")),r),l=n?()=>i.abort(n.reason):void 0;return n&&l&&(n.addEventListener("abort",l),n.aborted&&i.abort(n.reason)),{signal:i.signal,cleanup:()=>{clearTimeout(o),n&&l&&n.removeEventListener("abort",l)}}}safeClone(n){try{return n.clone()}catch{return n}}async parseResponse(n){if(!(n.headers.get("Content-Length")==="0"||n.status===204))return n.json()}};f();f();async function qe(e,t={}){let{labels:n,via:r,password:i,ttl:o,flags:l,captcha:c}=t,a=new FormData,u=[];for(let p of e){if(typeof p.content=="string"||p.content===null||p.content===void 0)throw s.file(`Unsupported file.content type: ${p.path}`,{filePath:p.path});if(!p.md5)throw s.file(`File missing md5 checksum: ${p.path}`,{filePath:p.path});a.append(g.FILES,new File([p.content],p.path,{type:"application/octet-stream"})),u.push(p.md5)}return a.append(g.CHECKSUMS,JSON.stringify(u)),n&&n.length>0&&a.append(g.LABELS,JSON.stringify(n)),r&&a.append(g.VIA,r),i&&a.append(g.PASSWORD,i),o!==void 0&&a.append(g.TTL,String(o)),l?.build&&a.append(g.BUILD,"true"),l?.prerender&&a.append(g.PRERENDER,"true"),l?.spa&&a.append(g.SPA,"true"),c&&a.append(g.CAPTCHA,c),a}f();X();async function Yt(){let e=JSON.stringify(ce,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await k(t);return{path:A,content:t,size:e.length,md5:n}}async function jt(e,t){let n=e.find(l=>l.path===F.INDEX_FILE||l.path===`/${F.INDEX_FILE}`);if(!n||n.size>F.MAX_INDEX_BYTES)return!1;let r;if(typeof Buffer<"u"&&Buffer.isBuffer(n.content))r=n.content.toString("utf-8");else if(typeof Blob<"u"&&n.content instanceof Blob)r=await n.content.text();else if(typeof File<"u"&&n.content instanceof File)r=await n.content.text();else return!1;let i={files:e.map(l=>l.path),index:r};return(await t.request(m.SPA_CHECK,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA check")).isSPA}async function Ye(e,t,n){if(n.spaDetect===!1||n.spa||n.build||n.prerender||e.some(r=>r.path===A))return e;try{if(await jt(e,t)){let i=await Yt();return[...e,i]}}catch{}return e}f();f();function U(e){if(e==null)return;if(e.length===0)return e;if(e.length>R.MAX_COUNT)throw s.validation(`Maximum ${R.MAX_COUNT} labels allowed`);let t=e.map((r,i)=>{if(typeof r!="string")throw s.validation(`Label at index ${i} must be a string`);let o=r.trim().toLowerCase();if(o.length<R.MIN_LENGTH)throw s.validation(`Labels must be at least ${R.MIN_LENGTH} characters long`);if(o.length>R.MAX_LENGTH)throw s.validation(`Labels must be no more than ${R.MAX_LENGTH} characters long`);if(!he.test(o))throw s.validation(`Labels must start and end with alphanumeric characters, with optional separators (${R.SEPARATORS}) between segments`);return o}),n=[...new Set(t)];if(n.length!==t.length)throw s.validation("Duplicate labels are not allowed");return n}async function je(e){let t=e.find(i=>i.path===A||i.path===`/${A}`);if(!t)return;let n=t.content,r=typeof n.text=="function"?await n.text():t.content.toString("utf8");ue(r)}var W={"Content-Type":"application/json"},Xt="sdk";function ye(e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor!==void 0&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}function Ee(e){let{getApi:t,processInput:n}=e;return{upload:async(r,i={})=>{if(!n)throw s.config("processInput function is not provided.");let o=t(),l=await n(r,i),c=await Ye(l,o,i);if(!c.length)throw s.business("No files to deploy");for(let O of c)if(!O.md5)throw s.file(`MD5 checksum missing for file: ${O.path}`,{filePath:O.path});Y(i.password);let a=V(i.ttl),u=ie(i.idempotencyKey),p=U(i.labels);await je(c);let y=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,I=await qe(c,{labels:p,via:i.via??Xt,password:i.password,ttl:a,flags:y,captcha:i.captcha});return o.request(o.deploy.endpoint,{method:"POST",body:I,...u?{headers:{[L.HEADER]:u}}:{},signal:i.signal||null},"Deploy",i.build||i.prerender?o.deploy.buildTimeout:o.deploy.timeout)},list:async r=>t().request(`${m.DEPLOYMENTS}${ye(r)}`,{method:"GET"},"List deployments"),get:async r=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"GET"},"Get deployment"),set:async(r,i)=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"PATCH",headers:W,body:JSON.stringify({labels:U(i.labels)})},"Update deployment labels"),delete:async r=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"DELETE"},"Delete deployment")}}function ge(e){let{getApi:t}=e;return{set:async(n,r={})=>{let i=U(r.labels),o={};r.deployment&&(o.deployment=r.deployment),i!==void 0&&(o.labels=i);let{data:l,status:c}=await t().requestWithStatus(m.DOMAIN(encodeURIComponent(n)),{method:"PUT",headers:W,body:JSON.stringify(o)},"Set domain");return{...l,isCreate:c===201}},list:async n=>t().request(`${m.DOMAINS}${ye(n)}`,{method:"GET"},"List domains"),get:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"GET"},"Get domain"),delete:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"DELETE"},"Delete domain"),verify:async n=>t().request(m.DOMAIN_VERIFY(encodeURIComponent(n)),{method:"POST"},"Verify domain"),validate:async n=>t().request(m.DOMAINS_VALIDATE,{method:"POST",headers:W,body:JSON.stringify({domain:n})},"Validate domain"),dns:async n=>t().request(m.DOMAIN_DNS(encodeURIComponent(n)),{method:"GET"},"Get domain DNS"),records:async n=>t().request(m.DOMAIN_RECORDS(encodeURIComponent(n)),{method:"GET"},"Get domain records"),share:async n=>t().request(m.DOMAIN_SHARE(encodeURIComponent(n)),{method:"GET"},"Get domain share")}}function Te(e){let{getApi:t}=e;return{get:async()=>t().request(m.ACCOUNT,{method:"GET"},"Get account")}}function Se(e){let{getApi:t}=e;return{create:async(n={})=>{let r=V(n.ttl),i=U(n.labels),o={};return r!==void 0&&(o.ttl=r),i!==void 0&&(o.labels=i),t().request(m.TOKENS,{method:"POST",headers:W,body:JSON.stringify(o)},"Create token")},list:async n=>t().request(`${m.TOKENS}${ye(n)}`,{method:"GET"},"List tokens"),get:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"GET"},"Get token"),delete:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"DELETE"},"Delete token")}}var J=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.credential=null;if(t={...t,apiUrl:t.apiUrl||void 0,token:t.token||void 0,caller:t.caller||void 0},this.clientOptions=t,t.caller!==void 0&&me(t.caller),t.token&&t.session)throw s.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(K(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new M({...t,getAuthHeaders:()=>this.getAuthHeaders()});let n={getApi:()=>this.http};this.deployments=Ee({...n,processInput:async(r,i)=>(await this.ensureInitialized(),this.processInput(r,i))}),this.domains=ge(n),this.account=Te(n),this.tokens=Se(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.request(m.LIMITS,{method:"GET"},"Get limits")}catch(t){throw this.initPromise=null,t}}async ping(){return this.http.request(m.PING,{method:"GET"},"Ping")}async deploy(t,n){return this.deployments.upload(t,n)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,n){this.http.on(t,n)}off(t,n){this.http.off(t,n)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw s.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw s.business("Invalid token provided. Token must be a non-empty string.");K(t),this.credential=t;return}if(typeof t!="function")throw s.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw s.authentication("Token provider returned no token.");if(typeof t!="string")throw s.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};H();f();var Re=require("zod");var De=require("zod"),Xe={apiUrl:De.z.string().url().optional(),token:De.z.string().min(1).optional()};H();var Qt=Re.z.object(Xe).strict(),Zt={apiUrl:x.API_URL,token:x.TOKEN};function We(){if(N()!=="node")return{};let e={apiUrl:process.env[x.API_URL]||void 0,token:process.env[x.TOKEN]||void 0};try{return Qt.parse(e)}catch(t){if(t instanceof Re.z.ZodError){let n=t.issues[0],r=n.path[0],i=(r&&Zt[r])??"SHIP environment configuration";throw s.config(`Invalid ${i}: ${n.message}`)}throw s.config("Invalid environment configuration")}}f();f();Pe();H();xe();we();X();Ce();function on(e,t,n,r=!0){let i=e===1?t:n;return r?`${e} ${i}`:i}Me();var te=class extends J{constructor(t={}){if(N()!=="node")throw s.business("Node.js Ship class can only be used in Node.js environment.");let n=We();super({...t,apiUrl:t.apiUrl||n.apiUrl,token:t.token||(t.session?void 0:n.token)})}async deploy(t,n){return super.deploy(t,n)}async processInput(t,n){let r=typeof t=="string"?[t]:t;if(!Array.isArray(r)||!r.every(o=>typeof o=="string"))throw s.business("Invalid input type for Node.js environment. Expected string or string[].");if(r.length===0)throw s.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(Me(),it));return i(r,n,this.platformLimits??void 0)}},ot=te;0&&(module.exports={API_KEY,API_PATHS,AUTH_BASE_PATH,AccountPlan,ApiHttp,AuthMethod,CALLER,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_FIELDS,DEPLOY_TOKEN,DeploymentStatus,DeploymentVia,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,IDEMPOTENCY_KEY_CONSTRAINTS,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,MY_API_KEY_URL,OAUTH_TOKEN,OAuthScope,PASSWORD_CONSTRAINTS,PUBLIC_DEPLOYMENT_TTL_SECONDS,SHIP_ENV,SPA_CHECK_CONSTRAINTS,SPA_DEFAULT_CONFIG,Ship,ShipError,TTL_CONSTRAINTS,TokenKind,UNBUILT_PROJECT_MARKERS,UNSAFE_FILENAME_CHARS,WEB_FILE_ACCEPT,__setTestEnvironment,allValidFilesReady,assertShipJsonSyntax,calculateMD5,classifyToken,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getENV,getValidFiles,hasUnbuiltMarker,hasUnsafeChars,isBlockedExtension,isCustomDomain,isDeployment,isPlatformDomain,isShipError,normalizeVia,optimizeDeployPaths,pluralize,processFilesForNode,readBearerValue,serializeLabels,validateApiKey,validateApiUrl,validateCaller,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles,validateIdempotencyKey,validateOAuthToken,validatePassword,validateToken,validateTtl});
|
|
1
|
+
"use strict";var st=Object.create;var G=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var pt=Object.getPrototypeOf,ct=Object.prototype.hasOwnProperty;var S=(e,t)=>()=>(e&&(t=e(e=0)),t);var ke=(e,t)=>{for(var n in t)G(e,n,{get:t[n],enumerable:!0})},Ue=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of lt(t))!ct.call(e,i)&&i!==n&&G(e,i,{get:()=>t[i],enumerable:!(r=at(t,i))||r.enumerable});return e};var P=(e,t,n)=>(n=e!=null?st(pt(e)):{},Ue(t||!e||!e.__esModule?G(n,"default",{value:e,enumerable:!0}):n,e)),ut=e=>Ue(G({},"__esModule",{value:!0}),e);function ft(e){if(!e||typeof e!="string")return;let t=e.trim().toLowerCase();return Object.values(He).includes(t)?t:void 0}function ie(e){if(e==null)return;if(typeof e!="string")throw s.validation("Idempotency key must be a string.");let t=e.trim();if(!t)throw s.validation("Idempotency key must not be empty.");if(t.length>L.MAX_LENGTH)throw s.validation(`Idempotency key must be at most ${L.MAX_LENGTH} characters.`);return t}function Tt(e){let t=e.code;return t==="ERR_INVALID_URL"?!1:typeof t=="string"?!0:e instanceof TypeError?!/\burl\b/i.test(e.message):!1}function v(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function St(e){let t=e.replace(/\\/g,"/").split("/").pop()??"",n=t.lastIndexOf(".");return n<=0||n===t.length-1?null:t.slice(n+1).toLowerCase()}function oe(e,t){let n=St(e);return n===null?!1:Array.isArray(t)?t.includes(n):t.has(n)}function se(e){return $e.test(e)}function C(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>z.has(n))}function Ge(e){return e.startsWith(ae.PREFIX)?R.API_KEY:e.startsWith(le.PREFIX)?R.DEPLOY_TOKEN:e.startsWith(pe.PREFIX)?R.OAUTH:R.OPAQUE}function Lt(e){return e.slice(0,re.length).toLowerCase()!==re?null:e.slice(re.length)||null}function ue(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n;try{n=JSON.parse(t)}catch(r){throw s.config(`invalid JSON format in config: ${r.message}`,{filePath:A})}if(n===null||typeof n!="object"||Array.isArray(n))throw s.config(`${A} must contain a JSON object`,{filePath:A})}function de(e,t,n){if(!e.startsWith(t.PREFIX))throw s.validation(`${n} must start with "${t.PREFIX}"`);if(e.length!==t.TOTAL_LENGTH)throw s.validation(`${n} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let r=e.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(r))throw s.validation(`${n} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function Be(e){de(e,ae,"API key")}function ze(e){de(e,le,"Deploy token")}function Ke(e){de(e,pe,"OAuth access token")}function K(e){switch(Ge(e)){case R.API_KEY:Be(e);return;case R.DEPLOY_TOKEN:ze(e);return;case R.OAUTH:Ke(e);return;case R.OPAQUE:if(!e)throw s.validation("Token must be a non-empty string")}}function me(e){if(!e||e.length>b.MAX_LENGTH||!b.PATTERN.test(e))throw s.validation(`Caller must be 1-${b.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function Pt(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw s.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw s.validation("API URL must not contain a path");if(t.search||t.hash)throw s.validation("API URL must not contain query parameters or fragments")}catch(t){throw v(t)?t:s.validation("API URL must be a valid URL")}}function bt(e){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(e)}function V(e){if(e!=null){if(typeof e!="number"||!Number.isFinite(e))throw s.validation("TTL must be a number of seconds");if(!Number.isInteger(e))throw s.validation("TTL must be a whole number of seconds");if(e<w.MIN_SECONDS||e>w.MAX_SECONDS)throw s.validation(`TTL must be between ${w.MIN_SECONDS} and ${w.MAX_SECONDS} seconds`);return e}}function fe(e,t){return e.endsWith(`.${t}`)}function wt(e,t){return!fe(e,t)}function _t(e,t){return fe(e,t)?e.slice(0,-(t.length+1)):null}function vt(e){return`https://${e}`}function Ct(e){return`https://${e}`}function Ft(e){return!e||e.length===0?null:JSON.stringify(e)}function Mt(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Y(e){if(e==null)return;if(typeof e!="string")throw s.validation("Password must be a string");let t=e.trim();if(t.length<_.MIN_LENGTH||t.length>_.MAX_LENGTH)throw s.validation(`Password must be between ${_.MIN_LENGTH} and ${_.MAX_LENGTH} characters`);return t}var dt,He,mt,L,ht,m,g,d,yt,ne,Et,gt,s,At,Rt,$e,z,Dt,It,B,ae,le,pe,b,R,re,Nt,A,ce,F,w,q,x,xt,Ot,h,D,he,_,f=S(()=>{"use strict";dt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},He={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc",CLD:"cld",CRS:"crs",API:"api"},mt={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},L={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};ht={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},m={DEPLOYMENTS:"/deployments",DEPLOYMENT:e=>`/deployments/${e}`,DEPLOYMENT_CONFIG:e=>`/deployments/${e}/config`,DOMAINS:"/domains",DOMAIN:e=>`/domains/${e}`,DOMAIN_VERIFY:e=>`/domains/${e}/verify`,DOMAIN_DNS:e=>`/domains/${e}/dns`,DOMAIN_RECORDS:e=>`/domains/${e}/records`,DOMAIN_SHARE:e=>`/domains/${e}/share`,DOMAIN_PROPAGATION:e=>`/domains/${e}/propagation`,DOMAINS_VALIDATE:"/domains/validate",TOKENS:"/tokens",TOKEN:e=>`/tokens/${e}`,ACCOUNT:"/account",ACCOUNT_KEY:"/account/key",ACCOUNT_CLAIM:"/account/claim",ACTIVITIES:"/activities",LABELS:"/labels",LIMITS:"/limits",PING:"/ping",SETUP:"/setup",SPA_CHECK:"/spa-check",UPLOAD:"/upload"},g={FILES:"files[]",CHECKSUMS:"checksums",LABELS:"labels",VIA:"via",PASSWORD:"password",TTL:"ttl",BUILD:"build",PRERENDER:"prerender",SPA:"spa",CAPTCHA:"captcha"},d={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Maintenance:"maintenance",Network:"network_error",Timeout:"timeout_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},yt=new Set([d.Network,d.Timeout,d.Cancelled,d.File,d.Config]),ne={client:new Set([d.Business,d.Cancelled,d.Config,d.File,d.Forbidden,d.NotFound,d.RateLimit,d.Validation]),network:new Set([d.Network,d.Timeout]),auth:new Set([d.Authentication])},Et=new Set(Object.values(d).filter(e=>!yt.has(e))),gt=200;s=class e extends Error{type;status;details;constructor(t,n,r,i){super(n),this.type=t,this.status=r,this.details=i,this.name="ShipError"}toResponse(){let t=this.details,n=this.type===d.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:n}}static async fromHttpResponse(t,n){let r,i,o;try{if(t.headers.get("content-type")?.includes("application/json")){let u=await t.json();if(u&&typeof u=="object"){let p=u;typeof p.message=="string"?r=p.message:typeof p.error=="string"&&(r=p.error),i=p.details,typeof p.error=="string"&&Et.has(p.error)&&(o=p.error)}}else{let u=(await t.text()).trim();u&&!u.startsWith("<")&&u.length<=gt&&(r=u)}}catch{}let l=t.headers.get("retry-after");if(l!==null){let a=l.trim(),u=/^\d+$/.test(a)?Number(a):Math.ceil((Date.parse(a)-Date.now())/1e3);if(Number.isFinite(u)&&u>=0){let p=i&&typeof i=="object"?i:{};p.retryAfter===void 0&&(i={...p,retryAfter:u})}}r=r||`${n||"Request"} failed with status ${t.status}`;let c=o??(t.status===401?d.Authentication:t.status===403?d.Forbidden:t.status===429?d.RateLimit:d.Api);return new e(c,r,t.status,i)}static fromFetchError(t,n){if(v(t))return t;let r=n||"Request",i=t?.name;return i==="AbortError"?e.cancelled(`${r} was cancelled`):i==="TimeoutError"?e.timeout(`${r} timed out`,{cause:t}):t instanceof Error?Tt(t)?e.network(`${r} failed: ${t.message}`,{cause:t}):new e(d.Api,`${r} failed: ${t.message}`):new e(d.Api,`${r} failed: Unknown error`)}static validation(t,n){return new e(d.Validation,t,400,n)}static notFound(t,n){let r=n?`${t} ${n} not found`:`${t} not found`;return new e(d.NotFound,r,404)}static forbidden(t,n){return new e(d.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(d.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(d.Authentication,t,401,n)}static business(t,n=400,r){return new e(d.Business,t,n,r)}static network(t,n){return new e(d.Network,t,void 0,n)}static timeout(t,n){return new e(d.Timeout,t,void 0,n)}static cancelled(t,n){return new e(d.Cancelled,t,void 0,n)}static file(t,n){return new e(d.File,t,void 0,n)}static config(t,n){return new e(d.Config,t,void 0,n)}static api(t,n=500,r){return new e(d.Api,t,n,r)}static maintenance(t,n){return new e(d.Maintenance,t,503,n)}isClientError(){return ne.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return ne.network.has(this.type)}isAuthError(){return ne.auth.has(this.type)}isType(t){return this.type===t}};At=["html","htm","xhtml","xml","txt","md","markdown","pdf","csv","json","jsonc","webmanifest","map","toml","yaml","yml","rss","atom","css","scss","sass","less","js","mjs","cjs","jsx","ts","tsx","wasm","vue","svelte","png","jpg","jpeg","gif","webp","avif","svg","ico","bmp","tif","tiff","heic","heif","woff","woff2","ttf","otf","eot","mp3","wav","ogg","oga","opus","m4a","aac","flac","weba","mp4","webm","ogv","mov","m4v","avi","glb","gltf","usdz","vtt","srt","zip"],Rt=At.map(e=>`.${e}`).join(","),$e=/[\x00-\x1f\x7f#?%\\<>"]/;z=new Set(["node_modules","package.json"]);Dt="/auth",It="signing-in",B={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},ae={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},le={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},pe={PREFIX:"oauth-",HEX_LENGTH:32,TOTAL_LENGTH:38},b={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},R={API_KEY:B.API_KEY,DEPLOY_TOKEN:B.TOKEN,OAUTH:B.OAUTH,OPAQUE:"opaque"};re="bearer ";Nt={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},A="ship.json",ce={rewrites:[{source:"/(.*)",destination:"/index.html"}]},F={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};w={MIN_SECONDS:1,MAX_SECONDS:365*24*60*60};q="https://api.shipstatic.com",x={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},xt="https://my.shipstatic.com/api-key",Ot=4320*60,h={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};D={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},he=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;_={MIN_LENGTH:6,MAX_LENGTH:128}});async function Vt(e){let t=(await import("spark-md5")).default,n=new t.ArrayBuffer,r=2097152;for(let i=0;i<e.size;i+=r){let o=Math.min(i+r,e.size);n.append(await e.slice(i,o).arrayBuffer())}return{md5:n.end()}}async function qt(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function Yt(e){let{createHash:t}=await import("crypto"),{createReadStream:n}=await import("fs");return new Promise((r,i)=>{let o=t("md5"),l=n(e);l.on("error",c=>i(s.file(`Failed to read file for MD5: ${c.message}`,{filePath:e}))),l.on("data",c=>o.update(c)),l.on("end",()=>r({md5:o.digest("hex")}))})}async function k(e){if(e instanceof Blob)return Vt(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return qt(e);if(typeof e=="string")return Yt(e);throw s.business("Invalid input for MD5 calculation")}var X=S(()=>{"use strict";f()});function Jt(e){Ae=e}function Qt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function N(){return Ae||Qt()}var Ae,H=S(()=>{"use strict";Ae=null});function Je(e){if(!e||e.length===0)return"";let t=e.filter(o=>o&&typeof o=="string").map(o=>o.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(o=>o.split("/").filter(Boolean)),r=[],i=Math.min(...n.map(o=>o.length));for(let o=0;o<i;o++){let l=n[0][o];if(n.every(c=>c[o]===l))r.push(l);else break}return r.join("/")}function Q(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Ie=S(()=>{"use strict"});function Ne(e,t={}){if(t.flatten===!1)return e.map(r=>({path:Q(r),name:Le(r)}));let n=tn(e);return e.map(r=>{let i=Q(r);if(n){let o=n.endsWith("/")?n:`${n}/`;i.startsWith(o)&&(i=i.substring(o.length))}return i||(i=Le(r)),{path:i,name:Le(r)}})}function tn(e){if(!e.length)return"";let n=e.map(o=>Q(o)).map(o=>o.split("/")),r=[],i=Math.min(...n.map(o=>o.length));for(let o=0;o<i-1;o++){let l=n[0][o];if(n.every(c=>c[o]===l))r.push(l);else break}return r.join("/")}function Le(e){return e.split(/[/\\]/).pop()||e}var Pe=S(()=>{"use strict";Ie()});function ee(e,t){return nn.find(n=>n.broken(e,t))}var nn,be=S(()=>{"use strict";f();xe();nn=[{name:"name",broken:({path:e})=>!Z(e).valid,sentence:({path:e})=>Z(e).reason??"Invalid file name"},{name:"extension",broken:({path:e},t)=>oe(e,t.blockedExtensions??[]),sentence:({path:e})=>`File extension not allowed: "${e}"`},{name:"fileSize",broken:({size:e},t)=>e>t.maxFileSize,sentence:({path:e},t)=>`File "${e}" too large. Maximum ${$(t.maxFileSize)} allowed`},{name:"totalSize",broken:({totalSize:e},t)=>e>t.maxTotalSize,sentence:({totalSize:e},t)=>`Total upload size too large. ${$(e)} exceeds maximum of ${$(t.maxTotalSize)}`}]});function $(e,t=1){if(e===0)return"0 Bytes";let n=1024,r=["Bytes","KB","MB","GB"],i=Math.floor(Math.log(e)/Math.log(n));return`${parseFloat((e/n**i).toFixed(t))} ${r[i]}`}function Z(e){if(se(e))return{valid:!1,reason:"File name contains unsafe characters"};if(e.startsWith(" ")||e.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(e.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,n=e.split("/").pop()||e;return t.test(n)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function rn(e,t){let n=[],r=[],i=[];if(e.length===0){let a={file:"(no files)",message:"At least one file must be provided"};return n.push(a),{files:[],validFiles:[],errors:n,warnings:[],canDeploy:!1}}for(let a of e)if(C(a.name))return n.push({file:a.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:e.map(u=>({...u,status:h.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:n,warnings:[],canDeploy:!1};if(e.length>t.maxFilesCount){let a={file:`(${e.length} files)`,message:`File count (${e.length}) exceeds limit of ${t.maxFilesCount}`};return n.push(a),{files:e.map(u=>({...u,status:h.VALIDATION_FAILED,statusMessage:a.message})),validFiles:[],errors:n,warnings:[],canDeploy:!1}}let o=0;for(let a of e){let u=h.READY,p="Ready for upload";if(a.status===h.PROCESSING_ERROR)u=h.VALIDATION_FAILED,p=a.statusMessage||"File failed during processing",n.push({file:a.name,message:p});else if(a.size===0){u=h.EXCLUDED,p="File is empty (0 bytes) and cannot be deployed due to storage limitations",r.push({file:a.name,message:p}),i.push({...a,status:u,statusMessage:p});continue}else if(a.size<0)u=h.VALIDATION_FAILED,p="File size must be positive",n.push({file:a.name,message:p});else if(!a.name||a.name.trim().length===0)u=h.VALIDATION_FAILED,p="File name cannot be empty",n.push({file:a.name||"(empty)",message:p});else if(a.name.includes("\0"))u=h.VALIDATION_FAILED,p="File name contains invalid characters (null byte)",n.push({file:a.name,message:p});else{let y={path:a.name,size:a.size,totalSize:o+a.size},I=ee(y,t);I?(u=h.VALIDATION_FAILED,p=I.sentence(y,t),n.push({file:I.name==="totalSize"?`(${e.length} files)`:a.name,message:p})):o=y.totalSize}i.push({...a,status:u,statusMessage:p})}n.length>0&&(i=i.map(a=>a.status===h.EXCLUDED?a:{...a,status:h.VALIDATION_FAILED,statusMessage:a.status===h.VALIDATION_FAILED?a.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=n.length===0?i.filter(a=>a.status===h.READY):[],c=n.length===0;return{files:i,validFiles:l,errors:n,warnings:r,canDeploy:c}}function Qe(e){return e.filter(t=>t.status===h.READY)}function on(e){return Qe(e).length>0}var xe=S(()=>{"use strict";f();be()});function Oe(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(r=>r&&C(r)))throw s.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(n=>{if(!n)return!1;let r=n.replace(/\\/g,"/").split("/").filter(Boolean);if(r.length===0)return!0;let i=r[r.length-1];if((0,Ze.isJunk)(i))return!1;for(let l of r)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let o=r.slice(0,-1);for(let l of o)if(et.some(c=>l.toLowerCase()===c.toLowerCase()))return!1;return!0})}var Ze,et,we=S(()=>{"use strict";f();Ze=require("junk"),et=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function _e(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw s.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function ve(e,t){let n=ee(e,t);if(n)throw s.business(n.sentence(e,t))}var Ce=S(()=>{"use strict";f();be()});async function tt(e,t={},n){let r=!!(t.build||t.prerender),i=Ne(e.map(p=>p.path),{flatten:t.pathDetect!==!1}).map(p=>p.path),o=new Set(Oe(i,{allowUnbuilt:r})),l=e.map((p,y)=>({source:p,deployPath:i[y]})).filter(({deployPath:p})=>o.has(p));if(l.length===0)return[];let c=r?null:an(n),a=[],u=0;for(let{source:p,deployPath:y}of l){if(c&&_e(y,p.origin),p.size===0)continue;c&&(u+=p.size,ve({path:y,size:p.size,totalSize:u},c));let I=await p.read(),{md5:O}=await k(I);a.push({path:y,content:I,size:p.size,md5:O})}if(c&&a.length>c.maxFilesCount)throw s.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return a}function an(e){if(!e)throw s.config("Platform limits not provided. Deploy-mode validation requires the limits argument \u2014 pass `ship.getLimits()` result.");return e}var nt=S(()=>{"use strict";f();Pe();we();X();Ce()});var it={};ke(it,{processFilesForNode:()=>Fe});function rt(e,t=new Set){let n=[],r=T.realpathSync(e);if(t.has(r))return n;t.add(r);for(let i of T.readdirSync(e)){let o=E.join(e,i),l=T.statSync(o);l.isDirectory()?n.push(...rt(o,t)):l.isFile()&&n.push({absPath:o,size:l.size})}return n}async function ln(e){try{return T.readFileSync(e)}catch(t){let n=t instanceof Error?t.message:String(t);throw s.file(`Failed to read file "${e}": ${n}`,{filePath:e})}}function pn(e){for(let t of e){let n=E.resolve(t);try{if(T.statSync(n).isDirectory()){let r=T.readdirSync(n).find(i=>z.has(i));if(r)throw s.business(`"${r}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(r){if(v(r))throw r}}}async function Fe(e,t={},n){if(N()!=="node")throw s.business("processFilesForNode can only be called in Node.js environment.");pn(e);let r=e.flatMap(c=>{let a=E.resolve(c);try{let u=T.statSync(a);return u.isDirectory()?rt(a):[{absPath:a,size:u.size}]}catch{throw s.file(`Path does not exist: ${c}`,{filePath:c})}}),i=new Map(r.map(c=>[c.absPath,c.size])),o=Je(e.map(c=>E.resolve(c)).map(c=>{try{return T.statSync(c).isDirectory()?c:E.dirname(c)}catch{return E.dirname(c)}})),l=[...i].map(([c,a])=>({path:cn(c,o),origin:c,size:a,read:()=>ln(c)}));return tt(l,t,n)}function cn(e,t){if(t&&t.length>0){let n=E.relative(t,e);if(n&&typeof n=="string"&&!n.startsWith(".."))return n.replace(/\\/g,"/")}return E.basename(e)}var T,E,Me=S(()=>{"use strict";T=P(require("fs"),1),E=P(require("path"),1);f();nt();H();Ie()});var un={};ke(un,{API_KEY:()=>ae,API_PATHS:()=>m,AUTH_BASE_PATH:()=>Dt,AccountPlan:()=>ht,ApiHttp:()=>M,AuthMethod:()=>B,CALLER:()=>b,DEFAULT_API:()=>q,DEPLOYMENT_CONFIG_FILENAME:()=>A,DEPLOY_FIELDS:()=>g,DEPLOY_TOKEN:()=>le,DeploymentStatus:()=>dt,DeploymentVia:()=>He,DomainStatus:()=>mt,ErrorType:()=>d,FILE_VALIDATION_STATUS:()=>h,FileValidationStatus:()=>h,IDEMPOTENCY_KEY_CONSTRAINTS:()=>L,JUNK_DIRECTORIES:()=>et,LABEL_CONSTRAINTS:()=>D,LABEL_PATTERN:()=>he,MY_API_KEY_URL:()=>xt,OAUTH_TOKEN:()=>pe,OAuthScope:()=>Nt,PASSWORD_CONSTRAINTS:()=>_,PUBLIC_DEPLOYMENT_TTL_SECONDS:()=>Ot,SHIP_ENV:()=>x,SIGN_IN_RETURN_PARAM:()=>It,SPA_CHECK_CONSTRAINTS:()=>F,SPA_DEFAULT_CONFIG:()=>ce,Ship:()=>te,ShipError:()=>s,TTL_CONSTRAINTS:()=>w,TokenKind:()=>R,UNBUILT_PROJECT_MARKERS:()=>z,UNSAFE_FILENAME_CHARS:()=>$e,WEB_FILE_ACCEPT:()=>Rt,__setTestEnvironment:()=>Jt,allValidFilesReady:()=>on,assertShipJsonSyntax:()=>ue,calculateMD5:()=>k,classifyToken:()=>Ge,createAccountResource:()=>Te,createDeploymentResource:()=>Ee,createDomainResource:()=>ge,createTokenResource:()=>Se,default:()=>ot,deserializeLabels:()=>Mt,extractSubdomain:()=>_t,filterJunk:()=>Oe,formatFileSize:()=>$,generateDeploymentUrl:()=>vt,generateDomainUrl:()=>Ct,getENV:()=>N,getValidFiles:()=>Qe,hasUnbuiltMarker:()=>C,hasUnsafeChars:()=>se,isBlockedExtension:()=>oe,isCustomDomain:()=>wt,isDeployment:()=>bt,isPlatformDomain:()=>fe,isShipError:()=>v,normalizeVia:()=>ft,optimizeDeployPaths:()=>Ne,pluralize:()=>sn,processFilesForNode:()=>Fe,readBearerValue:()=>Lt,serializeLabels:()=>Ft,validateApiKey:()=>Be,validateApiUrl:()=>Pt,validateCaller:()=>me,validateDeployFile:()=>ve,validateDeployPath:()=>_e,validateDeployToken:()=>ze,validateFileName:()=>Z,validateFiles:()=>rn,validateIdempotencyKey:()=>ie,validateOAuthToken:()=>Ke,validatePassword:()=>Y,validateToken:()=>K,validateTtl:()=>V});module.exports=ut(un);f();f();f();var j=class{constructor(){this.handlers=new Map}on(t,n){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(n)}off(t,n){let r=this.handlers.get(t);r&&(r.delete(n),r.size===0&&this.handlers.delete(t))}emit(t,...n){let r=this.handlers.get(t);if(!r)return;let i=Array.from(r);for(let o of i)try{o(...n)}catch(l){r.delete(o),t!=="error"&&setTimeout(()=>{let c=l instanceof Error?l:new Error(String(l));this.emit("error",c,String(t))},0)}}};var kt=3e4,Ut=2,Ht=300,$t=2e3,Gt=new Set([500,502,503,504]);function Bt(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let i=()=>{clearTimeout(l),t?.removeEventListener("abort",o)},o=()=>{i(),r(t?.reason)},l=setTimeout(()=>{i(),n()},e);t?.addEventListener("abort",o)})}var Ve=3e5,zt=3e5,Kt=Ve+zt,M=class extends j{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||q,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??kt,this.maxRetries=Math.max(0,n.maxRetries??Ut),this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.deploy={endpoint:n.deployEndpoint||m.DEPLOYMENTS,timeout:n.timeout??Ve,buildTimeout:n.timeout??Kt}}setGlobalHeaders(n){this.globalHeaders=n}async executeRequest(n,r,i,o=this.timeout){for(let l=0;;l++)try{return await this.attemptOnce(n,r,i,o)}catch(c){let a=s.fromFetchError(c,i);if(l>=this.maxRetries||!this.isRetryable(a,r))throw this.emit("error",a,n),a;this.emit("retry",a,n,l+1);let u=Math.min($t,Ht*2**l);try{await Bt(Math.random()*u,r.signal)}catch(p){let y=s.fromFetchError(p,i);throw this.emit("error",y,n),y}}}isRetryable(n,r){if(r.signal?.aborted||n.isType(d.Maintenance)||n.isType(d.Cancelled)||!(n.isNetworkError()||n.status!==void 0&&Gt.has(n.status)))return!1;let o=(r.method??"GET").toUpperCase();return o==="GET"||o==="HEAD"?!0:o==="PUT"||o==="DELETE"?!1:this.hasIdempotencyKey(r.headers)}hasIdempotencyKey(n){if(!n)return!1;let r=L.HEADER.toLowerCase();return Object.keys(n).some(i=>i.toLowerCase()===r)}async attemptOnce(n,r,i,o=this.timeout){let l=()=>{};try{let c=await this.mergeHeaders(r.headers),a=this.createTimeoutSignal(r.signal,o);l=a.cleanup;let u={...r,headers:c,credentials:this.session&&!c.Authorization?"include":void 0,signal:a.signal};this.emit("request",n,u);let p=await this.fetch(n,u);if(l(),!p.ok)throw await s.fromHttpResponse(p,i);return this.emit("response",this.safeClone(p),n),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(c){throw l(),s.fromFetchError(c,i)}}async request(n,r,i,o){let{data:l}=await this.executeRequest(`${this.apiUrl}${n}`,r,i,o);return l}async requestWithStatus(n,r,i){return this.executeRequest(`${this.apiUrl}${n}`,r,i)}async mergeHeaders(n={}){return{...this.globalHeaders,...this.caller?{[b.HEADER]:this.caller}:{},...await this.getAuthHeadersCallback(),...n}}createTimeoutSignal(n,r=this.timeout){let i=new AbortController,o=setTimeout(()=>i.abort(new DOMException(`Timed out after ${r}ms`,"TimeoutError")),r),l=n?()=>i.abort(n.reason):void 0;return n&&l&&(n.addEventListener("abort",l),n.aborted&&i.abort(n.reason)),{signal:i.signal,cleanup:()=>{clearTimeout(o),n&&l&&n.removeEventListener("abort",l)}}}safeClone(n){try{return n.clone()}catch{return n}}async parseResponse(n){if(!(n.headers.get("Content-Length")==="0"||n.status===204))return n.json()}};f();f();async function qe(e,t={}){let{labels:n,via:r,password:i,ttl:o,flags:l,captcha:c}=t,a=new FormData,u=[];for(let p of e){if(typeof p.content=="string"||p.content===null||p.content===void 0)throw s.file(`Unsupported file.content type: ${p.path}`,{filePath:p.path});if(!p.md5)throw s.file(`File missing md5 checksum: ${p.path}`,{filePath:p.path});a.append(g.FILES,new File([p.content],p.path,{type:"application/octet-stream"})),u.push(p.md5)}return a.append(g.CHECKSUMS,JSON.stringify(u)),n&&n.length>0&&a.append(g.LABELS,JSON.stringify(n)),r&&a.append(g.VIA,r),i&&a.append(g.PASSWORD,i),o!==void 0&&a.append(g.TTL,String(o)),l?.build&&a.append(g.BUILD,"true"),l?.prerender&&a.append(g.PRERENDER,"true"),l?.spa&&a.append(g.SPA,"true"),c&&a.append(g.CAPTCHA,c),a}f();X();async function jt(){let e=JSON.stringify(ce,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await k(t);return{path:A,content:t,size:e.length,md5:n}}async function Xt(e,t){let n=e.find(l=>l.path===F.INDEX_FILE||l.path===`/${F.INDEX_FILE}`);if(!n||n.size>F.MAX_INDEX_BYTES)return!1;let r;if(typeof Buffer<"u"&&Buffer.isBuffer(n.content))r=n.content.toString("utf-8");else if(typeof Blob<"u"&&n.content instanceof Blob)r=await n.content.text();else if(typeof File<"u"&&n.content instanceof File)r=await n.content.text();else return!1;let i={files:e.map(l=>l.path),index:r};return(await t.request(m.SPA_CHECK,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA check")).isSPA}async function Ye(e,t,n){if(n.spaDetect===!1||n.spa||n.build||n.prerender||e.some(r=>r.path===A))return e;try{if(await Xt(e,t)){let i=await jt();return[...e,i]}}catch{}return e}f();f();function U(e){if(e==null)return;if(e.length===0)return e;if(e.length>D.MAX_COUNT)throw s.validation(`Maximum ${D.MAX_COUNT} labels allowed`);let t=e.map((r,i)=>{if(typeof r!="string")throw s.validation(`Label at index ${i} must be a string`);let o=r.trim().toLowerCase();if(o.length<D.MIN_LENGTH)throw s.validation(`Labels must be at least ${D.MIN_LENGTH} characters long`);if(o.length>D.MAX_LENGTH)throw s.validation(`Labels must be no more than ${D.MAX_LENGTH} characters long`);if(!he.test(o))throw s.validation(`Labels must start and end with alphanumeric characters, with optional separators (${D.SEPARATORS}) between segments`);return o}),n=[...new Set(t)];if(n.length!==t.length)throw s.validation("Duplicate labels are not allowed");return n}async function je(e){let t=e.find(i=>i.path===A||i.path===`/${A}`);if(!t)return;let n=t.content,r=typeof n.text=="function"?await n.text():t.content.toString("utf8");ue(r)}var W={"Content-Type":"application/json"},Wt="sdk";function ye(e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor!==void 0&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}function Ee(e){let{getApi:t,processInput:n}=e;return{upload:async(r,i={})=>{if(!n)throw s.config("processInput function is not provided.");let o=t(),l=await n(r,i),c=await Ye(l,o,i);if(!c.length)throw s.business("No files to deploy");for(let O of c)if(!O.md5)throw s.file(`MD5 checksum missing for file: ${O.path}`,{filePath:O.path});Y(i.password);let a=V(i.ttl),u=ie(i.idempotencyKey),p=U(i.labels);await je(c);let y=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,I=await qe(c,{labels:p,via:i.via??Wt,password:i.password,ttl:a,flags:y,captcha:i.captcha});return o.request(o.deploy.endpoint,{method:"POST",body:I,...u?{headers:{[L.HEADER]:u}}:{},signal:i.signal||null},"Deploy",i.build||i.prerender?o.deploy.buildTimeout:o.deploy.timeout)},list:async r=>t().request(`${m.DEPLOYMENTS}${ye(r)}`,{method:"GET"},"List deployments"),get:async r=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"GET"},"Get deployment"),set:async(r,i)=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"PATCH",headers:W,body:JSON.stringify({labels:U(i.labels)})},"Update deployment labels"),delete:async r=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"DELETE"},"Delete deployment")}}function ge(e){let{getApi:t}=e;return{set:async(n,r={})=>{let i=U(r.labels),o={};r.deployment&&(o.deployment=r.deployment),i!==void 0&&(o.labels=i);let{data:l,status:c}=await t().requestWithStatus(m.DOMAIN(encodeURIComponent(n)),{method:"PUT",headers:W,body:JSON.stringify(o)},"Set domain");return{...l,isCreate:c===201}},list:async n=>t().request(`${m.DOMAINS}${ye(n)}`,{method:"GET"},"List domains"),get:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"GET"},"Get domain"),delete:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"DELETE"},"Delete domain"),verify:async n=>t().request(m.DOMAIN_VERIFY(encodeURIComponent(n)),{method:"POST"},"Verify domain"),validate:async n=>t().request(m.DOMAINS_VALIDATE,{method:"POST",headers:W,body:JSON.stringify({domain:n})},"Validate domain"),dns:async n=>t().request(m.DOMAIN_DNS(encodeURIComponent(n)),{method:"GET"},"Get domain DNS"),records:async n=>t().request(m.DOMAIN_RECORDS(encodeURIComponent(n)),{method:"GET"},"Get domain records"),share:async n=>t().request(m.DOMAIN_SHARE(encodeURIComponent(n)),{method:"GET"},"Get domain share")}}function Te(e){let{getApi:t}=e;return{get:async()=>t().request(m.ACCOUNT,{method:"GET"},"Get account")}}function Se(e){let{getApi:t}=e;return{create:async(n={})=>{let r=V(n.ttl),i=U(n.labels),o={};return r!==void 0&&(o.ttl=r),i!==void 0&&(o.labels=i),t().request(m.TOKENS,{method:"POST",headers:W,body:JSON.stringify(o)},"Create token")},list:async n=>t().request(`${m.TOKENS}${ye(n)}`,{method:"GET"},"List tokens"),get:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"GET"},"Get token"),delete:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"DELETE"},"Delete token")}}var J=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.credential=null;if(t={...t,apiUrl:t.apiUrl||void 0,token:t.token||void 0,caller:t.caller||void 0},this.clientOptions=t,t.caller!==void 0&&me(t.caller),t.token&&t.session)throw s.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(K(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new M({...t,getAuthHeaders:()=>this.getAuthHeaders()});let n={getApi:()=>this.http};this.deployments=Ee({...n,processInput:async(r,i)=>(await this.ensureInitialized(),this.processInput(r,i))}),this.domains=ge(n),this.account=Te(n),this.tokens=Se(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.request(m.LIMITS,{method:"GET"},"Get limits")}catch(t){throw this.initPromise=null,t}}async ping(){return this.http.request(m.PING,{method:"GET"},"Ping")}async deploy(t,n){return this.deployments.upload(t,n)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,n){this.http.on(t,n)}off(t,n){this.http.off(t,n)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw s.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw s.business("Invalid token provided. Token must be a non-empty string.");K(t),this.credential=t;return}if(typeof t!="function")throw s.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw s.authentication("Token provider returned no token.");if(typeof t!="string")throw s.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};H();f();var De=require("zod");var Re=require("zod"),Xe={apiUrl:Re.z.string().url().optional(),token:Re.z.string().min(1).optional()};H();var Zt=De.z.object(Xe).strict(),en={apiUrl:x.API_URL,token:x.TOKEN};function We(){if(N()!=="node")return{};let e={apiUrl:process.env[x.API_URL]||void 0,token:process.env[x.TOKEN]||void 0};try{return Zt.parse(e)}catch(t){if(t instanceof De.z.ZodError){let n=t.issues[0],r=n.path[0],i=(r&&en[r])??"SHIP environment configuration";throw s.config(`Invalid ${i}: ${n.message}`)}throw s.config("Invalid environment configuration")}}f();f();Pe();H();xe();we();X();Ce();function sn(e,t,n,r=!0){let i=e===1?t:n;return r?`${e} ${i}`:i}Me();var te=class extends J{constructor(t={}){if(N()!=="node")throw s.business("Node.js Ship class can only be used in Node.js environment.");let n=We();super({...t,apiUrl:t.apiUrl||n.apiUrl,token:t.token||(t.session?void 0:n.token)})}async deploy(t,n){return super.deploy(t,n)}async processInput(t,n){let r=typeof t=="string"?[t]:t;if(!Array.isArray(r)||!r.every(o=>typeof o=="string"))throw s.business("Invalid input type for Node.js environment. Expected string or string[].");if(r.length===0)throw s.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(Me(),it));return i(r,n,this.platformLimits??void 0)}},ot=te;0&&(module.exports={API_KEY,API_PATHS,AUTH_BASE_PATH,AccountPlan,ApiHttp,AuthMethod,CALLER,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_FIELDS,DEPLOY_TOKEN,DeploymentStatus,DeploymentVia,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,IDEMPOTENCY_KEY_CONSTRAINTS,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,MY_API_KEY_URL,OAUTH_TOKEN,OAuthScope,PASSWORD_CONSTRAINTS,PUBLIC_DEPLOYMENT_TTL_SECONDS,SHIP_ENV,SIGN_IN_RETURN_PARAM,SPA_CHECK_CONSTRAINTS,SPA_DEFAULT_CONFIG,Ship,ShipError,TTL_CONSTRAINTS,TokenKind,UNBUILT_PROJECT_MARKERS,UNSAFE_FILENAME_CHARS,WEB_FILE_ACCEPT,__setTestEnvironment,allValidFilesReady,assertShipJsonSyntax,calculateMD5,classifyToken,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getENV,getValidFiles,hasUnbuiltMarker,hasUnsafeChars,isBlockedExtension,isCustomDomain,isDeployment,isPlatformDomain,isShipError,normalizeVia,optimizeDeployPaths,pluralize,processFilesForNode,readBearerValue,serializeLabels,validateApiKey,validateApiUrl,validateCaller,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles,validateIdempotencyKey,validateOAuthToken,validatePassword,validateToken,validateTtl});
|
|
2
2
|
|
|
3
3
|
// Ship SDK: Enable axios-style CommonJS imports
|
|
4
4
|
const originalExports = module.exports;
|