File size: 8,446 Bytes
ffd5822 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | #!/usr/bin/env node
/**
* Generates stub packages for all workspace:* dependencies.
* Scans web/src for imports from @szl-holdings/*, @workspace/*, @szl/*
* and creates minimal stub packages under stubs/ directory.
*/
import { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync } from 'fs';
import { join, dirname, resolve } from 'path';
const ROOT = resolve(dirname(new URL(import.meta.url).pathname), '..');
const SRC_DIR = join(ROOT, 'web', 'src');
// Collect all .ts/.tsx files recursively
function collectFiles(dir, exts = ['.ts', '.tsx']) {
const results = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
results.push(...collectFiles(full, exts));
} else if (exts.some(ext => entry.name.endsWith(ext))) {
results.push(full);
}
}
return results;
}
// Also scan index.css for CSS imports
const cssFile = join(ROOT, 'web', 'src', 'index.css');
// Parse imports from a TypeScript/TSX file
function parseImports(content) {
const imports = [];
// Match: import { X, Y } from 'pkg'; import X from 'pkg'; import 'pkg';
const importRegex = /import\s+(?:(?:type\s+)?(?:\{([^}]*)\}|(\w+))\s+from\s+)?['"](@szl-holdings\/[^'"]+|@workspace\/[^'"]+|@szl\/[^'"]+)['"]/g;
let m;
while ((m = importRegex.exec(content)) !== null) {
const namedStr = m[1] || '';
const defaultImport = m[2] || null;
const modulePath = m[3];
const named = namedStr
.split(',')
.map(s => s.trim())
.filter(Boolean)
.map(s => {
// Handle "X as Y" -> extract X
const asMatch = s.match(/^(?:type\s+)?(\w+)(?:\s+as\s+\w+)?$/);
return asMatch ? asMatch[1] : s.replace(/^type\s+/, '');
})
.filter(s => /^\w+$/.test(s));
imports.push({ modulePath, named, defaultImport });
}
return imports;
}
// Collect all imports
const allFiles = collectFiles(SRC_DIR);
const importMap = new Map(); // pkgName -> Map<subpath, Set<exportName>>
for (const file of allFiles) {
const content = readFileSync(file, 'utf-8');
const imports = parseImports(content);
for (const { modulePath, named, defaultImport } of imports) {
// Split: @szl-holdings/shared-ui/utils -> pkg=@szl-holdings/shared-ui, sub=utils
const parts = modulePath.split('/');
let pkgName, subpath;
if (parts[0].startsWith('@')) {
pkgName = parts.slice(0, 2).join('/');
subpath = parts.slice(2).join('/') || '.';
} else {
pkgName = parts[0];
subpath = parts.slice(1).join('/') || '.';
}
if (!importMap.has(pkgName)) {
importMap.set(pkgName, new Map());
}
const subMap = importMap.get(pkgName);
if (!subMap.has(subpath)) {
subMap.set(subpath, new Set());
}
const exports = subMap.get(subpath);
for (const n of named) exports.add(n);
if (defaultImport) exports.add('__default__:' + defaultImport);
}
}
// Also handle CSS imports
try {
const cssContent = readFileSync(cssFile, 'utf-8');
const cssImportRegex = /@import\s+['"](@szl-holdings\/[^'"]+|@workspace\/[^'"]+|@szl\/[^'"]+)['"]/g;
let m;
while ((m = cssImportRegex.exec(cssContent)) !== null) {
const modulePath = m[1];
const parts = modulePath.split('/');
let pkgName, subpath;
if (parts[0].startsWith('@')) {
pkgName = parts.slice(0, 2).join('/');
subpath = parts.slice(2).join('/') || '.';
} else {
pkgName = parts[0];
subpath = parts.slice(1).join('/') || '.';
}
if (!importMap.has(pkgName)) importMap.set(pkgName, new Map());
const subMap = importMap.get(pkgName);
if (!subMap.has(subpath)) subMap.set(subpath, new Set());
subMap.get(subpath).add('__css__');
}
} catch (e) { /* ignore */ }
// React component stub generator
function generateStubCode(exportNames) {
const lines = ["import React from 'react';"];
const hasCSS = exportNames.has('__css__');
const jsExports = [...exportNames].filter(n => !n.startsWith('__'));
const defaultExports = [...exportNames].filter(n => n.startsWith('__default__:'));
// Known type-only exports that should be exported as types
const typeOnlyNames = new Set(['AuthTokens', 'CommandModeSignal', 'SidebarNavSection',
'KeyboardShortcut', 'OnboardingConfig', 'CommandItem', 'ActivationStep',
'DataProvenanceInfo', 'StatusVariant', 'AuditTrailEntry', 'PolicyDecisionRecord',
'ProofPanelData', 'RecommendationAction', 'AutonomyMode', 'AmbientSignal',
'DocumentPipelineResult', 'OwnershipNode']);
// Generate a React component stub
const componentStub = `(props) => React.createElement('div', { 'data-stub': true, ...props }, props?.children || null)`;
const fnStub = `(...args) => {}`;
for (const name of jsExports) {
if (typeOnlyNames.has(name)) {
// Skip type-only exports in JS (they're just types)
continue;
}
// Heuristic: PascalCase = React component, camelCase/UPPER = function/constant
if (/^[A-Z]/.test(name)) {
lines.push(`export const ${name} = ${componentStub};`);
} else if (name === 'cn') {
lines.push(`export function cn(...args) { return args.filter(Boolean).join(' '); }`);
} else if (name === 'toAlpha') {
lines.push(`export function toAlpha(hex, alpha) { return hex + Math.round(alpha * 255).toString(16).padStart(2, '0'); }`);
} else if (name === 'color') {
lines.push(`export const color = new Proxy({}, { get: (t, k) => '#888888' });`);
} else if (name === 'toast') {
lines.push(`export const toast = Object.assign((...a) => {}, { success: () => {}, error: () => {}, info: () => {}, warning: () => {}, dismiss: () => {} });`);
} else if (name === 'analytics') {
lines.push(`export const analytics = { track: () => {}, identify: () => {}, page: () => {}, reset: () => {} };`);
} else {
lines.push(`export const ${name} = ${fnStub};`);
}
}
// Default export
if (defaultExports.length > 0) {
lines.push(`export default ${componentStub};`);
} else if (jsExports.length === 0 && !hasCSS) {
lines.push(`export default {};`);
}
if (hasCSS) {
return '/* stub CSS */';
}
return lines.join('\n') + '\n';
}
// Generate stub packages
const STUBS_DIR = join(ROOT, 'stubs');
mkdirSync(STUBS_DIR, { recursive: true });
for (const [pkgName, subMap] of importMap) {
const safeDirName = pkgName.replace(/^@/, '').replace(/\//g, '__');
const pkgDir = join(STUBS_DIR, safeDirName);
mkdirSync(pkgDir, { recursive: true });
// Build exports map for package.json
const exportsMap = {};
const subpaths = [...subMap.keys()];
for (const sub of subpaths) {
const exportNames = subMap.get(sub);
const hasCSS = exportNames.has('__css__');
const fileName = sub === '.' ? 'index' : sub.replace(/\//g, '__');
const ext = hasCSS ? '.css' : '.js';
const filePath = `./${fileName}${ext}`;
// Write the stub file
const stubContent = generateStubCode(exportNames);
writeFileSync(join(pkgDir, `${fileName}${ext}`), stubContent);
// Add to exports map
const exportKey = sub === '.' ? '.' : `./${sub}`;
if (hasCSS) {
exportsMap[exportKey] = filePath;
} else {
exportsMap[exportKey] = { import: filePath, default: filePath };
}
}
// Add a wildcard catch-all export
exportsMap['./*'] = { import: './catch-all.js', default: './catch-all.js' };
// Write catch-all stub
writeFileSync(join(pkgDir, 'catch-all.js'), `
import React from 'react';
const Stub = (props) => React.createElement('div', { 'data-stub': true, ...props }, props?.children || null);
export default Stub;
export { Stub };
export const noop = () => {};
`);
// Write package.json
const pkgJson = {
name: pkgName,
version: '0.0.0-stub',
type: 'module',
exports: exportsMap,
main: './index.js',
};
// Write index.js if not already created
if (!subMap.has('.')) {
writeFileSync(join(pkgDir, 'index.js'), `
import React from 'react';
const Stub = (props) => React.createElement('div', { 'data-stub': true, ...props }, props?.children || null);
export default Stub;
export { Stub };
`);
pkgJson.exports['.'] = { import: './index.js', default: './index.js' };
}
writeFileSync(join(pkgDir, 'package.json'), JSON.stringify(pkgJson, null, 2) + '\n');
console.log(`✓ ${pkgName} (${subpaths.length} subpaths)`);
}
console.log(`\nGenerated ${importMap.size} stub packages in stubs/`);
|