@zapier/zapier-sdk 0.15.3 → 0.15.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/api/auth.d.ts +10 -0
  3. package/dist/api/auth.d.ts.map +1 -1
  4. package/dist/api/auth.js +45 -0
  5. package/dist/api/auth.test.d.ts +2 -0
  6. package/dist/api/auth.test.d.ts.map +1 -0
  7. package/dist/api/auth.test.js +220 -0
  8. package/dist/api/client.d.ts.map +1 -1
  9. package/dist/api/client.js +18 -32
  10. package/dist/api/client.methods.test.d.ts +2 -0
  11. package/dist/api/client.methods.test.d.ts.map +1 -0
  12. package/dist/api/client.methods.test.js +158 -0
  13. package/dist/api/client.test.js +27 -11
  14. package/dist/api/router.d.ts +16 -0
  15. package/dist/api/router.d.ts.map +1 -0
  16. package/dist/api/router.js +37 -0
  17. package/dist/api/router.test.d.ts +2 -0
  18. package/dist/api/router.test.d.ts.map +1 -0
  19. package/dist/api/router.test.js +109 -0
  20. package/dist/api/schemas.d.ts +38 -38
  21. package/dist/auth.d.ts +15 -0
  22. package/dist/auth.d.ts.map +1 -1
  23. package/dist/auth.js +25 -0
  24. package/dist/index.cjs +350 -87
  25. package/dist/index.d.mts +430 -269
  26. package/dist/index.mjs +350 -88
  27. package/dist/plugins/eventEmission/index.d.ts +1 -1
  28. package/dist/plugins/eventEmission/index.d.ts.map +1 -1
  29. package/dist/plugins/eventEmission/index.js +94 -22
  30. package/dist/plugins/eventEmission/index.test.js +340 -2
  31. package/dist/plugins/getAuthentication/index.d.ts +2 -5
  32. package/dist/plugins/getAuthentication/index.d.ts.map +1 -1
  33. package/dist/plugins/getAuthentication/index.js +3 -24
  34. package/dist/plugins/getAuthentication/index.test.js +32 -144
  35. package/dist/plugins/getAuthentication/schemas.d.ts +4 -13
  36. package/dist/plugins/getAuthentication/schemas.d.ts.map +1 -1
  37. package/dist/plugins/getAuthentication/schemas.js +1 -11
  38. package/dist/schemas/Action.d.ts +1 -1
  39. package/dist/schemas/Auth.d.ts +6 -6
  40. package/dist/sdk.d.ts +1 -1
  41. package/dist/temporary-internal-core/handlers/getAuthentication.d.ts +94 -0
  42. package/dist/temporary-internal-core/handlers/getAuthentication.d.ts.map +1 -0
  43. package/dist/temporary-internal-core/handlers/getAuthentication.js +68 -0
  44. package/dist/temporary-internal-core/handlers/getAuthentication.test.d.ts +2 -0
  45. package/dist/temporary-internal-core/handlers/getAuthentication.test.d.ts.map +1 -0
  46. package/dist/temporary-internal-core/handlers/getAuthentication.test.js +248 -0
  47. package/dist/temporary-internal-core/handlers/listApps.js +1 -1
  48. package/dist/temporary-internal-core/index.d.ts +2 -0
  49. package/dist/temporary-internal-core/index.d.ts.map +1 -1
  50. package/dist/temporary-internal-core/index.js +2 -0
  51. package/dist/temporary-internal-core/schemas/authentications/index.d.ts +454 -0
  52. package/dist/temporary-internal-core/schemas/authentications/index.d.ts.map +1 -0
  53. package/dist/temporary-internal-core/schemas/authentications/index.js +96 -0
  54. package/dist/temporary-internal-core/schemas/errors/index.d.ts +139 -0
  55. package/dist/temporary-internal-core/schemas/errors/index.d.ts.map +1 -0
  56. package/dist/temporary-internal-core/schemas/errors/index.js +129 -0
  57. package/dist/temporary-internal-core/utils/app-locators.d.ts +0 -20
  58. package/dist/temporary-internal-core/utils/app-locators.d.ts.map +1 -1
  59. package/dist/temporary-internal-core/utils/app-locators.js +1 -45
  60. package/dist/temporary-internal-core/utils/string-utils.d.ts +28 -0
  61. package/dist/temporary-internal-core/utils/string-utils.d.ts.map +1 -0
  62. package/dist/temporary-internal-core/utils/string-utils.js +52 -0
  63. package/dist/temporary-internal-core/utils/transformations.d.ts +14 -0
  64. package/dist/temporary-internal-core/utils/transformations.d.ts.map +1 -1
  65. package/dist/temporary-internal-core/utils/transformations.js +37 -1
  66. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -2283,49 +2283,68 @@ var getActionPlugin = ({ sdk }) => {
2283
2283
  }
2284
2284
  };
2285
2285
  };
2286
- var GetAuthenticationSchema = z.object({
2286
+ var AuthenticationSchema2 = z.object({
2287
+ id: z.number(),
2288
+ date: z.string(),
2289
+ lastchanged: z.string().optional(),
2290
+ account_id: z.number(),
2291
+ customuser_id: z.number().optional(),
2292
+ selected_api: z.string(),
2293
+ destination_selected_api: z.string().nullable().optional(),
2294
+ is_invite_only: z.boolean(),
2295
+ is_private: z.boolean(),
2296
+ shared_with_all: z.boolean(),
2297
+ is_stale: z.string().optional(),
2298
+ is_shared: z.string().optional(),
2299
+ marked_stale_at: z.string().nullable().optional(),
2300
+ label: z.string().nullable().optional(),
2301
+ identifier: z.string().nullable().optional(),
2302
+ title: z.string().nullable().optional(),
2303
+ url: z.string().optional(),
2304
+ groups: z.string().optional(),
2305
+ members: z.string().optional(),
2306
+ permissions: z.record(z.boolean()).optional()
2307
+ });
2308
+ z.object({
2309
+ count: z.number(),
2310
+ next: z.string().nullable().optional(),
2311
+ previous: z.string().nullable().optional(),
2312
+ results: z.array(AuthenticationSchema2)
2313
+ });
2314
+ var AuthenticationItemSchema2 = AuthenticationSchema2.omit({
2315
+ selected_api: true,
2316
+ customuser_id: true
2317
+ }).extend({
2318
+ // Renamed fields
2319
+ implementation_id: z.string().optional(),
2320
+ user_id: z.number().optional(),
2321
+ // Mapped fields (originals preserved in ...restOfAuth)
2322
+ is_expired: z.string().optional(),
2323
+ expired_at: z.string().nullable().optional(),
2324
+ // Computed fields
2325
+ app_key: z.string().optional(),
2326
+ app_version: z.string().optional()
2327
+ });
2328
+ var GetAuthenticationOptionsSchema = z.object({
2287
2329
  authenticationId: z.number().int().positive().describe("Authentication ID to retrieve")
2288
2330
  }).describe("Get a specific authentication by ID");
2331
+ var GetAuthenticationHandlerRequestSchema = z.object({
2332
+ authenticationId: z.union([z.string(), z.number()]).describe("Authentication ID - string from searchParams or number")
2333
+ }).transform((data) => ({
2334
+ authenticationId: typeof data.authenticationId === "string" ? parseInt(data.authenticationId, 10) : data.authenticationId
2335
+ }));
2336
+ z.object({
2337
+ data: z.lazy(() => AuthenticationItemSchema2)
2338
+ });
2289
2339
 
2290
2340
  // src/plugins/getAuthentication/index.ts
2291
2341
  var getAuthenticationPlugin = ({ context }) => {
2292
2342
  const getAuthentication = createFunction(async function getAuthentication2(options) {
2293
2343
  const { api } = context;
2294
- const { authenticationId } = options;
2295
- const data = await api.get(
2296
- `/zapier/api/v4/authentications/${authenticationId}/`,
2297
- {
2298
- customErrorHandler: ({ status }) => {
2299
- if (status === 401) {
2300
- return new ZapierAuthenticationError(
2301
- `Authentication failed. Your token may not have permission to access authentications or may be expired. (HTTP ${status})`,
2302
- { statusCode: status }
2303
- );
2304
- }
2305
- if (status === 403) {
2306
- return new ZapierAuthenticationError(
2307
- `Access forbidden. Your token may not have the required scopes to get authentication ${authenticationId}. (HTTP ${status})`,
2308
- { statusCode: status }
2309
- );
2310
- }
2311
- if (status === 404) {
2312
- return new ZapierResourceNotFoundError(
2313
- `Authentication ${authenticationId} not found. It may not exist or you may not have access to it. (HTTP ${status})`,
2314
- {
2315
- resourceType: "Authentication",
2316
- resourceId: String(authenticationId)
2317
- }
2318
- );
2319
- }
2320
- return void 0;
2321
- },
2322
- authRequired: true
2323
- }
2344
+ return await api.get(
2345
+ `/api/v0/authentications/${options.authenticationId}`
2324
2346
  );
2325
- return {
2326
- data: normalizeAuthenticationItem(data)
2327
- };
2328
- }, GetAuthenticationSchema);
2347
+ }, GetAuthenticationOptionsSchema);
2329
2348
  return {
2330
2349
  getAuthentication,
2331
2350
  context: {
@@ -2334,7 +2353,7 @@ var getAuthenticationPlugin = ({ context }) => {
2334
2353
  categories: ["authentication"],
2335
2354
  type: "item",
2336
2355
  itemType: "Authentication",
2337
- inputSchema: GetAuthenticationSchema,
2356
+ inputSchema: GetAuthenticationOptionsSchema,
2338
2357
  outputSchema: AuthenticationItemSchema,
2339
2358
  resolvers: {
2340
2359
  authenticationId: authenticationIdGenericResolver
@@ -3171,12 +3190,46 @@ function isJwt(token) {
3171
3190
  const base64UrlPattern = /^[A-Za-z0-9_-]+$/;
3172
3191
  return parts.every((part) => part.length > 0 && base64UrlPattern.test(part));
3173
3192
  }
3193
+ function parseJwt(token) {
3194
+ if (!isJwt(token)) {
3195
+ return null;
3196
+ }
3197
+ return token.split(".");
3198
+ }
3174
3199
  function getAuthorizationHeader(token) {
3175
3200
  if (isJwt(token)) {
3176
3201
  return `JWT ${token}`;
3177
3202
  }
3178
3203
  return `Bearer ${token}`;
3179
3204
  }
3205
+ function extractUserIdsFromJwt(token) {
3206
+ const parts = parseJwt(token);
3207
+ if (!parts) {
3208
+ return { customuser_id: null, account_id: null };
3209
+ }
3210
+ try {
3211
+ const payload = JSON.parse(
3212
+ Buffer.from(parts[1], "base64url").toString("utf-8")
3213
+ );
3214
+ let actualPayload = payload;
3215
+ if (payload.sub_type === "service" && payload.njwt) {
3216
+ const nestedParts = payload.njwt.split(".");
3217
+ if (nestedParts.length === 3) {
3218
+ actualPayload = JSON.parse(
3219
+ Buffer.from(nestedParts[1], "base64url").toString("utf-8")
3220
+ );
3221
+ }
3222
+ }
3223
+ const accountId = actualPayload["zap:acc"] != null ? parseInt(String(actualPayload["zap:acc"]), 10) : null;
3224
+ const customUserId = actualPayload.sub_type === "customuser" && actualPayload.sub != null ? parseInt(String(actualPayload.sub), 10) : null;
3225
+ return {
3226
+ customuser_id: customUserId !== null && !isNaN(customUserId) ? customUserId : null,
3227
+ account_id: accountId !== null && !isNaN(accountId) ? accountId : null
3228
+ };
3229
+ } catch {
3230
+ return { customuser_id: null, account_id: null };
3231
+ }
3232
+ }
3180
3233
 
3181
3234
  // src/api/debug.ts
3182
3235
  var utilModule = null;
@@ -3461,6 +3514,18 @@ async function getTokenFromEnvOrConfig(options = {}) {
3461
3514
  }
3462
3515
  return getTokenFromCliLogin(options);
3463
3516
  }
3517
+ async function resolveAuthToken(options = {}) {
3518
+ if (options.token) {
3519
+ return options.token;
3520
+ }
3521
+ if (options.getToken) {
3522
+ const token = await options.getToken();
3523
+ if (token) {
3524
+ return token;
3525
+ }
3526
+ }
3527
+ return getTokenFromEnvOrConfig(options);
3528
+ }
3464
3529
 
3465
3530
  // src/utils/url-utils.ts
3466
3531
  function getZapierBaseUrl(baseUrl) {
@@ -3508,7 +3573,7 @@ function getTrackingBaseUrl({
3508
3573
  return ZAPIER_BASE_URL;
3509
3574
  }
3510
3575
 
3511
- // src/temporary-internal-core/utils/app-locators.ts
3576
+ // src/temporary-internal-core/utils/string-utils.ts
3512
3577
  function splitVersionedKey2(versionedKey) {
3513
3578
  const parts = versionedKey.split("@");
3514
3579
  if (parts.length >= 2) {
@@ -3543,6 +3608,44 @@ function extractPaginationCursor(response) {
3543
3608
  return void 0;
3544
3609
  }
3545
3610
  }
3611
+ function normalizeAuthenticationItem2(auth, options = {}) {
3612
+ let appKey = options.app_key;
3613
+ let appVersion = options.app_version;
3614
+ if (auth.selected_api) {
3615
+ const [extractedAppKey, extractedVersion] = splitVersionedKey2(
3616
+ auth.selected_api
3617
+ );
3618
+ if (!appKey) {
3619
+ appKey = extractedAppKey;
3620
+ }
3621
+ if (!appVersion) {
3622
+ appVersion = extractedVersion;
3623
+ }
3624
+ }
3625
+ const {
3626
+ selected_api: selectedApi,
3627
+ customuser_id: userId,
3628
+ ...restOfAuth
3629
+ } = auth;
3630
+ return {
3631
+ ...restOfAuth,
3632
+ // Pass through all other API response fields except selected_api
3633
+ implementation_id: selectedApi,
3634
+ // Rename selected_api to implementation_id
3635
+ title: auth.title || auth.label || void 0,
3636
+ // Coerce title from label if missing
3637
+ is_expired: auth.is_stale,
3638
+ // Map is_stale to is_expired
3639
+ expired_at: auth.marked_stale_at,
3640
+ // Map marked_stale_at to expired_at
3641
+ app_key: appKey,
3642
+ // App key from implementations endpoint or parsed from selected_api
3643
+ app_version: appVersion,
3644
+ // Version from selected_api or provided
3645
+ user_id: userId
3646
+ // Map customuser_id to user_id
3647
+ };
3648
+ }
3546
3649
 
3547
3650
  // src/temporary-internal-core/handlers/listApps.ts
3548
3651
  var DEFAULT_PAGE_SIZE = 20;
@@ -3637,6 +3740,111 @@ var handleListApps = async ({ request, deps }) => {
3637
3740
  };
3638
3741
  };
3639
3742
 
3743
+ // src/temporary-internal-core/schemas/errors/index.ts
3744
+ var ZapierError2 = class extends Error {
3745
+ constructor(message, options = {}) {
3746
+ super(message);
3747
+ this.statusCode = options.statusCode;
3748
+ this.errors = options.errors;
3749
+ this.cause = options.cause;
3750
+ this.response = options.response;
3751
+ Object.setPrototypeOf(this, new.target.prototype);
3752
+ }
3753
+ };
3754
+ var ZapierAuthenticationError2 = class extends ZapierError2 {
3755
+ constructor(message, options = {}) {
3756
+ super(message, options);
3757
+ this.name = "ZapierAuthenticationError";
3758
+ }
3759
+ };
3760
+ var ZapierResourceNotFoundError2 = class extends ZapierError2 {
3761
+ constructor(message, options = {}) {
3762
+ super(message, options);
3763
+ this.name = "ZapierResourceNotFoundError";
3764
+ this.resourceType = options.resourceType;
3765
+ this.resourceId = options.resourceId;
3766
+ }
3767
+ };
3768
+
3769
+ // src/temporary-internal-core/handlers/getAuthentication.ts
3770
+ var handleGetAuthentication = async ({ request, deps }) => {
3771
+ const validatedRequest = GetAuthenticationHandlerRequestSchema.parse(request);
3772
+ const { httpClient } = deps;
3773
+ const { authenticationId } = validatedRequest;
3774
+ const authentication = await httpClient.get(
3775
+ `/zapier/api/v4/authentications/${authenticationId}/`,
3776
+ {
3777
+ authRequired: true,
3778
+ customErrorHandler: ({ status }) => {
3779
+ if (status === 401) {
3780
+ return new ZapierAuthenticationError2(
3781
+ `Authentication failed. Your token may not have permission to access authentications or may be expired. (HTTP ${status})`,
3782
+ { statusCode: status }
3783
+ );
3784
+ }
3785
+ if (status === 403) {
3786
+ return new ZapierAuthenticationError2(
3787
+ `Access forbidden. Your token may not have the required scopes to get authentication ${authenticationId}. (HTTP ${status})`,
3788
+ { statusCode: status }
3789
+ );
3790
+ }
3791
+ if (status === 404) {
3792
+ return new ZapierResourceNotFoundError2(
3793
+ `Authentication ${authenticationId} not found. It may not exist or you may not have access to it. (HTTP ${status})`,
3794
+ {
3795
+ resourceType: "Authentication",
3796
+ resourceId: String(authenticationId)
3797
+ }
3798
+ );
3799
+ }
3800
+ return void 0;
3801
+ }
3802
+ }
3803
+ );
3804
+ const normalizedAuthentication = normalizeAuthenticationItem2(authentication);
3805
+ return {
3806
+ data: normalizedAuthentication
3807
+ };
3808
+ };
3809
+
3810
+ // src/api/router.ts
3811
+ var routes = [
3812
+ {
3813
+ method: "GET",
3814
+ pattern: /^\/api\/v0\/apps$/,
3815
+ handler: handleListApps,
3816
+ paramMap: []
3817
+ },
3818
+ {
3819
+ method: "GET",
3820
+ pattern: /^\/api\/v0\/authentications\/([^\/]+)$/,
3821
+ handler: handleGetAuthentication,
3822
+ paramMap: ["authenticationId"]
3823
+ }
3824
+ ];
3825
+ function findMatchingRoute(routeList, method, path) {
3826
+ for (const route of routeList) {
3827
+ if (route.method !== method) {
3828
+ continue;
3829
+ }
3830
+ const match = path.match(route.pattern);
3831
+ if (match) {
3832
+ const params = {};
3833
+ route.paramMap.forEach((name, index) => {
3834
+ params[name] = match[index + 1];
3835
+ });
3836
+ return {
3837
+ handler: route.handler,
3838
+ params
3839
+ };
3840
+ }
3841
+ }
3842
+ return null;
3843
+ }
3844
+ function matchRoute(method, path) {
3845
+ return findMatchingRoute(routes, method, path);
3846
+ }
3847
+
3640
3848
  // src/api/client.ts
3641
3849
  var pathConfig = {
3642
3850
  // e.g. /relay -> https://sdkapi.zapier.com/api/v0/sdk/relay/...
@@ -3648,9 +3856,6 @@ var pathConfig = {
3648
3856
  "/zapier": {
3649
3857
  authHeader: "Authorization",
3650
3858
  pathPrefix: "/api/v0/sdk/zapier"
3651
- },
3652
- "/api/v0/apps": {
3653
- handlerOverride: handleListApps
3654
3859
  }
3655
3860
  };
3656
3861
  var ZapierApiClient = class {
@@ -3696,16 +3901,9 @@ var ZapierApiClient = class {
3696
3901
  }
3697
3902
  // Helper to get a token from the different places it could be gotten
3698
3903
  async getAuthToken() {
3699
- if (this.options.token) {
3700
- return this.options.token;
3701
- }
3702
- if (this.options.getToken) {
3703
- const token = await this.options.getToken();
3704
- if (token) {
3705
- return token;
3706
- }
3707
- }
3708
- return getTokenFromEnvOrConfig({
3904
+ return resolveAuthToken({
3905
+ token: this.options.token,
3906
+ getToken: this.options.getToken,
3709
3907
  onEvent: this.options.onEvent,
3710
3908
  fetch: this.options.fetch,
3711
3909
  baseUrl: this.options.baseUrl,
@@ -3808,14 +4006,6 @@ var ZapierApiClient = class {
3808
4006
  }
3809
4007
  return void 0;
3810
4008
  }
3811
- // Helper to check if a path config has a handler override
3812
- hasHandlerOverride(pathConfig2) {
3813
- return pathConfig2 !== void 0 && "handlerOverride" in pathConfig2 && typeof pathConfig2.handlerOverride === "function";
3814
- }
3815
- // Helper to check if a path config is a standard path config
3816
- isStandardPathConfig(pathConfig2) {
3817
- return pathConfig2 !== void 0 && !this.hasHandlerOverride(pathConfig2);
3818
- }
3819
4009
  // Helper to parse API error response
3820
4010
  parseErrorResponse(errorInfo) {
3821
4011
  const fallbackMessage = `HTTP ${errorInfo.status}: ${errorInfo.statusText}`;
@@ -3867,8 +4057,10 @@ var ZapierApiClient = class {
3867
4057
  pathConfig: config
3868
4058
  };
3869
4059
  }
4060
+ const baseUrl = new URL(this.options.baseUrl);
4061
+ const fullPath = baseUrl.pathname.replace(/\/$/, "") + path;
3870
4062
  return {
3871
- url: new URL(path, this.options.baseUrl),
4063
+ url: new URL(fullPath, baseUrl.origin),
3872
4064
  pathConfig: config
3873
4065
  };
3874
4066
  }
@@ -3887,7 +4079,7 @@ var ZapierApiClient = class {
3887
4079
  const headers = new Headers(options.headers ?? {});
3888
4080
  const authToken = await this.getAuthToken();
3889
4081
  if (authToken) {
3890
- const authHeaderName = this.isStandardPathConfig(pathConfig2) && pathConfig2.authHeader ? pathConfig2.authHeader : "Authorization";
4082
+ const authHeaderName = pathConfig2 && pathConfig2.authHeader ? pathConfig2.authHeader : "Authorization";
3891
4083
  headers.set(authHeaderName, getAuthorizationHeader(authToken));
3892
4084
  }
3893
4085
  if (options.authRequired) {
@@ -3901,10 +4093,14 @@ var ZapierApiClient = class {
3901
4093
  }
3902
4094
  // Helper to perform HTTP requests with JSON handling
3903
4095
  async fetchJson(method, path, data, options = {}) {
3904
- const { pathConfig: pathConfig2 } = this.buildUrl(path, options.searchParams);
3905
- if (this.hasHandlerOverride(pathConfig2)) {
3906
- const handlerRequest = method === "GET" ? options.searchParams : data;
3907
- return pathConfig2.handlerOverride({
4096
+ const routeMatch = matchRoute(method, path);
4097
+ if (routeMatch) {
4098
+ const handlerRequest = {
4099
+ ...typeof data === "object" ? data : {},
4100
+ ...options.searchParams,
4101
+ ...routeMatch.params
4102
+ };
4103
+ return routeMatch.handler({
3908
4104
  request: handlerRequest,
3909
4105
  deps: {
3910
4106
  httpClient: this
@@ -4573,7 +4769,7 @@ function getCpuTime() {
4573
4769
 
4574
4770
  // package.json
4575
4771
  var package_default = {
4576
- version: "0.15.3"};
4772
+ version: "0.15.8"};
4577
4773
 
4578
4774
  // src/plugins/eventEmission/builders.ts
4579
4775
  function createBaseEvent(context = {}) {
@@ -4644,17 +4840,26 @@ function buildErrorEventWithContext(data, context = {}) {
4644
4840
  }
4645
4841
 
4646
4842
  // src/plugins/eventEmission/index.ts
4843
+ var TELEMETRY_EMIT_TIMEOUT_MS = 300;
4647
4844
  var APPLICATION_LIFECYCLE_EVENT_SUBJECT = "platform.sdk.ApplicationLifecycleEvent";
4648
4845
  var ERROR_OCCURRED_EVENT_SUBJECT = "platform.sdk.ErrorOccurredEvent";
4649
4846
  var transportStates = /* @__PURE__ */ new WeakMap();
4650
- async function silentEmit(transport, subject, event) {
4847
+ async function silentEmit(transport, subject, event, userContextPromise) {
4651
4848
  try {
4652
4849
  let state = transportStates.get(transport);
4653
4850
  if (!state) {
4654
4851
  state = { hasWorked: false, hasLoggedFailure: false };
4655
4852
  transportStates.set(transport, state);
4656
4853
  }
4657
- transport.emit(subject, event).then(() => {
4854
+ let enrichedEvent = event;
4855
+ if (userContextPromise) {
4856
+ try {
4857
+ const userContext = await userContextPromise;
4858
+ enrichedEvent = Object.assign({}, event, userContext);
4859
+ } catch {
4860
+ }
4861
+ }
4862
+ transport.emit(subject, enrichedEvent).then(() => {
4658
4863
  state.hasWorked = true;
4659
4864
  }).catch((error) => {
4660
4865
  if (!state.hasWorked && !state.hasLoggedFailure) {
@@ -4702,6 +4907,24 @@ var eventEmissionPlugin = ({ context }) => {
4702
4907
  )
4703
4908
  )
4704
4909
  };
4910
+ const getUserContext = (async () => {
4911
+ try {
4912
+ const token = await resolveAuthToken({
4913
+ token: context.options.token,
4914
+ getToken: context.options.getToken,
4915
+ baseUrl: context.options.baseUrl,
4916
+ authBaseUrl: context.options.authBaseUrl,
4917
+ authClientId: context.options.authClientId,
4918
+ onEvent: context.options.onEvent,
4919
+ fetch: context.options.fetch
4920
+ });
4921
+ if (token) {
4922
+ return extractUserIdsFromJwt(token);
4923
+ }
4924
+ } catch {
4925
+ }
4926
+ return { customuser_id: null, account_id: null };
4927
+ })();
4705
4928
  const startupTime = Date.now();
4706
4929
  let shutdownStartTime = null;
4707
4930
  if (!config.enabled) {
@@ -4712,7 +4935,7 @@ var eventEmissionPlugin = ({ context }) => {
4712
4935
  config,
4713
4936
  emit: () => {
4714
4937
  },
4715
- createBaseEvent: () => ({
4938
+ createBaseEvent: async () => ({
4716
4939
  event_id: generateEventId(),
4717
4940
  timestamp_ms: getCurrentTimestamp(),
4718
4941
  release_id: getReleaseId(),
@@ -4732,21 +4955,34 @@ var eventEmissionPlugin = ({ context }) => {
4732
4955
  } catch {
4733
4956
  transport = createTransport({ type: "noop" });
4734
4957
  }
4735
- const createBaseEventHelper = () => ({
4736
- event_id: generateEventId(),
4737
- timestamp_ms: getCurrentTimestamp(),
4738
- release_id: getReleaseId(),
4739
- customuser_id: null,
4740
- account_id: null,
4741
- identity_id: null,
4742
- visitor_id: null,
4743
- correlation_id: null
4744
- });
4958
+ const createBaseEventHelper = async () => {
4959
+ const baseEvent = {
4960
+ event_id: generateEventId(),
4961
+ timestamp_ms: getCurrentTimestamp(),
4962
+ release_id: getReleaseId(),
4963
+ customuser_id: null,
4964
+ account_id: null,
4965
+ identity_id: null,
4966
+ visitor_id: null,
4967
+ correlation_id: null
4968
+ };
4969
+ try {
4970
+ const userContext = await getUserContext;
4971
+ return { ...baseEvent, ...userContext };
4972
+ } catch {
4973
+ return baseEvent;
4974
+ }
4975
+ };
4745
4976
  if (config.enabled) {
4746
4977
  const startupEvent = buildApplicationLifecycleEvent({
4747
4978
  lifecycle_event_type: "startup"
4748
4979
  });
4749
- silentEmit(transport, APPLICATION_LIFECYCLE_EVENT_SUBJECT, startupEvent);
4980
+ silentEmit(
4981
+ transport,
4982
+ APPLICATION_LIFECYCLE_EVENT_SUBJECT,
4983
+ startupEvent,
4984
+ getUserContext
4985
+ );
4750
4986
  if (typeof process?.on === "function") {
4751
4987
  process.on("exit", (code) => {
4752
4988
  const uptime = Date.now() - startupTime;
@@ -4758,10 +4994,15 @@ var eventEmissionPlugin = ({ context }) => {
4758
4994
  is_graceful_shutdown: code === 0,
4759
4995
  shutdown_duration_ms: shutdownDuration
4760
4996
  });
4761
- silentEmit(transport, APPLICATION_LIFECYCLE_EVENT_SUBJECT, exitEvent);
4997
+ silentEmit(
4998
+ transport,
4999
+ APPLICATION_LIFECYCLE_EVENT_SUBJECT,
5000
+ exitEvent,
5001
+ getUserContext
5002
+ );
4762
5003
  });
4763
5004
  process.on("uncaughtException", async (error) => {
4764
- const errorEvent = buildErrorEventWithContext({
5005
+ let errorEvent = buildErrorEventWithContext({
4765
5006
  error_message: error.message || "Unknown error",
4766
5007
  error_type: "UncaughtException",
4767
5008
  error_stack_trace: error.stack || null,
@@ -4770,10 +5011,17 @@ var eventEmissionPlugin = ({ context }) => {
4770
5011
  is_recoverable: false,
4771
5012
  execution_start_time: startupTime
4772
5013
  });
5014
+ try {
5015
+ const userContext = await getUserContext;
5016
+ errorEvent = { ...errorEvent, ...userContext };
5017
+ } catch {
5018
+ }
4773
5019
  try {
4774
5020
  await Promise.race([
4775
5021
  transport.emit(ERROR_OCCURRED_EVENT_SUBJECT, errorEvent),
4776
- new Promise((resolve2) => setTimeout(resolve2, 300))
5022
+ new Promise(
5023
+ (resolve2) => setTimeout(resolve2, TELEMETRY_EMIT_TIMEOUT_MS)
5024
+ )
4777
5025
  ]);
4778
5026
  } catch {
4779
5027
  }
@@ -4783,7 +5031,7 @@ var eventEmissionPlugin = ({ context }) => {
4783
5031
  async (reason, promise) => {
4784
5032
  const errorMessage = reason instanceof Error ? reason.message : typeof reason === "string" ? reason : "Unhandled promise rejection";
4785
5033
  const errorStack = reason instanceof Error ? reason.stack : null;
4786
- const errorEvent = buildErrorEventWithContext({
5034
+ let errorEvent = buildErrorEventWithContext({
4787
5035
  error_message: errorMessage,
4788
5036
  error_type: "UnhandledRejection",
4789
5037
  error_stack_trace: errorStack,
@@ -4795,10 +5043,17 @@ var eventEmissionPlugin = ({ context }) => {
4795
5043
  promise: String(promise)
4796
5044
  }
4797
5045
  });
5046
+ try {
5047
+ const userContext = await getUserContext;
5048
+ errorEvent = { ...errorEvent, ...userContext };
5049
+ } catch {
5050
+ }
4798
5051
  try {
4799
5052
  await Promise.race([
4800
5053
  transport.emit(ERROR_OCCURRED_EVENT_SUBJECT, errorEvent),
4801
- new Promise((resolve2) => setTimeout(resolve2, 300))
5054
+ new Promise(
5055
+ (resolve2) => setTimeout(resolve2, TELEMETRY_EMIT_TIMEOUT_MS)
5056
+ )
4802
5057
  ]);
4803
5058
  } catch {
4804
5059
  }
@@ -4807,16 +5062,23 @@ var eventEmissionPlugin = ({ context }) => {
4807
5062
  const handleSignal = async (signal) => {
4808
5063
  shutdownStartTime = Date.now();
4809
5064
  const uptime = Date.now() - startupTime;
4810
- const signalEvent = buildApplicationLifecycleEvent({
5065
+ let signalEvent = buildApplicationLifecycleEvent({
4811
5066
  lifecycle_event_type: "signal_termination",
4812
5067
  signal_name: signal,
4813
5068
  uptime_ms: uptime,
4814
5069
  is_graceful_shutdown: true
4815
5070
  });
5071
+ try {
5072
+ const userContext = await getUserContext;
5073
+ signalEvent = { ...signalEvent, ...userContext };
5074
+ } catch {
5075
+ }
4816
5076
  try {
4817
5077
  await Promise.race([
4818
5078
  transport.emit(APPLICATION_LIFECYCLE_EVENT_SUBJECT, signalEvent),
4819
- new Promise((resolve2) => setTimeout(resolve2, 300))
5079
+ new Promise(
5080
+ (resolve2) => setTimeout(resolve2, TELEMETRY_EMIT_TIMEOUT_MS)
5081
+ )
4820
5082
  ]);
4821
5083
  } catch {
4822
5084
  }
@@ -4832,7 +5094,7 @@ var eventEmissionPlugin = ({ context }) => {
4832
5094
  transport,
4833
5095
  config,
4834
5096
  emit: (subject, event) => {
4835
- silentEmit(transport, subject, event);
5097
+ silentEmit(transport, subject, event, getUserContext);
4836
5098
  },
4837
5099
  createBaseEvent: createBaseEventHelper
4838
5100
  }
@@ -4895,4 +5157,4 @@ function createZapierSdk(options = {}) {
4895
5157
  return createZapierSdkWithoutRegistry(options).addPlugin(registryPlugin);
4896
5158
  }
4897
5159
 
4898
- export { ActionKeyPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AuthenticationIdPropertySchema, DEFAULT_CONFIG_PATH, DebugPropertySchema, InputsPropertySchema, LimitPropertySchema, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, RelayFetchSchema, RelayRequestSchema, ZAPIER_BASE_URL, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierError, ZapierNotFoundError, ZapierResourceNotFoundError, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, apiPlugin, appKeyResolver, appsPlugin, authenticationIdGenericResolver, authenticationIdResolver, batch, buildApplicationLifecycleEvent, buildErrorEvent, buildErrorEventWithContext, createBaseEvent, createFunction, createSdk, createZapierSdk, createZapierSdkWithoutRegistry, fetchPlugin, findFirstAuthenticationPlugin, findManifestEntry, findUniqueAuthenticationPlugin, formatErrorMessage, generateEventId, getActionPlugin, getAppPlugin, getAuthenticationPlugin, getCiPlatform, getCpuTime, getCurrentTimestamp, getMemoryUsage, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getReleaseId, getTokenFromCliLogin, getTokenFromEnv, getTokenFromEnvOrConfig, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, isCi, isPositional, listActionsPlugin, listAppsPlugin, listAuthenticationsPlugin, listInputFieldsPlugin, manifestPlugin, readManifestFromFile, registryPlugin, requestPlugin, runActionPlugin, toSnakeCase, toTitleCase };
5160
+ export { ActionKeyPropertySchema, ActionTypePropertySchema, AppKeyPropertySchema, AuthenticationIdPropertySchema, DEFAULT_CONFIG_PATH, DebugPropertySchema, InputsPropertySchema, LimitPropertySchema, MAX_PAGE_LIMIT, OffsetPropertySchema, OutputPropertySchema, ParamsPropertySchema, RelayFetchSchema, RelayRequestSchema, ZAPIER_BASE_URL, ZapierActionError, ZapierApiError, ZapierAppNotFoundError, ZapierAuthenticationError, ZapierBundleError, ZapierConfigurationError, ZapierError, ZapierNotFoundError, ZapierResourceNotFoundError, ZapierTimeoutError, ZapierUnknownError, ZapierValidationError, actionKeyResolver, actionTypeResolver, apiPlugin, appKeyResolver, appsPlugin, authenticationIdGenericResolver, authenticationIdResolver, batch, buildApplicationLifecycleEvent, buildErrorEvent, buildErrorEventWithContext, createBaseEvent, createFunction, createSdk, createZapierSdk, createZapierSdkWithoutRegistry, fetchPlugin, findFirstAuthenticationPlugin, findManifestEntry, findUniqueAuthenticationPlugin, formatErrorMessage, generateEventId, getActionPlugin, getAppPlugin, getAuthenticationPlugin, getCiPlatform, getCpuTime, getCurrentTimestamp, getMemoryUsage, getOsInfo, getPlatformVersions, getPreferredManifestEntryKey, getProfilePlugin, getReleaseId, getTokenFromCliLogin, getTokenFromEnv, getTokenFromEnvOrConfig, inputFieldKeyResolver, inputsAllOptionalResolver, inputsResolver, isCi, isPositional, listActionsPlugin, listAppsPlugin, listAuthenticationsPlugin, listInputFieldsPlugin, manifestPlugin, readManifestFromFile, registryPlugin, requestPlugin, resolveAuthToken, runActionPlugin, toSnakeCase, toTitleCase };
@@ -16,7 +16,7 @@ export interface EventEmissionContext {
16
16
  transport: EventTransport;
17
17
  config: EventEmissionConfig;
18
18
  emit<T extends any>(subject: string, event: T): void;
19
- createBaseEvent(): BaseEvent;
19
+ createBaseEvent(): Promise<BaseEvent>;
20
20
  };
21
21
  }
22
22
  export interface EventEmissionProvides {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/plugins/eventEmission/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAUnE,MAAM,WAAW,mBAAmB;IAClC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,eAAe,CAAC;CAC7B;AAGD,MAAM,WAAW,oBAAoB;IACnC,aAAa,EAAE;QACb,SAAS,EAAE,cAAc,CAAC;QAC1B,MAAM,EAAE,mBAAmB,CAAC;QAE5B,IAAI,CAAC,CAAC,SAAS,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,IAAI,CAAC;QAErD,eAAe,IAAI,SAAS,CAAC;KAC9B,CAAC;CACH;AAED,MAAM,WAAW,qBAAqB;IACpC,OAAO,EAAE,oBAAoB,CAAC;CAC/B;AA+ED,eAAO,MAAM,mBAAmB,EAAE,MAAM,CACtC,EAAE,EACF;IACE,OAAO,EAAE;QACP,aAAa,CAAC,EAAE,mBAAmB,CAAC;QACpC,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,CAAC;CACH,EACD,qBAAqB,CAoMtB,CAAC;AAGF,YAAY,EACV,YAAY,EACZ,6BAA6B,EAC7B,sBAAsB,GACvB,MAAM,SAAS,CAAC;AACjB,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,EAC1B,eAAe,EACf,eAAe,GAChB,MAAM,YAAY,CAAC;AACpB,YAAY,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAC9D,cAAc,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/plugins/eventEmission/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAgBnE,MAAM,WAAW,mBAAmB;IAClC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,eAAe,CAAC;CAC7B;AAGD,MAAM,WAAW,oBAAoB;IACnC,aAAa,EAAE;QACb,SAAS,EAAE,cAAc,CAAC;QAC1B,MAAM,EAAE,mBAAmB,CAAC;QAE5B,IAAI,CAAC,CAAC,SAAS,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,IAAI,CAAC;QAErD,eAAe,IAAI,OAAO,CAAC,SAAS,CAAC,CAAC;KACvC,CAAC;CACH;AAED,MAAM,WAAW,qBAAqB;IACpC,OAAO,EAAE,oBAAoB,CAAC;CAC/B;AA4FD,eAAO,MAAM,mBAAmB,EAAE,MAAM,CACtC,EAAE,EACF;IACE,OAAO,EAAE;QACP,aAAa,CAAC,EAAE,mBAAmB,CAAC;QACpC,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,CAAC;CACH,EACD,qBAAqB,CA6QtB,CAAC;AAGF,YAAY,EACV,YAAY,EACZ,6BAA6B,EAC7B,sBAAsB,GACvB,MAAM,SAAS,CAAC;AACjB,OAAO,EACL,8BAA8B,EAC9B,0BAA0B,EAC1B,eAAe,EACf,eAAe,GAChB,MAAM,YAAY,CAAC;AACpB,YAAY,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAC9D,cAAc,SAAS,CAAC"}