@shipstatic/ship 0.6.4 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/browser.d.ts +2 -2
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +21 -21
- package/dist/cli.cjs.map +1 -1
- package/dist/completions/ship.bash +3 -3
- package/dist/completions/ship.fish +2 -2
- package/dist/completions/ship.zsh +3 -3
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
|
@@ -17,7 +17,7 @@ _ship_completions() {
|
|
|
17
17
|
case "${COMP_WORDS[1]}" in
|
|
18
18
|
"deployments")
|
|
19
19
|
case "${COMP_WORDS[2]}" in
|
|
20
|
-
"
|
|
20
|
+
"upload")
|
|
21
21
|
# File/directory completion for deploy path
|
|
22
22
|
COMPREPLY=( $(compgen -f -- "${current_word}") )
|
|
23
23
|
return
|
|
@@ -29,7 +29,7 @@ _ship_completions() {
|
|
|
29
29
|
;;
|
|
30
30
|
*)
|
|
31
31
|
if [[ ${COMP_CWORD} -eq 2 ]]; then
|
|
32
|
-
completions="list
|
|
32
|
+
completions="list upload get set remove"
|
|
33
33
|
COMPREPLY=( $(compgen -W "${completions}" -- "${current_word}") )
|
|
34
34
|
return
|
|
35
35
|
fi
|
|
@@ -90,7 +90,7 @@ _ship_completions() {
|
|
|
90
90
|
esac
|
|
91
91
|
|
|
92
92
|
# Delegate for commands that expect files
|
|
93
|
-
if [[ "$prev_word" == "
|
|
93
|
+
if [[ "$prev_word" == "upload" || "$prev_word" == "--config" ]]; then
|
|
94
94
|
COMPREPLY=( $(compgen -f -- "${current_word}") )
|
|
95
95
|
return
|
|
96
96
|
fi
|
|
@@ -23,7 +23,7 @@ function __ship_needs_file
|
|
|
23
23
|
set -l cmd (commandline -opc)
|
|
24
24
|
if test (count $cmd) -ge 2
|
|
25
25
|
set -l prev $cmd[-1]
|
|
26
|
-
if test "$prev" = "
|
|
26
|
+
if test "$prev" = "upload" -o "$prev" = "--config"
|
|
27
27
|
return 0
|
|
28
28
|
end
|
|
29
29
|
end
|
|
@@ -55,7 +55,7 @@ complete -c ship -l help -d 'Display help for command'
|
|
|
55
55
|
|
|
56
56
|
# Deployments subcommands
|
|
57
57
|
complete -c ship -f -n '__fish_seen_subcommand_from deployments' -a 'list' -d 'List all deployments'
|
|
58
|
-
complete -c ship -f -n '__fish_seen_subcommand_from deployments' -a '
|
|
58
|
+
complete -c ship -f -n '__fish_seen_subcommand_from deployments' -a 'upload' -d 'Upload deployment from directory'
|
|
59
59
|
complete -c ship -f -n '__fish_seen_subcommand_from deployments' -a 'get' -d 'Show deployment information'
|
|
60
60
|
complete -c ship -f -n '__fish_seen_subcommand_from deployments' -a 'set' -d 'Set deployment labels'
|
|
61
61
|
complete -c ship -f -n '__fish_seen_subcommand_from deployments' -a 'remove' -d 'Delete deployment permanently'
|
|
@@ -27,7 +27,7 @@ if [[ -n ${ZSH_VERSION-} ]]; then
|
|
|
27
27
|
case "${words[2]}" in
|
|
28
28
|
"deployments")
|
|
29
29
|
case "${words[3]}" in
|
|
30
|
-
"
|
|
30
|
+
"upload")
|
|
31
31
|
# File/directory completion for deploy path
|
|
32
32
|
_files
|
|
33
33
|
return
|
|
@@ -38,7 +38,7 @@ if [[ -n ${ZSH_VERSION-} ]]; then
|
|
|
38
38
|
;;
|
|
39
39
|
*)
|
|
40
40
|
if [[ $CURRENT -eq 3 ]]; then
|
|
41
|
-
completions=("list:List all deployments" "
|
|
41
|
+
completions=("list:List all deployments" "upload:Upload deployment from directory" "get:Show deployment information" "set:Set deployment labels" "remove:Delete deployment permanently")
|
|
42
42
|
_describe 'deployments commands' completions
|
|
43
43
|
return
|
|
44
44
|
fi
|
|
@@ -96,7 +96,7 @@ if [[ -n ${ZSH_VERSION-} ]]; then
|
|
|
96
96
|
esac
|
|
97
97
|
|
|
98
98
|
# If the previous command expects a file path, also use file completion.
|
|
99
|
-
if [[ "$prev_word" == "
|
|
99
|
+
if [[ "$prev_word" == "upload" || "$prev_word" == "--config" ]]; then
|
|
100
100
|
_files
|
|
101
101
|
return
|
|
102
102
|
fi
|
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Le=Object.create;var U=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Be=Object.getPrototypeOf,Me=Object.prototype.hasOwnProperty;var A=(n,e)=>()=>(n&&(e=n(n=0)),e);var ve=(n,e)=>{for(var t in e)U(n,t,{get:e[t],enumerable:!0})},Ce=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ue(e))!Me.call(n,o)&&o!==t&&U(n,o,{get:()=>e[o],enumerable:!(i=_e(e,o))||i.enumerable});return n};var w=(n,e,t)=>(t=n!=null?Le(Be(n)):{},Ce(e||!n||!n.__esModule?U(t,"default",{value:n,enumerable:!0}):t,n)),Ke=n=>Ce(U({},"__esModule",{value:!0}),n);function x(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function N(n){let e=n.lastIndexOf(".");if(e===-1||e===n.length-1)return!1;let t=n.slice(e+1).toLowerCase();return we.has(t)}function Ge(n){if(!n.startsWith(T))throw l.validation(`API key must start with "${T}"`);if(n.length!==Z)throw l.validation(`API key must be ${Z} characters total (${T} + ${B} hex chars)`);let e=n.slice(T.length);if(!/^[a-f0-9]{64}$/i.test(e))throw l.validation(`API key must contain ${B} hexadecimal characters after "${T}" prefix`)}function Ye(n){if(!n.startsWith(R))throw l.validation(`Deploy token must start with "${R}"`);if(n.length!==ee)throw l.validation(`Deploy token must be ${ee} characters total (${R} + ${M} hex chars)`);let e=n.slice(R.length);if(!/^[a-f0-9]{64}$/i.test(e))throw l.validation(`Deploy token must contain ${M} hexadecimal characters after "${R}" prefix`)}function We(n){try{let e=new URL(n);if(!["http:","https:"].includes(e.protocol))throw l.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw l.validation("API URL must not contain a path");if(e.search||e.hash)throw l.validation("API URL must not contain query parameters or fragments")}catch(e){throw x(e)?e:l.validation("API URL must be a valid URL")}}function Je(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(n)}function te(n,e){return n.endsWith(`.${e}`)}function Xe(n,e){return!te(n,e)}function Qe(n,e){return te(n,e)?n.slice(0,-(e.length+1)):null}function Ze(n,e){return`https://${n}.${e||"shipstatic.com"}`}function et(n){return`https://${n}`}function it(n){return!n||n.length===0?null:JSON.stringify(n)}function ot(n){if(!n)return[];try{let e=JSON.parse(n);return Array.isArray(e)?e:[]}catch{return[]}}var ze,He,Ve,f,Q,l,we,T,B,Z,je,R,M,ee,qe,K,$,y,tt,nt,D=A(()=>{"use strict";ze={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},He={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Ve={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"};(function(n){n.Validation="validation_failed",n.NotFound="not_found",n.RateLimit="rate_limit_exceeded",n.Authentication="authentication_failed",n.Business="business_logic_error",n.Api="internal_server_error",n.Network="network_error",n.Cancelled="operation_cancelled",n.File="file_error",n.Config="config_error"})(f||(f={}));Q={client:new Set([f.Business,f.Config,f.File,f.Validation]),network:new Set([f.Network]),auth:new Set([f.Authentication])},l=class n extends Error{type;status;details;constructor(e,t,i,o){super(t),this.type=e,this.status=i,this.details=o,this.name="ShipError"}toResponse(){let e=this.type===f.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 n(e.error,e.message,e.status,e.details)}static validation(e,t){return new n(f.Validation,e,400,t)}static notFound(e,t){let i=t?`${e} ${t} not found`:`${e} not found`;return new n(f.NotFound,i,404)}static rateLimit(e="Too many requests"){return new n(f.RateLimit,e,429)}static authentication(e="Authentication required",t){return new n(f.Authentication,e,401,t)}static business(e,t=400){return new n(f.Business,e,t)}static network(e,t){return new n(f.Network,e,void 0,{cause:t})}static cancelled(e){return new n(f.Cancelled,e)}static file(e,t){return new n(f.File,e,void 0,{filePath:t})}static config(e,t){return new n(f.Config,e,void 0,t)}static api(e,t=500){return new n(f.Api,e,t)}static database(e,t=500){return new n(f.Api,e,t)}static storage(e,t=500){return new n(f.Api,e,t)}get filePath(){return this.details?.filePath}isClientError(){return Q.client.has(this.type)}isNetworkError(){return Q.network.has(this.type)}isAuthError(){return Q.auth.has(this.type)}isValidationError(){return this.type===f.Validation}isFileError(){return this.type===f.File}isConfigError(){return this.type===f.Config}isType(e){return this.type===e}};we=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);T="ship-",B=64,Z=T.length+B,je=4,R="token-",M=64,ee=R.length+M,qe={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},K="ship.json";$="https://api.shipstatic.com",y={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};tt={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},nt=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function H(n){ne=n}function P(){if(ne===null)throw l.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ne}var ne,L=A(()=>{"use strict";D();ne=null});function rt(n){oe=n}function at(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function v(){return oe||at()}var oe,F=A(()=>{"use strict";oe=null});async function lt(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let s=Math.ceil(n.size/2097152),a=0,c=new e.ArrayBuffer,r=new FileReader,u=()=>{let p=a*2097152,d=Math.min(p+2097152,n.size);r.readAsArrayBuffer(n.slice(p,d))};r.onload=p=>{let d=p.target?.result;if(!d){i(l.business("Failed to read file chunk"));return}c.append(d),a++,a<s?u():t({md5:c.end()})},r.onerror=()=>{i(l.business("Failed to calculate MD5: FileReader error"))},u()})}async function pt(n){let e=await import("crypto");if(Buffer.isBuffer(n)){let i=e.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let t=await import("fs");return new Promise((i,o)=>{let s=e.createHash("md5"),a=t.createReadStream(n);a.on("error",c=>o(l.business(`Failed to read file for MD5: ${c.message}`))),a.on("data",c=>s.update(c)),a.on("end",()=>i({md5:s.digest("hex")}))})}async function _(n){let e=v();if(e==="browser"){if(!(n instanceof Blob))throw l.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return lt(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw l.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return pt(n)}throw l.business("Unknown or unsupported execution environment for MD5 calculation.")}var j=A(()=>{"use strict";F();D()});function ce(n){return!n||n.length===0?[]:n.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let i=t[t.length-1];if((0,Ie.isJunk)(i))return!1;for(let s of t)if(s!==".well-known"&&(s.startsWith(".")||s.length>255))return!1;let o=t.slice(0,-1);for(let s of o)if(Pe.some(a=>s.toLowerCase()===a.toLowerCase()))return!1;return!0})}var Ie,Pe,ue=A(()=>{"use strict";Ie=require("junk"),Pe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Fe(n){if(!n||n.length===0)return"";let e=n.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(s=>s.split("/").filter(Boolean)),i=[],o=Math.min(...t.map(s=>s.length));for(let s=0;s<o;s++){let a=t[0][s];if(t.every(c=>c[s]===a))i.push(a);else break}return i.join("/")}function Y(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var de=A(()=>{"use strict"});function me(n,e={}){if(e.flatten===!1)return n.map(i=>({path:Y(i),name:fe(i)}));let t=mt(n);return n.map(i=>{let o=Y(i);if(t){let s=t.endsWith("/")?t:`${t}/`;o.startsWith(s)&&(o=o.substring(s.length))}return o||(o=fe(i)),{path:o,name:fe(i)}})}function mt(n){if(!n.length)return"";let t=n.map(s=>Y(s)).map(s=>s.split("/")),i=[],o=Math.min(...t.map(s=>s.length));for(let s=0;s<o-1;s++){let a=t[0][s];if(t.every(c=>c[s]===a))i.push(a);else break}return i.join("/")}function fe(n){return n.split(/[/\\]/).pop()||n}var he=A(()=>{"use strict";de()});function W(n,e=1){if(n===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,o)).toFixed(e))+" "+i[o]}function J(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,i=n.split("/").pop()||n;return t.test(i)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function ht(n,e){let t=[],i=[],o=[];if(n.length===0){let r={file:"(no files)",message:"At least one file must be provided"};return t.push(r),{files:[],validFiles:[],errors:t,warnings:[],canDeploy:!1}}if(n.length>e.maxFilesCount){let r={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${e.maxFilesCount}`};return t.push(r),{files:n.map(u=>({...u,status:y.VALIDATION_FAILED,statusMessage:r.message})),validFiles:[],errors:t,warnings:[],canDeploy:!1}}let s=0;for(let r of n){let u=y.READY,p="Ready for upload",d=r.name?J(r.name):{valid:!1,reason:"File name cannot be empty"};if(r.status===y.PROCESSING_ERROR)u=y.VALIDATION_FAILED,p=r.statusMessage||"File failed during processing",t.push({file:r.name,message:p});else if(r.size===0){u=y.EXCLUDED,p="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:r.name,message:p}),o.push({...r,status:u,statusMessage:p});continue}else r.size<0?(u=y.VALIDATION_FAILED,p="File size must be positive",t.push({file:r.name,message:p})):!r.name||r.name.trim().length===0?(u=y.VALIDATION_FAILED,p="File name cannot be empty",t.push({file:r.name||"(empty)",message:p})):r.name.includes("\0")?(u=y.VALIDATION_FAILED,p="File name contains invalid characters (null byte)",t.push({file:r.name,message:p})):d.valid?N(r.name)?(u=y.VALIDATION_FAILED,p=`File extension not allowed: "${r.name}"`,t.push({file:r.name,message:p})):r.size>e.maxFileSize?(u=y.VALIDATION_FAILED,p=`File size (${W(r.size)}) exceeds limit of ${W(e.maxFileSize)}`,t.push({file:r.name,message:p})):(s+=r.size,s>e.maxTotalSize&&(u=y.VALIDATION_FAILED,p=`Total size would exceed limit of ${W(e.maxTotalSize)}`,t.push({file:r.name,message:p}))):(u=y.VALIDATION_FAILED,p=d.reason||"Invalid file name",t.push({file:r.name,message:p}));o.push({...r,status:u,statusMessage:p})}t.length>0&&(o=o.map(r=>r.status===y.EXCLUDED?r:{...r,status:y.VALIDATION_FAILED,statusMessage:r.status===y.VALIDATION_FAILED?r.statusMessage:"Deployment failed due to validation errors in bundle"}));let a=t.length===0?o.filter(r=>r.status===y.READY):[],c=t.length===0;return{files:o,validFiles:a,errors:t,warnings:i,canDeploy:c}}function be(n){return n.filter(e=>e.status===y.READY)}function yt(n){return be(n).length>0}var ye=A(()=>{"use strict";D()});function ge(n,e){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw l.business(`Security error: Unsafe file path "${n}" for file: ${e}`)}function De(n,e){let t=J(n);if(!t.valid)throw l.business(t.reason||"Invalid file name");if(N(n))throw l.business(`File extension not allowed: "${e}"`)}var Se=A(()=>{"use strict";D();ye()});var ke={};ve(ke,{processFilesForNode:()=>Ee});function Oe(n,e=new Set){let t=[],i=E.realpathSync(n);if(e.has(i))return t;e.add(i);let o=E.readdirSync(n);for(let s of o){let a=S.join(n,s),c=E.statSync(a);if(c.isDirectory()){let r=Oe(a,e);t.push(...r)}else c.isFile()&&t.push(a)}return t}async function Ee(n,e={}){if(v()!=="node")throw l.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(h=>{let g=S.resolve(h);try{return E.statSync(g).isDirectory()?Oe(g):[g]}catch{throw l.file(`Path does not exist: ${h}`,h)}}),i=[...new Set(t)],o=ce(i);if(o.length===0)return[];let s=n.map(h=>S.resolve(h)),a=Fe(s.map(h=>{try{return E.statSync(h).isDirectory()?h:S.dirname(h)}catch{return S.dirname(h)}})),c=o.map(h=>{if(a&&a.length>0){let g=S.relative(a,h);if(g&&typeof g=="string"&&!g.startsWith(".."))return g.replace(/\\/g,"/")}return S.basename(h)}),r=me(c,{flatten:e.pathDetect!==!1}),u=[],p=0,d=P();for(let h=0;h<o.length;h++){let g=o[h],O=r[h].path;try{ge(O,g);let C=E.statSync(g);if(C.size===0)continue;if(De(O,g),C.size>d.maxFileSize)throw l.business(`File ${g} is too large. Maximum allowed size is ${d.maxFileSize/(1024*1024)}MB.`);if(p+=C.size,p>d.maxTotalSize)throw l.business(`Total deploy size is too large. Maximum allowed is ${d.maxTotalSize/(1024*1024)}MB.`);let k=E.readFileSync(g),{md5:$e}=await _(k);u.push({path:O,content:k,size:k.length,md5:$e})}catch(C){if(x(C))throw C;let k=C instanceof Error?C.message:String(C);throw l.file(`Failed to read file "${g}": ${k}`,g)}}if(u.length>d.maxFilesCount)throw l.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return u}var E,S,Ae=A(()=>{"use strict";F();j();ue();Se();D();L();he();de();E=w(require("fs"),1),S=w(require("path"),1)});var gt={};ve(gt,{API_KEY_HEX_LENGTH:()=>B,API_KEY_HINT_LENGTH:()=>je,API_KEY_PREFIX:()=>T,API_KEY_TOTAL_LENGTH:()=>Z,AccountPlan:()=>Ve,ApiHttp:()=>I,AuthMethod:()=>qe,BLOCKED_EXTENSIONS:()=>we,DEFAULT_API:()=>$,DEPLOYMENT_CONFIG_FILENAME:()=>K,DEPLOY_TOKEN_HEX_LENGTH:()=>M,DEPLOY_TOKEN_PREFIX:()=>R,DEPLOY_TOKEN_TOTAL_LENGTH:()=>ee,DeploymentStatus:()=>ze,DomainStatus:()=>He,ErrorType:()=>f,FILE_VALIDATION_STATUS:()=>y,FileValidationStatus:()=>y,JUNK_DIRECTORIES:()=>Pe,LABEL_CONSTRAINTS:()=>tt,LABEL_PATTERN:()=>nt,Ship:()=>X,ShipError:()=>l,__setTestEnvironment:()=>rt,allValidFilesReady:()=>yt,calculateMD5:()=>_,createAccountResource:()=>ae,createDeploymentResource:()=>se,createDomainResource:()=>re,createTokenResource:()=>le,default:()=>Ne,deserializeLabels:()=>ot,extractSubdomain:()=>Qe,filterJunk:()=>ce,formatFileSize:()=>W,generateDeploymentUrl:()=>Ze,generateDomainUrl:()=>et,getCurrentConfig:()=>P,getENV:()=>v,getValidFiles:()=>be,isBlockedExtension:()=>N,isCustomDomain:()=>Xe,isDeployment:()=>Je,isPlatformDomain:()=>te,isShipError:()=>x,loadConfig:()=>G,mergeDeployOptions:()=>ie,optimizeDeployPaths:()=>me,pluralize:()=>ft,processFilesForNode:()=>Ee,resolveConfig:()=>V,serializeLabels:()=>it,setPlatformConfig:()=>H,validateApiKey:()=>Ge,validateApiUrl:()=>We,validateDeployFile:()=>De,validateDeployPath:()=>ge,validateDeployToken:()=>Ye,validateFileName:()=>J,validateFiles:()=>ht});module.exports=Ke(gt);D();var z=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let i=this.handlers.get(e);i&&(i.delete(t),i.size===0&&this.handlers.delete(e))}emit(e,...t){let i=this.handlers.get(e);if(!i)return;let o=Array.from(i);for(let s of o)try{s(...t)}catch(a){i.delete(s),e!=="error"&&setTimeout(()=>{a instanceof Error?this.emit("error",a,String(e)):this.emit("error",new Error(String(a)),String(e))},0)}}transfer(e){this.handlers.forEach((t,i)=>{t.forEach(o=>{e.on(i,o)})})}clear(){this.handlers.clear()}};var m={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},st=3e4,I=class extends z{constructor(e){super(),this.apiUrl=e.apiUrl||$,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??st,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,t,i){let o=this.mergeHeaders(t.headers),{signal:s,cleanup:a}=this.createTimeoutSignal(t.signal),c={...t,headers:o,credentials:o.Authorization?void 0:"include",signal:s};this.emit("request",e,c);try{let r=await fetch(e,c);return a(),r.ok||await this.handleResponseError(r,i),this.emit("response",this.safeClone(r),e),{data:await this.parseResponse(this.safeClone(r)),status:r.status}}catch(r){a();let u=r instanceof Error?r:new Error(String(r));this.emit("error",u,e),this.handleFetchError(r,i)}}async request(e,t,i){let{data:o}=await this.executeRequest(e,t,i);return o}async requestWithStatus(e,t,i){return this.executeRequest(e,t,i)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let t=new AbortController,i=setTimeout(()=>t.abort(),this.timeout);if(e){let o=()=>t.abort();e.addEventListener("abort",o),e.aborted&&t.abort()}return{signal:t.signal,cleanup:()=>clearTimeout(i)}}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,t){let i={};try{if(e.headers.get("content-type")?.includes("application/json")){let a=await e.json();if(a&&typeof a=="object"){let c=a;typeof c.message=="string"&&(i.message=c.message),typeof c.error=="string"&&(i.error=c.error)}}else i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let o=i.message||i.error||`${t} failed`;throw e.status===401?l.authentication(o):l.api(o,e.status)}handleFetchError(e,t){throw x(e)?e:e instanceof Error&&e.name==="AbortError"?l.cancelled(`${t} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?l.network(`${t} failed: ${e.message}`,e):e instanceof Error?l.business(`${t} failed: ${e.message}`):l.business(`${t} failed: Unknown error`)}async deploy(e,t={}){if(!e.length)throw l.business("No files to deploy");for(let a of e)if(!a.md5)throw l.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:i,headers:o}=await this.createDeployBody(e,t.labels,t.via),s={};return t.deployToken?s.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(s.Authorization=`Bearer ${t.apiKey}`),t.caller&&(s["X-Caller"]=t.caller),this.request(`${t.apiUrl||this.apiUrl}${m.DEPLOYMENTS}`,{method:"POST",body:i,headers:{...o,...s},signal:t.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,t){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:t})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,t,i){let o={};t&&(o.deployment=t),i!==void 0&&(o.labels=i);let{data:s,status:a}=await this.requestWithStatus(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Set domain");return{...s,isCreate:a===201}}async listDomains(){return this.request(`${this.apiUrl}${m.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,t){let i={};return e!==void 0&&(i.ttl=e),t!==void 0&&(i.labels=t),this.request(`${this.apiUrl}${m.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${m.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${m.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${m.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${m.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${m.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e){let t=e.find(a=>a.path==="index.html"||a.path==="/index.html");if(!t||t.size>100*1024)return!1;let i;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))i=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)i=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)i=await t.content.text();else return!1;let o={files:e.map(a=>a.path),index:i};return(await this.request(`${this.apiUrl}${m.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"SPA check")).isSPA}};D();L();D();D();function V(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||$,apiKey:n.apiKey!==void 0?n.apiKey:e.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:e.deployToken},i={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(i.apiKey=t.apiKey),t.deployToken!==void 0&&(i.deployToken=t.deployToken),i}function ie(n,e){let t={...n};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.caller===void 0&&e.caller!==void 0&&(t.caller=e.caller),t}D();j();async function ct(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:i}=await _(t);return{path:K,content:t,size:e.length,md5:i}}async function xe(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===K))return n;try{if(await e.checkSPA(n)){let o=await ct();return[...n,o]}}catch{}return n}function se(n){let{getApi:e,ensureInit:t,processInput:i,clientDefaults:o,hasAuth:s}=n;return{create:async(a,c={})=>{await t();let r=o?ie(c,o):c;if(s&&!s()&&!r.deployToken&&!r.apiKey)throw l.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!i)throw l.config("processInput function is not provided.");let u=e(),p=await i(a,r);return p=await xe(p,u,r),u.deploy(p,r)},list:async()=>(await t(),e().listDeployments()),get:async a=>(await t(),e().getDeployment(a)),set:async(a,c)=>(await t(),e().updateDeploymentLabels(a,c.labels)),remove:async a=>{await t(),await e().removeDeployment(a)}}}function re(n){let{getApi:e,ensureInit:t}=n;return{set:async(i,o={})=>(await t(),e().setDomain(i,o.deployment,o.labels)),list:async()=>(await t(),e().listDomains()),get:async i=>(await t(),e().getDomain(i)),remove:async i=>{await t(),await e().removeDomain(i)},verify:async i=>(await t(),e().verifyDomain(i)),validate:async i=>(await t(),e().validateDomain(i)),dns:async i=>(await t(),e().getDomainDns(i)),records:async i=>(await t(),e().getDomainRecords(i)),share:async i=>(await t(),e().getDomainShare(i))}}function ae(n){let{getApi:e,ensureInit:t}=n;return{get:async()=>(await t(),e().getAccount())}}function le(n){let{getApi:e,ensureInit:t}=n;return{create:async(i={})=>(await t(),e().createToken(i.ttl,i.labels)),list:async()=>(await t(),e().listTokens()),remove:async i=>{await t(),await e().removeToken(i)}}}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 t=this.resolveInitialConfig(e);this.http=new I({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=se({...i,processInput:(o,s)=>this.processInput(o,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=re(i),this._account=ae(i),this._tokens=le(i)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=P(),this._config)}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}setDeployToken(e){if(!e||typeof e!="string")throw l.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 l.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}};D();F();var b=require("zod");D();F();var pe="ship",ut=b.z.object({apiUrl:b.z.string().url().optional(),apiKey:b.z.string().optional(),deployToken:b.z.string().optional()}).strict();function Te(n){try{return ut.parse(n)}catch(e){if(e instanceof b.z.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw l.config(`Configuration validation failed${i}: ${t.message}`)}throw l.config("Configuration validation failed")}}async function dt(n){try{if(v()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(pe,{searchPlaces:[`.${pe}rc`,"package.json",`${t.homedir()}/.${pe}rc`],stopDir:t.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return Te(o.config)}catch(e){if(x(e))throw e}return{}}async function G(n){if(v()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await dt(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Te(i)}L();D();async function Re(n,e,t){let{FormData:i,File:o}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),a=new i,c=[];for(let d of n){if(!Buffer.isBuffer(d.content)&&!(typeof Blob<"u"&&d.content instanceof Blob))throw l.file(`Unsupported file.content type for Node.js: ${d.path}`,d.path);if(!d.md5)throw l.file(`File missing md5 checksum: ${d.path}`,d.path);let h=new o([d.content],d.path,{type:"application/octet-stream"});a.append("files[]",h),c.push(d.md5)}a.append("checksums",JSON.stringify(c)),e&&e.length>0&&a.append("labels",JSON.stringify(e)),t&&a.append("via",t);let r=new s(a),u=[];for await(let d of r.encode())u.push(Buffer.from(d));let p=Buffer.concat(u);return{body:p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength),headers:{"Content-Type":r.contentType,"Content-Length":Buffer.byteLength(p).toString()}}}j();function ft(n,e,t,i=!0){let o=n===1?e:t;return i?`${n} ${o}`:o}ue();he();F();ye();Se();D();L();Ae();var X=class extends q{constructor(e={}){if(v()!=="node")throw l.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return V(e,{})}async loadFullConfig(){try{let e=await G(this.clientOptions.configFile),t=V(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let i=new I({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();H(o)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){let i=typeof e=="string"?[e]:e;if(!Array.isArray(i)||!i.every(s=>typeof s=="string"))throw l.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw l.business("No files to deploy.");let{processFilesForNode:o}=await Promise.resolve().then(()=>(Ae(),ke));return o(i,t)}getDeployBodyCreator(){return Re}},Ne=X;0&&(module.exports={API_KEY_HEX_LENGTH,API_KEY_HINT_LENGTH,API_KEY_PREFIX,API_KEY_TOTAL_LENGTH,AccountPlan,ApiHttp,AuthMethod,BLOCKED_EXTENSIONS,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_TOKEN_HEX_LENGTH,DEPLOY_TOKEN_PREFIX,DEPLOY_TOKEN_TOTAL_LENGTH,DeploymentStatus,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,Ship,ShipError,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getCurrentConfig,getENV,getValidFiles,isBlockedExtension,isCustomDomain,isDeployment,isPlatformDomain,isShipError,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,serializeLabels,setPlatformConfig,validateApiKey,validateApiUrl,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles});
|
|
1
|
+
"use strict";var Le=Object.create;var U=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var Ue=Object.getOwnPropertyNames;var Be=Object.getPrototypeOf,Me=Object.prototype.hasOwnProperty;var A=(n,e)=>()=>(n&&(e=n(n=0)),e);var ve=(n,e)=>{for(var t in e)U(n,t,{get:e[t],enumerable:!0})},Ce=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ue(e))!Me.call(n,o)&&o!==t&&U(n,o,{get:()=>e[o],enumerable:!(i=_e(e,o))||i.enumerable});return n};var w=(n,e,t)=>(t=n!=null?Le(Be(n)):{},Ce(e||!n||!n.__esModule?U(t,"default",{value:n,enumerable:!0}):t,n)),Ke=n=>Ce(U({},"__esModule",{value:!0}),n);function x(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function N(n){let e=n.lastIndexOf(".");if(e===-1||e===n.length-1)return!1;let t=n.slice(e+1).toLowerCase();return we.has(t)}function Ge(n){if(!n.startsWith(T))throw l.validation(`API key must start with "${T}"`);if(n.length!==Z)throw l.validation(`API key must be ${Z} characters total (${T} + ${B} hex chars)`);let e=n.slice(T.length);if(!/^[a-f0-9]{64}$/i.test(e))throw l.validation(`API key must contain ${B} hexadecimal characters after "${T}" prefix`)}function Ye(n){if(!n.startsWith(R))throw l.validation(`Deploy token must start with "${R}"`);if(n.length!==ee)throw l.validation(`Deploy token must be ${ee} characters total (${R} + ${M} hex chars)`);let e=n.slice(R.length);if(!/^[a-f0-9]{64}$/i.test(e))throw l.validation(`Deploy token must contain ${M} hexadecimal characters after "${R}" prefix`)}function We(n){try{let e=new URL(n);if(!["http:","https:"].includes(e.protocol))throw l.validation("API URL must use http:// or https:// protocol");if(e.pathname!=="/"&&e.pathname!=="")throw l.validation("API URL must not contain a path");if(e.search||e.hash)throw l.validation("API URL must not contain query parameters or fragments")}catch(e){throw x(e)?e:l.validation("API URL must be a valid URL")}}function Je(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}$/i.test(n)}function te(n,e){return n.endsWith(`.${e}`)}function Xe(n,e){return!te(n,e)}function Qe(n,e){return te(n,e)?n.slice(0,-(e.length+1)):null}function Ze(n,e){return`https://${n}.${e||"shipstatic.com"}`}function et(n){return`https://${n}`}function it(n){return!n||n.length===0?null:JSON.stringify(n)}function ot(n){if(!n)return[];try{let e=JSON.parse(n);return Array.isArray(e)?e:[]}catch{return[]}}var ze,He,Ve,f,Q,l,we,T,B,Z,je,R,M,ee,qe,K,$,y,tt,nt,D=A(()=>{"use strict";ze={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},He={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Ve={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"};(function(n){n.Validation="validation_failed",n.NotFound="not_found",n.RateLimit="rate_limit_exceeded",n.Authentication="authentication_failed",n.Business="business_logic_error",n.Api="internal_server_error",n.Network="network_error",n.Cancelled="operation_cancelled",n.File="file_error",n.Config="config_error"})(f||(f={}));Q={client:new Set([f.Business,f.Config,f.File,f.Validation]),network:new Set([f.Network]),auth:new Set([f.Authentication])},l=class n extends Error{type;status;details;constructor(e,t,i,o){super(t),this.type=e,this.status=i,this.details=o,this.name="ShipError"}toResponse(){let e=this.type===f.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 n(e.error,e.message,e.status,e.details)}static validation(e,t){return new n(f.Validation,e,400,t)}static notFound(e,t){let i=t?`${e} ${t} not found`:`${e} not found`;return new n(f.NotFound,i,404)}static rateLimit(e="Too many requests"){return new n(f.RateLimit,e,429)}static authentication(e="Authentication required",t){return new n(f.Authentication,e,401,t)}static business(e,t=400){return new n(f.Business,e,t)}static network(e,t){return new n(f.Network,e,void 0,{cause:t})}static cancelled(e){return new n(f.Cancelled,e)}static file(e,t){return new n(f.File,e,void 0,{filePath:t})}static config(e,t){return new n(f.Config,e,void 0,t)}static api(e,t=500){return new n(f.Api,e,t)}static database(e,t=500){return new n(f.Api,e,t)}static storage(e,t=500){return new n(f.Api,e,t)}get filePath(){return this.details?.filePath}isClientError(){return Q.client.has(this.type)}isNetworkError(){return Q.network.has(this.type)}isAuthError(){return Q.auth.has(this.type)}isValidationError(){return this.type===f.Validation}isFileError(){return this.type===f.File}isConfigError(){return this.type===f.Config}isType(e){return this.type===e}};we=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);T="ship-",B=64,Z=T.length+B,je=4,R="token-",M=64,ee=R.length+M,qe={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},K="ship.json";$="https://api.shipstatic.com",y={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};tt={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},nt=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/});function H(n){ne=n}function P(){if(ne===null)throw l.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ne}var ne,L=A(()=>{"use strict";D();ne=null});function rt(n){oe=n}function at(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function v(){return oe||at()}var oe,F=A(()=>{"use strict";oe=null});async function lt(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let s=Math.ceil(n.size/2097152),a=0,c=new e.ArrayBuffer,r=new FileReader,u=()=>{let p=a*2097152,d=Math.min(p+2097152,n.size);r.readAsArrayBuffer(n.slice(p,d))};r.onload=p=>{let d=p.target?.result;if(!d){i(l.business("Failed to read file chunk"));return}c.append(d),a++,a<s?u():t({md5:c.end()})},r.onerror=()=>{i(l.business("Failed to calculate MD5: FileReader error"))},u()})}async function pt(n){let e=await import("crypto");if(Buffer.isBuffer(n)){let i=e.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let t=await import("fs");return new Promise((i,o)=>{let s=e.createHash("md5"),a=t.createReadStream(n);a.on("error",c=>o(l.business(`Failed to read file for MD5: ${c.message}`))),a.on("data",c=>s.update(c)),a.on("end",()=>i({md5:s.digest("hex")}))})}async function _(n){let e=v();if(e==="browser"){if(!(n instanceof Blob))throw l.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return lt(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw l.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return pt(n)}throw l.business("Unknown or unsupported execution environment for MD5 calculation.")}var j=A(()=>{"use strict";F();D()});function ce(n){return!n||n.length===0?[]:n.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let i=t[t.length-1];if((0,Ie.isJunk)(i))return!1;for(let s of t)if(s!==".well-known"&&(s.startsWith(".")||s.length>255))return!1;let o=t.slice(0,-1);for(let s of o)if(Pe.some(a=>s.toLowerCase()===a.toLowerCase()))return!1;return!0})}var Ie,Pe,ue=A(()=>{"use strict";Ie=require("junk"),Pe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Fe(n){if(!n||n.length===0)return"";let e=n.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(s=>s.split("/").filter(Boolean)),i=[],o=Math.min(...t.map(s=>s.length));for(let s=0;s<o;s++){let a=t[0][s];if(t.every(c=>c[s]===a))i.push(a);else break}return i.join("/")}function Y(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var de=A(()=>{"use strict"});function me(n,e={}){if(e.flatten===!1)return n.map(i=>({path:Y(i),name:fe(i)}));let t=mt(n);return n.map(i=>{let o=Y(i);if(t){let s=t.endsWith("/")?t:`${t}/`;o.startsWith(s)&&(o=o.substring(s.length))}return o||(o=fe(i)),{path:o,name:fe(i)}})}function mt(n){if(!n.length)return"";let t=n.map(s=>Y(s)).map(s=>s.split("/")),i=[],o=Math.min(...t.map(s=>s.length));for(let s=0;s<o-1;s++){let a=t[0][s];if(t.every(c=>c[s]===a))i.push(a);else break}return i.join("/")}function fe(n){return n.split(/[/\\]/).pop()||n}var he=A(()=>{"use strict";de()});function W(n,e=1){if(n===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,o)).toFixed(e))+" "+i[o]}function J(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,i=n.split("/").pop()||n;return t.test(i)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function ht(n,e){let t=[],i=[],o=[];if(n.length===0){let r={file:"(no files)",message:"At least one file must be provided"};return t.push(r),{files:[],validFiles:[],errors:t,warnings:[],canDeploy:!1}}if(n.length>e.maxFilesCount){let r={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${e.maxFilesCount}`};return t.push(r),{files:n.map(u=>({...u,status:y.VALIDATION_FAILED,statusMessage:r.message})),validFiles:[],errors:t,warnings:[],canDeploy:!1}}let s=0;for(let r of n){let u=y.READY,p="Ready for upload",d=r.name?J(r.name):{valid:!1,reason:"File name cannot be empty"};if(r.status===y.PROCESSING_ERROR)u=y.VALIDATION_FAILED,p=r.statusMessage||"File failed during processing",t.push({file:r.name,message:p});else if(r.size===0){u=y.EXCLUDED,p="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:r.name,message:p}),o.push({...r,status:u,statusMessage:p});continue}else r.size<0?(u=y.VALIDATION_FAILED,p="File size must be positive",t.push({file:r.name,message:p})):!r.name||r.name.trim().length===0?(u=y.VALIDATION_FAILED,p="File name cannot be empty",t.push({file:r.name||"(empty)",message:p})):r.name.includes("\0")?(u=y.VALIDATION_FAILED,p="File name contains invalid characters (null byte)",t.push({file:r.name,message:p})):d.valid?N(r.name)?(u=y.VALIDATION_FAILED,p=`File extension not allowed: "${r.name}"`,t.push({file:r.name,message:p})):r.size>e.maxFileSize?(u=y.VALIDATION_FAILED,p=`File size (${W(r.size)}) exceeds limit of ${W(e.maxFileSize)}`,t.push({file:r.name,message:p})):(s+=r.size,s>e.maxTotalSize&&(u=y.VALIDATION_FAILED,p=`Total size would exceed limit of ${W(e.maxTotalSize)}`,t.push({file:r.name,message:p}))):(u=y.VALIDATION_FAILED,p=d.reason||"Invalid file name",t.push({file:r.name,message:p}));o.push({...r,status:u,statusMessage:p})}t.length>0&&(o=o.map(r=>r.status===y.EXCLUDED?r:{...r,status:y.VALIDATION_FAILED,statusMessage:r.status===y.VALIDATION_FAILED?r.statusMessage:"Deployment failed due to validation errors in bundle"}));let a=t.length===0?o.filter(r=>r.status===y.READY):[],c=t.length===0;return{files:o,validFiles:a,errors:t,warnings:i,canDeploy:c}}function be(n){return n.filter(e=>e.status===y.READY)}function yt(n){return be(n).length>0}var ye=A(()=>{"use strict";D()});function ge(n,e){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw l.business(`Security error: Unsafe file path "${n}" for file: ${e}`)}function De(n,e){let t=J(n);if(!t.valid)throw l.business(t.reason||"Invalid file name");if(N(n))throw l.business(`File extension not allowed: "${e}"`)}var Se=A(()=>{"use strict";D();ye()});var ke={};ve(ke,{processFilesForNode:()=>Ee});function Oe(n,e=new Set){let t=[],i=E.realpathSync(n);if(e.has(i))return t;e.add(i);let o=E.readdirSync(n);for(let s of o){let a=S.join(n,s),c=E.statSync(a);if(c.isDirectory()){let r=Oe(a,e);t.push(...r)}else c.isFile()&&t.push(a)}return t}async function Ee(n,e={}){if(v()!=="node")throw l.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(h=>{let g=S.resolve(h);try{return E.statSync(g).isDirectory()?Oe(g):[g]}catch{throw l.file(`Path does not exist: ${h}`,h)}}),i=[...new Set(t)],o=ce(i);if(o.length===0)return[];let s=n.map(h=>S.resolve(h)),a=Fe(s.map(h=>{try{return E.statSync(h).isDirectory()?h:S.dirname(h)}catch{return S.dirname(h)}})),c=o.map(h=>{if(a&&a.length>0){let g=S.relative(a,h);if(g&&typeof g=="string"&&!g.startsWith(".."))return g.replace(/\\/g,"/")}return S.basename(h)}),r=me(c,{flatten:e.pathDetect!==!1}),u=[],p=0,d=P();for(let h=0;h<o.length;h++){let g=o[h],O=r[h].path;try{ge(O,g);let C=E.statSync(g);if(C.size===0)continue;if(De(O,g),C.size>d.maxFileSize)throw l.business(`File ${g} is too large. Maximum allowed size is ${d.maxFileSize/(1024*1024)}MB.`);if(p+=C.size,p>d.maxTotalSize)throw l.business(`Total deploy size is too large. Maximum allowed is ${d.maxTotalSize/(1024*1024)}MB.`);let k=E.readFileSync(g),{md5:$e}=await _(k);u.push({path:O,content:k,size:k.length,md5:$e})}catch(C){if(x(C))throw C;let k=C instanceof Error?C.message:String(C);throw l.file(`Failed to read file "${g}": ${k}`,g)}}if(u.length>d.maxFilesCount)throw l.business(`Too many files to deploy. Maximum allowed is ${d.maxFilesCount} files.`);return u}var E,S,Ae=A(()=>{"use strict";F();j();ue();Se();D();L();he();de();E=w(require("fs"),1),S=w(require("path"),1)});var gt={};ve(gt,{API_KEY_HEX_LENGTH:()=>B,API_KEY_HINT_LENGTH:()=>je,API_KEY_PREFIX:()=>T,API_KEY_TOTAL_LENGTH:()=>Z,AccountPlan:()=>Ve,ApiHttp:()=>I,AuthMethod:()=>qe,BLOCKED_EXTENSIONS:()=>we,DEFAULT_API:()=>$,DEPLOYMENT_CONFIG_FILENAME:()=>K,DEPLOY_TOKEN_HEX_LENGTH:()=>M,DEPLOY_TOKEN_PREFIX:()=>R,DEPLOY_TOKEN_TOTAL_LENGTH:()=>ee,DeploymentStatus:()=>ze,DomainStatus:()=>He,ErrorType:()=>f,FILE_VALIDATION_STATUS:()=>y,FileValidationStatus:()=>y,JUNK_DIRECTORIES:()=>Pe,LABEL_CONSTRAINTS:()=>tt,LABEL_PATTERN:()=>nt,Ship:()=>X,ShipError:()=>l,__setTestEnvironment:()=>rt,allValidFilesReady:()=>yt,calculateMD5:()=>_,createAccountResource:()=>ae,createDeploymentResource:()=>se,createDomainResource:()=>re,createTokenResource:()=>le,default:()=>Ne,deserializeLabels:()=>ot,extractSubdomain:()=>Qe,filterJunk:()=>ce,formatFileSize:()=>W,generateDeploymentUrl:()=>Ze,generateDomainUrl:()=>et,getCurrentConfig:()=>P,getENV:()=>v,getValidFiles:()=>be,isBlockedExtension:()=>N,isCustomDomain:()=>Xe,isDeployment:()=>Je,isPlatformDomain:()=>te,isShipError:()=>x,loadConfig:()=>G,mergeDeployOptions:()=>ie,optimizeDeployPaths:()=>me,pluralize:()=>ft,processFilesForNode:()=>Ee,resolveConfig:()=>V,serializeLabels:()=>it,setPlatformConfig:()=>H,validateApiKey:()=>Ge,validateApiUrl:()=>We,validateDeployFile:()=>De,validateDeployPath:()=>ge,validateDeployToken:()=>Ye,validateFileName:()=>J,validateFiles:()=>ht});module.exports=Ke(gt);D();var z=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let i=this.handlers.get(e);i&&(i.delete(t),i.size===0&&this.handlers.delete(e))}emit(e,...t){let i=this.handlers.get(e);if(!i)return;let o=Array.from(i);for(let s of o)try{s(...t)}catch(a){i.delete(s),e!=="error"&&setTimeout(()=>{a instanceof Error?this.emit("error",a,String(e)):this.emit("error",new Error(String(a)),String(e))},0)}}transfer(e){this.handlers.forEach((t,i)=>{t.forEach(o=>{e.on(i,o)})})}clear(){this.handlers.clear()}};var m={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",CONFIG:"/config",PING:"/ping",SPA_CHECK:"/spa-check"},st=3e4,I=class extends z{constructor(e){super(),this.apiUrl=e.apiUrl||$,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??st,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async executeRequest(e,t,i){let o=this.mergeHeaders(t.headers),{signal:s,cleanup:a}=this.createTimeoutSignal(t.signal),c={...t,headers:o,credentials:o.Authorization?void 0:"include",signal:s};this.emit("request",e,c);try{let r=await fetch(e,c);return a(),r.ok||await this.handleResponseError(r,i),this.emit("response",this.safeClone(r),e),{data:await this.parseResponse(this.safeClone(r)),status:r.status}}catch(r){a();let u=r instanceof Error?r:new Error(String(r));this.emit("error",u,e),this.handleFetchError(r,i)}}async request(e,t,i){let{data:o}=await this.executeRequest(e,t,i);return o}async requestWithStatus(e,t,i){return this.executeRequest(e,t,i)}mergeHeaders(e={}){return{...e,...this.getAuthHeadersCallback()}}createTimeoutSignal(e){let t=new AbortController,i=setTimeout(()=>t.abort(),this.timeout);if(e){let o=()=>t.abort();e.addEventListener("abort",o),e.aborted&&t.abort()}return{signal:t.signal,cleanup:()=>clearTimeout(i)}}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,t){let i={};try{if(e.headers.get("content-type")?.includes("application/json")){let a=await e.json();if(a&&typeof a=="object"){let c=a;typeof c.message=="string"&&(i.message=c.message),typeof c.error=="string"&&(i.error=c.error)}}else i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let o=i.message||i.error||`${t} failed`;throw e.status===401?l.authentication(o):l.api(o,e.status)}handleFetchError(e,t){throw x(e)?e:e instanceof Error&&e.name==="AbortError"?l.cancelled(`${t} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?l.network(`${t} failed: ${e.message}`,e):e instanceof Error?l.business(`${t} failed: ${e.message}`):l.business(`${t} failed: Unknown error`)}async deploy(e,t={}){if(!e.length)throw l.business("No files to deploy");for(let a of e)if(!a.md5)throw l.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:i,headers:o}=await this.createDeployBody(e,t.labels,t.via),s={};return t.deployToken?s.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(s.Authorization=`Bearer ${t.apiKey}`),t.caller&&(s["X-Caller"]=t.caller),this.request(`${t.apiUrl||this.apiUrl}${m.DEPLOYMENTS}`,{method:"POST",body:i,headers:{...o,...s},signal:t.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,t){return this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:t})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${m.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,t,i){let o={};t&&(o.deployment=t),i!==void 0&&(o.labels=i);let{data:s,status:a}=await this.requestWithStatus(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"Set domain");return{...s,isCreate:a===201}}async listDomains(){return this.request(`${this.apiUrl}${m.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${m.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${m.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,t){let i={};return e!==void 0&&(i.ttl=e),t!==void 0&&(i.labels=t),this.request(`${this.apiUrl}${m.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${m.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${m.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${m.ACCOUNT}`,{method:"GET"},"Get account")}async getConfig(){return this.request(`${this.apiUrl}${m.CONFIG}`,{method:"GET"},"Get config")}async ping(){return(await this.request(`${this.apiUrl}${m.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e){let t=e.find(a=>a.path==="index.html"||a.path==="/index.html");if(!t||t.size>100*1024)return!1;let i;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))i=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)i=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)i=await t.content.text();else return!1;let o={files:e.map(a=>a.path),index:i};return(await this.request(`${this.apiUrl}${m.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)},"SPA check")).isSPA}};D();L();D();D();function V(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||$,apiKey:n.apiKey!==void 0?n.apiKey:e.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:e.deployToken},i={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(i.apiKey=t.apiKey),t.deployToken!==void 0&&(i.deployToken=t.deployToken),i}function ie(n,e){let t={...n};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.caller===void 0&&e.caller!==void 0&&(t.caller=e.caller),t}D();j();async function ct(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:i}=await _(t);return{path:K,content:t,size:e.length,md5:i}}async function xe(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===K))return n;try{if(await e.checkSPA(n)){let o=await ct();return[...n,o]}}catch{}return n}function se(n){let{getApi:e,ensureInit:t,processInput:i,clientDefaults:o,hasAuth:s}=n;return{upload:async(a,c={})=>{await t();let r=o?ie(c,o):c;if(s&&!s()&&!r.deployToken&&!r.apiKey)throw l.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!i)throw l.config("processInput function is not provided.");let u=e(),p=await i(a,r);return p=await xe(p,u,r),u.deploy(p,r)},list:async()=>(await t(),e().listDeployments()),get:async a=>(await t(),e().getDeployment(a)),set:async(a,c)=>(await t(),e().updateDeploymentLabels(a,c.labels)),remove:async a=>{await t(),await e().removeDeployment(a)}}}function re(n){let{getApi:e,ensureInit:t}=n;return{set:async(i,o={})=>(await t(),e().setDomain(i,o.deployment,o.labels)),list:async()=>(await t(),e().listDomains()),get:async i=>(await t(),e().getDomain(i)),remove:async i=>{await t(),await e().removeDomain(i)},verify:async i=>(await t(),e().verifyDomain(i)),validate:async i=>(await t(),e().validateDomain(i)),dns:async i=>(await t(),e().getDomainDns(i)),records:async i=>(await t(),e().getDomainRecords(i)),share:async i=>(await t(),e().getDomainShare(i))}}function ae(n){let{getApi:e,ensureInit:t}=n;return{get:async()=>(await t(),e().getAccount())}}function le(n){let{getApi:e,ensureInit:t}=n;return{create:async(i={})=>(await t(),e().createToken(i.ttl,i.labels)),list:async()=>(await t(),e().listTokens()),remove:async i=>{await t(),await e().removeToken(i)}}}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 t=this.resolveInitialConfig(e);this.http=new I({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let i={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=se({...i,processInput:(o,s)=>this.processInput(o,s),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=re(i),this._account=ae(i),this._tokens=le(i)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.upload(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=P(),this._config)}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}setDeployToken(e){if(!e||typeof e!="string")throw l.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 l.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}};D();F();var b=require("zod");D();F();var pe="ship",ut=b.z.object({apiUrl:b.z.string().url().optional(),apiKey:b.z.string().optional(),deployToken:b.z.string().optional()}).strict();function Te(n){try{return ut.parse(n)}catch(e){if(e instanceof b.z.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw l.config(`Configuration validation failed${i}: ${t.message}`)}throw l.config("Configuration validation failed")}}async function dt(n){try{if(v()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(pe,{searchPlaces:[`.${pe}rc`,"package.json",`${t.homedir()}/.${pe}rc`],stopDir:t.homedir()}),o;if(n?o=i.load(n):o=i.search(),o&&o.config)return Te(o.config)}catch(e){if(x(e))throw e}return{}}async function G(n){if(v()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await dt(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Te(i)}L();D();async function Re(n,e,t){let{FormData:i,File:o}=await import("formdata-node"),{FormDataEncoder:s}=await import("form-data-encoder"),a=new i,c=[];for(let d of n){if(!Buffer.isBuffer(d.content)&&!(typeof Blob<"u"&&d.content instanceof Blob))throw l.file(`Unsupported file.content type for Node.js: ${d.path}`,d.path);if(!d.md5)throw l.file(`File missing md5 checksum: ${d.path}`,d.path);let h=new o([d.content],d.path,{type:"application/octet-stream"});a.append("files[]",h),c.push(d.md5)}a.append("checksums",JSON.stringify(c)),e&&e.length>0&&a.append("labels",JSON.stringify(e)),t&&a.append("via",t);let r=new s(a),u=[];for await(let d of r.encode())u.push(Buffer.from(d));let p=Buffer.concat(u);return{body:p.buffer.slice(p.byteOffset,p.byteOffset+p.byteLength),headers:{"Content-Type":r.contentType,"Content-Length":Buffer.byteLength(p).toString()}}}j();function ft(n,e,t,i=!0){let o=n===1?e:t;return i?`${n} ${o}`:o}ue();he();F();ye();Se();D();L();Ae();var X=class extends q{constructor(e={}){if(v()!=="node")throw l.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return V(e,{})}async loadFullConfig(){try{let e=await G(this.clientOptions.configFile),t=V(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let i=new I({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(i);let o=await this.http.getConfig();H(o)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){let i=typeof e=="string"?[e]:e;if(!Array.isArray(i)||!i.every(s=>typeof s=="string"))throw l.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw l.business("No files to deploy.");let{processFilesForNode:o}=await Promise.resolve().then(()=>(Ae(),ke));return o(i,t)}getDeployBodyCreator(){return Re}},Ne=X;0&&(module.exports={API_KEY_HEX_LENGTH,API_KEY_HINT_LENGTH,API_KEY_PREFIX,API_KEY_TOTAL_LENGTH,AccountPlan,ApiHttp,AuthMethod,BLOCKED_EXTENSIONS,DEFAULT_API,DEPLOYMENT_CONFIG_FILENAME,DEPLOY_TOKEN_HEX_LENGTH,DEPLOY_TOKEN_PREFIX,DEPLOY_TOKEN_TOTAL_LENGTH,DeploymentStatus,DomainStatus,ErrorType,FILE_VALIDATION_STATUS,FileValidationStatus,JUNK_DIRECTORIES,LABEL_CONSTRAINTS,LABEL_PATTERN,Ship,ShipError,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,deserializeLabels,extractSubdomain,filterJunk,formatFileSize,generateDeploymentUrl,generateDomainUrl,getCurrentConfig,getENV,getValidFiles,isBlockedExtension,isCustomDomain,isDeployment,isPlatformDomain,isShipError,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,serializeLabels,setPlatformConfig,validateApiKey,validateApiUrl,validateDeployFile,validateDeployPath,validateDeployToken,validateFileName,validateFiles});
|
|
2
2
|
|
|
3
3
|
// Ship SDK: Enable axios-style CommonJS imports
|
|
4
4
|
const originalExports = module.exports;
|