Skip to content

Commit d76e8ff

Browse files
authored
Merge pull request #140 from brionmario/bump-dependencies
fix: fix `web-worker` related issues
2 parents 583379a + 44ccb00 commit d76e8ff

File tree

13 files changed

+804
-134
lines changed

13 files changed

+804
-134
lines changed

.changeset/shy-suns-sleep.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@asgardeo/javascript': patch
3+
'@asgardeo/browser': patch
4+
'@asgardeo/react': patch
5+
---
6+
7+
fix web-worker related issues

packages/browser/esbuild.config.mjs

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
import { readFileSync } from 'fs';
2020
import * as esbuild from 'esbuild';
2121
import { createRequire } from 'module';
22-
import { fileURLToPath } from 'url';
22+
import inlineWorkerPlugin from 'esbuild-plugin-inline-worker';
2323

2424
const require = createRequire(import.meta.url);
2525
const pkg = JSON.parse(readFileSync('./package.json', 'utf8'));
@@ -36,7 +36,7 @@ const polyfillPlugin = {
3636
build.onResolve({ filter: /^crypto$/ }, () => ({
3737
path: require.resolve('crypto-browserify')
3838
}));
39-
39+
4040
// Buffer polyfill
4141
build.onResolve({ filter: /^buffer$/ }, () => ({
4242
path: require.resolve('buffer/')
@@ -71,7 +71,21 @@ const commonOptions = {
7171
}
7272
`
7373
},
74-
plugins: [polyfillPlugin]
74+
plugins: [
75+
polyfillPlugin,
76+
inlineWorkerPlugin({
77+
format: 'iife',
78+
target: 'es2020',
79+
platform: 'browser',
80+
define: {
81+
'global': 'self',
82+
'globalThis': 'self',
83+
'process.env.NODE_DEBUG': 'false',
84+
'process.version': '"16.0.0"',
85+
'process.browser': 'true'
86+
}
87+
})
88+
]
7589
};
7690

7791
await esbuild.build({

packages/browser/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@
4747
"@wso2/eslint-plugin": "catalog:",
4848
"@wso2/prettier-config": "catalog:",
4949
"esbuild": "^0.25.9",
50+
"esbuild-plugin-inline-worker": "^0.1.1",
5051
"esbuild-plugins-node-modules-polyfill": "^1.7.0",
5152
"eslint": "8.57.0",
5253
"playwright": "^1.52.0",

packages/browser/src/__legacy__/client.ts

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import {
2727
OIDCEndpoints,
2828
User,
2929
} from '@asgardeo/javascript';
30-
// import WorkerFile from '../worker';
30+
import WorkerFile from '../web.worker';
3131
import {MainThreadClient, WebWorkerClient} from './clients';
3232
import {Hooks, REFRESH_ACCESS_TOKEN_ERR0R} from './constants';
3333
import {AuthenticationHelper, SPAHelper} from './helpers';
@@ -70,8 +70,7 @@ export class AsgardeoSPAClient {
7070
protected _client: WebWorkerClientInterface | MainThreadClientInterface | undefined;
7171
protected _storage: BrowserStorage | undefined;
7272
protected _authHelper: typeof AuthenticationHelper = AuthenticationHelper;
73-
// protected _worker: new () => Worker = WorkerFile;
74-
protected _worker = null;
73+
protected _worker: new () => Worker = WorkerFile;
7574
protected _initialized: boolean = false;
7675
protected _startedInitialize: boolean = false;
7776
protected _onSignInCallback: (response: User) => void = () => null;
@@ -94,13 +93,13 @@ export class AsgardeoSPAClient {
9493
}
9594
}
9695

97-
// public instantiateWorker(worker: new () => Worker) {
98-
// if (worker) {
99-
// this._worker = worker;
100-
// } else {
101-
// this._worker = WorkerFile;
102-
// }
103-
// }
96+
public instantiateWorker(worker: new () => Worker) {
97+
if (worker) {
98+
this._worker = worker;
99+
} else {
100+
this._worker = WorkerFile;
101+
}
102+
}
104103

105104
/**
106105
* This method specifies if the `AsgardeoSPAClient` has been initialized or not.
@@ -239,7 +238,7 @@ export class AsgardeoSPAClient {
239238
this._startedInitialize = true;
240239

241240
authHelper && this.instantiateAuthHelper(authHelper);
242-
// workerFile && this.instantiateWorker(workerFile);
241+
workerFile && this.instantiateWorker(workerFile);
243242

244243
const _config = await this._client?.getConfigData();
245244

packages/browser/src/__legacy__/clients/web-worker-client.ts

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,26 @@ export const WebWorkerClient = async (
173173

174174
resolve(responseData);
175175
} else {
176-
reject(data.error ? JSON.parse(data.error) : null);
176+
let error = null;
177+
if (data.error) {
178+
try {
179+
error = JSON.parse(data.error);
180+
} catch (parseError) {
181+
// If JSON parsing fails, create a proper error object
182+
error = new AsgardeoAuthException(
183+
'SPA-WEB_WORKER_CLIENT-COM-PE01',
184+
'Worker communication error.',
185+
`Failed to parse worker error response: ${data.error}`
186+
);
187+
}
188+
} else {
189+
error = new AsgardeoAuthException(
190+
'SPA-WEB_WORKER_CLIENT-COM-UE01',
191+
'Unknown worker error.',
192+
'An unknown error occurred in the web worker.'
193+
);
194+
}
195+
reject(error);
177196
}
178197
});
179198
});
@@ -456,8 +475,8 @@ export const WebWorkerClient = async (
456475
type: GET_AUTH_URL,
457476
};
458477

459-
return communicate<ExtendedAuthorizeRequestUrlParams, AuthorizationResponse>(message).then(
460-
async (response: AuthorizationResponse) => {
478+
return communicate<ExtendedAuthorizeRequestUrlParams, AuthorizationResponse>(message)
479+
.then(async (response: AuthorizationResponse) => {
461480
if (response.pkce && config.enablePKCE) {
462481
const pkceKey: string = extractPkceStorageKeyFromState(
463482
new URL(response.authorizationURL).searchParams.get(OIDCRequestConstants.Params.STATE) ?? '',
@@ -467,8 +486,10 @@ export const WebWorkerClient = async (
467486
}
468487

469488
return Promise.resolve(response);
470-
},
471-
);
489+
})
490+
.catch(error => {
491+
return Promise.reject(error);
492+
});
472493
};
473494

474495
const requestAccessToken = async (

packages/browser/src/__legacy__/utils/message-utils.ts

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,42 @@ export class MessageUtils {
5252
delete error.toJSON;
5353
}
5454

55+
let serializedError: string;
56+
57+
try {
58+
// Handle Error objects specially
59+
if (error instanceof Error) {
60+
serializedError = JSON.stringify({
61+
name: error.name,
62+
message: error.message,
63+
stack: error.stack,
64+
// Copy any additional enumerable properties
65+
...error
66+
});
67+
} else if (typeof error === 'object' && error !== null) {
68+
// For other objects, try to stringify and fallback to a safe representation
69+
try {
70+
serializedError = JSON.stringify(error);
71+
} catch {
72+
serializedError = JSON.stringify({
73+
message: error.toString ? error.toString() : 'Unknown error',
74+
originalError: String(error)
75+
});
76+
}
77+
} else {
78+
// For primitives, stringify directly
79+
serializedError = JSON.stringify(error ?? "Unknown error");
80+
}
81+
} catch {
82+
// Final fallback if all else fails
83+
serializedError = JSON.stringify({
84+
message: 'Error serialization failed',
85+
originalError: String(error)
86+
});
87+
}
88+
5589
return {
56-
error: JSON.stringify(error ?? ""),
90+
error: serializedError,
5791
success: false
5892
};
5993
}

packages/browser/src/models/config.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,4 @@
1818

1919
import {Config} from '@asgardeo/javascript';
2020

21-
export type AsgardeoBrowserConfig = Config;
21+
export type AsgardeoBrowserConfig = Config<'sessionStorage' | 'localStorage' | 'browserMemory' | 'webWorker'>;
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* Copyright (c) 2025, WSO2 LLC. (https://www.wso2.com).
3+
*
4+
* WSO2 LLC. licenses this file to you under the Apache License,
5+
* Version 2.0 (the "License"); you may not use this file except
6+
* in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing,
12+
* software distributed under the License is distributed on an
13+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
* KIND, either express or implied. See the License for the
15+
* specific language governing permissions and limitations
16+
* under the License.
17+
*/
18+
19+
// Type declarations for worker files handled by esbuild-plugin-inline-worker
20+
21+
declare module "*.worker" {
22+
const WorkerFactory: {
23+
new (): Worker;
24+
};
25+
export default WorkerFactory;
26+
}
27+
28+
declare module "*.worker.js" {
29+
const WorkerFactory: {
30+
new (): Worker;
31+
};
32+
export default WorkerFactory;
33+
}
34+
35+
declare module "*.worker.ts" {
36+
const WorkerFactory: {
37+
new (): Worker;
38+
};
39+
export default WorkerFactory;
40+
}
41+
42+
declare module "*.worker.jsx" {
43+
const WorkerFactory: {
44+
new (): Worker;
45+
};
46+
export default WorkerFactory;
47+
}
48+
49+
declare module "*.worker.tsx" {
50+
const WorkerFactory: {
51+
new (): Worker;
52+
};
53+
export default WorkerFactory;
54+
}

packages/browser/src/web-worker.d.ts

Lines changed: 0 additions & 22 deletions
This file was deleted.

packages/browser/src/worker.ts renamed to packages/browser/src/web.worker.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,25 @@
1616
* under the License.
1717
*/
1818

19+
import { Buffer } from 'buffer/';
1920
import {AsgardeoAuthClient} from '@asgardeo/javascript';
2021
import {AuthenticationHelper, SPAHelper} from './__legacy__/helpers';
2122
import {WebWorkerClientConfig} from './__legacy__/models';
2223
import {workerReceiver} from './__legacy__/worker/worker-receiver';
2324

25+
// Set up global polyfills
26+
if (typeof self !== 'undefined' && !(self as any).Buffer) {
27+
(self as any).Buffer = Buffer;
28+
}
29+
30+
if (typeof self !== 'undefined') {
31+
if (!(self as any).global) {
32+
(self as any).global = self;
33+
}
34+
// Note: globalThis is read-only, so we don't try to override it
35+
// The esbuild config already maps globalThis to self via define
36+
}
37+
2438
workerReceiver((authClient: AsgardeoAuthClient<WebWorkerClientConfig>, spaHelper: SPAHelper<WebWorkerClientConfig>) => {
2539
return new AuthenticationHelper(authClient, spaHelper);
2640
});

0 commit comments

Comments
 (0)