@burdenoff/microfe-auth 2026.704.2 → 2026.710.1
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.
|
@@ -5,11 +5,11 @@ import { useEventBus as o } from "@burdenoff/fe-libs/shared/events";
|
|
|
5
5
|
import { getStoredAuthToken as s, graphqlFetch as c } from "@burdenoff/fe-libs/shared/graphql";
|
|
6
6
|
import { useActiveContext as l } from "@burdenoff/fe-libs/shared/providers/shell/ActiveContextProvider";
|
|
7
7
|
//#region src/auth/hooks/useContextSwitcherData.ts
|
|
8
|
-
var u = "\n query MyOrganizations {\n myOrganizations {\n total\n items {\n id\n name\n slug\n tenantId\n description\n logo\n website\n status\n type\n createdAt\n updatedAt\n }\n }\n }\n", d = "\n query WorkspacesByOrg {\n workspaces: myWorkspaces(limit: 100) {\n total\n items {\n id\n name\n slug\n tenantId\n organizationId\n type\n status\n region\n createdAt\n updatedAt\n }\n }\n }\n", f = "\n
|
|
9
|
-
async function
|
|
8
|
+
var u = "\n query MyOrganizations {\n myOrganizations {\n total\n items {\n id\n name\n slug\n tenantId\n description\n logo\n website\n status\n type\n createdAt\n updatedAt\n }\n }\n }\n", d = "\n query WorkspacesByOrg {\n workspaces: myWorkspaces(limit: 100) {\n total\n items {\n id\n name\n slug\n tenantId\n organizationId\n type\n status\n region\n createdAt\n updatedAt\n }\n }\n }\n", f = "\n mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {\n issueWorkspaceToken(input: $input) {\n success\n token\n expiresAt\n organizationId\n workspaceId\n projectId\n scopes\n error {\n code\n message\n }\n }\n }\n", p = "\n query MyProjectsForContext {\n projects: myProjects {\n total\n items {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n }\n", m = "\n mutation CreateDefaultProject($input: CreateProjectInput!) {\n createProject(input: $input) {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n";
|
|
9
|
+
async function h({ authToken: e, workspaceBaseUrl: t, workspaceToken: n }) {
|
|
10
10
|
let r = await c({
|
|
11
11
|
gateway: "workspace",
|
|
12
|
-
query:
|
|
12
|
+
query: m,
|
|
13
13
|
variables: { input: { name: "Default Project" } },
|
|
14
14
|
authToken: e,
|
|
15
15
|
workspaceToken: n,
|
|
@@ -17,7 +17,7 @@ async function g({ authToken: e, workspaceBaseUrl: t, workspaceToken: n }) {
|
|
|
17
17
|
});
|
|
18
18
|
return r.errors?.length ? (console.warn("Failed to create default project:", r.errors), null) : r.data?.createProject ?? null;
|
|
19
19
|
}
|
|
20
|
-
function
|
|
20
|
+
function g(e, t = 3e4) {
|
|
21
21
|
try {
|
|
22
22
|
let n = JSON.parse(atob(e.split(".")[1]));
|
|
23
23
|
return n.exp ? n.exp * 1e3 < Date.now() + t : !1;
|
|
@@ -25,7 +25,7 @@ function _(e, t = 3e4) {
|
|
|
25
25
|
return !0;
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
-
function
|
|
28
|
+
function _(e) {
|
|
29
29
|
try {
|
|
30
30
|
let t = JSON.parse(atob(e.split(".")[1]));
|
|
31
31
|
return {
|
|
@@ -38,26 +38,26 @@ function v(e) {
|
|
|
38
38
|
return null;
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
|
-
function
|
|
42
|
-
if (!e ||
|
|
43
|
-
let n =
|
|
41
|
+
function v(e, t) {
|
|
42
|
+
if (!e || g(e)) return !1;
|
|
43
|
+
let n = _(e);
|
|
44
44
|
return !(!n || t.workspaceId && n.workspaceId !== t.workspaceId || t.organizationId && n.organizationId !== t.organizationId || t.projectId && n.projectId !== t.projectId);
|
|
45
45
|
}
|
|
46
|
-
var
|
|
46
|
+
var y = class extends Error {
|
|
47
47
|
constructor(e) {
|
|
48
48
|
super(e), this.name = "AuthError";
|
|
49
49
|
}
|
|
50
50
|
};
|
|
51
|
-
function
|
|
51
|
+
function b(e) {
|
|
52
52
|
return e.some((e) => e.extensions?.code === "UNAUTHENTICATED" || e.message?.toLowerCase().includes("unauthorized") || e.message?.toLowerCase().includes("not authenticated"));
|
|
53
53
|
}
|
|
54
|
-
function
|
|
54
|
+
function x() {
|
|
55
55
|
let t = e.getState().accessToken;
|
|
56
|
-
if (t && !
|
|
56
|
+
if (t && !g(t)) return t;
|
|
57
57
|
let n = s();
|
|
58
|
-
return n && !
|
|
58
|
+
return n && !g(n) ? n : t;
|
|
59
59
|
}
|
|
60
|
-
function
|
|
60
|
+
function S(e) {
|
|
61
61
|
return Array.from(new Set(e.flatMap((e) => e.organizationId ? [e.organizationId] : []))).map((t, n) => ({
|
|
62
62
|
id: t,
|
|
63
63
|
name: e.find((e) => e.organizationId === t)?.name || `Organization ${n + 1}`,
|
|
@@ -65,55 +65,73 @@ function C(e) {
|
|
|
65
65
|
tenantId: e.find((e) => e.organizationId === t)?.tenantId || ""
|
|
66
66
|
}));
|
|
67
67
|
}
|
|
68
|
-
var
|
|
68
|
+
var C = new Set([
|
|
69
69
|
"project.created",
|
|
70
70
|
"project.updated",
|
|
71
71
|
"project.deleted",
|
|
72
72
|
"project.archived",
|
|
73
73
|
"project.unarchived"
|
|
74
|
-
]),
|
|
74
|
+
]), w = new Set([
|
|
75
75
|
"workspace.created",
|
|
76
76
|
"workspace.updated",
|
|
77
77
|
"workspace.deleted",
|
|
78
78
|
"workspace.archived",
|
|
79
79
|
"workspace.reactivated"
|
|
80
80
|
]);
|
|
81
|
-
function
|
|
81
|
+
function T(e) {
|
|
82
82
|
if (e && typeof e == "object" && "workspaceId" in e) {
|
|
83
83
|
let t = e.workspaceId;
|
|
84
84
|
return typeof t == "string" ? t : void 0;
|
|
85
85
|
}
|
|
86
86
|
}
|
|
87
|
-
function
|
|
88
|
-
let { organizationId:
|
|
87
|
+
function E(s) {
|
|
88
|
+
let { organizationId: m, workspaceId: _, projectId: E, setContext: D } = l(), O = o(), k = e((e) => e.organizations), A = e((e) => e.currentOrganizationId), j = e((e) => e.isLoadingOrganizations), M = e((e) => e.workspaces), N = e((e) => e.currentWorkspaceId), P = e((e) => e.workspaceToken), F = e((e) => e.isLoadingWorkspaces), I = e((e) => e.projects), L = e((e) => e.currentProjectId), R = e((e) => e.isLoadingProjects), [ee, z] = a(null), B = i(null), V = i(/* @__PURE__ */ new Map()), H = i(_), U = i(m);
|
|
89
89
|
r(() => {
|
|
90
|
-
H.current =
|
|
90
|
+
H.current = _, U.current = m;
|
|
91
91
|
});
|
|
92
92
|
let W = t(), G = s?.globalBaseUrl ?? W.globalBaseUrl, K = s?.workspaceBaseUrl ?? W.workspaceBaseUrl, q = i(null), J = i(null), Y = i(null), X = i(null);
|
|
93
93
|
r(() => {
|
|
94
94
|
let t = e.getState();
|
|
95
|
-
if (
|
|
96
|
-
workspaceId:
|
|
97
|
-
organizationId:
|
|
98
|
-
projectId:
|
|
95
|
+
if (m && m !== t.currentOrganizationId && m !== q.current && (q.current = m, t.setCurrentOrganizationId(m), t.workspaces.length > 0 && !t.workspaces.some((e) => e.organizationId === m) && t.setWorkspaces([])), _ && _ !== t.currentWorkspaceId && _ !== J.current && (J.current = _, t.setCurrentWorkspaceId(_), t.projects.length > 0 && !t.projects.some((e) => e.workspaceId === _) && (t.setProjects([]), t.setCurrentProjectId(null))), E && E !== t.currentProjectId && E !== Y.current && (Y.current = E, t.setCurrentProjectId(E)), t.workspaceToken && !v(t.workspaceToken, {
|
|
96
|
+
workspaceId: _,
|
|
97
|
+
organizationId: m,
|
|
98
|
+
projectId: E
|
|
99
99
|
})) {
|
|
100
|
-
let e = `${
|
|
100
|
+
let e = `${m ?? ""}|${_ ?? ""}|${E ?? ""}`;
|
|
101
101
|
X.current !== e && (X.current = e, t.setWorkspaceToken(null));
|
|
102
102
|
}
|
|
103
103
|
}, [
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
104
|
+
m,
|
|
105
|
+
_,
|
|
106
|
+
E
|
|
107
107
|
]);
|
|
108
|
-
let
|
|
108
|
+
let te = n(async () => {
|
|
109
109
|
if (B.current) return B.current;
|
|
110
|
-
let t = e.getState(), n =
|
|
111
|
-
return !n ||
|
|
110
|
+
let t = e.getState(), n = x();
|
|
111
|
+
return !n || g(n) ? [] : (t.setLoadingOrganizations(!0), z(null), B.current = (async () => {
|
|
112
112
|
try {
|
|
113
|
-
let r = U.current ?? t.currentOrganizationId, i = await
|
|
113
|
+
let r = U.current ?? t.currentOrganizationId, i = r ? await (async () => {
|
|
114
|
+
let [e, t] = await Promise.all([c({
|
|
115
|
+
gateway: "global",
|
|
116
|
+
query: u,
|
|
117
|
+
authToken: n,
|
|
118
|
+
baseUrl: G
|
|
119
|
+
}), c({
|
|
120
|
+
gateway: "global",
|
|
121
|
+
query: d,
|
|
122
|
+
authToken: n,
|
|
123
|
+
baseUrl: G
|
|
124
|
+
})]);
|
|
125
|
+
return {
|
|
126
|
+
data: e.data?.myOrganizations ? {
|
|
127
|
+
myOrganizations: e.data.myOrganizations,
|
|
128
|
+
...t.data?.workspaces ? { workspaces: t.data.workspaces } : {}
|
|
129
|
+
} : null,
|
|
130
|
+
errors: [...e.errors ?? [], ...t.errors ?? []]
|
|
131
|
+
};
|
|
132
|
+
})() : await c({
|
|
114
133
|
gateway: "global",
|
|
115
|
-
query:
|
|
116
|
-
variables: void 0,
|
|
134
|
+
query: u,
|
|
117
135
|
authToken: n,
|
|
118
136
|
baseUrl: G
|
|
119
137
|
});
|
|
@@ -124,7 +142,7 @@ function D(s) {
|
|
|
124
142
|
baseUrl: G
|
|
125
143
|
})), i.errors?.length) {
|
|
126
144
|
let e = i.errors[0]?.message ?? "GraphQL error";
|
|
127
|
-
throw
|
|
145
|
+
throw b(i.errors) ? new y(e) : (t.workspaces.length === 0 && console.error("Failed to fetch organizations:", i.errors), Error(e));
|
|
128
146
|
}
|
|
129
147
|
let a = i.data?.myOrganizations?.items ?? [];
|
|
130
148
|
if (r && a.length === 0 && t.workspaces.length === 0) {
|
|
@@ -142,10 +160,10 @@ function D(s) {
|
|
|
142
160
|
} }
|
|
143
161
|
});
|
|
144
162
|
}
|
|
145
|
-
let o = a.length === 0 && t.workspaces.length > 0 ?
|
|
163
|
+
let o = a.length === 0 && t.workspaces.length > 0 ? S(t.workspaces) : [], s = o.length > 0 ? o : a;
|
|
146
164
|
t.setOrganizations(s);
|
|
147
|
-
let l = r,
|
|
148
|
-
if (l && !
|
|
165
|
+
let l = r, f = l && a.some((e) => e.id === l);
|
|
166
|
+
if (l && !f && a.length > 0 && (l = a[0].id, D({
|
|
149
167
|
organizationId: l,
|
|
150
168
|
workspaceId: null,
|
|
151
169
|
tenantId: null,
|
|
@@ -170,7 +188,7 @@ function D(s) {
|
|
|
170
188
|
tenantId: e[0].tenantId,
|
|
171
189
|
projectId: null
|
|
172
190
|
};
|
|
173
|
-
H.current ? (t.setCurrentWorkspaceId(e[0].id), t.setWorkspaceToken(null),
|
|
191
|
+
H.current ? (t.setCurrentWorkspaceId(e[0].id), t.setWorkspaceToken(null), D(n)) : t.currentWorkspaceId || (t.setCurrentWorkspaceId(e[0].id), D(n));
|
|
174
192
|
}
|
|
175
193
|
}
|
|
176
194
|
} catch {} finally {
|
|
@@ -179,10 +197,10 @@ function D(s) {
|
|
|
179
197
|
}
|
|
180
198
|
return s;
|
|
181
199
|
} catch (e) {
|
|
182
|
-
if (e instanceof
|
|
200
|
+
if (e instanceof y) return [];
|
|
183
201
|
let n = e instanceof Error ? e.message : "Failed to fetch organizations";
|
|
184
202
|
if (t.workspaces.length === 0 && console.error("Failed to fetch organizations:", e), z(n), t.workspaces.length > 0) {
|
|
185
|
-
let e =
|
|
203
|
+
let e = S(t.workspaces);
|
|
186
204
|
if (e.length > 0) return t.setOrganizations(e), t.currentOrganizationId || t.setCurrentOrganizationId(e[0].id), e;
|
|
187
205
|
}
|
|
188
206
|
return [];
|
|
@@ -190,11 +208,11 @@ function D(s) {
|
|
|
190
208
|
t.setLoadingOrganizations(!1), B.current = null;
|
|
191
209
|
}
|
|
192
210
|
})(), B.current);
|
|
193
|
-
}, [G,
|
|
211
|
+
}, [G, D]), Z = n(async (t) => {
|
|
194
212
|
let n = V.current.get(t);
|
|
195
213
|
if (n) return n;
|
|
196
|
-
let r = e.getState(), i =
|
|
197
|
-
if (!i ||
|
|
214
|
+
let r = e.getState(), i = x();
|
|
215
|
+
if (!i || g(i)) return [];
|
|
198
216
|
r.setLoadingWorkspaces(!0), z(null);
|
|
199
217
|
let a = (async () => {
|
|
200
218
|
try {
|
|
@@ -206,12 +224,12 @@ function D(s) {
|
|
|
206
224
|
});
|
|
207
225
|
if (e.data?.workspaces?.items && (e.data.workspaces.items = e.data.workspaces.items.filter((e) => e.organizationId === t)), e.errors?.length) {
|
|
208
226
|
let t = e.errors[0]?.message ?? "GraphQL error";
|
|
209
|
-
throw
|
|
227
|
+
throw b(e.errors) ? new y(t) : (console.error("Failed to fetch workspaces:", e.errors), Error(t));
|
|
210
228
|
}
|
|
211
229
|
let n = (e.data?.workspaces?.items ?? []).filter((e) => e.organizationId === t);
|
|
212
230
|
return r.setWorkspaces(n), n;
|
|
213
231
|
} catch (e) {
|
|
214
|
-
if (e instanceof
|
|
232
|
+
if (e instanceof y) return [];
|
|
215
233
|
let t = e instanceof Error ? e.message : "Failed to fetch workspaces";
|
|
216
234
|
return console.error("Failed to fetch workspaces:", e), z(t), [];
|
|
217
235
|
} finally {
|
|
@@ -219,9 +237,9 @@ function D(s) {
|
|
|
219
237
|
}
|
|
220
238
|
})();
|
|
221
239
|
return V.current.set(t, a), a;
|
|
222
|
-
}, [G]), Q = n(async (t, n, r) => {
|
|
223
|
-
let
|
|
224
|
-
if (!
|
|
240
|
+
}, [G]), Q = n(async (t, n, r, i) => {
|
|
241
|
+
let a = e.getState(), o = x();
|
|
242
|
+
if (!o || g(o)) return {
|
|
225
243
|
success: !1,
|
|
226
244
|
error: "No valid access token available"
|
|
227
245
|
};
|
|
@@ -229,34 +247,35 @@ function D(s) {
|
|
|
229
247
|
try {
|
|
230
248
|
let e = await c({
|
|
231
249
|
gateway: "workspace",
|
|
232
|
-
query:
|
|
250
|
+
query: f,
|
|
233
251
|
variables: { input: {
|
|
234
252
|
organizationId: t,
|
|
235
253
|
...n && { workspaceId: n },
|
|
236
254
|
...r && { projectId: r }
|
|
237
255
|
} },
|
|
238
|
-
authToken:
|
|
239
|
-
baseUrl: K
|
|
256
|
+
authToken: o,
|
|
257
|
+
baseUrl: K,
|
|
258
|
+
tenantId: i
|
|
240
259
|
});
|
|
241
260
|
if (e.errors?.length) {
|
|
242
261
|
let t = e.errors[0]?.message ?? "GraphQL error";
|
|
243
|
-
return
|
|
262
|
+
return b(e.errors) || console.error("Failed to issue workspace token:", e.errors), {
|
|
244
263
|
success: !1,
|
|
245
264
|
error: t
|
|
246
265
|
};
|
|
247
266
|
}
|
|
248
|
-
let
|
|
249
|
-
if (
|
|
250
|
-
let e =
|
|
251
|
-
return e &&
|
|
267
|
+
let s = e.data?.issueWorkspaceToken;
|
|
268
|
+
if (s?.success && s.token) {
|
|
269
|
+
let e = s.workspaceId || n;
|
|
270
|
+
return e && a.setCurrentWorkspaceId(e), a.setWorkspaceToken(s.token), {
|
|
252
271
|
success: !0,
|
|
253
|
-
token:
|
|
272
|
+
token: s.token,
|
|
254
273
|
resolvedWorkspaceId: e || void 0
|
|
255
274
|
};
|
|
256
275
|
}
|
|
257
276
|
return {
|
|
258
277
|
success: !1,
|
|
259
|
-
error:
|
|
278
|
+
error: s?.error?.message ?? "Failed to issue workspace token"
|
|
260
279
|
};
|
|
261
280
|
} catch (e) {
|
|
262
281
|
let t = e instanceof Error ? e.message : "Failed to issue workspace token";
|
|
@@ -266,49 +285,49 @@ function D(s) {
|
|
|
266
285
|
};
|
|
267
286
|
}
|
|
268
287
|
}, [K]), $ = n(async () => {
|
|
269
|
-
let t = e.getState(), n =
|
|
270
|
-
if (!n ||
|
|
288
|
+
let t = e.getState(), n = x(), r = t.workspaceToken, i = t.currentWorkspaceId;
|
|
289
|
+
if (!n || g(n) || !r || !i) return [];
|
|
271
290
|
t.setLoadingProjects(!0), z(null);
|
|
272
291
|
try {
|
|
273
292
|
let e = await c({
|
|
274
293
|
gateway: "workspace",
|
|
275
|
-
query:
|
|
294
|
+
query: p,
|
|
276
295
|
authToken: n,
|
|
277
296
|
workspaceToken: r,
|
|
278
297
|
baseUrl: K
|
|
279
298
|
});
|
|
280
299
|
if (e.errors?.length) {
|
|
281
300
|
let t = e.errors[0]?.message ?? "GraphQL error";
|
|
282
|
-
throw
|
|
301
|
+
throw b(e.errors) ? new y(t) : (console.error("Failed to fetch projects:", e.errors), Error(t));
|
|
283
302
|
}
|
|
284
303
|
let i = e.data?.projects?.items ?? [];
|
|
285
304
|
return t.setProjects(i), i;
|
|
286
305
|
} catch (e) {
|
|
287
|
-
if (e instanceof
|
|
306
|
+
if (e instanceof y) return [];
|
|
288
307
|
let t = e instanceof Error ? e.message : "Failed to fetch projects";
|
|
289
308
|
return console.error("Failed to fetch projects:", e), z(t), [];
|
|
290
309
|
} finally {
|
|
291
310
|
t.setLoadingProjects(!1);
|
|
292
311
|
}
|
|
293
|
-
}, [K]),
|
|
312
|
+
}, [K]), ne = n(async (t) => {
|
|
294
313
|
let n = e.getState();
|
|
295
314
|
return n.setCurrentWorkspaceId(null), n.setWorkspaceToken(null), n.setProjects([]), n.setCurrentProjectId(null), n.setCurrentOrganizationId(t.id), await Z(t.id);
|
|
296
|
-
}, [Z]),
|
|
315
|
+
}, [Z]), re = n(async (t) => {
|
|
297
316
|
let n = e.getState();
|
|
298
317
|
if (n.setCurrentProjectId(null), n.setProjects([]), !t.organizationId) return console.error("Workspace missing organizationId:", t), {
|
|
299
318
|
success: !1,
|
|
300
319
|
error: "Workspace is missing organizationId"
|
|
301
320
|
};
|
|
302
|
-
let r = await Q(t.organizationId, t.id);
|
|
321
|
+
let r = await Q(t.organizationId, t.id, void 0, t.tenantId);
|
|
303
322
|
if (!r.success) return {
|
|
304
323
|
success: !1,
|
|
305
324
|
error: r.error
|
|
306
325
|
};
|
|
307
326
|
let i = await $();
|
|
308
327
|
if (i.length === 0) {
|
|
309
|
-
let t =
|
|
328
|
+
let t = x(), r = e.getState().workspaceToken;
|
|
310
329
|
if (t && r) {
|
|
311
|
-
let e = await
|
|
330
|
+
let e = await h({
|
|
312
331
|
authToken: t,
|
|
313
332
|
workspaceBaseUrl: K,
|
|
314
333
|
workspaceToken: r
|
|
@@ -324,9 +343,9 @@ function D(s) {
|
|
|
324
343
|
Q,
|
|
325
344
|
$,
|
|
326
345
|
K
|
|
327
|
-
]),
|
|
346
|
+
]), ie = n((t) => {
|
|
328
347
|
let n = e.getState();
|
|
329
|
-
n.setCurrentProjectId(t.id), n.workspaceToken && !
|
|
348
|
+
n.setCurrentProjectId(t.id), n.workspaceToken && !v(n.workspaceToken, {
|
|
330
349
|
workspaceId: n.currentWorkspaceId,
|
|
331
350
|
organizationId: n.currentOrganizationId,
|
|
332
351
|
projectId: t.id
|
|
@@ -349,49 +368,49 @@ function D(s) {
|
|
|
349
368
|
}, r = n(() => $()), i = n(() => {
|
|
350
369
|
let t = e.getState().currentOrganizationId;
|
|
351
370
|
return t ? Z(t) : Promise.resolve();
|
|
352
|
-
}), a =
|
|
371
|
+
}), a = O.onAny((t) => {
|
|
353
372
|
let n = t.name;
|
|
354
|
-
if (
|
|
355
|
-
let n =
|
|
373
|
+
if (C.has(n)) {
|
|
374
|
+
let n = T(t.payload), { currentWorkspaceId: i } = e.getState();
|
|
356
375
|
if (n && i && n !== i) return;
|
|
357
376
|
r();
|
|
358
377
|
return;
|
|
359
378
|
}
|
|
360
|
-
|
|
379
|
+
w.has(n) && i();
|
|
361
380
|
});
|
|
362
381
|
return () => {
|
|
363
382
|
t = !0, a();
|
|
364
383
|
};
|
|
365
384
|
}, [
|
|
366
|
-
|
|
385
|
+
O,
|
|
367
386
|
$,
|
|
368
387
|
Z
|
|
369
388
|
]), {
|
|
370
|
-
organizations:
|
|
371
|
-
workspaces:
|
|
389
|
+
organizations: k,
|
|
390
|
+
workspaces: M,
|
|
372
391
|
projects: I,
|
|
373
|
-
currentOrganizationId:
|
|
374
|
-
currentWorkspaceId:
|
|
392
|
+
currentOrganizationId: A,
|
|
393
|
+
currentWorkspaceId: N,
|
|
375
394
|
currentProjectId: L,
|
|
376
|
-
currentOrganization:
|
|
377
|
-
currentWorkspace:
|
|
395
|
+
currentOrganization: k.find((e) => e.id === A),
|
|
396
|
+
currentWorkspace: M.find((e) => e.id === N),
|
|
378
397
|
currentProject: I.find((e) => e.id === L),
|
|
379
|
-
workspaceToken:
|
|
380
|
-
isLoadingOrganizations:
|
|
398
|
+
workspaceToken: P,
|
|
399
|
+
isLoadingOrganizations: j,
|
|
381
400
|
isLoadingWorkspaces: F,
|
|
382
401
|
isLoadingProjects: R,
|
|
383
|
-
isLoading:
|
|
384
|
-
error:
|
|
385
|
-
fetchOrganizations:
|
|
402
|
+
isLoading: j || F || R,
|
|
403
|
+
error: ee,
|
|
404
|
+
fetchOrganizations: te,
|
|
386
405
|
fetchWorkspacesForOrg: Z,
|
|
387
406
|
issueWorkspaceToken: Q,
|
|
388
407
|
fetchProjects: $,
|
|
389
|
-
selectOrganization:
|
|
390
|
-
selectWorkspace:
|
|
391
|
-
selectProject:
|
|
408
|
+
selectOrganization: ne,
|
|
409
|
+
selectWorkspace: re,
|
|
410
|
+
selectProject: ie
|
|
392
411
|
};
|
|
393
412
|
}
|
|
394
|
-
function
|
|
413
|
+
function D(n) {
|
|
395
414
|
let i = e((e) => e.currentOrganizationId), a = e((e) => e.workspaces), o = e((e) => e.accessToken), s = e((e) => e.isLoadingWorkspaces), l = t(), u = n?.globalBaseUrl ?? l.globalBaseUrl, f = n?.disableWorkspaceSync ?? !1;
|
|
396
415
|
r(() => {
|
|
397
416
|
if (f || !i || !o || s) return;
|
|
@@ -421,10 +440,10 @@ function O(n) {
|
|
|
421
440
|
f
|
|
422
441
|
]);
|
|
423
442
|
}
|
|
424
|
-
function
|
|
425
|
-
let a = e((e) => e.currentWorkspaceId), o = e((e) => e.currentOrganizationId), s = e((e) => e.workspaces), l = e((e) => e.projects), u = e((e) => e.currentProjectId), d = e((e) => e.workspaceToken),
|
|
443
|
+
function O(n) {
|
|
444
|
+
let a = e((e) => e.currentWorkspaceId), o = e((e) => e.currentOrganizationId), s = e((e) => e.workspaces), l = e((e) => e.projects), u = e((e) => e.currentProjectId), d = e((e) => e.workspaceToken), m = e((e) => e.accessToken), _ = t(), y = n?.workspaceBaseUrl ?? _.workspaceBaseUrl, b = n?.disableProjectSync ?? !1, x = n?.skipProjectFetch ?? !1, S = i(!1), C = i(/* @__PURE__ */ new Map()), w = i(/* @__PURE__ */ new Map()), T = 3e4;
|
|
426
445
|
r(() => {
|
|
427
|
-
if (b || !a || !
|
|
446
|
+
if (b || !a || !m || S.current) return;
|
|
428
447
|
let t = w.current.get(a);
|
|
429
448
|
if (t && t.count >= 8 && Date.now() - t.lastFailureAt < T) return;
|
|
430
449
|
t && Date.now() - t.lastFailureAt >= T && w.current.delete(a);
|
|
@@ -432,12 +451,12 @@ function k(n) {
|
|
|
432
451
|
if (n && o && n.organizationId !== o) return;
|
|
433
452
|
let r = n?.organizationId ?? o;
|
|
434
453
|
if (!r) return;
|
|
435
|
-
let i = e.getState(),
|
|
454
|
+
let i = e.getState(), _ = !d || g(d) || !v(d, {
|
|
436
455
|
workspaceId: a,
|
|
437
456
|
organizationId: o,
|
|
438
457
|
projectId: u
|
|
439
458
|
}), E = l.some((e) => e.workspaceId === a);
|
|
440
|
-
if (E && !
|
|
459
|
+
if (E && !_) {
|
|
441
460
|
if (!i.currentProjectId) {
|
|
442
461
|
let e = l.find((e) => e.workspaceId === a);
|
|
443
462
|
e && i.setCurrentProjectId(e.id);
|
|
@@ -449,17 +468,18 @@ function k(n) {
|
|
|
449
468
|
let t = !1;
|
|
450
469
|
try {
|
|
451
470
|
let e = d;
|
|
452
|
-
if (
|
|
471
|
+
if (_) {
|
|
453
472
|
let t = await c({
|
|
454
473
|
gateway: "workspace",
|
|
455
|
-
query:
|
|
474
|
+
query: f,
|
|
456
475
|
variables: { input: {
|
|
457
476
|
organizationId: r,
|
|
458
477
|
workspaceId: a,
|
|
459
478
|
...u ? { projectId: u } : {}
|
|
460
479
|
} },
|
|
461
|
-
authToken:
|
|
462
|
-
baseUrl:
|
|
480
|
+
authToken: m,
|
|
481
|
+
baseUrl: y,
|
|
482
|
+
tenantId: s.find((e) => e.id === a)?.tenantId
|
|
463
483
|
});
|
|
464
484
|
if (t.data?.issueWorkspaceToken?.success && t.data.issueWorkspaceToken.token) e = t.data.issueWorkspaceToken.token, i.setWorkspaceToken(e);
|
|
465
485
|
else return;
|
|
@@ -467,17 +487,17 @@ function k(n) {
|
|
|
467
487
|
if (e && !E && !x) {
|
|
468
488
|
let t = await c({
|
|
469
489
|
gateway: "workspace",
|
|
470
|
-
query:
|
|
471
|
-
authToken:
|
|
490
|
+
query: p,
|
|
491
|
+
authToken: m,
|
|
472
492
|
workspaceToken: e,
|
|
473
|
-
baseUrl:
|
|
493
|
+
baseUrl: y
|
|
474
494
|
});
|
|
475
495
|
if (t.errors?.length) return;
|
|
476
496
|
let n = t.data?.projects?.items ?? [];
|
|
477
497
|
if (n.length === 0) {
|
|
478
|
-
let t = await
|
|
479
|
-
authToken:
|
|
480
|
-
workspaceBaseUrl:
|
|
498
|
+
let t = await h({
|
|
499
|
+
authToken: m,
|
|
500
|
+
workspaceBaseUrl: y,
|
|
481
501
|
workspaceToken: e
|
|
482
502
|
});
|
|
483
503
|
if (t) n = [t];
|
|
@@ -519,8 +539,8 @@ function k(n) {
|
|
|
519
539
|
l,
|
|
520
540
|
u,
|
|
521
541
|
d,
|
|
522
|
-
|
|
523
|
-
|
|
542
|
+
m,
|
|
543
|
+
y,
|
|
524
544
|
b,
|
|
525
545
|
x
|
|
526
546
|
]), r(() => {
|
|
@@ -531,6 +551,6 @@ function k(n) {
|
|
|
531
551
|
}, []);
|
|
532
552
|
}
|
|
533
553
|
//#endregion
|
|
534
|
-
export {
|
|
554
|
+
export { E as useContextSwitcherData, O as useProjectSyncEffect, D as useWorkspaceSyncEffect };
|
|
535
555
|
|
|
536
556
|
//# sourceMappingURL=useContextSwitcherData.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useContextSwitcherData.js","names":[],"sources":["../../../src/auth/hooks/useContextSwitcherData.ts"],"sourcesContent":["import { useCallback, useState, useEffect, useRef } from \"react\";\nimport {\n graphqlFetch,\n getStoredAuthToken,\n} from \"@burdenoff/fe-libs/shared/graphql\";\nimport { useActiveContext } from \"@burdenoff/fe-libs/shared/providers/shell/ActiveContextProvider\";\nimport { useEventBus } from \"@burdenoff/fe-libs/shared/events\";\nimport { useAuthStore } from \"../store/authStore\";\nimport type { Organization, Workspace, Project } from \"../types\";\nimport { resolveGatewayBaseUrls } from \"../utils/gatewayBaseUrls\";\n\n// =============================================================================\n// Hook Options\n// =============================================================================\n\nexport interface UseContextSwitcherDataOptions {\n /**\n * Optional Global API Gateway base URL override.\n * If not provided, uses GATEWAYS config from fe-libs.\n */\n globalBaseUrl?: string;\n /**\n * Optional Workspaces API Gateway base URL override.\n * If not provided, uses GATEWAYS config from fe-libs.\n */\n workspaceBaseUrl?: string;\n /** Disable initial organization/workspace bootstrap fetches */\n disableBootstrap?: boolean;\n /** Disable the workspace sync effect */\n disableWorkspaceSync?: boolean;\n /** Disable the project sync effect */\n disableProjectSync?: boolean;\n /** Only hydrate the workspace token; do not eagerly fetch projects */\n skipProjectFetch?: boolean;\n}\n\n// =============================================================================\n// GraphQL Response Types\n// =============================================================================\n\ninterface MyOrganizationsResponse {\n myOrganizations: {\n total: number;\n items: Organization[];\n };\n}\n\ninterface WorkspacesByOrgResponse {\n workspaces: {\n total: number;\n items: Workspace[];\n };\n}\n\ninterface IssueWorkspaceTokenResult {\n success: boolean;\n token: string | null;\n expiresAt: string | null;\n organizationId: string | null;\n workspaceId: string | null;\n projectId: string | null;\n scopes: string[] | null;\n error: {\n code: string;\n message: string;\n } | null;\n}\n\ninterface ProjectsResponse {\n projects: {\n total: number;\n items: Project[];\n };\n}\n\ninterface CreateProjectResponse {\n createProject: Project;\n}\n\n// =============================================================================\n// GraphQL Query/Mutation Strings\n// =============================================================================\n\nconst MY_ORGANIZATIONS_QUERY = `\n query MyOrganizations {\n myOrganizations {\n total\n items {\n id\n name\n slug\n tenantId\n description\n logo\n website\n status\n type\n createdAt\n updatedAt\n }\n }\n }\n`;\n\n// Both queries below historically used `workspaces(filter: $filter)` with\n// a `WorkspaceFilterInput` to fetch workspaces for a specific organization.\n// That Query field was removed/renamed in the global subgraph; calling it\n// now throws GRAPHQL_VALIDATION_FAILED (\"Cannot query field 'workspaces'\n// on type 'Query'\") which crashes the context switcher and cascades into a\n// \"Verifying workspace access...\" stuck-spinner on every Platform module\n// route (/billing, /support, /notifications, /devportal).\n//\n// The supported field is `myWorkspaces(limit, offset)` on the global\n// subgraph — self-scoped, returns the caller's workspaces across all\n// orgs. It does NOT accept a filter, so we fetch up to 100 of \"my\"\n// workspaces and let the existing downstream auto-pick logic filter by\n// organizationId client-side. The recovery path at line ~624 already\n// uses this exact aliased pattern; we're just promoting it to the\n// primary path.\nconst WORKSPACES_BY_ORG_QUERY = `\n query WorkspacesByOrg {\n workspaces: myWorkspaces(limit: 100) {\n total\n items {\n id\n name\n slug\n tenantId\n organizationId\n type\n status\n region\n createdAt\n updatedAt\n }\n }\n }\n`;\n\nconst CONTEXT_SWITCHER_BOOTSTRAP_QUERY = `\n query ContextSwitcherBootstrap {\n myOrganizations {\n total\n items {\n id\n name\n slug\n tenantId\n description\n logo\n website\n status\n type\n createdAt\n updatedAt\n }\n }\n workspaces: myWorkspaces(limit: 100) {\n total\n items {\n id\n name\n slug\n tenantId\n organizationId\n type\n status\n region\n createdAt\n updatedAt\n }\n }\n }\n`;\n\nconst ISSUE_WORKSPACE_TOKEN_MUTATION = `\n mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {\n issueWorkspaceToken(input: $input) {\n success\n token\n expiresAt\n organizationId\n workspaceId\n projectId\n scopes\n error {\n code\n message\n }\n }\n }\n`;\n\n// The workspace gateway exposes `myProjects` (public RBAC, caller-scoped to\n// the active workspace via x-workspace-id) and the privileged\n// `projects(filter)` (list:project). The header has no `list:project`\n// permission seeded for the typical operator, so the privileged form\n// returns FORBIDDEN even though the caller is a member of the workspace.\n// `myProjects` is the right field for \"give me the projects I can see in\n// this workspace\" — workspace scope is already established by the\n// workspace token + x-workspace-id header that we pass with the request.\nconst PROJECTS_QUERY = `\n query MyProjectsForContext {\n projects: myProjects {\n total\n items {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n }\n`;\n\nconst CREATE_DEFAULT_PROJECT_MUTATION = `\n mutation CreateDefaultProject($input: CreateProjectInput!) {\n createProject(input: $input) {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n`;\n\nasync function createDefaultProject({\n authToken,\n workspaceBaseUrl,\n workspaceToken,\n}: {\n authToken: string;\n workspaceBaseUrl: string;\n workspaceToken: string;\n}): Promise<Project | null> {\n const result = await graphqlFetch<CreateProjectResponse>({\n gateway: \"workspace\",\n query: CREATE_DEFAULT_PROJECT_MUTATION,\n variables: {\n input: {\n name: \"Default Project\",\n },\n },\n authToken,\n workspaceToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (result.errors?.length) {\n console.warn(\"Failed to create default project:\", result.errors);\n return null;\n }\n\n return result.data?.createProject ?? null;\n}\n\n// =============================================================================\n// Auth Helpers\n// =============================================================================\n\n/**\n * Check whether a JWT is expired (or within bufferMs of expiry).\n * Returns true if the token is expired, close to expiry, or malformed.\n */\nfunction isTokenExpired(token: string, bufferMs = 30_000): boolean {\n try {\n const payload = JSON.parse(atob(token.split(\".\")[1]));\n if (!payload.exp) return false;\n return payload.exp * 1000 < Date.now() + bufferMs;\n } catch {\n return true;\n }\n}\n\nfunction getWorkspaceTokenPayload(token: string): {\n workspaceId?: string;\n organizationId?: string;\n projectId?: string;\n exp?: number;\n} | null {\n try {\n const payload = JSON.parse(atob(token.split(\".\")[1]));\n return {\n workspaceId:\n typeof payload.workspaceId === \"string\"\n ? payload.workspaceId\n : undefined,\n organizationId:\n typeof payload.organizationId === \"string\"\n ? payload.organizationId\n : undefined,\n projectId:\n typeof payload.projectId === \"string\" ? payload.projectId : undefined,\n exp: typeof payload.exp === \"number\" ? payload.exp : undefined,\n };\n } catch {\n return null;\n }\n}\n\nfunction isWorkspaceTokenValidForContext(\n token: string | null | undefined,\n expected: {\n workspaceId?: string | null;\n organizationId?: string | null;\n projectId?: string | null;\n },\n): token is string {\n if (!token || isTokenExpired(token)) {\n return false;\n }\n\n const payload = getWorkspaceTokenPayload(token);\n if (!payload) {\n return false;\n }\n\n if (expected.workspaceId && payload.workspaceId !== expected.workspaceId) {\n return false;\n }\n\n if (\n expected.organizationId &&\n payload.organizationId !== expected.organizationId\n ) {\n return false;\n }\n\n if (expected.projectId && payload.projectId !== expected.projectId) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Custom error class for auth-related failures (expired token, unauthorized, etc.).\n * Used to distinguish auth errors in outer catch blocks so they can be\n * suppressed from console.error — they are expected during token refresh cycles\n * and do not indicate application bugs.\n */\nclass AuthError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\n/**\n * Detect whether a set of GraphQL errors are authentication-related.\n */\nfunction isAuthGraphQLError(\n errors: Array<{ message?: string; extensions?: { code?: string } }>,\n): boolean {\n return errors.some(\n (e) =>\n e.extensions?.code === \"UNAUTHENTICATED\" ||\n e.message?.toLowerCase().includes(\"unauthorized\") ||\n e.message?.toLowerCase().includes(\"not authenticated\"),\n );\n}\n\n/**\n * Resolve the best available access token:\n * 1. Try the zustand store token\n * 2. If expired, fall back to profile storage (may have been refreshed)\n * 3. Return null if no valid token is available\n */\nfunction resolveAccessToken(): string | null {\n const storeToken = useAuthStore.getState().accessToken;\n\n // If store token is valid (or has no exp claim), use it\n if (storeToken && !isTokenExpired(storeToken)) {\n return storeToken;\n }\n\n // Store token is expired or missing — try profile storage (may be fresher)\n const profileToken = getStoredAuthToken();\n if (profileToken && !isTokenExpired(profileToken)) {\n return profileToken;\n }\n\n // Both expired or missing — if store token exists at all, return it as a last\n // resort (the gateway will reject it and the useEffect will re-trigger after\n // token refresh). Returning null would silently swallow the first load.\n return storeToken;\n}\n\nfunction buildFallbackOrganizations(workspaces: Workspace[]): Organization[] {\n const uniqueOrgIds = Array.from(\n new Set(\n workspaces.flatMap((workspace) =>\n workspace.organizationId ? [workspace.organizationId] : [],\n ),\n ),\n );\n\n return uniqueOrgIds.map((organizationId, index) => ({\n id: organizationId,\n name:\n workspaces.find(\n (workspace) => workspace.organizationId === organizationId,\n )?.name || `Organization ${index + 1}`,\n slug: organizationId,\n tenantId:\n workspaces.find(\n (workspace) => workspace.organizationId === organizationId,\n )?.tenantId || \"\",\n }));\n}\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Hook for managing the context switcher data (organizations, workspaces, projects)\n *\n * Data flow:\n * 1. fetchOrganizations() - Get all orgs user has access to (Global Gateway)\n * 2. selectOrganization(org) - Set current org & fetch workspaces for that org\n * 3. selectWorkspace(ws) - Issue workspace token & fetch projects\n * 4. selectProject(proj) - Set current project\n *\n * All GraphQL calls go through graphqlFetch from fe-libs which automatically\n * resolves gateway URLs and injects auth + locale headers.\n *\n * @param options - Optional configuration (gateway base URL overrides)\n */\n// Domain events emitted by microfe-workspaces that should refresh the switcher's\n// cached lists. Module-scoped so they aren't reallocated on every effect run.\nconst PROJECT_REFRESH_EVENTS = new Set<string>([\n \"project.created\",\n \"project.updated\",\n \"project.deleted\",\n \"project.archived\",\n \"project.unarchived\",\n]);\nconst WORKSPACE_REFRESH_EVENTS = new Set<string>([\n \"workspace.created\",\n \"workspace.updated\",\n \"workspace.deleted\",\n \"workspace.archived\",\n \"workspace.reactivated\",\n]);\n\n// Safely read a string `workspaceId` off a cross-MFE event payload of unknown\n// shape, rather than trusting a bare cast (the payload is produced by another\n// MFE and could drift). Returns undefined when absent or not a string.\nfunction readEventWorkspaceId(payload: unknown): string | undefined {\n if (payload && typeof payload === \"object\" && \"workspaceId\" in payload) {\n const value = (payload as { workspaceId?: unknown }).workspaceId;\n return typeof value === \"string\" ? value : undefined;\n }\n return undefined;\n}\n\nexport function useContextSwitcherData(\n options?: UseContextSwitcherDataOptions,\n) {\n const {\n organizationId: activeOrganizationId,\n workspaceId: activeWorkspaceId,\n projectId: activeProjectId,\n setContext: setActiveContext,\n } = useActiveContext();\n\n const eventBus = useEventBus();\n\n // Use selectors for reactive state\n const organizations = useAuthStore((state) => state.organizations);\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const isLoadingOrganizations = useAuthStore(\n (state) => state.isLoadingOrganizations,\n );\n\n const workspaces = useAuthStore((state) => state.workspaces);\n const currentWorkspaceId = useAuthStore((state) => state.currentWorkspaceId);\n const workspaceToken = useAuthStore((state) => state.workspaceToken);\n const isLoadingWorkspaces = useAuthStore(\n (state) => state.isLoadingWorkspaces,\n );\n\n const projects = useAuthStore((state) => state.projects);\n const currentProjectId = useAuthStore((state) => state.currentProjectId);\n const isLoadingProjects = useAuthStore((state) => state.isLoadingProjects);\n\n // Local error state\n const [error, setError] = useState<string | null>(null);\n\n // Deduplication refs to prevent duplicate GraphQL calls\n const fetchOrganizationsPromiseRef = useRef<Promise<Organization[]> | null>(\n null,\n );\n const fetchWorkspacesPromisesRef = useRef<Map<string, Promise<Workspace[]>>>(\n new Map(),\n );\n\n // Stable refs for latest context values — avoids stale closures in callbacks\n // without adding them to useCallback dep arrays (which would recreate callbacks\n // on every context change and trigger spurious fetch re-runs).\n const activeWorkspaceIdRef = useRef(activeWorkspaceId);\n const activeOrganizationIdRef = useRef(activeOrganizationId);\n useEffect(() => {\n activeWorkspaceIdRef.current = activeWorkspaceId;\n activeOrganizationIdRef.current = activeOrganizationId;\n });\n\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const globalBaseUrl =\n options?.globalBaseUrl ?? resolvedBaseUrls.globalBaseUrl;\n const workspaceBaseUrl =\n options?.workspaceBaseUrl ?? resolvedBaseUrls.workspaceBaseUrl;\n\n // Refs to break feedback loops with the Header's \"store → URL\" sync effect.\n // Without these the pair can ping-pong: this effect writes (URL → store),\n // Header writes (store → URL), Zustand re-fires our subscribers, and React\n // hits \"Maximum update depth exceeded\" — especially when a downstream call\n // (workspace token issuance) returns 504 and leaves the two halves in\n // disagreement. The refs record the last value we pushed for each axis;\n // identical pushes are skipped so the loop has a hard floor.\n const lastAppliedOrgIdRef = useRef<string | null>(null);\n const lastAppliedWorkspaceIdRef = useRef<string | null>(null);\n const lastAppliedProjectIdRef = useRef<string | null>(null);\n const lastClearedTokenContextRef = useRef<string | null>(null);\n\n useEffect(() => {\n const store = useAuthStore.getState();\n\n if (\n activeOrganizationId &&\n activeOrganizationId !== store.currentOrganizationId &&\n activeOrganizationId !== lastAppliedOrgIdRef.current\n ) {\n lastAppliedOrgIdRef.current = activeOrganizationId;\n store.setCurrentOrganizationId(activeOrganizationId);\n if (\n store.workspaces.length > 0 &&\n !store.workspaces.some(\n (workspace) => workspace.organizationId === activeOrganizationId,\n )\n ) {\n store.setWorkspaces([]);\n }\n }\n\n if (\n activeWorkspaceId &&\n activeWorkspaceId !== store.currentWorkspaceId &&\n activeWorkspaceId !== lastAppliedWorkspaceIdRef.current\n ) {\n lastAppliedWorkspaceIdRef.current = activeWorkspaceId;\n store.setCurrentWorkspaceId(activeWorkspaceId);\n if (\n store.projects.length > 0 &&\n !store.projects.some(\n (project) => project.workspaceId === activeWorkspaceId,\n )\n ) {\n store.setProjects([]);\n store.setCurrentProjectId(null);\n }\n }\n\n if (\n activeProjectId &&\n activeProjectId !== store.currentProjectId &&\n activeProjectId !== lastAppliedProjectIdRef.current\n ) {\n lastAppliedProjectIdRef.current = activeProjectId;\n store.setCurrentProjectId(activeProjectId);\n }\n\n if (\n store.workspaceToken &&\n !isWorkspaceTokenValidForContext(store.workspaceToken, {\n workspaceId: activeWorkspaceId,\n organizationId: activeOrganizationId,\n projectId: activeProjectId,\n })\n ) {\n // Clear-token-once-per-context guard: when the upstream gateway is\n // flaky (504s during workspace token issuance) the surrounding state\n // machine can oscillate between \"got token but invalid\" and \"clearing\n // token\". The downstream re-issue path then loops. Only clear once per\n // (org, ws, proj) tuple — a successful re-issue resets the ref via\n // setWorkspaceToken landing a new token for the same context.\n const ctxKey = `${activeOrganizationId ?? \"\"}|${activeWorkspaceId ?? \"\"}|${activeProjectId ?? \"\"}`;\n if (lastClearedTokenContextRef.current !== ctxKey) {\n lastClearedTokenContextRef.current = ctxKey;\n store.setWorkspaceToken(null);\n }\n }\n }, [activeOrganizationId, activeWorkspaceId, activeProjectId]);\n\n // ===========================================================================\n // Fetch Organizations (Global Gateway)\n // ===========================================================================\n\n const fetchOrganizations = useCallback(async (): Promise<Organization[]> => {\n // Deduplicate: if a fetch is already in progress, return the same promise\n if (fetchOrganizationsPromiseRef.current) {\n return fetchOrganizationsPromiseRef.current;\n }\n\n const store = useAuthStore.getState();\n const token = resolveAccessToken();\n\n if (!token) {\n // Not an error — user may not be authenticated yet (e.g., page load before login).\n // The useEffect in Header.tsx will re-trigger when accessToken becomes available.\n return [];\n }\n\n // If the token is clearly expired and no fresh fallback was found, skip the\n // doomed request. The useEffect in Header.tsx re-triggers when the auth\n // provider refreshes the token and updates accessToken in the store.\n if (isTokenExpired(token)) {\n return [];\n }\n\n store.setLoadingOrganizations(true);\n setError(null);\n\n // Store the promise for deduplication before starting\n fetchOrganizationsPromiseRef.current = (async () => {\n try {\n const initialTargetOrgId =\n activeOrganizationIdRef.current ?? store.currentOrganizationId;\n let result = await graphqlFetch<\n MyOrganizationsResponse & Partial<WorkspacesByOrgResponse>\n >({\n gateway: \"global\",\n query: initialTargetOrgId\n ? CONTEXT_SWITCHER_BOOTSTRAP_QUERY\n : MY_ORGANIZATIONS_QUERY,\n // Both queries are now parameter-less (the legacy `filter` arg\n // was for the removed `workspaces(filter:)` field; `myWorkspaces`\n // doesn't accept it). Downstream code filters by organizationId\n // client-side.\n variables: undefined,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n\n // Self-heal stale-URL case: bootstrap query embeds\n // workspaces(filter: {organizationId: <urlOrg>}) — when the user\n // isn't a member of that org (URL was bookmarked from a different\n // tenant, org was deleted, etc.), the workspaces resolver throws\n // FORBIDDEN which blanks the entire data block, masking\n // myOrganizations as the visible error. Retry with the simpler\n // MY_ORGANIZATIONS_QUERY so the operator sees their actual orgs\n // and the URL params get corrected on next render.\n if (\n initialTargetOrgId &&\n result.errors?.length &&\n result.errors.some(\n (e) =>\n e?.extensions?.code === \"FORBIDDEN\" ||\n /not a member of this organization/i.test(e?.message ?? \"\") ||\n // Public gateway often drops the underlying FORBIDDEN error\n // and replaces it with the schema-level non-null violation\n // (\"Cannot return null for non-nullable field Query.myOrganizations\").\n // That happens when ANY field in the query throws — workspaces\n // here — and data:null cascades up. Treat that pattern as a\n // signal to retry without the workspaces filter.\n /Cannot return null for non-nullable field Query\\.myOrganizations/i.test(\n e?.message ?? \"\",\n ),\n )\n ) {\n // Fetch myOrganizations + ALL workspaces (no filter) so the\n // downstream auto-pick logic still has a workspace list to seed\n // context from. If we only refetched myOrganizations, the page\n // would render but every workspace-scoped query would fail with\n // \"Select a workspace…\".\n result = await graphqlFetch<\n MyOrganizationsResponse & Partial<WorkspacesByOrgResponse>\n >({\n gateway: \"global\",\n query: `\n query ContextSwitcherRecover {\n myOrganizations {\n total\n items { id name slug tenantId description logo website status type createdAt updatedAt }\n }\n workspaces: myWorkspaces {\n total\n items { id name slug tenantId organizationId type status region createdAt updatedAt }\n }\n }\n `,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n }\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n // Auth errors are expected during token refresh cycles — throw AuthError\n // so the outer catch can suppress console.error.\n throw new AuthError(errorMessage);\n }\n if (store.workspaces.length === 0) {\n console.error(\"Failed to fetch organizations:\", result.errors);\n }\n throw new Error(errorMessage);\n }\n\n let orgs: Organization[] = result.data?.myOrganizations?.items ?? [];\n\n // Stale-context recovery: bootstrap query was filtered by\n // initialTargetOrgId, so when the URL/persisted org doesn't belong to\n // this user the response is empty. Re-fetch the unfiltered list of\n // *all* orgs the user can access so the guard below can pick a real\n // default. Skip the recovery when no target was set (already\n // unfiltered) or when workspaces are already in the store (the\n // existing fallback path covers that case).\n if (\n initialTargetOrgId &&\n orgs.length === 0 &&\n store.workspaces.length === 0\n ) {\n const recovery = await graphqlFetch<MyOrganizationsResponse>({\n gateway: \"global\",\n query: MY_ORGANIZATIONS_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n if (!recovery.errors?.length) {\n orgs = recovery.data?.myOrganizations?.items ?? [];\n // discard the filtered workspaces payload — it was for the\n // ghost org and would only mislead the workspace selector below.\n result = {\n ...recovery,\n data: {\n myOrganizations: recovery.data?.myOrganizations ?? {\n items: [],\n total: 0,\n },\n },\n };\n } else {\n // Surface the failure so a user reporting \"blank org list\" has\n // something to grep for in the console. We still fall through —\n // the guard below either picks from a fallback (workspaces in\n // store) or no-ops, leaving the existing error path in place.\n console.warn(\n \"[ContextSwitcher] Stale-context recovery failed:\",\n recovery.errors,\n );\n }\n }\n\n const fallbackOrganizations =\n orgs.length === 0 && store.workspaces.length > 0\n ? buildFallbackOrganizations(store.workspaces)\n : [];\n const effectiveOrganizations =\n fallbackOrganizations.length > 0 ? fallbackOrganizations : orgs;\n\n store.setOrganizations(effectiveOrganizations);\n\n // Determine which organization to use for workspace fetching\n let targetOrgId = initialTargetOrgId;\n\n // Stale-context guard: if the persisted/URL org isn't in the user's\n // accessible orgs, fall back to the first available one and clear the\n // stale workspace/project so they get re-derived. Without this, URL\n // params like ?org=<ghost-id> from a prior session leak into the new\n // user's request headers and cause \"Authentication required\" /\n // \"not a member\" errors at every subgraph.\n //\n // Check against `orgs` (freshly returned from the API in this same\n // closure) rather than `effectiveOrganizations`, which can fall back\n // to ids derived from `store.workspaces` — that fallback path could\n // contain stale ghost orgIds and mask the guard.\n const targetOrgIsAccessible =\n targetOrgId && orgs.some((org) => org.id === targetOrgId);\n if (targetOrgId && !targetOrgIsAccessible && orgs.length > 0) {\n targetOrgId = orgs[0].id;\n setActiveContext({\n organizationId: targetOrgId,\n workspaceId: null,\n tenantId: null,\n projectId: null,\n });\n store.setWorkspaces([]);\n store.setProjects([]);\n store.setCurrentWorkspaceId(null);\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n }\n\n if (targetOrgId && targetOrgId !== store.currentOrganizationId) {\n store.setCurrentOrganizationId(targetOrgId);\n }\n\n // Auto-select first organization if none is selected\n if (effectiveOrganizations.length > 0 && !targetOrgId) {\n store.setCurrentOrganizationId(effectiveOrganizations[0].id);\n targetOrgId = effectiveOrganizations[0].id;\n }\n\n // Fetch workspaces for the selected/auto-selected org if:\n // 1. We have a target org (either auto-selected or persisted from localStorage)\n // 2. AND workspaces array is empty (not persisted, or cleared)\n // This handles both initial login AND page refresh scenarios.\n // Read from useAuthStore.getState() rather than the captured `store`\n // snapshot so we see the post-guard cleared value when the org guard\n // above fired (the local `store.workspaces` ref is stale after\n // setWorkspaces([])).\n if (targetOrgId && useAuthStore.getState().workspaces.length === 0) {\n store.setLoadingWorkspaces(true);\n try {\n // myWorkspaces returns ALL workspaces the user is a member of\n // across every org. Filter to the target org client-side here.\n const bootstrappedWorkspaces =\n initialTargetOrgId === targetOrgId\n ? result.data?.workspaces?.items?.filter(\n (w) => w.organizationId === targetOrgId,\n )\n : undefined;\n const ws = bootstrappedWorkspaces\n ? (bootstrappedWorkspaces as Workspace[])\n : await graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n }).then((wsResult) =>\n wsResult.errors?.length\n ? null\n : (wsResult.data?.workspaces?.items ?? []).filter(\n (w) => w.organizationId === targetOrgId,\n ),\n );\n\n if (ws) {\n store.setWorkspaces(ws);\n const persistedWorkspace = activeWorkspaceIdRef.current\n ? ws.find(\n (workspace) =>\n workspace.id === activeWorkspaceIdRef.current,\n )\n : null;\n\n if (persistedWorkspace) {\n store.setCurrentWorkspaceId(persistedWorkspace.id);\n } else if (ws.length > 0) {\n const nextActiveContext = {\n organizationId: targetOrgId,\n workspaceId: ws[0].id,\n tenantId: ws[0].tenantId,\n projectId: null,\n };\n\n if (activeWorkspaceIdRef.current) {\n // Stale-context guard: URL/persisted workspace ID is not in\n // the user's accessible workspaces for the active org. Fall\n // back to the first workspace and clear the stale URL param\n // so subsequent requests don't carry the ghost ID.\n store.setCurrentWorkspaceId(ws[0].id);\n store.setWorkspaceToken(null);\n setActiveContext(nextActiveContext);\n } else if (!store.currentWorkspaceId) {\n // Auto-select first workspace only if none is currently selected\n // (preserves selection from completeAuthFlow or persistence if applicable)\n store.setCurrentWorkspaceId(ws[0].id);\n setActiveContext(nextActiveContext);\n }\n }\n }\n } catch {\n // Non-critical — user can still select workspace manually\n } finally {\n store.setLoadingWorkspaces(false);\n }\n }\n\n return effectiveOrganizations;\n } catch (err) {\n // Auth errors are expected during token refresh / page load cycles.\n // Suppress from console.error — the useEffect will re-trigger when the\n // auth provider refreshes the token.\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch organizations\";\n if (store.workspaces.length === 0) {\n console.error(\"Failed to fetch organizations:\", err);\n }\n setError(message);\n\n if (store.workspaces.length > 0) {\n const fallbackOrganizations = buildFallbackOrganizations(\n store.workspaces,\n );\n if (fallbackOrganizations.length > 0) {\n store.setOrganizations(fallbackOrganizations);\n if (!store.currentOrganizationId) {\n store.setCurrentOrganizationId(fallbackOrganizations[0].id);\n }\n return fallbackOrganizations;\n }\n }\n\n return [];\n } finally {\n store.setLoadingOrganizations(false);\n fetchOrganizationsPromiseRef.current = null;\n }\n })();\n\n return fetchOrganizationsPromiseRef.current;\n }, [globalBaseUrl, setActiveContext]);\n\n // ===========================================================================\n // Fetch Workspaces for Organization (Global Gateway)\n // ===========================================================================\n\n const fetchWorkspacesForOrg = useCallback(\n async (organizationId: string): Promise<Workspace[]> => {\n // Deduplicate: if a fetch for this org is already in progress, return the same promise\n const existingPromise =\n fetchWorkspacesPromisesRef.current.get(organizationId);\n if (existingPromise) {\n return existingPromise;\n }\n\n const store = useAuthStore.getState();\n const token = resolveAccessToken();\n\n if (!token || isTokenExpired(token)) {\n return [];\n }\n\n store.setLoadingWorkspaces(true);\n setError(null);\n\n // Store the promise for deduplication before starting\n const fetchPromise = (async () => {\n try {\n const result = await graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n // myWorkspaces returns workspaces across all the user's orgs;\n // filter to the requested org before handing to downstream.\n if (result.data?.workspaces?.items) {\n result.data.workspaces.items = result.data.workspaces.items.filter(\n (w) => w.organizationId === organizationId,\n );\n }\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n throw new AuthError(errorMessage);\n }\n console.error(\"Failed to fetch workspaces:\", result.errors);\n throw new Error(errorMessage);\n }\n\n // `myWorkspaces` returns every workspace the caller can see across\n // all of their orgs/tenants. The store key is per-org (selecting\n // org X then opening the dropdown should only show X's workspaces),\n // so we filter down to the requested org here. The dropdown filter\n // in ContextSwitcher.tsx is a defence-in-depth — without this\n // narrowing the store would briefly hold the caller's other-org\n // workspaces and the auto-pick logic (lines below) might select\n // one of them as the default.\n const allWs: Workspace[] = result.data?.workspaces?.items ?? [];\n const ws = allWs.filter((w) => w.organizationId === organizationId);\n store.setWorkspaces(ws);\n return ws;\n } catch (err) {\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch workspaces\";\n console.error(\"Failed to fetch workspaces:\", err);\n setError(message);\n return [];\n } finally {\n store.setLoadingWorkspaces(false);\n fetchWorkspacesPromisesRef.current.delete(organizationId);\n }\n })();\n\n fetchWorkspacesPromisesRef.current.set(organizationId, fetchPromise);\n return fetchPromise;\n },\n [globalBaseUrl],\n );\n\n // ===========================================================================\n // Issue Workspace Token (Workspace Gateway - wspace-auth-svc)\n // ===========================================================================\n\n const issueWorkspaceToken = useCallback(\n async (\n organizationId: string,\n workspaceId?: string,\n projectId?: string | null,\n ): Promise<{\n success: boolean;\n token?: string;\n resolvedWorkspaceId?: string;\n error?: string;\n }> => {\n const store = useAuthStore.getState();\n const authToken = resolveAccessToken();\n\n if (!authToken || isTokenExpired(authToken)) {\n return { success: false, error: \"No valid access token available\" };\n }\n\n setError(null);\n\n try {\n const result = await graphqlFetch<{\n issueWorkspaceToken: IssueWorkspaceTokenResult;\n }>({\n gateway: \"workspace\",\n query: ISSUE_WORKSPACE_TOKEN_MUTATION,\n variables: {\n input: {\n organizationId,\n ...(workspaceId && { workspaceId }),\n ...(projectId && { projectId }),\n },\n },\n authToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (!isAuthGraphQLError(result.errors)) {\n console.error(\"Failed to issue workspace token:\", result.errors);\n }\n return { success: false, error: errorMessage };\n }\n\n const tokenResult = result.data?.issueWorkspaceToken;\n\n if (tokenResult?.success && tokenResult.token) {\n const resolvedWsId = tokenResult.workspaceId || workspaceId;\n if (resolvedWsId) {\n store.setCurrentWorkspaceId(resolvedWsId);\n }\n store.setWorkspaceToken(tokenResult.token);\n return {\n success: true,\n token: tokenResult.token,\n resolvedWorkspaceId: resolvedWsId || undefined,\n };\n }\n\n return {\n success: false,\n error:\n tokenResult?.error?.message ?? \"Failed to issue workspace token\",\n };\n } catch (err) {\n const message =\n err instanceof Error\n ? err.message\n : \"Failed to issue workspace token\";\n console.error(\"Failed to issue workspace token:\", err);\n setError(message);\n return { success: false, error: message };\n }\n },\n [workspaceBaseUrl],\n );\n\n // ===========================================================================\n // Fetch Projects (Workspace Gateway - requires workspace token)\n // ===========================================================================\n\n const fetchProjects = useCallback(async (): Promise<Project[]> => {\n const store = useAuthStore.getState();\n const authToken = resolveAccessToken();\n const wsToken = store.workspaceToken;\n const workspaceId = store.currentWorkspaceId;\n\n if (!authToken || isTokenExpired(authToken)) {\n return [];\n }\n\n if (!wsToken) {\n return [];\n }\n\n if (!workspaceId) {\n return [];\n }\n\n store.setLoadingProjects(true);\n setError(null);\n\n try {\n const result = await graphqlFetch<ProjectsResponse>({\n gateway: \"workspace\",\n query: PROJECTS_QUERY,\n authToken,\n workspaceToken: wsToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n throw new AuthError(errorMessage);\n }\n console.error(\"Failed to fetch projects:\", result.errors);\n throw new Error(errorMessage);\n }\n\n const projs: Project[] = result.data?.projects?.items ?? [];\n store.setProjects(projs);\n return projs;\n } catch (err) {\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch projects\";\n console.error(\"Failed to fetch projects:\", err);\n setError(message);\n return [];\n } finally {\n store.setLoadingProjects(false);\n }\n }, [workspaceBaseUrl]);\n\n // ===========================================================================\n // High-Level Selection Actions\n // ===========================================================================\n\n const selectOrganization = useCallback(\n async (org: Organization): Promise<Workspace[]> => {\n const store = useAuthStore.getState();\n\n store.setCurrentWorkspaceId(null);\n store.setWorkspaceToken(null);\n store.setProjects([]);\n store.setCurrentProjectId(null);\n store.setCurrentOrganizationId(org.id);\n\n const ws = await fetchWorkspacesForOrg(org.id);\n return ws;\n },\n [fetchWorkspacesForOrg],\n );\n\n const selectWorkspace = useCallback(\n async (\n workspace: Workspace,\n ): Promise<{\n success: boolean;\n projects?: Project[];\n error?: string;\n }> => {\n const store = useAuthStore.getState();\n\n store.setCurrentProjectId(null);\n store.setProjects([]);\n\n if (!workspace.organizationId) {\n console.error(\"Workspace missing organizationId:\", workspace);\n return {\n success: false,\n error: \"Workspace is missing organizationId\",\n };\n }\n\n const tokenResult = await issueWorkspaceToken(\n workspace.organizationId,\n workspace.id,\n );\n\n if (!tokenResult.success) {\n return { success: false, error: tokenResult.error };\n }\n\n let projs = await fetchProjects();\n if (projs.length === 0) {\n const authToken = resolveAccessToken();\n const workspaceToken = useAuthStore.getState().workspaceToken;\n if (authToken && workspaceToken) {\n const defaultProject = await createDefaultProject({\n authToken,\n workspaceBaseUrl,\n workspaceToken,\n });\n if (defaultProject) {\n projs = [defaultProject];\n store.setProjects(projs);\n }\n }\n }\n\n if (projs.length > 0) {\n store.setCurrentProjectId(projs[0]!.id);\n }\n\n return { success: true, projects: projs };\n },\n [issueWorkspaceToken, fetchProjects, workspaceBaseUrl],\n );\n\n const selectProject = useCallback((project: Project): void => {\n const store = useAuthStore.getState();\n store.setCurrentProjectId(project.id);\n if (\n store.workspaceToken &&\n !isWorkspaceTokenValidForContext(store.workspaceToken, {\n workspaceId: store.currentWorkspaceId,\n organizationId: store.currentOrganizationId,\n projectId: project.id,\n })\n ) {\n store.setWorkspaceToken(null);\n }\n }, []);\n\n // ===========================================================================\n // Cross-MFE refresh: keep the switcher lists current when another MFE mutates\n // org/workspace/project entities. microfe-workspaces emits these domain events\n // on the shared event bus (e.g. on project rename); without this the switcher\n // keeps showing the stale cached name until a full page reload.\n // ===========================================================================\n\n useEffect(() => {\n let cancelled = false;\n\n // Coalesce a refetch into a single in-flight run with one trailing re-run,\n // so a burst of events collapses to one request (+ one trailing) instead of\n // fanning out or being swallowed by a downstream per-key dedupe. The flag is\n // cleared on cleanup so nothing fires after the subscription is torn down.\n const makeCoalescedRefetch = (run: () => Promise<unknown>) => {\n let running = false;\n let queued = false;\n const trigger = () => {\n if (cancelled) return;\n if (running) {\n queued = true;\n return;\n }\n running = true;\n void run().finally(() => {\n running = false;\n if (!cancelled && queued) {\n queued = false;\n trigger();\n }\n });\n };\n return trigger;\n };\n\n const refreshProjects = makeCoalescedRefetch(() => fetchProjects());\n const refreshWorkspaces = makeCoalescedRefetch(() => {\n const orgId = useAuthStore.getState().currentOrganizationId;\n return orgId ? fetchWorkspacesForOrg(orgId) : Promise.resolve();\n });\n\n // Custom domain events (not in BurdenoffEventName) flow through `onAny`.\n const unsubscribe = eventBus.onAny((event) => {\n // Custom event names aren't in the BurdenoffEventName union; compare as string.\n const eventName: string = event.name;\n\n if (PROJECT_REFRESH_EVENTS.has(eventName)) {\n const eventWorkspaceId = readEventWorkspaceId(event.payload);\n const { currentWorkspaceId } = useAuthStore.getState();\n // Only refetch when the event targets the workspace currently in\n // context (events without a workspace id are treated as relevant).\n if (\n eventWorkspaceId &&\n currentWorkspaceId &&\n eventWorkspaceId !== currentWorkspaceId\n ) {\n return;\n }\n // Refetch only — a deleted project simply drops out of the list, and\n // `currentProject` resolves to undefined for it. Clearing the selection\n // here would race ActiveContext / the project sync effect (the real\n // source of truth), so we leave selection reconciliation to them.\n refreshProjects();\n return;\n }\n\n if (WORKSPACE_REFRESH_EVENTS.has(eventName)) {\n refreshWorkspaces();\n }\n });\n\n return () => {\n cancelled = true;\n unsubscribe();\n };\n }, [eventBus, fetchProjects, fetchWorkspacesForOrg]);\n\n // ===========================================================================\n // Get Current Items\n // ===========================================================================\n\n const currentOrganization = organizations.find(\n (org) => org.id === currentOrganizationId,\n );\n const currentWorkspace = workspaces.find(\n (ws) => ws.id === currentWorkspaceId,\n );\n const currentProject = projects.find((proj) => proj.id === currentProjectId);\n\n // ===========================================================================\n // Return Hook API\n // ===========================================================================\n\n return {\n organizations,\n workspaces,\n projects,\n\n currentOrganizationId,\n currentWorkspaceId,\n currentProjectId,\n\n currentOrganization,\n currentWorkspace,\n currentProject,\n\n workspaceToken,\n\n isLoadingOrganizations,\n isLoadingWorkspaces,\n isLoadingProjects,\n isLoading:\n isLoadingOrganizations || isLoadingWorkspaces || isLoadingProjects,\n\n error,\n\n fetchOrganizations,\n fetchWorkspacesForOrg,\n issueWorkspaceToken,\n fetchProjects,\n\n selectOrganization,\n selectWorkspace,\n selectProject,\n };\n}\n\n/**\n * Hook to reactively ensure workspaces are synced with the current organization.\n *\n * This handles edge cases where the organization changes but workspaces\n * from a different org are still in the store (e.g., stale data, race conditions).\n *\n * Usage:\n * ```tsx\n * import { useWorkspaceSyncEffect } from '@burdenoff/microfe-auth';\n *\n * function MyComponent() {\n * useWorkspaceSyncEffect(); // Ensures workspaces stay in sync\n * // ...\n * }\n * ```\n */\nexport function useWorkspaceSyncEffect(\n options?: UseContextSwitcherDataOptions,\n) {\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const workspaces = useAuthStore((state) => state.workspaces);\n const accessToken = useAuthStore((state) => state.accessToken);\n const isLoadingWorkspaces = useAuthStore(\n (state) => state.isLoadingWorkspaces,\n );\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const globalBaseUrl =\n options?.globalBaseUrl ?? resolvedBaseUrls.globalBaseUrl;\n const disableWorkspaceSync = options?.disableWorkspaceSync ?? false;\n\n useEffect(() => {\n if (disableWorkspaceSync) return;\n // Skip if no org selected, no token, or already loading\n if (!currentOrganizationId || !accessToken || isLoadingWorkspaces) return;\n\n // Check if any workspace matches the current org\n const hasMatchingWorkspaces = workspaces.some(\n (ws) => ws.organizationId === currentOrganizationId,\n );\n\n // If workspaces exist but none match current org, we need to refetch\n // This can happen in edge cases with stale data or race conditions\n if (workspaces.length > 0 && !hasMatchingWorkspaces) {\n const store = useAuthStore.getState();\n store.setLoadingWorkspaces(true);\n\n // Inline fetch to avoid circular dependency with useContextSwitcherData\n graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: accessToken,\n baseUrl: globalBaseUrl,\n })\n .then((result) => {\n // myWorkspaces returns ALL my workspaces; filter to current org\n // client-side (the old server-side filter no longer exists).\n if (result.data?.workspaces?.items) {\n result.data.workspaces.items = result.data.workspaces.items.filter(\n (w) => w.organizationId === currentOrganizationId,\n );\n }\n if (!result.errors?.length) {\n const allWs: Workspace[] = result.data?.workspaces?.items ?? [];\n // Same per-org narrowing as fetchWorkspacesForOrg — see the\n // comment there for why we don't just dump the full caller-\n // visible list into the store.\n const ws = allWs.filter(\n (w) => w.organizationId === currentOrganizationId,\n );\n store.setWorkspaces(ws);\n }\n })\n .catch(() => {\n // Silent fail - user can manually refresh or select org again\n })\n .finally(() => {\n store.setLoadingWorkspaces(false);\n });\n }\n }, [\n currentOrganizationId,\n workspaces,\n accessToken,\n isLoadingWorkspaces,\n globalBaseUrl,\n disableWorkspaceSync,\n ]);\n}\n\n/**\n * Hook to reactively ensure projects are loaded when a workspace is selected.\n *\n * This handles the case where a workspace is auto-selected (from URL/localStorage)\n * but projects haven't been fetched yet. It will:\n * 1. Issue a workspace token if not present\n * 2. Fetch projects for the selected workspace\n *\n * Usage:\n * ```tsx\n * import { useProjectSyncEffect } from '@burdenoff/microfe-auth';\n *\n * function MyComponent() {\n * useProjectSyncEffect(); // Ensures projects are loaded for selected workspace\n * // ...\n * }\n * ```\n */\nexport function useProjectSyncEffect(options?: UseContextSwitcherDataOptions) {\n const currentWorkspaceId = useAuthStore((state) => state.currentWorkspaceId);\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const workspaces = useAuthStore((state) => state.workspaces);\n const projects = useAuthStore((state) => state.projects);\n const currentProjectId = useAuthStore((state) => state.currentProjectId);\n const workspaceToken = useAuthStore((state) => state.workspaceToken);\n const accessToken = useAuthStore((state) => state.accessToken);\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const workspaceBaseUrl =\n options?.workspaceBaseUrl ?? resolvedBaseUrls.workspaceBaseUrl;\n const disableProjectSync = options?.disableProjectSync ?? false;\n const skipProjectFetch = options?.skipProjectFetch ?? false;\n\n // Use refs to prevent the infinite loop caused by including loading/failure\n // state in the dependency array. Without these, the cycle is:\n // setLoadingProjects(true) -> dep change -> effect re-runs (guarded) ->\n // async completes -> setLoadingProjects(false) -> dep change ->\n // effect re-runs -> starts again -> INFINITE LOOP\n const syncInProgressRef = useRef(false);\n // Pending retry timer per workspace, so transient failures (e.g. RBAC lag\n // right after workspace creation) get an automatic second chance even if no\n // dependency change re-triggers the effect.\n const retryTimerRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(\n new Map(),\n );\n // Per-workspace failure tracker — caps retry attempts when project bootstrap\n // (token issue, list, or default-create) fails. Without this, a persistent\n // backend failure (e.g. cross-layer workspace not yet synced) causes the\n // effect to re-fire every render: list returns empty → create-default fails\n // → setProjects([]) → new array reference → effect re-runs → loop.\n //\n // We track both count AND lastFailureAt so we can honour a \"cool-down\" window:\n // after PROJECT_SYNC_FAILURE_COOLDOWN_MS has elapsed since the last failure,\n // the counter is treated as cleared so transient backend hiccups (e.g. RBAC\n // role propagation lag right after signup) don't permanently lock a workspace\n // out of the context dropdown — the original cause of marqueue §729.\n const projectSyncFailuresRef = useRef<\n Map<string, { count: number; lastFailureAt: number }>\n >(new Map());\n const PROJECT_SYNC_MAX_FAILURES = 8;\n const PROJECT_SYNC_FAILURE_COOLDOWN_MS = 30_000;\n useEffect(() => {\n if (disableProjectSync) return;\n // Skip if no workspace selected or no access token\n if (!currentWorkspaceId || !accessToken) return;\n\n // Skip if a sync is already in progress (ref-based guard avoids dep loop)\n if (syncInProgressRef.current) return;\n\n // Stop retrying once this workspace has failed too many times in a row.\n // Counter is reset on success, on workspace switch (different key), by\n // an explicit user retry path (e.g. selectWorkspace), or after the\n // cool-down window has elapsed since the last failure (so transient\n // backend issues don't permanently wedge the dropdown).\n const failureEntry = projectSyncFailuresRef.current.get(currentWorkspaceId);\n if (\n failureEntry &&\n failureEntry.count >= PROJECT_SYNC_MAX_FAILURES &&\n Date.now() - failureEntry.lastFailureAt < PROJECT_SYNC_FAILURE_COOLDOWN_MS\n ) {\n return;\n }\n if (\n failureEntry &&\n Date.now() - failureEntry.lastFailureAt >=\n PROJECT_SYNC_FAILURE_COOLDOWN_MS\n ) {\n // Cool-down elapsed — clear the counter so we get a fresh budget.\n projectSyncFailuresRef.current.delete(currentWorkspaceId);\n }\n\n // Resolve organizationId: prefer the workspace object (if loaded), fall\n // back to the persisted currentOrganizationId. The workspaces array is\n // NOT persisted by zustand, so on page reload it is empty until\n // fetchOrganizations() completes. Using the persisted org ID lets us\n // issue the workspace token immediately instead of waiting.\n const currentWorkspace = workspaces.find(\n (ws) => ws.id === currentWorkspaceId,\n );\n\n // Guard: transient (newOrg, oldWs) divergence during org switches — token issuance always fails.\n if (\n currentWorkspace &&\n currentOrganizationId &&\n currentWorkspace.organizationId !== currentOrganizationId\n ) {\n return;\n }\n\n const organizationId =\n currentWorkspace?.organizationId ?? currentOrganizationId;\n if (!organizationId) return;\n\n const store = useAuthStore.getState();\n\n // If we don't have a workspace token or it's expired, issue one first\n const needsToken =\n !workspaceToken ||\n isTokenExpired(workspaceToken) ||\n !isWorkspaceTokenValidForContext(workspaceToken, {\n workspaceId: currentWorkspaceId,\n organizationId: currentOrganizationId,\n projectId: currentProjectId,\n });\n\n // Skip if projects are already loaded for this workspace AND token is valid\n const hasProjectsForWorkspace = projects.some(\n (p) => p.workspaceId === currentWorkspaceId,\n );\n if (hasProjectsForWorkspace && !needsToken) {\n if (!store.currentProjectId) {\n const firstProject = projects.find(\n (project) => project.workspaceId === currentWorkspaceId,\n );\n if (firstProject) {\n store.setCurrentProjectId(firstProject.id);\n }\n }\n return;\n }\n\n const syncProjects = async () => {\n syncInProgressRef.current = true;\n store.setLoadingProjects(true);\n let succeeded = false;\n\n try {\n let wsToken = workspaceToken;\n\n // Issue workspace token if needed\n if (needsToken) {\n const tokenResult = await graphqlFetch<{\n issueWorkspaceToken: IssueWorkspaceTokenResult;\n }>({\n gateway: \"workspace\",\n query: ISSUE_WORKSPACE_TOKEN_MUTATION,\n variables: {\n input: {\n organizationId,\n workspaceId: currentWorkspaceId,\n ...(currentProjectId ? { projectId: currentProjectId } : {}),\n },\n },\n authToken: accessToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (\n tokenResult.data?.issueWorkspaceToken?.success &&\n tokenResult.data.issueWorkspaceToken.token\n ) {\n wsToken = tokenResult.data.issueWorkspaceToken.token;\n store.setWorkspaceToken(wsToken);\n } else {\n return;\n }\n }\n\n // Fetch projects (skip if already loaded or token-only sync requested)\n if (wsToken && !hasProjectsForWorkspace && !skipProjectFetch) {\n const projectsResult = await graphqlFetch<ProjectsResponse>({\n gateway: \"workspace\",\n query: PROJECTS_QUERY,\n authToken: accessToken,\n workspaceToken: wsToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (projectsResult.errors?.length) {\n return;\n }\n\n let projs: Project[] = projectsResult.data?.projects?.items ?? [];\n if (projs.length === 0) {\n const defaultProject = await createDefaultProject({\n authToken: accessToken,\n workspaceBaseUrl,\n workspaceToken: wsToken,\n });\n if (defaultProject) {\n projs = [defaultProject];\n } else {\n // Default-project creation failed (e.g. workspace not yet\n // propagated to the workspace layer). Do NOT write [] back —\n // that would change the projects reference and re-trigger\n // this effect on the next render.\n return;\n }\n }\n\n store.setProjects(projs);\n\n // Auto-select first project if none selected and projects exist\n if (projs.length > 0 && !store.currentProjectId) {\n store.setCurrentProjectId(projs[0].id);\n }\n }\n\n succeeded = true;\n } catch {\n // A later auth/context update should be able to retry.\n } finally {\n store.setLoadingProjects(false);\n syncInProgressRef.current = false;\n const failures = projectSyncFailuresRef.current;\n if (succeeded) {\n failures.delete(currentWorkspaceId);\n const pending = retryTimerRef.current.get(currentWorkspaceId);\n if (pending) {\n clearTimeout(pending);\n retryTimerRef.current.delete(currentWorkspaceId);\n }\n } else {\n const existing = failures.get(currentWorkspaceId);\n const nextCount = (existing?.count ?? 0) + 1;\n failures.set(currentWorkspaceId, {\n count: nextCount,\n lastFailureAt: Date.now(),\n });\n // Schedule a backoff retry for transient backend lag (e.g. RBAC\n // role propagation right after signup → first projects() call hits\n // permission-denied). Without this, the effect would only re-run on\n // dep change and the user would be stuck staring at an empty\n // project dropdown until something else triggered a re-render.\n if (nextCount < PROJECT_SYNC_MAX_FAILURES) {\n const existingTimer = retryTimerRef.current.get(currentWorkspaceId);\n if (existingTimer) clearTimeout(existingTimer);\n const backoffMs = Math.min(1000 * 2 ** (nextCount - 1), 8000);\n const timer = setTimeout(() => {\n retryTimerRef.current.delete(currentWorkspaceId);\n // Only re-run if the workspace context is still the same and\n // a project hasn't been loaded for it in the meantime.\n const latest = useAuthStore.getState();\n if (\n latest.currentWorkspaceId === currentWorkspaceId &&\n !latest.projects.some(\n (p) => p.workspaceId === currentWorkspaceId,\n ) &&\n !syncInProgressRef.current\n ) {\n // Bump a render by clearing then resetting workspaceToken\n // when valid, OR by re-issuing projects fetch directly. The\n // simplest robust trigger is to clear the in-progress guard\n // and call syncProjects() again with current closure values.\n void syncProjects();\n }\n }, backoffMs);\n retryTimerRef.current.set(currentWorkspaceId, timer);\n }\n }\n }\n };\n\n syncProjects();\n }, [\n currentWorkspaceId,\n currentOrganizationId,\n workspaces,\n projects,\n currentProjectId,\n workspaceToken,\n accessToken,\n workspaceBaseUrl,\n disableProjectSync,\n skipProjectFetch,\n ]);\n\n // Cleanup any pending retry timers on unmount so we don't leak stray\n // setTimeout callbacks running against stale closures.\n useEffect(() => {\n const timers = retryTimerRef.current;\n return () => {\n timers.forEach((timer) => clearTimeout(timer));\n timers.clear();\n };\n }, []);\n}\n// hmr-bust-1778064429\n"],"mappings":";;;;;;;AAmFA,IAAM,IAAyB,2RAoCzB,IAA0B,oSAoB1B,IAAmC,kiBAoCnC,IAAiC,6SA0BjC,IAAiB,uPAkBjB,IAAkC;AAexC,eAAe,EAAqB,EAClC,cACA,qBACA,qBAK0B;CAC1B,IAAM,IAAS,MAAM,EAAoC;EACvD,SAAS;EACT,OAAO;EACP,WAAW,EACT,OAAO,EACL,MAAM,mBACP,EACF;EACD;EACA;EACA,SAAS;EACV,CAAC;AAOF,QALI,EAAO,QAAQ,UACjB,QAAQ,KAAK,qCAAqC,EAAO,OAAO,EACzD,QAGF,EAAO,MAAM,iBAAiB;;AAWvC,SAAS,EAAe,GAAe,IAAW,KAAiB;AACjE,KAAI;EACF,IA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AgB,EAAc,QAAQ,IAAI,EAAmB;AACnE,MAAI,KAAe,aAAa,EAAc;MAC9C,IAAM,IAAY,KAAK,IAAI,MAAO,MAAM,IAAY,IAAI,IAAK,EACvD,IAAQ,iBAAiB;AAC7B,SAAc,QAAQ,OAAO,EAAmB;OAGhD,IAAM,IAAS,EAAa,UAAU;AACtC,OACE,EAAO,uBAAuB,KAC9B,CAAC,EAAO,SAAS,MACd,MAAM,EAAE,gBAAgB,EAC1B,IACD,CAAC,EAAkB,WAMd,GAAc;SAEpB,EAAU;AACb,QAAc,QAAQ,IAAI,GAAoB,EAAM;;;;;AAM5D,KAAc;IACb;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,EAIF,QAAgB;EACd,IAAM,IAAS,EAAc;AAC7B,eAAa;AAEX,GADA,EAAO,SAAS,MAAU,aAAa,EAAM,CAAC,EAC9C,EAAO,OAAO;;IAEf,EAAE,CAAC"}
|
|
1
|
+
{"version":3,"file":"useContextSwitcherData.js","names":[],"sources":["../../../src/auth/hooks/useContextSwitcherData.ts"],"sourcesContent":["import { useCallback, useState, useEffect, useRef } from \"react\";\nimport {\n graphqlFetch,\n getStoredAuthToken,\n} from \"@burdenoff/fe-libs/shared/graphql\";\nimport { useActiveContext } from \"@burdenoff/fe-libs/shared/providers/shell/ActiveContextProvider\";\nimport { useEventBus } from \"@burdenoff/fe-libs/shared/events\";\nimport { useAuthStore } from \"../store/authStore\";\nimport type { Organization, Workspace, Project } from \"../types\";\nimport { resolveGatewayBaseUrls } from \"../utils/gatewayBaseUrls\";\n\n// =============================================================================\n// Hook Options\n// =============================================================================\n\nexport interface UseContextSwitcherDataOptions {\n /**\n * Optional Global API Gateway base URL override.\n * If not provided, uses GATEWAYS config from fe-libs.\n */\n globalBaseUrl?: string;\n /**\n * Optional Workspaces API Gateway base URL override.\n * If not provided, uses GATEWAYS config from fe-libs.\n */\n workspaceBaseUrl?: string;\n /** Disable initial organization/workspace bootstrap fetches */\n disableBootstrap?: boolean;\n /** Disable the workspace sync effect */\n disableWorkspaceSync?: boolean;\n /** Disable the project sync effect */\n disableProjectSync?: boolean;\n /** Only hydrate the workspace token; do not eagerly fetch projects */\n skipProjectFetch?: boolean;\n}\n\n// =============================================================================\n// GraphQL Response Types\n// =============================================================================\n\ninterface MyOrganizationsResponse {\n myOrganizations: {\n total: number;\n items: Organization[];\n };\n}\n\ninterface WorkspacesByOrgResponse {\n workspaces: {\n total: number;\n items: Workspace[];\n };\n}\n\ntype GraphQLFetchResult<T> = Awaited<ReturnType<typeof graphqlFetch<T>>>;\n\ninterface IssueWorkspaceTokenResult {\n success: boolean;\n token: string | null;\n expiresAt: string | null;\n organizationId: string | null;\n workspaceId: string | null;\n projectId: string | null;\n scopes: string[] | null;\n error: {\n code: string;\n message: string;\n } | null;\n}\n\ninterface ProjectsResponse {\n projects: {\n total: number;\n items: Project[];\n };\n}\n\ninterface CreateProjectResponse {\n createProject: Project;\n}\n\n// =============================================================================\n// GraphQL Query/Mutation Strings\n// =============================================================================\n\nconst MY_ORGANIZATIONS_QUERY = `\n query MyOrganizations {\n myOrganizations {\n total\n items {\n id\n name\n slug\n tenantId\n description\n logo\n website\n status\n type\n createdAt\n updatedAt\n }\n }\n }\n`;\n\n// Both queries below historically used `workspaces(filter: $filter)` with\n// a `WorkspaceFilterInput` to fetch workspaces for a specific organization.\n// That Query field was removed/renamed in the global subgraph; calling it\n// now throws GRAPHQL_VALIDATION_FAILED (\"Cannot query field 'workspaces'\n// on type 'Query'\") which crashes the context switcher and cascades into a\n// \"Verifying workspace access...\" stuck-spinner on every Platform module\n// route (/billing, /support, /notifications, /devportal).\n//\n// The supported field is `myWorkspaces(limit, offset)` on the global\n// subgraph — self-scoped, returns the caller's workspaces across all\n// orgs. It does NOT accept a filter, so we fetch up to 100 of \"my\"\n// workspaces and let the existing downstream auto-pick logic filter by\n// organizationId client-side. The recovery path at line ~624 already\n// uses this exact aliased pattern; we're just promoting it to the\n// primary path.\nconst WORKSPACES_BY_ORG_QUERY = `\n query WorkspacesByOrg {\n workspaces: myWorkspaces(limit: 100) {\n total\n items {\n id\n name\n slug\n tenantId\n organizationId\n type\n status\n region\n createdAt\n updatedAt\n }\n }\n }\n`;\n\nconst ISSUE_WORKSPACE_TOKEN_MUTATION = `\n mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {\n issueWorkspaceToken(input: $input) {\n success\n token\n expiresAt\n organizationId\n workspaceId\n projectId\n scopes\n error {\n code\n message\n }\n }\n }\n`;\n\n// The workspace gateway exposes `myProjects` (public RBAC, caller-scoped to\n// the active workspace via x-workspace-id) and the privileged\n// `projects(filter)` (list:project). The header has no `list:project`\n// permission seeded for the typical operator, so the privileged form\n// returns FORBIDDEN even though the caller is a member of the workspace.\n// `myProjects` is the right field for \"give me the projects I can see in\n// this workspace\" — workspace scope is already established by the\n// workspace token + x-workspace-id header that we pass with the request.\nconst PROJECTS_QUERY = `\n query MyProjectsForContext {\n projects: myProjects {\n total\n items {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n }\n`;\n\nconst CREATE_DEFAULT_PROJECT_MUTATION = `\n mutation CreateDefaultProject($input: CreateProjectInput!) {\n createProject(input: $input) {\n id\n name\n key\n workspaceId\n status\n archived\n createdAt\n updatedAt\n }\n }\n`;\n\nasync function createDefaultProject({\n authToken,\n workspaceBaseUrl,\n workspaceToken,\n}: {\n authToken: string;\n workspaceBaseUrl: string;\n workspaceToken: string;\n}): Promise<Project | null> {\n const result = await graphqlFetch<CreateProjectResponse>({\n gateway: \"workspace\",\n query: CREATE_DEFAULT_PROJECT_MUTATION,\n variables: {\n input: {\n name: \"Default Project\",\n },\n },\n authToken,\n workspaceToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (result.errors?.length) {\n console.warn(\"Failed to create default project:\", result.errors);\n return null;\n }\n\n return result.data?.createProject ?? null;\n}\n\n// =============================================================================\n// Auth Helpers\n// =============================================================================\n\n/**\n * Check whether a JWT is expired (or within bufferMs of expiry).\n * Returns true if the token is expired, close to expiry, or malformed.\n */\nfunction isTokenExpired(token: string, bufferMs = 30_000): boolean {\n try {\n const payload = JSON.parse(atob(token.split(\".\")[1]));\n if (!payload.exp) return false;\n return payload.exp * 1000 < Date.now() + bufferMs;\n } catch {\n return true;\n }\n}\n\nfunction getWorkspaceTokenPayload(token: string): {\n workspaceId?: string;\n organizationId?: string;\n projectId?: string;\n exp?: number;\n} | null {\n try {\n const payload = JSON.parse(atob(token.split(\".\")[1]));\n return {\n workspaceId:\n typeof payload.workspaceId === \"string\"\n ? payload.workspaceId\n : undefined,\n organizationId:\n typeof payload.organizationId === \"string\"\n ? payload.organizationId\n : undefined,\n projectId:\n typeof payload.projectId === \"string\" ? payload.projectId : undefined,\n exp: typeof payload.exp === \"number\" ? payload.exp : undefined,\n };\n } catch {\n return null;\n }\n}\n\nfunction isWorkspaceTokenValidForContext(\n token: string | null | undefined,\n expected: {\n workspaceId?: string | null;\n organizationId?: string | null;\n projectId?: string | null;\n },\n): token is string {\n if (!token || isTokenExpired(token)) {\n return false;\n }\n\n const payload = getWorkspaceTokenPayload(token);\n if (!payload) {\n return false;\n }\n\n if (expected.workspaceId && payload.workspaceId !== expected.workspaceId) {\n return false;\n }\n\n if (\n expected.organizationId &&\n payload.organizationId !== expected.organizationId\n ) {\n return false;\n }\n\n if (expected.projectId && payload.projectId !== expected.projectId) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Custom error class for auth-related failures (expired token, unauthorized, etc.).\n * Used to distinguish auth errors in outer catch blocks so they can be\n * suppressed from console.error — they are expected during token refresh cycles\n * and do not indicate application bugs.\n */\nclass AuthError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AuthError\";\n }\n}\n\n/**\n * Detect whether a set of GraphQL errors are authentication-related.\n */\nfunction isAuthGraphQLError(\n errors: Array<{ message?: string; extensions?: { code?: string } }>,\n): boolean {\n return errors.some(\n (e) =>\n e.extensions?.code === \"UNAUTHENTICATED\" ||\n e.message?.toLowerCase().includes(\"unauthorized\") ||\n e.message?.toLowerCase().includes(\"not authenticated\"),\n );\n}\n\n/**\n * Resolve the best available access token:\n * 1. Try the zustand store token\n * 2. If expired, fall back to profile storage (may have been refreshed)\n * 3. Return null if no valid token is available\n */\nfunction resolveAccessToken(): string | null {\n const storeToken = useAuthStore.getState().accessToken;\n\n // If store token is valid (or has no exp claim), use it\n if (storeToken && !isTokenExpired(storeToken)) {\n return storeToken;\n }\n\n // Store token is expired or missing — try profile storage (may be fresher)\n const profileToken = getStoredAuthToken();\n if (profileToken && !isTokenExpired(profileToken)) {\n return profileToken;\n }\n\n // Both expired or missing — if store token exists at all, return it as a last\n // resort (the gateway will reject it and the useEffect will re-trigger after\n // token refresh). Returning null would silently swallow the first load.\n return storeToken;\n}\n\nfunction buildFallbackOrganizations(workspaces: Workspace[]): Organization[] {\n const uniqueOrgIds = Array.from(\n new Set(\n workspaces.flatMap((workspace) =>\n workspace.organizationId ? [workspace.organizationId] : [],\n ),\n ),\n );\n\n return uniqueOrgIds.map((organizationId, index) => ({\n id: organizationId,\n name:\n workspaces.find(\n (workspace) => workspace.organizationId === organizationId,\n )?.name || `Organization ${index + 1}`,\n slug: organizationId,\n tenantId:\n workspaces.find(\n (workspace) => workspace.organizationId === organizationId,\n )?.tenantId || \"\",\n }));\n}\n\n// =============================================================================\n// Hook Implementation\n// =============================================================================\n\n/**\n * Hook for managing the context switcher data (organizations, workspaces, projects)\n *\n * Data flow:\n * 1. fetchOrganizations() - Get all orgs user has access to (Global Gateway)\n * 2. selectOrganization(org) - Set current org & fetch workspaces for that org\n * 3. selectWorkspace(ws) - Issue workspace token & fetch projects\n * 4. selectProject(proj) - Set current project\n *\n * All GraphQL calls go through graphqlFetch from fe-libs which automatically\n * resolves gateway URLs and injects auth + locale headers.\n *\n * @param options - Optional configuration (gateway base URL overrides)\n */\n// Domain events emitted by microfe-workspaces that should refresh the switcher's\n// cached lists. Module-scoped so they aren't reallocated on every effect run.\nconst PROJECT_REFRESH_EVENTS = new Set<string>([\n \"project.created\",\n \"project.updated\",\n \"project.deleted\",\n \"project.archived\",\n \"project.unarchived\",\n]);\nconst WORKSPACE_REFRESH_EVENTS = new Set<string>([\n \"workspace.created\",\n \"workspace.updated\",\n \"workspace.deleted\",\n \"workspace.archived\",\n \"workspace.reactivated\",\n]);\n\n// Safely read a string `workspaceId` off a cross-MFE event payload of unknown\n// shape, rather than trusting a bare cast (the payload is produced by another\n// MFE and could drift). Returns undefined when absent or not a string.\nfunction readEventWorkspaceId(payload: unknown): string | undefined {\n if (payload && typeof payload === \"object\" && \"workspaceId\" in payload) {\n const value = (payload as { workspaceId?: unknown }).workspaceId;\n return typeof value === \"string\" ? value : undefined;\n }\n return undefined;\n}\n\nexport function useContextSwitcherData(\n options?: UseContextSwitcherDataOptions,\n) {\n const {\n organizationId: activeOrganizationId,\n workspaceId: activeWorkspaceId,\n projectId: activeProjectId,\n setContext: setActiveContext,\n } = useActiveContext();\n\n const eventBus = useEventBus();\n\n // Use selectors for reactive state\n const organizations = useAuthStore((state) => state.organizations);\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const isLoadingOrganizations = useAuthStore(\n (state) => state.isLoadingOrganizations,\n );\n\n const workspaces = useAuthStore((state) => state.workspaces);\n const currentWorkspaceId = useAuthStore((state) => state.currentWorkspaceId);\n const workspaceToken = useAuthStore((state) => state.workspaceToken);\n const isLoadingWorkspaces = useAuthStore(\n (state) => state.isLoadingWorkspaces,\n );\n\n const projects = useAuthStore((state) => state.projects);\n const currentProjectId = useAuthStore((state) => state.currentProjectId);\n const isLoadingProjects = useAuthStore((state) => state.isLoadingProjects);\n\n // Local error state\n const [error, setError] = useState<string | null>(null);\n\n // Deduplication refs to prevent duplicate GraphQL calls\n const fetchOrganizationsPromiseRef = useRef<Promise<Organization[]> | null>(\n null,\n );\n const fetchWorkspacesPromisesRef = useRef<Map<string, Promise<Workspace[]>>>(\n new Map(),\n );\n\n // Stable refs for latest context values — avoids stale closures in callbacks\n // without adding them to useCallback dep arrays (which would recreate callbacks\n // on every context change and trigger spurious fetch re-runs).\n const activeWorkspaceIdRef = useRef(activeWorkspaceId);\n const activeOrganizationIdRef = useRef(activeOrganizationId);\n useEffect(() => {\n activeWorkspaceIdRef.current = activeWorkspaceId;\n activeOrganizationIdRef.current = activeOrganizationId;\n });\n\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const globalBaseUrl =\n options?.globalBaseUrl ?? resolvedBaseUrls.globalBaseUrl;\n const workspaceBaseUrl =\n options?.workspaceBaseUrl ?? resolvedBaseUrls.workspaceBaseUrl;\n\n // Refs to break feedback loops with the Header's \"store → URL\" sync effect.\n // Without these the pair can ping-pong: this effect writes (URL → store),\n // Header writes (store → URL), Zustand re-fires our subscribers, and React\n // hits \"Maximum update depth exceeded\" — especially when a downstream call\n // (workspace token issuance) returns 504 and leaves the two halves in\n // disagreement. The refs record the last value we pushed for each axis;\n // identical pushes are skipped so the loop has a hard floor.\n const lastAppliedOrgIdRef = useRef<string | null>(null);\n const lastAppliedWorkspaceIdRef = useRef<string | null>(null);\n const lastAppliedProjectIdRef = useRef<string | null>(null);\n const lastClearedTokenContextRef = useRef<string | null>(null);\n\n useEffect(() => {\n const store = useAuthStore.getState();\n\n if (\n activeOrganizationId &&\n activeOrganizationId !== store.currentOrganizationId &&\n activeOrganizationId !== lastAppliedOrgIdRef.current\n ) {\n lastAppliedOrgIdRef.current = activeOrganizationId;\n store.setCurrentOrganizationId(activeOrganizationId);\n if (\n store.workspaces.length > 0 &&\n !store.workspaces.some(\n (workspace) => workspace.organizationId === activeOrganizationId,\n )\n ) {\n store.setWorkspaces([]);\n }\n }\n\n if (\n activeWorkspaceId &&\n activeWorkspaceId !== store.currentWorkspaceId &&\n activeWorkspaceId !== lastAppliedWorkspaceIdRef.current\n ) {\n lastAppliedWorkspaceIdRef.current = activeWorkspaceId;\n store.setCurrentWorkspaceId(activeWorkspaceId);\n if (\n store.projects.length > 0 &&\n !store.projects.some(\n (project) => project.workspaceId === activeWorkspaceId,\n )\n ) {\n store.setProjects([]);\n store.setCurrentProjectId(null);\n }\n }\n\n if (\n activeProjectId &&\n activeProjectId !== store.currentProjectId &&\n activeProjectId !== lastAppliedProjectIdRef.current\n ) {\n lastAppliedProjectIdRef.current = activeProjectId;\n store.setCurrentProjectId(activeProjectId);\n }\n\n if (\n store.workspaceToken &&\n !isWorkspaceTokenValidForContext(store.workspaceToken, {\n workspaceId: activeWorkspaceId,\n organizationId: activeOrganizationId,\n projectId: activeProjectId,\n })\n ) {\n // Clear-token-once-per-context guard: when the upstream gateway is\n // flaky (504s during workspace token issuance) the surrounding state\n // machine can oscillate between \"got token but invalid\" and \"clearing\n // token\". The downstream re-issue path then loops. Only clear once per\n // (org, ws, proj) tuple — a successful re-issue resets the ref via\n // setWorkspaceToken landing a new token for the same context.\n const ctxKey = `${activeOrganizationId ?? \"\"}|${activeWorkspaceId ?? \"\"}|${activeProjectId ?? \"\"}`;\n if (lastClearedTokenContextRef.current !== ctxKey) {\n lastClearedTokenContextRef.current = ctxKey;\n store.setWorkspaceToken(null);\n }\n }\n }, [activeOrganizationId, activeWorkspaceId, activeProjectId]);\n\n // ===========================================================================\n // Fetch Organizations (Global Gateway)\n // ===========================================================================\n\n const fetchOrganizations = useCallback(async (): Promise<Organization[]> => {\n // Deduplicate: if a fetch is already in progress, return the same promise\n if (fetchOrganizationsPromiseRef.current) {\n return fetchOrganizationsPromiseRef.current;\n }\n\n const store = useAuthStore.getState();\n const token = resolveAccessToken();\n\n if (!token) {\n // Not an error — user may not be authenticated yet (e.g., page load before login).\n // The useEffect in Header.tsx will re-trigger when accessToken becomes available.\n return [];\n }\n\n // If the token is clearly expired and no fresh fallback was found, skip the\n // doomed request. The useEffect in Header.tsx re-triggers when the auth\n // provider refreshes the token and updates accessToken in the store.\n if (isTokenExpired(token)) {\n return [];\n }\n\n store.setLoadingOrganizations(true);\n setError(null);\n\n // Store the promise for deduplication before starting\n fetchOrganizationsPromiseRef.current = (async () => {\n try {\n const initialTargetOrgId =\n activeOrganizationIdRef.current ?? store.currentOrganizationId;\n let result: GraphQLFetchResult<\n MyOrganizationsResponse & Partial<WorkspacesByOrgResponse>\n > = initialTargetOrgId\n ? await (async () => {\n const [organizationsResult, workspacesResult] = await Promise.all(\n [\n graphqlFetch<MyOrganizationsResponse>({\n gateway: \"global\",\n query: MY_ORGANIZATIONS_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n }),\n graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n }),\n ],\n );\n\n const data = organizationsResult.data?.myOrganizations\n ? {\n myOrganizations: organizationsResult.data.myOrganizations,\n ...(workspacesResult.data?.workspaces\n ? { workspaces: workspacesResult.data.workspaces }\n : {}),\n }\n : null;\n\n return {\n data,\n errors: [\n ...(organizationsResult.errors ?? []),\n ...(workspacesResult.errors ?? []),\n ],\n };\n })()\n : await graphqlFetch<MyOrganizationsResponse>({\n gateway: \"global\",\n query: MY_ORGANIZATIONS_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n\n // Self-heal stale-URL case: if the workspace side of the bootstrap\n // fails because the URL points at an inaccessible org/workspace, retry\n // with the organization-only query so the operator sees their actual\n // orgs and the URL params get corrected on next render.\n if (\n initialTargetOrgId &&\n result.errors?.length &&\n result.errors.some(\n (e) =>\n e?.extensions?.code === \"FORBIDDEN\" ||\n /not a member of this organization/i.test(e?.message ?? \"\") ||\n // Public gateway often drops the underlying FORBIDDEN error\n // and replaces it with the schema-level non-null violation\n // (\"Cannot return null for non-nullable field Query.myOrganizations\").\n // That happens when ANY field in the query throws — workspaces\n // here — and data:null cascades up. Treat that pattern as a\n // signal to retry without the workspaces filter.\n /Cannot return null for non-nullable field Query\\.myOrganizations/i.test(\n e?.message ?? \"\",\n ),\n )\n ) {\n // Fetch myOrganizations + ALL workspaces (no filter) so the\n // downstream auto-pick logic still has a workspace list to seed\n // context from. If we only refetched myOrganizations, the page\n // would render but every workspace-scoped query would fail with\n // \"Select a workspace…\".\n result = await graphqlFetch<\n MyOrganizationsResponse & Partial<WorkspacesByOrgResponse>\n >({\n gateway: \"global\",\n query: `\n query ContextSwitcherRecover {\n myOrganizations {\n total\n items { id name slug tenantId description logo website status type createdAt updatedAt }\n }\n workspaces: myWorkspaces {\n total\n items { id name slug tenantId organizationId type status region createdAt updatedAt }\n }\n }\n `,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n }\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n // Auth errors are expected during token refresh cycles — throw AuthError\n // so the outer catch can suppress console.error.\n throw new AuthError(errorMessage);\n }\n if (store.workspaces.length === 0) {\n console.error(\"Failed to fetch organizations:\", result.errors);\n }\n throw new Error(errorMessage);\n }\n\n let orgs: Organization[] = result.data?.myOrganizations?.items ?? [];\n\n // Stale-context recovery: bootstrap query was filtered by\n // initialTargetOrgId, so when the URL/persisted org doesn't belong to\n // this user the response is empty. Re-fetch the unfiltered list of\n // *all* orgs the user can access so the guard below can pick a real\n // default. Skip the recovery when no target was set (already\n // unfiltered) or when workspaces are already in the store (the\n // existing fallback path covers that case).\n if (\n initialTargetOrgId &&\n orgs.length === 0 &&\n store.workspaces.length === 0\n ) {\n const recovery = await graphqlFetch<MyOrganizationsResponse>({\n gateway: \"global\",\n query: MY_ORGANIZATIONS_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n if (!recovery.errors?.length) {\n orgs = recovery.data?.myOrganizations?.items ?? [];\n // discard the filtered workspaces payload — it was for the\n // ghost org and would only mislead the workspace selector below.\n result = {\n ...recovery,\n data: {\n myOrganizations: recovery.data?.myOrganizations ?? {\n items: [],\n total: 0,\n },\n },\n };\n } else {\n // Surface the failure so a user reporting \"blank org list\" has\n // something to grep for in the console. We still fall through —\n // the guard below either picks from a fallback (workspaces in\n // store) or no-ops, leaving the existing error path in place.\n console.warn(\n \"[ContextSwitcher] Stale-context recovery failed:\",\n recovery.errors,\n );\n }\n }\n\n const fallbackOrganizations =\n orgs.length === 0 && store.workspaces.length > 0\n ? buildFallbackOrganizations(store.workspaces)\n : [];\n const effectiveOrganizations =\n fallbackOrganizations.length > 0 ? fallbackOrganizations : orgs;\n\n store.setOrganizations(effectiveOrganizations);\n\n // Determine which organization to use for workspace fetching\n let targetOrgId = initialTargetOrgId;\n\n // Stale-context guard: if the persisted/URL org isn't in the user's\n // accessible orgs, fall back to the first available one and clear the\n // stale workspace/project so they get re-derived. Without this, URL\n // params like ?org=<ghost-id> from a prior session leak into the new\n // user's request headers and cause \"Authentication required\" /\n // \"not a member\" errors at every subgraph.\n //\n // Check against `orgs` (freshly returned from the API in this same\n // closure) rather than `effectiveOrganizations`, which can fall back\n // to ids derived from `store.workspaces` — that fallback path could\n // contain stale ghost orgIds and mask the guard.\n const targetOrgIsAccessible =\n targetOrgId && orgs.some((org) => org.id === targetOrgId);\n if (targetOrgId && !targetOrgIsAccessible && orgs.length > 0) {\n targetOrgId = orgs[0].id;\n setActiveContext({\n organizationId: targetOrgId,\n workspaceId: null,\n tenantId: null,\n projectId: null,\n });\n store.setWorkspaces([]);\n store.setProjects([]);\n store.setCurrentWorkspaceId(null);\n store.setCurrentProjectId(null);\n store.setWorkspaceToken(null);\n }\n\n if (targetOrgId && targetOrgId !== store.currentOrganizationId) {\n store.setCurrentOrganizationId(targetOrgId);\n }\n\n // Auto-select first organization if none is selected\n if (effectiveOrganizations.length > 0 && !targetOrgId) {\n store.setCurrentOrganizationId(effectiveOrganizations[0].id);\n targetOrgId = effectiveOrganizations[0].id;\n }\n\n // Fetch workspaces for the selected/auto-selected org if:\n // 1. We have a target org (either auto-selected or persisted from localStorage)\n // 2. AND workspaces array is empty (not persisted, or cleared)\n // This handles both initial login AND page refresh scenarios.\n // Read from useAuthStore.getState() rather than the captured `store`\n // snapshot so we see the post-guard cleared value when the org guard\n // above fired (the local `store.workspaces` ref is stale after\n // setWorkspaces([])).\n if (targetOrgId && useAuthStore.getState().workspaces.length === 0) {\n store.setLoadingWorkspaces(true);\n try {\n // myWorkspaces returns ALL workspaces the user is a member of\n // across every org. Filter to the target org client-side here.\n const bootstrappedWorkspaces =\n initialTargetOrgId === targetOrgId\n ? result.data?.workspaces?.items?.filter(\n (w) => w.organizationId === targetOrgId,\n )\n : undefined;\n const ws = bootstrappedWorkspaces\n ? (bootstrappedWorkspaces as Workspace[])\n : await graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n }).then((wsResult) =>\n wsResult.errors?.length\n ? null\n : (wsResult.data?.workspaces?.items ?? []).filter(\n (w) => w.organizationId === targetOrgId,\n ),\n );\n\n if (ws) {\n store.setWorkspaces(ws);\n const persistedWorkspace = activeWorkspaceIdRef.current\n ? ws.find(\n (workspace) =>\n workspace.id === activeWorkspaceIdRef.current,\n )\n : null;\n\n if (persistedWorkspace) {\n store.setCurrentWorkspaceId(persistedWorkspace.id);\n } else if (ws.length > 0) {\n const nextActiveContext = {\n organizationId: targetOrgId,\n workspaceId: ws[0].id,\n tenantId: ws[0].tenantId,\n projectId: null,\n };\n\n if (activeWorkspaceIdRef.current) {\n // Stale-context guard: URL/persisted workspace ID is not in\n // the user's accessible workspaces for the active org. Fall\n // back to the first workspace and clear the stale URL param\n // so subsequent requests don't carry the ghost ID.\n store.setCurrentWorkspaceId(ws[0].id);\n store.setWorkspaceToken(null);\n setActiveContext(nextActiveContext);\n } else if (!store.currentWorkspaceId) {\n // Auto-select first workspace only if none is currently selected\n // (preserves selection from completeAuthFlow or persistence if applicable)\n store.setCurrentWorkspaceId(ws[0].id);\n setActiveContext(nextActiveContext);\n }\n }\n }\n } catch {\n // Non-critical — user can still select workspace manually\n } finally {\n store.setLoadingWorkspaces(false);\n }\n }\n\n return effectiveOrganizations;\n } catch (err) {\n // Auth errors are expected during token refresh / page load cycles.\n // Suppress from console.error — the useEffect will re-trigger when the\n // auth provider refreshes the token.\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch organizations\";\n if (store.workspaces.length === 0) {\n console.error(\"Failed to fetch organizations:\", err);\n }\n setError(message);\n\n if (store.workspaces.length > 0) {\n const fallbackOrganizations = buildFallbackOrganizations(\n store.workspaces,\n );\n if (fallbackOrganizations.length > 0) {\n store.setOrganizations(fallbackOrganizations);\n if (!store.currentOrganizationId) {\n store.setCurrentOrganizationId(fallbackOrganizations[0].id);\n }\n return fallbackOrganizations;\n }\n }\n\n return [];\n } finally {\n store.setLoadingOrganizations(false);\n fetchOrganizationsPromiseRef.current = null;\n }\n })();\n\n return fetchOrganizationsPromiseRef.current;\n }, [globalBaseUrl, setActiveContext]);\n\n // ===========================================================================\n // Fetch Workspaces for Organization (Global Gateway)\n // ===========================================================================\n\n const fetchWorkspacesForOrg = useCallback(\n async (organizationId: string): Promise<Workspace[]> => {\n // Deduplicate: if a fetch for this org is already in progress, return the same promise\n const existingPromise =\n fetchWorkspacesPromisesRef.current.get(organizationId);\n if (existingPromise) {\n return existingPromise;\n }\n\n const store = useAuthStore.getState();\n const token = resolveAccessToken();\n\n if (!token || isTokenExpired(token)) {\n return [];\n }\n\n store.setLoadingWorkspaces(true);\n setError(null);\n\n // Store the promise for deduplication before starting\n const fetchPromise = (async () => {\n try {\n const result = await graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: token,\n baseUrl: globalBaseUrl,\n });\n // myWorkspaces returns workspaces across all the user's orgs;\n // filter to the requested org before handing to downstream.\n if (result.data?.workspaces?.items) {\n result.data.workspaces.items = result.data.workspaces.items.filter(\n (w) => w.organizationId === organizationId,\n );\n }\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n throw new AuthError(errorMessage);\n }\n console.error(\"Failed to fetch workspaces:\", result.errors);\n throw new Error(errorMessage);\n }\n\n // `myWorkspaces` returns every workspace the caller can see across\n // all of their orgs/tenants. The store key is per-org (selecting\n // org X then opening the dropdown should only show X's workspaces),\n // so we filter down to the requested org here. The dropdown filter\n // in ContextSwitcher.tsx is a defence-in-depth — without this\n // narrowing the store would briefly hold the caller's other-org\n // workspaces and the auto-pick logic (lines below) might select\n // one of them as the default.\n const allWs: Workspace[] = result.data?.workspaces?.items ?? [];\n const ws = allWs.filter((w) => w.organizationId === organizationId);\n store.setWorkspaces(ws);\n return ws;\n } catch (err) {\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch workspaces\";\n console.error(\"Failed to fetch workspaces:\", err);\n setError(message);\n return [];\n } finally {\n store.setLoadingWorkspaces(false);\n fetchWorkspacesPromisesRef.current.delete(organizationId);\n }\n })();\n\n fetchWorkspacesPromisesRef.current.set(organizationId, fetchPromise);\n return fetchPromise;\n },\n [globalBaseUrl],\n );\n\n // ===========================================================================\n // Issue Workspace Token (Workspace Gateway - wspace-auth-svc)\n // ===========================================================================\n\n const issueWorkspaceToken = useCallback(\n async (\n organizationId: string,\n workspaceId?: string,\n projectId?: string | null,\n // Target workspace's tenant. Sent as x-tenant-id so the token service can\n // resolve the tenant for a super_admin switching into a workspace not\n // mirrored into the wspace layer (whose access token carries no tenant\n // claim). Regular members resolve their tenant via membership regardless.\n tenantId?: string,\n ): Promise<{\n success: boolean;\n token?: string;\n resolvedWorkspaceId?: string;\n error?: string;\n }> => {\n const store = useAuthStore.getState();\n const authToken = resolveAccessToken();\n\n if (!authToken || isTokenExpired(authToken)) {\n return { success: false, error: \"No valid access token available\" };\n }\n\n setError(null);\n\n try {\n const result = await graphqlFetch<{\n issueWorkspaceToken: IssueWorkspaceTokenResult;\n }>({\n gateway: \"workspace\",\n query: ISSUE_WORKSPACE_TOKEN_MUTATION,\n variables: {\n input: {\n organizationId,\n ...(workspaceId && { workspaceId }),\n ...(projectId && { projectId }),\n },\n },\n authToken,\n baseUrl: workspaceBaseUrl,\n tenantId,\n });\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (!isAuthGraphQLError(result.errors)) {\n console.error(\"Failed to issue workspace token:\", result.errors);\n }\n return { success: false, error: errorMessage };\n }\n\n const tokenResult = result.data?.issueWorkspaceToken;\n\n if (tokenResult?.success && tokenResult.token) {\n const resolvedWsId = tokenResult.workspaceId || workspaceId;\n if (resolvedWsId) {\n store.setCurrentWorkspaceId(resolvedWsId);\n }\n store.setWorkspaceToken(tokenResult.token);\n return {\n success: true,\n token: tokenResult.token,\n resolvedWorkspaceId: resolvedWsId || undefined,\n };\n }\n\n return {\n success: false,\n error:\n tokenResult?.error?.message ?? \"Failed to issue workspace token\",\n };\n } catch (err) {\n const message =\n err instanceof Error\n ? err.message\n : \"Failed to issue workspace token\";\n console.error(\"Failed to issue workspace token:\", err);\n setError(message);\n return { success: false, error: message };\n }\n },\n [workspaceBaseUrl],\n );\n\n // ===========================================================================\n // Fetch Projects (Workspace Gateway - requires workspace token)\n // ===========================================================================\n\n const fetchProjects = useCallback(async (): Promise<Project[]> => {\n const store = useAuthStore.getState();\n const authToken = resolveAccessToken();\n const wsToken = store.workspaceToken;\n const workspaceId = store.currentWorkspaceId;\n\n if (!authToken || isTokenExpired(authToken)) {\n return [];\n }\n\n if (!wsToken) {\n return [];\n }\n\n if (!workspaceId) {\n return [];\n }\n\n store.setLoadingProjects(true);\n setError(null);\n\n try {\n const result = await graphqlFetch<ProjectsResponse>({\n gateway: \"workspace\",\n query: PROJECTS_QUERY,\n authToken,\n workspaceToken: wsToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (result.errors?.length) {\n const errorMessage = result.errors[0]?.message ?? \"GraphQL error\";\n if (isAuthGraphQLError(result.errors)) {\n throw new AuthError(errorMessage);\n }\n console.error(\"Failed to fetch projects:\", result.errors);\n throw new Error(errorMessage);\n }\n\n const projs: Project[] = result.data?.projects?.items ?? [];\n store.setProjects(projs);\n return projs;\n } catch (err) {\n if (err instanceof AuthError) {\n return [];\n }\n const message =\n err instanceof Error ? err.message : \"Failed to fetch projects\";\n console.error(\"Failed to fetch projects:\", err);\n setError(message);\n return [];\n } finally {\n store.setLoadingProjects(false);\n }\n }, [workspaceBaseUrl]);\n\n // ===========================================================================\n // High-Level Selection Actions\n // ===========================================================================\n\n const selectOrganization = useCallback(\n async (org: Organization): Promise<Workspace[]> => {\n const store = useAuthStore.getState();\n\n store.setCurrentWorkspaceId(null);\n store.setWorkspaceToken(null);\n store.setProjects([]);\n store.setCurrentProjectId(null);\n store.setCurrentOrganizationId(org.id);\n\n const ws = await fetchWorkspacesForOrg(org.id);\n return ws;\n },\n [fetchWorkspacesForOrg],\n );\n\n const selectWorkspace = useCallback(\n async (\n workspace: Workspace,\n ): Promise<{\n success: boolean;\n projects?: Project[];\n error?: string;\n }> => {\n const store = useAuthStore.getState();\n\n store.setCurrentProjectId(null);\n store.setProjects([]);\n\n if (!workspace.organizationId) {\n console.error(\"Workspace missing organizationId:\", workspace);\n return {\n success: false,\n error: \"Workspace is missing organizationId\",\n };\n }\n\n const tokenResult = await issueWorkspaceToken(\n workspace.organizationId,\n workspace.id,\n undefined,\n workspace.tenantId,\n );\n\n if (!tokenResult.success) {\n return { success: false, error: tokenResult.error };\n }\n\n let projs = await fetchProjects();\n if (projs.length === 0) {\n const authToken = resolveAccessToken();\n const workspaceToken = useAuthStore.getState().workspaceToken;\n if (authToken && workspaceToken) {\n const defaultProject = await createDefaultProject({\n authToken,\n workspaceBaseUrl,\n workspaceToken,\n });\n if (defaultProject) {\n projs = [defaultProject];\n store.setProjects(projs);\n }\n }\n }\n\n if (projs.length > 0) {\n store.setCurrentProjectId(projs[0]!.id);\n }\n\n return { success: true, projects: projs };\n },\n [issueWorkspaceToken, fetchProjects, workspaceBaseUrl],\n );\n\n const selectProject = useCallback((project: Project): void => {\n const store = useAuthStore.getState();\n store.setCurrentProjectId(project.id);\n if (\n store.workspaceToken &&\n !isWorkspaceTokenValidForContext(store.workspaceToken, {\n workspaceId: store.currentWorkspaceId,\n organizationId: store.currentOrganizationId,\n projectId: project.id,\n })\n ) {\n store.setWorkspaceToken(null);\n }\n }, []);\n\n // ===========================================================================\n // Cross-MFE refresh: keep the switcher lists current when another MFE mutates\n // org/workspace/project entities. microfe-workspaces emits these domain events\n // on the shared event bus (e.g. on project rename); without this the switcher\n // keeps showing the stale cached name until a full page reload.\n // ===========================================================================\n\n useEffect(() => {\n let cancelled = false;\n\n // Coalesce a refetch into a single in-flight run with one trailing re-run,\n // so a burst of events collapses to one request (+ one trailing) instead of\n // fanning out or being swallowed by a downstream per-key dedupe. The flag is\n // cleared on cleanup so nothing fires after the subscription is torn down.\n const makeCoalescedRefetch = (run: () => Promise<unknown>) => {\n let running = false;\n let queued = false;\n const trigger = () => {\n if (cancelled) return;\n if (running) {\n queued = true;\n return;\n }\n running = true;\n void run().finally(() => {\n running = false;\n if (!cancelled && queued) {\n queued = false;\n trigger();\n }\n });\n };\n return trigger;\n };\n\n const refreshProjects = makeCoalescedRefetch(() => fetchProjects());\n const refreshWorkspaces = makeCoalescedRefetch(() => {\n const orgId = useAuthStore.getState().currentOrganizationId;\n return orgId ? fetchWorkspacesForOrg(orgId) : Promise.resolve();\n });\n\n // Custom domain events (not in BurdenoffEventName) flow through `onAny`.\n const unsubscribe = eventBus.onAny((event) => {\n // Custom event names aren't in the BurdenoffEventName union; compare as string.\n const eventName: string = event.name;\n\n if (PROJECT_REFRESH_EVENTS.has(eventName)) {\n const eventWorkspaceId = readEventWorkspaceId(event.payload);\n const { currentWorkspaceId } = useAuthStore.getState();\n // Only refetch when the event targets the workspace currently in\n // context (events without a workspace id are treated as relevant).\n if (\n eventWorkspaceId &&\n currentWorkspaceId &&\n eventWorkspaceId !== currentWorkspaceId\n ) {\n return;\n }\n // Refetch only — a deleted project simply drops out of the list, and\n // `currentProject` resolves to undefined for it. Clearing the selection\n // here would race ActiveContext / the project sync effect (the real\n // source of truth), so we leave selection reconciliation to them.\n refreshProjects();\n return;\n }\n\n if (WORKSPACE_REFRESH_EVENTS.has(eventName)) {\n refreshWorkspaces();\n }\n });\n\n return () => {\n cancelled = true;\n unsubscribe();\n };\n }, [eventBus, fetchProjects, fetchWorkspacesForOrg]);\n\n // ===========================================================================\n // Get Current Items\n // ===========================================================================\n\n const currentOrganization = organizations.find(\n (org) => org.id === currentOrganizationId,\n );\n const currentWorkspace = workspaces.find(\n (ws) => ws.id === currentWorkspaceId,\n );\n const currentProject = projects.find((proj) => proj.id === currentProjectId);\n\n // ===========================================================================\n // Return Hook API\n // ===========================================================================\n\n return {\n organizations,\n workspaces,\n projects,\n\n currentOrganizationId,\n currentWorkspaceId,\n currentProjectId,\n\n currentOrganization,\n currentWorkspace,\n currentProject,\n\n workspaceToken,\n\n isLoadingOrganizations,\n isLoadingWorkspaces,\n isLoadingProjects,\n isLoading:\n isLoadingOrganizations || isLoadingWorkspaces || isLoadingProjects,\n\n error,\n\n fetchOrganizations,\n fetchWorkspacesForOrg,\n issueWorkspaceToken,\n fetchProjects,\n\n selectOrganization,\n selectWorkspace,\n selectProject,\n };\n}\n\n/**\n * Hook to reactively ensure workspaces are synced with the current organization.\n *\n * This handles edge cases where the organization changes but workspaces\n * from a different org are still in the store (e.g., stale data, race conditions).\n *\n * Usage:\n * ```tsx\n * import { useWorkspaceSyncEffect } from '@burdenoff/microfe-auth';\n *\n * function MyComponent() {\n * useWorkspaceSyncEffect(); // Ensures workspaces stay in sync\n * // ...\n * }\n * ```\n */\nexport function useWorkspaceSyncEffect(\n options?: UseContextSwitcherDataOptions,\n) {\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const workspaces = useAuthStore((state) => state.workspaces);\n const accessToken = useAuthStore((state) => state.accessToken);\n const isLoadingWorkspaces = useAuthStore(\n (state) => state.isLoadingWorkspaces,\n );\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const globalBaseUrl =\n options?.globalBaseUrl ?? resolvedBaseUrls.globalBaseUrl;\n const disableWorkspaceSync = options?.disableWorkspaceSync ?? false;\n\n useEffect(() => {\n if (disableWorkspaceSync) return;\n // Skip if no org selected, no token, or already loading\n if (!currentOrganizationId || !accessToken || isLoadingWorkspaces) return;\n\n // Check if any workspace matches the current org\n const hasMatchingWorkspaces = workspaces.some(\n (ws) => ws.organizationId === currentOrganizationId,\n );\n\n // If workspaces exist but none match current org, we need to refetch\n // This can happen in edge cases with stale data or race conditions\n if (workspaces.length > 0 && !hasMatchingWorkspaces) {\n const store = useAuthStore.getState();\n store.setLoadingWorkspaces(true);\n\n // Inline fetch to avoid circular dependency with useContextSwitcherData\n graphqlFetch<WorkspacesByOrgResponse>({\n gateway: \"global\",\n query: WORKSPACES_BY_ORG_QUERY,\n authToken: accessToken,\n baseUrl: globalBaseUrl,\n })\n .then((result) => {\n // myWorkspaces returns ALL my workspaces; filter to current org\n // client-side (the old server-side filter no longer exists).\n if (result.data?.workspaces?.items) {\n result.data.workspaces.items = result.data.workspaces.items.filter(\n (w) => w.organizationId === currentOrganizationId,\n );\n }\n if (!result.errors?.length) {\n const allWs: Workspace[] = result.data?.workspaces?.items ?? [];\n // Same per-org narrowing as fetchWorkspacesForOrg — see the\n // comment there for why we don't just dump the full caller-\n // visible list into the store.\n const ws = allWs.filter(\n (w) => w.organizationId === currentOrganizationId,\n );\n store.setWorkspaces(ws);\n }\n })\n .catch(() => {\n // Silent fail - user can manually refresh or select org again\n })\n .finally(() => {\n store.setLoadingWorkspaces(false);\n });\n }\n }, [\n currentOrganizationId,\n workspaces,\n accessToken,\n isLoadingWorkspaces,\n globalBaseUrl,\n disableWorkspaceSync,\n ]);\n}\n\n/**\n * Hook to reactively ensure projects are loaded when a workspace is selected.\n *\n * This handles the case where a workspace is auto-selected (from URL/localStorage)\n * but projects haven't been fetched yet. It will:\n * 1. Issue a workspace token if not present\n * 2. Fetch projects for the selected workspace\n *\n * Usage:\n * ```tsx\n * import { useProjectSyncEffect } from '@burdenoff/microfe-auth';\n *\n * function MyComponent() {\n * useProjectSyncEffect(); // Ensures projects are loaded for selected workspace\n * // ...\n * }\n * ```\n */\nexport function useProjectSyncEffect(options?: UseContextSwitcherDataOptions) {\n const currentWorkspaceId = useAuthStore((state) => state.currentWorkspaceId);\n const currentOrganizationId = useAuthStore(\n (state) => state.currentOrganizationId,\n );\n const workspaces = useAuthStore((state) => state.workspaces);\n const projects = useAuthStore((state) => state.projects);\n const currentProjectId = useAuthStore((state) => state.currentProjectId);\n const workspaceToken = useAuthStore((state) => state.workspaceToken);\n const accessToken = useAuthStore((state) => state.accessToken);\n const resolvedBaseUrls = resolveGatewayBaseUrls();\n const workspaceBaseUrl =\n options?.workspaceBaseUrl ?? resolvedBaseUrls.workspaceBaseUrl;\n const disableProjectSync = options?.disableProjectSync ?? false;\n const skipProjectFetch = options?.skipProjectFetch ?? false;\n\n // Use refs to prevent the infinite loop caused by including loading/failure\n // state in the dependency array. Without these, the cycle is:\n // setLoadingProjects(true) -> dep change -> effect re-runs (guarded) ->\n // async completes -> setLoadingProjects(false) -> dep change ->\n // effect re-runs -> starts again -> INFINITE LOOP\n const syncInProgressRef = useRef(false);\n // Pending retry timer per workspace, so transient failures (e.g. RBAC lag\n // right after workspace creation) get an automatic second chance even if no\n // dependency change re-triggers the effect.\n const retryTimerRef = useRef<Map<string, ReturnType<typeof setTimeout>>>(\n new Map(),\n );\n // Per-workspace failure tracker — caps retry attempts when project bootstrap\n // (token issue, list, or default-create) fails. Without this, a persistent\n // backend failure (e.g. cross-layer workspace not yet synced) causes the\n // effect to re-fire every render: list returns empty → create-default fails\n // → setProjects([]) → new array reference → effect re-runs → loop.\n //\n // We track both count AND lastFailureAt so we can honour a \"cool-down\" window:\n // after PROJECT_SYNC_FAILURE_COOLDOWN_MS has elapsed since the last failure,\n // the counter is treated as cleared so transient backend hiccups (e.g. RBAC\n // role propagation lag right after signup) don't permanently lock a workspace\n // out of the context dropdown — the original cause of marqueue §729.\n const projectSyncFailuresRef = useRef<\n Map<string, { count: number; lastFailureAt: number }>\n >(new Map());\n const PROJECT_SYNC_MAX_FAILURES = 8;\n const PROJECT_SYNC_FAILURE_COOLDOWN_MS = 30_000;\n useEffect(() => {\n if (disableProjectSync) return;\n // Skip if no workspace selected or no access token\n if (!currentWorkspaceId || !accessToken) return;\n\n // Skip if a sync is already in progress (ref-based guard avoids dep loop)\n if (syncInProgressRef.current) return;\n\n // Stop retrying once this workspace has failed too many times in a row.\n // Counter is reset on success, on workspace switch (different key), by\n // an explicit user retry path (e.g. selectWorkspace), or after the\n // cool-down window has elapsed since the last failure (so transient\n // backend issues don't permanently wedge the dropdown).\n const failureEntry = projectSyncFailuresRef.current.get(currentWorkspaceId);\n if (\n failureEntry &&\n failureEntry.count >= PROJECT_SYNC_MAX_FAILURES &&\n Date.now() - failureEntry.lastFailureAt < PROJECT_SYNC_FAILURE_COOLDOWN_MS\n ) {\n return;\n }\n if (\n failureEntry &&\n Date.now() - failureEntry.lastFailureAt >=\n PROJECT_SYNC_FAILURE_COOLDOWN_MS\n ) {\n // Cool-down elapsed — clear the counter so we get a fresh budget.\n projectSyncFailuresRef.current.delete(currentWorkspaceId);\n }\n\n // Resolve organizationId: prefer the workspace object (if loaded), fall\n // back to the persisted currentOrganizationId. The workspaces array is\n // NOT persisted by zustand, so on page reload it is empty until\n // fetchOrganizations() completes. Using the persisted org ID lets us\n // issue the workspace token immediately instead of waiting.\n const currentWorkspace = workspaces.find(\n (ws) => ws.id === currentWorkspaceId,\n );\n\n // Guard: transient (newOrg, oldWs) divergence during org switches — token issuance always fails.\n if (\n currentWorkspace &&\n currentOrganizationId &&\n currentWorkspace.organizationId !== currentOrganizationId\n ) {\n return;\n }\n\n const organizationId =\n currentWorkspace?.organizationId ?? currentOrganizationId;\n if (!organizationId) return;\n\n const store = useAuthStore.getState();\n\n // If we don't have a workspace token or it's expired, issue one first\n const needsToken =\n !workspaceToken ||\n isTokenExpired(workspaceToken) ||\n !isWorkspaceTokenValidForContext(workspaceToken, {\n workspaceId: currentWorkspaceId,\n organizationId: currentOrganizationId,\n projectId: currentProjectId,\n });\n\n // Skip if projects are already loaded for this workspace AND token is valid\n const hasProjectsForWorkspace = projects.some(\n (p) => p.workspaceId === currentWorkspaceId,\n );\n if (hasProjectsForWorkspace && !needsToken) {\n if (!store.currentProjectId) {\n const firstProject = projects.find(\n (project) => project.workspaceId === currentWorkspaceId,\n );\n if (firstProject) {\n store.setCurrentProjectId(firstProject.id);\n }\n }\n return;\n }\n\n const syncProjects = async () => {\n syncInProgressRef.current = true;\n store.setLoadingProjects(true);\n let succeeded = false;\n\n try {\n let wsToken = workspaceToken;\n\n // Issue workspace token if needed\n if (needsToken) {\n const tokenResult = await graphqlFetch<{\n issueWorkspaceToken: IssueWorkspaceTokenResult;\n }>({\n gateway: \"workspace\",\n query: ISSUE_WORKSPACE_TOKEN_MUTATION,\n variables: {\n input: {\n organizationId,\n workspaceId: currentWorkspaceId,\n ...(currentProjectId ? { projectId: currentProjectId } : {}),\n },\n },\n authToken: accessToken,\n baseUrl: workspaceBaseUrl,\n // See issueWorkspaceToken: send the current workspace's tenant so a\n // super_admin (no tenant claim) can resolve it for an unmirrored ws.\n tenantId: workspaces.find((ws) => ws.id === currentWorkspaceId)\n ?.tenantId,\n });\n\n if (\n tokenResult.data?.issueWorkspaceToken?.success &&\n tokenResult.data.issueWorkspaceToken.token\n ) {\n wsToken = tokenResult.data.issueWorkspaceToken.token;\n store.setWorkspaceToken(wsToken);\n } else {\n return;\n }\n }\n\n // Fetch projects (skip if already loaded or token-only sync requested)\n if (wsToken && !hasProjectsForWorkspace && !skipProjectFetch) {\n const projectsResult = await graphqlFetch<ProjectsResponse>({\n gateway: \"workspace\",\n query: PROJECTS_QUERY,\n authToken: accessToken,\n workspaceToken: wsToken,\n baseUrl: workspaceBaseUrl,\n });\n\n if (projectsResult.errors?.length) {\n return;\n }\n\n let projs: Project[] = projectsResult.data?.projects?.items ?? [];\n if (projs.length === 0) {\n const defaultProject = await createDefaultProject({\n authToken: accessToken,\n workspaceBaseUrl,\n workspaceToken: wsToken,\n });\n if (defaultProject) {\n projs = [defaultProject];\n } else {\n // Default-project creation failed (e.g. workspace not yet\n // propagated to the workspace layer). Do NOT write [] back —\n // that would change the projects reference and re-trigger\n // this effect on the next render.\n return;\n }\n }\n\n store.setProjects(projs);\n\n // Auto-select first project if none selected and projects exist\n if (projs.length > 0 && !store.currentProjectId) {\n store.setCurrentProjectId(projs[0].id);\n }\n }\n\n succeeded = true;\n } catch {\n // A later auth/context update should be able to retry.\n } finally {\n store.setLoadingProjects(false);\n syncInProgressRef.current = false;\n const failures = projectSyncFailuresRef.current;\n if (succeeded) {\n failures.delete(currentWorkspaceId);\n const pending = retryTimerRef.current.get(currentWorkspaceId);\n if (pending) {\n clearTimeout(pending);\n retryTimerRef.current.delete(currentWorkspaceId);\n }\n } else {\n const existing = failures.get(currentWorkspaceId);\n const nextCount = (existing?.count ?? 0) + 1;\n failures.set(currentWorkspaceId, {\n count: nextCount,\n lastFailureAt: Date.now(),\n });\n // Schedule a backoff retry for transient backend lag (e.g. RBAC\n // role propagation right after signup → first projects() call hits\n // permission-denied). Without this, the effect would only re-run on\n // dep change and the user would be stuck staring at an empty\n // project dropdown until something else triggered a re-render.\n if (nextCount < PROJECT_SYNC_MAX_FAILURES) {\n const existingTimer = retryTimerRef.current.get(currentWorkspaceId);\n if (existingTimer) clearTimeout(existingTimer);\n const backoffMs = Math.min(1000 * 2 ** (nextCount - 1), 8000);\n const timer = setTimeout(() => {\n retryTimerRef.current.delete(currentWorkspaceId);\n // Only re-run if the workspace context is still the same and\n // a project hasn't been loaded for it in the meantime.\n const latest = useAuthStore.getState();\n if (\n latest.currentWorkspaceId === currentWorkspaceId &&\n !latest.projects.some(\n (p) => p.workspaceId === currentWorkspaceId,\n ) &&\n !syncInProgressRef.current\n ) {\n // Bump a render by clearing then resetting workspaceToken\n // when valid, OR by re-issuing projects fetch directly. The\n // simplest robust trigger is to clear the in-progress guard\n // and call syncProjects() again with current closure values.\n void syncProjects();\n }\n }, backoffMs);\n retryTimerRef.current.set(currentWorkspaceId, timer);\n }\n }\n }\n };\n\n syncProjects();\n }, [\n currentWorkspaceId,\n currentOrganizationId,\n workspaces,\n projects,\n currentProjectId,\n workspaceToken,\n accessToken,\n workspaceBaseUrl,\n disableProjectSync,\n skipProjectFetch,\n ]);\n\n // Cleanup any pending retry timers on unmount so we don't leak stray\n // setTimeout callbacks running against stale closures.\n useEffect(() => {\n const timers = retryTimerRef.current;\n return () => {\n timers.forEach((timer) => clearTimeout(timer));\n timers.clear();\n };\n }, []);\n}\n// hmr-bust-1778064429\n"],"mappings":";;;;;;;AAqFA,IAAM,IAAyB,2RAoCzB,IAA0B,oSAoB1B,IAAiC,6SA0BjC,IAAiB,uPAkBjB,IAAkC;AAexC,eAAe,EAAqB,EAClC,cACA,qBACA,qBAK0B;CAC1B,IAAM,IAAS,MAAM,EAAoC;EACvD,SAAS;EACT,OAAO;EACP,WAAW,EACT,OAAO,EACL,MAAM,mBACP,EACF;EACD;EACA;EACA,SAAS;EACV,CAAC;AAOF,QALI,EAAO,QAAQ,UACjB,QAAQ,KAAK,qCAAqC,EAAO,OAAO,EACzD,QAGF,EAAO,MAAM,iBAAiB;;AAWvC,SAAS,EAAe,GAAe,IAAW,KAAiB;AACjE,KAAI;EACF,IAAM,IAAU,KAAK,MAAM,KAAK,EAAM,MAAM,IAAI,CAAC,GAAG,CAAC;AAErD,SADK,EAAQ,MACN,EAAQ,MAAM,MAAO,KAAK,KAAK,GAAG,IADhB;SAEnB;AACN,SAAO;;;AAIX,SAAS,EAAyB,GAKzB;AACP,KAAI;EACF,IAAM,IAAU,KAAK,MAAM,KAAK,EAAM,MAAM,IAAI,CAAC,GAAG,CAAC;AACrD,SAAO;GACL,aACE,OAAO,EAAQ,eAAgB,WAC3B,EAAQ,cACR,KAAA;GACN,gBACE,OAAO,EAAQ,kBAAmB,WAC9B,EAAQ,iBACR,KAAA;GACN,W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