@stackone/core 1.49.1 → 1.49.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.mjs CHANGED
@@ -1 +1 @@
1
- import{notMissing as e,getCountrySubDivisionNameBySubDivisionCode as t,getCountryAlpha2CodeByCitizenship as r,getCountrySubDivisionCodeBySubDivisionName as o,getCountrySubDivisionsByAlpha2Code as n,getCountryCodeByCountryName as s,getCountryCodeByAlpha3Code as a,getCountryCodeByAlpha2Code as i,getCountryAlpha2CodeByCountryCode as u,getCountryAlpha2CodeByCountryName as c,getCountryAlpha2CodeByAlpha3Code as l,getCountryAlpha3CodeByCountryCode as d,getCountryAlpha3CodeByCountryName as p,getCountryAlpha3CodeByAlpha2Code as m,getCountryNameByCountryCode as g,getCountryNameByAlpha2Code as y,getCountryNameByAlpha3Code as b,getCountryNameByCountryName as f,getCountryCodeByCountryCode as h,getCountryAlpha3CodeByAlpha3Code as _,getCountryAlpha2CodeByAlpha2Code as v,isString as k,isMissing as E,safeParseToDateTimeString as S,safeParseToBoolean as I,safeParseToNumber as w,safeParseToString as x,encodeToBase64 as j,decodeFromBase64 as C,getContentHash as F}from"@stackone/utils";import{z as T}from"zod";import{evaluate as O,safeEvaluateRecord as R}from"@stackone/expressions";import{CUSTOM_ERROR_CONFIG_SCHEMA as A,RequestParameterLocations as D,HttpMethods as K,RequestClientFactory as N,parseRequestParameters as P,createAuthorizationHeaders as $}from"@stackone/transport";const M=T.object({stepsDataToGroup:T.array(T.string()),isSingleRecord:T.boolean().optional()}),U=T.object({data:T.unknown()}),q=(e,t,r)=>Object.entries(e).reduce(((e,[o,n])=>{const s=n?.output?.data;return Array.isArray(s)&&s.length===t?e[o]={output:{data:s[r]}}:e[o]=n,e}),{}),G=(e,t,r)=>{if(!e||!r)return{record:e};const o={unified:{...e},..."object"==typeof r?r:{}},n={},s=[],a={...e};for(const r of t){const{error:t,value:i}=L(o,e.id,r);t?s.push(t):r.custom?n[r.targetFieldKey]=i:a[r.targetFieldKey]=i}return{record:{...a,unified_custom_fields:Object.keys(n).length>0?n:void 0},errors:s.length>0?s:void 0}},L=(e,t,r)=>{const{expression:o,targetFieldKey:n}=r;if(!o)return{error:{message:"Expression is empty",id:t,targetField:n}};let s;try{s=O(o,e)}catch{return{error:{message:"Invalid expression",id:t,targetField:n}}}return void 0===s?{error:{message:"Expression returned no value",id:t,targetField:n}}:{value:s}},B=T.object({fields:T.object({targetFieldKey:T.string(),alias:T.string().optional(),expression:T.string(),type:T.enum(["string","number","boolean","datetime_string","enum"]),custom:T.boolean().default(!1),hidden:T.boolean().default(!1),enumMapper:T.object({matcher:T.string().or(T.object({matchExpression:T.string(),value:T.string()}).array())}).optional()}).array(),dataSource:T.string()}),H=T.object({data:T.unknown()}),z=(e,t)=>{if(!t)return;const r={},o=[],n={};for(const s of e){const{error:e,value:a}=W(t,t?.id,s);e?o.push(e):s.custom?r[s.targetFieldKey]=a:n[s.targetFieldKey]=a}return{record:{...n,unified_custom_fields:Object.keys(r).length>0?r:void 0},errors:o.length>0?o:void 0}},W=(e,t,r)=>{switch(r.type){case"string":case"number":case"boolean":case"datetime_string":return Q(r,t,e);case"enum":return Y(r,t,e);default:return{error:{message:"Invalid type",id:t,targetField:r.targetFieldKey}}}},Q=(e,t,r)=>{if(!e.expression)return{error:{message:"Expression is empty",id:t,targetField:e.targetFieldKey}};let o;try{o=O(e.expression,r)}catch{return{error:{message:"Invalid expression",id:t,targetField:e.targetFieldKey}}}return void 0===o?{error:{message:"Expression returned no value",id:t,targetField:e.targetFieldKey}}:{value:o}},Y=(E,S,I)=>{const w=Q(E,S,I),x=e(w.value)?w.value:null;if(void 0===E.enumMapper)return{error:{message:"Enum mapper was not defined",id:S,targetField:E.targetFieldKey}};const j=E.enumMapper.matcher;if(k(j)){const k=(e=>{switch(e){case"country_alpha2code_by_alpha2code":return v;case"country_alpha3code_by_alpha3code":return _;case"country_code_by_country_code":return h;case"country_name_by_country_name":return f;case"country_name_by_alpha3code":return b;case"country_name_by_alpha2code":return y;case"country_name_by_country_code":return g;case"country_alpha3code_by_alpha2code":return m;case"country_alpha3code_by_country_name":return p;case"country_alpha3code_by_country_code":return d;case"country_alpha2code_by_alpha3code":return l;case"country_alpha2code_by_country_name":return c;case"country_alpha2code_by_country_code":return u;case"country_code_by_alpha2code":return i;case"country_code_by_alpha3code":return a;case"country_code_by_country_name":return s;case"country_subdivisions_by_alpha2code":return n;case"country_subdivision_code_by_subdivision_name":return o;case"country_alpha2code_by_citizenship":return r;case"country_subdivision_name_by_subdivision_code":return t;default:return}})(j);if(e(k)){return{value:{value:(e(x)?k(x):null)??"unmapped_value",source_value:x}}}return{error:{message:`The built-in matcher "${j}" is not supported`,id:S,targetField:E.targetFieldKey}}}for(const e of j){const{matchExpression:t,value:r}=e;if(!0===O(t,I))return{value:{value:r,source_value:x}}}return{value:{value:"unmapped_value",source_value:x}}},J=T.object({type:T.literal("basic"),username:T.string().optional(),password:T.string().optional(),encoding:T.string().optional()}),V=T.object({type:T.literal("bearer"),token:T.string()}),X=T.discriminatedUnion("type",[J,V]),Z=T.object({baseUrl:T.string(),url:T.string(),method:T.enum(K),response:T.object({indexField:T.string().optional(),dataKey:T.string().optional(),nextKey:T.string().optional()}).optional(),iterator:T.object({key:T.string(),in:T.enum(D)}),cursor:T.object({token:T.string().optional().nullable(),position:T.number().optional().nullable()}).optional(),customErrors:A.array().optional(),args:T.object({name:T.string(),value:T.unknown(),in:T.enum(D),condition:T.string().optional()}).array().optional()}),ee=T.object({data:T.unknown().optional(),raw:T.unknown().optional(),statusCode:T.number(),message:T.string().optional(),next:T.string().optional().nullable(),position:T.number().optional()}).optional(),te=(e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce(((e,r)=>{const o=t.indexField;return o&&r[o]&&(e[r[o]]=r),e}),{});if(t?.indexField){const r=t.indexField;return r&&e[r]?{[e[r]]:e}:e}return e},re=T.object({type:T.literal("basic"),username:T.string().optional(),password:T.string().optional(),encoding:T.string().optional()}),oe=T.object({type:T.literal("bearer"),token:T.string()}),ne=T.discriminatedUnion("type",[re,oe]),se=T.object({baseUrl:T.string(),url:T.string(),method:T.enum(K),response:T.object({collection:T.boolean().optional(),indexField:T.string().optional(),dataKey:T.string().optional()}).optional(),customErrors:A.array().optional(),args:T.object({name:T.string(),value:T.unknown(),in:T.enum(D),condition:T.string().optional()}).array().optional()}),ae=T.object({data:T.unknown().optional(),raw:T.unknown().optional(),statusCode:T.number(),message:T.string().optional()}).optional(),ie=(e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce(((e,r)=>{const o=t.indexField;return o&&r[o]&&(e[r[o]]=r),e}),{});if(!t?.collection&&t?.indexField){const r=t.indexField;return r&&e[r]?{[e[r]]:e}:e}return e},ue=T.object({fields:T.object({targetFieldKey:T.string(),alias:T.string().optional(),type:T.string(),custom:T.boolean().default(!1),hidden:T.boolean().default(!1)}).array().optional(),dataSource:T.string()}),ce=T.object({data:T.unknown()});var le;!function(e){e.String="string",e.Number="number",e.Boolean="boolean",e.DateTimeString="datetime_string"}(le||(le={}));const de=({value:e,type:t,format:r})=>{if(E(e))return null;switch(t){case le.String:return x({value:e});case le.Number:return w({value:e});case le.Boolean:return I({value:e});case le.DateTimeString:return S({value:e,format:r});default:return e}},pe=e=>Object.values(le).includes(e),me=(t,r)=>{const o={...t};return r.forEach((r=>{const{targetFieldKey:n,type:s}=r;pe(s)&&(!r.custom&&e(o[n])?o[n]=de({value:t[n],type:s}):o.unified_custom_fields&&e(o.unified_custom_fields?.[n])&&(o.unified_custom_fields[n]=de({value:t.unified_custom_fields?.[n],type:s})))})),{...o}},ge=(t,r)=>{const o={...t};return r.forEach((r=>{const{targetFieldKey:n,type:s}=r;pe(s)&&(!r.custom&&e(o[n])?o[n]=de({value:t[n],type:s}):o.unified_custom_fields&&e(o.unified_custom_fields?.[n])&&(o.unified_custom_fields[n]=de({value:t.unified_custom_fields?.[n],type:s})))})),{...o}};var ye;!function(e){e.TYPECAST="typecast",e.MAP_FIELDS="map_fields",e.GROUP_DATA="group_data",e.REQUEST="request",e.PAGINATED_REQUEST="paginated_request"}(ye||(ye={}));const be={[ye.TYPECAST]:{v1:{fn:async({block:e})=>{const t=e?.fieldConfigs;if(!t||"disabled"===e?.debug?.custom_mappings)return{block:e,successful:!0};let r;return r=Array.isArray(e.result)?e.result.map((e=>me(e,t))):me(e.result,t),{block:{...e,result:r},successful:!0}}},v2:{fn:async({block:e,params:t})=>{const{fields:r,dataSource:o}=ue.parse(t),n=O(o,e);if(!r||"disabled"===e?.debug?.custom_mappings)return{block:e,successful:!0};let s;return s=Array.isArray(n)?n.map((e=>ge(e,r))):ge(n,r),{block:{...e},successful:!0,output:{data:s}}},inputSchema:ue,outputSchema:ce}},[ye.MAP_FIELDS]:{v1:{fn:async({block:e})=>{const t=e?.fieldConfigs,r=[],o=e.steps;if(!t||"disabled"===e?.debug?.custom_mappings||!o)return{block:e,successful:!0};let n;if(Array.isArray(e.result)){const s=e.result.length;n=e.result.map(((e,n)=>{const a=q(o,s,n),i=G(e,t,a);return r.push(...i.errors||[]),i.record}))}else{const s=G(e.result,t,o);n=s.record,r.push(...s.errors||[])}return{block:{...e,result:n},successful:!0,errors:Object.keys(r).length>0?r:void 0}}},v2:{fn:async({block:e,params:t})=>{const r=[],{fields:o,dataSource:n}=B.parse(t),s=O(n,e);if(!o||!n||"disabled"===e?.debug?.custom_mappings||!s)return{block:e,successful:!0};let a;if(Array.isArray(s))a=s.map((e=>{const t=z(o,e);return r.push(...t?.errors||[]),t?.record}));else{const e=z(o,s);a=e?.record,r.push(...e?.errors||[])}return{block:{...e},successful:!0,output:{data:a},errors:Object.keys(r).length>0?r:void 0}},inputSchema:B,outputSchema:H}},[ye.REQUEST]:{v1:{fn:async({block:e,params:t})=>{const r=N.build();if(!e.httpClient)throw new Error("HTTP client is not configured");const{args:o}=t,n=o?o.filter((t=>!t.condition||!0===O(t.condition,e))).map((e=>({...e,condition:void 0}))):void 0,s=t?R({...t,args:n},e):{},{baseUrl:a,url:i,method:u,response:c,customErrors:l,args:d}=se.parse(s),p=s?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,m=ne.parse(p),g=d?P(d):{query:{},body:{},headers:{}},y=$(m),b={...g?.headers??{},...y};let f;try{f=await r.performRequest({httpClient:e.httpClient,url:`${a}${i}`,queryParams:g?.query,method:u,headers:b,body:g?.body,customErrorConfigs:l})}catch(t){const r=t;return{block:e,successful:!1,errors:[t],output:{statusCode:r?.response?.status??500,message:r?.response?.message}}}const h=c?.dataKey?f.data[c?.dataKey]:f.data,_=ie(h,c);return{block:e,successful:!0,output:{data:_,raw:f,statusCode:f?.status,message:f?.message}}},inputSchema:se,outputSchema:ae}},[ye.GROUP_DATA]:{v1:{fn:async({block:t,params:r})=>{const{stepsDataToGroup:o,isSingleRecord:n}=M.parse(r),s=o.reduce(((r,o)=>{const s=t.steps?.[o]?.output?.data;return s?n?{...r,[o]:{...s}}:(Object.keys(s).forEach((t=>{const n=e(r[t])?r[t]:{};r[t]={...n,[o]:{...s[t]}}})),r):r}),{});return{block:{...t},successful:!0,output:{data:n?s:Object.values(s)}}},inputSchema:M,outputSchema:U}},[ye.PAGINATED_REQUEST]:{v1:{fn:async({block:t,params:r})=>{const o=N.build();if(!t.httpClient)throw new Error("HTTP client is not configured");const{args:n}=r,s=Number(t.inputs?.page_size),a=Number.isNaN(s)?25:s,i=n?n.filter((e=>!e.condition||!0===O(e.condition,t))).map((e=>({...e,condition:void 0}))):void 0,u=r?R({...r,args:i},t):{},{baseUrl:c,url:l,method:d,response:p,iterator:m,cursor:g,customErrors:y,args:b}=Z.parse(u),f=u?.authentication?.[t.context.authenticationType]?.[t.context.environment]?.authorization,h=X.parse(f),_=b?P(b):{query:{},body:{},headers:{}},v=$(h),k={..._?.headers??{},...v};let S=g?.token??null,I=null,w=null,x=[],j=[];const C=[];let F=a,T=g?.position??0,A=!0,D=!0;do{let e;A?A=!1:T=0,null!==S&&("query"===m.in?_.query[m.key]=S.toString():"body"===m.in&&(_.body[m.key]=S));try{e=await o.performRequest({httpClient:t.httpClient,url:`${c}${l}`,queryParams:_?.query,method:d,headers:k,body:_?.body,customErrorConfigs:y})}catch(e){const r=e;return{block:t,successful:!1,errors:[e],output:{statusCode:r?.response?.status??500,message:r?.response?.message}}}I=S,j=p?.dataKey?e.data[p?.dataKey]:e.data;const r=j?.slice(T,F);F-=r.length,T+=r.length,C.push(e),x=x.concat(r),w=e?.status,S=p?.nextKey?e.data[p?.nextKey]:void 0,r.length===j.length&&0===F&&(T=0,I=S),D=E(S)&&x.length<a}while(e(S)&&x.length<a&&j?.length>0);const K=te(x,p);return{block:t,successful:!0,output:{data:K,raw:C,statusCode:w,next:D?void 0:I,position:D?void 0:T}}},inputSchema:Z,outputSchema:ee}}},fe=(e,t)=>async({block:r,params:o})=>{try{e.inputSchema&&e.inputSchema.parse(o)}catch{return{block:r,successful:!1,errors:[{message:`Input parameters for ${t} are invalid`}]}}const n=await e.fn({block:r,params:o});try{e.outputSchema&&e.outputSchema.parse(n.output)}catch{return{block:r,successful:!1,errors:[{message:`Output data of ${t} has unexpected format`}]}}return n},he={build({functionName:e,version:t="1",validateSchemas:r=!1,stepFunctionsList:o=be}){const n=o?.[e]?.[`v${t}`];if(!n)throw new Error(`Unknown step function: ${e} v${t}`);return r?{...n,fn:fe(n,e)}:n}},_e={hris:{title:"HRIS",key:"hris",description:"Human Resource Information System"},crm:{title:"CRM",key:"crm",description:"Customer Relationship Management"},ats:{title:"ATS",key:"ats",description:"Applicant Tracking System"},lms:{title:"LMS",key:"lms",description:"Learning Management System"},marketing:{title:"Marketing",key:"marketing",description:"Marketing"},filestorage:{title:"File Storage",key:"filestorage",description:"File Storage"}},ve=e=>_e[e.toLowerCase()]??null,ke=e=>!!_e[e.toLowerCase()];var Ee;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warning=3]="Warning",e[e.Error=4]="Error"}(Ee||(Ee={}));const Se=T.object({r:T.record(T.string(),T.object({n:T.number().optional().nullable(),c:T.string().optional().nullable(),p:T.number().optional().nullable()})),v:T.number(),t:T.number()}),Ie=T.object({remote:T.record(T.string(),T.object({pageNumber:T.number().optional(),providerPageCursor:T.string().optional(),position:T.number().optional()})),version:T.number(),timestamp:T.number()}),we=e=>j(JSON.stringify(xe(e))),xe=e=>{const{remote:t,version:r,timestamp:o}=e;return{r:Object.fromEntries(Object.entries(t).map((([e,{pageNumber:t,providerPageCursor:r,position:o}])=>[e,{n:t,c:r,p:o}]))),v:r,t:o}},je=e=>{try{if(k(e)){const t=C(e),r=JSON.parse(t),o=Se.parse(r);return Ce(o)}return Ie.parse(e),e}catch{return null}},Ce=e=>{const{r:t,v:r,t:o}=e;return{remote:Object.fromEntries(Object.entries(t).map((([e,{n:t,c:r,p:o}])=>[e,{pageNumber:t,providerPageCursor:r,position:o}]))),version:r,timestamp:o}},Fe=(e,t)=>{const r="string"==typeof e?je(e):e,o="string"==typeof t?je(t):t;if(null===r||null===o)return r===o;const{timestamp:n,...s}=r,{timestamp:a,...i}=o;return F(s)===F(i)},Te=({cursor:e,ignoreStepIndex:t})=>!!E(e)||Object.keys(e?.remote??{}).reduce(((r,o)=>{const n=e?.remote?.[o];return(E(t)||o!==t.toString())&&(r=r&&E(n.pageNumber)&&E(n.position)&&E(n.providerPageCursor)),r}),!0),Oe=({cursor:e,stepIndex:t,pageNumber:r,providerPageCursor:o,position:n})=>{const s={pageNumber:r??void 0,providerPageCursor:o??void 0,position:n??void 0},a=E(r)&&E(o)&&E(n);return E(e)?{remote:a?{}:{[t]:s},version:2,timestamp:Date.now()}:a?(delete e.remote[t],e):{...e,remote:{...e.remote,[t]:s}}};class Re extends Error{constructor({category:e,name:t,type:r,context:o,message:n}){super(n),this.name=t??"CoreError",this.type=r,this.category=e,this.context=o,Error.captureStackTrace&&Error.captureStackTrace(this,Re)}toString(){const e=this.message?`: ${this.message}`:"";return`${this.category}-${this.name} [${this.type}]${e}`}}const Ae=e=>e instanceof Re,De=j("so1!"),Ke=":",Ne=",",Pe=new RegExp(`(?<!\\\\)${Ke}`,"g"),$e=new RegExp(`(?<!\\\\)${Ne}`,"g"),Me=1;class Ue extends Re{constructor(e,t,r){super({category:"CompositeId",name:t??"BaseCompositeIdError",type:e,message:r})}}class qe extends Ue{constructor(e){super("COMPOSITE_ID_MISSING_HEADER_ERROR","CompositeIdMissingHeaderError",e??"Invalid compositeId, missing header")}}class Ge extends Ue{constructor(e){super("COMPOSITE_ID_MISSING_BODY_ERROR","CompositeIdMissingBodyError",e??"Invalid compositeId, missing body")}}class Le extends Ue{constructor(e){super("COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR","CompositeIdUnknownIdentifierError",e??"Invalid compositeId, unknown identifier")}}class Be extends Ue{constructor(e){super("COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR","CompositeIdUnsupportedVersionError",e??"Invalid compositeId, unsupported version")}}const He=(e,t={version:1})=>{if(1===t.version)return Ve(We(e,t.aliases));throw new Be(`Cannot generate ID, unsupported version number: ${t.version}`)},ze=(e,t={version:1})=>{const r=Je(e,t),o={};return r?(r.split($e).forEach((e=>{const[r,n]=e.split(Pe),s=Ye(r,t.aliases??{});o[s]=et(n)})),o):o},We=(e,t={})=>{if((e=>!E(e)&&"value"in e&&void 0!==e.value)(e))return Qe({identifier:e,compositeIdAliases:t,isSoleIdentifier:!0});if((e=>!E(e)&&"identifiers"in e&&void 0!==e.identifiers)(e))return e.identifiers.map((e=>Qe({identifier:e,compositeIdAliases:t,isSoleIdentifier:!1}))).join(Ne);throw new Le},Qe=({identifier:e,compositeIdAliases:t,isSoleIdentifier:r})=>[r?"id":t[e.key]||e.key,Ze(e.value)].filter(Boolean).join(Ke),Ye=(e,t)=>Object.keys(t).find((r=>t[r]===e))||e,Je=(e,t)=>{if(1===t.version)return Xe(e);throw new Be(`Cannot decode ID, unsupported version number: ${t.version}`)},Ve=e=>`${De}${j(e)}`,Xe=e=>{if(!e.startsWith(De))throw new qe(`Trying to decode an ID without the header: ${e}`);const t=e.split(De)[1];if(!t)throw new Ge(`Trying to decode an ID without a body: ${e}`);return C(t)},Ze=e=>[Ne,Ke].reduce(((e,t)=>e.replace(t,"\\"+t)),e),et=e=>[Ne,Ke].reduce(((e,t)=>{const r="\\"+t;return e.replace(new RegExp("\\\\"+r,"g"),t)}),e),tt=e=>!E(e)&&e.startsWith(De);export{ne as AUTHENTICATION_SCHEMA,Me as COMPOSITE_ID_LATEST_VERSION,Re as CoreError,Ee as LogLevel,ye as StepFunctionName,he as StepFunctionsFactory,Fe as areCursorsEqual,ze as decodeCompositeId,He as encodeCompositeId,je as expandCursor,ve as getCategoryDetails,tt as isCompositeId,Ae as isCoreError,Te as isCursorEmpty,ke as isValidCategory,we as minifyCursor,Oe as updateCursor};
1
+ import{notMissing as e,getCountrySubDivisionNameBySubDivisionCode as t,getCountryAlpha2CodeByCitizenship as r,getCountrySubDivisionCodeBySubDivisionName as o,getCountrySubDivisionsByAlpha2Code as n,getCountryCodeByCountryName as s,getCountryCodeByAlpha3Code as a,getCountryCodeByAlpha2Code as i,getCountryAlpha2CodeByCountryCode as u,getCountryAlpha2CodeByCountryName as c,getCountryAlpha2CodeByAlpha3Code as l,getCountryAlpha3CodeByCountryCode as d,getCountryAlpha3CodeByCountryName as p,getCountryAlpha3CodeByAlpha2Code as m,getCountryNameByCountryCode as g,getCountryNameByAlpha2Code as y,getCountryNameByAlpha3Code as b,getCountryNameByCountryName as f,getCountryCodeByCountryCode as h,getCountryAlpha3CodeByAlpha3Code as _,getCountryAlpha2CodeByAlpha2Code as v,isString as k,isMissing as E,safeParseToDateTimeString as S,safeParseToBoolean as I,safeParseToNumber as w,safeParseToString as x,encodeToBase64 as j,decodeFromBase64 as C,getContentHash as F}from"@stackone/utils";import{z as T}from"zod";import{evaluate as O,safeEvaluateRecord as R}from"@stackone/expressions";import{CUSTOM_ERROR_CONFIG_SCHEMA as A,RequestParameterLocations as D,HttpMethods as K,RequestClientFactory as N,parseRequestParameters as P,createAuthorizationHeaders as $}from"@stackone/transport";const M=T.object({stepsDataToGroup:T.array(T.string()),isSingleRecord:T.boolean().optional()}),U=T.object({data:T.unknown()}),q=(e,t,r)=>Object.entries(e).reduce(((e,[o,n])=>{const s=n?.output?.data;return Array.isArray(s)&&s.length===t?e[o]={output:{data:s[r]}}:e[o]=n,e}),{}),G=(e,t,r)=>{if(!e||!r)return{record:e};const o={unified:{...e},..."object"==typeof r?r:{}},n={},s=[],a={...e};for(const r of t){const{error:t,value:i}=L(o,e.id,r);t?s.push(t):r.custom?n[r.targetFieldKey]=i:a[r.targetFieldKey]=i}return{record:{...a,unified_custom_fields:Object.keys(n).length>0?n:void 0},errors:s.length>0?s:void 0}},L=(e,t,r)=>{const{expression:o,targetFieldKey:n}=r;if(!o)return{error:{message:"Expression is empty",id:t,targetField:n}};let s;try{s=O(o,e)}catch{return{error:{message:"Invalid expression",id:t,targetField:n}}}return void 0===s?{error:{message:"Expression returned no value",id:t,targetField:n}}:{value:s}},B=T.object({fields:T.object({targetFieldKey:T.string(),alias:T.string().optional(),expression:T.string(),type:T.enum(["string","number","boolean","datetime_string","enum"]),custom:T.boolean().default(!1),hidden:T.boolean().default(!1),enumMapper:T.object({matcher:T.string().or(T.object({matchExpression:T.string(),value:T.string()}).array())}).optional()}).array(),dataSource:T.string()}),H=T.object({data:T.unknown()}),z=(e,t)=>{if(!t)return;const r={},o=[],n={};for(const s of e){const{error:e,value:a}=W(t,t?.id,s);e?o.push(e):s.custom?r[s.targetFieldKey]=a:n[s.targetFieldKey]=a}return{record:{...n,unified_custom_fields:Object.keys(r).length>0?r:void 0},errors:o.length>0?o:void 0}},W=(e,t,r)=>{switch(r.type){case"string":case"number":case"boolean":case"datetime_string":return Q(r,t,e);case"enum":return Y(r,t,e);default:return{error:{message:"Invalid type",id:t,targetField:r.targetFieldKey}}}},Q=(e,t,r)=>{if(!e.expression)return{error:{message:"Expression is empty",id:t,targetField:e.targetFieldKey}};let o;try{o=O(e.expression,r)}catch{return{error:{message:"Invalid expression",id:t,targetField:e.targetFieldKey}}}return void 0===o?{error:{message:"Expression returned no value",id:t,targetField:e.targetFieldKey}}:{value:o}},Y=(E,S,I)=>{const w=Q(E,S,I),x=e(w.value)?w.value:null;if(void 0===E.enumMapper)return{error:{message:"Enum mapper was not defined",id:S,targetField:E.targetFieldKey}};const j=E.enumMapper.matcher;if(k(j)){const k=(e=>{switch(e){case"country_alpha2code_by_alpha2code":return v;case"country_alpha3code_by_alpha3code":return _;case"country_code_by_country_code":return h;case"country_name_by_country_name":return f;case"country_name_by_alpha3code":return b;case"country_name_by_alpha2code":return y;case"country_name_by_country_code":return g;case"country_alpha3code_by_alpha2code":return m;case"country_alpha3code_by_country_name":return p;case"country_alpha3code_by_country_code":return d;case"country_alpha2code_by_alpha3code":return l;case"country_alpha2code_by_country_name":return c;case"country_alpha2code_by_country_code":return u;case"country_code_by_alpha2code":return i;case"country_code_by_alpha3code":return a;case"country_code_by_country_name":return s;case"country_subdivisions_by_alpha2code":return n;case"country_subdivision_code_by_subdivision_name":return o;case"country_alpha2code_by_citizenship":return r;case"country_subdivision_name_by_subdivision_code":return t;default:return}})(j);if(e(k)){return{value:{value:(e(x)?k(x):null)??"unmapped_value",source_value:x}}}return{error:{message:`The built-in matcher "${j}" is not supported`,id:S,targetField:E.targetFieldKey}}}for(const e of j){const{matchExpression:t,value:r}=e;if(!0===O(t,I))return{value:{value:r,source_value:x}}}return{value:{value:"unmapped_value",source_value:x}}},J=T.object({type:T.literal("basic"),username:T.string().optional(),password:T.string().optional(),encoding:T.string().optional()}),V=T.object({type:T.literal("bearer"),token:T.string()}),X=T.discriminatedUnion("type",[J,V]),Z=T.object({baseUrl:T.string(),url:T.string(),method:T.enum(K),response:T.object({indexField:T.string().optional(),dataKey:T.string().optional(),nextKey:T.string().optional()}).optional(),iterator:T.object({key:T.string(),in:T.enum(D)}),cursor:T.object({token:T.string().optional().nullable(),position:T.number().optional().nullable()}).optional(),customErrors:A.array().optional(),args:T.object({name:T.string(),value:T.unknown(),in:T.enum(D),condition:T.string().optional()}).array().optional()}),ee=T.object({data:T.unknown().optional(),raw:T.unknown().optional(),statusCode:T.number(),message:T.string().optional(),next:T.string().optional().nullable(),position:T.number().optional()}).optional(),te=(e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce(((e,r)=>{const o=t.indexField;return o&&r[o]&&(e[r[o]]=r),e}),{});if(t?.indexField){const r=t.indexField;return r&&e[r]?{[e[r]]:e}:e}return e},re=T.object({type:T.literal("basic"),username:T.string().optional(),password:T.string().optional(),encoding:T.string().optional()}),oe=T.object({type:T.literal("bearer"),token:T.string()}),ne=T.discriminatedUnion("type",[re,oe]),se=T.object({baseUrl:T.string(),url:T.string(),method:T.enum(K),response:T.object({collection:T.boolean().optional(),indexField:T.string().optional(),dataKey:T.string().optional()}).optional(),customErrors:A.array().optional(),args:T.object({name:T.string(),value:T.unknown(),in:T.enum(D),condition:T.string().optional()}).array().optional()}),ae=T.object({data:T.unknown().optional(),raw:T.unknown().optional(),statusCode:T.number(),message:T.string().optional()}).optional(),ie=(e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce(((e,r)=>{const o=t.indexField;return o&&r[o]&&(e[r[o]]=r),e}),{});if(!t?.collection&&t?.indexField){const r=t.indexField;return r&&e[r]?{[e[r]]:e}:e}return e},ue=T.object({fields:T.object({targetFieldKey:T.string(),alias:T.string().optional(),type:T.string(),custom:T.boolean().default(!1),hidden:T.boolean().default(!1)}).array().optional(),dataSource:T.string()}),ce=T.object({data:T.unknown()});var le;!function(e){e.String="string",e.Number="number",e.Boolean="boolean",e.DateTimeString="datetime_string"}(le||(le={}));const de=({value:e,type:t,format:r})=>{if(E(e))return null;switch(t){case le.String:return x({value:e});case le.Number:return w({value:e});case le.Boolean:return I({value:e});case le.DateTimeString:return S({value:e,format:r});default:return e}},pe=e=>Object.values(le).includes(e),me=(t,r)=>{const o={...t};return r.forEach((r=>{const{targetFieldKey:n,type:s}=r;pe(s)&&(!r.custom&&e(o[n])?o[n]=de({value:t[n],type:s}):o.unified_custom_fields&&e(o.unified_custom_fields?.[n])&&(o.unified_custom_fields[n]=de({value:t.unified_custom_fields?.[n],type:s})))})),{...o}},ge=(t,r)=>{const o={...t};return r.forEach((r=>{const{targetFieldKey:n,type:s}=r;pe(s)&&(!r.custom&&e(o[n])?o[n]=de({value:t[n],type:s}):o.unified_custom_fields&&e(o.unified_custom_fields?.[n])&&(o.unified_custom_fields[n]=de({value:t.unified_custom_fields?.[n],type:s})))})),{...o}};var ye;!function(e){e.TYPECAST="typecast",e.MAP_FIELDS="map_fields",e.GROUP_DATA="group_data",e.REQUEST="request",e.PAGINATED_REQUEST="paginated_request"}(ye||(ye={}));const be={[ye.TYPECAST]:{v1:{fn:async({block:e})=>{const t=e?.fieldConfigs;if(!t||"disabled"===e?.debug?.custom_mappings)return{block:e,successful:!0};let r;return r=Array.isArray(e.result)?e.result.map((e=>me(e,t))):me(e.result,t),{block:{...e,result:r},successful:!0}}},v2:{fn:async({block:e,params:t})=>{const{fields:r,dataSource:o}=ue.parse(t),n=O(o,e);if(!r||"disabled"===e?.debug?.custom_mappings)return{block:e,successful:!0};let s;return s=Array.isArray(n)?n.map((e=>ge(e,r))):ge(n,r),{block:{...e},successful:!0,output:{data:s}}},inputSchema:ue,outputSchema:ce}},[ye.MAP_FIELDS]:{v1:{fn:async({block:e})=>{const t=e?.fieldConfigs,r=[],o=e.steps;if(!t||"disabled"===e?.debug?.custom_mappings||!o)return{block:e,successful:!0};let n;if(Array.isArray(e.result)){const s=e.result.length;n=e.result.map(((e,n)=>{const a=q(o,s,n),i=G(e,t,a);return r.push(...i.errors||[]),i.record}))}else{const s=G(e.result,t,o);n=s.record,r.push(...s.errors||[])}return{block:{...e,result:n},successful:!0,errors:Object.keys(r).length>0?r:void 0}}},v2:{fn:async({block:e,params:t})=>{const r=[],{fields:o,dataSource:n}=B.parse(t),s=O(n,e);if(!o||!n||"disabled"===e?.debug?.custom_mappings||!s)return{block:e,successful:!0};let a;if(Array.isArray(s))a=s.map((e=>{const t=z(o,e);return r.push(...t?.errors||[]),t?.record}));else{const e=z(o,s);a=e?.record,r.push(...e?.errors||[])}return{block:{...e},successful:!0,output:{data:a},errors:Object.keys(r).length>0?r:void 0}},inputSchema:B,outputSchema:H}},[ye.REQUEST]:{v1:{fn:async({block:e,params:t})=>{const r=N.build();if(!e.httpClient)throw new Error("HTTP client is not configured");const{args:o}=t,n=o?o.filter((t=>!t.condition||!0===O(t.condition,e))).map((e=>({...e,condition:void 0}))):void 0,s=t?R({...t,args:n},e):{},a={...s,customErrors:t?.customErrors},{baseUrl:i,url:u,method:c,response:l,customErrors:d,args:p}=se.parse(a),m=s?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,g=ne.parse(m),y=p?P(p):{query:{},body:{},headers:{}},b=$(g),f={...y?.headers??{},...b};let h;try{h=await r.performRequest({httpClient:e.httpClient,url:`${i}${u}`,queryParams:y?.query,method:c,headers:f,body:y?.body,customErrorConfigs:d})}catch(t){const r=t;return{block:e,successful:!1,errors:[t],output:{statusCode:r?.response?.status??500,message:r?.response?.message}}}const _=l?.dataKey?h.data[l?.dataKey]:h.data,v=ie(_,l);return{block:e,successful:!0,output:{data:v,raw:h,statusCode:h?.status,message:h?.message}}},inputSchema:se,outputSchema:ae}},[ye.GROUP_DATA]:{v1:{fn:async({block:t,params:r})=>{const{stepsDataToGroup:o,isSingleRecord:n}=M.parse(r),s=o.reduce(((r,o)=>{const s=t.steps?.[o]?.output?.data;return s?n?{...r,[o]:{...s}}:(Object.keys(s).forEach((t=>{const n=e(r[t])?r[t]:{};r[t]={...n,[o]:{...s[t]}}})),r):r}),{});return{block:{...t},successful:!0,output:{data:n?s:Object.values(s)}}},inputSchema:M,outputSchema:U}},[ye.PAGINATED_REQUEST]:{v1:{fn:async({block:t,params:r})=>{const o=N.build();if(!t.httpClient)throw new Error("HTTP client is not configured");const{args:n}=r,s=Number(t.inputs?.page_size),a=Number.isNaN(s)?25:s,i=n?n.filter((e=>!e.condition||!0===O(e.condition,t))).map((e=>({...e,condition:void 0}))):void 0,u=r?R({...r,args:i},t):{},c={...u,customErrors:r?.customErrors},{baseUrl:l,url:d,method:p,response:m,iterator:g,cursor:y,customErrors:b,args:f}=Z.parse(c),h=u?.authentication?.[t.context.authenticationType]?.[t.context.environment]?.authorization,_=X.parse(h),v=f?P(f):{query:{},body:{},headers:{}},k=$(_),S={...v?.headers??{},...k};let I=y?.token??null,w=null,x=null,j=[],C=[];const F=[];let T=a,A=y?.position??0,D=!0,K=!0;do{let e;D?D=!1:A=0,null!==I&&("query"===g.in?v.query[g.key]=I.toString():"body"===g.in&&(v.body[g.key]=I));try{e=await o.performRequest({httpClient:t.httpClient,url:`${l}${d}`,queryParams:v?.query,method:p,headers:S,body:v?.body,customErrorConfigs:b})}catch(e){const r=e;return{block:t,successful:!1,errors:[e],output:{statusCode:r?.response?.status??500,message:r?.response?.message}}}w=I,C=m?.dataKey?e.data[m?.dataKey]:e.data;const r=C?.slice(A,T);T-=r.length,A+=r.length,F.push(e),j=j.concat(r),x=e?.status,I=m?.nextKey?e.data[m?.nextKey]:void 0,r.length===C.length&&0===T&&(A=0,w=I),K=E(I)&&j.length<a}while(e(I)&&j.length<a&&C?.length>0);const M=te(j,m);return{block:t,successful:!0,output:{data:M,raw:F,statusCode:x,next:K?void 0:w,position:K?void 0:A}}},inputSchema:Z,outputSchema:ee}}},fe=(e,t)=>async({block:r,params:o})=>{try{e.inputSchema&&e.inputSchema.parse(o)}catch{return{block:r,successful:!1,errors:[{message:`Input parameters for ${t} are invalid`}]}}const n=await e.fn({block:r,params:o});try{e.outputSchema&&e.outputSchema.parse(n.output)}catch{return{block:r,successful:!1,errors:[{message:`Output data of ${t} has unexpected format`}]}}return n},he={build({functionName:e,version:t="1",validateSchemas:r=!1,stepFunctionsList:o=be}){const n=o?.[e]?.[`v${t}`];if(!n)throw new Error(`Unknown step function: ${e} v${t}`);return r?{...n,fn:fe(n,e)}:n}},_e={hris:{title:"HRIS",key:"hris",description:"Human Resource Information System"},crm:{title:"CRM",key:"crm",description:"Customer Relationship Management"},ats:{title:"ATS",key:"ats",description:"Applicant Tracking System"},lms:{title:"LMS",key:"lms",description:"Learning Management System"},marketing:{title:"Marketing",key:"marketing",description:"Marketing"},filestorage:{title:"File Storage",key:"filestorage",description:"File Storage"}},ve=e=>_e[e.toLowerCase()]??null,ke=e=>!!_e[e.toLowerCase()];var Ee;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warning=3]="Warning",e[e.Error=4]="Error"}(Ee||(Ee={}));const Se=T.object({r:T.record(T.string(),T.object({n:T.number().optional().nullable(),c:T.string().optional().nullable(),p:T.number().optional().nullable()})),v:T.number(),t:T.number()}),Ie=T.object({remote:T.record(T.string(),T.object({pageNumber:T.number().optional(),providerPageCursor:T.string().optional(),position:T.number().optional()})),version:T.number(),timestamp:T.number()}),we=e=>j(JSON.stringify(xe(e))),xe=e=>{const{remote:t,version:r,timestamp:o}=e;return{r:Object.fromEntries(Object.entries(t).map((([e,{pageNumber:t,providerPageCursor:r,position:o}])=>[e,{n:t,c:r,p:o}]))),v:r,t:o}},je=e=>{try{if(k(e)){const t=C(e),r=JSON.parse(t),o=Se.parse(r);return Ce(o)}return Ie.parse(e),e}catch{return null}},Ce=e=>{const{r:t,v:r,t:o}=e;return{remote:Object.fromEntries(Object.entries(t).map((([e,{n:t,c:r,p:o}])=>[e,{pageNumber:t,providerPageCursor:r,position:o}]))),version:r,timestamp:o}},Fe=(e,t)=>{const r="string"==typeof e?je(e):e,o="string"==typeof t?je(t):t;if(null===r||null===o)return r===o;const{timestamp:n,...s}=r,{timestamp:a,...i}=o;return F(s)===F(i)},Te=({cursor:e,ignoreStepIndex:t})=>!!E(e)||Object.keys(e?.remote??{}).reduce(((r,o)=>{const n=e?.remote?.[o];return(E(t)||o!==t.toString())&&(r=r&&E(n.pageNumber)&&E(n.position)&&E(n.providerPageCursor)),r}),!0),Oe=({cursor:e,stepIndex:t,pageNumber:r,providerPageCursor:o,position:n})=>{const s={pageNumber:r??void 0,providerPageCursor:o??void 0,position:n??void 0},a=E(r)&&E(o)&&E(n);return E(e)?{remote:a?{}:{[t]:s},version:2,timestamp:Date.now()}:a?(delete e.remote[t],e):{...e,remote:{...e.remote,[t]:s}}};class Re extends Error{constructor({category:e,name:t,type:r,context:o,message:n}){super(n),this.name=t??"CoreError",this.type=r,this.category=e,this.context=o,Error.captureStackTrace&&Error.captureStackTrace(this,Re)}toString(){const e=this.message?`: ${this.message}`:"";return`${this.category}-${this.name} [${this.type}]${e}`}}const Ae=e=>e instanceof Re,De=j("so1!"),Ke=":",Ne=",",Pe=new RegExp(`(?<!\\\\)${Ke}`,"g"),$e=new RegExp(`(?<!\\\\)${Ne}`,"g"),Me=1;class Ue extends Re{constructor(e,t,r){super({category:"CompositeId",name:t??"BaseCompositeIdError",type:e,message:r})}}class qe extends Ue{constructor(e){super("COMPOSITE_ID_MISSING_HEADER_ERROR","CompositeIdMissingHeaderError",e??"Invalid compositeId, missing header")}}class Ge extends Ue{constructor(e){super("COMPOSITE_ID_MISSING_BODY_ERROR","CompositeIdMissingBodyError",e??"Invalid compositeId, missing body")}}class Le extends Ue{constructor(e){super("COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR","CompositeIdUnknownIdentifierError",e??"Invalid compositeId, unknown identifier")}}class Be extends Ue{constructor(e){super("COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR","CompositeIdUnsupportedVersionError",e??"Invalid compositeId, unsupported version")}}const He=(e,t={version:1})=>{if(1===t.version)return Ve(We(e,t.aliases));throw new Be(`Cannot generate ID, unsupported version number: ${t.version}`)},ze=(e,t={version:1})=>{const r=Je(e,t),o={};return r?(r.split($e).forEach((e=>{const[r,n]=e.split(Pe),s=Ye(r,t.aliases??{});o[s]=et(n)})),o):o},We=(e,t={})=>{if((e=>!E(e)&&"value"in e&&void 0!==e.value)(e))return Qe({identifier:e,compositeIdAliases:t,isSoleIdentifier:!0});if((e=>!E(e)&&"identifiers"in e&&void 0!==e.identifiers)(e))return e.identifiers.map((e=>Qe({identifier:e,compositeIdAliases:t,isSoleIdentifier:!1}))).join(Ne);throw new Le},Qe=({identifier:e,compositeIdAliases:t,isSoleIdentifier:r})=>[r?"id":t[e.key]||e.key,Ze(e.value)].filter(Boolean).join(Ke),Ye=(e,t)=>Object.keys(t).find((r=>t[r]===e))||e,Je=(e,t)=>{if(1===t.version)return Xe(e);throw new Be(`Cannot decode ID, unsupported version number: ${t.version}`)},Ve=e=>`${De}${j(e)}`,Xe=e=>{if(!e.startsWith(De))throw new qe(`Trying to decode an ID without the header: ${e}`);const t=e.split(De)[1];if(!t)throw new Ge(`Trying to decode an ID without a body: ${e}`);return C(t)},Ze=e=>[Ne,Ke].reduce(((e,t)=>e.replace(t,"\\"+t)),e),et=e=>[Ne,Ke].reduce(((e,t)=>{const r="\\"+t;return e.replace(new RegExp("\\\\"+r,"g"),t)}),e),tt=e=>!E(e)&&e.startsWith(De);export{ne as AUTHENTICATION_SCHEMA,Me as COMPOSITE_ID_LATEST_VERSION,Re as CoreError,Ee as LogLevel,ye as StepFunctionName,he as StepFunctionsFactory,Fe as areCursorsEqual,ze as decodeCompositeId,He as encodeCompositeId,je as expandCursor,ve as getCategoryDetails,tt as isCompositeId,Ae as isCoreError,Te as isCursorEmpty,ke as isValidCategory,we as minifyCursor,Oe as updateCursor};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("@stackone/utils"),t=require("zod"),r=require("@stackone/expressions"),o=require("@stackone/transport");const n=t.z.object({stepsDataToGroup:t.z.array(t.z.string()),isSingleRecord:t.z.boolean().optional()}),s=t.z.object({data:t.z.unknown()}),i=(e,t,r)=>Object.entries(e).reduce(((e,[o,n])=>{const s=n?.output?.data;return Array.isArray(s)&&s.length===t?e[o]={output:{data:s[r]}}:e[o]=n,e}),{}),a=(e,t,r)=>{if(!e||!r)return{record:e};const o={unified:{...e},..."object"==typeof r?r:{}},n={},s=[],i={...e};for(const r of t){const{error:t,value:a}=u(o,e.id,r);t?s.push(t):r.custom?n[r.targetFieldKey]=a:i[r.targetFieldKey]=a}return{record:{...i,unified_custom_fields:Object.keys(n).length>0?n:void 0},errors:s.length>0?s:void 0}},u=(e,t,o)=>{const{expression:n,targetFieldKey:s}=o;if(!n)return{error:{message:"Expression is empty",id:t,targetField:s}};let i;try{i=r.evaluate(n,e)}catch{return{error:{message:"Invalid expression",id:t,targetField:s}}}return void 0===i?{error:{message:"Expression returned no value",id:t,targetField:s}}:{value:i}},c=t.z.object({fields:t.z.object({targetFieldKey:t.z.string(),alias:t.z.string().optional(),expression:t.z.string(),type:t.z.enum(["string","number","boolean","datetime_string","enum"]),custom:t.z.boolean().default(!1),hidden:t.z.boolean().default(!1),enumMapper:t.z.object({matcher:t.z.string().or(t.z.object({matchExpression:t.z.string(),value:t.z.string()}).array())}).optional()}).array(),dataSource:t.z.string()}),l=t.z.object({data:t.z.unknown()}),d=(e,t)=>{if(!t)return;const r={},o=[],n={};for(const s of e){const{error:e,value:i}=p(t,t?.id,s);e?o.push(e):s.custom?r[s.targetFieldKey]=i:n[s.targetFieldKey]=i}return{record:{...n,unified_custom_fields:Object.keys(r).length>0?r:void 0},errors:o.length>0?o:void 0}},p=(e,t,r)=>{switch(r.type){case"string":case"number":case"boolean":case"datetime_string":return m(r,t,e);case"enum":return g(r,t,e);default:return{error:{message:"Invalid type",id:t,targetField:r.targetFieldKey}}}},m=(e,t,o)=>{if(!e.expression)return{error:{message:"Expression is empty",id:t,targetField:e.targetFieldKey}};let n;try{n=r.evaluate(e.expression,o)}catch{return{error:{message:"Invalid expression",id:t,targetField:e.targetFieldKey}}}return void 0===n?{error:{message:"Expression returned no value",id:t,targetField:e.targetFieldKey}}:{value:n}},g=(t,o,n)=>{const s=m(t,o,n),i=e.notMissing(s.value)?s.value:null;if(void 0===t.enumMapper)return{error:{message:"Enum mapper was not defined",id:o,targetField:t.targetFieldKey}};const a=t.enumMapper.matcher;if(e.isString(a)){const r=(t=>{switch(t){case"country_alpha2code_by_alpha2code":return e.getCountryAlpha2CodeByAlpha2Code;case"country_alpha3code_by_alpha3code":return e.getCountryAlpha3CodeByAlpha3Code;case"country_code_by_country_code":return e.getCountryCodeByCountryCode;case"country_name_by_country_name":return e.getCountryNameByCountryName;case"country_name_by_alpha3code":return e.getCountryNameByAlpha3Code;case"country_name_by_alpha2code":return e.getCountryNameByAlpha2Code;case"country_name_by_country_code":return e.getCountryNameByCountryCode;case"country_alpha3code_by_alpha2code":return e.getCountryAlpha3CodeByAlpha2Code;case"country_alpha3code_by_country_name":return e.getCountryAlpha3CodeByCountryName;case"country_alpha3code_by_country_code":return e.getCountryAlpha3CodeByCountryCode;case"country_alpha2code_by_alpha3code":return e.getCountryAlpha2CodeByAlpha3Code;case"country_alpha2code_by_country_name":return e.getCountryAlpha2CodeByCountryName;case"country_alpha2code_by_country_code":return e.getCountryAlpha2CodeByCountryCode;case"country_code_by_alpha2code":return e.getCountryCodeByAlpha2Code;case"country_code_by_alpha3code":return e.getCountryCodeByAlpha3Code;case"country_code_by_country_name":return e.getCountryCodeByCountryName;case"country_subdivisions_by_alpha2code":return e.getCountrySubDivisionsByAlpha2Code;case"country_subdivision_code_by_subdivision_name":return e.getCountrySubDivisionCodeBySubDivisionName;case"country_alpha2code_by_citizenship":return e.getCountryAlpha2CodeByCitizenship;case"country_subdivision_name_by_subdivision_code":return e.getCountrySubDivisionNameBySubDivisionCode;default:return}})(a);if(e.notMissing(r)){return{value:{value:(e.notMissing(i)?r(i):null)??"unmapped_value",source_value:i}}}return{error:{message:`The built-in matcher "${a}" is not supported`,id:o,targetField:t.targetFieldKey}}}for(const e of a){const{matchExpression:t,value:o}=e;if(!0===r.evaluate(t,n))return{value:{value:o,source_value:i}}}return{value:{value:"unmapped_value",source_value:i}}},y=t.z.object({type:t.z.literal("basic"),username:t.z.string().optional(),password:t.z.string().optional(),encoding:t.z.string().optional()}),b=t.z.object({type:t.z.literal("bearer"),token:t.z.string()}),h=t.z.discriminatedUnion("type",[y,b]),f=t.z.object({baseUrl:t.z.string(),url:t.z.string(),method:t.z.enum(o.HttpMethods),response:t.z.object({indexField:t.z.string().optional(),dataKey:t.z.string().optional(),nextKey:t.z.string().optional()}).optional(),iterator:t.z.object({key:t.z.string(),in:t.z.enum(o.RequestParameterLocations)}),cursor:t.z.object({token:t.z.string().optional().nullable(),position:t.z.number().optional().nullable()}).optional(),customErrors:o.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:t.z.object({name:t.z.string(),value:t.z.unknown(),in:t.z.enum(o.RequestParameterLocations),condition:t.z.string().optional()}).array().optional()}),_=t.z.object({data:t.z.unknown().optional(),raw:t.z.unknown().optional(),statusCode:t.z.number(),message:t.z.string().optional(),next:t.z.string().optional().nullable(),position:t.z.number().optional()}).optional(),v=(e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce(((e,r)=>{const o=t.indexField;return o&&r[o]&&(e[r[o]]=r),e}),{});if(t?.indexField){const r=t.indexField;return r&&e[r]?{[e[r]]:e}:e}return e},C=t.z.object({type:t.z.literal("basic"),username:t.z.string().optional(),password:t.z.string().optional(),encoding:t.z.string().optional()}),z=t.z.object({type:t.z.literal("bearer"),token:t.z.string()}),S=t.z.discriminatedUnion("type",[C,z]),E=t.z.object({baseUrl:t.z.string(),url:t.z.string(),method:t.z.enum(o.HttpMethods),response:t.z.object({collection:t.z.boolean().optional(),indexField:t.z.string().optional(),dataKey:t.z.string().optional()}).optional(),customErrors:o.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:t.z.object({name:t.z.string(),value:t.z.unknown(),in:t.z.enum(o.RequestParameterLocations),condition:t.z.string().optional()}).array().optional()}),x=t.z.object({data:t.z.unknown().optional(),raw:t.z.unknown().optional(),statusCode:t.z.number(),message:t.z.string().optional()}).optional(),k=(e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce(((e,r)=>{const o=t.indexField;return o&&r[o]&&(e[r[o]]=r),e}),{});if(!t?.collection&&t?.indexField){const r=t.indexField;return r&&e[r]?{[e[r]]:e}:e}return e},I=t.z.object({fields:t.z.object({targetFieldKey:t.z.string(),alias:t.z.string().optional(),type:t.z.string(),custom:t.z.boolean().default(!1),hidden:t.z.boolean().default(!1)}).array().optional(),dataSource:t.z.string()}),A=t.z.object({data:t.z.unknown()});var F;!function(e){e.String="string",e.Number="number",e.Boolean="boolean",e.DateTimeString="datetime_string"}(F||(F={}));const T=({value:t,type:r,format:o})=>{if(e.isMissing(t))return null;switch(r){case F.String:return e.safeParseToString({value:t});case F.Number:return e.safeParseToNumber({value:t});case F.Boolean:return e.safeParseToBoolean({value:t});case F.DateTimeString:return e.safeParseToDateTimeString({value:t,format:o});default:return t}},w=e=>Object.values(F).includes(e),M=(t,r)=>{const o={...t};return r.forEach((r=>{const{targetFieldKey:n,type:s}=r;w(s)&&(!r.custom&&e.notMissing(o[n])?o[n]=T({value:t[n],type:s}):o.unified_custom_fields&&e.notMissing(o.unified_custom_fields?.[n])&&(o.unified_custom_fields[n]=T({value:t.unified_custom_fields?.[n],type:s})))})),{...o}},N=(t,r)=>{const o={...t};return r.forEach((r=>{const{targetFieldKey:n,type:s}=r;w(s)&&(!r.custom&&e.notMissing(o[n])?o[n]=T({value:t[n],type:s}):o.unified_custom_fields&&e.notMissing(o.unified_custom_fields?.[n])&&(o.unified_custom_fields[n]=T({value:t.unified_custom_fields?.[n],type:s})))})),{...o}};var R;exports.StepFunctionName=void 0,(R=exports.StepFunctionName||(exports.StepFunctionName={})).TYPECAST="typecast",R.MAP_FIELDS="map_fields",R.GROUP_DATA="group_data",R.REQUEST="request",R.PAGINATED_REQUEST="paginated_request";const j={[exports.StepFunctionName.TYPECAST]:{v1:{fn:async({block:e})=>{const t=e?.fieldConfigs;if(!t||"disabled"===e?.debug?.custom_mappings)return{block:e,successful:!0};let r;return r=Array.isArray(e.result)?e.result.map((e=>M(e,t))):M(e.result,t),{block:{...e,result:r},successful:!0}}},v2:{fn:async({block:e,params:t})=>{const{fields:o,dataSource:n}=I.parse(t),s=r.evaluate(n,e);if(!o||"disabled"===e?.debug?.custom_mappings)return{block:e,successful:!0};let i;return i=Array.isArray(s)?s.map((e=>N(e,o))):N(s,o),{block:{...e},successful:!0,output:{data:i}}},inputSchema:I,outputSchema:A}},[exports.StepFunctionName.MAP_FIELDS]:{v1:{fn:async({block:e})=>{const t=e?.fieldConfigs,r=[],o=e.steps;if(!t||"disabled"===e?.debug?.custom_mappings||!o)return{block:e,successful:!0};let n;if(Array.isArray(e.result)){const s=e.result.length;n=e.result.map(((e,n)=>{const u=i(o,s,n),c=a(e,t,u);return r.push(...c.errors||[]),c.record}))}else{const s=a(e.result,t,o);n=s.record,r.push(...s.errors||[])}return{block:{...e,result:n},successful:!0,errors:Object.keys(r).length>0?r:void 0}}},v2:{fn:async({block:e,params:t})=>{const o=[],{fields:n,dataSource:s}=c.parse(t),i=r.evaluate(s,e);if(!n||!s||"disabled"===e?.debug?.custom_mappings||!i)return{block:e,successful:!0};let a;if(Array.isArray(i))a=i.map((e=>{const t=d(n,e);return o.push(...t?.errors||[]),t?.record}));else{const e=d(n,i);a=e?.record,o.push(...e?.errors||[])}return{block:{...e},successful:!0,output:{data:a},errors:Object.keys(o).length>0?o:void 0}},inputSchema:c,outputSchema:l}},[exports.StepFunctionName.REQUEST]:{v1:{fn:async({block:e,params:t})=>{const n=o.RequestClientFactory.build();if(!e.httpClient)throw new Error("HTTP client is not configured");const{args:s}=t,i=s?s.filter((t=>!t.condition||!0===r.evaluate(t.condition,e))).map((e=>({...e,condition:void 0}))):void 0,a=t?r.safeEvaluateRecord({...t,args:i},e):{},{baseUrl:u,url:c,method:l,response:d,customErrors:p,args:m}=E.parse(a),g=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,y=S.parse(g),b=m?o.parseRequestParameters(m):{query:{},body:{},headers:{}},h=o.createAuthorizationHeaders(y),f={...b?.headers??{},...h};let _;try{_=await n.performRequest({httpClient:e.httpClient,url:`${u}${c}`,queryParams:b?.query,method:l,headers:f,body:b?.body,customErrorConfigs:p})}catch(t){const r=t;return{block:e,successful:!1,errors:[t],output:{statusCode:r?.response?.status??500,message:r?.response?.message}}}const v=d?.dataKey?_.data[d?.dataKey]:_.data,C=k(v,d);return{block:e,successful:!0,output:{data:C,raw:_,statusCode:_?.status,message:_?.message}}},inputSchema:E,outputSchema:x}},[exports.StepFunctionName.GROUP_DATA]:{v1:{fn:async({block:t,params:r})=>{const{stepsDataToGroup:o,isSingleRecord:s}=n.parse(r),i=o.reduce(((r,o)=>{const n=t.steps?.[o]?.output?.data;return n?s?{...r,[o]:{...n}}:(Object.keys(n).forEach((t=>{const s=e.notMissing(r[t])?r[t]:{};r[t]={...s,[o]:{...n[t]}}})),r):r}),{});return{block:{...t},successful:!0,output:{data:s?i:Object.values(i)}}},inputSchema:n,outputSchema:s}},[exports.StepFunctionName.PAGINATED_REQUEST]:{v1:{fn:async({block:t,params:n})=>{const s=o.RequestClientFactory.build();if(!t.httpClient)throw new Error("HTTP client is not configured");const{args:i}=n,a=Number(t.inputs?.page_size),u=Number.isNaN(a)?25:a,c=i?i.filter((e=>!e.condition||!0===r.evaluate(e.condition,t))).map((e=>({...e,condition:void 0}))):void 0,l=n?r.safeEvaluateRecord({...n,args:c},t):{},{baseUrl:d,url:p,method:m,response:g,iterator:y,cursor:b,customErrors:_,args:C}=f.parse(l),z=l?.authentication?.[t.context.authenticationType]?.[t.context.environment]?.authorization,S=h.parse(z),E=C?o.parseRequestParameters(C):{query:{},body:{},headers:{}},x=o.createAuthorizationHeaders(S),k={...E?.headers??{},...x};let I=b?.token??null,A=null,F=null,T=[],w=[];const M=[];let N=u,R=b?.position??0,j=!0,O=!0;do{let r;j?j=!1:R=0,null!==I&&("query"===y.in?E.query[y.key]=I.toString():"body"===y.in&&(E.body[y.key]=I));try{r=await s.performRequest({httpClient:t.httpClient,url:`${d}${p}`,queryParams:E?.query,method:m,headers:k,body:E?.body,customErrorConfigs:_})}catch(e){const r=e;return{block:t,successful:!1,errors:[e],output:{statusCode:r?.response?.status??500,message:r?.response?.message}}}A=I,w=g?.dataKey?r.data[g?.dataKey]:r.data;const o=w?.slice(R,N);N-=o.length,R+=o.length,M.push(r),T=T.concat(o),F=r?.status,I=g?.nextKey?r.data[g?.nextKey]:void 0,o.length===w.length&&0===N&&(R=0,A=I),O=e.isMissing(I)&&T.length<u}while(e.notMissing(I)&&T.length<u&&w?.length>0);const P=v(T,g);return{block:t,successful:!0,output:{data:P,raw:M,statusCode:F,next:O?void 0:A,position:O?void 0:R}}},inputSchema:f,outputSchema:_}}},O=(e,t)=>async({block:r,params:o})=>{try{e.inputSchema&&e.inputSchema.parse(o)}catch{return{block:r,successful:!1,errors:[{message:`Input parameters for ${t} are invalid`}]}}const n=await e.fn({block:r,params:o});try{e.outputSchema&&e.outputSchema.parse(n.output)}catch{return{block:r,successful:!1,errors:[{message:`Output data of ${t} has unexpected format`}]}}return n},P={build({functionName:e,version:t="1",validateSchemas:r=!1,stepFunctionsList:o=j}){const n=o?.[e]?.[`v${t}`];if(!n)throw new Error(`Unknown step function: ${e} v${t}`);return r?{...n,fn:O(n,e)}:n}},D={hris:{title:"HRIS",key:"hris",description:"Human Resource Information System"},crm:{title:"CRM",key:"crm",description:"Customer Relationship Management"},ats:{title:"ATS",key:"ats",description:"Applicant Tracking System"},lms:{title:"LMS",key:"lms",description:"Learning Management System"},marketing:{title:"Marketing",key:"marketing",description:"Marketing"},filestorage:{title:"File Storage",key:"filestorage",description:"File Storage"}};var B;exports.LogLevel=void 0,(B=exports.LogLevel||(exports.LogLevel={}))[B.Trace=0]="Trace",B[B.Debug=1]="Debug",B[B.Info=2]="Info",B[B.Warning=3]="Warning",B[B.Error=4]="Error";const K=t.z.object({r:t.z.record(t.z.string(),t.z.object({n:t.z.number().optional().nullable(),c:t.z.string().optional().nullable(),p:t.z.number().optional().nullable()})),v:t.z.number(),t:t.z.number()}),q=t.z.object({remote:t.z.record(t.z.string(),t.z.object({pageNumber:t.z.number().optional(),providerPageCursor:t.z.string().optional(),position:t.z.number().optional()})),version:t.z.number(),timestamp:t.z.number()}),$=e=>{const{remote:t,version:r,timestamp:o}=e;return{r:Object.fromEntries(Object.entries(t).map((([e,{pageNumber:t,providerPageCursor:r,position:o}])=>[e,{n:t,c:r,p:o}]))),v:r,t:o}},U=t=>{try{if(e.isString(t)){const r=e.decodeFromBase64(t),o=JSON.parse(r),n=K.parse(o);return L(n)}return q.parse(t),t}catch{return null}},L=e=>{const{r:t,v:r,t:o}=e;return{remote:Object.fromEntries(Object.entries(t).map((([e,{n:t,c:r,p:o}])=>[e,{pageNumber:t,providerPageCursor:r,position:o}]))),version:r,timestamp:o}};class H extends Error{constructor({category:e,name:t,type:r,context:o,message:n}){super(n),this.name=t??"CoreError",this.type=r,this.category=e,this.context=o,Error.captureStackTrace&&Error.captureStackTrace(this,H)}toString(){const e=this.message?`: ${this.message}`:"";return`${this.category}-${this.name} [${this.type}]${e}`}}const G=e.encodeToBase64("so1!"),W=":",Q=",",V=new RegExp(`(?<!\\\\)${W}`,"g"),Y=new RegExp(`(?<!\\\\)${Q}`,"g");class J extends H{constructor(e,t,r){super({category:"CompositeId",name:t??"BaseCompositeIdError",type:e,message:r})}}class X extends J{constructor(e){super("COMPOSITE_ID_MISSING_HEADER_ERROR","CompositeIdMissingHeaderError",e??"Invalid compositeId, missing header")}}class Z extends J{constructor(e){super("COMPOSITE_ID_MISSING_BODY_ERROR","CompositeIdMissingBodyError",e??"Invalid compositeId, missing body")}}class ee extends J{constructor(e){super("COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR","CompositeIdUnknownIdentifierError",e??"Invalid compositeId, unknown identifier")}}class te extends J{constructor(e){super("COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR","CompositeIdUnsupportedVersionError",e??"Invalid compositeId, unsupported version")}}const re=(t,r={})=>{if((t=>!e.isMissing(t)&&"value"in t&&void 0!==t.value)(t))return oe({identifier:t,compositeIdAliases:r,isSoleIdentifier:!0});if((t=>!e.isMissing(t)&&"identifiers"in t&&void 0!==t.identifiers)(t))return t.identifiers.map((e=>oe({identifier:e,compositeIdAliases:r,isSoleIdentifier:!1}))).join(Q);throw new ee},oe=({identifier:e,compositeIdAliases:t,isSoleIdentifier:r})=>[r?"id":t[e.key]||e.key,ue(e.value)].filter(Boolean).join(W),ne=(e,t)=>Object.keys(t).find((r=>t[r]===e))||e,se=(e,t)=>{if(1===t.version)return ae(e);throw new te(`Cannot decode ID, unsupported version number: ${t.version}`)},ie=t=>`${G}${e.encodeToBase64(t)}`,ae=t=>{if(!t.startsWith(G))throw new X(`Trying to decode an ID without the header: ${t}`);const r=t.split(G)[1];if(!r)throw new Z(`Trying to decode an ID without a body: ${t}`);return e.decodeFromBase64(r)},ue=e=>[Q,W].reduce(((e,t)=>e.replace(t,"\\"+t)),e),ce=e=>[Q,W].reduce(((e,t)=>{const r="\\"+t;return e.replace(new RegExp("\\\\"+r,"g"),t)}),e);exports.AUTHENTICATION_SCHEMA=S,exports.COMPOSITE_ID_LATEST_VERSION=1,exports.CoreError=H,exports.StepFunctionsFactory=P,exports.areCursorsEqual=(t,r)=>{const o="string"==typeof t?U(t):t,n="string"==typeof r?U(r):r;if(null===o||null===n)return o===n;const{timestamp:s,...i}=o,{timestamp:a,...u}=n;return e.getContentHash(i)===e.getContentHash(u)},exports.decodeCompositeId=(e,t={version:1})=>{const r=se(e,t),o={};return r?(r.split(Y).forEach((e=>{const[r,n]=e.split(V),s=ne(r,t.aliases??{});o[s]=ce(n)})),o):o},exports.encodeCompositeId=(e,t={version:1})=>{if(1===t.version)return ie(re(e,t.aliases));throw new te(`Cannot generate ID, unsupported version number: ${t.version}`)},exports.expandCursor=U,exports.getCategoryDetails=e=>D[e.toLowerCase()]??null,exports.isCompositeId=t=>!e.isMissing(t)&&t.startsWith(G),exports.isCoreError=e=>e instanceof H,exports.isCursorEmpty=({cursor:t,ignoreStepIndex:r})=>!!e.isMissing(t)||Object.keys(t?.remote??{}).reduce(((o,n)=>{const s=t?.remote?.[n];return(e.isMissing(r)||n!==r.toString())&&(o=o&&e.isMissing(s.pageNumber)&&e.isMissing(s.position)&&e.isMissing(s.providerPageCursor)),o}),!0),exports.isValidCategory=e=>!!D[e.toLowerCase()],exports.minifyCursor=t=>e.encodeToBase64(JSON.stringify($(t))),exports.updateCursor=({cursor:t,stepIndex:r,pageNumber:o,providerPageCursor:n,position:s})=>{const i={pageNumber:o??void 0,providerPageCursor:n??void 0,position:s??void 0},a=e.isMissing(o)&&e.isMissing(n)&&e.isMissing(s);return e.isMissing(t)?{remote:a?{}:{[r]:i},version:2,timestamp:Date.now()}:a?(delete t.remote[r],t):{...t,remote:{...t.remote,[r]:i}}};
1
+ "use strict";var e=require("@stackone/utils"),t=require("zod"),r=require("@stackone/expressions"),o=require("@stackone/transport");const n=t.z.object({stepsDataToGroup:t.z.array(t.z.string()),isSingleRecord:t.z.boolean().optional()}),s=t.z.object({data:t.z.unknown()}),i=(e,t,r)=>Object.entries(e).reduce(((e,[o,n])=>{const s=n?.output?.data;return Array.isArray(s)&&s.length===t?e[o]={output:{data:s[r]}}:e[o]=n,e}),{}),a=(e,t,r)=>{if(!e||!r)return{record:e};const o={unified:{...e},..."object"==typeof r?r:{}},n={},s=[],i={...e};for(const r of t){const{error:t,value:a}=u(o,e.id,r);t?s.push(t):r.custom?n[r.targetFieldKey]=a:i[r.targetFieldKey]=a}return{record:{...i,unified_custom_fields:Object.keys(n).length>0?n:void 0},errors:s.length>0?s:void 0}},u=(e,t,o)=>{const{expression:n,targetFieldKey:s}=o;if(!n)return{error:{message:"Expression is empty",id:t,targetField:s}};let i;try{i=r.evaluate(n,e)}catch{return{error:{message:"Invalid expression",id:t,targetField:s}}}return void 0===i?{error:{message:"Expression returned no value",id:t,targetField:s}}:{value:i}},c=t.z.object({fields:t.z.object({targetFieldKey:t.z.string(),alias:t.z.string().optional(),expression:t.z.string(),type:t.z.enum(["string","number","boolean","datetime_string","enum"]),custom:t.z.boolean().default(!1),hidden:t.z.boolean().default(!1),enumMapper:t.z.object({matcher:t.z.string().or(t.z.object({matchExpression:t.z.string(),value:t.z.string()}).array())}).optional()}).array(),dataSource:t.z.string()}),l=t.z.object({data:t.z.unknown()}),d=(e,t)=>{if(!t)return;const r={},o=[],n={};for(const s of e){const{error:e,value:i}=p(t,t?.id,s);e?o.push(e):s.custom?r[s.targetFieldKey]=i:n[s.targetFieldKey]=i}return{record:{...n,unified_custom_fields:Object.keys(r).length>0?r:void 0},errors:o.length>0?o:void 0}},p=(e,t,r)=>{switch(r.type){case"string":case"number":case"boolean":case"datetime_string":return m(r,t,e);case"enum":return g(r,t,e);default:return{error:{message:"Invalid type",id:t,targetField:r.targetFieldKey}}}},m=(e,t,o)=>{if(!e.expression)return{error:{message:"Expression is empty",id:t,targetField:e.targetFieldKey}};let n;try{n=r.evaluate(e.expression,o)}catch{return{error:{message:"Invalid expression",id:t,targetField:e.targetFieldKey}}}return void 0===n?{error:{message:"Expression returned no value",id:t,targetField:e.targetFieldKey}}:{value:n}},g=(t,o,n)=>{const s=m(t,o,n),i=e.notMissing(s.value)?s.value:null;if(void 0===t.enumMapper)return{error:{message:"Enum mapper was not defined",id:o,targetField:t.targetFieldKey}};const a=t.enumMapper.matcher;if(e.isString(a)){const r=(t=>{switch(t){case"country_alpha2code_by_alpha2code":return e.getCountryAlpha2CodeByAlpha2Code;case"country_alpha3code_by_alpha3code":return e.getCountryAlpha3CodeByAlpha3Code;case"country_code_by_country_code":return e.getCountryCodeByCountryCode;case"country_name_by_country_name":return e.getCountryNameByCountryName;case"country_name_by_alpha3code":return e.getCountryNameByAlpha3Code;case"country_name_by_alpha2code":return e.getCountryNameByAlpha2Code;case"country_name_by_country_code":return e.getCountryNameByCountryCode;case"country_alpha3code_by_alpha2code":return e.getCountryAlpha3CodeByAlpha2Code;case"country_alpha3code_by_country_name":return e.getCountryAlpha3CodeByCountryName;case"country_alpha3code_by_country_code":return e.getCountryAlpha3CodeByCountryCode;case"country_alpha2code_by_alpha3code":return e.getCountryAlpha2CodeByAlpha3Code;case"country_alpha2code_by_country_name":return e.getCountryAlpha2CodeByCountryName;case"country_alpha2code_by_country_code":return e.getCountryAlpha2CodeByCountryCode;case"country_code_by_alpha2code":return e.getCountryCodeByAlpha2Code;case"country_code_by_alpha3code":return e.getCountryCodeByAlpha3Code;case"country_code_by_country_name":return e.getCountryCodeByCountryName;case"country_subdivisions_by_alpha2code":return e.getCountrySubDivisionsByAlpha2Code;case"country_subdivision_code_by_subdivision_name":return e.getCountrySubDivisionCodeBySubDivisionName;case"country_alpha2code_by_citizenship":return e.getCountryAlpha2CodeByCitizenship;case"country_subdivision_name_by_subdivision_code":return e.getCountrySubDivisionNameBySubDivisionCode;default:return}})(a);if(e.notMissing(r)){return{value:{value:(e.notMissing(i)?r(i):null)??"unmapped_value",source_value:i}}}return{error:{message:`The built-in matcher "${a}" is not supported`,id:o,targetField:t.targetFieldKey}}}for(const e of a){const{matchExpression:t,value:o}=e;if(!0===r.evaluate(t,n))return{value:{value:o,source_value:i}}}return{value:{value:"unmapped_value",source_value:i}}},y=t.z.object({type:t.z.literal("basic"),username:t.z.string().optional(),password:t.z.string().optional(),encoding:t.z.string().optional()}),b=t.z.object({type:t.z.literal("bearer"),token:t.z.string()}),h=t.z.discriminatedUnion("type",[y,b]),f=t.z.object({baseUrl:t.z.string(),url:t.z.string(),method:t.z.enum(o.HttpMethods),response:t.z.object({indexField:t.z.string().optional(),dataKey:t.z.string().optional(),nextKey:t.z.string().optional()}).optional(),iterator:t.z.object({key:t.z.string(),in:t.z.enum(o.RequestParameterLocations)}),cursor:t.z.object({token:t.z.string().optional().nullable(),position:t.z.number().optional().nullable()}).optional(),customErrors:o.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:t.z.object({name:t.z.string(),value:t.z.unknown(),in:t.z.enum(o.RequestParameterLocations),condition:t.z.string().optional()}).array().optional()}),_=t.z.object({data:t.z.unknown().optional(),raw:t.z.unknown().optional(),statusCode:t.z.number(),message:t.z.string().optional(),next:t.z.string().optional().nullable(),position:t.z.number().optional()}).optional(),v=(e,t)=>{if(t?.indexField&&Array.isArray(e))return e.reduce(((e,r)=>{const o=t.indexField;return o&&r[o]&&(e[r[o]]=r),e}),{});if(t?.indexField){const r=t.indexField;return r&&e[r]?{[e[r]]:e}:e}return e},C=t.z.object({type:t.z.literal("basic"),username:t.z.string().optional(),password:t.z.string().optional(),encoding:t.z.string().optional()}),z=t.z.object({type:t.z.literal("bearer"),token:t.z.string()}),S=t.z.discriminatedUnion("type",[C,z]),E=t.z.object({baseUrl:t.z.string(),url:t.z.string(),method:t.z.enum(o.HttpMethods),response:t.z.object({collection:t.z.boolean().optional(),indexField:t.z.string().optional(),dataKey:t.z.string().optional()}).optional(),customErrors:o.CUSTOM_ERROR_CONFIG_SCHEMA.array().optional(),args:t.z.object({name:t.z.string(),value:t.z.unknown(),in:t.z.enum(o.RequestParameterLocations),condition:t.z.string().optional()}).array().optional()}),x=t.z.object({data:t.z.unknown().optional(),raw:t.z.unknown().optional(),statusCode:t.z.number(),message:t.z.string().optional()}).optional(),k=(e,t)=>{if(t?.collection&&t?.indexField&&Array.isArray(e))return e.reduce(((e,r)=>{const o=t.indexField;return o&&r[o]&&(e[r[o]]=r),e}),{});if(!t?.collection&&t?.indexField){const r=t.indexField;return r&&e[r]?{[e[r]]:e}:e}return e},I=t.z.object({fields:t.z.object({targetFieldKey:t.z.string(),alias:t.z.string().optional(),type:t.z.string(),custom:t.z.boolean().default(!1),hidden:t.z.boolean().default(!1)}).array().optional(),dataSource:t.z.string()}),A=t.z.object({data:t.z.unknown()});var F;!function(e){e.String="string",e.Number="number",e.Boolean="boolean",e.DateTimeString="datetime_string"}(F||(F={}));const T=({value:t,type:r,format:o})=>{if(e.isMissing(t))return null;switch(r){case F.String:return e.safeParseToString({value:t});case F.Number:return e.safeParseToNumber({value:t});case F.Boolean:return e.safeParseToBoolean({value:t});case F.DateTimeString:return e.safeParseToDateTimeString({value:t,format:o});default:return t}},w=e=>Object.values(F).includes(e),M=(t,r)=>{const o={...t};return r.forEach((r=>{const{targetFieldKey:n,type:s}=r;w(s)&&(!r.custom&&e.notMissing(o[n])?o[n]=T({value:t[n],type:s}):o.unified_custom_fields&&e.notMissing(o.unified_custom_fields?.[n])&&(o.unified_custom_fields[n]=T({value:t.unified_custom_fields?.[n],type:s})))})),{...o}},N=(t,r)=>{const o={...t};return r.forEach((r=>{const{targetFieldKey:n,type:s}=r;w(s)&&(!r.custom&&e.notMissing(o[n])?o[n]=T({value:t[n],type:s}):o.unified_custom_fields&&e.notMissing(o.unified_custom_fields?.[n])&&(o.unified_custom_fields[n]=T({value:t.unified_custom_fields?.[n],type:s})))})),{...o}};var R;exports.StepFunctionName=void 0,(R=exports.StepFunctionName||(exports.StepFunctionName={})).TYPECAST="typecast",R.MAP_FIELDS="map_fields",R.GROUP_DATA="group_data",R.REQUEST="request",R.PAGINATED_REQUEST="paginated_request";const j={[exports.StepFunctionName.TYPECAST]:{v1:{fn:async({block:e})=>{const t=e?.fieldConfigs;if(!t||"disabled"===e?.debug?.custom_mappings)return{block:e,successful:!0};let r;return r=Array.isArray(e.result)?e.result.map((e=>M(e,t))):M(e.result,t),{block:{...e,result:r},successful:!0}}},v2:{fn:async({block:e,params:t})=>{const{fields:o,dataSource:n}=I.parse(t),s=r.evaluate(n,e);if(!o||"disabled"===e?.debug?.custom_mappings)return{block:e,successful:!0};let i;return i=Array.isArray(s)?s.map((e=>N(e,o))):N(s,o),{block:{...e},successful:!0,output:{data:i}}},inputSchema:I,outputSchema:A}},[exports.StepFunctionName.MAP_FIELDS]:{v1:{fn:async({block:e})=>{const t=e?.fieldConfigs,r=[],o=e.steps;if(!t||"disabled"===e?.debug?.custom_mappings||!o)return{block:e,successful:!0};let n;if(Array.isArray(e.result)){const s=e.result.length;n=e.result.map(((e,n)=>{const u=i(o,s,n),c=a(e,t,u);return r.push(...c.errors||[]),c.record}))}else{const s=a(e.result,t,o);n=s.record,r.push(...s.errors||[])}return{block:{...e,result:n},successful:!0,errors:Object.keys(r).length>0?r:void 0}}},v2:{fn:async({block:e,params:t})=>{const o=[],{fields:n,dataSource:s}=c.parse(t),i=r.evaluate(s,e);if(!n||!s||"disabled"===e?.debug?.custom_mappings||!i)return{block:e,successful:!0};let a;if(Array.isArray(i))a=i.map((e=>{const t=d(n,e);return o.push(...t?.errors||[]),t?.record}));else{const e=d(n,i);a=e?.record,o.push(...e?.errors||[])}return{block:{...e},successful:!0,output:{data:a},errors:Object.keys(o).length>0?o:void 0}},inputSchema:c,outputSchema:l}},[exports.StepFunctionName.REQUEST]:{v1:{fn:async({block:e,params:t})=>{const n=o.RequestClientFactory.build();if(!e.httpClient)throw new Error("HTTP client is not configured");const{args:s}=t,i=s?s.filter((t=>!t.condition||!0===r.evaluate(t.condition,e))).map((e=>({...e,condition:void 0}))):void 0,a=t?r.safeEvaluateRecord({...t,args:i},e):{},u={...a,customErrors:t?.customErrors},{baseUrl:c,url:l,method:d,response:p,customErrors:m,args:g}=E.parse(u),y=a?.authentication?.[e.context.authenticationType]?.[e.context.environment]?.authorization,b=S.parse(y),h=g?o.parseRequestParameters(g):{query:{},body:{},headers:{}},f=o.createAuthorizationHeaders(b),_={...h?.headers??{},...f};let v;try{v=await n.performRequest({httpClient:e.httpClient,url:`${c}${l}`,queryParams:h?.query,method:d,headers:_,body:h?.body,customErrorConfigs:m})}catch(t){const r=t;return{block:e,successful:!1,errors:[t],output:{statusCode:r?.response?.status??500,message:r?.response?.message}}}const C=p?.dataKey?v.data[p?.dataKey]:v.data,z=k(C,p);return{block:e,successful:!0,output:{data:z,raw:v,statusCode:v?.status,message:v?.message}}},inputSchema:E,outputSchema:x}},[exports.StepFunctionName.GROUP_DATA]:{v1:{fn:async({block:t,params:r})=>{const{stepsDataToGroup:o,isSingleRecord:s}=n.parse(r),i=o.reduce(((r,o)=>{const n=t.steps?.[o]?.output?.data;return n?s?{...r,[o]:{...n}}:(Object.keys(n).forEach((t=>{const s=e.notMissing(r[t])?r[t]:{};r[t]={...s,[o]:{...n[t]}}})),r):r}),{});return{block:{...t},successful:!0,output:{data:s?i:Object.values(i)}}},inputSchema:n,outputSchema:s}},[exports.StepFunctionName.PAGINATED_REQUEST]:{v1:{fn:async({block:t,params:n})=>{const s=o.RequestClientFactory.build();if(!t.httpClient)throw new Error("HTTP client is not configured");const{args:i}=n,a=Number(t.inputs?.page_size),u=Number.isNaN(a)?25:a,c=i?i.filter((e=>!e.condition||!0===r.evaluate(e.condition,t))).map((e=>({...e,condition:void 0}))):void 0,l=n?r.safeEvaluateRecord({...n,args:c},t):{},d={...l,customErrors:n?.customErrors},{baseUrl:p,url:m,method:g,response:y,iterator:b,cursor:_,customErrors:C,args:z}=f.parse(d),S=l?.authentication?.[t.context.authenticationType]?.[t.context.environment]?.authorization,E=h.parse(S),x=z?o.parseRequestParameters(z):{query:{},body:{},headers:{}},k=o.createAuthorizationHeaders(E),I={...x?.headers??{},...k};let A=_?.token??null,F=null,T=null,w=[],M=[];const N=[];let R=u,j=_?.position??0,O=!0,P=!0;do{let r;O?O=!1:j=0,null!==A&&("query"===b.in?x.query[b.key]=A.toString():"body"===b.in&&(x.body[b.key]=A));try{r=await s.performRequest({httpClient:t.httpClient,url:`${p}${m}`,queryParams:x?.query,method:g,headers:I,body:x?.body,customErrorConfigs:C})}catch(e){const r=e;return{block:t,successful:!1,errors:[e],output:{statusCode:r?.response?.status??500,message:r?.response?.message}}}F=A,M=y?.dataKey?r.data[y?.dataKey]:r.data;const o=M?.slice(j,R);R-=o.length,j+=o.length,N.push(r),w=w.concat(o),T=r?.status,A=y?.nextKey?r.data[y?.nextKey]:void 0,o.length===M.length&&0===R&&(j=0,F=A),P=e.isMissing(A)&&w.length<u}while(e.notMissing(A)&&w.length<u&&M?.length>0);const D=v(w,y);return{block:t,successful:!0,output:{data:D,raw:N,statusCode:T,next:P?void 0:F,position:P?void 0:j}}},inputSchema:f,outputSchema:_}}},O=(e,t)=>async({block:r,params:o})=>{try{e.inputSchema&&e.inputSchema.parse(o)}catch{return{block:r,successful:!1,errors:[{message:`Input parameters for ${t} are invalid`}]}}const n=await e.fn({block:r,params:o});try{e.outputSchema&&e.outputSchema.parse(n.output)}catch{return{block:r,successful:!1,errors:[{message:`Output data of ${t} has unexpected format`}]}}return n},P={build({functionName:e,version:t="1",validateSchemas:r=!1,stepFunctionsList:o=j}){const n=o?.[e]?.[`v${t}`];if(!n)throw new Error(`Unknown step function: ${e} v${t}`);return r?{...n,fn:O(n,e)}:n}},D={hris:{title:"HRIS",key:"hris",description:"Human Resource Information System"},crm:{title:"CRM",key:"crm",description:"Customer Relationship Management"},ats:{title:"ATS",key:"ats",description:"Applicant Tracking System"},lms:{title:"LMS",key:"lms",description:"Learning Management System"},marketing:{title:"Marketing",key:"marketing",description:"Marketing"},filestorage:{title:"File Storage",key:"filestorage",description:"File Storage"}};var B;exports.LogLevel=void 0,(B=exports.LogLevel||(exports.LogLevel={}))[B.Trace=0]="Trace",B[B.Debug=1]="Debug",B[B.Info=2]="Info",B[B.Warning=3]="Warning",B[B.Error=4]="Error";const K=t.z.object({r:t.z.record(t.z.string(),t.z.object({n:t.z.number().optional().nullable(),c:t.z.string().optional().nullable(),p:t.z.number().optional().nullable()})),v:t.z.number(),t:t.z.number()}),q=t.z.object({remote:t.z.record(t.z.string(),t.z.object({pageNumber:t.z.number().optional(),providerPageCursor:t.z.string().optional(),position:t.z.number().optional()})),version:t.z.number(),timestamp:t.z.number()}),$=e=>{const{remote:t,version:r,timestamp:o}=e;return{r:Object.fromEntries(Object.entries(t).map((([e,{pageNumber:t,providerPageCursor:r,position:o}])=>[e,{n:t,c:r,p:o}]))),v:r,t:o}},U=t=>{try{if(e.isString(t)){const r=e.decodeFromBase64(t),o=JSON.parse(r),n=K.parse(o);return L(n)}return q.parse(t),t}catch{return null}},L=e=>{const{r:t,v:r,t:o}=e;return{remote:Object.fromEntries(Object.entries(t).map((([e,{n:t,c:r,p:o}])=>[e,{pageNumber:t,providerPageCursor:r,position:o}]))),version:r,timestamp:o}};class H extends Error{constructor({category:e,name:t,type:r,context:o,message:n}){super(n),this.name=t??"CoreError",this.type=r,this.category=e,this.context=o,Error.captureStackTrace&&Error.captureStackTrace(this,H)}toString(){const e=this.message?`: ${this.message}`:"";return`${this.category}-${this.name} [${this.type}]${e}`}}const G=e.encodeToBase64("so1!"),W=":",Q=",",V=new RegExp(`(?<!\\\\)${W}`,"g"),Y=new RegExp(`(?<!\\\\)${Q}`,"g");class J extends H{constructor(e,t,r){super({category:"CompositeId",name:t??"BaseCompositeIdError",type:e,message:r})}}class X extends J{constructor(e){super("COMPOSITE_ID_MISSING_HEADER_ERROR","CompositeIdMissingHeaderError",e??"Invalid compositeId, missing header")}}class Z extends J{constructor(e){super("COMPOSITE_ID_MISSING_BODY_ERROR","CompositeIdMissingBodyError",e??"Invalid compositeId, missing body")}}class ee extends J{constructor(e){super("COMPOSITE_ID_UNKNOWN_IDENTIFIER_ERROR","CompositeIdUnknownIdentifierError",e??"Invalid compositeId, unknown identifier")}}class te extends J{constructor(e){super("COMPOSITE_ID_UNSUPPORTED_VERSION_ERROR","CompositeIdUnsupportedVersionError",e??"Invalid compositeId, unsupported version")}}const re=(t,r={})=>{if((t=>!e.isMissing(t)&&"value"in t&&void 0!==t.value)(t))return oe({identifier:t,compositeIdAliases:r,isSoleIdentifier:!0});if((t=>!e.isMissing(t)&&"identifiers"in t&&void 0!==t.identifiers)(t))return t.identifiers.map((e=>oe({identifier:e,compositeIdAliases:r,isSoleIdentifier:!1}))).join(Q);throw new ee},oe=({identifier:e,compositeIdAliases:t,isSoleIdentifier:r})=>[r?"id":t[e.key]||e.key,ue(e.value)].filter(Boolean).join(W),ne=(e,t)=>Object.keys(t).find((r=>t[r]===e))||e,se=(e,t)=>{if(1===t.version)return ae(e);throw new te(`Cannot decode ID, unsupported version number: ${t.version}`)},ie=t=>`${G}${e.encodeToBase64(t)}`,ae=t=>{if(!t.startsWith(G))throw new X(`Trying to decode an ID without the header: ${t}`);const r=t.split(G)[1];if(!r)throw new Z(`Trying to decode an ID without a body: ${t}`);return e.decodeFromBase64(r)},ue=e=>[Q,W].reduce(((e,t)=>e.replace(t,"\\"+t)),e),ce=e=>[Q,W].reduce(((e,t)=>{const r="\\"+t;return e.replace(new RegExp("\\\\"+r,"g"),t)}),e);exports.AUTHENTICATION_SCHEMA=S,exports.COMPOSITE_ID_LATEST_VERSION=1,exports.CoreError=H,exports.StepFunctionsFactory=P,exports.areCursorsEqual=(t,r)=>{const o="string"==typeof t?U(t):t,n="string"==typeof r?U(r):r;if(null===o||null===n)return o===n;const{timestamp:s,...i}=o,{timestamp:a,...u}=n;return e.getContentHash(i)===e.getContentHash(u)},exports.decodeCompositeId=(e,t={version:1})=>{const r=se(e,t),o={};return r?(r.split(Y).forEach((e=>{const[r,n]=e.split(V),s=ne(r,t.aliases??{});o[s]=ce(n)})),o):o},exports.encodeCompositeId=(e,t={version:1})=>{if(1===t.version)return ie(re(e,t.aliases));throw new te(`Cannot generate ID, unsupported version number: ${t.version}`)},exports.expandCursor=U,exports.getCategoryDetails=e=>D[e.toLowerCase()]??null,exports.isCompositeId=t=>!e.isMissing(t)&&t.startsWith(G),exports.isCoreError=e=>e instanceof H,exports.isCursorEmpty=({cursor:t,ignoreStepIndex:r})=>!!e.isMissing(t)||Object.keys(t?.remote??{}).reduce(((o,n)=>{const s=t?.remote?.[n];return(e.isMissing(r)||n!==r.toString())&&(o=o&&e.isMissing(s.pageNumber)&&e.isMissing(s.position)&&e.isMissing(s.providerPageCursor)),o}),!0),exports.isValidCategory=e=>!!D[e.toLowerCase()],exports.minifyCursor=t=>e.encodeToBase64(JSON.stringify($(t))),exports.updateCursor=({cursor:t,stepIndex:r,pageNumber:o,providerPageCursor:n,position:s})=>{const i={pageNumber:o??void 0,providerPageCursor:n??void 0,position:s??void 0},a=e.isMissing(o)&&e.isMissing(n)&&e.isMissing(s);return e.isMissing(t)?{remote:a?{}:{[r]:i},version:2,timestamp:Date.now()}:a?(delete t.remote[r],t):{...t,remote:{...t.remote,[r]:i}}};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stackone/core",
3
- "version": "1.49.1",
3
+ "version": "1.49.2",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.es.mjs",