@aliens-syndicate/cli 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.es-ES.md CHANGED
@@ -34,6 +34,26 @@ aliens run
34
34
 
35
35
  El comentario al inicio de `.config` lista los mismos comandos, y la página **Instalación** del sitio (`#installation`) los explica paso a paso.
36
36
 
37
+ `.config` enumera el framework y cada paquete con su versión, agrupados como en `package.json`: `dependencies:` para lo que usa la app y `devDependencies:` para lo que solo usa el build. Cada sección tiene una línea, `<paquete>: <versión>`; la línea de los iconos añade el estilo predeterminado después del nombre.
38
+
39
+ ```text
40
+ dependencies:
41
+ framework:
42
+ @aliens-syndicate/framework: 0.1.10
43
+ icons:
44
+ @aliens-syndicate/icons/stroke-rounded: 0.1.0
45
+ elements:
46
+ @aliens-syndicate/elements: 0.1.0
47
+ reactive:
48
+ @aliens-syndicate/reactive: 0.1.0
49
+
50
+ devDependencies:
51
+ utilities:
52
+ @aliens-syndicate/utilities: 0.1.0
53
+ ```
54
+
55
+ El build se detiene cuando una versión difiere de la instalada y explica cómo corregirlo. `aliens update` instala las versiones más nuevas, las escribe en `package.json` y en `.config` y reescribe la forma antigua con `from:`, y `aliens doctor` señala cada diferencia.
56
+
37
57
  Para publicar una nueva versión, actualiza `version` en `package.json` y ejecuta `npm publish` en la raíz, con la cuenta `aliens-syndicate` conectada en npm.
38
58
 
39
59
  El generador crea la Home en `project/app/pages/home/`, los cuatro niveles de Elements y las carpetas de los tipos de archivo de la aplicación. Los ejemplos comentados del catálogo de héroes vienen de la base del motor en `tools/starter/`, independientemente de la aplicación que tengas abierta. El Element `hero-card` reúne `.markup`, `.logic`, `.style` y `.test` en `project/app/elements/molecules/hero-card/`. Las carpetas `agents/`, `rules/` y `skills/` están en `ai/`.
@@ -127,11 +147,11 @@ Style Counter
127
147
  bg-(--primary) text-(--primary-ink)
128
148
  ```
129
149
 
130
- Dentro de un selector, una línea escrita como `propiedad: valor` es una declaración CSS. Por defecto, `.style` acepta solo CSS normal. Las utilidades son opcionales y viven en su propio paquete: instala `@aliens-syndicate/utilities` y decláralo en `.config` bajo `devDependencies:` → `utilities:` con `from: @aliens-syndicate/utilities`. Sin él, una línea de utilidades detiene el build y explica cómo añadir el paquete. Con él, cualquier otra línea enumera utilidades con los nombres popularizados por frameworks de CSS existentes: `flex`, `gap-4`, `rounded-lg`, `text-sm`. Variantes como `md:`, `max-lg:`, `hover:` y `dark:` escriben la regla `@media` o el selector, y utilidades como `backdrop-blur-md` y `bg-clip-text` añaden las declaraciones `-webkit-`. Los corchetes aceptan cualquier valor, como en `w-[1240px]`, y los paréntesis leen una propiedad personalizada, como en `text-(--muted)`. Cada `--color-<nombre>` de los estilos globales se convierte en un color, como en `bg-brand`. Una utilidad desconocida detiene el build con el archivo y la línea. La página **Utilities** del sitio de documentación (`#utilities-docs`) enumera cada clase con su CSS; `node tools/utilities-docs.mjs` la vuelve a generar a partir del catálogo del paquete.
150
+ Dentro de un selector, una línea escrita como `propiedad: valor` es una declaración CSS. Por defecto, `.style` acepta solo CSS normal. Las utilidades son opcionales y viven en su propio paquete: instala `@aliens-syndicate/utilities` y decláralo en `.config` bajo `devDependencies:` → `utilities:` como `@aliens-syndicate/utilities: <versión>`. Sin él, una línea de utilidades detiene el build y explica cómo añadir el paquete. Con él, cualquier otra línea enumera utilidades con los nombres popularizados por frameworks de CSS existentes: `flex`, `gap-4`, `rounded-lg`, `text-sm`. Variantes como `md:`, `max-lg:`, `hover:` y `dark:` escriben la regla `@media` o el selector, y utilidades como `backdrop-blur-md` y `bg-clip-text` añaden las declaraciones `-webkit-`. Los corchetes aceptan cualquier valor, como en `w-[1240px]`, y los paréntesis leen una propiedad personalizada, como en `text-(--muted)`. Cada `--color-<nombre>` de los estilos globales se convierte en un color, como en `bg-brand`. Una utilidad desconocida detiene el build con el archivo y la línea. La página **Utilities** del sitio de documentación (`#utilities-docs`) enumera cada clase con su CSS; `node tools/utilities-docs.mjs` la vuelve a generar a partir del catálogo del paquete.
131
151
 
132
- Los iconos son opcionales y viven en su propio paquete. Instala `@aliens-syndicate/icons` y declaralo en `.config` en `dependencies:` → `icons:` con `from: @aliens-syndicate/icons` y un `style:` predeterminado. Los iconos pertenecen al markup, sin span y sin clase: `icon add-01 size-4 blue-500 red-500` nombra el icono y después, en cualquier orden, uno de los diez estilos, un tamaño, hasta dos colores (el segundo pinta el tono claro de bulk, duotone y twotone) y un estado como `disabled` o `hidden`; `id`, `variant` y `label` son sus únicos atributos. El build dibuja cada icono inline, y un proyecto sin el paquete se genera igual. La página **Icons** (`#icon-docs`) lista los 6070 iconos por categoría y copia la etiqueta de cualquiera; `node tools/icon-docs.mjs` la regenera a partir del paquete.
152
+ Los iconos son opcionales y viven en su propio paquete. Instala `@aliens-syndicate/icons` y decláralo en `.config` en `dependencies:` → `icons:` como `@aliens-syndicate/icons/stroke-rounded: <versión>`, donde la parte después del nombre es el estilo predeterminado. Los iconos pertenecen al markup, sin span y sin clase: `icon add-01 size-4 blue-500 red-500` nombra el icono y después, en cualquier orden, uno de los diez estilos, un tamaño, hasta dos colores (el segundo pinta el tono claro de bulk, duotone y twotone) y un estado como `disabled` o `hidden`; `id`, `variant` y `label` son sus únicos atributos. El build dibuja cada icono inline, y un proyecto sin el paquete se genera igual. La página **Icons** (`#icon-docs`) lista los 6070 iconos por categoría y copia la etiqueta de cualquiera; `node tools/icon-docs.mjs` la regenera a partir del paquete.
133
153
 
134
- Los Elements listos también son opcionales y viven en `@aliens-syndicate/elements`; un proyecto nuevo empieza sin ellos. Instala el paquete y decláralo en `.config` bajo `dependencies:` → `elements:` con `from: @aliens-syndicate/elements`, y cualquier markup puede escribir `ui-button`, `ui-icon-button`, `ui-badge`, `ui-alert`, `ui-card`, `ui-avatar`, `ui-spinner`, `ui-progress`, `ui-stat`, `ui-accordion`, `ui-empty-state`, `ui-divider`, `ui-text-field`, `ui-checkbox` y `ui-switch` con sus propiedades, como en `ui-button label="Guardar" variant="ui-button_primary" action="save"`. Son archivos Space como los Elements del proyecto: el build los valida, `ai/.map` los lista y solo los Elements que la página renderiza llegan a `dist/`. Sus estilos son CSS puro que lee los tokens del starter, y un `.style` del proyecto con los mismos nombres de variant los sobrescribe. La página **Elements** (`#element-docs`) muestra cada uno en vivo, con sus propiedades y su código.
154
+ Los Elements listos también son opcionales y viven en `@aliens-syndicate/elements`; un proyecto nuevo empieza sin ellos. Instala el paquete y decláralo en `.config` bajo `dependencies:` → `elements:` como `@aliens-syndicate/elements: <versión>`, y cualquier markup puede escribir `ui-button`, `ui-icon-button`, `ui-badge`, `ui-alert`, `ui-card`, `ui-avatar`, `ui-spinner`, `ui-progress`, `ui-stat`, `ui-accordion`, `ui-empty-state`, `ui-divider`, `ui-text-field`, `ui-checkbox` y `ui-switch` con sus propiedades, como en `ui-button label="Guardar" variant="ui-button_primary" action="save"`. Son archivos Space como los Elements del proyecto: el build los valida, `ai/.map` los lista y solo los Elements que la página renderiza llegan a `dist/`. Sus estilos son CSS puro que lee los tokens del starter, y un `.style` del proyecto con los mismos nombres de variant los sobrescribe. La página **Elements** (`#element-docs`) muestra cada uno en vivo, con sus propiedades y su código.
135
155
 
136
156
  #### Logic
137
157
 
@@ -185,7 +205,7 @@ Logic Counter
185
205
 
186
206
  Solo se actualizan los binds que leen un valor, y se ejecutan antes que los effects y watches. Las escrituras fuera de una action, como en un `setTimeout` o después de un `fetch`, también actualizan la página. Un `computed` funciona en `bind:` y en el id `<element>-<nombre>` como un signal: `counter-doubled` muestra `doubled`. Asignar a un `computed` detiene el build, igual que un `watch` que no nombra ningún signal ni computed. Un effect que no deja de cambiar lo que lee se detiene en tiempo de ejecución con su nombre. Estas palabras son del lenguaje, así que `import: signal: aliens/core` es opcional.
187
207
 
188
- El Reactive Core de arriba viene en todo proyecto. Los operadores de stream están en el paquete opcional `@aliens-syndicate/reactive`: ejecuta `npm install @aliens-syndicate/reactive`, declara `reactive:` con `from: @aliens-syndicate/reactive` bajo `dependencies:` en `.config`, y un `.logic` puede declarar `stream nombre: tipo = expresión` con 22 operadores con los nombres de RxJS, como `debounce`, `switchMap`, `combineLatest` y `retry`. Sin el paquete, un miembro `stream` detiene el build e indica cómo añadirlo. La página **Reactive** del sitio de documentación (`#reactive-core`) separa ambas partes y ejecuta una búsqueda en vivo con `debounce`.
208
+ El Reactive Core de arriba viene en todo proyecto. Los operadores de stream están en el paquete opcional `@aliens-syndicate/reactive`: ejecuta `npm install @aliens-syndicate/reactive`, decláralo en `.config` bajo `dependencies:` → `reactive:` como `@aliens-syndicate/reactive: <versión>`, y un `.logic` puede declarar `stream nombre: tipo = expresión` con 22 operadores con los nombres de RxJS, como `debounce`, `switchMap`, `combineLatest` y `retry`. Sin el paquete, un miembro `stream` detiene el build e indica cómo añadirlo. La página **Reactive** del sitio de documentación (`#reactive-core`) separa ambas partes y ejecuta una búsqueda en vivo con `debounce`.
189
209
 
190
210
  Las etiquetas nativas aceptan las mismas propiedades cortas que los Elements: `variant` se convierte en `class`, `action` en `data-action`, `label` en `aria-label` y `text` en el texto de la etiqueta. `button` recibe `type="button"` cuando no declara `type`.
191
211
 
package/README.md CHANGED
@@ -34,6 +34,26 @@ aliens run
34
34
 
35
35
  The comment at the top of `.config` lists the same commands, and the **Installation** page of the site (`#installation`) walks through them step by step.
36
36
 
37
+ `.config` lists the framework and every package with its version, grouped as in `package.json`: `dependencies:` for what the app uses and `devDependencies:` for what only the build uses. Each section holds one line, `<package>: <version>`; the icons line adds the default style after the name.
38
+
39
+ ```text
40
+ dependencies:
41
+ framework:
42
+ @aliens-syndicate/framework: 0.1.10
43
+ icons:
44
+ @aliens-syndicate/icons/stroke-rounded: 0.1.0
45
+ elements:
46
+ @aliens-syndicate/elements: 0.1.0
47
+ reactive:
48
+ @aliens-syndicate/reactive: 0.1.0
49
+
50
+ devDependencies:
51
+ utilities:
52
+ @aliens-syndicate/utilities: 0.1.0
53
+ ```
54
+
55
+ The build stops when a version differs from the installed one and says how to fix it. `aliens update` installs the newest versions, writes them in `package.json` and `.config` and rewrites the older `from:` form, and `aliens doctor` points out every difference.
56
+
37
57
  To publish a new version, update `version` in `package.json` and run `npm publish` at the root, with the `aliens-syndicate` account logged in to npm.
38
58
 
39
59
  The generator creates the Home in `project/app/pages/home/`, the four Element levels and the folders for the application file types. The commented examples of the hero catalog come from the engine base in `tools/starter/`, regardless of the application you have open. The `hero-card` Element brings together `.markup`, `.logic`, `.style` and `.test` in `project/app/elements/molecules/hero-card/`. The `agents/`, `rules/` and `skills/` folders live in `ai/`.
@@ -127,11 +147,11 @@ Style Counter
127
147
  bg-(--primary) text-(--primary-ink)
128
148
  ```
129
149
 
130
- Inside a selector, a line written as `property: value` is a CSS declaration. By default `.style` reads plain CSS only. Utilities are optional and live in their own package: install `@aliens-syndicate/utilities` and declare it in `.config` under `devDependencies:` → `utilities:` with `from: @aliens-syndicate/utilities`. Without it, a utility line stops the build and says how to add the package. With it, any other line lists utilities with the names popularized by existing CSS frameworks: `flex`, `gap-4`, `rounded-lg`, `text-sm`. Variants such as `md:`, `max-lg:`, `hover:` and `dark:` write the `@media` rule or the selector, and utilities such as `backdrop-blur-md` and `bg-clip-text` add the `-webkit-` declarations. Brackets take any value, as in `w-[1240px]`, and parentheses read a custom property, as in `text-(--muted)`. Each `--color-<name>` in the global styles becomes a color, as in `bg-brand`. An unknown utility stops the build with the file and the line. The **Utilities** page of the documentation site (`#utilities-docs`) lists every class with its CSS; `node tools/utilities-docs.mjs` regenerates it from the package's catalog.
150
+ Inside a selector, a line written as `property: value` is a CSS declaration. By default `.style` reads plain CSS only. Utilities are optional and live in their own package: install `@aliens-syndicate/utilities` and declare it in `.config` under `devDependencies:` → `utilities:` as `@aliens-syndicate/utilities: <version>`. Without it, a utility line stops the build and says how to add the package. With it, any other line lists utilities with the names popularized by existing CSS frameworks: `flex`, `gap-4`, `rounded-lg`, `text-sm`. Variants such as `md:`, `max-lg:`, `hover:` and `dark:` write the `@media` rule or the selector, and utilities such as `backdrop-blur-md` and `bg-clip-text` add the `-webkit-` declarations. Brackets take any value, as in `w-[1240px]`, and parentheses read a custom property, as in `text-(--muted)`. Each `--color-<name>` in the global styles becomes a color, as in `bg-brand`. An unknown utility stops the build with the file and the line. The **Utilities** page of the documentation site (`#utilities-docs`) lists every class with its CSS; `node tools/utilities-docs.mjs` regenerates it from the package's catalog.
131
151
 
132
- Icons are optional and live in their own package. Install `@aliens-syndicate/icons` and declare it in `.config` under `dependencies:` → `icons:` with `from: @aliens-syndicate/icons` and a default `style:`. Icons belong to the markup, with no span and no class: `icon add-01 size-4 blue-500 red-500` names the icon and then, in any order, one of the ten styles, a size, up to two colors (the second paints the light tone of bulk, duotone and twotone) and a state such as `disabled` or `hidden`; `id`, `variant` and `label` are its only attributes. The build draws each icon inline, and a project without the package builds the same way. The **Icons** page (`#icon-docs`) lists all 6,070 icons by category and copies the tag of any of them; `node tools/icon-docs.mjs` regenerates it from the package.
152
+ Icons are optional and live in their own package. Install `@aliens-syndicate/icons` and declare it in `.config` under `dependencies:` → `icons:` as `@aliens-syndicate/icons/stroke-rounded: <version>`, where the part after the name is the default style. Icons belong to the markup, with no span and no class: `icon add-01 size-4 blue-500 red-500` names the icon and then, in any order, one of the ten styles, a size, up to two colors (the second paints the light tone of bulk, duotone and twotone) and a state such as `disabled` or `hidden`; `id`, `variant` and `label` are its only attributes. The build draws each icon inline, and a project without the package builds the same way. The **Icons** page (`#icon-docs`) lists all 6,070 icons by category and copies the tag of any of them; `node tools/icon-docs.mjs` regenerates it from the package.
133
153
 
134
- Ready-made Elements are optional too and live in `@aliens-syndicate/elements`; a new project starts without them. Install the package and declare it in `.config` under `dependencies:` → `elements:` with `from: @aliens-syndicate/elements`, and any markup can write `ui-button`, `ui-icon-button`, `ui-badge`, `ui-alert`, `ui-card`, `ui-avatar`, `ui-spinner`, `ui-progress`, `ui-stat`, `ui-accordion`, `ui-empty-state`, `ui-divider`, `ui-text-field`, `ui-checkbox` and `ui-switch` with their properties, as in `ui-button label="Save" variant="ui-button_primary" action="save"`. They are Space files like the Elements of the project: the build validates them, `ai/.map` lists them, and only the Elements a page renders reach `dist/`. Their styles are plain CSS that read the starter tokens, and a project `.style` with the same variant names overrides them. The **Elements** page (`#element-docs`) shows each one live, with its properties and source.
154
+ Ready-made Elements are optional too and live in `@aliens-syndicate/elements`; a new project starts without them. Install the package and declare it in `.config` under `dependencies:` → `elements:` as `@aliens-syndicate/elements: <version>`, and any markup can write `ui-button`, `ui-icon-button`, `ui-badge`, `ui-alert`, `ui-card`, `ui-avatar`, `ui-spinner`, `ui-progress`, `ui-stat`, `ui-accordion`, `ui-empty-state`, `ui-divider`, `ui-text-field`, `ui-checkbox` and `ui-switch` with their properties, as in `ui-button label="Save" variant="ui-button_primary" action="save"`. They are Space files like the Elements of the project: the build validates them, `ai/.map` lists them, and only the Elements a page renders reach `dist/`. Their styles are plain CSS that read the starter tokens, and a project `.style` with the same variant names overrides them. The **Elements** page (`#element-docs`) shows each one live, with its properties and source.
135
155
 
136
156
  #### Logic
137
157
 
@@ -185,7 +205,7 @@ Logic Counter
185
205
 
186
206
  Only the binds that read a value update, and they run before effects and watches. Writes outside an action, as in a `setTimeout` or after a `fetch`, update the page too. A `computed` works in `bind:` and in the `<element>-<name>` id like a signal: `counter-doubled` shows `doubled`. Assigning to a `computed` stops the build, and so does a `watch` that names no signal or computed. An effect that keeps changing what it reads stops at runtime with its name. These words belong to the language, so `import: signal: aliens/core` is optional.
187
207
 
188
- The Reactive Core above comes with every project. Stream operators live in the optional `@aliens-syndicate/reactive` package: run `npm install @aliens-syndicate/reactive`, declare `reactive:` with `from: @aliens-syndicate/reactive` under `dependencies:` in `.config`, and a `.logic` can declare `stream name: type = expression` with 22 operators named after RxJS, like `debounce`, `switchMap`, `combineLatest` and `retry`. Without the package, a `stream` member stops the build and says how to add it. The **Reactive** page of the documentation site (`#reactive-core`) separates both parts and runs a live search with `debounce`.
208
+ The Reactive Core above comes with every project. Stream operators live in the optional `@aliens-syndicate/reactive` package: run `npm install @aliens-syndicate/reactive`, declare it in `.config` under `dependencies:` → `reactive:` as `@aliens-syndicate/reactive: <version>`, and a `.logic` can declare `stream name: type = expression` with 22 operators named after RxJS, like `debounce`, `switchMap`, `combineLatest` and `retry`. Without the package, a `stream` member stops the build and says how to add it. The **Reactive** page of the documentation site (`#reactive-core`) separates both parts and runs a live search with `debounce`.
189
209
 
190
210
  Native tags accept the same short properties as Elements: `variant` becomes `class`, `action` becomes `data-action`, `label` becomes `aria-label` and `text` becomes the tag text. `button` gets `type="button"` when it declares no `type`.
191
211
 
package/README.pt-BR.md CHANGED
@@ -34,6 +34,26 @@ aliens run
34
34
 
35
35
  O comentário no topo do `.config` lista os mesmos comandos, e a página **Instalação** do site (`#installation`) explica cada um passo a passo.
36
36
 
37
+ O `.config` lista o framework e cada pacote com a sua versão, agrupados como no `package.json`: `dependencies:` para o que o app usa e `devDependencies:` para o que só o build usa. Cada seção tem uma linha, `<pacote>: <versão>`; a linha dos ícones traz o estilo padrão depois do nome.
38
+
39
+ ```text
40
+ dependencies:
41
+ framework:
42
+ @aliens-syndicate/framework: 0.1.10
43
+ icons:
44
+ @aliens-syndicate/icons/stroke-rounded: 0.1.0
45
+ elements:
46
+ @aliens-syndicate/elements: 0.1.0
47
+ reactive:
48
+ @aliens-syndicate/reactive: 0.1.0
49
+
50
+ devDependencies:
51
+ utilities:
52
+ @aliens-syndicate/utilities: 0.1.0
53
+ ```
54
+
55
+ O build para quando uma versão difere da instalada e diz como corrigir. O `aliens update` instala as versões mais novas, grava as versões no `package.json` e no `.config` e reescreve a forma antiga com `from:`, e o `aliens doctor` aponta cada diferença.
56
+
37
57
  Para publicar uma nova versão, atualize `version` em `package.json` e execute `npm publish` na raiz, com a conta `aliens-syndicate` logada no npm.
38
58
 
39
59
  O gerador cria a Home em `project/app/pages/home/`, os quatro níveis de Elements e as pastas dos tipos de arquivo da aplicação. Os exemplos comentados do catálogo de heróis vêm da base do motor em `tools/starter/`, independente da aplicação que estiver aberta. O Element `hero-card` reúne `.markup`, `.logic`, `.style` e `.test` em `project/app/elements/molecules/hero-card/`. As pastas `agents/`, `rules/` e `skills/` ficam em `ai/`.
@@ -127,11 +147,11 @@ Style Counter
127
147
  bg-(--primary) text-(--primary-ink)
128
148
  ```
129
149
 
130
- Dentro de um seletor, uma linha escrita como `propriedade: valor` é uma declaração CSS. Por padrão, `.style` aceita apenas CSS normal. Os utilitários são opcionais e ficam num pacote próprio: instale `@aliens-syndicate/utilities` e declare-o no `.config` em `devDependencies:` → `utilities:` com `from: @aliens-syndicate/utilities`. Sem ele, uma linha de utilitários interrompe o build e diz como adicionar o pacote. Com ele, qualquer outra linha lista utilitários com os nomes popularizados por frameworks de CSS existentes: `flex`, `gap-4`, `rounded-lg`, `text-sm`. Variantes como `md:`, `max-lg:`, `hover:` e `dark:` escrevem a regra `@media` ou o seletor, e utilitários como `backdrop-blur-md` e `bg-clip-text` acrescentam as declarações `-webkit-`. Colchetes aceitam qualquer valor, como em `w-[1240px]`, e parênteses leem uma propriedade customizada, como em `text-(--muted)`. Cada `--color-<nome>` dos estilos globais vira uma cor, como em `bg-brand`. Um utilitário desconhecido interrompe o build com o arquivo e a linha. A página **Utilities** do site de documentação (`#utilities-docs`) lista cada classe com o seu CSS; `node tools/utilities-docs.mjs` a gera de novo a partir do catálogo do pacote.
150
+ Dentro de um seletor, uma linha escrita como `propriedade: valor` é uma declaração CSS. Por padrão, `.style` aceita apenas CSS normal. Os utilitários são opcionais e ficam num pacote próprio: instale `@aliens-syndicate/utilities` e declare-o no `.config` em `devDependencies:` → `utilities:` como `@aliens-syndicate/utilities: <versão>`. Sem ele, uma linha de utilitários interrompe o build e diz como adicionar o pacote. Com ele, qualquer outra linha lista utilitários com os nomes popularizados por frameworks de CSS existentes: `flex`, `gap-4`, `rounded-lg`, `text-sm`. Variantes como `md:`, `max-lg:`, `hover:` e `dark:` escrevem a regra `@media` ou o seletor, e utilitários como `backdrop-blur-md` e `bg-clip-text` acrescentam as declarações `-webkit-`. Colchetes aceitam qualquer valor, como em `w-[1240px]`, e parênteses leem uma propriedade customizada, como em `text-(--muted)`. Cada `--color-<nome>` dos estilos globais vira uma cor, como em `bg-brand`. Um utilitário desconhecido interrompe o build com o arquivo e a linha. A página **Utilities** do site de documentação (`#utilities-docs`) lista cada classe com o seu CSS; `node tools/utilities-docs.mjs` a gera de novo a partir do catálogo do pacote.
131
151
 
132
- Os ícones são opcionais e ficam em um pacote próprio. Instale `@aliens-syndicate/icons` e declare no `.config` em `dependencies:` → `icons:` com `from: @aliens-syndicate/icons` e um `style:` padrão. Os ícones pertencem ao markup, sem span e sem classe: `icon add-01 size-4 blue-500 red-500` dá o nome do ícone e depois, em qualquer ordem, um dos dez estilos, um tamanho, até duas cores (a segunda pinta o tom claro do bulk, duotone e twotone) e um estado como `disabled` ou `hidden`; `id`, `variant` e `label` são seus únicos atributos. O build desenha cada ícone inline, e um projeto sem o pacote é gerado do mesmo jeito. A página **Icons** (`#icon-docs`) lista os 6.070 ícones por categoria e copia a tag de qualquer um; `node tools/icon-docs.mjs` a regenera a partir do pacote.
152
+ Os ícones são opcionais e ficam em um pacote próprio. Instale `@aliens-syndicate/icons` e declare no `.config` em `dependencies:` → `icons:` como `@aliens-syndicate/icons/stroke-rounded: <versão>`, em que a parte depois do nome é o estilo padrão. Os ícones pertencem ao markup, sem span e sem classe: `icon add-01 size-4 blue-500 red-500` dá o nome do ícone e depois, em qualquer ordem, um dos dez estilos, um tamanho, até duas cores (a segunda pinta o tom claro do bulk, duotone e twotone) e um estado como `disabled` ou `hidden`; `id`, `variant` e `label` são seus únicos atributos. O build desenha cada ícone inline, e um projeto sem o pacote é gerado do mesmo jeito. A página **Icons** (`#icon-docs`) lista os 6.070 ícones por categoria e copia a tag de qualquer um; `node tools/icon-docs.mjs` a regenera a partir do pacote.
133
153
 
134
- Os Elements prontos também são opcionais e ficam em `@aliens-syndicate/elements`; um projeto novo começa sem eles. Instale o pacote e declare no `.config` em `dependencies:` → `elements:` com `from: @aliens-syndicate/elements`, e qualquer markup pode escrever `ui-button`, `ui-icon-button`, `ui-badge`, `ui-alert`, `ui-card`, `ui-avatar`, `ui-spinner`, `ui-progress`, `ui-stat`, `ui-accordion`, `ui-empty-state`, `ui-divider`, `ui-text-field`, `ui-checkbox` e `ui-switch` com suas propriedades, como em `ui-button label="Salvar" variant="ui-button_primary" action="save"`. Eles são arquivos Space como os Elements do projeto: o build os valida, o `ai/.map` os lista e só os Elements que a página renderiza chegam ao `dist/`. Os estilos são CSS puro que lê os tokens do starter, e um `.style` do projeto com os mesmos nomes de variant os sobrescreve. A página **Elements** (`#element-docs`) mostra cada um ao vivo, com propriedades e código.
154
+ Os Elements prontos também são opcionais e ficam em `@aliens-syndicate/elements`; um projeto novo começa sem eles. Instale o pacote e declare no `.config` em `dependencies:` → `elements:` como `@aliens-syndicate/elements: <versão>`, e qualquer markup pode escrever `ui-button`, `ui-icon-button`, `ui-badge`, `ui-alert`, `ui-card`, `ui-avatar`, `ui-spinner`, `ui-progress`, `ui-stat`, `ui-accordion`, `ui-empty-state`, `ui-divider`, `ui-text-field`, `ui-checkbox` e `ui-switch` com suas propriedades, como em `ui-button label="Salvar" variant="ui-button_primary" action="save"`. Eles são arquivos Space como os Elements do projeto: o build os valida, o `ai/.map` os lista e só os Elements que a página renderiza chegam ao `dist/`. Os estilos são CSS puro que lê os tokens do starter, e um `.style` do projeto com os mesmos nomes de variant os sobrescreve. A página **Elements** (`#element-docs`) mostra cada um ao vivo, com propriedades e código.
135
155
 
136
156
  #### Logic
137
157
 
@@ -185,7 +205,7 @@ Logic Counter
185
205
 
186
206
  Só os binds que leem um valor são atualizados, e eles rodam antes dos effects e watches. Escritas fora de uma action, como num `setTimeout` ou depois de um `fetch`, também atualizam a página. Um `computed` funciona no `bind:` e no id `<element>-<nome>` como um signal: `counter-doubled` exibe `doubled`. Atribuir a um `computed` interrompe o build, assim como um `watch` que não nomeia signal nem computed. Um effect que não para de mudar o que lê é interrompido em tempo de execução com o seu nome. Essas palavras são da linguagem, então `import: signal: aliens/core` é opcional.
187
207
 
188
- O Reactive Core acima vem em todo projeto. Os operadores de stream ficam no pacote opcional `@aliens-syndicate/reactive`: rode `npm install @aliens-syndicate/reactive`, declare `reactive:` com `from: @aliens-syndicate/reactive` em `dependencies:` no `.config`, e um `.logic` pode declarar `stream nome: tipo = expressão` com 22 operadores com os nomes do RxJS, como `debounce`, `switchMap`, `combineLatest` e `retry`. Sem o pacote, um membro `stream` interrompe o build e diz como adicioná-lo. A página **Reactive** do site de documentação (`#reactive-core`) separa as duas partes e roda uma busca ao vivo com `debounce`.
208
+ O Reactive Core acima vem em todo projeto. Os operadores de stream ficam no pacote opcional `@aliens-syndicate/reactive`: rode `npm install @aliens-syndicate/reactive`, declare no `.config` em `dependencies:` → `reactive:` como `@aliens-syndicate/reactive: <versão>`, e um `.logic` pode declarar `stream nome: tipo = expressão` com 22 operadores com os nomes do RxJS, como `debounce`, `switchMap`, `combineLatest` e `retry`. Sem o pacote, um membro `stream` interrompe o build e diz como adicioná-lo. A página **Reactive** do site de documentação (`#reactive-core`) separa as duas partes e roda uma busca ao vivo com `debounce`.
189
209
 
190
210
  Tags nativas aceitam as mesmas propriedades curtas dos Elements: `variant` vira `class`, `action` vira `data-action`, `label` vira `aria-label` e `text` vira o texto da tag. `button` recebe `type="button"` quando não declara `type`.
191
211
 
package/README.zh-CN.md CHANGED
@@ -34,6 +34,26 @@ aliens run
34
34
 
35
35
  `.config` 顶部的注释列出了同样的命令,网站的 **安装** 页面(`#installation`)会一步步讲解。
36
36
 
37
+ `.config` 列出框架以及每个包和它的版本,分组方式与 `package.json` 相同:`dependencies:` 放应用使用的包,`devDependencies:` 放只有构建使用的包。每个分节只有一行 `<包>: <版本>`;图标那一行在包名后面写默认样式。
38
+
39
+ ```text
40
+ dependencies:
41
+ framework:
42
+ @aliens-syndicate/framework: 0.1.10
43
+ icons:
44
+ @aliens-syndicate/icons/stroke-rounded: 0.1.0
45
+ elements:
46
+ @aliens-syndicate/elements: 0.1.0
47
+ reactive:
48
+ @aliens-syndicate/reactive: 0.1.0
49
+
50
+ devDependencies:
51
+ utilities:
52
+ @aliens-syndicate/utilities: 0.1.0
53
+ ```
54
+
55
+ 当版本与已安装的版本不一致时,构建会停止并说明如何修复。`aliens update` 会安装最新版本,把版本写入 `package.json` 和 `.config`,并改写旧的 `from:` 写法;`aliens doctor` 会指出每一处差异。
56
+
37
57
  要发布新版本,请更新 `package.json` 中的 `version`,并在已登录 `aliens-syndicate` 账号的情况下于根目录运行 `npm publish`。
38
58
 
39
59
  生成器会在 `project/app/pages/home/` 中创建首页,并创建四个 Element 层级以及应用各文件类型的文件夹。英雄目录的注释示例来自引擎基础目录 `tools/starter/`,与当前打开的应用无关。`hero-card` Element 在 `project/app/elements/molecules/hero-card/` 中包含 `.markup`、`.logic`、`.style` 和 `.test`。`agents/`、`rules/` 和 `skills/` 文件夹位于 `ai/`。
@@ -127,11 +147,11 @@ Style Counter
127
147
  bg-(--primary) text-(--primary-ink)
128
148
  ```
129
149
 
130
- 在选择器内部,写成 `属性: 值` 的行是 CSS 声明。默认情况下 `.style` 只接受普通 CSS。工具类是可选的,位于独立的包中:安装 `@aliens-syndicate/utilities`,并在 `.config` 的 `devDependencies:` → `utilities:` 下声明 `from: @aliens-syndicate/utilities`。没有该包时,工具类行会让构建停止并提示如何添加它。有了该包,其他行列出现有 CSS 框架普及的工具类名称:`flex`、`gap-4`、`rounded-lg`、`text-sm`。`md:`、`max-lg:`、`hover:` 和 `dark:` 等变体会写出 `@media` 规则或选择器,`backdrop-blur-md` 和 `bg-clip-text` 等工具类会补上 `-webkit-` 声明。方括号接受任意值,例如 `w-[1240px]`;圆括号读取自定义属性,例如 `text-(--muted)`。全局样式中的每个 `--color-<名称>` 都会成为颜色,例如 `bg-brand`。未知的工具类会让构建停止,并给出文件和行号。文档站点的 **Utilities** 页面(`#utilities-docs`)列出了每个类及其 CSS;`node tools/utilities-docs.mjs` 会根据该包的目录重新生成该页面。
150
+ 在选择器内部,写成 `属性: 值` 的行是 CSS 声明。默认情况下 `.style` 只接受普通 CSS。工具类是可选的,位于独立的包中:安装 `@aliens-syndicate/utilities`,并在 `.config` 的 `devDependencies:` → `utilities:` 下写 `@aliens-syndicate/utilities: <版本>`。没有该包时,工具类行会让构建停止并提示如何添加它。有了该包,其他行列出现有 CSS 框架普及的工具类名称:`flex`、`gap-4`、`rounded-lg`、`text-sm`。`md:`、`max-lg:`、`hover:` 和 `dark:` 等变体会写出 `@media` 规则或选择器,`backdrop-blur-md` 和 `bg-clip-text` 等工具类会补上 `-webkit-` 声明。方括号接受任意值,例如 `w-[1240px]`;圆括号读取自定义属性,例如 `text-(--muted)`。全局样式中的每个 `--color-<名称>` 都会成为颜色,例如 `bg-brand`。未知的工具类会让构建停止,并给出文件和行号。文档站点的 **Utilities** 页面(`#utilities-docs`)列出了每个类及其 CSS;`node tools/utilities-docs.mjs` 会根据该包的目录重新生成该页面。
131
151
 
132
- 图标是可选的,位于独立的包中。安装 `@aliens-syndicate/icons`,在 `.config` 的 `dependencies:` → `icons:` 下写 `from: @aliens-syndicate/icons` 和默认的 `style:`。图标属于 markup,不需要 span,也不需要 class:`icon add-01 size-4 blue-500 red-500` 先写图标名称,再按任意顺序写十种样式之一、尺寸、最多两种颜色(第二种用于 bulk、duotone 和 twotone 的浅色部分),以及 `disabled` 或 `hidden` 等状态;`id`、`variant` 和 `label` 是它仅有的属性。构建会把每个图标内联绘制,没有该包的项目照常构建。**Icons**页面(`#icon-docs`)按分类列出全部 6,070 个图标,并可复制任意图标的标签;`node tools/icon-docs.mjs` 会根据该包重新生成它。
152
+ 图标是可选的,位于独立的包中。安装 `@aliens-syndicate/icons`,在 `.config` 的 `dependencies:` → `icons:` 下写 `@aliens-syndicate/icons/stroke-rounded: <版本>`,包名后面的部分就是默认样式。图标属于 markup,不需要 span,也不需要 class:`icon add-01 size-4 blue-500 red-500` 先写图标名称,再按任意顺序写十种样式之一、尺寸、最多两种颜色(第二种用于 bulk、duotone 和 twotone 的浅色部分),以及 `disabled` 或 `hidden` 等状态;`id`、`variant` 和 `label` 是它仅有的属性。构建会把每个图标内联绘制,没有该包的项目照常构建。**Icons**页面(`#icon-docs`)按分类列出全部 6,070 个图标,并可复制任意图标的标签;`node tools/icon-docs.mjs` 会根据该包重新生成它。
133
153
 
134
- 现成的 Element 同样是可选的,位于 `@aliens-syndicate/elements` 包中;新项目默认不包含它们。安装该包,并在 `.config` 的 `dependencies:` → `elements:` 下写入 `from: @aliens-syndicate/elements`,任何 markup 就可以使用 `ui-button`、`ui-icon-button`、`ui-badge`、`ui-alert`、`ui-card`、`ui-avatar`、`ui-spinner`、`ui-progress`、`ui-stat`、`ui-accordion`、`ui-empty-state`、`ui-divider`、`ui-text-field`、`ui-checkbox` 和 `ui-switch` 及其属性,例如 `ui-button label="保存" variant="ui-button_primary" action="save"`。它们和项目中的 Element 一样是 Space 文件:构建会校验它们,`ai/.map` 会列出它们,只有页面实际渲染的 Element 才会进入 `dist/`。它们的样式是读取 starter 令牌的纯 CSS,项目中使用相同 variant 名称的 `.style` 可以覆盖它们。**Elements** 页面(`#element-docs`)实时展示每个 Element 及其属性和源码。
154
+ 现成的 Element 同样是可选的,位于 `@aliens-syndicate/elements` 包中;新项目默认不包含它们。安装该包,并在 `.config` 的 `dependencies:` → `elements:` 下写入 `@aliens-syndicate/elements: <版本>`,任何 markup 就可以使用 `ui-button`、`ui-icon-button`、`ui-badge`、`ui-alert`、`ui-card`、`ui-avatar`、`ui-spinner`、`ui-progress`、`ui-stat`、`ui-accordion`、`ui-empty-state`、`ui-divider`、`ui-text-field`、`ui-checkbox` 和 `ui-switch` 及其属性,例如 `ui-button label="保存" variant="ui-button_primary" action="save"`。它们和项目中的 Element 一样是 Space 文件:构建会校验它们,`ai/.map` 会列出它们,只有页面实际渲染的 Element 才会进入 `dist/`。它们的样式是读取 starter 令牌的纯 CSS,项目中使用相同 variant 名称的 `.style` 可以覆盖它们。**Elements** 页面(`#element-docs`)实时展示每个 Element 及其属性和源码。
135
155
 
136
156
  #### Logic
137
157
 
@@ -185,7 +205,7 @@ Logic Counter
185
205
 
186
206
  只有读取该值的 bind 会更新,并且它们先于 effect 和 watch 运行。在 action 之外的写入,例如 `setTimeout` 中或 `fetch` 之后,也会更新页面。`computed` 与 signal 一样可用于 `bind:` 和 `<element>-<名称>` 形式的 id:`counter-doubled` 显示 `doubled`。给 `computed` 赋值会中止构建,`watch` 指向不存在的 signal 或 computed 时也会中止。不断修改自身所读取值的 effect 会在运行时以其名称报错并停止。这些都是语言本身的关键字,因此 `import: signal: aliens/core` 可以省略。
187
207
 
188
- 上述 Reactive Core 内置于每个项目。stream 操作符位于可选包 `@aliens-syndicate/reactive`:运行 `npm install @aliens-syndicate/reactive`,在 `.config` 的 `dependencies:` 下声明 `reactive:` 并写上 `from: @aliens-syndicate/reactive`,`.logic` 即可声明 `stream 名称: 类型 = 表达式`,使用 22 个沿用 RxJS 名称的操作符,例如 `debounce`、`switchMap`、`combineLatest` 和 `retry`。没有该包时,`stream` 成员会中止构建并说明如何添加。文档站点的 **Reactive** 页面(`#reactive-core`)将两部分分开展示,并运行一个带 `debounce` 的实时搜索。
208
+ 上述 Reactive Core 内置于每个项目。stream 操作符位于可选包 `@aliens-syndicate/reactive`:运行 `npm install @aliens-syndicate/reactive`,在 `.config` 的 `dependencies:` → `reactive:` 下写 `@aliens-syndicate/reactive: <版本>`,`.logic` 即可声明 `stream 名称: 类型 = 表达式`,使用 22 个沿用 RxJS 名称的操作符,例如 `debounce`、`switchMap`、`combineLatest` 和 `retry`。没有该包时,`stream` 成员会中止构建并说明如何添加。文档站点的 **Reactive** 页面(`#reactive-core`)将两部分分开展示,并运行一个带 `debounce` 的实时搜索。
189
209
 
190
210
  原生标签接受与 Element 相同的简写属性:`variant` 变为 `class`,`action` 变为 `data-action`,`label` 变为 `aria-label`,`text` 变为标签文本。未声明 `type` 的 `button` 会获得 `type="button"`。
191
211
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aliens-syndicate/cli",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
4
4
  "description": "CLI for Aliens, the AI-era front-end framework written in Space.",
5
5
  "license": "MIT",
6
6
  "author": "Aliens Syndicate",
@@ -30,10 +30,12 @@
30
30
  "publishConfig": {
31
31
  "access": "public"
32
32
  },
33
+ "dependencies": {
34
+ "@aliens-syndicate/icons": "0.1.0",
35
+ "@aliens-syndicate/elements": "0.1.0",
36
+ "@aliens-syndicate/reactive": "0.1.0"
37
+ },
33
38
  "devDependencies": {
34
- "@aliens-syndicate/elements": "^0.1.0",
35
- "@aliens-syndicate/icons": "^0.1.0",
36
- "@aliens-syndicate/reactive": "^0.1.0",
37
- "@aliens-syndicate/utilities": "^0.1.0"
39
+ "@aliens-syndicate/utilities": "0.1.0"
38
40
  }
39
41
  }
package/tools/build.mjs CHANGED
@@ -1,8 +1,9 @@
1
+ import { existsSync } from 'node:fs';
1
2
  import { cp, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
2
3
  import { basename, dirname, extname, join, relative, resolve } from 'node:path';
3
4
  import { createRequire, stripTypeScriptTypes } from 'node:module';
4
5
  import { pathToFileURL } from 'node:url';
5
- import { exampleMarker, namedKinds, sharedDirectory } from './project-layout.mjs';
6
+ import { dependencyGroups, dependencySections, exampleMarker, namedKinds, parseDependency, sharedDirectory } from './project-layout.mjs';
6
7
  import spaceSyntax from './vscode-space/syntax.cjs';
7
8
 
8
9
  const { analyzeSpace, htmlTags, isSpaceComment, roles: highlightRoleOf } = spaceSyntax;
@@ -114,35 +115,40 @@ const settings = name => Object.fromEntries(config.find(node => node.value === n
114
115
  }) ?? []);
115
116
  const { entry, assets: assetDirectory, shared: configuredShared, styles, agent: map, environment } = settings('files');
116
117
  const { default: defaultLocale, detection, directory: languageDirectory } = settings('language');
117
- // Extensions are grouped as in package.json: dependencies: for the packages the app uses (icons, elements, reactive)
118
- // and devDependencies: for the ones only the build uses (utilities). Each one is a section of its own inside the group,
119
- // with from: and its settings under it; the build reads both groups the same way.
120
- const extensionNames = ['utilities', 'icons', 'elements', 'reactive'];
121
- const extensionGroups = ['dependencies', 'devDependencies'];
118
+ // The framework and the extensions are listed as in package.json: dependencies: for what the app uses (framework,
119
+ // icons, elements, reactive) and devDependencies: for what only the build uses (utilities). Each section holds one
120
+ // line, "<package>[/<variant>]: <version>", read by parseDependency in project-layout.mjs. The icon style is the
121
+ // variant of the icons package, as in @aliens-syndicate/icons/stroke-rounded: 0.1.0.
122
+ const extensionNames = dependencySections.filter(name => name !== 'framework');
122
123
  const legacyExtension = config.find(node => [...extensionNames, 'style'].includes(node.value.replace(/:$/, '')));
123
124
  if (legacyExtension) {
124
125
  const name = legacyExtension.value === 'style:' ? 'utilities' : legacyExtension.value.slice(0, -1);
125
126
  const group = name === 'utilities' ? 'devDependencies' : 'dependencies';
126
- throw new Error(`${legacyExtension.location}: extensions now live under dependencies: or devDependencies:. Write ${group}:\n ${name}:\n from: @aliens-syndicate/${name}`);
127
+ throw new Error(`${legacyExtension.location}: extensions now live under dependencies: or devDependencies:, each with its version. Write ${group}:\n ${name}:\n @aliens-syndicate/${name}${name === 'icons' ? '/stroke-rounded' : ''}: <version>\n(aliens update rewrites .config for you.)`);
127
128
  }
128
129
  const extensionSettings = {};
129
- for (const group of config.filter(node => extensionGroups.includes(node.value.replace(/:$/, '')))) {
130
- if (!group.value.endsWith(':')) throw new Error(`${group.location}: ${group.value.split(':')[0]}: takes its extensions on the lines below it.`);
130
+ for (const group of config.filter(node => dependencyGroups.includes(node.value.replace(/:$/, '')))) {
131
+ if (!group.value.endsWith(':')) throw new Error(`${group.location}: ${group.value.split(':')[0]}: takes its sections on the lines below it.`);
131
132
  for (const node of group.children) {
132
133
  const name = node.value.replace(/:$/, '');
133
- if (!extensionNames.includes(name) || !node.value.endsWith(':')) throw new Error(`${node.location}: ${group.value} accepts ${extensionNames.join(', ')}, not "${node.value}".`);
134
+ if (!dependencySections.includes(name) || !node.value.endsWith(':')) throw new Error(`${node.location}: ${group.value} accepts ${dependencySections.join(', ')}, not "${node.value}".`);
134
135
  if (extensionSettings[name]) throw new Error(`${node.location}: ${name}: is already declared; keep it in dependencies: or devDependencies:, not both.`);
135
- extensionSettings[name] = Object.fromEntries(node.children.map(child => {
136
- const [, key, value] = pair.exec(child.value) ?? [];
137
- if (!key) throw new Error(`${child.location}: ${name}: takes key: value lines, like from: @aliens-syndicate/${name}.`);
138
- return [key, value];
139
- }));
136
+ const legacy = Object.fromEntries(node.children.map(child => pair.exec(child.value)?.slice(1) ?? []).filter(([key]) => ['from', 'style'].includes(key)));
137
+ if (legacy.from) {
138
+ throw new Error(`${node.location}: ${name}: now takes one line with the package and its version, like ${legacy.from}${legacy.style ? `/${legacy.style}` : ''}: <version>. ` +
139
+ 'aliens update rewrites .config for you.');
140
+ }
141
+ const dependency = node.children.length === 1 && !node.children[0].children.length ? parseDependency(node.children[0].value) : null;
142
+ if (!dependency) throw new Error(`${node.location}: ${name}: takes one line, "<package>: <version>", like @aliens-syndicate/${name === 'icons' ? 'icons/stroke-rounded' : name}: 0.1.0.`);
143
+ if (dependency.variant && name !== 'icons') throw new Error(`${node.children[0].location}: only icons takes a variant after the package name (its style); write ${dependency.name}: ${dependency.version}.`);
144
+ extensionSettings[name] = { ...dependency, location: node.children[0].location };
140
145
  }
141
146
  }
142
- const { from: iconPackage, style: configuredIconStyle } = extensionSettings.icons ?? {};
143
- const { from: stylePackage } = extensionSettings.utilities ?? {};
144
- const { from: elementPackage } = extensionSettings.elements ?? {};
145
- const { from: reactivePackage } = extensionSettings.reactive ?? {};
147
+ // framework: records the version of Aliens the project follows; the build loads nothing for it.
148
+ const { name: iconPackage, variant: configuredIconStyle } = extensionSettings.icons ?? {};
149
+ const { name: stylePackage } = extensionSettings.utilities ?? {};
150
+ const { name: elementPackage } = extensionSettings.elements ?? {};
151
+ const { name: reactivePackage } = extensionSettings.reactive ?? {};
146
152
  // console: prints the Space code of the page in the browser console when it opens, only in the local and dev
147
153
  // environments (build: environment:), each with its own toggle, true by default. Other environments never show it.
148
154
  // "console: false" (or true) on one line sets both; "console:" with local: and dev: under it sets each one.
@@ -164,31 +170,40 @@ const showCode = ['local', 'dev'].includes(buildEnvironment) && (consoleSettings
164
170
  // elements (usually @aliens-syndicate/elements) adds ready-made Elements that any markup can render; reactive (usually
165
171
  // @aliens-syndicate/reactive) adds stream members to .logic, with operators like debounce and switchMap.
166
172
  async function loadExtension(section, name) {
173
+ const { version, location } = extensionSettings[section];
167
174
  let entry;
168
175
  try {
169
176
  entry = /^\.{1,2}\//.test(name) ? join(workspace, name, 'index.mjs') : createRequire(join(workspace, 'package.json')).resolve(name);
170
177
  } catch {
171
- throw new Error(`.config: ${section}: from: ${name} is not installed. Run npm install ${name}.`);
178
+ throw new Error(`${location}: ${name} is not installed. Run npm install ${name}@${version}.`);
179
+ }
180
+ // The version in .config must be the installed one, so every machine builds with the same packages.
181
+ let directory = dirname(entry);
182
+ while (!existsSync(join(directory, 'package.json')) && dirname(directory) !== directory) directory = dirname(directory);
183
+ const installed = existsSync(join(directory, 'package.json')) ? JSON.parse(await readFile(join(directory, 'package.json'), 'utf8')).version : null;
184
+ if (installed && installed !== version) {
185
+ throw new Error(`${location}: .config declares ${name} ${version}, but ${installed} is installed. Write ${installed} in .config, ` +
186
+ `or run npm install ${name}@${version}. aliens update updates both.`);
172
187
  }
173
188
  return import(pathToFileURL(entry).href);
174
189
  }
175
190
  const iconModule = iconPackage ? await loadExtension('icons', iconPackage) : null;
176
191
  const styleModule = stylePackage ? await loadExtension('utilities', stylePackage) : null;
177
- if (styleModule && typeof styleModule.resolveUtility !== 'function') throw new Error(`.config: utilities: from: ${stylePackage} is not an Aliens utilities package.`);
192
+ if (styleModule && typeof styleModule.resolveUtility !== 'function') throw new Error(`${extensionSettings.utilities.location}: ${stylePackage} is not an Aliens utilities package.`);
178
193
  const elementModule = elementPackage ? await loadExtension('elements', elementPackage) : null;
179
- if (elementModule && typeof elementModule.elementsDirectory !== 'string') throw new Error(`.config: elements: from: ${elementPackage} is not an Aliens elements package.`);
194
+ if (elementModule && typeof elementModule.elementsDirectory !== 'string') throw new Error(`${extensionSettings.elements.location}: ${elementPackage} is not an Aliens elements package.`);
180
195
  const reactiveModule = reactivePackage ? await loadExtension('reactive', reactivePackage) : null;
181
- if (reactiveModule && typeof reactiveModule.createReactive !== 'function') throw new Error(`.config: reactive: from: ${reactivePackage} is not an Aliens reactive package.`);
196
+ if (reactiveModule && typeof reactiveModule.createReactive !== 'function') throw new Error(`${extensionSettings.reactive.location}: ${reactivePackage} is not an Aliens reactive package.`);
182
197
  const noStyle = (where, what) => new Error(`${where}: ${what} need the utilities package. Write CSS as "property: value", or run ` +
183
- 'npm install @aliens-syndicate/utilities and declare it in .config:\ndevDependencies:\n utilities:\n from: @aliens-syndicate/utilities');
198
+ 'npm install @aliens-syndicate/utilities and declare it in .config with the installed version:\ndevDependencies:\n utilities:\n @aliens-syndicate/utilities: <version>');
184
199
  // Without the utilities package, .style reads plain CSS declarations only.
185
200
  const resolveUtility = (token, options) => styleModule ? styleModule.resolveUtility(token, options) : { error: 'no utilities package' };
186
201
  const iconRenderer = iconModule?.createIconRenderer();
187
202
  const iconCatalog = iconModule ? await iconModule.readCatalog() : null;
188
203
  const iconStyle = iconRenderer ? configuredIconStyle ?? 'stroke-rounded' : null;
189
- if (iconRenderer && !iconRenderer.styles.includes(iconStyle)) throw new Error(`.config: icons: style: accepts ${iconRenderer.styles.join(', ')}.`);
204
+ if (iconRenderer && !iconRenderer.styles.includes(iconStyle)) throw new Error(`${extensionSettings.icons.location}: the icon style after ${iconPackage}/ is one of ${iconRenderer.styles.join(', ')}.`);
190
205
  const noIcons = where => new Error(`${where}: icons need a package. Run npm install @aliens-syndicate/icons and declare it in .config:\n` +
191
- 'dependencies:\n icons:\n from: @aliens-syndicate/icons\n style: stroke-rounded');
206
+ 'dependencies:\n icons:\n @aliens-syndicate/icons/stroke-rounded: <version>');
192
207
  // The icon tag: "icon <name> [style] [size-<n>] [color] [second color] [disabled] [hidden]", with id, variant and label
193
208
  // as its only attributes. The first word names the icon and the others may come in any order: one of the ten styles
194
209
  // (the one in .config by default), a size utility, up to two colors (the icon and the second tone of bulk, duotone and
@@ -672,7 +687,7 @@ function render(file, rootProps = {}, ancestry = [], parentScope = null) {
672
687
  }
673
688
 
674
689
  // Inside a selector, "property: value" is a CSS declaration. With the utilities package declared in .config
675
- // (devDependencies: utilities: from: @aliens-syndicate/utilities), 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
690
+ // (devDependencies: utilities: @aliens-syndicate/utilities: <version>), 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
676
691
  // hover: and dark: rewrite the selector; responsive variants such as md: and max-lg: become @media rules, written
677
692
  // after the rest of the file from the widest max-* to the narrowest and then from the narrowest min-width up.
678
693
  const declarationLine = /^-{0,2}[A-Za-z][\w-]*:\s+\S/;
@@ -797,7 +812,7 @@ function compileLogic(file) {
797
812
  // stream <name>: <type> = <expression>, or "=" at the end of the line and the expression indented below it.
798
813
  const flow = /^stream ([A-Za-z]\w*): (.+?) =(?: (.+))?$/.exec(member.value);
799
814
  if (flow) {
800
- if (!reactiveModule) throw new Error(`${member.location}: stream needs the reactive package. Run npm install @aliens-syndicate/reactive and declare it in .config:\ndependencies:\n reactive:\n from: @aliens-syndicate/reactive`);
815
+ if (!reactiveModule) throw new Error(`${member.location}: stream needs the reactive package. Run npm install @aliens-syndicate/reactive and declare it in .config with the installed version:\ndependencies:\n reactive:\n @aliens-syndicate/reactive: <version>`);
801
816
  if (Boolean(flow[3]) === Boolean(member.children.length)) throw new Error(`${member.location}: write the stream after "=", on the same line or indented below it.`);
802
817
  const expression = flow[3] ?? block(member).code;
803
818
  try { new Function(`return (${expression});`); } catch { throw new Error(`${member.location}: invalid expression.`); }
@@ -3,6 +3,8 @@ import { spawn } from 'node:child_process';
3
3
  import { existsSync, readFileSync } from 'node:fs';
4
4
  import { dirname, join, resolve } from 'node:path';
5
5
  import { createInterface } from 'node:readline/promises';
6
+ import { dependencyGroups, dependencyLine, parseDependency } from './project-layout.mjs';
7
+ export { dependencyLine };
6
8
 
7
9
  // Messages follow the system language (ALIENS_LANG overrides it): English, Portuguese, Spanish or Chinese.
8
10
  export const language = (() => {
@@ -22,13 +24,14 @@ export const defaultPort = 5151;
22
24
  export const projectToolFiles = ['build.mjs', 'watch.mjs', 'runtime.mjs', 'project-layout.mjs'];
23
25
  export const projectToolDirectories = ['vscode-space'];
24
26
 
25
- // The optional extensions a project can declare in .config under <group>: <section>: from:. The group follows
26
- // package.json: dependencies for the packages the app uses, devDependencies for the ones only the build uses.
27
+ // The optional extensions a project can declare in .config under <group>: <section>:, as one line with the package
28
+ // and its version, like @aliens-syndicate/elements: 0.1.0 (the icons line adds the style: …/icons/stroke-rounded).
29
+ // The group follows package.json: dependencies for the packages the app uses, devDependencies for the build only.
27
30
  // aliens new offers each one with "yes" as the answer by default, except those marked off: reactive adds stream
28
31
  // operators, while the Reactive Core (signal, computed, effect, watch, batch and cleanup) comes with every project.
29
32
  export const extensions = [
30
33
  { section: 'utilities', group: 'devDependencies', name: '@aliens-syndicate/utilities' },
31
- { section: 'icons', group: 'dependencies', name: '@aliens-syndicate/icons', extra: ' style: stroke-rounded\n' },
34
+ { section: 'icons', group: 'dependencies', name: '@aliens-syndicate/icons', variant: 'stroke-rounded' },
32
35
  { section: 'elements', group: 'dependencies', name: '@aliens-syndicate/elements' },
33
36
  { section: 'reactive', group: 'dependencies', name: '@aliens-syndicate/reactive', off: true }
34
37
  ];
@@ -135,15 +138,15 @@ export function requireProject() {
135
138
  }
136
139
 
137
140
  // .config is Space: sections at the first level and key: value pairs under them, nested by indentation (dependencies:
138
- // and devDependencies: hold one section per extension). A key with nothing after the colon opens a section.
139
- // Comments start with #.
141
+ // and devDependencies: hold one section per package, with "<package>: <version>" inside). A key with nothing after the
142
+ // colon opens a section. Comments start with #.
140
143
  export function readConfig(root) {
141
144
  const config = {};
142
145
  const stack = [{ indent: -1, values: config }];
143
146
  for (const line of readFileSync(join(root, '.config'), 'utf8').split(/\r?\n/)) {
144
147
  const value = line.trim();
145
148
  if (!value || value.startsWith('#')) continue;
146
- const pair = /^([\w.-]+):\s*(.*)$/.exec(value);
149
+ const pair = /^([^\s:]+):\s*(.*)$/.exec(value);
147
150
  if (!pair) continue;
148
151
  const indent = line.length - line.trimStart().length;
149
152
  while (stack.at(-1).indent >= indent) stack.pop();
@@ -157,13 +160,23 @@ export function readConfig(root) {
157
160
  return config;
158
161
  }
159
162
 
160
- // The extensions .config declares under dependencies: and devDependencies:, as { name, group, from, ...settings }.
161
- export const extensionGroups = ['dependencies', 'devDependencies'];
162
- export function configExtensions(config) {
163
+ // The packages .config declares under dependencies: and devDependencies:, as { name (the section), group, from (the
164
+ // package), variant, version }. An older .config with from: and style: lines reads with legacy: true and no version,
165
+ // so doctor can point to aliens update, which rewrites it. framework: is the version of Aliens, not an extension.
166
+ export const extensionGroups = dependencyGroups;
167
+ function configPackages(config) {
163
168
  return extensionGroups.flatMap(group => Object.entries(config?.[group] ?? {})
164
- .filter(([, values]) => typeof values === 'object' && values.from)
165
- .map(([name, values]) => ({ ...values, name, group })));
169
+ .filter(([, values]) => typeof values === 'object')
170
+ .map(([name, values]) => {
171
+ if (values.from) return { name, group, from: values.from, variant: values.style ?? null, version: null, legacy: true };
172
+ const [line] = Object.entries(values).map(([key, value]) => `${key}: ${value}`);
173
+ const dependency = line ? parseDependency(line) : null;
174
+ return dependency ? { name, group, from: dependency.name, variant: dependency.variant, version: dependency.version } : null;
175
+ })
176
+ .filter(Boolean));
166
177
  }
178
+ export const configExtensions = config => configPackages(config).filter(entry => entry.name !== 'framework');
179
+ export const configFramework = config => configPackages(config).find(entry => entry.name === 'framework') ?? null;
167
180
 
168
181
  // npm is npm.cmd on Windows, which spawn only runs through the shell.
169
182
  export function runCommand(command, args, options = {}) {
package/tools/cli.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  import { existsSync, readFileSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
5
  import {
6
- CliError, bold, captureCommand, cliPackage, configExtensions, cliRoot, cliVersion, installedVersion, cyan, defaultPort, dim, findProject, parseFlags, pick, readConfig, red, requireProject, runBuild
6
+ CliError, bold, captureCommand, cliPackage, configExtensions, configFramework, cliRoot, cliVersion, installedVersion, cyan, defaultPort, dim, findProject, parseFlags, pick, readConfig, red, requireProject, runBuild
7
7
  } from './cli-shared.mjs';
8
8
 
9
9
  const commands = [
@@ -57,13 +57,13 @@ const commands = [
57
57
 
58
58
  const labels = {
59
59
  en: { usage: 'Usage', commands: 'Commands', options: 'Options', aliases: 'alias', more: 'Run aliens <command> --help to see its options.',
60
- unknown: 'Unknown command "{command}".', suggestion: 'Did you mean {suggestion}?', cli: 'Aliens CLI', node: 'Node.js', os: 'System', project: 'Project', packages: 'Packages', packageManager: 'Package Manager', extensions: 'extensions', package: 'Package', version: 'Version', missing: 'not installed', repository: 'this repository', outside: 'Run aliens version inside a project to see its packages.' },
60
+ unknown: 'Unknown command "{command}".', suggestion: 'Did you mean {suggestion}?', cli: 'Aliens CLI', framework: 'Framework', node: 'Node.js', os: 'System', project: 'Project', packages: 'Packages', packageManager: 'Package Manager', extensions: 'extensions', package: 'Package', version: 'Version', missing: 'not installed', repository: 'this repository', outside: 'Run aliens version inside a project to see its packages.' },
61
61
  pt: { usage: 'Uso', commands: 'Comandos', options: 'Opções', aliases: 'atalho', more: 'Rode aliens <comando> --help para ver as opções dele.',
62
- unknown: 'Comando desconhecido "{command}".', suggestion: 'Você quis dizer {suggestion}?', cli: 'Aliens CLI', node: 'Node.js', os: 'Sistema', project: 'Projeto', packages: 'Pacotes', packageManager: 'Gerenciador de pacotes', extensions: 'extensões', package: 'Pacote', version: 'Versão', missing: 'não instalado', repository: 'este repositório', outside: 'Rode aliens version dentro de um projeto para ver os pacotes dele.' },
62
+ unknown: 'Comando desconhecido "{command}".', suggestion: 'Você quis dizer {suggestion}?', cli: 'Aliens CLI', framework: 'Framework', node: 'Node.js', os: 'Sistema', project: 'Projeto', packages: 'Pacotes', packageManager: 'Gerenciador de pacotes', extensions: 'extensões', package: 'Pacote', version: 'Versão', missing: 'não instalado', repository: 'este repositório', outside: 'Rode aliens version dentro de um projeto para ver os pacotes dele.' },
63
63
  es: { usage: 'Uso', commands: 'Comandos', options: 'Opciones', aliases: 'atajo', more: 'Ejecuta aliens <comando> --help para ver sus opciones.',
64
- unknown: 'Comando desconocido "{command}".', suggestion: '¿Quisiste decir {suggestion}?', cli: 'Aliens CLI', node: 'Node.js', os: 'Sistema', project: 'Proyecto', packages: 'Paquetes', packageManager: 'Gestor de paquetes', extensions: 'extensiones', package: 'Paquete', version: 'Versión', missing: 'no instalado', repository: 'este repositorio', outside: 'Ejecuta aliens version dentro de un proyecto para ver sus paquetes.' },
64
+ unknown: 'Comando desconocido "{command}".', suggestion: '¿Quisiste decir {suggestion}?', cli: 'Aliens CLI', framework: 'Framework', node: 'Node.js', os: 'Sistema', project: 'Proyecto', packages: 'Paquetes', packageManager: 'Gestor de paquetes', extensions: 'extensiones', package: 'Paquete', version: 'Versión', missing: 'no instalado', repository: 'este repositorio', outside: 'Ejecuta aliens version dentro de un proyecto para ver sus paquetes.' },
65
65
  zh: { usage: '用法', commands: '命令', options: '选项', aliases: '别名', more: '运行 aliens <命令> --help 查看该命令的选项。',
66
- unknown: '未知命令“{command}”。', suggestion: '你是想输入 {suggestion} 吗?', cli: 'Aliens CLI', node: 'Node.js', os: '系统', project: '项目', packages: '依赖包', packageManager: '包管理器', extensions: '扩展', package: '依赖包', version: '版本', missing: '未安装', repository: '本仓库', outside: '在项目中运行 aliens version 可查看其依赖包。' }
66
+ unknown: '未知命令“{command}”。', suggestion: '你是想输入 {suggestion} 吗?', cli: 'Aliens CLI', framework: 'Framework', node: 'Node.js', os: '系统', project: '项目', packages: '依赖包', packageManager: '包管理器', extensions: '扩展', package: '依赖包', version: '版本', missing: '未安装', repository: '本仓库', outside: '在项目中运行 aliens version 可查看其依赖包。' }
67
67
  };
68
68
  const label = pick(labels);
69
69
 
@@ -117,6 +117,8 @@ async function version(args) {
117
117
  [label.packageManager, npm.code === 0 ? `npm ${npm.output}` : '—'], [label.os, `${process.platform} ${process.arch}`]];
118
118
  const extensionPackages = configExtensions(config).map(extension => extension.from).filter(name => !/^\.{1,2}\//.test(name));
119
119
  if (config) info.push([label.project, `${config.project?.name ?? '?'} ${config.project?.version ?? ''}`.trim()]);
120
+ const framework = configFramework(config);
121
+ if (framework) info.push([label.framework, framework.version]);
120
122
 
121
123
  console.log('');
122
124
  banner.forEach((line, index) => console.log(shade([22, 28, 34, 40, 46][index], line)));
package/tools/create.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import { copyFile, cp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises';
3
3
  import { basename, join, relative, resolve } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
- import { createProjectDirectories, styleLayers } from './project-layout.mjs';
5
+ import { createProjectDirectories, dependencyLine, styleLayers } from './project-layout.mjs';
6
6
  import {
7
7
  CliError, ask, bold, cliPackage, cliVersion, confirm, cyan, defaultPort, dim, extensions, green, interactive, kebab,
8
8
  latestVersion, ok, parseFlags, pick, projectToolFiles, runCommand, validName, warn
@@ -14,28 +14,28 @@ const text = {
14
14
  utilities: 'Use utility classes in .style ({package})?', icons: 'Use the icon library ({package})?', elements: 'Use ready-made Elements ({package})?',
15
15
  reactive: 'Add stream operators like debounce and switchMap ({package})? signal, computed and effect already come with Aliens.',
16
16
  creating: 'Creating the Aliens project in {path}', created: 'Aliens project created in {path}', installing: 'Installing the packages with npm…',
17
- unpublished: '{package} is not on npm yet, so the project starts without it.', installFailed: 'npm install failed. Enter the folder and run npm install.',
17
+ unpublished: '{package} is not on npm yet, so the project starts without it.', offline: 'npm did not answer for {package}, so the project starts without it.', installFailed: 'npm install failed. Enter the folder and run npm install.',
18
18
  skipped: 'Packages not installed (--skip-install). Enter the folder and run npm install.', next: 'Next steps:' },
19
19
  pt: { usage: 'Uso: aliens new <nome-do-projeto>', name: 'Qual é o nome do projeto?', fallbackName: 'meu-app-aliens',
20
20
  badName: 'Use palavras minúsculas separadas por hífen no nome do projeto, como meu-app.', exists: 'A pasta {path} já existe.',
21
21
  utilities: 'Usar classes utilitárias no .style ({package})?', icons: 'Usar a biblioteca de ícones ({package})?', elements: 'Usar Elements prontos ({package})?',
22
22
  reactive: 'Adicionar operadores de stream como debounce e switchMap ({package})? signal, computed e effect já vêm com o Aliens.',
23
23
  creating: 'Criando o projeto Aliens em {path}', created: 'Projeto Aliens criado em {path}', installing: 'Instalando os pacotes com o npm…',
24
- unpublished: '{package} ainda não está no npm, então o projeto começa sem ele.', installFailed: 'O npm install falhou. Entre na pasta e rode npm install.',
24
+ unpublished: '{package} ainda não está no npm, então o projeto começa sem ele.', offline: 'O npm não respondeu sobre {package}, então o projeto começa sem ele.', installFailed: 'O npm install falhou. Entre na pasta e rode npm install.',
25
25
  skipped: 'Pacotes não instalados (--skip-install). Entre na pasta e rode npm install.', next: 'Próximos passos:' },
26
26
  es: { usage: 'Uso: aliens new <nombre-del-proyecto>', name: '¿Cómo se llama tu proyecto?', fallbackName: 'mi-app-aliens',
27
27
  badName: 'Usa palabras en minúsculas separadas por guiones en el nombre del proyecto, como mi-app.', exists: 'La carpeta {path} ya existe.',
28
28
  utilities: '¿Usar clases utilitarias en .style ({package})?', icons: '¿Usar la biblioteca de íconos ({package})?', elements: '¿Usar Elements listos ({package})?',
29
29
  reactive: '¿Añadir operadores de stream como debounce y switchMap ({package})? signal, computed y effect ya vienen con Aliens.',
30
30
  creating: 'Creando el proyecto Aliens en {path}', created: 'Proyecto Aliens creado en {path}', installing: 'Instalando los paquetes con npm…',
31
- unpublished: '{package} todavía no está en npm, así que el proyecto empieza sin él.', installFailed: 'npm install falló. Entra en la carpeta y ejecuta npm install.',
31
+ unpublished: '{package} todavía no está en npm, así que el proyecto empieza sin él.', offline: 'npm no respondió sobre {package}, así que el proyecto empieza sin él.', installFailed: 'npm install falló. Entra en la carpeta y ejecuta npm install.',
32
32
  skipped: 'Paquetes no instalados (--skip-install). Entra en la carpeta y ejecuta npm install.', next: 'Próximos pasos:' },
33
33
  zh: { usage: '用法:aliens new <项目名称>', name: '项目叫什么名字?', fallbackName: 'my-aliens-app',
34
34
  badName: '项目名称请使用以连字符分隔的小写单词,例如 my-app。', exists: '文件夹 {path} 已存在。',
35
35
  utilities: '在 .style 中使用工具类({package})?', icons: '使用图标库({package})?', elements: '使用现成的 Elements({package})?',
36
36
  reactive: '添加 debounce、switchMap 等 stream 操作符({package})?signal、computed 和 effect 已内置于 Aliens。',
37
37
  creating: '正在 {path} 中创建 Aliens 项目', created: 'Aliens 项目已创建于 {path}', installing: '正在用 npm 安装依赖包…',
38
- unpublished: '{package} 尚未发布到 npm,项目将先不包含它。', installFailed: 'npm install 失败。请进入文件夹运行 npm install。',
38
+ unpublished: '{package} 尚未发布到 npm,项目将先不包含它。', offline: 'npm 没有返回 {package} 的信息,项目将先不包含它。', installFailed: 'npm install 失败。请进入文件夹运行 npm install。',
39
39
  skipped: '未安装依赖包(--skip-install)。请进入文件夹运行 npm install。', next: '下一步:' }
40
40
  };
41
41
  const t = (key, values = {}) => Object.entries(values).reduce((message, [name, value]) => message.replaceAll(`{${name}}`, value), pick(text)[key]);
@@ -82,12 +82,14 @@ The configuration lives in \`.config\` and the build generates the \`ai/.map\` i
82
82
  The Home includes the style library, with tokens in \`project/styles/settings/\`, components in \`project/styles/components/\` and themes in \`project/styles/settings/theme.style\`.
83
83
  Add a \`:root[data-theme="name"]\` block to that file and run the build to make the theme available in the picker.
84
84
 
85
- \`.style\` reads plain CSS (\`property: value\`). To write utility classes like \`flex gap-4 md:flex-row\`, run \`npm install @aliens-syndicate/utilities\` and add to \`.config\`:
85
+ \`.config\` lists the framework and every package with its version, under \`dependencies:\` and \`devDependencies:\` as in \`package.json\`. The build stops when a version differs from the installed one, and \`aliens update\` updates both.
86
+
87
+ \`.style\` reads plain CSS (\`property: value\`). To write utility classes like \`flex gap-4 md:flex-row\`, run \`npm install -D @aliens-syndicate/utilities\` and add to \`.config\`, with the installed version:
86
88
 
87
89
  \`\`\`
88
90
  devDependencies:
89
91
  utilities:
90
- from: @aliens-syndicate/utilities
92
+ @aliens-syndicate/utilities: 0.1.0
91
93
  \`\`\`
92
94
 
93
95
  To use buttons, badges, alerts, cards and fields written in Space, run \`npm install @aliens-syndicate/elements\` and add to \`.config\`:
@@ -95,7 +97,7 @@ To use buttons, badges, alerts, cards and fields written in Space, run \`npm ins
95
97
  \`\`\`
96
98
  dependencies:
97
99
  elements:
98
- from: @aliens-syndicate/elements
100
+ @aliens-syndicate/elements: 0.1.0
99
101
  \`\`\`
100
102
 
101
103
  \`signal\`, \`computed\`, \`effect\`, \`watch\`, \`batch\` and \`cleanup:\` come with Aliens. For stream operators like \`debounce\`, \`switchMap\` and \`combineLatest\`, run \`npm install @aliens-syndicate/reactive\` and add to \`.config\`:
@@ -103,14 +105,14 @@ dependencies:
103
105
  \`\`\`
104
106
  dependencies:
105
107
  reactive:
106
- from: @aliens-syndicate/reactive
108
+ @aliens-syndicate/reactive: 0.1.0
107
109
  \`\`\`
108
110
 
109
111
  Pages and Elements live in \`project/app/pages/\` and \`project/app/elements/\`.
110
112
  `;
111
113
  }
112
114
 
113
- function config(name, chosen) {
115
+ function config(name, chosen, versions) {
114
116
  return `${configGuide}
115
117
  project:
116
118
  name: ${name}
@@ -133,8 +135,11 @@ console:
133
135
 
134
136
  serve:
135
137
  port: ${defaultPort}
136
- ${['dependencies', 'devDependencies'].map(group => chosen.filter(extension => extension.group === group)).filter(list => list.length)
137
- .map(list => `\n${list[0].group}:\n${list.map(extension => ` ${extension.section}:\n from: ${extension.name}\n${extension.extra ?? ''}`).join('')}`).join('')}
138
+ ${['dependencies', 'devDependencies'].map(group => [
139
+ ...(group === 'dependencies' ? [{ section: 'framework', name: '@aliens-syndicate/framework', version: cliVersion }] : []),
140
+ ...chosen.filter(extension => extension.group === group).map(extension => ({ ...extension, version: versions.get(extension.name) }))
141
+ ]).filter(list => list.length)
142
+ .map((list, index) => `\n${index ? 'devDependencies' : 'dependencies'}:\n${list.map(entry => ` ${entry.section}:\n ${dependencyLine(entry)}\n`).join('')}`).join('')}
138
143
  language:
139
144
  directory: project/language
140
145
  default: en-US
@@ -219,22 +224,21 @@ export async function create(args) {
219
224
 
220
225
  try {
221
226
  await copyStarter(destination, name);
222
- // Before installing, keep only the packages npm already publishes, so the build never asks for a missing one.
227
+ // .config and package.json carry the exact version of each package, so npm asks for every one, even with
228
+ // --skip-install. A package npm does not publish, or cannot answer for, stays out of the project.
223
229
  const packages = [{ name: cliPackage }, ...chosen];
224
230
  const versions = new Map();
225
- if (!flags['skip-install']) {
226
- await Promise.all(packages.map(async entry => versions.set(entry.name, await latestVersion(entry.name))));
227
- for (const extension of [...chosen]) {
228
- if (versions.get(extension.name)) continue;
229
- console.log(warn(t('unpublished', { package: extension.name })));
230
- chosen.splice(chosen.indexOf(extension), 1);
231
- }
231
+ await Promise.all(packages.map(async entry => versions.set(entry.name, await latestVersion(entry.name))));
232
+ versions.set(cliPackage, versions.get(cliPackage) || cliVersion);
233
+ for (const extension of [...chosen]) {
234
+ if (versions.get(extension.name)) continue;
235
+ console.log(warn(t(versions.get(extension.name) === false ? 'unpublished' : 'offline', { package: extension.name })));
236
+ chosen.splice(chosen.indexOf(extension), 1);
232
237
  }
233
238
  // package.json splits the packages the same way .config does; the CLI is a devDependency.
234
- const range = entry => entry.name === cliPackage && flags['skip-install'] ? `^${cliVersion}` : versions.get(entry.name) ? `^${versions.get(entry.name)}` : 'latest';
235
239
  const group = name => Object.fromEntries([{ name: cliPackage, group: 'devDependencies' }, ...chosen]
236
- .filter(entry => entry.group === name && (flags['skip-install'] || versions.get(entry.name)))
237
- .map(entry => [entry.name, range(entry)]));
240
+ .filter(entry => entry.group === name)
241
+ .map(entry => [entry.name, versions.get(entry.name)]));
238
242
  const dependencies = group('dependencies');
239
243
  const manifest = {
240
244
  name, version: '0.1.0', private: true, type: 'module',
@@ -242,7 +246,7 @@ export async function create(args) {
242
246
  ...(Object.keys(dependencies).length ? { dependencies } : {}), devDependencies: group('devDependencies')
243
247
  };
244
248
  await writeFile(join(destination, 'package.json'), JSON.stringify(manifest, null, 2) + '\n', { flag: 'wx' });
245
- await writeFile(join(destination, '.config'), config(name, chosen), { flag: 'wx' });
249
+ await writeFile(join(destination, '.config'), config(name, chosen, versions), { flag: 'wx' });
246
250
  } catch (error) {
247
251
  await rm(destination, { recursive: true, force: true });
248
252
  throw error;
package/tools/doctor.mjs CHANGED
@@ -5,7 +5,7 @@ import { join } from 'node:path';
5
5
  import { toolsDifferences } from './update.mjs';
6
6
  import {
7
7
  bold, captureCommand, installedVersion, cliPackage, cliRoot, cliVersion, compareVersions, cyan, defaultPort, dim, findProject, green,
8
- configExtensions, latestVersion, minimumNode, parseFlags, pick, readConfig, red, runBuild, yellow
8
+ configExtensions, configFramework, latestVersion, minimumNode, parseFlags, pick, readConfig, red, runBuild, yellow
9
9
  } from './cli-shared.mjs';
10
10
 
11
11
  const text = {
@@ -16,7 +16,7 @@ const text = {
16
16
  noProjectFix: 'Create one with aliens new <name>, or open a project folder', project: 'Project {name} in {path}',
17
17
  config: '.config is valid', configBad: '.config: {problem}', entryMissing: 'files: entry: {file} does not exist', tools: 'tools/ matches the CLI {version}',
18
18
  toolsOld: 'tools/ differs from the CLI {version} in {files}', toolsFix: 'aliens update', toolsSelf: 'tools/ is the CLI itself (framework repository)',
19
- extension: '{name} {version}', extensionMissing: '{name} is declared in .config ({section}:) but is not installed', extensionFix: 'npm install {name}',
19
+ extension: '{name} {version}', extensionMissing: '{name} is declared in .config ({section}:) but is not installed', extensionFix: 'npm install {name}', extensionVersion: '{name}: .config declares {declared}, but {version} is installed', extensionLegacy: '{name}: .config still uses from:, without the version', updateFix: 'aliens update', framework: 'framework {version} in .config', frameworkOld: '.config lists framework {declared}, but the CLI is {version}',
20
20
  port: 'Port {port} is free for aliens run', portUsed: 'Port {port} is in use', portDenied: 'Port {port} needs administrator rights on this system',
21
21
  portFix: 'aliens run --port <number>, or set serve: port: in .config', build: 'aliens build passes', buildBad: 'aliens build fails: {error}',
22
22
  buildFix: 'Fix the file and line in the message, then run aliens build', fine: 'No issues found.', issues: '{count} issue(s) found.', warnings: '{count} warning(s).' },
@@ -27,7 +27,7 @@ const text = {
27
27
  noProjectFix: 'Crie um com aliens new <nome> ou abra a pasta de um projeto', project: 'Projeto {name} em {path}',
28
28
  config: '.config válido', configBad: '.config: {problem}', entryMissing: 'files: entry: {file} não existe', tools: 'tools/ igual ao da CLI {version}',
29
29
  toolsOld: 'tools/ diferente da CLI {version} em {files}', toolsFix: 'aliens update', toolsSelf: 'tools/ é a própria CLI (repositório do framework)',
30
- extension: '{name} {version}', extensionMissing: '{name} está declarado no .config ({section}:) mas não está instalado', extensionFix: 'npm install {name}',
30
+ extension: '{name} {version}', extensionMissing: '{name} está declarado no .config ({section}:) mas não está instalado', extensionFix: 'npm install {name}', extensionVersion: '{name}: o .config declara {declared}, mas a {version} está instalada', extensionLegacy: '{name}: o .config ainda usa from:, sem a versão', updateFix: 'aliens update', framework: 'framework {version} no .config', frameworkOld: 'O .config lista o framework {declared}, mas a CLI é a {version}',
31
31
  port: 'Porta {port} livre para o aliens run', portUsed: 'A porta {port} está em uso', portDenied: 'A porta {port} exige permissão de administrador neste sistema',
32
32
  portFix: 'aliens run --port <número> ou defina serve: port: no .config', build: 'aliens build passa', buildBad: 'aliens build falha: {error}',
33
33
  buildFix: 'Corrija o arquivo e a linha da mensagem e rode aliens build', fine: 'Nenhum problema encontrado.', issues: '{count} problema(s) encontrado(s).', warnings: '{count} aviso(s).' },
@@ -38,7 +38,7 @@ const text = {
38
38
  noProjectFix: 'Crea uno con aliens new <nombre> o abre la carpeta de un proyecto', project: 'Proyecto {name} en {path}',
39
39
  config: '.config es válido', configBad: '.config: {problem}', entryMissing: 'files: entry: {file} no existe', tools: 'tools/ coincide con la CLI {version}',
40
40
  toolsOld: 'tools/ difiere de la CLI {version} en {files}', toolsFix: 'aliens update', toolsSelf: 'tools/ es la propia CLI (repositorio del framework)',
41
- extension: '{name} {version}', extensionMissing: '{name} está declarado en .config ({section}:) pero no está instalado', extensionFix: 'npm install {name}',
41
+ extension: '{name} {version}', extensionMissing: '{name} está declarado en .config ({section}:) pero no está instalado', extensionFix: 'npm install {name}', extensionVersion: '{name}: .config declara {declared}, pero está instalada la {version}', extensionLegacy: '{name}: .config todavía usa from:, sin la versión', updateFix: 'aliens update', framework: 'framework {version} en .config', frameworkOld: '.config indica framework {declared}, pero la CLI es la {version}',
42
42
  port: 'Puerto {port} libre para aliens run', portUsed: 'El puerto {port} está en uso', portDenied: 'El puerto {port} requiere permisos de administrador en este sistema',
43
43
  portFix: 'aliens run --port <número> o define serve: port: en .config', build: 'aliens build pasa', buildBad: 'aliens build falla: {error}',
44
44
  buildFix: 'Corrige el archivo y la línea del mensaje y ejecuta aliens build', fine: 'No se encontraron problemas.', issues: '{count} problema(s) encontrado(s).', warnings: '{count} aviso(s).' },
@@ -49,7 +49,7 @@ const text = {
49
49
  noProjectFix: '用 aliens new <名称> 创建一个,或打开项目文件夹', project: '项目 {name},位于 {path}',
50
50
  config: '.config 有效', configBad: '.config:{problem}', entryMissing: 'files: entry: {file} 不存在', tools: 'tools/ 与 CLI {version} 一致',
51
51
  toolsOld: 'tools/ 与 CLI {version} 不同:{files}', toolsFix: 'aliens update', toolsSelf: 'tools/ 就是 CLI 本身(框架仓库)',
52
- extension: '{name} {version}', extensionMissing: '{name} 已在 .config({section}:)中声明,但尚未安装', extensionFix: 'npm install {name}',
52
+ extension: '{name} {version}', extensionMissing: '{name} 已在 .config({section}:)中声明,但尚未安装', extensionFix: 'npm install {name}', extensionVersion: '{name}:.config 声明的是 {declared},但安装的是 {version}', extensionLegacy: '{name}:.config 仍在使用 from:,没有写版本', updateFix: 'aliens update', framework: '.config 中的 framework {version}', frameworkOld: '.config 中的 framework 是 {declared},但 CLI 是 {version}',
53
53
  port: '端口 {port} 可供 aliens run 使用', portUsed: '端口 {port} 已被占用', portDenied: '在此系统上,端口 {port} 需要管理员权限',
54
54
  portFix: 'aliens run --port <端口>,或在 .config 中设置 serve: port:', build: 'aliens build 通过', buildBad: 'aliens build 失败:{error}',
55
55
  buildFix: '按消息中的文件和行号修复后,运行 aliens build', fine: '未发现问题。', issues: '发现 {count} 个问题。', warnings: '{count} 个警告。' }
@@ -114,10 +114,18 @@ export async function doctor(args) {
114
114
  else report('warn', t('toolsOld', { version: cliVersion, files: changed.slice(0, 3).join(', ') + (changed.length > 3 ? '…' : '') }), t('toolsFix'));
115
115
  }
116
116
 
117
- for (const { name: section, group, from } of configExtensions(config)) {
117
+ // framework: follows the CLI whose tools/ the project carries; aliens update writes it.
118
+ const framework = configFramework(config);
119
+ if (framework?.version === cliVersion) report('ok', t('framework', { version: framework.version }));
120
+ else if (framework) report('warn', t('frameworkOld', { declared: framework.version, version: cliVersion }), t('updateFix'));
121
+
122
+ // Each package of .config must be installed in the version .config declares; the build stops otherwise.
123
+ for (const { name: section, group, from, version: declared, legacy } of configExtensions(config)) {
118
124
  const version = installedVersion(root, from);
119
- if (version) report('ok', t('extension', { name: from, version }));
120
- else report('fail', t('extensionMissing', { name: from, section: `${group}: ${section}` }), t('extensionFix', { name: group === 'devDependencies' ? `-D ${from}` : from }));
125
+ if (!version) report('fail', t('extensionMissing', { name: from, section: `${group}: ${section}` }), t('extensionFix', { name: `${group === 'devDependencies' ? '-D ' : ''}${from}${declared ? `@${declared}` : ''}` }));
126
+ else if (legacy) report('warn', t('extensionLegacy', { name: from }), t('updateFix'));
127
+ else if (version !== 'local' && version !== declared) report('fail', t('extensionVersion', { name: from, declared, version }), t('updateFix'));
128
+ else report('ok', t('extension', { name: from, version }));
121
129
  }
122
130
 
123
131
  const port = Number(config?.serve?.port ?? defaultPort);
@@ -1,15 +1,15 @@
1
1
  // Generates the Icons page (project/app/pages/icon-docs) from the catalog of the icon package that .config declares
2
- // under dependencies: icons: from:. The sidebar lists every category; the runtime fills each one with its icons when the page opens,
2
+ // under dependencies: icons: (the line @aliens-syndicate/icons/<style>: <version>). The sidebar lists every category; the runtime fills each one with its icons when the page opens,
3
3
  // so the catalog stays out of index.html. Run it after updating the package: node tools/icon-docs.mjs
4
- import { mkdir, readFile, writeFile } from 'node:fs/promises';
4
+ import { mkdir, writeFile } from 'node:fs/promises';
5
5
  import { createRequire } from 'node:module';
6
6
  import { join, resolve } from 'node:path';
7
7
  import { pathToFileURL } from 'node:url';
8
+ import { configExtensions, readConfig } from './cli-shared.mjs';
8
9
 
9
10
  const workspace = resolve(import.meta.dirname, '..');
10
- const config = await readFile(join(workspace, '.config'), 'utf8');
11
- const from = /^ {3}icons:\n(?: {6}.*\n)*? {6}from: (.+)$/m.exec(config)?.[1].trim();
12
- if (!from) throw new Error('icon-docs: declare the icon package in .config under dependencies: icons: from:.');
11
+ const { from, version } = configExtensions(readConfig(workspace)).find(extension => extension.name === 'icons') ?? {};
12
+ if (!from || !version) throw new Error('icon-docs: declare the icon package in .config under dependencies: icons:, like @aliens-syndicate/icons/stroke-rounded: 0.1.0.');
13
13
  const entry = /^\.{1,2}\//.test(from) ? join(workspace, from, 'index.mjs') : createRequire(join(workspace, 'package.json')).resolve(from);
14
14
  const { createIconRenderer, readCatalog } = await import(pathToFileURL(entry).href);
15
15
  const { categories, icons } = await readCatalog();
@@ -90,10 +90,10 @@ for (const [key, code] of [['usageInstall', 'npm install @aliens-syndicate/icons
90
90
  add(7, 'code');
91
91
  add(8, 'span={dependencies:} variant="icon-docs-code-line"');
92
92
  add(8, 'span={ icons:} variant="icon-docs-code-line"');
93
- add(8, 'span={ from: @aliens-syndicate/icons} variant="icon-docs-code-line"');
94
93
  add(8, 'span variant="icon-docs-code-line"');
95
- add(9, 'span={ style: }');
94
+ add(9, `span={ ${from}/}`);
96
95
  add(9, 'span={stroke-rounded} data-icon-style-name');
96
+ add(9, `span={: ${version}}`);
97
97
  } else {
98
98
  add(6, 'pre variant="icon-docs-code" tabindex="0"');
99
99
  add(7, 'code');
@@ -26,6 +26,23 @@ export const exampleMarker = '# Aliens example: Hero';
26
26
  export const styleLayers = ['settings', 'tools', 'generic', 'elements', 'objects', 'components', 'utilities'];
27
27
  export const elementLevels = ['atoms', 'molecules', 'organisms', 'templates'];
28
28
 
29
+ // .config lists the framework and the extensions as in package.json: dependencies: for what the app uses and
30
+ // devDependencies: for what only the build uses. Each section holds one line, "<package>[/<variant>]: <version>": the
31
+ // package is an npm name or a local folder (./path), the variant picks an option of the package (the icon style, as in
32
+ // @aliens-syndicate/icons/stroke-rounded) and the version is the one installed, quoted or not.
33
+ export const dependencyGroups = ['dependencies', 'devDependencies'];
34
+ export const dependencySections = ['framework', 'utilities', 'icons', 'elements', 'reactive'];
35
+ export function parseDependency(line) {
36
+ const version = '"?(\\d+\\.\\d+\\.\\d+[\\w.+-]*)"?';
37
+ const local = new RegExp(`^(\\.{1,2}\\/[^\\s:]+):\\s*${version}$`).exec(line.trim());
38
+ if (local) return { name: local[1], variant: null, version: local[2], spec: local[1] };
39
+ const match = new RegExp(`^((?:@[a-z0-9][\\w.-]*\\/)?[a-z0-9][\\w.-]*)(?:\\/([a-z0-9][\\w-]*))?:\\s*${version}$`, 'i').exec(line.trim());
40
+ if (!match) return null;
41
+ const [, name, variant = null, installed] = match;
42
+ return { name, variant, version: installed, spec: variant ? `${name}/${variant}` : name };
43
+ }
44
+ export const dependencyLine = ({ name, variant, version }) => `${variant ? `${name}/${variant}` : name}: ${version}`;
45
+
29
46
  export async function createProjectDirectories(workspace) {
30
47
  const directories = [
31
48
  'project/app/pages',
@@ -8,5 +8,5 @@ Rule Architecture
8
8
  # Compose atoms into molecules, organisms, and templates. A reusable Element does not depend on a page.
9
9
  # Keep the .markup, .logic, .style, and .test files of an Element together in its folder.
10
10
  # Use .style for element stylesheets and the global layers declared in project/styles/main.style.
11
- # In .style, write plain CSS as property: value. Utility class names, like flex gap-4 md:flex-row, need npm install @aliens-syndicate/utilities and devDependencies: utilities: from: @aliens-syndicate/utilities in .config.
12
- # Ready-made Elements, like ui-button and ui-card, need npm install @aliens-syndicate/elements and dependencies: elements: from: @aliens-syndicate/elements in .config; ai/.map then lists them.
11
+ # In .style, write plain CSS as property: value. Utility class names, like flex gap-4 md:flex-row, need npm install @aliens-syndicate/utilities and devDependencies: utilities: @aliens-syndicate/utilities: <version> in .config.
12
+ # Ready-made Elements, like ui-button and ui-card, need npm install @aliens-syndicate/elements and dependencies: elements: @aliens-syndicate/elements: <version> in .config; ai/.map then lists them.
package/tools/update.mjs CHANGED
@@ -2,32 +2,34 @@
2
2
  import { existsSync } from 'node:fs';
3
3
  import { cp, readdir, readFile } from 'node:fs/promises';
4
4
  import { join, relative } from 'node:path';
5
+ import { writeFile } from 'node:fs/promises';
5
6
  import {
6
7
  bold, cliPackage, cliRoot, installedVersion, cliVersion, compareVersions, cyan, dim, green, latestVersion, parseFlags, pick,
7
8
  projectToolDirectories, projectToolFiles, red, requireProject, runCommand, yellow, CliError
8
9
  } from './cli-shared.mjs';
10
+ import { dependencyGroups, dependencyLine, parseDependency } from './project-layout.mjs';
9
11
 
10
12
  const text = {
11
13
  en: { tools: 'Project tools', packages: 'Packages', update: 'UPDATE', same: 'tools/ already matches the CLI {version}.',
12
14
  self: 'This is the framework repository: its tools/ is the CLI itself.', none: 'No @aliens-syndicate package to update.',
13
15
  current: '{name} {version} is the latest', newer: '{name} {from} → {to}', local: '{name} comes from {spec} and is not updated from npm',
14
16
  offline: 'Could not reach npm to check {name}.', unpublished: '{name} is not published on npm.', installing: 'Running npm install…', installFailed: 'npm install failed. Fix the error above and run aliens update again.',
15
- dryRun: 'Dry run: nothing was changed. Run aliens update to apply.', done: 'Project updated.', cliNewer: 'Aliens CLI {latest} is available (you have {version}): npm install -g {package}@latest' },
17
+ dryRun: 'Dry run: nothing was changed. Run aliens update to apply.', config: '.config', configLine: '{section}: {line}', configSame: '.config already lists the installed versions.', done: 'Project updated.', cliNewer: 'Aliens CLI {latest} is available (you have {version}): npm install -g {package}@latest' },
16
18
  pt: { tools: 'Ferramentas do projeto', packages: 'Pacotes', update: 'ATUALIZADO', same: 'tools/ já está igual ao da CLI {version}.',
17
19
  self: 'Este é o repositório do framework: o tools/ dele é a própria CLI.', none: 'Nenhum pacote @aliens-syndicate para atualizar.',
18
20
  current: '{name} {version} é a mais recente', newer: '{name} {from} → {to}', local: '{name} vem de {spec} e não é atualizado pelo npm',
19
21
  offline: 'Não foi possível consultar o npm para {name}.', unpublished: '{name} não está publicado no npm.', installing: 'Rodando npm install…', installFailed: 'O npm install falhou. Corrija o erro acima e rode aliens update de novo.',
20
- dryRun: 'Simulação: nada foi alterado. Rode aliens update para aplicar.', done: 'Projeto atualizado.', cliNewer: 'A Aliens CLI {latest} está disponível (você tem a {version}): npm install -g {package}@latest' },
22
+ dryRun: 'Simulação: nada foi alterado. Rode aliens update para aplicar.', config: '.config', configLine: '{section}: {line}', configSame: 'O .config já lista as versões instaladas.', done: 'Projeto atualizado.', cliNewer: 'A Aliens CLI {latest} está disponível (você tem a {version}): npm install -g {package}@latest' },
21
23
  es: { tools: 'Herramientas del proyecto', packages: 'Paquetes', update: 'ACTUALIZADO', same: 'tools/ ya coincide con la CLI {version}.',
22
24
  self: 'Este es el repositorio del framework: su tools/ es la propia CLI.', none: 'Ningún paquete @aliens-syndicate para actualizar.',
23
25
  current: '{name} {version} es la más reciente', newer: '{name} {from} → {to}', local: '{name} viene de {spec} y no se actualiza desde npm',
24
26
  offline: 'No se pudo consultar npm para {name}.', unpublished: '{name} no está publicado en npm.', installing: 'Ejecutando npm install…', installFailed: 'npm install falló. Corrige el error de arriba y ejecuta aliens update otra vez.',
25
- dryRun: 'Simulación: no se cambió nada. Ejecuta aliens update para aplicar.', done: 'Proyecto actualizado.', cliNewer: 'La Aliens CLI {latest} está disponible (tienes la {version}): npm install -g {package}@latest' },
27
+ dryRun: 'Simulación: no se cambió nada. Ejecuta aliens update para aplicar.', config: '.config', configLine: '{section}: {line}', configSame: '.config ya lista las versiones instaladas.', done: 'Proyecto actualizado.', cliNewer: 'La Aliens CLI {latest} está disponible (tienes la {version}): npm install -g {package}@latest' },
26
28
  zh: { tools: '项目工具', packages: '依赖包', update: '已更新', same: 'tools/ 已与 CLI {version} 一致。',
27
29
  self: '这是框架仓库:它的 tools/ 就是 CLI 本身。', none: '没有需要更新的 @aliens-syndicate 包。',
28
30
  current: '{name} {version} 已是最新', newer: '{name} {from} → {to}', local: '{name} 来自 {spec},不会从 npm 更新',
29
31
  offline: '无法连接 npm 检查 {name}。', unpublished: '{name} 尚未发布到 npm。', installing: '正在运行 npm install…', installFailed: 'npm install 失败。请修复上面的错误后再次运行 aliens update。',
30
- dryRun: '试运行:没有做任何更改。运行 aliens update 以应用。', done: '项目已更新。', cliNewer: 'Aliens CLI {latest} 已发布(当前为 {version}):npm install -g {package}@latest' }
32
+ dryRun: '试运行:没有做任何更改。运行 aliens update 以应用。', config: '.config', configLine: '{section}: {line}', configSame: '.config 已列出已安装的版本。', done: '项目已更新。', cliNewer: 'Aliens CLI {latest} 已发布(当前为 {version}):npm install -g {package}@latest' }
31
33
  };
32
34
  const t = (key, values = {}) => Object.entries(values).reduce((message, [name, value]) => message.replaceAll(`{${name}}`, value), pick(text)[key]);
33
35
 
@@ -51,6 +53,67 @@ export async function toolsDifferences(root) {
51
53
  }
52
54
 
53
55
 
56
+ // .config keeps one "<package>: <version>" line in each section of dependencies: and devDependencies:. This rewrites
57
+ // the older from: and style: lines into that form and writes the installed version of every package. framework: takes
58
+ // the version of the CLI, whose tools/ the project now carries; in the framework repository, tools/ is that CLI.
59
+ async function syncConfig(root, dryRun) {
60
+ const path = join(root, '.config');
61
+ const lines = (await readFile(path, 'utf8')).split(/\r?\n/);
62
+ const output = [];
63
+ const changes = [];
64
+ let group = null;
65
+ let hasFramework = false;
66
+ for (let index = 0; index < lines.length; index++) {
67
+ const line = lines[index];
68
+ const indent = line.length - line.trimStart().length;
69
+ if (line.trim() && indent === 0) group = dependencyGroups.find(name => line.trim() === `${name}:`) ?? null;
70
+ const section = group && indent > 0 && /^\s+([\w-]+):\s*$/.exec(line)?.[1];
71
+ if (!section) {
72
+ output.push(line);
73
+ continue;
74
+ }
75
+ const children = [];
76
+ let blanks = 0;
77
+ while (index + 1 < lines.length && (!lines[index + 1].trim() || lines[index + 1].length - lines[index + 1].trimStart().length > indent)) {
78
+ if (lines[index + 1].trim()) {
79
+ children.push(lines[index + 1].trim());
80
+ blanks = 0;
81
+ } else blanks++;
82
+ index++;
83
+ }
84
+ // Blank lines after the section belong to what follows it.
85
+ index -= blanks;
86
+ if (section === 'framework') hasFramework = true;
87
+ const legacy = Object.fromEntries(children.map(child => /^(from|style):\s*(.+)$/.exec(child)?.slice(1) ?? []).filter(([key]) => key));
88
+ const current = legacy.from ? { name: legacy.from, variant: legacy.style ?? null, version: null } : parseDependency(children[0] ?? '');
89
+ const version = !current ? null
90
+ : section === 'framework' ? cliVersion
91
+ : /^\.{1,2}\//.test(current.name) ? current.version : installedVersion(root, current.name) ?? current.version;
92
+ output.push(line);
93
+ if (!current || !version) {
94
+ output.push(...children.map(child => ' '.repeat(indent + 3) + child));
95
+ continue;
96
+ }
97
+ const next = dependencyLine({ ...current, version });
98
+ output.push(' '.repeat(indent + 3) + next);
99
+ if (legacy.from || children.length !== 1 || children[0] !== next) changes.push({ section, line: next });
100
+ }
101
+ // A project created before framework: existed gets it at the top of dependencies:.
102
+ if (!hasFramework) {
103
+ const line = dependencyLine({ name: '@aliens-syndicate/framework', version: cliVersion });
104
+ const at = output.indexOf('dependencies:');
105
+ if (at >= 0) output.splice(at + 1, 0, ' framework:', ` ${line}`);
106
+ else {
107
+ const before = ['devDependencies:', 'language:'].map(name => output.indexOf(name)).find(position => position >= 0) ?? output.length;
108
+ output.splice(before, 0, 'dependencies:', ' framework:', ` ${line}`, '');
109
+ }
110
+ changes.unshift({ section: 'framework', line });
111
+ }
112
+ for (const { section, line } of changes) console.log(`${green(t('update').padEnd(11))}${t('configLine', { section, line })}`);
113
+ if (!changes.length) console.log(dim(t('configSame')));
114
+ else if (!dryRun) await writeFile(path, output.join('\n'));
115
+ }
116
+
54
117
  export async function update(args) {
55
118
  const { flags } = parseFlags(args, { booleans: ['dry-run'] });
56
119
  const dryRun = Boolean(flags['dry-run']);
@@ -97,11 +160,14 @@ export async function update(args) {
97
160
  console.log(dim(t('installing')));
98
161
  for (const [group, packages] of Object.entries(wanted)) {
99
162
  if (!packages.length) continue;
100
- const code = await runCommand('npm', ['install', ...(group === 'devDependencies' ? ['--save-dev'] : []), ...packages], { cwd: root });
163
+ const code = await runCommand('npm', ['install', '--save-exact', ...(group === 'devDependencies' ? ['--save-dev'] : []), ...packages], { cwd: root });
101
164
  if (code) throw new CliError(red(t('installFailed')));
102
165
  }
103
166
  }
104
167
 
168
+ console.log('\n' + bold(t('config')));
169
+ await syncConfig(root, dryRun);
170
+
105
171
  const latestCli = await latestVersion(cliPackage);
106
172
  if (latestCli && compareVersions(cliVersion, latestCli) < 0) {
107
173
  console.log('\n' + yellow(t('cliNewer', { latest: latestCli, version: cliVersion, package: cliPackage })));
@@ -5,11 +5,11 @@ import { readFile, readdir, writeFile, mkdir } from 'node:fs/promises';
5
5
  import { createRequire } from 'node:module';
6
6
  import { join, resolve } from 'node:path';
7
7
  import { pathToFileURL } from 'node:url';
8
+ import { configExtensions, readConfig } from './cli-shared.mjs';
8
9
 
9
10
  const workspace = resolve(import.meta.dirname, '..');
10
- const config = await readFile(join(workspace, '.config'), 'utf8');
11
- const from = /^utilities:\r?\n(?: {3}.*\r?\n)*? {3}from: (.+)$/m.exec(config)?.[1].trim();
12
- if (!from) throw new Error('utilities-docs: declare the utilities package in .config under utilities: from:.');
11
+ const { from, version } = configExtensions(readConfig(workspace)).find(extension => extension.name === 'utilities') ?? {};
12
+ if (!from || !version) throw new Error('utilities-docs: declare the utilities package in .config under devDependencies: utilities:, like @aliens-syndicate/utilities: 0.1.0.');
13
13
  const entry = /^\.{1,2}\//.test(from) ? join(workspace, from, 'index.mjs') : createRequire(join(workspace, 'package.json')).resolve(from);
14
14
  const {
15
15
  breakpoints, describeVariant, groups, paletteNames, registeredDefaults, resolveUtility, shadeSteps, variantCatalog
@@ -160,7 +160,7 @@ add(4, 'p={@utilitiesDocs.installDetail} variant="utilities-docs-lead"');
160
160
  add(4, 'ol variant="utilities-docs-steps"');
161
161
  for (const [key, title, code] of [
162
162
  ['installStep', 'terminal', ['npm install @aliens-syndicate/utilities']],
163
- ['configStep', '.config', ['devDependencies:', ' utilities:', ' from: @aliens-syndicate/utilities']],
163
+ ['configStep', '.config', ['devDependencies:', ' utilities:', ` ${from}: ${version}`]],
164
164
  ['useStep', 'counter.style', ['Style Counter', ' counter', ' flex items-center gap-3 md:gap-4', ' transition: color .15s',
165
165
  ' counter-button', ' px-4 py-2 rounded-lg hover:bg-(--surface)']]]) {
166
166
  add(5, 'li');