跳转到内容

MediaWiki:Gadget-interfaceVariantConverter.js:修订间差异

来自萌娘共享
代码变动:a157f65a - chore by U:星海子
标签由机器人或全自动脚本执行的操作
代码变动:a157f65a - chore by U:星海子
标签由机器人或全自动脚本执行的操作
第8行: 第8行:
/* <pre> */
/* <pre> */


// WARNING: This script would break if source wikitext contains <pre> tags, won't fix.
// <pre>
"use strict";
"use strict";
function _array_like_to_array(arr, len) {
$(() => (async () => {
    if (len == null || len > arr.length) len = arr.length;
     var _a, _b;
     for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    const pagename = mw.config.get("wgPageName");
     return arr2;
    const username = mw.config.get("wgUserName");
}
     const pageid = mw.config.get("wgArticleId");
function _array_with_holes(arr) {
    const basepage = pagename.replace(/\/.*?$/, "");
     if (Array.isArray(arr)) return arr;
     const api = new mw.Api(), zhAPI = /m?zh\.moegirl\.org\.cn/.test(location.hostname) ? api : new mw.ForeignApi("https://mzh.moegirl.org.cn/api.php", { anonymous: true });
}
    const lrAivc = $.extend({
function _assert_this_initialized(self) {
        main: ["zh-cn", "zh-tw", "zh-hk"],
    if (self === void 0) {
        dependent: {
         throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
            "(main)": "zh-cn",
    }
            "zh-hans": "zh-cn",
    return self;
            "zh-hant": "zh-tw",
}
        },
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
        noteTA: {
            G1: "MediaWiki",
        },
        autoPopulate: true,
         useOpenCC: true,
        manualAction: {
            "zh-hk": (t) => t.replaceAll("户", "戶"),
            "zh-tw": (t) => t.replaceAll("名稱空間", "命名空間").replaceAll("記憶體", "內存"),
        },
        watchlist: "nochange",
    }, window.lr_aivc);
    let prepopContent = "";
     try {
     try {
         var info = gen[key](arg);
         prepopContent = lrAivc.autoPopulate
        var value = info.value;
            ? (await api.get({
    } catch (error) {
                action: "parse",
        reject(error);
                assertuser: username,
        return;
                pageid,
                prop: "wikitext",
            })).parse.wikitext["*"]
            : "";
     }
     }
     if (info.done) {
     catch { }
        resolve(value);
    const toParams = (obj) => Object.entries(obj).map(([k, v]) => `${k}=${v}`).join("|");
     } else {
    const variantPage = (variant) => variant === "(main)" ? `${basepage}` : `${basepage}/${variant}`;
         Promise.resolve(value).then(_next, _throw);
     const REGEXP = {
    }
        lcMarker: /-{([\s\S]*?)}-/g,
}
        lcMarkerEsc: /-\\{([\s\S]*?)}\\-/g,
function _async_to_generator(fn) {
        nowiki: /<nowiki>([\s\S]*?)<\/nowiki>/g,
     return function() {
         link: /\[\[([\s\S]*?)(?:#([\s\S]*?))?(\|[\s\S]*?)?\]\]/g,
         var self = this, args = arguments;
        extLink: /([^[])\[([^[]+?)( [\s\S]+?)?\]([^\]])/g,
         return new Promise(function(resolve, reject) {
        template: /\{\{([\s\S]*?)\}\}/g,
            var gen = fn.apply(self, args);
        htmlEntity: /&([a-zA-Z0-9#]+);/g,
            function _next(value) {
        noOCC: /<!--noOCC-->([\s\S]*?)<!--\/noOCC-->/gi,
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
    };
             }
     const escapeWikitext = (original) => {
             function _throw(err) {
         const nowikis = [], mappings = [];
                 asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
         let replaced = original;
            }
        replaced = replaced.replace(REGEXP.lcMarker, (_, content) => `-\\{${content}}\\-`);
             _next(undefined);
        replaced = replaced.replace(REGEXP.nowiki, (_, content) => `<nowiki>${nowikis.push(content) - 1}</nowiki>`);
        replaced = replaced.replace(REGEXP.link, (match, target, anchor, text) => anchor || text ? `[[${text ? mappings.push(target) - 1 : target}${anchor ? `#${mappings.push(anchor) - 1}` : ""}${text || ""}]]` : match);
        replaced = replaced.replace(REGEXP.extLink, (_, before, target, text, after) => `${before}[${mappings.push(target) - 1}${text || ""}]${after}`);
        replaced = replaced.replace(REGEXP.template, (_, params) => {
            const paramList = params.split("|");
             mappings.push(paramList[0]);
             paramList.shift();
            return `${paramList.reduce((acc, param) => {
                 const [first, ...rest] = param.split("=");
                return rest.length ? `${acc}|${mappings.push(first) - 1}=${rest.join("=")}` : `${acc}|${param}`;
             }, `{{${mappings.length - 1}`)}}}`;
         });
         });
        replaced = replaced.replace(REGEXP.lcMarkerEsc, (_, content) => `-\\{${mappings.push(content || "") - 1}}\\-`);
        replaced = replaced.replace(REGEXP.htmlEntity, (_, entity) => `&${mappings.push(entity) - 1};`);
        replaced = replaced.replace(REGEXP.nowiki, (_, index) => `<nowiki><nowiki>${nowikis[index]}</nowiki></nowiki>`);
        return { replaced, mappings };
     };
     };
}
    const restoreWikitext = (original, mappings) => {
function _call_super(_this, derived, args) {
        const nowikis = [];
    derived = _get_prototype_of(derived);
        let replaced = original;
    return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
        replaced = replaced.replace(REGEXP.nowiki, (_, content) => `<nowiki>${nowikis.push(content) - 1}</nowiki>`);
}
         replaced = replaced.replace(REGEXP.htmlEntity, (_, index) => `&${mappings[index]};`);
function _class_call_check(instance, Constructor) {
         replaced = replaced.replace(REGEXP.template, (_, params) => {
    if (!(instance instanceof Constructor)) {
            const paramList = params.split("|");
         throw new TypeError("Cannot call a class as a function");
            const name = mappings[paramList[0]];
    }
            paramList.shift();
}
            return `${paramList.reduce((acc, param) => {
function _defineProperties(target, props) {
                const [first, ...rest] = param.split("=");
    for(var i = 0; i < props.length; i++){
                return rest.length ? `${acc}|${mappings[first]}=${rest.join("=")}` : `${acc}|${param}`;
        var descriptor = props[i];
             }, `{{${name}`)}}}`;
         descriptor.enumerable = descriptor.enumerable || false;
        descriptor.configurable = true;
        if ("value" in descriptor) descriptor.writable = true;
        Object.defineProperty(target, descriptor.key, descriptor);
    }
}
function _create_class(Constructor, protoProps, staticProps) {
    if (protoProps) _defineProperties(Constructor.prototype, protoProps);
    if (staticProps) _defineProperties(Constructor, staticProps);
    return Constructor;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
             value: value,
            enumerable: true,
            configurable: true,
            writable: true
         });
         });
    } else {
         replaced = replaced.replace(REGEXP.extLink, (_, before, target, text, after) => `${before}[${mappings[target]}${text || ""}]${after}`);
         obj[key] = value;
         replaced = replaced.replace(REGEXP.link, (match, target, anchor, text) => anchor || text ? `[[${text ? mappings[target] : target}${mappings[anchor] ? `#${mappings[anchor]}` : ""}${text || ""}]]` : match);
    }
        replaced = replaced.replace(REGEXP.nowiki, (_, index) => `<nowiki>${nowikis[index]}</nowiki>`);
    return obj;
        replaced = replaced.replace(REGEXP.lcMarkerEsc, (_, index) => `-{${mappings[index] ?? index}}-`);
}
         return replaced;
function _get(target, property, receiver) {
    if (typeof Reflect !== "undefined" && Reflect.get) {
         _get = Reflect.get;
    } else {
        _get = function get(target, property, receiver) {
            var base = _super_prop_base(target, property);
            if (!base) return;
            var desc = Object.getOwnPropertyDescriptor(base, property);
            if (desc.get) {
                return desc.get.call(receiver || target);
            }
            return desc.value;
        };
    }
    return _get(target, property, receiver || target);
}
function _get_prototype_of(o) {
    _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
         return o.__proto__ || Object.getPrototypeOf(o);
     };
     };
     return _get_prototype_of(o);
     class AIVCWindow extends (_b = OO.ui.ProcessDialog) {
}
        constructor(config) {
function _inherits(subClass, superClass) {
            super(config);
    if (typeof superClass !== "function" && superClass !== null) {
            this.config = config.data.config;
        throw new TypeError("Super expression must either be null or a function");
             this.prepopContent = config.data.prepopContent;
    }
    subClass.prototype = Object.create(superClass && superClass.prototype, {
        constructor: {
             value: subClass,
            writable: true,
            configurable: true
         }
         }
    });
        initialize() {
    if (superClass) _set_prototype_of(subClass, superClass);
            super.initialize();
}
            this.configPanel = new OO.ui.PanelLayout({
function _iterable_to_array(iter) {
                scrollable: false,
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
                expanded: false,
}
                padded: true,
function _iterable_to_array_limit(arr, i) {
            });
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
            this.confirmPanel = new OO.ui.PanelLayout({
    if (_i == null) return;
                scrollable: false,
    var _arr = [];
                expanded: false,
    var _n = true;
                padded: true,
    var _d = false;
            });
    var _s, _e;
            this.ogText = new OO.ui.MultilineTextInputWidget({
    try {
                value: this.prepopContent,
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
                autosize: true,
             _arr.push(_s.value);
            });
             if (i && _arr.length === i) break;
            const textField = new OO.ui.FieldLayout(this.ogText, {
                label: wgULS("原始内容", "原始內容"),
                align: "top",
            });
            this.mainVariants = new OO.ui.TextInputWidget({
                value: this.config.main.join(";"),
            });
            const mainField = new OO.ui.FieldLayout(this.mainVariants, {
                label: wgULS("主要变体", "主要變体"),
                align: "top",
            });
            this.depVariants = new OO.ui.TextInputWidget({
                value: Object.entries(this.config.dependent).map(([k, v]) => `${k}:${v}`).join(";"),
            });
            const depField = new OO.ui.FieldLayout(this.depVariants, {
                label: wgULS("依赖变体", "依賴變体"),
                align: "top",
            });
            this.noteTAParams = new OO.ui.TextInputWidget({
                value: toParams(this.config.noteTA),
            });
            const noteTAField = new OO.ui.FieldLayout(this.noteTAParams, {
                label: wgULS("NoteTA参数", "NoteTA參數"),
                align: "top",
            });
            this.occCheckbox = new OO.ui.CheckboxInputWidget({
                selected: this.config.useOpenCC,
            });
            const occField = new OO.ui.FieldLayout(this.occCheckbox, {
                label: "使用OpenCC",
                align: "inline",
            });
            this.configPanel.$element.append(textField.$element, mainField.$element, depField.$element, noteTAField.$element, occField.$element);
            this.stackLayout = new OO.ui.StackLayout({
                items: [this.configPanel, this.confirmPanel],
            });
             this.ogText.connect(this, { resize: "updateSize" });
             this.$body.append(this.stackLayout.$element);
         }
         }
    } catch (err) {
        getBodyHeight() {
        _d = true;
             return this.stackLayout.getCurrentItem().$element.outerHeight(true);
        _e = err;
    } finally{
        try {
             if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
         }
         }
    }
        getSetupProcess(data) {
    return _arr;
            return super.getSetupProcess(data).next(() => {
}
                this.actions.setMode("config");
function _non_iterable_rest() {
                this.stackLayout.setItem(this.configPanel);
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
             }, this);
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
             }));
         }
         }
         ownKeys.forEach(function(key) {
         getReadyProcess(data) {
             _define_property(target, key, source[key]);
             return super.getReadyProcess(data)
        });
                .next(() => {
    }
                 this.ogText.focus();
    return target;
             }, this);
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                 return Object.getOwnPropertyDescriptor(object, sym).enumerable;
             });
         }
         }
         keys.push.apply(keys, symbols);
         getActionProcess(action) {
    }
             if (action === "cancel") {
    return keys;
                return new OO.ui.Process(() => {
}
                    this.close({ action: action });
function _object_spread_props(target, source) {
                }, this);
    source = source != null ? source : {};
            }
    if (Object.getOwnPropertyDescriptors) {
            else if (action === "continue") {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
                return new OO.ui.Process($.when((async () => {
    } else {
                    this.config = $.extend(this.config, {
        ownKeys(Object(source)).forEach(function(key) {
                        main: this.mainVariants.getValue().split(";"),
             Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
                        dependent: Object.fromEntries(this.depVariants.getValue().split(";").map((v) => v.split(":"))),
        });
                        noteTAStr: this.noteTAParams.getValue(),
    }
                        useOpenCC: this.occCheckbox.isSelected(),
    return target;
                        dependentInv: {},
}
                    });
function _possible_constructor_return(self, call) {
                    if (this.config.main.includes("(main)")) {
    if (call && (_type_of(call) === "object" || typeof call === "function")) {
                        throw new OO.ui.Error(wgULS("主页面不得作为主要变体", "主頁面不得作為主要變体"));
        return call;
                    }
    }
                    this.config.main.forEach((v) => this.config.dependentInv[v] = [v]);
    return _assert_this_initialized(self);
                    try {
}
                        Object.entries(this.config.dependent).forEach(([k, v]) => this.config.dependentInv[v].push(k));
function _set_prototype_of(o, p) {
                    }
    _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
                    catch {
        o.__proto__ = p;
                        console.error("[VariantConverter] Error: Key not found in dependentInv. Config dump:", this.config);
        return o;
                        throw new OO.ui.Error(wgULS("依赖变体格式错误,请检查控制台", "依賴變体格式錯誤,請檢查控制臺"));
    };
                     }
    return _set_prototype_of(o, p);
                     this.textInputs = {};
}
                     this.confirmPanel.$element.empty();
function _sliced_to_array(arr, i) {
                     try {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
                         await this.getVariants(this.ogText.getValue());
}
                        this.actions.setMode("confirm");
function _super_prop_base(object, property) {
                        this.stackLayout.setItem(this.confirmPanel);
    while(!Object.prototype.hasOwnProperty.call(object, property)){
                         this.updateSize();
        object = _get_prototype_of(object);
        if (object === null) break;
    }
    return object;
}
function _to_array(arr) {
    return _array_with_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_rest();
}
function _type_of(obj) {
    "@swc/helpers - typeof";
    return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
function _is_native_reflect_construct() {
    try {
        var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
    } catch (_) {}
    return (_is_native_reflect_construct = function() {
        return !!result;
    })();
}
function _ts_generator(thisArg, body) {
    var f, y, t, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["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])) {
                     catch (e) {
                         _.label = op[1];
                         console.error("[VariantConverter] Error:", e);
                         break;
                         throw new OO.ui.Error(e);
                     }
                     }
                    if (op[0] === 6 && _.label < t[1]) {
                })()).promise(), this);
                         _.label = t[1];
            }
                         t = op;
            else if (action === "back") {
                         break;
                this.actions.setMode("config");
                this.stackLayout.setItem(this.configPanel);
                this.updateSize();
            }
            else if (action === "submit") {
                return new OO.ui.Process($.when((async () => {
                    try {
                         await this.saveChanges();
                        this.close({ action: action });
                         mw.notify("保存成功!", {
                            title: wgULS("自动繁简转换工具", "自動繁簡轉換工具"),
                            type: "success",
                            tag: "lr-aivc",
                        });
                         setTimeout(() => location.reload(), 730);
                     }
                     }
                     if (t && _.label < t[2]) {
                     catch (e) {
                         _.label = t[2];
                         console.error("[VariantConverter] Error:", e);
                         _.ops.push(op);
                         throw new OO.ui.Error(e);
                        break;
                     }
                     }
                     if (t[2]) _.ops.pop();
                })()).promise(), this);
                    _.trys.pop();
            }
            return super.getActionProcess(action);
        }
        addVariant(variant, text) {
            this.textInputs[variant] = new OO.ui.MultilineTextInputWidget({
                value: text,
                autosize: true,
            });
            const field = new OO.ui.FieldLayout(this.textInputs[variant], {
                label: variant,
                align: "top",
            });
            this.textInputs[variant].connect(this, { resize: "updateSize" });
            this.confirmPanel.$element.append(field.$element);
            if (window?.InPageEdit?.quickDiff) {
                this.confirmPanel.$element.append(new OO.ui.FieldLayout(new OO.ui.Widget({
                     content: [
                        new OO.ui.HorizontalLayout({
                            items: this.config.dependentInv[variant].map((v) => new OO.ui.ButtonWidget({
                                label: `${wgULS("对比", "對比")}${v === "(main)" ? wgULS("主页面", "主頁面") : v}`,
                            }).on("click", () => window.InPageEdit.quickDiff({
                                fromtitle: variantPage(v),
                                totext: this.textInputs[variant].getValue(),
                                pageName: variantPage(v),
                                isPreview: true,
                            }))),
                        }),
                    ],
                })).$element);
            }
        }
        async getVariants(original) {
            this.confirmPanel.$element.append(`<p>${wgULS("请确认以下转换是否正确", "請確認以下轉換是否正確")}:</p>`);
            if (!window.OpenCC && this.config.useOpenCC) {
                await libCachedCode.injectCachedCode("https://npm.elemecdn.com/opencc-js@latest", "script");
            }
            const { replaced, mappings } = escapeWikitext(original);
            for (const variant of this.config.main) {
                if (variant === "(main)") {
                     continue;
                     continue;
                }
                const text = `{{NoteTA|${this.config.noteTAStr}}}<pre id="converted">-{}-${replaced}</pre>`;
                const parsed = $($.parseHTML((await zhAPI.post({
                    action: "parse",
                    assertuser: username,
                    text,
                    contentmodel: "wikitext",
                    prop: "text",
                    uselang: variant,
                    disablelimitreport: true,
                    pst: true,
                })).parse.text["*"]));
                let converted = parsed.find("#converted").text();
                if (this.config.useOpenCC) {
                    const occMappings = [];
                    converted = converted.replace(REGEXP.noOCC, (_, content) => `<!--noOCC-->${occMappings.push(content) - 1}<!--/noOCC-->`);
                    const occVariant = variant.replace("hans", "cn").replace(/zh-(?:han)?/, "").replace("tw", "twp");
                    const converter = OpenCC.Converter({ from: occVariant, to: occVariant });
                    converted = converter(converted);
                    converted = converted.replace(REGEXP.noOCC, (_, index) => `<!--noOCC-->${occMappings[index]}<!--/noOCC-->`);
                }
                const final = this.config.manualAction[variant]?.(converted) || converted;
                const restored = restoreWikitext(final, mappings);
                this.addVariant(variant, restored);
             }
             }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
         }
         }
         if (op[0] & 5) throw op[1];
         async saveChanges() {
        return {
            console.log("[VariantConverter] Saved changes", await Promise.allSettled(this.config.main.map((variant) => {
             value: op[0] ? op[1] : void 0,
                const text = this.textInputs[variant].getValue();
             done: true
                return api.postWithToken("csrf", {
         };
                    action: "edit",
                    assertuser: username,
                    title: variantPage(variant),
                    text,
                    summary: `自动转换自[[${pagename}]]`,
                    tags: "VariantConverter|Automation tool",
                    watchlist: this.config.watchlist,
                });
             }).concat(Object.entries(this.config.dependent).map(([variant, parent]) => {
                const text = this.textInputs[parent].getValue();
                return api.postWithToken("csrf", {
                    action: "edit",
                    assertuser: username,
                    title: variantPage(variant),
                    text,
                    summary: `自动转换自[[${pagename}]](同步${parent})`,
                    tags: "VariantConverter|Automation tool",
                    watchlist: this.config.watchlist,
                });
             }))));
         }
     }
     }
}
    _a = AIVCWindow;
function _ts_values(o) {
    AIVCWindow.static = {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
        ...Reflect.get(_b, "static", _a),
    if (m) return m.call(o);
        tagName: "div",
    if (o && typeof o.length === "number") return {
        name: "lr-aivc",
        next: function() {
        title: wgULS("自动繁简转换工具", "自動繁簡轉換工具"),
             if (o && i >= o.length) o = void 0;
        actions: [
             return {
            {
                 value: o && o[i++],
                action: "cancel",
                 done: !o
                label: "取消",
             };
                flags: ["safe", "close", "destructive"],
         }
                modes: "config",
            },
            {
                action: "continue",
                label: wgULS("继续", "繼續"),
                flags: ["primary", "progressive"],
                modes: "config",
            },
            {
                action: "back",
                label: "返回",
                flags: ["safe", "back"],
                modes: "confirm",
             },
             {
                 action: "submit",
                label: wgULS("确认", "確認"),
                flags: ["primary", "progressive"],
                 modes: "confirm",
             },
         ],
     };
     };
     throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
     const $body = $(document.body);
}
    const windowManager = new OO.ui.WindowManager();
// TODO: Fix MultilineTextInput initial height
    $body.append(windowManager.$element);
// Test: https://zh.moegirl.org.cn/index.php?oldid=5572397
    const aivcDialog = new AIVCWindow({
// declare var lrAivc: {
        size: "large",
//    [key: string]: any;
        data: {
// };
            config: lrAivc,
// declare var OpenCC: any;
            prepopContent,
// declare var InPageEdit: {
        },
//    [key: string]: any;
    });
// };
    windowManager.addWindows([aivcDialog]);
$(function() {
    $(mw.util.addPortletLink("p-cactions", "#", wgULS("自动繁简转换", "自動繁簡轉換"), "ca-VariantConverter", wgULS("自动同步界面消息的繁简版本", "自動同步介面消息的繁簡版本"))).on("click", (e) => {
    return function() {
        e.preventDefault();
        return _async_to_generator(function() {
        $("#mw-notification-area").appendTo($body);
            var pagename, username, pageid, basepage, api, zhAPI, lrAivc, prepopContent, _tmp, e, toParams, variantPage, REGEXP, escapeWikitext, restoreWikitext, _OO_ui_ProcessDialog, AIVCWindow, $body, windowManager, aivcDialog;
        windowManager.openWindow(aivcDialog);
            return _ts_generator(this, function(_state) {
    });
                switch(_state.label){
})());  
                    case 0:
                        pagename = mw.config.get("wgPageName");
                        username = mw.config.get("wgUserName");
                        // await mw.loader.using(["mediawiki.api", "oojs-ui"]);
                        pageid = mw.config.get("wgArticleId");
                        basepage = pagename.replace(/\/.*?$/, "");
                        api = new mw.Api(), zhAPI = /m?zh\.moegirl\.org\.cn/.test(location.hostname) ? api : new mw.ForeignApi("https://mzh.moegirl.org.cn/api.php", {
                            anonymous: true
                        });
                        lrAivc = $.extend({
                            main: [
                                "zh-cn",
                                "zh-tw",
                                "zh-hk"
                            ],
                            dependent: {
                                "(main)": "zh-cn",
                                "zh-hans": "zh-cn",
                                "zh-hant": "zh-tw"
                            },
                            noteTA: {
                                G1: "MediaWiki"
                            },
                            autoPopulate: true,
                            useOpenCC: true,
                            manualAction: {
                                "zh-hk": function(t) {
                                    return t.replaceAll("户", "戶");
                                },
                                "zh-tw": function(t) {
                                    return t.replaceAll("名稱空間", "命名空間").replaceAll("記憶體", "內存");
                                }
                            },
                            watchlist: "nochange"
                        }, window.lr_aivc);
                        prepopContent = "";
                        _state.label = 1;
                    case 1:
                        _state.trys.push([
                            1,
                            5,
                            ,
                            6
                        ]);
                        if (!lrAivc.autoPopulate) return [
                            3,
                            3
                        ];
                        return [
                            4,
                            api.get({
                                action: "parse",
                                assertuser: username,
                                pageid: pageid,
                                prop: "wikitext"
                            })
                        ];
                    case 2:
                        _tmp = _state.sent().parse.wikitext["*"];
                        return [
                            3,
                            4
                        ];
                    case 3:
                        _tmp = "";
                        _state.label = 4;
                    case 4:
                        prepopContent = _tmp;
                        return [
                            3,
                            6
                        ];
                    case 5:
                        e = _state.sent();
                        return [
                            3,
                            6
                        ];
                    case 6:
                        toParams = function(obj) {
                            return Object.entries(obj).map(function(param) {
                                var _param = _sliced_to_array(param, 2), k = _param[0], v = _param[1];
                                return "".concat(k, "=").concat(v);
                            }).join("|");
                        };
                        variantPage = function(variant) {
                            return variant === "(main)" ? "".concat(basepage) : "".concat(basepage, "/").concat(variant);
                        };
                        REGEXP = {
                            // [\s\S] works with new lines (avoids using dotall flag)
                            lcMarker: /-{([\s\S]*?)}-/g,
                            lcMarkerEsc: /-\\{([\s\S]*?)}\\-/g,
                            nowiki: /<nowiki>([\s\S]*?)<\/nowiki>/g,
                            link: /\[\[([\s\S]*?)(?:#([\s\S]*?))?(\|[\s\S]*?)?\]\]/g,
                            extLink: /([^[])\[([^[]+?)( [\s\S]+?)?\]([^\]])/g,
                            // extLink: /(?<!\[)\[([^[]+?)( [\s\S]+?)?\](?!\])/g,
                            template: /\{\{([\s\S]*?)\}\}/g,
                            htmlEntity: /&([a-zA-Z0-9#]+);/g,
                            noOCC: /<!--noOCC-->([\s\S]*?)<!--\/noOCC-->/gi
                        };
                        escapeWikitext = function(original) {
                            var nowikis = [], mappings = [];
                            var replaced = original;
                            // Preserve all LC markers (including those within nowiki)
                            replaced = replaced.replace(REGEXP.lcMarker, function(_, content) {
                                return "-\\{".concat(content, "}\\-");
                            });
                            // Temporarily strip nowiki
                            replaced = replaced.replace(REGEXP.nowiki, function(_, content) {
                                return "<nowiki>".concat(nowikis.push(content) - 1, "</nowiki>");
                            });
                            // Replace link targets and anchors with IDs
                            replaced = replaced.replace(REGEXP.link, function(match, target, anchor, text) {
                                return anchor || text ? "[[".concat(text ? mappings.push(target) - 1 : target).concat(anchor ? "#".concat(mappings.push(anchor) - 1) : "").concat(text || "", "]]") : match;
                            });
                            // Replace external link targets with IDs
                            replaced = replaced.replace(REGEXP.extLink, function(_, before, target, text, after) {
                                return "".concat(before, "[").concat(mappings.push(target) - 1).concat(text || "", "]").concat(after);
                            });
                            // replaced = replaced.replace(REGEXP.extLink, (_, target, text) => `[${mappings.push(target) - 1}${text || ""}]`);
                            // Replace template names and parameters with IDs
                            replaced = replaced.replace(REGEXP.template, function(_, params) {
                                var paramList = params.split("|");
                                mappings.push(paramList[0]);
                                paramList.shift();
                                return "".concat(paramList.reduce(function(acc, param) {
                                    var _param_split = _to_array(param.split("=")), first = _param_split[0], rest = _param_split.slice(1);
                                    // If rest is not empty, it's a named parameter; otherwise, it's a positional parameter
                                    return rest.length ? "".concat(acc, "|").concat(mappings.push(first) - 1, "=").concat(rest.join("=")) : "".concat(acc, "|").concat(param);
                                }, "{{".concat(mappings.length - 1)), "}}");
                            });
                            // Replace LC markers with IDs
                            replaced = replaced.replace(REGEXP.lcMarkerEsc, function(_, content) {
                                return "-\\{".concat(mappings.push(content || "") - 1, "}\\-");
                            });
                            // Replace HTML entities with IDs
                            replaced = replaced.replace(REGEXP.htmlEntity, function(_, entity) {
                                return "&".concat(mappings.push(entity) - 1, ";");
                            });
                            // Restore nowiki
                            replaced = replaced.replace(REGEXP.nowiki, function(_, index) {
                                return "<nowiki><nowiki>".concat(nowikis[index], "</nowiki></nowiki>");
                            });
                            return {
                                replaced: replaced,
                                mappings: mappings
                            };
                        };
                        restoreWikitext = function(original, mappings) {
                            var nowikis = [];
                            var replaced = original;
                            // Temporarily strip nowiki
                            replaced = replaced.replace(REGEXP.nowiki, function(_, content) {
                                return "<nowiki>".concat(nowikis.push(content) - 1, "</nowiki>");
                            });
                            // Restore HTML entities
                            replaced = replaced.replace(REGEXP.htmlEntity, function(_, index) {
                                return "&".concat(mappings[index], ";");
                            });
                            // Restore template names and parameters
                            replaced = replaced.replace(REGEXP.template, function(_, params) {
                                var paramList = params.split("|");
                                var name = mappings[paramList[0]];
                                paramList.shift();
                                return "".concat(paramList.reduce(function(acc, param) {
                                    var _param_split = _to_array(param.split("=")), first = _param_split[0], rest = _param_split.slice(1);
                                    // If rest is not empty, it's a named parameter; otherwise, it's a positional parameter
                                    return rest.length ? "".concat(acc, "|").concat(mappings[first], "=").concat(rest.join("=")) : "".concat(acc, "|").concat(param);
                                }, "{{".concat(name)), "}}");
                            });
                            // Restore external link targets
                            replaced = replaced.replace(REGEXP.extLink, function(_, before, target, text, after) {
                                return "".concat(before, "[").concat(mappings[target]).concat(text || "", "]").concat(after);
                            });
                            // replaced = replaced.replace(REGEXP.extLink, (_, target, text) => `[${mappings[target]}${text || ""}]`);
                            // Restore link targets
                            replaced = replaced.replace(REGEXP.link, function(match, target, anchor, text) {
                                return anchor || text ? "[[".concat(text ? mappings[target] : target).concat(mappings[anchor] ? "#".concat(mappings[anchor]) : "").concat(text || "", "]]") : match;
                            });
                            // Restore nowiki
                            replaced = replaced.replace(REGEXP.nowiki, function(_, index) {
                                return "<nowiki>".concat(nowikis[index], "</nowiki>");
                            });
                            // Restore all LC markers (including those within nowiki)
                            replaced = replaced.replace(REGEXP.lcMarkerEsc, function(_, index) {
                                var _mappings_index;
                                return "-{".concat((_mappings_index = mappings[index]) !== null && _mappings_index !== void 0 ? _mappings_index : index, "}-");
                            });
                            return replaced;
                        };
                        AIVCWindow = /*#__PURE__*/ function(_superClass) {
                            _inherits(AIVCWindow, _superClass);
                            function AIVCWindow(config) {
                                _class_call_check(this, AIVCWindow);
                                var _this;
                                // Parent constructor
                                _this = _call_super(this, AIVCWindow, [
                                    config
                                ]);
                                _this.config = config.data.config;
                                _this.prepopContent = config.data.prepopContent;
                                return _this;
                            }
                            _create_class(AIVCWindow, [
                                {
                                    key: "initialize",
                                    value: function initialize() {
                                        // Parent method
                                        _get(_get_prototype_of(AIVCWindow.prototype), "initialize", this).call(this);
                                        this.configPanel = new OO.ui.PanelLayout({
                                            scrollable: false,
                                            expanded: false,
                                            padded: true
                                        });
                                        this.confirmPanel = new OO.ui.PanelLayout({
                                            scrollable: false,
                                            expanded: false,
                                            padded: true
                                        });
                                        this.ogText = new OO.ui.MultilineTextInputWidget({
                                            value: this.prepopContent,
                                            autosize: true
                                        });
                                        var textField = new OO.ui.FieldLayout(this.ogText, {
                                            label: wgULS("原始内容", "原始內容"),
                                            align: "top"
                                        });
                                        this.mainVariants = new OO.ui.TextInputWidget({
                                            value: this.config.main.join(";")
                                        });
                                        var mainField = new OO.ui.FieldLayout(this.mainVariants, {
                                            label: wgULS("主要变体", "主要變体"),
                                            align: "top"
                                        });
                                        this.depVariants = new OO.ui.TextInputWidget({
                                            value: Object.entries(this.config.dependent).map(function(param) {
                                                var _param = _sliced_to_array(param, 2), k = _param[0], v = _param[1];
                                                return "".concat(k, ":").concat(v);
                                            }).join(";")
                                        });
                                        var depField = new OO.ui.FieldLayout(this.depVariants, {
                                            label: wgULS("依赖变体", "依賴變体"),
                                            align: "top"
                                        });
                                        this.noteTAParams = new OO.ui.TextInputWidget({
                                            value: toParams(this.config.noteTA)
                                        });
                                        var noteTAField = new OO.ui.FieldLayout(this.noteTAParams, {
                                            label: wgULS("NoteTA参数", "NoteTA參數"),
                                            align: "top"
                                        });
                                        this.occCheckbox = new OO.ui.CheckboxInputWidget({
                                            selected: this.config.useOpenCC
                                        });
                                        var occField = new OO.ui.FieldLayout(this.occCheckbox, {
                                            label: "使用OpenCC",
                                            align: "inline"
                                        });
                                        this.configPanel.$element.append(textField.$element, mainField.$element, depField.$element, noteTAField.$element, occField.$element);
                                        this.stackLayout = new OO.ui.StackLayout({
                                            items: [
                                                this.configPanel,
                                                this.confirmPanel
                                            ]
                                        });
                                        this.ogText.connect(this, {
                                            resize: "updateSize"
                                        });
                                        this.$body.append(this.stackLayout.$element);
                                    }
                                },
                                {
                                    key: "getBodyHeight",
                                    value: function getBodyHeight() {
                                        return this.stackLayout.getCurrentItem().$element.outerHeight(true);
                                    }
                                },
                                {
                                    key: "getSetupProcess",
                                    value: function getSetupProcess(data) {
                                        var _this = this;
                                        return _get(_get_prototype_of(AIVCWindow.prototype), "getSetupProcess", this).call(this, data).next(function() {
                                            _this.actions.setMode("config");
                                            _this.stackLayout.setItem(_this.configPanel);
                                        }, this);
                                    }
                                },
                                {
                                    key: "getReadyProcess",
                                    value: function getReadyProcess(data) {
                                        var _this = this;
                                        return _get(_get_prototype_of(AIVCWindow.prototype), "getReadyProcess", this).call(this, data).next(function() {
                                            _this.ogText.focus();
                                        }, this);
                                    }
                                },
                                {
                                    key: "getActionProcess",
                                    value: function getActionProcess(action) {
                                        var _this = this;
                                        if (action === "cancel") {
                                            return new OO.ui.Process(function() {
                                                _this.close({
                                                    action: action
                                                });
                                            }, this);
                                        } else if (action === "continue") {
                                            return new OO.ui.Process($.when(function() {
                                                return _async_to_generator(function() {
                                                    var _this, e;
                                                    return _ts_generator(this, function(_state) {
                                                        switch(_state.label){
                                                            case 0:
                                                                _this = this;
                                                                this.config = $.extend(this.config, {
                                                                    main: this.mainVariants.getValue().split(";"),
                                                                    dependent: Object.fromEntries(this.depVariants.getValue().split(";").map(function(v) {
                                                                        return v.split(":");
                                                                    })),
                                                                    noteTAStr: this.noteTAParams.getValue(),
                                                                    useOpenCC: this.occCheckbox.isSelected(),
                                                                    dependentInv: {}
                                                                });
                                                                if (this.config.main.includes("(main)")) {
                                                                    throw new OO.ui.Error(wgULS("主页面不得作为主要变体", "主頁面不得作為主要變体"));
                                                                }
                                                                this.config.main.forEach(function(v) {
                                                                    return _this.config.dependentInv[v] = [
                                                                        v
                                                                    ];
                                                                });
                                                                try {
                                                                    Object.entries(this.config.dependent).forEach(function(param) {
                                                                        var _param = _sliced_to_array(param, 2), k = _param[0], v = _param[1];
                                                                        return _this.config.dependentInv[v /* as string */ ].push(k);
                                                                    });
                                                                } catch (e) {
                                                                    console.error("[VariantConverter] Error: Key not found in dependentInv. Config dump:", this.config);
                                                                    throw new OO.ui.Error(wgULS("依赖变体格式错误,请检查控制台", "依賴變体格式錯誤,請檢查控制臺"));
                                                                }
                                                                this.textInputs = {};
                                                                this.confirmPanel.$element.empty();
                                                                _state.label = 1;
                                                            case 1:
                                                                _state.trys.push([
                                                                    1,
                                                                    3,
                                                                    ,
                                                                    4
                                                                ]);
                                                                return [
                                                                    4,
                                                                    this.getVariants(this.ogText.getValue())
                                                                ];
                                                            case 2:
                                                                _state.sent();
                                                                this.actions.setMode("confirm");
                                                                this.stackLayout.setItem(this.confirmPanel);
                                                                this.updateSize();
                                                                return [
                                                                    3,
                                                                    4
                                                                ];
                                                            case 3:
                                                                e = _state.sent();
                                                                console.error("[VariantConverter] Error:", e);
                                                                throw new OO.ui.Error(e);
                                                            case 4:
                                                                return [
                                                                    2
                                                                ];
                                                        }
                                                    });
                                                }).call(_this);
                                            }()).promise(), this);
                                        } else if (action === "back") {
                                            this.actions.setMode("config");
                                            this.stackLayout.setItem(this.configPanel);
                                            this.updateSize();
                                        } else if (action === "submit") {
                                            return new OO.ui.Process($.when(function() {
                                                return _async_to_generator(function() {
                                                    var e;
                                                    return _ts_generator(this, function(_state) {
                                                        switch(_state.label){
                                                            case 0:
                                                                _state.trys.push([
                                                                    0,
                                                                    2,
                                                                    ,
                                                                    3
                                                                ]);
                                                                return [
                                                                    4,
                                                                    this.saveChanges()
                                                                ];
                                                            case 1:
                                                                _state.sent();
                                                                this.close({
                                                                    action: action
                                                                });
                                                                mw.notify("保存成功!", {
                                                                    title: wgULS("自动繁简转换工具", "自動繁簡轉換工具"),
                                                                    type: "success",
                                                                    tag: "lr-aivc"
                                                                });
                                                                setTimeout(function() {
                                                                    return location.reload();
                                                                }, 730);
                                                                return [
                                                                    3,
                                                                    3
                                                                ];
                                                            case 2:
                                                                e = _state.sent();
                                                                console.error("[VariantConverter] Error:", e);
                                                                throw new OO.ui.Error(e);
                                                            case 3:
                                                                return [
                                                                    2
                                                                ];
                                                        }
                                                    });
                                                }).call(_this);
                                            }()).promise(), this);
                                        }
                                        // Fallback to parent handler
                                        return _get(_get_prototype_of(AIVCWindow.prototype), "getActionProcess", this).call(this, action);
                                    }
                                },
                                {
                                    key: "addVariant",
                                    value: function addVariant(variant, text) {
                                        var _this = this;
                                        var _window_InPageEdit, _window;
                                        this.textInputs[variant] = new OO.ui.MultilineTextInputWidget({
                                            value: text,
                                            autosize: true
                                        });
                                        var field = new OO.ui.FieldLayout(this.textInputs[variant], {
                                            label: variant,
                                            align: "top"
                                        });
                                        this.textInputs[variant].connect(this, {
                                            resize: "updateSize"
                                        });
                                        this.confirmPanel.$element.append(field.$element);
                                        if ((_window = window) === null || _window === void 0 ? void 0 : (_window_InPageEdit = _window.InPageEdit) === null || _window_InPageEdit === void 0 ? void 0 : _window_InPageEdit.quickDiff) {
                                            this.confirmPanel.$element.append(new OO.ui.FieldLayout(new OO.ui.Widget({
                                                content: [
                                                    new OO.ui.HorizontalLayout({
                                                        items: this.config.dependentInv[variant].map(function(v) {
                                                            return new OO.ui.ButtonWidget({
                                                                label: "".concat(wgULS("对比", "對比")).concat(v === "(main)" ? wgULS("主页面", "主頁面") : v)
                                                            }).on("click", function() {
                                                                return window.InPageEdit.quickDiff({
                                                                    fromtitle: variantPage(v),
                                                                    totext: _this.textInputs[variant].getValue(),
                                                                    pageName: variantPage(v),
                                                                    isPreview: true
                                                                });
                                                            });
                                                        })
                                                    })
                                                ]
                                            })).$element);
                                        }
                                    }
                                },
                                {
                                    key: "getVariants",
                                    value: function getVariants(original) {
                                        return _async_to_generator(function() {
                                            var _escapeWikitext, replaced, mappings, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _this, _loop, _iterator, _step, err;
                                            return _ts_generator(this, function(_state) {
                                                switch(_state.label){
                                                    case 0:
                                                        this.confirmPanel.$element.append("<p>".concat(wgULS("请确认以下转换是否正确", "請確認以下轉換是否正確"), ":</p>"));
                                                        if (!(!window.OpenCC && this.config.useOpenCC)) return [
                                                            3,
                                                            2
                                                        ];
                                                        // Load in order to prevent reference error
                                                        return [
                                                            4,
                                                            libCachedCode.injectCachedCode("https://npm.elemecdn.com/opencc-js@latest", "script")
                                                        ];
                                                    case 1:
                                                        _state.sent();
                                                        _state.label = 2;
                                                    case 2:
                                                        _escapeWikitext = escapeWikitext(original), replaced = _escapeWikitext.replaced, mappings = _escapeWikitext.mappings;
                                                        _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                                                        _state.label = 3;
                                                    case 3:
                                                        _state.trys.push([
                                                            3,
                                                            8,
                                                            9,
                                                            10
                                                        ]);
                                                        _loop = function() {
                                                            var variant, _this_config_manualAction_variant, _this_config_manualAction, text, parsed, _, converted, occMappings, occVariant, converter, final, restored;
                                                            return _ts_generator(this, function(_state) {
                                                                switch(_state.label){
                                                                    case 0:
                                                                        variant = _step.value;
                                                                        if (variant === "(main)") {
                                                                            return [
                                                                                2,
                                                                                "continue"
                                                                            ];
                                                                        }
                                                                        text = "{{NoteTA|".concat(_this.config.noteTAStr, '}}<pre id="converted">-{}-').concat(replaced, "</pre>");
                                                                        _ = $.parseHTML;
                                                                        return [
                                                                            4,
                                                                            zhAPI.post({
                                                                                action: "parse",
                                                                                assertuser: username,
                                                                                text: text,
                                                                                contentmodel: "wikitext",
                                                                                prop: "text",
                                                                                uselang: variant,
                                                                                disablelimitreport: true,
                                                                                pst: true
                                                                            })
                                                                        ];
                                                                    case 1:
                                                                        parsed = $.apply(void 0, [
                                                                            _.apply($, [
                                                                                _state.sent().parse.text["*"]
                                                                            ])
                                                                        ]);
                                                                        converted = parsed.find("#converted").text();
                                                                        if (_this.config.useOpenCC) {
                                                                            occMappings = [];
                                                                            converted = converted.replace(REGEXP.noOCC, function(_, content) {
                                                                                return "<!--noOCC-->".concat(occMappings.push(content) - 1, "<!--/noOCC-->");
                                                                            });
                                                                            occVariant = variant.replace("hans", "cn").replace(/zh-(?:han)?/, "").replace("tw", "twp");
                                                                            converter = OpenCC.Converter({
                                                                                from: occVariant,
                                                                                to: occVariant
                                                                            });
                                                                            converted = converter(converted);
                                                                            converted = converted.replace(REGEXP.noOCC, function(_, index) {
                                                                                return "<!--noOCC-->".concat(occMappings[index], "<!--/noOCC-->");
                                                                            });
                                                                        }
                                                                        final = ((_this_config_manualAction_variant = (_this_config_manualAction = _this.config.manualAction)[variant]) === null || _this_config_manualAction_variant === void 0 ? void 0 : _this_config_manualAction_variant.call(_this_config_manualAction, converted)) || converted;
                                                                        restored = restoreWikitext(final, mappings);
                                                                        _this.addVariant(variant, restored);
                                                                        return [
                                                                            2
                                                                        ];
                                                                }
                                                            });
                                                        };
                                                        _iterator = this.config.main[Symbol.iterator]();
                                                        _state.label = 4;
                                                    case 4:
                                                        if (!!(_iteratorNormalCompletion = (_step = _iterator.next()).done)) return [
                                                            3,
                                                            7
                                                        ];
                                                        _this = this;
                                                        return [
                                                            5,
                                                            _ts_values(_loop())
                                                        ];
                                                    case 5:
                                                        _state.sent();
                                                        _state.label = 6;
                                                    case 6:
                                                        _iteratorNormalCompletion = true;
                                                        return [
                                                            3,
                                                            4
                                                        ];
                                                    case 7:
                                                        return [
                                                            3,
                                                            10
                                                        ];
                                                    case 8:
                                                        err = _state.sent();
                                                        _didIteratorError = true;
                                                        _iteratorError = err;
                                                        return [
                                                            3,
                                                            10
                                                        ];
                                                    case 9:
                                                        try {
                                                            if (!_iteratorNormalCompletion && _iterator.return != null) {
                                                                _iterator.return();
                                                            }
                                                        } finally{
                                                            if (_didIteratorError) {
                                                                throw _iteratorError;
                                                            }
                                                        }
                                                        return [
                                                            7
                                                        ];
                                                    case 10:
                                                        return [
                                                            2
                                                        ];
                                                }
                                            });
                                        }).call(this);
                                    }
                                },
                                {
                                    key: "saveChanges",
                                    value: function saveChanges() {
                                        return _async_to_generator(function() {
                                            var _this, _, _tmp;
                                            return _ts_generator(this, function(_state) {
                                                switch(_state.label){
                                                    case 0:
                                                        _this = this;
                                                        // Occasionally edits are not saved - keep this log until the bug is identified
                                                        _ = console.log;
                                                        _tmp = [
                                                            "[VariantConverter] Saved changes"
                                                        ];
                                                        return [
                                                            4,
                                                            Promise.allSettled(this.config.main.map(function(variant) {
                                                                var text = _this.textInputs[variant].getValue();
                                                                return api.postWithToken("csrf", {
                                                                    action: "edit",
                                                                    assertuser: username,
                                                                    title: variantPage(variant),
                                                                    text: text,
                                                                    summary: "自动转换自[[".concat(pagename, "]]"),
                                                                    tags: "VariantConverter|Automation tool",
                                                                    watchlist: _this.config.watchlist
                                                                });
                                                            }).concat(Object.entries(this.config.dependent).map(function(param) {
                                                                var _param = _sliced_to_array(param, 2), variant = _param[0], parent = _param[1];
                                                                var text = _this.textInputs[parent /* as string */ ].getValue();
                                                                return api.postWithToken("csrf", {
                                                                    action: "edit",
                                                                    assertuser: username,
                                                                    title: variantPage(variant),
                                                                    text: text,
                                                                    summary: "自动转换自[[".concat(pagename, "]](同步").concat(parent, ")"),
                                                                    tags: "VariantConverter|Automation tool",
                                                                    watchlist: _this.config.watchlist
                                                                });
                                                            })))
                                                        ];
                                                    case 1:
                                                        _.apply(console, _tmp.concat([
                                                            _state.sent()
                                                        ]));
                                                        return [
                                                            2
                                                        ];
                                                }
                                            });
                                        }).call(this);
                                    }
                                }
                            ]);
                            return AIVCWindow;
                        }(_OO_ui_ProcessDialog = OO.ui.ProcessDialog);
                        _define_property(AIVCWindow, "static", _object_spread_props(_object_spread({}, _get(_get_prototype_of(AIVCWindow), "static", AIVCWindow)), {
                            tagName: "div",
                            name: "lr-aivc",
                            title: wgULS("自动繁简转换工具", "自動繁簡轉換工具"),
                            actions: [
                                {
                                    action: "cancel",
                                    label: "取消",
                                    flags: [
                                        "safe",
                                        "close",
                                        "destructive"
                                    ],
                                    modes: "config"
                                },
                                {
                                    action: "continue",
                                    label: wgULS("继续", "繼續"),
                                    flags: [
                                        "primary",
                                        "progressive"
                                    ],
                                    modes: "config"
                                },
                                {
                                    action: "back",
                                    label: "返回",
                                    flags: [
                                        "safe",
                                        "back"
                                    ],
                                    modes: "confirm"
                                },
                                {
                                    action: "submit",
                                    label: wgULS("确认", "確認"),
                                    flags: [
                                        "primary",
                                        "progressive"
                                    ],
                                    modes: "confirm"
                                }
                            ]
                        }));
                        $body = $(document.body);
                        windowManager = new OO.ui.WindowManager();
                        $body.append(windowManager.$element);
                        aivcDialog = new AIVCWindow({
                            size: "large",
                            data: {
                                config: lrAivc,
                                prepopContent: prepopContent
                            }
                        });
                        windowManager.addWindows([
                            aivcDialog
                        ]);
                        $(mw.util.addPortletLink("p-cactions", "#", wgULS("自动繁简转换", "自動繁簡轉換"), "ca-VariantConverter", wgULS("自动同步界面消息的繁简版本", "自動同步介面消息的繁簡版本"))).on("click", function(e) {
                            e.preventDefault();
                            $("#mw-notification-area").appendTo($body);
                            windowManager.openWindow(aivcDialog);
                        });
                        return [
                            2
                        ];
                }
            });
        })();
    }();
}); // </pre>


/* </pre> */
/* </pre> */

2025年7月24日 (四) 20:53的版本

/**
 * -------------------------------------------------------------------------
 * !!! DON'T MODIFY THIS PAGE MANUALLY, YOUR CHANGES WILL BE OVERWRITTEN !!!
 * -------------------------------------------------------------------------
 */
var _addText = '{{GHIACode|page=GHIA:MoegirlPediaInterfaceCodes/blob/master/src/gadgets/interfaceVariantConverter/Gadget-interfaceVariantConverter.js|user=[[U:星海子]]|co-authors=|longId=a157f65a20db84d70f63275717dff38cbffb9db9|shortId=a157f65a|summary=chore}}'; 

/* <pre> */

"use strict";
$(() => (async () => {
    var _a, _b;
    const pagename = mw.config.get("wgPageName");
    const username = mw.config.get("wgUserName");
    const pageid = mw.config.get("wgArticleId");
    const basepage = pagename.replace(/\/.*?$/, "");
    const api = new mw.Api(), zhAPI = /m?zh\.moegirl\.org\.cn/.test(location.hostname) ? api : new mw.ForeignApi("https://mzh.moegirl.org.cn/api.php", { anonymous: true });
    const lrAivc = $.extend({
        main: ["zh-cn", "zh-tw", "zh-hk"],
        dependent: {
            "(main)": "zh-cn",
            "zh-hans": "zh-cn",
            "zh-hant": "zh-tw",
        },
        noteTA: {
            G1: "MediaWiki",
        },
        autoPopulate: true,
        useOpenCC: true,
        manualAction: {
            "zh-hk": (t) => t.replaceAll("户", "戶"),
            "zh-tw": (t) => t.replaceAll("名稱空間", "命名空間").replaceAll("記憶體", "內存"),
        },
        watchlist: "nochange",
    }, window.lr_aivc);
    let prepopContent = "";
    try {
        prepopContent = lrAivc.autoPopulate
            ? (await api.get({
                action: "parse",
                assertuser: username,
                pageid,
                prop: "wikitext",
            })).parse.wikitext["*"]
            : "";
    }
    catch { }
    const toParams = (obj) => Object.entries(obj).map(([k, v]) => `${k}=${v}`).join("|");
    const variantPage = (variant) => variant === "(main)" ? `${basepage}` : `${basepage}/${variant}`;
    const REGEXP = {
        lcMarker: /-{([\s\S]*?)}-/g,
        lcMarkerEsc: /-\\{([\s\S]*?)}\\-/g,
        nowiki: /<nowiki>([\s\S]*?)<\/nowiki>/g,
        link: /\[\[([\s\S]*?)(?:#([\s\S]*?))?(\|[\s\S]*?)?\]\]/g,
        extLink: /([^[])\[([^[]+?)( [\s\S]+?)?\]([^\]])/g,
        template: /\{\{([\s\S]*?)\}\}/g,
        htmlEntity: /&([a-zA-Z0-9#]+);/g,
        noOCC: /<!--noOCC-->([\s\S]*?)<!--\/noOCC-->/gi,
    };
    const escapeWikitext = (original) => {
        const nowikis = [], mappings = [];
        let replaced = original;
        replaced = replaced.replace(REGEXP.lcMarker, (_, content) => `-\\{${content}}\\-`);
        replaced = replaced.replace(REGEXP.nowiki, (_, content) => `<nowiki>${nowikis.push(content) - 1}</nowiki>`);
        replaced = replaced.replace(REGEXP.link, (match, target, anchor, text) => anchor || text ? `[[${text ? mappings.push(target) - 1 : target}${anchor ? `#${mappings.push(anchor) - 1}` : ""}${text || ""}]]` : match);
        replaced = replaced.replace(REGEXP.extLink, (_, before, target, text, after) => `${before}[${mappings.push(target) - 1}${text || ""}]${after}`);
        replaced = replaced.replace(REGEXP.template, (_, params) => {
            const paramList = params.split("|");
            mappings.push(paramList[0]);
            paramList.shift();
            return `${paramList.reduce((acc, param) => {
                const [first, ...rest] = param.split("=");
                return rest.length ? `${acc}|${mappings.push(first) - 1}=${rest.join("=")}` : `${acc}|${param}`;
            }, `{{${mappings.length - 1}`)}}}`;
        });
        replaced = replaced.replace(REGEXP.lcMarkerEsc, (_, content) => `-\\{${mappings.push(content || "") - 1}}\\-`);
        replaced = replaced.replace(REGEXP.htmlEntity, (_, entity) => `&${mappings.push(entity) - 1};`);
        replaced = replaced.replace(REGEXP.nowiki, (_, index) => `<nowiki><nowiki>${nowikis[index]}</nowiki></nowiki>`);
        return { replaced, mappings };
    };
    const restoreWikitext = (original, mappings) => {
        const nowikis = [];
        let replaced = original;
        replaced = replaced.replace(REGEXP.nowiki, (_, content) => `<nowiki>${nowikis.push(content) - 1}</nowiki>`);
        replaced = replaced.replace(REGEXP.htmlEntity, (_, index) => `&${mappings[index]};`);
        replaced = replaced.replace(REGEXP.template, (_, params) => {
            const paramList = params.split("|");
            const name = mappings[paramList[0]];
            paramList.shift();
            return `${paramList.reduce((acc, param) => {
                const [first, ...rest] = param.split("=");
                return rest.length ? `${acc}|${mappings[first]}=${rest.join("=")}` : `${acc}|${param}`;
            }, `{{${name}`)}}}`;
        });
        replaced = replaced.replace(REGEXP.extLink, (_, before, target, text, after) => `${before}[${mappings[target]}${text || ""}]${after}`);
        replaced = replaced.replace(REGEXP.link, (match, target, anchor, text) => anchor || text ? `[[${text ? mappings[target] : target}${mappings[anchor] ? `#${mappings[anchor]}` : ""}${text || ""}]]` : match);
        replaced = replaced.replace(REGEXP.nowiki, (_, index) => `<nowiki>${nowikis[index]}</nowiki>`);
        replaced = replaced.replace(REGEXP.lcMarkerEsc, (_, index) => `-{${mappings[index] ?? index}}-`);
        return replaced;
    };
    class AIVCWindow extends (_b = OO.ui.ProcessDialog) {
        constructor(config) {
            super(config);
            this.config = config.data.config;
            this.prepopContent = config.data.prepopContent;
        }
        initialize() {
            super.initialize();
            this.configPanel = new OO.ui.PanelLayout({
                scrollable: false,
                expanded: false,
                padded: true,
            });
            this.confirmPanel = new OO.ui.PanelLayout({
                scrollable: false,
                expanded: false,
                padded: true,
            });
            this.ogText = new OO.ui.MultilineTextInputWidget({
                value: this.prepopContent,
                autosize: true,
            });
            const textField = new OO.ui.FieldLayout(this.ogText, {
                label: wgULS("原始内容", "原始內容"),
                align: "top",
            });
            this.mainVariants = new OO.ui.TextInputWidget({
                value: this.config.main.join(";"),
            });
            const mainField = new OO.ui.FieldLayout(this.mainVariants, {
                label: wgULS("主要变体", "主要變体"),
                align: "top",
            });
            this.depVariants = new OO.ui.TextInputWidget({
                value: Object.entries(this.config.dependent).map(([k, v]) => `${k}:${v}`).join(";"),
            });
            const depField = new OO.ui.FieldLayout(this.depVariants, {
                label: wgULS("依赖变体", "依賴變体"),
                align: "top",
            });
            this.noteTAParams = new OO.ui.TextInputWidget({
                value: toParams(this.config.noteTA),
            });
            const noteTAField = new OO.ui.FieldLayout(this.noteTAParams, {
                label: wgULS("NoteTA参数", "NoteTA參數"),
                align: "top",
            });
            this.occCheckbox = new OO.ui.CheckboxInputWidget({
                selected: this.config.useOpenCC,
            });
            const occField = new OO.ui.FieldLayout(this.occCheckbox, {
                label: "使用OpenCC",
                align: "inline",
            });
            this.configPanel.$element.append(textField.$element, mainField.$element, depField.$element, noteTAField.$element, occField.$element);
            this.stackLayout = new OO.ui.StackLayout({
                items: [this.configPanel, this.confirmPanel],
            });
            this.ogText.connect(this, { resize: "updateSize" });
            this.$body.append(this.stackLayout.$element);
        }
        getBodyHeight() {
            return this.stackLayout.getCurrentItem().$element.outerHeight(true);
        }
        getSetupProcess(data) {
            return super.getSetupProcess(data).next(() => {
                this.actions.setMode("config");
                this.stackLayout.setItem(this.configPanel);
            }, this);
        }
        getReadyProcess(data) {
            return super.getReadyProcess(data)
                .next(() => {
                this.ogText.focus();
            }, this);
        }
        getActionProcess(action) {
            if (action === "cancel") {
                return new OO.ui.Process(() => {
                    this.close({ action: action });
                }, this);
            }
            else if (action === "continue") {
                return new OO.ui.Process($.when((async () => {
                    this.config = $.extend(this.config, {
                        main: this.mainVariants.getValue().split(";"),
                        dependent: Object.fromEntries(this.depVariants.getValue().split(";").map((v) => v.split(":"))),
                        noteTAStr: this.noteTAParams.getValue(),
                        useOpenCC: this.occCheckbox.isSelected(),
                        dependentInv: {},
                    });
                    if (this.config.main.includes("(main)")) {
                        throw new OO.ui.Error(wgULS("主页面不得作为主要变体", "主頁面不得作為主要變体"));
                    }
                    this.config.main.forEach((v) => this.config.dependentInv[v] = [v]);
                    try {
                        Object.entries(this.config.dependent).forEach(([k, v]) => this.config.dependentInv[v].push(k));
                    }
                    catch {
                        console.error("[VariantConverter] Error: Key not found in dependentInv. Config dump:", this.config);
                        throw new OO.ui.Error(wgULS("依赖变体格式错误,请检查控制台", "依賴變体格式錯誤,請檢查控制臺"));
                    }
                    this.textInputs = {};
                    this.confirmPanel.$element.empty();
                    try {
                        await this.getVariants(this.ogText.getValue());
                        this.actions.setMode("confirm");
                        this.stackLayout.setItem(this.confirmPanel);
                        this.updateSize();
                    }
                    catch (e) {
                        console.error("[VariantConverter] Error:", e);
                        throw new OO.ui.Error(e);
                    }
                })()).promise(), this);
            }
            else if (action === "back") {
                this.actions.setMode("config");
                this.stackLayout.setItem(this.configPanel);
                this.updateSize();
            }
            else if (action === "submit") {
                return new OO.ui.Process($.when((async () => {
                    try {
                        await this.saveChanges();
                        this.close({ action: action });
                        mw.notify("保存成功!", {
                            title: wgULS("自动繁简转换工具", "自動繁簡轉換工具"),
                            type: "success",
                            tag: "lr-aivc",
                        });
                        setTimeout(() => location.reload(), 730);
                    }
                    catch (e) {
                        console.error("[VariantConverter] Error:", e);
                        throw new OO.ui.Error(e);
                    }
                })()).promise(), this);
            }
            return super.getActionProcess(action);
        }
        addVariant(variant, text) {
            this.textInputs[variant] = new OO.ui.MultilineTextInputWidget({
                value: text,
                autosize: true,
            });
            const field = new OO.ui.FieldLayout(this.textInputs[variant], {
                label: variant,
                align: "top",
            });
            this.textInputs[variant].connect(this, { resize: "updateSize" });
            this.confirmPanel.$element.append(field.$element);
            if (window?.InPageEdit?.quickDiff) {
                this.confirmPanel.$element.append(new OO.ui.FieldLayout(new OO.ui.Widget({
                    content: [
                        new OO.ui.HorizontalLayout({
                            items: this.config.dependentInv[variant].map((v) => new OO.ui.ButtonWidget({
                                label: `${wgULS("对比", "對比")}${v === "(main)" ? wgULS("主页面", "主頁面") : v}`,
                            }).on("click", () => window.InPageEdit.quickDiff({
                                fromtitle: variantPage(v),
                                totext: this.textInputs[variant].getValue(),
                                pageName: variantPage(v),
                                isPreview: true,
                            }))),
                        }),
                    ],
                })).$element);
            }
        }
        async getVariants(original) {
            this.confirmPanel.$element.append(`<p>${wgULS("请确认以下转换是否正确", "請確認以下轉換是否正確")}:</p>`);
            if (!window.OpenCC && this.config.useOpenCC) {
                await libCachedCode.injectCachedCode("https://npm.elemecdn.com/opencc-js@latest", "script");
            }
            const { replaced, mappings } = escapeWikitext(original);
            for (const variant of this.config.main) {
                if (variant === "(main)") {
                    continue;
                }
                const text = `{{NoteTA|${this.config.noteTAStr}}}<pre id="converted">-{}-${replaced}</pre>`;
                const parsed = $($.parseHTML((await zhAPI.post({
                    action: "parse",
                    assertuser: username,
                    text,
                    contentmodel: "wikitext",
                    prop: "text",
                    uselang: variant,
                    disablelimitreport: true,
                    pst: true,
                })).parse.text["*"]));
                let converted = parsed.find("#converted").text();
                if (this.config.useOpenCC) {
                    const occMappings = [];
                    converted = converted.replace(REGEXP.noOCC, (_, content) => `<!--noOCC-->${occMappings.push(content) - 1}<!--/noOCC-->`);
                    const occVariant = variant.replace("hans", "cn").replace(/zh-(?:han)?/, "").replace("tw", "twp");
                    const converter = OpenCC.Converter({ from: occVariant, to: occVariant });
                    converted = converter(converted);
                    converted = converted.replace(REGEXP.noOCC, (_, index) => `<!--noOCC-->${occMappings[index]}<!--/noOCC-->`);
                }
                const final = this.config.manualAction[variant]?.(converted) || converted;
                const restored = restoreWikitext(final, mappings);
                this.addVariant(variant, restored);
            }
        }
        async saveChanges() {
            console.log("[VariantConverter] Saved changes", await Promise.allSettled(this.config.main.map((variant) => {
                const text = this.textInputs[variant].getValue();
                return api.postWithToken("csrf", {
                    action: "edit",
                    assertuser: username,
                    title: variantPage(variant),
                    text,
                    summary: `自动转换自[[${pagename}]]`,
                    tags: "VariantConverter|Automation tool",
                    watchlist: this.config.watchlist,
                });
            }).concat(Object.entries(this.config.dependent).map(([variant, parent]) => {
                const text = this.textInputs[parent].getValue();
                return api.postWithToken("csrf", {
                    action: "edit",
                    assertuser: username,
                    title: variantPage(variant),
                    text,
                    summary: `自动转换自[[${pagename}]](同步${parent})`,
                    tags: "VariantConverter|Automation tool",
                    watchlist: this.config.watchlist,
                });
            }))));
        }
    }
    _a = AIVCWindow;
    AIVCWindow.static = {
        ...Reflect.get(_b, "static", _a),
        tagName: "div",
        name: "lr-aivc",
        title: wgULS("自动繁简转换工具", "自動繁簡轉換工具"),
        actions: [
            {
                action: "cancel",
                label: "取消",
                flags: ["safe", "close", "destructive"],
                modes: "config",
            },
            {
                action: "continue",
                label: wgULS("继续", "繼續"),
                flags: ["primary", "progressive"],
                modes: "config",
            },
            {
                action: "back",
                label: "返回",
                flags: ["safe", "back"],
                modes: "confirm",
            },
            {
                action: "submit",
                label: wgULS("确认", "確認"),
                flags: ["primary", "progressive"],
                modes: "confirm",
            },
        ],
    };
    const $body = $(document.body);
    const windowManager = new OO.ui.WindowManager();
    $body.append(windowManager.$element);
    const aivcDialog = new AIVCWindow({
        size: "large",
        data: {
            config: lrAivc,
            prepopContent,
        },
    });
    windowManager.addWindows([aivcDialog]);
    $(mw.util.addPortletLink("p-cactions", "#", wgULS("自动繁简转换", "自動繁簡轉換"), "ca-VariantConverter", wgULS("自动同步界面消息的繁简版本", "自動同步介面消息的繁簡版本"))).on("click", (e) => {
        e.preventDefault();
        $("#mw-notification-area").appendTo($body);
        windowManager.openWindow(aivcDialog);
    });
})()); 

/* </pre> */