kritzel-stencil 0.1.47 → 0.1.48
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/cjs/{alignment.enum-D1ic11Bt.js → alignment.enum-CoTa4JOt.js} +14 -23
- package/dist/cjs/index.cjs.js +1 -1
- package/dist/cjs/kritzel-active-users_38.cjs.entry.js +5 -4
- package/dist/collection/classes/handlers/line-handle.handler.js +1 -1
- package/dist/collection/classes/handlers/move.handler.js +1 -1
- package/dist/collection/classes/handlers/resize.handler.js +3 -3
- package/dist/collection/classes/handlers/rotation.handler.js +3 -3
- package/dist/collection/classes/structures/app-state-map.structure.js +3 -1
- package/dist/collection/classes/structures/object-map.structure.js +1 -1
- package/dist/collection/constants/version.js +1 -1
- package/dist/collection/helpers/object.helper.js +6 -3
- package/dist/components/index.js +1 -1
- package/dist/components/kritzel-controls.js +1 -1
- package/dist/components/kritzel-current-user.js +1 -1
- package/dist/components/kritzel-editor.js +1 -1
- package/dist/components/kritzel-engine.js +1 -1
- package/dist/components/kritzel-menu-item.js +1 -1
- package/dist/components/kritzel-menu.js +1 -1
- package/dist/components/kritzel-more-menu.js +1 -1
- package/dist/components/kritzel-portal.js +1 -1
- package/dist/components/kritzel-settings.js +1 -1
- package/dist/components/kritzel-split-button.js +1 -1
- package/dist/components/kritzel-tool-config.js +1 -1
- package/dist/components/kritzel-workspace-manager.js +1 -1
- package/dist/components/p-BAN5dnHX.js +1 -0
- package/dist/components/{p-DU1oMYh6.js → p-C1oYQPkf.js} +1 -1
- package/dist/components/{p-DSXA1W46.js → p-C3qb7mcP.js} +1 -1
- package/dist/components/{p-CqzaRngv.js → p-CDm49CBI.js} +1 -1
- package/dist/components/{p-Cwd1kcmH.js → p-CJe-9vrE.js} +1 -1
- package/dist/components/{p-CgtCDws8.js → p-COc0ML8P.js} +1 -1
- package/dist/components/{p-D30yjVOs.js → p-CQiJ2YUG.js} +1 -1
- package/dist/components/{p-CT-XgEpj.js → p-CZxHfZG_.js} +1 -1
- package/dist/components/{p-Daul4QWI.js → p-DQqLRcKD.js} +1 -1
- package/dist/components/{p-Twjj9gUr.js → p-DgG7KGhm.js} +1 -1
- package/dist/components/{p-Bb4_LEKL.js → p-EAOKZYjL.js} +1 -1
- package/dist/components/{p-DbRfuRFb.js → p-tixOjR-m.js} +2 -2
- package/dist/esm/{alignment.enum-BetWL-f6.js → alignment.enum-BmwInKhT.js} +14 -23
- package/dist/esm/index.js +1 -1
- package/dist/esm/kritzel-active-users_38.entry.js +5 -4
- package/dist/stencil/index.esm.js +1 -1
- package/dist/stencil/p-30e1e867.entry.js +9 -0
- package/dist/stencil/p-BmwInKhT.js +1 -0
- package/dist/stencil/stencil.esm.js +1 -1
- package/dist/types/constants/version.d.ts +1 -1
- package/dist/types/helpers/object.helper.d.ts +1 -1
- package/package.json +1 -2
- package/dist/components/p-Bwbt-OqV.js +0 -1
- package/dist/stencil/p-BetWL-f6.js +0 -1
- package/dist/stencil/p-fd4ec8dc.entry.js +0 -9
|
@@ -51,22 +51,13 @@ class KritzelToolRegistry {
|
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
const urlAlphabet =
|
|
55
|
-
'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
|
|
56
|
-
|
|
57
|
-
/* @ts-self-types="./index.d.ts" */
|
|
58
|
-
let nanoid = (size = 21) => {
|
|
59
|
-
let id = '';
|
|
60
|
-
let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)));
|
|
61
|
-
while (size--) {
|
|
62
|
-
id += urlAlphabet[bytes[size] & 63];
|
|
63
|
-
}
|
|
64
|
-
return id
|
|
65
|
-
};
|
|
66
|
-
|
|
67
54
|
class ObjectHelper {
|
|
68
|
-
static generateUUID() {
|
|
69
|
-
|
|
55
|
+
static generateUUID(length = 16) {
|
|
56
|
+
const alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
57
|
+
const bytes = crypto.getRandomValues(new Uint8Array(length));
|
|
58
|
+
return Array.from(bytes)
|
|
59
|
+
.map(byte => alphabet[byte % alphabet.length])
|
|
60
|
+
.join('');
|
|
70
61
|
}
|
|
71
62
|
static isEmpty(obj) {
|
|
72
63
|
if (obj === null || obj === undefined) {
|
|
@@ -20185,7 +20176,7 @@ class KritzelMoveHandler extends KritzelBaseHandler {
|
|
|
20185
20176
|
const moveDeltaY = Math.abs(y - this.startY);
|
|
20186
20177
|
const moveThreshold = 5;
|
|
20187
20178
|
if (this.hasMoved || moveDeltaX > moveThreshold || moveDeltaY > moveThreshold) {
|
|
20188
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
20179
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
20189
20180
|
// Check for anchor disconnect threshold on lines
|
|
20190
20181
|
this.checkAndDisconnectAnchors(x, y);
|
|
20191
20182
|
selectionGroup.move(x, y, this.dragStartX, this.dragStartY);
|
|
@@ -20381,7 +20372,7 @@ class KritzelResizeHandler extends KritzelBaseHandler {
|
|
|
20381
20372
|
this.initialSize.height = selectionGroup.height;
|
|
20382
20373
|
this.initialSize.x = selectionGroup.translateX;
|
|
20383
20374
|
this.initialSize.y = selectionGroup.translateY;
|
|
20384
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
20375
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
20385
20376
|
}
|
|
20386
20377
|
}
|
|
20387
20378
|
}
|
|
@@ -20476,7 +20467,7 @@ class KritzelResizeHandler extends KritzelBaseHandler {
|
|
|
20476
20467
|
const resizeDeltaY = Math.abs(dy);
|
|
20477
20468
|
const resizeThreshold = 5;
|
|
20478
20469
|
if (resizeDeltaX > resizeThreshold || resizeDeltaY > resizeThreshold) {
|
|
20479
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
20470
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
20480
20471
|
this.hasResized = true;
|
|
20481
20472
|
}
|
|
20482
20473
|
if (!this.hasResized) {
|
|
@@ -20585,7 +20576,7 @@ class KritzelResizeHandler extends KritzelBaseHandler {
|
|
|
20585
20576
|
this._core.store.state.hasObjectsChanged = true;
|
|
20586
20577
|
}
|
|
20587
20578
|
this.reset();
|
|
20588
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
20579
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
20589
20580
|
}
|
|
20590
20581
|
}
|
|
20591
20582
|
}
|
|
@@ -20663,7 +20654,7 @@ class KritzelRotationHandler extends KritzelBaseHandler {
|
|
|
20663
20654
|
const cursorY = (clientY - this._core.store.state.translateY) / this._core.store.state.scale;
|
|
20664
20655
|
this.initialSelectionGroupRotation = selectionGroup.rotation;
|
|
20665
20656
|
this.initialRotation = Math.atan2(centerY - cursorY, centerX - cursorX) - selectionGroup.rotation;
|
|
20666
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
20657
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
20667
20658
|
}
|
|
20668
20659
|
}
|
|
20669
20660
|
}
|
|
@@ -20708,7 +20699,7 @@ class KritzelRotationHandler extends KritzelBaseHandler {
|
|
|
20708
20699
|
const currentRotation = Math.atan2(groupCenterY - cursorY, groupCenterX - cursorX);
|
|
20709
20700
|
this.rotation = currentRotation - this.initialRotation;
|
|
20710
20701
|
selectionGroup.rotate(this.rotation);
|
|
20711
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
20702
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
20712
20703
|
}
|
|
20713
20704
|
}
|
|
20714
20705
|
}
|
|
@@ -20735,7 +20726,7 @@ class KritzelRotationHandler extends KritzelBaseHandler {
|
|
|
20735
20726
|
this._core.store.state.isRotating = false;
|
|
20736
20727
|
this._core.store.state.hasObjectsChanged = true;
|
|
20737
20728
|
this.reset();
|
|
20738
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
20729
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
20739
20730
|
}
|
|
20740
20731
|
}
|
|
20741
20732
|
}
|
|
@@ -21354,7 +21345,7 @@ class KritzelLineHandleHandler extends KritzelBaseHandler {
|
|
|
21354
21345
|
if (handleType === 'start' || handleType === 'end') {
|
|
21355
21346
|
this._core.anchorManager.removeAnchor(line.id, handleType);
|
|
21356
21347
|
}
|
|
21357
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
21348
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
21358
21349
|
}
|
|
21359
21350
|
/**
|
|
21360
21351
|
* Handles pointer move events during a line handle drag operation.
|
package/dist/cjs/index.cjs.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var index = require('./index-Dc7LOVhs.js');
|
|
4
|
-
var alignment_enum = require('./alignment.enum-
|
|
4
|
+
var alignment_enum = require('./alignment.enum-CoTa4JOt.js');
|
|
5
5
|
var Y = require('yjs');
|
|
6
6
|
require('y-indexeddb');
|
|
7
7
|
|
|
@@ -20968,7 +20968,7 @@ class KritzelObjectMap {
|
|
|
20968
20968
|
const docName = core.editorId ? `kritzel-workspace-${core.editorId}-${workspaceId}` : `kritzel-workspace-${workspaceId}`;
|
|
20969
20969
|
const finalConfig = config ?? DEFAULT_SYNC_CONFIG;
|
|
20970
20970
|
// Instantiate providers from configuration
|
|
20971
|
-
const quiet = !core.store
|
|
20971
|
+
const quiet = !core.store?.state?.debugInfo?.showSyncProviderInfo;
|
|
20972
20972
|
for (const providerConfig of finalConfig.providers) {
|
|
20973
20973
|
let provider;
|
|
20974
20974
|
// Check if it's a class constructor or a factory
|
|
@@ -21779,7 +21779,8 @@ class KritzelAppStateMap {
|
|
|
21779
21779
|
// Create a dedicated Y.Doc for app state (workspaces)
|
|
21780
21780
|
this._ydoc = new Y__namespace.Doc();
|
|
21781
21781
|
this._workspacesMap = this._ydoc.getMap('workspaces');
|
|
21782
|
-
const
|
|
21782
|
+
const uuid = alignment_enum.ObjectHelper.generateUUID();
|
|
21783
|
+
const docName = core.editorId ? `kritzel-app-state-${core.editorId}-${uuid}` : `kritzel-app-state-${uuid}`;
|
|
21783
21784
|
const finalConfig = config ?? DEFAULT_SYNC_CONFIG;
|
|
21784
21785
|
// Instantiate providers from configuration
|
|
21785
21786
|
const quiet = !core.store.state.debugInfo.showSyncProviderInfo;
|
|
@@ -27514,7 +27515,7 @@ const KritzelPortal = class {
|
|
|
27514
27515
|
* This file is auto-generated by the version bump scripts.
|
|
27515
27516
|
* Do not modify manually.
|
|
27516
27517
|
*/
|
|
27517
|
-
const KRITZEL_VERSION = '0.1.
|
|
27518
|
+
const KRITZEL_VERSION = '0.1.48';
|
|
27518
27519
|
|
|
27519
27520
|
const kritzelSettingsCss = () => `:host{display:contents}kritzel-dialog{--kritzel-dialog-body-padding:0;--kritzel-dialog-width-large:800px;--kritzel-dialog-height-large:500px}.footer-button{padding:8px 16px;border-radius:6px;cursor:pointer;font-size:14px}.cancel-button{border:1px solid #ebebeb;background:#fff;color:inherit}.cancel-button:hover{background:#f5f5f5}.settings-content{padding:0}.settings-content h3{margin:0 0 16px 0;font-size:18px;font-weight:600;color:var(--kritzel-settings-content-heading-color, #333333)}.settings-content p{margin:0;font-size:14px;color:var(--kritzel-settings-content-text-color, #666666);line-height:1.5}.settings-group{display:flex;flex-direction:column;gap:24px}.settings-item{display:flex;flex-direction:column;gap:8px}.settings-row{display:flex;align-items:center;justify-content:space-between;gap:16px}.settings-label{font-size:14px;font-weight:600;color:var(--kritzel-settings-label-color, #333333);margin:0 0 4px 0}.settings-description{font-size:12px;color:var(--kritzel-settings-description-color, #888888);margin:0;line-height:1.4}.shortcuts-list{display:flex;flex-direction:column;gap:24px}.shortcuts-category{display:flex;flex-direction:column;gap:8px}.shortcuts-category-title{font-size:14px;font-weight:600;color:var(--kritzel-settings-label-color, #333333);margin:0 0 4px 0}.shortcuts-group{display:flex;flex-direction:column;gap:4px}.shortcut-item{display:flex;justify-content:space-between;align-items:center;padding:6px 8px;border-radius:4px;background:var(--kritzel-settings-shortcut-item-bg, rgba(0, 0, 0, 0.02))}.shortcut-label{font-size:14px;color:var(--kritzel-settings-content-text-color, #666666)}.shortcut-key{font-family:monospace;font-size:12px;padding:2px 8px;border-radius:4px;background:var(--kritzel-settings-shortcut-key-bg, #f0f0f0);color:var(--kritzel-settings-shortcut-key-color, #333333);border:1px solid var(--kritzel-settings-shortcut-key-border, #ddd)}`;
|
|
27520
27521
|
|
|
@@ -98,7 +98,7 @@ export class KritzelLineHandleHandler extends KritzelBaseHandler {
|
|
|
98
98
|
if (handleType === 'start' || handleType === 'end') {
|
|
99
99
|
this._core.anchorManager.removeAnchor(line.id, handleType);
|
|
100
100
|
}
|
|
101
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
101
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
102
102
|
}
|
|
103
103
|
/**
|
|
104
104
|
* Handles pointer move events during a line handle drag operation.
|
|
@@ -179,7 +179,7 @@ export class KritzelMoveHandler extends KritzelBaseHandler {
|
|
|
179
179
|
const moveDeltaY = Math.abs(y - this.startY);
|
|
180
180
|
const moveThreshold = 5;
|
|
181
181
|
if (this.hasMoved || moveDeltaX > moveThreshold || moveDeltaY > moveThreshold) {
|
|
182
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
182
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
183
183
|
// Check for anchor disconnect threshold on lines
|
|
184
184
|
this.checkAndDisconnectAnchors(x, y);
|
|
185
185
|
selectionGroup.move(x, y, this.dragStartX, this.dragStartY);
|
|
@@ -83,7 +83,7 @@ export class KritzelResizeHandler extends KritzelBaseHandler {
|
|
|
83
83
|
this.initialSize.height = selectionGroup.height;
|
|
84
84
|
this.initialSize.x = selectionGroup.translateX;
|
|
85
85
|
this.initialSize.y = selectionGroup.translateY;
|
|
86
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
86
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
87
87
|
}
|
|
88
88
|
}
|
|
89
89
|
}
|
|
@@ -178,7 +178,7 @@ export class KritzelResizeHandler extends KritzelBaseHandler {
|
|
|
178
178
|
const resizeDeltaY = Math.abs(dy);
|
|
179
179
|
const resizeThreshold = 5;
|
|
180
180
|
if (resizeDeltaX > resizeThreshold || resizeDeltaY > resizeThreshold) {
|
|
181
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
181
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
182
182
|
this.hasResized = true;
|
|
183
183
|
}
|
|
184
184
|
if (!this.hasResized) {
|
|
@@ -287,7 +287,7 @@ export class KritzelResizeHandler extends KritzelBaseHandler {
|
|
|
287
287
|
this._core.store.state.hasObjectsChanged = true;
|
|
288
288
|
}
|
|
289
289
|
this.reset();
|
|
290
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
290
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
291
291
|
}
|
|
292
292
|
}
|
|
293
293
|
}
|
|
@@ -72,7 +72,7 @@ export class KritzelRotationHandler extends KritzelBaseHandler {
|
|
|
72
72
|
const cursorY = (clientY - this._core.store.state.translateY) / this._core.store.state.scale;
|
|
73
73
|
this.initialSelectionGroupRotation = selectionGroup.rotation;
|
|
74
74
|
this.initialRotation = Math.atan2(centerY - cursorY, centerX - cursorX) - selectionGroup.rotation;
|
|
75
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
75
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
76
76
|
}
|
|
77
77
|
}
|
|
78
78
|
}
|
|
@@ -117,7 +117,7 @@ export class KritzelRotationHandler extends KritzelBaseHandler {
|
|
|
117
117
|
const currentRotation = Math.atan2(groupCenterY - cursorY, groupCenterX - cursorX);
|
|
118
118
|
this.rotation = currentRotation - this.initialRotation;
|
|
119
119
|
selectionGroup.rotate(this.rotation);
|
|
120
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
120
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
121
121
|
}
|
|
122
122
|
}
|
|
123
123
|
}
|
|
@@ -144,7 +144,7 @@ export class KritzelRotationHandler extends KritzelBaseHandler {
|
|
|
144
144
|
this._core.store.state.isRotating = false;
|
|
145
145
|
this._core.store.state.hasObjectsChanged = true;
|
|
146
146
|
this.reset();
|
|
147
|
-
clearTimeout(this._core.store.state.longTouchTimeout);
|
|
147
|
+
globalThis.clearTimeout?.(this._core.store.state.longTouchTimeout);
|
|
148
148
|
}
|
|
149
149
|
}
|
|
150
150
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as Y from "yjs";
|
|
2
2
|
import { KritzelWorkspace } from "../core/workspace.class";
|
|
3
3
|
import { DEFAULT_SYNC_CONFIG } from "../../configs/default-sync.config";
|
|
4
|
+
import { ObjectHelper } from "../../helpers/object.helper";
|
|
4
5
|
/**
|
|
5
6
|
* Manages the application state for workspaces with Yjs-based synchronization support.
|
|
6
7
|
* This class provides a synchronized map of workspaces that can be shared across
|
|
@@ -49,7 +50,8 @@ export class KritzelAppStateMap {
|
|
|
49
50
|
// Create a dedicated Y.Doc for app state (workspaces)
|
|
50
51
|
this._ydoc = new Y.Doc();
|
|
51
52
|
this._workspacesMap = this._ydoc.getMap('workspaces');
|
|
52
|
-
const
|
|
53
|
+
const uuid = ObjectHelper.generateUUID();
|
|
54
|
+
const docName = core.editorId ? `kritzel-app-state-${core.editorId}-${uuid}` : `kritzel-app-state-${uuid}`;
|
|
53
55
|
const finalConfig = config ?? DEFAULT_SYNC_CONFIG;
|
|
54
56
|
// Instantiate providers from configuration
|
|
55
57
|
const quiet = !core.store.state.debugInfo.showSyncProviderInfo;
|
|
@@ -107,7 +107,7 @@ export class KritzelObjectMap {
|
|
|
107
107
|
const docName = core.editorId ? `kritzel-workspace-${core.editorId}-${workspaceId}` : `kritzel-workspace-${workspaceId}`;
|
|
108
108
|
const finalConfig = config ?? DEFAULT_SYNC_CONFIG;
|
|
109
109
|
// Instantiate providers from configuration
|
|
110
|
-
const quiet = !core.store
|
|
110
|
+
const quiet = !core.store?.state?.debugInfo?.showSyncProviderInfo;
|
|
111
111
|
for (const providerConfig of finalConfig.providers) {
|
|
112
112
|
let provider;
|
|
113
113
|
// Check if it's a class constructor or a factory
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
import { nanoid } from "nanoid";
|
|
2
1
|
export class ObjectHelper {
|
|
3
|
-
static generateUUID() {
|
|
4
|
-
|
|
2
|
+
static generateUUID(length = 16) {
|
|
3
|
+
const alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
4
|
+
const bytes = crypto.getRandomValues(new Uint8Array(length));
|
|
5
|
+
return Array.from(bytes)
|
|
6
|
+
.map(byte => alphabet[byte % alphabet.length])
|
|
7
|
+
.join('');
|
|
5
8
|
}
|
|
6
9
|
static isEmpty(obj) {
|
|
7
10
|
if (obj === null || obj === undefined) {
|
package/dist/components/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{g as getAssetPath,r as render,s as setAssetPath,a as setNonce,b as setPlatformOptions}from"./p-pebXO4LU.js";export{f as KritzelBrushTool,d as KritzelGroup,b as KritzelImage,c as KritzelLine,g as KritzelLineTool,a as KritzelPath,j as KritzelSelectionTool,e as KritzelShape,i as KritzelShapeTool,K as KritzelText,h as KritzelTextTool,S as ShapeType}from"./p-D30yjVOs.js";export{I as IndexedDBSyncProvider,d as KritzelAlignment,c as KritzelAnchorManager,b as KritzelCursorHelper,K as KritzelEraserTool,a as KritzelImageTool}from"./p-DbRfuRFb.js";import*as t from"yjs";import{WebsocketProvider as n}from"y-websocket";export{K as KritzelWorkspace,W as WORKSPACE_EXPORT_VERSION}from"./p-AcQNA3C8.js";export{D as DEFAULT_BRUSH_CONFIG,b as DEFAULT_LINE_TOOL_CONFIG,a as DEFAULT_TEXT_CONFIG,KritzelEditor,defineCustomElement as defineCustomElementKritzelEditor}from"./kritzel-editor.js";export{K as KritzelThemeManager,d as darkTheme,l as lightTheme}from"./p-bWUahQFj.js";export{KritzelActiveUsers,defineCustomElement as defineCustomElementKritzelActiveUsers}from"./kritzel-active-users.js";export{KritzelAvatar,defineCustomElement as defineCustomElementKritzelAvatar}from"./kritzel-avatar.js";export{KritzelBackToContent,defineCustomElement as defineCustomElementKritzelBackToContent}from"./kritzel-back-to-content.js";export{KritzelBrushStyle,defineCustomElement as defineCustomElementKritzelBrushStyle}from"./kritzel-brush-style.js";export{KritzelColor,defineCustomElement as defineCustomElementKritzelColor}from"./kritzel-color.js";export{KritzelColorPalette,defineCustomElement as defineCustomElementKritzelColorPalette}from"./kritzel-color-palette.js";export{KritzelContextMenu,defineCustomElement as defineCustomElementKritzelContextMenu}from"./kritzel-context-menu.js";export{KritzelControls,defineCustomElement as defineCustomElementKritzelControls}from"./kritzel-controls.js";export{KritzelCurrentUser,defineCustomElement as defineCustomElementKritzelCurrentUser}from"./kritzel-current-user.js";export{KritzelCursorTrail,defineCustomElement as defineCustomElementKritzelCursorTrail}from"./kritzel-cursor-trail.js";export{KritzelDialog,defineCustomElement as defineCustomElementKritzelDialog}from"./kritzel-dialog.js";export{KritzelDropdown,defineCustomElement as defineCustomElementKritzelDropdown}from"./kritzel-dropdown.js";export{KritzelEngine,defineCustomElement as defineCustomElementKritzelEngine}from"./kritzel-engine.js";export{KritzelExport,defineCustomElement as defineCustomElementKritzelExport}from"./kritzel-export.js";export{KritzelFont,defineCustomElement as defineCustomElementKritzelFont}from"./kritzel-font.js";export{KritzelFontFamily,defineCustomElement as defineCustomElementKritzelFontFamily}from"./kritzel-font-family.js";export{KritzelFontSize,defineCustomElement as defineCustomElementKritzelFontSize}from"./kritzel-font-size.js";export{KritzelIcon,defineCustomElement as defineCustomElementKritzelIcon}from"./kritzel-icon.js";export{KritzelInput,defineCustomElement as defineCustomElementKritzelInput}from"./kritzel-input.js";export{KritzelLineEndings,defineCustomElement as defineCustomElementKritzelLineEndings}from"./kritzel-line-endings.js";export{KritzelMasterDetail,defineCustomElement as defineCustomElementKritzelMasterDetail}from"./kritzel-master-detail.js";export{KritzelMenu,defineCustomElement as defineCustomElementKritzelMenu}from"./kritzel-menu.js";export{KritzelMenuItem,defineCustomElement as defineCustomElementKritzelMenuItem}from"./kritzel-menu-item.js";export{KritzelMoreMenu,defineCustomElement as defineCustomElementKritzelMoreMenu}from"./kritzel-more-menu.js";export{KritzelNumericInput,defineCustomElement as defineCustomElementKritzelNumericInput}from"./kritzel-numeric-input.js";export{KritzelOpacitySlider,defineCustomElement as defineCustomElementKritzelOpacitySlider}from"./kritzel-opacity-slider.js";export{KritzelPillTabs,defineCustomElement as defineCustomElementKritzelPillTabs}from"./kritzel-pill-tabs.js";export{KritzelPortal,defineCustomElement as defineCustomElementKritzelPortal}from"./kritzel-portal.js";export{KritzelSettings,defineCustomElement as defineCustomElementKritzelSettings}from"./kritzel-settings.js";export{KritzelShapeFill,defineCustomElement as defineCustomElementKritzelShapeFill}from"./kritzel-shape-fill.js";export{KritzelShareDialog,defineCustomElement as defineCustomElementKritzelShareDialog}from"./kritzel-share-dialog.js";export{KritzelSlideToggle,defineCustomElement as defineCustomElementKritzelSlideToggle}from"./kritzel-slide-toggle.js";export{KritzelSplitButton,defineCustomElement as defineCustomElementKritzelSplitButton}from"./kritzel-split-button.js";export{KritzelStrokeSize,defineCustomElement as defineCustomElementKritzelStrokeSize}from"./kritzel-stroke-size.js";export{KritzelToolConfig,defineCustomElement as defineCustomElementKritzelToolConfig}from"./kritzel-tool-config.js";export{KritzelTooltip,defineCustomElement as defineCustomElementKritzelTooltip}from"./kritzel-tooltip.js";export{KritzelUtilityPanel,defineCustomElement as defineCustomElementKritzelUtilityPanel}from"./kritzel-utility-panel.js";export{KritzelWorkspaceManager,defineCustomElement as defineCustomElementKritzelWorkspaceManager}from"./kritzel-workspace-manager.js";const o=Math.floor,u=127,m=Number.MAX_SAFE_INTEGER;let p=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const y=()=>new p,w=t=>{const e=new Uint8Array((t=>{let e=t.cpos;for(let s=0;s<t.bufs.length;s++)e+=t.bufs[s].length;return e})(t));let s=0;for(let i=0;i<t.bufs.length;i++){const n=t.bufs[i];e.set(n,s),s+=n.length}return e.set(new Uint8Array(t.cbuf.buffer,0,t.cpos),s),e},C=(t,e)=>{const s=t.cbuf.length;t.cpos===s&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(2*s),t.cpos=0),t.cbuf[t.cpos++]=e},z=(t,e)=>{for(;e>u;)C(t,128|u&e),e=o(e/128);C(t,u&e)},E=(t,e)=>{z(t,e.byteLength),((t,e)=>{const s=t.cbuf.length,i=t.cpos,n=((t,e)=>t<e?t:e)(s-i,e.length),r=e.length-n;t.cbuf.set(e.subarray(0,n),i),t.cpos+=n,r>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(((t,e)=>t>e?t:e)(2*s,r)),t.cbuf.set(e.subarray(n)),t.cpos=r)})(t,e)},v=t=>Error(t),k=v("Unexpected end of array"),x=v("Integer out of Range");let A=class{constructor(t){this.arr=t,this.pos=0}};const T=t=>((t,e)=>{const s=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,s})(t,U(t)),U=t=>{let e=0,s=1;const i=t.arr.length;for(;t.pos<i;){const i=t.arr[t.pos++];if(e+=(i&u)*s,s*=128,i<128)return e;if(e>m)throw x}throw k};class M{doc;channel;_synced=!1;constructor(t,e,s){this.doc=e,this.channel=new BroadcastChannel(t),this.channel.onmessage=t=>{this.handleMessage(t.data)},this.doc.on("update",this.handleDocUpdate),this.broadcastSync(),setTimeout((()=>{this._synced=!0}),100),s?.quiet||console.info("BroadcastChannel Provider initialized: "+t)}handleDocUpdate=(t,e)=>{if(e!==this){const e=y();z(e,0),E(e,t),this.channel.postMessage(w(e))}};handleMessage(e){const s=(t=>new A(t))(new Uint8Array(e));switch(U(s)){case 0:const e=T(s);t.applyUpdate(this.doc,e,this);break;case 1:this.broadcastSync();break;case 2:const i=T(s),n=t.encodeStateAsUpdate(this.doc,i);if(n.length>0){const t=y();z(t,0),E(t,n),this.channel.postMessage(w(t))}}}broadcastSync(){const e=y();z(e,2),E(e,t.encodeStateVector(this.doc)),this.channel.postMessage(w(e))}async connect(){if(!this._synced)return new Promise((t=>{const e=()=>{this._synced?t():setTimeout(e,50)};e()}))}disconnect(){}destroy(){this.doc.off("update",this.handleDocUpdate),this.channel.close()}}class P{provider;isConnected=!1;_quiet=!1;constructor(t,e,s){const i=s?.url||"ws://localhost:1234",r=s?.roomName||t;this.provider=new n(i,r,e,{params:s?.params,protocols:s?.protocols,WebSocketPolyfill:s?.WebSocketPolyfill,awareness:s?.awareness,maxBackoffTime:s?.maxBackoffTime,disableBc:!0}),this._quiet=s?.quiet??!1,this.setupEventListeners(),this._quiet||console.info(`WebSocket Provider initialized: ${i}/${r}`)}static with(t){return{create:(e,s,i)=>{const n=i?{...t,...i}:t;return new P(e,s,n)}}}setupEventListeners(){this.provider.on("status",(({status:t})=>{"connected"===t?(this.isConnected=!0,this._quiet||console.info("WebSocket connected")):"disconnected"===t&&(this.isConnected=!1,this._quiet||console.info("WebSocket disconnected"))})),this.provider.on("sync",(t=>{t&&!this._quiet&&console.info("WebSocket synced")}))}async connect(){if(!this.isConnected)return new Promise(((t,e)=>{const s=setTimeout((()=>{e(Error("WebSocket connection timeout"))}),1e4),i=({status:e})=>{"connected"===e&&(clearTimeout(s),this.provider.off("status",i),this.isConnected=!0,t())};this.provider.on("status",i),this.provider.wsconnected&&(clearTimeout(s),this.provider.off("status",i),this.isConnected=!0,t())}))}disconnect(){this.provider&&this.provider.disconnect(),this.isConnected=!1}destroy(){this.provider&&this.provider.destroy(),this.isConnected=!1}}const O=Math.floor,F=127,N=Number.MAX_SAFE_INTEGER,R="undefined"!=typeof TextEncoder?new TextEncoder:null,H=R?t=>R.encode(t):t=>{const e=unescape(encodeURIComponent(t)),s=e.length,i=new Uint8Array(s);for(let t=0;t<s;t++)i[t]=e.codePointAt(t);return i};let L="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});L&&1===L.decode(new Uint8Array).length&&(L=null);const B=(t,e)=>{const s=t.cbuf.length;t.cpos===s&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(2*s),t.cpos=0),t.cbuf[t.cpos++]=e},_=(t,e)=>{for(;e>F;)B(t,128|F&e),e=O(e/128);B(t,F&e)},V=new Uint8Array(3e4),$=V.length/3,q=R&&R.encodeInto?(t,e)=>{if(e.length<$){const s=R.encodeInto(e,V).written||0;_(t,s);for(let e=0;e<s;e++)B(t,V[e])}else G(t,H(e))}:(t,e)=>{const s=unescape(encodeURIComponent(e)),i=s.length;_(t,i);for(let e=0;e<i;e++)B(t,s.codePointAt(e))},G=(t,e)=>{_(t,e.byteLength),((t,e)=>{const s=t.cbuf.length,i=t.cpos,n=((t,e)=>t<e?t:e)(s-i,e.length),r=e.length-n;t.cbuf.set(e.subarray(0,n),i),t.cpos+=n,r>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(((t,e)=>t>e?t:e)(2*s,r)),t.cbuf.set(e.subarray(n)),t.cpos=r)})(t,e)},J=t=>Error(t),Q=J("Unexpected end of array"),X=J("Integer out of Range"),Y=t=>t.arr[t.pos++],Z=t=>{let e=0,s=1;const i=t.arr.length;for(;t.pos<i;){const i=t.arr[t.pos++];if(e+=(i&F)*s,s*=128,i<128)return e;if(e>N)throw X}throw Q},tt=L?t=>L.decode((t=>((t,e)=>{const s=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,s})(t,Z(t)))(t)):t=>{let e=Z(t);if(0===e)return"";{let s=String.fromCodePoint(Y(t));if(--e<100)for(;e--;)s+=String.fromCodePoint(Y(t));else for(;e>0;){const i=e<1e4?e:1e4,n=t.arr.subarray(t.pos,t.pos+i);t.pos+=i,s+=String.fromCodePoint.apply(null,n),e-=i}return decodeURIComponent(escape(s))}};var et;!function(t){t[t.Token=0]="Token",t[t.PermissionDenied=1]="PermissionDenied",t[t.Authenticated=2]="Authenticated"}(et||(et={}));const st=t=>Array.from(t.entries()).map((([t,e])=>({clientId:t,...e})));var it;async function nt(t){return new Promise((e=>setTimeout(e,t)))}function rt(t,e){let s=e.delay;if(0===s)return 0;if(e.factor&&(s*=Math.pow(e.factor,t.attemptNum-1),0!==e.maxDelay&&(s=Math.min(s,e.maxDelay))),e.jitter){const t=Math.ceil(e.minDelay),i=Math.floor(s);s=Math.floor(Math.random()*(i-t+1))+t}return Math.round(s)}!function(t){t[t.Connecting=0]="Connecting",t[t.Open=1]="Open",t[t.Closing=2]="Closing",t[t.Closed=3]="Closed"}(it||(it={}));const ot=Math.floor,ht=128,at=127,lt=Number.MAX_SAFE_INTEGER,ct=()=>new Set,ut=Array.from,dt="undefined"!=typeof TextEncoder?new TextEncoder:null,mt=dt?t=>dt.encode(t):t=>{const e=unescape(encodeURIComponent(t)),s=e.length,i=new Uint8Array(s);for(let t=0;t<s;t++)i[t]=e.codePointAt(t);return i};let ft="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ft&&1===ft.decode(new Uint8Array).length&&(ft=null);class pt{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const yt=()=>new pt,gt=t=>{let e=t.cpos;for(let s=0;s<t.bufs.length;s++)e+=t.bufs[s].length;return e},wt=t=>{const e=new Uint8Array(gt(t));let s=0;for(let i=0;i<t.bufs.length;i++){const n=t.bufs[i];e.set(n,s),s+=n.length}return e.set(new Uint8Array(t.cbuf.buffer,0,t.cpos),s),e},Ct=(t,e)=>{const s=t.cbuf.length;t.cpos===s&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(2*s),t.cpos=0),t.cbuf[t.cpos++]=e},zt=(t,e)=>{for(;e>at;)Ct(t,ht|at&e),e=ot(e/128);Ct(t,at&e)},Et=new Uint8Array(3e4),vt=Et.length/3,kt=dt&&dt.encodeInto?(t,e)=>{if(e.length<vt){const s=dt.encodeInto(e,Et).written||0;zt(t,s);for(let e=0;e<s;e++)Ct(t,Et[e])}else Kt(t,mt(e))}:(t,e)=>{const s=unescape(encodeURIComponent(e)),i=s.length;zt(t,i);for(let e=0;e<i;e++)Ct(t,s.codePointAt(e))},Kt=(t,e)=>{zt(t,e.byteLength),((t,e)=>{const s=t.cbuf.length,i=t.cpos,n=((t,e)=>t<e?t:e)(s-i,e.length),r=e.length-n;t.cbuf.set(e.subarray(0,n),i),t.cpos+=n,r>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(((t,e)=>t>e?t:e)(2*s,r)),t.cbuf.set(e.subarray(n)),t.cpos=r)})(t,e)},St=t=>Error(t),xt=St("Unexpected end of array"),At=St("Integer out of Range");class bt{constructor(t){this.arr=t,this.pos=0}}const Tt=t=>new bt(t),Ut=t=>((t,e)=>{const s=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,s})(t,Mt(t)),jt=t=>t.arr[t.pos++],Mt=t=>{let e=0,s=1;const i=t.arr.length;for(;t.pos<i;){const i=t.arr[t.pos++];if(e+=(i&at)*s,s*=128,i<ht)return e;if(e>lt)throw At}throw xt},Dt=ft?t=>ft.decode(Ut(t)):t=>{let e=Mt(t);if(0===e)return"";{let s=String.fromCodePoint(jt(t));if(--e<100)for(;e--;)s+=String.fromCodePoint(jt(t));else for(;e>0;){const i=e<1e4?e:1e4,n=t.arr.subarray(t.pos,t.pos+i);t.pos+=i,s+=String.fromCodePoint.apply(null,n),e-=i}return decodeURIComponent(escape(s))}},Pt=Date.now,It=()=>new Map;class Ot{constructor(){this._observers=It()}on(t,e){((t,e,s)=>{let i=t.get(e);return void 0===i&&t.set(e,i=s()),i})(this._observers,t,ct).add(e)}once(t,e){const s=(...i)=>{this.off(t,s),e(...i)};this.on(t,s)}off(t,e){const s=this._observers.get(t);void 0!==s&&(s.delete(e),0===s.size&&this._observers.delete(t))}emit(t,e){return ut((this._observers.get(t)||It()).values()).forEach((t=>t(...e)))}destroy(){this._observers=It()}}const Ft=Object.keys,Nt=t=>Ft(t).length,Wt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Rt=(t,e)=>{if(null==t||null==e)return((t,e)=>t===e)(t,e);if(t.constructor!==e.constructor)return!1;if(t===e)return!0;switch(t.constructor){case ArrayBuffer:t=new Uint8Array(t),e=new Uint8Array(e);case Uint8Array:if(t.byteLength!==e.byteLength)return!1;for(let s=0;s<t.length;s++)if(t[s]!==e[s])return!1;break;case Set:if(t.size!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;break;case Map:if(t.size!==e.size)return!1;for(const s of t.keys())if(!e.has(s)||!Rt(t.get(s),e.get(s)))return!1;break;case Object:if(Nt(t)!==Nt(e))return!1;for(const s in t)if(!Wt(t,s)||!Rt(t[s],e[s]))return!1;break;case Array:if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!Rt(t[s],e[s]))return!1;break;default:return!1}return!0};class Ht extends Ot{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval((()=>{const t=Pt();null!==this.getLocalState()&&15e3<=t-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const e=[];this.meta.forEach(((s,i)=>{i!==this.clientID&&3e4<=t-s.lastUpdated&&this.states.has(i)&&e.push(i)})),e.length>0&&Lt(this,e,"timeout")}),ot(3e3)),t.on("destroy",(()=>{this.destroy()})),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const e=this.clientID,s=this.meta.get(e),i=void 0===s?0:s.clock+1,n=this.states.get(e);null===t?this.states.delete(e):this.states.set(e,t),this.meta.set(e,{clock:i,lastUpdated:Pt()});const r=[],o=[],h=[],a=[];null===t?a.push(e):null==n?null!=t&&r.push(e):(o.push(e),Rt(n,t)||h.push(e)),(r.length>0||h.length>0||a.length>0)&&this.emit("change",[{added:r,updated:h,removed:a},"local"]),this.emit("update",[{added:r,updated:o,removed:a},"local"])}setLocalStateField(t,e){const s=this.getLocalState();null!==s&&this.setLocalState({...s,[t]:e})}getStates(){return this.states}}const Lt=(t,e,s)=>{const i=[];for(let s=0;s<e.length;s++){const n=e[s];if(t.states.has(n)){if(t.states.delete(n),n===t.clientID){const e=t.meta.get(n);t.meta.set(n,{clock:e.clock+1,lastUpdated:Pt()})}i.push(n)}}i.length>0&&(t.emit("change",[{added:[],updated:[],removed:i},s]),t.emit("update",[{added:[],updated:[],removed:i},s]))},Bt=(t,e,s=t.states)=>{const i=e.length,n=yt();zt(n,i);for(let r=0;r<i;r++){const i=e[r],o=s.get(i)||null,h=t.meta.get(i).clock;zt(n,i),zt(n,h),kt(n,JSON.stringify(o))}return wt(n)};class _t{constructor(){this.callbacks={}}on(t,e){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(e),this}emit(t,...e){const s=this.callbacks[t];return s&&s.forEach((t=>t.apply(this,e))),this}off(t,e){const s=this.callbacks[t];return s&&(e?this.callbacks[t]=s.filter((t=>t!==e)):delete this.callbacks[t]),this}removeAllListeners(){this.callbacks={}}}class Vt{constructor(t){this.data=t,this.encoder=yt(),this.decoder=Tt(new Uint8Array(this.data))}peekVarString(){return(t=>{const e=t.pos,s=Dt(t);return t.pos=e,s})(this.decoder)}readVarUint(){return Mt(this.decoder)}readVarString(){return Dt(this.decoder)}readVarUint8Array(){return Ut(this.decoder)}writeVarUint(t){return zt(this.encoder,t)}writeVarString(t){return kt(this.encoder,t)}writeVarUint8Array(t){return Kt(this.encoder,t)}length(){return gt(this.encoder)}}var $t,qt;!function(t){t[t.Sync=0]="Sync",t[t.Awareness=1]="Awareness",t[t.Auth=2]="Auth",t[t.QueryAwareness=3]="QueryAwareness",t[t.Stateless=5]="Stateless",t[t.CLOSE=7]="CLOSE",t[t.SyncStatus=8]="SyncStatus"}($t||($t={})),function(t){t.Connecting="connecting",t.Connected="connected",t.Disconnected="disconnected"}(qt||(qt={}));class Gt{constructor(){this.encoder=yt()}get(t){return t.encoder}toUint8Array(){return wt(this.encoder)}}class Jt extends Gt{constructor(){super(...arguments),this.type=$t.CLOSE,this.description="Ask the server to close the connection"}get(t){return kt(this.encoder,t.documentName),zt(this.encoder,this.type),this.encoder}}class Qt extends _t{constructor(t){super(),this.messageQueue=[],this.configuration={url:"",autoConnect:!0,preserveTrailingSlash:!1,document:void 0,WebSocketPolyfill:void 0,messageReconnectTimeout:3e4,delay:1e3,initialDelay:0,factor:2,maxAttempts:0,minDelay:1e3,maxDelay:3e4,jitter:!0,timeout:0,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,handleTimeout:null,providerMap:new Map},this.webSocket=null,this.webSocketHandlers={},this.shouldConnect=!0,this.status=qt.Disconnected,this.lastMessageReceived=0,this.identifier=0,this.intervals={connectionChecker:null},this.connectionAttempt=null,this.receivedOnOpenPayload=void 0,this.closeTries=0,this.setConfiguration(t),this.configuration.WebSocketPolyfill=t.WebSocketPolyfill?t.WebSocketPolyfill:WebSocket,this.on("open",this.configuration.onOpen),this.on("open",this.onOpen.bind(this)),this.on("connect",this.configuration.onConnect),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("status",this.configuration.onStatus),this.on("disconnect",this.configuration.onDisconnect),this.on("close",this.configuration.onClose),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("close",this.onClose.bind(this)),this.on("message",this.onMessage.bind(this)),this.intervals.connectionChecker=setInterval(this.checkConnection.bind(this),this.configuration.messageReconnectTimeout/10),this.shouldConnect&&this.connect()}async onOpen(t){this.status=qt.Connected,this.emit("status",{status:qt.Connected}),this.cancelWebsocketRetry=void 0,this.receivedOnOpenPayload=t}attach(t){this.configuration.providerMap.set(t.configuration.name,t),this.status===qt.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===qt.Connected&&t.onOpen(this.receivedOnOpenPayload)}detach(t){this.configuration.providerMap.has(t.configuration.name)&&(t.send(Jt,{documentName:t.configuration.name}),this.configuration.providerMap.delete(t.configuration.name))}setConfiguration(t={}){this.configuration={...this.configuration,...t},this.configuration.autoConnect||(this.shouldConnect=!1)}async connect(){if(this.status===qt.Connected)return;this.cancelWebsocketRetry&&(this.cancelWebsocketRetry(),this.cancelWebsocketRetry=void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;const{retryPromise:t,cancelFunc:e}=(()=>{let t=!1;return{retryPromise:async function(t,e){const s=function(t){return t||(t={}),{delay:void 0===t.delay?200:t.delay,initialDelay:void 0===t.initialDelay?0:t.initialDelay,minDelay:void 0===t.minDelay?0:t.minDelay,maxDelay:void 0===t.maxDelay?0:t.maxDelay,factor:void 0===t.factor?0:t.factor,maxAttempts:void 0===t.maxAttempts?3:t.maxAttempts,timeout:void 0===t.timeout?0:t.timeout,jitter:!0===t.jitter,initialJitter:!0===t.initialJitter,handleError:void 0===t.handleError?null:t.handleError,handleTimeout:void 0===t.handleTimeout?null:t.handleTimeout,beforeAttempt:void 0===t.beforeAttempt?null:t.beforeAttempt,calculateDelay:void 0===t.calculateDelay?null:t.calculateDelay}}(e);for(const t of["delay","initialDelay","minDelay","maxDelay","maxAttempts","timeout"]){const e=s[t];if(!Number.isInteger(e)||e<0)throw Error(`Value for ${t} must be an integer greater than or equal to 0`)}if(s.factor.constructor!==Number||s.factor<0)throw Error("Value for factor must be a number greater than or equal to 0");if(s.delay<s.minDelay)throw Error(`delay cannot be less than minDelay (delay: ${s.delay}, minDelay: ${s.minDelay}`);const i={attemptNum:0,attemptsRemaining:s.maxAttempts?s.maxAttempts:-1,aborted:!1,abort(){i.aborted=!0}},n=s.calculateDelay||rt,r=s.calculateDelay?s.calculateDelay(i,s):s.initialDelay;if(r&&await nt(r),i.attemptNum<1&&s.initialJitter){const t=n(i,s);t&&await nt(t)}return async function e(){if(s.beforeAttempt&&s.beforeAttempt(i,s),i.aborted){const t=Error("Attempt aborted");throw t.code="ATTEMPT_ABORTED",t}const r=async t=>{if(s.handleError&&await s.handleError(t,i,s),i.aborted||0===i.attemptsRemaining)throw t;i.attemptNum++;const r=n(i,s);return r&&await nt(r),e()};return i.attemptsRemaining>0&&i.attemptsRemaining--,s.timeout?new Promise(((e,n)=>{const o=setTimeout((()=>{if(s.handleTimeout)try{e(s.handleTimeout(i,s))}catch(t){n(t)}else{const t=Error(`Retry timeout (attemptNum: ${i.attemptNum}, timeout: ${s.timeout})`);t.code="ATTEMPT_TIMEOUT",n(t)}}),s.timeout);t(i,s).then((t=>{clearTimeout(o),e(t)})).catch((t=>{clearTimeout(o),r(t).then(e).catch(n)}))})):t(i,s).catch(r)}()}(this.createWebSocketConnection.bind(this),{delay:this.configuration.delay,initialDelay:this.configuration.initialDelay,factor:this.configuration.factor,maxAttempts:this.configuration.maxAttempts,minDelay:this.configuration.minDelay,maxDelay:this.configuration.maxDelay,jitter:this.configuration.jitter,timeout:this.configuration.timeout,handleTimeout:this.configuration.handleTimeout,beforeAttempt:e=>{this.shouldConnect&&!t||e.abort()}}).catch((t=>{if(t&&"ATTEMPT_ABORTED"!==t.code)throw t})),cancelFunc:()=>{t=!0}}})();return this.cancelWebsocketRetry=e,t}attachWebSocketListeners(t,e){const{identifier:s}=t;this.webSocketHandlers[s]={message:t=>this.emit("message",t),close:t=>this.emit("close",{event:t}),open:t=>this.emit("open",t),error:t=>{e(t)}};const i=this.webSocketHandlers[t.identifier];Object.keys(i).forEach((e=>{t.addEventListener(e,i[e])}))}cleanupWebSocket(){if(!this.webSocket)return;const{identifier:t}=this.webSocket,e=this.webSocketHandlers[t];Object.keys(e).forEach((s=>{var i;null===(i=this.webSocket)||void 0===i||i.removeEventListener(s,e[s]),delete this.webSocketHandlers[t]})),this.webSocket.close(),this.webSocket=null}createWebSocketConnection(){return new Promise(((t,e)=>{this.webSocket&&(this.messageQueue=[],this.cleanupWebSocket()),this.lastMessageReceived=0,this.identifier+=1;const s=new this.configuration.WebSocketPolyfill(this.url);s.binaryType="arraybuffer",s.identifier=this.identifier,this.attachWebSocketListeners(s,e),this.webSocket=s,this.status=qt.Connecting,this.emit("status",{status:qt.Connecting}),this.connectionAttempt={resolve:t,reject:e}}))}onMessage(t){var e;this.resolveConnectionAttempt(),this.lastMessageReceived=Pt();const s=new Vt(t.data).peekVarString();null===(e=this.configuration.providerMap.get(s))||void 0===e||e.onMessage(t)}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=qt.Connected,this.emit("status",{status:qt.Connected}),this.emit("connect"),this.messageQueue.forEach((t=>this.send(t))),this.messageQueue=[])}stopConnectionAttempt(){this.connectionAttempt=null}rejectConnectionAttempt(){var t;null===(t=this.connectionAttempt)||void 0===t||t.reject(),this.connectionAttempt=null}checkConnection(){var t;this.status===qt.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=Pt()-this.lastMessageReceived||(this.closeTries+=1,this.closeTries>2?(this.onClose({event:{code:4408,reason:"forced"}}),this.closeTries=0):(null===(t=this.webSocket)||void 0===t||t.close(),this.messageQueue=[])))}get serverUrl(){if(this.configuration.preserveTrailingSlash)return this.configuration.url;let t=this.configuration.url;for(;"/"===t[t.length-1];)t=t.slice(0,t.length-1);return t}get url(){return this.serverUrl}disconnect(){if(this.shouldConnect=!1,null!==this.webSocket)try{this.webSocket.close(),this.messageQueue=[]}catch(t){console.error(t)}}send(t){var e;(null===(e=this.webSocket)||void 0===e?void 0:e.readyState)===it.Open?this.webSocket.send(t):this.messageQueue.push(t)}onClose({event:t}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=qt.Disconnected,this.emit("status",{status:qt.Disconnected}),this.emit("disconnect",{event:t}),!this.cancelWebsocketRetry&&this.shouldConnect&&setTimeout((()=>{this.connect()}),this.configuration.delay)}destroy(){this.emit("destroy"),clearInterval(this.intervals.connectionChecker),this.stopConnectionAttempt(),this.disconnect(),this.removeAllListeners(),this.cleanupWebSocket()}}const Xt=(e,s,i)=>{try{t.applyUpdate(s,Ut(e),i)}catch(t){console.error("Caught error while handling a Yjs update",t)}},Yt=Xt;class Zt{constructor(t){this.message=t}apply(t,e){const{message:s}=this,i=s.readVarUint(),n=s.length();switch(i){case $t.Sync:this.applySyncMessage(t,e);break;case $t.Awareness:this.applyAwarenessMessage(t);break;case $t.Auth:this.applyAuthMessage(t);break;case $t.QueryAwareness:this.applyQueryAwarenessMessage(t);break;case $t.Stateless:t.receiveStateless(Dt(s.decoder));break;case $t.SyncStatus:this.applySyncStatusMessage(t,1===(t=>{let e=t.arr[t.pos++],s=63&e,i=64;const n=(64&e)>0?-1:1;if(!(e&ht))return n*s;const r=t.arr.length;for(;t.pos<r;){if(e=t.arr[t.pos++],s+=(e&at)*i,i*=128,e<ht)return n*s;if(s>lt)throw At}throw xt})(s.decoder));break;case $t.CLOSE:const n={code:1e3,reason:Dt(s.decoder),target:t.configuration.websocketProvider.webSocket,type:"close"};t.onClose(),t.configuration.onClose({event:n}),t.forwardClose({event:n});break;default:throw Error("Can’t apply message of unknown type: "+i)}s.length()>n+1&&t.send(Gt,{encoder:s.encoder})}applySyncMessage(e,s){const{message:i}=this;i.writeVarUint($t.Sync);const n=((e,s,i,n)=>{const r=Mt(e);switch(r){case 0:((e,s,i)=>{((e,s,i)=>{zt(e,1),Kt(e,t.encodeStateAsUpdate(s,i))})(s,i,Ut(e))})(e,s,i);break;case 1:Xt(e,i,n);break;case 2:Yt(e,i,n);break;default:throw Error("Unknown message type")}return r})(i.decoder,i.encoder,e.document,e);s&&1===n&&(e.synced=!0)}applySyncStatusMessage(t,e){e&&t.decrementUnsyncedChanges()}applyAwarenessMessage(t){if(!t.awareness)return;const{message:e}=this;((t,e,s)=>{const i=Tt(e),n=Pt(),r=[],o=[],h=[],a=[],l=Mt(i);for(let e=0;e<l;e++){const e=Mt(i);let s=Mt(i);const l=JSON.parse(Dt(i)),c=t.meta.get(e),u=t.states.get(e),d=void 0===c?0:c.clock;(d<s||d===s&&null===l&&t.states.has(e))&&(null===l?e===t.clientID&&null!=t.getLocalState()?s++:t.states.delete(e):t.states.set(e,l),t.meta.set(e,{clock:s,lastUpdated:n}),void 0===c&&null!==l?r.push(e):void 0!==c&&null===l?a.push(e):null!==l&&(Rt(l,u)||h.push(e),o.push(e)))}(r.length>0||h.length>0||a.length>0)&&t.emit("change",[{added:r,updated:h,removed:a},s]),(r.length>0||o.length>0||a.length>0)&&t.emit("update",[{added:r,updated:o,removed:a},s])})(t.awareness,e.readVarUint8Array(),t)}applyAuthMessage(t){const{message:e}=this;((t,e,s,i)=>{switch(Z(t)){case et.Token:e();break;case et.PermissionDenied:s(tt(t));break;case et.Authenticated:i(tt(t))}})(e.decoder,t.sendToken.bind(t),t.permissionDeniedHandler.bind(t),t.authenticatedHandler.bind(t))}applyQueryAwarenessMessage(t){if(!t.awareness)return;const{message:e}=this;e.writeVarUint($t.Awareness),e.writeVarUint8Array(Bt(t.awareness,Array.from(t.awareness.getStates().keys())))}}class te{constructor(t,e={}){this.message=new t,this.encoder=this.message.get(e)}create(){return wt(this.encoder)}send(t){null==t||t.send(this.create())}}class ee extends Gt{constructor(){super(...arguments),this.type=$t.Auth,this.description="Authentication"}get(t){if(void 0===t.token)throw Error("The authentication message requires `token` as an argument.");return kt(this.encoder,t.documentName),zt(this.encoder,this.type),((t,e)=>{_(t,et.Token),q(t,e)})(this.encoder,t.token),this.encoder}}class se extends Gt{constructor(){super(...arguments),this.type=$t.Awareness,this.description="Awareness states update"}get(t){if(void 0===t.awareness)throw Error("The awareness message requires awareness as an argument");if(void 0===t.clients)throw Error("The awareness message requires clients as an argument");let e;return kt(this.encoder,t.documentName),zt(this.encoder,this.type),e=void 0===t.states?Bt(t.awareness,t.clients):Bt(t.awareness,t.clients,t.states),Kt(this.encoder,e),this.encoder}}class ie extends Gt{constructor(){super(...arguments),this.type=$t.Stateless,this.description="A stateless message"}get(t){var e;return kt(this.encoder,t.documentName),zt(this.encoder,this.type),kt(this.encoder,null!==(e=t.payload)&&void 0!==e?e:""),this.encoder}}class ne extends Gt{constructor(){super(...arguments),this.type=$t.Sync,this.description="First sync step"}get(e){if(void 0===e.document)throw Error("The sync step one message requires document as an argument");return kt(this.encoder,e.documentName),zt(this.encoder,this.type),((e,s)=>{zt(e,0);const i=t.encodeStateVector(s);Kt(e,i)})(this.encoder,e.document),this.encoder}}class re extends Gt{constructor(){super(...arguments),this.type=$t.Sync,this.description="A document update"}get(t){return kt(this.encoder,t.documentName),zt(this.encoder,this.type),((t,e)=>{zt(t,2),Kt(t,e)})(this.encoder,t.update),this.encoder}}class oe extends Error{constructor(){super(...arguments),this.code=1001}}class he extends _t{constructor(e){var s,i,n;super(),this.configuration={name:"",document:void 0,awareness:void 0,token:null,forceSyncInterval:!1,onAuthenticated:()=>null,onAuthenticationFailed:()=>null,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onSynced:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,onStateless:()=>null,onUnsyncedChanges:()=>null},this.isSynced=!1,this.unsyncedChanges=0,this.isAuthenticated=!1,this.authorizedScope=void 0,this.manageSocket=!1,this._isAttached=!1,this.intervals={forceSync:null},this.boundDocumentUpdateHandler=this.documentUpdateHandler.bind(this),this.boundAwarenessUpdateHandler=this.awarenessUpdateHandler.bind(this),this.boundPageHide=this.pageHide.bind(this),this.boundOnOpen=this.onOpen.bind(this),this.boundOnClose=this.onClose.bind(this),this.forwardConnect=()=>this.emit("connect"),this.forwardStatus=t=>this.emit("status",t),this.forwardClose=t=>this.emit("close",t),this.forwardDisconnect=t=>this.emit("disconnect",t),this.forwardDestroy=()=>this.emit("destroy"),this.setConfiguration(e),this.configuration.document=e.document?e.document:new t.Doc,this.configuration.awareness=void 0!==e.awareness?e.awareness:new Ht(this.document),this.on("open",this.configuration.onOpen),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("synced",this.configuration.onSynced),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("stateless",this.configuration.onStateless),this.on("unsyncedChanges",this.configuration.onUnsyncedChanges),this.on("authenticated",this.configuration.onAuthenticated),this.on("authenticationFailed",this.configuration.onAuthenticationFailed),null===(s=this.awareness)||void 0===s||s.on("update",(()=>{this.emit("awarenessUpdate",{states:st(this.awareness.getStates())})})),null===(i=this.awareness)||void 0===i||i.on("change",(()=>{this.emit("awarenessChange",{states:st(this.awareness.getStates())})})),this.document.on("update",this.boundDocumentUpdateHandler),null===(n=this.awareness)||void 0===n||n.on("update",this.boundAwarenessUpdateHandler),this.registerEventListeners(),this.configuration.forceSyncInterval&&"number"==typeof this.configuration.forceSyncInterval&&(this.intervals.forceSync=setInterval(this.forceSync.bind(this),this.configuration.forceSyncInterval)),this.manageSocket&&this.attach()}setConfiguration(t={}){t.websocketProvider||(this.manageSocket=!0,this.configuration.websocketProvider=new Qt(t)),this.configuration={...this.configuration,...t}}get document(){return this.configuration.document}get isAttached(){return this._isAttached}get awareness(){return this.configuration.awareness}get hasUnsyncedChanges(){return this.unsyncedChanges>0}resetUnsyncedChanges(){this.unsyncedChanges=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}incrementUnsyncedChanges(){this.unsyncedChanges+=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}decrementUnsyncedChanges(){this.unsyncedChanges>0&&(this.unsyncedChanges-=1),0===this.unsyncedChanges&&(this.synced=!0),this.emit("unsyncedChanges",{number:this.unsyncedChanges})}forceSync(){this.resetUnsyncedChanges(),this.send(ne,{document:this.document,documentName:this.configuration.name})}pageHide(){this.awareness&&Lt(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){"undefined"!=typeof window&&"addEventListener"in window&&window.addEventListener("pagehide",this.boundPageHide)}sendStateless(t){this.send(ie,{documentName:this.configuration.name,payload:t})}async sendToken(){let t;try{t=await this.getToken()}catch(t){return void this.permissionDeniedHandler("Failed to get token during sendToken(): "+t)}this.send(ee,{token:null!=t?t:"",documentName:this.configuration.name})}documentUpdateHandler(t,e){e!==this&&(this.incrementUnsyncedChanges(),this.send(re,{update:t,documentName:this.configuration.name}))}awarenessUpdateHandler({added:t,updated:e,removed:s},i){const n=t.concat(e).concat(s);this.send(se,{awareness:this.awareness,clients:n,documentName:this.configuration.name})}get synced(){return this.isSynced}set synced(t){this.isSynced!==t&&(this.isSynced=t,t&&this.emit("synced",{state:t}))}receiveStateless(t){this.emit("stateless",{payload:t})}async connect(){if(this.manageSocket)return this.configuration.websocketProvider.connect();console.warn("HocuspocusProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.")}disconnect(){if(this.manageSocket)return this.configuration.websocketProvider.disconnect();console.warn("HocuspocusProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.")}async onOpen(t){this.isAuthenticated=!1,this.emit("open",{event:t}),await this.sendToken(),this.startSync()}async getToken(){return"function"==typeof this.configuration.token?await this.configuration.token():this.configuration.token}startSync(){this.resetUnsyncedChanges(),this.send(ne,{document:this.document,documentName:this.configuration.name}),this.awareness&&null!==this.awareness.getLocalState()&&this.send(se,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.configuration.name})}send(t,e){if(!this._isAttached)return;const s=new te(t,e);this.emit("outgoingMessage",{message:s.message}),s.send(this.configuration.websocketProvider)}onMessage(t){const e=new Vt(t.data),s=e.readVarString();e.writeVarString(s),this.emit("message",{event:t,message:new Vt(t.data)}),new Zt(e).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,this.awareness&&Lt(this.awareness,Array.from(this.awareness.getStates().keys()).filter((t=>t!==this.document.clientID)),this)}destroy(){this.emit("destroy"),this.intervals.forceSync&&clearInterval(this.intervals.forceSync),this.awareness&&(Lt(this.awareness,[this.document.clientID],"provider destroy"),this.awareness.off("update",this.boundAwarenessUpdateHandler),this.awareness.destroy()),this.document.off("update",this.boundDocumentUpdateHandler),this.removeAllListeners(),this.detach(),this.manageSocket&&this.configuration.websocketProvider.destroy(),"undefined"!=typeof window&&"removeEventListener"in window&&window.removeEventListener("pagehide",this.boundPageHide)}detach(){this.configuration.websocketProvider.off("connect",this.configuration.onConnect),this.configuration.websocketProvider.off("connect",this.forwardConnect),this.configuration.websocketProvider.off("status",this.forwardStatus),this.configuration.websocketProvider.off("status",this.configuration.onStatus),this.configuration.websocketProvider.off("open",this.boundOnOpen),this.configuration.websocketProvider.off("close",this.boundOnClose),this.configuration.websocketProvider.off("close",this.configuration.onClose),this.configuration.websocketProvider.off("close",this.forwardClose),this.configuration.websocketProvider.off("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.off("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.off("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.off("destroy",this.forwardDestroy),this.configuration.websocketProvider.detach(this),this._isAttached=!1}attach(){this._isAttached||(this.configuration.websocketProvider.on("connect",this.configuration.onConnect),this.configuration.websocketProvider.on("connect",this.forwardConnect),this.configuration.websocketProvider.on("status",this.configuration.onStatus),this.configuration.websocketProvider.on("status",this.forwardStatus),this.configuration.websocketProvider.on("open",this.boundOnOpen),this.configuration.websocketProvider.on("close",this.boundOnClose),this.configuration.websocketProvider.on("close",this.configuration.onClose),this.configuration.websocketProvider.on("close",this.forwardClose),this.configuration.websocketProvider.on("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.on("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.on("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.on("destroy",this.forwardDestroy),this.configuration.websocketProvider.attach(this),this._isAttached=!0)}permissionDeniedHandler(t){this.emit("authenticationFailed",{reason:t}),this.isAuthenticated=!1}authenticatedHandler(t){this.isAuthenticated=!0,this.authorizedScope=t,this.emit("authenticated",{scope:t})}setAwarenessField(t,e){if(!this.awareness)throw new oe(`Cannot set awareness field "${t}" to ${JSON.stringify(e)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);this.awareness.setLocalStateField(t,e)}}class ae{provider;isConnected=!1;isSynced=!1;usesSharedSocket=!1;static sharedWebSocketProvider=null;constructor(t,e,s){const i=s?.name||t,n=s?.url||"ws://localhost:1234",r=s?.websocketProvider||ae.sharedWebSocketProvider;if(r){this.usesSharedSocket=!0;const t={websocketProvider:r,name:i,document:e,token:s?.token||null,onConnect:()=>{this.isConnected||(this.isConnected=!0,s?.quiet||console.info("Hocuspocus connected: "+i),s?.onConnect&&s.onConnect())},onDisconnect:()=>{(this.isConnected||this.isSynced)&&(this.isConnected=!1,this.isSynced=!1,s?.quiet||console.info("Hocuspocus disconnected: "+i),s?.onDisconnect&&s.onDisconnect())},onSynced:()=>{this.isSynced||(this.isSynced=!0,s?.quiet||console.info("Hocuspocus synced: "+i),s?.onSynced&&s.onSynced())}};void 0!==s?.forceSyncInterval&&(t.forceSyncInterval=s.forceSyncInterval),s?.onAuthenticationFailed&&(t.onAuthenticationFailed=s.onAuthenticationFailed),s?.onStatus&&(t.onStatus=s.onStatus),this.provider=new he(t),this.provider.attach(),s?.quiet||console.info("Hocuspocus Provider initialized (multiplexed): "+i)}else{this.usesSharedSocket=!1;const t={url:n,name:i,document:e,token:s?.token||null,onConnect:()=>{this.isConnected||(this.isConnected=!0,s?.quiet||console.info("Hocuspocus connected: "+i),s?.onConnect&&s.onConnect())},onDisconnect:()=>{(this.isConnected||this.isSynced)&&(this.isConnected=!1,this.isSynced=!1,s?.quiet||console.info("Hocuspocus disconnected: "+i),s?.onDisconnect&&s.onDisconnect())},onSynced:()=>{this.isSynced||(this.isSynced=!0,s?.quiet||console.info("Hocuspocus synced: "+i),s?.onSynced&&s.onSynced())}};void 0!==s?.forceSyncInterval&&(t.forceSyncInterval=s.forceSyncInterval),s?.onAuthenticationFailed&&(t.onAuthenticationFailed=s.onAuthenticationFailed),s?.onStatus&&(t.onStatus=s.onStatus),s?.WebSocketPolyfill&&(t.WebSocketPolyfill=s.WebSocketPolyfill),this.provider=new he(t),s?.quiet||console.info(`Hocuspocus Provider initialized: ${n}/${i}`)}}static createSharedWebSocket(t){if(ae.sharedWebSocketProvider)return console.warn("Shared WebSocket already exists. Returning existing instance."),ae.sharedWebSocketProvider;const e={url:t.url};return t.WebSocketPolyfill&&(e.WebSocketPolyfill=t.WebSocketPolyfill),t.onConnect&&(e.onConnect=t.onConnect),t.onDisconnect&&(e.onDisconnect=t.onDisconnect),t.onStatus&&(e.onStatus=t.onStatus),ae.sharedWebSocketProvider=new Qt(e),console.info("Shared Hocuspocus WebSocket created: "+t.url),ae.sharedWebSocketProvider}static destroySharedWebSocket(){ae.sharedWebSocketProvider&&(ae.sharedWebSocketProvider.destroy(),ae.sharedWebSocketProvider=null,console.info("Shared Hocuspocus WebSocket destroyed"))}static getSharedWebSocket(){return ae.sharedWebSocketProvider}static with(t){return{create:(e,s,i)=>{const n=i?{...t,...i}:t;return new ae(e,s,n)}}}async connect(){if(!this.isSynced)return new Promise(((t,e)=>{const s=setTimeout((()=>{e(Error("Hocuspocus connection timeout"))}),1e4),i=()=>{clearTimeout(s),this.provider.off("synced",i),t()};if(this.provider.on("synced",i),this.provider.isSynced)return clearTimeout(s),this.provider.off("synced",i),void t();this.isConnected||this.usesSharedSocket||this.provider.connect()}))}disconnect(){this.provider&&(this.usesSharedSocket?this.provider.detach():this.provider.disconnect()),this.isConnected=!1,this.isSynced=!1}destroy(){this.provider&&this.provider.destroy(),this.isConnected=!1,this.isSynced=!1}}export{M as BroadcastSyncProvider,ae as HocuspocusSyncProvider,P as WebSocketSyncProvider}
|
|
1
|
+
export{g as getAssetPath,r as render,s as setAssetPath,a as setNonce,b as setPlatformOptions}from"./p-pebXO4LU.js";export{f as KritzelBrushTool,d as KritzelGroup,b as KritzelImage,c as KritzelLine,g as KritzelLineTool,a as KritzelPath,j as KritzelSelectionTool,e as KritzelShape,i as KritzelShapeTool,K as KritzelText,h as KritzelTextTool,S as ShapeType}from"./p-CQiJ2YUG.js";export{I as IndexedDBSyncProvider,d as KritzelAlignment,c as KritzelAnchorManager,b as KritzelCursorHelper,K as KritzelEraserTool,a as KritzelImageTool}from"./p-tixOjR-m.js";import*as t from"yjs";import{WebsocketProvider as n}from"y-websocket";export{K as KritzelWorkspace,W as WORKSPACE_EXPORT_VERSION}from"./p-AcQNA3C8.js";export{D as DEFAULT_BRUSH_CONFIG,b as DEFAULT_LINE_TOOL_CONFIG,a as DEFAULT_TEXT_CONFIG,KritzelEditor,defineCustomElement as defineCustomElementKritzelEditor}from"./kritzel-editor.js";export{K as KritzelThemeManager,d as darkTheme,l as lightTheme}from"./p-bWUahQFj.js";export{KritzelActiveUsers,defineCustomElement as defineCustomElementKritzelActiveUsers}from"./kritzel-active-users.js";export{KritzelAvatar,defineCustomElement as defineCustomElementKritzelAvatar}from"./kritzel-avatar.js";export{KritzelBackToContent,defineCustomElement as defineCustomElementKritzelBackToContent}from"./kritzel-back-to-content.js";export{KritzelBrushStyle,defineCustomElement as defineCustomElementKritzelBrushStyle}from"./kritzel-brush-style.js";export{KritzelColor,defineCustomElement as defineCustomElementKritzelColor}from"./kritzel-color.js";export{KritzelColorPalette,defineCustomElement as defineCustomElementKritzelColorPalette}from"./kritzel-color-palette.js";export{KritzelContextMenu,defineCustomElement as defineCustomElementKritzelContextMenu}from"./kritzel-context-menu.js";export{KritzelControls,defineCustomElement as defineCustomElementKritzelControls}from"./kritzel-controls.js";export{KritzelCurrentUser,defineCustomElement as defineCustomElementKritzelCurrentUser}from"./kritzel-current-user.js";export{KritzelCursorTrail,defineCustomElement as defineCustomElementKritzelCursorTrail}from"./kritzel-cursor-trail.js";export{KritzelDialog,defineCustomElement as defineCustomElementKritzelDialog}from"./kritzel-dialog.js";export{KritzelDropdown,defineCustomElement as defineCustomElementKritzelDropdown}from"./kritzel-dropdown.js";export{KritzelEngine,defineCustomElement as defineCustomElementKritzelEngine}from"./kritzel-engine.js";export{KritzelExport,defineCustomElement as defineCustomElementKritzelExport}from"./kritzel-export.js";export{KritzelFont,defineCustomElement as defineCustomElementKritzelFont}from"./kritzel-font.js";export{KritzelFontFamily,defineCustomElement as defineCustomElementKritzelFontFamily}from"./kritzel-font-family.js";export{KritzelFontSize,defineCustomElement as defineCustomElementKritzelFontSize}from"./kritzel-font-size.js";export{KritzelIcon,defineCustomElement as defineCustomElementKritzelIcon}from"./kritzel-icon.js";export{KritzelInput,defineCustomElement as defineCustomElementKritzelInput}from"./kritzel-input.js";export{KritzelLineEndings,defineCustomElement as defineCustomElementKritzelLineEndings}from"./kritzel-line-endings.js";export{KritzelMasterDetail,defineCustomElement as defineCustomElementKritzelMasterDetail}from"./kritzel-master-detail.js";export{KritzelMenu,defineCustomElement as defineCustomElementKritzelMenu}from"./kritzel-menu.js";export{KritzelMenuItem,defineCustomElement as defineCustomElementKritzelMenuItem}from"./kritzel-menu-item.js";export{KritzelMoreMenu,defineCustomElement as defineCustomElementKritzelMoreMenu}from"./kritzel-more-menu.js";export{KritzelNumericInput,defineCustomElement as defineCustomElementKritzelNumericInput}from"./kritzel-numeric-input.js";export{KritzelOpacitySlider,defineCustomElement as defineCustomElementKritzelOpacitySlider}from"./kritzel-opacity-slider.js";export{KritzelPillTabs,defineCustomElement as defineCustomElementKritzelPillTabs}from"./kritzel-pill-tabs.js";export{KritzelPortal,defineCustomElement as defineCustomElementKritzelPortal}from"./kritzel-portal.js";export{KritzelSettings,defineCustomElement as defineCustomElementKritzelSettings}from"./kritzel-settings.js";export{KritzelShapeFill,defineCustomElement as defineCustomElementKritzelShapeFill}from"./kritzel-shape-fill.js";export{KritzelShareDialog,defineCustomElement as defineCustomElementKritzelShareDialog}from"./kritzel-share-dialog.js";export{KritzelSlideToggle,defineCustomElement as defineCustomElementKritzelSlideToggle}from"./kritzel-slide-toggle.js";export{KritzelSplitButton,defineCustomElement as defineCustomElementKritzelSplitButton}from"./kritzel-split-button.js";export{KritzelStrokeSize,defineCustomElement as defineCustomElementKritzelStrokeSize}from"./kritzel-stroke-size.js";export{KritzelToolConfig,defineCustomElement as defineCustomElementKritzelToolConfig}from"./kritzel-tool-config.js";export{KritzelTooltip,defineCustomElement as defineCustomElementKritzelTooltip}from"./kritzel-tooltip.js";export{KritzelUtilityPanel,defineCustomElement as defineCustomElementKritzelUtilityPanel}from"./kritzel-utility-panel.js";export{KritzelWorkspaceManager,defineCustomElement as defineCustomElementKritzelWorkspaceManager}from"./kritzel-workspace-manager.js";const o=Math.floor,u=127,m=Number.MAX_SAFE_INTEGER;let p=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const y=()=>new p,w=t=>{const e=new Uint8Array((t=>{let e=t.cpos;for(let s=0;s<t.bufs.length;s++)e+=t.bufs[s].length;return e})(t));let s=0;for(let i=0;i<t.bufs.length;i++){const n=t.bufs[i];e.set(n,s),s+=n.length}return e.set(new Uint8Array(t.cbuf.buffer,0,t.cpos),s),e},C=(t,e)=>{const s=t.cbuf.length;t.cpos===s&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(2*s),t.cpos=0),t.cbuf[t.cpos++]=e},z=(t,e)=>{for(;e>u;)C(t,128|u&e),e=o(e/128);C(t,u&e)},E=(t,e)=>{z(t,e.byteLength),((t,e)=>{const s=t.cbuf.length,i=t.cpos,n=((t,e)=>t<e?t:e)(s-i,e.length),r=e.length-n;t.cbuf.set(e.subarray(0,n),i),t.cpos+=n,r>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(((t,e)=>t>e?t:e)(2*s,r)),t.cbuf.set(e.subarray(n)),t.cpos=r)})(t,e)},v=t=>Error(t),k=v("Unexpected end of array"),x=v("Integer out of Range");let A=class{constructor(t){this.arr=t,this.pos=0}};const T=t=>((t,e)=>{const s=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,s})(t,U(t)),U=t=>{let e=0,s=1;const i=t.arr.length;for(;t.pos<i;){const i=t.arr[t.pos++];if(e+=(i&u)*s,s*=128,i<128)return e;if(e>m)throw x}throw k};class M{doc;channel;_synced=!1;constructor(t,e,s){this.doc=e,this.channel=new BroadcastChannel(t),this.channel.onmessage=t=>{this.handleMessage(t.data)},this.doc.on("update",this.handleDocUpdate),this.broadcastSync(),setTimeout((()=>{this._synced=!0}),100),s?.quiet||console.info("BroadcastChannel Provider initialized: "+t)}handleDocUpdate=(t,e)=>{if(e!==this){const e=y();z(e,0),E(e,t),this.channel.postMessage(w(e))}};handleMessage(e){const s=(t=>new A(t))(new Uint8Array(e));switch(U(s)){case 0:const e=T(s);t.applyUpdate(this.doc,e,this);break;case 1:this.broadcastSync();break;case 2:const i=T(s),n=t.encodeStateAsUpdate(this.doc,i);if(n.length>0){const t=y();z(t,0),E(t,n),this.channel.postMessage(w(t))}}}broadcastSync(){const e=y();z(e,2),E(e,t.encodeStateVector(this.doc)),this.channel.postMessage(w(e))}async connect(){if(!this._synced)return new Promise((t=>{const e=()=>{this._synced?t():setTimeout(e,50)};e()}))}disconnect(){}destroy(){this.doc.off("update",this.handleDocUpdate),this.channel.close()}}class P{provider;isConnected=!1;_quiet=!1;constructor(t,e,s){const i=s?.url||"ws://localhost:1234",r=s?.roomName||t;this.provider=new n(i,r,e,{params:s?.params,protocols:s?.protocols,WebSocketPolyfill:s?.WebSocketPolyfill,awareness:s?.awareness,maxBackoffTime:s?.maxBackoffTime,disableBc:!0}),this._quiet=s?.quiet??!1,this.setupEventListeners(),this._quiet||console.info(`WebSocket Provider initialized: ${i}/${r}`)}static with(t){return{create:(e,s,i)=>{const n=i?{...t,...i}:t;return new P(e,s,n)}}}setupEventListeners(){this.provider.on("status",(({status:t})=>{"connected"===t?(this.isConnected=!0,this._quiet||console.info("WebSocket connected")):"disconnected"===t&&(this.isConnected=!1,this._quiet||console.info("WebSocket disconnected"))})),this.provider.on("sync",(t=>{t&&!this._quiet&&console.info("WebSocket synced")}))}async connect(){if(!this.isConnected)return new Promise(((t,e)=>{const s=setTimeout((()=>{e(Error("WebSocket connection timeout"))}),1e4),i=({status:e})=>{"connected"===e&&(clearTimeout(s),this.provider.off("status",i),this.isConnected=!0,t())};this.provider.on("status",i),this.provider.wsconnected&&(clearTimeout(s),this.provider.off("status",i),this.isConnected=!0,t())}))}disconnect(){this.provider&&this.provider.disconnect(),this.isConnected=!1}destroy(){this.provider&&this.provider.destroy(),this.isConnected=!1}}const O=Math.floor,N=127,F=Number.MAX_SAFE_INTEGER,H="undefined"!=typeof TextEncoder?new TextEncoder:null,L=H?t=>H.encode(t):t=>{const e=unescape(encodeURIComponent(t)),s=e.length,i=new Uint8Array(s);for(let t=0;t<s;t++)i[t]=e.codePointAt(t);return i};let R="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});R&&1===R.decode(new Uint8Array).length&&(R=null);const B=(t,e)=>{const s=t.cbuf.length;t.cpos===s&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(2*s),t.cpos=0),t.cbuf[t.cpos++]=e},_=(t,e)=>{for(;e>N;)B(t,128|N&e),e=O(e/128);B(t,N&e)},$=new Uint8Array(3e4),V=$.length/3,q=H&&H.encodeInto?(t,e)=>{if(e.length<V){const s=H.encodeInto(e,$).written||0;_(t,s);for(let e=0;e<s;e++)B(t,$[e])}else G(t,L(e))}:(t,e)=>{const s=unescape(encodeURIComponent(e)),i=s.length;_(t,i);for(let e=0;e<i;e++)B(t,s.codePointAt(e))},G=(t,e)=>{_(t,e.byteLength),((t,e)=>{const s=t.cbuf.length,i=t.cpos,n=((t,e)=>t<e?t:e)(s-i,e.length),r=e.length-n;t.cbuf.set(e.subarray(0,n),i),t.cpos+=n,r>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(((t,e)=>t>e?t:e)(2*s,r)),t.cbuf.set(e.subarray(n)),t.cpos=r)})(t,e)},J=t=>Error(t),Q=J("Unexpected end of array"),X=J("Integer out of Range"),Y=t=>t.arr[t.pos++],Z=t=>{let e=0,s=1;const i=t.arr.length;for(;t.pos<i;){const i=t.arr[t.pos++];if(e+=(i&N)*s,s*=128,i<128)return e;if(e>F)throw X}throw Q},tt=R?t=>R.decode((t=>((t,e)=>{const s=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,s})(t,Z(t)))(t)):t=>{let e=Z(t);if(0===e)return"";{let s=String.fromCodePoint(Y(t));if(--e<100)for(;e--;)s+=String.fromCodePoint(Y(t));else for(;e>0;){const i=e<1e4?e:1e4,n=t.arr.subarray(t.pos,t.pos+i);t.pos+=i,s+=String.fromCodePoint.apply(null,n),e-=i}return decodeURIComponent(escape(s))}};var et;!function(t){t[t.Token=0]="Token",t[t.PermissionDenied=1]="PermissionDenied",t[t.Authenticated=2]="Authenticated"}(et||(et={}));const st=t=>Array.from(t.entries()).map((([t,e])=>({clientId:t,...e})));var it;async function nt(t){return new Promise((e=>setTimeout(e,t)))}function rt(t,e){let s=e.delay;if(0===s)return 0;if(e.factor&&(s*=Math.pow(e.factor,t.attemptNum-1),0!==e.maxDelay&&(s=Math.min(s,e.maxDelay))),e.jitter){const t=Math.ceil(e.minDelay),i=Math.floor(s);s=Math.floor(Math.random()*(i-t+1))+t}return Math.round(s)}!function(t){t[t.Connecting=0]="Connecting",t[t.Open=1]="Open",t[t.Closing=2]="Closing",t[t.Closed=3]="Closed"}(it||(it={}));const ot=Math.floor,ht=128,at=127,lt=Number.MAX_SAFE_INTEGER,ct=()=>new Set,ut=Array.from,dt="undefined"!=typeof TextEncoder?new TextEncoder:null,mt=dt?t=>dt.encode(t):t=>{const e=unescape(encodeURIComponent(t)),s=e.length,i=new Uint8Array(s);for(let t=0;t<s;t++)i[t]=e.codePointAt(t);return i};let ft="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ft&&1===ft.decode(new Uint8Array).length&&(ft=null);class pt{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const yt=()=>new pt,gt=t=>{let e=t.cpos;for(let s=0;s<t.bufs.length;s++)e+=t.bufs[s].length;return e},wt=t=>{const e=new Uint8Array(gt(t));let s=0;for(let i=0;i<t.bufs.length;i++){const n=t.bufs[i];e.set(n,s),s+=n.length}return e.set(new Uint8Array(t.cbuf.buffer,0,t.cpos),s),e},Ct=(t,e)=>{const s=t.cbuf.length;t.cpos===s&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(2*s),t.cpos=0),t.cbuf[t.cpos++]=e},zt=(t,e)=>{for(;e>at;)Ct(t,ht|at&e),e=ot(e/128);Ct(t,at&e)},Et=new Uint8Array(3e4),vt=Et.length/3,kt=dt&&dt.encodeInto?(t,e)=>{if(e.length<vt){const s=dt.encodeInto(e,Et).written||0;zt(t,s);for(let e=0;e<s;e++)Ct(t,Et[e])}else Kt(t,mt(e))}:(t,e)=>{const s=unescape(encodeURIComponent(e)),i=s.length;zt(t,i);for(let e=0;e<i;e++)Ct(t,s.codePointAt(e))},Kt=(t,e)=>{zt(t,e.byteLength),((t,e)=>{const s=t.cbuf.length,i=t.cpos,n=((t,e)=>t<e?t:e)(s-i,e.length),r=e.length-n;t.cbuf.set(e.subarray(0,n),i),t.cpos+=n,r>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(((t,e)=>t>e?t:e)(2*s,r)),t.cbuf.set(e.subarray(n)),t.cpos=r)})(t,e)},St=t=>Error(t),xt=St("Unexpected end of array"),At=St("Integer out of Range");class bt{constructor(t){this.arr=t,this.pos=0}}const Tt=t=>new bt(t),Ut=t=>((t,e)=>{const s=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,s})(t,Mt(t)),jt=t=>t.arr[t.pos++],Mt=t=>{let e=0,s=1;const i=t.arr.length;for(;t.pos<i;){const i=t.arr[t.pos++];if(e+=(i&at)*s,s*=128,i<ht)return e;if(e>lt)throw At}throw xt},Dt=ft?t=>ft.decode(Ut(t)):t=>{let e=Mt(t);if(0===e)return"";{let s=String.fromCodePoint(jt(t));if(--e<100)for(;e--;)s+=String.fromCodePoint(jt(t));else for(;e>0;){const i=e<1e4?e:1e4,n=t.arr.subarray(t.pos,t.pos+i);t.pos+=i,s+=String.fromCodePoint.apply(null,n),e-=i}return decodeURIComponent(escape(s))}},Pt=Date.now,It=()=>new Map;class Ot{constructor(){this._observers=It()}on(t,e){((t,e,s)=>{let i=t.get(e);return void 0===i&&t.set(e,i=s()),i})(this._observers,t,ct).add(e)}once(t,e){const s=(...i)=>{this.off(t,s),e(...i)};this.on(t,s)}off(t,e){const s=this._observers.get(t);void 0!==s&&(s.delete(e),0===s.size&&this._observers.delete(t))}emit(t,e){return ut((this._observers.get(t)||It()).values()).forEach((t=>t(...e)))}destroy(){this._observers=It()}}const Nt=Object.keys,Ft=t=>Nt(t).length,Wt=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Ht=(t,e)=>{if(null==t||null==e)return((t,e)=>t===e)(t,e);if(t.constructor!==e.constructor)return!1;if(t===e)return!0;switch(t.constructor){case ArrayBuffer:t=new Uint8Array(t),e=new Uint8Array(e);case Uint8Array:if(t.byteLength!==e.byteLength)return!1;for(let s=0;s<t.length;s++)if(t[s]!==e[s])return!1;break;case Set:if(t.size!==e.size)return!1;for(const s of t)if(!e.has(s))return!1;break;case Map:if(t.size!==e.size)return!1;for(const s of t.keys())if(!e.has(s)||!Ht(t.get(s),e.get(s)))return!1;break;case Object:if(Ft(t)!==Ft(e))return!1;for(const s in t)if(!Wt(t,s)||!Ht(t[s],e[s]))return!1;break;case Array:if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++)if(!Ht(t[s],e[s]))return!1;break;default:return!1}return!0};class Lt extends Ot{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval((()=>{const t=Pt();null!==this.getLocalState()&&15e3<=t-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const e=[];this.meta.forEach(((s,i)=>{i!==this.clientID&&3e4<=t-s.lastUpdated&&this.states.has(i)&&e.push(i)})),e.length>0&&Rt(this,e,"timeout")}),ot(3e3)),t.on("destroy",(()=>{this.destroy()})),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const e=this.clientID,s=this.meta.get(e),i=void 0===s?0:s.clock+1,n=this.states.get(e);null===t?this.states.delete(e):this.states.set(e,t),this.meta.set(e,{clock:i,lastUpdated:Pt()});const r=[],o=[],h=[],a=[];null===t?a.push(e):null==n?null!=t&&r.push(e):(o.push(e),Ht(n,t)||h.push(e)),(r.length>0||h.length>0||a.length>0)&&this.emit("change",[{added:r,updated:h,removed:a},"local"]),this.emit("update",[{added:r,updated:o,removed:a},"local"])}setLocalStateField(t,e){const s=this.getLocalState();null!==s&&this.setLocalState({...s,[t]:e})}getStates(){return this.states}}const Rt=(t,e,s)=>{const i=[];for(let s=0;s<e.length;s++){const n=e[s];if(t.states.has(n)){if(t.states.delete(n),n===t.clientID){const e=t.meta.get(n);t.meta.set(n,{clock:e.clock+1,lastUpdated:Pt()})}i.push(n)}}i.length>0&&(t.emit("change",[{added:[],updated:[],removed:i},s]),t.emit("update",[{added:[],updated:[],removed:i},s]))},Bt=(t,e,s=t.states)=>{const i=e.length,n=yt();zt(n,i);for(let r=0;r<i;r++){const i=e[r],o=s.get(i)||null,h=t.meta.get(i).clock;zt(n,i),zt(n,h),kt(n,JSON.stringify(o))}return wt(n)};class _t{constructor(){this.callbacks={}}on(t,e){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(e),this}emit(t,...e){const s=this.callbacks[t];return s&&s.forEach((t=>t.apply(this,e))),this}off(t,e){const s=this.callbacks[t];return s&&(e?this.callbacks[t]=s.filter((t=>t!==e)):delete this.callbacks[t]),this}removeAllListeners(){this.callbacks={}}}class $t{constructor(t){this.data=t,this.encoder=yt(),this.decoder=Tt(new Uint8Array(this.data))}peekVarString(){return(t=>{const e=t.pos,s=Dt(t);return t.pos=e,s})(this.decoder)}readVarUint(){return Mt(this.decoder)}readVarString(){return Dt(this.decoder)}readVarUint8Array(){return Ut(this.decoder)}writeVarUint(t){return zt(this.encoder,t)}writeVarString(t){return kt(this.encoder,t)}writeVarUint8Array(t){return Kt(this.encoder,t)}length(){return gt(this.encoder)}}var Vt,qt;!function(t){t[t.Sync=0]="Sync",t[t.Awareness=1]="Awareness",t[t.Auth=2]="Auth",t[t.QueryAwareness=3]="QueryAwareness",t[t.Stateless=5]="Stateless",t[t.CLOSE=7]="CLOSE",t[t.SyncStatus=8]="SyncStatus"}(Vt||(Vt={})),function(t){t.Connecting="connecting",t.Connected="connected",t.Disconnected="disconnected"}(qt||(qt={}));class Gt{constructor(){this.encoder=yt()}get(t){return t.encoder}toUint8Array(){return wt(this.encoder)}}class Jt extends Gt{constructor(){super(...arguments),this.type=Vt.CLOSE,this.description="Ask the server to close the connection"}get(t){return kt(this.encoder,t.documentName),zt(this.encoder,this.type),this.encoder}}class Qt extends _t{constructor(t){super(),this.messageQueue=[],this.configuration={url:"",autoConnect:!0,preserveTrailingSlash:!1,document:void 0,WebSocketPolyfill:void 0,messageReconnectTimeout:3e4,delay:1e3,initialDelay:0,factor:2,maxAttempts:0,minDelay:1e3,maxDelay:3e4,jitter:!0,timeout:0,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,handleTimeout:null,providerMap:new Map},this.webSocket=null,this.webSocketHandlers={},this.shouldConnect=!0,this.status=qt.Disconnected,this.lastMessageReceived=0,this.identifier=0,this.intervals={connectionChecker:null},this.connectionAttempt=null,this.receivedOnOpenPayload=void 0,this.closeTries=0,this.setConfiguration(t),this.configuration.WebSocketPolyfill=t.WebSocketPolyfill?t.WebSocketPolyfill:WebSocket,this.on("open",this.configuration.onOpen),this.on("open",this.onOpen.bind(this)),this.on("connect",this.configuration.onConnect),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("status",this.configuration.onStatus),this.on("disconnect",this.configuration.onDisconnect),this.on("close",this.configuration.onClose),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("close",this.onClose.bind(this)),this.on("message",this.onMessage.bind(this)),this.intervals.connectionChecker=setInterval(this.checkConnection.bind(this),this.configuration.messageReconnectTimeout/10),this.shouldConnect&&this.connect()}async onOpen(t){this.status=qt.Connected,this.emit("status",{status:qt.Connected}),this.cancelWebsocketRetry=void 0,this.receivedOnOpenPayload=t}attach(t){this.configuration.providerMap.set(t.configuration.name,t),this.status===qt.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===qt.Connected&&t.onOpen(this.receivedOnOpenPayload)}detach(t){this.configuration.providerMap.has(t.configuration.name)&&(t.send(Jt,{documentName:t.configuration.name}),this.configuration.providerMap.delete(t.configuration.name))}setConfiguration(t={}){this.configuration={...this.configuration,...t},this.configuration.autoConnect||(this.shouldConnect=!1)}async connect(){if(this.status===qt.Connected)return;this.cancelWebsocketRetry&&(this.cancelWebsocketRetry(),this.cancelWebsocketRetry=void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;const{retryPromise:t,cancelFunc:e}=(()=>{let t=!1;return{retryPromise:async function(t,e){const s=function(t){return t||(t={}),{delay:void 0===t.delay?200:t.delay,initialDelay:void 0===t.initialDelay?0:t.initialDelay,minDelay:void 0===t.minDelay?0:t.minDelay,maxDelay:void 0===t.maxDelay?0:t.maxDelay,factor:void 0===t.factor?0:t.factor,maxAttempts:void 0===t.maxAttempts?3:t.maxAttempts,timeout:void 0===t.timeout?0:t.timeout,jitter:!0===t.jitter,initialJitter:!0===t.initialJitter,handleError:void 0===t.handleError?null:t.handleError,handleTimeout:void 0===t.handleTimeout?null:t.handleTimeout,beforeAttempt:void 0===t.beforeAttempt?null:t.beforeAttempt,calculateDelay:void 0===t.calculateDelay?null:t.calculateDelay}}(e);for(const t of["delay","initialDelay","minDelay","maxDelay","maxAttempts","timeout"]){const e=s[t];if(!Number.isInteger(e)||e<0)throw Error(`Value for ${t} must be an integer greater than or equal to 0`)}if(s.factor.constructor!==Number||s.factor<0)throw Error("Value for factor must be a number greater than or equal to 0");if(s.delay<s.minDelay)throw Error(`delay cannot be less than minDelay (delay: ${s.delay}, minDelay: ${s.minDelay}`);const i={attemptNum:0,attemptsRemaining:s.maxAttempts?s.maxAttempts:-1,aborted:!1,abort(){i.aborted=!0}},n=s.calculateDelay||rt,r=s.calculateDelay?s.calculateDelay(i,s):s.initialDelay;if(r&&await nt(r),i.attemptNum<1&&s.initialJitter){const t=n(i,s);t&&await nt(t)}return async function e(){if(s.beforeAttempt&&s.beforeAttempt(i,s),i.aborted){const t=Error("Attempt aborted");throw t.code="ATTEMPT_ABORTED",t}const r=async t=>{if(s.handleError&&await s.handleError(t,i,s),i.aborted||0===i.attemptsRemaining)throw t;i.attemptNum++;const r=n(i,s);return r&&await nt(r),e()};return i.attemptsRemaining>0&&i.attemptsRemaining--,s.timeout?new Promise(((e,n)=>{const o=setTimeout((()=>{if(s.handleTimeout)try{e(s.handleTimeout(i,s))}catch(t){n(t)}else{const t=Error(`Retry timeout (attemptNum: ${i.attemptNum}, timeout: ${s.timeout})`);t.code="ATTEMPT_TIMEOUT",n(t)}}),s.timeout);t(i,s).then((t=>{clearTimeout(o),e(t)})).catch((t=>{clearTimeout(o),r(t).then(e).catch(n)}))})):t(i,s).catch(r)}()}(this.createWebSocketConnection.bind(this),{delay:this.configuration.delay,initialDelay:this.configuration.initialDelay,factor:this.configuration.factor,maxAttempts:this.configuration.maxAttempts,minDelay:this.configuration.minDelay,maxDelay:this.configuration.maxDelay,jitter:this.configuration.jitter,timeout:this.configuration.timeout,handleTimeout:this.configuration.handleTimeout,beforeAttempt:e=>{this.shouldConnect&&!t||e.abort()}}).catch((t=>{if(t&&"ATTEMPT_ABORTED"!==t.code)throw t})),cancelFunc:()=>{t=!0}}})();return this.cancelWebsocketRetry=e,t}attachWebSocketListeners(t,e){const{identifier:s}=t;this.webSocketHandlers[s]={message:t=>this.emit("message",t),close:t=>this.emit("close",{event:t}),open:t=>this.emit("open",t),error:t=>{e(t)}};const i=this.webSocketHandlers[t.identifier];Object.keys(i).forEach((e=>{t.addEventListener(e,i[e])}))}cleanupWebSocket(){if(!this.webSocket)return;const{identifier:t}=this.webSocket,e=this.webSocketHandlers[t];Object.keys(e).forEach((s=>{var i;null===(i=this.webSocket)||void 0===i||i.removeEventListener(s,e[s]),delete this.webSocketHandlers[t]})),this.webSocket.close(),this.webSocket=null}createWebSocketConnection(){return new Promise(((t,e)=>{this.webSocket&&(this.messageQueue=[],this.cleanupWebSocket()),this.lastMessageReceived=0,this.identifier+=1;const s=new this.configuration.WebSocketPolyfill(this.url);s.binaryType="arraybuffer",s.identifier=this.identifier,this.attachWebSocketListeners(s,e),this.webSocket=s,this.status=qt.Connecting,this.emit("status",{status:qt.Connecting}),this.connectionAttempt={resolve:t,reject:e}}))}onMessage(t){var e;this.resolveConnectionAttempt(),this.lastMessageReceived=Pt();const s=new $t(t.data).peekVarString();null===(e=this.configuration.providerMap.get(s))||void 0===e||e.onMessage(t)}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=qt.Connected,this.emit("status",{status:qt.Connected}),this.emit("connect"),this.messageQueue.forEach((t=>this.send(t))),this.messageQueue=[])}stopConnectionAttempt(){this.connectionAttempt=null}rejectConnectionAttempt(){var t;null===(t=this.connectionAttempt)||void 0===t||t.reject(),this.connectionAttempt=null}checkConnection(){var t;this.status===qt.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=Pt()-this.lastMessageReceived||(this.closeTries+=1,this.closeTries>2?(this.onClose({event:{code:4408,reason:"forced"}}),this.closeTries=0):(null===(t=this.webSocket)||void 0===t||t.close(),this.messageQueue=[])))}get serverUrl(){if(this.configuration.preserveTrailingSlash)return this.configuration.url;let t=this.configuration.url;for(;"/"===t[t.length-1];)t=t.slice(0,t.length-1);return t}get url(){return this.serverUrl}disconnect(){if(this.shouldConnect=!1,null!==this.webSocket)try{this.webSocket.close(),this.messageQueue=[]}catch(t){console.error(t)}}send(t){var e;(null===(e=this.webSocket)||void 0===e?void 0:e.readyState)===it.Open?this.webSocket.send(t):this.messageQueue.push(t)}onClose({event:t}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=qt.Disconnected,this.emit("status",{status:qt.Disconnected}),this.emit("disconnect",{event:t}),!this.cancelWebsocketRetry&&this.shouldConnect&&setTimeout((()=>{this.connect()}),this.configuration.delay)}destroy(){this.emit("destroy"),clearInterval(this.intervals.connectionChecker),this.stopConnectionAttempt(),this.disconnect(),this.removeAllListeners(),this.cleanupWebSocket()}}const Xt=(e,s,i)=>{try{t.applyUpdate(s,Ut(e),i)}catch(t){console.error("Caught error while handling a Yjs update",t)}},Yt=Xt;class Zt{constructor(t){this.message=t}apply(t,e){const{message:s}=this,i=s.readVarUint(),n=s.length();switch(i){case Vt.Sync:this.applySyncMessage(t,e);break;case Vt.Awareness:this.applyAwarenessMessage(t);break;case Vt.Auth:this.applyAuthMessage(t);break;case Vt.QueryAwareness:this.applyQueryAwarenessMessage(t);break;case Vt.Stateless:t.receiveStateless(Dt(s.decoder));break;case Vt.SyncStatus:this.applySyncStatusMessage(t,1===(t=>{let e=t.arr[t.pos++],s=63&e,i=64;const n=(64&e)>0?-1:1;if(!(e&ht))return n*s;const r=t.arr.length;for(;t.pos<r;){if(e=t.arr[t.pos++],s+=(e&at)*i,i*=128,e<ht)return n*s;if(s>lt)throw At}throw xt})(s.decoder));break;case Vt.CLOSE:const n={code:1e3,reason:Dt(s.decoder),target:t.configuration.websocketProvider.webSocket,type:"close"};t.onClose(),t.configuration.onClose({event:n}),t.forwardClose({event:n});break;default:throw Error("Can’t apply message of unknown type: "+i)}s.length()>n+1&&t.send(Gt,{encoder:s.encoder})}applySyncMessage(e,s){const{message:i}=this;i.writeVarUint(Vt.Sync);const n=((e,s,i,n)=>{const r=Mt(e);switch(r){case 0:((e,s,i)=>{((e,s,i)=>{zt(e,1),Kt(e,t.encodeStateAsUpdate(s,i))})(s,i,Ut(e))})(e,s,i);break;case 1:Xt(e,i,n);break;case 2:Yt(e,i,n);break;default:throw Error("Unknown message type")}return r})(i.decoder,i.encoder,e.document,e);s&&1===n&&(e.synced=!0)}applySyncStatusMessage(t,e){e&&t.decrementUnsyncedChanges()}applyAwarenessMessage(t){if(!t.awareness)return;const{message:e}=this;((t,e,s)=>{const i=Tt(e),n=Pt(),r=[],o=[],h=[],a=[],l=Mt(i);for(let e=0;e<l;e++){const e=Mt(i);let s=Mt(i);const l=JSON.parse(Dt(i)),c=t.meta.get(e),u=t.states.get(e),d=void 0===c?0:c.clock;(d<s||d===s&&null===l&&t.states.has(e))&&(null===l?e===t.clientID&&null!=t.getLocalState()?s++:t.states.delete(e):t.states.set(e,l),t.meta.set(e,{clock:s,lastUpdated:n}),void 0===c&&null!==l?r.push(e):void 0!==c&&null===l?a.push(e):null!==l&&(Ht(l,u)||h.push(e),o.push(e)))}(r.length>0||h.length>0||a.length>0)&&t.emit("change",[{added:r,updated:h,removed:a},s]),(r.length>0||o.length>0||a.length>0)&&t.emit("update",[{added:r,updated:o,removed:a},s])})(t.awareness,e.readVarUint8Array(),t)}applyAuthMessage(t){const{message:e}=this;((t,e,s,i)=>{switch(Z(t)){case et.Token:e();break;case et.PermissionDenied:s(tt(t));break;case et.Authenticated:i(tt(t))}})(e.decoder,t.sendToken.bind(t),t.permissionDeniedHandler.bind(t),t.authenticatedHandler.bind(t))}applyQueryAwarenessMessage(t){if(!t.awareness)return;const{message:e}=this;e.writeVarUint(Vt.Awareness),e.writeVarUint8Array(Bt(t.awareness,Array.from(t.awareness.getStates().keys())))}}class te{constructor(t,e={}){this.message=new t,this.encoder=this.message.get(e)}create(){return wt(this.encoder)}send(t){null==t||t.send(this.create())}}class ee extends Gt{constructor(){super(...arguments),this.type=Vt.Auth,this.description="Authentication"}get(t){if(void 0===t.token)throw Error("The authentication message requires `token` as an argument.");return kt(this.encoder,t.documentName),zt(this.encoder,this.type),((t,e)=>{_(t,et.Token),q(t,e)})(this.encoder,t.token),this.encoder}}class se extends Gt{constructor(){super(...arguments),this.type=Vt.Awareness,this.description="Awareness states update"}get(t){if(void 0===t.awareness)throw Error("The awareness message requires awareness as an argument");if(void 0===t.clients)throw Error("The awareness message requires clients as an argument");let e;return kt(this.encoder,t.documentName),zt(this.encoder,this.type),e=void 0===t.states?Bt(t.awareness,t.clients):Bt(t.awareness,t.clients,t.states),Kt(this.encoder,e),this.encoder}}class ie extends Gt{constructor(){super(...arguments),this.type=Vt.Stateless,this.description="A stateless message"}get(t){var e;return kt(this.encoder,t.documentName),zt(this.encoder,this.type),kt(this.encoder,null!==(e=t.payload)&&void 0!==e?e:""),this.encoder}}class ne extends Gt{constructor(){super(...arguments),this.type=Vt.Sync,this.description="First sync step"}get(e){if(void 0===e.document)throw Error("The sync step one message requires document as an argument");return kt(this.encoder,e.documentName),zt(this.encoder,this.type),((e,s)=>{zt(e,0);const i=t.encodeStateVector(s);Kt(e,i)})(this.encoder,e.document),this.encoder}}class re extends Gt{constructor(){super(...arguments),this.type=Vt.Sync,this.description="A document update"}get(t){return kt(this.encoder,t.documentName),zt(this.encoder,this.type),((t,e)=>{zt(t,2),Kt(t,e)})(this.encoder,t.update),this.encoder}}class oe extends Error{constructor(){super(...arguments),this.code=1001}}class he extends _t{constructor(e){var s,i,n;super(),this.configuration={name:"",document:void 0,awareness:void 0,token:null,forceSyncInterval:!1,onAuthenticated:()=>null,onAuthenticationFailed:()=>null,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onSynced:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,onStateless:()=>null,onUnsyncedChanges:()=>null},this.isSynced=!1,this.unsyncedChanges=0,this.isAuthenticated=!1,this.authorizedScope=void 0,this.manageSocket=!1,this._isAttached=!1,this.intervals={forceSync:null},this.boundDocumentUpdateHandler=this.documentUpdateHandler.bind(this),this.boundAwarenessUpdateHandler=this.awarenessUpdateHandler.bind(this),this.boundPageHide=this.pageHide.bind(this),this.boundOnOpen=this.onOpen.bind(this),this.boundOnClose=this.onClose.bind(this),this.forwardConnect=()=>this.emit("connect"),this.forwardStatus=t=>this.emit("status",t),this.forwardClose=t=>this.emit("close",t),this.forwardDisconnect=t=>this.emit("disconnect",t),this.forwardDestroy=()=>this.emit("destroy"),this.setConfiguration(e),this.configuration.document=e.document?e.document:new t.Doc,this.configuration.awareness=void 0!==e.awareness?e.awareness:new Lt(this.document),this.on("open",this.configuration.onOpen),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("synced",this.configuration.onSynced),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("stateless",this.configuration.onStateless),this.on("unsyncedChanges",this.configuration.onUnsyncedChanges),this.on("authenticated",this.configuration.onAuthenticated),this.on("authenticationFailed",this.configuration.onAuthenticationFailed),null===(s=this.awareness)||void 0===s||s.on("update",(()=>{this.emit("awarenessUpdate",{states:st(this.awareness.getStates())})})),null===(i=this.awareness)||void 0===i||i.on("change",(()=>{this.emit("awarenessChange",{states:st(this.awareness.getStates())})})),this.document.on("update",this.boundDocumentUpdateHandler),null===(n=this.awareness)||void 0===n||n.on("update",this.boundAwarenessUpdateHandler),this.registerEventListeners(),this.configuration.forceSyncInterval&&"number"==typeof this.configuration.forceSyncInterval&&(this.intervals.forceSync=setInterval(this.forceSync.bind(this),this.configuration.forceSyncInterval)),this.manageSocket&&this.attach()}setConfiguration(t={}){t.websocketProvider||(this.manageSocket=!0,this.configuration.websocketProvider=new Qt(t)),this.configuration={...this.configuration,...t}}get document(){return this.configuration.document}get isAttached(){return this._isAttached}get awareness(){return this.configuration.awareness}get hasUnsyncedChanges(){return this.unsyncedChanges>0}resetUnsyncedChanges(){this.unsyncedChanges=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}incrementUnsyncedChanges(){this.unsyncedChanges+=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}decrementUnsyncedChanges(){this.unsyncedChanges>0&&(this.unsyncedChanges-=1),0===this.unsyncedChanges&&(this.synced=!0),this.emit("unsyncedChanges",{number:this.unsyncedChanges})}forceSync(){this.resetUnsyncedChanges(),this.send(ne,{document:this.document,documentName:this.configuration.name})}pageHide(){this.awareness&&Rt(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){"undefined"!=typeof window&&"addEventListener"in window&&window.addEventListener("pagehide",this.boundPageHide)}sendStateless(t){this.send(ie,{documentName:this.configuration.name,payload:t})}async sendToken(){let t;try{t=await this.getToken()}catch(t){return void this.permissionDeniedHandler("Failed to get token during sendToken(): "+t)}this.send(ee,{token:null!=t?t:"",documentName:this.configuration.name})}documentUpdateHandler(t,e){e!==this&&(this.incrementUnsyncedChanges(),this.send(re,{update:t,documentName:this.configuration.name}))}awarenessUpdateHandler({added:t,updated:e,removed:s},i){const n=t.concat(e).concat(s);this.send(se,{awareness:this.awareness,clients:n,documentName:this.configuration.name})}get synced(){return this.isSynced}set synced(t){this.isSynced!==t&&(this.isSynced=t,t&&this.emit("synced",{state:t}))}receiveStateless(t){this.emit("stateless",{payload:t})}async connect(){if(this.manageSocket)return this.configuration.websocketProvider.connect();console.warn("HocuspocusProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.")}disconnect(){if(this.manageSocket)return this.configuration.websocketProvider.disconnect();console.warn("HocuspocusProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.")}async onOpen(t){this.isAuthenticated=!1,this.emit("open",{event:t}),await this.sendToken(),this.startSync()}async getToken(){return"function"==typeof this.configuration.token?await this.configuration.token():this.configuration.token}startSync(){this.resetUnsyncedChanges(),this.send(ne,{document:this.document,documentName:this.configuration.name}),this.awareness&&null!==this.awareness.getLocalState()&&this.send(se,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.configuration.name})}send(t,e){if(!this._isAttached)return;const s=new te(t,e);this.emit("outgoingMessage",{message:s.message}),s.send(this.configuration.websocketProvider)}onMessage(t){const e=new $t(t.data),s=e.readVarString();e.writeVarString(s),this.emit("message",{event:t,message:new $t(t.data)}),new Zt(e).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,this.awareness&&Rt(this.awareness,Array.from(this.awareness.getStates().keys()).filter((t=>t!==this.document.clientID)),this)}destroy(){this.emit("destroy"),this.intervals.forceSync&&clearInterval(this.intervals.forceSync),this.awareness&&(Rt(this.awareness,[this.document.clientID],"provider destroy"),this.awareness.off("update",this.boundAwarenessUpdateHandler),this.awareness.destroy()),this.document.off("update",this.boundDocumentUpdateHandler),this.removeAllListeners(),this.detach(),this.manageSocket&&this.configuration.websocketProvider.destroy(),"undefined"!=typeof window&&"removeEventListener"in window&&window.removeEventListener("pagehide",this.boundPageHide)}detach(){this.configuration.websocketProvider.off("connect",this.configuration.onConnect),this.configuration.websocketProvider.off("connect",this.forwardConnect),this.configuration.websocketProvider.off("status",this.forwardStatus),this.configuration.websocketProvider.off("status",this.configuration.onStatus),this.configuration.websocketProvider.off("open",this.boundOnOpen),this.configuration.websocketProvider.off("close",this.boundOnClose),this.configuration.websocketProvider.off("close",this.configuration.onClose),this.configuration.websocketProvider.off("close",this.forwardClose),this.configuration.websocketProvider.off("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.off("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.off("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.off("destroy",this.forwardDestroy),this.configuration.websocketProvider.detach(this),this._isAttached=!1}attach(){this._isAttached||(this.configuration.websocketProvider.on("connect",this.configuration.onConnect),this.configuration.websocketProvider.on("connect",this.forwardConnect),this.configuration.websocketProvider.on("status",this.configuration.onStatus),this.configuration.websocketProvider.on("status",this.forwardStatus),this.configuration.websocketProvider.on("open",this.boundOnOpen),this.configuration.websocketProvider.on("close",this.boundOnClose),this.configuration.websocketProvider.on("close",this.configuration.onClose),this.configuration.websocketProvider.on("close",this.forwardClose),this.configuration.websocketProvider.on("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.on("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.on("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.on("destroy",this.forwardDestroy),this.configuration.websocketProvider.attach(this),this._isAttached=!0)}permissionDeniedHandler(t){this.emit("authenticationFailed",{reason:t}),this.isAuthenticated=!1}authenticatedHandler(t){this.isAuthenticated=!0,this.authorizedScope=t,this.emit("authenticated",{scope:t})}setAwarenessField(t,e){if(!this.awareness)throw new oe(`Cannot set awareness field "${t}" to ${JSON.stringify(e)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);this.awareness.setLocalStateField(t,e)}}class ae{provider;isConnected=!1;isSynced=!1;usesSharedSocket=!1;static sharedWebSocketProvider=null;constructor(t,e,s){const i=s?.name||t,n=s?.url||"ws://localhost:1234",r=s?.websocketProvider||ae.sharedWebSocketProvider;if(r){this.usesSharedSocket=!0;const t={websocketProvider:r,name:i,document:e,token:s?.token||null,onConnect:()=>{this.isConnected||(this.isConnected=!0,s?.quiet||console.info("Hocuspocus connected: "+i),s?.onConnect&&s.onConnect())},onDisconnect:()=>{(this.isConnected||this.isSynced)&&(this.isConnected=!1,this.isSynced=!1,s?.quiet||console.info("Hocuspocus disconnected: "+i),s?.onDisconnect&&s.onDisconnect())},onSynced:()=>{this.isSynced||(this.isSynced=!0,s?.quiet||console.info("Hocuspocus synced: "+i),s?.onSynced&&s.onSynced())}};void 0!==s?.forceSyncInterval&&(t.forceSyncInterval=s.forceSyncInterval),s?.onAuthenticationFailed&&(t.onAuthenticationFailed=s.onAuthenticationFailed),s?.onStatus&&(t.onStatus=s.onStatus),this.provider=new he(t),this.provider.attach(),s?.quiet||console.info("Hocuspocus Provider initialized (multiplexed): "+i)}else{this.usesSharedSocket=!1;const t={url:n,name:i,document:e,token:s?.token||null,onConnect:()=>{this.isConnected||(this.isConnected=!0,s?.quiet||console.info("Hocuspocus connected: "+i),s?.onConnect&&s.onConnect())},onDisconnect:()=>{(this.isConnected||this.isSynced)&&(this.isConnected=!1,this.isSynced=!1,s?.quiet||console.info("Hocuspocus disconnected: "+i),s?.onDisconnect&&s.onDisconnect())},onSynced:()=>{this.isSynced||(this.isSynced=!0,s?.quiet||console.info("Hocuspocus synced: "+i),s?.onSynced&&s.onSynced())}};void 0!==s?.forceSyncInterval&&(t.forceSyncInterval=s.forceSyncInterval),s?.onAuthenticationFailed&&(t.onAuthenticationFailed=s.onAuthenticationFailed),s?.onStatus&&(t.onStatus=s.onStatus),s?.WebSocketPolyfill&&(t.WebSocketPolyfill=s.WebSocketPolyfill),this.provider=new he(t),s?.quiet||console.info(`Hocuspocus Provider initialized: ${n}/${i}`)}}static createSharedWebSocket(t){if(ae.sharedWebSocketProvider)return console.warn("Shared WebSocket already exists. Returning existing instance."),ae.sharedWebSocketProvider;const e={url:t.url};return t.WebSocketPolyfill&&(e.WebSocketPolyfill=t.WebSocketPolyfill),t.onConnect&&(e.onConnect=t.onConnect),t.onDisconnect&&(e.onDisconnect=t.onDisconnect),t.onStatus&&(e.onStatus=t.onStatus),ae.sharedWebSocketProvider=new Qt(e),console.info("Shared Hocuspocus WebSocket created: "+t.url),ae.sharedWebSocketProvider}static destroySharedWebSocket(){ae.sharedWebSocketProvider&&(ae.sharedWebSocketProvider.destroy(),ae.sharedWebSocketProvider=null,console.info("Shared Hocuspocus WebSocket destroyed"))}static getSharedWebSocket(){return ae.sharedWebSocketProvider}static with(t){return{create:(e,s,i)=>{const n=i?{...t,...i}:t;return new ae(e,s,n)}}}async connect(){if(!this.isSynced)return new Promise(((t,e)=>{const s=setTimeout((()=>{e(Error("Hocuspocus connection timeout"))}),1e4),i=()=>{clearTimeout(s),this.provider.off("synced",i),t()};if(this.provider.on("synced",i),this.provider.isSynced)return clearTimeout(s),this.provider.off("synced",i),void t();this.isConnected||this.usesSharedSocket||this.provider.connect()}))}disconnect(){this.provider&&(this.usesSharedSocket?this.provider.detach():this.provider.disconnect()),this.isConnected=!1,this.isSynced=!1}destroy(){this.provider&&this.provider.destroy(),this.isConnected=!1,this.isSynced=!1}}export{M as BroadcastSyncProvider,ae as HocuspocusSyncProvider,P as WebSocketSyncProvider}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{K as o,d as s}from"./p-
|
|
1
|
+
import{K as o,d as s}from"./p-C1oYQPkf.js";const p=o,r=s;export{p as KritzelControls,r as defineCustomElement}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{K as
|
|
1
|
+
import{K as o,d as s}from"./p-COc0ML8P.js";const p=o,r=s;export{p as KritzelCurrentUser,r as defineCustomElement}
|