@shipstatic/ship 0.7.5 → 0.7.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.d.ts +5 -0
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +11 -11
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Et=Object.create;var de=Object.defineProperty;var Tt=Object.getOwnPropertyDescriptor;var At=Object.getOwnPropertyNames;var xt=Object.getPrototypeOf,Ot=Object.prototype.hasOwnProperty;var I=(e,o)=>()=>(e&&(o=e(e=0)),o);var Rt=(e,o)=>{for(var t in o)de(e,t,{get:o[t],enumerable:!0})},kt=(e,o,t,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of At(o))!Ot.call(e,i)&&i!==t&&de(e,i,{get:()=>o[i],enumerable:!(n=Tt(o,i))||n.enumerable});return e};var E=(e,o,t)=>(t=e!=null?Et(xt(e)):{},kt(o||!e||!e.__esModule?de(t,"default",{value:e,enumerable:!0}):t,e));function O(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function ge(e){let o=e.lastIndexOf(".");if(o===-1||o===e.length-1)return!1;let t=e.slice(o+1).toLowerCase();return It.has(t)}function Q(e){if(!e.startsWith(_))throw l.validation(`API key must start with "${_}"`);if(e.length!==xe)throw l.validation(`API key must be ${xe} characters total (${_} + ${fe} hex chars)`);let o=e.slice(_.length);if(!/^[a-f0-9]{64}$/i.test(o))throw l.validation(`API key must contain ${fe} hexadecimal characters after "${_}" prefix`)}function ke(e){if(!e.startsWith(U))throw l.validation(`Deploy token must start with "${U}"`);if(e.length!==Oe)throw l.validation(`Deploy token must be ${Oe} characters total (${U} + ${he} hex chars)`);let o=e.slice(U.length);if(!/^[a-f0-9]{64}$/i.test(o))throw l.validation(`Deploy token must contain ${he} hexadecimal characters after "${U}" prefix`)}function Ie(e){try{let o=new URL(e);if(!["http:","https:"].includes(o.protocol))throw l.validation("API URL must use http:// or https:// protocol");if(o.pathname!=="/"&&o.pathname!=="")throw l.validation("API URL must not contain a path");if(o.search||o.hash)throw l.validation("API URL must not contain query parameters or fragments")}catch(o){throw O(o)?o:l.validation("API URL must be a valid URL")}}var g,me,l,It,Re,_,fe,xe,U,he,Oe,ye,j,C=I(()=>{"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={}));me={client:new Set([g.Business,g.Config,g.File,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},l=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 me.client.has(this.type)}isNetworkError(){return me.network.has(this.type)}isAuthError(){return me.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}};It=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"]);Re=new Set(["node_modules"]),_="ship-",fe=64,xe=_.length+fe,U="token-",he=64,Oe=U.length+he,ye="ship.json";j="https://api.shipstatic.com"});function Fe(e){Se=e}function te(){if(Se===null)throw l.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return Se}var Se,oe=I(()=>{"use strict";C();Se=null});function Pt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function F(){return $e||Pt()}var $e,V=I(()=>{"use strict";$e=null});async function $t(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,p=new FileReader,c=()=>{let u=r*2097152,d=Math.min(u+2097152,e.size);p.readAsArrayBuffer(e.slice(u,d))};p.onload=u=>{let d=u.target?.result;if(!d){n(l.business("Failed to read file chunk"));return}a.append(d),r++,r<s?c():t({md5:a.end()})},p.onerror=()=>{n(l.business("Failed to calculate MD5: FileReader error"))},c()})}async function Lt(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(l.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 ne(e){let o=F();if(o==="browser"){if(!(e instanceof Blob))throw l.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return $t(e)}if(o==="node"){if(!(Buffer.isBuffer(e)||typeof e=="string"))throw l.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Lt(e)}throw l.business("Unknown or unsupported execution environment for MD5 calculation.")}var be=I(()=>{"use strict";V();C()});function He(e){return!e||e.length===0?[]:e.filter(o=>{if(!o)return!1;let t=o.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let n=t[t.length-1];if((0,ze.isJunk)(n))return!1;for(let s of t)if(s!==".well-known"&&(s.startsWith(".")||s.length>255))return!1;let i=t.slice(0,-1);for(let s of i)if(jt.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var ze,jt,Ge=I(()=>{"use strict";ze=require("junk"),jt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ve(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 se(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ve=I(()=>{"use strict"});function qe(e,o={}){if(o.flatten===!1)return e.map(n=>({path:se(n),name:we(n)}));let t=Kt(e);return e.map(n=>{let i=se(n);if(t){let s=t.endsWith("/")?t:`${t}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=we(n)),{path:i,name:we(n)}})}function Kt(e){if(!e.length)return"";let t=e.map(s=>se(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 we(e){return e.split(/[/\\]/).pop()||e}var Je=I(()=>{"use strict";ve()});function We(e){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(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 Ye=I(()=>{"use strict";C()});function Xe(e,o){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw l.business(`Security error: Unsafe file path "${e}" for file: ${o}`)}function Ze(e,o){let t=We(e);if(!t.valid)throw l.business(t.reason||"Invalid file name");if(ge(e))throw l.business(`File extension not allowed: "${o}"`)}var Qe=I(()=>{"use strict";C();Ye()});var tt={};Rt(tt,{processFilesForNode:()=>Mt});function et(e,o=new Set){let t=[],n=A.realpathSync(e);if(o.has(n))return t;o.add(n);let i=A.readdirSync(e);for(let s of i){let r=x.join(e,s),a=A.statSync(r);if(a.isDirectory()){let p=et(r,o);t.push(...p)}else a.isFile()&&t.push(r)}return t}async function Mt(e,o={}){if(F()!=="node")throw l.business("processFilesForNode can only be called in Node.js environment.");for(let m of e){let D=x.resolve(m);try{if(A.statSync(D).isDirectory()){let R=A.readdirSync(D).find(k=>Re.has(k));if(R)throw l.business(`"${R}/" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(R){if(O(R))throw R}}let t=e.flatMap(m=>{let D=x.resolve(m);try{return A.statSync(D).isDirectory()?et(D):[D]}catch{throw l.file(`Path does not exist: ${m}`,m)}}),n=[...new Set(t)],i=He(n);if(i.length===0)return[];let s=e.map(m=>x.resolve(m)),r=Ve(s.map(m=>{try{return A.statSync(m).isDirectory()?m:x.dirname(m)}catch{return x.dirname(m)}})),a=i.map(m=>{if(r&&r.length>0){let D=x.relative(r,m);if(D&&typeof D=="string"&&!D.startsWith(".."))return D.replace(/\\/g,"/")}return x.basename(m)}),p=qe(a,{flatten:o.pathDetect!==!1}),c=[],u=0,d=te();for(let m=0;m<i.length;m++){let D=i[m],R=p[m].path;try{Xe(R,D);let k=A.statSync(D);if(k.size===0)continue;if(Ze(R,D),k.size>d.maxFileSize)throw l.business(`File ${D} is too large. Maximum allowed size is ${d.maxFileSize/(1024*1024)}MB.`);if(u+=k.size,u>d.maxTotalSize)throw l.business(`Total deploy size is too large. Maximum allowed is ${d.maxTotalSize/(1024*1024)}MB.`);let G=A.readFileSync(D),{md5:wt}=await ne(G);c.push({path:R,content:G,size:G.length,md5:wt})}catch(k){if(O(k))throw k;let G=k instanceof Error?k.message:String(k);throw l.file(`Failed to read file "${D}": ${G}`,D)}}if(c.length>d.maxFilesCount)throw l.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return c}var A,x,ot=I(()=>{"use strict";V();be();Ge();Qe();C();oe();Je();ve();A=E(require("fs"),1),x=E(require("path"),1)});var Dt=require("commander");C();var ee=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 S={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Ft=3e4,K=class extends ee{constructor(t){super();this.globalHeaders={};this.apiUrl=t.apiUrl||j,this.getAuthHeadersCallback=t.getAuthHeaders,this.timeout=t.timeout??Ft,this.createDeployBody=t.createDeployBody}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),p={...n,headers:s,credentials:s.Authorization?void 0:"include",signal:r};this.emit("request",t,p);try{let c=await fetch(t,p);return a(),c.ok||await this.handleResponseError(c,i),this.emit("response",this.safeClone(c),t),{data:await this.parseResponse(this.safeClone(c)),status:c.status}}catch(c){a();let u=c instanceof Error?c:new Error(String(c));this.emit("error",u,t),this.handleFetchError(c,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,...t,...this.getAuthHeadersCallback()}}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 p=a;typeof p.message=="string"&&(i.message=p.message),typeof p.error=="string"&&(i.error=p.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?l.authentication(s):l.api(s,t.status)}handleFetchError(t,n){throw O(t)?t:t instanceof Error&&t.name==="AbortError"?l.cancelled(`${n} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?l.network(`${n} failed: ${t.message}`,t):t instanceof Error?l.business(`${n} failed: ${t.message}`):l.business(`${n} failed: Unknown error`)}async deploy(t,n={}){if(!t.length)throw l.business("No files to deploy");for(let a of t)if(!a.md5)throw l.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:i,headers:s}=await this.createDeployBody(t,n.labels,n.via),r={};return n.deployToken?r.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(r.Authorization=`Bearer ${n.apiKey}`),n.caller&&(r["X-Caller"]=n.caller),this.request(`${n.apiUrl||this.apiUrl}${S.DEPLOYMENTS}`,{method:"POST",body:i,headers:{...s,...r},signal:n.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(t){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(t,n){return this.request(`${this.apiUrl}${S.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}${S.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}${S.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}${S.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}`,{method:"GET"},"Get domain")}async removeDomain(t){await this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/share`,{method:"GET"},"Get domain share")}async validateDomain(t){return this.request(`${this.apiUrl}${S.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}${S.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${S.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(t){await this.request(`${this.apiUrl}${S.TOKENS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${S.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${S.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${S.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(t){let n=t.find(a=>a.path==="index.html"||a.path==="/index.html");if(!n||n.size>100*1024)return!1;let i;if(typeof Buffer<"u"&&Buffer.isBuffer(n.content))i=n.content.toString("utf-8");else if(typeof Blob<"u"&&n.content instanceof Blob)i=await n.content.text();else if(typeof File<"u"&&n.content instanceof File)i=await n.content.text();else return!1;let s={files:t.map(a=>a.path),index:i};return(await this.request(`${this.apiUrl}${S.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA check")).isSPA}};C();oe();C();C();function De(e={},o={}){let t={apiUrl:e.apiUrl||o.apiUrl||j,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 Pe(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}C();be();async function Nt(){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 ne(t);return{path:ye,content:t,size:o.length,md5:n}}async function Le(e,o,t){if(t.spaDetect===!1||e.some(n=>n.path===ye))return e;try{if(await o.checkSPA(e)){let i=await Nt();return[...e,i]}}catch{}return e}function Ne(e){let{getApi:o,ensureInit:t,processInput:n,clientDefaults:i,hasAuth:s}=e;return{upload:async(r,a={})=>{await t();let p=i?Pe(a,i):a;if(s&&!s()&&!p.deployToken&&!p.apiKey)throw l.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw l.config("processInput function is not provided.");let c=o(),u=await n(r,p);return u=await Le(u,c,p),c.deploy(u,p)},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 _e(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 Ue(e){let{getApi:o,ensureInit:t}=e;return{get:async()=>(await t(),o().getAccount())}}function je(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 ie=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 K({...o,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=Ne({...n,processInput:(i,s)=>this.processInput(i,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=_e(n),this._account=Ue(n),this._tokens=je(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=te(),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 l.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 l.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}};C();V();var M=require("zod");C();V();var Ce="ship",_t=M.z.object({apiUrl:M.z.string().url().optional(),apiKey:M.z.string().optional(),deployToken:M.z.string().optional()}).strict();function Ke(e){try{return _t.parse(e)}catch(o){if(o instanceof M.z.ZodError){let t=o.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw l.config(`Configuration validation failed${n}: ${t.message}`)}throw l.config("Configuration validation failed")}}async function Ut(e){try{if(F()!=="node")return{};let{cosmiconfigSync:o}=await import("cosmiconfig"),t=await import("os"),n=o(Ce,{searchPlaces:[`.${Ce}rc`,"package.json",`${t.homedir()}/.${Ce}rc`],stopDir:t.homedir()}),i;if(e?i=n.load(e):i=n.search(),i&&i.config)return Ke(i.config)}catch(o){if(O(o))throw o}return{}}async function Me(e){if(F()!=="node")return{};let o={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await Ut(e),n={apiUrl:o.apiUrl??t.apiUrl,apiKey:o.apiKey??t.apiKey,deployToken:o.deployToken??t.deployToken};return Ke(n)}oe();C();async function Be(e,o,t){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new n,a=[];for(let d of e){if(!Buffer.isBuffer(d.content)&&!(typeof Blob<"u"&&d.content instanceof Blob))throw l.file(`Unsupported file.content type for Node.js: ${d.path}`,d.path);if(!d.md5)throw l.file(`File missing md5 checksum: ${d.path}`,d.path);let m=new i([d.content],d.path,{type:"application/octet-stream"});r.append("files[]",m),a.push(d.md5)}r.append("checksums",JSON.stringify(a)),o&&o.length>0&&r.append("labels",JSON.stringify(o)),t&&r.append("via",t);let p=new s(r),c=[];for await(let d of p.encode())c.push(Buffer.from(d));let u=Buffer.concat(c);return{body:u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),headers:{"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(u).toString()}}}var re=class extends ie{constructor(o={}){if(F()!=="node")throw l.business("Node.js Ship class can only be used in Node.js environment.");super(o)}resolveInitialConfig(o){return De(o,{})}async loadFullConfig(){try{let o=await Me(this.clientOptions.configFile),t=De(this.clientOptions,o);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let n=new K({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();Fe(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 l.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw l.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(ot(),tt));return i(n,t)}getDeployBodyCreator(){return Be}};C();var N=require("fs"),ce=E(require("path"),1);var Ee=E(require("columnify"),1),f=require("yoctocolors"),nt=["isCreate"],v=(e,o,t)=>t?o:e(o),w=(e,o,t)=>{console.log(o?JSON.stringify({success:e},null,2)+`
|
|
2
|
+
"use strict";var Tt=Object.create;var de=Object.defineProperty;var At=Object.getOwnPropertyDescriptor;var xt=Object.getOwnPropertyNames;var Ot=Object.getPrototypeOf,Rt=Object.prototype.hasOwnProperty;var I=(e,o)=>()=>(e&&(o=e(e=0)),o);var kt=(e,o)=>{for(var t in o)de(e,t,{get:o[t],enumerable:!0})},It=(e,o,t,n)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of xt(o))!Rt.call(e,i)&&i!==t&&de(e,i,{get:()=>o[i],enumerable:!(n=At(o,i))||n.enumerable});return e};var E=(e,o,t)=>(t=e!=null?Tt(Ot(e)):{},It(o||!e||!e.__esModule?de(t,"default",{value:e,enumerable:!0}):t,e));function O(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function ge(e){let o=e.lastIndexOf(".");if(o===-1||o===e.length-1)return!1;let t=e.slice(o+1).toLowerCase();return Ft.has(t)}function Se(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(t=>ye.has(t))}function Q(e){if(!e.startsWith(_))throw l.validation(`API key must start with "${_}"`);if(e.length!==Re)throw l.validation(`API key must be ${Re} characters total (${_} + ${fe} hex chars)`);let o=e.slice(_.length);if(!/^[a-f0-9]{64}$/i.test(o))throw l.validation(`API key must contain ${fe} hexadecimal characters after "${_}" prefix`)}function Ie(e){if(!e.startsWith(U))throw l.validation(`Deploy token must start with "${U}"`);if(e.length!==ke)throw l.validation(`Deploy token must be ${ke} characters total (${U} + ${he} hex chars)`);let o=e.slice(U.length);if(!/^[a-f0-9]{64}$/i.test(o))throw l.validation(`Deploy token must contain ${he} hexadecimal characters after "${U}" prefix`)}function Fe(e){try{let o=new URL(e);if(!["http:","https:"].includes(o.protocol))throw l.validation("API URL must use http:// or https:// protocol");if(o.pathname!=="/"&&o.pathname!=="")throw l.validation("API URL must not contain a path");if(o.search||o.hash)throw l.validation("API URL must not contain query parameters or fragments")}catch(o){throw O(o)?o:l.validation("API URL must be a valid URL")}}var g,me,l,Ft,ye,_,fe,Re,U,he,ke,De,j,b=I(()=>{"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={}));me={client:new Set([g.Business,g.Config,g.File,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},l=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 me.client.has(this.type)}isNetworkError(){return me.network.has(this.type)}isAuthError(){return me.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}};Ft=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"]);ye=new Set(["node_modules","package.json"]);_="ship-",fe=64,Re=_.length+fe,U="token-",he=64,ke=U.length+he,De="ship.json";j="https://api.shipstatic.com"});function Pe(e){be=e}function te(){if(be===null)throw l.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return be}var be,oe=I(()=>{"use strict";b();be=null});function $t(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function F(){return Le||$t()}var Le,V=I(()=>{"use strict";Le=null});async function Lt(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,p=new FileReader,c=()=>{let u=r*2097152,d=Math.min(u+2097152,e.size);p.readAsArrayBuffer(e.slice(u,d))};p.onload=u=>{let d=u.target?.result;if(!d){n(l.business("Failed to read file chunk"));return}a.append(d),r++,r<s?c():t({md5:a.end()})},p.onerror=()=>{n(l.business("Failed to calculate MD5: FileReader error"))},c()})}async function Nt(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(l.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 ne(e){let o=F();if(o==="browser"){if(!(e instanceof Blob))throw l.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Lt(e)}if(o==="node"){if(!(Buffer.isBuffer(e)||typeof e=="string"))throw l.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Nt(e)}throw l.business("Unknown or unsupported execution environment for MD5 calculation.")}var ve=I(()=>{"use strict";V();b()});function Ge(e){if(!e||e.length===0)return[];if(e.find(t=>t&&Se(t)))throw l.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,He.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(Kt.some(a=>r.toLowerCase()===a.toLowerCase()))return!1;return!0})}var He,Kt,Ve=I(()=>{"use strict";He=require("junk");b();Kt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function qe(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 se(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Ee=I(()=>{"use strict"});function Je(e,o={}){if(o.flatten===!1)return e.map(n=>({path:se(n),name:Te(n)}));let t=Mt(e);return e.map(n=>{let i=se(n);if(t){let s=t.endsWith("/")?t:`${t}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=Te(n)),{path:i,name:Te(n)}})}function Mt(e){if(!e.length)return"";let t=e.map(s=>se(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 Te(e){return e.split(/[/\\]/).pop()||e}var We=I(()=>{"use strict";Ee()});function Ye(e){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(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 Xe=I(()=>{"use strict";b()});function Ze(e,o){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw l.business(`Security error: Unsafe file path "${e}" for file: ${o}`)}function Qe(e,o){let t=Ye(e);if(!t.valid)throw l.business(t.reason||"Invalid file name");if(ge(e))throw l.business(`File extension not allowed: "${o}"`)}var et=I(()=>{"use strict";b();Xe()});var ot={};kt(ot,{processFilesForNode:()=>Bt});function tt(e,o=new Set){let t=[],n=A.realpathSync(e);if(o.has(n))return t;o.add(n);let i=A.readdirSync(e);for(let s of i){let r=x.join(e,s),a=A.statSync(r);if(a.isDirectory()){let p=tt(r,o);t.push(...p)}else a.isFile()&&t.push(r)}return t}async function Bt(e,o={}){if(F()!=="node")throw l.business("processFilesForNode can only be called in Node.js environment.");for(let m of e){let D=x.resolve(m);try{if(A.statSync(D).isDirectory()){let R=A.readdirSync(D).find(k=>ye.has(k));if(R)throw l.business(`"${R}/" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(R){if(O(R))throw R}}let t=e.flatMap(m=>{let D=x.resolve(m);try{return A.statSync(D).isDirectory()?tt(D):[D]}catch{throw l.file(`Path does not exist: ${m}`,m)}}),n=[...new Set(t)],i=Ge(n);if(i.length===0)return[];let s=e.map(m=>x.resolve(m)),r=qe(s.map(m=>{try{return A.statSync(m).isDirectory()?m:x.dirname(m)}catch{return x.dirname(m)}})),a=i.map(m=>{if(r&&r.length>0){let D=x.relative(r,m);if(D&&typeof D=="string"&&!D.startsWith(".."))return D.replace(/\\/g,"/")}return x.basename(m)}),p=Je(a,{flatten:o.pathDetect!==!1}),c=[],u=0,d=te();for(let m=0;m<i.length;m++){let D=i[m],R=p[m].path;try{Ze(R,D);let k=A.statSync(D);if(k.size===0)continue;if(Qe(R,D),k.size>d.maxFileSize)throw l.business(`File ${D} is too large. Maximum allowed size is ${d.maxFileSize/(1024*1024)}MB.`);if(u+=k.size,u>d.maxTotalSize)throw l.business(`Total deploy size is too large. Maximum allowed is ${d.maxTotalSize/(1024*1024)}MB.`);let G=A.readFileSync(D),{md5:Et}=await ne(G);c.push({path:R,content:G,size:G.length,md5:Et})}catch(k){if(O(k))throw k;let G=k instanceof Error?k.message:String(k);throw l.file(`Failed to read file "${D}": ${G}`,D)}}if(c.length>d.maxFilesCount)throw l.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return c}var A,x,nt=I(()=>{"use strict";V();ve();Ve();et();b();oe();We();Ee();A=E(require("fs"),1),x=E(require("path"),1)});var bt=require("commander");b();var ee=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 S={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},Pt=3e4,K=class extends ee{constructor(t){super();this.globalHeaders={};this.apiUrl=t.apiUrl||j,this.getAuthHeadersCallback=t.getAuthHeaders,this.timeout=t.timeout??Pt,this.createDeployBody=t.createDeployBody}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),p={...n,headers:s,credentials:s.Authorization?void 0:"include",signal:r};this.emit("request",t,p);try{let c=await fetch(t,p);return a(),c.ok||await this.handleResponseError(c,i),this.emit("response",this.safeClone(c),t),{data:await this.parseResponse(this.safeClone(c)),status:c.status}}catch(c){a();let u=c instanceof Error?c:new Error(String(c));this.emit("error",u,t),this.handleFetchError(c,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,...t,...this.getAuthHeadersCallback()}}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 p=a;typeof p.message=="string"&&(i.message=p.message),typeof p.error=="string"&&(i.error=p.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?l.authentication(s):l.api(s,t.status)}handleFetchError(t,n){throw O(t)?t:t instanceof Error&&t.name==="AbortError"?l.cancelled(`${n} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?l.network(`${n} failed: ${t.message}`,t):t instanceof Error?l.business(`${n} failed: ${t.message}`):l.business(`${n} failed: Unknown error`)}async deploy(t,n={}){if(!t.length)throw l.business("No files to deploy");for(let a of t)if(!a.md5)throw l.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:i,headers:s}=await this.createDeployBody(t,n.labels,n.via),r={};return n.deployToken?r.Authorization=`Bearer ${n.deployToken}`:n.apiKey&&(r.Authorization=`Bearer ${n.apiKey}`),n.caller&&(r["X-Caller"]=n.caller),this.request(`${n.apiUrl||this.apiUrl}${S.DEPLOYMENTS}`,{method:"POST",body:i,headers:{...s,...r},signal:n.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(t){return this.request(`${this.apiUrl}${S.DEPLOYMENTS}/${encodeURIComponent(t)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(t,n){return this.request(`${this.apiUrl}${S.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}${S.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}${S.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}${S.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}`,{method:"GET"},"Get domain")}async removeDomain(t){await this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(t){return this.request(`${this.apiUrl}${S.DOMAINS}/${encodeURIComponent(t)}/share`,{method:"GET"},"Get domain share")}async validateDomain(t){return this.request(`${this.apiUrl}${S.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}${S.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${S.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(t){await this.request(`${this.apiUrl}${S.TOKENS}/${encodeURIComponent(t)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${S.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${S.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${S.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(t){let n=t.find(a=>a.path==="index.html"||a.path==="/index.html");if(!n||n.size>100*1024)return!1;let i;if(typeof Buffer<"u"&&Buffer.isBuffer(n.content))i=n.content.toString("utf-8");else if(typeof Blob<"u"&&n.content instanceof Blob)i=await n.content.text();else if(typeof File<"u"&&n.content instanceof File)i=await n.content.text();else return!1;let s={files:t.map(a=>a.path),index:i};return(await this.request(`${this.apiUrl}${S.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA check")).isSPA}};b();oe();b();b();function Ce(e={},o={}){let t={apiUrl:e.apiUrl||o.apiUrl||j,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 $e(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}b();ve();async function _t(){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 ne(t);return{path:De,content:t,size:o.length,md5:n}}async function Ne(e,o,t){if(t.spaDetect===!1||e.some(n=>n.path===De))return e;try{if(await o.checkSPA(e)){let i=await _t();return[...e,i]}}catch{}return e}function _e(e){let{getApi:o,ensureInit:t,processInput:n,clientDefaults:i,hasAuth:s}=e;return{upload:async(r,a={})=>{await t();let p=i?$e(a,i):a;if(s&&!s()&&!p.deployToken&&!p.apiKey)throw l.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw l.config("processInput function is not provided.");let c=o(),u=await n(r,p);return u=await Ne(u,c,p),c.deploy(u,p)},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 Ue(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 je(e){let{getApi:o,ensureInit:t}=e;return{get:async()=>(await t(),o().getAccount())}}function Ke(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 ie=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 K({...o,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=_e({...n,processInput:(i,s)=>this.processInput(i,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=Ue(n),this._account=je(n),this._tokens=Ke(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=te(),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 l.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 l.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}};b();V();var M=require("zod");b();V();var we="ship",Ut=M.z.object({apiUrl:M.z.string().url().optional(),apiKey:M.z.string().optional(),deployToken:M.z.string().optional()}).strict();function Me(e){try{return Ut.parse(e)}catch(o){if(o instanceof M.z.ZodError){let t=o.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw l.config(`Configuration validation failed${n}: ${t.message}`)}throw l.config("Configuration validation failed")}}async function jt(e){try{if(F()!=="node")return{};let{cosmiconfigSync:o}=await import("cosmiconfig"),t=await import("os"),n=o(we,{searchPlaces:[`.${we}rc`,"package.json",`${t.homedir()}/.${we}rc`],stopDir:t.homedir()}),i;if(e?i=n.load(e):i=n.search(),i&&i.config)return Me(i.config)}catch(o){if(O(o))throw o}return{}}async function Be(e){if(F()!=="node")return{};let o={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await jt(e),n={apiUrl:o.apiUrl??t.apiUrl,apiKey:o.apiKey??t.apiKey,deployToken:o.deployToken??t.deployToken};return Me(n)}oe();b();async function ze(e,o,t){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new n,a=[];for(let d of e){if(!Buffer.isBuffer(d.content)&&!(typeof Blob<"u"&&d.content instanceof Blob))throw l.file(`Unsupported file.content type for Node.js: ${d.path}`,d.path);if(!d.md5)throw l.file(`File missing md5 checksum: ${d.path}`,d.path);let m=new i([d.content],d.path,{type:"application/octet-stream"});r.append("files[]",m),a.push(d.md5)}r.append("checksums",JSON.stringify(a)),o&&o.length>0&&r.append("labels",JSON.stringify(o)),t&&r.append("via",t);let p=new s(r),c=[];for await(let d of p.encode())c.push(Buffer.from(d));let u=Buffer.concat(c);return{body:u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength),headers:{"Content-Type":p.contentType,"Content-Length":Buffer.byteLength(u).toString()}}}var re=class extends ie{constructor(o={}){if(F()!=="node")throw l.business("Node.js Ship class can only be used in Node.js environment.");super(o)}resolveInitialConfig(o){return Ce(o,{})}async loadFullConfig(){try{let o=await Be(this.clientOptions.configFile),t=Ce(this.clientOptions,o);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let n=new K({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();Pe(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 l.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw l.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(nt(),ot));return i(n,t)}getDeployBodyCreator(){return ze}};b();var N=require("fs"),ce=E(require("path"),1);var Ae=E(require("columnify"),1),f=require("yoctocolors"),it=["isCreate"],v=(e,o,t)=>t?o:e(o),w=(e,o,t)=>{console.log(o?JSON.stringify({success:e},null,2)+`
|
|
3
3
|
`:`${v(f.green,e.toLowerCase().replace(/\.$/,""),t)}
|
|
4
4
|
`)},T=(e,o,t)=>{if(o)console.error(JSON.stringify({error:e},null,2)+`
|
|
5
5
|
`);else{let n=v(s=>(0,f.inverse)((0,f.red)(s)),`${v(f.hidden,"[",t)}error${v(f.hidden,"]",t)}`,t),i=v(f.red,e.toLowerCase().replace(/\.$/,""),t);console.error(`${n} ${i}
|
|
@@ -7,25 +7,25 @@
|
|
|
7
7
|
`);else{let n=v(s=>(0,f.inverse)((0,f.yellow)(s)),`${v(f.hidden,"[",t)}warning${v(f.hidden,"]",t)}`,t),i=v(f.yellow,e.toLowerCase().replace(/\.$/,""),t);console.log(`${n} ${i}
|
|
8
8
|
`)}},B=(e,o,t)=>{if(o)console.log(JSON.stringify({info:e},null,2)+`
|
|
9
9
|
`);else{let n=v(s=>(0,f.inverse)((0,f.blue)(s)),`${v(f.hidden,"[",t)}info${v(f.hidden,"]",t)}`,t),i=v(f.blue,e.toLowerCase().replace(/\.$/,""),t);console.log(`${n} ${i}
|
|
10
|
-
`)}},
|
|
10
|
+
`)}},zt=(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/,v(f.hidden,"T",t)).replace(/Z$/,v(f.hidden,"Z",t)):n},st=(e,o,t="details",n)=>{if(o===null)return"-";if(typeof o=="number"&&(e==="created"||e==="activated"||e==="expires"||e==="linked"||e==="grace"))return zt(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)},le=(e,o,t,n)=>{if(!e||e.length===0)return"";let i=e[0],s=o||Object.keys(i).filter(p=>i[p]!==void 0&&!it.includes(p)),r=e.map(p=>{let c=p,u={};return s.forEach(d=>{d in c&&c[d]!==void 0&&(u[d]=st(d,c[d],"table",t))}),u});return(0,Ae.default)(r,{columnSplitter:" ",columns:s,config:s.reduce((p,c)=>(p[c]={headingTransform:u=>v(f.dim,n?.[u]||u,t)},p),{})}).split(`
|
|
11
11
|
`).map(p=>p.replace(/\0/g,"").replace(/\s+$/,"")).join(`
|
|
12
12
|
`)+`
|
|
13
|
-
`},q=(e,o)=>{let t=Object.entries(e).filter(([s,r])=>
|
|
13
|
+
`},q=(e,o)=>{let t=Object.entries(e).filter(([s,r])=>it.includes(s)?!1:r!==void 0);if(t.length===0)return"";let n=t.map(([s,r])=>({property:s+":",value:st(s,r,"details",o)}));return(0,Ae.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>v(f.dim,s,o)}}}).split(`
|
|
14
14
|
`).map(s=>s.replace(/\0/g,"")).join(`
|
|
15
15
|
`)+`
|
|
16
|
-
`};function
|
|
16
|
+
`};function Ht(e,o,t){let{noColor:n}=t;if(e.deployments.length===0){console.log("no deployments found"),console.log();return}let i=["url","labels","created"];console.log(le(e.deployments,i,n,{url:"deployment"}))}function Gt(e,o,t){let{noColor:n}=t;if(e.domains.length===0){console.log("no domains found"),console.log();return}let i=["url","deployment","labels","linked","created"];console.log(le(e.domains,i,n,{url:"domain"}))}function Vt(e,o,t){let{noColor:n}=t,{_dnsRecords:i,_shareHash:s,isCreate:r,...a}=e;if(o.operation==="set"){let p=r?"created":"updated";w(`${e.domain} domain ${p}`,!1,n)}i&&i.length>0&&(console.log(),B("DNS Records to configure:",!1,n),i.forEach(p=>{console.log(` ${p.type}: ${p.name} \u2192 ${p.value}`)})),s&&(console.log(),B(`Setup instructions: https://setup.shipstatic.com/${s}/${e.domain}`,!1,n)),console.log(),console.log(q(a,n))}function qt(e,o,t){let{noColor:n}=t;o.operation==="upload"&&w(`${e.deployment} deployment uploaded`,!1,n),console.log(q(e,n))}function Jt(e,o,t){let{noColor:n}=t;console.log(q(e,n))}function Wt(e,o,t){let{noColor:n}=t;e.message&&w(e.message,!1,n)}function Yt(e,o,t){let{noColor:n}=t;if(e.valid){if(w("domain is valid",!1,n),console.log(),e.normalized&&console.log(` normalized: ${e.normalized}`),e.available!==null){let i=e.available?"available \u2713":"already taken";console.log(` availability: ${i}`)}console.log()}else T(e.error||"domain is invalid",!1,n)}function Xt(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(le(e.tokens,i,n))}function Zt(e,o,t){let{noColor:n}=t;o.operation==="create"&&e.token&&w(`token ${e.token} created`,!1,n),console.log(q(e,n))}function rt(e,o,t){let{json:n,noColor:i}=t;if(e===void 0){o.operation==="remove"&&o.resourceType&&o.resourceId?w(`${o.resourceId} ${o.resourceType.toLowerCase()} removed`,n,i):w("removed successfully",n,i);return}if(typeof e=="boolean"){e?w("api reachable",n,i):T("api unreachable",n,i);return}if(n&&e!==null&&typeof e=="object"){let s={...e};delete s._dnsRecords,delete s._shareHash,delete s.isCreate,console.log(JSON.stringify(s,null,2)),console.log();return}e!==null&&typeof e=="object"?"deployments"in e?Ht(e,o,t):"domains"in e?Gt(e,o,t):"tokens"in e?Xt(e,o,t):"domain"in e?Vt(e,o,t):"deployment"in e?qt(e,o,t):"token"in e?Zt(e,o,t):"email"in e?Jt(e,o,t):"valid"in e?Yt(e,o,t):"message"in e?Wt(e,o,t):w("success",n,i):w("success",n,i)}var y=E(require("fs"),1),P=E(require("path"),1),xe=E(require("os"),1);function at(){let e=process.env.SHELL||"";return e.includes("bash")?"bash":e.includes("zsh")?"zsh":e.includes("fish")?"fish":null}function lt(e,o){switch(e){case"bash":return{completionFile:P.join(o,".ship_completion.bash"),profileFile:P.join(o,".bash_profile"),scriptName:"ship.bash"};case"zsh":return{completionFile:P.join(o,".ship_completion.zsh"),profileFile:P.join(o,".zshrc"),scriptName:"ship.zsh"};case"fish":return{completionFile:P.join(o,".config/fish/completions/ship.fish"),profileFile:null,scriptName:"ship.fish"}}}function pt(e,o={}){let{json:t,noColor:n}=o,i=at(),s=xe.homedir();if(!i){T(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,t,n);return}let r=lt(i,s),a=P.join(e,r.scriptName);try{if(i==="fish"){let c=P.dirname(r.completionFile);y.existsSync(c)||y.mkdirSync(c,{recursive:!0}),y.copyFileSync(a,r.completionFile),w("fish completion installed successfully",t,n),B("please restart your shell to apply the changes",t,n);return}y.copyFileSync(a,r.completionFile);let p=`# ship
|
|
17
17
|
source '${r.completionFile}'
|
|
18
18
|
# ship end`;if(r.profileFile){if(y.existsSync(r.profileFile)){let c=y.readFileSync(r.profileFile,"utf-8");if(!c.includes("# ship")||!c.includes("# ship end")){let u=c.length>0&&!c.endsWith(`
|
|
19
19
|
`)?`
|
|
20
|
-
`:"";y.appendFileSync(r.profileFile,u+p)}}else y.writeFileSync(r.profileFile,p);w(`completion script installed for ${i}`,t,n),ae(`run "source ${r.profileFile}" or restart your shell`,t,n)}}catch(p){let c=p instanceof Error?p.message:String(p);T(`could not install completion script: ${c}`,t,n)}}function
|
|
20
|
+
`:"";y.appendFileSync(r.profileFile,u+p)}}else y.writeFileSync(r.profileFile,p);w(`completion script installed for ${i}`,t,n),ae(`run "source ${r.profileFile}" or restart your shell`,t,n)}}catch(p){let c=p instanceof Error?p.message:String(p);T(`could not install completion script: ${c}`,t,n)}}function ct(e={}){let{json:o,noColor:t}=e,n=at(),i=xe.homedir();if(!n){T(`unsupported shell: ${process.env.SHELL}. supported: bash, zsh, fish`,o,t);return}let s=lt(n,i);try{if(n==="fish"){y.existsSync(s.completionFile)?(y.unlinkSync(s.completionFile),w("fish completion uninstalled successfully",o,t)):ae("fish completion was not installed",o,t),B("please restart your shell to apply the changes",o,t);return}if(y.existsSync(s.completionFile)&&y.unlinkSync(s.completionFile),!s.profileFile)return;if(!y.existsSync(s.profileFile)){T("profile file not found",o,t);return}let r=y.readFileSync(s.profileFile,"utf-8"),a=r.split(`
|
|
21
21
|
`),p=[],c=0,u=!1;for(;c<a.length;)if(a[c].trim()==="# ship"){for(u=!0,c++;c<a.length&&a[c].trim()!=="# ship end";)c++;c<a.length&&c++}else p.push(a[c]),c++;if(u){let d=r.endsWith(`
|
|
22
22
|
`),m=p.length===0?"":p.join(`
|
|
23
23
|
`)+(d?`
|
|
24
|
-
`:"");y.writeFileSync(s.profileFile,m),w(`completion script uninstalled for ${n}`,o,t),ae(`run "source ${s.profileFile}" or restart your shell`,o,t)}else T("completion was not found in profile",o,t)}catch(r){let a=r instanceof Error?r.message:String(r);T(`could not uninstall completion script: ${a}`,o,t)}}var
|
|
25
|
-
`);return}let s=
|
|
24
|
+
`:"");y.writeFileSync(s.profileFile,m),w(`completion script uninstalled for ${n}`,o,t),ae(`run "source ${s.profileFile}" or restart your shell`,o,t)}else T("completion was not found in profile",o,t)}catch(r){let a=r instanceof Error?r.message:String(r);T(`could not uninstall completion script: ${a}`,o,t)}}var mt=require("readline/promises"),L=require("fs"),ft=require("os"),ht=require("path");b();var pe=require("yoctocolors"),z=(0,ht.join)((0,ft.homedir)(),".shiprc");function ut(e){return e.length<13?e:e.slice(0,9)+"..."+e.slice(-4)}function dt(){try{return(0,L.existsSync)(z)?JSON.parse((0,L.readFileSync)(z,"utf-8")):{}}catch{return{}}}async function gt(e={}){let{noColor:o,json:t}=e,n=u=>o?u:(0,pe.dim)(u),i=u=>o?u:(0,pe.green)(u);if(t){let u=dt(),d=typeof u.apiKey=="string"?u.apiKey:void 0,m=typeof u.apiUrl=="string"?u.apiUrl:void 0;console.log(JSON.stringify({path:z,exists:(0,L.existsSync)(z),...d?{apiKey:ut(d)}:{},...m&&m!==j?{apiUrl:m}:{}},null,2)+`
|
|
25
|
+
`);return}let s=dt(),r=typeof s.apiKey=="string"?s.apiKey:void 0,a=(0,mt.createInterface)({input:process.stdin,output:process.stdout});console.log("");let p=r?` API Key (${n(ut(r))}): `:" API Key: ",c;try{c=(await a.question(p)).trim()}finally{a.close()}c&&(Q(c),s.apiKey=c),(0,L.writeFileSync)(z,JSON.stringify(s,null,2)+`
|
|
26
26
|
`),console.log(`
|
|
27
27
|
${i("saved to")} ${n(z)}
|
|
28
|
-
`)}
|
|
28
|
+
`)}b();function yt(e){return O(e)?e:e instanceof Error?l.business(e.message):l.business(String(e??"Unknown error"))}function St(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 Dt(e,o){return JSON.stringify({error:e,...o?{details:o}:{}},null,2)}var ue=require("yoctocolors");function Qt(){let e=[ce.resolve(__dirname,"../package.json"),ce.resolve(__dirname,"../../package.json")];for(let o of e)try{return JSON.parse((0,N.readFileSync)(o,"utf-8"))}catch{}return{version:"0.0.0"}}var eo=Qt(),h=new bt.Command;h.exitOverride(e=>{(e.code==="commander.help"||e.code==="commander.version"||e.exitCode===0)&&process.exit(e.exitCode||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||J(o.noColor),process.exit(e.exitCode||1)}).configureOutput({writeErr:e=>{e.startsWith("error:")||process.stderr.write(e)},writeOut:e=>process.stdout.write(e)});function J(e){let o=i=>e?i:(0,ue.bold)(i),t=i=>e?i:(0,ue.dim)(i),n=`${o("USAGE")}
|
|
29
29
|
ship <path> \u{1F680} Deploy static sites with simplicity
|
|
30
30
|
|
|
31
31
|
${o("COMMANDS")}
|
|
@@ -69,7 +69,7 @@ ${o("FLAGS")}
|
|
|
69
69
|
--version Show version information
|
|
70
70
|
|
|
71
71
|
${t("Please report any issues to https://github.com/shipstatic/ship/issues")}
|
|
72
|
-
`;console.log(n)}function W(e,o=[]){return o.concat([e])}function Y(e,o){let t=e?.label?.length?e.label:o?.label;return t?.length?t:void 0}function X(e){return(...o)=>{let t=$(h),n=o[o.length-1];if(n?.args?.length){let i=n.args.find(s=>!e.includes(s));i&&T(`unknown command '${i}'`,t.json,t.noColor)}J(t.noColor),process.exit(1)}}function $(e){let o=e.optsWithGlobals();return o.color===!1&&(o.noColor=!0),o}function
|
|
73
|
-
`):(T(i,!1,t.noColor),n.isValidationError()&&i.includes("unknown command")&&J(t.noColor)),process.exit(1)}function
|
|
74
|
-
`:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&
|
|
72
|
+
`;console.log(n)}function W(e,o=[]){return o.concat([e])}function Y(e,o){let t=e?.label?.length?e.label:o?.label;return t?.length?t:void 0}function X(e){return(...o)=>{let t=$(h),n=o[o.length-1];if(n?.args?.length){let i=n.args.find(s=>!e.includes(s));i&&T(`unknown command '${i}'`,t.json,t.noColor)}J(t.noColor),process.exit(1)}}function $(e){let o=e.optsWithGlobals();return o.color===!1&&(o.noColor=!0),o}function Ct(e,o){let t=$(h),n=yt(e),i=St(n,o,{apiKey:t.apiKey,deployToken:t.deployToken});t.json?console.error(Dt(i,n.details)+`
|
|
73
|
+
`):(T(i,!1,t.noColor),n.isValidationError()&&i.includes("unknown command")&&J(t.noColor)),process.exit(1)}function C(e,o){return async function(...t){let n=$(this),i=o?{operation:o.operation,resourceType:o.resourceType,resourceId:o.getResourceId?.(...t)}:{};try{let s=to(),r=await e(s,n,...t);rt(r,i,{json:n.json,noColor:n.noColor})}catch(s){Ct(s,i)}}}function to(){let{config:e,apiUrl:o,apiKey:t,deployToken:n}=h.opts();return new re({configFile:e,apiUrl:o,apiKey:t,deployToken:n})}async function vt(e,o,t,n,i){if(!(0,N.existsSync)(o))throw l.file(`${o} path does not exist`,o);let s=(0,N.statSync)(o);if(!s.isDirectory()&&!s.isFile())throw l.file(`${o} path must be a file or directory`,o);let r={via:process.env.SHIP_VIA||"cli"};t&&(r.labels=t),n?.noPathDetect!==void 0&&(r.pathDetect=!n.noPathDetect),n?.noSpaDetect!==void 0&&(r.spaDetect=!n.noSpaDetect);let a=new AbortController;r.signal=a.signal;let p=null;if(process.stdout.isTTY&&!i.json&&!i.noColor){let{default:u}=await import("yocto-spinner");p=u({text:"uploading\u2026"}).start()}let c=()=>{a.abort(),p&&p.stop(),process.exit(130)};process.on("SIGINT",c);try{return await e.deployments.upload(o,r)}finally{process.removeListener("SIGINT",c),p&&p.stop()}}h.name("ship").description("\u{1F680} Deploy static sites with simplicity").version(eo.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("--no-color","Disable colored output").option("--help","Display help for command").helpOption(!1);h.hook("preAction",e=>{let o=$(e);o.help&&(J(o.noColor),process.exit(0))});h.hook("preAction",e=>{let o=$(e);try{o.apiKey&&typeof o.apiKey=="string"&&Q(o.apiKey),o.deployToken&&typeof o.deployToken=="string"&&Ie(o.deployToken),o.apiUrl&&typeof o.apiUrl=="string"&&Fe(o.apiUrl)}catch(t){throw O(t)&&(T(t.message,o.json,o.noColor),process.exit(1)),t}});h.command("ping").description("Check API connectivity").action(C((e,o)=>e.ping()));h.command("whoami").description("Get current account information").action(C((e,o)=>e.whoami(),{operation:"get",resourceType:"Account"}));var Z=h.command("deployments").description("Manage deployments").enablePositionalOptions().action(X(["list","upload","get","set","remove"]));Z.command("list").description("List all deployments").action(C((e,o)=>e.deployments.list()));Z.command("upload <path>").description("Upload deployment from file or directory").passThroughOptions().option("--label <label>","Label to add (can be repeated)",W,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(C((e,o,t,n)=>vt(e,t,Y(n,h.opts()),n,o),{operation:"upload"}));Z.command("get <deployment>").description("Show deployment information").action(C((e,o,t)=>e.deployments.get(t),{operation:"get",resourceType:"Deployment",getResourceId:e=>e}));Z.command("set <deployment>").description("Set deployment labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",W,[]).action(C(async(e,o,t,n)=>{let i=Y(n,h.opts())||[];return e.deployments.set(t,{labels:i})},{operation:"set",resourceType:"Deployment",getResourceId:e=>e}));Z.command("remove <deployment>").description("Delete deployment permanently").action(C((e,o,t)=>e.deployments.remove(t),{operation:"remove",resourceType:"Deployment",getResourceId:e=>e}));var H=h.command("domains").description("Manage domains").enablePositionalOptions().action(X(["list","get","set","validate","verify","remove"]));H.command("list").description("List all domains").action(C((e,o)=>e.domains.list()));H.command("get <name>").description("Show domain information").action(C((e,o,t)=>e.domains.get(t),{operation:"get",resourceType:"Domain",getResourceId:e=>e}));H.command("validate <name>").description("Check if domain name is valid and available").action(C((e,o,t)=>e.domains.validate(t),{operation:"validate",resourceType:"Domain",getResourceId:e=>e}));H.command("verify <name>").description("Trigger DNS verification for external domain").action(C((e,o,t)=>e.domains.verify(t),{operation:"verify",resourceType:"Domain",getResourceId:e=>e}));H.command("set <name> [deployment]").description("Create domain, link to deployment, or update labels").passThroughOptions().option("--label <label>","Label to set (can be repeated)",W,[]).action(C(async(e,o,t,n,i)=>{let s=Y(i,h.opts()),r={};n&&(r.deployment=n),s&&s.length>0&&(r.labels=s);let a=await e.domains.set(t,r);if(a.isCreate&&t.includes("."))try{let[p,c]=await Promise.all([e.domains.records(t),e.domains.share(t)]);return{...a,_dnsRecords:p.records,_shareHash:c.hash}}catch{}return a},{operation:"set",resourceType:"Domain",getResourceId:e=>e}));H.command("remove <name>").description("Delete domain permanently").action(C((e,o,t)=>e.domains.remove(t),{operation:"remove",resourceType:"Domain",getResourceId:e=>e}));var Oe=h.command("tokens").description("Manage deploy tokens").enablePositionalOptions().action(X(["list","create","remove"]));Oe.command("list").description("List all tokens").action(C((e,o)=>e.tokens.list()));Oe.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)",W,[]).action(C((e,o,t)=>{let n={};t?.ttl!==void 0&&(n.ttl=t.ttl);let i=Y(t,h.opts());return i&&i.length>0&&(n.labels=i),e.tokens.create(n)},{operation:"create",resourceType:"Token"}));Oe.command("remove <token>").description("Delete token permanently").action(C((e,o,t)=>e.tokens.remove(t),{operation:"remove",resourceType:"Token",getResourceId:e=>e}));var oo=h.command("account").description("Manage account").action(X(["get"]));oo.command("get").description("Show account information").action(C((e,o)=>e.whoami(),{operation:"get",resourceType:"Account"}));var wt=h.command("completion").description("Setup shell completion").action(X(["install","uninstall"]));wt.command("install").description("Install shell completion script").action(()=>{let e=$(h),o=ce.resolve(__dirname,"completions");pt(o,{json:e.json,noColor:e.noColor})});wt.command("uninstall").description("Uninstall shell completion script").action(()=>{let e=$(h);ct({json:e.json,noColor:e.noColor})});h.command("config").description("Create or update ~/.shiprc configuration").action(async()=>{let e=$(h);try{await gt({noColor:e.noColor,json:e.json})}catch(o){Ct(o)}});h.argument("[path]","Path to deploy").option("--label <label>","Label to add (can be repeated)",W,[]).option("--no-path-detect","Disable automatic path optimization and flattening").option("--no-spa-detect","Disable automatic SPA detection and configuration").action(C(async(e,o,t,n)=>{if(t||(J(o.noColor),process.exit(0)),!(0,N.existsSync)(t)&&!t.includes("/")&&!t.includes("\\")&&!t.includes(".")&&!t.startsWith("~"))throw l.validation(`unknown command '${t}'`);return vt(e,t,Y(n,h.opts()),n,o)},{operation:"upload"}));function no(){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?`
|
|
74
|
+
`:" ")),process.exit(0)}process.env.NODE_ENV!=="test"&&(process.argv.includes("--compbash")||process.argv.includes("--compzsh")||process.argv.includes("--compfish"))&&no();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}
|
|
75
75
|
//# sourceMappingURL=cli.cjs.map
|