vini-ds 0.1.0-alpha.1 → 0.1.0-alpha.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -4
- package/cli.mjs +425 -83
- package/package.json +25 -18
- package/project-diagnostics.mjs +250 -0
- package/version.mjs +34 -0
package/README.md
CHANGED
|
@@ -1,9 +1,21 @@
|
|
|
1
1
|
# VINi CLI
|
|
2
2
|
|
|
3
|
-
Connect with `npx vini-ds init`. This is a public alpha, 0.1.0-alpha.
|
|
3
|
+
Connect with `npx vini-ds init`. This is a public alpha, 0.1.0-alpha.13; it supports the bounded setup described below. For a reproducible installation, use the exact version.
|
|
4
4
|
|
|
5
|
-
Preview: `npx vini-ds@0.1.0-alpha.
|
|
5
|
+
Preview: `npx vini-ds@0.1.0-alpha.13 init --plan`. Connect: `npx vini-ds@0.1.0-alpha.13 init`.
|
|
6
6
|
|
|
7
|
-
Requires an existing React 18
|
|
7
|
+
Requires an existing Vite project with matching React and React DOM ^18.2.0 or ^19.3.1 and Node 20+. The installer does not edit the React dependency declarations in package.json. Check the lockfile and installed versions after installation; the package manager may resolve dependencies again. Detects npm or pnpm; configures CSS, ThemeBrandProvider and project-local Codex MCP/Skill. Does not change global Codex settings or project trust. This alpha supports the direct createRoot(...).render(JSX) entry form; use --entry for an explicit supported entry. New desktop Codex session discovery is a separate check.
|
|
8
8
|
|
|
9
|
-
Check an existing project with `npx vini-ds@latest status` (or `status --json`). A registry error means the available version is unknown. Review the suggested exact version with `npx vini-ds@0.1.0-alpha.
|
|
9
|
+
Check an existing project with `npx vini-ds@latest status` (or `status --json`). A registry error means the available version is unknown. A package status of current does not verify the open application page or the MCP connection in the current client. Review the suggested exact version with `npx vini-ds@0.1.0-alpha.13 update --plan`. For the name migration, complete the manual review below and use --imports-migrated; other updates use the same command without --plan. Identify the dev or preview server serving the original application URL. If it still serves old assets, update or restart only that server when its ownership and authorization are clear; otherwise ask its owner. Reload the same URL and exercise the affected component; never terminate an unidentified process. In the current project and client, call the connection's `refresh_connection` with the exact selected target when available. For a legacy connection or incompatible interface reconnect the project MCP once; restart the client only if reconnect is unavailable or already failed. In the same project and client read `vini://system/current`, the affected component contract, and `check_updates`; compare their versions with the target, installed packages and receipt. If the context is stale, follow the refresh or reconnect steps and repeat the checks instead of reinstalling packages just to refresh it. A separate STDIO process does not verify the current client. Treat package installation, the application page, and the current MCP client as separate results; if a check cannot be performed, report it as not verified. Update creates a recovery backup; if installation fails, inspect the reported recovery path before retrying. Previously installed private-GitHub Kits need an explicit migration and are not overwritten.
|
|
10
|
+
|
|
11
|
+
## Migrating existing projects to @vini-ds
|
|
12
|
+
|
|
13
|
+
Confirm the exact new CLI and all three packages are actually published before migrating. For a CLI-managed installation, run `npx vini-ds@0.1.0-alpha.13 update --plan` and review the existing receipt and planned dependency changes. Save the project state and manually review and replace every old `@vini/*` or `@timelex/vini-*` import, CSS path, configuration and other reference with the appropriate `@vini-ds/*` name. The CLI does not rewrite arbitrary project sources. Once that review is complete, run `npx vini-ds@0.1.0-alpha.13 update --imports-migrated`; the flag records your review, not proof of it. The CLI validates the entry, avoids an extra provider and replaces the managed dependencies without aliases. Check the build, lockfile and affected application scenario, then reconnect and verify the actual MCP client.
|
|
14
|
+
|
|
15
|
+
Older CLI or MCP instances may report the changed release as unknown after a future latest change; unknown is not proof that no update exists. Use the exact new CLI and reconnect the existing client. Direct unmanaged dependencies using older package names require a separate reviewed manual migration: remove old declarations after reviewing the project, then inspect `init --plan` before installing. No automatic edits to arbitrary project files are performed.
|
|
16
|
+
|
|
17
|
+
## Adopting an existing native installation
|
|
18
|
+
|
|
19
|
+
For a complete, directly installed pair of `@vini-ds/ui` and `@vini-ds/tokens` at the same version, first run `npx vini-ds@0.1.0-alpha.13 init --plan --adopt-manual`. Review the detected versions, React compatibility, source observations and proposed changes. Use `--cwd` for the project root, `--app-root` when the application is nested, and `--entry` when its entry needs to be selected explicitly. When the plan is ready, run the same command without `--plan`. Adoption preserves the installed UI and tokens version and existing entry, CSS imports and provider; it installs the agent at that same version and keeps a recovery backup. It is not an update to the CLI version. Repeating the completed adoption preserves the existing setup.
|
|
20
|
+
|
|
21
|
+
The plan uses static source evidence; it does not establish what renders in the browser or whether the current Codex client is connected. Verify those separately. A shared or symbolic-link `node_modules` is read for diagnostics but blocks adoption without changing its target; arrange an independently managed application directory before applying. Incomplete, mixed, incompatible or aliased installations require individual review. Older package families still follow the reviewed migration above.
|
package/cli.mjs
CHANGED
|
@@ -1,20 +1,45 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { promises as fs } from 'node:fs';
|
|
2
|
+
import { promises as fs, constants as fsConstants } from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { createHash, randomUUID } from 'node:crypto';
|
|
5
|
-
import { createRequire } from 'node:module';
|
|
6
5
|
import { fileURLToPath } from 'node:url';
|
|
7
|
-
import { isDeepStrictEqual } from 'node:util';
|
|
8
|
-
import { spawn } from 'node:child_process';
|
|
6
|
+
import { isDeepStrictEqual, promisify } from 'node:util';
|
|
7
|
+
import { execFile, spawn } from 'node:child_process';
|
|
9
8
|
import ts from 'typescript';
|
|
9
|
+
import { compareVersions, isExactVersion } from './version.mjs';
|
|
10
|
+
import { diagnoseProject } from './project-diagnostics.mjs';
|
|
10
11
|
|
|
11
12
|
const self=fileURLToPath(import.meta.url);
|
|
13
|
+
const execFileAsync=promisify(execFile);
|
|
12
14
|
const digest=value=>createHash('sha256').update(value).digest('hex');
|
|
15
|
+
const shellArg=value=>/^[A-Za-z0-9_./-]+$/u.test(value)?value:`'${value.replaceAll("'", "'\\''")}'`;
|
|
13
16
|
const fail=message=>{throw new Error(`VINi: ${message}`);};
|
|
14
17
|
const exists=async file=>fs.lstat(file).catch(error=>{if(error.code==='ENOENT')return null;throw error;});
|
|
15
|
-
const
|
|
18
|
+
const legacyPackages={ui:'@timelex/vini-ui',tokens:'@timelex/vini-tokens',agent:'@timelex/vini-agent'};
|
|
19
|
+
const nativeDsPackages={ui:'@vini-ds/ui',tokens:'@vini-ds/tokens',agent:'@vini-ds/agent'};
|
|
20
|
+
const packageKeys=['ui','tokens','agent'];
|
|
21
|
+
const isNativeDs=distribution=>!!distribution&&packageKeys.every(key=>distribution[key]===nativeDsPackages[key]);
|
|
22
|
+
const localNames=distribution=>Object.fromEntries(packageKeys.map(key=>[key,isNativeDs(distribution)?nativeDsPackages[key]:`@vini/${key}`]));
|
|
23
|
+
const packageSpec=(distribution,key)=>distribution[key]===localNames(distribution)[key]?distribution.version:`npm:${distribution[key]}@${distribution.version}`;
|
|
24
|
+
const pageCheck='Identify the dev or preview server serving the original application URL. If it still serves old assets, update or restart only that server when its ownership and authorization are clear; otherwise ask its owner. Reload the same URL and exercise the affected component. Do not terminate an unidentified process.';
|
|
25
|
+
const clientCheck='In the current project and client, use this connection’s refresh_connection with the exact selected target when available; then read vini://system/current, the affected component contract and check_updates through that connection and compare them with the target and installed packages. For a legacy connection or incompatible interface, reconnect the project MCP once; restart the client only if reconnect is unavailable or already failed. Do not reinstall packages only to refresh the connection. A separate STDIO process does not verify the current client; report unavailable checks as not verified.';
|
|
26
|
+
const generationPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
|
|
27
|
+
const isGeneration=value=>typeof value==='string'&&value.length===36&&generationPattern.test(value);
|
|
28
|
+
// Interpret only the exact simple caret ranges this CLI can prove; anything
|
|
29
|
+
// else is reported unknown instead of guessing semver compatibility.
|
|
30
|
+
function peerAccepts(range,version){return typeof range==='string'&&typeof version==='string'&&range.split('||').some(part=>{const match=/^\s*\^(\d+)\.(\d+)\.(\d+)\s*$/u.exec(part),v=/^(\d+)\.(\d+)\.(\d+)$/u.exec(version);return !!match&&!!v&&Number(match[1])>0&&Number(v[1])===Number(match[1])&&(Number(v[2])>Number(match[2])||Number(v[2])===Number(match[2])&&Number(v[3])>=Number(match[3]));});}
|
|
31
|
+
function validateNativeManifest(info,key,distribution){
|
|
32
|
+
if(!isNativeDs(distribution))return;
|
|
33
|
+
if(['dependencies','devDependencies','peerDependencies','optionalDependencies'].some(section=>Object.values(info[section]??{}).some(value=>typeof value==='string'&&/^npm:/u.test(value.trim()))))throw new Error(`${key} native package metadata contains an npm alias`);
|
|
34
|
+
if(key==='ui'){
|
|
35
|
+
const name=distribution.tokens,dep=info.dependencies?.[name],peer=info.peerDependencies?.[name];
|
|
36
|
+
if(['dependencies','devDependencies','peerDependencies','optionalDependencies','peerDependenciesMeta'].some(section=>Object.hasOwn(info[section]??{},'@vini/tokens'))||peer!==distribution.version||(dep!==undefined&&dep!==distribution.version)||Object.hasOwn(info.optionalDependencies??{},name)||info.peerDependenciesMeta?.[name]?.optional===true)throw new Error('native UI token dependency does not match the release');
|
|
37
|
+
}
|
|
38
|
+
}
|
|
16
39
|
const pointer='<!-- BEGIN:vini-npm -->\nFor VINi interface work, use `.agents/skills/vini-ds/SKILL.md` and the project-local `vini-ds` MCP server.\n<!-- END:vini-npm -->';
|
|
17
|
-
const usage='vini init|update [--plan] | status [--json] [--cwd PROJECT] [--app-root APP] [--entry src/main.tsx] [--package-manager npm|pnpm] [--registry HTTPS_URL]';
|
|
40
|
+
const usage='vini init [--plan] [--adopt-manual] | update [--plan] [--imports-migrated] | status [--json] [--cwd PROJECT] [--app-root APP] [--entry src/main.tsx] [--package-manager npm|pnpm] [--registry HTTPS_URL]';
|
|
41
|
+
// The package builder disables 19 for a retained delivery whose UI peers do not include it.
|
|
42
|
+
const supportedReact19 = true;
|
|
18
43
|
|
|
19
44
|
export function parseArgs(args) {
|
|
20
45
|
if(args.length===1&&['--help','-h'].includes(args[0]))return {help:true};
|
|
@@ -24,18 +49,33 @@ export function parseArgs(args) {
|
|
|
24
49
|
for(let i=1;i<args.length;i++) {
|
|
25
50
|
if(args[i]==='--plan'){if(options.plan)fail('duplicate --plan');options.plan=true;continue;}
|
|
26
51
|
if(args[i]==='--json'){if(options.json)fail('duplicate --json');options.json=true;continue;}
|
|
52
|
+
if(args[i]==='--imports-migrated'){if(options.importsMigrated)fail('duplicate --imports-migrated');options.importsMigrated=true;continue;}
|
|
53
|
+
if(args[i]==='--adopt-manual'){if(options.adoptManual)fail('duplicate --adopt-manual');options.adoptManual=true;continue;}
|
|
27
54
|
const key=names[args[i]];if(!key||options[key]||!args[i+1]||args[i+1].startsWith('--'))fail(usage);options[key]=args[++i];
|
|
28
55
|
}
|
|
29
56
|
if(options.packageManager&&!['npm','pnpm'].includes(options.packageManager))fail('only npm and pnpm are supported');
|
|
30
57
|
if(options.json&&options.command!=='status')fail('--json is supported by status');
|
|
31
|
-
if(options.command
|
|
58
|
+
if(options.importsMigrated&&options.command!=='update')fail('--imports-migrated is supported by update');
|
|
59
|
+
if(options.adoptManual&&options.command!=='init')fail('--adopt-manual is supported by init');
|
|
60
|
+
if(options.command==='status'&&(options.plan||options.packageManager))fail(usage);
|
|
32
61
|
if(options.registry){const url=new URL(options.registry);if(url.username||url.password||url.search||url.hash||(url.protocol!=='https:'&&!(url.protocol==='http:'&&['localhost','127.0.0.1','[::1]'].includes(url.hostname))))fail('registry must use HTTPS (HTTP localhost is allowed for testing)');}
|
|
33
62
|
return options;
|
|
34
63
|
}
|
|
35
64
|
async function fileBytes(file,optional=false) {
|
|
36
|
-
const
|
|
37
|
-
if(
|
|
38
|
-
|
|
65
|
+
const limit=4*1024*1024;
|
|
66
|
+
if(typeof fsConstants.O_NOFOLLOW!=='number'||typeof fsConstants.O_NONBLOCK!=='number')fail('safe regular-file reads are not supported on this platform');
|
|
67
|
+
let handle;
|
|
68
|
+
try{handle=await fs.open(file,fsConstants.O_RDONLY|fsConstants.O_NOFOLLOW|fsConstants.O_NONBLOCK);}
|
|
69
|
+
catch(error){if(error.code==='ENOENT'){if(optional)return null;fail(`missing ${file}`);}if(['ELOOP','EMLINK'].includes(error.code))fail(`expected bounded regular file: ${file}`);throw error;}
|
|
70
|
+
try{
|
|
71
|
+
const before=await handle.stat({bigint:true});
|
|
72
|
+
if(!before.isFile()||before.size>BigInt(limit))fail(`expected bounded regular file: ${file}`);
|
|
73
|
+
const chunks=[];let total=0;
|
|
74
|
+
while(true){const buffer=Buffer.allocUnsafe(Math.min(65536,limit+1-total));const {bytesRead}=await handle.read(buffer,0,buffer.length,null);if(!bytesRead)break;total+=bytesRead;if(total>limit)fail(`expected bounded regular file: ${file}`);chunks.push(buffer.subarray(0,bytesRead));}
|
|
75
|
+
const after=await handle.stat({bigint:true}),atPath=await fs.lstat(file,{bigint:true}).catch(error=>{if(error.code==='ENOENT')return null;throw error;});
|
|
76
|
+
if(!atPath||!atPath.isFile()||atPath.isSymbolicLink()||before.dev!==atPath.dev||before.ino!==atPath.ino||after.size!==atPath.size||after.mtimeNs!==atPath.mtimeNs||after.ctimeNs!==atPath.ctimeNs||before.dev!==after.dev||before.ino!==after.ino||before.size!==after.size||before.mtimeNs!==after.mtimeNs||before.ctimeNs!==after.ctimeNs||BigInt(total)!==after.size)fail(`file changed during read: ${file}`);
|
|
77
|
+
return Buffer.concat(chunks,total);
|
|
78
|
+
}finally{await handle.close();}
|
|
39
79
|
}
|
|
40
80
|
async function safeParents(root,file) {
|
|
41
81
|
const rel=path.relative(root,file);if(rel.startsWith('..'+path.sep)||path.isAbsolute(rel)||rel==='..')fail('file escapes project');
|
|
@@ -45,26 +85,34 @@ async function safeParents(root,file) {
|
|
|
45
85
|
function text(bytes,label) {const value=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes);if(value.charCodeAt(0)===0xfeff)fail(`${label}: BOM requires manual review`);return value;}
|
|
46
86
|
function json(bytes,label){try{return JSON.parse(text(bytes,label));}catch{fail(`invalid JSON: ${label}`);}}
|
|
47
87
|
function distributionCheck(value) {
|
|
48
|
-
if(!value
|
|
49
|
-
for(const key of ['ui','tokens','agent'])
|
|
88
|
+
if(!value||!isExactVersion(value.version))fail('CLI distribution has no exact version');
|
|
89
|
+
for(const key of ['ui','tokens','agent']){const name=value[key],match=typeof name==='string'&&name.length<=214?/^@[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/.exec(name):null;if(!match||match[0]!==name)fail(`invalid distribution ${key}`);}
|
|
50
90
|
return value;
|
|
51
91
|
}
|
|
92
|
+
function familyTransition(from,to) {
|
|
93
|
+
const keys=['ui','tokens','agent'];
|
|
94
|
+
if(keys.every(key=>from[key]===to[key]))return 'same';
|
|
95
|
+
if(keys.every(key=>from[key]===legacyPackages[key]&&to[key]===`@vini/${key}`)&&compareVersions(to.version,from.version)>0)return 'legacy-to-native';
|
|
96
|
+
if(isNativeDs(to)&&(keys.every(key=>from[key]===legacyPackages[key])||keys.every(key=>from[key]===`@vini/${key}`))&&compareVersions(to.version,from.version)>0)return 'manual-import-migration';
|
|
97
|
+
return 'unsupported';
|
|
98
|
+
}
|
|
52
99
|
export function transformEntry(source,file='main.tsx',distribution) {
|
|
53
100
|
if(source.startsWith('\uFEFF'))fail('entry has a BOM; review it manually');
|
|
54
101
|
const ast=ts.createSourceFile(file,source,ts.ScriptTarget.Latest,true,ts.ScriptKind.TSX);
|
|
55
102
|
if(ast.parseDiagnostics.length)fail('entry has syntax errors');
|
|
103
|
+
const local=localNames(distribution),css=[`${local.tokens}/fonts.css`,`${local.tokens}/themes.css`,`${local.tokens}/typography.css`,`${local.ui}/styles.css`];
|
|
56
104
|
const rootNames=new Set(),rootNamespaces=new Set(),providers=new Set(),imports=new Set();
|
|
57
105
|
for(const statement of ast.statements)if(ts.isImportDeclaration(statement)&&ts.isStringLiteral(statement.moduleSpecifier)) {
|
|
58
106
|
const module=statement.moduleSpecifier.text;imports.add(module);
|
|
59
|
-
if(distribution)for(const key of
|
|
107
|
+
if(distribution)for(const key of packageKeys)for(const published of new Set([distribution[key],legacyPackages[key],`@vini/${key}`,nativeDsPackages[key]])){if(published!==local[key]&&(module===published||module.startsWith(published+'/')))fail(`direct ${published} import requires an explicit manual-to-CLI migration; use one package identity`);}
|
|
60
108
|
const clause=statement.importClause,bindings=clause?.namedBindings;
|
|
61
109
|
if(module==='react-dom/client') {
|
|
62
110
|
if(clause?.name)rootNamespaces.add(clause.name.text);
|
|
63
111
|
if(bindings&&ts.isNamespaceImport(bindings))rootNamespaces.add(bindings.name.text);
|
|
64
112
|
if(bindings&&ts.isNamedImports(bindings))for(const item of bindings.elements)if((item.propertyName?.text??item.name.text)==='createRoot')rootNames.add(item.name.text);
|
|
65
113
|
}
|
|
66
|
-
if(module===
|
|
67
|
-
if(module===
|
|
114
|
+
if(module===local.ui&&bindings&&ts.isNamedImports(bindings))for(const item of bindings.elements)if((item.propertyName?.text??item.name.text)==='ThemeBrandProvider')providers.add(item.name.text);
|
|
115
|
+
if(module===local.ui&&bindings&&ts.isNamespaceImport(bindings))providers.add(`${bindings.name.text}.ThemeBrandProvider`);
|
|
68
116
|
}
|
|
69
117
|
const renders=[];
|
|
70
118
|
const isCreate=expression=>ts.isCallExpression(expression)&&(ts.isIdentifier(expression.expression)?rootNames.has(expression.expression.text):ts.isPropertyAccessExpression(expression.expression)&&ts.isIdentifier(expression.expression.expression)&&rootNamespaces.has(expression.expression.expression.text)&&expression.expression.name.text==='createRoot');
|
|
@@ -76,7 +124,7 @@ export function transformEntry(source,file='main.tsx',distribution) {
|
|
|
76
124
|
const found=[];function findProvider(node){if(ts.isJsxElement(node)&&providers.has(node.openingElement.tagName.getText(ast)))found.push(node);ts.forEachChild(node,findProvider);}findProvider(jsx);
|
|
77
125
|
let result=source;const prepend=css.filter(item=>!imports.has(item)).map(item=>`import ${JSON.stringify(item)};`);
|
|
78
126
|
if(found.length>1)fail('multiple ThemeBrandProvider scopes require manual setup');
|
|
79
|
-
if(!found.length){let alias='ViniThemeBrandProvider';while(new RegExp(`\\b${alias}\\b`).test(source))alias+='Root';prepend.push(`import { ThemeBrandProvider as ${alias} } from "
|
|
127
|
+
if(!found.length){let alias='ViniThemeBrandProvider';while(new RegExp(`\\b${alias}\\b`).test(source))alias+='Root';prepend.push(`import { ThemeBrandProvider as ${alias} } from "${local.ui}";`);const wrapped=`<${alias} theme="light" brand="vini" colorway="blue" typographyScope="desktop">{${argument.getText(ast)}}</${alias}>`;result=source.slice(0,argument.getStart(ast))+wrapped+source.slice(argument.end);}
|
|
80
128
|
else if(found[0]!==jsx){
|
|
81
129
|
// A provider directly inside StrictMode/Fragment still covers the whole app.
|
|
82
130
|
const outer=ts.isJsxElement(jsx)?jsx.children:ts.isJsxFragment(jsx)?jsx.children:[];
|
|
@@ -101,21 +149,41 @@ function agentsMerge(source) {
|
|
|
101
149
|
if(source.includes('<!-- BEGIN:vini-npm -->')||source.includes('<!-- END:vini-npm -->')){if(source.split('<!-- BEGIN:vini-npm -->').length!==2||source.split('<!-- END:vini-npm -->').length!==2||!source.includes(pointer))fail('modified VINi npm instructions need manual merge');return source;}
|
|
102
150
|
return source+(source&&!source.endsWith('\n')?'\n':'')+(source?'\n':'')+pointer+'\n';
|
|
103
151
|
}
|
|
104
|
-
export async function run(executable,args,{cwd,timeout=600000,env=process.env}={}) {
|
|
152
|
+
export async function run(executable,args,{cwd,timeout=600000,env=process.env,stdoutOnly=false}={}) {
|
|
105
153
|
return new Promise((resolve,reject)=>{
|
|
106
|
-
const child=spawn(executable,args,{cwd,env,shell:false,stdio:['ignore','pipe','pipe'],detached:process.platform!=='win32'});let output='',done=false,timed=false,killTimer;
|
|
107
|
-
const finish=error=>{if(done)return;done=true;clearTimeout(timer);clearTimeout(killTimer);error?reject(error):resolve(output);};
|
|
154
|
+
const child=spawn(executable,args,{cwd,env,shell:false,stdio:['ignore','pipe','pipe'],detached:process.platform!=='win32'});let output='',stdout='',done=false,timed=false,killTimer;
|
|
155
|
+
const finish=error=>{if(done)return;done=true;clearTimeout(timer);clearTimeout(killTimer);error?reject(error):resolve(stdoutOnly?stdout:output);};
|
|
108
156
|
const timer=setTimeout(()=>{timed=true;try{if(process.platform!=='win32')process.kill(-child.pid,'SIGTERM');else child.kill('SIGTERM');}catch{}killTimer=setTimeout(()=>{try{if(process.platform!=='win32')process.kill(-child.pid,'SIGKILL');else child.kill('SIGKILL');}catch{}const error=new Error(`${executable} timed out; preserve recovery before retrying`);error.uncertainChildren=true;finish(error);},1000);},timeout);
|
|
109
|
-
|
|
157
|
+
child.stdout.on('data',buf=>{const value=buf.toString();stdout=(stdout+value).slice(-16000);output=(output+value).slice(-16000);});
|
|
158
|
+
child.stderr.on('data',buf=>{output=(output+buf.toString()).slice(-16000);});
|
|
110
159
|
child.on('error',error=>finish(error));child.on('close',code=>{if(timed)return;finish(code===0?null:new Error(`${executable} exited ${code}:\n${output}`));});
|
|
111
160
|
});
|
|
112
161
|
}
|
|
113
|
-
async function
|
|
114
|
-
const
|
|
162
|
+
async function projectModuleEntry(app,entry,{observeLinked=false}={}) {
|
|
163
|
+
const modules=path.join(app,'node_modules'),stat=await exists(modules);
|
|
164
|
+
if(!stat||(!stat.isDirectory()&&!(observeLinked&&stat.isSymbolicLink())))fail('node_modules must be a real project directory');
|
|
165
|
+
const root=await fs.realpath(modules),resolved=await fs.realpath(entry);
|
|
166
|
+
if(!resolved.startsWith(root+path.sep))fail('installed package resolves outside project node_modules');
|
|
167
|
+
return resolved;
|
|
168
|
+
}
|
|
169
|
+
async function manifestForEntry(resolved,name,app,options) {
|
|
170
|
+
resolved=await projectModuleEntry(app,resolved,options);let dir=path.dirname(resolved);
|
|
115
171
|
while(true){const file=path.join(dir,'package.json');if(await exists(file)){const value=json(await fileBytes(file),file);if(value.name&&value.version)return {root:dir,manifest:value,entry:resolved};}const parent=path.dirname(dir);if(parent===dir)fail(`cannot find package metadata: ${name}`);dir=parent;}
|
|
116
172
|
}
|
|
173
|
+
// Node caches resolved pnpm symlink targets in-process. A completed install may
|
|
174
|
+
// replace those symlinks, so inspect the new installation in a fresh process.
|
|
175
|
+
async function freshResolveMaybe(manifest,names,cwd) {
|
|
176
|
+
const script='const {createRequire}=require("node:module");const req=createRequire(process.argv[1]);process.stdout.write(JSON.stringify(JSON.parse(process.argv[2]).map(name=>{try{return {path:req.resolve(name)}}catch(error){return {error:error.code||"unknown"}}})));';
|
|
177
|
+
let output;try{({stdout:output}=await execFileAsync(process.execPath,['-e',script,manifest,JSON.stringify(names)],{cwd,timeout:10000,maxBuffer:1024*1024,encoding:'utf8'}));}catch(error){fail(`fresh package resolution failed (${error.code??'unknown'})`);}
|
|
178
|
+
const entries=JSON.parse(output);if(!Array.isArray(entries)||entries.length!==names.length||!entries.every(value=>value&&((typeof value.path==='string'&&path.isAbsolute(value.path)&&value.error===undefined)||(typeof value.error==='string'&&value.path===undefined))))fail('fresh package resolution returned invalid paths');return entries;
|
|
179
|
+
}
|
|
180
|
+
async function freshResolve(manifest,names,cwd) {
|
|
181
|
+
const entries=await freshResolveMaybe(manifest,names,cwd);
|
|
182
|
+
for(let i=0;i<names.length;i++)if(entries[i].error)fail(`cannot resolve ${names[i]} after install (${entries[i].error})`);
|
|
183
|
+
return entries.map(entry=>entry.path);
|
|
184
|
+
}
|
|
117
185
|
async function verifyAgentContext(runner,entry,distribution,cwd) {
|
|
118
|
-
const result=JSON.parse(await runner(process.execPath,[entry,'--check'],{cwd,timeout:10000}));
|
|
186
|
+
const result=JSON.parse(await runner(process.execPath,[entry,'--check'],{cwd,timeout:10000,stdoutOnly:true}));
|
|
119
187
|
if(result.ok!==true||result.name!==distribution.agent||result.version!==distribution.version)fail('installed agent selfcheck does not match the CLI distribution');
|
|
120
188
|
for(const key of ['ui','tokens','agent'])if(result.packages?.[key]?.name!==distribution[key]||result.packages[key].version!==distribution.version)fail('agent contract and installed npm package pair differ');
|
|
121
189
|
return result;
|
|
@@ -132,23 +200,120 @@ async function readInstallation(root,requestedApp,expected) {
|
|
|
132
200
|
if(raw){receipt=json(raw,receiptPath);if(receipt.installer!=='vini-npm'||!receipt.distribution||typeof receipt.configTable!=='string')fail('unrecognized npm setup receipt');distributionCheck(receipt.distribution);}
|
|
133
201
|
const relative=requestedApp??receipt?.appRoot??'.';const app=await fs.realpath(path.resolve(root,relative));
|
|
134
202
|
if(app!==root&&!app.startsWith(root+path.sep))fail('app root must be inside project');
|
|
203
|
+
let appRootMatchesReceipt=null;
|
|
204
|
+
if(receipt){
|
|
205
|
+
const recorded=typeof receipt.appRoot==='string'?await fs.realpath(path.resolve(root,receipt.appRoot)).catch(()=>null):null;
|
|
206
|
+
appRootMatchesReceipt=!!recorded&&(recorded===root||recorded.startsWith(root+path.sep))&&recorded===app;
|
|
207
|
+
}
|
|
135
208
|
const manifestPath=path.join(app,'package.json');await safeParents(root,manifestPath);
|
|
136
|
-
const
|
|
209
|
+
const manifestBytes=await fileBytes(manifestPath),manifest=json(manifestBytes,manifestPath);
|
|
137
210
|
const dependencies={...manifest.optionalDependencies,...manifest.devDependencies,...manifest.dependencies};
|
|
138
211
|
const lockfiles=[];for(const name of ['package-lock.json','pnpm-lock.yaml']){const bytes=await fileBytes(path.join(app,name),true);if(bytes)lockfiles.push({name,sha256:`sha256:${digest(bytes)}`});}
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
212
|
+
const modulePath=path.join(app,'node_modules'),moduleStat=await exists(modulePath);
|
|
213
|
+
const modules=moduleStat?.isSymbolicLink()?{status:'linked',target:await fs.realpath(modulePath).catch(()=>null)}:moduleStat?.isDirectory()?{status:'local',target:await fs.realpath(modulePath)}:{status:moduleStat?'unsupported':'missing',target:null};
|
|
214
|
+
const installed={};let installedAgent,uiPeers=null,uiRoot=null;
|
|
215
|
+
const keys=['ui','tokens','agent'],local=localNames(receipt?.distribution??expected),resolved=await freshResolveMaybe(manifestPath,keys.map(key=>`${local[key]}${key==='agent'?'/mcp':''}`),app);
|
|
216
|
+
for(const [index,key] of keys.entries()) {
|
|
217
|
+
const alias=local[key];let actual=null,error=null,manifestSha256=null;
|
|
218
|
+
try{if(resolved[index].error){const problem=new Error('not resolvable');problem.code=resolved[index].error;throw problem;}const pkg=await manifestForEntry(resolved[index].path,alias,app,{observeLinked:true});validateNativeManifest(pkg.manifest,key,{...(receipt?.distribution??expected),version:pkg.manifest.version});actual={name:pkg.manifest.name,version:pkg.manifest.version};manifestSha256=`sha256:${digest(JSON.stringify(pkg.manifest))}`;if(key==='agent')installedAgent=pkg;if(key==='ui'){uiPeers=pkg.manifest.peerDependencies??{};uiRoot=pkg.root;}}
|
|
143
219
|
catch(problem){if(problem.code==='MODULE_NOT_FOUND'||problem.code==='ERR_PACKAGE_PATH_NOT_EXPORTED')error='not-resolvable';else error='metadata-unavailable';}
|
|
144
|
-
const declared=dependencies[alias]??null,recorded=receipt?(receipt.distribution
|
|
145
|
-
installed[key]={declared,actual,error,matchesLauncher:!!actual&&actual.name===expected[key]&&actual.version===expected.version,matchesReceipt:!!actual&&!!receipt&&actual.name===receipt.distribution[key]&&actual.version===receipt.distribution.version&&declared===recorded};
|
|
220
|
+
const declared=dependencies[alias]??null,recorded=receipt?packageSpec(receipt.distribution,key):null;
|
|
221
|
+
installed[key]={declared,actual,error,manifestSha256,matchesLauncher:!!actual&&actual.name===expected[key]&&actual.version===expected.version,matchesReceipt:!!actual&&!!receipt&&modules.status==='local'&&actual.name===receipt.distribution[key]&&actual.version===receipt.distribution.version&&declared===recorded};
|
|
146
222
|
}
|
|
147
223
|
let launcher='not-installed';
|
|
148
224
|
if(receipt){const file=path.join(root,'.vini-ds/npm-launcher.mjs');await safeParents(root,file);const bytes=await fileBytes(file,true);launcher=bytes&&digest(bytes)===receipt.launcherSha256?'matches-receipt':'missing-or-modified';}
|
|
149
225
|
let agentContext=null;
|
|
150
|
-
if(installedAgent){const file=path.join(installedAgent.root,'context/current.json');const bytes=await fileBytes(file,true);if(bytes){const current=json(bytes,file);agentContext={version:current.version??null,baseline:current.baseline??null,release:current.viniRelease??null};}}
|
|
151
|
-
|
|
226
|
+
if(installedAgent)try{const file=path.join(installedAgent.root,'context/current.json');const bytes=await fileBytes(file,true);if(bytes){const current=json(bytes,file);agentContext={name:current.name??null,version:current.version??null,packages:current.packages??null,sha256:`sha256:${digest(bytes)}`,baseline:current.baseline??null,release:current.viniRelease??null};}}catch{}
|
|
227
|
+
const runtime={};const runtimeNames=['react','react-dom'],runtimeEntries=await freshResolveMaybe(manifestPath,runtimeNames,app);
|
|
228
|
+
for(const [i,name] of runtimeNames.entries()){
|
|
229
|
+
let actual=null,error=null,reactPeer=null;try{if(runtimeEntries[i].error)throw new Error(runtimeEntries[i].error);const pkg=await manifestForEntry(runtimeEntries[i].path,name,app,{observeLinked:true});actual={name:pkg.manifest.name,version:pkg.manifest.version};reactPeer=pkg.manifest.peerDependencies?.react??null;}catch(problem){error=problem.message;}
|
|
230
|
+
runtime[name]={declared:dependencies[name]??null,actual,error,uiPeer:uiPeers?.[name]??null,...(name==='react-dom'?{reactPeer}:{})};
|
|
231
|
+
}
|
|
232
|
+
const runtimeCompatibility=runtime.react.actual&&runtime['react-dom'].actual&&runtime.react.uiPeer&&runtime['react-dom'].uiPeer&&runtime['react-dom'].reactPeer?{
|
|
233
|
+
status:peerAccepts(runtime.react.uiPeer,runtime.react.actual.version)&&peerAccepts(runtime['react-dom'].uiPeer,runtime['react-dom'].actual.version)&&peerAccepts(runtime['react-dom'].reactPeer,runtime.react.actual.version)?'compatible-by-observed-caret-peers':'unverified-or-incompatible',scope:'installed manifest peers only; does not establish full runtime support',
|
|
234
|
+
}:{status:'unknown',scope:'installed manifest peers only; does not establish full runtime support'};
|
|
235
|
+
const runtimeIdentity={};const uiRuntime=uiRoot?await freshResolveMaybe(path.join(uiRoot,'package.json'),runtimeNames,app):[];
|
|
236
|
+
for(const [i,name] of runtimeNames.entries()){
|
|
237
|
+
try{if(!runtimeEntries[i]?.path||!uiRuntime[i]?.path)throw new Error('not resolved');const [appPath,uiPath]=await Promise.all([projectModuleEntry(app,runtimeEntries[i].path,{observeLinked:true}),projectModuleEntry(app,uiRuntime[i].path,{observeLinked:true})]);runtimeIdentity[name]={status:appPath===uiPath?'same':'different',appPath,uiPath};}catch{runtimeIdentity[name]={status:'unknown'};}
|
|
238
|
+
}
|
|
239
|
+
const manual=manualInstallation(manifest,installed,expected,receipt);
|
|
240
|
+
return {projectRoot:root,appRoot:app,appRootMatchesReceipt,receipt:receipt?{distribution:receipt.distribution,appRoot:receipt.appRoot,...(typeof receipt.generation==='string'?{generation:receipt.generation}:{})}:null,launcher:{status:launcher,expected:receipt?.distribution??null},installed,runtime,runtimeCompatibility,runtimeIdentity,modules,manual,appManifestSha256:`sha256:${digest(manifestBytes)}`,lockfiles,agentContext};
|
|
241
|
+
}
|
|
242
|
+
function manualInstallation(manifest,installed,distribution,receipt) {
|
|
243
|
+
if(receipt)return {status:'managed-by-receipt',reason:null};
|
|
244
|
+
const sections=['dependencies','devDependencies','peerDependencies','optionalDependencies'];
|
|
245
|
+
const records=[];
|
|
246
|
+
for(const section of sections)for(const [name,spec] of Object.entries(manifest[section]??{})){
|
|
247
|
+
const known=packageKeys.some(key=>[distribution[key],legacyPackages[key],`@vini/${key}`,nativeDsPackages[key]].includes(name));
|
|
248
|
+
const alias=typeof spec==='string'&&/^npm:@(?:vini-ds|vini|timelex)\//u.test(spec.trim());
|
|
249
|
+
if(known||alias)records.push({section,name,spec});
|
|
250
|
+
}
|
|
251
|
+
if(!records.length&&!packageKeys.some(key=>installed[key]?.actual))return {status:'not-installed',reason:null};
|
|
252
|
+
if(!isNativeDs(distribution))return {status:'manual-incomplete',reason:'Manual adoption requires the direct @vini-ds package family; inspect existing package identities.',declarations:records};
|
|
253
|
+
const ui=installed.ui?.actual,tokens=installed.tokens?.actual,agent=installed.agent?.actual;
|
|
254
|
+
const expected=key=>records.filter(item=>item.name===distribution[key]);
|
|
255
|
+
const clean=['ui','tokens'].every(key=>expected(key).length===1&&expected(key)[0].section==='dependencies'&&isExactVersion(expected(key)[0].spec)&&installed[key]?.actual?.name===distribution[key]&&installed[key]?.actual?.version===expected(key)[0].spec);
|
|
256
|
+
const agentRecords=expected('agent');
|
|
257
|
+
const agentClean=agentRecords.length===0&&!agent||agentRecords.length===1&&agentRecords[0].section==='devDependencies'&&isExactVersion(agentRecords[0].spec)&&agent?.name===distribution.agent&&agent.version===agentRecords[0].spec&&agent.version===ui?.version;
|
|
258
|
+
const noOther=records.every(item=>packageKeys.some(key=>item.name===distribution[key]));
|
|
259
|
+
if(!clean||!ui||!tokens||ui.version!==tokens.version||!agentClean||!noOther)return {status:'manual-incomplete',reason:'VINi declarations or installed package identities/versions are incomplete, conflicting, or not exact; review them before adoption.',declarations:records};
|
|
260
|
+
return {status:'manual-installed',reason:null,version:ui.version,declarations:records};
|
|
261
|
+
}
|
|
262
|
+
function contextMatchesReceipt(state) {
|
|
263
|
+
const d=state.receipt?.distribution,c=state.agentContext;
|
|
264
|
+
return !!d&&!!c&&c.name===d.agent&&c.version===d.version&&packageKeys.every(key=>c.packages?.[key]?.name===d[key]&&c.packages[key].version===d.version);
|
|
265
|
+
}
|
|
266
|
+
// Directory changes provide an additional conservative signal if a whole
|
|
267
|
+
// lock lifetime falls between two reads; generation catches successful
|
|
268
|
+
// replacements. External installers and filesystems with coarse timestamp
|
|
269
|
+
// resolution remain outside a claim of transactional filesystem snapshots.
|
|
270
|
+
async function readCheckpoint(root,requestedApp) {
|
|
271
|
+
const lock=path.join(root,'.vini-npm-install.lock');
|
|
272
|
+
if(await exists(lock))return null;
|
|
273
|
+
const before=await fs.stat(root,{bigint:true});
|
|
274
|
+
const receiptPath=path.join(root,'.vini-ds/npm-install.json');await safeParents(root,receiptPath);
|
|
275
|
+
const receipt=await fileBytes(receiptPath,true);
|
|
276
|
+
let generation=null,relative=requestedApp??'.';if(receipt)try{const data=JSON.parse(receipt.toString('utf8'));generation=data.generation??null;relative=requestedApp??(typeof data.appRoot==='string'?data.appRoot:'.');}catch{}
|
|
277
|
+
const app=await fs.realpath(path.resolve(root,relative)).catch(()=>null);
|
|
278
|
+
if(!app||(app!==root&&!app.startsWith(root+path.sep)))return null;
|
|
279
|
+
const appStat=await fs.stat(app,{bigint:true});
|
|
280
|
+
const modules=await fs.lstat(path.join(app,'node_modules'),{bigint:true}).catch(error=>{if(error.code==='ENOENT')return null;throw error;});
|
|
281
|
+
const after=await fs.stat(root,{bigint:true});
|
|
282
|
+
const appAfter=await fs.stat(app,{bigint:true});
|
|
283
|
+
const modulesAfter=await fs.lstat(path.join(app,'node_modules'),{bigint:true}).catch(error=>{if(error.code==='ENOENT')return null;throw error;});
|
|
284
|
+
const fingerprint=stat=>stat?{dev:stat.dev,ino:stat.ino,mtime:stat.mtimeNs,ctime:stat.ctimeNs,mode:stat.mode}:null;
|
|
285
|
+
const same=(a,b)=>a===null?b===null:b!==null&&a.dev===b.dev&&a.ino===b.ino&&a.mtime===b.mtime&&a.ctime===b.ctime&&a.mode===b.mode;
|
|
286
|
+
if(await exists(lock)||!same(fingerprint(before),fingerprint(after))||!same(fingerprint(appStat),fingerprint(appAfter))||!same(fingerprint(modules),fingerprint(modulesAfter)))return null;
|
|
287
|
+
return {receipt,root:fingerprint(after),app,appStat:fingerprint(appAfter),modules:fingerprint(modulesAfter),generation};
|
|
288
|
+
}
|
|
289
|
+
function checkpointMatches(first,last) {
|
|
290
|
+
const same=(a,b)=>a===null?b===null:b!==null&&a.dev===b.dev&&a.ino===b.ino&&a.mtime===b.mtime&&a.ctime===b.ctime&&a.mode===b.mode;
|
|
291
|
+
return !!first&&!!last&&same(first.root,last.root)&&first.app===last.app&&same(first.appStat,last.appStat)&&same(first.modules,last.modules)&&
|
|
292
|
+
(first.receipt===null?last.receipt===null:last.receipt!==null&&first.receipt.equals(last.receipt));
|
|
293
|
+
}
|
|
294
|
+
function unverifiedStatus(root,target,reason) {
|
|
295
|
+
const installed=Object.fromEntries(packageKeys.map(key=>[key,{declared:null,actual:null,error:'not-verified',matchesLauncher:false,matchesReceipt:false}]));
|
|
296
|
+
const state={projectRoot:root,appRoot:null,appRootMatchesReceipt:null,receipt:null,launcher:{status:'not-verified',expected:null},installed,lockfiles:[],agentContext:null};
|
|
297
|
+
const verification=verificationState(target,state);verification.installation={...verification.installation,status:'not-verified',matchesTarget:null};
|
|
298
|
+
return {status:'unknown',statusScope:'package-installation-and-registry',...state,launcherVersion:target.version,launcherMatchesInstalled:false,available:{status:'not-checked',reason},familyTransition:null,changes:{status:'unknown'},nextStep:reason,verification,mutated:false};
|
|
299
|
+
}
|
|
300
|
+
async function inspectProject(root,app,entry) {
|
|
301
|
+
try {
|
|
302
|
+
if(!entry){const names=['src/main.tsx','src/main.jsx','src/main.ts','src/main.js'];const found=[];for(const name of names)if(await exists(path.join(app,name)))found.push(path.join(app,name));if(found.length!==1)return {status:'not-inspected',reason:'Select the app entry explicitly to inspect CSS, providers and fonts.'};entry=found[0];}
|
|
303
|
+
return {status:'observed',...await diagnoseProject({projectRoot:root,appRoot:app,entry})};
|
|
304
|
+
}catch(error){return {status:'not-inspected',reason:String(error.message??error)};}
|
|
305
|
+
}
|
|
306
|
+
// These observations are returned with the command, not persisted as a new receipt.
|
|
307
|
+
// A package/launcher check cannot establish what a running application or MCP client sees.
|
|
308
|
+
function verificationState(target,state) {
|
|
309
|
+
const receipt=state.receipt?.distribution??null;
|
|
310
|
+
const matched=!!receipt&&state.appRootMatchesReceipt===true&&state.launcher.status==='matches-receipt'&&contextMatchesReceipt(state)&&packageKeys.every(key=>state.installed[key].matchesReceipt);
|
|
311
|
+
const matchesTarget=matched&&receipt.version===target.version&&packageKeys.every(key=>receipt[key]===target[key]&&state.installed[key].actual?.name===target[key]&&state.installed[key].actual?.version===target.version);
|
|
312
|
+
return {target:{version:target.version,packages:Object.fromEntries(packageKeys.map(key=>[key,target[key]]))},
|
|
313
|
+
installation:{status:!receipt?(state.manual?.status??'not-installed'):matched?'matched':'mismatch',matchesTarget,receipt,packages:state.installed},
|
|
314
|
+
applicationPage:{status:'not-verified',nextStep:pageCheck},
|
|
315
|
+
clientMcp:{status:'not-verified',nextStep:clientCheck},
|
|
316
|
+
completion:{status:'not-verified',reason:'Installation, the application page and the current client MCP are separate checks; the CLI cannot verify the running page or client session.'}};
|
|
152
317
|
}
|
|
153
318
|
const validIntegrity=value=>{if(typeof value!=='string'||!/^sha512-[A-Za-z0-9+/]+={0,2}$/u.test(value))return false;const encoded=value.slice(7),bytes=Buffer.from(encoded,'base64');return bytes.length===64&&bytes.toString('base64')===encoded;};
|
|
154
319
|
function validRelease(value) {
|
|
@@ -156,12 +321,6 @@ function validRelease(value) {
|
|
|
156
321
|
const web=x=>{if(!safe(x))return false;try{const u=new URL(x);return u.protocol==='https:'&&!u.username&&!u.password&&!u.search&&!u.hash;}catch{return false;}};
|
|
157
322
|
return value===null||!!value&&web(value.atlas?.url)&&/^sha256:[0-9a-f]{64}$/u.test(value.atlas.archiveSha256??'')&&safe(value.atlas.siteRelease)&&/^[0-9a-f]{40}$/u.test(value.atlas.commit??'')&&safe(value.delivery?.id)&&/^sha256:[0-9a-f]{64}$/u.test(value.delivery.manifestSha256??'')&&/^sha256:[0-9a-f]{64}$/u.test(value.delivery.packageManifestSha256??'')&&safe(value.changes?.fromVersion)&&safe(value.changes?.summary)&&Array.isArray(value.changes?.components)&&value.changes.components.length<=500&&value.changes.components.every(x=>safe(x)&&x.length<=100);
|
|
158
323
|
}
|
|
159
|
-
function compareVersions(a,b) {
|
|
160
|
-
const parse=x=>{const m=/^(\d+)\.(\d+)\.(\d+)(?:-([a-z0-9.-]+))?$/u.exec(x??'');if(!m)throw new Error('invalid published version');return {core:m.slice(1,4).map(Number),pre:m[4]?.split('.')??null};};
|
|
161
|
-
const x=parse(a),y=parse(b);for(let i=0;i<3;i++)if(x.core[i]!==y.core[i])return Math.sign(x.core[i]-y.core[i]);
|
|
162
|
-
if(!x.pre||!y.pre)return x.pre? -1:y.pre?1:0;
|
|
163
|
-
for(let i=0;i<Math.max(x.pre.length,y.pre.length);i++){const l=x.pre[i],r=y.pre[i];if(l===undefined||r===undefined)return l===undefined?-1:1;if(l===r)continue;const ln=/^\d+$/u.test(l),rn=/^\d+$/u.test(r);if(ln&&rn)return Math.sign(Number(l)-Number(r));if(ln!==rn)return ln?-1:1;return l<r?-1:1;}return 0;
|
|
164
|
-
}
|
|
165
324
|
function registryUrl(raw) {
|
|
166
325
|
const url=new URL(raw);if(url.username||url.password||url.search||url.hash||(url.protocol!=='https:'&&!(url.protocol==='http:'&&['localhost','127.0.0.1','[::1]'].includes(url.hostname))))fail('registry must use HTTPS (HTTP localhost is allowed for testing)');
|
|
167
326
|
if(!url.pathname.endsWith('/'))url.pathname+='/';return url;
|
|
@@ -185,7 +344,15 @@ async function availableRelease(registry,cliName,expected,request=requestMetadat
|
|
|
185
344
|
const entries=await Promise.all(['ui','tokens','agent'].map(async key=>{
|
|
186
345
|
const info=await request(endpoint(distribution[key],distribution.version));
|
|
187
346
|
if(info?.name!==distribution[key]||info.version!==distribution.version||!validIntegrity(info?.dist?.integrity))throw new Error(`${key} exact-version metadata is unavailable or invalid`);
|
|
188
|
-
|
|
347
|
+
validateNativeManifest(info,key,distribution);
|
|
348
|
+
if(key==='ui'){
|
|
349
|
+
const token=localNames(distribution).tokens,native=distribution.tokens===token;
|
|
350
|
+
const dependency=info.dependencies?.[token];
|
|
351
|
+
const peer=info.peerDependencies?.[token];
|
|
352
|
+
const optional=Object.hasOwn(info.optionalDependencies??{},token)||info.peerDependenciesMeta?.[token]?.optional===true;
|
|
353
|
+
if(isNativeDs(distribution)&&['dependencies','peerDependencies','optionalDependencies','peerDependenciesMeta'].some(section=>Object.hasOwn(info[section]??{},'@vini/tokens')))throw new Error('native UI metadata includes old token identity');
|
|
354
|
+
if(optional||(native ? peer!==distribution.version || (dependency!==undefined&&dependency!==distribution.version) : dependency!==`npm:${distribution.tokens}@${distribution.version}` || (peer!==undefined&&peer!==distribution.version)))throw new Error('published UI token dependency does not match the release');
|
|
355
|
+
}
|
|
189
356
|
if(key==='agent'&&!isDeepStrictEqual(info.viniRelease??null,latest.viniRelease??null))throw new Error('CLI and agent release metadata differ');
|
|
190
357
|
return [key,{name:info.name,version:info.version,integrity:info.dist.integrity}];
|
|
191
358
|
}));const packages=Object.fromEntries(entries);
|
|
@@ -195,17 +362,33 @@ async function availableRelease(registry,cliName,expected,request=requestMetadat
|
|
|
195
362
|
export async function status(options={},suppliedDistribution,{request=requestMetadata,cliName,release}={}) {
|
|
196
363
|
const cli=suppliedDistribution?{name:cliName??'vini-ds',viniDistribution:suppliedDistribution,viniRelease:release}:json(await fileBytes(path.join(path.dirname(self),'package.json')),'CLI package');
|
|
197
364
|
const expected=distributionCheck(cli.viniDistribution),root=await fs.realpath(path.resolve(options.cwd??process.cwd()));
|
|
198
|
-
const
|
|
365
|
+
const lockReason='A VINi setup is active, was interrupted, or the project changed while reading. Wait for the owner or inspect .vini-npm-install.lock and the recorded recovery before retrying; do not remove a lock just because it is old.';
|
|
366
|
+
const checkpoint=await readCheckpoint(root,options.appRoot);
|
|
367
|
+
if(!checkpoint)return unverifiedStatus(root,expected,lockReason);
|
|
368
|
+
let state;
|
|
369
|
+
try{state=await readInstallation(root,options.appRoot,expected);}
|
|
370
|
+
catch(error){if(!checkpointMatches(checkpoint,await readCheckpoint(root,options.appRoot)))return unverifiedStatus(root,expected,lockReason);throw error;}
|
|
199
371
|
const registry=options.registry??process.env.npm_config_registry??'https://registry.npmjs.org/';
|
|
200
372
|
const published=await availableRelease(registry,cli.name,expected,request);
|
|
201
|
-
|
|
373
|
+
if(!checkpointMatches(checkpoint,await readCheckpoint(root,options.appRoot)))return unverifiedStatus(root,expected,lockReason);
|
|
374
|
+
let repeated;try{repeated=await readInstallation(root,options.appRoot,expected);}catch{return unverifiedStatus(root,expected,lockReason);}
|
|
375
|
+
if(!isDeepStrictEqual(state,repeated)||!checkpointMatches(checkpoint,await readCheckpoint(root,options.appRoot)))return unverifiedStatus(root,expected,lockReason);
|
|
376
|
+
if(checkpoint.receipt&&!isGeneration(checkpoint.generation)) {
|
|
377
|
+
const result=unverifiedStatus(root,expected,'This legacy receipt has no valid installation generation; installed observations cannot prove a stable snapshot. Review the selected update plan and verify the actual client; do not reinstall only to clear this status.');
|
|
378
|
+
result.available=published;result.installed=state.installed;result.receipt=state.receipt;result.appRoot=state.appRoot;result.appRootMatchesReceipt=state.appRootMatchesReceipt;result.launcher=state.launcher;result.lockfiles=state.lockfiles;result.agentContext=state.agentContext;
|
|
379
|
+
result.verification.installation={...result.verification.installation,receipt:state.receipt?.distribution??null,packages:state.installed};return result;
|
|
380
|
+
}
|
|
381
|
+
const aligned=!!state.receipt&&state.appRootMatchesReceipt&&state.launcher.status==='matches-receipt'&&contextMatchesReceipt(state)&&['ui','tokens','agent'].every(key=>state.installed[key].matchesReceipt);
|
|
202
382
|
const installedVersion=aligned?state.receipt.distribution.version:null;
|
|
203
383
|
const installedToLauncher=aligned&&['ui','tokens','agent'].every(key=>state.installed[key].matchesLauncher);
|
|
204
384
|
const latest=published.status==='available'?published.distribution.version:null;
|
|
385
|
+
const family=aligned&&published.status==='available'?familyTransition(state.receipt.distribution,published.distribution):null;
|
|
205
386
|
const ordering=aligned&&latest?compareVersions(installedVersion,latest):null;
|
|
206
|
-
const relation=!state.receipt?
|
|
207
|
-
const
|
|
208
|
-
|
|
387
|
+
const relation=!state.receipt?state.manual.status:!aligned?'mismatch':published.status!=='available'||family==='unsupported'?'unknown':ordering===0?'current':ordering<0?'update-available':'ahead-of-latest';
|
|
388
|
+
const appRelative=path.relative(root,state.appRoot)||'.',planLocation=` --cwd ${shellArg(root)}${appRelative==='.'?'':` --app-root ${shellArg(appRelative)}`}${options.entry?` --entry ${shellArg(options.entry)}`:''}`;
|
|
389
|
+
const next=relation==='manual-installed'?`Manual UI/tokens are present without a CLI receipt. Review npx ${cli.name}@${expected.version} init --plan --adopt-manual${planLocation}; the running page and client MCP remain separate checks.${state.modules.status==='linked'?' node_modules is shared via a symbolic link: use an independently managed app directory before applying; the linked target will not be changed.':''}`:relation==='manual-incomplete'?state.manual.reason:relation==='not-installed'?`npx ${cli.name}@${expected.version} init --plan`:relation==='mismatch'?(state.appRootMatchesReceipt===false?'Selected app root differs from the recorded npm setup; review the receipt before updating.':!contextMatchesReceipt(state)?'The installed agent context is missing or differs from the recorded package set; inspect the agent and receipt before changing the setup.':'Installed packages or launcher differ from the receipt; resolve the mismatch before updating.'):relation==='unknown'?(family==='unsupported'?'Installed and available package families do not have a supported automatic transition; review the distribution before migration.':'Registry unavailable; retry status before deciding about updates.'):relation==='update-available'?`npx ${cli.name}@${latest} update --plan`:relation==='ahead-of-latest'?'Installed release is newer than the registry latest tag; no downgrade is selected.':'Installed package versions match the latest available release.';
|
|
390
|
+
const diagnostics=await inspectProject(root,state.appRoot,options.entry?path.resolve(state.appRoot,options.entry):undefined);if(!checkpointMatches(checkpoint,await readCheckpoint(root,options.appRoot)))return unverifiedStatus(root,expected,lockReason);
|
|
391
|
+
return {status:relation,statusScope:'package-installation-and-registry',...state,diagnostics,launcherVersion:expected.version,launcherMatchesInstalled:installedToLauncher,available:published,familyTransition:family,changes:published.status==='available'&&family!=='unsupported'?transition(published.release,installedVersion,latest):{status:'unknown'},nextStep:next,verification:verificationState(expected,state),mutated:false};
|
|
209
392
|
}
|
|
210
393
|
export function formatStatus(result) {
|
|
211
394
|
const installed=['ui','tokens','agent'].map(key=>{const p=result.installed[key];return `${key}: ${p.actual?`${p.actual.name}@${p.actual.version}`:'not installed'}${p.error?` (${p.error})`:''}`;}).join('\n');
|
|
@@ -213,10 +396,13 @@ export function formatStatus(result) {
|
|
|
213
396
|
const changes=result.changes.status==='available'?`\nChanges: ${result.changes.summary}\nComponents: ${result.changes.components.join(', ')||'none listed'}`:'';
|
|
214
397
|
const release=result.available.release;
|
|
215
398
|
const site=release?`\nAtlas: ${release.atlas.url} (${release.atlas.siteRelease}, commit ${release.atlas.commit})\nAtlas archive: ${release.atlas.archiveSha256}\nDelivery: ${release.delivery.id}; package manifest: ${release.delivery.packageManifestSha256}; gateway manifest: ${release.delivery.manifestSha256}`:'';
|
|
216
|
-
|
|
399
|
+
const runtime=result.runtime?['react','react-dom'].map(name=>`${name}: declared ${result.runtime[name]?.declared??'missing'}; installed ${result.runtime[name]?.actual?.version??'not resolved'}; UI peer ${result.runtime[name]?.uiPeer??'not observed'}`).join('\n'):'';
|
|
400
|
+
const d=result.diagnostics;
|
|
401
|
+
const source=d?.status==='observed'?`\nStatic source observations (not proof of rendered page):\nCSS imports: ${d.css.imports.map(item=>`${item.file}:${item.line} ${item.specifier}`).join('; ')||'none found'}\nProvider uses: ${d.provider.jsxUses.map(item=>`${item.file}:${item.line} ${item.binding}`).join('; ')||'none found'}\nFont imports: ${d.fonts.imports.map(item=>`${item.file}:${item.line} ${item.specifier} (${item.status??'inspected'})`).join('; ')||'none found'}\nPotentially broad CSS rules (inspect actual cascade):\n${d.css.potentiallyBroadRules.map(item=>`${item.file}:${item.line} ${item.selector} [${item.properties.join(', ')}]${item.media.length?' '+item.media.join(' '):''}`).join('\n')||'none found'}\nUnresolved source imports: ${d.unresolved.length}; coverage: ${d.coverage}`:`\nSource diagnostics: ${d?.reason??'not inspected'}`;
|
|
402
|
+
return `VINi package status: ${result.status}\nSelected CLI target: ${result.verification.target.version}\n${installed}\n${runtime}\nCompatibility: ${result.runtimeCompatibility?.status??'unknown'} (observed installed peers only)\nReact identity (app / UI): ${result.runtimeIdentity?.react?.status??'unknown'}; React DOM: ${result.runtimeIdentity?.['react-dom']?.status??'unknown'}\nnode_modules: ${result.modules?.status??'not verified'}${result.modules?.status==='linked'?` -> ${result.modules.target??'unresolved'}`:''}\nLauncher expects: ${result.launcherVersion}\nReceipt: ${result.receipt?.distribution.version??'not installed'}; launcher: ${result.launcher.status}\nAvailable published release: ${available}${site}${changes}${source}\n${result.nextStep}\nUpdate completion: not verified\nApplication page: not verified\n${result.verification.applicationPage.nextStep}\nCurrent client MCP: not verified\n${result.verification.clientMcp.nextStep}`;
|
|
217
403
|
}
|
|
218
404
|
function launcher(distribution,appRelative) {
|
|
219
|
-
return `// Generated by VINi npm CLI; resolves persistent project packages, never npx cache.\nimport { createRequire } from 'node:module';\nimport { readFileSync, existsSync } from 'node:fs';\nimport { spawn } from 'node:child_process';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nconst project=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');\nconst req=createRequire(path.join(project
|
|
405
|
+
return `// Generated by VINi npm CLI; resolves persistent project packages, never npx cache.\nimport { createRequire } from 'node:module';\nimport { readFileSync, existsSync, realpathSync } from 'node:fs';\nimport { spawn } from 'node:child_process';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nconst project=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');\nconst appRelative=${JSON.stringify(appRelative)};\nconst req=createRequire(path.join(project,appRelative,'package.json'));\nconst expected=${JSON.stringify(distribution)};\nconst local=${JSON.stringify(localNames(distribution))};\nlet agentRoot;\nfor(const key of ['tokens','ui','agent']) { const entry=req.resolve(local[key]+(key==='agent'?'/mcp':'')); let dir=path.dirname(entry), meta; while(true){const file=path.join(dir,'package.json');if(existsSync(file)){meta=JSON.parse(readFileSync(file,'utf8'));if(meta.name&&meta.version)break;} const parent=path.dirname(dir);if(parent===dir)throw Error('VINi package metadata missing');dir=parent;} if(meta.name!==expected[key]||meta.version!==expected.version)throw Error('VINi installed package/agent versions differ; inspect the receipt and installed packages');if(key==='agent')agentRoot=realpathSync(dir);}\nlet supervisor;try{supervisor=realpathSync(req.resolve(local.agent+'/supervisor'));}catch{throw Error('Installed VINi agent does not provide a managed connection; review the selected release and reconnect the project MCP');}\nif(!supervisor.startsWith(agentRoot+path.sep))throw Error('VINi supervisor is outside the selected agent package');\nconst child=spawn(process.execPath,[supervisor,'--project-root',project,'--app-root',appRelative],{stdio:'inherit',cwd:project});\nfor(const sig of ['SIGINT','SIGTERM'])process.on(sig,()=>child.kill(sig));\nchild.on('error',error=>{console.error(error.message);process.exitCode=1;});\nchild.on('exit',(code,signal)=>{process.exitCode=code??1;});\n`;
|
|
220
406
|
}
|
|
221
407
|
async function managerFor(root,app,options,manifest) {
|
|
222
408
|
const dirs=[];let dir=app;while(true){dirs.push(dir);if(dir===root)break;dir=path.dirname(dir);}
|
|
@@ -231,33 +417,151 @@ async function managerFor(root,app,options,manifest) {
|
|
|
231
417
|
if(manifest.workspaces)fail('workspace root is not supported by this alpha; choose a standalone Vite app');
|
|
232
418
|
return manager??'npm';
|
|
233
419
|
}
|
|
234
|
-
|
|
420
|
+
// The lock is taken before reading the installation or making any mutation
|
|
421
|
+
// decision. Its metadata is diagnostic only: a PID or timestamp does not prove
|
|
422
|
+
// that a former owner (or its package-manager children) has stopped.
|
|
423
|
+
async function acquireInstallLock(root,command) {
|
|
424
|
+
const directory=path.join(root,'.vini-npm-install.lock'),ownerFile=path.join(directory,'owner.json');
|
|
425
|
+
try{await fs.mkdir(directory,{mode:0o700});}catch(error){if(error.code==='EEXIST')fail('another VINi setup is active or previous recovery needs review; inspect .vini-npm-install.lock and .vini-ds-recovery before retrying');throw error;}
|
|
426
|
+
const identity=await fs.lstat(directory), owner={version:1,nonce:randomUUID(),pid:process.pid,startedAt:new Date().toISOString(),command:command??'init',recovery:null};
|
|
427
|
+
let expected=Buffer.from(JSON.stringify(owner,null,2)+'\n');
|
|
428
|
+
try{await fs.writeFile(ownerFile,expected,{flag:'wx',mode:0o600});}catch(error){await fs.rmdir(directory).catch(()=>{});throw error;}
|
|
429
|
+
async function owns() {
|
|
430
|
+
const current=await fs.lstat(directory).catch(()=>null);
|
|
431
|
+
if(!current||!current.isDirectory()||current.isSymbolicLink()||current.dev!==identity.dev||current.ino!==identity.ino)return false;
|
|
432
|
+
const names=await fs.readdir(directory);
|
|
433
|
+
if(names.length!==1||names[0]!=='owner.json')return false;
|
|
434
|
+
const contents=await fileBytes(ownerFile,true);
|
|
435
|
+
return !!contents&&contents.equals(expected);
|
|
436
|
+
}
|
|
437
|
+
return {
|
|
438
|
+
async recordRecovery(recovery) {
|
|
439
|
+
if(!await owns())fail('VINi setup lock changed; preserve it and inspect recovery before retrying');
|
|
440
|
+
owner.recovery=recovery;const next=Buffer.from(JSON.stringify(owner,null,2)+'\n');
|
|
441
|
+
await fs.writeFile(ownerFile,next,{mode:0o600});expected=next;
|
|
442
|
+
},
|
|
443
|
+
async release() {
|
|
444
|
+
if(!await owns())fail('VINi setup lock changed; preserve it and inspect recovery before retrying');
|
|
445
|
+
await fs.unlink(ownerFile);await fs.rmdir(directory);
|
|
446
|
+
},
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
export async function init(options={},suppliedDistribution,dependencies={}) {
|
|
451
|
+
const root=await fs.realpath(path.resolve(options.cwd??process.cwd()));
|
|
452
|
+
if(options.plan){
|
|
453
|
+
const checkpoint=await readCheckpoint(root,options.appRoot),reason='another VINi setup is active or previous recovery needs review; inspect .vini-npm-install.lock before planning';
|
|
454
|
+
if(!checkpoint)fail(reason);
|
|
455
|
+
let plan;try{plan=await initWithLock({...options,cwd:root},suppliedDistribution,dependencies);}catch(error){if(!checkpointMatches(checkpoint,await readCheckpoint(root,options.appRoot)))fail('VINi setup changed while planning; inspect the lock and recovery before retrying');throw error;}
|
|
456
|
+
if(!checkpointMatches(checkpoint,await readCheckpoint(root,options.appRoot)))fail('VINi setup changed while planning; inspect the lock and recovery before retrying');
|
|
457
|
+
if(checkpoint.receipt&&!isGeneration(checkpoint.generation)){
|
|
458
|
+
plan.installedStatus='unverified';plan.changes={status:'not-available'};
|
|
459
|
+
plan.verification.installation={...plan.verification.installation,status:'not-verified',matchesTarget:null};
|
|
460
|
+
plan.snapshotNote='Legacy receipt has no valid generation; observations cannot prove a stable installation snapshot. The actual update rechecks under its lock.';
|
|
461
|
+
}
|
|
462
|
+
return plan;
|
|
463
|
+
}
|
|
464
|
+
const lock=await acquireInstallLock(root,options.command);let retain=false,primary,result;
|
|
465
|
+
try{result=await initWithLock({...options,cwd:root},suppliedDistribution,{...dependencies,recordRecovery:lock.recordRecovery});return result;}
|
|
466
|
+
catch(error){primary=error;retain=error.retainInstallLock===true;throw error;}
|
|
467
|
+
finally{if(!retain)try{await lock.release();}catch(cleanupError){if(primary){const combined=new Error(`${primary.message}; lock cleanup also failed: ${cleanupError.message}`);combined.cause=primary;throw combined;}throw new Error(`VINi operation may have completed (${result?.status??'unknown'}); saved originals: ${result?.recovery??'none for a no-op'}; lock cleanup failed: ${cleanupError.message}`);}}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
async function initWithLock(options={},suppliedDistribution,{runner=run,releaseMetadata,recordRecovery}={}) {
|
|
235
471
|
const cli=suppliedDistribution?null:json(await fileBytes(path.join(path.dirname(self),'package.json')),'CLI package');
|
|
236
|
-
|
|
237
|
-
|
|
472
|
+
let distribution=distributionCheck(suppliedDistribution??cli.viniDistribution);
|
|
473
|
+
let release=releaseMetadata??cli?.viniRelease;
|
|
238
474
|
if(release&&!validRelease(release))fail('invalid CLI release metadata');
|
|
239
475
|
const root=await fs.realpath(path.resolve(options.cwd??process.cwd()));
|
|
240
|
-
const
|
|
476
|
+
const kit=path.join(root,'.vini-ds'),receiptPath=path.join(kit,'npm-install.json');await safeParents(root,receiptPath);
|
|
477
|
+
const kitStat=await exists(kit),receiptBytes=await fileBytes(receiptPath,true);let previous=null;
|
|
478
|
+
if(kitStat&&!receiptBytes)fail('existing .vini-ds belongs to another setup; migrate the private-GitHub Kit explicitly before npm init');
|
|
479
|
+
if(receiptBytes){previous=json(receiptBytes,receiptPath);if(previous.installer!=='vini-npm'||!previous.distribution||typeof previous.configTable!=='string')fail('unrecognized npm setup receipt');distributionCheck(previous.distribution);}
|
|
480
|
+
if(options.command==='update'&&!previous)fail('no npm VINi setup to update; use init');
|
|
481
|
+
if(previous&&typeof previous.appRoot!=='string')fail('npm setup receipt has no valid app root');
|
|
482
|
+
const app=await fs.realpath(path.resolve(root,options.appRoot??previous?.appRoot??'.'));
|
|
241
483
|
if(app!==root&&!app.startsWith(root+path.sep))fail('app root must be inside project');
|
|
242
484
|
const manifestFile=path.join(app,'package.json'),manifest=json(await fileBytes(manifestFile),manifestFile);
|
|
243
485
|
const deps={...manifest.devDependencies,...manifest.dependencies};
|
|
244
|
-
const
|
|
245
|
-
|
|
246
|
-
if(
|
|
486
|
+
const initial=await readInstallation(root,path.relative(root,app)||'.',distribution);
|
|
487
|
+
const resumingAdoption=!!previous&&!!options.adoptManual&&previous.entryMode==='preserved-manual';
|
|
488
|
+
if(options.adoptManual&&previous&&!resumingAdoption)fail('this project already has a managed receipt; use status or update');
|
|
489
|
+
if(options.adoptManual&&!previous&&initial.manual.status!=='manual-installed')fail(`manual adoption requires a verified installed direct UI/tokens pair: ${initial.manual.reason??initial.manual.status}`);
|
|
490
|
+
if(resumingAdoption){if(packageKeys.some(key=>previous.distribution[key]!==distribution[key]))fail('recorded adoption uses a different package family');distribution=previous.distribution;release=null;}
|
|
491
|
+
const directIncomplete=isNativeDs(distribution)&&initial.manual.status==='manual-incomplete'&&(initial.manual.declarations??[]).every(item=>packageKeys.some(key=>item.name===distribution[key]));
|
|
492
|
+
if(!previous&&directIncomplete&&options.plan)return {status:'plan-only',command:'init',projectRoot:root,appRoot:app,installedStatus:initial.manual.status,installed:initial.installed,runtime:initial.runtime,runtimeCompatibility:initial.runtimeCompatibility,modules:initial.modules,manual:initial.manual,diagnostics:await inspectProject(root,app),mutated:false,nextStep:initial.manual.reason,applicationPage:'not-verified',nativeClient:'not-verified'};
|
|
493
|
+
if(!previous&&directIncomplete)fail(initial.manual.reason);
|
|
494
|
+
if(!previous&&initial.manual.status==='manual-installed'&&!options.adoptManual&&!options.plan)fail('existing direct VINi packages are not managed by this npm setup; review init --plan --adopt-manual, then explicitly choose adoption');
|
|
495
|
+
const adopting=!previous&&initial.manual.status==='manual-installed'&&(options.adoptManual||options.plan);
|
|
496
|
+
if(adopting){
|
|
497
|
+
if(compareVersions(initial.manual.version,distribution.version)>0)fail('installed manual release is newer than this CLI; use its matching or newer CLI and do not downgrade');
|
|
498
|
+
distribution={...distribution,version:initial.manual.version};
|
|
499
|
+
if(distribution.version!==(suppliedDistribution??cli.viniDistribution).version)release=null;
|
|
500
|
+
}
|
|
501
|
+
// Accept a bounded exact/caret/tilde declaration whose lower bound is covered by
|
|
502
|
+
// the public compatibility range. Do not rewrite React dependency declarations.
|
|
503
|
+
const runtimeMajor = value => {
|
|
504
|
+
const match = typeof value === 'string' && /^(?:\^|~)?(18|19)\.(\d+)\.(\d+)$/.exec(value);
|
|
505
|
+
if (!match) return null;
|
|
506
|
+
const major = Number(match[1]), minor = Number(match[2]), patch = Number(match[3]);
|
|
507
|
+
if (major === 18 && minor < 2) return null;
|
|
508
|
+
if (major === 19 && (!supportedReact19 || minor < 3 || (minor === 3 && patch < 1))) return null;
|
|
509
|
+
return major;
|
|
510
|
+
};
|
|
511
|
+
const reactMajor = runtimeMajor(deps.react), domMajor = runtimeMajor(deps['react-dom']);
|
|
512
|
+
if (!reactMajor || reactMajor !== domMajor) fail(`this alpha requires matching existing React and React DOM dependencies in ${supportedReact19 ? '^18.2.0 or ^19.3.1' : '^18.2.0'}; their dependency declarations will not be changed`);
|
|
513
|
+
if(adopting||resumingAdoption){
|
|
514
|
+
for(const name of ['react','react-dom']){const observed=initial.runtime[name];if(observed.actual?.name!==name||!peerAccepts(observed.uiPeer,observed.actual.version))fail(`installed ${name} is not verified compatible with the existing UI peer ${observed.uiPeer??'(not available)'}`);}
|
|
515
|
+
if(!peerAccepts(initial.runtime['react-dom'].reactPeer,initial.runtime.react.actual.version))fail('installed react-dom peer for React is incompatible or cannot be interpreted safely');
|
|
516
|
+
if(initial.runtime.react.actual.version.split('.')[0]!==initial.runtime['react-dom'].actual.version.split('.')[0])fail('installed React and React DOM majors differ');
|
|
517
|
+
for(const name of ['react','react-dom'])if(deps[name]!==initial.runtime[name].actual.version)fail(`manual adoption requires the existing ${name} declaration to match its exact installed version; review version and lockfile first`);
|
|
518
|
+
for(const name of ['react','react-dom'])if(initial.runtimeIdentity[name].status!=='same')fail(`existing UI and app do not resolve the same ${name} instance; inspect installed dependencies`);
|
|
519
|
+
}
|
|
247
520
|
const manager=await managerFor(root,app,options,manifest);
|
|
248
521
|
let entry;
|
|
249
522
|
if(options.entry)entry=path.resolve(app,options.entry);
|
|
250
523
|
else {const candidates=[];for(const name of ['src/main.tsx','src/main.jsx','src/main.ts','src/main.js'])if(await exists(path.join(app,name)))candidates.push(path.join(app,name));if(candidates.length!==1)fail('cannot identify one Vite React entry; pass --entry src/main.tsx');entry=candidates[0];}
|
|
251
524
|
await safeParents(root,entry);if(entry!==app&&!entry.startsWith(app+path.sep))fail('entry must be inside app');
|
|
252
|
-
const entryBefore=await fileBytes(entry),
|
|
253
|
-
const
|
|
254
|
-
const
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
const
|
|
259
|
-
|
|
260
|
-
|
|
525
|
+
const entryBefore=await fileBytes(entry);let entryAfter,entryPreparation='ready';
|
|
526
|
+
const diagnostics=await inspectProject(root,app,entry);
|
|
527
|
+
const requiredCss=[`${localNames(distribution).tokens}/fonts.css`,`${localNames(distribution).tokens}/themes.css`,`${localNames(distribution).tokens}/typography.css`,`${localNames(distribution).ui}/styles.css`];
|
|
528
|
+
const missingCss=requiredCss.filter(specifier=>!diagnostics.css?.imports?.some(item=>item.specifier===specifier&&item.kind==='static'&&item.reachability==='static'&&item.resolution?.status==='resolved'));
|
|
529
|
+
const allProviderUses=diagnostics.provider?.jsxUses??[],providerUses=allProviderUses.filter(item=>item.reachability==='static').length;
|
|
530
|
+
const incompleteGraph=diagnostics.status!=='observed'||diagnostics.scope?.truncated||diagnostics.unresolved?.length>0;
|
|
531
|
+
const adoptionEvidence={status:!incompleteGraph&&missingCss.length===0&&providerUses===1&&allProviderUses.length===1?'observed':'review-required',missingCss,providerUses,otherProviderUses:allProviderUses.length-providerUses,incompleteGraph:!!incompleteGraph,note:'Source observations (including traversed literal dynamic imports) do not prove the rendered root, active styles, fonts or client MCP.'};
|
|
532
|
+
try {entryAfter=adopting||resumingAdoption||previous?.entryMode==='preserved-manual'?entryBefore:Buffer.from(transformEntry(text(entryBefore,entry),entry,distribution));}
|
|
533
|
+
catch(error){if(options.plan&&previous&&isNativeDs(distribution)&&/direct .* import requires an explicit manual-to-CLI migration/.test(error.message)){entryAfter=null;entryPreparation='manual-import-migration-required';}else throw error;}
|
|
534
|
+
if(previous){
|
|
535
|
+
let recordedApp;try{recordedApp=await fs.realpath(path.resolve(root,previous.appRoot));}catch{fail('recorded npm app root is unavailable; review the setup before updating');}
|
|
536
|
+
if(recordedApp!==root&&!recordedApp.startsWith(root+path.sep))fail('recorded npm app root is outside project');
|
|
537
|
+
if(recordedApp!==app)fail('selected app root differs from the recorded npm setup');
|
|
538
|
+
}
|
|
539
|
+
const targetLocal=localNames(distribution),priorLocal=previous?localNames(previous.distribution):null;
|
|
540
|
+
for(const section of ['dependencies','devDependencies','peerDependencies','optionalDependencies'])for(const [name,spec] of Object.entries(manifest[section]??{})){
|
|
541
|
+
for(const key of ['ui','tokens','agent'])for(const published of new Set([distribution[key],legacyPackages[key],`@vini/${key}`,nativeDsPackages[key]])){
|
|
542
|
+
const canonical=priorLocal?.[key]??targetLocal[key];
|
|
543
|
+
if(name===canonical){
|
|
544
|
+
if(!previous&&!adopting)fail(`existing ${canonical} dependency is not managed by this npm setup; migrate explicitly`);
|
|
545
|
+
if(section!==(key==='agent'?'devDependencies':'dependencies'))fail(`${canonical} appears in an unexpected dependency section; review the npm setup`);
|
|
546
|
+
}
|
|
547
|
+
if(name===targetLocal[key]&&targetLocal[key]!==canonical)fail(`existing ${name} dependency is not managed by this npm setup; migrate explicitly`);
|
|
548
|
+
if(name===published&&name!==canonical)fail(`direct ${published} dependency requires an explicit manual-to-CLI migration; this installer uses ${canonical} and will not add a second package identity`);
|
|
549
|
+
const value=typeof spec==='string'?spec.trim():'';
|
|
550
|
+
if(value===`npm:${published}`||value.startsWith(`npm:${published}@`)){
|
|
551
|
+
const recorded=previous&&name===canonical&§ion===(key==='agent'?'devDependencies':'dependencies')&&previous.distribution[key]===published&&spec===`npm:${published}@${previous.distribution.version}`;
|
|
552
|
+
if(!recorded)fail(`unmanaged alias ${name} for ${published} requires an explicit manual-to-CLI migration; use one package identity`);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
if(previous){
|
|
557
|
+
const sameNames=packageKeys.every(key=>previous.distribution[key]===distribution[key]);
|
|
558
|
+
const supportedFamilyChange=(packageKeys.every(key=>previous.distribution[key]===legacyPackages[key])&&(packageKeys.every(key=>distribution[key]===`@vini/${key}`)||isNativeDs(distribution)))||(packageKeys.every(key=>previous.distribution[key]===`@vini/${key}`)&&isNativeDs(distribution));
|
|
559
|
+
if(!sameNames&&supportedFamilyChange&&compareVersions(distribution.version,previous.distribution.version)<=0)fail('package family migration requires a newer release; no downgrade is selected');
|
|
560
|
+
if(familyTransition(previous.distribution,distribution)==='unsupported')fail('package family transition is not supported; review the installed distribution before migration');
|
|
561
|
+
if(compareVersions(distribution.version,previous.distribution.version)<0)fail('installed release is newer than the requested release; no downgrade is selected');
|
|
562
|
+
}
|
|
563
|
+
const alias=(key)=>packageSpec(distribution,key);
|
|
564
|
+
if(previous)for(const key of ['ui','tokens','agent']){const prior=packageSpec(previous.distribution,key);if(deps[priorLocal[key]]!==prior&&!(priorLocal[key]===targetLocal[key]&&deps[priorLocal[key]]===alias(key)))fail(`${priorLocal[key]} differs from the recorded npm setup`);}
|
|
261
565
|
const lockfile=path.join(app,manager==='npm'?'package-lock.json':'pnpm-lock.yaml');
|
|
262
566
|
const configFile=path.join(root,'.codex/config.toml'),agentsFile=path.join(root,'AGENTS.md'),skillFile=path.join(root,'.agents/skills/vini-ds/SKILL.md'),launchFile=path.join(kit,'npm-launcher.mjs'),setupFile=path.join(kit,'QUICKSTART.md');
|
|
263
567
|
const files=[manifestFile,lockfile,entry,configFile,agentsFile,skillFile,launchFile,setupFile,receiptPath];
|
|
@@ -268,48 +572,84 @@ export async function init(options={},suppliedDistribution,{runner=run,releaseMe
|
|
|
268
572
|
const config=Buffer.from(configMerge(before.get(configFile)?text(before.get(configFile),configFile):'',configTable,previous?.configTable));
|
|
269
573
|
const agents=Buffer.from(agentsMerge(before.get(agentsFile)?text(before.get(agentsFile),agentsFile):''));
|
|
270
574
|
const current=await readInstallation(root,path.relative(root,app)||'.',distribution);
|
|
271
|
-
|
|
272
|
-
const
|
|
575
|
+
if(adopting&&(!isDeepStrictEqual(initial.manual,current.manual)||!isDeepStrictEqual(initial.runtime,current.runtime)||!isDeepStrictEqual(initial.modules,current.modules)||packageKeys.some(key=>!isDeepStrictEqual(initial.installed[key].actual,current.installed[key].actual)||initial.installed[key].manifestSha256!==current.installed[key].manifestSha256)))fail('manual installation changed while planning; review it before adoption');
|
|
576
|
+
const installedAligned=!!previous&¤t.launcher.status==='matches-receipt'&&contextMatchesReceipt(current)&&['ui','tokens','agent'].every(key=>current.installed[key].matchesReceipt);
|
|
577
|
+
const migration=!!previous&&familyTransition(previous.distribution,distribution)==='manual-import-migration';
|
|
578
|
+
const plan={status:'plan-only',command:options.command??'init',projectRoot:root,appRoot:app,entry:path.relative(app,entry),entryPreparation:adopting?'preserve-existing-entry':entryPreparation,packageManager:manager,installed:current.installed,runtime:current.runtime,modules:current.modules,manual:current.manual,installedStatus:previous?(installedAligned?'matches-receipt':'mismatch'):current.manual.status,from:previous?.distribution??(adopting?distribution:null),to:distribution,distribution,changes:transition(release,installedAligned?previous.distribution.version:null,distribution.version),release:release??null,restart:clientCheck,dependencies:{[targetLocal.ui]:alias('ui'),[targetLocal.tokens]:alias('tokens')},devDependencies:{[targetLocal.agent]:alias('agent')},...(adopting?{manualAdoption:{explicit:!!options.adoptManual,preserveEntry:true,preserveVersion:true,blocked:current.modules.status==='linked',nextStep:current.modules.status==='linked'?'node_modules is a symbolic link to shared dependencies; first choose an independently managed app directory. This command will not change its target.':'Review this plan, CSS/provider diagnostics and backup, then run init --adopt-manual.'}}:{}),...(migration?{removeDependencies:Object.values(priorLocal),manualMigration:'Review and replace all old imports and configuration in the project before update; pass --imports-migrated only after review. The CLI checks the entry and build but cannot verify every source file.'}:{}),agent:'project-local Codex MCP + Skill',applicationPage:'not-verified',nativeClient:'not-verified',verification:verificationState(distribution,current),postUpdateSteps:[pageCheck,clientCheck],globalConfig:'unchanged',supported:`React/React DOM ${supportedReact19?'^18.2.0 or ^19.3.1':'^18.2.0'}, Vite direct createRoot(...).render(JSX), standalone npm/pnpm app`};
|
|
579
|
+
plan.diagnostics=diagnostics;plan.runtimeCompatibility=current.runtimeCompatibility;plan.runtimeIdentity=current.runtimeIdentity;
|
|
580
|
+
if(adopting){plan.manualAdoption.sourceEvidence=adoptionEvidence;if(adoptionEvidence.status!=='observed'){plan.manualAdoption.blocked=true;plan.manualAdoption.nextStep='Review missing CSS imports and provider use. Static scanning cannot prove the rendered application; no files will be changed.';}}
|
|
273
581
|
if(options.plan)return plan;
|
|
582
|
+
if(adopting&&adoptionEvidence.status!=='observed')fail('manual adoption requires the four VINi CSS imports and one observed ThemeBrandProvider use; review source and rerun the plan');
|
|
583
|
+
if(migration&&!options.importsMigrated)fail('review and migrate all project imports and configuration before update; then pass --imports-migrated');
|
|
584
|
+
if(previous&&!installedAligned)fail('installed packages, agent context or launcher differ from the receipt; resolve the mismatch before updating');
|
|
274
585
|
const recoveryRoot=path.join(root,'.vini-ds-recovery');await safeParents(root,path.join(recoveryRoot,'placeholder'));
|
|
275
586
|
const recoveryRootExisted=!!await exists(recoveryRoot);
|
|
276
587
|
const modules=path.join(app,'node_modules');
|
|
277
|
-
const moduleStat=await exists(modules);if(moduleStat&&(moduleStat.isSymbolicLink()||!moduleStat.isDirectory()))fail('node_modules must be a real directory');
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
const expected=new Map(before);let modulesMoved=false,projectMutationStarted=false,installFailed=false,buildAttempted=false,uncertain=false;
|
|
588
|
+
const moduleStat=await exists(modules);if(moduleStat&&(moduleStat.isSymbolicLink()||!moduleStat.isDirectory()))fail('node_modules must be a real directory; linked/shared dependencies require an independent app installation before applying');
|
|
589
|
+
let backup;await fs.mkdir(recoveryRoot,{recursive:true,mode:0o700});backup=await fs.mkdtemp(path.join(recoveryRoot,'npm-'));await recordRecovery(backup);
|
|
590
|
+
const expected=new Map(before);let modulesMoved=false,modulesMayHaveChanged=false,projectMutationStarted=false,installFailed=false,buildAttempted=false;
|
|
281
591
|
const write=async(file,bytes)=>{await safeParents(root,file);const current=await fileBytes(file,true),expectedBytes=expected.get(file);if(current===null?expectedBytes!==null:expectedBytes===null||!current.equals(expectedBytes))fail(`concurrent change: ${file}`);await fs.mkdir(path.dirname(file),{recursive:true});const temporary=path.join(path.dirname(file),`.vini-${randomUUID()}`);await fs.writeFile(temporary,bytes,{flag:'wx',mode:(await exists(file))?.mode&0o777||0o600});await fs.rename(temporary,file);expected.set(file,bytes);};
|
|
282
592
|
const pm=async(args)=>runner(manager==='npm'?'npm':'corepack',manager==='npm'?args:['pnpm',...args],{cwd:app});
|
|
283
593
|
const registry=options.registry?[`--registry=${options.registry}`]:[];
|
|
284
594
|
try {
|
|
285
|
-
const next=structuredClone(manifest);next.dependencies={...next.dependencies
|
|
595
|
+
const next=structuredClone(manifest);next.dependencies={...next.dependencies};next.devDependencies={...next.devDependencies};
|
|
596
|
+
if(migration)for(const key of packageKeys){delete next.dependencies[priorLocal[key]];delete next.devDependencies[priorLocal[key]];}
|
|
597
|
+
next.dependencies[targetLocal.tokens]=alias('tokens');next.dependencies[targetLocal.ui]=alias('ui');next.devDependencies[targetLocal.agent]=alias('agent');delete next.dependencies[targetLocal.agent];delete next.devDependencies[targetLocal.ui];delete next.devDependencies[targetLocal.tokens];
|
|
286
598
|
const manifestAfter=Buffer.from(JSON.stringify(next,null,2)+'\n');
|
|
287
599
|
const unchanged=previous&&JSON.stringify(previous.distribution)===JSON.stringify(distribution)&&before.get(manifestFile).equals(manifestAfter)&&entryBefore.equals(entryAfter)&&before.get(configFile)?.equals(config)&&before.get(agentsFile)?.equals(agents)&&before.get(skillFile)!==null&&before.get(setupFile)!==null;
|
|
288
600
|
let verified=false;
|
|
289
|
-
if(unchanged){try{const
|
|
290
|
-
if(verified){
|
|
601
|
+
if(unchanged){try{const keys=['tokens','ui','agent'],entries=await freshResolve(manifestFile,keys.map(key=>`${targetLocal[key]}${key==='agent'?'/mcp':''}`),app);for(const [index,key]of keys.entries()){const pkg=await manifestForEntry(entries[index],targetLocal[key],app);if(pkg.manifest.name!==distribution[key]||pkg.manifest.version!==distribution.version)throw new Error('mismatch');validateNativeManifest(pkg.manifest,key,distribution);if(key==='agent')await verifyAgentContext(runner,pkg.entry,distribution,app);}verified=true;}catch{}}
|
|
602
|
+
if(verified){
|
|
603
|
+
let supervisor;
|
|
604
|
+
try{const [agentEntry,supervisorEntry]=await freshResolve(manifestFile,[`${targetLocal.agent}/mcp`,`${targetLocal.agent}/supervisor`],app);const agent=await manifestForEntry(agentEntry,targetLocal.agent,app);supervisor=await projectModuleEntry(app,supervisorEntry);if(!supervisor.startsWith((await fs.realpath(agent.root))+path.sep))throw new Error('outside agent');}
|
|
605
|
+
catch{fail('installed agent supervisor is missing or invalid; inspect the installed agent and receipt before retrying; no reinstall was started');}
|
|
606
|
+
const launch=Buffer.from(launcher(distribution,path.relative(root,app)||'.'));
|
|
607
|
+
if(before.get(launchFile)?.equals(launch)&&isGeneration(previous.generation)){await fs.rmdir(backup);if(!recoveryRootExisted)await fs.rmdir(recoveryRoot).catch(error=>{if(error.code!=='ENOTEMPTY'&&error.code!=='ENOENT')throw error;});return {...plan,status:'already-installed',build:'not-rerun'};}
|
|
608
|
+
// The installed set is already correct, but its recorded launcher is an
|
|
609
|
+
// older format. Repair only the launcher and receipt under this lock;
|
|
610
|
+
// do not reinstall packages or touch build output.
|
|
611
|
+
for(const [file,bytes]of before)if(bytes!==null){const target=path.join(backup,'files',path.relative(root,file));await fs.mkdir(path.dirname(target),{recursive:true});await fs.writeFile(target,bytes);}
|
|
612
|
+
projectMutationStarted=true;await write(launchFile,launch);
|
|
613
|
+
const receipt={...previous,generation:randomUUID(),launcherSha256:digest(launch)};
|
|
614
|
+
await write(receiptPath,Buffer.from(JSON.stringify(receipt,null,2)+'\n'));
|
|
615
|
+
const finalState=await readInstallation(root,path.relative(root,app)||'.',distribution),verification=verificationState(distribution,finalState);
|
|
616
|
+
if(!verification.installation.matchesTarget)fail('installed packages or launcher do not match the repaired receipt');
|
|
617
|
+
return {...plan,status:'connection-repaired',installed:finalState.installed,installedStatus:'matches-receipt',verification,build:'not-rerun',recovery:backup};
|
|
618
|
+
}
|
|
291
619
|
for(const [file,bytes]of before)if(bytes!==null){const target=path.join(backup,'files',path.relative(root,file));await fs.mkdir(path.dirname(target),{recursive:true});await fs.writeFile(target,bytes);}
|
|
292
620
|
if(moduleStat){await fs.rename(modules,path.join(backup,'node_modules'));modulesMoved=true;}
|
|
293
621
|
projectMutationStarted=true;
|
|
294
622
|
await write(manifestFile,manifestAfter);
|
|
295
|
-
try {await pm(manager==='npm'?['install','--ignore-scripts','--strict-peer-deps','--no-audit','--no-fund',...registry]:['install','--ignore-scripts','--config.strict-peer-dependencies=true','--no-frozen-lockfile',...registry]);}
|
|
623
|
+
try {modulesMayHaveChanged=true;await pm(manager==='npm'?['install','--ignore-scripts','--strict-peer-deps','--no-audit','--no-fund',...registry]:['install','--ignore-scripts','--config.strict-peer-dependencies=true','--no-frozen-lockfile',...registry]);}
|
|
296
624
|
catch(error){installFailed=true;throw error;}
|
|
297
625
|
expected.set(manifestFile,await fileBytes(manifestFile));expected.set(lockfile,await fileBytes(lockfile));
|
|
298
|
-
const
|
|
299
|
-
|
|
626
|
+
const packageRoots={};
|
|
627
|
+
const [tokensEntry,uiEntry,agentEntry,supervisorEntry,skillEntry,setupEntry,reactEntry,reactDomEntry]=await freshResolve(manifestFile,[targetLocal.tokens,targetLocal.ui,`${targetLocal.agent}/mcp`,`${targetLocal.agent}/supervisor`,`${targetLocal.agent}/skill`,`${targetLocal.agent}/setup`,'react','react-dom'],app);
|
|
628
|
+
for(const [key,entry]of [['tokens',tokensEntry],['ui',uiEntry],['agent',agentEntry]]){const pkg=await manifestForEntry(entry,targetLocal[key],app);if(pkg.manifest.name!==distribution[key]||pkg.manifest.version!==distribution.version)fail(`${key} npm version mismatch`);validateNativeManifest(pkg.manifest,key,distribution);packageRoots[key]=pkg;}
|
|
300
629
|
await verifyAgentContext(runner,packageRoots.agent.entry,distribution,app);
|
|
301
|
-
const
|
|
302
|
-
|
|
630
|
+
const supervisor=await projectModuleEntry(app,supervisorEntry),agentRoot=await fs.realpath(packageRoots.agent.root);
|
|
631
|
+
if(!supervisor.startsWith(agentRoot+path.sep))fail('agent supervisor must belong to the installed agent package');
|
|
632
|
+
const uiPeers=await freshResolve(path.join(packageRoots.ui.root,'package.json'),['react','react-dom'],app);
|
|
633
|
+
for(const [i,name]of ['react','react-dom'].entries())if(await projectModuleEntry(app,[reactEntry,reactDomEntry][i])!==await projectModuleEntry(app,uiPeers[i]))fail(`multiple ${name} instances after install`);
|
|
634
|
+
if(adopting||resumingAdoption){
|
|
635
|
+
const actualReact=await manifestForEntry(reactEntry,'react',app),actualDom=await manifestForEntry(reactDomEntry,'react-dom',app);
|
|
636
|
+
for(const [name,pkg] of [['react',actualReact],['react-dom',actualDom]])if(pkg.manifest.name!==name||pkg.manifest.version!==initial.runtime[name].actual.version||!peerAccepts(packageRoots.ui.manifest.peerDependencies?.[name],pkg.manifest.version))fail(`installed ${name} changed or is incompatible after manual adoption`);
|
|
637
|
+
if(!peerAccepts(actualDom.manifest.peerDependencies?.react,actualReact.manifest.version))fail('installed react-dom peer is incompatible after manual adoption');
|
|
638
|
+
}
|
|
639
|
+
const skill=await fileBytes(await projectModuleEntry(app,skillEntry)),setup=await fileBytes(await projectModuleEntry(app,setupEntry));
|
|
303
640
|
const launch=Buffer.from(launcher(distribution,path.relative(root,app)||'.'));
|
|
304
|
-
await write(entry,entryAfter);
|
|
641
|
+
if(!entryBefore.equals(entryAfter))await write(entry,entryAfter);
|
|
305
642
|
if(manifest.scripts?.build){buildAttempted=true;await pm(['run','build']);}
|
|
306
643
|
for(const file of [manifestFile,lockfile,entry]){const bytes=await fileBytes(file);if(!bytes.equals(expected.get(file)))fail(`project files changed during build: ${file}`);}
|
|
307
644
|
for(const [file,bytes]of [[launchFile,launch],[setupFile,setup],[configFile,config],[skillFile,skill],[agentsFile,agents]])await write(file,bytes);
|
|
308
|
-
const receipt={installer:'vini-npm',distribution,appRoot:path.relative(root,app)||'.',entry:path.relative(app,entry),configTable,skillSha256:digest(skill),launcherSha256:digest(launch)};
|
|
645
|
+
const receipt={installer:'vini-npm',generation:randomUUID(),distribution,appRoot:path.relative(root,app)||'.',entry:path.relative(app,entry),...(adopting||resumingAdoption||previous?.entryMode==='preserved-manual'?{entryMode:'preserved-manual'}:{}),configTable,skillSha256:digest(skill),launcherSha256:digest(launch)};
|
|
309
646
|
await write(receiptPath,Buffer.from(JSON.stringify(receipt,null,2)+'\n'));
|
|
310
|
-
|
|
647
|
+
const finalState=await readInstallation(root,path.relative(root,app)||'.',distribution);
|
|
648
|
+
const verification=verificationState(distribution,finalState);
|
|
649
|
+
if(!verification.installation.matchesTarget)fail('installed packages or launcher do not match the newly written receipt');
|
|
650
|
+
return {...plan,status:'installed',installed:finalState.installed,installedStatus:'matches-receipt',verification,build:buildAttempted?'passed':'not-configured',recovery:backup};
|
|
311
651
|
} catch(error) {
|
|
312
|
-
if(error.uncertainChildren){
|
|
652
|
+
if(error.uncertainChildren){const retained=new Error(`${error.message}; retained lock and recovery: ${backup}`);retained.retainInstallLock=true;throw retained;}
|
|
313
653
|
if(!projectMutationStarted&&!modulesMoved)throw new Error(`${error.message}; no project files or dependencies changed; recovery retained: ${backup}`);
|
|
314
654
|
const issues=[];
|
|
315
655
|
let mayRecover=!installFailed;
|
|
@@ -331,10 +671,12 @@ export async function init(options={},suppliedDistribution,{runner=run,releaseMe
|
|
|
331
671
|
}catch(recoveryError){issues.push(`package-manager recovery requires review: ${recoveryError.message}`);}
|
|
332
672
|
if(mayRecover) {
|
|
333
673
|
for(const [file,bytes]of before){try{const current=await fileBytes(file,true),exp=expected.get(file);if(current===null?exp!==null:exp===null||!current.equals(exp))throw new Error('changed after last completed step');if(bytes===null){if(current)await fs.unlink(file);}else await write(file,bytes);}catch(e){issues.push(`${path.relative(root,file)}: ${e.message}`);}}
|
|
334
|
-
try{const failed=await exists(modules);if(failed){if(failed.isSymbolicLink()||!failed.isDirectory())throw new Error('node_modules changed type');await fs.rename(modules,path.join(backup,'node_modules-failed'));}if(modulesMoved)await fs.rename(path.join(backup,'node_modules'),modules);}catch(e){issues.push(`node_modules: ${e.message}`);}
|
|
674
|
+
if(modulesMoved||modulesMayHaveChanged)try{const failed=await exists(modules);if(failed){if(failed.isSymbolicLink()||!failed.isDirectory())throw new Error('node_modules changed type');await fs.rename(modules,path.join(backup,'node_modules-failed'));}if(modulesMoved)await fs.rename(path.join(backup,'node_modules'),modules);}catch(e){issues.push(`node_modules: ${e.message}`);}
|
|
335
675
|
if(!kitStat)await fs.rmdir(kit).catch(()=>{});
|
|
336
676
|
}
|
|
337
|
-
|
|
338
|
-
|
|
677
|
+
const failure=new Error(`${error.message}; ${issues.length?'recovery incomplete: '+issues.join('; '):'original files and dependencies restored'}; saved originals: ${backup}${migration?'; manually migrated source imports were present before update and are not reverted; they may require the new packages, so review and restore the previous source or retry the migration before running the project':''}${buildAttempted?'; build outputs are not automatically restored':''}${issues.length?'; retained lock requires recovery review':''}`);
|
|
678
|
+
if(issues.length)failure.retainInstallLock=true;
|
|
679
|
+
throw failure;
|
|
680
|
+
}
|
|
339
681
|
}
|
|
340
682
|
if(process.argv[1]&&await fs.realpath(process.argv[1]).catch(()=>null)===self){try{const options=parseArgs(process.argv.slice(2));if(options.help)console.log(usage);else if(options.command==='status'){const result=await status(options);console.log(options.json?JSON.stringify(result,null,2):formatStatus(result));}else console.log(JSON.stringify(await init(options),null,2));}catch(error){console.error(error.message);process.exitCode=1;}}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vini-ds",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.13",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "VINi React project and local agent setup",
|
|
6
6
|
"bin": {
|
|
@@ -14,38 +14,45 @@
|
|
|
14
14
|
},
|
|
15
15
|
"files": [
|
|
16
16
|
"cli.mjs",
|
|
17
|
+
"version.mjs",
|
|
18
|
+
"project-diagnostics.mjs",
|
|
17
19
|
"README.md"
|
|
18
20
|
],
|
|
19
21
|
"dependencies": {
|
|
20
22
|
"typescript": "5.5.4"
|
|
21
23
|
},
|
|
22
24
|
"viniDistribution": {
|
|
23
|
-
"version": "0.1.0-alpha.
|
|
24
|
-
"ui": "@
|
|
25
|
-
"tokens": "@
|
|
26
|
-
"agent": "@
|
|
25
|
+
"version": "0.1.0-alpha.13",
|
|
26
|
+
"ui": "@vini-ds/ui",
|
|
27
|
+
"tokens": "@vini-ds/tokens",
|
|
28
|
+
"agent": "@vini-ds/agent"
|
|
27
29
|
},
|
|
28
30
|
"viniRelease": {
|
|
29
31
|
"atlas": {
|
|
30
|
-
"url": "https://vini-atlas
|
|
31
|
-
"archiveSha256": "sha256:
|
|
32
|
-
"siteRelease": "
|
|
33
|
-
"commit": "
|
|
32
|
+
"url": "https://vini-atlas.twc1.net/",
|
|
33
|
+
"archiveSha256": "sha256:035848c083a2bc32850377df27f3d5e2d2a3cc3b1ee1c2edb75a789526bb8297",
|
|
34
|
+
"siteRelease": "source-snapshot-20261115-card-align-e43b0d3",
|
|
35
|
+
"commit": "e43b0d3237825bcb09ebc0760a0a9544891b3353"
|
|
34
36
|
},
|
|
35
37
|
"delivery": {
|
|
36
|
-
"id": "candidate-
|
|
37
|
-
"manifestSha256": "sha256:
|
|
38
|
-
"packageManifestSha256": "sha256:
|
|
38
|
+
"id": "candidate-aeb9566ccd8ab46b",
|
|
39
|
+
"manifestSha256": "sha256:7a506ceb8d42a7e04f4d0e4fb7dfaec442b29b0f221a0483625bd8af899d4dea",
|
|
40
|
+
"packageManifestSha256": "sha256:f2431364911438a5ac24f4f76cf73bc4246535ced70fb530754af64e1d69125e"
|
|
39
41
|
},
|
|
40
42
|
"changes": {
|
|
41
|
-
"fromVersion": "0.1.0-alpha.
|
|
42
|
-
"summary": "
|
|
43
|
+
"fromVersion": "0.1.0-alpha.11",
|
|
44
|
+
"summary": "Поддержка React 18 и 19; Blue и генератор бренда; NativeSelect, Slider, исправление прокрутки Select; агент сообщает об обновлениях при начале работы. Atlas показывает примеры в натуральном размере без скачка при загрузке. В Card заголовок и действие выравниваются по вертикали, когда они единственные прямые элементы заголовка; при дополнительном содержимом действие остаётся сверху. В примерах Collapsible используется компактная кнопка.",
|
|
43
45
|
"components": [
|
|
44
|
-
"
|
|
45
|
-
"
|
|
46
|
-
"
|
|
47
|
-
"
|
|
46
|
+
"NativeSelect",
|
|
47
|
+
"Slider",
|
|
48
|
+
"Select",
|
|
49
|
+
"Card",
|
|
50
|
+
"Collapsible"
|
|
48
51
|
]
|
|
49
52
|
}
|
|
53
|
+
},
|
|
54
|
+
"repository": {
|
|
55
|
+
"type": "git",
|
|
56
|
+
"url": "https://github.com/youtimelex/vini.git"
|
|
50
57
|
}
|
|
51
58
|
}
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import { promises as fs } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import ts from 'typescript';
|
|
5
|
+
|
|
6
|
+
// Static, read-only evidence for a specific app entry; it cannot establish what
|
|
7
|
+
// an already running page loaded or whether the rendered root uses a provider.
|
|
8
|
+
const supported = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.css']);
|
|
9
|
+
const moduleExt = ['', '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.css', '/index.ts', '/index.tsx', '/index.js', '/index.jsx'];
|
|
10
|
+
const important = /^(?:all|align(?:-.+)?|appearance|background(?:-.+)?|border(?:-.+)?|box-sizing|color|display|filter|flex(?:-.+)?|font(?:-.+)?|gap|height|inset(?:-.+)?|justify(?:-.+)?|letter-spacing|line-height|margin(?:-.+)?|max-(?:width|height)|min-(?:width|height)|opacity|outline(?:-.+)?|overflow(?:-.+)?|padding(?:-.+)?|position|text(?:-.+)?|transform|visibility|white-space|width|z-index|--vini-.+)$/i;
|
|
11
|
+
const rootSelector = /^(?:\*|html|body|:root)(?=$|[\s.#[:>+~])/i;
|
|
12
|
+
const broadElement = /^(?:button|input|select|textarea|label|a|p|h[1-6]|svg|img|table|th|td)(?=$|[\s[:>+~])/i;
|
|
13
|
+
const within = (parent, child) => child === parent || child.startsWith(parent + path.sep);
|
|
14
|
+
const lineAt = (s, offset) => 1 + (s.slice(0, offset).match(/\n/g) ?? []).length;
|
|
15
|
+
|
|
16
|
+
function cleanComments(s) {
|
|
17
|
+
return s.replace(/\/\*[\s\S]*?\*\//g, value => value.replace(/[^\n]/g, ' '));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Traverse balanced CSS blocks and retain @media conditions. This is a
|
|
21
|
+
// deliberately conservative triage, not a full cascade or CSS parser.
|
|
22
|
+
function cssWarnings(source, file) {
|
|
23
|
+
const text = cleanComments(source), warnings = [];
|
|
24
|
+
const scan = (begin, end, media) => {
|
|
25
|
+
let start = begin, quote = '', escaped = false, parens = 0;
|
|
26
|
+
for (let i = begin; i < end; i++) {
|
|
27
|
+
const c = text[i];
|
|
28
|
+
if (quote) { if (escaped) escaped = false; else if (c === '\\') escaped = true; else if (c === quote) quote = ''; continue; }
|
|
29
|
+
if (c === '"' || c === "'") { quote = c; continue; }
|
|
30
|
+
if (c === '(') { parens++; continue; }
|
|
31
|
+
if (c === ')') { parens = Math.max(0, parens - 1); continue; }
|
|
32
|
+
if (c === ';' && parens === 0) { start = i + 1; continue; }
|
|
33
|
+
if (c !== '{' || parens) continue;
|
|
34
|
+
const raw = text.slice(start, i), selector = raw.trim();
|
|
35
|
+
let depth = 1, j = i + 1, blockQuote = '', blockEscape = false;
|
|
36
|
+
for (; j < end && depth; j++) {
|
|
37
|
+
const x = text[j];
|
|
38
|
+
if (blockQuote) { if (blockEscape) blockEscape = false; else if (x === '\\') blockEscape = true; else if (x === blockQuote) blockQuote = ''; continue; }
|
|
39
|
+
if (x === '"' || x === "'") blockQuote = x;
|
|
40
|
+
else if (x === '{') depth++;
|
|
41
|
+
else if (x === '}') depth--;
|
|
42
|
+
}
|
|
43
|
+
if (depth) break;
|
|
44
|
+
const close = j - 1;
|
|
45
|
+
if (/^@media\b/i.test(selector)) scan(i + 1, close, [...media, selector]);
|
|
46
|
+
else if (/^@(?:supports|layer|container|scope)\b/i.test(selector)) scan(i + 1, close, media);
|
|
47
|
+
else if (selector && !selector.startsWith('@')) {
|
|
48
|
+
const cssModule = file.endsWith('.module.css');
|
|
49
|
+
const suspect = selector.split(',').map(v => v.trim()).map(v => {
|
|
50
|
+
if (cssModule && !v.includes(':global(')) return null;
|
|
51
|
+
const positiveSlots = v.replace(/:not\(\s*\[data-slot[^\]]*\]\s*\)/gi, '');
|
|
52
|
+
const kinds = [];
|
|
53
|
+
if (rootSelector.test(v) || broadElement.test(v) || /^\*?:focus-visible(?:\b|$)/i.test(v) || v.startsWith(':global(')) kinds.push('broad-selector');
|
|
54
|
+
if (/\[data-slot(?:\s*[~|^$*]?=|\s*\])/i.test(positiveSlots)) kinds.push('component-slot-selector');
|
|
55
|
+
if (media.length && /(?:^|[\s>+~])\.sidebar(?=$|[\s.#[:>+~])/i.test(v)) kinds.push('sidebar-media-selector');
|
|
56
|
+
return kinds.length ? { selector: v, kinds } : null;
|
|
57
|
+
}).filter(Boolean);
|
|
58
|
+
if (suspect.length) {
|
|
59
|
+
const body = text.slice(i + 1, close);
|
|
60
|
+
// Nested declarations are not assumed to apply to the outer rule.
|
|
61
|
+
if (!body.includes('{')) {
|
|
62
|
+
const properties = [...body.matchAll(/(?:^|;)\s*([\w-]+)\s*:/g)].map(m => m[1]).filter(p => important.test(p));
|
|
63
|
+
if (properties.length) warnings.push({ file, line: lineAt(text, start + raw.search(/\S/)), selector: suspect.map(x => x.selector).join(', '), kinds: [...new Set(suspect.flatMap(x => x.kinds))], properties: [...new Set(properties)], media, interpretation: 'Potentially affects VINi elements; inspect the cascade and actual page before deciding.' });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
i = close; start = j;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
scan(0, text.length, []);
|
|
71
|
+
return warnings;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function existingFile(file) {
|
|
75
|
+
try { return (await fs.stat(file)).isFile(); } catch { return false; }
|
|
76
|
+
}
|
|
77
|
+
async function resolveLocal(parent, specifier, appReal) {
|
|
78
|
+
const base = path.resolve(path.dirname(parent), specifier.split(/[?#]/, 1)[0]);
|
|
79
|
+
for (const suffix of moduleExt) {
|
|
80
|
+
const candidate = base + suffix;
|
|
81
|
+
if (!supported.has(path.extname(candidate)) || !(await existingFile(candidate))) continue;
|
|
82
|
+
const real = await fs.realpath(candidate);
|
|
83
|
+
if (!within(appReal, real)) return { blocked: true, path: candidate };
|
|
84
|
+
return { path: real };
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function importsAndProvider(content, file) {
|
|
90
|
+
const script = ts.createSourceFile(file, content, ts.ScriptTarget.Latest, true,
|
|
91
|
+
file.endsWith('.tsx') ? ts.ScriptKind.TSX : file.endsWith('.jsx') ? ts.ScriptKind.JSX : ts.ScriptKind.TS);
|
|
92
|
+
const imports = [], providerBindings = new Set(), uses = [];
|
|
93
|
+
for (const item of script.statements) {
|
|
94
|
+
if ((ts.isImportDeclaration(item) || ts.isExportDeclaration(item)) && item.moduleSpecifier && ts.isStringLiteral(item.moduleSpecifier)) {
|
|
95
|
+
const spec = item.moduleSpecifier.text;
|
|
96
|
+
const clause = ts.isImportDeclaration(item) ? item.importClause : undefined;
|
|
97
|
+
const typeOnly = Boolean(clause?.isTypeOnly);
|
|
98
|
+
imports.push({ specifier: spec, line: lineAt(content, item.getStart(script)), kind: typeOnly ? 'type-only' : 'static' });
|
|
99
|
+
if (!typeOnly && /^@(?:vini-ds|vini)\/ui$/.test(spec)) {
|
|
100
|
+
const bindings = clause?.namedBindings;
|
|
101
|
+
if (bindings && ts.isNamedImports(bindings)) for (const element of bindings.elements) {
|
|
102
|
+
if (!element.isTypeOnly && (element.propertyName ?? element.name).text === 'ThemeBrandProvider') providerBindings.add(element.name.text);
|
|
103
|
+
}
|
|
104
|
+
if (bindings && ts.isNamespaceImport(bindings)) providerBindings.add(`${bindings.name.text}.ThemeBrandProvider`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const visit = node => {
|
|
109
|
+
if (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) {
|
|
110
|
+
const name = node.tagName.getText(script);
|
|
111
|
+
if (providerBindings.has(name)) uses.push({ file, line: lineAt(content, node.getStart(script)), binding: name });
|
|
112
|
+
}
|
|
113
|
+
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
|
|
114
|
+
const argument = node.arguments[0];
|
|
115
|
+
const literal = argument && (ts.isStringLiteral(argument) || ts.isNoSubstitutionTemplateLiteral(argument));
|
|
116
|
+
imports.push({ specifier: literal ? argument.text : null, line: lineAt(content, node.getStart(script)), kind: 'dynamic', literal: Boolean(literal) });
|
|
117
|
+
}
|
|
118
|
+
ts.forEachChild(node, visit);
|
|
119
|
+
};
|
|
120
|
+
visit(script);
|
|
121
|
+
return { imports, uses, providerImports: [...providerBindings].map(binding => ({ file, binding })) };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function packageCssResolution(require, specifier) {
|
|
125
|
+
try { return { status: 'resolved', path: require.resolve(specifier) }; }
|
|
126
|
+
catch (error) { return { status: 'unresolved', reason: error.code ?? 'resolution-failed' }; }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function inspectFontImport(require, specifier, location) {
|
|
130
|
+
try {
|
|
131
|
+
const css = require.resolve(specifier), text = await fs.readFile(css, 'utf8');
|
|
132
|
+
const packageName = specifier.split('/').slice(0, 2).join('/');
|
|
133
|
+
let packageRoot = path.dirname(css);
|
|
134
|
+
while (true) {
|
|
135
|
+
try { if (JSON.parse(await fs.readFile(path.join(packageRoot, 'package.json'), 'utf8')).name === packageName) break; } catch {}
|
|
136
|
+
const parent = path.dirname(packageRoot);
|
|
137
|
+
if (parent === packageRoot) throw new Error('font stylesheet package root not found');
|
|
138
|
+
packageRoot = parent;
|
|
139
|
+
}
|
|
140
|
+
const realPackageRoot = await fs.realpath(packageRoot);
|
|
141
|
+
const files = [...text.matchAll(/url\(\s*(['"]?)([^)'"\s]+)\1\s*\)/gi)]
|
|
142
|
+
.map(match => match[2]).filter(url => !/^(?:data:|https?:|\/\/|#)/i.test(url));
|
|
143
|
+
const checked = [];
|
|
144
|
+
for (const url of [...new Set(files)].slice(0, 256)) {
|
|
145
|
+
let target;
|
|
146
|
+
try { target = path.resolve(path.dirname(css), decodeURIComponent(url.split(/[?#]/, 1)[0])); } catch { checked.push({ url, status: 'invalid-asset-url' }); continue; }
|
|
147
|
+
if (!within(packageRoot, target)) { checked.push({ url, status: 'outside-package-not-inspected' }); continue; }
|
|
148
|
+
const real = await fs.realpath(target).catch(() => null);
|
|
149
|
+
if (real && !within(realPackageRoot, real)) { checked.push({ url, status: 'outside-package-not-inspected' }); continue; }
|
|
150
|
+
checked.push({ url, status: real && await existingFile(real) ? 'present' : 'missing' });
|
|
151
|
+
}
|
|
152
|
+
return { ...location, specifier, resolvedStylesheet: css, referencedLocalAssets: checked.length,
|
|
153
|
+
missingLocalAssets: checked.filter(item => item.status === 'missing').map(item => item.url),
|
|
154
|
+
uninspectedAssets: checked.filter(item => !['missing', 'present'].includes(item.status)), truncated: files.length > 256 };
|
|
155
|
+
} catch (error) { return { ...location, specifier, status: 'unresolved', reason: error.code ?? 'read-failed' }; }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async function inspectLocalFontRules(content, file, appReal) {
|
|
159
|
+
const source = cleanComments(content), records = [];
|
|
160
|
+
for (const match of source.matchAll(/@font-face\s*\{([^{}]*)\}/gi)) {
|
|
161
|
+
const body = match[1], family = /(?:^|;)\s*font-family\s*:\s*([^;]+)/i.exec(body)?.[1].trim() ?? null;
|
|
162
|
+
const assets = [];
|
|
163
|
+
for (const item of body.matchAll(/url\(\s*(['"]?)([^)'"\s]+)\1\s*\)/gi)) {
|
|
164
|
+
const url = item[2];
|
|
165
|
+
if (/^(?:data:|https?:|\/\/|#)/i.test(url)) { assets.push({ url, status: 'external-or-embedded-not-checked' }); continue; }
|
|
166
|
+
let target;
|
|
167
|
+
try {
|
|
168
|
+
const decoded = decodeURIComponent(url.split(/[?#]/, 1)[0]);
|
|
169
|
+
target = decoded.startsWith('/') ? path.join(appReal, 'public', decoded.slice(1)) : path.resolve(path.dirname(file), decoded);
|
|
170
|
+
} catch { assets.push({ url, status: 'invalid-asset-url' }); continue; }
|
|
171
|
+
if (!within(appReal, target)) { assets.push({ url, status: 'outside-app-not-inspected' }); continue; }
|
|
172
|
+
const real = await fs.realpath(target).catch(() => null);
|
|
173
|
+
if (real && !within(appReal, real)) { assets.push({ url, status: 'outside-app-not-inspected' }); continue; }
|
|
174
|
+
assets.push({ url, status: real && await existingFile(real) ? 'present' : 'missing' });
|
|
175
|
+
}
|
|
176
|
+
records.push({ file, line: lineAt(source, match.index), family, assets });
|
|
177
|
+
}
|
|
178
|
+
return records;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export async function diagnoseProject({ projectRoot, appRoot, entry }) {
|
|
182
|
+
if (!path.isAbsolute(projectRoot ?? '') || !path.isAbsolute(appRoot ?? '') || !path.isAbsolute(entry ?? ''))
|
|
183
|
+
throw new Error('projectRoot, appRoot and entry must be absolute paths');
|
|
184
|
+
const rootReal = await fs.realpath(projectRoot), appReal = await fs.realpath(appRoot), entryReal = await fs.realpath(entry);
|
|
185
|
+
if (!within(rootReal, appReal) || !within(appReal, entryReal)) throw new Error('entry must be inside the selected app and project');
|
|
186
|
+
const require = createRequire(path.join(appReal, 'package.json'));
|
|
187
|
+
// Drain the static graph first, so a file reachable via both paths keeps its
|
|
188
|
+
// stronger static classification; dynamic imports never become proof of use.
|
|
189
|
+
const staticQueue = [entryReal], dynamicQueue = [], visited = new Set(), imports = [], dynamicImports = [], providerImports = [], providerUses = [], warnings = [], unresolved = [], fonts = [], localFonts = [];
|
|
190
|
+
const schedule = (file, reachability) => (reachability === 'static' ? staticQueue : dynamicQueue).push(file);
|
|
191
|
+
const maxFiles = 1500, maxBytes = 2 * 1024 * 1024;
|
|
192
|
+
while ((staticQueue.length || dynamicQueue.length) && visited.size < maxFiles) {
|
|
193
|
+
const reachability = staticQueue.length ? 'static' : 'dynamic';
|
|
194
|
+
const file = (reachability === 'static' ? staticQueue : dynamicQueue).shift();
|
|
195
|
+
if (visited.has(file)) continue;
|
|
196
|
+
visited.add(file);
|
|
197
|
+
const stat = await fs.stat(file);
|
|
198
|
+
if (stat.size > maxBytes) { unresolved.push({ file, reachability, reason: 'file exceeds scan limit' }); continue; }
|
|
199
|
+
const content = await fs.readFile(file, 'utf8');
|
|
200
|
+
if (file.endsWith('.css')) {
|
|
201
|
+
warnings.push(...cssWarnings(content, file).map(x => ({ ...x, reachability })));
|
|
202
|
+
localFonts.push(...(await inspectLocalFontRules(content, file, appReal)).map(x => ({ ...x, reachability })));
|
|
203
|
+
for (const item of cleanComments(content).matchAll(/@import\s+(?:url\(\s*)?['"]([^'"]+)['"]/gi)) {
|
|
204
|
+
const specifier = item[1], line = lineAt(content, item.index);
|
|
205
|
+
const observed = { file, line, specifier, kind: 'css-import', reachability };
|
|
206
|
+
if (/^@vini(?:-ds)?\/(?:tokens|ui)\/.+\.css$/i.test(specifier)) observed.resolution = packageCssResolution(require, specifier);
|
|
207
|
+
imports.push(observed);
|
|
208
|
+
if (specifier.startsWith('.')) { const next = await resolveLocal(file, specifier, appReal); if (next?.path && !next.blocked) schedule(next.path, reachability); else unresolved.push({ file, line, specifier, reachability, reason: next?.blocked ? 'outside selected app' : 'not found' }); }
|
|
209
|
+
if (/^(?:@vini(?:-ds)?\/tokens\/fonts\.css|@fontsource\/[a-z0-9-]+\/[^/]+\.css)$/i.test(specifier)) fonts.push(await inspectFontImport(require, specifier, { file, line, reachability }));
|
|
210
|
+
}
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
const parsed = importsAndProvider(content, file);
|
|
214
|
+
providerImports.push(...parsed.providerImports.map(x => ({ ...x, reachability }))); providerUses.push(...parsed.uses.map(x => ({ ...x, reachability })));
|
|
215
|
+
for (const item of parsed.imports) {
|
|
216
|
+
const itemReachability = reachability === 'dynamic' || item.kind === 'dynamic' ? 'dynamic' : 'static';
|
|
217
|
+
const location = { file, line: item.line, reachability: itemReachability };
|
|
218
|
+
if (item.kind === 'dynamic') {
|
|
219
|
+
dynamicImports.push({ ...location, specifier: item.specifier, literal: item.literal });
|
|
220
|
+
if (!item.literal) { unresolved.push({ ...location, specifier: null, reason: 'computed dynamic import not evaluated' }); continue; }
|
|
221
|
+
}
|
|
222
|
+
const observed = { ...location, specifier: item.specifier, kind: item.kind };
|
|
223
|
+
if (/^@vini(?:-ds)?\/(?:tokens|ui)\/.+\.css$/i.test(item.specifier)) observed.resolution = packageCssResolution(require, item.specifier);
|
|
224
|
+
imports.push(observed);
|
|
225
|
+
if (item.kind === 'type-only') continue;
|
|
226
|
+
if (item.specifier.startsWith('.')) {
|
|
227
|
+
const ext = path.extname(item.specifier.split(/[?#]/, 1)[0]);
|
|
228
|
+
if (ext && !supported.has(ext)) { unresolved.push({ ...location, specifier: item.specifier, reason: 'non-source import not inspected' }); continue; }
|
|
229
|
+
const next = await resolveLocal(file, item.specifier, appReal);
|
|
230
|
+
if (next?.path && !next.blocked) schedule(next.path, itemReachability); else unresolved.push({ ...location, specifier: item.specifier, reason: next?.blocked ? 'outside selected app' : 'not found' });
|
|
231
|
+
} else if (item.specifier.startsWith('@/') || item.specifier.startsWith('~/') || item.specifier.startsWith('/')) {
|
|
232
|
+
unresolved.push({ ...location, specifier: item.specifier, reason: 'project alias or absolute import not resolved by static scan' });
|
|
233
|
+
} else if (item.kind === 'dynamic') {
|
|
234
|
+
unresolved.push({ ...location, specifier: item.specifier, reason: 'external dynamic module not inspected' });
|
|
235
|
+
}
|
|
236
|
+
if (/^(?:@vini(?:-ds)?\/tokens\/fonts\.css|@fontsource\/[a-z0-9-]+\/[^/]+\.css)$/i.test(item.specifier))
|
|
237
|
+
fonts.push(await inspectFontImport(require, item.specifier, location));
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
const cssImports = imports.filter(item => /\.css(?:[?#].*)?$/.test(item.specifier));
|
|
241
|
+
return {
|
|
242
|
+
scope: { projectRoot: rootReal, appRoot: appReal, entry: entryReal, scannedFiles: visited.size, truncated: staticQueue.length + dynamicQueue.length > 0 },
|
|
243
|
+
dynamicImports,
|
|
244
|
+
coverage: 'Static and literal dynamic imports reachable from the selected entry are labelled separately; external modules, alias paths, runtime imports, HTML links, CSS-in-JS and browser-loaded assets are not fully evaluated.',
|
|
245
|
+
css: { imports: cssImports, potentiallyBroadRules: warnings },
|
|
246
|
+
provider: { imports: providerImports, jsxUses: providerUses, note: 'JSX observations do not cover every possible provider pattern and do not prove which provider wraps a rendered root.' },
|
|
247
|
+
fonts: { imports: fonts, localRules: localFonts, note: 'Existing asset files do not prove that a browser requested or rendered the fonts.' },
|
|
248
|
+
unresolved
|
|
249
|
+
};
|
|
250
|
+
}
|
package/version.mjs
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Exact versions supported by the public VINi release builders: lowercase
|
|
2
|
+
// prerelease identifiers, no build metadata, with bounded input size.
|
|
3
|
+
const maxVersionLength = 100;
|
|
4
|
+
const pattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([a-z0-9]+(?:\.[a-z0-9]+)*))?$/u;
|
|
5
|
+
|
|
6
|
+
function parse(version) {
|
|
7
|
+
if (typeof version !== 'string' || version.length > maxVersionLength) throw new Error('invalid exact version');
|
|
8
|
+
const match = pattern.exec(version);
|
|
9
|
+
if (!match || match[0] !== version) throw new Error('invalid exact version');
|
|
10
|
+
const prerelease = match[4]?.split('.') ?? null;
|
|
11
|
+
if (prerelease?.some(part => /^\d+$/u.test(part) && part.length > 1 && part.startsWith('0'))) throw new Error('invalid exact version');
|
|
12
|
+
return { core: match.slice(1, 4).map(BigInt), prerelease };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function isExactVersion(version) {
|
|
16
|
+
try { parse(version); return true; } catch { return false; }
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Numeric fields use arbitrary precision, not JS Number. Results are -1/0/1.
|
|
20
|
+
export function compareVersions(left, right) {
|
|
21
|
+
const x = parse(left), y = parse(right);
|
|
22
|
+
for (let i = 0; i < 3; i++) if (x.core[i] !== y.core[i]) return x.core[i] < y.core[i] ? -1 : 1;
|
|
23
|
+
if (!x.prerelease || !y.prerelease) return x.prerelease === y.prerelease ? 0 : x.prerelease ? -1 : 1;
|
|
24
|
+
for (let i = 0; i < Math.max(x.prerelease.length, y.prerelease.length); i++) {
|
|
25
|
+
const a = x.prerelease[i], b = y.prerelease[i];
|
|
26
|
+
if (a === undefined || b === undefined) return a === b ? 0 : a === undefined ? -1 : 1;
|
|
27
|
+
if (a === b) continue;
|
|
28
|
+
const aNumeric = /^\d+$/u.test(a), bNumeric = /^\d+$/u.test(b);
|
|
29
|
+
if (aNumeric && bNumeric) return BigInt(a) < BigInt(b) ? -1 : 1;
|
|
30
|
+
if (aNumeric !== bNumeric) return aNumeric ? -1 : 1;
|
|
31
|
+
return a < b ? -1 : 1;
|
|
32
|
+
}
|
|
33
|
+
return 0;
|
|
34
|
+
}
|