UNPKG

@hotglue/cli

Version:

hotglue CLI tools

34 lines 104 kB
#!/usr/bin/env node "use strict";var e=require("fs"),t=require("path"),n=require("os"),o=require("yargs"),s=require("util");require("assert");var r=require("url"),a=require("fs/promises"),i=require("cosmiconfig"),c=require("chalk"),l=require("aws-sdk"),d=require("debug"),u=require("yaml"),f=require("cli-table"),p=require("ora"),g=require("micromatch"),y=require("axios");require("progress");var h=require("node:fs/promises"),m=require("crypto"),b="undefined"!=typeof document?document.currentScript:null;function w(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var $,v,j,k,_,E,x,S={};function O(){if($)return S;$=1;const o=e,s=t,r=n;function a(e){console.log(`[dotenv][DEBUG] ${e}`)}const i=/^\s*([\w.-]+)\s*=\s*("[^"]*"|'[^']*'|[^#]*)?(\s*|\s*#.*)?$/,c=/\\n/g,l=/\r\n|\n|\r/;function d(e,t){const n=Boolean(t&&t.debug),o={};return e.toString().split(l).forEach(function(e,t){const s=e.match(i);if(null!=s){const e=s[1];let t=s[2]||"";const n=t.length-1,r='"'===t[0]&&'"'===t[n];"'"===t[0]&&"'"===t[n]||r?(t=t.substring(1,n),r&&(t=t.replace(c,"\n"))):t=t.trim(),o[e]=t}else if(n){const n=e.trim();n.length&&"#"!==n[0]&&a(`Failed to match key and value when parsing line ${t+1}: ${e}`)}}),o}return S.config=function(e){let t=s.resolve(process.cwd(),".env"),n="utf8";const i=Boolean(e&&e.debug),c=Boolean(e&&e.override);var l;e&&(null!=e.path&&(t="~"===(l=e.path)[0]?s.join(r.homedir(),l.slice(1)):l),null!=e.encoding&&(n=e.encoding));try{const e=d(o.readFileSync(t,{encoding:n}),{debug:i});return Object.keys(e).forEach(function(t){Object.prototype.hasOwnProperty.call(process.env,t)?(!0===c&&(process.env[t]=e[t]),i&&a(!0===c?`"${t}" is already defined in \`process.env\` and WAS overwritten`:`"${t}" is already defined in \`process.env\` and was NOT overwritten`)):process.env[t]=e[t]}),{parsed:e}}catch(e){return i&&a(`Failed to load ${t} ${e.message}`),{error:e}}},S.parse=d,S}function I(){return process.versions.electron&&!process.defaultApp?0:1} /** * @license * Copyright (c) 2016, Contributors * SPDX-License-Identifier: ISC */ function T(e){if(e!==e.toLowerCase()&&e!==e.toUpperCase()||(e=e.toLowerCase()),-1===e.indexOf("-")&&-1===e.indexOf("_"))return e;{let t="",n=!1;const o=e.match(/^-+/);for(let s=o?o[0].length:0;s<e.length;s++){let o=e.charAt(s);n&&(n=!1,o=o.toUpperCase()),0===s||"-"!==o&&"_"!==o?"-"!==o&&"_"!==o&&(t+=o):n=!0}return t}} /** * @license * Copyright (c) 2016, Contributors * SPDX-License-Identifier: ISC */ let F;E||(E=1,O().config(Object.assign({},function(){if(j)return v;j=1;const e={};return null!=process.env.DOTENV_CONFIG_ENCODING&&(e.encoding=process.env.DOTENV_CONFIG_ENCODING),null!=process.env.DOTENV_CONFIG_PATH&&(e.path=process.env.DOTENV_CONFIG_PATH),null!=process.env.DOTENV_CONFIG_DEBUG&&(e.debug=process.env.DOTENV_CONFIG_DEBUG),null!=process.env.DOTENV_CONFIG_OVERRIDE&&(e.override=process.env.DOTENV_CONFIG_OVERRIDE),v=e}(),function(){if(_)return k;_=1;const e=/^dotenv_config_(encoding|path|debug|override)=(.+)$/;return k=function(t){return t.reduce(function(t,n){const o=n.match(e);return o&&(t[o[1]]=o[2]),t},{})}}()(process.argv)))),function(e){e.BOOLEAN="boolean",e.STRING="string",e.NUMBER="number",e.ARRAY="array"}(x||(x={}));function A(e){return void 0!==e?e+1:1}function U(e){return"__proto__"===e?"___proto___":e} /** * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js * CJS and ESM environments. * * @license * Copyright (c) 2016, Contributors * SPDX-License-Identifier: ISC */ const N=process&&process.env&&process.env.YARGS_MIN_NODE_VERSION?Number(process.env.YARGS_MIN_NODE_VERSION):12;if(process&&process.version){if(Number(process.version.match(/v([^.]+)/)[1])<N)throw Error(`yargs parser supports a minimum Node.js version of ${N}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`)}const D=process?process.env:{};new class{constructor(e){F=e}parse(e,t){const n=Object.assign({alias:void 0,array:void 0,boolean:void 0,config:void 0,configObjects:void 0,configuration:void 0,coerce:void 0,count:void 0,default:void 0,envPrefix:void 0,narg:void 0,normalize:void 0,string:void 0,number:void 0,__:void 0,key:void 0},t),o= /** * @license * Copyright (c) 2016, Contributors * SPDX-License-Identifier: ISC */ function(e){if(Array.isArray(e))return e.map(e=>"string"!=typeof e?e+"":e);e=e.trim();let t=0,n=null,o=null,s=null;const r=[];for(let a=0;a<e.length;a++)n=o,o=e.charAt(a)," "!==o||s?(o===s?s=null:"'"!==o&&'"'!==o||s||(s=o),r[t]||(r[t]=""),r[t]+=o):" "!==n&&t++;return r} /** * @license * Copyright (c) 2016, Contributors * SPDX-License-Identifier: ISC */(e),s="string"==typeof e,r=function(e){const t=[],n=Object.create(null);let o=!0;Object.keys(e).forEach(function(n){t.push([].concat(e[n],n))});for(;o;){o=!1;for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){if(t[e].filter(function(e){return-1!==t[n].indexOf(e)}).length){t[e]=t[e].concat(t[n]),t.splice(n,1),o=!0;break}}}return t.forEach(function(e){const t=(e=e.filter(function(e,t,n){return n.indexOf(e)===t})).pop();void 0!==t&&"string"==typeof t&&(n[t]=e)}),n}(Object.assign(Object.create(null),n.alias)),a=Object.assign({"boolean-negation":!0,"camel-case-expansion":!0,"combine-arrays":!1,"dot-notation":!0,"duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"greedy-arrays":!0,"halt-at-non-option":!1,"nargs-eats-options":!1,"negation-prefix":"no-","parse-numbers":!0,"parse-positional-numbers":!0,"populate--":!1,"set-placeholder-key":!1,"short-option-groups":!0,"strip-aliased":!1,"strip-dashed":!1,"unknown-options-as-args":!1},n.configuration),i=Object.assign(Object.create(null),n.default),c=n.configObjects||[],l=n.envPrefix,d=a["populate--"],u=d?"--":"_",f=Object.create(null),p=Object.create(null),g=n.__||F.format,y={aliases:Object.create(null),arrays:Object.create(null),bools:Object.create(null),strings:Object.create(null),numbers:Object.create(null),counts:Object.create(null),normalize:Object.create(null),configs:Object.create(null),nargs:Object.create(null),coercions:Object.create(null),keys:[]},h=/^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/,m=new RegExp("^--"+a["negation-prefix"]+"(.+)");[].concat(n.array||[]).filter(Boolean).forEach(function(e){const t="object"==typeof e?e.key:e,n=Object.keys(e).map(function(e){return{boolean:"bools",string:"strings",number:"numbers"}[e]}).filter(Boolean).pop();n&&(y[n][t]=!0),y.arrays[t]=!0,y.keys.push(t)}),[].concat(n.boolean||[]).filter(Boolean).forEach(function(e){y.bools[e]=!0,y.keys.push(e)}),[].concat(n.string||[]).filter(Boolean).forEach(function(e){y.strings[e]=!0,y.keys.push(e)}),[].concat(n.number||[]).filter(Boolean).forEach(function(e){y.numbers[e]=!0,y.keys.push(e)}),[].concat(n.count||[]).filter(Boolean).forEach(function(e){y.counts[e]=!0,y.keys.push(e)}),[].concat(n.normalize||[]).filter(Boolean).forEach(function(e){y.normalize[e]=!0,y.keys.push(e)}),"object"==typeof n.narg&&Object.entries(n.narg).forEach(([e,t])=>{"number"==typeof t&&(y.nargs[e]=t,y.keys.push(e))}),"object"==typeof n.coerce&&Object.entries(n.coerce).forEach(([e,t])=>{"function"==typeof t&&(y.coercions[e]=t,y.keys.push(e))}),void 0!==n.config&&(Array.isArray(n.config)||"string"==typeof n.config?[].concat(n.config).filter(Boolean).forEach(function(e){y.configs[e]=!0}):"object"==typeof n.config&&Object.entries(n.config).forEach(([e,t])=>{"boolean"!=typeof t&&"function"!=typeof t||(y.configs[e]=t)})),function(...e){e.forEach(function(e){Object.keys(e||{}).forEach(function(e){y.aliases[e]||(y.aliases[e]=[].concat(r[e]||[]),y.aliases[e].concat(e).forEach(function(t){if(/-/.test(t)&&a["camel-case-expansion"]){const n=T(t);n!==e&&-1===y.aliases[e].indexOf(n)&&(y.aliases[e].push(n),f[n]=!0)}}),y.aliases[e].concat(e).forEach(function(t){if(t.length>1&&/[A-Z]/.test(t)&&a["camel-case-expansion"]){const n=function(e,t){const n=e.toLowerCase();t=t||"-";let o="";for(let s=0;s<e.length;s++){const r=n.charAt(s),a=e.charAt(s);o+=r!==a&&s>0?`${t}${n.charAt(s)}`:a}return o}(t,"-");n!==e&&-1===y.aliases[e].indexOf(n)&&(y.aliases[e].push(n),f[n]=!0)}}),y.aliases[e].forEach(function(t){y.aliases[t]=[e].concat(y.aliases[e].filter(function(e){return t!==e}))}))})})}(n.key,r,n.default,y.arrays),Object.keys(i).forEach(function(e){(y.aliases[e]||[]).forEach(function(t){i[t]=i[e]})});let b=null;Object.keys(y.counts).find(e=>B(e,y.arrays)?(b=Error(g("Invalid configuration: %s, opts.count excludes opts.array.",e)),!0):!!B(e,y.nargs)&&(b=Error(g("Invalid configuration: %s, opts.count excludes opts.narg.",e)),!0));let w=[];const $=Object.assign(Object.create(null),{_:[]}),v={};for(let e=0;e<o.length;e++){const t=o[e],n=t.replace(/^-{3,}/,"---");let s,r,i,c,l,d;if("--"!==t&&L(t))j(t);else{if(n.match(/---+(=|$)/)){j(t);continue}if(t.match(/^--.+=/)||!a["short-option-groups"]&&t.match(/^-.+=/))c=t.match(/^--?([^=]+)=([\s\S]*)$/),null!==c&&Array.isArray(c)&&c.length>=3&&(B(c[1],y.arrays)?e=_(e,c[1],o,c[2]):!1!==B(c[1],y.nargs)?e=k(e,c[1],o,c[2]):E(c[1],c[2],!0));else if(t.match(m)&&a["boolean-negation"])c=t.match(m),null!==c&&Array.isArray(c)&&c.length>=2&&(r=c[1],E(r,!!B(r,y.arrays)&&[!1]));else if(t.match(/^--.+/)||!a["short-option-groups"]&&t.match(/^-[^-]+/))c=t.match(/^--?(.+)/),null!==c&&Array.isArray(c)&&c.length>=2&&(r=c[1],B(r,y.arrays)?e=_(e,r,o):!1!==B(r,y.nargs)?e=k(e,r,o):(l=o[e+1],void 0===l||l.match(/^-/)&&!l.match(h)||B(r,y.bools)||B(r,y.counts)?/^(true|false)$/.test(l)?(E(r,l),e++):E(r,M(r)):(E(r,l),e++)));else if(t.match(/^-.\..+=/))c=t.match(/^-([^=]+)=([\s\S]*)$/),null!==c&&Array.isArray(c)&&c.length>=3&&E(c[1],c[2]);else if(t.match(/^-.\..+/)&&!t.match(h))l=o[e+1],c=t.match(/^-(.\..+)/),null!==c&&Array.isArray(c)&&c.length>=2&&(r=c[1],void 0===l||l.match(/^-/)||B(r,y.bools)||B(r,y.counts)?E(r,M(r)):(E(r,l),e++));else if(t.match(/^-[^-]+/)&&!t.match(h)){i=t.slice(1,-1).split(""),s=!1;for(let n=0;n<i.length;n++){if(l=t.slice(n+2),i[n+1]&&"="===i[n+1]){d=t.slice(n+3),r=i[n],B(r,y.arrays)?e=_(e,r,o,d):!1!==B(r,y.nargs)?e=k(e,r,o,d):E(r,d),s=!0;break}if("-"!==l){if(/[A-Za-z]/.test(i[n])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(l)&&!1===B(l,y.bools)){E(i[n],l),s=!0;break}if(i[n+1]&&i[n+1].match(/\W/)){E(i[n],l),s=!0;break}E(i[n],M(i[n]))}else E(i[n],l)}r=t.slice(-1)[0],s||"-"===r||(B(r,y.arrays)?e=_(e,r,o):!1!==B(r,y.nargs)?e=k(e,r,o):(l=o[e+1],void 0===l||/^(-|--)[^-]/.test(l)&&!l.match(h)||B(r,y.bools)||B(r,y.counts)?/^(true|false)$/.test(l)?(E(r,l),e++):E(r,M(r)):(E(r,l),e++)))}else if(t.match(/^-[0-9]$/)&&t.match(h)&&B(t.slice(1),y.bools))r=t.slice(1),E(r,M(r));else{if("--"===t){w=o.slice(e+1);break}if(a["halt-at-non-option"]){w=o.slice(e);break}j(t)}}}function j(e){const t=I("_",e);"string"!=typeof t&&"number"!=typeof t||$._.push(t)}function k(e,t,n,o){let s,r=B(t,y.nargs);if(r="number"!=typeof r||isNaN(r)?1:r,0===r)return q(o)||(b=Error(g("Argument unexpected for: %s",t))),E(t,M(t)),e;let i=q(o)?0:1;if(a["nargs-eats-options"])n.length-(e+1)+i<r&&(b=Error(g("Not enough arguments following: %s",t))),i=r;else{for(s=e+1;s<n.length&&(!n[s].match(/^-[^0-9]/)||n[s].match(h)||L(n[s]));s++)i++;i<r&&(b=Error(g("Not enough arguments following: %s",t)))}let c=Math.min(i,r);for(!q(o)&&c>0&&(E(t,o),c--),s=e+1;s<c+e+1;s++)E(t,n[s]);return e+c}function _(e,t,n,o){let r=[],c=o||n[e+1];const l=B(t,y.nargs);if(B(t,y.bools)&&!/^(true|false)$/.test(c))r.push(!0);else if(q(c)||q(o)&&/^-/.test(c)&&!h.test(c)&&!L(c)){if(void 0!==i[t]){const e=i[t];r=Array.isArray(e)?e:[e]}}else{q(o)||r.push(O(t,o,!0));for(let o=e+1;o<n.length&&!(!a["greedy-arrays"]&&r.length>0||l&&"number"==typeof l&&r.length>=l)&&(c=n[o],!/^-/.test(c)||h.test(c)||L(c));o++)e=o,r.push(O(t,c,s))}return"number"==typeof l&&(l&&r.length<l||isNaN(l)&&0===r.length)&&(b=Error(g("Not enough arguments following: %s",t))),E(t,r),e}function E(e,t,n=s){if(/-/.test(e)&&a["camel-case-expansion"]){const t=e.split(".").map(function(e){return T(e)}).join(".");S(e,t)}const o=O(e,t,n),r=e.split(".");if(C($,r,o),y.aliases[e]&&y.aliases[e].forEach(function(e){const t=e.split(".");C($,t,o)}),r.length>1&&a["dot-notation"]&&(y.aliases[r[0]]||[]).forEach(function(t){let n=t.split(".");const s=[].concat(r);s.shift(),n=n.concat(s),(y.aliases[e]||[]).includes(n.join("."))||C($,n,o)}),B(e,y.normalize)&&!B(e,y.arrays)){[e].concat(y.aliases[e]||[]).forEach(function(e){Object.defineProperty(v,e,{enumerable:!0,get:()=>t,set(e){t="string"==typeof e?F.normalize(e):e}})})}}function S(e,t){y.aliases[e]&&y.aliases[e].length||(y.aliases[e]=[t],f[t]=!0),y.aliases[t]&&y.aliases[t].length||S(t,e)}function O(e,t,n){n&&(t=function(e){return"string"!=typeof e||"'"!==e[0]&&'"'!==e[0]||e[e.length-1]!==e[0]?e:e.substring(1,e.length-1)}(t)),(B(e,y.bools)||B(e,y.counts))&&"string"==typeof t&&(t="true"===t);let o=Array.isArray(t)?t.map(function(t){return I(e,t)}):I(e,t);return B(e,y.counts)&&(q(o)||"boolean"==typeof o)&&(o=A()),B(e,y.normalize)&&B(e,y.arrays)&&(o=Array.isArray(t)?t.map(e=>F.normalize(e)):F.normalize(t)),o}function I(e,t){if(!a["parse-positional-numbers"]&&"_"===e)return t;if(!B(e,y.strings)&&!B(e,y.bools)&&!Array.isArray(t)){(null!=(n=t)&&("number"==typeof n||!!/^0x[0-9a-f]+$/i.test(n)||!/^0[^.]/.test(n)&&/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(n))&&a["parse-numbers"]&&Number.isSafeInteger(Math.floor(parseFloat(`${t}`)))||!q(t)&&B(e,y.numbers))&&(t=Number(t))}var n;return t}function N(e,t){Object.keys(e).forEach(function(n){const o=e[n],s=t?t+"."+n:n;"object"==typeof o&&null!==o&&!Array.isArray(o)&&a["dot-notation"]?N(o,s):(!P($,s.split("."))||B(s,y.arrays)&&a["combine-arrays"])&&E(s,o)})}function D(e,t){if(void 0===l)return;const n="string"==typeof l?l:"",o=F.env();Object.keys(o).forEach(function(s){if(""===n||0===s.lastIndexOf(n,0)){const r=s.split("__").map(function(e,t){return 0===t&&(e=e.substring(n.length)),T(e)});(t&&y.configs[r.join(".")]||!t)&&!P(e,r)&&E(r.join("."),o[s])}})}function R(e,t,n,o=!1){Object.keys(n).forEach(function(s){P(e,s.split("."))||(C(e,s.split("."),n[s]),o&&(p[s]=!0),(t[s]||[]).forEach(function(t){P(e,t.split("."))||C(e,t.split("."),n[s])}))})}function P(e,t){let n=e;a["dot-notation"]||(t=[t.join(".")]),t.slice(0,-1).forEach(function(e){n=n[e]||{}});const o=t[t.length-1];return"object"==typeof n&&o in n}function C(e,t,n){let o=e;a["dot-notation"]||(t=[t.join(".")]),t.slice(0,-1).forEach(function(e){e=U(e),"object"==typeof o&&void 0===o[e]&&(o[e]={}),"object"!=typeof o[e]||Array.isArray(o[e])?(Array.isArray(o[e])?o[e].push({}):o[e]=[o[e],{}],o=o[e][o[e].length-1]):o=o[e]});const s=U(t[t.length-1]),r=B(t.join("."),y.arrays),i=Array.isArray(n);let c=a["duplicate-arguments-array"];!c&&B(s,y.nargs)&&(c=!0,(!q(o[s])&&1===y.nargs[s]||Array.isArray(o[s])&&o[s].length===y.nargs[s])&&(o[s]=void 0)),n===A()?o[s]=A(o[s]):Array.isArray(o[s])?c&&r&&i?o[s]=a["flatten-duplicate-arrays"]?o[s].concat(n):(Array.isArray(o[s][0])?o[s]:[o[s]]).concat([n]):c||Boolean(r)!==Boolean(i)?o[s]=o[s].concat([n]):o[s]=n:void 0===o[s]&&r?o[s]=i?n:[n]:!c||void 0===o[s]||B(s,y.counts)||B(s,y.bools)?o[s]=n:o[s]=[o[s],n]}function B(e,t){const n=[].concat(y.aliases[e]||[],e),o=Object.keys(t),s=n.find(e=>o.includes(e));return!!s&&t[s]}function K(e){const t=Object.keys(y);return[].concat(t.map(e=>y[e])).some(function(t){return Array.isArray(t)?t.includes(e):t[e]})}function L(e){return a["unknown-options-as-args"]&&function(e){if(e=e.replace(/^-{3,}/,"--"),e.match(h))return!1;if(function(e){if(e.match(h)||!e.match(/^-[^-]+/))return!1;let t,n=!0;const o=e.slice(1).split("");for(let s=0;s<o.length;s++){if(t=e.slice(s+2),!K(o[s])){n=!1;break}if(o[s+1]&&"="===o[s+1]||"-"===t||/[A-Za-z]/.test(o[s])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(t)||o[s+1]&&o[s+1].match(/\W/))break}return n}(e))return!1;return!function(e,...t){return[].concat(...t).some(function(t){const n=e.match(t);return n&&K(n[1])})}(e,/^-+([^=]+?)=[\s\S]*$/,m,/^-+([^=]+?)$/,/^-+([^=]+?)-$/,/^-+([^=]+?\d+)$/,/^-+([^=]+?)\W+.*$/)}(e)}function M(e){return B(e,y.bools)||B(e,y.counts)||!(`${e}`in i)?(t=function(e){let t=x.BOOLEAN;return B(e,y.strings)?t=x.STRING:B(e,y.numbers)?t=x.NUMBER:B(e,y.bools)?t=x.BOOLEAN:B(e,y.arrays)&&(t=x.ARRAY),t}(e),{[x.BOOLEAN]:!0,[x.STRING]:"",[x.NUMBER]:void 0,[x.ARRAY]:[]}[t]):i[e];var t}function q(e){return void 0===e}return D($,!0),D($,!1),function(e){const t=Object.create(null);R(t,y.aliases,i),Object.keys(y.configs).forEach(function(n){const o=e[n]||t[n];if(o)try{let e=null;const t=F.resolve(F.cwd(),o),s=y.configs[n];if("function"==typeof s){try{e=s(t)}catch(t){e=t}if(e instanceof Error)return void(b=e)}else e=F.require(t);N(e)}catch(t){"PermissionDenied"===t.name?b=t:e[n]&&(b=Error(g("Invalid JSON config file: %s",o)))}})}($),void 0!==c&&c.forEach(function(e){N(e)}),R($,y.aliases,i,!0),function(e){let t;const n=new Set;Object.keys(e).forEach(function(o){if(!n.has(o)&&(t=B(o,y.coercions),"function"==typeof t))try{const s=I(o,t(e[o]));[].concat(y.aliases[o]||[],o).forEach(t=>{n.add(t),e[t]=s})}catch(e){b=e}})}($),a["set-placeholder-key"]&&function(e){y.keys.forEach(t=>{~t.indexOf(".")||void 0===e[t]&&(e[t]=void 0)})}($),Object.keys(y.counts).forEach(function(e){P($,e.split("."))||E(e,0)}),d&&w.length&&($[u]=[]),w.forEach(function(e){$[u].push(e)}),a["camel-case-expansion"]&&a["strip-dashed"]&&Object.keys($).filter(e=>"--"!==e&&e.includes("-")).forEach(e=>{delete $[e]}),a["strip-aliased"]&&[].concat(...Object.keys(r).map(e=>r[e])).forEach(e=>{a["camel-case-expansion"]&&e.includes("-")&&delete $[e.split(".").map(e=>T(e)).join(".")],delete $[e]}),{aliases:Object.assign({},y.aliases),argv:Object.assign(v,$),configuration:a,defaulted:Object.assign({},p),error:b,newAliases:Object.assign({},f)}}}({cwd:process.cwd,env:()=>D,format:s.format,normalize:t.normalize,resolve:t.resolve,require:t=>{if("undefined"!=typeof require)return require(t);if(t.match(/\.json$/))return JSON.parse(e.readFileSync(t,"utf8"));throw Error("only .json config files are supported in ESM")}});var R={fs:{readFileSync:e.readFileSync,writeFile:e.writeFile},format:s.format,resolve:t.resolve,exists:t=>{try{return e.statSync(t).isFile()}catch(e){return!1}}};let P;class C{constructor(e){e=e||{},this.directory=e.directory||"./locales",this.updateFiles="boolean"!=typeof e.updateFiles||e.updateFiles,this.locale=e.locale||"en",this.fallbackToLanguage="boolean"!=typeof e.fallbackToLanguage||e.fallbackToLanguage,this.cache=Object.create(null),this.writeQueue=[]}__(...e){if("string"!=typeof arguments[0])return this._taggedLiteral(arguments[0],...arguments);const t=e.shift();let n=function(){};return"function"==typeof e[e.length-1]&&(n=e.pop()),n=n||function(){},this.cache[this.locale]||this._readLocaleFile(),!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]=t,this._enqueueWrite({directory:this.directory,locale:this.locale,cb:n})):n(),P.format.apply(P.format,[this.cache[this.locale][t]||t].concat(e))}__n(){const e=Array.prototype.slice.call(arguments),t=e.shift(),n=e.shift(),o=e.shift();let s=function(){};"function"==typeof e[e.length-1]&&(s=e.pop()),this.cache[this.locale]||this._readLocaleFile();let r=1===o?t:n;if(this.cache[this.locale][t]){r=this.cache[this.locale][t][1===o?"one":"other"]}!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]={one:t,other:n},this._enqueueWrite({directory:this.directory,locale:this.locale,cb:s})):s();const a=[r];return~r.indexOf("%d")&&a.push(o),P.format.apply(P.format,a.concat(e))}setLocale(e){this.locale=e}getLocale(){return this.locale}updateLocale(e){this.cache[this.locale]||this._readLocaleFile();for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&(this.cache[this.locale][t]=e[t])}_taggedLiteral(e,...t){let n="";return e.forEach(function(e,o){const s=t[o+1];n+=e,void 0!==s&&(n+="%s")}),this.__.apply(this,[n].concat([].slice.call(t,1)))}_enqueueWrite(e){this.writeQueue.push(e),1===this.writeQueue.length&&this._processWriteQueue()}_processWriteQueue(){const e=this,t=this.writeQueue[0],n=t.directory,o=t.locale,s=t.cb,r=this._resolveLocaleFile(n,o),a=JSON.stringify(this.cache[o],null,2);P.fs.writeFile(r,a,"utf-8",function(t){e.writeQueue.shift(),e.writeQueue.length>0&&e._processWriteQueue(),s(t)})}_readLocaleFile(){let e={};const t=this._resolveLocaleFile(this.directory,this.locale);try{P.fs.readFileSync&&(e=JSON.parse(P.fs.readFileSync(t,"utf-8")))}catch(n){if(n instanceof SyntaxError&&(n.message="syntax error in "+t),"ENOENT"!==n.code)throw n;e={}}this.cache[this.locale]=e}_resolveLocaleFile(e,t){let n=P.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(n)&&~t.lastIndexOf("_")){const o=P.resolve(e,"./",t.split("_")[0]+".json");this._fileExistsSync(o)&&(n=o)}return n}_fileExistsSync(e){return P.exists(e)}}let B;try{B=r.fileURLToPath("undefined"==typeof document?require("url").pathToFileURL(__filename).href:b&&"SCRIPT"===b.tagName.toUpperCase()&&b.src||new URL("index.js",document.baseURI).href)}catch(e){B=process.cwd()}B.split("node_modules")[0]||process.cwd(),process.cwd,process.exit,process.nextTick,void 0!==process.stdout.columns&&process.stdout.columns,function(e,t){P=t;const n=new C(e);n.__.bind(n),n.__n.bind(n),n.setLocale.bind(n),n.getLocale.bind(n),n.updateLocale.bind(n),n.locale}({directory:t.resolve(B,"../../../locales"),updateFiles:!1},R);const K={hg:{appName:"hotglue",clientApiBaseUri:process.env.HOTGLUE_CLIENT_API_BASE_URI||"https://api.hotglue.com",defaultConfigFileName:"config.yaml"}},L={},M=()=>t.resolve(n.homedir(),`.${K.hg.appName}`,K.hg.defaultConfigFileName),q=async()=>{const{appName:e}=K.hg;try{return await i.cosmiconfig(e).load(M())||{}}catch(e){return{}}},z=async()=>{const{appName:e}=K.hg,t=i.cosmiconfig(e,{searchPlaces:[`${e}.yaml`,`.${e}.yaml`,`.${e}rc.yaml`,`.${e}rc.yml`,`.${e}rc`,`.${e}rc.json`,`.${e}rc.js`]});try{return await t.search()||{}}catch(e){throw console.log(e),new Error(`Malformed configuration file: ${e.message}`)}},J={primary:e=>c.whiteBright(e),secondary:e=>c.white(e),info:e=>c.green(e),warn:e=>c.yellow(e),error:e=>c.redBright(e),success:e=>c.greenBright(e)};let V=J,W="primary";function Y(e){return V={...J,...e},ee}function G(e){process.stdout.write(e)}const Q=(e,t=W)=>{if(!e)return"";if("string"==typeof e)return V[t]?V[t](e):V[W](e);const n=s.inspect(e,{colors:!0});return V[t]?V[t](n):n};function H(...e){return console.log(...e),ee}function Z(e,t){return G(Q(e,t)),G("\n"),ee}function X(e,t){return G(Q(e,t)),ee}const ee={cl:H,pr:Z,pp:X,setTheme:Y,setDefault:function(e="primary"){return V[e]&&(W=e),ee}},te=e=>{console.log(JSON.stringify(e))},ne=d("hotglue-cli");function oe(e){return ne.extend(e)}const se=oe("commands:config:set"),re="set <setting> <value>";var ae=Object.freeze({__proto__:null,builder:async e=>(se("builder",re,e),e.option("setting",{describe:"The configuration parameter you wish to set",type:"string"}).option("value",{describe:"The configuration parameter's value",type:"string"}),e),command:re,desc:"Set configuration key-value pairs",handler:async e=>{se("handler",re,e);const{json:n,setting:o,value:s}=e;if(["apikey"].includes(o))try{const e=await q();e&&e.config?!n&&X("Updating profile config file..."):!n&&X("Creating profile config file...");const r=e&&e.config?{...e.config,[o]:s}:{[o]:s},i=u.stringify(r),c=e&&e.filepath?e.filepath:M();await(async(e,n)=>{await a.mkdir(t.dirname(e),{recursive:!0}),await a.writeFile(e,n)})(c,i),n?te({status:"success"}):X("Done").pr()}catch(e){n?te({status:"error",error:e}):console.log(e)}else n?te({status:"error",error:"Invalid settings parameter"}):console.error("Invalid settings parameter")}});const ie=[ae],ce=oe("commands:config"),le="config [action]";var de=Object.freeze({__proto__:null,builder:async function(e){return ce("builder",le),e.command(ie)},command:le,desc:"Configure your hotglue CLI",handler:async function(e){ce("handler",le,e);const{action:n}=e;if(!n)try{const e=await q();e.config&&0!==Object.keys(e.config).length||Z("No profile configuration found. Run config set to configure the hotglue CLI.");const n=new f({head:["Setting","Value","Config File","Type"]});e.config&&Object.entries(e.config).forEach(([t,o])=>n.push([t,o,e.filepath,"Profile"]));const o=await z();o.config&&Object.entries(o.config).forEach(([e,s])=>n.push([e,s,t.relative(process.cwd(),o.filepath),"Project"])),n.length>0&&console.log(n.toString())}catch(e){throw console.log(e),e}}}),ue={env:{config:{describe:"Environment Id",type:"string",alias:["e"]},demandText:'The "env" parameter (Environment Id) is required. Either pass here using `-e [env_id]` or add an env property in your rc file.'},apikey:{config:{describe:"API key",type:"string",alias:["k"]},demandText:"API key is required. Either pass here using -k [key] or configure your profile using config set."},dataFilePath:{config:{describe:"Singer data file path",type:"string",alias:["data","data-file-path"],default:"data.singer"}},json:{config:{describe:"Makes the output format to be JSON",type:"boolean",default:!1},demandText:""},tenant:{config:{describe:"Tenant (user) ID",type:"string",alias:["u"]},demandText:"TenantId is required. You can pass it using -u [tenantId]."},flow:{config:{describe:"Flow ID",type:"string",alias:["f"]},demandText:"FlowId is required. You can pass it using -f [flow_id]."},tap:{config:{describe:"Tap name",type:"string",alias:["t"]},demandText:"Tap name is required. You can pass it using -t <tap_name>."},connector:{config:{describe:"Connector ID",type:"string",alias:["c"]},demandText:"Connector ID is required. You can pass it using -c <connector>."},all:{config:{describe:"Run command for all taps/connectors",type:"boolean",default:!1,alias:["a"]},demandText:'This "all" flag is required. You can pass it using -a or --all.'},jobroot:{config:{describe:"Job Root (S3 prefix)",type:"string",alias:["j"]},demandText:"JobRoot key is required. You can pass it using -j [job_root]."},count:{config:{describe:"Max returned records",type:"number"}},downloadTo:{config:{describe:"Download folder",default:".",type:"string",alias:["d"]},demandText:"A destination folder is required. You can pass it using -d [folder] and can be either relative from cwd or absolute."},sourceFolder:{config:{describe:"Source folder",type:"string",default:".",alias:["s"]},demandText:""},configFilePath:{config:{describe:"Config file path",type:"string",default:"./config.json",alias:["p"]},demandText:'Local path of the config (with .json extension). Example: "/home/hotglue/config.json"'},overwrite:{config:{describe:"Overwrite existing",type:"boolean",default:!1,alias:["o"]},demandText:""},cleanup:{config:{describe:"Clean up target prior to action",type:"boolean",default:!1,alias:["c"]},demandText:""}};const fe=oe("base"),pe=async e=>{fe("builder");const t=await(async()=>{const e=await q(),t=await z();return{...L,...e.config,...t.config}})();return e.option("apikey",ue.apikey.config).option("env",ue.env.config).option("json",ue.json.config).config(t).demandOption(["env"],ue.env.demandText).demandOption(["apikey"],ue.apikey.demandText).strictCommands()},ge=oe("utils.js"),ye=async(e,n,o=[])=>{const{includeSymLinks:s,recursive:r,filter:i}=n,{matcher:c}=i,l=t.resolve(e),d=await a.readdir(l,{withFileTypes:!0});for(const e of d){const a=t.resolve(l,e.name);e.isSymbolicLink()&&!s||(!c||c(a)?e.isFile()?o.push(t.resolve(l,e.name)):e.isDirectory()&&r&&await ye(t.resolve(l,e.name),n,o):ge("skip",a))}return o},he=async(e,t)=>{const n={includeSymLinks:!1,recursive:!1,filter:{},...t},{pattern:o}=n.filter;return o&&(n.filter.matcher=g.matcher(o,{dot:!0})),ye(e,n)},me=(e,t)=>{ge("filter-in",e);const{pattern:n}={...t};let o=e;return n&&(o=g(o,n)),ge("filter-out",o),o};const be=e=>{const t=[];return new Promise((n,o)=>{e.on("error",o),e.on("data",e=>t.push(Buffer.from(e))),e.on("end",()=>n(Buffer.concat(t).toString("utf8")))})},we=(e,t=10)=>{const n=[];for(let o=0;o<e.length;o+=t){const s=e.slice(o,o+t);n.push(s)}return n},$e=async({debug:e,baseUri:t,env:n,apiKey:o})=>{const s=new URL(`${t}/${n}/resetAvailableEntities`),{data:r}=await y.delete(s,{headers:{"x-api-key":o,"Content-type":"application/json"}});e({data:r})},ve=async({debug:e,baseUri:t,task:n,env:o,apikey:s,...r})=>{const a=new URL(`${t}/credentials/${n}/${o}`);r&&Object.entries(r).forEach(([e,t])=>{a.searchParams.set(e,t)});const i=a.toString();e&&e("uri:",i);const{data:c}=await y.get(i,{headers:{"x-api-key":s}}),{accessKeyId:l,secretAccessKey:d,sessionToken:u}=c;return{accessKeyId:l,secretAccessKey:d,sessionToken:u}},je=async({debug:e,baseUri:t,env:n,apikey:o})=>{const s=`${t}/tenants/${n}`;e("requesting:",s);const{data:r}=await y.get(s,{headers:{"x-api-key":o}});return e("response-data",r),r},ke=async({debug:e,baseUri:t,env:n,flow:o,apikey:s})=>{const r={"x-api-key":s},a=new URL(`${t}/${n}/${o}/supportedSources`).toString();e&&e("uri:",a);const{data:i}=await y.get(a,{headers:r});return i},_e=async({debug:e,baseUri:t,env:n,flow:o,apikey:s})=>{const r={"x-api-key":s},a=new URL(`${t}/v2/${n}/${o}/supportedConnectors`).toString();e&&e("uri:",a);const{data:i}=await y.get(a,{headers:r});return i},Ee=async({debug:e,baseUri:t,env:n,flow:o,tenant:s,apikey:r,config:a})=>{const i=new URL(`${t}/${n}/${o}/${s}/linkedSources`);a&&i.searchParams.set("config","true");const c={"x-api-key":r},l=i.toString();e&&e("uri:",l);const{data:d}=await y.get(l,{headers:c});return d},xe=async({debug:e,baseUri:t,env:n,flow:o,tenant:s,apikey:r,config:a})=>{const i=new URL(`${t}/v2/${n}/${o}/${s}/linkedConnectors`);a&&i.searchParams.set("config","true");const c={"x-api-key":r},l=i.toString();e&&e("uri:",l);const{data:d}=await y.get(l,{headers:c});return d},Se=async({debug:e,baseUri:t,env:n,flow:o,tenant:s,apikey:r,connectorId:a,config:i})=>{const c={"x-api-key":r},l=new URL(`${t}/${n}/${o}/${s}/linkedSources`).toString(),d={tap:a,config:i};e&&e("uri:",l);const{data:u}=await y.patch(l,d,{headers:c});return u},Oe=async({debug:e,baseUri:t,env:n,flow:o,tenant:s,apikey:r,connectorId:a,config:i})=>{const c={"x-api-key":r},l=new URL(`${t}/v2/${n}/${o}/${s}/linkedConnectors`).toString(),d={connector_id:a,config:i};e&&e("uri:",l);const{data:u}=await y.patch(l,d,{headers:c});return u},Ie=async({debug:e,baseUri:t,env:n,apikey:o})=>{const s={"x-api-key":o},r=new URL(`${t}/${n}/flows/supported`).toString();e&&e("uri:",r);const{data:a}=await y.get(r,{headers:s});return a},Te=async({debug:e,baseUri:t,env:n,flow:o,apikey:s})=>{const r={"x-api-key":s},a=new URL(`${t}/${n}/flows/${o}/supported`).toString();e&&e("uri:",a);const{data:i}=await y.get(a,{headers:r});return i},Fe=async({debug:e,baseUri:t,env:n,apikey:o,from:s,to:r,count:a=1e4,...i})=>{const c={"x-api-key":o},l="string"==typeof a?parseInt(a,10):a;let d=[],u=0,f=1,p=!0;for(;p;){const o=new URL(`${t}/${n}/jobs`);o.searchParams.set("from",s),r&&o.searchParams.set("to",r),o.searchParams.set("count",l.toString()),o.searchParams.set("page",f.toString()),i&&Object.entries(i).forEach(([e,t])=>{null!=t&&"count"!==e&&"page"!==e&&o.searchParams.set(e,t)}),o.searchParams.set("include_export_details","false"),o.searchParams.set("skip_cache","true");const a=o.toString();e&&e(`Fetching page ${f}, uri:`,a);const{data:g}=await y.get(a,{headers:c});e&&e(`Page ${f} response:`,{jobsCount:g.jobs?.length||0,total:g.total||0});const h=g.jobs||[];d=d.concat(h),1===f&&(u=g.total||0),h.length<l?p=!1:f++}return e&&e(`Fetched ${d.length} jobs across ${f} page(s)`),{jobs:d,total:u}},Ae=async({debug:e,baseUri:t,env:n,apikey:o,tenant:s,flow:r,...a})=>{const i={"x-api-key":o},c=new URL(`${t}/${n}/${r}/${s}/jobs/retrigger`).toString(),l=a;e&&e("uri:",c),e&&e("payload:",l);const{data:d}=await y.post(c,l,{headers:i});return d},Ue=async({debug:e,baseUri:t,env:n,flow:o,user_id:s,apikey:r,schedule_expression:a,state:i,job_type:c,connector_id:l,extra_args:d})=>{const u={"x-api-key":r},f=new URL(`${t}/${n}/${o}/${s}/jobs/schedule`).toString(),p={schedule_expression:a,state:i};c&&(p.job_type=c),l&&(p.connector_id=l),d&&Object.assign(p,d),e&&e("uri:",f),e&&e("body:",p);const{data:g}=await y.put(f,p,{headers:u});return g},Ne=async({debug:e,baseUri:t,env:n,flow:o,user_id:s,apikey:r,job_root:a,include_export_details:i=!1})=>{const c=new URL(`${t}/${n}/${o}/${s}/jobs/status`);c.searchParams.set("job_root",a),c.searchParams.set("include_export_details",i?"true":"false");const l={"x-api-key":r},d=c.toString();e&&e("uri:",d);const{data:u}=await y.get(d,{headers:l});return u},De=d("commands:env:validators"),Re=async(e,t,n,o,s)=>{if(!Array.isArray(e))throw new Error("availableSources.json must be an array of objects");const r=(await Promise.all(o.filter(e=>1==e.version).map(async e=>await ke({debug:De,baseUri:t,env:s,flow:e.id,apikey:n})))).flat(),a=e.map(e=>{if(!e.tap)throw new Error(`Source ${JSON.stringify(e)} has no tap id`);return e.tap}),i=a.filter((e,t)=>a.indexOf(e)!==t);if(i.length>0)throw new Error(`Duplicate source id(s) found in availableSources.json: ${i.join(", ")}. All sources must have a unique tap id.`);const c=r.filter(e=>e.isForked&&!a.includes(e.tap));if(c.length>0)throw new Error(`Sources ${c.map(e=>e.label).join(", ")} are linked, but missing from your availableSources.json`)},Pe=async(e,t,n,o,s)=>{if(!Array.isArray(e))throw new Error("availableTargets.json must be an array of objects");const r=(await Promise.all(o.filter(e=>1==e.version).map(async e=>{const o=await(async({debug:e,baseUri:t,env:n,flow:o,apikey:s})=>{const r={"x-api-key":s},a=new URL(`${t}/${n}/${o}/supportedTargets`).toString();e&&e("uri:",a);const{data:i}=await y.get(a,{headers:r});return i})({debug:De,baseUri:t,env:s,flow:e.id,apikey:n});return o}))).flat(),a=e.map(e=>{if(!e.target)throw new Error(`Target ${JSON.stringify(e)} has no target id`);return e.target}),i=a.filter((e,t)=>a.indexOf(e)!==t);if(i.length>0)throw new Error(`Duplicate target id(s) found in availableTargets.json: ${i.join(", ")}. All targets must have a unique target id.`);const c=r.filter(e=>e.isForked&&!a.includes(e.target));if(c.length>0)throw new Error(`Targets ${c.map(e=>e.label).join(", ")} are linked, but missing from your availableTargets.json`)},Ce=async(e,t,n,o,s)=>{if(!Array.isArray(e))throw new Error("availableConnectors.json must be an array of objects");const r=(await Promise.all(o.filter(e=>2==e.version).map(async e=>await _e({debug:De,baseUri:t,env:s,flow:e.id,apikey:n})))).flat(),a=e.map(e=>{if(!e.id)throw new Error(`Connector ${JSON.stringify(e)} has no id`);return e.id}),i=a.filter((e,t)=>a.indexOf(e)!==t);if(i.length>0)throw new Error(`Duplicate connector id(s) found in availableConnectors.json: ${i.join(", ")}. All connectors must have a unique id.`);const c=r.filter(e=>e.isForked&&!a.includes(e.id));if(c.length>0)throw new Error(`Connectors ${c.map(e=>e.id).join(", ")} are linked, but missing from your availableConnectors.json`)},Be=oe("commands:env:deploy"),Ke="deploy";var Le=Object.freeze({__proto__:null,builder:async e=>(Be("builder",Ke),e.option("sourceFolder",ue.sourceFolder.config).demandOption("sourceFolder",ue.sourceFolder.demandText)),command:Ke,desc:"Deploy Environment settings",handler:async e=>{Be("handler",Ke,e);const{hg:n,json:o,apikey:s,env:r,sourceFolder:i}=e,{clientApiBaseUri:c}=n,d=t.resolve(process.cwd(),i);let u,g=p();try{u=Q(`Scanning ${Q(d,"info")} for deployable files`),!o&&g.start(Q(`In progress: ${u}...`,"secondary"));const e=await he(d,{filter:{pattern:"((**/requirements.txt)|(**/availableSources.json)|(**/availableTargets.json)|(**/availableConnectors.json)|(**/customTaps.json))"}});if(0===e.length)return void(o?te({status:"error",error:"There are no files to deploy at the specified location!"}):(g.fail(Q(`Error: ${u}.`,"secondary")),Z(Q(`Message: ${Q("There are no files to deploy at the specified location!")}`,"secondary"))));!o&&g.succeed(Q(`Finished: ${u}.`,"secondary"));for(const t of e)if(t.endsWith(".json"))try{const e=await a.readFile(t,{encoding:"utf-8"});JSON.parse(e)}catch(e){throw new Error(`File ${t} is not a valid JSON: ${String(e)}`)}const n=await Ie({debug:Be,baseUri:c,env:r,apikey:s});for(const t of e){if(t.endsWith("availableSources.json")){const e=JSON.parse(await a.readFile(t,{encoding:"utf-8"}));await Re(e,c,s,n,r)}if(t.endsWith("availableTargets.json")){const e=JSON.parse(await a.readFile(t,{encoding:"utf-8"}));await Pe(e,c,s,n,r)}if(t.endsWith("availableConnectors.json")){const e=JSON.parse(await a.readFile(t,{encoding:"utf-8"}));await Ce(e,c,s,n,r)}}u=Q("Verifying user and authorizing"),!o&&g.start(Q(`In progress: ${u}...`,"secondary"));const{accessKeyId:i,secretAccessKey:p,sessionToken:y}=await ve({debug:Be,baseUri:c,task:"env-deploy",env:r,apikey:s});!o&&g.succeed(Q(`Finished: ${u}.`,"secondary"));const h=new l.S3({accessKeyId:i,secretAccessKey:p,sessionToken:y});u=Q("Deploying environment files"),!o&&g.info(Q(`Info: ${u}.`,"secondary"));const m="config/",b=new f({head:["File","Status"]});for await(const n of e){const e=t.basename(n);u=Q(`Pushing file: ${Q(e,"info")}`),!o&&g.start(Q(`In progress: ${u}...`,"secondary"));const i={Bucket:r,Key:`${m}${e}`,Body:await a.readFile(n)},l=await h.putObject(i).promise();!o&&g.succeed(Q(`Finished: ${u}.`,"secondary")),Be("s3-put-res",l),b.push([e,"Deployed"]),await $e({debug:Be,baseUri:c,env:r,apiKey:s})}o?te({status:"success",deployedFiles:e}):H(b.toString())}catch(e){!o&&g.fail(Q(`Error: ${u}.`,"secondary")),Z(Q(`Message: ${Q(e.message)}`,"secondary")),Be(e),e&&e.response&&e.response.data&&Be("response",e.response.data),process.exit(1)}}});const Me=oe("commands:env:download"),qe="download";var ze=Object.freeze({__proto__:null,builder:async e=>(Me("builder",qe),e.option("downloadTo",ue.downloadTo.config)),command:qe,desc:"Download Environment settings",handler:async e=>{Me("handler",qe,e);const{hg:n,json:o,apikey:s,env:r,downloadTo:i}=e,{clientApiBaseUri:c}=n,d=t.resolve(process.cwd(),i);let u,g=p();try{u=Q("Verifying user and authorizing"),!o&&g.start(Q(`In progress: ${u}...`,"secondary"));const{accessKeyId:e,secretAccessKey:n,sessionToken:i}=await ve({debug:Me,baseUri:c,task:"env-download",env:r,apikey:s});!o&&g.succeed(Q(`Finished: ${u}.`,"secondary"));const p=new l.S3({accessKeyId:e,secretAccessKey:n,sessionToken:i});u=Q(`Scanning environment ${Q(r,"info")}`),!o&&g.start(Q(`In progress: ${u}...`,"secondary"));const y={Bucket:r,Prefix:"config/"},{Contents:h}=await p.listObjectsV2(y).promise();!o&&g.succeed(Q(`Finished: ${u}.`,"secondary")),Me("s3-files",h);const m=h?me(h.map(e=>e.Key),{pattern:"((*/requirements.txt)|(*/availableSources.json)|(*/availableTargets.json)|(*/availableConnectors.json)|(*/customTaps.json))"}):[];if(!m||0===m.length)return void(o?te({status:"success",downloadedFiles:[]}):g.warn(Q(`Warning: ${Q("Nothing to download!")}`,"secondary")));u=Q(`Downloading to ${Q(d,"info")}`),!o&&g.info(Q(`Info: ${u}.`,"secondary"));const b=new f({head:["File","Status"]});for await(const e of m){const n=t.basename(e),s=t.resolve(d,n);Me("local-file",s),await a.mkdir(t.dirname(s),{recursive:!0}),u=Q(`Downloading file: ${Q(n,"info")}`),!o&&g.start(Q(`In progress: ${u}...`,"secondary"));const i=p.getObject({Bucket:r,Key:e}).createReadStream();await a.writeFile(s,await be(i)),!o&&g.succeed(Q(`Finished: ${u}.`,"secondary")),b.push([n,"Downloaded"])}o?te({status:"success",downloadedFiles:m}):H(b.toString())}catch(e){o?te({status:"error",error:e}):(g.fail(Q(`Error: ${u}.`,"secondary")),Z(Q(`Message: ${Q(e.message)}`,"secondary")),Me(e),e&&e.response&&e.response.data&&Me("response",e.response.data)),process.exit(1)}}});const Je=[Le,ze],Ve=oe("commands:env"),We="env <action>";var Ye=Object.freeze({__proto__:null,builder:async function(e){Ve("builder",We);return(await pe(e)).command(Je)},command:We,desc:"Manage environment settings",handler:async function(e){Ve("handler",We,e)}});const Ge=async(e,t,n,o)=>{try{const s=e.getObject({Bucket:t,Key:`${n}/flows/${o}/flow.json`}).createReadStream(),r=await be(s);return 2===JSON.parse(r).version}catch(e){return!1}},Qe=async(e,t,n,o,s=void 0)=>s??await Ge(e,t,n,o)?"connectors":"taps",He=oe("commands:etl:delete"),Ze="delete";var Xe=Object.freeze({__proto__:null,builder:async e=>(He("builder",Ze),e.option("flow",ue.flow.config).demandOption("flow",ue.flow.demandText).option("tap",ue.tap.config).demandOption("tap",ue.tap.demandText).option("tenant",{...ue.tenant.config}).demandOption("tenant",ue.tenant.demandText)),command:Ze,desc:"Delete ETL scripts",handler:async e=>{He("handler",Ze,e);const{hg:t,json:n,apikey:o,env:s,flow:r,tap:a,tenant:i}=e,{clientApiBaseUri:c}=t;let d,u=p();try{d=Q(`Deleting ETL scripts for Tenant ${Q(i,"info")} Flow ${Q(r,"info")} and Tap ${Q(a,"info")} to ${Q(s,"info")}`),!n&&u.info(Q(`Info: ${d}.`,"secondary")),d=Q("Verifying user and authorizing"),!n&&u.start(Q(`In progress: ${d}...`,"secondary"));const{accessKeyId:e,secretAccessKey:t,sessionToken:p}=await ve({debug:He,baseUri:c,task:"etl-deploy",env:s,tenant:i,flow:r,tap:a,apikey:o}),g=new l.S3({accessKeyId:e,secretAccessKey:t,sessionToken:p});!n&&u.succeed(Q(`Finished: ${d}.`,"secondary")),d=Q("Deleting ETL scripts"),!n&&u.start(Q(`In progress: ${d}...`,"secondary"));const y=`${i}/flows/${r}/${await Qe(g,s,i,r)}/${a}/etl/`,h=await g.listObjectsV2({Bucket:s,Prefix:y}).promise();if(He("s3-list-objects-res",h),h.Contents?.length>0){const e=await g.deleteObjects({Bucket:s,Delete:{Objects:h.Contents.map(e=>({Key:e.Key}))}}).promise();He("s3-list-objects-res",e)}const m=await g.deleteObject({Bucket:s,Key:y}).promise();if(He("s3-delete-object-res",m),!n&&u.succeed(Q(`Finished: ${d}.`,"secondary")),h.Contents?.length>0){const e=new f({head:["File","Status"]});h.Contents.filter(({Key:e})=>e!==y).forEach(({Key:t})=>{const n=t.split("/"),o=n[n.length-1];e.push([o,Q("Deleted","info")])}),n?te({status:"success",deletedObjects:(h.Contents??[]).map(({Key:e})=>e)}):H(e.toString())}else d=Q("There was no file or folder to be deleted"),n?te({status:"success",deletedObjects:[]}):u.info(Q(`Info: ${d}.`,"secondary"))}catch(e){n?te({status:"error",error:e}):(u.fail(Q(`Error: ${d}.`,"secondary")),Z(Q(`Message: ${Q(e.message)}`,"secondary")),He(e),e&&e.response&&e.response.data&&He("response",e.response.data)),process.exit(1)}}});const et=oe("commands:etl:deploy"),tt="deploy";var nt=Object.freeze({__proto__:null,builder:async e=>(et("builder",tt),e.option("flow",ue.flow.config).demandOption("flow",ue.flow.demandText).option("tap",ue.tap.config).option("all",ue.all.config).option("tenant",{...ue.tenant.config,default:"default"}).option("sourceFolder",ue.sourceFolder.config).demandOption("sourceFolder",ue.sourceFolder.demandText)),command:tt,desc:"Deploy ETL scripts",handler:async e=>{et("handler",tt,e);const{hg:n,json:o,apikey:s,env:r,flow:i,tap:c,all:d,tenant:u,sourceFolder:g}=e,{clientApiBaseUri:y}=n;if(!d&&!c)throw new Error(`${ue.tap.demandText} Or you can pass the --all flag to run this command for all taps/connectors.`);let h,m=p();const b=t.resolve(process.cwd(),g);try{h=Q(`Deploying script for Tenant ${Q(u,"info")} Flow ${Q(i,"info")}${c?` and Tap ${Q(c,"info")}`:""} to ${Q(r,"info")}`),!o&&m.info(Q(`Info: ${h}.`,"secondary"));const e=await he(b,{recursive:!0,filter:{pattern:"!((**/sync-output)|(**/etl-output)|(**/snapshots))"}});if(0===e.length)return void(o?te({status:"error",error:"There are no files to deploy at the specified location!"}):m.fail(Q(`Error: ${Q("There are no files to deploy at the specified location!")}.`,"secondary")));(e=>{const t=["config.json","source-config.json","target-config.json","catalog.json","target-catalog.json","state.json"],n=["sync-output","snapshots","etl-output",".venv"];for(const o of e){if(t.includes(o))throw new Error(`File ${o} is a reserved file name and cannot be used in the ETL script.`);const e=n.find(e=>o.startsWith(`${e}/`));if(e)throw new Error(`Directory ${e} is a reserved directory name and cannot be used in the ETL script.`)}})(e.map(e=>t.relative(g,e))),h=Q("Verifying user and authorizing"),!o&&m.start(Q(`In progress: ${h}...`,"secondary"));const n={debug:et,baseUri:y,task:"etl-deploy",env:r,tenant:u,flow:i,apikey:s};c&&(n.tap=c);const{accessKeyId:d,secretAccessKey:p,sessionToken:w}=await ve(n);!o&&m.succeed(Q(`Finished: ${h}.`,"secondary"));const $=new l.S3({accessKeyId:d,secretAccessKey:p,sessionToken:w}),v=await Ge($,r,u,i);h=Q("Validating flow and tap location"),!o&&m.start(Q(`In progress: ${h}...`,"secondary"));const j=(await Ie({debug:et,baseUri:y,apikey:s,env:r})).find(({id:e})=>e===i);let k=[];try{if("default"===u||j?.type){if(k=((v?await _e({debug:et,baseUri:y,env:r,flow:i,apikey:s}):await ke({debug:et,baseUri:y,env:r,flow:i,apikey:s}))??[]).filter(e=>!c||e[v?"id":"tap"]===c),c&&0===k.length)throw new Error("Tap is not supported")}else{if(k=((v?await xe({debug:et,baseUri:y,env:r,flow:i,tenant:u,apikey:s}):await Ee({debug:et,baseUri:y,env:r,flow:i,tenant:u,apikey:s}))??[]).filter(e=>!c||e[v?"id":"tap"]===c),c&&0===k.length)throw new Error("Tap is not linked")}}catch(e){throw et("err",e),new Error("Target location doesn't exist. Check your tenant, flow and tap arguments.")}!o&&m.succeed(Q(`Finished: ${h}.`,"secondary"));const _=new f({head:["File","Status"]});for(const n of k){const s=n[v?"id":"tap"];h=Q(`Preparing ${s} deployment target`),!o&&m.start(Q(`In progress: ${h}...`,"secondary"));const c=`${u}/flows/${i}/${await Qe(null,null,null,null,v)}/${s}/etl/`,{Contents:l}=await $.listObjectsV2({Bucket:r,Prefix:`${c}`}).promise();!o&&m.succeed(Q(`Finished: ${h}.`,"secondary")),et("contents",l);const d=l.map(e=>({Key:e.Key}));if(d.length>0){h=Q(`Removing old ${s} ETL files`),!o&&m.start(Q(`In progress: ${h}...`,"secondary"));const e={Bucket:r,Delete:{Objects:d,Quiet:!0}};await $.deleteObjects(e).promise(),d.forEach(({Key:e})=>_.push([`${s}/${e.substring(c.length)}`,Q("Deleted","warn")])),!o&&m.succeed(Q(`Finished: ${h}.`,"secondary"))}for await(const n of e){const e="win32"===process.platform?t.relative(g,n).replace(/\\/g,"/"):t.relative(g,n),i=`${c}${e}`;h=Q(`Deploying file: ${Q(`${s}/${e}`,"info")}`),!o&&m.start(Q(`In progress: ${h}...`,"secondary"));const l={Bucket:r,Key:i,Body:await a.readFile(n)},d=await $.putObject(l).promise();!o&&m.succeed(Q(`Finished: ${h}.`,"secondary")),et("s3-put-res",d),_.push([`${s}/${e}`,Q("Deployed","info")])}}o?te({status:"success",deployedFiles:e}):H(_.toString())}catch(e){o?te({status:"error",error:e}):(m.fail(Q(`Error: ${h}.`,"secondary")),Z(Q(`Message: ${Q(e.message)}`,"secondary")),et(e),e&&e.response&&e.response.data&&et("response",e.response.data)),process.exit(1)}}});const ot=oe("commands:etl:download"),st="download";var rt=Object.freeze({__proto__:null,builder:async e=>(ot("builder",st),e.option("flow",ue.flow.config).demandOption("flow",ue.flow.demandText).option("tap",ue.tap.config).demandOption("tap",ue.tap.demandText).option("downloadTo",ue.downloadTo.config).demandOption("downloadTo",ue.downloadTo.demandText).option("tenant",{...ue.tenant.config,default:"default"}).option("overwrite",ue.overwrite.config).demandOption("overwrite",ue.overwrite.demandText)),command:st,desc:"Download ETL scripts",handler:async n=>{ot("handler",st,n);const{hg:o,json:s,apikey:r,env:i,flow:c,tap:d,tenant:u,downloadTo:g,overwrite:y}=n,{clientApiBaseUri:h}=o;let m,b=p();const w=t.resolve(process.cwd(),g);try{m=Q("Verifying user and authorizing"),!s&&b.start(Q(`In progress: ${m}...`,"secondary"));const{accessKeyId:n,secretAccessKey:o,sessionToken:p}=await ve({debug:ot,baseUri:h,task:"etl-download",env:i,tenant:u,flow:c,tap:d,apikey:r}),g=new l.S3({accessKeyId:n,secretAccessKey:o,sessionToken:p});!s&&b.succeed(Q(`Finished: ${m}.`,"secondary")),m=Q("Scanning for downloadable files"),!s&&b.start(Q(`In progress: ${m}...`,"secondary"));const $=`${u}/flows/${c}/${await Qe(g,i,u,c)}/${d}/etl/`,v={Bucket:i,Prefix:$},{Contents:j}=await g.listObjectsV2(v).promise();!s&&b.succeed(Q(`Finished: ${m}.`,"secondary")),ot("s3-list-res",j);const k=j?me(j.map(e=>e.Key),{pattern:"!(.ipynb_checkpoints/*)"}):[];if(!k||0===k.length)return void(s?te({status:"success",downloadedFiles:[]}):b.warn(Q(`Warning: ${Q("Nothing to download!")}`,"secondary")));m=Q(`Downloading script files to ${Q(w,"info")}`),!s&&b.info(Q(`Info: ${m}.`,"secondary"));const _=new f({head:["File","Status"]});for await(const n of k){const o=n.substring($.length),r=t.resolve(w,o);if(ot("file",r),n.endsWith("/")){!e.existsSync(r)&&await a.mkdir(r,{recursive:!0});continue}if(!y)try{await a.stat(r),ot("exists, skipping"),_.push([o,"Skipped"]);continue}catch(e){"ENOENT"!==e.code&&H(e)}m=Q(`Downloading file: ${Q(o,"info")}`),!s&&b.start(Q(`In progress: ${m}...`,"secondary")),await a.mkdir(t.dirname(r),{recursive:!0});const c=g.getObject({Bucket:i,Key:n}).createReadStream();await a.writeFile(r,await be(c)),!s&&b.succeed(Q(`Finished: ${m}.`,"secondary")),_.push([o,"Downloaded"])}s?te({status:"success",downloadedFiles:k}):H(_.toString())}catch(e){s?te({status:"error",error:e}):(b.fail(Q(`Error: ${m}.`,"secondary")),Z(Q(`Message: ${Q(e.message)}`,"secondary")),ot(e),e&&e.response&&e.response.data&&ot("response",e.response.data)),process.exit(1)}}});const at=[Xe,nt,rt],it=oe("commands:etl"),ct="etl <action>";var lt=Object.freeze({__proto__:null,builder:async function(e){it("builder",ct);return(await pe(e)).command(at)},command:ct,desc:"Manage ETL scripts",handler:async function(e){it("handler",ct,e)}});const dt=oe("commands:flows:list"),ut="list";var ft=Object.freeze({__proto__:null,builder:async e=>(dt("builder",ut),e.option("tenant",{...ue.tenant.config})),command:ut,desc:"List flows",handler:async e=>{dt("handler",ut,e);const{hg:t,json:n,apikey:o,env:s,tenant:r}=e,{clientApiBaseUri:a}=t;let i,c=p();try{i=Q(`Retrieving ${r?`${Q(r,"info")} tenant's`:"the"} flows for environment: ${Q(s,"info")}`);const e=`${a}/${s}/flows/${r?`linked?user_id=${r}`:"supported"}`;dt("requesting:",e),!n&&c.start(Q(`In progress: ${i}...`,"secondary"));const{data:t}=await y.get(e,{headers:{"x-api-key":o}});if(!n&&c.succeed(Q(`Finished: ${i}.`,"secondary")),dt("response-data",t),!t||0===t.length)return void(n?te([]):c.warn(Q(`Warning: ${Q("No flows for specified environment and tenant")}.`,"secondary")));if(n)te(t);else{const e=new f({head:["ID","Name","Flow Type","Taps","Targets","Connectors"]});t.sort((e,t)=>(e.name||"").localeCompare(t.na