├── .nvmrc ├── .prettierrc ├── .npmrc ├── .gitignore ├── package └── index.mjs ├── eslint.config.mjs ├── readme.md ├── jsconfig.json ├── package.json ├── .github └── workflows │ └── publish.yml ├── scripts ├── generate-inventory.mjs ├── build.mjs └── publish-historic.mjs ├── lib └── inventory.mjs └── LICENSE.txt /.nvmrc: -------------------------------------------------------------------------------- 1 | v24 2 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | engine-strict=true 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .mdn-content 2 | node_modules 3 | package/*.json 4 | package/*.md 5 | package/*.txt 6 | -------------------------------------------------------------------------------- /package/index.mjs: -------------------------------------------------------------------------------- 1 | import { readFileSync } from "fs"; 2 | import { dirname, join } from "path"; 3 | import { fileURLToPath } from "url"; 4 | 5 | const scriptdir = dirname(fileURLToPath(import.meta.url)); 6 | 7 | function read() { 8 | return JSON.parse( 9 | readFileSync(join(scriptdir, "index.json"), { encoding: "utf-8" }), 10 | ); 11 | } 12 | 13 | export default read(); 14 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | import eslint from "@eslint/js"; 2 | 3 | export default [ 4 | eslint.configs.recommended, 5 | { 6 | languageOptions: { 7 | ecmaVersion: 2022, 8 | sourceType: "module", 9 | globals: { 10 | console: "readonly", 11 | process: "readonly", 12 | Buffer: "readonly", 13 | __dirname: "readonly", 14 | __filename: "readonly", 15 | }, 16 | }, 17 | rules: { 18 | "no-warning-comments": [ 19 | "error", 20 | { terms: ["xxx"], location: "anywhere" }, 21 | ], 22 | }, 23 | }, 24 | ]; 25 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # [@mdn/content-inventory](https://github.com/mdn/content-inventory) 2 | 3 | `@mdn/content-inventory` is [MDN Web Docs content](https://github.com/mdn/content) metadata as a package. 4 | You can use it to query MDN page metadata without having to clone the large repository and parse the frontmatter yourself. 5 | 6 | MDN Web Docs page metadata and frontmatter by [Mozilla Contributors](https://developer.mozilla.org/en-US/docs/MDN/Community/Roles_teams#contributor) is licensed under [CC-BY-SA 2.5](https://creativecommons.org/licenses/by-sa/2.5/). 7 | 8 | For the code that build, publishes, and exports the MDN data, see `LICENSE.txt`. 9 | -------------------------------------------------------------------------------- /jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "checkJs": true, 4 | "strict": true, 5 | "noImplicitAny": true, 6 | "strictNullChecks": true, 7 | "strictFunctionTypes": true, 8 | "strictBindCallApply": true, 9 | "strictPropertyInitialization": true, 10 | "noImplicitThis": true, 11 | "useUnknownInCatchVariables": true, 12 | "alwaysStrict": true, 13 | "noUnusedLocals": true, 14 | "noUnusedParameters": true, 15 | "exactOptionalPropertyTypes": false, 16 | "noImplicitReturns": true, 17 | "noFallthroughCasesInSwitch": true, 18 | "noUncheckedIndexedAccess": true, 19 | "noImplicitOverride": true, 20 | "noPropertyAccessFromIndexSignature": false, 21 | "allowUnusedLabels": false, 22 | "allowUnreachableCode": false, 23 | "module": "esnext", 24 | "moduleResolution": "bundler", 25 | "resolveJsonModule": true, 26 | "allowSyntheticDefaultImports": true, 27 | "esModuleInterop": true, 28 | "forceConsistentCasingInFileNames": true, 29 | "skipLibCheck": true, 30 | "target": "es2022", 31 | "lib": ["es2022"], 32 | "outDir": "./dist" 33 | }, 34 | "include": ["./lib/*.mjs", "./package/index.mjs", "./scripts/*.mjs"] 35 | } 36 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@mdn/content-inventory", 3 | "version": "0.2.0", 4 | "description": "The MDN page inventory as a big JSON object.", 5 | "main": "lib/inventory.mjs", 6 | "type": "module", 7 | "scripts": { 8 | "lint": "npx eslint . --ignore-pattern '.mdn-content/*'", 9 | "test": "npx tsc --project jsconfig.json --noEmit", 10 | "build": "node scripts/build.mjs", 11 | "publish": "cd package && npm publish", 12 | "publish:dry-run": "cd package && npm publish --dry-run", 13 | "clean": "rm -f package/*.json" 14 | }, 15 | "engines": { 16 | "node": ">=24" 17 | }, 18 | "packageManager": "npm@11.6.2", 19 | "repository": { 20 | "type": "git", 21 | "url": "git+https://github.com/mdn/content-inventory.git" 22 | }, 23 | "author": "Daniel D. Beck (https://ddbeck.com)", 24 | "license": "Apache-2.0", 25 | "private": "true", 26 | "devDependencies": { 27 | "@eslint/js": "^9.4.0", 28 | "@js-temporal/polyfill": "^0.4.4", 29 | "@types/node": "^24.10.3", 30 | "@types/yargs": "^17.0.32", 31 | "eslint": "^8.57.0", 32 | "prettier": "^3.3.0", 33 | "typescript": "^5.4.5", 34 | "winston": "^3.13.0", 35 | "yargs": "^17.7.2" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish daily 2 | 3 | on: 4 | schedule: 5 | - cron: "58 5 * * *" 6 | workflow_dispatch: 7 | inputs: 8 | ref: 9 | description: mdn/content commit to publish a release from 10 | required: false 11 | type: string 12 | dryRun: 13 | description: Don't actually publish to npm 14 | required: false 15 | type: boolean 16 | 17 | concurrency: 18 | group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} 19 | cancel-in-progress: true 20 | 21 | permissions: {} 22 | 23 | jobs: 24 | publish: 25 | name: Publish to npm 26 | runs-on: ubuntu-latest 27 | permissions: 28 | id-token: write # trusted publishing + attestations 29 | 30 | steps: 31 | - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 32 | with: 33 | persist-credentials: false 34 | 35 | - uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0 36 | with: 37 | node-version-file: ".tool-versions" 38 | registry-url: "https://registry.npmjs.org" 39 | 40 | - run: npm install -g 'npm@>=11.5.1' # required for trusted publishing 41 | 42 | - run: npm ci 43 | 44 | - run: | 45 | if [ -n "$REF" ]; then 46 | npm run build -- --verbose --ref="$REF" 47 | else 48 | npm run build -- --verbose 49 | fi 50 | env: 51 | GH_TOKEN: ${{ github.token }} 52 | REF: ${{ inputs.ref }} 53 | 54 | - if: ${{ inputs.dryRun }} 55 | run: npm run publish:dry-run 56 | 57 | - if: ${{ ! inputs.dryRun }} 58 | run: npm run publish 59 | 60 | - run: npm info @mdn/content-inventory 61 | -------------------------------------------------------------------------------- /scripts/generate-inventory.mjs: -------------------------------------------------------------------------------- 1 | import { relative } from "path"; 2 | import { fileURLToPath } from "url"; 3 | import winston from "winston"; 4 | import yargs from "yargs"; 5 | import { Inventory } from "../lib/inventory.mjs"; 6 | 7 | const argv = yargs(process.argv.slice(2)) 8 | .scriptName("dist") 9 | .usage("$0", "Generate JSON from MDN content") 10 | .option("ref", { 11 | describe: 12 | "Choose a specific ref (commit, branch, or tag) to generate the inventory from", 13 | type: "string", 14 | default: "origin/main", 15 | }) 16 | .option("date", { 17 | describe: 18 | "Choose a specific date (in YYYY-MM-DD) to generate the inventory from", 19 | type: "string", 20 | }) 21 | .option("verbose", { 22 | alias: "v", 23 | describe: "Show more information about calculating the status", 24 | type: "count", 25 | default: 0, 26 | defaultDescription: "warn", 27 | }) 28 | .option("clean", { 29 | describe: "Wipe out repo when finished", 30 | type: "boolean", 31 | default: false, 32 | }) 33 | .parseSync(); 34 | 35 | const logger = winston.createLogger({ 36 | level: argv.verbose > 0 ? "debug" : "warn", 37 | format: winston.format.combine( 38 | winston.format.colorize(), 39 | winston.format.simple(), 40 | ), 41 | transports: new winston.transports.Console({ 42 | stderrLevels: ["debug", "warn", "info"], 43 | }), 44 | }); 45 | 46 | const destPath = relative(process.cwd(), ".mdn-content"); 47 | 48 | /** 49 | * Main function to generate and output inventory 50 | * @returns {Promise} 51 | */ 52 | async function main() { 53 | const inventory = new Inventory({ destPath, logger }); 54 | try { 55 | if (argv.date) { 56 | await inventory.init(argv.ref, argv.date); 57 | } else { 58 | await inventory.init(argv.ref); 59 | } 60 | console.log(JSON.stringify(inventory.toObject(), undefined, 2)); 61 | } finally { 62 | if (argv.clean) { 63 | inventory.cleanUp(); 64 | } 65 | } 66 | } 67 | 68 | if (import.meta.url.startsWith("file:")) { 69 | if (process.argv[1] === fileURLToPath(import.meta.url)) { 70 | main(); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /scripts/build.mjs: -------------------------------------------------------------------------------- 1 | import { Temporal } from "@js-temporal/polyfill"; 2 | import { copyFileSync, readFileSync, writeFileSync } from "fs"; 3 | import assert from "node:assert"; 4 | import winston from "winston"; 5 | import yargs from "yargs"; 6 | import { Inventory } from "../lib/inventory.mjs"; 7 | 8 | const argv = yargs(process.argv.slice(2)) 9 | .scriptName("build") 10 | .usage("$0", "Generate JSON from MDN content") 11 | .option("ref", { 12 | describe: 13 | "Choose a specific ref (commit, branch, or tag) to generate the inventory from", 14 | type: "string", 15 | default: "origin/main", 16 | }) 17 | .option("date", { 18 | describe: 19 | "Choose a specific date (in YYYY-MM-DD) to generate the inventory from", 20 | type: "string", 21 | }) 22 | .option("verbose", { 23 | alias: "v", 24 | describe: "Show more informational messages", 25 | type: "count", 26 | default: 0, 27 | defaultDescription: "warn", 28 | }) 29 | .parseSync(); 30 | 31 | const logger = winston.createLogger({ 32 | level: argv.verbose > 0 ? "debug" : "warn", 33 | format: winston.format.combine( 34 | winston.format.colorize(), 35 | winston.format.simple(), 36 | ), 37 | transports: new winston.transports.Console({ 38 | stderrLevels: ["debug", "info", "warn"], 39 | }), 40 | }); 41 | 42 | await main(); 43 | 44 | /** 45 | * Main function to generate inventory and package.json 46 | * @returns {Promise} 47 | */ 48 | async function main() { 49 | const publishDate = Temporal.PlainDate.from( 50 | argv.date ?? Temporal.Now.zonedDateTimeISO(), 51 | ) 52 | .toZonedDateTime({ timeZone: "UTC", plainTime: "00:00:01" }) 53 | .startOfDay(); 54 | 55 | logger.info("Generating inventory…"); 56 | await makeInventoryJSON(); 57 | 58 | logger.info("Creating package.json…"); 59 | makePackageJSON({ publishDate }); 60 | 61 | logger.info("Copying readme.md"); 62 | copyFileSync("readme.md", "package/readme.md"); 63 | } 64 | 65 | /** 66 | * Generate the inventory JSON file 67 | * @returns {Promise} 68 | */ 69 | async function makeInventoryJSON() { 70 | const startOfDay = Temporal.PlainDate.from( 71 | argv.date ?? Temporal.Now.zonedDateTimeISO(), 72 | ) 73 | .toZonedDateTime({ timeZone: "UTC", plainTime: "00:00:01" }) 74 | .startOfDay(); 75 | 76 | const inv = new Inventory({ logger }); 77 | await inv.init(argv.ref, startOfDay.toString()); 78 | 79 | writeFileSync( 80 | "package/index.json", 81 | JSON.stringify(inv.toObject(), undefined), 82 | { encoding: "utf8" }, 83 | ); 84 | } 85 | 86 | /** 87 | * Generate the package.json file for the package 88 | * @param {{ publishDate: Temporal.ZonedDateTime }} opts 89 | * @returns {void} 90 | */ 91 | function makePackageJSON(opts) { 92 | const { publishDate } = opts; 93 | 94 | const { name, version, description, repository, author } = JSON.parse( 95 | readFileSync("package.json", { encoding: "utf-8" }), 96 | ); 97 | 98 | copyFileSync("LICENSE.txt", "package/LICENSE.txt"); 99 | 100 | const [major, minor, patch] = version.split("."); 101 | for (const versionPart of [major, minor, patch]) { 102 | assert(typeof versionPart === "string"); 103 | } 104 | 105 | writeFileSync( 106 | "package/package.json", 107 | JSON.stringify( 108 | { 109 | name, 110 | version: `${major}.${minor}.${publishDate.toString().slice(0, 10).replaceAll("-", "")}`, 111 | description, 112 | repository, 113 | author, 114 | license: "CC-BY-SA-2.5", 115 | main: "index.mjs", 116 | type: "module", 117 | scripts: {}, 118 | }, 119 | undefined, 120 | 2, 121 | ), 122 | { encoding: "utf-8" }, 123 | ); 124 | } 125 | -------------------------------------------------------------------------------- /scripts/publish-historic.mjs: -------------------------------------------------------------------------------- 1 | import { Temporal } from "@js-temporal/polyfill"; 2 | import { execFileSync } from "child_process"; 3 | import { readFileSync } from "fs"; 4 | import { fileURLToPath } from "node:url"; 5 | import winston from "winston"; 6 | import yargs from "yargs"; 7 | 8 | const argv = yargs(process.argv.slice(2)) 9 | .scriptName("publish-historic") 10 | .usage("$0", "Publish historic releases") 11 | .option("dry-run", { 12 | alias: "n", 13 | describe: "Don't actually publish to npm", 14 | type: "boolean", 15 | default: true, 16 | }) 17 | .option("continue", { 18 | describe: "Continue to the next release, if a release already exists", 19 | type: "boolean", 20 | default: false, 21 | }) 22 | .option("verbose", { 23 | alias: "v", 24 | describe: "Show more information about calculating the status", 25 | type: "count", 26 | default: 0, 27 | defaultDescription: "warn", 28 | }) 29 | .parseSync(); 30 | 31 | const logger = winston.createLogger({ 32 | level: argv.verbose > 0 ? "debug" : "warn", 33 | format: winston.format.combine( 34 | winston.format.colorize(), 35 | winston.format.simple(), 36 | ), 37 | transports: new winston.transports.Console({ 38 | stderrLevels: ["debug", "warn", "info"], 39 | }), 40 | }); 41 | 42 | const START_DATE = Temporal.Instant.from( 43 | "2023-10-01T00:00:00.000Z", 44 | ).toZonedDateTimeISO("UTC"); 45 | 46 | /** 47 | * Main function to publish historic releases 48 | * @returns {void} 49 | */ 50 | function main() { 51 | const now = Temporal.Now.zonedDateTimeISO("UTC"); 52 | let target = START_DATE; 53 | 54 | while (Temporal.ZonedDateTime.compare(target, now) < 1) { 55 | npmRun("clean"); 56 | npmRun("build", `--date=${target.toString()}`); 57 | 58 | const forthcomingVersion = JSON.parse( 59 | readFileSync("package/package.json", { encoding: "utf-8" }), 60 | ).version; 61 | const forthcomingHash = JSON.parse( 62 | readFileSync("package/index.json", { encoding: "utf-8" }), 63 | ).metadata.commitShort; 64 | 65 | const forthcomingDate = target.toString().slice(0, 10).replaceAll("-", ""); 66 | logger.debug( 67 | `Attempting to publish for ${forthcomingDate} and ${forthcomingHash} as ${forthcomingVersion}`, 68 | ); 69 | 70 | /** @type {false | string} */ 71 | let alreadyPublished = false; 72 | for (const version of Object.keys(completedReleases())) { 73 | if ( 74 | version.includes(forthcomingDate) || 75 | version.includes(forthcomingHash) 76 | ) { 77 | alreadyPublished = `${forthcomingDate} or ${forthcomingHash} is already published as ${forthcomingVersion}`; 78 | } 79 | } 80 | 81 | if (alreadyPublished) { 82 | if (argv.continue) { 83 | logger.warn(`${alreadyPublished}; skipping this release`); 84 | } else { 85 | throw new Error(alreadyPublished); 86 | } 87 | } else { 88 | if (argv.dryRun) { 89 | npmRun("publish:dry-run"); 90 | } else { 91 | npmRun("publish"); 92 | } 93 | } 94 | 95 | npmRun("clean"); 96 | target = target.add({ days: 1 }); 97 | } 98 | } 99 | 100 | /** 101 | * Run an npm script with optional arguments 102 | * @param {string} command - The npm script command to run 103 | * @param {...string} moreArgs - Additional arguments to pass to the npm script 104 | * @returns {void} 105 | */ 106 | function npmRun(command, ...moreArgs) { 107 | if (moreArgs.length > 0) { 108 | moreArgs.unshift("--"); 109 | } 110 | 111 | execFileSync("npm", ["run", command, ...moreArgs], { 112 | stdio: "inherit", 113 | }); 114 | } 115 | 116 | /** 117 | * Get completed releases from npm registry 118 | * @returns {Record} 119 | */ 120 | function completedReleases() { 121 | try { 122 | return JSON.parse( 123 | execFileSync( 124 | "npm", 125 | ["view", "@mdn/content-inventory", "time", "--json"], 126 | { stdio: "pipe", encoding: "utf-8" }, 127 | ), 128 | ); 129 | } catch (err) { 130 | return {}; 131 | } 132 | } 133 | 134 | if (import.meta.url.startsWith("file:")) { 135 | if (process.argv[1] === fileURLToPath(import.meta.url)) { 136 | main(); 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /lib/inventory.mjs: -------------------------------------------------------------------------------- 1 | import { Temporal } from "@js-temporal/polyfill"; 2 | import assert from "node:assert/strict"; 3 | import { 4 | execFileSync, 5 | spawn, 6 | } from "node:child_process"; 7 | import { existsSync, readFileSync, rmSync } from "node:fs"; 8 | import { join, relative } from "node:path"; 9 | import winston from "winston"; 10 | 11 | const defaultLogger = winston.createLogger({ 12 | level: "warn", 13 | format: winston.format.combine( 14 | winston.format.colorize(), 15 | winston.format.simple(), 16 | ), 17 | transports: new winston.transports.Console({ 18 | stderrLevels: ["debug", "warn", "info"], 19 | }), 20 | }); 21 | 22 | /** 23 | * @typedef {Object} InventoryOptions 24 | * @property {string} [repo] - GitHub repository in the format "owner/repo" 25 | * @property {string} [destPath] - Destination path for cloning the repository 26 | * @property {winston.Logger} [logger] - Winston logger instance 27 | */ 28 | 29 | /** 30 | * @typedef {Object} InventoryMetadata 31 | * @property {string} commit - Full commit hash 32 | * @property {string} commitShort - Short commit hash 33 | * @property {string} authorDate - ISO 8601 date string of commit author date 34 | */ 35 | 36 | export class Inventory { 37 | /** 38 | * @param {InventoryOptions} [opts] 39 | */ 40 | constructor(opts) { 41 | const defaults = { 42 | repo: "mdn/content", 43 | destPath: relative(process.cwd(), ".mdn-content"), // TODO: use tempdir by default 44 | logger: defaultLogger, 45 | }; 46 | const resolvedOpts = { ...defaults, ...opts }; 47 | 48 | /** @type {string} */ 49 | this.repo = resolvedOpts.repo; 50 | /** @type {string} */ 51 | this.destPath = resolvedOpts.destPath; 52 | /** @type {winston.Logger} */ 53 | this.logger = resolvedOpts.logger; 54 | 55 | /** @type {string} */ 56 | this.rawInventoryStdErr = ""; 57 | /** @type {string} */ 58 | this.rawInventoryStdOut = ""; 59 | /** @type {string | undefined} */ 60 | this.rawRedirects = undefined; 61 | } 62 | 63 | /** 64 | * Initialize the inventory by cloning, checking out, and loading data 65 | * @param {string} ref - Git reference (commit, branch, or tag) 66 | * @param {string} [date] - Optional date string to find commit at specific time 67 | * @returns {Promise} 68 | */ 69 | async init(ref, date) { 70 | this.clone(); 71 | this.checkout(ref, date); 72 | this.loadRedirects(); 73 | this.installDeps(); 74 | const result = await this.loadInventory(); 75 | if (result === null || result > 0) { 76 | this.logger.error(this.rawInventoryStdErr); 77 | throw new Error("Failed to load data. See stdout above for details."); 78 | } 79 | } 80 | 81 | /** 82 | * Clone the repository if it doesn't exist 83 | * @returns {void} 84 | */ 85 | clone() { 86 | if ( 87 | !existsSync(this.destPath) || 88 | !existsSync(join(this.destPath, "/.git")) 89 | ) { 90 | this.logger.info(`Cloning ${this.repo} to ${this.destPath}`); 91 | execFileSync("gh", [ 92 | "repo", 93 | "clone", 94 | this.repo, 95 | this.destPath, 96 | "--", 97 | "--filter=blob:none", 98 | "--quiet", 99 | ]); 100 | } else { 101 | this.logger.info(`Reusing existing clone at ${this.destPath}`); 102 | } 103 | } 104 | 105 | /** 106 | * Checkout a specific git reference 107 | * @param {string} ref - Git reference (commit, branch, or tag) 108 | * @param {string} [date] - Optional date string to find commit at specific time 109 | * @returns {void} 110 | */ 111 | checkout(ref, date) { 112 | this.logger.debug(`Fetching from origin`); 113 | execFileSync("git", ["fetch", "origin"], { cwd: this.destPath }); 114 | if (date) { 115 | const target = Temporal.PlainDate.from(date) 116 | .toZonedDateTime({ timeZone: "UTC", plainTime: "00:00:01" }) 117 | .startOfDay(); 118 | this.logger.info(`Looking for commit on ${ref} at ${target.toString()}`); 119 | const hash = execFileSync( 120 | "git", 121 | ["rev-list", "-1", `--before=${target.toString()}`, ref], 122 | { cwd: this.destPath, encoding: "utf-8" }, 123 | ) 124 | .split("\n") 125 | .filter((line) => line.length > 0) 126 | .at(-1); 127 | if (!hash) { 128 | throw new Error(`Could not find commit near to ${target.toString()}`); 129 | } 130 | ref = hash; 131 | } 132 | 133 | this.logger.info(`Checking out ${ref}`); 134 | execFileSync("git", ["switch", "--quiet", "--detach", ref], { 135 | cwd: this.destPath, 136 | encoding: "utf-8", 137 | }); 138 | } 139 | 140 | /** 141 | * Install npm dependencies in the cloned repository 142 | * @returns {void} 143 | */ 144 | installDeps() { 145 | this.logger.info("Installing dependencies…"); 146 | execFileSync("npm", ["ci"], { 147 | cwd: this.destPath, 148 | encoding: "utf-8", 149 | stdio: "ignore", 150 | env: { ...process.env, CI: "true" }, 151 | }); 152 | } 153 | 154 | /** 155 | * Load the inventory data by running the content inventory command 156 | * @returns {Promise} 157 | */ 158 | loadInventory() { 159 | const process = spawn( 160 | "npm", 161 | ["--silent", "run", "content", "--", "inventory", "--quiet"], 162 | { cwd: this.destPath }, 163 | ); 164 | 165 | process.stdout.setEncoding("utf-8"); 166 | process.stderr.setEncoding("utf-8"); 167 | process.stdout.on("data", (/** @type {string} */ chunk) => { 168 | this.rawInventoryStdOut = this.rawInventoryStdOut + chunk; 169 | }); 170 | process.stderr.on("data", (/** @type {string} */ chunk) => { 171 | this.rawInventoryStdErr = this.rawInventoryStdErr + chunk; 172 | }); 173 | 174 | return new Promise((resolve, reject) => { 175 | process.on("error", (err) => { 176 | reject(err); 177 | }); 178 | 179 | process.on("close", (code) => { 180 | resolve(code); 181 | }); 182 | }); 183 | } 184 | 185 | /** 186 | * Load redirects from the repository 187 | * @returns {void} 188 | */ 189 | loadRedirects() { 190 | this.rawRedirects = readFileSync( 191 | `${this.destPath}/files/en-us/_redirects.txt`, 192 | "utf8", 193 | ); 194 | } 195 | 196 | /** 197 | * Get metadata about the checked out commit 198 | * @returns {InventoryMetadata} 199 | */ 200 | metadata() { 201 | /** @type {import("node:child_process").ExecFileSyncOptionsWithStringEncoding} */ 202 | const readOpts = { 203 | cwd: this.destPath, 204 | stdio: ["ignore", "pipe", "ignore"], 205 | encoding: "utf-8", 206 | }; 207 | 208 | const commitShort = execFileSync( 209 | "git", 210 | ["rev-parse", "--short", "HEAD"], 211 | readOpts, 212 | ) 213 | .split("\n") 214 | .filter((line) => line.length > 0) 215 | .at(-1); 216 | assert(commitShort?.length); 217 | 218 | const commit = execFileSync("git", ["rev-parse", "HEAD"], readOpts) 219 | .split("\n") 220 | .filter((line) => line.length > 0) 221 | .at(-1); 222 | assert(commit?.length); 223 | 224 | const authorInstant = execFileSync( 225 | "git", 226 | ["show", "--no-patch", "--format=%aI"], 227 | readOpts, 228 | ) 229 | .split("\n") 230 | .filter((line) => line.length > 0) 231 | .at(-1); 232 | assert(authorInstant?.length); 233 | const authorDate = Temporal.Instant.from(authorInstant) 234 | .toZonedDateTimeISO("UTC") 235 | .toString(); 236 | 237 | return { commit, commitShort, authorDate }; 238 | } 239 | 240 | /** 241 | * Get the parsed inventory data 242 | * @returns {any} 243 | */ 244 | inventory() { 245 | return JSON.parse(this.rawInventoryStdOut); 246 | } 247 | 248 | /** 249 | * Get the redirects map 250 | * @returns {Record} 251 | */ 252 | redirects() { 253 | if (this.rawRedirects === undefined) { 254 | throw new Error( 255 | "Redirects haven't been loaded. Did you call `init()` or `loadRedirects()` first?", 256 | ); 257 | } 258 | 259 | const lines = this.rawRedirects.split("\n"); 260 | const redirectLines = lines.filter( 261 | (line) => line.startsWith("/") && line.includes("\t"), 262 | ); 263 | /** @type {Map} */ 264 | const redirectMap = new Map(); 265 | for (const redirectLine of redirectLines) { 266 | const [source, target] = redirectLine.split("\t", 2); 267 | if (source && target) { 268 | redirectMap.set(source, target); 269 | } 270 | } 271 | return Object.fromEntries(redirectMap); 272 | } 273 | 274 | /** 275 | * Convert the inventory to a plain object 276 | * @returns {{ metadata: InventoryMetadata, inventory: any, redirects: Record }} 277 | */ 278 | toObject() { 279 | return { 280 | metadata: this.metadata(), 281 | inventory: this.inventory(), 282 | redirects: this.redirects(), 283 | }; 284 | } 285 | 286 | /** 287 | * Clean up the cloned repository 288 | * @returns {void} 289 | */ 290 | cleanUp() { 291 | this.logger.info("Cleaning up…"); 292 | rmSync(this.destPath, { recursive: true, force: true }); 293 | } 294 | } 295 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2024 Daniel D. Beck 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------