cook-ssg 2.0.0

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.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +445 -0
  3. package/bin/cook.js +66 -0
  4. package/package.json +75 -0
  5. package/patches/jsdom-fetch-fix.js +52 -0
  6. package/scripts/build.js +212 -0
  7. package/scripts/dev.js +119 -0
  8. package/scripts/plugins/apply-template.js +226 -0
  9. package/scripts/plugins/auto-components.js +215 -0
  10. package/scripts/plugins/bundle.js +338 -0
  11. package/scripts/plugins/copy-src.js +89 -0
  12. package/scripts/plugins/create-dir-from-file.js +144 -0
  13. package/scripts/plugins/create-dist.js +55 -0
  14. package/scripts/plugins/custom-plugins.js +118 -0
  15. package/scripts/plugins/declarative-shadow-dom.js +164 -0
  16. package/scripts/plugins/escape-code-blocks.js +54 -0
  17. package/scripts/plugins/generate-formats.js +361 -0
  18. package/scripts/plugins/generate-fragments.js +126 -0
  19. package/scripts/plugins/generate-sitemap-xml.js +216 -0
  20. package/scripts/plugins/minify-src.js +253 -0
  21. package/scripts/plugins/optimize-images.js +389 -0
  22. package/scripts/plugins/process-html-frontmatter.js +75 -0
  23. package/scripts/plugins/process-markdown.js +384 -0
  24. package/scripts/plugins/repeat-collection.js +296 -0
  25. package/scripts/plugins/replace-components.js +496 -0
  26. package/scripts/plugins/replace-external-link-protocol.js +171 -0
  27. package/scripts/plugins/replace-include.js +273 -0
  28. package/scripts/plugins/replace-inline.js +217 -0
  29. package/scripts/plugins/replace-template-strings.js +121 -0
  30. package/scripts/plugins/set-active-links.js +175 -0
  31. package/scripts/utils/config/config.js +277 -0
  32. package/scripts/utils/get-src/get-src.js +241 -0
  33. package/scripts/utils/logger/logger.js +47 -0
  34. package/scripts/utils/performance/performance.js +35 -0
  35. package/scripts/utils/spinner/spinner.js +112 -0
  36. package/scripts/utils/timer/timer.js +40 -0
  37. package/scripts/utils/util/util.js +719 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Prof Thomas Powell
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,445 @@
1
+ # Cook Build System
2
+
3
+ A static site build system with templating, bundling, and optimization features.
4
+
5
+ **Version:** 2.0.0
6
+ **License:** MIT
7
+ **Node.js:** >=18.0.0
8
+
9
+ [Getting Started](#getting-started) | [View/Run the site code](#viewrun-the-site-code) | [Environment Flags](#environment-flags) | [Build Process](#build-process) | [NPM Run Scripts](#npm-run-scripts)
10
+
11
+ ---
12
+
13
+ ## Getting Started
14
+
15
+ Run this in the terminal from your project's root:
16
+
17
+ ```bash
18
+ npm install
19
+ npm run dev
20
+ ```
21
+
22
+ This builds the site locally and runs it at `localhost:3000`, using BrowserSync for live reloading.
23
+
24
+ ### Project Structure
25
+
26
+ Your project should have the following structure:
27
+
28
+ ```
29
+ your-project/
30
+ ├── config/
31
+ │ ├── main.js # Build configuration overrides
32
+ │ └── data.js # Data for template string replacement
33
+ ├── src/ # Source files
34
+ │ ├── index.html
35
+ │ └── ...
36
+ └── package.json
37
+ ```
38
+
39
+ ---
40
+
41
+ ## View/Run the site code
42
+
43
+ There are different modes of viewing the site while working locally.
44
+
45
+ <details>
46
+ <summary>Running <strong>development</strong> mode locally (live reload)</summary><br>
47
+
48
+ To view your codebase locally, run `npm run dev`.
49
+
50
+ 1. This first runs `scripts/build.js`, which copies the `/src` files to `/dist`, and then modifies them per each active build plugin.
51
+ 2. After the `/dist` folder files are built, `scripts/dev.js` runs, which starts the BrowserSync live-reload server.
52
+
53
+ _[Note]:_ By default, files are not minified and link/script elements marked `[data-inline]` are not inlined (retain external file call).
54
+ This way, when using dev tools to inspect in `localhost`, you see the correct line numbers, etc.
55
+
56
+ _[Note]:_ Some functionality may be enabled or disabled only in this environment. In `package.json`, we specify a node environment variable to designate development-mode: `NODE_ENV=development npm run build && node scripts/dev.js`.
57
+ In the various build-plugin files, you'll then see some code affected via:<br>
58
+ `if (process.env.NODE_ENV === 'development')`<br>
59
+ or<br>
60
+ `if (process.env.NODE_ENV !== 'development')`.
61
+ </details>
62
+
63
+ ---
64
+
65
+ <details>
66
+ <summary>Running <strong>production</strong> mode locally (http-server)</summary><br>
67
+
68
+ To view the static, ready-for-production version of the site locally, run `npm run dev:prod`.
69
+
70
+ Instead of running BrowserSync live-reload, it instead runs `http-server` to be a simple, static server. This has the benefit of not injecting the 2 scripts BrowserSync adds, and emulates how the site should look and behave on the production server (pure-static site pages).
71
+ </details>
72
+
73
+ ---
74
+
75
+ <details>
76
+ <summary><strong>Production</strong> build only (no browser action)</summary><br>
77
+
78
+ If you just need to build the `/dist` directory with production optimizations (minification, inlining), run:
79
+
80
+ ```bash
81
+ NODE_ENV=production npm run build
82
+ ```
83
+ </details>
84
+
85
+ For both development modes, `dev` (BrowserSync - live reload) and `dev:prod` (http-server), the localhost port should be the same. Check the current port value in `package.json` under `config.devPort`, but by default it should be 3000: `localhost:3000`
86
+
87
+ ---
88
+
89
+ ## Environment Flags
90
+
91
+ Some site processes do not need to run every time locally, or they only need to run during deployment, etc. To accommodate this, some features are gated behind Node environment variables.
92
+
93
+ ### Deployment Environments
94
+
95
+ We specify 2 environments via environment variables: `development` and `production`. We use these to enable or disable parts of the build process, either from the core build code or custom, user plugins.
96
+
97
+ In the terminal, most `npm run xxxx` scripts already set which environment to use. You may also manually set them if necessary:
98
+
99
+ ```bash
100
+ NODE_ENV=development npm run build
101
+ NODE_ENV=production npm run build
102
+ ```
103
+
104
+ In a custom build plugin, you may use them in conditionals:
105
+
106
+ ```javascript
107
+ if (process.env.NODE_ENV === 'development') {
108
+ // development-only code
109
+ }
110
+ ```
111
+
112
+ ---
113
+
114
+ ## Build Process
115
+
116
+ The build process performs the following steps:
117
+
118
+ 1. **Creates `/dist`** - Removes existing dist folder and recreates it
119
+ 2. **Copies `/src` to `/dist`** - All source files are copied (excludes `.md` files)
120
+ 3. **Processes Markdown** - Converts `.md` files to `.html` with front matter support
121
+ 4. **Runs custom-user `before` plugins** - Runs once before file processing
122
+ 5. **Loops through each allowed file**, modifying contents per environment rules:
123
+ * Runs any custom-user `default` plugins (all plugins run per file)
124
+ * Replaces ES6 template strings (`${}`) with data from config
125
+ * Repeats elements for each item in collections (`[data-repeat]`)
126
+ * Adds missing `http://` protocol to external links
127
+ * Replaces include placeholders (`[data-include]`) with target source
128
+ * Replaces custom elements and `[data-component]` elements with templates
129
+ * Replaces inline placeholders (`[data-inline]`) with external source (production only)
130
+ * Sets `<a>` tags with matching `[href]` as active (`class="active"`)
131
+ * Sets `<a>` tags with partial `[href]` match as active parent (`class="active-parent"`)
132
+ * Stores link/script files marked for bundling (`[bundle]`)
133
+ * Minifies HTML, CSS, and JS source (production only)
134
+ 6. **Creates `sitemap.xml`** - Auto-generated in `/dist`
135
+ 7. **Creates bundled files** - `.css` and `.js` bundles are written
136
+ 8. **Runs custom-user `after` plugins** - Runs once after file processing
137
+
138
+ Many build settings can be customized in your project's `/config/main.js`.
139
+
140
+ ---
141
+
142
+ ## NPM Run Scripts
143
+
144
+ | Script | Description |
145
+ |--------|-------------|
146
+ | `npm run dev` | Development mode with BrowserSync live reload |
147
+ | `npm run dev:prod` | Production build + http-server for local preview |
148
+ | `npm run build` | Build only (uses NODE_ENV if set, defaults to development) |
149
+ | `npm test` | Run test suite |
150
+ | `npm run update:check` | Check for dependency updates |
151
+ | `npm run update:fix` | Update dependencies to latest versions |
152
+
153
+ ---
154
+
155
+ ## Configuration
156
+
157
+ ### `/config/main.js`
158
+
159
+ Override default build settings:
160
+
161
+ ```javascript
162
+ export default {
163
+ // Output directory (default: 'dist')
164
+ distPath: 'dist',
165
+
166
+ // Source directory (default: 'src')
167
+ srcPath: 'src',
168
+
169
+ // Sitemap configuration
170
+ sitemap: {
171
+ url: 'https://www.yoursite.com',
172
+ },
173
+
174
+ // Custom plugins
175
+ plugins: {
176
+ before: [], // Run before file loop
177
+ default: [], // Run for each file
178
+ after: [], // Run after file loop
179
+ },
180
+
181
+ // Files to watch for live reload
182
+ watch: [
183
+ '/assets/css/*.css',
184
+ '/**/*.html',
185
+ ],
186
+ };
187
+ ```
188
+
189
+ ### `/config/data.js`
190
+
191
+ Provide data for template string replacement:
192
+
193
+ ```javascript
194
+ export default {
195
+ siteTitle: 'My Website',
196
+ siteDescription: 'A great website',
197
+ // Use in HTML: ${siteTitle}
198
+ };
199
+ ```
200
+
201
+ ---
202
+
203
+ ## Features
204
+
205
+ ### Template Strings
206
+
207
+ Use ES6 template syntax in HTML files:
208
+
209
+ ```html
210
+ <title>${siteTitle}</title>
211
+ <meta name="description" content="${siteDescription}">
212
+ ```
213
+
214
+ ### Includes
215
+
216
+ Include partial HTML files:
217
+
218
+ ```html
219
+ <div data-include="/includes/header.html"></div>
220
+ ```
221
+
222
+ ### Inline Assets
223
+
224
+ Inline external CSS/JS in production:
225
+
226
+ ```html
227
+ <link rel="stylesheet" href="/assets/css/styles.css" data-inline>
228
+ <script src="/assets/js/app.js" data-inline></script>
229
+ ```
230
+
231
+ ### Bundling
232
+
233
+ Bundle multiple files into one:
234
+
235
+ ```html
236
+ <link rel="stylesheet" href="/assets/css/reset.css" data-bundle="main">
237
+ <link rel="stylesheet" href="/assets/css/styles.css" data-bundle="main">
238
+ <!-- Outputs: /assets/bundle/main.css -->
239
+ ```
240
+
241
+ ### Active Links
242
+
243
+ Automatically adds `class="active"` to links matching the current page URL.
244
+
245
+ ### Markdown
246
+
247
+ Convert `.md` files to HTML with front matter support. Markdown files in `/src` are processed and output as HTML to `/dist`.
248
+
249
+ **Basic Usage** (`/src/blog/my-post.md`):
250
+ ```markdown
251
+ ---
252
+ title: My Blog Post
253
+ date: 2024-03-15
254
+ description: A great article about something
255
+ layout: blog
256
+ tags:
257
+ - javascript
258
+ - tutorial
259
+ ---
260
+
261
+ # Welcome
262
+
263
+ This is my blog post content with **bold** and *italic* text.
264
+
265
+ ## Code Example
266
+
267
+ \`\`\`javascript
268
+ console.log('Hello, World!');
269
+ \`\`\`
270
+ ```
271
+
272
+ **Front Matter Variables:**
273
+ - `title` - Page title (auto-generated from filename if omitted)
274
+ - `date` - Publication date (used for sorting collections)
275
+ - `description` - Page description
276
+ - `layout` - Layout template to wrap content (optional)
277
+ - Any custom fields you need
278
+
279
+ **Output:** `/src/blog/my-post.md` → `/dist/blog/my-post/index.html`
280
+
281
+ **Layout Templates** (`/src/layouts/blog.html`):
282
+ ```html
283
+ <!DOCTYPE html>
284
+ <html>
285
+ <head>
286
+ <title>${title}</title>
287
+ <meta name="description" content="${description}">
288
+ </head>
289
+ <body>
290
+ <article>
291
+ ${content}
292
+ </article>
293
+ <time>${date}</time>
294
+ </body>
295
+ </html>
296
+ ```
297
+
298
+ **Collections:**
299
+ Markdown files are automatically grouped into collections by directory:
300
+ - `/src/blog/*.md` → `collections.blog`
301
+ - `/src/docs/*.md` → `collections.docs`
302
+
303
+ Access collections in templates:
304
+ ```html
305
+ <ul>
306
+ ${collections.blog.map(post => `
307
+ <li><a href="${post.url}">${post.title}</a></li>
308
+ `).join('')}
309
+ </ul>
310
+ ```
311
+
312
+ **Configuration** (`/config/main.js`):
313
+ ```javascript
314
+ export default {
315
+ markdown: {
316
+ // Default layout template (null = basic HTML wrapper)
317
+ layout: null,
318
+ // Directory for layout templates
319
+ layoutPath: 'layouts',
320
+ // Enable collections
321
+ collections: true,
322
+ // marked parser options
323
+ markedOptions: {
324
+ gfm: true, // GitHub Flavored Markdown
325
+ breaks: false, // Convert \n to <br>
326
+ },
327
+ },
328
+ };
329
+ ```
330
+
331
+ ### Repeat / Collections
332
+
333
+ Generate repeated elements from arrays or collections. Perfect for blog listings, navigation menus, and any list-based content.
334
+
335
+ **Basic Usage:**
336
+ ```html
337
+ <ul>
338
+ <li data-repeat="items as item">
339
+ <a href="${item.url}">${item.title}</a>
340
+ </li>
341
+ </ul>
342
+ ```
343
+
344
+ **With Markdown Collections:**
345
+ ```html
346
+ <!-- List all blog posts -->
347
+ <article data-repeat="collections.blog as post">
348
+ <h2><a href="${post.url}">${post.title}</a></h2>
349
+ <p>${post.description}</p>
350
+ <time>${post.date}</time>
351
+ </article>
352
+ ```
353
+
354
+ **With Index Variable:**
355
+ ```html
356
+ <ol>
357
+ <li data-repeat="items as item, index">
358
+ ${index}: ${item.name}
359
+ </li>
360
+ </ol>
361
+ ```
362
+
363
+ **Limit and Offset:**
364
+ ```html
365
+ <!-- Show only first 5 posts -->
366
+ <article data-repeat="collections.blog | limit:5 as post">
367
+ <h2>${post.title}</h2>
368
+ </article>
369
+
370
+ <!-- Skip first 2, show next 5 -->
371
+ <article data-repeat="collections.blog | offset:2 | limit:5 as post">
372
+ <h2>${post.title}</h2>
373
+ </article>
374
+ ```
375
+
376
+ **Data Sources:**
377
+ - `collections.blog` - From markdown files in `/src/blog/`
378
+ - `collections.docs` - From markdown files in `/src/docs/`
379
+ - `items` - From `/config/data.js`
380
+ - Any array in your data configuration
381
+
382
+ **Configuration** (`/config/main.js`):
383
+ ```javascript
384
+ export default {
385
+ repeat: {
386
+ // Attribute name (default: 'data-repeat')
387
+ attribute: 'data-repeat',
388
+ // Remove attribute from output (default: true)
389
+ removeAttribute: true,
390
+ },
391
+ };
392
+ ```
393
+
394
+ ### Components
395
+
396
+ Replace custom elements or semantic HTML elements with reusable templates. Supports two patterns:
397
+
398
+ **1. Custom Elements** (hyphenated tag names):
399
+ ```html
400
+ <site-header title="Welcome" subtitle="Home Page"></site-header>
401
+ <app-footer year="2024"></app-footer>
402
+ ```
403
+
404
+ **2. Semantic HTML with `data-component`**:
405
+ ```html
406
+ <header data-component="header" data-title="Welcome"></header>
407
+ <nav data-component="nav" data-active="home"></nav>
408
+ <footer data-component="footer" data-year="2024"></footer>
409
+ ```
410
+
411
+ **Component Templates** (`/src/components/header.html`):
412
+ ```html
413
+ <header class="site-header">
414
+ <h1>${title}</h1>
415
+ <p>${subtitle}</p>
416
+ ${slot}
417
+ </header>
418
+ ```
419
+
420
+ Template variables:
421
+ - `${attributeName}` - Data from element attributes (converted to camelCase)
422
+ - `${slot}` - Inner HTML content from the original element
423
+ - `${tagName}` - Original element's tag name
424
+
425
+ **Configuration** (`/config/main.js`):
426
+ ```javascript
427
+ export default {
428
+ components: {
429
+ // Path to components directory (default: 'components')
430
+ path: 'components',
431
+ // Optional prefix for custom elements (e.g., 'site-' matches <site-header>)
432
+ prefix: 'site-',
433
+ // Explicit mapping of element names to template files
434
+ mapping: {
435
+ 'app-nav': 'navigation.html',
436
+ },
437
+ },
438
+ };
439
+ ```
440
+
441
+ ---
442
+
443
+ ## License
444
+
445
+ MIT © 2020 Prof Thomas Powell
package/bin/cook.js ADDED
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { execSync } from 'node:child_process';
4
+ import { fileURLToPath } from 'node:url';
5
+ import path from 'node:path';
6
+ import { createRequire } from 'node:module';
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = path.dirname(__filename);
10
+ const require = createRequire(import.meta.url);
11
+ const pkg = require('../package.json');
12
+
13
+ const buildScript = path.resolve(__dirname, '..', 'scripts', 'build.js');
14
+ const devScript = path.resolve(__dirname, '..', 'scripts', 'dev.js');
15
+
16
+ const [,, command, ...args] = process.argv;
17
+
18
+ function showHelp() {
19
+ console.log(`
20
+ cook-ssg v${pkg.version} — Static site generation the web platform way
21
+
22
+ Usage:
23
+ cook build Build the site (production)
24
+ cook dev Build + live-reload dev server
25
+ cook dev --port N Dev server on a custom port (default: 3000)
26
+ cook --help Show this help
27
+ cook --version Show version
28
+ `);
29
+ }
30
+
31
+ switch (command) {
32
+ case 'build': {
33
+ const env = { ...process.env, NODE_ENV: process.env.NODE_ENV || 'production' };
34
+ execSync(`node "${buildScript}"`, { stdio: 'inherit', env });
35
+ break;
36
+ }
37
+
38
+ case 'dev': {
39
+ // Parse --port flag
40
+ const portIdx = args.indexOf('--port');
41
+ const port = portIdx !== -1 ? args[portIdx + 1] : undefined;
42
+ const env = { ...process.env, NODE_ENV: 'development' };
43
+ if (port) env.COOK_DEV_PORT = port;
44
+
45
+ // Run build first, then start dev server
46
+ execSync(`node "${buildScript}"`, { stdio: 'inherit', env });
47
+ execSync(`node "${devScript}"`, { stdio: 'inherit', env });
48
+ break;
49
+ }
50
+
51
+ case '--version':
52
+ case '-v':
53
+ console.log(pkg.version);
54
+ break;
55
+
56
+ case '--help':
57
+ case '-h':
58
+ case undefined:
59
+ showHelp();
60
+ break;
61
+
62
+ default:
63
+ console.error(`Unknown command: ${command}`);
64
+ showHelp();
65
+ process.exit(1);
66
+ }
package/package.json ADDED
@@ -0,0 +1,75 @@
1
+ {
2
+ "name": "cook-ssg",
3
+ "version": "2.0.0",
4
+ "description": "Cook your static pages into a beautifully performing site. Static site generation the web platform way.",
5
+ "type": "module",
6
+ "bin": {
7
+ "cook": "./bin/cook.js"
8
+ },
9
+ "main": "./scripts/build.js",
10
+ "exports": {
11
+ ".": "./scripts/build.js",
12
+ "./build": "./scripts/build.js",
13
+ "./dev": "./scripts/dev.js"
14
+ },
15
+ "files": [
16
+ "bin/",
17
+ "scripts/",
18
+ "patches/",
19
+ "LICENSE",
20
+ "README.md"
21
+ ],
22
+ "scripts": {
23
+ "postinstall": "node patches/jsdom-fetch-fix.js",
24
+ "build": "node scripts/build.js",
25
+ "dev": "NODE_ENV=development npm run build && node scripts/dev.js",
26
+ "dev:prod": "NODE_ENV=production npm run build && npx http-server ./dist -p 3000",
27
+ "test": "node --test test/*.test.js",
28
+ "test:watch": "node --test --watch test/*.test.js",
29
+ "reset": "rm -rf node_modules",
30
+ "reset:install": "npm run reset && npm install",
31
+ "update:check": "ncu",
32
+ "update:fix": "ncu -u"
33
+ },
34
+ "engines": {
35
+ "node": ">=18.0.0"
36
+ },
37
+ "keywords": [
38
+ "static-site-generator",
39
+ "ssg",
40
+ "web-components",
41
+ "web-platform",
42
+ "vanilla-breeze"
43
+ ],
44
+ "author": "Prof. Powell",
45
+ "license": "MIT",
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "git+https://github.com/ProfPowell/cook.git"
49
+ },
50
+ "homepage": "https://github.com/ProfPowell/cook#readme",
51
+ "bugs": {
52
+ "url": "https://github.com/ProfPowell/cook/issues"
53
+ },
54
+ "dependencies": {
55
+ "browser-sync": "^3.0.4",
56
+ "chalk": "^5.4.1",
57
+ "clean-css": "^5.3.3",
58
+ "cli-cursor": "^5.0.0",
59
+ "cli-spinners": "^3.3.0",
60
+ "fs-extra": "^11.3.2",
61
+ "gray-matter": "^4.0.3",
62
+ "html-minifier-terser": "^7.2.0",
63
+ "jsdom": "^27.3.0",
64
+ "lodash.clonedeep": "^4.5.0",
65
+ "lodash.merge": "^4.6.2",
66
+ "marked": "^17.0.1",
67
+ "rimraf": "^6.1.2",
68
+ "sharp": "^0.34.5",
69
+ "terser": "^5.44.1"
70
+ },
71
+ "devDependencies": {
72
+ "http-server": "^14.1.1",
73
+ "npm-check-updates": "^19.2.0"
74
+ }
75
+ }
@@ -0,0 +1,52 @@
1
+ // jsdom fetch fix patch
2
+ // See original issue: https://github.com/jsdom/jsdom/pull/2510
3
+ // Note: This patch may no longer be needed in jsdom 27.x+ as the fix was merged upstream.
4
+ // The patch will silently skip if the target file structure has changed.
5
+
6
+ import fs from 'fs-extra';
7
+ import { fileURLToPath } from 'node:url';
8
+ import path from 'node:path';
9
+
10
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
11
+
12
+ // Resolve jsdom relative to Cook's own node_modules (works whether Cook is
13
+ // the project root or installed as a dependency inside another project)
14
+ const filePath = path.resolve(__dirname, '..', 'node_modules', 'jsdom', 'lib', 'jsdom', 'browser', 'resources', 'per-document-resource-loader.js');
15
+
16
+ try {
17
+ // Check if file exists first
18
+ if (!fs.existsSync(filePath)) {
19
+ // File doesn't exist - jsdom structure may have changed, skip patch
20
+ console.log('[jsdom-patch] Target file not found, skipping patch (may not be needed in this jsdom version)');
21
+ process.exit(0);
22
+ }
23
+
24
+ let src = fs.readFileSync(filePath, 'utf-8');
25
+
26
+ // Check if patch is already applied
27
+ if (src.includes('if (this._resourceLoader === null) return null;')) {
28
+ console.log('[jsdom-patch] Patch already applied, skipping');
29
+ process.exit(0);
30
+ }
31
+
32
+ // Find target and add fix immediately inside the `fetch()` callback
33
+ const fetchRegex = /fetch\(url,\s*{\s*element,\s*onLoad,\s*onError\s*}\)\s*{/gm;
34
+
35
+ if (!fetchRegex.test(src)) {
36
+ console.log('[jsdom-patch] Target pattern not found, skipping patch (may not be needed in this jsdom version)');
37
+ process.exit(0);
38
+ }
39
+
40
+ // Reset regex lastIndex after test
41
+ fetchRegex.lastIndex = 0;
42
+
43
+ src = src.replace(fetchRegex, `fetch(url, { element, onLoad, onError }) { if (this._resourceLoader === null) return null;`);
44
+
45
+ // Write new src back to file
46
+ fs.writeFileSync(filePath, src, 'utf-8');
47
+ console.log('[jsdom-patch] Patch applied successfully');
48
+ }
49
+ catch (err) {
50
+ console.warn('[jsdom-patch] Warning: Could not apply jsdom patch:', err.message);
51
+ // Don't fail the install, just warn
52
+ }