@workos-inc/node 12.2.0 → 12.3.0

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.
@@ -256,41 +256,42 @@ var FetchHttpClient = class FetchHttpClient extends HttpClient {
256
256
  }
257
257
  async get(path, options) {
258
258
  const resourceURL = HttpClient.getResourceURL(this.baseURL, path, options.params);
259
- return await this.fetchRequestWithRetry(resourceURL, "GET", null, options.headers, options.maxRetries);
259
+ return await this.fetchRequestWithRetry(resourceURL, "GET", null, options.headers, options.maxRetries, options.signal);
260
260
  }
261
261
  async post(path, entity, options) {
262
262
  const resourceURL = HttpClient.getResourceURL(this.baseURL, path, options.params);
263
263
  return await this.fetchRequestWithRetry(resourceURL, "POST", HttpClient.getBody(entity), {
264
264
  ...HttpClient.getContentTypeHeader(entity),
265
265
  ...options.headers
266
- }, options.maxRetries);
266
+ }, options.maxRetries, options.signal);
267
267
  }
268
268
  async put(path, entity, options) {
269
269
  const resourceURL = HttpClient.getResourceURL(this.baseURL, path, options.params);
270
270
  return await this.fetchRequestWithRetry(resourceURL, "PUT", HttpClient.getBody(entity), {
271
271
  ...HttpClient.getContentTypeHeader(entity),
272
272
  ...options.headers
273
- }, options.maxRetries);
273
+ }, options.maxRetries, options.signal);
274
274
  }
275
275
  async patch(path, entity, options) {
276
276
  const resourceURL = HttpClient.getResourceURL(this.baseURL, path, options.params);
277
277
  return await this.fetchRequestWithRetry(resourceURL, "PATCH", HttpClient.getBody(entity), {
278
278
  ...HttpClient.getContentTypeHeader(entity),
279
279
  ...options.headers
280
- }, options.maxRetries);
280
+ }, options.maxRetries, options.signal);
281
281
  }
282
282
  async delete(path, options) {
283
283
  const resourceURL = HttpClient.getResourceURL(this.baseURL, path, options.params);
284
- return await this.fetchRequestWithRetry(resourceURL, "DELETE", null, options.headers, options.maxRetries);
284
+ return await this.fetchRequestWithRetry(resourceURL, "DELETE", null, options.headers, options.maxRetries, options.signal);
285
285
  }
286
286
  async deleteWithBody(path, entity, options) {
287
287
  const resourceURL = HttpClient.getResourceURL(this.baseURL, path, options.params);
288
288
  return await this.fetchRequestWithRetry(resourceURL, "DELETE", HttpClient.getBody(entity), {
289
289
  ...HttpClient.getContentTypeHeader(entity),
290
290
  ...options.headers
291
- }, options.maxRetries);
291
+ }, options.maxRetries, options.signal);
292
292
  }
293
- async fetchRequest(url, method, body, headers) {
293
+ async fetchRequest(url, method, body, headers, signal) {
294
+ signal?.throwIfAborted();
294
295
  const requestBody = body || (method === "POST" || method === "PUT" || method === "PATCH" ? "" : void 0);
295
296
  const { "User-Agent": userAgent } = this.options?.headers || {};
296
297
  const timeout = this.options?.timeout ?? DEFAULT_FETCH_TIMEOUT;
@@ -298,7 +299,13 @@ var FetchHttpClient = class FetchHttpClient extends HttpClient {
298
299
  const timeoutId = setTimeout(() => {
299
300
  abortController.abort();
300
301
  }, timeout);
301
- const timeoutError = (responseHeaders) => new HttpClientError({
302
+ const abortRequest = () => abortController.abort();
303
+ signal?.addEventListener("abort", abortRequest, { once: true });
304
+ const release = () => {
305
+ clearTimeout(timeoutId);
306
+ signal?.removeEventListener("abort", abortRequest);
307
+ };
308
+ const abortError = (responseHeaders) => signal?.aborted ? signal.reason : new HttpClientError({
302
309
  message: `Request timeout after ${timeout}ms`,
303
310
  response: {
304
311
  status: 408,
@@ -307,6 +314,7 @@ var FetchHttpClient = class FetchHttpClient extends HttpClient {
307
314
  }
308
315
  });
309
316
  let res;
317
+ let redirected = false;
310
318
  try {
311
319
  res = await this._fetchFn(url, {
312
320
  method,
@@ -318,12 +326,27 @@ var FetchHttpClient = class FetchHttpClient extends HttpClient {
318
326
  "User-Agent": (userAgent || "workos-node").toString()
319
327
  },
320
328
  body: requestBody,
321
- signal: abortController.signal
329
+ signal: abortController.signal,
330
+ redirect: "manual"
322
331
  });
332
+ if (res.status >= 300 && res.status < 400 || res.type === "opaqueredirect") {
333
+ clearTimeout(timeoutId);
334
+ redirected = true;
335
+ const location = res.headers.get("Location");
336
+ const message = `WorkOS API responded with ${res.type === "opaqueredirect" ? "an opaque redirect" : `a redirect (${res.status}${location ? ` to ${location}` : ""})`}. Redirects are not followed; check the apiHostname, port and https options.`;
337
+ throw new HttpClientError({
338
+ message,
339
+ response: {
340
+ status: res.status,
341
+ headers: res.headers,
342
+ data: { message }
343
+ }
344
+ });
345
+ }
323
346
  if (!res.ok) {
324
347
  const requestID = res.headers.get("X-Request-ID") ?? "";
325
348
  const rawBody = await res.text();
326
- clearTimeout(timeoutId);
349
+ release();
327
350
  let responseJson;
328
351
  try {
329
352
  responseJson = JSON.parse(rawBody);
@@ -351,37 +374,41 @@ var FetchHttpClient = class FetchHttpClient extends HttpClient {
351
374
  try {
352
375
  return await response.text();
353
376
  } catch (error) {
354
- throw abortController.signal.aborted ? timeoutError(response.headers) : error;
377
+ throw abortController.signal.aborted ? abortError(response.headers) : error;
355
378
  } finally {
356
- clearTimeout(timeoutId);
379
+ release();
357
380
  }
358
381
  })();
359
382
  rawBody.catch(() => void 0);
360
383
  return new FetchHttpClientResponse(res, rawBody);
361
384
  } catch (error) {
362
- clearTimeout(timeoutId);
363
- if (abortController.signal.aborted) throw timeoutError(res?.headers);
385
+ release();
386
+ if (abortController.signal.aborted) throw abortError(res?.headers);
364
387
  throw error;
388
+ } finally {
389
+ if (redirected) abortController.abort();
365
390
  }
366
391
  }
367
- async fetchRequestWithRetry(url, method, body, headers, maxRetries) {
392
+ async fetchRequestWithRetry(url, method, body, headers, maxRetries, signal) {
368
393
  const maxRetryAttempts = maxRetries ?? this.MAX_RETRY_ATTEMPTS;
369
394
  const requestHeaders = FetchHttpClient.withIdempotencyKey(method, headers, maxRetryAttempts);
370
395
  let response;
371
396
  let retryAttempts = 1;
372
397
  const makeRequest = async () => {
373
398
  let requestError = null;
399
+ let failed = false;
374
400
  try {
375
- response = await this.fetchRequest(url, method, body, requestHeaders);
401
+ response = await this.fetchRequest(url, method, body, requestHeaders, signal);
376
402
  } catch (e) {
377
403
  requestError = e;
404
+ failed = true;
378
405
  }
379
- if (this.shouldRetryRequest(requestError, retryAttempts, maxRetryAttempts)) {
406
+ if (!signal?.aborted && this.shouldRetryRequest(requestError, retryAttempts, maxRetryAttempts)) {
380
407
  retryAttempts++;
381
408
  await this.sleep(retryAttempts, FetchHttpClient.getRetryAfterMs(requestError));
382
409
  return makeRequest();
383
410
  }
384
- if (requestError != null) throw requestError;
411
+ if (failed) throw requestError;
385
412
  return response;
386
413
  };
387
414
  return makeRequest();
@@ -944,6 +971,56 @@ const deserializeAuthenticationResponse = (authenticationResponse) => {
944
971
  };
945
972
  };
946
973
  //#endregion
974
+ //#region src/connect/serializers/connect-application-redirect-uri.serializer.ts
975
+ const deserializeConnectApplicationRedirectUri = (response) => ({
976
+ uri: response.uri,
977
+ default: response.default
978
+ });
979
+ //#endregion
980
+ //#region src/connect/serializers/connect-application.serializer.ts
981
+ const deserializeConnectApplication = (response) => {
982
+ switch (response.application_type) {
983
+ case "oauth": return {
984
+ object: response.object,
985
+ id: response.id,
986
+ clientId: response.client_id,
987
+ description: response.description,
988
+ name: response.name,
989
+ scopes: response.scopes,
990
+ createdAt: new Date(response.created_at),
991
+ updatedAt: new Date(response.updated_at),
992
+ applicationType: "oauth",
993
+ redirectUris: response.redirect_uris.map(deserializeConnectApplicationRedirectUri),
994
+ usesPkce: response.uses_pkce,
995
+ isFirstParty: response.is_first_party,
996
+ wasDynamicallyRegistered: response.was_dynamically_registered,
997
+ organizationId: response.organization_id
998
+ };
999
+ case "m2m": return {
1000
+ object: response.object,
1001
+ id: response.id,
1002
+ clientId: response.client_id,
1003
+ description: response.description,
1004
+ name: response.name,
1005
+ scopes: response.scopes,
1006
+ createdAt: new Date(response.created_at),
1007
+ updatedAt: new Date(response.updated_at),
1008
+ applicationType: "m2m",
1009
+ organizationId: response.organization_id
1010
+ };
1011
+ default: throw new Error(`Unknown application_type: ${response.application_type}`);
1012
+ }
1013
+ };
1014
+ //#endregion
1015
+ //#region src/user-management/serializers/authorized-connect-application.serializer.ts
1016
+ const deserializeAuthorizedConnectApplication = (response) => ({
1017
+ object: response.object,
1018
+ id: response.id,
1019
+ grantedScopes: response.granted_scopes,
1020
+ oauthResource: response.oauth_resource,
1021
+ application: deserializeConnectApplication(response.application)
1022
+ });
1023
+ //#endregion
947
1024
  //#region src/user-management/serializers/create-magic-auth-options.serializer.ts
948
1025
  const serializeCreateMagicAuthOptions = (options) => ({
949
1026
  email: options.email,
@@ -1870,6 +1947,92 @@ const deserializeFeatureFlag = (featureFlag) => ({
1870
1947
  updatedAt: new Date(featureFlag.updated_at)
1871
1948
  });
1872
1949
  //#endregion
1950
+ //#region src/feature-flags/serializers/flag-rule.serializer.ts
1951
+ const deserializeFlagRule = (rule) => ({
1952
+ object: rule.object,
1953
+ id: rule.id,
1954
+ flagId: rule.flag_id,
1955
+ flagSlug: rule.flag_slug,
1956
+ environmentId: rule.environment_id,
1957
+ targetType: rule.target_type,
1958
+ position: rule.position,
1959
+ valueType: rule.value_type,
1960
+ value: rule.value,
1961
+ createdAt: new Date(rule.created_at),
1962
+ updatedAt: new Date(rule.updated_at)
1963
+ });
1964
+ //#endregion
1965
+ //#region src/feature-flags/serializers/flag-target.serializer.ts
1966
+ const deserializeTargetFields = (target) => ({
1967
+ object: target.object,
1968
+ id: target.id,
1969
+ flagId: target.flag_id,
1970
+ flagSlug: target.flag_slug,
1971
+ environmentId: target.environment_id,
1972
+ targetType: target.target_type,
1973
+ targetId: target.target_id,
1974
+ createdAt: new Date(target.created_at),
1975
+ updatedAt: new Date(target.updated_at)
1976
+ });
1977
+ const deserializeFlagTarget = (target) => ({
1978
+ ...deserializeTargetFields(target),
1979
+ ruleId: target.rule_id
1980
+ });
1981
+ const deserializeFlagTargetResource = (target) => "rule_id" in target ? deserializeFlagTarget(target) : {
1982
+ ...deserializeTargetFields(target),
1983
+ valueType: target.value_type,
1984
+ value: target.value
1985
+ };
1986
+ //#endregion
1987
+ //#region src/common/serializers/feature-flag-event.serializer.ts
1988
+ const deserializeFeatureFlagOwner = (owner) => owner === null ? null : {
1989
+ email: owner.email,
1990
+ firstName: owner.first_name,
1991
+ lastName: owner.last_name
1992
+ };
1993
+ const deserializeFeatureFlagEventData = (flag) => ({
1994
+ object: flag.object,
1995
+ id: flag.id,
1996
+ environmentId: flag.environment_id,
1997
+ slug: flag.slug,
1998
+ name: flag.name,
1999
+ description: flag.description,
2000
+ owner: deserializeFeatureFlagOwner(flag.owner),
2001
+ tags: flag.tags,
2002
+ enabled: flag.enabled,
2003
+ defaultValue: flag.default_value,
2004
+ createdAt: new Date(flag.created_at),
2005
+ updatedAt: new Date(flag.updated_at)
2006
+ });
2007
+ const deserializeFeatureFlagRuleContext = (context) => ({
2008
+ clientId: context.client_id,
2009
+ ...context.actor === void 0 ? {} : { actor: context.actor }
2010
+ });
2011
+ const deserializeFeatureFlagRuleUpdatedContext = (context) => {
2012
+ const previous = context.previous_attributes;
2013
+ const data = previous?.data;
2014
+ return {
2015
+ ...deserializeFeatureFlagRuleContext(context),
2016
+ ...previous === void 0 ? {} : { previousAttributes: { ...data === void 0 ? {} : { data: data.value === void 0 ? {} : { value: data.value } } } }
2017
+ };
2018
+ };
2019
+ const deserializeFeatureFlagUpdatedContext = (context) => {
2020
+ const previous = context.previous_attributes;
2021
+ const data = previous?.data;
2022
+ return {
2023
+ clientId: context.client_id,
2024
+ actor: context.actor,
2025
+ ...previous === void 0 ? {} : { previousAttributes: { ...data === void 0 ? {} : { data: {
2026
+ ...data.name === void 0 ? {} : { name: data.name },
2027
+ ...data.description === void 0 ? {} : { description: data.description },
2028
+ ...data.tags === void 0 ? {} : { tags: data.tags },
2029
+ ...data.owner === void 0 ? {} : { owner: deserializeFeatureFlagOwner(data.owner) },
2030
+ ...data.enabled === void 0 ? {} : { enabled: data.enabled },
2031
+ ...data.default_value === void 0 ? {} : { defaultValue: data.default_value }
2032
+ } } } }
2033
+ };
2034
+ };
2035
+ //#endregion
1873
2036
  //#region src/groups/serializers/create-group.serializer.ts
1874
2037
  const serializeCreateGroup = (model) => ({
1875
2038
  name: model.name,
@@ -2058,7 +2221,8 @@ const deserializeEvent = (event) => {
2058
2221
  return {
2059
2222
  ...eventBase,
2060
2223
  event: unknownEvent.event,
2061
- data: unknownEvent.data
2224
+ data: unknownEvent.data,
2225
+ context: unknownEvent.context
2062
2226
  };
2063
2227
  };
2064
2228
  function deserializeKnownEvent(event, eventBase) {
@@ -2289,6 +2453,45 @@ function deserializeKnownEvent(event, eventBase) {
2289
2453
  event: event.event,
2290
2454
  data: deserializeApiKey(event.data)
2291
2455
  };
2456
+ case "feature_flags.flag.created":
2457
+ case "feature_flags.flag.deleted": return {
2458
+ ...eventBase,
2459
+ event: event.event,
2460
+ data: deserializeFeatureFlagEventData(event.data),
2461
+ context: {
2462
+ clientId: event.context.client_id,
2463
+ actor: event.context.actor
2464
+ }
2465
+ };
2466
+ case "feature_flags.flag.updated": return {
2467
+ ...eventBase,
2468
+ event: event.event,
2469
+ data: deserializeFeatureFlagEventData(event.data),
2470
+ context: deserializeFeatureFlagUpdatedContext(event.context)
2471
+ };
2472
+ case "feature_flags.flag_rule.created":
2473
+ case "feature_flags.flag_rule.deleted": return {
2474
+ ...eventBase,
2475
+ event: event.event,
2476
+ data: deserializeFlagRule(event.data),
2477
+ context: deserializeFeatureFlagRuleContext(event.context)
2478
+ };
2479
+ case "feature_flags.flag_rule.updated": return {
2480
+ ...eventBase,
2481
+ event: event.event,
2482
+ data: deserializeFlagRule(event.data),
2483
+ context: deserializeFeatureFlagRuleUpdatedContext(event.context)
2484
+ };
2485
+ case "feature_flags.flag_target.created":
2486
+ case "feature_flags.flag_target.deleted": return {
2487
+ ...eventBase,
2488
+ event: event.event,
2489
+ data: deserializeFlagTargetResource(event.data),
2490
+ context: {
2491
+ clientId: event.context.client_id,
2492
+ actor: event.context.actor
2493
+ }
2494
+ };
2292
2495
  case "flag.created":
2293
2496
  case "flag.updated":
2294
2497
  case "flag.deleted":
@@ -3152,7 +3355,8 @@ var Agents = class {
3152
3355
  function serializeCreateOrganizationApiKeyOptions(options) {
3153
3356
  return {
3154
3357
  name: options.name,
3155
- permissions: options.permissions
3358
+ permissions: options.permissions,
3359
+ expires_at: options.expiresAt?.toISOString()
3156
3360
  };
3157
3361
  }
3158
3362
  //#endregion
@@ -3241,7 +3445,7 @@ var ApiKeys = class {
3241
3445
  * @example
3242
3446
  * "org_01EHZNVPK3SFK441A1RGBFSHRT"
3243
3447
  *
3244
- * @param options - Object containing name.
3448
+ * @param options - Object containing name, permissions, and expiresAt.
3245
3449
  * @returns {Promise<ApiKeyWithValue>}
3246
3450
  * @throws {NotFoundException} 404
3247
3451
  * @throws {UnprocessableEntityException} 422
@@ -3265,47 +3469,6 @@ const deserializeTokenExchangeResponse = (response) => ({
3265
3469
  ...response.scope !== void 0 && { scope: response.scope }
3266
3470
  });
3267
3471
  //#endregion
3268
- //#region src/connect/serializers/connect-application-redirect-uri.serializer.ts
3269
- const deserializeConnectApplicationRedirectUri = (response) => ({
3270
- uri: response.uri,
3271
- default: response.default
3272
- });
3273
- //#endregion
3274
- //#region src/connect/serializers/connect-application.serializer.ts
3275
- const deserializeConnectApplication = (response) => {
3276
- switch (response.application_type) {
3277
- case "oauth": return {
3278
- object: response.object,
3279
- id: response.id,
3280
- clientId: response.client_id,
3281
- description: response.description,
3282
- name: response.name,
3283
- scopes: response.scopes,
3284
- createdAt: new Date(response.created_at),
3285
- updatedAt: new Date(response.updated_at),
3286
- applicationType: "oauth",
3287
- redirectUris: response.redirect_uris.map(deserializeConnectApplicationRedirectUri),
3288
- usesPkce: response.uses_pkce,
3289
- isFirstParty: response.is_first_party,
3290
- wasDynamicallyRegistered: response.was_dynamically_registered,
3291
- organizationId: response.organization_id
3292
- };
3293
- case "m2m": return {
3294
- object: response.object,
3295
- id: response.id,
3296
- clientId: response.client_id,
3297
- description: response.description,
3298
- name: response.name,
3299
- scopes: response.scopes,
3300
- createdAt: new Date(response.created_at),
3301
- updatedAt: new Date(response.updated_at),
3302
- applicationType: "m2m",
3303
- organizationId: response.organization_id
3304
- };
3305
- default: throw new Error(`Unknown application_type: ${response.application_type}`);
3306
- }
3307
- };
3308
- //#endregion
3309
3472
  //#region src/connect/serializers/application-credentials-list-item.serializer.ts
3310
3473
  const deserializeApplicationCredentialsListItem = (response) => ({
3311
3474
  object: response.object,
@@ -3693,6 +3856,18 @@ const serializeListDirectoriesOptions = (options) => {
3693
3856
  if (options.search !== void 0) wire.search = options.search;
3694
3857
  return wire;
3695
3858
  };
3859
+ const serializeListUsersInDirectoryOptions = (options) => {
3860
+ const wire = {
3861
+ limit: options.limit,
3862
+ before: options.before,
3863
+ after: options.after,
3864
+ order: options.order,
3865
+ group: options.group,
3866
+ email: options.email
3867
+ };
3868
+ if (options.idpId !== void 0) wire.idp_id = options.idpId;
3869
+ return wire;
3870
+ };
3696
3871
  var DirectorySync = class {
3697
3872
  workos;
3698
3873
  constructor(workos) {
@@ -3749,6 +3924,7 @@ var DirectorySync = class {
3749
3924
  * @throws {AuthorizationException} 403
3750
3925
  * @throws {NotFoundException} 404
3751
3926
  * @throws {UnprocessableEntityException} 422
3927
+ * @deprecated Use {@link DirectorySync.listDirectoryGroups} instead.
3752
3928
  */
3753
3929
  async listGroups(options) {
3754
3930
  const paginationOptions = options;
@@ -3764,6 +3940,7 @@ var DirectorySync = class {
3764
3940
  * @returns {Promise<DirectoryGroup>}
3765
3941
  * @throws {AuthorizationException} 403
3766
3942
  * @throws {NotFoundException} 404
3943
+ * @deprecated Use {@link DirectorySync.getDirectoryGroup} instead.
3767
3944
  */
3768
3945
  async getGroup(options) {
3769
3946
  const { id } = options;
@@ -3780,6 +3957,7 @@ var DirectorySync = class {
3780
3957
  * @throws {NotFoundException} 404
3781
3958
  * @throws {UnprocessableEntityException} 422
3782
3959
  * @throws {RateLimitExceededException} 429
3960
+ * @deprecated Use {@link DirectorySync.listDirectoryUsers} instead.
3783
3961
  */
3784
3962
  async listUsers(options) {
3785
3963
  return new AutoPaginatable(await fetchAndDeserialize(this.workos, "/directory_users", deserializeDirectoryUserWithGroups, options), (params) => fetchAndDeserialize(this.workos, "/directory_users", deserializeDirectoryUserWithGroups, params), options);
@@ -3794,12 +3972,92 @@ var DirectorySync = class {
3794
3972
  * @returns {Promise<DirectoryUserWithGroups<TCustomAttributes>>}
3795
3973
  * @throws {AuthorizationException} 403
3796
3974
  * @throws {NotFoundException} 404
3975
+ * @deprecated Use {@link DirectorySync.getDirectoryUser} instead.
3797
3976
  */
3798
3977
  async getUser(options) {
3799
3978
  const { id } = options;
3800
3979
  const { data } = await this.workos.get(`/directory_users/${encodeURIComponent(id)}`);
3801
3980
  return deserializeDirectoryUserWithGroups(data);
3802
3981
  }
3982
+ /**
3983
+ * List Users for a Directory
3984
+ *
3985
+ * Get a list of the Directory Users in a Directory, optionally filtered to the members of a Directory Group.
3986
+ * @param options - Pagination and filter options.
3987
+ * @param options.directoryId - Unique identifier of the Directory.
3988
+ * @example "directory_01ECAZ4NV9QMV47GW873HDCX74"
3989
+ * @param options.group - Filter Directory Users to the members of this Directory Group.
3990
+ * @example "directory_group_01E64QTDNS0EGJ0FMCVY9BWGZT"
3991
+ * @param options.idpId - Filter Directory Users by the identity provider's unique identifier.
3992
+ * @example "2836"
3993
+ * @param options.email - Filter Directory Users by their primary email address.
3994
+ * @example "jane.doe@example.com"
3995
+ * @returns {Promise<AutoPaginatable<DirectoryUser<TCustomAttributes>, PaginationOptions>>}
3996
+ * @throws {AuthorizationException} 403
3997
+ * @throws {NotFoundException} 404
3998
+ * @throws {UnprocessableEntityException} 422
3999
+ */
4000
+ async listDirectoryUsers(options) {
4001
+ const { directoryId, ...rest } = options;
4002
+ const endpoint = `/directories/${encodeURIComponent(directoryId)}/users`;
4003
+ const wire = serializeListUsersInDirectoryOptions(rest);
4004
+ return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializeDirectoryUser, wire), (params) => fetchAndDeserialize(this.workos, endpoint, deserializeDirectoryUser, params), wire);
4005
+ }
4006
+ /**
4007
+ * Get a User for a Directory
4008
+ *
4009
+ * Get the details of a Directory User in a Directory.
4010
+ * @param options - The request options.
4011
+ * @param options.directoryId - Unique identifier of the Directory.
4012
+ * @example "directory_01ECAZ4NV9QMV47GW873HDCX74"
4013
+ * @param options.userId - Unique identifier for the Directory User.
4014
+ * @example "directory_user_01E1JG7J09H96KYP8HM9B0G5SJ"
4015
+ * @returns {Promise<DirectoryUser<TCustomAttributes>>}
4016
+ * @throws {AuthorizationException} 403
4017
+ * @throws {NotFoundException} 404
4018
+ */
4019
+ async getDirectoryUser(options) {
4020
+ const { directoryId, userId } = options;
4021
+ const { data } = await this.workos.get(`/directories/${encodeURIComponent(directoryId)}/users/${encodeURIComponent(userId)}`);
4022
+ return deserializeDirectoryUser(data);
4023
+ }
4024
+ /**
4025
+ * List Groups for a Directory
4026
+ *
4027
+ * Get a list of the Directory Groups in a Directory, optionally filtered to the groups a Directory User belongs to.
4028
+ * @param options - Pagination and filter options.
4029
+ * @param options.directoryId - Unique identifier of the Directory.
4030
+ * @example "directory_01ECAZ4NV9QMV47GW873HDCX74"
4031
+ * @param options.user - Filter Directory Groups to those this Directory User belongs to.
4032
+ * @example "directory_user_01E1JG7J09H96KYP8HM9B0G5SJ"
4033
+ * @returns {Promise<AutoPaginatable<DirectoryGroup, PaginationOptions>>}
4034
+ * @throws {AuthorizationException} 403
4035
+ * @throws {NotFoundException} 404
4036
+ * @throws {UnprocessableEntityException} 422
4037
+ */
4038
+ async listDirectoryGroups(options) {
4039
+ const { directoryId, ...wire } = options;
4040
+ const endpoint = `/directories/${encodeURIComponent(directoryId)}/groups`;
4041
+ return new AutoPaginatable(await fetchAndDeserialize(this.workos, endpoint, deserializeDirectoryGroup, wire), (params) => fetchAndDeserialize(this.workos, endpoint, deserializeDirectoryGroup, params), wire);
4042
+ }
4043
+ /**
4044
+ * Get a Group for a Directory
4045
+ *
4046
+ * Get the details of a Directory Group in a Directory.
4047
+ * @param options - The request options.
4048
+ * @param options.directoryId - Unique identifier of the Directory.
4049
+ * @example "directory_01ECAZ4NV9QMV47GW873HDCX74"
4050
+ * @param options.groupId - Unique identifier for the Directory Group.
4051
+ * @example "directory_group_01E1JJS84MFPPQ3G655FHTKX6Z"
4052
+ * @returns {Promise<DirectoryGroup>}
4053
+ * @throws {AuthorizationException} 403
4054
+ * @throws {NotFoundException} 404
4055
+ */
4056
+ async getDirectoryGroup(options) {
4057
+ const { directoryId, groupId } = options;
4058
+ const { data } = await this.workos.get(`/directories/${encodeURIComponent(directoryId)}/groups/${encodeURIComponent(groupId)}`);
4059
+ return deserializeDirectoryGroup(data);
4060
+ }
3803
4061
  };
3804
4062
  //#endregion
3805
4063
  //#region src/events/serializers/list-event-options.serializer.ts
@@ -5439,14 +5697,16 @@ var AdminPortal = class {
5439
5697
  * Generate a Portal Link
5440
5698
  *
5441
5699
  * Generate a Portal Link scoped to an Organization.
5442
- * @param payload - Object containing organization.
5700
+ * @param payload - Object containing organization. Pass `externalUserId`
5701
+ * for every admin you may later need to deprovision; only links generated
5702
+ * with one can be revoked via `revokeLink`.
5443
5703
  * @returns {Promise<{ link: string; }>}
5444
5704
  * @throws {BadRequestException} 400
5445
5705
  * @throws 403 response from the API.
5446
5706
  * @throws {NotFoundException} 404
5447
5707
  * @throws {UnprocessableEntityException} 422
5448
5708
  */
5449
- async generateLink({ intent, organization, returnUrl, successUrl, intentOptions, itContactEmails }) {
5709
+ async generateLink({ intent, organization, returnUrl, successUrl, intentOptions, itContactEmails, externalUserId }) {
5450
5710
  const { data } = await this.workos.post("/portal/generate_link", {
5451
5711
  intent,
5452
5712
  organization,
@@ -5456,10 +5716,31 @@ var AdminPortal = class {
5456
5716
  bookmark_slug: intentOptions.sso.bookmarkSlug,
5457
5717
  provider_type: intentOptions.sso.providerType
5458
5718
  } } : void 0,
5459
- it_contact_emails: itContactEmails
5719
+ it_contact_emails: itContactEmails,
5720
+ external_user_id: externalUserId
5460
5721
  });
5461
5722
  return data;
5462
5723
  }
5724
+ /**
5725
+ * Revoke Portal Links
5726
+ *
5727
+ * Revokes every Portal Link generated for the given organization with the
5728
+ * given `externalUserId`, and immediately ends any Admin Portal sessions that
5729
+ * were started from those links. Use this when an admin is deprovisioned from
5730
+ * your application: unopened links stop working, and their already-open
5731
+ * portal sessions are ended. Only links that were generated with an
5732
+ * `externalUserId` can be revoked, so pass one to `generateLink` for every
5733
+ * admin you may later need to deprovision.
5734
+ * @param payload - Object containing organization and externalUserId.
5735
+ * @throws {NotFoundException} 404
5736
+ * @throws {UnprocessableEntityException} 422
5737
+ */
5738
+ async revokeLink({ organization, externalUserId }) {
5739
+ await this.workos.post("/portal/revoke_link", {
5740
+ organization,
5741
+ external_user_id: externalUserId
5742
+ });
5743
+ }
5463
5744
  };
5464
5745
  //#endregion
5465
5746
  //#region src/common/utils/query-string.ts
@@ -6620,16 +6901,20 @@ var CookieSession = class {
6620
6901
  /**
6621
6902
  * Gets the URL to redirect the user to for logging out.
6622
6903
  *
6904
+ * Works for sessions whose access token has expired. The sealed cookie is
6905
+ * already authenticated by its encryption, so the session ID is read from
6906
+ * the access token without verifying it.
6907
+ *
6623
6908
  * @returns The URL to redirect the user to for logging out.
6624
6909
  */
6625
6910
  async getLogoutUrl({ returnTo } = {}) {
6626
- const authenticationResponse = await this.authenticate();
6627
- if (!authenticationResponse.authenticated) {
6628
- const { reason } = authenticationResponse;
6629
- throw new Error(`Failed to extract session ID for logout URL: ${reason}`);
6630
- }
6911
+ if (!this.sessionData) throw new Error(`Failed to extract session ID for logout URL: no_session_cookie_provided`);
6912
+ const { accessToken } = await unsealData(this.sessionData, { password: this.cookiePassword });
6913
+ if (!accessToken) throw new Error(`Failed to extract session ID for logout URL: invalid_session_cookie`);
6914
+ const { decodeJwt } = await getJose();
6915
+ const { sid: sessionId } = decodeJwt(accessToken);
6631
6916
  return this.userManagement.getLogoutUrl({
6632
- sessionId: authenticationResponse.sessionId,
6917
+ sessionId,
6633
6918
  returnTo
6634
6919
  });
6635
6920
  }
@@ -7216,6 +7501,32 @@ var UserManagement = class UserManagement {
7216
7501
  return new AutoPaginatable(await fetchAndDeserialize(this.workos, `/user_management/users/${encodePathParameter(userId)}/sessions`, deserializeSession, options ? serializeListSessionsOptions(options) : void 0), (params) => fetchAndDeserialize(this.workos, `/user_management/users/${encodePathParameter(userId)}/sessions`, deserializeSession, params), options ? serializeListSessionsOptions(options) : void 0);
7217
7502
  }
7218
7503
  /**
7504
+ * List authorized applications
7505
+ *
7506
+ * Get a list of Connect applications that the user has authorized.
7507
+ * @param userId - The ID of the user.
7508
+ * @param options - Pagination options.
7509
+ * @returns {Promise<AutoPaginatable<AuthorizedConnectApplication>>}
7510
+ * @throws {NotFoundException} 404
7511
+ * @throws {UnprocessableEntityException} 422
7512
+ */
7513
+ async listAuthorizedApplications(userId, options) {
7514
+ const path = `/user_management/users/${encodePathParameter(userId)}/authorized_applications`;
7515
+ return new AutoPaginatable(await fetchAndDeserialize(this.workos, path, deserializeAuthorizedConnectApplication, options), (params) => fetchAndDeserialize(this.workos, path, deserializeAuthorizedConnectApplication, params), options);
7516
+ }
7517
+ /**
7518
+ * Delete an authorized application
7519
+ *
7520
+ * Removes a user's authorization without deleting the Connect application.
7521
+ * @param userId - The ID of the user.
7522
+ * @param applicationId - The ID or client ID of the application.
7523
+ * @returns {Promise<void>}
7524
+ * @throws {NotFoundException} 404
7525
+ */
7526
+ async deleteAuthorizedApplication(userId, applicationId) {
7527
+ await this.workos.delete(`/user_management/users/${encodePathParameter(userId)}/authorized_applications/${encodePathParameter(applicationId)}`);
7528
+ }
7529
+ /**
7219
7530
  * Delete a user
7220
7531
  *
7221
7532
  * Permanently deletes a user in the current environment. It cannot be undone.
@@ -7675,6 +7986,21 @@ var UserManagement = class UserManagement {
7675
7986
  }
7676
7987
  };
7677
7988
  //#endregion
7989
+ //#region src/feature-flags/create-rule-with-targets-error.ts
7990
+ /** A rule was created, but adding one of its targets failed. */
7991
+ var CreateRuleWithTargetsError = class extends Error {
7992
+ rule;
7993
+ targets;
7994
+ failedTargetId;
7995
+ name = "CreateRuleWithTargetsError";
7996
+ constructor(rule, targets, failedTargetId, cause) {
7997
+ super("The rule was created, but adding a target failed.", { cause });
7998
+ this.rule = rule;
7999
+ this.targets = targets;
8000
+ this.failedTargetId = failedTargetId;
8001
+ }
8002
+ };
8003
+ //#endregion
7678
8004
  //#region src/feature-flags/event-emitter.ts
7679
8005
  /**
7680
8006
  * Minimal, runtime-agnostic, typed event emitter.
@@ -8026,26 +8352,18 @@ var FeatureFlagsRuntimeClient = class extends EventEmitter {
8026
8352
  async fetchWithTimeout() {
8027
8353
  this.pollAbortController = new AbortController();
8028
8354
  const { signal } = this.pollAbortController;
8029
- let timeoutId;
8030
- const fetchPromise = this.workos.get("/sdk/feature-flags?payload_version=2").then(({ data }) => data);
8031
- const timeoutPromise = new Promise((_, reject) => {
8032
- timeoutId = setTimeout(() => {
8033
- this.pollAbortController?.abort();
8034
- reject(/* @__PURE__ */ new Error("Request timed out"));
8035
- }, this.requestTimeoutMs);
8036
- });
8355
+ const timeoutId = setTimeout(() => {
8356
+ this.pollAbortController?.abort(/* @__PURE__ */ new Error("Request timed out"));
8357
+ }, this.requestTimeoutMs);
8358
+ const fetchPromise = this.workos.get("/sdk/feature-flags?payload_version=2", { signal }).then(({ data }) => data);
8037
8359
  const abortPromise = new Promise((_, reject) => {
8038
8360
  if (signal.aborted) {
8039
- reject(/* @__PURE__ */ new Error("Poll aborted"));
8361
+ reject(signal.reason);
8040
8362
  return;
8041
8363
  }
8042
- signal.addEventListener("abort", () => reject(/* @__PURE__ */ new Error("Poll aborted")), { once: true });
8364
+ signal.addEventListener("abort", () => reject(signal.reason), { once: true });
8043
8365
  });
8044
- return Promise.race([
8045
- fetchPromise,
8046
- timeoutPromise,
8047
- abortPromise
8048
- ]).finally(() => {
8366
+ return Promise.race([fetchPromise, abortPromise]).finally(() => {
8049
8367
  clearTimeout(timeoutId);
8050
8368
  });
8051
8369
  }
@@ -8100,6 +8418,93 @@ var FeatureFlags = class {
8100
8418
  constructor(workos) {
8101
8419
  this.workos = workos;
8102
8420
  }
8421
+ /** Append an empty rule to a flag. Duplicate target type/value pairs return 409. */
8422
+ async createFlagRule(options) {
8423
+ const { data } = await this.workos.post("/flag_rules", {
8424
+ flag_slug: options.flagSlug,
8425
+ target_type: options.targetType,
8426
+ value: options.value
8427
+ });
8428
+ return deserializeFlagRule(data);
8429
+ }
8430
+ /** List a flag's rules in evaluation order. */
8431
+ async listFlagRules(options) {
8432
+ const fetchPage = async ({ limit, before, after }) => {
8433
+ const { data } = await this.workos.get("/flag_rules", { query: {
8434
+ flag_slug: options.flagSlug,
8435
+ limit,
8436
+ before,
8437
+ after
8438
+ } });
8439
+ return deserializeList(data, deserializeFlagRule);
8440
+ };
8441
+ return new AutoPaginatable(await fetchPage(options), fetchPage, options);
8442
+ }
8443
+ /** Get a rule in the current environment. */
8444
+ async getFlagRule(id) {
8445
+ const { data } = await this.workos.get(`/flag_rules/${encodePathParameter(id)}`);
8446
+ return deserializeFlagRule(data);
8447
+ }
8448
+ /** Delete a rule and all its target memberships. */
8449
+ async deleteFlagRule(id) {
8450
+ await this.workos.delete(`/flag_rules/${encodePathParameter(id)}`);
8451
+ }
8452
+ /** Add a membership to a rule. The rule supplies the target type and value. */
8453
+ async createFlagTarget(options) {
8454
+ const { data } = await this.workos.post("/flag_targets", {
8455
+ rule_id: options.ruleId,
8456
+ target_id: options.targetId
8457
+ });
8458
+ return deserializeFlagTarget(data);
8459
+ }
8460
+ /** Get a membership, or a legacy target while the compatibility contract is enabled. */
8461
+ async getFlagTarget(id) {
8462
+ const { data } = await this.workos.get(`/flag_targets/${encodePathParameter(id)}`);
8463
+ return deserializeFlagTargetResource(data);
8464
+ }
8465
+ /** List targets with combined filters; the team's contract selects their shape. */
8466
+ async listFlagTargets(options = {}) {
8467
+ const fetchPage = async ({ limit, before, after }) => {
8468
+ const { data } = await this.workos.get("/flag_targets", { query: {
8469
+ rule_id: options.ruleId,
8470
+ flag_slug: options.flagSlug,
8471
+ target_type: options.targetType,
8472
+ target_id: options.targetId,
8473
+ order: options.order ?? "desc",
8474
+ limit,
8475
+ before,
8476
+ after
8477
+ } });
8478
+ return deserializeList(data, deserializeFlagTargetResource);
8479
+ };
8480
+ return new AutoPaginatable(await fetchPage(options), fetchPage, options);
8481
+ }
8482
+ /** Delete a membership by its flag_target ID, not the targeted entity's ID. */
8483
+ async deleteFlagTarget(id) {
8484
+ await this.workos.delete(`/flag_targets/${encodePathParameter(id)}`);
8485
+ }
8486
+ /**
8487
+ * Create a rule, then add its targets sequentially in input order.
8488
+ * This is not atomic: on failure, the rule and completed memberships remain.
8489
+ * A CreateRuleWithTargetsError exposes the rule, confirmed targets, failed
8490
+ * target ID, and original error. No later targets are attempted.
8491
+ */
8492
+ async createRuleWithTargets(options) {
8493
+ const rule = await this.createFlagRule(options);
8494
+ const targets = [];
8495
+ for (const targetId of options.targetIds) try {
8496
+ targets.push(await this.createFlagTarget({
8497
+ ruleId: rule.id,
8498
+ targetId
8499
+ }));
8500
+ } catch (cause) {
8501
+ throw new CreateRuleWithTargetsError(rule, targets, targetId, cause);
8502
+ }
8503
+ return {
8504
+ rule,
8505
+ targets
8506
+ };
8507
+ }
8103
8508
  /**
8104
8509
  * List feature flags
8105
8510
  *
@@ -8164,6 +8569,9 @@ var FeatureFlags = class {
8164
8569
  /**
8165
8570
  * Add a feature flag target
8166
8571
  *
8572
+ * @deprecated For rule-based targeting, use createFlagRule and createFlagTarget.
8573
+ * This compatibility helper remains supported.
8574
+ *
8167
8575
  * Enables a feature flag for a specific target in the current environment. Currently, supported targets include users and organizations.
8168
8576
  * @params options - Object containing slug and targetId.
8169
8577
  * @returns {Promise<void>}
@@ -8178,6 +8586,9 @@ var FeatureFlags = class {
8178
8586
  /**
8179
8587
  * Remove a feature flag target
8180
8588
  *
8589
+ * @deprecated For rule-based targeting, use deleteFlagTarget with a membership ID.
8590
+ * This compatibility helper remains supported.
8591
+ *
8181
8592
  * Removes a target from the feature flag's target list in the current environment. Currently, supported targets include users and organizations.
8182
8593
  * @params options - Object containing slug and targetId.
8183
8594
  * @returns {Promise<void>}
@@ -10006,7 +10417,7 @@ var Vault = class {
10006
10417
  };
10007
10418
  //#endregion
10008
10419
  //#region package.json
10009
- var version = "12.2.0";
10420
+ var version = "12.3.0";
10010
10421
  //#endregion
10011
10422
  //#region src/workos.ts
10012
10423
  const DEFAULT_HOSTNAME = "api.workos.com";
@@ -10110,7 +10521,7 @@ var WorkOS = class {
10110
10521
  timeout: options.timeout,
10111
10522
  maxRetries: options.maxRetries,
10112
10523
  headers
10113
- });
10524
+ }, options.fetchFn);
10114
10525
  }
10115
10526
  get version() {
10116
10527
  return version;
@@ -10154,9 +10565,11 @@ var WorkOS = class {
10154
10565
  res = await this.client.get(path, {
10155
10566
  params: options.query,
10156
10567
  headers: requestHeaders,
10157
- maxRetries: options.maxRetries
10568
+ maxRetries: options.maxRetries,
10569
+ signal: options.signal
10158
10570
  });
10159
10571
  } catch (error) {
10572
+ options.signal?.throwIfAborted();
10160
10573
  this.handleHttpError({
10161
10574
  path,
10162
10575
  error
@@ -10473,6 +10886,12 @@ Object.defineProperty(exports, "CookieSession", {
10473
10886
  return CookieSession;
10474
10887
  }
10475
10888
  });
10889
+ Object.defineProperty(exports, "CreateRuleWithTargetsError", {
10890
+ enumerable: true,
10891
+ get: function() {
10892
+ return CreateRuleWithTargetsError;
10893
+ }
10894
+ });
10476
10895
  Object.defineProperty(exports, "DirectoryUserWithGroupsState", {
10477
10896
  enumerable: true,
10478
10897
  get: function() {
@@ -10624,4 +11043,4 @@ Object.defineProperty(exports, "serializeRevokeSessionOptions", {
10624
11043
  }
10625
11044
  });
10626
11045
 
10627
- //# sourceMappingURL=factory-CEEOW8zX.cjs.map
11046
+ //# sourceMappingURL=factory-BurShrC1.cjs.map