2020-04-22 07:25:43 +02:00
|
|
|
import { NodePath, PluginObj, types as BabelTypes } from '@babel/core'
|
2019-04-02 16:09:34 +02:00
|
|
|
|
2020-05-18 21:24:37 +02:00
|
|
|
export default function ({
|
2019-05-23 09:52:36 +02:00
|
|
|
types: t,
|
|
|
|
}: {
|
|
|
|
types: typeof BabelTypes
|
|
|
|
}): PluginObj<any> {
|
2019-04-02 16:09:34 +02:00
|
|
|
return {
|
|
|
|
visitor: {
|
2019-05-23 09:52:36 +02:00
|
|
|
ImportDeclaration(path: NodePath<BabelTypes.ImportDeclaration>, state) {
|
2019-04-02 16:09:34 +02:00
|
|
|
const source = path.node.source.value
|
|
|
|
if (source !== 'next/data') return
|
|
|
|
|
2020-05-18 21:24:37 +02:00
|
|
|
const createHookSpecifier = path.get('specifiers').find((specifier) => {
|
2019-05-23 09:52:36 +02:00
|
|
|
return (
|
|
|
|
specifier.isImportSpecifier() &&
|
|
|
|
specifier.node.imported.name === 'createHook'
|
|
|
|
)
|
2019-04-02 16:09:34 +02:00
|
|
|
})
|
|
|
|
|
|
|
|
if (!createHookSpecifier) return
|
|
|
|
|
|
|
|
const bindingName = createHookSpecifier.node.local.name
|
|
|
|
const binding = path.scope.getBinding(bindingName)
|
|
|
|
|
|
|
|
if (!binding) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-05-18 21:24:37 +02:00
|
|
|
binding.referencePaths.forEach((refPath) => {
|
2019-04-02 16:09:34 +02:00
|
|
|
let callExpression = refPath.parentPath
|
|
|
|
|
|
|
|
if (!callExpression.isCallExpression()) return
|
2019-05-23 09:52:36 +02:00
|
|
|
|
2019-04-02 16:09:34 +02:00
|
|
|
let args: any = callExpression.get('arguments')
|
2019-05-23 09:52:36 +02:00
|
|
|
|
2019-04-02 16:09:34 +02:00
|
|
|
if (!args[0]) {
|
2019-05-23 09:52:36 +02:00
|
|
|
throw callExpression.buildCodeFrameError(
|
|
|
|
'first argument to createHook should be a function'
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2019-04-02 16:09:34 +02:00
|
|
|
if (!args[1]) {
|
|
|
|
callExpression.node.arguments.push(t.objectExpression([]))
|
|
|
|
}
|
2019-05-23 09:52:36 +02:00
|
|
|
|
2019-04-02 16:09:34 +02:00
|
|
|
args = callExpression.get('arguments')
|
|
|
|
|
2019-05-23 09:52:36 +02:00
|
|
|
args[1].node.properties.push(
|
|
|
|
t.objectProperty(
|
|
|
|
t.identifier('key'),
|
|
|
|
t.stringLiteral(state.opts.key)
|
|
|
|
)
|
|
|
|
)
|
2019-04-02 16:09:34 +02:00
|
|
|
})
|
2019-05-23 09:52:36 +02:00
|
|
|
},
|
|
|
|
},
|
2019-04-02 16:09:34 +02:00
|
|
|
}
|
|
|
|
}
|