@shipstatic/ship 0.4.21 → 0.4.23
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 +8 -3
- package/dist/browser.js +2 -2
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -3
- package/dist/index.d.ts +8 -3
- 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 ae=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,ht=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var gt=(t,e)=>{for(var o in e)ae(t,o,{get:e[o],enumerable:!0})},yt=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ut(e))!ht.call(t,i)&&i!==o&&ae(t,i,{get:()=>e[i],enumerable:!(n=mt(e,i))||n.enumerable});return t};var w=(t,e,o)=>(o=t!=null?dt(ft(t)):{},yt(e||!t||!t.__esModule?ae(o,"default",{value:t,enumerable:!0}):o,t));function k(t){return t!==null&&typeof t=="object"&&"name"in t&&t.name==="ShipError"&&"status"in t}function Re(t){if(!t.startsWith(N))throw p.validation(`API key must start with "${N}"`);if(t.length!==xe)throw p.validation(`API key must be ${xe} characters total (${N} + ${ce} hex chars)`);let e=t.slice(N.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`API key must contain ${ce} hexadecimal characters after "${N}" prefix`)}function ke(t){if(!t.startsWith(L))throw p.validation(`Deploy token must start with "${L}"`);if(t.length!==Ee)throw p.validation(`Deploy token must be ${Ee} characters total (${L} + ${le} hex chars)`);let e=t.slice(L.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`Deploy token must contain ${le} hexadecimal characters after "${L}" prefix`)}function be(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 k(e)?e:p.validation("API URL must be a valid URL")}}var h,pe,p,N,ce,xe,L,le,Ee,de,V,E=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"})(h||(h={}));pe={client:new Set([h.Business,h.Config,h.File,h.Validation]),network:new Set([h.Network]),auth:new Set([h.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===h.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(h.Validation,e,400,o)}static notFound(e,o){let n=o?`${e} ${o} not found`:`${e} not found`;return new t(h.NotFound,n,404)}static rateLimit(e="Too many requests"){return new t(h.RateLimit,e,429)}static authentication(e="Authentication required",o){return new t(h.Authentication,e,401,o)}static business(e,o=400){return new t(h.Business,e,o)}static network(e,o){return new t(h.Network,e,void 0,{cause:o})}static cancelled(e){return new t(h.Cancelled,e)}static file(e,o){return new t(h.File,e,void 0,{filePath:o})}static config(e,o){return new t(h.Config,e,void 0,o)}static api(e,o=500){return new t(h.Api,e,o)}static database(e,o=500){return new t(h.Api,e,o)}static storage(e,o=500){return new t(h.Api,e,o)}get filePath(){return this.details?.filePath}isClientError(){return pe.client.has(this.type)}isNetworkError(){return pe.network.has(this.type)}isAuthError(){return pe.auth.has(this.type)}isValidationError(){return this.type===h.Validation}isFileError(){return this.type===h.File}isConfigError(){return this.type===h.Config}isType(e){return this.type===e}};N="ship-",ce=64,xe=N.length+ce,L="token-",le=64,Ee=L.length+le,de="ship.json";V="https://api.shipstatic.com"});function Oe(t){me=t}function Y(){if(me===null)throw p.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return me}var me,X=P(()=>{"use strict";E();me=null});function Ct(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function I(){return Ae||Ct()}var Ae,B=P(()=>{"use strict";Ae=null});async function Dt(t){let e=(await import("spark-md5")).default;return new Promise((o,n)=>{let s=Math.ceil(t.size/2097152),r=0,c=new e.ArrayBuffer,a=new FileReader,l=()=>{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}c.append(d),r++,r<s?l():o({md5:c.end()})},a.onerror=()=>{n(p.business("Failed to calculate MD5: FileReader error"))},l()})}async function vt(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",c=>i(p.business(`Failed to read file for MD5: ${c.message}`))),r.on("data",c=>s.update(c)),r.on("end",()=>n({md5:s.digest("hex")}))})}async function Z(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 Dt(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 vt(t)}throw p.business("Unknown or unsupported execution environment for MD5 calculation.")}var fe=P(()=>{"use strict";B();E()});function _e(t){try{return Tt.parse(t)}catch(e){if(e instanceof U.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 xt(t){try{if(I()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),o=await import("os"),n=e(he,{searchPlaces:[`.${he}rc`,"package.json",`${o.homedir()}/.${he}rc`],stopDir:o.homedir()}),i;if(t?i=n.load(t):i=n.search(),i&&i.config)return _e(i.config)}catch(e){if(k(e))throw e}return{}}async function Ue(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 xt(t),n={apiUrl:e.apiUrl??o.apiUrl,apiKey:e.apiKey??o.apiKey,deployToken:e.deployToken??o.deployToken};return _e(n)}var U,he,Tt,Me=P(()=>{"use strict";U=require("zod");E();B();he="ship",Tt=U.z.object({apiUrl:U.z.string().url().optional(),apiKey:U.z.string().optional(),deployToken:U.z.string().optional()}).strict()});function ze(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,Be.isJunk)(n))return!1;let i=o.slice(0,-1);for(let s of i)if(Et.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var Be,Et,He=P(()=>{"use strict";Be=require("junk"),Et=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ge(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(c=>c[s]===r))n.push(r);else break}return n.join("/")}function ee(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Se=P(()=>{"use strict"});function Je(t,e={}){if(e.flatten===!1)return t.map(n=>({path:ee(n),name:Ce(n)}));let o=Rt(t);return t.map(n=>{let i=ee(n);if(o){let s=o.endsWith("/")?o:`${o}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=Ce(n)),{path:i,name:Ce(n)}})}function Rt(t){if(!t.length)return"";let o=t.map(s=>ee(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(c=>c[s]===r))n.push(r);else break}return n.join("/")}function Ce(t){return t.split(/[/\\]/).pop()||t}var qe=P(()=>{"use strict";Se()});var We={};gt(We,{processFilesForNode:()=>kt});function Ve(t,e=new Set){let o=[],n=b.realpathSync(t);if(e.has(n))return o;e.add(n);let i=b.readdirSync(t);for(let s of i){let r=R.join(t,s),c=b.statSync(r);if(c.isDirectory()){let a=Ve(r,e);o.push(...a)}else c.isFile()&&o.push(r)}return o}async function kt(t,e={}){if(I()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");let o=t.flatMap(g=>{let C=R.resolve(g);try{return b.statSync(C).isDirectory()?Ve(C):[C]}catch{throw p.file(`Path does not exist: ${g}`,g)}}),n=[...new Set(o)],i=ze(n);if(i.length===0)return[];let s=t.map(g=>R.resolve(g)),r=Ge(s.map(g=>{try{return b.statSync(g).isDirectory()?g:R.dirname(g)}catch{return R.dirname(g)}})),c=i.map(g=>{if(r&&r.length>0){let C=R.relative(r,g);if(C&&typeof C=="string"&&!C.startsWith(".."))return C.replace(/\\/g,"/")}return R.basename(g)}),a=Je(c,{flatten:e.pathDetect!==!1}),l=[],m=0,d=Y();for(let g=0;g<i.length;g++){let C=i[g],O=a[g].path;try{let A=b.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 K=b.readFileSync(C),{md5:lt}=await Z(K);if(O.includes("\0")||O.includes("/../")||O.startsWith("../")||O.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${O}" for file: ${C}`);l.push({path:O,content:K,size:K.length,md5:lt})}catch(A){if(k(A))throw A;let K=A instanceof Error?A.message:String(A);throw p.file(`Failed to read file "${C}": ${K}`,C)}}if(l.length>d.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return l}var b,R,Ye=P(()=>{"use strict";B();fe();He();E();X();qe();Se();b=w(require("fs"),1),R=w(require("path"),1)});var at=require("commander");E();var W=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"},St=3e4,_=class extends W{constructor(e){super(),this.apiUrl=e.apiUrl||V,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??St,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),c={...o,headers:i,credentials:i.Authorization?void 0:"include",signal:s};this.emit("request",e,c);try{let a=await fetch(e,c);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 l=a instanceof Error?a:new Error(String(a));this.emit("error",l,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 c=r;typeof c.message=="string"&&(n.message=c.message),typeof c.error=="string"&&(n.error=c.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 k(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.tags,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 updateDeploymentTags(e,o){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:o})},"Update deployment tags")}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.tags=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 updateDomainTags(e,o){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:o})},"Update domain tags")}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.tags=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}};E();X();E();E();function ue(t={},e={}){let o={apiUrl:t.apiUrl||e.apiUrl||V,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 Pe(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}E();fe();async function wt(){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 Z(o);return{path:de,content:o,size:e.length,md5:n}}async function Ie(t,e,o){if(o.spaDetect===!1||t.some(n=>n.path===de))return t;try{if(await e.checkSPA(t)){let i=await wt();return[...t,i]}}catch{}return t}function $e(t){let{getApi:e,ensureInit:o,processInput:n,clientDefaults:i,hasAuth:s}=t;return{create:async(r,c={})=>{await o();let a=i?Pe(c,i):c;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 l=e(),m=await n(r,a);return m=await Ie(m,l,a),l.deploy(m,a)},list:async()=>(await o(),e().listDeployments()),get:async r=>(await o(),e().getDeployment(r)),set:async(r,c)=>(await o(),e().updateDeploymentTags(r,c.tags)),remove:async r=>{await o(),await e().removeDeployment(r)}}}function Fe(t){let{getApi:e,ensureInit:o}=t;return{set:async(n,i={})=>{await o();let{deployment:s,tags:r}=i;return s===void 0&&r&&r.length>0?e().updateDomainTags(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 Ne(t){let{getApi:e,ensureInit:o}=t;return{get:async()=>(await o(),e().getAccount())}}function Le(t){let{getApi:e,ensureInit:o}=t;return{create:async(n={})=>(await o(),e().createToken(n.ttl,n.tags)),list:async()=>(await o(),e().listTokens()),remove:async n=>{await o(),await e().removeToken(n)}}}var Q=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 _({...e,...o,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=Fe(n),this._account=Ne(n),this._tokens=Le(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=Y(),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}};E();B();Me();X();E();var ge=w(require("mime-db"),1),ye={};for(let t in ge.default){let e=ge.default[t];e&&e.extensions&&e.extensions.forEach(o=>{ye[o]||(ye[o]=t)})}function je(t){let e=t.includes(".")?t.substring(t.lastIndexOf(".")+1).toLowerCase():"";return ye[e]||"application/octet-stream"}async function Ke(t,e,o){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new n,c=[];for(let d of t){let g=je(d.path),C;if(Buffer.isBuffer(d.content))C=new i([d.content],d.path,{type:g});else if(typeof Blob<"u"&&d.content instanceof Blob)C=new i([d.content],d.path,{type:g});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),c.push(d.md5)}r.append("checksums",JSON.stringify(c)),e&&e.length>0&&r.append("tags",JSON.stringify(e)),o&&r.append("via",o);let a=new s(r),l=[];for await(let d of a.encode())l.push(Buffer.from(d));let m=Buffer.concat(l);return{body:m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength),headers:{"Content-Type":a.contentType,"Content-Length":Buffer.byteLength(m).toString()}}}var te=class extends Q{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 ue(e,{})}async loadFullConfig(){try{let e=await Ue(this.clientOptions.configFile),o=ue(this.clientOptions,e);o.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(o.deployToken):o.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(o.apiKey);let n=new _({...this.clientOptions,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();Oe(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(()=>(Ye(),We));return i(n,o)}getDeployBodyCreator(){return Ke}};E();var F=require("fs"),ie=w(require("path"),1);var De=w(require("columnify"),1),u=require("yoctocolors"),Xe=["isCreate"],v=(t,e,o)=>o?e:t(e),T=(t,e,o)=>{console.log(e?JSON.stringify({success:t},null,2)+`
|
|
2
|
+
"use strict";var dt=Object.create;var ae=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,ht=Object.prototype.hasOwnProperty;var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var gt=(t,e)=>{for(var o in e)ae(t,o,{get:e[o],enumerable:!0})},yt=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ut(e))!ht.call(t,i)&&i!==o&&ae(t,i,{get:()=>e[i],enumerable:!(n=mt(e,i))||n.enumerable});return t};var w=(t,e,o)=>(o=t!=null?dt(ft(t)):{},yt(e||!t||!t.__esModule?ae(o,"default",{value:t,enumerable:!0}):o,t));function k(t){return t!==null&&typeof t=="object"&&"name"in t&&t.name==="ShipError"&&"status"in t}function Re(t){if(!t.startsWith(N))throw p.validation(`API key must start with "${N}"`);if(t.length!==xe)throw p.validation(`API key must be ${xe} characters total (${N} + ${ce} hex chars)`);let e=t.slice(N.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`API key must contain ${ce} hexadecimal characters after "${N}" prefix`)}function ke(t){if(!t.startsWith(L))throw p.validation(`Deploy token must start with "${L}"`);if(t.length!==Ee)throw p.validation(`Deploy token must be ${Ee} characters total (${L} + ${le} hex chars)`);let e=t.slice(L.length);if(!/^[a-f0-9]{64}$/i.test(e))throw p.validation(`Deploy token must contain ${le} hexadecimal characters after "${L}" prefix`)}function be(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 k(e)?e:p.validation("API URL must be a valid URL")}}var h,pe,p,N,ce,xe,L,le,Ee,de,V,E=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"})(h||(h={}));pe={client:new Set([h.Business,h.Config,h.File,h.Validation]),network:new Set([h.Network]),auth:new Set([h.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===h.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(h.Validation,e,400,o)}static notFound(e,o){let n=o?`${e} ${o} not found`:`${e} not found`;return new t(h.NotFound,n,404)}static rateLimit(e="Too many requests"){return new t(h.RateLimit,e,429)}static authentication(e="Authentication required",o){return new t(h.Authentication,e,401,o)}static business(e,o=400){return new t(h.Business,e,o)}static network(e,o){return new t(h.Network,e,void 0,{cause:o})}static cancelled(e){return new t(h.Cancelled,e)}static file(e,o){return new t(h.File,e,void 0,{filePath:o})}static config(e,o){return new t(h.Config,e,void 0,o)}static api(e,o=500){return new t(h.Api,e,o)}static database(e,o=500){return new t(h.Api,e,o)}static storage(e,o=500){return new t(h.Api,e,o)}get filePath(){return this.details?.filePath}isClientError(){return pe.client.has(this.type)}isNetworkError(){return pe.network.has(this.type)}isAuthError(){return pe.auth.has(this.type)}isValidationError(){return this.type===h.Validation}isFileError(){return this.type===h.File}isConfigError(){return this.type===h.Config}isType(e){return this.type===e}};N="ship-",ce=64,xe=N.length+ce,L="token-",le=64,Ee=L.length+le,de="ship.json";V="https://api.shipstatic.com"});function Oe(t){me=t}function Y(){if(me===null)throw p.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return me}var me,X=P(()=>{"use strict";E();me=null});function Ct(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function I(){return Ae||Ct()}var Ae,B=P(()=>{"use strict";Ae=null});async function Dt(t){let e=(await import("spark-md5")).default;return new Promise((o,n)=>{let s=Math.ceil(t.size/2097152),r=0,c=new e.ArrayBuffer,a=new FileReader,l=()=>{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}c.append(d),r++,r<s?l():o({md5:c.end()})},a.onerror=()=>{n(p.business("Failed to calculate MD5: FileReader error"))},l()})}async function vt(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",c=>i(p.business(`Failed to read file for MD5: ${c.message}`))),r.on("data",c=>s.update(c)),r.on("end",()=>n({md5:s.digest("hex")}))})}async function Z(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 Dt(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 vt(t)}throw p.business("Unknown or unsupported execution environment for MD5 calculation.")}var fe=P(()=>{"use strict";B();E()});function _e(t){try{return Tt.parse(t)}catch(e){if(e instanceof U.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 xt(t){try{if(I()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),o=await import("os"),n=e(he,{searchPlaces:[`.${he}rc`,"package.json",`${o.homedir()}/.${he}rc`],stopDir:o.homedir()}),i;if(t?i=n.load(t):i=n.search(),i&&i.config)return _e(i.config)}catch(e){if(k(e))throw e}return{}}async function Ue(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 xt(t),n={apiUrl:e.apiUrl??o.apiUrl,apiKey:e.apiKey??o.apiKey,deployToken:e.deployToken??o.deployToken};return _e(n)}var U,he,Tt,Me=P(()=>{"use strict";U=require("zod");E();B();he="ship",Tt=U.z.object({apiUrl:U.z.string().url().optional(),apiKey:U.z.string().optional(),deployToken:U.z.string().optional()}).strict()});function ze(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,Be.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(Et.some(r=>s.toLowerCase()===r.toLowerCase()))return!1;return!0})}var Be,Et,He=P(()=>{"use strict";Be=require("junk"),Et=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ge(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(c=>c[s]===r))n.push(r);else break}return n.join("/")}function ee(t){return t.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Se=P(()=>{"use strict"});function Je(t,e={}){if(e.flatten===!1)return t.map(n=>({path:ee(n),name:Ce(n)}));let o=Rt(t);return t.map(n=>{let i=ee(n);if(o){let s=o.endsWith("/")?o:`${o}/`;i.startsWith(s)&&(i=i.substring(s.length))}return i||(i=Ce(n)),{path:i,name:Ce(n)}})}function Rt(t){if(!t.length)return"";let o=t.map(s=>ee(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(c=>c[s]===r))n.push(r);else break}return n.join("/")}function Ce(t){return t.split(/[/\\]/).pop()||t}var qe=P(()=>{"use strict";Se()});var We={};gt(We,{processFilesForNode:()=>kt});function Ve(t,e=new Set){let o=[],n=b.realpathSync(t);if(e.has(n))return o;e.add(n);let i=b.readdirSync(t);for(let s of i){let r=R.join(t,s),c=b.statSync(r);if(c.isDirectory()){let a=Ve(r,e);o.push(...a)}else c.isFile()&&o.push(r)}return o}async function kt(t,e={}){if(I()!=="node")throw p.business("processFilesForNode can only be called in Node.js environment.");let o=t.flatMap(g=>{let C=R.resolve(g);try{return b.statSync(C).isDirectory()?Ve(C):[C]}catch{throw p.file(`Path does not exist: ${g}`,g)}}),n=[...new Set(o)],i=ze(n);if(i.length===0)return[];let s=t.map(g=>R.resolve(g)),r=Ge(s.map(g=>{try{return b.statSync(g).isDirectory()?g:R.dirname(g)}catch{return R.dirname(g)}})),c=i.map(g=>{if(r&&r.length>0){let C=R.relative(r,g);if(C&&typeof C=="string"&&!C.startsWith(".."))return C.replace(/\\/g,"/")}return R.basename(g)}),a=Je(c,{flatten:e.pathDetect!==!1}),l=[],m=0,d=Y();for(let g=0;g<i.length;g++){let C=i[g],O=a[g].path;try{let A=b.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 K=b.readFileSync(C),{md5:lt}=await Z(K);if(O.includes("\0")||O.includes("/../")||O.startsWith("../")||O.endsWith("/.."))throw p.business(`Security error: Unsafe file path "${O}" for file: ${C}`);l.push({path:O,content:K,size:K.length,md5:lt})}catch(A){if(k(A))throw A;let K=A instanceof Error?A.message:String(A);throw p.file(`Failed to read file "${C}": ${K}`,C)}}if(l.length>d.maxFilesCount)throw p.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return l}var b,R,Ye=P(()=>{"use strict";B();fe();He();E();X();qe();Se();b=w(require("fs"),1),R=w(require("path"),1)});var at=require("commander");E();var W=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"},St=3e4,_=class extends W{constructor(e){super(),this.apiUrl=e.apiUrl||V,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??St,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),c={...o,headers:i,credentials:i.Authorization?void 0:"include",signal:s};this.emit("request",e,c);try{let a=await fetch(e,c);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 l=a instanceof Error?a:new Error(String(a));this.emit("error",l,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 c=r;typeof c.message=="string"&&(n.message=c.message),typeof c.error=="string"&&(n.error=c.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 k(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.tags,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 updateDeploymentTags(e,o){return this.request(`${this.apiUrl}${y.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:o})},"Update deployment tags")}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.tags=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 updateDomainTags(e,o){return this.request(`${this.apiUrl}${y.DOMAINS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:o})},"Update domain tags")}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.tags=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}};E();X();E();E();function ue(t={},e={}){let o={apiUrl:t.apiUrl||e.apiUrl||V,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 Pe(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}E();fe();async function wt(){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 Z(o);return{path:de,content:o,size:e.length,md5:n}}async function Ie(t,e,o){if(o.spaDetect===!1||t.some(n=>n.path===de))return t;try{if(await e.checkSPA(t)){let i=await wt();return[...t,i]}}catch{}return t}function $e(t){let{getApi:e,ensureInit:o,processInput:n,clientDefaults:i,hasAuth:s}=t;return{create:async(r,c={})=>{await o();let a=i?Pe(c,i):c;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 l=e(),m=await n(r,a);return m=await Ie(m,l,a),l.deploy(m,a)},list:async()=>(await o(),e().listDeployments()),get:async r=>(await o(),e().getDeployment(r)),set:async(r,c)=>(await o(),e().updateDeploymentTags(r,c.tags)),remove:async r=>{await o(),await e().removeDeployment(r)}}}function Fe(t){let{getApi:e,ensureInit:o}=t;return{set:async(n,i={})=>{await o();let{deployment:s,tags:r}=i;return s===void 0&&r&&r.length>0?e().updateDomainTags(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 Ne(t){let{getApi:e,ensureInit:o}=t;return{get:async()=>(await o(),e().getAccount())}}function Le(t){let{getApi:e,ensureInit:o}=t;return{create:async(n={})=>(await o(),e().createToken(n.ttl,n.tags)),list:async()=>(await o(),e().listTokens()),remove:async n=>{await o(),await e().removeToken(n)}}}var Q=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 _({...e,...o,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=Fe(n),this._account=Ne(n),this._tokens=Le(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=Y(),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}};E();B();Me();X();E();var ge=w(require("mime-db"),1),ye={};for(let t in ge.default){let e=ge.default[t];e&&e.extensions&&e.extensions.forEach(o=>{ye[o]||(ye[o]=t)})}function je(t){let e=t.includes(".")?t.substring(t.lastIndexOf(".")+1).toLowerCase():"";return ye[e]||"application/octet-stream"}async function Ke(t,e,o){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),r=new n,c=[];for(let d of t){let g=je(d.path),C;if(Buffer.isBuffer(d.content))C=new i([d.content],d.path,{type:g});else if(typeof Blob<"u"&&d.content instanceof Blob)C=new i([d.content],d.path,{type:g});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),c.push(d.md5)}r.append("checksums",JSON.stringify(c)),e&&e.length>0&&r.append("tags",JSON.stringify(e)),o&&r.append("via",o);let a=new s(r),l=[];for await(let d of a.encode())l.push(Buffer.from(d));let m=Buffer.concat(l);return{body:m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength),headers:{"Content-Type":a.contentType,"Content-Length":Buffer.byteLength(m).toString()}}}var te=class extends Q{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 ue(e,{})}async loadFullConfig(){try{let e=await Ue(this.clientOptions.configFile),o=ue(this.clientOptions,e);o.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(o.deployToken):o.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(o.apiKey);let n=new _({...this.clientOptions,...o,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let i=await this.http.getConfig();Oe(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(()=>(Ye(),We));return i(n,o)}getDeployBodyCreator(){return Ke}};E();var F=require("fs"),ie=w(require("path"),1);var De=w(require("columnify"),1),u=require("yoctocolors"),Xe=["isCreate"],v=(t,e,o)=>o?e:t(e),T=(t,e,o)=>{console.log(e?JSON.stringify({success:t},null,2)+`
|
|
3
3
|
`:`${v(u.green,t.toLowerCase().replace(/\.$/,""),o)}
|
|
4
4
|
`)},x=(t,e,o)=>{if(e)console.error(JSON.stringify({error:t},null,2)+`
|
|
5
5
|
`);else{let n=v(s=>(0,u.inverse)((0,u.red)(s)),`${v(u.hidden,"[",o)}error${v(u.hidden,"]",o)}`,o),i=v(u.red,t.toLowerCase().replace(/\.$/,""),o);console.error(`${n} ${i}
|