From c5e887e4d4b8e2e282d04c6840e41bd71cc97332 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9C=E6=97=AD=E4=B9=8B?= <12930972+jiang-xuzhi@user.noreply.gitee.com> Date: Tue, 8 Aug 2023 14:32:12 +0800 Subject: [PATCH 1/4] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=B9=B0=E5=8D=95?= =?UTF-8?q?=E4=BB=B6-HBPO=E5=A4=9A=E4=B8=AA=E9=A1=B5=E9=9D=A2=EF=BC=8C?= =?UTF-8?q?=E5=BA=93=E5=AD=98=E8=B0=83=E6=95=B4=E8=A1=A8=E7=95=8C=E9=9D=A2?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AD=97=E6=AE=B5=EF=BC=8C=E5=B0=86businessT?= =?UTF-8?q?yped=E4=BF=AE=E6=94=B9=EF=BC=8C=E4=BF=AE=E6=94=B9=E5=AD=97?= =?UTF-8?q?=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../wwwroot/components/list/index.js | 9 +- .../wwwroot/models/businessType.js | 13 + .../wwwroot/models/inventory/adjust.js | 200 +++++ .../wwwroot/models/inventory/backup.js | 6 +- .../wwwroot/models/inventory/balance.js | 2 +- .../wwwroot/models/inventory/inventory.js | 23 +- .../wwwroot/models/inventory/log.js | 92 ++- .../wwwroot/models/inventory/vmi.js | 60 +- .../models/invoice/invoice_map_group.js | 6 +- .../jis-bbac/input/bbac_sa_detail_service.js | 49 +- .../models/jis-bbac/input/bbac_sa_service.js | 54 +- .../settlement/bbac_can_sa_detail_service.js | 18 +- .../jis-hbpo/input/hbpo_sa_detail_service.js | 48 +- .../models/jis-hbpo/input/hbpo_sa_service.js | 62 +- .../settlement/hbpo_can_sa_detail_service.js | 18 +- .../wwwroot/models/job-service.js | 4 +- .../models/pub_can_sa_detail_service.js | 16 +- .../wwwroot/router/business.js | 716 ++++++++++++++---- .../contrast/bj_pub_sa_detail_jobservice.js | 12 +- .../bj/input/bj_pub_sa_detail_service.js | 2 +- .../views/bj/input/bj_pub_sa_service.js | 2 +- .../bj/input/bj_pub_se_detail_service.js | 2 +- .../contrast/in_pub_sa_detail_jobservice.js | 12 +- .../in/input/in_pub_sa_detail_service.js | 2 +- .../views/in/input/in_pub_sa_service.js | 2 +- .../in/input/in_pub_se_detail_service.js | 2 +- .../wwwroot/views/inventory/adjust.js | 15 + .../views/invoice/invoice_map_group.js | 61 +- .../bbac_jit_pub_sa_detail_jobservice.js | 12 +- .../hbpo_jit_pub_sa_detail_jobservice.js | 12 +- .../input/bbac_jit_pub_sa_detail_service.js | 2 +- .../jit/input/bbac_jit_pub_sa_service.js | 2 +- .../input/bbac_jit_pub_se_detail_service.js | 2 +- .../input/hbpo_jit_pub_sa_detail_service.js | 2 +- .../jit/input/hbpo_jit_pub_sa_service.js | 2 +- .../input/hbpo_jit_pub_se_detail_service.js | 2 +- .../contrast/md_pub_sa_detail_jobservice.js | 24 + .../md/input/md_pub_sa_detail_service.js | 16 + .../views/md/input/md_pub_sa_service.js | 16 + .../md/input/md_pub_se_detail_service.js | 16 + .../md/settlement/md_pub_ba_detail_service.js | 15 + .../views/md/settlement/md_pub_ba_service.js | 15 + .../md_pub_can_sa_detail_service.js | 15 + .../md/settlement/md_pub_can_sa_service.js | 15 + .../md/settlement/md_pub_not_sa_service.js | 15 + .../md/settlement/md_pub_pd_detail_service.js | 15 + .../views/md/settlement/md_pub_pd_service.js | 15 + 47 files changed, 1292 insertions(+), 429 deletions(-) create mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/businessType.js create mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/adjust.js create mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/inventory/adjust.js create mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/contrast/md_pub_sa_detail_jobservice.js create mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/input/md_pub_sa_detail_service.js create mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/input/md_pub_sa_service.js create mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/input/md_pub_se_detail_service.js create mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_ba_detail_service.js create mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_ba_service.js create mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_can_sa_detail_service.js create mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_can_sa_service.js create mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_not_sa_service.js create mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_pd_detail_service.js create mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_pd_service.js diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/components/list/index.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/components/list/index.js index 4d54071d..ad0dcd04 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/components/list/index.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/components/list/index.js @@ -836,10 +836,11 @@ export default { } function isNotJit() { return ( - route.meta.businessType !== 3 || - route.meta.businessType !== 4 || - route.meta.businessType !== 7 || - route.meta.businessType !== 8 + route.meta.businessType !== "ZhiGongJianBBAC" || + route.meta.businessType !== "ZhiGongJianHBPO" || + route.meta.businessType !== "BeiJian" || + route.meta.businessType !== "YinDuJian" || + route.meta.businessType !== "MaiDanJianHBPO" ); } onMounted(async () => { diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/businessType.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/businessType.js new file mode 100644 index 00000000..d42f18ee --- /dev/null +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/businessType.js @@ -0,0 +1,13 @@ +const options = [ + { value: 0, label: "未定义" }, + { value: 1, label: "JisBBAC" }, + { value: 2, label: "JisHBPO" }, + { value: 3, label: "直供件BBAC" }, + { value: 4, label: "直供件HBPO" }, + { value: 5, label: "买单件BBAC" }, + { value: 6, label: "买单件HBPO" }, + { value: 7, label: "备件" }, + { value: 8, label: "印度件" }, +]; +const businessType = { title: "业务类型", type: "string", input: "select", options }; +export default businessType; \ No newline at end of file diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/adjust.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/adjust.js new file mode 100644 index 00000000..01d5910d --- /dev/null +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/adjust.js @@ -0,0 +1,200 @@ +import { billType, codeType, changedType, subBillType } from "./inventory.js"; + +const schema = { + title: "库存事务日志", + type: "object", + properties: { + changedNumber: { + title: "变动单号", + type: "string", + }, + changedTime: { + title: "变动时间", + type: "string", + input: "dateTime", + }, + changedType, + changedBy: { + title: "变动人", + type: "string", + }, + partCode: { + title: "调整LU零件号", + type: "string", + }, + customerPartCode: { + title: "调整客户零件号", + type: "string", + }, + orderNum: { + title: "EDI原始订单号", + type: "string", + }, + billType, + subBillType, + reMark: { + title: "备注", + type: "string", + }, + vinCode: { + title: "调整生产码", + type: "string", + }, + codeType, + qty: { + title: "调整生产码", + type: "number", + }, + billTime: { + title: "发运日期", + type: "string", + }, + billNum: { + title: "WMS发运单号", + type: "string", + }, + deliverTime: { + title: "订单日期", + type: "string", + input: "datetime", + }, + erpToLoc: { + title: "ERP库位", + type: "string", + }, + }, +}; + +const baseUrl = "settleaccount/vmi"; +const queryUrl = `${baseUrl}/log`; +const detailsUrl = `${baseUrl}/get/%s`; +const createUrl = `${baseUrl}/create`; +const updateUrl = `${baseUrl}/update/%s`; +const deleteUrl = `${baseUrl}/delete-list`; +const importUrl = `${baseUrl}/code-setting-upload-excel-import`; +const exportUrl = `${baseUrl}/export`; +const queryMethod = "POST"; +const detailsMethod = "POST"; +const createMethod = "POST"; +const updateMethod = "POST"; +const deleteMethod = "POST"; +const importMethod = "POST"; +const exportMethod = "POST"; + +export default function () { + return { + query: { + url: queryUrl, + method: queryMethod, + hasFilter: true, + schema: { + title: "通用代码", + type: "object", + properties: { + filters: { + title: "项目", + type: "array", + hidden: true, + items: { + type: "object", + properties: { + logic: { + type: "int", + }, + column: { + type: "string", + }, + action: { + type: "int", + }, + value: { + type: "string", + }, + }, + }, + default: [ + { + logic: "and", + column: "erpToLoc", + action: "like", + value: null, + readOnly: true, + }, + { + logic: "and", + column: "createdDate", + action: "like", + value: null, + readOnly: true, + }, + { + logic: "and", + column: "lu", + action: "like", + value: null, + readOnly: true, + }, + { + logic: "and", + column: "tmpe4", + action: "like", + value: null, + readOnly: true, + }, + { + logic: "and", + column: "vinCode", + action: "like", + value: null, + readOnly: true, + }, + { + logic: "and", + column: "codeType", + action: "like", + value: null, + readOnly: true, + }, + { + logic: "and", + column: "proType", + action: "like", + value: null, + readOnly: true, + }, + ], + }, + skipCount: { + hidden: true, + default: 0, + }, + maxResultCount: { + hidden: true, + default: 10, + }, + sorting: { + hidden: true, + }, + }, + }, + }, + table: { + schema: schema, + }, + edit: { + detailsUrl, + createUrl, + updateUrl, + deleteUrl, + importUrl, + exportUrl, + detailsMethod, + createMethod, + updateMethod, + deleteMethod, + importMethod, + exportMethod, + schema: schema, + }, + }; +} diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/backup.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/backup.js index 07e27b50..e0b82612 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/backup.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/backup.js @@ -10,6 +10,7 @@ const updateUrl = `${baseUrl}/update/%s`; const deleteUrl = `${baseUrl}/delete-list`; const importUrl = `${baseUrl}/code-setting-upload-excel-import`; const exportUrl = `${baseUrl}/backup-export`; +const invokeUrl = "settleaccount/vmi/invoke"; const queryMethod = "POST"; const detailsMethod = "POST"; const createMethod = "POST"; @@ -17,6 +18,7 @@ const updateMethod = "POST"; const deleteMethod = "POST"; const importMethod = "POST"; const exportMethod = "POST"; +const invokeMethod = "POST"; export default function () { return { @@ -92,7 +94,7 @@ export default function () { }, { logic: "and", - column: "proType", + column: "billType", action: "like", value: null, readOnly: true, @@ -123,12 +125,14 @@ export default function () { deleteUrl, importUrl, exportUrl, + invokeUrl, detailsMethod, createMethod, updateMethod, deleteMethod, importMethod, exportMethod, + invokeMethod, schema: schema, }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/balance.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/balance.js index 55a1df18..7cb02e44 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/balance.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/balance.js @@ -80,7 +80,7 @@ export default function () { }, { logic: "and", - column: "proType", + column: "billType", action: "like", value: null, readOnly: true, diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/inventory.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/inventory.js index 10feea32..edc500a9 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/inventory.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/inventory.js @@ -16,7 +16,26 @@ const options2 = [ { value: "08", label: "后左轮眉" }, { value: "09", label: "后右轮眉" }, ]; -const proType = { title: "发货类型", type: "number", input: "select", options: options1 }; +const options3 = [ + { value: 0, label: "无" }, + { value: 1, label: "保险杠BBAC" }, + { value: 2, label: "保险杠HBPO" }, + { value: 3, label: "买单件保险杠BBAC" }, + { value: 4, label: "买单件保险杠HBPO" }, + { value: 5, label: "买单件小件BBAC" }, + { value: 6, label: "买单件小件HBPO" }, + { value: 7, label: "小件BBAC" }, + { value: 8, label: "小件HBPO" }, + { value: 9, label: "JIT直供件BBAC" }, + { value: 10, label: "JIT直供件HBPO" }, +]; +const options4 = [ + { value: "In", label: "入库" }, + { value: "Out", label: "出库" }, +]; +const billType = { title: "发货类型", type: "number", input: "select", options: options1 }; const codeType = { title: "生产码类型", type: "string", input: "select", options: options2 }; +const subBillType = { title: "发货子类型", type: "number", input: "select", options: options3 }; +const changedType = { title: "变动类型", type: "string", input: "select", options: options4 }; -export { proType, codeType }; +export { billType, codeType, subBillType, changedType }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/log.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/log.js index b692765b..55bc5f3e 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/log.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/log.js @@ -1,4 +1,4 @@ -import { proType, codeType } from "./inventory.js"; +import { billType, codeType, changedType, subBillType } from "./inventory.js"; //变动单据号、发生时间、生产码类型、、订单号、库位、变动数、EDI顺序号、备注、变动类型(In、Out标识)、发货类型(JIS\JIT\买单件\备件等)、 //实扣LU零件号、实扣客户零件号、结算LU零件号、结算客户零件号、实扣生产码、结算生产码 @@ -7,38 +7,94 @@ const schema = { title: "库存事务日志", type: "object", properties: { - orderNumber: { + changedNumber: { title: "变动单号", type: "string", }, - createdDate: { - title: "发生时间", + changedTime: { + title: "变动时间", type: "string", + input: "dateTime", }, - codeType, - tmpe4: { - title: "订单号", + changedType, + changedBy: { + title: "变动人", type: "string", }, - erpToLoc: { - title: "库位", + partCode: { + title: "实扣厂内零件号", type: "string", }, - count: { - title: "变动数", - type: "number", + partCode2: { + title: "结算厂内零件号", + type: "string", + }, + customerPartCode: { + title: "结算客户零件号", + type: "string", }, - changedType: { - title: "变动类型", + realCode: { + title: "WMS实发生产码", type: "string", }, - proType, vinCode: { - title: "生产码", + title: "EDI订单生产码", + type: "string", + }, + settlementVinCode: { + title: "结算生产码", + type: "string", + }, + codeType: { + title: "生产码类型", + type: "string", + }, + billType, + subBillType, + qty: { + title: "数量", + type: "number", + }, + billTime: { + title: "发运日期", + type: "string", + input: "datetime", + }, + deliverTime: { + title: "订单日期", + type: "string", + input: "datetime", + }, + seq: { + title: "EDI顺序号", + type: "string", + }, + orderNum: { + title: "客户订单号", + type: "string", + }, + uniqueCode: { + title: "塑件唯一码", + type: "string", + }, + matchNumber: { + title: "EDI总成号", + type: "string", + }, + pjsNum: { + title: "PJIS生产顺序号", + type: "string", + }, + isReplenished: { + title: "是否补货", + type: "boolean", + }, + erpToLoc: { + title: "ERP库位", type: "string", }, - lu: { - title: "LU零件号", + configcode: { + title: "配置码", type: "string", }, }, diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/vmi.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/vmi.js index 88d6c4e7..676754e2 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/vmi.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/inventory/vmi.js @@ -1,4 +1,4 @@ -import { proType, codeType } from "./inventory.js"; +import { billType, codeType, subBillType } from "./inventory.js"; export default function () { return { @@ -10,10 +10,6 @@ export default function () { // hidden: true, // showForList: false, // }, - erpToLoc: { - title: "ERP库位", - type: "string", - }, lu: { title: "LU零件号", type: "string", @@ -27,47 +23,30 @@ export default function () { type: "string", }, codeType, - proType, - // codeType: { - // title: "生产码类型", - // type: "string", - // input: "select", - // options: [ - // { value: "01", label: "前保" }, - // { value: "02", label: "后保" }, - // { value: "03", label: "门槛" }, - // ], - // }, - // proType: { - // title: "发货类型", - // type: "string", - // input: "select", - // options: [ - // { value: "JIS", label: "JIS" }, - // { value: "JIT", label: "JIT" }, - // { value: "买单件", label: "买单件" }, - // { value: "备件", label: "备件" }, - // ], - // }, + billType, qty: { title: "数量", type: "string", }, - shippingDate: { + billTime: { title: "发运日期", type: "string", - input: "date", + input: "datetime", }, - creationTime: { + deliverTime: { title: "订单日期", type: "string", - input: "date", + input: "datetime", + }, + erpToLoc: { + title: "ERP库位", + type: "string", }, - seqNumber: { + seq: { title: "EDI顺序号", type: "string", }, - tmpe4: { + orderNum: { title: "客户订单号", type: "string", }, @@ -83,10 +62,23 @@ export default function () { title: "PJIS生产顺序号", type: "string", }, - desc: { + reMark: { title: "备注", type: "string", }, + configcode: { + title: "配置码", + type: "string", + }, + factory: { + title: "工厂", + type: "string", + }, + subBillType, + realCode: { + title: "WMS实发生产码", + type: "string", + }, }, }; } diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/invoice/invoice_map_group.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/invoice/invoice_map_group.js index fb73d173..5a91b60f 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/invoice/invoice_map_group.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/invoice/invoice_map_group.js @@ -40,13 +40,11 @@ const exportUrl = "settleaccount/invoice_service/export"; const rejectUrl = "settleaccount/invoice_service/reject"; const passedUrl = "settleaccount/invoice_service/approval-passed"; const sync_qadUrl = "settleaccount/invoice_service/sync_qad"; -const importJsonUrl = "settleaccount/vmi/excel-to-json"; const queryMethod = "POST"; const exportMethod = "POST"; const rejectMethod = "POST"; const passedMethod = "POST"; const sync_qadMethod = "POST"; -const importJsonMethod = "POST"; export default function () { return { @@ -111,12 +109,12 @@ export default function () { rejectUrl, passedUrl, sync_qadUrl, - importJsonUrl, + // importJsonUrl, exportMethod, rejectMethod, passedMethod, sync_qadMethod, - importJsonMethod, + // importJsonMethod, schema: schema, }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-bbac/input/bbac_sa_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-bbac/input/bbac_sa_detail_service.js index 139f6002..05d203ab 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-bbac/input/bbac_sa_detail_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-bbac/input/bbac_sa_detail_service.js @@ -2,39 +2,31 @@ const schema = { title: "JIS结算数据", type: "object", properties: { - project: { - title: "项目", + settleDate: { + title: "结算日期", type: "string", - readOnly: true, - showForList: true, - rules: [ - { - required: true, - }, - ], + input: "dateTime", }, - value: { - title: "值", + groupNum: { + title: "结算分组号", type: "string", - readOnly: true, - showForList: true, - rules: [ - { - required: true, - }, - ], }, - description: { - title: "描述", + deliveryDate: { + title: "到货日期", + type: "string", + input: "dateTime", + }, + lu: { + title: "客户零件号", + type: "string", + }, + qty: { + title: "结算数量", + type: "number", + }, + pn: { + title: "生产号", type: "string", - input: "textarea", - showForList: true, - rules: [ - { - required: true, - }, - { max: 60 }, - ], }, }, }; @@ -42,7 +34,6 @@ const schema = { const queryUrl = "settleaccount/bbac_sa_service/detail_query"; const queryMethod = "POST"; - export default function () { return { query: { diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-bbac/input/bbac_sa_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-bbac/input/bbac_sa_service.js index d66111b1..4fa76483 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-bbac/input/bbac_sa_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-bbac/input/bbac_sa_service.js @@ -1,58 +1,42 @@ import version from "../../version.js"; +import businessType from "../../businessType.js"; const schema = { title: "JIS结算数据", type: "object", properties: { version, - project: { - title: "项目", + billNum: { + title: "结算单据", type: "string", - readOnly: true, - showForList: true, - rules: [ - { - required: true, - }, - ], }, - value: { - title: "值", + dnBillNum: { + title: "出库单号", type: "string", - readOnly: true, - showForList: true, - rules: [ - { - required: true, - }, - ], }, - description: { - title: "描述", + state: { + title: "状态", + type: "string", + }, + recordCount: { + title: "明细记录行数", + type: "string", + }, + site: { + title: "工厂地点", type: "string", - input: "textarea", - showForList: true, - rules: [ - { - required: true, - }, - { max: 60 }, - ], }, + businessType, }, }; const baseUrl = "settleaccount/bbac_sa_service"; const queryUrl = "settleaccount/bbac_sa_service/get-list"; -const createUrl = "settleaccount/bbac_sa_service/create"; const deleteUrl = `${baseUrl}/delete-list`; -const importUrl = `${baseUrl}/code-setting-upload-excel-import`; -const exportUrl = `${baseUrl}/export`; +const importUrl = `${baseUrl}/import`; const queryMethod = "POST"; -const createMethod = "POST"; const deleteMethod = "POST"; const importMethod = "POST"; -const exportMethod = "POST"; export default function () { return { @@ -113,14 +97,10 @@ export default function () { schema: schema, }, edit: { - createUrl, deleteUrl, importUrl, - exportUrl, - createMethod, deleteMethod, importMethod, - exportMethod, schema: schema, }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-bbac/settlement/bbac_can_sa_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-bbac/settlement/bbac_can_sa_detail_service.js index df59ea5a..fdd619e1 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-bbac/settlement/bbac_can_sa_detail_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-bbac/settlement/bbac_can_sa_detail_service.js @@ -2,14 +2,14 @@ const schema = { title: "发票分组号明细", type: "object", properties: { - settleBillNum: { - title: "关联结算单号", - type: "int", - }, - site: { - title: "工厂地点", - type: "string", - }, + // settleBillNum: { + // title: "关联结算单号", + // type: "int", + // }, + // site: { + // title: "工厂地点", + // type: "string", + // }, version: { title: "期间", type: "string", @@ -46,7 +46,7 @@ const schema = { title: "结算数量", type: "decimal", }, - groupNumy: { + groupNum: { title: "结算分组号", type: "string", }, diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-hbpo/input/hbpo_sa_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-hbpo/input/hbpo_sa_detail_service.js index 1e9cd04b..30adaf80 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-hbpo/input/hbpo_sa_detail_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-hbpo/input/hbpo_sa_detail_service.js @@ -2,39 +2,31 @@ const schema = { title: "JIS结算数据", type: "object", properties: { - project: { - title: "项目", + settleDate: { + title: "结算日期", type: "string", - readOnly: true, - showForList: true, - rules: [ - { - required: true, - }, - ], + input: "dateTime", }, - value: { - title: "值", + groupNum: { + title: "结算分组号", type: "string", - readOnly: true, - showForList: true, - rules: [ - { - required: true, - }, - ], }, - description: { - title: "描述", + deliveryDate: { + title: "到货日期", + type: "string", + input: "dateTime", + }, + lu: { + title: "客户零件号", + type: "string", + }, + qty: { + title: "结算数量", + type: "number", + }, + pn: { + title: "生产号", type: "string", - input: "textarea", - showForList: true, - rules: [ - { - required: true, - }, - { max: 60 }, - ], }, }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-hbpo/input/hbpo_sa_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-hbpo/input/hbpo_sa_service.js index 89b4f191..a2023300 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-hbpo/input/hbpo_sa_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-hbpo/input/hbpo_sa_service.js @@ -1,62 +1,40 @@ import version from "../../version.js"; +import businessType from "../../businessType.js"; +import state from "../../state.js"; const schema = { title: "JIS结算数据", type: "object", properties: { version, - project: { - title: "项目", + billNum: { + title: "结算单据", type: "string", - readOnly: true, - showForList: true, - rules: [ - { - required: true, - }, - ], }, - value: { - title: "值", + dnBillNum: { + title: "出库单号", type: "string", - readOnly: true, - showForList: true, - rules: [ - { - required: true, - }, - ], }, - description: { - title: "描述", + state, + recordCount: { + title: "明细记录行数", + type: "string", + }, + site: { + title: "工厂地点", type: "string", - input: "textarea", - showForList: true, - rules: [ - { - required: true, - }, - { max: 60 }, - ], }, + businessType, }, }; const baseUrl = "settleaccount/hbpo_sa_service"; -const queryUrl = `${baseUrl}/get-list`; -const detailsUrl = `${baseUrl}/get/%s`; -const createUrl = `${baseUrl}/create`; -const updateUrl = `${baseUrl}/update/%s`; +const queryUrl = "settleaccount/hbpo_sa_service/get-list"; const deleteUrl = `${baseUrl}/delete-list`; -const importUrl = `${baseUrl}/code-setting-upload-excel-import`; -const exportUrl = `${baseUrl}/export`; +const importUrl = `${baseUrl}/import`; const queryMethod = "POST"; -const detailsMethod = "POST"; -const createMethod = "POST"; -const updateMethod = "POST"; const deleteMethod = "POST"; const importMethod = "POST"; -const exportMethod = "POST"; export default function () { return { @@ -117,18 +95,10 @@ export default function () { schema: schema, }, edit: { - detailsUrl, - createUrl, - updateUrl, deleteUrl, importUrl, - exportUrl, - detailsMethod, - createMethod, - updateMethod, deleteMethod, importMethod, - exportMethod, schema: schema, }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-hbpo/settlement/hbpo_can_sa_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-hbpo/settlement/hbpo_can_sa_detail_service.js index f35e23c3..e5318eb4 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-hbpo/settlement/hbpo_can_sa_detail_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/jis-hbpo/settlement/hbpo_can_sa_detail_service.js @@ -2,14 +2,14 @@ const schema = { title: "可结算单明细", type: "object", properties: { - settleBillNum: { - title: "关联结算单号", - type: "int", - }, - site: { - title: "工厂地点", - type: "string", - }, + // settleBillNum: { + // title: "关联结算单号", + // type: "int", + // }, + // site: { + // title: "工厂地点", + // type: "string", + // }, version: { title: "期间", type: "string", @@ -46,7 +46,7 @@ const schema = { title: "结算数量", type: "decimal", }, - groupNumy: { + groupNum: { title: "结算分组号", type: "string", }, diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/job-service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/job-service.js index 26c0708f..f4777357 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/job-service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/job-service.js @@ -42,11 +42,11 @@ const schema = { const queryUrl = "settleaccount/Job/list"; const deleteUrl = "settleaccount/Job/delete"; -const exportUrl = "settleaccount/pub_sa_detail_service/export"; +const exportUrl = "settleaccount/getblobfile/download/%s"; const compareUrl = "settleaccount/pub_sa_detail_service/pub-sa-se-compare"; const queryMethod = "POST"; const deleteMethod = "POST"; -const exportMethod = "POST"; +const exportMethod = "GET"; const compareMethod = "POST"; export default function () { diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/pub_can_sa_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/pub_can_sa_detail_service.js index 50f174b6..0ceb12e6 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/pub_can_sa_detail_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/models/pub_can_sa_detail_service.js @@ -6,14 +6,14 @@ const schema = { type: "object", properties: { state, - settleBillNum: { - title: "关联结算单号", - type: "string", - }, - site: { - title: "工厂地点", - type: "string", - }, + // settleBillNum: { + // title: "关联结算单号", + // type: "string", + // }, + // site: { + // title: "工厂地点", + // type: "string", + // }, businessType: { title: "业务分类", type: "EnumBusinessType", diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/router/business.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/router/business.js index 122a5406..acfe90da 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/router/business.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/router/business.js @@ -61,24 +61,6 @@ export default [ isTop: true, }, }, - { - path: "delete", - meta: { - type: "button", - title: "删除", - icon: "file", - isTop: true, - }, - }, - { - path: "import", - meta: { - type: "button", - title: "导入", - icon: "file", - isTop: true, - }, - }, { path: "export", meta: { @@ -218,6 +200,8 @@ export default [ type: "button", title: "下载", icon: "file", + pattern: "paged", + isHidden: true, }, }, ], @@ -272,6 +256,8 @@ export default [ type: "button", title: "下载", icon: "file", + pattern: "paged", + isHidden: true, }, }, ], @@ -586,24 +572,6 @@ export default [ isTop: true, }, }, - { - path: "delete", - meta: { - type: "button", - title: "删除", - icon: "file", - isTop: true, - }, - }, - { - path: "import", - meta: { - type: "button", - title: "导入", - icon: "file", - isTop: true, - }, - }, { path: "export", meta: { @@ -743,6 +711,8 @@ export default [ type: "button", title: "下载", icon: "file", + pattern: "paged", + isHidden: true, }, }, ], @@ -797,6 +767,8 @@ export default [ type: "button", title: "下载", icon: "file", + pattern: "paged", + isHidden: true, }, }, ], @@ -1211,7 +1183,7 @@ export default [ path: "hbpo_jit_pub_sa_detail_service", meta: { type: "page", - title: "4", + title: "HBPO结算数据明细", icon: "file", isHidden: true, }, @@ -1291,7 +1263,7 @@ export default [ type: "page", title: "BBAC发运与结算比对", icon: "file", - businessType: 3, + businessType: "ZhiGongJianBBAC", }, children: [ { @@ -1336,6 +1308,8 @@ export default [ type: "button", title: "下载", icon: "file", + pattern: "paged", + isHidden: true, }, }, ], @@ -1346,7 +1320,7 @@ export default [ type: "page", title: "HBPO发运与结算比对", icon: "file", - businessType: 4, + businessType: "ZhiGongJianHBPO", }, children: [ { @@ -1391,6 +1365,8 @@ export default [ type: "button", title: "下载", icon: "file", + pattern: "paged", + isHidden: true, }, }, ], @@ -1694,24 +1670,6 @@ export default [ isTop: true, }, }, - { - path: "delete", - meta: { - type: "button", - title: "删除", - icon: "file", - isTop: true, - }, - }, - { - path: "import", - meta: { - type: "button", - title: "导入", - icon: "file", - isTop: true, - }, - }, { path: "export", meta: { @@ -1778,7 +1736,7 @@ export default [ type: "page", title: "发运与结算比对", icon: "file", - businessType: 7, + businessType: "BeiJian", }, children: [ { @@ -1823,6 +1781,8 @@ export default [ type: "button", title: "下载", icon: "file", + pattern: "paged", + isHidden: true, }, }, ], @@ -2126,24 +2086,6 @@ export default [ isTop: true, }, }, - { - path: "delete", - meta: { - type: "button", - title: "删除", - icon: "file", - isTop: true, - }, - }, - { - path: "import", - meta: { - type: "button", - title: "导入", - icon: "file", - isTop: true, - }, - }, { path: "export", meta: { @@ -2210,7 +2152,7 @@ export default [ type: "page", title: "发运与结算比对", icon: "file", - businessType: 8, + businessType: "YinDuJian", }, children: [ { @@ -2255,6 +2197,8 @@ export default [ type: "button", title: "下载", icon: "file", + pattern: "paged", + isHidden: true, }, }, ], @@ -2487,114 +2431,541 @@ export default [ }, ], }, + //不知道自主起的名字 { - path: "invoice", + path: "md", meta: { type: "group", - title: "财务审核", + title: "买单件HBPO", icon: "folder", }, children: [ { - path: "invoice_map_group", + path: "input", meta: { - type: "page", - title: "财务审核", + type: "group", + title: "数据输入", icon: "file", }, children: [ { - path: "query", - meta: { - type: "button", - title: "查询", - icon: "file", - isTop: true, - }, - }, - { - path: "reject", - meta: { - type: "button", - title: "退回", - icon: "file", - isTop: true, - }, - }, - { - path: "importInvocie", - meta: { - type: "button", - title: "导入发票号", - icon: "file", - isTop: true, - pattern: "paged", - }, - }, - { - path: "passed ", + path: "md_pub_sa_service", meta: { - type: "button", - title: "审核通过", + type: "page", + title: "结算数据", icon: "file", - isTop: true, - pattern: "paged", }, + children: [ + { + path: "query", + meta: { + type: "button", + title: "查询", + icon: "file", + isTop: true, + }, + }, + { + path: "import", + meta: { + type: "button", + title: "导入", + icon: "file", + isTop: true, + }, + }, + { + path: "delete", + meta: { + type: "button", + title: "删除", + icon: "file", + isTop: true, + }, + }, + { + path: "export", + meta: { + type: "button", + title: "导出", + icon: "file", + isTop: true, + pattern: "paged", + }, + }, + ], }, { - path: "sync_qad ", + path: "md_pub_sa_detail_service", meta: { - type: "button", - title: "同步寄售库至QAD", + type: "page", + title: "结算数据明细", icon: "file", - isTop: true, - pattern: "paged", + isHidden: true, }, + children: [ + { + path: "query", + meta: { + type: "button", + title: "查询", + icon: "file", + isTop: true, + }, + }, + { + path: "export", + meta: { + type: "button", + title: "导出", + icon: "file", + isTop: true, + pattern: "paged", + }, + }, + ], }, - ], - }, - { - path: "invoice_wait_detail", - meta: { - type: "page", - title: "待开票明细", - icon: "file", - isHidden: true, - }, - children: [ { - path: "query", + path: "md_pub_se_detail_service", meta: { - type: "button", - title: "查询", + type: "page", + title: "发运数据", icon: "file", - isTop: true, }, + children: [ + { + path: "query", + meta: { + type: "button", + title: "查询", + icon: "file", + isTop: true, + }, + }, + { + path: "export", + meta: { + type: "button", + title: "导出", + icon: "file", + isTop: true, + pattern: "paged", + }, + }, + { + path: "synchronous", + meta: { + type: "button", + title: "手动同步", + icon: "file", + isTop: true, + }, + }, + ], }, ], }, { - path: "invoice_grp", + path: "contrast", meta: { - type: "page", - title: "发票分组", + type: "group", + title: "数据对比", icon: "file", - isHidden: true, }, children: [ { - path: "query", + path: "md_pub_sa_detail_jobservice", meta: { - type: "button", - title: "查询", + type: "page", + title: "发运与结算比对", icon: "file", - isTop: true, + businessType: "MaiDanJianHBPO", }, - }, - ], - }, - { - path: "invoice_not_settle", + children: [ + { + path: "query", + meta: { + type: "button", + title: "查询", + icon: "file", + isTop: true, + }, + }, + { + path: "compare", + meta: { + type: "button", + title: "生成对比", + icon: "file", + isTop: true, + }, + }, + { + path: "delete", + meta: { + type: "button", + title: "删除", + icon: "file", + isTop: true, + }, + }, + { + path: "update-data", + meta: { + type: "button", + title: "更新结算数据状态", + icon: "file", + isTop: true, + }, + }, + { + path: "export", + meta: { + type: "button", + title: "下载", + icon: "file", + pattern: "paged", + isHidden: true, + }, + }, + ], + }, + ], + }, + { + path: "settlement", + meta: { + type: "group", + title: "结算开票", + icon: "folder", + }, + children: [ + { + path: "md_pub_can_sa_service", + meta: { + type: "page", + title: "可结算单", + icon: "file", + }, + children: [ + { + path: "query", + meta: { + type: "button", + title: "查询", + icon: "file", + isTop: true, + }, + }, + { + path: "export", + meta: { + type: "button", + title: "导出", + icon: "file", + isTop: true, + pattern: "paged", + }, + }, + { + path: "generateInvoice", + meta: { + type: "button", + title: "生成发票数据", + icon: "file", + isTop: true, + pattern: "paged", + }, + }, + ], + }, + { + path: "md_pub_not_sa_service", + meta: { + type: "page", + title: "不可结算单", + icon: "file", + }, + children: [ + { + path: "query", + meta: { + type: "button", + title: "查询", + icon: "file", + isTop: true, + }, + }, + { + path: "export", + meta: { + type: "button", + title: "导出", + icon: "file", + isTop: true, + pattern: "paged", + }, + }, + { + path: "generateSettlementOrder", + meta: { + type: "button", + title: "生成可结算单", + icon: "file", + isTop: true, + pattern: "paged", + }, + }, + ], + }, + { + path: "md_pub_ba_service", + meta: { + type: "page", + title: "商务审批", + icon: "file", + }, + children: [ + { + path: "query", + meta: { + type: "button", + title: "查询", + icon: "file", + isTop: true, + }, + }, + { + path: "reject", + meta: { + type: "button", + title: "退回", + icon: "file", + isTop: true, + }, + }, + { + path: "export", + meta: { + type: "button", + title: "导出", + icon: "file", + isTop: true, + pattern: "paged", + }, + }, + { + path: "received ", + meta: { + type: "button", + title: "客户已收票", + icon: "file", + isTop: true, + pattern: "paged", + }, + }, + ], + }, + { + path: "md_pub_ba_detail_service", + meta: { + type: "page", + title: "商务审批明细", + icon: "file", + isHidden: true, + }, + children: [ + { + path: "query", + meta: { + type: "button", + title: "查询", + icon: "file", + isTop: true, + }, + }, + ], + }, + { + path: "md_pub_pd_service", + meta: { + type: "page", + title: "寄售库库存扣减审批", + icon: "file", + }, + children: [ + { + path: "query", + meta: { + type: "button", + title: "查询", + icon: "file", + isTop: true, + }, + }, + { + path: "reject", + meta: { + type: "button", + title: "退回", + icon: "file", + isTop: true, + }, + }, + { + path: "export", + meta: { + type: "button", + title: "导出", + icon: "file", + isTop: true, + pattern: "paged", + }, + }, + { + path: "approvalPassed ", + meta: { + type: "button", + title: "审核通过", + icon: "file", + isTop: true, + pattern: "paged", + }, + }, + ], + }, + { + path: "md_pub_pd_detail_service", + meta: { + type: "page", + title: "寄售库库存扣减审批明细", + icon: "file", + isHidden: true, + }, + children: [ + { + path: "query", + meta: { + type: "button", + title: "查询", + icon: "file", + isTop: true, + }, + }, + ], + }, + ], + }, + ], + }, + { + path: "invoice", + meta: { + type: "group", + title: "财务审核", + icon: "folder", + }, + children: [ + { + path: "invoice_map_group", + meta: { + type: "page", + title: "财务审核", + icon: "file", + }, + children: [ + { + path: "query", + meta: { + type: "button", + title: "查询", + icon: "file", + isTop: true, + }, + }, + { + path: "reject", + meta: { + type: "button", + title: "退回", + icon: "file", + isTop: true, + }, + }, + { + path: "importInvocie", + meta: { + type: "button", + title: "导入发票号", + icon: "file", + isTop: true, + pattern: "paged", + }, + }, + { + path: "passed ", + meta: { + type: "button", + title: "审核通过", + icon: "file", + isTop: true, + pattern: "paged", + }, + }, + { + path: "sync_qad ", + meta: { + type: "button", + title: "同步寄售库至QAD", + icon: "file", + isTop: true, + pattern: "paged", + }, + }, + ], + }, + { + path: "invoice_wait_detail", + meta: { + type: "page", + title: "待开票明细", + icon: "file", + isHidden: true, + }, + children: [ + { + path: "query", + meta: { + type: "button", + title: "查询", + icon: "file", + isTop: true, + }, + }, + ], + }, + { + path: "invoice_grp", + meta: { + type: "page", + title: "发票分组", + icon: "file", + isHidden: true, + }, + children: [ + { + path: "query", + meta: { + type: "button", + title: "查询", + icon: "file", + isTop: true, + }, + }, + ], + }, + { + path: "invoice_not_settle", meta: { type: "page", title: "不可开票明细清单", @@ -2781,13 +3152,58 @@ export default [ }, }, { - path: "backups", + path: "invoke", meta: { type: "button", title: "手动备份", icon: "file", isTop: true, - pattern: "paged", + }, + }, + ], + }, + { + path: "adjust", + meta: { + type: "page", + title: "技术库存调整表", + icon: "file", + }, + children: [ + { + path: "query", + meta: { + type: "button", + title: "查询", + icon: "file", + isTop: true, + }, + }, + { + path: "create", + meta: { + type: "button", + title: "新建", + icon: "file", + isTop: true, + }, + }, + { + path: "update", + meta: { + type: "button", + title: "编辑", + icon: "file", + isTop: true, + }, + }, + { + path: "import", + meta: { + type: "button", + title: "导入", + icon: "file", + isTop: true, }, }, ], diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/contrast/bj_pub_sa_detail_jobservice.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/contrast/bj_pub_sa_detail_jobservice.js index b24eca11..973c4b5a 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/contrast/bj_pub_sa_detail_jobservice.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/contrast/bj_pub_sa_detail_jobservice.js @@ -1,10 +1,11 @@ import AppList from "../../../components/list/index.js"; import html from "html"; import useConfig from "../../../models/job-service.js"; +import { ref, onMounted, onUnmounted } from "vue"; export default { components: { AppList }, - template: html``, + template: html``, setup() { const config = useConfig(); config.query.schema.title = "发运与结算"; @@ -12,7 +13,12 @@ export default { console.log(item.path, item, rows); }; config.query.schema.properties.name.default = "备件结算与发运数据对比"; - config.query.schema.properties.businessType.default = 7; - return { config, onCommand }; + config.query.schema.properties.businessType.default = "BeiJian"; + const appListRef = ref(null); + onMounted(() => + PubSub.subscribe(config.query.schema.properties.businessType.default, async () => await appListRef.value.load()) + ); + onUnmounted(() => PubSub.unsubscribe(config.query.schema.properties.businessType.default)); + return { config, onCommand, appListRef }; }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/input/bj_pub_sa_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/input/bj_pub_sa_detail_service.js index e9427598..578b28ff 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/input/bj_pub_sa_detail_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/input/bj_pub_sa_detail_service.js @@ -9,7 +9,7 @@ export default { const onCommand = async (item, rows) => { console.log(item.path, item, rows); }; - config.query.schema.properties.businessType.default=7; + config.query.schema.properties.businessType.default="BeiJian"; return { config, onCommand }; }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/input/bj_pub_sa_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/input/bj_pub_sa_service.js index 9ce95bce..d47e2c02 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/input/bj_pub_sa_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/input/bj_pub_sa_service.js @@ -10,7 +10,7 @@ export default { const onCommand = async (item, rows) => { console.log(item.path, item, rows); }; - config.query.schema.properties.businessType.default=7; + config.query.schema.properties.businessType.default="BeiJian"; return { config, onCommand }; }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/input/bj_pub_se_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/input/bj_pub_se_detail_service.js index ca74b249..e3413577 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/input/bj_pub_se_detail_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/bj/input/bj_pub_se_detail_service.js @@ -10,7 +10,7 @@ export default { const onCommand = async (item, rows) => { console.log(item.path, item, rows); }; - config.query.schema.properties.businessType.default = 7; + config.query.schema.properties.businessType.default = "BeiJian"; return { config, onCommand }; }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/contrast/in_pub_sa_detail_jobservice.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/contrast/in_pub_sa_detail_jobservice.js index 25046753..83d64074 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/contrast/in_pub_sa_detail_jobservice.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/contrast/in_pub_sa_detail_jobservice.js @@ -1,18 +1,24 @@ import AppList from "../../../components/list/index.js"; import html from "html"; import useConfig from "../../../models/job-service.js"; +import { ref, onMounted, onUnmounted } from "vue"; export default { components: { AppList }, - template: html``, + template: html``, setup() { const config = useConfig(); config.query.schema.title = "发运与结算"; const onCommand = async (item, rows) => { console.log(item.path, item, rows); }; - config.query.schema.properties.businessType.default = 8; + config.query.schema.properties.businessType.default = "YinDuJian"; config.query.schema.properties.name.default = "印度件结算与发运数据对比"; - return { config, onCommand }; + const appListRef = ref(null); + onMounted(() => + PubSub.subscribe(config.query.schema.properties.name.default, async () => await appListRef.value.load()) + ); + onUnmounted(() => PubSub.unsubscribe(config.query.schema.properties.businessType.default)); + return { config, onCommand, appListRef }; }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/input/in_pub_sa_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/input/in_pub_sa_detail_service.js index 121ca2a7..b4ef7753 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/input/in_pub_sa_detail_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/input/in_pub_sa_detail_service.js @@ -10,7 +10,7 @@ export default { const onCommand = async (item, rows) => { console.log(item.path, item, rows); }; - config.query.schema.properties.businessType.default = 8; + config.query.schema.properties.businessType.default = "YinDuJian"; return { config, onCommand }; }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/input/in_pub_sa_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/input/in_pub_sa_service.js index af7274b3..0358ab5a 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/input/in_pub_sa_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/input/in_pub_sa_service.js @@ -10,7 +10,7 @@ export default { const onCommand = async (item, rows) => { console.log(item.path, item, rows); }; - config.query.schema.properties.businessType.default = 8; + config.query.schema.properties.businessType.default = "YinDuJian"; return { config, onCommand }; }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/input/in_pub_se_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/input/in_pub_se_detail_service.js index 57ad119d..6bed30cd 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/input/in_pub_se_detail_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/in/input/in_pub_se_detail_service.js @@ -10,7 +10,7 @@ export default { const onCommand = async (item, rows) => { console.log(item.path, item, rows); }; - config.query.schema.properties.businessType.default = 8; + config.query.schema.properties.businessType.default = "YinDuJian"; return { config, onCommand }; }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/inventory/adjust.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/inventory/adjust.js new file mode 100644 index 00000000..96da44ab --- /dev/null +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/inventory/adjust.js @@ -0,0 +1,15 @@ +import AppList from "../../../components/list/index.js"; +import html from "html"; +import useConfig from "../../../models/inventory/adjust.js"; + +export default { + components: { AppList }, + template: html``, + setup() { + const config = useConfig(); + const onCommand = async (item, rows) => { + console.log(item.path, item, rows); + }; + return { config, onCommand }; + }, +}; \ No newline at end of file diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/invoice/invoice_map_group.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/invoice/invoice_map_group.js index 71b57c21..ba203786 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/invoice/invoice_map_group.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/invoice/invoice_map_group.js @@ -5,6 +5,7 @@ import useConfig from "../../../models/invoice/invoice_map_group.js"; import request from "../../../request/index.js"; import AppTable from "../../components/table/index.js"; import { ElMessageBox } from "element-plus"; +import { post } from "../../../request/index.js"; export default { components: { AppList, AppTable }, @@ -54,9 +55,9 @@ export default { - - - + + + @@ -101,19 +102,21 @@ export default { - - - - - 确定 - +
+ + + + + +
+ 确定
下一页 @@ -133,10 +136,23 @@ export default { } `, setup() { + const fileList = ref([]); + // const load = async () => {}; + // const editFormModel = ref(null); + // const editFormMode = ref(null); + // const defaultImportModel = config.import?.schema ? schemaToModel(config.import.schema) : {}; + // const importModel = ref(defaultImportModel); const openImportHandler = async () => { - const data = {}; - const response = await request("settleaccount/vmi/excel-to-json", data, { method: "POST" }); - console.log(response.data); + const url = "settleaccount/vmi/excel-to-json"; + const method = "POST"; + const formData = new FormData(); + if (config.query.schema.properties.businessType?.default) { + formData.append("businessType", config.query.schema.properties.businessType.default); + } + for (let i = 0; i < fileList.value.length; i++) { + formData.append(`files`, fileList.value[i].raw); + } + await post(url, formData, method); }; const formInline = reactive({ oldInvBillNum: "", @@ -149,6 +165,7 @@ export default { groupNum: "", }); //create + const invoiceValue = ref([]); const submitForm = () => { const newFormInline = { ...formInline }; invoiceValue.value.push(newFormInline); @@ -159,12 +176,10 @@ export default { }; //delete const selectedRows = ref([]); - const invoiceValue = ref([]); - const deleteRow = () => { + const deleteRow = async () => { const indexes = selectedRows.value.map((row) => invoiceValue.value.indexOf(row)); - indexes.sort((a, b) => b - a); indexes.forEach((index) => { - invoiceValue.value.splice(index, 1); + invoiceValue.value.splice(index, 10000000000); }); selectedRows.value = []; }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/contrast/bbac_jit_pub_sa_detail_jobservice.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/contrast/bbac_jit_pub_sa_detail_jobservice.js index 80af731e..45c57f8e 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/contrast/bbac_jit_pub_sa_detail_jobservice.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/contrast/bbac_jit_pub_sa_detail_jobservice.js @@ -1,18 +1,24 @@ import AppList from "../../../components/list/index.js"; import html from "html"; import useConfig from "../../../models/job-service.js"; +import { ref, onMounted, onUnmounted } from "vue"; export default { components: { AppList }, - template: html``, + template: html``, setup() { const config = useConfig(); config.query.schema.title = "发运与结算"; const onCommand = async (item, rows) => { console.log(item.path, item, rows); }; - config.query.schema.properties.businessType.default = 3; + config.query.schema.properties.businessType.default = "ZhiGongJianBBAC"; config.query.schema.properties.name.default = "直供件BBAC结算与发运数据对比"; - return { config, onCommand }; + const appListRef = ref(null); + onMounted(() => + PubSub.subscribe(config.query.schema.properties.name.default, async () => await appListRef.value.load()) + ); + onUnmounted(() => PubSub.unsubscribe(config.query.schema.properties.businessType.default)); + return { config, onCommand, appListRef }; }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/contrast/hbpo_jit_pub_sa_detail_jobservice.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/contrast/hbpo_jit_pub_sa_detail_jobservice.js index 88d0f9a4..c761e842 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/contrast/hbpo_jit_pub_sa_detail_jobservice.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/contrast/hbpo_jit_pub_sa_detail_jobservice.js @@ -1,18 +1,24 @@ import AppList from "../../../components/list/index.js"; import html from "html"; import useConfig from "../../../models/job-service.js"; +import { ref, onMounted, onUnmounted } from "vue"; export default { components: { AppList }, - template: html``, + template: html``, setup() { const config = useConfig(); config.query.schema.title = "发运与结算"; const onCommand = async (item, rows) => { console.log(item.path, item, rows); }; - config.query.schema.properties.businessType.default = 4; + config.query.schema.properties.businessType.default = "ZhiGongJianHBPO"; config.query.schema.properties.name.default = "直供件HBPO结算与发运数据对比"; - return { config, onCommand }; + const appListRef = ref(null); + onMounted(() => + PubSub.subscribe(config.query.schema.properties.name.default, async () => await appListRef.value.load()) + ); + onUnmounted(() => PubSub.unsubscribe(config.query.schema.properties.businessType.default)); + return { config, onCommand, appListRef }; }, }; \ No newline at end of file diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/bbac_jit_pub_sa_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/bbac_jit_pub_sa_detail_service.js index 00d64c05..29ea6e38 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/bbac_jit_pub_sa_detail_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/bbac_jit_pub_sa_detail_service.js @@ -10,7 +10,7 @@ export default { const onCommand = async (item, rows) => { console.log(item.path, item, rows); }; - config.query.schema.properties.businessType.default = 3; + config.query.schema.properties.businessType.default = "ZhiGongJianBBAC"; return { config, onCommand }; }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/bbac_jit_pub_sa_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/bbac_jit_pub_sa_service.js index ba56665f..edc6cf7a 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/bbac_jit_pub_sa_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/bbac_jit_pub_sa_service.js @@ -10,7 +10,7 @@ export default { const onCommand = async (item, rows) => { console.log(item.path, item, rows); }; - config.query.schema.properties.businessType.default = 3; + config.query.schema.properties.businessType.default = "ZhiGongJianBBAC"; return { config, onCommand }; }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/bbac_jit_pub_se_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/bbac_jit_pub_se_detail_service.js index 7b03245d..72b36273 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/bbac_jit_pub_se_detail_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/bbac_jit_pub_se_detail_service.js @@ -10,7 +10,7 @@ export default { const onCommand = async (item, rows) => { console.log(item.path, item, rows); }; - config.query.schema.properties.businessType.default = 3; + config.query.schema.properties.businessType.default = "ZhiGongJianBBAC"; return { config, onCommand }; }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/hbpo_jit_pub_sa_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/hbpo_jit_pub_sa_detail_service.js index f58aeccd..d44b7336 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/hbpo_jit_pub_sa_detail_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/hbpo_jit_pub_sa_detail_service.js @@ -10,7 +10,7 @@ export default { const onCommand = async (item, rows) => { console.log(item.path, item, rows); }; - config.query.schema.properties.businessType.default = 4; + config.query.schema.properties.businessType.default = "ZhiGongJianHBPO"; return { config, onCommand }; }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/hbpo_jit_pub_sa_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/hbpo_jit_pub_sa_service.js index 669374cb..426ecbdf 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/hbpo_jit_pub_sa_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/hbpo_jit_pub_sa_service.js @@ -10,7 +10,7 @@ export default { const onCommand = async (item, rows) => { console.log(item.path, item, rows); }; - config.query.schema.properties.businessType.default = 4; + config.query.schema.properties.businessType.default = "ZhiGongJianHBPO"; return { config, onCommand }; }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/hbpo_jit_pub_se_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/hbpo_jit_pub_se_detail_service.js index 9dbf9d93..70f00a7c 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/hbpo_jit_pub_se_detail_service.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/jit/input/hbpo_jit_pub_se_detail_service.js @@ -10,7 +10,7 @@ export default { const onCommand = async (item, rows) => { console.log(item.path, item, rows); }; - config.query.schema.properties.businessType.default = 4; + config.query.schema.properties.businessType.default = "ZhiGongJianHBPO"; return { config, onCommand }; }, }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/contrast/md_pub_sa_detail_jobservice.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/contrast/md_pub_sa_detail_jobservice.js new file mode 100644 index 00000000..be428ba6 --- /dev/null +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/contrast/md_pub_sa_detail_jobservice.js @@ -0,0 +1,24 @@ +import AppList from "../../../components/list/index.js"; +import html from "html"; +import useConfig from "../../../models/job-service.js"; +import { ref, onMounted, onUnmounted } from "vue"; + +export default { + components: { AppList }, + template: html``, + setup() { + const config = useConfig(); + config.query.schema.title = "发运与结算"; + const onCommand = async (item, rows) => { + console.log(item.path, item, rows); + }; + config.query.schema.properties.businessType.default = "MaiDanJianHBPO"; + // config.query.schema.properties.name.default = "直供件BBAC结算与发运数据对比"; + const appListRef = ref(null); + onMounted(() => + PubSub.subscribe(config.query.schema.properties.name.default, async () => await appListRef.value.load()) + ); + onUnmounted(() => PubSub.unsubscribe(config.query.schema.properties.businessType.default)); + return { config, onCommand, appListRef }; + }, +}; \ No newline at end of file diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/input/md_pub_sa_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/input/md_pub_sa_detail_service.js new file mode 100644 index 00000000..4abac8a5 --- /dev/null +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/input/md_pub_sa_detail_service.js @@ -0,0 +1,16 @@ +import AppList from "../../../components/list/index.js"; +import html from "html"; +import useConfig from "../../../models/pub_sa_detail_service.js"; + +export default { + components: { AppList }, + template: html``, + setup() { + const config = useConfig(); + const onCommand = async (item, rows) => { + console.log(item.path, item, rows); + }; + config.query.schema.properties.businessType.default = "MaiDanJianHBPO"; + return { config, onCommand }; + }, +}; \ No newline at end of file diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/input/md_pub_sa_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/input/md_pub_sa_service.js new file mode 100644 index 00000000..f7e199b1 --- /dev/null +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/input/md_pub_sa_service.js @@ -0,0 +1,16 @@ +import AppList from "../../../components/list/index.js"; +import html from "html"; +import useConfig from "../../../models/pub_sa_service.js"; + +export default { + components: { AppList }, + template: html``, + setup() { + const config = useConfig(); + const onCommand = async (item, rows) => { + console.log(item.path, item, rows); + }; + config.query.schema.properties.businessType.default = "MaiDanJianHBPO"; + return { config, onCommand }; + }, +}; \ No newline at end of file diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/input/md_pub_se_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/input/md_pub_se_detail_service.js new file mode 100644 index 00000000..13f6260c --- /dev/null +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/input/md_pub_se_detail_service.js @@ -0,0 +1,16 @@ +import AppList from "../../../components/list/index.js"; +import html from "html"; +import useConfig from "../../../models/pub_se_detail_service.js"; + +export default { + components: { AppList }, + template: html``, + setup() { + const config = useConfig(); + const onCommand = async (item, rows) => { + console.log(item.path, item, rows); + }; + config.query.schema.properties.businessType.default = "MaiDanJianHBPO"; + return { config, onCommand }; + }, +}; \ No newline at end of file diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_ba_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_ba_detail_service.js new file mode 100644 index 00000000..330af3df --- /dev/null +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_ba_detail_service.js @@ -0,0 +1,15 @@ +import AppList from "../../../components/list/index.js"; +import html from "html"; +import useConfig from "../../../models/pub_ba_detail_service"; + +export default { + components: { AppList }, + template: html``, + setup() { + const config = useConfig(); + const onCommand = async (item, rows) => { + console.log(item.path, item, rows); + }; + return { config, onCommand }; + }, +}; \ No newline at end of file diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_ba_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_ba_service.js new file mode 100644 index 00000000..a17bee4c --- /dev/null +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_ba_service.js @@ -0,0 +1,15 @@ +import AppList from "../../../components/list/index.js"; +import html from "html"; +import useConfig from "../../../models/pub_ba_service.js"; + +export default { + components: { AppList }, + template: html``, + setup() { + const config = useConfig(); + const onCommand = async (item, rows) => { + console.log(item.path, item, rows); + }; + return { config, onCommand }; + }, +}; \ No newline at end of file diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_can_sa_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_can_sa_detail_service.js new file mode 100644 index 00000000..8ba02935 --- /dev/null +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_can_sa_detail_service.js @@ -0,0 +1,15 @@ +import AppList from "../../../components/list/index.js"; +import html from "html"; +import useConfig from "../../../models/pub_can_sa_detail_service.js"; + +export default { + components: { AppList }, + template: html``, + setup() { + const config = useConfig(); + const onCommand = async (item, rows) => { + console.log(item.path, item, rows); + }; + return { config, onCommand }; + }, +}; \ No newline at end of file diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_can_sa_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_can_sa_service.js new file mode 100644 index 00000000..0afe7c1b --- /dev/null +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_can_sa_service.js @@ -0,0 +1,15 @@ +import AppList from "../../../components/list/index.js"; +import html from "html"; +import useConfig from "../../../models/pub_can_sa_service.js"; + +export default { + components: { AppList }, + template: html``, + setup() { + const config = useConfig(); + const onCommand = async (item, rows) => { + console.log(item.path, item, rows); + }; + return { config, onCommand }; + }, +}; \ No newline at end of file diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_not_sa_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_not_sa_service.js new file mode 100644 index 00000000..5fcd3054 --- /dev/null +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_not_sa_service.js @@ -0,0 +1,15 @@ +import AppList from "../../../components/list/index.js"; +import html from "html"; +import useConfig from "../../../models/pub_not_sa_service.js"; + +export default { + components: { AppList }, + template: html``, + setup() { + const config = useConfig(); + const onCommand = async (item, rows) => { + console.log(item.path, item, rows); + }; + return { config, onCommand }; + }, +}; \ No newline at end of file diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_pd_detail_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_pd_detail_service.js new file mode 100644 index 00000000..59e1fd72 --- /dev/null +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_pd_detail_service.js @@ -0,0 +1,15 @@ +import AppList from "../../../components/list/index.js"; +import html from "html"; +import useConfig from "../../../models/pub_pd_detail_service.js"; + +export default { + components: { AppList }, + template: html``, + setup() { + const config = useConfig(); + const onCommand = async (item, rows) => { + console.log(item.path, item, rows); + }; + return { config, onCommand }; + }, +}; \ No newline at end of file diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_pd_service.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_pd_service.js new file mode 100644 index 00000000..72204c7c --- /dev/null +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/views/md/settlement/md_pub_pd_service.js @@ -0,0 +1,15 @@ +import AppList from "../../../components/list/index.js"; +import html from "html"; +import useConfig from "../../../models/pub_pd_service.js"; + +export default { + components: { AppList }, + template: html``, + setup() { + const config = useConfig(); + const onCommand = async (item, rows) => { + console.log(item.path, item, rows); + }; + return { config, onCommand }; + }, +}; \ No newline at end of file From 14120ffd49ecd6bab5b652cb5cbebfc05c63b220 Mon Sep 17 00:00:00 2001 From: wanggang <76527413@qq.com> Date: Tue, 8 Aug 2023 15:59:49 +0800 Subject: [PATCH 2/4] =?UTF-8?q?=E5=AF=BC=E5=85=A5=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E4=B8=8B=E8=BD=BD=E6=A0=A1=E9=AA=8C=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../wwwroot/api/user.js | 17 +- .../wwwroot/assets/demo/index.html | 8 +- .../assets/demo/lib/pinia.esm-browser.js | 1987 -- .../assets/demo/lib/vue-router.esm-browser.js | 3613 ---- .../assets/demo/lib/vue.esm-browser.js | 15377 ---------------- .../wwwroot/assets/demo/pages/component.html | 6 +- .../wwwroot/components/form/form-input.js | 115 +- .../wwwroot/components/form/form-item.js | 2 +- .../wwwroot/components/list/index.js | 125 +- .../wwwroot/index.html | 4 +- .../tb_re-parts-relationship_service.js | 3 - .../wwwroot/request/index.js | 14 +- .../wwwroot/utils/validation.js | 4 +- .../wwwroot/views/login.js | 6 +- .../Entities/BQ/VmiAppService.cs | 19 +- 15 files changed, 190 insertions(+), 21110 deletions(-) delete mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/lib/pinia.esm-browser.js delete mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/lib/vue-router.esm-browser.js delete mode 100644 code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/lib/vue.esm-browser.js diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/api/user.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/api/user.js index d245865a..238fd097 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/api/user.js +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/api/user.js @@ -22,21 +22,6 @@ const isLogin = async () => { return false; }; -const login = async (data) => { - const url = "connect-token"; - const appStore = useAppStore(); - const result = await post(url, data, { headers: { "Content-Type": "application/x-www-form-urlencoded" } }, true); - if (!result.errors) { - appStore.token = result.data.access_token; - setRefreshToken(result.data.refresh_token); - appStore.user = await getUser(); - await refreshRouter(); - const redirect = router.currentRoute.value.query?.redirect ?? "/"; - router.push(redirect); - } - return result; -}; - const logout = () => { const appStore = useAppStore(); appStore.token = null; @@ -87,4 +72,4 @@ const removeRefreshToken = () => { connection.stop(); }; -export { isLogin, login, logout, getAccessToken, setAccessToken, setRefreshToken, getUser, hasPermission }; +export { isLogin, logout, getAccessToken, setAccessToken, setRefreshToken, getUser, hasPermission }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/index.html b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/index.html index 570d0e89..618352a4 100644 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/index.html +++ b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/index.html @@ -46,9 +46,9 @@ @@ -82,4 +82,4 @@ - \ No newline at end of file + diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/lib/pinia.esm-browser.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/lib/pinia.esm-browser.js deleted file mode 100644 index 589100e6..00000000 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/lib/pinia.esm-browser.js +++ /dev/null @@ -1,1987 +0,0 @@ -/*! - * pinia v2.1.1 - * (c) 2023 Eduardo San Martin Morote - * @license MIT - */ -import { hasInjectionContext, inject, toRaw, watch, unref, markRaw, effectScope, ref, isVue2, isRef, isReactive, set, getCurrentScope, onScopeDispose, getCurrentInstance, reactive, toRef, del, nextTick, computed, toRefs } from 'vue-demi'; -import { setupDevtoolsPlugin } from '@vue/devtools-api'; - -/** - * setActivePinia must be called to handle SSR at the top of functions like - * `fetch`, `setup`, `serverPrefetch` and others - */ -let activePinia; -/** - * Sets or unsets the active pinia. Used in SSR and internally when calling - * actions and getters - * - * @param pinia - Pinia instance - */ -// @ts-expect-error: cannot constrain the type of the return -const setActivePinia = (pinia) => (activePinia = pinia); -/** - * Get the currently active pinia if there is any. - */ -const getActivePinia = () => (hasInjectionContext() && inject(piniaSymbol)) || activePinia; -const piniaSymbol = (Symbol('pinia') ); - -function isPlainObject( -// eslint-disable-next-line @typescript-eslint/no-explicit-any -o) { - return (o && - typeof o === 'object' && - Object.prototype.toString.call(o) === '[object Object]' && - typeof o.toJSON !== 'function'); -} -// type DeepReadonly = { readonly [P in keyof T]: DeepReadonly } -// TODO: can we change these to numbers? -/** - * Possible types for SubscriptionCallback - */ -var MutationType; -(function (MutationType) { - /** - * Direct mutation of the state: - * - * - `store.name = 'new name'` - * - `store.$state.name = 'new name'` - * - `store.list.push('new item')` - */ - MutationType["direct"] = "direct"; - /** - * Mutated the state with `$patch` and an object - * - * - `store.$patch({ name: 'newName' })` - */ - MutationType["patchObject"] = "patch object"; - /** - * Mutated the state with `$patch` and a function - * - * - `store.$patch(state => state.name = 'newName')` - */ - MutationType["patchFunction"] = "patch function"; - // maybe reset? for $state = {} and $reset -})(MutationType || (MutationType = {})); - -const IS_CLIENT = typeof window !== 'undefined'; -/** - * Should we add the devtools plugins. - * - only if dev mode or forced through the prod devtools flag - * - not in test - * - only if window exists (could change in the future) - */ -const USE_DEVTOOLS = IS_CLIENT; - -/* - * FileSaver.js A saveAs() FileSaver implementation. - * - * Originally by Eli Grey, adapted as an ESM module by Eduardo San Martin - * Morote. - * - * License : MIT - */ -// The one and only way of getting global scope in all environments -// https://stackoverflow.com/q/3277182/1008999 -const _global = /*#__PURE__*/ (() => typeof window === 'object' && window.window === window - ? window - : typeof self === 'object' && self.self === self - ? self - : typeof global === 'object' && global.global === global - ? global - : typeof globalThis === 'object' - ? globalThis - : { HTMLElement: null })(); -function bom(blob, { autoBom = false } = {}) { - // prepend BOM for UTF-8 XML and text/* types (including HTML) - // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF - if (autoBom && - /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) { - return new Blob([String.fromCharCode(0xfeff), blob], { type: blob.type }); - } - return blob; -} -function download(url, name, opts) { - const xhr = new XMLHttpRequest(); - xhr.open('GET', url); - xhr.responseType = 'blob'; - xhr.onload = function () { - saveAs(xhr.response, name, opts); - }; - xhr.onerror = function () { - console.error('could not download file'); - }; - xhr.send(); -} -function corsEnabled(url) { - const xhr = new XMLHttpRequest(); - // use sync to avoid popup blocker - xhr.open('HEAD', url, false); - try { - xhr.send(); - } - catch (e) { } - return xhr.status >= 200 && xhr.status <= 299; -} -// `a.click()` doesn't work for all browsers (#465) -function click(node) { - try { - node.dispatchEvent(new MouseEvent('click')); - } - catch (e) { - const evt = document.createEvent('MouseEvents'); - evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null); - node.dispatchEvent(evt); - } -} -const _navigator = - typeof navigator === 'object' ? navigator : { userAgent: '' }; -// Detect WebView inside a native macOS app by ruling out all browsers -// We just need to check for 'Safari' because all other browsers (besides Firefox) include that too -// https://www.whatismybrowser.com/guides/the-latest-user-agent/macos -const isMacOSWebView = /*#__PURE__*/ (() => /Macintosh/.test(_navigator.userAgent) && - /AppleWebKit/.test(_navigator.userAgent) && - !/Safari/.test(_navigator.userAgent))(); -const saveAs = !IS_CLIENT - ? () => { } // noop - : // Use download attribute first if possible (#193 Lumia mobile) unless this is a macOS WebView or mini program - typeof HTMLAnchorElement !== 'undefined' && - 'download' in HTMLAnchorElement.prototype && - !isMacOSWebView - ? downloadSaveAs - : // Use msSaveOrOpenBlob as a second approach - 'msSaveOrOpenBlob' in _navigator - ? msSaveAs - : // Fallback to using FileReader and a popup - fileSaverSaveAs; -function downloadSaveAs(blob, name = 'download', opts) { - const a = document.createElement('a'); - a.download = name; - a.rel = 'noopener'; // tabnabbing - // TODO: detect chrome extensions & packaged apps - // a.target = '_blank' - if (typeof blob === 'string') { - // Support regular links - a.href = blob; - if (a.origin !== location.origin) { - if (corsEnabled(a.href)) { - download(blob, name, opts); - } - else { - a.target = '_blank'; - click(a); - } - } - else { - click(a); - } - } - else { - // Support blobs - a.href = URL.createObjectURL(blob); - setTimeout(function () { - URL.revokeObjectURL(a.href); - }, 4e4); // 40s - setTimeout(function () { - click(a); - }, 0); - } -} -function msSaveAs(blob, name = 'download', opts) { - if (typeof blob === 'string') { - if (corsEnabled(blob)) { - download(blob, name, opts); - } - else { - const a = document.createElement('a'); - a.href = blob; - a.target = '_blank'; - setTimeout(function () { - click(a); - }); - } - } - else { - // @ts-ignore: works on windows - navigator.msSaveOrOpenBlob(bom(blob, opts), name); - } -} -function fileSaverSaveAs(blob, name, opts, popup) { - // Open a popup immediately do go around popup blocker - // Mostly only available on user interaction and the fileReader is async so... - popup = popup || open('', '_blank'); - if (popup) { - popup.document.title = popup.document.body.innerText = 'downloading...'; - } - if (typeof blob === 'string') - return download(blob, name, opts); - const force = blob.type === 'application/octet-stream'; - const isSafari = /constructor/i.test(String(_global.HTMLElement)) || 'safari' in _global; - const isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent); - if ((isChromeIOS || (force && isSafari) || isMacOSWebView) && - typeof FileReader !== 'undefined') { - // Safari doesn't allow downloading of blob URLs - const reader = new FileReader(); - reader.onloadend = function () { - let url = reader.result; - if (typeof url !== 'string') { - popup = null; - throw new Error('Wrong reader.result type'); - } - url = isChromeIOS - ? url - : url.replace(/^data:[^;]*;/, 'data:attachment/file;'); - if (popup) { - popup.location.href = url; - } - else { - location.assign(url); - } - popup = null; // reverse-tabnabbing #460 - }; - reader.readAsDataURL(blob); - } - else { - const url = URL.createObjectURL(blob); - if (popup) - popup.location.assign(url); - else - location.href = url; - popup = null; // reverse-tabnabbing #460 - setTimeout(function () { - URL.revokeObjectURL(url); - }, 4e4); // 40s - } -} - -/** - * Shows a toast or console.log - * - * @param message - message to log - * @param type - different color of the tooltip - */ -function toastMessage(message, type) { - const piniaMessage = '🍍 ' + message; - if (typeof __VUE_DEVTOOLS_TOAST__ === 'function') { - __VUE_DEVTOOLS_TOAST__(piniaMessage, type); - } - else if (type === 'error') { - console.error(piniaMessage); - } - else if (type === 'warn') { - console.warn(piniaMessage); - } - else { - console.log(piniaMessage); - } -} -function isPinia(o) { - return '_a' in o && 'install' in o; -} - -function checkClipboardAccess() { - if (!('clipboard' in navigator)) { - toastMessage(`Your browser doesn't support the Clipboard API`, 'error'); - return true; - } -} -function checkNotFocusedError(error) { - if (error instanceof Error && - error.message.toLowerCase().includes('document is not focused')) { - toastMessage('You need to activate the "Emulate a focused page" setting in the "Rendering" panel of devtools.', 'warn'); - return true; - } - return false; -} -async function actionGlobalCopyState(pinia) { - if (checkClipboardAccess()) - return; - try { - await navigator.clipboard.writeText(JSON.stringify(pinia.state.value)); - toastMessage('Global state copied to clipboard.'); - } - catch (error) { - if (checkNotFocusedError(error)) - return; - toastMessage(`Failed to serialize the state. Check the console for more details.`, 'error'); - console.error(error); - } -} -async function actionGlobalPasteState(pinia) { - if (checkClipboardAccess()) - return; - try { - pinia.state.value = JSON.parse(await navigator.clipboard.readText()); - toastMessage('Global state pasted from clipboard.'); - } - catch (error) { - if (checkNotFocusedError(error)) - return; - toastMessage(`Failed to deserialize the state from clipboard. Check the console for more details.`, 'error'); - console.error(error); - } -} -async function actionGlobalSaveState(pinia) { - try { - saveAs(new Blob([JSON.stringify(pinia.state.value)], { - type: 'text/plain;charset=utf-8', - }), 'pinia-state.json'); - } - catch (error) { - toastMessage(`Failed to export the state as JSON. Check the console for more details.`, 'error'); - console.error(error); - } -} -let fileInput; -function getFileOpener() { - if (!fileInput) { - fileInput = document.createElement('input'); - fileInput.type = 'file'; - fileInput.accept = '.json'; - } - function openFile() { - return new Promise((resolve, reject) => { - fileInput.onchange = async () => { - const files = fileInput.files; - if (!files) - return resolve(null); - const file = files.item(0); - if (!file) - return resolve(null); - return resolve({ text: await file.text(), file }); - }; - // @ts-ignore: TODO: changed from 4.3 to 4.4 - fileInput.oncancel = () => resolve(null); - fileInput.onerror = reject; - fileInput.click(); - }); - } - return openFile; -} -async function actionGlobalOpenStateFile(pinia) { - try { - const open = await getFileOpener(); - const result = await open(); - if (!result) - return; - const { text, file } = result; - pinia.state.value = JSON.parse(text); - toastMessage(`Global state imported from "${file.name}".`); - } - catch (error) { - toastMessage(`Failed to export the state as JSON. Check the console for more details.`, 'error'); - console.error(error); - } -} - -function formatDisplay(display) { - return { - _custom: { - display, - }, - }; -} -const PINIA_ROOT_LABEL = '🍍 Pinia (root)'; -const PINIA_ROOT_ID = '_root'; -function formatStoreForInspectorTree(store) { - return isPinia(store) - ? { - id: PINIA_ROOT_ID, - label: PINIA_ROOT_LABEL, - } - : { - id: store.$id, - label: store.$id, - }; -} -function formatStoreForInspectorState(store) { - if (isPinia(store)) { - const storeNames = Array.from(store._s.keys()); - const storeMap = store._s; - const state = { - state: storeNames.map((storeId) => ({ - editable: true, - key: storeId, - value: store.state.value[storeId], - })), - getters: storeNames - .filter((id) => storeMap.get(id)._getters) - .map((id) => { - const store = storeMap.get(id); - return { - editable: false, - key: id, - value: store._getters.reduce((getters, key) => { - getters[key] = store[key]; - return getters; - }, {}), - }; - }), - }; - return state; - } - const state = { - state: Object.keys(store.$state).map((key) => ({ - editable: true, - key, - value: store.$state[key], - })), - }; - // avoid adding empty getters - if (store._getters && store._getters.length) { - state.getters = store._getters.map((getterName) => ({ - editable: false, - key: getterName, - value: store[getterName], - })); - } - if (store._customProperties.size) { - state.customProperties = Array.from(store._customProperties).map((key) => ({ - editable: true, - key, - value: store[key], - })); - } - return state; -} -function formatEventData(events) { - if (!events) - return {}; - if (Array.isArray(events)) { - // TODO: handle add and delete for arrays and objects - return events.reduce((data, event) => { - data.keys.push(event.key); - data.operations.push(event.type); - data.oldValue[event.key] = event.oldValue; - data.newValue[event.key] = event.newValue; - return data; - }, { - oldValue: {}, - keys: [], - operations: [], - newValue: {}, - }); - } - else { - return { - operation: formatDisplay(events.type), - key: formatDisplay(events.key), - oldValue: events.oldValue, - newValue: events.newValue, - }; - } -} -function formatMutationType(type) { - switch (type) { - case MutationType.direct: - return 'mutation'; - case MutationType.patchFunction: - return '$patch'; - case MutationType.patchObject: - return '$patch'; - default: - return 'unknown'; - } -} - -// timeline can be paused when directly changing the state -let isTimelineActive = true; -const componentStateTypes = []; -const MUTATIONS_LAYER_ID = 'pinia:mutations'; -const INSPECTOR_ID = 'pinia'; -const { assign: assign$1 } = Object; -/** - * Gets the displayed name of a store in devtools - * - * @param id - id of the store - * @returns a formatted string - */ -const getStoreType = (id) => '🍍 ' + id; -/** - * Add the pinia plugin without any store. Allows displaying a Pinia plugin tab - * as soon as it is added to the application. - * - * @param app - Vue application - * @param pinia - pinia instance - */ -function registerPiniaDevtools(app, pinia) { - setupDevtoolsPlugin({ - id: 'dev.esm.pinia', - label: 'Pinia 🍍', - logo: 'https://pinia.vuejs.org/logo.svg', - packageName: 'pinia', - homepage: 'https://pinia.vuejs.org', - componentStateTypes, - app, - }, (api) => { - if (typeof api.now !== 'function') { - toastMessage('You seem to be using an outdated version of Vue Devtools. Are you still using the Beta release instead of the stable one? You can find the links at https://devtools.vuejs.org/guide/installation.html.'); - } - api.addTimelineLayer({ - id: MUTATIONS_LAYER_ID, - label: `Pinia 🍍`, - color: 0xe5df88, - }); - api.addInspector({ - id: INSPECTOR_ID, - label: 'Pinia 🍍', - icon: 'storage', - treeFilterPlaceholder: 'Search stores', - actions: [ - { - icon: 'content_copy', - action: () => { - actionGlobalCopyState(pinia); - }, - tooltip: 'Serialize and copy the state', - }, - { - icon: 'content_paste', - action: async () => { - await actionGlobalPasteState(pinia); - api.sendInspectorTree(INSPECTOR_ID); - api.sendInspectorState(INSPECTOR_ID); - }, - tooltip: 'Replace the state with the content of your clipboard', - }, - { - icon: 'save', - action: () => { - actionGlobalSaveState(pinia); - }, - tooltip: 'Save the state as a JSON file', - }, - { - icon: 'folder_open', - action: async () => { - await actionGlobalOpenStateFile(pinia); - api.sendInspectorTree(INSPECTOR_ID); - api.sendInspectorState(INSPECTOR_ID); - }, - tooltip: 'Import the state from a JSON file', - }, - ], - nodeActions: [ - { - icon: 'restore', - tooltip: 'Reset the state (with "$reset")', - action: (nodeId) => { - const store = pinia._s.get(nodeId); - if (!store) { - toastMessage(`Cannot reset "${nodeId}" store because it wasn't found.`, 'warn'); - } - else if (typeof store.$reset !== 'function') { - toastMessage(`Cannot reset "${nodeId}" store because it doesn't have a "$reset" method implemented.`, 'warn'); - } - else { - store.$reset(); - toastMessage(`Store "${nodeId}" reset.`); - } - }, - }, - ], - }); - api.on.inspectComponent((payload, ctx) => { - const proxy = (payload.componentInstance && - payload.componentInstance.proxy); - if (proxy && proxy._pStores) { - const piniaStores = payload.componentInstance.proxy._pStores; - Object.values(piniaStores).forEach((store) => { - payload.instanceData.state.push({ - type: getStoreType(store.$id), - key: 'state', - editable: true, - value: store._isOptionsAPI - ? { - _custom: { - value: toRaw(store.$state), - actions: [ - { - icon: 'restore', - tooltip: 'Reset the state of this store', - action: () => store.$reset(), - }, - ], - }, - } - : // NOTE: workaround to unwrap transferred refs - Object.keys(store.$state).reduce((state, key) => { - state[key] = store.$state[key]; - return state; - }, {}), - }); - if (store._getters && store._getters.length) { - payload.instanceData.state.push({ - type: getStoreType(store.$id), - key: 'getters', - editable: false, - value: store._getters.reduce((getters, key) => { - try { - getters[key] = store[key]; - } - catch (error) { - // @ts-expect-error: we just want to show it in devtools - getters[key] = error; - } - return getters; - }, {}), - }); - } - }); - } - }); - api.on.getInspectorTree((payload) => { - if (payload.app === app && payload.inspectorId === INSPECTOR_ID) { - let stores = [pinia]; - stores = stores.concat(Array.from(pinia._s.values())); - payload.rootNodes = (payload.filter - ? stores.filter((store) => '$id' in store - ? store.$id - .toLowerCase() - .includes(payload.filter.toLowerCase()) - : PINIA_ROOT_LABEL.toLowerCase().includes(payload.filter.toLowerCase())) - : stores).map(formatStoreForInspectorTree); - } - }); - api.on.getInspectorState((payload) => { - if (payload.app === app && payload.inspectorId === INSPECTOR_ID) { - const inspectedStore = payload.nodeId === PINIA_ROOT_ID - ? pinia - : pinia._s.get(payload.nodeId); - if (!inspectedStore) { - // this could be the selected store restored for a different project - // so it's better not to say anything here - return; - } - if (inspectedStore) { - payload.state = formatStoreForInspectorState(inspectedStore); - } - } - }); - api.on.editInspectorState((payload, ctx) => { - if (payload.app === app && payload.inspectorId === INSPECTOR_ID) { - const inspectedStore = payload.nodeId === PINIA_ROOT_ID - ? pinia - : pinia._s.get(payload.nodeId); - if (!inspectedStore) { - return toastMessage(`store "${payload.nodeId}" not found`, 'error'); - } - const { path } = payload; - if (!isPinia(inspectedStore)) { - // access only the state - if (path.length !== 1 || - !inspectedStore._customProperties.has(path[0]) || - path[0] in inspectedStore.$state) { - path.unshift('$state'); - } - } - else { - // Root access, we can omit the `.value` because the devtools API does it for us - path.unshift('state'); - } - isTimelineActive = false; - payload.set(inspectedStore, path, payload.state.value); - isTimelineActive = true; - } - }); - api.on.editComponentState((payload) => { - if (payload.type.startsWith('🍍')) { - const storeId = payload.type.replace(/^🍍\s*/, ''); - const store = pinia._s.get(storeId); - if (!store) { - return toastMessage(`store "${storeId}" not found`, 'error'); - } - const { path } = payload; - if (path[0] !== 'state') { - return toastMessage(`Invalid path for store "${storeId}":\n${path}\nOnly state can be modified.`); - } - // rewrite the first entry to be able to directly set the state as - // well as any other path - path[0] = '$state'; - isTimelineActive = false; - payload.set(store, path, payload.state.value); - isTimelineActive = true; - } - }); - }); -} -function addStoreToDevtools(app, store) { - if (!componentStateTypes.includes(getStoreType(store.$id))) { - componentStateTypes.push(getStoreType(store.$id)); - } - setupDevtoolsPlugin({ - id: 'dev.esm.pinia', - label: 'Pinia 🍍', - logo: 'https://pinia.vuejs.org/logo.svg', - packageName: 'pinia', - homepage: 'https://pinia.vuejs.org', - componentStateTypes, - app, - settings: { - logStoreChanges: { - label: 'Notify about new/deleted stores', - type: 'boolean', - defaultValue: true, - }, - // useEmojis: { - // label: 'Use emojis in messages ⚡️', - // type: 'boolean', - // defaultValue: true, - // }, - }, - }, (api) => { - // gracefully handle errors - const now = typeof api.now === 'function' ? api.now.bind(api) : Date.now; - store.$onAction(({ after, onError, name, args }) => { - const groupId = runningActionId++; - api.addTimelineEvent({ - layerId: MUTATIONS_LAYER_ID, - event: { - time: now(), - title: '🛫 ' + name, - subtitle: 'start', - data: { - store: formatDisplay(store.$id), - action: formatDisplay(name), - args, - }, - groupId, - }, - }); - after((result) => { - activeAction = undefined; - api.addTimelineEvent({ - layerId: MUTATIONS_LAYER_ID, - event: { - time: now(), - title: '🛬 ' + name, - subtitle: 'end', - data: { - store: formatDisplay(store.$id), - action: formatDisplay(name), - args, - result, - }, - groupId, - }, - }); - }); - onError((error) => { - activeAction = undefined; - api.addTimelineEvent({ - layerId: MUTATIONS_LAYER_ID, - event: { - time: now(), - logType: 'error', - title: '💥 ' + name, - subtitle: 'end', - data: { - store: formatDisplay(store.$id), - action: formatDisplay(name), - args, - error, - }, - groupId, - }, - }); - }); - }, true); - store._customProperties.forEach((name) => { - watch(() => unref(store[name]), (newValue, oldValue) => { - api.notifyComponentUpdate(); - api.sendInspectorState(INSPECTOR_ID); - if (isTimelineActive) { - api.addTimelineEvent({ - layerId: MUTATIONS_LAYER_ID, - event: { - time: now(), - title: 'Change', - subtitle: name, - data: { - newValue, - oldValue, - }, - groupId: activeAction, - }, - }); - } - }, { deep: true }); - }); - store.$subscribe(({ events, type }, state) => { - api.notifyComponentUpdate(); - api.sendInspectorState(INSPECTOR_ID); - if (!isTimelineActive) - return; - // rootStore.state[store.id] = state - const eventData = { - time: now(), - title: formatMutationType(type), - data: assign$1({ store: formatDisplay(store.$id) }, formatEventData(events)), - groupId: activeAction, - }; - // reset for the next mutation - activeAction = undefined; - if (type === MutationType.patchFunction) { - eventData.subtitle = '⤵️'; - } - else if (type === MutationType.patchObject) { - eventData.subtitle = '🧩'; - } - else if (events && !Array.isArray(events)) { - eventData.subtitle = events.type; - } - if (events) { - eventData.data['rawEvent(s)'] = { - _custom: { - display: 'DebuggerEvent', - type: 'object', - tooltip: 'raw DebuggerEvent[]', - value: events, - }, - }; - } - api.addTimelineEvent({ - layerId: MUTATIONS_LAYER_ID, - event: eventData, - }); - }, { detached: true, flush: 'sync' }); - const hotUpdate = store._hotUpdate; - store._hotUpdate = markRaw((newStore) => { - hotUpdate(newStore); - api.addTimelineEvent({ - layerId: MUTATIONS_LAYER_ID, - event: { - time: now(), - title: '🔥 ' + store.$id, - subtitle: 'HMR update', - data: { - store: formatDisplay(store.$id), - info: formatDisplay(`HMR update`), - }, - }, - }); - // update the devtools too - api.notifyComponentUpdate(); - api.sendInspectorTree(INSPECTOR_ID); - api.sendInspectorState(INSPECTOR_ID); - }); - const { $dispose } = store; - store.$dispose = () => { - $dispose(); - api.notifyComponentUpdate(); - api.sendInspectorTree(INSPECTOR_ID); - api.sendInspectorState(INSPECTOR_ID); - api.getSettings().logStoreChanges && - toastMessage(`Disposed "${store.$id}" store 🗑`); - }; - // trigger an update so it can display new registered stores - api.notifyComponentUpdate(); - api.sendInspectorTree(INSPECTOR_ID); - api.sendInspectorState(INSPECTOR_ID); - api.getSettings().logStoreChanges && - toastMessage(`"${store.$id}" store installed 🆕`); - }); -} -let runningActionId = 0; -let activeAction; -/** - * Patches a store to enable action grouping in devtools by wrapping the store with a Proxy that is passed as the - * context of all actions, allowing us to set `runningAction` on each access and effectively associating any state - * mutation to the action. - * - * @param store - store to patch - * @param actionNames - list of actionst to patch - */ -function patchActionForGrouping(store, actionNames) { - // original actions of the store as they are given by pinia. We are going to override them - const actions = actionNames.reduce((storeActions, actionName) => { - // use toRaw to avoid tracking #541 - storeActions[actionName] = toRaw(store)[actionName]; - return storeActions; - }, {}); - for (const actionName in actions) { - store[actionName] = function () { - // setActivePinia(store._p) - // the running action id is incremented in a before action hook - const _actionId = runningActionId; - const trackedStore = new Proxy(store, { - get(...args) { - activeAction = _actionId; - return Reflect.get(...args); - }, - set(...args) { - activeAction = _actionId; - return Reflect.set(...args); - }, - }); - return actions[actionName].apply(trackedStore, arguments); - }; - } -} -/** - * pinia.use(devtoolsPlugin) - */ -function devtoolsPlugin({ app, store, options }) { - // HMR module - if (store.$id.startsWith('__hot:')) { - return; - } - // detect option api vs setup api - if (options.state) { - store._isOptionsAPI = true; - } - // only wrap actions in option-defined stores as this technique relies on - // wrapping the context of the action with a proxy - if (typeof options.state === 'function') { - patchActionForGrouping( - // @ts-expect-error: can cast the store... - store, Object.keys(options.actions)); - const originalHotUpdate = store._hotUpdate; - // Upgrade the HMR to also update the new actions - toRaw(store)._hotUpdate = function (newStore) { - originalHotUpdate.apply(this, arguments); - patchActionForGrouping(store, Object.keys(newStore._hmrPayload.actions)); - }; - } - addStoreToDevtools(app, - // FIXME: is there a way to allow the assignment from Store to StoreGeneric? - store); -} - -/** - * Creates a Pinia instance to be used by the application - */ -function createPinia() { - const scope = effectScope(true); - // NOTE: here we could check the window object for a state and directly set it - // if there is anything like it with Vue 3 SSR - const state = scope.run(() => ref({})); - let _p = []; - // plugins added before calling app.use(pinia) - let toBeInstalled = []; - const pinia = markRaw({ - install(app) { - // this allows calling useStore() outside of a component setup after - // installing pinia's plugin - setActivePinia(pinia); - if (!isVue2) { - pinia._a = app; - app.provide(piniaSymbol, pinia); - app.config.globalProperties.$pinia = pinia; - /* istanbul ignore else */ - if (USE_DEVTOOLS) { - registerPiniaDevtools(app, pinia); - } - toBeInstalled.forEach((plugin) => _p.push(plugin)); - toBeInstalled = []; - } - }, - use(plugin) { - if (!this._a && !isVue2) { - toBeInstalled.push(plugin); - } - else { - _p.push(plugin); - } - return this; - }, - _p, - // it's actually undefined here - // @ts-expect-error - _a: null, - _e: scope, - _s: new Map(), - state, - }); - // pinia devtools rely on dev only features so they cannot be forced unless - // the dev build of Vue is used. Avoid old browsers like IE11. - if (USE_DEVTOOLS && typeof Proxy !== 'undefined') { - pinia.use(devtoolsPlugin); - } - return pinia; -} - -/** - * Checks if a function is a `StoreDefinition`. - * - * @param fn - object to test - * @returns true if `fn` is a StoreDefinition - */ -const isUseStore = (fn) => { - return typeof fn === 'function' && typeof fn.$id === 'string'; -}; -/** - * Mutates in place `newState` with `oldState` to _hot update_ it. It will - * remove any key not existing in `newState` and recursively merge plain - * objects. - * - * @param newState - new state object to be patched - * @param oldState - old state that should be used to patch newState - * @returns - newState - */ -function patchObject(newState, oldState) { - // no need to go through symbols because they cannot be serialized anyway - for (const key in oldState) { - const subPatch = oldState[key]; - // skip the whole sub tree - if (!(key in newState)) { - continue; - } - const targetValue = newState[key]; - if (isPlainObject(targetValue) && - isPlainObject(subPatch) && - !isRef(subPatch) && - !isReactive(subPatch)) { - newState[key] = patchObject(targetValue, subPatch); - } - else { - // objects are either a bit more complex (e.g. refs) or primitives, so we - // just set the whole thing - if (isVue2) { - set(newState, key, subPatch); - } - else { - newState[key] = subPatch; - } - } - } - return newState; -} -/** - * Creates an _accept_ function to pass to `import.meta.hot` in Vite applications. - * - * @example - * ```js - * const useUser = defineStore(...) - * if (import.meta.hot) { - * import.meta.hot.accept(acceptHMRUpdate(useUser, import.meta.hot)) - * } - * ``` - * - * @param initialUseStore - return of the defineStore to hot update - * @param hot - `import.meta.hot` - */ -function acceptHMRUpdate(initialUseStore, hot) { - return (newModule) => { - const pinia = hot.data.pinia || initialUseStore._pinia; - if (!pinia) { - // this store is still not used - return; - } - // preserve the pinia instance across loads - hot.data.pinia = pinia; - // console.log('got data', newStore) - for (const exportName in newModule) { - const useStore = newModule[exportName]; - // console.log('checking for', exportName) - if (isUseStore(useStore) && pinia._s.has(useStore.$id)) { - // console.log('Accepting update for', useStore.$id) - const id = useStore.$id; - if (id !== initialUseStore.$id) { - console.warn(`The id of the store changed from "${initialUseStore.$id}" to "${id}". Reloading.`); - // return import.meta.hot.invalidate() - return hot.invalidate(); - } - const existingStore = pinia._s.get(id); - if (!existingStore) { - console.log(`[Pinia]: skipping hmr because store doesn't exist yet`); - return; - } - useStore(pinia, existingStore); - } - } - }; -} - -const noop = () => { }; -function addSubscription(subscriptions, callback, detached, onCleanup = noop) { - subscriptions.push(callback); - const removeSubscription = () => { - const idx = subscriptions.indexOf(callback); - if (idx > -1) { - subscriptions.splice(idx, 1); - onCleanup(); - } - }; - if (!detached && getCurrentScope()) { - onScopeDispose(removeSubscription); - } - return removeSubscription; -} -function triggerSubscriptions(subscriptions, ...args) { - subscriptions.slice().forEach((callback) => { - callback(...args); - }); -} - -const fallbackRunWithContext = (fn) => fn(); -function mergeReactiveObjects(target, patchToApply) { - // Handle Map instances - if (target instanceof Map && patchToApply instanceof Map) { - patchToApply.forEach((value, key) => target.set(key, value)); - } - // Handle Set instances - if (target instanceof Set && patchToApply instanceof Set) { - patchToApply.forEach(target.add, target); - } - // no need to go through symbols because they cannot be serialized anyway - for (const key in patchToApply) { - if (!patchToApply.hasOwnProperty(key)) - continue; - const subPatch = patchToApply[key]; - const targetValue = target[key]; - if (isPlainObject(targetValue) && - isPlainObject(subPatch) && - target.hasOwnProperty(key) && - !isRef(subPatch) && - !isReactive(subPatch)) { - // NOTE: here I wanted to warn about inconsistent types but it's not possible because in setup stores one might - // start the value of a property as a certain type e.g. a Map, and then for some reason, during SSR, change that - // to `undefined`. When trying to hydrate, we want to override the Map with `undefined`. - target[key] = mergeReactiveObjects(targetValue, subPatch); - } - else { - // @ts-expect-error: subPatch is a valid value - target[key] = subPatch; - } - } - return target; -} -const skipHydrateSymbol = Symbol('pinia:skipHydration') - ; -const skipHydrateMap = /*#__PURE__*/ new WeakMap(); -/** - * Tells Pinia to skip the hydration process of a given object. This is useful in setup stores (only) when you return a - * stateful object in the store but it isn't really state. e.g. returning a router instance in a setup store. - * - * @param obj - target object - * @returns obj - */ -function skipHydrate(obj) { - return isVue2 - ? // in @vue/composition-api, the refs are sealed so defineProperty doesn't work... - /* istanbul ignore next */ skipHydrateMap.set(obj, 1) && obj - : Object.defineProperty(obj, skipHydrateSymbol, {}); -} -/** - * Returns whether a value should be hydrated - * - * @param obj - target variable - * @returns true if `obj` should be hydrated - */ -function shouldHydrate(obj) { - return isVue2 - ? /* istanbul ignore next */ !skipHydrateMap.has(obj) - : !isPlainObject(obj) || !obj.hasOwnProperty(skipHydrateSymbol); -} -const { assign } = Object; -function isComputed(o) { - return !!(isRef(o) && o.effect); -} -function createOptionsStore(id, options, pinia, hot) { - const { state, actions, getters } = options; - const initialState = pinia.state.value[id]; - let store; - function setup() { - if (!initialState && (!hot)) { - /* istanbul ignore if */ - if (isVue2) { - set(pinia.state.value, id, state ? state() : {}); - } - else { - pinia.state.value[id] = state ? state() : {}; - } - } - // avoid creating a state in pinia.state.value - const localState = hot - ? // use ref() to unwrap refs inside state TODO: check if this is still necessary - toRefs(ref(state ? state() : {}).value) - : toRefs(pinia.state.value[id]); - return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => { - if (name in localState) { - console.warn(`[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "${name}" in store "${id}".`); - } - computedGetters[name] = markRaw(computed(() => { - setActivePinia(pinia); - // it was created just before - const store = pinia._s.get(id); - // allow cross using stores - /* istanbul ignore next */ - if (isVue2 && !store._r) - return; - // @ts-expect-error - // return getters![name].call(context, context) - // TODO: avoid reading the getter while assigning with a global variable - return getters[name].call(store, store); - })); - return computedGetters; - }, {})); - } - store = createSetupStore(id, setup, options, pinia, hot, true); - return store; -} -function createSetupStore($id, setup, options = {}, pinia, hot, isOptionsStore) { - let scope; - const optionsForPlugin = assign({ actions: {} }, options); - /* istanbul ignore if */ - if (!pinia._e.active) { - throw new Error('Pinia destroyed'); - } - // watcher options for $subscribe - const $subscribeOptions = { - deep: true, - // flush: 'post', - }; - /* istanbul ignore else */ - if (!isVue2) { - $subscribeOptions.onTrigger = (event) => { - /* istanbul ignore else */ - if (isListening) { - debuggerEvents = event; - // avoid triggering this while the store is being built and the state is being set in pinia - } - else if (isListening == false && !store._hotUpdating) { - // let patch send all the events together later - /* istanbul ignore else */ - if (Array.isArray(debuggerEvents)) { - debuggerEvents.push(event); - } - else { - console.error('🍍 debuggerEvents should be an array. This is most likely an internal Pinia bug.'); - } - } - }; - } - // internal state - let isListening; // set to true at the end - let isSyncListening; // set to true at the end - let subscriptions = []; - let actionSubscriptions = []; - let debuggerEvents; - const initialState = pinia.state.value[$id]; - // avoid setting the state for option stores if it is set - // by the setup - if (!isOptionsStore && !initialState && (!hot)) { - /* istanbul ignore if */ - if (isVue2) { - set(pinia.state.value, $id, {}); - } - else { - pinia.state.value[$id] = {}; - } - } - const hotState = ref({}); - // avoid triggering too many listeners - // https://github.com/vuejs/pinia/issues/1129 - let activeListener; - function $patch(partialStateOrMutator) { - let subscriptionMutation; - isListening = isSyncListening = false; - // reset the debugger events since patches are sync - /* istanbul ignore else */ - { - debuggerEvents = []; - } - if (typeof partialStateOrMutator === 'function') { - partialStateOrMutator(pinia.state.value[$id]); - subscriptionMutation = { - type: MutationType.patchFunction, - storeId: $id, - events: debuggerEvents, - }; - } - else { - mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator); - subscriptionMutation = { - type: MutationType.patchObject, - payload: partialStateOrMutator, - storeId: $id, - events: debuggerEvents, - }; - } - const myListenerId = (activeListener = Symbol()); - nextTick().then(() => { - if (activeListener === myListenerId) { - isListening = true; - } - }); - isSyncListening = true; - // because we paused the watcher, we need to manually call the subscriptions - triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]); - } - const $reset = isOptionsStore - ? function $reset() { - const { state } = options; - const newState = state ? state() : {}; - // we use a patch to group all changes into one single subscription - this.$patch(($state) => { - assign($state, newState); - }); - } - : /* istanbul ignore next */ - () => { - throw new Error(`🍍: Store "${$id}" is built using the setup syntax and does not implement $reset().`); - } - ; - function $dispose() { - scope.stop(); - subscriptions = []; - actionSubscriptions = []; - pinia._s.delete($id); - } - /** - * Wraps an action to handle subscriptions. - * - * @param name - name of the action - * @param action - action to wrap - * @returns a wrapped action to handle subscriptions - */ - function wrapAction(name, action) { - return function () { - setActivePinia(pinia); - const args = Array.from(arguments); - const afterCallbackList = []; - const onErrorCallbackList = []; - function after(callback) { - afterCallbackList.push(callback); - } - function onError(callback) { - onErrorCallbackList.push(callback); - } - // @ts-expect-error - triggerSubscriptions(actionSubscriptions, { - args, - name, - store, - after, - onError, - }); - let ret; - try { - ret = action.apply(this && this.$id === $id ? this : store, args); - // handle sync errors - } - catch (error) { - triggerSubscriptions(onErrorCallbackList, error); - throw error; - } - if (ret instanceof Promise) { - return ret - .then((value) => { - triggerSubscriptions(afterCallbackList, value); - return value; - }) - .catch((error) => { - triggerSubscriptions(onErrorCallbackList, error); - return Promise.reject(error); - }); - } - // trigger after callbacks - triggerSubscriptions(afterCallbackList, ret); - return ret; - }; - } - const _hmrPayload = /*#__PURE__*/ markRaw({ - actions: {}, - getters: {}, - state: [], - hotState, - }); - const partialStore = { - _p: pinia, - // _s: scope, - $id, - $onAction: addSubscription.bind(null, actionSubscriptions), - $patch, - $reset, - $subscribe(callback, options = {}) { - const removeSubscription = addSubscription(subscriptions, callback, options.detached, () => stopWatcher()); - const stopWatcher = scope.run(() => watch(() => pinia.state.value[$id], (state) => { - if (options.flush === 'sync' ? isSyncListening : isListening) { - callback({ - storeId: $id, - type: MutationType.direct, - events: debuggerEvents, - }, state); - } - }, assign({}, $subscribeOptions, options))); - return removeSubscription; - }, - $dispose, - }; - /* istanbul ignore if */ - if (isVue2) { - // start as non ready - partialStore._r = false; - } - const store = reactive(assign({ - _hmrPayload, - _customProperties: markRaw(new Set()), // devtools custom properties - }, partialStore - // must be added later - // setupStore - ) - ); - // store the partial store now so the setup of stores can instantiate each other before they are finished without - // creating infinite loops. - pinia._s.set($id, store); - const runWithContext = (pinia._a && pinia._a.runWithContext) || fallbackRunWithContext; - // TODO: idea create skipSerialize that marks properties as non serializable and they are skipped - const setupStore = pinia._e.run(() => { - scope = effectScope(); - return runWithContext(() => scope.run(setup)); - }); - // overwrite existing actions to support $onAction - for (const key in setupStore) { - const prop = setupStore[key]; - if ((isRef(prop) && !isComputed(prop)) || isReactive(prop)) { - // mark it as a piece of state to be serialized - if (hot) { - set(hotState.value, key, toRef(setupStore, key)); - // createOptionStore directly sets the state in pinia.state.value so we - // can just skip that - } - else if (!isOptionsStore) { - // in setup stores we must hydrate the state and sync pinia state tree with the refs the user just created - if (initialState && shouldHydrate(prop)) { - if (isRef(prop)) { - prop.value = initialState[key]; - } - else { - // probably a reactive object, lets recursively assign - // @ts-expect-error: prop is unknown - mergeReactiveObjects(prop, initialState[key]); - } - } - // transfer the ref to the pinia state to keep everything in sync - /* istanbul ignore if */ - if (isVue2) { - set(pinia.state.value[$id], key, prop); - } - else { - pinia.state.value[$id][key] = prop; - } - } - /* istanbul ignore else */ - { - _hmrPayload.state.push(key); - } - // action - } - else if (typeof prop === 'function') { - // @ts-expect-error: we are overriding the function we avoid wrapping if - const actionValue = hot ? prop : wrapAction(key, prop); - // this a hot module replacement store because the hotUpdate method needs - // to do it with the right context - /* istanbul ignore if */ - if (isVue2) { - set(setupStore, key, actionValue); - } - else { - // @ts-expect-error - setupStore[key] = actionValue; - } - /* istanbul ignore else */ - { - _hmrPayload.actions[key] = prop; - } - // list actions so they can be used in plugins - // @ts-expect-error - optionsForPlugin.actions[key] = prop; - } - else { - // add getters for devtools - if (isComputed(prop)) { - _hmrPayload.getters[key] = isOptionsStore - ? // @ts-expect-error - options.getters[key] - : prop; - if (IS_CLIENT) { - const getters = setupStore._getters || - // @ts-expect-error: same - (setupStore._getters = markRaw([])); - getters.push(key); - } - } - } - } - // add the state, getters, and action properties - /* istanbul ignore if */ - if (isVue2) { - Object.keys(setupStore).forEach((key) => { - set(store, key, setupStore[key]); - }); - } - else { - assign(store, setupStore); - // allows retrieving reactive objects with `storeToRefs()`. Must be called after assigning to the reactive object. - // Make `storeToRefs()` work with `reactive()` #799 - assign(toRaw(store), setupStore); - } - // use this instead of a computed with setter to be able to create it anywhere - // without linking the computed lifespan to wherever the store is first - // created. - Object.defineProperty(store, '$state', { - get: () => (hot ? hotState.value : pinia.state.value[$id]), - set: (state) => { - /* istanbul ignore if */ - if (hot) { - throw new Error('cannot set hotState'); - } - $patch(($state) => { - assign($state, state); - }); - }, - }); - // add the hotUpdate before plugins to allow them to override it - /* istanbul ignore else */ - { - store._hotUpdate = markRaw((newStore) => { - store._hotUpdating = true; - newStore._hmrPayload.state.forEach((stateKey) => { - if (stateKey in store.$state) { - const newStateTarget = newStore.$state[stateKey]; - const oldStateSource = store.$state[stateKey]; - if (typeof newStateTarget === 'object' && - isPlainObject(newStateTarget) && - isPlainObject(oldStateSource)) { - patchObject(newStateTarget, oldStateSource); - } - else { - // transfer the ref - newStore.$state[stateKey] = oldStateSource; - } - } - // patch direct access properties to allow store.stateProperty to work as - // store.$state.stateProperty - set(store, stateKey, toRef(newStore.$state, stateKey)); - }); - // remove deleted state properties - Object.keys(store.$state).forEach((stateKey) => { - if (!(stateKey in newStore.$state)) { - del(store, stateKey); - } - }); - // avoid devtools logging this as a mutation - isListening = false; - isSyncListening = false; - pinia.state.value[$id] = toRef(newStore._hmrPayload, 'hotState'); - isSyncListening = true; - nextTick().then(() => { - isListening = true; - }); - for (const actionName in newStore._hmrPayload.actions) { - const action = newStore[actionName]; - set(store, actionName, wrapAction(actionName, action)); - } - // TODO: does this work in both setup and option store? - for (const getterName in newStore._hmrPayload.getters) { - const getter = newStore._hmrPayload.getters[getterName]; - const getterValue = isOptionsStore - ? // special handling of options api - computed(() => { - setActivePinia(pinia); - return getter.call(store, store); - }) - : getter; - set(store, getterName, getterValue); - } - // remove deleted getters - Object.keys(store._hmrPayload.getters).forEach((key) => { - if (!(key in newStore._hmrPayload.getters)) { - del(store, key); - } - }); - // remove old actions - Object.keys(store._hmrPayload.actions).forEach((key) => { - if (!(key in newStore._hmrPayload.actions)) { - del(store, key); - } - }); - // update the values used in devtools and to allow deleting new properties later on - store._hmrPayload = newStore._hmrPayload; - store._getters = newStore._getters; - store._hotUpdating = false; - }); - } - if (USE_DEVTOOLS) { - const nonEnumerable = { - writable: true, - configurable: true, - // avoid warning on devtools trying to display this property - enumerable: false, - }; - ['_p', '_hmrPayload', '_getters', '_customProperties'].forEach((p) => { - Object.defineProperty(store, p, assign({ value: store[p] }, nonEnumerable)); - }); - } - /* istanbul ignore if */ - if (isVue2) { - // mark the store as ready before plugins - store._r = true; - } - // apply all plugins - pinia._p.forEach((extender) => { - /* istanbul ignore else */ - if (USE_DEVTOOLS) { - const extensions = scope.run(() => extender({ - store, - app: pinia._a, - pinia, - options: optionsForPlugin, - })); - Object.keys(extensions || {}).forEach((key) => store._customProperties.add(key)); - assign(store, extensions); - } - else { - assign(store, scope.run(() => extender({ - store, - app: pinia._a, - pinia, - options: optionsForPlugin, - }))); - } - }); - if (store.$state && - typeof store.$state === 'object' && - typeof store.$state.constructor === 'function' && - !store.$state.constructor.toString().includes('[native code]')) { - console.warn(`[🍍]: The "state" must be a plain object. It cannot be\n` + - `\tstate: () => new MyClass()\n` + - `Found in store "${store.$id}".`); - } - // only apply hydrate to option stores with an initial state in pinia - if (initialState && - isOptionsStore && - options.hydrate) { - options.hydrate(store.$state, initialState); - } - isListening = true; - isSyncListening = true; - return store; -} -function defineStore( -// TODO: add proper types from above -idOrOptions, setup, setupOptions) { - let id; - let options; - const isSetupStore = typeof setup === 'function'; - if (typeof idOrOptions === 'string') { - id = idOrOptions; - // the option store setup will contain the actual options in this case - options = isSetupStore ? setupOptions : setup; - } - else { - options = idOrOptions; - id = idOrOptions.id; - if (typeof id !== 'string') { - throw new Error(`[🍍]: "defineStore()" must be passed a store id as its first argument.`); - } - } - function useStore(pinia, hot) { - const hasContext = hasInjectionContext(); - pinia = - // in test mode, ignore the argument provided as we can always retrieve a - // pinia instance with getActivePinia() - (pinia) || - (hasContext ? inject(piniaSymbol, null) : null); - if (pinia) - setActivePinia(pinia); - if (!activePinia) { - throw new Error(`[🍍]: "getActivePinia()" was called but there was no active Pinia. Did you forget to install pinia?\n` + - `\tconst pinia = createPinia()\n` + - `\tapp.use(pinia)\n` + - `This will fail in production.`); - } - pinia = activePinia; - if (!pinia._s.has(id)) { - // creating the store registers it in `pinia._s` - if (isSetupStore) { - createSetupStore(id, setup, options, pinia); - } - else { - createOptionsStore(id, options, pinia); - } - /* istanbul ignore else */ - { - // @ts-expect-error: not the right inferred type - useStore._pinia = pinia; - } - } - const store = pinia._s.get(id); - if (hot) { - const hotId = '__hot:' + id; - const newStore = isSetupStore - ? createSetupStore(hotId, setup, options, pinia, true) - : createOptionsStore(hotId, assign({}, options), pinia, true); - hot._hotUpdate(newStore); - // cleanup the state properties and the store from the cache - delete pinia.state.value[hotId]; - pinia._s.delete(hotId); - } - if (IS_CLIENT) { - const currentInstance = getCurrentInstance(); - // save stores in instances to access them devtools - if (currentInstance && - currentInstance.proxy && - // avoid adding stores that are just built for hot module replacement - !hot) { - const vm = currentInstance.proxy; - const cache = '_pStores' in vm ? vm._pStores : (vm._pStores = {}); - cache[id] = store; - } - } - // StoreGeneric cannot be casted towards Store - return store; - } - useStore.$id = id; - return useStore; -} - -let mapStoreSuffix = 'Store'; -/** - * Changes the suffix added by `mapStores()`. Can be set to an empty string. - * Defaults to `"Store"`. Make sure to extend the MapStoresCustomization - * interface if you are using TypeScript. - * - * @param suffix - new suffix - */ -function setMapStoreSuffix(suffix // could be 'Store' but that would be annoying for JS -) { - mapStoreSuffix = suffix; -} -/** - * Allows using stores without the composition API (`setup()`) by generating an - * object to be spread in the `computed` field of a component. It accepts a list - * of store definitions. - * - * @example - * ```js - * export default { - * computed: { - * // other computed properties - * ...mapStores(useUserStore, useCartStore) - * }, - * - * created() { - * this.userStore // store with id "user" - * this.cartStore // store with id "cart" - * } - * } - * ``` - * - * @param stores - list of stores to map to an object - */ -function mapStores(...stores) { - if (Array.isArray(stores[0])) { - console.warn(`[🍍]: Directly pass all stores to "mapStores()" without putting them in an array:\n` + - `Replace\n` + - `\tmapStores([useAuthStore, useCartStore])\n` + - `with\n` + - `\tmapStores(useAuthStore, useCartStore)\n` + - `This will fail in production if not fixed.`); - stores = stores[0]; - } - return stores.reduce((reduced, useStore) => { - // @ts-expect-error: $id is added by defineStore - reduced[useStore.$id + mapStoreSuffix] = function () { - return useStore(this.$pinia); - }; - return reduced; - }, {}); -} -/** - * Allows using state and getters from one store without using the composition - * API (`setup()`) by generating an object to be spread in the `computed` field - * of a component. - * - * @param useStore - store to map from - * @param keysOrMapper - array or object - */ -function mapState(useStore, keysOrMapper) { - return Array.isArray(keysOrMapper) - ? keysOrMapper.reduce((reduced, key) => { - reduced[key] = function () { - return useStore(this.$pinia)[key]; - }; - return reduced; - }, {}) - : Object.keys(keysOrMapper).reduce((reduced, key) => { - // @ts-expect-error - reduced[key] = function () { - const store = useStore(this.$pinia); - const storeKey = keysOrMapper[key]; - // for some reason TS is unable to infer the type of storeKey to be a - // function - return typeof storeKey === 'function' - ? storeKey.call(this, store) - : store[storeKey]; - }; - return reduced; - }, {}); -} -/** - * Alias for `mapState()`. You should use `mapState()` instead. - * @deprecated use `mapState()` instead. - */ -const mapGetters = mapState; -/** - * Allows directly using actions from your store without using the composition - * API (`setup()`) by generating an object to be spread in the `methods` field - * of a component. - * - * @param useStore - store to map from - * @param keysOrMapper - array or object - */ -function mapActions(useStore, keysOrMapper) { - return Array.isArray(keysOrMapper) - ? keysOrMapper.reduce((reduced, key) => { - // @ts-expect-error - reduced[key] = function (...args) { - return useStore(this.$pinia)[key](...args); - }; - return reduced; - }, {}) - : Object.keys(keysOrMapper).reduce((reduced, key) => { - // @ts-expect-error - reduced[key] = function (...args) { - return useStore(this.$pinia)[keysOrMapper[key]](...args); - }; - return reduced; - }, {}); -} -/** - * Allows using state and getters from one store without using the composition - * API (`setup()`) by generating an object to be spread in the `computed` field - * of a component. - * - * @param useStore - store to map from - * @param keysOrMapper - array or object - */ -function mapWritableState(useStore, keysOrMapper) { - return Array.isArray(keysOrMapper) - ? keysOrMapper.reduce((reduced, key) => { - // @ts-ignore - reduced[key] = { - get() { - return useStore(this.$pinia)[key]; - }, - set(value) { - // it's easier to type it here as any - return (useStore(this.$pinia)[key] = value); - }, - }; - return reduced; - }, {}) - : Object.keys(keysOrMapper).reduce((reduced, key) => { - // @ts-ignore - reduced[key] = { - get() { - return useStore(this.$pinia)[keysOrMapper[key]]; - }, - set(value) { - // it's easier to type it here as any - return (useStore(this.$pinia)[keysOrMapper[key]] = value); - }, - }; - return reduced; - }, {}); -} - -/** - * Creates an object of references with all the state, getters, and plugin-added - * state properties of the store. Similar to `toRefs()` but specifically - * designed for Pinia stores so methods and non reactive properties are - * completely ignored. - * - * @param store - store to extract the refs from - */ -function storeToRefs(store) { - // See https://github.com/vuejs/pinia/issues/852 - // It's easier to just use toRefs() even if it includes more stuff - if (isVue2) { - // @ts-expect-error: toRefs include methods and others - return toRefs(store); - } - else { - store = toRaw(store); - const refs = {}; - for (const key in store) { - const value = store[key]; - if (isRef(value) || isReactive(value)) { - // @ts-expect-error: the key is state or getter - refs[key] = - // --- - toRef(store, key); - } - } - return refs; - } -} - -/** - * Vue 2 Plugin that must be installed for pinia to work. Note **you don't need - * this plugin if you are using Nuxt.js**. Use the `buildModule` instead: - * https://pinia.vuejs.org/ssr/nuxt.html. - * - * @example - * ```js - * import Vue from 'vue' - * import { PiniaVuePlugin, createPinia } from 'pinia' - * - * Vue.use(PiniaVuePlugin) - * const pinia = createPinia() - * - * new Vue({ - * el: '#app', - * // ... - * pinia, - * }) - * ``` - * - * @param _Vue - `Vue` imported from 'vue'. - */ -const PiniaVuePlugin = function (_Vue) { - // Equivalent of - // app.config.globalProperties.$pinia = pinia - _Vue.mixin({ - beforeCreate() { - const options = this.$options; - if (options.pinia) { - const pinia = options.pinia; - // HACK: taken from provide(): https://github.com/vuejs/composition-api/blob/main/src/apis/inject.ts#L31 - /* istanbul ignore else */ - if (!this._provided) { - const provideCache = {}; - Object.defineProperty(this, '_provided', { - get: () => provideCache, - set: (v) => Object.assign(provideCache, v), - }); - } - this._provided[piniaSymbol] = pinia; - // propagate the pinia instance in an SSR friendly way - // avoid adding it to nuxt twice - /* istanbul ignore else */ - if (!this.$pinia) { - this.$pinia = pinia; - } - pinia._a = this; - if (IS_CLIENT) { - // this allows calling useStore() outside of a component setup after - // installing pinia's plugin - setActivePinia(pinia); - } - if (USE_DEVTOOLS) { - registerPiniaDevtools(pinia._a, pinia); - } - } - else if (!this.$pinia && options.parent && options.parent.$pinia) { - this.$pinia = options.parent.$pinia; - } - }, - destroyed() { - delete this._pStores; - }, - }); -}; - -export { MutationType, PiniaVuePlugin, acceptHMRUpdate, createPinia, defineStore, getActivePinia, mapActions, mapGetters, mapState, mapStores, mapWritableState, setActivePinia, setMapStoreSuffix, skipHydrate, storeToRefs }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/lib/vue-router.esm-browser.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/lib/vue-router.esm-browser.js deleted file mode 100644 index 290e0461..00000000 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/lib/vue-router.esm-browser.js +++ /dev/null @@ -1,3613 +0,0 @@ -/*! - * vue-router v4.2.0 - * (c) 2023 Eduardo San Martin Morote - * @license MIT - */ -import { getCurrentInstance, inject, onUnmounted, onDeactivated, onActivated, computed, unref, watchEffect, defineComponent, reactive, h, provide, ref, watch, shallowRef, nextTick } from 'vue'; -import { setupDevtoolsPlugin } from '@vue/devtools-api'; - -const isBrowser = typeof window !== 'undefined'; - -function isESModule(obj) { - return obj.__esModule || obj[Symbol.toStringTag] === 'Module'; -} -const assign = Object.assign; -function applyToParams(fn, params) { - const newParams = {}; - for (const key in params) { - const value = params[key]; - newParams[key] = isArray(value) - ? value.map(fn) - : fn(value); - } - return newParams; -} -const noop = () => { }; -/** - * Typesafe alternative to Array.isArray - * https://github.com/microsoft/TypeScript/pull/48228 - */ -const isArray = Array.isArray; - -function warn(msg) { - // avoid using ...args as it breaks in older Edge builds - const args = Array.from(arguments).slice(1); - console.warn.apply(console, ['[Vue Router warn]: ' + msg].concat(args)); -} - -const TRAILING_SLASH_RE = /\/$/; -const removeTrailingSlash = (path) => path.replace(TRAILING_SLASH_RE, ''); -/** - * Transforms a URI into a normalized history location - * - * @param parseQuery - * @param location - URI to normalize - * @param currentLocation - current absolute location. Allows resolving relative - * paths. Must start with `/`. Defaults to `/` - * @returns a normalized history location - */ -function parseURL(parseQuery, location, currentLocation = '/') { - let path, query = {}, searchString = '', hash = ''; - // Could use URL and URLSearchParams but IE 11 doesn't support it - // TODO: move to new URL() - const hashPos = location.indexOf('#'); - let searchPos = location.indexOf('?'); - // the hash appears before the search, so it's not part of the search string - if (hashPos < searchPos && hashPos >= 0) { - searchPos = -1; - } - if (searchPos > -1) { - path = location.slice(0, searchPos); - searchString = location.slice(searchPos + 1, hashPos > -1 ? hashPos : location.length); - query = parseQuery(searchString); - } - if (hashPos > -1) { - path = path || location.slice(0, hashPos); - // keep the # character - hash = location.slice(hashPos, location.length); - } - // no search and no query - path = resolveRelativePath(path != null ? path : location, currentLocation); - // empty path means a relative query or hash `?foo=f`, `#thing` - return { - fullPath: path + (searchString && '?') + searchString + hash, - path, - query, - hash, - }; -} -/** - * Stringifies a URL object - * - * @param stringifyQuery - * @param location - */ -function stringifyURL(stringifyQuery, location) { - const query = location.query ? stringifyQuery(location.query) : ''; - return location.path + (query && '?') + query + (location.hash || ''); -} -/** - * Strips off the base from the beginning of a location.pathname in a non-case-sensitive way. - * - * @param pathname - location.pathname - * @param base - base to strip off - */ -function stripBase(pathname, base) { - // no base or base is not found at the beginning - if (!base || !pathname.toLowerCase().startsWith(base.toLowerCase())) - return pathname; - return pathname.slice(base.length) || '/'; -} -/** - * Checks if two RouteLocation are equal. This means that both locations are - * pointing towards the same {@link RouteRecord} and that all `params`, `query` - * parameters and `hash` are the same - * - * @param stringifyQuery - A function that takes a query object of type LocationQueryRaw and returns a string representation of it. - * @param a - first {@link RouteLocation} - * @param b - second {@link RouteLocation} - */ -function isSameRouteLocation(stringifyQuery, a, b) { - const aLastIndex = a.matched.length - 1; - const bLastIndex = b.matched.length - 1; - return (aLastIndex > -1 && - aLastIndex === bLastIndex && - isSameRouteRecord(a.matched[aLastIndex], b.matched[bLastIndex]) && - isSameRouteLocationParams(a.params, b.params) && - stringifyQuery(a.query) === stringifyQuery(b.query) && - a.hash === b.hash); -} -/** - * Check if two `RouteRecords` are equal. Takes into account aliases: they are - * considered equal to the `RouteRecord` they are aliasing. - * - * @param a - first {@link RouteRecord} - * @param b - second {@link RouteRecord} - */ -function isSameRouteRecord(a, b) { - // since the original record has an undefined value for aliasOf - // but all aliases point to the original record, this will always compare - // the original record - return (a.aliasOf || a) === (b.aliasOf || b); -} -function isSameRouteLocationParams(a, b) { - if (Object.keys(a).length !== Object.keys(b).length) - return false; - for (const key in a) { - if (!isSameRouteLocationParamsValue(a[key], b[key])) - return false; - } - return true; -} -function isSameRouteLocationParamsValue(a, b) { - return isArray(a) - ? isEquivalentArray(a, b) - : isArray(b) - ? isEquivalentArray(b, a) - : a === b; -} -/** - * Check if two arrays are the same or if an array with one single entry is the - * same as another primitive value. Used to check query and parameters - * - * @param a - array of values - * @param b - array of values or a single value - */ -function isEquivalentArray(a, b) { - return isArray(b) - ? a.length === b.length && a.every((value, i) => value === b[i]) - : a.length === 1 && a[0] === b; -} -/** - * Resolves a relative path that starts with `.`. - * - * @param to - path location we are resolving - * @param from - currentLocation.path, should start with `/` - */ -function resolveRelativePath(to, from) { - if (to.startsWith('/')) - return to; - if (!from.startsWith('/')) { - warn(`Cannot resolve a relative location without an absolute path. Trying to resolve "${to}" from "${from}". It should look like "/${from}".`); - return to; - } - if (!to) - return from; - const fromSegments = from.split('/'); - const toSegments = to.split('/'); - const lastToSegment = toSegments[toSegments.length - 1]; - // make . and ./ the same (../ === .., ../../ === ../..) - // this is the same behavior as new URL() - if (lastToSegment === '..' || lastToSegment === '.') { - toSegments.push(''); - } - let position = fromSegments.length - 1; - let toPosition; - let segment; - for (toPosition = 0; toPosition < toSegments.length; toPosition++) { - segment = toSegments[toPosition]; - // we stay on the same position - if (segment === '.') - continue; - // go up in the from array - if (segment === '..') { - // we can't go below zero, but we still need to increment toPosition - if (position > 1) - position--; - // continue - } - // we reached a non-relative path, we stop here - else - break; - } - return (fromSegments.slice(0, position).join('/') + - '/' + - toSegments - // ensure we use at least the last element in the toSegments - .slice(toPosition - (toPosition === toSegments.length ? 1 : 0)) - .join('/')); -} - -var NavigationType; -(function (NavigationType) { - NavigationType["pop"] = "pop"; - NavigationType["push"] = "push"; -})(NavigationType || (NavigationType = {})); -var NavigationDirection; -(function (NavigationDirection) { - NavigationDirection["back"] = "back"; - NavigationDirection["forward"] = "forward"; - NavigationDirection["unknown"] = ""; -})(NavigationDirection || (NavigationDirection = {})); -/** - * Starting location for Histories - */ -const START = ''; -// Generic utils -/** - * Normalizes a base by removing any trailing slash and reading the base tag if - * present. - * - * @param base - base to normalize - */ -function normalizeBase(base) { - if (!base) { - if (isBrowser) { - // respect tag - const baseEl = document.querySelector('base'); - base = (baseEl && baseEl.getAttribute('href')) || '/'; - // strip full URL origin - base = base.replace(/^\w+:\/\/[^\/]+/, ''); - } - else { - base = '/'; - } - } - // ensure leading slash when it was removed by the regex above avoid leading - // slash with hash because the file could be read from the disk like file:// - // and the leading slash would cause problems - if (base[0] !== '/' && base[0] !== '#') - base = '/' + base; - // remove the trailing slash so all other method can just do `base + fullPath` - // to build an href - return removeTrailingSlash(base); -} -// remove any character before the hash -const BEFORE_HASH_RE = /^[^#]+#/; -function createHref(base, location) { - return base.replace(BEFORE_HASH_RE, '#') + location; -} - -function getElementPosition(el, offset) { - const docRect = document.documentElement.getBoundingClientRect(); - const elRect = el.getBoundingClientRect(); - return { - behavior: offset.behavior, - left: elRect.left - docRect.left - (offset.left || 0), - top: elRect.top - docRect.top - (offset.top || 0), - }; -} -const computeScrollPosition = () => ({ - left: window.pageXOffset, - top: window.pageYOffset, -}); -function scrollToPosition(position) { - let scrollToOptions; - if ('el' in position) { - const positionEl = position.el; - const isIdSelector = typeof positionEl === 'string' && positionEl.startsWith('#'); - /** - * `id`s can accept pretty much any characters, including CSS combinators - * like `>` or `~`. It's still possible to retrieve elements using - * `document.getElementById('~')` but it needs to be escaped when using - * `document.querySelector('#\\~')` for it to be valid. The only - * requirements for `id`s are them to be unique on the page and to not be - * empty (`id=""`). Because of that, when passing an id selector, it should - * be properly escaped for it to work with `querySelector`. We could check - * for the id selector to be simple (no CSS combinators `+ >~`) but that - * would make things inconsistent since they are valid characters for an - * `id` but would need to be escaped when using `querySelector`, breaking - * their usage and ending up in no selector returned. Selectors need to be - * escaped: - * - * - `#1-thing` becomes `#\31 -thing` - * - `#with~symbols` becomes `#with\\~symbols` - * - * - More information about the topic can be found at - * https://mathiasbynens.be/notes/html5-id-class. - * - Practical example: https://mathiasbynens.be/demo/html5-id - */ - if (typeof position.el === 'string') { - if (!isIdSelector || !document.getElementById(position.el.slice(1))) { - try { - const foundEl = document.querySelector(position.el); - if (isIdSelector && foundEl) { - warn(`The selector "${position.el}" should be passed as "el: document.querySelector('${position.el}')" because it starts with "#".`); - // return to avoid other warnings - return; - } - } - catch (err) { - warn(`The selector "${position.el}" is invalid. If you are using an id selector, make sure to escape it. You can find more information about escaping characters in selectors at https://mathiasbynens.be/notes/css-escapes or use CSS.escape (https://developer.mozilla.org/en-US/docs/Web/API/CSS/escape).`); - // return to avoid other warnings - return; - } - } - } - const el = typeof positionEl === 'string' - ? isIdSelector - ? document.getElementById(positionEl.slice(1)) - : document.querySelector(positionEl) - : positionEl; - if (!el) { - warn(`Couldn't find element using selector "${position.el}" returned by scrollBehavior.`); - return; - } - scrollToOptions = getElementPosition(el, position); - } - else { - scrollToOptions = position; - } - if ('scrollBehavior' in document.documentElement.style) - window.scrollTo(scrollToOptions); - else { - window.scrollTo(scrollToOptions.left != null ? scrollToOptions.left : window.pageXOffset, scrollToOptions.top != null ? scrollToOptions.top : window.pageYOffset); - } -} -function getScrollKey(path, delta) { - const position = history.state ? history.state.position - delta : -1; - return position + path; -} -const scrollPositions = new Map(); -function saveScrollPosition(key, scrollPosition) { - scrollPositions.set(key, scrollPosition); -} -function getSavedScrollPosition(key) { - const scroll = scrollPositions.get(key); - // consume it so it's not used again - scrollPositions.delete(key); - return scroll; -} -// TODO: RFC about how to save scroll position -/** - * ScrollBehavior instance used by the router to compute and restore the scroll - * position when navigating. - */ -// export interface ScrollHandler { -// // returns a scroll position that can be saved in history -// compute(): ScrollPositionEntry -// // can take an extended ScrollPositionEntry -// scroll(position: ScrollPosition): void -// } -// export const scrollHandler: ScrollHandler = { -// compute: computeScroll, -// scroll: scrollToPosition, -// } - -let createBaseLocation = () => location.protocol + '//' + location.host; -/** - * Creates a normalized history location from a window.location object - * @param base - The base path - * @param location - The window.location object - */ -function createCurrentLocation(base, location) { - const { pathname, search, hash } = location; - // allows hash bases like #, /#, #/, #!, #!/, /#!/, or even /folder#end - const hashPos = base.indexOf('#'); - if (hashPos > -1) { - let slicePos = hash.includes(base.slice(hashPos)) - ? base.slice(hashPos).length - : 1; - let pathFromHash = hash.slice(slicePos); - // prepend the starting slash to hash so the url starts with /# - if (pathFromHash[0] !== '/') - pathFromHash = '/' + pathFromHash; - return stripBase(pathFromHash, ''); - } - const path = stripBase(pathname, base); - return path + search + hash; -} -function useHistoryListeners(base, historyState, currentLocation, replace) { - let listeners = []; - let teardowns = []; - // TODO: should it be a stack? a Dict. Check if the popstate listener - // can trigger twice - let pauseState = null; - const popStateHandler = ({ state, }) => { - const to = createCurrentLocation(base, location); - const from = currentLocation.value; - const fromState = historyState.value; - let delta = 0; - if (state) { - currentLocation.value = to; - historyState.value = state; - // ignore the popstate and reset the pauseState - if (pauseState && pauseState === from) { - pauseState = null; - return; - } - delta = fromState ? state.position - fromState.position : 0; - } - else { - replace(to); - } - // console.log({ deltaFromCurrent }) - // Here we could also revert the navigation by calling history.go(-delta) - // this listener will have to be adapted to not trigger again and to wait for the url - // to be updated before triggering the listeners. Some kind of validation function would also - // need to be passed to the listeners so the navigation can be accepted - // call all listeners - listeners.forEach(listener => { - listener(currentLocation.value, from, { - delta, - type: NavigationType.pop, - direction: delta - ? delta > 0 - ? NavigationDirection.forward - : NavigationDirection.back - : NavigationDirection.unknown, - }); - }); - }; - function pauseListeners() { - pauseState = currentLocation.value; - } - function listen(callback) { - // set up the listener and prepare teardown callbacks - listeners.push(callback); - const teardown = () => { - const index = listeners.indexOf(callback); - if (index > -1) - listeners.splice(index, 1); - }; - teardowns.push(teardown); - return teardown; - } - function beforeUnloadListener() { - const { history } = window; - if (!history.state) - return; - history.replaceState(assign({}, history.state, { scroll: computeScrollPosition() }), ''); - } - function destroy() { - for (const teardown of teardowns) - teardown(); - teardowns = []; - window.removeEventListener('popstate', popStateHandler); - window.removeEventListener('beforeunload', beforeUnloadListener); - } - // set up the listeners and prepare teardown callbacks - window.addEventListener('popstate', popStateHandler); - // TODO: could we use 'pagehide' or 'visibilitychange' instead? - // https://developer.chrome.com/blog/page-lifecycle-api/ - window.addEventListener('beforeunload', beforeUnloadListener, { - passive: true, - }); - return { - pauseListeners, - listen, - destroy, - }; -} -/** - * Creates a state object - */ -function buildState(back, current, forward, replaced = false, computeScroll = false) { - return { - back, - current, - forward, - replaced, - position: window.history.length, - scroll: computeScroll ? computeScrollPosition() : null, - }; -} -function useHistoryStateNavigation(base) { - const { history, location } = window; - // private variables - const currentLocation = { - value: createCurrentLocation(base, location), - }; - const historyState = { value: history.state }; - // build current history entry as this is a fresh navigation - if (!historyState.value) { - changeLocation(currentLocation.value, { - back: null, - current: currentLocation.value, - forward: null, - // the length is off by one, we need to decrease it - position: history.length - 1, - replaced: true, - // don't add a scroll as the user may have an anchor, and we want - // scrollBehavior to be triggered without a saved position - scroll: null, - }, true); - } - function changeLocation(to, state, replace) { - /** - * if a base tag is provided, and we are on a normal domain, we have to - * respect the provided `base` attribute because pushState() will use it and - * potentially erase anything before the `#` like at - * https://github.com/vuejs/router/issues/685 where a base of - * `/folder/#` but a base of `/` would erase the `/folder/` section. If - * there is no host, the `` tag makes no sense and if there isn't a - * base tag we can just use everything after the `#`. - */ - const hashIndex = base.indexOf('#'); - const url = hashIndex > -1 - ? (location.host && document.querySelector('base') - ? base - : base.slice(hashIndex)) + to - : createBaseLocation() + base + to; - try { - // BROWSER QUIRK - // NOTE: Safari throws a SecurityError when calling this function 100 times in 30 seconds - history[replace ? 'replaceState' : 'pushState'](state, '', url); - historyState.value = state; - } - catch (err) { - { - warn('Error with push/replace State', err); - } - // Force the navigation, this also resets the call count - location[replace ? 'replace' : 'assign'](url); - } - } - function replace(to, data) { - const state = assign({}, history.state, buildState(historyState.value.back, - // keep back and forward entries but override current position - to, historyState.value.forward, true), data, { position: historyState.value.position }); - changeLocation(to, state, true); - currentLocation.value = to; - } - function push(to, data) { - // Add to current entry the information of where we are going - // as well as saving the current position - const currentState = assign({}, - // use current history state to gracefully handle a wrong call to - // history.replaceState - // https://github.com/vuejs/router/issues/366 - historyState.value, history.state, { - forward: to, - scroll: computeScrollPosition(), - }); - if (!history.state) { - warn(`history.state seems to have been manually replaced without preserving the necessary values. Make sure to preserve existing history state if you are manually calling history.replaceState:\n\n` + - `history.replaceState(history.state, '', url)\n\n` + - `You can find more information at https://next.router.vuejs.org/guide/migration/#usage-of-history-state.`); - } - changeLocation(currentState.current, currentState, true); - const state = assign({}, buildState(currentLocation.value, to, null), { position: currentState.position + 1 }, data); - changeLocation(to, state, false); - currentLocation.value = to; - } - return { - location: currentLocation, - state: historyState, - push, - replace, - }; -} -/** - * Creates an HTML5 history. Most common history for single page applications. - * - * @param base - - */ -function createWebHistory(base) { - base = normalizeBase(base); - const historyNavigation = useHistoryStateNavigation(base); - const historyListeners = useHistoryListeners(base, historyNavigation.state, historyNavigation.location, historyNavigation.replace); - function go(delta, triggerListeners = true) { - if (!triggerListeners) - historyListeners.pauseListeners(); - history.go(delta); - } - const routerHistory = assign({ - // it's overridden right after - location: '', - base, - go, - createHref: createHref.bind(null, base), - }, historyNavigation, historyListeners); - Object.defineProperty(routerHistory, 'location', { - enumerable: true, - get: () => historyNavigation.location.value, - }); - Object.defineProperty(routerHistory, 'state', { - enumerable: true, - get: () => historyNavigation.state.value, - }); - return routerHistory; -} - -/** - * Creates an in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere. - * It's up to the user to replace that location with the starter location by either calling `router.push` or `router.replace`. - * - * @param base - Base applied to all urls, defaults to '/' - * @returns a history object that can be passed to the router constructor - */ -function createMemoryHistory(base = '') { - let listeners = []; - let queue = [START]; - let position = 0; - base = normalizeBase(base); - function setLocation(location) { - position++; - if (position === queue.length) { - // we are at the end, we can simply append a new entry - queue.push(location); - } - else { - // we are in the middle, we remove everything from here in the queue - queue.splice(position); - queue.push(location); - } - } - function triggerListeners(to, from, { direction, delta }) { - const info = { - direction, - delta, - type: NavigationType.pop, - }; - for (const callback of listeners) { - callback(to, from, info); - } - } - const routerHistory = { - // rewritten by Object.defineProperty - location: START, - // TODO: should be kept in queue - state: {}, - base, - createHref: createHref.bind(null, base), - replace(to) { - // remove current entry and decrement position - queue.splice(position--, 1); - setLocation(to); - }, - push(to, data) { - setLocation(to); - }, - listen(callback) { - listeners.push(callback); - return () => { - const index = listeners.indexOf(callback); - if (index > -1) - listeners.splice(index, 1); - }; - }, - destroy() { - listeners = []; - queue = [START]; - position = 0; - }, - go(delta, shouldTrigger = true) { - const from = this.location; - const direction = - // we are considering delta === 0 going forward, but in abstract mode - // using 0 for the delta doesn't make sense like it does in html5 where - // it reloads the page - delta < 0 ? NavigationDirection.back : NavigationDirection.forward; - position = Math.max(0, Math.min(position + delta, queue.length - 1)); - if (shouldTrigger) { - triggerListeners(this.location, from, { - direction, - delta, - }); - } - }, - }; - Object.defineProperty(routerHistory, 'location', { - enumerable: true, - get: () => queue[position], - }); - return routerHistory; -} - -/** - * Creates a hash history. Useful for web applications with no host (e.g. `file://`) or when configuring a server to - * handle any URL is not possible. - * - * @param base - optional base to provide. Defaults to `location.pathname + location.search` If there is a `` tag - * in the `head`, its value will be ignored in favor of this parameter **but note it affects all the history.pushState() - * calls**, meaning that if you use a `` tag, it's `href` value **has to match this parameter** (ignoring anything - * after the `#`). - * - * @example - * ```js - * // at https://example.com/folder - * createWebHashHistory() // gives a url of `https://example.com/folder#` - * createWebHashHistory('/folder/') // gives a url of `https://example.com/folder/#` - * // if the `#` is provided in the base, it won't be added by `createWebHashHistory` - * createWebHashHistory('/folder/#/app/') // gives a url of `https://example.com/folder/#/app/` - * // you should avoid doing this because it changes the original url and breaks copying urls - * createWebHashHistory('/other-folder/') // gives a url of `https://example.com/other-folder/#` - * - * // at file:///usr/etc/folder/index.html - * // for locations with no `host`, the base is ignored - * createWebHashHistory('/iAmIgnored') // gives a url of `file:///usr/etc/folder/index.html#` - * ``` - */ -function createWebHashHistory(base) { - // Make sure this implementation is fine in terms of encoding, specially for IE11 - // for `file://`, directly use the pathname and ignore the base - // location.pathname contains an initial `/` even at the root: `https://example.com` - base = location.host ? base || location.pathname + location.search : ''; - // allow the user to provide a `#` in the middle: `/base/#/app` - if (!base.includes('#')) - base += '#'; - if (!base.endsWith('#/') && !base.endsWith('#')) { - warn(`A hash base must end with a "#":\n"${base}" should be "${base.replace(/#.*$/, '#')}".`); - } - return createWebHistory(base); -} - -function isRouteLocation(route) { - return typeof route === 'string' || (route && typeof route === 'object'); -} -function isRouteName(name) { - return typeof name === 'string' || typeof name === 'symbol'; -} - -/** - * Initial route location where the router is. Can be used in navigation guards - * to differentiate the initial navigation. - * - * @example - * ```js - * import { START_LOCATION } from 'vue-router' - * - * router.beforeEach((to, from) => { - * if (from === START_LOCATION) { - * // initial navigation - * } - * }) - * ``` - */ -const START_LOCATION_NORMALIZED = { - path: '/', - name: undefined, - params: {}, - query: {}, - hash: '', - fullPath: '/', - matched: [], - meta: {}, - redirectedFrom: undefined, -}; - -const NavigationFailureSymbol = Symbol('navigation failure' ); -/** - * Enumeration with all possible types for navigation failures. Can be passed to - * {@link isNavigationFailure} to check for specific failures. - */ -var NavigationFailureType; -(function (NavigationFailureType) { - /** - * An aborted navigation is a navigation that failed because a navigation - * guard returned `false` or called `next(false)` - */ - NavigationFailureType[NavigationFailureType["aborted"] = 4] = "aborted"; - /** - * A cancelled navigation is a navigation that failed because a more recent - * navigation finished started (not necessarily finished). - */ - NavigationFailureType[NavigationFailureType["cancelled"] = 8] = "cancelled"; - /** - * A duplicated navigation is a navigation that failed because it was - * initiated while already being at the exact same location. - */ - NavigationFailureType[NavigationFailureType["duplicated"] = 16] = "duplicated"; -})(NavigationFailureType || (NavigationFailureType = {})); -// DEV only debug messages -const ErrorTypeMessages = { - [1 /* ErrorTypes.MATCHER_NOT_FOUND */]({ location, currentLocation }) { - return `No match for\n ${JSON.stringify(location)}${currentLocation - ? '\nwhile being at\n' + JSON.stringify(currentLocation) - : ''}`; - }, - [2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */]({ from, to, }) { - return `Redirected from "${from.fullPath}" to "${stringifyRoute(to)}" via a navigation guard.`; - }, - [4 /* ErrorTypes.NAVIGATION_ABORTED */]({ from, to }) { - return `Navigation aborted from "${from.fullPath}" to "${to.fullPath}" via a navigation guard.`; - }, - [8 /* ErrorTypes.NAVIGATION_CANCELLED */]({ from, to }) { - return `Navigation cancelled from "${from.fullPath}" to "${to.fullPath}" with a new navigation.`; - }, - [16 /* ErrorTypes.NAVIGATION_DUPLICATED */]({ from, to }) { - return `Avoided redundant navigation to current location: "${from.fullPath}".`; - }, -}; -function createRouterError(type, params) { - // keep full error messages in cjs versions - { - return assign(new Error(ErrorTypeMessages[type](params)), { - type, - [NavigationFailureSymbol]: true, - }, params); - } -} -function isNavigationFailure(error, type) { - return (error instanceof Error && - NavigationFailureSymbol in error && - (type == null || !!(error.type & type))); -} -const propertiesToLog = ['params', 'query', 'hash']; -function stringifyRoute(to) { - if (typeof to === 'string') - return to; - if ('path' in to) - return to.path; - const location = {}; - for (const key of propertiesToLog) { - if (key in to) - location[key] = to[key]; - } - return JSON.stringify(location, null, 2); -} - -// default pattern for a param: non-greedy everything but / -const BASE_PARAM_PATTERN = '[^/]+?'; -const BASE_PATH_PARSER_OPTIONS = { - sensitive: false, - strict: false, - start: true, - end: true, -}; -// Special Regex characters that must be escaped in static tokens -const REGEX_CHARS_RE = /[.+*?^${}()[\]/\\]/g; -/** - * Creates a path parser from an array of Segments (a segment is an array of Tokens) - * - * @param segments - array of segments returned by tokenizePath - * @param extraOptions - optional options for the regexp - * @returns a PathParser - */ -function tokensToParser(segments, extraOptions) { - const options = assign({}, BASE_PATH_PARSER_OPTIONS, extraOptions); - // the amount of scores is the same as the length of segments except for the root segment "/" - const score = []; - // the regexp as a string - let pattern = options.start ? '^' : ''; - // extracted keys - const keys = []; - for (const segment of segments) { - // the root segment needs special treatment - const segmentScores = segment.length ? [] : [90 /* PathScore.Root */]; - // allow trailing slash - if (options.strict && !segment.length) - pattern += '/'; - for (let tokenIndex = 0; tokenIndex < segment.length; tokenIndex++) { - const token = segment[tokenIndex]; - // resets the score if we are inside a sub-segment /:a-other-:b - let subSegmentScore = 40 /* PathScore.Segment */ + - (options.sensitive ? 0.25 /* PathScore.BonusCaseSensitive */ : 0); - if (token.type === 0 /* TokenType.Static */) { - // prepend the slash if we are starting a new segment - if (!tokenIndex) - pattern += '/'; - pattern += token.value.replace(REGEX_CHARS_RE, '\\$&'); - subSegmentScore += 40 /* PathScore.Static */; - } - else if (token.type === 1 /* TokenType.Param */) { - const { value, repeatable, optional, regexp } = token; - keys.push({ - name: value, - repeatable, - optional, - }); - const re = regexp ? regexp : BASE_PARAM_PATTERN; - // the user provided a custom regexp /:id(\\d+) - if (re !== BASE_PARAM_PATTERN) { - subSegmentScore += 10 /* PathScore.BonusCustomRegExp */; - // make sure the regexp is valid before using it - try { - new RegExp(`(${re})`); - } - catch (err) { - throw new Error(`Invalid custom RegExp for param "${value}" (${re}): ` + - err.message); - } - } - // when we repeat we must take care of the repeating leading slash - let subPattern = repeatable ? `((?:${re})(?:/(?:${re}))*)` : `(${re})`; - // prepend the slash if we are starting a new segment - if (!tokenIndex) - subPattern = - // avoid an optional / if there are more segments e.g. /:p?-static - // or /:p?-:p2 - optional && segment.length < 2 - ? `(?:/${subPattern})` - : '/' + subPattern; - if (optional) - subPattern += '?'; - pattern += subPattern; - subSegmentScore += 20 /* PathScore.Dynamic */; - if (optional) - subSegmentScore += -8 /* PathScore.BonusOptional */; - if (repeatable) - subSegmentScore += -20 /* PathScore.BonusRepeatable */; - if (re === '.*') - subSegmentScore += -50 /* PathScore.BonusWildcard */; - } - segmentScores.push(subSegmentScore); - } - // an empty array like /home/ -> [[{home}], []] - // if (!segment.length) pattern += '/' - score.push(segmentScores); - } - // only apply the strict bonus to the last score - if (options.strict && options.end) { - const i = score.length - 1; - score[i][score[i].length - 1] += 0.7000000000000001 /* PathScore.BonusStrict */; - } - // TODO: dev only warn double trailing slash - if (!options.strict) - pattern += '/?'; - if (options.end) - pattern += '$'; - // allow paths like /dynamic to only match dynamic or dynamic/... but not dynamic_something_else - else if (options.strict) - pattern += '(?:/|$)'; - const re = new RegExp(pattern, options.sensitive ? '' : 'i'); - function parse(path) { - const match = path.match(re); - const params = {}; - if (!match) - return null; - for (let i = 1; i < match.length; i++) { - const value = match[i] || ''; - const key = keys[i - 1]; - params[key.name] = value && key.repeatable ? value.split('/') : value; - } - return params; - } - function stringify(params) { - let path = ''; - // for optional parameters to allow to be empty - let avoidDuplicatedSlash = false; - for (const segment of segments) { - if (!avoidDuplicatedSlash || !path.endsWith('/')) - path += '/'; - avoidDuplicatedSlash = false; - for (const token of segment) { - if (token.type === 0 /* TokenType.Static */) { - path += token.value; - } - else if (token.type === 1 /* TokenType.Param */) { - const { value, repeatable, optional } = token; - const param = value in params ? params[value] : ''; - if (isArray(param) && !repeatable) { - throw new Error(`Provided param "${value}" is an array but it is not repeatable (* or + modifiers)`); - } - const text = isArray(param) - ? param.join('/') - : param; - if (!text) { - if (optional) { - // if we have more than one optional param like /:a?-static we don't need to care about the optional param - if (segment.length < 2) { - // remove the last slash as we could be at the end - if (path.endsWith('/')) - path = path.slice(0, -1); - // do not append a slash on the next iteration - else - avoidDuplicatedSlash = true; - } - } - else - throw new Error(`Missing required param "${value}"`); - } - path += text; - } - } - } - // avoid empty path when we have multiple optional params - return path || '/'; - } - return { - re, - score, - keys, - parse, - stringify, - }; -} -/** - * Compares an array of numbers as used in PathParser.score and returns a - * number. This function can be used to `sort` an array - * - * @param a - first array of numbers - * @param b - second array of numbers - * @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b - * should be sorted first - */ -function compareScoreArray(a, b) { - let i = 0; - while (i < a.length && i < b.length) { - const diff = b[i] - a[i]; - // only keep going if diff === 0 - if (diff) - return diff; - i++; - } - // if the last subsegment was Static, the shorter segments should be sorted first - // otherwise sort the longest segment first - if (a.length < b.length) { - return a.length === 1 && a[0] === 40 /* PathScore.Static */ + 40 /* PathScore.Segment */ - ? -1 - : 1; - } - else if (a.length > b.length) { - return b.length === 1 && b[0] === 40 /* PathScore.Static */ + 40 /* PathScore.Segment */ - ? 1 - : -1; - } - return 0; -} -/** - * Compare function that can be used with `sort` to sort an array of PathParser - * - * @param a - first PathParser - * @param b - second PathParser - * @returns 0 if both are equal, < 0 if a should be sorted first, > 0 if b - */ -function comparePathParserScore(a, b) { - let i = 0; - const aScore = a.score; - const bScore = b.score; - while (i < aScore.length && i < bScore.length) { - const comp = compareScoreArray(aScore[i], bScore[i]); - // do not return if both are equal - if (comp) - return comp; - i++; - } - if (Math.abs(bScore.length - aScore.length) === 1) { - if (isLastScoreNegative(aScore)) - return 1; - if (isLastScoreNegative(bScore)) - return -1; - } - // if a and b share the same score entries but b has more, sort b first - return bScore.length - aScore.length; - // this is the ternary version - // return aScore.length < bScore.length - // ? 1 - // : aScore.length > bScore.length - // ? -1 - // : 0 -} -/** - * This allows detecting splats at the end of a path: /home/:id(.*)* - * - * @param score - score to check - * @returns true if the last entry is negative - */ -function isLastScoreNegative(score) { - const last = score[score.length - 1]; - return score.length > 0 && last[last.length - 1] < 0; -} - -const ROOT_TOKEN = { - type: 0 /* TokenType.Static */, - value: '', -}; -const VALID_PARAM_RE = /[a-zA-Z0-9_]/; -// After some profiling, the cache seems to be unnecessary because tokenizePath -// (the slowest part of adding a route) is very fast -// const tokenCache = new Map() -function tokenizePath(path) { - if (!path) - return [[]]; - if (path === '/') - return [[ROOT_TOKEN]]; - if (!path.startsWith('/')) { - throw new Error(`Route paths should start with a "/": "${path}" should be "/${path}".` - ); - } - // if (tokenCache.has(path)) return tokenCache.get(path)! - function crash(message) { - throw new Error(`ERR (${state})/"${buffer}": ${message}`); - } - let state = 0 /* TokenizerState.Static */; - let previousState = state; - const tokens = []; - // the segment will always be valid because we get into the initial state - // with the leading / - let segment; - function finalizeSegment() { - if (segment) - tokens.push(segment); - segment = []; - } - // index on the path - let i = 0; - // char at index - let char; - // buffer of the value read - let buffer = ''; - // custom regexp for a param - let customRe = ''; - function consumeBuffer() { - if (!buffer) - return; - if (state === 0 /* TokenizerState.Static */) { - segment.push({ - type: 0 /* TokenType.Static */, - value: buffer, - }); - } - else if (state === 1 /* TokenizerState.Param */ || - state === 2 /* TokenizerState.ParamRegExp */ || - state === 3 /* TokenizerState.ParamRegExpEnd */) { - if (segment.length > 1 && (char === '*' || char === '+')) - crash(`A repeatable param (${buffer}) must be alone in its segment. eg: '/:ids+.`); - segment.push({ - type: 1 /* TokenType.Param */, - value: buffer, - regexp: customRe, - repeatable: char === '*' || char === '+', - optional: char === '*' || char === '?', - }); - } - else { - crash('Invalid state to consume buffer'); - } - buffer = ''; - } - function addCharToBuffer() { - buffer += char; - } - while (i < path.length) { - char = path[i++]; - if (char === '\\' && state !== 2 /* TokenizerState.ParamRegExp */) { - previousState = state; - state = 4 /* TokenizerState.EscapeNext */; - continue; - } - switch (state) { - case 0 /* TokenizerState.Static */: - if (char === '/') { - if (buffer) { - consumeBuffer(); - } - finalizeSegment(); - } - else if (char === ':') { - consumeBuffer(); - state = 1 /* TokenizerState.Param */; - } - else { - addCharToBuffer(); - } - break; - case 4 /* TokenizerState.EscapeNext */: - addCharToBuffer(); - state = previousState; - break; - case 1 /* TokenizerState.Param */: - if (char === '(') { - state = 2 /* TokenizerState.ParamRegExp */; - } - else if (VALID_PARAM_RE.test(char)) { - addCharToBuffer(); - } - else { - consumeBuffer(); - state = 0 /* TokenizerState.Static */; - // go back one character if we were not modifying - if (char !== '*' && char !== '?' && char !== '+') - i--; - } - break; - case 2 /* TokenizerState.ParamRegExp */: - // TODO: is it worth handling nested regexp? like :p(?:prefix_([^/]+)_suffix) - // it already works by escaping the closing ) - // https://paths.esm.dev/?p=AAMeJbiAwQEcDKbAoAAkP60PG2R6QAvgNaA6AFACM2ABuQBB# - // is this really something people need since you can also write - // /prefix_:p()_suffix - if (char === ')') { - // handle the escaped ) - if (customRe[customRe.length - 1] == '\\') - customRe = customRe.slice(0, -1) + char; - else - state = 3 /* TokenizerState.ParamRegExpEnd */; - } - else { - customRe += char; - } - break; - case 3 /* TokenizerState.ParamRegExpEnd */: - // same as finalizing a param - consumeBuffer(); - state = 0 /* TokenizerState.Static */; - // go back one character if we were not modifying - if (char !== '*' && char !== '?' && char !== '+') - i--; - customRe = ''; - break; - default: - crash('Unknown state'); - break; - } - } - if (state === 2 /* TokenizerState.ParamRegExp */) - crash(`Unfinished custom RegExp for param "${buffer}"`); - consumeBuffer(); - finalizeSegment(); - // tokenCache.set(path, tokens) - return tokens; -} - -function createRouteRecordMatcher(record, parent, options) { - const parser = tokensToParser(tokenizePath(record.path), options); - // warn against params with the same name - { - const existingKeys = new Set(); - for (const key of parser.keys) { - if (existingKeys.has(key.name)) - warn(`Found duplicated params with name "${key.name}" for path "${record.path}". Only the last one will be available on "$route.params".`); - existingKeys.add(key.name); - } - } - const matcher = assign(parser, { - record, - parent, - // these needs to be populated by the parent - children: [], - alias: [], - }); - if (parent) { - // both are aliases or both are not aliases - // we don't want to mix them because the order is used when - // passing originalRecord in Matcher.addRoute - if (!matcher.record.aliasOf === !parent.record.aliasOf) - parent.children.push(matcher); - } - return matcher; -} - -/** - * Creates a Router Matcher. - * - * @internal - * @param routes - array of initial routes - * @param globalOptions - global route options - */ -function createRouterMatcher(routes, globalOptions) { - // normalized ordered array of matchers - const matchers = []; - const matcherMap = new Map(); - globalOptions = mergeOptions({ strict: false, end: true, sensitive: false }, globalOptions); - function getRecordMatcher(name) { - return matcherMap.get(name); - } - function addRoute(record, parent, originalRecord) { - // used later on to remove by name - const isRootAdd = !originalRecord; - const mainNormalizedRecord = normalizeRouteRecord(record); - { - checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent); - } - // we might be the child of an alias - mainNormalizedRecord.aliasOf = originalRecord && originalRecord.record; - const options = mergeOptions(globalOptions, record); - // generate an array of records to correctly handle aliases - const normalizedRecords = [ - mainNormalizedRecord, - ]; - if ('alias' in record) { - const aliases = typeof record.alias === 'string' ? [record.alias] : record.alias; - for (const alias of aliases) { - normalizedRecords.push(assign({}, mainNormalizedRecord, { - // this allows us to hold a copy of the `components` option - // so that async components cache is hold on the original record - components: originalRecord - ? originalRecord.record.components - : mainNormalizedRecord.components, - path: alias, - // we might be the child of an alias - aliasOf: originalRecord - ? originalRecord.record - : mainNormalizedRecord, - // the aliases are always of the same kind as the original since they - // are defined on the same record - })); - } - } - let matcher; - let originalMatcher; - for (const normalizedRecord of normalizedRecords) { - const { path } = normalizedRecord; - // Build up the path for nested routes if the child isn't an absolute - // route. Only add the / delimiter if the child path isn't empty and if the - // parent path doesn't have a trailing slash - if (parent && path[0] !== '/') { - const parentPath = parent.record.path; - const connectingSlash = parentPath[parentPath.length - 1] === '/' ? '' : '/'; - normalizedRecord.path = - parent.record.path + (path && connectingSlash + path); - } - if (normalizedRecord.path === '*') { - throw new Error('Catch all routes ("*") must now be defined using a param with a custom regexp.\n' + - 'See more at https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes.'); - } - // create the object beforehand, so it can be passed to children - matcher = createRouteRecordMatcher(normalizedRecord, parent, options); - if (parent && path[0] === '/') - checkMissingParamsInAbsolutePath(matcher, parent); - // if we are an alias we must tell the original record that we exist, - // so we can be removed - if (originalRecord) { - originalRecord.alias.push(matcher); - { - checkSameParams(originalRecord, matcher); - } - } - else { - // otherwise, the first record is the original and others are aliases - originalMatcher = originalMatcher || matcher; - if (originalMatcher !== matcher) - originalMatcher.alias.push(matcher); - // remove the route if named and only for the top record (avoid in nested calls) - // this works because the original record is the first one - if (isRootAdd && record.name && !isAliasRecord(matcher)) - removeRoute(record.name); - } - if (mainNormalizedRecord.children) { - const children = mainNormalizedRecord.children; - for (let i = 0; i < children.length; i++) { - addRoute(children[i], matcher, originalRecord && originalRecord.children[i]); - } - } - // if there was no original record, then the first one was not an alias and all - // other aliases (if any) need to reference this record when adding children - originalRecord = originalRecord || matcher; - // TODO: add normalized records for more flexibility - // if (parent && isAliasRecord(originalRecord)) { - // parent.children.push(originalRecord) - // } - // Avoid adding a record that doesn't display anything. This allows passing through records without a component to - // not be reached and pass through the catch all route - if ((matcher.record.components && - Object.keys(matcher.record.components).length) || - matcher.record.name || - matcher.record.redirect) { - insertMatcher(matcher); - } - } - return originalMatcher - ? () => { - // since other matchers are aliases, they should be removed by the original matcher - removeRoute(originalMatcher); - } - : noop; - } - function removeRoute(matcherRef) { - if (isRouteName(matcherRef)) { - const matcher = matcherMap.get(matcherRef); - if (matcher) { - matcherMap.delete(matcherRef); - matchers.splice(matchers.indexOf(matcher), 1); - matcher.children.forEach(removeRoute); - matcher.alias.forEach(removeRoute); - } - } - else { - const index = matchers.indexOf(matcherRef); - if (index > -1) { - matchers.splice(index, 1); - if (matcherRef.record.name) - matcherMap.delete(matcherRef.record.name); - matcherRef.children.forEach(removeRoute); - matcherRef.alias.forEach(removeRoute); - } - } - } - function getRoutes() { - return matchers; - } - function insertMatcher(matcher) { - let i = 0; - while (i < matchers.length && - comparePathParserScore(matcher, matchers[i]) >= 0 && - // Adding children with empty path should still appear before the parent - // https://github.com/vuejs/router/issues/1124 - (matcher.record.path !== matchers[i].record.path || - !isRecordChildOf(matcher, matchers[i]))) - i++; - matchers.splice(i, 0, matcher); - // only add the original record to the name map - if (matcher.record.name && !isAliasRecord(matcher)) - matcherMap.set(matcher.record.name, matcher); - } - function resolve(location, currentLocation) { - let matcher; - let params = {}; - let path; - let name; - if ('name' in location && location.name) { - matcher = matcherMap.get(location.name); - if (!matcher) - throw createRouterError(1 /* ErrorTypes.MATCHER_NOT_FOUND */, { - location, - }); - // warn if the user is passing invalid params so they can debug it better when they get removed - { - const invalidParams = Object.keys(location.params || {}).filter(paramName => !matcher.keys.find(k => k.name === paramName)); - if (invalidParams.length) { - warn(`Discarded invalid param(s) "${invalidParams.join('", "')}" when navigating. See https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md#414-2022-08-22 for more details.`); - } - } - name = matcher.record.name; - params = assign( - // paramsFromLocation is a new object - paramsFromLocation(currentLocation.params, - // only keep params that exist in the resolved location - // TODO: only keep optional params coming from a parent record - matcher.keys.filter(k => !k.optional).map(k => k.name)), - // discard any existing params in the current location that do not exist here - // #1497 this ensures better active/exact matching - location.params && - paramsFromLocation(location.params, matcher.keys.map(k => k.name))); - // throws if cannot be stringified - path = matcher.stringify(params); - } - else if ('path' in location) { - // no need to resolve the path with the matcher as it was provided - // this also allows the user to control the encoding - path = location.path; - if (!path.startsWith('/')) { - warn(`The Matcher cannot resolve relative paths but received "${path}". Unless you directly called \`matcher.resolve("${path}")\`, this is probably a bug in vue-router. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/router.`); - } - matcher = matchers.find(m => m.re.test(path)); - // matcher should have a value after the loop - if (matcher) { - // we know the matcher works because we tested the regexp - params = matcher.parse(path); - name = matcher.record.name; - } - // location is a relative path - } - else { - // match by name or path of current route - matcher = currentLocation.name - ? matcherMap.get(currentLocation.name) - : matchers.find(m => m.re.test(currentLocation.path)); - if (!matcher) - throw createRouterError(1 /* ErrorTypes.MATCHER_NOT_FOUND */, { - location, - currentLocation, - }); - name = matcher.record.name; - // since we are navigating to the same location, we don't need to pick the - // params like when `name` is provided - params = assign({}, currentLocation.params, location.params); - path = matcher.stringify(params); - } - const matched = []; - let parentMatcher = matcher; - while (parentMatcher) { - // reversed order so parents are at the beginning - matched.unshift(parentMatcher.record); - parentMatcher = parentMatcher.parent; - } - return { - name, - path, - params, - matched, - meta: mergeMetaFields(matched), - }; - } - // add initial routes - routes.forEach(route => addRoute(route)); - return { addRoute, resolve, removeRoute, getRoutes, getRecordMatcher }; -} -function paramsFromLocation(params, keys) { - const newParams = {}; - for (const key of keys) { - if (key in params) - newParams[key] = params[key]; - } - return newParams; -} -/** - * Normalizes a RouteRecordRaw. Creates a copy - * - * @param record - * @returns the normalized version - */ -function normalizeRouteRecord(record) { - return { - path: record.path, - redirect: record.redirect, - name: record.name, - meta: record.meta || {}, - aliasOf: undefined, - beforeEnter: record.beforeEnter, - props: normalizeRecordProps(record), - children: record.children || [], - instances: {}, - leaveGuards: new Set(), - updateGuards: new Set(), - enterCallbacks: {}, - components: 'components' in record - ? record.components || null - : record.component && { default: record.component }, - }; -} -/** - * Normalize the optional `props` in a record to always be an object similar to - * components. Also accept a boolean for components. - * @param record - */ -function normalizeRecordProps(record) { - const propsObject = {}; - // props does not exist on redirect records, but we can set false directly - const props = record.props || false; - if ('component' in record) { - propsObject.default = props; - } - else { - // NOTE: we could also allow a function to be applied to every component. - // Would need user feedback for use cases - for (const name in record.components) - propsObject[name] = typeof props === 'boolean' ? props : props[name]; - } - return propsObject; -} -/** - * Checks if a record or any of its parent is an alias - * @param record - */ -function isAliasRecord(record) { - while (record) { - if (record.record.aliasOf) - return true; - record = record.parent; - } - return false; -} -/** - * Merge meta fields of an array of records - * - * @param matched - array of matched records - */ -function mergeMetaFields(matched) { - return matched.reduce((meta, record) => assign(meta, record.meta), {}); -} -function mergeOptions(defaults, partialOptions) { - const options = {}; - for (const key in defaults) { - options[key] = key in partialOptions ? partialOptions[key] : defaults[key]; - } - return options; -} -function isSameParam(a, b) { - return (a.name === b.name && - a.optional === b.optional && - a.repeatable === b.repeatable); -} -/** - * Check if a path and its alias have the same required params - * - * @param a - original record - * @param b - alias record - */ -function checkSameParams(a, b) { - for (const key of a.keys) { - if (!key.optional && !b.keys.find(isSameParam.bind(null, key))) - return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`); - } - for (const key of b.keys) { - if (!key.optional && !a.keys.find(isSameParam.bind(null, key))) - return warn(`Alias "${b.record.path}" and the original record: "${a.record.path}" must have the exact same param named "${key.name}"`); - } -} -/** - * A route with a name and a child with an empty path without a name should warn when adding the route - * - * @param mainNormalizedRecord - RouteRecordNormalized - * @param parent - RouteRecordMatcher - */ -function checkChildMissingNameWithEmptyPath(mainNormalizedRecord, parent) { - if (parent && - parent.record.name && - !mainNormalizedRecord.name && - !mainNormalizedRecord.path) { - warn(`The route named "${String(parent.record.name)}" has a child without a name and an empty path. Using that name won't render the empty path child so you probably want to move the name to the child instead. If this is intentional, add a name to the child route to remove the warning.`); - } -} -function checkMissingParamsInAbsolutePath(record, parent) { - for (const key of parent.keys) { - if (!record.keys.find(isSameParam.bind(null, key))) - return warn(`Absolute path "${record.record.path}" must have the exact same param named "${key.name}" as its parent "${parent.record.path}".`); - } -} -function isRecordChildOf(record, parent) { - return parent.children.some(child => child === record || isRecordChildOf(record, child)); -} - -/** - * Encoding Rules ␣ = Space Path: ␣ " < > # ? { } Query: ␣ " < > # & = Hash: ␣ " - * < > ` - * - * On top of that, the RFC3986 (https://tools.ietf.org/html/rfc3986#section-2.2) - * defines some extra characters to be encoded. Most browsers do not encode them - * in encodeURI https://github.com/whatwg/url/issues/369, so it may be safer to - * also encode `!'()*`. Leaving un-encoded only ASCII alphanumeric(`a-zA-Z0-9`) - * plus `-._~`. This extra safety should be applied to query by patching the - * string returned by encodeURIComponent encodeURI also encodes `[\]^`. `\` - * should be encoded to avoid ambiguity. Browsers (IE, FF, C) transform a `\` - * into a `/` if directly typed in. The _backtick_ (`````) should also be - * encoded everywhere because some browsers like FF encode it when directly - * written while others don't. Safari and IE don't encode ``"<>{}``` in hash. - */ -// const EXTRA_RESERVED_RE = /[!'()*]/g -// const encodeReservedReplacer = (c: string) => '%' + c.charCodeAt(0).toString(16) -const HASH_RE = /#/g; // %23 -const AMPERSAND_RE = /&/g; // %26 -const SLASH_RE = /\//g; // %2F -const EQUAL_RE = /=/g; // %3D -const IM_RE = /\?/g; // %3F -const PLUS_RE = /\+/g; // %2B -/** - * NOTE: It's not clear to me if we should encode the + symbol in queries, it - * seems to be less flexible than not doing so and I can't find out the legacy - * systems requiring this for regular requests like text/html. In the standard, - * the encoding of the plus character is only mentioned for - * application/x-www-form-urlencoded - * (https://url.spec.whatwg.org/#urlencoded-parsing) and most browsers seems lo - * leave the plus character as is in queries. To be more flexible, we allow the - * plus character on the query, but it can also be manually encoded by the user. - * - * Resources: - * - https://url.spec.whatwg.org/#urlencoded-parsing - * - https://stackoverflow.com/questions/1634271/url-encoding-the-space-character-or-20 - */ -const ENC_BRACKET_OPEN_RE = /%5B/g; // [ -const ENC_BRACKET_CLOSE_RE = /%5D/g; // ] -const ENC_CARET_RE = /%5E/g; // ^ -const ENC_BACKTICK_RE = /%60/g; // ` -const ENC_CURLY_OPEN_RE = /%7B/g; // { -const ENC_PIPE_RE = /%7C/g; // | -const ENC_CURLY_CLOSE_RE = /%7D/g; // } -const ENC_SPACE_RE = /%20/g; // } -/** - * Encode characters that need to be encoded on the path, search and hash - * sections of the URL. - * - * @internal - * @param text - string to encode - * @returns encoded string - */ -function commonEncode(text) { - return encodeURI('' + text) - .replace(ENC_PIPE_RE, '|') - .replace(ENC_BRACKET_OPEN_RE, '[') - .replace(ENC_BRACKET_CLOSE_RE, ']'); -} -/** - * Encode characters that need to be encoded on the hash section of the URL. - * - * @param text - string to encode - * @returns encoded string - */ -function encodeHash(text) { - return commonEncode(text) - .replace(ENC_CURLY_OPEN_RE, '{') - .replace(ENC_CURLY_CLOSE_RE, '}') - .replace(ENC_CARET_RE, '^'); -} -/** - * Encode characters that need to be encoded query values on the query - * section of the URL. - * - * @param text - string to encode - * @returns encoded string - */ -function encodeQueryValue(text) { - return (commonEncode(text) - // Encode the space as +, encode the + to differentiate it from the space - .replace(PLUS_RE, '%2B') - .replace(ENC_SPACE_RE, '+') - .replace(HASH_RE, '%23') - .replace(AMPERSAND_RE, '%26') - .replace(ENC_BACKTICK_RE, '`') - .replace(ENC_CURLY_OPEN_RE, '{') - .replace(ENC_CURLY_CLOSE_RE, '}') - .replace(ENC_CARET_RE, '^')); -} -/** - * Like `encodeQueryValue` but also encodes the `=` character. - * - * @param text - string to encode - */ -function encodeQueryKey(text) { - return encodeQueryValue(text).replace(EQUAL_RE, '%3D'); -} -/** - * Encode characters that need to be encoded on the path section of the URL. - * - * @param text - string to encode - * @returns encoded string - */ -function encodePath(text) { - return commonEncode(text).replace(HASH_RE, '%23').replace(IM_RE, '%3F'); -} -/** - * Encode characters that need to be encoded on the path section of the URL as a - * param. This function encodes everything {@link encodePath} does plus the - * slash (`/`) character. If `text` is `null` or `undefined`, returns an empty - * string instead. - * - * @param text - string to encode - * @returns encoded string - */ -function encodeParam(text) { - return text == null ? '' : encodePath(text).replace(SLASH_RE, '%2F'); -} -/** - * Decode text using `decodeURIComponent`. Returns the original text if it - * fails. - * - * @param text - string to decode - * @returns decoded string - */ -function decode(text) { - try { - return decodeURIComponent('' + text); - } - catch (err) { - warn(`Error decoding "${text}". Using original value`); - } - return '' + text; -} - -/** - * Transforms a queryString into a {@link LocationQuery} object. Accept both, a - * version with the leading `?` and without Should work as URLSearchParams - - * @internal - * - * @param search - search string to parse - * @returns a query object - */ -function parseQuery(search) { - const query = {}; - // avoid creating an object with an empty key and empty value - // because of split('&') - if (search === '' || search === '?') - return query; - const hasLeadingIM = search[0] === '?'; - const searchParams = (hasLeadingIM ? search.slice(1) : search).split('&'); - for (let i = 0; i < searchParams.length; ++i) { - // pre decode the + into space - const searchParam = searchParams[i].replace(PLUS_RE, ' '); - // allow the = character - const eqPos = searchParam.indexOf('='); - const key = decode(eqPos < 0 ? searchParam : searchParam.slice(0, eqPos)); - const value = eqPos < 0 ? null : decode(searchParam.slice(eqPos + 1)); - if (key in query) { - // an extra variable for ts types - let currentValue = query[key]; - if (!isArray(currentValue)) { - currentValue = query[key] = [currentValue]; - } - currentValue.push(value); - } - else { - query[key] = value; - } - } - return query; -} -/** - * Stringifies a {@link LocationQueryRaw} object. Like `URLSearchParams`, it - * doesn't prepend a `?` - * - * @internal - * - * @param query - query object to stringify - * @returns string version of the query without the leading `?` - */ -function stringifyQuery(query) { - let search = ''; - for (let key in query) { - const value = query[key]; - key = encodeQueryKey(key); - if (value == null) { - // only null adds the value - if (value !== undefined) { - search += (search.length ? '&' : '') + key; - } - continue; - } - // keep null values - const values = isArray(value) - ? value.map(v => v && encodeQueryValue(v)) - : [value && encodeQueryValue(value)]; - values.forEach(value => { - // skip undefined values in arrays as if they were not present - // smaller code than using filter - if (value !== undefined) { - // only append & with non-empty search - search += (search.length ? '&' : '') + key; - if (value != null) - search += '=' + value; - } - }); - } - return search; -} -/** - * Transforms a {@link LocationQueryRaw} into a {@link LocationQuery} by casting - * numbers into strings, removing keys with an undefined value and replacing - * undefined with null in arrays - * - * @param query - query object to normalize - * @returns a normalized query object - */ -function normalizeQuery(query) { - const normalizedQuery = {}; - for (const key in query) { - const value = query[key]; - if (value !== undefined) { - normalizedQuery[key] = isArray(value) - ? value.map(v => (v == null ? null : '' + v)) - : value == null - ? value - : '' + value; - } - } - return normalizedQuery; -} - -/** - * RouteRecord being rendered by the closest ancestor Router View. Used for - * `onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View - * Location Matched - * - * @internal - */ -const matchedRouteKey = Symbol('router view location matched' ); -/** - * Allows overriding the router view depth to control which component in - * `matched` is rendered. rvd stands for Router View Depth - * - * @internal - */ -const viewDepthKey = Symbol('router view depth' ); -/** - * Allows overriding the router instance returned by `useRouter` in tests. r - * stands for router - * - * @internal - */ -const routerKey = Symbol('router' ); -/** - * Allows overriding the current route returned by `useRoute` in tests. rl - * stands for route location - * - * @internal - */ -const routeLocationKey = Symbol('route location' ); -/** - * Allows overriding the current route used by router-view. Internally this is - * used when the `route` prop is passed. - * - * @internal - */ -const routerViewLocationKey = Symbol('router view location' ); - -/** - * Create a list of callbacks that can be reset. Used to create before and after navigation guards list - */ -function useCallbacks() { - let handlers = []; - function add(handler) { - handlers.push(handler); - return () => { - const i = handlers.indexOf(handler); - if (i > -1) - handlers.splice(i, 1); - }; - } - function reset() { - handlers = []; - } - return { - add, - list: () => handlers, - reset, - }; -} - -function registerGuard(record, name, guard) { - const removeFromList = () => { - record[name].delete(guard); - }; - onUnmounted(removeFromList); - onDeactivated(removeFromList); - onActivated(() => { - record[name].add(guard); - }); - record[name].add(guard); -} -/** - * Add a navigation guard that triggers whenever the component for the current - * location is about to be left. Similar to {@link beforeRouteLeave} but can be - * used in any component. The guard is removed when the component is unmounted. - * - * @param leaveGuard - {@link NavigationGuard} - */ -function onBeforeRouteLeave(leaveGuard) { - if (!getCurrentInstance()) { - warn('getCurrentInstance() returned null. onBeforeRouteLeave() must be called at the top of a setup function'); - return; - } - const activeRecord = inject(matchedRouteKey, - // to avoid warning - {}).value; - if (!activeRecord) { - warn('No active route record was found when calling `onBeforeRouteLeave()`. Make sure you call this function inside a component child of . Maybe you called it inside of App.vue?'); - return; - } - registerGuard(activeRecord, 'leaveGuards', leaveGuard); -} -/** - * Add a navigation guard that triggers whenever the current location is about - * to be updated. Similar to {@link beforeRouteUpdate} but can be used in any - * component. The guard is removed when the component is unmounted. - * - * @param updateGuard - {@link NavigationGuard} - */ -function onBeforeRouteUpdate(updateGuard) { - if (!getCurrentInstance()) { - warn('getCurrentInstance() returned null. onBeforeRouteUpdate() must be called at the top of a setup function'); - return; - } - const activeRecord = inject(matchedRouteKey, - // to avoid warning - {}).value; - if (!activeRecord) { - warn('No active route record was found when calling `onBeforeRouteUpdate()`. Make sure you call this function inside a component child of . Maybe you called it inside of App.vue?'); - return; - } - registerGuard(activeRecord, 'updateGuards', updateGuard); -} -function guardToPromiseFn(guard, to, from, record, name) { - // keep a reference to the enterCallbackArray to prevent pushing callbacks if a new navigation took place - const enterCallbackArray = record && - // name is defined if record is because of the function overload - (record.enterCallbacks[name] = record.enterCallbacks[name] || []); - return () => new Promise((resolve, reject) => { - const next = (valid) => { - if (valid === false) { - reject(createRouterError(4 /* ErrorTypes.NAVIGATION_ABORTED */, { - from, - to, - })); - } - else if (valid instanceof Error) { - reject(valid); - } - else if (isRouteLocation(valid)) { - reject(createRouterError(2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */, { - from: to, - to: valid, - })); - } - else { - if (enterCallbackArray && - // since enterCallbackArray is truthy, both record and name also are - record.enterCallbacks[name] === enterCallbackArray && - typeof valid === 'function') { - enterCallbackArray.push(valid); - } - resolve(); - } - }; - // wrapping with Promise.resolve allows it to work with both async and sync guards - const guardReturn = guard.call(record && record.instances[name], to, from, canOnlyBeCalledOnce(next, to, from) ); - let guardCall = Promise.resolve(guardReturn); - if (guard.length < 3) - guardCall = guardCall.then(next); - if (guard.length > 2) { - const message = `The "next" callback was never called inside of ${guard.name ? '"' + guard.name + '"' : ''}:\n${guard.toString()}\n. If you are returning a value instead of calling "next", make sure to remove the "next" parameter from your function.`; - if (typeof guardReturn === 'object' && 'then' in guardReturn) { - guardCall = guardCall.then(resolvedValue => { - // @ts-expect-error: _called is added at canOnlyBeCalledOnce - if (!next._called) { - warn(message); - return Promise.reject(new Error('Invalid navigation guard')); - } - return resolvedValue; - }); - } - else if (guardReturn !== undefined) { - // @ts-expect-error: _called is added at canOnlyBeCalledOnce - if (!next._called) { - warn(message); - reject(new Error('Invalid navigation guard')); - return; - } - } - } - guardCall.catch(err => reject(err)); - }); -} -function canOnlyBeCalledOnce(next, to, from) { - let called = 0; - return function () { - if (called++ === 1) - warn(`The "next" callback was called more than once in one navigation guard when going from "${from.fullPath}" to "${to.fullPath}". It should be called exactly one time in each navigation guard. This will fail in production.`); - // @ts-expect-error: we put it in the original one because it's easier to check - next._called = true; - if (called === 1) - next.apply(null, arguments); - }; -} -function extractComponentsGuards(matched, guardType, to, from) { - const guards = []; - for (const record of matched) { - if (!record.components && !record.children.length) { - warn(`Record with path "${record.path}" is either missing a "component(s)"` + - ` or "children" property.`); - } - for (const name in record.components) { - let rawComponent = record.components[name]; - { - if (!rawComponent || - (typeof rawComponent !== 'object' && - typeof rawComponent !== 'function')) { - warn(`Component "${name}" in record with path "${record.path}" is not` + - ` a valid component. Received "${String(rawComponent)}".`); - // throw to ensure we stop here but warn to ensure the message isn't - // missed by the user - throw new Error('Invalid route component'); - } - else if ('then' in rawComponent) { - // warn if user wrote import('/component.vue') instead of () => - // import('./component.vue') - warn(`Component "${name}" in record with path "${record.path}" is a ` + - `Promise instead of a function that returns a Promise. Did you ` + - `write "import('./MyPage.vue')" instead of ` + - `"() => import('./MyPage.vue')" ? This will break in ` + - `production if not fixed.`); - const promise = rawComponent; - rawComponent = () => promise; - } - else if (rawComponent.__asyncLoader && - // warn only once per component - !rawComponent.__warnedDefineAsync) { - rawComponent.__warnedDefineAsync = true; - warn(`Component "${name}" in record with path "${record.path}" is defined ` + - `using "defineAsyncComponent()". ` + - `Write "() => import('./MyPage.vue')" instead of ` + - `"defineAsyncComponent(() => import('./MyPage.vue'))".`); - } - } - // skip update and leave guards if the route component is not mounted - if (guardType !== 'beforeRouteEnter' && !record.instances[name]) - continue; - if (isRouteComponent(rawComponent)) { - // __vccOpts is added by vue-class-component and contain the regular options - const options = rawComponent.__vccOpts || rawComponent; - const guard = options[guardType]; - guard && guards.push(guardToPromiseFn(guard, to, from, record, name)); - } - else { - // start requesting the chunk already - let componentPromise = rawComponent(); - if (!('catch' in componentPromise)) { - warn(`Component "${name}" in record with path "${record.path}" is a function that does not return a Promise. If you were passing a functional component, make sure to add a "displayName" to the component. This will break in production if not fixed.`); - componentPromise = Promise.resolve(componentPromise); - } - guards.push(() => componentPromise.then(resolved => { - if (!resolved) - return Promise.reject(new Error(`Couldn't resolve component "${name}" at "${record.path}"`)); - const resolvedComponent = isESModule(resolved) - ? resolved.default - : resolved; - // replace the function with the resolved component - // cannot be null or undefined because we went into the for loop - record.components[name] = resolvedComponent; - // __vccOpts is added by vue-class-component and contain the regular options - const options = resolvedComponent.__vccOpts || resolvedComponent; - const guard = options[guardType]; - return guard && guardToPromiseFn(guard, to, from, record, name)(); - })); - } - } - } - return guards; -} -/** - * Allows differentiating lazy components from functional components and vue-class-component - * @internal - * - * @param component - */ -function isRouteComponent(component) { - return (typeof component === 'object' || - 'displayName' in component || - 'props' in component || - '__vccOpts' in component); -} -/** - * Ensures a route is loaded, so it can be passed as o prop to ``. - * - * @param route - resolved route to load - */ -function loadRouteLocation(route) { - return route.matched.every(record => record.redirect) - ? Promise.reject(new Error('Cannot load a route that redirects.')) - : Promise.all(route.matched.map(record => record.components && - Promise.all(Object.keys(record.components).reduce((promises, name) => { - const rawComponent = record.components[name]; - if (typeof rawComponent === 'function' && - !('displayName' in rawComponent)) { - promises.push(rawComponent().then(resolved => { - if (!resolved) - return Promise.reject(new Error(`Couldn't resolve component "${name}" at "${record.path}". Ensure you passed a function that returns a promise.`)); - const resolvedComponent = isESModule(resolved) - ? resolved.default - : resolved; - // replace the function with the resolved component - // cannot be null or undefined because we went into the for loop - record.components[name] = resolvedComponent; - return; - })); - } - return promises; - }, [])))).then(() => route); -} - -// TODO: we could allow currentRoute as a prop to expose `isActive` and -// `isExactActive` behavior should go through an RFC -function useLink(props) { - const router = inject(routerKey); - const currentRoute = inject(routeLocationKey); - const route = computed(() => router.resolve(unref(props.to))); - const activeRecordIndex = computed(() => { - const { matched } = route.value; - const { length } = matched; - const routeMatched = matched[length - 1]; - const currentMatched = currentRoute.matched; - if (!routeMatched || !currentMatched.length) - return -1; - const index = currentMatched.findIndex(isSameRouteRecord.bind(null, routeMatched)); - if (index > -1) - return index; - // possible parent record - const parentRecordPath = getOriginalPath(matched[length - 2]); - return ( - // we are dealing with nested routes - length > 1 && - // if the parent and matched route have the same path, this link is - // referring to the empty child. Or we currently are on a different - // child of the same parent - getOriginalPath(routeMatched) === parentRecordPath && - // avoid comparing the child with its parent - currentMatched[currentMatched.length - 1].path !== parentRecordPath - ? currentMatched.findIndex(isSameRouteRecord.bind(null, matched[length - 2])) - : index); - }); - const isActive = computed(() => activeRecordIndex.value > -1 && - includesParams(currentRoute.params, route.value.params)); - const isExactActive = computed(() => activeRecordIndex.value > -1 && - activeRecordIndex.value === currentRoute.matched.length - 1 && - isSameRouteLocationParams(currentRoute.params, route.value.params)); - function navigate(e = {}) { - if (guardEvent(e)) { - return router[unref(props.replace) ? 'replace' : 'push'](unref(props.to) - // avoid uncaught errors are they are logged anyway - ).catch(noop); - } - return Promise.resolve(); - } - // devtools only - if (isBrowser) { - const instance = getCurrentInstance(); - if (instance) { - const linkContextDevtools = { - route: route.value, - isActive: isActive.value, - isExactActive: isExactActive.value, - }; - // @ts-expect-error: this is internal - instance.__vrl_devtools = instance.__vrl_devtools || []; - // @ts-expect-error: this is internal - instance.__vrl_devtools.push(linkContextDevtools); - watchEffect(() => { - linkContextDevtools.route = route.value; - linkContextDevtools.isActive = isActive.value; - linkContextDevtools.isExactActive = isExactActive.value; - }, { flush: 'post' }); - } - } - /** - * NOTE: update {@link _RouterLinkI}'s `$slots` type when updating this - */ - return { - route, - href: computed(() => route.value.href), - isActive, - isExactActive, - navigate, - }; -} -const RouterLinkImpl = /*#__PURE__*/ defineComponent({ - name: 'RouterLink', - compatConfig: { MODE: 3 }, - props: { - to: { - type: [String, Object], - required: true, - }, - replace: Boolean, - activeClass: String, - // inactiveClass: String, - exactActiveClass: String, - custom: Boolean, - ariaCurrentValue: { - type: String, - default: 'page', - }, - }, - useLink, - setup(props, { slots }) { - const link = reactive(useLink(props)); - const { options } = inject(routerKey); - const elClass = computed(() => ({ - [getLinkClass(props.activeClass, options.linkActiveClass, 'router-link-active')]: link.isActive, - // [getLinkClass( - // props.inactiveClass, - // options.linkInactiveClass, - // 'router-link-inactive' - // )]: !link.isExactActive, - [getLinkClass(props.exactActiveClass, options.linkExactActiveClass, 'router-link-exact-active')]: link.isExactActive, - })); - return () => { - const children = slots.default && slots.default(link); - return props.custom - ? children - : h('a', { - 'aria-current': link.isExactActive - ? props.ariaCurrentValue - : null, - href: link.href, - // this would override user added attrs but Vue will still add - // the listener, so we end up triggering both - onClick: link.navigate, - class: elClass.value, - }, children); - }; - }, -}); -// export the public type for h/tsx inference -// also to avoid inline import() in generated d.ts files -/** - * Component to render a link that triggers a navigation on click. - */ -const RouterLink = RouterLinkImpl; -function guardEvent(e) { - // don't redirect with control keys - if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) - return; - // don't redirect when preventDefault called - if (e.defaultPrevented) - return; - // don't redirect on right click - if (e.button !== undefined && e.button !== 0) - return; - // don't redirect if `target="_blank"` - // @ts-expect-error getAttribute does exist - if (e.currentTarget && e.currentTarget.getAttribute) { - // @ts-expect-error getAttribute exists - const target = e.currentTarget.getAttribute('target'); - if (/\b_blank\b/i.test(target)) - return; - } - // this may be a Weex event which doesn't have this method - if (e.preventDefault) - e.preventDefault(); - return true; -} -function includesParams(outer, inner) { - for (const key in inner) { - const innerValue = inner[key]; - const outerValue = outer[key]; - if (typeof innerValue === 'string') { - if (innerValue !== outerValue) - return false; - } - else { - if (!isArray(outerValue) || - outerValue.length !== innerValue.length || - innerValue.some((value, i) => value !== outerValue[i])) - return false; - } - } - return true; -} -/** - * Get the original path value of a record by following its aliasOf - * @param record - */ -function getOriginalPath(record) { - return record ? (record.aliasOf ? record.aliasOf.path : record.path) : ''; -} -/** - * Utility class to get the active class based on defaults. - * @param propClass - * @param globalClass - * @param defaultClass - */ -const getLinkClass = (propClass, globalClass, defaultClass) => propClass != null - ? propClass - : globalClass != null - ? globalClass - : defaultClass; - -const RouterViewImpl = /*#__PURE__*/ defineComponent({ - name: 'RouterView', - // #674 we manually inherit them - inheritAttrs: false, - props: { - name: { - type: String, - default: 'default', - }, - route: Object, - }, - // Better compat for @vue/compat users - // https://github.com/vuejs/router/issues/1315 - compatConfig: { MODE: 3 }, - setup(props, { attrs, slots }) { - warnDeprecatedUsage(); - const injectedRoute = inject(routerViewLocationKey); - const routeToDisplay = computed(() => props.route || injectedRoute.value); - const injectedDepth = inject(viewDepthKey, 0); - // The depth changes based on empty components option, which allows passthrough routes e.g. routes with children - // that are used to reuse the `path` property - const depth = computed(() => { - let initialDepth = unref(injectedDepth); - const { matched } = routeToDisplay.value; - let matchedRoute; - while ((matchedRoute = matched[initialDepth]) && - !matchedRoute.components) { - initialDepth++; - } - return initialDepth; - }); - const matchedRouteRef = computed(() => routeToDisplay.value.matched[depth.value]); - provide(viewDepthKey, computed(() => depth.value + 1)); - provide(matchedRouteKey, matchedRouteRef); - provide(routerViewLocationKey, routeToDisplay); - const viewRef = ref(); - // watch at the same time the component instance, the route record we are - // rendering, and the name - watch(() => [viewRef.value, matchedRouteRef.value, props.name], ([instance, to, name], [oldInstance, from, oldName]) => { - // copy reused instances - if (to) { - // this will update the instance for new instances as well as reused - // instances when navigating to a new route - to.instances[name] = instance; - // the component instance is reused for a different route or name, so - // we copy any saved update or leave guards. With async setup, the - // mounting component will mount before the matchedRoute changes, - // making instance === oldInstance, so we check if guards have been - // added before. This works because we remove guards when - // unmounting/deactivating components - if (from && from !== to && instance && instance === oldInstance) { - if (!to.leaveGuards.size) { - to.leaveGuards = from.leaveGuards; - } - if (!to.updateGuards.size) { - to.updateGuards = from.updateGuards; - } - } - } - // trigger beforeRouteEnter next callbacks - if (instance && - to && - // if there is no instance but to and from are the same this might be - // the first visit - (!from || !isSameRouteRecord(to, from) || !oldInstance)) { - (to.enterCallbacks[name] || []).forEach(callback => callback(instance)); - } - }, { flush: 'post' }); - return () => { - const route = routeToDisplay.value; - // we need the value at the time we render because when we unmount, we - // navigated to a different location so the value is different - const currentName = props.name; - const matchedRoute = matchedRouteRef.value; - const ViewComponent = matchedRoute && matchedRoute.components[currentName]; - if (!ViewComponent) { - return normalizeSlot(slots.default, { Component: ViewComponent, route }); - } - // props from route configuration - const routePropsOption = matchedRoute.props[currentName]; - const routeProps = routePropsOption - ? routePropsOption === true - ? route.params - : typeof routePropsOption === 'function' - ? routePropsOption(route) - : routePropsOption - : null; - const onVnodeUnmounted = vnode => { - // remove the instance reference to prevent leak - if (vnode.component.isUnmounted) { - matchedRoute.instances[currentName] = null; - } - }; - const component = h(ViewComponent, assign({}, routeProps, attrs, { - onVnodeUnmounted, - ref: viewRef, - })); - if (isBrowser && - component.ref) { - // TODO: can display if it's an alias, its props - const info = { - depth: depth.value, - name: matchedRoute.name, - path: matchedRoute.path, - meta: matchedRoute.meta, - }; - const internalInstances = isArray(component.ref) - ? component.ref.map(r => r.i) - : [component.ref.i]; - internalInstances.forEach(instance => { - // @ts-expect-error - instance.__vrv_devtools = info; - }); - } - return ( - // pass the vnode to the slot as a prop. - // h and both accept vnodes - normalizeSlot(slots.default, { Component: component, route }) || - component); - }; - }, -}); -function normalizeSlot(slot, data) { - if (!slot) - return null; - const slotContent = slot(data); - return slotContent.length === 1 ? slotContent[0] : slotContent; -} -// export the public type for h/tsx inference -// also to avoid inline import() in generated d.ts files -/** - * Component to display the current route the user is at. - */ -const RouterView = RouterViewImpl; -// warn against deprecated usage with & -// due to functional component being no longer eager in Vue 3 -function warnDeprecatedUsage() { - const instance = getCurrentInstance(); - const parentName = instance.parent && instance.parent.type.name; - const parentSubTreeType = instance.parent && instance.parent.subTree && instance.parent.subTree.type; - if (parentName && - (parentName === 'KeepAlive' || parentName.includes('Transition')) && - typeof parentSubTreeType === 'object' && - parentSubTreeType.name === 'RouterView') { - const comp = parentName === 'KeepAlive' ? 'keep-alive' : 'transition'; - warn(` can no longer be used directly inside or .\n` + - `Use slot props instead:\n\n` + - `\n` + - ` <${comp}>\n` + - ` \n` + - ` \n` + - ``); - } -} - -/** - * Copies a route location and removes any problematic properties that cannot be shown in devtools (e.g. Vue instances). - * - * @param routeLocation - routeLocation to format - * @param tooltip - optional tooltip - * @returns a copy of the routeLocation - */ -function formatRouteLocation(routeLocation, tooltip) { - const copy = assign({}, routeLocation, { - // remove variables that can contain vue instances - matched: routeLocation.matched.map(matched => omit(matched, ['instances', 'children', 'aliasOf'])), - }); - return { - _custom: { - type: null, - readOnly: true, - display: routeLocation.fullPath, - tooltip, - value: copy, - }, - }; -} -function formatDisplay(display) { - return { - _custom: { - display, - }, - }; -} -// to support multiple router instances -let routerId = 0; -function addDevtools(app, router, matcher) { - // Take over router.beforeEach and afterEach - // make sure we are not registering the devtool twice - if (router.__hasDevtools) - return; - router.__hasDevtools = true; - // increment to support multiple router instances - const id = routerId++; - setupDevtoolsPlugin({ - id: 'org.vuejs.router' + (id ? '.' + id : ''), - label: 'Vue Router', - packageName: 'vue-router', - homepage: 'https://router.vuejs.org', - logo: 'https://router.vuejs.org/logo.png', - componentStateTypes: ['Routing'], - app, - }, api => { - if (typeof api.now !== 'function') { - console.warn('[Vue Router]: You seem to be using an outdated version of Vue Devtools. Are you still using the Beta release instead of the stable one? You can find the links at https://devtools.vuejs.org/guide/installation.html.'); - } - // display state added by the router - api.on.inspectComponent((payload, ctx) => { - if (payload.instanceData) { - payload.instanceData.state.push({ - type: 'Routing', - key: '$route', - editable: false, - value: formatRouteLocation(router.currentRoute.value, 'Current Route'), - }); - } - }); - // mark router-link as active and display tags on router views - api.on.visitComponentTree(({ treeNode: node, componentInstance }) => { - if (componentInstance.__vrv_devtools) { - const info = componentInstance.__vrv_devtools; - node.tags.push({ - label: (info.name ? `${info.name.toString()}: ` : '') + info.path, - textColor: 0, - tooltip: 'This component is rendered by <router-view>', - backgroundColor: PINK_500, - }); - } - // if multiple useLink are used - if (isArray(componentInstance.__vrl_devtools)) { - componentInstance.__devtoolsApi = api; - componentInstance.__vrl_devtools.forEach(devtoolsData => { - let backgroundColor = ORANGE_400; - let tooltip = ''; - if (devtoolsData.isExactActive) { - backgroundColor = LIME_500; - tooltip = 'This is exactly active'; - } - else if (devtoolsData.isActive) { - backgroundColor = BLUE_600; - tooltip = 'This link is active'; - } - node.tags.push({ - label: devtoolsData.route.path, - textColor: 0, - tooltip, - backgroundColor, - }); - }); - } - }); - watch(router.currentRoute, () => { - // refresh active state - refreshRoutesView(); - api.notifyComponentUpdate(); - api.sendInspectorTree(routerInspectorId); - api.sendInspectorState(routerInspectorId); - }); - const navigationsLayerId = 'router:navigations:' + id; - api.addTimelineLayer({ - id: navigationsLayerId, - label: `Router${id ? ' ' + id : ''} Navigations`, - color: 0x40a8c4, - }); - // const errorsLayerId = 'router:errors' - // api.addTimelineLayer({ - // id: errorsLayerId, - // label: 'Router Errors', - // color: 0xea5455, - // }) - router.onError((error, to) => { - api.addTimelineEvent({ - layerId: navigationsLayerId, - event: { - title: 'Error during Navigation', - subtitle: to.fullPath, - logType: 'error', - time: api.now(), - data: { error }, - groupId: to.meta.__navigationId, - }, - }); - }); - // attached to `meta` and used to group events - let navigationId = 0; - router.beforeEach((to, from) => { - const data = { - guard: formatDisplay('beforeEach'), - from: formatRouteLocation(from, 'Current Location during this navigation'), - to: formatRouteLocation(to, 'Target location'), - }; - // Used to group navigations together, hide from devtools - Object.defineProperty(to.meta, '__navigationId', { - value: navigationId++, - }); - api.addTimelineEvent({ - layerId: navigationsLayerId, - event: { - time: api.now(), - title: 'Start of navigation', - subtitle: to.fullPath, - data, - groupId: to.meta.__navigationId, - }, - }); - }); - router.afterEach((to, from, failure) => { - const data = { - guard: formatDisplay('afterEach'), - }; - if (failure) { - data.failure = { - _custom: { - type: Error, - readOnly: true, - display: failure ? failure.message : '', - tooltip: 'Navigation Failure', - value: failure, - }, - }; - data.status = formatDisplay('❌'); - } - else { - data.status = formatDisplay('✅'); - } - // we set here to have the right order - data.from = formatRouteLocation(from, 'Current Location during this navigation'); - data.to = formatRouteLocation(to, 'Target location'); - api.addTimelineEvent({ - layerId: navigationsLayerId, - event: { - title: 'End of navigation', - subtitle: to.fullPath, - time: api.now(), - data, - logType: failure ? 'warning' : 'default', - groupId: to.meta.__navigationId, - }, - }); - }); - /** - * Inspector of Existing routes - */ - const routerInspectorId = 'router-inspector:' + id; - api.addInspector({ - id: routerInspectorId, - label: 'Routes' + (id ? ' ' + id : ''), - icon: 'book', - treeFilterPlaceholder: 'Search routes', - }); - function refreshRoutesView() { - // the routes view isn't active - if (!activeRoutesPayload) - return; - const payload = activeRoutesPayload; - // children routes will appear as nested - let routes = matcher.getRoutes().filter(route => !route.parent); - // reset match state to false - routes.forEach(resetMatchStateOnRouteRecord); - // apply a match state if there is a payload - if (payload.filter) { - routes = routes.filter(route => - // save matches state based on the payload - isRouteMatching(route, payload.filter.toLowerCase())); - } - // mark active routes - routes.forEach(route => markRouteRecordActive(route, router.currentRoute.value)); - payload.rootNodes = routes.map(formatRouteRecordForInspector); - } - let activeRoutesPayload; - api.on.getInspectorTree(payload => { - activeRoutesPayload = payload; - if (payload.app === app && payload.inspectorId === routerInspectorId) { - refreshRoutesView(); - } - }); - /** - * Display information about the currently selected route record - */ - api.on.getInspectorState(payload => { - if (payload.app === app && payload.inspectorId === routerInspectorId) { - const routes = matcher.getRoutes(); - const route = routes.find(route => route.record.__vd_id === payload.nodeId); - if (route) { - payload.state = { - options: formatRouteRecordMatcherForStateInspector(route), - }; - } - } - }); - api.sendInspectorTree(routerInspectorId); - api.sendInspectorState(routerInspectorId); - }); -} -function modifierForKey(key) { - if (key.optional) { - return key.repeatable ? '*' : '?'; - } - else { - return key.repeatable ? '+' : ''; - } -} -function formatRouteRecordMatcherForStateInspector(route) { - const { record } = route; - const fields = [ - { editable: false, key: 'path', value: record.path }, - ]; - if (record.name != null) { - fields.push({ - editable: false, - key: 'name', - value: record.name, - }); - } - fields.push({ editable: false, key: 'regexp', value: route.re }); - if (route.keys.length) { - fields.push({ - editable: false, - key: 'keys', - value: { - _custom: { - type: null, - readOnly: true, - display: route.keys - .map(key => `${key.name}${modifierForKey(key)}`) - .join(' '), - tooltip: 'Param keys', - value: route.keys, - }, - }, - }); - } - if (record.redirect != null) { - fields.push({ - editable: false, - key: 'redirect', - value: record.redirect, - }); - } - if (route.alias.length) { - fields.push({ - editable: false, - key: 'aliases', - value: route.alias.map(alias => alias.record.path), - }); - } - if (Object.keys(route.record.meta).length) { - fields.push({ - editable: false, - key: 'meta', - value: route.record.meta, - }); - } - fields.push({ - key: 'score', - editable: false, - value: { - _custom: { - type: null, - readOnly: true, - display: route.score.map(score => score.join(', ')).join(' | '), - tooltip: 'Score used to sort routes', - value: route.score, - }, - }, - }); - return fields; -} -/** - * Extracted from tailwind palette - */ -const PINK_500 = 0xec4899; -const BLUE_600 = 0x2563eb; -const LIME_500 = 0x84cc16; -const CYAN_400 = 0x22d3ee; -const ORANGE_400 = 0xfb923c; -// const GRAY_100 = 0xf4f4f5 -const DARK = 0x666666; -function formatRouteRecordForInspector(route) { - const tags = []; - const { record } = route; - if (record.name != null) { - tags.push({ - label: String(record.name), - textColor: 0, - backgroundColor: CYAN_400, - }); - } - if (record.aliasOf) { - tags.push({ - label: 'alias', - textColor: 0, - backgroundColor: ORANGE_400, - }); - } - if (route.__vd_match) { - tags.push({ - label: 'matches', - textColor: 0, - backgroundColor: PINK_500, - }); - } - if (route.__vd_exactActive) { - tags.push({ - label: 'exact', - textColor: 0, - backgroundColor: LIME_500, - }); - } - if (route.__vd_active) { - tags.push({ - label: 'active', - textColor: 0, - backgroundColor: BLUE_600, - }); - } - if (record.redirect) { - tags.push({ - label: typeof record.redirect === 'string' - ? `redirect: ${record.redirect}` - : 'redirects', - textColor: 0xffffff, - backgroundColor: DARK, - }); - } - // add an id to be able to select it. Using the `path` is not possible because - // empty path children would collide with their parents - let id = record.__vd_id; - if (id == null) { - id = String(routeRecordId++); - record.__vd_id = id; - } - return { - id, - label: record.path, - tags, - children: route.children.map(formatRouteRecordForInspector), - }; -} -// incremental id for route records and inspector state -let routeRecordId = 0; -const EXTRACT_REGEXP_RE = /^\/(.*)\/([a-z]*)$/; -function markRouteRecordActive(route, currentRoute) { - // no route will be active if matched is empty - // reset the matching state - const isExactActive = currentRoute.matched.length && - isSameRouteRecord(currentRoute.matched[currentRoute.matched.length - 1], route.record); - route.__vd_exactActive = route.__vd_active = isExactActive; - if (!isExactActive) { - route.__vd_active = currentRoute.matched.some(match => isSameRouteRecord(match, route.record)); - } - route.children.forEach(childRoute => markRouteRecordActive(childRoute, currentRoute)); -} -function resetMatchStateOnRouteRecord(route) { - route.__vd_match = false; - route.children.forEach(resetMatchStateOnRouteRecord); -} -function isRouteMatching(route, filter) { - const found = String(route.re).match(EXTRACT_REGEXP_RE); - route.__vd_match = false; - if (!found || found.length < 3) { - return false; - } - // use a regexp without $ at the end to match nested routes better - const nonEndingRE = new RegExp(found[1].replace(/\$$/, ''), found[2]); - if (nonEndingRE.test(filter)) { - // mark children as matches - route.children.forEach(child => isRouteMatching(child, filter)); - // exception case: `/` - if (route.record.path !== '/' || filter === '/') { - route.__vd_match = route.re.test(filter); - return true; - } - // hide the / route - return false; - } - const path = route.record.path.toLowerCase(); - const decodedPath = decode(path); - // also allow partial matching on the path - if (!filter.startsWith('/') && - (decodedPath.includes(filter) || path.includes(filter))) - return true; - if (decodedPath.startsWith(filter) || path.startsWith(filter)) - return true; - if (route.record.name && String(route.record.name).includes(filter)) - return true; - return route.children.some(child => isRouteMatching(child, filter)); -} -function omit(obj, keys) { - const ret = {}; - for (const key in obj) { - if (!keys.includes(key)) { - // @ts-expect-error - ret[key] = obj[key]; - } - } - return ret; -} - -/** - * Creates a Router instance that can be used by a Vue app. - * - * @param options - {@link RouterOptions} - */ -function createRouter(options) { - const matcher = createRouterMatcher(options.routes, options); - const parseQuery$1 = options.parseQuery || parseQuery; - const stringifyQuery$1 = options.stringifyQuery || stringifyQuery; - const routerHistory = options.history; - if (!routerHistory) - throw new Error('Provide the "history" option when calling "createRouter()":' + - ' https://next.router.vuejs.org/api/#history.'); - const beforeGuards = useCallbacks(); - const beforeResolveGuards = useCallbacks(); - const afterGuards = useCallbacks(); - const currentRoute = shallowRef(START_LOCATION_NORMALIZED); - let pendingLocation = START_LOCATION_NORMALIZED; - // leave the scrollRestoration if no scrollBehavior is provided - if (isBrowser && options.scrollBehavior && 'scrollRestoration' in history) { - history.scrollRestoration = 'manual'; - } - const normalizeParams = applyToParams.bind(null, paramValue => '' + paramValue); - const encodeParams = applyToParams.bind(null, encodeParam); - const decodeParams = - // @ts-expect-error: intentionally avoid the type check - applyToParams.bind(null, decode); - function addRoute(parentOrRoute, route) { - let parent; - let record; - if (isRouteName(parentOrRoute)) { - parent = matcher.getRecordMatcher(parentOrRoute); - record = route; - } - else { - record = parentOrRoute; - } - return matcher.addRoute(record, parent); - } - function removeRoute(name) { - const recordMatcher = matcher.getRecordMatcher(name); - if (recordMatcher) { - matcher.removeRoute(recordMatcher); - } - else { - warn(`Cannot remove non-existent route "${String(name)}"`); - } - } - function getRoutes() { - return matcher.getRoutes().map(routeMatcher => routeMatcher.record); - } - function hasRoute(name) { - return !!matcher.getRecordMatcher(name); - } - function resolve(rawLocation, currentLocation) { - // const objectLocation = routerLocationAsObject(rawLocation) - // we create a copy to modify it later - currentLocation = assign({}, currentLocation || currentRoute.value); - if (typeof rawLocation === 'string') { - const locationNormalized = parseURL(parseQuery$1, rawLocation, currentLocation.path); - const matchedRoute = matcher.resolve({ path: locationNormalized.path }, currentLocation); - const href = routerHistory.createHref(locationNormalized.fullPath); - { - if (href.startsWith('//')) - warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`); - else if (!matchedRoute.matched.length) { - warn(`No match found for location with path "${rawLocation}"`); - } - } - // locationNormalized is always a new object - return assign(locationNormalized, matchedRoute, { - params: decodeParams(matchedRoute.params), - hash: decode(locationNormalized.hash), - redirectedFrom: undefined, - href, - }); - } - let matcherLocation; - // path could be relative in object as well - if ('path' in rawLocation) { - if ('params' in rawLocation && - !('name' in rawLocation) && - // @ts-expect-error: the type is never - Object.keys(rawLocation.params).length) { - warn(`Path "${rawLocation.path}" was passed with params but they will be ignored. Use a named route alongside params instead.`); - } - matcherLocation = assign({}, rawLocation, { - path: parseURL(parseQuery$1, rawLocation.path, currentLocation.path).path, - }); - } - else { - // remove any nullish param - const targetParams = assign({}, rawLocation.params); - for (const key in targetParams) { - if (targetParams[key] == null) { - delete targetParams[key]; - } - } - // pass encoded values to the matcher, so it can produce encoded path and fullPath - matcherLocation = assign({}, rawLocation, { - params: encodeParams(targetParams), - }); - // current location params are decoded, we need to encode them in case the - // matcher merges the params - currentLocation.params = encodeParams(currentLocation.params); - } - const matchedRoute = matcher.resolve(matcherLocation, currentLocation); - const hash = rawLocation.hash || ''; - if (hash && !hash.startsWith('#')) { - warn(`A \`hash\` should always start with the character "#". Replace "${hash}" with "#${hash}".`); - } - // the matcher might have merged current location params, so - // we need to run the decoding again - matchedRoute.params = normalizeParams(decodeParams(matchedRoute.params)); - const fullPath = stringifyURL(stringifyQuery$1, assign({}, rawLocation, { - hash: encodeHash(hash), - path: matchedRoute.path, - })); - const href = routerHistory.createHref(fullPath); - { - if (href.startsWith('//')) { - warn(`Location "${rawLocation}" resolved to "${href}". A resolved location cannot start with multiple slashes.`); - } - else if (!matchedRoute.matched.length) { - warn(`No match found for location with path "${'path' in rawLocation ? rawLocation.path : rawLocation}"`); - } - } - return assign({ - fullPath, - // keep the hash encoded so fullPath is effectively path + encodedQuery + - // hash - hash, - query: - // if the user is using a custom query lib like qs, we might have - // nested objects, so we keep the query as is, meaning it can contain - // numbers at `$route.query`, but at the point, the user will have to - // use their own type anyway. - // https://github.com/vuejs/router/issues/328#issuecomment-649481567 - stringifyQuery$1 === stringifyQuery - ? normalizeQuery(rawLocation.query) - : (rawLocation.query || {}), - }, matchedRoute, { - redirectedFrom: undefined, - href, - }); - } - function locationAsObject(to) { - return typeof to === 'string' - ? parseURL(parseQuery$1, to, currentRoute.value.path) - : assign({}, to); - } - function checkCanceledNavigation(to, from) { - if (pendingLocation !== to) { - return createRouterError(8 /* ErrorTypes.NAVIGATION_CANCELLED */, { - from, - to, - }); - } - } - function push(to) { - return pushWithRedirect(to); - } - function replace(to) { - return push(assign(locationAsObject(to), { replace: true })); - } - function handleRedirectRecord(to) { - const lastMatched = to.matched[to.matched.length - 1]; - if (lastMatched && lastMatched.redirect) { - const { redirect } = lastMatched; - let newTargetLocation = typeof redirect === 'function' ? redirect(to) : redirect; - if (typeof newTargetLocation === 'string') { - newTargetLocation = - newTargetLocation.includes('?') || newTargetLocation.includes('#') - ? (newTargetLocation = locationAsObject(newTargetLocation)) - : // force empty params - { path: newTargetLocation }; - // @ts-expect-error: force empty params when a string is passed to let - // the router parse them again - newTargetLocation.params = {}; - } - if (!('path' in newTargetLocation) && - !('name' in newTargetLocation)) { - warn(`Invalid redirect found:\n${JSON.stringify(newTargetLocation, null, 2)}\n when navigating to "${to.fullPath}". A redirect must contain a name or path. This will break in production.`); - throw new Error('Invalid redirect'); - } - return assign({ - query: to.query, - hash: to.hash, - // avoid transferring params if the redirect has a path - params: 'path' in newTargetLocation ? {} : to.params, - }, newTargetLocation); - } - } - function pushWithRedirect(to, redirectedFrom) { - const targetLocation = (pendingLocation = resolve(to)); - const from = currentRoute.value; - const data = to.state; - const force = to.force; - // to could be a string where `replace` is a function - const replace = to.replace === true; - const shouldRedirect = handleRedirectRecord(targetLocation); - if (shouldRedirect) - return pushWithRedirect(assign(locationAsObject(shouldRedirect), { - state: typeof shouldRedirect === 'object' - ? assign({}, data, shouldRedirect.state) - : data, - force, - replace, - }), - // keep original redirectedFrom if it exists - redirectedFrom || targetLocation); - // if it was a redirect we already called `pushWithRedirect` above - const toLocation = targetLocation; - toLocation.redirectedFrom = redirectedFrom; - let failure; - if (!force && isSameRouteLocation(stringifyQuery$1, from, targetLocation)) { - failure = createRouterError(16 /* ErrorTypes.NAVIGATION_DUPLICATED */, { to: toLocation, from }); - // trigger scroll to allow scrolling to the same anchor - handleScroll(from, from, - // this is a push, the only way for it to be triggered from a - // history.listen is with a redirect, which makes it become a push - true, - // This cannot be the first navigation because the initial location - // cannot be manually navigated to - false); - } - return (failure ? Promise.resolve(failure) : navigate(toLocation, from)) - .catch((error) => isNavigationFailure(error) - ? // navigation redirects still mark the router as ready - isNavigationFailure(error, 2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */) - ? error - : markAsReady(error) // also returns the error - : // reject any unknown error - triggerError(error, toLocation, from)) - .then((failure) => { - if (failure) { - if (isNavigationFailure(failure, 2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */)) { - if (// we are redirecting to the same location we were already at - isSameRouteLocation(stringifyQuery$1, resolve(failure.to), toLocation) && - // and we have done it a couple of times - redirectedFrom && - // @ts-expect-error: added only in dev - (redirectedFrom._count = redirectedFrom._count - ? // @ts-expect-error - redirectedFrom._count + 1 - : 1) > 30) { - warn(`Detected a possibly infinite redirection in a navigation guard when going from "${from.fullPath}" to "${toLocation.fullPath}". Aborting to avoid a Stack Overflow.\n Are you always returning a new location within a navigation guard? That would lead to this error. Only return when redirecting or aborting, that should fix this. This might break in production if not fixed.`); - return Promise.reject(new Error('Infinite redirect in navigation guard')); - } - return pushWithRedirect( - // keep options - assign({ - // preserve an existing replacement but allow the redirect to override it - replace, - }, locationAsObject(failure.to), { - state: typeof failure.to === 'object' - ? assign({}, data, failure.to.state) - : data, - force, - }), - // preserve the original redirectedFrom if any - redirectedFrom || toLocation); - } - } - else { - // if we fail we don't finalize the navigation - failure = finalizeNavigation(toLocation, from, true, replace, data); - } - triggerAfterEach(toLocation, from, failure); - return failure; - }); - } - /** - * Helper to reject and skip all navigation guards if a new navigation happened - * @param to - * @param from - */ - function checkCanceledNavigationAndReject(to, from) { - const error = checkCanceledNavigation(to, from); - return error ? Promise.reject(error) : Promise.resolve(); - } - function runWithContext(fn) { - const app = installedApps.values().next().value; - // support Vue < 3.3 - return app && typeof app.runWithContext === 'function' - ? app.runWithContext(fn) - : fn(); - } - // TODO: refactor the whole before guards by internally using router.beforeEach - function navigate(to, from) { - let guards; - const [leavingRecords, updatingRecords, enteringRecords] = extractChangingRecords(to, from); - // all components here have been resolved once because we are leaving - guards = extractComponentsGuards(leavingRecords.reverse(), 'beforeRouteLeave', to, from); - // leavingRecords is already reversed - for (const record of leavingRecords) { - record.leaveGuards.forEach(guard => { - guards.push(guardToPromiseFn(guard, to, from)); - }); - } - const canceledNavigationCheck = checkCanceledNavigationAndReject.bind(null, to, from); - guards.push(canceledNavigationCheck); - // run the queue of per route beforeRouteLeave guards - return (runGuardQueue(guards) - .then(() => { - // check global guards beforeEach - guards = []; - for (const guard of beforeGuards.list()) { - guards.push(guardToPromiseFn(guard, to, from)); - } - guards.push(canceledNavigationCheck); - return runGuardQueue(guards); - }) - .then(() => { - // check in components beforeRouteUpdate - guards = extractComponentsGuards(updatingRecords, 'beforeRouteUpdate', to, from); - for (const record of updatingRecords) { - record.updateGuards.forEach(guard => { - guards.push(guardToPromiseFn(guard, to, from)); - }); - } - guards.push(canceledNavigationCheck); - // run the queue of per route beforeEnter guards - return runGuardQueue(guards); - }) - .then(() => { - // check the route beforeEnter - guards = []; - for (const record of to.matched) { - // do not trigger beforeEnter on reused views - if (record.beforeEnter && !from.matched.includes(record)) { - if (isArray(record.beforeEnter)) { - for (const beforeEnter of record.beforeEnter) - guards.push(guardToPromiseFn(beforeEnter, to, from)); - } - else { - guards.push(guardToPromiseFn(record.beforeEnter, to, from)); - } - } - } - guards.push(canceledNavigationCheck); - // run the queue of per route beforeEnter guards - return runGuardQueue(guards); - }) - .then(() => { - // NOTE: at this point to.matched is normalized and does not contain any () => Promise - // clear existing enterCallbacks, these are added by extractComponentsGuards - to.matched.forEach(record => (record.enterCallbacks = {})); - // check in-component beforeRouteEnter - guards = extractComponentsGuards(enteringRecords, 'beforeRouteEnter', to, from); - guards.push(canceledNavigationCheck); - // run the queue of per route beforeEnter guards - return runGuardQueue(guards); - }) - .then(() => { - // check global guards beforeResolve - guards = []; - for (const guard of beforeResolveGuards.list()) { - guards.push(guardToPromiseFn(guard, to, from)); - } - guards.push(canceledNavigationCheck); - return runGuardQueue(guards); - }) - // catch any navigation canceled - .catch(err => isNavigationFailure(err, 8 /* ErrorTypes.NAVIGATION_CANCELLED */) - ? err - : Promise.reject(err))); - } - function triggerAfterEach(to, from, failure) { - // navigation is confirmed, call afterGuards - // TODO: wrap with error handlers - for (const guard of afterGuards.list()) { - runWithContext(() => guard(to, from, failure)); - } - } - /** - * - Cleans up any navigation guards - * - Changes the url if necessary - * - Calls the scrollBehavior - */ - function finalizeNavigation(toLocation, from, isPush, replace, data) { - // a more recent navigation took place - const error = checkCanceledNavigation(toLocation, from); - if (error) - return error; - // only consider as push if it's not the first navigation - const isFirstNavigation = from === START_LOCATION_NORMALIZED; - const state = !isBrowser ? {} : history.state; - // change URL only if the user did a push/replace and if it's not the initial navigation because - // it's just reflecting the url - if (isPush) { - // on the initial navigation, we want to reuse the scroll position from - // history state if it exists - if (replace || isFirstNavigation) - routerHistory.replace(toLocation.fullPath, assign({ - scroll: isFirstNavigation && state && state.scroll, - }, data)); - else - routerHistory.push(toLocation.fullPath, data); - } - // accept current navigation - currentRoute.value = toLocation; - handleScroll(toLocation, from, isPush, isFirstNavigation); - markAsReady(); - } - let removeHistoryListener; - // attach listener to history to trigger navigations - function setupListeners() { - // avoid setting up listeners twice due to an invalid first navigation - if (removeHistoryListener) - return; - removeHistoryListener = routerHistory.listen((to, _from, info) => { - if (!router.listening) - return; - // cannot be a redirect route because it was in history - const toLocation = resolve(to); - // due to dynamic routing, and to hash history with manual navigation - // (manually changing the url or calling history.hash = '#/somewhere'), - // there could be a redirect record in history - const shouldRedirect = handleRedirectRecord(toLocation); - if (shouldRedirect) { - pushWithRedirect(assign(shouldRedirect, { replace: true }), toLocation).catch(noop); - return; - } - pendingLocation = toLocation; - const from = currentRoute.value; - // TODO: should be moved to web history? - if (isBrowser) { - saveScrollPosition(getScrollKey(from.fullPath, info.delta), computeScrollPosition()); - } - navigate(toLocation, from) - .catch((error) => { - if (isNavigationFailure(error, 4 /* ErrorTypes.NAVIGATION_ABORTED */ | 8 /* ErrorTypes.NAVIGATION_CANCELLED */)) { - return error; - } - if (isNavigationFailure(error, 2 /* ErrorTypes.NAVIGATION_GUARD_REDIRECT */)) { - // Here we could call if (info.delta) routerHistory.go(-info.delta, - // false) but this is bug prone as we have no way to wait the - // navigation to be finished before calling pushWithRedirect. Using - // a setTimeout of 16ms seems to work but there is no guarantee for - // it to work on every browser. So instead we do not restore the - // history entry and trigger a new navigation as requested by the - // navigation guard. - // the error is already handled by router.push we just want to avoid - // logging the error - pushWithRedirect(error.to, toLocation - // avoid an uncaught rejection, let push call triggerError - ) - .then(failure => { - // manual change in hash history #916 ending up in the URL not - // changing, but it was changed by the manual url change, so we - // need to manually change it ourselves - if (isNavigationFailure(failure, 4 /* ErrorTypes.NAVIGATION_ABORTED */ | - 16 /* ErrorTypes.NAVIGATION_DUPLICATED */) && - !info.delta && - info.type === NavigationType.pop) { - routerHistory.go(-1, false); - } - }) - .catch(noop); - // avoid the then branch - return Promise.reject(); - } - // do not restore history on unknown direction - if (info.delta) { - routerHistory.go(-info.delta, false); - } - // unrecognized error, transfer to the global handler - return triggerError(error, toLocation, from); - }) - .then((failure) => { - failure = - failure || - finalizeNavigation( - // after navigation, all matched components are resolved - toLocation, from, false); - // revert the navigation - if (failure) { - if (info.delta && - // a new navigation has been triggered, so we do not want to revert, that will change the current history - // entry while a different route is displayed - !isNavigationFailure(failure, 8 /* ErrorTypes.NAVIGATION_CANCELLED */)) { - routerHistory.go(-info.delta, false); - } - else if (info.type === NavigationType.pop && - isNavigationFailure(failure, 4 /* ErrorTypes.NAVIGATION_ABORTED */ | 16 /* ErrorTypes.NAVIGATION_DUPLICATED */)) { - // manual change in hash history #916 - // it's like a push but lacks the information of the direction - routerHistory.go(-1, false); - } - } - triggerAfterEach(toLocation, from, failure); - }) - .catch(noop); - }); - } - // Initialization and Errors - let readyHandlers = useCallbacks(); - let errorHandlers = useCallbacks(); - let ready; - /** - * Trigger errorHandlers added via onError and throws the error as well - * - * @param error - error to throw - * @param to - location we were navigating to when the error happened - * @param from - location we were navigating from when the error happened - * @returns the error as a rejected promise - */ - function triggerError(error, to, from) { - markAsReady(error); - const list = errorHandlers.list(); - if (list.length) { - list.forEach(handler => handler(error, to, from)); - } - else { - { - warn('uncaught error during route navigation:'); - } - console.error(error); - } - return Promise.reject(error); - } - function isReady() { - if (ready && currentRoute.value !== START_LOCATION_NORMALIZED) - return Promise.resolve(); - return new Promise((resolve, reject) => { - readyHandlers.add([resolve, reject]); - }); - } - function markAsReady(err) { - if (!ready) { - // still not ready if an error happened - ready = !err; - setupListeners(); - readyHandlers - .list() - .forEach(([resolve, reject]) => (err ? reject(err) : resolve())); - readyHandlers.reset(); - } - return err; - } - // Scroll behavior - function handleScroll(to, from, isPush, isFirstNavigation) { - const { scrollBehavior } = options; - if (!isBrowser || !scrollBehavior) - return Promise.resolve(); - const scrollPosition = (!isPush && getSavedScrollPosition(getScrollKey(to.fullPath, 0))) || - ((isFirstNavigation || !isPush) && - history.state && - history.state.scroll) || - null; - return nextTick() - .then(() => scrollBehavior(to, from, scrollPosition)) - .then(position => position && scrollToPosition(position)) - .catch(err => triggerError(err, to, from)); - } - const go = (delta) => routerHistory.go(delta); - let started; - const installedApps = new Set(); - const router = { - currentRoute, - listening: true, - addRoute, - removeRoute, - hasRoute, - getRoutes, - resolve, - options, - push, - replace, - go, - back: () => go(-1), - forward: () => go(1), - beforeEach: beforeGuards.add, - beforeResolve: beforeResolveGuards.add, - afterEach: afterGuards.add, - onError: errorHandlers.add, - isReady, - install(app) { - const router = this; - app.component('RouterLink', RouterLink); - app.component('RouterView', RouterView); - app.config.globalProperties.$router = router; - Object.defineProperty(app.config.globalProperties, '$route', { - enumerable: true, - get: () => unref(currentRoute), - }); - // this initial navigation is only necessary on client, on server it doesn't - // make sense because it will create an extra unnecessary navigation and could - // lead to problems - if (isBrowser && - // used for the initial navigation client side to avoid pushing - // multiple times when the router is used in multiple apps - !started && - currentRoute.value === START_LOCATION_NORMALIZED) { - // see above - started = true; - push(routerHistory.location).catch(err => { - warn('Unexpected error when starting the router:', err); - }); - } - const reactiveRoute = {}; - for (const key in START_LOCATION_NORMALIZED) { - // @ts-expect-error: the key matches - reactiveRoute[key] = computed(() => currentRoute.value[key]); - } - app.provide(routerKey, router); - app.provide(routeLocationKey, reactive(reactiveRoute)); - app.provide(routerViewLocationKey, currentRoute); - const unmountApp = app.unmount; - installedApps.add(app); - app.unmount = function () { - installedApps.delete(app); - // the router is not attached to an app anymore - if (installedApps.size < 1) { - // invalidate the current navigation - pendingLocation = START_LOCATION_NORMALIZED; - removeHistoryListener && removeHistoryListener(); - removeHistoryListener = null; - currentRoute.value = START_LOCATION_NORMALIZED; - started = false; - ready = false; - } - unmountApp(); - }; - // TODO: this probably needs to be updated so it can be used by vue-termui - if (isBrowser) { - addDevtools(app, router, matcher); - } - }, - }; - // TODO: type this as NavigationGuardReturn or similar instead of any - function runGuardQueue(guards) { - return guards.reduce((promise, guard) => promise.then(() => runWithContext(guard)), Promise.resolve()); - } - return router; -} -function extractChangingRecords(to, from) { - const leavingRecords = []; - const updatingRecords = []; - const enteringRecords = []; - const len = Math.max(from.matched.length, to.matched.length); - for (let i = 0; i < len; i++) { - const recordFrom = from.matched[i]; - if (recordFrom) { - if (to.matched.find(record => isSameRouteRecord(record, recordFrom))) - updatingRecords.push(recordFrom); - else - leavingRecords.push(recordFrom); - } - const recordTo = to.matched[i]; - if (recordTo) { - // the type doesn't matter because we are comparing per reference - if (!from.matched.find(record => isSameRouteRecord(record, recordTo))) { - enteringRecords.push(recordTo); - } - } - } - return [leavingRecords, updatingRecords, enteringRecords]; -} - -/** - * Returns the router instance. Equivalent to using `$router` inside - * templates. - */ -function useRouter() { - return inject(routerKey); -} -/** - * Returns the current route location. Equivalent to using `$route` inside - * templates. - */ -function useRoute() { - return inject(routeLocationKey); -} - -export { NavigationFailureType, RouterLink, RouterView, START_LOCATION_NORMALIZED as START_LOCATION, createMemoryHistory, createRouter, createRouterMatcher, createWebHashHistory, createWebHistory, isNavigationFailure, loadRouteLocation, matchedRouteKey, onBeforeRouteLeave, onBeforeRouteUpdate, parseQuery, routeLocationKey, routerKey, routerViewLocationKey, stringifyQuery, useLink, useRoute, useRouter, viewDepthKey }; diff --git a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/lib/vue.esm-browser.js b/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/lib/vue.esm-browser.js deleted file mode 100644 index 37c9dd32..00000000 --- a/code/src/Modules/SettleAccount/host/SettleAccount.HttpApi.Host/wwwroot/assets/demo/lib/vue.esm-browser.js +++ /dev/null @@ -1,15377 +0,0 @@ -function makeMap(str, expectsLowerCase) { - const map = /* @__PURE__ */ Object.create(null); - const list = str.split(","); - for (let i = 0; i < list.length; i++) { - map[list[i]] = true; - } - return expectsLowerCase ? (val) => !!map[val.toLowerCase()] : (val) => !!map[val]; -} - -const EMPTY_OBJ = Object.freeze({}) ; -const EMPTY_ARR = Object.freeze([]) ; -const NOOP = () => { -}; -const NO = () => false; -const onRE = /^on[^a-z]/; -const isOn = (key) => onRE.test(key); -const isModelListener = (key) => key.startsWith("onUpdate:"); -const extend = Object.assign; -const remove = (arr, el) => { - const i = arr.indexOf(el); - if (i > -1) { - arr.splice(i, 1); - } -}; -const hasOwnProperty$1 = Object.prototype.hasOwnProperty; -const hasOwn = (val, key) => hasOwnProperty$1.call(val, key); -const isArray = Array.isArray; -const isMap = (val) => toTypeString(val) === "[object Map]"; -const isSet = (val) => toTypeString(val) === "[object Set]"; -const isDate = (val) => toTypeString(val) === "[object Date]"; -const isRegExp = (val) => toTypeString(val) === "[object RegExp]"; -const isFunction = (val) => typeof val === "function"; -const isString = (val) => typeof val === "string"; -const isSymbol = (val) => typeof val === "symbol"; -const isObject = (val) => val !== null && typeof val === "object"; -const isPromise = (val) => { - return isObject(val) && isFunction(val.then) && isFunction(val.catch); -}; -const objectToString = Object.prototype.toString; -const toTypeString = (value) => objectToString.call(value); -const toRawType = (value) => { - return toTypeString(value).slice(8, -1); -}; -const isPlainObject = (val) => toTypeString(val) === "[object Object]"; -const isIntegerKey = (key) => isString(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key; -const isReservedProp = /* @__PURE__ */ makeMap( - // the leading comma is intentional so empty string "" is also included - ",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted" -); -const isBuiltInDirective = /* @__PURE__ */ makeMap( - "bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo" -); -const cacheStringFunction = (fn) => { - const cache = /* @__PURE__ */ Object.create(null); - return (str) => { - const hit = cache[str]; - return hit || (cache[str] = fn(str)); - }; -}; -const camelizeRE = /-(\w)/g; -const camelize = cacheStringFunction((str) => { - return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : ""); -}); -const hyphenateRE = /\B([A-Z])/g; -const hyphenate = cacheStringFunction( - (str) => str.replace(hyphenateRE, "-$1").toLowerCase() -); -const capitalize = cacheStringFunction( - (str) => str.charAt(0).toUpperCase() + str.slice(1) -); -const toHandlerKey = cacheStringFunction( - (str) => str ? `on${capitalize(str)}` : `` -); -const hasChanged = (value, oldValue) => !Object.is(value, oldValue); -const invokeArrayFns = (fns, arg) => { - for (let i = 0; i < fns.length; i++) { - fns[i](arg); - } -}; -const def = (obj, key, value) => { - Object.defineProperty(obj, key, { - configurable: true, - enumerable: false, - value - }); -}; -const looseToNumber = (val) => { - const n = parseFloat(val); - return isNaN(n) ? val : n; -}; -const toNumber = (val) => { - const n = isString(val) ? Number(val) : NaN; - return isNaN(n) ? val : n; -}; -let _globalThis; -const getGlobalThis = () => { - return _globalThis || (_globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}); -}; - -const PatchFlagNames = { - [1]: `TEXT`, - [2]: `CLASS`, - [4]: `STYLE`, - [8]: `PROPS`, - [16]: `FULL_PROPS`, - [32]: `HYDRATE_EVENTS`, - [64]: `STABLE_FRAGMENT`, - [128]: `KEYED_FRAGMENT`, - [256]: `UNKEYED_FRAGMENT`, - [512]: `NEED_PATCH`, - [1024]: `DYNAMIC_SLOTS`, - [2048]: `DEV_ROOT_FRAGMENT`, - [-1]: `HOISTED`, - [-2]: `BAIL` -}; - -const slotFlagsText = { - [1]: "STABLE", - [2]: "DYNAMIC", - [3]: "FORWARDED" -}; - -const GLOBALS_WHITE_LISTED = "Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console"; -const isGloballyWhitelisted = /* @__PURE__ */ makeMap(GLOBALS_WHITE_LISTED); - -const range = 2; -function generateCodeFrame(source, start = 0, end = source.length) { - let lines = source.split(/(\r?\n)/); - const newlineSequences = lines.filter((_, idx) => idx % 2 === 1); - lines = lines.filter((_, idx) => idx % 2 === 0); - let count = 0; - const res = []; - for (let i = 0; i < lines.length; i++) { - count += lines[i].length + (newlineSequences[i] && newlineSequences[i].length || 0); - if (count >= start) { - for (let j = i - range; j <= i + range || end > count; j++) { - if (j < 0 || j >= lines.length) - continue; - const line = j + 1; - res.push( - `${line}${" ".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}` - ); - const lineLength = lines[j].length; - const newLineSeqLength = newlineSequences[j] && newlineSequences[j].length || 0; - if (j === i) { - const pad = start - (count - (lineLength + newLineSeqLength)); - const length = Math.max( - 1, - end > count ? lineLength - pad : end - start - ); - res.push(` | ` + " ".repeat(pad) + "^".repeat(length)); - } else if (j > i) { - if (end > count) { - const length = Math.max(Math.min(end - count, lineLength), 1); - res.push(` | ` + "^".repeat(length)); - } - count += lineLength + newLineSeqLength; - } - } - break; - } - } - return res.join("\n"); -} - -function normalizeStyle(value) { - if (isArray(value)) { - const res = {}; - for (let i = 0; i < value.length; i++) { - const item = value[i]; - const normalized = isString(item) ? parseStringStyle(item) : normalizeStyle(item); - if (normalized) { - for (const key in normalized) { - res[key] = normalized[key]; - } - } - } - return res; - } else if (isString(value)) { - return value; - } else if (isObject(value)) { - return value; - } -} -const listDelimiterRE = /;(?![^(]*\))/g; -const propertyDelimiterRE = /:([^]+)/; -const styleCommentRE = /\/\*[^]*?\*\//g; -function parseStringStyle(cssText) { - const ret = {}; - cssText.replace(styleCommentRE, "").split(listDelimiterRE).forEach((item) => { - if (item) { - const tmp = item.split(propertyDelimiterRE); - tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim()); - } - }); - return ret; -} -function normalizeClass(value) { - let res = ""; - if (isString(value)) { - res = value; - } else if (isArray(value)) { - for (let i = 0; i < value.length; i++) { - const normalized = normalizeClass(value[i]); - if (normalized) { - res += normalized + " "; - } - } - } else if (isObject(value)) { - for (const name in value) { - if (value[name]) { - res += name + " "; - } - } - } - return res.trim(); -} -function normalizeProps(props) { - if (!props) - return null; - let { class: klass, style } = props; - if (klass && !isString(klass)) { - props.class = normalizeClass(klass); - } - if (style) { - props.style = normalizeStyle(style); - } - return props; -} - -const HTML_TAGS = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot"; -const SVG_TAGS = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view"; -const VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr"; -const isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS); -const isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS); -const isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS); - -const specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`; -const isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs); -function includeBooleanAttr(value) { - return !!value || value === ""; -} - -function looseCompareArrays(a, b) { - if (a.length !== b.length) - return false; - let equal = true; - for (let i = 0; equal && i < a.length; i++) { - equal = looseEqual(a[i], b[i]); - } - return equal; -} -function looseEqual(a, b) { - if (a === b) - return true; - let aValidType = isDate(a); - let bValidType = isDate(b); - if (aValidType || bValidType) { - return aValidType && bValidType ? a.getTime() === b.getTime() : false; - } - aValidType = isSymbol(a); - bValidType = isSymbol(b); - if (aValidType || bValidType) { - return a === b; - } - aValidType = isArray(a); - bValidType = isArray(b); - if (aValidType || bValidType) { - return aValidType && bValidType ? looseCompareArrays(a, b) : false; - } - aValidType = isObject(a); - bValidType = isObject(b); - if (aValidType || bValidType) { - if (!aValidType || !bValidType) { - return false; - } - const aKeysCount = Object.keys(a).length; - const bKeysCount = Object.keys(b).length; - if (aKeysCount !== bKeysCount) { - return false; - } - for (const key in a) { - const aHasKey = a.hasOwnProperty(key); - const bHasKey = b.hasOwnProperty(key); - if (aHasKey && !bHasKey || !aHasKey && bHasKey || !looseEqual(a[key], b[key])) { - return false; - } - } - } - return String(a) === String(b); -} -function looseIndexOf(arr, val) { - return arr.findIndex((item) => looseEqual(item, val)); -} - -const toDisplayString = (val) => { - return isString(val) ? val : val == null ? "" : isArray(val) || isObject(val) && (val.toString === objectToString || !isFunction(val.toString)) ? JSON.stringify(val, replacer, 2) : String(val); -}; -const replacer = (_key, val) => { - if (val && val.__v_isRef) { - return replacer(_key, val.value); - } else if (isMap(val)) { - return { - [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val2]) => { - entries[`${key} =>`] = val2; - return entries; - }, {}) - }; - } else if (isSet(val)) { - return { - [`Set(${val.size})`]: [...val.values()] - }; - } else if (isObject(val) && !isArray(val) && !isPlainObject(val)) { - return String(val); - } - return val; -}; - -function warn$1(msg, ...args) { - console.warn(`[Vue warn] ${msg}`, ...args); -} - -let activeEffectScope; -class EffectScope { - constructor(detached = false) { - this.detached = detached; - /** - * @internal - */ - this._active = true; - /** - * @internal - */ - this.effects = []; - /** - * @internal - */ - this.cleanups = []; - this.parent = activeEffectScope; - if (!detached && activeEffectScope) { - this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push( - this - ) - 1; - } - } - get active() { - return this._active; - } - run(fn) { - if (this._active) { - const currentEffectScope = activeEffectScope; - try { - activeEffectScope = this; - return fn(); - } finally { - activeEffectScope = currentEffectScope; - } - } else { - warn$1(`cannot run an inactive effect scope.`); - } - } - /** - * This should only be called on non-detached scopes - * @internal - */ - on() { - activeEffectScope = this; - } - /** - * This should only be called on non-detached scopes - * @internal - */ - off() { - activeEffectScope = this.parent; - } - stop(fromParent) { - if (this._active) { - let i, l; - for (i = 0, l = this.effects.length; i < l; i++) { - this.effects[i].stop(); - } - for (i = 0, l = this.cleanups.length; i < l; i++) { - this.cleanups[i](); - } - if (this.scopes) { - for (i = 0, l = this.scopes.length; i < l; i++) { - this.scopes[i].stop(true); - } - } - if (!this.detached && this.parent && !fromParent) { - const last = this.parent.scopes.pop(); - if (last && last !== this) { - this.parent.scopes[this.index] = last; - last.index = this.index; - } - } - this.parent = void 0; - this._active = false; - } - } -} -function effectScope(detached) { - return new EffectScope(detached); -} -function recordEffectScope(effect, scope = activeEffectScope) { - if (scope && scope.active) { - scope.effects.push(effect); - } -} -function getCurrentScope() { - return activeEffectScope; -} -function onScopeDispose(fn) { - if (activeEffectScope) { - activeEffectScope.cleanups.push(fn); - } else { - warn$1( - `onScopeDispose() is called when there is no active effect scope to be associated with.` - ); - } -} - -const createDep = (effects) => { - const dep = new Set(effects); - dep.w = 0; - dep.n = 0; - return dep; -}; -const wasTracked = (dep) => (dep.w & trackOpBit) > 0; -const newTracked = (dep) => (dep.n & trackOpBit) > 0; -const initDepMarkers = ({ deps }) => { - if (deps.length) { - for (let i = 0; i < deps.length; i++) { - deps[i].w |= trackOpBit; - } - } -}; -const finalizeDepMarkers = (effect) => { - const { deps } = effect; - if (deps.length) { - let ptr = 0; - for (let i = 0; i < deps.length; i++) { - const dep = deps[i]; - if (wasTracked(dep) && !newTracked(dep)) { - dep.delete(effect); - } else { - deps[ptr++] = dep; - } - dep.w &= ~trackOpBit; - dep.n &= ~trackOpBit; - } - deps.length = ptr; - } -}; - -const targetMap = /* @__PURE__ */ new WeakMap(); -let effectTrackDepth = 0; -let trackOpBit = 1; -const maxMarkerBits = 30; -let activeEffect; -const ITERATE_KEY = Symbol("iterate" ); -const MAP_KEY_ITERATE_KEY = Symbol("Map key iterate" ); -class ReactiveEffect { - constructor(fn, scheduler = null, scope) { - this.fn = fn; - this.scheduler = scheduler; - this.active = true; - this.deps = []; - this.parent = void 0; - recordEffectScope(this, scope); - } - run() { - if (!this.active) { - return this.fn(); - } - let parent = activeEffect; - let lastShouldTrack = shouldTrack; - while (parent) { - if (parent === this) { - return; - } - parent = parent.parent; - } - try { - this.parent = activeEffect; - activeEffect = this; - shouldTrack = true; - trackOpBit = 1 << ++effectTrackDepth; - if (effectTrackDepth <= maxMarkerBits) { - initDepMarkers(this); - } else { - cleanupEffect(this); - } - return this.fn(); - } finally { - if (effectTrackDepth <= maxMarkerBits) { - finalizeDepMarkers(this); - } - trackOpBit = 1 << --effectTrackDepth; - activeEffect = this.parent; - shouldTrack = lastShouldTrack; - this.parent = void 0; - if (this.deferStop) { - this.stop(); - } - } - } - stop() { - if (activeEffect === this) { - this.deferStop = true; - } else if (this.active) { - cleanupEffect(this); - if (this.onStop) { - this.onStop(); - } - this.active = false; - } - } -} -function cleanupEffect(effect2) { - const { deps } = effect2; - if (deps.length) { - for (let i = 0; i < deps.length; i++) { - deps[i].delete(effect2); - } - deps.length = 0; - } -} -function effect(fn, options) { - if (fn.effect) { - fn = fn.effect.fn; - } - const _effect = new ReactiveEffect(fn); - if (options) { - extend(_effect, options); - if (options.scope) - recordEffectScope(_effect, options.scope); - } - if (!options || !options.lazy) { - _effect.run(); - } - const runner = _effect.run.bind(_effect); - runner.effect = _effect; - return runner; -} -function stop(runner) { - runner.effect.stop(); -} -let shouldTrack = true; -const trackStack = []; -function pauseTracking() { - trackStack.push(shouldTrack); - shouldTrack = false; -} -function resetTracking() { - const last = trackStack.pop(); - shouldTrack = last === void 0 ? true : last; -} -function track(target, type, key) { - if (shouldTrack && activeEffect) { - let depsMap = targetMap.get(target); - if (!depsMap) { - targetMap.set(target, depsMap = /* @__PURE__ */ new Map()); - } - let dep = depsMap.get(key); - if (!dep) { - depsMap.set(key, dep = createDep()); - } - const eventInfo = { effect: activeEffect, target, type, key } ; - trackEffects(dep, eventInfo); - } -} -function trackEffects(dep, debuggerEventExtraInfo) { - let shouldTrack2 = false; - if (effectTrackDepth <= maxMarkerBits) { - if (!newTracked(dep)) { - dep.n |= trackOpBit; - shouldTrack2 = !wasTracked(dep); - } - } else { - shouldTrack2 = !dep.has(activeEffect); - } - if (shouldTrack2) { - dep.add(activeEffect); - activeEffect.deps.push(dep); - if (activeEffect.onTrack) { - activeEffect.onTrack( - extend( - { - effect: activeEffect - }, - debuggerEventExtraInfo - ) - ); - } - } -} -function trigger(target, type, key, newValue, oldValue, oldTarget) { - const depsMap = targetMap.get(target); - if (!depsMap) { - return; - } - let deps = []; - if (type === "clear") { - deps = [...depsMap.values()]; - } else if (key === "length" && isArray(target)) { - const newLength = Number(newValue); - depsMap.forEach((dep, key2) => { - if (key2 === "length" || key2 >= newLength) { - deps.push(dep); - } - }); - } else { - if (key !== void 0) { - deps.push(depsMap.get(key)); - } - switch (type) { - case "add": - if (!isArray(target)) { - deps.push(depsMap.get(ITERATE_KEY)); - if (isMap(target)) { - deps.push(depsMap.get(MAP_KEY_ITERATE_KEY)); - } - } else if (isIntegerKey(key)) { - deps.push(depsMap.get("length")); - } - break; - case "delete": - if (!isArray(target)) { - deps.push(depsMap.get(ITERATE_KEY)); - if (isMap(target)) { - deps.push(depsMap.get(MAP_KEY_ITERATE_KEY)); - } - } - break; - case "set": - if (isMap(target)) { - deps.push(depsMap.get(ITERATE_KEY)); - } - break; - } - } - const eventInfo = { target, type, key, newValue, oldValue, oldTarget } ; - if (deps.length === 1) { - if (deps[0]) { - { - triggerEffects(deps[0], eventInfo); - } - } - } else { - const effects = []; - for (const dep of deps) { - if (dep) { - effects.push(...dep); - } - } - { - triggerEffects(createDep(effects), eventInfo); - } - } -} -function triggerEffects(dep, debuggerEventExtraInfo) { - const effects = isArray(dep) ? dep : [...dep]; - for (const effect2 of effects) { - if (effect2.computed) { - triggerEffect(effect2, debuggerEventExtraInfo); - } - } - for (const effect2 of effects) { - if (!effect2.computed) { - triggerEffect(effect2, debuggerEventExtraInfo); - } - } -} -function triggerEffect(effect2, debuggerEventExtraInfo) { - if (effect2 !== activeEffect || effect2.allowRecurse) { - if (effect2.onTrigger) { - effect2.onTrigger(extend({ effect: effect2 }, debuggerEventExtraInfo)); - } - if (effect2.scheduler) { - effect2.scheduler(); - } else { - effect2.run(); - } - } -} -function getDepFromReactive(object, key) { - var _a; - return (_a = targetMap.get(object)) == null ? void 0 : _a.get(key); -} - -const isNonTrackableKeys = /* @__PURE__ */ makeMap(`__proto__,__v_isRef,__isVue`); -const builtInSymbols = new Set( - /* @__PURE__ */ Object.getOwnPropertyNames(Symbol).filter((key) => key !== "arguments" && key !== "caller").map((key) => Symbol[key]).filter(isSymbol) -); -const get$1 = /* @__PURE__ */ createGetter(); -const shallowGet = /* @__PURE__ */ createGetter(false, true); -const readonlyGet = /* @__PURE__ */ createGetter(true); -const shallowReadonlyGet = /* @__PURE__ */ createGetter(true, true); -const arrayInstrumentations = /* @__PURE__ */ createArrayInstrumentations(); -function createArrayInstrumentations() { - const instrumentations = {}; - ["includes", "indexOf", "lastIndexOf"].forEach((key) => { - instrumentations[key] = function(...args) { - const arr = toRaw(this); - for (let i = 0, l = this.length; i < l; i++) { - track(arr, "get", i + ""); - } - const res = arr[key](...args); - if (res === -1 || res === false) { - return arr[key](...args.map(toRaw)); - } else { - return res; - } - }; - }); - ["push", "pop", "shift", "unshift", "splice"].forEach((key) => { - instrumentations[key] = function(...args) { - pauseTracking(); - const res = toRaw(this)[key].apply(this, args); - resetTracking(); - return res; - }; - }); - return instrumentations; -} -function hasOwnProperty(key) { - const obj = toRaw(this); - track(obj, "has", key); - return obj.hasOwnProperty(key); -} -function createGetter(isReadonly2 = false, shallow = false) { - return function get2(target, key, receiver) { - if (key === "__v_isReactive") { - return !isReadonly2; - } else if (key === "__v_isReadonly") { - return isReadonly2; - } else if (key === "__v_isShallow") { - return shallow; - } else if (key === "__v_raw" && receiver === (isReadonly2 ? shallow ? shallowReadonlyMap : readonlyMap : shallow ? shallowReactiveMap : reactiveMap).get(target)) { - return target; - } - const targetIsArray = isArray(target); - if (!isReadonly2) { - if (targetIsArray && hasOwn(arrayInstrumentations, key)) { - return Reflect.get(arrayInstrumentations, key, receiver); - } - if (key === "hasOwnProperty") { - return hasOwnProperty; - } - } - const res = Reflect.get(target, key, receiver); - if (isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) { - return res; - } - if (!isReadonly2) { - track(target, "get", key); - } - if (shallow) { - return res; - } - if (isRef(res)) { - return targetIsArray && isIntegerKey(key) ? res : res.value; - } - if (isObject(res)) { - return isReadonly2 ? readonly(res) : reactive(res); - } - return res; - }; -} -const set$1 = /* @__PURE__ */ createSetter(); -const shallowSet = /* @__PURE__ */ createSetter(true); -function createSetter(shallow = false) { - return function set2(target, key, value, receiver) { - let oldValue = target[key]; - if (isReadonly(oldValue) && isRef(oldValue) && !isRef(value)) { - return false; - } - if (!shallow) { - if (!isShallow(value) && !isReadonly(value)) { - oldValue = toRaw(oldValue); - value = toRaw(value); - } - if (!isArray(target) && isRef(oldValue) && !isRef(value)) { - oldValue.value = value; - return true; - } - } - const hadKey = isArray(target) && isIntegerKey(key) ? Number(key) < target.length : hasOwn(target, key); - const result = Reflect.set(target, key, value, receiver); - if (target === toRaw(receiver)) { - if (!hadKey) { - trigger(target, "add", key, value); - } else if (hasChanged(value, oldValue)) { - trigger(target, "set", key, value, oldValue); - } - } - return result; - }; -} -function deleteProperty(target, key) { - const hadKey = hasOwn(target, key); - const oldValue = target[key]; - const result = Reflect.deleteProperty(target, key); - if (result && hadKey) { - trigger(target, "delete", key, void 0, oldValue); - } - return result; -} -function has$1(target, key) { - const result = Reflect.has(target, key); - if (!isSymbol(key) || !builtInSymbols.has(key)) { - track(target, "has", key); - } - return result; -} -function ownKeys(target) { - track(target, "iterate", isArray(target) ? "length" : ITERATE_KEY); - return Reflect.ownKeys(target); -} -const mutableHandlers = { - get: get$1, - set: set$1, - deleteProperty, - has: has$1, - ownKeys -}; -const readonlyHandlers = { - get: readonlyGet, - set(target, key) { - { - warn$1( - `Set operation on key "${String(key)}" failed: target is readonly.`, - target - ); - } - return true; - }, - deleteProperty(target, key) { - { - warn$1( - `Delete operation on key "${String(key)}" failed: target is readonly.`, - target - ); - } - return true; - } -}; -const shallowReactiveHandlers = /* @__PURE__ */ extend( - {}, - mutableHandlers, - { - get: shallowGet, - set: shallowSet - } -); -const shallowReadonlyHandlers = /* @__PURE__ */ extend( - {}, - readonlyHandlers, - { - get: shallowReadonlyGet - } -); - -const toShallow = (value) => value; -const getProto = (v) => Reflect.getPrototypeOf(v); -function get(target, key, isReadonly = false, isShallow = false) { - target = target["__v_raw"]; - const rawTarget = toRaw(target); - const rawKey = toRaw(key); - if (!isReadonly) { - if (key !== rawKey) { - track(rawTarget, "get", key); - } - track(rawTarget, "get", rawKey); - } - const { has: has2 } = getProto(rawTarget); - const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive; - if (has2.call(rawTarget, key)) { - return wrap(target.get(key)); - } else if (has2.call(rawTarget, rawKey)) { - return wrap(target.get(rawKey)); - } else if (target !== rawTarget) { - target.get(key); - } -} -function has(key, isReadonly = false) { - const target = this["__v_raw"]; - const rawTarget = toRaw(target); - const rawKey = toRaw(key); - if (!isReadonly) { - if (key !== rawKey) { - track(rawTarget, "has", key); - } - track(rawTarget, "has", rawKey); - } - return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); -} -function size(target, isReadonly = false) { - target = target["__v_raw"]; - !isReadonly && track(toRaw(target), "iterate", ITERATE_KEY); - return Reflect.get(target, "size", target); -} -function add(value) { - value = toRaw(value); - const target = toRaw(this); - const proto = getProto(target); - const hadKey = proto.has.call(target, value); - if (!hadKey) { - target.add(value); - trigger(target, "add", value, value); - } - return this; -} -function set(key, value) { - value = toRaw(value); - const target = toRaw(this); - const { has: has2, get: get2 } = getProto(target); - let hadKey = has2.call(target, key); - if (!hadKey) { - key = toRaw(key); - hadKey = has2.call(target, key); - } else { - checkIdentityKeys(target, has2, key); - } - const oldValue = get2.call(target, key); - target.set(key, value); - if (!hadKey) { - trigger(target, "add", key, value); - } else if (hasChanged(value, oldValue)) { - trigger(target, "set", key, value, oldValue); - } - return this; -} -function deleteEntry(key) { - const target = toRaw(this); - const { has: has2, get: get2 } = getProto(target); - let hadKey = has2.call(target, key); - if (!hadKey) { - key = toRaw(key); - hadKey = has2.call(target, key); - } else { - checkIdentityKeys(target, has2, key); - } - const oldValue = get2 ? get2.call(target, key) : void 0; - const result = target.delete(key); - if (hadKey) { - trigger(target, "delete", key, void 0, oldValue); - } - return result; -} -function clear() { - const target = toRaw(this); - const hadItems = target.size !== 0; - const oldTarget = isMap(target) ? new Map(target) : new Set(target) ; - const result = target.clear(); - if (hadItems) { - trigger(target, "clear", void 0, void 0, oldTarget); - } - return result; -} -function createForEach(isReadonly, isShallow) { - return function forEach(callback, thisArg) { - const observed = this; - const target = observed["__v_raw"]; - const rawTarget = toRaw(target); - const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive; - !isReadonly && track(rawTarget, "iterate", ITERATE_KEY); - return target.forEach((value, key) => { - return callback.call(thisArg, wrap(value), wrap(key), observed); - }); - }; -} -function createIterableMethod(method, isReadonly, isShallow) { - return function(...args) { - const target = this["__v_raw"]; - const rawTarget = toRaw(target); - const targetIsMap = isMap(rawTarget); - const isPair = method === "entries" || method === Symbol.iterator && targetIsMap; - const isKeyOnly = method === "keys" && targetIsMap; - const innerIterator = target[method](...args); - const wrap = isShallow ? toShallow : isReadonly ? toReadonly : toReactive; - !isReadonly && track( - rawTarget, - "iterate", - isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY - ); - return { - // iterator protocol - next() { - const { value, done } = innerIterator.next(); - return done ? { value, done } : { - value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value), - done - }; - }, - // iterable protocol - [Symbol.iterator]() { - return this; - } - }; - }; -} -function createReadonlyMethod(type) { - return function(...args) { - { - const key = args[0] ? `on key "${args[0]}" ` : ``; - console.warn( - `${capitalize(type)} operation ${key}failed: target is readonly.`, - toRaw(this) - ); - } - return type === "delete" ? false : this; - }; -} -function createInstrumentations() { - const mutableInstrumentations2 = { - get(key) { - return get(this, key); - }, - get size() { - return size(this); - }, - has, - add, - set, - delete: deleteEntry, - clear, - forEach: createForEach(false, false) - }; - const shallowInstrumentations2 = { - get(key) { - return get(this, key, false, true); - }, - get size() { - return size(this); - }, - has, - add, - set, - delete: deleteEntry, - clear, - forEach: createForEach(false, true) - }; - const readonlyInstrumentations2 = { - get(key) { - return get(this, key, true); - }, - get size() { - return size(this, true); - }, - has(key) { - return has.call(this, key, true); - }, - add: createReadonlyMethod("add"), - set: createReadonlyMethod("set"), - delete: createReadonlyMethod("delete"), - clear: createReadonlyMethod("clear"), - forEach: createForEach(true, false) - }; - const shallowReadonlyInstrumentations2 = { - get(key) { - return get(this, key, true, true); - }, - get size() { - return size(this, true); - }, - has(key) { - return has.call(this, key, true); - }, - add: createReadonlyMethod("add"), - set: createReadonlyMethod("set"), - delete: createReadonlyMethod("delete"), - clear: createReadonlyMethod("clear"), - forEach: createForEach(true, true) - }; - const iteratorMethods = ["keys", "values", "entries", Symbol.iterator]; - iteratorMethods.forEach((method) => { - mutableInstrumentations2[method] = createIterableMethod( - method, - false, - false - ); - readonlyInstrumentations2[method] = createIterableMethod( - method, - true, - false - ); - shallowInstrumentations2[method] = createIterableMethod( - method, - false, - true - ); - shallowReadonlyInstrumentations2[method] = createIterableMethod( - method, - true, - true - ); - }); - return [ - mutableInstrumentations2, - readonlyInstrumentations2, - shallowInstrumentations2, - shallowReadonlyInstrumentations2 - ]; -} -const [ - mutableInstrumentations, - readonlyInstrumentations, - shallowInstrumentations, - shallowReadonlyInstrumentations -] = /* @__PURE__ */ createInstrumentations(); -function createInstrumentationGetter(isReadonly, shallow) { - const instrumentations = shallow ? isReadonly ? shallowReadonlyInstrumentations : shallowInstrumentations : isReadonly ? readonlyInstrumentations : mutableInstrumentations; - return (target, key, receiver) => { - if (key === "__v_isReactive") { - return !isReadonly; - } else if (key === "__v_isReadonly") { - return isReadonly; - } else if (key === "__v_raw") { - return target; - } - return Reflect.get( - hasOwn(instrumentations, key) && key in target ? instrumentations : target, - key, - receiver - ); - }; -} -const mutableCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(false, false) -}; -const shallowCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(false, true) -}; -const readonlyCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(true, false) -}; -const shallowReadonlyCollectionHandlers = { - get: /* @__PURE__ */ createInstrumentationGetter(true, true) -}; -function checkIdentityKeys(target, has2, key) { - const rawKey = toRaw(key); - if (rawKey !== key && has2.call(target, rawKey)) { - const type = toRawType(target); - console.warn( - `Reactive ${type} contains both the raw and reactive versions of the same object${type === `Map` ? ` as keys` : ``}, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible.` - ); - } -} - -const reactiveMap = /* @__PURE__ */ new WeakMap(); -const shallowReactiveMap = /* @__PURE__ */ new WeakMap(); -const readonlyMap = /* @__PURE__ */ new WeakMap(); -const shallowReadonlyMap = /* @__PURE__ */ new WeakMap(); -function targetTypeMap(rawType) { - switch (rawType) { - case "Object": - case "Array": - return 1 /* COMMON */; - case "Map": - case "Set": - case "WeakMap": - case "WeakSet": - return 2 /* COLLECTION */; - default: - return 0 /* INVALID */; - } -} -function getTargetType(value) { - return value["__v_skip"] || !Object.isExtensible(value) ? 0 /* INVALID */ : targetTypeMap(toRawType(value)); -} -function reactive(target) { - if (isReadonly(target)) { - return target; - } - return createReactiveObject( - target, - false, - mutableHandlers, - mutableCollectionHandlers, - reactiveMap - ); -} -function shallowReactive(target) { - return createReactiveObject( - target, - false, - shallowReactiveHandlers, - shallowCollectionHandlers, - shallowReactiveMap - ); -} -function readonly(target) { - return createReactiveObject( - target, - true, - readonlyHandlers, - readonlyCollectionHandlers, - readonlyMap - ); -} -function shallowReadonly(target) { - return createReactiveObject( - target, - true, - shallowReadonlyHandlers, - shallowReadonlyCollectionHandlers, - shallowReadonlyMap - ); -} -function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) { - if (!isObject(target)) { - { - console.warn(`value cannot be made reactive: ${String(target)}`); - } - return target; - } - if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) { - return target; - } - const existingProxy = proxyMap.get(target); - if (existingProxy) { - return existingProxy; - } - const targetType = getTargetType(target); - if (targetType === 0 /* INVALID */) { - return target; - } - const proxy = new Proxy( - target, - targetType === 2 /* COLLECTION */ ? collectionHandlers : baseHandlers - ); - proxyMap.set(target, proxy); - return proxy; -} -function isReactive(value) { - if (isReadonly(value)) { - return isReactive(value["__v_raw"]); - } - return !!(value && value["__v_isReactive"]); -} -function isReadonly(value) { - return !!(value && value["__v_isReadonly"]); -} -function isShallow(value) { - return !!(value && value["__v_isShallow"]); -} -function isProxy(value) { - return isReactive(value) || isReadonly(value); -} -function toRaw(observed) { - const raw = observed && observed["__v_raw"]; - return raw ? toRaw(raw) : observed; -} -function markRaw(value) { - def(value, "__v_skip", true); - return value; -} -const toReactive = (value) => isObject(value) ? reactive(value) : value; -const toReadonly = (value) => isObject(value) ? readonly(value) : value; - -function trackRefValue(ref2) { - if (shouldTrack && activeEffect) { - ref2 = toRaw(ref2); - { - trackEffects(ref2.dep || (ref2.dep = createDep()), { - target: ref2, - type: "get", - key: "value" - }); - } - } -} -function triggerRefValue(ref2, newVal) { - ref2 = toRaw(ref2); - const dep = ref2.dep; - if (dep) { - { - triggerEffects(dep, { - target: ref2, - type: "set", - key: "value", - newValue: newVal - }); - } - } -} -function isRef(r) { - return !!(r && r.__v_isRef === true); -} -function ref(value) { - return createRef(value, false); -} -function shallowRef(value) { - return createRef(value, true); -} -function createRef(rawValue, shallow) { - if (isRef(rawValue)) { - return rawValue; - } - return new RefImpl(rawValue, shallow); -} -class RefImpl { - constructor(value, __v_isShallow) { - this.__v_isShallow = __v_isShallow; - this.dep = void 0; - this.__v_isRef = true; - this._rawValue = __v_isShallow ? value : toRaw(value); - this._value = __v_isShallow ? value : toReactive(value); - } - get value() { - trackRefValue(this); - return this._value; - } - set value(newVal) { - const useDirectValue = this.__v_isShallow || isShallow(newVal) || isReadonly(newVal); - newVal = useDirectValue ? newVal : toRaw(newVal); - if (hasChanged(newVal, this._rawValue)) { - this._rawValue = newVal; - this._value = useDirectValue ? newVal : toReactive(newVal); - triggerRefValue(this, newVal); - } - } -} -function triggerRef(ref2) { - triggerRefValue(ref2, ref2.value ); -} -function unref(ref2) { - return isRef(ref2) ? ref2.value : ref2; -} -function toValue(source) { - return isFunction(source) ? source() : unref(source); -} -const shallowUnwrapHandlers = { - get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)), - set: (target, key, value, receiver) => { - const oldValue = target[key]; - if (isRef(oldValue) && !isRef(value)) { - oldValue.value = value; - return true; - } else { - return Reflect.set(target, key, value, receiver); - } - } -}; -function proxyRefs(objectWithRefs) { - return isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers); -} -class CustomRefImpl { - constructor(factory) { - this.dep = void 0; - this.__v_isRef = true; - const { get, set } = factory( - () => trackRefValue(this), - () => triggerRefValue(this) - ); - this._get = get; - this._set = set; - } - get value() { - return this._get(); - } - set value(newVal) { - this._set(newVal); - } -} -function customRef(factory) { - return new CustomRefImpl(factory); -} -function toRefs(object) { - if (!isProxy(object)) { - console.warn(`toRefs() expects a reactive object but received a plain one.`); - } - const ret = isArray(object) ? new Array(object.length) : {}; - for (const key in object) { - ret[key] = propertyToRef(object, key); - } - return ret; -} -class ObjectRefImpl { - constructor(_object, _key, _defaultValue) { - this._object = _object; - this._key = _key; - this._defaultValue = _defaultValue; - this.__v_isRef = true; - } - get value() { - const val = this._object[this._key]; - return val === void 0 ? this._defaultValue : val; - } - set value(newVal) { - this._object[this._key] = newVal; - } - get dep() { - return getDepFromReactive(toRaw(this._object), this._key); - } -} -class GetterRefImpl { - constructor(_getter) { - this._getter = _getter; - this.__v_isRef = true; - this.__v_isReadonly = true; - } - get value() { - return this._getter(); - } -} -function toRef(source, key, defaultValue) { - if (isRef(source)) { - return source; - } else if (isFunction(source)) { - return new GetterRefImpl(source); - } else if (isObject(source) && arguments.length > 1) { - return propertyToRef(source, key, defaultValue); - } else { - return ref(source); - } -} -function propertyToRef(source, key, defaultValue) { - const val = source[key]; - return isRef(val) ? val : new ObjectRefImpl( - source, - key, - defaultValue - ); -} - -class ComputedRefImpl { - constructor(getter, _setter, isReadonly, isSSR) { - this._setter = _setter; - this.dep = void 0; - this.__v_isRef = true; - this["__v_isReadonly"] = false; - this._dirty = true; - this.effect = new ReactiveEffect(getter, () => { - if (!this._dirty) { - this._dirty = true; - triggerRefValue(this); - } - }); - this.effect.computed = this; - this.effect.active = this._cacheable = !isSSR; - this["__v_isReadonly"] = isReadonly; - } - get value() { - const self = toRaw(this); - trackRefValue(self); - if (self._dirty || !self._cacheable) { - self._dirty = false; - self._value = self.effect.run(); - } - return self._value; - } - set value(newValue) { - this._setter(newValue); - } -} -function computed$1(getterOrOptions, debugOptions, isSSR = false) { - let getter; - let setter; - const onlyGetter = isFunction(getterOrOptions); - if (onlyGetter) { - getter = getterOrOptions; - setter = () => { - console.warn("Write operation failed: computed value is readonly"); - } ; - } else { - getter = getterOrOptions.get; - setter = getterOrOptions.set; - } - const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR); - if (debugOptions && !isSSR) { - cRef.effect.onTrack = debugOptions.onTrack; - cRef.effect.onTrigger = debugOptions.onTrigger; - } - return cRef; -} - -const stack = []; -function pushWarningContext(vnode) { - stack.push(vnode); -} -function popWarningContext() { - stack.pop(); -} -function warn(msg, ...args) { - pauseTracking(); - const instance = stack.length ? stack[stack.length - 1].component : null; - const appWarnHandler = instance && instance.appContext.config.warnHandler; - const trace = getComponentTrace(); - if (appWarnHandler) { - callWithErrorHandling( - appWarnHandler, - instance, - 11, - [ - msg + args.join(""), - instance && instance.proxy, - trace.map( - ({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>` - ).join("\n"), - trace - ] - ); - } else { - const warnArgs = [`[Vue warn]: ${msg}`, ...args]; - if (trace.length && // avoid spamming console during tests - true) { - warnArgs.push(` -`, ...formatTrace(trace)); - } - console.warn(...warnArgs); - } - resetTracking(); -} -function getComponentTrace() { - let currentVNode = stack[stack.length - 1]; - if (!currentVNode) { - return []; - } - const normalizedStack = []; - while (currentVNode) { - const last = normalizedStack[0]; - if (last && last.vnode === currentVNode) { - last.recurseCount++; - } else { - normalizedStack.push({ - vnode: currentVNode, - recurseCount: 0 - }); - } - const parentInstance = currentVNode.component && currentVNode.component.parent; - currentVNode = parentInstance && parentInstance.vnode; - } - return normalizedStack; -} -function formatTrace(trace) { - const logs = []; - trace.forEach((entry, i) => { - logs.push(...i === 0 ? [] : [` -`], ...formatTraceEntry(entry)); - }); - return logs; -} -function formatTraceEntry({ vnode, recurseCount }) { - const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``; - const isRoot = vnode.component ? vnode.component.parent == null : false; - const open = ` at <${formatComponentName( - vnode.component, - vnode.type, - isRoot - )}`; - const close = `>` + postfix; - return vnode.props ? [open, ...formatProps(vnode.props), close] : [open + close]; -} -function formatProps(props) { - const res = []; - const keys = Object.keys(props); - keys.slice(0, 3).forEach((key) => { - res.push(...formatProp(key, props[key])); - }); - if (keys.length > 3) { - res.push(` ...`); - } - return res; -} -function formatProp(key, value, raw) { - if (isString(value)) { - value = JSON.stringify(value); - return raw ? value : [`${key}=${value}`]; - } else if (typeof value === "number" || typeof value === "boolean" || value == null) { - return raw ? value : [`${key}=${value}`]; - } else if (isRef(value)) { - value = formatProp(key, toRaw(value.value), true); - return raw ? value : [`${key}=Ref<`, value, `>`]; - } else if (isFunction(value)) { - return [`${key}=fn${value.name ? `<${value.name}>` : ``}`]; - } else { - value = toRaw(value); - return raw ? value : [`${key}=`, value]; - } -} -function assertNumber(val, type) { - if (val === void 0) { - return; - } else if (typeof val !== "number") { - warn(`${type} is not a valid number - got ${JSON.stringify(val)}.`); - } else if (isNaN(val)) { - warn(`${type} is NaN - the duration expression might be incorrect.`); - } -} - -const ErrorTypeStrings = { - ["sp"]: "serverPrefetch hook", - ["bc"]: "beforeCreate hook", - ["c"]: "created hook", - ["bm"]: "beforeMount hook", - ["m"]: "mounted hook", - ["bu"]: "beforeUpdate hook", - ["u"]: "updated", - ["bum"]: "beforeUnmount hook", - ["um"]: "unmounted hook", - ["a"]: "activated hook", - ["da"]: "deactivated hook", - ["ec"]: "errorCaptured hook", - ["rtc"]: "renderTracked hook", - ["rtg"]: "renderTriggered hook", - [0]: "setup function", - [1]: "render function", - [2]: "watcher getter", - [3]: "watcher callback", - [4]: "watcher cleanup function", - [5]: "native event handler", - [6]: "component event handler", - [7]: "vnode hook", - [8]: "directive hook", - [9]: "transition hook", - [10]: "app errorHandler", - [11]: "app warnHandler", - [12]: "ref function", - [13]: "async component loader", - [14]: "scheduler flush. This is likely a Vue internals bug. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core" -}; -function callWithErrorHandling(fn, instance, type, args) { - let res; - try { - res = args ? fn(...args) : fn(); - } catch (err) { - handleError(err, instance, type); - } - return res; -} -function callWithAsyncErrorHandling(fn, instance, type, args) { - if (isFunction(fn)) { - const res = callWithErrorHandling(fn, instance, type, args); - if (res && isPromise(res)) { - res.catch((err) => { - handleError(err, instance, type); - }); - } - return res; - } - const values = []; - for (let i = 0; i < fn.length; i++) { - values.push(callWithAsyncErrorHandling(fn[i], instance, type, args)); - } - return values; -} -function handleError(err, instance, type, throwInDev = true) { - const contextVNode = instance ? instance.vnode : null; - if (instance) { - let cur = instance.parent; - const exposedInstance = instance.proxy; - const errorInfo = ErrorTypeStrings[type] ; - while (cur) { - const errorCapturedHooks = cur.ec; - if (errorCapturedHooks) { - for (let i = 0; i < errorCapturedHooks.length; i++) { - if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) { - return; - } - } - } - cur = cur.parent; - } - const appErrorHandler = instance.appContext.config.errorHandler; - if (appErrorHandler) { - callWithErrorHandling( - appErrorHandler, - null, - 10, - [err, exposedInstance, errorInfo] - ); - return; - } - } - logError(err, type, contextVNode, throwInDev); -} -function logError(err, type, contextVNode, throwInDev = true) { - { - const info = ErrorTypeStrings[type]; - if (contextVNode) { - pushWarningContext(contextVNode); - } - warn(`Unhandled error${info ? ` during execution of ${info}` : ``}`); - if (contextVNode) { - popWarningContext(); - } - if (throwInDev) { - throw err; - } else { - console.error(err); - } - } -} - -let isFlushing = false; -let isFlushPending = false; -const queue = []; -let flushIndex = 0; -const pendingPostFlushCbs = []; -let activePostFlushCbs = null; -let postFlushIndex = 0; -const resolvedPromise = /* @__PURE__ */ Promise.resolve(); -let currentFlushPromise = null; -const RECURSION_LIMIT = 100; -function nextTick(fn) { - const p = currentFlushPromise || resolvedPromise; - return fn ? p.then(this ? fn.bind(this) : fn) : p; -} -function findInsertionIndex(id) { - let start = flushIndex + 1; - let end = queue.length; - while (start < end) { - const middle = start + end >>> 1; - const middleJobId = getId(queue[middle]); - middleJobId < id ? start = middle + 1 : end = middle; - } - return start; -} -function queueJob(job) { - if (!queue.length || !queue.includes( - job, - isFlushing && job.allowRecurse ? flushIndex + 1 : flushIndex - )) { - if (job.id == null) { - queue.push(job); - } else { - queue.splice(findInsertionIndex(job.id), 0, job); - } - queueFlush(); - } -} -function queueFlush() { - if (!isFlushing && !isFlushPending) { - isFlushPending = true; - currentFlushPromise = resolvedPromise.then(flushJobs); - } -} -function invalidateJob(job) { - const i = queue.indexOf(job); - if (i > flushIndex) { - queue.splice(i, 1); - } -} -function queuePostFlushCb(cb) { - if (!isArray(cb)) { - if (!activePostFlushCbs || !activePostFlushCbs.includes( - cb, - cb.allowRecurse ? postFlushIndex + 1 : postFlushIndex - )) { - pendingPostFlushCbs.push(cb); - } - } else { - pendingPostFlushCbs.push(...cb); - } - queueFlush(); -} -function flushPreFlushCbs(seen, i = isFlushing ? flushIndex + 1 : 0) { - { - seen = seen || /* @__PURE__ */ new Map(); - } - for (; i < queue.length; i++) { - const cb = queue[i]; - if (cb && cb.pre) { - if (checkRecursiveUpdates(seen, cb)) { - continue; - } - queue.splice(i, 1); - i--; - cb(); - } - } -} -function flushPostFlushCbs(seen) { - if (pendingPostFlushCbs.length) { - const deduped = [...new Set(pendingPostFlushCbs)]; - pendingPostFlushCbs.length = 0; - if (activePostFlushCbs) { - activePostFlushCbs.push(...deduped); - return; - } - activePostFlushCbs = deduped; - { - seen = seen || /* @__PURE__ */ new Map(); - } - activePostFlushCbs.sort((a, b) => getId(a) - getId(b)); - for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) { - if (checkRecursiveUpdates(seen, activePostFlushCbs[postFlushIndex])) { - continue; - } - activePostFlushCbs[postFlushIndex](); - } - activePostFlushCbs = null; - postFlushIndex = 0; - } -} -const getId = (job) => job.id == null ? Infinity : job.id; -const comparator = (a, b) => { - const diff = getId(a) - getId(b); - if (diff === 0) { - if (a.pre && !b.pre) - return -1; - if (b.pre && !a.pre) - return 1; - } - return diff; -}; -function flushJobs(seen) { - isFlushPending = false; - isFlushing = true; - { - seen = seen || /* @__PURE__ */ new Map(); - } - queue.sort(comparator); - const check = (job) => checkRecursiveUpdates(seen, job) ; - try { - for (flushIndex = 0; flushIndex < queue.length; flushIndex++) { - const job = queue[flushIndex]; - if (job && job.active !== false) { - if (check(job)) { - continue; - } - callWithErrorHandling(job, null, 14); - } - } - } finally { - flushIndex = 0; - queue.length = 0; - flushPostFlushCbs(seen); - isFlushing = false; - currentFlushPromise = null; - if (queue.length || pendingPostFlushCbs.length) { - flushJobs(seen); - } - } -} -function checkRecursiveUpdates(seen, fn) { - if (!seen.has(fn)) { - seen.set(fn, 1); - } else { - const count = seen.get(fn); - if (count > RECURSION_LIMIT) { - const instance = fn.ownerInstance; - const componentName = instance && getComponentName(instance.type); - warn( - `Maximum recursive updates exceeded${componentName ? ` in component <${componentName}>` : ``}. This means you have a reactive effect that is mutating its own dependencies and thus recursively triggering itself. Possible sources include component template, render function, updated hook or watcher source function.` - ); - return true; - } else { - seen.set(fn, count + 1); - } - } -} - -let isHmrUpdating = false; -const hmrDirtyComponents = /* @__PURE__ */ new Set(); -{ - getGlobalThis().__VUE_HMR_RUNTIME__ = { - createRecord: tryWrap(createRecord), - rerender: tryWrap(rerender), - reload: tryWrap(reload) - }; -} -const map = /* @__PURE__ */ new Map(); -function registerHMR(instance) { - const id = instance.type.__hmrId; - let record = map.get(id); - if (!record) { - createRecord(id, instance.type); - record = map.get(id); - } - record.instances.add(instance); -} -function unregisterHMR(instance) { - map.get(instance.type.__hmrId).instances.delete(instance); -} -function createRecord(id, initialDef) { - if (map.has(id)) { - return false; - } - map.set(id, { - initialDef: normalizeClassComponent(initialDef), - instances: /* @__PURE__ */ new Set() - }); - return true; -} -function normalizeClassComponent(component) { - return isClassComponent(component) ? component.__vccOpts : component; -} -function rerender(id, newRender) { - const record = map.get(id); - if (!record) { - return; - } - record.initialDef.render = newRender; - [...record.instances].forEach((instance) => { - if (newRender) { - instance.render = newRender; - normalizeClassComponent(instance.type).render = newRender; - } - instance.renderCache = []; - isHmrUpdating = true; - instance.update(); - isHmrUpdating = false; - }); -} -function reload(id, newComp) { - const record = map.get(id); - if (!record) - return; - newComp = normalizeClassComponent(newComp); - updateComponentDef(record.initialDef, newComp); - const instances = [...record.instances]; - for (const instance of instances) { - const oldComp = normalizeClassComponent(instance.type); - if (!hmrDirtyComponents.has(oldComp)) { - if (oldComp !== record.initialDef) { - updateComponentDef(oldComp, newComp); - } - hmrDirtyComponents.add(oldComp); - } - instance.appContext.propsCache.delete(instance.type); - instance.appContext.emitsCache.delete(instance.type); - instance.appContext.optionsCache.delete(instance.type); - if (instance.ceReload) { - hmrDirtyComponents.add(oldComp); - instance.ceReload(newComp.styles); - hmrDirtyComponents.delete(oldComp); - } else if (instance.parent) { - queueJob(instance.parent.update); - } else if (instance.appContext.reload) { - instance.appContext.reload(); - } else if (typeof window !== "undefined") { - window.location.reload(); - } else { - console.warn( - "[HMR] Root or manually mounted instance modified. Full reload required." - ); - } - } - queuePostFlushCb(() => { - for (const instance of instances) { - hmrDirtyComponents.delete( - normalizeClassComponent(instance.type) - ); - } - }); -} -function updateComponentDef(oldComp, newComp) { - extend(oldComp, newComp); - for (const key in oldComp) { - if (key !== "__file" && !(key in newComp)) { - delete oldComp[key]; - } - } -} -function tryWrap(fn) { - return (id, arg) => { - try { - return fn(id, arg); - } catch (e) { - console.error(e); - console.warn( - `[HMR] Something went wrong during Vue component hot-reload. Full reload required.` - ); - } - }; -} - -let devtools; -let buffer = []; -let devtoolsNotInstalled = false; -function emit$1(event, ...args) { - if (devtools) { - devtools.emit(event, ...args); - } else if (!devtoolsNotInstalled) { - buffer.push({ event, args }); - } -} -function setDevtoolsHook(hook, target) { - var _a, _b; - devtools = hook; - if (devtools) { - devtools.enabled = true; - buffer.forEach(({ event, args }) => devtools.emit(event, ...args)); - buffer = []; - } else if ( - // handle late devtools injection - only do this if we are in an actual - // browser environment to avoid the timer handle stalling test runner exit - // (#4815) - typeof window !== "undefined" && // some envs mock window but not fully - window.HTMLElement && // also exclude jsdom - !((_b = (_a = window.navigator) == null ? void 0 : _a.userAgent) == null ? void 0 : _b.includes("jsdom")) - ) { - const replay = target.__VUE_DEVTOOLS_HOOK_REPLAY__ = target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []; - replay.push((newHook) => { - setDevtoolsHook(newHook, target); - }); - setTimeout(() => { - if (!devtools) { - target.__VUE_DEVTOOLS_HOOK_REPLAY__ = null; - devtoolsNotInstalled = true; - buffer = []; - } - }, 3e3); - } else { - devtoolsNotInstalled = true; - buffer = []; - } -} -function devtoolsInitApp(app, version) { - emit$1("app:init" /* APP_INIT */, app, version, { - Fragment, - Text, - Comment, - Static - }); -} -function devtoolsUnmountApp(app) { - emit$1("app:unmount" /* APP_UNMOUNT */, app); -} -const devtoolsComponentAdded = /* @__PURE__ */ createDevtoolsComponentHook( - "component:added" /* COMPONENT_ADDED */ -); -const devtoolsComponentUpdated = /* @__PURE__ */ createDevtoolsComponentHook("component:updated" /* COMPONENT_UPDATED */); -const _devtoolsComponentRemoved = /* @__PURE__ */ createDevtoolsComponentHook( - "component:removed" /* COMPONENT_REMOVED */ -); -const devtoolsComponentRemoved = (component) => { - if (devtools && typeof devtools.cleanupBuffer === "function" && // remove the component if it wasn't buffered - !devtools.cleanupBuffer(component)) { - _devtoolsComponentRemoved(component); - } -}; -function createDevtoolsComponentHook(hook) { - return (component) => { - emit$1( - hook, - component.appContext.app, - component.uid, - component.parent ? component.parent.uid : void 0, - component - ); - }; -} -const devtoolsPerfStart = /* @__PURE__ */ createDevtoolsPerformanceHook( - "perf:start" /* PERFORMANCE_START */ -); -const devtoolsPerfEnd = /* @__PURE__ */ createDevtoolsPerformanceHook( - "perf:end" /* PERFORMANCE_END */ -); -function createDevtoolsPerformanceHook(hook) { - return (component, type, time) => { - emit$1(hook, component.appContext.app, component.uid, component, type, time); - }; -} -function devtoolsComponentEmit(component, event, params) { - emit$1( - "component:emit" /* COMPONENT_EMIT */, - component.appContext.app, - component, - event, - params - ); -} - -function emit(instance, event, ...rawArgs) { - if (instance.isUnmounted) - return; - const props = instance.vnode.props || EMPTY_OBJ; - { - const { - emitsOptions, - propsOptions: [propsOptions] - } = instance; - if (emitsOptions) { - if (!(event in emitsOptions) && true) { - if (!propsOptions || !(toHandlerKey(event) in propsOptions)) { - warn( - `Component emitted event "${event}" but it is neither declared in the emits option nor as an "${toHandlerKey(event)}" prop.` - ); - } - } else { - const validator = emitsOptions[event]; - if (isFunction(validator)) { - const isValid = validator(...rawArgs); - if (!isValid) { - warn( - `Invalid event arguments: event validation failed for event "${event}".` - ); - } - } - } - } - } - let args = rawArgs; - const isModelListener = event.startsWith("update:"); - const modelArg = isModelListener && event.slice(7); - if (modelArg && modelArg in props) { - const modifiersKey = `${modelArg === "modelValue" ? "model" : modelArg}Modifiers`; - const { number, trim } = props[modifiersKey] || EMPTY_OBJ; - if (trim) { - args = rawArgs.map((a) => isString(a) ? a.trim() : a); - } - if (number) { - args = rawArgs.map(looseToNumber); - } - } - { - devtoolsComponentEmit(instance, event, args); - } - { - const lowerCaseEvent = event.toLowerCase(); - if (lowerCaseEvent !== event && props[toHandlerKey(lowerCaseEvent)]) { - warn( - `Event "${lowerCaseEvent}" is emitted in component ${formatComponentName( - instance, - instance.type - )} but the handler is registered for "${event}". Note that HTML attributes are case-insensitive and you cannot use v-on to listen to camelCase events when using in-DOM templates. You should probably use "${hyphenate(event)}" instead of "${event}".` - ); - } - } - let handlerName; - let handler = props[handlerName = toHandlerKey(event)] || // also try camelCase event handler (#2249) - props[handlerName = toHandlerKey(camelize(event))]; - if (!handler && isModelListener) { - handler = props[handlerName = toHandlerKey(hyphenate(event))]; - } - if (handler) { - callWithAsyncErrorHandling( - handler, - instance, - 6, - args - ); - } - const onceHandler = props[handlerName + `Once`]; - if (onceHandler) { - if (!instance.emitted) { - instance.emitted = {}; - } else if (instance.emitted[handlerName]) { - return; - } - instance.emitted[handlerName] = true; - callWithAsyncErrorHandling( - onceHandler, - instance, - 6, - args - ); - } -} -function normalizeEmitsOptions(comp, appContext, asMixin = false) { - const cache = appContext.emitsCache; - const cached = cache.get(comp); - if (cached !== void 0) { - return cached; - } - const raw = comp.emits; - let normalized = {}; - let hasExtends = false; - if (!isFunction(comp)) { - const extendEmits = (raw2) => { - const normalizedFromExtend = normalizeEmitsOptions(raw2, appContext, true); - if (normalizedFromExtend) { - hasExtends = true; - extend(normalized, normalizedFromExtend); - } - }; - if (!asMixin && appContext.mixins.length) { - appContext.mixins.forEach(extendEmits); - } - if (comp.extends) { - extendEmits(comp.extends); - } - if (comp.mixins) { - comp.mixins.forEach(extendEmits); - } - } - if (!raw && !hasExtends) { - if (isObject(comp)) { - cache.set(comp, null); - } - return null; - } - if (isArray(raw)) { - raw.forEach((key) => normalized[key] = null); - } else { - extend(normalized, raw); - } - if (isObject(comp)) { - cache.set(comp, normalized); - } - return normalized; -} -function isEmitListener(options, key) { - if (!options || !isOn(key)) { - return false; - } - key = key.slice(2).replace(/Once$/, ""); - return hasOwn(options, key[0].toLowerCase() + key.slice(1)) || hasOwn(options, hyphenate(key)) || hasOwn(options, key); -} - -let currentRenderingInstance = null; -let currentScopeId = null; -function setCurrentRenderingInstance(instance) { - const prev = currentRenderingInstance; - currentRenderingInstance = instance; - currentScopeId = instance && instance.type.__scopeId || null; - return prev; -} -function pushScopeId(id) { - currentScopeId = id; -} -function popScopeId() { - currentScopeId = null; -} -const withScopeId = (_id) => withCtx; -function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot) { - if (!ctx) - return fn; - if (fn._n) { - return fn; - } - const renderFnWithContext = (...args) => { - if (renderFnWithContext._d) { - setBlockTracking(-1); - } - const prevInstance = setCurrentRenderingInstance(ctx); - let res; - try { - res = fn(...args); - } finally { - setCurrentRenderingInstance(prevInstance); - if (renderFnWithContext._d) { - setBlockTracking(1); - } - } - { - devtoolsComponentUpdated(ctx); - } - return res; - }; - renderFnWithContext._n = true; - renderFnWithContext._c = true; - renderFnWithContext._d = true; - return renderFnWithContext; -} - -let accessedAttrs = false; -function markAttrsAccessed() { - accessedAttrs = true; -} -function renderComponentRoot(instance) { - const { - type: Component, - vnode, - proxy, - withProxy, - props, - propsOptions: [propsOptions], - slots, - attrs, - emit, - render, - renderCache, - data, - setupState, - ctx, - inheritAttrs - } = instance; - let result; - let fallthroughAttrs; - const prev = setCurrentRenderingInstance(instance); - { - accessedAttrs = false; - } - try { - if (vnode.shapeFlag & 4) { - const proxyToUse = withProxy || proxy; - result = normalizeVNode( - render.call( - proxyToUse, - proxyToUse, - renderCache, - props, - setupState, - data, - ctx - ) - ); - fallthroughAttrs = attrs; - } else { - const render2 = Component; - if (attrs === props) { - markAttrsAccessed(); - } - result = normalizeVNode( - render2.length > 1 ? render2( - props, - true ? { - get attrs() { - markAttrsAccessed(); - return attrs; - }, - slots, - emit - } : { attrs, slots, emit } - ) : render2( - props, - null - /* we know it doesn't need it */ - ) - ); - fallthroughAttrs = Component.props ? attrs : getFunctionalFallthrough(attrs); - } - } catch (err) { - blockStack.length = 0; - handleError(err, instance, 1); - result = createVNode(Comment); - } - let root = result; - let setRoot = void 0; - if (result.patchFlag > 0 && result.patchFlag & 2048) { - [root, setRoot] = getChildRoot(result); - } - if (fallthroughAttrs && inheritAttrs !== false) { - const keys = Object.keys(fallthroughAttrs); - const { shapeFlag } = root; - if (keys.length) { - if (shapeFlag & (1 | 6)) { - if (propsOptions && keys.some(isModelListener)) { - fallthroughAttrs = filterModelListeners( - fallthroughAttrs, - propsOptions - ); - } - root = cloneVNode(root, fallthroughAttrs); - } else if (!accessedAttrs && root.type !== Comment) { - const allAttrs = Object.keys(attrs); - const eventAttrs = []; - const extraAttrs = []; - for (let i = 0, l = allAttrs.length; i < l; i++) { - const key = allAttrs[i]; - if (isOn(key)) { - if (!isModelListener(key)) { - eventAttrs.push(key[2].toLowerCase() + key.slice(3)); - } - } else { - extraAttrs.push(key); - } - } - if (extraAttrs.length) { - warn( - `Extraneous non-props attributes (${extraAttrs.join(", ")}) were passed to component but could not be automatically inherited because component renders fragment or text root nodes.` - ); - } - if (eventAttrs.length) { - warn( - `Extraneous non-emits event listeners (${eventAttrs.join(", ")}) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. If the listener is intended to be a component custom event listener only, declare it using the "emits" option.` - ); - } - } - } - } - if (vnode.dirs) { - if (!isElementRoot(root)) { - warn( - `Runtime directive used on component with non-element root node. The directives will not function as intended.` - ); - } - root = cloneVNode(root); - root.dirs = root.dirs ? root.dirs.concat(vnode.dirs) : vnode.dirs; - } - if (vnode.transition) { - if (!isElementRoot(root)) { - warn( - `Component inside renders non-element root node that cannot be animated.` - ); - } - root.transition = vnode.transition; - } - if (setRoot) { - setRoot(root); - } else { - result = root; - } - setCurrentRenderingInstance(prev); - return result; -} -const getChildRoot = (vnode) => { - const rawChildren = vnode.children; - const dynamicChildren = vnode.dynamicChildren; - const childRoot = filterSingleRoot(rawChildren); - if (!childRoot) { - return [vnode, void 0]; - } - const index = rawChildren.indexOf(childRoot); - const dynamicIndex = dynamicChildren ? dynamicChildren.indexOf(childRoot) : -1; - const setRoot = (updatedRoot) => { - rawChildren[index] = updatedRoot; - if (dynamicChildren) { - if (dynamicIndex > -1) { - dynamicChildren[dynamicIndex] = updatedRoot; - } else if (updatedRoot.patchFlag > 0) { - vnode.dynamicChildren = [...dynamicChildren, updatedRoot]; - } - } - }; - return [normalizeVNode(childRoot), setRoot]; -}; -function filterSingleRoot(children) { - let singleRoot; - for (let i = 0; i < children.length; i++) { - const child = children[i]; - if (isVNode(child)) { - if (child.type !== Comment || child.children === "v-if") { - if (singleRoot) { - return; - } else { - singleRoot = child; - } - } - } else { - return; - } - } - return singleRoot; -} -const getFunctionalFallthrough = (attrs) => { - let res; - for (const key in attrs) { - if (key === "class" || key === "style" || isOn(key)) { - (res || (res = {}))[key] = attrs[key]; - } - } - return res; -}; -const filterModelListeners = (attrs, props) => { - const res = {}; - for (const key in attrs) { - if (!isModelListener(key) || !(key.slice(9) in props)) { - res[key] = attrs[key]; - } - } - return res; -}; -const isElementRoot = (vnode) => { - return vnode.shapeFlag & (6 | 1) || vnode.type === Comment; -}; -function shouldUpdateComponent(prevVNode, nextVNode, optimized) { - const { props: prevProps, children: prevChildren, component } = prevVNode; - const { props: nextProps, children: nextChildren, patchFlag } = nextVNode; - const emits = component.emitsOptions; - if ((prevChildren || nextChildren) && isHmrUpdating) { - return true; - } - if (nextVNode.dirs || nextVNode.transition) { - return true; - } - if (optimized && patchFlag >= 0) { - if (patchFlag & 1024) { - return true; - } - if (patchFlag & 16) { - if (!prevProps) { - return !!nextProps; - } - return hasPropsChanged(prevProps, nextProps, emits); - } else if (patchFlag & 8) { - const dynamicProps = nextVNode.dynamicProps; - for (let i = 0; i < dynamicProps.length; i++) { - const key = dynamicProps[i]; - if (nextProps[key] !== prevProps[key] && !isEmitListener(emits, key)) { - return true; - } - } - } - } else { - if (prevChildren || nextChildren) { - if (!nextChildren || !nextChildren.$stable) { - return true; - } - } - if (prevProps === nextProps) { - return false; - } - if (!prevProps) { - return !!nextProps; - } - if (!nextProps) { - return true; - } - return hasPropsChanged(prevProps, nextProps, emits); - } - return false; -} -function hasPropsChanged(prevProps, nextProps, emitsOptions) { - const nextKeys = Object.keys(nextProps); - if (nextKeys.length !== Object.keys(prevProps).length) { - return true; - } - for (let i = 0; i < nextKeys.length; i++) { - const key = nextKeys[i]; - if (nextProps[key] !== prevProps[key] && !isEmitListener(emitsOptions, key)) { - return true; - } - } - return false; -} -function updateHOCHostEl({ vnode, parent }, el) { - while (parent && parent.subTree === vnode) { - (vnode = parent.vnode).el = el; - parent = parent.parent; - } -} - -const isSuspense = (type) => type.__isSuspense; -const SuspenseImpl = { - name: "Suspense", - // In order to make Suspense tree-shakable, we need to avoid importing it - // directly in the renderer. The renderer checks for the __isSuspense flag - // on a vnode's type and calls the `process` method, passing in renderer - // internals. - __isSuspense: true, - process(n1, n2, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) { - if (n1 == null) { - mountSuspense( - n2, - container, - anchor, - parentComponent, - parentSuspense, - isSVG, - slotScopeIds, - optimized, - rendererInternals - ); - } else { - patchSuspense( - n1, - n2, - container, - anchor, - parentComponent, - isSVG, - slotScopeIds, - optimized, - rendererInternals - ); - } - }, - hydrate: hydrateSuspense, - create: createSuspenseBoundary, - normalize: normalizeSuspenseChildren -}; -const Suspense = SuspenseImpl ; -function triggerEvent(vnode, name) { - const eventListener = vnode.props && vnode.props[name]; - if (isFunction(eventListener)) { - eventListener(); - } -} -function mountSuspense(vnode, container, anchor, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals) { - const { - p: patch, - o: { createElement } - } = rendererInternals; - const hiddenContainer = createElement("div"); - const suspense = vnode.suspense = createSuspenseBoundary( - vnode, - parentSuspense, - parentComponent, - container, - hiddenContainer, - anchor, - isSVG, - slotScopeIds, - optimized, - rendererInternals - ); - patch( - null, - suspense.pendingBranch = vnode.ssContent, - hiddenContainer, - null, - parentComponent, - suspense, - isSVG, - slotScopeIds - ); - if (suspense.deps > 0) { - triggerEvent(vnode, "onPending"); - triggerEvent(vnode, "onFallback"); - patch( - null, - vnode.ssFallback, - container, - anchor, - parentComponent, - null, - // fallback tree will not have suspense context - isSVG, - slotScopeIds - ); - setActiveBranch(suspense, vnode.ssFallback); - } else { - suspense.resolve(false, true); - } -} -function patchSuspense(n1, n2, container, anchor, parentComponent, isSVG, slotScopeIds, optimized, { p: patch, um: unmount, o: { createElement } }) { - const suspense = n2.suspense = n1.suspense; - suspense.vnode = n2; - n2.el = n1.el; - const newBranch = n2.ssContent; - const newFallback = n2.ssFallback; - const { activeBranch, pendingBranch, isInFallback, isHydrating } = suspense; - if (pendingBranch) { - suspense.pendingBranch = newBranch; - if (isSameVNodeType(newBranch, pendingBranch)) { - patch( - pendingBranch, - newBranch, - suspense.hiddenContainer, - null, - parentComponent, - suspense, - isSVG, - slotScopeIds, - optimized - ); - if (suspense.deps <= 0) { - suspense.resolve(); - } else if (isInFallback) { - patch( - activeBranch, - newFallback, - container, - anchor, - parentComponent, - null, - // fallback tree will not have suspense context - isSVG, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, newFallback); - } - } else { - suspense.pendingId++; - if (isHydrating) { - suspense.isHydrating = false; - suspense.activeBranch = pendingBranch; - } else { - unmount(pendingBranch, parentComponent, suspense); - } - suspense.deps = 0; - suspense.effects.length = 0; - suspense.hiddenContainer = createElement("div"); - if (isInFallback) { - patch( - null, - newBranch, - suspense.hiddenContainer, - null, - parentComponent, - suspense, - isSVG, - slotScopeIds, - optimized - ); - if (suspense.deps <= 0) { - suspense.resolve(); - } else { - patch( - activeBranch, - newFallback, - container, - anchor, - parentComponent, - null, - // fallback tree will not have suspense context - isSVG, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, newFallback); - } - } else if (activeBranch && isSameVNodeType(newBranch, activeBranch)) { - patch( - activeBranch, - newBranch, - container, - anchor, - parentComponent, - suspense, - isSVG, - slotScopeIds, - optimized - ); - suspense.resolve(true); - } else { - patch( - null, - newBranch, - suspense.hiddenContainer, - null, - parentComponent, - suspense, - isSVG, - slotScopeIds, - optimized - ); - if (suspense.deps <= 0) { - suspense.resolve(); - } - } - } - } else { - if (activeBranch && isSameVNodeType(newBranch, activeBranch)) { - patch( - activeBranch, - newBranch, - container, - anchor, - parentComponent, - suspense, - isSVG, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, newBranch); - } else { - triggerEvent(n2, "onPending"); - suspense.pendingBranch = newBranch; - suspense.pendingId++; - patch( - null, - newBranch, - suspense.hiddenContainer, - null, - parentComponent, - suspense, - isSVG, - slotScopeIds, - optimized - ); - if (suspense.deps <= 0) { - suspense.resolve(); - } else { - const { timeout, pendingId } = suspense; - if (timeout > 0) { - setTimeout(() => { - if (suspense.pendingId === pendingId) { - suspense.fallback(newFallback); - } - }, timeout); - } else if (timeout === 0) { - suspense.fallback(newFallback); - } - } - } - } -} -let hasWarned = false; -function createSuspenseBoundary(vnode, parentSuspense, parentComponent, container, hiddenContainer, anchor, isSVG, slotScopeIds, optimized, rendererInternals, isHydrating = false) { - if (!hasWarned) { - hasWarned = true; - console[console.info ? "info" : "log"]( - ` is an experimental feature and its API will likely change.` - ); - } - const { - p: patch, - m: move, - um: unmount, - n: next, - o: { parentNode, remove } - } = rendererInternals; - let parentSuspenseId; - const isSuspensible = isVNodeSuspensible(vnode); - if (isSuspensible) { - if (parentSuspense == null ? void 0 : parentSuspense.pendingBranch) { - parentSuspenseId = parentSuspense.pendingId; - parentSuspense.deps++; - } - } - const timeout = vnode.props ? toNumber(vnode.props.timeout) : void 0; - { - assertNumber(timeout, `Suspense timeout`); - } - const suspense = { - vnode, - parent: parentSuspense, - parentComponent, - isSVG, - container, - hiddenContainer, - anchor, - deps: 0, - pendingId: 0, - timeout: typeof timeout === "number" ? timeout : -1, - activeBranch: null, - pendingBranch: null, - isInFallback: true, - isHydrating, - isUnmounted: false, - effects: [], - resolve(resume = false, sync = false) { - { - if (!resume && !suspense.pendingBranch) { - throw new Error( - `suspense.resolve() is called without a pending branch.` - ); - } - if (suspense.isUnmounted) { - throw new Error( - `suspense.resolve() is called on an already unmounted suspense boundary.` - ); - } - } - const { - vnode: vnode2, - activeBranch, - pendingBranch, - pendingId, - effects, - parentComponent: parentComponent2, - container: container2 - } = suspense; - if (suspense.isHydrating) { - suspense.isHydrating = false; - } else if (!resume) { - const delayEnter = activeBranch && pendingBranch.transition && pendingBranch.transition.mode === "out-in"; - if (delayEnter) { - activeBranch.transition.afterLeave = () => { - if (pendingId === suspense.pendingId) { - move(pendingBranch, container2, anchor2, 0); - } - }; - } - let { anchor: anchor2 } = suspense; - if (activeBranch) { - anchor2 = next(activeBranch); - unmount(activeBranch, parentComponent2, suspense, true); - } - if (!delayEnter) { - move(pendingBranch, container2, anchor2, 0); - } - } - setActiveBranch(suspense, pendingBranch); - suspense.pendingBranch = null; - suspense.isInFallback = false; - let parent = suspense.parent; - let hasUnresolvedAncestor = false; - while (parent) { - if (parent.pendingBranch) { - parent.effects.push(...effects); - hasUnresolvedAncestor = true; - break; - } - parent = parent.parent; - } - if (!hasUnresolvedAncestor) { - queuePostFlushCb(effects); - } - suspense.effects = []; - if (isSuspensible) { - if (parentSuspense && parentSuspense.pendingBranch && parentSuspenseId === parentSuspense.pendingId) { - parentSuspense.deps--; - if (parentSuspense.deps === 0 && !sync) { - parentSuspense.resolve(); - } - } - } - triggerEvent(vnode2, "onResolve"); - }, - fallback(fallbackVNode) { - if (!suspense.pendingBranch) { - return; - } - const { vnode: vnode2, activeBranch, parentComponent: parentComponent2, container: container2, isSVG: isSVG2 } = suspense; - triggerEvent(vnode2, "onFallback"); - const anchor2 = next(activeBranch); - const mountFallback = () => { - if (!suspense.isInFallback) { - return; - } - patch( - null, - fallbackVNode, - container2, - anchor2, - parentComponent2, - null, - // fallback tree will not have suspense context - isSVG2, - slotScopeIds, - optimized - ); - setActiveBranch(suspense, fallbackVNode); - }; - const delayEnter = fallbackVNode.transition && fallbackVNode.transition.mode === "out-in"; - if (delayEnter) { - activeBranch.transition.afterLeave = mountFallback; - } - suspense.isInFallback = true; - unmount( - activeBranch, - parentComponent2, - null, - // no suspense so unmount hooks fire now - true - // shouldRemove - ); - if (!delayEnter) { - mountFallback(); - } - }, - move(container2, anchor2, type) { - suspense.activeBranch && move(suspense.activeBranch, container2, anchor2, type); - suspense.container = container2; - }, - next() { - return suspense.activeBranch && next(suspense.activeBranch); - }, - registerDep(instance, setupRenderEffect) { - const isInPendingSuspense = !!suspense.pendingBranch; - if (isInPendingSuspense) { - suspense.deps++; - } - const hydratedEl = instance.vnode.el; - instance.asyncDep.catch((err) => { - handleError(err, instance, 0); - }).then((asyncSetupResult) => { - if (instance.isUnmounted || suspense.isUnmounted || suspense.pendingId !== instance.suspenseId) { - return; - } - instance.asyncResolved = true; - const { vnode: vnode2 } = instance; - { - pushWarningContext(vnode2); - } - handleSetupResult(instance, asyncSetupResult, false); - if (hydratedEl) { - vnode2.el = hydratedEl; - } - const placeholder = !hydratedEl && instance.subTree.el; - setupRenderEffect( - instance, - vnode2, - // component may have been moved before resolve. - // if this is not a hydration, instance.subTree will be the comment - // placeholder. - parentNode(hydratedEl || instance.subTree.el), - // anchor will not be used if this is hydration, so only need to - // consider the comment placeholder case. - hydratedEl ? null : next(instance.subTree), - suspense, - isSVG, - optimized - ); - if (placeholder) { - remove(placeholder); - } - updateHOCHostEl(instance, vnode2.el); - { - popWarningContext(); - } - if (isInPendingSuspense && --suspense.deps === 0) { - suspense.resolve(); - } - }); - }, - unmount(parentSuspense2, doRemove) { - suspense.isUnmounted = true; - if (suspense.activeBranch) { - unmount( - suspense.activeBranch, - parentComponent, - parentSuspense2, - doRemove - ); - } - if (suspense.pendingBranch) { - unmount( - suspense.pendingBranch, - parentComponent, - parentSuspense2, - doRemove - ); - } - } - }; - return suspense; -} -function hydrateSuspense(node, vnode, parentComponent, parentSuspense, isSVG, slotScopeIds, optimized, rendererInternals, hydrateNode) { - const suspense = vnode.suspense = createSuspenseBoundary( - vnode, - parentSuspense, - parentComponent, - node.parentNode, - document.createElement("div"), - null, - isSVG, - slotScopeIds, - optimized, - rendererInternals, - true - /* hydrating */ - ); - const result = hydrateNode( - node, - suspense.pendingBranch = vnode.ssContent, - parentComponent, - suspense, - slotScopeIds, - optimized - ); - if (suspense.deps === 0) { - suspense.resolve(false, true); - } - return result; -} -function normalizeSuspenseChildren(vnode) { - const { shapeFlag, children } = vnode; - const isSlotChildren = shapeFlag & 32; - vnode.ssContent = normalizeSuspenseSlot( - isSlotChildren ? children.default : children - ); - vnode.ssFallback = isSlotChildren ? normalizeSuspenseSlot(children.fallback) : createVNode(Comment); -} -function normalizeSuspenseSlot(s) { - let block; - if (isFunction(s)) { - const trackBlock = isBlockTreeEnabled && s._c; - if (trackBlock) { - s._d = false; - openBlock(); - } - s = s(); - if (trackBlock) { - s._d = true; - block = currentBlock; - closeBlock(); - } - } - if (isArray(s)) { - const singleChild = filterSingleRoot(s); - if (!singleChild) { - warn(` slots expect a single root node.`); - } - s = singleChild; - } - s = normalizeVNode(s); - if (block && !s.dynamicChildren) { - s.dynamicChildren = block.filter((c) => c !== s); - } - return s; -} -function queueEffectWithSuspense(fn, suspense) { - if (suspense && suspense.pendingBranch) { - if (isArray(fn)) { - suspense.effects.push(...fn); - } else { - suspense.effects.push(fn); - } - } else { - queuePostFlushCb(fn); - } -} -function setActiveBranch(suspense, branch) { - suspense.activeBranch = branch; - const { vnode, parentComponent } = suspense; - const el = vnode.el = branch.el; - if (parentComponent && parentComponent.subTree === vnode) { - parentComponent.vnode.el = el; - updateHOCHostEl(parentComponent, el); - } -} -function isVNodeSuspensible(vnode) { - var _a; - return ((_a = vnode.props) == null ? void 0 : _a.suspensible) != null && vnode.props.suspensible !== false; -} - -function watchEffect(effect, options) { - return doWatch(effect, null, options); -} -function watchPostEffect(effect, options) { - return doWatch( - effect, - null, - extend({}, options, { flush: "post" }) - ); -} -function watchSyncEffect(effect, options) { - return doWatch( - effect, - null, - extend({}, options, { flush: "sync" }) - ); -} -const INITIAL_WATCHER_VALUE = {}; -function watch(source, cb, options) { - if (!isFunction(cb)) { - warn( - `\`watch(fn, options?)\` signature has been moved to a separate API. Use \`watchEffect(fn, options?)\` instead. \`watch\` now only supports \`watch(source, cb, options?) signature.` - ); - } - return doWatch(source, cb, options); -} -function doWatch(source, cb, { immediate, deep, flush, onTrack, onTrigger } = EMPTY_OBJ) { - var _a; - if (!cb) { - if (immediate !== void 0) { - warn( - `watch() "immediate" option is only respected when using the watch(source, callback, options?) signature.` - ); - } - if (deep !== void 0) { - warn( - `watch() "deep" option is only respected when using the watch(source, callback, options?) signature.` - ); - } - } - const warnInvalidSource = (s) => { - warn( - `Invalid watch source: `, - s, - `A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types.` - ); - }; - const instance = getCurrentScope() === ((_a = currentInstance) == null ? void 0 : _a.scope) ? currentInstance : null; - let getter; - let forceTrigger = false; - let isMultiSource = false; - if (isRef(source)) { - getter = () => source.value; - forceTrigger = isShallow(source); - } else if (isReactive(source)) { - getter = () => source; - deep = true; - } else if (isArray(source)) { - isMultiSource = true; - forceTrigger = source.some((s) => isReactive(s) || isShallow(s)); - getter = () => source.map((s) => { - if (isRef(s)) { - return s.value; - } else if (isReactive(s)) { - return traverse(s); - } else if (isFunction(s)) { - return callWithErrorHandling(s, instance, 2); - } else { - warnInvalidSource(s); - } - }); - } else if (isFunction(source)) { - if (cb) { - getter = () => callWithErrorHandling(source, instance, 2); - } else { - getter = () => { - if (instance && instance.isUnmounted) { - return; - } - if (cleanup) { - cleanup(); - } - return callWithAsyncErrorHandling( - source, - instance, - 3, - [onCleanup] - ); - }; - } - } else { - getter = NOOP; - warnInvalidSource(source); - } - if (cb && deep) { - const baseGetter = getter; - getter = () => traverse(baseGetter()); - } - let cleanup; - let onCleanup = (fn) => { - cleanup = effect.onStop = () => { - callWithErrorHandling(fn, instance, 4); - }; - }; - let oldValue = isMultiSource ? new Array(source.length).fill(INITIAL_WATCHER_VALUE) : INITIAL_WATCHER_VALUE; - const job = () => { - if (!effect.active) { - return; - } - if (cb) { - const newValue = effect.run(); - if (deep || forceTrigger || (isMultiSource ? newValue.some( - (v, i) => hasChanged(v, oldValue[i]) - ) : hasChanged(newValue, oldValue)) || false) { - if (cleanup) { - cleanup(); - } - callWithAsyncErrorHandling(cb, instance, 3, [ - newValue, - // pass undefined as the old value when it's changed for the first time - oldValue === INITIAL_WATCHER_VALUE ? void 0 : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE ? [] : oldValue, - onCleanup - ]); - oldValue = newValue; - } - } else { - effect.run(); - } - }; - job.allowRecurse = !!cb; - let scheduler; - if (flush === "sync") { - scheduler = job; - } else if (flush === "post") { - scheduler = () => queuePostRenderEffect(job, instance && instance.suspense); - } else { - job.pre = true; - if (instance) - job.id = instance.uid; - scheduler = () => queueJob(job); - } - const effect = new ReactiveEffect(getter, scheduler); - { - effect.onTrack = onTrack; - effect.onTrigger = onTrigger; - } - if (cb) { - if (immediate) { - job(); - } else { - oldValue = effect.run(); - } - } else if (flush === "post") { - queuePostRenderEffect( - effect.run.bind(effect), - instance && instance.suspense - ); - } else { - effect.run(); - } - const unwatch = () => { - effect.stop(); - if (instance && instance.scope) { - remove(instance.scope.effects, effect); - } - }; - return unwatch; -} -function instanceWatch(source, value, options) { - const publicThis = this.proxy; - const getter = isString(source) ? source.includes(".") ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis); - let cb; - if (isFunction(value)) { - cb = value; - } else { - cb = value.handler; - options = value; - } - const cur = currentInstance; - setCurrentInstance(this); - const res = doWatch(getter, cb.bind(publicThis), options); - if (cur) { - setCurrentInstance(cur); - } else { - unsetCurrentInstance(); - } - return res; -} -function createPathGetter(ctx, path) { - const segments = path.split("."); - return () => { - let cur = ctx; - for (let i = 0; i < segments.length && cur; i++) { - cur = cur[segments[i]]; - } - return cur; - }; -} -function traverse(value, seen) { - if (!isObject(value) || value["__v_skip"]) { - return value; - } - seen = seen || /* @__PURE__ */ new Set(); - if (seen.has(value)) { - return value; - } - seen.add(value); - if (isRef(value)) { - traverse(value.value, seen); - } else if (isArray(value)) { - for (let i = 0; i < value.length; i++) { - traverse(value[i], seen); - } - } else if (isSet(value) || isMap(value)) { - value.forEach((v) => { - traverse(v, seen); - }); - } else if (isPlainObject(value)) { - for (const key in value) { - traverse(value[key], seen); - } - } - return value; -} - -function validateDirectiveName(name) { - if (isBuiltInDirective(name)) { - warn("Do not use built-in directive ids as custom directive id: " + name); - } -} -function withDirectives(vnode, directives) { - const internalInstance = currentRenderingInstance; - if (internalInstance === null) { - warn(`withDirectives can only be used inside render functions.`); - return vnode; - } - const instance = getExposeProxy(internalInstance) || internalInstance.proxy; - const bindings = vnode.dirs || (vnode.dirs = []); - for (let i = 0; i < directives.length; i++) { - let [dir, value, arg, modifiers = EMPTY_OBJ] = directives[i]; - if (dir) { - if (isFunction(dir)) { - dir = { - mounted: dir, - updated: dir - }; - } - if (dir.deep) { - traverse(value); - } - bindings.push({ - dir, - instance, - value, - oldValue: void 0, - arg, - modifiers - }); - } - } - return vnode; -} -function invokeDirectiveHook(vnode, prevVNode, instance, name) { - const bindings = vnode.dirs; - const oldBindings = prevVNode && prevVNode.dirs; - for (let i = 0; i < bindings.length; i++) { - const binding = bindings[i]; - if (oldBindings) { - binding.oldValue = oldBindings[i].value; - } - let hook = binding.dir[name]; - if (hook) { - pauseTracking(); - callWithAsyncErrorHandling(hook, instance, 8, [ - vnode.el, - binding, - vnode, - prevVNode - ]); - resetTracking(); - } - } -} - -function useTransitionState() { - const state = { - isMounted: false, - isLeaving: false, - isUnmounting: false, - leavingVNodes: /* @__PURE__ */ new Map() - }; - onMounted(() => { - state.isMounted = true; - }); - onBeforeUnmount(() => { - state.isUnmounting = true; - }); - return state; -} -const TransitionHookValidator = [Function, Array]; -const BaseTransitionPropsValidators = { - mode: String, - appear: Boolean, - persisted: Boolean, - // enter - onBeforeEnter: TransitionHookValidator, - onEnter: TransitionHookValidator, - onAfterEnter: TransitionHookValidator, - onEnterCancelled: TransitionHookValidator, - // leave - onBeforeLeave: TransitionHookValidator, - onLeave: TransitionHookValidator, - onAfterLeave: TransitionHookValidator, - onLeaveCancelled: TransitionHookValidator, - // appear - onBeforeAppear: TransitionHookValidator, - onAppear: TransitionHookValidator, - onAfterAppear: TransitionHookValidator, - onAppearCancelled: TransitionHookValidator -}; -const BaseTransitionImpl = { - name: `BaseTransition`, - props: BaseTransitionPropsValidators, - setup(props, { slots }) { - const instance = getCurrentInstance(); - const state = useTransitionState(); - let prevTransitionKey; - return () => { - const children = slots.default && getTransitionRawChildren(slots.default(), true); - if (!children || !children.length) { - return; - } - let child = children[0]; - if (children.length > 1) { - let hasFound = false; - for (const c of children) { - if (c.type !== Comment) { - if (hasFound) { - warn( - " can only be used on a single element or component. Use for lists." - ); - break; - } - child = c; - hasFound = true; - } - } - } - const rawProps = toRaw(props); - const { mode } = rawProps; - if (mode && mode !== "in-out" && mode !== "out-in" && mode !== "default") { - warn(`invalid mode: ${mode}`); - } - if (state.isLeaving) { - return emptyPlaceholder(child); - } - const innerChild = getKeepAliveChild(child); - if (!innerChild) { - return emptyPlaceholder(child); - } - const enterHooks = resolveTransitionHooks( - innerChild, - rawProps, - state, - instance - ); - setTransitionHooks(innerChild, enterHooks); - const oldChild = instance.subTree; - const oldInnerChild = oldChild && getKeepAliveChild(oldChild); - let transitionKeyChanged = false; - const { getTransitionKey } = innerChild.type; - if (getTransitionKey) { - const key = getTransitionKey(); - if (prevTransitionKey === void 0) { - prevTransitionKey = key; - } else if (key !== prevTransitionKey) { - prevTransitionKey = key; - transitionKeyChanged = true; - } - } - if (oldInnerChild && oldInnerChild.type !== Comment && (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged)) { - const leavingHooks = resolveTransitionHooks( - oldInnerChild, - rawProps, - state, - instance - ); - setTransitionHooks(oldInnerChild, leavingHooks); - if (mode === "out-in") { - state.isLeaving = true; - leavingHooks.afterLeave = () => { - state.isLeaving = false; - if (instance.update.active !== false) { - instance.update(); - } - }; - return emptyPlaceholder(child); - } else if (mode === "in-out" && innerChild.type !== Comment) { - leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => { - const leavingVNodesCache = getLeavingNodesForType( - state, - oldInnerChild - ); - leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild; - el._leaveCb = () => { - earlyRemove(); - el._leaveCb = void 0; - delete enterHooks.delayedLeave; - }; - enterHooks.delayedLeave = delayedLeave; - }; - } - } - return child; - }; - } -}; -const BaseTransition = BaseTransitionImpl; -function getLeavingNodesForType(state, vnode) { - const { leavingVNodes } = state; - let leavingVNodesCache = leavingVNodes.get(vnode.type); - if (!leavingVNodesCache) { - leavingVNodesCache = /* @__PURE__ */ Object.create(null); - leavingVNodes.set(vnode.type, leavingVNodesCache); - } - return leavingVNodesCache; -} -function resolveTransitionHooks(vnode, props, state, instance) { - const { - appear, - mode, - persisted = false, - onBeforeEnter, - onEnter, - onAfterEnter, - onEnterCancelled, - onBeforeLeave, - onLeave, - onAfterLeave, - onLeaveCancelled, - onBeforeAppear, - onAppear, - onAfterAppear, - onAppearCancelled - } = props; - const key = String(vnode.key); - const leavingVNodesCache = getLeavingNodesForType(state, vnode); - const callHook = (hook, args) => { - hook && callWithAsyncErrorHandling( - hook, - instance, - 9, - args - ); - }; - const callAsyncHook = (hook, args) => { - const done = args[1]; - callHook(hook, args); - if (isArray(hook)) { - if (hook.every((hook2) => hook2.length <= 1)) - done(); - } else if (hook.length <= 1) { - done(); - } - }; - const hooks = { - mode, - persisted, - beforeEnter(el) { - let hook = onBeforeEnter; - if (!state.isMounted) { - if (appear) { - hook = onBeforeAppear || onBeforeEnter; - } else { - return; - } - } - if (el._leaveCb) { - el._leaveCb( - true - /* cancelled */ - ); - } - const leavingVNode = leavingVNodesCache[key]; - if (leavingVNode && isSameVNodeType(vnode, leavingVNode) && leavingVNode.el._leaveCb) { - leavingVNode.el._leaveCb(); - } - callHook(hook, [el]); - }, - enter(el) { - let hook = onEnter; - let afterHook = onAfterEnter; - let cancelHook = onEnterCancelled; - if (!state.isMounted) { - if (appear) { - hook = onAppear || onEnter; - afterHook = onAfterAppear || onAfterEnter; - cancelHook = onAppearCancelled || onEnterCancelled; - } else { - return; - } - } - let called = false; - const done = el._enterCb = (cancelled) => { - if (called) - return; - called = true; - if (cancelled) { - callHook(cancelHook, [el]); - } else { - callHook(afterHook, [el]); - } - if (hooks.delayedLeave) { - hooks.delayedLeave(); - } - el._enterCb = void 0; - }; - if (hook) { - callAsyncHook(hook, [el, done]); - } else { - done(); - } - }, - leave(el, remove) { - const key2 = String(vnode.key); - if (el._enterCb) { - el._enterCb( - true - /* cancelled */ - ); - } - if (state.isUnmounting) { - return remove(); - } - callHook(onBeforeLeave, [el]); - let called = false; - const done = el._leaveCb = (cancelled) => { - if (called) - return; - called = true; - remove(); - if (cancelled) { - callHook(onLeaveCancelled, [el]); - } else { - callHook(onAfterLeave, [el]); - } - el._leaveCb = void 0; - if (leavingVNodesCache[key2] === vnode) { - delete leavingVNodesCache[key2]; - } - }; - leavingVNodesCache[key2] = vnode; - if (onLeave) { - callAsyncHook(onLeave, [el, done]); - } else { - done(); - } - }, - clone(vnode2) { - return resolveTransitionHooks(vnode2, props, state, instance); - } - }; - return hooks; -} -function emptyPlaceholder(vnode) { - if (isKeepAlive(vnode)) { - vnode = cloneVNode(vnode); - vnode.children = null; - return vnode; - } -} -function getKeepAliveChild(vnode) { - return isKeepAlive(vnode) ? vnode.children ? vnode.children[0] : void 0 : vnode; -} -function setTransitionHooks(vnode, hooks) { - if (vnode.shapeFlag & 6 && vnode.component) { - setTransitionHooks(vnode.component.subTree, hooks); - } else if (vnode.shapeFlag & 128) { - vnode.ssContent.transition = hooks.clone(vnode.ssContent); - vnode.ssFallback.transition = hooks.clone(vnode.ssFallback); - } else { - vnode.transition = hooks; - } -} -function getTransitionRawChildren(children, keepComment = false, parentKey) { - let ret = []; - let keyedFragmentCount = 0; - for (let i = 0; i < children.length; i++) { - let child = children[i]; - const key = parentKey == null ? child.key : String(parentKey) + String(child.key != null ? child.key : i); - if (child.type === Fragment) { - if (child.patchFlag & 128) - keyedFragmentCount++; - ret = ret.concat( - getTransitionRawChildren(child.children, keepComment, key) - ); - } else if (keepComment || child.type !== Comment) { - ret.push(key != null ? cloneVNode(child, { key }) : child); - } - } - if (keyedFragmentCount > 1) { - for (let i = 0; i < ret.length; i++) { - ret[i].patchFlag = -2; - } - } - return ret; -} - -function defineComponent(options, extraOptions) { - return isFunction(options) ? ( - // #8326: extend call and options.name access are considered side-effects - // by Rollup, so we have to wrap it in a pure-annotated IIFE. - /* @__PURE__ */ (() => extend({ name: options.name }, extraOptions, { setup: options }))() - ) : options; -} - -const isAsyncWrapper = (i) => !!i.type.__asyncLoader; -function defineAsyncComponent(source) { - if (isFunction(source)) { - source = { loader: source }; - } - const { - loader, - loadingComponent, - errorComponent, - delay = 200, - timeout, - // undefined = never times out - suspensible = true, - onError: userOnError - } = source; - let pendingRequest = null; - let resolvedComp; - let retries = 0; - const retry = () => { - retries++; - pendingRequest = null; - return load(); - }; - const load = () => { - let thisRequest; - return pendingRequest || (thisRequest = pendingRequest = loader().catch((err) => { - err = err instanceof Error ? err : new Error(String(err)); - if (userOnError) { - return new Promise((resolve, reject) => { - const userRetry = () => resolve(retry()); - const userFail = () => reject(err); - userOnError(err, userRetry, userFail, retries + 1); - }); - } else { - throw err; - } - }).then((comp) => { - if (thisRequest !== pendingRequest && pendingRequest) { - return pendingRequest; - } - if (!comp) { - warn( - `Async component loader resolved to undefined. If you are using retry(), make sure to return its return value.` - ); - } - if (comp && (comp.__esModule || comp[Symbol.toStringTag] === "Module")) { - comp = comp.default; - } - if (comp && !isObject(comp) && !isFunction(comp)) { - throw new Error(`Invalid async component load result: ${comp}`); - } - resolvedComp = comp; - return comp; - })); - }; - return defineComponent({ - name: "AsyncComponentWrapper", - __asyncLoader: load, - get __asyncResolved() { - return resolvedComp; - }, - setup() { - const instance = currentInstance; - if (resolvedComp) { - return () => createInnerComp(resolvedComp, instance); - } - const onError = (err) => { - pendingRequest = null; - handleError( - err, - instance, - 13, - !errorComponent - /* do not throw in dev if user provided error component */ - ); - }; - if (suspensible && instance.suspense || false) { - return load().then((comp) => { - return () => createInnerComp(comp, instance); - }).catch((err) => { - onError(err); - return () => errorComponent ? createVNode(errorComponent, { - error: err - }) : null; - }); - } - const loaded = ref(false); - const error = ref(); - const delayed = ref(!!delay); - if (delay) { - setTimeout(() => { - delayed.value = false; - }, delay); - } - if (timeout != null) { - setTimeout(() => { - if (!loaded.value && !error.value) { - const err = new Error( - `Async component timed out after ${timeout}ms.` - ); - onError(err); - error.value = err; - } - }, timeout); - } - load().then(() => { - loaded.value = true; - if (instance.parent && isKeepAlive(instance.parent.vnode)) { - queueJob(instance.parent.update); - } - }).catch((err) => { - onError(err); - error.value = err; - }); - return () => { - if (loaded.value && resolvedComp) { - return createInnerComp(resolvedComp, instance); - } else if (error.value && errorComponent) { - return createVNode(errorComponent, { - error: error.value - }); - } else if (loadingComponent && !delayed.value) { - return createVNode(loadingComponent); - } - }; - } - }); -} -function createInnerComp(comp, parent) { - const { ref: ref2, props, children, ce } = parent.vnode; - const vnode = createVNode(comp, props, children); - vnode.ref = ref2; - vnode.ce = ce; - delete parent.vnode.ce; - return vnode; -} - -const isKeepAlive = (vnode) => vnode.type.__isKeepAlive; -const KeepAliveImpl = { - name: `KeepAlive`, - // Marker for special handling inside the renderer. We are not using a === - // check directly on KeepAlive in the renderer, because importing it directly - // would prevent it from being tree-shaken. - __isKeepAlive: true, - props: { - include: [String, RegExp, Array], - exclude: [String, RegExp, Array], - max: [String, Number] - }, - setup(props, { slots }) { - const instance = getCurrentInstance(); - const sharedContext = instance.ctx; - const cache = /* @__PURE__ */ new Map(); - const keys = /* @__PURE__ */ new Set(); - let current = null; - { - instance.__v_cache = cache; - } - const parentSuspense = instance.suspense; - const { - renderer: { - p: patch, - m: move, - um: _unmount, - o: { createElement } - } - } = sharedContext; - const storageContainer = createElement("div"); - sharedContext.activate = (vnode, container, anchor, isSVG, optimized) => { - const instance2 = vnode.component; - move(vnode, container, anchor, 0, parentSuspense); - patch( - instance2.vnode, - vnode, - container, - anchor, - instance2, - parentSuspense, - isSVG, - vnode.slotScopeIds, - optimized - ); - queuePostRenderEffect(() => { - instance2.isDeactivated = false; - if (instance2.a) { - invokeArrayFns(instance2.a); - } - const vnodeHook = vnode.props && vnode.props.onVnodeMounted; - if (vnodeHook) { - invokeVNodeHook(vnodeHook, instance2.parent, vnode); - } - }, parentSuspense); - { - devtoolsComponentAdded(instance2); - } - }; - sharedContext.deactivate = (vnode) => { - const instance2 = vnode.component; - move(vnode, storageContainer, null, 1, parentSuspense); - queuePostRenderEffect(() => { - if (instance2.da) { - invokeArrayFns(instance2.da); - } - const vnodeHook = vnode.props && vnode.props.onVnodeUnmounted; - if (vnodeHook) { - invokeVNodeHook(vnodeHook, instance2.parent, vnode); - } - instance2.isDeactivated = true; - }, parentSuspense); - { - devtoolsComponentAdded(instance2); - } - }; - function unmount(vnode) { - resetShapeFlag(vnode); - _unmount(vnode, instance, parentSuspense, true); - } - function pruneCache(filter) { - cache.forEach((vnode, key) => { - const name = getComponentName(vnode.type); - if (name && (!filter || !filter(name))) { - pruneCacheEntry(key); - } - }); - } - function pruneCacheEntry(key) { - const cached = cache.get(key); - if (!current || !isSameVNodeType(cached, current)) { - unmount(cached); - } else if (current) { - resetShapeFlag(current); - } - cache.delete(key); - keys.delete(key); - } - watch( - () => [props.include, props.exclude], - ([include, exclude]) => { - include && pruneCache((name) => matches(include, name)); - exclude && pruneCache((name) => !matches(exclude, name)); - }, - // prune post-render after `current` has been updated - { flush: "post", deep: true } - ); - let pendingCacheKey = null; - const cacheSubtree = () => { - if (pendingCacheKey != null) { - cache.set(pendingCacheKey, getInnerChild(instance.subTree)); - } - }; - onMounted(cacheSubtree); - onUpdated(cacheSubtree); - onBeforeUnmount(() => { - cache.forEach((cached) => { - const { subTree, suspense } = instance; - const vnode = getInnerChild(subTree); - if (cached.type === vnode.type && cached.key === vnode.key) { - resetShapeFlag(vnode); - const da = vnode.component.da; - da && queuePostRenderEffect(da, suspense); - return; - } - unmount(cached); - }); - }); - return () => { - pendingCacheKey = null; - if (!slots.default) { - return null; - } - const children = slots.default(); - const rawVNode = children[0]; - if (children.length > 1) { - { - warn(`KeepAlive should contain exactly one component child.`); - } - current = null; - return children; - } else if (!isVNode(rawVNode) || !(rawVNode.shapeFlag & 4) && !(rawVNode.shapeFlag & 128)) { - current = null; - return rawVNode; - } - let vnode = getInnerChild(rawVNode); - const comp = vnode.type; - const name = getComponentName( - isAsyncWrapper(vnode) ? vnode.type.__asyncResolved || {} : comp - ); - const { include, exclude, max } = props; - if (include && (!name || !matches(include, name)) || exclude && name && matches(exclude, name)) { - current = vnode; - return rawVNode; - } - const key = vnode.key == null ? comp : vnode.key; - const cachedVNode = cache.get(key); - if (vnode.el) { - vnode = cloneVNode(vnode); - if (rawVNode.shapeFlag & 128) { - rawVNode.ssContent = vnode; - } - } - pendingCacheKey = key; - if (cachedVNode) { - vnode.el = cachedVNode.el; - vnode.component = cachedVNode.component; - if (vnode.transition) { - setTransitionHooks(vnode, vnode.transition); - } - vnode.shapeFlag |= 512; - keys.delete(key); - keys.add(key); - } else { - keys.add(key); - if (max && keys.size > parseInt(max, 10)) { - pruneCacheEntry(keys.values().next().value); - } - } - vnode.shapeFlag |= 256; - current = vnode; - return isSuspense(rawVNode.type) ? rawVNode : vnode; - }; - } -}; -const KeepAlive = KeepAliveImpl; -function matches(pattern, name) { - if (isArray(pattern)) { - return pattern.some((p) => matches(p, name)); - } else if (isString(pattern)) { - return pattern.split(",").includes(name); - } else if (isRegExp(pattern)) { - return pattern.test(name); - } - return false; -} -function onActivated(hook, target) { - registerKeepAliveHook(hook, "a", target); -} -function onDeactivated(hook, target) { - registerKeepAliveHook(hook, "da", target); -} -function registerKeepAliveHook(hook, type, target = currentInstance) { - const wrappedHook = hook.__wdc || (hook.__wdc = () => { - let current = target; - while (current) { - if (current.isDeactivated) { - return; - } - current = current.parent; - } - return hook(); - }); - injectHook(type, wrappedHook, target); - if (target) { - let current = target.parent; - while (current && current.parent) { - if (isKeepAlive(current.parent.vnode)) { - injectToKeepAliveRoot(wrappedHook, type, target, current); - } - current = current.parent; - } - } -} -function injectToKeepAliveRoot(hook, type, target, keepAliveRoot) { - const injected = injectHook( - type, - hook, - keepAliveRoot, - true - /* prepend */ - ); - onUnmounted(() => { - remove(keepAliveRoot[type], injected); - }, target); -} -function resetShapeFlag(vnode) { - vnode.shapeFlag &= ~256; - vnode.shapeFlag &= ~512; -} -function getInnerChild(vnode) { - return vnode.shapeFlag & 128 ? vnode.ssContent : vnode; -} - -function injectHook(type, hook, target = currentInstance, prepend = false) { - if (target) { - const hooks = target[type] || (target[type] = []); - const wrappedHook = hook.__weh || (hook.__weh = (...args) => { - if (target.isUnmounted) { - return; - } - pauseTracking(); - setCurrentInstance(target); - const res = callWithAsyncErrorHandling(hook, target, type, args); - unsetCurrentInstance(); - resetTracking(); - return res; - }); - if (prepend) { - hooks.unshift(wrappedHook); - } else { - hooks.push(wrappedHook); - } - return wrappedHook; - } else { - const apiName = toHandlerKey(ErrorTypeStrings[type].replace(/ hook$/, "")); - warn( - `${apiName} is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup().` + (` If you are using async setup(), make sure to register lifecycle hooks before the first await statement.` ) - ); - } -} -const createHook = (lifecycle) => (hook, target = currentInstance) => ( - // post-create lifecycle registrations are noops during SSR (except for serverPrefetch) - (!isInSSRComponentSetup || lifecycle === "sp") && injectHook(lifecycle, (...args) => hook(...args), target) -); -const onBeforeMount = createHook("bm"); -const onMounted = createHook("m"); -const onBeforeUpdate = createHook("bu"); -const onUpdated = createHook("u"); -const onBeforeUnmount = createHook("bum"); -const onUnmounted = createHook("um"); -const onServerPrefetch = createHook("sp"); -const onRenderTriggered = createHook( - "rtg" -); -const onRenderTracked = createHook( - "rtc" -); -function onErrorCaptured(hook, target = currentInstance) { - injectHook("ec", hook, target); -} - -const COMPONENTS = "components"; -const DIRECTIVES = "directives"; -function resolveComponent(name, maybeSelfReference) { - return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name; -} -const NULL_DYNAMIC_COMPONENT = Symbol.for("v-ndc"); -function resolveDynamicComponent(component) { - if (isString(component)) { - return resolveAsset(COMPONENTS, component, false) || component; - } else { - return component || NULL_DYNAMIC_COMPONENT; - } -} -function resolveDirective(name) { - return resolveAsset(DIRECTIVES, name); -} -function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) { - const instance = currentRenderingInstance || currentInstance; - if (instance) { - const Component = instance.type; - if (type === COMPONENTS) { - const selfName = getComponentName( - Component, - false - /* do not include inferred name to avoid breaking existing code */ - ); - if (selfName && (selfName === name || selfName === camelize(name) || selfName === capitalize(camelize(name)))) { - return Component; - } - } - const res = ( - // local registration - // check instance[type] first which is resolved for options API - resolve(instance[type] || Component[type], name) || // global registration - resolve(instance.appContext[type], name) - ); - if (!res && maybeSelfReference) { - return Component; - } - if (warnMissing && !res) { - const extra = type === COMPONENTS ? ` -If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.` : ``; - warn(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`); - } - return res; - } else { - warn( - `resolve${capitalize(type.slice(0, -1))} can only be used in render() or setup().` - ); - } -} -function resolve(registry, name) { - return registry && (registry[name] || registry[camelize(name)] || registry[capitalize(camelize(name))]); -} - -function renderList(source, renderItem, cache, index) { - let ret; - const cached = cache && cache[index]; - if (isArray(source) || isString(source)) { - ret = new Array(source.length); - for (let i = 0, l = source.length; i < l; i++) { - ret[i] = renderItem(source[i], i, void 0, cached && cached[i]); - } - } else if (typeof source === "number") { - if (!Number.isInteger(source)) { - warn(`The v-for range expect an integer value but got ${source}.`); - } - ret = new Array(source); - for (let i = 0; i < source; i++) { - ret[i] = renderItem(i + 1, i, void 0, cached && cached[i]); - } - } else if (isObject(source)) { - if (source[Symbol.iterator]) { - ret = Array.from( - source, - (item, i) => renderItem(item, i, void 0, cached && cached[i]) - ); - } else { - const keys = Object.keys(source); - ret = new Array(keys.length); - for (let i = 0, l = keys.length; i < l; i++) { - const key = keys[i]; - ret[i] = renderItem(source[key], key, i, cached && cached[i]); - } - } - } else { - ret = []; - } - if (cache) { - cache[index] = ret; - } - return ret; -} - -function createSlots(slots, dynamicSlots) { - for (let i = 0; i < dynamicSlots.length; i++) { - const slot = dynamicSlots[i]; - if (isArray(slot)) { - for (let j = 0; j < slot.length; j++) { - slots[slot[j].name] = slot[j].fn; - } - } else if (slot) { - slots[slot.name] = slot.key ? (...args) => { - const res = slot.fn(...args); - if (res) - res.key = slot.key; - return res; - } : slot.fn; - } - } - return slots; -} - -function renderSlot(slots, name, props = {}, fallback, noSlotted) { - if (currentRenderingInstance.isCE || currentRenderingInstance.parent && isAsyncWrapper(currentRenderingInstance.parent) && currentRenderingInstance.parent.isCE) { - if (name !== "default") - props.name = name; - return createVNode("slot", props, fallback && fallback()); - } - let slot = slots[name]; - if (slot && slot.length > 1) { - warn( - `SSR-optimized slot function detected in a non-SSR-optimized render function. You need to mark this component with $dynamic-slots in the parent template.` - ); - slot = () => []; - } - if (slot && slot._c) { - slot._d = false; - } - openBlock(); - const validSlotContent = slot && ensureValidVNode(slot(props)); - const rendered = createBlock( - Fragment, - { - key: props.key || // slot content array of a dynamic conditional slot may have a branch - // key attached in the `createSlots` helper, respect that - validSlotContent && validSlotContent.key || `_${name}` - }, - validSlotContent || (fallback ? fallback() : []), - validSlotContent && slots._ === 1 ? 64 : -2 - ); - if (!noSlotted && rendered.scopeId) { - rendered.slotScopeIds = [rendered.scopeId + "-s"]; - } - if (slot && slot._c) { - slot._d = true; - } - return rendered; -} -function ensureValidVNode(vnodes) { - return vnodes.some((child) => { - if (!isVNode(child)) - return true; - if (child.type === Comment) - return false; - if (child.type === Fragment && !ensureValidVNode(child.children)) - return false; - return true; - }) ? vnodes : null; -} - -function toHandlers(obj, preserveCaseIfNecessary) { - const ret = {}; - if (!isObject(obj)) { - warn(`v-on with no argument expects an object value.`); - return ret; - } - for (const key in obj) { - ret[preserveCaseIfNecessary && /[A-Z]/.test(key) ? `on:${key}` : toHandlerKey(key)] = obj[key]; - } - return ret; -} - -const getPublicInstance = (i) => { - if (!i) - return null; - if (isStatefulComponent(i)) - return getExposeProxy(i) || i.proxy; - return getPublicInstance(i.parent); -}; -const publicPropertiesMap = ( - // Move PURE marker to new line to workaround compiler discarding it - // due to type annotation - /* @__PURE__ */ extend(/* @__PURE__ */ Object.create(null), { - $: (i) => i, - $el: (i) => i.vnode.el, - $data: (i) => i.data, - $props: (i) => shallowReadonly(i.props) , - $attrs: (i) => shallowReadonly(i.attrs) , - $slots: (i) => shallowReadonly(i.slots) , - $refs: (i) => shallowReadonly(i.refs) , - $parent: (i) => getPublicInstance(i.parent), - $root: (i) => getPublicInstance(i.root), - $emit: (i) => i.emit, - $options: (i) => resolveMergedOptions(i) , - $forceUpdate: (i) => i.f || (i.f = () => queueJob(i.update)), - $nextTick: (i) => i.n || (i.n = nextTick.bind(i.proxy)), - $watch: (i) => instanceWatch.bind(i) - }) -); -const isReservedPrefix = (key) => key === "_" || key === "$"; -const hasSetupBinding = (state, key) => state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn(state, key); -const PublicInstanceProxyHandlers = { - get({ _: instance }, key) { - const { ctx, setupState, data, props, accessCache, type, appContext } = instance; - if (key === "__isVue") { - return true; - } - let normalizedProps; - if (key[0] !== "$") { - const n = accessCache[key]; - if (n !== void 0) { - switch (n) { - case 1 /* SETUP */: - return setupState[key]; - case 2 /* DATA */: - return data[key]; - case 4 /* CONTEXT */: - return ctx[key]; - case 3 /* PROPS */: - return props[key]; - } - } else if (hasSetupBinding(setupState, key)) { - accessCache[key] = 1 /* SETUP */; - return setupState[key]; - } else if (data !== EMPTY_OBJ && hasOwn(data, key)) { - accessCache[key] = 2 /* DATA */; - return data[key]; - } else if ( - // only cache other properties when instance has declared (thus stable) - // props - (normalizedProps = instance.propsOptions[0]) && hasOwn(normalizedProps, key) - ) { - accessCache[key] = 3 /* PROPS */; - return props[key]; - } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) { - accessCache[key] = 4 /* CONTEXT */; - return ctx[key]; - } else if (shouldCacheAccess) { - accessCache[key] = 0 /* OTHER */; - } - } - const publicGetter = publicPropertiesMap[key]; - let cssModule, globalProperties; - if (publicGetter) { - if (key === "$attrs") { - track(instance, "get", key); - markAttrsAccessed(); - } else if (key === "$slots") { - track(instance, "get", key); - } - return publicGetter(instance); - } else if ( - // css module (injected by vue-loader) - (cssModule = type.__cssModules) && (cssModule = cssModule[key]) - ) { - return cssModule; - } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) { - accessCache[key] = 4 /* CONTEXT */; - return ctx[key]; - } else if ( - // global properties - globalProperties = appContext.config.globalProperties, hasOwn(globalProperties, key) - ) { - { - return globalProperties[key]; - } - } else if (currentRenderingInstance && (!isString(key) || // #1091 avoid internal isRef/isVNode checks on component instance leading - // to infinite warning loop - key.indexOf("__v") !== 0)) { - if (data !== EMPTY_OBJ && isReservedPrefix(key[0]) && hasOwn(data, key)) { - warn( - `Property ${JSON.stringify( - key - )} must be accessed via $data because it starts with a reserved character ("$" or "_") and is not proxied on the render context.` - ); - } else if (instance === currentRenderingInstance) { - warn( - `Property ${JSON.stringify(key)} was accessed during render but is not defined on instance.` - ); - } - } - }, - set({ _: instance }, key, value) { - const { data, setupState, ctx } = instance; - if (hasSetupBinding(setupState, key)) { - setupState[key] = value; - return true; - } else if (setupState.__isScriptSetup && hasOwn(setupState, key)) { - warn(`Cannot mutate