@memberjunction/ng-workspace-initializer 5.48.0 → 5.49.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/services/workspace-initializer.service.d.ts +8 -0
- package/dist/lib/services/workspace-initializer.service.d.ts.map +1 -1
- package/dist/lib/services/workspace-initializer.service.js +54 -1
- package/dist/lib/services/workspace-initializer.service.js.map +1 -1
- package/package.json +10 -8
|
@@ -19,6 +19,14 @@ export declare class WorkspaceInitializerService {
|
|
|
19
19
|
* Replaces AppComponent error handling logic
|
|
20
20
|
*/
|
|
21
21
|
classifyError(err: any): WorkspaceInitError;
|
|
22
|
+
/**
|
|
23
|
+
* Org theming bootstrap: after metadata + ThemeService are ready, apply
|
|
24
|
+
* the brand theme the user last chose (a starred theme they swapped to), falling back
|
|
25
|
+
* to the org default. Derives the overlay via the theme engine and applies it always-on
|
|
26
|
+
* (under the user's light/dark choice). Non-fatal — a missing Theme entity (older DBs)
|
|
27
|
+
* or no theme simply leaves the stock MJ theme in place.
|
|
28
|
+
*/
|
|
29
|
+
private applyDefaultBrandTheme;
|
|
22
30
|
/**
|
|
23
31
|
* Helper function to safely check if an error is related to missing user roles
|
|
24
32
|
* Extracted from AppComponent.isNoUserRolesError()
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace-initializer.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/workspace-initializer.service.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"workspace-initializer.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/workspace-initializer.service.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAiB,MAAM,kCAAkC,CAAC;AAE/F,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAC5E,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;;AAG1G,qBAGa,2BAA2B;IAIpC,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,wBAAwB;IAChC,OAAO,CAAC,YAAY;IALtB,OAAO,CAAC,sBAAsB,CAAS;gBAG7B,QAAQ,EAAE,UAAU,EACpB,wBAAwB,EAAE,wBAAwB,EAClD,YAAY,EAAE,YAAY;IAGpC;;;OAGG;IACG,mBAAmB,CACvB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,gBAAgB,EAC1B,WAAW,EAAE,oBAAoB,GAChC,OAAO,CAAC,mBAAmB,CAAC;IAyF/B;;;OAGG;IACH,aAAa,CAAC,GAAG,EAAE,GAAG,GAAG,kBAAkB;IAsD3C;;;;;;OAMG;YACW,sBAAsB;IA6CpC;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IA+B1B;;;OAGG;IACH,OAAO,CAAC,oBAAoB;IAuB5B;;;OAGG;IACH,OAAO,CAAC,yBAAyB;IAwCjC;;;OAGG;IACG,eAAe,CAAC,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;yCAtU5E,2BAA2B;6CAA3B,2BAA2B;CA4VvC"}
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* error classification, and auth retry logic.
|
|
7
7
|
*/
|
|
8
8
|
import { Injectable } from '@angular/core';
|
|
9
|
-
import { LogStatus, Metadata } from '@memberjunction/core';
|
|
9
|
+
import { LogStatus, Metadata, RunView } from '@memberjunction/core';
|
|
10
10
|
import { setupGraphQLClient, GraphQLProviderConfigData, GraphQLDataProvider } from '@memberjunction/graphql-dataprovider';
|
|
11
11
|
import { AuthErrorType } from '@memberjunction/ng-auth-services';
|
|
12
12
|
import { SharedService } from '@memberjunction/ng-shared';
|
|
@@ -62,6 +62,7 @@ export class WorkspaceInitializerService {
|
|
|
62
62
|
// 2. Load metadata and validate user
|
|
63
63
|
await SharedService.RefreshData(true);
|
|
64
64
|
await this.themeService.Initialize();
|
|
65
|
+
await this.applyDefaultBrandTheme();
|
|
65
66
|
// This service runs the one-time app login flow and is wiring up the global
|
|
66
67
|
// Metadata.Provider via setupGraphQLClient above. There is no per-component
|
|
67
68
|
// provider scope here.
|
|
@@ -154,6 +155,58 @@ export class WorkspaceInitializerService {
|
|
|
154
155
|
shouldRetry: false
|
|
155
156
|
};
|
|
156
157
|
}
|
|
158
|
+
/**
|
|
159
|
+
* Org theming bootstrap: after metadata + ThemeService are ready, apply
|
|
160
|
+
* the brand theme the user last chose (a starred theme they swapped to), falling back
|
|
161
|
+
* to the org default. Derives the overlay via the theme engine and applies it always-on
|
|
162
|
+
* (under the user's light/dark choice). Non-fatal — a missing Theme entity (older DBs)
|
|
163
|
+
* or no theme simply leaves the stock MJ theme in place.
|
|
164
|
+
*/
|
|
165
|
+
async applyDefaultBrandTheme() {
|
|
166
|
+
try {
|
|
167
|
+
const rv = new RunView();
|
|
168
|
+
// Prefer the user's last-applied brand theme; fall back to the org default.
|
|
169
|
+
const selectedId = this.themeService.GetSelectedBrandThemeId();
|
|
170
|
+
let result = await rv.RunView({
|
|
171
|
+
EntityName: 'MJ: Themes',
|
|
172
|
+
ExtraFilter: selectedId ? `ID = '${selectedId}' AND Status = 'Active'` : "IsDefault = 1 AND Status = 'Active'",
|
|
173
|
+
MaxRows: 1,
|
|
174
|
+
ResultType: 'entity_object',
|
|
175
|
+
});
|
|
176
|
+
let theme = result.Success ? result.Results?.[0] : undefined;
|
|
177
|
+
// User's selection is gone/inactive — fall back to the org default.
|
|
178
|
+
if (!theme && selectedId) {
|
|
179
|
+
result = await rv.RunView({
|
|
180
|
+
EntityName: 'MJ: Themes',
|
|
181
|
+
ExtraFilter: "IsDefault = 1 AND Status = 'Active'",
|
|
182
|
+
MaxRows: 1,
|
|
183
|
+
ResultType: 'entity_object',
|
|
184
|
+
});
|
|
185
|
+
theme = result.Success ? result.Results?.[0] : undefined;
|
|
186
|
+
}
|
|
187
|
+
if (!theme) {
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
this.themeService.RegisterBrandTheme({
|
|
191
|
+
id: theme.ID,
|
|
192
|
+
name: theme.Name,
|
|
193
|
+
seeds: theme.Seeds,
|
|
194
|
+
description: theme.Description ?? undefined,
|
|
195
|
+
overrides: theme.Overrides ?? undefined,
|
|
196
|
+
customCss: theme.CustomCSS ?? undefined,
|
|
197
|
+
logos: {
|
|
198
|
+
lightMarkURL: theme.LightMarkURL ?? undefined,
|
|
199
|
+
darkMarkURL: theme.DarkMarkURL ?? undefined,
|
|
200
|
+
wordmarkURL: theme.WordmarkURL ?? undefined,
|
|
201
|
+
monochromeURL: theme.MonochromeURL ?? undefined,
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
await this.themeService.ApplyBrandOverlay(theme.ID);
|
|
205
|
+
}
|
|
206
|
+
catch (err) {
|
|
207
|
+
LogStatus(`Org brand theme bootstrap skipped: ${err instanceof Error ? err.message : String(err)}`);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
157
210
|
/**
|
|
158
211
|
* Helper function to safely check if an error is related to missing user roles
|
|
159
212
|
* Extracted from AppComponent.isNoUserRolesError()
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workspace-initializer.service.js","sourceRoot":"","sources":["../../../src/lib/services/workspace-initializer.service.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAY,SAAS,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,sCAAsC,CAAC;AAC1H,OAAO,EAAgC,aAAa,EAAE,MAAM,kCAAkC,CAAC;AAC/F,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAI1D,OAAO,EAAE,aAAa,EAAE,MAAM,MAAM,CAAC;;;;;AAKrC,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,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;YAEzD,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,EAAE,MAAM,EAAE,WAAW,EAAE,EAAE,CAAC,CAAC;YAC1E,MAAM,aAAa,CAAC,MAAM,CAAC,CAAC;YAE5B,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;qHAtSU,2BAA2B;gEAA3B,2BAA2B,WAA3B,2BAA2B,mBAF1B,MAAM;;iFAEP,2BAA2B;cAHvC,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB","sourcesContent":["/**\n * Workspace Initializer Service\n *\n * Extracted from MJExplorer AppComponent to make workspace initialization reusable\n * across all MemberJunction applications. Handles GraphQL setup, user validation,\n * error classification, and auth retry logic.\n */\n\nimport { Injectable } from '@angular/core';\nimport { LogError, LogStatus, Metadata } from '@memberjunction/core';\nimport { setupGraphQLClient, GraphQLProviderConfigData, GraphQLDataProvider } from '@memberjunction/graphql-dataprovider';\nimport { MJAuthBase, StandardUserInfo, AuthErrorType } from '@memberjunction/ng-auth-services';\nimport { SharedService } from '@memberjunction/ng-shared';\nimport { ThemeService } from '@memberjunction/ng-shared';\nimport { StartupValidationService } from '@memberjunction/ng-explorer-core';\nimport { WorkspaceEnvironment, WorkspaceInitResult, WorkspaceInitError } from '../models/workspace-types';\nimport { lastValueFrom } from 'rxjs';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class WorkspaceInitializerService {\n private _sessionExpiredHandled = false;\n\n constructor(\n private authBase: MJAuthBase,\n private startupValidationService: StartupValidationService,\n private themeService: ThemeService\n ) { }\n\n /**\n * Initialize workspace with authenticated user\n * Replaces all the logic from AppComponent.handleLogin()\n */\n async initializeWorkspace(\n token: string,\n userInfo: StandardUserInfo,\n environment: WorkspaceEnvironment\n ): Promise<WorkspaceInitResult> {\n if (!token) {\n return {\n success: false,\n error: {\n type: 'unknown',\n message: 'No token provided',\n userMessage: 'Authentication token is missing. Please log in again.',\n shouldRetry: false\n }\n };\n }\n\n try {\n const start = Date.now();\n\n // 1. Setup GraphQL client with token refresh callback\n const config = new GraphQLProviderConfigData(\n token,\n environment.GRAPHQL_URI,\n environment.GRAPHQL_WS_URI,\n async () => {\n // v3.0 API - clean abstraction, no provider-specific logic!\n const token = await this.authBase.refreshToken();\n return token.idToken;\n },\n environment.MJ_CORE_SCHEMA_NAME\n );\n config.OnAuthenticationError = (error: Error) => this.handleSessionExpired(error);\n\n await setupGraphQLClient(config);\n const end = Date.now();\n console.log(`[Workspace] GraphQL client setup complete: ${end - start}ms`);\n\n // Subscribe to cross-server cache invalidation events via GraphQL WebSocket\n // This enables real-time data refresh when other servers modify entities\n if (GraphQLDataProvider.Instance) {\n GraphQLDataProvider.Instance.SubscribeToCacheInvalidation();\n console.log('✓ Cache invalidation subscription active');\n }\n\n // 2. Load metadata and validate user\n await SharedService.RefreshData(true);\n await this.themeService.Initialize();\n // This service runs the one-time app login flow and is wiring up the global\n // Metadata.Provider via setupGraphQLClient above. There is no per-component\n // provider scope here.\n const md = new Metadata(); // global-provider-ok: bootstrap — wires the app's single global provider\n\n if (!md.CurrentUser) {\n return {\n success: false,\n error: {\n type: 'no_access',\n message: \"User doesn't have access to the application\",\n userMessage: \"You don't have access to the application, contact your system administrator.\",\n shouldRetry: false\n }\n };\n }\n\n // 3. Run startup validation checks (with small delay for initialization)\n setTimeout(() => {\n this.startupValidationService.validateSystemSetup();\n }, 500);\n\n // Clear any JWT retry timestamps on successful login\n localStorage.removeItem('jwt-retry-ts');\n\n return {\n success: true\n };\n } catch (err: any) {\n console.error('[Workspace] initializeWorkspace caught error:', err);\n console.error('[Workspace] Error message:', err?.message);\n console.error('[Workspace] Error stack:', err?.stack);\n if (err?.response?.errors) {\n console.error('[Workspace] GraphQL errors:', JSON.stringify(err.response.errors, null, 2));\n }\n const error = this.classifyError(err);\n console.error('[Workspace] Classified as:', error.type, '-', error.message);\n return {\n success: false,\n error\n };\n }\n }\n\n /**\n * Classify errors into actionable types\n * Replaces AppComponent error handling logic\n */\n classifyError(err: any): WorkspaceInitError {\n // Check for no-roles error first (highest priority)\n if (this.isNoUserRolesError(err)) {\n // Add the validation issue through the service\n this.startupValidationService.addNoRolesValidationIssue();\n\n return {\n type: 'no_roles',\n message: err.message || 'No user roles assigned',\n userMessage: 'Your account does not have any roles assigned. Please contact your administrator.',\n shouldRetry: false\n };\n }\n\n // Check for access denied\n if (err.message?.includes(\"don't have access\")) {\n return {\n type: 'no_access',\n message: err.message,\n userMessage: err.message,\n shouldRetry: false\n };\n }\n\n // Check for token expiration\n const authError = this.authBase.classifyError(err);\n if (authError.type === AuthErrorType.TOKEN_EXPIRED) {\n return {\n type: 'token_expired',\n message: authError.message,\n userMessage: authError.userMessage || 'Your session has expired. Please log in again.',\n shouldRetry: true\n };\n }\n\n // Network errors\n if (err.message?.includes('network') || err.message?.includes('fetch')) {\n return {\n type: 'network',\n message: err.message,\n userMessage: 'Network error. Please check your connection and try again.',\n shouldRetry: true\n };\n }\n\n // Unknown error\n return {\n type: 'unknown',\n message: err.message || 'Unknown error',\n userMessage: 'An unexpected error occurred. Please try again.',\n shouldRetry: false\n };\n }\n\n /**\n * Helper function to safely check if an error is related to missing user roles\n * Extracted from AppComponent.isNoUserRolesError()\n */\n private isNoUserRolesError(err: any): boolean {\n try {\n // Check if error has response with errors array\n if (!err || typeof err !== 'object') return false;\n\n // Check for GraphQL-style errors\n if (err.response && Array.isArray(err.response.errors)) {\n return err.response.errors.some((e: any) =>\n e && e.message && typeof e.message === 'string' &&\n e.message.includes('does not have read permissions on User Roles')\n );\n }\n\n // Check for error message directly on the error object\n if (err.message && typeof err.message === 'string') {\n const message = err.message;\n return message.includes('does not have read permissions on User Roles');\n }\n\n // Check for nested error object\n if (err.error && typeof err.error === 'object') {\n return this.isNoUserRolesError(err.error);\n }\n\n return false;\n } catch (e) {\n console.error('Error while checking for user roles error:', e);\n return false;\n }\n }\n\n /**\n * Called when token refresh fails irrecoverably mid-session.\n * Shows a brief notification overlay, then forces logout to clear caches and redirect to login.\n */\n private handleSessionExpired(error: Error): void {\n // Guard against multiple concurrent calls (e.g., parallel GraphQL requests all failing)\n if (this._sessionExpiredHandled) {\n return;\n }\n this._sessionExpiredHandled = true;\n\n console.warn('[Workspace] Session expired, forcing re-authentication:', error.message);\n\n this.showSessionExpiredOverlay();\n\n // Give the user a moment to read the message, then logout\n setTimeout(async () => {\n try {\n await this.authBase.logout();\n } catch (logoutError) {\n console.error('[Workspace] Error during forced logout:', logoutError);\n // Last resort: reload the page to clear state\n window.location.reload();\n }\n }, 3000);\n }\n\n /**\n * Creates a simple DOM overlay notifying the user their session has expired.\n * Uses inline styles so it works regardless of Angular component encapsulation.\n */\n private showSessionExpiredOverlay(): void {\n const overlay = document.createElement('div');\n overlay.setAttribute('style', [\n 'position: fixed',\n 'inset: 0',\n 'z-index: 999999',\n 'display: flex',\n 'align-items: center',\n 'justify-content: center',\n 'background: rgba(0, 0, 0, 0.6)',\n 'backdrop-filter: blur(4px)',\n ].join(';'));\n\n const card = document.createElement('div');\n card.setAttribute('style', [\n 'background: var(--mj-bg-surface, #fff)',\n 'color: var(--mj-text-primary, #333)',\n 'border-radius: 12px',\n 'padding: 32px 40px',\n 'max-width: 420px',\n 'text-align: center',\n 'box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25)',\n 'font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif',\n ].join(';'));\n\n card.innerHTML = `\n <div style=\"font-size: 40px; margin-bottom: 16px;\">\n <i class=\"fa-solid fa-clock\" style=\"color: var(--mj-status-warning, #ef6c00);\"></i>\n </div>\n <h2 style=\"margin: 0 0 8px; font-size: 20px; font-weight: 600;\">Session Expired</h2>\n <p style=\"margin: 0 0 16px; font-size: 14px; color: var(--mj-text-secondary, #666);\">\n Your session has expired. You will be redirected to log in again.\n </p>\n <div style=\"font-size: 13px; color: var(--mj-text-muted, #999);\">Redirecting...</div>\n `;\n\n overlay.appendChild(card);\n document.body.appendChild(overlay);\n }\n\n /**\n * Handle authentication retry with backoff\n * Replaces AppComponent.handleAuthRetry() logic\n */\n async handleAuthRetry(error: WorkspaceInitError, currentPath: string): Promise<boolean> {\n if (!error.shouldRetry) {\n return false;\n }\n\n const retryKey = 'auth-retry-dt';\n const lastRetryDateTime = localStorage.getItem(retryKey);\n const yesterday = +new Date(Date.now() - 1 * 24 * 60 * 60 * 1000);\n const retriedRecently = lastRetryDateTime && +new Date(lastRetryDateTime) > yesterday;\n\n if (!retriedRecently && error.type === 'token_expired') {\n LogStatus('JWT Expired, retrying once: ' + error.message);\n localStorage.setItem(retryKey, new Date().toISOString());\n\n const login$ = this.authBase.login({ appState: { target: currentPath } });\n await lastValueFrom(login$);\n\n return true;\n }\n\n return false;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"workspace-initializer.service.js","sourceRoot":"","sources":["../../../src/lib/services/workspace-initializer.service.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAY,SAAS,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAE9E,OAAO,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,sCAAsC,CAAC;AAC1H,OAAO,EAAgC,aAAa,EAAE,MAAM,kCAAkC,CAAC;AAC/F,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAI1D,OAAO,EAAE,aAAa,EAAE,MAAM,MAAM,CAAC;;;;;AAKrC,MAAM,OAAO,2BAA2B;IAI5B;IACA;IACA;IALF,sBAAsB,GAAG,KAAK,CAAC;IAEvC,YACU,QAAoB,EACpB,wBAAkD,EAClD,YAA0B;QAF1B,aAAQ,GAAR,QAAQ,CAAY;QACpB,6BAAwB,GAAxB,wBAAwB,CAA0B;QAClD,iBAAY,GA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AO,CAAC,QAAQ,CAAC,CAAC;QACzD,MAAM,SAAS,GAAG,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC;QAClE,MAAM,eAAe,GAAG,iBAAiB,IAAI,CAAC,IAAI,IAAI,CAAC,iBAAiB,CAAC,GAAG,SAAS,CAAC;QAEtF,IAAI,CAAC,eAAe,IAAI,KAAK,CAAC,IAAI,KAAK,eAAe,EAAE,CAAC;YACvD,SAAS,CAAC,8BAA8B,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC;YAC1D,YAAY,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;YAEzD,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,EAAE,MAAM,EAAE,WAAW,EAAE,EAAE,CAAC,CAAC;YAC1E,MAAM,aAAa,CAAC,MAAM,CAAC,CAAC;YAE5B,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;qHA3VU,2BAA2B;gEAA3B,2BAA2B,WAA3B,2BAA2B,mBAF1B,MAAM;;iFAEP,2BAA2B;cAHvC,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB","sourcesContent":["/**\n * Workspace Initializer Service\n *\n * Extracted from MJExplorer AppComponent to make workspace initialization reusable\n * across all MemberJunction applications. Handles GraphQL setup, user validation,\n * error classification, and auth retry logic.\n */\n\nimport { Injectable } from '@angular/core';\nimport { LogError, LogStatus, Metadata, RunView } from '@memberjunction/core';\nimport { MJThemeEntity } from '@memberjunction/core-entities';\nimport { setupGraphQLClient, GraphQLProviderConfigData, GraphQLDataProvider } from '@memberjunction/graphql-dataprovider';\nimport { MJAuthBase, StandardUserInfo, AuthErrorType } from '@memberjunction/ng-auth-services';\nimport { SharedService } from '@memberjunction/ng-shared';\nimport { ThemeService } from '@memberjunction/ng-shared';\nimport { StartupValidationService } from '@memberjunction/ng-explorer-core';\nimport { WorkspaceEnvironment, WorkspaceInitResult, WorkspaceInitError } from '../models/workspace-types';\nimport { lastValueFrom } from 'rxjs';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class WorkspaceInitializerService {\n private _sessionExpiredHandled = false;\n\n constructor(\n private authBase: MJAuthBase,\n private startupValidationService: StartupValidationService,\n private themeService: ThemeService\n ) { }\n\n /**\n * Initialize workspace with authenticated user\n * Replaces all the logic from AppComponent.handleLogin()\n */\n async initializeWorkspace(\n token: string,\n userInfo: StandardUserInfo,\n environment: WorkspaceEnvironment\n ): Promise<WorkspaceInitResult> {\n if (!token) {\n return {\n success: false,\n error: {\n type: 'unknown',\n message: 'No token provided',\n userMessage: 'Authentication token is missing. Please log in again.',\n shouldRetry: false\n }\n };\n }\n\n try {\n const start = Date.now();\n\n // 1. Setup GraphQL client with token refresh callback\n const config = new GraphQLProviderConfigData(\n token,\n environment.GRAPHQL_URI,\n environment.GRAPHQL_WS_URI,\n async () => {\n // v3.0 API - clean abstraction, no provider-specific logic!\n const token = await this.authBase.refreshToken();\n return token.idToken;\n },\n environment.MJ_CORE_SCHEMA_NAME\n );\n config.OnAuthenticationError = (error: Error) => this.handleSessionExpired(error);\n\n await setupGraphQLClient(config);\n const end = Date.now();\n console.log(`[Workspace] GraphQL client setup complete: ${end - start}ms`);\n\n // Subscribe to cross-server cache invalidation events via GraphQL WebSocket\n // This enables real-time data refresh when other servers modify entities\n if (GraphQLDataProvider.Instance) {\n GraphQLDataProvider.Instance.SubscribeToCacheInvalidation();\n console.log('✓ Cache invalidation subscription active');\n }\n\n // 2. Load metadata and validate user\n await SharedService.RefreshData(true);\n await this.themeService.Initialize();\n await this.applyDefaultBrandTheme();\n // This service runs the one-time app login flow and is wiring up the global\n // Metadata.Provider via setupGraphQLClient above. There is no per-component\n // provider scope here.\n const md = new Metadata(); // global-provider-ok: bootstrap — wires the app's single global provider\n\n if (!md.CurrentUser) {\n return {\n success: false,\n error: {\n type: 'no_access',\n message: \"User doesn't have access to the application\",\n userMessage: \"You don't have access to the application, contact your system administrator.\",\n shouldRetry: false\n }\n };\n }\n\n // 3. Run startup validation checks (with small delay for initialization)\n setTimeout(() => {\n this.startupValidationService.validateSystemSetup();\n }, 500);\n\n // Clear any JWT retry timestamps on successful login\n localStorage.removeItem('jwt-retry-ts');\n\n return {\n success: true\n };\n } catch (err: any) {\n console.error('[Workspace] initializeWorkspace caught error:', err);\n console.error('[Workspace] Error message:', err?.message);\n console.error('[Workspace] Error stack:', err?.stack);\n if (err?.response?.errors) {\n console.error('[Workspace] GraphQL errors:', JSON.stringify(err.response.errors, null, 2));\n }\n const error = this.classifyError(err);\n console.error('[Workspace] Classified as:', error.type, '-', error.message);\n return {\n success: false,\n error\n };\n }\n }\n\n /**\n * Classify errors into actionable types\n * Replaces AppComponent error handling logic\n */\n classifyError(err: any): WorkspaceInitError {\n // Check for no-roles error first (highest priority)\n if (this.isNoUserRolesError(err)) {\n // Add the validation issue through the service\n this.startupValidationService.addNoRolesValidationIssue();\n\n return {\n type: 'no_roles',\n message: err.message || 'No user roles assigned',\n userMessage: 'Your account does not have any roles assigned. Please contact your administrator.',\n shouldRetry: false\n };\n }\n\n // Check for access denied\n if (err.message?.includes(\"don't have access\")) {\n return {\n type: 'no_access',\n message: err.message,\n userMessage: err.message,\n shouldRetry: false\n };\n }\n\n // Check for token expiration\n const authError = this.authBase.classifyError(err);\n if (authError.type === AuthErrorType.TOKEN_EXPIRED) {\n return {\n type: 'token_expired',\n message: authError.message,\n userMessage: authError.userMessage || 'Your session has expired. Please log in again.',\n shouldRetry: true\n };\n }\n\n // Network errors\n if (err.message?.includes('network') || err.message?.includes('fetch')) {\n return {\n type: 'network',\n message: err.message,\n userMessage: 'Network error. Please check your connection and try again.',\n shouldRetry: true\n };\n }\n\n // Unknown error\n return {\n type: 'unknown',\n message: err.message || 'Unknown error',\n userMessage: 'An unexpected error occurred. Please try again.',\n shouldRetry: false\n };\n }\n\n /**\n * Org theming bootstrap: after metadata + ThemeService are ready, apply\n * the brand theme the user last chose (a starred theme they swapped to), falling back\n * to the org default. Derives the overlay via the theme engine and applies it always-on\n * (under the user's light/dark choice). Non-fatal — a missing Theme entity (older DBs)\n * or no theme simply leaves the stock MJ theme in place.\n */\n private async applyDefaultBrandTheme(): Promise<void> {\n try {\n const rv = new RunView();\n // Prefer the user's last-applied brand theme; fall back to the org default.\n const selectedId = this.themeService.GetSelectedBrandThemeId();\n let result = await rv.RunView<MJThemeEntity>({\n EntityName: 'MJ: Themes',\n ExtraFilter: selectedId ? `ID = '${selectedId}' AND Status = 'Active'` : \"IsDefault = 1 AND Status = 'Active'\",\n MaxRows: 1,\n ResultType: 'entity_object',\n });\n let theme = result.Success ? result.Results?.[0] : undefined;\n // User's selection is gone/inactive — fall back to the org default.\n if (!theme && selectedId) {\n result = await rv.RunView<MJThemeEntity>({\n EntityName: 'MJ: Themes',\n ExtraFilter: \"IsDefault = 1 AND Status = 'Active'\",\n MaxRows: 1,\n ResultType: 'entity_object',\n });\n theme = result.Success ? result.Results?.[0] : undefined;\n }\n if (!theme) {\n return;\n }\n this.themeService.RegisterBrandTheme({\n id: theme.ID,\n name: theme.Name,\n seeds: theme.Seeds,\n description: theme.Description ?? undefined,\n overrides: theme.Overrides ?? undefined,\n customCss: theme.CustomCSS ?? undefined,\n logos: {\n lightMarkURL: theme.LightMarkURL ?? undefined,\n darkMarkURL: theme.DarkMarkURL ?? undefined,\n wordmarkURL: theme.WordmarkURL ?? undefined,\n monochromeURL: theme.MonochromeURL ?? undefined,\n },\n });\n await this.themeService.ApplyBrandOverlay(theme.ID);\n } catch (err) {\n LogStatus(`Org brand theme bootstrap skipped: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n /**\n * Helper function to safely check if an error is related to missing user roles\n * Extracted from AppComponent.isNoUserRolesError()\n */\n private isNoUserRolesError(err: any): boolean {\n try {\n // Check if error has response with errors array\n if (!err || typeof err !== 'object') return false;\n\n // Check for GraphQL-style errors\n if (err.response && Array.isArray(err.response.errors)) {\n return err.response.errors.some((e: any) =>\n e && e.message && typeof e.message === 'string' &&\n e.message.includes('does not have read permissions on User Roles')\n );\n }\n\n // Check for error message directly on the error object\n if (err.message && typeof err.message === 'string') {\n const message = err.message;\n return message.includes('does not have read permissions on User Roles');\n }\n\n // Check for nested error object\n if (err.error && typeof err.error === 'object') {\n return this.isNoUserRolesError(err.error);\n }\n\n return false;\n } catch (e) {\n console.error('Error while checking for user roles error:', e);\n return false;\n }\n }\n\n /**\n * Called when token refresh fails irrecoverably mid-session.\n * Shows a brief notification overlay, then forces logout to clear caches and redirect to login.\n */\n private handleSessionExpired(error: Error): void {\n // Guard against multiple concurrent calls (e.g., parallel GraphQL requests all failing)\n if (this._sessionExpiredHandled) {\n return;\n }\n this._sessionExpiredHandled = true;\n\n console.warn('[Workspace] Session expired, forcing re-authentication:', error.message);\n\n this.showSessionExpiredOverlay();\n\n // Give the user a moment to read the message, then logout\n setTimeout(async () => {\n try {\n await this.authBase.logout();\n } catch (logoutError) {\n console.error('[Workspace] Error during forced logout:', logoutError);\n // Last resort: reload the page to clear state\n window.location.reload();\n }\n }, 3000);\n }\n\n /**\n * Creates a simple DOM overlay notifying the user their session has expired.\n * Uses inline styles so it works regardless of Angular component encapsulation.\n */\n private showSessionExpiredOverlay(): void {\n const overlay = document.createElement('div');\n overlay.setAttribute('style', [\n 'position: fixed',\n 'inset: 0',\n 'z-index: 999999',\n 'display: flex',\n 'align-items: center',\n 'justify-content: center',\n 'background: rgba(0, 0, 0, 0.6)',\n 'backdrop-filter: blur(4px)',\n ].join(';'));\n\n const card = document.createElement('div');\n card.setAttribute('style', [\n 'background: var(--mj-bg-surface, #fff)',\n 'color: var(--mj-text-primary, #333)',\n 'border-radius: 12px',\n 'padding: 32px 40px',\n 'max-width: 420px',\n 'text-align: center',\n 'box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25)',\n 'font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif',\n ].join(';'));\n\n card.innerHTML = `\n <div style=\"font-size: 40px; margin-bottom: 16px;\">\n <i class=\"fa-solid fa-clock\" style=\"color: var(--mj-status-warning, #ef6c00);\"></i>\n </div>\n <h2 style=\"margin: 0 0 8px; font-size: 20px; font-weight: 600;\">Session Expired</h2>\n <p style=\"margin: 0 0 16px; font-size: 14px; color: var(--mj-text-secondary, #666);\">\n Your session has expired. You will be redirected to log in again.\n </p>\n <div style=\"font-size: 13px; color: var(--mj-text-muted, #999);\">Redirecting...</div>\n `;\n\n overlay.appendChild(card);\n document.body.appendChild(overlay);\n }\n\n /**\n * Handle authentication retry with backoff\n * Replaces AppComponent.handleAuthRetry() logic\n */\n async handleAuthRetry(error: WorkspaceInitError, currentPath: string): Promise<boolean> {\n if (!error.shouldRetry) {\n return false;\n }\n\n const retryKey = 'auth-retry-dt';\n const lastRetryDateTime = localStorage.getItem(retryKey);\n const yesterday = +new Date(Date.now() - 1 * 24 * 60 * 60 * 1000);\n const retriedRecently = lastRetryDateTime && +new Date(lastRetryDateTime) > yesterday;\n\n if (!retriedRecently && error.type === 'token_expired') {\n LogStatus('JWT Expired, retrying once: ' + error.message);\n localStorage.setItem(retryKey, new Date().toISOString());\n\n const login$ = this.authBase.login({ appState: { target: currentPath } });\n await lastValueFrom(login$);\n\n return true;\n }\n\n return false;\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@memberjunction/ng-workspace-initializer",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.49.0",
|
|
4
4
|
"description": "MemberJunction: Workspace Initialization Service and Components",
|
|
5
5
|
"main": "./dist/public-api.js",
|
|
6
6
|
"typings": "./dist/public-api.d.ts",
|
|
@@ -30,13 +30,15 @@
|
|
|
30
30
|
"@angular/router": "21.1.3"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@memberjunction/core": "5.
|
|
34
|
-
"@memberjunction/
|
|
35
|
-
"@memberjunction/
|
|
36
|
-
"@memberjunction/
|
|
37
|
-
"@memberjunction/
|
|
38
|
-
"@memberjunction/ng-
|
|
39
|
-
"@memberjunction/ng-
|
|
33
|
+
"@memberjunction/core": "5.49.0",
|
|
34
|
+
"@memberjunction/core-entities": "5.49.0",
|
|
35
|
+
"@memberjunction/global": "5.49.0",
|
|
36
|
+
"@memberjunction/theme-engine": "5.49.0",
|
|
37
|
+
"@memberjunction/graphql-dataprovider": "5.49.0",
|
|
38
|
+
"@memberjunction/ng-auth-services": "5.49.0",
|
|
39
|
+
"@memberjunction/ng-explorer-core": "5.49.0",
|
|
40
|
+
"@memberjunction/ng-shared": "5.49.0",
|
|
41
|
+
"@memberjunction/ng-shared-generic": "5.49.0",
|
|
40
42
|
"rxjs": "^7.8.2",
|
|
41
43
|
"tslib": "^2.8.1"
|
|
42
44
|
},
|