@shipstatic/ship 0.5.1 → 0.5.2
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.js +2 -2
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +3 -3
- 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 +2 -2
package/dist/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Dt=Object.create;var me=Object.defineProperty;var bt=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var wt=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var Tt=(t,e)=>{for(var o in e)me(t,o,{get:e[o],enumerable:!0})},Rt=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of vt(e))!Et.call(t,i)&&i!==o&&me(t,i,{get:()=>e[i],enumerable:!(n=bt(e,i))||n.enumerable});return t};var b=(t,e,o)=>(o=t!=null?Dt(wt(t)):{},Rt(e||!t||!t.__esModule?me(o,"default",{value:t,enumerable:!0}):o,t));function R(t){return t!==null&&typeof t=="object"&&"name"in t&&t.name==="ShipError"&&"status"in t}function X(t){if(!t.startsWith(L))throw p.validation(`API key must start with "${L}"`);if(t.length!==ke)throw p.validation(`API key must be ${ke} characters total (${L} + ${fe} hex chars)`);let e=t.slice(L.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`API key must contain ${fe} hexadecimal characters after "${L}" prefix`)}function Ae(t){if(!t.startsWith(U))throw p.validation(`Deploy token must start with "${U}"`);if(t.length!==Oe)throw p.validation(`Deploy token must be ${Oe} characters total (${U} + ${he} hex chars)`);let e=t.slice(U.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`Deploy token must contain ${he} hexadecimal characters after "${U}" prefix`)}function Pe(t){try{let e=new URL(t);if(!["http:","https:"].includes(e.protocol))throw p.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw p.validation("API URL must not contain a path");if(e.search||e.hash)throw p.validation("API URL must not contain query parameters or fragments")}catch(e){throw R(e)?e:p.validation("API URL must be a valid URL")}}var g,ue,p,L,fe,ke,U,he,Oe,ge,_,w=P(()=>{"use strict";(function(t){t.Validation="validation_failed",t.NotFound="not_found",t.RateLimit="rate_limit_exceeded",t.Authentication="authentication_failed",t.Business="business_logic_error",t.Api="internal_server_error",t.Network="network_error",t.Cancelled="operation_cancelled",t.File="file_error",t.Config="config_error"})(g||(g={}));ue={client:new Set([g.Business,g.Config,g.File,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},p=class t extends Error{type;status;details;constructor(e,o,n,i){super(o),this.type=e,this.status=n,this.details=i,this.name="ShipError"}toResponse(){let e=this.type===g.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static fromResponse(e){return new t(e.error,e.message,e.status,e.details)}static validation(e,o){return new t(g.Validation,e,400,o)}static notFound(e,o){let n=o?`${e} ${o} not found`:`${e} not found`;return new t(g.NotFound,n,404)}static rateLimit(e="Too many requests"){return new t(g.RateLimit,e,429)}static authentication(e="Authentication required",o){return new t(g.Authentication,e,401,o)}static business(e,o=400){return new t(g.Business,e,o)}static network(e,o){return new t(g.Network,e,void 0,{cause:o})}static cancelled(e){return new t(g.Cancelled,e)}static file(e,o){return new t(g.File,e,void 0,{filePath:o})}static config(e,o){return new t(g.Config,e,void 0,o)}static api(e,o=500){return new t(g.Api,e,o)}static database(e,o=500){return new t(g.Api,e,o)}static storage(e,o=500){return new t(g.Api,e,o)}get filePath(){return this.details?.filePath}isClientError(){return ue.client.has(this.type)}isNetworkError(){return ue.network.has(this.type)}isAuthError(){return ue.auth.has(this.type)}isValidationError(){return this.type===g.Validation}isFileError(){return this.type===g.File}isConfigError(){return this.type===g.Config}isType(e){return this.type===e}};L="ship-",fe=64,ke=L.length+fe,U="token-",he=64,Oe=U.length+he,ge="ship.json";_="https://api.shipstatic.com"});function Ie(t){ye=t}function Q(){if(ye===null)throw p.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ye}var ye,ee=P(()=>{"use strict";w();ye=null});function Ot(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function I(){return $e||Ot()}var $e,G=P(()=>{"use strict";$e=null});async function At(t){let e=(await import("spark-md5")).default;return new Promise((o,n)=>{let s=Math.ceil(t.size/2097152),r=0,l=new e.ArrayBuffer,a=new FileReader,c=()=>{let m=r*2097152,d=Math.min(m+2097152,t.size);a.readAsArrayBuffer(t.slice(m,d))};a.onload=m=>{let d=m.target?.result;if(!d){n(p.business("Failed to read file chunk"));return}l.append(d),r++,r<s?c():o({md5:l.end()})},a.onerror=()=>{n(p.business("Failed to calculate MD5: FileReader error"))},c()})}async function Pt(t){let e=await import("crypto");if(Buffer.isBuffer(t)){let n=e.createHash("md5");return n.update(t),{md5:n.digest("hex")}}let o=await import("fs");return new Promise((n,i)=>{let s=e.createHash("md5"),r=o.createReadStream(t);r.on("error",l=>i(p.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 te(t){let e=I();if(e==="browser"){if(!(t instanceof Blob))throw p.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return At(t)}if(e==="node"){if(!(Buffer.isBuffer(t)||typeof t=="string"))throw p.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Pt(t)}throw p.business("Unknown or unsupported execution environment for MD5 calculation.")}var Ce=P(()=>{"use strict";G();w()});function Ke(t){try{return $t.parse(t)}catch(e){if(e instanceof K.z.ZodError){let o=e.issues[0],n=o.path.length>0?` at ${o.path.join(".")}`:"";throw p.config(`Configuration validation failed${n}: ${o.message}`)}throw p.config("Configuration validation failed")}}async function Ft(t){try{if(I()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),o=await import("os"),n=e(xe,{searchPlaces:[`.${xe}rc`,"package.json",`${o.homedir()}/.${xe}rc`],stopDir:o.homedir()}),i;if(t?i=n.load(t):i=n.search(),i&&i.config)return Ke(i.config)}catch(e){if(R(e))throw e}return{}}async function Me(t){if(I()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},o=await Ft(t),n={apiUrl:e.apiUrl??o.apiUrl,apiKey:e.apiKey??o.apiKey,deployToken:e.deployToken??o.deployToken};return Ke(n)}var K,xe,$t,Be=P(()=>{"use strict";K=require("zod");w();G();xe="ship",$t=K.z.object({apiUrl:K.z.string().url().optional(),apiKey:K.z.string().optional(),deployToken:K.z.string().optional()}).strict()});function Je(t){return!t||t.length===0?[]:t.filter(e=>{if(!e)return!1;let o=e.replace(/\\/g,"/").split("/").filter(Boolean);if(o.length===0)return!0;let n=o[o.length-1];if((0,Ge.isJunk)(n))return!1;for(let s of o)if(s.startsWith(".")||s.length>255)return!1;let i=o.slice(0,-1);for(let s of i)if(Nt.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var Ge,Nt,qe=P(()=>{"use strict";Ge=require("junk"),Nt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ve(t){if(!t||t.length===0)return"";let e=t.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let o=e.map(s=>s.split("/").filter(Boolean)),n=[],i=Math.min(...o.map(s=>s.length));for(let s=0;s<i;s++){let r=o[0][s];if(o.every(l=>l[s]===r))n.push(r);else break}return n.join("/")}function ne(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ve=P(()=>{"use strict"});function We(t,e={}){if(e.flatten===!1)return t.map(n=>({path:ne(n),name:we(n)}));let o=Lt(t);return t.map(n=>{let i=ne(n);if(o){let s=o.endsWith("/")?o:`${o}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=we(n)),{path:i,name:we(n)}})}function Lt(t){if(!t.length)return"";let o=t.map(s=>ne(s)).map(s=>s.split("/")),n=[],i=Math.min(...o.map(s=>s.length));for(let s=0;s<i-1;s++){let r=o[0][s];if(o.every(l=>l[s]===r))n.push(r);else break}return n.join("/")}function we(t){return t.split(/[/\\]/).pop()||t}var Ye=P(()=>{"use strict";ve()});var Ze={};Tt(Ze,{processFilesForNode:()=>Ut});function Xe(t,e=new Set){let o=[],n=k.realpathSync(t);if(e.has(n))return o;e.add(n);let i=k.readdirSync(t);for(let s of i){let r=T.join(t,s),l=k.statSync(r);if(l.isDirectory()){let a=Xe(r,e);o.push(...a)}else l.isFile()&&o.push(r)}return o}async function Ut(t,e={}){if(I()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");let o=t.flatMap(u=>{let C=T.resolve(u);try{return k.statSync(C).isDirectory()?Xe(C):[C]}catch{throw p.file(`Path does not exist: ${u}`,u)}}),n=[...new Set(o)],i=Je(n);if(i.length===0)return[];let s=t.map(u=>T.resolve(u)),r=Ve(s.map(u=>{try{return k.statSync(u).isDirectory()?u:T.dirname(u)}catch{return T.dirname(u)}})),l=i.map(u=>{if(r&&r.length>0){let C=T.relative(r,u);if(C&&typeof C=="string"&&!C.startsWith(".."))return C.replace(/\\/g,"/")}return T.basename(u)}),a=We(l,{flatten:e.pathDetect!==!1}),c=[],m=0,d=Q();for(let u=0;u<i.length;u++){let C=i[u],O=a[u].path;try{let A=k.statSync(C);if(A.size===0)continue;if(A.size>d.maxFileSize)throw p.business(`File ${C} is too large. Maximum allowed size is ${d.maxFileSize/(1024*1024)}MB.`);if(m+=A.size,m>d.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${d.maxTotalSize/(1024*1024)}MB.`);let H=k.readFileSync(C),{md5:xt}=await te(H);if(O.includes("\0")||O.includes("/../")||O.startsWith("../")||O.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${O}" for file: ${C}`);c.push({path:O,content:H,size:H.length,md5:xt})}catch(A){if(R(A))throw A;let H=A instanceof Error?A.message:String(A);throw p.file(`Failed to read file "${C}": ${H}`,C)}}if(c.length>d.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return c}var k,T,Qe=P(()=>{"use strict";G();Ce();qe();w();ee();Ye();ve();k=b(require("fs"),1),T=b(require("path"),1)});var gt=require("commander");w();var Z=class{constructor(){this.handlers=new Map}on(e,o){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(o)}off(e,o){let n=this.handlers.get(e);n&&(n.delete(o),n.size===0&&this.handlers.delete(e))}emit(e,...o){let n=this.handlers.get(e);if(!n)return;let i=Array.from(n);for(let s of i)try{s(...o)}catch(r){n.delete(s),e!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(e)):this.emit("error",new Error(String(r)),String(e))},0)}}transfer(e){this.handlers.forEach((o,n)=>{o.forEach(i=>{e.on(n,i)})})}clear(){this.handlers.clear()}};var y={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},kt=3e4,j=class extends Z{constructor(e){super(),this.apiUrl=e.apiUrl||_,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??kt,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,o,n){let i=this.mergeHeaders(o.headers),{signal:s,cleanup:r}=this.createTimeoutSignal(o.signal),l={...o,headers:i,credentials:i.Authorization?void 0:"include",signal:s};this.emit("request",e,l);try{let a=await fetch(e,l);return r(),a.ok||await this.handleResponseError(a,n),this.emit("response",this.safeClone(a),e),{data:await this.parseResponse(this.safeClone(a)),status:a.status}}catch(a){r();let c=a instanceof Error?a:new Error(String(a));this.emit("error",c,e),this.handleFetchError(a,n)}}async request(e,o,n){let{data:i}=await this.executeRequest(e,o,n);return i}async requestWithStatus(e,o,n){return this.executeRequest(e,o,n)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let o=new AbortController,n=setTimeout(()=>o.abort(),this.timeout);if(e){let i=()=>o.abort();e.addEventListener("abort",i),e.aborted&&o.abort()}return{signal:o.signal,cleanup:()=>clearTimeout(n)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,o){let n={};try{if(e.headers.get("content-type")?.includes("application/json")){let r=await e.json();if(r&&typeof r=="object"){let l=r;typeof l.message=="string"&&(n.message=l.message),typeof l.error=="string"&&(n.error=l.error)}}else n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let i=n.message||n.error||`${o} failed`;throw e.status===401?p.authentication(i):p.api(i,e.status)}handleFetchError(e,o){throw R(e)?e:e instanceof Error&&e.name==="AbortError"?p.cancelled(`${o} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?p.network(`${o} failed: ${e.message}`,e):e instanceof Error?p.business(`${o} failed: ${e.message}`):p.business(`${o} failed: Unknown error`)}async deploy(e,o={}){if(!e.length)throw p.business("No files to deploy");for(let r of e)if(!r.md5)throw p.file(`MD5 checksum missing for file: ${r.path}`,r.path);let{body:n,headers:i}=await this.createDeployBody(e,o.labels,o.via),s={};return o.deployToken?s.Authorization=`Bearer ${o.deployToken}`:o.apiKey&&(s.Authorization=`Bearer ${o.apiKey}`),o.caller&&(s["X-Caller"]=o.caller),this.request(`${o.apiUrl||this.apiUrl}${y.DEPLOYMENTS}`,{method:"POST",body:n,headers:{...i,...s},signal:o.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,o){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:o})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,o,n){let i={};o&&(i.deployment=o),n!==void 0&&(i.labels=n);let{data:s,status:r}=await this.requestWithStatus(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Set domain");return{...s,isCreate:r===201}}async listDomains(){return this.request(`${this.apiUrl}${y.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async updateDomainLabels(e,o){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:o})},"Update domain labels")}async removeDomain(e){await this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,o){let n={};return e!==void 0&&(n.ttl=e),o!==void 0&&(n.labels=o),this.request(`${this.apiUrl}${y.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${y.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${y.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${y.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${y.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${y.PING}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return this.request(`${this.apiUrl}${y.PING}`,{method:"GET"},"Ping")}async checkSPA(e){let o=e.find(r=>r.path==="index.html"||r.path==="/index.html");if(!o||o.size>100*1024)return!1;let n;if(typeof Buffer<"u"&&Buffer.isBuffer(o.content))n=o.content.toString("utf-8");else if(typeof Blob<"u"&&o.content instanceof Blob)n=await o.content.text();else if(typeof File<"u"&&o.content instanceof File)n=await o.content.text();else return!1;let i={files:e.map(r=>r.path),index:n};return(await this.request(`${this.apiUrl}${y.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA check")).isSPA}};w();ee();w();w();function Se(t={},e={}){let o={apiUrl:t.apiUrl||e.apiUrl||_,apiKey:t.apiKey!==void 0?t.apiKey:e.apiKey,deployToken:t.deployToken!==void 0?t.deployToken:e.deployToken},n={apiUrl:o.apiUrl};return o.apiKey!==void 0&&(n.apiKey=o.apiKey),o.deployToken!==void 0&&(n.deployToken=o.deployToken),n}function Fe(t,e){let o={...t};return o.apiUrl===void 0&&e.apiUrl!==void 0&&(o.apiUrl=e.apiUrl),o.apiKey===void 0&&e.apiKey!==void 0&&(o.apiKey=e.apiKey),o.deployToken===void 0&&e.deployToken!==void 0&&(o.deployToken=e.deployToken),o.timeout===void 0&&e.timeout!==void 0&&(o.timeout=e.timeout),o.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(o.maxConcurrency=e.maxConcurrency),o.onProgress===void 0&&e.onProgress!==void 0&&(o.onProgress=e.onProgress),o.caller===void 0&&e.caller!==void 0&&(o.caller=e.caller),o}w();Ce();async function It(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),o;typeof Buffer<"u"?o=Buffer.from(e,"utf-8"):o=new Blob([e],{type:"application/json"});let{md5:n}=await te(o);return{path:ge,content:o,size:e.length,md5:n}}async function Ne(t,e,o){if(o.spaDetect===!1||t.some(n=>n.path===ge))return t;try{if(await e.checkSPA(t)){let i=await It();return[...t,i]}}catch{}return t}function Le(t){let{getApi:e,ensureInit:o,processInput:n,clientDefaults:i,hasAuth:s}=t;return{create:async(r,l={})=>{await o();let a=i?Fe(l,i):l;if(s&&!s()&&!a.deployToken&&!a.apiKey)throw p.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw p.config("processInput function is not provided.");let c=e(),m=await n(r,a);return m=await Ne(m,c,a),c.deploy(m,a)},list:async()=>(await o(),e().listDeployments()),get:async r=>(await o(),e().getDeployment(r)),set:async(r,l)=>(await o(),e().updateDeploymentLabels(r,l.labels)),remove:async r=>{await o(),await e().removeDeployment(r)}}}function Ue(t){let{getApi:e,ensureInit:o}=t;return{set:async(n,i={})=>{await o();let{deployment:s,labels:r}=i;return s===void 0&&r&&r.length>0?e().updateDomainLabels(n,r):e().setDomain(n,s,r)},list:async()=>(await o(),e().listDomains()),get:async n=>(await o(),e().getDomain(n)),remove:async n=>{await o(),await e().removeDomain(n)},verify:async n=>(await o(),e().verifyDomain(n)),validate:async n=>(await o(),e().validateDomain(n)),dns:async n=>(await o(),e().getDomainDns(n)),records:async n=>(await o(),e().getDomainRecords(n)),share:async n=>(await o(),e().getDomainShare(n))}}function _e(t){let{getApi:e,ensureInit:o}=t;return{get:async()=>(await o(),e().getAccount())}}function je(t){let{getApi:e,ensureInit:o}=t;return{create:async(n={})=>(await o(),e().createToken(n.ttl,n.labels)),list:async()=>(await o(),e().listTokens()),remove:async n=>{await o(),await e().removeToken(n)}}}var oe=class{constructor(e={}){this.initPromise=null;this._config=null;this.auth=null;this.clientOptions=e,e.deployToken?this.auth={type:"token",value:e.deployToken}:e.apiKey&&(this.auth={type:"apiKey",value:e.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let o=this.resolveInitialConfig(e);this.http=new j({...e,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=Le({...n,processInput:(i,s)=>this.processInput(i,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=Ue(n),this._account=_e(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(e,o){return this.deployments.create(e,o)}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=Q(),this._config)}on(e,o){this.http.on(e,o)}off(e,o){this.http.off(e,o)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(o){console.warn("Event transfer failed during client replacement:",o)}this.http=e}setDeployToken(e){if(!e||typeof e!="string")throw p.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw p.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};w();G();Be();ee();w();var De=b(require("mime-db"),1),be={};for(let t in De.default){let e=De.default[t];e&&e.extensions&&e.extensions.forEach(o=>{be[o]||(be[o]=t)})}function ze(t){let e=t.includes(".")?t.substring(t.lastIndexOf(".")+1).toLowerCase():"";return be[e]||"application/octet-stream"}async function He(t,e,o){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new n,l=[];for(let d of t){let u=ze(d.path),C;if(Buffer.isBuffer(d.content))C=new i([d.content],d.path,{type:u});else if(typeof Blob<"u"&&d.content instanceof Blob)C=new i([d.content],d.path,{type:u});else throw p.file(`Unsupported file.content type for Node.js: ${d.path}`,d.path);if(!d.md5)throw p.file(`File missing md5 checksum: ${d.path}`,d.path);let O=d.path.startsWith("/")?d.path:"/"+d.path;r.append("files[]",C,O),l.push(d.md5)}r.append("checksums",JSON.stringify(l)),e&&e.length>0&&r.append("labels",JSON.stringify(e)),o&&r.append("via",o);let a=new s(r),c=[];for await(let d of a.encode())c.push(Buffer.from(d));let m=Buffer.concat(c);return{body:m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength),headers:{"Content-Type":a.contentType,"Content-Length":Buffer.byteLength(m).toString()}}}var ie=class extends oe{constructor(e={}){if(I()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return Se(e,{})}async loadFullConfig(){try{let e=await Me(this.clientOptions.configFile),o=Se(this.clientOptions,e);o.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(o.deployToken):o.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(o.apiKey);let n=new j({...this.clientOptions,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();Ie(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,o){let n=typeof e=="string"?[e]:e;if(!Array.isArray(n)||!n.every(s=>typeof s=="string"))throw p.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw p.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(Qe(),Ze));return i(n,o)}getDeployBodyCreator(){return He}};w();var N=require("fs"),pe=b(require("path"),1);var Ee=b(require("columnify"),1),f=require("yoctocolors"),et=["isCreate"],D=(t,e,o)=>o?e:t(e),v=(t,e,o)=>{console.log(e?JSON.stringify({success:t},null,2)+`
|
|
2
|
+
"use strict";var Dt=Object.create;var me=Object.defineProperty;var bt=Object.getOwnPropertyDescriptor;var vt=Object.getOwnPropertyNames;var wt=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var Tt=(t,e)=>{for(var o in e)me(t,o,{get:e[o],enumerable:!0})},Rt=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of vt(e))!Et.call(t,i)&&i!==o&&me(t,i,{get:()=>e[i],enumerable:!(n=bt(e,i))||n.enumerable});return t};var b=(t,e,o)=>(o=t!=null?Dt(wt(t)):{},Rt(e||!t||!t.__esModule?me(o,"default",{value:t,enumerable:!0}):o,t));function R(t){return t!==null&&typeof t=="object"&&"name"in t&&t.name==="ShipError"&&"status"in t}function X(t){if(!t.startsWith(L))throw p.validation(`API key must start with "${L}"`);if(t.length!==ke)throw p.validation(`API key must be ${ke} characters total (${L} + ${fe} hex chars)`);let e=t.slice(L.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`API key must contain ${fe} hexadecimal characters after "${L}" prefix`)}function Ae(t){if(!t.startsWith(_))throw p.validation(`Deploy token must start with "${_}"`);if(t.length!==Oe)throw p.validation(`Deploy token must be ${Oe} characters total (${_} + ${he} hex chars)`);let e=t.slice(_.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`Deploy token must contain ${he} hexadecimal characters after "${_}" prefix`)}function Pe(t){try{let e=new URL(t);if(!["http:","https:"].includes(e.protocol))throw p.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw p.validation("API URL must not contain a path");if(e.search||e.hash)throw p.validation("API URL must not contain query parameters or fragments")}catch(e){throw R(e)?e:p.validation("API URL must be a valid URL")}}var g,ue,p,L,fe,ke,_,he,Oe,ge,U,w=P(()=>{"use strict";(function(t){t.Validation="validation_failed",t.NotFound="not_found",t.RateLimit="rate_limit_exceeded",t.Authentication="authentication_failed",t.Business="business_logic_error",t.Api="internal_server_error",t.Network="network_error",t.Cancelled="operation_cancelled",t.File="file_error",t.Config="config_error"})(g||(g={}));ue={client:new Set([g.Business,g.Config,g.File,g.Validation]),network:new Set([g.Network]),auth:new Set([g.Authentication])},p=class t extends Error{type;status;details;constructor(e,o,n,i){super(o),this.type=e,this.status=n,this.details=i,this.name="ShipError"}toResponse(){let e=this.type===g.Authentication&&this.details?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static fromResponse(e){return new t(e.error,e.message,e.status,e.details)}static validation(e,o){return new t(g.Validation,e,400,o)}static notFound(e,o){let n=o?`${e} ${o} not found`:`${e} not found`;return new t(g.NotFound,n,404)}static rateLimit(e="Too many requests"){return new t(g.RateLimit,e,429)}static authentication(e="Authentication required",o){return new t(g.Authentication,e,401,o)}static business(e,o=400){return new t(g.Business,e,o)}static network(e,o){return new t(g.Network,e,void 0,{cause:o})}static cancelled(e){return new t(g.Cancelled,e)}static file(e,o){return new t(g.File,e,void 0,{filePath:o})}static config(e,o){return new t(g.Config,e,void 0,o)}static api(e,o=500){return new t(g.Api,e,o)}static database(e,o=500){return new t(g.Api,e,o)}static storage(e,o=500){return new t(g.Api,e,o)}get filePath(){return this.details?.filePath}isClientError(){return ue.client.has(this.type)}isNetworkError(){return ue.network.has(this.type)}isAuthError(){return ue.auth.has(this.type)}isValidationError(){return this.type===g.Validation}isFileError(){return this.type===g.File}isConfigError(){return this.type===g.Config}isType(e){return this.type===e}};L="ship-",fe=64,ke=L.length+fe,_="token-",he=64,Oe=_.length+he,ge="ship.json";U="https://api.shipstatic.com"});function Ie(t){ye=t}function Q(){if(ye===null)throw p.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ye}var ye,ee=P(()=>{"use strict";w();ye=null});function Ot(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function I(){return $e||Ot()}var $e,G=P(()=>{"use strict";$e=null});async function At(t){let e=(await import("spark-md5")).default;return new Promise((o,n)=>{let s=Math.ceil(t.size/2097152),r=0,l=new e.ArrayBuffer,a=new FileReader,c=()=>{let m=r*2097152,d=Math.min(m+2097152,t.size);a.readAsArrayBuffer(t.slice(m,d))};a.onload=m=>{let d=m.target?.result;if(!d){n(p.business("Failed to read file chunk"));return}l.append(d),r++,r<s?c():o({md5:l.end()})},a.onerror=()=>{n(p.business("Failed to calculate MD5: FileReader error"))},c()})}async function Pt(t){let e=await import("crypto");if(Buffer.isBuffer(t)){let n=e.createHash("md5");return n.update(t),{md5:n.digest("hex")}}let o=await import("fs");return new Promise((n,i)=>{let s=e.createHash("md5"),r=o.createReadStream(t);r.on("error",l=>i(p.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 te(t){let e=I();if(e==="browser"){if(!(t instanceof Blob))throw p.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return At(t)}if(e==="node"){if(!(Buffer.isBuffer(t)||typeof t=="string"))throw p.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Pt(t)}throw p.business("Unknown or unsupported execution environment for MD5 calculation.")}var Ce=P(()=>{"use strict";G();w()});function Ke(t){try{return $t.parse(t)}catch(e){if(e instanceof K.z.ZodError){let o=e.issues[0],n=o.path.length>0?` at ${o.path.join(".")}`:"";throw p.config(`Configuration validation failed${n}: ${o.message}`)}throw p.config("Configuration validation failed")}}async function Ft(t){try{if(I()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),o=await import("os"),n=e(xe,{searchPlaces:[`.${xe}rc`,"package.json",`${o.homedir()}/.${xe}rc`],stopDir:o.homedir()}),i;if(t?i=n.load(t):i=n.search(),i&&i.config)return Ke(i.config)}catch(e){if(R(e))throw e}return{}}async function Me(t){if(I()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},o=await Ft(t),n={apiUrl:e.apiUrl??o.apiUrl,apiKey:e.apiKey??o.apiKey,deployToken:e.deployToken??o.deployToken};return Ke(n)}var K,xe,$t,Be=P(()=>{"use strict";K=require("zod");w();G();xe="ship",$t=K.z.object({apiUrl:K.z.string().url().optional(),apiKey:K.z.string().optional(),deployToken:K.z.string().optional()}).strict()});function Je(t){return!t||t.length===0?[]:t.filter(e=>{if(!e)return!1;let o=e.replace(/\\/g,"/").split("/").filter(Boolean);if(o.length===0)return!0;let n=o[o.length-1];if((0,Ge.isJunk)(n))return!1;for(let s of o)if(s.startsWith(".")||s.length>255)return!1;let i=o.slice(0,-1);for(let s of i)if(Nt.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var Ge,Nt,qe=P(()=>{"use strict";Ge=require("junk"),Nt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ve(t){if(!t||t.length===0)return"";let e=t.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let o=e.map(s=>s.split("/").filter(Boolean)),n=[],i=Math.min(...o.map(s=>s.length));for(let s=0;s<i;s++){let r=o[0][s];if(o.every(l=>l[s]===r))n.push(r);else break}return n.join("/")}function ne(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ve=P(()=>{"use strict"});function We(t,e={}){if(e.flatten===!1)return t.map(n=>({path:ne(n),name:we(n)}));let o=Lt(t);return t.map(n=>{let i=ne(n);if(o){let s=o.endsWith("/")?o:`${o}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=we(n)),{path:i,name:we(n)}})}function Lt(t){if(!t.length)return"";let o=t.map(s=>ne(s)).map(s=>s.split("/")),n=[],i=Math.min(...o.map(s=>s.length));for(let s=0;s<i-1;s++){let r=o[0][s];if(o.every(l=>l[s]===r))n.push(r);else break}return n.join("/")}function we(t){return t.split(/[/\\]/).pop()||t}var Ye=P(()=>{"use strict";ve()});var Ze={};Tt(Ze,{processFilesForNode:()=>_t});function Xe(t,e=new Set){let o=[],n=k.realpathSync(t);if(e.has(n))return o;e.add(n);let i=k.readdirSync(t);for(let s of i){let r=T.join(t,s),l=k.statSync(r);if(l.isDirectory()){let a=Xe(r,e);o.push(...a)}else l.isFile()&&o.push(r)}return o}async function _t(t,e={}){if(I()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");let o=t.flatMap(u=>{let C=T.resolve(u);try{return k.statSync(C).isDirectory()?Xe(C):[C]}catch{throw p.file(`Path does not exist: ${u}`,u)}}),n=[...new Set(o)],i=Je(n);if(i.length===0)return[];let s=t.map(u=>T.resolve(u)),r=Ve(s.map(u=>{try{return k.statSync(u).isDirectory()?u:T.dirname(u)}catch{return T.dirname(u)}})),l=i.map(u=>{if(r&&r.length>0){let C=T.relative(r,u);if(C&&typeof C=="string"&&!C.startsWith(".."))return C.replace(/\\/g,"/")}return T.basename(u)}),a=We(l,{flatten:e.pathDetect!==!1}),c=[],m=0,d=Q();for(let u=0;u<i.length;u++){let C=i[u],O=a[u].path;try{let A=k.statSync(C);if(A.size===0)continue;if(A.size>d.maxFileSize)throw p.business(`File ${C} is too large. Maximum allowed size is ${d.maxFileSize/(1024*1024)}MB.`);if(m+=A.size,m>d.maxTotalSize)throw p.business(`Total deploy size is too large. Maximum allowed is ${d.maxTotalSize/(1024*1024)}MB.`);let H=k.readFileSync(C),{md5:xt}=await te(H);if(O.includes("\0")||O.includes("/../")||O.startsWith("../")||O.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${O}" for file: ${C}`);c.push({path:O,content:H,size:H.length,md5:xt})}catch(A){if(R(A))throw A;let H=A instanceof Error?A.message:String(A);throw p.file(`Failed to read file "${C}": ${H}`,C)}}if(c.length>d.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return c}var k,T,Qe=P(()=>{"use strict";G();Ce();qe();w();ee();Ye();ve();k=b(require("fs"),1),T=b(require("path"),1)});var gt=require("commander");w();var Z=class{constructor(){this.handlers=new Map}on(e,o){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(o)}off(e,o){let n=this.handlers.get(e);n&&(n.delete(o),n.size===0&&this.handlers.delete(e))}emit(e,...o){let n=this.handlers.get(e);if(!n)return;let i=Array.from(n);for(let s of i)try{s(...o)}catch(r){n.delete(s),e!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(e)):this.emit("error",new Error(String(r)),String(e))},0)}}transfer(e){this.handlers.forEach((o,n)=>{o.forEach(i=>{e.on(n,i)})})}clear(){this.handlers.clear()}};var y={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},kt=3e4,j=class extends Z{constructor(e){super(),this.apiUrl=e.apiUrl||U,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??kt,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,o,n){let i=this.mergeHeaders(o.headers),{signal:s,cleanup:r}=this.createTimeoutSignal(o.signal),l={...o,headers:i,credentials:i.Authorization?void 0:"include",signal:s};this.emit("request",e,l);try{let a=await fetch(e,l);return r(),a.ok||await this.handleResponseError(a,n),this.emit("response",this.safeClone(a),e),{data:await this.parseResponse(this.safeClone(a)),status:a.status}}catch(a){r();let c=a instanceof Error?a:new Error(String(a));this.emit("error",c,e),this.handleFetchError(a,n)}}async request(e,o,n){let{data:i}=await this.executeRequest(e,o,n);return i}async requestWithStatus(e,o,n){return this.executeRequest(e,o,n)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let o=new AbortController,n=setTimeout(()=>o.abort(),this.timeout);if(e){let i=()=>o.abort();e.addEventListener("abort",i),e.aborted&&o.abort()}return{signal:o.signal,cleanup:()=>clearTimeout(n)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async handleResponseError(e,o){let n={};try{if(e.headers.get("content-type")?.includes("application/json")){let r=await e.json();if(r&&typeof r=="object"){let l=r;typeof l.message=="string"&&(n.message=l.message),typeof l.error=="string"&&(n.error=l.error)}}else n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let i=n.message||n.error||`${o} failed`;throw e.status===401?p.authentication(i):p.api(i,e.status)}handleFetchError(e,o){throw R(e)?e:e instanceof Error&&e.name==="AbortError"?p.cancelled(`${o} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?p.network(`${o} failed: ${e.message}`,e):e instanceof Error?p.business(`${o} failed: ${e.message}`):p.business(`${o} failed: Unknown error`)}async deploy(e,o={}){if(!e.length)throw p.business("No files to deploy");for(let r of e)if(!r.md5)throw p.file(`MD5 checksum missing for file: ${r.path}`,r.path);let{body:n,headers:i}=await this.createDeployBody(e,o.labels,o.via),s={};return o.deployToken?s.Authorization=`Bearer ${o.deployToken}`:o.apiKey&&(s.Authorization=`Bearer ${o.apiKey}`),o.caller&&(s["X-Caller"]=o.caller),this.request(`${o.apiUrl||this.apiUrl}${y.DEPLOYMENTS}`,{method:"POST",body:n,headers:{...i,...s},signal:o.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,o){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:o})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,o,n){let i={};o&&(i.deployment=o),n!==void 0&&(i.labels=n);let{data:s,status:r}=await this.requestWithStatus(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Set domain");return{...s,isCreate:r===201}}async listDomains(){return this.request(`${this.apiUrl}${y.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async updateDomainLabels(e,o){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:o})},"Update domain labels")}async removeDomain(e){await this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${y.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,o){let n={};return e!==void 0&&(n.ttl=e),o!==void 0&&(n.labels=o),this.request(`${this.apiUrl}${y.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${y.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${y.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${y.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${y.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${y.PING}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return this.request(`${this.apiUrl}${y.PING}`,{method:"GET"},"Ping")}async checkSPA(e){let o=e.find(r=>r.path==="index.html"||r.path==="/index.html");if(!o||o.size>100*1024)return!1;let n;if(typeof Buffer<"u"&&Buffer.isBuffer(o.content))n=o.content.toString("utf-8");else if(typeof Blob<"u"&&o.content instanceof Blob)n=await o.content.text();else if(typeof File<"u"&&o.content instanceof File)n=await o.content.text();else return!1;let i={files:e.map(r=>r.path),index:n};return(await this.request(`${this.apiUrl}${y.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA check")).isSPA}};w();ee();w();w();function Se(t={},e={}){let o={apiUrl:t.apiUrl||e.apiUrl||U,apiKey:t.apiKey!==void 0?t.apiKey:e.apiKey,deployToken:t.deployToken!==void 0?t.deployToken:e.deployToken},n={apiUrl:o.apiUrl};return o.apiKey!==void 0&&(n.apiKey=o.apiKey),o.deployToken!==void 0&&(n.deployToken=o.deployToken),n}function Fe(t,e){let o={...t};return o.apiUrl===void 0&&e.apiUrl!==void 0&&(o.apiUrl=e.apiUrl),o.apiKey===void 0&&e.apiKey!==void 0&&(o.apiKey=e.apiKey),o.deployToken===void 0&&e.deployToken!==void 0&&(o.deployToken=e.deployToken),o.timeout===void 0&&e.timeout!==void 0&&(o.timeout=e.timeout),o.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(o.maxConcurrency=e.maxConcurrency),o.onProgress===void 0&&e.onProgress!==void 0&&(o.onProgress=e.onProgress),o.caller===void 0&&e.caller!==void 0&&(o.caller=e.caller),o}w();Ce();async function It(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),o;typeof Buffer<"u"?o=Buffer.from(e,"utf-8"):o=new Blob([e],{type:"application/json"});let{md5:n}=await te(o);return{path:ge,content:o,size:e.length,md5:n}}async function Ne(t,e,o){if(o.spaDetect===!1||t.some(n=>n.path===ge))return t;try{if(await e.checkSPA(t)){let i=await It();return[...t,i]}}catch{}return t}function Le(t){let{getApi:e,ensureInit:o,processInput:n,clientDefaults:i,hasAuth:s}=t;return{create:async(r,l={})=>{await o();let a=i?Fe(l,i):l;if(s&&!s()&&!a.deployToken&&!a.apiKey)throw p.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw p.config("processInput function is not provided.");let c=e(),m=await n(r,a);return m=await Ne(m,c,a),c.deploy(m,a)},list:async()=>(await o(),e().listDeployments()),get:async r=>(await o(),e().getDeployment(r)),set:async(r,l)=>(await o(),e().updateDeploymentLabels(r,l.labels)),remove:async r=>{await o(),await e().removeDeployment(r)}}}function _e(t){let{getApi:e,ensureInit:o}=t;return{set:async(n,i={})=>{await o();let{deployment:s,labels:r}=i;return s===void 0&&r&&r.length>0?e().updateDomainLabels(n,r):e().setDomain(n,s,r)},list:async()=>(await o(),e().listDomains()),get:async n=>(await o(),e().getDomain(n)),remove:async n=>{await o(),await e().removeDomain(n)},verify:async n=>(await o(),e().verifyDomain(n)),validate:async n=>(await o(),e().validateDomain(n)),dns:async n=>(await o(),e().getDomainDns(n)),records:async n=>(await o(),e().getDomainRecords(n)),share:async n=>(await o(),e().getDomainShare(n))}}function Ue(t){let{getApi:e,ensureInit:o}=t;return{get:async()=>(await o(),e().getAccount())}}function je(t){let{getApi:e,ensureInit:o}=t;return{create:async(n={})=>(await o(),e().createToken(n.ttl,n.labels)),list:async()=>(await o(),e().listTokens()),remove:async n=>{await o(),await e().removeToken(n)}}}var oe=class{constructor(e={}){this.initPromise=null;this._config=null;this.auth=null;this.clientOptions=e,e.deployToken?this.auth={type:"token",value:e.deployToken}:e.apiKey&&(this.auth={type:"apiKey",value:e.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let o=this.resolveInitialConfig(e);this.http=new j({...e,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=Le({...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(e,o){return this.deployments.create(e,o)}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=Q(),this._config)}on(e,o){this.http.on(e,o)}off(e,o){this.http.off(e,o)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(o){console.warn("Event transfer failed during client replacement:",o)}this.http=e}setDeployToken(e){if(!e||typeof e!="string")throw p.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw p.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};w();G();Be();ee();w();var De=b(require("mime-db"),1),be={};for(let t in De.default){let e=De.default[t];e&&e.extensions&&e.extensions.forEach(o=>{be[o]||(be[o]=t)})}function ze(t){let e=t.includes(".")?t.substring(t.lastIndexOf(".")+1).toLowerCase():"";return be[e]||"application/octet-stream"}async function He(t,e,o){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new n,l=[];for(let d of t){let u=ze(d.path),C;if(Buffer.isBuffer(d.content))C=new i([d.content],d.path,{type:u});else if(typeof Blob<"u"&&d.content instanceof Blob)C=new i([d.content],d.path,{type:u});else throw p.file(`Unsupported file.content type for Node.js: ${d.path}`,d.path);if(!d.md5)throw p.file(`File missing md5 checksum: ${d.path}`,d.path);let O=d.path.startsWith("/")?d.path:"/"+d.path;r.append("files[]",C,O),l.push(d.md5)}r.append("checksums",JSON.stringify(l)),e&&e.length>0&&r.append("labels",JSON.stringify(e)),o&&r.append("via",o);let a=new s(r),c=[];for await(let d of a.encode())c.push(Buffer.from(d));let m=Buffer.concat(c);return{body:m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength),headers:{"Content-Type":a.contentType,"Content-Length":Buffer.byteLength(m).toString()}}}var ie=class extends oe{constructor(e={}){if(I()!=="node")throw p.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return Se(e,{})}async loadFullConfig(){try{let e=await Me(this.clientOptions.configFile),o=Se(this.clientOptions,e);o.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(o.deployToken):o.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(o.apiKey);let n=new j({...this.clientOptions,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();Ie(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,o){let n=typeof e=="string"?[e]:e;if(!Array.isArray(n)||!n.every(s=>typeof s=="string"))throw p.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw p.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(Qe(),Ze));return i(n,o)}getDeployBodyCreator(){return He}};w();var N=require("fs"),pe=b(require("path"),1);var Ee=b(require("columnify"),1),f=require("yoctocolors"),et=["isCreate"],D=(t,e,o)=>o?e:t(e),v=(t,e,o)=>{console.log(e?JSON.stringify({success:t},null,2)+`
|
|
3
3
|
`:`${D(f.green,t.toLowerCase().replace(/\.$/,""),o)}
|
|
4
4
|
`)},E=(t,e,o)=>{if(e)console.error(JSON.stringify({error:t},null,2)+`
|
|
5
5
|
`);else{let n=D(s=>(0,f.inverse)((0,f.red)(s)),`${D(f.hidden,"[",o)}error${D(f.hidden,"]",o)}`,o),i=D(f.red,t.toLowerCase().replace(/\.$/,""),o);console.error(`${n} ${i}
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
`);else{let n=D(s=>(0,f.inverse)((0,f.yellow)(s)),`${D(f.hidden,"[",o)}warning${D(f.hidden,"]",o)}`,o),i=D(f.yellow,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${i}
|
|
8
8
|
`)}},M=(t,e,o)=>{if(e)console.log(JSON.stringify({info:t},null,2)+`
|
|
9
9
|
`);else{let n=D(s=>(0,f.inverse)((0,f.blue)(s)),`${D(f.hidden,"[",o)}info${D(f.hidden,"]",o)}`,o),i=D(f.blue,t.toLowerCase().replace(/\.$/,""),o);console.log(`${n} ${i}
|
|
10
|
-
`)}},
|
|
10
|
+
`)}},Ut=(t,e="details",o)=>{if(t==null||t===0)return"-";let n=new Date(t*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return e==="table"?n.replace(/T/,D(f.hidden,"T",o)).replace(/Z$/,D(f.hidden,"Z",o)):n},tt=(t,e,o="details",n)=>{if(typeof e=="number"&&(t==="created"||t==="expires"||t==="linked"))return Ut(e,o,n);if(t==="size"&&typeof e=="number"){let i=e/1048576;return i>=1?`${i.toFixed(1)}Mb`:`${(e/1024).toFixed(1)}Kb`}if(t==="config"){if(typeof e=="boolean")return e?"yes":"no";if(typeof e=="number")return e===1?"yes":"no"}return String(e)},re=(t,e,o,n)=>{if(!t||t.length===0)return"";let i=t[0],s=e||Object.keys(i).filter(a=>i[a]!==void 0&&!et.includes(a)),r=t.map(a=>{let c=a,m={};return s.forEach(d=>{d in c&&c[d]!==void 0&&(m[d]=tt(d,c[d],"table",o))}),m});return(0,Ee.default)(r,{columnSplitter:" ",columns:s,config:s.reduce((a,c)=>(a[c]={headingTransform:m=>D(f.dim,n?.[m]||m,o)},a),{})}).split(`
|
|
11
11
|
`).map(a=>a.replace(/\0/g,"").replace(/\s+$/,"")).join(`
|
|
12
12
|
`)+`
|
|
13
13
|
`},J=(t,e)=>{let o=Object.entries(t).filter(([s,r])=>et.includes(s)?!1:r!==void 0);if(o.length===0)return"";let n=o.map(([s,r])=>({property:s+":",value:tt(s,r,"details",e)}));return(0,Ee.default)(n,{columnSplitter:" ",showHeaders:!1,config:{property:{dataTransform:s=>D(f.dim,s,e)}}}).split(`
|
|
@@ -21,7 +21,7 @@ source '${r.completionFile}'
|
|
|
21
21
|
`),a=[],c=0,m=!1;for(;c<l.length;)if(l[c].trim()==="# ship"){for(m=!0,c++;c<l.length&&l[c].trim()!=="# ship end";)c++;c<l.length&&c++}else a.push(l[c]),c++;if(m){let d=r.endsWith(`
|
|
22
22
|
`),u=a.length===0?"":a.join(`
|
|
23
23
|
`)+(d?`
|
|
24
|
-
`:"");S.writeFileSync(s.profileFile,u),v(`completion script uninstalled for ${n}`,e,o),se(`run "source ${s.profileFile}" or restart your shell`,e,o)}else E("completion was not found in profile",e,o)}catch(r){let l=r instanceof Error?r.message:String(r);E(`could not uninstall completion script: ${l}`,e,o)}}var lt=require("readline/promises"),F=require("fs"),ct=require("os"),dt=require("path");w();var ae=require("yoctocolors"),B=(0,dt.join)((0,ct.homedir)(),".shiprc");function at(t){return t.length<13?t:t.slice(0,9)+"..."+t.slice(-4)}function pt(){try{return(0,F.existsSync)(B)?JSON.parse((0,F.readFileSync)(B,"utf-8")):{}}catch{return{}}}async function mt(t={}){let{noColor:e,json:o}=t,n=m=>e?m:(0,ae.dim)(m),i=m=>e?m:(0,ae.green)(m);if(o){let m=pt(),d=typeof m.apiKey=="string"?m.apiKey:void 0,u=typeof m.apiUrl=="string"?m.apiUrl:void 0;console.log(JSON.stringify({path:B,exists:(0,F.existsSync)(B),...d?{apiKey:at(d)}:{},...u&&u!==
|
|
24
|
+
`:"");S.writeFileSync(s.profileFile,u),v(`completion script uninstalled for ${n}`,e,o),se(`run "source ${s.profileFile}" or restart your shell`,e,o)}else E("completion was not found in profile",e,o)}catch(r){let l=r instanceof Error?r.message:String(r);E(`could not uninstall completion script: ${l}`,e,o)}}var lt=require("readline/promises"),F=require("fs"),ct=require("os"),dt=require("path");w();var ae=require("yoctocolors"),B=(0,dt.join)((0,ct.homedir)(),".shiprc");function at(t){return t.length<13?t:t.slice(0,9)+"..."+t.slice(-4)}function pt(){try{return(0,F.existsSync)(B)?JSON.parse((0,F.readFileSync)(B,"utf-8")):{}}catch{return{}}}async function mt(t={}){let{noColor:e,json:o}=t,n=m=>e?m:(0,ae.dim)(m),i=m=>e?m:(0,ae.green)(m);if(o){let m=pt(),d=typeof m.apiKey=="string"?m.apiKey:void 0,u=typeof m.apiUrl=="string"?m.apiUrl:void 0;console.log(JSON.stringify({path:B,exists:(0,F.existsSync)(B),...d?{apiKey:at(d)}:{},...u&&u!==U?{apiUrl:u}:{}},null,2)+`
|
|
25
25
|
`);return}let s=pt(),r=typeof s.apiKey=="string"?s.apiKey:void 0,l=(0,lt.createInterface)({input:process.stdin,output:process.stdout});console.log("");let a=r?` API Key (${n(at(r))}): `:" API Key: ",c;try{c=(await l.question(a)).trim()}finally{l.close()}c&&(X(c),s.apiKey=c),(0,F.writeFileSync)(B,JSON.stringify(s,null,2)+`
|
|
26
26
|
`),console.log(`
|
|
27
27
|
${i("saved to")} ${n(B)}
|