@seliseblocks/genesis-os 4.4.4 → 4.4.5

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.
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkI2KRZLP4_cjs = require('./chunk-I2KRZLP4.cjs');
3
+ var chunk4CMIWUZW_cjs = require('./chunk-4CMIWUZW.cjs');
4
4
  var chunkX4YCRWXO_cjs = require('./chunk-X4YCRWXO.cjs');
5
5
  var chunkBPJM3L7O_cjs = require('./chunk-BPJM3L7O.cjs');
6
6
  var chunk4QN4CYSC_cjs = require('./chunk-4QN4CYSC.cjs');
@@ -467,13 +467,13 @@ function usePopoverWidth() {
467
467
  // src/services/auth.service.ts
468
468
  var AuthService = class {
469
469
  logout() {
470
- return chunkI2KRZLP4_cjs.iamClient.post(chunkI2KRZLP4_cjs.AUTH_ENDPOINTS.LOGOUT, {});
470
+ return chunk4CMIWUZW_cjs.iamClient.post(chunk4CMIWUZW_cjs.AUTH_ENDPOINTS.LOGOUT, {});
471
471
  }
472
472
  };
473
473
  var authService = new AuthService();
474
474
  var forgetSession = () => {
475
- chunkI2KRZLP4_cjs.clearTenantClaims();
476
- chunkI2KRZLP4_cjs.announceSignOut();
475
+ chunk4CMIWUZW_cjs.clearTenantClaims();
476
+ chunk4CMIWUZW_cjs.announceSignOut();
477
477
  };
478
478
  var useLogout = () => {
479
479
  return reactQuery.useMutation({
@@ -594,7 +594,7 @@ var InitiateService = class {
594
594
  const headers = { Accept: "application/json" };
595
595
  if (blocksKey) headers["X-Blocks-Key"] = blocksKey;
596
596
  const response = await fetch(
597
- `${iamBaseUrl}${chunkI2KRZLP4_cjs.IAM_ENDPOINTS.INITIATE}?${params}`,
597
+ `${iamBaseUrl}${chunk4CMIWUZW_cjs.IAM_ENDPOINTS.INITIATE}?${params}`,
598
598
  { headers, signal }
599
599
  );
600
600
  if (!response.ok) {
@@ -686,8 +686,8 @@ var LoginService = class {
686
686
  if (flow === "signup") params.set("flow", flow);
687
687
  const headers = {};
688
688
  if (blocksKey) headers["X-Blocks-Key"] = blocksKey;
689
- return chunkI2KRZLP4_cjs.iamClient.get(
690
- `${chunkI2KRZLP4_cjs.IAM_ENDPOINTS.INITIATE}?${params.toString()}`,
689
+ return chunk4CMIWUZW_cjs.iamClient.get(
690
+ `${chunk4CMIWUZW_cjs.IAM_ENDPOINTS.INITIATE}?${params.toString()}`,
691
691
  headers
692
692
  );
693
693
  }
@@ -734,8 +734,8 @@ var SignUpService = class {
734
734
  // header, which `iamClient` already attaches. That is what lets the login
735
735
  // page ask whether signup is open before anyone has authenticated.
736
736
  getSignUpSetting() {
737
- return chunkI2KRZLP4_cjs.iamClient.get(
738
- chunkI2KRZLP4_cjs.ORGANIZATION_ENDPOINTS.GET_SIGNUP_SETTING
737
+ return chunk4CMIWUZW_cjs.iamClient.get(
738
+ chunk4CMIWUZW_cjs.ORGANIZATION_ENDPOINTS.GET_SIGNUP_SETTING
739
739
  );
740
740
  }
741
741
  };
@@ -817,24 +817,24 @@ function useLogo() {
817
817
 
818
818
  // src/services/notification.service.ts
819
819
  var NotificationService = class {
820
- notificationService = chunkI2KRZLP4_cjs.notificationClient;
820
+ notificationService = chunk4CMIWUZW_cjs.notificationClient;
821
821
  getNotifications = (pageNumber, pageSize) => {
822
822
  const params = new URLSearchParams({
823
823
  page: String(pageNumber - 1),
824
824
  pageSize: String(pageSize)
825
825
  });
826
826
  return this.notificationService.get(
827
- `${chunkI2KRZLP4_cjs.NOTIFICATION_ENDPOINTS.GET_NOTIFICATIONS}?${params}`
827
+ `${chunk4CMIWUZW_cjs.NOTIFICATION_ENDPOINTS.GET_NOTIFICATIONS}?${params}`
828
828
  );
829
829
  };
830
830
  markAsRead = (notificationId) => {
831
- return this.notificationService.post(chunkI2KRZLP4_cjs.NOTIFICATION_ENDPOINTS.MARK_AS_READ, {
831
+ return this.notificationService.post(chunk4CMIWUZW_cjs.NOTIFICATION_ENDPOINTS.MARK_AS_READ, {
832
832
  id: notificationId
833
833
  });
834
834
  };
835
835
  markAllNotificationsAsRead = () => {
836
836
  return this.notificationService.post(
837
- chunkI2KRZLP4_cjs.NOTIFICATION_ENDPOINTS.MARK_ALL_AS_READ,
837
+ chunk4CMIWUZW_cjs.NOTIFICATION_ENDPOINTS.MARK_ALL_AS_READ,
838
838
  {}
839
839
  );
840
840
  };
@@ -858,7 +858,7 @@ var NotificationService = class {
858
858
  window.dispatchEvent(notificationEvent);
859
859
  };
860
860
  getNotificationConfigs = (page = 0, pageSize = 10) => {
861
- const url = `${chunkI2KRZLP4_cjs.NOTIFICATION_CONFIG_ENDPOINTS.GET_CONFIGS}?page=${page}&pageSize=${pageSize}`;
861
+ const url = `${chunk4CMIWUZW_cjs.NOTIFICATION_CONFIG_ENDPOINTS.GET_CONFIGS}?page=${page}&pageSize=${pageSize}`;
862
862
  return this.notificationService.get(url);
863
863
  };
864
864
  };
@@ -896,7 +896,7 @@ var useGetBlocksNotificationConfig = (page = 0, pageSize = 100) => {
896
896
  // src/services/organization.service.ts
897
897
  var OrganizationService = class {
898
898
  getMyOrganizations() {
899
- return chunkI2KRZLP4_cjs.iamClient.get(chunkI2KRZLP4_cjs.ORGANIZATION_ENDPOINTS.GET_MY_ORGANIZATIONS);
899
+ return chunk4CMIWUZW_cjs.iamClient.get(chunk4CMIWUZW_cjs.ORGANIZATION_ENDPOINTS.GET_MY_ORGANIZATIONS);
900
900
  }
901
901
  };
902
902
 
@@ -917,38 +917,38 @@ var useGetMyOrganizations = () => {
917
917
  };
918
918
 
919
919
  // src/services/project.service.ts
920
- var logicClientForOS = new chunkI2KRZLP4_cjs.HttpClient({
920
+ var logicClientForOS = new chunk4CMIWUZW_cjs.HttpClient({
921
921
  baseURL: () => chunkX4YCRWXO_cjs.getRuntimeEnv("BLOCKS_LOGIC_BASE_URL"),
922
922
  blocksKey: () => chunkX4YCRWXO_cjs.getRuntimeEnv("BLOCKS_X_BLOCKS_KEY")
923
923
  });
924
924
  var ProjectService = class {
925
925
  getProjects(page = 0, pageSize = 100, tenantGroupId = "") {
926
- const url = `${chunkI2KRZLP4_cjs.PROJECT_ENDPOINTS.GETS}?page=${page}&pageSize=${pageSize}&tenantGroupId=${tenantGroupId}`;
927
- return chunkI2KRZLP4_cjs.logicClient.get(url);
926
+ const url = `${chunk4CMIWUZW_cjs.PROJECT_ENDPOINTS.GETS}?page=${page}&pageSize=${pageSize}&tenantGroupId=${tenantGroupId}`;
927
+ return chunk4CMIWUZW_cjs.logicClient.get(url);
928
928
  }
929
929
  // Resolves the project from the caller's auth context — there is no parameter
930
930
  // to pass; the token's tenant selects the project.
931
931
  getProject() {
932
- return chunkI2KRZLP4_cjs.logicClient.get(chunkI2KRZLP4_cjs.PROJECT_ENDPOINTS.GET);
932
+ return chunk4CMIWUZW_cjs.logicClient.get(chunk4CMIWUZW_cjs.PROJECT_ENDPOINTS.GET);
933
933
  }
934
934
  getEnvRepositories() {
935
- const url = `${chunkI2KRZLP4_cjs.PROJECT_ENDPOINTS.REPOS_LIST}`;
935
+ const url = `${chunk4CMIWUZW_cjs.PROJECT_ENDPOINTS.REPOS_LIST}`;
936
936
  return logicClientForOS.get(url);
937
937
  }
938
938
  repoUpdate(payload) {
939
- return logicClientForOS.post(chunkI2KRZLP4_cjs.PROJECT_ENDPOINTS.REPO_UPDATE, payload);
939
+ return logicClientForOS.post(chunk4CMIWUZW_cjs.PROJECT_ENDPOINTS.REPO_UPDATE, payload);
940
940
  }
941
941
  updateTenantGroup(payload) {
942
- return chunkI2KRZLP4_cjs.logicClient.post(chunkI2KRZLP4_cjs.PROJECT_ENDPOINTS.UPDATE_TENANT_GROUP, payload);
942
+ return chunk4CMIWUZW_cjs.logicClient.post(chunk4CMIWUZW_cjs.PROJECT_ENDPOINTS.UPDATE_TENANT_GROUP, payload);
943
943
  }
944
944
  updateProject(payload) {
945
- return chunkI2KRZLP4_cjs.logicClient.post(chunkI2KRZLP4_cjs.PROJECT_ENDPOINTS.UPDATE_PROJECT, payload);
945
+ return chunk4CMIWUZW_cjs.logicClient.post(chunk4CMIWUZW_cjs.PROJECT_ENDPOINTS.UPDATE_PROJECT, payload);
946
946
  }
947
947
  disableProject(payload) {
948
- return chunkI2KRZLP4_cjs.logicClient.post(chunkI2KRZLP4_cjs.PROJECT_ENDPOINTS.DISABLE, payload);
948
+ return chunk4CMIWUZW_cjs.logicClient.post(chunk4CMIWUZW_cjs.PROJECT_ENDPOINTS.DISABLE, payload);
949
949
  }
950
950
  validateCNameProject(payload) {
951
- return chunkI2KRZLP4_cjs.logicClient.post(chunkI2KRZLP4_cjs.PROJECT_ENDPOINTS.CONFIGURE, payload);
951
+ return chunk4CMIWUZW_cjs.logicClient.post(chunk4CMIWUZW_cjs.PROJECT_ENDPOINTS.CONFIGURE, payload);
952
952
  }
953
953
  };
954
954
  var projectService = new ProjectService();
@@ -1071,7 +1071,7 @@ var useScopedPath = (paramName = "itemId") => {
1071
1071
  // src/services/service-registry.service.ts
1072
1072
  var ServiceRegistryService = class {
1073
1073
  getAllServices(payload) {
1074
- return chunkI2KRZLP4_cjs.logicClient.post(`${chunkI2KRZLP4_cjs.SERVICE_REGISTRY_ENDPOINTS.GET_ALL}`, payload);
1074
+ return chunk4CMIWUZW_cjs.logicClient.post(`${chunk4CMIWUZW_cjs.SERVICE_REGISTRY_ENDPOINTS.GET_ALL}`, payload);
1075
1075
  }
1076
1076
  };
1077
1077
  var serviceRegistryService = new ServiceRegistryService();
@@ -1086,24 +1086,24 @@ var useGetAllServices = (options) => {
1086
1086
  // src/services/impersonation.service.ts
1087
1087
  var ImpersonationService = class {
1088
1088
  startImpersonation(request, options) {
1089
- return chunkI2KRZLP4_cjs.iamClient.post(
1090
- chunkI2KRZLP4_cjs.IMPERSONATE_ENDPOINTS.IMPERSONATE,
1089
+ return chunk4CMIWUZW_cjs.iamClient.post(
1090
+ chunk4CMIWUZW_cjs.IMPERSONATE_ENDPOINTS.IMPERSONATE,
1091
1091
  request,
1092
1092
  void 0,
1093
1093
  options
1094
1094
  );
1095
1095
  }
1096
1096
  stopImpersonation(options) {
1097
- return chunkI2KRZLP4_cjs.iamClient.post(
1098
- chunkI2KRZLP4_cjs.IMPERSONATE_ENDPOINTS.STOP_IMPERSONATION,
1097
+ return chunk4CMIWUZW_cjs.iamClient.post(
1098
+ chunk4CMIWUZW_cjs.IMPERSONATE_ENDPOINTS.STOP_IMPERSONATION,
1099
1099
  {},
1100
1100
  void 0,
1101
1101
  options
1102
1102
  );
1103
1103
  }
1104
1104
  impersonationStatus(options) {
1105
- return chunkI2KRZLP4_cjs.iamClient.post(
1106
- chunkI2KRZLP4_cjs.IMPERSONATE_ENDPOINTS.IMPERSONATION_STATUS,
1105
+ return chunk4CMIWUZW_cjs.iamClient.post(
1106
+ chunk4CMIWUZW_cjs.IMPERSONATE_ENDPOINTS.IMPERSONATION_STATUS,
1107
1107
  null,
1108
1108
  void 0,
1109
1109
  options
@@ -1112,10 +1112,12 @@ var ImpersonationService = class {
1112
1112
  };
1113
1113
  var impersonationService = new ImpersonationService();
1114
1114
  var IMPERSONATION_STATUS_QUERY_KEY = ["blocks-kit-impersonation", "status"];
1115
- var INSIDE_SESSION_LOCK = {
1115
+ var LOCKED_CALL_TIMEOUT_MS = 2e4;
1116
+ var insideSessionLock = () => ({
1116
1117
  skipTokenRotation: true,
1117
- skipSessionCheck: true
1118
- };
1118
+ skipSessionCheck: true,
1119
+ signal: chunk4CMIWUZW_cjs.timeoutSignal(LOCKED_CALL_TIMEOUT_MS)
1120
+ });
1119
1121
  var RETURN_STATUS_WAIT_MS = 5e3;
1120
1122
  var FOCUS_REFETCH_DELAY_MS = 50;
1121
1123
  var rootTenantId = () => chunkX4YCRWXO_cjs.getRuntimeEnv("BLOCKS_X_BLOCKS_KEY") || "";
@@ -1145,7 +1147,7 @@ var withRefreshedToken = async (call) => {
1145
1147
  return await call();
1146
1148
  } catch (error) {
1147
1149
  if (!isExpiredAccessToken(error)) throw error;
1148
- await chunkI2KRZLP4_cjs.iamClient.refreshWithinSessionLock();
1150
+ await chunk4CMIWUZW_cjs.iamClient.refreshWithinSessionLock();
1149
1151
  return call();
1150
1152
  }
1151
1153
  };
@@ -1186,11 +1188,11 @@ var useImpersonationStatusChecker = () => {
1186
1188
  var useSessionTenantGuard = () => {
1187
1189
  const queryClient = reactQuery.useQueryClient();
1188
1190
  react.useEffect(
1189
- () => chunkI2KRZLP4_cjs.HttpClient.setSessionGuard({
1191
+ () => chunk4CMIWUZW_cjs.HttpClient.setSessionGuard({
1190
1192
  expectedTenant: tenantShown,
1191
1193
  confirmTenant: async () => applyServerStatus(
1192
1194
  queryClient,
1193
- await impersonationService.impersonationStatus(INSIDE_SESSION_LOCK)
1195
+ await impersonationService.impersonationStatus(insideSessionLock())
1194
1196
  )
1195
1197
  }),
1196
1198
  [queryClient]
@@ -1258,17 +1260,17 @@ var useRecordClaimedTenant = () => {
1258
1260
  [queryClient]
1259
1261
  );
1260
1262
  };
1261
- var stopAndConfirm = () => chunkI2KRZLP4_cjs.iamClient.withSessionLock(async () => {
1263
+ var stopAndConfirm = () => chunk4CMIWUZW_cjs.iamClient.withSessionLock(async () => {
1262
1264
  let stopError = null;
1263
1265
  try {
1264
1266
  await withRefreshedToken(
1265
- () => impersonationService.stopImpersonation(INSIDE_SESSION_LOCK)
1267
+ () => impersonationService.stopImpersonation(insideSessionLock())
1266
1268
  );
1267
1269
  } catch (error) {
1268
1270
  stopError = error;
1269
1271
  }
1270
1272
  const status = await withRefreshedToken(
1271
- () => impersonationService.impersonationStatus(INSIDE_SESSION_LOCK)
1273
+ () => impersonationService.impersonationStatus(insideSessionLock())
1272
1274
  );
1273
1275
  return { status, stopError };
1274
1276
  });
@@ -1285,9 +1287,9 @@ var useStopImpersonation = () => {
1285
1287
  }
1286
1288
  });
1287
1289
  };
1288
- var startAndConfirm = (request) => chunkI2KRZLP4_cjs.iamClient.withSessionLock(async () => {
1290
+ var startAndConfirm = (request) => chunk4CMIWUZW_cjs.iamClient.withSessionLock(async () => {
1289
1291
  const result = await withRefreshedToken(
1290
- () => impersonationService.startImpersonation(request, INSIDE_SESSION_LOCK)
1292
+ () => impersonationService.startImpersonation(request, insideSessionLock())
1291
1293
  );
1292
1294
  if (result?.cookie_set !== true) {
1293
1295
  throw new chunkX4YCRWXO_cjs.HttpError(500, {
@@ -1297,7 +1299,7 @@ var startAndConfirm = (request) => chunkI2KRZLP4_cjs.iamClient.withSessionLock(a
1297
1299
  });
1298
1300
  }
1299
1301
  const status = await withRefreshedToken(
1300
- () => impersonationService.impersonationStatus(INSIDE_SESSION_LOCK)
1302
+ () => impersonationService.impersonationStatus(insideSessionLock())
1301
1303
  ).catch(() => null);
1302
1304
  return { result, status };
1303
1305
  });
@@ -1323,7 +1325,7 @@ var useStartImpersonation = () => {
1323
1325
  return result;
1324
1326
  },
1325
1327
  onSuccess: (_data, variables) => {
1326
- chunkI2KRZLP4_cjs.claimTenant(variables.targeted_tenant_id);
1328
+ chunk4CMIWUZW_cjs.claimTenant(variables.targeted_tenant_id);
1327
1329
  },
1328
1330
  onError: () => {
1329
1331
  void queryClient.invalidateQueries({
@@ -1394,5 +1396,5 @@ exports.useUpdateProject = useUpdateProject;
1394
1396
  exports.useUpdateRepositories = useUpdateRepositories;
1395
1397
  exports.useUpdateTenantGroup = useUpdateTenantGroup;
1396
1398
  exports.useValidateCNameProject = useValidateCNameProject;
1397
- //# sourceMappingURL=chunk-AD2ZGEQ5.cjs.map
1398
- //# sourceMappingURL=chunk-AD2ZGEQ5.cjs.map
1399
+ //# sourceMappingURL=chunk-IRIDGVV2.cjs.map
1400
+ //# sourceMappingURL=chunk-IRIDGVV2.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/query-state/use-query-states-kit.ts","../src/hooks/query-client/query-key-factory.ts","../src/hooks/query-client/use-query-client-kit.ts","../src/hooks/use-boolean.ts","../src/hooks/use-copy-to-clipboard.ts","../src/hooks/use-countdown.ts","../src/hooks/utils/fuse-search.ts","../src/hooks/use-debounced/util.ts","../src/hooks/use-debounced/index.ts","../src/hooks/use-fuse/use-fuse-search.ts","../src/hooks/use-fuse/use-fuse-index.ts","../src/hooks/use-fuse/use-debounced-fuse-filter.ts","../src/hooks/use-keyboard-shortcut.ts","../src/hooks/use-language.ts","../src/hooks/use-media-query.ts","../src/hooks/use-path-segments.ts","../src/hooks/use-popover-width.ts","../src/services/auth.service.ts","../src/hooks/use-logout.ts","../src/hooks/use-blocks-app-config-store.ts","../src/assets/icons/blocks-icon.tsx","../src/hooks/use-theme/index.ts","../src/hooks/use-icon.tsx","../src/services/initiate.service.ts","../src/hooks/use-initiate.ts","../src/hooks/use-language-switcher.ts","../src/services/login.service.ts","../src/hooks/use-login.ts","../src/services/signup.service.ts","../src/hooks/use-signup.ts","../src/hooks/use-logo.ts","../src/services/notification.service.ts","../src/hooks/use-notifications.ts","../src/services/organization.service.ts","../src/services/iam.service.ts","../src/hooks/use-organization.ts","../src/services/project.service.ts","../src/hooks/use-project.ts","../src/hooks/use-scoped-path.ts","../src/services/service-registry.service.ts","../src/hooks/use-service-registry.ts","../src/services/impersonation.service.ts","../src/hooks/use-impersonation.ts"],"names":["useMemo","useQueryStates","useQueryClient","useState","useEffect","useCallback","Fuse","useRef","iamClient","AUTH_ENDPOINTS","clearTenantClaims","announceSignOut","useMutation","useProjectStore","useAuthStore","useContext","BlocksAppLayoutContext","useStore","jsxs","jsx","useAppSettingsStore","getRuntimeEnv","IAM_ENDPOINTS","useQuery","ORGANIZATION_ENDPOINTS","notificationClient","NOTIFICATION_ENDPOINTS","NOTIFICATION_CONFIG_ENDPOINTS","HttpClient","PROJECT_ENDPOINTS","logicClient","useImpersonateStore","useParams","SERVICE_REGISTRY_ENDPOINTS","IMPERSONATE_ENDPOINTS","timeoutSignal","HttpError","focusManager","rootTenantId","claimTenant"],"mappings":";;;;;;;;;;;;;;;;;;;AAuIO,SAAS,kBACd,OAAA,EACkC;AAClC,EAAA,MAAM,EAAE,MAAA,EAAQ,QAAA,EAAU,QAAA,EAAU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AAA,CAAQ,kBAAkB,CAAA,EACrE;AACA,QAAA,MAAM,IAAIwB,4BAAU,GAAA,EAAK;AAAA,UACvB,MAAA,EAAQ;AAAA,YACN,OAAA,EACE;AAAA;AACJ,SACD,CAAA;AAAA,MACH;AACA,MAAA,OAAO,MAAA;AAAA,IACT,CAAA;AAAA,IACA,SAAA,EAAW,CAAC,KAAA,EAAO,SAAA,KAAc;AAO/B,MAAAG,6BAAA,CAAY,UAAU,kBAAkB,CAAA;AAAA,IAC1C,CAAA;AAAA,IACA,SAAS,MAAM;AAGb,MAAA,KAAK,YAAY,iBAAA,CAAkB;AAAA,QACjC,QAAA,EAAU;AAAA,OACX,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH","file":"chunk-IRIDGVV2.cjs","sourcesContent":["import { useMemo } from \"react\";\nimport {\n type Options as NuqsOptions,\n type SetValues,\n type UseQueryStatesKeysMap,\n type UseQueryStatesOptions,\n type Values,\n useQueryStates,\n} from \"nuqs\";\n\n/**\n * Schema map passed to `useQueryStatesKit`.\n *\n * This type maps query keys to `nuqs` parser builders (for example,\n * `parseAsString.withDefault(\"\")`).\n */\nexport type QueryStatesKitSchema = UseQueryStatesKeysMap;\n\n/**\n * Navigation options accepted by query update helpers.\n *\n * These options are forwarded to `nuqs` state updaters.\n */\nexport type QueryUpdateOptions = NuqsOptions;\n\n/**\n * Typed partial update payload for a query-state schema.\n *\n * Each key can be set to a parsed value or `null` to clear it from the URL.\n */\nexport type QueryPatch<TSchema extends QueryStatesKitSchema> = Partial<{\n [Key in keyof Values<TSchema>]: Values<TSchema>[Key] | null;\n}>;\n\n/**\n * Updater callback shape used by `setQuery` and `updateAndResetPage`.\n */\nexport type QueryPatchUpdater<TSchema extends QueryStatesKitSchema> = (\n previous: Values<TSchema>,\n) => QueryPatch<TSchema> | null;\n\ntype QueryKey<TSchema extends QueryStatesKitSchema> = Extract<\n keyof Values<TSchema>,\n string\n>;\n\n/**\n * Behavior defaults for URL updates performed by `useQueryStatesKit`.\n */\nexport type QueryStatesKitBehavior = {\n /** History mode used when no override is provided. */\n history?: \"replace\" | \"push\";\n /** Whether updates should be shallow by default. */\n shallow?: boolean;\n /** Whether updates should trigger scroll by default. */\n scroll?: boolean;\n /** Conventional pagination key for page helpers. */\n pageKey?: string;\n};\n\n/**\n * Options accepted by `useQueryStatesKit`.\n *\n * @typeParam TSchema Query-state schema map based on `nuqs` parsers.\n */\nexport type QueryStatesKitOptions<TSchema extends QueryStatesKitSchema> = {\n /** Parser map used by `nuqs/useQueryStates`. */\n schema: TSchema;\n /** Default values used by reset helpers. */\n defaults: Partial<Values<TSchema>>;\n /** Optional behavior defaults for URL update operations. */\n behavior?: QueryStatesKitBehavior;\n /** Optional extra options forwarded to `useQueryStates` declaration-time config. */\n hookOptions?: Partial<UseQueryStatesOptions<TSchema>>;\n};\n\n/**\n * Return shape of `useQueryStatesKit`.\n */\nexport type UseQueryStatesKitReturn<TSchema extends QueryStatesKitSchema> = {\n /** Parsed query-state values from `nuqs`. */\n query: Values<TSchema>;\n /** Partial query updater preserving untouched keys. */\n setQuery: (\n patch: QueryPatch<TSchema> | QueryPatchUpdater<TSchema>,\n options?: QueryUpdateOptions,\n ) => Promise<URLSearchParams>;\n /** Reset all keys or selected keys to configured defaults. */\n resetQuery: (\n keys?: ReadonlyArray<Extract<keyof Values<TSchema>, string>>,\n options?: QueryUpdateOptions,\n ) => Promise<URLSearchParams>;\n /** Clear all keys or selected keys from the URL by setting them to `null`. */\n clearQuery: (\n keys?: ReadonlyArray<Extract<keyof Values<TSchema>, string>>,\n options?: QueryUpdateOptions,\n ) => Promise<URLSearchParams>;\n /** Set a page-like key to a specific value. */\n setPage: (\n value: Values<TSchema>[QueryKey<TSchema>] | null,\n pageKey?: QueryKey<TSchema>,\n options?: QueryUpdateOptions,\n ) => Promise<URLSearchParams>;\n /** Reset a page-like key to defaults (or clear if no default exists). */\n resetPage: (\n pageKey?: QueryKey<TSchema>,\n options?: QueryUpdateOptions,\n ) => Promise<URLSearchParams>;\n /** Apply a partial update and reset page key in a single URL update. */\n updateAndResetPage: (\n patch: QueryPatch<TSchema> | QueryPatchUpdater<TSchema>,\n pageKey?: QueryKey<TSchema>,\n options?: QueryUpdateOptions,\n ) => Promise<URLSearchParams>;\n /** Raw `nuqs` setter for advanced usage. */\n setRawQuery: SetValues<TSchema>;\n};\n\n/**\n * Opinionated wrapper around `nuqs/useQueryStates` for filter/sort/pagination flows.\n *\n * Defaults:\n * - `history`: `\"replace\"`\n * - `shallow`: `true`\n * - `scroll`: `false`\n * - `pageKey`: `\"page\"`\n *\n * Integration note:\n * - Next.js: configure the nuqs Next adapter/provider per nuqs documentation.\n * - React Router: wrap your app with `NuqsAdapter` from `nuqs/adapters/react-router/v8`.\n *\n * @typeParam TSchema Query-state schema map based on `nuqs` parser builders.\n * @param options Hook configuration (`schema`, `defaults`, and optional behavior).\n * @returns Typed query state and helper actions.\n */\nexport function useQueryStatesKit<TSchema extends QueryStatesKitSchema>(\n options: QueryStatesKitOptions<TSchema>,\n): UseQueryStatesKitReturn<TSchema> {\n const { schema, defaults, behavior, hookOptions } = options;\n\n const resolvedBehavior = useMemo(\n () => ({\n history: behavior?.history ?? \"replace\",\n shallow: behavior?.shallow ?? true,\n scroll: behavior?.scroll ?? false,\n pageKey: behavior?.pageKey ?? \"page\",\n }),\n [behavior?.history, behavior?.pageKey, behavior?.scroll, behavior?.shallow],\n );\n\n const [query, setRawQuery] = useQueryStates(schema, {\n history: resolvedBehavior.history,\n shallow: resolvedBehavior.shallow,\n scroll: resolvedBehavior.scroll,\n ...hookOptions,\n });\n\n const resolveOptions = (\n override?: QueryUpdateOptions,\n ): QueryUpdateOptions => ({\n history: resolvedBehavior.history,\n shallow: resolvedBehavior.shallow,\n scroll: resolvedBehavior.scroll,\n ...override,\n });\n\n const setQuery: UseQueryStatesKitReturn<TSchema>[\"setQuery\"] = (\n patch,\n updateOptions,\n ) => {\n if (typeof patch === \"function\") {\n return setRawQuery(\n (previous) => patch(previous),\n resolveOptions(updateOptions),\n );\n }\n\n return setRawQuery(patch, resolveOptions(updateOptions));\n };\n\n const resetQuery: UseQueryStatesKitReturn<TSchema>[\"resetQuery\"] = (\n keys,\n updateOptions,\n ) => {\n const targetKeys =\n keys ?? (Object.keys(schema) as Array<QueryKey<TSchema>>);\n\n const resetPatch: Record<string, unknown> = {};\n for (const key of targetKeys) {\n resetPatch[key] =\n key in defaults ? defaults[key as keyof Values<TSchema>] : null;\n }\n\n return setRawQuery(\n resetPatch as QueryPatch<TSchema>,\n resolveOptions(updateOptions),\n );\n };\n\n const clearQuery: UseQueryStatesKitReturn<TSchema>[\"clearQuery\"] = (\n keys,\n updateOptions,\n ) => {\n if (!keys) {\n return setRawQuery(null, resolveOptions(updateOptions));\n }\n\n const clearPatch: Record<string, null> = {};\n for (const key of keys) {\n clearPatch[key] = null;\n }\n\n return setRawQuery(\n clearPatch as QueryPatch<TSchema>,\n resolveOptions(updateOptions),\n );\n };\n\n const setPage: UseQueryStatesKitReturn<TSchema>[\"setPage\"] = (\n value,\n pageKey,\n updateOptions,\n ) => {\n const key = (pageKey ?? resolvedBehavior.pageKey) as QueryKey<TSchema>;\n\n return setRawQuery(\n {\n [key]: value,\n } as QueryPatch<TSchema>,\n resolveOptions(updateOptions),\n );\n };\n\n const resetPage: UseQueryStatesKitReturn<TSchema>[\"resetPage\"] = (\n pageKey,\n updateOptions,\n ) => {\n const key = (pageKey ?? resolvedBehavior.pageKey) as QueryKey<TSchema>;\n const nextValue =\n key in defaults ? defaults[key as keyof Values<TSchema>] : null;\n\n return setRawQuery(\n {\n [key]: nextValue,\n } as QueryPatch<TSchema>,\n resolveOptions(updateOptions),\n );\n };\n\n const updateAndResetPage: UseQueryStatesKitReturn<TSchema>[\"updateAndResetPage\"] =\n (patch, pageKey, updateOptions) => {\n const key = (pageKey ?? resolvedBehavior.pageKey) as QueryKey<TSchema>;\n const nextPage =\n key in defaults ? defaults[key as keyof Values<TSchema>] : null;\n\n return setRawQuery((previous) => {\n const partialPatch =\n typeof patch === \"function\" ? patch(previous) : patch;\n if (!partialPatch) {\n return {\n [key]: nextPage,\n } as QueryPatch<TSchema>;\n }\n\n return {\n ...partialPatch,\n [key]: nextPage,\n };\n }, resolveOptions(updateOptions));\n };\n\n return {\n query,\n setQuery,\n resetQuery,\n clearQuery,\n setPage,\n resetPage,\n updateAndResetPage,\n setRawQuery,\n };\n}\n","import type {\n BlocksQueryKey,\n QueryKeyBuilder,\n QueryKeyFactory,\n QueryKeyPart,\n} from \"./types\";\n\nconst brandQueryKey = <const TParts extends readonly QueryKeyPart[]>(\n parts: TParts,\n): BlocksQueryKey<TParts> => parts as BlocksQueryKey<TParts>;\n\n/**\n * Creates a namespace-scoped query-key factory.\n *\n * Every key created by the returned factory starts with `namespace`, which makes\n * broad cache operations such as invalidating an entire domain predictable.\n *\n * @typeParam TNamespace Namespace segment prepended to every key.\n * @typeParam TDefinitions User-defined key builder map.\n * @param namespace Stable namespace for this cache domain.\n * @param define Receives a key builder and returns domain-specific key helpers.\n * @returns Namespace helpers plus the user-defined key helpers.\n *\n * @example\n * ```ts\n * export const userKeys = createQueryKeyFactory(\"user\", (key) => ({\n * current: () => key(\"current\"),\n * detail: (id: string) => key(\"detail\", id),\n * list: (filters: UserFilters) => key(\"list\", filters),\n * }));\n * ```\n */\nexport function createQueryKeyFactory<\n const TNamespace extends string,\n const TDefinitions extends Record<\n string,\n (...args: never[]) => BlocksQueryKey\n >,\n>(\n namespace: TNamespace,\n define: (key: QueryKeyBuilder<readonly [TNamespace]>) => TDefinitions,\n): QueryKeyFactory<TNamespace, TDefinitions> {\n const namespacedKey = <const TParts extends readonly QueryKeyPart[]>(\n ...parts: TParts\n ): BlocksQueryKey<readonly [TNamespace, ...TParts]> =>\n brandQueryKey([namespace, ...parts]);\n\n const key: QueryKeyBuilder<readonly [TNamespace]> = (...parts) =>\n namespacedKey(...parts);\n const definitions = define(key);\n\n return {\n ...definitions,\n all: () => namespacedKey(),\n key: namespacedKey,\n };\n}\n","import {\n type DefaultError,\n type QueryFunction,\n type SetDataOptions,\n type Updater,\n useQueryClient,\n} from \"@tanstack/react-query\";\nimport type {\n BlocksQueryKey,\n QueryClientKitFetchOptions,\n QueryClientKitFilters,\n UseQueryClientKitReturn,\n} from \"./types\";\n\nconst withQueryKey = <TFilters extends QueryClientKitFilters | undefined>(\n queryKey: BlocksQueryKey,\n filters: TFilters,\n) => ({\n ...filters,\n queryKey,\n});\n\n/**\n * Provides factory-first helpers around TanStack Query's `QueryClient`.\n *\n * The helper methods require keys produced by `createQueryKeyFactory`, keeping\n * cache reads, writes, and invalidations consistent across applications. The\n * raw TanStack client is still returned as `client` for advanced cases that are\n * intentionally outside the blocks-kit abstraction.\n *\n * @returns Typed cache helpers and the raw TanStack Query client.\n */\nexport function useQueryClientKit(): UseQueryClientKitReturn {\n const client = useQueryClient();\n\n return {\n client,\n invalidate: (key, filters, options) =>\n client.invalidateQueries(withQueryKey(key, filters), options),\n invalidateMany: async (keys, filters, options) => {\n await Promise.all(\n keys.map((key) =>\n client.invalidateQueries(withQueryKey(key, filters), options),\n ),\n );\n },\n cancel: (key, filters, options) =>\n client.cancelQueries(withQueryKey(key, filters), options),\n refetch: (key, filters, options) =>\n client.refetchQueries(withQueryKey(key, filters), options),\n remove: (key, filters) => client.removeQueries(withQueryKey(key, filters)),\n reset: (key, filters, options) =>\n client.resetQueries(withQueryKey(key, filters), options),\n getData: <TData = unknown>(key: BlocksQueryKey) =>\n client.getQueryData<TData>(key),\n setData: <TData = unknown>(\n key: BlocksQueryKey,\n updater: Updater<TData | undefined, TData | undefined>,\n options?: SetDataOptions,\n ): TData | undefined =>\n client.setQueryData<TData>(key, updater, options) as TData | undefined,\n getQueriesData: (key, filters) =>\n client.getQueriesData(withQueryKey(key, filters)),\n setQueriesData: (key, updater, filters) =>\n client.setQueriesData(withQueryKey(key, filters), updater),\n fetch: <\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TKey extends BlocksQueryKey = BlocksQueryKey,\n >(\n key: TKey,\n queryFn: QueryFunction<TQueryFnData, TKey>,\n options?: QueryClientKitFetchOptions<TQueryFnData, TError, TData, TKey>,\n ) =>\n client.fetchQuery({\n ...options,\n queryKey: key,\n queryFn,\n }),\n ensure: <\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TKey extends BlocksQueryKey = BlocksQueryKey,\n >(\n key: TKey,\n queryFn: QueryFunction<TQueryFnData, TKey>,\n options?: QueryClientKitFetchOptions<TQueryFnData, TError, TData, TKey>,\n ) =>\n client.ensureQueryData({\n ...options,\n queryKey: key,\n queryFn,\n }),\n };\n}\n","import { useState } from \"react\";\n\n/**\n * Manages a boolean state with convenience setters.\n *\n * @param initialValue Initial boolean value. Defaults to `false`.\n * @returns Boolean state, toggler, explicit setters, and raw `setValue`.\n */\nexport const useBoolean = (initialValue: boolean = false) => {\n const [value, setValue] = useState(initialValue);\n\n const toggle = () => setValue((previous) => !previous);\n const setTrue = () => setValue(true);\n const setFalse = () => setValue(false);\n\n return { value, toggle, setTrue, setFalse, setValue };\n};\n","import { useState } from \"react\";\n\n/**\n * Options accepted by the clipboard `copy` action.\n */\nexport type CopyOptions = {\n /** Callback executed after a successful copy operation. */\n onSuccess?: () => void;\n /** Callback executed when copy fails. */\n onError?: (error: Error) => void;\n /** Delay in milliseconds before `isCopying` resets to `false`. */\n resetAfterMs?: number;\n};\n\n/**\n * Provides clipboard copy state and actions for browser environments.\n *\n * Notes:\n * - Uses the async Clipboard API (`navigator.clipboard.writeText`).\n * - Returns `false` when API support is unavailable or copy fails.\n *\n * @returns Copy action, pending state, last copied text, and last error.\n */\nexport const useCopyToClipboard = () => {\n const [isCopying, setIsCopying] = useState(false);\n const [copiedText, setCopiedText] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n\n const copy = async (\n text: string,\n options: CopyOptions = {},\n ): Promise<boolean> => {\n if (isCopying) return false;\n\n const { onSuccess, onError, resetAfterMs = 500 } = options;\n\n if (!navigator?.clipboard?.writeText) {\n const clipboardError = new Error(\"Clipboard API not supported\");\n setError(clipboardError);\n onError?.(clipboardError);\n return false;\n }\n\n try {\n setIsCopying(true);\n setError(null);\n await navigator.clipboard.writeText(text);\n setCopiedText(text);\n onSuccess?.();\n return true;\n } catch (unknownError) {\n const copyError =\n unknownError instanceof Error\n ? unknownError\n : new Error(\"Unknown clipboard error\");\n setError(copyError);\n onError?.(copyError);\n return false;\n } finally {\n setTimeout(() => setIsCopying(false), resetAfterMs);\n }\n };\n\n return {\n isCopying,\n copiedText,\n error,\n copy,\n };\n};\n","import { useCallback, useEffect, useState } from \"react\";\n\n/**\n * Configuration options for `useCountdown`.\n */\nexport type UseCountdownOptions = {\n /** Starts the timer immediately when `true`. Defaults to `true`. */\n autoStart?: boolean;\n /** Tick interval in milliseconds. Defaults to `1000`. */\n intervalMs?: number;\n /** Called once when countdown reaches zero. */\n onComplete?: () => void;\n};\n\n/**\n * Runs a countdown timer with start/pause/reset controls.\n *\n * @param initialSeconds Initial duration in seconds.\n * @param options Countdown behavior options.\n * @returns Countdown state and control actions.\n */\nexport const useCountDown = (\n initialSeconds: number,\n options: UseCountdownOptions = {},\n) => {\n const { autoStart = true, intervalMs = 1000, onComplete } = options;\n const [remainingTime, setRemainingTime] = useState(initialSeconds);\n const [isRunning, setIsRunning] = useState(autoStart);\n\n useEffect(() => {\n if (!isRunning) return;\n if (remainingTime <= 0) {\n setIsRunning(false);\n onComplete?.();\n return;\n }\n\n const interval = setInterval(() => {\n setRemainingTime((previous) => Math.max(previous - 1, 0));\n }, intervalMs);\n\n return () => clearInterval(interval);\n }, [intervalMs, isRunning, onComplete, remainingTime]);\n\n const start = useCallback(() => setIsRunning(true), []);\n const pause = useCallback(() => setIsRunning(false), []);\n const reset = useCallback(\n (seconds?: number) => {\n setRemainingTime(seconds ?? initialSeconds);\n setIsRunning(autoStart);\n },\n [autoStart, initialSeconds],\n );\n\n return {\n remainingTime,\n isRunning,\n start,\n pause,\n reset,\n };\n};\n","import Fuse, { type FuseResult, type IFuseOptions } from \"fuse.js\";\n\nconst DEFAULT_THRESHOLD = 0.35;\nconst DEFAULT_DISTANCE = 100;\n\n/**\n * Returns default Fuse.js options suitable for UI search inputs.\n *\n * @typeParam T Row type.\n * @returns Default Fuse.js options.\n */\nexport const defaultFuseSearchOptions = <T>(): Partial<IFuseOptions<T>> => ({\n threshold: DEFAULT_THRESHOLD,\n distance: DEFAULT_DISTANCE,\n ignoreLocation: true,\n includeScore: true,\n});\n\n/**\n * Creates a Fuse.js search index for the given rows.\n *\n * @typeParam T Row type.\n * @param list Source rows.\n * @param options Fuse.js options.\n * @returns Fuse.js instance.\n */\nexport const createFuseSearcher = <T>(\n list: readonly T[],\n options: IFuseOptions<T>,\n): Fuse<T> => {\n return new Fuse([...list], options);\n};\n\n/**\n * Fuzzy-filters rows by query string.\n *\n * @typeParam T Row type.\n * @param list Source rows.\n * @param query Search query.\n * @param options Fuse.js options.\n * @returns Filtered rows. Returns all rows when query is empty.\n */\nexport const fuseFilter = <T>(\n list: readonly T[],\n query: string,\n options: IFuseOptions<T>,\n): T[] => {\n const trimmed = query.trim();\n if (!trimmed) {\n return [...list];\n }\n\n return createFuseSearcher(list, options)\n .search(trimmed)\n .map((result) => result.item);\n};\n\n/**\n * Fuzzy-searches rows and returns full Fuse.js metadata.\n *\n * @typeParam T Row type.\n * @param list Source rows.\n * @param query Search query.\n * @param options Fuse.js options.\n * @returns Fuse.js search results including scores and ref indices.\n */\nexport const fuseSearch = <T>(\n list: readonly T[],\n query: string,\n options: IFuseOptions<T>,\n): FuseResult<T>[] => {\n const trimmed = query.trim();\n if (!trimmed) {\n return list.map((item, refIndex) => ({\n item,\n refIndex,\n }));\n }\n\n return createFuseSearcher(list, options).search(trimmed);\n};\n\n/**\n * Fuzzy-searches using an existing Fuse.js index.\n *\n * @typeParam T Row type.\n * @param fuse Existing Fuse index.\n * @param list Source rows.\n * @param query Search query.\n * @returns Filtered rows. Returns all rows when query is empty.\n */\nexport const fuseSearchWithIndex = <T>(\n fuse: Fuse<T>,\n list: readonly T[],\n query: string,\n): T[] => {\n const trimmed = query.trim();\n if (!trimmed) {\n return [...list];\n }\n return fuse.search(trimmed).map((result) => result.item);\n};\n","import {\n createFuseSearcher,\n defaultFuseSearchOptions,\n fuseSearchWithIndex,\n} from \"../utils/fuse-search\";\nimport type { ColumnFuseFilterConfig } from \"./types\";\n\n/**\n * Applies multiple column-specific fuzzy filters sequentially.\n *\n * @typeParam T Row type.\n * @param list Source rows.\n * @param filters Column filter configuration list.\n * @returns Filtered rows after all column filters are applied.\n */\nexport const applyColumnFuseFilters = <T>(\n list: readonly T[],\n filters: ColumnFuseFilterConfig<T>[],\n): T[] =>\n filters.reduce<T[]>(\n (rows, filter) => {\n const trimmed = filter.query.trim();\n if (!trimmed || !filter.keys?.length) {\n return rows;\n }\n\n const options = { ...defaultFuseSearchOptions<T>(), keys: filter.keys };\n const fuse = createFuseSearcher(rows, options);\n return fuseSearchWithIndex(fuse, rows, trimmed);\n },\n [...list],\n );\n","import { useState, useEffect } from \"react\";\n\nexport function useDebounce<T>(value: T, delay: number): T {\n const [debouncedValue, setDebouncedValue] = useState<T>(value);\n\n useEffect(() => {\n const timer = setTimeout(() => setDebouncedValue(value), delay);\n return () => clearTimeout(timer);\n }, [value, delay]);\n\n return debouncedValue;\n}\n\nexport { applyColumnFuseFilters } from \"./util\";\nexport type { ColumnFuseFilterConfig } from \"./types\";\n","import { useMemo } from \"react\";\nimport type { IFuseOptions } from \"fuse.js\";\n\nimport { fuseFilter } from \"../utils/fuse-search\";\n\n/**\n * Memoized fuzzy search over a list.\n *\n * @typeParam T Row type.\n * @param list Source rows.\n * @param query Search query.\n * @param options Fuse.js options.\n * @returns Filtered rows.\n */\nexport const useFuseSearch = <T>(\n list: readonly T[],\n query: string,\n options: IFuseOptions<T>,\n): T[] => {\n return useMemo(\n () => fuseFilter(list, query, options),\n [list, query, options],\n );\n};\n","import { useMemo } from \"react\";\nimport Fuse, { type IFuseOptions } from \"fuse.js\";\n\n/**\n * Creates a memoized Fuse.js index for a list.\n *\n * @typeParam T Row type.\n * @param list Source rows.\n * @param options Fuse.js options.\n * @returns Memoized Fuse index.\n */\nexport const useFuseIndex = <T>(\n list: readonly T[],\n options: IFuseOptions<T>,\n): Fuse<T> => useMemo(() => new Fuse([...list], options), [list, options]);\n","import type { FuseResult } from \"fuse.js\";\nimport Fuse from \"fuse.js\";\nimport { useMemo } from \"react\";\nimport type { FuseSearchOptions } from \"./types\";\n\nexport function useDebouncedFuseFilter<T extends Record<string, unknown>>(\n items: T[],\n searchTerm: string,\n options: FuseSearchOptions<T> = {},\n): T[] {\n return useMemo(() => {\n if (!searchTerm.trim()) {\n return items;\n }\n\n const fuse = new Fuse(items, {\n threshold: 0.3,\n ...options,\n });\n\n const results: FuseResult<T>[] = fuse.search(searchTerm);\n return results.map((result) => result.item);\n }, [items, searchTerm, options]);\n}\n","import { useEffect } from \"react\";\n\nexport type KeyboardShortcutCombo = string | false;\n\ntype ParsedCombo = {\n key: string;\n mod: boolean;\n shift: boolean;\n alt: boolean;\n};\n\nconst EDITABLE_TAGS = new Set([\"INPUT\", \"TEXTAREA\", \"SELECT\"]);\n\nfunction isEditableTarget(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLElement)) return false;\n if (target.isContentEditable) return true;\n if (EDITABLE_TAGS.has(target.tagName)) {\n const type = (target as HTMLInputElement).type;\n return type !== \"checkbox\" && type !== \"radio\" && type !== \"button\";\n }\n return false;\n}\n\nfunction parseCombo(combo: string): ParsedCombo {\n const parts = combo\n .toLowerCase()\n .split(\"+\")\n .map((p) => p.trim())\n .filter(Boolean);\n const parsed: ParsedCombo = {\n key: \"\",\n mod: false,\n shift: false,\n alt: false,\n };\n for (const part of parts) {\n if (\n part === \"mod\" ||\n part === \"cmd\" ||\n part === \"ctrl\" ||\n part === \"meta\"\n ) {\n parsed.mod = true;\n } else if (part === \"shift\") {\n parsed.shift = true;\n } else if (part === \"alt\" || part === \"option\") {\n parsed.alt = true;\n } else {\n parsed.key = part;\n }\n }\n return parsed;\n}\n\nfunction matchesCombo(parsed: ParsedCombo, event: KeyboardEvent): boolean {\n const isMac =\n typeof navigator !== \"undefined\" &&\n /Mac|iPod|iPhone|iPad/.test(navigator.platform);\n const modPressed = isMac ? event.metaKey : event.ctrlKey;\n if (parsed.mod !== modPressed) return false;\n if (parsed.shift !== event.shiftKey) return false;\n if (parsed.alt !== event.altKey) return false;\n return event.key.toLowerCase() === parsed.key;\n}\n\n/**\n * Bind a keyboard combo to a handler at the document level.\n *\n * - `combo` follows the `\"mod+.\" | \"ctrl+shift+k\" | \"escape\" | false` syntax.\n * `mod` resolves to `Cmd` on macOS and `Ctrl` elsewhere. Pass `false` to\n * disable the listener entirely.\n * - The handler is suppressed when focus is inside an editable element\n * (input, textarea, contenteditable) unless `allowInEditable` is set.\n * - `event.preventDefault()` is called when a match fires, so the browser\n * does not also handle the shortcut (e.g. open the find bar).\n */\nexport function useKeyboardShortcut(\n combo: KeyboardShortcutCombo,\n handler: (event: KeyboardEvent) => void,\n options: { allowInEditable?: boolean } = {},\n): void {\n const { allowInEditable = false } = options;\n\n useEffect(() => {\n if (!combo) return;\n const parsed = parseCombo(combo);\n\n const onKeyDown = (event: KeyboardEvent) => {\n if (!allowInEditable && isEditableTarget(event.target)) return;\n if (!matchesCombo(parsed, event)) return;\n event.preventDefault();\n handler(event);\n };\n\n document.addEventListener(\"keydown\", onKeyDown);\n return () => document.removeEventListener(\"keydown\", onKeyDown);\n }, [combo, handler, allowInEditable]);\n}\n","import { useCallback, useEffect, useState } from \"react\";\n\n/**\n * Storage adapter used by `useLanguage`.\n */\nexport interface LanguageStorage {\n /** Reads a string value by key. */\n get: (key: string) => string | null;\n /** Writes a string value by key. */\n set: (key: string, value: string) => void;\n}\n\nconst localStorageAdapter: LanguageStorage = {\n get(key) {\n if (typeof window === \"undefined\") return null;\n return window.localStorage.getItem(key);\n },\n set(key, value) {\n if (typeof window === \"undefined\") return;\n window.localStorage.setItem(key, value);\n },\n};\n\n/**\n * Configuration options for `useLanguage`.\n */\nexport type UseLanguageOptions = {\n /** Storage key used for persistence. Defaults to `\"language\"`. */\n storageKey?: string;\n /** Fallback language when storage is empty. Defaults to `\"en\"`. */\n defaultLanguage?: string;\n /** Custom storage adapter. */\n storage?: LanguageStorage;\n /** Optional side effect invoked on language change. */\n onLanguageChange?: (language: string) => void;\n};\n\n/**\n * Manages a persisted language value with pluggable storage.\n *\n * @param options Hook options including storage adapter and callbacks.\n * @returns Current language and mutation helpers.\n */\nexport const useLanguage = (options: UseLanguageOptions = {}) => {\n const {\n storageKey = \"language\",\n defaultLanguage = \"en\",\n storage = localStorageAdapter,\n onLanguageChange,\n } = options;\n\n const [language, setLanguageState] = useState<string>(() => {\n const storedValue = storage.get(storageKey);\n return storedValue || defaultLanguage;\n });\n\n useEffect(() => {\n storage.set(storageKey, language);\n onLanguageChange?.(language);\n }, [language, onLanguageChange, storage, storageKey]);\n\n const setLanguage = useCallback((nextLanguage: string) => {\n setLanguageState(nextLanguage);\n }, []);\n\n return {\n language,\n setLanguage,\n changeLanguage: setLanguage,\n };\n};\n","import { useEffect, useState } from \"react\";\n\n/**\n * Options accepted by `useMediaQuery`.\n */\nexport type UseMediaQueryOptions = {\n /** SSR fallback value before client hydration. Defaults to `false`. */\n defaultValue?: boolean;\n};\n\n/**\n * Tracks whether a CSS media query currently matches.\n *\n * @param query Media query string (for example, `\"(min-width: 768px)\"`).\n * @param options SSR fallback options.\n * @returns `true` when query matches; otherwise `false`.\n */\nexport const useMediaQuery = (\n query: string,\n options: UseMediaQueryOptions = {},\n): boolean => {\n const { defaultValue = false } = options;\n\n const getMatches = (): boolean => {\n if (typeof window === \"undefined\") {\n return defaultValue;\n }\n return window.matchMedia(query).matches;\n };\n\n const [matches, setMatches] = useState<boolean>(getMatches);\n\n useEffect(() => {\n if (typeof window === \"undefined\") {\n return;\n }\n\n const mediaQueryList = window.matchMedia(query);\n const onChange = (event: MediaQueryListEvent) => setMatches(event.matches);\n\n setMatches(mediaQueryList.matches);\n mediaQueryList.addEventListener(\"change\", onChange);\n\n return () => mediaQueryList.removeEventListener(\"change\", onChange);\n }, [query]);\n\n return matches;\n};\n","import { useMemo } from \"react\";\n\n/**\n * Breadcrumb-like segment representation derived from a pathname.\n */\nexport type PathSegment = {\n /** Segment URL up to current index (for example, `/projects/123`). */\n href: string;\n /** Human-friendly label produced by the formatter. */\n label: string;\n /** Raw segment text from the pathname. */\n segment: string;\n /** Zero-based segment index. */\n index: number;\n};\n\n/**\n * Options for `getPathSegments` and `usePathSegments`.\n */\nexport type UsePathSegmentsOptions = {\n /** Custom label formatter for each raw segment. */\n formatter?: (segment: string) => string;\n};\n\n/**\n * Default segment label formatter.\n *\n * Converts kebab-case path parts to title case labels.\n *\n * @param segment Raw path segment.\n * @returns Human-friendly label.\n */\nexport const defaultPathSegmentFormatter = (segment: string): string =>\n segment\n .split(\"-\")\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\" \");\n\n/**\n * Parses a pathname into breadcrumb-like segments.\n *\n * @param pathname Source pathname.\n * @param options Label formatting options.\n * @returns Ordered list of path segments.\n */\nexport const getPathSegments = (\n pathname: string,\n options: UsePathSegmentsOptions = {},\n): PathSegment[] => {\n const { formatter = defaultPathSegmentFormatter } = options;\n const pathArray = pathname.split(\"/\").filter(Boolean);\n\n return pathArray.map((segment, index) => ({\n href: `/${pathArray.slice(0, index + 1).join(\"/\")}`,\n label: formatter(segment),\n segment,\n index,\n }));\n};\n\n/**\n * Memoized hook wrapper for `getPathSegments`.\n *\n * @param pathname Source pathname.\n * @param options Label formatting options.\n * @returns Memoized list of path segments.\n */\nexport const usePathSegments = (\n pathname: string,\n options: UsePathSegmentsOptions = {},\n): PathSegment[] => {\n return useMemo(() => getPathSegments(pathname, options), [options, pathname]);\n};\n","import { useState, useEffect, useRef, type RefObject } from \"react\";\n\nexport function usePopoverWidth(): [\n RefObject<HTMLButtonElement | null>,\n number | undefined,\n] {\n const [popoverWidth, setPopoverWidth] = useState<number | undefined>(\n undefined,\n );\n const buttonRef = useRef<HTMLButtonElement | null>(null);\n\n useEffect(() => {\n const updateWidth = () => {\n if (buttonRef.current) {\n setPopoverWidth(buttonRef.current.offsetWidth);\n }\n };\n\n updateWidth();\n window.addEventListener(\"resize\", updateWidth);\n\n return () => window.removeEventListener(\"resize\", updateWidth);\n }, []);\n\n return [buttonRef, popoverWidth];\n}\n","import { AUTH_ENDPOINTS } from \"@/constants/endpoint.constant\";\nimport { iamClient } from \"@/lib/http/instances\";\n\nexport class AuthService {\n logout() {\n return iamClient.post(AUTH_ENDPOINTS.LOGOUT, {});\n }\n}\n\nexport const authService = new AuthService();\n","import { announceSignOut, clearTenantClaims } from \"@/lib/tenant-ownership\";\nimport { authService } from \"@/services/auth.service\";\nimport { useAuthStore } from \"@/store/auth.store\";\nimport { useProjectStore } from \"@/store/project.store\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { useCallback } from \"react\";\n\n/** Local clean-up for any sign-out: other tabs are told, and no claim outlives the session. */\nconst forgetSession = (): void => {\n clearTenantClaims();\n announceSignOut();\n};\n\nexport const useLogout = () => {\n return useMutation({\n mutationKey: [\"logout\"],\n mutationFn: authService.logout,\n // Done here rather than in each logout control, so every way out of the app clears it.\n onSuccess: forgetSession,\n });\n};\n\n/**\n * Signs out from a screen the user cannot otherwise leave, such as a session that cannot be\n * returned to the console. Unlike the Logout button it leaves even when IAM refuses the logout\n * call, which a session that has already ended does.\n */\nexport const useSignOut = () =>\n useCallback(() => {\n void authService\n .logout()\n .catch(() => undefined)\n .finally(() => {\n forgetSession();\n useProjectStore.getState().resetProjectStore();\n useAuthStore.getState().resetAuthStore();\n window.location.replace(`${window.location.origin}/login`);\n });\n }, []);\n","import { BlocksAppLayoutContext } from \"@/contexts\";\nimport type { AppConfigStoreState } from \"@/store\";\nimport { useContext } from \"react\";\nimport { useStore } from \"zustand\";\n\nexport const useBlocksAppConfigStore = <T>(\n selector: (state: AppConfigStoreState) => T,\n): T => {\n const context = useContext(BlocksAppLayoutContext);\n\n if (!context) {\n throw new Error(\n \"useBlocksAppConfigStore must be used within a BlocksAppLayout\",\n );\n }\n return useStore(context, selector);\n};\n","type BlocksIconProps = {\n size: number;\n color?: string;\n};\n\nexport function BlocksIcon({ size, color = \"#2D86C7\" }: BlocksIconProps) {\n return (\n <svg\n width={size}\n height={size}\n viewBox=\"0 0 246 360\"\n fill=\"none\"\n xmlns=\"http://www.w3.org/2000/svg\"\n >\n <path\n d=\"M245.455 68.1627V129.877L168.982 156.67V93.9638L245.455 68.1627Z\"\n fill={color}\n />\n <path\n d=\"M240.389 62.3805L165.49 87.6573L5.30933 24.2563L85.3314 0L240.389 62.3805Z\"\n fill={color}\n />\n <path\n d=\"M161.797 93.8295V156.43L81.1141 122.607V188.07L0 152.738V29.6846L161.797 93.8295Z\"\n fill={color}\n />\n <path\n d=\"M76.4728 266.036L0 291.837V230.123L76.4728 203.329V266.036Z\"\n fill={color}\n />\n <path\n d=\"M160.123 360L5.07178 297.619L79.964 272.343L240.145 335.744L160.123 360Z\"\n fill={color}\n />\n <path\n d=\"M245.454 330.315L83.657 266.17V203.57L164.34 237.393V171.93L245.454 207.262V330.315Z\"\n fill={color}\n />\n </svg>\n );\n}\n","import { type Theme } from \"@/lib/theme\";\nimport { useAppSettingsStore } from \"@/store\";\n\nexport function useTheme() {\n const {\n settings: { theme },\n systemTheme,\n setSettings,\n setSystemTheme,\n } = useAppSettingsStore();\n\n const resolvedTheme: Exclude<Theme, \"system\"> =\n theme === \"system\" ? systemTheme : theme;\n\n const setTheme = (newTheme: Theme) => {\n setSettings({ theme: newTheme });\n // applyTheme(resolved) ← remove this; ThemeProvider's useEffect handles it\n if (newTheme === \"system\") {\n const current = window.matchMedia(\"(prefers-color-scheme: dark)\").matches\n ? \"dark\"\n : \"light\";\n setSystemTheme(current);\n }\n };\n\n return { theme, setTheme, resolvedTheme };\n}\n\n// Re-export so consumers importing Theme from here don't break\nexport type { Theme } from \"@/lib/theme\";\n","import { BlocksIcon } from \"@/assets/icons/blocks-icon\";\nimport { useTheme } from \"./use-theme\";\n\nexport function useIcon() {\n const { resolvedTheme } = useTheme();\n return resolvedTheme === \"dark\" ? (\n <BlocksIcon size={32} color=\"#DCDCDC\" />\n ) : (\n <BlocksIcon size={32} color=\"#2D86C7\" />\n );\n}\n","import { IAM_ENDPOINTS } from \"@/constants/endpoint.constant\";\nimport { getRuntimeEnv } from \"@/lib\";\n\nexport interface InitiateParams {\n clientId: string;\n redirectUri: string;\n forwardedTo: string;\n}\n\nclass InitiateService {\n async fetchRedirectUrl(\n { clientId, redirectUri, forwardedTo }: InitiateParams,\n signal?: AbortSignal,\n ): Promise<string> {\n const blocksKey = getRuntimeEnv(\"BLOCKS_X_BLOCKS_KEY\");\n const iamBaseUrl = getRuntimeEnv(\"userBaseUrl\");\n\n const params = new URLSearchParams({\n \"x-blocks-key\": blocksKey,\n clientId,\n redirectUri,\n forwardedTo,\n });\n const headers: Record<string, string> = { Accept: \"application/json\" };\n if (blocksKey) headers[\"X-Blocks-Key\"] = blocksKey;\n\n const response = await fetch(\n `${iamBaseUrl}${IAM_ENDPOINTS.INITIATE}?${params}`,\n { headers, signal },\n );\n\n if (!response.ok) {\n throw new Error(`Initiate request failed — HTTP ${response.status}`);\n }\n\n const data = await response.json();\n if (!data.redirect_uri)\n throw new Error(\"No redirect_uri in initiate response\");\n\n return data.redirect_uri as string;\n }\n}\n\nexport const initiateService = new InitiateService();\n","import {\n initiateService,\n type InitiateParams,\n} from \"@/services/initiate.service\";\nimport { useCallback, useEffect } from \"react\";\nimport { useQuery } from \"@tanstack/react-query\";\n\nexport function useInitiateRedirect({\n clientId,\n redirectUri,\n forwardedTo,\n}: InitiateParams) {\n const query = useQuery({\n queryKey: [\"initiate\", \"redirect\", clientId, redirectUri, forwardedTo],\n queryFn: () =>\n initiateService.fetchRedirectUrl({ clientId, redirectUri, forwardedTo }),\n staleTime: Infinity,\n gcTime: Infinity,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n retry: false,\n });\n\n useEffect(() => {\n if (query.data) {\n window.location.replace(query.data);\n }\n }, [query.data]);\n\n const error =\n query.error instanceof Error\n ? query.error\n : query.error\n ? new Error(\"Failed to redirect\")\n : null;\n\n return { isLoading: query.isLoading, error };\n}\n\ninterface UsePrefetchRedirectOptions extends InitiateParams {\n enabled?: boolean;\n}\n\nexport function usePrefetchRedirect({\n clientId,\n redirectUri,\n forwardedTo,\n enabled = true,\n}: UsePrefetchRedirectOptions) {\n const query = useQuery({\n queryKey: [\"initiate\", \"prefetch\", clientId, redirectUri, forwardedTo],\n queryFn: () =>\n initiateService.fetchRedirectUrl({ clientId, redirectUri, forwardedTo }),\n enabled,\n staleTime: Infinity,\n gcTime: Infinity,\n refetchOnMount: false,\n refetchOnWindowFocus: false,\n retry: false,\n });\n\n const redirect = useCallback(() => {\n if (query.data) window.location.replace(query.data);\n }, [query.data]);\n\n return {\n isFetching: query.isFetching,\n isReady: !query.isFetching && !!query.data,\n redirect,\n };\n}\n","import { useAppSettingsStore } from \"@/store\";\n\nexport function useLanguageSwitcher() {\n const {\n settings: { language },\n setSettings,\n } = useAppSettingsStore();\n\n const changeLanguage = (newLanguage: string) => {\n setSettings({ language: newLanguage });\n };\n return { language, changeLanguage };\n}\n","import { IAM_ENDPOINTS } from \"@/constants/endpoint.constant\";\nimport { iamClient } from \"@/lib/http/instances\";\nimport { getRuntimeEnv } from \"@/lib/runtime-env\";\n\n/** Which page the initiate response should point at. */\nexport type AuthFlow = \"login\" | \"signup\";\n\nexport interface LoginStartParams {\n redirectUri: string;\n /** Defaults to `login`, which is sent as no `flow` parameter at all. */\n flow?: AuthFlow;\n}\n\nexport interface LoginStartResponse {\n redirect_uri?: string;\n /** Echoed by IAM for `flow=signup`. Absent on servers that predate the parameter. */\n flow?: string;\n}\n\nclass LoginService {\n // One request shape serves both flows — the client, the tenant and the redirect URI\n // are identical, and only the page IAM points back at differs. `flow` is appended\n // only when it is signup, so a login request goes out byte-identical to before.\n startFlow({\n redirectUri,\n flow,\n }: LoginStartParams): Promise<LoginStartResponse> {\n const blocksKey = getRuntimeEnv(\"BLOCKS_X_BLOCKS_KEY\");\n const clientId = getRuntimeEnv(\"BLOCKS_OIDC_CLIENT_ID\");\n\n const params = new URLSearchParams({\n \"x-blocks-key\": blocksKey,\n clientId,\n redirectUri,\n });\n if (flow === \"signup\") params.set(\"flow\", flow);\n\n const headers: Record<string, string> = {};\n if (blocksKey) headers[\"X-Blocks-Key\"] = blocksKey;\n\n return iamClient.get<LoginStartResponse>(\n `${IAM_ENDPOINTS.INITIATE}?${params.toString()}`,\n headers,\n );\n }\n}\n\nexport const loginService = new LoginService();\n","import { useCallback, useRef } from \"react\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { loginService, type LoginStartParams } from \"@/services/login.service\";\n\nexport interface UseLoginResult {\n start: () => void;\n isLoading: boolean;\n error: Error | null;\n}\n\n// `useRef` is the synchronous dedupe guard: React batches the state update\n// triggered by `mutate()`, so `mutation.isPending` does not flip to `true`\n// within the same event tick in which `start()` was first invoked. Without\n// this guard, rapid clicks would each fire a fresh `mutate()`.\nexport function useLogin(): UseLoginResult {\n const inFlight = useRef(false);\n\n const mutation = useMutation({\n mutationKey: [\"login\", \"start\"],\n mutationFn: (params: LoginStartParams) => loginService.startFlow(params),\n onSuccess: (data) => {\n if (data?.redirect_uri) {\n window.location.href = data.redirect_uri;\n }\n },\n onError: (err) => {\n console.error(\"Error initiating login:\", err);\n },\n onSettled: () => {\n inFlight.current = false;\n },\n });\n\n const start = useCallback(() => {\n if (inFlight.current) return;\n if (mutation.isPending) return;\n inFlight.current = true;\n mutation.mutate({\n redirectUri: `${window.location.origin}/login/callback`,\n });\n }, [mutation]);\n\n const error = mutation.error instanceof Error ? mutation.error : null;\n\n return {\n start,\n isLoading: mutation.isPending,\n error,\n };\n}\n","import { ORGANIZATION_ENDPOINTS } from \"@/constants/endpoint.constant\";\nimport { iamClient } from \"@/lib/http/instances\";\nimport type { GetSignUpSettingResponse } from \"@/models/signup.model\";\n\nclass SignUpService {\n // Anonymous on the IAM side — the tenant is resolved from the X-Blocks-Key\n // header, which `iamClient` already attaches. That is what lets the login\n // page ask whether signup is open before anyone has authenticated.\n getSignUpSetting(): Promise<GetSignUpSettingResponse> {\n return iamClient.get<GetSignUpSettingResponse>(\n ORGANIZATION_ENDPOINTS.GET_SIGNUP_SETTING,\n );\n }\n}\n\nexport const signUpService = new SignUpService();\n","import { useCallback, useRef } from \"react\";\nimport { useMutation, useQuery } from \"@tanstack/react-query\";\nimport { getRuntimeEnv } from \"@/lib/runtime-env\";\nimport { loginService } from \"@/services/login.service\";\nimport { signUpService } from \"@/services/signup.service\";\n\nexport interface UseSignUpAffordanceResult {\n /** Whether the tenant offers a signup page worth linking to. */\n canSignUp: boolean;\n isLoading: boolean;\n}\n\n/**\n * Whether to render a Sign up control at all.\n *\n * Asked before anyone clicks, so it stays a settings lookup rather than an initiate\n * call. It fails closed: an unreachable or unauthorized settings endpoint means \"no\n * affordance\", not a retry storm on an unauthenticated page.\n *\n * `isSignUpEnable` is already the OR of the email and SSO flags server-side, so there\n * is nothing further to combine here. The one case it cannot see — SSO signup enabled\n * with no social provider configured, which renders an empty card — is caught by IAM\n * when the button is actually clicked.\n */\nexport function useSignUpAffordance(): UseSignUpAffordanceResult {\n const tenantId = getRuntimeEnv(\"BLOCKS_X_BLOCKS_KEY\");\n\n const { data, isLoading } = useQuery({\n queryKey: [\"sign-up-setting\", tenantId],\n queryFn: () => signUpService.getSignUpSetting(),\n enabled: !!tenantId,\n retry: false,\n staleTime: 5 * 60 * 1000,\n });\n\n return {\n canSignUp: !!tenantId && (data?.isSignUpEnable ?? false),\n isLoading: !!tenantId && isLoading,\n };\n}\n\nexport interface UseSignUpRedirectResult {\n start: () => void;\n isLoading: boolean;\n error: Error | null;\n}\n\n/**\n * Sends the user to IAM's signup page.\n *\n * Deliberately the same shape as `useLogin`: ask IAM where to go, then go there. The\n * URL is never built here, because IAM has to validate the clientId and redirect URI\n * against the database first — the redirect URI in particular rides all the way into\n * the activation email, and an unvalidated one silently returns the user to whichever\n * client happens to be first for the tenant.\n */\nexport function useSignUpRedirect(): UseSignUpRedirectResult {\n // Same synchronous guard as useLogin: React batches the state update from `mutate()`,\n // so `isPending` has not flipped yet within the tick the first click fires in.\n const inFlight = useRef(false);\n\n const mutation = useMutation({\n mutationKey: [\"signup\", \"start\"],\n mutationFn: async () => {\n const data = await loginService.startFlow({\n redirectUri: `${window.location.origin}/login/callback`,\n flow: \"signup\",\n });\n\n // An IAM that predates the `flow` parameter ignores it and answers with the\n // authorize URL, which would drop the user on the login page looking like a UI\n // bug rather than a version mismatch. We know what we asked for, so check what\n // came back before navigating anywhere.\n const isSignUpUrl =\n data?.flow === \"signup\" ||\n !!data?.redirect_uri?.includes(\"/oidc/signup/\");\n\n if (!data?.redirect_uri || !isSignUpUrl) {\n throw new Error(\n \"Signup is unavailable — the identity service did not return a signup URL\",\n );\n }\n\n return data.redirect_uri;\n },\n onSuccess: (redirectUri) => {\n window.location.href = redirectUri;\n },\n onError: (err) => {\n console.error(\"Error initiating signup:\", err);\n },\n onSettled: () => {\n inFlight.current = false;\n },\n });\n\n const start = useCallback(() => {\n if (inFlight.current) return;\n if (mutation.isPending) return;\n inFlight.current = true;\n mutation.mutate();\n }, [mutation]);\n\n const error = mutation.error instanceof Error ? mutation.error : null;\n\n return {\n start,\n isLoading: mutation.isPending,\n error,\n };\n}\n","import { useBlocksAppConfigStore } from \"@/hooks/use-blocks-app-config-store\";\n\nexport function useLogo() {\n const {\n config: { appLogoUrl },\n } = useBlocksAppConfigStore((state) => state);\n\n const resolveLogo = (variant: \"light\" | \"dark\") => {\n if (!appLogoUrl) return undefined;\n if (typeof appLogoUrl === \"string\") return appLogoUrl;\n return appLogoUrl[variant];\n };\n\n const appLightLogo = resolveLogo(\"light\");\n const appDarkLogo = resolveLogo(\"dark\");\n\n return {\n appLightLogo,\n appDarkLogo,\n };\n}\n","import { notificationClient } from \"@/lib/http/instances\";\nimport type { INotification, INotificationConfig } from \"@/models\";\nimport {\n NOTIFICATION_ENDPOINTS,\n NOTIFICATION_CONFIG_ENDPOINTS,\n} from \"@/constants/endpoint.constant\";\n\nexport class NotificationService {\n private readonly notificationService = notificationClient;\n\n getNotifications = (\n pageNumber: number,\n pageSize: number,\n ): Promise<{\n unReadNotificationsCount: number;\n totalNotificationsCount: number;\n notifications: INotification[];\n }> => {\n const params = new URLSearchParams({\n page: String(pageNumber - 1),\n pageSize: String(pageSize),\n });\n return this.notificationService.get(\n `${NOTIFICATION_ENDPOINTS.GET_NOTIFICATIONS}?${params}`,\n );\n };\n\n markAsRead = (\n notificationId: string,\n ): Promise<{ errors: null | unknown; isSuccess: boolean }> => {\n return this.notificationService.post(NOTIFICATION_ENDPOINTS.MARK_AS_READ, {\n id: notificationId,\n });\n };\n\n markAllNotificationsAsRead = (): Promise<{\n errors: null | unknown;\n isSuccess: boolean;\n }> => {\n return this.notificationService.post(\n NOTIFICATION_ENDPOINTS.MARK_ALL_AS_READ,\n {},\n );\n };\n\n getNotificationConfig = (\n config: INotificationConfig,\n message: string,\n ): void => {\n let parsedMessage: unknown = message;\n if (typeof message === \"string\") {\n try {\n parsedMessage = JSON.parse(message);\n } catch {\n parsedMessage = message;\n }\n }\n const notificationEvent = new CustomEvent(config.notifyMethod, {\n detail: {\n method: config.notifyMethod,\n message: parsedMessage,\n timestamp: new Date().toISOString(),\n config: config,\n },\n });\n window.dispatchEvent(notificationEvent);\n };\n\n getNotificationConfigs = (\n page: number = 0,\n pageSize: number = 10,\n ): Promise<{\n configurations: INotificationConfig[];\n totalCount: number;\n errors: null | unknown;\n isSuccess: boolean;\n }> => {\n const url = `${NOTIFICATION_CONFIG_ENDPOINTS.GET_CONFIGS}?page=${page}&pageSize=${pageSize}`;\n return this.notificationService.get(url);\n };\n}\n\nexport const notificationService = new NotificationService();\n","import { notificationService } from \"@/services/notification.service\";\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\n\nexport const useGetNotifications = (pageNumber: number, pageSize: number) => {\n return useQuery({\n queryKey: [\"notifications\", pageNumber, pageSize],\n queryFn: () => notificationService.getNotifications(pageNumber, pageSize),\n staleTime: 0,\n });\n};\n\nexport const useMarkAsRead = () => {\n return useMutation({\n mutationKey: [\"markAsRead\"],\n mutationFn: notificationService.markAsRead,\n });\n};\n\nexport const useMarkAllAsRead = () => {\n const queryClient = useQueryClient();\n return useMutation({\n mutationKey: [\"markAllAsRead\"],\n mutationFn: notificationService.markAllNotificationsAsRead,\n onSuccess: () => {\n queryClient.invalidateQueries({ queryKey: [\"notifications\"] });\n },\n });\n};\n\nexport const useGetBlocksNotificationConfig = (\n page: number = 0,\n pageSize: number = 100,\n) => {\n return useQuery({\n queryKey: [\"blocksNotificationConfigs\", page, pageSize],\n queryFn: () => notificationService.getNotificationConfigs(page, pageSize),\n });\n};\n","import { iamClient } from \"@/lib/http\";\nimport type { IGetMyOrganizationsResponse } from \"@/models\";\nimport { ORGANIZATION_ENDPOINTS } from \"@/constants/endpoint.constant\";\n\nexport class OrganizationService {\n getMyOrganizations(): Promise<IGetMyOrganizationsResponse> {\n return iamClient.get(ORGANIZATION_ENDPOINTS.GET_MY_ORGANIZATIONS);\n }\n}\n\nexport const organizationService = new OrganizationService();\n","import { OrganizationService } from \"./organization.service\";\n\nclass IAMService {\n constructor(public organization: OrganizationService) {}\n}\n\nexport const iamService = new IAMService(new OrganizationService());\n","import { iamService } from \"@/services/iam.service\";\nimport { useQuery } from \"@tanstack/react-query\";\n\nexport const useGetMyOrganizations = () => {\n return useQuery({\n queryKey: [\"organizations\", \"my\"],\n queryFn: () => iamService.organization.getMyOrganizations(),\n enabled: false,\n });\n};\n","import { logicClient } from \"@/lib/http/instances\";\nimport type {\n IProjectGroup,\n IGetProjectResponse,\n IDisableProjectPayload,\n IDisableProjectResponse,\n IUpdateTenantGroupPayload,\n IUpdateProjectResponse,\n IEnvRepository,\n IUpdateProjectPayload,\n IValidateCnameProjectPayload,\n IValidateCnameProjectResponse,\n} from \"@/models\";\nimport { PROJECT_ENDPOINTS } from \"@/constants/endpoint.constant\";\nimport { getRuntimeEnv, HttpClient } from \"@/lib\";\n\n//Exception only for OS.\nconst logicClientForOS = new HttpClient({\n baseURL: () => getRuntimeEnv(\"BLOCKS_LOGIC_BASE_URL\"),\n blocksKey: () => getRuntimeEnv(\"BLOCKS_X_BLOCKS_KEY\"),\n});\n\nexport class ProjectService {\n getProjects(\n page = 0,\n pageSize = 100,\n tenantGroupId = \"\",\n ): Promise<IProjectGroup[]> {\n const url = `${PROJECT_ENDPOINTS.GETS}?page=${page}&pageSize=${pageSize}&tenantGroupId=${tenantGroupId}`;\n return logicClient.get(url);\n }\n\n // Resolves the project from the caller's auth context — there is no parameter\n // to pass; the token's tenant selects the project.\n getProject(): Promise<IGetProjectResponse> {\n return logicClient.get(PROJECT_ENDPOINTS.GET);\n }\n\n getEnvRepositories(): Promise<{\n data: IEnvRepository[];\n errors: unknown | null;\n isSuccess: boolean;\n }> {\n const url = `${PROJECT_ENDPOINTS.REPOS_LIST}`;\n return logicClientForOS.get(url);\n }\n\n repoUpdate(payload: {\n projectKey: string;\n projectEnv: string;\n repoWithDomains: {\n repoId: string;\n repoUrl: string;\n customDeploymentDomain: string;\n }[];\n }): Promise<{\n errors: unknown | null;\n isSuccess: boolean;\n }> {\n return logicClientForOS.post(PROJECT_ENDPOINTS.REPO_UPDATE, payload);\n }\n\n updateTenantGroup(\n payload: IUpdateTenantGroupPayload,\n ): Promise<IUpdateProjectResponse> {\n return logicClient.post(PROJECT_ENDPOINTS.UPDATE_TENANT_GROUP, payload);\n }\n\n updateProject(\n payload: IUpdateProjectPayload,\n ): Promise<IUpdateProjectResponse> {\n return logicClient.post(PROJECT_ENDPOINTS.UPDATE_PROJECT, payload);\n }\n\n disableProject(\n payload: IDisableProjectPayload,\n ): Promise<IDisableProjectResponse> {\n return logicClient.post(PROJECT_ENDPOINTS.DISABLE, payload);\n }\n\n validateCNameProject(\n payload: IValidateCnameProjectPayload,\n ): Promise<IValidateCnameProjectResponse> {\n return logicClient.post(PROJECT_ENDPOINTS.CONFIGURE, payload);\n }\n}\n\nexport const projectService = new ProjectService();\n","import { useEffect } from \"react\";\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { projectService } from \"@/services/project.service\";\nimport { useProjectStore } from \"@/store/project.store\";\nimport { useImpersonateStore } from \"@/store/impersonate.store\";\nimport type {\n IUpdateProjectPayload,\n IUpdateTenantGroupPayload,\n IValidateCnameProjectPayload,\n} from \"@/models\";\n\nconst ENV_REPOS_KEY = \"env-repositories\";\nconst IDENTIFIER = \"identifier\";\nconst PROJECT_KEY = [IDENTIFIER, \"project\"];\nconst PROJECTS_KEY = [IDENTIFIER, \"projects\"];\nexport const PROJECTS_STALE_TIME_MS = 5 * 1000;\n\nexport const useGetProjects = (options: {\n tenantGroupId?: string;\n enabled?: boolean;\n}) => {\n const setProjects = useProjectStore((state) => state.setProjects);\n const query = useQuery({\n queryKey: [...PROJECTS_KEY, options?.tenantGroupId],\n queryFn: () => projectService.getProjects(0, 100, options?.tenantGroupId),\n enabled: !!options?.enabled,\n // Keep the list in step with the OS app: refetch on every mount (coming back\n // to the Console) and on window focus once it is older than a few seconds.\n staleTime: PROJECTS_STALE_TIME_MS,\n refetchOnMount: \"always\",\n refetchOnWindowFocus: true,\n });\n\n useEffect(() => {\n if (!query.data) return;\n const flattenedProjects = query.data.flatMap((group) => group.projects);\n setProjects(flattenedProjects);\n }, [query.data, setProjects]);\n\n return query;\n};\n\nexport const useGetProject = () => {\n const selectedProject = useProjectStore((state) => state.selectedProject);\n const { isImpersonated, impersonatedTenantId, originalTenantId } =\n useImpersonateStore();\n\n // The endpoint answers \"the project of whoever I am\", so the tenant the token is\n // scoped to identifies the response — key the cache on that, not on an id the\n // server never reads. All consumers mount inside ImpersonationChecker, which\n // renders nothing until the store is populated, so this is resolved by the time\n // the query runs.\n const tokenTenantId = isImpersonated\n ? impersonatedTenantId\n : originalTenantId;\n\n return useQuery({\n queryKey: [...PROJECT_KEY, tokenTenantId],\n queryFn: () => projectService.getProject(),\n // Deliberately unchanged from the previous `Boolean(options.projectId)`, which\n // was fed `selectedProject?.itemId`. It is load-bearing: on project-overview\n // routes ImpersonationTerminator drops the token to root and no project is\n // selected, and this keeps the query idle there. Tightening it to also require\n // the token's tenant to match the selected project is the stricter, more\n // correct rule — but it depends on `selectedProject.tenantId` and the\n // impersonation status endpoint agreeing byte-for-byte, which is unverified.\n // Getting that wrong disables the query permanently and blanks\n // dashboard-overview (`if (!data?.data) return null`).\n enabled: isImpersonated && Boolean(selectedProject?.itemId),\n });\n};\n\nexport const useGetEnvRepositories = (projectKey: string) => {\n return useQuery({\n queryKey: [ENV_REPOS_KEY, projectKey],\n queryFn: () => projectService.getEnvRepositories(),\n enabled: !!projectKey,\n });\n};\n\nexport const useUpdateRepositories = () => {\n const queryClient = useQueryClient();\n return useMutation({\n mutationKey: [ENV_REPOS_KEY, \"update\"],\n mutationFn: projectService.repoUpdate,\n onSuccess: () => {\n queryClient.invalidateQueries({ queryKey: [ENV_REPOS_KEY] });\n },\n });\n};\nexport const useUpdateTenantGroup = () => {\n const queryClient = useQueryClient();\n return useMutation({\n mutationKey: [IDENTIFIER, \"tenant-group-update\"],\n mutationFn: (payload: IUpdateTenantGroupPayload) =>\n projectService.updateTenantGroup(payload),\n onSuccess: () => {\n queryClient.invalidateQueries({\n queryKey: [IDENTIFIER, \"tenant-group\"],\n });\n queryClient.invalidateQueries({ queryKey: PROJECTS_KEY });\n },\n });\n};\n\nexport const useUpdateProject = () => {\n const queryClient = useQueryClient();\n return useMutation({\n mutationKey: [IDENTIFIER, \"project-update\"],\n mutationFn: (payload: IUpdateProjectPayload) =>\n projectService.updateProject(payload),\n onSuccess: () => {\n queryClient.invalidateQueries({ queryKey: PROJECT_KEY });\n queryClient.invalidateQueries({ queryKey: PROJECTS_KEY });\n },\n });\n};\n\nexport const useValidateCNameProject = (\n options: IValidateCnameProjectPayload,\n) => {\n const queryClient = useQueryClient();\n return useMutation({\n mutationKey: [...PROJECTS_KEY, options],\n mutationFn: () => projectService.validateCNameProject(options),\n onSuccess: () => {\n queryClient.invalidateQueries({\n queryKey: PROJECT_KEY,\n });\n queryClient.invalidateQueries({ queryKey: PROJECTS_KEY });\n },\n });\n};\n\nexport const useDisableProject = (options: { projectKey: string }) => {\n const queryClient = useQueryClient();\n return useMutation({\n mutationKey: [...PROJECTS_KEY, \"disable\"],\n mutationFn: () => projectService.disableProject(options),\n onSuccess: () => {\n queryClient.invalidateQueries({ queryKey: PROJECT_KEY });\n queryClient.invalidateQueries({ queryKey: PROJECTS_KEY });\n },\n });\n};\n","import { useParams } from \"react-router\";\n\n/**\n * Builds absolute paths scoped to the active project id in the URL\n * (`/app/:<paramName>/...`). Use inside a project-scoped subtree so links carry\n * the id without each call site having to read the route param.\n *\n * Pair it with {@link DashboardRoute} / {@link ProjectOverviewRoute}, which put\n * the id in the URL. App-specific base paths (e.g. an LMT section) can be built\n * on top: `const lmtBase = useScopedPath()(\"lmt\")`.\n *\n * @param paramName Route param that holds the id. Defaults to `itemId`.\n * @returns `(sub) => \"/app/<id>/<sub>\"`.\n *\n * @example\n * const scoped = useScopedPath();\n * navigate(scoped(`idp/role-detail/${roleId}`));\n */\nexport const useScopedPath = (paramName = \"itemId\") => {\n const params = useParams();\n const id = params[paramName] ?? \"\";\n return (sub: string) => `/app/${id}/${sub.replace(/^\\/+/, \"\")}`;\n};\n","import { SERVICE_REGISTRY_ENDPOINTS } from \"@/constants/endpoint.constant\";\nimport { logicClient } from \"@/lib/http\";\nimport type { IGetAllServicesPayload, IGetAllServicesResponse } from \"@/models\";\n\nexport class ServiceRegistryService {\n getAllServices(\n payload: IGetAllServicesPayload,\n ): Promise<IGetAllServicesResponse> {\n return logicClient.post(`${SERVICE_REGISTRY_ENDPOINTS.GET_ALL}`, payload);\n }\n}\n\nexport const serviceRegistryService = new ServiceRegistryService();\n","import type { IGetAllServicesPayload } from \"@/models\";\nimport { serviceRegistryService } from \"@/services/service-registry.service\";\nimport { useQuery } from \"@tanstack/react-query\";\n\nexport const useGetAllServices = (options: IGetAllServicesPayload) => {\n return useQuery({\n queryKey: [\"services\", options.projectKey, options.page, options.pageSize],\n queryFn: () => serviceRegistryService.getAllServices(options),\n enabled: !!options.projectKey,\n });\n};\n","import { IMPERSONATE_ENDPOINTS } from \"@/constants/endpoint.constant\";\nimport { iamClient } from \"@/lib/http/instances\";\nimport type { HttpClientOptions } from \"@/lib/http/types\";\nimport type {\n ImpersonationRequest,\n ImpersonationStatusResponse,\n StartImpersonationResponse,\n} from \"@/models/impersonation.model\";\n\nclass ImpersonationService {\n startImpersonation(\n request: ImpersonationRequest,\n options?: HttpClientOptions,\n ): Promise<StartImpersonationResponse> {\n return iamClient.post(\n IMPERSONATE_ENDPOINTS.IMPERSONATE,\n request,\n undefined,\n options,\n );\n }\n\n stopImpersonation(options?: HttpClientOptions): Promise<void> {\n return iamClient.post(\n IMPERSONATE_ENDPOINTS.STOP_IMPERSONATION,\n {},\n undefined,\n options,\n );\n }\n\n impersonationStatus(\n options?: HttpClientOptions,\n ): Promise<ImpersonationStatusResponse> {\n return iamClient.post(\n IMPERSONATE_ENDPOINTS.IMPERSONATION_STATUS,\n null,\n undefined,\n options,\n );\n }\n}\n\nexport const impersonationService = new ImpersonationService();\n","import { HttpClient } from \"@/lib/http/client\";\nimport { HttpError } from \"@/lib/http/error\";\nimport { iamClient } from \"@/lib/http/instances\";\nimport { timeoutSignal } from \"@/lib/http/session-lock\";\nimport { getRuntimeEnv } from \"@/lib/runtime-env\";\nimport { claimTenant } from \"@/lib/tenant-ownership\";\nimport type {\n ImpersonationRequest,\n ImpersonationStatusResponse,\n StartImpersonationResponse,\n} from \"@/models/impersonation.model\";\nimport { impersonationService } from \"@/services/impersonation.service\";\nimport { useImpersonateStore } from \"@/store/impersonate.store\";\nimport {\n focusManager,\n type Query,\n type QueryClient,\n useMutation,\n useQuery,\n useQueryClient,\n} from \"@tanstack/react-query\";\nimport { useCallback, useEffect } from \"react\";\n\nconst IMPERSONATION_STATUS_QUERY_KEY = [\"blocks-kit-impersonation\", \"status\"];\n\n/**\n * How long one call made while holding the session lock may take -- the same bound a token refresh\n * has. Every tab's refresh waits for that lock, so a call whose answer never comes must give it up.\n */\nconst LOCKED_CALL_TIMEOUT_MS = 20_000;\n\n/**\n * Options for a call made while holding the session lock: the client's own refresh would wait for\n * that lock, so a call that needs a fresh token goes through `withRefreshedToken` instead. Each call\n * gets its own time limit.\n */\nconst insideSessionLock = () => ({\n skipTokenRotation: true,\n skipSessionCheck: true,\n signal: timeoutSignal(LOCKED_CALL_TIMEOUT_MS),\n});\n\n/** How long a returning tab waits for the status before refetching its data anyway. */\nconst RETURN_STATUS_WAIT_MS = 5_000;\n\n/**\n * Gives React a moment to apply a status that moved the tenant -- the guards stop rendering the\n * page -- before the returning tab refetches what is still on screen.\n */\nconst FOCUS_REFETCH_DELAY_MS = 50;\n\nconst rootTenantId = (): string => getRuntimeEnv(\"BLOCKS_X_BLOCKS_KEY\") || \"\";\n\nconst buildStoppedStatus = (): ImpersonationStatusResponse => ({\n impersonated: false,\n originalTenantId: rootTenantId(),\n impersonatedTenantId: null,\n});\n\nconst isSameTenant = (\n a: string | null | undefined,\n b: string | null | undefined,\n): boolean => !!a && !!b && a.toLowerCase() === b.toLowerCase();\n\n/** The tenant a status answer puts the session cookie in. */\nconst tenantOfStatus = (\n status: ImpersonationStatusResponse | null | undefined,\n): string | null => {\n if (!status) return null;\n return status.impersonated\n ? (status.impersonatedTenantId ?? null)\n : rootTenantId() || null;\n};\n\n/** The tenant the guards are rendering for, or null before the first status has arrived. */\nconst tenantShown = (): string | null => {\n const { isInitialized, isImpersonated, impersonatedTenantId } =\n useImpersonateStore.getState();\n if (!isInitialized) return null;\n return isImpersonated ? impersonatedTenantId : rootTenantId() || null;\n};\n\n/** IAM's own refusals carry an error code; a bare 401 is the access token having expired. */\nconst errorCodeOf = (error: unknown): string | null => {\n if (!(error instanceof HttpError)) return null;\n const code = error.errors?.error;\n return typeof code === \"string\" ? code : null;\n};\n\nconst isExpiredAccessToken = (error: unknown): boolean =>\n error instanceof HttpError && error.status === 401 && !errorCodeOf(error);\n\n/**\n * Makes `call` once more after refreshing the token, if it failed only because the access token had\n * expired. For use inside the session lock, where the client's own refresh would wait on the lock.\n */\nconst withRefreshedToken = async <T>(call: () => Promise<T>): Promise<T> => {\n try {\n return await call();\n } catch (error) {\n if (!isExpiredAccessToken(error)) throw error;\n await iamClient.refreshWithinSessionLock();\n return call();\n }\n};\n\nconst isStatusQuery = (query: Query): boolean =>\n query.queryKey[0] === IMPERSONATION_STATUS_QUERY_KEY[0];\n\n/**\n * Drops what was cached for the tenant the page was showing, after the session turned out to be\n * in another one. Anything fetched in between went out under the other tenant's token, and the\n * cache would serve it under this page's keys when the page is back in its own tenant. Active\n * queries are left until the guards have stopped rendering them.\n */\nconst dropDataFromBeforeTheMove = (queryClient: QueryClient): void => {\n void queryClient.cancelQueries({ predicate: (q) => !isStatusQuery(q) });\n setTimeout(() => {\n queryClient.removeQueries({\n predicate: (q) => !isStatusQuery(q),\n type: \"inactive\",\n });\n void queryClient.invalidateQueries({\n predicate: (q) => !isStatusQuery(q),\n refetchType: \"none\",\n });\n }, FOCUS_REFETCH_DELAY_MS);\n};\n\n/**\n * Records a status read from the server and, when it puts the session in a tenant other than the\n * one being shown, drops that tenant's cached data. Returns the tenant the session is in.\n */\nconst applyServerStatus = (\n queryClient: QueryClient,\n status: ImpersonationStatusResponse,\n): string | null => {\n const shown = tenantShown();\n queryClient.setQueryData(IMPERSONATION_STATUS_QUERY_KEY, status);\n const actual = tenantOfStatus(status);\n if (shown && actual && !isSameTenant(shown, actual)) {\n dropDataFromBeforeTheMove(queryClient);\n }\n return actual;\n};\n\nexport const useImpersonationStatusChecker = () => {\n return useQuery({\n queryKey: IMPERSONATION_STATUS_QUERY_KEY,\n // The status is what decides the tenant, so it is never held back for disagreeing with it.\n queryFn: () =>\n impersonationService.impersonationStatus({ skipSessionCheck: true }),\n staleTime: 0,\n refetchOnMount: \"always\",\n // A returning tab asks first and refetches its data after; see useStatusFirstOnTabReturn.\n refetchOnWindowFocus: false,\n });\n};\n\n/**\n * Lets the HTTP client check, after every token refresh, that the session is still in the tenant\n * the page is showing, and drop a retry that would otherwise be answered with another tenant's\n * data. The check asks the server; it does not trust anything this tab believes.\n */\nexport const useSessionTenantGuard = () => {\n const queryClient = useQueryClient();\n\n useEffect(\n () =>\n HttpClient.setSessionGuard({\n expectedTenant: tenantShown,\n confirmTenant: async () =>\n applyServerStatus(\n queryClient,\n await impersonationService.impersonationStatus(insideSessionLock()),\n ),\n }),\n [queryClient],\n );\n};\n\n/** TanStack Query's own tab-return listener, restored when the guards unmount. */\nconst listenForVisibility = (onFocus: () => void) => {\n if (typeof window === \"undefined\" || !window.addEventListener) {\n return undefined;\n }\n const listener = () => onFocus();\n window.addEventListener(\"visibilitychange\", listener, false);\n return () => window.removeEventListener(\"visibilitychange\", listener);\n};\n\nconst confirmTenantOnReturn = async (\n queryClient: QueryClient,\n): Promise<void> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const status = await Promise.race([\n impersonationService.impersonationStatus({ skipSessionCheck: true }),\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(\"Impersonation status timed out\")),\n RETURN_STATUS_WAIT_MS,\n );\n }),\n ]);\n applyServerStatus(queryClient, status);\n } catch {\n // Unknown, not moved: the page keeps what it last confirmed.\n } finally {\n clearTimeout(timer);\n }\n};\n\n/**\n * On returning to the tab, asks where the session is before refetching anything else.\n *\n * TanStack Query refetches every stale query the moment the tab becomes visible, the status among\n * them. If another tab moved the shared cookie meanwhile, those refetches went out under the new\n * tenant's token while the page still showed the old one, and their answers were cached under the\n * old page's keys. Asking first lets the guards stop rendering the page before anything is sent.\n */\nexport const useStatusFirstOnTabReturn = () => {\n const queryClient = useQueryClient();\n\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n\n focusManager.setEventListener((onFocus) => {\n const listener = () => {\n if (document.visibilityState === \"hidden\") {\n onFocus();\n return;\n }\n void confirmTenantOnReturn(queryClient).finally(() => {\n setTimeout(() => onFocus(), FOCUS_REFETCH_DELAY_MS);\n });\n };\n window.addEventListener(\"visibilitychange\", listener, false);\n return () => window.removeEventListener(\"visibilitychange\", listener);\n });\n\n return () => focusManager.setEventListener(listenForVisibility);\n }, [queryClient]);\n};\n\n/**\n * Records where another tab's claim says the shared cookie now is.\n *\n * A claim is first-hand: a tab only makes one after the server confirmed the swap. Without recording\n * it, this tab's cached status stays wherever it last looked, and it looks again only on\n * `visibilitychange` -- which never fires for two windows side by side, both always visible. A\n * console that had stopped impersonation then went on believing the cookie was root after another\n * window re-entered a project, so \"Leave <project>\" cleared the notice without ever calling stop,\n * and the console rendered under the project's token.\n */\nexport const useRecordClaimedTenant = () => {\n const queryClient = useQueryClient();\n\n return useCallback(\n (tenantId: string, rootTenantId: string) => {\n queryClient.setQueryData<ImpersonationStatusResponse>(\n IMPERSONATION_STATUS_QUERY_KEY,\n tenantId === rootTenantId\n ? buildStoppedStatus()\n : (current) => ({\n impersonated: true,\n originalTenantId: current?.originalTenantId || rootTenantId,\n impersonatedTenantId: tenantId,\n }),\n );\n },\n [queryClient],\n );\n};\n\n/** What a stop attempt left behind. */\nexport interface StopImpersonationOutcome {\n /** Where the server says the session is after the attempt. */\n status: ImpersonationStatusResponse;\n /** Why the stop call failed, or null when it succeeded. */\n stopError: unknown;\n}\n\n/**\n * Stops impersonation and asks the server where the session ended up, whatever the stop returned.\n *\n * Neither the stop's answer nor its failure says where the cookie is. A stop that never left the\n * browser leaves the session in the project; one whose answer was lost has already moved it; a 401\n * is an expired access token as often as a finished impersonation. Each of those used to be read\n * as \"stopped\", and the console rendered under the project's token. The status is the only answer\n * that describes the cookie the next request will carry.\n */\nconst stopAndConfirm = (): Promise<StopImpersonationOutcome> =>\n iamClient.withSessionLock(async () => {\n let stopError: unknown = null;\n try {\n await withRefreshedToken(() =>\n impersonationService.stopImpersonation(insideSessionLock()),\n );\n } catch (error) {\n stopError = error;\n }\n const status = await withRefreshedToken(() =>\n impersonationService.impersonationStatus(insideSessionLock()),\n );\n return { status, stopError };\n });\n\nexport const useStopImpersonation = () => {\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationKey: [\"impersonation\", \"stop\"],\n mutationFn: stopAndConfirm,\n onSuccess: ({ status }) => {\n queryClient.setQueryData<ImpersonationStatusResponse>(\n IMPERSONATION_STATUS_QUERY_KEY,\n status,\n );\n },\n });\n};\n\n/**\n * Starts (or retargets) impersonation, then confirms with the server that the session is in the\n * target tenant before reporting success.\n *\n * A 200 whose `cookie_set` is not true is treated as a failure, because it is one: the browser\n * authenticates with the HttpOnly cookie and ignores body tokens, so such a response leaves the\n * previous cookie in place. Recording \"impersonated\" for it used to make the client render a\n * project under whatever tenant the unchanged cookie still pointed at.\n *\n * Even `cookie_set: true` describes the response, not the cookie: a response that lands after it --\n * another tab, or a refresh this tab had in flight -- can replace it. The status check reads the\n * cookie the next request will carry.\n */\nconst startAndConfirm = (\n request: ImpersonationRequest,\n): Promise<{\n result: StartImpersonationResponse;\n status: ImpersonationStatusResponse | null;\n}> =>\n iamClient.withSessionLock(async () => {\n const result = await withRefreshedToken(() =>\n impersonationService.startImpersonation(request, insideSessionLock()),\n );\n\n if (result?.cookie_set !== true) {\n throw new HttpError(500, {\n errors: {\n general:\n \"Impersonation did not replace the session cookie (cookie_set was not true)\",\n },\n });\n }\n\n const status = await withRefreshedToken(() =>\n impersonationService.impersonationStatus(insideSessionLock()),\n ).catch(() => null);\n\n return { result, status };\n });\n\nexport const useStartImpersonation = () => {\n const queryClient = useQueryClient();\n\n return useMutation({\n mutationKey: [\"impersonation\", \"start\"],\n mutationFn: async (request: ImpersonationRequest) => {\n const { result, status } = await startAndConfirm(request);\n if (status) {\n queryClient.setQueryData<ImpersonationStatusResponse>(\n IMPERSONATION_STATUS_QUERY_KEY,\n status,\n );\n }\n if (\n !status?.impersonated ||\n !isSameTenant(status.impersonatedTenantId, request.targeted_tenant_id)\n ) {\n throw new HttpError(409, {\n errors: {\n general:\n \"The server did not confirm that the session is in the project\",\n },\n });\n }\n return result;\n },\n onSuccess: (_data, variables) => {\n // Claimed here rather than at each call site. The access cookie is named after the application\n // domain alone, so every tab on this origin shares one token and the tab that impersonated last\n // owns it; a tab that is visible but not focused keeps polling under it none the wiser. The\n // claim used to live only in the route guard, which the environment cards -- the main way into a\n // project, in both this package and blocks-os -- do not go through, so entering a project from a\n // card silently repointed every other tab's cookie without telling them.\n claimTenant(variables.targeted_tenant_id);\n },\n onError: () => {\n // The cookie's tenant is now unknown: the call may have failed before, during or after the\n // server swapped it. Refetch rather than leave a stale claim standing.\n void queryClient.invalidateQueries({\n queryKey: IMPERSONATION_STATUS_QUERY_KEY,\n });\n },\n });\n};\n"]}
@@ -1,7 +1,7 @@
1
1
  import { refractor } from './chunk-FGY7QM3Y.js';
2
- import { notificationService, useKeyboardShortcut, usePopoverWidth, useBlocksAppConfigStore, useTheme, useLogout, useGetMyOrganizations, useLanguageSwitcher, useGetBlocksNotificationConfig, useLogo, useStartImpersonation, useGetProjects, useGetProject, useImpersonationStatusChecker, useSessionTenantGuard, useStatusFirstOnTabReturn, useStopImpersonation, useRecordClaimedTenant, useSignOut, useLogin, useSignUpAffordance, useSignUpRedirect, useInitiateRedirect, useGetEnvRepositories, useUpdateTenantGroup, useIcon, useDisableProject, projectService, initiateService, useGetNotifications, useMarkAsRead, useMarkAllAsRead, impersonationService, useDebouncedFuseFilter, useUpdateRepositories, usePrefetchRedirect } from './chunk-EKAGSVC7.js';
2
+ import { notificationService, useKeyboardShortcut, usePopoverWidth, useBlocksAppConfigStore, useTheme, useLogout, useGetMyOrganizations, useLanguageSwitcher, useGetBlocksNotificationConfig, useLogo, useStartImpersonation, useGetProjects, useGetProject, useImpersonationStatusChecker, useSessionTenantGuard, useStatusFirstOnTabReturn, useStopImpersonation, useRecordClaimedTenant, useSignOut, useLogin, useSignUpAffordance, useSignUpRedirect, useInitiateRedirect, useGetEnvRepositories, useUpdateTenantGroup, useIcon, useDisableProject, projectService, initiateService, useGetNotifications, useMarkAsRead, useMarkAllAsRead, impersonationService, useDebouncedFuseFilter, useUpdateRepositories, usePrefetchRedirect } from './chunk-ZR6LRRN6.js';
3
3
  import { showErrorToast, createStorage, getForwardedToPath, debounce, formatFullDate, formatDate, deepEqual, showSuccessToast, isErrorWithErrors, getServiceBaseUrl, getServiceSwaggerUrl } from './chunk-JSXAKNHQ.js';
4
- import { fadeTransition, fadeInUp, staggerContainer, staggerItem, fadeInScale, subscribeToSignOut, subscribeToTenantClaims, holdTenant, iamClient, AUTH_ENDPOINTS, claimTenant, readCurrentOwner, TAB_ID, isTenantHeldElsewhere, isSameClaim, PROFILE_ENDPOINTS } from './chunk-R7WBG4YN.js';
4
+ import { fadeTransition, fadeInUp, staggerContainer, staggerItem, fadeInScale, subscribeToSignOut, subscribeToTenantClaims, holdTenant, iamClient, AUTH_ENDPOINTS, claimTenant, readCurrentOwner, TAB_ID, isTenantHeldElsewhere, isSameClaim, PROFILE_ENDPOINTS } from './chunk-O5ACQLWB.js';
5
5
  import { getRuntimeEnv, HttpError } from './chunk-JUVLHPQI.js';
6
6
  import { defaultRightSidePanelContextValue, RightSidePanelContext, SidebarContext, DashboardLayoutProvider } from './chunk-XRAO7JBH.js';
7
7
  import { useIsMobile, useIsActiveMenu, useFilteredMenus } from './chunk-AHCHUUXM.js';
@@ -13603,5 +13603,5 @@ var TablePagination2 = React8.forwardRef(
13603
13603
  TablePagination2.displayName = "TablePagination";
13604
13604
 
13605
13605
  export { Accordion, AccordionContent, AccordionItem, AccordionTrigger, Alert, AlertDescription, AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogOverlay, AlertDialogPortal, AlertDialogTitle, AlertDialogTrigger, AlertTitle, AppLoadingSpinner, AppSwitcher, ArchiveProject, AspectRatio, AuthLayout, AuthResolver, Avatar, AvatarFallback, AvatarImage, BackToConsoleNavigator, Badge, Breadcrumb, BreadcrumbEllipsis, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator, Button, Calendar, CallbackPage, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious, ChartContainer, ChartLegend, ChartLegendContent, ChartStyle, ChartTooltip, ChartTooltipContent, Checkbox, Collapsible, CollapsibleContent2 as CollapsibleContent, CollapsibleTrigger2 as CollapsibleTrigger, Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, ConfirmationModal, ConsoleHeader, ConsoleLayout, ConsolePage, ContextMenu, ContextMenuCheckboxItem, ContextMenuContent, ContextMenuGroup, ContextMenuItem, ContextMenuLabel, ContextMenuPortal, ContextMenuRadioGroup, ContextMenuRadioItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger, CopyToClipboardButton, CopyableSnippet, DEFAULT_KANBAN_COLUMNS, DashboardHeader, DashboardLayout, DashboardOverview, DashboardRoute, DashboardSectionCard, DataTable, DataTableHeaderCell, DateRangePicker, DesktopMenuItem, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, Drawer, DrawerClose, DrawerContent, DrawerDescription, DrawerFooter, DrawerHeader, DrawerOverlay, DrawerPortal, DrawerTitle, DrawerTrigger, DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, EditProject, EditProjectDialog, EditProjectForm, EnvironmentCard, EnvironmentList, ErrorBoundary, ErrorDisplay, ErrorDisplayWithCard, FileInput, FileUploader, FileUploaderContent, FileUploaderItem, FilterControls, FilterToolBarMobileView, FilterToolbar, Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, HoverCard, HoverCardContent, HoverCardTrigger, ImpersonationChecker, ImpersonationSynchronizer, ImpersonationTerminator, ImportFileModalContent, InfiniteScroll, InfiniteScroller, InfoTooltip, Input, InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot, KanbanBoard, KanbanBoardColumn, KanbanBoardContainer, KanbanTaskCard, Label, LanguageSelector, LoadingButton, LoginPage, Logo, MaskedText, Menubar, MenubarCheckboxItem, MenubarContent, MenubarGroup, MenubarItem, MenubarLabel, MenubarMenu, MenubarPortal, MenubarRadioGroup, MenubarRadioItem, MenubarSeparator, MenubarShortcut, MenubarSub, MenubarSubContent, MenubarSubTrigger, MenubarTrigger, MobileMenuItem, MultiSelect, NavigationMenu, NavigationMenuContent, NavigationMenuIndicator, NavigationMenuItem, NavigationMenuLink, NavigationMenuList, NavigationMenuTrigger, NavigationMenuViewport, Notification, OidcLayout, Pagination, PaginationContent, PaginationEllipsis, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious, PasswordInput, Popover, PopoverContent, PopoverTrigger, ProfilePage, Progress, ProjectActions, ProjectCardLoadingSkeleton, ProjectDetail, ProjectList2 as ProjectList, ProjectListRowLoadingSkeleton, ProjectOverview, ProjectRepoList, ProtectedGuard, PublicGuard, PublicLayout, RadioGroup4 as RadioGroup, RadioGroupItem, RenderAlternatively, RenderConditionally, ResizableHandle, ResizablePanel, ResizablePanelGroup, RightSidePanel, RightSidePanelBody, RightSidePanelClose, RightSidePanelDescription, RightSidePanelFooter, RightSidePanelHeader, RightSidePanelProvider, RightSidePanelTitle, RightSidePanelTrigger, ScrollArea, ScrollBar, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, SelectedEnvironment, SelectedProject, Separator, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetOverlay, SheetPortal, SheetTitle, SheetTrigger, Sidebar, SidebarCollapsedTooltip, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupAction, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarInput, SidebarInset, SidebarMenu, SidebarMenuAction, SidebarMenuBadge, SidebarMenuButton, SidebarMenuDesktop, SidebarMenuItem, SidebarMenuSkeleton, SidebarMenuSub, SidebarMenuSubButton, SidebarMenuSubItem, SidebarMobileView, SidebarProvider, SidebarRail, SidebarSeparator, SidebarTrigger, Skeleton, Slider, Spinner, Stepper, Switch, Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableLoadingSkeleton, TablePagination2 as TablePagination, TableRow, Tabs, TabsContent, TabsList, TabsTrigger, Textarea, ThemeSwitcher, Timeline, Toggle, ToggleGroup, ToggleGroupItem, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, UserDropdownMenu, WizardHorizontalTrackBar, WizardStepContent, WizardStepIndicator, WizardStepViewport, WizardStepperProvider, WizardVerticalTrackBar, badgeVariants, buttonVariants, editProjectFormDefaultValues, editProjectFormSchema, filteredAppSwitcherData, hasDraggableData, kanbanKeyboardCoordinateGetter, navigationMenuTriggerStyle, paginationQueryParsers, sidebarCollapsedTooltipClass, sortQueryParsers, spinnerVariants, toggleVariants, useFileUpload, useFormField, useNotificationSocket, useOidcContext, usePaginationQueryParams, useRightSidePanel, useSortQueryParams, useWizardStepper };
13606
- //# sourceMappingURL=chunk-VSLB4SJE.js.map
13607
- //# sourceMappingURL=chunk-VSLB4SJE.js.map
13606
+ //# sourceMappingURL=chunk-NPMO67H6.js.map
13607
+ //# sourceMappingURL=chunk-NPMO67H6.js.map