next-with-linaria
Version:
Linaria support for Next.js App Router
136 lines • 6.01 kB
JavaScript
;
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_zlib_1 = __importDefault(require("node:zlib"));
const transform_1 = require("@wyw-in-js/transform");
const path_1 = __importDefault(require("path"));
const fast_check_1 = require("../utils/fast-check");
const insert_import_1 = require("../utils/insert-import");
const source_map_1 = require("../utils/source-map");
const consts_1 = require("./consts");
const cache = new transform_1.TransformCacheCollection();
const resolvers = {};
const stripQueryAndHash = (request) => {
const queryIdx = request.indexOf('?');
const hashIdx = request.indexOf('#');
if (queryIdx === -1)
return hashIdx === -1 ? request : request.slice(0, hashIdx);
if (hashIdx === -1)
return request.slice(0, queryIdx);
return request.slice(0, Math.min(queryIdx, hashIdx));
};
const getResolverKey = (importer, stack) => {
const root = stack.length ? stack[stack.length - 1] : importer;
return stripQueryAndHash(root);
};
const asyncResolve = (what, importer, stack = [importer]) => {
const key = getResolverKey(importer, stack);
const resolver = resolvers[key];
if (!resolver || resolver.length === 0) {
throw new Error(`No resolver found for ${key}`);
}
return Promise.all(resolver.map((r) => r(what, importer, stack))).then((results) => {
const firstResult = results[0];
if (results.some((r) => r !== firstResult)) {
throw new Error('Resolvers returned different results');
}
return firstResult;
});
};
function addResolver(resourcePath, resolver) {
const key = stripQueryAndHash(resourcePath);
if (!resolvers[key]) {
resolvers[key] = [];
}
resolvers[key].push(resolver);
return () => {
resolvers[key] = resolvers[key].filter((r) => r !== resolver);
};
}
const webpackTransformLoader = function (content, inputSourceMap) {
this.async();
const _a = this.getOptions() || {}, { fastCheck = true, prefixer = true } = _a, pluginOptions = __rest(_a, ["fastCheck", "prefixer"]);
const contentStr = content.toString();
if (!(0, fast_check_1.performFastCheck)(contentStr, fastCheck)) {
this.callback(null, contentStr, inputSourceMap);
return;
}
const removeResolver = addResolver(this.resourcePath, (what, importer) => {
const importerPath = stripQueryAndHash(importer);
const context = path_1.default.isAbsolute(importerPath)
? path_1.default.dirname(importerPath)
: path_1.default.join(process.cwd(), path_1.default.dirname(importerPath));
return new Promise((resolve, reject) => {
this.resolve(context, what, (err, result) => {
if (err) {
reject(err);
}
else if (result) {
const filePath = stripQueryAndHash(result);
if (path_1.default.isAbsolute(filePath)) {
this.addDependency(filePath);
}
resolve(result);
}
else {
reject(new Error(`Cannot resolve ${what}`));
}
});
});
});
const filename = path_1.default.basename(this.resourcePath, path_1.default.extname(this.resourcePath));
const transformServices = {
options: {
filename: this.resourcePath,
inputSourceMap: (0, source_map_1.convertSourceMap)(inputSourceMap, this.resourcePath),
root: process.cwd(),
prefixer,
pluginOptions,
},
cache,
};
(0, transform_1.transform)(transformServices, contentStr, asyncResolve)
.then(async (result) => {
var _a, _b, _c, _d;
if (result.cssText) {
const { cssText } = result;
await Promise.all((_b = (_a = result.dependencies) === null || _a === void 0 ? void 0 : _a.map((dep) => {
return asyncResolve(dep, this.resourcePath);
})) !== null && _b !== void 0 ? _b : []);
try {
const compressedCss = node_zlib_1.default.gzipSync(cssText);
const encodedCss = Buffer.from(compressedCss).toString('base64');
const isGlobalStyle = filename.endsWith(consts_1.LINARIA_GLOBAL_EXTENSION);
const cssSuffix = isGlobalStyle
? `${consts_1.LINARIA_GLOBAL_EXTENSION}.css`
: `${consts_1.LINARIA_MODULE_EXTENSION}.css`;
const cssFilename = `${filename}${cssSuffix}`;
const importStatement = `import "./${cssFilename}!=!./${filename}?./${cssFilename}?css=${encodedCss}"`;
const finalCode = (0, insert_import_1.insertImportStatement)(result.code, importStatement);
this.callback(null, finalCode, (_c = result.sourceMap) !== null && _c !== void 0 ? _c : undefined);
}
catch (err) {
this.callback(err);
}
return;
}
this.callback(null, result.code, (_d = result.sourceMap) !== null && _d !== void 0 ? _d : undefined);
})
.catch((err) => this.callback(err))
.finally(removeResolver);
};
exports.default = webpackTransformLoader;
//# sourceMappingURL=webpack-transform-loader.js.map