@astryxdesign/cli 0.6.1 → 0.6.2-canary.bc93547
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/CHANGELOG.md +34 -0
- package/README.md +1 -1
- package/api/component/_adapter.mjs +64 -23
- package/api/component/component.doc.mjs +1 -1
- package/api/component/component.type.d.mts +8 -2
- package/api/component/component.type.mjs +5 -2
- package/api/component/integration-import-agreement.test.mjs +162 -6
- package/api/component/list/list.mjs +91 -15
- package/api/doctor/doctor.mjs +5 -16
- package/api/init/init.doc.mjs +2 -2
- package/api/init/init.type.d.mts +1 -1
- package/api/init/init.type.mjs +1 -1
- package/api/init/run/run.mjs +1 -1
- package/api/integration/add-helpers.mjs +2 -1
- package/api/integration/pack-check.mjs +9 -3
- package/api/search/search.d.mts +1 -1
- package/api/search/search.mjs +135 -41
- package/api/theme/build/build.d.mts +45 -17
- package/api/theme/build/build.family.test.mjs +435 -0
- package/api/theme/build/build.mjs +681 -121
- package/api/theme/build/build.packed-old-core.test.mjs +25 -9
- package/api/theme/build/build.test.mjs +142 -0
- package/api/theme/build/core-interception.d.mts +14 -2
- package/api/theme/build/core-interception.mjs +38 -14
- package/api/theme/build/family.d.mts +15 -0
- package/api/theme/build/family.mjs +442 -0
- package/api/theme/palette/generate/generate.mjs +2 -1
- package/assets/docs/theme.doc.dense.mjs +12 -0
- package/assets/docs/theme.doc.mjs +37 -0
- package/assets/docs/working-with-ai.doc.mjs +2 -1
- package/clients/cli/commands/build-theme.mjs +63 -5
- package/clients/cli/commands/component/index.mjs +4 -1
- package/clients/cli/commands/init.doc.mjs +2 -2
- package/clients/cli/commands/theme-build.doc.mjs +28 -10
- package/foundation/agent-docs/agent-doc-state.mjs +1 -1
- package/foundation/agent-docs/agent-docs.d.mts +2 -2
- package/foundation/agent-docs/agent-docs.mjs +8 -6
- package/foundation/agent-docs/agent-docs.test.mjs +14 -0
- package/foundation/discovery/__fixtures__/component-both-exports.doc.d.mts +24 -0
- package/foundation/discovery/__fixtures__/component-both-exports.doc.mjs +19 -0
- package/foundation/discovery/__fixtures__/component-default-export.doc.d.mts +14 -0
- package/foundation/discovery/__fixtures__/component-default-export.doc.mjs +13 -0
- package/foundation/discovery/__fixtures__/component-named-export.doc.d.mts +13 -0
- package/foundation/discovery/__fixtures__/component-named-export.doc.mjs +11 -0
- package/foundation/discovery/component-discovery.d.mts +5 -3
- package/foundation/discovery/component-discovery.mjs +25 -9
- package/foundation/discovery/component-loader.mjs +4 -1
- package/foundation/discovery/component-loader.test.mjs +48 -0
- package/foundation/discovery/theming-targets.test.mjs +29 -0
- package/foundation/fs/paths.d.mts +19 -0
- package/foundation/fs/paths.mjs +54 -0
- package/foundation/fs/paths.test.mjs +102 -1
- package/foundation/fs/publish-file-eperm-mutation.test.mjs +62 -0
- package/foundation/fs/publish-file-hardlink-unavailable.test.mjs +107 -0
- package/foundation/fs/publish-file.d.mts +22 -0
- package/foundation/fs/publish-file.mjs +68 -0
- package/foundation/fs/publish-file.test.mjs +136 -0
- package/foundation/integrations/manifest-writer.mjs +2 -1
- package/foundation/response/response-types.doc.mjs +1 -1
- package/package.json +15 -10
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* @file theme build API — compile
|
|
4
|
+
* @file theme build API — compile standalone themes or one selected family.
|
|
5
5
|
*
|
|
6
|
-
* `themeBuild
|
|
7
|
-
*
|
|
6
|
+
* `themeBuild` and `themeBuildFamily` share the same loader, compiler,
|
|
7
|
+
* serializers, check, and writer. They read defineTheme() sources and, via
|
|
8
8
|
* @astryxdesign/core's shared generator (the SINGLE source of truth so the
|
|
9
9
|
* build emits the exact CSS the `<Theme>` runtime does), writes:
|
|
10
10
|
* - A CSS file with token overrides and component styles
|
|
@@ -39,7 +39,9 @@
|
|
|
39
39
|
|
|
40
40
|
import * as fs from 'node:fs';
|
|
41
41
|
import * as path from 'node:path';
|
|
42
|
-
import {
|
|
42
|
+
import {isBuiltin} from 'node:module';
|
|
43
|
+
import {fileURLToPath, pathToFileURL} from 'node:url';
|
|
44
|
+
import {parse} from '@babel/parser';
|
|
43
45
|
import {createJiti} from 'jiti';
|
|
44
46
|
import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
|
|
45
47
|
import {CLI_ROOT, findCoreDir} from '../../../foundation/fs/paths.mjs';
|
|
@@ -58,6 +60,7 @@ import {
|
|
|
58
60
|
} from '../../../foundation/discovery/theming-targets.mjs';
|
|
59
61
|
import {collectUnloadedFonts, formatFontLoadingHelp} from './font-warning.mjs';
|
|
60
62
|
import {interceptCore} from './core-interception.mjs';
|
|
63
|
+
import {generateFamilyCSS, resolveThemeFamily} from './family.mjs';
|
|
61
64
|
|
|
62
65
|
// Import shared theme processing from core. `astryx theme build` MUST produce the
|
|
63
66
|
// exact same CSS as the `<Theme>` runtime, so it has exactly one generation
|
|
@@ -199,17 +202,84 @@ function normalizeForCompare(content) {
|
|
|
199
202
|
.join('\n');
|
|
200
203
|
}
|
|
201
204
|
|
|
205
|
+
/** @param {Array<{dest: string, content: string}>} writes @param {string} cwd @returns {Array<{path: string, reason: 'missing' | 'outdated'}>} */
|
|
206
|
+
function staleBuildOutputs(writes, cwd) {
|
|
207
|
+
/** @type {Array<{path: string, reason: 'missing' | 'outdated'}>} */
|
|
208
|
+
const stale = [];
|
|
209
|
+
for (const write of writes) {
|
|
210
|
+
const rel = path.relative(cwd, write.dest);
|
|
211
|
+
if (!fs.existsSync(write.dest)) {
|
|
212
|
+
stale.push({path: rel, reason: 'missing'});
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const onDisk = fs.readFileSync(write.dest, 'utf8');
|
|
216
|
+
if (normalizeForCompare(onDisk) !== normalizeForCompare(write.content)) {
|
|
217
|
+
stale.push({path: rel, reason: 'outdated'});
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return stale;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** @param {Array<{dest: string, content: string}>} writes */
|
|
224
|
+
function writeBuildOutputs(writes) {
|
|
225
|
+
if (writes.length === 0) return;
|
|
226
|
+
fs.mkdirSync(path.dirname(writes[0].dest), {recursive: true});
|
|
227
|
+
/** @type {Array<{tmp: string, dest: string}>} */
|
|
228
|
+
const staged = [];
|
|
229
|
+
try {
|
|
230
|
+
for (const write of writes) {
|
|
231
|
+
const tmp = `${write.dest}.${process.pid}.tmp`;
|
|
232
|
+
fs.writeFileSync(tmp, write.content);
|
|
233
|
+
staged.push({tmp, dest: write.dest});
|
|
234
|
+
}
|
|
235
|
+
for (const stagedWrite of staged) {
|
|
236
|
+
fs.renameSync(stagedWrite.tmp, stagedWrite.dest);
|
|
237
|
+
}
|
|
238
|
+
} catch (error) {
|
|
239
|
+
for (const stagedWrite of staged) {
|
|
240
|
+
try {
|
|
241
|
+
fs.rmSync(stagedWrite.tmp, {force: true});
|
|
242
|
+
} catch {
|
|
243
|
+
// Best effort: the command still fails and never reports success.
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
const message = `Failed to write theme outputs: ${/** @type {Error} */ (error).message}`;
|
|
247
|
+
throw new AstryxError(message, undefined, ERROR_CODES.ERR_WRITE_FAILED);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
202
251
|
/**
|
|
203
252
|
* Convert a theme name to a valid JS identifier.
|
|
204
|
-
*
|
|
253
|
+
*
|
|
254
|
+
* Deterministic sanitization rule — only transforms characters that are invalid
|
|
255
|
+
* in JS identifiers (`-` and `.`); underscores are already valid and preserved:
|
|
256
|
+
* 1. Replace every run of invalid separators (`-`, `.`) followed by an
|
|
257
|
+
* alphanumeric or underscore character with that character uppercased.
|
|
258
|
+
* 2. Strip any remaining invalid separators (leading or trailing).
|
|
259
|
+
* 3. If the result starts with a digit, prefix with `_`.
|
|
260
|
+
* 4. If the result is empty, return `_`.
|
|
261
|
+
*
|
|
262
|
+
* Examples:
|
|
263
|
+
* 'ocean' → 'ocean'
|
|
264
|
+
* 'default-minimal' → 'defaultMinimal'
|
|
265
|
+
* 'chaos-07' → 'chaos07'
|
|
266
|
+
* 'a-1-b' → 'a1B'
|
|
267
|
+
* 'my--theme' → 'myTheme'
|
|
268
|
+
* 'brand.v2' → 'brandV2'
|
|
269
|
+
* 'my_theme' → 'my_theme' (underscore preserved)
|
|
270
|
+
* 'neo_wave-2.x' → 'neo_wave2X'
|
|
271
|
+
*
|
|
205
272
|
* @param {string} name
|
|
206
273
|
* @returns {string}
|
|
207
274
|
*/
|
|
208
275
|
function toIdentifier(name) {
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
276
|
+
const id = name
|
|
277
|
+
.replace(
|
|
278
|
+
/[-.]+([a-zA-Z0-9_])/g,
|
|
279
|
+
(/** @type {string} */ _, /** @type {string} */ c) => c.toUpperCase(),
|
|
280
|
+
)
|
|
281
|
+
.replace(/[-.]+/g, '');
|
|
282
|
+
return /^\d/.test(id) ? `_${id}` : id || '_';
|
|
213
283
|
}
|
|
214
284
|
|
|
215
285
|
/**
|
|
@@ -1136,7 +1206,85 @@ const THEME_MODULE_EXTENSIONS = [
|
|
|
1136
1206
|
'.js',
|
|
1137
1207
|
'.json',
|
|
1138
1208
|
];
|
|
1139
|
-
|
|
1209
|
+
// prettier-ignore
|
|
1210
|
+
const registryGraphError = (/** @type {string} */ message) => new AstryxError(message, undefined, ERROR_CODES.ERR_THEME_INVALID);
|
|
1211
|
+
// prettier-ignore
|
|
1212
|
+
function parseRegistryModule(/** @type {string} */ source, /** @type {string} */ filePath) {
|
|
1213
|
+
try { return parse(source, {sourceType: 'unambiguous', plugins: ['typescript', 'jsx', 'decorators-legacy', 'importAttributes']}); }
|
|
1214
|
+
catch (error) { throw registryGraphError(`Cannot inspect registry module ${filePath}: ${error instanceof Error ? error.message : String(error)}`); }
|
|
1215
|
+
}
|
|
1216
|
+
// prettier-ignore
|
|
1217
|
+
function moduleDependencies(/** @type {string} */ source, /** @type {string} */ filePath) {
|
|
1218
|
+
const ast = parseRegistryModule(source, filePath);
|
|
1219
|
+
/** @type {Array<{specifier: string, commonJs: boolean, imports: string[]}>} */ const found = [];
|
|
1220
|
+
/** @param {any} node */ const literal = node => typeof node?.value === 'string' ? node.value : node?.type === 'TemplateLiteral' && node.expressions.length === 0 ? node.quasis[0]?.value?.cooked : null;
|
|
1221
|
+
/** @param {any} node */ const visit = node => {
|
|
1222
|
+
if (!node || typeof node !== 'object') return;
|
|
1223
|
+
if (['ImportDeclaration', 'ExportNamedDeclaration', 'ExportAllDeclaration'].includes(node.type) && node.importKind !== 'type' && typeof node.source?.value === 'string') {
|
|
1224
|
+
const specifiers = /** @type {any[]} */ (node.specifiers);
|
|
1225
|
+
const imports = node.type === 'ImportDeclaration' ? specifiers.filter(item => item.importKind !== 'type' && item.type !== 'ImportNamespaceSpecifier').map(item => item.type === 'ImportDefaultSpecifier' ? 'default' : item.imported?.name ?? item.imported?.value) : node.type === 'ExportNamedDeclaration' ? specifiers.filter(item => item.exportKind !== 'type' && item.type === 'ExportSpecifier').map(item => item.local?.name ?? item.local?.value) : [];
|
|
1226
|
+
found.push({specifier: node.source.value, commonJs: false, imports});
|
|
1227
|
+
}
|
|
1228
|
+
const dependency = node.type === 'ImportExpression' ? node.source : node.type === 'CallExpression' && (node.callee?.type === 'Import' || node.callee?.name === 'require') ? node.arguments?.[0] : null;
|
|
1229
|
+
if (dependency) { const specifier = literal(dependency); if (specifier == null) throw registryGraphError(`Registry module ${filePath} has a non-static dependency; family output cannot prove that graph is resolvable and CSS-free.`); found.push({specifier, commonJs: node.callee?.name === 'require', imports: []}); }
|
|
1230
|
+
for (const value of Object.values(node)) if (Array.isArray(value)) value.forEach(child => child?.type && visit(child)); else if (value?.type) visit(value);
|
|
1231
|
+
};
|
|
1232
|
+
visit(ast); return found;
|
|
1233
|
+
}
|
|
1234
|
+
// prettier-ignore
|
|
1235
|
+
function resolveRegistryModule(/** @type {string} */ specifier, /** @type {string} */ parentPath, commonJs = false) {
|
|
1236
|
+
if (isBuiltin(specifier) || specifier.startsWith('node:')) return null;
|
|
1237
|
+
let resolved;
|
|
1238
|
+
try {
|
|
1239
|
+
const resolver = createJiti(parentPath, {extensions: THEME_MODULE_EXTENSIONS});
|
|
1240
|
+
if (commonJs) resolved = resolver.resolve(specifier);
|
|
1241
|
+
else if (specifier.startsWith('.')) resolved = fileURLToPath(new URL(specifier, pathToFileURL(parentPath)));
|
|
1242
|
+
else if (path.isAbsolute(specifier)) resolved = specifier;
|
|
1243
|
+
else { const url = resolver.esmResolve(specifier); resolved = url.startsWith('file:') ? fileURLToPath(url) : url; }
|
|
1244
|
+
} catch (error) { throw registryGraphError(`Cannot resolve registry import "${specifier}" from ${parentPath}: ${error instanceof Error ? error.message : String(error)}`); }
|
|
1245
|
+
if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) throw registryGraphError(`Cannot resolve registry import "${specifier}" from ${parentPath}.`);
|
|
1246
|
+
return fs.realpathSync(resolved);
|
|
1247
|
+
}
|
|
1248
|
+
/** @returns {boolean | null} */
|
|
1249
|
+
// prettier-ignore
|
|
1250
|
+
function hasNamedExport(/** @type {string} */ file, /** @type {string} */ name, seen = new Set()) {
|
|
1251
|
+
const key = `${file}\0${name}`; if (seen.has(key)) return false; seen.add(key);
|
|
1252
|
+
const ast = parseRegistryModule(fs.readFileSync(file, 'utf8'), file); let esm = false; let unknown = false;
|
|
1253
|
+
for (const node of /** @type {any[]} */ (ast.program.body)) {
|
|
1254
|
+
if (node.type === 'ExportDefaultDeclaration') { esm = true; if (name === 'default') return true; }
|
|
1255
|
+
if (node.type === 'ExportNamedDeclaration') {
|
|
1256
|
+
esm = true; const declaration = /** @type {any} */ (node.declaration);
|
|
1257
|
+
if ((declaration?.id?.name === name) || (declaration?.type === 'VariableDeclaration' && declaration.declarations.some((/** @type {any} */ item) => item.id?.name === name))) return true;
|
|
1258
|
+
for (const specifier of /** @type {any[]} */ (node.specifiers)) if ((specifier.exported?.name ?? specifier.exported?.value) === name) {
|
|
1259
|
+
if (!node.source || specifier.type === 'ExportNamespaceSpecifier') return true;
|
|
1260
|
+
const target = resolveRegistryModule(node.source.value, file); return target ? hasNamedExport(target, specifier.local?.name ?? specifier.local?.value, seen) : false;
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
if (node.type === 'ExportAllDeclaration') { esm = true; const target = resolveRegistryModule(node.source.value, file); const status = target ? hasNamedExport(target, name, seen) : false; if (status === true) return true; if (status === null) unknown = true; }
|
|
1264
|
+
}
|
|
1265
|
+
return esm ? unknown ? null : false : null;
|
|
1266
|
+
}
|
|
1267
|
+
// prettier-ignore
|
|
1268
|
+
async function validateRegistryGraphs(/** @type {Array<{specifier: string, exportName: string}>} */ registries, /** @type {string} */ aggregatePath) {
|
|
1269
|
+
/** @type {Array<{specifier: string, parent: string, commonJs: boolean, imports: string[], root?: {exportName: string}}>} */ const pending = registries.map(root => ({specifier: root.specifier, parent: aggregatePath, commonJs: false, imports: [root.exportName], root}));
|
|
1270
|
+
/** @type {Array<{file: string, exportName: string}>} */ const runtimeChecks = []; const seen = new Set();
|
|
1271
|
+
while (pending.length > 0) {
|
|
1272
|
+
const current = pending.pop(); if (!current) break; const {specifier, parent, commonJs, imports, root} = current;
|
|
1273
|
+
if (/\.css(?:$|[?#])/i.test(specifier)) throw registryGraphError(`Theme family registry graph imports CSS: ${specifier}`);
|
|
1274
|
+
const file = resolveRegistryModule(specifier, parent, commonJs); if (!file) continue;
|
|
1275
|
+
if (/\.css$/i.test(file)) throw registryGraphError(`Theme family registry graph imports CSS: ${file}`);
|
|
1276
|
+
const external = file.split(path.sep).includes('node_modules');
|
|
1277
|
+
for (const name of imports) if (external) runtimeChecks.push({file, exportName: name}); else { const named = hasNamedExport(file, name); if (named === false) throw registryGraphError(`Family registry ${file} does not export "${name}".`); if (named === null) runtimeChecks.push({file, exportName: name}); }
|
|
1278
|
+
if (root) runtimeChecks.push({file, exportName: root.exportName});
|
|
1279
|
+
if (seen.has(file)) continue; seen.add(file);
|
|
1280
|
+
if (/\.[cm]?[jt]sx?$/i.test(file)) for (const edge of moduleDependencies(fs.readFileSync(file, 'utf8'), file)) pending.push({...edge, parent: file});
|
|
1281
|
+
}
|
|
1282
|
+
for (const [index, root] of runtimeChecks.entries()) {
|
|
1283
|
+
let exports; try { exports = await import(`${pathToFileURL(root.file).href}?astryx-family-check=${Date.now()}-${index}`); }
|
|
1284
|
+
catch (error) { throw registryGraphError(`Cannot import family registry ${root.file}: ${error instanceof Error ? error.message : String(error)}`); }
|
|
1285
|
+
if (!(root.exportName in exports)) throw registryGraphError(`Family registry ${root.file} does not export "${root.exportName}".`);
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1140
1288
|
/**
|
|
1141
1289
|
* Errors that mean "the synchronous loader cannot evaluate this module", as
|
|
1142
1290
|
* opposed to "this module is broken". Only the former may fall back to the
|
|
@@ -1175,23 +1323,27 @@ function isSyncLoaderLimitation(error) {
|
|
|
1175
1323
|
* author's adaptations unobserved. The sync path transpiles it, so the wrapped
|
|
1176
1324
|
* core reaches inside installed packages too.
|
|
1177
1325
|
*
|
|
1178
|
-
* A module the sync path cannot evaluate
|
|
1179
|
-
*
|
|
1180
|
-
*
|
|
1181
|
-
*
|
|
1182
|
-
*
|
|
1326
|
+
* A module the sync path cannot evaluate (top-level await) is force-transpiled
|
|
1327
|
+
* through jiti's asynchronous evaluator. That keeps interception active for
|
|
1328
|
+
* the entry and captures its exact `extends` value; relative dependencies may
|
|
1329
|
+
* use native ESM, so family mode binds those objects back to the exact selected
|
|
1330
|
+
* source export and old-Core adaptation checks keep treating that path as
|
|
1331
|
+
* degraded/fail-closed.
|
|
1183
1332
|
*
|
|
1184
1333
|
* @param {string} filePath
|
|
1185
1334
|
* @param {import('./core-interception.mjs').CoreInterception} [interception]
|
|
1186
1335
|
* @returns {Promise<{theme: any, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}
|
|
1187
1336
|
*/
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1337
|
+
// prettier-ignore
|
|
1338
|
+
async function importThemeModule(filePath, interception, /** @type {any} */ loader = undefined) {
|
|
1339
|
+
const jiti =
|
|
1340
|
+
loader ??
|
|
1341
|
+
createJiti(import.meta.url, {
|
|
1342
|
+
moduleCache: false,
|
|
1343
|
+
jsx: true,
|
|
1344
|
+
extensions: THEME_MODULE_EXTENSIONS,
|
|
1345
|
+
...(interception ? {virtualModules: interception.modules} : {}),
|
|
1346
|
+
});
|
|
1195
1347
|
|
|
1196
1348
|
/** @type {any} */
|
|
1197
1349
|
let mod;
|
|
@@ -1211,7 +1363,17 @@ async function importThemeModule(filePath, interception) {
|
|
|
1211
1363
|
// theme's own failure and belongs to the caller unchanged.
|
|
1212
1364
|
if (!isSyncLoaderLimitation(error)) throw error;
|
|
1213
1365
|
degraded.topLevelAwait = true;
|
|
1214
|
-
|
|
1366
|
+
// Force asynchronous transformation instead of native import: this
|
|
1367
|
+
// keeps virtual Core interception active even when the module uses
|
|
1368
|
+
// top-level await.
|
|
1369
|
+
mod = await jiti.evalModule(fs.readFileSync(filePath, 'utf8'), {
|
|
1370
|
+
id: filePath,
|
|
1371
|
+
filename: filePath,
|
|
1372
|
+
ext: path.extname(filePath),
|
|
1373
|
+
cache: jiti.cache,
|
|
1374
|
+
async: true,
|
|
1375
|
+
forceTranspile: true,
|
|
1376
|
+
});
|
|
1215
1377
|
}
|
|
1216
1378
|
} finally {
|
|
1217
1379
|
commonJsPatch.undo();
|
|
@@ -1261,9 +1423,10 @@ function isThemeObject(value) {
|
|
|
1261
1423
|
* @param {import('./core-interception.mjs').CoreInterception} [interception]
|
|
1262
1424
|
* @returns {Promise<{theme: any, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}
|
|
1263
1425
|
*/
|
|
1264
|
-
|
|
1426
|
+
// prettier-ignore
|
|
1427
|
+
async function extractThemeDefinition(filePath, interception, /** @type {any} */ loader = undefined) {
|
|
1265
1428
|
try {
|
|
1266
|
-
return await importThemeModule(filePath, interception);
|
|
1429
|
+
return await importThemeModule(filePath, interception, loader);
|
|
1267
1430
|
} catch (jitiError) {
|
|
1268
1431
|
try {
|
|
1269
1432
|
return {
|
|
@@ -1331,26 +1494,45 @@ function extractThemeDefinitionLegacy(filePath) {
|
|
|
1331
1494
|
* @param {string} filePath
|
|
1332
1495
|
* @returns {{exportName: string, importPath: string} | null}
|
|
1333
1496
|
*/
|
|
1334
|
-
function
|
|
1497
|
+
function extractRegistryInfo(filePath, field = 'icons', familyMode = false) {
|
|
1335
1498
|
const content = fs.readFileSync(filePath, 'utf8');
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1499
|
+
if (!familyMode) {
|
|
1500
|
+
const fieldMatch = content.match(
|
|
1501
|
+
new RegExp(`${field}:\\s*([a-zA-Z_][a-zA-Z0-9_]*)`),
|
|
1502
|
+
);
|
|
1503
|
+
if (!fieldMatch) return null;
|
|
1504
|
+
const varName = fieldMatch[1];
|
|
1505
|
+
const match = content.match(
|
|
1506
|
+
new RegExp(
|
|
1507
|
+
`import\\s*{[^}]*\\b${varName}\\b[^}]*}\\s*from\\s*['"]([^'"]+)['"]`,
|
|
1508
|
+
),
|
|
1509
|
+
);
|
|
1510
|
+
return match ? {exportName: varName, importPath: match[1]} : null;
|
|
1511
|
+
}
|
|
1512
|
+
const defineIndex = content.indexOf('defineTheme(');
|
|
1513
|
+
if (defineIndex < 0) return null;
|
|
1514
|
+
const themeSource = content.slice(defineIndex);
|
|
1515
|
+
const explicit = themeSource.match(
|
|
1516
|
+
new RegExp(`${field}:\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*(?=[,}])`),
|
|
1346
1517
|
);
|
|
1347
|
-
const
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1518
|
+
const shorthand = themeSource.match(
|
|
1519
|
+
new RegExp(`[,{]\\s*(${field})\\s*(?=[,}])`),
|
|
1520
|
+
);
|
|
1521
|
+
const varName = explicit?.[1] ?? shorthand?.[1];
|
|
1522
|
+
if (!varName) return null;
|
|
1523
|
+
for (const match of content.matchAll(
|
|
1524
|
+
/import\s*{([^}]*)}\s*from\s*['"]([^'"]+)['"]/g,
|
|
1525
|
+
)) {
|
|
1526
|
+
for (const specifier of match[1].split(',')) {
|
|
1527
|
+
const [exportName, localName = exportName] = specifier
|
|
1528
|
+
.trim()
|
|
1529
|
+
.split(/\s+as\s+/);
|
|
1530
|
+
if (localName === varName) {
|
|
1531
|
+
return {exportName, importPath: match[2]};
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
return null;
|
|
1354
1536
|
}
|
|
1355
1537
|
|
|
1356
1538
|
/**
|
|
@@ -1376,9 +1558,20 @@ function extractIconInfo(filePath) {
|
|
|
1376
1558
|
* @param {any} themeDef
|
|
1377
1559
|
* @param {{exportName: string, importPath: string} | null} iconInfo
|
|
1378
1560
|
* @param {string} [iconsSpecifier] - Overrides the scraped icon import specifier.
|
|
1561
|
+
* @param {{themeBinding?: string, iconBinding?: string, iconsExpression?: string, indicatorsExpression?: string, artifactBaseName?: string, exportIcons?: boolean}} [moduleOptions]
|
|
1379
1562
|
* @returns {string}
|
|
1380
1563
|
*/
|
|
1381
|
-
function generateBuiltModule(
|
|
1564
|
+
function generateBuiltModule(
|
|
1565
|
+
themeDef,
|
|
1566
|
+
iconInfo,
|
|
1567
|
+
iconsSpecifier,
|
|
1568
|
+
moduleOptions = {},
|
|
1569
|
+
) {
|
|
1570
|
+
const themeBinding =
|
|
1571
|
+
moduleOptions.themeBinding ?? `${toIdentifier(themeDef.name)}Theme`;
|
|
1572
|
+
const iconBinding = moduleOptions.iconBinding ?? iconInfo?.exportName;
|
|
1573
|
+
const artifactBaseName = moduleOptions.artifactBaseName ?? themeDef.name;
|
|
1574
|
+
const exportIcons = moduleOptions.exportIcons ?? true;
|
|
1382
1575
|
// Preserve the historical generated bytes when no override is supplied.
|
|
1383
1576
|
// User-provided specifiers need string-literal encoding so quotes and
|
|
1384
1577
|
// backslashes cannot produce invalid JavaScript.
|
|
@@ -1387,10 +1580,18 @@ function generateBuiltModule(themeDef, iconInfo, iconsSpecifier) {
|
|
|
1387
1580
|
? `'${iconInfo?.importPath}'`
|
|
1388
1581
|
: JSON.stringify(iconsSpecifier);
|
|
1389
1582
|
const iconImport = iconInfo
|
|
1390
|
-
? `import { ${iconInfo.exportName} } from ${renderedSpecifier};\n`
|
|
1583
|
+
? `import { ${iconInfo.exportName}${iconBinding === iconInfo.exportName ? '' : ` as ${iconBinding}`} } from ${renderedSpecifier};\n`
|
|
1584
|
+
: '';
|
|
1585
|
+
const iconsExpression =
|
|
1586
|
+
moduleOptions.iconsExpression ?? (iconInfo ? iconBinding : undefined);
|
|
1587
|
+
const iconsField = iconsExpression ? ` icons: ${iconsExpression},` : '';
|
|
1588
|
+
const indicatorsField = moduleOptions.indicatorsExpression
|
|
1589
|
+
? `\n indicators: ${moduleOptions.indicatorsExpression},`
|
|
1391
1590
|
: '';
|
|
1392
|
-
const
|
|
1393
|
-
|
|
1591
|
+
const iconReExport =
|
|
1592
|
+
iconInfo && exportIcons
|
|
1593
|
+
? `\nexport { ${iconBinding}${iconBinding === iconInfo.exportName ? '' : ` as ${iconInfo.exportName}`} };\n`
|
|
1594
|
+
: '';
|
|
1394
1595
|
|
|
1395
1596
|
// Resolve token values — tuples become light-dark() strings
|
|
1396
1597
|
/** @type {Record<string, unknown>} */
|
|
@@ -1453,14 +1654,14 @@ function generateBuiltModule(themeDef, iconInfo, iconsSpecifier) {
|
|
|
1453
1654
|
* ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`
|
|
1454
1655
|
* Import the CSS file alongside this module:
|
|
1455
1656
|
*
|
|
1456
|
-
* import { ${
|
|
1457
|
-
* import './${
|
|
1657
|
+
* import { ${themeBinding} } from './${artifactBaseName}';
|
|
1658
|
+
* import './${artifactBaseName}.css';
|
|
1458
1659
|
*/
|
|
1459
|
-
export const ${
|
|
1660
|
+
export const ${themeBinding} = {
|
|
1460
1661
|
name: '${themeDef.name}',
|
|
1461
1662
|
__built: true,
|
|
1462
1663
|
tokens: ${tokensStr},
|
|
1463
|
-
${inheritableFields}${iconsField}
|
|
1664
|
+
${inheritableFields}${iconsField}${indicatorsField}
|
|
1464
1665
|
};
|
|
1465
1666
|
${iconReExport}`;
|
|
1466
1667
|
}
|
|
@@ -1470,14 +1671,23 @@ ${iconReExport}`;
|
|
|
1470
1671
|
* @param {any} themeDef
|
|
1471
1672
|
* @param {{exportName: string, importPath: string} | null} iconInfo
|
|
1472
1673
|
* @param {string | null} variantsFileName
|
|
1674
|
+
* @param {{themeBinding?: string, includeIconExport?: boolean, includeThemeImport?: boolean}} [typeOptions]
|
|
1473
1675
|
* @returns {string}
|
|
1474
1676
|
*/
|
|
1475
|
-
function generateBuiltTypes(
|
|
1476
|
-
|
|
1477
|
-
|
|
1677
|
+
function generateBuiltTypes(
|
|
1678
|
+
themeDef,
|
|
1679
|
+
iconInfo,
|
|
1680
|
+
variantsFileName,
|
|
1681
|
+
typeOptions = {},
|
|
1682
|
+
) {
|
|
1683
|
+
const themeBinding =
|
|
1684
|
+
typeOptions.themeBinding ?? `${toIdentifier(themeDef.name)}Theme`;
|
|
1685
|
+
const iconType =
|
|
1686
|
+
iconInfo && (typeOptions.includeIconExport ?? true)
|
|
1687
|
+
? `import type { IconRegistry } from '@astryxdesign/core/Icon';
|
|
1478
1688
|
export declare const ${iconInfo.exportName}: IconRegistry;
|
|
1479
1689
|
`
|
|
1480
|
-
|
|
1690
|
+
: '';
|
|
1481
1691
|
// Pull in the generated custom-variant augmentations so that importing the
|
|
1482
1692
|
// theme's types also loads the module augmentations (otherwise the
|
|
1483
1693
|
// `.variants.d.ts` is emitted but never referenced, and the custom variants
|
|
@@ -1486,9 +1696,11 @@ export declare const ${iconInfo.exportName}: IconRegistry;
|
|
|
1486
1696
|
? `/// <reference path="./${variantsFileName}" />
|
|
1487
1697
|
`
|
|
1488
1698
|
: '';
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1699
|
+
const themeImport =
|
|
1700
|
+
(typeOptions.includeThemeImport ?? true)
|
|
1701
|
+
? `import type { DefinedTheme } from '@astryxdesign/core/theme';\n`
|
|
1702
|
+
: '';
|
|
1703
|
+
return `${variantsRef}${themeImport}${iconType}export declare const ${themeBinding}: DefinedTheme;\n`;
|
|
1492
1704
|
}
|
|
1493
1705
|
|
|
1494
1706
|
// =============================================================================
|
|
@@ -1832,15 +2044,15 @@ function validateHeadingTypeAugmentationSupport(themeDef) {
|
|
|
1832
2044
|
* `logger` (silent by default).
|
|
1833
2045
|
*
|
|
1834
2046
|
* @param {string} file - Theme file path, resolved against `cwd`.
|
|
1835
|
-
* @param {{out?: string, check?: boolean, iconsSpecifier?: string}} [options] -
|
|
2047
|
+
* @param {{out?: string, check?: boolean, iconsSpecifier?: string, __prepareFamily?: boolean, __familyLoader?: any, __familyInterception?: any}} [options] -
|
|
1836
2048
|
* `out` overrides the output CSS path; `check` compares against on-disk outputs
|
|
1837
2049
|
* instead of writing. `iconsSpecifier` overrides the icon registry import
|
|
1838
2050
|
* specifier in the generated module (e.g. `./icons.mjs`); when omitted, the
|
|
1839
2051
|
* specifier scraped from the theme source is emitted unchanged.
|
|
1840
2052
|
* @param {{cwd?: string}} [ctx]
|
|
1841
|
-
* @returns {Promise<
|
|
2053
|
+
* @returns {Promise<any>}
|
|
1842
2054
|
*/
|
|
1843
|
-
|
|
2055
|
+
async function themeBuildInternal(
|
|
1844
2056
|
file,
|
|
1845
2057
|
options = {},
|
|
1846
2058
|
{cwd = process.cwd()} = {},
|
|
@@ -1857,21 +2069,26 @@ export async function themeBuild(
|
|
|
1857
2069
|
|
|
1858
2070
|
logger.log(`\nBuilding theme from ${path.relative(cwd, filePath)}...`);
|
|
1859
2071
|
|
|
1860
|
-
//
|
|
1861
|
-
//
|
|
1862
|
-
//
|
|
1863
|
-
//
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
2072
|
+
// Standalone builds only need interception when an older Core could erase
|
|
2073
|
+
// adaptations. Family preparation always supplies the same recorder as its
|
|
2074
|
+
// shared loader so exact authored parent identity stays CLI-private instead
|
|
2075
|
+
// of becoming a public DefinedTheme field.
|
|
2076
|
+
const interception =
|
|
2077
|
+
options.__familyInterception ??
|
|
2078
|
+
(_generateAdaptationCSS
|
|
2079
|
+
? undefined
|
|
2080
|
+
: interceptCore(_coreThemeModule, _coreRootModule));
|
|
1868
2081
|
|
|
1869
2082
|
// Extract theme definition
|
|
1870
2083
|
let themeDef;
|
|
1871
2084
|
/** Paths through the load that interception could not fully observe. */
|
|
1872
2085
|
let loadDegradation;
|
|
1873
2086
|
try {
|
|
1874
|
-
const loaded = await extractThemeDefinition(
|
|
2087
|
+
const loaded = await extractThemeDefinition(
|
|
2088
|
+
filePath,
|
|
2089
|
+
interception,
|
|
2090
|
+
options.__familyLoader,
|
|
2091
|
+
);
|
|
1875
2092
|
themeDef = loaded.theme;
|
|
1876
2093
|
loadDegradation = loaded.degraded;
|
|
1877
2094
|
} catch (e) {
|
|
@@ -1883,6 +2100,16 @@ export async function themeBuild(
|
|
|
1883
2100
|
// reaches anything that reads or writes it. (Symbol keys are invisible to
|
|
1884
2101
|
// JSON.stringify and Object.keys, so it could not reach output regardless.)
|
|
1885
2102
|
// Both reads happen BEFORE the strip, which is what removes the evidence.
|
|
2103
|
+
const ancestryObserved =
|
|
2104
|
+
!options.__prepareFamily ||
|
|
2105
|
+
!interception ||
|
|
2106
|
+
interception.observed(themeDef) ||
|
|
2107
|
+
Object.hasOwn(themeDef, 'extends');
|
|
2108
|
+
if (options.__prepareFamily && interception) interception.retain(themeDef);
|
|
2109
|
+
const sourceParent =
|
|
2110
|
+
options.__prepareFamily && interception
|
|
2111
|
+
? interception.parentOf(themeDef)
|
|
2112
|
+
: undefined;
|
|
1886
2113
|
const adaptationLineage = interception
|
|
1887
2114
|
? interception.lineageOf(themeDef)
|
|
1888
2115
|
: undefined;
|
|
@@ -1895,6 +2122,13 @@ export async function themeBuild(
|
|
|
1895
2122
|
const unobservedLineage =
|
|
1896
2123
|
interception && hasCoverageGap ? interception.unobservedIn(themeDef) : [];
|
|
1897
2124
|
if (interception) interception.strip(themeDef);
|
|
2125
|
+
if (!ancestryObserved) {
|
|
2126
|
+
throw new AstryxError(
|
|
2127
|
+
`Theme "${themeDef.name ?? path.basename(filePath)}" exact family ancestry could not be observed during CLI loading.`,
|
|
2128
|
+
undefined,
|
|
2129
|
+
ERROR_CODES.ERR_THEME_INVALID,
|
|
2130
|
+
);
|
|
2131
|
+
}
|
|
1898
2132
|
|
|
1899
2133
|
if (!themeDef.name) {
|
|
1900
2134
|
throw new AstryxError(
|
|
@@ -1988,6 +2222,7 @@ export async function themeBuild(
|
|
|
1988
2222
|
|
|
1989
2223
|
let css;
|
|
1990
2224
|
let resolvedTheme;
|
|
2225
|
+
let cssPlan;
|
|
1991
2226
|
{
|
|
1992
2227
|
// jiti returns an already-resolved theme; a plain object literal (or the
|
|
1993
2228
|
// legacy eval path) returns raw defineTheme input, which still has to go
|
|
@@ -2131,8 +2366,9 @@ export async function themeBuild(
|
|
|
2131
2366
|
}
|
|
2132
2367
|
// Media-surface rules come last so onDark/onLight win over matching
|
|
2133
2368
|
// adaptations on the same resolved leaf.
|
|
2369
|
+
let onMediaCss = '';
|
|
2134
2370
|
if (_generateOnMediaCSS) {
|
|
2135
|
-
|
|
2371
|
+
onMediaCss = _generateOnMediaCSS(resolvedTheme);
|
|
2136
2372
|
if (onMediaCss) {
|
|
2137
2373
|
cssParts.push(`@layer astryx-theme {\n${onMediaCss}\n}`);
|
|
2138
2374
|
}
|
|
@@ -2161,6 +2397,15 @@ export async function themeBuild(
|
|
|
2161
2397
|
`@layer astryx-base {\n${baseCss}\n}`,
|
|
2162
2398
|
);
|
|
2163
2399
|
}
|
|
2400
|
+
cssPlan = {
|
|
2401
|
+
base: baseCss,
|
|
2402
|
+
prose,
|
|
2403
|
+
component,
|
|
2404
|
+
adaptation: adaptationCss.component,
|
|
2405
|
+
adaptationProse: adaptationCss.prose,
|
|
2406
|
+
onMedia: onMediaCss,
|
|
2407
|
+
colorScheme: colorSchemeDecl.trimEnd(),
|
|
2408
|
+
};
|
|
2164
2409
|
css = cssParts.join('\n\n') + '\n';
|
|
2165
2410
|
}
|
|
2166
2411
|
|
|
@@ -2204,7 +2449,14 @@ export async function themeBuild(
|
|
|
2204
2449
|
const jsPath = path.join(outDir, `${baseName}.js`);
|
|
2205
2450
|
const dtsPath = path.join(outDir, `${baseName}.d.ts`);
|
|
2206
2451
|
|
|
2207
|
-
const iconInfo =
|
|
2452
|
+
const iconInfo = extractRegistryInfo(
|
|
2453
|
+
filePath,
|
|
2454
|
+
'icons',
|
|
2455
|
+
options.__prepareFamily,
|
|
2456
|
+
);
|
|
2457
|
+
const indicatorInfo = options.__prepareFamily
|
|
2458
|
+
? extractRegistryInfo(filePath, 'indicators', true)
|
|
2459
|
+
: null;
|
|
2208
2460
|
|
|
2209
2461
|
// Type augmentation .d.ts if theme has custom prop values. Computed
|
|
2210
2462
|
// before the main .d.ts so the latter can reference it (see below).
|
|
@@ -2237,10 +2489,34 @@ export async function themeBuild(
|
|
|
2237
2489
|
generatedHeader(sourceRelative, 'ts', buildCommand, versions) +
|
|
2238
2490
|
generateBuiltTypes(themeDef, iconInfo, variantsFileName);
|
|
2239
2491
|
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2492
|
+
const unloadedFonts = [
|
|
2493
|
+
...new Set([
|
|
2494
|
+
...collectUnloadedFonts(resolvedTheme),
|
|
2495
|
+
...adaptationRuleValues(resolvedTheme).flatMap(
|
|
2496
|
+
(/** @type {any} */ value) => collectUnloadedFonts(value),
|
|
2497
|
+
),
|
|
2498
|
+
]),
|
|
2499
|
+
];
|
|
2500
|
+
|
|
2501
|
+
if (options.__prepareFamily) {
|
|
2502
|
+
return {
|
|
2503
|
+
filePath,
|
|
2504
|
+
sourceRelative: sourceRelative.split(path.sep).join('/'),
|
|
2505
|
+
theme: displayTheme,
|
|
2506
|
+
sourceTheme: themeDef,
|
|
2507
|
+
sourceParent,
|
|
2508
|
+
iconInfo,
|
|
2509
|
+
indicatorInfo,
|
|
2510
|
+
variantDecl,
|
|
2511
|
+
css: cssPlan,
|
|
2512
|
+
versions,
|
|
2513
|
+
tokenCount,
|
|
2514
|
+
componentCount,
|
|
2515
|
+
warnings: warningMessages,
|
|
2516
|
+
unloadedFonts,
|
|
2517
|
+
};
|
|
2518
|
+
}
|
|
2519
|
+
|
|
2244
2520
|
const writes = [
|
|
2245
2521
|
{dest: outPath, content: cssContent},
|
|
2246
2522
|
{dest: jsPath, content: jsContent},
|
|
@@ -2255,19 +2531,7 @@ export async function themeBuild(
|
|
|
2255
2531
|
// volatile @generated `Command:` line is ignored. Returns a
|
|
2256
2532
|
// receipt listing stale/missing outputs so callers (CI) can fail on drift.
|
|
2257
2533
|
if (options.check) {
|
|
2258
|
-
|
|
2259
|
-
const stale = [];
|
|
2260
|
-
for (const w of writes) {
|
|
2261
|
-
const rel = path.relative(cwd, w.dest);
|
|
2262
|
-
if (!fs.existsSync(w.dest)) {
|
|
2263
|
-
stale.push({path: rel, reason: 'missing'});
|
|
2264
|
-
continue;
|
|
2265
|
-
}
|
|
2266
|
-
const onDisk = fs.readFileSync(w.dest, 'utf8');
|
|
2267
|
-
if (normalizeForCompare(onDisk) !== normalizeForCompare(w.content)) {
|
|
2268
|
-
stale.push({path: rel, reason: 'outdated'});
|
|
2269
|
-
}
|
|
2270
|
-
}
|
|
2534
|
+
const stale = staleBuildOutputs(writes, cwd);
|
|
2271
2535
|
const upToDate = stale.length === 0;
|
|
2272
2536
|
if (upToDate) {
|
|
2273
2537
|
logger.log(`\n✓ Theme outputs are up to date with ${sourceRelative}.`);
|
|
@@ -2293,30 +2557,7 @@ export async function themeBuild(
|
|
|
2293
2557
|
};
|
|
2294
2558
|
}
|
|
2295
2559
|
|
|
2296
|
-
|
|
2297
|
-
/** @type {Array<{tmp: string, dest: string}>} */
|
|
2298
|
-
const staged = [];
|
|
2299
|
-
try {
|
|
2300
|
-
for (const w of writes) {
|
|
2301
|
-
const tmp = `${w.dest}.${process.pid}.tmp`;
|
|
2302
|
-
fs.writeFileSync(tmp, w.content);
|
|
2303
|
-
staged.push({tmp, dest: w.dest});
|
|
2304
|
-
}
|
|
2305
|
-
for (const s of staged) {
|
|
2306
|
-
fs.renameSync(s.tmp, s.dest);
|
|
2307
|
-
}
|
|
2308
|
-
} catch (err) {
|
|
2309
|
-
// Roll back any temp files we managed to create.
|
|
2310
|
-
for (const s of staged) {
|
|
2311
|
-
try {
|
|
2312
|
-
fs.rmSync(s.tmp, {force: true});
|
|
2313
|
-
} catch {
|
|
2314
|
-
/* best-effort */
|
|
2315
|
-
}
|
|
2316
|
-
}
|
|
2317
|
-
const msg = `Failed to write theme outputs: ${/** @type {Error} */ (err).message}`;
|
|
2318
|
-
throw new AstryxError(msg, undefined, ERROR_CODES.ERR_WRITE_FAILED);
|
|
2319
|
-
}
|
|
2560
|
+
writeBuildOutputs(writes);
|
|
2320
2561
|
|
|
2321
2562
|
logger.log(`\n✓ ${path.relative(cwd, outPath)}`);
|
|
2322
2563
|
logger.log(
|
|
@@ -2369,14 +2610,6 @@ Or with a <link> tag:
|
|
|
2369
2610
|
// permanently in violation of its own "compiles with no warnings" guard).
|
|
2370
2611
|
// Adaptation rules are resolved theme writes in their own right, so a family
|
|
2371
2612
|
// named only inside one needs the same notice as one named at the root.
|
|
2372
|
-
const unloadedFonts = [
|
|
2373
|
-
...new Set([
|
|
2374
|
-
...collectUnloadedFonts(resolvedTheme),
|
|
2375
|
-
...adaptationRuleValues(resolvedTheme).flatMap(
|
|
2376
|
-
(/** @type {any} */ value) => collectUnloadedFonts(value),
|
|
2377
|
-
),
|
|
2378
|
-
]),
|
|
2379
|
-
];
|
|
2380
2613
|
for (const family of unloadedFonts) {
|
|
2381
2614
|
const msg = `Font "${family}" is named by this theme but not loaded — add a <link> or @font-face in your app (recipe: astryx docs typography)`;
|
|
2382
2615
|
noticeMessages.push(msg);
|
|
@@ -2406,3 +2639,330 @@ Or with a <link> tag:
|
|
|
2406
2639
|
},
|
|
2407
2640
|
};
|
|
2408
2641
|
}
|
|
2642
|
+
|
|
2643
|
+
/** @param {string} file @param {{out?: string, check?: boolean, iconsSpecifier?: string}} [options] @param {{cwd?: string}} [ctx] @returns {Promise<import('../theme.type.mjs').ThemeBuildResponse | import('../theme.type.mjs').ThemeBuildCheckResponse | null>} */
|
|
2644
|
+
export async function themeBuild(file, options = {}, ctx = {}) {
|
|
2645
|
+
return /** @type {any} */ (themeBuildInternal(file, options, ctx));
|
|
2646
|
+
}
|
|
2647
|
+
/** @param {string} name */
|
|
2648
|
+
// prettier-ignore
|
|
2649
|
+
function familyThemeBinding(name) {
|
|
2650
|
+
const words = name.split(/[^A-Za-z0-9_$]+/).filter(Boolean);
|
|
2651
|
+
let identifier = words.map((word, index) => index === 0 ? word : word.charAt(0).toUpperCase() + word.slice(1)).join('');
|
|
2652
|
+
if (!/^[A-Za-z_$]/.test(identifier)) identifier = `_${identifier}`;
|
|
2653
|
+
return `${identifier || '_'}Theme`;
|
|
2654
|
+
}
|
|
2655
|
+
/** @param {any[]} members */
|
|
2656
|
+
// prettier-ignore
|
|
2657
|
+
function allocateFamilyBindings(members) {
|
|
2658
|
+
const used = new Map();
|
|
2659
|
+
return new Map(members.map(member => { const base = familyThemeBinding(member.theme.name), count = used.get(base) ?? 0; used.set(base, count + 1); return [member.theme.name, count === 0 ? base : `${base}${count + 1}`]; }));
|
|
2660
|
+
}
|
|
2661
|
+
/** Rebase a scraped relative registry import to the aggregate module. @param {any} info @param {string} filePath @param {string} outDir @param {string | undefined} override */
|
|
2662
|
+
// prettier-ignore
|
|
2663
|
+
function familyRegistryInput(info, filePath, outDir, override) {
|
|
2664
|
+
if (!info || override !== undefined) return {info, specifier: override};
|
|
2665
|
+
const source = info.importPath;
|
|
2666
|
+
if (!source.startsWith('./') && !source.startsWith('../')) return {info, specifier: undefined};
|
|
2667
|
+
const absolute = path.resolve(path.dirname(filePath), source);
|
|
2668
|
+
let specifier = path.relative(outDir, absolute).split(path.sep).join('/');
|
|
2669
|
+
if (!specifier.startsWith('./') && !specifier.startsWith('../')) specifier = `./${specifier}`;
|
|
2670
|
+
return {info, specifier};
|
|
2671
|
+
}
|
|
2672
|
+
/** Dependency-first load plan including local barrels between selected files. @param {string[]} files @param {string} cwd */
|
|
2673
|
+
// prettier-ignore
|
|
2674
|
+
function planFamilySources(files, cwd) {
|
|
2675
|
+
/** @type {Array<{file: string, filePath: string}>} */ const entries = files.map(file => ({file, filePath: path.resolve(cwd, file)}));
|
|
2676
|
+
/** @param {string} value */ const canonical = value => fs.existsSync(value) ? fs.realpathSync(value) : path.resolve(value);
|
|
2677
|
+
/** @type {Map<string, {file: string, filePath: string}>} */ const selected = new Map(entries.map(entry => [canonical(entry.filePath), entry]));
|
|
2678
|
+
if (selected.size !== entries.length) return entries.map(entry => ({...entry, selected: true}));
|
|
2679
|
+
/** @type {Map<string, Set<string>>} */ const reachableMemo = new Map(), dependencies = new Map();
|
|
2680
|
+
/** @param {string} filePath @param {Set<string>} [visiting] @returns {Set<string>} */
|
|
2681
|
+
const reachableSelected = (filePath, visiting = new Set()) => {
|
|
2682
|
+
const key = canonical(filePath), cached = reachableMemo.get(key); if (cached) return cached;
|
|
2683
|
+
if (visiting.has(key) || !fs.existsSync(key)) return new Set();
|
|
2684
|
+
visiting.add(key); /** @type {Set<string>} */ const found = new Set(), direct = new Set(); let ast;
|
|
2685
|
+
try { ast = parse(fs.readFileSync(key, 'utf8'), {sourceType: 'unambiguous', plugins: ['typescript', 'jsx', 'decorators-legacy', 'importAttributes']}); }
|
|
2686
|
+
catch { visiting.delete(key); reachableMemo.set(key, found); return found; }
|
|
2687
|
+
for (const node of /** @type {any[]} */ (ast.program.body)) {
|
|
2688
|
+
const specifier = node.importKind !== 'type' ? node.source?.value : null; if (typeof specifier !== 'string' || (!specifier.startsWith('.') && !path.isAbsolute(specifier))) continue;
|
|
2689
|
+
let dependency; try { dependency = canonical(createJiti(key, {extensions: THEME_MODULE_EXTENSIONS}).resolve(specifier)); } catch { continue; }
|
|
2690
|
+
if (!dependency.split(path.sep).includes('node_modules') && /\.[cm]?[jt]sx?$/.test(dependency)) direct.add(dependency);
|
|
2691
|
+
if (selected.has(dependency)) found.add(dependency); else for (const nested of reachableSelected(dependency, visiting)) found.add(nested);
|
|
2692
|
+
}
|
|
2693
|
+
visiting.delete(key); dependencies.set(key, direct); reachableMemo.set(key, found); return found;
|
|
2694
|
+
};
|
|
2695
|
+
for (const entry of entries) reachableSelected(entry.filePath);
|
|
2696
|
+
/** @type {Array<{file: string, filePath: string, selected: boolean}>} */ const plan = []; /** @type {Set<string>} */ const marks = new Set();
|
|
2697
|
+
/** @param {string} key */ const visit = key => { if (marks.has(key)) return; marks.add(key); for (const dependency of dependencies.get(key) ?? []) if (selected.has(dependency) || reachableSelected(dependency).size > 0) visit(dependency); const entry = selected.get(key); plan.push(entry ? {...entry, selected: true} : {file: key, filePath: key, selected: false}); };
|
|
2698
|
+
for (const entry of entries) visit(canonical(entry.filePath)); return plan;
|
|
2699
|
+
}
|
|
2700
|
+
|
|
2701
|
+
/** Preload an intermediary module into the shared family cache. @param {string} filePath @param {any} loader @param {import('./core-interception.mjs').CoreInterception} interception */
|
|
2702
|
+
// prettier-ignore
|
|
2703
|
+
async function preloadFamilySource(filePath, loader, interception) {
|
|
2704
|
+
const patch = interception.patchCommonJs(filePath);
|
|
2705
|
+
try { try { loader(filePath); } catch (error) { if (!isSyncLoaderLimitation(error)) throw error; await loader.evalModule(fs.readFileSync(filePath, 'utf8'), {id: filePath, filename: filePath, ext: path.extname(filePath), cache: loader.cache, async: true, forceTranspile: true}); } }
|
|
2706
|
+
finally { patch.undo(); }
|
|
2707
|
+
}
|
|
2708
|
+
|
|
2709
|
+
/** @param {string[]} files @param {{familyKey: string, check?: boolean, iconsSpecifier?: string}} options @param {{cwd?: string}} [ctx] */
|
|
2710
|
+
export async function themeBuildFamily(
|
|
2711
|
+
files,
|
|
2712
|
+
options,
|
|
2713
|
+
{cwd = process.cwd()} = {},
|
|
2714
|
+
) {
|
|
2715
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(options?.familyKey ?? '')) {
|
|
2716
|
+
throw new AstryxError(
|
|
2717
|
+
'Family key must be an exact lower-kebab filename stem (for example, ocean-family).',
|
|
2718
|
+
undefined,
|
|
2719
|
+
ERROR_CODES.ERR_THEME_INVALID,
|
|
2720
|
+
);
|
|
2721
|
+
}
|
|
2722
|
+
try {
|
|
2723
|
+
sanitizeName(options.familyKey, {label: 'family key'});
|
|
2724
|
+
} catch (error) {
|
|
2725
|
+
const message =
|
|
2726
|
+
error instanceof Error ? error.message : 'Invalid family key.';
|
|
2727
|
+
throw new AstryxError(message, undefined, ERROR_CODES.ERR_THEME_INVALID);
|
|
2728
|
+
}
|
|
2729
|
+
const familyInterception = interceptCore(_coreThemeModule, _coreRootModule);
|
|
2730
|
+
// prettier-ignore
|
|
2731
|
+
const familyLoader = createJiti(import.meta.url, {moduleCache: true, interopDefault: false, jsx: true, extensions: THEME_MODULE_EXTENSIONS, virtualModules: familyInterception.modules});
|
|
2732
|
+
/** @type {any[]} */
|
|
2733
|
+
const prepared = [];
|
|
2734
|
+
for (const source of planFamilySources(files, cwd)) {
|
|
2735
|
+
if (!source.selected) {
|
|
2736
|
+
await preloadFamilySource(
|
|
2737
|
+
source.filePath,
|
|
2738
|
+
familyLoader,
|
|
2739
|
+
familyInterception,
|
|
2740
|
+
);
|
|
2741
|
+
continue;
|
|
2742
|
+
}
|
|
2743
|
+
const file = source.file;
|
|
2744
|
+
// prettier-ignore
|
|
2745
|
+
const member = await themeBuildInternal(file, {iconsSpecifier: options.iconsSpecifier, __prepareFamily: true, __familyLoader: familyLoader, __familyInterception: familyInterception}, {cwd});
|
|
2746
|
+
if (!member || member.type) {
|
|
2747
|
+
throw new AstryxError(
|
|
2748
|
+
`Theme family member "${file}" did not produce a complete build plan.`,
|
|
2749
|
+
undefined,
|
|
2750
|
+
ERROR_CODES.ERR_THEME_INVALID,
|
|
2751
|
+
);
|
|
2752
|
+
}
|
|
2753
|
+
prepared.push(member);
|
|
2754
|
+
}
|
|
2755
|
+
let members;
|
|
2756
|
+
try {
|
|
2757
|
+
members = resolveThemeFamily(prepared);
|
|
2758
|
+
} catch (error) {
|
|
2759
|
+
const message =
|
|
2760
|
+
error instanceof Error ? error.message : 'Invalid selected theme family.';
|
|
2761
|
+
throw new AstryxError(message, undefined, ERROR_CODES.ERR_THEME_INVALID);
|
|
2762
|
+
}
|
|
2763
|
+
for (const member of members) {
|
|
2764
|
+
for (const [field, info] of [
|
|
2765
|
+
['icons', member.iconInfo],
|
|
2766
|
+
['indicators', member.indicatorInfo],
|
|
2767
|
+
]) {
|
|
2768
|
+
const value = member.theme[field];
|
|
2769
|
+
const inherited = member.sourceParent?.[field];
|
|
2770
|
+
if (
|
|
2771
|
+
value &&
|
|
2772
|
+
Object.keys(value).length > 0 &&
|
|
2773
|
+
value !== inherited &&
|
|
2774
|
+
!info
|
|
2775
|
+
) {
|
|
2776
|
+
throw new AstryxError(
|
|
2777
|
+
`Theme "${member.theme.name}" must supply ${field} through a named import for family output.`,
|
|
2778
|
+
undefined,
|
|
2779
|
+
ERROR_CODES.ERR_THEME_INVALID,
|
|
2780
|
+
);
|
|
2781
|
+
}
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
const baseName = options.familyKey;
|
|
2785
|
+
if (members.some(member => member.theme.name === baseName)) {
|
|
2786
|
+
throw new AstryxError(
|
|
2787
|
+
`Family key "${baseName}" collides with a selected theme's standalone outputs. Choose a distinct filename stem.`,
|
|
2788
|
+
undefined,
|
|
2789
|
+
ERROR_CODES.ERR_THEME_INVALID,
|
|
2790
|
+
);
|
|
2791
|
+
}
|
|
2792
|
+
const root = members[0];
|
|
2793
|
+
const outDir = path.dirname(root.filePath);
|
|
2794
|
+
const outPath = path.join(outDir, `${baseName}.css`);
|
|
2795
|
+
const jsPath = path.join(outDir, `${baseName}.js`);
|
|
2796
|
+
const dtsPath = path.join(outDir, `${baseName}.d.ts`);
|
|
2797
|
+
const sources = new Set(
|
|
2798
|
+
members.flatMap(member =>
|
|
2799
|
+
[path.resolve(member.filePath), fs.realpathSync(member.filePath)].map(
|
|
2800
|
+
value => value.toLowerCase(),
|
|
2801
|
+
),
|
|
2802
|
+
),
|
|
2803
|
+
);
|
|
2804
|
+
const collision = [outPath, jsPath, dtsPath].find(output => {
|
|
2805
|
+
const candidates = [path.resolve(output)];
|
|
2806
|
+
if (fs.existsSync(output)) candidates.push(fs.realpathSync(output));
|
|
2807
|
+
return candidates.some(value => sources.has(value.toLowerCase()));
|
|
2808
|
+
});
|
|
2809
|
+
if (collision) {
|
|
2810
|
+
throw new AstryxError(
|
|
2811
|
+
`Family output ${path.relative(cwd, collision)} collides with a selected source file.`,
|
|
2812
|
+
undefined,
|
|
2813
|
+
ERROR_CODES.ERR_THEME_INVALID,
|
|
2814
|
+
);
|
|
2815
|
+
}
|
|
2816
|
+
const sourceRelative = members
|
|
2817
|
+
.map(member => member.sourceRelative)
|
|
2818
|
+
.join(', ');
|
|
2819
|
+
const buildCommand = `${getCliInvocation()} theme build --family ${members
|
|
2820
|
+
.map(member => member.sourceRelative)
|
|
2821
|
+
.join(' ')} --family-key ${baseName}`;
|
|
2822
|
+
const bindings = allocateFamilyBindings(members);
|
|
2823
|
+
const css = generateFamilyCSS(members);
|
|
2824
|
+
/** @type {Array<{specifier: string, exportName: string}>} */
|
|
2825
|
+
const registryImports = [];
|
|
2826
|
+
const js = members
|
|
2827
|
+
.map(member => {
|
|
2828
|
+
const themeBinding = bindings.get(member.theme.name);
|
|
2829
|
+
const parentBinding = member.parentName
|
|
2830
|
+
? bindings.get(member.parentName)
|
|
2831
|
+
: null;
|
|
2832
|
+
// prettier-ignore
|
|
2833
|
+
const icon = familyRegistryInput(member.iconInfo, member.filePath, outDir, options.iconsSpecifier);
|
|
2834
|
+
// prettier-ignore
|
|
2835
|
+
const indicator = familyRegistryInput(member.indicatorInfo, member.filePath, outDir, undefined);
|
|
2836
|
+
// prettier-ignore
|
|
2837
|
+
for (const registry of [icon, indicator]) if (registry.info) registryImports.push({specifier: registry.specifier ?? registry.info.importPath, exportName: registry.info.exportName});
|
|
2838
|
+
const ownIcons = icon.info ? `${themeBinding}Icons` : null;
|
|
2839
|
+
const inheritedIcons = parentBinding ? `${parentBinding}.icons` : null;
|
|
2840
|
+
const ownIndicators = indicator.info ? `${themeBinding}Indicators` : null;
|
|
2841
|
+
const inheritedIndicators = parentBinding
|
|
2842
|
+
? `${parentBinding}.indicators`
|
|
2843
|
+
: null;
|
|
2844
|
+
/** @param {string | null} own @param {string | null} inherited */
|
|
2845
|
+
const expression = (own, inherited) =>
|
|
2846
|
+
own && inherited
|
|
2847
|
+
? `{...${inherited}, ...${own}}`
|
|
2848
|
+
: (own ?? inherited ?? undefined);
|
|
2849
|
+
const indicatorImport = indicator.info
|
|
2850
|
+
? `import { ${indicator.info.exportName} as ${ownIndicators} } from ${JSON.stringify(indicator.specifier ?? indicator.info.importPath)};\n`
|
|
2851
|
+
: '';
|
|
2852
|
+
return (
|
|
2853
|
+
indicatorImport +
|
|
2854
|
+
generateBuiltModule(member.theme, icon.info, icon.specifier, {
|
|
2855
|
+
themeBinding,
|
|
2856
|
+
iconBinding: ownIcons ?? undefined,
|
|
2857
|
+
iconsExpression: expression(ownIcons, inheritedIcons),
|
|
2858
|
+
indicatorsExpression: expression(ownIndicators, inheritedIndicators),
|
|
2859
|
+
artifactBaseName: baseName,
|
|
2860
|
+
exportIcons: false,
|
|
2861
|
+
})
|
|
2862
|
+
);
|
|
2863
|
+
})
|
|
2864
|
+
.join('\n');
|
|
2865
|
+
await validateRegistryGraphs(registryImports, jsPath);
|
|
2866
|
+
const declarations = members
|
|
2867
|
+
.map((member, index) =>
|
|
2868
|
+
generateBuiltTypes(member.theme, member.iconInfo, null, {
|
|
2869
|
+
themeBinding: bindings.get(member.theme.name),
|
|
2870
|
+
includeIconExport: false,
|
|
2871
|
+
includeThemeImport: index === 0,
|
|
2872
|
+
}),
|
|
2873
|
+
)
|
|
2874
|
+
.join('');
|
|
2875
|
+
const augmentations = [
|
|
2876
|
+
...new Set(members.map(member => member.variantDecl).filter(Boolean)),
|
|
2877
|
+
].join('\n');
|
|
2878
|
+
const writes = [
|
|
2879
|
+
{
|
|
2880
|
+
dest: outPath,
|
|
2881
|
+
content:
|
|
2882
|
+
generatedHeader(sourceRelative, 'css', buildCommand, root.versions) +
|
|
2883
|
+
css,
|
|
2884
|
+
},
|
|
2885
|
+
{
|
|
2886
|
+
dest: jsPath,
|
|
2887
|
+
content:
|
|
2888
|
+
generatedHeader(sourceRelative, 'js', buildCommand, root.versions) + js,
|
|
2889
|
+
},
|
|
2890
|
+
{
|
|
2891
|
+
dest: dtsPath,
|
|
2892
|
+
content:
|
|
2893
|
+
generatedHeader(sourceRelative, 'ts', buildCommand, root.versions) +
|
|
2894
|
+
declarations +
|
|
2895
|
+
(augmentations ? `\n${augmentations}` : ''),
|
|
2896
|
+
},
|
|
2897
|
+
];
|
|
2898
|
+
const outputs = {
|
|
2899
|
+
css: path.relative(cwd, outPath),
|
|
2900
|
+
js: path.relative(cwd, jsPath),
|
|
2901
|
+
dts: path.relative(cwd, dtsPath),
|
|
2902
|
+
};
|
|
2903
|
+
if (options.check) {
|
|
2904
|
+
const stale = staleBuildOutputs(writes, cwd);
|
|
2905
|
+
const upToDate = stale.length === 0;
|
|
2906
|
+
if (upToDate) {
|
|
2907
|
+
logger.log(
|
|
2908
|
+
`\n✓ Theme family outputs are up to date with ${sourceRelative}.`,
|
|
2909
|
+
);
|
|
2910
|
+
} else {
|
|
2911
|
+
logger.error(
|
|
2912
|
+
`\n✗ ${stale.length} theme family output(s) are out of date:`,
|
|
2913
|
+
);
|
|
2914
|
+
for (const entry of stale) {
|
|
2915
|
+
logger.error(
|
|
2916
|
+
` ${entry.reason === 'missing' ? 'missing' : 'stale'}: ${entry.path}`,
|
|
2917
|
+
);
|
|
2918
|
+
}
|
|
2919
|
+
logger.error(`\n Rebuild with: ${buildCommand}`);
|
|
2920
|
+
}
|
|
2921
|
+
return {
|
|
2922
|
+
type: 'theme.build.check',
|
|
2923
|
+
data: {
|
|
2924
|
+
name: root.theme.name,
|
|
2925
|
+
upToDate,
|
|
2926
|
+
stale,
|
|
2927
|
+
checked: writes.map(write => path.relative(cwd, write.dest)),
|
|
2928
|
+
},
|
|
2929
|
+
};
|
|
2930
|
+
}
|
|
2931
|
+
writeBuildOutputs(writes);
|
|
2932
|
+
for (const output of Object.values(outputs)) logger.log(`✓ ${output}`);
|
|
2933
|
+
const themeBindings = members.map(member => bindings.get(member.theme.name));
|
|
2934
|
+
const relOutDir = path.relative(cwd, outDir) || '.';
|
|
2935
|
+
const jsImport = importSpecifier(relOutDir, baseName);
|
|
2936
|
+
const cssImport = `${jsImport}.css`;
|
|
2937
|
+
logger.log(`
|
|
2938
|
+
Load the family CSS once, then select any member by theme identity:
|
|
2939
|
+
import { ${themeBindings.join(', ')} } from '${jsImport}';
|
|
2940
|
+
import '${cssImport}';
|
|
2941
|
+
Or load the same stylesheet natively:
|
|
2942
|
+
<link rel="stylesheet" href="${cssImport}" />
|
|
2943
|
+
`);
|
|
2944
|
+
const warnings = [...new Set(members.flatMap(member => member.warnings))];
|
|
2945
|
+
const unloadedFonts = [
|
|
2946
|
+
...new Set(members.flatMap(member => member.unloadedFonts)),
|
|
2947
|
+
];
|
|
2948
|
+
const notices = unloadedFonts.map(
|
|
2949
|
+
family =>
|
|
2950
|
+
`Font "${family}" is named by this theme family but not loaded — add a <link> or @font-face in your app (recipe: astryx docs typography)`,
|
|
2951
|
+
);
|
|
2952
|
+
for (const notice of notices) logger.log(` note: ${notice}`);
|
|
2953
|
+
return {
|
|
2954
|
+
type: 'theme.build',
|
|
2955
|
+
data: {
|
|
2956
|
+
name: root.theme.name,
|
|
2957
|
+
tokenCount: members.reduce((sum, member) => sum + member.tokenCount, 0),
|
|
2958
|
+
componentCount: members.reduce(
|
|
2959
|
+
(sum, member) => sum + member.componentCount,
|
|
2960
|
+
0,
|
|
2961
|
+
),
|
|
2962
|
+
sizeKB: parseFloat((Buffer.byteLength(css) / 1024).toFixed(1)),
|
|
2963
|
+
outputs,
|
|
2964
|
+
warnings,
|
|
2965
|
+
notices,
|
|
2966
|
+
},
|
|
2967
|
+
};
|
|
2968
|
+
}
|