@budibase/server 3.23.10 → 3.23.11

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.
@@ -76,8 +76,8 @@
76
76
  setBackground(theme)
77
77
  })()
78
78
  </script>
79
- <script type="module" crossorigin src="/builder/assets/index-200c1478.js"></script>
80
- <link rel="stylesheet" href="/builder/assets/index-25de6765.css">
79
+ <script type="module" crossorigin src="/builder/assets/index-d2c74196.js"></script>
80
+ <link rel="stylesheet" href="/builder/assets/index-68c7076a.css">
81
81
  </head>
82
82
 
83
83
  <body id="app">
@@ -909,7 +909,7 @@ Example: return $("Score") + $("Weight")
909
909
  CONSTRAINT [PK_${o}] PRIMARY KEY (${u})`),c+=`
910
910
  );`,r.push(c)}return r.join(`
911
911
  `)}},Cie={schema:yRr,integration:kie};var Ntt=require("@aws-sdk/client-s3"),Ltt=ie(require("csvtojson")),Ftt=ie(require("stream"));var vRr={docs:"https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html",description:"Amazon Simple Storage Service (Amazon S3) is an object storage service that offers industry-leading scalability, data availability, security, and performance.",friendlyName:"Amazon S3",type:"Object store",features:{connection:!0},datasource:{region:{type:"string",required:!1,default:"us-east-1"},accessKeyId:{type:"password",required:!0},secretAccessKey:{type:"password",required:!0},endpoint:{type:"string",required:!1},signatureVersion:{type:"string",required:!1,default:"v4"}},query:{create:{type:"fields",fields:{bucket:{display:"New Bucket",type:"string",required:!0},location:{required:!0,default:"us-east-1",type:"string"},grantFullControl:{display:"Grant full control",type:"string"},grantRead:{display:"Grant read",type:"string"},grantReadAcp:{display:"Grant read ACP",type:"string"},grantWrite:{display:"Grant write",type:"string"},grantWriteAcp:{display:"Grant write ACP",type:"string"}}},read:{type:"fields",fields:{bucket:{type:"string",required:!0},delimiter:{type:"string"},marker:{type:"string"},maxKeys:{type:"number",display:"Max Keys"},prefix:{type:"string"}}},readCsv:{displayName:"Read CSV",type:"fields",readable:!0,fields:{bucket:{type:"string",required:!0},key:{type:"string",required:!0}}},delete:{type:"fields",fields:{bucket:{type:"string",required:!0},delete:{type:"json",required:!0}}}},extra:{acl:{required:!1,displayName:"ACL",type:"list",data:{create:["private","public-read","public-read-write","authenticated-read"]}}}},Die=class{static{a(this,"S3Integration")}constructor(t){this.config={forcePathStyle:t.s3ForcePathStyle||!0,credentials:{accessKeyId:t.accessKeyId,secretAccessKey:t.secretAccessKey},region:t.region,endpoint:t.endpoint},t.endpoint?(this.config.requestChecksumCalculation="WHEN_REQUIRED",this.config.responseChecksumValidation="WHEN_REQUIRED",this.config.forcePathStyle=!0):delete this.config.endpoint,this.client=new Ntt.S3(this.config)}async testConnection(){let t={connected:!1};try{await this.client.listBuckets({MaxBuckets:1}),t.connected=!0}catch(r){t.error=r.message}return t}async create(t){let r={Bucket:t.bucket,ACL:t.extra?.acl,GrantFullControl:t.grantFullControl,GrantRead:t.grantRead,GrantReadACP:t.grantReadAcp,GrantWrite:t.grantWrite,GrantWriteACP:t.grantWriteAcp};return t.location&&(r.CreateBucketConfiguration={LocationConstraint:t.location}),await this.client.createBucket(r)}async read(t){return(await this.client.listObjects({Bucket:t.bucket,Delimiter:t.delimiter,Marker:t.marker,MaxKeys:t.maxKeys,Prefix:t.prefix})).Contents}async readCsv(t){let n=(await this.client.getObject({Bucket:t.bucket,Key:t.key})).Body?.transformToWebStream();if(!n||!(n instanceof Ftt.default.Readable))throw new Error("Unable to retrieve CSV - invalid stream");let i=!1;return new Promise((o,s)=>{n.on("error",c=>{s(c)});let u=(0,Ltt.default)().fromStream(n).on("error",()=>{i=!0});n.on("end",()=>{o(u)})}).catch(o=>{throw i?new Error("Could not read CSV"):o})}async delete(t){return await this.client.deleteObjects({Bucket:t.bucket,Delete:JSON.parse(t.delete)})}},Pie={schema:vRr,integration:Die};var Utt=ie(require("airtable"));var wRr={docs:"https://airtable.com/api",description:"Airtable is a spreadsheet-database hybrid, with the features of a database but applied to a spreadsheet.",friendlyName:"Airtable",type:"Spreadsheet",features:{connection:!0},datasource:{apiKey:{type:"password",default:"enter api key",required:!0},base:{type:"string",default:"mybase",required:!0}},query:{create:{type:"fields",customisable:!0,fields:{table:{type:"string",required:!0}}},read:{type:"fields",fields:{table:{type:"string",required:!0},view:{type:"string",required:!0},numRecords:{type:"number",default:10}}},update:{type:"fields",customisable:!0,fields:{id:{display:"Record ID",type:"string",required:!0},table:{type:"string",required:!0}}},delete:{type:"json"}}},Nie=class{static{a(this,"AirtableIntegration")}constructor(t){this.config=t,this.client=new Utt.default(t).base(t.base)}async testConnection(){let t=Date.now().toString();try{return await this.client.makeRequest({path:`/${t}`}),{connected:!0}}catch(r){return r.message===`Could not find table ${t} in application ${this.config.base}`?{connected:!0}:{connected:!1,error:r.message}}}async create(t){let{table:r,json:n}=t;try{return await this.client(r).create([{fields:n}])}catch(i){throw console.error("Error writing to airtable",i),i}}async read(t){try{return(await this.client(t.table).select({maxRecords:t.numRecords||10,view:t.view}).firstPage()).map(({fields:n})=>n)}catch(r){return console.error("Error writing to airtable",r),[]}}async update(t){let{table:r,id:n,json:i}=t;try{return await this.client(r).update([{id:n,fields:i}])}catch(o){throw console.error("Error writing to airtable",o),o}}async delete(t){try{return await this.client(t.table).destroy(t.ids)}catch(r){throw console.error("Error writing to airtable",r),r}}},Lie={schema:wRr,integration:Nie};var Mtt=ie(require("mysql2/promise"));var ERr=Vt.Sql,_Rr={docs:"https://github.com/sidorares/node-mysql2",plus:!0,friendlyName:"MySQL",type:"Relational",description:"MySQL Database Service is a fully managed database service to deploy cloud-native applications. ",features:{connection:!0,fetch_table_names:!0,export_schema:!0},datasource:{host:{type:"string",default:To,required:!0},port:{type:"number",default:3306,required:!1},user:{type:"string",default:"root",required:!0},password:{type:"password",default:"root",required:!0},database:{type:"string",required:!0},ssl:{type:"object",required:!1},rejectUnauthorized:{type:"boolean",default:!0,required:!1}},query:{create:{type:"sql"},read:{type:"sql"},update:{type:"sql"},delete:{type:"sql"}}},SRr=a(function(e,t){return e.type=="DATETIME"||e.type==="DATE"||e.type==="TIMESTAMP"||e.type==="LONGLONG"?e.string():e.type==="BIT"&&e.length===1?e.buffer()?.[0]:t()},"defaultTypeCasting");function xRr(e){for(let t=0;t<e.length;t++){let r=e[t];if(typeof r!="string")continue;let n=r.match(pet);if(n&&n[0]!==""&&!isNaN(Number(n[0])))e[t]=parseFloat(r);else if(det(r)){let i;i=new Date(r),isNaN(i)&&(i=r),e[t]=i}}return e}a(xRr,"bindingTypeCoerce");var Fie=class extends ERr{constructor(r){super("mysql2");this.config=r,r.ssl&&Object.keys(r.ssl).length===0&&delete r.ssl,r.rejectUnauthorized!=null&&!r.rejectUnauthorized&&r.ssl&&typeof r.ssl!="string"&&(r.ssl.rejectUnauthorized=r.rejectUnauthorized),delete r.rejectUnauthorized,this.config={...r,typeCast:SRr,multipleStatements:!0,timezone:"Z"}}static{a(this,"MySQLIntegration")}async testConnection(){let r={connected:!1};try{let[n]=await this.internalQuery({sql:"SELECT 1+1 AS checkRes"},{connect:!0});r.connected=n?.checkRes==2}catch(n){let i=kb("MYSQL",n.errno);i?r.error=i:r.error=n.message}return r}getBindingIdentifier(){return"?"}getStringConcat(r){return`concat(${r.join(", ")})`}defineTypeCastingFromSchema(r){r&&(this.config.typeCast=function(n,i){if(r[n.name]?.name===n.name&&["LONGLONG","NEWDECIMAL","DECIMAL"].includes(n.type))if(r[n.name]?.type==="number"){let o=n.string();return o?Number(o):null}else return n.string();return n.type=="DATETIME"||n.type==="DATE"||n.type==="TIMESTAMP"?n.string():n.type==="BIT"&&n.length===1?n.buffer()?.[0]:i()})}async connect(){this.client=await Mtt.default.createConnection(this.config),(await this.internalQuery({sql:"SELECT VERSION();"},{connect:!1}))?.[0]?.["VERSION()"]?.toLowerCase().includes("mariadb")&&this.setExtendedSqlClient("mariadb")}async disconnect(){await this.client.end()}async internalQuery(r,n={connect:!0,disableCoercion:!1}){try{n?.connect&&await this.connect();let i=r.bindings||[],o=n?.disableCoercion?i:xRr(i);return this.log(r.sql,o),(await this.client.query(r.sql,o))[0]}catch(i){let o=kb("MYSQL",i.errno);throw o?new Error(o,{cause:i}):i}finally{n?.connect&&this.client&&await this.disconnect()}}async buildSchema(r,n){let i={};await this.connect();try{let u=await this.queryTableNames();for(let c of u){let l=[],f={},p=await this.internalQuery({sql:`DESCRIBE \`${c}\`;`},{connect:!1});for(let d of p){let h=d.Field;d.Key==="PRI"&&l.indexOf(d.Key)===-1&&l.push(h);let m=d.Default!=null,g=typeof d.Extra=="string"&&(d.Extra==="auto_increment"||d.Extra.toLowerCase().includes("generated")),y=d.Null!=="YES";f[h]=gm({name:h,autocolumn:g,presence:y&&!g&&!m,externalType:d.Type,options:d.Type.startsWith("enum")?d.Type.substring(6,d.Type.length-2).split("','"):void 0})}i[c]||(i[c]={type:"table",_id:vs(r,c),sourceId:r,sourceType:"external",primary:l,name:c,schema:f})}}finally{await this.disconnect()}let o=wf(i,n),s=Ef(i);return{tables:o,errors:s}}async queryTableNames(){return(await this.internalQuery({sql:"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = 'BASE TABLE'"},{connect:!1})).map(n=>n.TABLE_NAME)}async getTableNames(){await this.connect();try{return this.queryTableNames()}finally{await this.disconnect()}}async queryViewNames(){return(await this.internalQuery({sql:"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = DATABASE()"},{connect:!1})).map(n=>n.TABLE_NAME)}async getViewNames(){await this.connect();try{return this.queryViewNames()}finally{await this.disconnect()}}async create(r){let n=await this.internalQuery(Ni(r));return n.length?n:[{created:!0}]}async read(r){return this.internalQuery(Ni(r))}async update(r){let n=await this.internalQuery(Ni(r));return n.length?n:[{updated:!0}]}async delete(r){let n=await this.internalQuery(Ni(r));return n.length?n:[{deleted:!0}]}async query(r){await this.connect();try{let n=a(o=>this.internalQuery(o,{connect:!1,disableCoercion:!0}),"queryFn"),i=a(o=>Array.isArray(o)?this.convertJsonStringColumns(r.table,o,r.tableAliases):o,"processFn");return await this.queryWithReturning(r,n,i)}finally{await this.disconnect()}}async getExternalSchema(){try{let[r]=await this.internalQuery({sql:`SHOW CREATE DATABASE IF NOT EXISTS \`${this.config.database}\``}),n=[r["Create Database"]],i=await this.internalQuery({sql:"SHOW TABLES"});for(let o of i){let s=o[`Tables_in_${this.config.database}`],c=(await this.internalQuery({sql:`SHOW CREATE TABLE \`${s}\``}))[0]["Create Table"];n.push(c)}return n.join(`;
912
- `)+";"}finally{this.disconnect()}}},Uie={schema:_Rr,integration:Fie};var gB=require("arangojs");var TRr={docs:"https://github.com/arangodb/arangojs",friendlyName:"ArangoDB",type:"Non-relational",description:"ArangoDB is a scalable open-source multi-model database natively supporting graph, document and search. All supported data models & access patterns can be combined in queries allowing for maximal flexibility. ",features:{connection:!0},datasource:{url:{type:"string",default:"http://localhost:8529",required:!0},username:{type:"string",default:"root",required:!0},password:{type:"password",required:!0},databaseName:{type:"string",default:"_system",required:!0},collection:{type:"string",required:!0}},query:{read:{type:"sql"},create:{type:"json"}}},Mie=class{static{a(this,"ArangoDBIntegration")}constructor(t){let r={url:t.url,databaseName:t.databaseName,auth:{username:t.username,password:t.password}};this.config=t,this.client=new gB.Database(r)}async testConnection(){let t={connected:!1};try{await this.client.get(),t.connected=!0}catch(r){t.error=r.message}return t}async read(t){try{return(await this.client.query(t.sql)).all()}catch(r){throw console.error("Error querying arangodb",r.message),r}finally{this.client.close()}}async create(t){let r=this.client.collection(this.config.collection);try{return(await this.client.query(gB.aql`INSERT ${t.json} INTO ${r} RETURN NEW`)).all()}catch(n){throw console.error("Error querying arangodb",n.message),n}finally{this.client.close()}}},jie={schema:TRr,integration:Mie};var Btt=ie(require("lodash/get")),Bie=ie(require("querystring"));var yB=require("perf_hooks"),qie=require("url");var qtt=require("content-disposition"),$tt=ie(require("path")),ztt=require("xml2js");function jtt(e,t){let r=e.get("content-type")||"",n=e.get("content-disposition")||"";if(n){let i=/"(?:[^"\\]|\\.)*"|;/g,o=null,s=!1;for(;(o=i.exec(n))!==null;)o[0]===";"&&(s=!0);if(!s)return{contentDisposition:`attachment; ${n}`,contentType:r}}else if(t?.downloadImages&&r.startsWith("image/"))return{contentDisposition:`attachment; filename="image.${r.split("/")[1]}"`,contentType:r};return{contentDisposition:n,contentType:r}}a(jtt,"getAttachmentHeaders");var bm=require("undici");var CI={path:{type:"string",display:"URL"},queryString:{type:"string"},headers:{type:"object"},enabledHeaders:{type:"object"},requestBody:{type:"json"},bodyType:{type:"string",enum:Object.values(uq)},pagination:{type:"object"}},RRr={docs:"https://github.com/node-fetch/node-fetch",description:"With the REST API datasource, you can connect, query and pull data from multiple REST APIs. You can then use the retrieved data to build apps.",friendlyName:"REST API",type:"API",datasource:{url:{type:"string",default:"",required:!1,deprecated:!0},defaultHeaders:{type:"object",required:!1,default:{}},rejectUnauthorized:{display:"Reject Unauthorized",type:"boolean",default:!0,required:!1},downloadImages:{display:"Download images",type:"boolean",default:!0,required:!1}},query:{create:{readable:!0,displayName:"POST",type:"fields",fields:CI},read:{displayName:"GET",readable:!0,type:"fields",fields:CI},update:{displayName:"PUT",readable:!0,type:"fields",fields:CI},patch:{displayName:"PATCH",readable:!0,type:"fields",fields:CI},delete:{displayName:"DELETE",type:"fields",fields:CI}}},$ie=a(e=>Object.prototype.toString.call(e)==="[object Object]","isPlainRecord"),ORr=a(e=>{if(e==null)return{bodyString:"",bodyObject:{},jsonValue:void 0};if(typeof e=="string")try{let t=JSON.parse(e);return $ie(t)?{bodyString:e,bodyObject:t,jsonValue:t}:{bodyString:e,bodyObject:{},jsonValue:t}}catch(t){return{bodyString:e,bodyObject:{},parseError:t}}return Buffer.isBuffer(e)?{bodyString:e.toString(),bodyObject:{},jsonValue:e.toString()}:e instanceof Uint8Array?{bodyString:Buffer.from(e).toString(),bodyObject:{},jsonValue:Buffer.from(e).toString()}:$ie(e)?{bodyString:JSON.stringify(e),bodyObject:e,jsonValue:e}:Array.isArray(e)?{bodyString:JSON.stringify(e),bodyObject:{},jsonValue:e}:{bodyString:JSON.stringify(e),bodyObject:{},jsonValue:void 0}},"normaliseBody"),zie=class{constructor(t){this.headers={};this.startTimeMs=yB.performance.now();this.config=t}static{a(this,"RestIntegration")}async parseResponse(t,r){let n,i,o={},s,{contentType:u,contentDisposition:c}=jtt(t.headers,{downloadImages:this.config.downloadImages}),l=t.headers.get("content-length"),f=t.status>=200&&t.status<300;(c.includes("filename")||c.includes("attachment")||c.includes("form-data"))&&f&&(s=$tt.default.basename((0,qtt.parse)(c).parameters?.filename)||"");let p=!1,d;try{if(s)return Het(t,s,this.startTimeMs);{d=t.text?await t.text():"",!l&&d&&(l=Buffer.byteLength(d,"utf8").toString());let y=l&&parseInt(l)>0||d.length>0;if(t.status===204)n=[],i="";else if(y&&u.includes("application/json"))p=!0,n=JSON.parse(d),i=d;else if(y&&u.includes("text/xml")||u.includes("application/xml")){p=!0;let b=await Get(d);n=b.data,i=b.rawXml}else n=d,i=d}}catch(y){if(p)n=d,i=d;else throw new Error(`Failed to parse response body: ${y}`)}let h=Qj(l||"0"),m=`${Math.round(yB.performance.now()-this.startTimeMs)}ms`;for(let[y,b]of t.headers.entries())o[y]=b;let g;return r?.responseParam&&(g=(0,Btt.default)(n,r.responseParam)),{data:n,info:{code:t.status,size:h,time:m},extra:{raw:i,headers:o},pagination:{cursor:g}}}getUrl(t,r,n,i){if(n?.location==="query"&&i){let{pageParam:u,sizeParam:c}=n,l=new qie.URLSearchParams;u&&i.page!=null&&l.append(u,i.page),c&&i.limit!=null&&l.append(c,String(i.limit));let f=l.toString();f&&(r=`${f}&${r}`)}if(r){let u=Bie.default.decode(r),c={};for(let[l,f]of Object.entries(u))f!==""&&f!=null&&(c[l]=f);Object.keys(c).length>0?r="?"+Bie.default.encode(c):r=""}let o=`${t}${r}`,s=o;return this.config.url&&!o.startsWith("http")&&(s=this.config.url?`${this.config.url}/${o}`:o),s.startsWith("http")||(s=`http://${s}`),s}addBody(t,r,n,i,o){if(n.headers||(n.headers={}),t==="none")return n;let s,u={},c="",l;if(r!=null){let{bodyString:p,bodyObject:d,parseError:h,jsonValue:m}=ORr(r);c=p,u=d,s=h,l=m}let f=a(p=>{i?.location==="body"&&(i?.pageParam&&o?.page!=null&&p(i.pageParam,o.page),i?.sizeParam&&o?.limit!=null&&p(i.sizeParam,o.limit))},"addPaginationToBody");switch(t){case"text":n.body=c;break;case"encoded":{let p=new qie.URLSearchParams;for(let[d,h]of Object.entries(u))p.append(d,String(h));f((d,h)=>{h!=null&&p.append(d,String(h))}),n.body=p;break}case"form":{let p=new bm.FormData,d=a((g,y)=>{if(y==null){p.append(g,"");return}if(typeof y=="string"){p.append(g,y);return}if(y instanceof Blob){p.append(g,y);return}if(Buffer.isBuffer(y)){p.append(g,Buffer.from(y).toString());return}if(y instanceof Uint8Array){p.append(g,Buffer.from(y).toString());return}p.append(g,String(y))},"appendFormValue");for(let[g,y]of Object.entries(u))d(g,y);f((g,y)=>{y!=null&&d(g,y)});let m=p.getHeaders?.();if(m){let y=a(()=>{if(!n.headers){let b={};return n.headers=b,b}if(Array.isArray(n.headers)){let b=n.headers.reduce((v,[w,x])=>(v[w]=x,v),{});return n.headers=b,b}if(n.headers instanceof bm.Headers){let b={};return n.headers.forEach((v,w)=>{b[w]=v}),n.headers=b,b}return n.headers},"ensureHeaderObject")();for(let[b,v]of Object.entries(m)){let w=b.toLowerCase();if(Object.keys(y).find(I=>I.toLowerCase()===w)||typeof v>"u"||v===null)continue;let T=Array.isArray(v)?v.join(", "):String(v);y[b]=T}}n.body=p;break}case"xml":u!=null&&Object.keys(u).length&&(c=new ztt.Builder().buildObject(u)),n.body=c,n.headers["Content-Type"]="application/xml";break;case"json":{if(s)throw"Invalid JSON for request body";let p;if(typeof l<"u")p=l;else if(c)try{p=JSON.parse(c)}catch{p=u}else p=u;if(i?.location==="body"&&$ie(p)){let d={...p};i.pageParam&&o?.page!=null&&(d[i.pageParam]=o.page),i.sizeParam&&o?.limit!=null&&(d[i.sizeParam]=o.limit),p=d}else if(i?.location==="body"){let d={...u};i.pageParam&&o?.page!=null&&(d[i.pageParam]=o.page),i.sizeParam&&o?.limit!=null&&(d[i.sizeParam]=o.limit),Object.keys(d).length>0&&(p=d)}n.body=typeof p=="string"?p:JSON.stringify(p),n.headers["Content-Type"]="application/json";break}}return n}async getAuthHeaders(t,r){if(!t)return{};if(r==="oauth2")return{Authorization:await H.oauth2.getToken(t)};if(!this.config.authConfigs)return{};let n={},i=this.config.authConfigs.filter(o=>o._id===t)[0];if(i){let{type:o,config:s}=i;switch(o){case"basic":n.Authorization=`Basic ${Buffer.from(`${s.username}:${s.password}`).toString("base64")}`;break;case"bearer":n.Authorization=`Bearer ${s.token}`;break;default:throw Ut.unreachable(o)}}return n}async _req(t,r=!0){let{path:n="",queryString:i="",headers:o={},method:s="GET",disabledHeaders:u,bodyType:c="none",requestBody:l,authConfigId:f,authConfigType:p,pagination:d,paginationValues:h}=t,m=await this.getAuthHeaders(f,p);if(this.headers={...this.config.defaultHeaders||{},...o,...m},u)for(let x of Object.keys(this.headers))u[x]&&delete this.headers[x];let g={method:s,headers:this.headers};g=this.addBody(c,l,g,d,h),this.config.legacyHttpParser&&(g.extraHttpOptions={insecureHTTPParser:!0}),this.startTimeMs=yB.performance.now();let y=this.getUrl(n,i,d,h);if(await GU.isBlacklisted(y))throw new Error("Cannot connect to URL.");let b=!!Oe.REST_REJECT_UNAUTHORIZED,v=WZe({rejectUnauthorized:b});if(v)console.log("[rest integration] Using proxy for request",{url:y,hasDispatcher:!0,isHttpsUrl:y.startsWith("https://"),rejectUnauthorized:b,configRejectUnauthorized:this.config.rejectUnauthorized,proxyUri:process.env.GLOBAL_AGENT_HTTPS_PROXY||process.env.GLOBAL_AGENT_HTTP_PROXY||process.env.HTTPS_PROXY||process.env.HTTP_PROXY}),g.dispatcher=v;else if(b){let x=new bm.Agent({connect:{rejectUnauthorized:!1}});g.dispatcher=x}let w;try{w=await(0,bm.fetch)(y,g)}catch(x){let T=x;throw console.log("[rest integration] Fetch error details",{url:y,error:T.message,cause:T.cause?.message,code:T.cause?.code,hasDispatcher:!!g.dispatcher,isHttpsUrl:y.startsWith("https://"),rejectUnauthorized:b}),T.cause?.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||T.cause?.code==="CERT_UNTRUSTED"||T.cause?.code==="SELF_SIGNED_CERT_IN_CHAIN"?new Error(`SSL certificate verification failed for ${y}. Consider setting rejectUnauthorized to false if using self-signed certificates. Original error: ${T.message}`):T.cause?.code==="ECONNREFUSED"&&g.dispatcher?new Error(`Connection refused when using proxy. Check proxy configuration and ensure the proxy server is accessible. Original error: ${T.message}`):T}return w.status===401&&p==="oauth2"&&r?(await H.oauth2.cleanStoredToken(f),await this._req(t,!1)):await this.parseResponse(w,d)}async create(t){return this._req({...t,method:"POST"})}async read(t){return this._req({...t,method:"GET"})}async update(t){return this._req({...t,method:"PUT"})}async patch(t){return this._req({...t,method:"PATCH"})}async delete(t){return this._req({...t,method:"DELETE"})}},Wie={schema:RRr,integration:zie};var Wtt=ie(require("dd-trace")),Gtt=require("google-auth-library"),Htt=require("google-spreadsheet"),Vtt=ie(require("node-fetch"));var IRr={string:!0,formula:!0,ai:!0,number:!0,longform:!0,datetime:!0,options:!0,boolean:!0,barcodeqr:!0,bb_reference:!0,bb_reference_single:!0,array:!1,attachment:!1,attachment_single:!1,link:!1,auto:!1,json:!1,internal:!1,bigint:!1,signature_single:!1},kRr=Object.entries(IRr).filter(([e,t])=>t).map(([e])=>e),CRr={plus:!0,auth:{type:"google"},relationships:!1,docs:"https://developers.google.com/sheets/api/quickstart/nodejs",description:"Create and collaborate on online spreadsheets in real-time and from any device.",friendlyName:"Google Sheets",type:"Spreadsheet",features:{connection:!0,fetch_table_names:!0},datasource:{spreadsheetId:{display:"Spreadsheet URL",type:"string",required:!0}},query:{create:{type:"fields",fields:{sheet:{type:"string",required:!0},row:{type:"json",required:!0}}},read:{type:"fields",fields:{sheet:{type:"string",required:!0}}},update:{type:"fields",fields:{sheet:{type:"string",required:!0},rowIndex:{type:"string",required:!0},row:{type:"json",required:!0}}},delete:{type:"fields",fields:{sheet:{type:"string",required:!0},rowIndex:{type:"number",required:!0}}}}},Gie=class{constructor(t){this.client=void 0;this.config=t,this.spreadsheetId=this.cleanSpreadsheetUrl(this.config.spreadsheetId)}static{a(this,"GoogleSheetsIntegration")}async testConnection(){try{return await this.connect(),{connected:!0}}catch(t){return{connected:!1,error:t.message}}}getBindingIdentifier(){return""}getStringConcat(t){return""}cleanSpreadsheetUrl(t){if(!t)throw new Error("You must set a spreadsheet ID in your configuration to fetch tables.");let r=t.split("/");return r.length>5?r[5]:t}async fetchAccessToken(t){let r=await(0,Vtt.default)("https://www.googleapis.com/oauth2/v4/token",{method:"POST",body:JSON.stringify({...t,grant_type:"refresh_token"}),headers:{"Content-Type":"application/json"}}),n=await r.json();if(r.status!==200)throw new Error(`Error authenticating with google sheets. ${n.error_description}`);return n}async connect(){try{let t=z.getCurrentContext(),r=t?.googleSheets?.oauthClient;if(!r){await Hie(this.config);let i=await ii.getGoogleDatasourceConfig();if(!i)throw new Se("Google config not found",400);r=new Gtt.OAuth2Client({clientId:i.clientID,clientSecret:i.clientSecret});let o=await this.fetchAccessToken({client_id:i.clientID,client_secret:i.clientSecret,refresh_token:this.config.auth.refreshToken});r.setCredentials({refresh_token:this.config.auth.refreshToken,access_token:o.access_token}),t&&!t.googleSheets&&(t.googleSheets={oauthClient:r,clients:{}},t.cleanup=t.cleanup||[])}let n=t?.googleSheets?.clients[this.spreadsheetId];n||(n=new Htt.GoogleSpreadsheet(this.spreadsheetId,r),await n.loadInfo(),t?.googleSheets?.clients&&(t.googleSheets.clients[this.spreadsheetId]=n)),this.client=n}catch(t){throw t.message?.includes("operation is not supported")&&(t.message="This operation is not supported - XLSX sheets must be converted."),console.error("Error connecting to google sheets",t),t}}async getTableNames(){return await this.connect(),this.client.sheetsByIndex.map(r=>r.title)}getTableSchema(t,r,n,i){let o={type:"table",name:t,primary:[vI],schema:{},sourceId:n,sourceType:"external"};i&&(o._id=i);for(let s of r)o.schema[s]={name:s,type:"string"};return o}async buildSchema(t,r,n){if(!this.config.auth)return{tables:{},errors:{}};await this.connect();let i=this.client.sheetsByIndex.filter(c=>!n||n.includes(c.title)),o={},s={};await Ut.parallelForeach(i,async c=>{try{await c.getRows({limit:1})}catch(l){if(!(l instanceof Error))throw l;if(l.message.startsWith("No values in the header row")||l.message.startsWith("All your header cells are blank")){s[c.title]=`Failed to find a header row in sheet "${c.title}", is the first row blank?`;return}throw l}},10);for(let c of i){let l=vs(t,c.title);o[c.title]=this.getTableSchema(c.title,c.headerValues,t,l)}let u=wf(o,r);return s={...s,...Ef(u)},{tables:u,errors:s}}async query(t){let r=t.table.name;switch(t.operation){case"CREATE":return this.create({sheet:r,row:t.body});case"BULK_CREATE":return this.createBulk({sheet:r,rows:t.body});case"BULK_UPSERT":return this.createBulk({sheet:r,rows:t.body});case"READ":return this.read({...t,sheet:r});case"UPDATE":return this.update({rowIndex:t.extra?.idFilter?.equal?.rowNumber,sheet:r,row:t.body,table:t.table});case"DELETE":return this.delete({rowIndex:t.extra?.idFilter?.equal?.rowNumber,sheet:r});case"CREATE_TABLE":if(!t.table)throw new Error("attempted to create a table without specifying the table to create");return this.createTable(t.table);case"UPDATE_TABLE":if(!t.table)throw new Error("attempted to create a table without specifying the table to create");return this.updateTable(t.table);case"DELETE_TABLE":return this.deleteTable(t?.table?.name);default:throw new Error(`GSheets integration does not support "${t.operation}".`)}}buildRowObject(t,r,n){let i={rowNumber:n,_id:n.toString()};for(let o=0;o<t.length;o++)i[t[o]]=r[t[o]];return i}async createTable(t){try{await this.connect(),await this.client.addSheet({title:t.name,headerValues:Object.keys(t.schema)})}catch(r){throw console.error("Error creating new table in google sheets",r),r}}async updateTable(t){await this.connect();let r=this.client.sheetsByTitle[t.name];if(await r.loadHeaderRow(),t._rename){let n=[];for(let i of r.headerValues)i===t._rename.old?n.push(t._rename.updated):n.push(i);try{await r.setHeaderRow(n)}catch(i){throw console.error("Error updating column name in google sheets",i),i}}else{let n=[...r.headerValues];for(let[i,o]of Object.entries(t.schema)){if(!kRr.includes(o.type))throw new Error(`Column type: ${o.type} not allowed for GSheets integration.`);!r.headerValues.includes(i)&&o.type!=="formula"&&o.type!=="ai"&&n.push(i)}try{n.length>r.gridProperties.columnCount&&(await r.resize({rowCount:r.rowCount,columnCount:n.length}),this.client.resetLocalCache(),await this.client.loadInfo(),r=this.client.sheetsByTitle[t.name],await r.loadHeaderRow()),await r.setHeaderRow(n)}catch(i){throw console.error("Error updating table in google sheets",i),i}}}async deleteTable(t){try{await this.connect(),await this.client.sheetsByTitle[t].delete()}catch(r){throw console.error("Error deleting table in google sheets",r),r}}async create(t){try{await this.connect();let r=this.client.sheetsByTitle[t.sheet],n=typeof t.row=="string"?JSON.parse(t.row):t.row,i=await r.addRow(n);return[this.buildRowObject(r.headerValues,i.toObject(),i.rowNumber)]}catch(r){throw console.error("Error writing to google sheets",r),r}}async createBulk(t){try{await this.connect();let r=this.client.sheetsByTitle[t.sheet],n=[];for(let o of t.rows)n.push(typeof o=="string"?JSON.parse(o):o);return(await r.addRows(n)).map(o=>this.buildRowObject(r.headerValues,o.toObject(),o.rowNumber))}catch(r){throw console.error("Error bulk writing to google sheets",r),r}}async read(t){return await Wtt.default.trace("googlesheets.read",async r=>{r.addTags({sheet:t.sheet,filters:t.filters,sort:t.sort,paginate:t.paginate}),await this.connect();let n=Lr.hasFilters(t.filters),i=t.paginate?.limit||100,o=t.paginate?.offset||0;r.addTags({hasFilters:n,limit:i,offset:o});let s=t.paginate?.page;typeof s=="string"&&(s=parseInt(s)),s!==void 0&&(o=s*i);let u=this.client.sheetsByTitle[t.sheet];r.addTags({rowCount:u.rowCount});let c=[];t.paginate&&!n?c=await u.getRows({limit:i,offset:o}):c=await u.getRows(),r.addTags({totalRowsRead:c.length});let l=c.map(f=>this.buildRowObject(u.headerValues,f.toObject(),f.rowNumber));if(l=Lr.runQuery(l,t.filters||{}),n&&t.paginate&&(l=l.slice(o,o+i)),t.sort){Object.keys(t.sort).length!==1&&console.warn("Googlesheets does not support multiple sorting",{sortInfo:t.sort});let[f,p]=Object.entries(t.sort)[0];l=Lr.sort(l,f,p.direction,p.type)}return r.addTags({totalRowsReturned:l.length}),l})}async getRowByIndex(t,r){let n=this.client.sheetsByTitle[t],o=(await n.getRows())[r-2];return{sheet:n,row:o}}async update(t){try{await this.connect();let{sheet:r,row:n}=await this.getRowByIndex(t.sheet,t.rowIndex);if(n){let i=typeof t.row=="string"?JSON.parse(t.row):t.row;for(let o in i)if(n.set(o,i[o]),n.get(o)===null&&n.set(o,""),t.table){let{type:s,subtype:u,constraints:c}=t.table.schema[o];s==="bb_reference"&&u==="user"&&c?.type!=="array"&&Array.isArray(n.get(o))&&n.set(o,n.get(o)[0])}return await n.save(),[this.buildRowObject(r.headerValues,n.toObject(),n.rowNumber)]}else throw new Error("Row does not exist.")}catch(r){throw console.error("Error reading from google sheets",r),r}}async delete(t){await this.connect();let{row:r}=await this.getRowByIndex(t.sheet,t.rowIndex);if(r)return await r.delete(),[{deleted:t.rowIndex,[vI]:t.rowIndex}];throw new Error("Row does not exist.")}};async function Hie(e){if(e.continueSetupId){let t=z.getWorkspaceId(),r=await $t.get(`datasource:creation:${t}:google:${e.continueSetupId}`);e.auth=r.tokens,delete e.continueSetupId}}a(Hie,"setupCreationAuth");var Vie={schema:CRr,integration:Gie};var Ktt=require("@google-cloud/firestore");var DRr={docs:"https://firebase.google.com/docs/firestore/quickstart",friendlyName:"Firestore",type:"Non-relational",description:"Cloud Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud.",features:{connection:!0},datasource:{email:{type:"string",required:!0},privateKey:{type:"string",display:"Private Key",required:!0},projectId:{type:"string",display:"Project ID",required:!0},databaseId:{type:"string",display:"Database ID",required:!1,default:"(default)",placeholder:"(default)"}},query:{create:{type:"json"},read:{type:"json"},update:{type:"json"},delete:{type:"json"}},extra:{collection:{displayName:"Collection",type:"string",required:!0},filterField:{displayName:"Filter field",type:"string",required:!1},filter:{displayName:"Filter comparison",type:"list",required:!1,data:{read:["==","<","<=","!=",">=",">","array-contains","in","not-in","array-contains-any"]}},filterValue:{displayName:"Filter value",type:"string",required:!1}}},Kie=class{static{a(this,"FirebaseIntegration")}constructor(t){this.config=t,this.client=new Ktt.Firestore({projectId:t.projectId,databaseId:t.databaseId||"(default)",credentials:{client_email:t.email,private_key:t.privateKey?.replace(/\\n/g,`
912
+ `)+";"}finally{this.disconnect()}}},Uie={schema:_Rr,integration:Fie};var gB=require("arangojs");var TRr={docs:"https://github.com/arangodb/arangojs",friendlyName:"ArangoDB",type:"Non-relational",description:"ArangoDB is a scalable open-source multi-model database natively supporting graph, document and search. All supported data models & access patterns can be combined in queries allowing for maximal flexibility. ",features:{connection:!0},datasource:{url:{type:"string",default:"http://localhost:8529",required:!0},username:{type:"string",default:"root",required:!0},password:{type:"password",required:!0},databaseName:{type:"string",default:"_system",required:!0},collection:{type:"string",required:!0}},query:{read:{type:"sql"},create:{type:"json"}}},Mie=class{static{a(this,"ArangoDBIntegration")}constructor(t){let r={url:t.url,databaseName:t.databaseName,auth:{username:t.username,password:t.password}};this.config=t,this.client=new gB.Database(r)}async testConnection(){let t={connected:!1};try{await this.client.get(),t.connected=!0}catch(r){t.error=r.message}return t}async read(t){try{return(await this.client.query(t.sql)).all()}catch(r){throw console.error("Error querying arangodb",r.message),r}finally{this.client.close()}}async create(t){let r=this.client.collection(this.config.collection);try{return(await this.client.query(gB.aql`INSERT ${t.json} INTO ${r} RETURN NEW`)).all()}catch(n){throw console.error("Error querying arangodb",n.message),n}finally{this.client.close()}}},jie={schema:TRr,integration:Mie};var Btt=ie(require("lodash/get")),Bie=ie(require("querystring"));var yB=require("perf_hooks"),qie=require("url");var qtt=require("content-disposition"),$tt=ie(require("path")),ztt=require("xml2js");function jtt(e,t){let r=e.get("content-type")||"",n=e.get("content-disposition")||"";if(n){let i=/"(?:[^"\\]|\\.)*"|;/g,o=null,s=!1;for(;(o=i.exec(n))!==null;)o[0]===";"&&(s=!0);if(!s)return{contentDisposition:`attachment; ${n}`,contentType:r}}else if(t?.downloadImages&&r.startsWith("image/"))return{contentDisposition:`attachment; filename="image.${r.split("/")[1]}"`,contentType:r};return{contentDisposition:n,contentType:r}}a(jtt,"getAttachmentHeaders");var bm=require("undici");var CI={path:{type:"string",display:"URL"},queryString:{type:"string"},headers:{type:"object"},enabledHeaders:{type:"object"},requestBody:{type:"json"},bodyType:{type:"string",enum:Object.values(uq)},pagination:{type:"object"}},RRr={docs:"https://github.com/node-fetch/node-fetch",description:"With the REST API datasource, you can connect, query and pull data from multiple REST APIs. You can then use the retrieved data to build apps.",friendlyName:"REST API",type:"API",datasource:{url:{type:"string",default:"",required:!1,deprecated:!0},defaultHeaders:{type:"object",required:!1,default:{}},rejectUnauthorized:{display:"Reject Unauthorized",type:"boolean",default:!0,required:!1},downloadImages:{display:"Download images",type:"boolean",default:!0,required:!1}},query:{create:{readable:!0,displayName:"POST",type:"fields",fields:CI},read:{displayName:"GET",readable:!0,type:"fields",fields:CI},update:{displayName:"PUT",readable:!0,type:"fields",fields:CI},patch:{displayName:"PATCH",readable:!0,type:"fields",fields:CI},delete:{displayName:"DELETE",type:"fields",fields:CI}}},$ie=a(e=>Object.prototype.toString.call(e)==="[object Object]","isPlainRecord"),ORr=a(e=>{if(e==null)return{bodyString:"",bodyObject:{},jsonValue:void 0};if(typeof e=="string")try{let t=JSON.parse(e);return $ie(t)?{bodyString:e,bodyObject:t,jsonValue:t}:{bodyString:e,bodyObject:{},jsonValue:t}}catch(t){return{bodyString:e,bodyObject:{},parseError:t}}return Buffer.isBuffer(e)?{bodyString:e.toString(),bodyObject:{},jsonValue:e.toString()}:e instanceof Uint8Array?{bodyString:Buffer.from(e).toString(),bodyObject:{},jsonValue:Buffer.from(e).toString()}:$ie(e)?{bodyString:JSON.stringify(e),bodyObject:e,jsonValue:e}:Array.isArray(e)?{bodyString:JSON.stringify(e),bodyObject:{},jsonValue:e}:{bodyString:JSON.stringify(e),bodyObject:{},jsonValue:void 0}},"normaliseBody"),zie=class{constructor(t){this.headers={};this.startTimeMs=yB.performance.now();this.config=t}static{a(this,"RestIntegration")}async parseResponse(t,r){let n,i,o={},s,{contentType:u,contentDisposition:c}=jtt(t.headers,{downloadImages:this.config.downloadImages}),l=t.headers.get("content-length"),f=t.status>=200&&t.status<300;(c.includes("filename")||c.includes("attachment")||c.includes("form-data"))&&f&&(s=$tt.default.basename((0,qtt.parse)(c).parameters?.filename)||"");let p=!1,d;try{if(s)return Het(t,s,this.startTimeMs);{d=t.text?await t.text():"",!l&&d&&(l=Buffer.byteLength(d,"utf8").toString());let y=l&&parseInt(l)>0||d.length>0;if(t.status===204)n=[],i="";else if(y&&u.includes("application/json"))p=!0,n=JSON.parse(d),i=d;else if(y&&u.includes("text/xml")||u.includes("application/xml")){p=!0;let b=await Get(d);n=b.data,i=b.rawXml}else n=d,i=d}}catch(y){if(p)n=d,i=d;else throw new Error(`Failed to parse response body: ${y}`)}let h=Qj(l||"0"),m=`${Math.round(yB.performance.now()-this.startTimeMs)}ms`;for(let[y,b]of t.headers.entries())o[y]=b;let g;return r?.responseParam&&(g=(0,Btt.default)(n,r.responseParam)),{data:n,info:{code:t.status,size:h,time:m},extra:{raw:i,headers:o},pagination:{cursor:g}}}getUrl(t,r,n,i){if(n?.location==="query"&&i){let{pageParam:u,sizeParam:c}=n,l=new qie.URLSearchParams;u&&i.page!=null&&l.append(u,i.page),c&&i.limit!=null&&l.append(c,String(i.limit));let f=l.toString();f&&(r=`${f}&${r}`)}if(r){let u=Bie.default.decode(r),c={};for(let[l,f]of Object.entries(u))f!==""&&f!=null&&(c[l]=f);Object.keys(c).length>0?r="?"+Bie.default.encode(c):r=""}let o=`${t}${r}`,s=o;return this.config.url&&!o.startsWith("http")&&(s=this.config.url?`${this.config.url}/${o}`:o),s.startsWith("http")||(s=`http://${s}`),s}addBody(t,r,n,i,o){if(n.headers||(n.headers={}),t==="none")return n;let s,u={},c="",l;if(r!=null){let{bodyString:p,bodyObject:d,parseError:h,jsonValue:m}=ORr(r);c=p,u=d,s=h,l=m}let f=a(p=>{i?.location==="body"&&(i?.pageParam&&o?.page!=null&&p(i.pageParam,o.page),i?.sizeParam&&o?.limit!=null&&p(i.sizeParam,o.limit))},"addPaginationToBody");switch(t){case"text":n.body=c;break;case"encoded":{let p=new qie.URLSearchParams;for(let[d,h]of Object.entries(u))p.append(d,String(h));f((d,h)=>{h!=null&&p.append(d,String(h))}),n.body=p;break}case"form":{let p=new bm.FormData,d=a((y,b)=>{if(b==null){p.append(y,"");return}if(typeof b=="string"){p.append(y,b);return}if(b instanceof Blob){p.append(y,b);return}if(Buffer.isBuffer(b)){p.append(y,Buffer.from(b).toString());return}if(b instanceof Uint8Array){p.append(y,Buffer.from(b).toString());return}p.append(y,String(b))},"appendFormValue");for(let[y,b]of Object.entries(u))d(y,b);f((y,b)=>{b!=null&&d(y,b)});let m=a(()=>n.headers?Array.isArray(n.headers)?n.headers.reduce((b,[v,w])=>(b[v]=w,b),{}):n.headers instanceof bm.Headers?Object.fromEntries(n.headers):n.headers:{},"ensureHeaderObject")(),g=Object.keys(m).find(y=>y.toLowerCase()==="content-type");g&&delete m[g],n.headers=m,n.body=p;break}case"xml":u!=null&&Object.keys(u).length&&(c=new ztt.Builder().buildObject(u)),n.body=c,n.headers["Content-Type"]="application/xml";break;case"json":{if(s)throw"Invalid JSON for request body";let p;if(typeof l<"u")p=l;else if(c)try{p=JSON.parse(c)}catch{p=u}else p=u;if(i?.location==="body"&&$ie(p)){let d={...p};i.pageParam&&o?.page!=null&&(d[i.pageParam]=o.page),i.sizeParam&&o?.limit!=null&&(d[i.sizeParam]=o.limit),p=d}else if(i?.location==="body"){let d={...u};i.pageParam&&o?.page!=null&&(d[i.pageParam]=o.page),i.sizeParam&&o?.limit!=null&&(d[i.sizeParam]=o.limit),Object.keys(d).length>0&&(p=d)}n.body=typeof p=="string"?p:JSON.stringify(p),n.headers["Content-Type"]="application/json";break}}return n}async getAuthHeaders(t,r){if(!t)return{};if(r==="oauth2")return{Authorization:await H.oauth2.getToken(t)};if(!this.config.authConfigs)return{};let n={},i=this.config.authConfigs.filter(o=>o._id===t)[0];if(i){let{type:o,config:s}=i;switch(o){case"basic":n.Authorization=`Basic ${Buffer.from(`${s.username}:${s.password}`).toString("base64")}`;break;case"bearer":n.Authorization=`Bearer ${s.token}`;break;default:throw Ut.unreachable(o)}}return n}async _req(t,r=!0){let{path:n="",queryString:i="",headers:o={},method:s="GET",disabledHeaders:u,bodyType:c="none",requestBody:l,authConfigId:f,authConfigType:p,pagination:d,paginationValues:h}=t,m=await this.getAuthHeaders(f,p);if(this.headers={...this.config.defaultHeaders||{},...o,...m},u)for(let x of Object.keys(this.headers))u[x]&&delete this.headers[x];let g={method:s,headers:this.headers};g=this.addBody(c,l,g,d,h),this.config.legacyHttpParser&&(g.extraHttpOptions={insecureHTTPParser:!0}),this.startTimeMs=yB.performance.now();let y=this.getUrl(n,i,d,h);if(await GU.isBlacklisted(y))throw new Error("Cannot connect to URL.");let b=!!Oe.REST_REJECT_UNAUTHORIZED,v=WZe({rejectUnauthorized:b});if(v)console.log("[rest integration] Using proxy for request",{url:y,hasDispatcher:!0,isHttpsUrl:y.startsWith("https://"),rejectUnauthorized:b,configRejectUnauthorized:this.config.rejectUnauthorized,proxyUri:process.env.GLOBAL_AGENT_HTTPS_PROXY||process.env.GLOBAL_AGENT_HTTP_PROXY||process.env.HTTPS_PROXY||process.env.HTTP_PROXY}),g.dispatcher=v;else if(b){let x=new bm.Agent({connect:{rejectUnauthorized:!1}});g.dispatcher=x}let w;try{w=await(0,bm.fetch)(y,g)}catch(x){let T=x;throw console.log("[rest integration] Fetch error details",{url:y,error:T.message,cause:T.cause?.message,code:T.cause?.code,hasDispatcher:!!g.dispatcher,isHttpsUrl:y.startsWith("https://"),rejectUnauthorized:b}),T.cause?.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"||T.cause?.code==="CERT_UNTRUSTED"||T.cause?.code==="SELF_SIGNED_CERT_IN_CHAIN"?new Error(`SSL certificate verification failed for ${y}. Consider setting rejectUnauthorized to false if using self-signed certificates. Original error: ${T.message}`):T.cause?.code==="ECONNREFUSED"&&g.dispatcher?new Error(`Connection refused when using proxy. Check proxy configuration and ensure the proxy server is accessible. Original error: ${T.message}`):T}return w.status===401&&p==="oauth2"&&r?(await H.oauth2.cleanStoredToken(f),await this._req(t,!1)):await this.parseResponse(w,d)}async create(t){return this._req({...t,method:"POST"})}async read(t){return this._req({...t,method:"GET"})}async update(t){return this._req({...t,method:"PUT"})}async patch(t){return this._req({...t,method:"PATCH"})}async delete(t){return this._req({...t,method:"DELETE"})}},Wie={schema:RRr,integration:zie};var Wtt=ie(require("dd-trace")),Gtt=require("google-auth-library"),Htt=require("google-spreadsheet"),Vtt=ie(require("node-fetch"));var IRr={string:!0,formula:!0,ai:!0,number:!0,longform:!0,datetime:!0,options:!0,boolean:!0,barcodeqr:!0,bb_reference:!0,bb_reference_single:!0,array:!1,attachment:!1,attachment_single:!1,link:!1,auto:!1,json:!1,internal:!1,bigint:!1,signature_single:!1},kRr=Object.entries(IRr).filter(([e,t])=>t).map(([e])=>e),CRr={plus:!0,auth:{type:"google"},relationships:!1,docs:"https://developers.google.com/sheets/api/quickstart/nodejs",description:"Create and collaborate on online spreadsheets in real-time and from any device.",friendlyName:"Google Sheets",type:"Spreadsheet",features:{connection:!0,fetch_table_names:!0},datasource:{spreadsheetId:{display:"Spreadsheet URL",type:"string",required:!0}},query:{create:{type:"fields",fields:{sheet:{type:"string",required:!0},row:{type:"json",required:!0}}},read:{type:"fields",fields:{sheet:{type:"string",required:!0}}},update:{type:"fields",fields:{sheet:{type:"string",required:!0},rowIndex:{type:"string",required:!0},row:{type:"json",required:!0}}},delete:{type:"fields",fields:{sheet:{type:"string",required:!0},rowIndex:{type:"number",required:!0}}}}},Gie=class{constructor(t){this.client=void 0;this.config=t,this.spreadsheetId=this.cleanSpreadsheetUrl(this.config.spreadsheetId)}static{a(this,"GoogleSheetsIntegration")}async testConnection(){try{return await this.connect(),{connected:!0}}catch(t){return{connected:!1,error:t.message}}}getBindingIdentifier(){return""}getStringConcat(t){return""}cleanSpreadsheetUrl(t){if(!t)throw new Error("You must set a spreadsheet ID in your configuration to fetch tables.");let r=t.split("/");return r.length>5?r[5]:t}async fetchAccessToken(t){let r=await(0,Vtt.default)("https://www.googleapis.com/oauth2/v4/token",{method:"POST",body:JSON.stringify({...t,grant_type:"refresh_token"}),headers:{"Content-Type":"application/json"}}),n=await r.json();if(r.status!==200)throw new Error(`Error authenticating with google sheets. ${n.error_description}`);return n}async connect(){try{let t=z.getCurrentContext(),r=t?.googleSheets?.oauthClient;if(!r){await Hie(this.config);let i=await ii.getGoogleDatasourceConfig();if(!i)throw new Se("Google config not found",400);r=new Gtt.OAuth2Client({clientId:i.clientID,clientSecret:i.clientSecret});let o=await this.fetchAccessToken({client_id:i.clientID,client_secret:i.clientSecret,refresh_token:this.config.auth.refreshToken});r.setCredentials({refresh_token:this.config.auth.refreshToken,access_token:o.access_token}),t&&!t.googleSheets&&(t.googleSheets={oauthClient:r,clients:{}},t.cleanup=t.cleanup||[])}let n=t?.googleSheets?.clients[this.spreadsheetId];n||(n=new Htt.GoogleSpreadsheet(this.spreadsheetId,r),await n.loadInfo(),t?.googleSheets?.clients&&(t.googleSheets.clients[this.spreadsheetId]=n)),this.client=n}catch(t){throw t.message?.includes("operation is not supported")&&(t.message="This operation is not supported - XLSX sheets must be converted."),console.error("Error connecting to google sheets",t),t}}async getTableNames(){return await this.connect(),this.client.sheetsByIndex.map(r=>r.title)}getTableSchema(t,r,n,i){let o={type:"table",name:t,primary:[vI],schema:{},sourceId:n,sourceType:"external"};i&&(o._id=i);for(let s of r)o.schema[s]={name:s,type:"string"};return o}async buildSchema(t,r,n){if(!this.config.auth)return{tables:{},errors:{}};await this.connect();let i=this.client.sheetsByIndex.filter(c=>!n||n.includes(c.title)),o={},s={};await Ut.parallelForeach(i,async c=>{try{await c.getRows({limit:1})}catch(l){if(!(l instanceof Error))throw l;if(l.message.startsWith("No values in the header row")||l.message.startsWith("All your header cells are blank")){s[c.title]=`Failed to find a header row in sheet "${c.title}", is the first row blank?`;return}throw l}},10);for(let c of i){let l=vs(t,c.title);o[c.title]=this.getTableSchema(c.title,c.headerValues,t,l)}let u=wf(o,r);return s={...s,...Ef(u)},{tables:u,errors:s}}async query(t){let r=t.table.name;switch(t.operation){case"CREATE":return this.create({sheet:r,row:t.body});case"BULK_CREATE":return this.createBulk({sheet:r,rows:t.body});case"BULK_UPSERT":return this.createBulk({sheet:r,rows:t.body});case"READ":return this.read({...t,sheet:r});case"UPDATE":return this.update({rowIndex:t.extra?.idFilter?.equal?.rowNumber,sheet:r,row:t.body,table:t.table});case"DELETE":return this.delete({rowIndex:t.extra?.idFilter?.equal?.rowNumber,sheet:r});case"CREATE_TABLE":if(!t.table)throw new Error("attempted to create a table without specifying the table to create");return this.createTable(t.table);case"UPDATE_TABLE":if(!t.table)throw new Error("attempted to create a table without specifying the table to create");return this.updateTable(t.table);case"DELETE_TABLE":return this.deleteTable(t?.table?.name);default:throw new Error(`GSheets integration does not support "${t.operation}".`)}}buildRowObject(t,r,n){let i={rowNumber:n,_id:n.toString()};for(let o=0;o<t.length;o++)i[t[o]]=r[t[o]];return i}async createTable(t){try{await this.connect(),await this.client.addSheet({title:t.name,headerValues:Object.keys(t.schema)})}catch(r){throw console.error("Error creating new table in google sheets",r),r}}async updateTable(t){await this.connect();let r=this.client.sheetsByTitle[t.name];if(await r.loadHeaderRow(),t._rename){let n=[];for(let i of r.headerValues)i===t._rename.old?n.push(t._rename.updated):n.push(i);try{await r.setHeaderRow(n)}catch(i){throw console.error("Error updating column name in google sheets",i),i}}else{let n=[...r.headerValues];for(let[i,o]of Object.entries(t.schema)){if(!kRr.includes(o.type))throw new Error(`Column type: ${o.type} not allowed for GSheets integration.`);!r.headerValues.includes(i)&&o.type!=="formula"&&o.type!=="ai"&&n.push(i)}try{n.length>r.gridProperties.columnCount&&(await r.resize({rowCount:r.rowCount,columnCount:n.length}),this.client.resetLocalCache(),await this.client.loadInfo(),r=this.client.sheetsByTitle[t.name],await r.loadHeaderRow()),await r.setHeaderRow(n)}catch(i){throw console.error("Error updating table in google sheets",i),i}}}async deleteTable(t){try{await this.connect(),await this.client.sheetsByTitle[t].delete()}catch(r){throw console.error("Error deleting table in google sheets",r),r}}async create(t){try{await this.connect();let r=this.client.sheetsByTitle[t.sheet],n=typeof t.row=="string"?JSON.parse(t.row):t.row,i=await r.addRow(n);return[this.buildRowObject(r.headerValues,i.toObject(),i.rowNumber)]}catch(r){throw console.error("Error writing to google sheets",r),r}}async createBulk(t){try{await this.connect();let r=this.client.sheetsByTitle[t.sheet],n=[];for(let o of t.rows)n.push(typeof o=="string"?JSON.parse(o):o);return(await r.addRows(n)).map(o=>this.buildRowObject(r.headerValues,o.toObject(),o.rowNumber))}catch(r){throw console.error("Error bulk writing to google sheets",r),r}}async read(t){return await Wtt.default.trace("googlesheets.read",async r=>{r.addTags({sheet:t.sheet,filters:t.filters,sort:t.sort,paginate:t.paginate}),await this.connect();let n=Lr.hasFilters(t.filters),i=t.paginate?.limit||100,o=t.paginate?.offset||0;r.addTags({hasFilters:n,limit:i,offset:o});let s=t.paginate?.page;typeof s=="string"&&(s=parseInt(s)),s!==void 0&&(o=s*i);let u=this.client.sheetsByTitle[t.sheet];r.addTags({rowCount:u.rowCount});let c=[];t.paginate&&!n?c=await u.getRows({limit:i,offset:o}):c=await u.getRows(),r.addTags({totalRowsRead:c.length});let l=c.map(f=>this.buildRowObject(u.headerValues,f.toObject(),f.rowNumber));if(l=Lr.runQuery(l,t.filters||{}),n&&t.paginate&&(l=l.slice(o,o+i)),t.sort){Object.keys(t.sort).length!==1&&console.warn("Googlesheets does not support multiple sorting",{sortInfo:t.sort});let[f,p]=Object.entries(t.sort)[0];l=Lr.sort(l,f,p.direction,p.type)}return r.addTags({totalRowsReturned:l.length}),l})}async getRowByIndex(t,r){let n=this.client.sheetsByTitle[t],o=(await n.getRows())[r-2];return{sheet:n,row:o}}async update(t){try{await this.connect();let{sheet:r,row:n}=await this.getRowByIndex(t.sheet,t.rowIndex);if(n){let i=typeof t.row=="string"?JSON.parse(t.row):t.row;for(let o in i)if(n.set(o,i[o]),n.get(o)===null&&n.set(o,""),t.table){let{type:s,subtype:u,constraints:c}=t.table.schema[o];s==="bb_reference"&&u==="user"&&c?.type!=="array"&&Array.isArray(n.get(o))&&n.set(o,n.get(o)[0])}return await n.save(),[this.buildRowObject(r.headerValues,n.toObject(),n.rowNumber)]}else throw new Error("Row does not exist.")}catch(r){throw console.error("Error reading from google sheets",r),r}}async delete(t){await this.connect();let{row:r}=await this.getRowByIndex(t.sheet,t.rowIndex);if(r)return await r.delete(),[{deleted:t.rowIndex,[vI]:t.rowIndex}];throw new Error("Row does not exist.")}};async function Hie(e){if(e.continueSetupId){let t=z.getWorkspaceId(),r=await $t.get(`datasource:creation:${t}:google:${e.continueSetupId}`);e.auth=r.tokens,delete e.continueSetupId}}a(Hie,"setupCreationAuth");var Vie={schema:CRr,integration:Gie};var Ktt=require("@google-cloud/firestore");var DRr={docs:"https://firebase.google.com/docs/firestore/quickstart",friendlyName:"Firestore",type:"Non-relational",description:"Cloud Firestore is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud.",features:{connection:!0},datasource:{email:{type:"string",required:!0},privateKey:{type:"string",display:"Private Key",required:!0},projectId:{type:"string",display:"Project ID",required:!0},databaseId:{type:"string",display:"Database ID",required:!1,default:"(default)",placeholder:"(default)"}},query:{create:{type:"json"},read:{type:"json"},update:{type:"json"},delete:{type:"json"}},extra:{collection:{displayName:"Collection",type:"string",required:!0},filterField:{displayName:"Filter field",type:"string",required:!1},filter:{displayName:"Filter comparison",type:"list",required:!1,data:{read:["==","<","<=","!=",">=",">","array-contains","in","not-in","array-contains-any"]}},filterValue:{displayName:"Filter value",type:"string",required:!1}}},Kie=class{static{a(this,"FirebaseIntegration")}constructor(t){this.config=t,this.client=new Ktt.Firestore({projectId:t.projectId,databaseId:t.databaseId||"(default)",credentials:{client_email:t.email,private_key:t.privateKey?.replace(/\\n/g,`
913
913
  `)}})}async testConnection(){try{return await this.client.listCollections(),{connected:!0}}catch(t){return{connected:!1,error:t.message}}}async create(t){try{let r=this.client.collection(t.extra.collection).doc();return await r.set({...t.json,id:r.id}),(await r.get()).data()}catch(r){throw console.error("Error writing to Firestore",r),r}}async read(t){try{let r,n=this.client.collection(t.extra.collection);t.extra.filterField&&t.extra.filter&&t.extra.filterValue?r=await n.where(t.extra.filterField,t.extra.filter,t.extra.filterValue).get():r=await n.get();let i=[];return r.forEach(o=>i.push(o.data())),i}catch(r){throw console.error("Error querying Firestore",r),r}}async update(t){try{return await this.client.collection(t.extra.collection).doc(t.json.id).update(t.json),(await this.client.collection(t.extra.collection).doc(t.json.id).get()).data()}catch(r){throw console.error("Error writing to Firestore",r),r}}async delete(t){try{return await this.client.collection(t.extra.collection).doc(t.json.id).delete(),!0}catch(r){throw console.error("Error deleting from Firestore",r),r}}},Qie={schema:DRr,integration:Kie};var Qtt=ie(require("ioredis"));var PRr={docs:"https://redis.io/docs/",description:"Redis is a caching tool, providing powerful key-value store capabilities.",friendlyName:"Redis",type:"Non-relational",features:{connection:!0},datasource:{host:{type:"string",required:!0,default:To},port:{type:"number",required:!0,default:6379},username:{type:"string",required:!1},password:{type:"password",required:!1},db:{type:"number",required:!1,display:"DB",default:0}},query:{create:{type:"fields",fields:{key:{type:"string",required:!0},value:{type:"string",required:!0},ttl:{type:"number"}}},read:{readable:!0,type:"fields",fields:{key:{type:"string",required:!0}}},delete:{type:"fields",fields:{key:{type:"string",required:!0}}},command:{readable:!0,displayName:"Redis Command",type:"json"}}},Yie=class{static{a(this,"RedisIntegration")}constructor(t){this.config=t,this.client=new Qtt.default({host:this.config.host,port:this.config.port,username:this.config.username,password:this.config.password,db:this.config.db})}async testConnection(){let t={connected:!1};try{await this.client.ping(),t.connected=!0}catch(r){t.error=r.message}finally{await this.disconnect()}return t}async disconnect(){return this.client.quit()}async redisContext(t){try{return await t()}catch(r){throw new Error(`Redis error: ${r}`)}finally{await this.disconnect()}}async create(t){return this.redisContext(async()=>{let r=await this.client.set(t.key,t.value);return t.ttl&&await this.client.expire(t.key,t.ttl),r})}async read(t){return this.redisContext(async()=>await this.client.get(t.key))}async delete(t){return this.redisContext(async()=>await this.client.del(t.key))}async command(t){return this.redisContext(async()=>{let r=t.json.trim().split(`
914
914
  `),n=[],i;for(let u of r){let c=u.trim().match(/".*"/);c?.[0]?i=[...u.substring(0,u.indexOf(c[0])-1).trim().split(" "),c?.[0]]:i=u.trim().split(" "),i[0]=i[0].toLowerCase(),n.push(i)}return(await this.client.pipeline(n).exec())?.map(u=>{if(typeof u=="string")return u;if(Array.isArray(u))return u[1]})})}},Jie={schema:PRr,integration:Yie};var Ytt=ie(require("snowflake-sdk")),Jtt=require("util");var NRr={docs:"https://developers.snowflake.com/",description:"Snowflake is a solution for data warehousing, data lakes, data engineering, data science, data application development, and securely sharing and consuming shared data.",friendlyName:"Snowflake",type:"Relational",features:{connection:!0},datasource:{account:{type:"string",required:!0},username:{type:"string",required:!0},password:{type:"password",required:!0},role:{type:"string"},warehouse:{type:"string",required:!0},database:{type:"string",required:!0},schema:{type:"string",required:!0}},query:{create:{type:"sql"},read:{type:"sql"},update:{type:"sql"},delete:{type:"sql"}}},Xie=class{static{a(this,"SnowflakePromise")}constructor(t){this.config=t}async connect(){return this.client?.isUp()?void 0:(this.client=Ytt.default.createConnection(this.config),(0,Jtt.promisify)(this.client.connect.bind(this.client))())}async execute(t){return new Promise((r,n)=>{if(!this.client)throw Error("No snowflake client present to execute query. Run connect() first to initialise.");this.client.execute({sqlText:t,complete:function(i,o,s){if(i)return n(i);r(s)}})})}},Zie=class{static{a(this,"SnowflakeIntegration")}constructor(t){this.client=new Xie(t)}async testConnection(){try{return await this.client.connect(),{connected:!0}}catch(t){return{connected:!1,error:t.message}}}async internalQuery(t){await this.client.connect();try{return await this.client.execute(t.sql)}catch(r){throw r?.message.split(":")[1]||r?.message}}async create(t){return this.internalQuery(t)}async read(t){return this.internalQuery(t)}async update(t){return this.internalQuery(t)}async delete(t){return this.internalQuery(t)}},eae={schema:NRr,integration:Zie};var vm=ie(require("oracledb"));var LRr=Vt.Sql;vm.default.outFormat=vm.default.OUT_FORMAT_OBJECT;var FRr={docs:"https://github.com/oracle/node-oracledb",plus:!0,friendlyName:"Oracle",type:"Relational",description:"Oracle Database is an object-relational database management system developed by Oracle Corporation",features:{connection:!0,fetch_table_names:!0},datasource:{host:{type:"string",default:To,required:!0},port:{type:"number",required:!0,default:1521},database:{type:"string",required:!0,display:"Service Name"},user:{type:"string",required:!0},password:{type:"password",required:!0}},query:{create:{type:"sql"},read:{type:"sql"},update:{type:"sql"},delete:{type:"sql"}}},URr=["BLOB","NCLOB"],tae={PRIMARY:"P",NOT_NULL_OR_CHECK:"C",FOREIGN_KEY:"R",UNIQUE:"U"},rae=class e extends LRr{constructor(r){super("oracledb");this.index=1;this.getConnection=async()=>{let r=`${this.config.host}:${this.config.port||1521}/${this.config.database}`,n={user:this.config.user,password:this.config.password,connectString:r},i=Intl.DateTimeFormat().resolvedOptions().timeZone,o=await vm.default.getConnection(n);return await o.execute(`ALTER SESSION SET TIME_ZONE = '${i}'`),o};this.config=r}static{a(this,"OracleIntegration")}static{this.COLUMNS_SQL=`
915
915
  SELECT