-
Notifications
You must be signed in to change notification settings - Fork 125
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(troika-worker-utils): add main thread fallback when web workers …
…are not allowed When web workers are not allowed, due to either total lack of support or local restrictions e.g. CSP, this adds a fallback that runs in the main thread. Behavior should be exactly the same other than logging a warning.
- Loading branch information
Showing
3 changed files
with
89 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import Thenable from './Thenable.js' | ||
|
||
/** | ||
* Fallback for `defineWorkerModule` that behaves identically but runs in the main | ||
* thread, for when the execution environment doesn't support web workers or they | ||
* are disallowed due to e.g. CSP security restrictions. | ||
*/ | ||
export function defineMainThreadModule(options) { | ||
let moduleFunc = function(...args) { | ||
return moduleFunc._getInitResult().then(initResult => { | ||
if (typeof initResult === 'function') { | ||
return initResult(...args) | ||
} else { | ||
throw new Error('Worker module function was called but `init` did not return a callable function') | ||
} | ||
}) | ||
} | ||
moduleFunc._getInitResult = function() { | ||
// We can ignore getTransferables in main thread. TODO workerId? | ||
let {dependencies, init} = options | ||
|
||
// Resolve dependencies | ||
dependencies = Array.isArray(dependencies) ? dependencies.map(dep => | ||
dep && dep._getInitResult ? dep._getInitResult() : dep | ||
) : [] | ||
|
||
// Invoke init with the resolved dependencies | ||
let initThenable = Thenable.all(dependencies).then(deps => { | ||
return init.apply(null, deps) | ||
}) | ||
|
||
// Cache the resolved promise for subsequent calls | ||
moduleFunc._getInitResult = () => initThenable | ||
|
||
return initThenable | ||
} | ||
return moduleFunc | ||
} |