mp-weixin-back 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,302 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
21
+ }
22
+ return a;
23
+ };
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __export = (target, all) => {
26
+ for (var name in all)
27
+ __defProp(target, name, { get: all[name], enumerable: true });
28
+ };
29
+ var __copyProps = (to, from, except, desc) => {
30
+ if (from && typeof from === "object" || typeof from === "function") {
31
+ for (let key of __getOwnPropNames(from))
32
+ if (!__hasOwnProp.call(to, key) && key !== except)
33
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
34
+ }
35
+ return to;
36
+ };
37
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
38
+ // If the importer is in node compatibility mode or this is not an ESM
39
+ // file that has been converted to a CommonJS file using a Babel-
40
+ // compatible transform (i.e. "__esModule" has not been set), then set
41
+ // "default" to the CommonJS "module.exports" for node compatibility.
42
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
43
+ mod
44
+ ));
45
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
46
+ var __async = (__this, __arguments, generator) => {
47
+ return new Promise((resolve, reject) => {
48
+ var fulfilled = (value) => {
49
+ try {
50
+ step(generator.next(value));
51
+ } catch (e) {
52
+ reject(e);
53
+ }
54
+ };
55
+ var rejected = (value) => {
56
+ try {
57
+ step(generator.throw(value));
58
+ } catch (e) {
59
+ reject(e);
60
+ }
61
+ };
62
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
63
+ step((generator = generator.apply(__this, __arguments)).next());
64
+ });
65
+ };
66
+
67
+ // src/index.ts
68
+ var src_exports = {};
69
+ __export(src_exports, {
70
+ default: () => src_default
71
+ });
72
+ module.exports = __toCommonJS(src_exports);
73
+
74
+ // src/context.ts
75
+ var import_path = __toESM(require("path"), 1);
76
+ var import_fs = __toESM(require("fs"), 1);
77
+ var import_json5 = __toESM(require("json5"), 1);
78
+
79
+ // utils/index.ts
80
+ var import_generator = __toESM(require("@babel/generator"), 1);
81
+ var import_compiler_sfc = require("@vue/compiler-sfc");
82
+ var import_ast_kit = require("ast-kit");
83
+
84
+ // utils/constant.ts
85
+ var virtualFileId = "mp-weixin-back-helper";
86
+
87
+ // utils/index.ts
88
+ function isArrowFunction(func) {
89
+ if (typeof func !== "function") return false;
90
+ return !func.hasOwnProperty("prototype") && func.toString().includes("=>");
91
+ }
92
+ function parseSFC(code) {
93
+ return __async(this, null, function* () {
94
+ try {
95
+ return (0, import_compiler_sfc.parse)(code).descriptor;
96
+ } catch (error) {
97
+ throw new Error(`\u89E3\u6790vue\u6587\u4EF6\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6587\u4EF6\u662F\u5426\u6B63\u786E`);
98
+ }
99
+ });
100
+ }
101
+ function transformVueFile(code, id) {
102
+ return __async(this, null, function* () {
103
+ var _a, _b;
104
+ if (code.includes("<page-container")) {
105
+ return code;
106
+ }
107
+ if (!code.includes("<template")) {
108
+ return code;
109
+ }
110
+ const componentStr = '<page-container :show="__MP_BACK_SHOW_PAGE_CONTAINER__" :overlay="false" @beforeleave="onBeforeLeave" :z-index="1" :duration="false"></page-container>';
111
+ const sfc = yield parseSFC(code);
112
+ const setupCode = (_a = sfc.scriptSetup) == null ? void 0 : _a.loc.source;
113
+ const setupAst = (0, import_ast_kit.babelParse)(setupCode || "", (_b = sfc.scriptSetup) == null ? void 0 : _b.lang);
114
+ let pageBackConfig = this.config;
115
+ let hasPageBack = false, hasImportRef = false, pageBackFnName = "onPageBack", callbackCode = ``;
116
+ if (setupAst) {
117
+ (0, import_ast_kit.walkAST)(setupAst, {
118
+ enter(node) {
119
+ var _a2;
120
+ if (node.type == "ImportDeclaration" && node.source.value.includes(virtualFileId)) {
121
+ const importSpecifier = node.specifiers[0];
122
+ hasPageBack = true;
123
+ pageBackFnName = importSpecifier.local.name;
124
+ }
125
+ if (node.type == "ImportDeclaration" && node.source.value === "vue") {
126
+ const importSpecifiers = node.specifiers;
127
+ for (let i = 0; i < importSpecifiers.length; i++) {
128
+ const element = importSpecifiers[i];
129
+ if (element.local.name == "ref") {
130
+ hasImportRef = true;
131
+ break;
132
+ }
133
+ }
134
+ }
135
+ if (node.type == "ExpressionStatement" && node.expression.type == "CallExpression" && ((_a2 = node.expression.callee.loc) == null ? void 0 : _a2.identifierName) == pageBackFnName) {
136
+ const callback = node.expression.arguments[0];
137
+ const backArguments = node.expression.arguments[1];
138
+ if (backArguments && backArguments.type == "ObjectExpression") {
139
+ const config = new Function(`return (${(0, import_generator.default)(backArguments).code});`)();
140
+ pageBackConfig = __spreadValues(__spreadValues({}, pageBackConfig), config);
141
+ }
142
+ if (callback && (callback.type === "ArrowFunctionExpression" || callback.type === "FunctionExpression")) {
143
+ const body = callback.body;
144
+ if (body.type === "BlockStatement") {
145
+ body.body.forEach((statement) => {
146
+ callbackCode += (0, import_generator.default)(statement).code;
147
+ });
148
+ }
149
+ }
150
+ }
151
+ }
152
+ });
153
+ }
154
+ if (!hasPageBack) return;
155
+ if (!pageBackConfig.preventDefault) {
156
+ callbackCode += `uni.navigateBack({ delta: 1 });`;
157
+ }
158
+ const configBack = (() => {
159
+ if (!pageBackConfig.onPageBack) return "";
160
+ if (typeof pageBackConfig.onPageBack !== "function") {
161
+ throw new Error("`onPageBack` must be a function");
162
+ }
163
+ const params = JSON.stringify({
164
+ page: this.getPageById(id)
165
+ });
166
+ const hasFunction = pageBackConfig.onPageBack.toString().includes("function");
167
+ if (isArrowFunction(pageBackConfig.onPageBack) || hasFunction) {
168
+ return `(${pageBackConfig.onPageBack})(${params});`;
169
+ }
170
+ return `(function ${pageBackConfig.onPageBack})()`;
171
+ })();
172
+ const beforeLeaveStr = `
173
+ ${!hasImportRef ? "import { ref } from 'vue'" : ""}
174
+ let __MP_BACK_FREQUENCY__ = 1
175
+ const __MP_BACK_SHOW_PAGE_CONTAINER__ = ref(true);
176
+ const onBeforeLeave = () => {
177
+ console.log("__MP_BACK_FREQUENCY__", __MP_BACK_FREQUENCY__, ${pageBackConfig.frequency})
178
+ if (__MP_BACK_FREQUENCY__ < ${pageBackConfig.frequency}) {
179
+ __MP_BACK_SHOW_PAGE_CONTAINER__.value = false
180
+ setTimeout(() => {
181
+ __MP_BACK_SHOW_PAGE_CONTAINER__.value = true
182
+ }, 0);
183
+ __MP_BACK_FREQUENCY__++
184
+ }
185
+ // \u8FD0\u884C\u914D\u7F6E\u7684\u533F\u540D\u51FD\u6570
186
+ ${configBack}
187
+ ${callbackCode}
188
+ };
189
+ `;
190
+ const result = code.replace(
191
+ /(<template.*?>)([\s\S]*?)(<\/template>)([\s\S]*?)(<script\s+(?:lang="ts"\s+)?setup.*?>|$)/,
192
+ (match, templateStart, templateContent, templateEnd, middleContent, scriptSetup) => {
193
+ const hasScriptSetup = Boolean(scriptSetup);
194
+ const scriptStartTag = hasScriptSetup ? scriptSetup : "<script setup>";
195
+ const scriptEndTag = hasScriptSetup ? "" : "</script>";
196
+ const injectedTemplate = `${templateStart}${templateContent}
197
+ ${componentStr}
198
+ ${templateEnd}`;
199
+ const injectedScript = `
200
+ ${middleContent}${scriptStartTag}
201
+ ${beforeLeaveStr}
202
+ ${scriptEndTag}`;
203
+ return injectedTemplate + injectedScript;
204
+ }
205
+ );
206
+ return result;
207
+ });
208
+ }
209
+
210
+ // src/context.ts
211
+ var pageContext = class {
212
+ constructor(config) {
213
+ this.pages = [];
214
+ this.config = config;
215
+ }
216
+ getPagesJsonPath() {
217
+ const pagesJsonPath = import_path.default.join(this.config.root, "src/pages.json");
218
+ return pagesJsonPath;
219
+ }
220
+ // 获取页面配置详情
221
+ getPagesJsonInfo() {
222
+ return __async(this, null, function* () {
223
+ const hasPagesJson = import_fs.default.existsSync(this.getPagesJsonPath());
224
+ if (!hasPagesJson) return;
225
+ try {
226
+ const content = yield import_fs.default.promises.readFile(this.getPagesJsonPath(), "utf-8");
227
+ const pagesContent = import_json5.default.parse(content);
228
+ const { pages, subpackages } = pagesContent;
229
+ if (pages) {
230
+ const mainPages = pages.reduce((acc, current) => {
231
+ acc.push(current.path);
232
+ return acc;
233
+ }, []);
234
+ this.pages.push(...mainPages);
235
+ }
236
+ if (subpackages) {
237
+ const root = subpackages.root;
238
+ const subPages = subpackages.pages.reduce((acc, current) => {
239
+ acc.push(`${root}/${current.path}`.replace("//", "/"));
240
+ return acc;
241
+ }, []);
242
+ this.pages.push(...subPages);
243
+ }
244
+ } catch (error) {
245
+ throw new Error("\u8BF7\u6B63\u786E\u914D\u7F6E\u9879\u76EE\u7684pages.json\u6587\u4EF6");
246
+ }
247
+ });
248
+ }
249
+ // 获取指定id的page
250
+ getPageById(id) {
251
+ const path2 = (id.split("src/")[1] || "").replace(".vue", "");
252
+ return this.pages.find((i) => i === path2) || null;
253
+ }
254
+ transform(code, id) {
255
+ return __async(this, null, function* () {
256
+ const result = yield transformVueFile.call(this, code, id);
257
+ return result;
258
+ });
259
+ }
260
+ };
261
+
262
+ // src/index.ts
263
+ function MpBackPlugin(userOptions = {}) {
264
+ let context;
265
+ const defaultOptions = {
266
+ preventDefault: false,
267
+ frequency: 1
268
+ };
269
+ const options = __spreadValues(__spreadValues({}, defaultOptions), userOptions);
270
+ return {
271
+ name: "vite-plugin-mp-weixin-back",
272
+ enforce: "pre",
273
+ configResolved(config) {
274
+ context = new pageContext(__spreadProps(__spreadValues({}, options), { mode: config.mode, root: config.root }));
275
+ },
276
+ buildStart() {
277
+ context.getPagesJsonInfo();
278
+ },
279
+ resolveId(id) {
280
+ if (id === virtualFileId) {
281
+ return virtualFileId;
282
+ }
283
+ },
284
+ load(id) {
285
+ if (id.includes("node_modules")) {
286
+ return;
287
+ }
288
+ if (id === virtualFileId) {
289
+ return `export default function onPageBack() {}`;
290
+ }
291
+ },
292
+ transform(code, id) {
293
+ return __async(this, null, function* () {
294
+ if (id.includes("node_modules") || !id.includes(".vue")) {
295
+ return;
296
+ }
297
+ return context.transform(code, id);
298
+ });
299
+ }
300
+ };
301
+ }
302
+ var src_default = MpBackPlugin;