@aliens-syndicate/cli 0.1.7 → 0.1.9
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 +47 -4
- package/README.md +47 -4
- package/README.pt-BR.md +47 -4
- package/README.zh-CN.md +47 -4
- package/package.json +7 -4
- package/tools/build.mjs +217 -34
- package/tools/cli-shared.mjs +42 -11
- package/tools/cli.mjs +10 -7
- package/tools/create.mjs +54 -26
- package/tools/doctor.mjs +12 -10
- package/tools/icon-docs.mjs +9 -8
- package/tools/project-layout.mjs +17 -0
- package/tools/runtime.mjs +252 -41
- package/tools/starter/ai/rules/architecture.rule +2 -2
- package/tools/update.mjs +71 -5
- package/tools/{style-docs.mjs → utilities-docs.mjs} +92 -92
- package/tools/vscode-space/space.tmLanguage.json +1 -1
- package/tools/vscode-space/syntax.cjs +7 -3
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,38 +115,95 @@ 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
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
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');
|
|
123
|
+
const legacyExtension = config.find(node => [...extensionNames, 'style'].includes(node.value.replace(/:$/, '')));
|
|
124
|
+
if (legacyExtension) {
|
|
125
|
+
const name = legacyExtension.value === 'style:' ? 'utilities' : legacyExtension.value.slice(0, -1);
|
|
126
|
+
const group = name === 'utilities' ? 'devDependencies' : 'dependencies';
|
|
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.)`);
|
|
128
|
+
}
|
|
129
|
+
const extensionSettings = {};
|
|
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.`);
|
|
132
|
+
for (const node of group.children) {
|
|
133
|
+
const name = node.value.replace(/:$/, '');
|
|
134
|
+
if (!dependencySections.includes(name) || !node.value.endsWith(':')) throw new Error(`${node.location}: ${group.value} accepts ${dependencySections.join(', ')}, not "${node.value}".`);
|
|
135
|
+
if (extensionSettings[name]) throw new Error(`${node.location}: ${name}: is already declared; keep it in dependencies: or devDependencies:, not both.`);
|
|
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 };
|
|
145
|
+
}
|
|
146
|
+
}
|
|
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 ?? {};
|
|
152
|
+
// console: prints the Space code of the page in the browser console when it opens, only in the local and dev
|
|
153
|
+
// environments (build: environment:), each with its own toggle, true by default. Other environments never show it.
|
|
154
|
+
// "console: false" (or true) on one line sets both; "console:" with local: and dev: under it sets each one.
|
|
155
|
+
const { environment: buildEnvironment = 'local' } = settings('build');
|
|
156
|
+
const consoleNode = config.find(node => /^console:(\s|$)/.test(node.value));
|
|
157
|
+
const consoleAll = consoleNode?.value.slice('console:'.length).trim();
|
|
158
|
+
if (consoleAll && !['true', 'false'].includes(consoleAll)) throw new Error(`${consoleNode.location}: console: accepts true or false, or local: and dev: under it.`);
|
|
159
|
+
if (consoleAll && consoleNode.children.length) throw new Error(`${consoleNode.location}: console: ${consoleAll} sets local and dev together, so it takes no local: or dev: under it.`);
|
|
160
|
+
const consoleSettings = Object.fromEntries((consoleNode?.children ?? []).map(node => {
|
|
161
|
+
const [, key, value] = pair.exec(node.value) ?? [];
|
|
162
|
+
if (!['local', 'dev'].includes(key)) throw new Error(`${node.location}: console: accepts local: and dev:, not "${node.value}".`);
|
|
163
|
+
if (!['true', 'false'].includes(value)) throw new Error(`${node.location}: console: ${key}: accepts true or false.`);
|
|
164
|
+
return [key, value];
|
|
165
|
+
}));
|
|
166
|
+
const showCode = ['local', 'dev'].includes(buildEnvironment) && (consoleSettings[buildEnvironment] ?? consoleAll ?? 'true') === 'true';
|
|
167
|
+
// Extensions are separate packages that the project installs and declares in .config under <group>: <name>: from:, or a
|
|
122
168
|
// local folder written as ./path. Icons (usually @aliens-syndicate/icons) let markup draw the icon tag inline (see
|
|
123
169
|
// renderIcon); utilities (usually @aliens-syndicate/utilities) lets .style list utilities besides plain CSS declarations;
|
|
124
|
-
// elements (usually @aliens-syndicate/elements) adds ready-made Elements that any markup can render
|
|
170
|
+
// elements (usually @aliens-syndicate/elements) adds ready-made Elements that any markup can render; reactive (usually
|
|
171
|
+
// @aliens-syndicate/reactive) adds stream members to .logic, with operators like debounce and switchMap.
|
|
125
172
|
async function loadExtension(section, name) {
|
|
173
|
+
const { version, location } = extensionSettings[section];
|
|
126
174
|
let entry;
|
|
127
175
|
try {
|
|
128
176
|
entry = /^\.{1,2}\//.test(name) ? join(workspace, name, 'index.mjs') : createRequire(join(workspace, 'package.json')).resolve(name);
|
|
129
177
|
} catch {
|
|
130
|
-
throw new Error(
|
|
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.`);
|
|
131
187
|
}
|
|
132
188
|
return import(pathToFileURL(entry).href);
|
|
133
189
|
}
|
|
134
190
|
const iconModule = iconPackage ? await loadExtension('icons', iconPackage) : null;
|
|
135
191
|
const styleModule = stylePackage ? await loadExtension('utilities', stylePackage) : null;
|
|
136
|
-
if (styleModule && typeof styleModule.resolveUtility !== 'function') throw new Error(
|
|
192
|
+
if (styleModule && typeof styleModule.resolveUtility !== 'function') throw new Error(`${extensionSettings.utilities.location}: ${stylePackage} is not an Aliens utilities package.`);
|
|
137
193
|
const elementModule = elementPackage ? await loadExtension('elements', elementPackage) : null;
|
|
138
|
-
if (elementModule && typeof elementModule.elementsDirectory !== 'string') throw new Error(
|
|
194
|
+
if (elementModule && typeof elementModule.elementsDirectory !== 'string') throw new Error(`${extensionSettings.elements.location}: ${elementPackage} is not an Aliens elements package.`);
|
|
195
|
+
const reactiveModule = reactivePackage ? await loadExtension('reactive', reactivePackage) : null;
|
|
196
|
+
if (reactiveModule && typeof reactiveModule.createReactive !== 'function') throw new Error(`${extensionSettings.reactive.location}: ${reactivePackage} is not an Aliens reactive package.`);
|
|
139
197
|
const noStyle = (where, what) => new Error(`${where}: ${what} need the utilities package. Write CSS as "property: value", or run ` +
|
|
140
|
-
'npm install @aliens-syndicate/utilities and declare it in .config:\
|
|
198
|
+
'npm install @aliens-syndicate/utilities and declare it in .config with the installed version:\ndevDependencies:\n utilities:\n @aliens-syndicate/utilities: <version>');
|
|
141
199
|
// Without the utilities package, .style reads plain CSS declarations only.
|
|
142
200
|
const resolveUtility = (token, options) => styleModule ? styleModule.resolveUtility(token, options) : { error: 'no utilities package' };
|
|
143
201
|
const iconRenderer = iconModule?.createIconRenderer();
|
|
144
202
|
const iconCatalog = iconModule ? await iconModule.readCatalog() : null;
|
|
145
203
|
const iconStyle = iconRenderer ? configuredIconStyle ?? 'stroke-rounded' : null;
|
|
146
|
-
if (iconRenderer && !iconRenderer.styles.includes(iconStyle)) throw new Error(
|
|
204
|
+
if (iconRenderer && !iconRenderer.styles.includes(iconStyle)) throw new Error(`${extensionSettings.icons.location}: the icon style after ${iconPackage}/ is one of ${iconRenderer.styles.join(', ')}.`);
|
|
147
205
|
const noIcons = where => new Error(`${where}: icons need a package. Run npm install @aliens-syndicate/icons and declare it in .config:\n` +
|
|
148
|
-
'icons:\n
|
|
206
|
+
'dependencies:\n icons:\n @aliens-syndicate/icons/stroke-rounded: <version>');
|
|
149
207
|
// The icon tag: "icon <name> [style] [size-<n>] [color] [second color] [disabled] [hidden]", with id, variant and label
|
|
150
208
|
// as its only attributes. The first word names the icon and the others may come in any order: one of the ten styles
|
|
151
209
|
// (the one in .config by default), a size utility, up to two colors (the icon and the second tone of bulk, duotone and
|
|
@@ -628,8 +686,8 @@ function render(file, rootProps = {}, ancestry = [], parentScope = null) {
|
|
|
628
686
|
return renderNode(nodes[0], true);
|
|
629
687
|
}
|
|
630
688
|
|
|
631
|
-
// Inside a selector, "property: value" is a CSS declaration. With the utilities package declared in .config
|
|
632
|
-
//
|
|
689
|
+
// Inside a selector, "property: value" is a CSS declaration. With the utilities package declared in .config
|
|
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
|
|
633
691
|
// hover: and dark: rewrite the selector; responsive variants such as md: and max-lg: become @media rules, written
|
|
634
692
|
// after the rest of the file from the widest max-* to the narrowest and then from the narrowest min-width up.
|
|
635
693
|
const declarationLine = /^-{0,2}[A-Za-z][\w-]*:\s+\S/;
|
|
@@ -660,7 +718,7 @@ function compileStyles(nodes, declares) {
|
|
|
660
718
|
const utility = resolveUtility(token, { colors: themeColors });
|
|
661
719
|
if (utility.error) {
|
|
662
720
|
const hint = /^[-\w]+:\S/.test(token) && !token.includes('[') && !token.includes('(')
|
|
663
|
-
? ' A CSS declaration needs a space after the colon.' : ' See the
|
|
721
|
+
? ' A CSS declaration needs a space after the colon.' : ' See the Utilities page for the utility names.';
|
|
664
722
|
throw new Error(`${line.location}: ${utility.error}.${hint}`);
|
|
665
723
|
}
|
|
666
724
|
for (const property of utility.properties) usedProperties.add(property);
|
|
@@ -698,22 +756,82 @@ function compileStyles(nodes, declares) {
|
|
|
698
756
|
|
|
699
757
|
const bindKinds = new Set(['text', 'show', 'pressed', 'expanded']);
|
|
700
758
|
const kebab = name => name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase());
|
|
759
|
+
// Reactive Core in .logic: signal holds state, computed derives a value from signals and other computed values,
|
|
760
|
+
// effect runs its body now and whenever a value it read changes, and watch runs its body when one value changes,
|
|
761
|
+
// with the old value as previous. effect and watch take an optional cleanup:, which runs before the next run.
|
|
762
|
+
// The words belong to the language, so import: signal: aliens/core is optional.
|
|
763
|
+
const coreImports = new Set(['signal', 'computed', 'effect', 'watch', 'batch', 'cleanup']);
|
|
701
764
|
function compileLogic(file) {
|
|
702
765
|
const { name, children } = declarations.get(file);
|
|
703
766
|
const element = basename(file, '.logic');
|
|
767
|
+
const lines = sources.get(file).split(/\r?\n/);
|
|
768
|
+
// The lines under body: or cleanup:, without their indentation.
|
|
769
|
+
const block = node => {
|
|
770
|
+
const from = Number(node.location.split(':').at(-1));
|
|
771
|
+
let until = from;
|
|
772
|
+
const indent = (node.level + 1) * indentation.length;
|
|
773
|
+
while (until < lines.length && (!lines[until].trim() || lines[until].startsWith(' '.repeat(indent)))) until++;
|
|
774
|
+
return { code: lines.slice(from, until).map(line => line.slice(indent)).join('\n'), location: node.location };
|
|
775
|
+
};
|
|
776
|
+
const bodies = [];
|
|
777
|
+
const reaction = (member, kind) => {
|
|
778
|
+
const body = member.children.find(node => node.value === 'body:');
|
|
779
|
+
const cleanup = member.children.find(node => node.value === 'cleanup:');
|
|
780
|
+
if (!body?.children.length || (cleanup && !cleanup.children.length) || member.children.length !== (cleanup ? 2 : 1)) {
|
|
781
|
+
throw new Error(`${member.location}: ${kind} takes body: and, optionally, cleanup:.`);
|
|
782
|
+
}
|
|
783
|
+
const compiled = { body: block(body), cleanup: cleanup && block(cleanup) };
|
|
784
|
+
bodies.push(compiled.body, ...(compiled.cleanup ? [compiled.cleanup] : []));
|
|
785
|
+
return compiled;
|
|
786
|
+
};
|
|
704
787
|
const binds = [];
|
|
705
788
|
const page = {};
|
|
706
|
-
const
|
|
789
|
+
const signals = new Map();
|
|
790
|
+
const computed = new Map();
|
|
791
|
+
const streams = new Map();
|
|
792
|
+
const effects = new Map();
|
|
793
|
+
const watches = new Map();
|
|
707
794
|
const actionNames = [];
|
|
708
795
|
const members = [];
|
|
709
796
|
for (const member of children) {
|
|
710
|
-
if (member.value === 'import:' && member.children.length
|
|
797
|
+
if (member.value === 'import:' && member.children.length &&
|
|
798
|
+
member.children.every(node => coreImports.has(/^(\w+): aliens\/core$/.exec(node.value)?.[1]))) continue;
|
|
711
799
|
const field = /^signal ([A-Za-z]\w*): (string|number|boolean) = (.+)$/.exec(member.value);
|
|
712
800
|
if (field && !member.children.length) {
|
|
713
|
-
|
|
801
|
+
signals.set(field[1], field[2]);
|
|
714
802
|
members.push(`${field[1]}: ${field[2]} = ${field[3]};`);
|
|
715
803
|
continue;
|
|
716
804
|
}
|
|
805
|
+
const derived = /^computed ([A-Za-z]\w*): (string|number|boolean) = (.+)$/.exec(member.value);
|
|
806
|
+
if (derived && !member.children.length) {
|
|
807
|
+
try { new Function(`return (${derived[3]});`); } catch { throw new Error(`${member.location}: invalid expression.`); }
|
|
808
|
+
if (computed.has(derived[1])) throw new Error(`${member.location}: duplicate computed ${derived[1]}.`);
|
|
809
|
+
computed.set(derived[1], { type: derived[2], expression: derived[3] });
|
|
810
|
+
continue;
|
|
811
|
+
}
|
|
812
|
+
// stream <name>: <type> = <expression>, or "=" at the end of the line and the expression indented below it.
|
|
813
|
+
const flow = /^stream ([A-Za-z]\w*): (.+?) =(?: (.+))?$/.exec(member.value);
|
|
814
|
+
if (flow) {
|
|
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>`);
|
|
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.`);
|
|
817
|
+
const expression = flow[3] ?? block(member).code;
|
|
818
|
+
try { new Function(`return (${expression});`); } catch { throw new Error(`${member.location}: invalid expression.`); }
|
|
819
|
+
if (streams.has(flow[1])) throw new Error(`${member.location}: duplicate stream ${flow[1]}.`);
|
|
820
|
+
streams.set(flow[1], { type: flow[2], expression });
|
|
821
|
+
continue;
|
|
822
|
+
}
|
|
823
|
+
const effect = /^effect ([A-Za-z]\w*):$/.exec(member.value)?.[1];
|
|
824
|
+
if (effect) {
|
|
825
|
+
if (effects.has(effect)) throw new Error(`${member.location}: duplicate effect ${effect}.`);
|
|
826
|
+
effects.set(effect, reaction(member, 'effect'));
|
|
827
|
+
continue;
|
|
828
|
+
}
|
|
829
|
+
const watch = /^watch ([A-Za-z]\w*):$/.exec(member.value)?.[1];
|
|
830
|
+
if (watch) {
|
|
831
|
+
if (watches.has(watch)) throw new Error(`${member.location}: ${watch} already has a watch; join both bodies in one.`);
|
|
832
|
+
watches.set(watch, { ...reaction(member, 'watch'), location: member.location });
|
|
833
|
+
continue;
|
|
834
|
+
}
|
|
717
835
|
if (listPattern.test(member.value)) {
|
|
718
836
|
listsOf(file);
|
|
719
837
|
continue;
|
|
@@ -754,20 +872,26 @@ function compileLogic(file) {
|
|
|
754
872
|
!body?.children.length || action.children.length !== 2) {
|
|
755
873
|
throw new Error(`${action.location}: the Web preview supports actions without parameters that return void.`);
|
|
756
874
|
}
|
|
757
|
-
const
|
|
758
|
-
|
|
759
|
-
let until = from;
|
|
760
|
-
const indent = (body.level + 1) * indentation.length;
|
|
761
|
-
while (until < lines.length && (!lines[until].trim() || lines[until].startsWith(' '.repeat(indent)))) until++;
|
|
875
|
+
const { code, location } = block(body);
|
|
876
|
+
bodies.push({ code, location });
|
|
762
877
|
actionNames.push(actionName);
|
|
763
|
-
members.push(`${actionName}(): void {\n${
|
|
878
|
+
members.push(`${actionName}(): void {\n${code}\n}`);
|
|
764
879
|
}
|
|
765
880
|
}
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
}
|
|
881
|
+
const memberNames = [...signals.keys(), ...computed.keys(), ...streams.keys(), ...actionNames];
|
|
882
|
+
if (new Set(memberNames).size !== memberNames.length) throw new Error(`${file}: duplicate class member.`);
|
|
769
883
|
for (const [key, field] of Object.entries(page)) {
|
|
770
|
-
if (!
|
|
884
|
+
if (!signals.has(field)) throw new Error(`${file}: page: ${key} names the missing signal ${field}.`);
|
|
885
|
+
}
|
|
886
|
+
for (const [target, { location }] of watches) {
|
|
887
|
+
if (!signals.has(target) && !computed.has(target) && !streams.has(target)) throw new Error(`${location}: watch ${target} names no signal, computed or stream of ${element}.`);
|
|
888
|
+
}
|
|
889
|
+
// A computed or a stream is read only: an action, effect or watch that assigns to it stops the build.
|
|
890
|
+
for (const field of [...computed.keys(), ...streams.keys()]) {
|
|
891
|
+
const write = new RegExp(`(?:\\+\\+|--)\\s*this\\.${field}\\b|this\\.${field}\\s*(?:\\+\\+|--|(?:\\*\\*|<<|>>>?|&&|\\|\\||\\?\\?|[-+*/%&|^])?=(?!=))`);
|
|
892
|
+
for (const { code, location } of bodies) {
|
|
893
|
+
if (write.test(code)) throw new Error(`${location}: ${field} is ${computed.has(field) ? 'computed' : 'a stream'}, so it can't be assigned; change what it reads.`);
|
|
894
|
+
}
|
|
771
895
|
}
|
|
772
896
|
const standalone = standaloneLogic.has(element);
|
|
773
897
|
if (standalone && binds.length) throw new Error(`${binds[0].location}: bind: needs tags; ${element} has no .markup.`);
|
|
@@ -776,20 +900,35 @@ function compileLogic(file) {
|
|
|
776
900
|
for (const bind of binds) {
|
|
777
901
|
if (!ids.has(bind.id)) throw new Error(`${bind.location}: id "${bind.id}" is not a tag of ${element}.`);
|
|
778
902
|
}
|
|
779
|
-
// An id named "<element>-<signal>" shows that
|
|
780
|
-
for (const field of
|
|
903
|
+
// An id named "<element>-<signal>" or "<element>-<computed>" shows that value without a bind: entry.
|
|
904
|
+
for (const field of [...signals.keys(), ...computed.keys(), ...streams.keys()]) {
|
|
781
905
|
const id = `${element}-${kebab(field)}`;
|
|
782
906
|
if (ids.has(id) && !binds.some(bind => bind.id === id && bind.kind === 'text')) {
|
|
783
907
|
binds.push({ id, kind: 'text', expression: `this.${field}` });
|
|
784
908
|
}
|
|
785
909
|
}
|
|
786
910
|
}
|
|
787
|
-
const
|
|
911
|
+
const typeOf = field => signals.get(field) ?? (computed.get(field) ?? streams.get(field)).type;
|
|
912
|
+
// A stream expression reads the creators of the package, like from and fromEvent, as plain names.
|
|
913
|
+
const streamTools = '{ Stream, from, of, interval, timer, fromEvent, combineLatest, merge, concat, zip }';
|
|
914
|
+
const fn = (parameters, code) => `function (${parameters}) {\n${code}\n}`;
|
|
915
|
+
const optional = cleanup => cleanup ? fn('', cleanup.code) : 'null';
|
|
916
|
+
// create returns the class instance plus the functions the runtime turns into computed values, effects and watches.
|
|
917
|
+
const create = stripTypeScriptTypes(`(function (element) {
|
|
918
|
+
class ${name} {\n${members.join('\n')}\n}
|
|
919
|
+
return {
|
|
920
|
+
state: new ${name}(),
|
|
921
|
+
computed: [${[...computed].map(([field, { type, expression }]) => `[${JSON.stringify(field)}, function (): ${type} { return (${expression}); }]`).join(', ')}],
|
|
922
|
+
streams: [${[...streams].map(([field, { expression }]) => `[${JSON.stringify(field)}, function (${streamTools}) {\nreturn (${expression});\n}]`).join(', ')}],
|
|
923
|
+
effects: [${[...effects].map(([label, { body, cleanup }]) => `[${JSON.stringify(label)}, ${fn('', body.code)}, ${optional(cleanup)}]`).join(', ')}],
|
|
924
|
+
watches: [${[...watches].map(([target, { body, cleanup }]) => `[${JSON.stringify(target)}, ${fn(`previous: ${typeOf(target)}`, body.code)}, ${optional(cleanup)}]`).join(', ')}]
|
|
925
|
+
};
|
|
926
|
+
})`).trim();
|
|
788
927
|
const compiledBinds = binds.map(({ id, kind, expression }) =>
|
|
789
928
|
`[${JSON.stringify(id)}, ${JSON.stringify(kind)}, function () { return (${expression}); }]`).join(', ');
|
|
790
|
-
const source = `{ create
|
|
929
|
+
const source = `{ create: ${create}, signals: ${JSON.stringify([...signals.keys()])}, actions: ${JSON.stringify(actionNames)}, ` +
|
|
791
930
|
`bind: [${compiledBinds}], page: ${JSON.stringify(page)}, standalone: ${standalone} }`;
|
|
792
|
-
return { source, actions: actionNames, page, standalone };
|
|
931
|
+
return { source, actions: actionNames, page, standalone, streams: streams.size > 0 };
|
|
793
932
|
}
|
|
794
933
|
|
|
795
934
|
const manifest = declarations.get(styles).children;
|
|
@@ -885,6 +1024,48 @@ const css = [...[...usedProperties].sort().map(name => styleModule.propertyRule(
|
|
|
885
1024
|
...compiledStyles.filter(({ element }) => !element || renderedElements.has(element) || usedProviders.has(element)).map(entry => entry.css)]
|
|
886
1025
|
.filter(Boolean).join('\n\n');
|
|
887
1026
|
const compiledLogic = usedLogic.map(([name, entry]) => `${JSON.stringify(name)}: ${entry.source}`).join(',\n');
|
|
1027
|
+
// The code the console shows: the .markup, .logic and .style of the project and of the package Elements the page
|
|
1028
|
+
// renders, colored like the editor does. To stay small, each file is one string where the private-use character
|
|
1029
|
+
// \uE001 + n starts the color of highlightRoles[n] and \uE000 goes back to plain text.
|
|
1030
|
+
const consoleCode = showCode ? {
|
|
1031
|
+
colors: Object.fromEntries([['light', editorPalette['[*Light*][*light*]'].rules], ['dark', editorPalette.rules]].map(([theme, rules]) =>
|
|
1032
|
+
[theme, highlightRoles.map(role => rules[`${Object.keys(highlightRoleOf).find(type => highlightRoleOf[type] === role)}:space`])])),
|
|
1033
|
+
files: [...declarations.keys()].filter(file => /\.(markup|logic|style)$/.test(file) &&
|
|
1034
|
+
(!packageFiles.has(file) || renderedElements.has(elementOfFile(file)) || usedProviders.has(elementOfFile(file)))).map(file => {
|
|
1035
|
+
const source = sources.get(file).replace(/[\uE000-\uE0FF]/g, '');
|
|
1036
|
+
const { tokens } = analyzeSpace(source, extname(file));
|
|
1037
|
+
let index = 0;
|
|
1038
|
+
let current = -1;
|
|
1039
|
+
const paint = (text, role) => {
|
|
1040
|
+
if (!text) return '';
|
|
1041
|
+
const color = role ? highlightRoles.indexOf(role) : -1;
|
|
1042
|
+
const marker = color === current ? '' : String.fromCharCode(0xE001 + color);
|
|
1043
|
+
current = color;
|
|
1044
|
+
return marker + text;
|
|
1045
|
+
};
|
|
1046
|
+
return [file, source.split(/\r\n|\n|\r/).map((line, lineIndex) => {
|
|
1047
|
+
let start = 0;
|
|
1048
|
+
let output = '';
|
|
1049
|
+
while (tokens[index]?.line === lineIndex) {
|
|
1050
|
+
const token = tokens[index++];
|
|
1051
|
+
output += paint(line.slice(start, token.start));
|
|
1052
|
+
start = token.start + token.length;
|
|
1053
|
+
output += paint(line.slice(token.start, start), token.role);
|
|
1054
|
+
}
|
|
1055
|
+
return output + paint(line.slice(start));
|
|
1056
|
+
}).join('\n')];
|
|
1057
|
+
})
|
|
1058
|
+
} : null;
|
|
1059
|
+
// Which .markup draws each view (a tag with data-view and an id), so the console names the file of the address.
|
|
1060
|
+
if (consoleCode) {
|
|
1061
|
+
consoleCode.views = {};
|
|
1062
|
+
for (const [file] of consoleCode.files.filter(([file]) => file.endsWith('.markup'))) {
|
|
1063
|
+
for (const line of sources.get(file).split(/\r?\n/)) {
|
|
1064
|
+
const id = /\bdata-view\b/.test(line) && /\bid="([^"]+)"/.exec(line)?.[1];
|
|
1065
|
+
if (id) consoleCode.views[id] = file;
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
888
1069
|
const output = join(workspace, 'dist');
|
|
889
1070
|
const favicon = assetFiles.includes(join(assetDirectory, 'mark.png')) ? '\n <link rel="icon" href="./assets/mark.png">' : '';
|
|
890
1071
|
await mkdir(output, { recursive: true });
|
|
@@ -900,9 +1081,11 @@ const defaultLocale = ${JSON.stringify(defaultLocale)};
|
|
|
900
1081
|
const detectLocale = ${detection === 'browser'};
|
|
901
1082
|
const iconStyle = ${JSON.stringify(iconStyle)};
|
|
902
1083
|
const iconRenderer = ${iconCatalogUsed ? `(${iconModule.createIconRenderer})()` : 'null'};
|
|
1084
|
+
const reactiveStreams = ${usedLogic.some(([, entry]) => entry.streams) ? `(${reactiveModule.createReactive})` : 'null'};
|
|
903
1085
|
const copyIcons = ${JSON.stringify(iconRenderer && iconCatalog.icons['copy-01'] && iconCatalog.icons['tick-02'] ? {
|
|
904
1086
|
copy: inlineIcon('copy-01', iconStyle, 'copy-icon'), copied: inlineIcon('tick-02', iconStyle, 'copied-icon')
|
|
905
1087
|
} : null)};
|
|
1088
|
+
const consoleCode = ${JSON.stringify(consoleCode)};
|
|
906
1089
|
${runtime}`),
|
|
907
1090
|
writeFile(join(output, 'index.html'), `<!doctype html>
|
|
908
1091
|
<html lang="${defaultLocale}">
|
package/tools/cli-shared.mjs
CHANGED
|
@@ -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,11 +24,16 @@ 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 <
|
|
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.
|
|
30
|
+
// aliens new offers each one with "yes" as the answer by default, except those marked off: reactive adds stream
|
|
31
|
+
// operators, while the Reactive Core (signal, computed, effect, watch, batch and cleanup) comes with every project.
|
|
26
32
|
export const extensions = [
|
|
27
|
-
{ section: 'utilities', name: '@aliens-syndicate/utilities' },
|
|
28
|
-
{ section: 'icons', name: '@aliens-syndicate/icons',
|
|
29
|
-
{ section: 'elements', name: '@aliens-syndicate/elements' }
|
|
33
|
+
{ section: 'utilities', group: 'devDependencies', name: '@aliens-syndicate/utilities' },
|
|
34
|
+
{ section: 'icons', group: 'dependencies', name: '@aliens-syndicate/icons', variant: 'stroke-rounded' },
|
|
35
|
+
{ section: 'elements', group: 'dependencies', name: '@aliens-syndicate/elements' },
|
|
36
|
+
{ section: 'reactive', group: 'dependencies', name: '@aliens-syndicate/reactive', off: true }
|
|
30
37
|
];
|
|
31
38
|
|
|
32
39
|
const paint = code => text => process.stdout.isTTY && !process.env.NO_COLOR ? `\x1b[${code}m${text}\x1b[0m` : String(text);
|
|
@@ -130,23 +137,47 @@ export function requireProject() {
|
|
|
130
137
|
return root;
|
|
131
138
|
}
|
|
132
139
|
|
|
133
|
-
// .config is Space: sections at the first level and key: value pairs under them
|
|
140
|
+
// .config is Space: sections at the first level and key: value pairs under them, nested by indentation (dependencies:
|
|
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 #.
|
|
134
143
|
export function readConfig(root) {
|
|
135
144
|
const config = {};
|
|
136
|
-
|
|
145
|
+
const stack = [{ indent: -1, values: config }];
|
|
137
146
|
for (const line of readFileSync(join(root, '.config'), 'utf8').split(/\r?\n/)) {
|
|
138
147
|
const value = line.trim();
|
|
139
148
|
if (!value || value.startsWith('#')) continue;
|
|
140
|
-
const pair = /^([
|
|
149
|
+
const pair = /^([^\s:]+):\s*(.*)$/.exec(value);
|
|
141
150
|
if (!pair) continue;
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
151
|
+
const indent = line.length - line.trimStart().length;
|
|
152
|
+
while (stack.at(-1).indent >= indent) stack.pop();
|
|
153
|
+
const parent = stack.at(-1).values;
|
|
154
|
+
if (pair[2]) parent[pair[1]] = pair[2];
|
|
155
|
+
else {
|
|
156
|
+
parent[pair[1]] = typeof parent[pair[1]] === 'object' ? parent[pair[1]] : {};
|
|
157
|
+
stack.push({ indent, values: parent[pair[1]] });
|
|
158
|
+
}
|
|
146
159
|
}
|
|
147
160
|
return config;
|
|
148
161
|
}
|
|
149
162
|
|
|
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) {
|
|
168
|
+
return extensionGroups.flatMap(group => Object.entries(config?.[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));
|
|
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;
|
|
180
|
+
|
|
150
181
|
// npm is npm.cmd on Windows, which spawn only runs through the shell.
|
|
151
182
|
export function runCommand(command, args, options = {}) {
|
|
152
183
|
return new Promise((resolvePromise, reject) => {
|
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, 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 = [
|
|
@@ -12,6 +12,7 @@ const commands = [
|
|
|
12
12
|
es: 'Crea un proyecto Aliens y pregunta qué extensiones instalar.', zh: '创建 Aliens 项目,并询问要安装哪些扩展。' },
|
|
13
13
|
options: [['-y, --yes', { en: 'Accepts every default without asking', pt: 'Aceita todos os padrões sem perguntar', es: 'Acepta todos los valores por defecto sin preguntar', zh: '不询问,全部使用默认值' }],
|
|
14
14
|
['--no-utilities, --no-icons, --no-elements', { en: 'Leaves that extension out', pt: 'Deixa essa extensão de fora', es: 'Deja fuera esa extensión', zh: '不包含该扩展' }],
|
|
15
|
+
['--reactive', { en: 'Adds the stream operators of @aliens-syndicate/reactive', pt: 'Adiciona os operadores de stream do @aliens-syndicate/reactive', es: 'Añade los operadores de stream de @aliens-syndicate/reactive', zh: '添加 @aliens-syndicate/reactive 的 stream 操作符' }],
|
|
15
16
|
['--skip-install', { en: 'Creates the files without running npm install', pt: 'Cria os arquivos sem rodar o npm install', es: 'Crea los archivos sin ejecutar npm install', zh: '只创建文件,不运行 npm install' }]] },
|
|
16
17
|
{ name: 'run', aliases: ['watch'], usage: 'aliens run [--port <number>]', load: async () => (await import('./serve.mjs')).serve,
|
|
17
18
|
about: { en: `Builds, serves on http://localhost:${defaultPort} and rebuilds and reloads the browser on every save.`,
|
|
@@ -56,13 +57,13 @@ const commands = [
|
|
|
56
57
|
|
|
57
58
|
const labels = {
|
|
58
59
|
en: { usage: 'Usage', commands: 'Commands', options: 'Options', aliases: 'alias', more: 'Run aliens <command> --help to see its options.',
|
|
59
|
-
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.' },
|
|
60
61
|
pt: { usage: 'Uso', commands: 'Comandos', options: 'Opções', aliases: 'atalho', more: 'Rode aliens <comando> --help para ver as opções dele.',
|
|
61
|
-
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.' },
|
|
62
63
|
es: { usage: 'Uso', commands: 'Comandos', options: 'Opciones', aliases: 'atajo', more: 'Ejecuta aliens <comando> --help para ver sus opciones.',
|
|
63
|
-
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.' },
|
|
64
65
|
zh: { usage: '用法', commands: '命令', options: '选项', aliases: '别名', more: '运行 aliens <命令> --help 查看该命令的选项。',
|
|
65
|
-
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 可查看其依赖包。' }
|
|
66
67
|
};
|
|
67
68
|
const label = pick(labels);
|
|
68
69
|
|
|
@@ -114,15 +115,17 @@ async function version(args) {
|
|
|
114
115
|
const config = root ? readConfig(root) : null;
|
|
115
116
|
const info = [[label.cli, cliVersion], [label.node, process.versions.node],
|
|
116
117
|
[label.packageManager, npm.code === 0 ? `npm ${npm.output}` : '—'], [label.os, `${process.platform} ${process.arch}`]];
|
|
117
|
-
const extensionPackages =
|
|
118
|
+
const extensionPackages = configExtensions(config).map(extension => extension.from).filter(name => !/^\.{1,2}\//.test(name));
|
|
118
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]);
|
|
119
122
|
|
|
120
123
|
console.log('');
|
|
121
124
|
banner.forEach((line, index) => console.log(shade([22, 28, 34, 40, 46][index], line)));
|
|
122
125
|
console.log('');
|
|
123
126
|
for (const [name, value] of info) console.log(`${name}: ${value}`);
|
|
124
127
|
if (config) {
|
|
125
|
-
const sections =
|
|
128
|
+
const sections = configExtensions(config).map(extension => extension.name);
|
|
126
129
|
if (sections.length) console.log(dim(`... ${label.extensions}: ${sections.join(', ')}`));
|
|
127
130
|
}
|
|
128
131
|
|