@shipstatic/ship 0.8.6 → 0.8.7
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 +4 -0
- package/SKILL.md +173 -98
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +23 -23
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/cli.cjs
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var At=Object.create;var fe=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var Ft=Object.getPrototypeOf,$t=Object.prototype.hasOwnProperty;var F=(e,o)=>()=>(e&&(o=e(e=0)),o);var Pt=(e,o)=>{for(var t in o)fe(e,t,{get:o[t],enumerable:!0})},Lt=(e,o,t,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of It(o))!$t.call(e,i)&&i!==t&&fe(e,i,{get:()=>o[i],enumerable:!(n=xt(o,i))||n.enumerable});return e};var R=(e,o,t)=>(t=e!=null?At(Ft(e)):{},Lt(o||!e||!e.__esModule?fe(t,"default",{value:e,enumerable:!0}):t,e));function A(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function De(e){let o=e.lastIndexOf(".");if(o===-1||o===e.length-1)return!1;let t=e.slice(o+1).toLowerCase();return Nt.has(t)}function Pe(e){return _t.test(e)}function be(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(t=>Se.has(t))}function oe(e){if(!e.startsWith(K))throw c.validation(`API key must start with "${K}"`);if(e.length!==Fe)throw c.validation(`API key must be ${Fe} characters total (${K} + ${ge} hex chars)`);let o=e.slice(K.length);if(!/^[a-f0-9]{64}$/i.test(o))throw c.validation(`API key must contain ${ge} hexadecimal characters after "${K}" prefix`)}function Le(e){if(!e.startsWith(z))throw c.validation(`Deploy token must start with "${z}"`);if(e.length!==$e)throw c.validation(`Deploy token must be ${$e} characters total (${z} + ${ye} hex chars)`);let o=e.slice(z.length);if(!/^[a-f0-9]{64}$/i.test(o))throw c.validation(`Deploy token must contain ${ye} hexadecimal characters after "${z}" prefix`)}function Ne(e){try{let o=new URL(e);if(!["http:","https:"].includes(o.protocol))throw c.validation("API URL must use http:// or https:// protocol");if(o.pathname!=="/"&&o.pathname!=="")throw c.validation("API URL must not contain a path");if(o.search||o.hash)throw c.validation("API URL must not contain query parameters or fragments")}catch(o){throw A(o)?o:c.validation("API URL must be a valid URL")}}var g,he,c,Nt,_t,Se,K,ge,Fe,z,ye,$e,Ce,B,v=F(()=>{"use strict";(function(e){e.Validation="validation_failed",e.NotFound="not_found",e.RateLimit="rate_limit_exceeded",e.Authentication="authentication_failed",e.Business="business_logic_error",e.Api="internal_server_error",e.Network="network_error",e.Cancelled="operation_cancelled",e.File="file_error",e.Config="config_error"})(g||(g={}));he={client:new Set([g.Business,g.Config,g.File,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},c=class e extends Error{type;status;details;constructor(o,t,n,i){super(t),this.type=o,this.status=n,this.details=i,this.name="ShipError"}toResponse(){let o=this.type===g.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:o}}static fromResponse(o){return new e(o.error,o.message,o.status,o.details)}static validation(o,t){return new e(g.Validation,o,400,t)}static notFound(o,t){let n=t?`${o} ${t} not found`:`${o} not found`;return new e(g.NotFound,n,404)}static rateLimit(o="Too many requests"){return new e(g.RateLimit,o,429)}static authentication(o="Authentication required",t){return new e(g.Authentication,o,401,t)}static business(o,t=400){return new e(g.Business,o,t)}static network(o,t){return new e(g.Network,o,void 0,{cause:t})}static cancelled(o){return new e(g.Cancelled,o)}static file(o,t){return new e(g.File,o,void 0,{filePath:t})}static config(o,t){return new e(g.Config,o,void 0,t)}static api(o,t=500){return new e(g.Api,o,t)}static database(o,t=500){return new e(g.Api,o,t)}static storage(o,t=500){return new e(g.Api,o,t)}get filePath(){return this.details?.filePath}isClientError(){return he.client.has(this.type)}isNetworkError(){return he.network.has(this.type)}isAuthError(){return he.auth.has(this.type)}isValidationError(){return this.type===g.Validation}isFileError(){return this.type===g.File}isConfigError(){return this.type===g.Config}isType(o){return this.type===o}};Nt=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"]);_t=/[\x00-\x1f\x7f#?%\\<>"]/;Se=new Set(["node_modules","package.json"]);K="ship-",ge=64,Fe=K.length+ge,z="token-",ye=64,$e=z.length+ye,Ce="ship.json";B="https://api.shipstatic.com"});function _e(e){ve=e}function ie(){if(ve===null)throw c.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ve}var ve,se=F(()=>{"use strict";v();ve=null});function jt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function P(){return je||jt()}var je,Y=F(()=>{"use strict";je=null});async function Mt(e){let o=(await import("spark-md5")).default;return new Promise((t,n)=>{let s=Math.ceil(e.size/2097152),r=0,a=new o.ArrayBuffer,l=new FileReader,p=()=>{let d=r*2097152,m=Math.min(d+2097152,e.size);l.readAsArrayBuffer(e.slice(d,m))};l.onload=d=>{let m=d.target?.result;if(!m){n(c.business("Failed to read file chunk"));return}a.append(m),r++,r<s?p():t({md5:a.end()})},l.onerror=()=>{n(c.business("Failed to calculate MD5: FileReader error"))},p()})}async function Kt(e){let o=await import("crypto");if(Buffer.isBuffer(e)){let n=o.createHash("md5");return n.update(e),{md5:n.digest("hex")}}let t=await import("fs");return new Promise((n,i)=>{let s=o.createHash("md5"),r=t.createReadStream(e);r.on("error",a=>i(c.business(`Failed to read file for MD5: ${a.message}`))),r.on("data",a=>s.update(a)),r.on("end",()=>n({md5:s.digest("hex")}))})}async function re(e){let o=P();if(o==="browser"){if(!(e instanceof Blob))throw c.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Mt(e)}if(o==="node"){if(!(Buffer.isBuffer(e)||typeof e=="string"))throw c.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Kt(e)}throw c.business("Unknown or unsupported execution environment for MD5 calculation.")}var Ee=F(()=>{"use strict";Y();v()});function Ye(e,o){if(!e||e.length===0)return[];if(!o?.allowUnbuilt&&e.find(n=>n&&be(n)))throw c.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(t=>{if(!t)return!1;let n=t.replace(/\\/g,"/").split("/").filter(Boolean);if(n.length===0)return!0;let i=n[n.length-1];if((0,Je.isJunk)(i))return!1;for(let r of n)if(r!==".well-known"&&(r.startsWith(".")||r.length>255))return!1;let s=n.slice(0,-1);for(let r of s)if(Ht.some(a=>r.toLowerCase()===a.toLowerCase()))return!1;return!0})}var Je,Ht,We=F(()=>{"use strict";Je=require("junk");v();Ht=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Xe(e){if(!e||e.length===0)return"";let o=e.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(o.length===0)return"";if(o.length===1)return o[0];let t=o.map(s=>s.split("/").filter(Boolean)),n=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i;s++){let r=t[0][s];if(t.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function le(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Te=F(()=>{"use strict"});function Ze(e,o={}){if(o.flatten===!1)return e.map(n=>({path:le(n),name:Oe(n)}));let t=Vt(e);return e.map(n=>{let i=le(n);if(t){let s=t.endsWith("/")?t:`${t}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=Oe(n)),{path:i,name:Oe(n)}})}function Vt(e){if(!e.length)return"";let t=e.map(s=>le(s)).map(s=>s.split("/")),n=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i-1;s++){let r=t[0][s];if(t.every(a=>a[s]===r))n.push(r);else break}return n.join("/")}function Oe(e){return e.split(/[/\\]/).pop()||e}var Qe=F(()=>{"use strict";Te()});function et(e){if(Pe(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 o=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,t=e.split("/").pop()||e;return o.test(t)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}var tt=F(()=>{"use strict";v()});function ot(e,o){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw c.business(`Security error: Unsafe file path "${e}" for file: ${o}`)}function nt(e,o){let t=et(e);if(!t.valid)throw c.business(t.reason||"Invalid file name");if(De(e))throw c.business(`File extension not allowed: "${o}"`)}var it=F(()=>{"use strict";v();tt()});var rt={};Pt(rt,{processFilesForNode:()=>qt});function st(e,o=new Set){let t=[],n=O.realpathSync(e);if(o.has(n))return t;o.add(n);let i=O.readdirSync(e);for(let s of i){let r=k.join(e,s),a=O.statSync(r);if(a.isDirectory()){let l=st(r,o);t.push(...l)}else a.isFile()&&t.push(r)}return t}async function qt(e,o={}){if(P()!=="node")throw c.business("processFilesForNode can only be called in Node.js environment.");for(let h of e){let C=k.resolve(h);try{if(O.statSync(C).isDirectory()){let x=O.readdirSync(C).find(I=>Se.has(I));if(x)throw c.business(`"${x}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(x){if(A(x))throw x}}let t=e.flatMap(h=>{let C=k.resolve(h);try{return O.statSync(C).isDirectory()?st(C):[C]}catch{throw c.file(`Path does not exist: ${h}`,h)}}),n=[...new Set(t)],i=e.map(h=>k.resolve(h)),s=Xe(i.map(h=>{try{return O.statSync(h).isDirectory()?h:k.dirname(h)}catch{return k.dirname(h)}})),r=n.map(h=>{if(s&&s.length>0){let C=k.relative(s,h);if(C&&typeof C=="string"&&!C.startsWith(".."))return C.replace(/\\/g,"/")}return k.basename(h)}),a=new Set(Ye(r));if(a.size===0)return[];let l=[],p=[];for(let h=0;h<n.length;h++)a.has(r[h])&&(l.push(n[h]),p.push(r[h]));let d=Ze(p,{flatten:o.pathDetect!==!1}),m=[],y=0,_=ie();for(let h=0;h<l.length;h++){let C=l[h],x=d[h].path;try{ot(x,C);let I=O.statSync(C);if(I.size===0)continue;if(nt(x,C),I.size>_.maxFileSize)throw c.business(`File ${C} is too large. Maximum allowed size is ${_.maxFileSize/(1024*1024)}MB.`);if(y+=I.size,y>_.maxTotalSize)throw c.business(`Total deploy size is too large. Maximum allowed is ${_.maxTotalSize/(1024*1024)}MB.`);let J=O.readFileSync(C),{md5:kt}=await re(J);m.push({path:x,content:J,size:J.length,md5:kt})}catch(I){if(A(I))throw I;let J=I instanceof Error?I.message:String(I);throw c.file(`Failed to read file "${C}": ${J}`,C)}}if(m.length>_.maxFilesCount)throw c.business(`Too many files to deploy. Maximum allowed is ${_.maxFilesCount} files.`);return m}var O,k,at=F(()=>{"use strict";Y();Ee();We();it();v();se();Qe();Te();O=R(require("fs"),1),k=R(require("path"),1)});var Et=require("commander");v();var ne=class{constructor(){this.handlers=new Map}on(o,t){this.handlers.has(o)||this.handlers.set(o,new Set),this.handlers.get(o).add(t)}off(o,t){let n=this.handlers.get(o);n&&(n.delete(t),n.size===0&&this.handlers.delete(o))}emit(o,...t){let n=this.handlers.get(o);if(!n)return;let i=Array.from(n);for(let s of i)try{s(...t)}catch(r){n.delete(s),o!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(o)):this.emit("error",new Error(String(r)),String(o))},0)}}transfer(o){this.handlers.forEach((t,n)=>{t.forEach(i=>{o.on(n,i)})})}clear(){this.handlers.clear()}};var D={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Ut=3e4,G=class extends ne{constructor(t){super();this.globalHeaders={};this.apiUrl=t.apiUrl||B,this.getAuthHeadersCallback=t.getAuthHeaders,this.useCredentials=t.useCredentials??!1,this.timeout=t.timeout??Ut,this.createDeployBody=t.createDeployBody,this.deployEndpoint=t.deployEndpoint||D.DEPLOYMENTS}setGlobalHeaders(t){this.globalHeaders=t}transferEventsTo(t){this.transfer(t)}async executeRequest(t,n,i){let s=this.mergeHeaders(n.headers),{signal:r,cleanup:a}=this.createTimeoutSignal(n.signal),l={...n,headers:s,credentials:this.useCredentials&&!s.Authorization?"include":void 0,signal:r};this.emit("request",t,l);try{let p=await fetch(t,l);return a(),p.ok||await this.handleResponseError(p,i),this.emit("response",this.safeClone(p),t),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(p){a();let d=p instanceof Error?p:new Error(String(p));this.emit("error",d,t),this.handleFetchError(p,i)}}async request(t,n,i){let{data:s}=await this.executeRequest(t,n,i);return s}async requestWithStatus(t,n,i){return this.executeRequest(t,n,i)}mergeHeaders(t={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...t}}createTimeoutSignal(t){let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeout);if(t){let s=()=>n.abort();t.addEventListener("abort",s),t.aborted&&n.abort()}return{signal:n.signal,cleanup:()=>clearTimeout(i)}}safeClone(t){try{return t.clone()}catch{return t}}async parseResponse(t){if(!(t.headers.get("Content-Length")==="0"||t.status===204))return t.json()}async handleResponseError(t,n){let i={};try{if(t.headers.get("content-type")?.includes("application/json")){let a=await t.json();if(a&&typeof a=="object"){let l=a;typeof l.message=="string"&&(i.message=l.message),typeof l.error=="string"&&(i.error=l.error)}}else i={message:await t.text()}}catch{i={message:"Failed to parse error response"}}let s=i.message||i.error||`${n} failed`;throw t.status===401?c.authentication(s):c.api(s,t.status)}handleFetchError(t,n){throw A(t)?t:t instanceof Error&&t.name==="AbortError"?c.cancelled(`${n} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?c.network(`${n} failed: ${t.message}`,t):t instanceof Error?c.business(`${n} failed: ${t.message}`):c.business(`${n} failed: Unknown error`)}async deploy(t,n={}){if(!t.length)throw c.business("No files to deploy");for(let l of t)if(!l.md5)throw c.file(`MD5 checksum missing for file: ${l.path}`,l.path);let i=n.build||n.prerender?{build:n.build,prerender:n.prerender}:void 0,{body:s,headers:r}=await this.createDeployBody(t,n.labels,n.via,i),a={};return n.deployToken?a.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(a.Authorization=`Bearer ${n.apiKey}`),n.caller&&(a["X-Caller"]=n.caller),this.request(`${n.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:s,headers:{...r,...a},signal:n.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${D.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(t){return this.request(`${this.apiUrl}${D.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(t,n){return this.request(`${this.apiUrl}${D.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:n})},"Update deployment labels")}async removeDeployment(t){await this.request(`${this.apiUrl}${D.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove deployment")}async setDomain(t,n,i){let s={};n&&(s.deployment=n),i!==void 0&&(s.labels=i);let{data:r,status:a}=await this.requestWithStatus(`${this.apiUrl}${D.DOMAINS}/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Set domain");return{...r,isCreate:a===201}}async listDomains(){return this.request(`${this.apiUrl}${D.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(t){return this.request(`${this.apiUrl}${D.DOMAINS}/${encodeURIComponent(t)}`,{method:"GET"},"Get domain")}async removeDomain(t){await this.request(`${this.apiUrl}${D.DOMAINS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(t){return this.request(`${this.apiUrl}${D.DOMAINS}/${encodeURIComponent(t)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(t){return this.request(`${this.apiUrl}${D.DOMAINS}/${encodeURIComponent(t)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(t){return this.request(`${this.apiUrl}${D.DOMAINS}/${encodeURIComponent(t)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(t){return this.request(`${this.apiUrl}${D.DOMAINS}/${encodeURIComponent(t)}/share`,{method:"GET"},"Get domain share")}async validateDomain(t){return this.request(`${this.apiUrl}${D.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:t})},"Validate domain")}async createToken(t,n){let i={};return t!==void 0&&(i.ttl=t),n!==void 0&&(i.labels=n),this.request(`${this.apiUrl}${D.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${D.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(t){await this.request(`${this.apiUrl}${D.TOKENS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove token")}async fetchAgentToken(){return this.request(`${this.apiUrl}${D.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent token")}async getAccount(){return this.request(`${this.apiUrl}${D.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${D.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${D.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(t,n={}){let i=t.find(p=>p.path==="index.html"||p.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 r={"Content-Type":"application/json"};n.deployToken?r.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(r.Authorization=`Bearer ${n.apiKey}`);let a={files:t.map(p=>p.path),index:s};return(await this.request(`${this.apiUrl}${D.SPA_CHECK}`,{method:"POST",headers:r,body:JSON.stringify(a)},"SPA check")).isSPA}};v();se();v();v();function we(e={},o={}){let t={apiUrl:e.apiUrl||o.apiUrl||B,apiKey:e.apiKey!==void 0?e.apiKey:o.apiKey,deployToken:e.deployToken!==void 0?e.deployToken:o.deployToken},n={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(n.apiKey=t.apiKey),t.deployToken!==void 0&&(n.deployToken=t.deployToken),n}function Ue(e,o){let t={...e};return t.apiUrl===void 0&&o.apiUrl!==void 0&&(t.apiUrl=o.apiUrl),t.apiKey===void 0&&o.apiKey!==void 0&&(t.apiKey=o.apiKey),t.deployToken===void 0&&o.deployToken!==void 0&&(t.deployToken=o.deployToken),t.timeout===void 0&&o.timeout!==void 0&&(t.timeout=o.timeout),t.maxConcurrency===void 0&&o.maxConcurrency!==void 0&&(t.maxConcurrency=o.maxConcurrency),t.onProgress===void 0&&o.onProgress!==void 0&&(t.onProgress=o.onProgress),t.caller===void 0&&o.caller!==void 0&&(t.caller=o.caller),t}v();Ee();async function zt(){let o=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(o,"utf-8"):t=new Blob([o],{type:"application/json"});let{md5:n}=await re(t);return{path:Ce,content:t,size:o.length,md5:n}}async function Me(e,o,t){if(t.spaDetect===!1||t.build||t.prerender||e.some(n=>n.path===Ce))return e;try{if(await o.checkSPA(e,t)){let i=await zt();return[...e,i]}}catch{}return e}function Ke(e){let{getApi:o,ensureInit:t,processInput:n,clientDefaults:i,hasAuth:s}=e;return{upload:async(r,a={})=>{await t();let l=i?Ue(a,i):a;if(s&&!s()&&!l.deployToken&&!l.apiKey)try{let m=o(),{secret:y}=await m.fetchAgentToken();l.deployToken=y}catch{throw c.authentication("Too many requests; try again later or configure a free API key with 'ship config'")}if(!n)throw c.config("processInput function is not provided.");let p=o(),d=await n(r,l);return d=await Me(d,p,l),p.deploy(d,l)},list:async()=>(await t(),o().listDeployments()),get:async r=>(await t(),o().getDeployment(r)),set:async(r,a)=>(await t(),o().updateDeploymentLabels(r,a.labels)),remove:async r=>{await t(),await o().removeDeployment(r)}}}function ze(e){let{getApi:o,ensureInit:t}=e;return{set:async(n,i={})=>(await t(),o().setDomain(n,i.deployment,i.labels)),list:async()=>(await t(),o().listDomains()),get:async n=>(await t(),o().getDomain(n)),remove:async n=>{await t(),await o().removeDomain(n)},verify:async n=>(await t(),o().verifyDomain(n)),validate:async n=>(await t(),o().validateDomain(n)),dns:async n=>(await t(),o().getDomainDns(n)),records:async n=>(await t(),o().getDomainRecords(n)),share:async n=>(await t(),o().getDomainShare(n))}}function Be(e){let{getApi:o,ensureInit:t}=e;return{get:async()=>(await t(),o().getAccount())}}function Ge(e){let{getApi:o,ensureInit:t}=e;return{create:async(n={})=>(await t(),o().createToken(n.ttl,n.labels)),list:async()=>(await t(),o().listTokens()),remove:async n=>{await t(),await o().removeToken(n)}}}var ae=class{constructor(o={}){this.initPromise=null;this._config=null;this.auth=null;this.customHeaders={};this.clientOptions=o,o.deployToken?this.auth={type:"token",value:o.deployToken}:o.apiKey&&(this.auth={type:"apiKey",value:o.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(o);this.http=new G({...o,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=Ke({...n,processInput:(i,s)=>this.processInput(i,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=ze(n),this._account=Be(n),this._tokens=Ge(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(o,t){return this.deployments.upload(o,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=ie(),this._config)}on(o,t){this.http.on(o,t)}off(o,t){this.http.off(o,t)}setHeaders(o){this.customHeaders=o,this.http.setGlobalHeaders(o)}clearHeaders(){this.customHeaders={},this.http.setGlobalHeaders({})}replaceHttpClient(o){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(o)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=o,Object.keys(this.customHeaders).length>0&&this.http.setGlobalHeaders(this.customHeaders)}setDeployToken(o){if(!o||typeof o!="string")throw c.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:o}}setApiKey(o){if(!o||typeof o!="string")throw c.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:o}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};v();Y();var H=require("zod");v();Y();var Re="ship",Bt=H.z.object({apiUrl:H.z.string().url().optional(),apiKey:H.z.string().optional(),deployToken:H.z.string().optional()}).strict();function He(e){try{return Bt.parse(e)}catch(o){if(o instanceof H.z.ZodError){let t=o.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw c.config(`Configuration validation failed${n}: ${t.message}`)}throw c.config("Configuration validation failed")}}async function Gt(e){try{if(P()!=="node")return{};let{cosmiconfigSync:o}=await import("cosmiconfig"),t=await import("os"),n=o(Re,{searchPlaces:[`.${Re}rc`,"package.json",`${t.homedir()}/.${Re}rc`],stopDir:t.homedir()}),i;if(e?i=n.load(e):i=n.search(),i&&i.config)return He(i.config)}catch(o){if(A(o))throw o}return{}}async function Ve(e){if(P()!=="node")return{};let o={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await Gt(e),n={apiUrl:o.apiUrl??t.apiUrl,apiKey:o.apiKey??t.apiKey,deployToken:o.deployToken??t.deployToken};return He(n)}se();v();async function qe(e,o,t,n){let{FormData:i,File:s}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),a=new i,l=[];for(let y of e){if(!Buffer.isBuffer(y.content)&&!(typeof Blob<"u"&&y.content instanceof Blob))throw c.file(`Unsupported file.content type for Node.js: ${y.path}`,y.path);if(!y.md5)throw c.file(`File missing md5 checksum: ${y.path}`,y.path);let _=new s([y.content],y.path,{type:"application/octet-stream"});a.append("files[]",_),l.push(y.md5)}a.append("checksums",JSON.stringify(l)),o&&o.length>0&&a.append("labels",JSON.stringify(o)),t&&a.append("via",t),n?.build&&a.append("build","true"),n?.prerender&&a.append("prerender","true");let p=new r(a),d=[];for await(let y of p.encode())d.push(Buffer.from(y));let m=Buffer.concat(d);return{body:m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength),headers:{"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(m).toString()}}}var pe=class extends ae{constructor(o={}){if(P()!=="node")throw c.business("Node.js Ship class can only be used in Node.js environment.");super(o)}resolveInitialConfig(o){return we(o,{})}async loadFullConfig(){try{let o=await Ve(this.clientOptions.configFile),t=we(this.clientOptions,o);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let n=new G({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();_e(i)}catch(o){throw this.initPromise=null,o}}async processInput(o,t){let n=typeof o=="string"?[o]:o;if(!Array.isArray(n)||!n.every(s=>typeof s=="string"))throw c.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw c.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(at(),rt));return i(n,t)}getDeployBodyCreator(){return qe}};v();var M=require("fs"),me=R(require("path"),1);var ke=R(require("columnify"),1),u=require("yoctocolors"),lt=["isCreate","claim"],w=(e,o,t)=>t?o:e(o),E=(e,o,t)=>{console.log(o?JSON.stringify({success:e},null,2)+`
|
|
3
|
-
`:`${w(
|
|
2
|
+
"use strict";var xt=Object.create;var he=Object.defineProperty;var It=Object.getOwnPropertyDescriptor;var Ft=Object.getOwnPropertyNames;var $t=Object.getPrototypeOf,Pt=Object.prototype.hasOwnProperty;var F=(e,o)=>()=>(e&&(o=e(e=0)),o);var Lt=(e,o)=>{for(var t in o)he(e,t,{get:o[t],enumerable:!0})},Nt=(e,o,t,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of Ft(o))!Pt.call(e,i)&&i!==t&&he(e,i,{get:()=>o[i],enumerable:!(n=It(o,i))||n.enumerable});return e};var R=(e,o,t)=>(t=e!=null?xt($t(e)):{},Nt(o||!e||!e.__esModule?he(t,"default",{value:e,enumerable:!0}):t,e));function A(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function Se(e){let o=e.lastIndexOf(".");if(o===-1||o===e.length-1)return!1;let t=e.slice(o+1).toLowerCase();return _t.has(t)}function Le(e){return Ut.test(e)}function Ce(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(t=>be.has(t))}function ne(e){if(!e.startsWith(K))throw c.validation(`API key must start with "${K}"`);if(e.length!==$e)throw c.validation(`API key must be ${$e} characters total (${K} + ${ye} hex chars)`);let o=e.slice(K.length);if(!/^[a-f0-9]{64}$/i.test(o))throw c.validation(`API key must contain ${ye} hexadecimal characters after "${K}" prefix`)}function Ne(e){if(!e.startsWith(z))throw c.validation(`Deploy token must start with "${z}"`);if(e.length!==Pe)throw c.validation(`Deploy token must be ${Pe} characters total (${z} + ${De} hex chars)`);let o=e.slice(z.length);if(!/^[a-f0-9]{64}$/i.test(o))throw c.validation(`Deploy token must contain ${De} hexadecimal characters after "${z}" prefix`)}function _e(e){try{let o=new URL(e);if(!["http:","https:"].includes(o.protocol))throw c.validation("API URL must use http:// or https:// protocol");if(o.pathname!=="/"&&o.pathname!=="")throw c.validation("API URL must not contain a path");if(o.search||o.hash)throw c.validation("API URL must not contain query parameters or fragments")}catch(o){throw A(o)?o:c.validation("API URL must be a valid URL")}}var y,ge,c,_t,Ut,be,K,ye,$e,z,De,Pe,ve,B,v=F(()=>{"use strict";(function(e){e.Validation="validation_failed",e.NotFound="not_found",e.RateLimit="rate_limit_exceeded",e.Authentication="authentication_failed",e.Business="business_logic_error",e.Api="internal_server_error",e.Network="network_error",e.Cancelled="operation_cancelled",e.File="file_error",e.Config="config_error"})(y||(y={}));ge={client:new Set([y.Business,y.Config,y.File,y.Validation]),network:new Set([y.Network]),auth:new Set([y.Authentication])},c=class e extends Error{type;status;details;constructor(o,t,n,i){super(t),this.type=o,this.status=n,this.details=i,this.name="ShipError"}toResponse(){let o=this.type===y.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:o}}static fromResponse(o){return new e(o.error,o.message,o.status,o.details)}static validation(o,t){return new e(y.Validation,o,400,t)}static notFound(o,t){let n=t?`${o} ${t} not found`:`${o} not found`;return new e(y.NotFound,n,404)}static rateLimit(o="Too many requests"){return new e(y.RateLimit,o,429)}static authentication(o="Authentication required",t){return new e(y.Authentication,o,401,t)}static business(o,t=400){return new e(y.Business,o,t)}static network(o,t){return new e(y.Network,o,void 0,{cause:t})}static cancelled(o){return new e(y.Cancelled,o)}static file(o,t){return new e(y.File,o,void 0,{filePath:t})}static config(o,t){return new e(y.Config,o,void 0,t)}static api(o,t=500){return new e(y.Api,o,t)}static database(o,t=500){return new e(y.Api,o,t)}static storage(o,t=500){return new e(y.Api,o,t)}get filePath(){return this.details?.filePath}isClientError(){return ge.client.has(this.type)}isNetworkError(){return ge.network.has(this.type)}isAuthError(){return ge.auth.has(this.type)}isValidationError(){return this.type===y.Validation}isFileError(){return this.type===y.File}isConfigError(){return this.type===y.Config}isType(o){return this.type===o}};_t=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"]);Ut=/[\x00-\x1f\x7f#?%\\<>"]/;be=new Set(["node_modules","package.json"]);K="ship-",ye=64,$e=K.length+ye,z="token-",De=64,Pe=z.length+De,ve="ship.json";B="https://api.shipstatic.com"});function Ue(e){we=e}function se(){if(we===null)throw c.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return we}var we,re=F(()=>{"use strict";v();we=null});function Mt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function P(){return Me||Mt()}var Me,Y=F(()=>{"use strict";Me=null});async function Kt(e){let o=(await import("spark-md5")).default;return new Promise((t,n)=>{let s=Math.ceil(e.size/2097152),r=0,l=new o.ArrayBuffer,a=new FileReader,p=()=>{let d=r*2097152,u=Math.min(d+2097152,e.size);a.readAsArrayBuffer(e.slice(d,u))};a.onload=d=>{let u=d.target?.result;if(!u){n(c.business("Failed to read file chunk"));return}l.append(u),r++,r<s?p():t({md5:l.end()})},a.onerror=()=>{n(c.business("Failed to calculate MD5: FileReader error"))},p()})}async function zt(e){let o=await import("crypto");if(Buffer.isBuffer(e)){let n=o.createHash("md5");return n.update(e),{md5:n.digest("hex")}}let t=await import("fs");return new Promise((n,i)=>{let s=o.createHash("md5"),r=t.createReadStream(e);r.on("error",l=>i(c.business(`Failed to read file for MD5: ${l.message}`))),r.on("data",l=>s.update(l)),r.on("end",()=>n({md5:s.digest("hex")}))})}async function ae(e){let o=P();if(o==="browser"){if(!(e instanceof Blob))throw c.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Kt(e)}if(o==="node"){if(!(Buffer.isBuffer(e)||typeof e=="string"))throw c.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return zt(e)}throw c.business("Unknown or unsupported execution environment for MD5 calculation.")}var Re=F(()=>{"use strict";Y();v()});function We(e,o){if(!e||e.length===0)return[];if(!o?.allowUnbuilt&&e.find(n=>n&&Ce(n)))throw c.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(t=>{if(!t)return!1;let n=t.replace(/\\/g,"/").split("/").filter(Boolean);if(n.length===0)return!0;let i=n[n.length-1];if((0,Ye.isJunk)(i))return!1;for(let r of n)if(r!==".well-known"&&(r.startsWith(".")||r.length>255))return!1;let s=n.slice(0,-1);for(let r of s)if(Vt.some(l=>r.toLowerCase()===l.toLowerCase()))return!1;return!0})}var Ye,Vt,Xe=F(()=>{"use strict";Ye=require("junk");v();Vt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ze(e){if(!e||e.length===0)return"";let o=e.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(o.length===0)return"";if(o.length===1)return o[0];let t=o.map(s=>s.split("/").filter(Boolean)),n=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i;s++){let r=t[0][s];if(t.every(l=>l[s]===r))n.push(r);else break}return n.join("/")}function pe(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Oe=F(()=>{"use strict"});function Qe(e,o={}){if(o.flatten===!1)return e.map(n=>({path:pe(n),name:ke(n)}));let t=qt(e);return e.map(n=>{let i=pe(n);if(t){let s=t.endsWith("/")?t:`${t}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=ke(n)),{path:i,name:ke(n)}})}function qt(e){if(!e.length)return"";let t=e.map(s=>pe(s)).map(s=>s.split("/")),n=[],i=Math.min(...t.map(s=>s.length));for(let s=0;s<i-1;s++){let r=t[0][s];if(t.every(l=>l[s]===r))n.push(r);else break}return n.join("/")}function ke(e){return e.split(/[/\\]/).pop()||e}var et=F(()=>{"use strict";Oe()});function tt(e){if(Le(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 o=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,t=e.split("/").pop()||e;return o.test(t)?{valid:!1,reason:"File name uses a reserved system name"}:e.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}var ot=F(()=>{"use strict";v()});function nt(e,o){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw c.business(`Security error: Unsafe file path "${e}" for file: ${o}`)}function it(e,o){let t=tt(e);if(!t.valid)throw c.business(t.reason||"Invalid file name");if(Se(e))throw c.business(`File extension not allowed: "${o}"`)}var st=F(()=>{"use strict";v();ot()});var at={};Lt(at,{processFilesForNode:()=>Jt});function rt(e,o=new Set){let t=[],n=O.realpathSync(e);if(o.has(n))return t;o.add(n);let i=O.readdirSync(e);for(let s of i){let r=k.join(e,s),l=O.statSync(r);if(l.isDirectory()){let a=rt(r,o);t.push(...a)}else l.isFile()&&t.push(r)}return t}async function Jt(e,o={}){if(P()!=="node")throw c.business("processFilesForNode can only be called in Node.js environment.");for(let m of e){let C=k.resolve(m);try{if(O.statSync(C).isDirectory()){let x=O.readdirSync(C).find(I=>be.has(I));if(x)throw c.business(`"${x}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(x){if(A(x))throw x}}let t=e.flatMap(m=>{let C=k.resolve(m);try{return O.statSync(C).isDirectory()?rt(C):[C]}catch{throw c.file(`Path does not exist: ${m}`,m)}}),n=[...new Set(t)],i=e.map(m=>k.resolve(m)),s=Ze(i.map(m=>{try{return O.statSync(m).isDirectory()?m:k.dirname(m)}catch{return k.dirname(m)}})),r=n.map(m=>{if(s&&s.length>0){let C=k.relative(s,m);if(C&&typeof C=="string"&&!C.startsWith(".."))return C.replace(/\\/g,"/")}return k.basename(m)}),a=Qe(r,{flatten:o.pathDetect!==!1}).map(m=>m.path),p=new Set(We(a));if(p.size===0)return[];let d=[],u=[];for(let m=0;m<n.length;m++)p.has(a[m])&&(d.push(n[m]),u.push(a[m]));let g=[],oe=0,M=se();for(let m=0;m<d.length;m++){let C=d[m],x=u[m];try{nt(x,C);let I=O.statSync(C);if(I.size===0)continue;if(it(x,C),I.size>M.maxFileSize)throw c.business(`File ${C} is too large. Maximum allowed size is ${M.maxFileSize/(1024*1024)}MB.`);if(oe+=I.size,oe>M.maxTotalSize)throw c.business(`Total deploy size is too large. Maximum allowed is ${M.maxTotalSize/(1024*1024)}MB.`);let J=O.readFileSync(C),{md5:At}=await ae(J);g.push({path:x,content:J,size:J.length,md5:At})}catch(I){if(A(I))throw I;let J=I instanceof Error?I.message:String(I);throw c.file(`Failed to read file "${C}": ${J}`,C)}}if(g.length>M.maxFilesCount)throw c.business(`Too many files to deploy. Maximum allowed is ${M.maxFilesCount} files.`);return g}var O,k,lt=F(()=>{"use strict";Y();Re();Xe();st();v();re();et();Oe();O=R(require("fs"),1),k=R(require("path"),1)});var Rt=require("commander");v();var ie=class{constructor(){this.handlers=new Map}on(o,t){this.handlers.has(o)||this.handlers.set(o,new Set),this.handlers.get(o).add(t)}off(o,t){let n=this.handlers.get(o);n&&(n.delete(t),n.size===0&&this.handlers.delete(o))}emit(o,...t){let n=this.handlers.get(o);if(!n)return;let i=Array.from(n);for(let s of i)try{s(...t)}catch(r){n.delete(s),o!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(o)):this.emit("error",new Error(String(r)),String(o))},0)}}transfer(o){this.handlers.forEach((t,n)=>{t.forEach(i=>{o.on(n,i)})})}clear(){this.handlers.clear()}};var D={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},jt=3e4,G=class extends ie{constructor(t){super();this.globalHeaders={};this.apiUrl=t.apiUrl||B,this.getAuthHeadersCallback=t.getAuthHeaders,this.useCredentials=t.useCredentials??!1,this.timeout=t.timeout??jt,this.createDeployBody=t.createDeployBody,this.deployEndpoint=t.deployEndpoint||D.DEPLOYMENTS}setGlobalHeaders(t){this.globalHeaders=t}transferEventsTo(t){this.transfer(t)}async executeRequest(t,n,i){let s=this.mergeHeaders(n.headers),{signal:r,cleanup:l}=this.createTimeoutSignal(n.signal),a={...n,headers:s,credentials:this.useCredentials&&!s.Authorization?"include":void 0,signal:r};this.emit("request",t,a);try{let p=await fetch(t,a);return l(),p.ok||await this.handleResponseError(p,i),this.emit("response",this.safeClone(p),t),{data:await this.parseResponse(this.safeClone(p)),status:p.status}}catch(p){l();let d=p instanceof Error?p:new Error(String(p));this.emit("error",d,t),this.handleFetchError(p,i)}}async request(t,n,i){let{data:s}=await this.executeRequest(t,n,i);return s}async requestWithStatus(t,n,i){return this.executeRequest(t,n,i)}mergeHeaders(t={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...t}}createTimeoutSignal(t){let n=new AbortController,i=setTimeout(()=>n.abort(),this.timeout);if(t){let s=()=>n.abort();t.addEventListener("abort",s),t.aborted&&n.abort()}return{signal:n.signal,cleanup:()=>clearTimeout(i)}}safeClone(t){try{return t.clone()}catch{return t}}async parseResponse(t){if(!(t.headers.get("Content-Length")==="0"||t.status===204))return t.json()}async handleResponseError(t,n){let i={};try{if(t.headers.get("content-type")?.includes("application/json")){let l=await t.json();if(l&&typeof l=="object"){let a=l;typeof a.message=="string"&&(i.message=a.message),typeof a.error=="string"&&(i.error=a.error)}}else i={message:await t.text()}}catch{i={message:"Failed to parse error response"}}let s=i.message||i.error||`${n} failed`;throw t.status===401?c.authentication(s):c.api(s,t.status)}handleFetchError(t,n){throw A(t)?t:t instanceof Error&&t.name==="AbortError"?c.cancelled(`${n} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?c.network(`${n} failed: ${t.message}`,t):t instanceof Error?c.business(`${n} failed: ${t.message}`):c.business(`${n} failed: Unknown error`)}async deploy(t,n={}){if(!t.length)throw c.business("No files to deploy");for(let a of t)if(!a.md5)throw c.file(`MD5 checksum missing for file: ${a.path}`,a.path);let i=n.build||n.prerender?{build:n.build,prerender:n.prerender}:void 0,{body:s,headers:r}=await this.createDeployBody(t,n.labels,n.via,i),l={};return n.deployToken?l.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(l.Authorization=`Bearer ${n.apiKey}`),n.caller&&(l["X-Caller"]=n.caller),this.request(`${n.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:s,headers:{...r,...l},signal:n.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${D.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(t){return this.request(`${this.apiUrl}${D.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(t,n){return this.request(`${this.apiUrl}${D.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:n})},"Update deployment labels")}async removeDeployment(t){await this.request(`${this.apiUrl}${D.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove deployment")}async setDomain(t,n,i){let s={};n&&(s.deployment=n),i!==void 0&&(s.labels=i);let{data:r,status:l}=await this.requestWithStatus(`${this.apiUrl}${D.DOMAINS}/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Set domain");return{...r,isCreate:l===201}}async listDomains(){return this.request(`${this.apiUrl}${D.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(t){return this.request(`${this.apiUrl}${D.DOMAINS}/${encodeURIComponent(t)}`,{method:"GET"},"Get domain")}async removeDomain(t){await this.request(`${this.apiUrl}${D.DOMAINS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(t){return this.request(`${this.apiUrl}${D.DOMAINS}/${encodeURIComponent(t)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(t){return this.request(`${this.apiUrl}${D.DOMAINS}/${encodeURIComponent(t)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(t){return this.request(`${this.apiUrl}${D.DOMAINS}/${encodeURIComponent(t)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(t){return this.request(`${this.apiUrl}${D.DOMAINS}/${encodeURIComponent(t)}/share`,{method:"GET"},"Get domain share")}async validateDomain(t){return this.request(`${this.apiUrl}${D.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:t})},"Validate domain")}async createToken(t,n){let i={};return t!==void 0&&(i.ttl=t),n!==void 0&&(i.labels=n),this.request(`${this.apiUrl}${D.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${D.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(t){await this.request(`${this.apiUrl}${D.TOKENS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove token")}async fetchAgentToken(){return this.request(`${this.apiUrl}${D.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent token")}async getAccount(){return this.request(`${this.apiUrl}${D.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${D.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${D.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(t,n={}){let i=t.find(p=>p.path==="index.html"||p.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 r={"Content-Type":"application/json"};n.deployToken?r.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(r.Authorization=`Bearer ${n.apiKey}`);let l={files:t.map(p=>p.path),index:s};return(await this.request(`${this.apiUrl}${D.SPA_CHECK}`,{method:"POST",headers:r,body:JSON.stringify(l)},"SPA check")).isSPA}};v();re();v();v();function Ee(e={},o={}){let t={apiUrl:e.apiUrl||o.apiUrl||B,apiKey:e.apiKey!==void 0?e.apiKey:o.apiKey,deployToken:e.deployToken!==void 0?e.deployToken:o.deployToken},n={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(n.apiKey=t.apiKey),t.deployToken!==void 0&&(n.deployToken=t.deployToken),n}function je(e,o){let t={...e};return t.apiUrl===void 0&&o.apiUrl!==void 0&&(t.apiUrl=o.apiUrl),t.apiKey===void 0&&o.apiKey!==void 0&&(t.apiKey=o.apiKey),t.deployToken===void 0&&o.deployToken!==void 0&&(t.deployToken=o.deployToken),t.timeout===void 0&&o.timeout!==void 0&&(t.timeout=o.timeout),t.maxConcurrency===void 0&&o.maxConcurrency!==void 0&&(t.maxConcurrency=o.maxConcurrency),t.onProgress===void 0&&o.onProgress!==void 0&&(t.onProgress=o.onProgress),t.caller===void 0&&o.caller!==void 0&&(t.caller=o.caller),t}v();Re();async function Bt(){let o=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(o,"utf-8"):t=new Blob([o],{type:"application/json"});let{md5:n}=await ae(t);return{path:ve,content:t,size:o.length,md5:n}}async function Ke(e,o,t){if(t.spaDetect===!1||t.build||t.prerender||e.some(n=>n.path===ve))return e;try{if(await o.checkSPA(e,t)){let i=await Bt();return[...e,i]}}catch{}return e}function ze(e){let{getApi:o,ensureInit:t,processInput:n,clientDefaults:i,hasAuth:s}=e;return{upload:async(r,l={})=>{await t();let a=i?je(l,i):l;if(s&&!s()&&!a.deployToken&&!a.apiKey)try{let u=o(),{secret:g}=await u.fetchAgentToken();a.deployToken=g}catch{throw c.authentication("Too many requests; try again later or configure a free API key with 'ship config'")}if(!n)throw c.config("processInput function is not provided.");let p=o(),d=await n(r,a);return d=await Ke(d,p,a),p.deploy(d,a)},list:async()=>(await t(),o().listDeployments()),get:async r=>(await t(),o().getDeployment(r)),set:async(r,l)=>(await t(),o().updateDeploymentLabels(r,l.labels)),remove:async r=>{await t(),await o().removeDeployment(r)}}}function Be(e){let{getApi:o,ensureInit:t}=e;return{set:async(n,i={})=>(await t(),o().setDomain(n,i.deployment,i.labels)),list:async()=>(await t(),o().listDomains()),get:async n=>(await t(),o().getDomain(n)),remove:async n=>{await t(),await o().removeDomain(n)},verify:async n=>(await t(),o().verifyDomain(n)),validate:async n=>(await t(),o().validateDomain(n)),dns:async n=>(await t(),o().getDomainDns(n)),records:async n=>(await t(),o().getDomainRecords(n)),share:async n=>(await t(),o().getDomainShare(n))}}function Ge(e){let{getApi:o,ensureInit:t}=e;return{get:async()=>(await t(),o().getAccount())}}function He(e){let{getApi:o,ensureInit:t}=e;return{create:async(n={})=>(await t(),o().createToken(n.ttl,n.labels)),list:async()=>(await t(),o().listTokens()),remove:async n=>{await t(),await o().removeToken(n)}}}var le=class{constructor(o={}){this.initPromise=null;this._config=null;this.auth=null;this.customHeaders={};this.clientOptions=o,o.deployToken?this.auth={type:"token",value:o.deployToken}:o.apiKey&&(this.auth={type:"apiKey",value:o.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(o);this.http=new G({...o,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=ze({...n,processInput:(i,s)=>this.processInput(i,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=Be(n),this._account=Ge(n),this._tokens=He(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(o,t){return this.deployments.upload(o,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=se(),this._config)}on(o,t){this.http.on(o,t)}off(o,t){this.http.off(o,t)}setHeaders(o){this.customHeaders=o,this.http.setGlobalHeaders(o)}clearHeaders(){this.customHeaders={},this.http.setGlobalHeaders({})}replaceHttpClient(o){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(o)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=o,Object.keys(this.customHeaders).length>0&&this.http.setGlobalHeaders(this.customHeaders)}setDeployToken(o){if(!o||typeof o!="string")throw c.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:o}}setApiKey(o){if(!o||typeof o!="string")throw c.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:o}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};v();Y();var H=require("zod");v();Y();var Te="ship",Gt=H.z.object({apiUrl:H.z.string().url().optional(),apiKey:H.z.string().optional(),deployToken:H.z.string().optional()}).strict();function Ve(e){try{return Gt.parse(e)}catch(o){if(o instanceof H.z.ZodError){let t=o.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw c.config(`Configuration validation failed${n}: ${t.message}`)}throw c.config("Configuration validation failed")}}async function Ht(e){try{if(P()!=="node")return{};let{cosmiconfigSync:o}=await import("cosmiconfig"),t=await import("os"),n=o(Te,{searchPlaces:[`.${Te}rc`,"package.json",`${t.homedir()}/.${Te}rc`],stopDir:t.homedir()}),i;if(e?i=n.load(e):i=n.search(),i&&i.config)return Ve(i.config)}catch(o){if(A(o))throw o}return{}}async function qe(e){if(P()!=="node")return{};let o={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await Ht(e),n={apiUrl:o.apiUrl??t.apiUrl,apiKey:o.apiKey??t.apiKey,deployToken:o.deployToken??t.deployToken};return Ve(n)}re();v();async function Je(e,o,t,n){let{FormData:i,File:s}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),l=new i,a=[];for(let g of e){if(!Buffer.isBuffer(g.content)&&!(typeof Blob<"u"&&g.content instanceof Blob))throw c.file(`Unsupported file.content type for Node.js: ${g.path}`,g.path);if(!g.md5)throw c.file(`File missing md5 checksum: ${g.path}`,g.path);let oe=new s([g.content],g.path,{type:"application/octet-stream"});l.append("files[]",oe),a.push(g.md5)}l.append("checksums",JSON.stringify(a)),o&&o.length>0&&l.append("labels",JSON.stringify(o)),t&&l.append("via",t),n?.build&&l.append("build","true"),n?.prerender&&l.append("prerender","true");let p=new r(l),d=[];for await(let g of p.encode())d.push(Buffer.from(g));let u=Buffer.concat(d);return{body:u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),headers:{"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(u).toString()}}}var ce=class extends le{constructor(o={}){if(P()!=="node")throw c.business("Node.js Ship class can only be used in Node.js environment.");super(o)}resolveInitialConfig(o){return Ee(o,{})}async loadFullConfig(){try{let o=await qe(this.clientOptions.configFile),t=Ee(this.clientOptions,o);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let n=new G({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();Ue(i)}catch(o){throw this.initPromise=null,o}}async processInput(o,t){let n=typeof o=="string"?[o]:o;if(!Array.isArray(n)||!n.every(s=>typeof s=="string"))throw c.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw c.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(lt(),at));return i(n,t)}getDeployBodyCreator(){return Je}};v();var j=require("fs"),ue=R(require("path"),1);var Ae=R(require("columnify"),1),f=require("yoctocolors"),pt=["isCreate","claim"],w=(e,o,t)=>t?o:e(o),E=(e,o,t)=>{console.log(o?JSON.stringify({success:e},null,2)+`
|
|
3
|
+
`:`${w(f.green,e.toLowerCase().replace(/\.$/,""),t)}
|
|
4
4
|
`)},T=(e,o,t)=>{if(o)console.error(JSON.stringify({error:e},null,2)+`
|
|
5
|
-
`);else{let n=w(s=>(0,
|
|
6
|
-
`)}},
|
|
7
|
-
`);else{let n=w(s=>(0,
|
|
8
|
-
`)}},
|
|
9
|
-
`);else{let n=w(s=>(0,
|
|
10
|
-
`)}},
|
|
11
|
-
`).map(
|
|
5
|
+
`);else{let n=w(s=>(0,f.inverse)((0,f.red)(s)),`${w(f.hidden,"[",t)}error${w(f.hidden,"]",t)}`,t),i=w(f.red,e.toLowerCase().replace(/\.$/,""),t);console.error(`${n} ${i}
|
|
6
|
+
`)}},de=(e,o,t)=>{if(o)console.log(JSON.stringify({warning:e},null,2)+`
|
|
7
|
+
`);else{let n=w(s=>(0,f.inverse)((0,f.yellow)(s)),`${w(f.hidden,"[",t)}warning${w(f.hidden,"]",t)}`,t),i=w(f.yellow,e.toLowerCase().replace(/\.$/,""),t);console.log(`${n} ${i}
|
|
8
|
+
`)}},_=(e,o,t)=>{if(o)console.log(JSON.stringify({info:e},null,2)+`
|
|
9
|
+
`);else{let n=w(s=>(0,f.inverse)((0,f.blue)(s)),`${w(f.hidden,"[",t)}info${w(f.hidden,"]",t)}`,t),i=w(f.blue,e.toLowerCase().replace(/\.$/,""),t);console.log(`${n} ${i}
|
|
10
|
+
`)}},Yt=(e,o="details",t)=>{if(e==null||e===0)return"-";let n=new Date(e*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return o==="table"?n.replace(/T/,w(f.hidden,"T",t)).replace(/Z$/,w(f.hidden,"Z",t)):n},ct=(e,o,t="details",n)=>{if(o===null||Array.isArray(o)&&o.length===0)return"-";if(typeof o=="number"&&(e==="created"||e==="activated"||e==="expires"||e==="linked"||e==="grace"))return Yt(o,t,n);if(e==="size"&&typeof o=="number"){let i=o/1048576;return i>=1?`${i.toFixed(1)}Mb`:`${(o/1024).toFixed(1)}Kb`}if(e==="config"){if(typeof o=="boolean")return o?"yes":"no";if(typeof o=="number")return o===1?"yes":"no"}return String(o)},W=(e,o,t,n)=>{if(!e||e.length===0)return"";let i=e[0],s=o||Object.keys(i).filter(a=>i[a]!==void 0&&!pt.includes(a)),r=e.map(a=>{let p=a,d={};return s.forEach(u=>{u in p&&p[u]!==void 0&&(d[u]=ct(u,p[u],"table",t))}),d});return(0,Ae.default)(r,{columnSplitter:" ",columns:s,config:s.reduce((a,p)=>(a[p]={headingTransform:d=>w(f.dim,n?.[d]||d,t)},a),{})}).split(`
|
|
11
|
+
`).map(a=>a.replace(/\0/g,"").replace(/\s+$/,"")).join(`
|
|
12
12
|
`)+`
|
|
13
|
-
`},V=(e,o)=>{let t=Object.entries(e).filter(([s,r])=>
|
|
13
|
+
`},V=(e,o)=>{let t=Object.entries(e).filter(([s,r])=>pt.includes(s)?!1:r!==void 0);if(t.length===0)return"";let n=t.map(([s,r])=>({property:s+":",value:ct(s,r,"details",o)}));return(0,Ae.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>w(f.dim,s,o)}}}).split(`
|
|
14
14
|
`).map(s=>s.replace(/\0/g,"")).join(`
|
|
15
15
|
`)+`
|
|
16
|
-
`};var
|
|
16
|
+
`};var xe=(e,o)=>`https://setup.shipstatic.com/${e}/${o}`;function Wt(e,o,t){let{noColor:n}=t;if(e.deployments.length===0){console.log("no deployments found"),console.log();return}let i=["deployment","labels","files","size","created","via"];console.log(W(e.deployments,i,n))}function Xt(e,o,t){let{noColor:n}=t;if(e.domains.length===0){console.log("no domains found"),console.log();return}let i=["domain","deployment","labels","linked","links","created"];console.log(W(e.domains,i,n))}function Zt(e,o,t){let{noColor:n}=t,{_dnsRecords:i,_shareHash:s,isCreate:r,...l}=e;if(o.operation==="set"){let a=r?"created":"updated";E(`https://${e.domain} domain ${a}`,!1,n)}i&&i.length>0&&(console.log(),_("DNS Records to configure:",!1,n),i.forEach(a=>{console.log(` ${a.type}: ${a.name} \u2192 ${a.value}`)})),s&&(console.log(),_(`Setup instructions: ${xe(s,e.domain)}`,!1,n)),console.log(V(l,n))}function Qt(e,o,t){let{noColor:n}=t;o.operation==="upload"&&E(`https://${e.deployment} deployment uploaded`,!1,n),console.log(V(e,n));let i=e.claim;i&&(console.log(`claim to keep permanently:
|
|
17
17
|
${i}
|
|
18
|
-
`),
|
|
18
|
+
`),_("configure a free API key with 'ship config' to deploy to your own account",!1,n))}function eo(e,o,t){let{noColor:n}=t;console.log(V(e,n))}function to(e,o,t){let{noColor:n}=t;e.message&&E(e.message,!1,n)}function oo(e,o,t){let{noColor:n}=t;if(e.valid){if(E("domain is valid",!1,n),console.log(),e.normalized&&console.log(` normalized: ${e.normalized}`),e.available!==null){let i=e.available?n?"available":"available \u2713":"already taken";console.log(` availability: ${i}`)}console.log()}else T(e.error||"domain is invalid",!1,n)}function no(e,o,t){let{noColor:n}=t;if(e.records.length===0){console.log("no records found"),console.log();return}let i=["type","name","value"];console.log(W(e.records,i,n))}function io(e,o,t){let{noColor:n}=t,i=e.dns?.provider?.name||null;console.log(V({domain:e.domain,provider:i},n))}function so(e,o,t){let{noColor:n}=t;E(xe(e.hash,e.domain),!1,n)}function ro(e,o,t){let{noColor:n}=t;if(e.tokens.length===0){console.log("no tokens found"),console.log();return}let i=["token","labels","created","expires"];console.log(W(e.tokens,i,n))}function ao(e,o,t){let{noColor:n}=t;o.operation==="create"&&e.token&&E(`token ${e.token} created`,!1,n),console.log(V(e,n))}function dt(e,o,t){let{json:n,quiet:i,noColor:s}=t;if(i){if(e===void 0||typeof e=="boolean")return;if(e!==null&&typeof e=="object")if("deployments"in e)e.deployments.forEach(r=>console.log(r.deployment));else if("domains"in e)e.domains.forEach(r=>console.log(r.domain));else if("tokens"in e)e.tokens.forEach(r=>console.log(r.token));else if("records"in e)e.records.forEach(r=>console.log(`${r.type} ${r.name} ${r.value}`));else if("hash"in e){let r=e;console.log(xe(r.hash,r.domain))}else if("dns"in e){let r=e.dns?.provider?.name;r&&console.log(r)}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("email"in e)console.log(e.email);else if("valid"in e){let r=e;r.valid&&r.normalized&&console.log(r.normalized)}else"message"in e&&console.log(e.message);return}if(e===void 0){if(o.operation==="remove"&&o.resourceType&&o.resourceId){let r=o.resourceType!=="Token"?"https://":"";E(`${r}${o.resourceId} ${o.resourceType.toLowerCase()} removed`,n,s)}else E("removed successfully",n,s);return}if(typeof e=="boolean"){e?E("api reachable",n,s):T("api unreachable",n,s);return}if(n&&e!==null&&typeof e=="object"){let r={...e};delete r._dnsRecords,delete r._shareHash,delete r.isCreate,console.log(JSON.stringify(r,null,2)),console.log();return}e!==null&&typeof e=="object"?"deployments"in e?Wt(e,o,t):"domains"in e?Xt(e,o,t):"tokens"in e?ro(e,o,t):"records"in e?no(e,o,t):"hash"in e?so(e,o,t):"dns"in e?io(e,o,t):"domain"in e?Zt(e,o,t):"deployment"in e?Qt(e,o,t):"token"in e?ao(e,o,t):"email"in e?eo(e,o,t):"valid"in e?oo(e,o,t):"message"in e?to(e,o,t):E("success",n,s):E("success",n,s)}var S=R(require("fs"),1),L=R(require("path"),1),Ie=R(require("os"),1);function mt(){let e=process.env.SHELL||"";return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":null}function ut(e,o){switch(e){case"bash":return{completionFile:L.join(o,".ship_completion.bash"),profileFile:L.join(o,".bash_profile"),scriptName:"ship.bash"};case"zsh":return{completionFile:L.join(o,".ship_completion.zsh"),profileFile:L.join(o,".zshrc"),scriptName:"ship.zsh"};case"fish":return{completionFile:L.join(o,".config/fish/completions/ship.fish"),profileFile:null,scriptName:"ship.fish"}}}function ft(e,o={}){let{json:t,noColor:n}=o,i=mt(),s=Ie.homedir();if(!i){T(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,t,n);return}let r=ut(i,s),l=L.join(e,r.scriptName);try{if(i==="fish"){let p=L.dirname(r.completionFile);S.existsSync(p)||S.mkdirSync(p,{recursive:!0}),S.copyFileSync(l,r.completionFile),E("fish completion installed successfully",t,n),_("please restart your shell to apply the changes",t,n);return}S.copyFileSync(l,r.completionFile);let a=`# ship
|
|
19
19
|
source '${r.completionFile}'
|
|
20
20
|
# ship end`;if(r.profileFile){if(S.existsSync(r.profileFile)){let p=S.readFileSync(r.profileFile,"utf-8");if(!p.includes("# ship")||!p.includes("# ship end")){let d=p.length>0&&!p.endsWith(`
|
|
21
21
|
`)?`
|
|
22
|
-
`:"";S.appendFileSync(r.profileFile,d+
|
|
23
|
-
`),
|
|
24
|
-
`),
|
|
25
|
-
`)+(
|
|
26
|
-
`:"");S.writeFileSync(s.profileFile,
|
|
27
|
-
`);return}let s=
|
|
22
|
+
`:"";S.appendFileSync(r.profileFile,d+a)}}else S.writeFileSync(r.profileFile,a);E(`completion script installed for ${i}`,t,n),de(`run "source ${r.profileFile}" or restart your shell`,t,n)}}catch(a){let p=a instanceof Error?a.message:String(a);T(`could not install completion script: ${p}`,t,n)}}function ht(e={}){let{json:o,noColor:t}=e,n=mt(),i=Ie.homedir();if(!n){T(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,o,t);return}let s=ut(n,i);try{if(n==="fish"){S.existsSync(s.completionFile)?(S.unlinkSync(s.completionFile),E("fish completion uninstalled successfully",o,t)):de("fish completion was not installed",o,t),_("please restart your shell to apply the changes",o,t);return}if(S.existsSync(s.completionFile)&&S.unlinkSync(s.completionFile),!s.profileFile)return;if(!S.existsSync(s.profileFile)){T("profile file not found",o,t);return}let r=S.readFileSync(s.profileFile,"utf-8"),l=r.split(`
|
|
23
|
+
`),a=[],p=0,d=!1;for(;p<l.length;)if(l[p].trim()==="# ship"){for(d=!0,p++;p<l.length&&l[p].trim()!=="# ship end";)p++;p<l.length&&p++}else a.push(l[p]),p++;if(d){let u=r.endsWith(`
|
|
24
|
+
`),g=a.length===0?"":a.join(`
|
|
25
|
+
`)+(u?`
|
|
26
|
+
`:"");S.writeFileSync(s.profileFile,g),E(`completion script uninstalled for ${n}`,o,t),de(`run "source ${s.profileFile}" or restart your shell`,o,t)}else T("completion was not found in profile",o,t)}catch(r){let l=r instanceof Error?r.message:String(r);T(`could not uninstall completion script: ${l}`,o,t)}}var Dt=require("readline/promises"),U=require("fs"),St=require("os"),bt=require("path");v();var me=require("yoctocolors"),q=(0,bt.join)((0,St.homedir)(),".shiprc");function gt(e){return e.length<13?e:e.slice(0,9)+"..."+e.slice(-4)}function yt(){try{return(0,U.existsSync)(q)?JSON.parse((0,U.readFileSync)(q,"utf-8")):{}}catch{return{}}}async function Ct(e={}){let{noColor:o,json:t}=e,n=d=>o?d:(0,me.dim)(d),i=d=>o?d:(0,me.green)(d);if(t){let d=yt(),u=typeof d.apiKey=="string"?d.apiKey:void 0,g=typeof d.apiUrl=="string"?d.apiUrl:void 0;console.log(JSON.stringify({path:q,exists:(0,U.existsSync)(q),...u?{apiKey:gt(u)}:{},...g&&g!==B?{apiUrl:g}:{}},null,2)+`
|
|
27
|
+
`);return}let s=yt(),r=typeof s.apiKey=="string"?s.apiKey:void 0,l=(0,Dt.createInterface)({input:process.stdin,output:process.stdout});console.log(""),console.log(` ${n("Create a free API key at")} https://my.shipstatic.com/api-key`),console.log("");let a=r?` API Key (${n(gt(r))}): `:" API Key: ",p;try{p=(await l.question(a)).trim()}finally{l.close()}p&&(ne(p),s.apiKey=p),(0,U.writeFileSync)(q,JSON.stringify(s,null,2)+`
|
|
28
28
|
`),console.log(`
|
|
29
29
|
${i("saved to")} ${n(q)}
|
|
30
|
-
`)}v();function
|
|
30
|
+
`)}v();function vt(e){return A(e)?e:e instanceof Error?c.business(e.message):c.business(String(e??"Unknown error"))}function wt(e,o,t){if(e.isAuthError())return t?.apiKey?"authentication failed: invalid API key":t?.deployToken?"authentication failed: invalid or expired deploy token":"authentication required: use --api-key or --deploy-token, or set SHIP_API_KEY";if(e.isNetworkError()){let n=e.details?.url;return n?`network error: could not reach ${n}`:"network error: could not reach the API. check your internet connection"}return e.isFileError()||e.isValidationError()||e.isClientError()||e.status&&e.status>=400&&e.status<500?e.message:"server error: please try again or check https://status.shipstatic.com"}function Et(e,o){return JSON.stringify({error:e,...o?{details:o}:{}},null,2)}var fe=require("yoctocolors");function lo(){let e=[ue.resolve(__dirname,"../package.json"),ue.resolve(__dirname,"../../package.json")];for(let o of e)try{return JSON.parse((0,j.readFileSync)(o,"utf-8"))}catch{}return{version:"0.0.0"}}var po=lo(),h=new Rt.Command;h.exitOverride(e=>{(e.code==="commander.help"||e.code==="commander.version"||e.exitCode===0)&&process.exit(e.exitCode||0),process.argv.includes("--help")&&(X($(h).noColor),process.exit(0));let o=$(h),t=e.message||"unknown command error";t=t.replace(/^error: /,"").replace(/\n.*/,"").replace(/\.$/,"").toLowerCase(),T(t,o.json,o.noColor),o.json||X(o.noColor),process.exit(e.exitCode||1)}).configureOutput({writeErr:e=>{e.startsWith("error:")||process.stderr.write(e)},writeOut:e=>process.stdout.write(e)});function X(e){let o=s=>e?s:(0,fe.bold)(s),t=s=>e?s:(0,fe.dim)(s),n=s=>e?"":`${s} `,i=`${o("USAGE")}
|
|
31
31
|
ship <path> ${n("\u{1F680}")}Deploy static sites with simplicity
|
|
32
32
|
|
|
33
33
|
${o("COMMANDS")}
|
|
@@ -80,8 +80,8 @@ ${o("EXAMPLES")}
|
|
|
80
80
|
ship ./dist -q | ship domains set www.example.com
|
|
81
81
|
|
|
82
82
|
${t("Please report any issues to https://github.com/shipstatic/ship/issues")}
|
|
83
|
-
`;console.log(i)}function Z(e,o=[]){return o.concat([e])}function Q(e,o){let t=e?.label?.length?e.label:o?.label;if(!t?.length)return;let n=t.filter(i=>i!=="");return n.length?n:[]}function ee(e,o){return(...t)=>{let n=$(
|
|
84
|
-
`),process.exit(1)}}function $(e){let o=e.optsWithGlobals();o.color===!1&&(o.noColor=!0);let t=!!process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0";return!o.noColor&&!t&&(!process.stdout.isTTY||process.env.NO_COLOR!==void 0)&&(o.noColor=!0),o}function
|
|
85
|
-
`):(T(i,!1,t.noColor),n.isValidationError()&&i.includes("unknown command")&&X(t.noColor)),process.exit(1)}function b(e,o){return async function(...t){let n=$(this),i=o?{operation:o.operation,resourceType:o.resourceType,resourceId:o.getResourceId?.(...t)}:{};try{let s=
|
|
86
|
-
`:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&
|
|
83
|
+
`;console.log(i)}function Z(e,o=[]){return o.concat([e])}function Q(e,o){let t=e?.label?.length?e.label:o?.label;if(!t?.length)return;let n=t.filter(i=>i!=="");return n.length?n:[]}function ee(e,o){return(...t)=>{let n=$(h),i=t[t.length-1];if(i?.args?.length){let s=i.args.find(r=>!o.includes(r));s&&T(`unknown command '${s}'`,n.json,n.noColor)}n.json||console.log(`usage: ship ${e} <${o.join("|")}>
|
|
84
|
+
`),process.exit(1)}}function $(e){let o=e.optsWithGlobals();o.color===!1&&(o.noColor=!0);let t=!!process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0";return!o.noColor&&!t&&(!process.stdout.isTTY||process.env.NO_COLOR!==void 0)&&(o.noColor=!0),o}function Tt(e,o){let t=$(h),n=vt(e),i=wt(n,o,{apiKey:t.apiKey,deployToken:t.deployToken});t.json?console.error(Et(i,n.details)+`
|
|
85
|
+
`):(T(i,!1,t.noColor),n.isValidationError()&&i.includes("unknown command")&&X(t.noColor)),process.exit(1)}function b(e,o){return async function(...t){let n=$(this),i=o?{operation:o.operation,resourceType:o.resourceType,resourceId:o.getResourceId?.(...t)}:{};try{let s=co(),r=await e(s,n,...t);dt(r,i,{json:n.json,quiet:n.quiet,noColor:n.noColor})}catch(s){Tt(s,i)}}}function co(){let{config:e,apiUrl:o,apiKey:t,deployToken:n}=h.opts();return new ce({configFile:e,apiUrl:o,apiKey:t,deployToken:n})}async function Ot(e,o,t,n,i){if(!(0,j.existsSync)(o))throw c.file(`${o} path does not exist`,o);let s=(0,j.statSync)(o);if(!s.isDirectory()&&!s.isFile())throw c.file(`${o} path must be a file or directory`,o);let r={via:process.env.SHIP_VIA||"cli"};t!==void 0&&(r.labels=t),n?.noPathDetect!==void 0&&(r.pathDetect=!n.noPathDetect),n?.noSpaDetect!==void 0&&(r.spaDetect=!n.noSpaDetect);let l=new AbortController;r.signal=l.signal;let a=null;if(process.stdout.isTTY&&!i.json&&!i.quiet&&!i.noColor){let{default:d}=await import("yocto-spinner");a=d({text:"uploading\u2026"}).start()}let p=()=>{l.abort(),a&&a.stop(),process.exit(130)};process.on("SIGINT",p);try{return await e.deployments.upload(o,r)}finally{process.removeListener("SIGINT",p),a&&a.stop()}}h.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(po.version,"--version","Show version information").option("--api-key <key>","API key for authenticated deployments").option("--deploy-token <token>","Deploy token for single-use deployments").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").option("--help","Display help for command").helpOption(!1);h.hook("preAction",e=>{let o=$(e);o.help&&(X(o.noColor),process.exit(0))});h.hook("preAction",e=>{let o=$(e);try{o.apiKey&&typeof o.apiKey=="string"&&ne(o.apiKey),o.deployToken&&typeof o.deployToken=="string"&&Ne(o.deployToken),o.apiUrl&&typeof o.apiUrl=="string"&&_e(o.apiUrl)}catch(t){throw A(t)&&(T(t.message,o.json,o.noColor),process.exit(1)),t}});h.command("ping").description("Check API connectivity").action(b((e,o)=>e.ping()));h.command("whoami").description("Get current account information").action(b((e,o)=>e.whoami(),{operation:"get",resourceType:"Account"}));var te=h.command("deployments").description("Manage deployments").enablePositionalOptions().action(ee("deployments",["list","upload","get","set","remove"]));te.command("list").description("List all deployments").action(b((e,o)=>e.deployments.list()));te.command("upload <path>").description("Upload deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",Z,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(b((e,o,t,n)=>Ot(e,t,Q(n,h.opts()),n,o),{operation:"upload"}));te.command("get <deployment>").description("Show deployment information").action(b((e,o,t)=>e.deployments.get(t),{operation:"get",resourceType:"Deployment",getResourceId:e=>e}));te.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",Z,[]).action(b(async(e,o,t,n)=>{let i=Q(n,h.opts())||[];return e.deployments.set(t,{labels:i})},{operation:"set",resourceType:"Deployment",getResourceId:e=>e}));te.command("remove <deployment>").description("Delete deployment permanently").action(b((e,o,t)=>e.deployments.remove(t),{operation:"remove",resourceType:"Deployment",getResourceId:e=>e}));var N=h.command("domains").description("Manage domains").enablePositionalOptions().action(ee("domains",["list","get","set","validate","records","dns","share","verify","remove"]));N.command("list").description("List all domains").action(b((e,o)=>e.domains.list()));N.command("get <name>").description("Show domain information").action(b((e,o,t)=>e.domains.get(t),{operation:"get",resourceType:"Domain",getResourceId:e=>e}));N.command("validate <name>").description("Check if domain name is valid and available").action(b(async(e,o,t)=>{let n=await e.domains.validate(t);return n.valid||(process.exitCode=1),n},{operation:"validate",resourceType:"Domain",getResourceId:e=>e}));N.command("verify <name>").description("Trigger DNS verification for external domain").action(b((e,o,t)=>e.domains.verify(t),{operation:"verify",resourceType:"Domain",getResourceId:e=>e}));N.command("records <name>").description("Show required DNS records for domain setup").action(b((e,o,t)=>e.domains.records(t),{operation:"records",resourceType:"Domain",getResourceId:e=>e}));N.command("dns <name>").description("Look up DNS provider for a domain").action(b((e,o,t)=>e.domains.dns(t),{operation:"dns",resourceType:"Domain",getResourceId:e=>e}));N.command("share <name>").description("Get shareable DNS setup link").action(b((e,o,t)=>e.domains.share(t),{operation:"share",resourceType:"Domain",getResourceId:e=>e}));N.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",Z,[]).action(b(async(e,o,t,n,i)=>{!n&&!process.stdin.isTTY&&(n=await new Promise(a=>{let p="";process.stdin.on("data",d=>p+=d),process.stdin.on("end",()=>a(p.trim()||void 0))}));let s=Q(i,h.opts()),r={};n&&(r.deployment=n),s!==void 0&&(r.labels=s);let l=await e.domains.set(t,r);if(l.isCreate&&t.includes("."))try{let[a,p]=await Promise.all([e.domains.records(t),e.domains.share(t)]);return{...l,_dnsRecords:a.records,_shareHash:p.hash}}catch{}return l},{operation:"set",resourceType:"Domain",getResourceId:e=>e}));N.command("remove <name>").description("Delete domain permanently").action(b((e,o,t)=>e.domains.remove(t),{operation:"remove",resourceType:"Domain",getResourceId:e=>e}));var Fe=h.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(ee("tokens",["list","create","remove"]));Fe.command("list").description("List all tokens").action(b((e,o)=>e.tokens.list()));Fe.command("create").description("Create a new deploy token").option("--ttl <seconds>","Time to live in seconds (default: never expires)",parseInt).option("--label <label>","Label to set (can be repeated)",Z,[]).action(b((e,o,t)=>{let n={};t?.ttl!==void 0&&(n.ttl=t.ttl);let i=Q(t,h.opts());return i!==void 0&&(n.labels=i),e.tokens.create(n)},{operation:"create",resourceType:"Token"}));Fe.command("remove <token>").description("Delete token permanently").action(b((e,o,t)=>e.tokens.remove(t),{operation:"remove",resourceType:"Token",getResourceId:e=>e}));var mo=h.command("account").description("Manage account").action(ee("account",["get"]));mo.command("get").description("Show account information").action(b((e,o)=>e.whoami(),{operation:"get",resourceType:"Account"}));var kt=h.command("completion").description("Setup shell completion").action(ee("completion",["install","uninstall"]));kt.command("install").description("Install shell completion script").action(()=>{let e=$(h),o=ue.resolve(__dirname,"completions");ft(o,{json:e.json,noColor:e.noColor})});kt.command("uninstall").description("Uninstall shell completion script").action(()=>{let e=$(h);ht({json:e.json,noColor:e.noColor})});h.command("config").description("Save your API key").action(async()=>{let e=$(h);try{await Ct({noColor:e.noColor,json:e.json})}catch(o){Tt(o)}});h.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",Z,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(b(async(e,o,t,n)=>{if(t||(X(o.noColor),process.exit(0)),!(0,j.existsSync)(t)&&!t.includes("/")&&!t.includes("\\")&&!t.includes(".")&&!t.startsWith("~"))throw c.validation(`unknown command '${t}'`);return Ot(e,t,Q(n,h.opts()),n,o)},{operation:"upload"}));function uo(){let e=process.argv,o=e.includes("--compbash"),t=e.includes("--compzsh"),n=e.includes("--compfish");if(!o&&!t&&!n)return;console.log(["ping","whoami","deployments","domains","tokens","account","config","completion"].join(n?`
|
|
86
|
+
`:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&uo();if(process.env.NODE_ENV!=="test")try{h.parse(process.argv)}catch(e){if(e instanceof Error&&"code"in e){let o=e.code,t=e.exitCode;o?.startsWith("commander.")&&process.exit(t||1)}throw e}
|
|
87
87
|
//# sourceMappingURL=cli.cjs.map
|