astro-purgecss 5.2.2 → 5.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var fs=require('fs'),path=require('path'),purgecss=require('purgecss'),crypto=require('crypto'),promises=require('fs/promises'),url=require('url');var y,C,S,O,R=true;typeof process<"u"&&({FORCE_COLOR:y,NODE_DISABLE_COLORS:C,NO_COLOR:S,TERM:O}=process.env||{},R=process.stdout&&process.stdout.isTTY);var I={enabled:!C&&S==null&&O!=="dumb"&&(y!=null&&y!=="0"||R)};function e(n,t){let s=new RegExp(`\\x1b\\[${t}m`,"g"),m=`\x1B[${n}m`,i=`\x1B[${t}m`;return function(l){return !I.enabled||l==null?l:m+(~(""+l).indexOf(i)?l.replace(s,i+m):l)+i}}var F=e(2,22),P=e(31,39),E=e(32,39);async function T(n){try{return await promises.readFile(n,"utf8")}catch(t){return N(`Error reading file ${n}: ${t}`),""}}async function $(n,t){try{await promises.writeFile(n,t,"utf8");}catch(s){N(`Error writing file ${n}: ${s}`);}}async function w(n,t,s){await $(n,t),fs.existsSync(s)&&s!==n&&await promises.unlink(s);}function A(n,t){let s=crypto.createHash("sha256").update(t).digest("hex").slice(0,8);return `${n.slice(0,-13)}.${s}.css`}function D(n){if(!(n instanceof URL))throw new TypeError("Expected a URL object");let t=url.fileURLToPath(n).replace(/\/+$/,"");return process.platform==="win32"?t.replace(/^\/+/,""):t}var L=new Intl.DateTimeFormat("en-us",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:false});function d(n){let t=L.format(new Date);console.log(F(t),E("\u25B6"),n);}function N(n){let t=L.format(new Date);console.error(F(t),P("\u25A0"),n);}var U="astro-purgecss",G=n=>n.match(/[\w
|
|
1
|
+
'use strict';var fs=require('fs'),path=require('path'),purgecss=require('purgecss'),crypto=require('crypto'),promises=require('fs/promises'),url=require('url');var y,C,S,O,R=true;typeof process<"u"&&({FORCE_COLOR:y,NODE_DISABLE_COLORS:C,NO_COLOR:S,TERM:O}=process.env||{},R=process.stdout&&process.stdout.isTTY);var I={enabled:!C&&S==null&&O!=="dumb"&&(y!=null&&y!=="0"||R)};function e(n,t){let s=new RegExp(`\\x1b\\[${t}m`,"g"),m=`\x1B[${n}m`,i=`\x1B[${t}m`;return function(l){return !I.enabled||l==null?l:m+(~(""+l).indexOf(i)?l.replace(s,i+m):l)+i}}var F=e(2,22),P=e(31,39),E=e(32,39);async function T(n){try{return await promises.readFile(n,"utf8")}catch(t){return N(`Error reading file ${n}: ${t}`),""}}async function $(n,t){try{await promises.writeFile(n,t,"utf8");}catch(s){N(`Error writing file ${n}: ${s}`);}}async function w(n,t,s){await $(n,t),fs.existsSync(s)&&s!==n&&await promises.unlink(s);}function A(n,t){let s=crypto.createHash("sha256").update(t).digest("hex").slice(0,8);return `${n.slice(0,-13)}.${s}.css`}function D(n){if(!(n instanceof URL))throw new TypeError("Expected a URL object");let t=url.fileURLToPath(n).replace(/\/+$/,"");return process.platform==="win32"?t.replace(/^\/+/,""):t}var L=new Intl.DateTimeFormat("en-us",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:false});function d(n){let t=L.format(new Date);console.log(F(t),E("\u25B6"),n);}function N(n){let t=L.format(new Date);console.error(F(t),P("\u25A0"),n);}var U="astro-purgecss",G=n=>n.match(/[\w-/:\.#\(\),';%]+(?<!:)/g)||[];function W(n={}){let t;return {name:U,hooks:{"astro:config:done":({config:s})=>{t=s;},"astro:build:done":async({dir:s,pages:m,logger:i})=>{let l=t.output;i.info(`\u{1F4E6} Running in '${l}' mode`);let o=D(s),v=l!=="static";if(!o||!t.build.format||!t.build.assets){i.warn(`${U} requires the following astro.config options: 'outDir', 'build.format', 'build.assets'`);return}let f=(await new purgecss.PurgeCSS().purge({css:[`${o}/**/*.css`.replace(/\\/g,"/")],defaultExtractor:G,...n,content:[`${o}/**/*.html`.replace(/\\/g,"/"),`${o}/**/*.js`.replace(/\\/g,"/"),...n.content||[]]})).filter(({file:c})=>c?.endsWith(".css"));if(f.length===0){i.info("\u2139\uFE0F No CSS files found to process");return}if(i.info(`Found ${f.length} CSS ${f.length===1?"file":"files"} to process`),v){await Promise.all(f.map(async({css:c,file:r})=>{await w(r,c,r),d(r.replace(o,""));})),i.info("\u{1F389} Purging completed successfully!");return}let x=(await Promise.all(f.map(async({css:c,file:r})=>{if(!r.includes(t.build.assets)){await w(r,c,r);let g=r.replace(o,"");return d(g),{oldFilename:g,newFilename:g}}let p=A(r,c);await w(p,c,r);let b=r.replace(o,""),h=p.replace(o,"");return d(h),{oldFilename:b,newFilename:h}}))).filter(({oldFilename:c,newFilename:r})=>c!==r);if(x.length>0){i.info(`Updating ${x.length} CSS ${x.length===1?"reference":"references"} in HTML files...`);let c=m.filter(r=>typeof r.pathname=="string").map(r=>{let a=r.pathname;if(a==="")return path.join(o,"index.html");if(a==="404/")return path.join(o,"404.html");switch(t.build.format){case "file":return path.join(o,`${a}.html`);case "directory":return path.join(o,a,"index.html");case "preserve":let p=path.join(o,`${a}.html`);return fs.existsSync(p)?p:path.join(o,a,"index.html")}});await Promise.all(c.map(async r=>{let a=await T(r);for(let{oldFilename:p,newFilename:b}of x){let h=p.replace(/\\/g,"/"),g=b.replace(/\\/g,"/");a=a.replace(new RegExp(h,"g"),g);}await $(r,a),d(r.replace(o,""));}));}i.info("\u{1F389} Purging completed successfully!");}}}}var Te=W;module.exports=Te;//# sourceMappingURL=index.cjs.map
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/colors.mjs","../src/utils.ts","../src/index.ts"],"names":["FORCE_COLOR","NODE_DISABLE_COLORS","NO_COLOR","TERM","isTTY","$","init","x","y","rgx","open","close","txt","reset","dim","red","green","readFileContent","filePath","readFile","err","error","writeFileContent","content","writeFile","writeCssFile","newFilePath","css","oldFilePath","existsSync","unlink","generateFileHash","hash","createHash","cleanPath","file","path","fileURLToPath","dt","success","message","date","INTEGRATION_NAME","defaultExtractor","Plugin","options","config","cfg","dir","pages","logger","buildMode","outDir","isSSR","purgedCssFiles","PurgeCSS","changedFiles","relativePath","hashedFilename","relativeOldPath","relativeNewPath","oldFilename","newFilename","htmlFiles","page","pathname","join","directFile","htmlFile","normalizedOldPath","normalizedNewPath","index_default"],"mappings":"gKAAA,IAAIA,EAAaC,CAAqBC,CAAAA,CAAAA,CAAUC,CAAMC,CAAAA,CAAAA,CAAM,IACxD,CAAA,OAAO,QAAY,GACrB,GAAA,CAAE,WAAAJ,CAAAA,CAAAA,CAAa,mBAAAC,CAAAA,CAAAA,CAAqB,SAAAC,CAAU,CAAA,IAAA,CAAAC,CAAK,CAAA,CAAI,OAAQ,CAAA,GAAA,EAAO,EACvEC,CAAAA,CAAAA,CAAQ,OAAQ,CAAA,MAAA,EAAU,OAAQ,CAAA,MAAA,CAAO,OAGnC,IAAMC,CAAAA,CAAI,CAChB,OAAA,CAAS,CAACJ,CAAAA,EAAuBC,CAAY,EAAA,IAAA,EAAQC,CAAS,GAAA,MAAA,GAC7DH,CAAe,EAAA,IAAA,EAAQA,CAAgB,GAAA,GAAA,EAAOI,EAEhD,CAEA,CAAA,SAASE,CAAKC,CAAAA,CAAAA,CAAGC,CAAG,CAAA,CACnB,IAAIC,CAAM,CAAA,IAAI,MAAO,CAAA,CAAA,QAAA,EAAWD,CAAC,CAAA,CAAA,CAAA,CAAK,GAAG,CACrCE,CAAAA,CAAAA,CAAO,CAAQH,KAAAA,EAAAA,CAAC,CAAKI,CAAAA,CAAAA,CAAAA,CAAAA,CAAQ,CAAQH,KAAAA,EAAAA,CAAC,CAE1C,CAAA,CAAA,CAAA,OAAO,SAAUI,CAAAA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_COLORS, NO_COLOR, TERM } = process.env || {});\n\tisTTY = process.stdout && process.stdout.isTTY;\n}\n\nexport const $ = {\n\tenabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && (\n\t\tFORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY\n\t)\n}\n\nfunction init(x, y) {\n\tlet rgx = new RegExp(`\\\\x1b\\\\[${y}m`, 'g');\n\tlet open = `\\x1b[${x}m`, close = `\\x1b[${y}m`;\n\n\treturn function (txt) {\n\t\tif (!$.enabled || txt == null) return txt;\n\t\treturn open + (!!~(''+txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;\n\t};\n}\n\n// modifiers\nexport const reset = init(0, 0);\nexport const bold = init(1, 22);\nexport const dim = init(2, 22);\nexport const italic = init(3, 23);\nexport const underline = init(4, 24);\nexport const inverse = init(7, 27);\nexport const hidden = init(8, 28);\nexport const strikethrough = init(9, 29);\n\n// colors\nexport const black = init(30, 39);\nexport const red = init(31, 39);\nexport const green = init(32, 39);\nexport const yellow = init(33, 39);\nexport const blue = init(34, 39);\nexport const magenta = init(35, 39);\nexport const cyan = init(36, 39);\nexport const white = init(37, 39);\nexport const gray = init(90, 39);\nexport const grey = init(90, 39);\n\n// background colors\nexport const bgBlack = init(40, 49);\nexport const bgRed = init(41, 49);\nexport const bgGreen = init(42, 49);\nexport const bgYellow = init(43, 49);\nexport const bgBlue = init(44, 49);\nexport const bgMagenta = init(45, 49);\nexport const bgCyan = init(46, 49);\nexport const bgWhite = init(47, 49);\n","import { dim, green, red } from 'kleur/colors';\nimport { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { readFile, unlink, writeFile } from 'node:fs/promises';\nimport { fileURLToPath } from 'node:url';\n\nexport async function readFileContent(filePath: string): Promise<string> {\n try {\n const content = await readFile(filePath, 'utf8');\n return content;\n } catch (err) {\n error(`Error reading file ${filePath}: ${err}`);\n return '';\n }\n}\n\nexport async function writeFileContent(filePath: string, content: string) {\n try {\n await writeFile(filePath, content, 'utf8');\n } catch (err) {\n error(`Error writing file ${filePath}: ${err}`);\n }\n}\n\nexport async function writeCssFile(\n newFilePath: string,\n css: string,\n oldFilePath: string\n) {\n await writeFileContent(newFilePath, css);\n\n // Remove old file if it exists and is different from new file\n if (existsSync(oldFilePath) && oldFilePath !== newFilePath) {\n await unlink(oldFilePath);\n }\n}\n\nexport function generateFileHash(filePath: string, content: string) {\n // Get content hash before writing to file\n const hash = createHash('sha256').update(content).digest('hex').slice(0, 8);\n\n // Generate new file name with hash\n // Astro original hash is 8 characters long\n return `${filePath.slice(0, -13)}.${hash}.css`;\n}\n\n// Clean from extra slash on windows and trailing forward slash on non-windows\nexport function cleanPath(file: URL): string {\n if (!(file instanceof URL)) {\n throw new TypeError('Expected a URL object');\n }\n\n // Remove trailing forward slash if present\n let path = fileURLToPath(file).replace(/\\/+$/, '');\n\n // Remove leading forward slash on windows if present\n return process.platform === 'win32' ? path.replace(/^\\/+/, '') : path;\n}\n\nexport const dt = new Intl.DateTimeFormat('en-us', {\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n hour12: false\n});\n\nexport function success(message: string) {\n const date = dt.format(new Date());\n console.log(dim(date), green('▶'), message);\n}\n\nexport function error(message: string) {\n const date = dt.format(new Date());\n console.error(dim(date), red('■'), message);\n}\n","import type { AstroConfig, AstroIntegration } from 'astro';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { PurgeCSS, type UserDefinedOptions } from 'purgecss';\n\nimport {\n cleanPath,\n generateFileHash,\n readFileContent,\n success,\n writeCssFile,\n writeFileContent\n} from './utils';\n\n/**\n * Extended PurgeCSS options interface that allows partial configuration\n * of the standard PurgeCSS options\n */\nexport interface PurgeCSSOptions extends Partial<UserDefinedOptions> {}\n\nconst INTEGRATION_NAME = 'astro-purgecss' as const;\n\n/**\n * default extractor to handle various CSS selector patterns\n * @param content string\n */\nconst defaultExtractor = (content: string) =>\n content.match(/[\\w-/:]+(?<!:)/g) || [];\n\n/**\n * Astro integration for PurgeCSS that removes unused CSS from the final build\n * @param options - PurgeCSS configuration options\n * @returns AstroIntegration - The configured Astro integration\n */\nfunction Plugin(options: PurgeCSSOptions = {}): AstroIntegration {\n let config: AstroConfig;\n\n return {\n name: INTEGRATION_NAME,\n hooks: {\n 'astro:config:done': ({ config: cfg }) => {\n config = cfg;\n },\n 'astro:build:done': async ({ dir, pages, logger }) => {\n const buildMode = config.output;\n logger.info(`📦 Running in '${buildMode}' mode`);\n\n // Convert the URL to a filesystem path\n const outDir = cleanPath(dir);\n\n // Used to skip file rehashing for SSR/Hybrid modes\n const isSSR = buildMode !== 'static';\n\n // Validate required Astro configuration\n if (!outDir || !config.build.format || !config.build.assets) {\n logger.warn(\n `${INTEGRATION_NAME} requires the following astro.config options: 'outDir', 'build.format', 'build.assets'`\n );\n return;\n }\n\n // Run PurgeCSS on all CSS files\n // Replace is needed to make sure to pass correct glob format on windows machines\n const purgeResults = await new PurgeCSS().purge({\n css: [`${outDir}/**/*.css`.replace(/\\\\/g, '/')],\n defaultExtractor,\n ...options,\n content: [\n `${outDir}/**/*.html`.replace(/\\\\/g, '/'),\n `${outDir}/**/*.js`.replace(/\\\\/g, '/'),\n ...(options.content || [])\n ]\n });\n\n // Filter out non-CSS files from purge results\n const purgedCssFiles = purgeResults.filter(({ file }) =>\n file?.endsWith('.css')\n ) as Array<{\n css: string;\n file: string;\n }>;\n\n if (purgedCssFiles.length === 0) {\n logger.info('ℹ️ No CSS files found to process');\n return;\n }\n\n logger.info(\n `Found ${purgedCssFiles.length} CSS ${purgedCssFiles.length === 1 ? 'file' : 'files'} to process`\n );\n\n // Handle SSR/Hybrid mode\n if (isSSR) {\n await Promise.all(\n purgedCssFiles.map(async ({ css, file }) => {\n await writeCssFile(file, css, file);\n success(file.replace(outDir, ''));\n })\n );\n logger.info('🎉 Purging completed successfully!');\n return;\n }\n\n // Process files for static mode with content hashing\n let processedFiles = await Promise.all(\n purgedCssFiles.map(async ({ css, file }) => {\n const isAssetFile = file.includes(config.build.assets);\n\n // Skip rehashing for non-asset files (not generated by astro)\n // ex: assets/styles/light.css\n if (!isAssetFile) {\n await writeCssFile(file, css, file);\n const relativePath = file.replace(outDir, '');\n success(relativePath);\n return {\n oldFilename: relativePath,\n newFilename: relativePath\n };\n }\n\n // Generate new filename with content hash\n const hashedFilename = generateFileHash(file, css);\n await writeCssFile(hashedFilename, css, file);\n\n const relativeOldPath = file.replace(outDir, '');\n const relativeNewPath = hashedFilename.replace(outDir, '');\n success(relativeNewPath);\n\n return {\n oldFilename: relativeOldPath,\n newFilename: relativeNewPath\n };\n })\n );\n\n // Filter to only get files that actually changed\n const changedFiles = processedFiles.filter(\n ({ oldFilename, newFilename }) => oldFilename !== newFilename\n );\n\n if (changedFiles.length > 0) {\n logger.info(\n `Updating ${changedFiles.length} CSS ${changedFiles.length === 1 ? 'reference' : 'references'} in HTML files...`\n );\n // Get all HTML pages based on build format\n const htmlFiles = pages\n .filter((page) => typeof page.pathname === 'string')\n .map((page) => {\n const pathname = page.pathname as string;\n\n // Handle root/index page\n if (pathname === '') {\n return join(outDir, 'index.html');\n }\n\n // Handle custom 404 page (https://docs.astro.build/en/basics/astro-pages/#custom-404-error-page)\n if (pathname === '404/') {\n return join(outDir, '404.html');\n }\n\n switch (config.build.format) {\n case 'file':\n // Format: /blog -> /blog.html\n return join(outDir, `${pathname}.html`);\n\n case 'directory':\n // Format: /blog -> /blog/index.html\n return join(outDir, pathname, 'index.html');\n\n case 'preserve':\n // Check if direct HTML file exists, otherwise use directory format\n const directFile = join(outDir, `${pathname}.html`);\n return existsSync(directFile)\n ? directFile\n : join(outDir, pathname, 'index.html');\n }\n });\n\n // Update CSS references in HTML files\n await Promise.all(\n htmlFiles.map(async (htmlFile) => {\n let content = await readFileContent(htmlFile);\n\n for (const { oldFilename, newFilename } of changedFiles) {\n const normalizedOldPath = oldFilename.replace(/\\\\/g, '/');\n const normalizedNewPath = newFilename.replace(/\\\\/g, '/');\n \n content = content.replace(new RegExp(normalizedOldPath, 'g'), normalizedNewPath);\n }\n\n await writeFileContent(htmlFile, content);\n success(htmlFile.replace(outDir, ''));\n })\n );\n }\n\n logger.info('🎉 Purging completed successfully!');\n }\n }\n };\n}\n\nexport default Plugin;\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/colors.mjs","../src/utils.ts","../src/index.ts"],"names":["FORCE_COLOR","NODE_DISABLE_COLORS","NO_COLOR","TERM","isTTY","$","init","x","y","rgx","open","close","txt","reset","dim","red","green","readFileContent","filePath","readFile","err","error","writeFileContent","content","writeFile","writeCssFile","newFilePath","css","oldFilePath","existsSync","unlink","generateFileHash","hash","createHash","cleanPath","file","path","fileURLToPath","dt","success","message","date","INTEGRATION_NAME","defaultExtractor","Plugin","options","config","cfg","dir","pages","logger","buildMode","outDir","isSSR","purgedCssFiles","PurgeCSS","changedFiles","relativePath","hashedFilename","relativeOldPath","relativeNewPath","oldFilename","newFilename","htmlFiles","page","pathname","join","directFile","htmlFile","normalizedOldPath","normalizedNewPath","index_default"],"mappings":"gKAAA,IAAIA,EAAaC,CAAqBC,CAAAA,CAAAA,CAAUC,CAAMC,CAAAA,CAAAA,CAAM,IACxD,CAAA,OAAO,QAAY,GACrB,GAAA,CAAE,WAAAJ,CAAAA,CAAAA,CAAa,mBAAAC,CAAAA,CAAAA,CAAqB,SAAAC,CAAU,CAAA,IAAA,CAAAC,CAAK,CAAA,CAAI,OAAQ,CAAA,GAAA,EAAO,EACvEC,CAAAA,CAAAA,CAAQ,OAAQ,CAAA,MAAA,EAAU,OAAQ,CAAA,MAAA,CAAO,OAGnC,IAAMC,CAAAA,CAAI,CAChB,OAAA,CAAS,CAACJ,CAAAA,EAAuBC,CAAY,EAAA,IAAA,EAAQC,CAAS,GAAA,MAAA,GAC7DH,CAAe,EAAA,IAAA,EAAQA,CAAgB,GAAA,GAAA,EAAOI,EAEhD,CAEA,CAAA,SAASE,CAAKC,CAAAA,CAAAA,CAAG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AAA,OAAA,CAAQhB,CAAQ,CAAA,EAAE,CAAC,EACtC,CAAC,CACH,EACF,CAEAF,CAAAA,CAAO,IAAK,CAAA,2CAAoC,EAClD,CACF,CACF,CACF,CAEA,IAAOqB,EAAQ3B,CAAAA","file":"index.cjs","sourcesContent":["let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true;\nif (typeof process !== 'undefined') {\n\t({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {});\n\tisTTY = process.stdout && process.stdout.isTTY;\n}\n\nexport const $ = {\n\tenabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && (\n\t\tFORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY\n\t)\n}\n\nfunction init(x, y) {\n\tlet rgx = new RegExp(`\\\\x1b\\\\[${y}m`, 'g');\n\tlet open = `\\x1b[${x}m`, close = `\\x1b[${y}m`;\n\n\treturn function (txt) {\n\t\tif (!$.enabled || txt == null) return txt;\n\t\treturn open + (!!~(''+txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;\n\t};\n}\n\n// modifiers\nexport const reset = init(0, 0);\nexport const bold = init(1, 22);\nexport const dim = init(2, 22);\nexport const italic = init(3, 23);\nexport const underline = init(4, 24);\nexport const inverse = init(7, 27);\nexport const hidden = init(8, 28);\nexport const strikethrough = init(9, 29);\n\n// colors\nexport const black = init(30, 39);\nexport const red = init(31, 39);\nexport const green = init(32, 39);\nexport const yellow = init(33, 39);\nexport const blue = init(34, 39);\nexport const magenta = init(35, 39);\nexport const cyan = init(36, 39);\nexport const white = init(37, 39);\nexport const gray = init(90, 39);\nexport const grey = init(90, 39);\n\n// background colors\nexport const bgBlack = init(40, 49);\nexport const bgRed = init(41, 49);\nexport const bgGreen = init(42, 49);\nexport const bgYellow = init(43, 49);\nexport const bgBlue = init(44, 49);\nexport const bgMagenta = init(45, 49);\nexport const bgCyan = init(46, 49);\nexport const bgWhite = init(47, 49);\n","import { dim, green, red } from 'kleur/colors';\nimport { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { readFile, unlink, writeFile } from 'node:fs/promises';\nimport { fileURLToPath } from 'node:url';\n\nexport async function readFileContent(filePath: string): Promise<string> {\n try {\n const content = await readFile(filePath, 'utf8');\n return content;\n } catch (err) {\n error(`Error reading file ${filePath}: ${err}`);\n return '';\n }\n}\n\nexport async function writeFileContent(filePath: string, content: string) {\n try {\n await writeFile(filePath, content, 'utf8');\n } catch (err) {\n error(`Error writing file ${filePath}: ${err}`);\n }\n}\n\nexport async function writeCssFile(\n newFilePath: string,\n css: string,\n oldFilePath: string\n) {\n await writeFileContent(newFilePath, css);\n\n // Remove old file if it exists and is different from new file\n if (existsSync(oldFilePath) && oldFilePath !== newFilePath) {\n await unlink(oldFilePath);\n }\n}\n\nexport function generateFileHash(filePath: string, content: string) {\n // Get content hash before writing to file\n const hash = createHash('sha256').update(content).digest('hex').slice(0, 8);\n\n // Generate new file name with hash\n // Astro original hash is 8 characters long\n return `${filePath.slice(0, -13)}.${hash}.css`;\n}\n\n// Clean from extra slash on windows and trailing forward slash on non-windows\nexport function cleanPath(file: URL): string {\n if (!(file instanceof URL)) {\n throw new TypeError('Expected a URL object');\n }\n\n // Remove trailing forward slash if present\n let path = fileURLToPath(file).replace(/\\/+$/, '');\n\n // Remove leading forward slash on windows if present\n return process.platform === 'win32' ? path.replace(/^\\/+/, '') : path;\n}\n\nexport const dt = new Intl.DateTimeFormat('en-us', {\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n hour12: false\n});\n\nexport function success(message: string) {\n const date = dt.format(new Date());\n console.log(dim(date), green('▶'), message);\n}\n\nexport function error(message: string) {\n const date = dt.format(new Date());\n console.error(dim(date), red('■'), message);\n}\n","import type { AstroConfig, AstroIntegration } from 'astro';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { PurgeCSS, type UserDefinedOptions } from 'purgecss';\n\nimport {\n cleanPath,\n generateFileHash,\n readFileContent,\n success,\n writeCssFile,\n writeFileContent\n} from './utils';\n\n/**\n * Extended PurgeCSS options interface that allows partial configuration\n * of the standard PurgeCSS options\n */\nexport interface PurgeCSSOptions extends Partial<UserDefinedOptions> {}\n\nconst INTEGRATION_NAME = 'astro-purgecss' as const;\n\n/**\n * default extractor to handle various CSS selector patterns\n * @param content string\n */\nconst defaultExtractor = (content: string) =>\n content.match(/[\\w-/:\\.#\\(\\),';%]+(?<!:)/g) || [];\n\n/**\n * Astro integration for PurgeCSS that removes unused CSS from the final build\n * @param options - PurgeCSS configuration options\n * @returns AstroIntegration - The configured Astro integration\n */\nfunction Plugin(options: PurgeCSSOptions = {}): AstroIntegration {\n let config: AstroConfig;\n\n return {\n name: INTEGRATION_NAME,\n hooks: {\n 'astro:config:done': ({ config: cfg }) => {\n config = cfg;\n },\n 'astro:build:done': async ({ dir, pages, logger }) => {\n const buildMode = config.output;\n logger.info(`📦 Running in '${buildMode}' mode`);\n\n // Convert the URL to a filesystem path\n const outDir = cleanPath(dir);\n\n // Used to skip file rehashing for SSR/Hybrid modes\n const isSSR = buildMode !== 'static';\n\n // Validate required Astro configuration\n if (!outDir || !config.build.format || !config.build.assets) {\n logger.warn(\n `${INTEGRATION_NAME} requires the following astro.config options: 'outDir', 'build.format', 'build.assets'`\n );\n return;\n }\n\n // Run PurgeCSS on all CSS files\n // Replace is needed to make sure to pass correct glob format on windows machines\n const purgeResults = await new PurgeCSS().purge({\n css: [`${outDir}/**/*.css`.replace(/\\\\/g, '/')],\n defaultExtractor,\n ...options,\n content: [\n `${outDir}/**/*.html`.replace(/\\\\/g, '/'),\n `${outDir}/**/*.js`.replace(/\\\\/g, '/'),\n ...(options.content || [])\n ]\n });\n\n // Filter out non-CSS files from purge results\n const purgedCssFiles = purgeResults.filter(({ file }) =>\n file?.endsWith('.css')\n ) as Array<{\n css: string;\n file: string;\n }>;\n\n if (purgedCssFiles.length === 0) {\n logger.info('ℹ️ No CSS files found to process');\n return;\n }\n\n logger.info(\n `Found ${purgedCssFiles.length} CSS ${purgedCssFiles.length === 1 ? 'file' : 'files'} to process`\n );\n\n // Handle SSR/Hybrid mode\n if (isSSR) {\n await Promise.all(\n purgedCssFiles.map(async ({ css, file }) => {\n await writeCssFile(file, css, file);\n success(file.replace(outDir, ''));\n })\n );\n logger.info('🎉 Purging completed successfully!');\n return;\n }\n\n // Process files for static mode with content hashing\n let processedFiles = await Promise.all(\n purgedCssFiles.map(async ({ css, file }) => {\n const isAssetFile = file.includes(config.build.assets);\n\n // Skip rehashing for non-asset files (not generated by astro)\n // ex: assets/styles/light.css\n if (!isAssetFile) {\n await writeCssFile(file, css, file);\n const relativePath = file.replace(outDir, '');\n success(relativePath);\n return {\n oldFilename: relativePath,\n newFilename: relativePath\n };\n }\n\n // Generate new filename with content hash\n const hashedFilename = generateFileHash(file, css);\n await writeCssFile(hashedFilename, css, file);\n\n const relativeOldPath = file.replace(outDir, '');\n const relativeNewPath = hashedFilename.replace(outDir, '');\n success(relativeNewPath);\n\n return {\n oldFilename: relativeOldPath,\n newFilename: relativeNewPath\n };\n })\n );\n\n // Filter to only get files that actually changed\n const changedFiles = processedFiles.filter(\n ({ oldFilename, newFilename }) => oldFilename !== newFilename\n );\n\n if (changedFiles.length > 0) {\n logger.info(\n `Updating ${changedFiles.length} CSS ${changedFiles.length === 1 ? 'reference' : 'references'} in HTML files...`\n );\n // Get all HTML pages based on build format\n const htmlFiles = pages\n .filter((page) => typeof page.pathname === 'string')\n .map((page) => {\n const pathname = page.pathname as string;\n\n // Handle root/index page\n if (pathname === '') {\n return join(outDir, 'index.html');\n }\n\n // Handle custom 404 page (https://docs.astro.build/en/basics/astro-pages/#custom-404-error-page)\n if (pathname === '404/') {\n return join(outDir, '404.html');\n }\n\n switch (config.build.format) {\n case 'file':\n // Format: /blog -> /blog.html\n return join(outDir, `${pathname}.html`);\n\n case 'directory':\n // Format: /blog -> /blog/index.html\n return join(outDir, pathname, 'index.html');\n\n case 'preserve':\n // Check if direct HTML file exists, otherwise use directory format\n const directFile = join(outDir, `${pathname}.html`);\n return existsSync(directFile)\n ? directFile\n : join(outDir, pathname, 'index.html');\n }\n });\n\n // Update CSS references in HTML files\n await Promise.all(\n htmlFiles.map(async (htmlFile) => {\n let content = await readFileContent(htmlFile);\n\n for (const { oldFilename, newFilename } of changedFiles) {\n const normalizedOldPath = oldFilename.replace(/\\\\/g, '/');\n const normalizedNewPath = newFilename.replace(/\\\\/g, '/');\n \n content = content.replace(new RegExp(normalizedOldPath, 'g'), normalizedNewPath);\n }\n\n await writeFileContent(htmlFile, content);\n success(htmlFile.replace(outDir, ''));\n })\n );\n }\n\n logger.info('🎉 Purging completed successfully!');\n }\n }\n };\n}\n\nexport default Plugin;\n"]}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {existsSync}from'
|
|
1
|
+
import {existsSync}from'fs';import {join}from'path';import {PurgeCSS}from'purgecss';import {createHash}from'crypto';import {unlink,readFile,writeFile}from'fs/promises';import {fileURLToPath}from'url';var y,C,S,O,R=true;typeof process<"u"&&({FORCE_COLOR:y,NODE_DISABLE_COLORS:C,NO_COLOR:S,TERM:O}=process.env||{},R=process.stdout&&process.stdout.isTTY);var I={enabled:!C&&S==null&&O!=="dumb"&&(y!=null&&y!=="0"||R)};function e(n,t){let s=new RegExp(`\\x1b\\[${t}m`,"g"),m=`\x1B[${n}m`,i=`\x1B[${t}m`;return function(l){return !I.enabled||l==null?l:m+(~(""+l).indexOf(i)?l.replace(s,i+m):l)+i}}var F=e(2,22),P=e(31,39),E=e(32,39);async function T(n){try{return await readFile(n,"utf8")}catch(t){return N(`Error reading file ${n}: ${t}`),""}}async function $(n,t){try{await writeFile(n,t,"utf8");}catch(s){N(`Error writing file ${n}: ${s}`);}}async function w(n,t,s){await $(n,t),existsSync(s)&&s!==n&&await unlink(s);}function A(n,t){let s=createHash("sha256").update(t).digest("hex").slice(0,8);return `${n.slice(0,-13)}.${s}.css`}function D(n){if(!(n instanceof URL))throw new TypeError("Expected a URL object");let t=fileURLToPath(n).replace(/\/+$/,"");return process.platform==="win32"?t.replace(/^\/+/,""):t}var L=new Intl.DateTimeFormat("en-us",{hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:false});function d(n){let t=L.format(new Date);console.log(F(t),E("\u25B6"),n);}function N(n){let t=L.format(new Date);console.error(F(t),P("\u25A0"),n);}var U="astro-purgecss",G=n=>n.match(/[\w-/:\.#\(\),';%]+(?<!:)/g)||[];function W(n={}){let t;return {name:U,hooks:{"astro:config:done":({config:s})=>{t=s;},"astro:build:done":async({dir:s,pages:m,logger:i})=>{let l=t.output;i.info(`\u{1F4E6} Running in '${l}' mode`);let o=D(s),v=l!=="static";if(!o||!t.build.format||!t.build.assets){i.warn(`${U} requires the following astro.config options: 'outDir', 'build.format', 'build.assets'`);return}let f=(await new PurgeCSS().purge({css:[`${o}/**/*.css`.replace(/\\/g,"/")],defaultExtractor:G,...n,content:[`${o}/**/*.html`.replace(/\\/g,"/"),`${o}/**/*.js`.replace(/\\/g,"/"),...n.content||[]]})).filter(({file:c})=>c?.endsWith(".css"));if(f.length===0){i.info("\u2139\uFE0F No CSS files found to process");return}if(i.info(`Found ${f.length} CSS ${f.length===1?"file":"files"} to process`),v){await Promise.all(f.map(async({css:c,file:r})=>{await w(r,c,r),d(r.replace(o,""));})),i.info("\u{1F389} Purging completed successfully!");return}let x=(await Promise.all(f.map(async({css:c,file:r})=>{if(!r.includes(t.build.assets)){await w(r,c,r);let g=r.replace(o,"");return d(g),{oldFilename:g,newFilename:g}}let p=A(r,c);await w(p,c,r);let b=r.replace(o,""),h=p.replace(o,"");return d(h),{oldFilename:b,newFilename:h}}))).filter(({oldFilename:c,newFilename:r})=>c!==r);if(x.length>0){i.info(`Updating ${x.length} CSS ${x.length===1?"reference":"references"} in HTML files...`);let c=m.filter(r=>typeof r.pathname=="string").map(r=>{let a=r.pathname;if(a==="")return join(o,"index.html");if(a==="404/")return join(o,"404.html");switch(t.build.format){case "file":return join(o,`${a}.html`);case "directory":return join(o,a,"index.html");case "preserve":let p=join(o,`${a}.html`);return existsSync(p)?p:join(o,a,"index.html")}});await Promise.all(c.map(async r=>{let a=await T(r);for(let{oldFilename:p,newFilename:b}of x){let h=p.replace(/\\/g,"/"),g=b.replace(/\\/g,"/");a=a.replace(new RegExp(h,"g"),g);}await $(r,a),d(r.replace(o,""));}));}i.info("\u{1F389} Purging completed successfully!");}}}}var Te=W;export{Te as default};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/colors.mjs","../src/utils.ts","../src/index.ts"],"names":["FORCE_COLOR","NODE_DISABLE_COLORS","NO_COLOR","TERM","isTTY","$","init","x","y","rgx","open","close","txt","reset","dim","red","green","readFileContent","filePath","readFile","err","error","writeFileContent","content","writeFile","writeCssFile","newFilePath","css","oldFilePath","existsSync","unlink","generateFileHash","hash","createHash","cleanPath","file","path","fileURLToPath","dt","success","message","date","INTEGRATION_NAME","defaultExtractor","Plugin","options","config","cfg","dir","pages","logger","buildMode","outDir","isSSR","purgedCssFiles","PurgeCSS","changedFiles","relativePath","hashedFilename","relativeOldPath","relativeNewPath","oldFilename","newFilename","htmlFiles","page","pathname","join","directFile","htmlFile","normalizedOldPath","normalizedNewPath","index_default"],"mappings":"iOAAA,IAAIA,EAAaC,CAAqBC,CAAAA,CAAAA,CAAUC,CAAMC,CAAAA,CAAAA,CAAM,IACxD,CAAA,OAAO,QAAY,GACrB,GAAA,CAAE,WAAAJ,CAAAA,CAAAA,CAAa,mBAAAC,CAAAA,CAAAA,CAAqB,SAAAC,CAAU,CAAA,IAAA,CAAAC,CAAK,CAAA,CAAI,OAAQ,CAAA,GAAA,EAAO,EACvEC,CAAAA,CAAAA,CAAQ,OAAQ,CAAA,MAAA,EAAU,OAAQ,CAAA,MAAA,CAAO,OA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,GAAG,CAExDvC,CAAAA,CAAAA,CAAUA,CAAQ,CAAA,OAAA,CAAQ,IAAI,MAAA,CAAO8C,CAAmB,CAAA,GAAG,CAAGC,CAAAA,CAAiB,EACjF,CAEA,MAAMhD,CAAiB8C,CAAAA,CAAAA,CAAU7C,CAAO,CAAA,CACxCgB,EAAQ6B,CAAS,CAAA,OAAA,CAAQhB,CAAQ,CAAA,EAAE,CAAC,EACtC,CAAC,CACH,EACF,CAEAF,CAAAA,CAAO,IAAK,CAAA,2CAAoC,EAClD,CACF,CACF,CACF,CAEA,IAAOqB,EAAQ3B,CAAAA","file":"index.js","sourcesContent":["let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true;\nif (typeof process !== 'undefined') {\n\t({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {});\n\tisTTY = process.stdout && process.stdout.isTTY;\n}\n\nexport const $ = {\n\tenabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && (\n\t\tFORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY\n\t)\n}\n\nfunction init(x, y) {\n\tlet rgx = new RegExp(`\\\\x1b\\\\[${y}m`, 'g');\n\tlet open = `\\x1b[${x}m`, close = `\\x1b[${y}m`;\n\n\treturn function (txt) {\n\t\tif (!$.enabled || txt == null) return txt;\n\t\treturn open + (!!~(''+txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;\n\t};\n}\n\n// modifiers\nexport const reset = init(0, 0);\nexport const bold = init(1, 22);\nexport const dim = init(2, 22);\nexport const italic = init(3, 23);\nexport const underline = init(4, 24);\nexport const inverse = init(7, 27);\nexport const hidden = init(8, 28);\nexport const strikethrough = init(9, 29);\n\n// colors\nexport const black = init(30, 39);\nexport const red = init(31, 39);\nexport const green = init(32, 39);\nexport const yellow = init(33, 39);\nexport const blue = init(34, 39);\nexport const magenta = init(35, 39);\nexport const cyan = init(36, 39);\nexport const white = init(37, 39);\nexport const gray = init(90, 39);\nexport const grey = init(90, 39);\n\n// background colors\nexport const bgBlack = init(40, 49);\nexport const bgRed = init(41, 49);\nexport const bgGreen = init(42, 49);\nexport const bgYellow = init(43, 49);\nexport const bgBlue = init(44, 49);\nexport const bgMagenta = init(45, 49);\nexport const bgCyan = init(46, 49);\nexport const bgWhite = init(47, 49);\n","import { dim, green, red } from 'kleur/colors';\nimport { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { readFile, unlink, writeFile } from 'node:fs/promises';\nimport { fileURLToPath } from 'node:url';\n\nexport async function readFileContent(filePath: string): Promise<string> {\n try {\n const content = await readFile(filePath, 'utf8');\n return content;\n } catch (err) {\n error(`Error reading file ${filePath}: ${err}`);\n return '';\n }\n}\n\nexport async function writeFileContent(filePath: string, content: string) {\n try {\n await writeFile(filePath, content, 'utf8');\n } catch (err) {\n error(`Error writing file ${filePath}: ${err}`);\n }\n}\n\nexport async function writeCssFile(\n newFilePath: string,\n css: string,\n oldFilePath: string\n) {\n await writeFileContent(newFilePath, css);\n\n // Remove old file if it exists and is different from new file\n if (existsSync(oldFilePath) && oldFilePath !== newFilePath) {\n await unlink(oldFilePath);\n }\n}\n\nexport function generateFileHash(filePath: string, content: string) {\n // Get content hash before writing to file\n const hash = createHash('sha256').update(content).digest('hex').slice(0, 8);\n\n // Generate new file name with hash\n // Astro original hash is 8 characters long\n return `${filePath.slice(0, -13)}.${hash}.css`;\n}\n\n// Clean from extra slash on windows and trailing forward slash on non-windows\nexport function cleanPath(file: URL): string {\n if (!(file instanceof URL)) {\n throw new TypeError('Expected a URL object');\n }\n\n // Remove trailing forward slash if present\n let path = fileURLToPath(file).replace(/\\/+$/, '');\n\n // Remove leading forward slash on windows if present\n return process.platform === 'win32' ? path.replace(/^\\/+/, '') : path;\n}\n\nexport const dt = new Intl.DateTimeFormat('en-us', {\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n hour12: false\n});\n\nexport function success(message: string) {\n const date = dt.format(new Date());\n console.log(dim(date), green('▶'), message);\n}\n\nexport function error(message: string) {\n const date = dt.format(new Date());\n console.error(dim(date), red('■'), message);\n}\n","import type { AstroConfig, AstroIntegration } from 'astro';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { PurgeCSS, type UserDefinedOptions } from 'purgecss';\n\nimport {\n cleanPath,\n generateFileHash,\n readFileContent,\n success,\n writeCssFile,\n writeFileContent\n} from './utils';\n\n/**\n * Extended PurgeCSS options interface that allows partial configuration\n * of the standard PurgeCSS options\n */\nexport interface PurgeCSSOptions extends Partial<UserDefinedOptions> {}\n\nconst INTEGRATION_NAME = 'astro-purgecss' as const;\n\n/**\n * default extractor to handle various CSS selector patterns\n * @param content string\n */\nconst defaultExtractor = (content: string) =>\n content.match(/[\\w-/:]+(?<!:)/g) || [];\n\n/**\n * Astro integration for PurgeCSS that removes unused CSS from the final build\n * @param options - PurgeCSS configuration options\n * @returns AstroIntegration - The configured Astro integration\n */\nfunction Plugin(options: PurgeCSSOptions = {}): AstroIntegration {\n let config: AstroConfig;\n\n return {\n name: INTEGRATION_NAME,\n hooks: {\n 'astro:config:done': ({ config: cfg }) => {\n config = cfg;\n },\n 'astro:build:done': async ({ dir, pages, logger }) => {\n const buildMode = config.output;\n logger.info(`📦 Running in '${buildMode}' mode`);\n\n // Convert the URL to a filesystem path\n const outDir = cleanPath(dir);\n\n // Used to skip file rehashing for SSR/Hybrid modes\n const isSSR = buildMode !== 'static';\n\n // Validate required Astro configuration\n if (!outDir || !config.build.format || !config.build.assets) {\n logger.warn(\n `${INTEGRATION_NAME} requires the following astro.config options: 'outDir', 'build.format', 'build.assets'`\n );\n return;\n }\n\n // Run PurgeCSS on all CSS files\n // Replace is needed to make sure to pass correct glob format on windows machines\n const purgeResults = await new PurgeCSS().purge({\n css: [`${outDir}/**/*.css`.replace(/\\\\/g, '/')],\n defaultExtractor,\n ...options,\n content: [\n `${outDir}/**/*.html`.replace(/\\\\/g, '/'),\n `${outDir}/**/*.js`.replace(/\\\\/g, '/'),\n ...(options.content || [])\n ]\n });\n\n // Filter out non-CSS files from purge results\n const purgedCssFiles = purgeResults.filter(({ file }) =>\n file?.endsWith('.css')\n ) as Array<{\n css: string;\n file: string;\n }>;\n\n if (purgedCssFiles.length === 0) {\n logger.info('ℹ️ No CSS files found to process');\n return;\n }\n\n logger.info(\n `Found ${purgedCssFiles.length} CSS ${purgedCssFiles.length === 1 ? 'file' : 'files'} to process`\n );\n\n // Handle SSR/Hybrid mode\n if (isSSR) {\n await Promise.all(\n purgedCssFiles.map(async ({ css, file }) => {\n await writeCssFile(file, css, file);\n success(file.replace(outDir, ''));\n })\n );\n logger.info('🎉 Purging completed successfully!');\n return;\n }\n\n // Process files for static mode with content hashing\n let processedFiles = await Promise.all(\n purgedCssFiles.map(async ({ css, file }) => {\n const isAssetFile = file.includes(config.build.assets);\n\n // Skip rehashing for non-asset files (not generated by astro)\n // ex: assets/styles/light.css\n if (!isAssetFile) {\n await writeCssFile(file, css, file);\n const relativePath = file.replace(outDir, '');\n success(relativePath);\n return {\n oldFilename: relativePath,\n newFilename: relativePath\n };\n }\n\n // Generate new filename with content hash\n const hashedFilename = generateFileHash(file, css);\n await writeCssFile(hashedFilename, css, file);\n\n const relativeOldPath = file.replace(outDir, '');\n const relativeNewPath = hashedFilename.replace(outDir, '');\n success(relativeNewPath);\n\n return {\n oldFilename: relativeOldPath,\n newFilename: relativeNewPath\n };\n })\n );\n\n // Filter to only get files that actually changed\n const changedFiles = processedFiles.filter(\n ({ oldFilename, newFilename }) => oldFilename !== newFilename\n );\n\n if (changedFiles.length > 0) {\n logger.info(\n `Updating ${changedFiles.length} CSS ${changedFiles.length === 1 ? 'reference' : 'references'} in HTML files...`\n );\n // Get all HTML pages based on build format\n const htmlFiles = pages\n .filter((page) => typeof page.pathname === 'string')\n .map((page) => {\n const pathname = page.pathname as string;\n\n // Handle root/index page\n if (pathname === '') {\n return join(outDir, 'index.html');\n }\n\n // Handle custom 404 page (https://docs.astro.build/en/basics/astro-pages/#custom-404-error-page)\n if (pathname === '404/') {\n return join(outDir, '404.html');\n }\n\n switch (config.build.format) {\n case 'file':\n // Format: /blog -> /blog.html\n return join(outDir, `${pathname}.html`);\n\n case 'directory':\n // Format: /blog -> /blog/index.html\n return join(outDir, pathname, 'index.html');\n\n case 'preserve':\n // Check if direct HTML file exists, otherwise use directory format\n const directFile = join(outDir, `${pathname}.html`);\n return existsSync(directFile)\n ? directFile\n : join(outDir, pathname, 'index.html');\n }\n });\n\n // Update CSS references in HTML files\n await Promise.all(\n htmlFiles.map(async (htmlFile) => {\n let content = await readFileContent(htmlFile);\n\n for (const { oldFilename, newFilename } of changedFiles) {\n const normalizedOldPath = oldFilename.replace(/\\\\/g, '/');\n const normalizedNewPath = newFilename.replace(/\\\\/g, '/');\n \n content = content.replace(new RegExp(normalizedOldPath, 'g'), normalizedNewPath);\n }\n\n await writeFileContent(htmlFile, content);\n success(htmlFile.replace(outDir, ''));\n })\n );\n }\n\n logger.info('🎉 Purging completed successfully!');\n }\n }\n };\n}\n\nexport default Plugin;\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/.pnpm/kleur@4.1.5/node_modules/kleur/colors.mjs","../src/utils.ts","../src/index.ts"],"names":["FORCE_COLOR","NODE_DISABLE_COLORS","NO_COLOR","TERM","isTTY","$","init","x","y","rgx","open","close","txt","reset","dim","red","green","readFileContent","filePath","readFile","err","error","writeFileContent","content","writeFile","writeCssFile","newFilePath","css","oldFilePath","existsSync","unlink","generateFileHash","hash","createHash","cleanPath","file","path","fileURLToPath","dt","success","message","date","INTEGRATION_NAME","defaultExtractor","Plugin","options","config","cfg","dir","pages","logger","buildMode","outDir","isSSR","purgedCssFiles","PurgeCSS","changedFiles","relativePath","hashedFilename","relativeOldPath","relativeNewPath","oldFilename","newFilename","htmlFiles","page","pathname","join","directFile","htmlFile","normalizedOldPath","normalizedNewPath","index_default"],"mappings":"wMAAA,IAAIA,EAAaC,CAAqBC,CAAAA,CAAAA,CAAUC,CAAMC,CAA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I7C,CAAAA,CAAU,MAAMN,CAAAA,CAAgBmD,CAAQ,CAAA,CAE5C,IAAW,GAAA,CAAE,YAAAP,CAAa,CAAA,WAAA,CAAAC,CAAY,CAAA,GAAKN,CAAc,CAAA,CACvD,IAAMa,CAAoBR,CAAAA,CAAAA,CAAY,OAAQ,CAAA,KAAA,CAAO,GAAG,CAAA,CAClDS,EAAoBR,CAAY,CAAA,OAAA,CAAQ,KAAO,CAAA,GAAG,CAExDvC,CAAAA,CAAAA,CAAUA,CAAQ,CAAA,OAAA,CAAQ,IAAI,MAAA,CAAO8C,CAAmB,CAAA,GAAG,CAAGC,CAAAA,CAAiB,EACjF,CAEA,MAAMhD,CAAiB8C,CAAAA,CAAAA,CAAU7C,CAAO,CAAA,CACxCgB,EAAQ6B,CAAS,CAAA,OAAA,CAAQhB,CAAQ,CAAA,EAAE,CAAC,EACtC,CAAC,CACH,EACF,CAEAF,CAAAA,CAAO,IAAK,CAAA,2CAAoC,EAClD,CACF,CACF,CACF,CAEA,IAAOqB,EAAQ3B,CAAAA","file":"index.js","sourcesContent":["let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true;\nif (typeof process !== 'undefined') {\n\t({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env || {});\n\tisTTY = process.stdout && process.stdout.isTTY;\n}\n\nexport const $ = {\n\tenabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && (\n\t\tFORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY\n\t)\n}\n\nfunction init(x, y) {\n\tlet rgx = new RegExp(`\\\\x1b\\\\[${y}m`, 'g');\n\tlet open = `\\x1b[${x}m`, close = `\\x1b[${y}m`;\n\n\treturn function (txt) {\n\t\tif (!$.enabled || txt == null) return txt;\n\t\treturn open + (!!~(''+txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;\n\t};\n}\n\n// modifiers\nexport const reset = init(0, 0);\nexport const bold = init(1, 22);\nexport const dim = init(2, 22);\nexport const italic = init(3, 23);\nexport const underline = init(4, 24);\nexport const inverse = init(7, 27);\nexport const hidden = init(8, 28);\nexport const strikethrough = init(9, 29);\n\n// colors\nexport const black = init(30, 39);\nexport const red = init(31, 39);\nexport const green = init(32, 39);\nexport const yellow = init(33, 39);\nexport const blue = init(34, 39);\nexport const magenta = init(35, 39);\nexport const cyan = init(36, 39);\nexport const white = init(37, 39);\nexport const gray = init(90, 39);\nexport const grey = init(90, 39);\n\n// background colors\nexport const bgBlack = init(40, 49);\nexport const bgRed = init(41, 49);\nexport const bgGreen = init(42, 49);\nexport const bgYellow = init(43, 49);\nexport const bgBlue = init(44, 49);\nexport const bgMagenta = init(45, 49);\nexport const bgCyan = init(46, 49);\nexport const bgWhite = init(47, 49);\n","import { dim, green, red } from 'kleur/colors';\nimport { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { readFile, unlink, writeFile } from 'node:fs/promises';\nimport { fileURLToPath } from 'node:url';\n\nexport async function readFileContent(filePath: string): Promise<string> {\n try {\n const content = await readFile(filePath, 'utf8');\n return content;\n } catch (err) {\n error(`Error reading file ${filePath}: ${err}`);\n return '';\n }\n}\n\nexport async function writeFileContent(filePath: string, content: string) {\n try {\n await writeFile(filePath, content, 'utf8');\n } catch (err) {\n error(`Error writing file ${filePath}: ${err}`);\n }\n}\n\nexport async function writeCssFile(\n newFilePath: string,\n css: string,\n oldFilePath: string\n) {\n await writeFileContent(newFilePath, css);\n\n // Remove old file if it exists and is different from new file\n if (existsSync(oldFilePath) && oldFilePath !== newFilePath) {\n await unlink(oldFilePath);\n }\n}\n\nexport function generateFileHash(filePath: string, content: string) {\n // Get content hash before writing to file\n const hash = createHash('sha256').update(content).digest('hex').slice(0, 8);\n\n // Generate new file name with hash\n // Astro original hash is 8 characters long\n return `${filePath.slice(0, -13)}.${hash}.css`;\n}\n\n// Clean from extra slash on windows and trailing forward slash on non-windows\nexport function cleanPath(file: URL): string {\n if (!(file instanceof URL)) {\n throw new TypeError('Expected a URL object');\n }\n\n // Remove trailing forward slash if present\n let path = fileURLToPath(file).replace(/\\/+$/, '');\n\n // Remove leading forward slash on windows if present\n return process.platform === 'win32' ? path.replace(/^\\/+/, '') : path;\n}\n\nexport const dt = new Intl.DateTimeFormat('en-us', {\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n hour12: false\n});\n\nexport function success(message: string) {\n const date = dt.format(new Date());\n console.log(dim(date), green('▶'), message);\n}\n\nexport function error(message: string) {\n const date = dt.format(new Date());\n console.error(dim(date), red('■'), message);\n}\n","import type { AstroConfig, AstroIntegration } from 'astro';\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { PurgeCSS, type UserDefinedOptions } from 'purgecss';\n\nimport {\n cleanPath,\n generateFileHash,\n readFileContent,\n success,\n writeCssFile,\n writeFileContent\n} from './utils';\n\n/**\n * Extended PurgeCSS options interface that allows partial configuration\n * of the standard PurgeCSS options\n */\nexport interface PurgeCSSOptions extends Partial<UserDefinedOptions> {}\n\nconst INTEGRATION_NAME = 'astro-purgecss' as const;\n\n/**\n * default extractor to handle various CSS selector patterns\n * @param content string\n */\nconst defaultExtractor = (content: string) =>\n content.match(/[\\w-/:\\.#\\(\\),';%]+(?<!:)/g) || [];\n\n/**\n * Astro integration for PurgeCSS that removes unused CSS from the final build\n * @param options - PurgeCSS configuration options\n * @returns AstroIntegration - The configured Astro integration\n */\nfunction Plugin(options: PurgeCSSOptions = {}): AstroIntegration {\n let config: AstroConfig;\n\n return {\n name: INTEGRATION_NAME,\n hooks: {\n 'astro:config:done': ({ config: cfg }) => {\n config = cfg;\n },\n 'astro:build:done': async ({ dir, pages, logger }) => {\n const buildMode = config.output;\n logger.info(`📦 Running in '${buildMode}' mode`);\n\n // Convert the URL to a filesystem path\n const outDir = cleanPath(dir);\n\n // Used to skip file rehashing for SSR/Hybrid modes\n const isSSR = buildMode !== 'static';\n\n // Validate required Astro configuration\n if (!outDir || !config.build.format || !config.build.assets) {\n logger.warn(\n `${INTEGRATION_NAME} requires the following astro.config options: 'outDir', 'build.format', 'build.assets'`\n );\n return;\n }\n\n // Run PurgeCSS on all CSS files\n // Replace is needed to make sure to pass correct glob format on windows machines\n const purgeResults = await new PurgeCSS().purge({\n css: [`${outDir}/**/*.css`.replace(/\\\\/g, '/')],\n defaultExtractor,\n ...options,\n content: [\n `${outDir}/**/*.html`.replace(/\\\\/g, '/'),\n `${outDir}/**/*.js`.replace(/\\\\/g, '/'),\n ...(options.content || [])\n ]\n });\n\n // Filter out non-CSS files from purge results\n const purgedCssFiles = purgeResults.filter(({ file }) =>\n file?.endsWith('.css')\n ) as Array<{\n css: string;\n file: string;\n }>;\n\n if (purgedCssFiles.length === 0) {\n logger.info('ℹ️ No CSS files found to process');\n return;\n }\n\n logger.info(\n `Found ${purgedCssFiles.length} CSS ${purgedCssFiles.length === 1 ? 'file' : 'files'} to process`\n );\n\n // Handle SSR/Hybrid mode\n if (isSSR) {\n await Promise.all(\n purgedCssFiles.map(async ({ css, file }) => {\n await writeCssFile(file, css, file);\n success(file.replace(outDir, ''));\n })\n );\n logger.info('🎉 Purging completed successfully!');\n return;\n }\n\n // Process files for static mode with content hashing\n let processedFiles = await Promise.all(\n purgedCssFiles.map(async ({ css, file }) => {\n const isAssetFile = file.includes(config.build.assets);\n\n // Skip rehashing for non-asset files (not generated by astro)\n // ex: assets/styles/light.css\n if (!isAssetFile) {\n await writeCssFile(file, css, file);\n const relativePath = file.replace(outDir, '');\n success(relativePath);\n return {\n oldFilename: relativePath,\n newFilename: relativePath\n };\n }\n\n // Generate new filename with content hash\n const hashedFilename = generateFileHash(file, css);\n await writeCssFile(hashedFilename, css, file);\n\n const relativeOldPath = file.replace(outDir, '');\n const relativeNewPath = hashedFilename.replace(outDir, '');\n success(relativeNewPath);\n\n return {\n oldFilename: relativeOldPath,\n newFilename: relativeNewPath\n };\n })\n );\n\n // Filter to only get files that actually changed\n const changedFiles = processedFiles.filter(\n ({ oldFilename, newFilename }) => oldFilename !== newFilename\n );\n\n if (changedFiles.length > 0) {\n logger.info(\n `Updating ${changedFiles.length} CSS ${changedFiles.length === 1 ? 'reference' : 'references'} in HTML files...`\n );\n // Get all HTML pages based on build format\n const htmlFiles = pages\n .filter((page) => typeof page.pathname === 'string')\n .map((page) => {\n const pathname = page.pathname as string;\n\n // Handle root/index page\n if (pathname === '') {\n return join(outDir, 'index.html');\n }\n\n // Handle custom 404 page (https://docs.astro.build/en/basics/astro-pages/#custom-404-error-page)\n if (pathname === '404/') {\n return join(outDir, '404.html');\n }\n\n switch (config.build.format) {\n case 'file':\n // Format: /blog -> /blog.html\n return join(outDir, `${pathname}.html`);\n\n case 'directory':\n // Format: /blog -> /blog/index.html\n return join(outDir, pathname, 'index.html');\n\n case 'preserve':\n // Check if direct HTML file exists, otherwise use directory format\n const directFile = join(outDir, `${pathname}.html`);\n return existsSync(directFile)\n ? directFile\n : join(outDir, pathname, 'index.html');\n }\n });\n\n // Update CSS references in HTML files\n await Promise.all(\n htmlFiles.map(async (htmlFile) => {\n let content = await readFileContent(htmlFile);\n\n for (const { oldFilename, newFilename } of changedFiles) {\n const normalizedOldPath = oldFilename.replace(/\\\\/g, '/');\n const normalizedNewPath = newFilename.replace(/\\\\/g, '/');\n \n content = content.replace(new RegExp(normalizedOldPath, 'g'), normalizedNewPath);\n }\n\n await writeFileContent(htmlFile, content);\n success(htmlFile.replace(outDir, ''));\n })\n );\n }\n\n logger.info('🎉 Purging completed successfully!');\n }\n }\n };\n}\n\nexport default Plugin;\n"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "astro-purgecss",
|
|
3
3
|
"description": "Remove unused CSS rules from your final Astro bundle",
|
|
4
|
-
"version": "5.2.
|
|
4
|
+
"version": "5.2.3",
|
|
5
5
|
"homepage": "https://github.com/codiume/orbit",
|
|
6
6
|
"bugs": "https://github.com/codiume/orbit/issues",
|
|
7
7
|
"author": "codiume",
|