@shipstatic/ship 2.0.0-beta.12 → 2.0.0-beta.14

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 CHANGED
@@ -139,6 +139,8 @@ ship.getLimits() // → platform plan limits (cached)
139
139
 
140
140
  The `-q` flag outputs only the resource identifier — perfect for piping and scripting:
141
141
 
142
+ `ship tokens create -q` is the one exception: it prints the token **secret**, which is shown once and never again.
143
+
142
144
  ```bash
143
145
  # Deploy and link domain in one pipe
144
146
  ship ./dist -q | ship domains set www.example.com
package/SKILL.md CHANGED
@@ -223,6 +223,8 @@ Every command supports three modes:
223
223
  | `--json` | JSON on stdout | Parsing programmatically |
224
224
  | `-q` | Identifier only | Piping between commands |
225
225
 
226
+ `-q` prints the resource identifier — except `tokens create -q`, which prints the token **secret** (shown once, never again).
227
+
226
228
  Errors go to stderr in all modes. Exit 0 = success, 1 = error.
227
229
 
228
230
  List commands return `{"<resource>s": [...], "cursor": null}`. A non-null `cursor` means more pages remain — pass it back with `--cursor` to continue, and size pages with `--limit`. There is no total; a count is an aggregate over a collection, not a property of one page. `domains list` text mode omits status — use `--json` to see `pending` vs `success`.
package/dist/cli.cjs CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Zt=Object.create;var Se=Object.defineProperty;var Qt=Object.getOwnPropertyDescriptor;var en=Object.getOwnPropertyNames;var tn=Object.getPrototypeOf,nn=Object.prototype.hasOwnProperty;var L=(e,t)=>()=>(e&&(t=e(e=0)),t);var on=(e,t)=>{for(var n in t)Se(e,n,{get:t[n],enumerable:!0})},sn=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of en(t))!nn.call(e,i)&&i!==n&&Se(e,i,{get:()=>t[i],enumerable:!(o=Qt(t,i))||o.enumerable});return e};var R=(e,t,n)=>(n=e!=null?Zt(tn(e)):{},sn(t||!e||!e.__esModule?Se(n,"default",{value:e,enumerable:!0}):n,e));function We(e){if(e==null)return;if(typeof e!="string")throw p.validation("Idempotency key must be a string.");let t=e.trim();if(!t)throw p.validation("Idempotency key must not be empty.");if(t.length>Ke.MAX_LENGTH)throw p.validation(`Idempotency key must be at most ${Ke.MAX_LENGTH} characters.`);return t}function A(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function we(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return!1;let n=e.slice(t+1).toLowerCase();return pn.has(n)}function Xe(e){return cn.test(e)}function Ce(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>Te.has(n))}function dn(e){return e.startsWith(Je.PREFIX)?V.API_KEY:e.startsWith(Ze.PREFIX)?V.DEPLOY_TOKEN:V.OPAQUE}function et(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n;try{n=JSON.parse(t)}catch(o){throw p.config(`invalid JSON format in config: ${o.message}`,{filePath:P})}if(n===null||typeof n!="object"||Array.isArray(n))throw p.config(`${P} must contain a JSON object`,{filePath:P})}function tt(e,t,n){if(!e.startsWith(t.PREFIX))throw p.validation(`${n} must start with "${t.PREFIX}"`);if(e.length!==t.TOTAL_LENGTH)throw p.validation(`${n} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let o=e.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(o))throw p.validation(`${n} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function mn(e){tt(e,Je,"API key")}function un(e){tt(e,Ze,"Deploy token")}function H(e){switch(dn(e)){case V.API_KEY:mn(e);return;case V.DEPLOY_TOKEN:un(e);return;case V.OPAQUE:if(!e)throw p.validation("Token must be a non-empty string")}}function nt(e){if(!e||e.length>be.MAX_LENGTH||!be.PATTERN.test(e))throw p.validation(`Caller must be 1-${be.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function ot(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw p.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw p.validation("API URL must not contain a path");if(t.search||t.hash)throw p.validation("API URL must not contain query parameters or fragments")}catch(t){throw A(t)?t:p.validation("API URL must be a valid URL")}}function Oe(e){if(e==null)return;if(typeof e!="string")throw p.validation("Password must be a string");let t=e.trim();if(t.length<te.MIN_LENGTH||t.length>te.MAX_LENGTH)throw p.validation(`Password must be between ${te.MIN_LENGTH} and ${te.MAX_LENGTH} characters`);return t}var E,Ke,g,rn,Ee,an,ln,p,pn,cn,Te,Ye,Je,Ze,be,V,P,Qe,ne,F,it,te,w=L(()=>{"use strict";E={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"},Ke={MAX_LENGTH:256,WINDOW_SECONDS:1440*60};g={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"},rn=new Set([g.Network,g.Cancelled,g.File,g.Config]),Ee={client:new Set([g.Business,g.Cancelled,g.Config,g.File,g.Forbidden,g.NotFound,g.RateLimit,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},an=new Set(Object.values(g).filter(e=>!rn.has(e))),ln=200,p=class e extends Error{type;status;details;constructor(t,n,o,i){super(n),this.type=t,this.status=o,this.details=i,this.name="ShipError"}toResponse(){let t=this.details,n=this.type===g.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 o,i,s;try{if(t.headers.get("content-type")?.includes("application/json")){let d=await t.json();if(d&&typeof d=="object"){let r=d;typeof r.message=="string"?o=r.message:typeof r.error=="string"&&(o=r.error),i=r.details,typeof r.error=="string"&&an.has(r.error)&&(s=r.error)}}else{let d=(await t.text()).trim();d&&!d.startsWith("<")&&d.length<=ln&&(o=d)}}catch{}let a=t.headers.get("retry-after");if(a!==null){let m=a.trim(),d=/^\d+$/.test(m)?Number(m):Math.ceil((Date.parse(m)-Date.now())/1e3);if(Number.isFinite(d)&&d>=0){let r=i&&typeof i=="object"?i:{};r.retryAfter===void 0&&(i={...r,retryAfter:d})}}o=o||`${n||"Request"} failed with status ${t.status}`;let l=s??(t.status===401?g.Authentication:t.status===403?g.Forbidden:t.status===429?g.RateLimit:g.Api);return new e(l,o,t.status,i)}static fromFetchError(t,n){if(A(t))return t;let o=n||"Request";return t instanceof Error?t.name==="AbortError"?e.cancelled(`${o} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?e.network(`${o} failed: ${t.message}`,{cause:t}):new e(g.Api,`${o} failed: ${t.message}`):new e(g.Api,`${o} failed: Unknown error`)}static validation(t,n){return new e(g.Validation,t,400,n)}static notFound(t,n){let o=n?`${t} ${n} not found`:`${t} not found`;return new e(g.NotFound,o,404)}static forbidden(t,n){return new e(g.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(g.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(g.Authentication,t,401,n)}static business(t,n=400,o){return new e(g.Business,t,n,o)}static network(t,n){return new e(g.Network,t,void 0,n)}static cancelled(t,n){return new e(g.Cancelled,t,void 0,n)}static file(t,n){return new e(g.File,t,void 0,n)}static config(t,n){return new e(g.Config,t,void 0,n)}static api(t,n=500,o){return new e(g.Api,t,n,o)}isClientError(){return Ee.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return Ee.network.has(this.type)}isAuthError(){return Ee.auth.has(this.type)}isType(t){return this.type===t}};pn=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"]);cn=/[\x00-\x1f\x7f#?%\\<>"]/;Te=new Set(["node_modules","package.json"]);Ye={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},Je={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},Ze={PREFIX:"deploy-",HEX_LENGTH:64,TOTAL_LENGTH:71},be={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},V={API_KEY:Ye.API_KEY,DEPLOY_TOKEN:Ye.TOKEN,OPAQUE:"opaque"};P="ship.json",Qe={rewrites:[{source:"/(.*)",destination:"/index.html"}]};ne="https://api.shipstatic.com",F={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},it=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,te={MIN_LENGTH:6,MAX_LENGTH:128}});function fn(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function q(){return st||fn()}var st,ie=L(()=>{"use strict";st=null});async function vn(e){let t=(await import("spark-md5")).default,n=new t.ArrayBuffer,o=2097152;for(let i=0;i<e.size;i+=o){let s=Math.min(i+o,e.size);n.append(await e.slice(i,s).arrayBuffer())}return{md5:n.end()}}async function xn(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function _n(e){let{createHash:t}=await import("crypto"),{createReadStream:n}=await import("fs");return new Promise((o,i)=>{let s=t("md5"),a=n(e);a.on("error",l=>i(p.file(`Failed to read file for MD5: ${l.message}`,{filePath:e}))),a.on("data",l=>s.update(l)),a.on("end",()=>o({md5:s.digest("hex")}))})}async function de(e){if(e instanceof Blob)return vn(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return xn(e);if(typeof e=="string")return _n(e);throw p.business("Invalid input for MD5 calculation")}var Ie=L(()=>{"use strict";w()});function $t(e){if(!e||e.length===0)return"";let t=e.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(s=>s.split("/").filter(Boolean)),o=[],i=Math.min(...n.map(s=>s.length));for(let s=0;s<i;s++){let a=n[0][s];if(n.every(l=>l[s]===a))o.push(a);else break}return o.join("/")}function ue(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Ne=L(()=>{"use strict"});function vt(e,t={}){if(t.flatten===!1)return e.map(o=>({path:ue(o),name:Fe(o)}));let n=Pn(e);return e.map(o=>{let i=ue(o);if(n){let s=n.endsWith("/")?n:`${n}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=Fe(o)),{path:i,name:Fe(o)}})}function Pn(e){if(!e.length)return"";let n=e.map(s=>ue(s)).map(s=>s.split("/")),o=[],i=Math.min(...n.map(s=>s.length));for(let s=0;s<i-1;s++){let a=n[0][s];if(n.every(l=>l[s]===a))o.push(a);else break}return o.join("/")}function Fe(e){return e.split(/[/\\]/).pop()||e}var xt=L(()=>{"use strict";Ne()});function _t(e){if(Xe(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}}var Lt=L(()=>{"use strict";w()});function kt(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(o=>o&&Ce(o)))throw p.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 o=n.replace(/\\/g,"/").split("/").filter(Boolean);if(o.length===0)return!0;let i=o[o.length-1];if((0,Pt.isJunk)(i))return!1;for(let a of o)if(a!==".well-known"&&(a.startsWith(".")||a.length>255))return!1;let s=o.slice(0,-1);for(let a of s)if(kn.some(l=>a.toLowerCase()===l.toLowerCase()))return!1;return!0})}var Pt,kn,It=L(()=>{"use strict";w();Pt=require("junk"),kn=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Nt(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function Ft(e,t){let n=_t(e);if(!n.valid)throw p.business(n.reason||"Invalid file name");if(we(e))throw p.business(`File extension not allowed: "${t}"`)}var Mt=L(()=>{"use strict";w();Lt()});var jt={};on(jt,{processFilesForNode:()=>In});function Ut(e,t=new Set){let n=[],o=$.realpathSync(e);if(t.has(o))return n;t.add(o);let i=$.readdirSync(e);for(let s of i){let a=v.join(e,s),l=$.statSync(a);if(l.isDirectory()){let m=Ut(a,t);n.push(...m)}else l.isFile()&&n.push(a)}return n}async function In(e,t={},n){if(q()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");for(let f of e){let y=v.resolve(f);try{if($.statSync(y).isDirectory()){let T=$.readdirSync(y).find(C=>Te.has(C));if(T)throw p.business(`"${T}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(T){if(A(T))throw T}}let o=e.flatMap(f=>{let y=v.resolve(f);try{return $.statSync(y).isDirectory()?Ut(y):[y]}catch{throw p.file(`Path does not exist: ${f}`,{filePath:f})}}),i=[...new Set(o)],s=e.map(f=>v.resolve(f)),a=$t(s.map(f=>{try{return $.statSync(f).isDirectory()?f:v.dirname(f)}catch{return v.dirname(f)}})),l=i.map(f=>{if(a&&a.length>0){let y=v.relative(a,f);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return v.basename(f)}),d=vt(l,{flatten:t.pathDetect!==!1}).map(f=>f.path),r=new Set(kt(d));if(r.size===0)return[];let c=[],u=[];for(let f=0;f<i.length;f++)r.has(d[f])&&(c.push(i[f]),u.push(d[f]));let h=[],S=0;if(!n)throw p.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let f=0;f<c.length;f++){let y=c[f],T=u[f];try{Nt(T,y);let C=$.statSync(y);if(C.size===0)continue;if(Ft(T,y),C.size>n.maxFileSize)throw p.business(`File ${y} is too large. Maximum allowed size is ${n.maxFileSize/(1024*1024)}MB.`);if(S+=C.size,S>n.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${n.maxTotalSize/(1024*1024)}MB.`);let x=$.readFileSync(y),{md5:De}=await de(x);h.push({path:T,content:x,size:x.length,md5:De})}catch(C){if(A(C))throw C;let x=C instanceof Error?C.message:String(C);throw p.file(`Failed to read file "${y}": ${x}`,{filePath:y})}}if(h.length>n.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${n.maxFilesCount} files.`);return h}var $,v,Gt=L(()=>{"use strict";$=R(require("fs"),1),v=R(require("path"),1);w();xt();ie();It();Ie();Ne();Mt()});var Jt=require("commander");var z=require("fs"),Ve=R(require("path"),1);w();var G=require("commander"),ye=require("yoctocolors");w();var Ae=require("zod");var Re=require("zod"),oe={apiUrl:Re.z.string().url().optional(),token:Re.z.string().min(1).optional()};ie();var hn=Ae.z.object(oe).strict(),gn={apiUrl:"SHIP_API_URL",token:"SHIP_TOKEN"};function K(){if(q()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL||void 0,token:process.env.SHIP_TOKEN||void 0};try{return hn.parse(e)}catch(t){if(t instanceof Ae.z.ZodError){let n=t.issues[0],o=n.path[0],i=(o&&gn[o])??"SHIP environment configuration";throw p.config(`Invalid ${i}: ${n.message}`)}throw p.config("Invalid environment configuration")}}var b=R(require("fs"),1),Pe=R(require("os"),1),j=R(require("path"),1);w();var _=e=>e.commands.filter(t=>t.name()!=="help"),X=e=>_(e).filter(t=>_(t).length>0),yn=e=>e.registeredArguments.some(t=>/^(path|file|dir)/i.test(t.name())),Dn=e=>e.options.filter(t=>/<(file|path|dir)\w*>/i.test(t.flags)).map(t=>t.long??""),rt=e=>e.options.flatMap(t=>[t.long,t.short].filter(Boolean).map(n=>({flag:n,description:t.description}))),$e=e=>X(e).flatMap(t=>_(t).filter(n=>n.options.length>0).map(n=>({path:`${t.name()} ${n.name()}`,cmd:n}))),at=e=>e.options.flatMap(t=>[t.long,t.short].filter(Boolean).map(n=>({flag:n,description:t.description}))),ve=e=>[...X(e).flatMap(t=>_(t).filter(yn).map(n=>n.name())),...Dn(e)],xe=e=>`${e} ship shell completion \u2014 GENERATED from the command tree.
2
+ "use strict";var Zt=Object.create;var Se=Object.defineProperty;var Qt=Object.getOwnPropertyDescriptor;var en=Object.getOwnPropertyNames;var tn=Object.getPrototypeOf,nn=Object.prototype.hasOwnProperty;var P=(e,t)=>()=>(e&&(t=e(e=0)),t);var on=(e,t)=>{for(var n in t)Se(e,n,{get:t[n],enumerable:!0})},sn=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of en(t))!nn.call(e,i)&&i!==n&&Se(e,i,{get:()=>t[i],enumerable:!(o=Qt(t,i))||o.enumerable});return e};var R=(e,t,n)=>(n=e!=null?Zt(tn(e)):{},sn(t||!e||!e.__esModule?Se(n,"default",{value:e,enumerable:!0}):n,e));function We(e){if(e==null)return;if(typeof e!="string")throw p.validation("Idempotency key must be a string.");let t=e.trim();if(!t)throw p.validation("Idempotency key must not be empty.");if(t.length>qe.MAX_LENGTH)throw p.validation(`Idempotency key must be at most ${qe.MAX_LENGTH} characters.`);return t}function A(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function we(e){let t=e.lastIndexOf(".");if(t===-1||t===e.length-1)return!1;let n=e.slice(t+1).toLowerCase();return pn.has(n)}function Xe(e){return cn.test(e)}function Oe(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>Ce.has(n))}function dn(e){return e.startsWith(Je.PREFIX)?V.API_KEY:e.startsWith(Ze.PREFIX)?V.DEPLOY_TOKEN:V.OPAQUE}function et(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n;try{n=JSON.parse(t)}catch(o){throw p.config(`invalid JSON format in config: ${o.message}`,{filePath:_})}if(n===null||typeof n!="object"||Array.isArray(n))throw p.config(`${_} must contain a JSON object`,{filePath:_})}function tt(e,t,n){if(!e.startsWith(t.PREFIX))throw p.validation(`${n} must start with "${t.PREFIX}"`);if(e.length!==t.TOTAL_LENGTH)throw p.validation(`${n} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let o=e.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(o))throw p.validation(`${n} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function mn(e){tt(e,Je,"API key")}function un(e){tt(e,Ze,"Deploy token")}function H(e){switch(dn(e)){case V.API_KEY:mn(e);return;case V.DEPLOY_TOKEN:un(e);return;case V.OPAQUE:if(!e)throw p.validation("Token must be a non-empty string")}}function nt(e){if(!e||e.length>be.MAX_LENGTH||!be.PATTERN.test(e))throw p.validation(`Caller must be 1-${be.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function ot(e){try{let t=new URL(e);if(!["http:","https:"].includes(t.protocol))throw p.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw p.validation("API URL must not contain a path");if(t.search||t.hash)throw p.validation("API URL must not contain query parameters or fragments")}catch(t){throw A(t)?t:p.validation("API URL must be a valid URL")}}function Te(e){if(e==null)return;if(typeof e!="string")throw p.validation("Password must be a string");let t=e.trim();if(t.length<te.MIN_LENGTH||t.length>te.MAX_LENGTH)throw p.validation(`Password must be between ${te.MIN_LENGTH} and ${te.MAX_LENGTH} characters`);return t}var Ye,S,qe,g,rn,Ee,an,ln,p,pn,cn,Ce,Ke,Je,Ze,be,V,_,Qe,ne,F,it,te,b=P(()=>{"use strict";Ye={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},S={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"},qe={MAX_LENGTH:256,WINDOW_SECONDS:1440*60};g={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"},rn=new Set([g.Network,g.Cancelled,g.File,g.Config]),Ee={client:new Set([g.Business,g.Cancelled,g.Config,g.File,g.Forbidden,g.NotFound,g.RateLimit,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},an=new Set(Object.values(g).filter(e=>!rn.has(e))),ln=200,p=class e extends Error{type;status;details;constructor(t,n,o,i){super(n),this.type=t,this.status=o,this.details=i,this.name="ShipError"}toResponse(){let t=this.details,n=this.type===g.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 o,i,s;try{if(t.headers.get("content-type")?.includes("application/json")){let d=await t.json();if(d&&typeof d=="object"){let r=d;typeof r.message=="string"?o=r.message:typeof r.error=="string"&&(o=r.error),i=r.details,typeof r.error=="string"&&an.has(r.error)&&(s=r.error)}}else{let d=(await t.text()).trim();d&&!d.startsWith("<")&&d.length<=ln&&(o=d)}}catch{}let a=t.headers.get("retry-after");if(a!==null){let u=a.trim(),d=/^\d+$/.test(u)?Number(u):Math.ceil((Date.parse(u)-Date.now())/1e3);if(Number.isFinite(d)&&d>=0){let r=i&&typeof i=="object"?i:{};r.retryAfter===void 0&&(i={...r,retryAfter:d})}}o=o||`${n||"Request"} failed with status ${t.status}`;let l=s??(t.status===401?g.Authentication:t.status===403?g.Forbidden:t.status===429?g.RateLimit:g.Api);return new e(l,o,t.status,i)}static fromFetchError(t,n){if(A(t))return t;let o=n||"Request";return t instanceof Error?t.name==="AbortError"?e.cancelled(`${o} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?e.network(`${o} failed: ${t.message}`,{cause:t}):new e(g.Api,`${o} failed: ${t.message}`):new e(g.Api,`${o} failed: Unknown error`)}static validation(t,n){return new e(g.Validation,t,400,n)}static notFound(t,n){let o=n?`${t} ${n} not found`:`${t} not found`;return new e(g.NotFound,o,404)}static forbidden(t,n){return new e(g.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(g.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(g.Authentication,t,401,n)}static business(t,n=400,o){return new e(g.Business,t,n,o)}static network(t,n){return new e(g.Network,t,void 0,n)}static cancelled(t,n){return new e(g.Cancelled,t,void 0,n)}static file(t,n){return new e(g.File,t,void 0,n)}static config(t,n){return new e(g.Config,t,void 0,n)}static api(t,n=500,o){return new e(g.Api,t,n,o)}isClientError(){return Ee.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return Ee.network.has(this.type)}isAuthError(){return Ee.auth.has(this.type)}isType(t){return this.type===t}};pn=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"]);cn=/[\x00-\x1f\x7f#?%\\<>"]/;Ce=new Set(["node_modules","package.json"]);Ke={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},Je={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},Ze={PREFIX:"deploy-",HEX_LENGTH:64,TOTAL_LENGTH:71},be={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},V={API_KEY:Ke.API_KEY,DEPLOY_TOKEN:Ke.TOKEN,OPAQUE:"opaque"};_="ship.json",Qe={rewrites:[{source:"/(.*)",destination:"/index.html"}]};ne="https://api.shipstatic.com",F={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},it=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,te={MIN_LENGTH:6,MAX_LENGTH:128}});function fn(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function q(){return st||fn()}var st,ie=P(()=>{"use strict";st=null});async function vn(e){let t=(await import("spark-md5")).default,n=new t.ArrayBuffer,o=2097152;for(let i=0;i<e.size;i+=o){let s=Math.min(i+o,e.size);n.append(await e.slice(i,s).arrayBuffer())}return{md5:n.end()}}async function xn(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function Ln(e){let{createHash:t}=await import("crypto"),{createReadStream:n}=await import("fs");return new Promise((o,i)=>{let s=t("md5"),a=n(e);a.on("error",l=>i(p.file(`Failed to read file for MD5: ${l.message}`,{filePath:e}))),a.on("data",l=>s.update(l)),a.on("end",()=>o({md5:s.digest("hex")}))})}async function de(e){if(e instanceof Blob)return vn(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return xn(e);if(typeof e=="string")return Ln(e);throw p.business("Invalid input for MD5 calculation")}var Ie=P(()=>{"use strict";b()});function $t(e){if(!e||e.length===0)return"";let t=e.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(s=>s.split("/").filter(Boolean)),o=[],i=Math.min(...n.map(s=>s.length));for(let s=0;s<i;s++){let a=n[0][s];if(n.every(l=>l[s]===a))o.push(a);else break}return o.join("/")}function ue(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Ne=P(()=>{"use strict"});function vt(e,t={}){if(t.flatten===!1)return e.map(o=>({path:ue(o),name:Fe(o)}));let n=_n(e);return e.map(o=>{let i=ue(o);if(n){let s=n.endsWith("/")?n:`${n}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=Fe(o)),{path:i,name:Fe(o)}})}function _n(e){if(!e.length)return"";let n=e.map(s=>ue(s)).map(s=>s.split("/")),o=[],i=Math.min(...n.map(s=>s.length));for(let s=0;s<i-1;s++){let a=n[0][s];if(n.every(l=>l[s]===a))o.push(a);else break}return o.join("/")}function Fe(e){return e.split(/[/\\]/).pop()||e}var xt=P(()=>{"use strict";Ne()});function Lt(e){if(Xe(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}}var Pt=P(()=>{"use strict";b()});function kt(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(o=>o&&Oe(o)))throw p.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 o=n.replace(/\\/g,"/").split("/").filter(Boolean);if(o.length===0)return!0;let i=o[o.length-1];if((0,_t.isJunk)(i))return!1;for(let a of o)if(a!==".well-known"&&(a.startsWith(".")||a.length>255))return!1;let s=o.slice(0,-1);for(let a of s)if(kn.some(l=>a.toLowerCase()===l.toLowerCase()))return!1;return!0})}var _t,kn,It=P(()=>{"use strict";b();_t=require("junk"),kn=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Nt(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function Ft(e,t){let n=Lt(e);if(!n.valid)throw p.business(n.reason||"Invalid file name");if(we(e))throw p.business(`File extension not allowed: "${t}"`)}var Mt=P(()=>{"use strict";b();Pt()});var jt={};on(jt,{processFilesForNode:()=>In});function Ut(e,t=new Set){let n=[],o=$.realpathSync(e);if(t.has(o))return n;t.add(o);let i=$.readdirSync(e);for(let s of i){let a=v.join(e,s),l=$.statSync(a);if(l.isDirectory()){let u=Ut(a,t);n.push(...u)}else l.isFile()&&n.push(a)}return n}async function In(e,t={},n){if(q()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");for(let f of e){let y=v.resolve(f);try{if($.statSync(y).isDirectory()){let C=$.readdirSync(y).find(O=>Ce.has(O));if(C)throw p.business(`"${C}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(C){if(A(C))throw C}}let o=e.flatMap(f=>{let y=v.resolve(f);try{return $.statSync(y).isDirectory()?Ut(y):[y]}catch{throw p.file(`Path does not exist: ${f}`,{filePath:f})}}),i=[...new Set(o)],s=e.map(f=>v.resolve(f)),a=$t(s.map(f=>{try{return $.statSync(f).isDirectory()?f:v.dirname(f)}catch{return v.dirname(f)}})),l=i.map(f=>{if(a&&a.length>0){let y=v.relative(a,f);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return v.basename(f)}),d=vt(l,{flatten:t.pathDetect!==!1}).map(f=>f.path),r=new Set(kt(d));if(r.size===0)return[];let c=[],m=[];for(let f=0;f<i.length;f++)r.has(d[f])&&(c.push(i[f]),m.push(d[f]));let h=[],E=0;if(!n)throw p.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let f=0;f<c.length;f++){let y=c[f],C=m[f];try{Nt(C,y);let O=$.statSync(y);if(O.size===0)continue;if(Ft(C,y),O.size>n.maxFileSize)throw p.business(`File ${y} is too large. Maximum allowed size is ${n.maxFileSize/(1024*1024)}MB.`);if(E+=O.size,E>n.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${n.maxTotalSize/(1024*1024)}MB.`);let x=$.readFileSync(y),{md5:De}=await de(x);h.push({path:C,content:x,size:x.length,md5:De})}catch(O){if(A(O))throw O;let x=O instanceof Error?O.message:String(O);throw p.file(`Failed to read file "${y}": ${x}`,{filePath:y})}}if(h.length>n.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${n.maxFilesCount} files.`);return h}var $,v,Gt=P(()=>{"use strict";$=R(require("fs"),1),v=R(require("path"),1);b();xt();ie();It();Ie();Ne();Mt()});var Jt=require("commander");var z=require("fs"),Ve=R(require("path"),1);b();var G=require("commander"),ye=require("yoctocolors");b();var Ae=require("zod");var Re=require("zod"),oe={apiUrl:Re.z.string().url().optional(),token:Re.z.string().min(1).optional()};ie();var hn=Ae.z.object(oe).strict(),gn={apiUrl:"SHIP_API_URL",token:"SHIP_TOKEN"};function K(){if(q()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL||void 0,token:process.env.SHIP_TOKEN||void 0};try{return hn.parse(e)}catch(t){if(t instanceof Ae.z.ZodError){let n=t.issues[0],o=n.path[0],i=(o&&gn[o])??"SHIP environment configuration";throw p.config(`Invalid ${i}: ${n.message}`)}throw p.config("Invalid environment configuration")}}var w=R(require("fs"),1),_e=R(require("os"),1),j=R(require("path"),1);b();var L=e=>e.commands.filter(t=>t.name()!=="help"),X=e=>L(e).filter(t=>L(t).length>0),yn=e=>e.registeredArguments.some(t=>/^(path|file|dir)/i.test(t.name())),Dn=e=>e.options.filter(t=>/<(file|path|dir)\w*>/i.test(t.flags)).map(t=>t.long??""),rt=e=>e.options.flatMap(t=>[t.long,t.short].filter(Boolean).map(n=>({flag:n,description:t.description}))),$e=e=>X(e).flatMap(t=>L(t).filter(n=>n.options.length>0).map(n=>({path:`${t.name()} ${n.name()}`,cmd:n}))),at=e=>e.options.flatMap(t=>[t.long,t.short].filter(Boolean).map(n=>({flag:n,description:t.description}))),ve=e=>[...X(e).flatMap(t=>L(t).filter(yn).map(n=>n.name())),...Dn(e)],xe=e=>`${e} ship shell completion \u2014 GENERATED from the command tree.
3
3
  ${e} Do not edit: rendered by src/node/cli/completions.ts at install time,
4
4
  ${e} so this file always matches the binary that wrote it.
5
5
  `;function Sn(e){let t=X(e).map(o=>` "${o.name()}")
6
6
  if [[ \${COMP_CWORD} -eq 2 ]]; then
7
- COMPREPLY=( $(compgen -W "${_(o).map(i=>i.name()).join(" ")}" -- "\${current_word}") )
7
+ COMPREPLY=( $(compgen -W "${L(o).map(i=>i.name()).join(" ")}" -- "\${current_word}") )
8
8
  return
9
9
  fi
10
10
  ;;`).join(`
@@ -40,7 +40,7 @@ ${$e(e).map(({path:o,cmd:i})=>` "${o}") local_flags="${rt(i).map(s=>s.flag)
40
40
  fi
41
41
 
42
42
  if [[ \${COMP_CWORD} -eq 1 ]]; then
43
- COMPREPLY=( $(compgen -W "${_(e).map(o=>o.name()).join(" ")}" -- "\${current_word}") )
43
+ COMPREPLY=( $(compgen -W "${L(e).map(o=>o.name()).join(" ")}" -- "\${current_word}") )
44
44
  return
45
45
  fi
46
46
 
@@ -50,7 +50,7 @@ ${$e(e).map(({path:o,cmd:i})=>` "${o}") local_flags="${rt(i).map(s=>s.flag)
50
50
  complete -F _ship_completions ship
51
51
  `}var se=(e,t)=>`"${e}:${t.replace(/:/g,"\\:").replace(/"/g,'\\"')}"`;function En(e){let t=X(e).map(o=>` "${o.name()}")
52
52
  if [[ $CURRENT -eq 3 ]]; then
53
- completions=(${_(o).map(i=>se(i.name(),i.description())).join(" ")})
53
+ completions=(${L(o).map(i=>se(i.name(),i.description())).join(" ")})
54
54
  _describe '${o.name()} commands' completions
55
55
  return
56
56
  fi
@@ -95,7 +95,7 @@ ${$e(e).map(({path:o,cmd:i})=>` "${o}") completions+=(${rt(i).map(s=>se(s
95
95
  fi
96
96
 
97
97
  if [[ $CURRENT -eq 2 ]]; then
98
- completions=(${_(e).map(o=>se(o.name(),o.description())).join(" ")})
98
+ completions=(${L(e).map(o=>se(o.name(),o.description())).join(" ")})
99
99
  _describe 'commands' completions
100
100
  return
101
101
  fi
@@ -107,35 +107,35 @@ ${$e(e).map(({path:o,cmd:i})=>` "${o}") completions+=(${rt(i).map(s=>se(s
107
107
  compdef _ship ship
108
108
  fi
109
109
  fi
110
- `}var re=e=>e.replace(/\\/g,"\\\\").replace(/'/g,"\\'");function bn(e){let t=[];t.push("# Top-level commands");for(let o of _(e))t.push(`complete -c ship -f -n '__fish_use_subcommand' -a '${o.name()}' -d '${re(o.description())}'`);t.push("","# Global options");for(let o of e.options){let i=o.long?.replace(/^--/,"");if(!i)continue;let s=/<(file|path|dir)\w*>/i.test(o.flags)?" -r":o.required||o.optional?" -x":"";t.push(`complete -c ship -l ${i} -d '${re(o.description)}'${s}`)}for(let o of X(e)){t.push("",`# ${o.name()} subcommands`);for(let i of _(o))t.push(`complete -c ship -f -n '__fish_seen_subcommand_from ${o.name()}' -a '${i.name()}' -d '${re(i.description())}'`)}for(let{path:o,cmd:i}of $e(e)){let[s,a]=o.split(" ");t.push("",`# ${o} options`);for(let l of i.options){let m=l.long?.replace(/^--/,"");if(!m)continue;let d=l.required||l.optional?" -x":"";t.push(`complete -c ship -l ${m} -d '${re(l.description)}'${d} -n '__fish_seen_subcommand_from ${s}; and __fish_seen_subcommand_from ${a}'`)}}let n=ve(e);return t.push("","# Native file completion where a filesystem argument is expected","function __ship_needs_file"," set -l cmd (commandline -opc)"," if test (count $cmd) -ge 2"," set -l prev $cmd[-1]",` if contains -- "$prev" ${n.map(o=>`'${o}'`).join(" ")}`," return 0"," end"," end"," return 1","end","complete -c ship -F -n '__ship_needs_file'"),`${xe("#")}
110
+ `}var re=e=>e.replace(/\\/g,"\\\\").replace(/'/g,"\\'");function bn(e){let t=[];t.push("# Top-level commands");for(let o of L(e))t.push(`complete -c ship -f -n '__fish_use_subcommand' -a '${o.name()}' -d '${re(o.description())}'`);t.push("","# Global options");for(let o of e.options){let i=o.long?.replace(/^--/,"");if(!i)continue;let s=/<(file|path|dir)\w*>/i.test(o.flags)?" -r":o.required||o.optional?" -x":"";t.push(`complete -c ship -l ${i} -d '${re(o.description)}'${s}`)}for(let o of X(e)){t.push("",`# ${o.name()} subcommands`);for(let i of L(o))t.push(`complete -c ship -f -n '__fish_seen_subcommand_from ${o.name()}' -a '${i.name()}' -d '${re(i.description())}'`)}for(let{path:o,cmd:i}of $e(e)){let[s,a]=o.split(" ");t.push("",`# ${o} options`);for(let l of i.options){let u=l.long?.replace(/^--/,"");if(!u)continue;let d=l.required||l.optional?" -x":"";t.push(`complete -c ship -l ${u} -d '${re(l.description)}'${d} -n '__fish_seen_subcommand_from ${s}; and __fish_seen_subcommand_from ${a}'`)}}let n=ve(e);return t.push("","# Native file completion where a filesystem argument is expected","function __ship_needs_file"," set -l cmd (commandline -opc)"," if test (count $cmd) -ge 2"," set -l prev $cmd[-1]",` if contains -- "$prev" ${n.map(o=>`'${o}'`).join(" ")}`," return 0"," end"," end"," return 1","end","complete -c ship -F -n '__ship_needs_file'"),`${xe("#")}
111
111
  ${t.join(`
112
112
  `)}
113
- `}function lt(e,t){switch(t){case"bash":return Sn(e);case"zsh":return En(e);case"fish":return bn(e)}}var _e=R(require("columnify"),1),D=require("yoctocolors"),pt=["isCreate","claim"],O=(e,t,n)=>n?t:e(t),wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Tn=e=>/^[A-Z][a-z]/.test(e)?e.charAt(0).toLowerCase()+e.slice(1):e,Y=e=>Tn(e).replace(/\.$/,""),k=(e,t,n)=>{console.log(t?`${JSON.stringify({success:e},null,2)}
114
- `:`${O(D.green,Y(e),n)}
113
+ `}function lt(e,t){switch(t){case"bash":return Sn(e);case"zsh":return En(e);case"fish":return bn(e)}}var Le=R(require("columnify"),1),D=require("yoctocolors"),pt=["isCreate","claim"],T=(e,t,n)=>n?t:e(t),wn=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Cn=e=>/^[A-Z][a-z]/.test(e)?e.charAt(0).toLowerCase()+e.slice(1):e,Y=e=>Cn(e).replace(/\.$/,""),k=(e,t,n)=>{console.log(t?`${JSON.stringify({success:e},null,2)}
114
+ `:`${T(D.green,Y(e),n)}
115
115
  `)},ae=(e,t,n)=>{if(t)console.log(`${JSON.stringify({warning:e},null,2)}
116
- `);else{let o=O(s=>(0,D.inverse)((0,D.yellow)(s)),`${O(D.hidden,"[",n)}warning${O(D.hidden,"]",n)}`,n),i=O(D.yellow,Y(e),n);console.log(`${o} ${i}
116
+ `);else{let o=T(s=>(0,D.inverse)((0,D.yellow)(s)),`${T(D.hidden,"[",n)}warning${T(D.hidden,"]",n)}`,n),i=T(D.yellow,Y(e),n);console.log(`${o} ${i}
117
117
  `)}},M=(e,t,n)=>{if(t)console.log(`${JSON.stringify({info:e},null,2)}
118
- `);else{let o=O(s=>(0,D.inverse)((0,D.blue)(s)),`${O(D.hidden,"[",n)}info${O(D.hidden,"]",n)}`,n),i=O(D.blue,Y(e),n);console.log(`${o} ${i}
118
+ `);else{let o=T(s=>(0,D.inverse)((0,D.blue)(s)),`${T(D.hidden,"[",n)}info${T(D.hidden,"]",n)}`,n),i=T(D.blue,Y(e),n);console.log(`${o} ${i}
119
119
  `)}};function W(e,t,n){if(t&&typeof e!="string"){console.error(`${JSON.stringify(e.toResponse(),null,2)}
120
- `);return}let o=O(a=>(0,D.inverse)((0,D.red)(a)),`${O(D.hidden,"[",n)}error${O(D.hidden,"]",n)}`,n),i=typeof e=="string"?e:e.message,s=O(D.red,Y(i),n);console.error(`${o} ${s}
121
- `)}var Cn=(e,t="details",n)=>{if(e==null||e===0)return"-";let o=new Date(e*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return t==="table"?o.replace(/T/,O(D.hidden,"T",n)).replace(/Z$/,O(D.hidden,"Z",n)):o},Le=(e,t,n="details",o)=>{if(t===null||Array.isArray(t)&&t.length===0)return"-";if(typeof t=="number"&&(e==="created"||e==="activated"||e==="expires"||e==="linked"||e==="grace"||e==="used"))return Cn(t,n,o);if(e==="size"&&typeof t=="number"){let i=t/1048576;return i>=1?`${i.toFixed(1)}Mb`:`${(t/1024).toFixed(1)}Kb`}if(e==="config"||e==="password"){if(typeof t=="boolean")return t?"yes":"no";if(typeof t=="number")return t===1?"yes":"no"}if(wn(t)){let i=Object.entries(t);return i.length===0?"-":i.map(([s,a])=>`${s}=${Le(s,a,n,o)}`).join(", ")}return String(t)},J=(e,t,n,o)=>{if(!e||e.length===0)return"";let i=e[0],s=t||Object.keys(i).filter(m=>i[m]!==void 0&&!pt.includes(m)),a=e.map(m=>{let d=m,r={};return s.forEach(c=>{c in d&&d[c]!==void 0&&(r[c]=Le(c,d[c],"table",n))}),r});return`${(0,_e.default)(a,{columnSplitter:" ",columns:s,config:s.reduce((m,d)=>(m[d]={headingTransform:r=>O(D.dim,o?.[r]||r,n)},m),{})}).split(`
122
- `).map(m=>m.replace(/\0/g,"").replace(/\s+$/,"")).join(`
120
+ `);return}let o=T(a=>(0,D.inverse)((0,D.red)(a)),`${T(D.hidden,"[",n)}error${T(D.hidden,"]",n)}`,n),i=typeof e=="string"?e:e.message,s=T(D.red,Y(i),n);console.error(`${o} ${s}
121
+ `)}var On=(e,t="details",n)=>{if(e==null||e===0)return"-";let o=new Date(e*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return t==="table"?o.replace(/T/,T(D.hidden,"T",n)).replace(/Z$/,T(D.hidden,"Z",n)):o},Pe=(e,t,n="details",o)=>{if(t===null||Array.isArray(t)&&t.length===0)return"-";if(typeof t=="number"&&(e==="created"||e==="activated"||e==="expires"||e==="linked"||e==="grace"||e==="used"))return On(t,n,o);if(e==="size"&&typeof t=="number"){let i=t/1048576;return i>=1?`${i.toFixed(1)}Mb`:`${(t/1024).toFixed(1)}Kb`}if(e==="config"||e==="password"){if(typeof t=="boolean")return t?"yes":"no";if(typeof t=="number")return t===1?"yes":"no"}if(wn(t)){let i=Object.entries(t);return i.length===0?"-":i.map(([s,a])=>`${s}=${Pe(s,a,n,o)}`).join(", ")}return String(t)},J=(e,t,n,o)=>{if(!e||e.length===0)return"";let i=e[0],s=t||Object.keys(i).filter(u=>i[u]!==void 0&&!pt.includes(u)),a=e.map(u=>{let d=u,r={};return s.forEach(c=>{c in d&&d[c]!==void 0&&(r[c]=Pe(c,d[c],"table",n))}),r});return`${(0,Le.default)(a,{columnSplitter:" ",columns:s,config:s.reduce((u,d)=>(u[d]={headingTransform:r=>T(D.dim,o?.[r]||r,n)},u),{})}).split(`
122
+ `).map(u=>u.replace(/\0/g,"").replace(/\s+$/,"")).join(`
123
123
  `)}
124
- `},U=(e,t)=>{let n=Object.entries(e).filter(([s,a])=>pt.includes(s)?!1:a!==void 0);if(n.length===0)return"";let o=n.map(([s,a])=>({property:`${s}:`,value:Le(s,a,"details",t)}));return`${(0,_e.default)(o,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>O(D.dim,s,t)}}}).split(`
124
+ `},U=(e,t)=>{let n=Object.entries(e).filter(([s,a])=>pt.includes(s)?!1:a!==void 0);if(n.length===0)return"";let o=n.map(([s,a])=>({property:`${s}:`,value:Pe(s,a,"details",t)}));return`${(0,Le.default)(o,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>T(D.dim,s,t)}}}).split(`
125
125
  `).map(s=>s.replace(/\0/g,"")).join(`
126
126
  `)}
127
- `};function ct(){let e=process.env.SHELL||"";return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":null}function dt(e,t){switch(e){case"bash":return{completionFile:j.join(t,".ship_completion.bash"),profileFile:j.join(t,".bash_profile")};case"zsh":return{completionFile:j.join(t,".ship_completion.zsh"),profileFile:j.join(t,".zshrc")};case"fish":return{completionFile:j.join(t,".config/fish/completions/ship.fish"),profileFile:null}}}function mt(e,t={}){let{json:n,noColor:o}=t,i=ct(),s=Pe.homedir();if(!i)throw p.config(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`);let a=dt(i,s),l=lt(e,i);try{if(i==="fish"){let d=j.dirname(a.completionFile);b.existsSync(d)||b.mkdirSync(d,{recursive:!0}),b.writeFileSync(a.completionFile,l),k("fish completion installed successfully",n,o),M("please restart your shell to apply the changes",n,o);return}b.writeFileSync(a.completionFile,l);let m=`# ship
127
+ `};function ct(){let e=process.env.SHELL||"";return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":null}function dt(e,t){switch(e){case"bash":return{completionFile:j.join(t,".ship_completion.bash"),profileFile:j.join(t,".bash_profile")};case"zsh":return{completionFile:j.join(t,".ship_completion.zsh"),profileFile:j.join(t,".zshrc")};case"fish":return{completionFile:j.join(t,".config/fish/completions/ship.fish"),profileFile:null}}}function mt(e,t={}){let{json:n,noColor:o}=t,i=ct(),s=_e.homedir();if(!i)throw p.config(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`);let a=dt(i,s),l=lt(e,i);try{if(i==="fish"){let d=j.dirname(a.completionFile);w.existsSync(d)||w.mkdirSync(d,{recursive:!0}),w.writeFileSync(a.completionFile,l),k("fish completion installed successfully",n,o),M("please restart your shell to apply the changes",n,o);return}w.writeFileSync(a.completionFile,l);let u=`# ship
128
128
  source '${a.completionFile}'
129
129
  # ship end
130
- `;if(a.profileFile){if(b.existsSync(a.profileFile)){let d=b.readFileSync(a.profileFile,"utf-8");if(!d.includes("# ship")||!d.includes("# ship end")){let r=d.length>0&&!d.endsWith(`
130
+ `;if(a.profileFile){if(w.existsSync(a.profileFile)){let d=w.readFileSync(a.profileFile,"utf-8");if(!d.includes("# ship")||!d.includes("# ship end")){let r=d.length>0&&!d.endsWith(`
131
131
  `)?`
132
- `:"";b.appendFileSync(a.profileFile,r+m)}}else b.writeFileSync(a.profileFile,m);k(`completion script installed for ${i}`,n,o),ae(`run "source ${a.profileFile}" or restart your shell`,n,o)}}catch(m){if(A(m))throw m;let d=m instanceof Error?m.message:String(m);throw p.file(`could not install completion script: ${d}`)}}function ut(e={}){let{json:t,noColor:n}=e,o=ct(),i=Pe.homedir();if(!o)throw p.config(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`);let s=dt(o,i);try{if(o==="fish"){b.existsSync(s.completionFile)?(b.unlinkSync(s.completionFile),k("fish completion uninstalled successfully",t,n)):ae("fish completion was not installed",t,n),M("please restart your shell to apply the changes",t,n);return}if(b.existsSync(s.completionFile)&&b.unlinkSync(s.completionFile),!s.profileFile)return;if(!b.existsSync(s.profileFile))throw p.config("profile file not found");let l=b.readFileSync(s.profileFile,"utf-8").split(`
133
- `),m=[],d=0,r=!1;for(;d<l.length;)if(l[d].trim()==="# ship"){for(r=!0,d++;d<l.length&&l[d].trim()!=="# ship end";)d++;d<l.length&&d++}else m.push(l[d]),d++;if(r)b.writeFileSync(s.profileFile,m.join(`
134
- `)),k(`completion script uninstalled for ${o}`,t,n),ae(`run "source ${s.profileFile}" or restart your shell`,t,n);else throw p.config("completion was not found in profile")}catch(a){if(A(a))throw a;let l=a instanceof Error?a.message:String(a);throw p.file(`could not uninstall completion script: ${l}`)}}var I=require("fs"),gt=require("os"),yt=require("path"),Dt=require("readline/promises");w();var le=require("yoctocolors"),B=(0,yt.join)((0,gt.homedir)(),".shiprc");function ft(e){return e.length<13?"...":`${e.slice(0,9)}...${e.slice(-4)}`}function ht(){try{return(0,I.existsSync)(B)?JSON.parse((0,I.readFileSync)(B,"utf-8")):{}}catch{return{}}}async function St(e={}){let{noColor:t,json:n}=e,o=r=>t?r:(0,le.dim)(r),i=r=>t?r:(0,le.green)(r);if(n){let r=ht(),c=typeof r.token=="string"?r.token:void 0,u=typeof r.apiUrl=="string"?r.apiUrl:void 0;console.log(`${JSON.stringify({path:B,exists:(0,I.existsSync)(B),...c?{token:ft(c)}:{},...u&&u!==ne?{apiUrl:u}:{}},null,2)}
135
- `);return}let s=ht(),a=typeof s.token=="string"?s.token:void 0,l=(0,Dt.createInterface)({input:process.stdin,output:process.stdout});console.log(""),console.log(` ${o("Create a free API key at")} https://my.shipstatic.com/api-key`),console.log("");let m=a?` Token (${o(ft(a))}): `:" Token: ",d;try{d=(await l.question(m)).trim()}finally{l.close()}d&&(H(d),s.token=d),(0,I.writeFileSync)(B,`${JSON.stringify(s,null,2)}
132
+ `:"";w.appendFileSync(a.profileFile,r+u)}}else w.writeFileSync(a.profileFile,u);k(`completion script installed for ${i}`,n,o),ae(`run "source ${a.profileFile}" or restart your shell`,n,o)}}catch(u){if(A(u))throw u;let d=u instanceof Error?u.message:String(u);throw p.file(`could not install completion script: ${d}`)}}function ut(e={}){let{json:t,noColor:n}=e,o=ct(),i=_e.homedir();if(!o)throw p.config(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`);let s=dt(o,i);try{if(o==="fish"){w.existsSync(s.completionFile)?(w.unlinkSync(s.completionFile),k("fish completion uninstalled successfully",t,n)):ae("fish completion was not installed",t,n),M("please restart your shell to apply the changes",t,n);return}if(w.existsSync(s.completionFile)&&w.unlinkSync(s.completionFile),!s.profileFile)return;if(!w.existsSync(s.profileFile))throw p.config("profile file not found");let l=w.readFileSync(s.profileFile,"utf-8").split(`
133
+ `),u=[],d=0,r=!1;for(;d<l.length;)if(l[d].trim()==="# ship"){for(r=!0,d++;d<l.length&&l[d].trim()!=="# ship end";)d++;d<l.length&&d++}else u.push(l[d]),d++;if(r)w.writeFileSync(s.profileFile,u.join(`
134
+ `)),k(`completion script uninstalled for ${o}`,t,n),ae(`run "source ${s.profileFile}" or restart your shell`,t,n);else throw p.config("completion was not found in profile")}catch(a){if(A(a))throw a;let l=a instanceof Error?a.message:String(a);throw p.file(`could not uninstall completion script: ${l}`)}}var I=require("fs"),gt=require("os"),yt=require("path"),Dt=require("readline/promises");b();var le=require("yoctocolors"),B=(0,yt.join)((0,gt.homedir)(),".shiprc");function ft(e){return e.length<13?"...":`${e.slice(0,9)}...${e.slice(-4)}`}function ht(){try{return(0,I.existsSync)(B)?JSON.parse((0,I.readFileSync)(B,"utf-8")):{}}catch{return{}}}async function St(e={}){let{noColor:t,json:n}=e,o=r=>t?r:(0,le.dim)(r),i=r=>t?r:(0,le.green)(r);if(n){let r=ht(),c=typeof r.token=="string"?r.token:void 0,m=typeof r.apiUrl=="string"?r.apiUrl:void 0;console.log(`${JSON.stringify({path:B,exists:(0,I.existsSync)(B),...c?{token:ft(c)}:{},...m&&m!==ne?{apiUrl:m}:{}},null,2)}
135
+ `);return}let s=ht(),a=typeof s.token=="string"?s.token:void 0,l=(0,Dt.createInterface)({input:process.stdin,output:process.stdout});console.log(""),console.log(` ${o("Create a free API key at")} https://my.shipstatic.com/api-key`),console.log("");let u=a?` Token (${o(ft(a))}): `:" Token: ",d;try{d=(await l.question(u)).trim()}finally{l.close()}d&&(H(d),s.token=d),(0,I.writeFileSync)(B,`${JSON.stringify(s,null,2)}
136
136
  `,{mode:384}),(0,I.chmodSync)(B,384),console.log(`
137
137
  ${i("saved to")} ${o(B)}
138
- `)}w();w();w();var pe=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 o=this.handlers.get(t);o&&(o.delete(n),o.size===0&&this.handlers.delete(t))}emit(t,...n){let o=this.handlers.get(t);if(!o)return;let i=Array.from(o);for(let s of i)try{s(...n)}catch(a){o.delete(s),t!=="error"&&setTimeout(()=>{let l=a instanceof Error?a:new Error(String(a));this.emit("error",l,String(t))},0)}}};w();w();function Z(e){if(e==null)return;if(e.length===0)return e;if(e.length>F.MAX_COUNT)throw p.validation(`Maximum ${F.MAX_COUNT} labels allowed`);let t=e.map((o,i)=>{if(typeof o!="string")throw p.validation(`Label at index ${i} must be a string`);let s=o.trim().toLowerCase();if(s.length<F.MIN_LENGTH)throw p.validation(`Labels must be at least ${F.MIN_LENGTH} characters long`);if(s.length>F.MAX_LENGTH)throw p.validation(`Labels must be no more than ${F.MAX_LENGTH} characters long`);if(!it.test(s))throw p.validation(`Labels must start and end with alphanumeric characters, with optional separators (${F.SEPARATORS}) between segments`);return s}),n=[...new Set(t)];if(n.length!==t.length)throw p.validation("Duplicate labels are not allowed");return n}async function Et(e){let t=e.find(i=>i.path===P||i.path===`/${P}`);if(!t)return;let n=t.content,o=typeof n.text=="function"?await n.text():t.content.toString("utf8");et(o)}var On=3e4,bt=3e5,Rn=3e5,An=bt+Rn,$n="sdk";function ke(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}`:""}var ce=class extends pe{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||ne,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??On,this.deployTimeout=n.timeout??bt,this.deployBuildTimeout=n.timeout??An,this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.createDeployBody=n.createDeployBody,this.deployEndpoint=n.deployEndpoint||E.DEPLOYMENTS}setGlobalHeaders(n){this.globalHeaders=n}async executeRequest(n,o,i,s=this.timeout){let a=()=>{};try{let l=await this.mergeHeaders(o.headers),m=this.createTimeoutSignal(o.signal,s);a=m.cleanup;let d={...o,headers:l,credentials:this.session&&!l.Authorization?"include":void 0,signal:m.signal};this.emit("request",n,d);let r=await this.fetch(n,d);if(a(),!r.ok)throw await p.fromHttpResponse(r,i);return this.emit("response",this.safeClone(r),n),{data:await this.parseResponse(this.safeClone(r)),status:r.status}}catch(l){a();let m=p.fromFetchError(l,i);throw this.emit("error",m,n),m}}async request(n,o,i,s){let{data:a}=await this.executeRequest(n,o,i,s);return a}async requestWithStatus(n,o,i){return this.executeRequest(n,o,i)}async mergeHeaders(n={}){return{...this.globalHeaders,...this.caller?{"X-Caller":this.caller}:{},...await this.getAuthHeadersCallback(),...n}}createTimeoutSignal(n,o=this.timeout){let i=new AbortController,s=setTimeout(()=>i.abort(),o);if(n){let a=()=>i.abort();n.addEventListener("abort",a),n.aborted&&i.abort()}return{signal:i.signal,cleanup:()=>clearTimeout(s)}}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()}async deploy(n,o={}){if(!n.length)throw p.business("No files to deploy");for(let d of n)if(!d.md5)throw p.file(`MD5 checksum missing for file: ${d.path}`,{filePath:d.path});Oe(o.password);let i=We(o.idempotencyKey),s=Z(o.labels);await Et(n);let a=o.build||o.prerender||o.spa?{build:o.build,prerender:o.prerender,spa:o.spa}:void 0,{body:l,headers:m}=await this.createDeployBody(n,{labels:s,via:o.via??$n,password:o.password,flags:a,captcha:o.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:l,headers:i?{...m,"Idempotency-Key":i}:m,signal:o.signal||null},"Deploy",o.build||o.prerender?this.deployBuildTimeout:this.deployTimeout)}async listDeployments(n){return this.request(`${this.apiUrl}${E.DEPLOYMENTS}${ke(n)}`,{method:"GET"},"List deployments")}async getDeployment(n){return this.request(`${this.apiUrl}${E.DEPLOYMENT(encodeURIComponent(n))}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(n,o){let i=Z(o);return this.request(`${this.apiUrl}${E.DEPLOYMENT(encodeURIComponent(n))}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:i})},"Update deployment labels")}async deleteDeployment(n){return this.request(`${this.apiUrl}${E.DEPLOYMENT(encodeURIComponent(n))}`,{method:"DELETE"},"Delete deployment")}async setDomain(n,o,i){let s=Z(i),a={};o&&(a.deployment=o),s!==void 0&&(a.labels=s);let{data:l,status:m}=await this.requestWithStatus(`${this.apiUrl}${E.DOMAIN(encodeURIComponent(n))}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)},"Set domain");return{...l,isCreate:m===201}}async listDomains(n){return this.request(`${this.apiUrl}${E.DOMAINS}${ke(n)}`,{method:"GET"},"List domains")}async getDomain(n){return this.request(`${this.apiUrl}${E.DOMAIN(encodeURIComponent(n))}`,{method:"GET"},"Get domain")}async deleteDomain(n){return this.request(`${this.apiUrl}${E.DOMAIN(encodeURIComponent(n))}`,{method:"DELETE"},"Delete domain")}async verifyDomain(n){return this.request(`${this.apiUrl}${E.DOMAIN_VERIFY(encodeURIComponent(n))}`,{method:"POST"},"Verify domain")}async getDomainDns(n){return this.request(`${this.apiUrl}${E.DOMAIN_DNS(encodeURIComponent(n))}`,{method:"GET"},"Get domain DNS")}async getDomainRecords(n){return this.request(`${this.apiUrl}${E.DOMAIN_RECORDS(encodeURIComponent(n))}`,{method:"GET"},"Get domain records")}async getDomainShare(n){return this.request(`${this.apiUrl}${E.DOMAIN_SHARE(encodeURIComponent(n))}`,{method:"GET"},"Get domain share")}async validateDomain(n){return this.request(`${this.apiUrl}${E.DOMAINS_VALIDATE}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:n})},"Validate domain")}async createToken(n,o){let i=Z(o),s={};return n!==void 0&&(s.ttl=n),i!==void 0&&(s.labels=i),this.request(`${this.apiUrl}${E.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(n){return this.request(`${this.apiUrl}${E.TOKENS}${ke(n)}`,{method:"GET"},"List tokens")}async deleteToken(n){return this.request(`${this.apiUrl}${E.TOKEN(encodeURIComponent(n))}`,{method:"DELETE"},"Delete token")}async getToken(n){return this.request(`${this.apiUrl}${E.TOKEN(encodeURIComponent(n))}`,{method:"GET"},"Get token")}async getAccount(){return this.request(`${this.apiUrl}${E.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${E.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return this.request(`${this.apiUrl}${E.PING}`,{method:"GET"},"Ping")}async checkSPA(n,o={}){let i=n.find(m=>m.path==="index.html"||m.path==="/index.html");if(!i||i.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(i.content))s=i.content.toString("utf-8");else if(typeof Blob<"u"&&i.content instanceof Blob)s=await i.content.text();else if(typeof File<"u"&&i.content instanceof File)s=await i.content.text();else return!1;let a={files:n.map(m=>m.path),index:s};return(await this.request(`${this.apiUrl}${E.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)},"SPA check")).isSPA}};w();w();Ie();async function Ln(){let e=JSON.stringify(Qe,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await de(t);return{path:P,content:t,size:e.length,md5:n}}async function wt(e,t,n){if(n.spaDetect===!1||n.spa||n.build||n.prerender||e.some(o=>o.path===P))return e;try{if(await t.checkSPA(e,n)){let i=await Ln();return[...e,i]}}catch{}return e}function Tt(e){let{getApi:t,ensureInit:n,processInput:o}=e;return{upload:async(i,s={})=>{if(await n(),!o)throw p.config("processInput function is not provided.");let a=t(),l=await o(i,s);return l=await wt(l,a,s),a.deploy(l,s)},list:async i=>(await n(),t().listDeployments(i)),get:async i=>(await n(),t().getDeployment(i)),set:async(i,s)=>(await n(),t().updateDeploymentLabels(i,s.labels)),delete:async i=>(await n(),t().deleteDeployment(i))}}function Ct(e){let{getApi:t,ensureInit:n}=e;return{set:async(o,i={})=>(await n(),t().setDomain(o,i.deployment,i.labels)),list:async o=>(await n(),t().listDomains(o)),get:async o=>(await n(),t().getDomain(o)),delete:async o=>(await n(),t().deleteDomain(o)),verify:async o=>(await n(),t().verifyDomain(o)),validate:async o=>(await n(),t().validateDomain(o)),dns:async o=>(await n(),t().getDomainDns(o)),records:async o=>(await n(),t().getDomainRecords(o)),share:async o=>(await n(),t().getDomainShare(o))}}function Ot(e){let{getApi:t,ensureInit:n}=e;return{get:async()=>(await n(),t().getAccount())}}function Rt(e){let{getApi:t,ensureInit:n}=e;return{create:async(o={})=>(await n(),t().createToken(o.ttl,o.labels)),list:async o=>(await n(),t().listTokens(o)),get:async o=>(await n(),t().getToken(o)),delete:async o=>(await n(),t().deleteToken(o))}}var me=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&&nt(t.caller),t.token&&t.session)throw p.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(H(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new ce({...t,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=Tt({...n,processInput:(o,i)=>this.processInput(o,i)}),this.domains=Ct(n),this.account=Ot(n),this.tokens=Rt(n)}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,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 p.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw p.business("Invalid token provided. Token must be a non-empty string.");H(t),this.credential=t;return}if(typeof t!="function")throw p.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 p.authentication("Token provider returned no token.");if(typeof t!="string")throw p.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};ie();w();async function At(e,t={}){let{FormData:n,File:o}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),{labels:s,via:a,password:l,flags:m,captcha:d}=t,r=new n,c=[];for(let f of e){if(!Buffer.isBuffer(f.content)&&!(typeof Blob<"u"&&f.content instanceof Blob))throw p.file(`Unsupported file.content type for Node.js: ${f.path}`,{filePath:f.path});if(!f.md5)throw p.file(`File missing md5 checksum: ${f.path}`,{filePath:f.path});let y=new o([f.content],f.path,{type:"application/octet-stream"});r.append("files[]",y),c.push(f.md5)}r.append("checksums",JSON.stringify(c)),s&&s.length>0&&r.append("labels",JSON.stringify(s)),a&&r.append("via",a),l&&r.append("password",l),m?.build&&r.append("build","true"),m?.prerender&&r.append("prerender","true"),m?.spa&&r.append("spa","true"),d&&r.append("captcha",d);let u=new i(r),h=[];for await(let f of u.encode())h.push(Buffer.from(f));let S=Buffer.concat(h);return{body:S.buffer.slice(S.byteOffset,S.byteOffset+S.byteLength),headers:{"Content-Type":u.contentType,"Content-Length":Buffer.byteLength(S).toString()}}}var fe=class extends me{constructor(t={}){if(q()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");let n=K();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 o=typeof t=="string"?[t]:t;if(!Array.isArray(o)||!o.every(s=>typeof s=="string"))throw p.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw p.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(Gt(),jt));return i(o,n,this.platformLimits??void 0)}getDeployBodyCreator(){return At}};var Ht=require("os");w();var Bt=require("cosmiconfig"),Ue=require("zod");var Nn=Ue.z.object(oe).strict(),Me="ship";function he(e){let t=e||void 0,n=(0,Ht.homedir)(),o=(0,Bt.cosmiconfigSync)(Me,{searchPlaces:[`.${Me}rc`,"package.json",`${n}/.${Me}rc`],stopDir:n}),i;try{i=t?o.load(t):o.search()}catch(s){if(A(s))throw s;let a=s instanceof Error?s.message:String(s),l=t?` (${t})`:"";throw p.config(`Failed to read ship config${l}: ${a}`)}if(!i?.config)return{};try{return Nn.parse(i.config)}catch(s){if(s instanceof Ue.z.ZodError){let a=s.issues[0];if(a.code==="unrecognized_keys"){let m=a.keys.filter(d=>d==="apiKey"||d==="deployToken");if(m.length>0){let d=m.map(r=>`"${r}"`).join(" and ");throw p.config(`Invalid config in ${i.filepath}: ${d} ${m.length>1?"are":"is"} no longer supported \u2014 the key is now "token". Run \`ship config\` to rewrite it.`)}}let l=a.path.length>0?` at ${a.path.join(".")}`:"";throw p.config(`Invalid config in ${i.filepath}${l}: ${a.message}`)}throw p.config(`Invalid config in ${i.filepath}`)}}function je(e,t,n){return{apiUrl:e.apiUrl||t.apiUrl||n.apiUrl,token:e.token||t.token||n.token}}function zt(e={}){return new fe(je(e,K(),he(e.config)))}w();function Vt(e){return A(e)?e:e instanceof Error?p.business(e.message):p.business(String(e??"Unknown error"))}function qt(e,t,n){return e.isAuthError()?n?.token?"authentication failed: invalid or expired token":"authentication required: pass --token, set SHIP_TOKEN, or run ship config":e.isNetworkError()?"network error: could not reach the API. check your internet connection":e.isClientError()?e.message:`${e.message.replace(/\.$/,"")} \u2014 try again, or check https://status.shipstatic.com`}var He=(e,t)=>`https://setup.shipstatic.com/${e}/${t}`;function Ge(e,t){return e[t]}var Fn={deleting:"served until cleanup completes"},Mn={upload:"uploaded",create:"created",delete:"deleted",verify:"verification queued"},Un=new Set(["delete","verify"]);function jn(e,t){let{operation:n,resourceType:o}=t;if(!n||!o||e===null||typeof e!="object")return null;let i=o.toLowerCase(),s=n==="set"?Ge(e,"isCreate")?"created":"updated":Mn[n];if(!s)return null;let a=Ge(e,i);if(typeof a!="string")return null;let l=Ge(e,"status"),m=typeof l=="string"?Fn[l]:void 0;return`${a} ${i} ${m?`${l} \u2014 ${m}`:s}`}function Gn(e,t,n){let{noColor:o}=n;if(e.deployments.length===0){console.log("no deployments found"),console.log();return}let i=["deployment","labels","files","size","created","via"];console.log(J(e.deployments,i,o)),Be(e.cursor,o)}function Be(e,t){e&&M(`more results available \u2014 rerun with --cursor ${e}`,!1,t)}function Hn(e,t,n){let{noColor:o}=n;if(e.domains.length===0){console.log("no domains found"),console.log();return}let i=["domain","deployment","labels","linked","links","created"];console.log(J(e.domains,i,o)),Be(e.cursor,o)}function Bn(e,t,n){let{noColor:o}=n,{_dnsRecords:i,_shareHash:s,isCreate:a,...l}=e;i&&i.length>0&&(console.log(),M("DNS records to configure:",!1,o),i.forEach(m=>{console.log(` ${m.type}: ${m.name} \u2192 ${m.value}`)})),s&&(console.log(),M(`Setup instructions: ${He(s,e.domain)}`,!1,o)),console.log(U(l,o))}function zn(e,t,n){let{noColor:o}=n;console.log(U(e,o));let i=e.claim;if(i){let s=e.expires?Math.round((e.expires-e.created)/86400):null;console.log(`IMPORTANT: this deployment${s?` expires in ${s} day${s!==1?"s":""}`:" will expire"}, claim it to keep permanently:
138
+ `)}b();b();b();var pe=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 o=this.handlers.get(t);o&&(o.delete(n),o.size===0&&this.handlers.delete(t))}emit(t,...n){let o=this.handlers.get(t);if(!o)return;let i=Array.from(o);for(let s of i)try{s(...n)}catch(a){o.delete(s),t!=="error"&&setTimeout(()=>{let l=a instanceof Error?a:new Error(String(a));this.emit("error",l,String(t))},0)}}};b();b();function Z(e){if(e==null)return;if(e.length===0)return e;if(e.length>F.MAX_COUNT)throw p.validation(`Maximum ${F.MAX_COUNT} labels allowed`);let t=e.map((o,i)=>{if(typeof o!="string")throw p.validation(`Label at index ${i} must be a string`);let s=o.trim().toLowerCase();if(s.length<F.MIN_LENGTH)throw p.validation(`Labels must be at least ${F.MIN_LENGTH} characters long`);if(s.length>F.MAX_LENGTH)throw p.validation(`Labels must be no more than ${F.MAX_LENGTH} characters long`);if(!it.test(s))throw p.validation(`Labels must start and end with alphanumeric characters, with optional separators (${F.SEPARATORS}) between segments`);return s}),n=[...new Set(t)];if(n.length!==t.length)throw p.validation("Duplicate labels are not allowed");return n}async function Et(e){let t=e.find(i=>i.path===_||i.path===`/${_}`);if(!t)return;let n=t.content,o=typeof n.text=="function"?await n.text():t.content.toString("utf8");et(o)}var Tn=3e4,bt=3e5,Rn=3e5,An=bt+Rn,$n="sdk";function ke(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}`:""}var ce=class extends pe{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||ne,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??Tn,this.deployTimeout=n.timeout??bt,this.deployBuildTimeout=n.timeout??An,this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.createDeployBody=n.createDeployBody,this.deployEndpoint=n.deployEndpoint||S.DEPLOYMENTS}setGlobalHeaders(n){this.globalHeaders=n}async executeRequest(n,o,i,s=this.timeout){let a=()=>{};try{let l=await this.mergeHeaders(o.headers),u=this.createTimeoutSignal(o.signal,s);a=u.cleanup;let d={...o,headers:l,credentials:this.session&&!l.Authorization?"include":void 0,signal:u.signal};this.emit("request",n,d);let r=await this.fetch(n,d);if(a(),!r.ok)throw await p.fromHttpResponse(r,i);return this.emit("response",this.safeClone(r),n),{data:await this.parseResponse(this.safeClone(r)),status:r.status}}catch(l){a();let u=p.fromFetchError(l,i);throw this.emit("error",u,n),u}}async request(n,o,i,s){let{data:a}=await this.executeRequest(n,o,i,s);return a}async requestWithStatus(n,o,i){return this.executeRequest(n,o,i)}async mergeHeaders(n={}){return{...this.globalHeaders,...this.caller?{"X-Caller":this.caller}:{},...await this.getAuthHeadersCallback(),...n}}createTimeoutSignal(n,o=this.timeout){let i=new AbortController,s=setTimeout(()=>i.abort(),o);if(n){let a=()=>i.abort();n.addEventListener("abort",a),n.aborted&&i.abort()}return{signal:i.signal,cleanup:()=>clearTimeout(s)}}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()}async deploy(n,o={}){if(!n.length)throw p.business("No files to deploy");for(let d of n)if(!d.md5)throw p.file(`MD5 checksum missing for file: ${d.path}`,{filePath:d.path});Te(o.password);let i=We(o.idempotencyKey),s=Z(o.labels);await Et(n);let a=o.build||o.prerender||o.spa?{build:o.build,prerender:o.prerender,spa:o.spa}:void 0,{body:l,headers:u}=await this.createDeployBody(n,{labels:s,via:o.via??$n,password:o.password,flags:a,captcha:o.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:l,headers:i?{...u,"Idempotency-Key":i}:u,signal:o.signal||null},"Deploy",o.build||o.prerender?this.deployBuildTimeout:this.deployTimeout)}async listDeployments(n){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}${ke(n)}`,{method:"GET"},"List deployments")}async getDeployment(n){return this.request(`${this.apiUrl}${S.DEPLOYMENT(encodeURIComponent(n))}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(n,o){let i=Z(o);return this.request(`${this.apiUrl}${S.DEPLOYMENT(encodeURIComponent(n))}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:i})},"Update deployment labels")}async deleteDeployment(n){return this.request(`${this.apiUrl}${S.DEPLOYMENT(encodeURIComponent(n))}`,{method:"DELETE"},"Delete deployment")}async setDomain(n,o,i){let s=Z(i),a={};o&&(a.deployment=o),s!==void 0&&(a.labels=s);let{data:l,status:u}=await this.requestWithStatus(`${this.apiUrl}${S.DOMAIN(encodeURIComponent(n))}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)},"Set domain");return{...l,isCreate:u===201}}async listDomains(n){return this.request(`${this.apiUrl}${S.DOMAINS}${ke(n)}`,{method:"GET"},"List domains")}async getDomain(n){return this.request(`${this.apiUrl}${S.DOMAIN(encodeURIComponent(n))}`,{method:"GET"},"Get domain")}async deleteDomain(n){return this.request(`${this.apiUrl}${S.DOMAIN(encodeURIComponent(n))}`,{method:"DELETE"},"Delete domain")}async verifyDomain(n){return this.request(`${this.apiUrl}${S.DOMAIN_VERIFY(encodeURIComponent(n))}`,{method:"POST"},"Verify domain")}async getDomainDns(n){return this.request(`${this.apiUrl}${S.DOMAIN_DNS(encodeURIComponent(n))}`,{method:"GET"},"Get domain DNS")}async getDomainRecords(n){return this.request(`${this.apiUrl}${S.DOMAIN_RECORDS(encodeURIComponent(n))}`,{method:"GET"},"Get domain records")}async getDomainShare(n){return this.request(`${this.apiUrl}${S.DOMAIN_SHARE(encodeURIComponent(n))}`,{method:"GET"},"Get domain share")}async validateDomain(n){return this.request(`${this.apiUrl}${S.DOMAINS_VALIDATE}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:n})},"Validate domain")}async createToken(n,o){let i=Z(o),s={};return n!==void 0&&(s.ttl=n),i!==void 0&&(s.labels=i),this.request(`${this.apiUrl}${S.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(n){return this.request(`${this.apiUrl}${S.TOKENS}${ke(n)}`,{method:"GET"},"List tokens")}async deleteToken(n){return this.request(`${this.apiUrl}${S.TOKEN(encodeURIComponent(n))}`,{method:"DELETE"},"Delete token")}async getToken(n){return this.request(`${this.apiUrl}${S.TOKEN(encodeURIComponent(n))}`,{method:"GET"},"Get token")}async getAccount(){return this.request(`${this.apiUrl}${S.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${S.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return this.request(`${this.apiUrl}${S.PING}`,{method:"GET"},"Ping")}async checkSPA(n,o={}){let i=n.find(u=>u.path==="index.html"||u.path==="/index.html");if(!i||i.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(i.content))s=i.content.toString("utf-8");else if(typeof Blob<"u"&&i.content instanceof Blob)s=await i.content.text();else if(typeof File<"u"&&i.content instanceof File)s=await i.content.text();else return!1;let a={files:n.map(u=>u.path),index:s};return(await this.request(`${this.apiUrl}${S.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)},"SPA check")).isSPA}};b();b();Ie();async function Pn(){let e=JSON.stringify(Qe,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await de(t);return{path:_,content:t,size:e.length,md5:n}}async function wt(e,t,n){if(n.spaDetect===!1||n.spa||n.build||n.prerender||e.some(o=>o.path===_))return e;try{if(await t.checkSPA(e,n)){let i=await Pn();return[...e,i]}}catch{}return e}function Ct(e){let{getApi:t,ensureInit:n,processInput:o}=e;return{upload:async(i,s={})=>{if(await n(),!o)throw p.config("processInput function is not provided.");let a=t(),l=await o(i,s);return l=await wt(l,a,s),a.deploy(l,s)},list:async i=>(await n(),t().listDeployments(i)),get:async i=>(await n(),t().getDeployment(i)),set:async(i,s)=>(await n(),t().updateDeploymentLabels(i,s.labels)),delete:async i=>(await n(),t().deleteDeployment(i))}}function Ot(e){let{getApi:t,ensureInit:n}=e;return{set:async(o,i={})=>(await n(),t().setDomain(o,i.deployment,i.labels)),list:async o=>(await n(),t().listDomains(o)),get:async o=>(await n(),t().getDomain(o)),delete:async o=>(await n(),t().deleteDomain(o)),verify:async o=>(await n(),t().verifyDomain(o)),validate:async o=>(await n(),t().validateDomain(o)),dns:async o=>(await n(),t().getDomainDns(o)),records:async o=>(await n(),t().getDomainRecords(o)),share:async o=>(await n(),t().getDomainShare(o))}}function Tt(e){let{getApi:t,ensureInit:n}=e;return{get:async()=>(await n(),t().getAccount())}}function Rt(e){let{getApi:t,ensureInit:n}=e;return{create:async(o={})=>(await n(),t().createToken(o.ttl,o.labels)),list:async o=>(await n(),t().listTokens(o)),get:async o=>(await n(),t().getToken(o)),delete:async o=>(await n(),t().deleteToken(o))}}var me=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&&nt(t.caller),t.token&&t.session)throw p.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(H(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new ce({...t,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=Ct({...n,processInput:(o,i)=>this.processInput(o,i)}),this.domains=Ot(n),this.account=Tt(n),this.tokens=Rt(n)}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,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 p.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw p.business("Invalid token provided. Token must be a non-empty string.");H(t),this.credential=t;return}if(typeof t!="function")throw p.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 p.authentication("Token provider returned no token.");if(typeof t!="string")throw p.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};ie();b();async function At(e,t={}){let{FormData:n,File:o}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),{labels:s,via:a,password:l,flags:u,captcha:d}=t,r=new n,c=[];for(let f of e){if(!Buffer.isBuffer(f.content)&&!(typeof Blob<"u"&&f.content instanceof Blob))throw p.file(`Unsupported file.content type for Node.js: ${f.path}`,{filePath:f.path});if(!f.md5)throw p.file(`File missing md5 checksum: ${f.path}`,{filePath:f.path});let y=new o([f.content],f.path,{type:"application/octet-stream"});r.append("files[]",y),c.push(f.md5)}r.append("checksums",JSON.stringify(c)),s&&s.length>0&&r.append("labels",JSON.stringify(s)),a&&r.append("via",a),l&&r.append("password",l),u?.build&&r.append("build","true"),u?.prerender&&r.append("prerender","true"),u?.spa&&r.append("spa","true"),d&&r.append("captcha",d);let m=new i(r),h=[];for await(let f of m.encode())h.push(Buffer.from(f));let E=Buffer.concat(h);return{body:E.buffer.slice(E.byteOffset,E.byteOffset+E.byteLength),headers:{"Content-Type":m.contentType,"Content-Length":Buffer.byteLength(E).toString()}}}var fe=class extends me{constructor(t={}){if(q()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");let n=K();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 o=typeof t=="string"?[t]:t;if(!Array.isArray(o)||!o.every(s=>typeof s=="string"))throw p.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw p.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(Gt(),jt));return i(o,n,this.platformLimits??void 0)}getDeployBodyCreator(){return At}};var Ht=require("os");b();var Bt=require("cosmiconfig"),Ue=require("zod");var Nn=Ue.z.object(oe).strict(),Me="ship";function he(e){let t=e||void 0,n=(0,Ht.homedir)(),o=(0,Bt.cosmiconfigSync)(Me,{searchPlaces:[`.${Me}rc`,"package.json",`${n}/.${Me}rc`],stopDir:n}),i;try{i=t?o.load(t):o.search()}catch(s){if(A(s))throw s;let a=s instanceof Error?s.message:String(s),l=t?` (${t})`:"";throw p.config(`Failed to read ship config${l}: ${a}`)}if(!i?.config)return{};try{return Nn.parse(i.config)}catch(s){if(s instanceof Ue.z.ZodError){let a=s.issues[0];if(a.code==="unrecognized_keys"){let u=a.keys.filter(d=>d==="apiKey"||d==="deployToken");if(u.length>0){let d=u.map(r=>`"${r}"`).join(" and ");throw p.config(`Invalid config in ${i.filepath}: ${d} ${u.length>1?"are":"is"} no longer supported \u2014 the key is now "token". Run \`ship config\` to rewrite it.`)}}let l=a.path.length>0?` at ${a.path.join(".")}`:"";throw p.config(`Invalid config in ${i.filepath}${l}: ${a.message}`)}throw p.config(`Invalid config in ${i.filepath}`)}}function je(e,t,n){return{apiUrl:e.apiUrl||t.apiUrl||n.apiUrl,token:e.token||t.token||n.token}}function zt(e={}){return new fe(je(e,K(),he(e.config)))}b();function Vt(e){return A(e)?e:e instanceof Error?p.business(e.message):p.business(String(e??"Unknown error"))}function qt(e,t){return e.isAuthError()?t?.token?"authentication failed: invalid or expired token":"authentication required: pass --token, set SHIP_TOKEN, or run ship config":e.isNetworkError()?"network error: could not reach the API. check your internet connection":e.isClientError()?e.message:`${e.message.replace(/\.$/,"")} \u2014 try again, or check https://status.shipstatic.com`}b();var He=(e,t)=>`https://setup.shipstatic.com/${e}/${t}`;function Ge(e,t){return e[t]}var Fn={[Ye.DELETING]:"served until cleanup completes"},Mn={upload:"uploaded",create:"created",delete:"deleted",verify:"verification queued"},Un=new Set(["delete","verify"]);function jn(e,t){let{operation:n,resource:o}=t;if(!n||!o||e===null||typeof e!="object")return null;let i=n==="set"?Ge(e,"isCreate")?"created":"updated":Mn[n];if(!i)return null;let s=Ge(e,o);if(typeof s!="string")return null;let a=Ge(e,"status"),l=typeof a=="string"?Fn[a]:void 0;return`${s} ${o} ${l?`${a} \u2014 ${l}`:i}`}function Gn(e,t,n){let{noColor:o}=n;if(e.deployments.length===0){console.log("no deployments found"),console.log();return}let i=["deployment","labels","files","size","created","via"];console.log(J(e.deployments,i,o)),Be(e.cursor,o)}function Be(e,t){e&&M(`more results available \u2014 rerun with --cursor ${e}`,!1,t)}function Hn(e,t,n){let{noColor:o}=n;if(e.domains.length===0){console.log("no domains found"),console.log();return}let i=["domain","deployment","labels","linked","links","created"];console.log(J(e.domains,i,o)),Be(e.cursor,o)}function Bn(e,t,n){let{noColor:o}=n,{_dnsRecords:i,_shareHash:s,isCreate:a,...l}=e;i&&i.length>0&&(console.log(),M("DNS records to configure:",!1,o),i.forEach(u=>{console.log(` ${u.type}: ${u.name} \u2192 ${u.value}`)})),s&&(console.log(),M(`Setup instructions: ${He(s,e.domain)}`,!1,o)),console.log(U(l,o))}function zn(e,t,n){let{noColor:o}=n;console.log(U(e,o));let i=e.claim;if(i){let s=e.expires?Math.round((e.expires-e.created)/86400):null;console.log(`IMPORTANT: this deployment${s?` expires in ${s} day${s!==1?"s":""}`:" will expire"}, claim it to keep permanently:
139
139
  ${i}
140
140
  `),M("configure a free API key with 'ship config' to deploy to your own account",!1,o)}}function Vn(e,t,n){let{noColor:o}=n;console.log(U(e,o))}function qn(e,t,n){let{noColor:o}=n;if(e.valid){if(k(`${e.normalized??"domain"} domain is valid`,!1,o),console.log(),e.available!==null){let i=e.available?o?"available":"available \u2713":"already taken";console.log(` availability: ${i}`)}console.log()}else console.log(`${Y(e.reason??"domain is invalid")}
141
141
  `)}function Kn(e,t,n){let{noColor:o}=n;if(e.records.length===0){console.log("no records found"),console.log();return}let i=["type","name","value"];console.log(J(e.records,i,o))}function Yn(e,t,n){let{noColor:o}=n,i=e.dns?.provider?.name||null;console.log(U({domain:e.domain,provider:i},o))}function Wn(e,t,n){let{noColor:o}=n;console.log(U({domain:e.domain,setup:He(e.hash,e.domain)},o))}function Xn(e,t,n){let{noColor:o}=n;if(e.tokens.length===0){console.log("no tokens found"),console.log();return}let i=["token","labels","created","expires"];console.log(J(e.tokens,i,o)),Be(e.cursor,o)}function Jn(e,t,n){let{noColor:o}=n;console.log(U(e,o))}function Kt(e,t,n){let{json:o,quiet:i,noColor:s}=n;if(i){if(e!==null&&typeof e=="object"){if("deployments"in e)for(let l of e.deployments)console.log(l.deployment);else if("domains"in e)for(let l of e.domains)console.log(l.domain);else if("tokens"in e)for(let l of e.tokens)console.log(l.token);else if("records"in e)for(let l of e.records)console.log(`${l.type} ${l.name} ${l.value}`);else if("hash"in e){let l=e;console.log(He(l.hash,l.domain))}else if("dns"in e){let l=e.dns?.provider?.name;l&&console.log(l)}else if("domain"in e)console.log(e.domain);else if("deployment"in e)console.log(e.deployment);else if("secret"in e)console.log(e.secret);else if("token"in e)console.log(e.token);else if("email"in e)console.log(e.email);else if("valid"in e){let l=e;l.valid&&l.normalized&&console.log(l.normalized)}}return}if(o&&e!==null&&typeof e=="object"){let l={...e};delete l._dnsRecords,delete l._shareHash,delete l.isCreate,console.log(JSON.stringify(l,null,2)),console.log();return}let a=jn(e,t);if(a&&k(a,!1,s),!(t.operation&&Un.has(t.operation))){if(t.operation==="ping"){k("api reachable",!1,s);return}e!==null&&typeof e=="object"&&("deployments"in e?Gn(e,t,n):"domains"in e?Hn(e,t,n):"tokens"in e?Xn(e,t,n):"records"in e?Kn(e,t,n):"hash"in e?Wn(e,t,n):"dns"in e?Yn(e,t,n):"domain"in e?Bn(e,t,n):"deployment"in e?zn(e,t,n):"token"in e?Jn(e,t,n):"email"in e?Vn(e,t,n):"valid"in e?qn(e,t,n):console.log(U(e,s)))}}function Zn(){let e=[Ve.resolve(__dirname,"../package.json"),Ve.resolve(__dirname,"../../package.json")];for(let t of e)try{return JSON.parse((0,z.readFileSync)(t,"utf-8"))}catch{}return{version:"0.0.0"}}var Qn=Zn();function eo(e){let t=s=>e?s:(0,ye.bold)(s),n=s=>e?s:(0,ye.dim)(s),o=s=>e?"":`${s} `;return`${t("USAGE")}
@@ -193,8 +193,7 @@ ${t("EXAMPLES")}
193
193
  ship ./dist -q | ship domains set www.example.com
194
194
 
195
195
  ${n("Please report any issues to https://github.com/shipstatic/ship/issues")}
196
- `}var ze=e=>new p(g.Validation,e);function Q(e,t=[]){return t.concat([e])}function ge(e){let t=Number.parseInt(e,10);if(Number.isNaN(t))throw new G.InvalidArgumentError("Not a number.");return t}function ee(e,t){let n=e?.label?.length?e.label:t?.label;if(!n?.length)return;let o=n.filter(i=>i!=="");return o.length?o:[]}function Yt(e,t){return e?.password??t?.password??(process.env.SHIP_PASSWORD||void 0)}function N(e){let t=e.optsWithGlobals();t.color===!1&&(t.noColor=!0);let n=!!process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0";return!t.noColor&&!n&&(!process.stdout.isTTY||process.env.NO_COLOR!==void 0)&&(t.noColor=!0),t}function to(e){let t={};try{t=he(e.config)}catch{}let n=je(e,K(),t).token;return typeof n=="string"?n:void 0}async function Wt(e,t,n,o,i,s){if(!(0,z.existsSync)(t))throw p.file(`${t} path does not exist`,{filePath:t});let a=(0,z.statSync)(t);if(!a.isDirectory()&&!a.isFile())throw p.file(`${t} path must be a file or directory`,{filePath:t});let l={via:process.env.SHIP_VIA||"cli"};n!==void 0&&(l.labels=n),o!==void 0&&(l.password=o),i?.noPathDetect!==void 0&&(l.pathDetect=!i.noPathDetect),i?.noSpaDetect!==void 0&&(l.spaDetect=!i.noSpaDetect);let m=new AbortController;l.signal=m.signal;let d=null;if(process.stdout.isTTY&&!s.json&&!s.quiet&&!s.noColor){let{default:c}=await import("yocto-spinner");d=c({text:"uploading\u2026"}).start()}let r=()=>{m.abort(),d&&d.stop(),process.exit(130)};process.on("SIGINT",r);try{return await e.deployments.upload(t,l)}finally{process.removeListener("SIGINT",r),d&&d.stop()}}function qe(){let e=new G.Command;e.exitOverride(r=>{if(r.code==="commander.help"||r.code==="commander.version"||r.exitCode===0)throw r;let c=N(e),u=r.message||"unknown command error";throw u=u.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),W(ze(u),c.json,c.noColor),c.json||e.outputHelp(),r}).configureOutput({writeErr:r=>{r.startsWith("error:")||process.stderr.write(r)},writeOut:r=>process.stdout.write(r)});function t(r,c){return(...u)=>{let h=N(e),S=u[u.length-1];if(S?.args?.length){let f=S.args.find(y=>!c.includes(y));f&&W(ze(`unknown command '${f}'`),h.json,h.noColor)}h.json||console.log(`usage: ship ${r} <${c.join("|")}>
197
- `),process.exitCode=1}}function n(r,c){let u=N(e),h=Vt(r);if(u.json)W(h,!0,u.noColor);else{let S=qt(h,c,{token:h.isAuthError()?to(e.opts()):void 0});W(S,!1,u.noColor),h.type===g.Validation&&S.includes("unknown command")&&e.outputHelp()}process.exitCode=1}function o(r,c){return async function(...u){let h=N(this),S=c?{operation:c.operation,resourceType:c.resourceType}:{};try{let{config:f,apiUrl:y,token:T}=e.opts(),C=zt({config:f,apiUrl:y,token:T}),x=await r(C,h,...u);Kt(x,S,{json:h.json,quiet:h.quiet,noColor:h.noColor})}catch(f){n(f,S)}}}e.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(Qn.version,"-V, --version","Show version information").option("--token <token>","Any ship token: API key (ship-\u2026) or deploy token (deploy-\u2026)").option("--config <file>","Custom config file path").option("--api-url <url>","API URL (for development)").option("--json","Output results in JSON format").option("-q, --quiet","Output only the resource identifier").option("--no-color","Disable colored output").helpOption("-h, --help","Display help for command").helpCommand("help [command]","Display help for command").configureHelp({formatHelp:(r,c)=>r.parent===null?`${eo(N(r).noColor)}
198
- `:G.Help.prototype.formatHelp.call(c,r,c)}).allowExcessArguments(),e.hook("preAction",r=>{let c=N(r);try{c.token&&typeof c.token=="string"&&H(c.token),c.apiUrl&&typeof c.apiUrl=="string"&&ot(c.apiUrl)}catch(u){throw A(u)?(W(u,c.json,c.noColor),new G.CommanderError(1,"ship.invalidOption",u.message)):u}}),e.command("ping").description("Check API connectivity").action(o((r,c)=>r.ping(),{operation:"ping"})),e.command("whoami").description("Get current account information").action(o((r,c)=>r.whoami(),{operation:"get",resourceType:"Account"}));let i=e.command("deployments").description("Manage deployments").enablePositionalOptions().action(t("deployments",["list","upload","get","set","delete"]));i.command("list").description("List deployments (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",ge).option("--cursor <cursor>","Continue from a previous page's cursor").action(o((r,c,u)=>r.deployments.list(u))),i.command("upload <path>").description("Upload deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",Q,[]).option("--password <password>","Password-protect this deployment").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(o((r,c,u,h)=>Wt(r,u,ee(h,e.opts()),Yt(h,e.opts()),h,c),{operation:"upload",resourceType:"Deployment"})),i.command("get <deployment>").description("Show deployment information").action(o((r,c,u)=>r.deployments.get(u),{operation:"get",resourceType:"Deployment"})),i.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",Q,[]).action(o(async(r,c,u,h)=>{let S=ee(h,e.opts())||[];return r.deployments.set(u,{labels:S})},{operation:"set",resourceType:"Deployment"})),i.command("delete <deployment>").description("Delete deployment permanently").action(o((r,c,u)=>r.deployments.delete(u),{operation:"delete",resourceType:"Deployment"}));let s=e.command("domains").description("Manage domains").enablePositionalOptions().action(t("domains",["list","get","set","validate","records","dns","share","verify","delete"]));s.command("list").description("List domains (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",ge).option("--cursor <cursor>","Continue from a previous page's cursor").action(o((r,c,u)=>r.domains.list(u))),s.command("get <name>").description("Show domain information").action(o((r,c,u)=>r.domains.get(u),{operation:"get",resourceType:"Domain"})),s.command("validate <name>").description("Check if domain name is valid and available").action(o(async(r,c,u)=>{let h=await r.domains.validate(u);return h.valid||(process.exitCode=1),h},{operation:"validate",resourceType:"Domain"})),s.command("verify <name>").description("Trigger DNS verification for external domain").action(o((r,c,u)=>r.domains.verify(u),{operation:"verify",resourceType:"Domain"})),s.command("records <name>").description("Show required DNS records for domain setup").action(o((r,c,u)=>r.domains.records(u),{operation:"records",resourceType:"Domain"})),s.command("dns <name>").description("Look up DNS provider for a domain").action(o((r,c,u)=>r.domains.dns(u),{operation:"dns",resourceType:"Domain"})),s.command("share <name>").description("Get shareable DNS setup link").action(o((r,c,u)=>r.domains.share(u),{operation:"share",resourceType:"Domain"})),s.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",Q,[]).action(o(async(r,c,u,h,S)=>{!h&&!process.stdin.isTTY&&(h=await new Promise(C=>{let x="";process.stdin.on("data",De=>x+=De),process.stdin.on("end",()=>C(x.trim()||void 0))}));let f=ee(S,e.opts()),y={};h&&(y.deployment=h),f!==void 0&&(y.labels=f);let T=await r.domains.set(u,y);if(T.isCreate&&u.includes("."))try{let[C,x]=await Promise.all([r.domains.records(u),r.domains.share(u)]);return{...T,_dnsRecords:C.records,_shareHash:x.hash}}catch{}return T},{operation:"set",resourceType:"Domain"})),s.command("delete <name>").description("Delete domain permanently").action(o((r,c,u)=>r.domains.delete(u),{operation:"delete",resourceType:"Domain"}));let a=e.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(t("tokens",["list","create","delete"]));a.command("list").description("List deploy tokens (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",ge).option("--cursor <cursor>","Continue from a previous page's cursor").action(o((r,c,u)=>r.tokens.list(u))),a.command("create").description("Create a new deploy token").option("--ttl <seconds>","Time to live in seconds (default: never expires)",ge).option("--label <label>","Label to set (can be repeated)",Q,[]).action(o((r,c,u)=>{let h={};u?.ttl!==void 0&&(h.ttl=u.ttl);let S=ee(u,e.opts());return S!==void 0&&(h.labels=S),r.tokens.create(h)},{operation:"create",resourceType:"Token"})),a.command("get <token>").description("Show one deploy token").action(o((r,c,u)=>r.tokens.get(u))),a.command("delete <token>").description("Delete token permanently").action(o((r,c,u)=>r.tokens.delete(u),{operation:"delete",resourceType:"Token"})),e.command("account").description("Manage account").action(t("account",["get"])).command("get").description("Show account information").action(o((r,c)=>r.whoami(),{operation:"get",resourceType:"Account"}));let m=e.command("completion").description("Setup shell completion").action(t("completion",["install","uninstall"]));m.command("install").description("Install shell completion script").action(()=>{let r=N(e);try{mt(e,{json:r.json,noColor:r.noColor})}catch(c){n(c)}}),m.command("uninstall").description("Uninstall shell completion script").action(()=>{let r=N(e);try{ut({json:r.json,noColor:r.noColor})}catch(c){n(c)}}),e.command("config").description("Save your token").action(async()=>{let r=N(e);try{await St({noColor:r.noColor,json:r.json})}catch(c){n(c)}});let d=o((r,c,u,h)=>Wt(r,u,ee(h,e.opts()),Yt(h,e.opts()),h,c),{operation:"upload",resourceType:"Deployment"});return e.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",Q,[]).option("--password <password>","Password-protect this deployment").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(async function(r,c){if(!r){this.outputHelp();return}if(!(0,z.existsSync)(r)&&!r.includes("/")&&!r.includes("\\")&&!r.includes(".")&&!r.startsWith("~")){n(ze(`unknown command '${r}'`),{operation:"upload"});return}return d.call(this,r,c)}),e}function Xt(){let e=process.argv.includes("--compfish"),t=qe().commands.map(n=>n.name()).filter(n=>n!=="help");console.log(t.join(e?`
199
- `:" "))}var no=process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish");no?Xt():qe().parseAsync(process.argv).catch(e=>{if(e instanceof Jt.CommanderError){process.exitCode=e.exitCode;return}throw e});
196
+ `}var ze=e=>new p(g.Validation,e);function Q(e,t=[]){return t.concat([e])}function ge(e){let t=Number.parseInt(e,10);if(Number.isNaN(t))throw new G.InvalidArgumentError("Not a number.");return t}function ee(e,t){let n=e?.label?.length?e.label:t?.label;if(!n?.length)return;let o=n.filter(i=>i!=="");return o.length?o:[]}function Yt(e,t){return e?.password??t?.password??(process.env.SHIP_PASSWORD||void 0)}function N(e){let t=e.optsWithGlobals();t.color===!1&&(t.noColor=!0);let n=!!process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0";return!t.noColor&&!n&&(!process.stdout.isTTY||process.env.NO_COLOR!==void 0)&&(t.noColor=!0),t}function to(e){let t={};try{t=he(e.config)}catch{}let n=je(e,K(),t).token;return typeof n=="string"?n:void 0}async function Wt(e,t,n,o,i,s){if(!(0,z.existsSync)(t))throw p.file(`${t} path does not exist`,{filePath:t});let a=(0,z.statSync)(t);if(!a.isDirectory()&&!a.isFile())throw p.file(`${t} path must be a file or directory`,{filePath:t});let l={via:process.env.SHIP_VIA||"cli"};n!==void 0&&(l.labels=n),o!==void 0&&(l.password=o),i?.noPathDetect!==void 0&&(l.pathDetect=!i.noPathDetect),i?.noSpaDetect!==void 0&&(l.spaDetect=!i.noSpaDetect);let u=new AbortController;l.signal=u.signal;let d=null;if(process.stdout.isTTY&&!s.json&&!s.quiet&&!s.noColor){let{default:c}=await import("yocto-spinner");d=c({text:"uploading\u2026"}).start()}let r=()=>{u.abort(),d&&d.stop(),process.exit(130)};process.on("SIGINT",r);try{return await e.deployments.upload(t,l)}finally{process.removeListener("SIGINT",r),d&&d.stop()}}function Xt(){let e=new G.Command;e.exitOverride(r=>{if(r.code==="commander.help"||r.code==="commander.version"||r.exitCode===0)throw r;let c=N(e),m=r.message||"unknown command error";throw m=m.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),W(ze(m),c.json,c.noColor),c.json||e.outputHelp(),r}).configureOutput({writeErr:r=>{r.startsWith("error:")||process.stderr.write(r)},writeOut:r=>process.stdout.write(r)});function t(r,c){return(...m)=>{let h=N(e),E=m[m.length-1];if(E?.args?.length){let f=E.args.find(y=>!c.includes(y));f&&W(ze(`unknown command '${f}'`),h.json,h.noColor)}h.json||console.log(`usage: ship ${r} <${c.join("|")}>
197
+ `),process.exitCode=1}}function n(r){let c=N(e),m=Vt(r);if(c.json)W(m,!0,c.noColor);else{let h=qt(m,{token:m.isAuthError()?to(e.opts()):void 0});W(h,!1,c.noColor),m.type===g.Validation&&h.includes("unknown command")&&e.outputHelp()}process.exitCode=1}function o(r,c={}){return async function(...m){let h=N(this);try{let{config:E,apiUrl:f,token:y}=e.opts(),C=zt({config:E,apiUrl:f,token:y}),O=await r(C,h,...m);Kt(O,c,{json:h.json,quiet:h.quiet,noColor:h.noColor})}catch(E){n(E)}}}e.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(Qn.version,"-V, --version","Show version information").option("--token <token>","Any ship token: API key (ship-\u2026) or deploy token (deploy-\u2026)").option("--config <file>","Custom config file path").option("--api-url <url>","API URL (for development)").option("--json","Output results in JSON format").option("-q, --quiet","Output only the resource identifier").option("--no-color","Disable colored output").helpOption("-h, --help","Display help for command").helpCommand("help [command]","Display help for command").configureHelp({formatHelp:(r,c)=>r.parent===null?`${eo(N(r).noColor)}
198
+ `:G.Help.prototype.formatHelp.call(c,r,c)}).allowExcessArguments(),e.hook("preAction",r=>{let c=N(r);try{c.token&&typeof c.token=="string"&&H(c.token),c.apiUrl&&typeof c.apiUrl=="string"&&ot(c.apiUrl)}catch(m){throw A(m)?(W(m,c.json,c.noColor),new G.CommanderError(1,"ship.invalidOption",m.message)):m}}),e.command("ping").description("Check API connectivity").action(o((r,c)=>r.ping(),{operation:"ping"})),e.command("whoami").description("Get current account information").action(o((r,c)=>r.whoami(),{operation:"get",resource:"account"}));let i=e.command("deployments").description("Manage deployments").enablePositionalOptions().action(t("deployments",["list","upload","get","set","delete"]));i.command("list").description("List deployments (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",ge).option("--cursor <cursor>","Continue from a previous page's cursor").action(o((r,c,m)=>r.deployments.list(m))),i.command("upload <path>").description("Upload deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",Q,[]).option("--password <password>","Password-protect this deployment").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(o((r,c,m,h)=>Wt(r,m,ee(h,e.opts()),Yt(h,e.opts()),h,c),{operation:"upload",resource:"deployment"})),i.command("get <deployment>").description("Show deployment information").action(o((r,c,m)=>r.deployments.get(m),{operation:"get",resource:"deployment"})),i.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",Q,[]).action(o(async(r,c,m,h)=>{let E=ee(h,e.opts())||[];return r.deployments.set(m,{labels:E})},{operation:"set",resource:"deployment"})),i.command("delete <deployment>").description("Delete deployment permanently").action(o((r,c,m)=>r.deployments.delete(m),{operation:"delete",resource:"deployment"}));let s=e.command("domains").description("Manage domains").enablePositionalOptions().action(t("domains",["list","get","set","validate","records","dns","share","verify","delete"]));s.command("list").description("List domains (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",ge).option("--cursor <cursor>","Continue from a previous page's cursor").action(o((r,c,m)=>r.domains.list(m))),s.command("get <name>").description("Show domain information").action(o((r,c,m)=>r.domains.get(m),{operation:"get",resource:"domain"})),s.command("validate <name>").description("Check if domain name is valid and available").action(o(async(r,c,m)=>{let h=await r.domains.validate(m);return h.valid||(process.exitCode=1),h},{operation:"validate",resource:"domain"})),s.command("verify <name>").description("Trigger DNS verification for external domain").action(o((r,c,m)=>r.domains.verify(m),{operation:"verify",resource:"domain"})),s.command("records <name>").description("Show required DNS records for domain setup").action(o((r,c,m)=>r.domains.records(m),{operation:"records",resource:"domain"})),s.command("dns <name>").description("Look up DNS provider for a domain").action(o((r,c,m)=>r.domains.dns(m),{operation:"dns",resource:"domain"})),s.command("share <name>").description("Get shareable DNS setup link").action(o((r,c,m)=>r.domains.share(m),{operation:"share",resource:"domain"})),s.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",Q,[]).action(o(async(r,c,m,h,E)=>{!h&&!process.stdin.isTTY&&(h=await new Promise(O=>{let x="";process.stdin.on("data",De=>x+=De),process.stdin.on("end",()=>O(x.trim()||void 0))}));let f=ee(E,e.opts()),y={};h&&(y.deployment=h),f!==void 0&&(y.labels=f);let C=await r.domains.set(m,y);if(C.isCreate&&m.includes("."))try{let[O,x]=await Promise.all([r.domains.records(m),r.domains.share(m)]);return{...C,_dnsRecords:O.records,_shareHash:x.hash}}catch{}return C},{operation:"set",resource:"domain"})),s.command("delete <name>").description("Delete domain permanently").action(o((r,c,m)=>r.domains.delete(m),{operation:"delete",resource:"domain"}));let a=e.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(t("tokens",["list","create","delete"]));a.command("list").description("List deploy tokens (one page \u2014 see --limit and --cursor)").option("--limit <count>","Maximum number of results per page",ge).option("--cursor <cursor>","Continue from a previous page's cursor").action(o((r,c,m)=>r.tokens.list(m))),a.command("create").description("Create a new deploy token").option("--ttl <seconds>","Time to live in seconds (default: never expires)",ge).option("--label <label>","Label to set (can be repeated)",Q,[]).action(o((r,c,m)=>{let h={};m?.ttl!==void 0&&(h.ttl=m.ttl);let E=ee(m,e.opts());return E!==void 0&&(h.labels=E),r.tokens.create(h)},{operation:"create",resource:"token"})),a.command("get <token>").description("Show one deploy token").action(o((r,c,m)=>r.tokens.get(m))),a.command("delete <token>").description("Delete token permanently").action(o((r,c,m)=>r.tokens.delete(m),{operation:"delete",resource:"token"})),e.command("account").description("Manage account").action(t("account",["get"])).command("get").description("Show account information").action(o((r,c)=>r.whoami(),{operation:"get",resource:"account"}));let u=e.command("completion").description("Setup shell completion").action(t("completion",["install","uninstall"]));u.command("install").description("Install shell completion script").action(()=>{let r=N(e);try{mt(e,{json:r.json,noColor:r.noColor})}catch(c){n(c)}}),u.command("uninstall").description("Uninstall shell completion script").action(()=>{let r=N(e);try{ut({json:r.json,noColor:r.noColor})}catch(c){n(c)}}),e.command("config").description("Save your token").action(async()=>{let r=N(e);try{await St({noColor:r.noColor,json:r.json})}catch(c){n(c)}});let d=o((r,c,m,h)=>Wt(r,m,ee(h,e.opts()),Yt(h,e.opts()),h,c),{operation:"upload",resource:"deployment"});return e.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",Q,[]).option("--password <password>","Password-protect this deployment").option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(async function(r,c){if(!r){this.outputHelp();return}if(!(0,z.existsSync)(r)&&!r.includes("/")&&!r.includes("\\")&&!r.includes(".")&&!r.startsWith("~")){n(ze(`unknown command '${r}'`));return}return d.call(this,r,c)}),e}Xt().parseAsync(process.argv).catch(e=>{if(e instanceof Jt.CommanderError){process.exitCode=e.exitCode;return}throw e});
200
199
  //# sourceMappingURL=cli.cjs.map