cbst 0.1.1 → 0.2.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,20 @@
1
+ # Changelog
2
+
3
+ # 0.2.1
4
+
5
+ - Ignore `mailto:` and other protocols properly
6
+ - Update deps
7
+
8
+ # 0.2.0
9
+
10
+ - Exit with code 1 on errors (including unresolved references)
11
+ - Support source map references
12
+ - Fix glob prefix
13
+
14
+ # 0.1.1
15
+
16
+ - Fix binary
17
+
18
+ # 0.1.0
19
+
20
+ - Initial version
package/LICENSE.md CHANGED
@@ -1,4 +1,4 @@
1
- Copyright 2022 Morris Brodersen <mb@morrisbrodersen.de>
1
+ Copyright 2022-2023 Morris Brodersen <mb@morrisbrodersen.de>
2
2
 
3
3
  Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
4
4
 
package/README.md CHANGED
@@ -25,20 +25,20 @@ cbst <input dir> <output dir> [<config file>]
25
25
  This diff demonstrates how versioning is applied to a simple website:
26
26
 
27
27
  ```diff
28
- # index.html
28
+ # /index.html
29
29
 
30
30
  <!DOCTYPE html>
31
31
  <html>
32
32
  <head>
33
33
  <title>Hello, World!</title>
34
- - <link rel="stylesheet" href="styles/main.css">
35
- + <link rel="stylesheet" href="styles/main.ed1e118152.css">
34
+ - <link rel="stylesheet" href="/styles/main.css">
35
+ + <link rel="stylesheet" href="/styles/main.ed1e118152.css">
36
36
  </head>
37
37
  <body>
38
38
  <h1>Hello, World!</h1>
39
39
  <p>
40
- - <img id="welcome" src="assets/loading.png">
41
- + <img id="welcome" src="assets/loading.834ab3df39.png">
40
+ - <img id="welcome" src="/assets/loading.svg">
41
+ + <img id="welcome" src="/assets/loading.834ab3df39.svg">
42
42
  </p>
43
43
  <script type="module">
44
44
  - import { main } from './scripts/main.js';
@@ -49,19 +49,19 @@ This diff demonstrates how versioning is applied to a simple website:
49
49
  </body>
50
50
  </html>
51
51
 
52
- # scripts/main.js -> scripts/main.f39e95e656.js
52
+ # /scripts/main.js -> /scripts/main.f39e95e656.js
53
53
 
54
- - import { yell } from './yell.js';
55
- + import { yell } from './yell.93724d33b5.js';
54
+ - import { hello } from './hello.js';
55
+ + import { hello } from './hello.93724d33b5.js';
56
56
 
57
57
  export function main() {
58
- yell('hello');
59
- - document.getElementById('welcome').src = 'assets/welcome.svg';
60
- + document.getElementById('welcome').src = 'assets/welcome.afe45bb832.svg';
58
+ hello('world');
59
+ - document.getElementById('welcome').src = '/assets/welcome.svg';
60
+ + document.getElementById('welcome').src = '/assets/welcome.afe45bb832.svg';
61
61
  }
62
62
 
63
- # styles/main.css -> styles/main.ed1e118152.css
64
- # scripts/yell.js -> scripts/yell.93724d33b5.js
63
+ # /styles/main.css -> /styles/main.ed1e118152.css
64
+ # /scripts/hello.js -> /scripts/hello.93724d33b5.js
65
65
  # etc.
66
66
  ```
67
67
 
@@ -1,11 +1,13 @@
1
1
  /// <reference types="node" />
2
2
  /// <reference types="node" />
3
+ /// <reference types="node" />
4
+ import EventEmitter from 'events';
3
5
  import { Cache } from './util/Cache';
4
6
  import { Glob } from './util/Glob';
5
7
  export interface CacheBusterConfig {
6
8
  /**
7
9
  * List of file patterns to exclude entirely.
8
- * Defaults to an `[]`.
10
+ * Defaults to `[]`.
9
11
  */
10
12
  exclude?: string[];
11
13
  /**
@@ -43,17 +45,11 @@ export interface CacheBusterOptions extends CacheBusterConfig {
43
45
  * Output directory
44
46
  */
45
47
  outputDir: string;
46
- /**
47
- * Error handler
48
- */
49
- onError?: ErrorHandler;
50
48
  }
51
- export type ErrorHandler = (err: Error) => unknown;
52
- export declare class CacheBuster {
49
+ export declare class CacheBuster extends EventEmitter {
53
50
  static defaultConfig: Required<CacheBusterConfig>;
54
51
  protected inputDir: string;
55
52
  protected outputDir: string;
56
- protected onError?: ErrorHandler;
57
53
  protected excludeGlob: Glob;
58
54
  protected sourceGlob: Glob;
59
55
  protected htmlGlob: Glob;
@@ -64,8 +60,10 @@ export declare class CacheBuster {
64
60
  protected getReferencesCache: Cache<string[]>;
65
61
  protected hashRawFileCache: Cache<string>;
66
62
  protected readFileCache: Cache<Buffer>;
67
- protected map: Record<string, string>;
63
+ protected map: Map<string, string>;
64
+ protected unresolved: Map<string, Set<string>>;
68
65
  protected referenceRx: RegExp;
66
+ protected externalReferenceRx: RegExp;
69
67
  protected baseRx: RegExp;
70
68
  protected extensionRx: RegExp;
71
69
  constructor(options: CacheBusterOptions);
@@ -77,9 +75,9 @@ export declare class CacheBuster {
77
75
  hashFile(file: string): Promise<string | undefined>;
78
76
  hashFileReferences(file: string, exclude: string[]): Promise<string[]>;
79
77
  hashRawFile(file: string): Promise<string>;
80
- handleReferenceError(err: Error, source: string, reference: string): void;
78
+ handleReferenceError(error: Error, source: string, reference: string): void;
81
79
  getReferences(file: string): Promise<string[]>;
82
- isReference(reference: string): boolean;
80
+ isResolvableReference(reference: string): boolean;
83
81
  resolveReference(base: string, reference: string): string;
84
82
  getBase(file: string): Promise<string>;
85
83
  formatVersion(hash: string): string;
@@ -1,27 +1,32 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.CacheBuster = void 0;
4
7
  const crypto_1 = require("crypto");
8
+ const events_1 = __importDefault(require("events"));
5
9
  const fs_1 = require("fs");
6
10
  const path_1 = require("path");
7
11
  const ReferenceError_1 = require("./ReferenceError");
8
- const assert_1 = require("./util/assert");
9
12
  const Cache_1 = require("./util/Cache");
10
13
  const Glob_1 = require("./util/Glob");
11
- class CacheBuster {
14
+ class CacheBuster extends events_1.default {
12
15
  constructor(options) {
16
+ super();
13
17
  this.hashFileCache = new Cache_1.Cache((file) => this.hashFile(file));
14
18
  this.getReferencesCache = new Cache_1.Cache((file) => this.getReferences(file));
15
19
  this.hashRawFileCache = new Cache_1.Cache((file) => this.hashRawFile(file));
16
20
  this.readFileCache = new Cache_1.Cache((file) => this.readFile(file));
17
- this.map = {};
18
- this.referenceRx = /((")(([^"\s]+)\.([a-zA-Z0-9]+))")|((')(([^'\s]+)\.([a-zA-Z0-9]+))')/g;
21
+ this.map = new Map();
22
+ this.unresolved = new Map();
23
+ this.referenceRx = /((")(([^"\s]+)\.([a-zA-Z0-9]+))")|((')(([^'\s]+)\.([a-zA-Z0-9]+))')|# sourceMappingURL=(([^\s]+)\.([a-zA-Z0-9]+))/g;
24
+ this.externalReferenceRx = /^([a-zA-Z0-9]+:|\/\/)/;
19
25
  this.baseRx = /<base[^<>]+href\s*=\s*"([^"]+)"[^<>]*>/i;
20
26
  this.extensionRx = /(?<=\.)[^.]+$/;
21
27
  const o = { ...CacheBuster.defaultConfig, ...options };
22
28
  this.inputDir = o.inputDir;
23
29
  this.outputDir = o.outputDir;
24
- this.onError = o.onError;
25
30
  this.excludeGlob = new Glob_1.Glob(o.exclude);
26
31
  this.sourceGlob = new Glob_1.Glob(o.source);
27
32
  this.htmlGlob = new Glob_1.Glob(o.html);
@@ -34,7 +39,7 @@ class CacheBuster {
34
39
  await this.writeManifest();
35
40
  }
36
41
  async writeManifest() {
37
- await this.writeFile(this.manifest, JSON.stringify({ map: this.map }));
42
+ await this.writeFile(this.manifest, JSON.stringify({ map: Object.fromEntries(this.map.entries()) }));
38
43
  }
39
44
  async handleDir(dir) {
40
45
  if (this.excludeGlob.match(dir))
@@ -58,7 +63,7 @@ class CacheBuster {
58
63
  const outputFile = hash
59
64
  ? file.replace(this.extensionRx, (extension) => `${this.formatVersion(hash)}.${extension}`)
60
65
  : file;
61
- this.map[file] = outputFile;
66
+ this.map.set(file, outputFile);
62
67
  await this.writeFile(outputFile, output);
63
68
  if (!this.sourceGlob.match(file)) {
64
69
  this.readFileCache.delete(file);
@@ -78,14 +83,17 @@ class CacheBuster {
78
83
  let i = 0;
79
84
  return source.replace(this.referenceRx, (match, ...groups) => {
80
85
  const quote = groups[1] || groups[6];
81
- const reference = groups[2] || groups[7];
82
- const filename = groups[3] || groups[8];
83
- const extension = groups[4] || groups[9];
84
- if (!this.isReference(reference))
86
+ const reference = groups[2] || groups[7] || groups[10];
87
+ const filename = groups[3] || groups[8] || groups[11];
88
+ const extension = groups[4] || groups[9] || groups[12];
89
+ if (!this.isResolvableReference(reference))
85
90
  return match;
86
91
  const hash = hashes[i++];
87
92
  if (!hash)
88
93
  return match;
94
+ if (groups[10]) {
95
+ return `# sourceMappingURL=${filename}.${this.formatVersion(hash)}.${extension}`;
96
+ }
89
97
  return `${quote}${filename}.${this.formatVersion(hash)}.${extension}${quote}`;
90
98
  });
91
99
  }
@@ -105,17 +113,26 @@ class CacheBuster {
105
113
  this.handleReferenceError(err, file, it);
106
114
  return '';
107
115
  })));
108
- const deep = await Promise.all(references.map((it) => this.hashFileReferences(it, [...exclude, file])));
116
+ const deep = await Promise.all(references.map((it) => this.hashFileReferences(it, [...exclude, file]).catch((err) => {
117
+ this.handleReferenceError(err, file, it);
118
+ return [];
119
+ })));
109
120
  return [...direct, ...deep.flat()];
110
121
  }
111
122
  async hashRawFile(file) {
112
123
  const buffer = await this.readFileCache.get(file);
113
124
  return this.hash([buffer]);
114
125
  }
115
- handleReferenceError(err, source, reference) {
116
- if (this.onError) {
117
- this.onError?.(new ReferenceError_1.ReferenceError(err, source, reference));
126
+ handleReferenceError(error, source, reference) {
127
+ let unresolved = this.unresolved.get(source);
128
+ if (!unresolved) {
129
+ unresolved = new Set();
130
+ this.unresolved.set(source, unresolved);
118
131
  }
132
+ if (unresolved.has(reference))
133
+ return;
134
+ unresolved.add(reference);
135
+ this.emit('error', new ReferenceError_1.ReferenceError(error, source, reference));
119
136
  }
120
137
  // references
121
138
  async getReferences(file) {
@@ -126,15 +143,15 @@ class CacheBuster {
126
143
  const base = await this.getBase(file);
127
144
  const references = [];
128
145
  for (const match of source.matchAll(this.referenceRx)) {
129
- const reference = match[3] || match[8];
130
- if (this.isReference(reference)) {
146
+ const reference = match[3] || match[8] || match[11];
147
+ if (this.isResolvableReference(reference)) {
131
148
  references.push(this.resolveReference(base, reference));
132
149
  }
133
150
  }
134
151
  return references;
135
152
  }
136
- isReference(reference) {
137
- return !reference.includes('//');
153
+ isResolvableReference(reference) {
154
+ return !reference.match(this.externalReferenceRx);
138
155
  }
139
156
  resolveReference(base, reference) {
140
157
  if (reference[0] === '/')
@@ -177,11 +194,12 @@ class CacheBuster {
177
194
  }
178
195
  safePath(rootDir, candidate) {
179
196
  const s = path_1.posix.normalize(path_1.posix.join(rootDir, candidate));
180
- (0, assert_1.assert)(s.indexOf(rootDir) === 0, `Trying to access file outside of ${rootDir}: ${candidate}`);
197
+ if (s.indexOf(rootDir) !== 0) {
198
+ throw new Error(`Trying to access file outside of ${rootDir}: ${candidate}`);
199
+ }
181
200
  return s;
182
201
  }
183
202
  }
184
- exports.CacheBuster = CacheBuster;
185
203
  CacheBuster.defaultConfig = {
186
204
  exclude: [],
187
205
  source: ['*.html', '*.css', '*.js', '*.svg'],
@@ -190,3 +208,4 @@ CacheBuster.defaultConfig = {
190
208
  manifest: '.manifest.json',
191
209
  hashLength: 10,
192
210
  };
211
+ exports.CacheBuster = CacheBuster;
@@ -3,7 +3,7 @@ import { ConsoleLike } from './util/ConsoleLike';
3
3
  export declare class CacheBusterCli {
4
4
  protected console: ConsoleLike;
5
5
  constructor(console?: ConsoleLike);
6
- run(argv: string[], noExit?: boolean): Promise<void>;
6
+ run(argv: string[]): Promise<number>;
7
7
  help(): string;
8
8
  loadConfig(file: string): Promise<CacheBusterConfig>;
9
9
  }
@@ -3,16 +3,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CacheBusterCli = void 0;
4
4
  const fs_1 = require("fs");
5
5
  const CacheBuster_1 = require("./CacheBuster");
6
- const assert_1 = require("./util/assert");
6
+ const isRecord_1 = require("./util/isRecord");
7
+ const isStringArray_1 = require("./util/isStringArray");
7
8
  class CacheBusterCli {
8
9
  constructor(console = global.console) {
9
10
  this.console = console;
10
11
  }
11
- async run(argv, noExit = false) {
12
+ async run(argv) {
12
13
  try {
13
14
  if (argv.includes('--help')) {
14
15
  this.console.log(this.help());
15
- return;
16
+ return 0;
16
17
  }
17
18
  const [inputDir, outputDir, configFile] = argv;
18
19
  if (!inputDir)
@@ -24,16 +25,19 @@ class CacheBusterCli {
24
25
  ...config,
25
26
  inputDir,
26
27
  outputDir,
27
- onError: (err) => this.console.error(`Warning: ${err.message}`),
28
+ });
29
+ let exitCode = 0;
30
+ cacheBuster.on('error', (err) => {
31
+ this.console.error(err.message);
32
+ exitCode = 1;
28
33
  });
29
34
  await cacheBuster.run();
35
+ return exitCode;
30
36
  }
31
37
  catch (err) {
32
38
  this.console.error(err instanceof Error ? err.message : `${err}`);
33
39
  this.console.error(this.help());
34
- if (noExit)
35
- throw err;
36
- process.exit(1);
40
+ return 1;
37
41
  }
38
42
  }
39
43
  help() {
@@ -42,13 +46,27 @@ class CacheBusterCli {
42
46
  }
43
47
  async loadConfig(file) {
44
48
  const config = JSON.parse(await fs_1.promises.readFile(file, 'utf-8'));
45
- (0, assert_1.assertRecord)(config, 'Config must be an object');
46
- (0, assert_1.assertStringArray)(config.exclude ?? [], '"exclude" must be an array of strings');
47
- (0, assert_1.assertStringArray)(config.sources ?? [], '"sources" must be an array of strings');
48
- (0, assert_1.assertStringArray)(config.html ?? [], '"html" must be an array of strings');
49
- (0, assert_1.assertStringArray)(config.dynamic ?? [], '"dynamic" must be an array of strings');
50
- (0, assert_1.assertString)(config.manifest ?? '', '"manifest" must be a string');
51
- (0, assert_1.assertNumber)(config.hashLength ?? 10, '"hashLength" must be number');
49
+ if (!(0, isRecord_1.isRecord)(config)) {
50
+ throw new Error('Config must be an object');
51
+ }
52
+ if (!(0, isStringArray_1.isStringArray)(config.exclude ?? [])) {
53
+ throw new Error('"exclude" must be an array of strings');
54
+ }
55
+ if (!(0, isStringArray_1.isStringArray)(config.sources ?? [])) {
56
+ throw new Error('"sources" must be an array of strings');
57
+ }
58
+ if (!(0, isStringArray_1.isStringArray)(config.html ?? [])) {
59
+ throw new Error('"html" must be an array of strings');
60
+ }
61
+ if (!(0, isStringArray_1.isStringArray)(config.dynamic ?? [])) {
62
+ throw new Error('"dynamic" must be an array of strings');
63
+ }
64
+ if (typeof (config.manifest ?? '') !== 'string') {
65
+ throw new Error('"manifest" must be a string');
66
+ }
67
+ if (typeof (config.hashLength ?? 10) !== 'number') {
68
+ throw new Error('"hashLength" must be number');
69
+ }
52
70
  return config;
53
71
  }
54
72
  }
@@ -1,6 +1,10 @@
1
1
  export declare class ReferenceError extends Error {
2
- originalError: Error;
2
+ originalError: Error & {
3
+ code?: string;
4
+ };
3
5
  source: string;
4
6
  reference: string;
5
- constructor(originalError: Error, source: string, reference: string);
7
+ constructor(originalError: Error & {
8
+ code?: string;
9
+ }, source: string, reference: string);
6
10
  }
@@ -3,7 +3,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ReferenceError = void 0;
4
4
  class ReferenceError extends Error {
5
5
  constructor(originalError, source, reference) {
6
- super(`Could not resolve reference ${reference} from ${source} (${originalError.message})`);
6
+ super(originalError.code === 'ENOENT'
7
+ ? `Could not resolve ${reference} from ${source}`
8
+ : `Could not resolve ${reference} from ${source} (${originalError.message})`);
7
9
  this.originalError = originalError;
8
10
  this.source = source;
9
11
  this.reference = reference;
package/dist/util/Glob.js CHANGED
@@ -21,7 +21,7 @@ class Glob {
21
21
  }
22
22
  compile(pattern) {
23
23
  const inverted = !!pattern.match(/^!/);
24
- const absolutePrefix = pattern.match(/^!?\//) ? '^' : '';
24
+ const prefix = pattern.match(/^!?\//) ? '^' : '(^|/)';
25
25
  const rxBase = pattern
26
26
  .slice(inverted ? 1 : 0)
27
27
  .replace(/(\/\*\*\/)|(\*\*)|(\*)|([.+])/g, (_, ...groups) => {
@@ -41,7 +41,7 @@ class Glob {
41
41
  return `\\${groups[3]}`;
42
42
  }
43
43
  });
44
- const rx = new RegExp(absolutePrefix + rxBase + '$');
44
+ const rx = new RegExp(prefix + rxBase + '$');
45
45
  return {
46
46
  inverted,
47
47
  rx,
@@ -0,0 +1 @@
1
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isRecord = void 0;
4
+ function isRecord(value) {
5
+ return typeof value === 'object' && !!value && !Array.isArray(value);
6
+ }
7
+ exports.isRecord = isRecord;
@@ -0,0 +1 @@
1
+ export declare function isStringArray(value: unknown): value is string[];
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isStringArray = void 0;
4
+ function isStringArray(value) {
5
+ return Array.isArray(value) && value.every((it) => typeof it === 'string');
6
+ }
7
+ exports.isStringArray = isStringArray;
package/package.json CHANGED
@@ -1,7 +1,12 @@
1
1
  {
2
2
  "name": "cbst",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "A cache buster that versions a website's files for immutable cache control",
5
+ "keywords": [
6
+ "versioning",
7
+ "revving",
8
+ "cache busting"
9
+ ],
5
10
  "author": "Morris Brodersen <mb@morrisbrodersen.de>",
6
11
  "license": "ISC",
7
12
  "repository": {
@@ -20,7 +25,7 @@
20
25
  "build": "tsc --project tsconfig.build.json",
21
26
  "clean": "rm -rf coverage dist test/fixtures/out",
22
27
  "lint": "eslint .",
23
- "format": "pretter --write .",
28
+ "format": "prettier --write .",
24
29
  "format-check": "prettier --check .",
25
30
  "test": "jest --runInBand --coverage",
26
31
  "maybe-publish": "bash scripts/maybe-publish.sh"
@@ -35,6 +40,6 @@
35
40
  "prettier": "^2.6.2",
36
41
  "ts-jest": "^29.0.3",
37
42
  "ts-node": "^10.9.1",
38
- "typescript": "^4.6.4"
43
+ "typescript": "^5.0.4"
39
44
  }
40
45
  }
@@ -1,5 +0,0 @@
1
- export declare function assertRecord(value: unknown, message: string): asserts value is Record<string, unknown>;
2
- export declare function assertString(value: unknown, message: string): asserts value is string;
3
- export declare function assertStringArray(value: unknown, message: string): asserts value is string[];
4
- export declare function assertNumber(value: unknown, message: string): void;
5
- export declare function assert(condition: boolean, message: string): asserts condition;
@@ -1,25 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.assert = exports.assertNumber = exports.assertStringArray = exports.assertString = exports.assertRecord = void 0;
4
- const assert_1 = require("assert");
5
- function assertRecord(value, message) {
6
- assert(typeof value === 'object' && !!value && !Array.isArray(value), message);
7
- }
8
- exports.assertRecord = assertRecord;
9
- function assertString(value, message) {
10
- assert(typeof value === 'string', message);
11
- }
12
- exports.assertString = assertString;
13
- function assertStringArray(value, message) {
14
- assert(Array.isArray(value) && value.every((it) => typeof it === 'string'), message);
15
- }
16
- exports.assertStringArray = assertStringArray;
17
- function assertNumber(value, message) {
18
- assert(typeof value === 'number' && isFinite(value), message);
19
- }
20
- exports.assertNumber = assertNumber;
21
- function assert(condition, message) {
22
- if (!condition)
23
- throw new assert_1.AssertionError({ message });
24
- }
25
- exports.assert = assert;