|
| 1 | +import { promises as fs } from 'node:fs'; |
| 2 | +import { fileURLToPath } from 'node:url'; |
| 3 | +import { dirname, join } from 'node:path'; |
| 4 | + |
| 5 | +const __filename = fileURLToPath(import.meta.url); |
| 6 | +const __dirname = dirname(__filename); |
| 7 | +const distDir = join(__dirname, '../dist'); |
| 8 | + |
| 9 | +import * as acorn from "acorn"; |
| 10 | + |
| 11 | +/** |
| 12 | + * Fix common invalid syntax issues that creep into bundled JS. |
| 13 | + * - Converts stray HTML-style comments into valid JS comments |
| 14 | + * - Handles spacing and multiline safely |
| 15 | + * - Optionally decodes < and > entities |
| 16 | + */ |
| 17 | +const fixJavaScriptSyntax = (content, { decodeEntities = false } = {}) => { |
| 18 | + let fixed = content; |
| 19 | + |
| 20 | + // 1. Fix malformed HTML comments like < !-- ... --> |
| 21 | + fixed = fixed.replace(/<\s*!--([\s\S]*?)-->/g, (_, inner) => { |
| 22 | + return `/* ${inner.trim()} */`; |
| 23 | + }); |
| 24 | + |
| 25 | + // 2. Convert proper <!-- ... --> comments |
| 26 | + // Use block comments instead of // to safely handle multi-line |
| 27 | + fixed = fixed.replace(/<!--([\s\S]*?)-->/g, (_, inner) => { |
| 28 | + return `/* ${inner.trim()} */`; |
| 29 | + }); |
| 30 | + |
| 31 | + // 3. Decode HTML entities only if requested |
| 32 | + if (decodeEntities) { |
| 33 | + fixed = fixed.replace(/</g, "<").replace(/>/g, ">"); |
| 34 | + } |
| 35 | + |
| 36 | + // 4. Validate with Acorn (throws if still invalid) |
| 37 | + try { |
| 38 | + acorn.parse(fixed, { ecmaVersion: "latest", sourceType: "module" }); |
| 39 | + } catch (err) { |
| 40 | + console.error("❌ Still invalid after fix:", err.message); |
| 41 | + throw err; |
| 42 | + } |
| 43 | + |
| 44 | + return fixed; |
| 45 | +}; |
| 46 | + |
| 47 | + |
| 48 | +const removeFile = async () => { |
| 49 | + try { |
| 50 | + const filePath = join(distDir, 'editoria11y.esm.js'); |
| 51 | + await fs.unlink(filePath); |
| 52 | + console.log('🗑️ Removed old bundle:', filePath); |
| 53 | + } catch (err) { |
| 54 | + if (err.code === 'ENOENT') { |
| 55 | + console.log('ℹ️ File does not exist, nothing to remove.'); |
| 56 | + } else { |
| 57 | + console.error('❌ Error removing file:', err); |
| 58 | + } |
| 59 | + } |
| 60 | +}; |
| 61 | + |
| 62 | +/** |
| 63 | + * Replace a pattern in the input string, or throw if not found. |
| 64 | + */ |
| 65 | +const requestReplace = (input, pattern, replacement, description = 'pattern') => { |
| 66 | + const regex = typeof pattern === 'string' ? new RegExp(pattern, 'g') : pattern; |
| 67 | + const result = input.replace(regex, replacement); |
| 68 | + |
| 69 | + if (result === input) { |
| 70 | + throw new Error(`❌ Could not find ${description}`); |
| 71 | + } |
| 72 | + |
| 73 | + return result; |
| 74 | +} |
| 75 | +// Add nonce modifications |
| 76 | +const addNonceSupport = (content) => { |
| 77 | + // Flexible patterns to handle spaces/newlines/minified code |
| 78 | + content = requestReplace( |
| 79 | + content, |
| 80 | + /customTests\s*:\s*0\s*,[\s\S]*?};/, |
| 81 | + `customTests: 0, |
| 82 | +
|
| 83 | + nonce: false, |
| 84 | +
|
| 85 | +};`, |
| 86 | + 'customTests block' |
| 87 | + ); |
| 88 | + |
| 89 | + content = requestReplace( |
| 90 | + content, |
| 91 | + /Ed11y\.attachCSS\s*=\s*function\s*\(appendTo\)\s*{[\s\S]*?};/, |
| 92 | + `Ed11y.attachCSS = function(appendTo) { |
| 93 | + const bundle = cssBundle.cloneNode(true); |
| 94 | + if (Ed11y.options.nonce) { |
| 95 | + bundle.querySelectorAll('link').forEach(link => { |
| 96 | + link.setAttribute('nonce', Ed11y.options.nonce); |
| 97 | + }); |
| 98 | + } |
| 99 | + appendTo.appendChild(bundle); |
| 100 | +};`, |
| 101 | + 'attachCSS function' |
| 102 | + ); |
| 103 | + |
| 104 | + return content; |
| 105 | +} |
| 106 | + |
| 107 | +const buildBundle = async (files) => { |
| 108 | + return files.reduce(async (bundlePromise, file) => { |
| 109 | + const bundle = await bundlePromise; // wait for previous iteration |
| 110 | + const filePath = join(__dirname, '../js', file); |
| 111 | + |
| 112 | + try { |
| 113 | + await fs.access(filePath); |
| 114 | + let content = await fs.readFile(filePath, 'utf8'); |
| 115 | + // Apply fixes to all files |
| 116 | + content = fixJavaScriptSyntax(content); |
| 117 | + if (file === 'ed11y.js') { |
| 118 | + content = addNonceSupport(content); |
| 119 | + } |
| 120 | + |
| 121 | + return bundle + content + '\n'; |
| 122 | + } catch (err) { |
| 123 | + if (err.code === 'ENOENT') { |
| 124 | + console.log(`⚠️ Skipping missing file: ${filePath}`); |
| 125 | + return bundle; |
| 126 | + } else { |
| 127 | + console.error(`❌ Error processing ${filePath}:`, err); |
| 128 | + return bundle; |
| 129 | + } |
| 130 | + } |
| 131 | + }, Promise.resolve('')); // start with an empty bundle |
| 132 | +}; |
| 133 | + |
| 134 | +const writeFiles = async (esmBundle) => { |
| 135 | + try { |
| 136 | + const esmPath = join(distDir, 'editoria11y.esm.js'); |
| 137 | + await fs.writeFile(esmPath, esmBundle, 'utf8'); |
| 138 | + console.log('✅ Wrote JS bundle:', esmPath); |
| 139 | + |
| 140 | + const cssSrcPath = join(distDir, 'editoria11y.min.css'); |
| 141 | + const cssDestPath = join(distDir, 'editoria11y.css'); |
| 142 | + await fs.copyFile(cssSrcPath, cssDestPath); |
| 143 | + console.log('✅ Copied CSS to:', cssDestPath); |
| 144 | + } catch (err) { |
| 145 | + console.error('❌ Error writing files:', err); |
| 146 | + } |
| 147 | +}; |
| 148 | + |
| 149 | +const buildESM = async () => { |
| 150 | + await removeFile(); |
| 151 | + |
| 152 | + const files = [ |
| 153 | + 'ed11y-localization.js', |
| 154 | + 'ed11y-test-embeds.js', |
| 155 | + 'ed11y-test-headings.js', |
| 156 | + 'ed11y-test-images.js', |
| 157 | + 'ed11y-test-links.js', |
| 158 | + 'ed11y-test-text.js', |
| 159 | + 'ed11y.js', |
| 160 | + 'ed11y-element-alt.js', |
| 161 | + 'ed11y-element-panel.js', |
| 162 | + 'ed11y-element-result.js', |
| 163 | + 'ed11y-element-tip.js', |
| 164 | + ]; |
| 165 | + |
| 166 | + const jsBundle = await buildBundle(files); |
| 167 | + |
| 168 | + const esmBundle = `${jsBundle} |
| 169 | +
|
| 170 | +export default Ed11y; |
| 171 | +export { Ed11y }; |
| 172 | +`; |
| 173 | + await writeFiles(esmBundle); |
| 174 | + |
| 175 | + console.log('🎉 Build complete with nonce support and syntax fixes'); |
| 176 | + console.log(' - Original files unchanged'); |
| 177 | + console.log(' - Generated: dist/editoria11y.esm.js'); |
| 178 | + console.log(' - Generated: dist/editoria11y.css'); |
| 179 | +}; |
| 180 | + |
| 181 | +await buildESM(); |
0 commit comments