Deploy implemented Videoreg interface and persistent theme cycle
This commit is contained in:
1 parent
6405a8d101
commit
a12eefa1de
98 files changed
+4094
-2319
No files matched your search
@@ -0,0 +1,25 @@
|
||||
/** Audit the actually imported UI graph, public APIs, layers and real consumers. */
|
||||
import ts from 'typescript';
|
||||
import { readdir,readFile,stat,writeFile } from 'node:fs/promises';
|
||||
import { resolve,relative,dirname,sep } from 'node:path';
|
||||
const root=resolve('web-front/src'), fsd=resolve(root,'fsd'), app=resolve(root,'app');
|
||||
async function files(dir){let all=[];for(const d of await readdir(dir,{withFileTypes:true})){const p=resolve(dir,d.name);if(d.isDirectory())all.push(...await files(p));else if(/\.(ts|tsx)$/.test(p)&&!p.endsWith('.test.ts'))all.push(p);}return all;}
|
||||
async function exists(p){try{return (await stat(p)).isFile();}catch{return false;}}
|
||||
async function target(owner,name){let stem;if(name.startsWith('@/'))stem=resolve(root,name.slice(2));else if(name.startsWith('.'))stem=resolve(dirname(owner),name);else return null;for(const p of [stem,...['.ts','.tsx','.json','.css'].map(x=>stem+x),...['index.ts','index.tsx'].map(x=>resolve(stem,x))])if(await exists(p))return p;return null;}
|
||||
const paths=[...await files(fsd),...await files(app)],info=new Map(),errors=[],edges=[];
|
||||
const levels={app:6,pages:5,widgets:4,features:3,entities:2,shared:1};
|
||||
function owner(p){if(p.startsWith(app+sep))return {layer:'app',slice:'app'};const [layer,slice]=relative(fsd,p).split(sep);return {layer,slice};}
|
||||
for(const path of paths){const code=await readFile(path,'utf8'),ast=ts.createSourceFile(path,code,ts.ScriptTarget.Latest,true),imports=[];
|
||||
for(const node of ast.statements){if((ts.isImportDeclaration(node)||ts.isExportDeclaration(node))&&node.moduleSpecifier&&ts.isStringLiteral(node.moduleSpecifier)){const name=node.moduleSpecifier.text,to=await target(path,name);imports.push({name,to,names:ts.isImportDeclaration(node)&&node.importClause?.namedBindings&&ts.isNamedImports(node.importClause.namedBindings)?node.importClause.namedBindings.elements.map(x=>x.name.text):[]});}}
|
||||
const from=owner(path);if((from.layer==='shared'||from.layer==='entities')&&ast.statements.some(n=>ts.isExpressionStatement(n)&&ts.isStringLiteral(n.expression)&&n.expression.text==='use client'))errors.push({kind:'client-boundary-in-shared/entity',file:relative(root,path)});
|
||||
for(const imp of imports){if(imp.name==='@/content/library')errors.push({kind:'compatibility-cycle-risk',file:relative(root,path)});if(!imp.to)continue;if(imp.to.startsWith(fsd+sep)){const dest=owner(imp.to);if(levels[dest.layer]>levels[from.layer]||(dest.layer===from.layer&&dest.slice!==from.slice&&from.layer!=='app'))errors.push({kind:'upward/lateral-import',from:relative(root,path),to:relative(root,imp.to)});if(imp.name.startsWith('@/fsd/')&&!(dest.layer==='shared'&&imp.to.endsWith('.css'))&&!/^index\.tsx?$/.test(imp.to.split(sep).at(-1)))errors.push({kind:'slice-public-api-bypass',from:relative(root,path),import:imp.name});}edges.push({from:relative(root,path),to:relative(root,imp.to),import:imp.name});}
|
||||
info.set(path,{imports,ast});
|
||||
}
|
||||
const active=new Set();async function visit(p){if(active.has(p))return;active.add(p);for(const imp of info.get(p)?.imports??[])if(imp.to)await visit(imp.to);}
|
||||
for(const p of await files(app))await visit(p);
|
||||
const consumers={};for(const [path,data] of info){if(!active.has(path)||path.includes('/pages/ui-kit/'))continue;for(const imp of data.imports)if(imp.name==='@/fsd/shared/ui')for(const name of imp.names)(consumers[name]??=[]).push(relative(root,path));}
|
||||
const ui=info.get(resolve(fsd,'shared/ui/index.tsx'));const exports=ui.ast.statements.filter(n=>ts.isFunctionDeclaration(n)&&n.modifiers?.some(m=>m.kind===ts.SyntaxKind.ExportKeyword)).map(n=>n.name.text);
|
||||
for(const name of exports)if(!consumers[name]?.length)errors.push({kind:'shared-ui-without-real-page-consumer',component:name});
|
||||
if(await exists(resolve(root,'pages/index.tsx')))errors.push({kind:'accidental-next-pages-router'});
|
||||
const report={scope:'Active technical-library FSD graph; inactive legacy catalog shared->entities debt preserved, no runtime cycle inferred',activeSourceFiles:active.size,FSDModules:info.size,edges,sharedComponentRealConsumers:consumers,errors};
|
||||
await writeFile('docs/design-system/fsd-graph.json',JSON.stringify(report,null,2)+'\n');console.log(JSON.stringify({activeFiles:active.size,modules:info.size,sharedComponents:exports.length,errors}));if(errors.length)process.exitCode=1;
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare original corpus, anchors and binary payload against published R3."""
|
||||
from pathlib import Path
|
||||
import hashlib,json,subprocess,sys
|
||||
sys.path.insert(0,str(Path('scripts/rebuild-v2/vendor').resolve()))
|
||||
from bs4 import BeautifulSoup
|
||||
root=Path('.');out=root/'web-front/out';checks=[]
|
||||
def check(kind,path,ok):
|
||||
checks.append(dict(kind=kind,path=path,same=bool(ok)))
|
||||
def digest(data):return hashlib.sha256(data).hexdigest()
|
||||
for name in ['web-front/src/content/v2-articles.json','web-front/src/content/v2-community.json','deploy/legacy-map.conf','deploy/legacy-routes.json','deploy/legacy-matchers.json']:
|
||||
check('immutable-source/legacy',name,(root/name).read_bytes()==subprocess.check_output(['git','show','6405a8d:'+name]))
|
||||
public=subprocess.check_output(['git','ls-tree','-r','--name-only','6405a8d','--','web-front/public'],text=True).splitlines()
|
||||
for name in public:
|
||||
relative=name.removeprefix('web-front/public/');before=subprocess.check_output(['git','show','6405a8d:'+name]);check('original-public-source-bytes',relative,digest((root/name).read_bytes())==digest(before));check('original-public-export-bytes',relative,(out/relative).is_file()and digest((out/relative).read_bytes())==digest(before))
|
||||
articles=json.loads((root/'web-front/src/content/v2-articles.json').read_text())+json.loads((root/'web-front/src/content/v2-community.json').read_text())
|
||||
for article in articles:
|
||||
path=article['path'];soup=BeautifulSoup((out/(path.lstrip('/')+'.html')).read_bytes(),'html.parser');body=soup.select_one('article.article-body');check('real-reader',path,body is not None)
|
||||
if body is None:continue
|
||||
for i,s in enumerate(article['sections']):
|
||||
section=body.find('section',id='section-'+str(i));key=path+'#section-'+str(i);check('anchor-and-toc',key,section is not None and soup.find('a',href='#section-'+str(i))is not None)
|
||||
if section is None:continue
|
||||
check('exact-heading',key,section.h2.get_text()==s['heading']);check('exact-paragraphs',key,[p.get_text()for p in section.find_all('p',recursive=False)]==s['paragraphs'])
|
||||
if s.get('list'):check('exact-list',key,[n.get_text()for n in section.find('ol').find_all('li')]==s['list'])
|
||||
if s.get('note'):check('exact-note',key,section.select_one('.reading-note').get_text()==s['note'])
|
||||
if s.get('code'):check('exact-code',key,section.find('code').get_text()==s['code'])
|
||||
if s.get('table'):
|
||||
t=s['table'];table=section.find('table');check('exact-table-caption',key,table.caption.get_text()==t['caption']);check('exact-table-headers',key,[c.get_text()for c in table.thead.find_all('th')]==t['head']);check('exact-table-cells',key,[[c.get_text()for c in row.find_all(['th','td'])]for row in table.tbody.find_all('tr')]==t['rows'])
|
||||
if s.get('figure'):f=s['figure'];check('exact-figure/caption',key,section.find('img',src=f['src'])is not None and section.find('figcaption').get_text()==f['caption'])
|
||||
for link in s.get('links',[]):a=section.find('a',href=link['href']);check('exact-resource-link',key+' '+link['href'],a is not None and a.get_text()==link['label']+' ↗')
|
||||
for frame in s.get('gallery',[])[:6]:check('original-frame/name',key+' '+frame['filename'],section.find('img',src=frame['src'])is not None and frame['filename']in section.get_text())
|
||||
check('exact-related-targets',path,[a['href']for a in body.select('.related-reading a')]==article['related'])
|
||||
x=dict(scope='Actual rendered historical body/anchors/related and all original public bytes; brand/UI utility additions excluded from historical count',baselineCommit='6405a8d',sourceCommit=json.loads((out/'health/ready').read_text())['metadata']['commitSha'],originalArticles=len(articles),originalPublicFiles=len(public),checks=checks,failures=[x for x in checks if not x['same']],newUtilityRoutes=['/sources','/privacy','/ui-kit'],fullHistoricalRestorationAccepted=False)
|
||||
(root/'docs/design-system/evidence/preservation.json').write_text(json.dumps(x,ensure_ascii=False,indent=2)+'\n');print(json.dumps(dict(checks=len(checks),failures=x['failures'],originalArticles=len(articles),originalPublicFiles=len(public)),ensure_ascii=False));raise SystemExit(1 if x['failures']else 0)
|
||||
@@ -236,12 +236,23 @@ def active_source_files():
|
||||
continue
|
||||
candidates = [stem, *[Path(str(stem) + suffix) for suffix in (".ts", ".tsx", ".js", ".jsx", ".json", ".css")], stem / "index.ts", stem / "index.tsx"]
|
||||
pending.extend(p for p in candidates if p.is_file())
|
||||
# Framework icon conventions and first-party public code/branding have no
|
||||
# import edge, but still belong to the exact source identity.
|
||||
seen.update((ROOT / "web-front/public").glob("*.js"))
|
||||
seen.update(p for p in (ROOT / "web-front/public/brand").rglob("*") if p.is_file())
|
||||
seen.update(p for pattern in ("icon.*", "favicon.ico", "apple-icon.*") for p in (src / "app").glob(pattern) if p.is_file())
|
||||
# Hash the actual build/check inputs too; they are not browser destinations.
|
||||
seen.update(ROOT / name for name in ("package.json", "package-lock.json", "tsconfig.json", "web-front/next.config.ts", "scripts/design-system/check-fsd.mjs", "scripts/rebuild-v2/check-built.py", "scripts/rebuild-v2/decode-raster-sharp.mjs", "scripts/rebuild-v2/check-raster-sharp.mjs"))
|
||||
return sorted(seen)
|
||||
|
||||
|
||||
def source_occurrences(files):
|
||||
occurrences = []
|
||||
for path in files:
|
||||
if not (path.is_relative_to(ROOT / "web-front/src") or path.is_relative_to(ROOT / "web-front/public")):
|
||||
continue # Build/check tooling is hash-bound, not an active web reference.
|
||||
if path.suffix.lower() not in (".ts", ".tsx", ".js", ".jsx", ".css", ".json", ".svg"):
|
||||
continue # Binary sources are hash-bound; never decode them as text.
|
||||
text = path.read_text()
|
||||
relative = path.relative_to(ROOT).as_posix()
|
||||
if path.suffix == ".json":
|
||||
|
||||
@@ -16,6 +16,20 @@ try {
|
||||
assert.equal(report.results[0].width, 64);
|
||||
assert.equal(report.results[0].height, 32);
|
||||
assert.equal(report.results[1].valid, false, 'Truncated PNG must fail, not be skipped or treated as metadata-only pass');
|
||||
const frames = await Promise.all([16, 32, 48].map(size => sharp({ create: { width: size, height: size, channels: 4, background: '#17382f' } }).png().toBuffer()));
|
||||
const directory = Buffer.alloc(6 + frames.length * 16); directory.writeUInt16LE(1, 2); directory.writeUInt16LE(frames.length, 4);
|
||||
let offset = directory.length;
|
||||
frames.forEach((frame, i) => { const at = 6 + i * 16; directory[at] = [16,32,48][i]; directory[at+1] = [16,32,48][i]; directory.writeUInt16LE(1,at+4);directory.writeUInt16LE(32,at+6);directory.writeUInt32LE(frame.length,at+8);directory.writeUInt32LE(offset,at+12);offset += frame.length; });
|
||||
const ico = Buffer.concat([directory,...frames]);
|
||||
await writeFile(join(root,'all-frames.ico'),ico);
|
||||
await writeFile(join(root,'truncated-directory.ico'),ico.subarray(0,24));
|
||||
const bounds=Buffer.from(ico);bounds.writeUInt32LE(0xffffffff,18);await writeFile(join(root,'bad-bounds.ico'),bounds);
|
||||
const overlap=Buffer.from(ico);overlap.writeUInt32LE(directory.length,34);await writeFile(join(root,'overlap.ico'),overlap);
|
||||
const corrupt=Buffer.from(ico);corrupt[directory.length+frames[0].length]=0;await writeFile(join(root,'bad-middle-frame.ico'),corrupt);
|
||||
const icons=await decodeBatch({root,files:['all-frames.ico','truncated-directory.ico','bad-bounds.ico','overlap.ico','bad-middle-frame.ico']});
|
||||
assert.equal(icons.results[0].valid,true);assert.deepEqual(icons.results[0].frames.map(f=>[f.width,f.height]),[[16,16],[32,32],[48,48]]);
|
||||
assert.ok(icons.results.slice(1).every(f=>f.valid===false),'Every corrupt directory/member must fail the full ICO');
|
||||
process.stdout.write(JSON.stringify({test:'all-ICO-frames-and-corruption',status:'passed',results:icons.results})+'\n');
|
||||
process.stdout.write(JSON.stringify({ test: 'full-raster-decode-positive-and-corruption', status: 'passed', results: report.results }) + '\n');
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
|
||||
@@ -1,12 +1,32 @@
|
||||
/** Fully decode all raster pixels with npm-lockfile-pinned sharp; no network. */
|
||||
import sharp from 'sharp';
|
||||
import { realpath } from 'node:fs/promises';
|
||||
import { realpath, readFile } from 'node:fs/promises';
|
||||
import { resolve, sep } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
sharp.cache(false);
|
||||
sharp.concurrency(1);
|
||||
|
||||
/** Decode every PNG-backed ICO directory member, not just its largest frame. */
|
||||
export async function decodeIco(bytes) {
|
||||
if (bytes.length < 6 || bytes.length > 25 * 1024 * 1024 || bytes.readUInt16LE(0) !== 0 || bytes.readUInt16LE(2) !== 1) throw new Error('Invalid ICO header');
|
||||
const count = bytes.readUInt16LE(4), ranges = [], frames = [];
|
||||
if (count < 1 || count > 64 || bytes.length < 6 + count * 16) throw new Error('Invalid ICO directory');
|
||||
for (let i = 0; i < count; i++) {
|
||||
const at = 6 + i * 16, width = bytes[at] || 256, height = bytes[at + 1] || 256;
|
||||
const size = bytes.readUInt32LE(at + 8), offset = bytes.readUInt32LE(at + 12), end = offset + size;
|
||||
if (size < 8 || offset < 6 + count * 16 || end > bytes.length || ranges.some(([a, b]) => offset < b && end > a)) throw new Error('Invalid ICO member bounds/overlap');
|
||||
ranges.push([offset, end]);
|
||||
const png = bytes.subarray(offset, end);
|
||||
if (!png.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) throw new Error('ICO member must be PNG-backed; unsupported DIB is not skipped');
|
||||
const image = sharp(png, { failOn: 'error', limitInputPixels: 65536 });
|
||||
const { info } = await image.raw().toBuffer({ resolveWithObject: true });
|
||||
if (info.width !== width || info.height !== height) throw new Error('ICO directory/pixels dimension mismatch');
|
||||
frames.push({ width, height, decodedBytes: info.size });
|
||||
}
|
||||
return { width: Math.max(...frames.map(f => f.width)), height: Math.max(...frames.map(f => f.height)), format: 'ico', pages: count, decodedBytes: frames.reduce((n, f) => n + f.decodedBytes, 0), frames };
|
||||
}
|
||||
|
||||
export async function decodeBatch({ root, files }) {
|
||||
if (sharp.versions.sharp !== '0.34.5') {
|
||||
throw new Error(`Expected lockfile sharp0.34.5, found ${sharp.versions.sharp}`);
|
||||
@@ -20,6 +40,11 @@ export async function decodeBatch({ root, files }) {
|
||||
try {
|
||||
const candidate = await realpath(resolve(boundary, file));
|
||||
if (!candidate.startsWith(boundary + sep)) throw new Error('Raster path outside public root');
|
||||
if (candidate.toLowerCase().endsWith('.ico')) {
|
||||
const decoded = await decodeIco(await readFile(candidate));
|
||||
results.push({ file, type: 'raster', valid: true, ...decoded, decoder: `sharp${sharp.versions.sharp}/all-ICO-PNG-frames` });
|
||||
continue;
|
||||
}
|
||||
const image = sharp(candidate, { failOn: 'error', animated: true, limitInputPixels: 64000000 });
|
||||
const metadata = await image.metadata();
|
||||
// metadata() alone is insufficient: force actual decode of every pixel.
|
||||
|
||||
Reference in new issue
Block a user