@worknice/js-sdk 0.0.5 → 0.0.6

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.
@@ -15,11 +15,11 @@ var ApiErrorCode = /* @__PURE__ */ ((ApiErrorCode2) => {
15
15
  return ApiErrorCode2;
16
16
  })(ApiErrorCode || {});
17
17
  const ApiErrorCodeMessage = {
18
- ["INVALID_QUERY" /* INVALID_QUERY */]: "The GraphQL query could not be executed due to a syntax error, missing information or a validation error.",
19
- ["QUERY_EXECUTION_FAILED" /* QUERY_EXECUTION_FAILED */]: "An error occurred while executing the GraphQL query. This is likely a problem with the Worknice API.",
18
+ ["INVALID_QUERY" /* INVALID_QUERY */]: "The Worknice API was unable to execute the query. This could be due to a syntax error or invalid query.",
19
+ ["QUERY_EXECUTION_FAILED" /* QUERY_EXECUTION_FAILED */]: "The Worknice API returned an error while executing the query.",
20
20
  ["SESSION_UNAUTHENTICATED" /* SESSION_UNAUTHENTICATED */]: "API token is missing or invalid.",
21
21
  ["SESSION_UNASSOCIATED" /* SESSION_UNASSOCIATED */]: "No person, org or account associated with the session. The session is in 'unassociated' state (the user has no active logins).",
22
- ["UNEXPECTED_RESPONSE" /* UNEXPECTED_RESPONSE */]: "The API returned an unexpected response. This is likely a problem with the Worknice API or a mismatch between JS-SDK and the API. Make sure you are using the latest version of the JS-SDK."
22
+ ["UNEXPECTED_RESPONSE" /* UNEXPECTED_RESPONSE */]: "The API returned an unexpected response. This could be a configuration problem (wrong URL for the API endpoint) or an outdated/mismatched JS-SDK version."
23
23
  };
24
24
  var ApiError_default = ApiError;
25
25
  export {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/ApiError.ts"],"sourcesContent":["class ApiError extends Error {\n readonly code: ApiErrorCode;\n constructor(code: ApiErrorCode, options?: ErrorOptions) {\n super(ApiErrorCodeMessage[code], options);\n this.name = \"ApiError\";\n this.code = code;\n }\n}\n\nenum ApiErrorCode {\n INVALID_QUERY = \"INVALID_QUERY\",\n QUERY_EXECUTION_FAILED = \"QUERY_EXECUTION_FAILED\",\n SESSION_UNASSOCIATED = \"SESSION_UNASSOCIATED\",\n SESSION_UNAUTHENTICATED = \"SESSION_UNAUTHENTICATED\",\n UNEXPECTED_RESPONSE = \"UNEXPECTED_RESPONSE\",\n}\n\nconst ApiErrorCodeMessage: Record<ApiErrorCode, string> = {\n [ApiErrorCode.INVALID_QUERY]:\n \"The GraphQL query could not be executed due to a syntax error, missing information or a validation error.\",\n [ApiErrorCode.QUERY_EXECUTION_FAILED]:\n \"An error occurred while executing the GraphQL query. This is likely a problem with the Worknice API.\",\n [ApiErrorCode.SESSION_UNAUTHENTICATED]: \"API token is missing or invalid.\",\n [ApiErrorCode.SESSION_UNASSOCIATED]:\n \"No person, org or account associated with the session. The session is in 'unassociated' state (the user has no active logins).\",\n [ApiErrorCode.UNEXPECTED_RESPONSE]:\n \"The API returned an unexpected response. This is likely a problem with the Worknice API or a mismatch between JS-SDK and the API. Make sure you are using the latest version of the JS-SDK.\",\n} as const;\n\nexport default ApiError;\nexport { ApiErrorCode };\n"],"mappings":"AAAA,MAAM,iBAAiB,MAAM;AAAA,EAClB;AAAA,EACT,YAAY,MAAoB,SAAwB;AACtD,UAAM,oBAAoB,IAAI,GAAG,OAAO;AACxC,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAK,eAAL,kBAAKA,kBAAL;AACE,EAAAA,cAAA,mBAAgB;AAChB,EAAAA,cAAA,4BAAyB;AACzB,EAAAA,cAAA,0BAAuB;AACvB,EAAAA,cAAA,6BAA0B;AAC1B,EAAAA,cAAA,yBAAsB;AALnB,SAAAA;AAAA,GAAA;AAQL,MAAM,sBAAoD;AAAA,EACxD,CAAC,mCAA0B,GACzB;AAAA,EACF,CAAC,qDAAmC,GAClC;AAAA,EACF,CAAC,uDAAoC,GAAG;AAAA,EACxC,CAAC,iDAAiC,GAChC;AAAA,EACF,CAAC,+CAAgC,GAC/B;AACJ;AAEA,IAAO,mBAAQ;","names":["ApiErrorCode"]}
1
+ {"version":3,"sources":["../../src/api/ApiError.ts"],"sourcesContent":["class ApiError extends Error {\n readonly code: ApiErrorCode;\n constructor(code: ApiErrorCode, options?: ErrorOptions) {\n super(ApiErrorCodeMessage[code], options);\n this.name = \"ApiError\";\n this.code = code;\n }\n}\n\nenum ApiErrorCode {\n INVALID_QUERY = \"INVALID_QUERY\",\n QUERY_EXECUTION_FAILED = \"QUERY_EXECUTION_FAILED\",\n SESSION_UNASSOCIATED = \"SESSION_UNASSOCIATED\",\n SESSION_UNAUTHENTICATED = \"SESSION_UNAUTHENTICATED\",\n UNEXPECTED_RESPONSE = \"UNEXPECTED_RESPONSE\",\n}\n\nconst ApiErrorCodeMessage: Record<ApiErrorCode, string> = {\n [ApiErrorCode.INVALID_QUERY]:\n \"The Worknice API was unable to execute the query. This could be due to a syntax error or invalid query.\",\n [ApiErrorCode.QUERY_EXECUTION_FAILED]:\n \"The Worknice API returned an error while executing the query.\",\n [ApiErrorCode.SESSION_UNAUTHENTICATED]: \"API token is missing or invalid.\",\n [ApiErrorCode.SESSION_UNASSOCIATED]:\n \"No person, org or account associated with the session. The session is in 'unassociated' state (the user has no active logins).\",\n [ApiErrorCode.UNEXPECTED_RESPONSE]:\n \"The API returned an unexpected response. This could be a configuration problem (wrong URL for the API endpoint) or an outdated/mismatched JS-SDK version.\",\n} as const;\n\nexport default ApiError;\nexport { ApiErrorCode };\n"],"mappings":"AAAA,MAAM,iBAAiB,MAAM;AAAA,EAClB;AAAA,EACT,YAAY,MAAoB,SAAwB;AACtD,UAAM,oBAAoB,IAAI,GAAG,OAAO;AACxC,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAK,eAAL,kBAAKA,kBAAL;AACE,EAAAA,cAAA,mBAAgB;AAChB,EAAAA,cAAA,4BAAyB;AACzB,EAAAA,cAAA,0BAAuB;AACvB,EAAAA,cAAA,6BAA0B;AAC1B,EAAAA,cAAA,yBAAsB;AALnB,SAAAA;AAAA,GAAA;AAQL,MAAM,sBAAoD;AAAA,EACxD,CAAC,mCAA0B,GACzB;AAAA,EACF,CAAC,qDAAmC,GAClC;AAAA,EACF,CAAC,uDAAoC,GAAG;AAAA,EACxC,CAAC,iDAAiC,GAChC;AAAA,EACF,CAAC,+CAAgC,GAC/B;AACJ;AAEA,IAAO,mBAAQ;","names":["ApiErrorCode"]}
@@ -7,6 +7,8 @@ import '../api/WorkniceIntegrationLogger.js';
7
7
  type Tasks<Req extends Request = Request> = {
8
8
  persistDetails: (context: TaskContext<CreateIntegrationRequestPayload, null, Req>) => Promise<void>;
9
9
  };
10
- declare const handleCreateIntegrationWebhook: <Req extends Request = Request>(request: Req, { persistDetails }: Tasks<Req>, options?: HandlerOptions) => Promise<Response>;
10
+ declare const handleCreateIntegrationWebhook: <Req extends Request = Request>(request: Req, { persistDetails }: Tasks<Req>, options?: HandlerOptions & {
11
+ action?: "initialize" | "authorize" | "activate";
12
+ }) => Promise<Response>;
11
13
 
12
14
  export { handleCreateIntegrationWebhook as default };
@@ -7,8 +7,23 @@ const handleCreateIntegrationWebhook = async (request, { persistDetails }, optio
7
7
  const { logger, payload, worknice } = context;
8
8
  logger.debug("Persisting details\u2026");
9
9
  await persistDetails(context);
10
- logger.debug("Initializing integration\u2026");
11
- await worknice.initializeIntegration({ id: payload.integrationId });
10
+ switch (options?.action ?? "initialize") {
11
+ case "initialize": {
12
+ logger.debug("Initializing integration\u2026");
13
+ await worknice.initializeIntegration({ id: payload.integrationId });
14
+ break;
15
+ }
16
+ case "authorize": {
17
+ logger.debug("Authorizing integration\u2026");
18
+ await worknice.authorizeIntegration({ integrationId: payload.integrationId });
19
+ break;
20
+ }
21
+ case "activate": {
22
+ logger.debug("Activating integration\u2026");
23
+ await worknice.activateIntegration({ id: payload.integrationId });
24
+ break;
25
+ }
26
+ }
12
27
  },
13
28
  parseRequest: async (context) => {
14
29
  const payload = await context.request.json();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/helpers/handleCreateIntegrationWebhook.ts"],"sourcesContent":["import type { CreateIntegrationRequestPayload } from \"../webhooks.js\";\nimport type { HandlerOptions, TaskContext } from \"./_types.js\";\nimport handleRequestWithWorknice from \"./handleRequestWithWorknice.js\";\n\ntype Tasks<Req extends Request = Request> = {\n persistDetails: (\n context: TaskContext<CreateIntegrationRequestPayload, null, Req>,\n ) => Promise<void>;\n};\n\nconst handleCreateIntegrationWebhook = async <Req extends Request = Request>(\n request: Req,\n { persistDetails }: Tasks<Req>,\n options?: HandlerOptions,\n) =>\n handleRequestWithWorknice<CreateIntegrationRequestPayload, void, null, Req>(\n request,\n {\n getApiToken: async ({ payload }) => payload.apiToken,\n handleRequest: async (context) => {\n const { logger, payload, worknice } = context;\n logger.debug(\"Persisting details…\");\n await persistDetails(context);\n logger.debug(\"Initializing integration…\");\n await worknice.initializeIntegration({ id: payload.integrationId });\n },\n parseRequest: async (context) => {\n const payload = await context.request.json();\n return {\n env: null,\n payload,\n };\n },\n },\n options,\n );\n\nexport default handleCreateIntegrationWebhook;\n"],"mappings":"AAEA,OAAO,+BAA+B;AAQtC,MAAM,iCAAiC,OACrC,SACA,EAAE,eAAe,GACjB,YAEA;AAAA,EACE;AAAA,EACA;AAAA,IACE,aAAa,OAAO,EAAE,QAAQ,MAAM,QAAQ;AAAA,IAC5C,eAAe,OAAO,YAAY;AAChC,YAAM,EAAE,QAAQ,SAAS,SAAS,IAAI;AACtC,aAAO,MAAM,0BAAqB;AAClC,YAAM,eAAe,OAAO;AAC5B,aAAO,MAAM,gCAA2B;AACxC,YAAM,SAAS,sBAAsB,EAAE,IAAI,QAAQ,cAAc,CAAC;AAAA,IACpE;AAAA,IACA,cAAc,OAAO,YAAY;AAC/B,YAAM,UAAU,MAAM,QAAQ,QAAQ,KAAK;AAC3C,aAAO;AAAA,QACL,KAAK;AAAA,QACL;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EACA;AACF;AAEF,IAAO,yCAAQ;","names":[]}
1
+ {"version":3,"sources":["../../src/helpers/handleCreateIntegrationWebhook.ts"],"sourcesContent":["import type { CreateIntegrationRequestPayload } from \"../webhooks.js\";\nimport type { HandlerOptions, TaskContext } from \"./_types.js\";\nimport handleRequestWithWorknice from \"./handleRequestWithWorknice.js\";\n\ntype Tasks<Req extends Request = Request> = {\n persistDetails: (\n context: TaskContext<CreateIntegrationRequestPayload, null, Req>,\n ) => Promise<void>;\n};\n\nconst handleCreateIntegrationWebhook = async <Req extends Request = Request>(\n request: Req,\n { persistDetails }: Tasks<Req>,\n options?: HandlerOptions & { action?: \"initialize\" | \"authorize\" | \"activate\" },\n) =>\n handleRequestWithWorknice<CreateIntegrationRequestPayload, void, null, Req>(\n request,\n {\n getApiToken: async ({ payload }) => payload.apiToken,\n handleRequest: async (context) => {\n const { logger, payload, worknice } = context;\n logger.debug(\"Persisting details…\");\n await persistDetails(context);\n switch (options?.action ?? \"initialize\") {\n case \"initialize\": {\n logger.debug(\"Initializing integration…\");\n await worknice.initializeIntegration({ id: payload.integrationId });\n break;\n }\n case \"authorize\": {\n logger.debug(\"Authorizing integration…\");\n await worknice.authorizeIntegration({ integrationId: payload.integrationId });\n break;\n }\n case \"activate\": {\n logger.debug(\"Activating integration…\");\n await worknice.activateIntegration({ id: payload.integrationId });\n break;\n }\n }\n },\n parseRequest: async (context) => {\n const payload = await context.request.json();\n return {\n env: null,\n payload,\n };\n },\n },\n options,\n );\n\nexport default handleCreateIntegrationWebhook;\n"],"mappings":"AAEA,OAAO,+BAA+B;AAQtC,MAAM,iCAAiC,OACrC,SACA,EAAE,eAAe,GACjB,YAEA;AAAA,EACE;AAAA,EACA;AAAA,IACE,aAAa,OAAO,EAAE,QAAQ,MAAM,QAAQ;AAAA,IAC5C,eAAe,OAAO,YAAY;AAChC,YAAM,EAAE,QAAQ,SAAS,SAAS,IAAI;AACtC,aAAO,MAAM,0BAAqB;AAClC,YAAM,eAAe,OAAO;AAC5B,cAAQ,SAAS,UAAU,cAAc;AAAA,QACvC,KAAK,cAAc;AACjB,iBAAO,MAAM,gCAA2B;AACxC,gBAAM,SAAS,sBAAsB,EAAE,IAAI,QAAQ,cAAc,CAAC;AAClE;AAAA,QACF;AAAA,QACA,KAAK,aAAa;AAChB,iBAAO,MAAM,+BAA0B;AACvC,gBAAM,SAAS,qBAAqB,EAAE,eAAe,QAAQ,cAAc,CAAC;AAC5E;AAAA,QACF;AAAA,QACA,KAAK,YAAY;AACf,iBAAO,MAAM,8BAAyB;AACtC,gBAAM,SAAS,oBAAoB,EAAE,IAAI,QAAQ,cAAc,CAAC;AAChE;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,IACA,cAAc,OAAO,YAAY;AAC/B,YAAM,UAAU,MAAM,QAAQ,QAAQ,KAAK;AAC3C,aAAO;AAAA,QACL,KAAK;AAAA,QACL;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA,EACA;AACF;AAEF,IAAO,yCAAQ;","names":[]}
@@ -572,6 +572,11 @@ const handleTriggerIntegrationSyncWebhook = async (request, {
572
572
  },
573
573
  contextWithIntegration
574
574
  );
575
+ if (personConnections.some((connection) => connection.remote?.id === remote.id)) {
576
+ throw Error(
577
+ `A connection already exists for the ${config.appName} person "${remote.name}".`
578
+ );
579
+ }
575
580
  await worknice.updatePersonConnection({
576
581
  personConnectionId: personConnection.id,
577
582
  personId: personConnection.person.id,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/helpers/handleTriggerIntegrationSyncWebhook.ts"],"sourcesContent":["import isInstantAfter from \"@worknice/utils/temporal/isInstantAfter\";\nimport isValidInstant from \"@worknice/utils/temporal/isValidInstant\";\nimport { Temporal } from \"temporal-polyfill\";\nimport { ConnectionStatus, type GetPeopleQuery, type WorkniceClient } from \"../api/_types.js\";\nimport type { PartialPersonDataTransferLine } from \"../employee-records/_types.js\";\nimport comparePersonDataTransferLines from \"../employee-records/comparePersonDataTransferLines.js\";\nimport mergePersonDataTransferLines from \"../employee-records/mergePersonDataTransferLines.js\";\nimport validatePersonDataTransferLineBankAccounts from \"../employee-records/validatePersonDataTransferLineBankAccounts.js\";\nimport validatePersonDataTransferLineDateOfBirth from \"../employee-records/validatePersonDataTransferLineDateOfBirth.js\";\nimport validatePersonDataTransferLineFullName from \"../employee-records/validatePersonDataTransferLineFullName.js\";\nimport validatePersonDataTransferLineGender from \"../employee-records/validatePersonDataTransferLineGender.js\";\nimport validatePersonDataTransferLinePersonalEmail from \"../employee-records/validatePersonDataTransferLinePersonalEmail.js\";\nimport validatePersonDataTransferLinePersonalPhone from \"../employee-records/validatePersonDataTransferLinePersonalPhone.js\";\nimport validatePersonDataTransferLineResidentialAddress from \"../employee-records/validatePersonDataTransferLineResidentialAddress.js\";\nimport type { TriggerIntegrationSyncRequestPayload } from \"../webhooks.js\";\nimport type { HandlerOptions, TaskContext } from \"./_types.js\";\nimport handleRequestWithWorknice from \"./handleRequestWithWorknice.js\";\n\ntype Context<Env, Req extends Request = Request> = TaskContext<\n TriggerIntegrationSyncRequestPayload,\n Env,\n Req\n> & {\n integration: Awaited<ReturnType<WorkniceClient[\"getIntegration\"]>>;\n};\n\ntype Person = PartialPersonDataTransferLine & {\n metadata: {\n deleted: boolean;\n employeeCode: string | null;\n sourceId: string;\n targetId: string | null;\n updatedAt: string;\n };\n profile: {\n displayName: string;\n profileEmail: string | null;\n } | null;\n};\n\ntype Tasks<Env, Req extends Request = Request> = {\n createRemotePerson?: (\n person: Person,\n context: Context<Env, Req>,\n ) => Promise<{ id: string; name: string }>;\n getApiToken: (\n context: Pick<Context<Env, Req>, \"env\" | \"logger\" | \"payload\" | \"request\">,\n ) => Promise<string>;\n getConfig: (context: Context<Env, Req>) => Promise<Config>;\n getEnv: (context: Pick<Context<Env, Req>, \"logger\" | \"payload\" | \"request\">) => Promise<Env>;\n getRemotePeople: (context: Context<Env, Req>) => Promise<Array<Person>>;\n updateRemotePerson?: (person: Person, context: Context<Env, Req>) => Promise<unknown>;\n};\n\ntype Config = {\n appName: string;\n automaticMatching?: boolean;\n mode?: \"connection-only\" | \"one-way\" | \"two-way\";\n syncFields?: {\n bankAccounts?: boolean;\n dateOfBirth?: boolean;\n emergencyContacts?: boolean;\n fullName?: boolean;\n gender?: boolean;\n personalEmail?: boolean;\n personalPhone?: boolean;\n postalAddress?: boolean;\n profile?: boolean;\n remuneration?: boolean;\n residentialAddress?: boolean;\n superFunds?: boolean;\n taxDetails?: boolean;\n tenure?: boolean;\n };\n};\n\n/**\n * The process for syncing has four steps:\n *\n * 1. Update person connections: Create new person connections for Worknice\n * people or remote people that don't have existing connections. If needed,\n * update names of existing person connections. If enabled, automatically\n * match connections.\n *\n * 2. Update merged people: Copy details from the Worknice people to remote\n * people or vice-versa (based on whichever one was updated most recently)\n * for person connections that are already marked as merged.\n *\n * 3. Merge matched people: Update both Worknice people and remote people for\n * person connections that are marked as matched using details from both\n * people merged together. Mark the connections as merged.\n *\n * 4. Add new people to the remote app: Create new people in the remote app for\n * connections are unmatched and local-only. Mark the connections as merged.\n */\n\nconst handleTriggerIntegrationSyncWebhook = async <Env, Req extends Request = Request>(\n request: Req,\n {\n createRemotePerson,\n getApiToken,\n getConfig,\n getEnv,\n getRemotePeople,\n updateRemotePerson,\n }: Tasks<Env, Req>,\n options?: HandlerOptions,\n) =>\n handleRequestWithWorknice<TriggerIntegrationSyncRequestPayload, undefined, Env, Req>(\n request,\n {\n getApiToken,\n handleRequest: async (context) => {\n const { logger, payload, worknice } = context;\n\n let cachedDataImport: Awaited<ReturnType<WorkniceClient[\"createDataImport\"]>>;\n\n const getDataImport = async () => {\n if (!cachedDataImport) {\n cachedDataImport = await worknice.createDataImport({\n integrationId: payload.integrationId,\n });\n }\n\n return cachedDataImport;\n };\n\n try {\n logger.connect(worknice, payload.integrationId);\n\n logger.indent(\"Retrieving Worknice data…\");\n\n const integration = await worknice.getIntegration({\n integrationId: payload.integrationId,\n });\n\n if (integration.archived) {\n logger.info(\"Integration is archived. Skipping sync.\");\n return;\n }\n\n if (integration.status !== \"SYNCING\") {\n logger.info(\"Integration does not have a syncing status. Skipping sync.\");\n return;\n }\n\n logger.info(\"Retrieved integration from Worknice.\");\n\n const personConnections = await worknice.getPersonConnections({\n integrationId: payload.integrationId,\n });\n\n logger.info(`Retrieved ${personConnections.length} person connection(s) from Worknice.`);\n\n const people = await worknice.getPeople({ orgId: integration.org.id });\n\n logger.info(`Retrieved ${people.length} person(s) from Worknice.`);\n\n logger.dedent(\"Completed retrieving Worknice data.\");\n\n const contextWithIntegration = {\n ...context,\n integration,\n };\n\n logger.indent(\"Loading configuration details…\");\n\n const config = await getConfig(contextWithIntegration);\n\n logger.info(\n config.automaticMatching\n ? \"Automatic matching enabled.\"\n : \"Automatic matching disabled.\",\n );\n logger.info(`Using a \"${config.mode}\" sync mode.`);\n\n logger.dedent(\"Finished loading configuration details.\");\n\n logger.indent(`Retrieving ${config.appName} data…`);\n\n const remotePeople = await getRemotePeople(contextWithIntegration);\n\n logger.info(`Retrieved ${remotePeople.length} people from ${config.appName}.`);\n\n logger.dedent(`Completed retrieving ${config.appName} data.`);\n\n logger.indent(\"Updating person connections…\");\n\n for (const remotePerson of remotePeople) {\n const remotePersonName = personToName(remotePerson);\n try {\n const remotePersonConnection = personConnections.find(\n (\n connection,\n ): connection is typeof connection & {\n status:\n | ConnectionStatus.Connected\n | ConnectionStatus.Merged\n | ConnectionStatus.RemoteOnly;\n } => connection.remote?.id === remotePerson.metadata.sourceId,\n );\n\n if (remotePerson.metadata.deleted) {\n // The remote person has been deleted. If they have a person\n // connection, it should be deleted.\n\n if (remotePersonConnection) {\n await worknice.deletePersonConnection({\n personConnectionId: remotePersonConnection.id,\n });\n\n logger.info(\n `Deleted connection for \"${remotePersonName}\" in ${config.appName} because they have been terminated.`,\n );\n }\n } else {\n // A connection for remote person should be added or updated in\n // Worknice.\n\n if (\n remotePersonConnection &&\n (remotePersonConnection.status === ConnectionStatus.Connected ||\n remotePersonConnection.status === ConnectionStatus.Merged)\n ) {\n // The remote person is already connected to a Worknice person.\n\n if (remotePersonConnection.remote?.name !== remotePersonName) {\n // The employee's name has changed in the remote app and that\n // needs to be reflected in the person connection in Worknice.\n\n const connection = await worknice.updatePersonConnection({\n personConnectionId: remotePersonConnection.id,\n personId: remotePersonConnection.person.id,\n remote: {\n id: remotePerson.metadata.sourceId,\n name: remotePersonName,\n },\n status: remotePersonConnection.status,\n });\n\n personConnections.splice(\n personConnections.indexOf(remotePersonConnection),\n 1,\n connection,\n );\n\n logger.info(\n `Updated person connection remote name from \"${remotePersonConnection.remote?.name}\" to \"${remotePersonName}\".`,\n );\n }\n } else {\n // The remote person is not already connected to a Worknice person, but\n // could already have a remote-only connection.\n\n if (\n remotePersonConnection &&\n remotePersonConnection.remote?.name !== remotePersonName\n ) {\n // The person's name has changed in the remote and that\n // needs to be reflected in the person connection in\n // Worknice.\n\n const connection = await worknice.updatePersonConnection({\n personConnectionId: remotePersonConnection.id,\n remote: {\n id: remotePerson.metadata.sourceId,\n name: remotePersonName,\n },\n status: remotePersonConnection.status,\n });\n\n personConnections.splice(\n personConnections.indexOf(remotePersonConnection),\n 1,\n connection,\n );\n\n logger.info(\n `Updated person connection remote name from \"${remotePersonConnection.remote?.name}\" to \"${remotePersonName}\".`,\n );\n }\n\n const matchingWorknicePerson =\n people.find(\n (person) =>\n person.id === remotePerson.metadata.targetId ||\n (person.employeeCode !== null &&\n person.employeeCode === remotePerson.metadata.employeeCode) ||\n (person.personalEmail !== null &&\n person.personalEmail === remotePerson.personalEmail?.personalEmail) ||\n (person.profileEmail !== null &&\n person.profileEmail === remotePerson.profile?.profileEmail),\n ) ?? null;\n\n if (config.automaticMatching === true && matchingWorknicePerson) {\n // There is a person in Worknice with an ID, employee code\n // or email address that matches the remote person. The\n // Worknice person should be automatically connected to the\n // remote person.\n\n const personConnection = personConnections.find(\n (\n connection,\n ): connection is typeof connection & {\n status:\n | ConnectionStatus.Connected\n | ConnectionStatus.LocalOnly\n | ConnectionStatus.Merged;\n } => connection.person?.id === matchingWorknicePerson.id,\n );\n\n if (\n personConnection?.status === ConnectionStatus.Connected ||\n personConnection?.status === ConnectionStatus.Merged\n ) {\n // The person is already matched with a different remote person.\n\n logger.info(\n `Unable to automatically match person \"${matchingWorknicePerson.displayName}\" in Worknice to person \"${remotePersonName}\" in ${config.appName} because the Worknice person has already been matched to a different ${config.appName} person.`,\n );\n } else {\n // The Worknice person is not yet matched to a remote person. The\n // Worknice person and remote person records should be matched.\n\n if (personConnection) {\n // The Worknice person already has a local-only connection in this\n // integration that can be updated to match to this remote person.\n\n if (remotePersonConnection) {\n // There are person connections for both the Worknice\n // person and the remote person that need to be combined\n // into a single person connection.\n\n await worknice.deletePersonConnection({\n personConnectionId: personConnection.id,\n });\n\n personConnections.splice(personConnections.indexOf(personConnection), 1);\n\n const updatedConnection = await worknice.updatePersonConnection({\n personConnectionId: remotePersonConnection.id,\n personId: matchingWorknicePerson.id,\n remote: {\n id: remotePerson.metadata.sourceId,\n name: remotePersonName,\n },\n status: ConnectionStatus.Connected,\n });\n\n personConnections.splice(\n personConnections.indexOf(remotePersonConnection),\n 1,\n updatedConnection,\n );\n\n logger.info(\n `Automatically matched and combined person connections for person \"${matchingWorknicePerson.displayName}\" in Worknice and person \"${remotePersonName}\" in ${config.appName}.`,\n );\n } else {\n // There is a local-only connection for this Worknice person\n // that should be updated to connect to this remote person.\n\n const updatedConnection = await worknice.updatePersonConnection({\n personConnectionId: personConnection.id,\n personId: personConnection.person.id,\n remote: {\n id: remotePerson.metadata.sourceId,\n name: remotePersonName,\n },\n status: ConnectionStatus.Connected,\n });\n\n personConnections.splice(\n personConnections.indexOf(personConnection),\n 1,\n updatedConnection,\n );\n\n logger.info(\n `Automatically matched existing person connection for person \"${matchingWorknicePerson.displayName}\" in Worknice to person \"${remotePersonName}\" in ${config.appName}.`,\n );\n }\n } else {\n // The Worknice person does not have a connection in this\n // integration and should be connected now.\n\n if (remotePersonConnection) {\n // There is a remote-only connection for this remote person that\n // should be updated to match to this Worknice person.\n\n const updatedConnection = await worknice.updatePersonConnection({\n personConnectionId: remotePersonConnection.id,\n personId: matchingWorknicePerson.id,\n remote: {\n ...remotePersonConnection.remote,\n name: remotePersonName,\n },\n status: ConnectionStatus.Connected,\n });\n\n personConnections.splice(\n personConnections.indexOf(remotePersonConnection),\n 1,\n updatedConnection,\n );\n\n logger.info(\n `Automatically matched existing person connection for person \"${remotePersonName}\" in ${config.appName} to person \"${matchingWorknicePerson.displayName}\" in Worknice.`,\n );\n } else {\n // There is no connection for the remote person or the\n // Worknice person in this integration. A new connection\n // should be created.\n\n const newPersonConnection = await worknice.createPersonConnection({\n integrationId: payload.integrationId,\n personId: matchingWorknicePerson.id,\n remote: {\n id: remotePerson.metadata.sourceId,\n name: remotePersonName,\n },\n status: ConnectionStatus.Connected,\n });\n\n personConnections.push(newPersonConnection);\n\n logger.info(\n `Created new person connection for person \"${remotePersonName}\" in ${config.appName} and automatically matched to person \"${matchingWorknicePerson.displayName}\" in Worknice.`,\n );\n }\n }\n }\n } else if (remotePersonConnection === undefined) {\n // There is no person in Worknice which should be automatically\n // connected to this remote person and there is no existing connection\n // for this remote person.\n\n const newPersonConnection = await worknice.createPersonConnection({\n integrationId: payload.integrationId,\n remote: {\n id: remotePerson.metadata.sourceId,\n name: remotePersonName,\n },\n status: ConnectionStatus.RemoteOnly,\n });\n\n personConnections.push(newPersonConnection);\n\n logger.info(\n `New person connection created for person \"${remotePersonName}\" in ${config.appName}.`,\n );\n }\n }\n }\n } catch (error) {\n logger.info(\n `Unable to update person connection for person \"${remotePersonName}\" in ${config.appName} because of the following error:`,\n );\n logger.error(error);\n }\n }\n\n logger.dedent(\"Finished updating person connections.\");\n\n if (config.mode === \"one-way\" || config.mode === \"two-way\") {\n logger.indent(\"Updating people with connections marked as merged…\");\n\n const mergedConnections = personConnections.filter(\n (\n personConnection,\n ): personConnection is typeof personConnection & {\n status: ConnectionStatus.Merged;\n } => personConnection.status === ConnectionStatus.Merged,\n );\n\n for (const personConnection of mergedConnections) {\n const worknicePerson = people.find(\n (person) => person.id === personConnection.person.id,\n );\n const remotePerson = remotePeople.find(\n (person) => person.metadata.sourceId === personConnection.remote.id,\n );\n\n if (!worknicePerson) {\n throw Error(\n `Unable to find person in Worknice with the ID \"${personConnection.person.id}\".`,\n );\n }\n\n if (!remotePerson) {\n throw Error(\n `Unable to find person in ${config.appName} with the ID \"${personConnection.remote.id}\".`,\n );\n }\n\n const remotePersonName = personToName(remotePerson);\n\n const worknicePersonDataTransferLine = {\n ...worknicePersonToPersonDataTransferLine(worknicePerson),\n metadata: {\n deleted: false,\n employeeCode: worknicePerson.employeeCode ?? null,\n sourceId: worknicePerson.id,\n targetId: remotePerson.metadata.sourceId,\n updatedAt: worknicePerson.updatedAt,\n },\n profile: {\n displayName: worknicePerson.displayName,\n profileEmail: worknicePerson.profileEmail ?? null,\n },\n };\n\n const remotePersonDataTransferLine = remotePerson;\n\n const comparison = comparePersonDataTransferLines(\n worknicePersonDataTransferLine,\n remotePersonDataTransferLine,\n );\n\n if (\n comparison.hasDifferences &&\n ((config.syncFields?.bankAccounts &&\n comparison.sections.bankAccounts.hasDifferences) ||\n (config.syncFields?.dateOfBirth &&\n comparison.sections.dateOfBirth.hasDifferences) ||\n (config.syncFields?.fullName && comparison.sections.fullName.hasDifferences) ||\n (config.syncFields?.gender && comparison.sections.gender.hasDifferences) ||\n (config.syncFields?.personalEmail &&\n comparison.sections.personalEmail.hasDifferences) ||\n (config.syncFields?.personalPhone &&\n comparison.sections.personalPhone.hasDifferences) ||\n (config.syncFields?.residentialAddress &&\n comparison.sections.residentialAddress.hasDifferences))\n ) {\n // Differences found between the Worknice person and the remote\n // person. Update either the Worknice person or the remote\n // person with details from the other.\n\n const worknicePersonUpdatedAt = Temporal.Instant.from(worknicePerson.updatedAt);\n\n if (!isValidInstant(remotePerson.metadata.updatedAt)) {\n throw Error(\n `Invalid updatedAt value for ${config.appName} person \"${remotePersonName}\". Must be in ISO 8601 format, including a date, a time, and a time zone offset.`,\n {\n cause: Error(`Unable to parse: ${remotePerson.metadata.updatedAt}`),\n },\n );\n }\n\n const remotePersonUpdatedAt = Temporal.Instant.from(\n remotePerson.metadata.updatedAt,\n );\n\n if (isInstantAfter(worknicePersonUpdatedAt, remotePersonUpdatedAt)) {\n if (config.mode === \"two-way\") {\n // The Worknice person was updated more recently than the remote\n // person. Update the remote person using details from Worknice.\n\n if (!updateRemotePerson) {\n throw Error(\n \"No updateRemotePerson function supplied to handleTriggerIntegrationSyncWebhook.\",\n );\n }\n\n try {\n await updateRemotePerson(\n worknicePersonDataTransferLine,\n contextWithIntegration,\n );\n logger.info(`Updated person \"${remotePersonName}\" in ${config.appName}.`);\n } catch (error) {\n logger.info(\n `Unable to update person \"${remotePersonName}\" in ${config.appName} because of the following error:`,\n );\n logger.error(error);\n }\n }\n } else {\n // The remote person was updated more recently than the\n // Worknice person. Update the Worknice person using details\n // from the remote.\n\n try {\n const bankAccounts = validatePersonDataTransferLineBankAccounts(\n remotePersonDataTransferLine.bankAccounts,\n );\n const dateOfBirth = validatePersonDataTransferLineDateOfBirth(\n remotePersonDataTransferLine.dateOfBirth,\n );\n // emergencyContacts\n const fullName = validatePersonDataTransferLineFullName(\n remotePersonDataTransferLine.fullName,\n );\n const gender = validatePersonDataTransferLineGender(\n remotePersonDataTransferLine.gender,\n );\n const personalEmail = validatePersonDataTransferLinePersonalEmail(\n remotePersonDataTransferLine.personalEmail,\n );\n const personalPhone = validatePersonDataTransferLinePersonalPhone(\n remotePersonDataTransferLine.personalPhone,\n );\n // postalAddress\n // profile\n // remuneration\n const residentialAddress = validatePersonDataTransferLineResidentialAddress(\n remotePersonDataTransferLine.residentialAddress,\n );\n // // TODO: Enable syncing super funds. See PROD-2216.\n // const superFunds = validatePersonDataTransferLineSuperFunds(remotePersonDataTransferLine.superFunds);\n // // TODO: Enable syncing tax details. See PROD-2375.\n // const taxDetails = validatePersonDataTransferLineTaxDetails(remotePersonDataTransferLine.taxDetails);\n // // TODO: Enable syncing tenure. See PROD-1371.\n // const tenure = validatePersonDataTransferLineTenure(remotePersonDataTransferLine.tenure);\n\n const dataImport = await getDataImport();\n\n await worknice.createPersonDataImportLine({\n bankAccounts,\n config: {\n bankAccounts: config.syncFields?.bankAccounts ?? false,\n dateOfBirth: config.syncFields?.dateOfBirth ?? false,\n emergencyContacts: config.syncFields?.emergencyContacts ?? false,\n fullName: config.syncFields?.fullName ?? false,\n gender: config.syncFields?.gender ?? false,\n personalEmail: config.syncFields?.personalEmail ?? false,\n personalPhone: config.syncFields?.personalPhone ?? false,\n postalAddress: config.syncFields?.postalAddress ?? false,\n profile: config.syncFields?.profile ?? false,\n remuneration: config.syncFields?.remuneration ?? false,\n residentialAddress: config.syncFields?.residentialAddress ?? false,\n superFunds: config.syncFields?.superFunds ?? false,\n taxDetails: config.syncFields?.taxDetails ?? false,\n tenure: config.syncFields?.tenure ?? false,\n },\n dataImportId: dataImport.id,\n dateOfBirth,\n emergencyContacts: null,\n fullName,\n gender,\n personalEmail,\n personalPhone,\n personId: worknicePerson.id,\n postalAddress: null,\n residentialAddress,\n // TODO: Enable syncing super funds. See PROD-2216.\n superFunds: null,\n // TODO: Enable syncing tax details. See PROD-2375.\n taxDetails: null,\n // TODO: Enable syncing tenure. See PROD-1371.\n tenure: null,\n });\n\n logger.info(`Updated person \"${worknicePerson.displayName}\" in Worknice.`);\n } catch (error) {\n logger.info(\n `Unable to update person \"${worknicePerson.displayName}\" in Worknice because of the following error:`,\n );\n logger.error(error);\n }\n }\n }\n }\n\n logger.dedent(\"Finished updating people with connections marked as merged.\");\n }\n\n logger.indent(\"Merging unmerged connections…\");\n\n const connectedConnections = personConnections.filter(\n (\n personConnection,\n ): personConnection is typeof personConnection & {\n status: ConnectionStatus.Connected;\n } => personConnection.status === ConnectionStatus.Connected,\n );\n\n for (const personConnection of connectedConnections) {\n const worknicePerson = people.find(\n (person) => person.id === personConnection.person.id,\n );\n const remotePerson = remotePeople.find(\n (person) => person.metadata.sourceId === personConnection.remote.id,\n );\n\n if (!worknicePerson) {\n throw Error(\n `Unable to find person in Worknice with the ID \"${personConnection.person.id}\".`,\n );\n }\n\n if (!remotePerson) {\n throw Error(\n `Unable to find person in ${config.appName} with the ID \"${personConnection.remote.id}\".`,\n );\n }\n\n const remotePersonName = personToName(remotePerson);\n\n logger.indent(\n `Merging Worknice person \"${worknicePerson.displayName}\" with ${config.appName} person \"${remotePersonName}\"…`,\n );\n\n try {\n if (config.mode === \"one-way\" || config.mode === \"two-way\") {\n const worknicePersonUpdatedAt = Temporal.Instant.from(worknicePerson.updatedAt);\n\n if (!isValidInstant(remotePerson.metadata.updatedAt)) {\n throw Error(\n `Invalid updatedAt value for ${config.appName} person \"${remotePersonName}\". Must be in ISO 8601 format, including a date, a time, and a time zone offset.`,\n {\n cause: Error(`Unable to parse: ${remotePerson.metadata.updatedAt}`),\n },\n );\n }\n\n const remotePersonUpdatedAt = Temporal.Instant.from(\n remotePerson.metadata.updatedAt,\n );\n\n const [primaryDataTransferLine, secondaryDataTransferLine] = isInstantAfter(\n worknicePersonUpdatedAt,\n remotePersonUpdatedAt,\n )\n ? [worknicePersonToPersonDataTransferLine(worknicePerson), remotePerson]\n : [remotePerson, worknicePersonToPersonDataTransferLine(worknicePerson)];\n const mergedDataTransferLine = mergePersonDataTransferLines(\n primaryDataTransferLine,\n secondaryDataTransferLine,\n );\n\n const bankAccounts = validatePersonDataTransferLineBankAccounts(\n mergedDataTransferLine.bankAccounts,\n );\n const dateOfBirth = validatePersonDataTransferLineDateOfBirth(\n mergedDataTransferLine.dateOfBirth,\n );\n // emergencyContacts\n const fullName = validatePersonDataTransferLineFullName(\n mergedDataTransferLine.fullName,\n );\n const gender = validatePersonDataTransferLineGender(mergedDataTransferLine.gender);\n const personalEmail = validatePersonDataTransferLinePersonalEmail(\n mergedDataTransferLine.personalEmail,\n );\n const personalPhone = validatePersonDataTransferLinePersonalPhone(\n mergedDataTransferLine.personalPhone,\n );\n // postalAddress\n // profile\n // remuneration\n const residentialAddress = validatePersonDataTransferLineResidentialAddress(\n mergedDataTransferLine.residentialAddress,\n );\n // // TODO: Enable syncing super funds. See PROD-2216.\n // const superFunds = validatePersonDataTransferLineSuperFunds(mergedDataTransferLine.superFunds);\n // // TODO: Enable syncing tax details. See PROD-2375.\n // const taxDetails = validatePersonDataTransferLineTaxDetails(mergedDataTransferLine.taxDetails);\n // // TODO: Enable syncing tenure. See PROD-1371.\n // const tenure = validatePersonDataTransferLineTenure(mergedDataTransferLine.tenure);\n\n const dataImport = await getDataImport();\n\n await worknice.createPersonDataImportLine({\n bankAccounts,\n config: {\n bankAccounts: config.syncFields?.bankAccounts ?? false,\n dateOfBirth: config.syncFields?.dateOfBirth ?? false,\n emergencyContacts: config.syncFields?.emergencyContacts ?? false,\n fullName: config.syncFields?.fullName ?? false,\n gender: config.syncFields?.gender ?? false,\n personalEmail: config.syncFields?.personalEmail ?? false,\n personalPhone: config.syncFields?.personalPhone ?? false,\n postalAddress: config.syncFields?.postalAddress ?? false,\n profile: config.syncFields?.profile ?? false,\n remuneration: config.syncFields?.remuneration ?? false,\n residentialAddress: config.syncFields?.residentialAddress ?? false,\n superFunds: config.syncFields?.superFunds ?? false,\n taxDetails: config.syncFields?.taxDetails ?? false,\n tenure: config.syncFields?.tenure ?? false,\n },\n dataImportId: dataImport.id,\n dateOfBirth,\n emergencyContacts: null,\n fullName,\n gender,\n personalEmail,\n personalPhone,\n personId: worknicePerson.id,\n postalAddress: null,\n residentialAddress,\n // TODO: Enable syncing super funds. See PROD-2216.\n superFunds: null,\n // TODO: Enable syncing tax details. See PROD-2375.\n taxDetails: null,\n // TODO: Enable syncing tenure. See PROD-1371.\n tenure: null,\n });\n\n logger.info(`Updated person \"${worknicePerson.displayName}\" in Worknice.`);\n\n if (config.mode === \"two-way\") {\n if (!updateRemotePerson) {\n throw Error(\n \"No updateRemotePerson function supplied to handleTriggerIntegrationSyncWebhook.\",\n );\n }\n\n await updateRemotePerson(\n {\n ...mergedDataTransferLine,\n metadata: {\n deleted: false,\n employeeCode: worknicePerson.employeeCode ?? null,\n sourceId: worknicePerson.id,\n targetId: remotePerson.metadata.sourceId,\n updatedAt: worknicePerson.updatedAt,\n },\n profile: {\n displayName: worknicePerson.displayName,\n profileEmail: worknicePerson.profileEmail ?? null,\n },\n },\n contextWithIntegration,\n );\n\n logger.info(`Updated person \"${remotePersonName}\" in ${config.appName}.`);\n }\n }\n\n await worknice.updatePersonConnection({\n personConnectionId: personConnection.id,\n personId: personConnection.person.id,\n remote: {\n id: remotePerson.metadata.sourceId,\n name: remotePersonName,\n },\n status: ConnectionStatus.Merged,\n });\n\n logger.dedent(`Finished merging.`);\n } catch (error) {\n logger.info(\n `Unable to merge ${config.appName} person \"${remotePersonName}\" and Worknice person \"${worknicePerson.displayName}\" because of the following error:`,\n );\n logger.error(error);\n logger.dedent();\n }\n }\n\n logger.dedent(\"Finished merging unmerged connections.\");\n\n if (config.mode === \"two-way\") {\n logger.indent(`Adding new people to ${config.appName}…`);\n\n const localOnlyConnections = personConnections.filter(\n (\n personConnection,\n ): personConnection is typeof personConnection & {\n status: ConnectionStatus.LocalOnly;\n } => personConnection.status === ConnectionStatus.LocalOnly,\n );\n\n for (const personConnection of localOnlyConnections) {\n const worknicePerson = people.find(\n (person) => person.id === personConnection.person.id,\n );\n\n if (!worknicePerson) {\n throw Error(\n `Unable to find person in Worknice with the ID \"${personConnection.person.id}\".`,\n );\n }\n\n try {\n if (!createRemotePerson) {\n throw Error(\n \"No createRemotePerson function supplied to handleTriggerIntegrationSyncWebhook.\",\n );\n }\n\n const remote = await createRemotePerson(\n {\n ...worknicePersonToPersonDataTransferLine(worknicePerson),\n metadata: {\n deleted: false,\n employeeCode: worknicePerson.employeeCode ?? null,\n sourceId: worknicePerson.id,\n targetId: null,\n updatedAt: worknicePerson.updatedAt,\n },\n profile: {\n displayName: worknicePerson.displayName,\n profileEmail: worknicePerson.profileEmail ?? null,\n },\n },\n contextWithIntegration,\n );\n\n await worknice.updatePersonConnection({\n personConnectionId: personConnection.id,\n personId: personConnection.person.id,\n remote,\n status: ConnectionStatus.Merged,\n });\n\n logger.info(`Added new person \"${remote.name}\" to ${config.appName}.`);\n } catch (error) {\n logger.info(\n `Unable to add person \"${worknicePerson.displayName}\" in Worknice to ${config.appName} because of the following error:`,\n );\n logger.error(error);\n }\n }\n\n logger.dedent(`Finished adding new people to ${config.appName}.`);\n }\n\n await worknice.completeSync({ integrationId: payload.integrationId });\n\n logger.info(\"Sync completed.\");\n } catch (error) {\n await worknice.completeSync({ integrationId: payload.integrationId });\n throw error;\n }\n },\n parseRequest: async (context) => {\n const payload = await context.request.json();\n return {\n env: await getEnv({ ...context, payload }),\n payload,\n };\n },\n },\n options,\n );\n\nconst personToName = (person: Person) => {\n if (\n (person.fullName?.givenName ?? \"\").trim() !== \"\" &&\n (person.fullName?.familyName ?? \"\").trim() !== \"\"\n ) {\n return `${person.fullName?.givenName} ${person.fullName?.familyName}`;\n }\n\n if ((person.profile?.displayName ?? \"\").trim() !== \"\") {\n return `${person.profile?.displayName}`;\n }\n\n return `(unnamed person ${person.metadata.sourceId})`;\n};\n\nconst worknicePersonToPersonDataTransferLine = (\n worknicePerson: NonNullable<GetPeopleQuery[\"org\"][\"people\"][number]>,\n): PartialPersonDataTransferLine => ({\n bankAccounts: worknicePerson.bankAccount1AllocationMethod\n ? {\n bankAccount1Allocation: worknicePerson.bankAccount1Allocation ?? null,\n bankAccount1AllocationMethod: worknicePerson.bankAccount1AllocationMethod,\n bankAccount1Bsb: worknicePerson.bankAccount1Bsb ?? null,\n bankAccount1Name: worknicePerson.bankAccount1Name ?? null,\n bankAccount1Number: worknicePerson.bankAccount1Number ?? null,\n bankAccount2Allocation: worknicePerson.bankAccount2Allocation ?? null,\n bankAccount2AllocationMethod: worknicePerson.bankAccount2AllocationMethod ?? null,\n bankAccount2Bsb: worknicePerson.bankAccount2Bsb ?? null,\n bankAccount2Name: worknicePerson.bankAccount2Name ?? null,\n bankAccount2Number: worknicePerson.bankAccount2Number ?? null,\n bankAccount3Allocation: worknicePerson.bankAccount3Allocation ?? null,\n bankAccount3AllocationMethod: worknicePerson.bankAccount3AllocationMethod ?? null,\n bankAccount3Bsb: worknicePerson.bankAccount3Bsb ?? null,\n bankAccount3Name: worknicePerson.bankAccount3Name ?? null,\n bankAccount3Number: worknicePerson.bankAccount3Number ?? null,\n bankAccount4Allocation: worknicePerson.bankAccount4Allocation ?? null,\n bankAccount4AllocationMethod: worknicePerson.bankAccount4AllocationMethod ?? null,\n bankAccount4Bsb: worknicePerson.bankAccount4Bsb ?? null,\n bankAccount4Name: worknicePerson.bankAccount4Name ?? null,\n bankAccount4Number: worknicePerson.bankAccount4Number ?? null,\n bankAccount5Allocation: worknicePerson.bankAccount5Allocation ?? null,\n bankAccount5AllocationMethod: worknicePerson.bankAccount5AllocationMethod ?? null,\n bankAccount5Bsb: worknicePerson.bankAccount5Bsb ?? null,\n bankAccount5Name: worknicePerson.bankAccount5Name ?? null,\n bankAccount5Number: worknicePerson.bankAccount5Number ?? null,\n }\n : null,\n dateOfBirth: worknicePerson.dateOfBirth ? { dateOfBirth: worknicePerson.dateOfBirth } : null,\n emergencyContacts: null,\n fullName: worknicePerson.givenName\n ? {\n familyName: worknicePerson.familyName ?? null,\n givenName: worknicePerson.givenName ?? null,\n otherGivenNames: worknicePerson.otherGivenNames ?? null,\n }\n : null,\n gender: worknicePerson.gender\n ? {\n gender: worknicePerson.gender,\n }\n : null,\n personalEmail: worknicePerson.personalEmail\n ? {\n personalEmail: worknicePerson.personalEmail,\n }\n : null,\n personalPhone: worknicePerson.personalPhone\n ? {\n personalPhone: worknicePerson.personalPhone,\n }\n : null,\n postalAddress: null,\n residentialAddress: worknicePerson.residentialAddressLine1\n ? {\n residentialAddressCity: worknicePerson.residentialAddressCity ?? null,\n // FIXME: This should not default to \"Australia\". See PROD-1085.\n residentialAddressCountry: worknicePerson.residentialAddressCountry ?? \"Australia\",\n residentialAddressLine1: worknicePerson.residentialAddressLine1 ?? null,\n residentialAddressLine2: worknicePerson.residentialAddressLine2 ?? null,\n residentialAddressPostcode: worknicePerson.residentialAddressPostcode ?? null,\n residentialAddressState: worknicePerson.residentialAddressState ?? null,\n }\n : null,\n // TODO: Enable syncing super funds. See PROD-2216.\n superFunds: null,\n // TODO: Enable syncing tax details. See PROD-2375.\n taxDetails: null,\n // TODO: Enable syncing tenure. See PROD-1371.\n tenure: null,\n});\n\nexport default handleTriggerIntegrationSyncWebhook;\n"],"mappings":"AAAA,OAAO,oBAAoB;AAC3B,OAAO,oBAAoB;AAC3B,SAAS,gBAAgB;AACzB,SAAS,wBAAkE;AAE3E,OAAO,oCAAoC;AAC3C,OAAO,kCAAkC;AACzC,OAAO,gDAAgD;AACvD,OAAO,+CAA+C;AACtD,OAAO,4CAA4C;AACnD,OAAO,0CAA0C;AACjD,OAAO,iDAAiD;AACxD,OAAO,iDAAiD;AACxD,OAAO,sDAAsD;AAG7D,OAAO,+BAA+B;AAgFtC,MAAM,sCAAsC,OAC1C,SACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GACA,YAEA;AAAA,EACE;AAAA,EACA;AAAA,IACE;AAAA,IACA,eAAe,OAAO,YAAY;AAChC,YAAM,EAAE,QAAQ,SAAS,SAAS,IAAI;AAEtC,UAAI;AAEJ,YAAM,gBAAgB,YAAY;AAChC,YAAI,CAAC,kBAAkB;AACrB,6BAAmB,MAAM,SAAS,iBAAiB;AAAA,YACjD,eAAe,QAAQ;AAAA,UACzB,CAAC;AAAA,QACH;AAEA,eAAO;AAAA,MACT;AAEA,UAAI;AACF,eAAO,QAAQ,UAAU,QAAQ,aAAa;AAE9C,eAAO,OAAO,gCAA2B;AAEzC,cAAM,cAAc,MAAM,SAAS,eAAe;AAAA,UAChD,eAAe,QAAQ;AAAA,QACzB,CAAC;AAED,YAAI,YAAY,UAAU;AACxB,iBAAO,KAAK,yCAAyC;AACrD;AAAA,QACF;AAEA,YAAI,YAAY,WAAW,WAAW;AACpC,iBAAO,KAAK,4DAA4D;AACxE;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AC/B;AAAA,IACE,wBAAwB,eAAe,0BAA0B;AAAA;AAAA,IAEjE,2BAA2B,eAAe,6BAA6B;AAAA,IACvE,yBAAyB,eAAe,2BAA2B;AAAA,IACnE,yBAAyB,eAAe,2BAA2B;AAAA,IACnE,4BAA4B,eAAe,8BAA8B;AAAA,IACzE,yBAAyB,eAAe,2BAA2B;AAAA,EACrE,IACA;AAAA;AAAA,EAEJ,YAAY;AAAA;AAAA,EAEZ,YAAY;AAAA;AAAA,EAEZ,QAAQ;AACV;AAEA,IAAO,8CAAQ;","names":[]}
1
+ {"version":3,"sources":["../../src/helpers/handleTriggerIntegrationSyncWebhook.ts"],"sourcesContent":["import isInstantAfter from \"@worknice/utils/temporal/isInstantAfter\";\nimport isValidInstant from \"@worknice/utils/temporal/isValidInstant\";\nimport { Temporal } from \"temporal-polyfill\";\nimport { ConnectionStatus, type GetPeopleQuery, type WorkniceClient } from \"../api/_types.js\";\nimport type { PartialPersonDataTransferLine } from \"../employee-records/_types.js\";\nimport comparePersonDataTransferLines from \"../employee-records/comparePersonDataTransferLines.js\";\nimport mergePersonDataTransferLines from \"../employee-records/mergePersonDataTransferLines.js\";\nimport validatePersonDataTransferLineBankAccounts from \"../employee-records/validatePersonDataTransferLineBankAccounts.js\";\nimport validatePersonDataTransferLineDateOfBirth from \"../employee-records/validatePersonDataTransferLineDateOfBirth.js\";\nimport validatePersonDataTransferLineFullName from \"../employee-records/validatePersonDataTransferLineFullName.js\";\nimport validatePersonDataTransferLineGender from \"../employee-records/validatePersonDataTransferLineGender.js\";\nimport validatePersonDataTransferLinePersonalEmail from \"../employee-records/validatePersonDataTransferLinePersonalEmail.js\";\nimport validatePersonDataTransferLinePersonalPhone from \"../employee-records/validatePersonDataTransferLinePersonalPhone.js\";\nimport validatePersonDataTransferLineResidentialAddress from \"../employee-records/validatePersonDataTransferLineResidentialAddress.js\";\nimport type { TriggerIntegrationSyncRequestPayload } from \"../webhooks.js\";\nimport type { HandlerOptions, TaskContext } from \"./_types.js\";\nimport handleRequestWithWorknice from \"./handleRequestWithWorknice.js\";\n\ntype Context<Env, Req extends Request = Request> = TaskContext<\n TriggerIntegrationSyncRequestPayload,\n Env,\n Req\n> & {\n integration: Awaited<ReturnType<WorkniceClient[\"getIntegration\"]>>;\n};\n\ntype Person = PartialPersonDataTransferLine & {\n metadata: {\n deleted: boolean;\n employeeCode: string | null;\n sourceId: string;\n targetId: string | null;\n updatedAt: string;\n };\n profile: {\n displayName: string;\n profileEmail: string | null;\n } | null;\n};\n\ntype Tasks<Env, Req extends Request = Request> = {\n createRemotePerson?: (\n person: Person,\n context: Context<Env, Req>,\n ) => Promise<{ id: string; name: string }>;\n getApiToken: (\n context: Pick<Context<Env, Req>, \"env\" | \"logger\" | \"payload\" | \"request\">,\n ) => Promise<string>;\n getConfig: (context: Context<Env, Req>) => Promise<Config>;\n getEnv: (context: Pick<Context<Env, Req>, \"logger\" | \"payload\" | \"request\">) => Promise<Env>;\n getRemotePeople: (context: Context<Env, Req>) => Promise<Array<Person>>;\n updateRemotePerson?: (person: Person, context: Context<Env, Req>) => Promise<unknown>;\n};\n\ntype Config = {\n appName: string;\n automaticMatching?: boolean;\n mode?: \"connection-only\" | \"one-way\" | \"two-way\";\n syncFields?: {\n bankAccounts?: boolean;\n dateOfBirth?: boolean;\n emergencyContacts?: boolean;\n fullName?: boolean;\n gender?: boolean;\n personalEmail?: boolean;\n personalPhone?: boolean;\n postalAddress?: boolean;\n profile?: boolean;\n remuneration?: boolean;\n residentialAddress?: boolean;\n superFunds?: boolean;\n taxDetails?: boolean;\n tenure?: boolean;\n };\n};\n\n/**\n * The process for syncing has four steps:\n *\n * 1. Update person connections: Create new person connections for Worknice\n * people or remote people that don't have existing connections. If needed,\n * update names of existing person connections. If enabled, automatically\n * match connections.\n *\n * 2. Update merged people: Copy details from the Worknice people to remote\n * people or vice-versa (based on whichever one was updated most recently)\n * for person connections that are already marked as merged.\n *\n * 3. Merge matched people: Update both Worknice people and remote people for\n * person connections that are marked as matched using details from both\n * people merged together. Mark the connections as merged.\n *\n * 4. Add new people to the remote app: Create new people in the remote app for\n * connections are unmatched and local-only. Mark the connections as merged.\n */\n\nconst handleTriggerIntegrationSyncWebhook = async <Env, Req extends Request = Request>(\n request: Req,\n {\n createRemotePerson,\n getApiToken,\n getConfig,\n getEnv,\n getRemotePeople,\n updateRemotePerson,\n }: Tasks<Env, Req>,\n options?: HandlerOptions,\n) =>\n handleRequestWithWorknice<TriggerIntegrationSyncRequestPayload, undefined, Env, Req>(\n request,\n {\n getApiToken,\n handleRequest: async (context) => {\n const { logger, payload, worknice } = context;\n\n let cachedDataImport: Awaited<ReturnType<WorkniceClient[\"createDataImport\"]>>;\n\n const getDataImport = async () => {\n if (!cachedDataImport) {\n cachedDataImport = await worknice.createDataImport({\n integrationId: payload.integrationId,\n });\n }\n\n return cachedDataImport;\n };\n\n try {\n logger.connect(worknice, payload.integrationId);\n\n logger.indent(\"Retrieving Worknice data…\");\n\n const integration = await worknice.getIntegration({\n integrationId: payload.integrationId,\n });\n\n if (integration.archived) {\n logger.info(\"Integration is archived. Skipping sync.\");\n return;\n }\n\n if (integration.status !== \"SYNCING\") {\n logger.info(\"Integration does not have a syncing status. Skipping sync.\");\n return;\n }\n\n logger.info(\"Retrieved integration from Worknice.\");\n\n const personConnections = await worknice.getPersonConnections({\n integrationId: payload.integrationId,\n });\n\n logger.info(`Retrieved ${personConnections.length} person connection(s) from Worknice.`);\n\n const people = await worknice.getPeople({ orgId: integration.org.id });\n\n logger.info(`Retrieved ${people.length} person(s) from Worknice.`);\n\n logger.dedent(\"Completed retrieving Worknice data.\");\n\n const contextWithIntegration = {\n ...context,\n integration,\n };\n\n logger.indent(\"Loading configuration details…\");\n\n const config = await getConfig(contextWithIntegration);\n\n logger.info(\n config.automaticMatching\n ? \"Automatic matching enabled.\"\n : \"Automatic matching disabled.\",\n );\n logger.info(`Using a \"${config.mode}\" sync mode.`);\n\n logger.dedent(\"Finished loading configuration details.\");\n\n logger.indent(`Retrieving ${config.appName} data…`);\n\n const remotePeople = await getRemotePeople(contextWithIntegration);\n\n logger.info(`Retrieved ${remotePeople.length} people from ${config.appName}.`);\n\n logger.dedent(`Completed retrieving ${config.appName} data.`);\n\n logger.indent(\"Updating person connections…\");\n\n for (const remotePerson of remotePeople) {\n const remotePersonName = personToName(remotePerson);\n try {\n const remotePersonConnection = personConnections.find(\n (\n connection,\n ): connection is typeof connection & {\n status:\n | ConnectionStatus.Connected\n | ConnectionStatus.Merged\n | ConnectionStatus.RemoteOnly;\n } => connection.remote?.id === remotePerson.metadata.sourceId,\n );\n\n if (remotePerson.metadata.deleted) {\n // The remote person has been deleted. If they have a person\n // connection, it should be deleted.\n\n if (remotePersonConnection) {\n await worknice.deletePersonConnection({\n personConnectionId: remotePersonConnection.id,\n });\n\n logger.info(\n `Deleted connection for \"${remotePersonName}\" in ${config.appName} because they have been terminated.`,\n );\n }\n } else {\n // A connection for remote person should be added or updated in\n // Worknice.\n\n if (\n remotePersonConnection &&\n (remotePersonConnection.status === ConnectionStatus.Connected ||\n remotePersonConnection.status === ConnectionStatus.Merged)\n ) {\n // The remote person is already connected to a Worknice person.\n\n if (remotePersonConnection.remote?.name !== remotePersonName) {\n // The employee's name has changed in the remote app and that\n // needs to be reflected in the person connection in Worknice.\n\n const connection = await worknice.updatePersonConnection({\n personConnectionId: remotePersonConnection.id,\n personId: remotePersonConnection.person.id,\n remote: {\n id: remotePerson.metadata.sourceId,\n name: remotePersonName,\n },\n status: remotePersonConnection.status,\n });\n\n personConnections.splice(\n personConnections.indexOf(remotePersonConnection),\n 1,\n connection,\n );\n\n logger.info(\n `Updated person connection remote name from \"${remotePersonConnection.remote?.name}\" to \"${remotePersonName}\".`,\n );\n }\n } else {\n // The remote person is not already connected to a Worknice person, but\n // could already have a remote-only connection.\n\n if (\n remotePersonConnection &&\n remotePersonConnection.remote?.name !== remotePersonName\n ) {\n // The person's name has changed in the remote and that\n // needs to be reflected in the person connection in\n // Worknice.\n\n const connection = await worknice.updatePersonConnection({\n personConnectionId: remotePersonConnection.id,\n remote: {\n id: remotePerson.metadata.sourceId,\n name: remotePersonName,\n },\n status: remotePersonConnection.status,\n });\n\n personConnections.splice(\n personConnections.indexOf(remotePersonConnection),\n 1,\n connection,\n );\n\n logger.info(\n `Updated person connection remote name from \"${remotePersonConnection.remote?.name}\" to \"${remotePersonName}\".`,\n );\n }\n\n const matchingWorknicePerson =\n people.find(\n (person) =>\n person.id === remotePerson.metadata.targetId ||\n (person.employeeCode !== null &&\n person.employeeCode === remotePerson.metadata.employeeCode) ||\n (person.personalEmail !== null &&\n person.personalEmail === remotePerson.personalEmail?.personalEmail) ||\n (person.profileEmail !== null &&\n person.profileEmail === remotePerson.profile?.profileEmail),\n ) ?? null;\n\n if (config.automaticMatching === true && matchingWorknicePerson) {\n // There is a person in Worknice with an ID, employee code\n // or email address that matches the remote person. The\n // Worknice person should be automatically connected to the\n // remote person.\n\n const personConnection = personConnections.find(\n (\n connection,\n ): connection is typeof connection & {\n status:\n | ConnectionStatus.Connected\n | ConnectionStatus.LocalOnly\n | ConnectionStatus.Merged;\n } => connection.person?.id === matchingWorknicePerson.id,\n );\n\n if (\n personConnection?.status === ConnectionStatus.Connected ||\n personConnection?.status === ConnectionStatus.Merged\n ) {\n // The person is already matched with a different remote person.\n\n logger.info(\n `Unable to automatically match person \"${matchingWorknicePerson.displayName}\" in Worknice to person \"${remotePersonName}\" in ${config.appName} because the Worknice person has already been matched to a different ${config.appName} person.`,\n );\n } else {\n // The Worknice person is not yet matched to a remote person. The\n // Worknice person and remote person records should be matched.\n\n if (personConnection) {\n // The Worknice person already has a local-only connection in this\n // integration that can be updated to match to this remote person.\n\n if (remotePersonConnection) {\n // There are person connections for both the Worknice\n // person and the remote person that need to be combined\n // into a single person connection.\n\n await worknice.deletePersonConnection({\n personConnectionId: personConnection.id,\n });\n\n personConnections.splice(personConnections.indexOf(personConnection), 1);\n\n const updatedConnection = await worknice.updatePersonConnection({\n personConnectionId: remotePersonConnection.id,\n personId: matchingWorknicePerson.id,\n remote: {\n id: remotePerson.metadata.sourceId,\n name: remotePersonName,\n },\n status: ConnectionStatus.Connected,\n });\n\n personConnections.splice(\n personConnections.indexOf(remotePersonConnection),\n 1,\n updatedConnection,\n );\n\n logger.info(\n `Automatically matched and combined person connections for person \"${matchingWorknicePerson.displayName}\" in Worknice and person \"${remotePersonName}\" in ${config.appName}.`,\n );\n } else {\n // There is a local-only connection for this Worknice person\n // that should be updated to connect to this remote person.\n\n const updatedConnection = await worknice.updatePersonConnection({\n personConnectionId: personConnection.id,\n personId: personConnection.person.id,\n remote: {\n id: remotePerson.metadata.sourceId,\n name: remotePersonName,\n },\n status: ConnectionStatus.Connected,\n });\n\n personConnections.splice(\n personConnections.indexOf(personConnection),\n 1,\n updatedConnection,\n );\n\n logger.info(\n `Automatically matched existing person connection for person \"${matchingWorknicePerson.displayName}\" in Worknice to person \"${remotePersonName}\" in ${config.appName}.`,\n );\n }\n } else {\n // The Worknice person does not have a connection in this\n // integration and should be connected now.\n\n if (remotePersonConnection) {\n // There is a remote-only connection for this remote person that\n // should be updated to match to this Worknice person.\n\n const updatedConnection = await worknice.updatePersonConnection({\n personConnectionId: remotePersonConnection.id,\n personId: matchingWorknicePerson.id,\n remote: {\n ...remotePersonConnection.remote,\n name: remotePersonName,\n },\n status: ConnectionStatus.Connected,\n });\n\n personConnections.splice(\n personConnections.indexOf(remotePersonConnection),\n 1,\n updatedConnection,\n );\n\n logger.info(\n `Automatically matched existing person connection for person \"${remotePersonName}\" in ${config.appName} to person \"${matchingWorknicePerson.displayName}\" in Worknice.`,\n );\n } else {\n // There is no connection for the remote person or the\n // Worknice person in this integration. A new connection\n // should be created.\n\n const newPersonConnection = await worknice.createPersonConnection({\n integrationId: payload.integrationId,\n personId: matchingWorknicePerson.id,\n remote: {\n id: remotePerson.metadata.sourceId,\n name: remotePersonName,\n },\n status: ConnectionStatus.Connected,\n });\n\n personConnections.push(newPersonConnection);\n\n logger.info(\n `Created new person connection for person \"${remotePersonName}\" in ${config.appName} and automatically matched to person \"${matchingWorknicePerson.displayName}\" in Worknice.`,\n );\n }\n }\n }\n } else if (remotePersonConnection === undefined) {\n // There is no person in Worknice which should be automatically\n // connected to this remote person and there is no existing connection\n // for this remote person.\n\n const newPersonConnection = await worknice.createPersonConnection({\n integrationId: payload.integrationId,\n remote: {\n id: remotePerson.metadata.sourceId,\n name: remotePersonName,\n },\n status: ConnectionStatus.RemoteOnly,\n });\n\n personConnections.push(newPersonConnection);\n\n logger.info(\n `New person connection created for person \"${remotePersonName}\" in ${config.appName}.`,\n );\n }\n }\n }\n } catch (error) {\n logger.info(\n `Unable to update person connection for person \"${remotePersonName}\" in ${config.appName} because of the following error:`,\n );\n logger.error(error);\n }\n }\n\n logger.dedent(\"Finished updating person connections.\");\n\n if (config.mode === \"one-way\" || config.mode === \"two-way\") {\n logger.indent(\"Updating people with connections marked as merged…\");\n\n const mergedConnections = personConnections.filter(\n (\n personConnection,\n ): personConnection is typeof personConnection & {\n status: ConnectionStatus.Merged;\n } => personConnection.status === ConnectionStatus.Merged,\n );\n\n for (const personConnection of mergedConnections) {\n const worknicePerson = people.find(\n (person) => person.id === personConnection.person.id,\n );\n const remotePerson = remotePeople.find(\n (person) => person.metadata.sourceId === personConnection.remote.id,\n );\n\n if (!worknicePerson) {\n throw Error(\n `Unable to find person in Worknice with the ID \"${personConnection.person.id}\".`,\n );\n }\n\n if (!remotePerson) {\n throw Error(\n `Unable to find person in ${config.appName} with the ID \"${personConnection.remote.id}\".`,\n );\n }\n\n const remotePersonName = personToName(remotePerson);\n\n const worknicePersonDataTransferLine = {\n ...worknicePersonToPersonDataTransferLine(worknicePerson),\n metadata: {\n deleted: false,\n employeeCode: worknicePerson.employeeCode ?? null,\n sourceId: worknicePerson.id,\n targetId: remotePerson.metadata.sourceId,\n updatedAt: worknicePerson.updatedAt,\n },\n profile: {\n displayName: worknicePerson.displayName,\n profileEmail: worknicePerson.profileEmail ?? null,\n },\n };\n\n const remotePersonDataTransferLine = remotePerson;\n\n const comparison = comparePersonDataTransferLines(\n worknicePersonDataTransferLine,\n remotePersonDataTransferLine,\n );\n\n if (\n comparison.hasDifferences &&\n ((config.syncFields?.bankAccounts &&\n comparison.sections.bankAccounts.hasDifferences) ||\n (config.syncFields?.dateOfBirth &&\n comparison.sections.dateOfBirth.hasDifferences) ||\n (config.syncFields?.fullName && comparison.sections.fullName.hasDifferences) ||\n (config.syncFields?.gender && comparison.sections.gender.hasDifferences) ||\n (config.syncFields?.personalEmail &&\n comparison.sections.personalEmail.hasDifferences) ||\n (config.syncFields?.personalPhone &&\n comparison.sections.personalPhone.hasDifferences) ||\n (config.syncFields?.residentialAddress &&\n comparison.sections.residentialAddress.hasDifferences))\n ) {\n // Differences found between the Worknice person and the remote\n // person. Update either the Worknice person or the remote\n // person with details from the other.\n\n const worknicePersonUpdatedAt = Temporal.Instant.from(worknicePerson.updatedAt);\n\n if (!isValidInstant(remotePerson.metadata.updatedAt)) {\n throw Error(\n `Invalid updatedAt value for ${config.appName} person \"${remotePersonName}\". Must be in ISO 8601 format, including a date, a time, and a time zone offset.`,\n {\n cause: Error(`Unable to parse: ${remotePerson.metadata.updatedAt}`),\n },\n );\n }\n\n const remotePersonUpdatedAt = Temporal.Instant.from(\n remotePerson.metadata.updatedAt,\n );\n\n if (isInstantAfter(worknicePersonUpdatedAt, remotePersonUpdatedAt)) {\n if (config.mode === \"two-way\") {\n // The Worknice person was updated more recently than the remote\n // person. Update the remote person using details from Worknice.\n\n if (!updateRemotePerson) {\n throw Error(\n \"No updateRemotePerson function supplied to handleTriggerIntegrationSyncWebhook.\",\n );\n }\n\n try {\n await updateRemotePerson(\n worknicePersonDataTransferLine,\n contextWithIntegration,\n );\n logger.info(`Updated person \"${remotePersonName}\" in ${config.appName}.`);\n } catch (error) {\n logger.info(\n `Unable to update person \"${remotePersonName}\" in ${config.appName} because of the following error:`,\n );\n logger.error(error);\n }\n }\n } else {\n // The remote person was updated more recently than the\n // Worknice person. Update the Worknice person using details\n // from the remote.\n\n try {\n const bankAccounts = validatePersonDataTransferLineBankAccounts(\n remotePersonDataTransferLine.bankAccounts,\n );\n const dateOfBirth = validatePersonDataTransferLineDateOfBirth(\n remotePersonDataTransferLine.dateOfBirth,\n );\n // emergencyContacts\n const fullName = validatePersonDataTransferLineFullName(\n remotePersonDataTransferLine.fullName,\n );\n const gender = validatePersonDataTransferLineGender(\n remotePersonDataTransferLine.gender,\n );\n const personalEmail = validatePersonDataTransferLinePersonalEmail(\n remotePersonDataTransferLine.personalEmail,\n );\n const personalPhone = validatePersonDataTransferLinePersonalPhone(\n remotePersonDataTransferLine.personalPhone,\n );\n // postalAddress\n // profile\n // remuneration\n const residentialAddress = validatePersonDataTransferLineResidentialAddress(\n remotePersonDataTransferLine.residentialAddress,\n );\n // // TODO: Enable syncing super funds. See PROD-2216.\n // const superFunds = validatePersonDataTransferLineSuperFunds(remotePersonDataTransferLine.superFunds);\n // // TODO: Enable syncing tax details. See PROD-2375.\n // const taxDetails = validatePersonDataTransferLineTaxDetails(remotePersonDataTransferLine.taxDetails);\n // // TODO: Enable syncing tenure. See PROD-1371.\n // const tenure = validatePersonDataTransferLineTenure(remotePersonDataTransferLine.tenure);\n\n const dataImport = await getDataImport();\n\n await worknice.createPersonDataImportLine({\n bankAccounts,\n config: {\n bankAccounts: config.syncFields?.bankAccounts ?? false,\n dateOfBirth: config.syncFields?.dateOfBirth ?? false,\n emergencyContacts: config.syncFields?.emergencyContacts ?? false,\n fullName: config.syncFields?.fullName ?? false,\n gender: config.syncFields?.gender ?? false,\n personalEmail: config.syncFields?.personalEmail ?? false,\n personalPhone: config.syncFields?.personalPhone ?? false,\n postalAddress: config.syncFields?.postalAddress ?? false,\n profile: config.syncFields?.profile ?? false,\n remuneration: config.syncFields?.remuneration ?? false,\n residentialAddress: config.syncFields?.residentialAddress ?? false,\n superFunds: config.syncFields?.superFunds ?? false,\n taxDetails: config.syncFields?.taxDetails ?? false,\n tenure: config.syncFields?.tenure ?? false,\n },\n dataImportId: dataImport.id,\n dateOfBirth,\n emergencyContacts: null,\n fullName,\n gender,\n personalEmail,\n personalPhone,\n personId: worknicePerson.id,\n postalAddress: null,\n residentialAddress,\n // TODO: Enable syncing super funds. See PROD-2216.\n superFunds: null,\n // TODO: Enable syncing tax details. See PROD-2375.\n taxDetails: null,\n // TODO: Enable syncing tenure. See PROD-1371.\n tenure: null,\n });\n\n logger.info(`Updated person \"${worknicePerson.displayName}\" in Worknice.`);\n } catch (error) {\n logger.info(\n `Unable to update person \"${worknicePerson.displayName}\" in Worknice because of the following error:`,\n );\n logger.error(error);\n }\n }\n }\n }\n\n logger.dedent(\"Finished updating people with connections marked as merged.\");\n }\n\n logger.indent(\"Merging unmerged connections…\");\n\n const connectedConnections = personConnections.filter(\n (\n personConnection,\n ): personConnection is typeof personConnection & {\n status: ConnectionStatus.Connected;\n } => personConnection.status === ConnectionStatus.Connected,\n );\n\n for (const personConnection of connectedConnections) {\n const worknicePerson = people.find(\n (person) => person.id === personConnection.person.id,\n );\n const remotePerson = remotePeople.find(\n (person) => person.metadata.sourceId === personConnection.remote.id,\n );\n\n if (!worknicePerson) {\n throw Error(\n `Unable to find person in Worknice with the ID \"${personConnection.person.id}\".`,\n );\n }\n\n if (!remotePerson) {\n throw Error(\n `Unable to find person in ${config.appName} with the ID \"${personConnection.remote.id}\".`,\n );\n }\n\n const remotePersonName = personToName(remotePerson);\n\n logger.indent(\n `Merging Worknice person \"${worknicePerson.displayName}\" with ${config.appName} person \"${remotePersonName}\"…`,\n );\n\n try {\n if (config.mode === \"one-way\" || config.mode === \"two-way\") {\n const worknicePersonUpdatedAt = Temporal.Instant.from(worknicePerson.updatedAt);\n\n if (!isValidInstant(remotePerson.metadata.updatedAt)) {\n throw Error(\n `Invalid updatedAt value for ${config.appName} person \"${remotePersonName}\". Must be in ISO 8601 format, including a date, a time, and a time zone offset.`,\n {\n cause: Error(`Unable to parse: ${remotePerson.metadata.updatedAt}`),\n },\n );\n }\n\n const remotePersonUpdatedAt = Temporal.Instant.from(\n remotePerson.metadata.updatedAt,\n );\n\n const [primaryDataTransferLine, secondaryDataTransferLine] = isInstantAfter(\n worknicePersonUpdatedAt,\n remotePersonUpdatedAt,\n )\n ? [worknicePersonToPersonDataTransferLine(worknicePerson), remotePerson]\n : [remotePerson, worknicePersonToPersonDataTransferLine(worknicePerson)];\n const mergedDataTransferLine = mergePersonDataTransferLines(\n primaryDataTransferLine,\n secondaryDataTransferLine,\n );\n\n const bankAccounts = validatePersonDataTransferLineBankAccounts(\n mergedDataTransferLine.bankAccounts,\n );\n const dateOfBirth = validatePersonDataTransferLineDateOfBirth(\n mergedDataTransferLine.dateOfBirth,\n );\n // emergencyContacts\n const fullName = validatePersonDataTransferLineFullName(\n mergedDataTransferLine.fullName,\n );\n const gender = validatePersonDataTransferLineGender(mergedDataTransferLine.gender);\n const personalEmail = validatePersonDataTransferLinePersonalEmail(\n mergedDataTransferLine.personalEmail,\n );\n const personalPhone = validatePersonDataTransferLinePersonalPhone(\n mergedDataTransferLine.personalPhone,\n );\n // postalAddress\n // profile\n // remuneration\n const residentialAddress = validatePersonDataTransferLineResidentialAddress(\n mergedDataTransferLine.residentialAddress,\n );\n // // TODO: Enable syncing super funds. See PROD-2216.\n // const superFunds = validatePersonDataTransferLineSuperFunds(mergedDataTransferLine.superFunds);\n // // TODO: Enable syncing tax details. See PROD-2375.\n // const taxDetails = validatePersonDataTransferLineTaxDetails(mergedDataTransferLine.taxDetails);\n // // TODO: Enable syncing tenure. See PROD-1371.\n // const tenure = validatePersonDataTransferLineTenure(mergedDataTransferLine.tenure);\n\n const dataImport = await getDataImport();\n\n await worknice.createPersonDataImportLine({\n bankAccounts,\n config: {\n bankAccounts: config.syncFields?.bankAccounts ?? false,\n dateOfBirth: config.syncFields?.dateOfBirth ?? false,\n emergencyContacts: config.syncFields?.emergencyContacts ?? false,\n fullName: config.syncFields?.fullName ?? false,\n gender: config.syncFields?.gender ?? false,\n personalEmail: config.syncFields?.personalEmail ?? false,\n personalPhone: config.syncFields?.personalPhone ?? false,\n postalAddress: config.syncFields?.postalAddress ?? false,\n profile: config.syncFields?.profile ?? false,\n remuneration: config.syncFields?.remuneration ?? false,\n residentialAddress: config.syncFields?.residentialAddress ?? false,\n superFunds: config.syncFields?.superFunds ?? false,\n taxDetails: config.syncFields?.taxDetails ?? false,\n tenure: config.syncFields?.tenure ?? false,\n },\n dataImportId: dataImport.id,\n dateOfBirth,\n emergencyContacts: null,\n fullName,\n gender,\n personalEmail,\n personalPhone,\n personId: worknicePerson.id,\n postalAddress: null,\n residentialAddress,\n // TODO: Enable syncing super funds. See PROD-2216.\n superFunds: null,\n // TODO: Enable syncing tax details. See PROD-2375.\n taxDetails: null,\n // TODO: Enable syncing tenure. See PROD-1371.\n tenure: null,\n });\n\n logger.info(`Updated person \"${worknicePerson.displayName}\" in Worknice.`);\n\n if (config.mode === \"two-way\") {\n if (!updateRemotePerson) {\n throw Error(\n \"No updateRemotePerson function supplied to handleTriggerIntegrationSyncWebhook.\",\n );\n }\n\n await updateRemotePerson(\n {\n ...mergedDataTransferLine,\n metadata: {\n deleted: false,\n employeeCode: worknicePerson.employeeCode ?? null,\n sourceId: worknicePerson.id,\n targetId: remotePerson.metadata.sourceId,\n updatedAt: worknicePerson.updatedAt,\n },\n profile: {\n displayName: worknicePerson.displayName,\n profileEmail: worknicePerson.profileEmail ?? null,\n },\n },\n contextWithIntegration,\n );\n\n logger.info(`Updated person \"${remotePersonName}\" in ${config.appName}.`);\n }\n }\n\n await worknice.updatePersonConnection({\n personConnectionId: personConnection.id,\n personId: personConnection.person.id,\n remote: {\n id: remotePerson.metadata.sourceId,\n name: remotePersonName,\n },\n status: ConnectionStatus.Merged,\n });\n\n logger.dedent(`Finished merging.`);\n } catch (error) {\n logger.info(\n `Unable to merge ${config.appName} person \"${remotePersonName}\" and Worknice person \"${worknicePerson.displayName}\" because of the following error:`,\n );\n logger.error(error);\n logger.dedent();\n }\n }\n\n logger.dedent(\"Finished merging unmerged connections.\");\n\n if (config.mode === \"two-way\") {\n logger.indent(`Adding new people to ${config.appName}…`);\n\n const localOnlyConnections = personConnections.filter(\n (\n personConnection,\n ): personConnection is typeof personConnection & {\n status: ConnectionStatus.LocalOnly;\n } => personConnection.status === ConnectionStatus.LocalOnly,\n );\n\n for (const personConnection of localOnlyConnections) {\n const worknicePerson = people.find(\n (person) => person.id === personConnection.person.id,\n );\n\n if (!worknicePerson) {\n throw Error(\n `Unable to find person in Worknice with the ID \"${personConnection.person.id}\".`,\n );\n }\n\n try {\n if (!createRemotePerson) {\n throw Error(\n \"No createRemotePerson function supplied to handleTriggerIntegrationSyncWebhook.\",\n );\n }\n\n const remote = await createRemotePerson(\n {\n ...worknicePersonToPersonDataTransferLine(worknicePerson),\n metadata: {\n deleted: false,\n employeeCode: worknicePerson.employeeCode ?? null,\n sourceId: worknicePerson.id,\n targetId: null,\n updatedAt: worknicePerson.updatedAt,\n },\n profile: {\n displayName: worknicePerson.displayName,\n profileEmail: worknicePerson.profileEmail ?? null,\n },\n },\n contextWithIntegration,\n );\n\n if (personConnections.some((connection) => connection.remote?.id === remote.id)) {\n throw Error(\n `A connection already exists for the ${config.appName} person \"${remote.name}\".`,\n );\n }\n\n await worknice.updatePersonConnection({\n personConnectionId: personConnection.id,\n personId: personConnection.person.id,\n remote,\n status: ConnectionStatus.Merged,\n });\n\n logger.info(`Added new person \"${remote.name}\" to ${config.appName}.`);\n } catch (error) {\n logger.info(\n `Unable to add person \"${worknicePerson.displayName}\" in Worknice to ${config.appName} because of the following error:`,\n );\n logger.error(error);\n }\n }\n\n logger.dedent(`Finished adding new people to ${config.appName}.`);\n }\n\n await worknice.completeSync({ integrationId: payload.integrationId });\n\n logger.info(\"Sync completed.\");\n } catch (error) {\n await worknice.completeSync({ integrationId: payload.integrationId });\n throw error;\n }\n },\n parseRequest: async (context) => {\n const payload = await context.request.json();\n return {\n env: await getEnv({ ...context, payload }),\n payload,\n };\n },\n },\n options,\n );\n\nconst personToName = (person: Person) => {\n if (\n (person.fullName?.givenName ?? \"\").trim() !== \"\" &&\n (person.fullName?.familyName ?? \"\").trim() !== \"\"\n ) {\n return `${person.fullName?.givenName} ${person.fullName?.familyName}`;\n }\n\n if ((person.profile?.displayName ?? \"\").trim() !== \"\") {\n return `${person.profile?.displayName}`;\n }\n\n return `(unnamed person ${person.metadata.sourceId})`;\n};\n\nconst worknicePersonToPersonDataTransferLine = (\n worknicePerson: NonNullable<GetPeopleQuery[\"org\"][\"people\"][number]>,\n): PartialPersonDataTransferLine => ({\n bankAccounts: worknicePerson.bankAccount1AllocationMethod\n ? {\n bankAccount1Allocation: worknicePerson.bankAccount1Allocation ?? null,\n bankAccount1AllocationMethod: worknicePerson.bankAccount1AllocationMethod,\n bankAccount1Bsb: worknicePerson.bankAccount1Bsb ?? null,\n bankAccount1Name: worknicePerson.bankAccount1Name ?? null,\n bankAccount1Number: worknicePerson.bankAccount1Number ?? null,\n bankAccount2Allocation: worknicePerson.bankAccount2Allocation ?? null,\n bankAccount2AllocationMethod: worknicePerson.bankAccount2AllocationMethod ?? null,\n bankAccount2Bsb: worknicePerson.bankAccount2Bsb ?? null,\n bankAccount2Name: worknicePerson.bankAccount2Name ?? null,\n bankAccount2Number: worknicePerson.bankAccount2Number ?? null,\n bankAccount3Allocation: worknicePerson.bankAccount3Allocation ?? null,\n bankAccount3AllocationMethod: worknicePerson.bankAccount3AllocationMethod ?? null,\n bankAccount3Bsb: worknicePerson.bankAccount3Bsb ?? null,\n bankAccount3Name: worknicePerson.bankAccount3Name ?? null,\n bankAccount3Number: worknicePerson.bankAccount3Number ?? null,\n bankAccount4Allocation: worknicePerson.bankAccount4Allocation ?? null,\n bankAccount4AllocationMethod: worknicePerson.bankAccount4AllocationMethod ?? null,\n bankAccount4Bsb: worknicePerson.bankAccount4Bsb ?? null,\n bankAccount4Name: worknicePerson.bankAccount4Name ?? null,\n bankAccount4Number: worknicePerson.bankAccount4Number ?? null,\n bankAccount5Allocation: worknicePerson.bankAccount5Allocation ?? null,\n bankAccount5AllocationMethod: worknicePerson.bankAccount5AllocationMethod ?? null,\n bankAccount5Bsb: worknicePerson.bankAccount5Bsb ?? null,\n bankAccount5Name: worknicePerson.bankAccount5Name ?? null,\n bankAccount5Number: worknicePerson.bankAccount5Number ?? null,\n }\n : null,\n dateOfBirth: worknicePerson.dateOfBirth ? { dateOfBirth: worknicePerson.dateOfBirth } : null,\n emergencyContacts: null,\n fullName: worknicePerson.givenName\n ? {\n familyName: worknicePerson.familyName ?? null,\n givenName: worknicePerson.givenName ?? null,\n otherGivenNames: worknicePerson.otherGivenNames ?? null,\n }\n : null,\n gender: worknicePerson.gender\n ? {\n gender: worknicePerson.gender,\n }\n : null,\n personalEmail: worknicePerson.personalEmail\n ? {\n personalEmail: worknicePerson.personalEmail,\n }\n : null,\n personalPhone: worknicePerson.personalPhone\n ? {\n personalPhone: worknicePerson.personalPhone,\n }\n : null,\n postalAddress: null,\n residentialAddress: worknicePerson.residentialAddressLine1\n ? {\n residentialAddressCity: worknicePerson.residentialAddressCity ?? null,\n // FIXME: This should not default to \"Australia\". See PROD-1085.\n residentialAddressCountry: worknicePerson.residentialAddressCountry ?? \"Australia\",\n residentialAddressLine1: worknicePerson.residentialAddressLine1 ?? null,\n residentialAddressLine2: worknicePerson.residentialAddressLine2 ?? null,\n residentialAddressPostcode: worknicePerson.residentialAddressPostcode ?? null,\n residentialAddressState: worknicePerson.residentialAddressState ?? null,\n }\n : null,\n // TODO: Enable syncing super funds. See PROD-2216.\n superFunds: null,\n // TODO: Enable syncing tax details. See PROD-2375.\n taxDetails: null,\n // TODO: Enable syncing tenure. See PROD-1371.\n tenure: null,\n});\n\nexport default handleTriggerIntegrationSyncWebhook;\n"],"mappings":"AAAA,OAAO,oBAAoB;AAC3B,OAAO,oBAAoB;AAC3B,SAAS,gBAAgB;AACzB,SAAS,wBAAkE;AAE3E,OAAO,oCAAoC;AAC3C,OAAO,kCAAkC;AACzC,OAAO,gDAAgD;AACvD,OAAO,+CAA+C;A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EJ,YAAY;AAAA;AAAA,EAEZ,YAAY;AAAA;AAAA,EAEZ,QAAQ;AACV;AAEA,IAAO,8CAAQ;","names":[]}
@@ -10,6 +10,10 @@ ${stack}
10
10
  };
11
11
  const errorToMessage = (error, indent = 0) => {
12
12
  if (error instanceof Error) {
13
+ if (error instanceof AggregateError) {
14
+ return `[${error.name}]${error.message ? ` ${error.message}` : ""}${error.errors.map((error2) => `
15
+ ${" ".repeat(indent + 1)}` + errorToMessage(error2, indent + 1)).join("")}`;
16
+ }
13
17
  return `[${error.name}] ${error instanceof ApiError ? `(${error.code}) ${error.message}` : error.message}${error.cause ? `
14
18
  ${" ".repeat(indent + 1)}${errorToMessage(error.cause, indent + 1)}` : ""}`;
15
19
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/errorToString.ts"],"sourcesContent":["import ApiError from \"../api/ApiError.js\";\n\n/**\n * Converts an error to a string that can be logged. Displays a trace of errors\n * causes, `errorCode` value from `ApiError` and a stack trace for the root\n * error:\n *\n * ```txt\n * [ApiError] (UNEXPECTED_RESPONSE) The API returned an unexpected response. This is likely a problem with the Worknice API or a mismatch between JS-SDK and the API. Make sure you are using the latest version of the JS-SDK.\n * [RequestError] POST https://app.worknice.com/api/graphql 404 Not Found\n *\n * ApiError: The API returned an unexpected response. This is likely a problem with the Worknice API or a mismatch between JS-SDK and the API. Make sure you are using the latest version of the JS-SDK.\n * at fetchFromApi (webpack-internal:///(api)/./src/api/createWorkniceClient.js:69:19)\n * at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n * at async Object.eval [as initializeIntegration] (webpack-internal:///(api)/./src/api/operations/initializeIntegration.js:10:24)\n * at async handleCreateIntegrationWebhook (webpack-internal:///(api)/./src/helpers/handleCreateIntegrationWebhook.js:21:9)\n * ```\n */\nconst errorToString = (\n error: unknown,\n options?: { format: \"chain\" | \"simple\"; stack: boolean },\n): string => {\n const message =\n options?.format === \"simple\"\n ? error instanceof Error\n ? error.message\n : `${error}`\n : errorToMessage(error);\n const stack = options?.stack === false ? undefined : errorToStack(error);\n return stack ? `${message}\\n\\n${stack}\\n` : `${message}\\n`;\n};\n\nconst errorToMessage = (error: unknown, indent: number = 0): string => {\n if (error instanceof Error) {\n return `[${error.name}] ${\n error instanceof ApiError ? `(${error.code}) ${error.message}` : error.message\n }${error.cause ? `\\n${\" \".repeat(indent + 1)}${errorToMessage(error.cause, indent + 1)}` : \"\"}`;\n }\n return JSON.stringify(error);\n};\n\nconst errorToStack = (error: unknown): string | undefined => {\n if (error instanceof Error) {\n return error.stack ?? (error.cause ? errorToStack(error.cause) : undefined);\n }\n return undefined;\n};\n\nexport default errorToString;\n"],"mappings":"AAAA,OAAO,cAAc;AAkBrB,MAAM,gBAAgB,CACpB,OACA,YACW;AACX,QAAM,UACJ,SAAS,WAAW,WAChB,iBAAiB,QACf,MAAM,UACN,GAAG,KAAK,KACV,eAAe,KAAK;AAC1B,QAAM,QAAQ,SAAS,UAAU,QAAQ,SAAY,aAAa,KAAK;AACvE,SAAO,QAAQ,GAAG,OAAO;AAAA;AAAA,EAAO,KAAK;AAAA,IAAO,GAAG,OAAO;AAAA;AACxD;AAEA,MAAM,iBAAiB,CAAC,OAAgB,SAAiB,MAAc;AACrE,MAAI,iBAAiB,OAAO;AAC1B,WAAO,IAAI,MAAM,IAAI,KACnB,iBAAiB,WAAW,IAAI,MAAM,IAAI,KAAK,MAAM,OAAO,KAAK,MAAM,OACzE,GAAG,MAAM,QAAQ;AAAA,EAAK,KAAK,OAAO,SAAS,CAAC,CAAC,GAAG,eAAe,MAAM,OAAO,SAAS,CAAC,CAAC,KAAK,EAAE;AAAA,EAChG;AACA,SAAO,KAAK,UAAU,KAAK;AAC7B;AAEA,MAAM,eAAe,CAAC,UAAuC;AAC3D,MAAI,iBAAiB,OAAO;AAC1B,WAAO,MAAM,UAAU,MAAM,QAAQ,aAAa,MAAM,KAAK,IAAI;AAAA,EACnE;AACA,SAAO;AACT;AAEA,IAAO,wBAAQ;","names":[]}
1
+ {"version":3,"sources":["../../src/utils/errorToString.ts"],"sourcesContent":["import ApiError from \"../api/ApiError.js\";\n\n/**\n * Converts an error to a string that can be logged. Displays a trace of errors\n * causes, `errorCode` value from `ApiError` and a stack trace for the root\n * error:\n *\n * ```txt\n * [ApiError] (UNEXPECTED_RESPONSE) The API returned an unexpected response. This is likely a problem with the Worknice API or a mismatch between JS-SDK and the API. Make sure you are using the latest version of the JS-SDK.\n * [RequestError] POST https://app.worknice.com/api/graphql 404 Not Found\n *\n * ApiError: The API returned an unexpected response. This is likely a problem with the Worknice API or a mismatch between JS-SDK and the API. Make sure you are using the latest version of the JS-SDK.\n * at fetchFromApi (webpack-internal:///(api)/./src/api/createWorkniceClient.js:69:19)\n * at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n * at async Object.eval [as initializeIntegration] (webpack-internal:///(api)/./src/api/operations/initializeIntegration.js:10:24)\n * at async handleCreateIntegrationWebhook (webpack-internal:///(api)/./src/helpers/handleCreateIntegrationWebhook.js:21:9)\n * ```\n */\nconst errorToString = (\n error: unknown,\n options?: { format: \"chain\" | \"simple\"; stack: boolean },\n): string => {\n const message =\n options?.format === \"simple\"\n ? error instanceof Error\n ? error.message\n : `${error}`\n : errorToMessage(error);\n const stack = options?.stack === false ? undefined : errorToStack(error);\n return stack ? `${message}\\n\\n${stack}\\n` : `${message}\\n`;\n};\n\nconst errorToMessage = (error: unknown, indent: number = 0): string => {\n if (error instanceof Error) {\n if (error instanceof AggregateError) {\n return `[${error.name}]${error.message ? ` ${error.message}` : \"\"}${error.errors\n .map((error) => `\\n${\" \".repeat(indent + 1)}` + errorToMessage(error, indent + 1))\n .join(\"\")}`;\n }\n\n return `[${error.name}] ${\n error instanceof ApiError ? `(${error.code}) ${error.message}` : error.message\n }${error.cause ? `\\n${\" \".repeat(indent + 1)}${errorToMessage(error.cause, indent + 1)}` : \"\"}`;\n }\n return JSON.stringify(error);\n};\n\nconst errorToStack = (error: unknown): string | undefined => {\n if (error instanceof Error) {\n return error.stack ?? (error.cause ? errorToStack(error.cause) : undefined);\n }\n return undefined;\n};\n\nexport default errorToString;\n"],"mappings":"AAAA,OAAO,cAAc;AAkBrB,MAAM,gBAAgB,CACpB,OACA,YACW;AACX,QAAM,UACJ,SAAS,WAAW,WAChB,iBAAiB,QACf,MAAM,UACN,GAAG,KAAK,KACV,eAAe,KAAK;AAC1B,QAAM,QAAQ,SAAS,UAAU,QAAQ,SAAY,aAAa,KAAK;AACvE,SAAO,QAAQ,GAAG,OAAO;AAAA;AAAA,EAAO,KAAK;AAAA,IAAO,GAAG,OAAO;AAAA;AACxD;AAEA,MAAM,iBAAiB,CAAC,OAAgB,SAAiB,MAAc;AACrE,MAAI,iBAAiB,OAAO;AAC1B,QAAI,iBAAiB,gBAAgB;AACnC,aAAO,IAAI,MAAM,IAAI,IAAI,MAAM,UAAU,IAAI,MAAM,OAAO,KAAK,EAAE,GAAG,MAAM,OACvE,IAAI,CAACA,WAAU;AAAA,EAAK,KAAK,OAAO,SAAS,CAAC,CAAC,KAAK,eAAeA,QAAO,SAAS,CAAC,CAAC,EACjF,KAAK,EAAE,CAAC;AAAA,IACb;AAEA,WAAO,IAAI,MAAM,IAAI,KACnB,iBAAiB,WAAW,IAAI,MAAM,IAAI,KAAK,MAAM,OAAO,KAAK,MAAM,OACzE,GAAG,MAAM,QAAQ;AAAA,EAAK,KAAK,OAAO,SAAS,CAAC,CAAC,GAAG,eAAe,MAAM,OAAO,SAAS,CAAC,CAAC,KAAK,EAAE;AAAA,EAChG;AACA,SAAO,KAAK,UAAU,KAAK;AAC7B;AAEA,MAAM,eAAe,CAAC,UAAuC;AAC3D,MAAI,iBAAiB,OAAO;AAC1B,WAAO,MAAM,UAAU,MAAM,QAAQ,aAAa,MAAM,KAAK,IAAI;AAAA,EACnE;AACA,SAAO;AACT;AAEA,IAAO,wBAAQ;","names":["error"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@worknice/js-sdk",
3
3
  "description": "",
4
- "version": "0.0.5",
4
+ "version": "0.0.6",
5
5
  "license": "MIT",
6
6
  "private": false,
7
7
  "files": [
@@ -36,7 +36,7 @@
36
36
  "dependencies": {
37
37
  "dedent": "^0.7.0",
38
38
  "uuid": "^8.3.2",
39
- "@worknice/utils": "^0.0.4"
39
+ "@worknice/utils": "^0.0.5"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@graphql-codegen/add": "^5.0.0",
@@ -54,7 +54,8 @@
54
54
  "eslint": "^8.57.1",
55
55
  "temporal-polyfill": "^0.2.5",
56
56
  "tsup": "^8.2.4",
57
- "typescript": "~5.5.0"
57
+ "typescript": "~5.5.0",
58
+ "vitest": "^2.1.8"
58
59
  },
59
60
  "peerDependencies": {
60
61
  "currency.js": "^2.0.4",
@@ -63,11 +64,13 @@
63
64
  "scripts": {
64
65
  "build": "cp ../../apps/notebook/src/utils/webhooks.ts ./src && rm -rf ./dist && tsup",
65
66
  "dev": "cp ../../apps/notebook/src/utils/webhooks.ts ./src && pnpm dev:codegen && pnpm run --stream \"/^dev:.*/\"",
67
+ "dev:test": "vitest",
66
68
  "dev:tsup": "rm -rf ./dist && tsup --watch",
67
69
  "dev:codegen": "graphql-codegen -c graphql.config.json -w",
68
70
  "gen:types": "graphql-codegen -c graphql.config.json",
69
71
  "release": "pnpm build && pnpm dlx @jsdevtools/version-bump-prompt --commit \"chore(js-sdk): release v%s\" --tag \"js-sdk-v%s\" && pnpm publish --access public",
70
72
  "test": "if [[ -z $TURBO_HASH ]]; then echo 'Use `pnpm turbo test` to run tests.\n' && exit 1; else exit 0; fi",
73
+ "test:unit": "vitest run",
71
74
  "test:lint": "eslint src --color",
72
75
  "test:prettier": "prettier -c '**/*.{js,ts,tsx,css}'",
73
76
  "test:types": "cp ../../apps/notebook/src/utils/webhooks.ts ./src && tsc --noEmit --pretty"