@jacebenson/jsn 4.5.1 → 5.0.0
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 +34 -4
- package/bin/jsn.js +0 -14
- package/package.json +3 -6
- 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/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/server.js +60 -0
- package/src/commands/docs/service-snapshot.js +43 -0
- package/src/commands/docs/sync-service.js +162 -0
- package/src/commands/setup.js +36 -26
- package/src/config.js +9 -0
- package/src/setup-preferences.js +57 -0
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Publish a portable backup of the live service index, without re-ingesting docs.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { gzipSync } from 'node:zlib';
|
|
6
|
+
import Database from 'better-sqlite3';
|
|
7
|
+
import { validateDatabase, validateManifest } from './snapshot.js';
|
|
8
|
+
|
|
9
|
+
export async function publishServiceSnapshot(storage) {
|
|
10
|
+
const output = path.join(storage, 'snapshots');
|
|
11
|
+
fs.mkdirSync(output, { recursive: true });
|
|
12
|
+
const db = new Database(path.join(storage, 'docs.sqlite3'), { readonly: true, fileMustExist: true });
|
|
13
|
+
const temporary = fs.mkdtempSync(path.join(output, '.export-'));
|
|
14
|
+
try {
|
|
15
|
+
const revision = db.prepare("SELECT value FROM meta WHERE key='source_revision'").get()?.value;
|
|
16
|
+
if (!/^[a-f0-9]{7,64}$/.test(revision || '')) throw new Error('Index has no valid source revision');
|
|
17
|
+
try {
|
|
18
|
+
const cached = validateManifest(JSON.parse(fs.readFileSync(path.join(output, 'manifest.json'), 'utf8')));
|
|
19
|
+
if (cached.revision === revision && fs.existsSync(path.join(output, path.basename(cached.url)))) return cached;
|
|
20
|
+
} catch { /* no published snapshot yet */ }
|
|
21
|
+
const filename = path.join(temporary, 'docs.sqlite3');
|
|
22
|
+
await db.backup(filename);
|
|
23
|
+
const copy = new Database(filename);
|
|
24
|
+
try {
|
|
25
|
+
copy.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('snapshot_revision', ?)").run(revision);
|
|
26
|
+
copy.pragma('wal_checkpoint(TRUNCATE)');
|
|
27
|
+
copy.pragma('journal_mode = DELETE');
|
|
28
|
+
} finally { copy.close(); }
|
|
29
|
+
const documents = validateDatabase(filename);
|
|
30
|
+
const bytes = fs.readFileSync(filename);
|
|
31
|
+
const compressed = gzipSync(bytes);
|
|
32
|
+
const sha256 = createHash('sha256').update(compressed).digest('hex');
|
|
33
|
+
const name = `docs-${revision}-${sha256}.sqlite.gz`;
|
|
34
|
+
const manifest = validateManifest({ format: 1, schema: 1, cliCompatibility: 'docs-schema-1', revision,
|
|
35
|
+
documents, sha256, compressedBytes: compressed.length, databaseBytes: bytes.length,
|
|
36
|
+
builtAt: new Date().toISOString(), url: `https://jsn.jace.pro/docs-index/artifacts/${name}` });
|
|
37
|
+
fs.writeFileSync(path.join(temporary, name), compressed);
|
|
38
|
+
fs.renameSync(path.join(temporary, name), path.join(output, name));
|
|
39
|
+
fs.writeFileSync(path.join(temporary, 'manifest.json'), JSON.stringify(manifest) + '\n');
|
|
40
|
+
fs.renameSync(path.join(temporary, 'manifest.json'), path.join(output, 'manifest.json'));
|
|
41
|
+
return manifest;
|
|
42
|
+
} finally { db.close(); fs.rmSync(temporary, { recursive: true, force: true }); }
|
|
43
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
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
|
+
import { installSnapshot } from './snapshot.js';
|
|
12
|
+
import { publishServiceSnapshot } from './service-snapshot.js';
|
|
13
|
+
|
|
14
|
+
const defaultStorage = path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'docs-service');
|
|
15
|
+
function git(args) {
|
|
16
|
+
const result = spawnSync('git', args, { encoding: 'utf8', maxBuffer: 4 * 1024 * 1024, timeout: 15 * 60 * 1000 });
|
|
17
|
+
if (result.status !== 0) throw new Error(`Git ${args[0]} failed: ${result.error?.message || result.stderr?.slice(-1000) || result.status}`);
|
|
18
|
+
return result.stdout.trim();
|
|
19
|
+
}
|
|
20
|
+
function writeStatus(storage, status) {
|
|
21
|
+
const temporary = path.join(storage, `status-${randomUUID()}.json`);
|
|
22
|
+
fs.writeFileSync(temporary, JSON.stringify(status, null, 2) + '\n');
|
|
23
|
+
fs.renameSync(temporary, path.join(storage, 'status.json'));
|
|
24
|
+
}
|
|
25
|
+
async function performSync(options = {}) {
|
|
26
|
+
const storage = options.storage || process.env.DOCS_STORAGE_DIR || defaultStorage;
|
|
27
|
+
const source = options.source || process.env.DOCS_SOURCE_URL || 'https://github.com/ServiceNow/ServiceNowDocs.git';
|
|
28
|
+
const branch = options.branch || process.env.DOCS_SOURCE_BRANCH || 'australia';
|
|
29
|
+
fs.mkdirSync(storage, { recursive: true });
|
|
30
|
+
const repo = path.join(storage, 'source');
|
|
31
|
+
const live = path.join(storage, 'docs.sqlite3');
|
|
32
|
+
const staging = path.join(storage, `build-${randomUUID()}.sqlite3`);
|
|
33
|
+
let previous = {};
|
|
34
|
+
try { previous = JSON.parse(fs.readFileSync(path.join(storage, 'status.json'), 'utf8')); } catch { /* first run */ }
|
|
35
|
+
// The shared service lock excludes concurrent publishers.
|
|
36
|
+
for (const name of fs.readdirSync(storage)) {
|
|
37
|
+
if (/^(build|clone)-[a-f0-9-]+(?:\.sqlite3(?:-wal|-shm)?)?$/.test(name)) {
|
|
38
|
+
fs.rmSync(path.join(storage, name), { recursive: true, force: true });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const startedAt = new Date().toISOString();
|
|
42
|
+
writeStatus(storage, { ...previous, state: 'syncing', startedAt });
|
|
43
|
+
try {
|
|
44
|
+
// Only the first installation uses the hosted seed. Updates always use GitHub.
|
|
45
|
+
// Custom source repositories must never be seeded with an unrelated corpus.
|
|
46
|
+
if (!fs.existsSync(live) && ((!options.source && !process.env.DOCS_SOURCE_URL) || options.manifestURL) && branch === 'australia') {
|
|
47
|
+
try {
|
|
48
|
+
const seed = await installSnapshot({ dbPath: live,
|
|
49
|
+
manifestURL: options.manifestURL || process.env.DOCS_BOOTSTRAP_MANIFEST_URL,
|
|
50
|
+
fetchFn: options.fetchFn });
|
|
51
|
+
const db = new Database(live);
|
|
52
|
+
try {
|
|
53
|
+
db.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('source_revision', ?)").run(seed.revision);
|
|
54
|
+
db.prepare("INSERT OR REPLACE INTO meta(key,value) VALUES('source_branch', ?)").run(branch);
|
|
55
|
+
db.pragma('wal_checkpoint(TRUNCATE)'); db.pragma('journal_mode = DELETE');
|
|
56
|
+
} finally { db.close(); }
|
|
57
|
+
previous = { ...previous, revision: seed.revision, documents: seed.documents, seededFrom: 'snapshot' };
|
|
58
|
+
} catch (error) {
|
|
59
|
+
// An unavailable seed never prevents the original GitHub build path.
|
|
60
|
+
previous = { ...previous, bootstrapError: error.message };
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (!fs.existsSync(path.join(repo, '.git')) && fs.existsSync(live) && !options.force) {
|
|
64
|
+
const remote = git(['ls-remote', '--', source, `refs/heads/${branch}`]).split(/\s/)[0];
|
|
65
|
+
const db = new Database(live, { readonly: true });
|
|
66
|
+
let current;
|
|
67
|
+
try { current = db.prepare("SELECT value FROM meta WHERE key='source_revision'").get()?.value; }
|
|
68
|
+
finally { db.close(); }
|
|
69
|
+
if (remote && current === remote) {
|
|
70
|
+
await publishServiceSnapshot(storage);
|
|
71
|
+
const status = { ...previous, state: 'ready', revision: current, checkedAt: new Date().toISOString(), startedAt, error: null, changed: false };
|
|
72
|
+
writeStatus(storage, status);
|
|
73
|
+
return status;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
if (!fs.existsSync(path.join(repo, '.git'))) {
|
|
77
|
+
const cloning = path.join(storage, `clone-${randomUUID()}`);
|
|
78
|
+
try {
|
|
79
|
+
git(['clone', '--depth', '1', '--branch', branch, '--', source, cloning]);
|
|
80
|
+
if (fs.existsSync(repo)) fs.rmSync(repo, { recursive: true, force: true });
|
|
81
|
+
fs.renameSync(cloning, repo);
|
|
82
|
+
} finally { fs.rmSync(cloning, { recursive: true, force: true }); }
|
|
83
|
+
} else {
|
|
84
|
+
// This clone is private to the service. Never operate on a developer's checkout.
|
|
85
|
+
git(['-C', repo, 'fetch', '--depth', '1', 'origin', branch]);
|
|
86
|
+
git(['-C', repo, 'reset', '--hard', 'FETCH_HEAD']);
|
|
87
|
+
}
|
|
88
|
+
const revision = git(['-C', repo, 'rev-parse', 'HEAD']);
|
|
89
|
+
const markdown = path.join(repo, 'markdown');
|
|
90
|
+
if (!fs.statSync(markdown).isDirectory()) throw new Error('Source has no markdown directory');
|
|
91
|
+
let oldRevision;
|
|
92
|
+
if (fs.existsSync(live)) {
|
|
93
|
+
const db = new Database(live, { readonly: true });
|
|
94
|
+
try {
|
|
95
|
+
oldRevision = db.prepare("SELECT value FROM meta WHERE key = 'source_revision'").get()?.value;
|
|
96
|
+
if (oldRevision !== revision || options.force) await db.backup(staging);
|
|
97
|
+
} finally { db.close(); }
|
|
98
|
+
}
|
|
99
|
+
if (oldRevision === revision && !options.force) {
|
|
100
|
+
await publishServiceSnapshot(storage);
|
|
101
|
+
const status = { ...previous, state: 'ready', revision, checkedAt: new Date().toISOString(), startedAt, error: null, changed: false };
|
|
102
|
+
writeStatus(storage, status);
|
|
103
|
+
return status;
|
|
104
|
+
}
|
|
105
|
+
const roots = [{ dir: markdown, prefix: '' }];
|
|
106
|
+
const result = fs.existsSync(staging)
|
|
107
|
+
? refreshDocs({ roots, dbPath: staging, sourceLeaseHeld: true })
|
|
108
|
+
: ingestDocs({ roots, dbPath: staging, embed: false });
|
|
109
|
+
if (result.errors) throw new Error(`Indexing skipped ${result.errors} documents; retaining the published index`);
|
|
110
|
+
const db = new Database(staging);
|
|
111
|
+
let count;
|
|
112
|
+
try {
|
|
113
|
+
count = db.prepare('SELECT COUNT(*) AS n FROM docs').get().n;
|
|
114
|
+
if (!count) throw new Error('Refusing to publish an empty documentation index');
|
|
115
|
+
if (db.pragma('quick_check', { simple: true }) !== 'ok') throw new Error('SQLite integrity check failed');
|
|
116
|
+
db.exec("INSERT INTO docs_fts(docs_fts, rank) VALUES('integrity-check', 1)");
|
|
117
|
+
const set = db.prepare('INSERT OR REPLACE INTO meta(key, value) VALUES(?, ?)');
|
|
118
|
+
set.run('source_revision', revision);
|
|
119
|
+
set.run('source_branch', branch);
|
|
120
|
+
db.pragma('wal_checkpoint(TRUNCATE)');
|
|
121
|
+
db.pragma('journal_mode = DELETE');
|
|
122
|
+
} finally { db.close(); }
|
|
123
|
+
fs.renameSync(staging, live);
|
|
124
|
+
await publishServiceSnapshot(storage);
|
|
125
|
+
const status = { state: 'ready', revision, documents: count, startedAt, checkedAt: new Date().toISOString(), publishedAt: new Date().toISOString(), changed: true, error: null, result };
|
|
126
|
+
writeStatus(storage, status);
|
|
127
|
+
return status;
|
|
128
|
+
} catch (error) {
|
|
129
|
+
writeStatus(storage, { ...previous, state: 'failed', startedAt, checkedAt: new Date().toISOString(), error: error.message });
|
|
130
|
+
throw error;
|
|
131
|
+
} finally {
|
|
132
|
+
for (const suffix of ['', '-wal', '-shm']) fs.rmSync(staging + suffix, { force: true });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
export async function syncDocumentation(options = {}) {
|
|
136
|
+
const storage = options.storage || process.env.DOCS_STORAGE_DIR || defaultStorage;
|
|
137
|
+
fs.mkdirSync(storage, { recursive: true });
|
|
138
|
+
const lock = path.join(storage, 'sync-service.lock');
|
|
139
|
+
try { fs.mkdirSync(lock); }
|
|
140
|
+
catch (error) {
|
|
141
|
+
if (error.code !== 'EEXIST') throw error;
|
|
142
|
+
let pid;
|
|
143
|
+
try { pid = Number(fs.readFileSync(path.join(lock, 'pid'), 'utf8')); } catch { /* another process may be writing it */ }
|
|
144
|
+
if (!pid) {
|
|
145
|
+
if (Date.now() - fs.statSync(lock).mtimeMs < 30_000) return { state: 'syncing', changed: false };
|
|
146
|
+
fs.rmSync(lock, { recursive: true, force: true });
|
|
147
|
+
return syncDocumentation(options);
|
|
148
|
+
}
|
|
149
|
+
try { process.kill(pid, 0); return { state: 'syncing', changed: false }; }
|
|
150
|
+
catch (probe) { if (probe.code !== 'ESRCH') throw probe; }
|
|
151
|
+
fs.rmSync(lock, { recursive: true });
|
|
152
|
+
// Retry acquisition, so another waiting publisher still wins exclusively.
|
|
153
|
+
return syncDocumentation(options);
|
|
154
|
+
}
|
|
155
|
+
fs.writeFileSync(path.join(lock, 'pid'), String(process.pid));
|
|
156
|
+
try { return await performSync(options); }
|
|
157
|
+
finally { fs.rmSync(lock, { recursive: true, force: true }); }
|
|
158
|
+
}
|
|
159
|
+
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
160
|
+
try { process.stdout.write(JSON.stringify(await syncDocumentation()) + '\n'); }
|
|
161
|
+
catch (error) { process.stderr.write(error.message + '\n'); process.exitCode = 1; }
|
|
162
|
+
}
|
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
|
+
}
|