[bugfix] Avoid randomness at init time to allow running on cloudflare. (#3016)

Describe what your pull request does. If appropriate, add GIFs or images
showing the before and after.

Follow up to #2987 

### Change Type

- [x] `patch` — Bug fix


### Release Notes

- Prevent using randomness API at init time, to allow importing the
tldraw package in a cloudflare worker.
This commit is contained in:
David Sheldrick 2024-03-01 15:34:16 +00:00 committed by GitHub
parent ba6cba64c6
commit 1d5a9efa17
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 12 additions and 5 deletions

View file

@ -50,8 +50,9 @@ function iOS() {
* A string that is unique per browser tab * A string that is unique per browser tab
* @public * @public
*/ */
export const TAB_ID: string = export const TAB_ID: string = window
window?.[tabIdKey] ?? window?.sessionStorage[tabIdKey] ?? `TLDRAW_INSTANCE_STATE_V1_` + uniqueId() ? window[tabIdKey] ?? window.sessionStorage[tabIdKey] ?? `TLDRAW_INSTANCE_STATE_V1_` + uniqueId()
: '<error>'
if (window) { if (window) {
window[tabIdKey] = TAB_ID window[tabIdKey] = TAB_ID
if (iOS()) { if (iOS()) {

View file

@ -240,18 +240,24 @@ const channel =
channel?.addEventListener('message', (e) => { channel?.addEventListener('message', (e) => {
const data = e.data as undefined | UserChangeBroadcastMessage const data = e.data as undefined | UserChangeBroadcastMessage
if (data?.type === broadcastEventKey && data?.origin !== broadcastOrigin) { if (data?.type === broadcastEventKey && data?.origin !== getBroadcastOrigin()) {
globalUserPreferences.set(migrateUserPreferences(data.data)) globalUserPreferences.set(migrateUserPreferences(data.data))
} }
}) })
const broadcastOrigin = uniqueId() let _broadcastOrigin = null as null | string
function getBroadcastOrigin() {
if (_broadcastOrigin === null) {
_broadcastOrigin = uniqueId()
}
return _broadcastOrigin
}
const broadcastEventKey = 'tldraw-user-preferences-change' as const const broadcastEventKey = 'tldraw-user-preferences-change' as const
function broadcastUserPreferencesChange() { function broadcastUserPreferencesChange() {
channel?.postMessage({ channel?.postMessage({
type: broadcastEventKey, type: broadcastEventKey,
origin: broadcastOrigin, origin: getBroadcastOrigin(),
data: { data: {
user: getUserPreferences(), user: getUserPreferences(),
version: userMigrations.currentVersion, version: userMigrations.currentVersion,