@activepieces/piece-amazon-s3 0.6.2 → 0.6.4

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.
Files changed (2) hide show
  1. package/package.json +10 -4
  2. package/src/index.js +3 -3
package/package.json CHANGED
@@ -1,15 +1,21 @@
1
1
  {
2
2
  "name": "@activepieces/piece-amazon-s3",
3
- "version": "0.6.2",
3
+ "version": "0.6.4",
4
4
  "main": "./src/index.js",
5
5
  "dependencies": {
6
+ "@aws-sdk/lib-storage": "3.974.0",
6
7
  "@aws-sdk/client-s3": "3.974.0",
7
- "@aws-sdk/client-sts": "3.974.0",
8
- "@aws-sdk/client-secrets-manager": "3.0.0",
9
8
  "@aws-sdk/s3-request-presigner": "3.894.0",
9
+ "@aws-sdk/client-secrets-manager": "3.0.0",
10
+ "openpgp": "6.3.0",
10
11
  "dayjs": "1.11.9",
11
12
  "mime-types": "2.1.35",
12
- "openpgp": "6.3.0"
13
+ "@aws-sdk/client-sts": "3.974.0",
14
+ "zod": "4.3.6",
15
+ "form-data": "4.0.6",
16
+ "nanoid": "3.3.8",
17
+ "ipaddr.js": "2.3.0",
18
+ "deepmerge-ts": "7.1.0"
13
19
  },
14
20
  "files": [
15
21
  "src/index.js",
package/src/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var so=Object.create;var Ne=Object.defineProperty;var po=Object.getOwnPropertyDescriptor;var co=Object.getOwnPropertyNames;var uo=Object.getPrototypeOf,lo=Object.prototype.hasOwnProperty;var p=(e,t)=>Ne(e,"name",{value:t,configurable:!0});var Po=(e,t)=>{for(var o in t)Ne(e,o,{get:t[o],enumerable:!0})},Kt=(e,t,o,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of co(t))!lo.call(e,u)&&u!==o&&Ne(e,u,{get:()=>t[u],enumerable:!(a=po(t,u))||a.enumerable});return e};var d=(e,t,o)=>(o=e!=null?so(uo(e)):{},Kt(t||!e||!e.__esModule?Ne(o,"default",{value:e,enumerable:!0}):o,e)),mo=e=>Kt(Ne({},"__esModule",{value:!0}),e);var Qn={};Po(Qn,{amazonS3:()=>Zn});module.exports=mo(Qn);var W=d(require("zod/mini"));var Pt=W.object({retryOnFailure:W.object({defaultValue:W.optional(W.boolean()),hide:W.optional(W.boolean())}),continueOnFailure:W.object({defaultValue:W.optional(W.boolean()),hide:W.optional(W.boolean())})}),dt=class{constructor(t,o,a,u,l,m,y,O,h,A,N){this.name=t;this.displayName=o;this.description=a;this.props=u;this.run=l;this.test=m;this.requireAuth=y;this.errorHandlingOptions=O;this.outputSchema=h;this.audience=A;this.aiMetadata=N}static{p(this,"IAction")}},w=p(e=>new dt(e.name,e.displayName,e.description,e.props,e.run,e.test??e.run,e.requireAuth??!0,e.errorHandlingOptions??{continueOnFailure:{defaultValue:!1},retryOnFailure:{defaultValue:!1}},e.outputSchema,e.audience,e.aiMetadata),"createAction");var Dr=d(require("zod/mini"));var q=d(require("zod/mini"));var U=d(require("zod/mini"));var x=U.object({displayName:U.string(),description:U.optional(U.string())}),g=p((e,t)=>U.object({type:U.literal(t),required:U.boolean(),defaultValue:U.optional(U.any())}),"TPropertyValue");var he=d(require("zod/mini"));var H=he.object({...x.shape,...g(he.string(),"SHORT_TEXT").shape}),oe=he.object({...x.shape,...g(he.string(),"LONG_TEXT").shape});var ue=d(require("zod/mini"));var v=d(require("zod/mini")),Gt=v.object({label:v.string(),value:v.unknown()}),Ye=v.object({disabled:v.optional(v.boolean()),placeholder:v.optional(v.string()),options:v.array(Gt)});var K=ue.object({...x.shape,options:Ye,...g(ue.unknown(),"STATIC_DROPDOWN").shape}),ne=ue.object({...x.shape,options:Ye,...g(ue.array(ue.unknown()),"STATIC_MULTI_SELECT_DROPDOWN").shape});var G=d(require("zod/mini"));var mt=G.object({...x.shape,...g(G.unknown(),"DROPDOWN").shape,refreshers:G.array(G.string())}),ze=G.object({...x.shape,...g(G.array(G.unknown()),"MULTI_SELECT_DROPDOWN").shape,refreshers:G.array(G.string())});var $e=d(require("zod/mini"));var ie=$e.object({...x.shape,...g($e.boolean(),"CHECKBOX").shape});var Je=d(require("zod/mini"));var ae=Je.object({...x.shape,...g(Je.number(),"NUMBER").shape});var Ze=d(require("zod/mini"));var De=Ze.object({...x.shape,...g(Ze.unknown(),"FILE").shape});var Qe=d(require("zod/mini"));var be=Qe.object({...x.shape,...g(Qe.string(),"DATE_TIME").shape});var jt=q.record(q.string(),q.union([H,oe,K,ze,ne,ie,ae,De,be])),Me=q.object({...x.shape,properties:jt,...g(q.array(q.unknown()),"ARRAY").shape});var j=d(require("zod/mini"));var Z=d(require("zod/mini"));var we=Z.object({...x.shape,...g(Z.union([Z.record(Z.string(),Z.unknown())]),"JSON").shape});var Xt=j.union([H,K,we,Me,ne]),yo=j.record(j.string(),Xt),yt=j.object({refreshers:j.array(j.string()),...x.shape,...g(j.unknown(),"DYNAMIC").shape});var et=d(require("zod/mini"));var tt=et.object({...x.shape,...g(et.void(),"MARKDOWN").shape});var ke=(o=>(o.ARCHIVE="ARCHIVE",o.REGISTRY="REGISTRY",o))(ke||{}),Se=(o=>(o.CUSTOM="CUSTOM",o.OFFICIAL="OFFICIAL",o))(Se||{}),xe=(z=>(z.ARTIFICIAL_INTELLIGENCE="ARTIFICIAL_INTELLIGENCE",z.COMMUNICATION="COMMUNICATION",z.COMMERCE="COMMERCE",z.CORE="CORE",z.UNIVERSAL_AI="UNIVERSAL_AI",z.FLOW_CONTROL="FLOW_CONTROL",z.BUSINESS_INTELLIGENCE="BUSINESS_INTELLIGENCE",z.ACCOUNTING="ACCOUNTING",z.PRODUCTIVITY="PRODUCTIVITY",z.CONTENT_AND_FILES="CONTENT_AND_FILES",z.DEVELOPER_TOOLS="DEVELOPER_TOOLS",z.CUSTOMER_SUPPORT="CUSTOMER_SUPPORT",z.FORMS_AND_SURVEYS="FORMS_AND_SURVEYS",z.HUMAN_RESOURCES="HUMAN_RESOURCES",z.PAYMENT_PROCESSING="PAYMENT_PROCESSING",z.MARKETING="MARKETING",z.SALES_AND_CRM="SALES_AND_CRM",z))(xe||{});var Le=(o=>(o.AUTHORIZATION_CODE="authorization_code",o.CLIENT_CREDENTIALS="client_credentials",o))(Le||{}),At="both_client_credentials_and_authorization_code";var le=d(require("zod/mini")),de=(u=>(u.POLLING="POLLING",u.WEBHOOK="WEBHOOK",u.APP_WEBHOOK="APP_WEBHOOK",u.MANUAL="MANUAL",u))(de||{}),Ue=(l=>(l.NONE="NONE",l.HEADER_PRESENT="HEADER_PRESENT",l.QUERY_PRESENT="QUERY_PRESENT",l.BODY_PARAM_PRESENT="BODY_PARAM_PRESENT",l.HEAD_REQUEST="HEAD_REQUEST",l))(Ue||{}),Ao=le.object({strategy:le.enum(Ue),paramName:le.optional(le.string())}),ve=(o=>(o.SIMULATION="SIMULATION",o.TEST_FUNCTION="TEST_FUNCTION",o))(ve||{});var f=d(require("zod/mini"));var rt=(o=>(o.WEBSOCKET="WEBSOCKET",o.NONE="NONE",o))(rt||{}),qt=f.object({status:f.optional(f.number()),body:f.optional(f.unknown()),headers:f.optional(f.record(f.string(),f.string()))}),Yt=f.object({type:f.literal("DELAY"),resumeDateTime:f.string(),requestIdToReply:f.optional(f.string()),handlerId:f.optional(f.string()),streamStepProgress:f.optional(f.enum(rt))}),$t=f.object({type:f.literal("WEBHOOK"),requestId:f.string(),requestIdToReply:f.optional(f.string()),response:qt,handlerId:f.optional(f.string()),streamStepProgress:f.optional(f.enum(rt))}),go=f.union([Yt,$t]);var F=d(require("zod/mini")),To=F.object({body:F.unknown(),rawBody:F.optional(F.unknown()),headers:F.record(F.string(),F.string()),queryParams:F.record(F.string(),F.string())});var Eo=require("deepmerge-ts");function k(e){return e==null}p(k,"isNil");var Zt=require("nanoid"),ot=d(require("zod/mini"));var fo="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Qt=21,ma=ot.string().check(ot.regex(new RegExp(`^[0-9a-zA-Z]{${Qt}}$`))),ho=(0,Zt.customAlphabet)(fo,Qt);var R=d(require("zod/mini"));var Pe=R.pipe(R.transform(e=>e instanceof Date?e.toISOString():e),R.string()),Y={id:R.string(),created:Pe,updated:Pe},C=p(e=>R.optional(R.nullable(e)),"Nullable");function gt(e){return R.optional(R.nullable(R.enum(e)))}p(gt,"NullableEnum");var ga=R.pipe(R.transform(e=>e==="true"||e===!0?!0:e==="false"||e===!1?!1:void 0),R.optional(R.boolean())),nt=p(e=>R.pipe(R.transform(t=>Array.isArray(t)?t:t!==void 0?[t]:void 0),R.optional(R.array(e))),"OptionalArrayFromQuery");var Ie=d(require("zod/mini")),fa=Ie.record(Ie.string(),Ie.unknown());var Tt=d(require("zod/mini"));var Fe=(A=>(A.OPENAI="openai",A.OPENROUTER="openrouter",A.ANTHROPIC="anthropic",A.AZURE="azure",A.GOOGLE="google",A.ACTIVEPIECES="activepieces",A.CLOUDFLARE_GATEWAY="cloudflare-gateway",A.CUSTOM="custom",A.BEDROCK="bedrock",A.MISTRAL="mistral",A))(Fe||{});var it=d(require("zod/mini")),ba=it.string().check(it.regex(/^#[0-9A-Fa-f]{6}$/));var J=d(require("zod/mini"));var wa=J.object({filename:J.string(),data:J.unknown(),type:J.literal("file"),mimetype:J.optional(J.string())});var So=d(require("ipaddr.js"));var X=d(require("zod/mini"));var Ba=X.object({...Y,name:X.string(),permissions:X.array(X.string()),platformId:C(X.string()),type:X.string(),userCount:X.optional(X.number())});var n=d(require("zod/mini"));var er=(a=>(a.AGENT_DECIDE="agent-decide",a.CHOOSE_YOURSELF="choose-yourself",a.LEAVE_EMPTY="leave-empty",a))(er||{}),Et=(o=>(o.FILE="FILE",o.TABLE="TABLE",o))(Et||{}),ft=(a=>(a.SSE="sse",a.STREAMABLE_HTTP="streamable-http",a.SIMPLE_HTTP="http",a))(ft||{});var ht=(a=>(a.TEXT="text",a.NUMBER="number",a.BOOLEAN="boolean",a))(ht||{});var St=(o=>(o.IN_PROGRESS="in-progress",o.COMPLETED="completed",o))(St||{});var xo=n.object({mode:n.enum(er),value:n.unknown()}),Io=n.object({auth:n.optional(n.string()),fields:n.record(n.string(),xo)}),Ro=n.object({pieceName:n.string(),pieceVersion:n.string(),actionName:n.string(),predefinedInput:n.optional(Io)}),Oo=n.object({type:n.literal("PIECE"),toolName:n.string().check(n.minLength(1)),pieceMetadata:Ro}),Co=n.object({type:n.literal("none")}),_o=n.object({type:n.literal("access_token"),accessToken:n.string()}),No=n.object({type:n.literal("api_key"),apiKey:n.string(),apiKeyHeader:n.string()}),zo=n.object({type:n.literal("headers"),headers:n.record(n.string(),n.string())}),Do=n.discriminatedUnion("type",[Co,_o,No,zo]),tr=n.object({type:n.literal("FLOW"),toolName:n.string().check(n.minLength(1)),externalFlowId:n.string(),flowDisplayName:n.optional(n.string())}),rr=n.object({type:n.literal("MCP"),toolName:n.string().check(n.minLength(1)),serverUrl:n.url(),protocol:n.enum(ft),auth:Do}),or=n.object({type:n.literal("KNOWLEDGE_BASE"),toolName:n.string().check(n.minLength(1)),sourceType:n.enum(Et),sourceId:n.string(),sourceName:n.string()}),bo=n.discriminatedUnion("type",[Oo,tr,rr,or]),Mo=n.object({displayName:n.string(),description:n.optional(n.string()),type:n.enum(ht)}),nr=n.object({type:n.literal("MARKDOWN"),markdown:n.string()}),Re={type:n.literal("TOOL_CALL"),input:C(n.record(n.string(),n.unknown())),output:n.optional(n.unknown()),toolName:n.string(),status:n.enum(St),toolCallId:n.string(),startTime:n.string(),endTime:n.optional(n.string())},Ps=n.object(Re),ir=n.discriminatedUnion("toolCallType",[n.object({...Re,toolCallType:n.literal("PIECE"),pieceName:n.string(),pieceVersion:n.string(),actionName:n.string()}),n.object({...Re,toolCallType:n.literal("FLOW"),displayName:n.string(),externalFlowId:n.string()}),n.object({...Re,toolCallType:n.literal("MCP"),displayName:n.string(),serverUrl:n.string()}),n.object({...Re,toolCallType:n.literal("KNOWLEDGE_BASE"),displayName:n.string(),sourceType:n.string()}),n.object({...Re,toolCallType:n.literal("UNKNOWN"),displayName:n.string()})]),wo=n.union([nr,ir]);var c=d(require("zod/mini"));var xt=(o=>(o.IMAGE="image",o.TEXT="text",o))(xt||{}),se=c.object({apiKey:c.string()}),ko=se,Lo=c.object({apiKey:c.string(),apiKeyHash:c.string()}),Uo=se,vo=se,Fo=se,Bo=se,Vo=se,Wo=se,Ho=se,ar=c.object({accessKeyId:c.string().check(c.minLength(1)),secretAccessKey:c.string().check(c.minLength(1))}),Ko=c.object({}),Go=c.object({}),jo=c.object({}),Xo=c.object({}),qo=c.object({}),Yo=c.object({}),sr=c.object({modelId:c.string(),modelName:c.string(),modelType:c.enum(xt)}),pr=c.object({apiKeyHeader:c.string(),baseUrl:c.string(),models:c.array(sr),defaultHeaders:c.optional(c.record(c.string(),c.string()))}),cr=c.object({accountId:c.string(),gatewayId:c.string(),models:c.array(sr),vertexProject:c.optional(c.string()),vertexRegion:c.optional(c.string())}),ur=c.object({resourceName:c.string(),apiVersion:c.pipe(c.transform(e=>typeof e=="string"&&e.trim().length===0?void 0:e),c.optional(c.string()))}),lr=c.object({region:c.string().check(c.minLength(1))}),$o=c.union([ko,Fo,Bo,Vo,Wo,vo,Uo,Lo,ar,Ho]),dr=c.union([pr,cr,ur,lr,Ko,jo,Xo,qo,Go,Yo]),Jo=c.object({id:c.string(),name:c.string(),type:c.enum(xt)}),Zo=c.object({id:c.string(),name:c.string(),provider:c.enum(Fe),config:dr,enabledForChat:c.boolean()}),Qo=c.object({provider:c.enum(Fe),config:dr,auth:$o,platformId:c.string()});var gs={openai:"openai",anthropic:"anthropic","google-ai-studio":"google","google-vertex-ai":"google"};var I=d(require("zod/mini"));var en=I.object({base64Url:I.string(),fileName:I.string(),extension:I.optional(I.string())}),tn=I.object({mimeType:I.string(),url:I.string(),fileName:I.optional(I.string())}),It=I.union([en,tn]);var rn=I.union([I.object({type:I.literal("file"),value:It}),I.object({type:I.literal("markdown"),value:I.string(),files:I.optional(I.array(It))})]),on=I.object({sessionId:I.string(),message:I.string(),files:I.optional(I.array(I.string()))});var r=d(require("zod/mini"));var mr=(o=>(o.ON_NEW_RECORD="ON_NEW_RECORD",o.ON_UPDATE_RECORD="ON_UPDATE_RECORD",o))(mr||{}),yr=(o=>(o.ENABLED="ENABLED",o.DISABLED="DISABLED",o))(yr||{}),Rt=(a=>(a.RECORD_CREATED="RECORD_CREATED",a.RECORD_UPDATED="RECORD_UPDATED",a.RECORD_DELETED="RECORD_DELETED",a))(Rt||{});var nn=r.union([r.object({...Y,name:r.string(),externalId:r.string(),type:r.literal("STATIC_DROPDOWN"),tableId:r.string(),projectId:r.string(),data:r.object({options:r.array(r.object({value:r.string()}))})}),r.object({...Y,name:r.string(),externalId:r.string(),type:r.union([r.literal("TEXT"),r.literal("NUMBER"),r.literal("DATE")]),tableId:r.string(),projectId:r.string()})]),an=r.object({...Y,name:r.string(),folderId:C(r.string()),projectId:r.string(),externalId:r.string(),status:gt(yr),trigger:gt(mr)}),sn=r.object({...Y,tableId:r.string(),projectId:r.string(),cells:r.record(r.string(),r.object({updated:r.string(),created:r.string(),value:r.unknown(),fieldName:r.string()}))}),pn=r.object({events:r.array(r.enum(Rt)),webhookUrl:r.string(),flowId:r.string()}),cn=r.object({fields:r.array(r.object({id:r.string(),name:r.string()})),rows:r.array(r.record(r.string(),r.string())),name:r.string()}),un=r.object({projectId:r.string(),limit:r.optional(r.coerce.number()),cursor:r.optional(r.string()),name:r.optional(r.string()),externalIds:nt(r.string()),folderId:r.optional(r.string()),folderIds:nt(r.string())}),ln=r.object({records:r.array(r.array(r.object({fieldId:r.string(),value:gr()}))),tableId:r.string()}),dn=r.object({cells:r.optional(r.array(r.object({fieldId:r.string(),value:gr()}))),tableId:r.string(),agentUpdate:r.optional(r.boolean())}),Ar=r.discriminatedUnion("operator",[Ae("eq"),Ae("neq"),Ae("gt"),Ae("gte"),Ae("lt"),Ae("lte"),Ae("co"),Pr("exists"),Pr("not_exists")]),Pn=r.object({tableId:r.string(),limit:r.optional(r.coerce.number()),cursor:r.optional(r.string()),filters:nt(Ar)});function gr(){return r.pipe(r.transform(e=>e==null?e:String(e)),r.nullable(r.string()))}p(gr,"coerceToString");function Ae(e){return r.object({fieldId:r.string(),operator:r.literal(e),value:r.string()})}p(Ae,"valueFilter");function Pr(e){return r.object({fieldId:r.string(),operator:r.literal(e)})}p(Pr,"existenceFilter");var D=d(require("zod/mini"));var mn=D.object({status:D.optional(D.number()),body:D.optional(D.unknown()),headers:D.optional(D.record(D.string(),D.string()))}),yn=D.object({...Y,deleted:C(Pe),ownerId:D.string(),displayName:D.string(),platformId:D.string(),externalId:C(D.string())});var M=d(require("zod/mini"));var Tr=M.object({name:M.string(),description:M.optional(M.string()),type:M.string(),required:M.boolean()}),An=M.object({pieceName:M.string(),triggerName:M.string(),input:M.object({toolName:M.string(),toolDescription:M.string(),inputSchema:M.array(Tr),returnsResponse:M.boolean()})});var s=d(require("zod/mini"));var Er="^[0-9]+\\.[0-9]+\\.[0-9]+$",Ls=new RegExp(Er),Tn="^([~^])?[0-9]+\\.[0-9]+\\.[0-9]+$",Us=s.string().check(s.regex(new RegExp(Er))),vs=s.string().check(s.regex(new RegExp(Tn))),En=s.object({packageType:s.literal("ARCHIVE"),pieceType:s.enum(Se),pieceName:s.string(),pieceVersion:s.string(),archiveId:s.string(),platformId:s.string()}),fr=s.object({packageType:s.literal("REGISTRY"),pieceType:s.literal("OFFICIAL"),pieceName:s.string(),pieceVersion:s.string()}),hr=s.object({packageType:s.literal("REGISTRY"),pieceType:s.literal("CUSTOM"),pieceName:s.string(),pieceVersion:s.string(),platformId:s.string()}),Fs=s.union([fr,hr]),Bs=s.union([En,fr,hr]),Sr=(t=>(t.CRON_EXPRESSION="CRON_EXPRESSION",t))(Sr||{}),fn=s.object({type:s.enum(Sr),cronExpression:s.string(),timezone:s.string()}),Vs=s.object({...Y,type:s.enum(de),projectId:s.string(),flowId:s.string(),triggerName:s.string(),schedule:C(fn),flowVersionId:s.string(),pieceName:s.string(),pieceVersion:s.string(),deleted:C(s.string()),simulate:s.boolean()}),xr=(S=>(S.UNKNOWN="UNKNOWN",S.FLOW_RUN_LOG="FLOW_RUN_LOG",S.FLOW_RUN_LOG_SLICE="FLOW_RUN_LOG_SLICE",S.PACKAGE_ARCHIVE="PACKAGE_ARCHIVE",S.FLOW_STEP_FILE="FLOW_STEP_FILE",S.SAMPLE_DATA="SAMPLE_DATA",S.TRIGGER_PAYLOAD="TRIGGER_PAYLOAD",S.SAMPLE_DATA_INPUT="SAMPLE_DATA_INPUT",S.TRIGGER_EVENT_FILE="TRIGGER_EVENT_FILE",S.PROJECT_RELEASE="PROJECT_RELEASE",S.FLOW_VERSION_BACKUP="FLOW_VERSION_BACKUP",S.PLATFORM_ASSET="PLATFORM_ASSET",S.USER_PROFILE_PICTURE="USER_PROFILE_PICTURE",S.WEBHOOK_PAYLOAD="WEBHOOK_PAYLOAD",S.KNOWLEDGE_BASE="KNOWLEDGE_BASE",S.FLOW_BUNDLE="FLOW_BUNDLE",S))(xr||{}),Ir=(o=>(o.NONE="NONE",o.ZSTD="ZSTD",o))(Ir||{}),Rr=(o=>(o.S3="S3",o.DB="DB",o))(Rr||{}),Ws=s.object({...Y,projectId:C(s.string()),platformId:C(s.string()),type:s.enum(xr),compression:s.enum(Ir),data:s.optional(s.unknown()),location:s.enum(Rr),size:C(s.number()),fileName:C(s.string()),s3Key:C(s.string()),metadata:C(s.record(s.string(),s.string()))}),Or=(a=>(a.ADMIN="ADMIN",a.MEMBER="MEMBER",a.OPERATOR="OPERATOR",a))(Or||{}),Cr=(o=>(o.ACTIVE="ACTIVE",o.INACTIVE="INACTIVE",o))(Cr||{}),Hs=s.object({id:s.string(),email:s.string(),firstName:s.string(),status:s.enum(Cr),externalId:C(s.string()),platformId:C(s.string()),platformRole:s.enum(Or),lastName:s.string(),created:Pe,updated:Pe,lastActiveDate:C(Pe),imageUrl:C(s.string())});var me=d(require("zod/mini"));var Ct=me.object({...x.shape,...g(me.record(me.string(),me.unknown()),"OBJECT").shape});var at=d(require("zod/mini"));var zr=at.object({...x.shape,...g(at.string(),"COLOR").shape});var _t=Dr.union([H,oe,tt,ie,K,ne,mt,ze,yt,ae,Me,Ct,we,be,De,zr]),T={ShortText(e){return{...e,valueSchema:void 0,type:"SHORT_TEXT"}},Checkbox(e){return{...e,valueSchema:void 0,type:"CHECKBOX"}},LongText(e){return{...e,valueSchema:void 0,type:"LONG_TEXT"}},MarkDown(e){return{displayName:"Markdown",required:!1,description:e.value,type:"MARKDOWN",valueSchema:void 0,variant:e.variant??"INFO"}},Number(e){return{...e,valueSchema:void 0,type:"NUMBER"}},Json(e){return{...e,valueSchema:void 0,type:"JSON"}},Array(e){return{...e,valueSchema:void 0,type:"ARRAY"}},Object(e){return{...e,valueSchema:void 0,type:"OBJECT"}},Dropdown(e){return{...e,valueSchema:void 0,type:"DROPDOWN"}},StaticDropdown(e){return{...e,valueSchema:void 0,type:"STATIC_DROPDOWN"}},MultiSelectDropdown(e){return{...e,valueSchema:void 0,type:"MULTI_SELECT_DROPDOWN"}},DynamicProperties(e){return{...e,valueSchema:void 0,type:"DYNAMIC"}},StaticMultiSelectDropdown(e){return{...e,valueSchema:void 0,type:"STATIC_MULTI_SELECT_DROPDOWN"}},DateTime(e){return{...e,valueSchema:void 0,type:"DATE_TIME"}},File(e){return{...e,valueSchema:void 0,type:"FILE"}},Custom(e){let t=e.code.toString();return{...e,code:t,valueSchema:void 0,type:"CUSTOM"}},Color(e){return{...e,valueSchema:void 0,type:"COLOR"}}};var Ur=d(require("zod/mini"));var B=d(require("zod/mini"));var ge=d(require("zod/mini")),Q=ge.object({displayName:ge.string(),description:ge.optional(ge.string())});var br=B.object({username:B.string(),password:B.string()}),Nt=B.object({...Q.shape,username:B.object({displayName:B.string(),description:B.optional(B.string())}),password:B.object({displayName:B.string(),description:B.optional(B.string())}),...g(br,"BASIC_AUTH").shape});var ee=d(require("zod/mini"));var In=ee.record(ee.string(),ee.union([H,oe,ae,ie,K])),zt=ee.object({...Q.shape,props:In,...g(ee.unknown(),"CUSTOM_AUTH").shape});var te=d(require("zod/mini"));var Be=d(require("zod/mini"));var Te=Be.object({...Q.shape,...g(Be.object({auth:Be.string()}),"SECRET_TEXT").shape});var Rn=te.record(te.string(),te.union([H,oe,Te,ae,ie,K,ne,tt])),Mr=te.object({...Q.shape,props:Rn,...g(te.unknown(),"OIDC").shape});var P=d(require("zod/mini"));var Dt=(o=>(o.HEADER="HEADER",o.BODY="BODY",o))(Dt||{}),wr=P.union([H,Te,K]),kr=P.record(P.string(),wr),On=P.object({props:P.optional(P.record(P.string(),wr)),authUrl:P.string(),tokenUrl:P.string(),scope:P.array(P.string()),prompt:P.optional(P.union([P.literal("none"),P.literal("consent"),P.literal("login"),P.literal("omit")])),pkce:P.optional(P.boolean()),pkceMethod:P.optional(P.union([P.literal("plain"),P.literal("S256")])),authorizationMethod:P.optional(P.enum(Dt)),grantType:P.optional(P.union([P.enum(Le),P.literal(At)])),extra:P.optional(P.record(P.string(),P.string()))}),Lr=P.object({access_token:P.string(),props:P.optional(kr),data:P.record(P.string(),P.any())}),bt=P.object({...Q.shape,...On.shape,...g(Lr,"OAUTH2").shape});var Oe=Ur.union([Nt,zt,Mr,bt,Te]),Ve="Connection",We={SecretText(e){return{...e,valueSchema:void 0,type:"SECRET_TEXT"}},OAuth2(e){return{...e,valueSchema:void 0,type:"OAUTH2",displayName:e.displayName||Ve}},BasicAuth(e){return{...e,valueSchema:void 0,type:"BASIC_AUTH",displayName:e.displayName||Ve,required:!0}},CustomAuth(e){return{...e,valueSchema:void 0,type:"CUSTOM_AUTH",displayName:e.displayName||Ve}},OIDC(e){return{...e,valueSchema:void 0,type:"OIDC",displayName:e.displayName||Ve}},None(){}};var hc={OAUTH2:"OAUTH2",CLOUD_OAUTH2:"OAUTH2",PLATFORM_OAUTH2:"OAUTH2",BASIC_AUTH:"BASIC_AUTH",CUSTOM_AUTH:"CUSTOM_AUTH",OIDC:"OIDC",SECRET_TEXT:"SECRET_TEXT",NO_AUTH:void 0};var ye=d(require("zod/mini"));var Ce=d(require("zod/mini"));var Cn=Ce.object({...x.shape,...g(Ce.unknown(),"CUSTOM").shape,code:Ce.string()});var V=d(require("zod/mini"));var Nn=ye.union([_t,Oe]),Mt=ye.record(ye.string(),Nn),Uc=ye.record(ye.string(),_t);var re=d(require("zod/mini"));var vr=re.union([re.object({strategy:re.literal("CRON"),cronExpression:re.string()}),re.object({strategy:re.literal("NONE")})]),_e=class{constructor(t,o,a,u,l,m,y,O,h,A,N,L,qe,Vt,E,S,z,Wt,Ht){this.name=t;this.displayName=o;this.description=a;this.requireAuth=u;this.props=l;this.type=m;this.handshakeConfiguration=y;this.onHandshake=O;this.renewConfiguration=h;this.onRenew=A;this.onEnable=N;this.onDisable=L;this.onStart=qe;this.run=Vt;this.test=E;this.sampleData=S;this.testStrategy=z;this.outputSchema=Wt;this.aiMetadata=Ht}static{p(this,"ITrigger")}},Fr=p(e=>{switch(e.type){case"WEBHOOK":return new _e(e.name,e.displayName,e.description,e.requireAuth??!0,e.props,e.type,e.handshakeConfiguration??{strategy:"NONE"},e.onHandshake??(async()=>({status:200})),e.renewConfiguration??{strategy:"NONE"},e.onRenew??(async()=>Promise.resolve()),e.onEnable,e.onDisable,e.onStart??(async()=>Promise.resolve()),e.run,e.test??(()=>Promise.resolve([e.sampleData])),e.sampleData,e.test?"TEST_FUNCTION":"SIMULATION",e.outputSchema,e.aiMetadata);case"POLLING":return new _e(e.name,e.displayName,e.description,e.requireAuth??!0,e.props,e.type,{strategy:"NONE"},async()=>({status:200}),{strategy:"NONE"},async()=>Promise.resolve(),e.onEnable,e.onDisable,e.onStart??(async()=>Promise.resolve()),e.run,e.test??(()=>Promise.resolve([e.sampleData])),e.sampleData,"TEST_FUNCTION",e.outputSchema,e.aiMetadata);case"MANUAL":return new _e(e.name,e.displayName,e.description,e.requireAuth??!0,e.props,e.type,{strategy:"NONE"},async()=>({status:200}),{strategy:"NONE"},async()=>Promise.resolve(),e.onEnable,e.onDisable,e.onStart??(async()=>Promise.resolve()),e.run,e.test??(()=>Promise.resolve([e.sampleData])),e.sampleData,"TEST_FUNCTION",e.outputSchema,e.aiMetadata);case"APP_WEBHOOK":return new _e(e.name,e.displayName,e.description,e.requireAuth??!0,e.props,e.type,{strategy:"NONE"},async()=>({status:200}),{strategy:"NONE"},async()=>Promise.resolve(),e.onEnable,e.onDisable,e.onStart??(async()=>Promise.resolve()),e.run,e.test??(()=>Promise.resolve([e.sampleData])),e.sampleData,k(e.sampleData)&&k(e.test)?"SIMULATION":"TEST_FUNCTION",e.outputSchema,e.aiMetadata)}},"createTrigger");var Br="2",st="0.82.0";var wt=class{constructor(t,o,a,u,l,m,y,O,h=st,A,N=""){this.displayName=t;this.logoUrl=o;this.authors=a;this.events=u;this.categories=y;this.auth=O;this.minimumSupportedRelease=h;this.maximumSupportedRelease=A;this.description=N;this._actions={};this._triggers={};this.getContextInfo=p(()=>({version:Br}),"getContextInfo");(!zn(h)||Dn(h,st))&&(this.minimumSupportedRelease=st),l.forEach(L=>this._actions[L.name]=L),m.forEach(L=>this._triggers[L.name]=L)}static{p(this,"Piece")}metadata(){return{displayName:this.displayName,logoUrl:this.logoUrl,actions:this._actions,triggers:this._triggers,categories:this.categories,description:this.description,authors:this.authors,auth:this.auth,minimumSupportedRelease:this.minimumSupportedRelease,maximumSupportedRelease:this.maximumSupportedRelease,contextInfo:this.getContextInfo?.()}}getAction(t){return this._actions[t]}getTrigger(t){return this._triggers[t]}actions(){return this._actions}triggers(){return this._triggers}},Vr=p(e=>{if(e.auth&&Array.isArray(e.auth)&&!e.auth.every((o,a,u)=>a===u.findIndex(l=>l.type===o.type)))throw new Error("Auth properties must be unique by type");return new wt(e.displayName,e.logoUrl,e.authors??[],e.events,e.actions,e.triggers,e.categories??[],e.auth,e.minimumSupportedRelease,e.maximumSupportedRelease,e.description)},"createPiece");function zn(e){return/^\d+\.\d+\.\d+$/.test(e)}p(zn,"isValidSimpleSemver");function Dn(e,t){let[o,a,u]=e.split(".").map(Number),[l,m,y]=t.split(".").map(Number);return o!==l?o<l:a!==m?a<m:u<y}p(Dn,"isSemverLessThan");var i=d(require("zod/mini"));var bn=i.optional(i.record(i.string(),i.record(i.string(),i.string()))),Wr=i.object({id:i.optional(i.string()),name:i.string(),displayName:i.string(),logoUrl:i.string(),description:i.string(),authors:i.array(i.string()),platformId:i.optional(i.string()),directoryPath:i.optional(i.string()),auth:i.optional(i.union([Oe,i.array(Oe)])),version:i.string(),categories:i.optional(i.array(i.enum(xe))),minimumSupportedRelease:i.optional(i.string()),maximumSupportedRelease:i.optional(i.string()),i18n:bn}),Mn=i.enum(["human","ai","both"]),Hr=i.object({description:i.optional(i.string()),idempotent:i.optional(i.boolean())}),Kr=i.object({name:i.string(),displayName:i.string(),description:i.string(),props:Mt,requireAuth:i.boolean(),errorHandlingOptions:i.optional(Pt),outputSchema:i.optional(i.custom()),audience:i.optional(Mn),aiMetadata:i.optional(Hr)}),Gr=i.object({name:i.string(),displayName:i.string(),description:i.string(),props:Mt,errorHandlingOptions:i.optional(Pt),type:i.enum(de),sampleData:i.unknown(),handshakeConfiguration:i.optional(i.custom()),renewConfiguration:i.optional(vr),testStrategy:i.enum(ve),outputSchema:i.optional(i.custom()),aiMetadata:i.optional(Hr)}),wn=i.object({...Wr.shape,actions:i.record(i.string(),Kr),triggers:i.record(i.string(),Gr)}),kn=i.object({...Wr.shape,actions:i.number(),triggers:i.number(),suggestedActions:i.optional(i.array(Gr)),suggestedTriggers:i.optional(i.array(Kr))}),jr=i.object({projectUsage:i.number(),pieceType:i.enum(Se),packageType:i.enum(ke),platformId:i.optional(i.string()),archiveId:i.optional(i.string())}),Uu=i.object({...wn.shape,...jr.shape}),vu=i.object({...kn.shape,...jr.shape}),Fu=i.object({name:i.string(),version:i.string()});var Ln=d(require("path")),Un=d(require("fs/promises"));var kt=require("@aws-sdk/client-s3"),Xr=require("@aws-sdk/client-secrets-manager"),ct=require("@aws-sdk/client-sts");var vn="sts.amazonaws.com";function pe(e){if(!e.accessKeyId||!e.secretAccessKey)throw new Error("Access Key ID and Secret Access Key are required");return new kt.S3({credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey},forcePathStyle:e.endpoint?!0:void 0,region:e.region,endpoint:e.endpoint===""||k(e.endpoint)?void 0:e.endpoint})}p(pe,"createS3");function qr(e){if(!e.accessKeyId||!e.secretAccessKey)throw new Error("Access Key ID and Secret Access Key are required");return new Xr.SecretsManagerClient({credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey},region:e.region,endpoint:void 0})}p(qr,"createSecretsManagerClient");async function He({auth:e,server:t,durationSeconds:o}){let a=await Lt({auth:e,server:t,durationSeconds:o});return new kt.S3({credentials:a,region:e.region})}p(He,"createS3WithAssumeRole");function Ee(e){return"roleArn"in e}p(Ee,"isOidcAuth");async function $({authProps:e,server:t}){return Ee(e)?He({auth:e,server:t}):pe(e)}p($,"resolveS3Client");async function Lt({auth:e,server:t,durationSeconds:o=Bn}){if(!e.roleArn)throw new Error("Role ARN is required for IAM Role authentication");let a=Math.min(Math.max(o,Ke),fe),u=`${t.token}:${e.roleArn}:${e.region}:${a}`,l=pt.get(u);if(l&&l.expiresAtMS-Date.now()>Vn)return l.credentials;let m=await fetch(`${t.apiUrl}v1/worker/oidc-token`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({audience:vn})});if(!m.ok)throw new Error(`Failed to get OIDC token: ${m.statusText}`);let{token:y}=await m.json(),O=new ct.STSClient({region:e.region}),{Credentials:h}=await O.send(new ct.AssumeRoleWithWebIdentityCommand({RoleArn:e.roleArn,RoleSessionName:"activepieces-execution",WebIdentityToken:y,DurationSeconds:a}));if(!h?.AccessKeyId||!h.SecretAccessKey)throw new Error("Failed to assume role: no credentials returned");let A={accessKeyId:h.AccessKeyId,secretAccessKey:h.SecretAccessKey,sessionToken:h.SessionToken},N=h.Expiration?.getTime()??Date.now()+a*1e3;return Fn(),pt.set(u,{credentials:A,expiresAtMS:N}),A}p(Lt,"getTemporaryCredentials");function Fn(){let e=Date.now();for(let[t,o]of pt)o.expiresAtMS<=e&&pt.delete(t)}p(Fn,"sweepExpiredCredentials");var Bn=3600,Vn=5*60*1e3,pt=new Map,Ke=900,fe=43200;var Wn=`
1
+ "use strict";var po=Object.create;var De=Object.defineProperty;var co=Object.getOwnPropertyDescriptor;var uo=Object.getOwnPropertyNames;var lo=Object.getPrototypeOf,mo=Object.prototype.hasOwnProperty;var p=(e,t)=>De(e,"name",{value:t,configurable:!0});var Po=(e,t)=>{for(var o in t)De(e,o,{get:t[o],enumerable:!0})},Kt=(e,t,o,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of uo(t))!mo.call(e,u)&&u!==o&&De(e,u,{get:()=>t[u],enumerable:!(a=co(t,u))||a.enumerable});return e};var d=(e,t,o)=>(o=e!=null?po(lo(e)):{},Kt(t||!e||!e.__esModule?De(o,"default",{value:e,enumerable:!0}):o,e)),yo=e=>Kt(De({},"__esModule",{value:!0}),e);var ei={};Po(ei,{amazonS3:()=>Qn});module.exports=yo(ei);var V=d(require("zod/mini"));var mt=V.object({retryOnFailure:V.object({defaultValue:V.optional(V.boolean()),hide:V.optional(V.boolean())}),continueOnFailure:V.object({defaultValue:V.optional(V.boolean()),hide:V.optional(V.boolean())})}),dt=class{constructor(t,o,a,u,l,P,y,O,h,g,N){this.name=t;this.displayName=o;this.description=a;this.props=u;this.run=l;this.test=P;this.requireAuth=y;this.errorHandlingOptions=O;this.outputSchema=h;this.audience=g;this.aiMetadata=N}static{p(this,"IAction")}},w=p(e=>new dt(e.name,e.displayName,e.description,e.props,e.run,e.test??e.run,e.requireAuth??!0,e.errorHandlingOptions??{continueOnFailure:{defaultValue:!1},retryOnFailure:{defaultValue:!1}},e.outputSchema,e.audience,e.aiMetadata),"createAction");var zr=d(require("zod/mini"));var X=d(require("zod/mini"));var L=d(require("zod/mini"));var x=L.object({displayName:L.string(),description:L.optional(L.string())}),A=p((e,t)=>L.object({type:L.literal(t),required:L.boolean(),defaultValue:L.optional(L.any())}),"TPropertyValue");var xe=d(require("zod/mini"));var W=xe.object({...x.shape,...A(xe.string(),"SHORT_TEXT").shape}),ne=xe.object({...x.shape,...A(xe.string(),"LONG_TEXT").shape});var le=d(require("zod/mini"));var U=d(require("zod/mini")),Gt=U.object({label:U.string(),value:U.unknown()}),$e=U.object({disabled:U.optional(U.boolean()),placeholder:U.optional(U.string()),options:U.array(Gt)});var H=le.object({...x.shape,options:$e,...A(le.unknown(),"STATIC_DROPDOWN").shape}),ie=le.object({...x.shape,options:$e,...A(le.array(le.unknown()),"STATIC_MULTI_SELECT_DROPDOWN").shape});var K=d(require("zod/mini"));var Pt=K.object({...x.shape,...A(K.unknown(),"DROPDOWN").shape,refreshers:K.array(K.string())}),be=K.object({...x.shape,...A(K.array(K.unknown()),"MULTI_SELECT_DROPDOWN").shape,refreshers:K.array(K.string())});var Je=d(require("zod/mini"));var ae=Je.object({...x.shape,...A(Je.boolean(),"CHECKBOX").shape});var Ze=d(require("zod/mini"));var se=Ze.object({...x.shape,...A(Ze.number(),"NUMBER").shape});var de=d(require("zod/mini"));var Me=de.object({...x.shape,streaming:de.optional(de.boolean()),...A(de.unknown(),"FILE").shape});var Qe=d(require("zod/mini"));var we=Qe.object({...x.shape,...A(Qe.string(),"DATE_TIME").shape});var jt=X.record(X.string(),X.union([W,ne,H,be,ie,ae,se,Me,we])),ke=X.object({...x.shape,properties:jt,...A(X.array(X.unknown()),"ARRAY").shape});var G=d(require("zod/mini"));var Q=d(require("zod/mini"));var Le=Q.object({...x.shape,...A(Q.union([Q.record(Q.string(),Q.unknown())]),"JSON").shape});var Xt=G.union([W,H,Le,ke,ie]),go=G.record(G.string(),Xt),yt=G.object({refreshers:G.array(G.string()),...x.shape,...A(G.unknown(),"DYNAMIC").shape});var et=d(require("zod/mini"));var tt=et.object({...x.shape,...A(et.void(),"MARKDOWN").shape});var Ue=(o=>(o.ARCHIVE="ARCHIVE",o.REGISTRY="REGISTRY",o))(Ue||{}),Ie=(o=>(o.CUSTOM="CUSTOM",o.OFFICIAL="OFFICIAL",o))(Ie||{}),Re=(z=>(z.ARTIFICIAL_INTELLIGENCE="ARTIFICIAL_INTELLIGENCE",z.COMMUNICATION="COMMUNICATION",z.COMMERCE="COMMERCE",z.CORE="CORE",z.UNIVERSAL_AI="UNIVERSAL_AI",z.FLOW_CONTROL="FLOW_CONTROL",z.BUSINESS_INTELLIGENCE="BUSINESS_INTELLIGENCE",z.ACCOUNTING="ACCOUNTING",z.PRODUCTIVITY="PRODUCTIVITY",z.CONTENT_AND_FILES="CONTENT_AND_FILES",z.DEVELOPER_TOOLS="DEVELOPER_TOOLS",z.CUSTOMER_SUPPORT="CUSTOMER_SUPPORT",z.FORMS_AND_SURVEYS="FORMS_AND_SURVEYS",z.HUMAN_RESOURCES="HUMAN_RESOURCES",z.PAYMENT_PROCESSING="PAYMENT_PROCESSING",z.MARKETING="MARKETING",z.SALES_AND_CRM="SALES_AND_CRM",z))(Re||{});var ve=(o=>(o.AUTHORIZATION_CODE="authorization_code",o.CLIENT_CREDENTIALS="client_credentials",o))(ve||{}),gt="both_client_credentials_and_authorization_code";var me=d(require("zod/mini")),Pe=(u=>(u.POLLING="POLLING",u.WEBHOOK="WEBHOOK",u.APP_WEBHOOK="APP_WEBHOOK",u.MANUAL="MANUAL",u))(Pe||{}),Fe=(l=>(l.NONE="NONE",l.HEADER_PRESENT="HEADER_PRESENT",l.QUERY_PRESENT="QUERY_PRESENT",l.BODY_PARAM_PRESENT="BODY_PARAM_PRESENT",l.HEAD_REQUEST="HEAD_REQUEST",l))(Fe||{}),Ao=me.object({strategy:me.enum(Fe),paramName:me.optional(me.string())}),Be=(o=>(o.SIMULATION="SIMULATION",o.TEST_FUNCTION="TEST_FUNCTION",o))(Be||{});var f=d(require("zod/mini"));var rt=(o=>(o.WEBSOCKET="WEBSOCKET",o.NONE="NONE",o))(rt||{}),qt=f.object({status:f.optional(f.number()),body:f.optional(f.unknown()),headers:f.optional(f.record(f.string(),f.string()))}),Yt=f.object({type:f.literal("DELAY"),resumeDateTime:f.string(),requestIdToReply:f.optional(f.string()),handlerId:f.optional(f.string()),streamStepProgress:f.optional(f.enum(rt))}),$t=f.object({type:f.literal("WEBHOOK"),requestId:f.string(),requestIdToReply:f.optional(f.string()),response:qt,handlerId:f.optional(f.string()),streamStepProgress:f.optional(f.enum(rt))}),To=f.union([Yt,$t]);var v=d(require("zod/mini")),Eo=v.object({body:v.unknown(),rawBody:v.optional(v.unknown()),headers:v.record(v.string(),v.string()),queryParams:v.record(v.string(),v.string())});var fo=require("deepmerge-ts");function k(e){return e==null}p(k,"isNil");var Zt=require("nanoid"),ot=d(require("zod/mini"));var ho="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Qt=21,ya=ot.string().check(ot.regex(new RegExp(`^[0-9a-zA-Z]{${Qt}}$`))),So=(0,Zt.customAlphabet)(ho,Qt);var R=d(require("zod/mini"));var ye=R.pipe(R.transform(e=>e instanceof Date?e.toISOString():e),R.string()),q={id:R.string(),created:ye,updated:ye},C=p(e=>R.optional(R.nullable(e)),"Nullable");function At(e){return R.optional(R.nullable(R.enum(e)))}p(At,"NullableEnum");var Ta=R.pipe(R.transform(e=>e==="true"||e===!0?!0:e==="false"||e===!1?!1:void 0),R.optional(R.boolean())),nt=p(e=>R.pipe(R.transform(t=>Array.isArray(t)?t:t!==void 0?[t]:void 0),R.optional(R.array(e))),"OptionalArrayFromQuery");var Oe=d(require("zod/mini")),ha=Oe.record(Oe.string(),Oe.unknown());var Tt=d(require("zod/mini"));var Ve=(g=>(g.OPENAI="openai",g.OPENROUTER="openrouter",g.ANTHROPIC="anthropic",g.AZURE="azure",g.GOOGLE="google",g.ACTIVEPIECES="activepieces",g.CLOUDFLARE_GATEWAY="cloudflare-gateway",g.CUSTOM="custom",g.BEDROCK="bedrock",g.MISTRAL="mistral",g))(Ve||{});var it=d(require("zod/mini")),Ma=it.string().check(it.regex(/^#[0-9A-Fa-f]{6}$/));var $=d(require("zod/mini"));var ka=$.object({filename:$.string(),data:$.unknown(),type:$.literal("file"),mimetype:$.optional($.string())});var xo=d(require("ipaddr.js"));var j=d(require("zod/mini"));var Va=j.object({...q,name:j.string(),permissions:j.array(j.string()),platformId:C(j.string()),type:j.string(),userCount:j.optional(j.number())});var n=d(require("zod/mini"));var er=(a=>(a.AGENT_DECIDE="agent-decide",a.CHOOSE_YOURSELF="choose-yourself",a.LEAVE_EMPTY="leave-empty",a))(er||{}),Et=(o=>(o.FILE="FILE",o.TABLE="TABLE",o))(Et||{}),ft=(a=>(a.SSE="sse",a.STREAMABLE_HTTP="streamable-http",a.SIMPLE_HTTP="http",a))(ft||{});var ht=(a=>(a.TEXT="text",a.NUMBER="number",a.BOOLEAN="boolean",a))(ht||{});var St=(o=>(o.IN_PROGRESS="in-progress",o.COMPLETED="completed",o))(St||{});var Io=n.object({mode:n.enum(er),value:n.unknown()}),Ro=n.object({auth:n.optional(n.string()),fields:n.record(n.string(),Io)}),Oo=n.object({pieceName:n.string(),pieceVersion:n.string(),actionName:n.string(),predefinedInput:n.optional(Ro)}),Co=n.object({type:n.literal("PIECE"),toolName:n.string().check(n.minLength(1)),pieceMetadata:Oo}),_o=n.object({type:n.literal("none")}),No=n.object({type:n.literal("access_token"),accessToken:n.string()}),zo=n.object({type:n.literal("api_key"),apiKey:n.string(),apiKeyHeader:n.string()}),Do=n.object({type:n.literal("headers"),headers:n.record(n.string(),n.string())}),bo=n.discriminatedUnion("type",[_o,No,zo,Do]),tr=n.object({type:n.literal("FLOW"),toolName:n.string().check(n.minLength(1)),externalFlowId:n.string(),flowDisplayName:n.optional(n.string())}),rr=n.object({type:n.literal("MCP"),toolName:n.string().check(n.minLength(1)),serverUrl:n.url(),protocol:n.enum(ft),auth:bo}),or=n.object({type:n.literal("KNOWLEDGE_BASE"),toolName:n.string().check(n.minLength(1)),sourceType:n.enum(Et),sourceId:n.string(),sourceName:n.string()}),Mo=n.discriminatedUnion("type",[Co,tr,rr,or]),wo=n.object({displayName:n.string(),description:n.optional(n.string()),type:n.enum(ht)}),nr=n.object({type:n.literal("MARKDOWN"),markdown:n.string()}),Ce={type:n.literal("TOOL_CALL"),input:C(n.record(n.string(),n.unknown())),output:n.optional(n.unknown()),toolName:n.string(),status:n.enum(St),toolCallId:n.string(),startTime:n.string(),endTime:n.optional(n.string())},Ps=n.object(Ce),ir=n.discriminatedUnion("toolCallType",[n.object({...Ce,toolCallType:n.literal("PIECE"),pieceName:n.string(),pieceVersion:n.string(),actionName:n.string()}),n.object({...Ce,toolCallType:n.literal("FLOW"),displayName:n.string(),externalFlowId:n.string()}),n.object({...Ce,toolCallType:n.literal("MCP"),displayName:n.string(),serverUrl:n.string()}),n.object({...Ce,toolCallType:n.literal("KNOWLEDGE_BASE"),displayName:n.string(),sourceType:n.string()}),n.object({...Ce,toolCallType:n.literal("UNKNOWN"),displayName:n.string()})]),ko=n.union([nr,ir]);var c=d(require("zod/mini"));var xt=(o=>(o.IMAGE="image",o.TEXT="text",o))(xt||{}),pe=c.object({apiKey:c.string()}),Lo=pe,Uo=c.object({apiKey:c.string(),apiKeyHash:c.string()}),vo=pe,Fo=pe,Bo=pe,Vo=pe,Wo=pe,Ho=pe,Ko=pe,ar=c.object({accessKeyId:c.string().check(c.minLength(1)),secretAccessKey:c.string().check(c.minLength(1))}),Go=c.object({}),jo=c.object({}),Xo=c.object({}),qo=c.object({}),Yo=c.object({}),$o=c.object({}),sr=c.object({modelId:c.string(),modelName:c.string(),modelType:c.enum(xt)}),pr=c.object({apiKeyHeader:c.string(),baseUrl:c.string(),models:c.array(sr),defaultHeaders:c.optional(c.record(c.string(),c.string()))}),cr=c.object({accountId:c.string(),gatewayId:c.string(),models:c.array(sr),vertexProject:c.optional(c.string()),vertexRegion:c.optional(c.string())}),ur=c.object({resourceName:c.string(),apiVersion:c.pipe(c.transform(e=>typeof e=="string"&&e.trim().length===0?void 0:e),c.optional(c.string()))}),lr=c.object({region:c.string().check(c.minLength(1))}),Jo=c.union([Lo,Bo,Vo,Wo,Ho,Fo,vo,Uo,ar,Ko]),dr=c.union([pr,cr,ur,lr,Go,Xo,qo,Yo,jo,$o]),Zo=c.object({id:c.string(),name:c.string(),type:c.enum(xt)}),Qo=c.object({id:c.string(),name:c.string(),provider:c.enum(Ve),config:dr,enabledForChat:c.boolean()}),en=c.object({provider:c.enum(Ve),config:dr,auth:Jo,platformId:c.string()});var Ts={openai:"openai",anthropic:"anthropic","google-ai-studio":"google","google-vertex-ai":"google"};var I=d(require("zod/mini"));var tn=I.object({base64Url:I.string(),fileName:I.string(),extension:I.optional(I.string())}),rn=I.object({mimeType:I.string(),url:I.string(),fileName:I.optional(I.string())}),It=I.union([tn,rn]);var on=I.union([I.object({type:I.literal("file"),value:It}),I.object({type:I.literal("markdown"),value:I.string(),files:I.optional(I.array(It))})]),nn=I.object({sessionId:I.string(),message:I.string(),files:I.optional(I.array(I.string()))});var r=d(require("zod/mini"));var Pr=(o=>(o.ON_NEW_RECORD="ON_NEW_RECORD",o.ON_UPDATE_RECORD="ON_UPDATE_RECORD",o))(Pr||{}),yr=(o=>(o.ENABLED="ENABLED",o.DISABLED="DISABLED",o))(yr||{}),Rt=(a=>(a.RECORD_CREATED="RECORD_CREATED",a.RECORD_UPDATED="RECORD_UPDATED",a.RECORD_DELETED="RECORD_DELETED",a))(Rt||{});var an=r.union([r.object({...q,name:r.string(),externalId:r.string(),type:r.literal("STATIC_DROPDOWN"),tableId:r.string(),projectId:r.string(),data:r.object({options:r.array(r.object({value:r.string()}))})}),r.object({...q,name:r.string(),externalId:r.string(),type:r.union([r.literal("TEXT"),r.literal("NUMBER"),r.literal("DATE")]),tableId:r.string(),projectId:r.string()})]),sn=r.object({...q,name:r.string(),folderId:C(r.string()),projectId:r.string(),externalId:r.string(),status:At(yr),trigger:At(Pr)}),pn=r.object({...q,tableId:r.string(),projectId:r.string(),cells:r.record(r.string(),r.object({updated:r.string(),created:r.string(),value:r.unknown(),fieldName:r.string()}))}),cn=r.object({events:r.array(r.enum(Rt)),webhookUrl:r.string(),flowId:r.string()}),un=r.object({fields:r.array(r.object({id:r.string(),name:r.string()})),rows:r.array(r.record(r.string(),r.string())),name:r.string()}),ln=r.object({projectId:r.string(),limit:r.optional(r.coerce.number()),cursor:r.optional(r.string()),name:r.optional(r.string()),externalIds:nt(r.string()),folderId:r.optional(r.string()),folderIds:nt(r.string())}),dn=r.object({records:r.array(r.array(r.object({fieldId:r.string(),value:Ar()}))),tableId:r.string()}),mn=r.object({cells:r.optional(r.array(r.object({fieldId:r.string(),value:Ar()}))),tableId:r.string(),agentUpdate:r.optional(r.boolean())}),gr=r.discriminatedUnion("operator",[Te("eq"),Te("neq"),Te("gt"),Te("gte"),Te("lt"),Te("lte"),Te("co"),mr("exists"),mr("not_exists")]),Pn=r.object({tableId:r.string(),limit:r.optional(r.coerce.number()),cursor:r.optional(r.string()),filters:nt(gr)});function Ar(){return r.pipe(r.transform(e=>e==null?e:String(e)),r.nullable(r.string()))}p(Ar,"coerceToString");function Te(e){return r.object({fieldId:r.string(),operator:r.literal(e),value:r.string()})}p(Te,"valueFilter");function mr(e){return r.object({fieldId:r.string(),operator:r.literal(e)})}p(mr,"existenceFilter");var D=d(require("zod/mini"));var yn=D.object({status:D.optional(D.number()),body:D.optional(D.unknown()),headers:D.optional(D.record(D.string(),D.string()))}),gn=D.object({...q,deleted:C(ye),ownerId:D.string(),displayName:D.string(),platformId:D.string(),externalId:C(D.string())});var M=d(require("zod/mini"));var Tr=M.object({name:M.string(),description:M.optional(M.string()),type:M.string(),required:M.boolean()}),An=M.object({pieceName:M.string(),triggerName:M.string(),input:M.object({toolName:M.string(),toolDescription:M.string(),inputSchema:M.array(Tr),returnsResponse:M.boolean()})});var s=d(require("zod/mini"));var Er="^[0-9]+\\.[0-9]+\\.[0-9]+$",Us=new RegExp(Er),En="^([~^])?[0-9]+\\.[0-9]+\\.[0-9]+$",vs=s.string().check(s.regex(new RegExp(Er))),Fs=s.string().check(s.regex(new RegExp(En))),fn=s.object({packageType:s.literal("ARCHIVE"),pieceType:s.enum(Ie),pieceName:s.string(),pieceVersion:s.string(),archiveId:s.string(),platformId:s.string()}),fr=s.object({packageType:s.literal("REGISTRY"),pieceType:s.literal("OFFICIAL"),pieceName:s.string(),pieceVersion:s.string()}),hr=s.object({packageType:s.literal("REGISTRY"),pieceType:s.literal("CUSTOM"),pieceName:s.string(),pieceVersion:s.string(),platformId:s.string()}),Bs=s.union([fr,hr]),Vs=s.union([fn,fr,hr]);var hn=s.discriminatedUnion("type",[s.object({type:s.literal("CRON_EXPRESSION"),cronExpression:s.string(),timezone:s.string()}),s.object({type:s.literal("INTERVAL"),intervalMs:s.int().check(s.minimum(6e4))})]),Ws=s.object({...q,type:s.enum(Pe),projectId:s.string(),flowId:s.string(),triggerName:s.string(),schedule:C(hn),flowVersionId:s.string(),pieceName:s.string(),pieceVersion:s.string(),deleted:C(s.string()),simulate:s.boolean()}),Sr=(S=>(S.UNKNOWN="UNKNOWN",S.FLOW_RUN_LOG="FLOW_RUN_LOG",S.FLOW_RUN_LOG_SLICE="FLOW_RUN_LOG_SLICE",S.PACKAGE_ARCHIVE="PACKAGE_ARCHIVE",S.FLOW_STEP_FILE="FLOW_STEP_FILE",S.SAMPLE_DATA="SAMPLE_DATA",S.TRIGGER_PAYLOAD="TRIGGER_PAYLOAD",S.SAMPLE_DATA_INPUT="SAMPLE_DATA_INPUT",S.TRIGGER_EVENT_FILE="TRIGGER_EVENT_FILE",S.PROJECT_RELEASE="PROJECT_RELEASE",S.FLOW_VERSION_BACKUP="FLOW_VERSION_BACKUP",S.PLATFORM_ASSET="PLATFORM_ASSET",S.USER_PROFILE_PICTURE="USER_PROFILE_PICTURE",S.WEBHOOK_PAYLOAD="WEBHOOK_PAYLOAD",S.KNOWLEDGE_BASE="KNOWLEDGE_BASE",S.FLOW_BUNDLE="FLOW_BUNDLE",S))(Sr||{}),xr=(o=>(o.NONE="NONE",o.ZSTD="ZSTD",o))(xr||{}),Ir=(o=>(o.S3="S3",o.DB="DB",o))(Ir||{}),Hs=s.object({...q,projectId:C(s.string()),platformId:C(s.string()),type:s.enum(Sr),compression:s.enum(xr),data:s.optional(s.unknown()),location:s.enum(Ir),size:C(s.number()),fileName:C(s.string()),s3Key:C(s.string()),metadata:C(s.record(s.string(),s.string()))}),Rr=(a=>(a.ADMIN="ADMIN",a.MEMBER="MEMBER",a.OPERATOR="OPERATOR",a))(Rr||{}),Or=(o=>(o.ACTIVE="ACTIVE",o.INACTIVE="INACTIVE",o))(Or||{}),Ks=s.object({id:s.string(),email:s.string(),firstName:s.string(),status:s.enum(Or),externalId:C(s.string()),platformId:C(s.string()),platformRole:s.enum(Rr),lastName:s.string(),created:ye,updated:ye,lastActiveDate:C(ye),imageUrl:C(s.string())});var ge=d(require("zod/mini"));var Ct=ge.object({...x.shape,...A(ge.record(ge.string(),ge.unknown()),"OBJECT").shape});var at=d(require("zod/mini"));var Nr=at.object({...x.shape,...A(at.string(),"COLOR").shape});var _t=zr.union([W,ne,tt,ae,H,ie,Pt,be,yt,se,ke,Ct,Le,we,Me,Nr]),T={ShortText(e){return{...e,valueSchema:void 0,type:"SHORT_TEXT"}},Checkbox(e){return{...e,valueSchema:void 0,type:"CHECKBOX"}},LongText(e){return{...e,valueSchema:void 0,type:"LONG_TEXT"}},MarkDown(e){return{displayName:"Markdown",required:!1,description:e.value,type:"MARKDOWN",valueSchema:void 0,variant:e.variant??"INFO"}},Number(e){return{...e,valueSchema:void 0,type:"NUMBER"}},Json(e){return{...e,valueSchema:void 0,type:"JSON"}},Array(e){return{...e,valueSchema:void 0,type:"ARRAY"}},Object(e){return{...e,valueSchema:void 0,type:"OBJECT"}},Dropdown(e){return{...e,valueSchema:void 0,type:"DROPDOWN"}},StaticDropdown(e){return{...e,valueSchema:void 0,type:"STATIC_DROPDOWN"}},MultiSelectDropdown(e){return{...e,valueSchema:void 0,type:"MULTI_SELECT_DROPDOWN"}},DynamicProperties(e){return{...e,valueSchema:void 0,type:"DYNAMIC"}},StaticMultiSelectDropdown(e){return{...e,valueSchema:void 0,type:"STATIC_MULTI_SELECT_DROPDOWN"}},DateTime(e){return{...e,valueSchema:void 0,type:"DATE_TIME"}},File(e){return{...e,valueSchema:void 0,type:"FILE"}},Custom(e){let t=e.code.toString();return{...e,code:t,valueSchema:void 0,type:"CUSTOM"}},Color(e){return{...e,valueSchema:void 0,type:"COLOR"}}};var Lr=d(require("zod/mini"));var F=d(require("zod/mini"));var Ee=d(require("zod/mini")),ee=Ee.object({displayName:Ee.string(),description:Ee.optional(Ee.string())});var Dr=F.object({username:F.string(),password:F.string()}),Nt=F.object({...ee.shape,username:F.object({displayName:F.string(),description:F.optional(F.string())}),password:F.object({displayName:F.string(),description:F.optional(F.string())}),...A(Dr,"BASIC_AUTH").shape});var te=d(require("zod/mini"));var Rn=te.record(te.string(),te.union([W,ne,se,ae,H])),zt=te.object({...ee.shape,props:Rn,...A(te.unknown(),"CUSTOM_AUTH").shape});var re=d(require("zod/mini"));var We=d(require("zod/mini"));var fe=We.object({...ee.shape,...A(We.object({auth:We.string()}),"SECRET_TEXT").shape});var On=re.record(re.string(),re.union([W,ne,fe,se,ae,H,ie,tt])),br=re.object({...ee.shape,props:On,...A(re.unknown(),"OIDC").shape});var m=d(require("zod/mini"));var Dt=(o=>(o.HEADER="HEADER",o.BODY="BODY",o))(Dt||{}),Mr=m.union([W,fe,H]),wr=m.record(m.string(),Mr),Cn=m.object({props:m.optional(m.record(m.string(),Mr)),authUrl:m.string(),tokenUrl:m.string(),scope:m.array(m.string()),prompt:m.optional(m.union([m.literal("none"),m.literal("consent"),m.literal("login"),m.literal("omit")])),pkce:m.optional(m.boolean()),pkceMethod:m.optional(m.union([m.literal("plain"),m.literal("S256")])),authorizationMethod:m.optional(m.enum(Dt)),grantType:m.optional(m.union([m.enum(ve),m.literal(gt)])),extra:m.optional(m.record(m.string(),m.string()))}),kr=m.object({access_token:m.string(),props:m.optional(wr),data:m.record(m.string(),m.any())}),bt=m.object({...ee.shape,...Cn.shape,...A(kr,"OAUTH2").shape});var _e=Lr.union([Nt,zt,br,bt,fe]),He="Connection",Ke={SecretText(e){return{...e,valueSchema:void 0,type:"SECRET_TEXT"}},OAuth2(e){return{...e,valueSchema:void 0,type:"OAUTH2",displayName:e.displayName||He}},BasicAuth(e){return{...e,valueSchema:void 0,type:"BASIC_AUTH",displayName:e.displayName||He,required:!0}},CustomAuth(e){return{...e,valueSchema:void 0,type:"CUSTOM_AUTH",displayName:e.displayName||He}},OIDC(e){return{...e,valueSchema:void 0,type:"OIDC",displayName:e.displayName||He}},None(){}};var Sc={OAUTH2:"OAUTH2",CLOUD_OAUTH2:"OAUTH2",PLATFORM_OAUTH2:"OAUTH2",BASIC_AUTH:"BASIC_AUTH",CUSTOM_AUTH:"CUSTOM_AUTH",OIDC:"OIDC",SECRET_TEXT:"SECRET_TEXT",NO_AUTH:void 0};var Ae=d(require("zod/mini"));var Ne=d(require("zod/mini"));var _n=Ne.object({...x.shape,...A(Ne.unknown(),"CUSTOM").shape,code:Ne.string()});var B=d(require("zod/mini"));var zn=Ae.union([_t,_e]),Mt=Ae.record(Ae.string(),zn),vc=Ae.record(Ae.string(),_t);var oe=d(require("zod/mini"));var Ur=oe.union([oe.object({strategy:oe.literal("CRON"),cronExpression:oe.string()}),oe.object({strategy:oe.literal("NONE")})]),ze=class{constructor(t,o,a,u,l,P,y,O,h,g,N,J,Z,Vt,E,S,z,Wt,Ht){this.name=t;this.displayName=o;this.description=a;this.requireAuth=u;this.props=l;this.type=P;this.handshakeConfiguration=y;this.onHandshake=O;this.renewConfiguration=h;this.onRenew=g;this.onEnable=N;this.onDisable=J;this.onStart=Z;this.run=Vt;this.test=E;this.sampleData=S;this.testStrategy=z;this.outputSchema=Wt;this.aiMetadata=Ht}static{p(this,"ITrigger")}},vr=p(e=>{switch(e.type){case"WEBHOOK":return new ze(e.name,e.displayName,e.description,e.requireAuth??!0,e.props,e.type,e.handshakeConfiguration??{strategy:"NONE"},e.onHandshake??(async()=>({status:200})),e.renewConfiguration??{strategy:"NONE"},e.onRenew??(async()=>Promise.resolve()),e.onEnable,e.onDisable,e.onStart??(async()=>Promise.resolve()),e.run,e.test??(()=>Promise.resolve([e.sampleData])),e.sampleData,e.test?"TEST_FUNCTION":"SIMULATION",e.outputSchema,e.aiMetadata);case"POLLING":return new ze(e.name,e.displayName,e.description,e.requireAuth??!0,e.props,e.type,{strategy:"NONE"},async()=>({status:200}),{strategy:"NONE"},(async()=>Promise.resolve()),e.onEnable,e.onDisable,e.onStart??(async()=>Promise.resolve()),e.run,e.test??(()=>Promise.resolve([e.sampleData])),e.sampleData,"TEST_FUNCTION",e.outputSchema,e.aiMetadata);case"MANUAL":return new ze(e.name,e.displayName,e.description,e.requireAuth??!0,e.props,e.type,{strategy:"NONE"},async()=>({status:200}),{strategy:"NONE"},(async()=>Promise.resolve()),e.onEnable,e.onDisable,e.onStart??(async()=>Promise.resolve()),e.run,e.test??(()=>Promise.resolve([e.sampleData])),e.sampleData,"TEST_FUNCTION",e.outputSchema,e.aiMetadata);case"APP_WEBHOOK":return new ze(e.name,e.displayName,e.description,e.requireAuth??!0,e.props,e.type,{strategy:"NONE"},async()=>({status:200}),{strategy:"NONE"},(async()=>Promise.resolve()),e.onEnable,e.onDisable,e.onStart??(async()=>Promise.resolve()),e.run,e.test??(()=>Promise.resolve([e.sampleData])),e.sampleData,k(e.sampleData)&&k(e.test)?"SIMULATION":"TEST_FUNCTION",e.outputSchema,e.aiMetadata)}},"createTrigger");var Fr="2",st="0.82.0";var wt=class{constructor(t,o,a,u,l,P,y,O,h=st,g,N="",J){this.displayName=t;this.logoUrl=o;this.authors=a;this.events=u;this.categories=y;this.auth=O;this.minimumSupportedRelease=h;this.maximumSupportedRelease=g;this.description=N;this.deprecated=J;this._actions={};this._triggers={};this.getContextInfo=p(()=>({version:Fr}),"getContextInfo");(!Dn(h)||bn(h,st))&&(this.minimumSupportedRelease=st),l.forEach(Z=>this._actions[Z.name]=Z),P.forEach(Z=>this._triggers[Z.name]=Z)}static{p(this,"Piece")}metadata(){return{displayName:this.displayName,logoUrl:this.logoUrl,actions:this._actions,triggers:this._triggers,categories:this.categories,description:this.description,authors:this.authors,auth:this.auth,minimumSupportedRelease:this.minimumSupportedRelease,maximumSupportedRelease:this.maximumSupportedRelease,deprecated:this.deprecated,contextInfo:this.getContextInfo?.()}}getAction(t){return this._actions[t]}getTrigger(t){return this._triggers[t]}actions(){return this._actions}triggers(){return this._triggers}},Br=p(e=>{if(e.auth&&Array.isArray(e.auth)&&!e.auth.every((o,a,u)=>a===u.findIndex(l=>l.type===o.type)))throw new Error("Auth properties must be unique by type");return new wt(e.displayName,e.logoUrl,e.authors??[],e.events,e.actions,e.triggers,e.categories??[],e.auth,e.minimumSupportedRelease,e.maximumSupportedRelease,e.description,e.deprecated)},"createPiece");function Dn(e){return/^\d+\.\d+\.\d+$/.test(e)}p(Dn,"isValidSimpleSemver");function bn(e,t){let[o,a,u]=e.split(".").map(Number),[l,P,y]=t.split(".").map(Number);return o!==l?o<l:a!==P?a<P:u<y}p(bn,"isSemverLessThan");var i=d(require("zod/mini"));var Mn=i.optional(i.record(i.string(),i.record(i.string(),i.string()))),Vr=i.object({id:i.optional(i.string()),name:i.string(),displayName:i.string(),logoUrl:i.string(),description:i.string(),authors:i.array(i.string()),platformId:i.optional(i.string()),directoryPath:i.optional(i.string()),auth:i.optional(i.union([_e,i.array(_e)])),version:i.string(),categories:i.optional(i.array(i.enum(Re))),minimumSupportedRelease:i.optional(i.string()),maximumSupportedRelease:i.optional(i.string()),deprecated:i.optional(i.boolean()),i18n:Mn}),wn=i.enum(["human","ai","both"]),Wr=i.object({description:i.optional(i.string()),idempotent:i.optional(i.boolean())}),Hr=i.object({name:i.string(),displayName:i.string(),description:i.string(),props:Mt,requireAuth:i.boolean(),errorHandlingOptions:i.optional(mt),outputSchema:i.optional(i.custom()),audience:i.optional(wn),aiMetadata:i.optional(Wr)}),Kr=i.object({name:i.string(),displayName:i.string(),description:i.string(),props:Mt,errorHandlingOptions:i.optional(mt),type:i.enum(Pe),sampleData:i.unknown(),handshakeConfiguration:i.optional(i.custom()),renewConfiguration:i.optional(Ur),testStrategy:i.enum(Be),outputSchema:i.optional(i.custom()),aiMetadata:i.optional(Wr)}),kn=i.object({...Vr.shape,actions:i.record(i.string(),Hr),triggers:i.record(i.string(),Kr)}),Ln=i.object({...Vr.shape,actions:i.number(),triggers:i.number(),suggestedActions:i.optional(i.array(Hr)),suggestedTriggers:i.optional(i.array(Kr))}),Gr=i.object({projectUsage:i.number(),pieceType:i.enum(Ie),packageType:i.enum(Ue),platformId:i.optional(i.string()),archiveId:i.optional(i.string())}),vu=i.object({...kn.shape,...Gr.shape}),Fu=i.object({...Ln.shape,...Gr.shape}),Bu=i.object({name:i.string(),version:i.string()});var Un=d(require("path")),vn=d(require("fs/promises"));var Yr=require("node:stream");var kt=require("@aws-sdk/client-s3"),jr=require("@aws-sdk/client-secrets-manager"),ct=require("@aws-sdk/client-sts");var Fn="sts.amazonaws.com";function ce(e){if(!e.accessKeyId||!e.secretAccessKey)throw new Error("Access Key ID and Secret Access Key are required");return new kt.S3({credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey},forcePathStyle:e.endpoint?!0:void 0,region:e.region,endpoint:e.endpoint===""||k(e.endpoint)?void 0:e.endpoint})}p(ce,"createS3");function Xr(e){if(!e.accessKeyId||!e.secretAccessKey)throw new Error("Access Key ID and Secret Access Key are required");return new jr.SecretsManagerClient({credentials:{accessKeyId:e.accessKeyId,secretAccessKey:e.secretAccessKey},region:e.region,endpoint:void 0})}p(Xr,"createSecretsManagerClient");async function Ge({auth:e,server:t,durationSeconds:o}){let a=await Lt({auth:e,server:t,durationSeconds:o});return new kt.S3({credentials:a,region:e.region})}p(Ge,"createS3WithAssumeRole");function he(e){return"roleArn"in e}p(he,"isOidcAuth");async function Y({authProps:e,server:t}){return he(e)?Ge({auth:e,server:t}):ce(e)}p(Y,"resolveS3Client");async function Lt({auth:e,server:t,durationSeconds:o=Vn}){if(!e.roleArn)throw new Error("Role ARN is required for IAM Role authentication");let a=Math.min(Math.max(o,je),Se),u=`${t.token}:${e.roleArn}:${e.region}:${a}`,l=pt.get(u);if(l&&l.expiresAtMS-Date.now()>Wn)return l.credentials;let P=await fetch(`${t.apiUrl}v1/worker/oidc-token`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"Content-Type":"application/json"},body:JSON.stringify({audience:Fn})});if(!P.ok)throw new Error(`Failed to get OIDC token: ${P.statusText}`);let{token:y}=await P.json(),O=new ct.STSClient({region:e.region}),{Credentials:h}=await O.send(new ct.AssumeRoleWithWebIdentityCommand({RoleArn:e.roleArn,RoleSessionName:"activepieces-execution",WebIdentityToken:y,DurationSeconds:a}));if(!h?.AccessKeyId||!h.SecretAccessKey)throw new Error("Failed to assume role: no credentials returned");let g={accessKeyId:h.AccessKeyId,secretAccessKey:h.SecretAccessKey,sessionToken:h.SessionToken},N=h.Expiration?.getTime()??Date.now()+a*1e3;return Bn(),pt.set(u,{credentials:g,expiresAtMS:N}),g}p(Lt,"getTemporaryCredentials");function Bn(){let e=Date.now();for(let[t,o]of pt)o.expiresAtMS<=e&&pt.delete(t)}p(Bn,"sweepExpiredCredentials");var Vn=3600,Wn=300*1e3,pt=new Map,je=900,Se=43200;var Hn=`
2
2
  Connect your Amazon S3 account using AWS Access Key credentials.
3
3
 
4
4
  **How to get your credentials:**
@@ -8,7 +8,7 @@ Connect your Amazon S3 account using AWS Access Key credentials.
8
8
  4. Make sure the IAM user has the **AmazonS3FullAccess** policy (or a scoped S3 policy for your bucket).
9
9
 
10
10
  Using a non-AWS S3-compatible service (MinIO, DigitalOcean Spaces, Backblaze B2, etc.)? Set the **Endpoint** field to your service URL.
11
- `,Hn=`
11
+ `,Kn=`
12
12
  Connect your Amazon S3 account using an IAM Role via OIDC \u2014 no permanent keys required.
13
13
 
14
14
  Activepieces acts as an OIDC identity provider. AWS trusts this provider and issues temporary credentials via \`AssumeRoleWithWebIdentity\`.
@@ -40,4 +40,4 @@ Activepieces acts as an OIDC identity provider. AWS trusts this provider and iss
40
40
  }
41
41
  \`\`\`
42
42
  3. Attach S3 permissions to the role and paste the **Role ARN** below.
43
- `,Yr=[{label:"Default",value:"us-east-1"},{label:"US East (N. Virginia) [us-east-1]",value:"us-east-1"},{label:"US East (Ohio) [us-east-2]",value:"us-east-2"},{label:"US West (N. California) [us-west-1]",value:"us-west-1"},{label:"US West (Oregon) [us-west-2]",value:"us-west-2"},{label:"Africa (Cape Town) [af-south-1]",value:"af-south-1"},{label:"Asia Pacific (Hong Kong) [ap-east-1]",value:"ap-east-1"},{label:"Asia Pacific (Mumbai) [ap-south-1]",value:"ap-south-1"},{label:"Asia Pacific (Osaka-Local) [ap-northeast-3]",value:"ap-northeast-3"},{label:"Asia Pacific (Seoul) [ap-northeast-2]",value:"ap-northeast-2"},{label:"Asia Pacific (Singapore) [ap-southeast-1]",value:"ap-southeast-1"},{label:"Asia Pacific (Sydney) [ap-southeast-2]",value:"ap-southeast-2"},{label:"Asia Pacific (Tokyo) [ap-northeast-1]",value:"ap-northeast-1"},{label:"Canada (Central) [ca-central-1]",value:"ca-central-1"},{label:"Europe (Frankfurt) [eu-central-1]",value:"eu-central-1"},{label:"Europe (Ireland) [eu-west-1]",value:"eu-west-1"},{label:"Europe (London) [eu-west-2]",value:"eu-west-2"},{label:"Europe (Milan) [eu-south-1]",value:"eu-south-1"},{label:"Europe (Paris) [eu-west-3]",value:"eu-west-3"},{label:"Europe (Stockholm) [eu-north-1]",value:"eu-north-1"},{label:"Middle East (Bahrain) [me-south-1]",value:"me-south-1"},{label:"South America (S\xE3o Paulo) [sa-east-1]",value:"sa-east-1"},{label:"Europe (Spain) [eu-south-2]",value:"eu-south-2"},{label:"Asia Pacific (Hyderabad) [ap-south-2]",value:"ap-south-2"},{label:"Asia Pacific (Jakarta) [ap-southeast-3]",value:"ap-southeast-3"},{label:"Asia Pacific (Melbourne) [ap-southeast-4]",value:"ap-southeast-4"},{label:"China (Beijing) [cn-north-1]",value:"cn-north-1"},{label:"China (Ningxia) [cn-northwest-1]",value:"cn-northwest-1"},{label:"Europe (Zurich) [eu-central-2]",value:"eu-central-2"},{label:"Middle East (UAE) [me-central-1]",value:"me-central-1"}],Kn=We.CustomAuth({displayName:"Amazon S3 (Access Key)",description:Wn,props:{accessKeyId:T.ShortText({displayName:"Access Key ID",description:"Your AWS access key ID. Found in AWS IAM Console \u2192 Users \u2192 Security credentials.",required:!0}),secretAccessKey:We.SecretText({displayName:"Secret Access Key",description:"Your AWS secret access key. Only shown once when you create the access key.",required:!0}),endpoint:T.ShortText({displayName:"Endpoint (Optional)",description:"Leave blank for Amazon S3. Only set when using MinIO, DigitalOcean Spaces, Backblaze B2, etc.",required:!1}),region:T.StaticDropdown({displayName:"Region",options:{options:Yr},required:!0}),bucket:T.ShortText({displayName:"Bucket Name",description:'The name of your S3 bucket (e.g. "my-company-files").',required:!0})},validate:p(async({auth:e})=>{if(!e.accessKeyId||!e.secretAccessKey)return{valid:!1,error:"Access Key ID and Secret Access Key are required."};try{return await pe(e).listObjectsV2({Bucket:e.bucket,MaxKeys:1}),{valid:!0}}catch(t){return{valid:!1,error:t?.message}}},"validate"),required:!0}),Gn=We.OIDC({displayName:"Amazon S3 (IAM Role / OIDC)",description:Hn,props:{roleArn:T.ShortText({displayName:"Role ARN",description:"The ARN of the IAM role to assume (e.g. arn:aws:iam::123456789012:role/MyRole).",required:!0}),region:T.StaticDropdown({displayName:"Region",options:{options:Yr},required:!0}),bucket:T.ShortText({displayName:"Bucket Name",description:'The name of your S3 bucket (e.g. "my-company-files").',required:!0})},validate:p(async({auth:e})=>e.roleArn?/^arn:(?:aws|aws-us-gov|aws-cn):iam::\d{12}:role\/[\w+=,.@\-/]{1,512}$/.test(e.roleArn)?{valid:!0}:{valid:!1,error:"Invalid IAM Role ARN format. Expected: arn:aws:iam::123456789012:role/RoleName"}:{valid:!1,error:"Role ARN is required for IAM Role authentication."},"validate"),required:!0}),b=[Kn,Gn];var $r=w({auth:b,name:"read-file",displayName:"Read File",description:"Read a file from S3 to use it in other steps",audience:"both",aiMetadata:{description:"Downloads a single object from the configured S3 bucket by its full key (path) and makes its contents available as a file for later steps. Use to fetch a known file when you have its exact key. Reading the same key repeatedly returns the same content with no side effect (idempotent).",idempotent:!0},props:{key:T.ShortText({displayName:"File Path",description:'The full path to the file within your S3 bucket (e.g. "documents/report.csv" or "myfile.txt"). This is also called the S3 "key".',required:!0})},async run(e){let t=e.auth.props,{bucket:o}=t,{key:a}=e.propsValue,m=await(await(await $({authProps:t,server:e.server})).getObject({Bucket:o,Key:a})).Body?.transformToString("base64");if(!m)throw new Error(`Could not read file ${a} from S3`);return await e.files.write({fileName:a,data:Buffer.from(m,"base64")})}});var Ge=d(require("mime-types")),Jr=w({auth:b,name:"upload-file",displayName:"Upload File",description:"Upload an File to S3",audience:"both",aiMetadata:{description:"Uploads a file to the configured S3 bucket, optionally setting a destination filename, content type, and canned ACL (e.g. private vs. public-read). Use to store new content in S3. Not idempotent: when no filename is given a unique timestamp-based key is generated, so each call writes a new object.",idempotent:!1},props:{file:T.File({displayName:"File",description:"The file to upload to S3.",required:!0}),fileName:T.ShortText({displayName:"File Name (Optional)",required:!1,description:'The name to save the file as in S3 (e.g. "report-2024.csv"). If left blank, a unique name is generated automatically.'}),acl:T.StaticDropdown({displayName:"Access Control (ACL)",description:'Who can access this file after upload. Use "Private" for internal files, "Public Read" to make the file publicly accessible via URL.',required:!1,options:{options:[{label:"Private (only your account)",value:"private"},{label:"Public Read (anyone can view)",value:"public-read"},{label:"Public Read/Write (anyone can view and upload)",value:"public-read-write"},{label:"Authenticated AWS Users Read",value:"authenticated-read"},{label:"AWS EC2 Read (aws-exec-read)",value:"aws-exec-read"},{label:"Bucket Owner Read",value:"bucket-owner-read"},{label:"Bucket Owner Full Control",value:"bucket-owner-full-control"}]}}),type:T.ShortText({displayName:"Content Type",description:"Content Type of the uploaded file, if not set the API will try to figure out the content type.",required:!1})},async run(e){let t=e.auth.props,{bucket:o}=t,{file:a,fileName:u,acl:l,type:m}=e.propsValue,y=await $({authProps:t,server:e.server}),O,h=null;if(m)if(Ge.default.extension(m))O=m,h="."+Ge.default.extension(m);else throw new Error("The content type entered does not exist or is misspelled, please check your input.");else{if(!a.extension||a.extension===void 0||!Ge.default.contentType(a.extension))throw new Error("Content type could not be interpreted, please check the input file.");h="."+a.extension,O=Ge.default.contentType(h)}let A=new Date().toISOString()+Date.now()+h,N=u?u.endsWith(h)?u:u+h:A,L=await y.putObject({Bucket:o,Key:N,ACL:l,ContentType:O,Body:a.data});return{fileName:N,etag:L.ETag}}});var je={async poll(e,{store:t,auth:o,propsValue:a,maxItemsToPoll:u,files:l,server:m}){switch(e.strategy){case 0:{let y=await t.get("lastPoll");if(k(y))throw new Error("lastPoll doesn't exist in the store.");let O=await e.items({store:t,auth:o,propsValue:a,lastFetchEpochMS:y,server:m}),h=O.reduce((A,N)=>Math.max(A,N.epochMilliSeconds),y);return await t.put("lastPoll",h),O.filter(A=>A.epochMilliSeconds>y).map(A=>A.data)}case 1:{let y=await t.get("lastItem"),O=await e.items({store:t,auth:o,propsValue:a,lastItemId:y,files:l,server:m}),h=O.findIndex(L=>L.id===y),A=[];k(y)||h==-1?A=O??[]:A=O?.slice(0,h)??[],k(u)||(A=A.slice(-u));let N=A?.[0]?.id;return k(N)||await t.put("lastItem",N),A.map(L=>L.data)}}},async onEnable(e,{store:t,auth:o,propsValue:a,server:u}){switch(e.strategy){case 0:{await t.put("lastPoll",Date.now());break}case 1:{let m=(await e.items({store:t,auth:o,propsValue:a,lastItemId:null,server:u}))?.[0]?.id;k(m)?await t.delete("lastItem"):await t.put("lastItem",m);break}}},async onDisable(e,t){switch(e.strategy){case 0:case 1:return}},async test(e,{auth:t,propsValue:o,store:a,files:u,server:l}){let m=[];switch(e.strategy){case 0:{m=await e.items({store:a,auth:t,propsValue:o,lastFetchEpochMS:0,server:l});break}case 1:{m=await e.items({store:a,auth:t,propsValue:o,lastItemId:null,files:u,server:l});break}}return jn(m.map(y=>y.data))}};function jn(e){return e.length<=5?e:e.slice(0,5)}p(jn,"getFirstFiveOrAll");var Zr=d(require("dayjs"));var ut={strategy:0,items:p(async({auth:e,propsValue:t,lastFetchEpochMS:o,server:a})=>{if(!a)throw new Error("Server context is required to resolve Amazon S3 credentials");let u=e.props,l=await $({authProps:u,server:a});return(await Xn({s3:l,bucket:u.bucket,folderPath:t.folderPath,isTest:o===0})).filter(y=>Number.isFinite(y.epochMilliSeconds))},"items")},Qr=Fr({auth:b,name:"new_file",displayName:"New or Updated File",description:"Triggers when you add or update a file in your bucket. The bucket/folder you choose must not contain more than 10,000 files.",aiMetadata:{description:"Fires when an object is added or modified in the configured S3 bucket, optionally scoped to a folder prefix. Polls the bucket and emits each new or updated file based on its last-modified time. The watched bucket/folder must contain no more than 10,000 files."},props:{markdown:T.MarkDown({variant:"INFO",value:"Triggers when you add or update a file in your bucket. The bucket/folder you choose must not contain more than 10,000 files."}),folderPath:T.ShortText({displayName:"Folder Path",required:!1})},type:"POLLING",onEnable:p(async e=>{await je.onEnable(ut,{auth:e.auth,store:e.store,propsValue:e.propsValue})},"onEnable"),onDisable:p(async e=>{await je.onDisable(ut,{auth:e.auth,store:e.store,propsValue:e.propsValue})},"onDisable"),run:p(async e=>je.poll(ut,{auth:e.auth,store:e.store,propsValue:e.propsValue,files:e.files,server:e.server}),"run"),test:p(async e=>je.test(ut,{auth:e.auth,store:e.store,propsValue:e.propsValue,files:e.files,server:e.server}),"test"),sampleData:{Key:"myfolder/100-3.png",LastModified:"2023-08-04T13:51:26.000Z",ETag:'"e9f16cce12352322272525f5af65a2e"',Size:40239,StorageClass:"STANDARD"}});async function Xn({s3:e,bucket:t,folderPath:o,isTest:a}){let l=[],m=0,y=!0,O;do{let h={Bucket:t,MaxKeys:a?10:1e3,ContinuationToken:O};o&&(h.Prefix=o.endsWith("/")?o.slice(0,-1):o);let A=await e.listObjectsV2(h),N=A.Contents??[];if(m+N.length>1e4){l.push(...N.slice(0,1e4-m));break}if(l.push(...N),m+=N.length,a)break;y=!!A.IsTruncated,O=A.NextContinuationToken??void 0}while(y);return l.map(h=>({epochMilliSeconds:(0,Zr.default)(h.LastModified).valueOf(),data:h}))}p(Xn,"fetchS3FilesForTrigger");var Ut=require("@aws-sdk/client-s3"),vt=require("@aws-sdk/s3-request-presigner");var eo=w({auth:b,name:"generate-signed-url",displayName:"Generate signed URL",description:"Generate a signed URL for a file in a s3 bucket",audience:"both",aiMetadata:{description:"Generates a time-limited pre-signed download (GET) URL for an existing object in the configured S3 bucket, letting anyone with the link fetch the file without AWS credentials until it expires. Use when you need to share read access to a stored file. Read-only and idempotent (no object is modified), though each call returns a freshly signed URL.",idempotent:!0},props:{key:T.ShortText({displayName:"File Path",description:'The full path to the file within your S3 bucket (e.g. "documents/report.csv" or "myfile.txt"). This is also called the S3 "key".',required:!0}),expiresIn:T.Number({displayName:"Expires In (minutes)",description:"How long the URL should remain valid (in minutes).",required:!0,defaultValue:10})},async run(e){let t=e.auth.props,{key:o,expiresIn:a}=e.propsValue;return Ee(t)?await qn({auth:t,server:e.server,key:o,expiresIn:a}):await Yn({auth:t,key:o,expiresIn:a})}});async function qn({auth:e,server:t,key:o,expiresIn:a}){let u=a*60;if(u>fe)throw new Error(`IAM Role (OIDC) signed URLs can be valid for at most ${fe/60} minutes (12 hours). Reduce "Expires In", or use Access Key authentication for longer-lived URLs.`);let l=Math.max(u,Ke),m=await He({auth:e,server:t,durationSeconds:l}),y=new Ut.GetObjectCommand({Bucket:e.bucket,Key:o});return(0,vt.getSignedUrl)(m,y,{expiresIn:u})}p(qn,"createPresignedUrlWithAssumeRole");function Yn({auth:e,key:t,expiresIn:o}){let a=pe(e),u=new Ut.GetObjectCommand({Bucket:e.bucket,Key:t});return(0,vt.getSignedUrl)(a,u,{expiresIn:o*60})}p(Yn,"createPresignedUrlWithClient");var Ft=require("@aws-sdk/client-s3"),Bt=require("@aws-sdk/s3-request-presigner");var to=w({auth:b,name:"generate-signed-upload-url",displayName:"Generate Signed Upload URL",description:"Generate a pre-signed URL that allows anyone with the link to upload a file directly to S3 without needing AWS credentials.",audience:"both",aiMetadata:{description:"Generates a time-limited pre-signed upload (PUT) URL for a target key in the configured S3 bucket, letting anyone with the link upload a file directly to S3 without AWS credentials until it expires. Use to delegate an upload to an external client. Generating the URL does not itself create or modify any object and is idempotent (each call returns a freshly signed URL).",idempotent:!0},props:{key:T.ShortText({displayName:"File Key",description:'The destination path and filename inside the bucket, e.g. "uploads/photo.jpg".',required:!0}),expiresIn:T.Number({displayName:"Expires In (minutes)",description:"How long the upload URL should remain valid (in minutes).",required:!0,defaultValue:10})},async run(e){let t=e.auth.props,{key:o,expiresIn:a}=e.propsValue;return{url:Ee(t)?await $n({auth:t,server:e.server,key:o,expiresIn:a}):await Jn({auth:t,key:o,expiresIn:a})}}});async function $n({auth:e,server:t,key:o,expiresIn:a}){let u=(a??10)*60;if(u>fe)throw new Error(`IAM Role (OIDC) signed URLs can be valid for at most ${fe/60} minutes (12 hours). Reduce "Expires In", or use Access Key authentication for longer-lived URLs.`);let l=Math.max(u,Ke),m=await He({auth:e,server:t,durationSeconds:l}),y=new Ft.PutObjectCommand({Bucket:e.bucket,Key:o});return(0,Bt.getSignedUrl)(m,y,{expiresIn:u})}p($n,"createUploadUrlWithAssumeRole");function Jn({auth:e,key:t,expiresIn:o}){let a=pe(e),u=new Ft.PutObjectCommand({Bucket:e.bucket,Key:t});return(0,Bt.getSignedUrl)(a,u,{expiresIn:(o??10)*60})}p(Jn,"createUploadUrlWithClient");var ro=w({auth:b,name:"moveFile",displayName:"Move File",description:"Move a File to Another Folder",audience:"both",aiMetadata:{description:"Moves an object within the configured S3 bucket by copying it to a new key under the destination folder (keeping the same filename) and then deleting the original. Use to relocate or archive a file. Not idempotent \u2014 the source object is deleted on the first successful run, so a repeat call errors because the source key no longer exists.",idempotent:!1},props:{fileKey:T.ShortText({displayName:"File Path",description:'The full path to the file you want to move (e.g. "old-folder/report.csv").',required:!0}),folderKey:T.ShortText({displayName:"Destination Folder",description:'The folder path to move the file into (e.g. "archive/" or "new-folder"). The file name is kept the same.',required:!0})},async run(e){let t=e.auth.props,{bucket:o}=t,{fileKey:a,folderKey:u}=e.propsValue,l=await $({authProps:t,server:e.server}),m=a.split("/").pop(),O=`${u.endsWith("/")?u.slice(0,-1):u}/${m}`,h=await l.copyObject({Bucket:o,Key:O,CopySource:encodeURIComponent(`${o}/${a}`)}),A=await l.deleteObject({Bucket:o,Key:a});return h}});var oo=w({auth:b,name:"deleteFile",displayName:"Delete File",description:"Deletes an existing file.",audience:"both",aiMetadata:{description:"Deletes a single object from the configured S3 bucket by its full key (path). Use to remove a known file. Idempotent: deleting an already-absent key succeeds without error, so repeating the call has no further effect.",idempotent:!0},props:{key:T.ShortText({displayName:"File Path",description:'The full path to the file within your S3 bucket (e.g. "documents/report.csv" or "myfile.txt"). This is also called the S3 "key".',required:!0})},async run(e){let t=e.auth.props,{bucket:o}=t,{key:a}=e.propsValue;return await(await $({authProps:t,server:e.server})).deleteObject({Bucket:o,Key:a})}});var no=w({auth:b,name:"list-files",displayName:"List Files",description:"List all files from an S3 bucket folder/prefix.",audience:"both",aiMetadata:{description:"Lists objects in the configured S3 bucket, optionally filtered to a folder prefix (empty prefix lists the whole bucket), capped at a maximum count (1-1000, default 1000) and sorted newest-first. Use to discover files or look up an object key before reading, moving, or deleting it. Read-only and idempotent.",idempotent:!0},props:{prefix:T.ShortText({displayName:"Folder Path (Optional)",description:'Filter results to a specific folder. Enter the folder path including the trailing slash (e.g. "invoices/" or "reports/2024/"). Leave empty to list all files in the bucket.',required:!1}),maxKeys:T.Number({displayName:"Maximum Files",description:"Maximum number of files to return (1\u20131000). Defaults to 1000. Use a lower number if you only need the most recent files.",required:!1,defaultValue:1e3})},async run(e){let t=e.auth.props,o=await $({authProps:t,server:e.server}),a={Bucket:t.bucket,MaxKeys:Math.min(Math.max(e.propsValue.maxKeys||1e3,1),1e3)};e.propsValue.prefix&&(a.Prefix=e.propsValue.prefix);try{let u=await o.listObjectsV2(a),l=[];if(u.Contents)for(let y of u.Contents)!y.Key||y.Size===void 0||!y.LastModified||!y.ETag||l.push({key:y.Key,size:y.Size,lastModified:y.LastModified,etag:y.ETag,storageClass:y.StorageClass});return l.sort((y,O)=>new Date(O.lastModified).getTime()-new Date(y.lastModified).getTime()),{files:l,isTruncated:u.IsTruncated||!1}}catch(u){throw new Error(`Failed to list files from S3: ${u instanceof Error?u.message:"Unknown error"}`)}}});var Xe=require("@aws-sdk/client-secrets-manager"),io=require("@aws-sdk/client-s3"),ce=d(require("openpgp"));var ao=w({auth:b,name:"decrypt-pgp-file",displayName:"Decrypt PGP File",description:"Decrypt a PGP encrypted file from S3 using a private key stored in AWS Secrets Manager",audience:"both",aiMetadata:{description:"Downloads a PGP-encrypted object from the configured S3 bucket and decrypts it using a private key (and optional passphrase) retrieved from AWS Secrets Manager by ARN, returning the decrypted contents as a file. Use when an S3 file is PGP-encrypted and you have the key stored in Secrets Manager. Requires the secret ARN for the private key; idempotent since it only reads and decrypts without modifying anything.",idempotent:!0},props:{key:T.ShortText({displayName:"S3 File Key",description:"The key (path) of the encrypted file in S3",required:!0}),secretArn:T.ShortText({displayName:"Secret ARN",description:"The ARN of the secret in AWS Secrets Manager containing the PGP private key",required:!0}),passphraseArn:T.ShortText({displayName:"Passphrase ARN",description:"Optional ARN of the secret in AWS Secrets Manager containing the passphrase for the private key (if the key is encrypted)",required:!1}),secretsManagerRegion:T.ShortText({displayName:"Secrets Manager Region",description:"The AWS region where the Secrets Manager secret is stored (defaults to S3 region if not provided)",required:!1}),allowUnauthenticatedMessages:T.Checkbox({displayName:"Allow Unauthenticated Messages",description:"Allow decryption of messages without integrity protection (no MDC). WARNING: Without MDC, a malicious actor can silently modify the ciphertext, so the decrypted output may have been tampered with. Only enable this when working with legacy files where integrity protection was never used.",required:!1,defaultValue:!1}),allowInsecureDecryptionWithSigningKeys:T.Checkbox({displayName:"Allow Decryption With Signing Keys",description:"Allow decryption using a key not marked for encryption (e.g. a signing-only key). Enable this if your PGP key was not flagged for encryption use.",required:!1,defaultValue:!1})},async run(e){let t=e.auth.props,{bucket:o}=t,{key:a,secretArn:u,passphraseArn:l,secretsManagerRegion:m,allowUnauthenticatedMessages:y,allowInsecureDecryptionWithSigningKeys:O}=e.propsValue,h,A;if(Ee(t)){let E=await Lt({auth:t,server:e.server});h=new io.S3({credentials:E,region:t.region}),A=new Xe.SecretsManagerClient({credentials:E,region:m||t.region})}else{let E=m?{...t,region:m}:t;h=pe(t),A=qr(E)}let N;try{let S=await(await h.getObject({Bucket:o,Key:a})).Body?.transformToString("base64");if(!S)throw new Error(`Could not read file ${a} from S3`);N=Buffer.from(S,"base64")}catch(E){throw new Error(`Failed to download file from S3: ${E instanceof Error?E.message:"Unknown error"}`)}let L;try{let E=new Xe.GetSecretValueCommand({SecretId:u}),S=await A.send(E);if(!S.SecretString)throw new Error(`Secret ${u} does not contain a string value`);L=S.SecretString.trim()}catch(E){throw E instanceof Error&&E.name==="AccessDeniedException"?new Error(`Access denied when retrieving secret ${u}. Please ensure your AWS credentials have the secretsmanager:GetSecretValue permission for this secret.`):E instanceof Error&&E.name==="ResourceNotFoundException"?new Error(`Secret ${u} not found. Please verify the secret ARN is correct and exists in region ${m||t.region}.`):E instanceof Error&&E.name==="InvalidParameterException"?new Error(`Invalid secret ARN: ${u}. Please verify the ARN format is correct.`):new Error(`Failed to retrieve secret from AWS Secrets Manager: ${E instanceof Error?E.message:"Unknown error"}`)}let qe;if(l)try{let E=new Xe.GetSecretValueCommand({SecretId:l}),S=await A.send(E);if(!S.SecretString)throw new Error(`Secret ${l} does not contain a string value`);qe=S.SecretString.trim()}catch(E){throw E instanceof Error&&E.name==="AccessDeniedException"?new Error(`Access denied when retrieving passphrase secret ${l}. Please ensure your AWS credentials have the secretsmanager:GetSecretValue permission for this secret.`):E instanceof Error&&E.name==="ResourceNotFoundException"?new Error(`Passphrase secret ${l} not found. Please verify the secret ARN is correct and exists in region ${m||t.region}.`):E instanceof Error&&E.name==="InvalidParameterException"?new Error(`Invalid passphrase secret ARN: ${l}. Please verify the ARN format is correct.`):new Error(`Failed to retrieve passphrase from AWS Secrets Manager: ${E instanceof Error?E.message:"Unknown error"}`)}let Vt=N.toString("utf8");try{let E;try{E=await ce.readMessage({armoredMessage:Vt})}catch{E=await ce.readMessage({binaryMessage:N})}let S=await ce.readPrivateKey({armoredKey:L});if(!S.isPrivate())throw new Error("The provided key is not a private key. Please ensure you are using a private key, not a public key.");if(!S.isDecrypted()){if(!qe)throw new Error("Private key is encrypted but no passphrase was provided. Please provide a Passphrase ARN.");try{S=await ce.decryptKey({privateKey:S,passphrase:qe})}catch(lt){throw new Error(`Failed to unlock private key with passphrase: ${lt instanceof Error?lt.message:"Unknown error"}`)}}let z=await ce.decrypt({message:E,decryptionKeys:S,format:"binary",config:{allowInsecureDecryptionWithSigningKeys:O??!1,allowUnauthenticatedMessages:y??!1}}),Wt=new Uint8Array(await z.data),Ht=a.split("/").at(-1)?.toLowerCase().replace(/\.(pgp|gpg)$/i,"");return await e.files.write({fileName:Ht??"decrypted_file",data:Buffer.from(Wt)})}catch(E){throw new Error(`Failed to decrypt file: ${E instanceof Error?E.message:"Unknown error"}`)}}});var Zn=Vr({displayName:"Amazon S3",description:"Scalable storage in the cloud",logoUrl:"https://cdn.activepieces.com/pieces/amazon-s3.png",minimumSupportedRelease:"0.30.0",authors:["Willianwg","kishanprmr","MoShizzle","AbdulTheActivePiecer","khaledmashaly","abuaboud","Kevinyu-alan","hugh-codes"],categories:["DEVELOPER_TOOLS"],auth:b,actions:[Jr,$r,eo,to,ro,oo,no,ao],triggers:[Qr]});0&&(module.exports={amazonS3});
43
+ `,qr=[{label:"Default",value:"us-east-1"},{label:"US East (N. Virginia) [us-east-1]",value:"us-east-1"},{label:"US East (Ohio) [us-east-2]",value:"us-east-2"},{label:"US West (N. California) [us-west-1]",value:"us-west-1"},{label:"US West (Oregon) [us-west-2]",value:"us-west-2"},{label:"Africa (Cape Town) [af-south-1]",value:"af-south-1"},{label:"Asia Pacific (Hong Kong) [ap-east-1]",value:"ap-east-1"},{label:"Asia Pacific (Mumbai) [ap-south-1]",value:"ap-south-1"},{label:"Asia Pacific (Osaka-Local) [ap-northeast-3]",value:"ap-northeast-3"},{label:"Asia Pacific (Seoul) [ap-northeast-2]",value:"ap-northeast-2"},{label:"Asia Pacific (Singapore) [ap-southeast-1]",value:"ap-southeast-1"},{label:"Asia Pacific (Sydney) [ap-southeast-2]",value:"ap-southeast-2"},{label:"Asia Pacific (Tokyo) [ap-northeast-1]",value:"ap-northeast-1"},{label:"Canada (Central) [ca-central-1]",value:"ca-central-1"},{label:"Europe (Frankfurt) [eu-central-1]",value:"eu-central-1"},{label:"Europe (Ireland) [eu-west-1]",value:"eu-west-1"},{label:"Europe (London) [eu-west-2]",value:"eu-west-2"},{label:"Europe (Milan) [eu-south-1]",value:"eu-south-1"},{label:"Europe (Paris) [eu-west-3]",value:"eu-west-3"},{label:"Europe (Stockholm) [eu-north-1]",value:"eu-north-1"},{label:"Middle East (Bahrain) [me-south-1]",value:"me-south-1"},{label:"South America (S\xE3o Paulo) [sa-east-1]",value:"sa-east-1"},{label:"Europe (Spain) [eu-south-2]",value:"eu-south-2"},{label:"Asia Pacific (Hyderabad) [ap-south-2]",value:"ap-south-2"},{label:"Asia Pacific (Jakarta) [ap-southeast-3]",value:"ap-southeast-3"},{label:"Asia Pacific (Melbourne) [ap-southeast-4]",value:"ap-southeast-4"},{label:"China (Beijing) [cn-north-1]",value:"cn-north-1"},{label:"China (Ningxia) [cn-northwest-1]",value:"cn-northwest-1"},{label:"Europe (Zurich) [eu-central-2]",value:"eu-central-2"},{label:"Middle East (UAE) [me-central-1]",value:"me-central-1"}],Gn=Ke.CustomAuth({displayName:"Amazon S3 (Access Key)",description:Hn,props:{accessKeyId:T.ShortText({displayName:"Access Key ID",description:"Your AWS access key ID. Found in AWS IAM Console \u2192 Users \u2192 Security credentials.",required:!0}),secretAccessKey:Ke.SecretText({displayName:"Secret Access Key",description:"Your AWS secret access key. Only shown once when you create the access key.",required:!0}),endpoint:T.ShortText({displayName:"Endpoint (Optional)",description:"Leave blank for Amazon S3. Only set when using MinIO, DigitalOcean Spaces, Backblaze B2, etc.",required:!1}),region:T.StaticDropdown({displayName:"Region",options:{options:qr},required:!0}),bucket:T.ShortText({displayName:"Bucket Name",description:'The name of your S3 bucket (e.g. "my-company-files").',required:!0})},validate:p(async({auth:e})=>{if(!e.accessKeyId||!e.secretAccessKey)return{valid:!1,error:"Access Key ID and Secret Access Key are required."};try{return await ce(e).listObjectsV2({Bucket:e.bucket,MaxKeys:1}),{valid:!0}}catch(t){return{valid:!1,error:t?.message}}},"validate"),required:!0}),jn=Ke.OIDC({displayName:"Amazon S3 (IAM Role / OIDC)",description:Kn,props:{roleArn:T.ShortText({displayName:"Role ARN",description:"The ARN of the IAM role to assume (e.g. arn:aws:iam::123456789012:role/MyRole).",required:!0}),region:T.StaticDropdown({displayName:"Region",options:{options:qr},required:!0}),bucket:T.ShortText({displayName:"Bucket Name",description:'The name of your S3 bucket (e.g. "my-company-files").',required:!0})},validate:p(async({auth:e})=>e.roleArn?/^arn:(?:aws|aws-us-gov|aws-cn):iam::\d{12}:role\/[\w+=,.@\-/]{1,512}$/.test(e.roleArn)?{valid:!0}:{valid:!1,error:"Invalid IAM Role ARN format. Expected: arn:aws:iam::123456789012:role/RoleName"}:{valid:!1,error:"Role ARN is required for IAM Role authentication."},"validate"),required:!0}),b=[Gn,jn];var $r=w({auth:b,name:"read-file",displayName:"Read File",description:"Read a file from S3 to use it in other steps",audience:"both",aiMetadata:{description:"Downloads a single object from the configured S3 bucket by its full key (path) and makes its contents available as a file for later steps. Use to fetch a known file when you have its exact key. Reading the same key repeatedly returns the same content with no side effect (idempotent).",idempotent:!0},props:{key:T.ShortText({displayName:"File Path",description:'The full path to the file within your S3 bucket (e.g. "documents/report.csv" or "myfile.txt"). This is also called the S3 "key".',required:!0})},async run(e){let t=e.auth.props,{bucket:o}=t,{key:a}=e.propsValue,l=await(await Y({authProps:t,server:e.server})).getObject({Bucket:o,Key:a});if(!(l.Body instanceof Yr.Readable))throw new Error(`Could not read file ${a} from S3`);return await e.files.write({fileName:a,data:l.Body})}});var Jr=require("@aws-sdk/lib-storage");var Xe=d(require("mime-types")),Zr=w({auth:b,name:"upload-file",displayName:"Upload File",description:"Upload an File to S3",audience:"both",aiMetadata:{description:"Uploads a file to the configured S3 bucket, optionally setting a destination filename, content type, and canned ACL (e.g. private vs. public-read). Use to store new content in S3. Not idempotent: when no filename is given a unique timestamp-based key is generated, so each call writes a new object.",idempotent:!1},props:{file:T.File({displayName:"File",description:"The file to upload to S3.",required:!0,streaming:!0}),fileName:T.ShortText({displayName:"File Name (Optional)",required:!1,description:'The name to save the file as in S3 (e.g. "report-2024.csv"). If left blank, a unique name is generated automatically.'}),acl:T.StaticDropdown({displayName:"Access Control (ACL)",description:'Who can access this file after upload. Use "Private" for internal files, "Public Read" to make the file publicly accessible via URL.',required:!1,options:{options:[{label:"Private (only your account)",value:"private"},{label:"Public Read (anyone can view)",value:"public-read"},{label:"Public Read/Write (anyone can view and upload)",value:"public-read-write"},{label:"Authenticated AWS Users Read",value:"authenticated-read"},{label:"AWS EC2 Read (aws-exec-read)",value:"aws-exec-read"},{label:"Bucket Owner Read",value:"bucket-owner-read"},{label:"Bucket Owner Full Control",value:"bucket-owner-full-control"}]}}),type:T.ShortText({displayName:"Content Type",description:"Content Type of the uploaded file, if not set the API will try to figure out the content type.",required:!1})},async run(e){let t=e.auth.props,{bucket:o}=t,{file:a,fileName:u,acl:l,type:P}=e.propsValue,y=await Y({authProps:t,server:e.server}),O,h=null;if(P)if(Xe.default.extension(P))O=P,h="."+Xe.default.extension(P);else throw new Error("The content type entered does not exist or is misspelled, please check your input.");else{if(!a.extension||a.extension===void 0||!Xe.default.contentType(a.extension))throw new Error("Content type could not be interpreted, please check the input file.");h="."+a.extension,O=Xe.default.contentType(h)}let g=new Date().toISOString()+Date.now()+h,N=u?u.endsWith(h)?u:u+h:g,J=await new Jr.Upload({client:y,params:{Bucket:o,Key:N,ACL:l,ContentType:O,Body:a.body}}).done();return{fileName:N,etag:J.ETag}}});var qe={async poll(e,{store:t,auth:o,propsValue:a,maxItemsToPoll:u,files:l,server:P}){switch(e.strategy){case 0:{let y=await t.get("lastPoll");if(k(y))throw new Error("lastPoll doesn't exist in the store.");let O=await e.items({store:t,auth:o,propsValue:a,lastFetchEpochMS:y,server:P}),h=O.reduce((g,N)=>Math.max(g,N.epochMilliSeconds),y);return await t.put("lastPoll",h),O.filter(g=>g.epochMilliSeconds>y).map(g=>g.data)}case 1:{let y=await t.get("lastItem"),O=await e.items({store:t,auth:o,propsValue:a,lastItemId:y,files:l,server:P}),h=O.findIndex(J=>J.id===y),g=[];k(y)||h==-1?g=O??[]:g=O?.slice(0,h)??[],k(u)||(g=g.slice(-u));let N=g?.[0]?.id;return k(N)||await t.put("lastItem",N),g.map(J=>J.data)}}},async onEnable(e,{store:t,auth:o,propsValue:a,server:u}){switch(e.strategy){case 0:{await t.put("lastPoll",Date.now());break}case 1:{let P=(await e.items({store:t,auth:o,propsValue:a,lastItemId:null,server:u}))?.[0]?.id;k(P)?await t.delete("lastItem"):await t.put("lastItem",P);break}}},async onDisable(e,t){switch(e.strategy){case 0:case 1:return}},async test(e,{auth:t,propsValue:o,store:a,files:u,server:l}){let P=[];switch(e.strategy){case 0:{P=await e.items({store:a,auth:t,propsValue:o,lastFetchEpochMS:0,server:l});break}case 1:{P=await e.items({store:a,auth:t,propsValue:o,lastItemId:null,files:u,server:l});break}}return Xn(P.map(y=>y.data))}};function Xn(e){return e.length<=5?e:e.slice(0,5)}p(Xn,"getFirstFiveOrAll");var Qr=d(require("dayjs"));var ut={strategy:0,items:p(async({auth:e,propsValue:t,lastFetchEpochMS:o,server:a})=>{if(!a)throw new Error("Server context is required to resolve Amazon S3 credentials");let u=e.props,l=await Y({authProps:u,server:a});return(await qn({s3:l,bucket:u.bucket,folderPath:t.folderPath,isTest:o===0})).filter(y=>Number.isFinite(y.epochMilliSeconds))},"items")},eo=vr({auth:b,name:"new_file",displayName:"New or Updated File",description:"Triggers when you add or update a file in your bucket. The bucket/folder you choose must not contain more than 10,000 files.",aiMetadata:{description:"Fires when an object is added or modified in the configured S3 bucket, optionally scoped to a folder prefix. Polls the bucket and emits each new or updated file based on its last-modified time. The watched bucket/folder must contain no more than 10,000 files."},props:{markdown:T.MarkDown({variant:"INFO",value:"Triggers when you add or update a file in your bucket. The bucket/folder you choose must not contain more than 10,000 files."}),folderPath:T.ShortText({displayName:"Folder Path",required:!1})},type:"POLLING",onEnable:p(async e=>{await qe.onEnable(ut,{auth:e.auth,store:e.store,propsValue:e.propsValue})},"onEnable"),onDisable:p(async e=>{await qe.onDisable(ut,{auth:e.auth,store:e.store,propsValue:e.propsValue})},"onDisable"),run:p(async e=>qe.poll(ut,{auth:e.auth,store:e.store,propsValue:e.propsValue,files:e.files,server:e.server}),"run"),test:p(async e=>qe.test(ut,{auth:e.auth,store:e.store,propsValue:e.propsValue,files:e.files,server:e.server}),"test"),sampleData:{Key:"myfolder/100-3.png",LastModified:"2023-08-04T13:51:26.000Z",ETag:'"e9f16cce12352322272525f5af65a2e"',Size:40239,StorageClass:"STANDARD"}});async function qn({s3:e,bucket:t,folderPath:o,isTest:a}){let l=[],P=0,y=!0,O;do{let h={Bucket:t,MaxKeys:a?10:1e3,ContinuationToken:O};o&&(h.Prefix=o.endsWith("/")?o.slice(0,-1):o);let g=await e.listObjectsV2(h),N=g.Contents??[];if(P+N.length>1e4){l.push(...N.slice(0,1e4-P));break}if(l.push(...N),P+=N.length,a)break;y=!!g.IsTruncated,O=g.NextContinuationToken??void 0}while(y);return l.map(h=>({epochMilliSeconds:(0,Qr.default)(h.LastModified).valueOf(),data:h}))}p(qn,"fetchS3FilesForTrigger");var Ut=require("@aws-sdk/client-s3"),vt=require("@aws-sdk/s3-request-presigner");var to=w({auth:b,name:"generate-signed-url",displayName:"Generate signed URL",description:"Generate a signed URL for a file in a s3 bucket",audience:"both",aiMetadata:{description:"Generates a time-limited pre-signed download (GET) URL for an existing object in the configured S3 bucket, letting anyone with the link fetch the file without AWS credentials until it expires. Use when you need to share read access to a stored file. Read-only and idempotent (no object is modified), though each call returns a freshly signed URL.",idempotent:!0},props:{key:T.ShortText({displayName:"File Path",description:'The full path to the file within your S3 bucket (e.g. "documents/report.csv" or "myfile.txt"). This is also called the S3 "key".',required:!0}),expiresIn:T.Number({displayName:"Expires In (minutes)",description:"How long the URL should remain valid (in minutes).",required:!0,defaultValue:10})},async run(e){let t=e.auth.props,{key:o,expiresIn:a}=e.propsValue;return he(t)?await Yn({auth:t,server:e.server,key:o,expiresIn:a}):await $n({auth:t,key:o,expiresIn:a})}});async function Yn({auth:e,server:t,key:o,expiresIn:a}){let u=a*60;if(u>Se)throw new Error(`IAM Role (OIDC) signed URLs can be valid for at most ${Se/60} minutes (12 hours). Reduce "Expires In", or use Access Key authentication for longer-lived URLs.`);let l=Math.max(u,je),P=await Ge({auth:e,server:t,durationSeconds:l}),y=new Ut.GetObjectCommand({Bucket:e.bucket,Key:o});return(0,vt.getSignedUrl)(P,y,{expiresIn:u})}p(Yn,"createPresignedUrlWithAssumeRole");function $n({auth:e,key:t,expiresIn:o}){let a=ce(e),u=new Ut.GetObjectCommand({Bucket:e.bucket,Key:t});return(0,vt.getSignedUrl)(a,u,{expiresIn:o*60})}p($n,"createPresignedUrlWithClient");var Ft=require("@aws-sdk/client-s3"),Bt=require("@aws-sdk/s3-request-presigner");var ro=w({auth:b,name:"generate-signed-upload-url",displayName:"Generate Signed Upload URL",description:"Generate a pre-signed URL that allows anyone with the link to upload a file directly to S3 without needing AWS credentials.",audience:"both",aiMetadata:{description:"Generates a time-limited pre-signed upload (PUT) URL for a target key in the configured S3 bucket, letting anyone with the link upload a file directly to S3 without AWS credentials until it expires. Use to delegate an upload to an external client. Generating the URL does not itself create or modify any object and is idempotent (each call returns a freshly signed URL).",idempotent:!0},props:{key:T.ShortText({displayName:"File Key",description:'The destination path and filename inside the bucket, e.g. "uploads/photo.jpg".',required:!0}),expiresIn:T.Number({displayName:"Expires In (minutes)",description:"How long the upload URL should remain valid (in minutes).",required:!0,defaultValue:10})},async run(e){let t=e.auth.props,{key:o,expiresIn:a}=e.propsValue;return{url:he(t)?await Jn({auth:t,server:e.server,key:o,expiresIn:a}):await Zn({auth:t,key:o,expiresIn:a})}}});async function Jn({auth:e,server:t,key:o,expiresIn:a}){let u=(a??10)*60;if(u>Se)throw new Error(`IAM Role (OIDC) signed URLs can be valid for at most ${Se/60} minutes (12 hours). Reduce "Expires In", or use Access Key authentication for longer-lived URLs.`);let l=Math.max(u,je),P=await Ge({auth:e,server:t,durationSeconds:l}),y=new Ft.PutObjectCommand({Bucket:e.bucket,Key:o});return(0,Bt.getSignedUrl)(P,y,{expiresIn:u})}p(Jn,"createUploadUrlWithAssumeRole");function Zn({auth:e,key:t,expiresIn:o}){let a=ce(e),u=new Ft.PutObjectCommand({Bucket:e.bucket,Key:t});return(0,Bt.getSignedUrl)(a,u,{expiresIn:(o??10)*60})}p(Zn,"createUploadUrlWithClient");var oo=w({auth:b,name:"moveFile",displayName:"Move File",description:"Move a File to Another Folder",audience:"both",aiMetadata:{description:"Moves an object within the configured S3 bucket by copying it to a new key under the destination folder (keeping the same filename) and then deleting the original. Use to relocate or archive a file. Not idempotent \u2014 the source object is deleted on the first successful run, so a repeat call errors because the source key no longer exists.",idempotent:!1},props:{fileKey:T.ShortText({displayName:"File Path",description:'The full path to the file you want to move (e.g. "old-folder/report.csv").',required:!0}),folderKey:T.ShortText({displayName:"Destination Folder",description:'The folder path to move the file into (e.g. "archive/" or "new-folder"). The file name is kept the same.',required:!0})},async run(e){let t=e.auth.props,{bucket:o}=t,{fileKey:a,folderKey:u}=e.propsValue,l=await Y({authProps:t,server:e.server}),P=a.split("/").pop(),O=`${u.endsWith("/")?u.slice(0,-1):u}/${P}`,h=await l.copyObject({Bucket:o,Key:O,CopySource:encodeURIComponent(`${o}/${a}`)}),g=await l.deleteObject({Bucket:o,Key:a});return h}});var no=w({auth:b,name:"deleteFile",displayName:"Delete File",description:"Deletes an existing file.",audience:"both",aiMetadata:{description:"Deletes a single object from the configured S3 bucket by its full key (path). Use to remove a known file. Idempotent: deleting an already-absent key succeeds without error, so repeating the call has no further effect.",idempotent:!0},props:{key:T.ShortText({displayName:"File Path",description:'The full path to the file within your S3 bucket (e.g. "documents/report.csv" or "myfile.txt"). This is also called the S3 "key".',required:!0})},async run(e){let t=e.auth.props,{bucket:o}=t,{key:a}=e.propsValue;return await(await Y({authProps:t,server:e.server})).deleteObject({Bucket:o,Key:a})}});var io=w({auth:b,name:"list-files",displayName:"List Files",description:"List all files from an S3 bucket folder/prefix.",audience:"both",aiMetadata:{description:"Lists objects in the configured S3 bucket, optionally filtered to a folder prefix (empty prefix lists the whole bucket), capped at a maximum count (1-1000, default 1000) and sorted newest-first. Use to discover files or look up an object key before reading, moving, or deleting it. Read-only and idempotent.",idempotent:!0},props:{prefix:T.ShortText({displayName:"Folder Path (Optional)",description:'Filter results to a specific folder. Enter the folder path including the trailing slash (e.g. "invoices/" or "reports/2024/"). Leave empty to list all files in the bucket.',required:!1}),maxKeys:T.Number({displayName:"Maximum Files",description:"Maximum number of files to return (1\u20131000). Defaults to 1000. Use a lower number if you only need the most recent files.",required:!1,defaultValue:1e3})},async run(e){let t=e.auth.props,o=await Y({authProps:t,server:e.server}),a={Bucket:t.bucket,MaxKeys:Math.min(Math.max(e.propsValue.maxKeys||1e3,1),1e3)};e.propsValue.prefix&&(a.Prefix=e.propsValue.prefix);try{let u=await o.listObjectsV2(a),l=[];if(u.Contents)for(let y of u.Contents)!y.Key||y.Size===void 0||!y.LastModified||!y.ETag||l.push({key:y.Key,size:y.Size,lastModified:y.LastModified,etag:y.ETag,storageClass:y.StorageClass});return l.sort((y,O)=>new Date(O.lastModified).getTime()-new Date(y.lastModified).getTime()),{files:l,isTruncated:u.IsTruncated||!1}}catch(u){throw new Error(`Failed to list files from S3: ${u instanceof Error?u.message:"Unknown error"}`)}}});var Ye=require("@aws-sdk/client-secrets-manager"),ao=require("@aws-sdk/client-s3"),ue=d(require("openpgp"));var so=w({auth:b,name:"decrypt-pgp-file",displayName:"Decrypt PGP File",description:"Decrypt a PGP encrypted file from S3 using a private key stored in AWS Secrets Manager",audience:"both",aiMetadata:{description:"Downloads a PGP-encrypted object from the configured S3 bucket and decrypts it using a private key (and optional passphrase) retrieved from AWS Secrets Manager by ARN, returning the decrypted contents as a file. Use when an S3 file is PGP-encrypted and you have the key stored in Secrets Manager. Requires the secret ARN for the private key; idempotent since it only reads and decrypts without modifying anything.",idempotent:!0},props:{key:T.ShortText({displayName:"S3 File Key",description:"The key (path) of the encrypted file in S3",required:!0}),secretArn:T.ShortText({displayName:"Secret ARN",description:"The ARN of the secret in AWS Secrets Manager containing the PGP private key",required:!0}),passphraseArn:T.ShortText({displayName:"Passphrase ARN",description:"Optional ARN of the secret in AWS Secrets Manager containing the passphrase for the private key (if the key is encrypted)",required:!1}),secretsManagerRegion:T.ShortText({displayName:"Secrets Manager Region",description:"The AWS region where the Secrets Manager secret is stored (defaults to S3 region if not provided)",required:!1}),allowUnauthenticatedMessages:T.Checkbox({displayName:"Allow Unauthenticated Messages",description:"Allow decryption of messages without integrity protection (no MDC). WARNING: Without MDC, a malicious actor can silently modify the ciphertext, so the decrypted output may have been tampered with. Only enable this when working with legacy files where integrity protection was never used.",required:!1,defaultValue:!1}),allowInsecureDecryptionWithSigningKeys:T.Checkbox({displayName:"Allow Decryption With Signing Keys",description:"Allow decryption using a key not marked for encryption (e.g. a signing-only key). Enable this if your PGP key was not flagged for encryption use.",required:!1,defaultValue:!1})},async run(e){let t=e.auth.props,{bucket:o}=t,{key:a,secretArn:u,passphraseArn:l,secretsManagerRegion:P,allowUnauthenticatedMessages:y,allowInsecureDecryptionWithSigningKeys:O}=e.propsValue,h,g;if(he(t)){let E=await Lt({auth:t,server:e.server});h=new ao.S3({credentials:E,region:t.region}),g=new Ye.SecretsManagerClient({credentials:E,region:P||t.region})}else{let E=P?{...t,region:P}:t;h=ce(t),g=Xr(E)}let N;try{let S=await(await h.getObject({Bucket:o,Key:a})).Body?.transformToString("base64");if(!S)throw new Error(`Could not read file ${a} from S3`);N=Buffer.from(S,"base64")}catch(E){throw new Error(`Failed to download file from S3: ${E instanceof Error?E.message:"Unknown error"}`)}let J;try{let E=new Ye.GetSecretValueCommand({SecretId:u}),S=await g.send(E);if(!S.SecretString)throw new Error(`Secret ${u} does not contain a string value`);J=S.SecretString.trim()}catch(E){throw E instanceof Error&&E.name==="AccessDeniedException"?new Error(`Access denied when retrieving secret ${u}. Please ensure your AWS credentials have the secretsmanager:GetSecretValue permission for this secret.`):E instanceof Error&&E.name==="ResourceNotFoundException"?new Error(`Secret ${u} not found. Please verify the secret ARN is correct and exists in region ${P||t.region}.`):E instanceof Error&&E.name==="InvalidParameterException"?new Error(`Invalid secret ARN: ${u}. Please verify the ARN format is correct.`):new Error(`Failed to retrieve secret from AWS Secrets Manager: ${E instanceof Error?E.message:"Unknown error"}`)}let Z;if(l)try{let E=new Ye.GetSecretValueCommand({SecretId:l}),S=await g.send(E);if(!S.SecretString)throw new Error(`Secret ${l} does not contain a string value`);Z=S.SecretString.trim()}catch(E){throw E instanceof Error&&E.name==="AccessDeniedException"?new Error(`Access denied when retrieving passphrase secret ${l}. Please ensure your AWS credentials have the secretsmanager:GetSecretValue permission for this secret.`):E instanceof Error&&E.name==="ResourceNotFoundException"?new Error(`Passphrase secret ${l} not found. Please verify the secret ARN is correct and exists in region ${P||t.region}.`):E instanceof Error&&E.name==="InvalidParameterException"?new Error(`Invalid passphrase secret ARN: ${l}. Please verify the ARN format is correct.`):new Error(`Failed to retrieve passphrase from AWS Secrets Manager: ${E instanceof Error?E.message:"Unknown error"}`)}let Vt=N.toString("utf8");try{let E;try{E=await ue.readMessage({armoredMessage:Vt})}catch{E=await ue.readMessage({binaryMessage:N})}let S=await ue.readPrivateKey({armoredKey:J});if(!S.isPrivate())throw new Error("The provided key is not a private key. Please ensure you are using a private key, not a public key.");if(!S.isDecrypted()){if(!Z)throw new Error("Private key is encrypted but no passphrase was provided. Please provide a Passphrase ARN.");try{S=await ue.decryptKey({privateKey:S,passphrase:Z})}catch(lt){throw new Error(`Failed to unlock private key with passphrase: ${lt instanceof Error?lt.message:"Unknown error"}`)}}let z=await ue.decrypt({message:E,decryptionKeys:S,format:"binary",config:{allowInsecureDecryptionWithSigningKeys:O??!1,allowUnauthenticatedMessages:y??!1}}),Wt=new Uint8Array(await z.data),Ht=a.split("/").at(-1)?.toLowerCase().replace(/\.(pgp|gpg)$/i,"");return await e.files.write({fileName:Ht??"decrypted_file",data:Buffer.from(Wt)})}catch(E){throw new Error(`Failed to decrypt file: ${E instanceof Error?E.message:"Unknown error"}`)}}});var Qn=Br({displayName:"Amazon S3",description:"Scalable storage in the cloud",logoUrl:"https://cdn.activepieces.com/pieces/amazon-s3.png",minimumSupportedRelease:"0.30.0",authors:["Willianwg","kishanprmr","MoShizzle","AbdulTheActivePiecer","khaledmashaly","abuaboud","Kevinyu-alan","hugh-codes"],categories:["DEVELOPER_TOOLS"],auth:b,actions:[Zr,$r,to,ro,oo,no,io,so],triggers:[eo]});0&&(module.exports={amazonS3});