@felfhenor/cli 0.0.0-stage → 0.2.1
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/bin.js +52 -0
- package/codegen.js +105 -0
- package/content-build.js +132 -0
- package/content-types.js +18 -0
- package/discover.js +83 -0
- package/fs-util.js +28 -0
- package/i18n-build.js +78 -0
- package/package.json +18 -4
- package/project.js +14 -0
- package/watch.js +18 -0
- package/README.md +0 -3
package/bin.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { codegen } from './codegen.js';
|
|
3
|
+
import { contentBuild } from './content-build.js';
|
|
4
|
+
import { projectLoad } from './project.js';
|
|
5
|
+
import { watchRun } from './watch.js';
|
|
6
|
+
const USAGE = `Usage: fel <command>
|
|
7
|
+
|
|
8
|
+
codegen [--production] Registry, project constants and index.generated.html
|
|
9
|
+
content [--pseudo] Gamedata YAML into JSON, schemas and locale tables
|
|
10
|
+
validate Check content without writing anything
|
|
11
|
+
watch [--pseudo] codegen + content on every change
|
|
12
|
+
`;
|
|
13
|
+
function report(problems) {
|
|
14
|
+
problems.forEach((p) => console.error(` ${p}`));
|
|
15
|
+
if (problems.length)
|
|
16
|
+
console.error(`fel: ${problems.length} problem(s).`);
|
|
17
|
+
}
|
|
18
|
+
async function build(pseudo) {
|
|
19
|
+
const ctx = projectLoad();
|
|
20
|
+
await codegen(ctx);
|
|
21
|
+
report(await contentBuild(ctx, { pseudo }));
|
|
22
|
+
}
|
|
23
|
+
async function main() {
|
|
24
|
+
const [command, ...args] = process.argv.slice(2);
|
|
25
|
+
const pseudo = args.includes('--pseudo');
|
|
26
|
+
if (command === 'codegen') {
|
|
27
|
+
await codegen(projectLoad(), args.includes('--production'));
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
if (command === 'content' || command === 'validate') {
|
|
31
|
+
const write = command === 'content';
|
|
32
|
+
const problems = await contentBuild(projectLoad(), { pseudo, write });
|
|
33
|
+
report(problems);
|
|
34
|
+
if (problems.length)
|
|
35
|
+
process.exit(1);
|
|
36
|
+
if (!write)
|
|
37
|
+
console.log('fel validate: content is valid.');
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (command === 'watch') {
|
|
41
|
+
const rebuild = () => build(pseudo).catch((e) => console.error(String(e)));
|
|
42
|
+
await rebuild();
|
|
43
|
+
watchRun(projectLoad(), rebuild);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
console.log(USAGE);
|
|
47
|
+
process.exit(command ? 1 : 0);
|
|
48
|
+
}
|
|
49
|
+
main().catch((e) => {
|
|
50
|
+
console.error(e instanceof Error ? e.message : e);
|
|
51
|
+
process.exit(1);
|
|
52
|
+
});
|
package/codegen.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { relative } from 'node:path';
|
|
3
|
+
import { discoverDefinitions, discoverDuplicates } from './discover.js';
|
|
4
|
+
import { FelProjectSchema } from '@felfhenor/core';
|
|
5
|
+
import { toPosix, writeIfChanged, writeJsonIfChanged } from './fs-util.js';
|
|
6
|
+
const HEADER = '// Generated by `fel codegen`; do not edit.';
|
|
7
|
+
const REGISTRY_FIELD = {
|
|
8
|
+
slice: 'slices',
|
|
9
|
+
system: 'systems',
|
|
10
|
+
migration: 'migrations',
|
|
11
|
+
content: 'contentTypes',
|
|
12
|
+
};
|
|
13
|
+
function codegenImport(ctx, def) {
|
|
14
|
+
const from = toPosix(relative(ctx.path(ctx.project.content.src), def.file)).replace(/\.ts$/, '');
|
|
15
|
+
return `import { ${def.exportName} } from './${from}';`;
|
|
16
|
+
}
|
|
17
|
+
function codegenRegistry(ctx, defs) {
|
|
18
|
+
const field = (kind) => ` ${REGISTRY_FIELD[kind]}: [${defs
|
|
19
|
+
.filter((d) => d.kind === kind)
|
|
20
|
+
.map((d) => d.exportName)
|
|
21
|
+
.join(', ')}],`;
|
|
22
|
+
const slices = defs.filter((d) => d.kind === 'slice');
|
|
23
|
+
return [
|
|
24
|
+
HEADER,
|
|
25
|
+
"import type { FelRegistry, SliceValue } from '@felfhenor/core';",
|
|
26
|
+
...defs.map((def) => codegenImport(ctx, def)),
|
|
27
|
+
'',
|
|
28
|
+
'export const felRegistry: FelRegistry = {',
|
|
29
|
+
...['slice', 'system', 'migration', 'content'].map(field),
|
|
30
|
+
'};',
|
|
31
|
+
'',
|
|
32
|
+
'export interface FelSaveData {',
|
|
33
|
+
...slices.map((d) => ` '${d.key}': SliceValue<typeof ${d.exportName}>;`),
|
|
34
|
+
'}',
|
|
35
|
+
'',
|
|
36
|
+
].join('\n');
|
|
37
|
+
}
|
|
38
|
+
function codegenEnv(ctx, production) {
|
|
39
|
+
const missing = ctx.project.env.filter((name) => process.env[name] === undefined);
|
|
40
|
+
if (production && missing.length) {
|
|
41
|
+
throw new Error(`Missing env vars for a production build: ${missing.join(', ')}`);
|
|
42
|
+
}
|
|
43
|
+
return Object.fromEntries(ctx.project.env.map((name) => [name, process.env[name] ?? '']));
|
|
44
|
+
}
|
|
45
|
+
function codegenProject(ctx, production) {
|
|
46
|
+
const project = { ...ctx.project, envValues: codegenEnv(ctx, production) };
|
|
47
|
+
return [
|
|
48
|
+
HEADER,
|
|
49
|
+
'// Env values here ship in the client bundle: client keys only, never secrets.',
|
|
50
|
+
"import type { FelProject } from '@felfhenor/core';",
|
|
51
|
+
'',
|
|
52
|
+
`export const felProject: FelProject = ${JSON.stringify(project, null, 2)};`,
|
|
53
|
+
'',
|
|
54
|
+
].join('\n');
|
|
55
|
+
}
|
|
56
|
+
function escapeHtml(text) {
|
|
57
|
+
return text
|
|
58
|
+
.replace(/&/g, '&')
|
|
59
|
+
.replace(/"/g, '"')
|
|
60
|
+
.replace(/</g, '<');
|
|
61
|
+
}
|
|
62
|
+
function codegenMetaTags(ctx) {
|
|
63
|
+
const { name, description, meta } = ctx.project;
|
|
64
|
+
const tags = [
|
|
65
|
+
`<title>${escapeHtml(name)}</title>`,
|
|
66
|
+
`<meta name="application-name" content="${escapeHtml(name)}" />`,
|
|
67
|
+
`<meta name="description" content="${escapeHtml(description)}" />`,
|
|
68
|
+
`<meta name="theme-color" content="${escapeHtml(meta.themeColor)}" />`,
|
|
69
|
+
`<meta property="og:type" content="website" />`,
|
|
70
|
+
`<meta property="og:title" content="${escapeHtml(name)}" />`,
|
|
71
|
+
`<meta property="og:description" content="${escapeHtml(description)}" />`,
|
|
72
|
+
...(meta.ogImage
|
|
73
|
+
? [`<meta property="og:image" content="${escapeHtml(meta.ogImage)}" />`]
|
|
74
|
+
: []),
|
|
75
|
+
];
|
|
76
|
+
return tags.join('\n ');
|
|
77
|
+
}
|
|
78
|
+
function codegenIndexHtml(ctx) {
|
|
79
|
+
const src = ctx.path(ctx.project.content.src, 'index.html');
|
|
80
|
+
const template = readFileSync(src, 'utf-8');
|
|
81
|
+
if (!template.includes('<!-- fel:meta -->')) {
|
|
82
|
+
throw new Error(`${src} needs a <!-- fel:meta --> placeholder in <head>.`);
|
|
83
|
+
}
|
|
84
|
+
const html = template.replace('<!-- fel:meta -->', codegenMetaTags(ctx));
|
|
85
|
+
writeIfChanged(ctx.path(ctx.project.content.src, 'index.generated.html'), html);
|
|
86
|
+
}
|
|
87
|
+
function codegenCheck(defs) {
|
|
88
|
+
const reserved = defs
|
|
89
|
+
.filter((d) => d.kind === 'slice' && d.key.startsWith('fel.'))
|
|
90
|
+
.map((d) => `Slice key "${d.key}" in ${d.file} uses the engine's reserved "fel." prefix.`);
|
|
91
|
+
const problems = [...discoverDuplicates(defs), ...reserved];
|
|
92
|
+
if (problems.length)
|
|
93
|
+
throw new Error(problems.join('\n'));
|
|
94
|
+
}
|
|
95
|
+
export async function codegen(ctx, production = false) {
|
|
96
|
+
const defs = await discoverDefinitions(ctx);
|
|
97
|
+
codegenCheck(defs);
|
|
98
|
+
const src = (file) => ctx.path(ctx.project.content.src, file);
|
|
99
|
+
writeIfChanged(src('fel.registry.generated.ts'), codegenRegistry(ctx, defs));
|
|
100
|
+
writeIfChanged(src('fel.generated.ts'), codegenProject(ctx, production));
|
|
101
|
+
writeJsonIfChanged(ctx.path('schemas', 'felproj.schema.json'), FelProjectSchema);
|
|
102
|
+
codegenIndexHtml(ctx);
|
|
103
|
+
console.log(`fel codegen: ${defs.length} definitions.`);
|
|
104
|
+
return defs;
|
|
105
|
+
}
|
package/content-build.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { contentRefsRewrite } from '@felfhenor/core';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { relative } from 'node:path';
|
|
4
|
+
import * as yaml from 'js-yaml';
|
|
5
|
+
import { glob } from 'tinyglobby';
|
|
6
|
+
import { contentTypesLoad } from './content-types.js';
|
|
7
|
+
import { readJson, toPosix, writeIfChanged, writeJsonIfChanged, } from './fs-util.js';
|
|
8
|
+
import { i18nBuild } from './i18n-build.js';
|
|
9
|
+
async function contentReadYaml(ctx) {
|
|
10
|
+
const dir = ctx.path(ctx.project.content.dir);
|
|
11
|
+
const files = await glob('*/**/*.{yml,yaml}', {
|
|
12
|
+
cwd: dir,
|
|
13
|
+
ignore: ['i18n/**'],
|
|
14
|
+
});
|
|
15
|
+
const raw = {};
|
|
16
|
+
files.sort().forEach((file) => {
|
|
17
|
+
const type = toPosix(file).split('/')[0];
|
|
18
|
+
const doc = yaml.load(readFileSync(`${dir}/${file}`, 'utf-8')) ?? [];
|
|
19
|
+
if (!Array.isArray(doc))
|
|
20
|
+
throw new Error(`${file}: expected a list.`);
|
|
21
|
+
(raw[type] ??= []).push(...doc);
|
|
22
|
+
});
|
|
23
|
+
return raw;
|
|
24
|
+
}
|
|
25
|
+
function contentCheckIdentity(raw, problems) {
|
|
26
|
+
const ids = new Set();
|
|
27
|
+
const names = new Set();
|
|
28
|
+
Object.entries(raw).forEach(([type, entries]) => entries.forEach((entry) => {
|
|
29
|
+
if (!entry.id || !entry.name) {
|
|
30
|
+
problems.push(`${type}: every entry needs an id and a name.`);
|
|
31
|
+
}
|
|
32
|
+
if (ids.has(entry.id))
|
|
33
|
+
problems.push(`${type}: duplicate id "${entry.id}".`);
|
|
34
|
+
if (names.has(entry.name)) {
|
|
35
|
+
problems.push(`${type}: duplicate name "${entry.name}".`);
|
|
36
|
+
}
|
|
37
|
+
ids.add(entry.id);
|
|
38
|
+
names.add(entry.name);
|
|
39
|
+
}));
|
|
40
|
+
}
|
|
41
|
+
// YAML may reference an entry by id or by name; the output always holds the id.
|
|
42
|
+
function contentResolver(raw, problems) {
|
|
43
|
+
return (value, type) => {
|
|
44
|
+
const entries = raw[type] ?? [];
|
|
45
|
+
const match = entries.find((e) => e.id === value) ??
|
|
46
|
+
entries.find((e) => e.name === value);
|
|
47
|
+
if (!match)
|
|
48
|
+
problems.push(`Unresolved ${type} reference "${value}".`);
|
|
49
|
+
return match?.id ?? value;
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function contentRewrite(raw, types, problems) {
|
|
53
|
+
const resolve = contentResolver(raw, problems);
|
|
54
|
+
return Object.fromEntries(types.map((type) => [
|
|
55
|
+
type.type,
|
|
56
|
+
(raw[type.type] ?? []).map((entry) => contentRefsRewrite(entry, type.schema, resolve)),
|
|
57
|
+
]));
|
|
58
|
+
}
|
|
59
|
+
function contentValidate(content, types, problems) {
|
|
60
|
+
return types.flatMap((type) => content[type.type].map((raw) => {
|
|
61
|
+
const entry = type.prepare(raw);
|
|
62
|
+
[...type.unknownKeys(raw), ...type.errors(entry)].forEach((e) => problems.push(`${type.type} "${entry.name}": ${e}`));
|
|
63
|
+
return entry;
|
|
64
|
+
}));
|
|
65
|
+
}
|
|
66
|
+
// Defaulted properties are optional to authors; unknown ones (typos) are flagged.
|
|
67
|
+
export function contentAuthoringSchema(schema) {
|
|
68
|
+
const copy = JSON.parse(JSON.stringify(schema));
|
|
69
|
+
const visit = (node) => {
|
|
70
|
+
const props = node.properties;
|
|
71
|
+
if (props)
|
|
72
|
+
node.additionalProperties = false;
|
|
73
|
+
if (node.required && props) {
|
|
74
|
+
node.required = node.required.filter((key) => props[key].default === undefined);
|
|
75
|
+
}
|
|
76
|
+
Object.values(props ?? {}).forEach(visit);
|
|
77
|
+
if (node.items)
|
|
78
|
+
visit(node.items);
|
|
79
|
+
(node.anyOf ?? []).forEach(visit);
|
|
80
|
+
};
|
|
81
|
+
visit(copy);
|
|
82
|
+
return copy;
|
|
83
|
+
}
|
|
84
|
+
function contentWriteVscodeMapping(ctx, mapping) {
|
|
85
|
+
const file = ctx.path('.vscode', 'settings.json');
|
|
86
|
+
let settings = {};
|
|
87
|
+
try {
|
|
88
|
+
settings = readJson(file);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
settings = {};
|
|
92
|
+
}
|
|
93
|
+
// Keeps the author's own mappings; only entries pointing into ./schemas/ are ours.
|
|
94
|
+
const current = (settings['yaml.schemas'] ?? {});
|
|
95
|
+
const theirs = Object.fromEntries(Object.entries(current).filter(([file]) => !file.startsWith('./schemas/')));
|
|
96
|
+
const next = { ...settings, 'yaml.schemas': { ...theirs, ...mapping } };
|
|
97
|
+
writeIfChanged(file, `${JSON.stringify(next, null, 2)}\n`);
|
|
98
|
+
}
|
|
99
|
+
function contentWriteSchemas(ctx, types) {
|
|
100
|
+
const mapping = {};
|
|
101
|
+
types.forEach((type) => {
|
|
102
|
+
const file = `schemas/${type.type}.schema.json`;
|
|
103
|
+
writeJsonIfChanged(ctx.path(file), {
|
|
104
|
+
$schema: 'http://json-schema.org/draft-07/schema#',
|
|
105
|
+
type: 'array',
|
|
106
|
+
items: contentAuthoringSchema(type.schema),
|
|
107
|
+
});
|
|
108
|
+
mapping[`./${file}`] =
|
|
109
|
+
`${ctx.project.content.dir}/${type.type}/**/*.{yml,yaml}`;
|
|
110
|
+
});
|
|
111
|
+
contentWriteVscodeMapping(ctx, mapping);
|
|
112
|
+
}
|
|
113
|
+
export async function contentBuild(ctx, options = {}) {
|
|
114
|
+
const types = await contentTypesLoad(ctx);
|
|
115
|
+
const raw = await contentReadYaml(ctx);
|
|
116
|
+
const problems = [];
|
|
117
|
+
Object.keys(raw)
|
|
118
|
+
.filter((type) => !types.some((t) => t.type === type))
|
|
119
|
+
.forEach((type) => problems.push(`${type}/: no content type "${type}" is defined.`));
|
|
120
|
+
contentCheckIdentity(raw, problems);
|
|
121
|
+
const content = contentRewrite(raw, types, problems);
|
|
122
|
+
const entries = contentValidate(content, types, problems);
|
|
123
|
+
if (problems.length || options.write === false)
|
|
124
|
+
return problems;
|
|
125
|
+
const outDir = ctx.project.content.outDir;
|
|
126
|
+
writeJsonIfChanged(ctx.path(outDir, 'content.json'), content);
|
|
127
|
+
contentWriteSchemas(ctx, types);
|
|
128
|
+
i18nBuild(ctx, entries, types, !!options.pseudo);
|
|
129
|
+
const shown = toPosix(relative(ctx.root, ctx.path(outDir)));
|
|
130
|
+
console.log(`fel content: ${entries.length} entries in ${types.length} types -> ${shown}`);
|
|
131
|
+
return problems;
|
|
132
|
+
}
|
package/content-types.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { createJiti } from 'jiti';
|
|
2
|
+
import { discoverDefinitions } from './discover.js';
|
|
3
|
+
// Only content files are executed, so they must import nothing but core, typebox and other content files.
|
|
4
|
+
export async function contentTypesLoad(ctx) {
|
|
5
|
+
const defs = (await discoverDefinitions(ctx)).filter((d) => d.kind === 'content');
|
|
6
|
+
const jiti = createJiti(ctx.path('.felproj'), {
|
|
7
|
+
moduleCache: false,
|
|
8
|
+
tsconfigPaths: ctx.path('tsconfig.json'),
|
|
9
|
+
});
|
|
10
|
+
return Promise.all(defs.map((def) => contentTypeImport(jiti, def)));
|
|
11
|
+
}
|
|
12
|
+
async function contentTypeImport(jiti, def) {
|
|
13
|
+
const mod = await jiti.import(def.file);
|
|
14
|
+
const type = mod[def.exportName];
|
|
15
|
+
if (!type?.schema)
|
|
16
|
+
throw new Error(`${def.file}: ${def.exportName} is not a content type.`);
|
|
17
|
+
return type;
|
|
18
|
+
}
|
package/discover.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { glob } from 'tinyglobby';
|
|
3
|
+
import { toPosix } from './fs-util.js';
|
|
4
|
+
const DEFINE_FN = {
|
|
5
|
+
content: 'defineContentType',
|
|
6
|
+
slice: 'defineSlice',
|
|
7
|
+
system: 'defineSystem',
|
|
8
|
+
migration: 'defineSaveMigration',
|
|
9
|
+
};
|
|
10
|
+
// Keys are read without running the file, so they must be literals in an exported const.
|
|
11
|
+
function definitionPattern(kind) {
|
|
12
|
+
return new RegExp(String.raw `export\s+const\s+(\w+)\s*=\s*${DEFINE_FN[kind]}\s*(?:<[^(]*>)?\(\s*(?:'([^']+)'|"([^"]+)"|(\d+))`, 'g');
|
|
13
|
+
}
|
|
14
|
+
const CONTENT_IMPORT_ALLOWED = /^(@felfhenor\/core|typebox(\/.*)?|\..*\.content)$/;
|
|
15
|
+
// Content files are executed in Node by the CLI, so they may only reach core, typebox and other content files.
|
|
16
|
+
// `from '…'`, side-effect `import '…'`, `import('…')` and `require('…')`.
|
|
17
|
+
const IMPORT_SPECIFIER = /\b(?:from|import)\s*\(?\s*['"]([^'"]+)['"]|\brequire\s*\(\s*['"]([^'"]+)['"]/g;
|
|
18
|
+
function definitionCheckContentImports(file, text) {
|
|
19
|
+
const specifiers = [...text.matchAll(IMPORT_SPECIFIER)].map((m) => m[1] ?? m[2]);
|
|
20
|
+
const bad = specifiers.filter((s) => !CONTENT_IMPORT_ALLOWED.test(s));
|
|
21
|
+
if (bad.length) {
|
|
22
|
+
throw new Error(`${file}: content files may only import @felfhenor/core, typebox and other *.content files (found ${bad.join(', ')}).`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
// Every define call must be one codegen can see, or its slice/system would silently never register.
|
|
26
|
+
function definitionsInFile(kind, file) {
|
|
27
|
+
const text = readFileSync(file, 'utf-8');
|
|
28
|
+
const found = [...text.matchAll(definitionPattern(kind))].map((m) => ({
|
|
29
|
+
kind,
|
|
30
|
+
file,
|
|
31
|
+
exportName: m[1],
|
|
32
|
+
key: m[2] ?? m[3] ?? m[4],
|
|
33
|
+
}));
|
|
34
|
+
const calls = text.match(new RegExp(String.raw `\b${DEFINE_FN[kind]}\s*[<(]`, 'g'));
|
|
35
|
+
if (!found.length || found.length !== calls?.length) {
|
|
36
|
+
throw new Error(`${file}: every ${DEFINE_FN[kind]} call must be \`export const x = ${DEFINE_FN[kind]}(<literal>, ...)\`.`);
|
|
37
|
+
}
|
|
38
|
+
if (kind === 'content')
|
|
39
|
+
definitionCheckContentImports(file, text);
|
|
40
|
+
return found;
|
|
41
|
+
}
|
|
42
|
+
// A define call outside its kind's file suffix would never be discovered, so it's an error rather than a silent no-op.
|
|
43
|
+
async function discoverMisplaced(ctx) {
|
|
44
|
+
const files = await glob('**/*.ts', {
|
|
45
|
+
cwd: ctx.path(ctx.project.content.src),
|
|
46
|
+
absolute: true,
|
|
47
|
+
ignore: ['**/*.spec.ts', '**/*.generated.ts', '**/node_modules/**'],
|
|
48
|
+
});
|
|
49
|
+
return files.sort().flatMap((file) => {
|
|
50
|
+
const text = readFileSync(file, 'utf-8');
|
|
51
|
+
return Object.keys(DEFINE_FN)
|
|
52
|
+
.filter((kind) => !file.endsWith(`.${kind}.ts`))
|
|
53
|
+
.filter((kind) => new RegExp(String.raw `\b${DEFINE_FN[kind]}\s*[<(]`).test(text))
|
|
54
|
+
.map((kind) => `${toPosix(file)}: ${DEFINE_FN[kind]} only works in a *.${kind}.ts file.`);
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
export async function discoverDefinitions(ctx) {
|
|
58
|
+
const misplaced = await discoverMisplaced(ctx);
|
|
59
|
+
if (misplaced.length)
|
|
60
|
+
throw new Error(misplaced.join('\n'));
|
|
61
|
+
const kinds = Object.keys(DEFINE_FN);
|
|
62
|
+
const perKind = await Promise.all(kinds.map(async (kind) => {
|
|
63
|
+
const files = await glob(`**/*.${kind}.ts`, {
|
|
64
|
+
cwd: ctx.path(ctx.project.content.src),
|
|
65
|
+
absolute: true,
|
|
66
|
+
});
|
|
67
|
+
return files
|
|
68
|
+
.sort()
|
|
69
|
+
.flatMap((file) => definitionsInFile(kind, toPosix(file)));
|
|
70
|
+
}));
|
|
71
|
+
return perKind.flat();
|
|
72
|
+
}
|
|
73
|
+
export function discoverDuplicates(defs) {
|
|
74
|
+
const seen = new Map();
|
|
75
|
+
return defs.flatMap((def) => {
|
|
76
|
+
const id = `${def.kind}:${def.key}`;
|
|
77
|
+
const clash = seen.get(id);
|
|
78
|
+
seen.set(id, def);
|
|
79
|
+
return clash
|
|
80
|
+
? [`Duplicate ${def.kind} "${def.key}" in ${clash.file} and ${def.file}`]
|
|
81
|
+
: [];
|
|
82
|
+
});
|
|
83
|
+
}
|
package/fs-util.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
// Skipping unchanged files keeps `ng serve` from reloading on every content rebuild.
|
|
4
|
+
export function writeIfChanged(path, text) {
|
|
5
|
+
let current;
|
|
6
|
+
try {
|
|
7
|
+
current = readFileSync(path, 'utf-8');
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
current = undefined;
|
|
11
|
+
}
|
|
12
|
+
if (current === text)
|
|
13
|
+
return false;
|
|
14
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
15
|
+
const tmp = `${path}.tmp`;
|
|
16
|
+
writeFileSync(tmp, text, 'utf-8');
|
|
17
|
+
renameSync(tmp, path);
|
|
18
|
+
return true;
|
|
19
|
+
}
|
|
20
|
+
export function writeJsonIfChanged(path, value) {
|
|
21
|
+
return writeIfChanged(path, `${JSON.stringify(value, null, 2)}\n`);
|
|
22
|
+
}
|
|
23
|
+
export function readJson(path) {
|
|
24
|
+
return JSON.parse(readFileSync(path, 'utf-8'));
|
|
25
|
+
}
|
|
26
|
+
export function toPosix(path) {
|
|
27
|
+
return path.replace(/\\/g, '/');
|
|
28
|
+
}
|
package/i18n-build.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { i18nExpandPath } from '@felfhenor/core';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import * as yaml from 'js-yaml';
|
|
4
|
+
import { writeJsonIfChanged } from './fs-util.js';
|
|
5
|
+
export const PSEUDO_LOCALE = 'en-XA';
|
|
6
|
+
function i18nPathValue(entry, path) {
|
|
7
|
+
return path
|
|
8
|
+
.split('.')
|
|
9
|
+
.reduce((node, key) => node?.[key], entry);
|
|
10
|
+
}
|
|
11
|
+
// The base-locale strings a translator works from, keyed exactly as locale tables are.
|
|
12
|
+
export function i18nBaseTable(entries, types) {
|
|
13
|
+
const table = {};
|
|
14
|
+
entries.forEach((entry) => {
|
|
15
|
+
const type = types.find((t) => t.type === entry.__type);
|
|
16
|
+
const texts = {};
|
|
17
|
+
type.i18n
|
|
18
|
+
.flatMap((path) => i18nExpandPath(entry, path))
|
|
19
|
+
.forEach((path) => (texts[path] = i18nPathValue(entry, path)));
|
|
20
|
+
(table[entry.__type] ??= {})[entry.__key] = texts;
|
|
21
|
+
});
|
|
22
|
+
return table;
|
|
23
|
+
}
|
|
24
|
+
const PSEUDO_MAP = {
|
|
25
|
+
a: 'á',
|
|
26
|
+
e: 'é',
|
|
27
|
+
i: 'í',
|
|
28
|
+
o: 'ó',
|
|
29
|
+
u: 'ú',
|
|
30
|
+
A: 'Á',
|
|
31
|
+
E: 'É',
|
|
32
|
+
O: 'Ó',
|
|
33
|
+
};
|
|
34
|
+
function i18nPseudo(text) {
|
|
35
|
+
// Leaves {{ placeholders }} intact so interpolation still works in the pseudo-locale.
|
|
36
|
+
const accented = text.replace(/\{\{[^}]*\}\}|[aeiouAEO]/g, (m) => PSEUDO_MAP[m] ?? m);
|
|
37
|
+
return `[${accented}]`;
|
|
38
|
+
}
|
|
39
|
+
function i18nMapTable(table, fn) {
|
|
40
|
+
return Object.fromEntries(Object.entries(table).map(([type, byKey]) => [
|
|
41
|
+
type,
|
|
42
|
+
Object.fromEntries(Object.entries(byKey).map(([key, texts]) => [
|
|
43
|
+
key,
|
|
44
|
+
Object.fromEntries(Object.entries(texts).map(([p, s]) => [p, fn(s)])),
|
|
45
|
+
])),
|
|
46
|
+
]));
|
|
47
|
+
}
|
|
48
|
+
function i18nReadLocale(ctx, locale) {
|
|
49
|
+
const file = ctx.path(ctx.project.content.dir, 'i18n', `${locale}.yml`);
|
|
50
|
+
return existsSync(file)
|
|
51
|
+
? (yaml.load(readFileSync(file, 'utf-8')) ?? {})
|
|
52
|
+
: {};
|
|
53
|
+
}
|
|
54
|
+
// Every locale gets the base UI strings underneath its own, so a missing key shows base text, not the key.
|
|
55
|
+
export function i18nBuild(ctx, entries, types, pseudo) {
|
|
56
|
+
const { baseLocale, locales } = ctx.project.i18n;
|
|
57
|
+
const out = (name) => ctx.path(ctx.project.content.outDir, 'i18n', `${name}.json`);
|
|
58
|
+
const base = i18nReadLocale(ctx, baseLocale);
|
|
59
|
+
const baseContent = i18nBaseTable(entries, types);
|
|
60
|
+
writeJsonIfChanged(out('template'), {
|
|
61
|
+
ui: base.ui ?? {},
|
|
62
|
+
content: baseContent,
|
|
63
|
+
});
|
|
64
|
+
locales.forEach((locale) => {
|
|
65
|
+
const table = i18nReadLocale(ctx, locale);
|
|
66
|
+
writeJsonIfChanged(out(locale), {
|
|
67
|
+
ui: { ...base.ui, ...table.ui },
|
|
68
|
+
content: locale === baseLocale ? {} : (table.content ?? {}),
|
|
69
|
+
});
|
|
70
|
+
});
|
|
71
|
+
if (!pseudo)
|
|
72
|
+
return;
|
|
73
|
+
const pseudoUi = Object.fromEntries(Object.entries(base.ui ?? {}).map(([k, v]) => [k, i18nPseudo(v)]));
|
|
74
|
+
writeJsonIfChanged(out(PSEUDO_LOCALE), {
|
|
75
|
+
ui: pseudoUi,
|
|
76
|
+
content: i18nMapTable(baseContent, i18nPseudo),
|
|
77
|
+
});
|
|
78
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@felfhenor/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "The `fel` command: codegen, content build, validation and watch for felfhenor games.",
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": {
|
|
8
|
+
"fel": "./bin.js"
|
|
9
|
+
},
|
|
10
|
+
"peerDependencies": {
|
|
11
|
+
"@felfhenor/core": "^0.2.1",
|
|
12
|
+
"typebox": "^1.4.7"
|
|
13
|
+
},
|
|
14
|
+
"dependencies": {
|
|
15
|
+
"chokidar": "^6.0.0",
|
|
16
|
+
"jiti": "^2.7.0",
|
|
17
|
+
"js-yaml": "^5.5.0",
|
|
18
|
+
"tinyglobby": "^0.2.17"
|
|
19
|
+
}
|
|
20
|
+
}
|
package/project.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { FelProjectSchema } from '@felfhenor/core';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import Value from 'typebox/value';
|
|
4
|
+
import { readJson } from './fs-util.js';
|
|
5
|
+
export function projectLoad(root = process.cwd()) {
|
|
6
|
+
const raw = readJson(resolve(root, '.felproj'));
|
|
7
|
+
const project = Value.Default(FelProjectSchema, raw);
|
|
8
|
+
const errors = [...Value.Errors(FelProjectSchema, project)];
|
|
9
|
+
if (errors.length) {
|
|
10
|
+
const lines = errors.map((e) => ` ${e.instancePath || '/'} ${e.message}`);
|
|
11
|
+
throw new Error(`.felproj is invalid:\n${lines.join('\n')}`);
|
|
12
|
+
}
|
|
13
|
+
return { root, project, path: (...parts) => resolve(root, ...parts) };
|
|
14
|
+
}
|
package/watch.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { watch } from 'chokidar';
|
|
2
|
+
const WATCHED_FILE = /\.(ya?ml|felproj)$|index\.html$|\.(content|slice|system|migration)\.ts$/;
|
|
3
|
+
// Coalesces bursts of saves (editors often write twice) into one rebuild.
|
|
4
|
+
export function watchRun(ctx, rebuild) {
|
|
5
|
+
let timer;
|
|
6
|
+
let running = Promise.resolve();
|
|
7
|
+
const schedule = () => {
|
|
8
|
+
clearTimeout(timer);
|
|
9
|
+
timer = setTimeout(() => (running = running.then(rebuild)), 150);
|
|
10
|
+
};
|
|
11
|
+
const { dir, src } = ctx.project.content;
|
|
12
|
+
const watcher = watch([ctx.path(dir), ctx.path(src), ctx.path('.felproj')], {
|
|
13
|
+
ignoreInitial: true,
|
|
14
|
+
ignored: (path, stats) => !!stats?.isFile() && !WATCHED_FILE.test(path),
|
|
15
|
+
});
|
|
16
|
+
watcher.on('all', schedule);
|
|
17
|
+
console.log('fel watch: watching for changes...');
|
|
18
|
+
}
|
package/README.md
DELETED