@jacebenson/jsn 5.5.1-dev.162.1 → 5.5.1-dev.164.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 CHANGED
@@ -289,13 +289,41 @@ Local mode downloads the public documentation on first use and checks for update
289
289
  daily while running. The server starts again automatically when needed. A first
290
290
  search can report that the index is still being prepared; later updates preserve
291
291
  the last working index if offline. Local storage lives under
292
- `~/.jsn/docs-service` (`JSN_DATA_HOME` overrides the parent directory).
292
+ `~/.jsn/docs/docs.db` for the default family. Other families use
293
+ `~/.jsn/docs/releases/NAME/docs.db`. `JSN_DATA_HOME` overrides the parent directory.
294
+ Existing default-family installs keep their original index path.
293
295
 
294
296
  To host the same service yourself, run `jsn docs --serve --host 0.0.0.0 --port 3000`.
295
297
  It manages its own index; expose it through your normal HTTPS proxy. The hosted
296
298
  website and this server share one search engine. `JSN_DOCS_URL` temporarily
297
299
  overrides the saved choice without starting a local server.
298
300
 
301
+ Choose a family with `jsn docs "GlideRecord" --release brazil`. The same option
302
+ applies to `--path`, `docs show <ID>`, `docs status`, `docs sync`, `docs install`
303
+ and `--serve`. Resolution is `--release` first, then the optional `docs.release`
304
+ preference, then `australia`. Release names contain 1–40 lowercase letters,
305
+ digits or dashes. The service decides which families exist.
306
+
307
+ Documentation preferences are saved in the global profile config at
308
+ `$XDG_CONFIG_HOME/servicenow/config.json`, normally
309
+ `~/.config/servicenow/config.json`. Alongside `docs.source` and `docs.url`, set
310
+ `docs.release` without changing the service URL:
311
+
312
+ ```json
313
+ { "docs": { "source": "hosted", "url": "https://jsn.jace.pro", "release": "brazil" } }
314
+ ```
315
+
316
+ `jsn docs releases` lists installed families, revisions, document counts, index
317
+ paths and the default marker without contacting the network. To install an
318
+ optional local index, use `jsn docs install --source snapshot --release brazil`,
319
+ or `jsn docs sync --release brazil --no-embed`. Sync downloads the named Git
320
+ branch; `--no-ingest` downloads only the source. Snapshot installs use
321
+ `/docs-index/releases/NAME/manifest.json` and verify the declared release. Only
322
+ the default family can fall back to the old `/docs-index/manifest.json` when
323
+ the family manifest returns 404. That legacy manifest may omit `release`.
324
+ `jsn docs --serve --release brazil` serves only Brazil and rejects requests
325
+ for other families. Search, read and status JSON include the selected `release`.
326
+
299
327
  Exact paths remain stable across revisions. Numeric IDs can be pinned with
300
328
  `--revision <search-revision>`. Older `docs search`, `docs show` and `docs status`
301
329
  spellings remain compatible but are omitted from the everyday help menu.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jacebenson/jsn",
3
- "version": "5.5.1-dev.162.1",
3
+ "version": "5.5.1-dev.164.1",
4
4
  "description": "A command-line interface for ServiceNow that follows the Unix philosophy: simple, composable, and scriptable.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -39,9 +39,10 @@ async function request(endpoint, params, options = {}) {
39
39
  const code = response.status === 404 ? 'not_found' : response.status === 429 ? 'rate_limited' : response.status === 400 ? 'usage_error' : 'api_error';
40
40
  const message = typeof data?.error === 'string' ? data.error.slice(0, 300) : `Documentation service returned HTTP ${response.status}.`;
41
41
  const hint = response.status === 409 ? 'Search again for the current revision, or retrieve the document by its exact path.'
42
- : response.status === 429 ? 'Wait before retrying.' : response.status >= 500 ? 'Try again later; the documentation service may be updating or unavailable.' : '';
42
+ : response.status === 429 ? 'Wait before retrying.' : response.status >= 500 ? 'Try again later; the documentation service may be updating or unavailable.' : typeof data?.hint === 'string' ? data.hint : '';
43
43
  throw new AppError(code, message, hint, response.status);
44
44
  }
45
+ if (options.release && data?.release !== undefined && data.release !== options.release) throw new AppError('api_error', `Documentation service returned release ${data.release}, expected ${options.release}.`);
45
46
  return { data, service };
46
47
  }
47
48
  function invalidResponse() {
@@ -54,24 +55,33 @@ export async function searchHostedDocs(options = {}) {
54
55
  if (!Number.isInteger(limit) || limit < 1 || limit > 50 || !Number.isInteger(offset) || offset < 0 || offset > 10000) {
55
56
  throw new AppError('usage_error', 'Use --limit 1–50 and --offset 0–10000.');
56
57
  }
57
- const { data, service } = await request('api/docs/search', { q: query, limit, offset, bundle: options.bundle }, options);
58
+ const { data, service } = await request('api/docs/search', { q: query, limit, offset, bundle: options.bundle, release: options.release }, options);
58
59
  if (!data || !Array.isArray(data.results) || data.results.length > limit || data.count !== data.results.length ||
59
60
  !Number.isInteger(data.total) || data.total < data.count || typeof data.revision !== 'string' ||
60
61
  !data.results.every(row => row && Number.isInteger(row.id) && typeof row.path === 'string')) throw invalidResponse();
61
- return { ...data, query, limit, offset, service };
62
+ // A service that predates release selection echoes no release of its own; when every
63
+ // row it returned is stamped with a different family, say so instead of relabelling it.
64
+ if (options.release && data.release === undefined) {
65
+ const stamped = new Set(data.results.map(row => row.release).filter(value => typeof value === 'string' && value));
66
+ if (stamped.size === 1 && !stamped.has(options.release)) {
67
+ throw new AppError('api_error', `Documentation service answered with ${[...stamped][0]} documents, expected ${options.release}.`,
68
+ 'Update the documentation service to serve multiple releases, or omit --release.');
69
+ }
70
+ }
71
+ return { ...data, release: options.release ?? data.release, query, limit, offset, service };
62
72
  }
63
73
  export async function getHostedDoc(idOrPath, options = {}) {
64
74
  const identifier = String(idOrPath || '');
65
75
  if (!identifier) throw new AppError('usage_error', 'Provide a document ID or exact path.');
66
76
  const numeric = /^\d+$/.test(identifier);
67
77
  const { data, service } = await request(numeric ? `api/docs/${identifier}` : 'api/docs/document', {
68
- ...(numeric ? {} : { path: identifier }), revision: options.revision,
78
+ ...(numeric ? {} : { path: identifier }), revision: options.revision, release: options.release,
69
79
  }, options);
70
80
  if (!data || !data.document || typeof data.document.body !== 'string' || typeof data.document.path !== 'string' || typeof data.revision !== 'string') throw invalidResponse();
71
- return { ...data.document, revision: data.revision, service };
81
+ return { ...data.document, release: options.release ?? data.release, revision: data.revision, service };
72
82
  }
73
83
  export async function getHostedDocsStatus(options = {}) {
74
- const { data, service } = await request('api/docs/status', {}, options);
84
+ const { data, service } = await request('api/docs/status', { release: options.release }, options);
75
85
  if (!data || typeof data.state !== 'string') throw invalidResponse();
76
- return { ...data, service };
86
+ return { ...data, release: options.release ?? data.release, service };
77
87
  }
@@ -10,7 +10,7 @@ import process from 'node:process';
10
10
  import TurndownService from 'turndown';
11
11
  import { parseFrontmatter, stringifyFrontmatter } from '../../frontmatter.js';
12
12
  import Database from 'better-sqlite3';
13
- import { getDocsCommunityDir, getDocsDbPath, docsDbExists } from './db.js';
13
+ import { getDocsCommunityDir, resolveDocsDbPath, docsDbExists } from './db.js';
14
14
  import { refreshDocs } from './refresh.js';
15
15
  import { ingestDocs } from './ingest.js';
16
16
 
@@ -216,7 +216,7 @@ export async function syncCommunity(opts = {}) {
216
216
  const expand = opts.expand === true;
217
217
  const force = opts.force === true;
218
218
  const delayMs = opts.delayMs != null ? opts.delayMs : 500;
219
- const dbPath = opts.dbPath || getDocsDbPath();
219
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
220
220
 
221
221
  const results = { hubs: [], articles: [], skipped: [], errors: [] };
222
222
 
@@ -326,8 +326,8 @@ function findExisting(url, urlIndex) {
326
326
  return urlIndex.get(url) || null;
327
327
  }
328
328
 
329
- export function listCommunityDocs({ dbPath } = {}) {
330
- const dbFile = dbPath || getDocsDbPath();
329
+ export function listCommunityDocs({ dbPath, release } = {}) {
330
+ const dbFile = dbPath || resolveDocsDbPath(release);
331
331
  if (!fs.existsSync(dbFile)) return { total: 0, docs: [] };
332
332
  const db = new Database(dbFile, { readonly: true });
333
333
  const rows = db
@@ -5,9 +5,11 @@ import path from 'node:path';
5
5
  import os from 'node:os';
6
6
  import Database from 'better-sqlite3';
7
7
  import { docsReaderLease } from './locks.js';
8
+ import { AppError } from '../../errors.js';
8
9
 
9
10
  const LEGACY_DOCS_DIR_NAME = 'servicenow-cli/docs';
10
11
  const DOCS_DIR_NAME = 'docs';
12
+ export const DEFAULT_DOCS_RELEASE = 'australia'; // Bump when a new release family ships.
11
13
 
12
14
  function xdgCacheHome() {
13
15
  if (process.env.XDG_CACHE_HOME) return process.env.XDG_CACHE_HOME;
@@ -79,16 +81,29 @@ export function getDocsDbPath() {
79
81
  return path.join(getDocsCacheDir(), 'docs.db');
80
82
  }
81
83
 
82
- export function getDocsSourceDir() {
83
- return path.join(getDocsCacheDir(), 'source');
84
+ export function resolveDocsRelease(value, config = {}) {
85
+ const release = value ?? config.docs?.release ?? DEFAULT_DOCS_RELEASE;
86
+ if (typeof release !== 'string' || !/^[a-z0-9-]{1,40}$/.test(release)) {
87
+ throw new AppError('usage_error', 'Documentation release must contain 1–40 lowercase letters, digits or dashes.');
88
+ }
89
+ return release;
90
+ }
91
+
92
+ export function resolveDocsDbPath(release = DEFAULT_DOCS_RELEASE) {
93
+ release = resolveDocsRelease(release);
94
+ return release === DEFAULT_DOCS_RELEASE ? getDocsDbPath() : path.join(jsnDataHome(), DOCS_DIR_NAME, 'releases', release, 'docs.db');
95
+ }
96
+
97
+ export function getDocsSourceDir(release) {
98
+ return path.join(path.dirname(resolveDocsDbPath(release)), 'source');
84
99
  }
85
100
 
86
- export function getDocsSourceMarkdownDir() {
87
- return path.join(getDocsSourceDir(), 'markdown');
101
+ export function getDocsSourceMarkdownDir(release) {
102
+ return path.join(getDocsSourceDir(release), 'markdown');
88
103
  }
89
104
 
90
- export function getDocsCommunityDir() {
91
- return path.join(getDocsCacheDir(), 'community');
105
+ export function getDocsCommunityDir(release) {
106
+ return path.join(path.dirname(resolveDocsDbPath(release)), 'community');
92
107
  }
93
108
 
94
109
  export function ensureDocsCacheDir() {
@@ -122,15 +137,15 @@ export function* walkDocs(roots) {
122
137
  }
123
138
 
124
139
  export function defaultDocsRoots(opts = {}) {
125
- const communityDir = opts.communityDir || getDocsCommunityDir();
140
+ const communityDir = opts.communityDir || getDocsCommunityDir(opts.release);
126
141
  return [
127
- { dir: opts.docsDir || getDocsSourceMarkdownDir(), prefix: '' },
142
+ { dir: opts.docsDir || getDocsSourceMarkdownDir(opts.release), prefix: '' },
128
143
  { dir: communityDir, prefix: 'community/' },
129
144
  ];
130
145
  }
131
146
 
132
147
  export function openDocsDb(opts = {}) {
133
- const dbPath = opts.dbPath || getDocsDbPath();
148
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
134
149
  fs.mkdirSync(path.dirname(dbPath), { recursive: true });
135
150
  const release = docsReaderLease(dbPath);
136
151
  let db;
@@ -156,8 +171,8 @@ export function closeDocsDb(db) {
156
171
  }
157
172
  }
158
173
 
159
- export function docsDbExists() {
160
- return fs.existsSync(getDocsDbPath());
174
+ export function docsDbExists(release) {
175
+ return fs.existsSync(resolveDocsDbPath(release));
161
176
  }
162
177
 
163
178
  export function getSchemaVersion(db) {
@@ -1,16 +1,19 @@
1
1
  // Documentation search always uses the same API, hosted or self-hosted.
2
- import { searchHostedDocs, getHostedDoc, getHostedDocsStatus } from './client.js';
2
+ import { searchHostedDocs, getHostedDoc, getHostedDocsStatus, configuredDocsService } from './client.js';
3
3
  import { documentationService } from './local.js';
4
4
  import { startDocumentationServer } from './server.js';
5
5
  import { declareCapabilities } from '../../capabilities.js';
6
6
  import { AppError } from '../../errors.js';
7
+ import { resolveDocsRelease } from './db.js';
8
+ import { listDocsReleases } from './releases.js';
7
9
 
8
10
  declareCapabilities('docs', { noInstance: true, skipDailyChecks: true });
9
11
 
10
12
  async function search(argv, app) {
11
13
  const query = Array.isArray(argv.query) ? argv.query.join(' ') : argv.query;
12
- const result = await searchHostedDocs({ query, limit: argv.limit, offset: argv.offset, bundle: argv.bundle, serviceUrl: await documentationService(app.config) });
13
- const lines = [];
14
+ const result = await searchHostedDocs({ query, limit: argv.limit, offset: argv.offset, bundle: argv.bundle, release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
15
+ const summary = `${result.count} of ${result.total} result(s) for "${result.query}" in ${result.release}`;
16
+ const lines = [summary, ''];
14
17
  for (const row of result.results) {
15
18
  lines.push(`[${row.id}] ${row.title || row.path}`, ` ${row.path}`);
16
19
  const summary = String(row.summary || row.snippet || '').replace(/\s+/g, ' ').trim();
@@ -21,16 +24,16 @@ async function search(argv, app) {
21
24
  if (result.count && next < result.total && next <= 10000) lines.push(`… ${result.total - next} more results (use --offset ${next} for the next page)`);
22
25
  if (!result.count) lines.push('No matching documents. Try fewer words or a different term.');
23
26
  if (result.count) lines.push('Read with "jsn docs --path <exact-path>"; IDs can be pinned with --revision.');
24
- app.ok({ ...result, _formatted: lines.join('\n') + '\n' }, { summary: `${result.count} of ${result.total} result(s) for "${result.query}"` });
27
+ app.ok({ ...result, _formatted: lines.join('\n') + '\n' }, { summary });
25
28
  }
26
29
  async function read(argv, app) {
27
30
  const maxLines = argv.lines ?? 80;
28
31
  if (!Number.isInteger(maxLines) || maxLines < 1 || maxLines > 10000) throw new AppError('usage_error', 'Use --lines 1–10000.');
29
- const row = await getHostedDoc(argv.path || argv['id-or-path'], { revision: argv.revision, serviceUrl: await documentationService(app.config) });
32
+ const row = await getHostedDoc(argv.path || argv['id-or-path'], { revision: argv.revision, release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
30
33
  const title = row.title || row.path;
31
34
  const lines = row.body.split('\n');
32
35
  const hint = lines.length > maxLines ? `\n\n… ${lines.length - maxLines} more lines (use --lines ${Math.min(lines.length, 10000)} or --json for full content)` : '';
33
- app.ok({ ...row, _formatted: `${title}\n${'─'.repeat(Math.min(title.length, 80))}\n\n${lines.slice(0, maxLines).join('\n')}${hint}\n` }, { summary: `Doc ${row.id}: ${title}` });
36
+ app.ok({ ...row, _formatted: `Doc ${row.id}: ${title} in ${row.release}\n${'─'.repeat(Math.min(title.length, 80))}\n\n${lines.slice(0, maxLines).join('\n')}${hint}\n` }, { summary: `Doc ${row.id}: ${title} in ${row.release}` });
34
37
  }
35
38
 
36
39
  export function docsCmd(wrap) {
@@ -41,6 +44,7 @@ export function docsCmd(wrap) {
41
44
  builder: y => y
42
45
  .usage('Usage: jsn docs "search terms" [options]')
43
46
  .positional('query', { type: 'string', describe: 'Search words (up to 200 characters)' })
47
+ .option('release', { type: 'string', describe: 'Documentation family (docs.release config, otherwise australia)' })
44
48
  .option('serve', { type: 'boolean', describe: 'Run the shared documentation server (downloads its index automatically)' })
45
49
  .option('host', { type: 'string', default: '127.0.0.1', describe: 'Server bind address with --serve' })
46
50
  .option('port', { type: 'number', default: 3000, describe: 'Server port with --serve' })
@@ -50,32 +54,45 @@ export function docsCmd(wrap) {
50
54
  .option('path', { type: 'string', describe: 'Read an exact document path or ID from search results' })
51
55
  .option('revision', { type: 'string', describe: 'Require the revision returned by search (recommended with IDs)' })
52
56
  .option('lines', { type: 'number', default: 80, describe: 'Preview lines; JSON contains the full Markdown body' })
57
+ .command({ command: 'releases', describe: 'List locally installed documentation families', handler: wrap(async (_argv, app) => {
58
+ const releases = listDocsReleases();
59
+ app.ok({ releases, _formatted: releases.length ? releases.map(row => `${row.release}${row.default ? ' (default)' : ''} ${row.revision || 'unknown'} ${row.documents} documents ${row.indexPath}`).join('\n') + '\n' : 'No local documentation families installed.\n' }, { summary: `${releases.length} local documentation release(s)` });
60
+ }) })
61
+ .command({ command: 'sync', describe: 'Clone or update a documentation family and its local index',
62
+ builder: y => y.option('embed', { type: 'boolean', default: true }).option('ingest', { type: 'boolean', default: true }),
63
+ handler: wrap(async (argv, app) => {
64
+ const { syncDocs } = await import('./sync.js');
65
+ const release = resolveDocsRelease(argv.release, app.config);
66
+ app.ok({ ...syncDocs({ release, embed: argv.embed, noIngest: argv.ingest === false }), release });
67
+ }),
68
+ })
53
69
  // Compatibility spellings remain callable without becoming another menu.
54
70
  .command({ command: 'install', hidden: true,
55
71
  builder: y => y.option('source', { type: 'string', choices: ['snapshot', 'github', 'skip'] })
56
72
  .option('manifest-url', { type: 'string' }),
57
73
  handler: wrap(async (argv, app) => {
58
74
  const { installDocumentation } = await import('./install.js');
59
- app.ok(await installDocumentation(argv.source, { manifestURL: argv['manifest-url'] }));
75
+ app.ok(await installDocumentation(argv.source, { manifestURL: argv['manifest-url'], release: resolveDocsRelease(argv.release, app.config), serviceUrl: configuredDocsService(app.config) }));
60
76
  }),
61
77
  })
62
78
  .command({ command: 'search <query..>', hidden: true, handler: wrap(search) })
63
79
  .command({ command: 'show <id-or-path>', hidden: true, handler: wrap(read) })
64
- .command({ command: 'status', hidden: true, handler: wrap(async (_argv, app) => {
65
- const data = await getHostedDocsStatus({ serviceUrl: await documentationService(app.config) });
66
- app.ok(data, { summary: `Documentation service: ${data.state}` });
80
+ .command({ command: 'status', hidden: true, handler: wrap(async (argv, app) => {
81
+ const data = await getHostedDocsStatus({ release: resolveDocsRelease(argv.release, app.config), serviceUrl: await documentationService(app.config, resolveDocsRelease(argv.release, app.config)) });
82
+ app.ok(data, { summary: `Documentation service: ${data.state} in ${data.release}` });
67
83
  }) }),
68
84
  handler: wrap(async (argv, app) => {
69
85
  if (argv.serve) {
70
86
  if (!Number.isInteger(argv.port) || argv.port < 0 || argv.port > 65535) throw new AppError('usage_error', 'Use a port between 0 and 65535.');
71
- const { server, url } = await startDocumentationServer({ host: argv.host, port: argv.port });
72
- app.ok({ url, state: 'listening' }, { summary: 'Documentation server started; the index updates automatically.' });
87
+ const release = resolveDocsRelease(argv.release, app.config);
88
+ const { server, url } = await startDocumentationServer({ host: argv.host, port: argv.port, release });
89
+ app.ok({ url, release, state: 'listening' }, { summary: `Documentation server started for ${release}; the index updates automatically.` });
73
90
  for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => server.close());
74
91
  return;
75
92
  }
76
93
  if (argv.path) return read(argv, app);
77
94
  if (argv.query?.length) return search(argv, app);
78
- const service = await documentationService(app.config);
95
+ const service = await documentationService(app.config, resolveDocsRelease(argv.release, app.config));
79
96
  const summary = 'Search ServiceNow documentation';
80
97
  app.ok({ command: 'docs', service,
81
98
  _formatted: `jsn docs "search terms"\njsn docs --path <exact-path>\n\nService: ${service}\nChange documentation preferences in jsn setup → Defaults and documentation.\nNo ServiceNow connection is needed. Hosted mode downloads no database.\n`,
@@ -1,11 +1,11 @@
1
1
  // Populate HRR phase-vector embeddings for semantic reranking.
2
2
 
3
3
  import fs from 'node:fs';
4
- import { withDocsDb, getDocsDbPath } from './db.js';
4
+ import { withDocsDb, resolveDocsDbPath } from './db.js';
5
5
  import { encodeText, phasesToBytes, docSurface, DEFAULT_DIM } from './hrr.js';
6
6
 
7
7
  export function embedDocs(opts = {}) {
8
- const dbPath = opts.dbPath || getDocsDbPath();
8
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
9
9
 
10
10
  if (!fs.existsSync(dbPath)) {
11
11
  throw new Error(`Database not found: ${dbPath}. Run "jsn docs sync" first.`);
@@ -6,7 +6,7 @@ try {
6
6
  for await (const line of readline.createInterface({ input: process.stdin, crlfDelay: Infinity })) {
7
7
  try {
8
8
  const { operation, arguments: args = {} } = JSON.parse(line);
9
- if (operation !== 'summary') index ||= new DocumentationIndex(process.env.DOCS_STORAGE_DIR);
9
+ if (operation !== 'summary') index ||= new DocumentationIndex(process.env.DOCS_STORAGE_DIR, process.env.JSN_DOCS_RELEASE || undefined);
10
10
  const value = operation === 'summary' ? documentationSummary(args) : operation === 'revision' ? index.revision()
11
11
  : operation === 'search' ? index.search(args) : operation === 'document' ? index.document(args) : null;
12
12
  process.stdout.write(JSON.stringify({ value }) + '\n');
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import Database from 'better-sqlite3';
5
+ import { resolveDocsDbPath } from './db.js';
5
6
 
6
7
  export class DocumentationError extends Error {
7
8
  constructor(message, status = 503) { super(message); this.status = status; }
@@ -47,12 +48,12 @@ export function documentationSummary(input) {
47
48
  };
48
49
  }
49
50
  export class DocumentationIndex {
50
- constructor(storage) {
51
- try { this.db = new Database(path.join(storage, 'docs.sqlite3'), { readonly: true, fileMustExist: true, timeout: 2000 }); }
51
+ constructor(storage, release) {
52
+ try { this.db = new Database(release ? resolveDocsDbPath(release) : path.join(storage, 'docs.sqlite3'), { readonly: true, fileMustExist: true, timeout: 2000 }); }
52
53
  catch { throw new DocumentationError('Documentation is being prepared. Please try again shortly.'); }
53
54
  }
54
55
  close() { this.db.close(); }
55
- revision() { return this.db.prepare("SELECT value FROM meta WHERE key = 'source_revision'").get()?.value || ''; }
56
+ revision() { return this.db.prepare("SELECT value FROM meta WHERE key = 'source_revision'").get()?.value || this.db.prepare("SELECT value FROM meta WHERE key = 'snapshot_revision'").get()?.value || ''; }
56
57
  search({ query, limit = 20, offset = 0, bundle } = {}) {
57
58
  const text = String(query || '').trim();
58
59
  if (!text || text.length > 200) throw new DocumentationError('Enter a search of 1 to 200 characters.', 400);
@@ -7,14 +7,14 @@ import { docsReaderLease } from './locks.js';
7
7
  import { installDatabase } from './replace.js';
8
8
  import { createHash } from 'node:crypto';
9
9
  import { parseFrontmatter } from '../../frontmatter.js';
10
- import { withDocsDb, initDocsSchema, getDocsDbPath, walkDocs, defaultDocsRoots, getDocsSourceDir } from './db.js';
10
+ import { withDocsDb, initDocsSchema, resolveDocsDbPath, walkDocs, defaultDocsRoots, getDocsSourceDir } from './db.js';
11
11
  import { encodeText, phasesToBytes, docSurface, DEFAULT_DIM } from './hrr.js';
12
12
 
13
13
  export function ingestDocs(opts = {}) {
14
- const dbPath = opts.dbPath || getDocsDbPath();
14
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
15
15
  fs.mkdirSync(path.dirname(dbPath), { recursive: true });
16
16
  const staging = `${dbPath}.${randomUUID()}.building`;
17
- const resource = opts.sourceResource || (!opts.roots ? getDocsSourceDir() : null);
17
+ const resource = opts.sourceResource || (!opts.roots ? getDocsSourceDir(opts.release) : null);
18
18
  if (resource) fs.mkdirSync(path.dirname(resource), { recursive: true });
19
19
  const releaseSource = resource && !opts.sourceLeaseHeld ? docsReaderLease(resource) : () => {};
20
20
  try {
@@ -25,7 +25,7 @@ export function ingestDocs(opts = {}) {
25
25
  } finally { releaseSource(); fs.rmSync(staging, { force: true }); }
26
26
  }
27
27
  function ingestStagedDocs(opts = {}) {
28
- const dbPath = opts.dbPath || getDocsDbPath();
28
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
29
29
  const embed = opts.embed !== false;
30
30
  const roots = opts.roots || defaultDocsRoots(opts);
31
31
 
@@ -3,36 +3,37 @@ import path from 'node:path';
3
3
  import { spawn } from 'node:child_process';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { docsReaderLease } from './locks.js';
6
- import { getDocsDbPath, getDocsCacheDir, getDocsSourceDir } from './db.js';
7
- import { fetchManifest, installSnapshot, snapshotEstimate, validateDatabase, installDatabase, docsSnapshotStatus, DEFAULT_MANIFEST_URL } from './snapshot.js';
6
+ import { resolveDocsDbPath, resolveDocsRelease, getDocsSourceDir } from './db.js';
7
+ import { fetchManifest, fetchReleaseManifest, installSnapshot, snapshotEstimate, validateDatabase, installDatabase, docsSnapshotStatus, DEFAULT_MANIFEST_URL } from './snapshot.js';
8
8
  import { canUsePicker } from '../../helpers.js';
9
9
  import { errUsageHint } from '../../errors.js';
10
10
 
11
11
  export async function installDocumentation(source, options = {}) {
12
- if (source === 'skip') return { source, skipped: true };
12
+ const release = resolveDocsRelease(options.release);
13
+ const target = resolveDocsDbPath(release);
14
+ if (source === 'skip') return { source, release, skipped: true };
13
15
  if (source === 'snapshot') {
14
- const manifestURL = options.manifestURL || DEFAULT_MANIFEST_URL;
15
- const manifest = options.manifest || await fetchManifest(manifestURL);
16
+ const { manifestURL, manifest } = options.manifest ? { manifest: options.manifest, manifestURL: options.manifestURL || DEFAULT_MANIFEST_URL } : await fetchReleaseManifest({ ...options, release });
16
17
  process.stderr.write(`Prebuilt searchable database: ${snapshotEstimate(manifest)}.\n`);
17
- return installSnapshot({ manifestURL, manifest });
18
+ return installSnapshot({ manifestURL, manifest, release, dbPath: target });
18
19
  }
19
20
  if (source !== 'github') throw errUsageHint('Choose a documentation source.', 'Use jsn docs install --source snapshot|github|skip');
20
21
  process.stderr.write('Raw GitHub source: approximately 51,000 files plus local indexing; estimated 5–25 minutes including semantic indexing (prior runs ~5 minutes; validation full build ~21 minutes; actual time and size vary).\n');
21
- fs.mkdirSync(getDocsCacheDir(), { recursive: true });
22
- const staging = fs.mkdtempSync(path.join(getDocsCacheDir(), '.github-install-'));
22
+ fs.mkdirSync(path.dirname(target), { recursive: true });
23
+ const staging = fs.mkdtempSync(path.join(path.dirname(target), '.github-install-'));
23
24
  try {
24
25
  const { syncDocs } = await import('./sync.js');
25
26
  const { ingestDocs } = await import('./ingest.js');
26
- const repoDir = getDocsSourceDir(), dbPath = path.join(staging, 'docs.db');
27
- syncDocs({ repoDir, markdownDir: path.join(repoDir, 'markdown'), noIngest: true, embed: false });
27
+ const repoDir = getDocsSourceDir(release), dbPath = path.join(staging, 'docs.db');
28
+ syncDocs({ release, repoDir, markdownDir: path.join(repoDir, 'markdown'), noIngest: true, embed: false });
28
29
  const releaseSource = docsReaderLease(repoDir);
29
30
  let result;
30
31
  try { result = ingestDocs({ dbPath, roots: [{ dir: path.join(repoDir, 'markdown'), prefix: '' }], embed: true }); }
31
32
  finally { releaseSource(); }
32
33
  if (result.errors) throw new Error('Raw documentation indexing failed; existing index retained');
33
34
  validateDatabase(dbPath);
34
- installDatabase(dbPath, getDocsDbPath(), { afterInstall: () => fs.rmSync(`${getDocsDbPath()}.snapshot.json`, { force: true }) });
35
- return { source, documents: result.count, dbPath: getDocsDbPath() };
35
+ installDatabase(dbPath, target, { afterInstall: () => fs.rmSync(`${target}.snapshot.json`, { force: true }) });
36
+ return { source, release, documents: result.count, dbPath: target };
36
37
  } finally { fs.rmSync(staging, { recursive: true, force: true }); }
37
38
  }
38
39
  export async function chooseDocumentationSource() {
@@ -59,25 +60,26 @@ export async function offerDocumentation(_app, _argv = {}) {
59
60
  return installDocumentation(source, { manifest: approvedManifest });
60
61
  }
61
62
  export async function ensureDocumentation(app, argv) {
62
- if (fs.existsSync(getDocsDbPath())) { scheduleFreshnessCheck(); return; }
63
+ const release = resolveDocsRelease(argv.release, app.config);
64
+ if (fs.existsSync(resolveDocsDbPath(release))) { scheduleFreshnessCheck(release); return; }
63
65
  if (!canUsePicker(app, argv)) throw errUsageHint('No local documentation index. Documentation installation is optional and requires a source choice.',
64
66
  'Run jsn docs install --source snapshot for a verified prebuilt database, or --source github for raw files + local indexing (estimated 5–25 minutes). Use --source skip to defer.');
65
67
  const result = await offerDocumentation(app, argv);
66
68
  if (result.skipped) throw errUsageHint('Documentation installation skipped.', 'Run jsn docs install --source snapshot|github when ready.');
67
69
  }
68
- export function scheduleFreshnessCheck() {
70
+ export function scheduleFreshnessCheck(release) {
69
71
  if (process.env.JSN_NO_DOCS_CHECK === '1') return;
70
- const receipt = docsSnapshotStatus();
72
+ const receipt = docsSnapshotStatus(release);
71
73
  if (!receipt) return;
72
74
  try {
73
- const stamp = `${getDocsDbPath()}.check-stamp`;
75
+ const stamp = `${resolveDocsDbPath(release)}.check-stamp`;
74
76
  try {
75
77
  if (Date.now() - fs.statSync(stamp).mtimeMs < 86400000) return;
76
78
  fs.rmSync(stamp);
77
79
  } catch (error) { if (error.code !== 'ENOENT') return; }
78
80
  fs.writeFileSync(stamp, '', { flag: 'wx' });
79
81
  // A separate bounded worker prevents network from delaying local search.
80
- const child = spawn(process.execPath, [fileURLToPath(new URL('./snapshot-check.js', import.meta.url)), getDocsDbPath()], {
82
+ const child = spawn(process.execPath, [fileURLToPath(new URL('./snapshot-check.js', import.meta.url)), resolveDocsDbPath(release)], {
81
83
  detached: true, stdio: 'ignore', windowsHide: true,
82
84
  });
83
85
  child.on('error', () => {});
@@ -6,6 +6,7 @@ import { setTimeout as delay } from 'node:timers/promises';
6
6
  import { AppError } from '../../errors.js';
7
7
  import { configuredDocsService, docsServiceUrl } from './client.js';
8
8
  import os from 'node:os';
9
+ import { resolveDocsDbPath } from './db.js';
9
10
 
10
11
  function storageDirectory() { return path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'docs-service'); }
11
12
  async function healthy(state) {
@@ -17,7 +18,8 @@ async function healthy(state) {
17
18
  return response.ok && (await response.json()).service === 'jsn-docs';
18
19
  } catch { return false; }
19
20
  }
20
- export async function ensureLocalDocumentation({ storage = storageDirectory() } = {}) {
21
+ export async function ensureLocalDocumentation({ storage = storageDirectory(), release } = {}) {
22
+ if (release) storage = path.dirname(resolveDocsDbPath(release));
21
23
  fs.mkdirSync(storage, { recursive: true, mode: 0o700 });
22
24
  const stateFile = path.join(storage, 'server.json'), lock = path.join(storage, 'server-start.lock');
23
25
  const state = () => { try { return JSON.parse(fs.readFileSync(stateFile, 'utf8')); } catch { return {}; } };
@@ -43,7 +45,7 @@ export async function ensureLocalDocumentation({ storage = storageDirectory() }
43
45
  const log = fs.openSync(path.join(storage, 'server.log'), 'a', 0o600);
44
46
  try {
45
47
  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'] });
48
+ env: { ...process.env, DOCS_STORAGE_DIR: storage, JSN_DOCS_RELEASE: release || '', JSN_DOCS_HOST: '127.0.0.1', JSN_DOCS_PORT: '0' }, stdio: ['ignore', log, log, 'ipc'] });
47
49
  } finally { fs.closeSync(log); }
48
50
  const next = await new Promise((resolve, reject) => {
49
51
  const timer = setTimeout(() => { child.kill(); reject(new Error('Timed out starting the documentation server.')); }, 10_000);
@@ -61,8 +63,8 @@ export async function ensureLocalDocumentation({ storage = storageDirectory() }
61
63
  throw new AppError('network_error', 'Could not start the local documentation service.', error.message);
62
64
  } finally { fs.rmSync(lock, { recursive: true, force: true }); }
63
65
  }
64
- export async function documentationService(config = {}) {
66
+ export async function documentationService(config = {}, release) {
65
67
  if (process.env.JSN_DOCS_URL) return docsServiceUrl(process.env.JSN_DOCS_URL);
66
- if (config.docs?.source === 'local') return (await ensureLocalDocumentation()).url;
68
+ if (config.docs?.source === 'local') return (await ensureLocalDocumentation({ release })).url;
67
69
  return configuredDocsService(config);
68
70
  }
@@ -7,17 +7,17 @@ import { docsReaderLease } from './locks.js';
7
7
  import { errUsageHint } from '../../errors.js';
8
8
  import { createHash } from 'node:crypto';
9
9
  import { parseFrontmatter } from '../../frontmatter.js';
10
- import { withDocsDb, getDocsDbPath, walkDocs, defaultDocsRoots, getDocsSourceDir } from './db.js';
10
+ import { withDocsDb, resolveDocsDbPath, walkDocs, defaultDocsRoots, getDocsSourceDir } from './db.js';
11
11
  import { encodeText, phasesToBytes, docSurface, DEFAULT_DIM } from './hrr.js';
12
12
 
13
13
  export function refreshDocs(opts = {}) {
14
- const resource = opts.sourceResource || (!opts.roots ? getDocsSourceDir() : null);
14
+ const resource = opts.sourceResource || (!opts.roots ? getDocsSourceDir(opts.release) : null);
15
15
  if (resource) fs.mkdirSync(path.dirname(resource), { recursive: true });
16
16
  const release = resource && !opts.sourceLeaseHeld ? docsReaderLease(resource) : () => {};
17
17
  try { return refreshDocsLocked(opts); } finally { release(); }
18
18
  }
19
19
  function refreshDocsLocked(opts = {}) {
20
- const dbPath = opts.dbPath || getDocsDbPath();
20
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
21
21
  const roots = opts.roots || defaultDocsRoots(opts);
22
22
 
23
23
  if (roots.some(root => (!root.prefix || opts.roots) && (!fs.existsSync(root.dir) || !fs.statSync(root.dir).isDirectory()))) {
@@ -0,0 +1,27 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import Database from 'better-sqlite3';
4
+ import { DEFAULT_DOCS_RELEASE, resolveDocsDbPath, getMeta } from './db.js';
5
+ import { docsReaderLease } from './locks.js';
6
+
7
+ // Local discovery deliberately does not depend on the hosted service.
8
+ export function listDocsReleases() {
9
+ const directory = path.join(path.dirname(resolveDocsDbPath()), 'releases');
10
+ const families = new Set([DEFAULT_DOCS_RELEASE]);
11
+ if (fs.existsSync(directory)) for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
12
+ if (entry.isDirectory() && /^[a-z0-9-]{1,40}$/.test(entry.name)) families.add(entry.name);
13
+ }
14
+ const rows = [];
15
+ for (const release of [...families].sort()) {
16
+ const indexPath = resolveDocsDbPath(release);
17
+ if (!fs.existsSync(indexPath)) continue;
18
+ const unlock = docsReaderLease(indexPath);
19
+ let db;
20
+ try {
21
+ db = new Database(indexPath, { readonly: true, fileMustExist: true });
22
+ rows.push({ release, revision: getMeta(db, 'source_revision') || getMeta(db, 'snapshot_revision'),
23
+ documents: db.prepare('SELECT COUNT(*) AS n FROM docs').get().n, indexPath, default: release === DEFAULT_DOCS_RELEASE });
24
+ } finally { db?.close(); unlock(); }
25
+ }
26
+ return rows;
27
+ }
@@ -1,7 +1,7 @@
1
1
  // CLI search against the docs SQLite database.
2
2
 
3
3
  import fs from 'node:fs';
4
- import { getDocsDbPath, hasEmbeddings, openDocsDb, closeDocsDb, withDocsDb, getMeta } from './db.js';
4
+ import { resolveDocsDbPath, hasEmbeddings, openDocsDb, closeDocsDb, withDocsDb, getMeta } from './db.js';
5
5
  import { sanitizeFts5Query } from './fts.js';
6
6
  import { encodeText, similarity, bytesToPhases, DEFAULT_DIM } from './hrr.js';
7
7
 
@@ -20,7 +20,7 @@ function safeParse(s) {
20
20
  * handle (pass opts.dbPath to target a non-default database — used by tests).
21
21
  */
22
22
  export function getDocByIdOrPath(idOrPath, opts = {}) {
23
- const dbPath = opts.dbPath || getDocsDbPath();
23
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
24
24
  const db = openDocsDb({ dbPath });
25
25
  try {
26
26
  let row;
@@ -44,7 +44,7 @@ export function getDocByIdOrPath(idOrPath, opts = {}) {
44
44
  }
45
45
 
46
46
  export function searchDocs(opts = {}) {
47
- const dbPath = opts.dbPath || getDocsDbPath();
47
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
48
48
  const q = (opts.query || '').toString().trim();
49
49
  if (!q) {
50
50
  throw new Error('Query is required.');
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import http from 'node:http';
6
6
  import { URL } from 'node:url';
7
7
  import Database from 'better-sqlite3';
8
- import { getDocsDbPath, hasEmbeddings, closeDocsDb } from './db.js';
8
+ import { resolveDocsDbPath, hasEmbeddings, closeDocsDb } from './db.js';
9
9
  import { sanitizeFts5Query } from './fts.js';
10
10
  import { encodeText, similarity, bytesToPhases, DEFAULT_DIM } from './hrr.js';
11
11
 
@@ -65,7 +65,7 @@ function serveStatic(req, res, filePath) {
65
65
  }
66
66
 
67
67
  export function serveDocs(opts = {}) {
68
- const dbPath = opts.dbPath || getDocsDbPath();
68
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
69
69
  const port = parseInt(opts.port, 10) || 3000;
70
70
  const host = opts.host || '127.0.0.1';
71
71
 
@@ -254,7 +254,7 @@ export function serveDocs(opts = {}) {
254
254
  if (resolved) return;
255
255
  resolved = true;
256
256
  server.removeListener('error', onError);
257
- process.stderr.write(`ServiceNow docs search listening on http://${host}:${currentPort}\n`);
257
+ process.stderr.write(`ServiceNow docs search for ${opts.release || 'default'} listening on http://${host}:${currentPort}\n`);
258
258
  resolve({ server, port: currentPort, host, dbPath });
259
259
  }
260
260
 
@@ -2,12 +2,14 @@ import http from 'node:http';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import os from 'node:os';
5
+ import { resolveDocsDbPath, resolveDocsRelease } from './db.js';
5
6
  import { fork } from 'node:child_process';
6
7
  import { fileURLToPath } from 'node:url';
7
8
  import { DocumentationIndex, documentationStatus } from './index.js';
8
9
 
9
10
  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
+ export async function startDocumentationServer({ storage = serviceStorage(), host = '127.0.0.1', port = 0, refresh = true, release } = {}) {
12
+ if (release !== undefined) { release = resolveDocsRelease(release); storage = path.dirname(resolveDocsDbPath(release)); }
11
13
  fs.mkdirSync(storage, { recursive: true });
12
14
  let worker;
13
15
  const server = http.createServer((req, res) => {
@@ -16,15 +18,16 @@ export async function startDocumentationServer({ storage = serviceStorage(), hos
16
18
  let index;
17
19
  try {
18
20
  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 (url.pathname === '/up') return send(200, { service: 'jsn-docs', release });
22
+ if (release && url.searchParams.has('release') && url.searchParams.get('release') !== release) return send(400, { error: `This documentation server serves ${release}.`, hint: `Use --release ${release}.` });
23
+ if (url.pathname === '/api/docs/status') return send(200, { ...documentationStatus(storage), release });
21
24
  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);
25
+ index = new DocumentationIndex(storage, release);
23
26
  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 }));
27
+ 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 }), release });
25
28
  const revision = index.revision();
26
29
  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) }) });
30
+ return send(200, { release, revision, document: index.document({ path: params.path, id: url.pathname.split('/').at(-1) }) });
28
31
  } catch (error) { send(error.status || 503, { error: error.status ? error.message : 'Documentation search is temporarily unavailable.' }); }
29
32
  finally { index?.close(); }
30
33
  });
@@ -36,7 +39,7 @@ export async function startDocumentationServer({ storage = serviceStorage(), hos
36
39
  const log = fs.openSync(path.join(storage, 'sync.log'), 'a', 0o600);
37
40
  try {
38
41
  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: [],
42
+ env: { ...process.env, DOCS_STORAGE_DIR: storage, JSN_DOCS_RELEASE: release || '' }, stdio: ['ignore', log, log, 'ipc'], execArgv: [],
40
43
  });
41
44
  worker.on('exit', () => { worker = null; });
42
45
  worker.on('error', () => { worker = null; });
@@ -52,9 +55,9 @@ export async function startDocumentationServer({ storage = serviceStorage(), hos
52
55
  }
53
56
  if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
54
57
  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
+ const { server, url } = await startDocumentationServer({ host: process.env.JSN_DOCS_HOST || '127.0.0.1', port: Number(process.env.JSN_DOCS_PORT || 0), release: process.env.JSN_DOCS_RELEASE || undefined });
59
+ if (process.send) { process.send({ url, pid: process.pid, release: process.env.JSN_DOCS_RELEASE || undefined }); process.disconnect(); }
60
+ else process.stdout.write(`Documentation service${process.env.JSN_DOCS_RELEASE ? ` for ${process.env.JSN_DOCS_RELEASE}` : ''} listening at ${url}\n`);
58
61
  for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => { server.close(); });
59
62
  } catch (error) { process.stderr.write(error.message + '\n'); process.exitCode = 1; }
60
63
  }
@@ -6,10 +6,10 @@ import { gzipSync } from 'node:zlib';
6
6
  import Database from 'better-sqlite3';
7
7
  import { validateDatabase, validateManifest } from './snapshot.js';
8
8
 
9
- export async function publishServiceSnapshot(storage) {
9
+ export async function publishServiceSnapshot(storage, { dbPath = path.join(storage, 'docs.sqlite3'), release } = {}) {
10
10
  const output = path.join(storage, 'snapshots');
11
11
  fs.mkdirSync(output, { recursive: true });
12
- const db = new Database(path.join(storage, 'docs.sqlite3'), { readonly: true, fileMustExist: true });
12
+ const db = new Database(dbPath, { readonly: true, fileMustExist: true });
13
13
  const temporary = fs.mkdtempSync(path.join(output, '.export-'));
14
14
  try {
15
15
  const revision = db.prepare("SELECT value FROM meta WHERE key='source_revision'").get()?.value;
@@ -31,7 +31,7 @@ export async function publishServiceSnapshot(storage) {
31
31
  const compressed = gzipSync(bytes);
32
32
  const sha256 = createHash('sha256').update(compressed).digest('hex');
33
33
  const name = `docs-${revision}-${sha256}.sqlite.gz`;
34
- const manifest = validateManifest({ format: 1, schema: 1, cliCompatibility: 'docs-schema-1', revision,
34
+ const manifest = validateManifest({ format: 1, schema: 1, cliCompatibility: 'docs-schema-1', revision, ...(release ? { release } : {}),
35
35
  documents, sha256, compressedBytes: compressed.length, databaseBytes: bytes.length,
36
36
  builtAt: new Date().toISOString(), url: `https://jsn.jace.pro/docs-index/artifacts/${name}` });
37
37
  fs.writeFileSync(path.join(temporary, name), compressed);
@@ -4,7 +4,8 @@ import path from 'node:path';
4
4
  import { createHash, randomUUID } from 'node:crypto';
5
5
  import { gzipSync, gunzipSync } from 'node:zlib';
6
6
  import Database from 'better-sqlite3';
7
- import { getDocsDbPath, getDocsCacheDir } from './db.js';
7
+ import { resolveDocsDbPath, resolveDocsRelease, DEFAULT_DOCS_RELEASE } from './db.js';
8
+ import { docsServiceUrl } from './client.js';
8
9
  import { docsReaderLease } from './locks.js';
9
10
  import { ingestDocs } from './ingest.js';
10
11
  import { installDatabase } from './replace.js';
@@ -36,7 +37,7 @@ export function validateDatabase(filename) {
36
37
  return count;
37
38
  } finally { db.close(); }
38
39
  }
39
- export function buildSnapshot({ docsDir, outputDir, revision, artifactBaseURL, embed = true }) {
40
+ export function buildSnapshot({ docsDir, outputDir, revision, artifactBaseURL, embed = true, release }) {
40
41
  if (!/^[a-f0-9]{7,64}$/.test(revision || '')) throw new Error('A source commit revision is required');
41
42
  fs.mkdirSync(outputDir, { recursive: true });
42
43
  const temporary = fs.mkdtempSync(path.join(outputDir, '.build-'));
@@ -52,7 +53,7 @@ export function buildSnapshot({ docsDir, outputDir, revision, artifactBaseURL, e
52
53
  const documents = validateDatabase(filename);
53
54
  const bytes = fs.readFileSync(filename), compressed = gzipSync(bytes);
54
55
  const name = `docs-schema-${SNAPSHOT_SCHEMA}-${revision}.sqlite.gz`;
55
- const manifest = validateManifest({ format: 1, schema: SNAPSHOT_SCHEMA, cliCompatibility: 'docs-schema-1', revision,
56
+ const manifest = validateManifest({ format: 1, schema: SNAPSHOT_SCHEMA, cliCompatibility: 'docs-schema-1', revision, ...(release ? { release: resolveDocsRelease(release) } : {}),
56
57
  sha256: digest(compressed), compressedBytes: compressed.length, databaseBytes: bytes.length,
57
58
  documents, buildSeconds: result.secs, builtAt: new Date().toISOString(), url: new URL(name, artifactBaseURL.endsWith('/') ? artifactBaseURL : artifactBaseURL + '/').href });
58
59
  const artifact = path.join(outputDir, name);
@@ -68,7 +69,7 @@ export function buildSnapshot({ docsDir, outputDir, revision, artifactBaseURL, e
68
69
  async function download(url, maxBytes, fetchFn, timeout = 600000) {
69
70
  const response = await fetchFn(url, { signal: AbortSignal.timeout(timeout) });
70
71
  if (response.url && new URL(response.url).protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(new URL(response.url).hostname)) throw new Error('Docs download redirected to insecure transport');
71
- if (!response.ok) throw new Error(`Docs download rejected (HTTP ${response.status})`);
72
+ if (!response.ok) throw Object.assign(new Error(`Docs download rejected (HTTP ${response.status})`), { status: response.status });
72
73
  if (Number(response.headers.get('content-length')) > maxBytes) { await response.body?.cancel(); throw new Error('Docs download exceeds size limit'); }
73
74
  const parts = []; let size = 0;
74
75
  for await (const chunk of response.body) {
@@ -83,11 +84,30 @@ export async function fetchManifest(url = DEFAULT_MANIFEST_URL, { fetchFn = fetc
83
84
  validateManifest({ format: 1, schema: 1, cliCompatibility: 'docs-schema-1', revision: 'abcdef0', sha256: '0'.repeat(64), compressedBytes: 1, databaseBytes: 1, url });
84
85
  return validateManifest(JSON.parse((await download(url, 65536, fetchFn, 15000)).toString('utf8')));
85
86
  }
87
+ export function validateManifestRelease(manifest, release, legacy = false) {
88
+ if (manifest.release !== undefined && manifest.release !== release) throw new Error(`Docs snapshot release ${manifest.release} does not match requested release ${release}; existing index retained`);
89
+ if (manifest.release === undefined && (!legacy || release !== DEFAULT_DOCS_RELEASE)) throw new Error(`Docs snapshot manifest must declare release ${release}; existing index retained`);
90
+ return manifest;
91
+ }
92
+ export async function fetchReleaseManifest({ release = DEFAULT_DOCS_RELEASE, serviceUrl, manifestURL, fetchFn = fetch } = {}) {
93
+ release = resolveDocsRelease(release);
94
+ if (manifestURL) return { manifest: validateManifestRelease(await fetchManifest(manifestURL, { fetchFn }), release, release === DEFAULT_DOCS_RELEASE), manifestURL };
95
+ const service = docsServiceUrl(serviceUrl);
96
+ const familyURL = new URL(`docs-index/releases/${release}/manifest.json`, service).href;
97
+ try { return { manifest: validateManifestRelease(await fetchManifest(familyURL, { fetchFn }), release), manifestURL: familyURL }; }
98
+ catch (error) {
99
+ if (release !== DEFAULT_DOCS_RELEASE || error.status !== 404) throw error;
100
+ const legacyURL = new URL('docs-index/manifest.json', service).href;
101
+ return { manifest: validateManifestRelease(await fetchManifest(legacyURL, { fetchFn }), release, true), manifestURL: legacyURL };
102
+ }
103
+ }
86
104
  export function snapshotEstimate(manifest) {
87
105
  return `${(manifest.compressedBytes / 1048576).toFixed(1)} MiB; estimated ${Math.max(1, Math.ceil(manifest.compressedBytes / 5242880))} seconds at 5 MiB/s plus verification (actual time varies)`;
88
106
  }
89
- export async function installSnapshot({ manifestURL = DEFAULT_MANIFEST_URL, manifest, dbPath = getDocsDbPath(), fetchFn = fetch } = {}) {
107
+ export async function installSnapshot({ release = DEFAULT_DOCS_RELEASE, manifestURL = DEFAULT_MANIFEST_URL, manifest, dbPath = resolveDocsDbPath(release), fetchFn = fetch } = {}) {
108
+ release = resolveDocsRelease(release);
90
109
  manifest = manifest ? validateManifest(manifest) : await fetchManifest(manifestURL, { fetchFn });
110
+ validateManifestRelease(manifest, release, release === DEFAULT_DOCS_RELEASE && !new URL(manifestURL).pathname.includes('/docs-index/releases/'));
91
111
  const compressed = await download(manifest.url, manifest.compressedBytes, fetchFn);
92
112
  if (compressed.length !== manifest.compressedBytes || digest(compressed) !== manifest.sha256) throw new Error('Docs snapshot checksum/size mismatch; existing index retained');
93
113
  const bytes = gunzipSync(compressed, { maxOutputLength: manifest.databaseBytes });
@@ -106,10 +126,10 @@ export async function installSnapshot({ manifestURL = DEFAULT_MANIFEST_URL, mani
106
126
  fs.writeFileSync(receiptStage, JSON.stringify({ ...manifest, manifestURL, checkedAt: Date.now() }), { mode: 0o600 });
107
127
  installDatabase(staged, dbPath, { afterInstall: () => fs.renameSync(receiptStage, receipt) });
108
128
  } finally { fs.rmSync(receiptStage, { force: true }); }
109
- return { revision: manifest.revision, documents: manifest.documents, dbPath, source: 'snapshot' };
129
+ return { release, revision: manifest.revision, documents: manifest.documents, dbPath, source: 'snapshot' };
110
130
  } finally { fs.rmSync(staged, { force: true }); }
111
131
  }
112
- export function rollbackSnapshot(dbPath = getDocsDbPath()) {
132
+ export function rollbackSnapshot(dbPath = resolveDocsDbPath()) {
113
133
  const previous = `${dbPath}.previous`;
114
134
  if (!fs.existsSync(previous)) throw new Error('No previous docs snapshot is available');
115
135
  validateDatabase(previous);
@@ -118,13 +138,14 @@ export function rollbackSnapshot(dbPath = getDocsDbPath()) {
118
138
  finally { fs.rmSync(staged, { force: true }); }
119
139
  return { dbPath, rolledBack: true };
120
140
  }
121
- export function docsSnapshotStatus() {
122
- const receipt = path.join(getDocsCacheDir(), 'docs.db.snapshot.json');
141
+ export function docsSnapshotStatus(family) {
142
+ const dbPath = resolveDocsDbPath(family);
143
+ const receipt = `${dbPath}.snapshot.json`;
123
144
  let release, db;
124
145
  try {
125
- release = docsReaderLease(getDocsDbPath());
146
+ release = docsReaderLease(dbPath);
126
147
  const value = JSON.parse(fs.readFileSync(receipt, 'utf8'));
127
- db = new Database(getDocsDbPath(), { readonly: true, fileMustExist: true });
148
+ db = new Database(dbPath, { readonly: true, fileMustExist: true });
128
149
  return db.prepare("SELECT value FROM meta WHERE key='snapshot_revision'").get()?.value === value.revision ? value : null;
129
150
  } catch { return null; } finally { db?.close(); release?.(); }
130
151
  }
@@ -10,6 +10,7 @@ import { ingestDocs } from './ingest.js';
10
10
  import { refreshDocs } from './refresh.js';
11
11
  import { installSnapshot } from './snapshot.js';
12
12
  import { publishServiceSnapshot } from './service-snapshot.js';
13
+ import { DEFAULT_DOCS_RELEASE, resolveDocsDbPath, resolveDocsRelease } from './db.js';
13
14
 
14
15
  const defaultStorage = path.join(process.env.JSN_DATA_HOME || path.join(os.homedir(), '.jsn'), 'docs-service');
15
16
  function git(args) {
@@ -25,10 +26,11 @@ function writeStatus(storage, status) {
25
26
  async function performSync(options = {}) {
26
27
  const storage = options.storage || process.env.DOCS_STORAGE_DIR || defaultStorage;
27
28
  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
+ const family = options.release || process.env.JSN_DOCS_RELEASE;
30
+ const branch = family ? resolveDocsRelease(family) : options.branch || process.env.DOCS_SOURCE_BRANCH || DEFAULT_DOCS_RELEASE;
29
31
  fs.mkdirSync(storage, { recursive: true });
30
32
  const repo = path.join(storage, 'source');
31
- const live = path.join(storage, 'docs.sqlite3');
33
+ const live = family ? resolveDocsDbPath(family) : path.join(storage, 'docs.sqlite3');
32
34
  const staging = path.join(storage, `build-${randomUUID()}.sqlite3`);
33
35
  let previous = {};
34
36
  try { previous = JSON.parse(fs.readFileSync(path.join(storage, 'status.json'), 'utf8')); } catch { /* first run */ }
@@ -43,7 +45,7 @@ async function performSync(options = {}) {
43
45
  try {
44
46
  // Only the first installation uses the hosted seed. Updates always use GitHub.
45
47
  // 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') {
48
+ if (!fs.existsSync(live) && ((!options.source && !process.env.DOCS_SOURCE_URL) || options.manifestURL) && branch === DEFAULT_DOCS_RELEASE) {
47
49
  try {
48
50
  const seed = await installSnapshot({ dbPath: live,
49
51
  manifestURL: options.manifestURL || process.env.DOCS_BOOTSTRAP_MANIFEST_URL,
@@ -67,7 +69,7 @@ async function performSync(options = {}) {
67
69
  try { current = db.prepare("SELECT value FROM meta WHERE key='source_revision'").get()?.value; }
68
70
  finally { db.close(); }
69
71
  if (remote && current === remote) {
70
- await publishServiceSnapshot(storage);
72
+ await publishServiceSnapshot(storage, { dbPath: live, release: family });
71
73
  const status = { ...previous, state: 'ready', revision: current, checkedAt: new Date().toISOString(), startedAt, error: null, changed: false };
72
74
  writeStatus(storage, status);
73
75
  return status;
@@ -97,7 +99,7 @@ async function performSync(options = {}) {
97
99
  } finally { db.close(); }
98
100
  }
99
101
  if (oldRevision === revision && !options.force) {
100
- await publishServiceSnapshot(storage);
102
+ await publishServiceSnapshot(storage, { dbPath: live, release: family });
101
103
  const status = { ...previous, state: 'ready', revision, checkedAt: new Date().toISOString(), startedAt, error: null, changed: false };
102
104
  writeStatus(storage, status);
103
105
  return status;
@@ -121,7 +123,7 @@ async function performSync(options = {}) {
121
123
  db.pragma('journal_mode = DELETE');
122
124
  } finally { db.close(); }
123
125
  fs.renameSync(staging, live);
124
- await publishServiceSnapshot(storage);
126
+ await publishServiceSnapshot(storage, { dbPath: live, release: family });
125
127
  const status = { state: 'ready', revision, documents: count, startedAt, checkedAt: new Date().toISOString(), publishedAt: new Date().toISOString(), changed: true, error: null, result };
126
128
  writeStatus(storage, status);
127
129
  return status;
@@ -4,15 +4,14 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { docsInstallLease, docsHaveReaders } from './locks.js';
6
6
  import { spawnSync } from 'node:child_process';
7
- import { getDocsSourceDir, getDocsSourceMarkdownDir, getDocsDbPath, docsDbExists } from './db.js';
7
+ import { getDocsSourceDir, getDocsSourceMarkdownDir, resolveDocsDbPath, resolveDocsRelease, withDocsDb, setMeta } from './db.js';
8
8
  import { ingestDocs } from './ingest.js';
9
9
  import { refreshDocs } from './refresh.js';
10
10
 
11
11
  const REPO_URL = 'https://github.com/ServiceNow/ServiceNowDocs';
12
- const BRANCH = 'australia';
13
12
 
14
13
  function git(args, cwd, stdio = 'inherit') {
15
- const r = spawnSync('git', args, { cwd, stdio });
14
+ const r = spawnSync('git', args, { cwd, stdio: stdio === 'inherit' ? ['ignore', 2, 2] : stdio });
16
15
  if (r.error && r.error.code === 'ENOENT') {
17
16
  throw new Error('git is not installed. Install git to sync docs, or download the docs repo manually.');
18
17
  }
@@ -22,7 +21,7 @@ function git(args, cwd, stdio = 'inherit') {
22
21
  }
23
22
 
24
23
  export function syncDocs(opts = {}) {
25
- const repoDir = opts.repoDir || getDocsSourceDir();
24
+ const repoDir = opts.repoDir || getDocsSourceDir(opts.release);
26
25
  fs.mkdirSync(path.dirname(repoDir), { recursive: true });
27
26
  const release = docsInstallLease(repoDir);
28
27
  try {
@@ -31,9 +30,10 @@ export function syncDocs(opts = {}) {
31
30
  } finally { release(); }
32
31
  }
33
32
  function syncDocsLocked(opts = {}) {
34
- const repoDir = opts.repoDir || getDocsSourceDir();
35
- const markdownDir = opts.markdownDir || getDocsSourceMarkdownDir();
36
- const dbPath = opts.dbPath || getDocsDbPath();
33
+ const repoDir = opts.repoDir || getDocsSourceDir(opts.release);
34
+ const markdownDir = opts.markdownDir || getDocsSourceMarkdownDir(opts.release);
35
+ const dbPath = opts.dbPath || resolveDocsDbPath(opts.release);
36
+ const branch = resolveDocsRelease(opts.release);
37
37
  const embed = opts.embed !== false;
38
38
  const noIngest = opts.noIngest === true;
39
39
 
@@ -53,14 +53,16 @@ function syncDocsLocked(opts = {}) {
53
53
 
54
54
  if (!initialStatus.clone) {
55
55
  process.stderr.write(`Updating existing clone at ${repoDir} ...\n`);
56
- git(['-C', repoDir, 'pull', '--ff-only'], repoDir, 'inherit');
56
+ git(['-C', repoDir, 'fetch', 'origin', branch], repoDir, 'inherit');
57
+ git(['-C', repoDir, 'checkout', branch], repoDir, 'inherit');
58
+ git(['-C', repoDir, 'merge', '--ff-only', 'FETCH_HEAD'], repoDir, 'inherit');
57
59
  } else {
58
60
  fs.mkdirSync(path.dirname(repoDir), { recursive: true });
59
- process.stderr.write(`Cloning ${REPO_URL} (branch ${BRANCH}) into ${repoDir} ...\n`);
61
+ process.stderr.write(`Cloning ${REPO_URL} (branch ${branch}) into ${repoDir} ...\n`);
60
62
  git([
61
63
  'clone',
62
64
  '--depth', '1',
63
- '--branch', BRANCH,
65
+ '--branch', branch,
64
66
  '--config', 'core.longpaths=true',
65
67
  REPO_URL,
66
68
  repoDir,
@@ -71,18 +73,25 @@ function syncDocsLocked(opts = {}) {
71
73
  throw new Error(`Expected markdown folder not found at ${markdownDir}.`);
72
74
  }
73
75
 
76
+ const revisionResult = spawnSync('git', ['-C', repoDir, 'rev-parse', 'HEAD'], { encoding: 'utf8' });
77
+ if (revisionResult.status !== 0) throw new Error('Could not read documentation source revision.');
78
+ const revision = revisionResult.stdout.trim();
79
+ const recordRevision = () => withDocsDb({ dbPath }, db => { setMeta(db, 'source_revision', revision); setMeta(db, 'source_branch', branch); });
80
+
74
81
  if (noIngest) {
75
82
  return { repoDir, markdownDir, dbPath, ingested: false, note: 'Run without --no-ingest to build the index.' };
76
83
  }
77
84
 
78
85
  // If the DB already exists, use incremental refresh. Otherwise, full ingest.
79
- if (docsDbExists()) {
86
+ if (fs.existsSync(dbPath)) {
80
87
  process.stderr.write(`Docs DB found — running incremental refresh...\n`);
81
- const result = refreshDocs({ docsDir: markdownDir, dbPath, sourceResource: repoDir, sourceLeaseHeld: true });
82
- return { repoDir, markdownDir, dbPath, ingested: true, incremental: true, ...result };
88
+ const result = refreshDocs({ release: branch, docsDir: markdownDir, dbPath, sourceResource: repoDir, sourceLeaseHeld: true });
89
+ recordRevision();
90
+ return { repoDir, markdownDir, dbPath, revision, ingested: true, incremental: true, ...result };
83
91
  }
84
92
 
85
93
  process.stderr.write('No existing DB — running full ingest...\n');
86
- const result = ingestDocs({ docsDir: markdownDir, dbPath, embed, sourceResource: repoDir, sourceLeaseHeld: true });
87
- return { repoDir, markdownDir, dbPath, ingested: true, incremental: false, ...result };
94
+ const result = ingestDocs({ release: branch, docsDir: markdownDir, dbPath, embed, sourceResource: repoDir, sourceLeaseHeld: true });
95
+ recordRevision();
96
+ return { repoDir, markdownDir, dbPath, revision, ingested: true, incremental: false, ...result };
88
97
  }