vite-plugin-esi
Version:
Vite plugin to resolve ESI with [nodesi](https://www.npmjs.com/package/nodesi).
72 lines (67 loc) • 1.97 kB
JavaScript
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/transform.ts
import ESI from "nodesi";
// src/errors.ts
var TagsNotFoundError = class extends Error {
constructor(message) {
super(message);
this.name = "TagsNotFoundError";
}
};
// src/transform.ts
function transformHtml(html, options) {
const regex = new RegExp('<!--*\\s*vite-plugin-esi\\s(name="(?<name>[a-zA-Z0-9]+)").*->', "g");
return html.replace(regex, (_match, _, __, ___, ____, groups) => {
const tags = options[groups.name];
if (!tags) {
throw new TagsNotFoundError(`no tags found for ${groups.name}`);
}
return tags.map((tag) => {
const { src, type = "include", onError = "abort" } = tag;
return `<esi:${type} src="${src}" onerror="${onError}" />`;
}).join("\n");
});
}
function resolveESI(html, options) {
return __async(this, null, function* () {
const esi = new ESI(options == null ? void 0 : options.nodeEsi);
const resolvedHtml = yield esi.process(html, { headers: options == null ? void 0 : options.headers });
return resolvedHtml;
});
}
// src/index.ts
function esiPlugin(options) {
var _a;
const shouldResolveESI = (_a = options.resolveESI) != null ? _a : true;
return {
name: "vite-plugin-esi",
transformIndexHtml(inputHtml) {
const html = transformHtml(inputHtml, options.esi);
if (shouldResolveESI) {
return resolveESI(html);
}
}
};
}
export {
esiPlugin as default
};