"use strict";
(self["webpackChunk_jupyter_shared_docprovider_extension"] = self["webpackChunk_jupyter_shared_docprovider_extension"] || []).push([["vendors-node_modules_jupyter_docprovider_lib_index_js"],{

/***/ "../../node_modules/css-loader/dist/cjs.js!../../node_modules/@jupyter/docprovider/style/slider.css":
/*!**********************************************************************************************************!*\
  !*** ../../node_modules/css-loader/dist/cjs.js!../../node_modules/@jupyter/docprovider/style/slider.css ***!
  \**********************************************************************************************************/
/***/ ((module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../css-loader/dist/runtime/sourceMaps.js */ "../../node_modules/css-loader/dist/runtime/sourceMaps.js");
/* harmony import */ var _css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../css-loader/dist/runtime/api.js */ "../../node_modules/css-loader/dist/runtime/api.js");
/* harmony import */ var _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1__);
// Imports


var ___CSS_LOADER_EXPORT___ = _css_loader_dist_runtime_api_js__WEBPACK_IMPORTED_MODULE_1___default()((_css_loader_dist_runtime_sourceMaps_js__WEBPACK_IMPORTED_MODULE_0___default()));
// Module
___CSS_LOADER_EXPORT___.push([module.id, `/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|---------------------------------------------------------------------------- */

.jp-timelineSliderWrapper .jp-sliderContainer{
  display: flex;
  align-items: center;
}

.jp-Slider {
  height: 4.5px
}

#jp-slider-status-bar {
  display: flex;
}

.jp-timestampDisplay {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 6px;
}

.jp-restoreBtnContainer {
  width: 192px;
}

.jp-ToolbarButtonComponent.jp-restoreBtn {
  cursor: pointer;
  color: var(--jp-layout-color2);
  width: 100%;
  background: var(--jp-accept-color-normal)
}
`, "",{"version":3,"sources":["webpack://./../../node_modules/@jupyter/docprovider/style/slider.css"],"names":[],"mappings":"AAAA;;;+EAG+E;;AAE/E;EACE,aAAa;EACb,mBAAmB;AACrB;;AAEA;EACE;AACF;;AAEA;EACE,aAAa;AACf;;AAEA;EACE,aAAa;EACb,mBAAmB;EACnB,mBAAmB;EACnB,QAAQ;AACV;;AAEA;EACE,YAAY;AACd;;AAEA;EACE,eAAe;EACf,8BAA8B;EAC9B,WAAW;EACX;AACF","sourcesContent":["/* -----------------------------------------------------------------------------\n| Copyright (c) Jupyter Development Team.\n| Distributed under the terms of the Modified BSD License.\n|---------------------------------------------------------------------------- */\n\n.jp-timelineSliderWrapper .jp-sliderContainer{\n  display: flex;\n  align-items: center;\n}\n\n.jp-Slider {\n  height: 4.5px\n}\n\n#jp-slider-status-bar {\n  display: flex;\n}\n\n.jp-timestampDisplay {\n  display: flex;\n  flex-direction: row;\n  align-items: center;\n  gap: 6px;\n}\n\n.jp-restoreBtnContainer {\n  width: 192px;\n}\n\n.jp-ToolbarButtonComponent.jp-restoreBtn {\n  cursor: pointer;\n  color: var(--jp-layout-color2);\n  width: 100%;\n  background: var(--jp-accept-color-normal)\n}\n"],"sourceRoot":""}]);
// Exports
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (___CSS_LOADER_EXPORT___);


/***/ }),

/***/ "../../node_modules/@jupyter/docprovider/lib/TimelineSlider.js":
/*!*********************************************************************!*\
  !*** ../../node_modules/@jupyter/docprovider/lib/TimelineSlider.js ***!
  \*********************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   TimelineWidget: () => (/* binding */ TimelineWidget)
/* harmony export */ });
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _component__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./component */ "../../node_modules/@jupyter/docprovider/lib/component.js");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/



class TimelineWidget extends _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.ReactWidget {
    constructor(apiURL, provider, contentType, format) {
        super();
        this.apiURL = apiURL;
        this.provider = provider;
        this.contentType = contentType;
        this.format = format;
        this.addClass('jp-timelineSliderWrapper');
    }
    render() {
        return (react__WEBPACK_IMPORTED_MODULE_1__.createElement(_component__WEBPACK_IMPORTED_MODULE_2__.TimelineSliderComponent, { key: this.apiURL, apiURL: this.apiURL, provider: this.provider, contentType: this.contentType, format: this.format }));
    }
    updateContent(apiURL, provider) {
        this.apiURL = apiURL;
        this.provider = provider;
        this.contentType = this.provider.contentType;
        this.format = this.provider.format;
        this.update();
    }
}


/***/ }),

/***/ "../../node_modules/@jupyter/docprovider/lib/awareness.js":
/*!****************************************************************!*\
  !*** ../../node_modules/@jupyter/docprovider/lib/awareness.js ***!
  \****************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   WebSocketAwarenessProvider: () => (/* binding */ WebSocketAwarenessProvider)
/* harmony export */ });
/* harmony import */ var y_websocket__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! y-websocket */ "../../node_modules/y-websocket/src/y-websocket.js");
/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/

/**
 * A class to provide Yjs synchronization over WebSocket.
 *
 * We specify custom messages that the server can interpret. For reference please look in yjs_ws_server.
 *
 */
class WebSocketAwarenessProvider extends y_websocket__WEBPACK_IMPORTED_MODULE_0__.WebsocketProvider {
    /**
     * Construct a new WebSocketAwarenessProvider
     *
     * @param options The instantiation options for a WebSocketAwarenessProvider
     */
    constructor(options) {
        super(options.url, options.roomID, options.awareness.doc, {
            awareness: options.awareness
        });
        this._isDisposed = false;
        this._awareness = options.awareness;
        this._user = options.user;
        this._user.ready
            .then(() => this._onUserChanged(this._user))
            .catch(e => console.error(e));
        this._user.userChanged.connect(this._onUserChanged, this);
    }
    get isDisposed() {
        return this._isDisposed;
    }
    dispose() {
        if (this._isDisposed) {
            return;
        }
        this._user.userChanged.disconnect(this._onUserChanged, this);
        this._isDisposed = true;
        this.destroy();
    }
    _onUserChanged(user) {
        this._awareness.setLocalStateField('user', user.identity);
    }
}


/***/ }),

/***/ "../../node_modules/@jupyter/docprovider/lib/component.js":
/*!****************************************************************!*\
  !*** ../../node_modules/@jupyter/docprovider/lib/component.js ***!
  \****************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   TimelineSliderComponent: () => (/* binding */ TimelineSliderComponent)
/* harmony export */ });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react */ "webpack/sharing/consume/default/react");
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _style_slider_css__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../style/slider.css */ "../../node_modules/@jupyter/docprovider/style/slider.css");
/* harmony import */ var _requests__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./requests */ "../../node_modules/@jupyter/docprovider/lib/requests.js");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @jupyterlab/ui-components */ "webpack/sharing/consume/default/@jupyterlab/ui-components");
/* harmony import */ var _jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__);
/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/





const TimelineSliderComponent = ({ apiURL, provider, contentType, format }) => {
    const [data, setData] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)({
        roomId: '',
        timestamps: [],
        forkRoom: '',
        sessionId: ''
    });
    const [currentTimestampIndex, setCurrentTimestampIndex] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(data.timestamps.length - 1);
    const [toggle, setToggle] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    const [isBtn, setIsBtn] = (0,react__WEBPACK_IMPORTED_MODULE_0__.useState)(false);
    const isFirstChange = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(true);
    const isFirstSliderChange = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(true);
    const sessionRef = (0,react__WEBPACK_IMPORTED_MODULE_0__.useRef)(null);
    async function fetchTimeline(notebookPath) {
        try {
            if (isFirstChange.current) {
                const response = await (0,_requests__WEBPACK_IMPORTED_MODULE_4__.requestDocumentTimeline)(format, contentType, notebookPath);
                if (!response.ok) {
                    if (response.status === 404) {
                        throw new Error('Not found');
                    }
                    else if (response.status === 503) {
                        throw new Error('WebSocket closed');
                    }
                    else {
                        throw new Error(`Failed to fetch data: ${response.statusText}`);
                    }
                }
                const text = await response.text();
                let data = { roomId: '', timestamps: [], forkRoom: '', sessionId: '' };
                if (text) {
                    _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.Notification.warning('Document is now in read-only mode. Changes will not be saved.', { autoClose: 2500 });
                    data = JSON.parse(text);
                    setData(data);
                    setCurrentTimestampIndex(data.timestamps.length - 1);
                    provider.connectToForkDoc(data.forkRoom, data.sessionId);
                    sessionRef.current = await (0,_requests__WEBPACK_IMPORTED_MODULE_4__.requestDocSession)(format, contentType, extractFilenameFromURL(apiURL));
                }
                setToggle(true);
                isFirstChange.current = false;
                return data;
            }
        }
        catch (error) {
            console.error('Error fetching data:', error);
        }
    }
    const handleRestore = async () => {
        if (!sessionRef.current) {
            console.error('Session is not initialized');
            return;
        }
        const response = await (0,_requests__WEBPACK_IMPORTED_MODULE_4__.requestUndoRedo)(`${sessionRef.current.format}:${sessionRef.current.type}:${sessionRef.current.fileId}`, 'restore', 0, data.forkRoom);
        if (response.code === 200) {
            _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.Notification.success(response.status, { autoClose: 4000 });
            provider.reconnect();
            setToggle(false);
            isFirstChange.current = true;
        }
        else {
            _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_3__.Notification.error(response.status, { autoClose: 4000 });
        }
    };
    const handleSliderChange = async (event) => {
        const currentTimestamp = parseInt(event.target.value);
        const steps = Math.abs(currentTimestamp - currentTimestampIndex);
        try {
            const action = determineAction(currentTimestamp);
            setCurrentTimestampIndex(currentTimestamp);
            if (isFirstSliderChange.current) {
                setIsBtn(true);
                isFirstSliderChange.current = false;
            }
            if (!sessionRef.current) {
                console.error('Session is not initialized');
                return;
            }
            await (0,_requests__WEBPACK_IMPORTED_MODULE_4__.requestUndoRedo)(`${sessionRef.current.format}:${sessionRef.current.type}:${sessionRef.current.fileId}`, action, steps, data.forkRoom);
        }
        catch (error) {
            console.error('Error fetching or applying updates:', error);
        }
    };
    function determineAction(currentTimestamp) {
        return currentTimestamp < currentTimestampIndex ? 'undo' : 'redo';
    }
    function extractFilenameFromURL(url) {
        try {
            const parsedURL = new URL(url);
            const pathname = parsedURL.pathname;
            const segments = pathname.split('/');
            return segments.slice(4 - segments.length).join('/');
        }
        catch (error) {
            console.error('Invalid URL:', error);
            return '';
        }
    }
    const formatTimestamp = (timestamp) => {
        const date = new Date(timestamp * 1000);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };
    return (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "jp-sliderContainer" },
        react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { onClick: () => {
                fetchTimeline(extractFilenameFromURL(apiURL));
            }, className: "jp-mod-highlighted", title: "Document Timeline" },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement(_jupyterlab_ui_components__WEBPACK_IMPORTED_MODULE_2__.historyIcon.react, { marginRight: "4px" })),
        toggle && (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "jp-timestampDisplay" },
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("input", { type: "range", min: 0, max: data.timestamps.length - 1, value: currentTimestampIndex, onChange: handleSliderChange, className: "jp-Slider" }),
            react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", null,
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("strong", null,
                    extractFilenameFromURL(apiURL).split('/').pop(),
                    " "),
                ' '),
            isBtn && (react__WEBPACK_IMPORTED_MODULE_0___default().createElement("div", { className: "jp-restoreBtnContainer" },
                react__WEBPACK_IMPORTED_MODULE_0___default().createElement("button", { onClick: handleRestore, className: "jp-ToolbarButtonComponent jp-restoreBtn" },
                    "Restore version",
                    ' ',
                    formatTimestamp(data.timestamps[currentTimestampIndex]))))))));
};


/***/ }),

/***/ "../../node_modules/@jupyter/docprovider/lib/index.js":
/*!************************************************************!*\
  !*** ../../node_modules/@jupyter/docprovider/lib/index.js ***!
  \************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ICollaborativeDrive: () => (/* reexport safe */ _tokens__WEBPACK_IMPORTED_MODULE_5__.ICollaborativeDrive),
/* harmony export */   IGlobalAwareness: () => (/* reexport safe */ _tokens__WEBPACK_IMPORTED_MODULE_5__.IGlobalAwareness),
/* harmony export */   NotebookCellServerExecutor: () => (/* reexport safe */ _notebookCellExecutor__WEBPACK_IMPORTED_MODULE_1__.NotebookCellServerExecutor),
/* harmony export */   TimelineWidget: () => (/* reexport safe */ _TimelineSlider__WEBPACK_IMPORTED_MODULE_6__.TimelineWidget),
/* harmony export */   WebSocketAwarenessProvider: () => (/* reexport safe */ _awareness__WEBPACK_IMPORTED_MODULE_0__.WebSocketAwarenessProvider),
/* harmony export */   WebSocketProvider: () => (/* reexport safe */ _yprovider__WEBPACK_IMPORTED_MODULE_4__.WebSocketProvider),
/* harmony export */   YDrive: () => (/* reexport safe */ _ydrive__WEBPACK_IMPORTED_MODULE_3__.YDrive),
/* harmony export */   requestDocSession: () => (/* reexport safe */ _requests__WEBPACK_IMPORTED_MODULE_2__.requestDocSession),
/* harmony export */   requestDocumentTimeline: () => (/* reexport safe */ _requests__WEBPACK_IMPORTED_MODULE_2__.requestDocumentTimeline),
/* harmony export */   requestUndoRedo: () => (/* reexport safe */ _requests__WEBPACK_IMPORTED_MODULE_2__.requestUndoRedo)
/* harmony export */ });
/* harmony import */ var _awareness__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./awareness */ "../../node_modules/@jupyter/docprovider/lib/awareness.js");
/* harmony import */ var _notebookCellExecutor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./notebookCellExecutor */ "../../node_modules/@jupyter/docprovider/lib/notebookCellExecutor.js");
/* harmony import */ var _requests__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./requests */ "../../node_modules/@jupyter/docprovider/lib/requests.js");
/* harmony import */ var _ydrive__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./ydrive */ "../../node_modules/@jupyter/docprovider/lib/ydrive.js");
/* harmony import */ var _yprovider__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./yprovider */ "../../node_modules/@jupyter/docprovider/lib/yprovider.js");
/* harmony import */ var _tokens__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./tokens */ "../../node_modules/@jupyter/docprovider/lib/tokens.js");
/* harmony import */ var _TimelineSlider__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./TimelineSlider */ "../../node_modules/@jupyter/docprovider/lib/TimelineSlider.js");
/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/
/**
 * @packageDocumentation
 * @module docprovider
 */









/***/ }),

/***/ "../../node_modules/@jupyter/docprovider/lib/notebookCellExecutor.js":
/*!***************************************************************************!*\
  !*** ../../node_modules/@jupyter/docprovider/lib/notebookCellExecutor.js ***!
  \***************************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   NotebookCellServerExecutor: () => (/* binding */ NotebookCellServerExecutor)
/* harmony export */ });
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/coreutils */ "webpack/sharing/consume/default/@jupyterlab/coreutils");
/* harmony import */ var _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _jupyterlab_services__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @jupyterlab/services */ "webpack/sharing/consume/default/@jupyterlab/services");
/* harmony import */ var _jupyterlab_services__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_services__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _jupyterlab_translation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! @jupyterlab/translation */ "webpack/sharing/consume/default/@jupyterlab/translation");
/* harmony import */ var _jupyterlab_translation__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_translation__WEBPACK_IMPORTED_MODULE_3__);
/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/




/**
 * Notebook cell executor posting a request to the server for execution.
 */
class NotebookCellServerExecutor {
    /**
     * Constructor
     *
     * @param options Constructor options; the contents manager, the collaborative drive and optionally the server settings.
     */
    constructor(options) {
        var _a;
        this._serverSettings =
            (_a = options.serverSettings) !== null && _a !== void 0 ? _a : _jupyterlab_services__WEBPACK_IMPORTED_MODULE_2__.ServerConnection.makeSettings();
    }
    /**
     * Execute a given cell of the notebook.
     *
     * @param options Execution options
     * @returns Execution success status
     */
    async runCell({ cell, notebook, notebookConfig, onCellExecuted, onCellExecutionScheduled, sessionContext, sessionDialogs, translator }) {
        var _a, _b, _c;
        translator = translator !== null && translator !== void 0 ? translator : _jupyterlab_translation__WEBPACK_IMPORTED_MODULE_3__.nullTranslator;
        const trans = translator.load('jupyterlab');
        switch (cell.model.type) {
            case 'markdown':
                cell.rendered = true;
                cell.inputHidden = false;
                onCellExecuted({ cell, success: true });
                break;
            case 'code':
                if (sessionContext) {
                    if (sessionContext.isTerminating) {
                        await (0,_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.showDialog)({
                            title: trans.__('Kernel Terminating'),
                            body: trans.__('The kernel for %1 appears to be terminating. You can not run any cell for now.', (_a = sessionContext.session) === null || _a === void 0 ? void 0 : _a.path),
                            buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.Dialog.okButton()]
                        });
                        break;
                    }
                    if (sessionContext.pendingInput) {
                        await (0,_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.showDialog)({
                            title: trans.__('Cell not executed due to pending input'),
                            body: trans.__('The cell has not been executed to avoid kernel deadlock as there is another pending input! Submit your pending input and try again.'),
                            buttons: [_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.Dialog.okButton()]
                        });
                        return false;
                    }
                    if (sessionContext.hasNoKernel) {
                        const shouldSelect = await sessionContext.startKernel();
                        if (shouldSelect && sessionDialogs) {
                            await sessionDialogs.selectKernel(sessionContext);
                        }
                    }
                    if (sessionContext.hasNoKernel) {
                        cell.model.sharedModel.transact(() => {
                            cell.model.clearExecution();
                        });
                        return true;
                    }
                    const kernelId = (_c = (_b = sessionContext === null || sessionContext === void 0 ? void 0 : sessionContext.session) === null || _b === void 0 ? void 0 : _b.kernel) === null || _c === void 0 ? void 0 : _c.id;
                    const apiURL = _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_1__.URLExt.join(this._serverSettings.baseUrl, `api/kernels/${kernelId}/execute`);
                    const cellId = cell.model.sharedModel.getId();
                    const documentId = notebook.sharedModel.getState('document_id');
                    const init = {
                        method: 'POST',
                        body: JSON.stringify({ cell_id: cellId, document_id: documentId })
                    };
                    onCellExecutionScheduled({ cell });
                    let success = false;
                    try {
                        // FIXME quid of deletedCells and timing record
                        const response = await _jupyterlab_services__WEBPACK_IMPORTED_MODULE_2__.ServerConnection.makeRequest(apiURL, init, this._serverSettings);
                        success = response.ok;
                    }
                    catch (error) {
                        onCellExecuted({
                            cell,
                            success: false
                        });
                        if (cell.isDisposed) {
                            return false;
                        }
                        else {
                            throw error;
                        }
                    }
                    onCellExecuted({ cell, success });
                    return true;
                }
                cell.model.sharedModel.transact(() => {
                    cell.model.clearExecution();
                }, false);
                break;
            default:
                break;
        }
        return Promise.resolve(true);
    }
}


/***/ }),

/***/ "../../node_modules/@jupyter/docprovider/lib/requests.js":
/*!***************************************************************!*\
  !*** ../../node_modules/@jupyter/docprovider/lib/requests.js ***!
  \***************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   requestDocSession: () => (/* binding */ requestDocSession),
/* harmony export */   requestDocumentTimeline: () => (/* binding */ requestDocumentTimeline),
/* harmony export */   requestUndoRedo: () => (/* binding */ requestUndoRedo)
/* harmony export */ });
/* harmony import */ var _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/coreutils */ "webpack/sharing/consume/default/@jupyterlab/coreutils");
/* harmony import */ var _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/services */ "webpack/sharing/consume/default/@jupyterlab/services");
/* harmony import */ var _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__);
/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/


/**
 * Document session endpoint provided by `jupyter_collaboration`
 * See https://github.com/jupyterlab/jupyter_collaboration
 */
const DOC_SESSION_URL = 'api/collaboration/session';
const DOC_FORK_URL = 'api/collaboration/undo_redo';
const TIMELINE_URL = 'api/collaboration/timeline';
async function requestDocSession(format, type, path) {
    const settings = _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.ServerConnection.makeSettings();
    const url = _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_0__.URLExt.join(settings.baseUrl, DOC_SESSION_URL, encodeURIComponent(path));
    const body = {
        method: 'PUT',
        body: JSON.stringify({ format, type })
    };
    let response;
    try {
        response = await _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.ServerConnection.makeRequest(url, body, settings);
    }
    catch (error) {
        throw new _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.ServerConnection.NetworkError(error);
    }
    let data = await response.text();
    if (data.length > 0) {
        try {
            data = JSON.parse(data);
        }
        catch (error) {
            console.log('Not a JSON response body.', response);
        }
    }
    if (!response.ok) {
        throw new _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.ServerConnection.ResponseError(response, data.message || data);
    }
    return data;
}
async function requestDocumentTimeline(format, type, path) {
    const settings = _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.ServerConnection.makeSettings();
    let url = _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_0__.URLExt.join(settings.baseUrl, TIMELINE_URL, path);
    url = url.concat(`?format=${format}&&type=${type}`);
    const body = {
        method: 'GET'
    };
    let response;
    try {
        response = await _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.ServerConnection.makeRequest(url, body, settings);
    }
    catch (error) {
        throw new _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.ServerConnection.NetworkError(error);
    }
    return response;
}
async function requestUndoRedo(roomid, action, steps, forkRoom) {
    const settings = _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.ServerConnection.makeSettings();
    let url = _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_0__.URLExt.join(settings.baseUrl, DOC_FORK_URL, encodeURIComponent(roomid));
    url = url.concat(`?action=${action}&&steps=${steps}&&forkRoom=${forkRoom}`);
    const body = { method: 'PUT' };
    let response;
    try {
        response = await _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.ServerConnection.makeRequest(url, body, settings);
    }
    catch (error) {
        throw new _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.ServerConnection.NetworkError(error);
    }
    let data = await response.text();
    if (data.length > 0) {
        try {
            data = JSON.parse(data);
        }
        catch (error) {
            console.log('Not a JSON response body.', response);
        }
    }
    if (!response.ok) {
        throw new _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.ServerConnection.ResponseError(response, data.message || data);
    }
    return data;
}


/***/ }),

/***/ "../../node_modules/@jupyter/docprovider/lib/tokens.js":
/*!*************************************************************!*\
  !*** ../../node_modules/@jupyter/docprovider/lib/tokens.js ***!
  \*************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   ICollaborativeDrive: () => (/* binding */ ICollaborativeDrive),
/* harmony export */   IGlobalAwareness: () => (/* binding */ IGlobalAwareness)
/* harmony export */ });
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @lumino/coreutils */ "webpack/sharing/consume/default/@lumino/coreutils");
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_lumino_coreutils__WEBPACK_IMPORTED_MODULE_0__);
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

/**
 * The collaborative drive.
 */
const ICollaborativeDrive = new _lumino_coreutils__WEBPACK_IMPORTED_MODULE_0__.Token('@jupyter/collaboration-extension:ICollaborativeDrive');
/**
 * The global awareness token.
 */
const IGlobalAwareness = new _lumino_coreutils__WEBPACK_IMPORTED_MODULE_0__.Token('@jupyter/collaboration:IGlobalAwareness');


/***/ }),

/***/ "../../node_modules/@jupyter/docprovider/lib/ydrive.js":
/*!*************************************************************!*\
  !*** ../../node_modules/@jupyter/docprovider/lib/ydrive.js ***!
  \*************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   YDrive: () => (/* binding */ YDrive)
/* harmony export */ });
/* harmony import */ var _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/coreutils */ "webpack/sharing/consume/default/@jupyterlab/coreutils");
/* harmony import */ var _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @jupyterlab/services */ "webpack/sharing/consume/default/@jupyterlab/services");
/* harmony import */ var _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _lumino_signaling__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @lumino/signaling */ "webpack/sharing/consume/default/@lumino/signaling");
/* harmony import */ var _lumino_signaling__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_lumino_signaling__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _yprovider__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./yprovider */ "../../node_modules/@jupyter/docprovider/lib/yprovider.js");
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.




const DISABLE_RTC = _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_0__.PageConfig.getOption('disableRTC') === 'true' ? true : false;
/**
 * The url for the default drive service.
 */
const DOCUMENT_PROVIDER_URL = 'api/collaboration/room';
/**
 * A Collaborative implementation for an `IDrive`, talking to the
 * server using the Jupyter REST API and a WebSocket connection.
 */
class YDrive extends _jupyterlab_services__WEBPACK_IMPORTED_MODULE_1__.Drive {
    /**
     * Construct a new drive object.
     *
     * @param user - The user manager to add the identity to the awareness of documents.
     */
    constructor(user, translator, globalAwareness) {
        super({ name: 'RTC' });
        this._onCreate = (options, sharedModel) => {
            var _a, _b;
            if (typeof options.format !== 'string') {
                return;
            }
            try {
                const provider = new _yprovider__WEBPACK_IMPORTED_MODULE_3__.WebSocketProvider({
                    url: _jupyterlab_coreutils__WEBPACK_IMPORTED_MODULE_0__.URLExt.join(this.serverSettings.wsUrl, DOCUMENT_PROVIDER_URL),
                    path: options.path,
                    format: options.format,
                    contentType: options.contentType,
                    model: sharedModel,
                    user: this._user,
                    translator: this._trans
                });
                // Add the document path in the list of opened ones for this user.
                const state = ((_a = this._globalAwareness) === null || _a === void 0 ? void 0 : _a.getLocalState()) || {};
                const documents = state.documents || [];
                if (!documents.includes(options.path)) {
                    documents.push(`${this.name}:${options.path}`);
                    (_b = this._globalAwareness) === null || _b === void 0 ? void 0 : _b.setLocalStateField('documents', documents);
                }
                const key = `${options.format}:${options.contentType}:${options.path}`;
                this._providers.set(key, provider);
                sharedModel.changed.connect(async (_, change) => {
                    if (!change.stateChange) {
                        return;
                    }
                    const hashChanges = change.stateChange.filter(change => change.name === 'hash');
                    if (hashChanges.length === 0) {
                        return;
                    }
                    if (hashChanges.length > 1) {
                        console.error('Unexpected multiple changes to hash value in a single transaction');
                    }
                    const hashChange = hashChanges[0];
                    // A change in hash signifies that a save occurred on the server-side
                    // (e.g. a collaborator performed the save) - we want to notify the
                    // observers about this change so that they can store the new hash value.
                    const model = await this.get(options.path, { content: false });
                    this._ydriveFileChanged.emit({
                        type: 'save',
                        newValue: { ...model, hash: hashChange.newValue },
                        // we do not have the old model because it was discarded when server made the change,
                        // we only have the old hash here (which may be empty if the file was newly created!)
                        oldValue: { hash: hashChange.oldValue }
                    });
                });
                sharedModel.disposed.connect(() => {
                    var _a, _b;
                    const provider = this._providers.get(key);
                    if (provider) {
                        provider.dispose();
                        this._providers.delete(key);
                    }
                    // Remove the document path from the list of opened ones for this user.
                    const state = ((_a = this._globalAwareness) === null || _a === void 0 ? void 0 : _a.getLocalState()) || {};
                    const documents = state.documents || [];
                    const index = documents.indexOf(`${this.name}:${options.path}`);
                    if (index > -1) {
                        documents.splice(index, 1);
                    }
                    (_b = this._globalAwareness) === null || _b === void 0 ? void 0 : _b.setLocalStateField('documents', documents);
                });
            }
            catch (error) {
                // Falling back to the contents API if opening the websocket failed
                //  This may happen if the shared document is not a YDocument.
                console.error(`Failed to open websocket connection for ${options.path}.\n:${error}`);
            }
        };
        this._ydriveFileChanged = new _lumino_signaling__WEBPACK_IMPORTED_MODULE_2__.Signal(this);
        this._user = user;
        this._trans = translator;
        this._globalAwareness = globalAwareness;
        this._providers = new Map();
        this.sharedModelFactory = new SharedModelFactory(this._onCreate);
        super.fileChanged.connect((_, change) => {
            // pass through any events from the Drive superclass
            this._ydriveFileChanged.emit(change);
        });
    }
    get providers() {
        return this._providers;
    }
    /**
     * Dispose of the resources held by the manager.
     */
    dispose() {
        if (this.isDisposed) {
            return;
        }
        this._providers.forEach(p => p.dispose());
        this._providers.clear();
        super.dispose();
    }
    /**
     * Get a file or directory.
     *
     * @param localPath: The path to the file.
     *
     * @param options: The options used to fetch the file.
     *
     * @returns A promise which resolves with the file content.
     *
     * Uses the [Jupyter Notebook API](http://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyter/notebook/master/notebook/services/api/api.yaml#!/contents) and validates the response model.
     */
    async get(localPath, options) {
        if (options && options.format && options.type) {
            const key = `${options.format}:${options.type}:${localPath}`;
            const provider = this._providers.get(key);
            if (provider) {
                // If the document doesn't exist, `super.get` will reject with an
                // error and the provider will never be resolved.
                // Use `Promise.all` to reject as soon as possible. The Context will
                // show a dialog to the user.
                const [model] = await Promise.all([
                    super.get(localPath, { ...options, content: false }),
                    provider.ready
                ]);
                return model;
            }
        }
        return super.get(localPath, options);
    }
    /**
     * Save a file.
     *
     * @param localPath - The desired file path.
     *
     * @param options - Optional overrides to the model.
     *
     * @returns A promise which resolves with the file content model when the
     *   file is saved.
     */
    async save(localPath, options = {}) {
        // Check that there is a provider - it won't e.g. if the document model is not collaborative.
        if (options.format && options.type) {
            const key = `${options.format}:${options.type}:${localPath}`;
            const provider = this._providers.get(key);
            if (provider) {
                // Save is done from the backend
                const fetchOptions = {
                    type: options.type,
                    format: options.format,
                    content: false
                };
                return this.get(localPath, fetchOptions);
            }
        }
        return super.save(localPath, options);
    }
    /**
     * A signal emitted when a file operation takes place.
     */
    get fileChanged() {
        return this._ydriveFileChanged;
    }
}
/**
 * Yjs sharedModel factory for real-time collaboration.
 */
class SharedModelFactory {
    /**
     * Shared model factory constructor
     *
     * @param _onCreate Callback on new document model creation
     */
    constructor(_onCreate) {
        this._onCreate = _onCreate;
        /**
         * Whether the IDrive supports real-time collaboration or not.
         */
        this.collaborative = !DISABLE_RTC;
        this._documentFactories = new Map();
    }
    /**
     * Register a SharedDocumentFactory.
     *
     * @param type Document type
     * @param factory Document factory
     */
    registerDocumentFactory(type, factory) {
        if (this._documentFactories.has(type)) {
            throw new Error(`The content type ${type} already exists`);
        }
        this._documentFactories.set(type, factory);
    }
    /**
     * Create a new `ISharedDocument` instance.
     *
     * It should return `undefined` if the factory is not able to create a `ISharedDocument`.
     */
    createNew(options) {
        if (typeof options.format !== 'string') {
            console.warn(`Only defined format are supported; got ${options.format}.`);
            return;
        }
        if (!this.collaborative || !options.collaborative) {
            // Bail if the document model does not support collaboration
            // the `sharedModel` will be the default one.
            return;
        }
        if (this._documentFactories.has(options.contentType)) {
            const factory = this._documentFactories.get(options.contentType);
            const sharedModel = factory(options);
            this._onCreate(options, sharedModel);
            return sharedModel;
        }
        return;
    }
}


/***/ }),

/***/ "../../node_modules/@jupyter/docprovider/lib/yprovider.js":
/*!****************************************************************!*\
  !*** ../../node_modules/@jupyter/docprovider/lib/yprovider.js ***!
  \****************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   WebSocketProvider: () => (/* binding */ WebSocketProvider)
/* harmony export */ });
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @jupyterlab/apputils */ "webpack/sharing/consume/default/@jupyterlab/apputils");
/* harmony import */ var _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @lumino/coreutils */ "webpack/sharing/consume/default/@lumino/coreutils");
/* harmony import */ var _lumino_coreutils__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_lumino_coreutils__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _lumino_signaling__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @lumino/signaling */ "webpack/sharing/consume/default/@lumino/signaling");
/* harmony import */ var _lumino_signaling__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_lumino_signaling__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var y_websocket__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! y-websocket */ "../../node_modules/y-websocket/src/y-websocket.js");
/* harmony import */ var _requests__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./requests */ "../../node_modules/@jupyter/docprovider/lib/requests.js");
/* -----------------------------------------------------------------------------
| Copyright (c) Jupyter Development Team.
| Distributed under the terms of the Modified BSD License.
|----------------------------------------------------------------------------*/





/**
 * A class to provide Yjs synchronization over WebSocket.
 *
 * We specify custom messages that the server can interpret. For reference please look in yjs_ws_server.
 *
 */
class WebSocketProvider {
    /**
     * Construct a new WebSocketProvider
     *
     * @param options The instantiation options for a WebSocketProvider
     */
    constructor(options) {
        this._onConnectionClosed = (event) => {
            if (event.code === 1003) {
                console.error('Document provider closed:', event.reason);
                (0,_jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.showErrorMessage)(this._trans.__('Document session error'), event.reason, [
                    _jupyterlab_apputils__WEBPACK_IMPORTED_MODULE_0__.Dialog.okButton()
                ]);
                // Dispose shared model immediately. Better break the document model,
                // than overriding data on disk.
                this._sharedModel.dispose();
            }
        };
        this._onSync = (isSynced) => {
            if (isSynced) {
                if (this._yWebsocketProvider) {
                    this._yWebsocketProvider.off('sync', this._onSync);
                    const state = this._sharedModel.ydoc.getMap('state');
                    state.set('document_id', this._yWebsocketProvider.roomname);
                }
                this._ready.resolve();
            }
        };
        this._ready = new _lumino_coreutils__WEBPACK_IMPORTED_MODULE_1__.PromiseDelegate();
        this._isDisposed = false;
        this._path = options.path;
        this._contentType = options.contentType;
        this._format = options.format;
        this._serverUrl = options.url;
        this._sharedModel = options.model;
        this._awareness = options.model.awareness;
        this._yWebsocketProvider = null;
        this._trans = options.translator;
        const user = options.user;
        user.ready
            .then(() => {
            this._onUserChanged(user);
        })
            .catch(e => console.error(e));
        user.userChanged.connect(this._onUserChanged, this);
        this._connect().catch(e => console.warn(e));
    }
    /**
     * Test whether the object has been disposed.
     */
    get isDisposed() {
        return this._isDisposed;
    }
    /**
     * A promise that resolves when the document provider is ready.
     */
    get ready() {
        return this._ready.promise;
    }
    get contentType() {
        return this._contentType;
    }
    get format() {
        return this._format;
    }
    /**
     * Dispose of the resources held by the object.
     */
    dispose() {
        var _a, _b, _c;
        if (this.isDisposed) {
            return;
        }
        this._isDisposed = true;
        (_a = this._yWebsocketProvider) === null || _a === void 0 ? void 0 : _a.off('connection-close', this._onConnectionClosed);
        (_b = this._yWebsocketProvider) === null || _b === void 0 ? void 0 : _b.off('sync', this._onSync);
        (_c = this._yWebsocketProvider) === null || _c === void 0 ? void 0 : _c.destroy();
        this._disconnect();
        _lumino_signaling__WEBPACK_IMPORTED_MODULE_2__.Signal.clearData(this);
    }
    async reconnect() {
        this._disconnect();
        this._connect();
    }
    async _connect() {
        const session = await (0,_requests__WEBPACK_IMPORTED_MODULE_3__.requestDocSession)(this._format, this._contentType, this._path);
        this._yWebsocketProvider = new y_websocket__WEBPACK_IMPORTED_MODULE_4__.WebsocketProvider(this._serverUrl, `${session.format}:${session.type}:${session.fileId}`, this._sharedModel.ydoc, {
            disableBc: true,
            params: { sessionId: session.sessionId },
            awareness: this._awareness
        });
        this._yWebsocketProvider.on('sync', this._onSync);
        this._yWebsocketProvider.on('connection-close', this._onConnectionClosed);
    }
    async connectToForkDoc(forkRoomId, sessionId) {
        this._disconnect();
        this._yWebsocketProvider = new y_websocket__WEBPACK_IMPORTED_MODULE_4__.WebsocketProvider(this._serverUrl, forkRoomId, this._sharedModel.ydoc, {
            disableBc: true,
            params: { sessionId },
            awareness: this._awareness
        });
    }
    get wsProvider() {
        return this._yWebsocketProvider;
    }
    _disconnect() {
        var _a, _b, _c;
        (_a = this._yWebsocketProvider) === null || _a === void 0 ? void 0 : _a.off('connection-close', this._onConnectionClosed);
        (_b = this._yWebsocketProvider) === null || _b === void 0 ? void 0 : _b.off('sync', this._onSync);
        (_c = this._yWebsocketProvider) === null || _c === void 0 ? void 0 : _c.destroy();
        this._yWebsocketProvider = null;
    }
    _onUserChanged(user) {
        this._awareness.setLocalStateField('user', user.identity);
    }
}


/***/ }),

/***/ "../../node_modules/css-loader/dist/runtime/api.js":
/*!*********************************************************!*\
  !*** ../../node_modules/css-loader/dist/runtime/api.js ***!
  \*********************************************************/
/***/ ((module) => {



/*
  MIT License http://www.opensource.org/licenses/mit-license.php
  Author Tobias Koppers @sokra
*/
module.exports = function (cssWithMappingToString) {
  var list = [];

  // return the list of modules as css string
  list.toString = function toString() {
    return this.map(function (item) {
      var content = "";
      var needLayer = typeof item[5] !== "undefined";
      if (item[4]) {
        content += "@supports (".concat(item[4], ") {");
      }
      if (item[2]) {
        content += "@media ".concat(item[2], " {");
      }
      if (needLayer) {
        content += "@layer".concat(item[5].length > 0 ? " ".concat(item[5]) : "", " {");
      }
      content += cssWithMappingToString(item);
      if (needLayer) {
        content += "}";
      }
      if (item[2]) {
        content += "}";
      }
      if (item[4]) {
        content += "}";
      }
      return content;
    }).join("");
  };

  // import a list of modules into the list
  list.i = function i(modules, media, dedupe, supports, layer) {
    if (typeof modules === "string") {
      modules = [[null, modules, undefined]];
    }
    var alreadyImportedModules = {};
    if (dedupe) {
      for (var k = 0; k < this.length; k++) {
        var id = this[k][0];
        if (id != null) {
          alreadyImportedModules[id] = true;
        }
      }
    }
    for (var _k = 0; _k < modules.length; _k++) {
      var item = [].concat(modules[_k]);
      if (dedupe && alreadyImportedModules[item[0]]) {
        continue;
      }
      if (typeof layer !== "undefined") {
        if (typeof item[5] === "undefined") {
          item[5] = layer;
        } else {
          item[1] = "@layer".concat(item[5].length > 0 ? " ".concat(item[5]) : "", " {").concat(item[1], "}");
          item[5] = layer;
        }
      }
      if (media) {
        if (!item[2]) {
          item[2] = media;
        } else {
          item[1] = "@media ".concat(item[2], " {").concat(item[1], "}");
          item[2] = media;
        }
      }
      if (supports) {
        if (!item[4]) {
          item[4] = "".concat(supports);
        } else {
          item[1] = "@supports (".concat(item[4], ") {").concat(item[1], "}");
          item[4] = supports;
        }
      }
      list.push(item);
    }
  };
  return list;
};

/***/ }),

/***/ "../../node_modules/css-loader/dist/runtime/sourceMaps.js":
/*!****************************************************************!*\
  !*** ../../node_modules/css-loader/dist/runtime/sourceMaps.js ***!
  \****************************************************************/
/***/ ((module) => {



module.exports = function (item) {
  var content = item[1];
  var cssMapping = item[3];
  if (!cssMapping) {
    return content;
  }
  if (typeof btoa === "function") {
    var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(cssMapping))));
    var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
    var sourceMapping = "/*# ".concat(data, " */");
    return [content].concat([sourceMapping]).join("\n");
  }
  return [content].join("\n");
};

/***/ }),

/***/ "../../node_modules/lib0/url.js":
/*!**************************************!*\
  !*** ../../node_modules/lib0/url.js ***!
  \**************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   decodeQueryParams: () => (/* binding */ decodeQueryParams),
/* harmony export */   encodeQueryParams: () => (/* binding */ encodeQueryParams)
/* harmony export */ });
/* harmony import */ var _object_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./object.js */ "../../node_modules/lib0/object.js");
/**
 * Utility module to work with urls.
 *
 * @module url
 */



/**
 * Parse query parameters from an url.
 *
 * @param {string} url
 * @return {Object<string,string>}
 */
const decodeQueryParams = url => {
  /**
   * @type {Object<string,string>}
   */
  const query = {}
  const urlQuerySplit = url.split('?')
  const pairs = urlQuerySplit[urlQuerySplit.length - 1].split('&')
  for (let i = 0; i < pairs.length; i++) {
    const item = pairs[i]
    if (item.length > 0) {
      const pair = item.split('=')
      query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '')
    }
  }
  return query
}

/**
 * @param {Object<string,string>} params
 * @return {string}
 */
const encodeQueryParams = params =>
  _object_js__WEBPACK_IMPORTED_MODULE_0__.map(params, (val, key) => `${encodeURIComponent(key)}=${encodeURIComponent(val)}`).join('&')


/***/ }),

/***/ "../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js":
/*!********************************************************************************!*\
  !*** ../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js ***!
  \********************************************************************************/
/***/ ((module) => {



var stylesInDOM = [];
function getIndexByIdentifier(identifier) {
  var result = -1;
  for (var i = 0; i < stylesInDOM.length; i++) {
    if (stylesInDOM[i].identifier === identifier) {
      result = i;
      break;
    }
  }
  return result;
}
function modulesToDom(list, options) {
  var idCountMap = {};
  var identifiers = [];
  for (var i = 0; i < list.length; i++) {
    var item = list[i];
    var id = options.base ? item[0] + options.base : item[0];
    var count = idCountMap[id] || 0;
    var identifier = "".concat(id, " ").concat(count);
    idCountMap[id] = count + 1;
    var indexByIdentifier = getIndexByIdentifier(identifier);
    var obj = {
      css: item[1],
      media: item[2],
      sourceMap: item[3],
      supports: item[4],
      layer: item[5]
    };
    if (indexByIdentifier !== -1) {
      stylesInDOM[indexByIdentifier].references++;
      stylesInDOM[indexByIdentifier].updater(obj);
    } else {
      var updater = addElementStyle(obj, options);
      options.byIndex = i;
      stylesInDOM.splice(i, 0, {
        identifier: identifier,
        updater: updater,
        references: 1
      });
    }
    identifiers.push(identifier);
  }
  return identifiers;
}
function addElementStyle(obj, options) {
  var api = options.domAPI(options);
  api.update(obj);
  var updater = function updater(newObj) {
    if (newObj) {
      if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap && newObj.supports === obj.supports && newObj.layer === obj.layer) {
        return;
      }
      api.update(obj = newObj);
    } else {
      api.remove();
    }
  };
  return updater;
}
module.exports = function (list, options) {
  options = options || {};
  list = list || [];
  var lastIdentifiers = modulesToDom(list, options);
  return function update(newList) {
    newList = newList || [];
    for (var i = 0; i < lastIdentifiers.length; i++) {
      var identifier = lastIdentifiers[i];
      var index = getIndexByIdentifier(identifier);
      stylesInDOM[index].references--;
    }
    var newLastIdentifiers = modulesToDom(newList, options);
    for (var _i = 0; _i < lastIdentifiers.length; _i++) {
      var _identifier = lastIdentifiers[_i];
      var _index = getIndexByIdentifier(_identifier);
      if (stylesInDOM[_index].references === 0) {
        stylesInDOM[_index].updater();
        stylesInDOM.splice(_index, 1);
      }
    }
    lastIdentifiers = newLastIdentifiers;
  };
};

/***/ }),

/***/ "../../node_modules/style-loader/dist/runtime/insertBySelector.js":
/*!************************************************************************!*\
  !*** ../../node_modules/style-loader/dist/runtime/insertBySelector.js ***!
  \************************************************************************/
/***/ ((module) => {



var memo = {};

/* istanbul ignore next  */
function getTarget(target) {
  if (typeof memo[target] === "undefined") {
    var styleTarget = document.querySelector(target);

    // Special case to return head of iframe instead of iframe itself
    if (window.HTMLIFrameElement && styleTarget instanceof window.HTMLIFrameElement) {
      try {
        // This will throw an exception if access to iframe is blocked
        // due to cross-origin restrictions
        styleTarget = styleTarget.contentDocument.head;
      } catch (e) {
        // istanbul ignore next
        styleTarget = null;
      }
    }
    memo[target] = styleTarget;
  }
  return memo[target];
}

/* istanbul ignore next  */
function insertBySelector(insert, style) {
  var target = getTarget(insert);
  if (!target) {
    throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");
  }
  target.appendChild(style);
}
module.exports = insertBySelector;

/***/ }),

/***/ "../../node_modules/style-loader/dist/runtime/insertStyleElement.js":
/*!**************************************************************************!*\
  !*** ../../node_modules/style-loader/dist/runtime/insertStyleElement.js ***!
  \**************************************************************************/
/***/ ((module) => {



/* istanbul ignore next  */
function insertStyleElement(options) {
  var element = document.createElement("style");
  options.setAttributes(element, options.attributes);
  options.insert(element, options.options);
  return element;
}
module.exports = insertStyleElement;

/***/ }),

/***/ "../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js":
/*!**************************************************************************************!*\
  !*** ../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js ***!
  \**************************************************************************************/
/***/ ((module, __unused_webpack_exports, __webpack_require__) => {



/* istanbul ignore next  */
function setAttributesWithoutAttributes(styleElement) {
  var nonce =  true ? __webpack_require__.nc : 0;
  if (nonce) {
    styleElement.setAttribute("nonce", nonce);
  }
}
module.exports = setAttributesWithoutAttributes;

/***/ }),

/***/ "../../node_modules/style-loader/dist/runtime/styleDomAPI.js":
/*!*******************************************************************!*\
  !*** ../../node_modules/style-loader/dist/runtime/styleDomAPI.js ***!
  \*******************************************************************/
/***/ ((module) => {



/* istanbul ignore next  */
function apply(styleElement, options, obj) {
  var css = "";
  if (obj.supports) {
    css += "@supports (".concat(obj.supports, ") {");
  }
  if (obj.media) {
    css += "@media ".concat(obj.media, " {");
  }
  var needLayer = typeof obj.layer !== "undefined";
  if (needLayer) {
    css += "@layer".concat(obj.layer.length > 0 ? " ".concat(obj.layer) : "", " {");
  }
  css += obj.css;
  if (needLayer) {
    css += "}";
  }
  if (obj.media) {
    css += "}";
  }
  if (obj.supports) {
    css += "}";
  }
  var sourceMap = obj.sourceMap;
  if (sourceMap && typeof btoa !== "undefined") {
    css += "\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))), " */");
  }

  // For old IE
  /* istanbul ignore if  */
  options.styleTagTransform(css, styleElement, options.options);
}
function removeStyleElement(styleElement) {
  // istanbul ignore if
  if (styleElement.parentNode === null) {
    return false;
  }
  styleElement.parentNode.removeChild(styleElement);
}

/* istanbul ignore next  */
function domAPI(options) {
  if (typeof document === "undefined") {
    return {
      update: function update() {},
      remove: function remove() {}
    };
  }
  var styleElement = options.insertStyleElement(options);
  return {
    update: function update(obj) {
      apply(styleElement, options, obj);
    },
    remove: function remove() {
      removeStyleElement(styleElement);
    }
  };
}
module.exports = domAPI;

/***/ }),

/***/ "../../node_modules/style-loader/dist/runtime/styleTagTransform.js":
/*!*************************************************************************!*\
  !*** ../../node_modules/style-loader/dist/runtime/styleTagTransform.js ***!
  \*************************************************************************/
/***/ ((module) => {



/* istanbul ignore next  */
function styleTagTransform(css, styleElement) {
  if (styleElement.styleSheet) {
    styleElement.styleSheet.cssText = css;
  } else {
    while (styleElement.firstChild) {
      styleElement.removeChild(styleElement.firstChild);
    }
    styleElement.appendChild(document.createTextNode(css));
  }
}
module.exports = styleTagTransform;

/***/ }),

/***/ "../../node_modules/y-protocols/auth.js":
/*!**********************************************!*\
  !*** ../../node_modules/y-protocols/auth.js ***!
  \**********************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   messagePermissionDenied: () => (/* binding */ messagePermissionDenied),
/* harmony export */   readAuthMessage: () => (/* binding */ readAuthMessage),
/* harmony export */   writePermissionDenied: () => (/* binding */ writePermissionDenied)
/* harmony export */ });
/* harmony import */ var yjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! yjs */ "webpack/sharing/consume/default/yjs");
/* harmony import */ var yjs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(yjs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lib0_encoding__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! lib0/encoding */ "../../node_modules/lib0/encoding.js");
/* harmony import */ var lib0_decoding__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! lib0/decoding */ "../../node_modules/lib0/decoding.js");

 // eslint-disable-line



const messagePermissionDenied = 0

/**
 * @param {encoding.Encoder} encoder
 * @param {string} reason
 */
const writePermissionDenied = (encoder, reason) => {
  lib0_encoding__WEBPACK_IMPORTED_MODULE_1__.writeVarUint(encoder, messagePermissionDenied)
  lib0_encoding__WEBPACK_IMPORTED_MODULE_1__.writeVarString(encoder, reason)
}

/**
 * @callback PermissionDeniedHandler
 * @param {any} y
 * @param {string} reason
 */

/**
 *
 * @param {decoding.Decoder} decoder
 * @param {Y.Doc} y
 * @param {PermissionDeniedHandler} permissionDeniedHandler
 */
const readAuthMessage = (decoder, y, permissionDeniedHandler) => {
  switch (lib0_decoding__WEBPACK_IMPORTED_MODULE_2__.readVarUint(decoder)) {
    case messagePermissionDenied: permissionDeniedHandler(y, lib0_decoding__WEBPACK_IMPORTED_MODULE_2__.readVarString(decoder))
  }
}


/***/ }),

/***/ "../../node_modules/y-websocket/src/y-websocket.js":
/*!*********************************************************!*\
  !*** ../../node_modules/y-websocket/src/y-websocket.js ***!
  \*********************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   WebsocketProvider: () => (/* binding */ WebsocketProvider),
/* harmony export */   messageAuth: () => (/* binding */ messageAuth),
/* harmony export */   messageAwareness: () => (/* binding */ messageAwareness),
/* harmony export */   messageQueryAwareness: () => (/* binding */ messageQueryAwareness),
/* harmony export */   messageSync: () => (/* binding */ messageSync)
/* harmony export */ });
/* harmony import */ var yjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! yjs */ "webpack/sharing/consume/default/yjs");
/* harmony import */ var yjs__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(yjs__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var lib0_broadcastchannel__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! lib0/broadcastchannel */ "../../node_modules/lib0/broadcastchannel.js");
/* harmony import */ var lib0_time__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! lib0/time */ "../../node_modules/lib0/time.js");
/* harmony import */ var lib0_encoding__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! lib0/encoding */ "../../node_modules/lib0/encoding.js");
/* harmony import */ var lib0_decoding__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! lib0/decoding */ "../../node_modules/lib0/decoding.js");
/* harmony import */ var y_protocols_sync__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! y-protocols/sync */ "../../node_modules/y-protocols/sync.js");
/* harmony import */ var y_protocols_auth__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! y-protocols/auth */ "../../node_modules/y-protocols/auth.js");
/* harmony import */ var y_protocols_awareness__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! y-protocols/awareness */ "../../node_modules/y-protocols/awareness.js");
/* harmony import */ var lib0_observable__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! lib0/observable */ "../../node_modules/lib0/observable.js");
/* harmony import */ var lib0_math__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! lib0/math */ "../../node_modules/lib0/math.js");
/* harmony import */ var lib0_url__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! lib0/url */ "../../node_modules/lib0/url.js");
/* harmony import */ var lib0_environment__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! lib0/environment */ "../../node_modules/lib0/environment.js");
/* provided dependency */ var process = __webpack_require__(/*! process/browser */ "../../node_modules/process/browser.js");
/**
 * @module provider/websocket
 */

/* eslint-env browser */

 // eslint-disable-line












const messageSync = 0
const messageQueryAwareness = 3
const messageAwareness = 1
const messageAuth = 2

/**
 *                       encoder,          decoder,          provider,          emitSynced, messageType
 * @type {Array<function(encoding.Encoder, decoding.Decoder, WebsocketProvider, boolean,    number):void>}
 */
const messageHandlers = []

messageHandlers[messageSync] = (
  encoder,
  decoder,
  provider,
  emitSynced,
  _messageType
) => {
  lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder, messageSync)
  const syncMessageType = y_protocols_sync__WEBPACK_IMPORTED_MODULE_1__.readSyncMessage(
    decoder,
    encoder,
    provider.doc,
    provider
  )
  if (
    emitSynced && syncMessageType === y_protocols_sync__WEBPACK_IMPORTED_MODULE_1__.messageYjsSyncStep2 &&
    !provider.synced
  ) {
    provider.synced = true
  }
}

messageHandlers[messageQueryAwareness] = (
  encoder,
  _decoder,
  provider,
  _emitSynced,
  _messageType
) => {
  lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder, messageAwareness)
  lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint8Array(
    encoder,
    y_protocols_awareness__WEBPACK_IMPORTED_MODULE_3__.encodeAwarenessUpdate(
      provider.awareness,
      Array.from(provider.awareness.getStates().keys())
    )
  )
}

messageHandlers[messageAwareness] = (
  _encoder,
  decoder,
  provider,
  _emitSynced,
  _messageType
) => {
  y_protocols_awareness__WEBPACK_IMPORTED_MODULE_3__.applyAwarenessUpdate(
    provider.awareness,
    lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint8Array(decoder),
    provider
  )
}

messageHandlers[messageAuth] = (
  _encoder,
  decoder,
  provider,
  _emitSynced,
  _messageType
) => {
  y_protocols_auth__WEBPACK_IMPORTED_MODULE_2__.readAuthMessage(
    decoder,
    provider.doc,
    (_ydoc, reason) => permissionDeniedHandler(provider, reason)
  )
}

// @todo - this should depend on awareness.outdatedTime
const messageReconnectTimeout = 30000

/**
 * @param {WebsocketProvider} provider
 * @param {string} reason
 */
const permissionDeniedHandler = (provider, reason) =>
  console.warn(`Permission denied to access ${provider.url}.\n${reason}`)

/**
 * @param {WebsocketProvider} provider
 * @param {Uint8Array} buf
 * @param {boolean} emitSynced
 * @return {encoding.Encoder}
 */
const readMessage = (provider, buf, emitSynced) => {
  const decoder = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.createDecoder(buf)
  const encoder = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder()
  const messageType = lib0_decoding__WEBPACK_IMPORTED_MODULE_5__.readVarUint(decoder)
  const messageHandler = provider.messageHandlers[messageType]
  if (/** @type {any} */ (messageHandler)) {
    messageHandler(encoder, decoder, provider, emitSynced, messageType)
  } else {
    console.error('Unable to compute message')
  }
  return encoder
}

/**
 * @param {WebsocketProvider} provider
 */
const setupWS = (provider) => {
  if (provider.shouldConnect && provider.ws === null) {
    const websocket = new provider._WS(provider.url)
    websocket.binaryType = 'arraybuffer'
    provider.ws = websocket
    provider.wsconnecting = true
    provider.wsconnected = false
    provider.synced = false

    websocket.onmessage = (event) => {
      provider.wsLastMessageReceived = lib0_time__WEBPACK_IMPORTED_MODULE_6__.getUnixTime()
      const encoder = readMessage(provider, new Uint8Array(event.data), true)
      if (lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.length(encoder) > 1) {
        websocket.send(lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(encoder))
      }
    }
    websocket.onerror = (event) => {
      provider.emit('connection-error', [event, provider])
    }
    websocket.onclose = (event) => {
      provider.emit('connection-close', [event, provider])
      provider.ws = null
      provider.wsconnecting = false
      if (provider.wsconnected) {
        provider.wsconnected = false
        provider.synced = false
        // update awareness (all users except local left)
        y_protocols_awareness__WEBPACK_IMPORTED_MODULE_3__.removeAwarenessStates(
          provider.awareness,
          Array.from(provider.awareness.getStates().keys()).filter((client) =>
            client !== provider.doc.clientID
          ),
          provider
        )
        provider.emit('status', [{
          status: 'disconnected'
        }])
      } else {
        provider.wsUnsuccessfulReconnects++
      }
      // Start with no reconnect timeout and increase timeout by
      // using exponential backoff starting with 100ms
      setTimeout(
        setupWS,
        lib0_math__WEBPACK_IMPORTED_MODULE_7__.min(
          lib0_math__WEBPACK_IMPORTED_MODULE_7__.pow(2, provider.wsUnsuccessfulReconnects) * 100,
          provider.maxBackoffTime
        ),
        provider
      )
    }
    websocket.onopen = () => {
      provider.wsLastMessageReceived = lib0_time__WEBPACK_IMPORTED_MODULE_6__.getUnixTime()
      provider.wsconnecting = false
      provider.wsconnected = true
      provider.wsUnsuccessfulReconnects = 0
      provider.emit('status', [{
        status: 'connected'
      }])
      // always send sync step 1 when connected
      const encoder = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder()
      lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder, messageSync)
      y_protocols_sync__WEBPACK_IMPORTED_MODULE_1__.writeSyncStep1(encoder, provider.doc)
      websocket.send(lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(encoder))
      // broadcast local awareness state
      if (provider.awareness.getLocalState() !== null) {
        const encoderAwarenessState = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder()
        lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoderAwarenessState, messageAwareness)
        lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint8Array(
          encoderAwarenessState,
          y_protocols_awareness__WEBPACK_IMPORTED_MODULE_3__.encodeAwarenessUpdate(provider.awareness, [
            provider.doc.clientID
          ])
        )
        websocket.send(lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(encoderAwarenessState))
      }
    }
    provider.emit('status', [{
      status: 'connecting'
    }])
  }
}

/**
 * @param {WebsocketProvider} provider
 * @param {ArrayBuffer} buf
 */
const broadcastMessage = (provider, buf) => {
  const ws = provider.ws
  if (provider.wsconnected && ws && ws.readyState === ws.OPEN) {
    ws.send(buf)
  }
  if (provider.bcconnected) {
    lib0_broadcastchannel__WEBPACK_IMPORTED_MODULE_8__.publish(provider.bcChannel, buf, provider)
  }
}

/**
 * Websocket Provider for Yjs. Creates a websocket connection to sync the shared document.
 * The document name is attached to the provided url. I.e. the following example
 * creates a websocket connection to http://localhost:1234/my-document-name
 *
 * @example
 *   import * as Y from 'yjs'
 *   import { WebsocketProvider } from 'y-websocket'
 *   const doc = new Y.Doc()
 *   const provider = new WebsocketProvider('http://localhost:1234', 'my-document-name', doc)
 *
 * @extends {Observable<string>}
 */
class WebsocketProvider extends lib0_observable__WEBPACK_IMPORTED_MODULE_9__.Observable {
  /**
   * @param {string} serverUrl
   * @param {string} roomname
   * @param {Y.Doc} doc
   * @param {object} opts
   * @param {boolean} [opts.connect]
   * @param {awarenessProtocol.Awareness} [opts.awareness]
   * @param {Object<string,string>} [opts.params]
   * @param {typeof WebSocket} [opts.WebSocketPolyfill] Optionall provide a WebSocket polyfill
   * @param {number} [opts.resyncInterval] Request server state every `resyncInterval` milliseconds
   * @param {number} [opts.maxBackoffTime] Maximum amount of time to wait before trying to reconnect (we try to reconnect using exponential backoff)
   * @param {boolean} [opts.disableBc] Disable cross-tab BroadcastChannel communication
   */
  constructor (serverUrl, roomname, doc, {
    connect = true,
    awareness = new y_protocols_awareness__WEBPACK_IMPORTED_MODULE_3__.Awareness(doc),
    params = {},
    WebSocketPolyfill = WebSocket,
    resyncInterval = -1,
    maxBackoffTime = 2500,
    disableBc = false
  } = {}) {
    super()
    // ensure that url is always ends with /
    while (serverUrl[serverUrl.length - 1] === '/') {
      serverUrl = serverUrl.slice(0, serverUrl.length - 1)
    }
    const encodedParams = lib0_url__WEBPACK_IMPORTED_MODULE_10__.encodeQueryParams(params)
    this.maxBackoffTime = maxBackoffTime
    this.bcChannel = serverUrl + '/' + roomname
    this.url = serverUrl + '/' + roomname +
      (encodedParams.length === 0 ? '' : '?' + encodedParams)
    this.roomname = roomname
    this.doc = doc
    this._WS = WebSocketPolyfill
    this.awareness = awareness
    this.wsconnected = false
    this.wsconnecting = false
    this.bcconnected = false
    this.disableBc = disableBc
    this.wsUnsuccessfulReconnects = 0
    this.messageHandlers = messageHandlers.slice()
    /**
     * @type {boolean}
     */
    this._synced = false
    /**
     * @type {WebSocket?}
     */
    this.ws = null
    this.wsLastMessageReceived = 0
    /**
     * Whether to connect to other peers or not
     * @type {boolean}
     */
    this.shouldConnect = connect

    /**
     * @type {number}
     */
    this._resyncInterval = 0
    if (resyncInterval > 0) {
      this._resyncInterval = /** @type {any} */ (setInterval(() => {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
          // resend sync step 1
          const encoder = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder()
          lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder, messageSync)
          y_protocols_sync__WEBPACK_IMPORTED_MODULE_1__.writeSyncStep1(encoder, doc)
          this.ws.send(lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(encoder))
        }
      }, resyncInterval))
    }

    /**
     * @param {ArrayBuffer} data
     * @param {any} origin
     */
    this._bcSubscriber = (data, origin) => {
      if (origin !== this) {
        const encoder = readMessage(this, new Uint8Array(data), false)
        if (lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.length(encoder) > 1) {
          lib0_broadcastchannel__WEBPACK_IMPORTED_MODULE_8__.publish(this.bcChannel, lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(encoder), this)
        }
      }
    }
    /**
     * Listens to Yjs updates and sends them to remote peers (ws and broadcastchannel)
     * @param {Uint8Array} update
     * @param {any} origin
     */
    this._updateHandler = (update, origin) => {
      if (origin !== this) {
        const encoder = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder()
        lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder, messageSync)
        y_protocols_sync__WEBPACK_IMPORTED_MODULE_1__.writeUpdate(encoder, update)
        broadcastMessage(this, lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(encoder))
      }
    }
    this.doc.on('update', this._updateHandler)
    /**
     * @param {any} changed
     * @param {any} _origin
     */
    this._awarenessUpdateHandler = ({ added, updated, removed }, _origin) => {
      const changedClients = added.concat(updated).concat(removed)
      const encoder = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder()
      lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder, messageAwareness)
      lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint8Array(
        encoder,
        y_protocols_awareness__WEBPACK_IMPORTED_MODULE_3__.encodeAwarenessUpdate(awareness, changedClients)
      )
      broadcastMessage(this, lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(encoder))
    }
    this._exitHandler = () => {
      y_protocols_awareness__WEBPACK_IMPORTED_MODULE_3__.removeAwarenessStates(
        this.awareness,
        [doc.clientID],
        'app closed'
      )
    }
    if (lib0_environment__WEBPACK_IMPORTED_MODULE_11__.isNode && typeof process !== 'undefined') {
      process.on('exit', this._exitHandler)
    }
    awareness.on('update', this._awarenessUpdateHandler)
    this._checkInterval = /** @type {any} */ (setInterval(() => {
      if (
        this.wsconnected &&
        messageReconnectTimeout <
          lib0_time__WEBPACK_IMPORTED_MODULE_6__.getUnixTime() - this.wsLastMessageReceived
      ) {
        // no message received in a long time - not even your own awareness
        // updates (which are updated every 15 seconds)
        /** @type {WebSocket} */ (this.ws).close()
      }
    }, messageReconnectTimeout / 10))
    if (connect) {
      this.connect()
    }
  }

  /**
   * @type {boolean}
   */
  get synced () {
    return this._synced
  }

  set synced (state) {
    if (this._synced !== state) {
      this._synced = state
      this.emit('synced', [state])
      this.emit('sync', [state])
    }
  }

  destroy () {
    if (this._resyncInterval !== 0) {
      clearInterval(this._resyncInterval)
    }
    clearInterval(this._checkInterval)
    this.disconnect()
    if (lib0_environment__WEBPACK_IMPORTED_MODULE_11__.isNode && typeof process !== 'undefined') {
      process.off('exit', this._exitHandler)
    }
    this.awareness.off('update', this._awarenessUpdateHandler)
    this.doc.off('update', this._updateHandler)
    super.destroy()
  }

  connectBc () {
    if (this.disableBc) {
      return
    }
    if (!this.bcconnected) {
      lib0_broadcastchannel__WEBPACK_IMPORTED_MODULE_8__.subscribe(this.bcChannel, this._bcSubscriber)
      this.bcconnected = true
    }
    // send sync step1 to bc
    // write sync step 1
    const encoderSync = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder()
    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoderSync, messageSync)
    y_protocols_sync__WEBPACK_IMPORTED_MODULE_1__.writeSyncStep1(encoderSync, this.doc)
    lib0_broadcastchannel__WEBPACK_IMPORTED_MODULE_8__.publish(this.bcChannel, lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(encoderSync), this)
    // broadcast local state
    const encoderState = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder()
    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoderState, messageSync)
    y_protocols_sync__WEBPACK_IMPORTED_MODULE_1__.writeSyncStep2(encoderState, this.doc)
    lib0_broadcastchannel__WEBPACK_IMPORTED_MODULE_8__.publish(this.bcChannel, lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(encoderState), this)
    // write queryAwareness
    const encoderAwarenessQuery = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder()
    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoderAwarenessQuery, messageQueryAwareness)
    lib0_broadcastchannel__WEBPACK_IMPORTED_MODULE_8__.publish(
      this.bcChannel,
      lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(encoderAwarenessQuery),
      this
    )
    // broadcast local awareness state
    const encoderAwarenessState = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder()
    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoderAwarenessState, messageAwareness)
    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint8Array(
      encoderAwarenessState,
      y_protocols_awareness__WEBPACK_IMPORTED_MODULE_3__.encodeAwarenessUpdate(this.awareness, [
        this.doc.clientID
      ])
    )
    lib0_broadcastchannel__WEBPACK_IMPORTED_MODULE_8__.publish(
      this.bcChannel,
      lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(encoderAwarenessState),
      this
    )
  }

  disconnectBc () {
    // broadcast message with local awareness state set to null (indicating disconnect)
    const encoder = lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.createEncoder()
    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint(encoder, messageAwareness)
    lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.writeVarUint8Array(
      encoder,
      y_protocols_awareness__WEBPACK_IMPORTED_MODULE_3__.encodeAwarenessUpdate(this.awareness, [
        this.doc.clientID
      ], new Map())
    )
    broadcastMessage(this, lib0_encoding__WEBPACK_IMPORTED_MODULE_4__.toUint8Array(encoder))
    if (this.bcconnected) {
      lib0_broadcastchannel__WEBPACK_IMPORTED_MODULE_8__.unsubscribe(this.bcChannel, this._bcSubscriber)
      this.bcconnected = false
    }
  }

  disconnect () {
    this.shouldConnect = false
    this.disconnectBc()
    if (this.ws !== null) {
      this.ws.close()
    }
  }

  connect () {
    this.shouldConnect = true
    if (!this.wsconnected && this.ws === null) {
      setupWS(this)
      this.connectBc()
    }
  }
}


/***/ }),

/***/ "../../node_modules/@jupyter/docprovider/style/slider.css":
/*!****************************************************************!*\
  !*** ../../node_modules/@jupyter/docprovider/style/slider.css ***!
  \****************************************************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */   "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! !../../../style-loader/dist/runtime/injectStylesIntoStyleTag.js */ "../../node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js");
/* harmony import */ var _style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! !../../../style-loader/dist/runtime/styleDomAPI.js */ "../../node_modules/style-loader/dist/runtime/styleDomAPI.js");
/* harmony import */ var _style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! !../../../style-loader/dist/runtime/insertBySelector.js */ "../../node_modules/style-loader/dist/runtime/insertBySelector.js");
/* harmony import */ var _style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! !../../../style-loader/dist/runtime/setAttributesWithoutAttributes.js */ "../../node_modules/style-loader/dist/runtime/setAttributesWithoutAttributes.js");
/* harmony import */ var _style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! !../../../style-loader/dist/runtime/insertStyleElement.js */ "../../node_modules/style-loader/dist/runtime/insertStyleElement.js");
/* harmony import */ var _style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4__);
/* harmony import */ var _style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! !../../../style-loader/dist/runtime/styleTagTransform.js */ "../../node_modules/style-loader/dist/runtime/styleTagTransform.js");
/* harmony import */ var _style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5__);
/* harmony import */ var _css_loader_dist_cjs_js_slider_css__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! !!../../../css-loader/dist/cjs.js!./slider.css */ "../../node_modules/css-loader/dist/cjs.js!../../node_modules/@jupyter/docprovider/style/slider.css");

      
      
      
      
      
      
      
      
      

var options = {};

options.styleTagTransform = (_style_loader_dist_runtime_styleTagTransform_js__WEBPACK_IMPORTED_MODULE_5___default());
options.setAttributes = (_style_loader_dist_runtime_setAttributesWithoutAttributes_js__WEBPACK_IMPORTED_MODULE_3___default());

      options.insert = _style_loader_dist_runtime_insertBySelector_js__WEBPACK_IMPORTED_MODULE_2___default().bind(null, "head");
    
options.domAPI = (_style_loader_dist_runtime_styleDomAPI_js__WEBPACK_IMPORTED_MODULE_1___default());
options.insertStyleElement = (_style_loader_dist_runtime_insertStyleElement_js__WEBPACK_IMPORTED_MODULE_4___default());

var update = _style_loader_dist_runtime_injectStylesIntoStyleTag_js__WEBPACK_IMPORTED_MODULE_0___default()(_css_loader_dist_cjs_js_slider_css__WEBPACK_IMPORTED_MODULE_6__["default"], options);




       /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (_css_loader_dist_cjs_js_slider_css__WEBPACK_IMPORTED_MODULE_6__["default"] && _css_loader_dist_cjs_js_slider_css__WEBPACK_IMPORTED_MODULE_6__["default"].locals ? _css_loader_dist_cjs_js_slider_css__WEBPACK_IMPORTED_MODULE_6__["default"].locals : undefined);


/***/ })

}]);
//# sourceMappingURL=vendors-node_modules_jupyter_docprovider_lib_index_js.713f20cc6cba18abc306.js.map