@topik/cli 0.1.0-alpha.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 The Topik Authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/cli.d.mts ADDED
@@ -0,0 +1 @@
1
+ export { };
package/dist/cli.mjs ADDED
@@ -0,0 +1,292 @@
1
+ #!/usr/bin/env node
2
+ import { boolean, command, positional, run, string } from "@drizzle-team/brocli";
3
+ import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
4
+ import { extname, join, resolve } from "node:path";
5
+ import { compile, validateResources, watch } from "@topik/core";
6
+ import { existsSync } from "node:fs";
7
+ import { createServer } from "node:http";
8
+ import { parseAllDocuments } from "yaml";
9
+ //#region src/errors.ts
10
+ var CliError = class extends Error {
11
+ constructor(message, options) {
12
+ super(message, options);
13
+ this.name = "CliError";
14
+ }
15
+ };
16
+ //#endregion
17
+ //#region src/validation-output.ts
18
+ function formatValidationFailure(errors, resourceCount, context) {
19
+ const lines = errors.map((error) => `${error.resource}: ${error.path} ${error.message}`);
20
+ lines.push("");
21
+ lines.push(`${errors.length} validation error(s) in ${resourceCount} resources while ${context}`);
22
+ return lines.join("\n");
23
+ }
24
+ //#endregion
25
+ //#region src/compile/index.ts
26
+ const formatExtensions = {
27
+ json: ".json",
28
+ jsonl: ".jsonl",
29
+ yaml: ".yaml"
30
+ };
31
+ async function toYaml(value) {
32
+ if (process.versions.bun) return Bun.YAML.stringify(value);
33
+ const { stringify } = await import("yaml");
34
+ return stringify(value);
35
+ }
36
+ function serialize(resource, format) {
37
+ switch (format) {
38
+ case "json": return Promise.resolve(JSON.stringify(resource, null, 2) + "\n");
39
+ case "jsonl": return Promise.resolve(JSON.stringify(resource) + "\n");
40
+ case "yaml": return toYaml(resource);
41
+ }
42
+ }
43
+ const compile$1 = command({
44
+ name: "compile",
45
+ desc: "Compile wiki content into Topik resource files",
46
+ options: {
47
+ dir: positional("dir").desc("Path to the content directory").default("."),
48
+ outDir: string("out-dir").alias("o").desc("Output directory for compiled resources"),
49
+ format: string("format").alias("f").desc("Output format").enum("json", "jsonl", "yaml").default("json"),
50
+ dryRun: boolean("dry-run").desc("Show what would be compiled without writing files").default(false),
51
+ clean: boolean("clean").desc("Remove existing output before compiling").default(false),
52
+ validate: boolean("validate").desc("Validate compiled resources against schemas").default(false)
53
+ },
54
+ handler: async (options) => {
55
+ const dir = resolve(options.dir);
56
+ const format = options.format;
57
+ const { resources } = await compile({ dir });
58
+ if (options.validate) {
59
+ const { valid, errors } = validateResources(resources);
60
+ if (!valid) throw new CliError(formatValidationFailure(errors, resources.length, "validating compiled output"));
61
+ }
62
+ const ext = formatExtensions[format];
63
+ if (options.dryRun) {
64
+ for (const resource of resources) console.log(`${resource.type}/${resource.name}${ext}`);
65
+ console.log(`\n${resources.length} resources (dry run)`);
66
+ return;
67
+ }
68
+ const outDir = options.outDir ? resolve(options.outDir) : join(dir, ".topik", "resources");
69
+ if (options.clean) await rm(outDir, {
70
+ recursive: true,
71
+ force: true
72
+ });
73
+ const types = new Set(resources.map((r) => r.type));
74
+ await Promise.all([...types].map((type) => mkdir(join(outDir, type), { recursive: true })));
75
+ await Promise.all(resources.map(async (resource) => writeFile(join(outDir, resource.type, `${resource.name}${ext}`), await serialize(resource, format))));
76
+ console.log(`Compiled ${resources.length} resources to ${outDir}`);
77
+ }
78
+ });
79
+ //#endregion
80
+ //#region src/dev/index.ts
81
+ const ASSET_EXTENSIONS = {
82
+ ".png": "image/png",
83
+ ".jpg": "image/jpeg",
84
+ ".jpeg": "image/jpeg",
85
+ ".gif": "image/gif",
86
+ ".svg": "image/svg+xml",
87
+ ".webp": "image/webp",
88
+ ".avif": "image/avif",
89
+ ".ico": "image/x-icon",
90
+ ".mp4": "video/mp4",
91
+ ".webm": "video/webm"
92
+ };
93
+ function sendSSE(res, event, data) {
94
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
95
+ }
96
+ function handleResources(watcher, _req, res) {
97
+ res.writeHead(200, {
98
+ "Content-Type": "application/json",
99
+ "Access-Control-Allow-Origin": "*"
100
+ });
101
+ res.end(JSON.stringify({ resources: [...watcher.resources.values()] }));
102
+ }
103
+ function handleEvents(watcher, _req, res) {
104
+ res.writeHead(200, {
105
+ "Content-Type": "text/event-stream",
106
+ "Cache-Control": "no-cache",
107
+ Connection: "keep-alive",
108
+ "Access-Control-Allow-Origin": "*"
109
+ });
110
+ sendSSE(res, "sync", { resources: Object.fromEntries(watcher.resources) });
111
+ const onUpdate = (key, resource) => {
112
+ sendSSE(res, "update", {
113
+ key,
114
+ resource
115
+ });
116
+ };
117
+ watcher.on("update", onUpdate);
118
+ res.on("close", () => {
119
+ watcher.off("update", onUpdate);
120
+ });
121
+ }
122
+ const dev = command({
123
+ name: "dev",
124
+ desc: "Start a development server that watches for content changes",
125
+ options: {
126
+ dir: positional("dir").desc("Path to the content directory").default("."),
127
+ port: string("port").alias("p").desc("Port to listen on").default("50001")
128
+ },
129
+ handler: async (options) => {
130
+ const dir = resolve(options.dir);
131
+ const port = parseInt(options.port, 10);
132
+ console.log(`Watching ${dir} for changes...`);
133
+ const watcher = await watch({ dir });
134
+ console.log(`Compiled ${watcher.resources.size} resources`);
135
+ watcher.on("error", (error) => {
136
+ console.error("Compile error:", error.message);
137
+ });
138
+ watcher.on("update", (key) => {
139
+ console.log(`Updated ${key}`);
140
+ });
141
+ const server = createServer((req, res) => {
142
+ if (req.method === "OPTIONS") {
143
+ res.writeHead(204, {
144
+ "Access-Control-Allow-Origin": "*",
145
+ "Access-Control-Allow-Methods": "GET, OPTIONS",
146
+ "Access-Control-Allow-Headers": "Content-Type"
147
+ });
148
+ res.end();
149
+ return;
150
+ }
151
+ const url = new URL(req.url ?? "/", `http://localhost:${port}`);
152
+ if (req.method === "GET" && url.pathname === "/health") {
153
+ res.writeHead(200, {
154
+ "Content-Type": "application/json",
155
+ "Access-Control-Allow-Origin": "*"
156
+ });
157
+ res.end(JSON.stringify({ status: "ok" }));
158
+ return;
159
+ }
160
+ if (req.method === "GET" && url.pathname === "/resources") {
161
+ handleResources(watcher, req, res);
162
+ return;
163
+ }
164
+ if (req.method === "GET" && url.pathname === "/events") {
165
+ handleEvents(watcher, req, res);
166
+ return;
167
+ }
168
+ if (req.method === "GET") {
169
+ const mime = ASSET_EXTENSIONS[extname(url.pathname)];
170
+ if (mime) {
171
+ const filePath = resolve(join(dir, url.pathname));
172
+ if (filePath.startsWith(dir + "/") && existsSync(filePath)) {
173
+ readFile(filePath).then((data) => {
174
+ res.writeHead(200, {
175
+ "Content-Type": mime,
176
+ "Access-Control-Allow-Origin": "*"
177
+ });
178
+ res.end(data);
179
+ }).catch(() => {
180
+ res.writeHead(500, { "Access-Control-Allow-Origin": "*" });
181
+ res.end();
182
+ });
183
+ return;
184
+ }
185
+ }
186
+ }
187
+ res.writeHead(404, {
188
+ "Content-Type": "text/plain",
189
+ "Access-Control-Allow-Origin": "*"
190
+ });
191
+ res.end("Not Found");
192
+ });
193
+ server.listen(port, () => {
194
+ console.log(`Dev server listening on http://localhost:${port}`);
195
+ });
196
+ process.on("SIGINT", async () => {
197
+ server.close();
198
+ await watcher.close();
199
+ process.exit(0);
200
+ });
201
+ }
202
+ });
203
+ //#endregion
204
+ //#region src/validate/index.ts
205
+ function parseJson(path, content) {
206
+ try {
207
+ return JSON.parse(content);
208
+ } catch (error) {
209
+ throw new CliError(`Failed to parse JSON resource file ${path}`, { cause: error });
210
+ }
211
+ }
212
+ function parseJsonl(path, content) {
213
+ return content.split("\n").map((line, index) => ({
214
+ line,
215
+ index: index + 1
216
+ })).filter(({ line }) => line.trim().length > 0).map(({ line, index }) => {
217
+ try {
218
+ return JSON.parse(line);
219
+ } catch (error) {
220
+ throw new CliError(`Failed to parse JSONL resource file ${path} at line ${index}`, { cause: error });
221
+ }
222
+ });
223
+ }
224
+ function parseYaml(path, content) {
225
+ try {
226
+ return parseAllDocuments(content).filter((document) => document.contents !== null).map((document) => {
227
+ if (document.errors.length > 0) throw document.errors[0];
228
+ return document.toJS();
229
+ });
230
+ } catch (error) {
231
+ throw new CliError(`Failed to parse YAML resource file ${path}`, { cause: error });
232
+ }
233
+ }
234
+ async function readResourceFile(path) {
235
+ const content = await readFile(path, "utf-8");
236
+ switch (extname(path).toLowerCase()) {
237
+ case ".json": return [parseJson(path, content)];
238
+ case ".jsonl": return parseJsonl(path, content);
239
+ case ".yaml":
240
+ case ".yml": return parseYaml(path, content);
241
+ default: throw new CliError(`Unsupported resource file format for ${path}`);
242
+ }
243
+ }
244
+ async function loadResources(path) {
245
+ if ((await stat(path).catch((error) => {
246
+ throw new CliError(`Failed to access ${path}`, { cause: error });
247
+ })).isFile()) return readResourceFile(path);
248
+ const resourceFiles = (await readdir(path, {
249
+ withFileTypes: true,
250
+ recursive: true
251
+ })).filter((entry) => {
252
+ if (!entry.isFile()) return false;
253
+ const extension = extname(entry.name).toLowerCase();
254
+ return extension === ".json" || extension === ".jsonl" || extension === ".yaml" || extension === ".yml";
255
+ });
256
+ return (await Promise.all(resourceFiles.map((entry) => readResourceFile(join(entry.parentPath, entry.name))))).flat();
257
+ }
258
+ const validate = command({
259
+ name: "validate",
260
+ desc: "Validate wiki resource files in JSON, JSONL, or YAML format against schemas",
261
+ options: { path: positional("path").desc("File or directory to validate").required() },
262
+ handler: async (options) => {
263
+ const resources = await loadResources(resolve(options.path));
264
+ if (resources.length === 0) {
265
+ console.log("No resource files found.");
266
+ return;
267
+ }
268
+ const { valid, errors } = validateResources(resources);
269
+ if (valid) console.log(`Validated ${resources.length} resources`);
270
+ else throw new CliError(formatValidationFailure(errors, resources.length, "validating resources"));
271
+ }
272
+ });
273
+ //#endregion
274
+ //#region src/cli.ts
275
+ try {
276
+ await run([
277
+ compile$1,
278
+ dev,
279
+ validate
280
+ ], {
281
+ name: "topik",
282
+ description: "Topik CLI"
283
+ });
284
+ } catch (error) {
285
+ if (error instanceof CliError) {
286
+ console.error(error.message);
287
+ process.exit(1);
288
+ }
289
+ throw error;
290
+ }
291
+ //#endregion
292
+ export {};
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@topik/cli",
3
+ "version": "0.1.0-alpha.2",
4
+ "description": "Topik CLI",
5
+ "license": "MIT",
6
+ "bin": {
7
+ "topik": "./dist/cli.mjs"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "type": "module",
13
+ "exports": {
14
+ ".": "./dist/cli.mjs",
15
+ "./package.json": "./package.json"
16
+ },
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "dependencies": {
21
+ "@drizzle-team/brocli": "^0.11.0",
22
+ "yaml": "^2.7.0",
23
+ "@topik/core": "0.1.0-alpha.2"
24
+ },
25
+ "devDependencies": {
26
+ "@types/bun": "^1.3.11",
27
+ "@types/node": "^24",
28
+ "@typescript/native-preview": "7.0.0-dev.20260316.1",
29
+ "typescript": "^5",
30
+ "vite-plus": "^0.1.12"
31
+ },
32
+ "scripts": {
33
+ "build": "vp pack",
34
+ "dev": "vp pack --watch",
35
+ "test": "vp test",
36
+ "check": "vp check"
37
+ }
38
+ }