Skip to content

Commit

Permalink
Update packages/core/src/definePage.ts
Browse files Browse the repository at this point in the history
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
  • Loading branch information
CrazyZhang3 and coderabbitai[bot] authored Aug 27, 2024
1 parent fa71a29 commit 13465ef
Showing 1 changed file with 33 additions and 29 deletions.
62 changes: 33 additions & 29 deletions packages/core/src/definePage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,46 +6,50 @@ import { MACRO_DEFINE_PAGE } from './constant'
import type { PageMetaDatum } from './types'

function findMacroWithImports(scriptSetup: SFCScriptBlock | null) {
const empty = { imports: [], macro: undefined }
try {
const empty = { imports: [], macro: undefined }

if (!scriptSetup)
return empty
if (!scriptSetup)
return empty

const parsed = babelParse(scriptSetup.content, scriptSetup.lang || 'js', {
plugins: [['importAttributes', { deprecatedAssertSyntax: true }]],
})
const parsed = babelParse(scriptSetup.content, scriptSetup.lang || 'js', {
plugins: [['importAttributes', { deprecatedAssertSyntax: true }]],
})

const stmts = parsed.body
const stmts = parsed.body

const nodes = stmts
.map((raw: t.Node) => {
let node = raw
if (raw.type === 'ExpressionStatement')
node = raw.expression
return isCallOf(node, MACRO_DEFINE_PAGE) ? node : undefined
})
.filter((node): node is t.CallExpression => !!node)
const nodes = stmts
.map((raw: t.Node) => {
let node = raw
if (raw.type === 'ExpressionStatement')
node = raw.expression
return isCallOf(node, MACRO_DEFINE_PAGE) ? node : undefined
})
.filter((node): node is t.CallExpression => !!node)

if (!nodes.length)
return empty
if (!nodes.length)
return empty

if (nodes.length > 1)
throw new Error(`duplicate ${MACRO_DEFINE_PAGE}() call`)
if (nodes.length > 1)
throw new Error(`duplicate ${MACRO_DEFINE_PAGE}() call`)

const macro = nodes[0]
const macro = nodes[0]

const [arg] = macro.arguments
const [arg] = macro.arguments

if (arg && !t.isFunctionExpression(arg) && !t.isArrowFunctionExpression(arg) && !t.isObjectExpression(arg))
throw new Error(`${MACRO_DEFINE_PAGE}() only accept argument in function or object`)
if (arg && !t.isFunctionExpression(arg) && !t.isArrowFunctionExpression(arg) && !t.isObjectExpression(arg))
throw new Error(`${MACRO_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)
const imports = stmts
.map((node: t.Node) => (node.type === 'ImportDeclaration') ? node : undefined)
.filter((node): node is t.ImportDeclaration => !!node)

return {
imports,
macro,
return {
imports,
macro,
}
} catch (error) {
throw new Error(`Error parsing script setup content: ${error.message}`)
}
}

Expand Down

0 comments on commit 13465ef

Please sign in to comment.