"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AssetsLoader = exports.AssetsLoaderComponent = exports.AssetsLoaderClass = void 0;
var sdk_1 = require("@builder6/sdk");
var with_builder_1 = require("../functions/with-builder");
var react_1 = __importStar(require("react"));
var builder_block_component_1 = require("../components/builder-block.component");
var AssetsLoaderClass = /** @class */ (function () {
    function AssetsLoaderClass() {
    }
    AssetsLoaderClass.registerRemoteAssets = function (assetUrls, unpkgUrl) {
        var _b, assetUrls_1, assetUrls_1_1;
        var _c, e_1, _d, _e;
        return __awaiter(this, void 0, void 0, function () {
            var assetUrl, response, assets, error_1, e_1_1;
            return __generator(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        this.unpkgUrl = unpkgUrl;
                        _f.label = 1;
                    case 1:
                        _f.trys.push([1, 15, 16, 21]);
                        _b = true, assetUrls_1 = __asyncValues(assetUrls);
                        _f.label = 2;
                    case 2: return [4 /*yield*/, assetUrls_1.next()];
                    case 3:
                        if (!(assetUrls_1_1 = _f.sent(), _c = assetUrls_1_1.done, !_c)) return [3 /*break*/, 14];
                        _e = assetUrls_1_1.value;
                        _b = false;
                        _f.label = 4;
                    case 4:
                        _f.trys.push([4, , 12, 13]);
                        assetUrl = _e;
                        assetUrl = assetUrl.replace('https://unpkg.com', this.unpkgUrl);
                        if (this.remoteAssets[assetUrl]) {
                            console.log("Already loading: ".concat(assetUrl));
                            return [3 /*break*/, 13];
                        }
                        this.remoteAssets[assetUrl] = 'loading';
                        _f.label = 5;
                    case 5:
                        _f.trys.push([5, 9, 10, 11]);
                        return [4 /*yield*/, fetch(assetUrl, { mode: 'cors' })];
                    case 6:
                        response = _f.sent();
                        if (!response.ok) {
                            throw new Error("Failed to fetch asset: ".concat(response.statusText));
                        }
                        return [4 /*yield*/, response.json()];
                    case 7:
                        assets = _f.sent();
                        return [4 /*yield*/, this.registerAssets(assets)];
                    case 8:
                        _f.sent();
                        console.log("Assets loaded: ".concat(assetUrl));
                        return [3 /*break*/, 11];
                    case 9:
                        error_1 = _f.sent();
                        console.error("Error loading asset from ".concat(assetUrl, ":"), error_1);
                        return [3 /*break*/, 11];
                    case 10:
                        this.remoteAssets[assetUrl] = 'loaded';
                        return [7 /*endfinally*/];
                    case 11: return [3 /*break*/, 13];
                    case 12:
                        _b = true;
                        return [7 /*endfinally*/];
                    case 13: return [3 /*break*/, 2];
                    case 14: return [3 /*break*/, 21];
                    case 15:
                        e_1_1 = _f.sent();
                        e_1 = { error: e_1_1 };
                        return [3 /*break*/, 21];
                    case 16:
                        _f.trys.push([16, , 19, 20]);
                        if (!(!_b && !_c && (_d = assetUrls_1.return))) return [3 /*break*/, 18];
                        return [4 /*yield*/, _d.call(assetUrls_1)];
                    case 17:
                        _f.sent();
                        _f.label = 18;
                    case 18: return [3 /*break*/, 20];
                    case 19:
                        if (e_1) throw e_1.error;
                        return [7 /*endfinally*/];
                    case 20: return [7 /*endfinally*/];
                    case 21: return [2 /*return*/];
                }
            });
        });
    };
    AssetsLoaderClass.registerAssets = function (assets) {
        return __awaiter(this, void 0, void 0, function () {
            var packages, components, _i, _b, pkg, _c, _d, url, _e, _f, component;
            return __generator(this, function (_g) {
                switch (_g.label) {
                    case 0:
                        packages = assets.packages, components = assets.components;
                        _i = 0, _b = packages || [];
                        _g.label = 1;
                    case 1:
                        if (!(_i < _b.length)) return [3 /*break*/, 8];
                        pkg = _b[_i];
                        if (!(pkg.urls && pkg.library)) return [3 /*break*/, 7];
                        _c = 0, _d = pkg.urls;
                        _g.label = 2;
                    case 2:
                        if (!(_c < _d.length)) return [3 /*break*/, 6];
                        url = _d[_c];
                        if (!url.endsWith('.js')) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.injectScript(url)];
                    case 3:
                        _g.sent();
                        return [3 /*break*/, 5];
                    case 4:
                        if (url.endsWith('.css')) {
                            this.injectCSS(url);
                        }
                        _g.label = 5;
                    case 5:
                        _c++;
                        return [3 /*break*/, 2];
                    case 6:
                        this.packages[pkg.package] = pkg;
                        _g.label = 7;
                    case 7:
                        _i++;
                        return [3 /*break*/, 1];
                    case 8:
                        _e = 0, _f = components || [];
                        _g.label = 9;
                    case 9:
                        if (!(_e < _f.length)) return [3 /*break*/, 12];
                        component = _f[_e];
                        if (!component.url) return [3 /*break*/, 11];
                        return [4 /*yield*/, this.injectScript(component.url)];
                    case 10:
                        _g.sent();
                        if (component.exportName && typeof window[component.exportName] !== "undefined") {
                            this.registerMeta(window[component.exportName]);
                        }
                        _g.label = 11;
                    case 11:
                        _e++;
                        return [3 /*break*/, 9];
                    case 12: return [2 /*return*/];
                }
            });
        });
    };
    AssetsLoaderClass.injectScript = function (src) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            var script = document.createElement('script');
            script.src = src.replace('https://unpkg.com', _this.unpkgUrl);
            script.async = true;
            script.onload = function () { return resolve(); };
            script.onerror = function () { return reject(new Error("Failed to load script: ".concat(src))); };
            document.head.appendChild(script);
        });
    };
    AssetsLoaderClass.injectCSS = function (href) {
        var link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = href.replace('https://unpkg.com', this.unpkgUrl);
        document.head.appendChild(link);
    };
    var _a;
    _a = AssetsLoaderClass;
    AssetsLoaderClass.remoteAssets = {};
    AssetsLoaderClass.packages = {};
    AssetsLoaderClass.registerMeta = function (meta) {
        if (meta.components) {
            meta.components.forEach(function (comp, index) { return __awaiter(void 0, void 0, void 0, function () {
                var library, pkg, component;
                var _b, _c, _d;
                return __generator(_a, function (_e) {
                    if (((_b = comp.npm) === null || _b === void 0 ? void 0 : _b.package) && ((_c = comp.npm) === null || _c === void 0 ? void 0 : _c.exportName)) {
                        library = (_d = this.packages[comp.npm.package]) === null || _d === void 0 ? void 0 : _d.library;
                        if (library) {
                            pkg = window[library];
                            if (pkg && pkg[comp.npm.exportName]) {
                                component = pkg[comp.npm.exportName];
                                component['plugins'] = comp;
                                // 判断 Builder6.components 中name是否存在，如果不存在则创建
                                if (!sdk_1.Builder.components.find(function (item) { return item.name === comp.componentName; })) {
                                    sdk_1.Builder.registerComponent(component, { name: comp.componentName });
                                }
                            }
                            else {
                                console.error("Component ".concat(comp.npm.exportName, " not found in package ").concat(comp.npm.package));
                            }
                        }
                    }
                    return [2 /*return*/];
                });
            }); });
        }
    };
    return AssetsLoaderClass;
}());
exports.AssetsLoaderClass = AssetsLoaderClass;
var AssetsLoaderComponent = /** @class */ (function (_super) {
    __extends(AssetsLoaderComponent, _super);
    function AssetsLoaderComponent(props) {
        var _this = _super.call(this, props) || this;
        _this.state = {
            assetsLoaded: false
        };
        return _this;
    }
    AssetsLoaderComponent.prototype.componentDidMount = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this.loadAssets()];
                    case 1:
                        _b.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    AssetsLoaderComponent.prototype.componentDidUpdate = function (prevProps) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!(prevProps.urls !== this.props.urls)) return [3 /*break*/, 2];
                        this.setState({ assetsLoaded: false }); // Reset state before loading new assets
                        return [4 /*yield*/, this.loadAssets()];
                    case 1:
                        _b.sent();
                        _b.label = 2;
                    case 2: return [2 /*return*/];
                }
            });
        });
    };
    AssetsLoaderComponent.prototype.loadAssets = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _b, urls, _c, unpkgUrl;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        _b = this.props, urls = _b.urls, _c = _b.unpkgUrl, unpkgUrl = _c === void 0 ? 'https://unpkg.com' : _c;
                        return [4 /*yield*/, AssetsLoaderClass.registerRemoteAssets(urls, unpkgUrl)];
                    case 1:
                        _d.sent();
                        this.setState({ assetsLoaded: true });
                        return [2 /*return*/];
                }
            });
        });
    };
    AssetsLoaderComponent.prototype.render = function () {
        var assetsLoaded = this.state.assetsLoaded;
        var _b = this.props, children = _b.children, urls = _b.urls;
        if (!assetsLoaded) {
            return react_1.default.createElement("div", null,
                "Loading assets from ",
                urls,
                " ...");
        }
        return (react_1.default.createElement(react_1.default.Fragment, null,
            this.props.children,
            this.props.builderBlock &&
                this.props.builderBlock.children &&
                this.props.builderBlock.children.map(function (block, index) { return (react_1.default.createElement(builder_block_component_1.BuilderBlock, { key: block.id, block: block })); })));
    };
    return AssetsLoaderComponent;
}(react_1.Component));
exports.AssetsLoaderComponent = AssetsLoaderComponent;
exports.AssetsLoader = (0, with_builder_1.withBuilder)(AssetsLoaderComponent, {
    name: 'Core:AssetsLoader',
    static: true,
    image: 'https://cdn.builder.io/api/v1/image/assets%2FIsxPKMo2gPRRKeakUztj1D6uqed2%2F682efef23ace49afac61748dd305c70a',
    inputs: [
        {
            name: 'urls',
            type: 'javascript',
            required: true,
            defaultValue: '',
            code: true,
        },
    ],
    canHaveChildren: true,
});
//# sourceMappingURL=AssetsLoader.js.map