@bitcobblers/wod-wiki-tools 0.0.0-stage → 0.36.2133
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/dist/bin/wod.cjs +3532 -0
- package/dist/bin/wod.cjs.map +1 -0
- package/dist/bin/wod.d.cts +1 -0
- package/dist/bin/wod.d.ts +1 -0
- package/dist/bin/wod.mjs +17 -0
- package/dist/bin/wod.mjs.map +1 -0
- package/dist/chunk-6L5ZDZJ7.mjs +15 -0
- package/dist/chunk-6L5ZDZJ7.mjs.map +1 -0
- package/dist/chunk-DZESCGCM.mjs +123 -0
- package/dist/chunk-DZESCGCM.mjs.map +1 -0
- package/dist/chunk-EUQWEX6Z.mjs +253 -0
- package/dist/chunk-EUQWEX6Z.mjs.map +1 -0
- package/dist/chunk-K3GZZFAC.mjs +300 -0
- package/dist/chunk-K3GZZFAC.mjs.map +1 -0
- package/dist/chunk-OZI2FYPF.mjs +2061 -0
- package/dist/chunk-OZI2FYPF.mjs.map +1 -0
- package/dist/compiler-KT6P3AC6.mjs +730 -0
- package/dist/compiler-KT6P3AC6.mjs.map +1 -0
- package/dist/index.cjs +3548 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +356 -0
- package/dist/index.d.ts +356 -0
- package/dist/index.mjs +12 -0
- package/dist/index.mjs.map +1 -0
- package/dist/server/app.cjs +299 -0
- package/dist/server/app.cjs.map +1 -0
- package/dist/server/app.d.cts +24 -0
- package/dist/server/app.d.ts +24 -0
- package/dist/server/app.mjs +9 -0
- package/dist/server/app.mjs.map +1 -0
- package/dist/server-Z2T7IGZX.mjs +11 -0
- package/dist/server-Z2T7IGZX.mjs.map +1 -0
- package/dist/web/playground/ai-skills/parse.md +656 -0
- package/dist/web/playground/assets/main-Bh_mthqc.js +212 -0
- package/dist/web/playground/assets/main-Bhn9NHgQ.css +2 -0
- package/dist/web/playground/assets/rolldown-runtime-C0FnF6B9.js +1 -0
- package/dist/web/playground/assets/statementBuilderFlow-gvzmxfiE.js +2 -0
- package/dist/web/playground/assets/vendor-BlJqgFME.js +201 -0
- package/dist/web/playground/assets/vendor-codemirror-BtJgoBjf.js +40 -0
- package/dist/web/playground/fonts/Inter-Regular.woff2 +0 -0
- package/dist/web/playground/fonts/Inter-SemiBold.woff2 +0 -0
- package/dist/web/playground/images/hero/editing.png +0 -0
- package/dist/web/playground/images/hero/journal.png +0 -0
- package/dist/web/playground/images/hero/results.png +0 -0
- package/dist/web/playground/images/hero/timer.png +0 -0
- package/dist/web/playground/images/wod-wiki-logo-dark.png +0 -0
- package/dist/web/playground/images/wod-wiki-logo-light.png +0 -0
- package/dist/web/playground/index.html +60 -0
- package/dist/web/playground/seed/core/chunks/canvas.d2a5e6e7.json +1 -0
- package/dist/web/playground/seed/core/chunks/template.e5e0e82d.json +1 -0
- package/dist/web/playground/seed/core/manifest.json +24 -0
- package/dist/web/playground/seed/core/report.html +43 -0
- package/dist/web/server/ai-skills/parse.md +656 -0
- package/dist/web/server/assets/main-Bhn9NHgQ.css +2 -0
- package/dist/web/server/assets/main-CPRFCrjV.js +211 -0
- package/dist/web/server/assets/rolldown-runtime-C0FnF6B9.js +1 -0
- package/dist/web/server/assets/statementBuilderFlow-DT1tyXgc.js +2 -0
- package/dist/web/server/assets/vendor-BlJqgFME.js +201 -0
- package/dist/web/server/assets/vendor-codemirror-BtJgoBjf.js +40 -0
- package/dist/web/server/fonts/Inter-Regular.woff2 +0 -0
- package/dist/web/server/fonts/Inter-SemiBold.woff2 +0 -0
- package/dist/web/server/images/hero/editing.png +0 -0
- package/dist/web/server/images/hero/journal.png +0 -0
- package/dist/web/server/images/hero/results.png +0 -0
- package/dist/web/server/images/hero/timer.png +0 -0
- package/dist/web/server/images/wod-wiki-logo-dark.png +0 -0
- package/dist/web/server/images/wod-wiki-logo-light.png +0 -0
- package/dist/web/server/index.html +60 -0
- package/dist/web/server/seed/core/chunks/canvas.d2a5e6e7.json +1 -0
- package/dist/web/server/seed/core/chunks/template.e5e0e82d.json +1 -0
- package/dist/web/server/seed/core/manifest.json +24 -0
- package/dist/web/server/seed/core/report.html +43 -0
- package/package.json +46 -4
- package/README.md +0 -3
package/dist/bin/wod.cjs
ADDED
|
@@ -0,0 +1,3532 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
var wodWikiLang = require('@bitcobblers/wod-wiki-lang');
|
|
5
|
+
var wodWikiCore = require('@bitcobblers/wod-wiki-core');
|
|
6
|
+
var child_process = require('child_process');
|
|
7
|
+
var fs = require('fs');
|
|
8
|
+
var path = require('path');
|
|
9
|
+
var wodWikiWql = require('@bitcobblers/wod-wiki-wql');
|
|
10
|
+
var crypto = require('crypto');
|
|
11
|
+
var promises = require('fs/promises');
|
|
12
|
+
var sql = require('@bitcobblers/wod-wiki-storage/sql');
|
|
13
|
+
var wodWikiStorage = require('@bitcobblers/wod-wiki-storage');
|
|
14
|
+
var wodWikiEngine = require('@bitcobblers/wod-wiki-engine');
|
|
15
|
+
|
|
16
|
+
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
17
|
+
var __defProp = Object.defineProperty;
|
|
18
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
19
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
20
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
21
|
+
}) : x)(function(x) {
|
|
22
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
23
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
24
|
+
});
|
|
25
|
+
var __esm = (fn, res) => function __init() {
|
|
26
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
27
|
+
};
|
|
28
|
+
var __export = (target, all) => {
|
|
29
|
+
for (var name in all)
|
|
30
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
31
|
+
};
|
|
32
|
+
function nodeRequire() {
|
|
33
|
+
const g = globalThis;
|
|
34
|
+
if (typeof g.process?.versions?.node === "undefined" && typeof g.Bun === "undefined") {
|
|
35
|
+
throw new Error("SQLite operations are only supported in Node / Bun environments");
|
|
36
|
+
}
|
|
37
|
+
const req = g.require ?? (typeof __require === "function" ? __require : void 0);
|
|
38
|
+
if (!req) throw new Error("SQLite operations require a CJS require shim (missing tsup banner?)");
|
|
39
|
+
return req;
|
|
40
|
+
}
|
|
41
|
+
function loadSql() {
|
|
42
|
+
sqlModulePromise ??= import(
|
|
43
|
+
/* @vite-ignore */
|
|
44
|
+
'@bitcobblers/wod-wiki-storage/sql'
|
|
45
|
+
);
|
|
46
|
+
return sqlModulePromise;
|
|
47
|
+
}
|
|
48
|
+
function resolveDbPath(dbPath) {
|
|
49
|
+
const chosen = dbPath ?? process.env.WOD_WIKI_DB ?? "./wodwiki.db";
|
|
50
|
+
return nodePath().resolve(process.cwd(), chosen);
|
|
51
|
+
}
|
|
52
|
+
async function openCliDb(target, opts) {
|
|
53
|
+
if (target === void 0 || typeof target === "string") {
|
|
54
|
+
return openSqliteDb(resolveDbPath(target), opts);
|
|
55
|
+
}
|
|
56
|
+
switch (target.kind) {
|
|
57
|
+
case "sqlite":
|
|
58
|
+
return openSqliteDb(target.path, opts);
|
|
59
|
+
case "turso":
|
|
60
|
+
return openRemoteDb(
|
|
61
|
+
{ DB_DRIVER: "turso", DATABASE_URL: target.url, LIBSQL_AUTH_TOKEN: target.authToken },
|
|
62
|
+
target.label,
|
|
63
|
+
opts
|
|
64
|
+
);
|
|
65
|
+
case "postgres":
|
|
66
|
+
return openRemoteDb({ DB_DRIVER: "postgres", DATABASE_URL: target.url }, target.label, opts);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
async function openSqliteDb(resolved, opts) {
|
|
70
|
+
const [{ createClient }, sql] = await Promise.all([
|
|
71
|
+
import(
|
|
72
|
+
/* @vite-ignore */
|
|
73
|
+
'@libsql/client'
|
|
74
|
+
),
|
|
75
|
+
loadSql()
|
|
76
|
+
]);
|
|
77
|
+
const initialize = opts?.initialize ?? true;
|
|
78
|
+
if (!initialize && !nodeFs().existsSync(resolved)) {
|
|
79
|
+
throw new Error(`[wod] no database at ${resolved} \u2014 run \`wod init\` to create and initialize it`);
|
|
80
|
+
}
|
|
81
|
+
if (initialize) nodeFs().mkdirSync(nodePath().dirname(resolved), { recursive: true });
|
|
82
|
+
const db = sql.libsqlDatabase(createClient({ url: `file:${resolved}` }));
|
|
83
|
+
try {
|
|
84
|
+
if (initialize) {
|
|
85
|
+
await sql.initializeStore(db);
|
|
86
|
+
await sql.initializeDomain(db);
|
|
87
|
+
} else {
|
|
88
|
+
await sql.verifyReadiness(db).catch((error) => {
|
|
89
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
90
|
+
throw new Error(`${message} \u2014 run \`wod init\` to initialize it`, { cause: error });
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
return { db, storage: new sql.SqlStorage(db), path: resolved, close: () => db.close() };
|
|
94
|
+
} catch (error) {
|
|
95
|
+
await db.close();
|
|
96
|
+
throw error;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
async function openRemoteDb(env, label, opts) {
|
|
100
|
+
const [{ openDatabase }, sql] = await Promise.all([
|
|
101
|
+
import(
|
|
102
|
+
/* @vite-ignore */
|
|
103
|
+
'@bitcobblers/wod-wiki-storage/sql/node'
|
|
104
|
+
),
|
|
105
|
+
loadSql()
|
|
106
|
+
]);
|
|
107
|
+
let db;
|
|
108
|
+
try {
|
|
109
|
+
db = await openDatabase(env, { create: opts?.create });
|
|
110
|
+
if (opts?.initialize === false) {
|
|
111
|
+
await sql.verifyReadiness(db);
|
|
112
|
+
} else {
|
|
113
|
+
await sql.initializeStore(db);
|
|
114
|
+
await sql.initializeDomain(db);
|
|
115
|
+
}
|
|
116
|
+
} catch (error) {
|
|
117
|
+
await db?.close().catch(() => {
|
|
118
|
+
});
|
|
119
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
120
|
+
throw new Error(
|
|
121
|
+
`[wod] ${label}: ${message}${opts?.initialize === false ? " \u2014 run `wod init` to initialize it" : ""}`,
|
|
122
|
+
{ cause: error }
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
return { db, storage: new sql.SqlStorage(db), path: label, close: () => db.close() };
|
|
126
|
+
}
|
|
127
|
+
function formatV5Digest(digest) {
|
|
128
|
+
const bytes = digest.slice(0, 16);
|
|
129
|
+
bytes[6] = bytes[6] & 15 | 80;
|
|
130
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
131
|
+
const hex = [...bytes].map((b) => b.toString(16).padStart(2, "0"));
|
|
132
|
+
return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10, 16).join("")}`;
|
|
133
|
+
}
|
|
134
|
+
function uuid5(namespace, name) {
|
|
135
|
+
return formatV5Digest(nodeCrypto().createHash("sha1").update(namespace).update(name).digest());
|
|
136
|
+
}
|
|
137
|
+
function stableNoteId(sourceLabel, content) {
|
|
138
|
+
if (sourceLabel && sourceLabel !== "-") {
|
|
139
|
+
return uuid5(CLI_UUID_NAMESPACE, `wod-cli:${nodePath().resolve(process.cwd(), sourceLabel)}`);
|
|
140
|
+
}
|
|
141
|
+
return uuid5(CLI_UUID_NAMESPACE, `wod-cli:stdin:${content.length}:${content.slice(0, 256)}`);
|
|
142
|
+
}
|
|
143
|
+
function randomId() {
|
|
144
|
+
return nodeCrypto().randomUUID();
|
|
145
|
+
}
|
|
146
|
+
async function allRows(sql, db, store) {
|
|
147
|
+
return sql.listRows(db, sql.storeDefinition(store));
|
|
148
|
+
}
|
|
149
|
+
async function rowsByIndex(sql, db, store, index, only) {
|
|
150
|
+
return sql.listRows(db, sql.storeDefinition(store), { only }, void 0, index);
|
|
151
|
+
}
|
|
152
|
+
function sqliteEventStore(db) {
|
|
153
|
+
const all = async () => await allRows(await loadSql(), db, "events");
|
|
154
|
+
return {
|
|
155
|
+
getEventsByTimeRange: async (start, end) => (await all()).filter((r) => r.timestamp >= start && r.timestamp <= end),
|
|
156
|
+
getEventsByResult: async (resultId) => (await all()).filter((r) => r.resultId === resultId),
|
|
157
|
+
getEventsForNote: async (noteId) => (await all()).filter((r) => r.noteId === noteId),
|
|
158
|
+
getEventsByContent: async (blockContentId4) => (await all()).filter((r) => r.blockContentId === blockContentId4),
|
|
159
|
+
scanAll: all,
|
|
160
|
+
appendEvents: async (appended) => {
|
|
161
|
+
const sql = await loadSql();
|
|
162
|
+
await db.transaction(async (tx) => {
|
|
163
|
+
const eventsDef = sql.storeDefinition("events");
|
|
164
|
+
for (const row of appended) await sql.putRow(tx, eventsDef, row);
|
|
165
|
+
});
|
|
166
|
+
},
|
|
167
|
+
finalizeSummaries: async (resultId, finals) => {
|
|
168
|
+
const sql = await loadSql();
|
|
169
|
+
await db.transaction(async (tx) => {
|
|
170
|
+
const eventsDef = sql.storeDefinition("events");
|
|
171
|
+
const existing = (await sql.listRows(tx, eventsDef)).filter(
|
|
172
|
+
(r) => r.resultId === resultId && r.grain === "summary" && r.origin !== "user"
|
|
173
|
+
);
|
|
174
|
+
for (const row of existing) await sql.deleteRows(tx, eventsDef, row.id);
|
|
175
|
+
for (const row of finals) await sql.putRow(tx, eventsDef, row);
|
|
176
|
+
});
|
|
177
|
+
},
|
|
178
|
+
deleteEvents: async (ids) => {
|
|
179
|
+
const sql = await loadSql();
|
|
180
|
+
await db.transaction(async (tx) => {
|
|
181
|
+
const eventsDef = sql.storeDefinition("events");
|
|
182
|
+
for (const id of ids) await sql.deleteRows(tx, eventsDef, id);
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
function sqliteNoteStore(db) {
|
|
188
|
+
return {
|
|
189
|
+
getAllNotes: async () => await allRows(await loadSql(), db, "notes"),
|
|
190
|
+
getNotesByIds: async (noteIds) => {
|
|
191
|
+
const sql = await loadSql();
|
|
192
|
+
const rows = await sql.getRows(db, sql.storeDefinition("notes"), [...noteIds]);
|
|
193
|
+
return rows.filter((row) => row !== void 0);
|
|
194
|
+
},
|
|
195
|
+
getNoteIdsForTag: async (label) => {
|
|
196
|
+
const sql = await loadSql();
|
|
197
|
+
const tags = (await allRows(sql, db, "tags")).filter((t) => t.label === label);
|
|
198
|
+
const ids = {};
|
|
199
|
+
for (const tag of tags) {
|
|
200
|
+
for (const row of await rowsByIndex(sql, db, "note_tags", "by-tag", tag.id)) {
|
|
201
|
+
ids[row.noteId] = true;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return new Set(Object.keys(ids));
|
|
205
|
+
},
|
|
206
|
+
getNoteTagLabels: async (noteId) => {
|
|
207
|
+
const sql = await loadSql();
|
|
208
|
+
const tagRows = await allRows(sql, db, "tags");
|
|
209
|
+
const labelById = {};
|
|
210
|
+
for (const t of tagRows) labelById[t.id] = t.label;
|
|
211
|
+
const links = await rowsByIndex(sql, db, "note_tags", "by-note", noteId);
|
|
212
|
+
return links.map((l) => labelById[l.tagId]).filter((l) => typeof l === "string");
|
|
213
|
+
},
|
|
214
|
+
queryDomain: async (request) => {
|
|
215
|
+
const result = await (await loadSql()).handleDomainQuery(db, request);
|
|
216
|
+
return result;
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
function sqliteBlockStore(db) {
|
|
221
|
+
return {
|
|
222
|
+
getAllBlocks: async () => await allRows(await loadSql(), db, "block_index"),
|
|
223
|
+
queryDomain: async (request) => {
|
|
224
|
+
const result = await (await loadSql()).handleDomainQuery(db, { ...request, plan: "blocks" });
|
|
225
|
+
return result;
|
|
226
|
+
}
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
function sqliteEffortStore(db) {
|
|
230
|
+
return {
|
|
231
|
+
getAllEfforts: async () => {
|
|
232
|
+
const stored = await allRows(await loadSql(), db, "efforts");
|
|
233
|
+
const bySlug = {};
|
|
234
|
+
for (const effort of stored) bySlug[effort.slug] = effort;
|
|
235
|
+
for (const effort of wodWikiLang.bundledEfforts) {
|
|
236
|
+
bySlug[effort.slug] ??= effort;
|
|
237
|
+
}
|
|
238
|
+
return Object.values(bySlug);
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
function sqliteIndexStore(db, store) {
|
|
243
|
+
return {
|
|
244
|
+
getAllFromIndex: async (index, key) => rowsByIndex(await loadSql(), db, store, index, key)
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
async function getNoteBundle(db, noteId) {
|
|
248
|
+
const sql = await loadSql();
|
|
249
|
+
const note = await sql.getRow(db, sql.storeDefinition("notes"), noteId);
|
|
250
|
+
return { note };
|
|
251
|
+
}
|
|
252
|
+
async function getSessionBundle(db, resultId) {
|
|
253
|
+
const sql = await loadSql();
|
|
254
|
+
const session = await sql.getRow(db, sql.storeDefinition("sessions"), resultId);
|
|
255
|
+
if (!session) return void 0;
|
|
256
|
+
const events = await sql.listRows(db, sql.storeDefinition("events"), { only: resultId }, void 0, "by-result-grain");
|
|
257
|
+
return { session, events };
|
|
258
|
+
}
|
|
259
|
+
async function getEffortBySlug(db, slug) {
|
|
260
|
+
const sql = await loadSql();
|
|
261
|
+
const efforts = await allRows(sql, db, "efforts");
|
|
262
|
+
return efforts.find((e) => e.slug === slug);
|
|
263
|
+
}
|
|
264
|
+
async function listTagsByType(db, type) {
|
|
265
|
+
const sql = await loadSql();
|
|
266
|
+
const tags = await allRows(sql, db, "tags");
|
|
267
|
+
return tags.filter((t) => t.type === type);
|
|
268
|
+
}
|
|
269
|
+
var nodePath, nodeFs, nodeCrypto, sqlModulePromise, CLI_UUID_NAMESPACE;
|
|
270
|
+
var init_db = __esm({
|
|
271
|
+
"src/cli/db.ts"() {
|
|
272
|
+
nodePath = () => nodeRequire()("node:path");
|
|
273
|
+
nodeFs = () => nodeRequire()("node:fs");
|
|
274
|
+
nodeCrypto = () => nodeRequire()("node:crypto");
|
|
275
|
+
CLI_UUID_NAMESPACE = "c0ffee00-8b1a-4e2c-9d3f-5a6b7c8d9e0f";
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
function catalogForChunkId(chunkId) {
|
|
279
|
+
const value = /^(?:collection|feed)\.(.+)$/.exec(chunkId)?.[1];
|
|
280
|
+
return value && value !== "_root" ? value : void 0;
|
|
281
|
+
}
|
|
282
|
+
function canvasRouteSlug(content) {
|
|
283
|
+
const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(content);
|
|
284
|
+
if (fm?.[1] && !/^template:\s*canvas\s*$/m.test(fm[1])) return null;
|
|
285
|
+
return fm?.[1]?.match(/^route:\s*(\S+)\s*$/m)?.[1]?.replace(/^\//, "") || null;
|
|
286
|
+
}
|
|
287
|
+
function seedNoteSourceId(path, content, chunkId) {
|
|
288
|
+
const parts = path.split("/");
|
|
289
|
+
const stem = (parts.at(-1) ?? "").replace(/\.md$/i, "");
|
|
290
|
+
const under = parts.slice(2).map((p) => p.replace(/\.md$/i, "")).join("/");
|
|
291
|
+
if (chunkId === CANVAS_CHUNK_ID2) return `guides:${canvasRouteSlug(content) ?? under}`;
|
|
292
|
+
if (chunkId === DASHBOARDS_CHUNK_ID) return "dashboards";
|
|
293
|
+
if (chunkId === EFFORTS_CHUNK_ID) return "efforts";
|
|
294
|
+
if (chunkId === TEMPLATE_CHUNK_ID) return "playground";
|
|
295
|
+
if (chunkId.startsWith("collection.")) {
|
|
296
|
+
const catalog = catalogForChunkId(chunkId);
|
|
297
|
+
return !catalog ? "collection:_root" : stem.toLowerCase() === "readme" ? `collection:${catalog}` : `collection:${catalog}/${stem}`;
|
|
298
|
+
}
|
|
299
|
+
if (chunkId.startsWith("feed.")) return `feed:feeds/${under}`;
|
|
300
|
+
return void 0;
|
|
301
|
+
}
|
|
302
|
+
var SEED_SCHEMA2, SEED_REGISTERED_WIDGETS, EFFORTS_CHUNK_ID, CANVAS_CHUNK_ID2, DASHBOARDS_CHUNK_ID, TEMPLATE_CHUNK_ID;
|
|
303
|
+
var init_contract = __esm({
|
|
304
|
+
"src/seedbuild/contract.ts"() {
|
|
305
|
+
SEED_SCHEMA2 = 8;
|
|
306
|
+
SEED_REGISTERED_WIDGETS = wodWikiCore.KNOWN_SECTION_WIDGETS;
|
|
307
|
+
EFFORTS_CHUNK_ID = "efforts";
|
|
308
|
+
CANVAS_CHUNK_ID2 = "canvas";
|
|
309
|
+
DASHBOARDS_CHUNK_ID = "dashboards";
|
|
310
|
+
TEMPLATE_CHUNK_ID = "template";
|
|
311
|
+
}
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
// src/seedbuild/effort-slugs.ts
|
|
315
|
+
function extractEffortSlugs2(statements) {
|
|
316
|
+
const slugs = /* @__PURE__ */ new Set();
|
|
317
|
+
for (const statement of statements) {
|
|
318
|
+
if (statement.exerciseId) {
|
|
319
|
+
slugs.add(statement.exerciseId);
|
|
320
|
+
} else {
|
|
321
|
+
const effortMetric = statement.metrics?.getMetric?.("effort");
|
|
322
|
+
const effort = effortMetric && typeof effortMetric.value === "string" ? effortMetric.value : void 0;
|
|
323
|
+
if (effort) {
|
|
324
|
+
const slug = effort.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
325
|
+
if (slug) slugs.add(slug);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
return Array.from(slugs);
|
|
330
|
+
}
|
|
331
|
+
var init_effort_slugs = __esm({
|
|
332
|
+
"src/seedbuild/effort-slugs.ts"() {
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
|
|
336
|
+
// src/seedbuild/filename.ts
|
|
337
|
+
function fileToDisplayName(filename) {
|
|
338
|
+
const base = filename.replace(/\.md$/, "");
|
|
339
|
+
if (base.toUpperCase() === "README") return "Overview";
|
|
340
|
+
const cleaned = base.replace(/^day-\d+-/, "");
|
|
341
|
+
const tokens = cleaned.split(/[-_]/);
|
|
342
|
+
const titled = [];
|
|
343
|
+
for (let i = 0; i < tokens.length; i++) {
|
|
344
|
+
const token = tokens[i];
|
|
345
|
+
const next = tokens[i + 1];
|
|
346
|
+
const after = tokens[i + 2];
|
|
347
|
+
const prev = tokens[i - 1];
|
|
348
|
+
if (/^\d{1,2}$/.test(token) && /^\d{1,2}$/.test(next ?? "") && !/^\d+$/.test(prev ?? "") && !/^\d+$/.test(after ?? "")) {
|
|
349
|
+
titled.push(`${token}.${next}`);
|
|
350
|
+
i++;
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
if (titled.length > 0 && FILE_TITLE_STOP_WORDS[token.toLowerCase()]) {
|
|
354
|
+
titled.push(token.toLowerCase());
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
titled.push(token.charAt(0).toUpperCase() + token.slice(1));
|
|
358
|
+
}
|
|
359
|
+
return titled.join(" ");
|
|
360
|
+
}
|
|
361
|
+
var FILE_TITLE_STOP_WORDS;
|
|
362
|
+
var init_filename = __esm({
|
|
363
|
+
"src/seedbuild/filename.ts"() {
|
|
364
|
+
FILE_TITLE_STOP_WORDS = {
|
|
365
|
+
and: true,
|
|
366
|
+
or: true,
|
|
367
|
+
of: true,
|
|
368
|
+
for: true,
|
|
369
|
+
to: true,
|
|
370
|
+
in: true,
|
|
371
|
+
on: true,
|
|
372
|
+
at: true,
|
|
373
|
+
by: true,
|
|
374
|
+
with: true,
|
|
375
|
+
the: true,
|
|
376
|
+
a: true,
|
|
377
|
+
an: true
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
// src/seedbuild/frontmatter.ts
|
|
383
|
+
function unquote(value) {
|
|
384
|
+
return value.replace(
|
|
385
|
+
/^(['"])(.*)\1$/,
|
|
386
|
+
(_match, quote, inner) => quote === '"' ? inner.replace(/\\(["\\])/g, "$1") : inner
|
|
387
|
+
);
|
|
388
|
+
}
|
|
389
|
+
function parseFrontmatter(raw) {
|
|
390
|
+
const match = raw.match(FRONTMATTER_RE);
|
|
391
|
+
if (!match) return { meta: {}, body: raw };
|
|
392
|
+
return { meta: parseMetaLines(match[1].split(/\r?\n/)), body: raw.slice(match[0].length) };
|
|
393
|
+
}
|
|
394
|
+
function parseMetaLines(lines) {
|
|
395
|
+
const meta = {};
|
|
396
|
+
for (let i = 0; i < lines.length; i++) {
|
|
397
|
+
const keyMatch = lines[i].match(/^([A-Za-z][\w.-]*)\s*:(.*)$/);
|
|
398
|
+
if (!keyMatch) continue;
|
|
399
|
+
const key = keyMatch[1];
|
|
400
|
+
const rawVal = keyMatch[2].trim();
|
|
401
|
+
if (rawVal === "") {
|
|
402
|
+
const items = [];
|
|
403
|
+
while (i + 1 < lines.length) {
|
|
404
|
+
const itemMatch = lines[i + 1].match(/^\s+-\s+(.+)$/);
|
|
405
|
+
if (!itemMatch) break;
|
|
406
|
+
items.push(itemMatch[1].trim());
|
|
407
|
+
i++;
|
|
408
|
+
}
|
|
409
|
+
meta[key] = items.length > 0 ? items : "";
|
|
410
|
+
} else {
|
|
411
|
+
const wasQuoted = /^(['"])(.*)\1$/.test(rawVal);
|
|
412
|
+
const value = unquote(rawVal);
|
|
413
|
+
const num = Number(value);
|
|
414
|
+
meta[key] = !wasQuoted && value !== "" && !isNaN(num) ? num : value;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
return meta;
|
|
418
|
+
}
|
|
419
|
+
function getScalar(meta, key) {
|
|
420
|
+
const value = meta[key];
|
|
421
|
+
return typeof value === "string" || typeof value === "number" ? value : void 0;
|
|
422
|
+
}
|
|
423
|
+
function getList(meta, key) {
|
|
424
|
+
const value = meta[key];
|
|
425
|
+
return Array.isArray(value) ? value : [];
|
|
426
|
+
}
|
|
427
|
+
var FRONTMATTER_RE;
|
|
428
|
+
var init_frontmatter = __esm({
|
|
429
|
+
"src/seedbuild/frontmatter.ts"() {
|
|
430
|
+
FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
|
|
431
|
+
}
|
|
432
|
+
});
|
|
433
|
+
function parseDiscipline(val) {
|
|
434
|
+
if (!val) return void 0;
|
|
435
|
+
const normalized = unquoteYaml(val.trim()).toLowerCase();
|
|
436
|
+
if (wodWikiLang.isEffortDiscipline(normalized)) return normalized;
|
|
437
|
+
console.warn(`[effort-file] unknown discipline '${val}' \u2014 treating as unset`);
|
|
438
|
+
return void 0;
|
|
439
|
+
}
|
|
440
|
+
function unquoteYaml(val) {
|
|
441
|
+
if (val.startsWith('"') && val.endsWith('"')) {
|
|
442
|
+
return val.slice(1, -1).replace(/\\(["\\])/g, "$1");
|
|
443
|
+
}
|
|
444
|
+
if (val.startsWith("'") && val.endsWith("'")) {
|
|
445
|
+
return val.slice(1, -1).replace(/\\'/g, "'");
|
|
446
|
+
}
|
|
447
|
+
return val;
|
|
448
|
+
}
|
|
449
|
+
function coerceNestedScalar(raw) {
|
|
450
|
+
if (raw === "true") return true;
|
|
451
|
+
if (raw === "false") return false;
|
|
452
|
+
if (raw !== "" && !Number.isNaN(Number(raw))) return Number(raw);
|
|
453
|
+
return raw;
|
|
454
|
+
}
|
|
455
|
+
function readNestedSection(lines, key) {
|
|
456
|
+
const start = lines.findIndex((l) => new RegExp(`^${key}:\\s*$`).test(l));
|
|
457
|
+
if (start === -1) return void 0;
|
|
458
|
+
const result = {};
|
|
459
|
+
let subKey = null;
|
|
460
|
+
for (let i = start + 1; i < lines.length; i++) {
|
|
461
|
+
const line = lines[i];
|
|
462
|
+
if (/^\S/.test(line)) break;
|
|
463
|
+
const trimmed = line.trim();
|
|
464
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
465
|
+
const indent = line.length - line.trimStart().length;
|
|
466
|
+
const m = trimmed.match(/^([\w.-]+):\s*(.*)$/);
|
|
467
|
+
if (!m) continue;
|
|
468
|
+
const [, k, rawVal] = m;
|
|
469
|
+
if (indent === 2) {
|
|
470
|
+
if (rawVal === "") {
|
|
471
|
+
subKey = k;
|
|
472
|
+
result[k] = {};
|
|
473
|
+
} else {
|
|
474
|
+
subKey = null;
|
|
475
|
+
result[k] = coerceNestedScalar(rawVal);
|
|
476
|
+
}
|
|
477
|
+
} else if (indent >= 4 && subKey !== null) {
|
|
478
|
+
result[subKey][k] = coerceNestedScalar(rawVal);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
return Object.keys(result).length > 0 ? result : void 0;
|
|
482
|
+
}
|
|
483
|
+
function parseEffortFile(raw) {
|
|
484
|
+
const blockMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
|
485
|
+
if (!blockMatch) return null;
|
|
486
|
+
const { meta, body } = parseFrontmatter(raw);
|
|
487
|
+
const innerLines = blockMatch[1].split(/\r?\n/);
|
|
488
|
+
const id = getScalar(meta, "id");
|
|
489
|
+
const slug = getScalar(meta, "slug");
|
|
490
|
+
const label = getScalar(meta, "label");
|
|
491
|
+
const aliases = getList(meta, "aliases");
|
|
492
|
+
const baseAttrs = readNestedSection(innerLines, "baseAttributes");
|
|
493
|
+
const hints = readNestedSection(innerLines, "hints");
|
|
494
|
+
const derivation = readNestedSection(innerLines, "derivation");
|
|
495
|
+
const metRaw = baseAttrs?.met;
|
|
496
|
+
const met = typeof metRaw === "number" ? metRaw : Number(metRaw);
|
|
497
|
+
if (!id || !slug || !label || metRaw === void 0 || Number.isNaN(met)) return null;
|
|
498
|
+
const discipline = parseDiscipline(
|
|
499
|
+
typeof baseAttrs?.discipline === "string" ? baseAttrs.discipline : void 0
|
|
500
|
+
);
|
|
501
|
+
const intensityTier = baseAttrs?.intensityTier;
|
|
502
|
+
const trimmedBody = body.trim();
|
|
503
|
+
return {
|
|
504
|
+
id: String(id),
|
|
505
|
+
slug: String(slug),
|
|
506
|
+
label: String(label),
|
|
507
|
+
aliases,
|
|
508
|
+
baseAttributes: {
|
|
509
|
+
met,
|
|
510
|
+
...discipline ? { discipline } : {},
|
|
511
|
+
...intensityTier ? { intensityTier } : {}
|
|
512
|
+
},
|
|
513
|
+
registrySource: "bundled",
|
|
514
|
+
...trimmedBody ? { body: trimmedBody } : {},
|
|
515
|
+
...hints ? { hints } : {},
|
|
516
|
+
...derivation ? { derivation } : {}
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
var init_effort_file = __esm({
|
|
520
|
+
"src/seedbuild/effort-file.ts"() {
|
|
521
|
+
init_frontmatter();
|
|
522
|
+
}
|
|
523
|
+
});
|
|
524
|
+
function resolveGitVersion(repoRoot) {
|
|
525
|
+
try {
|
|
526
|
+
const run = (args) => child_process.execSync(`git ${args}`, { cwd: repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
527
|
+
const count = Number(run("rev-list --count HEAD"));
|
|
528
|
+
return {
|
|
529
|
+
version: Number.isFinite(count) && count > 0 ? count : 0,
|
|
530
|
+
versionLabel: run("describe --tags --long --always --dirty"),
|
|
531
|
+
commit: run("rev-parse HEAD"),
|
|
532
|
+
dirty: run("status --porcelain") !== ""
|
|
533
|
+
};
|
|
534
|
+
} catch {
|
|
535
|
+
return UNKNOWN_GIT_VERSION;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
var UNKNOWN_GIT_VERSION;
|
|
539
|
+
var init_git_version = __esm({
|
|
540
|
+
"src/seedbuild/git-version.ts"() {
|
|
541
|
+
UNKNOWN_GIT_VERSION = {
|
|
542
|
+
version: 0,
|
|
543
|
+
versionLabel: "unknown",
|
|
544
|
+
commit: "",
|
|
545
|
+
dirty: false
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
});
|
|
549
|
+
function escapeHtml(s) {
|
|
550
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
551
|
+
}
|
|
552
|
+
function rowHtml(c) {
|
|
553
|
+
const kind = c.kind ?? "notes";
|
|
554
|
+
return `<tr><td>${escapeHtml(c.id)}</td><td>${kind}</td><td>${c.count}</td><td>${(c.bytes / 1024).toFixed(1)} KB</td><td><code>${c.sha256.slice(0, 8)}</code></td></tr>`;
|
|
555
|
+
}
|
|
556
|
+
function writeBuildReport(outDir, data) {
|
|
557
|
+
const { manifest, totalMs, passMs, fileCount } = data;
|
|
558
|
+
const totalBytes = manifest.chunks.reduce((s, c) => s + c.bytes, 0);
|
|
559
|
+
const dirtyBadge = manifest.dirty ? ' <strong style="color:#b45309">(dirty working tree \u2014 not reproducible from <code>' + escapeHtml(manifest.commit ?? "") + "</code>)</strong>" : "";
|
|
560
|
+
const html = `<!doctype html>
|
|
561
|
+
<html lang="en">
|
|
562
|
+
<head>
|
|
563
|
+
<meta charset="utf-8" />
|
|
564
|
+
<title>Seed build report</title>
|
|
565
|
+
<style>
|
|
566
|
+
body { font-family: system-ui, sans-serif; max-width: 960px; margin: 2rem auto; padding: 0 1rem; color: #1f2937; }
|
|
567
|
+
h1 { font-size: 1.4rem; } h2 { font-size: 1.1rem; margin-top: 2rem; }
|
|
568
|
+
table { border-collapse: collapse; width: 100%; font-size: 0.9rem; }
|
|
569
|
+
th, td { text-align: left; padding: 0.3rem 0.6rem; border-bottom: 1px solid #e5e7eb; }
|
|
570
|
+
code { font-size: 0.85em; }
|
|
571
|
+
dl { display: grid; grid-template-columns: max-content 1fr; gap: 0.2rem 1rem; font-size: 0.95rem; }
|
|
572
|
+
dt { font-weight: 600; }
|
|
573
|
+
</style>
|
|
574
|
+
</head>
|
|
575
|
+
<body>
|
|
576
|
+
<h1>Seed build report</h1>
|
|
577
|
+
<h2>Version</h2>
|
|
578
|
+
<dl>
|
|
579
|
+
<dt>version</dt><dd>${manifest.version} <code>${escapeHtml(manifest.versionLabel ?? "")}</code>${dirtyBadge}</dd>
|
|
580
|
+
<dt>commit</dt><dd><code>${escapeHtml(manifest.commit ?? "unknown")}</code></dd>
|
|
581
|
+
<dt>built at</dt><dd>${escapeHtml(manifest.builtAt)}</dd>
|
|
582
|
+
<dt>schema</dt><dd>v${manifest.schema}</dd>
|
|
583
|
+
</dl>
|
|
584
|
+
<h2>Benchmarks</h2>
|
|
585
|
+
<dl>
|
|
586
|
+
<dt>total</dt><dd>${totalMs} ms</dd>
|
|
587
|
+
<dt>corpus scan + partition</dt><dd>${passMs.scan} ms (${fileCount} files)</dd>
|
|
588
|
+
<dt>block-index derivation</dt><dd>${passMs.blockIndex} ms</dd>
|
|
589
|
+
<dt>block syntax gate</dt><dd>${passMs.parseGate} ms</dd>
|
|
590
|
+
<dt>block-efforts derivation</dt><dd>${passMs.blockEfforts} ms</dd>
|
|
591
|
+
<dt>chunk writes</dt><dd>${passMs.write} ms</dd>
|
|
592
|
+
</dl>
|
|
593
|
+
<h2>Chunks (${manifest.chunks.length}, ${(totalBytes / 1024).toFixed(0)} KB total)</h2>
|
|
594
|
+
<table>
|
|
595
|
+
<thead><tr><th>id</th><th>kind</th><th>rows</th><th>size</th><th>sha256</th></tr></thead>
|
|
596
|
+
<tbody>
|
|
597
|
+
${manifest.chunks.map(rowHtml).join("\n")}
|
|
598
|
+
</tbody>
|
|
599
|
+
</table>
|
|
600
|
+
</body>
|
|
601
|
+
</html>
|
|
602
|
+
`;
|
|
603
|
+
const file = path.join(outDir, "report.html");
|
|
604
|
+
fs.writeFileSync(file, html, "utf8");
|
|
605
|
+
return file;
|
|
606
|
+
}
|
|
607
|
+
var init_report = __esm({
|
|
608
|
+
"src/seedbuild/report.ts"() {
|
|
609
|
+
}
|
|
610
|
+
});
|
|
611
|
+
|
|
612
|
+
// src/seedbuild/compiler.ts
|
|
613
|
+
var compiler_exports = {};
|
|
614
|
+
__export(compiler_exports, {
|
|
615
|
+
buildBlockEffortRows: () => buildBlockEffortRows,
|
|
616
|
+
buildBlockIndexRows: () => buildBlockIndexRows,
|
|
617
|
+
chunkIdFor: () => chunkIdFor,
|
|
618
|
+
collectCorpusMarkdown: () => collectCorpusMarkdown,
|
|
619
|
+
compileSeedRow: () => compileSeedRow,
|
|
620
|
+
discoverUncatalogedEfforts: () => discoverUncatalogedEfforts,
|
|
621
|
+
feedDateToCreatedAt: () => feedDateToCreatedAt,
|
|
622
|
+
generateSeed: () => generateSeed,
|
|
623
|
+
loadExistingEffortMap: () => loadExistingEffortMap,
|
|
624
|
+
partitionIntoChunks: () => partitionIntoChunks,
|
|
625
|
+
scaffoldDiscoveredEfforts: () => scaffoldDiscoveredEfforts,
|
|
626
|
+
validateDashboardNote: () => validateDashboardNote,
|
|
627
|
+
validateWodBlockSyntax: () => validateWodBlockSyntax
|
|
628
|
+
});
|
|
629
|
+
function listMarkdownFiles(dir, prefix = "") {
|
|
630
|
+
if (!fs.existsSync(dir)) return [];
|
|
631
|
+
const out = [];
|
|
632
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
633
|
+
const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
|
|
634
|
+
if (entry.isDirectory()) out.push(...listMarkdownFiles(path.join(dir, entry.name), rel));
|
|
635
|
+
else if (entry.isFile() && entry.name.endsWith(".md")) out.push(rel);
|
|
636
|
+
}
|
|
637
|
+
return out.sort();
|
|
638
|
+
}
|
|
639
|
+
function chunkIdFor(relPath) {
|
|
640
|
+
const parts = relPath.split("/");
|
|
641
|
+
if (parts[0] !== "markdown" || parts.length < 2) return null;
|
|
642
|
+
const corpus = parts[1];
|
|
643
|
+
if (parts.length === 2) return null;
|
|
644
|
+
const slug = parts[2]?.replace(/\.md$/, "");
|
|
645
|
+
switch (corpus) {
|
|
646
|
+
case "canvas":
|
|
647
|
+
case "dashboards":
|
|
648
|
+
case "efforts":
|
|
649
|
+
return corpus;
|
|
650
|
+
case "collections":
|
|
651
|
+
return parts.length === 3 ? `collection._root` : `collection.${slug}`;
|
|
652
|
+
case "feeds":
|
|
653
|
+
return parts.length === 3 ? `feed._root` : `feed.${slug}`;
|
|
654
|
+
default:
|
|
655
|
+
return null;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
function collectCorpusMarkdown(markdownDir) {
|
|
659
|
+
return listMarkdownFiles(markdownDir).map((p) => `markdown/${p}`);
|
|
660
|
+
}
|
|
661
|
+
function partitionIntoChunks(paths) {
|
|
662
|
+
const byId = /* @__PURE__ */ new Map();
|
|
663
|
+
for (const p of paths) {
|
|
664
|
+
const id = chunkIdFor(p);
|
|
665
|
+
if (id === null) {
|
|
666
|
+
throw new Error(
|
|
667
|
+
`[generate-seed] Parity failure: '${p}' is not part of any known corpus (canvas | dashboards | efforts | collections | feeds). Extend chunkIdFor() if this is a new corpus.`
|
|
668
|
+
);
|
|
669
|
+
}
|
|
670
|
+
const list = byId.get(id);
|
|
671
|
+
if (list) list.push(p);
|
|
672
|
+
else byId.set(id, [p]);
|
|
673
|
+
}
|
|
674
|
+
return [...byId.entries()].sort(([a], [b]) => a < b ? -1 : 1).map(([id, files]) => ({ id, files }));
|
|
675
|
+
}
|
|
676
|
+
function validateDashboardNote(raw) {
|
|
677
|
+
const problems = [];
|
|
678
|
+
const { meta } = parseFrontmatter(raw);
|
|
679
|
+
const { sections } = wodWikiWql.parseDashboardNote(raw);
|
|
680
|
+
const doc = wodWikiWql.buildDashboardDocument(sections, meta);
|
|
681
|
+
if (!doc.isDashboard) return ["file is not a dashboard note (missing dashboard frontmatter)"];
|
|
682
|
+
if (doc.title === void 0) problems.push("dashboard has no title");
|
|
683
|
+
if (doc.widgets.length < 3) problems.push(`dashboard has only ${doc.widgets.length} widgets (the locked format has \u2265 3)`);
|
|
684
|
+
const declared = new Set(doc.tokens.map((t) => t.name));
|
|
685
|
+
for (const widget of doc.widgets) {
|
|
686
|
+
const where = `widget '${widget.title ?? widget.body.slice(0, 40)}'`;
|
|
687
|
+
if (widget.title === void 0) problems.push(`${where}: missing title`);
|
|
688
|
+
if (!wodWikiWql.isDashboardWidgetType(wodWikiWql.resolveWidgetType(widget.type))) {
|
|
689
|
+
problems.push(`${where}: unknown widget type '${widget.type}'`);
|
|
690
|
+
}
|
|
691
|
+
const parsed = wodWikiWql.parseQuery(widget.body);
|
|
692
|
+
if (parsed.error !== void 0) problems.push(`${where}: WQL parse error: ${parsed.error}`);
|
|
693
|
+
for (const ref of [
|
|
694
|
+
...widget.body.matchAll(/\$([A-Za-z][\w-]*)/g),
|
|
695
|
+
...Object.values(widget.attributes).flatMap((v) => [...String(v).matchAll(/\$([A-Za-z][\w-]*)/g)])
|
|
696
|
+
]) {
|
|
697
|
+
if (!declared.has(ref[1])) problems.push(`${where}: undeclared token $${ref[1]}`);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
return problems;
|
|
701
|
+
}
|
|
702
|
+
function gateDashboards(groups, corpusRoot) {
|
|
703
|
+
for (const group of groups) {
|
|
704
|
+
if (group.id !== DASHBOARDS_CHUNK_ID) continue;
|
|
705
|
+
for (const p of group.files) {
|
|
706
|
+
const problems = validateDashboardNote(fs.readFileSync(path.join(corpusRoot, p), "utf8"));
|
|
707
|
+
if (problems.length > 0) {
|
|
708
|
+
throw new Error(`[generate-seed] Dashboard validation failed for '${p}':
|
|
709
|
+
- ${problems.join("\n - ")}`);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
function getFileCreatedAt(file, repoRoot) {
|
|
715
|
+
try {
|
|
716
|
+
const out = child_process.execSync(`git log -1 --format=%ct -- '${file}'`, { cwd: repoRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
717
|
+
const ts = Number(out) * 1e3;
|
|
718
|
+
return Number.isFinite(ts) && ts > 0 ? ts : 0;
|
|
719
|
+
} catch {
|
|
720
|
+
return 0;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
function feedDateToCreatedAt(dateKey) {
|
|
724
|
+
if (!/^\d{4}-\d{2}-\d{2}$/.test(dateKey)) return 0;
|
|
725
|
+
const ts = Date.parse(`${dateKey}T00:00:00Z`);
|
|
726
|
+
return Number.isNaN(ts) ? 0 : ts;
|
|
727
|
+
}
|
|
728
|
+
function compileSeedRow(path, content, metadata = {}) {
|
|
729
|
+
let ordinal = 0;
|
|
730
|
+
const blocks = wodWikiCore.reconcileNoteBlocks(content, { sourceRevision: 1, registeredWidgets: SEED_REGISTERED_WIDGETS, createId: () => `seed:${path}:${ordinal++}` });
|
|
731
|
+
const noteId = metadata.routeId ?? path;
|
|
732
|
+
const sections = wodWikiCore.parseDocumentSections(content);
|
|
733
|
+
const blockIndex = Object.values(blocks).map((block, position) => {
|
|
734
|
+
const section = sections.find((section2) => section2.from === block.from && section2.to === block.to);
|
|
735
|
+
return { id: `${noteId}:${block.id}`, noteId, blockId: block.id, blockVersion: 1, sourceRevision: 1, from: block.from, to: block.to, position, dataType: block.kind, ...block.kind === "wod" ? { blockContentId: wodWikiCore.blockContentId(section?.scriptBlock?.content ?? content.slice(block.from, block.to)) } : {}, rawContent: content.slice(block.from, block.to), noteTitle: metadata.noteTitle ?? fileToDisplayName(path.split("/").at(-1) ?? path), createdAt: metadata.createdAt ?? 0, isStatic: true, sourceId: metadata.sourceId, sourcePath: path, routeId: metadata.routeId };
|
|
736
|
+
});
|
|
737
|
+
return { path, content, blocks, blockIndex, blockEfforts: [] };
|
|
738
|
+
}
|
|
739
|
+
function buildBlockIndexRows(markdownDir, corpusRoot) {
|
|
740
|
+
const rows = [];
|
|
741
|
+
for (const path$1 of collectCorpusMarkdown(markdownDir)) {
|
|
742
|
+
const chunkId = chunkIdFor(path$1);
|
|
743
|
+
if (!chunkId) continue;
|
|
744
|
+
const content = fs.readFileSync(path.join(corpusRoot, path$1), "utf8");
|
|
745
|
+
const parts = path$1.split("/");
|
|
746
|
+
const stem = (parts.at(-1) ?? "").replace(/\.md$/, "");
|
|
747
|
+
const catalog = parts[2];
|
|
748
|
+
const routeId = chunkId === "canvas" ? canvasRouteSlug(content) ?? void 0 : chunkId.startsWith("collection.") ? stem.toLowerCase() === "readme" ? catalog : `${catalog}/${stem}` : chunkId.startsWith("feed.") ? parts.slice(1).join("/").replace(/\.md$/, "") : void 0;
|
|
749
|
+
const sourceId = seedNoteSourceId(path$1, content, chunkId);
|
|
750
|
+
const createdAt = chunkId.startsWith("feed.") ? feedDateToCreatedAt(parts.at(-2) ?? "") : getFileCreatedAt(path$1, corpusRoot);
|
|
751
|
+
rows.push(...compileSeedRow(path$1, content, { routeId, sourceId, createdAt }).blockIndex);
|
|
752
|
+
}
|
|
753
|
+
return rows;
|
|
754
|
+
}
|
|
755
|
+
function validateWodBlockSyntax(blocks) {
|
|
756
|
+
const problems = [];
|
|
757
|
+
for (const block of blocks) {
|
|
758
|
+
if (block.dataType !== "wod" || !block.rawContent?.trim()) continue;
|
|
759
|
+
const section = wodWikiCore.parseDocumentSections(block.rawContent, { registeredWidgets: SEED_REGISTERED_WIDGETS }).find((s) => s.scriptBlock);
|
|
760
|
+
const source = section?.scriptBlock?.content ?? block.rawContent;
|
|
761
|
+
if (!source.trim()) continue;
|
|
762
|
+
const where = block.sourcePath ?? block.noteId;
|
|
763
|
+
if (section?.sport) {
|
|
764
|
+
const parsed = wodWikiLang.parseScript(source, { sport: section.sport });
|
|
765
|
+
for (const error of parsed.errors ?? []) {
|
|
766
|
+
problems.push(`${where}: ${error.message}`);
|
|
767
|
+
}
|
|
768
|
+
continue;
|
|
769
|
+
}
|
|
770
|
+
const doc = source.endsWith("\n") ? source : source + "\n";
|
|
771
|
+
const tree = wodWikiLang.whiteboardParser.parse(doc);
|
|
772
|
+
tree.iterate({
|
|
773
|
+
enter: (node) => {
|
|
774
|
+
if (!node.type.isError) return;
|
|
775
|
+
const line = doc.slice(0, node.from).split("\n").length;
|
|
776
|
+
const snippet = source.slice(node.from, Math.min(node.to, node.from + 60)).split("\n")[0];
|
|
777
|
+
problems.push(`${where}:${line} \`${snippet}\``);
|
|
778
|
+
}
|
|
779
|
+
});
|
|
780
|
+
}
|
|
781
|
+
return problems;
|
|
782
|
+
}
|
|
783
|
+
function formatDiscoveredLabel(raw) {
|
|
784
|
+
const clean = raw.replace(/[-_]+/g, " ").trim();
|
|
785
|
+
return clean.split(/\s+/).map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(" ");
|
|
786
|
+
}
|
|
787
|
+
function loadExistingEffortMap(markdownDir) {
|
|
788
|
+
const slugs = /* @__PURE__ */ new Set();
|
|
789
|
+
const aliasToCanonical = /* @__PURE__ */ new Map();
|
|
790
|
+
const effortsDir = path.join(markdownDir, "efforts");
|
|
791
|
+
for (const file of listMarkdownFiles(effortsDir)) {
|
|
792
|
+
const raw = fs.readFileSync(path.join(effortsDir, file), "utf8");
|
|
793
|
+
const parsed = parseEffortFile(raw);
|
|
794
|
+
if (!parsed) continue;
|
|
795
|
+
slugs.add(parsed.slug);
|
|
796
|
+
aliasToCanonical.set(parsed.slug, parsed.slug);
|
|
797
|
+
aliasToCanonical.set(parsed.label.toLowerCase(), parsed.slug);
|
|
798
|
+
aliasToCanonical.set(parsed.slug.replace(/-/g, " "), parsed.slug);
|
|
799
|
+
for (const alias of parsed.aliases) {
|
|
800
|
+
aliasToCanonical.set(alias.toLowerCase(), parsed.slug);
|
|
801
|
+
aliasToCanonical.set(alias.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, ""), parsed.slug);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
return { slugs, aliasToCanonical };
|
|
805
|
+
}
|
|
806
|
+
function discoverUncatalogedEfforts(markdownDir, corpusRoot) {
|
|
807
|
+
const { slugs, aliasToCanonical } = loadExistingEffortMap(markdownDir);
|
|
808
|
+
const blocks = buildBlockIndexRows(markdownDir, corpusRoot);
|
|
809
|
+
const discovered = /* @__PURE__ */ new Map();
|
|
810
|
+
for (const block of blocks) {
|
|
811
|
+
if (block.dataType !== "wod" || !block.rawContent) continue;
|
|
812
|
+
const section = wodWikiCore.parseDocumentSections(block.rawContent, { registeredWidgets: SEED_REGISTERED_WIDGETS }).find((section2) => section2.scriptBlock);
|
|
813
|
+
const script = wodWikiLang.parseScript(section?.scriptBlock?.content ?? block.rawContent);
|
|
814
|
+
for (const statement of script.statements) {
|
|
815
|
+
const effortMetric = statement.metrics?.getMetric?.("effort");
|
|
816
|
+
const effortLabel = (effortMetric && typeof effortMetric.value === "string" ? effortMetric.value : void 0) ?? statement.exerciseId;
|
|
817
|
+
if (!effortLabel) continue;
|
|
818
|
+
const slugified = effortLabel.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
|
|
819
|
+
if (!slugified || NON_EFFORT_SLUGS[slugified]) continue;
|
|
820
|
+
const canonical = aliasToCanonical.get(slugified) ?? aliasToCanonical.get(effortLabel.toLowerCase());
|
|
821
|
+
if (canonical && slugs.has(canonical)) continue;
|
|
822
|
+
const existing = discovered.get(slugified);
|
|
823
|
+
if (existing) {
|
|
824
|
+
existing.rawLabels.add(effortLabel);
|
|
825
|
+
} else {
|
|
826
|
+
discovered.set(slugified, {
|
|
827
|
+
label: formatDiscoveredLabel(effortLabel),
|
|
828
|
+
rawLabels: /* @__PURE__ */ new Set([effortLabel])
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
return Array.from(discovered.entries()).map(([slug, data]) => ({
|
|
834
|
+
slug,
|
|
835
|
+
label: data.label,
|
|
836
|
+
rawLabels: Array.from(data.rawLabels)
|
|
837
|
+
}));
|
|
838
|
+
}
|
|
839
|
+
function scaffoldDiscoveredEfforts(discovered, markdownDir) {
|
|
840
|
+
const targetDir = path.join(markdownDir, "efforts", "discovered");
|
|
841
|
+
if (!fs.existsSync(targetDir)) {
|
|
842
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
843
|
+
}
|
|
844
|
+
const createdPaths = [];
|
|
845
|
+
for (const effort of discovered) {
|
|
846
|
+
const filePath = path.join(targetDir, `${effort.slug}.md`);
|
|
847
|
+
if (fs.existsSync(filePath)) continue;
|
|
848
|
+
const aliases = effort.rawLabels.filter((l) => l.toLowerCase() !== effort.label.toLowerCase()).map((l) => ` - "${l.replace(/"/g, '\\"')}"`);
|
|
849
|
+
const content = [
|
|
850
|
+
"---",
|
|
851
|
+
`id: effort-bundled-${effort.slug}`,
|
|
852
|
+
`slug: ${effort.slug}`,
|
|
853
|
+
`label: "${effort.label.replace(/"/g, '\\"')}"`,
|
|
854
|
+
aliases.length > 0 ? `aliases:
|
|
855
|
+
${aliases.join("\n")}` : "aliases: []",
|
|
856
|
+
"baseAttributes:",
|
|
857
|
+
" met: 5.0",
|
|
858
|
+
" discipline: general",
|
|
859
|
+
" intensityTier: moderate",
|
|
860
|
+
"registrySource: bundled",
|
|
861
|
+
"---",
|
|
862
|
+
""
|
|
863
|
+
].join("\n");
|
|
864
|
+
fs.writeFileSync(filePath, content, "utf8");
|
|
865
|
+
createdPaths.push(filePath);
|
|
866
|
+
}
|
|
867
|
+
return createdPaths;
|
|
868
|
+
}
|
|
869
|
+
function buildBlockEffortRows(markdownDir, corpusRoot, blocks = buildBlockIndexRows(markdownDir, corpusRoot)) {
|
|
870
|
+
const efforts = [];
|
|
871
|
+
const { aliasToCanonical } = loadExistingEffortMap(markdownDir);
|
|
872
|
+
for (const block of blocks) {
|
|
873
|
+
if (block.dataType !== "wod" || !block.rawContent) continue;
|
|
874
|
+
const section = wodWikiCore.parseDocumentSections(block.rawContent, { registeredWidgets: SEED_REGISTERED_WIDGETS }).find((section2) => section2.scriptBlock);
|
|
875
|
+
const script = wodWikiLang.parseScript(section?.scriptBlock?.content ?? block.rawContent);
|
|
876
|
+
const effortSlugs = extractEffortSlugs2(script.statements);
|
|
877
|
+
const linked = /* @__PURE__ */ new Set();
|
|
878
|
+
for (const rawSlug of effortSlugs) {
|
|
879
|
+
const norm = rawSlug.toLowerCase().trim();
|
|
880
|
+
const canonicalSlug = aliasToCanonical.get(norm) ?? aliasToCanonical.get(norm.replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "")) ?? norm.replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
|
|
881
|
+
if (!canonicalSlug || NON_EFFORT_SLUGS[canonicalSlug] || NON_EFFORT_SLUGS[norm]) {
|
|
882
|
+
continue;
|
|
883
|
+
}
|
|
884
|
+
if (linked.has(canonicalSlug)) continue;
|
|
885
|
+
linked.add(canonicalSlug);
|
|
886
|
+
efforts.push({
|
|
887
|
+
id: `${block.id}:${canonicalSlug}`,
|
|
888
|
+
noteId: block.noteId,
|
|
889
|
+
blockId: block.blockId,
|
|
890
|
+
blockContentId: block.blockContentId,
|
|
891
|
+
effortSlug: canonicalSlug,
|
|
892
|
+
isStatic: block.isStatic,
|
|
893
|
+
sourcePath: block.sourcePath,
|
|
894
|
+
createdAt: block.createdAt
|
|
895
|
+
});
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
return efforts;
|
|
899
|
+
}
|
|
900
|
+
function sha256Hex(data) {
|
|
901
|
+
return crypto.createHash("sha256").update(data).digest("hex");
|
|
902
|
+
}
|
|
903
|
+
function generateSeed(options = {}) {
|
|
904
|
+
const t0 = Date.now();
|
|
905
|
+
const passMs = { scan: 0, blockIndex: 0, parseGate: 0, blockEfforts: 0, write: 0 };
|
|
906
|
+
const corpusRoot = options.corpusRoot ?? process.cwd();
|
|
907
|
+
const markdownDir = options.markdownDir ?? path.join(corpusRoot, "markdown");
|
|
908
|
+
const outDir = options.outDir ?? path.join(corpusRoot, "dist");
|
|
909
|
+
const gitVersion = options.version !== void 0 ? { ...resolveGitVersion(corpusRoot), version: options.version } : resolveGitVersion(corpusRoot);
|
|
910
|
+
if (options.scaffoldDiscoveredEfforts) {
|
|
911
|
+
const discovered = discoverUncatalogedEfforts(markdownDir, corpusRoot);
|
|
912
|
+
if (discovered.length > 0) {
|
|
913
|
+
scaffoldDiscoveredEfforts(discovered, markdownDir);
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
const tScan = Date.now();
|
|
917
|
+
const paths = collectCorpusMarkdown(markdownDir);
|
|
918
|
+
const groups = partitionIntoChunks(paths);
|
|
919
|
+
gateDashboards(groups, corpusRoot);
|
|
920
|
+
if (options.templateFile && fs.existsSync(options.templateFile)) {
|
|
921
|
+
const templateRowPath = options.templateRowPath ?? path.relative(corpusRoot, options.templateFile).split("\\").join("/");
|
|
922
|
+
groups.push({ id: TEMPLATE_CHUNK_ID, files: [templateRowPath] });
|
|
923
|
+
}
|
|
924
|
+
passMs.scan = Date.now() - tScan;
|
|
925
|
+
const tBlockIndex = Date.now();
|
|
926
|
+
const blockRows = buildBlockIndexRows(markdownDir, corpusRoot);
|
|
927
|
+
passMs.blockIndex = Date.now() - tBlockIndex;
|
|
928
|
+
const tParseGate = Date.now();
|
|
929
|
+
const syntaxProblems = validateWodBlockSyntax(blockRows);
|
|
930
|
+
passMs.parseGate = Date.now() - tParseGate;
|
|
931
|
+
if (syntaxProblems.length > 0) {
|
|
932
|
+
const shown = syntaxProblems.slice(0, 20).map((p) => ` ${p}`).join("\n");
|
|
933
|
+
const more = syntaxProblems.length > 20 ? `
|
|
934
|
+
\u2026 and ${syntaxProblems.length - 20} more` : "";
|
|
935
|
+
throw new Error(`[wod build] block syntax gate failed \u2014 ${syntaxProblems.length} block(s) do not parse:
|
|
936
|
+
${shown}${more}`);
|
|
937
|
+
}
|
|
938
|
+
const chunksDir = path.join(outDir, "chunks");
|
|
939
|
+
fs.rmSync(outDir, { recursive: true, force: true });
|
|
940
|
+
fs.mkdirSync(chunksDir, { recursive: true });
|
|
941
|
+
const manifestChunks = [];
|
|
942
|
+
const tBlockEfforts = Date.now();
|
|
943
|
+
const effortRows = buildBlockEffortRows(markdownDir, corpusRoot, blockRows);
|
|
944
|
+
passMs.blockEfforts = Date.now() - tBlockEfforts;
|
|
945
|
+
const blocksByPath = /* @__PURE__ */ new Map();
|
|
946
|
+
const effortsByPath = /* @__PURE__ */ new Map();
|
|
947
|
+
for (const row of blockRows) {
|
|
948
|
+
const rows = blocksByPath.get(row.sourcePath) ?? [];
|
|
949
|
+
rows.push(row);
|
|
950
|
+
blocksByPath.set(row.sourcePath, rows);
|
|
951
|
+
}
|
|
952
|
+
for (const row of effortRows) {
|
|
953
|
+
const rows = effortsByPath.get(row.sourcePath) ?? [];
|
|
954
|
+
rows.push(row);
|
|
955
|
+
effortsByPath.set(row.sourcePath, rows);
|
|
956
|
+
}
|
|
957
|
+
let totalFiles = 0;
|
|
958
|
+
const tWrite = Date.now();
|
|
959
|
+
for (const { id, files } of groups) {
|
|
960
|
+
const templateSource = id === TEMPLATE_CHUNK_ID ? options.templateFile : void 0;
|
|
961
|
+
const rows = files.map((p) => {
|
|
962
|
+
const raw = fs.readFileSync(templateSource ?? path.join(corpusRoot, p), "utf8");
|
|
963
|
+
const content = id === TEMPLATE_CHUNK_ID ? raw.replace(/\$CURSOR/g, "") : raw;
|
|
964
|
+
const compiled = compileSeedRow(p, content);
|
|
965
|
+
compiled.blockIndex = blocksByPath.get(p) ?? compiled.blockIndex;
|
|
966
|
+
compiled.blockEfforts = effortsByPath.get(p) ?? [];
|
|
967
|
+
return compiled;
|
|
968
|
+
});
|
|
969
|
+
const bytes = Buffer.from(JSON.stringify(rows), "utf8");
|
|
970
|
+
const sha = sha256Hex(bytes);
|
|
971
|
+
const file = `chunks/${id}.${sha.slice(0, 8)}.json`;
|
|
972
|
+
fs.writeFileSync(path.join(outDir, file), bytes);
|
|
973
|
+
manifestChunks.push({ id, path: file, sha256: sha, bytes: bytes.length, count: rows.length });
|
|
974
|
+
totalFiles += rows.length;
|
|
975
|
+
}
|
|
976
|
+
passMs.write = Date.now() - tWrite;
|
|
977
|
+
const manifest = {
|
|
978
|
+
schema: SEED_SCHEMA2,
|
|
979
|
+
version: gitVersion.version,
|
|
980
|
+
versionLabel: gitVersion.versionLabel,
|
|
981
|
+
commit: gitVersion.commit,
|
|
982
|
+
dirty: gitVersion.dirty,
|
|
983
|
+
builtAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
984
|
+
chunks: manifestChunks
|
|
985
|
+
};
|
|
986
|
+
fs.writeFileSync(path.join(outDir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
|
|
987
|
+
const reportPath = writeBuildReport(outDir, {
|
|
988
|
+
manifest,
|
|
989
|
+
totalMs: Date.now() - t0,
|
|
990
|
+
passMs,
|
|
991
|
+
fileCount: paths.length});
|
|
992
|
+
return { manifest, outDir, totalFiles, reportPath, passMs };
|
|
993
|
+
}
|
|
994
|
+
var NON_EFFORT_SLUGS;
|
|
995
|
+
var init_compiler = __esm({
|
|
996
|
+
"src/seedbuild/compiler.ts"() {
|
|
997
|
+
init_contract();
|
|
998
|
+
init_effort_slugs();
|
|
999
|
+
init_filename();
|
|
1000
|
+
init_effort_file();
|
|
1001
|
+
init_git_version();
|
|
1002
|
+
init_report();
|
|
1003
|
+
init_frontmatter();
|
|
1004
|
+
NON_EFFORT_SLUGS = {
|
|
1005
|
+
"amrap": true,
|
|
1006
|
+
"emom": true,
|
|
1007
|
+
"tabata": true,
|
|
1008
|
+
"for-time": true,
|
|
1009
|
+
"rounds": true,
|
|
1010
|
+
"sets": true,
|
|
1011
|
+
"repetitions": true,
|
|
1012
|
+
"count-down": true,
|
|
1013
|
+
"total-reps": true,
|
|
1014
|
+
"warmup": true,
|
|
1015
|
+
"cooldown": true,
|
|
1016
|
+
"cool-down": true,
|
|
1017
|
+
"transition": true,
|
|
1018
|
+
"rest": true,
|
|
1019
|
+
"break": true,
|
|
1020
|
+
"work": true,
|
|
1021
|
+
"i-suck-at-this": true,
|
|
1022
|
+
"isuckatthis": true,
|
|
1023
|
+
"movement": true,
|
|
1024
|
+
"movement-you": true,
|
|
1025
|
+
"selected-exercise": true,
|
|
1026
|
+
"training-setup": true,
|
|
1027
|
+
"grade-system": true,
|
|
1028
|
+
"hangs": true,
|
|
1029
|
+
"warm-light-wind": true,
|
|
1030
|
+
"basin": true,
|
|
1031
|
+
"rock-canyon": true,
|
|
1032
|
+
"b-onsight": true,
|
|
1033
|
+
"a-redpoint": true,
|
|
1034
|
+
"d-redpoint": true,
|
|
1035
|
+
"v0-flash": true,
|
|
1036
|
+
"v2-flash": true,
|
|
1037
|
+
"v7-redpoint": true,
|
|
1038
|
+
"avgrpe-mean": true,
|
|
1039
|
+
"calculate": true,
|
|
1040
|
+
"totalload-sum": true,
|
|
1041
|
+
"query": true,
|
|
1042
|
+
"by": true,
|
|
1043
|
+
"": true,
|
|
1044
|
+
"-": true,
|
|
1045
|
+
"...": true,
|
|
1046
|
+
"x": true,
|
|
1047
|
+
"s": true,
|
|
1048
|
+
"bw": true
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
1051
|
+
});
|
|
1052
|
+
|
|
1053
|
+
// src/server/errors.ts
|
|
1054
|
+
var HttpError;
|
|
1055
|
+
var init_errors = __esm({
|
|
1056
|
+
"src/server/errors.ts"() {
|
|
1057
|
+
HttpError = class extends Error {
|
|
1058
|
+
constructor(status, message, code) {
|
|
1059
|
+
super(message);
|
|
1060
|
+
this.status = status;
|
|
1061
|
+
this.code = code;
|
|
1062
|
+
this.name = "HttpError";
|
|
1063
|
+
}
|
|
1064
|
+
status;
|
|
1065
|
+
code;
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
});
|
|
1069
|
+
function bunFile(path) {
|
|
1070
|
+
const bun2 = globalThis;
|
|
1071
|
+
if (!bun2.Bun) throw new Error("the wod-wiki server handler requires the Bun runtime (https://bun.sh)");
|
|
1072
|
+
return bun2.Bun.file(path);
|
|
1073
|
+
}
|
|
1074
|
+
function jsonParam(url, name) {
|
|
1075
|
+
const raw = qget(url, name);
|
|
1076
|
+
if (raw === void 0) return void 0;
|
|
1077
|
+
try {
|
|
1078
|
+
return JSON.parse(raw);
|
|
1079
|
+
} catch {
|
|
1080
|
+
throw new HttpError(400, `invalid JSON in ?${name}`);
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
function rangeParam(url) {
|
|
1084
|
+
const v = jsonParam(url, "range");
|
|
1085
|
+
if (v === void 0) return void 0;
|
|
1086
|
+
if (v !== null && typeof v === "object" && !Array.isArray(v)) return v;
|
|
1087
|
+
return { only: v };
|
|
1088
|
+
}
|
|
1089
|
+
function countParam(url) {
|
|
1090
|
+
const raw = qget(url, "count");
|
|
1091
|
+
if (raw === void 0) return void 0;
|
|
1092
|
+
const n = Number(raw);
|
|
1093
|
+
if (!Number.isFinite(n) || n < 0) throw new HttpError(400, "invalid ?count");
|
|
1094
|
+
return Math.trunc(n);
|
|
1095
|
+
}
|
|
1096
|
+
async function readJsonBody(req, maxBytes) {
|
|
1097
|
+
const body = await req.text();
|
|
1098
|
+
if (maxBytes !== void 0 && body.length > maxBytes) {
|
|
1099
|
+
throw new HttpError(413, `domain query body exceeds ${maxBytes} bytes`);
|
|
1100
|
+
}
|
|
1101
|
+
try {
|
|
1102
|
+
return JSON.parse(body);
|
|
1103
|
+
} catch {
|
|
1104
|
+
throw new HttpError(400, "body must be valid JSON");
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
function txOps(value) {
|
|
1108
|
+
if (!Array.isArray(value)) throw new HttpError(400, "tx body must be {ops: []}");
|
|
1109
|
+
return value.map((op) => {
|
|
1110
|
+
if (op === null || typeof op !== "object" || Array.isArray(op) || !("store" in op) || typeof op.store !== "string" || !("op" in op)) {
|
|
1111
|
+
throw new HttpError(400, "tx op must have a store and operation");
|
|
1112
|
+
}
|
|
1113
|
+
const def = sql.storeDefinition(op.store);
|
|
1114
|
+
const store = def.name;
|
|
1115
|
+
switch (op.op) {
|
|
1116
|
+
case "put":
|
|
1117
|
+
if (!("value" in op)) throw new HttpError(400, "put requires value");
|
|
1118
|
+
return { op: "put", store, value: op.value };
|
|
1119
|
+
case "delete":
|
|
1120
|
+
if (!("key" in op)) throw new HttpError(400, "delete requires key");
|
|
1121
|
+
return { op: "delete", store, key: op.key };
|
|
1122
|
+
case "clear":
|
|
1123
|
+
return { op: "clear", store };
|
|
1124
|
+
case "check": {
|
|
1125
|
+
if (!("key" in op) || !("value" in op)) throw new HttpError(400, "check requires key and value");
|
|
1126
|
+
const scalar = (key) => typeof key === "string" || typeof key === "number" && Number.isFinite(key);
|
|
1127
|
+
if (!scalar(op.key) && !(Array.isArray(op.key) && op.key.length > 0 && op.key.every(scalar))) {
|
|
1128
|
+
throw new HttpError(400, "check requires a scalar key or non-empty scalar tuple");
|
|
1129
|
+
}
|
|
1130
|
+
if (op.value !== null && (typeof op.value !== "object" || Array.isArray(op.value))) {
|
|
1131
|
+
throw new HttpError(400, "check value must be a row or null");
|
|
1132
|
+
}
|
|
1133
|
+
const parts = Array.isArray(op.key) ? op.key : [op.key];
|
|
1134
|
+
if (parts.length !== def.keyPath.length) throw new HttpError(400, "check key arity must match the store");
|
|
1135
|
+
if (op.value !== null) {
|
|
1136
|
+
let rowKey;
|
|
1137
|
+
try {
|
|
1138
|
+
rowKey = wodWikiStorage.keyFromValue(def, op.value);
|
|
1139
|
+
} catch {
|
|
1140
|
+
throw new HttpError(400, "check row must have its primary key");
|
|
1141
|
+
}
|
|
1142
|
+
if (JSON.stringify(rowKey) !== JSON.stringify(op.key)) throw new HttpError(400, "check row primary key must match key");
|
|
1143
|
+
}
|
|
1144
|
+
return { op: "check", store, key: op.key, value: op.value };
|
|
1145
|
+
}
|
|
1146
|
+
default:
|
|
1147
|
+
throw new HttpError(400, "tx op must be put | delete | clear | check");
|
|
1148
|
+
}
|
|
1149
|
+
});
|
|
1150
|
+
}
|
|
1151
|
+
async function realpathSafe(path) {
|
|
1152
|
+
try {
|
|
1153
|
+
return await promises.realpath(path);
|
|
1154
|
+
} catch {
|
|
1155
|
+
return void 0;
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
async function serveFile(real, rel) {
|
|
1159
|
+
const cache = rel.includes("seed/chunks/") ? "public, max-age=31536000, immutable" : "no-cache";
|
|
1160
|
+
const ext = rel.slice(rel.lastIndexOf(".") + 1).toLowerCase();
|
|
1161
|
+
return new Response(bunFile(real), {
|
|
1162
|
+
headers: { "content-type": MIME[ext] ?? "application/octet-stream", "cache-control": cache }
|
|
1163
|
+
});
|
|
1164
|
+
}
|
|
1165
|
+
async function serveSpaShell(distRoot) {
|
|
1166
|
+
const index = await realpathSafe(path.join(distRoot, "index.html"));
|
|
1167
|
+
if (index && (index === distRoot || index.startsWith(distRoot + path.sep)) && await promises.stat(index).then((s) => s.isFile(), () => false)) {
|
|
1168
|
+
return new Response(bunFile(index), {
|
|
1169
|
+
headers: { "content-type": MIME.html, "cache-control": "no-cache" }
|
|
1170
|
+
});
|
|
1171
|
+
}
|
|
1172
|
+
return void 0;
|
|
1173
|
+
}
|
|
1174
|
+
async function staticResponse(distRoot, method, pathname) {
|
|
1175
|
+
if (method !== "GET") return plain("method not allowed", 405);
|
|
1176
|
+
if (!distRoot) {
|
|
1177
|
+
return plain("wod-wiki-api: playground dist not found. Set PLAYGROUND_DIST or run the playground server build.", 503);
|
|
1178
|
+
}
|
|
1179
|
+
let rel;
|
|
1180
|
+
try {
|
|
1181
|
+
rel = decodeURIComponent(pathname).replace(/^\/+/, "");
|
|
1182
|
+
} catch {
|
|
1183
|
+
return plain("bad request", 400);
|
|
1184
|
+
}
|
|
1185
|
+
if (rel === "") rel = "index.html";
|
|
1186
|
+
const parts = rel.split("/");
|
|
1187
|
+
if (parts.some((p) => p === "..")) return plain("forbidden", 403);
|
|
1188
|
+
const base = parts[parts.length - 1] ?? "";
|
|
1189
|
+
const hasExtension = base.includes(".");
|
|
1190
|
+
const abs = path.resolve(distRoot, ...parts);
|
|
1191
|
+
const real = await realpathSafe(abs);
|
|
1192
|
+
if (real && (real === distRoot || real.startsWith(distRoot + path.sep))) {
|
|
1193
|
+
const info = await promises.stat(real).then((s) => s.isFile(), () => false);
|
|
1194
|
+
if (info) return serveFile(real, rel);
|
|
1195
|
+
}
|
|
1196
|
+
if (!hasExtension) {
|
|
1197
|
+
const shell = await serveSpaShell(distRoot);
|
|
1198
|
+
if (shell) return shell;
|
|
1199
|
+
}
|
|
1200
|
+
return plain("not found", 404);
|
|
1201
|
+
}
|
|
1202
|
+
async function storeRoutes(db, method, sub, url, req) {
|
|
1203
|
+
let inner = sub.slice("/v1/".length);
|
|
1204
|
+
if (inner.endsWith("/")) inner = inner.slice(0, -1);
|
|
1205
|
+
if (inner === "") return notFound();
|
|
1206
|
+
const segments = inner.split("/");
|
|
1207
|
+
let name;
|
|
1208
|
+
let action;
|
|
1209
|
+
if (segments.length === 1) {
|
|
1210
|
+
name = segments[0];
|
|
1211
|
+
} else if (segments.length === 2) {
|
|
1212
|
+
[name, action] = segments;
|
|
1213
|
+
} else if (segments.length === 3 && segments[1] === "index" && segments[2] !== "") {
|
|
1214
|
+
[name, , action] = segments;
|
|
1215
|
+
action = `index/${action}`;
|
|
1216
|
+
} else {
|
|
1217
|
+
return notFound();
|
|
1218
|
+
}
|
|
1219
|
+
const def = sql.storeDefinition(name);
|
|
1220
|
+
const range = rangeParam(url);
|
|
1221
|
+
const count = countParam(url);
|
|
1222
|
+
if (action === "get" && method === "GET") {
|
|
1223
|
+
const key = jsonParam(url, "key");
|
|
1224
|
+
if (key === void 0) throw new HttpError(400, "missing ?key");
|
|
1225
|
+
const row = await sql.getRow(db, def, key);
|
|
1226
|
+
return row === void 0 ? notFound() : json(row, 200);
|
|
1227
|
+
}
|
|
1228
|
+
if (action === "all" && method === "GET") {
|
|
1229
|
+
return json(await sql.listRows(db, def, range, count), 200);
|
|
1230
|
+
}
|
|
1231
|
+
if (action === "count" && method === "GET") {
|
|
1232
|
+
const indexName = qget(url, "index");
|
|
1233
|
+
const n = indexName ? await sql.countRows(db, def, range, indexName) : await sql.countRows(db, def, range);
|
|
1234
|
+
return json({ count: Number(n) }, 200);
|
|
1235
|
+
}
|
|
1236
|
+
if (action === "clear" && method === "POST") {
|
|
1237
|
+
await db.transaction((tx) => sql.refreshDomain(tx, [{ op: "clear", store: def.name }]));
|
|
1238
|
+
return noContent();
|
|
1239
|
+
}
|
|
1240
|
+
if (action?.startsWith("index/") && method === "GET") {
|
|
1241
|
+
return json(await sql.listRows(db, def, range, count, action.slice("index/".length)), 200);
|
|
1242
|
+
}
|
|
1243
|
+
if (action === void 0 && method === "PUT") {
|
|
1244
|
+
const parsed = await readJsonBody(req);
|
|
1245
|
+
const value = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) && "value" in parsed ? parsed.value : void 0;
|
|
1246
|
+
if (value === void 0) throw new HttpError(400, "body must be {value: ...}");
|
|
1247
|
+
const [key] = await db.transaction((tx) => sql.refreshDomain(tx, [{ op: "put", store: def.name, value }]));
|
|
1248
|
+
return json({ key }, 200);
|
|
1249
|
+
}
|
|
1250
|
+
if (action === void 0 && method === "DELETE") {
|
|
1251
|
+
const keyParam = jsonParam(url, "key");
|
|
1252
|
+
const target = keyParam !== void 0 ? keyParam : range;
|
|
1253
|
+
if (target === void 0 || target === null) throw new HttpError(400, "DELETE requires ?key or ?range");
|
|
1254
|
+
await db.transaction((tx) => sql.refreshDomain(tx, [{ op: "delete", store: def.name, key: target }]));
|
|
1255
|
+
return noContent();
|
|
1256
|
+
}
|
|
1257
|
+
return methodNotAllowed();
|
|
1258
|
+
}
|
|
1259
|
+
async function apiRoutes(db, req, method, sub, url) {
|
|
1260
|
+
if (sub === "/health") {
|
|
1261
|
+
return json({ ok: true, driver: db.dialect }, 200);
|
|
1262
|
+
}
|
|
1263
|
+
if (sub === "/v1/wipe" && method === "POST") {
|
|
1264
|
+
await db.transaction(async (tx) => {
|
|
1265
|
+
await sql.wipeRows(tx);
|
|
1266
|
+
await sql.wipeDomain(tx);
|
|
1267
|
+
});
|
|
1268
|
+
return noContent();
|
|
1269
|
+
}
|
|
1270
|
+
if (sub === "/v1/tx" && method === "POST") {
|
|
1271
|
+
const parsed = await readJsonBody(req);
|
|
1272
|
+
const ops = typeof parsed === "object" && parsed !== null && "ops" in parsed ? parsed.ops : void 0;
|
|
1273
|
+
const parsedOps = txOps(ops);
|
|
1274
|
+
const results = await db.transaction((tx) => sql.refreshDomain(tx, parsedOps));
|
|
1275
|
+
return json({ results }, 200);
|
|
1276
|
+
}
|
|
1277
|
+
if (sub === "/v1/query") {
|
|
1278
|
+
if (method !== "POST") return methodNotAllowed();
|
|
1279
|
+
const body = await readJsonBody(req, sql.MAX_BODY);
|
|
1280
|
+
return json(await sql.handleDomainQuery(db, body), 200);
|
|
1281
|
+
}
|
|
1282
|
+
if (sub.startsWith("/v1/")) return storeRoutes(db, method, sub, url, req);
|
|
1283
|
+
return notFound();
|
|
1284
|
+
}
|
|
1285
|
+
function distRootOf(playgroundDist) {
|
|
1286
|
+
if (!playgroundDist) return void 0;
|
|
1287
|
+
try {
|
|
1288
|
+
return fs.realpathSync(playgroundDist);
|
|
1289
|
+
} catch {
|
|
1290
|
+
return void 0;
|
|
1291
|
+
}
|
|
1292
|
+
}
|
|
1293
|
+
function createHandler(db, options) {
|
|
1294
|
+
const distRoot = distRootOf(options.playgroundDist);
|
|
1295
|
+
return async (request) => {
|
|
1296
|
+
try {
|
|
1297
|
+
const url = new URL(request.url);
|
|
1298
|
+
const method = request.method === "HEAD" ? "GET" : request.method;
|
|
1299
|
+
const path = url.pathname;
|
|
1300
|
+
const response = path === "/api" || path.startsWith("/api/") ? db ? await apiRoutes(db, request, method, path.slice("/api".length) || "/", url) : notFound() : await staticResponse(distRoot, method, path);
|
|
1301
|
+
return response;
|
|
1302
|
+
} catch (e) {
|
|
1303
|
+
if (e instanceof HttpError || e instanceof sql.StorageError) {
|
|
1304
|
+
const status = e.status;
|
|
1305
|
+
if (status >= 500) console.error("[wod-wiki-api]", e.message);
|
|
1306
|
+
const body = { error: status >= 500 ? "internal error" : e.message };
|
|
1307
|
+
if (e.code) body.code = e.code;
|
|
1308
|
+
return json(body, status);
|
|
1309
|
+
}
|
|
1310
|
+
console.error("[wod-wiki-api]", e);
|
|
1311
|
+
return json({ error: "internal error" }, 500);
|
|
1312
|
+
}
|
|
1313
|
+
};
|
|
1314
|
+
}
|
|
1315
|
+
var json, plain, notFound, methodNotAllowed, noContent, qget, MIME;
|
|
1316
|
+
var init_app = __esm({
|
|
1317
|
+
"src/server/app.ts"() {
|
|
1318
|
+
init_errors();
|
|
1319
|
+
json = (value, status) => new Response(JSON.stringify(value), { status, headers: { "content-type": "application/json" } });
|
|
1320
|
+
plain = (body, status) => new Response(body, { status, headers: { "content-type": "text/plain; charset=utf-8" } });
|
|
1321
|
+
notFound = () => json({ error: "not found" }, 404);
|
|
1322
|
+
methodNotAllowed = () => json({ error: "method not allowed" }, 405);
|
|
1323
|
+
noContent = () => new Response(null, { status: 204 });
|
|
1324
|
+
qget = (url, name) => url.searchParams.get(name) ?? void 0;
|
|
1325
|
+
MIME = {
|
|
1326
|
+
html: "text/html; charset=utf-8",
|
|
1327
|
+
js: "text/javascript; charset=utf-8",
|
|
1328
|
+
mjs: "text/javascript; charset=utf-8",
|
|
1329
|
+
css: "text/css; charset=utf-8",
|
|
1330
|
+
json: "application/json; charset=utf-8",
|
|
1331
|
+
map: "application/json; charset=utf-8",
|
|
1332
|
+
svg: "image/svg+xml",
|
|
1333
|
+
png: "image/png",
|
|
1334
|
+
jpg: "image/jpeg",
|
|
1335
|
+
jpeg: "image/jpeg",
|
|
1336
|
+
webp: "image/webp",
|
|
1337
|
+
ico: "image/x-icon",
|
|
1338
|
+
woff: "font/woff",
|
|
1339
|
+
woff2: "font/woff2",
|
|
1340
|
+
ttf: "font/ttf",
|
|
1341
|
+
mp3: "audio/mpeg",
|
|
1342
|
+
wav: "audio/wav",
|
|
1343
|
+
webmanifest: "application/manifest+json",
|
|
1344
|
+
xml: "application/xml",
|
|
1345
|
+
txt: "text/plain; charset=utf-8"
|
|
1346
|
+
};
|
|
1347
|
+
}
|
|
1348
|
+
});
|
|
1349
|
+
|
|
1350
|
+
// src/cli/server.ts
|
|
1351
|
+
var server_exports = {};
|
|
1352
|
+
__export(server_exports, {
|
|
1353
|
+
runCliServer: () => runCliServer
|
|
1354
|
+
});
|
|
1355
|
+
function bun() {
|
|
1356
|
+
const b = globalThis.Bun;
|
|
1357
|
+
if (!b) {
|
|
1358
|
+
throw new Error("wod server/playground requires the Bun runtime \u2014 start with: bun wod server");
|
|
1359
|
+
}
|
|
1360
|
+
return b;
|
|
1361
|
+
}
|
|
1362
|
+
function moduleDir() {
|
|
1363
|
+
const p = nodePath();
|
|
1364
|
+
const meta = ({ url: (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('wod.cjs', document.baseURI).href)) });
|
|
1365
|
+
if (typeof meta.dir === "string") return p.resolve(meta.dir);
|
|
1366
|
+
if (typeof meta.url === "string" && meta.url.startsWith("file:")) {
|
|
1367
|
+
return p.resolve(p.dirname(decodeURIComponent(new URL(".", meta.url).pathname)));
|
|
1368
|
+
}
|
|
1369
|
+
throw new Error("wod server/playground: cannot determine the installed engine module directory");
|
|
1370
|
+
}
|
|
1371
|
+
function engineRoot() {
|
|
1372
|
+
const p = nodePath();
|
|
1373
|
+
const fs = nodeFs();
|
|
1374
|
+
for (let dir = moduleDir(); ; dir = p.dirname(dir)) {
|
|
1375
|
+
try {
|
|
1376
|
+
if (JSON.parse(fs.readFileSync(p.resolve(dir, "package.json"), "utf8")).name === "@bitcobblers/wod-wiki-tools") return dir;
|
|
1377
|
+
} catch {
|
|
1378
|
+
}
|
|
1379
|
+
const parent = p.dirname(dir);
|
|
1380
|
+
if (parent === dir) break;
|
|
1381
|
+
}
|
|
1382
|
+
throw new Error("wod server/playground: cannot locate the installed @bitcobblers/wod-wiki-tools package");
|
|
1383
|
+
}
|
|
1384
|
+
function resolveDist(mode, options) {
|
|
1385
|
+
const p = nodePath();
|
|
1386
|
+
const explicit = options.dist?.trim() || options.env.PLAYGROUND_DIST?.trim() || void 0;
|
|
1387
|
+
if (explicit) {
|
|
1388
|
+
const dist2 = p.resolve(explicit);
|
|
1389
|
+
if (!nodeFs().existsSync(p.resolve(dist2, "index.html"))) {
|
|
1390
|
+
throw new Error(
|
|
1391
|
+
`wod ${mode}: no built frontend (index.html) at ${dist2} \u2014 --dist/PLAYGROUND_DIST must point at an already-built directory (the CLI never builds frontends at runtime)`
|
|
1392
|
+
);
|
|
1393
|
+
}
|
|
1394
|
+
return dist2;
|
|
1395
|
+
}
|
|
1396
|
+
const dist = p.resolve(engineRoot(), "dist", "web", mode === "playground" ? "playground" : "server");
|
|
1397
|
+
if (!nodeFs().existsSync(p.resolve(dist, "index.html"))) {
|
|
1398
|
+
throw new Error(
|
|
1399
|
+
`wod ${mode}: packaged frontend missing \u2014 expected ${dist}/index.html. Reinstall @bitcobblers/wod-wiki-tools (bun add @bitcobblers/wod-wiki-tools), or rebuild the release assets from a checkout (bun run build:cli) and reinstall the package.`
|
|
1400
|
+
);
|
|
1401
|
+
}
|
|
1402
|
+
return dist;
|
|
1403
|
+
}
|
|
1404
|
+
function resolveBind(mode, options) {
|
|
1405
|
+
const host = options.host?.trim() || options.env.HOST?.trim() || "127.0.0.1";
|
|
1406
|
+
const rawPort = options.port?.trim() || options.env.PORT?.trim() || "3000";
|
|
1407
|
+
const port = Number(rawPort);
|
|
1408
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
1409
|
+
throw new Error(`wod ${mode}: invalid port ${JSON.stringify(rawPort)} (need integer 1..65535)`);
|
|
1410
|
+
}
|
|
1411
|
+
return { host, port };
|
|
1412
|
+
}
|
|
1413
|
+
async function runCliServer(mode, options, writeOut) {
|
|
1414
|
+
const runtime = bun();
|
|
1415
|
+
const { host, port } = resolveBind(mode, options);
|
|
1416
|
+
let db;
|
|
1417
|
+
let dbLabel = "no database";
|
|
1418
|
+
if (mode === "server") {
|
|
1419
|
+
const database = options.database;
|
|
1420
|
+
if (!database) {
|
|
1421
|
+
throw new Error("wod server: no database configuration resolved \u2014 this is a runner bug (expected resolveDatabaseConfig output)");
|
|
1422
|
+
}
|
|
1423
|
+
try {
|
|
1424
|
+
db = await openCliDb(database, { initialize: false });
|
|
1425
|
+
} catch (e) {
|
|
1426
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
1427
|
+
throw new Error(`wod server: database not ready \u2014 run \`wod init\` first. ${message}`, { cause: e });
|
|
1428
|
+
}
|
|
1429
|
+
dbLabel = db.path;
|
|
1430
|
+
}
|
|
1431
|
+
let server;
|
|
1432
|
+
try {
|
|
1433
|
+
const dist = resolveDist(mode, options);
|
|
1434
|
+
const handler = createHandler(db?.db ?? null, { playgroundDist: dist });
|
|
1435
|
+
server = runtime.serve({ port, hostname: host, fetch: handler });
|
|
1436
|
+
if (mode === "server") {
|
|
1437
|
+
writeOut(`wod server: http://${host}:${port} \u2014 ${dbLabel} \xB7 dist ${dist}`);
|
|
1438
|
+
} else {
|
|
1439
|
+
writeOut(`wod playground: http://${host}:${port} \u2014 in-browser storage (no database) \xB7 dist ${dist}`);
|
|
1440
|
+
}
|
|
1441
|
+
} catch (e) {
|
|
1442
|
+
if (db) await db.close();
|
|
1443
|
+
throw e;
|
|
1444
|
+
}
|
|
1445
|
+
let closing = false;
|
|
1446
|
+
const shutdown = async () => {
|
|
1447
|
+
if (closing) process.exit(0);
|
|
1448
|
+
closing = true;
|
|
1449
|
+
try {
|
|
1450
|
+
await server.stop();
|
|
1451
|
+
} finally {
|
|
1452
|
+
if (db) await db.close();
|
|
1453
|
+
process.exit(0);
|
|
1454
|
+
}
|
|
1455
|
+
};
|
|
1456
|
+
process.on("SIGINT", () => {
|
|
1457
|
+
void shutdown();
|
|
1458
|
+
});
|
|
1459
|
+
process.on("SIGTERM", () => {
|
|
1460
|
+
void shutdown();
|
|
1461
|
+
});
|
|
1462
|
+
await new Promise(() => {
|
|
1463
|
+
});
|
|
1464
|
+
}
|
|
1465
|
+
var init_server = __esm({
|
|
1466
|
+
"src/cli/server.ts"() {
|
|
1467
|
+
init_db();
|
|
1468
|
+
init_app();
|
|
1469
|
+
}
|
|
1470
|
+
});
|
|
1471
|
+
function getPathUtils() {
|
|
1472
|
+
if (typeof globalThis.process?.versions?.node === "undefined" && !("Bun" in globalThis)) {
|
|
1473
|
+
throw new Error("Path resolution is only supported in Node / Bun environments");
|
|
1474
|
+
}
|
|
1475
|
+
return {
|
|
1476
|
+
// eslint-disable-next-line no-restricted-syntax -- lazy CJS require keeps node builtins out of browser bundles
|
|
1477
|
+
resolve: __require("path").resolve,
|
|
1478
|
+
// eslint-disable-next-line no-restricted-syntax -- lazy CJS require keeps node builtins out of browser bundles
|
|
1479
|
+
pathToFileURL: __require("url").pathToFileURL
|
|
1480
|
+
};
|
|
1481
|
+
}
|
|
1482
|
+
var PackLoadError = class extends Error {
|
|
1483
|
+
constructor(spec, originalError) {
|
|
1484
|
+
const msg = originalError instanceof Error ? originalError.message : String(originalError);
|
|
1485
|
+
super(`Failed to load Language Pack "${spec}": ${msg}`);
|
|
1486
|
+
this.spec = spec;
|
|
1487
|
+
this.originalError = originalError;
|
|
1488
|
+
this.name = "PackLoadError";
|
|
1489
|
+
}
|
|
1490
|
+
spec;
|
|
1491
|
+
originalError;
|
|
1492
|
+
};
|
|
1493
|
+
async function loadLanguagePack(moduleSpec) {
|
|
1494
|
+
try {
|
|
1495
|
+
let importPath = moduleSpec;
|
|
1496
|
+
if (moduleSpec.startsWith(".") || moduleSpec.startsWith("/") || moduleSpec.includes("\\") || moduleSpec.endsWith(".ts") || moduleSpec.endsWith(".js") || moduleSpec.endsWith(".mjs")) {
|
|
1497
|
+
const { resolve: resolve2, pathToFileURL } = getPathUtils();
|
|
1498
|
+
const resolved = resolve2(process.cwd(), moduleSpec);
|
|
1499
|
+
importPath = pathToFileURL(resolved).href;
|
|
1500
|
+
}
|
|
1501
|
+
const imported = await import(
|
|
1502
|
+
/* @vite-ignore */
|
|
1503
|
+
importPath
|
|
1504
|
+
);
|
|
1505
|
+
const candidate = imported.default ?? imported.pack ?? imported;
|
|
1506
|
+
if (!candidate || typeof candidate !== "object") {
|
|
1507
|
+
throw new Error(`Module "${moduleSpec}" does not export a valid LanguagePack object`);
|
|
1508
|
+
}
|
|
1509
|
+
const pack = candidate;
|
|
1510
|
+
wodWikiEngine.registerLanguagePack(pack);
|
|
1511
|
+
return pack;
|
|
1512
|
+
} catch (error) {
|
|
1513
|
+
if (error instanceof PackLoadError) throw error;
|
|
1514
|
+
throw new PackLoadError(moduleSpec, error);
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
var ParseSyntaxError = class extends Error {
|
|
1518
|
+
constructor(errors, message = "Parse error in Whiteboard Script") {
|
|
1519
|
+
const details = errors.map((e) => e.message).join("; ");
|
|
1520
|
+
super(`${message}: ${details}`);
|
|
1521
|
+
this.errors = errors;
|
|
1522
|
+
this.name = "ParseSyntaxError";
|
|
1523
|
+
}
|
|
1524
|
+
errors;
|
|
1525
|
+
};
|
|
1526
|
+
function runParse(source, options = {}) {
|
|
1527
|
+
const parser = wodWikiLang.createParser();
|
|
1528
|
+
const script = parser.read(source, options.sport);
|
|
1529
|
+
if (script.errors && script.errors.length > 0) {
|
|
1530
|
+
throw new ParseSyntaxError(script.errors);
|
|
1531
|
+
}
|
|
1532
|
+
const tree = wodWikiEngine.buildStatementTree(script);
|
|
1533
|
+
return wodWikiEngine.createIRFile("parse-tree", tree, { source: options.sourceLabel ?? "cli:wod parse" });
|
|
1534
|
+
}
|
|
1535
|
+
function buildWorkoutResults(outputs, options) {
|
|
1536
|
+
return {
|
|
1537
|
+
startTime: options.startTime ?? options.now.nowMs(),
|
|
1538
|
+
endTime: options.now.nowMs(),
|
|
1539
|
+
duration: options.elapsedTime,
|
|
1540
|
+
completed: options.completed,
|
|
1541
|
+
logs: outputs.map(wodWikiLang.toStoredOutputStatement)
|
|
1542
|
+
};
|
|
1543
|
+
}
|
|
1544
|
+
async function runExecution(source, options = {}) {
|
|
1545
|
+
const parser = wodWikiLang.createParser();
|
|
1546
|
+
const script = parser.read(source, options.sport);
|
|
1547
|
+
if (script.errors && script.errors.length > 0) {
|
|
1548
|
+
throw new ParseSyntaxError(script.errors);
|
|
1549
|
+
}
|
|
1550
|
+
const startTime = options.startTime ?? Date.now();
|
|
1551
|
+
const now = options.now ?? wodWikiLang.frozenNow(new Date(startTime));
|
|
1552
|
+
const compiler = wodWikiLang.createCompiler();
|
|
1553
|
+
const clock = wodWikiLang.createMockClock(new Date(startTime));
|
|
1554
|
+
const stack = new wodWikiLang.RuntimeStack();
|
|
1555
|
+
const eventBus = new wodWikiLang.EventBus();
|
|
1556
|
+
const runtime = new wodWikiLang.ScriptRuntime(
|
|
1557
|
+
script,
|
|
1558
|
+
compiler,
|
|
1559
|
+
{ stack, clock, eventBus },
|
|
1560
|
+
{},
|
|
1561
|
+
now
|
|
1562
|
+
);
|
|
1563
|
+
const { engine, analyticsContext } = wodWikiLang.createAnalyticsEngineForBlock({
|
|
1564
|
+
id: options.blockId ?? "cli-block",
|
|
1565
|
+
content: source,
|
|
1566
|
+
statements: script.statements,
|
|
1567
|
+
sport: options.sport,
|
|
1568
|
+
version: options.blockVersion ?? 1,
|
|
1569
|
+
startLine: 0,
|
|
1570
|
+
endLine: 0,
|
|
1571
|
+
dialect: options.dialect ?? "time",
|
|
1572
|
+
state: "idle",
|
|
1573
|
+
createdAt: Date.now()
|
|
1574
|
+
});
|
|
1575
|
+
runtime.analyticsContext = analyticsContext;
|
|
1576
|
+
runtime.setAnalyticsEngine(engine);
|
|
1577
|
+
const outputs = [];
|
|
1578
|
+
runtime.subscribeToOutput((out) => {
|
|
1579
|
+
outputs.push(out);
|
|
1580
|
+
});
|
|
1581
|
+
runtime.do(new wodWikiLang.StartSessionAction());
|
|
1582
|
+
const maxSteps = options.maxIterations ?? 5e3;
|
|
1583
|
+
let steps = 0;
|
|
1584
|
+
while (stack.count > 0 && steps < maxSteps) {
|
|
1585
|
+
runtime.handle(new wodWikiLang.NextEvent(void 0, runtime.nowProvider));
|
|
1586
|
+
clock.advance(1e3);
|
|
1587
|
+
steps++;
|
|
1588
|
+
}
|
|
1589
|
+
const workoutResults = buildWorkoutResults(outputs, {
|
|
1590
|
+
startTime,
|
|
1591
|
+
elapsedTime: steps * 1e3,
|
|
1592
|
+
completed: stack.count === 0,
|
|
1593
|
+
now
|
|
1594
|
+
});
|
|
1595
|
+
const logs = outputs.map(wodWikiLang.toStoredOutputStatement);
|
|
1596
|
+
return wodWikiEngine.createIRFile(
|
|
1597
|
+
"execution-log",
|
|
1598
|
+
{
|
|
1599
|
+
results: workoutResults,
|
|
1600
|
+
logs,
|
|
1601
|
+
statements: logs,
|
|
1602
|
+
sourceScript: source
|
|
1603
|
+
},
|
|
1604
|
+
{ source: options.sourceLabel ?? "cli:wod run" }
|
|
1605
|
+
);
|
|
1606
|
+
}
|
|
1607
|
+
function getFs() {
|
|
1608
|
+
if (typeof globalThis.process?.versions?.node === "undefined" && typeof globalThis.Bun === "undefined") {
|
|
1609
|
+
throw new Error("File system operations are only supported in Node / Bun environments");
|
|
1610
|
+
}
|
|
1611
|
+
return __require("fs");
|
|
1612
|
+
}
|
|
1613
|
+
var WqlSyntaxError = class extends Error {
|
|
1614
|
+
constructor(query, syntaxError) {
|
|
1615
|
+
super(`WQL Syntax Error in "${query}": ${syntaxError}`);
|
|
1616
|
+
this.query = query;
|
|
1617
|
+
this.syntaxError = syntaxError;
|
|
1618
|
+
this.name = "WqlSyntaxError";
|
|
1619
|
+
}
|
|
1620
|
+
query;
|
|
1621
|
+
syntaxError;
|
|
1622
|
+
};
|
|
1623
|
+
function extractPayload(rawJson) {
|
|
1624
|
+
try {
|
|
1625
|
+
const parsed = JSON.parse(rawJson);
|
|
1626
|
+
if (wodWikiEngine.isIRFile(parsed)) {
|
|
1627
|
+
return parsed.data;
|
|
1628
|
+
}
|
|
1629
|
+
return parsed;
|
|
1630
|
+
} catch (err) {
|
|
1631
|
+
throw new Error(`Failed to parse JSON input: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
function buildStoresFromData(data) {
|
|
1635
|
+
const events = [
|
|
1636
|
+
...data.eventRecords,
|
|
1637
|
+
...data.facts.map((f, i) => ({
|
|
1638
|
+
id: `fact:${f.resultId ?? "stdin"}:${f.metricKey ?? f.type}:${i}`,
|
|
1639
|
+
resultId: f.resultId ?? "stdin-result-1",
|
|
1640
|
+
noteId: f.noteId ?? "stdin-note-1",
|
|
1641
|
+
blockContentId: f.blockContentId,
|
|
1642
|
+
pageId: f.pageId,
|
|
1643
|
+
origin: f.origin,
|
|
1644
|
+
timestamp: f.timestamp,
|
|
1645
|
+
grain: f.grain === "event" ? "event" : "summary",
|
|
1646
|
+
outputType: "analytics",
|
|
1647
|
+
effortSlug: f.effortSlug,
|
|
1648
|
+
metrics: [{
|
|
1649
|
+
type: f.metricKey ?? f.type,
|
|
1650
|
+
value: f.value,
|
|
1651
|
+
...f.unit ? { unit: f.unit } : {},
|
|
1652
|
+
origin: "engine"
|
|
1653
|
+
}],
|
|
1654
|
+
blockId: f.blockId,
|
|
1655
|
+
blockVersion: f.blockVersion
|
|
1656
|
+
}))
|
|
1657
|
+
];
|
|
1658
|
+
const eventStore = wodWikiEngine.inMemoryEventStore(events);
|
|
1659
|
+
const noteStore = {
|
|
1660
|
+
getAllNotes: async () => [...data.notes],
|
|
1661
|
+
getNotesByIds: async (ids) => {
|
|
1662
|
+
const selected = new Set(ids);
|
|
1663
|
+
return data.notes.filter((note) => selected.has(note.id));
|
|
1664
|
+
},
|
|
1665
|
+
getNoteIdsForTag: async (tag) => {
|
|
1666
|
+
const matching = /* @__PURE__ */ new Set();
|
|
1667
|
+
for (const [noteId, tags] of Object.entries(data.noteTags)) {
|
|
1668
|
+
if (tags.includes(tag)) matching.add(noteId);
|
|
1669
|
+
}
|
|
1670
|
+
return matching;
|
|
1671
|
+
},
|
|
1672
|
+
getNoteTagLabels: async (noteId) => [...data.noteTags[noteId] ?? []]
|
|
1673
|
+
};
|
|
1674
|
+
const blockStore = {
|
|
1675
|
+
getAllBlocks: async () => [...data.blocks]
|
|
1676
|
+
};
|
|
1677
|
+
const effortStore = {
|
|
1678
|
+
getAllEfforts: async () => [...data.efforts]
|
|
1679
|
+
};
|
|
1680
|
+
return { eventStore, noteStore, blockStore, effortStore };
|
|
1681
|
+
}
|
|
1682
|
+
function loadQueryData(options) {
|
|
1683
|
+
const data = {
|
|
1684
|
+
eventRecords: [],
|
|
1685
|
+
facts: [],
|
|
1686
|
+
results: [],
|
|
1687
|
+
notes: [],
|
|
1688
|
+
blocks: [],
|
|
1689
|
+
revisions: [],
|
|
1690
|
+
efforts: [...wodWikiLang.bundledEfforts],
|
|
1691
|
+
noteTags: {}
|
|
1692
|
+
};
|
|
1693
|
+
if (options.corpusPath) {
|
|
1694
|
+
const fs = getFs();
|
|
1695
|
+
if (!fs.existsSync(options.corpusPath)) {
|
|
1696
|
+
throw new Error(`Corpus file not found at path: ${options.corpusPath}`);
|
|
1697
|
+
}
|
|
1698
|
+
const raw = fs.readFileSync(options.corpusPath, "utf-8");
|
|
1699
|
+
const payload = extractPayload(raw);
|
|
1700
|
+
if (Array.isArray(payload)) {
|
|
1701
|
+
data.facts = payload;
|
|
1702
|
+
} else if (payload && typeof payload === "object") {
|
|
1703
|
+
const obj = payload;
|
|
1704
|
+
if ("segments" in obj) throw new Error("Incompatible corpus segments; whole Notes and block revisions are required");
|
|
1705
|
+
if (obj.kind === "event-journal" || Array.isArray(obj.records)) {
|
|
1706
|
+
if (Array.isArray(obj.blockRevisions)) data.revisions = obj.blockRevisions;
|
|
1707
|
+
if (Array.isArray(obj.sessions)) data.results = obj.sessions;
|
|
1708
|
+
if (Array.isArray(obj.records)) {
|
|
1709
|
+
data.eventRecords = obj.records;
|
|
1710
|
+
}
|
|
1711
|
+
if (Array.isArray(obj.notes)) {
|
|
1712
|
+
data.notes = obj.notes;
|
|
1713
|
+
for (const n of obj.notes) {
|
|
1714
|
+
if (n && typeof n === "object" && n.id && Array.isArray(n.tags)) {
|
|
1715
|
+
data.noteTags[n.id] = n.tags;
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
} else if (obj.facts || obj.results || obj.notes || obj.blocks || obj.efforts || obj.tags || obj.logs) {
|
|
1720
|
+
const corpus = payload;
|
|
1721
|
+
if (corpus.facts) data.facts = corpus.facts;
|
|
1722
|
+
if (Array.isArray(corpus.results)) data.results = corpus.results;
|
|
1723
|
+
if (corpus.notes) data.notes = corpus.notes;
|
|
1724
|
+
if (corpus.blocks) data.blocks = corpus.blocks;
|
|
1725
|
+
if (corpus.efforts) data.efforts = corpus.efforts;
|
|
1726
|
+
if (corpus.revisions) data.revisions = corpus.revisions;
|
|
1727
|
+
if (corpus.tags) data.noteTags = corpus.tags;
|
|
1728
|
+
if (corpus.logs) {
|
|
1729
|
+
const identity = {
|
|
1730
|
+
noteId: "corpus-note-1",
|
|
1731
|
+
resultId: "corpus-result-1",
|
|
1732
|
+
origin: "journal",
|
|
1733
|
+
workoutTimestamp: corpus.logs[0]?.timeSpan?.started ?? Date.now()
|
|
1734
|
+
};
|
|
1735
|
+
data.eventRecords = [...wodWikiWql.toEventRows(corpus.logs, identity), ...wodWikiWql.toSummaryEventRows(corpus.logs, identity)];
|
|
1736
|
+
}
|
|
1737
|
+
} else {
|
|
1738
|
+
throw new Error(`Unrecognized corpus payload shape in "${options.corpusPath}" (expected event-journal, fact-set, or CorpusIRData)`);
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
} else if (options.stdinLog) {
|
|
1742
|
+
const payload = extractPayload(options.stdinLog);
|
|
1743
|
+
let executionLog;
|
|
1744
|
+
const rawLogs = payload.logs ?? ("statements" in payload ? payload.statements : void 0) ?? [];
|
|
1745
|
+
if ("results" in payload) {
|
|
1746
|
+
executionLog = { results: payload.results, logs: rawLogs, statements: rawLogs };
|
|
1747
|
+
} else {
|
|
1748
|
+
executionLog = { results: payload, logs: rawLogs, statements: rawLogs };
|
|
1749
|
+
}
|
|
1750
|
+
const identity = {
|
|
1751
|
+
noteId: "stdin-note-1",
|
|
1752
|
+
resultId: "stdin-result-1",
|
|
1753
|
+
origin: "journal",
|
|
1754
|
+
workoutTimestamp: executionLog.results.startTime
|
|
1755
|
+
};
|
|
1756
|
+
data.eventRecords = [
|
|
1757
|
+
...wodWikiWql.toEventRows(executionLog.logs, identity),
|
|
1758
|
+
...wodWikiWql.toSummaryEventRows(executionLog.logs, identity)
|
|
1759
|
+
];
|
|
1760
|
+
} else if (options.stdinFacts) {
|
|
1761
|
+
const payload = extractPayload(options.stdinFacts);
|
|
1762
|
+
if (Array.isArray(payload)) {
|
|
1763
|
+
data.facts = payload;
|
|
1764
|
+
} else if (payload && typeof payload === "object" && "facts" in payload) {
|
|
1765
|
+
data.facts = payload.facts;
|
|
1766
|
+
}
|
|
1767
|
+
} else {
|
|
1768
|
+
throw new Error("No input dataset provided. Specify --corpus <path>, --stdin-log, or --stdin-facts.");
|
|
1769
|
+
}
|
|
1770
|
+
for (const note of data.notes) {
|
|
1771
|
+
if (typeof note.rawContent !== "string" || !Number.isSafeInteger(note.sourceRevision) || note.sourceRevision < 1) {
|
|
1772
|
+
throw new Error("Incompatible corpus Note; exact rawContent and sourceRevision are required");
|
|
1773
|
+
}
|
|
1774
|
+
wodWikiCore.validateNoteBlocks(note.rawContent, note.blocks, note.sourceRevision);
|
|
1775
|
+
if (!data.blocks.some((row) => row.noteId === note.id)) {
|
|
1776
|
+
for (const [position, block] of Object.values(note.blocks).sort((a, b) => a.from - b.from).entries()) {
|
|
1777
|
+
const rawContent = note.rawContent.slice(block.from, block.to);
|
|
1778
|
+
const body = wodWikiCore.parseDocumentSections(rawContent)[0]?.displayContent ?? rawContent;
|
|
1779
|
+
data.blocks.push({
|
|
1780
|
+
id: `${note.id}:${block.id}`,
|
|
1781
|
+
noteId: note.id,
|
|
1782
|
+
blockId: block.id,
|
|
1783
|
+
blockVersion: block.version,
|
|
1784
|
+
sourceRevision: note.sourceRevision,
|
|
1785
|
+
from: block.from,
|
|
1786
|
+
to: block.to,
|
|
1787
|
+
position,
|
|
1788
|
+
dataType: block.kind,
|
|
1789
|
+
rawContent,
|
|
1790
|
+
noteTitle: note.title,
|
|
1791
|
+
createdAt: note.createdAt,
|
|
1792
|
+
...block.kind === "wod" ? { blockContentId: wodWikiCore.blockContentId(body) } : {}
|
|
1793
|
+
});
|
|
1794
|
+
}
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
for (const session of data.results) {
|
|
1798
|
+
if ("segmentId" in session || "segmentVersion" in session || "data" in session || "version" in session || "rawContent" in session || !session.blockId || !Number.isSafeInteger(session.blockVersion) || session.blockVersion < 1) {
|
|
1799
|
+
throw new Error("Incompatible corpus Session; exact blockId/blockVersion pin required");
|
|
1800
|
+
}
|
|
1801
|
+
if (!data.revisions.some((row) => row.noteId === session.noteId && row.blockId === session.blockId && row.version === session.blockVersion && row.kind === "wod")) {
|
|
1802
|
+
throw new Error("Corpus Session immutable revision is unavailable");
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
for (const row of [...data.eventRecords, ...data.facts, ...data.blocks]) {
|
|
1806
|
+
if ("segmentId" in row || "segmentVersion" in row) throw new Error("Incompatible corpus segment pin");
|
|
1807
|
+
}
|
|
1808
|
+
const revisions = new Map(data.revisions.map((row) => [JSON.stringify([row.noteId, row.blockId, row.version]), row]));
|
|
1809
|
+
for (const row of data.eventRecords) {
|
|
1810
|
+
if (row.blockId !== void 0 || row.blockVersion !== void 0) {
|
|
1811
|
+
if (!row.blockId || !Number.isSafeInteger(row.blockVersion) || !revisions.has(JSON.stringify([row.noteId, row.blockId, row.blockVersion]))) {
|
|
1812
|
+
throw new Error("Corpus Event immutable revision is unavailable");
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
for (const row of data.blocks) {
|
|
1817
|
+
const note = data.notes.find((candidate) => candidate.id === row.noteId);
|
|
1818
|
+
const block = note?.blocks[row.blockId];
|
|
1819
|
+
if (!note || !block || row.blockVersion !== block.version || row.sourceRevision !== note.sourceRevision || row.from !== block.from || row.to !== block.to || row.dataType !== block.kind) {
|
|
1820
|
+
throw new Error("Corpus block projection does not match current Note source");
|
|
1821
|
+
}
|
|
1822
|
+
row.rawContent = note.rawContent.slice(block.from, block.to);
|
|
1823
|
+
}
|
|
1824
|
+
return data;
|
|
1825
|
+
}
|
|
1826
|
+
async function runQueryCli(wqlString, options = {}) {
|
|
1827
|
+
const parsed = wodWikiWql.parseQuery(wqlString);
|
|
1828
|
+
if (parsed.error) {
|
|
1829
|
+
throw new WqlSyntaxError(wqlString, parsed.error);
|
|
1830
|
+
}
|
|
1831
|
+
const stores = options.stores ?? buildStoresFromData(loadQueryData(options));
|
|
1832
|
+
const service = new wodWikiWql.QueryService(stores);
|
|
1833
|
+
if (wodWikiWql.isPipelineQuery(parsed)) {
|
|
1834
|
+
const result2 = await service.runPipeline(wqlString, {
|
|
1835
|
+
preferredUnit: options.preferredUnit
|
|
1836
|
+
});
|
|
1837
|
+
return wodWikiEngine.createIRFile("pipeline-result", result2, { source: options.sourceLabel ?? "cli:wod query" });
|
|
1838
|
+
}
|
|
1839
|
+
if (wodWikiWql.isFindQuery(parsed)) {
|
|
1840
|
+
const result2 = await service.runFind(parsed);
|
|
1841
|
+
const kind = parsed.target === "session" ? "rows-result" : "find-result";
|
|
1842
|
+
return wodWikiEngine.createIRFile(kind, result2, { source: options.sourceLabel ?? "cli:wod query" });
|
|
1843
|
+
}
|
|
1844
|
+
const result = await service.runQuery(wqlString, {
|
|
1845
|
+
preferredUnit: options.preferredUnit
|
|
1846
|
+
});
|
|
1847
|
+
return wodWikiEngine.createIRFile("query-result", result, { source: options.sourceLabel ?? "cli:wod query" });
|
|
1848
|
+
}
|
|
1849
|
+
|
|
1850
|
+
// src/cli/runner.ts
|
|
1851
|
+
init_db();
|
|
1852
|
+
|
|
1853
|
+
// src/cli/config.ts
|
|
1854
|
+
function nodeRequire2() {
|
|
1855
|
+
const g = globalThis;
|
|
1856
|
+
if (typeof g.process?.versions?.node === "undefined" && typeof g.Bun === "undefined") {
|
|
1857
|
+
throw new Error("database configuration is only supported in Node / Bun environments");
|
|
1858
|
+
}
|
|
1859
|
+
const req = g.require ?? (typeof __require === "function" ? __require : void 0);
|
|
1860
|
+
if (!req) throw new Error("database configuration requires a CJS require shim (missing tsup banner?)");
|
|
1861
|
+
return req;
|
|
1862
|
+
}
|
|
1863
|
+
var nodePath2 = () => nodeRequire2()("node:path");
|
|
1864
|
+
var nodeFs2 = () => nodeRequire2()("node:fs");
|
|
1865
|
+
function parseEnvFile(content) {
|
|
1866
|
+
return nodeRequire2()("node:util").parseEnv(content);
|
|
1867
|
+
}
|
|
1868
|
+
function loadCliEnvironment(envFile) {
|
|
1869
|
+
const fs = nodeFs2();
|
|
1870
|
+
const path = nodePath2();
|
|
1871
|
+
let file;
|
|
1872
|
+
if (envFile !== void 0) {
|
|
1873
|
+
file = path.resolve(process.cwd(), envFile);
|
|
1874
|
+
if (!fs.existsSync(file)) throw new Error(`[wod] --env-file: file not found: ${envFile}`);
|
|
1875
|
+
} else {
|
|
1876
|
+
let dir = process.cwd();
|
|
1877
|
+
for (; ; ) {
|
|
1878
|
+
const candidate = path.join(dir, ".env");
|
|
1879
|
+
if (fs.existsSync(candidate)) {
|
|
1880
|
+
file = candidate;
|
|
1881
|
+
break;
|
|
1882
|
+
}
|
|
1883
|
+
const parent = path.dirname(dir);
|
|
1884
|
+
if (parent === dir) break;
|
|
1885
|
+
dir = parent;
|
|
1886
|
+
}
|
|
1887
|
+
}
|
|
1888
|
+
return file !== void 0 ? parseEnvFile(fs.readFileSync(file, "utf-8")) : {};
|
|
1889
|
+
}
|
|
1890
|
+
var SQLITE_URL_SCHEMES = /^(libsql|https?|wss?|file):\/\//;
|
|
1891
|
+
var PG_URL_SCHEMES = /^postgres(ql)?:\/\//;
|
|
1892
|
+
var TURSO_URL_SCHEMES = /^(libsql|https?|wss?):\/\//;
|
|
1893
|
+
var PG_FLAG_KEYS = [
|
|
1894
|
+
"postgresHost",
|
|
1895
|
+
"postgresPort",
|
|
1896
|
+
"postgresUser",
|
|
1897
|
+
"postgresPassword",
|
|
1898
|
+
"postgresDatabase",
|
|
1899
|
+
"postgresSsl"
|
|
1900
|
+
];
|
|
1901
|
+
var PG_ENV_KEYS = [
|
|
1902
|
+
"POSTGRES_HOST",
|
|
1903
|
+
"POSTGRES_PORT",
|
|
1904
|
+
"POSTGRES_USER",
|
|
1905
|
+
"POSTGRES_PASSWORD",
|
|
1906
|
+
"POSTGRES_DATABASE",
|
|
1907
|
+
"POSTGRES_SSL"
|
|
1908
|
+
];
|
|
1909
|
+
var isBackend = (v) => v === "sqlite" || v === "postgres" || v === "turso";
|
|
1910
|
+
function setEnv(v) {
|
|
1911
|
+
return v !== void 0 && v.trim() !== "" ? v : void 0;
|
|
1912
|
+
}
|
|
1913
|
+
function fail(message) {
|
|
1914
|
+
throw new Error(`[wod] ${message}`);
|
|
1915
|
+
}
|
|
1916
|
+
function parsePort(v, source) {
|
|
1917
|
+
if (!/^\d+$/.test(v)) fail(`${source} must be an integer 1..65535, got ${JSON.stringify(v)}`);
|
|
1918
|
+
const port = Number(v);
|
|
1919
|
+
if (port < 1 || port > 65535) fail(`${source} must be an integer 1..65535, got ${v}`);
|
|
1920
|
+
return port;
|
|
1921
|
+
}
|
|
1922
|
+
function sslMode(v, source) {
|
|
1923
|
+
if (v === void 0 || v === "") return "prefer";
|
|
1924
|
+
if (typeof v === "boolean") return v ? "require" : "disable";
|
|
1925
|
+
const s = v.trim().toLowerCase();
|
|
1926
|
+
if (["true", "1", "yes", "require"].includes(s)) return "require";
|
|
1927
|
+
if (["false", "0", "no", "disable", "disabled"].includes(s)) return "disable";
|
|
1928
|
+
if (s === "prefer" || s === "verify-ca" || s === "verify-full") return s;
|
|
1929
|
+
fail(`${source} must be disable|prefer|require|verify-ca|verify-full, got ${JSON.stringify(v)}`);
|
|
1930
|
+
}
|
|
1931
|
+
function safeUrlLabel(raw) {
|
|
1932
|
+
try {
|
|
1933
|
+
const u = new URL(raw);
|
|
1934
|
+
return `${u.protocol}//${u.host}${u.pathname}`;
|
|
1935
|
+
} catch {
|
|
1936
|
+
return "<unparsable-url>";
|
|
1937
|
+
}
|
|
1938
|
+
}
|
|
1939
|
+
function postgresFromUrl(url, source) {
|
|
1940
|
+
if (!PG_URL_SCHEMES.test(url)) {
|
|
1941
|
+
fail(`${source} must start with postgres:// or postgresql://`);
|
|
1942
|
+
}
|
|
1943
|
+
let u;
|
|
1944
|
+
try {
|
|
1945
|
+
u = new URL(url);
|
|
1946
|
+
} catch {
|
|
1947
|
+
fail(`${source} is not a parseable URL`);
|
|
1948
|
+
}
|
|
1949
|
+
const database = decodeURIComponent(u.pathname.replace(/^\/+|\/+$/g, ""));
|
|
1950
|
+
if (database === "") fail(`${source} has no database name`);
|
|
1951
|
+
return {
|
|
1952
|
+
kind: "postgres",
|
|
1953
|
+
label: safeUrlLabel(url),
|
|
1954
|
+
url,
|
|
1955
|
+
host: u.hostname,
|
|
1956
|
+
port: u.port !== "" ? parsePort(u.port, `${source} port`) : 5432,
|
|
1957
|
+
database,
|
|
1958
|
+
user: u.username !== "" ? decodeURIComponent(u.username) : void 0,
|
|
1959
|
+
password: u.password !== "" ? decodeURIComponent(u.password) : void 0,
|
|
1960
|
+
ssl: sslMode(u.searchParams.get("sslmode") ?? u.searchParams.get("ssl") ?? void 0, `${source} ssl parameter`)
|
|
1961
|
+
};
|
|
1962
|
+
}
|
|
1963
|
+
function resolvePostgres(options, e, databaseUrl) {
|
|
1964
|
+
const flagProps = PG_FLAG_KEYS.some((k) => options[k] !== void 0);
|
|
1965
|
+
const envProps = PG_ENV_KEYS.some((k) => setEnv(e[k]) !== void 0);
|
|
1966
|
+
if (flagProps || envProps && databaseUrl === void 0) {
|
|
1967
|
+
const host = options.postgresHost ?? setEnv(e.POSTGRES_HOST) ?? "127.0.0.1";
|
|
1968
|
+
const port = parsePort(options.postgresPort ?? setEnv(e.POSTGRES_PORT) ?? "5432", "--postgres-port/POSTGRES_PORT");
|
|
1969
|
+
const database = options.postgresDatabase ?? setEnv(e.POSTGRES_DATABASE);
|
|
1970
|
+
if (database === void 0) {
|
|
1971
|
+
fail("--postgres-database (or POSTGRES_DATABASE) is required for per-property PostgreSQL configuration");
|
|
1972
|
+
}
|
|
1973
|
+
const user = options.postgresUser ?? setEnv(e.POSTGRES_USER);
|
|
1974
|
+
const password = options.postgresPassword ?? setEnv(e.POSTGRES_PASSWORD);
|
|
1975
|
+
const ssl = sslMode(options.postgresSsl ?? setEnv(e.POSTGRES_SSL), "--postgres-ssl/POSTGRES_SSL");
|
|
1976
|
+
try {
|
|
1977
|
+
const u = new URL(`postgresql://${host}`);
|
|
1978
|
+
u.port = String(port);
|
|
1979
|
+
u.pathname = `/${database}`;
|
|
1980
|
+
if (user !== void 0) u.username = user;
|
|
1981
|
+
if (password !== void 0) u.password = password;
|
|
1982
|
+
u.searchParams.set("sslmode", ssl);
|
|
1983
|
+
return {
|
|
1984
|
+
kind: "postgres",
|
|
1985
|
+
label: `postgresql://${u.host}${u.pathname}`,
|
|
1986
|
+
url: u.toString(),
|
|
1987
|
+
host,
|
|
1988
|
+
port,
|
|
1989
|
+
database,
|
|
1990
|
+
user,
|
|
1991
|
+
password,
|
|
1992
|
+
ssl
|
|
1993
|
+
};
|
|
1994
|
+
} catch {
|
|
1995
|
+
fail("invalid PostgreSQL host/database in per-property configuration");
|
|
1996
|
+
}
|
|
1997
|
+
}
|
|
1998
|
+
if (databaseUrl !== void 0) return postgresFromUrl(databaseUrl, "DB_DRIVER=postgres DATABASE_URL");
|
|
1999
|
+
fail("DB_DRIVER=postgres requires DATABASE_URL starting with postgres:// or postgresql:// \u2014 or per-property --postgres-host/--postgres-database flags");
|
|
2000
|
+
}
|
|
2001
|
+
function resolveTurso(options, e, databaseUrl) {
|
|
2002
|
+
const url = options.tursoUrl ?? setEnv(e.TURSO_DATABASE_URL) ?? databaseUrl;
|
|
2003
|
+
if (url === void 0) {
|
|
2004
|
+
fail("DB_DRIVER=turso requires --turso-url / TURSO_DATABASE_URL or DATABASE_URL (libsql:// or https://)");
|
|
2005
|
+
}
|
|
2006
|
+
if (PG_URL_SCHEMES.test(url)) fail("DB_DRIVER=turso cannot use a postgres:// URL");
|
|
2007
|
+
if (!TURSO_URL_SCHEMES.test(url)) fail("DB_DRIVER=turso requires a libsql://, https://, http:// or wss:// URL");
|
|
2008
|
+
return {
|
|
2009
|
+
kind: "turso",
|
|
2010
|
+
label: safeUrlLabel(url),
|
|
2011
|
+
url,
|
|
2012
|
+
authToken: options.tursoAuthToken ?? setEnv(e.TURSO_AUTH_TOKEN) ?? setEnv(e.LIBSQL_AUTH_TOKEN)
|
|
2013
|
+
};
|
|
2014
|
+
}
|
|
2015
|
+
function resolveSqlite(options, e, databaseUrl) {
|
|
2016
|
+
if (options.db !== void 0) {
|
|
2017
|
+
const path2 = nodePath2().resolve(process.cwd(), options.db);
|
|
2018
|
+
return { kind: "sqlite", label: path2, path: path2 };
|
|
2019
|
+
}
|
|
2020
|
+
if (databaseUrl !== void 0) {
|
|
2021
|
+
if (PG_URL_SCHEMES.test(databaseUrl)) fail("DB_DRIVER=sqlite cannot use a postgres:// DATABASE_URL");
|
|
2022
|
+
if (databaseUrl.startsWith("file:")) {
|
|
2023
|
+
const path2 = nodePath2().resolve(process.cwd(), decodeURIComponent(databaseUrl.slice("file:".length).split("?")[0]));
|
|
2024
|
+
return { kind: "sqlite", label: path2, path: path2 };
|
|
2025
|
+
}
|
|
2026
|
+
if (!SQLITE_URL_SCHEMES.test(databaseUrl)) {
|
|
2027
|
+
fail("DB_DRIVER=sqlite requires a libsql://, https://, http://, wss:// or file:// DATABASE_URL");
|
|
2028
|
+
}
|
|
2029
|
+
return { kind: "turso", label: safeUrlLabel(databaseUrl), url: databaseUrl, authToken: setEnv(e.LIBSQL_AUTH_TOKEN) };
|
|
2030
|
+
}
|
|
2031
|
+
const path = nodePath2().resolve(process.cwd(), setEnv(e.WOD_WIKI_DB) ?? setEnv(e.SQLITE_PATH) ?? "./wodwiki.db");
|
|
2032
|
+
return { kind: "sqlite", label: path, path };
|
|
2033
|
+
}
|
|
2034
|
+
function envBackend(e) {
|
|
2035
|
+
const kinds = /* @__PURE__ */ new Set();
|
|
2036
|
+
if (setEnv(e.WOD_WIKI_DB) !== void 0 || setEnv(e.SQLITE_PATH) !== void 0) kinds.add("sqlite");
|
|
2037
|
+
const dbUrl = setEnv(e.DATABASE_URL);
|
|
2038
|
+
if (PG_ENV_KEYS.some((k) => setEnv(e[k]) !== void 0) || dbUrl !== void 0 && PG_URL_SCHEMES.test(dbUrl)) {
|
|
2039
|
+
kinds.add("postgres");
|
|
2040
|
+
} else if (dbUrl !== void 0 && SQLITE_URL_SCHEMES.test(dbUrl)) {
|
|
2041
|
+
kinds.add("sqlite");
|
|
2042
|
+
}
|
|
2043
|
+
if (setEnv(e.TURSO_DATABASE_URL) !== void 0) kinds.add("turso");
|
|
2044
|
+
if (kinds.size > 1) {
|
|
2045
|
+
fail(`ambiguous database configuration: ${[...kinds].join(" + ")} env vars are both set \u2014 set DB_DRIVER (or pass explicit flags) to choose`);
|
|
2046
|
+
}
|
|
2047
|
+
return kinds.values().next().value ?? "sqlite";
|
|
2048
|
+
}
|
|
2049
|
+
function resolveDatabaseConfig(options = {}, env) {
|
|
2050
|
+
const e = env ?? { ...loadCliEnvironment(options.envFile), ...process.env };
|
|
2051
|
+
const driverFlag = options.dbDriver;
|
|
2052
|
+
if (driverFlag !== void 0 && !isBackend(driverFlag)) {
|
|
2053
|
+
fail(`--db-driver must be sqlite|postgres|turso, got ${JSON.stringify(driverFlag)}`);
|
|
2054
|
+
}
|
|
2055
|
+
const pinned = [];
|
|
2056
|
+
if (options.db !== void 0) pinned.push(["--db", "sqlite"]);
|
|
2057
|
+
if (driverFlag !== void 0) pinned.push([`--db-driver ${driverFlag}`, driverFlag]);
|
|
2058
|
+
if (options.tursoUrl !== void 0) pinned.push(["--turso-url", "turso"]);
|
|
2059
|
+
if (options.tursoAuthToken !== void 0) pinned.push(["--turso-auth-token", "turso"]);
|
|
2060
|
+
if (PG_FLAG_KEYS.some((k) => options[k] !== void 0)) pinned.push(["--postgres-*", "postgres"]);
|
|
2061
|
+
const kinds = new Set(pinned.map(([, kind]) => kind));
|
|
2062
|
+
if (kinds.size > 1) {
|
|
2063
|
+
fail(`conflicting database selectors: ${pinned.map(([flag, kind]) => `${flag} (${kind})`).join(", ")}`);
|
|
2064
|
+
}
|
|
2065
|
+
if (options.databaseUrl !== void 0) {
|
|
2066
|
+
if (options.db !== void 0) fail("conflicting database selectors: --db and --database-url are both set");
|
|
2067
|
+
if (options.tursoUrl !== void 0) fail("conflicting database selectors: --turso-url and --database-url are both set");
|
|
2068
|
+
if (PG_FLAG_KEYS.some((k) => options[k] !== void 0)) {
|
|
2069
|
+
fail("conflicting database selectors: --database-url and --postgres-* flags are both set");
|
|
2070
|
+
}
|
|
2071
|
+
}
|
|
2072
|
+
let backend;
|
|
2073
|
+
if (pinned.length > 0) {
|
|
2074
|
+
backend = pinned[0][1];
|
|
2075
|
+
} else {
|
|
2076
|
+
const envDriver = setEnv(e.DB_DRIVER);
|
|
2077
|
+
if (envDriver !== void 0) {
|
|
2078
|
+
if (!isBackend(envDriver)) {
|
|
2079
|
+
fail(`Unsupported DB_DRIVER: ${envDriver} (expected sqlite|turso|postgres)`);
|
|
2080
|
+
}
|
|
2081
|
+
backend = envDriver;
|
|
2082
|
+
} else {
|
|
2083
|
+
backend = envBackend(e);
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
const databaseUrl = options.databaseUrl ?? setEnv(e.DATABASE_URL);
|
|
2087
|
+
switch (backend) {
|
|
2088
|
+
case "postgres":
|
|
2089
|
+
return resolvePostgres(options, e, databaseUrl);
|
|
2090
|
+
case "turso":
|
|
2091
|
+
return resolveTurso(options, e, databaseUrl);
|
|
2092
|
+
case "sqlite":
|
|
2093
|
+
return resolveSqlite(options, e, databaseUrl);
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
|
|
2097
|
+
// src/cli/persist.ts
|
|
2098
|
+
init_db();
|
|
2099
|
+
var registeredWidgets = wodWikiCore.KNOWN_SECTION_WIDGETS;
|
|
2100
|
+
var saveStores = ["notes", "block_revisions", "block_index", "block_efforts", "tags", "note_tags", "sessions"];
|
|
2101
|
+
function extractEffortSlugs(statements) {
|
|
2102
|
+
const slugs = /* @__PURE__ */ new Set();
|
|
2103
|
+
for (const statement of statements) {
|
|
2104
|
+
if (statement.exerciseId) {
|
|
2105
|
+
slugs.add(statement.exerciseId);
|
|
2106
|
+
} else {
|
|
2107
|
+
const effortMetric = statement.metrics?.getMetric?.("effort");
|
|
2108
|
+
const effort = effortMetric && "effort" in effortMetric ? effortMetric.effort : void 0;
|
|
2109
|
+
if (typeof effort === "string") {
|
|
2110
|
+
const slug = effort.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
2111
|
+
if (slug) slugs.add(slug);
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
return [...slugs];
|
|
2116
|
+
}
|
|
2117
|
+
function titleFromLabel(sourceLabel) {
|
|
2118
|
+
if (!sourceLabel || sourceLabel === "-") return "stdin";
|
|
2119
|
+
const stem = sourceLabel.split("/").pop() ?? sourceLabel;
|
|
2120
|
+
return stem.replace(/\.[^.]+$/, "") || sourceLabel;
|
|
2121
|
+
}
|
|
2122
|
+
async function saveSource(db, options, startTime) {
|
|
2123
|
+
const noteId = options.noteId ?? stableNoteId(options.sourceLabel, options.source);
|
|
2124
|
+
const observed = await db.storage.readonly("notes").get(noteId);
|
|
2125
|
+
const expected = options.expectedSourceRevision ?? observed?.sourceRevision ?? 0;
|
|
2126
|
+
const now = options.now ?? Date.now();
|
|
2127
|
+
return db.storage.transaction([...saveStores], "readwrite", async (tx) => {
|
|
2128
|
+
const existing = await tx.readonly("notes").get(noteId);
|
|
2129
|
+
if ((existing?.sourceRevision ?? 0) !== expected) {
|
|
2130
|
+
throw new Error(`Stale Note source revision for ${noteId}; expected ${expected}`);
|
|
2131
|
+
}
|
|
2132
|
+
let sourceRevision = existing?.rawContent === options.source ? existing.sourceRevision : (existing?.sourceRevision ?? 0) + 1;
|
|
2133
|
+
const blocks = wodWikiCore.reconcileNoteBlocks(options.source, {
|
|
2134
|
+
sourceRevision,
|
|
2135
|
+
blocks: options.blocks ?? (existing?.rawContent === options.source ? existing.blocks : void 0),
|
|
2136
|
+
registeredWidgets,
|
|
2137
|
+
createId: randomId
|
|
2138
|
+
});
|
|
2139
|
+
wodWikiCore.validateNoteBlocks(options.source, blocks, sourceRevision, { registeredWidgets });
|
|
2140
|
+
const history = await tx.readonly("block_revisions").getAllFromIndex("by-note", noteId);
|
|
2141
|
+
const latest = /* @__PURE__ */ new Map();
|
|
2142
|
+
for (const row of history) {
|
|
2143
|
+
if ((latest.get(row.blockId)?.version ?? 0) < row.version) latest.set(row.blockId, row);
|
|
2144
|
+
}
|
|
2145
|
+
const revisions = [];
|
|
2146
|
+
for (const block of Object.values(blocks)) {
|
|
2147
|
+
const saved = latest.get(block.id);
|
|
2148
|
+
const rawContent = options.source.slice(block.from, block.to);
|
|
2149
|
+
const unchanged = saved && saved.rawContent === rawContent && saved.kind === block.kind && saved.dialect === block.dialect && saved.sport === block.sport;
|
|
2150
|
+
block.version = unchanged ? saved.version : (saved?.version ?? 0) + 1;
|
|
2151
|
+
if (!unchanged) revisions.push({
|
|
2152
|
+
noteId,
|
|
2153
|
+
blockId: block.id,
|
|
2154
|
+
version: block.version,
|
|
2155
|
+
kind: block.kind,
|
|
2156
|
+
rawContent,
|
|
2157
|
+
savedAt: now,
|
|
2158
|
+
...block.dialect ? { dialect: block.dialect } : {},
|
|
2159
|
+
...block.sport ? { sport: block.sport } : {}
|
|
2160
|
+
});
|
|
2161
|
+
}
|
|
2162
|
+
if (existing?.rawContent === options.source && !wodWikiStorage.rowsEqual(existing.blocks, blocks)) {
|
|
2163
|
+
sourceRevision++;
|
|
2164
|
+
for (const block of Object.values(blocks)) block.sourceRevision = sourceRevision;
|
|
2165
|
+
}
|
|
2166
|
+
const note = {
|
|
2167
|
+
...existing,
|
|
2168
|
+
id: noteId,
|
|
2169
|
+
title: options.title ?? existing?.title ?? titleFromLabel(options.sourceLabel),
|
|
2170
|
+
type: existing?.type ?? "note",
|
|
2171
|
+
date: existing?.date ?? now,
|
|
2172
|
+
createdAt: existing?.createdAt ?? now,
|
|
2173
|
+
rawContent: options.source,
|
|
2174
|
+
sourceRevision,
|
|
2175
|
+
blocks
|
|
2176
|
+
};
|
|
2177
|
+
const priorRows = await tx.readonly("block_index").getAllFromIndex("by-note", noteId);
|
|
2178
|
+
const priorEfforts = await tx.readonly("block_efforts").getAllFromIndex("by-note", noteId);
|
|
2179
|
+
const priorById = new Map(priorRows.map((row) => [row.id, row]));
|
|
2180
|
+
const nextRows = [];
|
|
2181
|
+
const nextEfforts = [];
|
|
2182
|
+
for (const [position, block] of Object.values(blocks).sort((a, b) => a.from - b.from).entries()) {
|
|
2183
|
+
const id = `${noteId}:${block.id}`;
|
|
2184
|
+
const prior = priorById.get(id);
|
|
2185
|
+
const rawContent = options.source.slice(block.from, block.to);
|
|
2186
|
+
const body = wodWikiCore.parseDocumentSections(rawContent, { registeredWidgets })[0]?.displayContent ?? rawContent;
|
|
2187
|
+
const fingerprint = block.kind === "wod" ? wodWikiCore.blockContentId(body) : void 0;
|
|
2188
|
+
nextRows.push({
|
|
2189
|
+
...prior,
|
|
2190
|
+
id,
|
|
2191
|
+
noteId,
|
|
2192
|
+
blockId: block.id,
|
|
2193
|
+
blockVersion: block.version,
|
|
2194
|
+
dataType: block.kind,
|
|
2195
|
+
sourceRevision,
|
|
2196
|
+
from: block.from,
|
|
2197
|
+
to: block.to,
|
|
2198
|
+
position,
|
|
2199
|
+
rawContent,
|
|
2200
|
+
noteTitle: note.title,
|
|
2201
|
+
createdAt: prior?.createdAt ?? now,
|
|
2202
|
+
blockContentId: fingerprint,
|
|
2203
|
+
...note.sourceId ? { sourceId: note.sourceId } : {}
|
|
2204
|
+
});
|
|
2205
|
+
if (block.kind === "wod") {
|
|
2206
|
+
for (const effortSlug of extractEffortSlugs(wodWikiLang.parseScript(body, { sport: block.sport, dialect: block.dialect }).statements)) {
|
|
2207
|
+
const effortId = `${noteId}:${block.id}:${effortSlug}`;
|
|
2208
|
+
const previous = priorEfforts.find((row) => row.id === effortId);
|
|
2209
|
+
nextEfforts.push({
|
|
2210
|
+
...previous,
|
|
2211
|
+
id: effortId,
|
|
2212
|
+
noteId,
|
|
2213
|
+
blockId: block.id,
|
|
2214
|
+
blockContentId: fingerprint,
|
|
2215
|
+
effortSlug,
|
|
2216
|
+
createdAt: previous?.createdAt ?? now
|
|
2217
|
+
});
|
|
2218
|
+
}
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
if (!wodWikiStorage.rowsEqual(existing, note)) await tx.readwrite("notes").put(note);
|
|
2222
|
+
if (revisions.length) await tx.readwrite("block_revisions").putMany(revisions);
|
|
2223
|
+
await diffProjection(tx, "block_index", priorRows, nextRows);
|
|
2224
|
+
await diffProjection(tx, "block_efforts", priorEfforts, nextEfforts);
|
|
2225
|
+
const tags = await saveTags(tx, noteId, options.tags, now);
|
|
2226
|
+
let session;
|
|
2227
|
+
let revision;
|
|
2228
|
+
if (startTime !== void 0) {
|
|
2229
|
+
const block = Object.values(blocks).filter((row) => row.kind === "wod").sort((a, b) => a.from - b.from)[0];
|
|
2230
|
+
if (!block) throw new Error("[wod run] Note has no actionable workout block");
|
|
2231
|
+
revision = revisions.find((row) => row.blockId === block.id) ?? latest.get(block.id);
|
|
2232
|
+
if (!revision) throw new Error("[wod run] Saved workout revision is unavailable");
|
|
2233
|
+
session = {
|
|
2234
|
+
id: randomId(),
|
|
2235
|
+
noteId,
|
|
2236
|
+
blockId: block.id,
|
|
2237
|
+
blockVersion: block.version,
|
|
2238
|
+
blockContentId: wodWikiCore.blockContentId(wodWikiCore.parseDocumentSections(revision.rawContent)[0]?.displayContent ?? revision.rawContent),
|
|
2239
|
+
origin: "journal",
|
|
2240
|
+
status: "in-progress",
|
|
2241
|
+
startTime,
|
|
2242
|
+
endTime: startTime,
|
|
2243
|
+
duration: 0,
|
|
2244
|
+
completed: false,
|
|
2245
|
+
createdAt: startTime
|
|
2246
|
+
};
|
|
2247
|
+
await tx.readwrite("sessions").put(session);
|
|
2248
|
+
}
|
|
2249
|
+
return { noteId, note, blocks: nextRows.length, efforts: nextEfforts.length, tags, created: !existing, session, revision };
|
|
2250
|
+
});
|
|
2251
|
+
}
|
|
2252
|
+
async function diffProjection(tx, store, previous, next) {
|
|
2253
|
+
const nextIds = new Set(next.map((row) => row.id));
|
|
2254
|
+
for (const row of previous) if (!nextIds.has(row.id)) await tx.readwrite(store).delete(row.id);
|
|
2255
|
+
const old = new Map(previous.map((row) => [row.id, row]));
|
|
2256
|
+
for (const row of next) {
|
|
2257
|
+
if (!wodWikiStorage.rowsEqual(old.get(row.id), row)) {
|
|
2258
|
+
if (store === "block_index" && "blockVersion" in row) await tx.readwrite("block_index").put(row);
|
|
2259
|
+
if (store === "block_efforts" && "effortSlug" in row) await tx.readwrite("block_efforts").put(row);
|
|
2260
|
+
}
|
|
2261
|
+
}
|
|
2262
|
+
}
|
|
2263
|
+
async function saveTags(tx, noteId, items, now) {
|
|
2264
|
+
const previous = await tx.readonly("note_tags").getAllFromIndex("by-note", noteId);
|
|
2265
|
+
if (!items) return previous.length;
|
|
2266
|
+
const next = /* @__PURE__ */ new Map();
|
|
2267
|
+
for (const item of items) {
|
|
2268
|
+
const label = item.label.trim();
|
|
2269
|
+
if (!label) continue;
|
|
2270
|
+
const found = (await tx.readonly("tags").getAllFromIndex("by-label", label))[0];
|
|
2271
|
+
const tag = found ? { ...found, ...!found.type && item.type ? { type: item.type } : {} } : { id: uuid5(CLI_UUID_NAMESPACE, `tag:${label}`), label, type: item.type, createdAt: now };
|
|
2272
|
+
if (!wodWikiStorage.rowsEqual(found, tag)) await tx.readwrite("tags").put(tag);
|
|
2273
|
+
const id = previous.find((link) => link.tagId === tag.id)?.id ?? uuid5(CLI_UUID_NAMESPACE, `note-tag:${noteId}:${tag.id}`);
|
|
2274
|
+
next.set(id, { ...previous.find((link) => link.id === id), id, noteId, tagId: tag.id });
|
|
2275
|
+
}
|
|
2276
|
+
for (const link of previous) if (!next.has(link.id)) await tx.readwrite("note_tags").delete(link.id);
|
|
2277
|
+
const old = new Map(previous.map((row) => [row.id, row]));
|
|
2278
|
+
for (const link of next.values()) if (!wodWikiStorage.rowsEqual(old.get(link.id), link)) await tx.readwrite("note_tags").put(link);
|
|
2279
|
+
return next.size;
|
|
2280
|
+
}
|
|
2281
|
+
function persistNote(db, options) {
|
|
2282
|
+
return saveSource(db, options);
|
|
2283
|
+
}
|
|
2284
|
+
async function startRun(db, options, startTime = Date.now()) {
|
|
2285
|
+
const saved = await saveSource(db, options, startTime);
|
|
2286
|
+
if (!saved.session || !saved.revision) throw new Error("[wod run] Atomic run capture failed");
|
|
2287
|
+
return { session: saved.session, revision: saved.revision, noteCreated: saved.created };
|
|
2288
|
+
}
|
|
2289
|
+
async function persistRun(db, started, executionLog) {
|
|
2290
|
+
const results = executionLog.results;
|
|
2291
|
+
const session = {
|
|
2292
|
+
...started.session,
|
|
2293
|
+
status: results.completed ? "completed" : "in-progress",
|
|
2294
|
+
endTime: results.endTime,
|
|
2295
|
+
duration: results.duration ?? 0,
|
|
2296
|
+
completed: results.completed
|
|
2297
|
+
};
|
|
2298
|
+
const identity = {
|
|
2299
|
+
noteId: session.noteId,
|
|
2300
|
+
resultId: session.id,
|
|
2301
|
+
blockId: session.blockId,
|
|
2302
|
+
blockVersion: session.blockVersion,
|
|
2303
|
+
blockContentId: session.blockContentId,
|
|
2304
|
+
origin: session.origin,
|
|
2305
|
+
pageId: session.pageId,
|
|
2306
|
+
workoutTimestamp: session.createdAt
|
|
2307
|
+
};
|
|
2308
|
+
const events = wodWikiWql.toEventRows(executionLog.logs, identity);
|
|
2309
|
+
const summaries = wodWikiWql.toSummaryEventRows(executionLog.logs, identity);
|
|
2310
|
+
await db.storage.transaction(["sessions", "events", "block_revisions"], "readwrite", async (tx) => {
|
|
2311
|
+
const saved = await tx.readonly("sessions").get(session.id);
|
|
2312
|
+
if (!saved || saved.noteId !== session.noteId || saved.blockId !== session.blockId || saved.blockVersion !== session.blockVersion) {
|
|
2313
|
+
throw new Error("[wod run] Captured Session source pin changed");
|
|
2314
|
+
}
|
|
2315
|
+
const revision = await tx.readonly("block_revisions").get([session.noteId, session.blockId, session.blockVersion]);
|
|
2316
|
+
if (!revision || !wodWikiStorage.rowsEqual(revision, started.revision)) throw new Error("[wod run] Captured revision is unavailable");
|
|
2317
|
+
await tx.readwrite("sessions").put(session);
|
|
2318
|
+
await tx.readwrite("events").putMany([...events, ...summaries]);
|
|
2319
|
+
});
|
|
2320
|
+
return { noteId: session.noteId, resultId: session.id, session, events: events.length, summaries: summaries.length, noteCreated: started.noteCreated };
|
|
2321
|
+
}
|
|
2322
|
+
async function persistSessionBundle(db, session, events) {
|
|
2323
|
+
if ("segmentId" in session || "segmentVersion" in session || "version" in session || "rawContent" in session || "data" in session || !session.noteId || !session.blockId || !Number.isSafeInteger(session.blockVersion) || session.blockVersion < 1) {
|
|
2324
|
+
throw new Error("[wod import] Session requires an exact block revision pin");
|
|
2325
|
+
}
|
|
2326
|
+
await db.storage.transaction(["sessions", "events", "block_revisions"], "readwrite", async (tx) => {
|
|
2327
|
+
const revision = await tx.readonly("block_revisions").get([session.noteId, session.blockId, session.blockVersion]);
|
|
2328
|
+
if (!revision || revision.kind !== "wod") throw new Error("[wod import] Exact immutable workout revision is unavailable");
|
|
2329
|
+
for (const event of events) {
|
|
2330
|
+
if (event.resultId !== session.id || event.noteId !== session.noteId || event.blockId !== session.blockId || event.blockVersion !== session.blockVersion) {
|
|
2331
|
+
throw new Error("[wod import] Event source pin differs from Session source pin");
|
|
2332
|
+
}
|
|
2333
|
+
}
|
|
2334
|
+
const existing = await tx.readonly("sessions").get(session.id);
|
|
2335
|
+
if (existing && !wodWikiStorage.rowsEqual(existing, session)) throw new Error("[wod import] Session identity conflicts with existing row");
|
|
2336
|
+
if (!existing) await tx.readwrite("sessions").put(session);
|
|
2337
|
+
for (const event of events) {
|
|
2338
|
+
const old = await tx.readonly("events").get(event.id);
|
|
2339
|
+
if (old && !wodWikiStorage.rowsEqual(old, event)) throw new Error("[wod import] Event identity conflicts with existing row");
|
|
2340
|
+
if (!old) await tx.readwrite("events").put(event);
|
|
2341
|
+
}
|
|
2342
|
+
});
|
|
2343
|
+
return { events: events.length };
|
|
2344
|
+
}
|
|
2345
|
+
async function persistEffort(db, effort) {
|
|
2346
|
+
const sql = await loadSql();
|
|
2347
|
+
await db.db.transaction(async (tx) => {
|
|
2348
|
+
await sql.putRow(tx, sql.storeDefinition("efforts"), effort);
|
|
2349
|
+
});
|
|
2350
|
+
}
|
|
2351
|
+
async function persistTypedTags(db, labels, type) {
|
|
2352
|
+
return db.storage.transaction(["tags"], "readwrite", async (tx) => {
|
|
2353
|
+
let added = 0;
|
|
2354
|
+
for (const raw of labels) {
|
|
2355
|
+
const label = raw.trim();
|
|
2356
|
+
if (!label) continue;
|
|
2357
|
+
const tag = (await tx.readonly("tags").getAllFromIndex("by-label", label))[0];
|
|
2358
|
+
if (!tag) {
|
|
2359
|
+
await tx.readwrite("tags").put({ id: uuid5(CLI_UUID_NAMESPACE, `tag:${label}`), label, type, createdAt: Date.now() });
|
|
2360
|
+
added++;
|
|
2361
|
+
} else if (!tag.type) {
|
|
2362
|
+
await tx.readwrite("tags").put({ ...tag, type });
|
|
2363
|
+
}
|
|
2364
|
+
}
|
|
2365
|
+
return added;
|
|
2366
|
+
});
|
|
2367
|
+
}
|
|
2368
|
+
|
|
2369
|
+
// src/cli/seed.ts
|
|
2370
|
+
init_db();
|
|
2371
|
+
async function importSeedDir(db, dir, sourceId) {
|
|
2372
|
+
const fs = nodeFs(), path = nodePath();
|
|
2373
|
+
const source = sourceId || path.basename(dir);
|
|
2374
|
+
const manifest = wodWikiEngine.assertSeedManifest(JSON.parse(fs.readFileSync(path.resolve(dir, "manifest.json"), "utf-8")));
|
|
2375
|
+
const key = wodWikiEngine.seedMetaKey(source);
|
|
2376
|
+
let expected = await db.storage.readonly("meta").get(key);
|
|
2377
|
+
if (expected && expected.schema !== wodWikiEngine.SEED_SCHEMA) throw new Error("Incompatible seed checkpoint; recreate storage");
|
|
2378
|
+
let meta = expected ?? wodWikiEngine.emptySeedMeta(key);
|
|
2379
|
+
if (manifest.version < meta.seedVersion) throw new Error("Seed manifest is older than stored checkpoint");
|
|
2380
|
+
const summary = { sourceId: source, version: manifest.version, notes: 0, efforts: 0, blocks: 0, blockEfforts: 0, deleted: 0, skippedUserOwned: 0 };
|
|
2381
|
+
const metadataChanged = manifest.version !== meta.seedVersion || manifest.builtAt !== meta.builtAt;
|
|
2382
|
+
const plan = manifest.chunks.filter((c) => metadataChanged || meta.chunks[c.id]?.sha256 !== c.sha256);
|
|
2383
|
+
plan.sort((a, b) => Number(b.id === wodWikiEngine.CANVAS_CHUNK_ID) - Number(a.id === wodWikiEngine.CANVAS_CHUNK_ID));
|
|
2384
|
+
const accumulate = (result) => {
|
|
2385
|
+
summary.notes += result.totalNotes;
|
|
2386
|
+
summary.efforts += result.totalEfforts;
|
|
2387
|
+
summary.blocks += result.totalBlocks;
|
|
2388
|
+
summary.deleted += result.deleted;
|
|
2389
|
+
summary.skippedUserOwned += result.skippedUserOwned;
|
|
2390
|
+
};
|
|
2391
|
+
for (const chunk of plan) {
|
|
2392
|
+
const rows = wodWikiEngine.assertSeedRows(JSON.parse(fs.readFileSync(path.resolve(dir, chunk.path), "utf-8")));
|
|
2393
|
+
if (rows.length !== chunk.count) throw new Error("Seed chunk count mismatch");
|
|
2394
|
+
const next = { ...meta, chunks: { ...meta.chunks, [chunk.id]: { sha256: chunk.sha256, noteIds: await Promise.all(rows.map((r) => wodWikiEngine.seedNoteId(r.path))) } }, importedAt: Date.now() };
|
|
2395
|
+
accumulate(await wodWikiEngine.applySeedChunk(db.storage, { chunkId: chunk.id, rows, manifest, expectedMeta: expected, meta: next }));
|
|
2396
|
+
summary.blockEfforts += rows.reduce((count, row) => count + row.blockEfforts.length, 0);
|
|
2397
|
+
meta = next;
|
|
2398
|
+
expected = next;
|
|
2399
|
+
}
|
|
2400
|
+
for (const chunkId of Object.keys(meta.chunks)) {
|
|
2401
|
+
if (manifest.chunks.some((c) => c.id === chunkId)) continue;
|
|
2402
|
+
const chunks = { ...meta.chunks };
|
|
2403
|
+
delete chunks[chunkId];
|
|
2404
|
+
const next = { ...meta, chunks, importedAt: Date.now() };
|
|
2405
|
+
accumulate(await wodWikiEngine.applySeedChunk(db.storage, { chunkId, rows: [], manifest, expectedMeta: expected, meta: next }));
|
|
2406
|
+
meta = next;
|
|
2407
|
+
expected = next;
|
|
2408
|
+
}
|
|
2409
|
+
if (plan.length || metadataChanged || Object.keys(meta.chunks).length !== Object.keys(expected?.chunks ?? {}).length) {
|
|
2410
|
+
const next = { ...meta, schema: wodWikiEngine.SEED_SCHEMA, seedVersion: manifest.version, builtAt: manifest.builtAt, importedAt: Date.now() };
|
|
2411
|
+
await wodWikiEngine.applySeedChunk(db.storage, { chunkId: null, rows: [], manifest, expectedMeta: expected, meta: next });
|
|
2412
|
+
}
|
|
2413
|
+
return summary;
|
|
2414
|
+
}
|
|
2415
|
+
function defaultSeedDirs(cwd) {
|
|
2416
|
+
const base = nodePath().resolve(cwd, "apps", "playground", "public", "seed");
|
|
2417
|
+
return ["core", "community"].map((id) => nodePath().resolve(base, id)).filter((dir) => nodeFs().existsSync(nodePath().resolve(dir, "manifest.json")));
|
|
2418
|
+
}
|
|
2419
|
+
|
|
2420
|
+
// src/cli/formatters.ts
|
|
2421
|
+
function escapeCsvField(field) {
|
|
2422
|
+
if (field === void 0 || field === null) return "";
|
|
2423
|
+
const str = String(field);
|
|
2424
|
+
if (str.includes(",") || str.includes('"') || str.includes("\n") || str.includes("\r")) {
|
|
2425
|
+
return `"${str.replace(/"/g, '""')}"`;
|
|
2426
|
+
}
|
|
2427
|
+
return str;
|
|
2428
|
+
}
|
|
2429
|
+
function formatDate(ts) {
|
|
2430
|
+
if (!ts) return "-";
|
|
2431
|
+
try {
|
|
2432
|
+
return new Date(ts).toISOString();
|
|
2433
|
+
} catch {
|
|
2434
|
+
return String(ts);
|
|
2435
|
+
}
|
|
2436
|
+
}
|
|
2437
|
+
function formatMetricValue(m) {
|
|
2438
|
+
if (m.image) return m.image;
|
|
2439
|
+
if (m.value === void 0 || m.value === null) return "";
|
|
2440
|
+
if (typeof m.value === "object") return JSON.stringify(m.value);
|
|
2441
|
+
return String(m.value);
|
|
2442
|
+
}
|
|
2443
|
+
function formatMetric(m) {
|
|
2444
|
+
const t = m.type || "metric";
|
|
2445
|
+
return `${t}:${formatMetricValue(m)}`;
|
|
2446
|
+
}
|
|
2447
|
+
function formatParseOutput(ir, format, pretty = true) {
|
|
2448
|
+
if (format === "json") {
|
|
2449
|
+
return JSON.stringify(ir, null, pretty ? 2 : void 0);
|
|
2450
|
+
}
|
|
2451
|
+
const flatNodes = [];
|
|
2452
|
+
const walk = (node) => {
|
|
2453
|
+
flatNodes.push(node);
|
|
2454
|
+
for (const child of node.children ?? []) {
|
|
2455
|
+
walk(child);
|
|
2456
|
+
}
|
|
2457
|
+
};
|
|
2458
|
+
walk(ir.data);
|
|
2459
|
+
if (format === "csv") {
|
|
2460
|
+
const header = "id,type,from,to,raw,metrics,hints";
|
|
2461
|
+
const rows = flatNodes.map(
|
|
2462
|
+
(n) => [
|
|
2463
|
+
n.id,
|
|
2464
|
+
n.type,
|
|
2465
|
+
n.from,
|
|
2466
|
+
n.to,
|
|
2467
|
+
escapeCsvField(n.raw),
|
|
2468
|
+
escapeCsvField(n.metrics.map(formatMetric).join("; ")),
|
|
2469
|
+
escapeCsvField(n.hints?.join("; ") ?? "")
|
|
2470
|
+
].join(",")
|
|
2471
|
+
);
|
|
2472
|
+
return [header, ...rows].join("\n");
|
|
2473
|
+
}
|
|
2474
|
+
const lines = [];
|
|
2475
|
+
lines.push(`Parse Tree (${flatNodes.length} statements):`);
|
|
2476
|
+
lines.push("\u2500".repeat(80));
|
|
2477
|
+
lines.push(
|
|
2478
|
+
["ID".padEnd(6), "Type".padEnd(12), "Span".padEnd(12), "Hints".padEnd(20), "Raw Text"].join(" | ")
|
|
2479
|
+
);
|
|
2480
|
+
lines.push("\u2500".repeat(80));
|
|
2481
|
+
for (const n of flatNodes) {
|
|
2482
|
+
const span = `${n.from}-${n.to}`;
|
|
2483
|
+
const hints = (n.hints ?? []).join(", ");
|
|
2484
|
+
lines.push(
|
|
2485
|
+
[
|
|
2486
|
+
String(n.id).padEnd(6),
|
|
2487
|
+
n.type.padEnd(12),
|
|
2488
|
+
span.padEnd(12),
|
|
2489
|
+
(hints.length > 18 ? hints.slice(0, 15) + "..." : hints).padEnd(20),
|
|
2490
|
+
n.raw.replace(/\n/g, "\\n")
|
|
2491
|
+
].join(" | ")
|
|
2492
|
+
);
|
|
2493
|
+
}
|
|
2494
|
+
return lines.join("\n");
|
|
2495
|
+
}
|
|
2496
|
+
function formatExecutionOutput(ir, format, pretty = true) {
|
|
2497
|
+
if (format === "json") {
|
|
2498
|
+
return JSON.stringify(ir, null, pretty ? 2 : void 0);
|
|
2499
|
+
}
|
|
2500
|
+
const { results, logs } = ir.data;
|
|
2501
|
+
const statements = logs;
|
|
2502
|
+
if (format === "csv") {
|
|
2503
|
+
const header = "id,outputType,started,ended,sourceBlockKey,stackLevel,completionReason,metrics,hints";
|
|
2504
|
+
const rows = statements.map(
|
|
2505
|
+
(s) => [
|
|
2506
|
+
s.id,
|
|
2507
|
+
s.outputType,
|
|
2508
|
+
s.timeSpan?.started ?? s.timestamp ?? 0,
|
|
2509
|
+
s.timeSpan?.ended ?? "",
|
|
2510
|
+
escapeCsvField(s.sourceBlockKey),
|
|
2511
|
+
s.stackLevel,
|
|
2512
|
+
escapeCsvField(s.completionReason ?? ""),
|
|
2513
|
+
escapeCsvField(s.metrics.map(formatMetric).join("; ")),
|
|
2514
|
+
escapeCsvField(s.hints?.join("; ") ?? "")
|
|
2515
|
+
].join(",")
|
|
2516
|
+
);
|
|
2517
|
+
return [header, ...rows].join("\n");
|
|
2518
|
+
}
|
|
2519
|
+
const lines = [];
|
|
2520
|
+
lines.push(`Workout Execution Results:`);
|
|
2521
|
+
lines.push(` Duration: ${results.duration}ms`);
|
|
2522
|
+
lines.push(` Completed: ${results.completed ? "yes" : "no"}`);
|
|
2523
|
+
lines.push(` Start: ${formatDate(results.startTime)}`);
|
|
2524
|
+
lines.push(` End: ${formatDate(results.endTime)}`);
|
|
2525
|
+
lines.push(` Logs: ${statements.length} statements emitted`);
|
|
2526
|
+
lines.push("\u2500".repeat(80));
|
|
2527
|
+
lines.push(
|
|
2528
|
+
["ID".padEnd(8), "Type".padEnd(12), "Block".padEnd(18), "Reason".padEnd(15), "Metrics"].join(" | ")
|
|
2529
|
+
);
|
|
2530
|
+
lines.push("\u2500".repeat(80));
|
|
2531
|
+
for (const s of statements) {
|
|
2532
|
+
const metricsStr = s.metrics.map(formatMetric).join(", ");
|
|
2533
|
+
lines.push(
|
|
2534
|
+
[
|
|
2535
|
+
String(s.id).padEnd(8),
|
|
2536
|
+
(s.outputType ?? "segment").padEnd(12),
|
|
2537
|
+
(s.sourceBlockKey ?? "-").padEnd(18),
|
|
2538
|
+
(s.completionReason ?? "-").padEnd(15),
|
|
2539
|
+
metricsStr
|
|
2540
|
+
].join(" | ")
|
|
2541
|
+
);
|
|
2542
|
+
}
|
|
2543
|
+
return lines.join("\n");
|
|
2544
|
+
}
|
|
2545
|
+
function formatQueryOutput(ir, format, pretty = true) {
|
|
2546
|
+
if (format === "json") {
|
|
2547
|
+
return JSON.stringify(ir, null, pretty ? 2 : void 0);
|
|
2548
|
+
}
|
|
2549
|
+
const kind = ir.kind;
|
|
2550
|
+
if (kind === "rows-result") {
|
|
2551
|
+
const data2 = ir.data;
|
|
2552
|
+
if (format === "csv") {
|
|
2553
|
+
const header = "resultId,timestamp,outputType,eventId,metrics";
|
|
2554
|
+
const rows = [];
|
|
2555
|
+
for (const run of data2.runs) {
|
|
2556
|
+
for (const event of run.events) {
|
|
2557
|
+
rows.push(
|
|
2558
|
+
[
|
|
2559
|
+
run.resultId,
|
|
2560
|
+
run.timestamp,
|
|
2561
|
+
event.outputType,
|
|
2562
|
+
event.id,
|
|
2563
|
+
escapeCsvField(event.metrics.map(formatMetric).join("; "))
|
|
2564
|
+
].join(",")
|
|
2565
|
+
);
|
|
2566
|
+
}
|
|
2567
|
+
}
|
|
2568
|
+
return [header, ...rows].join("\n");
|
|
2569
|
+
}
|
|
2570
|
+
const lines2 = [];
|
|
2571
|
+
lines2.push(`Rows Query Result (${data2.runs.length} runs):`);
|
|
2572
|
+
if (data2.error) lines2.push(`Error: ${data2.error}`);
|
|
2573
|
+
lines2.push("\u2500".repeat(80));
|
|
2574
|
+
lines2.push(
|
|
2575
|
+
["Result ID".padEnd(20), "Date".padEnd(24), "Events"].join(" | ")
|
|
2576
|
+
);
|
|
2577
|
+
lines2.push("\u2500".repeat(80));
|
|
2578
|
+
for (const run of data2.runs) {
|
|
2579
|
+
lines2.push(
|
|
2580
|
+
[
|
|
2581
|
+
run.resultId.padEnd(20),
|
|
2582
|
+
formatDate(run.timestamp).padEnd(24),
|
|
2583
|
+
String(run.events.length)
|
|
2584
|
+
].join(" | ")
|
|
2585
|
+
);
|
|
2586
|
+
}
|
|
2587
|
+
return lines2.join("\n");
|
|
2588
|
+
}
|
|
2589
|
+
if (kind === "find-result") {
|
|
2590
|
+
const data2 = ir.data;
|
|
2591
|
+
if (format === "csv") {
|
|
2592
|
+
const header = "target,id,title_or_label,sourceId";
|
|
2593
|
+
const rows = [];
|
|
2594
|
+
for (const n of data2.notes) {
|
|
2595
|
+
rows.push(["note", n.id, escapeCsvField(n.title), escapeCsvField(n.sourceId ?? "")].join(","));
|
|
2596
|
+
}
|
|
2597
|
+
for (const b of data2.blocks) {
|
|
2598
|
+
rows.push(["block", b.id, escapeCsvField(b.noteTitle), escapeCsvField(b.sourceId ?? "")].join(","));
|
|
2599
|
+
}
|
|
2600
|
+
for (const e of data2.efforts ?? []) {
|
|
2601
|
+
rows.push(["effort", e.id, escapeCsvField(e.label), escapeCsvField(e.slug)].join(","));
|
|
2602
|
+
}
|
|
2603
|
+
return [header, ...rows].join("\n");
|
|
2604
|
+
}
|
|
2605
|
+
const lines2 = [];
|
|
2606
|
+
const matchedCount2 = data2.stages?.matched ?? 0;
|
|
2607
|
+
const selectedCount = data2.stages?.selected ?? 0;
|
|
2608
|
+
lines2.push(`Find Result (matched: ${matchedCount2} / selected: ${selectedCount}):`);
|
|
2609
|
+
lines2.push("\u2500".repeat(80));
|
|
2610
|
+
lines2.push(["Type".padEnd(8), "ID".padEnd(24), "Title / Label".padEnd(30), "Source ID"].join(" | "));
|
|
2611
|
+
lines2.push("\u2500".repeat(80));
|
|
2612
|
+
for (const n of data2.notes) {
|
|
2613
|
+
lines2.push(["note".padEnd(8), n.id.padEnd(24), n.title.padEnd(30), n.sourceId ?? "-"].join(" | "));
|
|
2614
|
+
}
|
|
2615
|
+
for (const b of data2.blocks) {
|
|
2616
|
+
lines2.push(["block".padEnd(8), b.id.padEnd(24), b.noteTitle.padEnd(30), b.sourceId ?? "-"].join(" | "));
|
|
2617
|
+
}
|
|
2618
|
+
for (const e of data2.efforts ?? []) {
|
|
2619
|
+
lines2.push(["effort".padEnd(8), e.id.padEnd(24), e.label.padEnd(30), e.slug].join(" | "));
|
|
2620
|
+
}
|
|
2621
|
+
return lines2.join("\n");
|
|
2622
|
+
}
|
|
2623
|
+
if (kind === "pipeline-result") {
|
|
2624
|
+
const data2 = ir.data;
|
|
2625
|
+
const sink = data2.chart ? `:${data2.chart.head}` : "data";
|
|
2626
|
+
if (format === "csv") {
|
|
2627
|
+
const header = "series,timestamp,date,value,unit";
|
|
2628
|
+
const rows = [];
|
|
2629
|
+
for (const s of data2.series ?? []) {
|
|
2630
|
+
for (const pt of s.points) {
|
|
2631
|
+
rows.push(
|
|
2632
|
+
[
|
|
2633
|
+
escapeCsvField(s.label || s.key),
|
|
2634
|
+
pt.ts,
|
|
2635
|
+
formatDate(pt.ts),
|
|
2636
|
+
pt.value,
|
|
2637
|
+
escapeCsvField(s.unit ?? data2.unit ?? "")
|
|
2638
|
+
].join(",")
|
|
2639
|
+
);
|
|
2640
|
+
}
|
|
2641
|
+
}
|
|
2642
|
+
return [header, ...rows].join("\n");
|
|
2643
|
+
}
|
|
2644
|
+
const lines2 = [];
|
|
2645
|
+
if (data2.error) lines2.push(`Pipeline Error: ${data2.error}`);
|
|
2646
|
+
lines2.push(`Pipeline Result (\u2192 ${sink}):`);
|
|
2647
|
+
lines2.push("\u2500".repeat(80));
|
|
2648
|
+
if (data2.table) {
|
|
2649
|
+
lines2.push(`Table: ${data2.table.rows.length} of ${data2.table.totalCount} rows`);
|
|
2650
|
+
}
|
|
2651
|
+
for (const s of data2.series ?? []) {
|
|
2652
|
+
lines2.push(`${s.label || s.key}: ${s.points.length} points${s.unit ? ` (${s.unit})` : ""}`);
|
|
2653
|
+
}
|
|
2654
|
+
if (data2.notes?.length) lines2.push(`notes: ${data2.notes.length}`);
|
|
2655
|
+
if (data2.blocks?.length) lines2.push(`blocks: ${data2.blocks.length}`);
|
|
2656
|
+
if (data2.efforts?.length) lines2.push(`efforts: ${data2.efforts.length}`);
|
|
2657
|
+
if (data2.runs?.length) lines2.push(`runs: ${data2.runs.length}`);
|
|
2658
|
+
return lines2.join("\n");
|
|
2659
|
+
}
|
|
2660
|
+
const data = ir.data;
|
|
2661
|
+
if (data.scalar !== void 0 && data.series.length === 0) {
|
|
2662
|
+
if (format === "csv") {
|
|
2663
|
+
return `metric,scalar,unit
|
|
2664
|
+
${escapeCsvField(data.parsed.metric)},${data.scalar},${escapeCsvField(data.unit ?? "")}`;
|
|
2665
|
+
}
|
|
2666
|
+
return `Scalar Result: ${data.scalar}${data.unit ? " " + data.unit : ""}`;
|
|
2667
|
+
}
|
|
2668
|
+
if (format === "csv") {
|
|
2669
|
+
const header = "series,timestamp,date,value,unit";
|
|
2670
|
+
const rows = [];
|
|
2671
|
+
for (const s of data.series) {
|
|
2672
|
+
for (const pt of s.points) {
|
|
2673
|
+
rows.push(
|
|
2674
|
+
[
|
|
2675
|
+
escapeCsvField(s.label || s.key),
|
|
2676
|
+
pt.ts,
|
|
2677
|
+
formatDate(pt.ts),
|
|
2678
|
+
pt.value,
|
|
2679
|
+
escapeCsvField(s.unit ?? data.unit ?? "")
|
|
2680
|
+
].join(",")
|
|
2681
|
+
);
|
|
2682
|
+
}
|
|
2683
|
+
}
|
|
2684
|
+
return [header, ...rows].join("\n");
|
|
2685
|
+
}
|
|
2686
|
+
const lines = [];
|
|
2687
|
+
const matchedCount = data.stages?.matched ?? data.stages?.selected ?? data.matched?.length ?? 0;
|
|
2688
|
+
lines.push(`Query Result (${data.series.length} series, ${matchedCount} matched facts):`);
|
|
2689
|
+
lines.push(
|
|
2690
|
+
["Series / Group".padEnd(20), "Timestamp".padEnd(16), "Date".padEnd(24), "Value".padEnd(12), "Unit"].join(" | ")
|
|
2691
|
+
);
|
|
2692
|
+
lines.push("\u2500".repeat(80));
|
|
2693
|
+
for (const s of data.series) {
|
|
2694
|
+
for (const pt of s.points) {
|
|
2695
|
+
lines.push(
|
|
2696
|
+
[
|
|
2697
|
+
(s.label || s.key).padEnd(20),
|
|
2698
|
+
String(pt.ts).padEnd(16),
|
|
2699
|
+
formatDate(pt.ts).padEnd(24),
|
|
2700
|
+
String(pt.value).padEnd(12),
|
|
2701
|
+
s.unit ?? data.unit ?? "-"
|
|
2702
|
+
].join(" | ")
|
|
2703
|
+
);
|
|
2704
|
+
}
|
|
2705
|
+
}
|
|
2706
|
+
return lines.join("\n");
|
|
2707
|
+
}
|
|
2708
|
+
|
|
2709
|
+
// src/version.ts
|
|
2710
|
+
var VERSION = "0.36.2133";
|
|
2711
|
+
|
|
2712
|
+
// src/cli/runner.ts
|
|
2713
|
+
function getFs2() {
|
|
2714
|
+
if (typeof globalThis.process?.versions?.node === "undefined" && typeof globalThis.Bun === "undefined") {
|
|
2715
|
+
throw new Error("File system operations are only supported in Node / Bun environments");
|
|
2716
|
+
}
|
|
2717
|
+
return __require("fs");
|
|
2718
|
+
}
|
|
2719
|
+
function cliNoteSource(source, label, sport) {
|
|
2720
|
+
if (/\.(?:md|markdown)$/i.test(label) || wodWikiCore.parseDocumentSections(source).some((section) => section.scriptBlock)) return source;
|
|
2721
|
+
let length = 3;
|
|
2722
|
+
for (const match of source.matchAll(/`+/g)) length = Math.max(length, match[0].length + 1);
|
|
2723
|
+
const fence = "`".repeat(length);
|
|
2724
|
+
return `${fence}time${sport ? `:${sport}` : ""}
|
|
2725
|
+
${source}
|
|
2726
|
+
${fence}
|
|
2727
|
+
`;
|
|
2728
|
+
}
|
|
2729
|
+
var VALUE_FLAGS = [
|
|
2730
|
+
["--db", "db"],
|
|
2731
|
+
["--db-driver", "dbDriver"],
|
|
2732
|
+
["--database-url", "databaseUrl"],
|
|
2733
|
+
["--postgres-host", "postgresHost"],
|
|
2734
|
+
["--postgres-port", "postgresPort"],
|
|
2735
|
+
["--postgres-user", "postgresUser"],
|
|
2736
|
+
["--postgres-password", "postgresPassword"],
|
|
2737
|
+
["--postgres-database", "postgresDatabase"],
|
|
2738
|
+
["--postgres-ssl", "postgresSsl"],
|
|
2739
|
+
["--turso-url", "tursoUrl"],
|
|
2740
|
+
["--turso-auth-token", "tursoAuthToken"],
|
|
2741
|
+
["--env-file", "envFile"],
|
|
2742
|
+
["--host", "host"],
|
|
2743
|
+
["--port", "port"],
|
|
2744
|
+
["--dist", "dist"]
|
|
2745
|
+
];
|
|
2746
|
+
function readValueFlag(args, i, flag) {
|
|
2747
|
+
const inline = args[i].startsWith(`${flag}=`);
|
|
2748
|
+
if (inline) {
|
|
2749
|
+
const value2 = args[i].slice(flag.length + 1);
|
|
2750
|
+
if (!value2) throw new Error(`Missing value for ${flag}`);
|
|
2751
|
+
return { value: value2, next: i + 1 };
|
|
2752
|
+
}
|
|
2753
|
+
const value = args[i + 1];
|
|
2754
|
+
if (value === void 0 || value === "" || value.startsWith("--")) throw new Error(`Missing value for ${flag}`);
|
|
2755
|
+
return { value, next: i + 2 };
|
|
2756
|
+
}
|
|
2757
|
+
function parseCliArgs(args) {
|
|
2758
|
+
const result = {
|
|
2759
|
+
format: "json",
|
|
2760
|
+
packs: [],
|
|
2761
|
+
sources: []
|
|
2762
|
+
};
|
|
2763
|
+
const valueArgs = result;
|
|
2764
|
+
let i = 0;
|
|
2765
|
+
while (i < args.length) {
|
|
2766
|
+
const arg = args[i];
|
|
2767
|
+
if (arg === "--at" || arg.startsWith("--at=")) throw new Error("Unknown option --at; whole Note exports have no as-of version");
|
|
2768
|
+
const valueFlag = VALUE_FLAGS.find(([flag]) => arg === flag || arg.startsWith(`${flag}=`));
|
|
2769
|
+
if (valueFlag) {
|
|
2770
|
+
const [flag, key] = valueFlag;
|
|
2771
|
+
const { value, next } = readValueFlag(args, i, flag);
|
|
2772
|
+
valueArgs[key] = value;
|
|
2773
|
+
i = next;
|
|
2774
|
+
continue;
|
|
2775
|
+
}
|
|
2776
|
+
if (arg === "--help" || arg === "-h") {
|
|
2777
|
+
result.help = true;
|
|
2778
|
+
i++;
|
|
2779
|
+
} else if (arg === "--version" || arg === "-v") {
|
|
2780
|
+
result.version = true;
|
|
2781
|
+
i++;
|
|
2782
|
+
} else if (arg === "--corpus" || arg === "-c") {
|
|
2783
|
+
result.corpus = args[++i];
|
|
2784
|
+
i++;
|
|
2785
|
+
} else if (arg === "--stdin-log") {
|
|
2786
|
+
result.stdinLog = true;
|
|
2787
|
+
i++;
|
|
2788
|
+
} else if (arg === "--stdin-facts") {
|
|
2789
|
+
result.stdinFacts = true;
|
|
2790
|
+
i++;
|
|
2791
|
+
} else if (arg === "--format") {
|
|
2792
|
+
const fmt = args[++i];
|
|
2793
|
+
if (fmt === "json" || fmt === "table" || fmt === "csv") {
|
|
2794
|
+
result.format = fmt;
|
|
2795
|
+
}
|
|
2796
|
+
i++;
|
|
2797
|
+
} else if (arg.startsWith("--format=")) {
|
|
2798
|
+
const fmt = arg.slice("--format=".length);
|
|
2799
|
+
if (fmt === "json" || fmt === "table" || fmt === "csv") {
|
|
2800
|
+
result.format = fmt;
|
|
2801
|
+
}
|
|
2802
|
+
i++;
|
|
2803
|
+
} else if (arg === "-o" || arg === "--output") {
|
|
2804
|
+
result.output = args[++i];
|
|
2805
|
+
i++;
|
|
2806
|
+
} else if (arg.startsWith("--output=")) {
|
|
2807
|
+
result.output = arg.slice("--output=".length);
|
|
2808
|
+
i++;
|
|
2809
|
+
} else if (arg === "--pack") {
|
|
2810
|
+
const packSpec = args[++i];
|
|
2811
|
+
if (packSpec) result.packs.push(packSpec);
|
|
2812
|
+
i++;
|
|
2813
|
+
} else if (arg.startsWith("--pack=")) {
|
|
2814
|
+
result.packs.push(arg.slice("--pack=".length));
|
|
2815
|
+
i++;
|
|
2816
|
+
} else if (arg === "--sport") {
|
|
2817
|
+
result.sport = args[++i];
|
|
2818
|
+
i++;
|
|
2819
|
+
} else if (arg === "--unit") {
|
|
2820
|
+
result.unit = args[++i];
|
|
2821
|
+
i++;
|
|
2822
|
+
} else if (arg === "--debug") {
|
|
2823
|
+
result.debug = "";
|
|
2824
|
+
i++;
|
|
2825
|
+
} else if (arg.startsWith("--debug=")) {
|
|
2826
|
+
result.debug = arg.slice("--debug=".length);
|
|
2827
|
+
i++;
|
|
2828
|
+
} else if (arg === "--source") {
|
|
2829
|
+
const source = args[++i];
|
|
2830
|
+
if (source) result.sources.push(source);
|
|
2831
|
+
i++;
|
|
2832
|
+
} else if (arg.startsWith("--source=")) {
|
|
2833
|
+
result.sources.push(arg.slice("--source=".length));
|
|
2834
|
+
i++;
|
|
2835
|
+
} else if (arg === "--scaffold") {
|
|
2836
|
+
result.scaffold = true;
|
|
2837
|
+
i++;
|
|
2838
|
+
} else if (arg === "--template") {
|
|
2839
|
+
result.template = args[++i];
|
|
2840
|
+
i++;
|
|
2841
|
+
} else if (arg.startsWith("--template=")) {
|
|
2842
|
+
result.template = arg.slice("--template=".length);
|
|
2843
|
+
i++;
|
|
2844
|
+
} else if (arg === "--out") {
|
|
2845
|
+
result.output = args[++i];
|
|
2846
|
+
i++;
|
|
2847
|
+
} else if (arg.startsWith("--out=")) {
|
|
2848
|
+
result.output = arg.slice("--out=".length);
|
|
2849
|
+
i++;
|
|
2850
|
+
} else if (arg === "--dir") {
|
|
2851
|
+
result.dir = args[++i];
|
|
2852
|
+
i++;
|
|
2853
|
+
} else if (arg.startsWith("--dir=")) {
|
|
2854
|
+
result.dir = arg.slice("--dir=".length);
|
|
2855
|
+
i++;
|
|
2856
|
+
} else if (!result.subcommand) {
|
|
2857
|
+
if (arg === "parse" || arg === "run" || arg === "query" || arg === "download" || arg === "import" || arg === "build" || arg === "seed" || arg === "reset" || arg === "init" || arg === "server" || arg === "serve" || arg === "playground" || arg === "help" || arg === "version") {
|
|
2858
|
+
result.subcommand = arg;
|
|
2859
|
+
} else {
|
|
2860
|
+
result.target = arg;
|
|
2861
|
+
}
|
|
2862
|
+
i++;
|
|
2863
|
+
} else if (!result.target) {
|
|
2864
|
+
result.target = arg;
|
|
2865
|
+
i++;
|
|
2866
|
+
} else if (!result.target2) {
|
|
2867
|
+
result.target2 = arg;
|
|
2868
|
+
i++;
|
|
2869
|
+
} else {
|
|
2870
|
+
i++;
|
|
2871
|
+
}
|
|
2872
|
+
}
|
|
2873
|
+
for (const [flag, value] of [["--port", result.port], ["--postgres-port", result.postgresPort]]) {
|
|
2874
|
+
if (value !== void 0 && (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 65535)) {
|
|
2875
|
+
throw new Error(`Invalid value for ${flag}: "${value}" is not a TCP port (1-65535)`);
|
|
2876
|
+
}
|
|
2877
|
+
}
|
|
2878
|
+
return result;
|
|
2879
|
+
}
|
|
2880
|
+
function readBunStdinText() {
|
|
2881
|
+
const g = globalThis;
|
|
2882
|
+
if (g && typeof g === "object" && "Bun" in g) {
|
|
2883
|
+
const bun2 = g.Bun;
|
|
2884
|
+
if (bun2 && typeof bun2 === "object" && "stdin" in bun2) {
|
|
2885
|
+
const stdin = bun2.stdin;
|
|
2886
|
+
if (stdin && typeof stdin === "object" && "text" in stdin) {
|
|
2887
|
+
const text = stdin.text;
|
|
2888
|
+
if (typeof text === "function") return text;
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2891
|
+
}
|
|
2892
|
+
return void 0;
|
|
2893
|
+
}
|
|
2894
|
+
async function readStdin() {
|
|
2895
|
+
const bunText = readBunStdinText();
|
|
2896
|
+
if (bunText) return bunText();
|
|
2897
|
+
return new Promise((resolve2, reject) => {
|
|
2898
|
+
const chunks = [];
|
|
2899
|
+
process.stdin.on("data", (chunk) => {
|
|
2900
|
+
chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
|
|
2901
|
+
});
|
|
2902
|
+
process.stdin.on("end", () => {
|
|
2903
|
+
resolve2(Buffer.concat(chunks).toString("utf-8"));
|
|
2904
|
+
});
|
|
2905
|
+
process.stdin.on("error", (err) => {
|
|
2906
|
+
reject(err);
|
|
2907
|
+
});
|
|
2908
|
+
});
|
|
2909
|
+
}
|
|
2910
|
+
function getUsageText() {
|
|
2911
|
+
return `
|
|
2912
|
+
wod CLI \u2014 Headless Whiteboard Language & WQL Engine runner (v${VERSION})
|
|
2913
|
+
|
|
2914
|
+
USAGE:
|
|
2915
|
+
wod parse <file | -> [options]
|
|
2916
|
+
wod run <file | -> [options]
|
|
2917
|
+
wod query '<wql-string>' [options]
|
|
2918
|
+
wod download <note|session|effort|equipment> <id> [options]
|
|
2919
|
+
wod import <note|session|effort|equipment> <file> [options]
|
|
2920
|
+
wod build [dir] [options]
|
|
2921
|
+
wod seed [options]
|
|
2922
|
+
wod reset [options]
|
|
2923
|
+
wod init Initialize the configured database (idempotent)
|
|
2924
|
+
wod server [options]
|
|
2925
|
+
Serve the app (HTTP API + packaged frontend; alias: serve)
|
|
2926
|
+
wod playground [options]
|
|
2927
|
+
Serve the local playground (browser IndexedDB build)
|
|
2928
|
+
|
|
2929
|
+
SUBCOMMANDS:
|
|
2930
|
+
parse <file | -> Parse Whiteboard Script, create a note in the database
|
|
2931
|
+
(whole source + saved revisions + sparse block index), optionally emit parse-tree IR.
|
|
2932
|
+
Markdown carrying a 'wod-note-id' frontmatter stamp
|
|
2933
|
+
(see download) imports back into that same note.
|
|
2934
|
+
run <file | -> Execute the script state machine, record a session +
|
|
2935
|
+
event/summary rows in the database, optionally emit
|
|
2936
|
+
execution-log IR
|
|
2937
|
+
query '<wql>' Evaluate WQL against the database (or an explicit
|
|
2938
|
+
dataset) and emit QueryResult / RowsQueryResult IR
|
|
2939
|
+
download note <id> Export the note's authored markdown to <id>.md.
|
|
2940
|
+
The frontmatter identity stamp allows re-import.
|
|
2941
|
+
Frontmatter tags (general + typed equipment/quality/\u2026)
|
|
2942
|
+
are materialized into the tag graph on parse/import.
|
|
2943
|
+
download session <id>
|
|
2944
|
+
Write the session's generated metrics (event + summary
|
|
2945
|
+
rows, one CSV row per metric) to <id>.csv. Import back
|
|
2946
|
+
with 'wod import session'.
|
|
2947
|
+
download effort <slug>
|
|
2948
|
+
Write the effort registry row as corpus-style markdown
|
|
2949
|
+
(frontmatter id/slug/label/aliases/baseAttributes + body)
|
|
2950
|
+
to <slug>.md. Import back with 'wod import effort'.
|
|
2951
|
+
download equipment
|
|
2952
|
+
Write every equipment tag as a one-column CSV to
|
|
2953
|
+
equipment.csv. Import back with 'wod import equipment'.
|
|
2954
|
+
import note <file> Re-import exported note markdown (same as parse with
|
|
2955
|
+
the stamped identity).
|
|
2956
|
+
import session <file>
|
|
2957
|
+
Import a session + its events from a downloaded CSV.
|
|
2958
|
+
The exact saved block revision must already exist.
|
|
2959
|
+
import effort <file>
|
|
2960
|
+
Upsert an effort registry row from corpus-style markdown.
|
|
2961
|
+
import equipment <file>
|
|
2962
|
+
Create/upgrade equipment tags (CSV, one label per row).
|
|
2963
|
+
build [dir] Compile a seed corpus: validate every .md under
|
|
2964
|
+
<dir>/markdown (parity gate + dashboard format gate) and
|
|
2965
|
+
write manifest.json + content-hashed chunks/ +
|
|
2966
|
+
report.html to <dir>/dist with source/maps/projections bundled
|
|
2967
|
+
(override with -o/--output). Version stamps derive from
|
|
2968
|
+
<dir>'s git history (full checkout required).
|
|
2969
|
+
|
|
2970
|
+
BUILD OPTIONS (for 'build'):
|
|
2971
|
+
--scaffold Also scaffold markdown/efforts/discovered/*.md stubs for
|
|
2972
|
+
workout effort labels missing from the registry.
|
|
2973
|
+
--template <file> Compile an extra markdown file as the 'template' chunk
|
|
2974
|
+
(the host's playground intake template).
|
|
2975
|
+
|
|
2976
|
+
INPUT SOURCING (for 'query'; without these, the database is queried):
|
|
2977
|
+
-c, --corpus <path> Load historical corpus dataset from a versioned JSON file
|
|
2978
|
+
--stdin-log Read kind: 'execution-log' JSON payload from stdin
|
|
2979
|
+
--stdin-facts Read raw kind: 'fact-set' JSON payload from stdin
|
|
2980
|
+
|
|
2981
|
+
DATABASE (init / parse / run / query / download / import / seed / reset / server):
|
|
2982
|
+
Pick one backend; explicit flags win over the process environment, the
|
|
2983
|
+
process environment wins over .env files. Run 'wod init' once first: it
|
|
2984
|
+
creates the SQLite file + schema, creates the PostgreSQL database when
|
|
2985
|
+
your role is authorized to (otherwise use an existing/provisioned one),
|
|
2986
|
+
or installs the schema in your provisioned Turso database \u2014 idempotently,
|
|
2987
|
+
preserving existing notes. 'wod server' refuses an uninitialized database.
|
|
2988
|
+
--db <path> Local SQLite database file (default: $WOD_WIKI_DB
|
|
2989
|
+
or ./wodwiki.db). Passing --db always selects SQLite,
|
|
2990
|
+
even when the environment names a remote backend.
|
|
2991
|
+
Created on demand by parse/run/seed.
|
|
2992
|
+
--db-driver <name> Backend driver: sqlite (default), postgres, or
|
|
2993
|
+
turso ($DB_DRIVER)
|
|
2994
|
+
--database-url <url> Database connection URL ($DATABASE_URL); accepts
|
|
2995
|
+
PostgreSQL, local SQLite, and remote libSQL URLs.
|
|
2996
|
+
--postgres-host <host> PostgreSQL host ($POSTGRES_HOST)
|
|
2997
|
+
--postgres-port <port> PostgreSQL port ($POSTGRES_PORT)
|
|
2998
|
+
--postgres-user <user> PostgreSQL user ($POSTGRES_USER)
|
|
2999
|
+
--postgres-password <pw> PostgreSQL password ($POSTGRES_PASSWORD)
|
|
3000
|
+
--postgres-database <db> PostgreSQL database name ($POSTGRES_DATABASE)
|
|
3001
|
+
--postgres-ssl <mode> PostgreSQL SSL mode, e.g. disable/prefer/require
|
|
3002
|
+
($POSTGRES_SSL)
|
|
3003
|
+
--turso-url <url> Turso/libSQL database URL (libsql://\u2026). The
|
|
3004
|
+
hosted database must already exist (provisioned on
|
|
3005
|
+
Turso); only its schema is installed.
|
|
3006
|
+
--turso-auth-token <token> Turso authentication token (never printed)
|
|
3007
|
+
--env-file <path> Load variables from this file; a missing file is
|
|
3008
|
+
an error. Without it: ./.env when present, otherwise
|
|
3009
|
+
the workspace-root .env. Credentials are never logged.
|
|
3010
|
+
|
|
3011
|
+
HOSTING (for 'server' / 'playground'; requires the Bun runtime):
|
|
3012
|
+
server HTTP API over the configured database plus the frontend
|
|
3013
|
+
packaged inside the engine module. Requires an
|
|
3014
|
+
initialized database. ('serve' is an accepted alias.)
|
|
3015
|
+
playground Serves the playground app backed by browser IndexedDB;
|
|
3016
|
+
the configured database is not touched.
|
|
3017
|
+
--host <host> Bind address (default 127.0.0.1, $HOST)
|
|
3018
|
+
--port <port> TCP port (default 3000, $PORT)
|
|
3019
|
+
--dist <dir> Serve this prebuilt frontend directory instead of the
|
|
3020
|
+
packaged one ($PLAYGROUND_DIST); must already contain
|
|
3021
|
+
index.html.
|
|
3022
|
+
|
|
3023
|
+
SEED SOURCING (for 'seed'):
|
|
3024
|
+
--source <dir> Extra compiled seed directory (manifest.json + chunks);
|
|
3025
|
+
repeatable. Defaults to the bundled core + community
|
|
3026
|
+
artifacts under apps/playground/public/seed.
|
|
3027
|
+
|
|
3028
|
+
OPTIONS:
|
|
3029
|
+
--format <fmt> Output format: json (default), table, csv
|
|
3030
|
+
-o, --output <path> Write the IR payload (or download) to a path instead of
|
|
3031
|
+
the default; '-' writes to stdout
|
|
3032
|
+
--debug[=name] Also write the IR payload to <name> (default
|
|
3033
|
+
wod-<subcommand>-debug.json); without it, parse/run
|
|
3034
|
+
print a one-line summary of what was persisted
|
|
3035
|
+
--pack <module> Dynamically load and register a Language Pack (repeatable)
|
|
3036
|
+
--sport <sport> Target sport fence dialect (e.g. climbing, crossfit)
|
|
3037
|
+
--unit <unit> Preferred display unit for queries (e.g. lb, kg)
|
|
3038
|
+
-h, --help Show help message
|
|
3039
|
+
-v, --version Show version number
|
|
3040
|
+
|
|
3041
|
+
ENVIRONMENT (flags > process env > .env):
|
|
3042
|
+
WOD_WIKI_DB, SQLITE_PATH SQLite file path
|
|
3043
|
+
DB_DRIVER sqlite | postgres | turso
|
|
3044
|
+
DATABASE_URL PostgreSQL connection URL
|
|
3045
|
+
POSTGRES_HOST, POSTGRES_PORT, POSTGRES_USER,
|
|
3046
|
+
POSTGRES_PASSWORD, POSTGRES_DATABASE, POSTGRES_SSL
|
|
3047
|
+
TURSO_DATABASE_URL, TURSO_AUTH_TOKEN, LIBSQL_AUTH_TOKEN
|
|
3048
|
+
HOST, PORT, PLAYGROUND_DIST server / playground defaults
|
|
3049
|
+
|
|
3050
|
+
EXIT CODES:
|
|
3051
|
+
0 - OK / Success
|
|
3052
|
+
1 - General / Runtime error
|
|
3053
|
+
2 - Parse / Syntax error
|
|
3054
|
+
3 - Language Pack load error
|
|
3055
|
+
`;
|
|
3056
|
+
}
|
|
3057
|
+
function printUsage(writer) {
|
|
3058
|
+
const text = getUsageText();
|
|
3059
|
+
if (writer) {
|
|
3060
|
+
writer(text);
|
|
3061
|
+
} else {
|
|
3062
|
+
process.stdout.write(text.endsWith("\n") ? text : text + "\n");
|
|
3063
|
+
}
|
|
3064
|
+
}
|
|
3065
|
+
async function cliMain(argv = process.argv.slice(2), io = {}) {
|
|
3066
|
+
const writeOut = io.stdout ?? ((t) => process.stdout.write(t + "\n"));
|
|
3067
|
+
const writeErr = io.stderr ?? ((t) => process.stderr.write(t + "\n"));
|
|
3068
|
+
const getStdin = io.readStdinFn ?? readStdin;
|
|
3069
|
+
let envLoaded;
|
|
3070
|
+
const cliEnv = () => envLoaded ??= { ...loadCliEnvironment(parsed.envFile), ...process.env };
|
|
3071
|
+
let dbResolved;
|
|
3072
|
+
const cliDb = () => dbResolved ??= resolveDatabaseConfig(parsed, cliEnv());
|
|
3073
|
+
let parsed;
|
|
3074
|
+
try {
|
|
3075
|
+
parsed = parseCliArgs(argv);
|
|
3076
|
+
} catch (error) {
|
|
3077
|
+
writeErr(error instanceof Error ? error.message : String(error));
|
|
3078
|
+
return 1;
|
|
3079
|
+
}
|
|
3080
|
+
if (parsed.version || parsed.subcommand === "version") {
|
|
3081
|
+
writeOut(`wod v${VERSION}`);
|
|
3082
|
+
return 0;
|
|
3083
|
+
}
|
|
3084
|
+
if (parsed.help || parsed.subcommand === "help") {
|
|
3085
|
+
printUsage(writeOut);
|
|
3086
|
+
return 0;
|
|
3087
|
+
}
|
|
3088
|
+
if (!parsed.subcommand) {
|
|
3089
|
+
printUsage(writeErr);
|
|
3090
|
+
return 1;
|
|
3091
|
+
}
|
|
3092
|
+
for (const packSpec of parsed.packs) {
|
|
3093
|
+
try {
|
|
3094
|
+
await loadLanguagePack(packSpec);
|
|
3095
|
+
} catch (err) {
|
|
3096
|
+
if (err instanceof PackLoadError) {
|
|
3097
|
+
writeErr(err.message);
|
|
3098
|
+
} else {
|
|
3099
|
+
writeErr(`[wod] Language pack load error: ${err instanceof Error ? err.message : String(err)}`);
|
|
3100
|
+
}
|
|
3101
|
+
return 3;
|
|
3102
|
+
}
|
|
3103
|
+
}
|
|
3104
|
+
const deliverOutput = (formattedText) => {
|
|
3105
|
+
if (parsed.output && parsed.output !== "-") {
|
|
3106
|
+
getFs2().writeFileSync(parsed.output, formattedText, "utf-8");
|
|
3107
|
+
} else {
|
|
3108
|
+
writeOut(formattedText);
|
|
3109
|
+
}
|
|
3110
|
+
};
|
|
3111
|
+
const debugTarget = (subcommand) => parsed.debug === void 0 ? void 0 : parsed.debug || `wod-${subcommand}-debug.json`;
|
|
3112
|
+
const writeDebugFile = (subcommand, ir) => {
|
|
3113
|
+
const target = debugTarget(subcommand);
|
|
3114
|
+
if (target !== void 0) {
|
|
3115
|
+
getFs2().writeFileSync(target, JSON.stringify(ir, null, 2) + "\n", "utf-8");
|
|
3116
|
+
}
|
|
3117
|
+
};
|
|
3118
|
+
try {
|
|
3119
|
+
if (parsed.subcommand === "parse") {
|
|
3120
|
+
if (!parsed.target) {
|
|
3121
|
+
writeErr('[wod parse] Error: Missing input file or "-" for stdin');
|
|
3122
|
+
return 1;
|
|
3123
|
+
}
|
|
3124
|
+
let source;
|
|
3125
|
+
if (parsed.target === "-") {
|
|
3126
|
+
source = await getStdin();
|
|
3127
|
+
} else {
|
|
3128
|
+
const fs = getFs2();
|
|
3129
|
+
if (!fs.existsSync(parsed.target)) {
|
|
3130
|
+
writeErr(`[wod parse] File not found: ${parsed.target}`);
|
|
3131
|
+
return 1;
|
|
3132
|
+
}
|
|
3133
|
+
source = fs.readFileSync(parsed.target, "utf-8");
|
|
3134
|
+
}
|
|
3135
|
+
const noteSource = cliNoteSource(source, parsed.target, parsed.sport);
|
|
3136
|
+
const ir = runParse(source, { sport: parsed.sport, sourceLabel: `cli:wod parse ${parsed.target}` });
|
|
3137
|
+
const identity = wodWikiEngine.extractNoteIdentity(source);
|
|
3138
|
+
const tags = wodWikiEngine.extractTypedTags(source);
|
|
3139
|
+
const db = await openCliDb(cliDb());
|
|
3140
|
+
try {
|
|
3141
|
+
const persisted = await persistNote(db, {
|
|
3142
|
+
source: noteSource,
|
|
3143
|
+
sourceLabel: parsed.target,
|
|
3144
|
+
noteId: identity?.noteId,
|
|
3145
|
+
title: identity?.title,
|
|
3146
|
+
tags
|
|
3147
|
+
});
|
|
3148
|
+
writeOut(
|
|
3149
|
+
`[wod parse] note ${persisted.noteId}${persisted.created ? "" : " (updated)"} \u2014 ${persisted.blocks} blocks, ${persisted.efforts} efforts${persisted.tags > 0 ? `, ${persisted.tags} tags` : ""} \u2192 ${db.path}`
|
|
3150
|
+
);
|
|
3151
|
+
} finally {
|
|
3152
|
+
await db.close();
|
|
3153
|
+
}
|
|
3154
|
+
if (parsed.output) {
|
|
3155
|
+
const pretty = Boolean(process.stdout.isTTY);
|
|
3156
|
+
deliverOutput(formatParseOutput(ir, parsed.format, pretty));
|
|
3157
|
+
}
|
|
3158
|
+
writeDebugFile("parse", ir);
|
|
3159
|
+
return 0;
|
|
3160
|
+
}
|
|
3161
|
+
if (parsed.subcommand === "run") {
|
|
3162
|
+
if (!parsed.target) {
|
|
3163
|
+
writeErr('[wod run] Error: Missing input file or "-" for stdin');
|
|
3164
|
+
return 1;
|
|
3165
|
+
}
|
|
3166
|
+
let source;
|
|
3167
|
+
if (parsed.target === "-") {
|
|
3168
|
+
source = await getStdin();
|
|
3169
|
+
} else {
|
|
3170
|
+
const fs = getFs2();
|
|
3171
|
+
if (!fs.existsSync(parsed.target)) {
|
|
3172
|
+
writeErr(`[wod run] File not found: ${parsed.target}`);
|
|
3173
|
+
return 1;
|
|
3174
|
+
}
|
|
3175
|
+
source = fs.readFileSync(parsed.target, "utf-8");
|
|
3176
|
+
}
|
|
3177
|
+
const identity = wodWikiEngine.extractNoteIdentity(source);
|
|
3178
|
+
const db = await openCliDb(cliDb());
|
|
3179
|
+
let ir;
|
|
3180
|
+
try {
|
|
3181
|
+
const started = await startRun(db, {
|
|
3182
|
+
source: cliNoteSource(source, parsed.target, parsed.sport),
|
|
3183
|
+
sourceLabel: parsed.target,
|
|
3184
|
+
noteId: identity?.noteId,
|
|
3185
|
+
title: identity?.title,
|
|
3186
|
+
tags: wodWikiEngine.extractTypedTags(source)
|
|
3187
|
+
});
|
|
3188
|
+
const section = wodWikiCore.parseDocumentSections(started.revision.rawContent).find((row) => row.scriptBlock);
|
|
3189
|
+
if (!section?.scriptBlock) throw new Error("[wod run] Captured workout source cannot be parsed");
|
|
3190
|
+
const bare = !/\.(?:md|markdown)$/i.test(parsed.target) && !wodWikiCore.parseDocumentSections(source).some((row) => row.scriptBlock);
|
|
3191
|
+
const frozenBody = bare ? section.scriptBlock.content.slice(0, -1) : section.scriptBlock.content;
|
|
3192
|
+
ir = await runExecution(frozenBody, {
|
|
3193
|
+
sport: started.revision.sport,
|
|
3194
|
+
dialect: started.revision.dialect,
|
|
3195
|
+
blockId: started.session.blockId,
|
|
3196
|
+
blockVersion: started.session.blockVersion,
|
|
3197
|
+
startTime: started.session.startTime,
|
|
3198
|
+
sourceLabel: `cli:wod run ${parsed.target}`
|
|
3199
|
+
});
|
|
3200
|
+
const persisted = await persistRun(db, started, ir.data);
|
|
3201
|
+
writeOut(
|
|
3202
|
+
`[wod run] session ${persisted.resultId} \u2014 ${persisted.events} events, ${persisted.summaries} summaries on note ${persisted.noteId} \u2192 ${db.path}`
|
|
3203
|
+
);
|
|
3204
|
+
} finally {
|
|
3205
|
+
await db.close();
|
|
3206
|
+
}
|
|
3207
|
+
if (parsed.output) {
|
|
3208
|
+
const pretty = Boolean(process.stdout.isTTY);
|
|
3209
|
+
deliverOutput(formatExecutionOutput(ir, parsed.format, pretty));
|
|
3210
|
+
}
|
|
3211
|
+
writeDebugFile("run", ir);
|
|
3212
|
+
return 0;
|
|
3213
|
+
}
|
|
3214
|
+
if (parsed.subcommand === "query") {
|
|
3215
|
+
if (!parsed.target) {
|
|
3216
|
+
writeErr("[wod query] Error: Missing WQL query argument");
|
|
3217
|
+
return 1;
|
|
3218
|
+
}
|
|
3219
|
+
const useDb = !parsed.corpus && !parsed.stdinLog && !parsed.stdinFacts;
|
|
3220
|
+
let stdinLogContent;
|
|
3221
|
+
let stdinFactsContent;
|
|
3222
|
+
if (parsed.stdinLog) {
|
|
3223
|
+
stdinLogContent = await getStdin();
|
|
3224
|
+
} else if (parsed.stdinFacts) {
|
|
3225
|
+
stdinFactsContent = await getStdin();
|
|
3226
|
+
}
|
|
3227
|
+
let ir;
|
|
3228
|
+
if (useDb) {
|
|
3229
|
+
const config = cliDb();
|
|
3230
|
+
if (config.kind === "sqlite" && !nodeFs().existsSync(config.path)) {
|
|
3231
|
+
writeErr(
|
|
3232
|
+
`[wod query] No input dataset and no database at ${config.path}. Specify --corpus <file>, --stdin-log, --stdin-facts, or run \`wod seed\` first.`
|
|
3233
|
+
);
|
|
3234
|
+
return 1;
|
|
3235
|
+
}
|
|
3236
|
+
const db = await openCliDb(config, config.kind === "sqlite" ? void 0 : { initialize: false });
|
|
3237
|
+
try {
|
|
3238
|
+
ir = await runQueryCli(parsed.target, {
|
|
3239
|
+
preferredUnit: parsed.unit,
|
|
3240
|
+
sourceLabel: `cli:wod query "${parsed.target}"`,
|
|
3241
|
+
stores: {
|
|
3242
|
+
eventStore: sqliteEventStore(db.db),
|
|
3243
|
+
noteStore: sqliteNoteStore(db.db),
|
|
3244
|
+
blockStore: sqliteBlockStore(db.db),
|
|
3245
|
+
effortStore: sqliteEffortStore(db.db),
|
|
3246
|
+
blockEffortsStore: sqliteIndexStore(db.db, "block_efforts"),
|
|
3247
|
+
tagsStore: sqliteIndexStore(db.db, "tags"),
|
|
3248
|
+
noteTagsStore: sqliteIndexStore(db.db, "note_tags")
|
|
3249
|
+
}
|
|
3250
|
+
});
|
|
3251
|
+
} finally {
|
|
3252
|
+
await db.close();
|
|
3253
|
+
}
|
|
3254
|
+
} else {
|
|
3255
|
+
if (!parsed.corpus && !stdinLogContent && !stdinFactsContent) {
|
|
3256
|
+
writeErr("[wod query] Error: Query requires input data. Specify --corpus <file>, --stdin-log, or --stdin-facts.");
|
|
3257
|
+
return 1;
|
|
3258
|
+
}
|
|
3259
|
+
ir = await runQueryCli(parsed.target, {
|
|
3260
|
+
corpusPath: parsed.corpus,
|
|
3261
|
+
stdinLog: stdinLogContent,
|
|
3262
|
+
stdinFacts: stdinFactsContent,
|
|
3263
|
+
preferredUnit: parsed.unit,
|
|
3264
|
+
sourceLabel: `cli:wod query "${parsed.target}"`
|
|
3265
|
+
});
|
|
3266
|
+
}
|
|
3267
|
+
const pretty = !parsed.output && Boolean(process.stdout.isTTY);
|
|
3268
|
+
const formatted = formatQueryOutput(ir, parsed.format, pretty);
|
|
3269
|
+
deliverOutput(formatted);
|
|
3270
|
+
writeDebugFile("query", ir);
|
|
3271
|
+
return 0;
|
|
3272
|
+
}
|
|
3273
|
+
if (parsed.subcommand === "download") {
|
|
3274
|
+
const kind = parsed.target;
|
|
3275
|
+
const id = parsed.target2;
|
|
3276
|
+
const DOWNLOAD_KINDS = ["note", "session", "effort", "equipment"];
|
|
3277
|
+
if (!id && kind !== "equipment" || !DOWNLOAD_KINDS.includes(kind ?? "")) {
|
|
3278
|
+
writeErr("[wod download] Usage: wod download <note|session|effort|equipment> <id> [-o <path>]");
|
|
3279
|
+
return 1;
|
|
3280
|
+
}
|
|
3281
|
+
const targetId = id;
|
|
3282
|
+
const db = await openCliDb(cliDb());
|
|
3283
|
+
try {
|
|
3284
|
+
if (kind === "note") {
|
|
3285
|
+
const bundle = await getNoteBundle(db.db, targetId);
|
|
3286
|
+
if (!bundle.note) {
|
|
3287
|
+
writeErr(`[wod download] Note not found in ${db.path}: ${id}`);
|
|
3288
|
+
return 1;
|
|
3289
|
+
}
|
|
3290
|
+
const markdown = wodWikiEngine.composeNoteMarkdown(bundle.note);
|
|
3291
|
+
const target = parsed.output && parsed.output !== "-" ? parsed.output : `${id}.md`;
|
|
3292
|
+
if (parsed.output === "-") {
|
|
3293
|
+
writeOut(markdown);
|
|
3294
|
+
} else {
|
|
3295
|
+
nodeFs().writeFileSync(target, markdown, "utf-8");
|
|
3296
|
+
}
|
|
3297
|
+
if (parsed.output !== "-") writeOut(`[wod download] note ${id} \u2192 ${target}`);
|
|
3298
|
+
} else if (kind === "session") {
|
|
3299
|
+
const bundle = await getSessionBundle(db.db, targetId);
|
|
3300
|
+
if (!bundle) {
|
|
3301
|
+
writeErr(`[wod download] Session not found in ${db.path}: ${id}`);
|
|
3302
|
+
return 1;
|
|
3303
|
+
}
|
|
3304
|
+
const csv = wodWikiEngine.sessionToCsv(bundle.session, bundle.events);
|
|
3305
|
+
const target = parsed.output && parsed.output !== "-" ? parsed.output : `${id}.csv`;
|
|
3306
|
+
if (parsed.output === "-") {
|
|
3307
|
+
writeOut(csv);
|
|
3308
|
+
} else {
|
|
3309
|
+
nodeFs().writeFileSync(target, csv, "utf-8");
|
|
3310
|
+
}
|
|
3311
|
+
if (parsed.output !== "-") writeOut(`[wod download] session ${id} \u2192 ${target} (${bundle.events.length} events)`);
|
|
3312
|
+
} else if (kind === "effort") {
|
|
3313
|
+
const effort = await getEffortBySlug(db.db, targetId);
|
|
3314
|
+
if (!effort) {
|
|
3315
|
+
writeErr(`[wod download] Effort not found in ${db.path}: ${id}`);
|
|
3316
|
+
return 1;
|
|
3317
|
+
}
|
|
3318
|
+
const markdown = wodWikiEngine.effortToMarkdown(effort);
|
|
3319
|
+
const target = parsed.output && parsed.output !== "-" ? parsed.output : `${id}.md`;
|
|
3320
|
+
if (parsed.output === "-") {
|
|
3321
|
+
writeOut(markdown);
|
|
3322
|
+
} else {
|
|
3323
|
+
nodeFs().writeFileSync(target, markdown, "utf-8");
|
|
3324
|
+
}
|
|
3325
|
+
writeOut(`[wod download] effort ${id} \u2192 ${target}`);
|
|
3326
|
+
} else {
|
|
3327
|
+
const labels = (await listTagsByType(db.db, "equipment")).map((t) => t.label).sort();
|
|
3328
|
+
const csv = wodWikiEngine.equipmentToCsv(labels);
|
|
3329
|
+
const target = parsed.output && parsed.output !== "-" ? parsed.output : "equipment.csv";
|
|
3330
|
+
if (parsed.output === "-") {
|
|
3331
|
+
writeOut(csv);
|
|
3332
|
+
} else {
|
|
3333
|
+
nodeFs().writeFileSync(target, csv, "utf-8");
|
|
3334
|
+
}
|
|
3335
|
+
writeOut(`[wod download] equipment \u2192 ${target} (${labels.length} labels)`);
|
|
3336
|
+
}
|
|
3337
|
+
} finally {
|
|
3338
|
+
await db.close();
|
|
3339
|
+
}
|
|
3340
|
+
return 0;
|
|
3341
|
+
}
|
|
3342
|
+
if (parsed.subcommand === "import") {
|
|
3343
|
+
const kind = parsed.target;
|
|
3344
|
+
const file = parsed.target2;
|
|
3345
|
+
const IMPORT_KINDS = ["note", "session", "effort", "equipment"];
|
|
3346
|
+
if (!file || !IMPORT_KINDS.includes(kind ?? "")) {
|
|
3347
|
+
writeErr("[wod import] Usage: wod import <note|session|effort|equipment> <file>");
|
|
3348
|
+
return 1;
|
|
3349
|
+
}
|
|
3350
|
+
const fs = nodeFs();
|
|
3351
|
+
if (!fs.existsSync(file)) {
|
|
3352
|
+
writeErr(`[wod import] File not found: ${file}`);
|
|
3353
|
+
return 1;
|
|
3354
|
+
}
|
|
3355
|
+
if (kind === "note") {
|
|
3356
|
+
const source = fs.readFileSync(file, "utf-8");
|
|
3357
|
+
const identity = wodWikiEngine.extractNoteIdentity(source);
|
|
3358
|
+
const tags = wodWikiEngine.extractTypedTags(source);
|
|
3359
|
+
const db2 = await openCliDb(cliDb());
|
|
3360
|
+
try {
|
|
3361
|
+
const persisted = await persistNote(db2, {
|
|
3362
|
+
source,
|
|
3363
|
+
sourceLabel: file,
|
|
3364
|
+
noteId: identity?.noteId,
|
|
3365
|
+
title: identity?.title,
|
|
3366
|
+
tags
|
|
3367
|
+
});
|
|
3368
|
+
writeOut(
|
|
3369
|
+
`[wod import] note ${persisted.noteId}${persisted.created ? "" : " (updated)"} \u2014 ${persisted.blocks} blocks${persisted.tags > 0 ? `, ${persisted.tags} tags` : ""} \u2192 ${db2.path}`
|
|
3370
|
+
);
|
|
3371
|
+
} finally {
|
|
3372
|
+
await db2.close();
|
|
3373
|
+
}
|
|
3374
|
+
return 0;
|
|
3375
|
+
}
|
|
3376
|
+
if (kind === "effort") {
|
|
3377
|
+
const effort = wodWikiEngine.markdownToEffort(fs.readFileSync(file, "utf-8"));
|
|
3378
|
+
if (!effort) {
|
|
3379
|
+
writeErr(`[wod import] Unparseable effort file (need frontmatter id/slug/label + numeric baseAttributes.met): ${file}`);
|
|
3380
|
+
return 1;
|
|
3381
|
+
}
|
|
3382
|
+
const db2 = await openCliDb(cliDb());
|
|
3383
|
+
try {
|
|
3384
|
+
await persistEffort(db2, { ...effort, registrySource: "user" });
|
|
3385
|
+
writeOut(`[wod import] effort ${effort.slug} \u2014 ${effort.label} \u2192 ${db2.path}`);
|
|
3386
|
+
} finally {
|
|
3387
|
+
await db2.close();
|
|
3388
|
+
}
|
|
3389
|
+
return 0;
|
|
3390
|
+
}
|
|
3391
|
+
if (kind === "equipment") {
|
|
3392
|
+
const labels = wodWikiEngine.csvToEquipmentLabels(fs.readFileSync(file, "utf-8"));
|
|
3393
|
+
if (labels.length === 0) {
|
|
3394
|
+
writeErr(`[wod import] No equipment labels found in ${file}`);
|
|
3395
|
+
return 1;
|
|
3396
|
+
}
|
|
3397
|
+
const db2 = await openCliDb(cliDb());
|
|
3398
|
+
try {
|
|
3399
|
+
const added = await persistTypedTags(db2, labels, "equipment");
|
|
3400
|
+
writeOut(`[wod import] equipment \u2014 ${labels.length} labels (${added} new) \u2192 ${db2.path}`);
|
|
3401
|
+
} finally {
|
|
3402
|
+
await db2.close();
|
|
3403
|
+
}
|
|
3404
|
+
return 0;
|
|
3405
|
+
}
|
|
3406
|
+
const { session, events } = wodWikiEngine.csvToSessionRows(fs.readFileSync(file, "utf-8"));
|
|
3407
|
+
const db = await openCliDb(cliDb());
|
|
3408
|
+
try {
|
|
3409
|
+
const result = await persistSessionBundle(db, session, events);
|
|
3410
|
+
writeOut(
|
|
3411
|
+
`[wod import] session ${session.id} \u2014 ${result.events} events \u2192 ${db.path}`
|
|
3412
|
+
);
|
|
3413
|
+
} finally {
|
|
3414
|
+
await db.close();
|
|
3415
|
+
}
|
|
3416
|
+
return 0;
|
|
3417
|
+
}
|
|
3418
|
+
if (parsed.subcommand === "build") {
|
|
3419
|
+
const cwd = process.cwd();
|
|
3420
|
+
const root = nodePath().resolve(cwd, parsed.dir ?? parsed.target ?? ".");
|
|
3421
|
+
if (!nodeFs().existsSync(nodePath().resolve(root, "markdown"))) {
|
|
3422
|
+
writeErr(`[wod build] No markdown/ corpus under ${root} \u2014 run from the content repo root (or pass its directory).`);
|
|
3423
|
+
return 1;
|
|
3424
|
+
}
|
|
3425
|
+
const { generateSeed: generateSeed2 } = await Promise.resolve().then(() => (init_compiler(), compiler_exports));
|
|
3426
|
+
try {
|
|
3427
|
+
const result = generateSeed2({
|
|
3428
|
+
corpusRoot: root,
|
|
3429
|
+
...parsed.output ? { outDir: nodePath().resolve(cwd, parsed.output) } : {},
|
|
3430
|
+
...parsed.template ? { templateFile: nodePath().resolve(cwd, parsed.template) } : {},
|
|
3431
|
+
scaffoldDiscoveredEfforts: parsed.scaffold === true
|
|
3432
|
+
});
|
|
3433
|
+
const kb = (n) => `${(n / 1024).toFixed(0)} KB`;
|
|
3434
|
+
const totalBytes = result.manifest.chunks.reduce((s, c) => s + c.bytes, 0);
|
|
3435
|
+
writeOut(`[wod build] schema v${result.manifest.schema} version ${result.manifest.version} (${result.manifest.versionLabel}) \u2192 ${result.outDir}`);
|
|
3436
|
+
for (const c of result.manifest.chunks) {
|
|
3437
|
+
writeOut(` ${c.id.padEnd(48)} ${String(c.count).padStart(4)} files ${kb(c.bytes).padStart(8)}`);
|
|
3438
|
+
}
|
|
3439
|
+
writeOut(`[wod build] ${result.manifest.chunks.length} chunks, ${result.totalFiles} files, ${kb(totalBytes)} total \u2014 scan ${result.passMs.scan}ms, block-index ${result.passMs.blockIndex}ms, block-efforts ${result.passMs.blockEfforts}ms, write ${result.passMs.write}ms`);
|
|
3440
|
+
return 0;
|
|
3441
|
+
} catch (error) {
|
|
3442
|
+
writeErr(`[wod build] ${error.message}`);
|
|
3443
|
+
return 1;
|
|
3444
|
+
}
|
|
3445
|
+
}
|
|
3446
|
+
if (parsed.subcommand === "seed") {
|
|
3447
|
+
const dirs = parsed.sources.length > 0 ? parsed.sources.map((s) => nodePath().resolve(process.cwd(), s)) : defaultSeedDirs(process.cwd());
|
|
3448
|
+
if (dirs.length === 0) {
|
|
3449
|
+
writeErr(
|
|
3450
|
+
"[wod seed] No seed sources found. Run `bun scripts/sync-seed.ts` to build the bundled artifacts, or pass --source <dir> pointing at a compiled seed directory (manifest.json + chunks)."
|
|
3451
|
+
);
|
|
3452
|
+
return 1;
|
|
3453
|
+
}
|
|
3454
|
+
const db = await openCliDb(cliDb());
|
|
3455
|
+
try {
|
|
3456
|
+
for (const dir of dirs) {
|
|
3457
|
+
const summary = await importSeedDir(db, dir, "");
|
|
3458
|
+
writeOut(
|
|
3459
|
+
`[wod seed] ${summary.sourceId}: v${summary.version} \u2014 ${summary.notes} notes, ${summary.efforts} efforts, ${summary.blocks} blocks, ${summary.blockEfforts} block-efforts (${summary.deleted} deleted, ${summary.skippedUserOwned} user-owned skipped) \u2192 ${db.path}`
|
|
3460
|
+
);
|
|
3461
|
+
}
|
|
3462
|
+
} finally {
|
|
3463
|
+
await db.close();
|
|
3464
|
+
}
|
|
3465
|
+
return 0;
|
|
3466
|
+
}
|
|
3467
|
+
if (parsed.subcommand === "reset") {
|
|
3468
|
+
const config = cliDb();
|
|
3469
|
+
if (config.kind !== "sqlite") {
|
|
3470
|
+
writeErr(
|
|
3471
|
+
`[wod reset] refusing to reset the configured ${config.kind} database \u2014 reset only removes a local SQLite file. Clear remote databases through their provider.`
|
|
3472
|
+
);
|
|
3473
|
+
return 1;
|
|
3474
|
+
}
|
|
3475
|
+
const target = config.path;
|
|
3476
|
+
if (nodeFs().existsSync(target)) {
|
|
3477
|
+
nodeFs().unlinkSync(target);
|
|
3478
|
+
writeOut(`[wod reset] removed ${target}`);
|
|
3479
|
+
} else {
|
|
3480
|
+
writeOut(`[wod reset] nothing to reset \u2014 ${target} does not exist`);
|
|
3481
|
+
}
|
|
3482
|
+
return 0;
|
|
3483
|
+
}
|
|
3484
|
+
if (parsed.subcommand === "init") {
|
|
3485
|
+
const db = await openCliDb(cliDb(), { create: true });
|
|
3486
|
+
try {
|
|
3487
|
+
writeOut(`[wod init] database ready at ${db.path}`);
|
|
3488
|
+
} finally {
|
|
3489
|
+
await db.close();
|
|
3490
|
+
}
|
|
3491
|
+
return 0;
|
|
3492
|
+
}
|
|
3493
|
+
if (parsed.subcommand === "server" || parsed.subcommand === "serve" || parsed.subcommand === "playground") {
|
|
3494
|
+
if (!("Bun" in globalThis)) {
|
|
3495
|
+
writeErr(
|
|
3496
|
+
`[wod ${parsed.subcommand}] Error: hosting requires the Bun runtime (https://bun.sh) \u2014 run \`bun wod server\` / \`bun wod playground\`.`
|
|
3497
|
+
);
|
|
3498
|
+
return 1;
|
|
3499
|
+
}
|
|
3500
|
+
const mode = parsed.subcommand === "playground" ? "playground" : "server";
|
|
3501
|
+
const { runCliServer: runCliServer2 } = await Promise.resolve().then(() => (init_server(), server_exports));
|
|
3502
|
+
const options = { env: cliEnv() };
|
|
3503
|
+
if (mode === "server") options.database = cliDb();
|
|
3504
|
+
if (parsed.host !== void 0) options.host = parsed.host;
|
|
3505
|
+
if (parsed.port !== void 0) options.port = parsed.port;
|
|
3506
|
+
if (parsed.dist !== void 0) options.dist = parsed.dist;
|
|
3507
|
+
await runCliServer2(mode, options, writeOut);
|
|
3508
|
+
return 0;
|
|
3509
|
+
}
|
|
3510
|
+
writeErr(`[wod] Unknown subcommand "${parsed.subcommand}"`);
|
|
3511
|
+
return 1;
|
|
3512
|
+
} catch (error) {
|
|
3513
|
+
if (error instanceof ParseSyntaxError || error instanceof WqlSyntaxError) {
|
|
3514
|
+
writeErr(error.message);
|
|
3515
|
+
return 2;
|
|
3516
|
+
}
|
|
3517
|
+
if (error instanceof PackLoadError) {
|
|
3518
|
+
writeErr(error.message);
|
|
3519
|
+
return 3;
|
|
3520
|
+
}
|
|
3521
|
+
writeErr(`[wod] Error: ${error instanceof Error ? error.message : String(error)}`);
|
|
3522
|
+
return 1;
|
|
3523
|
+
}
|
|
3524
|
+
}
|
|
3525
|
+
|
|
3526
|
+
// src/bin/wod.ts
|
|
3527
|
+
void (async () => {
|
|
3528
|
+
const exitCode = await cliMain(process.argv.slice(2));
|
|
3529
|
+
process.exitCode = exitCode;
|
|
3530
|
+
})();
|
|
3531
|
+
//# sourceMappingURL=wod.cjs.map
|
|
3532
|
+
//# sourceMappingURL=wod.cjs.map
|