Skip to content

Commit

Permalink
fix: resolve import paths with caching enabled
Browse files Browse the repository at this point in the history
Some paths did not receive the correct path replacements with caching enabled
  • Loading branch information
cshawaus committed Jan 19, 2022
1 parent 58b31bc commit f5c2a35
Show file tree
Hide file tree
Showing 4 changed files with 82 additions and 45 deletions.
2 changes: 2 additions & 0 deletions package.json
Expand Up @@ -61,6 +61,7 @@
}
},
"dependencies": {
"debug": "^4.3.3",
"es-module-lexer": "^0.9.3",
"magic-string": "^0.25.7",
"rollup-pluginutils": "^2.8.2"
Expand All @@ -70,6 +71,7 @@
"@commitlint/config-conventional": "^16.0.0",
"@semantic-release/changelog": "^5.0.1",
"@semantic-release/git": "^9.0.1",
"@types/debug": "^4.1.7",
"@types/node": "^12.20.39",
"@typescript-eslint/eslint-plugin": "^5.8.1",
"@typescript-eslint/parser": "^5.8.1",
Expand Down
101 changes: 57 additions & 44 deletions src/bundles.ts
Expand Up @@ -10,6 +10,7 @@ import {
getReplacementPath,
hasMainEntryPath,
isOutputChunk,
logger,
relativePathPattern,
setMainEntryPath,
} from './helpers'
Expand Down Expand Up @@ -46,6 +47,8 @@ export function bundlesImportRewriter(options: BundlesImportRewriterOptions): Pl
options.mainEntryPath ||
(chunk.isEntry && chunk.facadeModuleId && /(ts|js)x?$/.test(chunk.facadeModuleId) && !hasMainEntryPath())
) {
logger('setting main entry path', options.mainEntryPath || chunk.fileName)

setMainEntryPath(options.mainEntryPath || chunk.fileName)
}

Expand All @@ -70,6 +73,8 @@ export function bundlesImportRewriter(options: BundlesImportRewriterOptions): Pl
const { e: end, d: dynamicIndex, n: importPath, s: start } = imports[index]

if (dynamicIndex === -1 && importPath && relativePathPattern.test(importPath)) {
logger('render chunk (dynamic import)', importPath, getReplacementPath(importPath, options, chunk.imports))

str().overwrite(start, end, getReplacementPath(importPath, options, chunk.imports))
}
}
Expand All @@ -86,6 +91,7 @@ export function bundlesImportRewriter(options: BundlesImportRewriterOptions): Pl

async writeBundle(rollupOptions, bundles) {
const mainEntryPath = getMainEntryPath()
const mainEntryAEMPath = getAEMImportFilePath(mainEntryPath, options)

for (const [fileName, chunk] of Object.entries(bundles)) {
if (!isOutputChunk(chunk) || !chunk.code) {
Expand All @@ -94,57 +100,64 @@ export function bundlesImportRewriter(options: BundlesImportRewriterOptions): Pl

const source = chunk.code

if (mainEntryPath === fileName && options.caching && options.caching.enabled) {
const mainEntryAEMPath = getAEMImportFilePath(mainEntryPath, options)

const mainEntryAEMPathWithHash = getAEMImportFilePath(
mainEntryPath,
options,
true,
rollupOptions as NormalizedOutputOptions,
)

writeFileSync(
join(rollupOptions.dir as string, fileName),
source.replace(mainEntryAEMPath, mainEntryAEMPathWithHash),
)
} else {
await init

let imports: ReadonlyArray<ImportSpecifier> = []
try {
imports = parseImports(source)[0]
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
this.error(e, e.idx)
}

if (!imports.length) {
continue
}
await init

let s!: MagicString
const str = () => s || (s = new MagicString(source))
let imports: ReadonlyArray<ImportSpecifier> = []
try {
imports = parseImports(source)[0]
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
this.error(e, e.idx)
}

for (let index = 0; index < imports.length; index++) {
const { e: end, d: dynamicIndex } = imports[index]
if (!imports.length) {
continue
}

if (dynamicIndex > -1) {
const dynamicEnd = source.indexOf(')', end) + 1
const original = source.slice(dynamicIndex + 8, dynamicEnd - 2)
let s!: MagicString
const str = () => s || (s = new MagicString(source))

for (let index = 0; index < imports.length; index++) {
const { e: end, d: dynamicIndex, n: importPath, s: start } = imports[index]

logger('write bundle (dynamic import)', importPath)

// Native imports
if (
dynamicIndex === -1 &&
importPath &&
importPath.substring(importPath.lastIndexOf('/') + 1) === mainEntryAEMPath
) {
const mainEntryAEMPathWithHash = getAEMImportFilePath(
mainEntryPath,
options,
true,
rollupOptions as NormalizedOutputOptions,
)

str().overwrite(
start,
end,
importPath.substring(0, importPath.lastIndexOf('/') + 1) + mainEntryAEMPathWithHash,
)
}

if (!original.startsWith('/')) {
str().overwrite(
dynamicIndex + 8,
dynamicEnd - 2,
getReplacementPath(original, options, chunk.dynamicImports),
)
}
// Dynamic imports
if (dynamicIndex > -1) {
const dynamicEnd = source.indexOf(')', end) + 1
const original = source.slice(dynamicIndex + 8, dynamicEnd - 2)

if (!original.startsWith('/')) {
str().overwrite(
dynamicIndex + 8,
dynamicEnd - 2,
getReplacementPath(original, options, chunk.dynamicImports),
)
}
}

writeFileSync(join(rollupOptions.dir as string, fileName), (s && s.toString()) || source)
}

writeFileSync(join(rollupOptions.dir as string, fileName), (s && s.toString()) || source)
}
},
}
Expand Down
10 changes: 10 additions & 0 deletions src/helpers.ts
@@ -1,15 +1,25 @@
import { createHash } from 'crypto'
import _debug from 'debug'
import { existsSync, readFileSync } from 'fs'
import { join } from 'path'

import type { NormalizedOutputOptions, OutputAsset, OutputChunk } from 'rollup'

import type { AEMLongCacheConfiguration, BundlesImportRewriterOptions } from './types'

const debug = _debug('aem-vite-import-rewriter')

let mainEntryPath!: string

export const relativePathPattern = /([.]{1,2}\/)+/

/**
* Send debugging information onto the local debug instance.
*/
export function logger(...args: any[]) {
debug(args)
}

/**
* Check if the main entry file path has been set.
*/
Expand Down
14 changes: 13 additions & 1 deletion yarn.lock
Expand Up @@ -594,6 +594,13 @@
resolved "https://registry.yarnpkg.com/@tsconfig/node16/-/node16-1.0.2.tgz#423c77877d0569db20e1fc80885ac4118314010e"
integrity sha512-eZxlbI8GZscaGS7kkc/trHTT5xgrjH3/1n2JDwusC9iahPKWMRvRjJSAN5mCXviuTGQ/lHnhvv8Q1YTpnfz9gA==

"@types/debug@^4.1.7":
version "4.1.7"
resolved "https://registry.yarnpkg.com/@types/debug/-/debug-4.1.7.tgz#7cc0ea761509124709b8b2d1090d8f6c17aadb82"
integrity sha512-9AonUzyTjXXhEOa0DnqpzZi6VHlqKMswga9EXjpXnnqxwLtdvPPtlO8evrI5D9S6asFRCQ6v+wpiUKbw+vKqyg==
dependencies:
"@types/ms" "*"

"@types/json-schema@^7.0.9":
version "7.0.9"
resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.9.tgz#97edc9037ea0c38585320b28964dde3b39e4660d"
Expand All @@ -604,6 +611,11 @@
resolved "https://registry.yarnpkg.com/@types/minimist/-/minimist-1.2.1.tgz#283f669ff76d7b8260df8ab7a4262cc83d988256"
integrity sha512-fZQQafSREFyuZcdWFAExYjBiCL7AUCdgsk80iO0q4yihYYdcIiH28CcuPTGFgLOCC8RlW49GSQxdHwZP+I7CNg==

"@types/ms@*":
version "0.7.31"
resolved "https://registry.yarnpkg.com/@types/ms/-/ms-0.7.31.tgz#31b7ca6407128a3d2bbc27fe2d21b345397f6197"
integrity sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA==

"@types/node@^12.20.39":
version "12.20.39"
resolved "https://registry.yarnpkg.com/@types/node/-/node-12.20.39.tgz#ef3cb119eaba80e9f1012c78b9384a7489a18bf6"
Expand Down Expand Up @@ -1352,7 +1364,7 @@ debug@4, debug@^4.0.0, debug@^4.1.0, debug@^4.1.1, debug@^4.3.1:
dependencies:
ms "2.1.2"

debug@^4.3.2:
debug@^4.3.2, debug@^4.3.3:
version "4.3.3"
resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.3.tgz#04266e0b70a98d4462e6e288e38259213332b664"
integrity sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==
Expand Down

0 comments on commit f5c2a35

Please sign in to comment.