-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathutils.ts
More file actions
722 lines (617 loc) · 21.5 KB
/
Copy pathutils.ts
File metadata and controls
722 lines (617 loc) · 21.5 KB
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
import ts from 'typescript'
import path from 'path'
import fs from 'fs'
import { ParsedFilePkg, Transformer } from './types'
const specFileOrFolderRgx =
/(__mocks__|__tests__)|(\.(spec|test)\.(tsx|ts|js|jsx)$)/
export const INTERNAL_CONFIG_KEY = '__i18nConfig'
export const clientLine = ['"use client"', "'use client'"]
export const defaultLoader =
'(l, n) => import(`@next-translate-root/locales/${l}/${n}`).then(m => m.default)'
export function getDefaultAppJs(
existLocalesFolder: boolean,
configFileName: string
) {
return `
import * as React from 'react'
import ${INTERNAL_CONFIG_KEY} from '@next-translate-root/${configFileName}'
import appWithI18n from 'next-translate/appWithI18n'
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default appWithI18n(MyApp, {
...${INTERNAL_CONFIG_KEY},
skipInitialProps: true,
isLoader: true,
${addLoadLocalesFrom(existLocalesFolder)}
})
`
}
export function addLoadLocalesFrom(existLocalesFolder: boolean) {
const defaultFn = existLocalesFolder
? defaultLoader
: `() => Promise.resolve({})`
return `loadLocaleFrom: ${INTERNAL_CONFIG_KEY} && ${INTERNAL_CONFIG_KEY}.loadLocaleFrom || (${defaultFn}),`
}
/**
* @param basePath - Path to the root of the target project
* @param cutDependencies - Whether to not include imports and the standard library
* @returns Compiler options
*/
export function getTsCompilerOptions(
basePath: string,
cutDependencies = false
): ts.CompilerOptions {
let options: ts.CompilerOptions
const configPath = ts.findConfigFile(
basePath,
ts.sys.fileExists,
'tsconfig.json'
)
if (!configPath) {
// Configuration file not found - most likely it is JS
options = { allowJs: true }
} else {
const readConfigFileResult = ts.readConfigFile(configPath, ts.sys.readFile)
const jsonConfig = readConfigFileResult.config
const convertResult = ts.convertCompilerOptionsFromJson(
jsonConfig.compilerOptions,
basePath
)
options = convertResult.options
}
if (cutDependencies) {
// This allows us to ignore all files except those that are added explicitly.
// Including imports and standard library.
// This was done in order to speed up file analysis
options = { ...options, types: [], noResolve: true, noLib: true }
}
return options
}
/**
* @param program - File container [program]{@link ts.Program}
* @param filename - The name of the file inside the program
* @returns A file package that allows us to analyze and modify the code inside
*/
export function getFilePkg(program: ts.Program, filename: string) {
const checker = program.getTypeChecker()
const sourceFile = program.getSourceFile(filename)!
const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed })
const fileSymbol = checker.getSymbolAtLocation(sourceFile)
let filePkg: ParsedFilePkg
function transform(transformer: Transformer) {
const { sourceFile } = filePkg
const transformationResult = ts.transform(sourceFile, [
(context) => (sourceFile) => transformer(sourceFile, context),
])
filePkg.sourceFile = transformationResult.transformed[0]
filePkg.fileSymbol = checker.getSymbolAtLocation(filePkg.sourceFile)
}
function getCode() {
const { sourceFile } = filePkg
return printer.printNode(ts.EmitHint.Unspecified, sourceFile, sourceFile)
}
filePkg = { program, checker, sourceFile, fileSymbol, transform, getCode }
return filePkg
}
/**
* @param basePath - Path to the root of the target project
* @param filename - Path to JS/TS file
* @returns File package for further manipulations
*/
export function parseFile(basePath: string, filename: string): ParsedFilePkg {
/**
* Parameter `filename` is the filepath relative to `basePath`, but the Program
* created by `ts.createProgram` will be relative to `process.cwd()`.
*
* We have to modify `filename` and make sure it is relative to `
* process.cwd`, otherwise `program.getSourceFile` in `getFilePkg` will return undefined
*/
const cwd = process.cwd()
const filenameRelativeCWD = path.relative(cwd, path.join(basePath, filename))
const options = getTsCompilerOptions(basePath, true)
const program = ts.createProgram([filenameRelativeCWD], options)
return getFilePkg(program, filenameRelativeCWD)
}
/**
* Does the same as "parseFile", but in a fake environment
* and for code directly (no file on disk, of course)
*
* @param format - Pseudo file extension
* @param code - Contents of the pseudo file
* @returns File package for further manipulations
*/
export function parseCode(format: string, code: string): ParsedFilePkg {
const options = getTsCompilerOptions('/', true)
const host = ts.createCompilerHost(options)
const filename = `source.${format}`
host.getSourceFile = (fileName: string) => {
return ts.createSourceFile(fileName, code, ts.ScriptTarget.Latest)
}
const program = ts.createProgram([filename], options, host)
return getFilePkg(program, filename)
}
/**
* @param filePkg - File package
* @param node - The node for which we will get the symbol
* @returns Entity for more detailed analysis by the compiler
*/
export function getSymbol(filePkg: ParsedFilePkg, node: ts.Node) {
if ((node as any).symbol) {
return (node as any).symbol
}
const location = ts.isVariableDeclaration(node) ? node.name : node
return filePkg.checker.getSymbolAtLocation(location)
}
/**
* @param filePkg - File package
* @param moduleName - The name of the module about which we will receive information
* @returns If a module with this name was imported, then the map "export name: local name"
*/
export function getImportedNames(filePkg: ParsedFilePkg, moduleName: string) {
const importClause = filePkg.sourceFile.forEachChild((node) => {
if (ts.isImportDeclaration(node)) {
if (node.moduleSpecifier.getText().slice(1, -1) === moduleName) {
return node.importClause
}
}
return undefined
})
if (importClause) {
const exportedNamesToImported = new Map<string, ts.Identifier>()
// Default import
if (importClause.name) {
exportedNamesToImported.set('default', importClause.name)
}
// Named imports
if (importClause.namedBindings) {
importClause.namedBindings.forEachChild((node) => {
if (ts.isImportSpecifier(node)) {
if (node.propertyName) {
// Alias is used
exportedNamesToImported.set(node.propertyName.getText(), node.name)
} else {
exportedNamesToImported.set(node.name.getText(), node.name)
}
}
})
}
return exportedNamesToImported
}
// The requested module was not imported in the file
return undefined
}
/**
* @param filePkg - File package
* @param parenthesizedExpression - Parenthesis expression
* @returns Content inside parenthesis
*/
export function resolveParenthesis(
filePkg: ParsedFilePkg,
parenthesizedExpression: ts.ParenthesizedExpression
): ts.Expression {
const content = parenthesizedExpression.expression
if (ts.isParenthesizedExpression(content)) {
return resolveParenthesis(filePkg, content)
} else {
return content
}
}
/**
* @param filePkg - File package
* @param identifier - Identifier whose declaration will be searched for
* @returns Deepest declaration, or last id found
*/
export function resolveIdentifier(
filePkg: ParsedFilePkg,
identifier: ts.Identifier
): ts.Declaration | ts.Identifier {
const identifierSymbol = getSymbol(filePkg, identifier)
if (identifierSymbol && Array.isArray(identifierSymbol.declarations)) {
const identifierDeclaration = identifierSymbol.declarations[0]
if (ts.isVariableDeclaration(identifierDeclaration)) {
let initializer = identifierDeclaration.initializer
if (initializer && ts.isParenthesizedExpression(initializer)) {
initializer = resolveParenthesis(filePkg, initializer)
}
if (initializer && ts.isIdentifier(initializer)) {
return resolveIdentifier(filePkg, initializer)
}
}
return identifierDeclaration
}
// Return the last found identifier if we can't find its definition
return identifier
}
export function getNamedExport(
filePkg: ParsedFilePkg,
name: string,
resolveExport = true
) {
const { checker, fileSymbol } = filePkg
let exportContent: ts.Expression | ts.Declaration | undefined
if (fileSymbol) {
const exportSymbol = checker.tryGetMemberInModuleExports(name, fileSymbol)
if (exportSymbol && Array.isArray(exportSymbol.declarations)) {
const exportDeclaration = exportSymbol.declarations[0]
if (resolveExport && ts.isExportAssignment(exportDeclaration)) {
exportContent = exportDeclaration.expression
if (ts.isParenthesizedExpression(exportContent)) {
exportContent = resolveParenthesis(filePkg, exportContent)
}
if (ts.isIdentifier(exportContent)) {
exportContent = resolveIdentifier(filePkg, exportContent)
}
} else {
exportContent = exportDeclaration
}
}
}
return exportContent
}
// Alias for `getNamedExport('default')`
export function getDefaultExport(filePkg: ParsedFilePkg, resolveExport = true) {
return getNamedExport(filePkg, 'default', resolveExport)
}
export function hasExportName(filePkg: ParsedFilePkg, name: string) {
if (Boolean(getNamedExport(filePkg, name, false))) return true
// Fallback for re-exports (export * from '...')
// When noResolve is true, the checker may not be able to resolve these
const isDataFetchingMethod = [
'getStaticProps',
'getStaticPaths',
'getServerSideProps',
'getInitialProps',
].includes(name)
if (!isDataFetchingMethod) return false
return filePkg.sourceFile.statements.some((node) => {
return (
ts.isExportDeclaration(node) &&
!node.isTypeOnly &&
!node.exportClause &&
node.moduleSpecifier !== undefined
)
})
}
export function getStaticName(
filePkg: ParsedFilePkg,
target: ts.Declaration | ts.Expression,
name: string
) {
const symbol = getSymbol(filePkg, target)
if (symbol) {
return filePkg.checker.tryGetMemberInModuleExports(name, symbol)
}
return undefined
}
export function hasStaticName(
filePkg: ParsedFilePkg,
target: ts.Declaration | ts.Expression,
name: string
) {
return Boolean(getStaticName(filePkg, target, name))
}
export function isPageToIgnore(pageFilePath: string) {
const fileName = pageFilePath.substring(pageFilePath.lastIndexOf('/') + 1)
return (
pageFilePath.startsWith('/api/') ||
pageFilePath.startsWith('/_document.') ||
pageFilePath.startsWith('/middleware.') ||
fileName.startsWith('_middleware.') ||
specFileOrFolderRgx.test(pageFilePath)
)
}
export function hasHOC(filePkg: ParsedFilePkg) {
let defaultExport = getDefaultExport(filePkg)
if (
!defaultExport ||
hasExportName(filePkg, 'getStaticProps') ||
hasExportName(filePkg, 'getServerSideProps') ||
hasExportName(filePkg, 'getStaticPaths')
) {
return false
}
if (ts.isVariableDeclaration(defaultExport) && defaultExport.initializer) {
defaultExport = defaultExport.initializer
if (ts.isParenthesizedExpression(defaultExport)) {
defaultExport = resolveParenthesis(filePkg, defaultExport)
}
if (ts.isIdentifier(defaultExport)) {
defaultExport = resolveIdentifier(filePkg, defaultExport)
}
// If is exported normally (variable), is not a HOC
if (!ts.isCallExpression(defaultExport)) {
return false
}
}
// If is exported normally (function or class), is not a HOC
if (
ts.isFunctionDeclaration(defaultExport) ||
ts.isClassDeclaration(defaultExport)
) {
return false
}
const importedNames = getImportedNames(
filePkg,
'next-translate/withTranslation'
)
const withTranslationId = importedNames?.get('default')
// If the export is the result of a function call (except withTranslation),
// is a HOC
function isCallExpressionWithHOC(callExpression: ts.CallExpression): boolean {
const callable = callExpression.expression
const expressionsToVisit = [callable, ...callExpression.arguments]
// Recursively check the callable part and its arguments
for (const expression of expressionsToVisit) {
if (ts.isCallExpression(expression)) {
return isCallExpressionWithHOC(expression)
}
// detect: export default ``HOCed``(...)
if (ts.isIdentifier(expression)) {
const resolved = resolveIdentifier(filePkg, expression)
// detect: const ``HOCed = withHOC(Page)``; export default HOCed(...)
if (ts.isVariableDeclaration(resolved)) {
let initializer = resolved.initializer
if (initializer && ts.isParenthesizedExpression(initializer)) {
initializer = resolveParenthesis(filePkg, initializer)
}
if (initializer && ts.isCallExpression(initializer)) {
return isCallExpressionWithHOC(initializer)
}
}
// detect: import ``withHOC`` from '...'
if (ts.isImportClause(resolved)) {
if (resolved.name?.getText() !== withTranslationId?.getText()) {
return true
}
}
}
}
return false
}
if (ts.isCallExpression(defaultExport)) {
if (withTranslationId) {
return isCallExpressionWithHOC(defaultExport)
} else {
return true
}
}
return false
}
export function isNotExportModifier(modifier: ts.ModifierLike) {
const exportModifiers: ts.SyntaxKind[] = [
ts.SyntaxKind.DefaultKeyword,
ts.SyntaxKind.ExportKeyword,
]
return !exportModifiers.includes(modifier.kind)
}
/**
* Removes the export modifiers from the entity and also
* makes it available locally by the given name
*
* @param filePkg - File package
* @param exportName - The name under which the entity was exported from the file
* @param defaultLocalName - The name that will be applied if the entity *does not* have its own
* @returns The name by which the entity can now be retrieved. Empty string if entity not found
*/
export function interceptExport(
filePkg: ParsedFilePkg,
exportName: string,
defaultLocalName: string
) {
const exportContent = getNamedExport(filePkg, exportName, false)
// If the entity is already available by some name inside the module,
// then we use it to avoid problems due to renames
let finalLocalName = ''
// Extra import statement if we need to redirect `export { ... } from '...'`
let extraImport: ts.ImportDeclaration | undefined
// We do nothing and return an empty string if there is no such export name
if (!exportContent) return finalLocalName
filePkg.transform((sourceFile, context) => {
function visitor(node: ts.Node): ts.Node {
// `export class A`
if (ts.isClassDeclaration(node) && node === exportContent) {
if (node.name) finalLocalName = node.name.getText()
// Turning the class export into a regular declaration
return ts.factory.updateClassDeclaration(
node,
node.modifiers?.filter(isNotExportModifier),
node.name ?? ts.factory.createIdentifier(defaultLocalName),
node.typeParameters,
node.heritageClauses,
node.members
)
}
// `export function fun123`
if (ts.isFunctionDeclaration(node) && node === exportContent) {
if (node.name) finalLocalName = node.name.getText()
// Turning the function export into a regular declaration
return ts.factory.updateFunctionDeclaration(
node,
node.modifiers?.filter(isNotExportModifier),
node.asteriskToken,
node.name ?? ts.factory.createIdentifier(defaultLocalName),
node.typeParameters,
node.parameters,
node.type,
node.body
)
}
// `export const a = 1, b = 2`
if (
ts.isVariableStatement(node) &&
ts.isVariableDeclaration(exportContent!) &&
node.declarationList.declarations.includes(exportContent)
) {
finalLocalName = exportContent.name.getText()
// `export const a = 1` -> `const a = 1`
return ts.factory.updateVariableStatement(
node,
node.modifiers?.filter(isNotExportModifier),
node.declarationList
)
}
// `export { ... } [from '...']`
if (
ts.isExportDeclaration(node) &&
ts.isExportSpecifier(exportContent!) &&
node.exportClause &&
ts.isNamedExports(node.exportClause)
) {
// List of names exported from the module, except for the target
const filteredSpecifiers = node.exportClause.elements.filter(
(specifier) => specifier !== exportContent
)
if (node.moduleSpecifier) {
// `export { ... } from '...'`
finalLocalName = defaultLocalName
extraImport = ts.factory.createImportDeclaration(
undefined,
ts.factory.createImportClause(
node.isTypeOnly,
undefined,
ts.factory.createNamedImports([
ts.factory.createImportSpecifier(
exportContent.isTypeOnly,
exportContent.propertyName ?? exportContent.name,
ts.factory.createIdentifier(defaultLocalName)
),
])
),
node.moduleSpecifier
)
} else {
// `export { ... }`
const localId = exportContent.propertyName ?? exportContent.name
finalLocalName = localId.getText()
}
// Remove target export specifier
return ts.factory.updateExportDeclaration(
node,
node.modifiers,
node.isTypeOnly,
ts.factory.updateNamedExports(node.exportClause, filteredSpecifiers),
node.moduleSpecifier,
node.assertClause
)
}
// `export default 123`
if (ts.isExportAssignment(node) && node === exportContent) {
finalLocalName = defaultLocalName
// If the exported expression can be placed in a variable, then we do so.
// const {finalLocalName} = {exportContent}
return ts.factory.createVariableStatement(
undefined,
ts.factory.createVariableDeclarationList(
[
ts.factory.createVariableDeclaration(
defaultLocalName,
undefined,
undefined,
node.expression
),
],
ts.NodeFlags.Const
)
)
}
return ts.visitEachChild(node, visitor, context)
}
return ts.visitEachChild(sourceFile, visitor, context)
})
if (extraImport) {
filePkg.transform((sourceFile) => {
return ts.factory.updateSourceFile(sourceFile, [
extraImport!,
...sourceFile.statements,
])
})
}
return finalLocalName
}
export function removeCommentsFromCode(code: string) {
return code.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '')
}
export function calculatePageDir(
name: 'pages' | 'app',
pagesInDir: string | undefined,
dir: string
) {
if (pagesInDir) return pagesInDir.replace(new RegExp('(app|pages)$'), name)
const dirs = [
name,
`src/${name}`,
// https://github.com/blitz-js/blitz/blob/canary/nextjs/packages/next/build/utils.ts#L54-L59
`app/${name}`,
`integrations/${name}`,
] as const
for (const possiblePageDir of dirs) {
if (fs.existsSync(path.join(dir, possiblePageDir))) {
return path.join(possiblePageDir)
}
}
return name
}
export function existPages(dir: string, pages: string | undefined) {
return pages && fs.existsSync(path.join(dir, pages))
}
/**
* Checks if the project has a folder with locales/{lang}/{namespace}.json
* @param dir: string - Path to the root of the target project
* @returns boolean - Whether the project has a folder with locales/{lang}/{namespace}.json
*/
export function existLocalesFolderWithNamespaces(dir: string) {
const existLocalesFolder = fs.existsSync(path.join(dir, 'locales'))
if (!existLocalesFolder) return false
const langFolder = fs.readdirSync(path.join(dir, 'locales')).find((file) => {
const currentLangFolder = path.join(dir, 'locales', file)
return (
fs.existsSync(currentLangFolder) &&
fs.lstatSync(currentLangFolder).isDirectory()
)
})
if (!langFolder) return false
const existNamespaceFile = fs
.readdirSync(path.join(dir, 'locales', langFolder))
.some((file) => {
const namespaceFile = path.join(dir, 'locales', langFolder, file)
return (
fs.existsSync(namespaceFile) &&
!fs.lstatSync(namespaceFile).isDirectory()
)
})
return existNamespaceFile
}
export function isInsideAppDir(
path: string,
appFolder: string,
pagesFolder: string
) {
const appIndex = path.indexOf(appFolder)
const pagesIndex = path.indexOf(pagesFolder)
if (appIndex === -1) return false
if (appIndex > -1 && pagesIndex === -1) return true
return appIndex < pagesIndex
}
const CONFIG_FILE_NAMES = ['i18n.json', 'i18n.js', 'i18n.mjs', 'i18n.cjs']
export function getConfigFileName(basePath: string) {
return CONFIG_FILE_NAMES.find((fileName) =>
fs.existsSync(path.join(basePath, fileName))
)
}
const REGEX_PREFIX = '__REGEX__'
export function regexToString(regex: RegExp | string) {
if (typeof regex === 'string') {
return regex
}
return `${REGEX_PREFIX}${regex.source}`
}
export function stringToRegex(str: string | RegExp) {
if (typeof str !== 'string') {
return str
}
if (!str.startsWith(REGEX_PREFIX)) {
return str
}
return new RegExp(str.replace(REGEX_PREFIX, ''))
}