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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530import FS from 'node:fs/promises'
import { inspect } from 'node:util'
import { parse } from '@babel/parser'
import type {
Node,
NumericLiteral,
ObjectExpression,
ObjectMethod,
ObjectProperty,
StringLiteral,
VariableDeclarator,
} from '@babel/types'
import {
is,
traverse,
} from '@babel/types'
import Logger from '../../../Logger'
import { MeteorViteError } from '../../../vite/error/MeteorViteError'
import type {
MeteorInstallCallExpression,
MeteorPackageProperty,
ModuleMethod,
ModuleMethodName,
} from './ParserTypes'
import {
KnownModuleMethodNames,
} from './ParserTypes'
interface ParseOptions {
/**
* Absolute file path to the package's JavaScript file.
* This file needs to have been built by Meteor.
* The package source code is not handled by the parser.
*/
filePath: string
/**
* Optionally use file content from memory instead of pulling the file content during parser setup.
* Used primarily to for performance reasons in mock tests and potentially within the Vite plugin load requests.
*
* We still want the filePath property to maintain good traceability in error messages.
*/
fileContent?: Promise<string> | string
}
export async function parseMeteorPackage({ fileContent, filePath }: ParseOptions) {
const startTime = Date.now()
const content = (fileContent || FS.readFile(filePath, 'utf-8'))
const result: ParsedPackage = await parseSource(await content)
if (!result.name) {
throw new ParserError(`Could not extract name from package in: ${filePath}`, {
parseOptions: { fileContent, filePath },
})
}
if (!result.packageId)
result.packageId = `meteor/${result.name}`
const moduleExports = Object.keys(result.modules)
const packageExports = Object.keys(result.packageScopeExports)
if (!moduleExports.length && !packageExports.length) {
console.warn(
'Unable to retrieve any metadata from the provided source code!',
{ result },
)
throw new ParserError(`No modules or package-scope exports could be extracted from package: ${result.name}`)
}
return {
result,
timeSpent: `${Date.now() - startTime}ms`,
}
}
function parseSource(code: string) {
return new Promise<ParsedPackage>((resolve) => {
const source = parse(code)
const result: ParsedPackage = {
name: '',
modules: {},
packageScopeExports: {},
mainModulePath: '',
packageId: '',
}
traverse(source, {
enter(node) {
const packageScope = parsePackageScope(node)
const meteorInstall = MeteorInstall.parse(node)
result.mainModulePath = readMainModulePath(node) || result.mainModulePath
if (meteorInstall)
Object.assign(result, meteorInstall)
if (packageScope) {
result.name = result.name || packageScope.name
result.packageScopeExports[packageScope.name] = packageScope.exports
}
},
})
resolve(result)
})
}
function readMainModulePath(node: Node) {
if (node.type !== 'VariableDeclarator')
return
if (!is('Identifier', node.id, { name: 'exports' }))
return
if (node.init?.type !== 'CallExpression')
return
if (!is('Identifier', node.init.callee, { name: 'require' }))
return
if (node.init.arguments[0]?.type !== 'StringLiteral')
return
// node_modules/meteor/<author>:<packageName>/<mainModule>
return node.init.arguments[0].value
}
const propParser = {
getKey(property: ObjectMethod | ObjectProperty) {
if (property.key.type === 'Identifier')
return property.key.name
if (property.key.type === 'StringLiteral')
return property.key.value
throw new ModuleExportsError('Unsupported property key type!', property)
},
}
function parsePackageScope(node: Node) {
if (node.type !== 'CallExpression')
return
if (node.callee.type !== 'MemberExpression')
return
const { object, property } = node.callee
if (object.type !== 'Identifier')
return
if (object.name !== 'Package')
return
if (property.type !== 'Identifier')
return
if (property.name !== '_define')
return
const args = {
packageName: node.arguments[0],
moduleExports: node.arguments[1],
packageExports: node.arguments[2],
}
if (args.packageName.type !== 'StringLiteral')
throw new ModuleExportsError('Unexpected type received for package name!', args.packageName)
/**
* Deals with the meteor/meteor core packages that don't use the module system.
*/
if (!args.packageExports && args.moduleExports?.type === 'ObjectExpression')
args.packageExports = args.moduleExports
const packageExport = {
name: args.packageName.value,
exports: [] as string[],
}
/**
* Module is likely a lazy-loaded package or one that only provides side effects as there are no exports in any
* form.
*/
if (!args.packageExports)
return packageExport
if (args.packageExports.type !== 'ObjectExpression')
throw new ModuleExportsError('Unexpected type received for package-scope exports argument!', args.packageExports)
args.packageExports.properties.forEach((property) => {
if (property.type === 'SpreadElement')
throw new ModuleExportsError('Unexpected property type received for package-scope exports!', property)
packageExport.exports.push(propParser.getKey(property))
})
return packageExport
}
/**
* Parser for a build Meteor package's meteorInstall() call.
* Traverses through all the entries in the passed object to build up a map of each file exposed by the package
* as well as tracking exports (module.export, module.exportDefault) and re-exports (module.link).
* {@link https://github.com/Akryum/meteor-vite/blob/8b0a7a5f5f95d78661793e8b4bc7f266c1081ed9/npm-packages/meteor-vite/test/__mocks/meteor-bundle/rdb_svelte-meteor-data.js#L25 example of meteorInstall() }
*/
class MeteorInstall {
public readonly modules: ModuleList = {}
public readonly packageId: string
public readonly name: string
constructor({ packageId, name }: Pick<MeteorInstall, 'packageId' | 'name'>) {
this.packageId = packageId
this.name = name
}
public static parse(requireDeclaration: Node) {
if (!this.isRequireDeclaration(requireDeclaration))
return
if (!this.isMeteorInstall(requireDeclaration.init))
return
const modules = requireDeclaration.init.arguments[0]
const node_modules = modules.properties[0]
const meteor = node_modules.value.properties[0]
const packageName = meteor.value.properties[0]
const packageModules = packageName.value.properties
const meteorPackage = new this({
packageId: `${propParser.getKey(meteor)}/${propParser.getKey(packageName)}`,
name: propParser.getKey(packageName),
})
meteorPackage.traverseModules(packageModules, '')
return meteorPackage
}
protected static isRequireDeclaration(node: Node): node is VariableDeclarator {
if (node.type !== 'VariableDeclarator')
return false
if (node.id.type !== 'Identifier')
return false
if (node.id.name !== 'require')
return false
return true
}
protected static isMeteorInstall(expression?: Node | null): expression is MeteorInstallCallExpression {
if (!expression)
return false
if (expression.type !== 'CallExpression')
return false
if (!is('Identifier', expression.callee, { name: 'meteorInstall' }))
return false
return true
}
public traverseModules(properties: MeteorPackageProperty[], parentPath: string) {
properties.forEach((property) => {
const path = `${parentPath}${property.key.value.toString()}`
const module = new PackageModule()
if (property.value.type === 'ObjectExpression')
return this.traverseModules(property.value.properties, `${path}/`)
traverse(property.value.body, {
enter(node) {
module.parse(node)
},
})
this.modules[path] = module.exports
})
}
}
/**
* An individual file within a built Meteor package's meteorInstall file tree.
* It essentially represents a single file and its associated exports within a given Meteor package.
* E.g. `index.js` or `cookie-store.js`.
*
* {@link https://github.com/Akryum/meteor-vite/blob/78a451fa311989d10cbb061bb929d8feb795ea2c/npm-packages/meteor-vite/test/__mocks/meteor-bundle/test_ts-modules.js#L20 `explicit-relative-path.ts`} would count as a module here.
*/
class PackageModule {
public readonly exports: ModuleExportData[] = []
// Todo: Accept module metadata from callee to provide more insightful error messages
constructor() {}
/**
* Helper for checking if an already validated node is of the provided method
*/
protected isMethod<MethodName extends ModuleMethodName>(node: ModuleMethod.MethodMap[ModuleMethodName], method: MethodName): node is ModuleMethod.MethodMap[MethodName] {
return node.callee.property.name === method
}
/**
* Check if provided node is a valid `module.[method]` call expression.
*/
protected shouldParse(node: Node): node is ModuleMethod.MethodMap[ModuleMethodName] {
if (node.type !== 'CallExpression')
return false
const callee = node.callee
if (callee.type !== 'MemberExpression')
return false
if (callee.object.type !== 'Identifier')
return false
if (!callee.object.name.match(/^module\d*$/))
return false
if (callee.property.type !== 'Identifier')
return false
const calleeMethod = callee.property.name
if (!KnownModuleMethodNames.includes(calleeMethod as ModuleMethodName)) {
Logger.warn(`Meteor module.${calleeMethod}(...) is not recognized by Meteor-Vite! Please open an issue to get this resolved! ๐`)
return false
}
return true
}
/**
* Parse everything within the current module and store detected exports.
* Todo: Possibly migrate parsers to their own class to save on memory usage?
*/
public parse(node: Node) {
if (!this.shouldParse(node))
return
if (this.isMethod(node, 'link'))
return this.exports.push(...this.parseLink(node))
if (this.isMethod(node, 'export'))
return this.exports.push(...this.parseExport(node))
if (this.isMethod(node, 'exportDefault'))
this.exports.push(...this.parseExportDefault(node))
}
/**
* Parse a Meteor bundle's `module.link()` call.
* {@link ModuleMethod.Link}
*/
protected parseLink(node: ModuleMethod.WithoutArgs<'link'>) {
const [importPath, exports, id] = node.arguments
if (importPath.type !== 'StringLiteral')
throw new ModuleExportsError('Expected string as the first argument in module.link()!', importPath)
// Module.link('./some-path') without any arguments.
// Translates to `import './some-path' - so no exports to be found here. ๐
if (!exports)
return []
if (exports.type !== 'ObjectExpression')
throw new ModuleExportsError('Expected ObjectExpression as the second argument in module.link()!', importPath)
if (id?.type !== 'NumericLiteral')
throw new ModuleExportsError('Expected NumericLiteral as the last argument in module.link()!', importPath)
return formatExports({
packageName: importPath,
expression: exports,
id,
})
}
/**
* Parse a Meteor bundle's `module.export({ ... })` call.
* {@link ModuleMethod.export see type for examples}
*/
protected parseExport(node: ModuleMethod.WithoutArgs<'export'>) {
if (node.arguments[0].type !== 'ObjectExpression')
throw new ModuleExportsError('Unexpected export type!', exports)
return formatExports({
expression: node.arguments[0],
})
}
/**
* Parse a Meteor bundle's `module.exportDefault()` call.
* {@link ModuleMethod.exportDefault see examples in type declaration}
*/
protected parseExportDefault(node: ModuleMethod.WithoutArgs<'exportDefault'>) {
const args = node.arguments
let name = 'default'
if (args[0].type === 'Identifier')
name = args[0].name
else if (args[0].type === 'ConditionalExpression')
name = 'CONDITIONAL_EXPORT_DEFAULT'
else
throw new ModuleExportsError('Unexpected default export value!', args[0])
// todo: test for default exports with `export default { foo: 'bar' }`
return [{ type: 'export-default', name } satisfies ModuleExportData]
}
}
function formatExports({ expression, packageName, id }: { expression: ObjectExpression; packageName?: StringLiteral; id?: NumericLiteral }) {
return expression.properties.map((property) => {
if (property.type === 'SpreadElement')
throw new ModuleExportsError('Unexpected property type!', property)
const result: ModuleExportData = {
name: propParser.getKey(property),
type: 'export',
...id && { id: id.value },
}
if (packageName) {
result.type = 're-export'
result.from = packageName.value
}
if (result.type === 're-export' && property.type === 'ObjectMethod')
result.type = 'global-binding'
if (result.type === 're-export' && property.type === 'ObjectProperty') {
const content = property.value
if (content.type !== 'StringLiteral')
throw new ModuleExportsError('Received unsupported result type in re-export!', property)
if (content.value !== result.name)
result.as = content.value
}
return result
})
}
class ParserError extends MeteorViteError {
constructor(
public originalMessage: string,
public readonly metadata?: {
parseOptions?: ParseOptions
node?: Node
},
) {
super(originalMessage)
}
public async formatLog() {
const { parseOptions, node } = await this.metadata || {}
if (parseOptions?.fileContent) {
this.addLine([
`// File content for: ${this.metadata?.parseOptions?.filePath}`,
'',
...(await parseOptions.fileContent).split(/[\r\n]+/),
])
}
if (node)
this.addLine([inspect(node)])
}
}
class ModuleExportsError extends ParserError {
constructor(
public readonly message: string,
public readonly node: Node,
) {
super(message, { node })
}
}
/**
* Meteor package-level exports.
* {@link https://docs.meteor.com/api/packagejs.html#PackageAPI-export}
*/
export type PackageScopeExports = Record<string, string[]>
export type ModuleList = { [key in string]: ModuleExportData[] }
export interface ModuleExportData {
/**
* "Name" of the object to be exported.
* @example ts
* export const <name> = '...'
*/
name?: string
type: 'export' // Named export (export const fooBar = '...')
| 're-export' // Exporting properties from another module. (export { fooBar } from './somewhere' )
| 'global-binding' // Meteor globals. (`Meteor`, `DDP`, etc) These should likely just be excluded from the vite stubs.
| 'export-default' // Default module export (export default fooBar);
/**
* Internal Meteor ID for a linked Meteor module.
* This isn't really all that useful apart from testing.
*/
id?: number
/**
* The module we're re-exporting from. This only applies to re-exports.
* @example ts
* export { foo } from '<from>'
*/
from?: string
/**
* The value of the "as" keyword when exporting a module.
* @example ts
* export { foo as bar }
*/
as?: string
}
export interface ParsedPackage {
/**
* Meteor Atmosphere package name.
* E.g. ostrio:cookies, accounts-base, ddp
*/
name: string
/**
* List of ES modules included in this package.
*/
modules: ModuleList
/**
* Path to the package's mainModule as defined with `api.mainModule(...)`
* {@link https://docs.meteor.com/api/packagejs.html}
*/
mainModulePath?: string
/**
* Meteor package-level exports.
* {@link https://docs.meteor.com/api/packagejs.html#PackageAPI-export}
*/
packageScopeExports: PackageScopeExports
/**
* Base Atmosphere package import This is usually where we find the full package content, even for packages
* that have multiple entry points.
* E.g. `meteor/ostrio:cookies`, `meteor/meteor`, `meteor/vite:bundler`
*/
packageId: string
}