Socket
Socket
Sign inDemoInstall

@aem-vite/import-rewriter

Package Overview
Dependencies
215
Maintainers
1
Versions
20
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 4.1.3 to 5.0.0

46

CHANGELOG.md

@@ -0,1 +1,47 @@

# [5.0.0](https://github.com/aem-vite/import-rewriter/compare/v4.1.3...v5.0.0) (2022-02-12)
### Code Refactoring
* remove css rewriter ([3c5c49e](https://github.com/aem-vite/import-rewriter/commit/3c5c49e93f29309b5c04f0391602b158d7401d9e))
### Features
* redesign imports handler ([7b1ac3b](https://github.com/aem-vite/import-rewriter/commit/7b1ac3b8438178a67a323f67a618cbcd99809303))
### BREAKING CHANGES
* Complete redesign of the dynamic/native imports handler
The previous implementation was kind of clunky and didn't behave correct in most situations. A new `resourcesPath` configuration exists in the bundles rewriter which enforces a strict contract between the handler and your configuration, removing all assumptions.
Please refer to the below for how you should optimally setup your Vite configuration.
```js
{
base: command === 'build' ? '/etc.clientlibs/<project>/clientlibs/<clientlib>/' : '/',
build: {
rollupOptions: {
output: {
chunkFileNames: '<clientlib>/resources/js/chunks/[name].js`,
entryFileNames: '<clientlib>/resources/js/[name].js`,
},
},
},
plugins: [
bundlesImportRewriter({
publicPath: '/etc.clientlibs/<project>/clientlibs/<clientlib>',
resourcesPath: 'resources/js',
}),
],
}
```
* Vite 2.6.x and greater is now required
To keep up with internal fixes and feature additions Vite 2.6.x or greater is required to support `server.origin` which removes the need for the CSS Rewriter.
## [4.1.3](https://github.com/aem-vite/import-rewriter/compare/v4.1.2...v4.1.3) (2022-01-20)

@@ -2,0 +48,0 @@

50

lib/index.d.ts

@@ -26,9 +26,2 @@ import { Plugin } from 'vite';

keyFormat?: string | false;
/**
* Define whether your HTML Library Manager configuration has the `minify` option enabled.
* This will replace `.js` with `.min.js` to match AEM.
*
* @default false
*/
minification?: boolean;
}

@@ -43,2 +36,9 @@ interface BaseImportRewriterOptions {

publicPath: string;
/**
* The path to where bundles and chunks are stored. This should be the same for both.
*
* @example
* resources/js
*/
resourcesPath: string;
}

@@ -51,28 +51,9 @@ interface BundlesImportRewriterOptions extends BaseImportRewriterOptions {

/**
* Define the main entry path used for your Vite builds.
* Define whether your HTML Library Manager configuration has the `minify` option enabled.
* This will replace `.js` with `.min.js` to match AEM.
*
* The AEM Vite import rewriter plugin will automatically assume the first entry defined is
* the correct file but you can override this for each Vite configuration.
*
* Any path you do define needs to be relative to your configured output directory.
*
* @example
* ```ts
* {
* mainEntryPath: 'core.footer/resources/js/main.js',
* }
* ```
* @default false
*/
mainEntryPath?: string;
minify?: boolean;
}
interface CssImportRewriterOptions extends BaseImportRewriterOptions {
/**
* Base path for static assets. This only needs to be partial so the static path in your CSS
* can be replaced by your `assetsDir` path.
*
* @example
* /src/assets
*/
assetsBasePath: string;
}

@@ -86,9 +67,2 @@ /**

/**
* Identifies all static asset paths and converts them into AEM ClientLib compliant paths.
*
* @param options import rewriter options
*/
declare function cssImportRewriter(options: CssImportRewriterOptions): Plugin;
export { bundlesImportRewriter, cssImportRewriter };
export { bundlesImportRewriter };

@@ -32,4 +32,3 @@ var __create = Object.create;

__export(src_exports, {
bundlesImportRewriter: () => bundlesImportRewriter,
cssImportRewriter: () => cssImportRewriter
bundlesImportRewriter: () => bundlesImportRewriter
});

@@ -48,14 +47,11 @@

var import_path = require("path");
var mainEntryPath;
var entryPaths = /* @__PURE__ */ new Set();
var debug = (0, import_debug.default)("aem-vite-import-rewriter");
var relativePathPattern = /([.]{1,2}\/)+/;
function hasMainEntryPath() {
return mainEntryPath && mainEntryPath.length > 0 || false;
function getEntryPaths() {
return entryPaths;
}
function getMainEntryPath() {
return mainEntryPath;
function setEntryPath(path) {
entryPaths.add(path);
}
function setMainEntryPath(path) {
mainEntryPath = path;
}
function isOutputChunk(assetOrChunk) {

@@ -67,25 +63,38 @@ return typeof assetOrChunk.imports !== void 0;

}
function getCacheKey(path, keyFormat) {
function getCacheKey(entryPath, keyFormat) {
const keyFormatString = keyFormat === void 0 ? "lc-%s-lc" : typeof keyFormat === "string" ? keyFormat : "%s";
return keyFormatString.replace("%s", (0, import_fs.existsSync)(path) ? generateChecksum((0, import_fs.readFileSync)(path).toString()) : "unknown");
const combinedContents = [...entryPaths].map((entry) => {
const path = (0, import_path.join)(entryPath, entry);
return (0, import_fs.existsSync)(path) ? (0, import_fs.readFileSync)(path).toString() : "";
});
return keyFormatString.replace("%s", generateChecksum(combinedContents.join("")));
}
function getAEMImportFilePath(path, options, withCacheChecksum = false, rollupOptions) {
if (mainEntryPath && mainEntryPath === path) {
path = `${path.substring(0, path.indexOf("/"))}.js`;
if (withCacheChecksum && options.caching && options.caching.enabled && rollupOptions !== void 0) {
const entryPath = (0, import_path.join)(rollupOptions.dir, mainEntryPath);
path = path.substring(0, path.length - 3);
path = `${path}.${getCacheKey(entryPath, options.caching.keyFormat)}`;
path = `${path}.${options.caching.minification === true ? "min.js" : "js"}`;
}
function getAemClientLibPath(options, forImport = false, withChecksum = false, rollupOptions) {
let path = options.publicPath;
if (forImport) {
return `${path}/${options.resourcesPath}/`;
}
return path;
if (withChecksum && options.caching && options.caching.enabled && rollupOptions !== void 0) {
const entryPath = rollupOptions.dir;
path = `${path}.${getCacheKey(entryPath, options.caching.keyFormat)}`;
return `${path}${options.minify === true ? ".min" : ""}.js`;
}
return `${path}.js`;
}
function getReplacementPath(path, options, imports) {
const matchedImport = imports.find((imp) => imp.endsWith(path.replace(relativePathPattern, "")));
return matchedImport ? path.replace(new RegExp(`${relativePathPattern.source}${path.replace(relativePathPattern, "")}`), options.publicPath + getAEMImportFilePath(matchedImport, options)) : path;
function getReplacementPath(parentPath, path, options, entryAliases) {
const isEntryPath = entryPaths.has(parentPath);
if (isEntryPath) {
return path.replace(new RegExp(`^${relativePathPattern.source}`), getAemClientLibPath(options, true));
}
return isInputAnEntryAlias(path, entryAliases) ? path.replace(new RegExp(`${relativePathPattern.source}${path.replace(relativePathPattern, "")}`), getAemClientLibPath(options)) : path;
}
function isInputAnEntryAlias(input, entryAliases) {
var _a;
const entryAliasesExpr = new RegExp(`^[./]+(${Object.keys(entryAliases).join("|")})\\.js$`);
return ((_a = input.match(entryAliasesExpr)) == null ? void 0 : _a[0]) ? true : false;
}
// src/bundles.ts
function bundlesImportRewriter(options) {
const entryAliases = {};
return {

@@ -95,2 +104,16 @@ apply: "build",

name: "aem-vite:import-rewriter",
configResolved(config) {
const inputs = config.build.rollupOptions.input;
if (!inputs || typeof inputs !== "object" || Array.isArray(inputs)) {
throw new Error("Missing valid input aliases which are required to map to an AEM ClientLib path, see https://www.aemvite.dev/guide/front-end/vite/#source-structure for more information.");
}
for (const [key, value] of Object.entries(inputs)) {
if (/(ts|js)x?$/.test(value)) {
entryAliases[key] = value;
}
}
if (Object.keys(entryAliases).length > 1) {
throw new Error("Invalid number of JavaScript inputs provided. Only a single input is currently supported which is a limitation of AEM ClientLibs. It is recommended to create a second ClientLib and Vite config if you need to meet this need.");
}
},
async renderChunk(source, chunk, rollupOptions) {

@@ -103,5 +126,5 @@ if (rollupOptions.format !== "es") {

}
if (options.mainEntryPath || chunk.isEntry && chunk.facadeModuleId && /(ts|js)x?$/.test(chunk.facadeModuleId) && !hasMainEntryPath()) {
debug("setting main entry path: %s\n", options.mainEntryPath || chunk.fileName);
setMainEntryPath(options.mainEntryPath || chunk.fileName);
if (chunk.isEntry && chunk.facadeModuleId && /(ts|js)x?$/.test(chunk.facadeModuleId)) {
debug("setting new entry path: %s\n", chunk.fileName);
setEntryPath(chunk.fileName);
}

@@ -123,6 +146,7 @@ await import_es_module_lexer.init;

if (dynamicIndex === -1 && importPath && relativePathPattern.test(importPath)) {
const replacementPath = getReplacementPath(chunk.fileName, importPath, options, entryAliases);
debug("render chunk (dynamic import) chunk: %s", chunk.fileName);
debug("render chunk (dynamic import) import: %s", importPath);
debug("render chunk (dynamic import) replacement: %s\n", getReplacementPath(importPath, options, chunk.imports));
str().overwrite(start, end, getReplacementPath(importPath, options, chunk.imports));
debug("render chunk (dynamic import) replacement: %s\n", replacementPath);
str().overwrite(start, end, replacementPath);
}

@@ -139,4 +163,3 @@ }

async writeBundle(rollupOptions, bundles) {
const mainEntryPath2 = getMainEntryPath();
const mainEntryAEMPath = getAEMImportFilePath(mainEntryPath2, options);
const aemClientLibPath = getAemClientLibPath(options);
for (const [fileName, chunk] of Object.entries(bundles)) {

@@ -146,6 +169,2 @@ if (!isOutputChunk(chunk) || !chunk.code) {

}
let aemImportPath = mainEntryAEMPath;
if (options.caching && options.caching.enabled) {
aemImportPath = getAEMImportFilePath(mainEntryPath2, options, true, rollupOptions);
}
const source = chunk.code;

@@ -166,17 +185,28 @@ await import_es_module_lexer.init;

const { e: end, d: dynamicIndex, n: importPath, s: start } = imports[index];
debug("write bundle (dynamic import) chunk: %s", chunk.fileName);
debug("write bundle (dynamic import) import: %s\n", importPath);
if (dynamicIndex === -1 && importPath && importPath.substring(importPath.lastIndexOf("/") + 1) === mainEntryAEMPath) {
str().overwrite(start, end, importPath.substring(0, importPath.lastIndexOf("/") + 1) + aemImportPath);
if (dynamicIndex === -1 && importPath && relativePathPattern.test(importPath)) {
const replacementPath = getReplacementPath(chunk.fileName, importPath, options, entryAliases);
debug("write bundle (native import) chunk: %s", chunk.fileName);
debug("write bundle (native import) import: %s\n", importPath);
str().overwrite(start, end, replacementPath);
}
if (dynamicIndex > -1) {
debug("write bundle (dynamic import) chunk: %s", chunk.fileName);
debug("write bundle (dynamic import) import: %s\n", importPath);
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));
str().overwrite(dynamicIndex + 8, dynamicEnd - 2, getReplacementPath(chunk.fileName, original, options, entryAliases));
}
}
}
let aemImportPath = aemClientLibPath;
let newSource = s && s.toString() || source;
newSource = newSource.replace(new RegExp(mainEntryPath2, "g"), aemImportPath);
if (options.caching && options.caching.enabled) {
aemImportPath = getAemClientLibPath(options, false, true, rollupOptions);
}
newSource = newSource.replace(new RegExp(aemClientLibPath, "g"), aemImportPath);
const relativeClientLibPath = aemImportPath.substring(aemImportPath.lastIndexOf("/") + 1);
getEntryPaths().forEach((path) => {
newSource = newSource.replace(new RegExp(path, "g"), relativeClientLibPath);
});
(0, import_fs2.writeFileSync)((0, import_path2.join)(rollupOptions.dir, fileName), newSource);

@@ -187,28 +217,7 @@ }

}
// src/css.ts
var import_rollup_pluginutils = require("rollup-pluginutils");
function cssImportRewriter(options) {
const filter = (0, import_rollup_pluginutils.createFilter)(/\.(scss|sass|less|styl|stylus|css)$/i, []);
return {
enforce: "post",
name: "aem-vite:import-rewriter:css",
transform(code, id) {
if (filter(id)) {
code = code.replace(new RegExp(options.assetsBasePath, "g"), options.publicPath);
return {
code,
id,
map: { mappings: "" }
};
}
}
};
}
module.exports = __toCommonJS(src_exports);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
bundlesImportRewriter,
cssImportRewriter
bundlesImportRewriter
});
//# sourceMappingURL=index.js.map

@@ -14,3 +14,3 @@ {

},
"version": "4.1.3",
"version": "5.0.0",
"engines": {

@@ -68,3 +68,4 @@ "node": ">= 12"

"magic-string": "^0.25.7",
"rollup-pluginutils": "^2.8.2"
"rollup-pluginutils": "^2.8.2",
"vite": "^2.8.0"
},

@@ -88,7 +89,6 @@ "devDependencies": {

"tsup": "^5.11.9",
"typescript": "^4.5.4",
"vite": "*"
"typescript": "^4.5.4"
},
"peerDependencies": {
"vite": ">2.0.0-0"
"vite": ">2.6.0"
},

@@ -95,0 +95,0 @@ "optionalDependencies": {

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc