@weapp-vite/web 1.3.14 → 1.3.16
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/_virtual/_rolldown/runtime.mjs +18 -0
- package/dist/compiler/wxml/attributes.mjs +93 -0
- package/dist/compiler/wxml/attributes.mjs.map +1 -0
- package/dist/compiler/wxml/compile.mjs +158 -0
- package/dist/compiler/wxml/compile.mjs.map +1 -0
- package/dist/compiler/wxml/dependency.mjs +31 -0
- package/dist/compiler/wxml/dependency.mjs.map +1 -0
- package/dist/compiler/wxml/interpolation.mjs +142 -0
- package/dist/compiler/wxml/interpolation.mjs.map +1 -0
- package/dist/compiler/wxml/navigation.mjs +85 -0
- package/dist/compiler/wxml/navigation.mjs.map +1 -0
- package/dist/compiler/wxml/parser.mjs +41 -0
- package/dist/compiler/wxml/parser.mjs.map +1 -0
- package/dist/compiler/wxml/renderer.mjs +114 -0
- package/dist/compiler/wxml/renderer.mjs.map +1 -0
- package/dist/compiler/wxml/specialNodes.mjs +84 -0
- package/dist/compiler/wxml/specialNodes.mjs.map +1 -0
- package/dist/compiler/wxs.mjs +83 -0
- package/dist/compiler/wxs.mjs.map +1 -0
- package/dist/css/wxss.d.mts +25 -0
- package/dist/css/wxss.mjs +17 -0
- package/dist/css/wxss.mjs.map +1 -0
- package/dist/index.d.mts +18 -2
- package/dist/index.mjs +18 -3
- package/dist/plugin/constants.mjs +43 -0
- package/dist/plugin/constants.mjs.map +1 -0
- package/dist/plugin/entry.mjs +29 -0
- package/dist/plugin/entry.mjs.map +1 -0
- package/dist/plugin/files.mjs +58 -0
- package/dist/plugin/files.mjs.map +1 -0
- package/dist/plugin/index.d.mts +33 -0
- package/dist/plugin/index.mjs +188 -0
- package/dist/plugin/index.mjs.map +1 -0
- package/dist/plugin/navigation.mjs +20 -0
- package/dist/plugin/navigation.mjs.map +1 -0
- package/dist/plugin/path.mjs +85 -0
- package/dist/plugin/path.mjs.map +1 -0
- package/dist/plugin/register.mjs +83 -0
- package/dist/plugin/register.mjs.map +1 -0
- package/dist/plugin/scan.mjs +195 -0
- package/dist/plugin/scan.mjs.map +1 -0
- package/dist/plugin/scanConfig.mjs +45 -0
- package/dist/plugin/scanConfig.mjs.map +1 -0
- package/dist/plugin/state.mjs +22 -0
- package/dist/plugin/state.mjs.map +1 -0
- package/dist/plugin/types.d.mts +46 -0
- package/dist/plugin.d.mts +3 -2
- package/dist/plugin.mjs +3 -2
- package/dist/runtime/button/helpers.mjs +92 -0
- package/dist/runtime/button/helpers.mjs.map +1 -0
- package/dist/runtime/button/index.d.mts +9 -0
- package/dist/runtime/button/index.mjs +198 -0
- package/dist/runtime/button/index.mjs.map +1 -0
- package/dist/runtime/button/style.mjs +168 -0
- package/dist/runtime/button/style.mjs.map +1 -0
- package/dist/runtime/component/behavior.mjs +98 -0
- package/dist/runtime/component/behavior.mjs.map +1 -0
- package/dist/runtime/component/constants.mjs +8 -0
- package/dist/runtime/component/constants.mjs.map +1 -0
- package/dist/runtime/component/dom.mjs +26 -0
- package/dist/runtime/component/dom.mjs.map +1 -0
- package/dist/runtime/component/element.mjs +208 -0
- package/dist/runtime/component/element.mjs.map +1 -0
- package/dist/runtime/component/events.mjs +48 -0
- package/dist/runtime/component/events.mjs.map +1 -0
- package/dist/runtime/component/index.d.mts +7 -0
- package/dist/runtime/component/index.mjs +44 -0
- package/dist/runtime/component/index.mjs.map +1 -0
- package/dist/runtime/component/state.mjs +63 -0
- package/dist/runtime/component/state.mjs.map +1 -0
- package/dist/runtime/component/types.d.mts +49 -0
- package/dist/runtime/component/utils.mjs +39 -0
- package/dist/runtime/component/utils.mjs.map +1 -0
- package/dist/runtime/execution.d.mts +7 -0
- package/dist/runtime/execution.mjs +37 -0
- package/dist/runtime/execution.mjs.map +1 -0
- package/dist/runtime/index.d.mts +16 -2
- package/dist/runtime/index.mjs +16 -2
- package/dist/runtime/legacyTemplate/dom.mjs +131 -0
- package/dist/runtime/legacyTemplate/dom.mjs.map +1 -0
- package/dist/runtime/legacyTemplate/expression.mjs +113 -0
- package/dist/runtime/legacyTemplate/expression.mjs.map +1 -0
- package/dist/runtime/legacyTemplate/index.d.mts +9 -0
- package/dist/runtime/legacyTemplate/index.mjs +131 -0
- package/dist/runtime/legacyTemplate/index.mjs.map +1 -0
- package/dist/runtime/legacyTemplate/types.d.mts +6 -0
- package/dist/runtime/navigationBar/index.d.mts +10 -0
- package/dist/runtime/navigationBar/index.mjs +162 -0
- package/dist/runtime/navigationBar/index.mjs.map +1 -0
- package/dist/runtime/navigationBar/style.mjs +108 -0
- package/dist/runtime/navigationBar/style.mjs.map +1 -0
- package/dist/runtime/polyfill/ad.mjs +150 -0
- package/dist/runtime/polyfill/ad.mjs.map +1 -0
- package/dist/runtime/polyfill/appState.mjs +31 -0
- package/dist/runtime/polyfill/appState.mjs.map +1 -0
- package/dist/runtime/polyfill/async.mjs +31 -0
- package/dist/runtime/polyfill/async.mjs.map +1 -0
- package/dist/runtime/polyfill/auth.mjs +120 -0
- package/dist/runtime/polyfill/auth.mjs.map +1 -0
- package/dist/runtime/polyfill/authApi.mjs +101 -0
- package/dist/runtime/polyfill/authApi.mjs.map +1 -0
- package/dist/runtime/polyfill/background.mjs +31 -0
- package/dist/runtime/polyfill/background.mjs.map +1 -0
- package/dist/runtime/polyfill/canvasContext.mjs +115 -0
- package/dist/runtime/polyfill/canvasContext.mjs.map +1 -0
- package/dist/runtime/polyfill/capability.mjs +17 -0
- package/dist/runtime/polyfill/capability.mjs.map +1 -0
- package/dist/runtime/polyfill/cloud.mjs +39 -0
- package/dist/runtime/polyfill/cloud.mjs.map +1 -0
- package/dist/runtime/polyfill/device.mjs +44 -0
- package/dist/runtime/polyfill/device.mjs.map +1 -0
- package/dist/runtime/polyfill/deviceApi.mjs +31 -0
- package/dist/runtime/polyfill/deviceApi.mjs.map +1 -0
- package/dist/runtime/polyfill/deviceAuthSystemApi.d.mts +102 -0
- package/dist/runtime/polyfill/deviceAuthSystemApi.mjs +144 -0
- package/dist/runtime/polyfill/deviceAuthSystemApi.mjs.map +1 -0
- package/dist/runtime/polyfill/filePicker.mjs +158 -0
- package/dist/runtime/polyfill/filePicker.mjs.map +1 -0
- package/dist/runtime/polyfill/fileSystemManager.mjs +45 -0
- package/dist/runtime/polyfill/fileSystemManager.mjs.map +1 -0
- package/dist/runtime/polyfill/files.mjs +118 -0
- package/dist/runtime/polyfill/files.mjs.map +1 -0
- package/dist/runtime/polyfill/index.d.mts +40 -0
- package/dist/runtime/polyfill/index.mjs +99 -0
- package/dist/runtime/polyfill/index.mjs.map +1 -0
- package/dist/runtime/polyfill/interaction.mjs +38 -0
- package/dist/runtime/polyfill/interaction.mjs.map +1 -0
- package/dist/runtime/polyfill/interactionApi.mjs +54 -0
- package/dist/runtime/polyfill/interactionApi.mjs.map +1 -0
- package/dist/runtime/polyfill/location.mjs +106 -0
- package/dist/runtime/polyfill/location.mjs.map +1 -0
- package/dist/runtime/polyfill/locationApi.mjs +120 -0
- package/dist/runtime/polyfill/locationApi.mjs.map +1 -0
- package/dist/runtime/polyfill/mediaActions.mjs +52 -0
- package/dist/runtime/polyfill/mediaActions.mjs.map +1 -0
- package/dist/runtime/polyfill/mediaApi/file.mjs +63 -0
- package/dist/runtime/polyfill/mediaApi/file.mjs.map +1 -0
- package/dist/runtime/polyfill/mediaApi/info.mjs +59 -0
- package/dist/runtime/polyfill/mediaApi/info.mjs.map +1 -0
- package/dist/runtime/polyfill/mediaApi/picker.mjs +82 -0
- package/dist/runtime/polyfill/mediaApi/picker.mjs.map +1 -0
- package/dist/runtime/polyfill/mediaApi/preview.mjs +39 -0
- package/dist/runtime/polyfill/mediaApi/preview.mjs.map +1 -0
- package/dist/runtime/polyfill/mediaApi/process.mjs +46 -0
- package/dist/runtime/polyfill/mediaApi/process.mjs.map +1 -0
- package/dist/runtime/polyfill/mediaInfo.mjs +136 -0
- package/dist/runtime/polyfill/mediaInfo.mjs.map +1 -0
- package/dist/runtime/polyfill/mediaPicker.mjs +213 -0
- package/dist/runtime/polyfill/mediaPicker.mjs.map +1 -0
- package/dist/runtime/polyfill/mediaProcess.mjs +65 -0
- package/dist/runtime/polyfill/mediaProcess.mjs.map +1 -0
- package/dist/runtime/polyfill/menuApi.mjs +70 -0
- package/dist/runtime/polyfill/menuApi.mjs.map +1 -0
- package/dist/runtime/polyfill/navigationBarRuntime.mjs +65 -0
- package/dist/runtime/polyfill/navigationBarRuntime.mjs.map +1 -0
- package/dist/runtime/polyfill/network/request.mjs +162 -0
- package/dist/runtime/polyfill/network/request.mjs.map +1 -0
- package/dist/runtime/polyfill/network/requestBridge.mjs +49 -0
- package/dist/runtime/polyfill/network/requestBridge.mjs.map +1 -0
- package/dist/runtime/polyfill/network/status.mjs +55 -0
- package/dist/runtime/polyfill/network/status.mjs.map +1 -0
- package/dist/runtime/polyfill/platformApi.mjs +33 -0
- package/dist/runtime/polyfill/platformApi.mjs.map +1 -0
- package/dist/runtime/polyfill/platformRuntime.mjs +120 -0
- package/dist/runtime/polyfill/platformRuntime.mjs.map +1 -0
- package/dist/runtime/polyfill/routeRuntime/dom.mjs +36 -0
- package/dist/runtime/polyfill/routeRuntime/dom.mjs.map +1 -0
- package/dist/runtime/polyfill/routeRuntime/lifecycle.mjs +83 -0
- package/dist/runtime/polyfill/routeRuntime/lifecycle.mjs.map +1 -0
- package/dist/runtime/polyfill/routeRuntime/options.d.mts +33 -0
- package/dist/runtime/polyfill/routeRuntime/options.mjs +76 -0
- package/dist/runtime/polyfill/routeRuntime/options.mjs.map +1 -0
- package/dist/runtime/polyfill/routeRuntime/url.mjs +35 -0
- package/dist/runtime/polyfill/routeRuntime/url.mjs.map +1 -0
- package/dist/runtime/polyfill/routeRuntime.d.mts +43 -0
- package/dist/runtime/polyfill/routeRuntime.mjs +202 -0
- package/dist/runtime/polyfill/routeRuntime.mjs.map +1 -0
- package/dist/runtime/polyfill/runtimeCapabilityApi.mjs +26 -0
- package/dist/runtime/polyfill/runtimeCapabilityApi.mjs.map +1 -0
- package/dist/runtime/polyfill/runtimeDataApi.d.mts +79 -0
- package/dist/runtime/polyfill/runtimeDataApi.mjs +134 -0
- package/dist/runtime/polyfill/runtimeDataApi.mjs.map +1 -0
- package/dist/runtime/polyfill/runtimeInfra.mjs +40 -0
- package/dist/runtime/polyfill/runtimeInfra.mjs.map +1 -0
- package/dist/runtime/polyfill/runtimeOps.mjs +62 -0
- package/dist/runtime/polyfill/runtimeOps.mjs.map +1 -0
- package/dist/runtime/polyfill/selectorQuery.mjs +204 -0
- package/dist/runtime/polyfill/selectorQuery.mjs.map +1 -0
- package/dist/runtime/polyfill/storage.mjs +103 -0
- package/dist/runtime/polyfill/storage.mjs.map +1 -0
- package/dist/runtime/polyfill/storageAsync.mjs +62 -0
- package/dist/runtime/polyfill/storageAsync.mjs.map +1 -0
- package/dist/runtime/polyfill/subscribe.mjs +30 -0
- package/dist/runtime/polyfill/subscribe.mjs.map +1 -0
- package/dist/runtime/polyfill/system.mjs +111 -0
- package/dist/runtime/polyfill/system.mjs.map +1 -0
- package/dist/runtime/polyfill/systemApi.mjs +65 -0
- package/dist/runtime/polyfill/systemApi.mjs.map +1 -0
- package/dist/runtime/polyfill/types/base.d.mts +12 -0
- package/dist/runtime/polyfill/types/common.d.mts +126 -0
- package/dist/runtime/polyfill/types/locationRuntime.d.mts +151 -0
- package/dist/runtime/polyfill/types/mediaAuth.d.mts +152 -0
- package/dist/runtime/polyfill/types/platformRuntime.d.mts +141 -0
- package/dist/runtime/polyfill/types/systemAuth.d.mts +122 -0
- package/dist/runtime/polyfill/ui.mjs +135 -0
- package/dist/runtime/polyfill/ui.mjs.map +1 -0
- package/dist/runtime/polyfill/uiFeedback.mjs +35 -0
- package/dist/runtime/polyfill/uiFeedback.mjs.map +1 -0
- package/dist/runtime/polyfill/uiMediaApi.d.mts +172 -0
- package/dist/runtime/polyfill/uiMediaApi.mjs +162 -0
- package/dist/runtime/polyfill/uiMediaApi.mjs.map +1 -0
- package/dist/runtime/polyfill/videoContext.mjs +56 -0
- package/dist/runtime/polyfill/videoContext.mjs.map +1 -0
- package/dist/runtime/polyfill/vkSession.mjs +58 -0
- package/dist/runtime/polyfill/vkSession.mjs.map +1 -0
- package/dist/runtime/polyfill/windowResize.mjs +39 -0
- package/dist/runtime/polyfill/windowResize.mjs.map +1 -0
- package/dist/runtime/polyfill/worker.mjs +77 -0
- package/dist/runtime/polyfill/worker.mjs.map +1 -0
- package/dist/runtime/polyfill.d.mts +5 -0
- package/dist/runtime/renderContext.d.mts +21 -0
- package/dist/runtime/renderContext.mjs +147 -0
- package/dist/runtime/renderContext.mjs.map +1 -0
- package/dist/runtime/rpx.d.mts +9 -0
- package/dist/runtime/rpx.mjs +27 -0
- package/dist/runtime/rpx.mjs.map +1 -0
- package/dist/runtime/style.d.mts +6 -0
- package/dist/runtime/style.mjs +37 -0
- package/dist/runtime/style.mjs.map +1 -0
- package/dist/runtime/template.d.mts +10 -0
- package/dist/runtime/warning.d.mts +10 -0
- package/dist/runtime/warning.mjs +43 -0
- package/dist/runtime/warning.mjs.map +1 -0
- package/dist/{slugify-B4l45KNs.mjs → shared/slugify.mjs} +3 -1
- package/dist/shared/slugify.mjs.map +1 -0
- package/dist/shared/wxml.mjs +64 -0
- package/dist/shared/wxml.mjs.map +1 -0
- package/package.json +2 -2
- package/dist/index-w9xxIH-l.d.mts +0 -1229
- package/dist/plugin-BARxSPO8.mjs +0 -1567
- package/dist/plugin-DP2iPVmw.d.mts +0 -96
- package/dist/runtime-D6j2_x_N.mjs +0 -6251
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { SELF_CLOSING_TAGS, normalizeTagName } from "../../shared/wxml.mjs";
|
|
2
|
+
import { buildExpression, buildTemplateDataExpression, parseInterpolations } from "./interpolation.mjs";
|
|
3
|
+
import { extractFor, isConditionalElement, renderAttributes, resolveComponentTagName, stripControlAttributes } from "./attributes.mjs";
|
|
4
|
+
|
|
5
|
+
//#region src/compiler/wxml/renderer.ts
|
|
6
|
+
var Renderer = class {
|
|
7
|
+
renderNodes(nodes, scopeVar, wxsVar, componentTags) {
|
|
8
|
+
const parts = [];
|
|
9
|
+
for (let index = 0; index < nodes.length; index += 1) {
|
|
10
|
+
const node = nodes[index];
|
|
11
|
+
if (isConditionalElement(node)) {
|
|
12
|
+
const { rendered, endIndex } = this.renderConditionalSequence(nodes, index, scopeVar, wxsVar, componentTags);
|
|
13
|
+
parts.push(rendered);
|
|
14
|
+
index = endIndex;
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
parts.push(this.renderNode(node, scopeVar, wxsVar, componentTags));
|
|
18
|
+
}
|
|
19
|
+
if (parts.length === 0) return "\"\"";
|
|
20
|
+
if (parts.length === 1) return parts[0];
|
|
21
|
+
return `[${parts.join(", ")}]`;
|
|
22
|
+
}
|
|
23
|
+
renderConditionalSequence(nodes, startIndex, scopeVar, wxsVar, componentTags) {
|
|
24
|
+
const branches = [];
|
|
25
|
+
let cursor = startIndex;
|
|
26
|
+
while (cursor < nodes.length) {
|
|
27
|
+
const candidate = nodes[cursor];
|
|
28
|
+
if (!isConditionalElement(candidate)) break;
|
|
29
|
+
const attribs = candidate.attribs ?? {};
|
|
30
|
+
if (branches.length === 0 && !("wx:if" in attribs)) break;
|
|
31
|
+
if (branches.length > 0 && !("wx:elif" in attribs) && !("wx:else" in attribs)) break;
|
|
32
|
+
branches.push({
|
|
33
|
+
node: candidate,
|
|
34
|
+
attribs
|
|
35
|
+
});
|
|
36
|
+
cursor += 1;
|
|
37
|
+
if ("wx:else" in attribs) break;
|
|
38
|
+
}
|
|
39
|
+
if (!branches.length) {
|
|
40
|
+
const node = nodes[startIndex];
|
|
41
|
+
if (!node) return {
|
|
42
|
+
rendered: "\"\"",
|
|
43
|
+
endIndex: startIndex
|
|
44
|
+
};
|
|
45
|
+
return {
|
|
46
|
+
rendered: this.renderNode(node, scopeVar, wxsVar, componentTags),
|
|
47
|
+
endIndex: startIndex
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
let expr = "\"\"";
|
|
51
|
+
for (let index = branches.length - 1; index >= 0; index -= 1) {
|
|
52
|
+
const { node, attribs } = branches[index];
|
|
53
|
+
const cleanedAttribs = stripControlAttributes(attribs);
|
|
54
|
+
if ("wx:else" in attribs) {
|
|
55
|
+
expr = this.renderElement(node, scopeVar, wxsVar, componentTags, { overrideAttribs: cleanedAttribs });
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const conditionExpr = attribs["wx:if"] ?? attribs["wx:elif"] ?? "";
|
|
59
|
+
const rendered = this.renderElement(node, scopeVar, wxsVar, componentTags, { overrideAttribs: cleanedAttribs });
|
|
60
|
+
expr = `(${buildExpression(parseInterpolations(conditionExpr), scopeVar, wxsVar)} ? ${rendered} : ${expr})`;
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
rendered: expr,
|
|
64
|
+
endIndex: startIndex + branches.length - 1
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
renderNode(node, scopeVar, wxsVar, componentTags) {
|
|
68
|
+
if (node.type === "text") return buildExpression(parseInterpolations(node.data ?? ""), scopeVar, wxsVar);
|
|
69
|
+
if (node.type === "element") {
|
|
70
|
+
if (node.name === "template" && node.attribs?.is) return this.renderTemplateInvoke(node, scopeVar, wxsVar);
|
|
71
|
+
return this.renderElement(node, scopeVar, wxsVar, componentTags);
|
|
72
|
+
}
|
|
73
|
+
return "\"\"";
|
|
74
|
+
}
|
|
75
|
+
renderTemplateInvoke(node, scopeVar, wxsVar) {
|
|
76
|
+
const attribs = node.attribs ?? {};
|
|
77
|
+
const isExpr = buildExpression(parseInterpolations(attribs.is ?? ""), scopeVar, wxsVar);
|
|
78
|
+
const dataExpr = attribs.data ? buildTemplateDataExpression(attribs.data, scopeVar, wxsVar) : void 0;
|
|
79
|
+
return `ctx.renderTemplate(__templates, ${isExpr}, ${dataExpr ? `ctx.mergeScope(${scopeVar}, ${dataExpr})` : scopeVar}, ctx)`;
|
|
80
|
+
}
|
|
81
|
+
renderElement(node, scopeVar, wxsVar, componentTags, options = {}) {
|
|
82
|
+
const attribs = options.overrideAttribs ?? node.attribs ?? {};
|
|
83
|
+
if (!options.skipFor) {
|
|
84
|
+
const forInfo = extractFor(node.attribs ?? {});
|
|
85
|
+
if (forInfo.expr) {
|
|
86
|
+
const listExpr = `ctx.normalizeList(${buildExpression(parseInterpolations(forInfo.expr), scopeVar, wxsVar)})`;
|
|
87
|
+
const itemVar = forInfo.itemName;
|
|
88
|
+
const indexVar = forInfo.indexName;
|
|
89
|
+
const scopeExpr = `ctx.createScope(${scopeVar}, { ${itemVar}: ${itemVar}, ${indexVar}: ${indexVar} })`;
|
|
90
|
+
const itemRender = this.renderElement(node, "__scope", wxsVar, componentTags, {
|
|
91
|
+
skipFor: true,
|
|
92
|
+
overrideAttribs: forInfo.restAttribs
|
|
93
|
+
});
|
|
94
|
+
return `repeat(${listExpr}, (${itemVar}, ${indexVar}) => ${`ctx.key(${JSON.stringify(forInfo.key ?? "")}, ${itemVar}, ${indexVar}, ${scopeExpr}, ${wxsVar})`}, (${itemVar}, ${indexVar}) => { const __scope = ${scopeExpr}; return ${itemRender}; })`;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const customTag = resolveComponentTagName(node.name ?? "", componentTags);
|
|
98
|
+
const tagName = customTag ?? normalizeTagName(node.name ?? "");
|
|
99
|
+
if (tagName === "#fragment") return this.renderNodes(node.children ?? [], scopeVar, wxsVar, componentTags);
|
|
100
|
+
const attrs = renderAttributes(attribs, scopeVar, wxsVar, {
|
|
101
|
+
skipControl: true,
|
|
102
|
+
preferProperty: Boolean(customTag)
|
|
103
|
+
});
|
|
104
|
+
const childNodes = node.children ?? [];
|
|
105
|
+
const children = childNodes.map((child) => `\${${this.renderNode(child, scopeVar, wxsVar, componentTags)}}`).join("");
|
|
106
|
+
if (SELF_CLOSING_TAGS.has(tagName) && childNodes.length === 0) return `html\`<${tagName}${attrs} />\``;
|
|
107
|
+
return `html\`<${tagName}${attrs}>${children}</${tagName}>\``;
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
const renderer = new Renderer();
|
|
111
|
+
|
|
112
|
+
//#endregion
|
|
113
|
+
export { renderer };
|
|
114
|
+
//# sourceMappingURL=renderer.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"renderer.mjs","names":[],"sources":["../../../src/compiler/wxml/renderer.ts"],"sourcesContent":["import type { RenderElementNode, RenderNode } from './types'\nimport { normalizeTagName, SELF_CLOSING_TAGS } from '../../shared/wxml'\nimport {\n extractFor,\n isConditionalElement,\n renderAttributes,\n resolveComponentTagName,\n stripControlAttributes,\n} from './attributes'\nimport { buildExpression, buildTemplateDataExpression, parseInterpolations } from './interpolation'\n\ninterface RenderElementOptions {\n skipFor?: boolean\n overrideAttribs?: Record<string, string>\n}\n\nexport class Renderer {\n renderNodes(\n nodes: RenderNode[],\n scopeVar: string,\n wxsVar: string,\n componentTags?: Record<string, string>,\n ): string {\n const parts: string[] = []\n for (let index = 0; index < nodes.length; index += 1) {\n const node = nodes[index]\n if (isConditionalElement(node)) {\n const { rendered, endIndex } = this.renderConditionalSequence(\n nodes,\n index,\n scopeVar,\n wxsVar,\n componentTags,\n )\n parts.push(rendered)\n index = endIndex\n continue\n }\n parts.push(this.renderNode(node, scopeVar, wxsVar, componentTags))\n }\n if (parts.length === 0) {\n return '\"\"'\n }\n if (parts.length === 1) {\n return parts[0]!\n }\n return `[${parts.join(', ')}]`\n }\n\n private renderConditionalSequence(\n nodes: RenderNode[],\n startIndex: number,\n scopeVar: string,\n wxsVar: string,\n componentTags?: Record<string, string>,\n ): { rendered: string, endIndex: number } {\n const branches: Array<{ node: RenderElementNode, attribs: Record<string, string> }> = []\n let cursor = startIndex\n while (cursor < nodes.length) {\n const candidate = nodes[cursor]\n if (!isConditionalElement(candidate)) {\n break\n }\n const attribs = candidate.attribs ?? {}\n if (branches.length === 0 && !('wx:if' in attribs)) {\n break\n }\n if (branches.length > 0 && !('wx:elif' in attribs) && !('wx:else' in attribs)) {\n break\n }\n branches.push({ node: candidate, attribs })\n cursor += 1\n if ('wx:else' in attribs) {\n break\n }\n }\n if (!branches.length) {\n const node = nodes[startIndex]\n if (!node) {\n return { rendered: '\"\"', endIndex: startIndex }\n }\n return { rendered: this.renderNode(node, scopeVar, wxsVar, componentTags), endIndex: startIndex }\n }\n let expr = '\"\"'\n for (let index = branches.length - 1; index >= 0; index -= 1) {\n const { node, attribs } = branches[index]!\n const cleanedAttribs = stripControlAttributes(attribs)\n if ('wx:else' in attribs) {\n expr = this.renderElement(node, scopeVar, wxsVar, componentTags, { overrideAttribs: cleanedAttribs })\n continue\n }\n const conditionExpr = attribs['wx:if'] ?? attribs['wx:elif'] ?? ''\n const rendered = this.renderElement(node, scopeVar, wxsVar, componentTags, { overrideAttribs: cleanedAttribs })\n const condition = buildExpression(parseInterpolations(conditionExpr), scopeVar, wxsVar)\n expr = `(${condition} ? ${rendered} : ${expr})`\n }\n return { rendered: expr, endIndex: startIndex + branches.length - 1 }\n }\n\n private renderNode(\n node: RenderNode,\n scopeVar: string,\n wxsVar: string,\n componentTags?: Record<string, string>,\n ): string {\n if (node.type === 'text') {\n const parts = parseInterpolations(node.data ?? '')\n return buildExpression(parts, scopeVar, wxsVar)\n }\n if (node.type === 'element') {\n if (node.name === 'template' && node.attribs?.is) {\n return this.renderTemplateInvoke(node, scopeVar, wxsVar)\n }\n return this.renderElement(node, scopeVar, wxsVar, componentTags)\n }\n return '\"\"'\n }\n\n private renderTemplateInvoke(\n node: RenderElementNode,\n scopeVar: string,\n wxsVar: string,\n ): string {\n const attribs = node.attribs ?? {}\n const isExpr = buildExpression(parseInterpolations(attribs.is ?? ''), scopeVar, wxsVar)\n const dataExpr = attribs.data\n ? buildTemplateDataExpression(attribs.data, scopeVar, wxsVar)\n : undefined\n const scopeExpr = dataExpr\n ? `ctx.mergeScope(${scopeVar}, ${dataExpr})`\n : scopeVar\n return `ctx.renderTemplate(__templates, ${isExpr}, ${scopeExpr}, ctx)`\n }\n\n private renderElement(\n node: RenderElementNode,\n scopeVar: string,\n wxsVar: string,\n componentTags?: Record<string, string>,\n options: RenderElementOptions = {},\n ): string {\n const attribs = options.overrideAttribs ?? node.attribs ?? {}\n if (!options.skipFor) {\n const forInfo = extractFor(node.attribs ?? {})\n if (forInfo.expr) {\n const listExpression = buildExpression(parseInterpolations(forInfo.expr), scopeVar, wxsVar)\n const listExpr = `ctx.normalizeList(${listExpression})`\n const itemVar = forInfo.itemName\n const indexVar = forInfo.indexName\n const scopeExpr = `ctx.createScope(${scopeVar}, { ${itemVar}: ${itemVar}, ${indexVar}: ${indexVar} })`\n const itemRender = this.renderElement(\n node,\n '__scope',\n wxsVar,\n componentTags,\n { skipFor: true, overrideAttribs: forInfo.restAttribs },\n )\n const keyExpr = `ctx.key(${JSON.stringify(forInfo.key ?? '')}, ${itemVar}, ${indexVar}, ${scopeExpr}, ${wxsVar})`\n return `repeat(${listExpr}, (${itemVar}, ${indexVar}) => ${keyExpr}, (${itemVar}, ${indexVar}) => { const __scope = ${scopeExpr}; return ${itemRender}; })`\n }\n }\n\n const customTag = resolveComponentTagName(node.name ?? '', componentTags)\n const tagName = customTag ?? normalizeTagName(node.name ?? '')\n if (tagName === '#fragment') {\n return this.renderNodes(node.children ?? [], scopeVar, wxsVar, componentTags)\n }\n\n const attrs = renderAttributes(attribs, scopeVar, wxsVar, {\n skipControl: true,\n preferProperty: Boolean(customTag),\n })\n const childNodes = node.children ?? []\n const children = childNodes\n .map(child => `\\${${this.renderNode(child, scopeVar, wxsVar, componentTags)}}`)\n .join('')\n if (SELF_CLOSING_TAGS.has(tagName) && childNodes.length === 0) {\n return `html\\`<${tagName}${attrs} />\\``\n }\n return `html\\`<${tagName}${attrs}>${children}</${tagName}>\\``\n }\n}\n\nexport const renderer = new Renderer()\n"],"mappings":";;;;;AAgBA,IAAa,WAAb,MAAsB;CACpB,YACE,OACA,UACA,QACA,eACQ;EACR,MAAM,QAAkB,EAAE;AAC1B,OAAK,IAAI,QA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if (lower.endsWith(".wxs") || lower.endsWith(".wxs.ts") || lower.endsWith(".wxs.js")) return false;
|
|
7
|
+
return lower.endsWith(".ts") || lower.endsWith(".js");
|
|
8
|
+
}
|
|
9
|
+
function collectSpecialNodes(nodes, context) {
|
|
10
|
+
const renderable = [];
|
|
11
|
+
for (const node of nodes) {
|
|
12
|
+
if (node.type === "element") {
|
|
13
|
+
const name = node.name ?? "";
|
|
14
|
+
if (name === "template" && node.attribs?.name) {
|
|
15
|
+
context.templates.push({
|
|
16
|
+
name: node.attribs.name,
|
|
17
|
+
nodes: collectSpecialNodes(node.children ?? [], context)
|
|
18
|
+
});
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
if ((name === "import" || name === "wx-import") && node.attribs?.src) {
|
|
22
|
+
const resolved = context.resolveTemplate(node.attribs.src);
|
|
23
|
+
if (resolved) context.imports.push({
|
|
24
|
+
id: resolved,
|
|
25
|
+
importName: `__wxml_import_${context.imports.length}`
|
|
26
|
+
});
|
|
27
|
+
else context.warnings.push(`[web] 无法解析模板依赖: ${node.attribs.src} (from ${context.sourceId})`);
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if ((name === "include" || name === "wx-include") && node.attribs?.src) {
|
|
31
|
+
const resolved = context.resolveTemplate(node.attribs.src);
|
|
32
|
+
if (resolved) context.includes.push({
|
|
33
|
+
id: resolved,
|
|
34
|
+
importName: `__wxml_include_${context.includes.length}`
|
|
35
|
+
});
|
|
36
|
+
else context.warnings.push(`[web] 无法解析模板依赖: ${node.attribs.src} (from ${context.sourceId})`);
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (name === "wxs") {
|
|
40
|
+
const moduleName = node.attribs?.module?.trim();
|
|
41
|
+
if (moduleName) {
|
|
42
|
+
if (context.wxsModules.get(moduleName)) context.warnings.push(`[web] WXS 模块名重复: ${moduleName} (from ${context.sourceId})`);
|
|
43
|
+
context.wxsModules.set(moduleName, context.sourceId);
|
|
44
|
+
if (node.attribs?.src) {
|
|
45
|
+
const resolved = context.resolveWxs(node.attribs.src);
|
|
46
|
+
if (resolved) context.wxs.push({
|
|
47
|
+
module: moduleName,
|
|
48
|
+
kind: "src",
|
|
49
|
+
importName: `__wxs_${context.wxs.length}`,
|
|
50
|
+
value: resolved
|
|
51
|
+
});
|
|
52
|
+
} else {
|
|
53
|
+
const inlineCode = (node.children ?? []).filter((child) => child.type === "text").map((child) => child.data ?? "").join("");
|
|
54
|
+
context.wxs.push({
|
|
55
|
+
module: moduleName,
|
|
56
|
+
kind: "inline",
|
|
57
|
+
importName: `__wxs_${context.wxs.length}`,
|
|
58
|
+
value: inlineCode
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (node.children?.length) node.children = collectSpecialNodes(node.children, context);
|
|
65
|
+
}
|
|
66
|
+
renderable.push(node);
|
|
67
|
+
}
|
|
68
|
+
return renderable;
|
|
69
|
+
}
|
|
70
|
+
function toRelativeImport(from, target) {
|
|
71
|
+
const rel = relative(dirname(from), target);
|
|
72
|
+
if (!rel || rel.startsWith(".")) {
|
|
73
|
+
const fallback = normalizeTemplatePath(target).split("/").pop() ?? "";
|
|
74
|
+
return rel || `./${fallback}`;
|
|
75
|
+
}
|
|
76
|
+
return `./${rel}`;
|
|
77
|
+
}
|
|
78
|
+
function normalizeTemplatePath(pathname) {
|
|
79
|
+
return pathname.split("\\").join("/");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
//#endregion
|
|
83
|
+
export { collectSpecialNodes, normalizeTemplatePath, shouldMarkWxsImport, toRelativeImport };
|
|
84
|
+
//# sourceMappingURL=specialNodes.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"specialNodes.mjs","names":[],"sources":["../../../src/compiler/wxml/specialNodes.ts"],"sourcesContent":["import type {\n ImportEntry,\n IncludeEntry,\n RenderNode,\n TemplateDefinition,\n WxsEntry,\n} from './types'\n\nimport { dirname, relative } from 'pathe'\n\nexport function shouldMarkWxsImport(pathname: string) {\n const lower = pathname.toLowerCase()\n if (lower.endsWith('.wxs') || lower.endsWith('.wxs.ts') || lower.endsWith('.wxs.js')) {\n return false\n }\n return lower.endsWith('.ts') || lower.endsWith('.js')\n}\n\ninterface CollectSpecialNodesContext {\n templates: TemplateDefinition[]\n includes: IncludeEntry[]\n imports: ImportEntry[]\n wxs: WxsEntry[]\n wxsModules: Map<string, string>\n warnings: string[]\n sourceId: string\n resolveTemplate: (raw: string) => string | undefined\n resolveWxs: (raw: string) => string | undefined\n}\n\nexport function collectSpecialNodes(nodes: RenderNode[], context: CollectSpecialNodesContext) {\n const renderable: RenderNode[] = []\n for (const node of nodes) {\n if (node.type === 'element') {\n const name = node.name ?? ''\n if (name === 'template' && node.attribs?.name) {\n context.templates.push({\n name: node.attribs.name,\n nodes: collectSpecialNodes(node.children ?? [], context),\n })\n continue\n }\n if ((name === 'import' || name === 'wx-import') && node.attribs?.src) {\n const resolved = context.resolveTemplate(node.attribs.src)\n if (resolved) {\n context.imports.push({\n id: resolved,\n importName: `__wxml_import_${context.imports.length}`,\n })\n }\n else {\n context.warnings.push(`[web] 无法解析模板依赖: ${node.attribs.src} (from ${context.sourceId})`)\n }\n continue\n }\n if ((name === 'include' || name === 'wx-include') && node.attribs?.src) {\n const resolved = context.resolveTemplate(node.attribs.src)\n if (resolved) {\n context.includes.push({\n id: resolved,\n importName: `__wxml_include_${context.includes.length}`,\n })\n }\n else {\n context.warnings.push(`[web] 无法解析模板依赖: ${node.attribs.src} (from ${context.sourceId})`)\n }\n continue\n }\n if (name === 'wxs') {\n const moduleName = node.attribs?.module?.trim()\n if (moduleName) {\n const previousSource = context.wxsModules.get(moduleName)\n if (previousSource) {\n context.warnings.push(`[web] WXS 模块名重复: ${moduleName} (from ${context.sourceId})`)\n }\n context.wxsModules.set(moduleName, context.sourceId)\n if (node.attribs?.src) {\n const resolved = context.resolveWxs(node.attribs.src)\n if (resolved) {\n context.wxs.push({\n module: moduleName,\n kind: 'src',\n importName: `__wxs_${context.wxs.length}`,\n value: resolved,\n })\n }\n }\n else {\n const inlineCode = (node.children ?? [])\n .filter(child => child.type === 'text')\n .map(child => child.data ?? '')\n .join('')\n context.wxs.push({\n module: moduleName,\n kind: 'inline',\n importName: `__wxs_${context.wxs.length}`,\n value: inlineCode,\n })\n }\n }\n continue\n }\n if (node.children?.length) {\n node.children = collectSpecialNodes(node.children, context)\n }\n }\n renderable.push(node)\n }\n return renderable\n}\n\nexport function toRelativeImport(from: string, target: string) {\n const fromDir = dirname(from)\n const rel = relative(fromDir, target)\n if (!rel || rel.startsWith('.')) {\n const fallback = normalizeTemplatePath(target).split('/').pop() ?? ''\n return rel || `./${fallback}`\n }\n return `./${rel}`\n}\n\nexport function normalizeTemplatePath(pathname: string) {\n return pathname.split('\\\\').join('/')\n}\n"],"mappings":";;;AAUA,SAAgB,oBAAoB,UAAkB;CACpD,MAAM,QAAQ,SAAS,aAAa;AACpC,KAAI,MAAM,SAAS,OAAO,IAAI,MAAM,SAAS,UAAU,IAAI,MAAM,SAAS,UAAU,CAClF,QAAO;AAET,QAAO,MAAM,SAAS,MAAM,IAAI,MAAM,SAAS,MAAM;;AAevD,SAAgB,oBAAoB,OAAqB,SAAqC;CAC5F,MAAM,aAA2B,EAAE;AACnC,MAAK,MAAM,QAAQ,OAAO;AACxB,MAAI,KAAK,SAAS,WAAW;GAC3B,MAAM,OAAO,KAAK,QAAQ;AAC1B,OAAI,SAAS,cAAc,KAAK,SAAS,MAAM;AAC7C,YAAQ,UAAU,KAAK;KACrB,MAAM,KAAK,QAAQ;KACnB,OAAO,oBAAoB,KAAK,YAAY,EAAE,EAAE,QAAQ;KACzD,CAAC;AACF;;AAEF,QAAK,SAAS,YAAY,SAAS,gBAAgB,KAAK,SAAS,KAAK;IACpE,MAAM,WAAW,QAAQ,gBAAgB,KAAK,QAAQ,IAAI;AAC1D,QAAI,SACF,SAAQ,QAAQ,KAAK;KACnB,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AiB,MAAc,QAAgB;CAE7D,MAAM,MAAM,SADI,QAAQ,KAAK,EACC,OAAO;AACrC,KAAI,CAAC,OAAO,IAAI,WAAW,IAAI,EAAE;EAC/B,MAAM,WAAW,sBAAsB,OAAO,CAAC,MAAM,IAAI,CAAC,KAAK,IAAI;AACnE,SAAO,OAAO,KAAK;;AAErB,QAAO,KAAK;;AAGd,SAAgB,sBAAsB,UAAkB;AACtD,QAAO,SAAS,MAAM,KAAK,CAAC,KAAK,IAAI"}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
//#region src/compiler/wxs.ts
|
|
2
|
+
const REQUIRE_RE = /require\(\s*['"]([^'"]+)['"]\s*\)/g;
|
|
3
|
+
function normalizePath(p) {
|
|
4
|
+
return p.split("\\\\").join("/");
|
|
5
|
+
}
|
|
6
|
+
function isPlainWxsScript(pathname) {
|
|
7
|
+
const lower = pathname.toLowerCase();
|
|
8
|
+
if (lower.endsWith(".wxs") || lower.endsWith(".wxs.ts") || lower.endsWith(".wxs.js")) return false;
|
|
9
|
+
return lower.endsWith(".ts") || lower.endsWith(".js");
|
|
10
|
+
}
|
|
11
|
+
function appendWxsQuery(pathname) {
|
|
12
|
+
if (pathname.includes("?wxs") || pathname.includes("&wxs")) return pathname;
|
|
13
|
+
return `${pathname}${pathname.includes("?") ? "&" : "?"}wxs`;
|
|
14
|
+
}
|
|
15
|
+
function isSupportedRequirePath(request) {
|
|
16
|
+
const normalized = request.replace(/\\/g, "/");
|
|
17
|
+
return normalized.startsWith(".") || normalized.startsWith("/");
|
|
18
|
+
}
|
|
19
|
+
function transformWxsToEsm(code, id, options) {
|
|
20
|
+
const dependencies = [];
|
|
21
|
+
const importLines = [];
|
|
22
|
+
const mapEntries = [];
|
|
23
|
+
const warnings = [];
|
|
24
|
+
const seen = /* @__PURE__ */ new Set();
|
|
25
|
+
while (true) {
|
|
26
|
+
const match = REQUIRE_RE.exec(code);
|
|
27
|
+
if (!match) break;
|
|
28
|
+
const request = match[1];
|
|
29
|
+
if (!request || seen.has(request)) continue;
|
|
30
|
+
seen.add(request);
|
|
31
|
+
if (!isSupportedRequirePath(request)) {
|
|
32
|
+
warnings.push(`[@weapp-vite/web] WXS require 仅支持相对或绝对路径: ${request} (from ${id})`);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
const normalizedRequest = request.replace(/\\/g, "/");
|
|
36
|
+
const resolved = options.resolvePath(normalizedRequest, id);
|
|
37
|
+
if (!resolved) {
|
|
38
|
+
warnings.push(`[@weapp-vite/web] 无法解析 WXS require: ${request} (from ${id})`);
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
let importPath = normalizePath(options.toImportPath?.(resolved, id) ?? resolved);
|
|
42
|
+
if (isPlainWxsScript(resolved)) importPath = appendWxsQuery(importPath);
|
|
43
|
+
const importName = `__wxs_dep_${dependencies.length}`;
|
|
44
|
+
importLines.push(`import ${importName} from '${importPath}'`);
|
|
45
|
+
mapEntries.push(`[${JSON.stringify(request)}, ${importName}]`);
|
|
46
|
+
dependencies.push(resolved);
|
|
47
|
+
}
|
|
48
|
+
const requireMap = `const __wxs_require_map = new Map([${mapEntries.join(", ")}])`;
|
|
49
|
+
const requireFn = [
|
|
50
|
+
`const __wxs_require_warned = new Set()`,
|
|
51
|
+
`function require(id) {`,
|
|
52
|
+
` if (__wxs_require_map.has(id)) {`,
|
|
53
|
+
` return __wxs_require_map.get(id)`,
|
|
54
|
+
` }`,
|
|
55
|
+
` if (!__wxs_require_warned.has(id)) {`,
|
|
56
|
+
` __wxs_require_warned.add(id)`,
|
|
57
|
+
` if (typeof console !== 'undefined' && typeof console.warn === 'function') {`,
|
|
58
|
+
` console.warn(\`[@weapp-vite/web] WXS require 未解析: \${id}\`)`,
|
|
59
|
+
` }`,
|
|
60
|
+
` }`,
|
|
61
|
+
` return undefined`,
|
|
62
|
+
`}`
|
|
63
|
+
].join("\\n");
|
|
64
|
+
const moduleInit = `const module = { exports: {} }\\nconst exports = module.exports`;
|
|
65
|
+
const helpers = `const getRegExp = (pattern, flags) => new RegExp(pattern, flags)\\nconst getDate = (value) => (value == null ? new Date() : new Date(value))`;
|
|
66
|
+
return {
|
|
67
|
+
code: [
|
|
68
|
+
...importLines,
|
|
69
|
+
requireMap,
|
|
70
|
+
requireFn,
|
|
71
|
+
moduleInit,
|
|
72
|
+
helpers,
|
|
73
|
+
code,
|
|
74
|
+
`export default module.exports`
|
|
75
|
+
].join("\\n"),
|
|
76
|
+
dependencies,
|
|
77
|
+
warnings: warnings.length > 0 ? warnings : void 0
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
//#endregion
|
|
82
|
+
export { transformWxsToEsm };
|
|
83
|
+
//# sourceMappingURL=wxs.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wxs.mjs","names":[],"sources":["../../src/compiler/wxs.ts"],"sourcesContent":["export interface WxsTransformResult {\n code: string\n dependencies: string[]\n warnings?: string[]\n}\n\nexport interface WxsTransformOptions {\n resolvePath: (request: string, importer: string) => string | undefined\n toImportPath?: (resolved: string, importer: string) => string\n}\n\nconst REQUIRE_RE = /require\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g\n\nfunction normalizePath(p: string) {\n return p.split('\\\\\\\\').join('/')\n}\n\nfunction isPlainWxsScript(pathname: string) {\n const lower = pathname.toLowerCase()\n if (lower.endsWith('.wxs') || lower.endsWith('.wxs.ts') || lower.endsWith('.wxs.js')) {\n return false\n }\n return lower.endsWith('.ts') || lower.endsWith('.js')\n}\n\nfunction appendWxsQuery(pathname: string) {\n if (pathname.includes('?wxs') || pathname.includes('&wxs')) {\n return pathname\n }\n return `${pathname}${pathname.includes('?') ? '&' : '?'}wxs`\n}\n\nfunction isSupportedRequirePath(request: string) {\n const normalized = request.replace(/\\\\/g, '/')\n return normalized.startsWith('.') || normalized.startsWith('/')\n}\n\nexport function transformWxsToEsm(code: string, id: string, options: WxsTransformOptions): WxsTransformResult {\n const dependencies: string[] = []\n const importLines: string[] = []\n const mapEntries: string[] = []\n const warnings: string[] = []\n\n const seen = new Set<string>()\n while (true) {\n const match = REQUIRE_RE.exec(code)\n if (!match) {\n break\n }\n const request = match[1]\n if (!request || seen.has(request)) {\n continue\n }\n seen.add(request)\n if (!isSupportedRequirePath(request)) {\n warnings.push(`[@weapp-vite/web] WXS require 仅支持相对或绝对路径: ${request} (from ${id})`)\n continue\n }\n const normalizedRequest = request.replace(/\\\\/g, '/')\n const resolved = options.resolvePath(normalizedRequest, id)\n if (!resolved) {\n warnings.push(`[@weapp-vite/web] 无法解析 WXS require: ${request} (from ${id})`)\n continue\n }\n let importPath = normalizePath(options.toImportPath?.(resolved, id) ?? resolved)\n if (isPlainWxsScript(resolved)) {\n importPath = appendWxsQuery(importPath)\n }\n const importName = `__wxs_dep_${dependencies.length}`\n importLines.push(`import ${importName} from '${importPath}'`)\n mapEntries.push(`[${JSON.stringify(request)}, ${importName}]`)\n dependencies.push(resolved)\n }\n\n const requireMap = `const __wxs_require_map = new Map([${mapEntries.join(', ')}])`\n const requireFn = [\n `const __wxs_require_warned = new Set()`,\n `function require(id) {`,\n ` if (__wxs_require_map.has(id)) {`,\n ` return __wxs_require_map.get(id)`,\n ` }`,\n ` if (!__wxs_require_warned.has(id)) {`,\n ` __wxs_require_warned.add(id)`,\n ` if (typeof console !== 'undefined' && typeof console.warn === 'function') {`,\n ` console.warn(\\`[@weapp-vite/web] WXS require 未解析: \\${id}\\`)`,\n ` }`,\n ` }`,\n ` return undefined`,\n `}`,\n ].join('\\\\n')\n const moduleInit = `const module = { exports: {} }\\\\nconst exports = module.exports`\n const helpers = `const getRegExp = (pattern, flags) => new RegExp(pattern, flags)\\\\nconst getDate = (value) => (value == null ? new Date() : new Date(value))`\n\n const body = [\n ...importLines,\n requireMap,\n requireFn,\n moduleInit,\n helpers,\n code,\n `export default module.exports`,\n ].join('\\\\n')\n\n return {\n code: body,\n dependencies,\n warnings: warnings.length > 0 ? warnings : undefined,\n }\n}\n"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I,aAAa,cAAc,QAAQ,eAAe,UAAU,GAAG,IAAI,SAAS;AAChF,MAAI,iBAAiB,SAAS,CAC5B,cAAa,eAAe,WAAW;EAEzC,MAAM,aAAa,aAAa,aAAa;AAC7C,cAAY,KAAK,UAAU,WAAW,SAAS,WAAW,GAAG;AAC7D,aAAW,KAAK,IAAI,KAAK,UAAU,QAAQ,CAAC,IAAI,WAAW,GAAG;AAC9D,eAAa,KAAK,SAAS;;CAG7B,MAAM,aAAa,sCAAsC,WAAW,KAAK,KAAK,CAAC;CAC/E,MAAM,YAAY;EAChB;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,KAAK,MAAM;CACb,MAAM,aAAa;CACnB,MAAM,UAAU;AAYhB,QAAO;EACL,MAXW;GACX,GAAG;GACH;GACA;GACA;GACA;GACA;GACA;GACD,CAAC,KAAK,MAAM;EAIX;EACA,UAAU,SAAS,SAAS,IAAI,WAAW;EAC5C"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
//#region src/css/wxss.d.ts
|
|
2
|
+
interface WxssTransformOptions {
|
|
3
|
+
/**
|
|
4
|
+
* 1rpx 对应的 CSS 像素数。
|
|
5
|
+
* 默认值近似于 750rpx 设计稿在 375px 屏幕上的换算。
|
|
6
|
+
*/
|
|
7
|
+
pxPerRpx?: number;
|
|
8
|
+
/**
|
|
9
|
+
* rpx 换算的设计宽度。传入后会把 rpx 转为
|
|
10
|
+
* `calc(var(--rpx) * N)` 以实现响应式缩放。
|
|
11
|
+
*/
|
|
12
|
+
designWidth?: number;
|
|
13
|
+
/**
|
|
14
|
+
* 用于存储运行时 rpx 大小的 CSS 变量名。
|
|
15
|
+
* @default "--rpx"
|
|
16
|
+
*/
|
|
17
|
+
rpxVar?: string;
|
|
18
|
+
}
|
|
19
|
+
interface WxssTransformResult {
|
|
20
|
+
css: string;
|
|
21
|
+
}
|
|
22
|
+
declare function transformWxssToCss(source: string, options?: WxssTransformOptions): WxssTransformResult;
|
|
23
|
+
//#endregion
|
|
24
|
+
export { WxssTransformOptions, transformWxssToCss };
|
|
25
|
+
//# sourceMappingURL=wxss.d.mts.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
//#region src/css/wxss.ts
|
|
2
|
+
const RPX_RE = /(-?(?:\d+(?:\.\d+)?|\.\d+))rpx/gi;
|
|
3
|
+
function transformWxssToCss(source, options) {
|
|
4
|
+
const rpxVar = options?.rpxVar ?? "--rpx";
|
|
5
|
+
const useVariable = typeof options?.designWidth === "number" && Number.isFinite(options.designWidth);
|
|
6
|
+
const ratio = options?.pxPerRpx ?? .5;
|
|
7
|
+
return { css: source.replace(RPX_RE, (_, value) => {
|
|
8
|
+
const numeric = Number.parseFloat(value);
|
|
9
|
+
if (Number.isNaN(numeric)) return `${value}px`;
|
|
10
|
+
if (useVariable) return `calc(var(${rpxVar}) * ${numeric})`;
|
|
11
|
+
return `${Math.round(numeric * ratio * 1e3) / 1e3}px`;
|
|
12
|
+
}) };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
//#endregion
|
|
16
|
+
export { transformWxssToCss };
|
|
17
|
+
//# sourceMappingURL=wxss.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wxss.mjs","names":[],"sources":["../../src/css/wxss.ts"],"sourcesContent":["export interface WxssTransformOptions {\n /**\n * 1rpx 对应的 CSS 像素数。\n * 默认值近似于 750rpx 设计稿在 375px 屏幕上的换算。\n */\n pxPerRpx?: number\n /**\n * rpx 换算的设计宽度。传入后会把 rpx 转为\n * `calc(var(--rpx) * N)` 以实现响应式缩放。\n */\n designWidth?: number\n /**\n * 用于存储运行时 rpx 大小的 CSS 变量名。\n * @default \"--rpx\"\n */\n rpxVar?: string\n}\n\nexport interface WxssTransformResult {\n css: string\n}\n\nconst RPX_RE = /(-?(?:\\d+(?:\\.\\d+)?|\\.\\d+))rpx/gi\n\nexport function transformWxssToCss(source: string, options?: WxssTransformOptions): WxssTransformResult {\n const rpxVar = options?.rpxVar ?? '--rpx'\n const useVariable = typeof options?.designWidth === 'number' && Number.isFinite(options.designWidth)\n const ratio = options?.pxPerRpx ?? 0.5\n const css = source.replace(RPX_RE, (_, value: string) => {\n const numeric = Number.parseFloat(value)\n if (Number.isNaN(numeric)) {\n return `${value}px`\n }\n if (useVariable) {\n return `calc(var(${rpxVar}) * ${numeric})`\n }\n const converted = Math.round(numeric * ratio * 1000) / 1000\n return `${converted}px`\n })\n return {\n css,\n }\n}\n"],"mappings":";AAsBA,MAAM,SAAS;AAEf,SAAgB,mBAAmB,QAAgB,SAAqD;CACtG,MAAM,SAAS,SAAS,UAAU;CAClC,MAAM,cAAc,OAAO,SAAS,gBAAgB,YAAY,OAAO,SAAS,QAAQ,YAAY;CACpG,MAAM,QAAQ,SAAS,YAAY;AAYnC,QAAO,EACL,KAZU,OAAO,QAAQ,SAAS,GAAG,UAAkB;EACvD,MAAM,UAAU,OAAO,WAAW,MAAM;AACxC,MAAI,OAAO,MAAM,QAAQ,CACvB,QAAO,GAAG,MAAM;AAElB,MAAI,YACF,QAAO,YAAY,OAAO,MAAM,QAAQ;AAG1C,SAAO,GADW,KAAK,MAAM,UAAU,QAAQ,IAAK,GAAG,IACnC;GACpB,EAGD"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { transformWxssToCss } from "./css/wxss.mjs";
|
|
2
|
+
import { WeappWebPluginOptions } from "./plugin/types.mjs";
|
|
3
|
+
import { weappWebPlugin } from "./plugin/index.mjs";
|
|
4
|
+
import { ButtonFormConfig, ensureButtonDefined, setButtonFormConfig } from "./runtime/button/index.mjs";
|
|
5
|
+
import { RenderContext, createRenderContext } from "./runtime/renderContext.mjs";
|
|
6
|
+
import { createTemplate, renderTemplate } from "./runtime/legacyTemplate/index.mjs";
|
|
7
|
+
import { TemplateRenderer, TemplateScope } from "./runtime/template.mjs";
|
|
8
|
+
import { defineComponent } from "./runtime/component/index.mjs";
|
|
9
|
+
import { getRuntimeExecutionMode, setRuntimeExecutionMode } from "./runtime/execution.mjs";
|
|
10
|
+
import { NavigationBarMetrics, setNavigationBarMetrics } from "./runtime/navigationBar/index.mjs";
|
|
11
|
+
import { authorize, checkSession, getAccountInfoSync, getAppAuthorizeSetting, getAppBaseInfo, getBatteryInfo, getBatteryInfoSync, getDeviceInfo, getFuzzyLocation, getLocation, getMenuButtonBoundingClientRect, getNetworkType, getSetting, getSystemInfo, getSystemInfoSync, getSystemSetting, getUserInfo, getUserProfile, getWindowInfo, login, offNetworkStatusChange, offWindowResize, onNetworkStatusChange, onWindowResize, openAppAuthorizeSetting, openSetting, vibrateShort } from "./runtime/polyfill/deviceAuthSystemApi.mjs";
|
|
12
|
+
import { getEnterOptionsSync, getLaunchOptionsSync, initializePageRoutes, navigateBack, navigateTo, reLaunch, redirectTo, registerApp, registerComponent, registerPage, switchTab } from "./runtime/polyfill/routeRuntime.mjs";
|
|
13
|
+
import { clearStorage, clearStorageSync, createCanvasContext, createSelectorQuery, createVKSession, createVideoContext, createWorker, downloadFile, exitMiniProgram, getFileSystemManager, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, hideKeyboard, loadSubPackage, navigateToMiniProgram, nextTick, pageScrollTo, preloadSubpackage, removeStorage, removeStorageSync, request, setStorage, setStorageSync, startPullDownRefresh, stopPullDownRefresh, uploadFile } from "./runtime/polyfill/runtimeDataApi.mjs";
|
|
14
|
+
import { chooseAddress, chooseFile, chooseImage, chooseLocation, chooseMedia, chooseMessageFile, chooseVideo, compressImage, compressVideo, getClipboardData, getImageInfo, getVideoInfo, hideLoading, hideTabBar, makePhoneCall, openCustomerServiceChat, openDocument, openLocation, openVideoEditor, previewImage, previewMedia, requestPayment, requestSubscribeMessage, saveFile, saveFileToDisk, saveImageToPhotosAlbum, saveVideoToPhotosAlbum, scanCode, setClipboardData, showActionSheet, showLoading, showModal, showShareMenu, showTabBar, showToast, updateShareMenu } from "./runtime/polyfill/uiMediaApi.mjs";
|
|
15
|
+
import { canIUse, createInterstitialAd, createRewardedVideoAd, getExtConfig, getExtConfigSync, getLogManager, getUpdateManager, hideNavigationBarLoading, reportAnalytics, setBackgroundColor, setBackgroundTextStyle, setNavigationBarColor, setNavigationBarTitle, showNavigationBarLoading } from "./runtime/polyfill/index.mjs";
|
|
16
|
+
import { RpxConfig, setupRpx } from "./runtime/rpx.mjs";
|
|
17
|
+
import { injectStyle, removeStyle } from "./runtime/style.mjs";
|
|
18
|
+
import { RuntimeWarningLevel, RuntimeWarningOptions, setRuntimeWarningOptions } from "./runtime/warning.mjs";
|
|
3
19
|
export { ButtonFormConfig, NavigationBarMetrics, RenderContext, RpxConfig, RuntimeWarningLevel, RuntimeWarningOptions, TemplateRenderer, TemplateScope, type WeappWebPluginOptions, authorize, canIUse, checkSession, chooseAddress, chooseFile, chooseImage, chooseLocation, chooseMedia, chooseMessageFile, chooseVideo, clearStorage, clearStorageSync, compressImage, compressVideo, createCanvasContext, createInterstitialAd, createRenderContext, createRewardedVideoAd, createSelectorQuery, createTemplate, createVKSession, createVideoContext, createWorker, defineComponent, downloadFile, ensureButtonDefined, exitMiniProgram, getAccountInfoSync, getAppAuthorizeSetting, getAppBaseInfo, getBatteryInfo, getBatteryInfoSync, getClipboardData, getDeviceInfo, getEnterOptionsSync, getExtConfig, getExtConfigSync, getFileSystemManager, getFuzzyLocation, getImageInfo, getLaunchOptionsSync, getLocation, getLogManager, getMenuButtonBoundingClientRect, getNetworkType, getRuntimeExecutionMode, getSetting, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, getSystemInfo, getSystemInfoSync, getSystemSetting, getUpdateManager, getUserInfo, getUserProfile, getVideoInfo, getWindowInfo, hideKeyboard, hideLoading, hideNavigationBarLoading, hideTabBar, initializePageRoutes, injectStyle, loadSubPackage, login, makePhoneCall, navigateBack, navigateTo, navigateToMiniProgram, nextTick, offNetworkStatusChange, offWindowResize, onNetworkStatusChange, onWindowResize, openAppAuthorizeSetting, openCustomerServiceChat, openDocument, openLocation, openSetting, openVideoEditor, pageScrollTo, preloadSubpackage, previewImage, previewMedia, reLaunch, redirectTo, registerApp, registerComponent, registerPage, removeStorage, removeStorageSync, removeStyle, renderTemplate, reportAnalytics, request, requestPayment, requestSubscribeMessage, saveFile, saveFileToDisk, saveImageToPhotosAlbum, saveVideoToPhotosAlbum, scanCode, setBackgroundColor, setBackgroundTextStyle, setButtonFormConfig, setClipboardData, setNavigationBarColor, setNavigationBarMetrics, setNavigationBarTitle, setRuntimeExecutionMode, setRuntimeWarningOptions, setStorage, setStorageSync, setupRpx, showActionSheet, showLoading, showModal, showNavigationBarLoading, showShareMenu, showTabBar, showToast, startPullDownRefresh, stopPullDownRefresh, switchTab, transformWxssToCss, updateShareMenu, uploadFile, vibrateShort, weappWebPlugin };
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,18 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import { transformWxssToCss } from "./css/wxss.mjs";
|
|
2
|
+
import { weappWebPlugin } from "./plugin/index.mjs";
|
|
3
|
+
import { injectStyle, removeStyle } from "./runtime/style.mjs";
|
|
4
|
+
import { ensureButtonDefined, setButtonFormConfig } from "./runtime/button/index.mjs";
|
|
5
|
+
import { setRuntimeWarningOptions } from "./runtime/warning.mjs";
|
|
6
|
+
import { getRuntimeExecutionMode, setRuntimeExecutionMode } from "./runtime/execution.mjs";
|
|
7
|
+
import { createRenderContext } from "./runtime/renderContext.mjs";
|
|
8
|
+
import { defineComponent } from "./runtime/component/index.mjs";
|
|
9
|
+
import { setNavigationBarMetrics } from "./runtime/navigationBar/index.mjs";
|
|
10
|
+
import { authorize, checkSession, getAccountInfoSync, getAppAuthorizeSetting, getAppBaseInfo, getBatteryInfo, getBatteryInfoSync, getDeviceInfo, getFuzzyLocation, getLocation, getMenuButtonBoundingClientRect, getNetworkType, getSetting, getSystemInfo, getSystemInfoSync, getSystemSetting, getUserInfo, getUserProfile, getWindowInfo, login, offNetworkStatusChange, offWindowResize, onNetworkStatusChange, onWindowResize, openAppAuthorizeSetting, openSetting, vibrateShort } from "./runtime/polyfill/deviceAuthSystemApi.mjs";
|
|
11
|
+
import { setupRpx } from "./runtime/rpx.mjs";
|
|
12
|
+
import { getEnterOptionsSync, getLaunchOptionsSync, initializePageRoutes, navigateBack, navigateTo, reLaunch, redirectTo, registerApp, registerComponent, registerPage, switchTab } from "./runtime/polyfill/routeRuntime.mjs";
|
|
13
|
+
import { clearStorage, clearStorageSync, createCanvasContext, createSelectorQuery, createVKSession, createVideoContext, createWorker, downloadFile, exitMiniProgram, getFileSystemManager, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, hideKeyboard, loadSubPackage, navigateToMiniProgram, nextTick, pageScrollTo, preloadSubpackage, removeStorage, removeStorageSync, request, setStorage, setStorageSync, startPullDownRefresh, stopPullDownRefresh, uploadFile } from "./runtime/polyfill/runtimeDataApi.mjs";
|
|
14
|
+
import { chooseAddress, chooseFile, chooseImage, chooseLocation, chooseMedia, chooseMessageFile, chooseVideo, compressImage, compressVideo, getClipboardData, getImageInfo, getVideoInfo, hideLoading, hideTabBar, makePhoneCall, openCustomerServiceChat, openDocument, openLocation, openVideoEditor, previewImage, previewMedia, requestPayment, requestSubscribeMessage, saveFile, saveFileToDisk, saveImageToPhotosAlbum, saveVideoToPhotosAlbum, scanCode, setClipboardData, showActionSheet, showLoading, showModal, showShareMenu, showTabBar, showToast, updateShareMenu } from "./runtime/polyfill/uiMediaApi.mjs";
|
|
15
|
+
import { canIUse, createInterstitialAd, createRewardedVideoAd, getExtConfig, getExtConfigSync, getLogManager, getUpdateManager, hideNavigationBarLoading, reportAnalytics, setBackgroundColor, setBackgroundTextStyle, setNavigationBarColor, setNavigationBarTitle, showNavigationBarLoading } from "./runtime/polyfill/index.mjs";
|
|
16
|
+
import { createTemplate, renderTemplate } from "./runtime/legacyTemplate/index.mjs";
|
|
17
|
+
|
|
18
|
+
export { authorize, canIUse, checkSession, chooseAddress, chooseFile, chooseImage, chooseLocation, chooseMedia, chooseMessageFile, chooseVideo, clearStorage, clearStorageSync, compressImage, compressVideo, createCanvasContext, createInterstitialAd, createRenderContext, createRewardedVideoAd, createSelectorQuery, createTemplate, createVKSession, createVideoContext, createWorker, defineComponent, downloadFile, ensureButtonDefined, exitMiniProgram, getAccountInfoSync, getAppAuthorizeSetting, getAppBaseInfo, getBatteryInfo, getBatteryInfoSync, getClipboardData, getDeviceInfo, getEnterOptionsSync, getExtConfig, getExtConfigSync, getFileSystemManager, getFuzzyLocation, getImageInfo, getLaunchOptionsSync, getLocation, getLogManager, getMenuButtonBoundingClientRect, getNetworkType, getRuntimeExecutionMode, getSetting, getStorage, getStorageInfo, getStorageInfoSync, getStorageSync, getSystemInfo, getSystemInfoSync, getSystemSetting, getUpdateManager, getUserInfo, getUserProfile, getVideoInfo, getWindowInfo, hideKeyboard, hideLoading, hideNavigationBarLoading, hideTabBar, initializePageRoutes, injectStyle, loadSubPackage, login, makePhoneCall, navigateBack, navigateTo, navigateToMiniProgram, nextTick, offNetworkStatusChange, offWindowResize, onNetworkStatusChange, onWindowResize, openAppAuthorizeSetting, openCustomerServiceChat, openDocument, openLocation, openSetting, openVideoEditor, pageScrollTo, preloadSubpackage, previewImage, previewMedia, reLaunch, redirectTo, registerApp, registerComponent, registerPage, removeStorage, removeStorageSync, removeStyle, renderTemplate, reportAnalytics, request, requestPayment, requestSubscribeMessage, saveFile, saveFileToDisk, saveImageToPhotosAlbum, saveVideoToPhotosAlbum, scanCode, setBackgroundColor, setBackgroundTextStyle, setButtonFormConfig, setClipboardData, setNavigationBarColor, setNavigationBarMetrics, setNavigationBarTitle, setRuntimeExecutionMode, setRuntimeWarningOptions, setStorage, setStorageSync, setupRpx, showActionSheet, showLoading, showModal, showNavigationBarLoading, showShareMenu, showTabBar, showToast, startPullDownRefresh, stopPullDownRefresh, switchTab, transformWxssToCss, updateShareMenu, uploadFile, vibrateShort, weappWebPlugin };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
//#region src/plugin/constants.ts
|
|
2
|
+
const SCRIPT_EXTS = [
|
|
3
|
+
".ts",
|
|
4
|
+
".tsx",
|
|
5
|
+
".js",
|
|
6
|
+
".jsx",
|
|
7
|
+
".mjs",
|
|
8
|
+
".cjs"
|
|
9
|
+
];
|
|
10
|
+
const STYLE_EXTS = [
|
|
11
|
+
".wxss",
|
|
12
|
+
".scss",
|
|
13
|
+
".less",
|
|
14
|
+
".css"
|
|
15
|
+
];
|
|
16
|
+
const TRANSFORM_STYLE_EXTS = [".wxss"];
|
|
17
|
+
const TEMPLATE_EXTS = [
|
|
18
|
+
".wxml",
|
|
19
|
+
".axml",
|
|
20
|
+
".swan",
|
|
21
|
+
".ttml",
|
|
22
|
+
".qml",
|
|
23
|
+
".ksml",
|
|
24
|
+
".xhsml",
|
|
25
|
+
".html"
|
|
26
|
+
];
|
|
27
|
+
const WXS_EXTS = [
|
|
28
|
+
".wxs",
|
|
29
|
+
".wxs.ts",
|
|
30
|
+
".wxs.js"
|
|
31
|
+
];
|
|
32
|
+
const WXS_RESOLVE_EXTS = [
|
|
33
|
+
".wxs",
|
|
34
|
+
".wxs.ts",
|
|
35
|
+
".wxs.js",
|
|
36
|
+
".ts",
|
|
37
|
+
".js"
|
|
38
|
+
];
|
|
39
|
+
const ENTRY_ID = "\0@weapp-vite/web/entry";
|
|
40
|
+
|
|
41
|
+
//#endregion
|
|
42
|
+
export { ENTRY_ID, SCRIPT_EXTS, STYLE_EXTS, TEMPLATE_EXTS, TRANSFORM_STYLE_EXTS, WXS_EXTS, WXS_RESOLVE_EXTS };
|
|
43
|
+
//# sourceMappingURL=constants.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.mjs","names":[],"sources":["../../src/plugin/constants.ts"],"sourcesContent":["export const SCRIPT_EXTS = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']\nexport const STYLE_EXTS = ['.wxss', '.scss', '.less', '.css']\nexport const TRANSFORM_STYLE_EXTS = ['.wxss']\nexport const TEMPLATE_EXTS = ['.wxml', '.axml', '.swan', '.ttml', '.qml', '.ksml', '.xhsml', '.html']\nexport const WXS_EXTS = ['.wxs', '.wxs.ts', '.wxs.js']\nexport const WXS_RESOLVE_EXTS = ['.wxs', '.wxs.ts', '.wxs.js', '.ts', '.js']\n\nexport const ENTRY_ID = '\\0@weapp-vite/web/entry'\n"],"mappings":";AAAA,MAAa,cAAc;CAAC;CAAO;CAAQ;CAAO;CAAQ;CAAQ;CAAO;AACzE,MAAa,aAAa;CAAC;CAAS;CAAS;CAAS;CAAO;AAC7D,MAAa,uBAAuB,CAAC,QAAQ;AAC7C,MAAa,gBAAgB;CAAC;CAAS;CAAS;CAAS;CAAS;CAAQ;CAAS;CAAU;CAAQ;AACrG,MAAa,WAAW;CAAC;CAAQ;CAAW;CAAU;AACtD,MAAa,mBAAmB;CAAC;CAAQ;CAAW;CAAW;CAAO;CAAM;AAE5E,MAAa,WAAW"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { relativeModuleId, resolveRuntimePolyfillPath, toViteFsImport } from "./path.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/plugin/entry.ts
|
|
4
|
+
function generateEntryModule(result, root, wxssOptions, pluginOptions) {
|
|
5
|
+
const importLines = [`import { initializePageRoutes } from '${toViteFsImport(resolveRuntimePolyfillPath())}'`];
|
|
6
|
+
const bodyLines = [];
|
|
7
|
+
for (const page of result.pages) importLines.push(`import '${relativeModuleId(root, page.script)}'`);
|
|
8
|
+
for (const component of result.components) importLines.push(`import '${relativeModuleId(root, component.script)}'`);
|
|
9
|
+
if (result.app) importLines.push(`import '${relativeModuleId(root, result.app)}'`);
|
|
10
|
+
const pageOrder = result.pages.map((page) => page.id);
|
|
11
|
+
const rpxConfig = wxssOptions?.designWidth ? {
|
|
12
|
+
designWidth: wxssOptions.designWidth,
|
|
13
|
+
varName: wxssOptions.rpxVar
|
|
14
|
+
} : void 0;
|
|
15
|
+
const initOptions = {};
|
|
16
|
+
if (rpxConfig) initOptions.rpx = rpxConfig;
|
|
17
|
+
if (pluginOptions?.form?.preventDefault !== void 0) initOptions.form = { preventDefault: pluginOptions.form.preventDefault };
|
|
18
|
+
const runtimeOptions = {};
|
|
19
|
+
if (pluginOptions?.runtime?.executionMode) runtimeOptions.executionMode = pluginOptions.runtime.executionMode;
|
|
20
|
+
if (pluginOptions?.runtime?.warnings) runtimeOptions.warnings = pluginOptions.runtime.warnings;
|
|
21
|
+
if (Object.keys(runtimeOptions).length > 0) initOptions.runtime = runtimeOptions;
|
|
22
|
+
const initOptionsCode = Object.keys(initOptions).length > 0 ? `, ${JSON.stringify(initOptions)}` : "";
|
|
23
|
+
bodyLines.push(`initializePageRoutes(${JSON.stringify(pageOrder)}${initOptionsCode})`);
|
|
24
|
+
return [...importLines, ...bodyLines].join("\n");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
//#endregion
|
|
28
|
+
export { generateEntryModule };
|
|
29
|
+
//# sourceMappingURL=entry.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"entry.mjs","names":[],"sources":["../../src/plugin/entry.ts"],"sourcesContent":["import type { WxssTransformOptions } from '../css/wxss'\n\nimport type { ScanResult, WeappWebPluginOptions } from './types'\nimport { relativeModuleId, resolveRuntimePolyfillPath, toViteFsImport } from './path'\n\nexport function generateEntryModule(\n result: ScanResult,\n root: string,\n wxssOptions?: WxssTransformOptions,\n pluginOptions?: WeappWebPluginOptions,\n) {\n const runtimePolyfillId = toViteFsImport(resolveRuntimePolyfillPath())\n const importLines: string[] = [`import { initializePageRoutes } from '${runtimePolyfillId}'`]\n const bodyLines: string[] = []\n\n for (const page of result.pages) {\n importLines.push(`import '${relativeModuleId(root, page.script)}'`)\n }\n for (const component of result.components) {\n importLines.push(`import '${relativeModuleId(root, component.script)}'`)\n }\n if (result.app) {\n importLines.push(`import '${relativeModuleId(root, result.app)}'`)\n }\n\n const pageOrder = result.pages.map(page => page.id)\n const rpxConfig = wxssOptions?.designWidth\n ? { designWidth: wxssOptions.designWidth, varName: wxssOptions.rpxVar }\n : undefined\n\n const initOptions: Record<string, any> = {}\n if (rpxConfig) {\n initOptions.rpx = rpxConfig\n }\n if (pluginOptions?.form?.preventDefault !== undefined) {\n initOptions.form = { preventDefault: pluginOptions.form.preventDefault }\n }\n\n const runtimeOptions: Record<string, any> = {}\n if (pluginOptions?.runtime?.executionMode) {\n runtimeOptions.executionMode = pluginOptions.runtime.executionMode\n }\n if (pluginOptions?.runtime?.warnings) {\n runtimeOptions.warnings = pluginOptions.runtime.warnings\n }\n if (Object.keys(runtimeOptions).length > 0) {\n initOptions.runtime = runtimeOptions\n }\n\n const initOptionsCode = Object.keys(initOptions).length > 0 ? `, ${JSON.stringify(initOptions)}` : ''\n bodyLines.push(`initializePageRoutes(${JSON.stringify(pageOrder)}${initOptionsCode})`)\n return [...importLines, ...bodyLines].join('\\n')\n}\n"],"mappings":";;;AAKA,SAAgB,oBACd,QACA,MACA,aACA,eACA;CAEA,MAAM,cAAwB,CAAC,yCADL,eAAe,4BAA4B,CAAC,CACoB,GAAG;CAC7F,MAAM,YAAsB,EAAE;AAE9B,MAAK,MAAM,QAAQ,OAAO,MACxB,aAAY,KAAK,WAAW,iBAAiB,MAAM,KAAK,OAAO,CAAC,GAAG;AAErE,MAAK,MAAM,aAAa,OAAO,WAC7B,aAAY,KAAK,WAAW,iBAAiB,MAAM,UAAU,OAAO,CAAC,GAAG;AAE1E,KAAI,OAAO,IACT,aAAY,KAAK,WAAW,iBAAiB,MAAM,OAAO,IAAI,CAAC,GAAG;CAGpE,MAAM,YAAY,OAAO,MAAM,KAAI,SAAQ,KAAK,GAAG;CACnD,MAAM,YAAY,aAAa,cAC3B;EAAE,aAAa,YAAY;EAAa,SAAS,YAAY;EAAQ,GACrE;CAEJ,MAAM,cAAmC,EAAE;AAC3C,KAAI,UACF,aAAY,MAAM;AAEpB,KAAI,eAAe,MAAM,mBAAmB,OAC1C,aAAY,OAAO,EAAE,gBAAgB,cAAc,KAAK,gBAAgB;CAG1E,MAAM,iBAAsC,EAAE;AAC9C,KAAI,eAAe,SAAS,cAC1B,gBAAe,gBAAgB,cAAc,QAAQ;AAEvD,KAAI,eAAe,SAAS,SAC1B,gBAAe,WAAW,cAAc,QAAQ;AAElD,KAAI,OAAO,KAAK,eAAe,CAAC,SAAS,EACvC,aAAY,UAAU;CAGxB,MAAM,kBAAkB,OAAO,KAAK,YAAY,CAAC,SAAS,IAAI,KAAK,KAAK,UAAU,YAAY,KAAK;AACnG,WAAU,KAAK,wBAAwB,KAAK,UAAU,UAAU,GAAG,gBAAgB,GAAG;AACtF,QAAO,CAAC,GAAG,aAAa,GAAG,UAAU,CAAC,KAAK,KAAK"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { SCRIPT_EXTS, STYLE_EXTS, TEMPLATE_EXTS } from "./constants.mjs";
|
|
2
|
+
import { extname } from "pathe";
|
|
3
|
+
import { fs } from "@weapp-core/shared";
|
|
4
|
+
import { bundleRequire } from "rolldown-require";
|
|
5
|
+
|
|
6
|
+
//#region src/plugin/files.ts
|
|
7
|
+
function isRecord(value) {
|
|
8
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
9
|
+
}
|
|
10
|
+
async function readJsonFile(pathname) {
|
|
11
|
+
const candidates = [pathname];
|
|
12
|
+
if (pathname.endsWith(".json")) candidates.push(`${pathname}.ts`, `${pathname}.js`);
|
|
13
|
+
for (const candidate of candidates) {
|
|
14
|
+
if (!await fs.pathExists(candidate)) continue;
|
|
15
|
+
if (candidate.endsWith(".json")) {
|
|
16
|
+
const json = await fs.readJson(candidate).catch(() => void 0);
|
|
17
|
+
if (!isRecord(json)) return;
|
|
18
|
+
return json;
|
|
19
|
+
}
|
|
20
|
+
const { mod } = await bundleRequire({
|
|
21
|
+
filepath: candidate,
|
|
22
|
+
preserveTemporaryFile: true
|
|
23
|
+
});
|
|
24
|
+
const resolved = typeof mod.default === "function" ? await mod.default() : mod.default;
|
|
25
|
+
if (!isRecord(resolved)) return;
|
|
26
|
+
return resolved;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
async function resolveJsonPath(basePath) {
|
|
30
|
+
const candidates = [basePath];
|
|
31
|
+
if (basePath.endsWith(".json")) candidates.push(`${basePath}.ts`, `${basePath}.js`);
|
|
32
|
+
for (const candidate of candidates) if (await fs.pathExists(candidate)) return candidate;
|
|
33
|
+
}
|
|
34
|
+
async function resolveScriptFile(basePath) {
|
|
35
|
+
if (extname(basePath) && await fs.pathExists(basePath)) return basePath;
|
|
36
|
+
for (const candidateExt of SCRIPT_EXTS) {
|
|
37
|
+
const candidate = `${basePath}${candidateExt}`;
|
|
38
|
+
if (await fs.pathExists(candidate)) return candidate;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
async function resolveStyleFile(scriptPath) {
|
|
42
|
+
const base = scriptPath.replace(new RegExp(`${extname(scriptPath)}$`), "");
|
|
43
|
+
for (const ext of STYLE_EXTS) {
|
|
44
|
+
const candidate = `${base}${ext}`;
|
|
45
|
+
if (await fs.pathExists(candidate)) return candidate;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
async function resolveTemplateFile(scriptPath) {
|
|
49
|
+
const base = scriptPath.replace(new RegExp(`${extname(scriptPath)}$`), "");
|
|
50
|
+
for (const ext of TEMPLATE_EXTS) {
|
|
51
|
+
const candidate = `${base}${ext}`;
|
|
52
|
+
if (await fs.pathExists(candidate)) return candidate;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
//#endregion
|
|
57
|
+
export { isRecord, readJsonFile, resolveJsonPath, resolveScriptFile, resolveStyleFile, resolveTemplateFile };
|
|
58
|
+
//# sourceMappingURL=files.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"files.mjs","names":[],"sources":["../../src/plugin/files.ts"],"sourcesContent":["import { fs } from '@weapp-core/shared'\nimport { extname } from 'pathe'\nimport { bundleRequire } from 'rolldown-require'\n\nimport { SCRIPT_EXTS, STYLE_EXTS, TEMPLATE_EXTS } from './constants'\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nexport async function readJsonFile(pathname: string) {\n const candidates = [pathname]\n if (pathname.endsWith('.json')) {\n candidates.push(`${pathname}.ts`, `${pathname}.js`)\n }\n\n for (const candidate of candidates) {\n if (!(await fs.pathExists(candidate))) {\n continue\n }\n if (candidate.endsWith('.json')) {\n const json = await fs.readJson(candidate).catch(() => undefined)\n if (!isRecord(json)) {\n return undefined\n }\n return json\n }\n const { mod } = await bundleRequire({\n filepath: candidate,\n preserveTemporaryFile: true,\n })\n const resolved = typeof mod.default === 'function'\n ? await mod.default()\n : mod.default\n if (!isRecord(resolved)) {\n return undefined\n }\n return resolved\n }\n\n return undefined\n}\n\nexport async function resolveJsonPath(basePath: string) {\n const candidates = [basePath]\n if (basePath.endsWith('.json')) {\n candidates.push(`${basePath}.ts`, `${basePath}.js`)\n }\n for (const candidate of candidates) {\n if (await fs.pathExists(candidate)) {\n return candidate\n }\n }\n return undefined\n}\n\nexport async function resolveScriptFile(basePath: string) {\n const ext = extname(basePath)\n if (ext && (await fs.pathExists(basePath))) {\n return basePath\n }\n for (const candidateExt of SCRIPT_EXTS) {\n const candidate = `${basePath}${candidateExt}`\n if (await fs.pathExists(candidate)) {\n return candidate\n }\n }\n return undefined\n}\n\nexport async function resolveStyleFile(scriptPath: string) {\n const base = scriptPath.replace(new RegExp(`${extname(scriptPath)}$`), '')\n for (const ext of STYLE_EXTS) {\n const candidate = `${base}${ext}`\n if (await fs.pathExists(candidate)) {\n return candidate\n }\n }\n return undefined\n}\n\nexport async function resolveTemplateFile(scriptPath: string) {\n const base = scriptPath.replace(new RegExp(`${extname(scriptPath)}$`), '')\n for (const ext of TEMPLATE_EXTS) {\n const candidate = `${base}${ext}`\n if (await fs.p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