@jacebenson/jsn 4.5.0 → 4.5.1-dev.117.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.
@@ -1,300 +1,84 @@
1
- // jsn docs — ServiceNow documentation search.
2
-
3
- import fs from 'node:fs';
4
- import path from 'node:path';
5
- import net from 'node:net';
6
- import process from 'node:process';
1
+ // Documentation search always uses the same API, hosted or self-hosted.
2
+ import { searchHostedDocs, getHostedDoc, getHostedDocsStatus } from './client.js';
3
+ import { documentationService } from './local.js';
4
+ import { startDocumentationServer } from './server.js';
7
5
  import { declareCapabilities } from '../../capabilities.js';
8
- import { formatCommandList } from '../../helpers.js';
6
+ import { AppError } from '../../errors.js';
9
7
 
10
8
  declareCapabilities('docs', { noInstance: true, skipDailyChecks: true });
11
9
 
12
- function formatBytes(n) {
13
- if (n == null) return '-';
14
- if (n < 1024) return `${n} B`;
15
- if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
16
- return `${(n / (1024 * 1024)).toFixed(1)} MB`;
10
+ async function search(argv, app) {
11
+ 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
+ for (const row of result.results) {
15
+ lines.push(`[${row.id}] ${row.title || row.path}`, ` ${row.path}`);
16
+ const summary = String(row.summary || row.snippet || '').replace(/\s+/g, ' ').trim();
17
+ if (summary) lines.push(` ${summary}`);
18
+ lines.push('');
19
+ }
20
+ const next = result.offset + result.count;
21
+ if (result.count && next < result.total && next <= 10000) lines.push(`… ${result.total - next} more results (use --offset ${next} for the next page)`);
22
+ if (!result.count) lines.push('No matching documents. Try fewer words or a different term.');
23
+ 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}"` });
25
+ }
26
+ async function read(argv, app) {
27
+ const maxLines = argv.lines ?? 80;
28
+ 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) });
30
+ const title = row.title || row.path;
31
+ const lines = row.body.split('\n');
32
+ 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}` });
17
34
  }
18
35
 
19
36
  export function docsCmd(wrap) {
20
37
  return {
21
- command: 'docs [subcommand]',
22
- describe: 'Search ServiceNow documentation locally (install, sync, status, search, serve)',
23
- builder: (yargs) => {
24
- return yargs
25
- .command({ command: 'install', describe: 'Install optional docs: raw GitHub files or a verified prebuilt searchable database',
26
- builder: y => y.option('source', { type: 'string', choices: ['snapshot', 'github', 'skip'], describe: 'Explicit source; raw GitHub estimated ~5 minutes; snapshot estimate comes from manifest' })
27
- .option('manifest-url', { type: 'string', describe: 'HTTPS snapshot manifest mirror' }),
28
- handler: wrap(async (argv, app) => {
29
- const { installDocumentation, offerDocumentation } = await import('./install.js');
30
- const { canUsePicker } = await import('../../helpers.js');
31
- const result = argv.source ? await installDocumentation(argv.source, { manifestURL: argv['manifest-url'] })
32
- : canUsePicker(app, argv) ? await offerDocumentation(app, argv) : await installDocumentation(undefined);
33
- app.ok(result, { summary: result.skipped ? 'Documentation skipped' : 'Documentation installed' });
34
- }),
35
- })
36
- .command({ command: 'rollback', describe: 'Restore the previously installed local docs database', handler: wrap(async (_argv, app) => {
37
- const { rollbackSnapshot } = await import('./snapshot.js');
38
- app.ok(rollbackSnapshot(), { summary: 'Previous documentation index restored' });
39
- }) })
40
- .command({
41
- command: 'sync',
42
- describe: 'Clone/update ServiceNowDocs and build the docs.db index',
43
- builder: (y) => y
44
- .option('no-embed', { type: 'boolean', describe: 'Skip HRR semantic embeddings' })
45
- .option('no-ingest', { type: 'boolean', describe: 'Clone/pull only; do not rebuild index' }),
46
- handler: wrap(async (argv, app) => {
47
- const { getDocsDbPath, getDocsSourceMarkdownDir } = await import('./db.js');
48
- const { syncDocs } = await import('./sync.js');
49
- const result = syncDocs({
50
- markdownDir: getDocsSourceMarkdownDir(),
51
- dbPath: getDocsDbPath(),
52
- embed: argv['no-embed'] !== true,
53
- noIngest: argv['no-ingest'] === true,
54
- });
55
- app.ok(result, { summary: 'Docs sync complete' });
56
- }),
57
- })
58
- .command({
59
- command: 'status',
60
- describe: 'Show docs database status',
61
- handler: wrap(async (argv, app) => {
62
- const { getDocsDbPath, getDocsSourceDir, getDocsSourceMarkdownDir, docsDbExists, withDocsDb, getDocsIndexStats } = await import('./db.js');
63
- const dbPath = getDocsDbPath();
64
- const repoDir = getDocsSourceDir();
65
- const markdownDir = getDocsSourceMarkdownDir();
66
- const downloaded = fs.existsSync(path.join(repoDir, '.git')) && fs.existsSync(markdownDir);
67
- const dbExists = docsDbExists();
68
-
69
- let state, embedded, documents, bundles, docTypes, syncedAt, dbSize;
70
- if (dbExists) {
71
- const stats = withDocsDb({}, (db) => getDocsIndexStats(db));
72
- ({ documents, bundles, docTypes, syncedAt } = stats);
73
- const stat = fs.statSync(dbPath);
74
- dbSize = stat.size;
75
-
76
- embedded = stats.embeddedCount >= documents && documents > 0;
77
- if (embedded) state = 'ready';
78
- else if (documents > 0) state = 'indexed (not embedded)';
79
- else state = 'empty';
80
- } else {
81
- state = downloaded ? 'not indexed' : 'not downloaded';
82
- embedded = false;
83
- }
84
-
85
- // Quick probe to see if the server is running on the default port.
86
- const served = await new Promise((resolve) => {
87
- const sock = new net.Socket();
88
- sock.setTimeout(500);
89
- sock.on('connect', () => { sock.destroy(); resolve(true); });
90
- sock.on('error', () => resolve(false));
91
- sock.on('timeout', () => { sock.destroy(); resolve(false); });
92
- sock.connect(3000, '127.0.0.1');
93
- });
94
-
95
- const { docsSnapshotStatus } = await import('./snapshot.js');
96
- const snapshot = docsSnapshotStatus();
97
- let available = null;
98
- try { available = JSON.parse(fs.readFileSync(`${dbPath}.available.json`, 'utf8')); } catch { /* No background update information. */ }
99
- app.ok({
100
- state,
101
- ...(snapshot ? { snapshot: { revision: snapshot.revision, schema: snapshot.schema } } : {}),
102
- ...(snapshot && available?.installed === snapshot.revision && available.revision !== snapshot.revision ? { updateAvailable: { revision: available.revision, command: 'jsn docs install --source snapshot' } } : {}),
103
- downloaded: { ok: downloaded, path: repoDir },
104
- db: { ok: dbExists, path: dbPath },
105
- embedded: { ok: embedded },
106
- ...(documents != null && { documents, bundles, docTypes, syncedAt: syncedAt ? new Date(parseInt(syncedAt, 10)).toISOString() : null }),
107
- ...(dbSize != null && { dbSizeHuman: formatBytes(dbSize) }),
108
- ...(served && { served: 'http://127.0.0.1:3000' }),
109
- }, { summary: `Docs database: ${state}` });
110
- }),
111
- })
112
- .command({
113
- command: 'search <query>',
114
- describe: 'Search docs (FTS5 + optional HRR hybrid rerank)',
115
- builder: (y) => y
116
- .positional('query', { type: 'string', describe: 'Search query' })
117
- .option('limit', { type: 'number', default: 20, describe: 'Max results' })
118
- .option('offset', { type: 'number', default: 0, describe: 'Result offset' })
119
- .option('bundle', { type: 'string', describe: 'Filter by bundle' })
120
- .option('doc-type', { type: 'string', describe: 'Filter by doc type' })
121
- .option('mode', { type: 'string', choices: ['keyword', 'hybrid'], default: 'hybrid', describe: 'Search mode' }),
122
- handler: wrap(async (argv, app) => {
123
- const { ensureDocumentation } = await import('./install.js');
124
- await ensureDocumentation(app, argv);
125
- const { searchDocs } = await import('./search.js');
126
- const result = searchDocs({
127
- query: argv.query,
128
- limit: argv.limit,
129
- offset: argv.offset,
130
- bundle: argv.bundle,
131
- docType: argv['doc-type'],
132
- mode: argv.mode,
133
- });
134
-
135
- // Build a readable text blob for styled TTY output.
136
- const lines = [];
137
- for (const r of result.results) {
138
- const title = r.title || r.path || '(untitled)';
139
- const snippet = (r.snippet || r.body || '')
140
- .replace(/\\n/g, ' ')
141
- .replace(/\s+/g, ' ')
142
- .trim()
143
- .substring(0, 200);
144
- lines.push(`[${r.id}] ${title}`);
145
- if (snippet) lines.push(` ${snippet}`);
146
- lines.push('');
147
- }
148
-
149
- const hasMore = result.total > result.count;
150
- if (hasMore) {
151
- const nextOffset = (result.count + (argv.offset || 0));
152
- lines.push(`… ${result.total - result.count} more results (use --offset ${nextOffset} for next page)`);
153
- }
154
-
155
- app.ok({
156
- _formatted: lines.join('\n'),
157
- query: result.query,
158
- mode: result.mode,
159
- total: result.total,
160
- count: result.count,
161
- results: result.results,
162
- }, { summary: `${result.count} of ${result.total} result(s) for "${result.query}" (${result.mode})` });
163
- }),
164
- })
165
- .command({
166
- command: 'show <id-or-path>',
167
- describe: 'Show a documentation page by id or path',
168
- builder: (y) => y
169
- .positional('id-or-path', { type: 'string', describe: 'Document id (number) or file path' })
170
- .option('lines', { type: 'number', default: 80, describe: 'Lines of body to show in terminal (use --json for full content)' }),
171
- handler: wrap(async (argv, app) => {
172
- const { getDocByIdOrPath } = await import('./search.js');
173
- const idOrPath = argv['id-or-path'];
174
- const row = getDocByIdOrPath(idOrPath);
175
-
176
- if (!row) {
177
- throw Object.assign(new Error(`No doc found for "${idOrPath}"`), { code: 'not_found' });
178
- }
179
-
180
- let fm = {};
181
- try { fm = JSON.parse(row.frontmatter || '{}'); } catch { /* ignore */ }
182
-
183
- const title = row.title || fm.title || row.path || '(untitled)';
184
- const header = `${title}\n${'─'.repeat(Math.min(title.length, 80))}`;
185
- const body = row.body || '';
186
- const bodyLines = body.split('\n');
187
- const truncated = bodyLines.length > argv.lines;
188
- const preview = bodyLines.slice(0, argv.lines).join('\n');
189
- const hint = truncated ? `\n\n… ${bodyLines.length - argv.lines} more lines (use --lines ${bodyLines.length} or --json for full content)` : '';
190
-
191
- app.ok({
192
- id: row.id,
193
- path: row.path,
194
- title: row.title,
195
- bundle: row.bundle,
196
- release: row.release,
197
- canonical_url: fm.canonical_url || null,
198
- body,
199
- _formatted: `${header}\n\n${preview}${hint}`,
200
- }, { summary: `Doc ${row.id}: ${title}` });
201
- }),
202
- })
203
- .command({
204
- command: 'serve',
205
- describe: 'Start the docs search web UI',
206
- builder: (y) => y
207
- .option('port', { type: 'number', default: 3000, describe: 'HTTP port' })
208
- .option('host', { type: 'string', default: '127.0.0.1', describe: 'Bind address' })
209
- .option('expose', { type: 'boolean', default: false, describe: 'Bind to 0.0.0.0 to expose on the network' }),
210
- handler: wrap(async (argv, _app) => {
211
- const { serveDocs } = await import('./serve.js');
212
- try {
213
- const host = argv.expose ? '0.0.0.0' : argv.host;
214
- await serveDocs({ port: argv.port, host });
215
- } catch (err) {
216
- process.stderr.write(`Error: ${err.message}\n`);
217
- process.exit(1);
218
- }
219
- }),
220
- })
221
- .command({
222
- command: 'embed',
223
- describe: 'Backfill or refresh HRR semantic embeddings',
224
- handler: wrap(async (argv, app) => {
225
- const { embedDocs } = await import('./embed.js');
226
- const result = embedDocs();
227
- app.ok(result, { summary: `Embedded ${result.embedded} of ${result.total} docs` });
228
- }),
229
- })
230
- .command({
231
- command: 'refresh',
232
- describe: 'Incrementally refresh docs.db from existing source clone',
233
- handler: wrap(async (argv, app) => {
234
- const { getDocsSourceMarkdownDir } = await import('./db.js');
235
- const { refreshDocs } = await import('./refresh.js');
236
- const result = refreshDocs({ docsDir: getDocsSourceMarkdownDir() });
237
- app.ok(result, { summary: `Refresh complete: +${result.added} ~${result.updated} -${result.removed} =${result.unchanged}` });
238
- }),
239
- })
240
- .command({
241
- command: 'community <action>',
242
- describe: 'Sync ServiceNow Community articles into the searchable docs index',
243
- builder: (y) => y
244
- .command({
245
- command: 'sync',
246
- describe: 'Fetch community hub pages (+ linked articles with --expand) and index them',
247
- builder: (yy) => yy
248
- .option('expand', { type: 'boolean', describe: 'Also fetch every linked community article found on the hub pages' })
249
- .option('force', { type: 'boolean', describe: 'Re-fetch articles already downloaded' })
250
- .option('sources', { type: 'string', describe: 'Path to a community-sources.json (default: bundled)' })
251
- .option('delay-ms', { type: 'number', describe: 'Delay between article fetches (default: 500)' }),
252
- handler: wrap(async (argv, app) => {
253
- const { syncCommunity } = await import('./community.js');
254
- const result = await syncCommunity({
255
- sourcesFile: argv.sources,
256
- expand: argv.expand === true,
257
- force: argv.force === true,
258
- delayMs: argv['delay-ms'],
259
- });
260
- app.ok(result, {
261
- summary: `Community sync: ${result.hubs.length} hub(s), ${result.articles.length} article(s), ${result.skipped.length} skipped, ${result.errors.length} error(s)`,
262
- });
263
- }),
264
- })
265
- .command({
266
- command: 'list',
267
- describe: 'List community docs currently in the index',
268
- handler: wrap(async (argv, app) => {
269
- const { listCommunityDocs } = await import('./community.js');
270
- const result = listCommunityDocs();
271
- const lines = result.docs.map((d) => `[${d.id}] ${d.title || d.path} (${d.doc_type})`);
272
- app.ok({
273
- _formatted: lines.length ? lines.join('\n') : '(no community docs indexed yet)',
274
- total: result.total,
275
- docs: result.docs,
276
- }, { summary: `${result.total} community doc(s) indexed` });
277
- }),
278
- })
279
- .demandCommand(1, 'Specify an action: sync or list'),
280
- });
281
- },
282
- handler: wrap(async (argv, app) => {
283
- const { getDocsDbPath } = await import('./db.js');
284
- const subcommands = argv.subcommands || [];
285
- const summary = 'jsn docs — optional local documentation (install, sync, status, search, show, serve, rollback).';
286
- app.ok({
287
- command: 'docs',
288
- subcommands,
289
- _formatted: formatCommandList({
290
- title: summary,
291
- commands: subcommands,
292
- footer: [
293
- 'Tip: use "jsn docs serve --expose" to bind to 0.0.0.0 and share on your network.',
294
- `Docs DB: ${getDocsDbPath()} (run "jsn docs status" for details, or query directly with sqlite3)`,
295
- 'Run "jsn docs <command> --help" for details.',
296
- ].join('\n'),
38
+ command: 'docs [query..]',
39
+ defaultPositionals: true,
40
+ describe: 'Search ServiceNow documentation (hosted by default; configure your service in setup)',
41
+ builder: y => y
42
+ .usage('Usage: jsn docs "search terms" [options]')
43
+ .positional('query', { type: 'string', describe: 'Search words (up to 200 characters)' })
44
+ .option('serve', { type: 'boolean', describe: 'Run the shared documentation server (downloads its index automatically)' })
45
+ .option('host', { type: 'string', default: '127.0.0.1', describe: 'Server bind address with --serve' })
46
+ .option('port', { type: 'number', default: 3000, describe: 'Server port with --serve' })
47
+ .option('limit', { type: 'number', default: 20, describe: 'Results per page (1–50)' })
48
+ .option('offset', { type: 'number', default: 0, describe: 'Result offset (0–10000)' })
49
+ .option('bundle', { type: 'string', describe: 'Filter by documentation bundle' })
50
+ .option('path', { type: 'string', describe: 'Read an exact document path or ID from search results' })
51
+ .option('revision', { type: 'string', describe: 'Require the revision returned by search (recommended with IDs)' })
52
+ .option('lines', { type: 'number', default: 80, describe: 'Preview lines; JSON contains the full Markdown body' })
53
+ // Compatibility spellings remain callable without becoming another menu.
54
+ .command({ command: 'install', hidden: true,
55
+ builder: y => y.option('source', { type: 'string', choices: ['snapshot', 'github', 'skip'] })
56
+ .option('manifest-url', { type: 'string' }),
57
+ handler: wrap(async (argv, app) => {
58
+ const { installDocumentation } = await import('./install.js');
59
+ app.ok(await installDocumentation(argv.source, { manifestURL: argv['manifest-url'] }));
297
60
  }),
61
+ })
62
+ .command({ command: 'search <query..>', hidden: true, handler: wrap(search) })
63
+ .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}` });
67
+ }) }),
68
+ handler: wrap(async (argv, app) => {
69
+ if (argv.serve) {
70
+ 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.' });
73
+ for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => server.close());
74
+ return;
75
+ }
76
+ if (argv.path) return read(argv, app);
77
+ if (argv.query?.length) return search(argv, app);
78
+ const service = await documentationService(app.config);
79
+ const summary = 'Search ServiceNow documentation';
80
+ app.ok({ command: 'docs', service,
81
+ _formatted: `jsn docs "search terms"\njsn docs --path <exact-path>\n\nService: ${service}\nChange documentation preferences in jsn setup → Advanced settings.\nNo ServiceNow connection is needed. Hosted mode downloads no database.\n`,
298
82
  }, { summary });
299
83
  }),
300
84
  };
@@ -0,0 +1,117 @@
1
+ // FTS5 query sanitizing for the docs index.
2
+ //
3
+ // ServiceNow documentation is full of dotted, hyphenated and slash-separated
4
+ // identifiers (`com.snc.itsm.roles`, `glide.ui.escape_all_script`,
5
+ // `change-management`). FTS5 reads a bare `.`, `:`, `-`, `/` or `+` as query
6
+ // syntax and throws `fts5: syntax error`, so every token is rendered as a
7
+ // quoted phrase unless it is plain word characters. Uppercase AND/OR/NOT and a
8
+ // trailing `*` prefix keep working as operators.
9
+
10
+ const FTS_COLUMNS = new Set(['title', 'body']);
11
+ const BOOLEAN_OPERATORS = new Set(['AND', 'OR', 'NOT']);
12
+ const WORD = /^[\p{L}\p{N}_]+$/u;
13
+
14
+ function quotePhrase(text) {
15
+ return `"${text.replace(/"/g, '""')}"`;
16
+ }
17
+
18
+ function renderValue(value, prefix) {
19
+ const rendered = WORD.test(value) ? value : quotePhrase(value);
20
+ return prefix ? `${rendered}*` : rendered;
21
+ }
22
+
23
+ function renderTerm(text) {
24
+ let prefix = false;
25
+ let core = text;
26
+ while (core.endsWith('*')) {
27
+ prefix = true;
28
+ core = core.slice(0, -1);
29
+ }
30
+ if (!core) return null;
31
+
32
+ const separator = core.indexOf(':');
33
+ if (separator > 0) {
34
+ const column = core.slice(0, separator);
35
+ const rest = core.slice(separator + 1);
36
+ if (FTS_COLUMNS.has(column) && rest) {
37
+ return `${column}: ${renderValue(rest, prefix)}`;
38
+ }
39
+ }
40
+ return renderValue(core, prefix);
41
+ }
42
+
43
+ function splitTokens(input) {
44
+ const tokens = [];
45
+ let i = 0;
46
+ while (i < input.length) {
47
+ const ch = input[i];
48
+ if (/\s/.test(ch)) {
49
+ i += 1;
50
+ continue;
51
+ }
52
+ if (ch === '"') {
53
+ let j = i + 1;
54
+ let text = '';
55
+ while (j < input.length) {
56
+ if (input[j] === '"') {
57
+ if (input[j + 1] === '"') {
58
+ text += '"';
59
+ j += 2;
60
+ continue;
61
+ }
62
+ j += 1;
63
+ break;
64
+ }
65
+ text += input[j];
66
+ j += 1;
67
+ }
68
+ let prefix = false;
69
+ if (input[j] === '*') {
70
+ prefix = true;
71
+ j += 1;
72
+ }
73
+ tokens.push({ kind: 'phrase', text, prefix });
74
+ i = j;
75
+ continue;
76
+ }
77
+ let j = i;
78
+ while (j < input.length && !/\s/.test(input[j])) j += 1;
79
+ tokens.push({ kind: 'term', text: input.slice(i, j) });
80
+ i = j;
81
+ }
82
+ return tokens;
83
+ }
84
+
85
+ /**
86
+ * Turn a free-text search query into an FTS5 MATCH expression that cannot throw
87
+ * a syntax error on punctuation. Returns '' when nothing searchable is left.
88
+ */
89
+ export function sanitizeFts5Query(query) {
90
+ const raw = query == null ? '' : String(query);
91
+ const out = [];
92
+
93
+ for (const token of splitTokens(raw)) {
94
+ if (token.kind === 'phrase') {
95
+ out.push({ text: quotePhrase(token.text) + (token.prefix ? '*' : '') });
96
+ continue;
97
+ }
98
+ if (BOOLEAN_OPERATORS.has(token.text)) {
99
+ // Operators only mean something between two operands.
100
+ if (out.length === 0) continue;
101
+ if (out[out.length - 1].operator) {
102
+ // FTS5 only accepts NOT as an infix operator, so "a AND NOT b" becomes "a NOT b".
103
+ if (token.text === 'NOT' && out[out.length - 1].text !== 'NOT') {
104
+ out[out.length - 1] = { text: 'NOT', operator: true };
105
+ }
106
+ continue;
107
+ }
108
+ out.push({ text: token.text, operator: true });
109
+ continue;
110
+ }
111
+ const rendered = renderTerm(token.text);
112
+ if (rendered) out.push({ text: rendered });
113
+ }
114
+
115
+ while (out.length > 0 && out[out.length - 1].operator) out.pop();
116
+ return out.map((token) => token.text).join(' ');
117
+ }
@@ -0,0 +1,15 @@
1
+ // The Rails adapter uses this JSON-lines bridge to the same Node search engine.
2
+ import readline from 'node:readline';
3
+ import { DocumentationIndex, documentationSummary } from './index.js';
4
+ let index;
5
+ try {
6
+ for await (const line of readline.createInterface({ input: process.stdin, crlfDelay: Infinity })) {
7
+ try {
8
+ const { operation, arguments: args = {} } = JSON.parse(line);
9
+ if (operation !== 'summary') index ||= new DocumentationIndex(process.env.DOCS_STORAGE_DIR);
10
+ const value = operation === 'summary' ? documentationSummary(args) : operation === 'revision' ? index.revision()
11
+ : operation === 'search' ? index.search(args) : operation === 'document' ? index.document(args) : null;
12
+ process.stdout.write(JSON.stringify({ value }) + '\n');
13
+ } catch (error) { process.stdout.write(JSON.stringify({ error: error.status ? error.message : 'Documentation search is temporarily unavailable.', status: error.status || 503 }) + '\n'); }
14
+ }
15
+ } finally { index?.close(); }
@@ -0,0 +1,81 @@
1
+ // One search engine for the hosted website and the optional local service.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import Database from 'better-sqlite3';
5
+
6
+ export class DocumentationError extends Error {
7
+ constructor(message, status = 503) { super(message); this.status = status; }
8
+ }
9
+ export function documentationStatus(storage) {
10
+ try {
11
+ const value = JSON.parse(fs.readFileSync(path.join(storage, 'status.json'), 'utf8'));
12
+ return Object.fromEntries(['state', 'checkedAt', 'publishedAt', 'documents', 'revision'].filter(key => key in value).map(key => [key, value[key]]));
13
+ } catch { return { state: 'unavailable' }; }
14
+ }
15
+ function plain(value) {
16
+ return String(value).replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
17
+ .replace(/\\([\p{P}\p{S}])/gu, '$1').replace(/[`*#]/g, '').replace(/<[^>]*>/g, '')
18
+ .replace(/&(?:amp|lt|gt|quot|#39);/g, entity => ({ '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'" })[entity])
19
+ .replace(/\s+/g, ' ').trim();
20
+ }
21
+ function firstParagraph(body) {
22
+ let fenced = false, current = [];
23
+ const paragraphs = [];
24
+ for (const line of String(body).split('\n')) {
25
+ if (/^ {0,3}(?:`{3,}|~{3,})/.test(line)) { fenced = !fenced; continue; }
26
+ if (fenced || /^(?: {4}|\t)/.test(line)) continue;
27
+ if (!line.trim()) { if (current.length) paragraphs.push(current.join(' ')); current = []; }
28
+ else if (!/^\s*(?:\||#{1,6}\s|<|[-*+]\s|\d+\.\s|\*?\*?Parent Topic:)/i.test(line)) current.push(line.trim());
29
+ }
30
+ if (current.length) paragraphs.push(current.join(' '));
31
+ return plain(paragraphs.find(text => text.length > 30) || '');
32
+ }
33
+ export function documentationSummary(input) {
34
+ const { frontmatter, preview, ...row } = input;
35
+ let metadata;
36
+ try { metadata = JSON.parse(frontmatter || '{}'); } catch { metadata = {}; }
37
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) metadata = {};
38
+ const description = typeof metadata.description === 'string' ? plain(metadata.description) : '';
39
+ const excerpt = firstParagraph(preview || '');
40
+ let summary = description || excerpt || `Read ${row.title || 'this reference'} in the ServiceNow documentation.`;
41
+ if (summary.length > 280) summary = summary.slice(0, 280).match(/^(.{60,}[.!?])(?:\s|$)/)?.[1] || summary.slice(0, 279).replace(/\s+\S*$/, '') + '…';
42
+ const classification = typeof metadata.classification === 'string' && metadata.classification ? metadata.classification : String(row.path || '').split('/')[0];
43
+ const category = plain(classification.replaceAll('-', ' '));
44
+ return { ...row, doc_type: row.doc_type || metadata.topic_type || null, summary,
45
+ summary_source: description ? 'description' : excerpt ? 'paragraph' : 'fallback',
46
+ category: typeof metadata.product === 'string' && metadata.product.trim() ? plain(metadata.product) : category.charAt(0).toUpperCase() + category.slice(1).replace(/^pi /, 'PI '),
47
+ };
48
+ }
49
+ export class DocumentationIndex {
50
+ constructor(storage) {
51
+ try { this.db = new Database(path.join(storage, 'docs.sqlite3'), { readonly: true, fileMustExist: true, timeout: 2000 }); }
52
+ catch { throw new DocumentationError('Documentation is being prepared. Please try again shortly.'); }
53
+ }
54
+ close() { this.db.close(); }
55
+ revision() { return this.db.prepare("SELECT value FROM meta WHERE key = 'source_revision'").get()?.value || ''; }
56
+ search({ query, limit = 20, offset = 0, bundle } = {}) {
57
+ const text = String(query || '').trim();
58
+ if (!text || text.length > 200) throw new DocumentationError('Enter a search of 1 to 200 characters.', 400);
59
+ const tokens = text.match(/[\p{L}\p{N}_]+/gu)?.slice(0, 20);
60
+ if (!tokens?.length) throw new DocumentationError('Enter a word to search for.', 400);
61
+ limit = Number(limit); offset = Number(offset);
62
+ if (!Number.isInteger(limit) || limit < 1 || limit > 50 || !Number.isInteger(offset) || offset < 0 || offset > 10000) throw new DocumentationError('Limit must be 1–50 and offset 0–10000.', 400);
63
+ const filter = bundle ? ' AND d.bundle = ?' : '';
64
+ const binds = [tokens.map(token => `"${token}"`).join(' AND '), ...(bundle ? [bundle] : [])];
65
+ const total = this.db.prepare(`SELECT COUNT(*) AS n FROM docs_fts JOIN docs d ON d.id=docs_fts.rowid WHERE docs_fts MATCH ?${filter}`).get(...binds).n;
66
+ const results = this.db.prepare(`SELECT d.id, d.path, d.title, d.bundle, d.doc_type, d.release, d.frontmatter,
67
+ substr(d.body, 1, 12000) AS preview, snippet(docs_fts, 1, '', '', ' … ', 24) AS snippet
68
+ FROM docs_fts JOIN docs d ON d.id=docs_fts.rowid WHERE docs_fts MATCH ?${filter}
69
+ ORDER BY CASE WHEN lower(d.title) = lower(?) THEN 0 WHEN instr(lower(d.title), lower(?)) = 1 THEN 1
70
+ WHEN instr(lower(d.title), lower(?)) > 0 THEN 2 ELSE 3 END, bm25(docs_fts, 10.0, 1.0), d.id LIMIT ? OFFSET ?`)
71
+ .all(...binds, text, text, text, limit, offset).map(documentationSummary);
72
+ return { query: text, revision: this.revision(), total, count: results.length, limit, offset, results };
73
+ }
74
+ document({ id, path: docPath } = {}) {
75
+ const select = 'SELECT id, path, title, bundle, doc_type, release, body FROM docs WHERE';
76
+ const row = docPath ? this.db.prepare(`${select} path = ?`).get(docPath)
77
+ : /^\d{1,18}$/.test(String(id)) ? this.db.prepare(`${select} id = ?`).get(String(id)) : null;
78
+ if (!row) throw new DocumentationError('Document not found.', 404);
79
+ return row;
80
+ }
81
+ }