Fold MediaEngine (media-backend, media-webui) into this repo
Per owner decision: MediaEngine (the Media product family's Go backend and SvelteKit frontend, previously its own repo referenced by 7 thin service repos via git submodule) is folded directly into shared/ as media-backend/ and media-webui/, rather than staying separate. media-backend/go.mod's replace directive now points at ../backend (a true sibling within this repo) instead of a vendored ../shared/backend copy, since there's no more nested vendoring - it's the real thing. Also moved MediaEngine's own CI (media-backend-lint.yml, media-backend-tests.yml) and dev tooling scripts (scripts/media/*, audit/lint/enforce scripts for the media-backend+media-webui content), fixing their path assumptions for the new layout, and dropped scripts/media/sync-shared.mjs (confirmed dead code, and now doubly obsolete since there's no more vendored shared/ subfolder for it to check). Added media:* script aliases to package.json for the moved tooling, namespaced to avoid colliding with this repo's own scripts. Also fixed sync-consumers.ps1's workspace-root resolution to walk up until it finds a directory containing both Original/ and Forks/, instead of assuming shared/ is always a direct child of the workspace root - it broke when shared/ moved from Web/shared to Web/Central/shared earlier in this same restructuring. Removed the now-obsolete Original/MediaEngine entry from its consumer list. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
79d9461769
commit
acde180086
99 files changed
+20488
-1
No files matched your search
@@ -0,0 +1,29 @@
|
||||
import { readFileSync, readdirSync, existsSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
// TODO(MediaEngine extraction): this audits legacy pre-SvelteKit `<project>/public/*.html`
|
||||
// script tags. MediaEngine's webui/ is SvelteKit-based (no per-service `public/` HTML pages), and
|
||||
// none of the sibling monorepo service directories below live inside this repo anymore (they're
|
||||
// now separate repos: MediaModerator, MediaTools, MediaKiosk, MediaViewer). The existsSync guard
|
||||
// below means this currently no-ops safely (nothing to audit) rather than erroring. Left as-is
|
||||
// rather than guessing at a SvelteKit-equivalent audit — remove or repurpose if useful.
|
||||
const projects = ['MediaModerator', 'MediaTools', 'MediaKiosk', 'MediaViewer'];
|
||||
const scriptSrcRe = /<script[^>]+src="([^"]+)"[^>]*>/g;
|
||||
|
||||
projects.forEach(proj => {
|
||||
const pubDir = join(proj, 'public');
|
||||
if (!existsSync(pubDir)) return;
|
||||
const htmlFiles = readdirSync(pubDir)
|
||||
.filter(f => f.endsWith('.html'))
|
||||
.sort();
|
||||
console.log(`=== ${proj} ===`);
|
||||
htmlFiles.forEach(htmlFile => {
|
||||
const content = readFileSync(join(pubDir, htmlFile), 'utf8');
|
||||
const scripts = [];
|
||||
let m;
|
||||
scriptSrcRe.lastIndex = 0;
|
||||
while ((m = scriptSrcRe.exec(content)) !== null) scripts.push(m[1]);
|
||||
console.log(` ${htmlFile} -> ${scripts.join(', ')}`);
|
||||
});
|
||||
console.log();
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
|
||||
const repoRoot = process.cwd();
|
||||
const strict = process.argv.includes('--strict');
|
||||
|
||||
const includeExt = new Set(['.js', '.ejs', '.html']);
|
||||
const skipDirs = new Set(['node_modules', '.git', 'dist', 'release', 'coverage']);
|
||||
|
||||
const styleDisplayAssign = /style\.display\s*=\s*['"](?:flex|grid)['"]/gi;
|
||||
const inlineDisplayStyle = /style\s*=\s*['"][^'"]*display\s*:\s*(?:flex|grid)[^'"]*['"]/gi;
|
||||
|
||||
async function walk(dir, out = []) {
|
||||
const entries = await fs.readdir(dir, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
if (skipDirs.has(entry.name)) continue;
|
||||
await walk(full, out);
|
||||
continue;
|
||||
}
|
||||
if (!includeExt.has(path.extname(entry.name))) continue;
|
||||
out.push(full);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function lineNumberAt(content, index) {
|
||||
let line = 1;
|
||||
for (let i = 0; i < index; i += 1) {
|
||||
if (content.charCodeAt(i) === 10) line += 1;
|
||||
}
|
||||
return line;
|
||||
}
|
||||
|
||||
function collectMatches(content, regex, type) {
|
||||
const rows = [];
|
||||
regex.lastIndex = 0;
|
||||
let match;
|
||||
while ((match = regex.exec(content)) !== null) {
|
||||
rows.push({
|
||||
type,
|
||||
line: lineNumberAt(content, match.index),
|
||||
snippet: match[0],
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
const allFiles = await walk(repoRoot);
|
||||
const violations = [];
|
||||
|
||||
// After folding media-backend/media-webui directly into the shared repo, this filter targets
|
||||
// the frontend directories where inline HTML/CSS layout violations are actually possible
|
||||
// (the plain Go backend/ and Go media-backend/ have none; there is no more nested shared/).
|
||||
const includedTopLevelDirs = ['media-webui/', 'scripts/media/'];
|
||||
|
||||
for (const filePath of allFiles) {
|
||||
const rel = path.relative(repoRoot, filePath).replaceAll('\\', '/');
|
||||
if (!includedTopLevelDirs.some(prefix => rel.startsWith(prefix))) continue;
|
||||
const content = await fs.readFile(filePath, 'utf8');
|
||||
const hits = [
|
||||
...collectMatches(content, styleDisplayAssign, 'js-style-display'),
|
||||
...collectMatches(content, inlineDisplayStyle, 'inline-style-display'),
|
||||
];
|
||||
if (hits.length) {
|
||||
violations.push({ file: rel, hits });
|
||||
}
|
||||
}
|
||||
|
||||
const total = violations.reduce((sum, row) => sum + row.hits.length, 0);
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
ok: strict ? total === 0 : true,
|
||||
strict,
|
||||
files: violations.length,
|
||||
violations: total,
|
||||
entries: violations,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
|
||||
if (strict && total > 0) {
|
||||
process.exitCode = 1;
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env node
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const repoRoot = path.resolve(__dirname, '..', '..');
|
||||
|
||||
// After a test run we want certain scratch roots removed entirely.
|
||||
// NOTE: These are repo-root directories.
|
||||
const DELETE_DIRS = [
|
||||
'avatars',
|
||||
'thumbnails',
|
||||
'downloads',
|
||||
'logs',
|
||||
'output',
|
||||
'input',
|
||||
'loras',
|
||||
'copy',
|
||||
'database',
|
||||
];
|
||||
|
||||
// Some roots are expected to remain present but empty.
|
||||
// Keep this list lean to avoid surprising destructive behavior.
|
||||
const EMPTY_DIRS = [
|
||||
// (intentionally empty)
|
||||
];
|
||||
|
||||
function rimrafChildren(dir) {
|
||||
if (!fs.existsSync(dir)) return { skipped: true };
|
||||
let removed = 0;
|
||||
for (const entry of fs.readdirSync(dir)) {
|
||||
const full = path.join(dir, entry);
|
||||
try {
|
||||
fs.rmSync(full, { recursive: true, force: true });
|
||||
removed++;
|
||||
} catch (e) {
|
||||
console.error('[CLEAN] Failed removing', full, e.message);
|
||||
}
|
||||
}
|
||||
return { removed };
|
||||
}
|
||||
|
||||
function rimrafDir(dir) {
|
||||
if (!fs.existsSync(dir)) return { skipped: true };
|
||||
try {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
return { deleted: true };
|
||||
} catch (e) {
|
||||
console.error('[CLEAN] Failed removing dir', dir, e.message);
|
||||
return { deleted: false, error: e.message };
|
||||
}
|
||||
}
|
||||
|
||||
function ensureDir(dir) {
|
||||
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
const results = [];
|
||||
for (const rel of EMPTY_DIRS) {
|
||||
const abs = path.join(repoRoot, rel);
|
||||
ensureDir(abs);
|
||||
const res = rimrafChildren(abs);
|
||||
results.push({ dir: rel, mode: 'empty', ...res });
|
||||
}
|
||||
|
||||
const deleted = [];
|
||||
for (const rel of DELETE_DIRS) {
|
||||
const abs = path.join(repoRoot, rel);
|
||||
const res = rimrafDir(abs);
|
||||
deleted.push({ dir: rel, mode: 'delete', ...res });
|
||||
}
|
||||
|
||||
function removeFallbackDirs(baseDir) {
|
||||
let removed = 0;
|
||||
if (!fs.existsSync(baseDir)) return removed;
|
||||
for (const entry of fs.readdirSync(baseDir)) {
|
||||
if (entry.startsWith('tmp-fallback-')) {
|
||||
const full = path.join(baseDir, entry);
|
||||
try {
|
||||
fs.rmSync(full, { recursive: true, force: true });
|
||||
removed++;
|
||||
} catch (e) {
|
||||
console.error('[CLEAN] Failed removing fallback dir', full, e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
// Remove tmp-fallback-* directories from known roots.
|
||||
// Tests can create these in repo root.
|
||||
let fallbackRemoved = 0;
|
||||
fallbackRemoved += removeFallbackDirs(repoRoot);
|
||||
|
||||
// Sweep tests/ folder for orphaned ephemeral Postgres artifacts left behind by crashed runs
|
||||
// or CWD-relative path.resolve('tests').
|
||||
// Pattern: mediacollection-embedded-pg-* dirs, mediacollection-test-postgres-*.json state files.
|
||||
// NOTE: no top-level tests/ dir currently exists and no embedded-postgres JS test tooling was
|
||||
// found anywhere in this repo — this sweep is a harmless no-op today but kept for forward
|
||||
// compatibility / parity with the source script. The former sweep of a nested shared/tests/
|
||||
// was dropped: after folding media-backend/media-webui directly into the shared repo (no more
|
||||
// vendored shared/ copy), there is no longer a nested "shared" subdirectory to sweep.
|
||||
const pgSweepDirs = [path.join(repoRoot, 'tests')];
|
||||
let pgArtifactsRemoved = 0;
|
||||
for (const sweepDir of pgSweepDirs) {
|
||||
try {
|
||||
for (const name of fs.readdirSync(sweepDir)) {
|
||||
if (
|
||||
name.startsWith('mediacollection-embedded-pg-') ||
|
||||
(name.startsWith('mediacollection-test-postgres-') &&
|
||||
(name.endsWith('.json') || name.endsWith('.json.lock'))) ||
|
||||
name.startsWith('media-analyzer-test-')
|
||||
) {
|
||||
const full = path.join(sweepDir, name);
|
||||
try {
|
||||
fs.rmSync(full, { recursive: true, force: true });
|
||||
pgArtifactsRemoved++;
|
||||
} catch (e) {
|
||||
console.error('[CLEAN] Failed removing artifact', full, e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
// If sweepDir is outside the canonical tests/ dir and now empty, remove it entirely.
|
||||
if (sweepDir !== path.join(repoRoot, 'tests')) {
|
||||
try {
|
||||
const remaining = fs.readdirSync(sweepDir);
|
||||
if (remaining.length === 0) {
|
||||
fs.rmdirSync(sweepDir);
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* ignore scan errors */
|
||||
}
|
||||
}
|
||||
|
||||
const summary = { ok: true, cleaned: results, fallbackRemoved, pgArtifactsRemoved };
|
||||
summary.deleted = deleted;
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
|
||||
// Windows occasionally reports a native module handle crash (exit code 3221225477) after
|
||||
// synchronous fs.rmSync bursts. Yield event loop once and exit 0 explicitly to stabilize CI.
|
||||
setTimeout(() => {
|
||||
try {
|
||||
process.exitCode = 0; // be explicit
|
||||
} catch {
|
||||
/* noop */
|
||||
}
|
||||
}, 10);
|
||||
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Enforce design-system CSS constraints for shared theme files.
|
||||
*
|
||||
* Rules enforced:
|
||||
* - Theme CSS must not contain project/service-coupled selector tokens.
|
||||
* - Theme CSS must not contain route-coupled panel IDs in selectors.
|
||||
*
|
||||
* TODO(MediaEngine extraction): the original monorepo version of this script also asserted that
|
||||
* MediaShared/public/css/index.css and MediaDesktop/public/index.css stayed byte-for-byte synced.
|
||||
* That check is no longer possible from inside MediaEngine: MediaDesktop is now a fully separate
|
||||
* repo (Original/MediaDesktop) and isn't checked out alongside this one, so there is nothing here
|
||||
* to diff it against. The desktop-vs-shared theme sync check has been dropped rather than pointed
|
||||
* at a nonexistent path; if that guarantee still matters, it belongs in MediaDesktop's own CI
|
||||
* (comparing its vendored shared/ copy's theme file against its own), not here.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(__dirname, '..', '..');
|
||||
|
||||
// MediaShared/public/css/index.css became packages/media-shared-assets/public/css/index.css
|
||||
// once media-backend/media-webui were folded directly into the shared repo (no more vendored copy).
|
||||
const sharedThemePath = path.join(
|
||||
repoRoot,
|
||||
'packages',
|
||||
'media-shared-assets',
|
||||
'public',
|
||||
'css',
|
||||
'index.css'
|
||||
);
|
||||
|
||||
const bannedSelectorRules = [
|
||||
{
|
||||
name: 'project-coupled service token',
|
||||
regex: /\b(?:kiosk|viewer|moderator|generator|library|analyzer|downloader|servant)-page\b/i,
|
||||
},
|
||||
{
|
||||
name: 'project-coupled state class token',
|
||||
regex:
|
||||
/\b(?:viewer|kiosk|moderator|generator|library|analyzer|downloader|servant)-(?:home|page|stage|mode|active|panel)\b/i,
|
||||
},
|
||||
{
|
||||
name: 'project-prefixed keyframe name',
|
||||
regex:
|
||||
/@keyframes\s+nc-(?:viewer|kiosk|moderator|generator|library|analyzer|downloader|servant)/i,
|
||||
},
|
||||
{
|
||||
name: 'project-coupled data attribute',
|
||||
regex:
|
||||
/\[data-(?:kiosk|viewer|moderator|generator|library|analyzer|downloader|servant)[^\]]*\]/i,
|
||||
},
|
||||
{
|
||||
name: 'route-coupled panel selector',
|
||||
regex: /#panel-[a-z0-9_-]+/i,
|
||||
},
|
||||
];
|
||||
|
||||
function readUtf8(filePath) {
|
||||
return fs.readFileSync(filePath, 'utf8');
|
||||
}
|
||||
|
||||
function stripCssComments(text) {
|
||||
return text.replace(/\/\*[\s\S]*?\*\//g, '');
|
||||
}
|
||||
|
||||
function findViolations(filePath, content) {
|
||||
const cleaned = stripCssComments(content);
|
||||
const lines = cleaned.split(/\r?\n/);
|
||||
const violations = [];
|
||||
|
||||
for (let i = 0; i < lines.length; i += 1) {
|
||||
const line = lines[i];
|
||||
for (const rule of bannedSelectorRules) {
|
||||
if (rule.regex.test(line)) {
|
||||
violations.push({
|
||||
filePath,
|
||||
line: i + 1,
|
||||
rule: rule.name,
|
||||
snippet: line.trim(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return violations;
|
||||
}
|
||||
|
||||
function main() {
|
||||
if (!fs.existsSync(sharedThemePath)) {
|
||||
console.error('[enforce-design-system-css] Missing expected theme file:');
|
||||
console.error(` - ${path.relative(repoRoot, sharedThemePath)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const sharedTheme = readUtf8(sharedThemePath);
|
||||
|
||||
const allViolations = findViolations(sharedThemePath, sharedTheme);
|
||||
|
||||
if (allViolations.length > 0) {
|
||||
console.error('[enforce-design-system-css] Design-system CSS violations found:');
|
||||
for (const v of allViolations) {
|
||||
const rel = path.isAbsolute(v.filePath) ? path.relative(repoRoot, v.filePath) : v.filePath;
|
||||
console.error(` - ${rel}:${v.line} [${v.rule}] ${v.snippet}`);
|
||||
}
|
||||
console.error('[enforce-design-system-css] Fix violations before running lint/test.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log(
|
||||
'[enforce-design-system-css] OK: shared theme is free of project-coupled selectors.'
|
||||
);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* enforce-js-mapping.mjs
|
||||
* Enforces the 1:1 HTML→JS naming rule per §7.1:
|
||||
* public/ must contain exactly as many .js files as .html files,
|
||||
* with matching names (index.html → index.js; all others name.html → name.js).
|
||||
*
|
||||
* Run: node scripts/shared/enforce-js-mapping.mjs
|
||||
*
|
||||
* TODO(MediaEngine extraction): §7.1's 1:1 HTML/JS rule applied to the legacy pre-SvelteKit
|
||||
* `<project>/public/*.html` + `*.js` pages below. MediaEngine's webui/ is SvelteKit-based (routes
|
||||
* under webui/src/routes, no public/*.html+*.js pairs), and none of the other project directories
|
||||
* listed below live inside this repo anymore (they're now separate repos). The existsSync guard
|
||||
* per project means this currently no-ops safely (nothing found to check). Left as-is rather than
|
||||
* inventing a SvelteKit-equivalent rule — remove or repurpose if useful.
|
||||
*/
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const ROOT = path.resolve(__dirname, '..', '..');
|
||||
|
||||
const log = (...args) => console.log('[enforce-js-mapping]', ...args);
|
||||
|
||||
function readFile(p) {
|
||||
return fs.readFileSync(p, 'utf8');
|
||||
}
|
||||
function writeFile(p, content) {
|
||||
fs.writeFileSync(p, content, 'utf8');
|
||||
}
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
function moveFile(src, dst) {
|
||||
fs.mkdirSync(path.dirname(dst), { recursive: true });
|
||||
fs.renameSync(src, dst);
|
||||
}
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
function deleteFile(p) {
|
||||
if (fs.existsSync(p)) fs.unlinkSync(p);
|
||||
}
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
function ensureDir(p) {
|
||||
fs.mkdirSync(p, { recursive: true });
|
||||
}
|
||||
|
||||
// Replace a src path in an HTML file (exact string match on the attribute value)
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
function replaceSrc(htmlPath, oldSrc, newSrc) {
|
||||
let content = readFile(htmlPath);
|
||||
// Match both quoted variants, relative and absolute
|
||||
const escaped = oldSrc.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const re = new RegExp(`(src=["'])${escaped}(["'])`, 'g');
|
||||
if (!re.test(content)) {
|
||||
log(` WARN: could not find src="${oldSrc}" in ${path.relative(ROOT, htmlPath)}`);
|
||||
return;
|
||||
}
|
||||
content = content.replace(re, `$1${newSrc}$2`);
|
||||
writeFile(htmlPath, content);
|
||||
log(` HTML: ${oldSrc} → ${newSrc}`);
|
||||
}
|
||||
|
||||
// Remove an entire <script ... src="..."> line from an HTML file
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
function removeScriptLine(htmlPath, srcValue) {
|
||||
let content = readFile(htmlPath);
|
||||
const escaped = srcValue.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const re = new RegExp(`[ \t]*<script[^>]*src=["']${escaped}["'][^>]*>[ \t]*\n?`, 'g');
|
||||
if (!re.test(content)) {
|
||||
log(` WARN: could not find script src="${srcValue}" in ${path.relative(ROOT, htmlPath)}`);
|
||||
return;
|
||||
}
|
||||
content = content.replace(re, '');
|
||||
writeFile(htmlPath, content);
|
||||
log(` HTML: removed script src="${srcValue}"`);
|
||||
}
|
||||
|
||||
// Append content (from init file) to end of another JS file
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
function appendContent(targetPath, appendContent) {
|
||||
const existing = readFile(targetPath);
|
||||
writeFile(targetPath, existing.trimEnd() + '\n\n' + appendContent.trimStart());
|
||||
}
|
||||
// ─── Verification ─────────────────────────────────────────────────────────────
|
||||
log('\n── Verification ──');
|
||||
const projects = [
|
||||
{ name: 'MediaModerator', publicDir: 'MediaModerator/public' },
|
||||
{ name: 'MediaTools', publicDir: 'MediaTools/public' },
|
||||
{ name: 'MediaTools Converter', publicDir: 'MediaTools/public/converter' },
|
||||
{ name: 'MediaTools Generator', publicDir: 'MediaTools/generator/public' },
|
||||
{ name: 'MediaTools Downloader', publicDir: 'MediaTools/downloader/public' },
|
||||
{ name: 'MediaKiosk', publicDir: 'MediaKiosk/public' },
|
||||
{ name: 'MediaViewer', publicDir: 'MediaViewer/public' },
|
||||
{ name: 'MediaAnalyzer', publicDir: 'MediaAnalyzer/public' },
|
||||
{ name: 'MediaDesktop', publicDir: 'MediaDesktop/public' },
|
||||
];
|
||||
let allOk = true;
|
||||
for (const { name, publicDir } of projects) {
|
||||
const pd = path.join(ROOT, publicDir);
|
||||
if (!fs.existsSync(pd)) continue;
|
||||
|
||||
const htmlFiles = fs
|
||||
.readdirSync(pd)
|
||||
.filter(f => f.endsWith('.html'))
|
||||
.map(f => f.replace(/\.html$/, ''));
|
||||
const jsFiles = fs
|
||||
.readdirSync(pd)
|
||||
.filter(f => f.endsWith('.js'))
|
||||
.map(f => f.replace(/\.js$/, ''));
|
||||
|
||||
// Expected mapping: name.html → name (index.html → index.js, no special case)
|
||||
const expectedJs = htmlFiles.map(h => h).sort();
|
||||
const actualJs = jsFiles.sort();
|
||||
|
||||
const missing = expectedJs.filter(j => !actualJs.includes(j));
|
||||
const extra = actualJs.filter(j => !expectedJs.includes(j));
|
||||
const ok = missing.length === 0 && extra.length === 0;
|
||||
if (!ok) allOk = false;
|
||||
|
||||
const status = ok ? '✅' : '❌';
|
||||
log(` ${status} ${name}: HTML=[${htmlFiles.sort().join(', ')}] JS=[${actualJs.join(', ')}]`);
|
||||
if (missing.length) log(` MISSING JS: ${missing.join(', ')}`);
|
||||
if (extra.length) log(` EXTRA JS: ${extra.join(', ')}`);
|
||||
}
|
||||
|
||||
log(
|
||||
allOk
|
||||
? '\n✅ All projects satisfy the 1:1 HTML↔JS mapping rule.'
|
||||
: '\n❌ Some projects have violations — review above.'
|
||||
);
|
||||
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env node
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(__dirname, '..', '..');
|
||||
|
||||
// The monorepo kept its canonical JS/TS test sources under a single repo-root tests/ dir, which
|
||||
// doesn't exist in MediaEngine. Scan the real locations JS/TS test files can currently live in
|
||||
// this repo instead: webui/src (SvelteKit app) and shared/packages/*/test(s) (vendored from the
|
||||
// shared repo). repoRoot/tests is kept as a forward-compatible root in case one is added later.
|
||||
// As of the MediaEngine extraction none of these contain vitest/mocha/jest-style test files yet
|
||||
// (shared/packages/node-backend/test/auth.test.js uses plain `node --test`, which shares the same
|
||||
// describe/it/test .skip API surface these patterns already match), so this currently passes
|
||||
// trivially rather than being a dead check.
|
||||
const testsRoots = [
|
||||
path.join(repoRoot, 'tests'),
|
||||
path.join(repoRoot, 'media-webui', 'src'),
|
||||
path.join(repoRoot, 'shared', 'packages'),
|
||||
];
|
||||
|
||||
const TEST_FILE_EXTENSIONS = new Set(['.js', '.mjs', '.cjs']);
|
||||
const DISALLOWED_LINE_PATTERNS = [
|
||||
{
|
||||
name: 'skip/todo/runIf declaration',
|
||||
regex: /^\s*(?:await\s+)?(?:it|test|describe)\s*\.\s*(?:skip|todo|skipIf|runIf)\b/,
|
||||
},
|
||||
{
|
||||
name: 'this.skip invocation',
|
||||
regex: /\bthis\s*\.\s*skip\s*\(/,
|
||||
},
|
||||
];
|
||||
|
||||
const SKIP_DIR_NAMES = new Set(['node_modules', '.git', 'dist', 'build', '.svelte-kit']);
|
||||
|
||||
function listTestFiles(dir) {
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
const out = [];
|
||||
const stack = [dir];
|
||||
while (stack.length) {
|
||||
const current = stack.pop();
|
||||
const entries = fs.readdirSync(current, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
const full = path.join(current, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
if (SKIP_DIR_NAMES.has(entry.name)) continue;
|
||||
stack.push(full);
|
||||
} else if (entry.isFile()) {
|
||||
const ext = path.extname(entry.name).toLowerCase();
|
||||
if (TEST_FILE_EXTENSIONS.has(ext)) {
|
||||
out.push(full);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out.sort();
|
||||
}
|
||||
|
||||
function collectViolations(filePath) {
|
||||
const src = fs.readFileSync(filePath, 'utf8');
|
||||
const lines = src.split(/\r?\n/);
|
||||
const violations = [];
|
||||
|
||||
for (let i = 0; i < lines.length; i += 1) {
|
||||
const line = lines[i];
|
||||
for (const pattern of DISALLOWED_LINE_PATTERNS) {
|
||||
if (pattern.regex.test(line)) {
|
||||
violations.push({
|
||||
line: i + 1,
|
||||
name: pattern.name,
|
||||
text: line.trim(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return violations;
|
||||
}
|
||||
|
||||
const files = testsRoots.flatMap(listTestFiles).sort();
|
||||
const failures = [];
|
||||
|
||||
for (const filePath of files) {
|
||||
const violations = collectViolations(filePath);
|
||||
if (violations.length) {
|
||||
failures.push({ filePath, violations });
|
||||
}
|
||||
}
|
||||
|
||||
if (failures.length) {
|
||||
console.error('[enforce-no-skipped-tests] Found disallowed skip-style test usage.');
|
||||
for (const entry of failures) {
|
||||
const rel = path.relative(repoRoot, entry.filePath).replace(/\\/g, '/');
|
||||
for (const v of entry.violations) {
|
||||
console.error(` - ${rel}:${v.line} (${v.name}) -> ${v.text}`);
|
||||
}
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log('[enforce-no-skipped-tests] OK: no skipped/pending test declarations found.');
|
||||
@@ -0,0 +1,3 @@
|
||||
import * as v from 'vitest';
|
||||
console.log('vitest exports sample:', Object.keys(v).slice(0, 20));
|
||||
console.log('has test:', typeof v.test);
|
||||
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Run eslint for each JS/TS package and emit a single JSON summary.
|
||||
* Does NOT print per-file diagnostics unless a failure occurs; keeps CI logs lean while enabling
|
||||
* machine parsing. Exit code is non-zero if any package reports errors or warnings (configurable).
|
||||
*
|
||||
* MediaEngine extraction note: the monorepo version of this script discovered the monorepo root by
|
||||
* walking up for a MediaShared/package.json marker and iterated MediaShared/MediaModerator/
|
||||
* MediaViewer/MediaTools using a shared root eslint.config.mjs. None of those sibling packages or
|
||||
* the root config exist in MediaEngine — webui/ is the only JS/TS package here, and it already
|
||||
* ships its own local eslint.config.js (picked up automatically, no --config override needed).
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, resolve, join } from 'node:path';
|
||||
import { existsSync } from 'node:fs';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const root = resolve(__dirname, '..', '..');
|
||||
|
||||
const packages = [{ name: 'media-webui', path: 'media-webui' }];
|
||||
|
||||
function resolveEslintInvocation({ pkgDir }) {
|
||||
const pkgEslintJs = resolve(pkgDir, 'node_modules', 'eslint', 'bin', 'eslint.js');
|
||||
if (existsSync(pkgEslintJs)) {
|
||||
return { cmd: process.execPath, argsPrefix: [pkgEslintJs] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function spawnCrossPlatform(cmd, args, opts) {
|
||||
if (process.platform === 'win32' && cmd.toLowerCase().endsWith('.cmd')) {
|
||||
return spawnSync('cmd.exe', ['/d', '/s', '/c', cmd, ...args], opts);
|
||||
}
|
||||
return spawnSync(cmd, args, opts);
|
||||
}
|
||||
|
||||
const summary = { timestamp: new Date().toISOString(), packages: [], ok: true };
|
||||
let hadFailure = false;
|
||||
|
||||
for (const pkg of packages) {
|
||||
const pkgDir = resolve(root, pkg.path);
|
||||
const resolved = resolveEslintInvocation({ pkgDir });
|
||||
let result;
|
||||
if (resolved) {
|
||||
result = spawnCrossPlatform(
|
||||
resolved.cmd,
|
||||
[...resolved.argsPrefix, '.', '--format', 'json', '--max-warnings=0'],
|
||||
{
|
||||
cwd: pkgDir,
|
||||
encoding: 'utf8',
|
||||
}
|
||||
);
|
||||
} else {
|
||||
const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
|
||||
result = spawnCrossPlatform(npxCmd, ['eslint', '.', '--format', 'json', '--max-warnings=0'], {
|
||||
cwd: pkgDir,
|
||||
encoding: 'utf8',
|
||||
});
|
||||
}
|
||||
|
||||
if (result.error) {
|
||||
summary.packages.push({ name: pkg.name, error: result.error.message, ok: false });
|
||||
hadFailure = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
let parsed = [];
|
||||
try {
|
||||
parsed = JSON.parse(result.stdout || '[]');
|
||||
} catch (e) {
|
||||
summary.packages.push({
|
||||
name: pkg.name,
|
||||
parseError: e.message,
|
||||
raw: (result.stdout || '').slice(0, 2000),
|
||||
ok: false,
|
||||
});
|
||||
hadFailure = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
let errorCount = 0;
|
||||
let warningCount = 0;
|
||||
let fileCount = 0;
|
||||
for (const file of parsed) {
|
||||
fileCount++;
|
||||
errorCount += file.errorCount || 0;
|
||||
warningCount += file.warningCount || 0;
|
||||
}
|
||||
|
||||
const ok = errorCount === 0 && warningCount === 0; // treat warnings as failures for consistency with --max-warnings=0
|
||||
if (!ok) hadFailure = true;
|
||||
summary.packages.push({ name: pkg.name, fileCount, errorCount, warningCount, ok });
|
||||
}
|
||||
|
||||
summary.ok = !hadFailure;
|
||||
const json = JSON.stringify(summary, null, 2);
|
||||
console.log(json);
|
||||
if (hadFailure) process.exit(1);
|
||||
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Lint all JS/TS packages sequentially with clear section headers, plus a repo-wide Prettier
|
||||
* format check.
|
||||
* Exits non‑zero if any package fails its lint step.
|
||||
*
|
||||
* MediaEngine extraction note: the monorepo version of this script discovered the monorepo root
|
||||
* by walking up for a MediaShared/package.json marker, iterated nine sibling Media* packages
|
||||
* against a shared root eslint.config.mjs/.stylelintrc.json, and ran Prettier/Stylelint out of
|
||||
* MediaShared/node_modules (npm workspace hoisting). None of that exists in MediaEngine: there is
|
||||
* no root package.json, no shared devDependency hoisting, and webui/ is the only JS/TS package —
|
||||
* it already ships its own local eslint.config.js and prettier.config.js. The Stylelint section
|
||||
* has been dropped entirely rather than pointed at a nonexistent .stylelintrc.json: webui has no
|
||||
* stylelint devDependency and its CSS is Tailwind-authored, so there was nothing equivalent to
|
||||
* carry over. If CSS linting is wanted later, it would need its own stylelint config added to
|
||||
* webui/ (or a new root package.json) first.
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { existsSync } from 'node:fs';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const root = resolve(__dirname, '..', '..');
|
||||
|
||||
const packages = [{ name: 'media-webui', path: 'media-webui' }];
|
||||
|
||||
function resolveEslintInvocation({ pkgDir }) {
|
||||
const pkgEslintJs = resolve(pkgDir, 'node_modules', 'eslint', 'bin', 'eslint.js');
|
||||
if (existsSync(pkgEslintJs)) {
|
||||
return { cmd: process.execPath, argsPrefix: [pkgEslintJs] };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function spawnCrossPlatform(cmd, args, opts) {
|
||||
// On Windows, running .cmd directly without a shell can fail. Use cmd.exe wrapper.
|
||||
if (process.platform === 'win32' && cmd.toLowerCase().endsWith('.cmd')) {
|
||||
return spawnSync('cmd.exe', ['/d', '/s', '/c', cmd, ...args], opts);
|
||||
}
|
||||
return spawnSync(cmd, args, opts);
|
||||
}
|
||||
|
||||
let failures = 0;
|
||||
|
||||
for (const pkg of packages) {
|
||||
const pkgDir = resolve(root, pkg.path);
|
||||
console.log(`\n===== LINT: ${pkg.name} (${pkg.path}) =====`);
|
||||
if (!existsSync(pkgDir)) {
|
||||
failures++;
|
||||
console.error(`✖ Lint failed for ${pkg.name} (directory not found at ${pkgDir})`);
|
||||
continue;
|
||||
}
|
||||
const resolved = resolveEslintInvocation({ pkgDir });
|
||||
let result;
|
||||
if (resolved) {
|
||||
result = spawnCrossPlatform(resolved.cmd, [...resolved.argsPrefix, '.', '--max-warnings=0'], {
|
||||
cwd: pkgDir,
|
||||
stdio: 'inherit',
|
||||
env: process.env,
|
||||
});
|
||||
} else {
|
||||
const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
|
||||
result = spawnCrossPlatform(npxCmd, ['eslint', '.', '--max-warnings=0'], {
|
||||
cwd: pkgDir,
|
||||
stdio: 'inherit',
|
||||
env: process.env,
|
||||
});
|
||||
}
|
||||
if (result.error) {
|
||||
failures++;
|
||||
console.error(`✖ Lint failed for ${pkg.name}: ${result.error.message}`);
|
||||
continue;
|
||||
}
|
||||
if (result.status !== 0) {
|
||||
failures++;
|
||||
console.error(`✖ Lint failed for ${pkg.name}`);
|
||||
} else {
|
||||
console.log(`✔ Lint passed for ${pkg.name}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ===== webui: Prettier format check =====
|
||||
console.log('\n===== FORMAT CHECK (Prettier, webui) =====');
|
||||
{
|
||||
const webuiDir = resolve(root, 'media-webui');
|
||||
const prettierBin = resolve(webuiDir, 'node_modules', 'prettier', 'bin', 'prettier.cjs');
|
||||
const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
|
||||
const fmtResult = existsSync(prettierBin)
|
||||
? spawnCrossPlatform(process.execPath, [prettierBin, '--check', '.'], {
|
||||
cwd: webuiDir,
|
||||
stdio: 'inherit',
|
||||
env: process.env,
|
||||
})
|
||||
: spawnCrossPlatform(npxCmd, ['prettier', '--check', '.'], {
|
||||
cwd: webuiDir,
|
||||
stdio: 'inherit',
|
||||
env: process.env,
|
||||
});
|
||||
if (fmtResult.error || fmtResult.status !== 0) {
|
||||
failures++;
|
||||
console.error('✖ Format check failed');
|
||||
} else {
|
||||
console.log('✔ Format check passed');
|
||||
}
|
||||
}
|
||||
|
||||
if (failures > 0) {
|
||||
console.error(`\nLint completed with ${failures} failing check(s).`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log('\nAll lint checks passed.');
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env node
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createRequire } from 'node:module';
|
||||
import path from 'node:path';
|
||||
|
||||
// Run vitest with JSON reporter and parse skipped tests/suites.
|
||||
// Usage: node scripts/list-skipped-tests.mjs
|
||||
// Exits with code 0 if none skipped, 1 if any skipped.
|
||||
//
|
||||
// TODO(MediaEngine extraction): as of the extraction from MediaCollection, MediaEngine has no
|
||||
// vitest suite anywhere (webui/ has no vitest devDependency/config; shared/packages/node-backend
|
||||
// uses plain `node --test`; backend/ is Go), so `require.resolve('vitest/package.json')` below
|
||||
// will fail immediately. The hardcoded `--config ../vitest.config.mjs` below also assumed this
|
||||
// script runs from a subdirectory (e.g. the old repo-root tests/ dir) one level below a
|
||||
// vitest.config.mjs — that layout does not exist in MediaEngine either. Left unfixed rather than
|
||||
// guessed at: revisit once/if a real vitest suite is introduced in this repo, and point the
|
||||
// --config flag at wherever that config actually lives.
|
||||
|
||||
// Resolve local vitest binary (avoid relying on npx which can be absent in some CI / shells)
|
||||
function resolveVitestBin() {
|
||||
try {
|
||||
const require = createRequire(import.meta.url);
|
||||
const pkgPath = require.resolve('vitest/package.json');
|
||||
const binDir = path.dirname(pkgPath);
|
||||
// Vitest exposes a bin field pointing to dist/cli.js; require it to ensure path stability
|
||||
const pkg = require('vitest/package.json');
|
||||
if (pkg && pkg.bin && pkg.bin.vitest) {
|
||||
return path.join(binDir, pkg.bin.vitest);
|
||||
}
|
||||
// Fallback: common location
|
||||
return path.join(binDir, 'dist', 'cli.js');
|
||||
} catch (err) {
|
||||
console.error('[list-skipped-tests] Unable to resolve vitest binary:', err.message);
|
||||
process.exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
const vitestBin = resolveVitestBin();
|
||||
const nodeExec = process.execPath; // Use current Node runtime
|
||||
|
||||
// Always pass explicit config to ensure identical file set as normal test run.
|
||||
// Use 'run' subcommand to execute once (no watch) and JSON reporter for machine parsing.
|
||||
const args = [vitestBin, 'run', '--config', '../vitest.config.mjs', '--reporter=json'];
|
||||
const child = spawn(nodeExec, args, { stdio: ['ignore', 'pipe', 'inherit'] });
|
||||
let jsonBlock = '';
|
||||
child.stdout.on('data', d => {
|
||||
const text = d.toString();
|
||||
// Capture last JSON object emitted by vitest reporter (it prints progress lines + final JSON)
|
||||
jsonBlock += text;
|
||||
});
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
child.on('close', _code => {
|
||||
// Attempt to find the final JSON object (Vitest prints *only* JSON in our current mode but be defensive)
|
||||
const match = jsonBlock.match(/(\{[\s\S]*\})\s*$/);
|
||||
if (!match) {
|
||||
console.error('[list-skipped-tests] Failed to parse Vitest JSON output');
|
||||
process.exit(2);
|
||||
}
|
||||
let report;
|
||||
try {
|
||||
report = JSON.parse(match[1]);
|
||||
} catch (e) {
|
||||
console.error('[list-skipped-tests] JSON parse error', e);
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
// Vitest JSON reporter structure (observed):
|
||||
// { numTotalTests, testResults: [ { name, assertionResults: [ { title, status } ] } ] }
|
||||
// Legacy / alternative structure: { testFiles: [ { file, tests:[{ state }] } ] }
|
||||
const skipped = [];
|
||||
let totalFiles = 0;
|
||||
|
||||
if (Array.isArray(report.testResults)) {
|
||||
totalFiles = report.testResults.length;
|
||||
for (const tr of report.testResults) {
|
||||
const filePath = tr.name || tr.file || 'unknown';
|
||||
(tr.assertionResults || []).forEach(ar => {
|
||||
// Vitest marks skipped tests with status === 'skipped'. Support 'todo' & 'pending' for completeness.
|
||||
if (ar.status === 'skipped' || ar.status === 'todo' || ar.status === 'pending') {
|
||||
skipped.push({ file: filePath, test: ar.fullName || ar.title, state: ar.status });
|
||||
}
|
||||
});
|
||||
}
|
||||
} else if (Array.isArray(report.testFiles)) {
|
||||
// fallback structure
|
||||
totalFiles = report.testFiles.length;
|
||||
for (const f of report.testFiles) {
|
||||
if (!f) continue;
|
||||
const filePath = f.file || f.name || 'unknown';
|
||||
(f.tests || []).forEach(t => {
|
||||
if (t.state === 'skip' || t.state === 'todo' || t.state === 'pending') {
|
||||
skipped.push({ file: filePath, test: t.name, state: t.state });
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.error('[list-skipped-tests] Unrecognized Vitest JSON structure');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const summary = { totalFiles, skippedCount: skipped.length, skipped };
|
||||
console.log(JSON.stringify(summary, null, 2));
|
||||
process.exit(skipped.length > 0 ? 1 : 0);
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env node
|
||||
// Simple timing harness: runs vitest in JSON reporter mode and summarizes collection vs test execution time.
|
||||
//
|
||||
// TODO(MediaEngine extraction): this script assumes a vitest test suite is configured in whatever
|
||||
// directory it's invoked from. As of the extraction from MediaCollection, MediaEngine has no vitest
|
||||
// suite anywhere (webui/ has no vitest devDependency or config; shared/packages/node-backend uses
|
||||
// plain `node --test`; backend/ is Go). This is a generic, path-assumption-free script (no fix
|
||||
// needed for the MediaEngine layout), but it currently has nothing to run against — it will fail
|
||||
// with "vitest not found" / no config until a vitest suite is introduced somewhere in this repo.
|
||||
import { spawn } from 'node:child_process';
|
||||
|
||||
const args = ['vitest', 'run', '--reporter=json'];
|
||||
const child = spawn(process.platform === 'win32' ? 'npx.cmd' : 'npx', args, {
|
||||
stdio: ['ignore', 'pipe', 'inherit'],
|
||||
});
|
||||
|
||||
let json = '';
|
||||
child.stdout.on('data', d => {
|
||||
json += d.toString();
|
||||
});
|
||||
child.on('close', code => {
|
||||
if (code !== 0) {
|
||||
console.error('vitest exited with code', code);
|
||||
process.exit(code);
|
||||
}
|
||||
// Vitest JSON reporter may output multiple JSON objects; take last complete JSON object.
|
||||
const matches = json.trim().match(/\{[\s\S]*$/); // naive: last JSON-like block
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(matches ? matches[0] : json);
|
||||
} catch {
|
||||
console.error('Failed to parse vitest JSON output');
|
||||
process.exit(1);
|
||||
}
|
||||
const summary = data?.summary || {};
|
||||
const out = {
|
||||
testFiles: summary.testFiles ?? summary.files ?? 'n/a',
|
||||
tests: summary.tests ?? 'n/a',
|
||||
durationMs: summary.duration ?? 'n/a',
|
||||
failed: summary.failed ?? 0,
|
||||
skipped: summary.skipped ?? 0,
|
||||
passed: summary.passed ?? 0,
|
||||
// Vitest does not expose collect vs run granularly in JSON; we could extend later by parsing stdout.
|
||||
note: 'For deeper phase timing, run "npx vitest run --reporter basic" and inspect breakdown.',
|
||||
};
|
||||
console.log(JSON.stringify(out, null, 2));
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
const out = { ok: false, error: 'simulate-category-removal removed' };
|
||||
console.error('[simulate-category-removal] removed');
|
||||
console.log(JSON.stringify(out));
|
||||
process.exit(0);
|
||||
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/env node
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const repoRoot = path.resolve(__dirname, '..', '..');
|
||||
|
||||
const registryBase = 'https://registry.npmjs.org';
|
||||
const sections = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];
|
||||
|
||||
function shouldSkipSpec(spec) {
|
||||
if (!spec) return true;
|
||||
const lower = spec.toLowerCase();
|
||||
return (
|
||||
lower.startsWith('file:') ||
|
||||
lower.startsWith('workspace:') ||
|
||||
lower.startsWith('link:') ||
|
||||
lower.startsWith('github:') ||
|
||||
lower.startsWith('git+') ||
|
||||
lower.startsWith('http://') ||
|
||||
lower.startsWith('https://') ||
|
||||
lower.startsWith('npm:')
|
||||
);
|
||||
}
|
||||
|
||||
function isSimpleRange(spec) {
|
||||
if (!spec) return false;
|
||||
if (spec === '*' || spec === 'latest') return true;
|
||||
if (spec.includes(' ') || spec.includes('||')) return false;
|
||||
return /^[~^]?\d+(\.\d+){0,2}([-.][0-9A-Za-z-.]+)?$/.test(spec);
|
||||
}
|
||||
|
||||
function buildNextSpec(currentSpec, latest) {
|
||||
if (currentSpec === '*' || currentSpec === 'latest') {
|
||||
return `^${latest}`;
|
||||
}
|
||||
if (currentSpec.startsWith('~')) return `~${latest}`;
|
||||
if (currentSpec.startsWith('^')) return `^${latest}`;
|
||||
return `^${latest}`;
|
||||
}
|
||||
|
||||
async function fetchLatestVersion(pkgName) {
|
||||
const encoded = encodeURIComponent(pkgName);
|
||||
const res = await fetch(`${registryBase}/${encoded}`);
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to fetch ${pkgName}: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
const data = await res.json();
|
||||
const latest = data?.['dist-tags']?.latest;
|
||||
if (!latest) {
|
||||
throw new Error(`Missing dist-tags.latest for ${pkgName}`);
|
||||
}
|
||||
return latest;
|
||||
}
|
||||
|
||||
async function loadJson(filePath) {
|
||||
const raw = await fs.readFile(filePath, 'utf8');
|
||||
return JSON.parse(raw);
|
||||
}
|
||||
|
||||
async function saveJson(filePath, data) {
|
||||
const next = JSON.stringify(data, null, 2) + '\n';
|
||||
await fs.writeFile(filePath, next, 'utf8');
|
||||
}
|
||||
|
||||
async function updatePackageJson(packageJsonPath) {
|
||||
const pkg = await loadJson(packageJsonPath);
|
||||
let changed = false;
|
||||
const changes = [];
|
||||
|
||||
for (const section of sections) {
|
||||
const deps = pkg[section];
|
||||
if (!deps) continue;
|
||||
|
||||
const entries = Object.entries(deps);
|
||||
for (const [name, spec] of entries) {
|
||||
if (shouldSkipSpec(spec) || !isSimpleRange(spec)) continue;
|
||||
let latest;
|
||||
try {
|
||||
latest = await fetchLatestVersion(name);
|
||||
} catch (err) {
|
||||
console.warn(`[skip] ${name}: ${err.message}`);
|
||||
continue;
|
||||
}
|
||||
const nextSpec = buildNextSpec(spec, latest);
|
||||
if (nextSpec !== spec) {
|
||||
deps[name] = nextSpec;
|
||||
changed = true;
|
||||
changes.push({ name, from: spec, to: nextSpec, section });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
await saveJson(packageJsonPath, pkg);
|
||||
}
|
||||
|
||||
return { changed, changes };
|
||||
}
|
||||
|
||||
// MediaEngine has no root package.json / npm workspaces (unlike the monorepo this was extracted
|
||||
// from), so there's no "workspaces" array to discover packages from. webui/ is the only local npm
|
||||
// package whose dependency versions this repo owns and should bump directly. shared/package.json
|
||||
// is intentionally excluded: it's a vendored, byte-for-byte copy synced in from the separate
|
||||
// shared repo (see scripts/sync-shared.mjs) and any local edit to it would just be overwritten by
|
||||
// the next sync — dependency bumps for shared/ belong upstream in that repo instead.
|
||||
const LOCAL_PACKAGE_DIRS = ['media-webui'];
|
||||
|
||||
async function main() {
|
||||
const packageJsonPaths = LOCAL_PACKAGE_DIRS.map(dir => path.join(repoRoot, dir, 'package.json'));
|
||||
|
||||
const results = [];
|
||||
for (const pkgPath of packageJsonPaths) {
|
||||
try {
|
||||
const result = await updatePackageJson(pkgPath);
|
||||
results.push({ pkgPath, ...result });
|
||||
} catch (err) {
|
||||
console.error(`[error] ${pkgPath}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
const updated = results.filter(r => r.changed);
|
||||
const totalChanges = updated.reduce((sum, r) => sum + r.changes.length, 0);
|
||||
|
||||
console.log(`Updated ${updated.length} package.json file(s).`);
|
||||
console.log(`Total dependency updates: ${totalChanges}`);
|
||||
|
||||
for (const { pkgPath, changes } of updated) {
|
||||
const rel = path.relative(repoRoot, pkgPath);
|
||||
console.log(`\n${rel}`);
|
||||
for (const change of changes) {
|
||||
console.log(` ${change.section}: ${change.name} ${change.from} -> ${change.to}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(err => {
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
Reference in new issue
Block a user