@jacebenson/jsn 5.5.6 → 5.5.7-dev.212.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -1
- package/package.json +9 -8
- package/src/amb.js +15 -0
- package/src/app.js +4 -15
- package/src/auth/credential-store.js +131 -32
- package/src/auth/oauth.js +4 -28
- package/src/auth/transport.js +22 -0
- package/src/auth.js +23 -2
- package/src/cli-adapter.js +18 -1
- package/src/cli.js +0 -3
- package/src/commands/auth.js +21 -5
- package/src/commands/codesearch.js +11 -2
- package/src/commands/docs/community.js +1 -1
- package/src/commands/docs/db.js +38 -4
- package/src/commands/docs/docs.js +14 -13
- package/src/commands/docs/index.js +2 -1
- package/src/commands/docs/refresh.js +2 -1
- package/src/commands/docs/releases.js +1 -1
- package/src/commands/docs/replace.js +1 -1
- package/src/commands/docs/service-snapshot.js +1 -1
- package/src/commands/docs/snapshot.js +2 -1
- package/src/commands/docs/sync-service.js +5 -3
- package/src/commands/flows.js +7 -2
- package/src/commands/setup.js +28 -31
- package/src/commands/skill.js +3 -8
- package/src/commands/version.js +5 -1
- package/src/config.js +93 -18
- package/src/docs-links.js +28 -0
- package/src/help.js +4 -0
- package/src/midserver-install.js +3 -0
- package/src/paginated-search.js +146 -178
- package/src/perf.js +1 -1
- package/src/prompt-engine.js +169 -0
- package/src/prompts.js +304 -42
- package/src/sdk.js +10 -44
- package/src/session.js +6 -1
- package/src/sqlite.js +94 -0
- package/src/commands/docs/public/index.html +0 -178
- package/src/commands/docs/public/vendor/marked.min.js +0 -69
- package/src/commands/docs/public/vendor/purify.min.js +0 -3
- package/src/commands/docs/serve.js +0 -287
- package/src/commands/history.js +0 -57
- package/src/mutation-history.js +0 -75
|
@@ -1,287 +0,0 @@
|
|
|
1
|
-
// Built-in HTTP server for docs search (node:http only, no Express).
|
|
2
|
-
|
|
3
|
-
import fs from 'node:fs';
|
|
4
|
-
import path from 'node:path';
|
|
5
|
-
import http from 'node:http';
|
|
6
|
-
import { URL } from 'node:url';
|
|
7
|
-
import Database from 'better-sqlite3';
|
|
8
|
-
import { resolveDocsDbPath, hasEmbeddings, closeDocsDb } from './db.js';
|
|
9
|
-
import { sanitizeFts5Query } from './fts.js';
|
|
10
|
-
import { encodeText, similarity, bytesToPhases, DEFAULT_DIM } from './hrr.js';
|
|
11
|
-
|
|
12
|
-
const PUBLIC_DIR = path.join(import.meta.dirname, 'public');
|
|
13
|
-
|
|
14
|
-
function safeParse(s) {
|
|
15
|
-
try {
|
|
16
|
-
return JSON.parse(s);
|
|
17
|
-
} catch {
|
|
18
|
-
return null;
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
function sendJSON(res, status, obj) {
|
|
23
|
-
const body = JSON.stringify(obj, null, 2);
|
|
24
|
-
res.writeHead(status, {
|
|
25
|
-
'Content-Type': 'application/json',
|
|
26
|
-
'Content-Length': Buffer.byteLength(body),
|
|
27
|
-
});
|
|
28
|
-
res.end(body);
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function sendText(res, status, text, type = 'text/plain') {
|
|
32
|
-
res.writeHead(status, {
|
|
33
|
-
'Content-Type': type,
|
|
34
|
-
'Content-Length': Buffer.byteLength(text),
|
|
35
|
-
});
|
|
36
|
-
res.end(text);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function serveStatic(req, res, filePath) {
|
|
40
|
-
if (!fs.existsSync(filePath)) {
|
|
41
|
-
sendText(res, 404, 'Not found');
|
|
42
|
-
return;
|
|
43
|
-
}
|
|
44
|
-
const stat = fs.statSync(filePath);
|
|
45
|
-
if (stat.isDirectory()) {
|
|
46
|
-
sendText(res, 403, 'Forbidden');
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
const ext = path.extname(filePath).toLowerCase();
|
|
50
|
-
const mime = {
|
|
51
|
-
'.html': 'text/html',
|
|
52
|
-
'.js': 'application/javascript',
|
|
53
|
-
'.css': 'text/css',
|
|
54
|
-
'.json': 'application/json',
|
|
55
|
-
'.png': 'image/png',
|
|
56
|
-
'.jpg': 'image/jpeg',
|
|
57
|
-
'.svg': 'image/svg+xml',
|
|
58
|
-
}[ext] || 'application/octet-stream';
|
|
59
|
-
|
|
60
|
-
res.writeHead(200, {
|
|
61
|
-
'Content-Type': mime,
|
|
62
|
-
'Content-Length': stat.size,
|
|
63
|
-
});
|
|
64
|
-
fs.createReadStream(filePath).pipe(res);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
export function serveDocs(opts = {}) {
|
|
68
|
-
const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
|
|
69
|
-
const port = parseInt(opts.port, 10) || 3000;
|
|
70
|
-
const host = opts.host || '127.0.0.1';
|
|
71
|
-
|
|
72
|
-
if (!fs.existsSync(dbPath)) {
|
|
73
|
-
throw new Error(`Database not found: ${dbPath}. Run "jsn docs sync" first.`);
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
const db = new Database(dbPath, { readonly: true });
|
|
77
|
-
const hasEmb = hasEmbeddings(db);
|
|
78
|
-
const hrrDim = (() => {
|
|
79
|
-
try {
|
|
80
|
-
const row = db.prepare("SELECT value FROM meta WHERE key='hrr_dim'").get();
|
|
81
|
-
return row ? parseInt(row.value, 10) : DEFAULT_DIM;
|
|
82
|
-
} catch {
|
|
83
|
-
return DEFAULT_DIM;
|
|
84
|
-
}
|
|
85
|
-
})();
|
|
86
|
-
|
|
87
|
-
const server = http.createServer((req, res) => {
|
|
88
|
-
try {
|
|
89
|
-
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
|
|
90
|
-
const pathname = decodeURIComponent(url.pathname);
|
|
91
|
-
|
|
92
|
-
if (pathname === '/health') {
|
|
93
|
-
return sendJSON(res, 200, { ok: true });
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
if (pathname === '/stats') {
|
|
97
|
-
const total = db.prepare('SELECT COUNT(*) AS n FROM docs').get().n;
|
|
98
|
-
return sendJSON(res, 200, { documents: total, db: path.resolve(dbPath), embeddings: hasEmb, hrr_dim: hrrDim });
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
if (pathname === '/bundles') {
|
|
102
|
-
const rows = db
|
|
103
|
-
.prepare('SELECT bundle, COUNT(*) AS count FROM docs WHERE bundle IS NOT NULL GROUP BY bundle ORDER BY count DESC')
|
|
104
|
-
.all();
|
|
105
|
-
return sendJSON(res, 200, rows);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
if (pathname === '/search') {
|
|
109
|
-
const q = (url.searchParams.get('q') || '').trim();
|
|
110
|
-
if (!q) return sendJSON(res, 400, { error: "Missing query parameter 'q'." });
|
|
111
|
-
|
|
112
|
-
const limit = Math.min(parseInt(url.searchParams.get('limit'), 10) || 20, 100);
|
|
113
|
-
const offset = parseInt(url.searchParams.get('offset'), 10) || 0;
|
|
114
|
-
const bundle = url.searchParams.get('bundle') || null;
|
|
115
|
-
const docType = url.searchParams.get('doc_type') || null;
|
|
116
|
-
let mode = (url.searchParams.get('mode') || (hasEmb ? 'hybrid' : 'keyword')).toString();
|
|
117
|
-
if (mode === 'hybrid' && !hasEmb) mode = 'keyword';
|
|
118
|
-
|
|
119
|
-
const ftsQuery = sanitizeFts5Query(q);
|
|
120
|
-
if (!ftsQuery) {
|
|
121
|
-
return sendJSON(res, 200, { query: q, mode, count: 0, results: [] });
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
const filters = [];
|
|
125
|
-
const params = { q: ftsQuery, limit, offset };
|
|
126
|
-
if (bundle) {
|
|
127
|
-
filters.push('d.bundle = @bundle');
|
|
128
|
-
params.bundle = bundle;
|
|
129
|
-
}
|
|
130
|
-
if (docType) {
|
|
131
|
-
filters.push('d.doc_type = @docType');
|
|
132
|
-
params.docType = docType;
|
|
133
|
-
}
|
|
134
|
-
const where = filters.length ? ' AND ' + filters.join(' AND ') : '';
|
|
135
|
-
|
|
136
|
-
try {
|
|
137
|
-
if (mode === 'keyword') {
|
|
138
|
-
const rows = db
|
|
139
|
-
.prepare(
|
|
140
|
-
`SELECT d.id, d.path, d.title, d.bundle, d.doc_type, d.release,
|
|
141
|
-
json_extract(d.frontmatter, '$.canonical_url') AS canonical_url,
|
|
142
|
-
snippet(docs_fts, 1, '[', ']', ' … ', 12) AS snippet,
|
|
143
|
-
bm25(docs_fts) AS score
|
|
144
|
-
FROM docs_fts
|
|
145
|
-
JOIN docs d ON d.id = docs_fts.rowid
|
|
146
|
-
WHERE docs_fts MATCH @q${where}
|
|
147
|
-
ORDER BY score
|
|
148
|
-
LIMIT @limit OFFSET @offset`
|
|
149
|
-
)
|
|
150
|
-
.all(params);
|
|
151
|
-
return sendJSON(res, 200, { query: q, mode, count: rows.length, results: rows });
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
const candParams = { q: ftsQuery, cand: (limit + offset) * 4 + 20 };
|
|
155
|
-
if (bundle) candParams.bundle = bundle;
|
|
156
|
-
if (docType) candParams.docType = docType;
|
|
157
|
-
const candidates = db
|
|
158
|
-
.prepare(
|
|
159
|
-
`SELECT d.id, d.path, d.title, d.bundle, d.doc_type, d.release, d.hrr_vector,
|
|
160
|
-
json_extract(d.frontmatter, '$.canonical_url') AS canonical_url,
|
|
161
|
-
snippet(docs_fts, 1, '[', ']', ' … ', 12) AS snippet,
|
|
162
|
-
bm25(docs_fts) AS bm25
|
|
163
|
-
FROM docs_fts
|
|
164
|
-
JOIN docs d ON d.id = docs_fts.rowid
|
|
165
|
-
WHERE docs_fts MATCH @q${where}
|
|
166
|
-
ORDER BY bm25
|
|
167
|
-
LIMIT @cand`
|
|
168
|
-
)
|
|
169
|
-
.all(candParams);
|
|
170
|
-
|
|
171
|
-
if (candidates.length === 0) {
|
|
172
|
-
return sendJSON(res, 200, { query: q, mode, count: 0, results: [] });
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
const queryVec = encodeText(q, hrrDim);
|
|
176
|
-
const queryTokens = new Set(q.toLowerCase().split(/\s+/).filter(Boolean));
|
|
177
|
-
|
|
178
|
-
const bmVals = candidates.map((c) => c.bm25);
|
|
179
|
-
const bmMin = Math.min(...bmVals);
|
|
180
|
-
const bmMax = Math.max(...bmVals);
|
|
181
|
-
const bmRange = bmMax - bmMin || 1;
|
|
182
|
-
|
|
183
|
-
const FTS_W = 0.4, JACCARD_W = 0.3, HRR_W = 0.3;
|
|
184
|
-
|
|
185
|
-
for (const c of candidates) {
|
|
186
|
-
const ftsScore = 1 - (c.bm25 - bmMin) / bmRange;
|
|
187
|
-
const contentTokens = new Set(
|
|
188
|
-
`${c.title || ''} ${c.path || ''}`.toLowerCase().split(/\s+/).filter(Boolean)
|
|
189
|
-
);
|
|
190
|
-
let inter = 0;
|
|
191
|
-
for (const t of queryTokens) if (contentTokens.has(t)) inter++;
|
|
192
|
-
const union = queryTokens.size + contentTokens.size - inter;
|
|
193
|
-
const jaccard = union ? inter / union : 0;
|
|
194
|
-
|
|
195
|
-
let hrrSim = 0.5;
|
|
196
|
-
if (c.hrr_vector) {
|
|
197
|
-
hrrSim = (similarity(queryVec, bytesToPhases(c.hrr_vector)) + 1) / 2;
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
c.score = FTS_W * ftsScore + JACCARD_W * jaccard + HRR_W * hrrSim;
|
|
201
|
-
delete c.hrr_vector;
|
|
202
|
-
delete c.bm25;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
candidates.sort((a, b) => b.score - a.score);
|
|
206
|
-
const results = candidates.slice(offset, offset + limit);
|
|
207
|
-
return sendJSON(res, 200, { query: q, mode, count: results.length, results });
|
|
208
|
-
} catch (err) {
|
|
209
|
-
return sendJSON(res, 400, { error: `Invalid FTS query: ${err.message}` });
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
|
|
213
|
-
if (pathname.startsWith('/doc/')) {
|
|
214
|
-
const id = pathname.slice(5);
|
|
215
|
-
if (!id) return sendJSON(res, 400, { error: "Missing 'id'." });
|
|
216
|
-
const row = db.prepare('SELECT * FROM docs WHERE id = ?').get(id);
|
|
217
|
-
if (!row) return sendJSON(res, 404, { error: 'Not found' });
|
|
218
|
-
row.frontmatter = safeParse(row.frontmatter);
|
|
219
|
-
return sendJSON(res, 200, row);
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
if (pathname === '/doc') {
|
|
223
|
-
const p = url.searchParams.get('path') || '';
|
|
224
|
-
if (!p) return sendJSON(res, 400, { error: "Missing 'path'." });
|
|
225
|
-
const row = db.prepare('SELECT * FROM docs WHERE path = ?').get(p);
|
|
226
|
-
if (!row) return sendJSON(res, 404, { error: 'Not found' });
|
|
227
|
-
row.frontmatter = safeParse(row.frontmatter);
|
|
228
|
-
return sendJSON(res, 200, row);
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
// Static files.
|
|
232
|
-
let filePath = path.join(PUBLIC_DIR, pathname === '/' ? 'index.html' : pathname);
|
|
233
|
-
// Security: prevent escaping public dir.
|
|
234
|
-
filePath = path.resolve(filePath);
|
|
235
|
-
const publicResolved = path.resolve(PUBLIC_DIR);
|
|
236
|
-
if (!filePath.startsWith(publicResolved + path.sep) && filePath !== publicResolved) {
|
|
237
|
-
return sendText(res, 403, 'Forbidden');
|
|
238
|
-
}
|
|
239
|
-
return serveStatic(req, res, filePath);
|
|
240
|
-
} catch (err) {
|
|
241
|
-
sendJSON(res, 500, { error: err.message });
|
|
242
|
-
}
|
|
243
|
-
});
|
|
244
|
-
|
|
245
|
-
server.once('close', () => closeDocsDb(db));
|
|
246
|
-
|
|
247
|
-
return new Promise((resolve, reject) => {
|
|
248
|
-
let currentPort = parseInt(port, 10);
|
|
249
|
-
const maxAttempts = 10;
|
|
250
|
-
let attempts = 0;
|
|
251
|
-
let resolved = false;
|
|
252
|
-
|
|
253
|
-
function onListening() {
|
|
254
|
-
if (resolved) return;
|
|
255
|
-
resolved = true;
|
|
256
|
-
server.removeListener('error', onError);
|
|
257
|
-
process.stderr.write(`ServiceNow docs search for ${opts.release || 'default'} listening on http://${host}:${currentPort}\n`);
|
|
258
|
-
resolve({ server, port: currentPort, host, dbPath });
|
|
259
|
-
}
|
|
260
|
-
|
|
261
|
-
function onError(err) {
|
|
262
|
-
if (resolved) return;
|
|
263
|
-
server.removeListener('listening', onListening);
|
|
264
|
-
if (err.code === 'EADDRINUSE' && attempts < maxAttempts) {
|
|
265
|
-
process.stderr.write(`Port ${currentPort} in use, trying ${currentPort + 1}...\n`);
|
|
266
|
-
currentPort++;
|
|
267
|
-
tryListen();
|
|
268
|
-
return;
|
|
269
|
-
}
|
|
270
|
-
if (err.code === 'EADDRINUSE') {
|
|
271
|
-
err.message = `Could not find an open port between ${port} and ${currentPort}. Try specifying one with --port.`;
|
|
272
|
-
}
|
|
273
|
-
resolved = true;
|
|
274
|
-
closeDocsDb(db);
|
|
275
|
-
reject(err);
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
function tryListen() {
|
|
279
|
-
attempts++;
|
|
280
|
-
server.once('error', onError);
|
|
281
|
-
server.once('listening', onListening);
|
|
282
|
-
server.listen(currentPort, host);
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
tryListen();
|
|
286
|
-
});
|
|
287
|
-
}
|
package/src/commands/history.js
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
import { declareCapabilities } from '../capabilities.js';
|
|
2
|
-
import { listHistory, pruneHistory } from '../mutation-history.js';
|
|
3
|
-
|
|
4
|
-
export function historyCmd(wrap) {
|
|
5
|
-
declareCapabilities('history', { noInstance: true, skipDailyChecks: true });
|
|
6
|
-
const list = wrap(async (argv, app) => {
|
|
7
|
-
const entries = listHistory({ ...argv, instance: argv['instance-url'], profile: argv['profile-name'] });
|
|
8
|
-
app.ok({ entries, retentionDays: 7, _formatted: renderHistory(entries, { details: argv.details }) });
|
|
9
|
-
});
|
|
10
|
-
const filters = b => b
|
|
11
|
-
.option('details', { type: 'boolean', default: false, describe: 'Show full record IDs, instance URLs and reasons' })
|
|
12
|
-
.option('since', { type: 'string', describe: 'Earliest ISO timestamp' })
|
|
13
|
-
.option('until', { type: 'string', describe: 'Latest ISO timestamp' })
|
|
14
|
-
.option('instance-url', { type: 'string', describe: 'Filter by instance origin' })
|
|
15
|
-
.option('profile-name', { type: 'string', describe: 'Filter by recorded profile name (including removed profiles)' })
|
|
16
|
-
.option('table', { type: 'string', describe: 'Filter by table' })
|
|
17
|
-
.option('operation', { choices: ['create', 'update', 'delete'], type: 'string' })
|
|
18
|
-
.option('record', { type: 'string', describe: 'Filter by full resolved sys_id' })
|
|
19
|
-
.option('limit', { type: 'number', default: 50, describe: 'Maximum entries (1–10000)' });
|
|
20
|
-
return { command: 'history [subcommand]', describe: 'Local seven-day mutation history (not a durable ServiceNow audit)',
|
|
21
|
-
builder: y => filters(y).command({ command: 'list', describe: 'List local mutations', builder: filters, handler: list })
|
|
22
|
-
.command({ command: 'prune', describe: 'Remove expired entries only', handler: wrap(async (_argv, app) => {
|
|
23
|
-
app.ok({ ...pruneHistory(), _formatted: 'Expired local history removed; seven days retained.' });
|
|
24
|
-
}) }), handler: list };
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export function renderHistory(entries, { details = false, timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone } = {}) {
|
|
28
|
-
if (!entries.length) return 'No local mutations in the last seven days.';
|
|
29
|
-
const date = new Intl.DateTimeFormat('en-GB', { timeZone, month: 'short', day: '2-digit',
|
|
30
|
-
hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
|
|
31
|
-
// Strip terminal control characters from stored identifiers and labels.
|
|
32
|
-
// eslint-disable-next-line no-control-regex
|
|
33
|
-
const clean = value => String(value ?? '').replace(/[\x00-\x1f\x7f]/g, ' ');
|
|
34
|
-
const clip = (value, length) => value.length > length ? `${value.slice(0, length - 1)}…` : value;
|
|
35
|
-
const rows = entries.map(entry => {
|
|
36
|
-
let connection = entry.profile;
|
|
37
|
-
if (!connection) {
|
|
38
|
-
try { connection = new URL(entry.instance).host; } catch { connection = entry.instance; }
|
|
39
|
-
}
|
|
40
|
-
return [date.format(new Date(entry.timestamp)), entry.operation, clip(clean(entry.table), 22),
|
|
41
|
-
clip(clean(entry.sys_id || '(unknown)'), 12), entry.outcome, clip(clean(connection), 22)];
|
|
42
|
-
});
|
|
43
|
-
const headers = ['WHEN', 'ACTION', 'TABLE', 'RECORD', 'RESULT', 'CONNECTION'];
|
|
44
|
-
const widths = headers.map((header, i) => Math.max(header.length, ...rows.map(row => row[i].length)));
|
|
45
|
-
const format = row => row.map((cell, i) => cell.padEnd(widths[i])).join(' ').trimEnd();
|
|
46
|
-
const lines = [`Recent mutations · ${timeZone}`, '', format(headers)];
|
|
47
|
-
rows.forEach((row, i) => {
|
|
48
|
-
lines.push(format(row));
|
|
49
|
-
if (details) {
|
|
50
|
-
const entry = entries[i];
|
|
51
|
-
lines.push(` ${clean(entry.timestamp)} · ${clean(entry.table)}/${clean(entry.sys_id || '(unknown)')}`,
|
|
52
|
-
` ${clean(entry.instance)}${entry.reason ? ` · ${clean(entry.reason)}` : ''}`);
|
|
53
|
-
}
|
|
54
|
-
});
|
|
55
|
-
if (!details) lines.push('', 'Use --details for full IDs, URLs and reasons; --json for structured history.');
|
|
56
|
-
return lines.join('\n');
|
|
57
|
-
}
|
package/src/mutation-history.js
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
// Local convenience history, independent of documentation indexes and sync.
|
|
2
|
-
import Database from 'better-sqlite3';
|
|
3
|
-
import fs from 'node:fs';
|
|
4
|
-
import os from 'node:os';
|
|
5
|
-
import path from 'node:path';
|
|
6
|
-
import { errUsage } from './errors.js';
|
|
7
|
-
|
|
8
|
-
export const RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
9
|
-
const operations = ['create', 'update', 'delete'];
|
|
10
|
-
const outcomes = ['succeeded', 'failed', 'unknown'];
|
|
11
|
-
export function historyPath() {
|
|
12
|
-
return path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'history.db');
|
|
13
|
-
}
|
|
14
|
-
function openHistory(filename, now) {
|
|
15
|
-
fs.mkdirSync(path.dirname(filename), { recursive: true, mode: 0o700 });
|
|
16
|
-
const db = new Database(filename);
|
|
17
|
-
try {
|
|
18
|
-
if (process.platform !== 'win32') fs.chmodSync(filename, 0o600);
|
|
19
|
-
db.pragma('busy_timeout = 3000');
|
|
20
|
-
db.exec(`CREATE TABLE IF NOT EXISTS mutation_history (
|
|
21
|
-
id INTEGER PRIMARY KEY, timestamp INTEGER NOT NULL, instance TEXT NOT NULL,
|
|
22
|
-
profile TEXT, table_name TEXT NOT NULL, sys_id TEXT, operation TEXT NOT NULL,
|
|
23
|
-
outcome TEXT NOT NULL, reason TEXT, http_status INTEGER
|
|
24
|
-
); CREATE INDEX IF NOT EXISTS mutation_history_time ON mutation_history(timestamp)`);
|
|
25
|
-
db.prepare('DELETE FROM mutation_history WHERE timestamp < ?').run(now - RETENTION_MS);
|
|
26
|
-
return db;
|
|
27
|
-
} catch (error) { db.close(); throw error; }
|
|
28
|
-
}
|
|
29
|
-
export function sanitizeReason(value) {
|
|
30
|
-
if (!value) return null;
|
|
31
|
-
// eslint-disable-next-line no-control-regex -- strip controls from user-supplied prose
|
|
32
|
-
return String(value).replace(/[\u0000-\u001f\u007f]/g, ' ')
|
|
33
|
-
.replace(/\b(?:Bearer|Basic)\s+\S+/gi, '[redacted]')
|
|
34
|
-
.replace(/\b(password|token|cookie|secret|authorization|access_token|sysparm_ck)\s*[:=]\s*(?:"[^"]*"|'[^']*'|\S+)/gi, '$1=[redacted]')
|
|
35
|
-
.slice(0, 1000);
|
|
36
|
-
}
|
|
37
|
-
export function appendMutation(event, { filename = historyPath(), now = Date.now() } = {}) {
|
|
38
|
-
if (!operations.includes(event.operation) || !outcomes.includes(event.outcome)) throw errUsage('Invalid history event');
|
|
39
|
-
const instance = new URL(event.instance).origin;
|
|
40
|
-
// Deliberate whitelist: never serialize SDK options, response bodies, or payloads.
|
|
41
|
-
const row = { timestamp: now, instance, profile: event.profile || null,
|
|
42
|
-
table_name: event.table, sys_id: event.sys_id || null, operation: event.operation,
|
|
43
|
-
outcome: event.outcome, reason: sanitizeReason(event.reason), http_status: event.http_status || null };
|
|
44
|
-
const db = openHistory(filename, now);
|
|
45
|
-
try {
|
|
46
|
-
db.prepare(`INSERT INTO mutation_history
|
|
47
|
-
(timestamp,instance,profile,table_name,sys_id,operation,outcome,reason,http_status)
|
|
48
|
-
VALUES (@timestamp,@instance,@profile,@table_name,@sys_id,@operation,@outcome,@reason,@http_status)`).run(row);
|
|
49
|
-
} finally { db.close(); }
|
|
50
|
-
}
|
|
51
|
-
export function pruneHistory({ filename = historyPath(), now = Date.now() } = {}) {
|
|
52
|
-
const db = openHistory(filename, now);
|
|
53
|
-
try { return { retentionDays: 7 }; } finally { db.close(); }
|
|
54
|
-
}
|
|
55
|
-
export function listHistory(filters = {}, { filename = historyPath(), now = Date.now() } = {}) {
|
|
56
|
-
const where = [], values = [];
|
|
57
|
-
for (const [key, column] of Object.entries({ instance: 'instance', profile: 'profile', table: 'table_name', operation: 'operation', record: 'sys_id' })) {
|
|
58
|
-
if (filters[key]) { where.push(`${column} = ?`); values.push(key === 'instance' ? new URL(filters[key]).origin : filters[key]); }
|
|
59
|
-
}
|
|
60
|
-
for (const [key, operator] of [['since', '>='], ['until', '<=']]) {
|
|
61
|
-
if (filters[key]) {
|
|
62
|
-
const time = Date.parse(filters[key]);
|
|
63
|
-
if (!Number.isFinite(time)) throw errUsage(`Invalid --${key} timestamp; use an ISO date`);
|
|
64
|
-
where.push(`timestamp ${operator} ?`); values.push(time);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
const limit = filters.limit ?? 50;
|
|
68
|
-
if (!Number.isInteger(limit) || limit < 1 || limit > 10000) throw errUsage('--limit must be an integer from 1 to 10000');
|
|
69
|
-
const db = openHistory(filename, now);
|
|
70
|
-
try {
|
|
71
|
-
return db.prepare(`SELECT id,timestamp,instance,profile,table_name AS "table",sys_id,operation,outcome,reason,http_status
|
|
72
|
-
FROM mutation_history ${where.length ? `WHERE ${where.join(' AND ')}` : ''} ORDER BY timestamp DESC,id DESC LIMIT ?`)
|
|
73
|
-
.all(...values, limit).map(row => ({ ...row, timestamp: new Date(row.timestamp).toISOString() }));
|
|
74
|
-
} finally { db.close(); }
|
|
75
|
-
}
|