cbst 0.2.2 → 1.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.
package/LICENSE.md CHANGED
@@ -1,4 +1,4 @@
1
- Copyright 2022-2023 Morris Brodersen <mb@morrisbrodersen.de>
1
+ Copyright 2022-2024 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
@@ -74,25 +74,25 @@ The configuration file (JSON) supports the following properties:
74
74
  - Defaults to `[]`.
75
75
  - `source`
76
76
  - List of file patterns to treat as sources with references to other files.
77
- - Defaults to `['*.html', '*.css', '*.js', '*.svg']`.
77
+ - Defaults to `["*.html", "*.css", "*.js", "*.svg", "*.json"]`.
78
78
  - `html`
79
79
  - List of file patterns to treat as HTML.
80
- - Defaults to `['*.html']`.
80
+ - Defaults to `["*.html"]`.
81
81
  - `dynamic`
82
82
  - List of file patterns to treat as dynamic.
83
83
  - Matching files will not be versioned.
84
84
  - References from matching source files will be still be rewritten.
85
- - Defaults to `['*.html']`.
86
- - `manifest`
87
- - Manifest filename.
88
- - Defaults to `'.manifest.json'`.
85
+ - Defaults to `["*.html"]`.
86
+ - `metadata`
87
+ - Metadata filename.
88
+ - Defaults to `.cbst.json`.
89
89
  - `hashLength`
90
90
  - Length of hashes in versioned filenames.
91
91
  - Defaults to `10`.
92
92
 
93
93
  File patterns support `*` (slash-free wildcards) and `/**/` (directory wildcards).
94
94
 
95
- ## Versioning and references
95
+ ## Versioning and References
96
96
 
97
97
  As `cbst` transforms files, it also rewrites any references to other versioned files.
98
98
  References are detected by scanning source files for **quoted strings** that
@@ -106,7 +106,7 @@ the reference is rewritten with the versioned filename.
106
106
 
107
107
  If a reference cannot be resolved to a file, the reference is not modified.
108
108
 
109
- ## Static vs. dynamic files
109
+ ## Static vs. Dynamic Files
110
110
 
111
111
  **Static files** (not listed in `dynamic`) will be versioned based on a hash
112
112
  of their contents, as well as the contents of any referenced files.
@@ -1,6 +1,3 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- /// <reference types="node" />
4
1
  import EventEmitter from 'events';
5
2
  import { Cache } from './util/Cache';
6
3
  import { Glob } from './util/Glob';
@@ -12,7 +9,7 @@ export interface CacheBusterConfig {
12
9
  exclude?: string[];
13
10
  /**
14
11
  * List of file patterns to treat as source files with references.
15
- * Defaults to `['*.html', '*.css', '*.js', '*.svg']`.
12
+ * Defaults to `['*.html', '*.css', '*.js', '*.svg', '*.json']`.
16
13
  */
17
14
  source?: string[];
18
15
  /**
@@ -26,10 +23,10 @@ export interface CacheBusterConfig {
26
23
  */
27
24
  dynamic?: string[];
28
25
  /**
29
- * Manifest filename.
30
- * Defaults to `'.manifest.json'`
26
+ * Metadata filename.
27
+ * Defaults to `'.cbst.json'`
31
28
  */
32
- manifest?: string;
29
+ metadata?: string;
33
30
  /**
34
31
  * Length of hashes in versioned filenames.
35
32
  * Defaults to 10.
@@ -54,7 +51,7 @@ export declare class CacheBuster extends EventEmitter {
54
51
  protected sourceGlob: Glob;
55
52
  protected htmlGlob: Glob;
56
53
  protected dynamicGlob: Glob;
57
- protected manifest: string;
54
+ protected metadata: string;
58
55
  protected hashLength: number;
59
56
  protected hashFileCache: Cache<string | undefined>;
60
57
  protected getReferencesCache: Cache<string[]>;
@@ -68,7 +65,7 @@ export declare class CacheBuster extends EventEmitter {
68
65
  protected extensionRx: RegExp;
69
66
  constructor(options: CacheBusterOptions);
70
67
  run(): Promise<void>;
71
- writeManifest(): Promise<void>;
68
+ writeMetadata(): Promise<void>;
72
69
  handleDir(dir: string): Promise<undefined>;
73
70
  handleFile(file: string): Promise<undefined>;
74
71
  transformFile(file: string): Promise<string | Buffer>;
@@ -1,45 +1,55 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.CacheBuster = void 0;
7
- const crypto_1 = require("crypto");
8
- const events_1 = __importDefault(require("events"));
9
- const fs_1 = require("fs");
10
- const path_1 = require("path");
11
- const ReferenceError_1 = require("./ReferenceError");
12
- const Cache_1 = require("./util/Cache");
13
- const Glob_1 = require("./util/Glob");
14
- class CacheBuster extends events_1.default {
1
+ import { createHash } from 'crypto';
2
+ import EventEmitter from 'events';
3
+ import { promises as fs } from 'fs';
4
+ import { posix as path } from 'path';
5
+ import { ReferenceError } from './ReferenceError';
6
+ import { Cache } from './util/Cache';
7
+ import { Glob } from './util/Glob';
8
+ export class CacheBuster extends EventEmitter {
9
+ static defaultConfig = {
10
+ exclude: [],
11
+ source: ['*.html', '*.css', '*.js', '*.svg', '*.json'],
12
+ html: ['*.html'],
13
+ dynamic: ['*.html'],
14
+ metadata: '.cbst.json',
15
+ hashLength: 10,
16
+ };
17
+ inputDir;
18
+ outputDir;
19
+ excludeGlob;
20
+ sourceGlob;
21
+ htmlGlob;
22
+ dynamicGlob;
23
+ metadata;
24
+ hashLength;
25
+ hashFileCache = new Cache((file) => this.hashFile(file));
26
+ getReferencesCache = new Cache((file) => this.getReferences(file));
27
+ hashRawFileCache = new Cache((file) => this.hashRawFile(file));
28
+ readFileCache = new Cache((file) => this.readFile(file));
29
+ map = new Map();
30
+ unresolved = new Map();
31
+ referenceRx = /((")(([^"\s]+)\.([a-zA-Z0-9]+))")|((')(([^'\s]+)\.([a-zA-Z0-9]+))')|# sourceMappingURL=(([^\s]+)\.([a-zA-Z0-9]+))/g;
32
+ externalReferenceRx = /^([a-zA-Z][a-zA-Z0-9+.\-]*:|\/\/)/;
33
+ baseRx = /<base[^<>]+href\s*=\s*"([^"]+)"[^<>]*>/i;
34
+ extensionRx = /(?<=\.)[^.]+$/;
15
35
  constructor(options) {
16
36
  super();
17
- this.hashFileCache = new Cache_1.Cache((file) => this.hashFile(file));
18
- this.getReferencesCache = new Cache_1.Cache((file) => this.getReferences(file));
19
- this.hashRawFileCache = new Cache_1.Cache((file) => this.hashRawFile(file));
20
- this.readFileCache = new Cache_1.Cache((file) => this.readFile(file));
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-Z][a-zA-Z0-9+.\-]*:|\/\/)/;
25
- this.baseRx = /<base[^<>]+href\s*=\s*"([^"]+)"[^<>]*>/i;
26
- this.extensionRx = /(?<=\.)[^.]+$/;
27
37
  const o = { ...CacheBuster.defaultConfig, ...options };
28
38
  this.inputDir = o.inputDir;
29
39
  this.outputDir = o.outputDir;
30
- this.excludeGlob = new Glob_1.Glob(o.exclude);
31
- this.sourceGlob = new Glob_1.Glob(o.source);
32
- this.htmlGlob = new Glob_1.Glob(o.html);
33
- this.dynamicGlob = new Glob_1.Glob(o.dynamic);
34
- this.manifest = o.manifest;
40
+ this.excludeGlob = new Glob(o.exclude);
41
+ this.sourceGlob = new Glob(o.source);
42
+ this.htmlGlob = new Glob(o.html);
43
+ this.dynamicGlob = new Glob(o.dynamic);
44
+ this.metadata = o.metadata;
35
45
  this.hashLength = o.hashLength;
36
46
  }
37
47
  async run() {
38
48
  await this.handleDir('.');
39
- await this.writeManifest();
49
+ await this.writeMetadata();
40
50
  }
41
- async writeManifest() {
42
- await this.writeFile(this.manifest, JSON.stringify({ map: Object.fromEntries(this.map.entries()) }));
51
+ async writeMetadata() {
52
+ await this.writeFile(this.metadata, JSON.stringify({ map: Object.fromEntries(this.map.entries()) }));
43
53
  }
44
54
  async handleDir(dir) {
45
55
  if (this.excludeGlob.match(dir))
@@ -48,10 +58,10 @@ class CacheBuster extends events_1.default {
48
58
  entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
49
59
  for (const entry of entries) {
50
60
  if (entry.isFile()) {
51
- await this.handleFile(path_1.posix.join(dir, entry.name));
61
+ await this.handleFile(path.join(dir, entry.name));
52
62
  }
53
63
  else if (entry.isDirectory()) {
54
- await this.handleDir(path_1.posix.join(dir, entry.name));
64
+ await this.handleDir(path.join(dir, entry.name));
55
65
  }
56
66
  }
57
67
  }
@@ -132,7 +142,7 @@ class CacheBuster extends events_1.default {
132
142
  if (unresolved.has(reference))
133
143
  return;
134
144
  unresolved.add(reference);
135
- this.emit('error', new ReferenceError_1.ReferenceError(error, source, reference));
145
+ this.emit('error', new ReferenceError(error, source, reference));
136
146
  }
137
147
  // references
138
148
  async getReferences(file) {
@@ -159,7 +169,7 @@ class CacheBuster extends events_1.default {
159
169
  resolveReference(base, reference) {
160
170
  if (reference[0] === '/')
161
171
  return reference.slice(1);
162
- return path_1.posix.join(base[0] === '/' ? base.slice(1) : base, reference);
172
+ return path.join(base[0] === '/' ? base.slice(1) : base, reference);
163
173
  }
164
174
  async getBase(file) {
165
175
  if (this.htmlGlob.match(file)) {
@@ -169,46 +179,37 @@ class CacheBuster extends events_1.default {
169
179
  if (match)
170
180
  return match[1];
171
181
  }
172
- return path_1.posix.dirname(file);
182
+ return path.dirname(file);
173
183
  }
174
184
  // hashing
175
185
  formatVersion(hash) {
176
186
  return hash.slice(0, this.hashLength);
177
187
  }
178
188
  hash(inputs) {
179
- const h = (0, crypto_1.createHash)('sha1');
189
+ const h = createHash('sha1');
180
190
  for (const input of inputs)
181
191
  h.update(input);
182
192
  return h.digest('hex');
183
193
  }
184
194
  // i/o
185
195
  async readFile(file) {
186
- return fs_1.promises.readFile(this.safePath(this.inputDir, file));
196
+ return fs.readFile(this.safePath(this.inputDir, file));
187
197
  }
188
198
  async readDir(dir) {
189
- return fs_1.promises.readdir(this.safePath(this.inputDir, dir), {
199
+ return fs.readdir(this.safePath(this.inputDir, dir), {
190
200
  withFileTypes: true,
191
201
  });
192
202
  }
193
203
  async writeFile(file, data) {
194
204
  const outputFile = this.safePath(this.outputDir, file);
195
- await fs_1.promises.mkdir(path_1.posix.dirname(outputFile), { recursive: true });
196
- return fs_1.promises.writeFile(outputFile, data);
205
+ await fs.mkdir(path.dirname(outputFile), { recursive: true });
206
+ return fs.writeFile(outputFile, data);
197
207
  }
198
208
  safePath(rootDir, candidate) {
199
- const s = path_1.posix.normalize(path_1.posix.join(rootDir, candidate));
209
+ const s = path.normalize(path.join(rootDir, candidate));
200
210
  if (s.indexOf(rootDir) !== 0) {
201
211
  throw new Error(`Trying to access file outside of ${rootDir}: ${candidate}`);
202
212
  }
203
213
  return s;
204
214
  }
205
215
  }
206
- CacheBuster.defaultConfig = {
207
- exclude: [],
208
- source: ['*.html', '*.css', '*.js', '*.svg'],
209
- html: ['*.html'],
210
- dynamic: ['*.html'],
211
- manifest: '.manifest.json',
212
- hashLength: 10,
213
- };
214
- exports.CacheBuster = CacheBuster;
@@ -1,11 +1,9 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CacheBusterCli = void 0;
4
- const fs_1 = require("fs");
5
- const CacheBuster_1 = require("./CacheBuster");
6
- const isRecord_1 = require("./util/isRecord");
7
- const isStringArray_1 = require("./util/isStringArray");
8
- class CacheBusterCli {
1
+ import { promises as fs } from 'fs';
2
+ import { CacheBuster } from './CacheBuster';
3
+ import { isRecord } from './util/isRecord';
4
+ import { isStringArray } from './util/isStringArray';
5
+ export class CacheBusterCli {
6
+ console;
9
7
  constructor(console = global.console) {
10
8
  this.console = console;
11
9
  }
@@ -21,7 +19,7 @@ class CacheBusterCli {
21
19
  if (!outputDir)
22
20
  throw new Error('No output directory given');
23
21
  const config = configFile ? await this.loadConfig(configFile) : undefined;
24
- const cacheBuster = new CacheBuster_1.CacheBuster({
22
+ const cacheBuster = new CacheBuster({
25
23
  ...config,
26
24
  inputDir,
27
25
  outputDir,
@@ -45,20 +43,20 @@ class CacheBusterCli {
45
43
  cbst <input dir> <output dir> [<config file>]`;
46
44
  }
47
45
  async loadConfig(file) {
48
- const config = JSON.parse(await fs_1.promises.readFile(file, 'utf-8'));
49
- if (!(0, isRecord_1.isRecord)(config)) {
46
+ const config = JSON.parse(await fs.readFile(file, 'utf-8'));
47
+ if (!isRecord(config)) {
50
48
  throw new Error('Config must be an object');
51
49
  }
52
- if (!(0, isStringArray_1.isStringArray)(config.exclude ?? [])) {
50
+ if (!isStringArray(config.exclude ?? [])) {
53
51
  throw new Error('"exclude" must be an array of strings');
54
52
  }
55
- if (!(0, isStringArray_1.isStringArray)(config.sources ?? [])) {
53
+ if (!isStringArray(config.sources ?? [])) {
56
54
  throw new Error('"sources" must be an array of strings');
57
55
  }
58
- if (!(0, isStringArray_1.isStringArray)(config.html ?? [])) {
56
+ if (!isStringArray(config.html ?? [])) {
59
57
  throw new Error('"html" must be an array of strings');
60
58
  }
61
- if (!(0, isStringArray_1.isStringArray)(config.dynamic ?? [])) {
59
+ if (!isStringArray(config.dynamic ?? [])) {
62
60
  throw new Error('"dynamic" must be an array of strings');
63
61
  }
64
62
  if (typeof (config.manifest ?? '') !== 'string') {
@@ -70,4 +68,3 @@ class CacheBusterCli {
70
68
  return config;
71
69
  }
72
70
  }
73
- exports.CacheBusterCli = CacheBusterCli;
@@ -1,7 +1,7 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ReferenceError = void 0;
4
- class ReferenceError extends Error {
1
+ export class ReferenceError extends Error {
2
+ originalError;
3
+ source;
4
+ reference;
5
5
  constructor(originalError, source, reference) {
6
6
  super(originalError.code === 'ENOENT'
7
7
  ? `Could not resolve ${reference} from ${source}`
@@ -11,4 +11,3 @@ class ReferenceError extends Error {
11
11
  this.reference = reference;
12
12
  }
13
13
  }
14
- exports.ReferenceError = ReferenceError;
package/dist/bin.js CHANGED
@@ -1,6 +1,4 @@
1
1
  #!/usr/bin/env node
2
- "use strict";
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- const CacheBusterCli_1 = require("./CacheBusterCli");
5
- const cli = new CacheBusterCli_1.CacheBusterCli();
2
+ import { CacheBusterCli } from './CacheBusterCli';
3
+ const cli = new CacheBusterCli();
6
4
  cli.run(process.argv.slice(2)).then((exitCode) => process.exit(exitCode));
package/dist/index.js CHANGED
@@ -1,19 +1,3 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./CacheBuster"), exports);
18
- __exportStar(require("./CacheBusterCli"), exports);
19
- __exportStar(require("./ReferenceError"), exports);
1
+ export * from './CacheBuster';
2
+ export * from './CacheBusterCli';
3
+ export * from './ReferenceError';
@@ -1,8 +1,7 @@
1
- export type CacheFn<T> = (key: string) => Promise<T>;
2
1
  export declare class Cache<T> {
3
- protected fn: CacheFn<T>;
2
+ protected fn: (key: string) => Promise<T>;
4
3
  protected map: Map<string, Promise<T>>;
5
- constructor(fn: CacheFn<T>);
4
+ constructor(fn: (key: string) => Promise<T>);
6
5
  get(key: string): Promise<T>;
7
6
  delete(key: string): void;
8
7
  }
@@ -1,10 +1,8 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Cache = void 0;
4
- class Cache {
1
+ export class Cache {
2
+ fn;
3
+ map = new Map();
5
4
  constructor(fn) {
6
5
  this.fn = fn;
7
- this.map = new Map();
8
6
  }
9
7
  get(key) {
10
8
  const cached = this.map.get(key);
@@ -18,4 +16,3 @@ class Cache {
18
16
  this.map.delete(key);
19
17
  }
20
18
  }
21
- exports.Cache = Cache;
@@ -1,2 +1 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
1
+ export {};
package/dist/util/Glob.js CHANGED
@@ -1,7 +1,5 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Glob = void 0;
4
- class Glob {
1
+ export class Glob {
2
+ patterns;
5
3
  constructor(patterns) {
6
4
  this.patterns = patterns.map((pattern) => this.compile(pattern));
7
5
  }
@@ -48,4 +46,3 @@ class Glob {
48
46
  };
49
47
  }
50
48
  }
51
- exports.Glob = Glob;
@@ -1,7 +1,3 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isRecord = void 0;
4
- function isRecord(value) {
1
+ export function isRecord(value) {
5
2
  return typeof value === 'object' && !!value && !Array.isArray(value);
6
3
  }
7
- exports.isRecord = isRecord;
@@ -1,7 +1,3 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isStringArray = void 0;
4
- function isStringArray(value) {
1
+ export function isStringArray(value) {
5
2
  return Array.isArray(value) && value.every((it) => typeof it === 'string');
6
3
  }
7
- exports.isStringArray = isStringArray;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cbst",
3
- "version": "0.2.2",
3
+ "version": "1.0.0",
4
4
  "description": "A cache buster that versions a website's files for immutable cache control",
5
5
  "keywords": [
6
6
  "versioning",
@@ -9,35 +9,41 @@
9
9
  ],
10
10
  "author": "Morris Brodersen <mb@morrisbrodersen.de>",
11
11
  "license": "ISC",
12
+ "homepage": "https://github.com/morris/cbst",
12
13
  "repository": {
13
14
  "type": "git",
14
- "url": "https://github.com/morris/cbst.git"
15
+ "url": "git+https://github.com/morris/cbst.git"
16
+ },
17
+ "bugs": {
18
+ "url": "https://github.com/morris/cbst/issues"
15
19
  },
16
20
  "engines": {
17
- "node": ">=14"
21
+ "node": ">=20"
18
22
  },
23
+ "type": "module",
19
24
  "files": [
20
25
  "dist"
21
26
  ],
22
- "main": "dist/index.js",
23
- "bin": "dist/bin.js",
27
+ "exports": "./dist/index.js",
28
+ "bin": {
29
+ "cbst": "dist/bin.js"
30
+ },
24
31
  "scripts": {
25
32
  "build": "tsc --project tsconfig.build.json",
26
33
  "clean": "rm -rf coverage dist test/fixtures/out",
27
34
  "lint": "eslint .",
28
35
  "format": "prettier --write .",
29
36
  "format-check": "prettier --check .",
30
- "test": "jest --runInBand --coverage",
31
- "maybe-publish": "bash scripts/maybe-publish.sh"
37
+ "test": "jest --runInBand --coverage"
32
38
  },
33
39
  "devDependencies": {
34
40
  "@types/jest": "^29.1.2",
35
- "@types/node": "^14.18.31",
36
- "@typescript-eslint/eslint-plugin": "^5.23.0",
37
- "@typescript-eslint/parser": "^5.23.0",
41
+ "@types/node": "^20.14.8",
42
+ "@typescript-eslint/eslint-plugin": "^7.13.1",
43
+ "@typescript-eslint/parser": "^7.13.1",
38
44
  "eslint": "^8.15.0",
39
45
  "jest": "^29.1.2",
40
- "prettier": "^2.6.2",
46
+ "prettier": "^3.3.2",
41
47
  "ts-jest": "^29.0.3",
42
48
  "ts-node": "^10.9.1",
43
49
  "typescript": "^5.0.4"
package/CHANGELOG.md DELETED
@@ -1,26 +0,0 @@
1
- # Changelog
2
-
3
- # 0.2.2
4
-
5
- - Fix CLI exit code
6
- - Fix `exclude` not excluding some references
7
- - Fix identification of external references
8
-
9
- # 0.2.1
10
-
11
- - Ignore `mailto:` and other protocols properly
12
- - Update deps
13
-
14
- # 0.2.0
15
-
16
- - Exit with code 1 on errors (including unresolved references)
17
- - Support source map references
18
- - Fix glob prefix
19
-
20
- # 0.1.1
21
-
22
- - Fix binary
23
-
24
- # 0.1.0
25
-
26
- - Initial version