@weapp-vite/volar 2.0.7 → 2.1.0

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.mjs CHANGED
@@ -5,33 +5,13 @@ import { JSON_SCHEMA_DEFINITIONS } from "@weapp-core/schematics";
5
5
  //#region package.json
6
6
  var name = "@weapp-vite/volar";
7
7
  //#endregion
8
- //#region src/schema.ts
9
- /**
10
- * 为小程序配置生成 JSON Schema
11
- * 为支持 JSON Schema 的编辑器提供验证和自动补全
12
- *
13
- * 注意:JSON Schema 定义由 @weapp-core/schematics 统一维护
14
- * 使用 Zod 定义并自动生成,确保单一数据源
15
- */
16
- /**
17
- * 根据文件类型获取对应的 JSON Schema
18
- * Schema 定义来自 @weapp-core/schematics,使用 Zod 维护单一数据源
19
- */
20
- function getSchemaForType(type) {
21
- const definition = JSON_SCHEMA_DEFINITIONS.find((d) => d.typeName === type);
22
- if (!definition) return null;
23
- return definition.schema;
24
- }
25
- //#endregion
26
- //#region src/index.ts
8
+ //#region src/constants.ts
27
9
  const BLOCK_TYPE = "json";
28
- const JS_LANG = "js";
29
10
  const JSONC_LANG = "jsonc";
30
11
  const JSON_LANG = "json";
31
- const JSON5_LANG = "json5";
32
12
  const PLUGIN_VERSION = 2.2;
33
- const TS_LANG = "ts";
34
13
  const BACKSLASH_RE = /\\/g;
14
+ const IDENTIFIER_NAME_RE = /^[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*$/u;
35
15
  const NON_SPACE_RE = /\S/;
36
16
  const WXS_MODULE_RE = /<wxs[\s\S]*?module\s*=\s*(?:"([^"]+)"|'([^']+)')[\s\S]*?\/?>/gi;
37
17
  const FULL_CAPABILITIES = {
@@ -50,21 +30,185 @@ const VOID_CAPABILITIES = {
50
30
  structure: false,
51
31
  format: false
52
32
  };
53
- const require = createRequire(typeof module !== "undefined" && module.filename ? module.filename : path.join(process.cwd(), "weapp-vite-volar.cjs"));
54
- let hasSchematicsTypes = false;
55
- try {
56
- require.resolve("@weapp-core/schematics");
57
- hasSchematicsTypes = true;
58
- } catch {
59
- hasSchematicsTypes = false;
33
+ //#endregion
34
+ //#region src/schema.ts
35
+ /**
36
+ * 为小程序配置生成 JSON Schema
37
+ * 为支持 JSON Schema 的编辑器提供验证和自动补全
38
+ *
39
+ * 注意:JSON Schema 定义由 @weapp-core/schematics 统一维护
40
+ * 使用 Zod 定义并自动生成,确保单一数据源
41
+ */
42
+ /**
43
+ * 根据文件类型获取对应的 JSON Schema
44
+ * Schema 定义来自 @weapp-core/schematics,使用 Zod 维护单一数据源
45
+ */
46
+ function getSchemaForType(type) {
47
+ const definition = JSON_SCHEMA_DEFINITIONS.find((d) => d.typeName === type);
48
+ if (!definition) return null;
49
+ return definition.schema;
60
50
  }
61
- function parseVueSfc(content, filename = "component.vue") {
62
- try {
63
- return require("@vue/compiler-sfc").parse(content, { filename });
64
- } catch {
51
+ //#endregion
52
+ //#region src/jsonBlock.ts
53
+ function normalizeFilename(filename) {
54
+ if (!filename) return "";
55
+ return filename.replace(BACKSLASH_RE, "/");
56
+ }
57
+ function inferConfigType(filename) {
58
+ const normalized = normalizeFilename(filename);
59
+ if (normalized.endsWith("/app.vue")) return "App";
60
+ if (normalized.includes("/plugin/")) return "Plugin";
61
+ if (normalized.includes("/components/")) return "Component";
62
+ if (normalized.includes("/theme/")) return "Theme";
63
+ if (normalized.includes("/sitemap")) return "Sitemap";
64
+ return "Page";
65
+ }
66
+ function normalizeLang(lang) {
67
+ if (!lang) return JSON_LANG;
68
+ const lower = lang.toLowerCase();
69
+ if (lower === "txt") return JSON_LANG;
70
+ return lower;
71
+ }
72
+ function getEmbeddedCodesFromCustomBlocks(sfc) {
73
+ const names = [];
74
+ for (let i = 0; i < sfc.customBlocks.length; i++) {
75
+ const block = sfc.customBlocks[i];
76
+ if (block.type === "json") {
77
+ const normalizedLang = normalizeLang(block.lang);
78
+ if (normalizedLang === "js" || normalizedLang === "ts") {
79
+ names.push({
80
+ id: `${BLOCK_TYPE}_${i}`,
81
+ lang: "ts"
82
+ });
83
+ continue;
84
+ }
85
+ const embeddedLang = normalizedLang === "json" || normalizedLang === "jsonc" || normalizedLang === "json5" ? JSONC_LANG : JSON_LANG;
86
+ names.push({
87
+ id: `${BLOCK_TYPE}_${i}`,
88
+ lang: embeddedLang
89
+ });
90
+ }
91
+ }
92
+ return names;
93
+ }
94
+ function findExportDefaultExpression(code, tsModule, lang) {
95
+ const scriptKind = lang === "ts" ? 3 : 1;
96
+ const sourceFile = tsModule.createSourceFile(`config.${lang}`, code, 99, true, scriptKind);
97
+ for (const statement of sourceFile.statements) if (tsModule.isExportAssignment(statement)) {
98
+ const expressionStart = statement.expression.getStart(sourceFile);
99
+ const expressionEnd = statement.expression.getEnd();
100
+ const leading = code.slice(0, statement.getStart(sourceFile));
101
+ return {
102
+ expression: code.slice(expressionStart, expressionEnd),
103
+ expressionStart,
104
+ expressionEnd,
105
+ leading,
106
+ trailing: code.slice(statement.getEnd())
107
+ };
108
+ }
109
+ return null;
110
+ }
111
+ function injectSchemaIntoJsonObject(content, schemaId) {
112
+ const trimmed = content.trim();
113
+ if (!trimmed.startsWith("{")) return content;
114
+ const leftBraceIndex = content.indexOf("{");
115
+ if (leftBraceIndex < 0) return content;
116
+ const firstNonSpace = content.slice(leftBraceIndex + 1).match(NON_SPACE_RE);
117
+ const nextCharIndex = firstNonSpace ? leftBraceIndex + 1 + firstNonSpace.index : -1;
118
+ const isEmptyObject = nextCharIndex >= 0 && content[nextCharIndex] === "}";
119
+ const schemaLine = ` "$schema": "${schemaId}"`;
120
+ const injected = isEmptyObject ? `{\n${schemaLine}\n}` : `{\n${schemaLine},${content.slice(leftBraceIndex + 1)}`;
121
+ if (trimmed === content) return injected;
122
+ return `${content.slice(0, content.indexOf(trimmed))}${injected}${content.slice(content.indexOf(trimmed) + trimmed.length)}`;
123
+ }
124
+ function resolveEmbeddedJsonBlock(fileName, sfc, embeddedCode, tsModule, hasSchematicsTypes) {
125
+ const match = embeddedCode.id.match(new RegExp(`^${BLOCK_TYPE}_(\\d+)$`));
126
+ if (!match) return;
127
+ const index = Number.parseInt(match[1]);
128
+ const block = sfc.customBlocks[index];
129
+ if (!block) return;
130
+ const normalizedLang = normalizeLang(block.lang);
131
+ const configType = inferConfigType(fileName);
132
+ if (!hasSchematicsTypes) {
133
+ embeddedCode.content.push([
134
+ block.content,
135
+ block.name,
136
+ 0,
137
+ FULL_CAPABILITIES
138
+ ]);
65
139
  return;
66
140
  }
141
+ if (normalizedLang === "js" || normalizedLang === "ts") {
142
+ const parsed = tsModule && findExportDefaultExpression(block.content, tsModule, normalizedLang);
143
+ if (parsed) {
144
+ const typeImport = `import type { ${configType} as __WeappConfig } from '@weapp-core/schematics'\n`;
145
+ embeddedCode.content.push([
146
+ `${typeImport}const __weapp_defineConfig = <T extends __WeappConfig>(config: T) => config
147
+
148
+ `,
149
+ void 0,
150
+ 0,
151
+ VOID_CAPABILITIES
152
+ ]);
153
+ if (parsed.leading) embeddedCode.content.push([
154
+ parsed.leading,
155
+ block.name,
156
+ 0,
157
+ FULL_CAPABILITIES
158
+ ]);
159
+ embeddedCode.content.push([
160
+ "export default __weapp_defineConfig(",
161
+ void 0,
162
+ parsed.expressionStart,
163
+ VOID_CAPABILITIES
164
+ ]);
165
+ embeddedCode.content.push([
166
+ parsed.expression,
167
+ block.name,
168
+ parsed.expressionStart,
169
+ FULL_CAPABILITIES
170
+ ]);
171
+ embeddedCode.content.push([
172
+ ")",
173
+ void 0,
174
+ parsed.expressionEnd,
175
+ VOID_CAPABILITIES
176
+ ]);
177
+ if (parsed.trailing) embeddedCode.content.push([
178
+ parsed.trailing,
179
+ block.name,
180
+ parsed.expressionEnd,
181
+ FULL_CAPABILITIES
182
+ ]);
183
+ return;
184
+ }
185
+ embeddedCode.content.push([
186
+ block.content,
187
+ block.name,
188
+ 0,
189
+ FULL_CAPABILITIES
190
+ ]);
191
+ return;
192
+ }
193
+ const schema = getSchemaForType(configType);
194
+ if (schema && schema.$id && !block.content.includes("$schema")) {
195
+ embeddedCode.content.push([
196
+ injectSchemaIntoJsonObject(block.content, schema.$id),
197
+ block.name,
198
+ 0,
199
+ FULL_CAPABILITIES
200
+ ]);
201
+ return;
202
+ }
203
+ embeddedCode.content.push([
204
+ block.content,
205
+ block.name,
206
+ 0,
207
+ FULL_CAPABILITIES
208
+ ]);
67
209
  }
210
+ //#endregion
211
+ //#region src/scriptSetup.ts
68
212
  function collectWxsModuleNames(templateContent) {
69
213
  if (!templateContent) return [];
70
214
  const names = /* @__PURE__ */ new Set();
@@ -83,6 +227,10 @@ function appendWxsDeclarations(code, moduleNames) {
83
227
  if (!declarations) return code;
84
228
  return code ? `${code}\n\n${declarations}\n` : `${declarations}\n`;
85
229
  }
230
+ function appendScriptSetupDeclarations(code, declarations) {
231
+ if (!declarations) return code;
232
+ return code ? `${code}\n\n${declarations}\n` : `${declarations}\n`;
233
+ }
86
234
  function createSyntheticScriptSetup(moduleNames) {
87
235
  const content = createWxsModuleDeclarations(moduleNames);
88
236
  if (!content) return;
@@ -111,54 +259,248 @@ function createSyntheticScriptSetup(moduleNames) {
111
259
  name: "scriptSetup"
112
260
  };
113
261
  }
114
- function normalizeFilename(filename) {
115
- if (!filename) return "";
116
- return filename.replace(BACKSLASH_RE, "/");
262
+ function syncScriptBlockSource(block) {
263
+ if (!block) return;
264
+ const attrs = Object.entries(block.attrs ?? {}).filter(([, value]) => value != null).map(([key, value]) => value === true ? key : `${key}="${String(value)}"`).join(" ");
265
+ const openTag = attrs ? `<script ${attrs}>` : "<script>";
266
+ block.loc.source = `${openTag}\n${block.content}\n<\/script>`;
117
267
  }
118
- function inferConfigType(filename) {
119
- const normalized = normalizeFilename(filename);
120
- if (normalized.endsWith("/app.vue")) return "App";
121
- if (normalized.includes("/plugin/")) return "Plugin";
122
- if (normalized.includes("/components/")) return "Component";
123
- if (normalized.includes("/theme/")) return "Theme";
124
- if (normalized.includes("/sitemap")) return "Sitemap";
125
- return "Page";
268
+ function isIdentifierName(name) {
269
+ return IDENTIFIER_NAME_RE.test(name);
126
270
  }
127
- function normalizeLang(lang) {
128
- if (!lang) return JSON_LANG;
129
- const lower = lang.toLowerCase();
130
- if (lower === "txt") return JSON_LANG;
131
- return lower;
271
+ function getPropertyNameText(node, tsModule) {
272
+ if (tsModule.isIdentifier(node) || tsModule.isStringLiteral(node) || tsModule.isNumericLiteral(node)) return node.text;
132
273
  }
133
- function findExportDefaultExpression(code, tsModule, lang) {
134
- const scriptKind = lang === TS_LANG ? tsModule.ScriptKind.TS : tsModule.ScriptKind.JS;
135
- const sourceFile = tsModule.createSourceFile(`config.${lang}`, code, tsModule.ScriptTarget.Latest, true, scriptKind);
136
- for (const statement of sourceFile.statements) if (tsModule.isExportAssignment(statement)) {
137
- const expressionStart = statement.expression.getStart(sourceFile);
138
- const expressionEnd = statement.expression.getEnd();
139
- const leading = code.slice(0, statement.getStart(sourceFile));
140
- return {
141
- expression: code.slice(expressionStart, expressionEnd),
142
- expressionStart,
143
- expressionEnd,
144
- leading,
145
- trailing: code.slice(statement.getEnd())
146
- };
274
+ function collectBindingNames(name, tsModule, bindings) {
275
+ if (tsModule.isIdentifier(name)) {
276
+ bindings.add(name.text);
277
+ return;
278
+ }
279
+ for (const element of name.elements) if (tsModule.isBindingElement(element)) collectBindingNames(element.name, tsModule, bindings);
280
+ }
281
+ function collectTopLevelBindingNames(code, tsModule, lang) {
282
+ const scriptKind = lang === "ts" ? 3 : 1;
283
+ const sourceFile = tsModule.createSourceFile(`bindings.${lang}`, code, 99, true, scriptKind);
284
+ const bindings = /* @__PURE__ */ new Set();
285
+ for (const statement of sourceFile.statements) {
286
+ if (tsModule.isVariableStatement(statement)) {
287
+ for (const declaration of statement.declarationList.declarations) collectBindingNames(declaration.name, tsModule, bindings);
288
+ continue;
289
+ }
290
+ if ((tsModule.isFunctionDeclaration(statement) || tsModule.isClassDeclaration(statement) || tsModule.isEnumDeclaration(statement)) && statement.name) {
291
+ bindings.add(statement.name.text);
292
+ continue;
293
+ }
294
+ if (tsModule.isImportDeclaration(statement) && statement.importClause) {
295
+ const { importClause } = statement;
296
+ if (importClause.name) bindings.add(importClause.name.text);
297
+ if (importClause.namedBindings) if (tsModule.isNamespaceImport(importClause.namedBindings)) bindings.add(importClause.namedBindings.name.text);
298
+ else for (const element of importClause.namedBindings.elements) bindings.add(element.name.text);
299
+ }
300
+ }
301
+ return bindings;
302
+ }
303
+ function unwrapParenthesizedExpression(node, tsModule) {
304
+ let current = node;
305
+ while (tsModule.isParenthesizedExpression(current)) current = current.expression;
306
+ return current;
307
+ }
308
+ function findReturnedExpression(node, tsModule) {
309
+ if (tsModule.isObjectLiteralExpression(node)) return node;
310
+ if (!tsModule.isBlock(node)) return node;
311
+ for (const statement of node.statements) {
312
+ if (!tsModule.isReturnStatement(statement) || !statement.expression) continue;
313
+ return unwrapParenthesizedExpression(statement.expression, tsModule);
314
+ }
315
+ }
316
+ function findReturnedObjectLiteral(node, tsModule) {
317
+ const expression = findReturnedExpression(node, tsModule);
318
+ return expression && tsModule.isObjectLiteralExpression(expression) ? expression : void 0;
319
+ }
320
+ function extractDefineOptionsObjectLiteral(node, tsModule) {
321
+ if (!tsModule.isIdentifier(node.expression) || node.expression.text !== "defineOptions") return;
322
+ const [firstArg] = node.arguments;
323
+ if (!firstArg) return;
324
+ const arg = unwrapParenthesizedExpression(firstArg, tsModule);
325
+ if (tsModule.isObjectLiteralExpression(arg)) return arg;
326
+ if (tsModule.isArrowFunction(arg) || tsModule.isFunctionExpression(arg)) return findReturnedObjectLiteral(arg.body, tsModule);
327
+ }
328
+ function setBindingType(map, name, typeText) {
329
+ if (!map.has(name)) map.set(name, typeText);
330
+ }
331
+ function getRuntimeConstructorType(node, tsModule) {
332
+ if (tsModule.isIdentifier(node)) {
333
+ if (node.text === "String") return "string";
334
+ if (node.text === "Number") return "number";
335
+ if (node.text === "Boolean") return "boolean";
336
+ if (node.text === "Array") return "any[]";
337
+ if (node.text === "Object") return "Record<string, any>";
338
+ }
339
+ if (tsModule.isArrayLiteralExpression(node)) {
340
+ const types = [...new Set(node.elements.map((element) => {
341
+ if (tsModule.isSpreadElement(element)) return null;
342
+ return getRuntimeConstructorType(element, tsModule);
343
+ }).filter((typeText) => Boolean(typeText)))];
344
+ return types.length > 0 ? types.join(" | ") : null;
147
345
  }
148
346
  return null;
149
347
  }
150
- function injectSchemaIntoJsonObject(content, schemaId) {
151
- const trimmed = content.trim();
152
- if (!trimmed.startsWith("{")) return content;
153
- const leftBraceIndex = content.indexOf("{");
154
- if (leftBraceIndex < 0) return content;
155
- const firstNonSpace = content.slice(leftBraceIndex + 1).match(NON_SPACE_RE);
156
- const nextCharIndex = firstNonSpace ? leftBraceIndex + 1 + firstNonSpace.index : -1;
157
- const isEmptyObject = nextCharIndex >= 0 && content[nextCharIndex] === "}";
158
- const schemaLine = ` "$schema": "${schemaId}"`;
159
- const injected = isEmptyObject ? `{\n${schemaLine}\n}` : `{\n${schemaLine},${content.slice(leftBraceIndex + 1)}`;
160
- if (trimmed === content) return injected;
161
- return `${content.slice(0, content.indexOf(trimmed))}${injected}${content.slice(content.indexOf(trimmed) + trimmed.length)}`;
348
+ function getFunctionSignatureTypeText(node, sourceFile) {
349
+ if (!(node.parameters.some((parameter) => Boolean(parameter.type)) || Boolean(node.type))) return "(...args: any[]) => any";
350
+ return `(${node.parameters.map((parameter) => parameter.getText(sourceFile)).join(", ")}) => ${node.type?.getText(sourceFile) ?? "any"}`;
351
+ }
352
+ function getMiniProgramPropertyType(node, tsModule) {
353
+ const runtimeType = getRuntimeConstructorType(node, tsModule);
354
+ if (runtimeType) return runtimeType;
355
+ if (!tsModule.isObjectLiteralExpression(node)) return "any";
356
+ for (const property of node.properties) {
357
+ if (!tsModule.isPropertyAssignment(property)) continue;
358
+ if (getPropertyNameText(property.name, tsModule) !== "type") continue;
359
+ return getRuntimeConstructorType(unwrapParenthesizedExpression(property.initializer, tsModule), tsModule) ?? "any";
360
+ }
361
+ return "any";
362
+ }
363
+ function getExpressionTypeText(node, tsModule, sourceFile) {
364
+ const expression = unwrapParenthesizedExpression(node, tsModule);
365
+ if (tsModule.isAsExpression(expression) || tsModule.isTypeAssertionExpression(expression)) return expression.type.getText(sourceFile);
366
+ if (tsModule.isStringLiteral(expression) || tsModule.isNoSubstitutionTemplateLiteral(expression)) return "string";
367
+ if (tsModule.isNumericLiteral(expression)) return "number";
368
+ if (expression.kind === tsModule.SyntaxKind.TrueKeyword || expression.kind === tsModule.SyntaxKind.FalseKeyword) return "boolean";
369
+ if (tsModule.isPrefixUnaryExpression(expression) && tsModule.isNumericLiteral(expression.operand)) return "number";
370
+ if (tsModule.isArrayLiteralExpression(expression)) {
371
+ const itemTypes = [...new Set(expression.elements.map((element) => {
372
+ if (tsModule.isSpreadElement(element)) return null;
373
+ return getExpressionTypeText(element, tsModule, sourceFile);
374
+ }).filter((typeText) => Boolean(typeText) && typeText !== "undefined"))];
375
+ if (itemTypes.length === 0) return "any[]";
376
+ return itemTypes.length === 1 ? `${itemTypes[0]}[]` : `(${itemTypes.join(" | ")})[]`;
377
+ }
378
+ if (tsModule.isObjectLiteralExpression(expression)) {
379
+ const fields = [];
380
+ for (const property of expression.properties) {
381
+ if (tsModule.isPropertyAssignment(property)) {
382
+ const name = getPropertyNameText(property.name, tsModule);
383
+ if (name) fields.push(`${name}: ${getExpressionTypeText(property.initializer, tsModule, sourceFile)}`);
384
+ continue;
385
+ }
386
+ if (tsModule.isShorthandPropertyAssignment(property)) {
387
+ fields.push(`${property.name.text}: any`);
388
+ continue;
389
+ }
390
+ if (tsModule.isMethodDeclaration(property) || tsModule.isGetAccessorDeclaration(property)) {
391
+ const name = getPropertyNameText(property.name, tsModule);
392
+ if (name) fields.push(`${name}: (...args: any[]) => any`);
393
+ }
394
+ }
395
+ return fields.length > 0 ? `{ ${fields.join("; ")} }` : "Record<string, any>";
396
+ }
397
+ if (tsModule.isArrowFunction(expression) || tsModule.isFunctionExpression(expression)) return "(...args: any[]) => any";
398
+ if (tsModule.isIdentifier(expression) && expression.text === "undefined") return "undefined";
399
+ return "any";
400
+ }
401
+ function getFunctionLikeReturnTypeText(node, tsModule, sourceFile) {
402
+ if (node.type) return node.type.getText(sourceFile);
403
+ if (!node.body) return "any";
404
+ const returnedExpression = tsModule.isBlock(node.body) ? findReturnedExpression(node.body, tsModule) : findReturnedExpression(node.body, tsModule);
405
+ return returnedExpression ? getExpressionTypeText(returnedExpression, tsModule, sourceFile) : "any";
406
+ }
407
+ function collectDefineOptionsTemplateBindings(code, tsModule, lang) {
408
+ const scriptKind = lang === "ts" ? 3 : 1;
409
+ const sourceFile = tsModule.createSourceFile(`script-setup.${lang}`, code, 99, true, scriptKind);
410
+ const valueBindings = /* @__PURE__ */ new Map();
411
+ const functionBindings = /* @__PURE__ */ new Map();
412
+ const visit = (node) => {
413
+ if (tsModule.isCallExpression(node)) {
414
+ const optionsObject = extractDefineOptionsObjectLiteral(node, tsModule);
415
+ if (optionsObject) for (const property of optionsObject.properties) {
416
+ const sectionName = tsModule.isPropertyAssignment(property) || tsModule.isMethodDeclaration(property) ? getPropertyNameText(property.name, tsModule) : void 0;
417
+ if (!sectionName) continue;
418
+ if (sectionName === "methods") {
419
+ const methodsObject = tsModule.isPropertyAssignment(property) ? unwrapParenthesizedExpression(property.initializer, tsModule) : void 0;
420
+ if (methodsObject && tsModule.isObjectLiteralExpression(methodsObject)) for (const entry of methodsObject.properties) {
421
+ if (!tsModule.isPropertyAssignment(entry) && !tsModule.isMethodDeclaration(entry) && !tsModule.isShorthandPropertyAssignment(entry)) continue;
422
+ const name = getPropertyNameText(entry.name, tsModule);
423
+ if (!name || !isIdentifierName(name)) continue;
424
+ setBindingType(functionBindings, name, tsModule.isPropertyAssignment(entry) && (tsModule.isArrowFunction(entry.initializer) || tsModule.isFunctionExpression(entry.initializer)) ? getFunctionSignatureTypeText(entry.initializer, sourceFile) : tsModule.isMethodDeclaration(entry) ? getFunctionSignatureTypeText(entry, sourceFile) : "(...args: any[]) => any");
425
+ }
426
+ continue;
427
+ }
428
+ if (sectionName === "properties" || sectionName === "computed") {
429
+ const objectValue = tsModule.isPropertyAssignment(property) ? unwrapParenthesizedExpression(property.initializer, tsModule) : void 0;
430
+ if (objectValue && tsModule.isObjectLiteralExpression(objectValue)) for (const entry of objectValue.properties) {
431
+ if (!tsModule.isPropertyAssignment(entry) && !tsModule.isMethodDeclaration(entry) && !tsModule.isShorthandPropertyAssignment(entry) && !tsModule.isGetAccessorDeclaration(entry)) continue;
432
+ const name = getPropertyNameText(entry.name, tsModule);
433
+ if (!name || !isIdentifierName(name)) continue;
434
+ let typeText = "any";
435
+ if (sectionName === "properties" && tsModule.isPropertyAssignment(entry)) typeText = getMiniProgramPropertyType(unwrapParenthesizedExpression(entry.initializer, tsModule), tsModule);
436
+ else if (sectionName === "computed") {
437
+ if (tsModule.isPropertyAssignment(entry)) {
438
+ const initializer = unwrapParenthesizedExpression(entry.initializer, tsModule);
439
+ if (tsModule.isArrowFunction(initializer) || tsModule.isFunctionExpression(initializer)) typeText = getFunctionLikeReturnTypeText(initializer, tsModule, sourceFile);
440
+ } else if (tsModule.isMethodDeclaration(entry) || tsModule.isGetAccessorDeclaration(entry)) typeText = getFunctionLikeReturnTypeText(entry, tsModule, sourceFile);
441
+ }
442
+ setBindingType(valueBindings, name, typeText);
443
+ }
444
+ continue;
445
+ }
446
+ if (sectionName === "data") {
447
+ let dataObject;
448
+ if (tsModule.isMethodDeclaration(property)) dataObject = findReturnedObjectLiteral(property.body ?? tsModule.factory.createBlock([], false), tsModule);
449
+ else if (tsModule.isPropertyAssignment(property)) {
450
+ const initializer = unwrapParenthesizedExpression(property.initializer, tsModule);
451
+ if (tsModule.isObjectLiteralExpression(initializer)) dataObject = initializer;
452
+ else if (tsModule.isArrowFunction(initializer) || tsModule.isFunctionExpression(initializer)) dataObject = findReturnedObjectLiteral(initializer.body, tsModule);
453
+ }
454
+ if (dataObject) for (const property of dataObject.properties) {
455
+ if (!tsModule.isPropertyAssignment(property) && !tsModule.isMethodDeclaration(property) && !tsModule.isShorthandPropertyAssignment(property) && !tsModule.isGetAccessorDeclaration(property)) continue;
456
+ const name = getPropertyNameText(property.name, tsModule);
457
+ if (!name || !isIdentifierName(name)) continue;
458
+ setBindingType(valueBindings, name, tsModule.isPropertyAssignment(property) ? getExpressionTypeText(property.initializer, tsModule, sourceFile) : "(...args: any[]) => any");
459
+ }
460
+ }
461
+ }
462
+ }
463
+ tsModule.forEachChild(node, visit);
464
+ };
465
+ visit(sourceFile);
466
+ return {
467
+ values: [...valueBindings],
468
+ functions: [...functionBindings]
469
+ };
470
+ }
471
+ function createDefineOptionsTemplateDeclarations(code, tsModule, lang) {
472
+ const topLevelBindings = collectTopLevelBindingNames(code, tsModule, lang);
473
+ const bindings = collectDefineOptionsTemplateBindings(code, tsModule, lang);
474
+ const declarations = [];
475
+ for (const [name, typeText] of bindings.values) {
476
+ if (topLevelBindings.has(name)) continue;
477
+ declarations.push(`const ${name}: ${typeText} = null as any`);
478
+ }
479
+ for (const [name, typeText] of bindings.functions) {
480
+ if (topLevelBindings.has(name)) continue;
481
+ declarations.push(`const ${name}: ${typeText} = null as any`);
482
+ }
483
+ return declarations.join("\n");
484
+ }
485
+ function resolveScriptSetupLang(lang) {
486
+ return lang === "js" ? "js" : "ts";
487
+ }
488
+ //#endregion
489
+ //#region src/index.ts
490
+ const require = createRequire(typeof module !== "undefined" && module.filename ? module.filename : path.join(process.cwd(), "weapp-vite-volar.cjs"));
491
+ let hasSchematicsTypes = false;
492
+ try {
493
+ require.resolve("@weapp-core/schematics");
494
+ hasSchematicsTypes = true;
495
+ } catch {
496
+ hasSchematicsTypes = false;
497
+ }
498
+ function parseVueSfc(content, filename = "component.vue") {
499
+ try {
500
+ return require("@vue/compiler-sfc").parse(content, { filename });
501
+ } catch {
502
+ return;
503
+ }
162
504
  }
163
505
  /**
164
506
  * Volar 语言插件:为 weapp 配置块提供类型与 schema 提示。
@@ -180,118 +522,21 @@ const plugin = (ctx) => {
180
522
  if (!parsed) return;
181
523
  const descriptor = parsed.descriptor;
182
524
  const wxsModuleNames = collectWxsModuleNames(descriptor.template?.content);
183
- if (!wxsModuleNames.length) return parsed;
184
- if (descriptor.scriptSetup) descriptor.scriptSetup.content = appendWxsDeclarations(descriptor.scriptSetup.content, wxsModuleNames);
185
- else descriptor.scriptSetup = createSyntheticScriptSetup(wxsModuleNames);
525
+ const scriptSetup = descriptor.scriptSetup;
526
+ const scriptSetupLang = resolveScriptSetupLang(scriptSetup?.lang);
527
+ const defineOptionsDeclarations = scriptSetup?.content && tsModule ? createDefineOptionsTemplateDeclarations(scriptSetup.content, tsModule, scriptSetupLang) : "";
528
+ if (!wxsModuleNames.length && !defineOptionsDeclarations) return parsed;
529
+ if (descriptor.scriptSetup) {
530
+ descriptor.scriptSetup.content = appendScriptSetupDeclarations(appendWxsDeclarations(descriptor.scriptSetup.content, wxsModuleNames), defineOptionsDeclarations);
531
+ syncScriptBlockSource(descriptor.scriptSetup);
532
+ } else descriptor.scriptSetup = createSyntheticScriptSetup(wxsModuleNames);
186
533
  return parsed;
187
534
  },
188
535
  getEmbeddedCodes(_, sfc) {
189
- const names = [];
190
- for (let i = 0; i < sfc.customBlocks.length; i++) {
191
- const block = sfc.customBlocks[i];
192
- if (block.type === BLOCK_TYPE) {
193
- const normalizedLang = normalizeLang(block.lang);
194
- if (normalizedLang === JS_LANG || normalizedLang === TS_LANG) {
195
- names.push({
196
- id: `${BLOCK_TYPE}_${i}`,
197
- lang: TS_LANG
198
- });
199
- continue;
200
- }
201
- const embeddedLang = normalizedLang === JSON_LANG || normalizedLang === JSONC_LANG || normalizedLang === JSON5_LANG ? JSONC_LANG : JSON_LANG;
202
- names.push({
203
- id: `${BLOCK_TYPE}_${i}`,
204
- lang: embeddedLang
205
- });
206
- }
207
- }
208
- return names;
536
+ return getEmbeddedCodesFromCustomBlocks(sfc);
209
537
  },
210
538
  resolveEmbeddedCode(fileName, sfc, embeddedCode) {
211
- const match = embeddedCode.id.match(new RegExp(`^${BLOCK_TYPE}_(\\d+)$`));
212
- if (!match) return;
213
- const index = Number.parseInt(match[1]);
214
- const block = sfc.customBlocks[index];
215
- if (!block) return;
216
- const normalizedLang = normalizeLang(block.lang);
217
- const configType = inferConfigType(fileName);
218
- if (!hasSchematicsTypes) {
219
- embeddedCode.content.push([
220
- block.content,
221
- block.name,
222
- 0,
223
- FULL_CAPABILITIES
224
- ]);
225
- return;
226
- }
227
- if (normalizedLang === JS_LANG || normalizedLang === TS_LANG) {
228
- const parsed = tsModule && findExportDefaultExpression(block.content, tsModule, normalizedLang);
229
- if (parsed && hasSchematicsTypes) {
230
- const typeImport = `import type { ${configType} as __WeappConfig } from '@weapp-core/schematics'\n`;
231
- embeddedCode.content.push([
232
- `${typeImport}const __weapp_defineConfig = <T extends __WeappConfig>(config: T) => config
233
-
234
- `,
235
- void 0,
236
- 0,
237
- VOID_CAPABILITIES
238
- ]);
239
- if (parsed.leading) embeddedCode.content.push([
240
- parsed.leading,
241
- block.name,
242
- 0,
243
- FULL_CAPABILITIES
244
- ]);
245
- embeddedCode.content.push([
246
- "export default __weapp_defineConfig(",
247
- void 0,
248
- parsed.expressionStart,
249
- VOID_CAPABILITIES
250
- ]);
251
- embeddedCode.content.push([
252
- parsed.expression,
253
- block.name,
254
- parsed.expressionStart,
255
- FULL_CAPABILITIES
256
- ]);
257
- embeddedCode.content.push([
258
- ")",
259
- void 0,
260
- parsed.expressionEnd,
261
- VOID_CAPABILITIES
262
- ]);
263
- if (parsed.trailing) embeddedCode.content.push([
264
- parsed.trailing,
265
- block.name,
266
- parsed.expressionEnd,
267
- FULL_CAPABILITIES
268
- ]);
269
- return;
270
- }
271
- embeddedCode.content.push([
272
- block.content,
273
- block.name,
274
- 0,
275
- FULL_CAPABILITIES
276
- ]);
277
- return;
278
- }
279
- const schema = getSchemaForType(configType);
280
- if (schema && schema.$id && !block.content.includes("$schema")) {
281
- embeddedCode.content.push([
282
- injectSchemaIntoJsonObject(block.content, schema.$id),
283
- block.name,
284
- 0,
285
- FULL_CAPABILITIES
286
- ]);
287
- return;
288
- }
289
- embeddedCode.content.push([
290
- block.content,
291
- block.name,
292
- 0,
293
- FULL_CAPABILITIES
294
- ]);
539
+ resolveEmbeddedJsonBlock(fileName, sfc, embeddedCode, tsModule, hasSchematicsTypes);
295
540
  }
296
541
  };
297
542
  };