polen
Version:
A framework for delightful GraphQL developer portals
58 lines • 2.62 kB
JavaScript
import jsesc from 'jsesc';
// import { id,or,exclude } from 'rolldown/filter'
import {} from '@rolldown/pluginutils';
export const create = (options = {}) => {
const codec = options.codec?.validate ?? JSON;
const codecImportExport = options.codec?.importExport ?? `default`;
const pluginName = options.name ?? `json-imports`;
// Always exclude \0 prefixed modules
const baseExcludePatterns = [/^\0/];
const moduleTypes = options.filter?.moduleTypes ?? [`json`];
const isCustomCodec = Boolean(options.codec?.importPath);
// Check if we should handle this file based on extension
const shouldHandle = (id) => {
// Exclude internal modules with \0 prefix
if (id.startsWith(`\0`))
return false;
// Check if it has one of our configured extensions
return moduleTypes.some(type => id.endsWith(`.${type}`));
};
return {
name: pluginName,
enforce: `pre`,
// Transform files based on extension
transform(code, id) {
if (!shouldHandle(id))
return;
try {
// Skip validation for superjson since the codec validates the envelope format
if (options.codec?.validate && !options.codec.importPath?.includes(`superjson`)) {
codec.parse(code);
}
if (!isCustomCodec) {
// For native JSON, directly export as JavaScript object literal
return `export default ${code}`;
}
else {
// For custom codecs, we need to parse at runtime
if (!options.codec?.importPath) {
throw new Error(`codec.importPath is required when using a custom codec`);
}
const importIdentifier = codecImportExport === `default` ? `codec` : codecImportExport;
const importStatement = codecImportExport === `default`
? `import ${importIdentifier} from '${options.codec.importPath}'`
: `import { ${codecImportExport} } from '${options.codec.importPath}'`;
return `
${importStatement}
const data = ${importIdentifier}.parse('${jsesc(code)}')
export { data as default }`;
}
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.error(`Failed to parse JSON in ${id}: ${message}`);
}
},
};
};
//# sourceMappingURL=vite-plugin-json.js.map