Skip to content

Commit a3af243

Browse files
committed
test(transform): add ecosystem tests
1 parent 017ad51 commit a3af243

File tree

12 files changed

+264
-73
lines changed

12 files changed

+264
-73
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@
3535
"prepublishOnly": "pnpm lint && pnpm test",
3636
"release": "np",
3737
"test": "vitest run",
38-
"test:spec": "vitest test/stringify.test.ts",
3938
"test:types": "tsc --noEmit"
4039
},
4140
"dependencies": {
@@ -64,6 +63,7 @@
6463
"@types/node": "18.15.3",
6564
"@vitest/browser": "^0.30.1",
6665
"acorn": "8.8.2",
66+
"degit": "^2.8.4",
6767
"eslint": "8.36.0",
6868
"eslint-config-prettier": "latest",
6969
"eslint-plugin-prettier": "latest",

pnpm-lock.yaml

Lines changed: 15 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/core/storage.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,14 @@ export const liveFlytrapStorage: FlytrapStorage = {
159159
return
160160
}
161161

162+
log.info(
163+
'api-calls',
164+
`[POST] https://www.useflytrap.com/api/v1/captures - Payload size ~${stringifiedPayload.length} bytes.`
165+
)
166+
log.info(
167+
'storage',
168+
`[POST] https://www.useflytrap.com/api/v1/captures - Payload size ~${stringifiedPayload.length} bytes.`
169+
)
162170
// TODO: use something like `devalue` to get closer to reality
163171
const { error: captureError } = await post(
164172
`https://www.useflytrap.com/api/v1/captures`,

src/transform.ts

Lines changed: 61 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { pathToFileURL } from 'node:url'
2-
import { createUnplugin } from 'unplugin'
2+
import { UnpluginOptions, createUnplugin } from 'unplugin'
33
import { parseURL, parseQuery } from 'ufo'
44
import MagicString from 'magic-string'
55
import { addFlytrapInit, addMissingFlytrapImports } from './transform/imports'
@@ -11,66 +11,77 @@ import { loadConfig } from './transform/config'
1111
import { setFlytrapConfig } from './core/config'
1212
import { log } from './core/logging'
1313

14-
export const FlytrapTransformPlugin = createUnplugin(() => {
15-
return {
16-
name: 'FlytrapTransformPlugin',
17-
enforce: 'pre',
18-
transformInclude(id) {
19-
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href))
20-
const { type } = parseQuery(search)
14+
export const unpluginOptions: UnpluginOptions = {
15+
name: 'FlytrapTransformPlugin',
16+
enforce: 'pre',
17+
transformInclude(id) {
18+
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href))
19+
const { type } = parseQuery(search)
2120

22-
// vue files
23-
if (pathname.endsWith('.vue') && (type === 'script' || !search)) {
24-
return true
25-
}
21+
// vue files
22+
if (pathname.endsWith('.vue') && (type === 'script' || !search)) {
23+
return true
24+
}
2625

27-
// svelte files
28-
if (pathname.endsWith('.svelte') && (type === 'script' || !search)) {
29-
return true
30-
}
26+
// svelte files
27+
if (pathname.endsWith('.svelte') && (type === 'script' || !search)) {
28+
return true
29+
}
3130

32-
// js files
33-
if (pathname.match(/\.((c|m)?j|t)sx?$/g)) {
34-
return true
35-
}
31+
// js files
32+
if (pathname.match(/\.((c|m)?j|t)sx?$/g)) {
33+
return true
34+
}
3635

37-
return false
38-
},
39-
async transform(code, id) {
40-
if (code.includes('@flytrap-ignore') || id.includes('/node_modules/')) {
41-
return
42-
}
36+
return false
37+
},
38+
async transform(code, id) {
39+
if (code.includes('@flytrap-ignore') || id.includes('/node_modules/')) {
40+
return
41+
}
4342

44-
// Logging config
45-
const config = await loadConfig()
46-
if (config) setFlytrapConfig(config)
47-
log.info('transform', `Transforming file ${id}`)
43+
// Logging config
44+
const config = await loadConfig()
45+
if (config) setFlytrapConfig(config)
46+
log.info('transform', `Transforming file ${id}`)
4847

49-
const ss = new MagicString(code)
50-
// add missing Flytrap imports
51-
addMissingFlytrapImports(ss)
48+
const ss = new MagicString(code)
49+
// add missing Flytrap imports
50+
addMissingFlytrapImports(ss)
5251

53-
// add Flytrap init
52+
// add Flytrap init
53+
if (process.env.NODE_ENV !== 'test') {
5454
await addFlytrapInit(ss)
55+
}
5556

56-
// Find package root
57-
const pkgDirPath = packageDirectorySync()
58-
if (!pkgDirPath) {
59-
throw createHumanLog({
60-
event: 'transform_failed',
61-
explanation: 'transform_pkg_not_found'
62-
}).toString()
63-
}
57+
// Find package root
58+
const pkgDirPath = packageDirectorySync()
59+
if (!pkgDirPath) {
60+
throw createHumanLog({
61+
event: 'transform_failed',
62+
explanation: 'transform_pkg_not_found'
63+
}).toString()
64+
}
6465

65-
try {
66-
return flytrapTransform(ss.toString(), id.replace(pkgDirPath, ''))
67-
} catch (e) {
68-
console.warn(`Oops! Something went wrong while transforming file ${id}. Error:`)
69-
console.warn(e)
66+
try {
67+
return flytrapTransform(ss.toString(), id.replace(pkgDirPath, ''))
68+
} catch (e) {
69+
console.log('TRANSFORMED FILE CODE: ')
70+
console.log(ss.toString())
71+
console.log(
72+
' errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- errorr -- '
73+
)
74+
console.log('filepath ', id)
75+
console.log(JSON.stringify(e))
76+
console.log(e)
77+
console.log('FILE ', id)
78+
if (process.env.NODE_ENV === 'test') {
79+
throw e
7080
}
81+
console.warn(`Oops! Something went wrong while transforming file ${id}. Error:`)
82+
console.warn(e)
7183
}
7284
}
73-
})
85+
}
7486

75-
// Export code transform
76-
export * from './transform/index'
87+
export const FlytrapTransformPlugin = createUnplugin(() => unpluginOptions)

src/transform/config.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { lilconfig } from 'lilconfig'
2-
import { join } from 'path'
32
import { tryCatch } from '../core/util'
43
import { createHumanLog } from '../core/human-logs'
54
import { FlytrapConfig } from '../core/types'
@@ -10,7 +9,6 @@ export async function loadConfig(): Promise<FlytrapConfig | undefined> {
109
const moduleName = 'flytrap'
1110

1211
const { search } = lilconfig('flytrap', {
13-
stopDir: join(process.cwd(), '..'),
1412
searchPlaces: [
1513
'package.json',
1614
`.${moduleName}rc.json`,

src/transform/imports.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,19 @@ import MagicString from 'magic-string'
22
import { findStaticImports } from 'mlly'
33
import { FLYTRAP_PACKAGE_NAME } from '../core/config'
44
import { loadConfig } from './config'
5-
import * as flytrapExports from '../index'
65
import { parse } from '@babel/parser'
76

87
export function getCoreExports(): string[] {
9-
return Object.keys(flytrapExports)
8+
return ['useFlytrapCall', 'useFlytrapCallAsync', 'useFlytrapFunction', 'capture', 'identify']
109
}
1110

1211
export function findStartingIndex(s: MagicString) {
1312
const ast = parse(s.toString(), { sourceType: 'module', plugins: ['jsx', 'typescript'] })
1413

14+
if (ast.program.interpreter && ast.program.interpreter.end) {
15+
return ast.program.interpreter.end
16+
}
17+
1518
if (ast.program.directives && ast.program.directives[0]?.type === 'Directive') {
1619
return ast.program.directives[0].end ?? 0
1720
}

src/transform/index.ts

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,7 @@ export function flytrapTransform(code: string, filePath: string) {
161161

162162
const takenCallIds: string[] = []
163163
const takenFunctionIds: string[] = []
164+
const takenFunctionNames: string[] = []
164165

165166
_babelInterop(babelTraverse)(ast, {
166167
ArrowFunctionExpression(path) {
@@ -207,11 +208,36 @@ export function flytrapTransform(code: string, filePath: string) {
207208
const useFunctionName = 'useFlytrapFunction'
208209
const scopes = getScopes(path)
209210

210-
const functionName = (path.node.id as Identifier).name
211+
const functionName = path.node.id ? path.node.id.name : 'anonymous'
212+
211213
// derive function ID
212214
const functionId = getAvailableFunctionId(filePath, scopes, functionName, takenFunctionIds)
213215
takenFunctionIds.push(functionId)
214216

217+
// case for default exports
218+
if (path.parent.type === 'ExportDefaultDeclaration') {
219+
const newNode = callExpression(identifier(useFunctionName), [
220+
toExpression(path.node),
221+
objectExpression([
222+
objectProperty(identifier('id'), stringLiteral(functionId)),
223+
// @ts-ignore
224+
// objectProperty(identifier('name'), stringLiteral(path.node.id.name)),
225+
objectProperty(
226+
identifier('name'),
227+
path.node.id ? stringLiteral(path.node.id.name) : stringLiteral(functionName)
228+
),
229+
objectProperty(identifier('filePath'), stringLiteral(filePath)),
230+
objectProperty(identifier('lineNumber'), numericLiteral(getLineNumber(path.node))),
231+
objectProperty(
232+
identifier('scopes'),
233+
arrayExpression(scopes.map((scope) => stringLiteral(scope)))
234+
)
235+
])
236+
])
237+
path.replaceWith(newNode)
238+
return
239+
}
240+
215241
const newNode = variableDeclaration('const', [
216242
variableDeclarator(
217243
// @ts-ignore

test/stringify.test.ts

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,4 @@
1-
import {
2-
useFlytrapFunction,
3-
useFlytrapCall,
4-
_resetExecutingFunctions,
5-
_resetFunctionCalls,
6-
getFunctionCalls
7-
} from 'useflytrap'
8-
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
9-
import { z } from 'zod'
1+
import { describe, it } from 'vitest'
102
import { walk } from '../src/core/stringify'
113

124
describe('stringifying unserialzable values', () => {

0 commit comments

Comments
 (0)