"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = function(module) {
        var getter = module && module.__esModule ? function() {
            return module['default'];
        } : function() {
            return module;
        };
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = function(exports1, definition) {
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = function(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
    };
})();
(()=>{
    __webpack_require__.r = function(exports1) {
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    Application: ()=>Application
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const external_react_namespaceObject = require("react");
var external_react_default = /*#__PURE__*/ __webpack_require__.n(external_react_namespaceObject);
const requirejs_namespaceObject = require("@tachybase/requirejs");
const schema_namespaceObject = require("@tachybase/schema");
const sdk_namespaceObject = require("@tachybase/sdk");
const external_lodash_namespaceObject = require("lodash");
const client_namespaceObject = require("react-dom/client");
const external_react_i18next_namespaceObject = require("react-i18next");
const external_react_router_dom_namespaceObject = require("react-router-dom");
const index_js_namespaceObject = require("../api-client/index.js");
const CollectionField_js_namespaceObject = require("../data-source/collection-field/CollectionField.js");
const DataSourceApplicationProvider_js_namespaceObject = require("../data-source/components/DataSourceApplicationProvider.js");
const DataBlockProvider_js_namespaceObject = require("../data-source/data-block/DataBlockProvider.js");
const DataSourceManager_js_namespaceObject = require("../data-source/data-source/DataSourceManager.js");
const external_i18n_index_js_namespaceObject = require("../i18n/index.js");
const css_variable_index_js_namespaceObject = require("../style/css-variable/index.js");
const theme_index_js_namespaceObject = require("../style/theme/index.js");
const external_AppSchemaComponentProvider_js_namespaceObject = require("./AppSchemaComponentProvider.js");
const external_AttachmentPreviewManager_js_namespaceObject = require("./AttachmentPreviewManager.js");
const external_components_index_js_namespaceObject = require("./components/index.js");
const external_NoticesManager_js_namespaceObject = require("./NoticesManager.js");
const external_PluginContextMenu_js_namespaceObject = require("./PluginContextMenu.js");
const external_PluginManager_js_namespaceObject = require("./PluginManager.js");
const external_RouterManager_js_namespaceObject = require("./RouterManager.js");
const external_schema_initializer_index_js_namespaceObject = require("./schema-initializer/index.js");
const components_index_js_namespaceObject = require("./schema-initializer/components/index.js");
const external_schema_settings_index_js_namespaceObject = require("./schema-settings/index.js");
const external_SystemSettingsManager_js_namespaceObject = require("./SystemSettingsManager.js");
const external_UserSettingsManager_js_namespaceObject = require("./UserSettingsManager.js");
const external_utils_index_js_namespaceObject = require("./utils/index.js");
const globalDeps_js_namespaceObject = require("./utils/globalDeps.js");
const external_WebSocketClient_js_namespaceObject = require("./WebSocketClient.js");
function _define_property(obj, key, value) {
    if (key in obj) Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
    });
    else obj[key] = value;
    return obj;
}
class Application {
    get pm() {
        return this.pluginManager;
    }
    get adminUrl() {
        if ('main' === this.name) return '/admin/';
        return "/apps/".concat(this.name, "/admin/");
    }
    initRequireJs() {
        this.requirejs = (0, requirejs_namespaceObject.getRequireJs)();
        (0, globalDeps_js_namespaceObject.defineGlobalDeps)(this.requirejs);
        window.define = this.requirejs.define;
        window.require = this.requirejs.require;
    }
    addDefaultProviders() {
        this.use(index_js_namespaceObject.APIClientProvider, {
            apiClient: this.apiClient
        });
        this.use(external_react_i18next_namespaceObject.I18nextProvider, {
            i18n: this.i18n
        });
        this.use(theme_index_js_namespaceObject.GlobalThemeProvider);
        this.use(css_variable_index_js_namespaceObject.CSSVariableProvider);
        this.use(external_AppSchemaComponentProvider_js_namespaceObject.AppSchemaComponentProvider, {
            designable: this.options.designable,
            appName: this.name,
            components: this.components,
            scope: this.scopes
        });
        this.use(theme_index_js_namespaceObject.AntdAppProvider);
        this.use(DataSourceApplicationProvider_js_namespaceObject.DataSourceApplicationProvider, {
            dataSourceManager: this.dataSourceManager
        });
    }
    addReactRouterComponents() {
        this.addComponents({
            Link: external_react_router_dom_namespaceObject.Link,
            Navigate: external_react_router_dom_namespaceObject.Navigate,
            NavLink: external_react_router_dom_namespaceObject.NavLink
        });
    }
    addRoutes() {
        this.router.add('not-found', {
            path: '*',
            Component: this.components['AppNotFound']
        });
    }
    getOptions() {
        return this.options;
    }
    getPublicPath() {
        return this.options.publicPath || '/';
    }
    getName() {
        return (0, sdk_namespaceObject.getSubAppName)(this.getPublicPath()) || null;
    }
    getApiUrl() {
        let pathname = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : '';
        let baseURL = this.apiClient.axios['defaults']['baseURL'];
        if (!baseURL.startsWith('http://') && !baseURL.startsWith('https://')) {
            const { protocol, host } = window.location;
            baseURL = "".concat(protocol, "//").concat(host).concat(baseURL);
        }
        return baseURL.replace(/\/$/g, '') + '/' + pathname.replace(/^\//g, '');
    }
    getRouteUrl(pathname) {
        return this.options.publicPath.replace(/\/$/g, '') + pathname;
    }
    getCollectionManager(dataSource) {
        var _this_dataSourceManager_getDataSource;
        return null === (_this_dataSourceManager_getDataSource = this.dataSourceManager.getDataSource(dataSource)) || void 0 === _this_dataSourceManager_getDataSource ? void 0 : _this_dataSourceManager_getDataSource.collectionManager;
    }
    getComposeProviders() {
        const Providers = (0, external_utils_index_js_namespaceObject.compose)(...this.providers)(external_components_index_js_namespaceObject.BlankComponent);
        Providers.displayName = 'Providers';
        return Providers;
    }
    use(component, props) {
        return this.addProvider(component, props);
    }
    addProvider(component, props) {
        return this.providers.push([
            component,
            props
        ]);
    }
    addProviders(providers) {
        providers.forEach((provider)=>{
            if (Array.isArray(provider)) this.addProvider(provider[0], provider[1]);
            else this.addProvider(provider);
        });
    }
    async load() {
        let loadFailed = false;
        this.ws.on('message', (event)=>{
            var _data_payload;
            const data = JSON.parse(event.data);
            if (null == data ? void 0 : null === (_data_payload = data.payload) || void 0 === _data_payload ? void 0 : _data_payload.refresh) {
                window.location.reload();
                return;
            }
            if ('notification' === data.type) {
                var _data_payload1, _data_payload2;
                this.notification[(null === (_data_payload1 = data.payload) || void 0 === _data_payload1 ? void 0 : _data_payload1.type) || 'info']({
                    message: null === (_data_payload2 = data.payload) || void 0 === _data_payload2 ? void 0 : _data_payload2.message
                });
                return;
            }
            if ('notice' === data.type) this.noticeManager.on(data.payload);
            const maintaining = 'maintaining' === data.type && 'APP_RUNNING' !== data.payload.code;
            if (maintaining) {
                this.maintaining = true;
                this.error = data.payload;
            } else {
                if (loadFailed) {
                    window.location.reload();
                    return;
                }
                this.maintaining = false;
                this.maintained = true;
                this.error = null;
            }
        });
        this.ws.on('serverDown', ()=>{
            this.maintaining = true;
            this.maintained = true;
        });
        this.ws.connect();
        try {
            this.loading = true;
            await this.pm.load();
        } catch (error) {
            var _error_response_data, _error_response, _error_response_data_errors, _error_response_data1, _error_response1;
            if (this.ws.enabled) await new Promise((resolve)=>{
                setTimeout(()=>resolve(null), 1000);
            });
            loadFailed = true;
            const others = (null == error ? void 0 : null === (_error_response = error.response) || void 0 === _error_response ? void 0 : null === (_error_response_data = _error_response.data) || void 0 === _error_response_data ? void 0 : _error_response_data.error) || (null == error ? void 0 : null === (_error_response1 = error.response) || void 0 === _error_response1 ? void 0 : null === (_error_response_data1 = _error_response1.data) || void 0 === _error_response_data1 ? void 0 : null === (_error_response_data_errors = _error_response_data1.errors) || void 0 === _error_response_data_errors ? void 0 : _error_response_data_errors[0]) || {
                message: null == error ? void 0 : error.message
            };
            this.error = {
                code: 'LOAD_ERROR',
                ...others
            };
            console.error(error, this.error);
        }
        this.loading = false;
    }
    getComponent(Component) {
        let isShowError = !(arguments.length > 1) || void 0 === arguments[1] || arguments[1];
        const showError = (msg)=>isShowError && console.error(msg);
        if (!Component) {
            showError("getComponent called with ".concat(Component));
            return;
        }
        if ('function' == typeof Component) return Component;
        if ('string' == typeof Component) {
            const res = (0, external_lodash_namespaceObject.get)(this.components, Component);
            if (!res) {
                showError("Component ".concat(Component, " not found"));
                return;
            }
            return res;
        }
        showError("Component ".concat(Component, " should be a string or a React component"));
    }
    renderComponent(Component, props) {
        return /*#__PURE__*/ external_react_default().createElement(this.getComponent(Component), props);
    }
    addComponent(component, name) {
        const componentName = name || component.displayName || component.name;
        if (!componentName) {
            console.error('Component must have a displayName or pass name as second argument');
            return;
        }
        (0, external_lodash_namespaceObject.set)(this.components, componentName, component);
    }
    addComponents(components) {
        Object.keys(components).forEach((name)=>{
            this.addComponent(components[name], name);
        });
    }
    addScopes(scopes) {
        this.scopes = (0, external_lodash_namespaceObject.merge)(this.scopes, scopes);
    }
    getRootComponent() {
        const Root = ()=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_components_index_js_namespaceObject.AppComponent, {
                app: this
            });
        return Root;
    }
    mount(containerOrSelector) {
        const container = (0, external_utils_index_js_namespaceObject.normalizeContainer)(containerOrSelector);
        if (!container) return;
        const App = this.getRootComponent();
        const root = (0, client_namespaceObject.createRoot)(container);
        root.render(/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(App, {}));
        return root;
    }
    constructor(options = {}){
        _define_property(this, "options", void 0);
        _define_property(this, "providers", void 0);
        _define_property(this, "router", void 0);
        _define_property(this, "scopes", void 0);
        _define_property(this, "i18n", void 0);
        _define_property(this, "ws", void 0);
        _define_property(this, "apiClient", void 0);
        _define_property(this, "components", void 0);
        _define_property(this, "pluginManager", void 0);
        _define_property(this, "systemSettingsManager", void 0);
        _define_property(this, "userSettingsManager", void 0);
        _define_property(this, "devDynamicImport", void 0);
        _define_property(this, "requirejs", void 0);
        _define_property(this, "notification", void 0);
        _define_property(this, "schemaInitializerManager", void 0);
        _define_property(this, "schemaSettingsManager", void 0);
        _define_property(this, "dataSourceManager", void 0);
        _define_property(this, "noticeManager", void 0);
        _define_property(this, "pluginContextMenu", void 0);
        _define_property(this, "AttachmentPreviewManager", void 0);
        _define_property(this, "name", void 0);
        _define_property(this, "loading", void 0);
        _define_property(this, "maintained", void 0);
        _define_property(this, "maintaining", void 0);
        _define_property(this, "error", void 0);
        this.options = options;
        this.providers = [];
        this.scopes = {};
        this.components = {
            DataBlockProvider: DataBlockProvider_js_namespaceObject.DataBlockProvider,
            ...external_components_index_js_namespaceObject.defaultAppComponents,
            ...components_index_js_namespaceObject,
            CollectionField: CollectionField_js_namespaceObject.CollectionField
        };
        this.loading = true;
        this.maintained = false;
        this.maintaining = false;
        this.error = null;
        this.initRequireJs();
        (0, schema_namespaceObject.define)(this, {
            maintained: schema_namespaceObject.observable.ref,
            loading: schema_namespaceObject.observable.ref,
            maintaining: schema_namespaceObject.observable.ref,
            error: schema_namespaceObject.observable.ref
        });
        this.devDynamicImport = options.devDynamicImport;
        this.scopes = (0, external_lodash_namespaceObject.merge)(this.scopes, options.scopes);
        this.components = (0, external_lodash_namespaceObject.merge)(this.components, options.components);
        this.apiClient = options.apiClient instanceof index_js_namespaceObject.APIClient ? options.apiClient : new index_js_namespaceObject.APIClient(options.apiClient);
        this.apiClient.app = this;
        this.i18n = options.i18n || external_i18n_index_js_namespaceObject.i18n;
        this.router = new external_RouterManager_js_namespaceObject.RouterManager(options.router, this);
        this.schemaSettingsManager = new external_schema_settings_index_js_namespaceObject.SchemaSettingsManager(options.schemaSettings, this);
        this.pluginManager = new external_PluginManager_js_namespaceObject.PluginManager(options.plugins, options.loadRemotePlugins, this);
        this.schemaInitializerManager = new external_schema_initializer_index_js_namespaceObject.SchemaInitializerManager(options.schemaInitializers, this);
        this.dataSourceManager = new DataSourceManager_js_namespaceObject.DataSourceManager(options.dataSourceManager, this);
        this.noticeManager = new external_NoticesManager_js_namespaceObject.NoticeManager(this);
        this.addDefaultProviders();
        this.addReactRouterComponents();
        this.addProviders(options.providers || []);
        this.ws = new external_WebSocketClient_js_namespaceObject.WebSocketClient(options.ws, this);
        this.systemSettingsManager = new external_SystemSettingsManager_js_namespaceObject.SystemSettingsManager(options.pluginSettings, this);
        this.userSettingsManager = new external_UserSettingsManager_js_namespaceObject.UserSettingsManager(options.userSettings, this);
        this.addRoutes();
        this.name = this.options.name || (0, sdk_namespaceObject.getSubAppName)(options.publicPath) || 'main';
        this.pluginContextMenu = new external_PluginContextMenu_js_namespaceObject.PluginContextMenu(options.pluginMenuItems);
        this.AttachmentPreviewManager = new external_AttachmentPreviewManager_js_namespaceObject.AttachmentPreviewManager(options.attachmentItem, this);
    }
}
var __webpack_export_target__ = exports;
for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', {
    value: true
});
