@jacebenson/jsn 4.5.0 → 4.5.1-dev.118.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 +33 -3
- package/package.json +3 -3
- package/skills/servicenow/SKILL.md +3 -0
- package/src/cli-adapter.js +15 -7
- package/src/commands/auth.js +6 -4
- package/src/commands/docs/client.js +77 -0
- package/src/commands/docs/db.js +0 -1
- package/src/commands/docs/docs.js +72 -288
- package/src/commands/docs/fts.js +117 -0
- package/src/commands/docs/index-worker.js +15 -0
- package/src/commands/docs/index.js +81 -0
- package/src/commands/docs/local.js +68 -0
- package/src/commands/docs/search.js +15 -6
- package/src/commands/docs/serve.js +8 -2
- package/src/commands/docs/server.js +60 -0
- package/src/commands/docs/sync-service.js +126 -0
- package/src/commands/setup.js +36 -26
- package/src/config.js +9 -0
- package/src/setup-preferences.js +57 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { fork } from 'node:child_process';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
|
+
import { AppError } from '../../errors.js';
|
|
7
|
+
import { configuredDocsService, docsServiceUrl } from './client.js';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
|
|
10
|
+
function storageDirectory() { return path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'docs-service'); }
|
|
11
|
+
async function healthy(state) {
|
|
12
|
+
try {
|
|
13
|
+
const url = new URL(state.url);
|
|
14
|
+
if (url.hostname !== '127.0.0.1' || url.protocol !== 'http:') return false;
|
|
15
|
+
process.kill(state.pid, 0);
|
|
16
|
+
const response = await fetch(new URL('up', url), { signal: AbortSignal.timeout(1000) });
|
|
17
|
+
return response.ok && (await response.json()).service === 'jsn-docs';
|
|
18
|
+
} catch { return false; }
|
|
19
|
+
}
|
|
20
|
+
export async function ensureLocalDocumentation({ storage = storageDirectory() } = {}) {
|
|
21
|
+
fs.mkdirSync(storage, { recursive: true, mode: 0o700 });
|
|
22
|
+
const stateFile = path.join(storage, 'server.json'), lock = path.join(storage, 'server-start.lock');
|
|
23
|
+
const state = () => { try { return JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch { return {}; } };
|
|
24
|
+
if (await healthy(state())) return state();
|
|
25
|
+
let acquired = false;
|
|
26
|
+
for (let attempt = 0; attempt < 100 && !acquired; attempt++) {
|
|
27
|
+
try { fs.mkdirSync(lock); fs.writeFileSync(path.join(lock, 'pid'), String(process.pid)); acquired = true; }
|
|
28
|
+
catch (error) {
|
|
29
|
+
if (error.code !== 'EEXIST') throw error;
|
|
30
|
+
if (await healthy(state())) return state();
|
|
31
|
+
try {
|
|
32
|
+
const pid = Number(fs.readFileSync(path.join(lock, 'pid'), 'utf8'));
|
|
33
|
+
if (pid) process.kill(pid, 0);
|
|
34
|
+
else if (Date.now() - fs.statSync(lock).mtimeMs > 30_000) fs.rmSync(lock, { recursive: true, force: true });
|
|
35
|
+
} catch (probe) { if (probe.code === 'ESRCH') fs.rmSync(lock, { recursive: true, force: true }); }
|
|
36
|
+
await delay(100);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
if (!acquired) throw new AppError('network_error', 'The local documentation service is still starting. Try again shortly.');
|
|
40
|
+
let child;
|
|
41
|
+
try {
|
|
42
|
+
if (await healthy(state())) return state();
|
|
43
|
+
const log = fs.openSync(path.join(storage, 'server.log'), 'a', 0o600);
|
|
44
|
+
try {
|
|
45
|
+
child = fork(fileURLToPath(new URL('./server.js', import.meta.url)), [], { detached: true, execArgv: [],
|
|
46
|
+
env: { ...process.env, DOCS_STORAGE_DIR: storage, JSN_DOCS_HOST: '127.0.0.1', JSN_DOCS_PORT: '0' }, stdio: ['ignore', log, log, 'ipc'] });
|
|
47
|
+
} finally { fs.closeSync(log); }
|
|
48
|
+
const next = await new Promise((resolve, reject) => {
|
|
49
|
+
const timer = setTimeout(() => { child.kill(); reject(new Error('Timed out starting the documentation server.')); }, 10_000);
|
|
50
|
+
child.once('message', message => { clearTimeout(timer); resolve(message); });
|
|
51
|
+
child.once('error', error => { clearTimeout(timer); reject(error); });
|
|
52
|
+
child.once('exit', () => { clearTimeout(timer); reject(new Error('The documentation server stopped before it was ready.')); });
|
|
53
|
+
});
|
|
54
|
+
if (!await healthy(next)) throw new Error('Local documentation server did not become healthy.');
|
|
55
|
+
fs.writeFileSync(stateFile + '.tmp', JSON.stringify(next) + '\n', { mode: 0o600 });
|
|
56
|
+
fs.renameSync(stateFile + '.tmp', stateFile);
|
|
57
|
+
child.unref();
|
|
58
|
+
return next;
|
|
59
|
+
} catch (error) {
|
|
60
|
+
child?.kill();
|
|
61
|
+
throw new AppError('network_error', 'Could not start the local documentation service.', error.message);
|
|
62
|
+
} finally { fs.rmSync(lock, { recursive: true, force: true }); }
|
|
63
|
+
}
|
|
64
|
+
export async function documentationService(config = {}) {
|
|
65
|
+
if (process.env.JSN_DOCS_URL) return docsServiceUrl(process.env.JSN_DOCS_URL);
|
|
66
|
+
if (config.docs?.source === 'local') return (await ensureLocalDocumentation()).url;
|
|
67
|
+
return configuredDocsService(config);
|
|
68
|
+
}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
import fs from 'node:fs';
|
|
4
4
|
import { getDocsDbPath, hasEmbeddings, openDocsDb, closeDocsDb, withDocsDb, getMeta } from './db.js';
|
|
5
|
+
import { sanitizeFts5Query } from './fts.js';
|
|
5
6
|
import { encodeText, similarity, bytesToPhases, DEFAULT_DIM } from './hrr.js';
|
|
6
7
|
|
|
7
8
|
function safeParse(s) {
|
|
@@ -28,9 +29,12 @@ export function getDocByIdOrPath(idOrPath, opts = {}) {
|
|
|
28
29
|
} else {
|
|
29
30
|
row = db.prepare('SELECT * FROM docs WHERE path LIKE ?').get(`%${idOrPath}%`);
|
|
30
31
|
if (!row) {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
const ftsQuery = sanitizeFts5Query(idOrPath);
|
|
33
|
+
if (ftsQuery) {
|
|
34
|
+
row = db.prepare(
|
|
35
|
+
`SELECT d.* FROM docs_fts JOIN docs d ON d.id = docs_fts.rowid WHERE docs_fts MATCH ? LIMIT 1`
|
|
36
|
+
).get(ftsQuery);
|
|
37
|
+
}
|
|
34
38
|
}
|
|
35
39
|
}
|
|
36
40
|
return row;
|
|
@@ -58,8 +62,13 @@ export function searchDocs(opts = {}) {
|
|
|
58
62
|
const mode = opts.mode === 'keyword' ? 'keyword' : 'hybrid';
|
|
59
63
|
const useHybrid = mode === 'hybrid' && hasEmbeddings(db);
|
|
60
64
|
|
|
65
|
+
const ftsQuery = sanitizeFts5Query(q);
|
|
66
|
+
if (!ftsQuery) {
|
|
67
|
+
return { query: q, mode: useHybrid ? 'hybrid' : 'keyword', total: 0, count: 0, results: [] };
|
|
68
|
+
}
|
|
69
|
+
|
|
61
70
|
const filters = [];
|
|
62
|
-
const params = { q, limit, offset };
|
|
71
|
+
const params = { q: ftsQuery, limit, offset };
|
|
63
72
|
if (bundle) {
|
|
64
73
|
filters.push('d.bundle = @bundle');
|
|
65
74
|
params.bundle = bundle;
|
|
@@ -73,7 +82,7 @@ export function searchDocs(opts = {}) {
|
|
|
73
82
|
// Total matching docs (for pagination)
|
|
74
83
|
const total = db
|
|
75
84
|
.prepare(`SELECT COUNT(*) AS n FROM docs_fts JOIN docs d ON d.id = docs_fts.rowid WHERE docs_fts MATCH @q${where}`)
|
|
76
|
-
.get({ q, ...(bundle && { bundle }), ...(docType && { docType }) }).n;
|
|
85
|
+
.get({ q: ftsQuery, ...(bundle && { bundle }), ...(docType && { docType }) }).n;
|
|
77
86
|
|
|
78
87
|
let rows;
|
|
79
88
|
if (!useHybrid) {
|
|
@@ -91,7 +100,7 @@ export function searchDocs(opts = {}) {
|
|
|
91
100
|
)
|
|
92
101
|
.all(params);
|
|
93
102
|
} else {
|
|
94
|
-
const candParams = { q, cand: (limit + offset) * 4 + 20 };
|
|
103
|
+
const candParams = { q: ftsQuery, cand: (limit + offset) * 4 + 20 };
|
|
95
104
|
if (bundle) candParams.bundle = bundle;
|
|
96
105
|
if (docType) candParams.docType = docType;
|
|
97
106
|
const candidates = db
|
|
@@ -6,6 +6,7 @@ import http from 'node:http';
|
|
|
6
6
|
import { URL } from 'node:url';
|
|
7
7
|
import Database from 'better-sqlite3';
|
|
8
8
|
import { getDocsDbPath, hasEmbeddings, closeDocsDb } from './db.js';
|
|
9
|
+
import { sanitizeFts5Query } from './fts.js';
|
|
9
10
|
import { encodeText, similarity, bytesToPhases, DEFAULT_DIM } from './hrr.js';
|
|
10
11
|
|
|
11
12
|
const PUBLIC_DIR = path.join(import.meta.dirname, 'public');
|
|
@@ -115,8 +116,13 @@ export function serveDocs(opts = {}) {
|
|
|
115
116
|
let mode = (url.searchParams.get('mode') || (hasEmb ? 'hybrid' : 'keyword')).toString();
|
|
116
117
|
if (mode === 'hybrid' && !hasEmb) mode = 'keyword';
|
|
117
118
|
|
|
119
|
+
const ftsQuery = sanitizeFts5Query(q);
|
|
120
|
+
if (!ftsQuery) {
|
|
121
|
+
return sendJSON(res, 200, { query: q, mode, count: 0, results: [] });
|
|
122
|
+
}
|
|
123
|
+
|
|
118
124
|
const filters = [];
|
|
119
|
-
const params = { q, limit, offset };
|
|
125
|
+
const params = { q: ftsQuery, limit, offset };
|
|
120
126
|
if (bundle) {
|
|
121
127
|
filters.push('d.bundle = @bundle');
|
|
122
128
|
params.bundle = bundle;
|
|
@@ -145,7 +151,7 @@ export function serveDocs(opts = {}) {
|
|
|
145
151
|
return sendJSON(res, 200, { query: q, mode, count: rows.length, results: rows });
|
|
146
152
|
}
|
|
147
153
|
|
|
148
|
-
const candParams = { q, cand: (limit + offset) * 4 + 20 };
|
|
154
|
+
const candParams = { q: ftsQuery, cand: (limit + offset) * 4 + 20 };
|
|
149
155
|
if (bundle) candParams.bundle = bundle;
|
|
150
156
|
if (docType) candParams.docType = docType;
|
|
151
157
|
const candidates = db
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import { fork } from 'node:child_process';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { DocumentationIndex, documentationStatus } from './index.js';
|
|
8
|
+
|
|
9
|
+
export function serviceStorage() { return process.env.DOCS_STORAGE_DIR || path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'docs-service'); }
|
|
10
|
+
export async function startDocumentationServer({ storage = serviceStorage(), host = '127.0.0.1', port = 0, refresh = true } = {}) {
|
|
11
|
+
fs.mkdirSync(storage, { recursive: true });
|
|
12
|
+
let worker;
|
|
13
|
+
const server = http.createServer((req, res) => {
|
|
14
|
+
const send = (status, value) => { res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' }); res.end(JSON.stringify(value)); };
|
|
15
|
+
if (req.method !== 'GET') return send(405, { error: 'Use GET.' });
|
|
16
|
+
let index;
|
|
17
|
+
try {
|
|
18
|
+
const url = new URL(req.url, 'http://localhost');
|
|
19
|
+
if (url.pathname === '/up') return send(200, { service: 'jsn-docs' });
|
|
20
|
+
if (url.pathname === '/api/docs/status') return send(200, documentationStatus(storage));
|
|
21
|
+
if (!['/api/docs/search', '/api/docs/document'].includes(url.pathname) && !/^\/api\/docs\/\d{1,18}$/.test(url.pathname)) return send(404, { error: 'Not found.' });
|
|
22
|
+
index = new DocumentationIndex(storage);
|
|
23
|
+
const params = Object.fromEntries(url.searchParams);
|
|
24
|
+
if (url.pathname === '/api/docs/search') return send(200, index.search({ query: params.q, limit: params.limit ?? 20, offset: params.offset ?? 0, bundle: params.bundle }));
|
|
25
|
+
const revision = index.revision();
|
|
26
|
+
if (params.revision && params.revision !== revision) return send(409, { error: 'Documentation has changed. Search again or retrieve by exact path.' });
|
|
27
|
+
return send(200, { revision, document: index.document({ path: params.path, id: url.pathname.split('/').at(-1) }) });
|
|
28
|
+
} catch (error) { send(error.status || 503, { error: error.status ? error.message : 'Documentation search is temporarily unavailable.' }); }
|
|
29
|
+
finally { index?.close(); }
|
|
30
|
+
});
|
|
31
|
+
function checkForUpdates() {
|
|
32
|
+
if (worker) return;
|
|
33
|
+
const status = documentationStatus(storage);
|
|
34
|
+
const elapsed = Date.now() - Date.parse(status.checkedAt || 0);
|
|
35
|
+
if (elapsed < (status.state === 'ready' ? 24 : 1) * 3600_000) return;
|
|
36
|
+
const log = fs.openSync(path.join(storage, 'sync.log'), 'a', 0o600);
|
|
37
|
+
try {
|
|
38
|
+
worker = fork(fileURLToPath(new URL('./sync-service.js', import.meta.url)), [], {
|
|
39
|
+
env: { ...process.env, DOCS_STORAGE_DIR: storage }, stdio: ['ignore', log, log, 'ipc'], execArgv: [],
|
|
40
|
+
});
|
|
41
|
+
worker.on('exit', () => { worker = null; });
|
|
42
|
+
worker.on('error', () => { worker = null; });
|
|
43
|
+
} finally { fs.closeSync(log); }
|
|
44
|
+
}
|
|
45
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, resolve); });
|
|
46
|
+
const interval = refresh ? setInterval(checkForUpdates, 60_000) : null;
|
|
47
|
+
interval?.unref();
|
|
48
|
+
if (refresh) checkForUpdates();
|
|
49
|
+
server.on('close', () => { clearInterval(interval); worker?.kill('SIGTERM'); });
|
|
50
|
+
const address = server.address();
|
|
51
|
+
return { server, url: `http://${host.includes(':') ? `[${host}]` : host}:${address.port}/` };
|
|
52
|
+
}
|
|
53
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
54
|
+
try {
|
|
55
|
+
const { server, url } = await startDocumentationServer({ host: process.env.JSN_DOCS_HOST || '127.0.0.1', port: Number(process.env.JSN_DOCS_PORT || 0) });
|
|
56
|
+
if (process.send) { process.send({ url, pid: process.pid }); process.disconnect(); }
|
|
57
|
+
else process.stdout.write(`Documentation service listening at ${url}\n`);
|
|
58
|
+
for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => { server.close(); });
|
|
59
|
+
} catch (error) { process.stderr.write(error.message + '\n'); process.exitCode = 1; }
|
|
60
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// Server-owned GitHub mirror and atomic FTS5 publication. Reuses the CLI ingester.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import os from 'node:os';
|
|
7
|
+
import { spawnSync } from 'node:child_process';
|
|
8
|
+
import Database from 'better-sqlite3';
|
|
9
|
+
import { ingestDocs } from './ingest.js';
|
|
10
|
+
import { refreshDocs } from './refresh.js';
|
|
11
|
+
|
|
12
|
+
const defaultStorage = path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'docs-service');
|
|
13
|
+
function git(args) {
|
|
14
|
+
const result = spawnSync('git', args, { encoding: 'utf8', maxBuffer: 4 * 1024 * 1024, timeout: 15 * 60 * 1000 });
|
|
15
|
+
if (result.status !== 0) throw new Error(`Git ${args[0]} failed: ${result.error?.message || result.stderr?.slice(-1000) || result.status}`);
|
|
16
|
+
return result.stdout.trim();
|
|
17
|
+
}
|
|
18
|
+
function writeStatus(storage, status) {
|
|
19
|
+
const temporary = path.join(storage, `status-${randomUUID()}.json`);
|
|
20
|
+
fs.writeFileSync(temporary, JSON.stringify(status, null, 2) + '\n');
|
|
21
|
+
fs.renameSync(temporary, path.join(storage, 'status.json'));
|
|
22
|
+
}
|
|
23
|
+
async function performSync(options = {}) {
|
|
24
|
+
const storage = options.storage || process.env.DOCS_STORAGE_DIR || defaultStorage;
|
|
25
|
+
const source = options.source || process.env.DOCS_SOURCE_URL || 'https://github.com/ServiceNow/ServiceNowDocs.git';
|
|
26
|
+
const branch = options.branch || process.env.DOCS_SOURCE_BRANCH || 'australia';
|
|
27
|
+
fs.mkdirSync(storage, { recursive: true });
|
|
28
|
+
const repo = path.join(storage, 'source');
|
|
29
|
+
const live = path.join(storage, 'docs.sqlite3');
|
|
30
|
+
const staging = path.join(storage, `build-${randomUUID()}.sqlite3`);
|
|
31
|
+
let previous = {};
|
|
32
|
+
try { previous = JSON.parse(fs.readFileSync(path.join(storage, 'status.json'), 'utf8')); } catch { /* first run */ }
|
|
33
|
+
// The shared service lock excludes concurrent publishers.
|
|
34
|
+
for (const name of fs.readdirSync(storage)) {
|
|
35
|
+
if (/^(build|clone)-[a-f0-9-]+(?:\.sqlite3(?:-wal|-shm)?)?$/.test(name)) {
|
|
36
|
+
fs.rmSync(path.join(storage, name), { recursive: true, force: true });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const startedAt = new Date().toISOString();
|
|
40
|
+
writeStatus(storage, { ...previous, state: 'syncing', startedAt });
|
|
41
|
+
try {
|
|
42
|
+
if (!fs.existsSync(path.join(repo, '.git'))) {
|
|
43
|
+
const cloning = path.join(storage, `clone-${randomUUID()}`);
|
|
44
|
+
try {
|
|
45
|
+
git(['clone', '--depth', '1', '--branch', branch, '--', source, cloning]);
|
|
46
|
+
if (fs.existsSync(repo)) fs.rmSync(repo, { recursive: true, force: true });
|
|
47
|
+
fs.renameSync(cloning, repo);
|
|
48
|
+
} finally { fs.rmSync(cloning, { recursive: true, force: true }); }
|
|
49
|
+
} else {
|
|
50
|
+
// This clone is private to the service. Never operate on a developer's checkout.
|
|
51
|
+
git(['-C', repo, 'fetch', '--depth', '1', 'origin', branch]);
|
|
52
|
+
git(['-C', repo, 'reset', '--hard', 'FETCH_HEAD']);
|
|
53
|
+
}
|
|
54
|
+
const revision = git(['-C', repo, 'rev-parse', 'HEAD']);
|
|
55
|
+
const markdown = path.join(repo, 'markdown');
|
|
56
|
+
if (!fs.statSync(markdown).isDirectory()) throw new Error('Source has no markdown directory');
|
|
57
|
+
let oldRevision;
|
|
58
|
+
if (fs.existsSync(live)) {
|
|
59
|
+
const db = new Database(live, { readonly: true });
|
|
60
|
+
try {
|
|
61
|
+
oldRevision = db.prepare("SELECT value FROM meta WHERE key = 'source_revision'").get()?.value;
|
|
62
|
+
if (oldRevision !== revision || options.force) await db.backup(staging);
|
|
63
|
+
} finally { db.close(); }
|
|
64
|
+
}
|
|
65
|
+
if (oldRevision === revision && !options.force) {
|
|
66
|
+
const status = { ...previous, state: 'ready', revision, checkedAt: new Date().toISOString(), startedAt, error: null, changed: false };
|
|
67
|
+
writeStatus(storage, status);
|
|
68
|
+
return status;
|
|
69
|
+
}
|
|
70
|
+
const roots = [{ dir: markdown, prefix: '' }];
|
|
71
|
+
const result = fs.existsSync(staging)
|
|
72
|
+
? refreshDocs({ roots, dbPath: staging })
|
|
73
|
+
: ingestDocs({ roots, dbPath: staging, embed: false });
|
|
74
|
+
if (result.errors) throw new Error(`Indexing skipped ${result.errors} documents; retaining the published index`);
|
|
75
|
+
const db = new Database(staging);
|
|
76
|
+
let count;
|
|
77
|
+
try {
|
|
78
|
+
count = db.prepare('SELECT COUNT(*) AS n FROM docs').get().n;
|
|
79
|
+
if (!count) throw new Error('Refusing to publish an empty documentation index');
|
|
80
|
+
if (db.pragma('quick_check', { simple: true }) !== 'ok') throw new Error('SQLite integrity check failed');
|
|
81
|
+
db.exec("INSERT INTO docs_fts(docs_fts, rank) VALUES('integrity-check', 1)");
|
|
82
|
+
const set = db.prepare('INSERT OR REPLACE INTO meta(key, value) VALUES(?, ?)');
|
|
83
|
+
set.run('source_revision', revision);
|
|
84
|
+
set.run('source_branch', branch);
|
|
85
|
+
db.pragma('wal_checkpoint(TRUNCATE)');
|
|
86
|
+
db.pragma('journal_mode = DELETE');
|
|
87
|
+
} finally { db.close(); }
|
|
88
|
+
fs.renameSync(staging, live);
|
|
89
|
+
const status = { state: 'ready', revision, documents: count, startedAt, checkedAt: new Date().toISOString(), publishedAt: new Date().toISOString(), changed: true, error: null, result };
|
|
90
|
+
writeStatus(storage, status);
|
|
91
|
+
return status;
|
|
92
|
+
} catch (error) {
|
|
93
|
+
writeStatus(storage, { ...previous, state: 'failed', startedAt, checkedAt: new Date().toISOString(), error: error.message });
|
|
94
|
+
throw error;
|
|
95
|
+
} finally {
|
|
96
|
+
for (const suffix of ['', '-wal', '-shm']) fs.rmSync(staging + suffix, { force: true });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
export async function syncDocumentation(options = {}) {
|
|
100
|
+
const storage = options.storage || process.env.DOCS_STORAGE_DIR || defaultStorage;
|
|
101
|
+
fs.mkdirSync(storage, { recursive: true });
|
|
102
|
+
const lock = path.join(storage, 'sync-service.lock');
|
|
103
|
+
try { fs.mkdirSync(lock); }
|
|
104
|
+
catch (error) {
|
|
105
|
+
if (error.code !== 'EEXIST') throw error;
|
|
106
|
+
let pid;
|
|
107
|
+
try { pid = Number(fs.readFileSync(path.join(lock, 'pid'), 'utf8')); } catch { /* another process may be writing it */ }
|
|
108
|
+
if (!pid) {
|
|
109
|
+
if (Date.now() - fs.statSync(lock).mtimeMs < 30_000) return { state: 'syncing', changed: false };
|
|
110
|
+
fs.rmSync(lock, { recursive: true, force: true });
|
|
111
|
+
return syncDocumentation(options);
|
|
112
|
+
}
|
|
113
|
+
try { process.kill(pid, 0); return { state: 'syncing', changed: false }; }
|
|
114
|
+
catch (probe) { if (probe.code !== 'ESRCH') throw probe; }
|
|
115
|
+
fs.rmSync(lock, { recursive: true });
|
|
116
|
+
// Retry acquisition, so another waiting publisher still wins exclusively.
|
|
117
|
+
return syncDocumentation(options);
|
|
118
|
+
}
|
|
119
|
+
fs.writeFileSync(path.join(lock, 'pid'), String(process.pid));
|
|
120
|
+
try { return await performSync(options); }
|
|
121
|
+
finally { fs.rmSync(lock, { recursive: true, force: true }); }
|
|
122
|
+
}
|
|
123
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
124
|
+
try { process.stdout.write(JSON.stringify(await syncDocumentation()) + '\n'); }
|
|
125
|
+
catch (error) { process.stderr.write(error.message + '\n'); process.exitCode = 1; }
|
|
126
|
+
}
|
package/src/commands/setup.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { configureGlobalDefaults, configureDocumentation } from '../setup-preferences.js';
|
|
2
|
+
import { select } from '../prompts.js';
|
|
1
3
|
import { loginWizard, loginProfile, showAuthStatus, switchProfile, modifyProfile, logoutProfile, removeConnection } from './auth.js';
|
|
2
4
|
import { errUsageHint } from '../errors.js';
|
|
3
5
|
import { declareCapabilities } from '../capabilities.js';
|
|
@@ -7,14 +9,14 @@ import { declareCapabilities } from '../capabilities.js';
|
|
|
7
9
|
declareCapabilities('setup', { noInstance: true, skipContextHeader: true });
|
|
8
10
|
|
|
9
11
|
const HUB_CHOICES = [
|
|
10
|
-
{
|
|
11
|
-
{ name: '
|
|
12
|
-
{ name: '
|
|
13
|
-
{ name: '
|
|
14
|
-
{ name: 'Change settings', value: 'modify', command: 'jsn auth modify --profile <name> --read-only --confirm-deletes --no-include-counts' },
|
|
15
|
-
{
|
|
16
|
-
{ name: '
|
|
17
|
-
{ name: '
|
|
12
|
+
{ section: 'Connections', name: 'Check connections', value: 'status', command: 'jsn auth status --details --json (use --local to skip instance probes)' },
|
|
13
|
+
{ section: 'Connections', name: 'Choose default connection', value: 'switch', command: 'jsn auth switch <name>' },
|
|
14
|
+
{ section: 'Connections', name: 'Add a connection', value: 'add', command: 'jsn auth login <instance> --name <name> --basic' },
|
|
15
|
+
{ section: 'Connections', name: 'Sign in again', value: 'login', command: 'jsn auth login --profile <name> (with the authentication options below)' },
|
|
16
|
+
{ section: 'Connections', name: 'Change connection settings', value: 'modify', command: 'jsn auth modify --profile <name> --read-only --confirm-deletes --no-include-counts' },
|
|
17
|
+
{ section: 'JSN settings', name: 'Defaults and documentation', value: 'advanced', command: 'jsn setup' },
|
|
18
|
+
{ section: 'Cleanup', name: 'Sign out (keep connection)', value: 'logout', command: 'jsn auth logout --profile <name> --force (only after explicit approval)' },
|
|
19
|
+
{ section: 'Cleanup', name: 'Remove a connection', value: 'remove', command: 'jsn auth remove <name>' },
|
|
18
20
|
];
|
|
19
21
|
|
|
20
22
|
const setupHelp = () => [
|
|
@@ -60,17 +62,23 @@ export const authHubPrompt = async (...args) => {
|
|
|
60
62
|
const page = usePagination({
|
|
61
63
|
items: choices,
|
|
62
64
|
active,
|
|
63
|
-
|
|
65
|
+
// Pagination budgets terminal lines, including the section headings.
|
|
66
|
+
pageSize: choices.length + new Set(choices.map(choice => choice.section)).size * 2 - 1,
|
|
64
67
|
loop: false,
|
|
65
|
-
renderItem: ({ item, isActive }) =>
|
|
68
|
+
renderItem: ({ item, isActive }) => {
|
|
69
|
+
const index = choices.indexOf(item);
|
|
70
|
+
const heading = choices[index - 1]?.section !== item.section ? `${index ? '\n' : ''} ${item.section}\n` : '';
|
|
71
|
+
return `${heading}${isActive ? '❯' : ' '} ${item.name}`;
|
|
72
|
+
},
|
|
66
73
|
});
|
|
67
74
|
return `${config.message}\n${page}\n\n↑↓ navigate • ⏎ select • q/Esc exit`;
|
|
68
75
|
})(...args);
|
|
69
76
|
};
|
|
70
77
|
|
|
71
78
|
/** Interactive hub: what do you want to do? Returns an action or undefined on exit. */
|
|
72
|
-
export async function authHubMenu({ promptFn = authHubPrompt, input, output } = {}) {
|
|
73
|
-
|
|
79
|
+
export async function authHubMenu({ promptFn = authHubPrompt, input, output, hasProfiles = true } = {}) {
|
|
80
|
+
const choices = hasProfiles ? HUB_CHOICES : HUB_CHOICES.filter(choice => ['add', 'advanced'].includes(choice.value));
|
|
81
|
+
return promptFn({ message: 'What would you like to do?', choices }, { input, output });
|
|
74
82
|
}
|
|
75
83
|
|
|
76
84
|
/**
|
|
@@ -90,6 +98,15 @@ export async function dispatchSetupAction(app, argv, action) {
|
|
|
90
98
|
return logoutProfile(argv, app);
|
|
91
99
|
} else if (action === 'remove') {
|
|
92
100
|
return removeConnection(argv, app);
|
|
101
|
+
} else if (action === 'advanced') {
|
|
102
|
+
const setting = await select({ message: 'JSN settings', choices: [
|
|
103
|
+
{ name: 'Defaults for future connections', value: 'defaults' },
|
|
104
|
+
{ name: 'Documentation source', value: 'docs' },
|
|
105
|
+
{ name: 'Back', value: 'back' },
|
|
106
|
+
] });
|
|
107
|
+
if (setting === 'defaults') await configureGlobalDefaults(app.config, { documentation: false });
|
|
108
|
+
if (setting === 'docs') await configureDocumentation(app.config);
|
|
109
|
+
if (setting !== 'back') app.ok({ settings: setting }, { summary: 'Settings saved; existing connections unchanged' });
|
|
93
110
|
} else if (action === 'modify') {
|
|
94
111
|
return modifyProfile(app, argv);
|
|
95
112
|
}
|
|
@@ -101,7 +118,7 @@ export async function dispatchSetupAction(app, argv, action) {
|
|
|
101
118
|
export function setupCmd(wrap) {
|
|
102
119
|
return {
|
|
103
120
|
command: 'setup',
|
|
104
|
-
describe: 'Set up and manage
|
|
121
|
+
describe: 'Set up JSN defaults and manage ServiceNow connections (interactive)',
|
|
105
122
|
builder: y => y.option('docs-source', { type: 'string', choices: ['snapshot', 'github', 'skip'], describe: 'Install optional documentation directly without the authentication wizard' }).epilogue(setupHelp()),
|
|
106
123
|
handler: wrap(async (argv, app) => {
|
|
107
124
|
if (argv['docs-source']) {
|
|
@@ -114,25 +131,18 @@ export function setupCmd(wrap) {
|
|
|
114
131
|
throw errUsageHint('"jsn setup" is interactive. Use explicit auth commands instead.', setupHelp());
|
|
115
132
|
}
|
|
116
133
|
const profileNames = Object.keys(app.config.profiles || {});
|
|
117
|
-
|
|
134
|
+
const firstSetup = !app.config.connectionDefaults;
|
|
135
|
+
if (firstSetup) await configureGlobalDefaults(app.config);
|
|
136
|
+
else if (!app.config.docs) await configureDocumentation(app.config);
|
|
137
|
+
if (profileNames.length === 0 && firstSetup) {
|
|
118
138
|
const result = await loginWizard(app, argv);
|
|
119
139
|
await showAuthStatus({ ...argv, profile: result.profileName }, app);
|
|
120
|
-
const { docsDbExists } = await import('./docs/db.js');
|
|
121
|
-
if (!docsDbExists()) {
|
|
122
|
-
const { offerDocumentation } = await import('./docs/install.js');
|
|
123
|
-
app.ok(await offerDocumentation(app, argv));
|
|
124
|
-
}
|
|
125
140
|
return;
|
|
126
141
|
}
|
|
127
|
-
const action = await authHubMenu();
|
|
142
|
+
const action = await authHubMenu({ hasProfiles: profileNames.length > 0 });
|
|
128
143
|
if (action === undefined) return;
|
|
129
|
-
if (action === 'docs') {
|
|
130
|
-
const { offerDocumentation } = await import('./docs/install.js');
|
|
131
|
-
app.ok(await offerDocumentation(app, argv));
|
|
132
|
-
return;
|
|
133
|
-
}
|
|
134
144
|
const result = await dispatchSetupAction(app, argv, action);
|
|
135
|
-
if (
|
|
145
|
+
if (!['status', 'advanced'].includes(action)) await showAuthStatus({ ...argv, profile: result?.profile || result?.profileName }, app);
|
|
136
146
|
}),
|
|
137
147
|
};
|
|
138
148
|
}
|
package/src/config.js
CHANGED
|
@@ -46,6 +46,11 @@ function loadFromFile(cfg, filePath, source) {
|
|
|
46
46
|
try {
|
|
47
47
|
const data = fs.readFileSync(filePath, 'utf-8');
|
|
48
48
|
const fileCfg = JSON.parse(data);
|
|
49
|
+
// Installation-wide preferences are never taken from a project config.
|
|
50
|
+
if (source === 'global') {
|
|
51
|
+
if (fileCfg.connection_defaults && typeof fileCfg.connection_defaults === 'object') cfg.connectionDefaults = fileCfg.connection_defaults;
|
|
52
|
+
if (fileCfg.docs && typeof fileCfg.docs === 'object') cfg.docs = fileCfg.docs;
|
|
53
|
+
}
|
|
49
54
|
if (fileCfg.instance_url) {
|
|
50
55
|
cfg.instanceURL = fileCfg.instance_url;
|
|
51
56
|
cfg.sources.instance_url = source;
|
|
@@ -87,6 +92,8 @@ export function createConfig() {
|
|
|
87
92
|
activeProfile: '',
|
|
88
93
|
format: 'auto',
|
|
89
94
|
sources: {},
|
|
95
|
+
connectionDefaults: null,
|
|
96
|
+
docs: null,
|
|
90
97
|
};
|
|
91
98
|
}
|
|
92
99
|
|
|
@@ -120,6 +127,8 @@ export function saveConfig(cfg) {
|
|
|
120
127
|
const dir = globalConfigDir();
|
|
121
128
|
fs.mkdirSync(dir, { recursive: true, mode: 0o750 });
|
|
122
129
|
const payload = {
|
|
130
|
+
connection_defaults: cfg.connectionDefaults || undefined,
|
|
131
|
+
docs: cfg.docs || undefined,
|
|
123
132
|
instance_url: cfg.instanceURL || undefined,
|
|
124
133
|
profiles: Object.keys(cfg.profiles).length > 0 ? cfg.profiles : undefined,
|
|
125
134
|
default_profile: cfg.defaultProfile || undefined,
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import * as prompts from './prompts.js';
|
|
2
|
+
const { confirm, select, input } = prompts;
|
|
3
|
+
import { ensureLocalDocumentation } from './commands/docs/local.js';
|
|
4
|
+
import { saveConfig } from './config.js';
|
|
5
|
+
import { docsServiceUrl, DEFAULT_DOCS_URL } from './commands/docs/client.js';
|
|
6
|
+
|
|
7
|
+
export function connectionPreferences(config, existing = {}, flags = {}) {
|
|
8
|
+
const saved = { read_only: false, skip_confirmations: false, include_counts: true };
|
|
9
|
+
// Legacy profiles retain their historical defaults when a field is absent.
|
|
10
|
+
const source = Object.keys(existing).length ? existing : (config.connectionDefaults || {});
|
|
11
|
+
for (const key of Object.keys(saved)) if (typeof source[key] === 'boolean') saved[key] = source[key];
|
|
12
|
+
for (const key of ['read_only', 'skip_confirmations', 'include_counts']) {
|
|
13
|
+
const flag = key.replaceAll('_', '-');
|
|
14
|
+
if (typeof flags[flag] === 'boolean') saved[key] = flags[flag];
|
|
15
|
+
}
|
|
16
|
+
return Object.fromEntries(['read_only', 'skip_confirmations', 'include_counts'].map(key => [key, Boolean(saved[key])]));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function askConnectionPreferences(defaults, prompts = { confirm }) {
|
|
20
|
+
return {
|
|
21
|
+
read_only: await prompts.confirm({ message: 'Read-only connections (block changes)?', default: defaults.read_only }),
|
|
22
|
+
skip_confirmations: !(await prompts.confirm({ message: 'Confirm before deleting records?', default: !defaults.skip_confirmations })),
|
|
23
|
+
include_counts: await prompts.confirm({ message: 'Include result totals on list commands?', default: defaults.include_counts }),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function chooseConnectionPreferences(config, flags = {}, prompts = { confirm }) {
|
|
28
|
+
const defaults = connectionPreferences(config, {}, flags);
|
|
29
|
+
const summary = `Read-only: ${defaults.read_only ? 'yes' : 'no'} · Delete confirmations: ${defaults.skip_confirmations ? 'off' : 'on'} · Result totals: ${defaults.include_counts ? 'on' : 'off'}`;
|
|
30
|
+
if (await prompts.confirm({ message: `${summary}\nUse these defaults for this connection?`, default: true })) return defaults;
|
|
31
|
+
return askConnectionPreferences(defaults, prompts);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export async function configureDocumentation(config, prompts = { input, confirm }) {
|
|
35
|
+
const current = config.docs || { source: 'hosted', url: DEFAULT_DOCS_URL };
|
|
36
|
+
const hosted = await prompts.confirm({ message: 'Use JSN-hosted documentation?', default: current.source === 'hosted' });
|
|
37
|
+
const next = { source: hosted ? 'hosted' : 'custom', url: DEFAULT_DOCS_URL };
|
|
38
|
+
if (!hosted && await prompts.confirm({ message: 'Run a local documentation server for you?', default: current.source !== 'custom' })) {
|
|
39
|
+
next.source = 'local';
|
|
40
|
+
next.url = (await ensureLocalDocumentation()).url;
|
|
41
|
+
} else if (!hosted) {
|
|
42
|
+
next.url = await prompts.input({ message: 'Docs service base URL:', default: current.source === 'custom' ? current.url : 'http://127.0.0.1:3000',
|
|
43
|
+
validate: value => { try { docsServiceUrl(value); return true; } catch (error) { return error.message; } } });
|
|
44
|
+
next.url = docsServiceUrl(next.url);
|
|
45
|
+
}
|
|
46
|
+
config.docs = next;
|
|
47
|
+
saveConfig(config);
|
|
48
|
+
return next;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function configureGlobalDefaults(config, { documentation = true, prompts = { confirm, select, input } } = {}) {
|
|
52
|
+
const preferences = await askConnectionPreferences(connectionPreferences(config), prompts);
|
|
53
|
+
config.connectionDefaults = preferences;
|
|
54
|
+
saveConfig(config);
|
|
55
|
+
if (documentation) await configureDocumentation(config, prompts);
|
|
56
|
+
return preferences;
|
|
57
|
+
}
|