-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathpage.ts
213 lines (159 loc) · 5.84 KB
/
page.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import { existsSync, readFileSync } from 'node:fs'
import { dirname, extname, join } from 'node:path'
import process from 'node:process'
import type { SFCDescriptor, SFCScriptBlock } from '@vue/compiler-sfc'
import { babelParse, isCallOf } from 'ast-kit'
import * as t from '@babel/types'
import generate from '@babel/generator'
import JSON5 from 'json5'
import { parse as YAMLParser } from 'yaml'
import { normalizePath } from 'vite'
import type { PageContext } from './context'
import { debug, parseSFC } from './utils'
import type { DefinePageOptions, PageMetaDatum, PagePath, RouteBlockLang } from './types'
import { DEFINE_PAGE } from './constant'
import { runProcess } from './child-process'
export class Page {
ctx: PageContext
file: PagePath
private rawOptions: string = ''
private options: PageMetaDatum | undefined
constructor(ctx: PageContext, file: PagePath) {
this.ctx = ctx
this.file = file
}
async getOptions(forceUpdate = false) {
if (forceUpdate || !this.options)
await this.readOptions()
return this.options!
}
async hasChanged() {
const { hasChanged } = await this.readOptions()
return hasChanged
}
async readOptions() {
try {
const { relativePath, absolutePath } = this.file
// eslint-disable-next-line unused-imports/no-unused-vars
const { path, ...others } = await readPageOptionsFromFile(absolutePath, this.ctx.options.routeBlockLang)
this.options = {
path: normalizePath(relativePath.replace(extname(relativePath), '')),
...others,
}
const raw = (this.options ? JSON.stringify(this.options) : '')
const hasChanged = this.rawOptions !== raw
this.rawOptions = raw
return {
options: this.options,
hasChanged,
}
}
catch (err: any) {
throw new Error(`Read page options fail in ${this.file.relativePath}\n${err.message}`)
}
}
}
async function readPageOptionsFromFile(path: string, routeBlockLang: RouteBlockLang) {
const content = readFileSync(path, 'utf-8')
const sfc = await parseSFC(content)
const macroOptions = await readPageOptionsFromMacro(path, sfc)
if (macroOptions)
return macroOptions
const blockOptions = await readPageOptionsFromBlock(path, routeBlockLang, sfc)
if (blockOptions)
return blockOptions
return {} as DefinePageOptions
}
async function readPageOptionsFromMacro(path: string, sfc?: SFCDescriptor) {
if (!sfc) {
const content = readFileSync(path, 'utf-8')
sfc = await parseSFC(content)
}
const { macro, imports } = findMacroWithImports(sfc.scriptSetup)
if (!macro)
return
if (sfc?.customBlocks.find(b => b.type === 'route'))
throw new Error(`mixed ${DEFINE_PAGE}() and <route/> is not allowed`)
const [arg] = macro.arguments as [t.Expression]
if (!arg)
return
const options: DefinePageOptions = await runExpressionByTSX({ file: path, arg, imports })
return options
}
async function readPageOptionsFromBlock(path: string, routeBlockLang: RouteBlockLang, sfc?: SFCDescriptor) {
if (!sfc) {
const content = readFileSync(path, 'utf-8')
sfc = await parseSFC(content)
}
const block = sfc.customBlocks.find(b => b.type === 'route')
if (!block)
return
const lang = (block.lang ?? routeBlockLang) as RouteBlockLang
debug.routeBlock(`use ${lang} parser`)
let options = {} as PageMetaDatum
if (['json5', 'jsonc', 'json'].includes(lang))
options = JSON5.parse(block.content) as PageMetaDatum
else if (['yaml', 'yml'].includes(lang))
options = YAMLParser(block.content) as PageMetaDatum
if (!options.type)
options.type = (typeof block.attrs.type === 'string') && block.attrs.type.length ? block.attrs.type : 'page'
return options
}
function findMacroWithImports(scriptSetup: SFCScriptBlock | null) {
const empty = { imports: [], macro: undefined } as {
imports: t.ImportDeclaration[]
macro: t.CallExpression | undefined
}
if (!scriptSetup)
return empty
const parsed = babelParse(scriptSetup.content, scriptSetup.lang || 'js', {
plugins: [['importAttributes', { deprecatedAssertSyntax: true }]],
})
const stmts = parsed.body
const nodes = stmts
.map((raw: t.Node) => {
let node = raw
if (raw.type === 'ExpressionStatement')
node = raw.expression
return isCallOf(node, DEFINE_PAGE) ? node : undefined
})
.filter((node): node is t.CallExpression => !!node)
if (!nodes.length)
return empty
if (nodes.length > 1)
throw new Error(`duplicate ${DEFINE_PAGE}() call`)
const macro = nodes[0]
const [arg] = macro.arguments
if (arg && !t.isFunctionExpression(arg) && !t.isArrowFunctionExpression(arg) && !t.isObjectExpression(arg))
throw new Error(`${DEFINE_PAGE}() only accept argument in function or object`)
const imports = stmts
.map((node: t.Node) => (node.type === 'ImportDeclaration') ? node : undefined)
.filter((node): node is t.ImportDeclaration => !!node)
return {
imports,
macro,
}
}
export function findMacro(scriptSetup: SFCScriptBlock | null) {
return findMacroWithImports(scriptSetup).macro
}
async function runExpressionByTSX(options: { file: string, arg: t.Expression, imports: t.ImportDeclaration[] }) {
const {
file,
arg,
imports,
} = options
const tsx = join(process.cwd(), 'node_modules', '.bin', 'tsx')
if (!existsSync(tsx))
throw new Error(`[vite-plugin-uni-pages] "tsx" is required for function argument of definePage macro`)
const code = generate(arg).code
const cwd = dirname(file)
let script = ''
for (const imp of imports)
script += `${generate(imp).code}\n`
script += t.isFunctionExpression(arg) || t.isArrowFunctionExpression(arg)
? `Promise.resolve((${code})()).then(res=>console.log(JSON.stringify(res)))`
: `console.log(JSON.stringify(${code}))`
const result = await runProcess(tsx, ['-e', script], { cwd })
return JSON.parse(result)
}