@eminuckan/spine 0.2.0 → 0.2.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.
- package/README.md +2 -2
- package/dist/api-client/api-config.server.d.ts +40 -0
- package/dist/api-client/api-config.server.d.ts.map +1 -0
- package/dist/api-client/error-codes.d.ts +57 -0
- package/dist/api-client/error-codes.d.ts.map +1 -0
- package/dist/api-client/error-handler.d.ts +52 -0
- package/dist/api-client/error-handler.d.ts.map +1 -0
- package/dist/api-client/fetch-client.server.d.ts +29 -0
- package/dist/api-client/fetch-client.server.d.ts.map +1 -0
- package/dist/api-client/index.d.ts +11 -3
- package/dist/api-client/index.d.ts.map +1 -0
- package/dist/api-client/index.js +3 -2
- package/dist/api-client/retry-handler.d.ts +29 -0
- package/dist/api-client/retry-handler.d.ts.map +1 -0
- package/dist/api-client/server.d.ts +9 -4
- package/dist/api-client/server.d.ts.map +1 -0
- package/dist/api-client/server.js +4 -3
- package/dist/api-client/types.d.ts +121 -0
- package/dist/api-client/types.d.ts.map +1 -0
- package/dist/{api-client-Ftxqm3Ep.js → api-client-DsrxK05Z.js} +1 -1
- package/dist/{api-client-Ftxqm3Ep.js.map → api-client-DsrxK05Z.js.map} +1 -1
- package/dist/auth/auth.server.d.ts +124 -0
- package/dist/auth/auth.server.d.ts.map +1 -0
- package/dist/auth/index.d.ts +8 -2
- package/dist/auth/index.d.ts.map +1 -0
- package/dist/auth/redis-session-storage.server.d.ts +21 -0
- package/dist/auth/redis-session-storage.server.d.ts.map +1 -0
- package/dist/auth/route-protection.server.d.ts +107 -0
- package/dist/auth/route-protection.server.d.ts.map +1 -0
- package/dist/auth/server.d.ts +13 -3
- package/dist/auth/server.d.ts.map +1 -0
- package/dist/auth/server.js +3 -3
- package/dist/auth/token-refresh.server.d.ts +17 -0
- package/dist/auth/token-refresh.server.d.ts.map +1 -0
- package/dist/auth/types.d.ts +160 -0
- package/dist/auth/types.d.ts.map +1 -0
- package/dist/auth.server-BPiCtlJE.js +5 -0
- package/dist/{auth.server-C979TR6W.js → auth.server-Cx2h2qu3.js} +3 -3
- package/dist/{auth.server-C979TR6W.js.map → auth.server-Cx2h2qu3.js.map} +1 -1
- package/dist/http/response.d.ts +12 -0
- package/dist/http/response.d.ts.map +1 -0
- package/dist/identity/identity-context-provider.d.ts +19 -0
- package/dist/identity/identity-context-provider.d.ts.map +1 -0
- package/dist/identity/identity-context.server.d.ts +73 -0
- package/dist/identity/identity-context.server.d.ts.map +1 -0
- package/dist/identity/identity-store.d.ts +55 -0
- package/dist/identity/identity-store.d.ts.map +1 -0
- package/dist/identity/index.d.ts +9 -4
- package/dist/identity/index.d.ts.map +1 -0
- package/dist/identity/server.d.ts +6 -4
- package/dist/identity/server.d.ts.map +1 -0
- package/dist/identity/server.js +2 -1
- package/dist/identity/types.d.ts +91 -0
- package/dist/identity/types.d.ts.map +1 -0
- package/dist/index.d.ts +14 -12
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +6 -5
- package/dist/logging/config.d.ts +7 -0
- package/dist/logging/config.d.ts.map +1 -0
- package/dist/logging/index.d.ts +9 -3
- package/dist/logging/index.d.ts.map +1 -0
- package/dist/logging/logger.d.ts +22 -0
- package/dist/logging/logger.d.ts.map +1 -0
- package/dist/logging/types.d.ts +27 -0
- package/dist/logging/types.d.ts.map +1 -0
- package/dist/permissions/components.d.ts +48 -0
- package/dist/permissions/components.d.ts.map +1 -0
- package/dist/permissions/constants.d.ts +9 -0
- package/dist/permissions/constants.d.ts.map +1 -0
- package/dist/permissions/hooks.d.ts +47 -0
- package/dist/permissions/hooks.d.ts.map +1 -0
- package/dist/permissions/index.d.ts +28 -2
- package/dist/permissions/index.d.ts.map +1 -0
- package/dist/permissions/permission-initializer.d.ts +18 -0
- package/dist/permissions/permission-initializer.d.ts.map +1 -0
- package/dist/permissions/permission-service.d.ts +53 -0
- package/dist/permissions/permission-service.d.ts.map +1 -0
- package/dist/permissions/permission-store.d.ts +42 -0
- package/dist/permissions/permission-store.d.ts.map +1 -0
- package/dist/permissions/route-protection.server.d.ts +33 -0
- package/dist/permissions/route-protection.server.d.ts.map +1 -0
- package/dist/permissions/types.d.ts +44 -0
- package/dist/permissions/types.d.ts.map +1 -0
- package/dist/query-client/index.d.ts +8 -2
- package/dist/query-client/index.d.ts.map +1 -0
- package/dist/query-client/index.js +1 -1
- package/dist/query-client/query-config.d.ts +55 -0
- package/dist/query-client/query-config.d.ts.map +1 -0
- package/dist/query-client/types.d.ts +115 -0
- package/dist/query-client/types.d.ts.map +1 -0
- package/dist/{query-client-DRPQIKHX.js → query-client-Bpe08pk9.js} +1 -1
- package/dist/query-client-Bpe08pk9.js.map +1 -0
- package/dist/react-router/index.d.ts +9 -12
- package/dist/react-router/index.d.ts.map +1 -0
- package/dist/react-router/index.js +6 -5
- package/dist/react-router/server.d.ts +9 -18
- package/dist/react-router/server.d.ts.map +1 -0
- package/dist/react-router/server.js +13 -12
- package/dist/{redis-session-storage.server-DhufyPjd.js → redis-session-storage.server-BR_0y-QO.js} +2 -2
- package/dist/{redis-session-storage.server-DhufyPjd.js.map → redis-session-storage.server-BR_0y-QO.js.map} +1 -1
- package/dist/{server-CiSbg-9C.js → server-BHfKHKF_.js} +5 -5
- package/dist/{server-CiSbg-9C.js.map → server-BHfKHKF_.js.map} +1 -1
- package/dist/{server-C-DiVP9e.js → server-BxvRxjCK.js} +2 -2
- package/dist/{server-C-DiVP9e.js.map → server-BxvRxjCK.js.map} +1 -1
- package/dist/{server-iWm3oeCM.js → server-C3L8J7iE.js} +3 -2
- package/dist/server-C3L8J7iE.js.map +1 -0
- package/dist/{server-CNp6gjFE.js → server-CouYoZiw.js} +1 -1
- package/dist/{server-CNp6gjFE.js.map → server-CouYoZiw.js.map} +1 -1
- package/dist/server-DZmcd2Lr.js +422 -0
- package/dist/server-DZmcd2Lr.js.map +1 -0
- package/dist/server.d.ts +14 -18
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +13 -12
- package/dist/signalr/index.d.ts +8 -4
- package/dist/signalr/index.d.ts.map +1 -0
- package/dist/signalr/index.js +1 -1
- package/dist/signalr/signalr-client.d.ts +98 -0
- package/dist/signalr/signalr-client.d.ts.map +1 -0
- package/dist/signalr/types.d.ts +42 -0
- package/dist/signalr/types.d.ts.map +1 -0
- package/dist/{signalr-BJGcXc0m.js → signalr-SJ-1sIxw.js} +1 -1
- package/dist/{signalr-BJGcXc0m.js.map → signalr-SJ-1sIxw.js.map} +1 -1
- package/dist/tenant/index.d.ts +9 -3
- package/dist/tenant/index.d.ts.map +1 -0
- package/dist/tenant/server.d.ts +7 -3
- package/dist/tenant/server.d.ts.map +1 -0
- package/dist/tenant/server.js +2 -2
- package/dist/tenant/tenant-context.d.ts +45 -0
- package/dist/tenant/tenant-context.d.ts.map +1 -0
- package/dist/tenant/tenant-cookie.server.d.ts +35 -0
- package/dist/tenant/tenant-cookie.server.d.ts.map +1 -0
- package/dist/tenant/tenant-store.d.ts +58 -0
- package/dist/tenant/tenant-store.d.ts.map +1 -0
- package/dist/tenant/tenant.server.d.ts +49 -0
- package/dist/tenant/tenant.server.d.ts.map +1 -0
- package/dist/tenant/types.d.ts +51 -0
- package/dist/tenant/types.d.ts.map +1 -0
- package/dist/types-BnKaWdfe.js +8 -0
- package/dist/types-BnKaWdfe.js.map +1 -0
- package/dist/utils.d.ts +6 -0
- package/dist/utils.d.ts.map +1 -0
- package/package.json +2 -3
- package/dist/auth.server-DU-x2LPA.js +0 -5
- package/dist/index-BIJOC8Fb.d.ts +0 -272
- package/dist/index-BIJOC8Fb.d.ts.map +0 -1
- package/dist/index-Bt9XE6gj.d.ts +0 -104
- package/dist/index-Bt9XE6gj.d.ts.map +0 -1
- package/dist/index-C2hGpzGr.d.ts +0 -74
- package/dist/index-C2hGpzGr.d.ts.map +0 -1
- package/dist/index-CfQsb3l_.d.ts +0 -170
- package/dist/index-CfQsb3l_.d.ts.map +0 -1
- package/dist/index-D6RK_5vm.d.ts +0 -199
- package/dist/index-D6RK_5vm.d.ts.map +0 -1
- package/dist/index-DrttYPAj.d.ts +0 -30
- package/dist/index-DrttYPAj.d.ts.map +0 -1
- package/dist/index-geY2ynnN.d.ts +0 -141
- package/dist/index-geY2ynnN.d.ts.map +0 -1
- package/dist/index-kr8Wk7v5.d.ts +0 -1
- package/dist/query-client-DRPQIKHX.js.map +0 -1
- package/dist/server-BoeUiXSh.d.ts +0 -40
- package/dist/server-BoeUiXSh.d.ts.map +0 -1
- package/dist/server-CLbksnvg.d.ts +0 -144
- package/dist/server-CLbksnvg.d.ts.map +0 -1
- package/dist/server-CXGaRaiS.d.ts +0 -256
- package/dist/server-CXGaRaiS.d.ts.map +0 -1
- package/dist/server-DLgH3FRR.js +0 -312
- package/dist/server-DLgH3FRR.js.map +0 -1
- package/dist/server-DazqdM63.d.ts +0 -93
- package/dist/server-DazqdM63.d.ts.map +0 -1
- package/dist/server-iWm3oeCM.js.map +0 -1
- package/dist/server-zEKMDpP7.d.ts +0 -80
- package/dist/server-zEKMDpP7.d.ts.map +0 -1
- package/dist/types-BTjFzIhv.d.ts +0 -31
- package/dist/types-BTjFzIhv.d.ts.map +0 -1
- package/dist/types-DoIfDhl6.d.ts +0 -55
- package/dist/types-DoIfDhl6.d.ts.map +0 -1
- package/dist/types-DufLRY7A.d.ts +0 -164
- package/dist/types-DufLRY7A.d.ts.map +0 -1
- package/dist/types-uDrDMkCq.d.ts +0 -93
- package/dist/types-uDrDMkCq.d.ts.map +0 -1
- /package/dist/{src-D7mh9MKA.js → src-CJ2RLi94.js} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getAuthSession
|
|
1
|
+
import { getAuthSession } from "./redis-session-storage.server-BR_0y-QO.js";
|
|
2
2
|
|
|
3
3
|
//#region src/tenant/tenant-cookie.server.ts
|
|
4
4
|
const DEFAULT_TENANT_COOKIE_CONFIG = {
|
|
@@ -182,4 +182,4 @@ async function clearCurrentTenant() {
|
|
|
182
182
|
|
|
183
183
|
//#endregion
|
|
184
184
|
export { clearActiveTenant, clearCurrentTenant, configureIdentityContextFetcher, configureTenantCookie, getActiveTenant, getAvailableTenants, getCurrentTenant, getTenantFromIdentityContext, initializeTenant, resetTenantCookieConfig, setActiveTenant, setCurrentTenant };
|
|
185
|
-
//# sourceMappingURL=server-
|
|
185
|
+
//# sourceMappingURL=server-BxvRxjCK.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-C-DiVP9e.js","names":["DEFAULT_TENANT_COOKIE_CONFIG: Required<TenantCookieConfig>","tenantCookieConfig: Required<TenantCookieConfig>","request: Request","tenantId: string","config: TenantCookieConfig","identityContextFetcher: IdentityContextFetcher | null","fetcher: IdentityContextFetcher","request: Request","tenantId: string"],"sources":["../src/tenant/tenant-cookie.server.ts","../src/tenant/tenant.server.ts"],"sourcesContent":["/**\n * Tenant Cookie Server Module\n * \n * Cookie-based tenant storage.\n */\n\nexport type TenantCookieSameSite = 'Strict' | 'Lax' | 'None';\n\nexport interface TenantCookieConfig {\n name?: string;\n maxAge?: number;\n path?: string;\n secure?: boolean;\n httpOnly?: boolean;\n sameSite?: TenantCookieSameSite;\n}\n\nconst DEFAULT_TENANT_COOKIE_CONFIG: Required<TenantCookieConfig> = {\n name: '__active-org',\n maxAge: 60 * 60 * 24 * 365,\n path: '/',\n secure: process.env.NODE_ENV === 'production',\n httpOnly: false,\n sameSite: 'Lax',\n};\n\nlet tenantCookieConfig: Required<TenantCookieConfig> = {\n ...DEFAULT_TENANT_COOKIE_CONFIG,\n};\n\nfunction getTenantCookieConfig(): Required<TenantCookieConfig> {\n return tenantCookieConfig;\n}\n\n/**\n * Get active tenant from cookie\n */\nexport async function getActiveTenant(request: Request): Promise<string | null> {\n const config = getTenantCookieConfig();\n const cookies = request.headers.get('Cookie');\n if (!cookies) return null;\n\n const match = cookies.match(new RegExp(`${config.name}=([^;]+)`));\n if (!match) return null;\n\n return decodeURIComponent(match[1]);\n}\n\n/**\n * Set active tenant cookie value\n */\nexport async function setActiveTenant(tenantId: string): Promise<string> {\n const config = getTenantCookieConfig();\n const secure = config.secure ? '; Secure' : '';\n const httpOnly = config.httpOnly ? '; HttpOnly' : '';\n return `${config.name}=${encodeURIComponent(tenantId)}; Path=${config.path}${httpOnly}; SameSite=${config.sameSite}; Max-Age=${config.maxAge}${secure}`;\n}\n\n/**\n * Clear active tenant cookie value\n */\nexport async function clearActiveTenant(): Promise<string> {\n const config = getTenantCookieConfig();\n const secure = config.secure ? '; Secure' : '';\n const httpOnly = config.httpOnly ? '; HttpOnly' : '';\n return `${config.name}=; Path=${config.path}${httpOnly}; SameSite=${config.sameSite}; Max-Age=0${secure}`;\n}\n\n/**\n * Configure tenant cookie name\n */\nexport function configureTenantCookie(config: TenantCookieConfig): void {\n tenantCookieConfig = {\n ...tenantCookieConfig,\n ...config,\n };\n}\n\n/**\n * Reset tenant cookie config back to defaults.\n */\nexport function resetTenantCookieConfig(): void {\n tenantCookieConfig = {\n ...DEFAULT_TENANT_COOKIE_CONFIG,\n };\n}\n","/**\n * Tenant Server Module\n * \n * Server-side tenant management.\n */\n\nimport { getAuthSession } from '../auth/redis-session-storage.server';\nimport { getActiveTenant, setActiveTenant, clearActiveTenant } from './tenant-cookie.server';\n\n/**\n * Identity context fetcher type (to avoid circular dependency)\n */\nexport type IdentityContextFetcher = (request: Request) => Promise<{\n memberships?: Array<{ tenantId: string }>;\n} | null>;\n\nlet identityContextFetcher: IdentityContextFetcher | null = null;\n\n/**\n * Configure identity context fetcher\n */\nexport function configureIdentityContextFetcher(fetcher: IdentityContextFetcher): void {\n identityContextFetcher = fetcher;\n}\n\n/**\n * Get current active tenant from cookie\n */\nexport async function getCurrentTenant(request: Request): Promise<string | null> {\n try {\n const tenantFromCookie = await getActiveTenant(request);\n if (tenantFromCookie) {\n return tenantFromCookie;\n }\n return null;\n } catch (error) {\n console.error('Error getting current tenant:', error);\n return null;\n }\n}\n\n/**\n * Get tenant from identity context\n */\nexport async function getTenantFromIdentityContext(request: Request): Promise<string | null> {\n try {\n const sessionData = await getAuthSession(request);\n if (!sessionData?.user?.sub) {\n return null;\n }\n\n if (!identityContextFetcher) {\n console.warn('Identity context fetcher not configured');\n return null;\n }\n\n const context = await identityContextFetcher(request);\n\n if (context?.memberships && context.memberships.length > 0) {\n return context.memberships[0].tenantId;\n }\n\n return null;\n } catch (error) {\n console.error('Error getting tenant from identity context:', error);\n return null;\n }\n}\n\n/**\n * Get available tenants from identity context\n */\nexport async function getAvailableTenants(request: Request): Promise<string[]> {\n try {\n const sessionData = await getAuthSession(request);\n if (!sessionData?.user?.sub) {\n return [];\n }\n\n if (!identityContextFetcher) {\n console.warn('Identity context fetcher not configured');\n return [];\n }\n\n const context = await identityContextFetcher(request);\n\n if (context?.memberships && context.memberships.length > 0) {\n return context.memberships.map((m) => m.tenantId);\n }\n\n return [];\n } catch (error) {\n console.error('Error getting available tenants:', error);\n return [];\n }\n}\n\n/**\n * Set current active tenant\n */\nexport async function setCurrentTenant(\n request: Request,\n tenantId: string\n): Promise<{ headers: Headers; success: boolean; error?: string }> {\n try {\n const sessionData = await getAuthSession(request);\n\n if (!sessionData.user) {\n return { headers: new Headers(), success: false, error: 'No active session' };\n }\n\n const cookieValue = await setActiveTenant(tenantId);\n const headers = new Headers();\n headers.append('Set-Cookie', cookieValue);\n\n return { headers, success: true };\n } catch (error) {\n console.error('Failed to set current tenant:', error);\n return {\n headers: new Headers(),\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n}\n\n/**\n * Initialize tenant on first login\n */\nexport async function initializeTenant(\n request: Request\n): Promise<{ headers: Headers; tenantId: string } | null> {\n try {\n const sessionData = await getAuthSession(request);\n if (!sessionData?.user) {\n return null;\n }\n\n // Check if tenant is already set in cookie\n const currentTenant = await getCurrentTenant(request);\n if (currentTenant) {\n return null;\n }\n\n // Get tenant from identity context\n const tenantId = await getTenantFromIdentityContext(request);\n\n if (tenantId) {\n const cookieValue = await setActiveTenant(tenantId);\n const headers = new Headers();\n headers.append('Set-Cookie', cookieValue);\n return { headers, tenantId };\n }\n\n return null;\n } catch (error) {\n console.error('Failed to initialize tenant:', error);\n return null;\n }\n}\n\n/**\n * Clear current tenant\n */\nexport async function clearCurrentTenant(): Promise<Headers> {\n const cookieValue = await clearActiveTenant();\n const headers = new Headers();\n headers.append('Set-Cookie', cookieValue);\n return headers;\n}\n"],"mappings":";;;AAiBA,MAAMA,+BAA6D;CACjE,MAAM;CACN,QAAQ,KAAK,KAAK,KAAK;CACvB,MAAM;CACN,QAAQ,QAAQ,IAAI,aAAa;CACjC,UAAU;CACV,UAAU;AACX;AAED,IAAIC,qBAAmD,EACrD,GAAG,6BACJ;AAED,SAAS,wBAAsD;AAC7D,QAAO;AACR;;;;AAKD,eAAsB,gBAAgBC,SAA0C;CAC9E,MAAM,SAAS,uBAAuB;CACtC,MAAM,UAAU,QAAQ,QAAQ,IAAI,SAAS;AAC7C,MAAK,QAAS,QAAO;CAErB,MAAM,QAAQ,QAAQ,MAAM,IAAI,QAAQ,EAAE,OAAO,KAAK,WAAW;AACjE,MAAK,MAAO,QAAO;AAEnB,QAAO,mBAAmB,MAAM,GAAG;AACpC;;;;AAKD,eAAsB,gBAAgBC,UAAmC;CACvE,MAAM,SAAS,uBAAuB;CACtC,MAAM,SAAS,OAAO,SAAS,aAAa;CAC5C,MAAM,WAAW,OAAO,WAAW,eAAe;AAClD,SAAQ,EAAE,OAAO,KAAK,GAAG,mBAAmB,SAAS,CAAC,SAAS,OAAO,KAAK,EAAE,SAAS,aAAa,OAAO,SAAS,YAAY,OAAO,OAAO,EAAE,OAAO;AACvJ;;;;AAKD,eAAsB,oBAAqC;CACzD,MAAM,SAAS,uBAAuB;CACtC,MAAM,SAAS,OAAO,SAAS,aAAa;CAC5C,MAAM,WAAW,OAAO,WAAW,eAAe;AAClD,SAAQ,EAAE,OAAO,KAAK,UAAU,OAAO,KAAK,EAAE,SAAS,aAAa,OAAO,SAAS,aAAa,OAAO;AACzG;;;;AAKD,SAAgB,sBAAsBC,QAAkC;AACtE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UACiE;AACjE,KAAI;EACF,MAAM,cAAc,MAAM,eAAe,QAAQ;AAEjD,OAAK,YAAY,KACf,QAAO;GAAE,SAAS,IAAI;GAAW,SAAS;GAAO,OAAO;EAAqB;EAG/E,MAAM,cAAc,MAAM,gBAAgB,SAAS;EACnD,MAAM,UAAU,IAAI;AACpB,UAAQ,OAAO,cAAc,YAAY;AAEzC,SAAO;GAAE;GAAS,SAAS;EAAM;CAClC,SAAQ,OAAO;AACd,UAAQ,MAAM,iCAAiC,MAAM;AACrD,SAAO;GACL,SAAS,IAAI;GACb,SAAS;GACT,OAAO,iBAAiB,QAAQ,MAAM,UAAU;EACjD;CACF;AACF;;;;AAKD,eAAsB,iBACpBD,SACwD;AACxD,KAAI;EACF,MAAM,cAAc,MAAM,eAAe,QAAQ;AACjD,OAAK,aAAa,KAChB,QAAO;EAIT,MAAM,gBAAgB,MAAM,iBAAiB,QAAQ;AACrD,MAAI,cACF,QAAO;EAIT,MAAM,WAAW,MAAM,6BAA6B,QAAQ;AAE5D,MAAI,UAAU;GACZ,MAAM,cAAc,MAAM,gBAAgB,SAAS;GACnD,MAAM,UAAU,IAAI;AACpB,WAAQ,OAAO,cAAc,YAAY;AACzC,UAAO;IAAE;IAAS;GAAU;EAC7B;AAED,SAAO;CACR,SAAQ,OAAO;AACd,UAAQ,MAAM,gCAAgC,MAAM;AACpD,SAAO;CACR;AACF;;;;AAKD,eAAsB,qBAAuC;CAC3D,MAAM,cAAc,MAAM,mBAAmB;CAC7C,MAAM,UAAU,IAAI;AACpB,SAAQ,OAAO,cAAc,YAAY;AACzC,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"server-BxvRxjCK.js","names":["DEFAULT_TENANT_COOKIE_CONFIG: Required<TenantCookieConfig>","tenantCookieConfig: Required<TenantCookieConfig>","request: Request","tenantId: string","config: TenantCookieConfig","identityContextFetcher: IdentityContextFetcher | null","fetcher: IdentityContextFetcher","request: Request","tenantId: string"],"sources":["../src/tenant/tenant-cookie.server.ts","../src/tenant/tenant.server.ts"],"sourcesContent":["/**\n * Tenant Cookie Server Module\n * \n * Cookie-based tenant storage.\n */\n\nexport type TenantCookieSameSite = 'Strict' | 'Lax' | 'None';\n\nexport interface TenantCookieConfig {\n name?: string;\n maxAge?: number;\n path?: string;\n secure?: boolean;\n httpOnly?: boolean;\n sameSite?: TenantCookieSameSite;\n}\n\nconst DEFAULT_TENANT_COOKIE_CONFIG: Required<TenantCookieConfig> = {\n name: '__active-org',\n maxAge: 60 * 60 * 24 * 365,\n path: '/',\n secure: process.env.NODE_ENV === 'production',\n httpOnly: false,\n sameSite: 'Lax',\n};\n\nlet tenantCookieConfig: Required<TenantCookieConfig> = {\n ...DEFAULT_TENANT_COOKIE_CONFIG,\n};\n\nfunction getTenantCookieConfig(): Required<TenantCookieConfig> {\n return tenantCookieConfig;\n}\n\n/**\n * Get active tenant from cookie\n */\nexport async function getActiveTenant(request: Request): Promise<string | null> {\n const config = getTenantCookieConfig();\n const cookies = request.headers.get('Cookie');\n if (!cookies) return null;\n\n const match = cookies.match(new RegExp(`${config.name}=([^;]+)`));\n if (!match) return null;\n\n return decodeURIComponent(match[1]);\n}\n\n/**\n * Set active tenant cookie value\n */\nexport async function setActiveTenant(tenantId: string): Promise<string> {\n const config = getTenantCookieConfig();\n const secure = config.secure ? '; Secure' : '';\n const httpOnly = config.httpOnly ? '; HttpOnly' : '';\n return `${config.name}=${encodeURIComponent(tenantId)}; Path=${config.path}${httpOnly}; SameSite=${config.sameSite}; Max-Age=${config.maxAge}${secure}`;\n}\n\n/**\n * Clear active tenant cookie value\n */\nexport async function clearActiveTenant(): Promise<string> {\n const config = getTenantCookieConfig();\n const secure = config.secure ? '; Secure' : '';\n const httpOnly = config.httpOnly ? '; HttpOnly' : '';\n return `${config.name}=; Path=${config.path}${httpOnly}; SameSite=${config.sameSite}; Max-Age=0${secure}`;\n}\n\n/**\n * Configure tenant cookie name\n */\nexport function configureTenantCookie(config: TenantCookieConfig): void {\n tenantCookieConfig = {\n ...tenantCookieConfig,\n ...config,\n };\n}\n\n/**\n * Reset tenant cookie config back to defaults.\n */\nexport function resetTenantCookieConfig(): void {\n tenantCookieConfig = {\n ...DEFAULT_TENANT_COOKIE_CONFIG,\n };\n}\n","/**\n * Tenant Server Module\n * \n * Server-side tenant management.\n */\n\nimport { getAuthSession } from '../auth/redis-session-storage.server';\nimport { getActiveTenant, setActiveTenant, clearActiveTenant } from './tenant-cookie.server';\n\n/**\n * Identity context fetcher type (to avoid circular dependency)\n */\nexport type IdentityContextFetcher = (request: Request) => Promise<{\n memberships?: Array<{ tenantId: string }>;\n} | null>;\n\nlet identityContextFetcher: IdentityContextFetcher | null = null;\n\n/**\n * Configure identity context fetcher\n */\nexport function configureIdentityContextFetcher(fetcher: IdentityContextFetcher): void {\n identityContextFetcher = fetcher;\n}\n\n/**\n * Get current active tenant from cookie\n */\nexport async function getCurrentTenant(request: Request): Promise<string | null> {\n try {\n const tenantFromCookie = await getActiveTenant(request);\n if (tenantFromCookie) {\n return tenantFromCookie;\n }\n return null;\n } catch (error) {\n console.error('Error getting current tenant:', error);\n return null;\n }\n}\n\n/**\n * Get tenant from identity context\n */\nexport async function getTenantFromIdentityContext(request: Request): Promise<string | null> {\n try {\n const sessionData = await getAuthSession(request);\n if (!sessionData?.user?.sub) {\n return null;\n }\n\n if (!identityContextFetcher) {\n console.warn('Identity context fetcher not configured');\n return null;\n }\n\n const context = await identityContextFetcher(request);\n\n if (context?.memberships && context.memberships.length > 0) {\n return context.memberships[0].tenantId;\n }\n\n return null;\n } catch (error) {\n console.error('Error getting tenant from identity context:', error);\n return null;\n }\n}\n\n/**\n * Get available tenants from identity context\n */\nexport async function getAvailableTenants(request: Request): Promise<string[]> {\n try {\n const sessionData = await getAuthSession(request);\n if (!sessionData?.user?.sub) {\n return [];\n }\n\n if (!identityContextFetcher) {\n console.warn('Identity context fetcher not configured');\n return [];\n }\n\n const context = await identityContextFetcher(request);\n\n if (context?.memberships && context.memberships.length > 0) {\n return context.memberships.map((m) => m.tenantId);\n }\n\n return [];\n } catch (error) {\n console.error('Error getting available tenants:', error);\n return [];\n }\n}\n\n/**\n * Set current active tenant\n */\nexport async function setCurrentTenant(\n request: Request,\n tenantId: string\n): Promise<{ headers: Headers; success: boolean; error?: string }> {\n try {\n const sessionData = await getAuthSession(request);\n\n if (!sessionData.user) {\n return { headers: new Headers(), success: false, error: 'No active session' };\n }\n\n const cookieValue = await setActiveTenant(tenantId);\n const headers = new Headers();\n headers.append('Set-Cookie', cookieValue);\n\n return { headers, success: true };\n } catch (error) {\n console.error('Failed to set current tenant:', error);\n return {\n headers: new Headers(),\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n}\n\n/**\n * Initialize tenant on first login\n */\nexport async function initializeTenant(\n request: Request\n): Promise<{ headers: Headers; tenantId: string } | null> {\n try {\n const sessionData = await getAuthSession(request);\n if (!sessionData?.user) {\n return null;\n }\n\n // Check if tenant is already set in cookie\n const currentTenant = await getCurrentTenant(request);\n if (currentTenant) {\n return null;\n }\n\n // Get tenant from identity context\n const tenantId = await getTenantFromIdentityContext(request);\n\n if (tenantId) {\n const cookieValue = await setActiveTenant(tenantId);\n const headers = new Headers();\n headers.append('Set-Cookie', cookieValue);\n return { headers, tenantId };\n }\n\n return null;\n } catch (error) {\n console.error('Failed to initialize tenant:', error);\n return null;\n }\n}\n\n/**\n * Clear current tenant\n */\nexport async function clearCurrentTenant(): Promise<Headers> {\n const cookieValue = await clearActiveTenant();\n const headers = new Headers();\n headers.append('Set-Cookie', cookieValue);\n return headers;\n}\n"],"mappings":";;;AAiBA,MAAMA,+BAA6D;CACjE,MAAM;CACN,QAAQ,KAAK,KAAK,KAAK;CACvB,MAAM;CACN,QAAQ,QAAQ,IAAI,aAAa;CACjC,UAAU;CACV,UAAU;AACX;AAED,IAAIC,qBAAmD,EACrD,GAAG,6BACJ;AAED,SAAS,wBAAsD;AAC7D,QAAO;AACR;;;;AAKD,eAAsB,gBAAgBC,SAA0C;CAC9E,MA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AAM,eAAe,QAAQ;AACjD,OAAK,aAAa,KAChB,QAAO;EAIT,MAAM,gBAAgB,MAAM,iBAAiB,QAAQ;AACrD,MAAI,cACF,QAAO;EAIT,MAAM,WAAW,MAAM,6BAA6B,QAAQ;AAE5D,MAAI,UAAU;GACZ,MAAM,cAAc,MAAM,gBAAgB,SAAS;GACnD,MAAM,UAAU,IAAI;AACpB,WAAQ,OAAO,cAAc,YAAY;AACzC,UAAO;IAAE;IAAS;GAAU;EAC7B;AAED,SAAO;CACR,SAAQ,OAAO;AACd,UAAQ,MAAM,gCAAgC,MAAM;AACpD,SAAO;CACR;AACF;;;;AAKD,eAAsB,qBAAuC;CAC3D,MAAM,cAAc,MAAM,mBAAmB;CAC7C,MAAM,UAAU,IAAI;AACpB,SAAQ,OAAO,cAAc,YAAY;AACzC,QAAO;AACR"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { logger } from "./logging-_h2mi3L9.js";
|
|
2
|
+
import { isApiClientError } from "./types-BnKaWdfe.js";
|
|
2
3
|
|
|
3
4
|
//#region src/identity/identity-context.server.ts
|
|
4
5
|
let identityAPIFetcher = null;
|
|
@@ -27,7 +28,7 @@ async function fetchIdentityContext(request) {
|
|
|
27
28
|
return context;
|
|
28
29
|
} catch (error) {
|
|
29
30
|
logger.error("Failed to fetch identity context", error instanceof Error ? error : void 0);
|
|
30
|
-
if (error &&
|
|
31
|
+
if (isApiClientError(error) && error.response?.status === 404 && error.problemDetails?.title === "CurrentUserMissing") {
|
|
31
32
|
logger.error("CurrentUserMissing error detected - session is invalid");
|
|
32
33
|
const invalidSessionError = new Error("INVALID_SESSION");
|
|
33
34
|
invalidSessionError.isInvalidSession = true;
|
|
@@ -142,4 +143,4 @@ function updateContextVersion(userId, newVersion) {
|
|
|
142
143
|
|
|
143
144
|
//#endregion
|
|
144
145
|
export { clearIdentityContextCache, configureIdentityAPIFetcher, configurePermissionFetcher, contextToUserInfo, fetchIdentityContext, fetchUserPermissions, getIdentityContext, hasContextVersionChanged, updateContextVersion };
|
|
145
|
-
//# sourceMappingURL=server-
|
|
146
|
+
//# sourceMappingURL=server-C3L8J7iE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-C3L8J7iE.js","names":["identityAPIFetcher: IdentityAPIFetcher | null","fetcher: IdentityAPIFetcher","request: Request","error: unknown","userId: string","userId?: string","permissionFetcher: PermissionFetcher | null","fetcher: PermissionFetcher","tenantId: string","context: IdentityContextData","options: ContextToUserInfoOptions","permissions: string[]","newVersion: number"],"sources":["../src/identity/identity-context.server.ts"],"sourcesContent":["/**\n * Identity Context Server Module\n * \n * Server-side identity context management.\n */\n\nimport type { AddressData, IdentityContextData, TenantMembership } from './types';\nimport { isApiClientError } from '../api-client/types';\nimport { logger } from '../logging';\n\n/**\n * Identity API fetcher type (to avoid coupling with specific API client)\n */\nexport type IdentityAPIFetcher = (request: Request) => Promise<IdentityContextData>;\n\nlet identityAPIFetcher: IdentityAPIFetcher | null = null;\n\n/**\n * Configure identity API fetcher\n */\nexport function configureIdentityAPIFetcher(fetcher: IdentityAPIFetcher): void {\n identityAPIFetcher = fetcher;\n}\n\n// In-memory cache for identity context\nconst contextCache = new Map<\n string,\n {\n context: IdentityContextData;\n timestamp: number;\n version: number;\n }\n>();\n\nconst CONTEXT_CACHE_TTL = 5 * 60 * 1000; // 5 minutes\n\n/**\n * Fetch identity context from backend\n */\nexport async function fetchIdentityContext(request: Request): Promise<IdentityContextData> {\n if (!identityAPIFetcher) {\n throw new Error('Identity API fetcher not configured. Call configureIdentityAPIFetcher first.');\n }\n\n try {\n logger.info('Fetching identity context');\n const context = await identityAPIFetcher(request);\n \n logger.debug('Identity context fetched', {\n hasAnyMembership: context.hasAnyMembership,\n hasSubscription: context.hasSubscription,\n isOnboarded: context.isOnboarded,\n membershipCount: context.memberships?.length || 0,\n });\n\n return context;\n } catch (error: unknown) {\n logger.error('Failed to fetch identity context', error instanceof Error ? error : undefined);\n\n // Check if this is a CurrentUserMissing error\n if (isApiClientError(error) && error.response?.status === 404 && error.problemDetails?.title === 'CurrentUserMissing') {\n logger.error('CurrentUserMissing error detected - session is invalid');\n const invalidSessionError = new Error('INVALID_SESSION');\n (invalidSessionError as Error & { isInvalidSession: boolean }).isInvalidSession = true;\n throw invalidSessionError;\n }\n\n throw error;\n }\n}\n\n/**\n * Get cached identity context or fetch fresh if needed\n */\nexport async function getIdentityContext(\n request: Request,\n userId: string,\n forceRefresh = false\n): Promise<IdentityContextData> {\n const cacheKey = userId;\n const cached = contextCache.get(cacheKey);\n const now = Date.now();\n\n // Return cached if valid and not forcing refresh\n if (!forceRefresh && cached && now - cached.timestamp < CONTEXT_CACHE_TTL) {\n logger.debug('Using cached identity context for user', { userId });\n return cached.context;\n }\n\n // Fetch fresh context\n const context = await fetchIdentityContext(request);\n\n // Cache the result\n contextCache.set(cacheKey, {\n context,\n timestamp: now,\n version: context.contextVersion ?? 0,\n });\n\n logger.debug('Cached fresh identity context for user', { userId });\n return context;\n}\n\n/**\n * Clear identity context cache for user\n */\nexport function clearIdentityContextCache(userId?: string): void {\n if (userId) {\n contextCache.delete(userId);\n logger.debug('Cleared identity context cache for user', { userId });\n } else {\n contextCache.clear();\n logger.debug('Cleared all identity context cache');\n }\n}\n\n/**\n * Permission fetcher type\n */\nexport type PermissionFetcher = (request: Request, tenantId: string) => Promise<string[]>;\n\nlet permissionFetcher: PermissionFetcher | null = null;\n\n/**\n * Configure permission fetcher\n */\nexport function configurePermissionFetcher(fetcher: PermissionFetcher): void {\n permissionFetcher = fetcher;\n}\n\n/**\n * Fetch user permissions for a specific tenant\n */\nexport async function fetchUserPermissions(request: Request, tenantId: string): Promise<string[]> {\n if (!tenantId) {\n logger.warn('No tenant ID provided, skipping permission fetch');\n return [];\n }\n\n if (!permissionFetcher) {\n throw new Error('Permission fetcher not configured. Call configurePermissionFetcher first.');\n }\n\n try {\n return await permissionFetcher(request, tenantId);\n } catch (error) {\n logger.error('Failed to fetch user permissions', error instanceof Error ? error : undefined);\n return [];\n }\n}\n\nexport interface UserContextInfo {\n tenants: string[];\n memberships: TenantMembership[];\n currentTenant?: string;\n isOnboarded: boolean;\n permissions: string[];\n hasSubscription: boolean;\n userId?: string;\n email?: string;\n firstName?: string | null;\n lastName?: string | null;\n displayName?: string | null;\n profileImageUrl?: string | null;\n phoneNumber?: string | null;\n timeZone?: string;\n addresses?: AddressData[];\n hasOwnerMembership: boolean;\n}\n\nexport interface ContextToUserInfoOptions {\n currentTenant?: string | null;\n request?: Request;\n}\n\n/**\n * Convert raw identity context into a tenant-aware user info shape.\n */\nexport async function contextToUserInfo(\n context: IdentityContextData,\n options: ContextToUserInfoOptions = {}\n): Promise<UserContextInfo> {\n const memberships = context.memberships || [];\n const tenants = memberships.map((membership) => membership.tenantId);\n const resolvedCurrentTenant =\n options.currentTenant && tenants.includes(options.currentTenant)\n ? options.currentTenant\n : tenants[0] || undefined;\n\n let permissions: string[] = [];\n if (resolvedCurrentTenant && options.request) {\n permissions = await fetchUserPermissions(options.request, resolvedCurrentTenant);\n }\n\n return {\n tenants,\n memberships,\n currentTenant: resolvedCurrentTenant,\n isOnboarded: context.isOnboarded ?? false,\n permissions,\n hasSubscription: context.hasSubscription ?? false,\n userId: context.userId,\n email: context.email,\n firstName: context.firstName,\n lastName: context.lastName,\n displayName: context.displayName,\n profileImageUrl: context.profileImageUrl,\n phoneNumber: context.phoneNumber,\n timeZone: context.timeZone,\n addresses: context.addresses,\n hasOwnerMembership: context.hasOwnerMembership ?? false,\n };\n}\n\n/**\n * Check if a cached context version differs from the latest version.\n */\nexport function hasContextVersionChanged(userId: string, newVersion: number): boolean {\n const cached = contextCache.get(userId);\n return !cached || cached.version !== newVersion;\n}\n\n/**\n * Mark a cached identity context as stale after a version change.\n */\nexport function updateContextVersion(userId: string, newVersion: number): void {\n const cached = contextCache.get(userId);\n if (!cached) return;\n\n cached.version = newVersion;\n cached.timestamp = 0;\n logger.debug('Marked identity context as stale for user', {\n userId,\n version: newVersion,\n });\n}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Q,UAAU,OAAO,YAAY;AACtC;;;;AAKD,SAAgB,qBAAqBR,QAAgBQ,YAA0B;CAC7E,MAAM,SAAS,aAAa,IAAI,OAAO;AACvC,MAAK,OAAQ;AAEb,QAAO,UAAU;AACjB,QAAO,YAAY;AACnB,QAAO,MAAM,6CAA6C;EACxD;EACA,SAAS;CACV,EAAC;AACH"}
|
|
@@ -75,4 +75,4 @@ function withPermission(permission, loader, options) {
|
|
|
75
75
|
|
|
76
76
|
//#endregion
|
|
77
77
|
export { checkPermission, configurePermissionRouteProtection, requirePermission, resetPermissionRouteProtection, withPermission };
|
|
78
|
-
//# sourceMappingURL=server-
|
|
78
|
+
//# sourceMappingURL=server-CouYoZiw.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-
|
|
1
|
+
{"version":3,"file":"server-CouYoZiw.js","names":["details: ForbiddenPermissionDetails","permissionRouteProtectionConfig: PermissionRouteProtectionConfig","config: PermissionRouteProtectionConfig","request: Request","permission: PermissionCode | PermissionCode[]","options: PermissionCheckOptions","loader: (args: any) => Promise<TLoaderData>","options?: PermissionCheckOptions","args: any"],"sources":["../src/permissions/route-protection.server.ts"],"sourcesContent":["import { PermissionChecker } from './permission-service';\nimport type { PermissionCheckOptions, PermissionCode } from './types';\n\nexport interface PermissionRouteSession {\n user?: {\n sub?: string;\n email?: string | null;\n } | null;\n accessToken?: string | null;\n}\n\nexport interface PermissionRouteContext {\n permissions: PermissionCode[];\n currentTenant?: string | null;\n}\n\nexport interface ForbiddenPermissionDetails {\n request: Request;\n permission: PermissionCode | PermissionCode[];\n permissionsToCheck: PermissionCode[];\n missingPermissions?: PermissionCode[];\n options: PermissionCheckOptions;\n session: PermissionRouteSession;\n context: PermissionRouteContext;\n}\n\nexport interface PermissionRouteProtectionConfig {\n getSession?: (request: Request) => Promise<PermissionRouteSession>;\n resolveContext?: (\n request: Request,\n session: PermissionRouteSession\n ) => Promise<PermissionRouteContext>;\n createUnauthorizedResponse?: (\n request: Request,\n session: PermissionRouteSession\n ) => Response;\n createForbiddenResponse?: (details: ForbiddenPermissionDetails) => Response;\n}\n\nconst DEFAULT_UNAUTHORIZED_RESPONSE = () =>\n new Response('Unauthorized', {\n status: 401,\n statusText: 'You must be logged in to access this resource',\n });\n\nconst DEFAULT_FORBIDDEN_RESPONSE = (details: ForbiddenPermissionDetails) => {\n const message =\n process.env.NODE_ENV === 'development'\n ? `Missing permissions: ${details.missingPermissions?.join(', ')}`\n : \"You don't have permission to access this resource\";\n\n return new Response(message, {\n status: 403,\n statusText: 'Forbidden',\n });\n};\n\nlet permissionRouteProtectionConfig: PermissionRouteProtectionConfig = {};\n\nfunction getPermissionRouteProtectionConfig(): Required<PermissionRouteProtectionConfig> {\n if (!permissionRouteProtectionConfig.getSession) {\n throw new Error(\n 'Permission route protection session getter not configured. Call configurePermissionRouteProtection first.'\n );\n }\n\n if (!permissionRouteProtectionConfig.resolveContext) {\n throw new Error(\n 'Permission route protection context resolver not configured. Call configurePermissionRouteProtection first.'\n );\n }\n\n return {\n getSession: permissionRouteProtectionConfig.getSession,\n resolveContext: permissionRouteProtectionConfig.resolveContext,\n createUnauthorizedResponse:\n permissionRouteProtectionConfig.createUnauthorizedResponse || DEFAULT_UNAUTHORIZED_RESPONSE,\n createForbiddenResponse:\n permissionRouteProtectionConfig.createForbiddenResponse || DEFAULT_FORBIDDEN_RESPONSE,\n };\n}\n\nexport function configurePermissionRouteProtection(\n config: PermissionRouteProtectionConfig\n): void {\n permissionRouteProtectionConfig = {\n ...permissionRouteProtectionConfig,\n ...config,\n };\n}\n\nexport function resetPermissionRouteProtection(): void {\n permissionRouteProtectionConfig = {};\n}\n\nasync function getPermissionRouteState(request: Request): Promise<{\n config: Required<PermissionRouteProtectionConfig>;\n session: PermissionRouteSession;\n context: PermissionRouteContext;\n}> {\n const config = getPermissionRouteProtectionConfig();\n const session = await config.getSession(request);\n const context = await config.resolveContext(request, session);\n\n return {\n config,\n session,\n context,\n };\n}\n\nexport async function requirePermission(\n request: Request,\n permission: PermissionCode | PermissionCode[],\n options: PermissionCheckOptions = {}\n): Promise<void> {\n const { config, session, context } = await getPermissionRouteState(request);\n\n if (!session.user || !session.accessToken) {\n throw config.createUnauthorizedResponse(request, session);\n }\n\n const checker = new PermissionChecker(context.permissions || []);\n const permissionsToCheck = Array.isArray(permission) ? permission : [permission];\n const result = checker.hasPermissions(permissionsToCheck, options);\n\n if (!result.hasPermission) {\n throw config.createForbiddenResponse({\n request,\n permission,\n permissionsToCheck,\n missingPermissions: result.missingPermissions,\n options,\n session,\n context,\n });\n }\n}\n\nexport async function checkPermission(\n request: Request,\n permission: PermissionCode | PermissionCode[],\n options: PermissionCheckOptions = {}\n): Promise<boolean> {\n try {\n await requirePermission(request, permission, options);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function withPermission<TLoaderData>(\n permission: PermissionCode | PermissionCode[],\n loader: (args: any) => Promise<TLoaderData>,\n options?: PermissionCheckOptions\n) {\n return async (args: any): Promise<TLoaderData> => {\n await requirePermission(args.request, permission, options);\n return loader(args);\n };\n}\n"],"mappings":";;;AAuCA,MAAM,gCAAgC,MACpC,IAAI,SAAS,gBAAgB;CAC3B,QAAQ;CACR,YAAY;AACb;AAEH,MAAM,6BAA6B,CAACA,YAAwC;CAC1E,MAAM,UACJ,QAAQ,IAAI,aAAa,iBACpB,uBAAuB,QAAQ,oBAAoB,KAAK,KAAK,CAAC,IAC/D;AAEN,QAAO,IAAI,SAAS,SAAS;EAC3B,QAAQ;EACR,YAAY;CACb;AACF;AAED,IAAIC,kCAAmE,CAAE;AAEzE,SAAS,qCAAgF;AACvF,MAAK,gCAAgC,WACnC,OAAM,IAAI,MACR;AAIJ,MAAK,gCAAgC,eACnC,OAAM,IAAI,MACR;AAIJ,QAAO;EACL,YAAY,gCAAgC;EAC5C,gBAAgB,gCAAgC;EAChD,4BACE,gCAAgC,8BAA8B;EAChE,yBACE,gCAAgC,2BAA2B;CAC9D;AACF;AAED,SAAgB,mCACdC,QACM;AACN,mCAAkC;EAChC,GAAG;EACH,GAAG;CACJ;AACF;AAED,SAAgB,iCAAuC;AACrD,mCAAkC,CAAE;AACrC;AAED,eAAe,wBAAwBC,SAIpC;CACD,MAAM,SAAS,oCAAoC;CACnD,MAAM,UAAU,MAAM,OAAO,WAAW,QAAQ;CAChD,MAAM,UAAU,MAAM,OAAO,eAAe,SAAS,QAAQ;AAE7D,QAAO;EACL;EACA;EACA;CACD;AACF;AAED,eAAsB,kBACpBA,SACAC,YACAC,UAAkC,CAAE,GACrB;CACf,MAAM,EAAE,QAAQ,SAAS,SAAS,GAAG,MAAM,wBAAwB,QAAQ;AAE3E,MAAK,QAAQ,SAAS,QAAQ,YAC5B,OAAM,OAAO,2BAA2B,SAAS,QAAQ;CAG3D,MAAM,UAAU,IAAI,kBAAkB,QAAQ,eAAe,CAAE;CAC/D,MAAM,qBAAqB,MAAM,QAAQ,WAAW,GAAG,aAAa,CAAC,UAAW;CAChF,MAAM,SAAS,QAAQ,eAAe,oBAAoB,QAAQ;AAElE,MAAK,OAAO,cACV,OAAM,OAAO,wBAAwB;EACnC;EACA;EACA;EACA,oBAAoB,OAAO;EAC3B;EACA;EACA;CACD,EAAC;AAEL;AAED,eAAsB,gBACpBF,SACAC,YACAC,UAAkC,CAAE,GAClB;AAClB,KAAI;AACF,QAAM,kBAAkB,SAAS,YAAY,QAAQ;AACrD,SAAO;CACR,QAAO;AACN,SAAO;CACR;AACF;AAED,SAAgB,eACdD,YACAE,QACAC,SACA;AACA,QAAO,OAAOC,SAAoC;AAChD,QAAM,kBAAkB,KAAK,SAAS,YAAY,QAAQ;AAC1D,SAAO,OAAO,KAAK;CACpB;AACF"}
|
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
import { isApiClientError } from "./types-BnKaWdfe.js";
|
|
2
|
+
import { calculateBackoffDelay, fetchWithTimeout, isRetryableError } from "./api-client-DsrxK05Z.js";
|
|
3
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
|
+
|
|
5
|
+
//#region src/api-client/api-config.server.ts
|
|
6
|
+
/**
|
|
7
|
+
* Base URL Configuration
|
|
8
|
+
* Single unified base URL for all API operations
|
|
9
|
+
*/
|
|
10
|
+
const DEFAULT_API_BASE_URL = process.env.API_BASE_URL || "https://localhost:5001";
|
|
11
|
+
/**
|
|
12
|
+
* Default Headers
|
|
13
|
+
* Applied to all API requests
|
|
14
|
+
*/
|
|
15
|
+
const DEFAULT_HEADERS = {
|
|
16
|
+
Accept: "application/json, application/problem+json",
|
|
17
|
+
"Content-Type": "application/json"
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Create API Config Factory
|
|
21
|
+
*
|
|
22
|
+
* Creates a factory function that generates API configurations
|
|
23
|
+
* with the provided auth and tenant resolvers.
|
|
24
|
+
*/
|
|
25
|
+
function createAPIConfigFactory(getAccessToken, getCurrentTenant, logger, factoryOptions = {}) {
|
|
26
|
+
const { baseURL = DEFAULT_API_BASE_URL, defaultHeaders = DEFAULT_HEADERS, userAgent = "MimirCore/1.0", timeout = 3e4 } = factoryOptions;
|
|
27
|
+
/**
|
|
28
|
+
* Resolve tenant ID from request or options
|
|
29
|
+
*/
|
|
30
|
+
async function resolveTenantId(request, options) {
|
|
31
|
+
if (options.tenantId) {
|
|
32
|
+
logger?.debug?.("Using explicit tenant ID", { tenantId: options.tenantId });
|
|
33
|
+
return options.tenantId;
|
|
34
|
+
}
|
|
35
|
+
try {
|
|
36
|
+
const tenantId = await getCurrentTenant(request);
|
|
37
|
+
if (tenantId) logger?.debug?.("Resolved tenant from context", { tenantId });
|
|
38
|
+
return tenantId;
|
|
39
|
+
} catch (error) {
|
|
40
|
+
logger?.warn?.("Failed to resolve current tenant", error instanceof Error ? error : void 0);
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Creates unified API configuration for all services.
|
|
46
|
+
*
|
|
47
|
+
* This function automatically:
|
|
48
|
+
* - Adds authentication token to Authorization header
|
|
49
|
+
* - Injects tenant context as X-Tenant-Id header
|
|
50
|
+
* - Configures base URL from environment
|
|
51
|
+
* - Applies default headers
|
|
52
|
+
*
|
|
53
|
+
* @param request - The incoming request object
|
|
54
|
+
* @param options - Configuration options
|
|
55
|
+
* @returns API configuration object
|
|
56
|
+
* @throws Error if required authentication or tenant context is missing
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ` ypescript
|
|
60
|
+
* // Standard usage with auth and tenant
|
|
61
|
+
* const config = await createAPIConfig(request);
|
|
62
|
+
* const api = new IdentityApi(config);
|
|
63
|
+
*
|
|
64
|
+
* // Without tenant requirement
|
|
65
|
+
* const config = await createAPIConfig(request, { requireTenant: false });
|
|
66
|
+
*
|
|
67
|
+
* // With explicit tenant override
|
|
68
|
+
* const config = await createAPIConfig(request, { tenantId: 'specific-tenant-id' });
|
|
69
|
+
* `
|
|
70
|
+
*/
|
|
71
|
+
async function createAPIConfig(request, options = {}) {
|
|
72
|
+
const { requireTenant = true, includeAuth = true, customHeaders = {} } = options;
|
|
73
|
+
const headers = {
|
|
74
|
+
...defaultHeaders,
|
|
75
|
+
"User-Agent": userAgent,
|
|
76
|
+
...customHeaders
|
|
77
|
+
};
|
|
78
|
+
let accessToken;
|
|
79
|
+
if (includeAuth) {
|
|
80
|
+
const token = await getAccessToken(request);
|
|
81
|
+
if (!token) {
|
|
82
|
+
logger?.error?.("No access token available for API request");
|
|
83
|
+
throw new Error("No access token available");
|
|
84
|
+
}
|
|
85
|
+
accessToken = token;
|
|
86
|
+
headers.Authorization = `Bearer ${token}`;
|
|
87
|
+
logger?.debug?.("Added authorization header to API config");
|
|
88
|
+
}
|
|
89
|
+
const tenantId = await resolveTenantId(request, options);
|
|
90
|
+
if (requireTenant) {
|
|
91
|
+
if (!tenantId) {
|
|
92
|
+
logger?.error?.("Tenant context required but not available");
|
|
93
|
+
throw new Error("Tenant context is required for this operation");
|
|
94
|
+
}
|
|
95
|
+
headers["X-Tenant-Id"] = tenantId;
|
|
96
|
+
logger?.debug?.("Added tenant context header", { tenantId });
|
|
97
|
+
}
|
|
98
|
+
logger?.debug?.("API config created", {
|
|
99
|
+
basePath: baseURL,
|
|
100
|
+
hasAuth: includeAuth,
|
|
101
|
+
hasTenant: !!tenantId,
|
|
102
|
+
requireTenant
|
|
103
|
+
});
|
|
104
|
+
return {
|
|
105
|
+
basePath: baseURL,
|
|
106
|
+
accessToken,
|
|
107
|
+
headers,
|
|
108
|
+
tenantId: tenantId || "",
|
|
109
|
+
baseOptions: { timeout }
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Get the configured API base URL
|
|
114
|
+
*/
|
|
115
|
+
function getAPIBaseURL() {
|
|
116
|
+
return baseURL;
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
createAPIConfig,
|
|
120
|
+
getAPIBaseURL
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
//#endregion
|
|
125
|
+
//#region src/api-client/fetch-client.server.ts
|
|
126
|
+
const refreshPromiseMap = new Map();
|
|
127
|
+
const responseRequestMeta = new WeakMap();
|
|
128
|
+
const rawResponseStore = new AsyncLocalStorage();
|
|
129
|
+
function getSessionKeyFromRequest(request) {
|
|
130
|
+
const cookie = request.headers.get("cookie") || "";
|
|
131
|
+
return `session:${cookie.slice(0, 50)}`;
|
|
132
|
+
}
|
|
133
|
+
function getOrCreateRefreshPromise(sessionKey, refreshFn, logger) {
|
|
134
|
+
const existingPromise = refreshPromiseMap.get(sessionKey);
|
|
135
|
+
if (existingPromise) {
|
|
136
|
+
logger?.info?.("Token refresh already in progress, waiting for existing refresh");
|
|
137
|
+
return existingPromise;
|
|
138
|
+
}
|
|
139
|
+
logger?.info?.("Starting new token refresh");
|
|
140
|
+
const refreshPromise = refreshFn().finally(() => {
|
|
141
|
+
refreshPromiseMap.delete(sessionKey);
|
|
142
|
+
});
|
|
143
|
+
refreshPromiseMap.set(sessionKey, refreshPromise);
|
|
144
|
+
return refreshPromise;
|
|
145
|
+
}
|
|
146
|
+
function ensureRequestMeta(init) {
|
|
147
|
+
if (!init.__spineMeta) init.__spineMeta = {};
|
|
148
|
+
return init.__spineMeta;
|
|
149
|
+
}
|
|
150
|
+
function headersToRecord(headersInit) {
|
|
151
|
+
return Object.fromEntries(new Headers(headersInit).entries());
|
|
152
|
+
}
|
|
153
|
+
function cloneInit(init) {
|
|
154
|
+
const source = init;
|
|
155
|
+
return {
|
|
156
|
+
...source,
|
|
157
|
+
headers: headersToRecord(source.headers),
|
|
158
|
+
__spineMeta: source.__spineMeta ? { ...source.__spineMeta } : void 0
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
function createTimeoutFetch(timeout) {
|
|
162
|
+
if (!timeout) return void 0;
|
|
163
|
+
return (input, init) => fetchWithTimeout(input, {
|
|
164
|
+
...init,
|
|
165
|
+
timeout
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
function isProblemDetails(value) {
|
|
169
|
+
return typeof value === "object" && value !== null && "title" in value && "status" in value && "detail" in value;
|
|
170
|
+
}
|
|
171
|
+
async function parseResponseBody(response) {
|
|
172
|
+
const clone = response.clone();
|
|
173
|
+
const contentType = clone.headers.get("content-type") || "";
|
|
174
|
+
if (contentType.includes("application/json") || contentType.includes("+json")) try {
|
|
175
|
+
return await clone.json();
|
|
176
|
+
} catch {
|
|
177
|
+
return void 0;
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
const text = await clone.text();
|
|
181
|
+
return text || void 0;
|
|
182
|
+
} catch {
|
|
183
|
+
return void 0;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
function createClientError(params) {
|
|
187
|
+
const error = new Error(params.message);
|
|
188
|
+
error.name = "APIClientError";
|
|
189
|
+
error.isApiClientError = true;
|
|
190
|
+
error.response = params.response;
|
|
191
|
+
error.config = params.config;
|
|
192
|
+
error.problemDetails = params.problemDetails;
|
|
193
|
+
error.shouldLogout = params.shouldLogout;
|
|
194
|
+
error.originalError = params.originalError;
|
|
195
|
+
error.cause = params.cause;
|
|
196
|
+
return error;
|
|
197
|
+
}
|
|
198
|
+
async function toAPIResponse(rawResponse, resolvedData) {
|
|
199
|
+
const data = resolvedData === void 0 ? await parseResponseBody(rawResponse) : resolvedData;
|
|
200
|
+
return {
|
|
201
|
+
data,
|
|
202
|
+
status: rawResponse.status,
|
|
203
|
+
statusText: rawResponse.statusText,
|
|
204
|
+
headers: headersToRecord(rawResponse.headers),
|
|
205
|
+
raw: rawResponse
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
async function normalizeClientError(error) {
|
|
209
|
+
if (isApiClientError(error)) return error;
|
|
210
|
+
if (error && typeof error === "object" && "response" in error && error.response instanceof Response) {
|
|
211
|
+
const response = error.response;
|
|
212
|
+
const responseData = await parseResponseBody(response);
|
|
213
|
+
const problemDetails = isProblemDetails(responseData) ? responseData : void 0;
|
|
214
|
+
return createClientError({
|
|
215
|
+
message: problemDetails?.detail || problemDetails?.title || response.statusText || "API request failed",
|
|
216
|
+
response: await toAPIResponse(response, responseData),
|
|
217
|
+
config: responseRequestMeta.get(response),
|
|
218
|
+
problemDetails,
|
|
219
|
+
cause: error
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
return createClientError({
|
|
223
|
+
message: error instanceof Error ? error.message : "API request failed",
|
|
224
|
+
cause: error
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
function isRetryableFetchError(error) {
|
|
228
|
+
if (isRetryableError(error)) return true;
|
|
229
|
+
if (error && typeof error === "object" && "cause" in error) return isRetryableError(error.cause);
|
|
230
|
+
return false;
|
|
231
|
+
}
|
|
232
|
+
async function maybeRetryResponse(context, retryConfig, logger) {
|
|
233
|
+
const init = cloneInit(context.init);
|
|
234
|
+
const meta = ensureRequestMeta(init);
|
|
235
|
+
if (context.response.status === 401 || context.response.status === 409) return void 0;
|
|
236
|
+
if (!isRetryableError(context.response)) return void 0;
|
|
237
|
+
const retryCount = meta.retryCount ?? 0;
|
|
238
|
+
if (retryCount >= retryConfig.maxRetries) return void 0;
|
|
239
|
+
meta.retryCount = retryCount + 1;
|
|
240
|
+
const delay = calculateBackoffDelay(meta.retryCount, retryConfig.baseDelay, retryConfig.maxDelay);
|
|
241
|
+
logger?.info?.("Retrying request", {
|
|
242
|
+
url: context.url,
|
|
243
|
+
method: (init.method ?? "GET").toUpperCase(),
|
|
244
|
+
attempt: meta.retryCount,
|
|
245
|
+
maxRetries: retryConfig.maxRetries,
|
|
246
|
+
delay,
|
|
247
|
+
status: context.response.status
|
|
248
|
+
});
|
|
249
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
250
|
+
return context.fetch(context.url, init);
|
|
251
|
+
}
|
|
252
|
+
async function maybeRetryError(context, retryConfig, logger) {
|
|
253
|
+
const init = cloneInit(context.init);
|
|
254
|
+
const meta = ensureRequestMeta(init);
|
|
255
|
+
const retryCount = meta.retryCount ?? 0;
|
|
256
|
+
if (!isRetryableFetchError(context.error) || retryCount >= retryConfig.maxRetries) return void 0;
|
|
257
|
+
meta.retryCount = retryCount + 1;
|
|
258
|
+
const delay = calculateBackoffDelay(meta.retryCount, retryConfig.baseDelay, retryConfig.maxDelay);
|
|
259
|
+
logger?.info?.("Retrying request after fetch failure", {
|
|
260
|
+
url: context.url,
|
|
261
|
+
method: (init.method ?? "GET").toUpperCase(),
|
|
262
|
+
attempt: meta.retryCount,
|
|
263
|
+
maxRetries: retryConfig.maxRetries,
|
|
264
|
+
delay
|
|
265
|
+
});
|
|
266
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
267
|
+
return context.fetch(context.url, init);
|
|
268
|
+
}
|
|
269
|
+
function createFetchMiddleware(request, options = {}) {
|
|
270
|
+
const { logger, attemptTokenRefresh, retryConfig = {}, addRequestId = true } = options;
|
|
271
|
+
const normalizedRetryConfig = {
|
|
272
|
+
maxRetries: retryConfig.maxRetries ?? 3,
|
|
273
|
+
baseDelay: retryConfig.baseDelay ?? 1e3,
|
|
274
|
+
maxDelay: retryConfig.maxDelay ?? 1e4
|
|
275
|
+
};
|
|
276
|
+
return [{
|
|
277
|
+
async pre(context) {
|
|
278
|
+
const init = cloneInit(context.init);
|
|
279
|
+
const meta = ensureRequestMeta(init);
|
|
280
|
+
const headers = new Headers(init.headers);
|
|
281
|
+
if (addRequestId) {
|
|
282
|
+
const requestId = headers.get("X-Request-Id") || crypto.randomUUID();
|
|
283
|
+
headers.set("X-Request-Id", requestId);
|
|
284
|
+
meta.requestId = requestId;
|
|
285
|
+
}
|
|
286
|
+
init.headers = headersToRecord(headers);
|
|
287
|
+
logger?.debug?.("API request initiated", {
|
|
288
|
+
method: (init.method ?? "GET").toUpperCase(),
|
|
289
|
+
url: context.url,
|
|
290
|
+
requestId: meta.requestId
|
|
291
|
+
});
|
|
292
|
+
return {
|
|
293
|
+
url: context.url,
|
|
294
|
+
init
|
|
295
|
+
};
|
|
296
|
+
},
|
|
297
|
+
async post(context) {
|
|
298
|
+
const init = cloneInit(context.init);
|
|
299
|
+
const meta = ensureRequestMeta(init);
|
|
300
|
+
responseRequestMeta.set(context.response, {
|
|
301
|
+
url: context.url,
|
|
302
|
+
method: (init.method ?? "GET").toUpperCase(),
|
|
303
|
+
headers: headersToRecord(init.headers)
|
|
304
|
+
});
|
|
305
|
+
if (context.response.status === 401 && attemptTokenRefresh && !meta.refreshed) {
|
|
306
|
+
meta.refreshed = true;
|
|
307
|
+
logger?.info?.("Received 401 from backend, attempting token refresh", {
|
|
308
|
+
url: context.url,
|
|
309
|
+
method: (init.method ?? "GET").toUpperCase()
|
|
310
|
+
});
|
|
311
|
+
const refreshResult = await getOrCreateRefreshPromise(getSessionKeyFromRequest(request), () => attemptTokenRefresh(request), logger);
|
|
312
|
+
if (refreshResult.success && refreshResult.newAccessToken) {
|
|
313
|
+
const headers = new Headers(init.headers);
|
|
314
|
+
headers.set("Authorization", `Bearer ${refreshResult.newAccessToken}`);
|
|
315
|
+
init.headers = headersToRecord(headers);
|
|
316
|
+
logger?.info?.("Token refresh successful, retrying original request");
|
|
317
|
+
return context.fetch(context.url, init);
|
|
318
|
+
}
|
|
319
|
+
if (refreshResult.shouldLogout) throw createClientError({
|
|
320
|
+
message: "REFRESH_TOKEN_EXPIRED",
|
|
321
|
+
response: await toAPIResponse(context.response),
|
|
322
|
+
config: responseRequestMeta.get(context.response),
|
|
323
|
+
shouldLogout: true,
|
|
324
|
+
originalError: refreshResult,
|
|
325
|
+
cause: refreshResult
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
const retryResponse = await maybeRetryResponse(context, normalizedRetryConfig, logger);
|
|
329
|
+
if (retryResponse) return retryResponse;
|
|
330
|
+
if (context.response.status >= 400) {
|
|
331
|
+
const responseData = await parseResponseBody(context.response);
|
|
332
|
+
const problemDetails = isProblemDetails(responseData) ? responseData : void 0;
|
|
333
|
+
logger?.error?.("API error response received", void 0, {
|
|
334
|
+
url: context.url,
|
|
335
|
+
method: (init.method ?? "GET").toUpperCase(),
|
|
336
|
+
status: context.response.status,
|
|
337
|
+
code: problemDetails?.title,
|
|
338
|
+
detail: problemDetails?.detail,
|
|
339
|
+
traceId: problemDetails?.traceId
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
return context.response;
|
|
343
|
+
},
|
|
344
|
+
async onError(context) {
|
|
345
|
+
const retryResponse = await maybeRetryError(context, normalizedRetryConfig, logger);
|
|
346
|
+
if (retryResponse) return retryResponse;
|
|
347
|
+
return void 0;
|
|
348
|
+
}
|
|
349
|
+
}];
|
|
350
|
+
}
|
|
351
|
+
function instrumentRawMethods(client) {
|
|
352
|
+
if (client.__spineRawMethodsInstrumented) return;
|
|
353
|
+
const prototype = Object.getPrototypeOf(client);
|
|
354
|
+
for (const key of Object.getOwnPropertyNames(prototype)) {
|
|
355
|
+
if (!key.endsWith("Raw")) continue;
|
|
356
|
+
const original = prototype[key];
|
|
357
|
+
if (typeof original !== "function") continue;
|
|
358
|
+
Object.defineProperty(client, key, {
|
|
359
|
+
configurable: true,
|
|
360
|
+
enumerable: false,
|
|
361
|
+
writable: true,
|
|
362
|
+
value: async (...args) => {
|
|
363
|
+
const result = await original.apply(client, args);
|
|
364
|
+
rawResponseStore.getStore()?.set(key, result);
|
|
365
|
+
return result;
|
|
366
|
+
}
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
client.__spineRawMethodsInstrumented = true;
|
|
370
|
+
}
|
|
371
|
+
function wrapClient(client) {
|
|
372
|
+
instrumentRawMethods(client);
|
|
373
|
+
const methodCache = new Map();
|
|
374
|
+
return new Proxy(client, { get(target, prop, receiver) {
|
|
375
|
+
const value = Reflect.get(target, prop, receiver);
|
|
376
|
+
if (typeof prop !== "string" || typeof value !== "function" || prop.endsWith("Raw")) return typeof value === "function" ? value.bind(target) : value;
|
|
377
|
+
if (methodCache.has(prop)) return methodCache.get(prop);
|
|
378
|
+
const wrapped = async (...args) => rawResponseStore.run(new Map(), async () => {
|
|
379
|
+
try {
|
|
380
|
+
const resolvedData = await value.apply(target, args);
|
|
381
|
+
const rawResponse = rawResponseStore.getStore()?.get(`${prop}Raw`);
|
|
382
|
+
if (rawResponse) return toAPIResponse(rawResponse.raw, resolvedData);
|
|
383
|
+
return {
|
|
384
|
+
data: resolvedData,
|
|
385
|
+
status: 200,
|
|
386
|
+
statusText: "OK",
|
|
387
|
+
headers: {}
|
|
388
|
+
};
|
|
389
|
+
} catch (error) {
|
|
390
|
+
throw await normalizeClientError(error);
|
|
391
|
+
}
|
|
392
|
+
});
|
|
393
|
+
methodCache.set(prop, wrapped);
|
|
394
|
+
return wrapped;
|
|
395
|
+
} });
|
|
396
|
+
}
|
|
397
|
+
async function createApiClient(request, ClientClass, createAPIConfig, ConfigurationClass, options = {}) {
|
|
398
|
+
const { requireTenant, includeAuth, tenantId, customHeaders, credentials,...fetchOptions } = options;
|
|
399
|
+
const config = await createAPIConfig(request, {
|
|
400
|
+
requireTenant,
|
|
401
|
+
includeAuth,
|
|
402
|
+
tenantId,
|
|
403
|
+
customHeaders
|
|
404
|
+
});
|
|
405
|
+
const configuration = new ConfigurationClass({
|
|
406
|
+
basePath: config.basePath,
|
|
407
|
+
accessToken: config.accessToken,
|
|
408
|
+
headers: config.headers,
|
|
409
|
+
credentials: credentials ?? config.credentials,
|
|
410
|
+
middleware: createFetchMiddleware(request, fetchOptions),
|
|
411
|
+
fetchApi: createTimeoutFetch(config.baseOptions?.timeout)
|
|
412
|
+
});
|
|
413
|
+
const client = new ClientClass(configuration);
|
|
414
|
+
return {
|
|
415
|
+
client: wrapClient(client),
|
|
416
|
+
tenantId: config.tenantId
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
//#endregion
|
|
421
|
+
export { createAPIConfigFactory, createApiClient, createFetchMiddleware };
|
|
422
|
+
//# sourceMappingURL=server-DZmcd2Lr.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-DZmcd2Lr.js","names":["DEFAULT_HEADERS: Record<string, string>","getAccessToken: GetAccessTokenFn","getCurrentTenant: GetCurrentTenantFn","logger?: APILogger","factoryOptions: APIConfigFactoryOptions","request: Request","options: CreateAPIConfigOptions","headers: Record<string, string>","accessToken: string | undefined","request: Request","sessionKey: string","refreshFn: () => Promise<TokenRefreshResult>","logger?: APILogger","init: SpineRequestInit","headersInit?: HeadersInit","init: RequestInit","timeout?: number","value: unknown","response: Response","params: {\n message: string;\n response?: APIResponse<T>;\n config?: ResponseRequestMeta;\n problemDetails?: ProblemDetails;\n shouldLogout?: boolean;\n originalError?: unknown;\n cause?: unknown;\n}","rawResponse: Response","resolvedData?: T","error: unknown","context: FetchResponseContext","retryConfig: Required<Pick<RetryConfig, 'maxRetries' | 'baseDelay' | 'maxDelay'>>","context: FetchErrorContext","options: FetchSetupOptions","client: T","ClientClass: new (configuration?: unknown) => T","createAPIConfig: (request: Request, options?: CreateAPIConfigOptions) => Promise<APIConfig>","ConfigurationClass: new (params?: Record<string, unknown>) => unknown","options: CreateApiClientOptions"],"sources":["../src/api-client/api-config.server.ts","../src/api-client/fetch-client.server.ts"],"sourcesContent":["/**\n * API Configuration Server Module\n *\n * Centralized configuration for all API clients,\n * automatically handling authentication tokens and tenant context.\n */\n\nimport type { APIConfig, CreateAPIConfigOptions, GetAccessTokenFn, GetCurrentTenantFn, APILogger } from './types';\n\n/**\n * Base URL Configuration\n * Single unified base URL for all API operations\n */\nconst DEFAULT_API_BASE_URL = process.env.API_BASE_URL || 'https://localhost:5001';\n\n/**\n * Default Headers\n * Applied to all API requests\n */\nconst DEFAULT_HEADERS: Record<string, string> = {\n Accept: 'application/json, application/problem+json',\n 'Content-Type': 'application/json',\n};\n\n/**\n * API Config Factory Options\n */\nexport interface APIConfigFactoryOptions {\n /**\n * Base URL for API requests\n */\n baseURL?: string;\n /**\n * Default headers applied to all requests\n */\n defaultHeaders?: Record<string, string>;\n /**\n * User agent string\n */\n userAgent?: string;\n /**\n * Default timeout in milliseconds\n */\n timeout?: number;\n}\n\n/**\n * Create API Config Factory\n *\n * Creates a factory function that generates API configurations\n * with the provided auth and tenant resolvers.\n */\nexport function createAPIConfigFactory(\n getAccessToken: GetAccessTokenFn,\n getCurrentTenant: GetCurrentTenantFn,\n logger?: APILogger,\n factoryOptions: APIConfigFactoryOptions = {}\n) {\n const {\n baseURL = DEFAULT_API_BASE_URL,\n defaultHeaders = DEFAULT_HEADERS,\n userAgent = 'MimirCore/1.0',\n timeout = 30000,\n } = factoryOptions;\n\n /**\n * Resolve tenant ID from request or options\n */\n async function resolveTenantId(\n request: Request,\n options: CreateAPIConfigOptions\n ): Promise<string | null> {\n // Use explicit tenant ID if provided\n if (options.tenantId) {\n logger?.debug?.('Using explicit tenant ID', { tenantId: options.tenantId });\n return options.tenantId;\n }\n\n // Resolve from current tenant context\n try {\n const tenantId = await getCurrentTenant(request);\n if (tenantId) {\n logger?.debug?.('Resolved tenant from context', { tenantId });\n }\n return tenantId;\n } catch (error) {\n logger?.warn?.('Failed to resolve current tenant', error instanceof Error ? error : undefined);\n return null;\n }\n }\n\n /**\n * Creates unified API configuration for all services.\n *\n * This function automatically:\n * - Adds authentication token to Authorization header\n * - Injects tenant context as X-Tenant-Id header\n * - Configures base URL from environment\n * - Applies default headers\n *\n * @param request - The incoming request object\n * @param options - Configuration options\n * @returns API configuration object\n * @throws Error if required authentication or tenant context is missing\n *\n * @example\n * `\typescript\n * // Standard usage with auth and tenant\n * const config = await createAPIConfig(request);\n * const api = new IdentityApi(config);\n *\n * // Without tenant requirement\n * const config = await createAPIConfig(request, { requireTenant: false });\n *\n * // With explicit tenant override\n * const config = await createAPIConfig(request, { tenantId: 'specific-tenant-id' });\n * `\n */\n async function createAPIConfig(\n request: Request,\n options: CreateAPIConfigOptions = {}\n ): Promise<APIConfig> {\n const {\n requireTenant = true,\n includeAuth = true,\n customHeaders = {},\n } = options;\n\n // Start with default headers\n const headers: Record<string, string> = {\n ...defaultHeaders,\n 'User-Agent': userAgent,\n ...customHeaders,\n };\n\n let accessToken: string | undefined;\n\n // Add authentication if required\n if (includeAuth) {\n const token = await getAccessToken(request);\n if (!token) {\n logger?.error?.('No access token available for API request');\n throw new Error('No access token available');\n }\n\n accessToken = token;\n headers.Authorization = `Bearer ${token}`;\n logger?.debug?.('Added authorization header to API config');\n }\n\n // Resolve tenant context\n const tenantId = await resolveTenantId(request, options);\n\n // Add tenant header if required\n if (requireTenant) {\n if (!tenantId) {\n logger?.error?.('Tenant context required but not available');\n throw new Error('Tenant context is required for this operation');\n }\n\n headers['X-Tenant-Id'] = tenantId;\n logger?.debug?.('Added tenant context header', { tenantId });\n }\n\n logger?.debug?.('API config created', {\n basePath: baseURL,\n hasAuth: includeAuth,\n hasTenant: !!tenantId,\n requireTenant,\n });\n\n return {\n basePath: baseURL,\n accessToken,\n headers,\n tenantId: tenantId || '',\n baseOptions: {\n timeout,\n },\n };\n }\n\n /**\n * Get the configured API base URL\n */\n function getAPIBaseURL(): string {\n return baseURL;\n }\n\n return {\n createAPIConfig,\n getAPIBaseURL,\n };\n}\n\nexport type APIConfigFactory = ReturnType<typeof createAPIConfigFactory>;\n","/**\n * Fetch-native API client setup for generated OpenAPI clients.\n *\n * This module preserves the shared request behaviors we need around fetch:\n * - request ID enrichment\n * - serialized token refresh on 401\n * - retry with exponential backoff\n * - ProblemDetails-aware error shaping\n *\n * It gives downstream apps a single fetch-native entry point for generated clients.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type {\n APIClientError,\n APIConfig,\n APIResponse,\n APILogger,\n CreateAPIConfigOptions,\n EnhancedAPIClient,\n FetchErrorContext,\n FetchMiddleware,\n FetchResponseContext,\n ProblemDetails,\n RetryConfig,\n TokenRefreshFn,\n TokenRefreshResult,\n} from './types';\nimport { isApiClientError } from './types';\nimport { calculateBackoffDelay, fetchWithTimeout, isRetryableError } from './retry-handler';\n\ntype RuntimeApiResponse<T> = {\n raw: Response;\n value(): Promise<T>;\n};\n\ntype GeneratedFetchClient = object;\n\ntype SpineRequestInit = RequestInit & {\n __spineMeta?: {\n requestId?: string;\n retryCount?: number;\n refreshed?: boolean;\n };\n};\n\ntype ResponseRequestMeta = {\n url: string;\n method: string;\n headers: Record<string, string>;\n};\n\nconst refreshPromiseMap = new Map<string, Promise<TokenRefreshResult>>();\nconst responseRequestMeta = new WeakMap<Response, ResponseRequestMeta>();\nconst rawResponseStore = new AsyncLocalStorage<Map<string, RuntimeApiResponse<unknown>>>();\n\nfunction getSessionKeyFromRequest(request: Request): string {\n const cookie = request.headers.get('cookie') || '';\n return `session:${cookie.slice(0, 50)}`;\n}\n\nfunction getOrCreateRefreshPromise(\n sessionKey: string,\n refreshFn: () => Promise<TokenRefreshResult>,\n logger?: APILogger\n): Promise<TokenRefreshResult> {\n const existingPromise = refreshPromiseMap.get(sessionKey);\n if (existingPromise) {\n logger?.info?.('Token refresh already in progress, waiting for existing refresh');\n return existingPromise;\n }\n\n logger?.info?.('Starting new token refresh');\n\n const refreshPromise = refreshFn().finally(() => {\n refreshPromiseMap.delete(sessionKey);\n });\n\n refreshPromiseMap.set(sessionKey, refreshPromise);\n return refreshPromise;\n}\n\nfunction ensureRequestMeta(init: SpineRequestInit): NonNullable<SpineRequestInit['__spineMeta']> {\n if (!init.__spineMeta) {\n init.__spineMeta = {};\n }\n\n return init.__spineMeta;\n}\n\nfunction headersToRecord(headersInit?: HeadersInit): Record<string, string> {\n return Object.fromEntries(new Headers(headersInit).entries());\n}\n\nfunction cloneInit(init: RequestInit): SpineRequestInit {\n const source = init as SpineRequestInit;\n\n return {\n ...source,\n headers: headersToRecord(source.headers),\n __spineMeta: source.__spineMeta ? { ...source.__spineMeta } : undefined,\n };\n}\n\nfunction createTimeoutFetch(timeout?: number): typeof fetch | undefined {\n if (!timeout) {\n return undefined;\n }\n\n return (input, init) => fetchWithTimeout(input, { ...init, timeout });\n}\n\nfunction isProblemDetails(value: unknown): value is ProblemDetails {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'title' in value &&\n 'status' in value &&\n 'detail' in value\n );\n}\n\nasync function parseResponseBody(response: Response): Promise<unknown> {\n const clone = response.clone();\n const contentType = clone.headers.get('content-type') || '';\n\n if (contentType.includes('application/json') || contentType.includes('+json')) {\n try {\n return await clone.json();\n } catch {\n return undefined;\n }\n }\n\n try {\n const text = await clone.text();\n return text || undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction createClientError<T = unknown>(params: {\n message: string;\n response?: APIResponse<T>;\n config?: ResponseRequestMeta;\n problemDetails?: ProblemDetails;\n shouldLogout?: boolean;\n originalError?: unknown;\n cause?: unknown;\n}): APIClientError<T> {\n const error = new Error(params.message) as APIClientError<T>;\n\n error.name = 'APIClientError';\n error.isApiClientError = true;\n error.response = params.response;\n error.config = params.config;\n error.problemDetails = params.problemDetails;\n error.shouldLogout = params.shouldLogout;\n error.originalError = params.originalError;\n error.cause = params.cause;\n\n return error;\n}\n\nasync function toAPIResponse<T>(\n rawResponse: Response,\n resolvedData?: T\n): Promise<APIResponse<T>> {\n const data = resolvedData === undefined ? ((await parseResponseBody(rawResponse)) as T) : resolvedData;\n\n return {\n data,\n status: rawResponse.status,\n statusText: rawResponse.statusText,\n headers: headersToRecord(rawResponse.headers),\n raw: rawResponse,\n };\n}\n\nasync function normalizeClientError(error: unknown): Promise<APIClientError> {\n if (isApiClientError(error)) {\n return error;\n }\n\n if (error && typeof error === 'object' && 'response' in error && (error as { response?: unknown }).response instanceof Response) {\n const response = (error as { response: Response }).response;\n const responseData = await parseResponseBody(response);\n const problemDetails = isProblemDetails(responseData) ? responseData : undefined;\n\n return createClientError({\n message:\n problemDetails?.detail ||\n problemDetails?.title ||\n response.statusText ||\n 'API request failed',\n response: await toAPIResponse(response, responseData),\n config: responseRequestMeta.get(response),\n problemDetails,\n cause: error,\n });\n }\n\n return createClientError({\n message: error instanceof Error ? error.message : 'API request failed',\n cause: error,\n });\n}\n\nfunction isRetryableFetchError(error: unknown): boolean {\n if (isRetryableError(error)) {\n return true;\n }\n\n if (error && typeof error === 'object' && 'cause' in error) {\n return isRetryableError((error as { cause?: unknown }).cause);\n }\n\n return false;\n}\n\nasync function maybeRetryResponse(\n context: FetchResponseContext,\n retryConfig: Required<Pick<RetryConfig, 'maxRetries' | 'baseDelay' | 'maxDelay'>>,\n logger?: APILogger\n): Promise<Response | undefined> {\n const init = cloneInit(context.init);\n const meta = ensureRequestMeta(init);\n\n if (context.response.status === 401 || context.response.status === 409) {\n return undefined;\n }\n\n if (!isRetryableError(context.response)) {\n return undefined;\n }\n\n const retryCount = meta.retryCount ?? 0;\n if (retryCount >= retryConfig.maxRetries) {\n return undefined;\n }\n\n meta.retryCount = retryCount + 1;\n\n const delay = calculateBackoffDelay(meta.retryCount, retryConfig.baseDelay, retryConfig.maxDelay);\n logger?.info?.('Retrying request', {\n url: context.url,\n method: (init.method ?? 'GET').toUpperCase(),\n attempt: meta.retryCount,\n maxRetries: retryConfig.maxRetries,\n delay,\n status: context.response.status,\n });\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n\n return context.fetch(context.url, init);\n}\n\nasync function maybeRetryError(\n context: FetchErrorContext,\n retryConfig: Required<Pick<RetryConfig, 'maxRetries' | 'baseDelay' | 'maxDelay'>>,\n logger?: APILogger\n): Promise<Response | undefined> {\n const init = cloneInit(context.init);\n const meta = ensureRequestMeta(init);\n const retryCount = meta.retryCount ?? 0;\n\n if (!isRetryableFetchError(context.error) || retryCount >= retryConfig.maxRetries) {\n return undefined;\n }\n\n meta.retryCount = retryCount + 1;\n\n const delay = calculateBackoffDelay(meta.retryCount, retryConfig.baseDelay, retryConfig.maxDelay);\n logger?.info?.('Retrying request after fetch failure', {\n url: context.url,\n method: (init.method ?? 'GET').toUpperCase(),\n attempt: meta.retryCount,\n maxRetries: retryConfig.maxRetries,\n delay,\n });\n\n await new Promise((resolve) => setTimeout(resolve, delay));\n\n return context.fetch(context.url, init);\n}\n\nexport interface FetchSetupOptions {\n logger?: APILogger;\n attemptTokenRefresh?: TokenRefreshFn;\n retryConfig?: RetryConfig;\n addRequestId?: boolean;\n}\n\nexport function createFetchMiddleware(\n request: Request,\n options: FetchSetupOptions = {}\n): FetchMiddleware[] {\n const {\n logger,\n attemptTokenRefresh,\n retryConfig = {},\n addRequestId = true,\n } = options;\n\n const normalizedRetryConfig = {\n maxRetries: retryConfig.maxRetries ?? 3,\n baseDelay: retryConfig.baseDelay ?? 1000,\n maxDelay: retryConfig.maxDelay ?? 10000,\n };\n\n return [\n {\n async pre(context) {\n const init = cloneInit(context.init);\n const meta = ensureRequestMeta(init);\n const headers = new Headers(init.headers);\n\n if (addRequestId) {\n const requestId = headers.get('X-Request-Id') || crypto.randomUUID();\n headers.set('X-Request-Id', requestId);\n meta.requestId = requestId;\n }\n\n init.headers = headersToRecord(headers);\n\n logger?.debug?.('API request initiated', {\n method: (init.method ?? 'GET').toUpperCase(),\n url: context.url,\n requestId: meta.requestId,\n });\n\n return {\n url: context.url,\n init,\n };\n },\n\n async post(context) {\n const init = cloneInit(context.init);\n const meta = ensureRequestMeta(init);\n\n responseRequestMeta.set(context.response, {\n url: context.url,\n method: (init.method ?? 'GET').toUpperCase(),\n headers: headersToRecord(init.headers),\n });\n\n if (context.response.status === 401 && attemptTokenRefresh && !meta.refreshed) {\n meta.refreshed = true;\n\n logger?.info?.('Received 401 from backend, attempting token refresh', {\n url: context.url,\n method: (init.method ?? 'GET').toUpperCase(),\n });\n\n const refreshResult = await getOrCreateRefreshPromise(\n getSessionKeyFromRequest(request),\n () => attemptTokenRefresh(request),\n logger\n );\n\n if (refreshResult.success && refreshResult.newAccessToken) {\n const headers = new Headers(init.headers);\n headers.set('Authorization', `Bearer ${refreshResult.newAccessToken}`);\n init.headers = headersToRecord(headers);\n\n logger?.info?.('Token refresh successful, retrying original request');\n\n return context.fetch(context.url, init);\n }\n\n if (refreshResult.shouldLogout) {\n throw createClientError({\n message: 'REFRESH_TOKEN_EXPIRED',\n response: await toAPIResponse(context.response),\n config: responseRequestMeta.get(context.response),\n shouldLogout: true,\n originalError: refreshResult,\n cause: refreshResult,\n });\n }\n }\n\n const retryResponse = await maybeRetryResponse(context, normalizedRetryConfig, logger);\n if (retryResponse) {\n return retryResponse;\n }\n\n if (context.response.status >= 400) {\n const responseData = await parseResponseBody(context.response);\n const problemDetails = isProblemDetails(responseData) ? responseData : undefined;\n\n logger?.error?.('API error response received', undefined, {\n url: context.url,\n method: (init.method ?? 'GET').toUpperCase(),\n status: context.response.status,\n code: problemDetails?.title,\n detail: problemDetails?.detail,\n traceId: problemDetails?.traceId,\n });\n }\n\n return context.response;\n },\n\n async onError(context) {\n const retryResponse = await maybeRetryError(context, normalizedRetryConfig, logger);\n if (retryResponse) {\n return retryResponse;\n }\n\n return undefined;\n },\n },\n ];\n}\n\nexport interface CreateApiClientOptions extends FetchSetupOptions, CreateAPIConfigOptions {\n credentials?: RequestCredentials;\n}\n\nfunction instrumentRawMethods<T extends GeneratedFetchClient>(client: T): void {\n if ((client as { __spineRawMethodsInstrumented?: boolean }).__spineRawMethodsInstrumented) {\n return;\n }\n\n const prototype = Object.getPrototypeOf(client) as Record<string, unknown>;\n\n for (const key of Object.getOwnPropertyNames(prototype)) {\n if (!key.endsWith('Raw')) {\n continue;\n }\n\n const original = prototype[key];\n if (typeof original !== 'function') {\n continue;\n }\n\n Object.defineProperty(client, key, {\n configurable: true,\n enumerable: false,\n writable: true,\n value: async (...args: unknown[]) => {\n const result = await (original as (...innerArgs: unknown[]) => Promise<RuntimeApiResponse<unknown>>).apply(client, args);\n rawResponseStore.getStore()?.set(key, result);\n return result;\n },\n });\n }\n\n (client as { __spineRawMethodsInstrumented?: boolean }).__spineRawMethodsInstrumented = true;\n}\n\nfunction wrapClient<T extends GeneratedFetchClient>(client: T): EnhancedAPIClient<T> {\n instrumentRawMethods(client);\n\n const methodCache = new Map<PropertyKey, unknown>();\n\n return new Proxy(client, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n if (typeof prop !== 'string' || typeof value !== 'function' || prop.endsWith('Raw')) {\n return typeof value === 'function' ? value.bind(target) : value;\n }\n\n if (methodCache.has(prop)) {\n return methodCache.get(prop);\n }\n\n const wrapped = async (...args: unknown[]) =>\n rawResponseStore.run(new Map(), async () => {\n try {\n const resolvedData = await (value as (...innerArgs: unknown[]) => Promise<unknown>).apply(target, args);\n const rawResponse = rawResponseStore.getStore()?.get(`${prop}Raw`);\n\n if (rawResponse) {\n return toAPIResponse(rawResponse.raw, resolvedData);\n }\n\n return {\n data: resolvedData,\n status: 200,\n statusText: 'OK',\n headers: {},\n };\n } catch (error) {\n throw await normalizeClientError(error);\n }\n });\n\n methodCache.set(prop, wrapped);\n return wrapped;\n },\n }) as EnhancedAPIClient<T>;\n}\n\nexport async function createApiClient<T extends GeneratedFetchClient>(\n request: Request,\n ClientClass: new (configuration?: unknown) => T,\n createAPIConfig: (request: Request, options?: CreateAPIConfigOptions) => Promise<APIConfig>,\n ConfigurationClass: new (params?: Record<string, unknown>) => unknown,\n options: CreateApiClientOptions = {}\n): Promise<{ client: EnhancedAPIClient<T>; tenantId: string }> {\n const {\n requireTenant,\n includeAuth,\n tenantId,\n customHeaders,\n credentials,\n ...fetchOptions\n } = options;\n\n const config = await createAPIConfig(request, {\n requireTenant,\n includeAuth,\n tenantId,\n customHeaders,\n });\n\n const configuration = new ConfigurationClass({\n basePath: config.basePath,\n accessToken: config.accessToken,\n headers: config.headers,\n credentials: credentials ?? config.credentials,\n middleware: createFetchMiddleware(request, fetchOptions),\n fetchApi: createTimeoutFetch(config.baseOptions?.timeout),\n });\n\n const client = new ClientClass(configuration);\n\n return {\n client: wrapClient(client),\n tenantId: config.tenantId,\n };\n}\n"],"mappings":";;;;;;;;;AAaA,MAAM,uBAAuB,QAAQ,IAAI,gBAAgB;;;;;AAMzD,MAAMA,kBAA0C;CAC9C,QAAQ;CACR,gBAAgB;AACjB;;;;;;;AA8BD,SAAgB,uBACdC,gBACAC,kBACAC,QACAC,iBAA0C,CAAE,GAC5C;CACA,MAAM,EACJ,UAAU,sBACV,iBAAiB,iBACjB,YAAY,iBACZ,UAAU,KACX,GAAG;;;;CAKJ,eAAe,gBACbC,SACAC,SACwB;AAExB,MAAI,QAAQ,UAAU;AACpB,WAAQ,QAAQ,4BAA4B,EAAE,UAAU,QAAQ,SAAU,EAAC;AAC3E,UAAO,QAAQ;EAChB;AAGD,MAAI;GACF,MAAM,WAAW,MAAM,iBAAiB,QAAQ;AAChD,OAAI,SACF,SAAQ,QAAQ,gCAAgC,EAAE,SAAU,EAAC;AAE/D,UAAO;EACR,SAAQ,OAAO;AACd,WAAQ,OAAO,oCAAoC,iBAAiB,QAAQ,eAAkB;AAC9F,UAAO;EACR;CACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BD,eAAe,gBACbD,SACAC,UAAkC,CAAE,GAChB;EACpB,MAAM,EACJ,gBAAgB,MAChB,cAAc,MACd,gBAAgB,CAAE,GACnB,GAAG;EAGJ,MAAMC,UAAkC;GACtC,GAAG;GACH,cAAc;GACd,GAAG;EACJ;EAED,IAAIC;AAGJ,MAAI,aAAa;GACf,MAAM,QAAQ,MA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