@zjazj/web 0.0.0-stage → 0.0.2

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.
package/dist/index.js ADDED
@@ -0,0 +1,999 @@
1
+ // src/index.ts
2
+ import { registerMessages as registerMessages2 } from "@zjazj/i18n";
3
+
4
+ // src/locales/en-US.json
5
+ var en_US_default = {
6
+ apps: "Apps",
7
+ account: "Account",
8
+ signOut: "Sign out",
9
+ theme: "Theme",
10
+ themeLight: "Light",
11
+ themeDark: "Dark",
12
+ themeSystem: "System",
13
+ language: "Language",
14
+ localeEnUS: "English",
15
+ localeZhCN: "\u7B80\u4F53\u4E2D\u6587",
16
+ tenant: "Tenant",
17
+ devIdentity: "Dev identity",
18
+ notFoundTitle: "Page not found",
19
+ notFoundBody: "This page does not exist in tenant {{tenant}}.",
20
+ forbiddenTitle: "No access",
21
+ forbiddenBody: "You do not have permission to open this page.",
22
+ tenantChangedTitle: "Tenant changed",
23
+ tenantChangedBody: "You switched tenant in another tab. Reload this page to continue.",
24
+ reload: "Reload",
25
+ backToApps: "Back to Apps",
26
+ signIn: "Sign in",
27
+ signingInTitle: "Signing in",
28
+ signingInBody: "One moment.",
29
+ signedOutTitle: "You are signed out",
30
+ signedOutBody: "Sign in again to continue.",
31
+ signInRequiredTitle: "Sign-in is not available",
32
+ signInRequiredBody: "Sign-in is not set up at this address. For local development, start the app with ENV=dev.",
33
+ signInFailedTitle: "Sign-in failed",
34
+ tryAgain: "Try again",
35
+ noTenantTitle: "No tenant",
36
+ noTenantBody: "Your account does not belong to a tenant yet. Ask an administrator to invite you.",
37
+ errorTitle: "Something went wrong",
38
+ traceId: "Trace id: {{id}}"
39
+ };
40
+
41
+ // src/locales/zh-CN.json
42
+ var zh_CN_default = {
43
+ apps: "\u5E94\u7528",
44
+ account: "\u8D26\u53F7",
45
+ signOut: "\u9000\u51FA\u767B\u5F55",
46
+ theme: "\u4E3B\u9898",
47
+ themeLight: "\u6D45\u8272",
48
+ themeDark: "\u6DF1\u8272",
49
+ themeSystem: "\u8DDF\u968F\u7CFB\u7EDF",
50
+ language: "\u8BED\u8A00",
51
+ localeEnUS: "English",
52
+ localeZhCN: "\u7B80\u4F53\u4E2D\u6587",
53
+ tenant: "\u79DF\u6237",
54
+ devIdentity: "\u5F00\u53D1\u8EAB\u4EFD",
55
+ notFoundTitle: "\u9875\u9762\u4E0D\u5B58\u5728",
56
+ notFoundBody: "\u79DF\u6237 {{tenant}} \u4E0B\u6CA1\u6709\u8FD9\u4E2A\u9875\u9762\u3002",
57
+ forbiddenTitle: "\u65E0\u6743\u8BBF\u95EE",
58
+ forbiddenBody: "\u4F60\u6CA1\u6709\u6253\u5F00\u8FD9\u4E2A\u9875\u9762\u7684\u6743\u9650\u3002",
59
+ tenantChangedTitle: "\u79DF\u6237\u5DF2\u5207\u6362",
60
+ tenantChangedBody: "\u4F60\u5728\u53E6\u4E00\u4E2A\u6807\u7B7E\u9875\u5207\u6362\u4E86\u79DF\u6237\u3002\u8BF7\u5237\u65B0\u672C\u9875\u540E\u7EE7\u7EED\u3002",
61
+ reload: "\u5237\u65B0",
62
+ backToApps: "\u8FD4\u56DE\u5E94\u7528\u5217\u8868",
63
+ signIn: "\u767B\u5F55",
64
+ signingInTitle: "\u6B63\u5728\u767B\u5F55",
65
+ signingInBody: "\u8BF7\u7A0D\u5019\u3002",
66
+ signedOutTitle: "\u4F60\u5DF2\u9000\u51FA\u767B\u5F55",
67
+ signedOutBody: "\u91CD\u65B0\u767B\u5F55\u540E\u7EE7\u7EED\u3002",
68
+ signInRequiredTitle: "\u65E0\u6CD5\u767B\u5F55",
69
+ signInRequiredBody: "\u8FD9\u4E2A\u5730\u5740\u6CA1\u6709\u914D\u7F6E\u767B\u5F55\u3002\u672C\u5730\u5F00\u53D1\u8BF7\u4EE5 ENV=dev \u542F\u52A8\u5E94\u7528\u3002",
70
+ signInFailedTitle: "\u767B\u5F55\u5931\u8D25",
71
+ tryAgain: "\u91CD\u8BD5",
72
+ noTenantTitle: "\u6CA1\u6709\u79DF\u6237",
73
+ noTenantBody: "\u4F60\u7684\u8D26\u53F7\u8FD8\u4E0D\u5C5E\u4E8E\u4EFB\u4F55\u79DF\u6237\u3002\u8BF7\u8054\u7CFB\u7BA1\u7406\u5458\u9080\u8BF7\u4F60\u3002",
74
+ errorTitle: "\u51FA\u9519\u4E86",
75
+ traceId: "\u8FFD\u8E2A\u53F7\uFF1A{{id}}"
76
+ };
77
+
78
+ // src/app.tsx
79
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
80
+ import { createRouter, RouterProvider } from "@tanstack/react-router";
81
+ import { registerMessages, setTimeZone } from "@zjazj/i18n";
82
+ import { Toaster } from "@zjazj/ui";
83
+ import { StrictMode } from "react";
84
+ import { createRoot } from "react-dom/client";
85
+
86
+ // src/client.ts
87
+ import { hc } from "hono/client";
88
+
89
+ // src/config.ts
90
+ function withSlashes(path) {
91
+ const trimmed = (path ?? "/").replace(/^\/+|\/+$/g, "");
92
+ return trimmed ? `/${trimmed}/` : "/";
93
+ }
94
+ function getPlatformConfig() {
95
+ const raw = typeof window !== "undefined" && window.__PLATFORM__ || {};
96
+ const name = raw.name ?? "app";
97
+ return {
98
+ name,
99
+ id: raw.id ?? "",
100
+ title: raw.title ?? name,
101
+ version: raw.version,
102
+ basePath: withSlashes(raw.basePath),
103
+ portalUrl: raw.portalUrl ?? "/",
104
+ dev: raw.dev
105
+ };
106
+ }
107
+ function apiBaseUrl(config = getPlatformConfig()) {
108
+ const origin = typeof window !== "undefined" ? window.location.origin : "http://localhost";
109
+ return `${origin}${config.basePath}api`;
110
+ }
111
+
112
+ // src/tenant.ts
113
+ var TENANT_STORAGE_KEY = "platform.tenant";
114
+ var listeners = /* @__PURE__ */ new Set();
115
+ var pinned;
116
+ var changed = false;
117
+ function notify() {
118
+ for (const listener of listeners) listener();
119
+ }
120
+ function parseStoredTenant(raw) {
121
+ if (!raw) return void 0;
122
+ try {
123
+ const parsed = JSON.parse(raw);
124
+ if (parsed && typeof parsed === "object") {
125
+ const { organizationId, tenantId } = parsed;
126
+ return {
127
+ ...typeof organizationId === "string" && organizationId ? { organizationId } : {},
128
+ ...typeof tenantId === "string" && tenantId ? { tenantId } : {}
129
+ };
130
+ }
131
+ } catch {
132
+ }
133
+ return { tenantId: raw };
134
+ }
135
+ function readStoredTenant() {
136
+ try {
137
+ const stored = parseStoredTenant(globalThis.localStorage?.getItem(TENANT_STORAGE_KEY));
138
+ return stored?.organizationId && stored.tenantId ? stored : void 0;
139
+ } catch {
140
+ return void 0;
141
+ }
142
+ }
143
+ function writeStoredTenant(value) {
144
+ const current = readStoredTenant();
145
+ if (current?.organizationId === value.organizationId && current.tenantId === value.tenantId) {
146
+ return;
147
+ }
148
+ try {
149
+ globalThis.localStorage?.setItem(TENANT_STORAGE_KEY, JSON.stringify(value));
150
+ } catch {
151
+ }
152
+ }
153
+ function clearStoredTenant() {
154
+ try {
155
+ globalThis.localStorage?.removeItem(TENANT_STORAGE_KEY);
156
+ } catch {
157
+ }
158
+ }
159
+ function pinTenant(tenantId) {
160
+ pinned = tenantId;
161
+ if (changed) {
162
+ changed = false;
163
+ notify();
164
+ }
165
+ }
166
+ function getPinnedTenant() {
167
+ return pinned;
168
+ }
169
+ function isTenantChanged() {
170
+ return changed;
171
+ }
172
+ function subscribeTenant(listener) {
173
+ listeners.add(listener);
174
+ return () => {
175
+ listeners.delete(listener);
176
+ };
177
+ }
178
+ function handleTenantStorage(newValue) {
179
+ const tenantId = parseStoredTenant(newValue)?.tenantId;
180
+ if (!pinned || !tenantId || tenantId === pinned || changed) return;
181
+ changed = true;
182
+ notify();
183
+ }
184
+ if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
185
+ window.addEventListener("storage", (event) => {
186
+ if (event.key === TENANT_STORAGE_KEY) handleTenantStorage(event.newValue);
187
+ });
188
+ }
189
+
190
+ // src/auth.ts
191
+ var AUTH_CONFIG_PATH = "/auth/config";
192
+ var AUTH_CALLBACK_PATH = "/auth/callback";
193
+ var RETURN_TO_KEY = "platform.auth.returnTo";
194
+ var SESSION_CHANNEL = "platform.session";
195
+ var TOKEN_LOCK = "platform.auth.token";
196
+ var EXPIRY_LEEWAY_SECONDS = 60;
197
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
198
+ function strings(value) {
199
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
200
+ }
201
+ function firstString(...values) {
202
+ return values.find((value) => typeof value === "string" && value !== "");
203
+ }
204
+ function messageOf(error) {
205
+ return error instanceof Error ? error.message : String(error);
206
+ }
207
+ async function loadAuthConfig(fetcher = fetch) {
208
+ const response = await fetcher(AUTH_CONFIG_PATH, { headers: { Accept: "application/json" } });
209
+ if (!response.ok) throw new Error(`GET ${AUTH_CONFIG_PATH} answered ${response.status}`);
210
+ let body;
211
+ try {
212
+ body = await response.json();
213
+ } catch {
214
+ throw new Error(`GET ${AUTH_CONFIG_PATH} did not answer with JSON`);
215
+ }
216
+ const { endpoint, appId, resource } = body ?? {};
217
+ if (typeof endpoint !== "string" || !endpoint || typeof appId !== "string" || !appId) {
218
+ throw new Error(`GET ${AUTH_CONFIG_PATH} answered without an endpoint and a client id`);
219
+ }
220
+ return { endpoint, appId, ...typeof resource === "string" && resource ? { resource } : {} };
221
+ }
222
+ async function createLogtoClient(config) {
223
+ const { default: LogtoClient, UserScope } = await import("@logto/browser");
224
+ return new LogtoClient({
225
+ endpoint: config.endpoint,
226
+ appId: config.appId,
227
+ resources: config.resource ? [config.resource] : void 0,
228
+ scopes: [
229
+ UserScope.Email,
230
+ UserScope.Profile,
231
+ UserScope.Organizations,
232
+ UserScope.OrganizationRoles
233
+ ]
234
+ });
235
+ }
236
+ function decodeTokenClaims(token) {
237
+ const part = token.split(".")[1];
238
+ if (!part) throw new Error("The token is not a JWT.");
239
+ const base64 = part.replaceAll("-", "+").replaceAll("_", "/");
240
+ const binary = atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
241
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
242
+ const claims = JSON.parse(new TextDecoder().decode(bytes));
243
+ if (!claims || typeof claims !== "object") throw new Error("The token has no claims.");
244
+ return claims;
245
+ }
246
+ function userFromTokenClaims(claims, profile = {}) {
247
+ const { sub, tenant_id: tenantId } = claims;
248
+ if (typeof sub !== "string" || sub === "") throw new Error("The token has no subject.");
249
+ if (typeof tenantId !== "string" || !UUID_PATTERN.test(tenantId)) {
250
+ throw new Error("The token has no tenant.");
251
+ }
252
+ const roles = strings(claims.organization_roles);
253
+ const timeZone = firstString(claims.tenant_time_zone);
254
+ return {
255
+ id: sub,
256
+ tenantId: tenantId.toLowerCase(),
257
+ tenantSlug: firstString(claims.tenant_slug, claims.organization_id) ?? "",
258
+ username: firstString(
259
+ claims.username,
260
+ claims.name,
261
+ claims.email,
262
+ profile.username,
263
+ profile.name,
264
+ profile.email
265
+ ) ?? sub,
266
+ roles: roles.length > 0 ? roles : strings(claims.roles),
267
+ permissions: strings(claims.permissions),
268
+ ...timeZone ? { timeZone } : {}
269
+ };
270
+ }
271
+ function rememberLocation() {
272
+ const { pathname, search, hash } = window.location;
273
+ try {
274
+ window.sessionStorage.setItem(RETURN_TO_KEY, `${pathname}${search}${hash}`);
275
+ } catch {
276
+ }
277
+ }
278
+ function withTokenLock(task) {
279
+ const locks = globalThis.navigator?.locks;
280
+ return locks ? locks.request(TOKEN_LOCK, task) : task();
281
+ }
282
+ function createPlatformSession(options = {}) {
283
+ const loadConfig = options.loadConfig ?? (() => loadAuthConfig());
284
+ const createClient2 = options.createClient ?? createLogtoClient;
285
+ const now = options.now ?? Date.now;
286
+ const listeners2 = /* @__PURE__ */ new Set();
287
+ let status = { state: "loading" };
288
+ let user = null;
289
+ let profile = {};
290
+ let organizationId;
291
+ let token;
292
+ let connecting;
293
+ let refreshing;
294
+ let signingIn;
295
+ const update = (nextUser, nextStatus) => {
296
+ const userChanged = JSON.stringify(nextUser) !== JSON.stringify(user);
297
+ const statusChanged = nextStatus.state !== status.state || nextStatus.code !== status.code || nextStatus.message !== status.message;
298
+ if (userChanged) user = nextUser;
299
+ if (statusChanged) status = nextStatus;
300
+ if (userChanged || statusChanged) for (const listener of listeners2) listener();
301
+ };
302
+ const isReady = () => status.state === "ready";
303
+ const fail = (code, error) => {
304
+ token = void 0;
305
+ update(null, { state: "error", code, message: messageOf(error) });
306
+ };
307
+ const end = () => {
308
+ token = void 0;
309
+ update(null, { state: "ended" });
310
+ };
311
+ const connect = () => {
312
+ if (!connecting) {
313
+ const attempt = (async () => createClient2(await loadConfig()))();
314
+ connecting = attempt;
315
+ attempt.catch(() => {
316
+ if (connecting === attempt) connecting = void 0;
317
+ });
318
+ }
319
+ return connecting;
320
+ };
321
+ const readToken = (value) => {
322
+ const claims = decodeTokenClaims(value);
323
+ const next = userFromTokenClaims(claims, profile);
324
+ token = { value, expiresAt: typeof claims.exp === "number" ? claims.exp : 0 };
325
+ return next;
326
+ };
327
+ const adopt = async (identity) => {
328
+ profile = await identity.getIdTokenClaims() ?? {};
329
+ const organizations = strings(profile.organizations);
330
+ const stored = readStoredTenant();
331
+ const organization = stored && organizations.includes(stored.organizationId) ? stored.organizationId : organizations[0];
332
+ if (!organization) {
333
+ fail("no_organization", "The account is not a member of any tenant.");
334
+ return;
335
+ }
336
+ const value = await identity.getOrganizationToken(organization);
337
+ let next;
338
+ try {
339
+ next = readToken(value);
340
+ } catch (error) {
341
+ fail("no_tenant", error);
342
+ return;
343
+ }
344
+ organizationId = organization;
345
+ writeStoredTenant({ organizationId: organization, tenantId: next.tenantId });
346
+ update(next, { state: "ready" });
347
+ };
348
+ const restore = async () => {
349
+ let identity;
350
+ try {
351
+ identity = await connect();
352
+ } catch (error) {
353
+ fail("not_configured", error);
354
+ return;
355
+ }
356
+ try {
357
+ if (await identity.isAuthenticated()) {
358
+ await adopt(identity);
359
+ return;
360
+ }
361
+ } catch {
362
+ }
363
+ update(null, { state: "signed-out" });
364
+ };
365
+ const started = restore();
366
+ const refresh = () => withTokenLock(async () => {
367
+ const current = token;
368
+ try {
369
+ const identity = await connect();
370
+ await identity.clearAccessToken();
371
+ const value = await identity.getOrganizationToken(organizationId);
372
+ update(readToken(value), { state: "ready" });
373
+ return value;
374
+ } catch {
375
+ if (current && current.expiresAt > now() / 1e3) {
376
+ token = current;
377
+ return current.value;
378
+ }
379
+ end();
380
+ return null;
381
+ }
382
+ });
383
+ const startSignIn = async () => {
384
+ let identity;
385
+ try {
386
+ identity = await connect();
387
+ } catch (error) {
388
+ fail("not_configured", error);
389
+ return;
390
+ }
391
+ try {
392
+ if (!isReady() && await identity.isAuthenticated()) {
393
+ await adopt(identity);
394
+ if (isReady()) return;
395
+ }
396
+ } catch {
397
+ }
398
+ try {
399
+ rememberLocation();
400
+ await identity.signIn(`${window.location.origin}${AUTH_CALLBACK_PATH}`);
401
+ } catch (error) {
402
+ fail("sign_in_failed", error);
403
+ }
404
+ };
405
+ const channel = typeof BroadcastChannel === "function" ? new BroadcastChannel(SESSION_CHANNEL) : void 0;
406
+ channel?.addEventListener("message", (event) => {
407
+ const type = event.data?.type;
408
+ if (type === "signed-out" && isReady()) end();
409
+ });
410
+ channel?.unref?.();
411
+ return {
412
+ kind: "platform",
413
+ getUser: () => user,
414
+ getStatus: () => status,
415
+ async getAccessToken() {
416
+ await started;
417
+ if (!isReady() || !token) return null;
418
+ if (token.expiresAt - now() / 1e3 > EXPIRY_LEEWAY_SECONDS) return token.value;
419
+ refreshing ??= refresh().finally(() => {
420
+ refreshing = void 0;
421
+ });
422
+ return refreshing;
423
+ },
424
+ signIn() {
425
+ signingIn ??= started.then(startSignIn).finally(() => {
426
+ signingIn = void 0;
427
+ });
428
+ return signingIn;
429
+ },
430
+ async signOut() {
431
+ channel?.postMessage({ type: "signed-out" });
432
+ clearStoredTenant();
433
+ end();
434
+ try {
435
+ const identity = await connect();
436
+ await identity.signOut(window.location.origin);
437
+ } catch {
438
+ }
439
+ },
440
+ subscribe(listener) {
441
+ listeners2.add(listener);
442
+ return () => {
443
+ listeners2.delete(listener);
444
+ };
445
+ }
446
+ };
447
+ }
448
+
449
+ // src/session.ts
450
+ var DEV_USER_STORAGE_KEY = "platform.dev.user";
451
+ var DEV_TOKEN_PREFIX = "dev.";
452
+ var READY = { state: "ready" };
453
+ function base64Url(value) {
454
+ const bytes = new TextEncoder().encode(value);
455
+ let binary = "";
456
+ for (const byte of bytes) binary += String.fromCharCode(byte);
457
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
458
+ }
459
+ function encodeDevToken(user) {
460
+ const { isDev: _isDev, ...payload } = user;
461
+ return DEV_TOKEN_PREFIX + base64Url(JSON.stringify(payload));
462
+ }
463
+ function readStoredPatch() {
464
+ try {
465
+ const stored = globalThis.localStorage?.getItem(DEV_USER_STORAGE_KEY);
466
+ const parsed = stored ? JSON.parse(stored) : null;
467
+ return parsed && typeof parsed === "object" ? parsed : {};
468
+ } catch {
469
+ return {};
470
+ }
471
+ }
472
+ function createDevSession(base) {
473
+ const listeners2 = /* @__PURE__ */ new Set();
474
+ let patch = readStoredPatch();
475
+ let current = { ...base, ...patch, isDev: true };
476
+ const update = (next) => {
477
+ patch = next;
478
+ current = { ...base, ...patch, isDev: true };
479
+ try {
480
+ if (Object.keys(patch).length === 0) globalThis.localStorage?.removeItem(DEV_USER_STORAGE_KEY);
481
+ else globalThis.localStorage?.setItem(DEV_USER_STORAGE_KEY, JSON.stringify(patch));
482
+ } catch {
483
+ }
484
+ for (const listener of listeners2) listener();
485
+ };
486
+ return {
487
+ kind: "dev",
488
+ getUser: () => current,
489
+ getStatus: () => READY,
490
+ getAccessToken: async () => encodeDevToken(current),
491
+ signIn: async () => {
492
+ },
493
+ signOut: async () => update({}),
494
+ subscribe(listener) {
495
+ listeners2.add(listener);
496
+ return () => {
497
+ listeners2.delete(listener);
498
+ };
499
+ },
500
+ setUser: (next) => update({ ...patch, ...next }),
501
+ reset: () => update({})
502
+ };
503
+ }
504
+ var active;
505
+ function getSession() {
506
+ if (!active) {
507
+ const dev = getPlatformConfig().dev;
508
+ active = dev ? createDevSession(dev.user) : createPlatformSession();
509
+ }
510
+ return active;
511
+ }
512
+ function setSession(session) {
513
+ active = session;
514
+ }
515
+
516
+ // src/client.ts
517
+ var ApiError = class _ApiError extends Error {
518
+ status;
519
+ code;
520
+ traceId;
521
+ field;
522
+ constructor(fields) {
523
+ super(fields.message);
524
+ this.name = "ApiError";
525
+ this.status = fields.status;
526
+ this.code = fields.code;
527
+ this.traceId = fields.traceId;
528
+ this.field = fields.field;
529
+ }
530
+ /** Build the error from a response. Accepts the flat body and the body nested in `detail`. */
531
+ static async fromResponse(response) {
532
+ let body = {};
533
+ try {
534
+ const parsed = await response.clone().json();
535
+ if (parsed && typeof parsed === "object") {
536
+ const detail = parsed.detail;
537
+ body = detail && typeof detail === "object" ? detail : parsed;
538
+ }
539
+ } catch {
540
+ }
541
+ const text = (value) => typeof value === "string" && value ? value : void 0;
542
+ return new _ApiError({
543
+ status: response.status,
544
+ code: text(body.code) ?? `http_${response.status}`,
545
+ message: text(body.message) ?? (response.statusText || `Request failed (${response.status})`),
546
+ traceId: text(body.trace_id) ?? response.headers.get("X-Request-Id") ?? void 0,
547
+ field: text(body.field)
548
+ });
549
+ }
550
+ };
551
+ async function platformFetch(input, init) {
552
+ if (isTenantChanged()) {
553
+ throw new ApiError({
554
+ status: 409,
555
+ code: "tenant_changed",
556
+ message: "The tenant changed in another tab. Reload the page."
557
+ });
558
+ }
559
+ const session = getSession();
560
+ const headers = new Headers(
561
+ init?.headers ?? (input instanceof Request ? input.headers : void 0)
562
+ );
563
+ if (!headers.has("Authorization")) {
564
+ const token = await session.getAccessToken();
565
+ if (token) headers.set("Authorization", `Bearer ${token}`);
566
+ }
567
+ const response = await fetch(input, { ...init, headers });
568
+ if (response.ok) return response;
569
+ throw await ApiError.fromResponse(response);
570
+ }
571
+ function createClient(baseUrl = apiBaseUrl()) {
572
+ return hc(baseUrl, { fetch: platformFetch });
573
+ }
574
+
575
+ // src/context.tsx
576
+ import { createContext, useContext, useSyncExternalStore } from "react";
577
+
578
+ // src/permissions.ts
579
+ function permissionMatches(granted, code) {
580
+ if (granted.has(code) || granted.has("*")) return true;
581
+ const parts = code.split(":");
582
+ for (let keep = parts.length - 1; keep > 0; keep -= 1) {
583
+ const candidate = [...parts.slice(0, keep), ...Array(parts.length - keep).fill("*")].join(":");
584
+ if (granted.has(candidate)) return true;
585
+ }
586
+ return false;
587
+ }
588
+ function hasPermissions(granted, required) {
589
+ const set = granted instanceof Set ? granted : new Set(granted);
590
+ return required.every((code) => permissionMatches(set, code));
591
+ }
592
+
593
+ // src/context.tsx
594
+ import { jsx } from "react/jsx-runtime";
595
+ var PlatformContext = createContext(null);
596
+ function PlatformProvider(props) {
597
+ const { children, ...value } = props;
598
+ return /* @__PURE__ */ jsx(PlatformContext.Provider, { value, children });
599
+ }
600
+ function usePlatform() {
601
+ const value = useContext(PlatformContext);
602
+ if (!value) throw new Error("Platform hooks must be used inside an app created by createApp()");
603
+ return value;
604
+ }
605
+ function useAppConfig() {
606
+ return usePlatform().config;
607
+ }
608
+ function useSession() {
609
+ return usePlatform().session;
610
+ }
611
+ function useSessionStatus() {
612
+ const { session } = usePlatform();
613
+ return useSyncExternalStore(session.subscribe, session.getStatus, session.getStatus);
614
+ }
615
+ function useOptionalUser() {
616
+ const { session } = usePlatform();
617
+ return useSyncExternalStore(session.subscribe, session.getUser, session.getUser);
618
+ }
619
+ function useUser() {
620
+ const user = useOptionalUser();
621
+ if (!user) throw new Error("useUser() was called without a signed-in user");
622
+ return user;
623
+ }
624
+ function useTenant() {
625
+ const user = useUser();
626
+ return { id: user.tenantId, slug: user.tenantSlug, timeZone: user.timeZone };
627
+ }
628
+ function useCan(...codes) {
629
+ const user = useOptionalUser();
630
+ return user ? hasPermissions(user.permissions, codes) : false;
631
+ }
632
+ function Can({ permission, children, fallback = null }) {
633
+ const codes = Array.isArray(permission) ? permission : [permission];
634
+ return useCan(...codes) ? children : fallback;
635
+ }
636
+
637
+ // src/layout.tsx
638
+ import { Link, Outlet, useMatches, useRouter, useRouterState } from "@tanstack/react-router";
639
+ import { LOCALES } from "@zjazj/i18n";
640
+ import { useLocale, useT } from "@zjazj/i18n/react";
641
+ import {
642
+ Avatar,
643
+ AvatarFallback,
644
+ Badge,
645
+ Button,
646
+ DropdownMenu,
647
+ DropdownMenuContent,
648
+ DropdownMenuItem,
649
+ DropdownMenuLabel,
650
+ DropdownMenuRadioGroup,
651
+ DropdownMenuRadioItem,
652
+ DropdownMenuSeparator,
653
+ DropdownMenuSub,
654
+ DropdownMenuSubContent,
655
+ DropdownMenuSubTrigger,
656
+ DropdownMenuTrigger,
657
+ Separator,
658
+ Sidebar,
659
+ SidebarContent,
660
+ SidebarGroup,
661
+ SidebarGroupContent,
662
+ SidebarGroupLabel,
663
+ SidebarHeader,
664
+ SidebarInset,
665
+ SidebarMenu,
666
+ SidebarMenuButton,
667
+ SidebarMenuItem,
668
+ SidebarProvider,
669
+ SidebarRail,
670
+ SidebarTrigger,
671
+ useTheme
672
+ } from "@zjazj/ui";
673
+ import { LayoutGrid, LogOut } from "lucide-react";
674
+ import { useEffect, useMemo, useSyncExternalStore as useSyncExternalStore2 } from "react";
675
+
676
+ // src/menu.ts
677
+ function requiredPermissions(meta) {
678
+ if (!meta?.permission) return [];
679
+ return Array.isArray(meta.permission) ? meta.permission : [meta.permission];
680
+ }
681
+ function buildMenu(routes, permissions) {
682
+ const items = [];
683
+ const seen = /* @__PURE__ */ new Set();
684
+ for (const route of routes) {
685
+ const meta = route.options?.staticData;
686
+ const to = route.fullPath;
687
+ if (!meta?.menu || !to || to.includes("$") || seen.has(to)) continue;
688
+ if (!hasPermissions(permissions, requiredPermissions(meta))) continue;
689
+ seen.add(to);
690
+ items.push({ ...meta.menu, to, order: meta.menu.order ?? 100 });
691
+ }
692
+ items.sort((a, b) => a.order - b.order || a.label.localeCompare(b.label));
693
+ const groups = [];
694
+ for (const item of items) {
695
+ let group = groups.find((candidate) => candidate.label === item.group);
696
+ if (!group) {
697
+ group = { label: item.group, items: [] };
698
+ groups.push(group);
699
+ }
700
+ group.items.push(item);
701
+ }
702
+ return groups;
703
+ }
704
+
705
+ // src/layout.tsx
706
+ import { Fragment, jsx as jsx2, jsxs } from "react/jsx-runtime";
707
+ function Message(props) {
708
+ return /* @__PURE__ */ jsxs("div", { className: "flex min-h-[60vh] flex-col items-center justify-center gap-3 p-8 text-center", children: [
709
+ /* @__PURE__ */ jsx2("h1", { className: "text-2xl font-semibold", children: props.title }),
710
+ /* @__PURE__ */ jsx2("p", { className: "text-muted-foreground max-w-md", children: props.body }),
711
+ props.children
712
+ ] });
713
+ }
714
+ function AppsLink() {
715
+ const t = useT("web");
716
+ const { portalUrl } = useAppConfig();
717
+ return /* @__PURE__ */ jsx2(Button, { asChild: true, variant: "outline", size: "sm", children: /* @__PURE__ */ jsxs("a", { href: portalUrl, target: "platform-portal", children: [
718
+ /* @__PURE__ */ jsx2(LayoutGrid, {}),
719
+ t("backToApps")
720
+ ] }) });
721
+ }
722
+ function NotFound() {
723
+ const t = useT("web");
724
+ const user = useOptionalUser();
725
+ return /* @__PURE__ */ jsx2(
726
+ Message,
727
+ {
728
+ title: t("notFoundTitle"),
729
+ body: t("notFoundBody", { tenant: user?.tenantSlug || user?.tenantId || "-" }),
730
+ children: /* @__PURE__ */ jsx2(AppsLink, {})
731
+ }
732
+ );
733
+ }
734
+ function Forbidden() {
735
+ const t = useT("web");
736
+ return /* @__PURE__ */ jsx2(Message, { title: t("forbiddenTitle"), body: t("forbiddenBody") });
737
+ }
738
+ function ErrorScreen({ error }) {
739
+ const t = useT("web");
740
+ const message = error instanceof Error ? error.message : String(error);
741
+ return /* @__PURE__ */ jsx2(Message, { title: t("errorTitle"), body: message, children: error instanceof ApiError && error.traceId ? /* @__PURE__ */ jsx2("code", { className: "text-muted-foreground text-xs", children: t("traceId", { id: error.traceId }) }) : null });
742
+ }
743
+ function SessionScreen() {
744
+ const t = useT("web");
745
+ const session = useSession();
746
+ const status = useSessionStatus();
747
+ if (status.state === "ended") {
748
+ return /* @__PURE__ */ jsx2(Message, { title: t("signedOutTitle"), body: t("signedOutBody"), children: /* @__PURE__ */ jsx2(Button, { onClick: () => void session.signIn(), children: t("signIn") }) });
749
+ }
750
+ if (status.state === "error" && status.code === "not_configured") {
751
+ return /* @__PURE__ */ jsx2(Message, { title: t("signInRequiredTitle"), body: t("signInRequiredBody") });
752
+ }
753
+ if (status.state === "error" && status.code === "no_organization") {
754
+ return /* @__PURE__ */ jsx2(Message, { title: t("noTenantTitle"), body: t("noTenantBody"), children: /* @__PURE__ */ jsx2(Button, { variant: "outline", onClick: () => void session.signOut(), children: t("signOut") }) });
755
+ }
756
+ if (status.state === "error") {
757
+ return /* @__PURE__ */ jsx2(Message, { title: t("signInFailedTitle"), body: status.message ?? "", children: /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
758
+ /* @__PURE__ */ jsx2(Button, { onClick: () => void session.signIn(), children: t("tryAgain") }),
759
+ /* @__PURE__ */ jsx2(Button, { variant: "outline", onClick: () => void session.signOut(), children: t("signOut") })
760
+ ] }) });
761
+ }
762
+ return /* @__PURE__ */ jsx2(Message, { title: t("signingInTitle"), body: t("signingInBody") });
763
+ }
764
+ function TenantChanged() {
765
+ const t = useT("web");
766
+ return /* @__PURE__ */ jsx2("div", { className: "bg-background/95 fixed inset-0 z-[100] flex items-center justify-center", children: /* @__PURE__ */ jsx2(Message, { title: t("tenantChangedTitle"), body: t("tenantChangedBody"), children: /* @__PURE__ */ jsx2(Button, { onClick: () => window.location.reload(), children: t("reload") }) }) });
767
+ }
768
+ var THEME_MODES = [
769
+ { mode: "light", label: "themeLight" },
770
+ { mode: "dark", label: "themeDark" },
771
+ { mode: "system", label: "themeSystem" }
772
+ ];
773
+ var LOCALE_LABELS = { "en-US": "localeEnUS", "zh-CN": "localeZhCN" };
774
+ function AccountMenu() {
775
+ const t = useT("web");
776
+ const user = useUser();
777
+ const session = useSession();
778
+ const { theme, setTheme } = useTheme();
779
+ const [locale, setLocale] = useLocale();
780
+ const initials = user.username.trim().slice(0, 2).toUpperCase() || "?";
781
+ return /* @__PURE__ */ jsxs(DropdownMenu, { children: [
782
+ /* @__PURE__ */ jsx2(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsx2(Button, { variant: "ghost", size: "icon", className: "rounded-full", "aria-label": t("account"), children: /* @__PURE__ */ jsx2(Avatar, { className: "size-8", children: /* @__PURE__ */ jsx2(AvatarFallback, { children: initials }) }) }) }),
783
+ /* @__PURE__ */ jsxs(DropdownMenuContent, { align: "end", className: "w-56", children: [
784
+ /* @__PURE__ */ jsxs(DropdownMenuLabel, { className: "flex flex-col gap-1", children: [
785
+ /* @__PURE__ */ jsx2("span", { className: "truncate", children: user.username }),
786
+ /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground truncate text-xs font-normal", children: [
787
+ t("tenant"),
788
+ ": ",
789
+ user.tenantSlug || user.tenantId
790
+ ] })
791
+ ] }),
792
+ /* @__PURE__ */ jsx2(DropdownMenuSeparator, {}),
793
+ /* @__PURE__ */ jsxs(DropdownMenuSub, { children: [
794
+ /* @__PURE__ */ jsx2(DropdownMenuSubTrigger, { children: t("theme") }),
795
+ /* @__PURE__ */ jsx2(DropdownMenuSubContent, { children: /* @__PURE__ */ jsx2(
796
+ DropdownMenuRadioGroup,
797
+ {
798
+ value: theme,
799
+ onValueChange: (value) => setTheme(value),
800
+ children: THEME_MODES.map((option) => /* @__PURE__ */ jsx2(DropdownMenuRadioItem, { value: option.mode, children: t(option.label) }, option.mode))
801
+ }
802
+ ) })
803
+ ] }),
804
+ /* @__PURE__ */ jsxs(DropdownMenuSub, { children: [
805
+ /* @__PURE__ */ jsx2(DropdownMenuSubTrigger, { children: t("language") }),
806
+ /* @__PURE__ */ jsx2(DropdownMenuSubContent, { children: /* @__PURE__ */ jsx2(
807
+ DropdownMenuRadioGroup,
808
+ {
809
+ value: locale,
810
+ onValueChange: (value) => setLocale(value),
811
+ children: LOCALES.map((option) => /* @__PURE__ */ jsx2(DropdownMenuRadioItem, { value: option, children: t(LOCALE_LABELS[option]) }, option))
812
+ }
813
+ ) })
814
+ ] }),
815
+ /* @__PURE__ */ jsx2(DropdownMenuSeparator, {}),
816
+ /* @__PURE__ */ jsxs(DropdownMenuItem, { onSelect: () => void session.signOut(), children: [
817
+ /* @__PURE__ */ jsx2(LogOut, {}),
818
+ t("signOut")
819
+ ] })
820
+ ] })
821
+ ] });
822
+ }
823
+ function Navigation({ groups, pathname }) {
824
+ const t = useT("app");
825
+ return /* @__PURE__ */ jsx2(Fragment, { children: groups.map((group) => /* @__PURE__ */ jsxs(SidebarGroup, { children: [
826
+ group.label ? /* @__PURE__ */ jsx2(SidebarGroupLabel, { children: t(group.label) }) : null,
827
+ /* @__PURE__ */ jsx2(SidebarGroupContent, { children: /* @__PURE__ */ jsx2(SidebarMenu, { children: group.items.map((item) => {
828
+ const active2 = item.to === "/" ? pathname === "/" : pathname === item.to || pathname.startsWith(`${item.to}/`);
829
+ return /* @__PURE__ */ jsx2(SidebarMenuItem, { children: /* @__PURE__ */ jsx2(SidebarMenuButton, { asChild: true, isActive: active2, tooltip: t(item.label), children: /* @__PURE__ */ jsxs(Link, { to: item.to, children: [
830
+ item.icon ? /* @__PURE__ */ jsx2(item.icon, {}) : null,
831
+ /* @__PURE__ */ jsx2("span", { children: t(item.label) })
832
+ ] }) }) }, item.to);
833
+ }) }) })
834
+ ] }, group.label ?? "")) });
835
+ }
836
+ function AppShell() {
837
+ const t = useT("web");
838
+ const config = useAppConfig();
839
+ const session = useSession();
840
+ const status = useSessionStatus();
841
+ const user = useOptionalUser();
842
+ const router = useRouter();
843
+ const matches = useMatches();
844
+ const pathname = useRouterState({ select: (state) => state.location.pathname });
845
+ const tenantChanged = useSyncExternalStore2(subscribeTenant, isTenantChanged, () => false);
846
+ const permissions = user?.permissions;
847
+ const groups = useMemo(
848
+ () => buildMenu(Object.values(router.routesById), permissions ?? []),
849
+ [router, permissions]
850
+ );
851
+ const metas = matches.map((match) => match.staticData);
852
+ const leaf = metas.at(-1);
853
+ const required = metas.flatMap(requiredPermissions);
854
+ const allowed = hasPermissions(permissions ?? [], required);
855
+ const label = [...metas].reverse().find((meta) => meta?.menu)?.menu?.label;
856
+ const tApp = useT("app");
857
+ const pageTitle = label ? tApp(label) : void 0;
858
+ useEffect(() => {
859
+ document.title = pageTitle ? `${pageTitle} \xB7 ${config.title}` : config.title;
860
+ }, [pageTitle, config.title]);
861
+ const isPublic = leaf?.public === true;
862
+ const mustSignIn = !user && !isPublic && status.state === "signed-out";
863
+ useEffect(() => {
864
+ if (mustSignIn) void session.signIn();
865
+ }, [mustSignIn, session]);
866
+ if (!user) {
867
+ return isPublic ? /* @__PURE__ */ jsx2(Outlet, {}) : /* @__PURE__ */ jsx2(SessionScreen, {});
868
+ }
869
+ if (leaf?.layout === "none") {
870
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
871
+ allowed ? /* @__PURE__ */ jsx2(Outlet, {}) : /* @__PURE__ */ jsx2(Forbidden, {}),
872
+ tenantChanged ? /* @__PURE__ */ jsx2(TenantChanged, {}) : null
873
+ ] });
874
+ }
875
+ return /* @__PURE__ */ jsxs(SidebarProvider, { children: [
876
+ /* @__PURE__ */ jsxs(Sidebar, { collapsible: "icon", children: [
877
+ /* @__PURE__ */ jsx2(SidebarHeader, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 px-2 py-1.5", children: [
878
+ /* @__PURE__ */ jsx2("span", { className: "bg-primary text-primary-foreground flex size-7 shrink-0 items-center justify-center rounded-md text-xs font-semibold", children: config.title.slice(0, 1).toUpperCase() }),
879
+ /* @__PURE__ */ jsx2("span", { className: "truncate font-semibold group-data-[collapsible=icon]:hidden", children: config.title })
880
+ ] }) }),
881
+ /* @__PURE__ */ jsx2(SidebarContent, { children: /* @__PURE__ */ jsx2(Navigation, { groups, pathname }) }),
882
+ /* @__PURE__ */ jsx2(SidebarRail, {})
883
+ ] }),
884
+ /* @__PURE__ */ jsxs(SidebarInset, { children: [
885
+ /* @__PURE__ */ jsxs("header", { className: "bg-background sticky top-0 z-10 flex h-14 shrink-0 items-center gap-2 border-b px-4", children: [
886
+ /* @__PURE__ */ jsx2(SidebarTrigger, {}),
887
+ /* @__PURE__ */ jsx2(Separator, { orientation: "vertical", className: "mx-1 h-5" }),
888
+ /* @__PURE__ */ jsx2("span", { className: "truncate font-medium", children: pageTitle ?? config.title }),
889
+ /* @__PURE__ */ jsxs("div", { className: "ml-auto flex items-center gap-2", children: [
890
+ user.isDev ? /* @__PURE__ */ jsx2(Badge, { variant: "outline", children: t("devIdentity") }) : null,
891
+ /* @__PURE__ */ jsx2(Button, { asChild: true, variant: "ghost", size: "sm", children: /* @__PURE__ */ jsxs("a", { href: config.portalUrl, target: "platform-portal", children: [
892
+ /* @__PURE__ */ jsx2(LayoutGrid, {}),
893
+ t("apps")
894
+ ] }) }),
895
+ /* @__PURE__ */ jsx2(AccountMenu, {})
896
+ ] })
897
+ ] }),
898
+ /* @__PURE__ */ jsx2("main", { className: "flex-1 p-4 md:p-6", children: allowed ? /* @__PURE__ */ jsx2(Outlet, {}) : /* @__PURE__ */ jsx2(Forbidden, {}) })
899
+ ] }),
900
+ tenantChanged ? /* @__PURE__ */ jsx2(TenantChanged, {}) : null
901
+ ] });
902
+ }
903
+
904
+ // src/app.tsx
905
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
906
+ function defaultQueryClient() {
907
+ return new QueryClient({
908
+ defaultOptions: {
909
+ queries: {
910
+ // A 4xx will not succeed on a retry.
911
+ retry: (failureCount, error) => !(error instanceof ApiError && error.status < 500) && failureCount < 2,
912
+ staleTime: 1e4
913
+ }
914
+ }
915
+ });
916
+ }
917
+ function createApp(options) {
918
+ const config = getPlatformConfig();
919
+ const session = getSession();
920
+ const queryClient = options.queryClient ?? defaultQueryClient();
921
+ if (options.messages) registerMessages("app", options.messages);
922
+ const syncUser = () => {
923
+ const user = session.getUser();
924
+ setTimeZone(user?.timeZone);
925
+ if (user) pinTenant(user.tenantId);
926
+ };
927
+ syncUser();
928
+ session.subscribe(() => {
929
+ syncUser();
930
+ queryClient.clear();
931
+ void router.invalidate();
932
+ });
933
+ const router = createRouter({
934
+ routeTree: options.routeTree,
935
+ basepath: config.basePath,
936
+ context: { queryClient },
937
+ defaultPreload: "intent",
938
+ defaultNotFoundComponent: NotFound,
939
+ defaultErrorComponent: ErrorScreen
940
+ });
941
+ return {
942
+ config,
943
+ session,
944
+ queryClient,
945
+ router,
946
+ mount(target) {
947
+ const element = typeof target === "string" ? document.querySelector(target) : target;
948
+ if (!element) throw new Error(`createApp().mount: no element matches ${String(target)}`);
949
+ const root = createRoot(element);
950
+ root.render(
951
+ /* @__PURE__ */ jsx3(StrictMode, { children: /* @__PURE__ */ jsx3(PlatformProvider, { config, session, children: /* @__PURE__ */ jsxs2(QueryClientProvider, { client: queryClient, children: [
952
+ /* @__PURE__ */ jsx3(RouterProvider, { router }),
953
+ /* @__PURE__ */ jsx3(Toaster, {})
954
+ ] }) }) })
955
+ );
956
+ return root;
957
+ }
958
+ };
959
+ }
960
+
961
+ // src/index.ts
962
+ registerMessages2("web", { "en-US": en_US_default, "zh-CN": zh_CN_default });
963
+ export {
964
+ AUTH_CALLBACK_PATH,
965
+ AUTH_CONFIG_PATH,
966
+ ApiError,
967
+ AppShell,
968
+ Can,
969
+ ErrorScreen,
970
+ Forbidden,
971
+ NotFound,
972
+ PlatformProvider,
973
+ RETURN_TO_KEY,
974
+ TENANT_STORAGE_KEY,
975
+ apiBaseUrl,
976
+ buildMenu,
977
+ createApp,
978
+ createClient,
979
+ createDevSession,
980
+ createPlatformSession,
981
+ encodeDevToken,
982
+ getPinnedTenant,
983
+ getPlatformConfig,
984
+ getSession,
985
+ hasPermissions,
986
+ isTenantChanged,
987
+ permissionMatches,
988
+ pinTenant,
989
+ platformFetch,
990
+ readStoredTenant,
991
+ setSession,
992
+ useAppConfig,
993
+ useCan,
994
+ useOptionalUser,
995
+ useSession,
996
+ useSessionStatus,
997
+ useTenant,
998
+ useUser
999
+ };