@aliens-syndicate/cli 0.1.2 → 0.1.4

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.
Files changed (39) hide show
  1. package/README.es-ES.md +53 -10
  2. package/README.md +53 -10
  3. package/README.pt-BR.md +53 -10
  4. package/README.zh-CN.md +53 -10
  5. package/package.json +6 -1
  6. package/tools/build.mjs +372 -36
  7. package/tools/cache.mjs +41 -0
  8. package/tools/cli-shared.mjs +237 -0
  9. package/tools/cli.mjs +145 -48
  10. package/tools/create.mjs +207 -78
  11. package/tools/doctor.mjs +139 -0
  12. package/tools/generate.mjs +175 -0
  13. package/tools/icon-docs.mjs +132 -0
  14. package/tools/project-layout.mjs +3 -3
  15. package/tools/runtime.mjs +216 -8
  16. package/tools/serve.mjs +152 -0
  17. package/tools/starter/ai/agents/codingbot.agent +5 -0
  18. package/tools/starter/ai/rules/architecture.rule +12 -0
  19. package/tools/starter/ai/skills/create-element.skill +7 -0
  20. package/tools/starter/app/elements/molecules/kit-card-link/kit-card-link.markup +0 -2
  21. package/tools/starter/app/pages/kit-overview/kit-overview.markup +6 -6
  22. package/tools/starter/app/pages/style-guide/style-guide.style +57 -57
  23. package/tools/starter/styles/components/alerts.style +6 -5
  24. package/tools/starter/styles/components/badges.style +6 -5
  25. package/tools/starter/styles/components/borders.style +2 -1
  26. package/tools/starter/styles/components/buttons.style +14 -13
  27. package/tools/starter/styles/components/cards.style +1 -1
  28. package/tools/starter/styles/components/feedback.style +3 -2
  29. package/tools/starter/styles/components/forms.style +5 -4
  30. package/tools/starter/styles/components/tables.style +4 -3
  31. package/tools/starter/styles/components/typography.style +6 -5
  32. package/tools/starter/styles/generic/ui-base.style +1 -1
  33. package/tools/starter/styles/objects/ui-layout.style +1 -1
  34. package/tools/style-docs.mjs +274 -0
  35. package/tools/update.mjs +110 -0
  36. package/tools/vscode-space/package.json +5 -8
  37. package/tools/vscode-space/space.tmLanguage.json +1 -1
  38. package/tools/vscode-space/syntax.cjs +103 -62
  39. package/tools/watch.mjs +48 -0
package/tools/build.mjs CHANGED
@@ -1,10 +1,11 @@
1
1
  import { cp, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
2
2
  import { basename, dirname, extname, join, relative, resolve } from 'node:path';
3
- import { stripTypeScriptTypes } from 'node:module';
3
+ import { createRequire, stripTypeScriptTypes } from 'node:module';
4
+ import { pathToFileURL } from 'node:url';
4
5
  import { exampleMarker, namedKinds, sharedDirectory } from './project-layout.mjs';
5
6
  import spaceSyntax from './vscode-space/syntax.cjs';
6
7
 
7
- const { analyzeSpace, isSpaceComment } = spaceSyntax;
8
+ const { analyzeSpace, htmlTags, isSpaceComment, roles: highlightRoleOf } = spaceSyntax;
8
9
 
9
10
  const workspace = resolve(import.meta.dirname, '..');
10
11
  const rootConfig = await readFile(join(workspace, '.config'), 'utf8').catch(error => {
@@ -12,7 +13,10 @@ const rootConfig = await readFile(join(workspace, '.config'), 'utf8').catch(erro
12
13
  throw error;
13
14
  });
14
15
  const root = rootConfig === undefined ? join(workspace, 'project') : workspace;
15
- const read = file => readFile(join(root, file), 'utf8');
16
+ // Files of an elements package keep the package name as their path (like @aliens-syndicate/elements/ui-button/
17
+ // ui-button.markup), so errors and ai/.map name them; packageFiles maps that path to the file on disk.
18
+ const packageFiles = new Map();
19
+ const read = file => readFile(packageFiles.get(file) ?? join(root, file), 'utf8');
16
20
  const indentation = ' ';
17
21
  async function filesIn(directory, { optional = false } = {}) {
18
22
  let entries;
@@ -110,6 +114,93 @@ const settings = name => Object.fromEntries(config.find(node => node.value === n
110
114
  }) ?? []);
111
115
  const { entry, assets: assetDirectory, shared: configuredShared, styles, agent: map, environment } = settings('files');
112
116
  const { default: defaultLocale, detection, directory: languageDirectory } = settings('language');
117
+ const { from: iconPackage, style: configuredIconStyle } = settings('icons');
118
+ const { from: stylePackage } = settings('style');
119
+ const { from: elementPackage } = settings('elements');
120
+ // Extensions are separate packages that the project installs and declares in .config under <section>: from:, or a
121
+ // local folder written as ./path. Icons (usually @aliens-syndicate/icons) let markup draw the icon tag inline (see
122
+ // renderIcon); style (usually @aliens-syndicate/style) lets .style list utilities besides plain CSS declarations;
123
+ // elements (usually @aliens-syndicate/elements) adds ready-made Elements that any markup can render.
124
+ async function loadExtension(section, name) {
125
+ let entry;
126
+ try {
127
+ entry = /^\.{1,2}\//.test(name) ? join(workspace, name, 'index.mjs') : createRequire(join(workspace, 'package.json')).resolve(name);
128
+ } catch {
129
+ throw new Error(`.config: ${section}: from: ${name} is not installed. Run npm install ${name}.`);
130
+ }
131
+ return import(pathToFileURL(entry).href);
132
+ }
133
+ const iconModule = iconPackage ? await loadExtension('icons', iconPackage) : null;
134
+ const styleModule = stylePackage ? await loadExtension('style', stylePackage) : null;
135
+ if (styleModule && typeof styleModule.resolveUtility !== 'function') throw new Error(`.config: style: from: ${stylePackage} is not an Aliens style extension.`);
136
+ const elementModule = elementPackage ? await loadExtension('elements', elementPackage) : null;
137
+ if (elementModule && typeof elementModule.elementsDirectory !== 'string') throw new Error(`.config: elements: from: ${elementPackage} is not an Aliens elements package.`);
138
+ const noStyle = (where, what) => new Error(`${where}: ${what} need the style extension. Write CSS as "property: value", or run ` +
139
+ 'npm install @aliens-syndicate/style and declare it in .config:\nstyle:\n from: @aliens-syndicate/style');
140
+ // Without the style extension, .style reads plain CSS declarations only.
141
+ const resolveUtility = (token, options) => styleModule ? styleModule.resolveUtility(token, options) : { error: 'no style extension' };
142
+ const iconRenderer = iconModule?.createIconRenderer();
143
+ const iconCatalog = iconModule ? await iconModule.readCatalog() : null;
144
+ const iconStyle = iconRenderer ? configuredIconStyle ?? 'stroke-rounded' : null;
145
+ if (iconRenderer && !iconRenderer.styles.includes(iconStyle)) throw new Error(`.config: icons: style: accepts ${iconRenderer.styles.join(', ')}.`);
146
+ const noIcons = where => new Error(`${where}: icons need a package. Run npm install @aliens-syndicate/icons and declare it in .config:\n` +
147
+ 'icons:\n from: @aliens-syndicate/icons\n style: stroke-rounded');
148
+ // The icon tag: "icon <name> [style] [size-<n>] [color] [second color] [disabled] [hidden]", with id, variant and label
149
+ // as its only attributes. The first word names the icon and the others may come in any order: one of the ten styles
150
+ // (the one in .config by default), a size utility, up to two colors (the icon and the second tone of bulk, duotone and
151
+ // twotone), disabled and hidden. Without label the icon is decorative and hidden from assistive technology.
152
+ const iconTag = /^icon(?=\s|$)/;
153
+ function iconParts(node) {
154
+ const rest = node.value.slice('icon'.length);
155
+ const attributes = [];
156
+ const words = [];
157
+ const part = /\s+(?:([\w:-]+)=("[^"]*"|\{[^}]*\})|(\{[^}]*\})|([^\s"{}=]+))/y;
158
+ for (let offset = 0; offset < rest.length;) {
159
+ part.lastIndex = offset;
160
+ const match = part.exec(rest);
161
+ if (!match) throw new Error(`${node.location}: invalid icon near "${rest.slice(offset).trim()}".`);
162
+ if (match[1]) attributes.push([match[1], match[2]]);
163
+ else words.push(match[3] ?? match[4]);
164
+ offset = part.lastIndex;
165
+ }
166
+ for (const [key] of attributes) {
167
+ if (!['id', 'variant', 'label'].includes(key)) throw new Error(`${node.location}: icon accepts id, variant and label; write the rest as words.`);
168
+ }
169
+ return { attributes, words };
170
+ }
171
+ let iconCount = 0;
172
+ const decorative = ' class="space-icon" aria-hidden="true" focusable="false"';
173
+ function inlineIcon(name, style, id, { tone, attributes = decorative, css = '' } = {}) {
174
+ return iconRenderer.svg(iconCatalog.icons[name], style, { id, tone })
175
+ .replace(/^<svg xmlns='http:\/\/www\.w3\.org\/2000\/svg'/, `<svg${attributes}${css ? ` style="${escape(css)}"` : ''}`);
176
+ }
177
+ function readIcon(words, location) {
178
+ const [name, ...rest] = words;
179
+ if (!name) throw new Error(`${location}: write the icon name after icon, like icon add-01.`);
180
+ if (!iconRenderer) throw noIcons(location);
181
+ if (!Object.hasOwn(iconCatalog.icons, name)) throw new Error(`${location}: there is no icon ${name}; the Icons page lists every name.`);
182
+ const icon = { name, style: null, size: [], colors: [], disabled: false, hidden: false };
183
+ for (const word of rest) {
184
+ if (iconRenderer.styles.includes(word)) {
185
+ if (icon.style) throw new Error(`${location}: the icon has two styles, ${icon.style} and ${word}.`);
186
+ icon.style = word;
187
+ } else if (word === 'disabled') icon.disabled = true;
188
+ else if (word === 'hidden') icon.hidden = true;
189
+ else if (!styleModule) throw noStyle(location, `"${word}" is a utility; icon sizes and colors`);
190
+ else if (word.startsWith('size-')) {
191
+ const utility = resolveUtility(word, { colors: themeColors });
192
+ if (utility.error || utility.variants.length) throw new Error(`${location}: ${utility.error ?? `${word} takes no variant`}.`);
193
+ icon.size = utility.declarations;
194
+ } else {
195
+ const utility = resolveUtility(`text-${word}`, { colors: themeColors });
196
+ const color = !utility.error && !utility.variants.length && utility.declarations.length === 1 && utility.declarations[0][0] === 'color';
197
+ if (!color) throw new Error(`${location}: "${word}" is not an icon style, a size-<n>, a color, disabled or hidden.`);
198
+ if (icon.colors.length === 2) throw new Error(`${location}: an icon takes up to two colors.`);
199
+ icon.colors.push(utility.declarations[0][1]);
200
+ }
201
+ }
202
+ return icon;
203
+ }
113
204
  const appDirectory = dirname(entry);
114
205
  const shared = configuredShared ?? join(dirname(appDirectory), sharedDirectory);
115
206
  const styleDirectory = dirname(styles);
@@ -119,7 +210,19 @@ const [appFiles, assetFiles, globalStyles, agentFiles, languageFiles, sharedFile
119
210
  ...[appDirectory, assetDirectory, styleDirectory, agentDirectory, languageDirectory].map(directory => filesIn(directory)),
120
211
  filesIn(shared, { optional: true })
121
212
  ]);
122
- const projectFiles = [...appFiles, ...sharedFiles, ...globalStyles, ...agentFiles];
213
+ // The Elements of the package: every .markup, .logic and .style in its elements directory, at any depth.
214
+ const elementPackageDirectory = elementPackage ? join(elementPackage) : null;
215
+ async function packageFilesIn(directory, path) {
216
+ const entries = await readdir(directory, { withFileTypes: true });
217
+ const files = await Promise.all(entries.map(entry => entry.isDirectory() ? packageFilesIn(join(directory, entry.name), join(path, entry.name))
218
+ : entry.isFile() && /\.(markup|logic|style)$/.test(entry.name) ? [[join(path, entry.name), join(directory, entry.name)]] : []));
219
+ return files.flat();
220
+ }
221
+ if (elementModule) {
222
+ for (const [file, disk] of (await packageFilesIn(elementModule.elementsDirectory, elementPackageDirectory)).sort()) packageFiles.set(file, disk);
223
+ }
224
+ const elementPackageFiles = [...packageFiles.keys()];
225
+ const projectFiles = [...appFiles, ...sharedFiles, ...globalStyles, ...agentFiles, ...elementPackageFiles];
123
226
  const namedFiles = projectFiles.filter(file => namedKinds.has(extname(file).slice(1).toLowerCase()));
124
227
  const unsupported = projectFiles.find(file => /\.(styles|mockup)$/i.test(file));
125
228
  if (unsupported) throw new Error(`${unsupported}: use the registered Space extensions .style and .mock.`);
@@ -130,18 +233,38 @@ for (const file of namedFiles) {
130
233
  if (model) declarations.set(file, model);
131
234
  }
132
235
  sourceLines(sources.get(environment), environment);
236
+ // A comment that starts with #AGENT is a directive for AI agents only: the build copies it to the .map, with file
237
+ // and line, and leaves it out of the generated code.
238
+ const agentDirective = /^#\s*AGENT\b:?\s*(.*)$/;
239
+ const directives = new Map();
240
+ for (const file of [...namedFiles, environment]) {
241
+ const found = sources.get(file).split(/\r?\n/).flatMap((line, index) => {
242
+ const match = agentDirective.exec(line.trim());
243
+ if (!match) return [];
244
+ if (!match[1]) throw new Error(`${file}:${index + 1}: write the directive after #AGENT.`);
245
+ return [[index + 1, match[1]]];
246
+ });
247
+ if (found.length) directives.set(file, found);
248
+ }
133
249
  // An Element is the set of files that share a name in one folder. No file is required: .markup renders, .logic
134
250
  // behaves and .style provides styles. A .logic without .markup runs on its own; a .style without .markup provides
135
251
  // variants named after its Element to any markup.
136
252
  const elements = new Map();
137
253
  const elementFiles = new Map();
138
- const componentDirectories = [join(appDirectory, 'pages'), join(appDirectory, 'elements'), join(shared, 'elements')];
254
+ const componentDirectories = [join(appDirectory, 'pages'), join(appDirectory, 'elements'), join(shared, 'elements'),
255
+ ...(elementPackageDirectory ? [elementPackageDirectory] : [])];
139
256
  for (const file of declarations.keys()) {
140
257
  const kind = extname(file).slice(1);
141
258
  if (!['markup', 'logic', 'style'].includes(kind) || !componentDirectories.some(directory => file.startsWith(directory + '/'))) continue;
142
259
  const name = basename(file, '.' + kind);
143
260
  const entry = elementFiles.get(name) ?? { directory: dirname(file) };
144
- if (entry[kind] || entry.directory !== dirname(file)) throw new Error(`Duplicate Element name: ${name}.`);
261
+ if (entry[kind] || entry.directory !== dirname(file)) {
262
+ const fromPackage = elementPackageDirectory && [entry.directory, dirname(file)].some(directory =>
263
+ directory === elementPackageDirectory || directory.startsWith(elementPackageDirectory + '/'));
264
+ throw new Error(fromPackage
265
+ ? `${packageFiles.has(file) ? entry.directory : file}: ${name} is also an Element of ${elementPackage}; rename the Element of the project.`
266
+ : `Duplicate Element name: ${name}.`);
267
+ }
145
268
  entry[kind] = file;
146
269
  elementFiles.set(name, entry);
147
270
  if (kind === 'markup') elements.set(name, file);
@@ -179,7 +302,9 @@ function resolveValue(value, props, location) {
179
302
  const field = value.slice(1, -1);
180
303
  if (!field.startsWith('$')) return field;
181
304
  const name = field.slice(1);
182
- if (!Object.hasOwn(props, name)) throw new Error(`${location}: missing Element property ${name}.`);
305
+ if (!Object.hasOwn(props, name)) {
306
+ throw new Error(name.includes('.') ? `${location}: the list item has no field ${name.slice(name.indexOf('.') + 1)}.` : `${location}: missing Element property ${name}.`);
307
+ }
183
308
  return props[name];
184
309
  }
185
310
 
@@ -243,15 +368,46 @@ function variantClasses(value, id) {
243
368
  }
244
369
  return classes;
245
370
  }
246
- const htmlTags = new Set(('a abbr address article aside audio b blockquote body br button canvas caption cite code col ' +
247
- 'colgroup data datalist dd del details dfn dialog div dl dt em fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 ' +
248
- 'head header hgroup hr html i iframe img input ins kbd label legend li link main mark menu meter nav noscript object ol ' +
249
- 'optgroup option output p picture pre progress q rp rt ruby s samp search section select slot small source span strong ' +
250
- 'sub summary sup svg table tbody td template textarea tfoot th thead time tr track u ul var video wbr').split(' '));
251
371
  for (const [name, files] of elementFiles) {
252
372
  if (htmlTags.has(name)) throw new Error(`${files.markup ?? files.logic ?? files.style}: an Element can't take the name of the HTML tag ${name}.`);
253
373
  }
254
- const highlightRoles = ['action', 'comment', 'control', 'reactive', 'return', 'type', 'value'];
374
+ // list <name>: in a .logic declares a fixed list. Each item has a name, and that name is its identity: the build writes it
375
+ // as data-key on the first tag of the item, so no track expression is needed. Markup repeats a block with
376
+ // "for <item> in <list>" and reads the fields as {$item.field}, plus {$item.key} and {$item.index}.
377
+ const listPattern = /^list ([a-z][A-Za-z0-9]*):$/;
378
+ const forPattern = /^for ([a-z][A-Za-z0-9]*) in ([a-z][A-Za-z0-9]*)$/;
379
+ const listCache = new Map();
380
+ function listsOf(file) {
381
+ if (listCache.has(file)) return listCache.get(file);
382
+ const lists = new Map();
383
+ for (const member of declarations.get(file).children) {
384
+ const name = listPattern.exec(member.value)?.[1];
385
+ if (!name) continue;
386
+ if (lists.has(name)) throw new Error(`${member.location}: duplicate list ${name}.`);
387
+ if (!member.children.length) throw new Error(`${member.location}: list ${name} has no items.`);
388
+ const keys = new Set();
389
+ const items = member.children.map((item, index) => {
390
+ const key = /^([a-z][a-z0-9]*(?:-[a-z0-9]+)*):$/.exec(item.value)?.[1];
391
+ if (!key || !item.children.length) throw new Error(`${item.location}: name each list item, like agent:, and write its fields below it.`);
392
+ if (keys.has(key)) throw new Error(`${item.location}: duplicate item ${key}; the item name is its identity.`);
393
+ keys.add(key);
394
+ const fields = { key, index: String(index) };
395
+ for (const field of item.children) {
396
+ const match = pair.exec(field.value);
397
+ if (!match || !match[2] || field.children.length) throw new Error(`${field.location}: write each field as name: value.`);
398
+ if (Object.hasOwn(fields, match[1])) {
399
+ throw new Error(`${field.location}: ${['key', 'index'].includes(match[1]) ? `${match[1]} is built in` : `duplicate field ${match[1]}`}.`);
400
+ }
401
+ fields[match[1]] = match[2].replace(/^"(.*)"$/, '$1');
402
+ }
403
+ return fields;
404
+ });
405
+ lists.set(name, items);
406
+ }
407
+ listCache.set(file, lists);
408
+ return lists;
409
+ }
410
+ const highlightRoles = [...new Set(Object.values(highlightRoleOf))].sort();
255
411
  const logicAttributes = new Set(['data-bind', 'data-show', 'data-pressed', 'data-expanded', 'data-state', 'data-theme-control', 'data-language']);
256
412
  const names = new Map();
257
413
  function addName(name, kind, location) {
@@ -269,11 +425,17 @@ function addVariant(token, id, location) {
269
425
  addName(token, 'variant', location);
270
426
  }
271
427
  for (const role of highlightRoles) addName(`space-${role}`, 'variant', 'Space highlighter');
428
+ for (const name of ['space-icon', 'space-icon_disabled']) addName(name, 'variant', 'Icon tag');
272
429
  for (const [file, { children }] of declarations) {
273
430
  if (!file.endsWith('.markup')) continue;
274
431
  (function visit(nodes) {
275
432
  for (const node of nodes) {
276
- for (const [key, raw] of parseNode(node).attributes) {
433
+ if (forPattern.test(node.value)) {
434
+ visit(node.children);
435
+ continue;
436
+ }
437
+ const parts = iconTag.test(node.value) ? iconParts(node) : parseNode(node);
438
+ for (const [key, raw] of parts.attributes) {
277
439
  if (key === 'class') throw new Error(`${node.location}: Space has no class attribute; name the tag with id or share a style with variant.`);
278
440
  if (logicAttributes.has(key)) {
279
441
  throw new Error(`${node.location}: give the tag an id and declare ${key.slice(5)} under bind: in the .logic.`);
@@ -282,7 +444,7 @@ for (const [file, { children }] of declarations) {
282
444
  const value = raw.slice(1, -1);
283
445
  if (key === 'id') addName(value, 'id', node.location);
284
446
  }
285
- const attributes = Object.fromEntries(parseNode(node).attributes.filter(([, raw]) => raw?.startsWith('"')).map(([key, raw]) => [key, raw.slice(1, -1)]));
447
+ const attributes = Object.fromEntries(parts.attributes.filter(([, raw]) => raw?.startsWith('"')).map(([key, raw]) => [key, raw.slice(1, -1)]));
286
448
  for (const token of (attributes.variant ?? '').split(/\s+/).filter(Boolean)) addVariant(token, attributes.id, node.location);
287
449
  visit(node.children);
288
450
  }
@@ -316,7 +478,7 @@ const usedProviders = new Set();
316
478
  const actionCalls = [];
317
479
  const logicIds = new Map();
318
480
  const dependencies = new Map();
319
- function render(file, props = {}, ancestry = [], parentScope = null) {
481
+ function render(file, rootProps = {}, ancestry = [], parentScope = null) {
320
482
  if (!sources.has(file)) throw new Error(`Missing markup: ${file}`);
321
483
  if (ancestry.includes(file)) throw new Error(`Circular Element reference: ${[...ancestry, file].join(' → ')}`);
322
484
  const nodes = declarations.get(file).children;
@@ -336,7 +498,62 @@ function render(file, props = {}, ancestry = [], parentScope = null) {
336
498
  const rootBinding = declarations.has(file.replace(/\.markup$/, '.logic')) ? name : null;
337
499
  if (rootBinding && !logicIds.has(name)) logicIds.set(name, new Set());
338
500
  const scope = rootBinding ? logicIds.get(name) : parentScope;
339
- function renderNode(node, isRoot = false) {
501
+ // A list comes from the .logic of this Element or of the Elements around it, nearest first.
502
+ const findList = (listName, location) => {
503
+ for (const element of [name, ...ancestors]) {
504
+ const logicFile = elementFiles.get(element)?.logic;
505
+ const list = logicFile && listsOf(logicFile).get(listName);
506
+ if (list) return list;
507
+ }
508
+ throw new Error(`${location}: no .logic of this Element or of the Elements around it declares list ${listName}.`);
509
+ };
510
+ function renderIcon(node, props) {
511
+ if (node.children.length) throw new Error(`${node.location}: icon takes no children.`);
512
+ const { attributes: parsed, words } = iconParts(node);
513
+ const values = Object.fromEntries(parsed.map(([key, raw]) => [key, raw.startsWith('"') ? raw.slice(1, -1) : resolveValue(raw, props, node.location)]));
514
+ const icon = readIcon(words.flatMap(word => String(word.startsWith('{') ? resolveValue(word, props, node.location) : word)
515
+ .split(/\s+/).filter(Boolean)), node.location);
516
+ let attributes = '';
517
+ const classes = icon.disabled ? ['space-icon', 'space-icon_disabled'] : ['space-icon'];
518
+ if (typeof values.variant === 'string') {
519
+ for (const token of values.variant.split(/\s+/).filter(Boolean)) {
520
+ checkOwner(token, node.location);
521
+ addVariant(token, values.id, node.location);
522
+ }
523
+ classes.push(...variantClasses(values.variant, values.id));
524
+ }
525
+ attributes += ` class="${escape(classes.join(' '))}"`;
526
+ if (typeof values.id === 'string') {
527
+ checkOwner(values.id, node.location);
528
+ addName(values.id, 'id', node.location);
529
+ if (renderedIds.has(values.id)) throw new Error(`${node.location}: id "${values.id}" is already on the page at ${renderedIds.get(values.id)}.`);
530
+ renderedIds.set(values.id, node.location);
531
+ scope?.add(values.id);
532
+ attributes += ` id="${escape(values.id)}"`;
533
+ }
534
+ const label = typeof values.label === 'string' ? values.label : null;
535
+ const key = label && translation(label, node.location);
536
+ attributes += label
537
+ ? ` role="img"${key ? ` data-i18n-aria-label="${escape(key)}"` : ''} aria-label="${escape(key ? languages[defaultLocale][key] : label)}"`
538
+ : ' aria-hidden="true"';
539
+ attributes += ` focusable="false"${icon.disabled ? ' aria-disabled="true"' : ''}${icon.hidden ? ' hidden' : ''}`;
540
+ const css = [...icon.size.map(([property, value]) => `${property}: ${value}`), ...(icon.colors[0] ? [`color: ${icon.colors[0]}`] : [])].join('; ');
541
+ return inlineIcon(icon.name, icon.style ?? iconStyle, `icon${++iconCount}`, { tone: icon.colors[1], attributes, css });
542
+ }
543
+ function renderNode(node, isRoot = false, props = rootProps) {
544
+ const loop = forPattern.exec(node.value);
545
+ if (loop) {
546
+ const [, item, listName] = loop;
547
+ if (isRoot) throw new Error(`${node.location}: for repeats tags inside the root; wrap it in a tag.`);
548
+ if (!node.children.length) throw new Error(`${node.location}: write the tags to repeat below for.`);
549
+ if (Object.keys(props).some(key => key.startsWith(item + '.'))) throw new Error(`${node.location}: ${item} is already a list item here.`);
550
+ return findList(listName, node.location).map(fields => {
551
+ const scoped = { ...props, ...Object.fromEntries(Object.entries(fields).map(([field, value]) => [`${item}.${field}`, value])) };
552
+ return node.children.map(child => renderNode(child, false, scoped)).join('')
553
+ .replace(/^<([a-z][\w-]*)/, `<$1 data-key="${escape(fields.key)}"`);
554
+ }).join('');
555
+ }
556
+ if (iconTag.test(node.value)) return renderIcon(node, props);
340
557
  const { tag, inline, attributes: parsed } = parseNode(node);
341
558
  const attributes = Object.create(null);
342
559
  for (const [key, raw] of parsed) {
@@ -346,7 +563,14 @@ function render(file, props = {}, ancestry = [], parentScope = null) {
346
563
  if (inline || node.children.length) throw new Error(`${node.location}: Element references accept properties.`);
347
564
  if (!dependencies.has(file)) dependencies.set(file, new Set());
348
565
  dependencies.get(file).add(tag);
349
- return render(elements.get(tag), attributes, [...ancestry, file], scope);
566
+ try {
567
+ return render(elements.get(tag), attributes, [...ancestry, file], scope);
568
+ } catch (error) {
569
+ // An error inside an Element also names the tag that rendered it, the line to fix when the Element comes from a package.
570
+ if (!error.renderedAt) error.message += `\n rendered by ${node.location}`;
571
+ error.renderedAt = true;
572
+ throw error;
573
+ }
350
574
  }
351
575
  if (elementFiles.has(tag)) {
352
576
  throw new Error(`${node.location}: ${tag} has no .markup to render; ${styleProviders.has(tag) ? `use variant="${tag}"` : `call it with action="${tag}.<action>"`}.`);
@@ -396,25 +620,79 @@ function render(file, props = {}, ancestry = [], parentScope = null) {
396
620
  if (label) markup += ` data-i18n="${escape(label)}"`;
397
621
  markup += '>';
398
622
  if (voidTags.has(tag)) return markup;
399
- const children = node.children.map(child => renderNode(child)).join('');
623
+ const children = node.children.map(child => renderNode(child, false, props)).join('');
400
624
  const content = source === undefined ? escape(label ? languages[defaultLocale][label] : text) : highlightSpace(text, source);
401
625
  return markup + content + children + '</' + tag + '>';
402
626
  }
403
627
  return renderNode(nodes[0], true);
404
628
  }
405
629
 
630
+ // Inside a selector, "property: value" is a CSS declaration. With the style extension declared in .config (style:
631
+ // from: @aliens-syndicate/style), any other line lists utilities with the Tailwind CSS names: "flex items-center gap-4 max-md:flex-col hover:bg-surface". State variants such as
632
+ // hover: and dark: rewrite the selector; responsive variants such as md: and max-lg: become @media rules, written
633
+ // after the rest of the file from the widest max-* to the narrowest and then from the narrowest min-width up.
634
+ const declarationLine = /^-{0,2}[A-Za-z][\w-]*:\s+\S/;
635
+ const themeColors = new Set();
636
+ const usedProperties = new Set();
637
+ const usedKeyframes = new Set();
638
+ const ruleText = (selector, declarations) => `${selector} {\n${declarations.map(entry => ' ' + entry + ';').join('\n')}\n}`;
406
639
  function compileStyles(nodes, declares) {
407
- return nodes.map(node => {
408
- const scope = node.value.startsWith('@media ');
640
+ const base = [];
641
+ const states = [];
642
+ const responsive = [];
643
+ for (const node of nodes) {
644
+ if (node.value.startsWith('@media ') || node.value.startsWith('@supports ')) {
645
+ base.push(`${node.value} {\n${compileStyles(node.children, declares)}\n}`);
646
+ continue;
647
+ }
409
648
  const selector = node.value.startsWith('@') ? node.value : compileSelector(node.value, node.location, declares);
410
- const css = scope ? compileStyles(node.children, declares) : node.children.map(declaration => {
411
- if (!/^[-\w]+:\s*\S/.test(declaration.value) || declaration.children.length) {
412
- throw new Error(`${declaration.location}: expected a CSS declaration.`);
649
+ const plain = [];
650
+ const variantGroups = new Map();
651
+ for (const line of node.children) {
652
+ if (line.children.length) throw new Error(`${line.location}: expected a CSS declaration or a list of utilities.`);
653
+ if (declarationLine.test(line.value) || node.value.startsWith('@')) {
654
+ plain.push(line.value);
655
+ continue;
413
656
  }
414
- return ' ' + declaration.value + ';';
415
- }).join('\n');
416
- return `${selector} {\n${css}\n}`;
417
- }).join('\n\n');
657
+ if (!styleModule) throw noStyle(line.location, `"${line.value}" is not a CSS declaration; utilities`);
658
+ for (const token of line.value.split(/\s+/)) {
659
+ const utility = resolveUtility(token, { colors: themeColors });
660
+ if (utility.error) {
661
+ const hint = /^[-\w]+:\S/.test(token) && !token.includes('[') && !token.includes('(')
662
+ ? ' A CSS declaration needs a space after the colon.' : ' See the Style page for the utility names.';
663
+ throw new Error(`${line.location}: ${utility.error}.${hint}`);
664
+ }
665
+ for (const property of utility.properties) usedProperties.add(property);
666
+ if (utility.keyframes) usedKeyframes.add(utility.keyframes);
667
+ const declarations = utility.declarations.map(([property, value]) => `${property}: ${value}`);
668
+ if (!utility.variants.length && !utility.child) {
669
+ plain.push(...declarations);
670
+ continue;
671
+ }
672
+ if (!variantGroups.has(utility.key)) variantGroups.set(utility.key, { utility, declarations: [] });
673
+ variantGroups.get(utility.key).declarations.push(...declarations);
674
+ }
675
+ }
676
+ if (plain.length) base.push(ruleText(selector, plain));
677
+ for (const { utility, declarations } of variantGroups.values()) {
678
+ const selectors = styleModule.splitSelectors(selector).map(part => utility.variants
679
+ .filter(found => found.selector).reduce((current, found) => found.selector(current), part) + utility.child);
680
+ const rule = ruleText(selectors.join(', '), declarations);
681
+ const wrappers = utility.variants.filter(found => found.media || found.supports)
682
+ .map(found => found.media ? `@media ${found.media}` : `@supports ${found.supports}`);
683
+ if (!wrappers.length) states.push(rule);
684
+ else responsive.push({ wrappers, order: utility.variants.find(found => found.order).order, rule });
685
+ }
686
+ }
687
+ responsive.sort((left, right) => left.order[0] - right.order[0] || left.order[1] - right.order[1]);
688
+ const scoped = [];
689
+ for (const entry of responsive) {
690
+ const key = entry.wrappers.join(' ');
691
+ if (scoped.at(-1)?.key === key) scoped.at(-1).rules.push(entry.rule);
692
+ else scoped.push({ key, wrappers: entry.wrappers, rules: [entry.rule] });
693
+ }
694
+ const media = scoped.map(({ wrappers, rules }) => wrappers.reduceRight((inner, wrapper) => `${wrapper} {\n${inner}\n}`, rules.join('\n\n')));
695
+ return [...base, ...states, ...media].join('\n\n');
418
696
  }
419
697
 
420
698
  const bindKinds = new Set(['text', 'show', 'pressed', 'expanded']);
@@ -435,6 +713,10 @@ function compileLogic(file) {
435
713
  members.push(`${field[1]}: ${field[2]} = ${field[3]};`);
436
714
  continue;
437
715
  }
716
+ if (listPattern.test(member.value)) {
717
+ listsOf(file);
718
+ continue;
719
+ }
438
720
  if (member.value === 'page:') {
439
721
  for (const entry of member.children) {
440
722
  const match = /^(theme|locale): ([A-Za-z]\w*)$/.exec(entry.value);
@@ -517,7 +799,8 @@ const stylesheetFiles = manifest.flatMap(section => {
517
799
  if (section.value === 'import:') return entries.map(file => join(styleDirectory, file));
518
800
  throw new Error(`${section.location}: unsupported stylesheet manifest entry.`);
519
801
  });
520
- stylesheetFiles.push(...[...sharedFiles, ...appFiles].filter(file => file.endsWith('.style') && declarations.has(file)));
802
+ // The package styles come before the project styles, so a project style overrides them.
803
+ stylesheetFiles.push(...[...elementPackageFiles, ...sharedFiles, ...appFiles].filter(file => file.endsWith('.style') && declarations.has(file)));
521
804
  const themeFile = join(styleDirectory, 'settings', 'theme.style');
522
805
  const themeNames = new Set(['light', 'dark']);
523
806
  if (stylesheetFiles.includes(themeFile)) {
@@ -525,9 +808,18 @@ if (stylesheetFiles.includes(themeFile)) {
525
808
  for (const match of value.matchAll(/:root\[data-theme="([a-z][a-z0-9-]*)"\]/g)) themeNames.add(match[1]);
526
809
  }
527
810
  }
811
+ // Every --color-<name> in the global styles becomes a color utility, like bg-<name> and text-<name>.
812
+ for (const file of globalStyles.filter(path => declarations.has(path))) {
813
+ for (const rule of declarations.get(file).children) {
814
+ for (const line of rule.children) {
815
+ const name = /^--color-([a-z][a-z0-9-]*):\s/.exec(line.value)?.[1];
816
+ if (name) themeColors.add(name);
817
+ }
818
+ }
819
+ }
528
820
  const html = render(markupEntry);
529
821
  const logic = new Map();
530
- for (const file of [...appFiles, ...sharedFiles].filter(file => file.endsWith('.logic') && declarations.has(file))) {
822
+ for (const file of [...elementPackageFiles, ...appFiles, ...sharedFiles].filter(file => file.endsWith('.logic') && declarations.has(file))) {
531
823
  const name = basename(file, '.logic');
532
824
  if (logic.has(name)) throw new Error(`Duplicate Logic name: ${name}.`);
533
825
  logic.set(name, compileLogic(file));
@@ -551,24 +843,65 @@ const usedLogic = [...logic].filter(([name, entry]) => logicIds.has(name) || use
551
843
  const elementOfFile = file => componentDirectories.some(directory => file.startsWith(directory + '/')) ? basename(file, '.style') : null;
552
844
  const compiledStyles = stylesheetFiles.map(file => {
553
845
  const element = elementOfFile(file);
554
- const declares = globalStyles.includes(file) ? libraryElement : styleProviders.has(element) ? element : null;
846
+ // A package Element declares the variants named after it, so its .style may offer variants no markup uses yet.
847
+ const declares = globalStyles.includes(file) ? libraryElement : styleProviders.has(element) || packageFiles.has(file) ? element : null;
555
848
  return { file, element, css: compileStyles(declarations.get(file).children, declares) };
556
849
  });
557
- const css = compiledStyles.filter(({ element }) => !element || renderedElements.has(element) || usedProviders.has(element))
558
- .map(entry => entry.css).join('\n\n');
559
- const compiledLogic = usedLogic.map(([name, entry]) => `${JSON.stringify(name)}: ${entry.source}`).join(',\n');
560
850
  const runtime = await readFile(join(import.meta.dirname, 'runtime.mjs'), 'utf8');
851
+ const iconCatalogUsed = html.includes(' data-icon-catalog');
852
+ if (iconCatalogUsed && !iconRenderer) throw noIcons('The Icons page');
853
+ // Every icon tag renders an inline svg with class space-icon; space-icon_disabled marks the disabled ones.
854
+ const iconCss = iconRenderer ? `.space-icon {
855
+ display: inline-block;
856
+ width: 1em;
857
+ height: 1em;
858
+ flex-shrink: 0;
859
+ vertical-align: -0.125em;
860
+ }
861
+
862
+ .space-icon_disabled {
863
+ opacity: 0.4;
864
+ }
865
+
866
+ .space-icon[hidden] {
867
+ display: none;
868
+ }` : '';
869
+ // The site highlights Space with the colors the editor extension declares, read from its package.json, so a color
870
+ // changes in one place. Every token type of a role must share one color in each theme.
871
+ const editorPalette = JSON.parse(await readFile(join(import.meta.dirname, 'vscode-space', 'package.json'), 'utf8'))
872
+ .contributes.configurationDefaults['editor.semanticTokenColorCustomizations'];
873
+ const highlightTheme = rules => highlightRoles.map(role => {
874
+ const colors = new Set(Object.entries(highlightRoleOf).filter(([, owner]) => owner === role)
875
+ .map(([type]) => rules[`${type}:space`]).filter(Boolean));
876
+ if (colors.size !== 1) throw new Error(`tools/vscode-space/package.json: the Space types of the ${role} role need one color, found ${[...colors].join(', ') || 'none'}.`);
877
+ return ` --space-${role}: ${[...colors][0]};`;
878
+ }).join('\n');
879
+ const highlightCss = `:root {\n${highlightTheme(editorPalette['[*Light*][*light*]'].rules)}\n}\n\n` +
880
+ `:root[data-theme="dark"] {\n${highlightTheme(editorPalette.rules)}\n}`;
881
+ const highlightUsed = new RegExp(`var\\(--space-(?:${highlightRoles.join('|')})\\)`);
882
+ const css = [...[...usedProperties].sort().map(name => styleModule.propertyRule(name)), ...usedKeyframes, iconCss,
883
+ compiledStyles.some(entry => highlightUsed.test(entry.css)) ? highlightCss : '',
884
+ ...compiledStyles.filter(({ element }) => !element || renderedElements.has(element) || usedProviders.has(element)).map(entry => entry.css)]
885
+ .filter(Boolean).join('\n\n');
886
+ const compiledLogic = usedLogic.map(([name, entry]) => `${JSON.stringify(name)}: ${entry.source}`).join(',\n');
561
887
  const output = join(workspace, 'dist');
562
888
  const favicon = assetFiles.includes(join(assetDirectory, 'mark.png')) ? '\n <link rel="icon" href="./assets/mark.png">' : '';
563
889
  await mkdir(output, { recursive: true });
564
890
  await Promise.all([
565
891
  cp(join(root, assetDirectory), join(output, 'assets'), { recursive: true }),
566
892
  writeFile(join(output, 'main.css'), css + '\n'),
893
+ // The Icons page loads the whole catalog when it opens, so other pages never download it.
894
+ ...(iconCatalogUsed ? [writeFile(join(output, 'icons.json'), JSON.stringify({ categories: iconCatalog.categories, icons: iconCatalog.icons }))] : []),
567
895
  writeFile(join(output, 'app.js'), `const logic = { ${compiledLogic} };
568
896
  const languages = ${JSON.stringify(languages)};
569
897
  const availableThemes = ${JSON.stringify([...themeNames])};
570
898
  const defaultLocale = ${JSON.stringify(defaultLocale)};
571
899
  const detectLocale = ${detection === 'browser'};
900
+ const iconStyle = ${JSON.stringify(iconStyle)};
901
+ const iconRenderer = ${iconCatalogUsed ? `(${iconModule.createIconRenderer})()` : 'null'};
902
+ const copyIcons = ${JSON.stringify(iconRenderer && iconCatalog.icons['copy-01'] && iconCatalog.icons['tick-02'] ? {
903
+ copy: inlineIcon('copy-01', iconStyle, 'copy-icon'), copied: inlineIcon('tick-02', iconStyle, 'copied-icon')
904
+ } : null)};
572
905
  ${runtime}`),
573
906
  writeFile(join(output, 'index.html'), `<!doctype html>
574
907
  <html lang="${defaultLocale}">
@@ -596,11 +929,14 @@ entrypoints:
596
929
  assets: ${assetDirectory}
597
930
  styles: ${styles}
598
931
  architecture:
599
- ${[[appDirectory, appFiles], [assetDirectory, assetFiles], [shared, sharedFiles], [styleDirectory, globalStyles], [languageDirectory, languageFiles], [agentDirectory, agentFiles.filter(file => file !== map)]]
600
- .filter(([directory, files]) => directory !== shared || files.length > 0)
932
+ ${[[appDirectory, appFiles], [assetDirectory, assetFiles], [shared, sharedFiles], [styleDirectory, globalStyles], [languageDirectory, languageFiles], [agentDirectory, agentFiles.filter(file => file !== map)],
933
+ [elementPackageDirectory, elementPackageFiles]]
934
+ .filter(([directory, files]) => (directory !== shared && directory !== elementPackageDirectory) || files.length > 0)
601
935
  .map(([directory, files]) => [`${indentation}${directory}:`, ...files.map(file => indentation.repeat(2) + relative(directory, file))].join('\n')).join('\n')}
602
936
  dependencies:
603
937
  ${[...dependencies].map(([file, uses]) => `${indentation}${file}:\n${[...uses].map(name => indentation.repeat(2) + name).join('\n')}`).join('\n')}
938
+ directives:
939
+ ${[...directives].map(([file, found]) => `${indentation}${file}:\n${found.map(([line, text]) => `${indentation.repeat(2)}${line}: ${text}`).join('\n')}`).join('\n')}
604
940
  validation:
605
941
  web_preview: passed
606
942
  `);
@@ -0,0 +1,41 @@
1
+ // aliens cache: deletes what the build and the tools generate, so the next aliens build or aliens run starts clean.
2
+ import { existsSync } from 'node:fs';
3
+ import { lstat, readdir, rm } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import { dim, green, parseFlags, pick, requireProject } from './cli-shared.mjs';
6
+
7
+ const text = {
8
+ en: { removed: 'REMOVED', clean: 'Nothing to clean: no cache in this project.', done: 'Cache cleared, {size} freed. Run aliens build or aliens run to generate dist/ again.' },
9
+ pt: { removed: 'REMOVIDO', clean: 'Nada para limpar: nenhum cache neste projeto.', done: 'Cache limpo, {size} liberados. Rode aliens build ou aliens run para gerar o dist/ de novo.' },
10
+ es: { removed: 'ELIMINADO', clean: 'Nada que limpiar: no hay caché en este proyecto.', done: 'Caché limpiada, {size} liberados. Ejecuta aliens build o aliens run para generar dist/ otra vez.' },
11
+ zh: { removed: '已删除', clean: '无需清理:此项目没有缓存。', done: '缓存已清除,释放了 {size}。运行 aliens build 或 aliens run 重新生成 dist/。' }
12
+ };
13
+ const t = (key, values = {}) => Object.entries(values).reduce((message, [name, value]) => message.replaceAll(`{${name}}`, value), pick(text)[key]);
14
+
15
+ // dist/ is the build output; node_modules/.cache and .aliens/ hold what tools keep between runs.
16
+ const targets = ['dist', join('node_modules', '.cache'), '.aliens'];
17
+
18
+ async function sizeOf(path) {
19
+ const info = await lstat(path);
20
+ if (!info.isDirectory()) return info.size;
21
+ const entries = await readdir(path);
22
+ return (await Promise.all(entries.map(entry => sizeOf(join(path, entry))))).reduce((total, size) => total + size, info.size);
23
+ }
24
+ const readable = bytes => bytes < 1024 ? `${bytes} B` : bytes < 1024 ** 2 ? `${(bytes / 1024).toFixed(1)} KB` : `${(bytes / 1024 ** 2).toFixed(1)} MB`;
25
+
26
+ export async function cache(args) {
27
+ parseFlags(args);
28
+ const root = requireProject();
29
+ let freed = 0;
30
+ let removed = 0;
31
+ for (const target of targets) {
32
+ const path = join(root, target);
33
+ if (!existsSync(path)) continue;
34
+ const size = await sizeOf(path);
35
+ await rm(path, { recursive: true, force: true });
36
+ freed += size;
37
+ removed++;
38
+ console.log(`${green(t('removed').padEnd(10))}${target}/ ${dim(`(${readable(size)})`)}`);
39
+ }
40
+ console.log(removed ? '\n' + t('done', { size: readable(freed) }) : t('clean'));
41
+ }