Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ npm run check:public

## Publishing

After a successful GitHub Pages deployment, the `search` job indexes the pages in the deployed sitemap that fall outside `/api/`. It converts the rendered article to Markdown so included examples match the page. Search results carry the GitHub Pages URL in `item.metadata.source_url`. The job skips unchanged documents and removes retired guides that it previously uploaded.
After a successful GitHub Pages deployment, the `search` job indexes the pages in the deployed sitemap outside `/api/`, plus the Bybit REST and WebSocket clients and the types named in Bybit guides or linked from the constructors and guide methods. It converts the rendered article to Markdown so included examples match the page. Search results carry the GitHub Pages URL in `item.metadata.source_url`. Bybit API references carry `doc_kind: api_reference`. For a reference-only lookup, pass `{"doc_kind":"api_reference"}` in `ai_search_options.retrieval.filters`. The instance defines `doc_kind` as a text metadata field. The job skips unchanged documents and removes retired pages that it previously uploaded.

The `indexnow` job then waits until that published revision is live and submits documentation URLs to [IndexNow](https://www.indexnow.org/) so Bing can pick them up quickly. The build snapshots the live sitemap first, and the job submits new URLs plus any whose lastmod changed. The combined sitemap does not currently include lastmod, so the job falls back to the built sitemap, capped at 10,000 URLs, and skips the request if the list is empty. The ownership key is a public file at the docs root; IndexNow fetches it to verify the ping. A failed IndexNow request is logged and does not fail the deployment.

Expand Down
11 changes: 8 additions & 3 deletions scripts/publish-search.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ const publisher = 'sieblyio/docs';
const prefix = 'siebly-docs__';
const submitted = new Set(['queued', 'running', 'completed']);

function matchesPage(item, page) {
return item?.metadata?.content_digest === page.digest &&
item.metadata.source_url === page.url && item.metadata.doc_kind === page.docKind;
}

export async function sync(bundle, items) {
const remote = await items.list();
const existing = new Map(remote.map(item => [item.key, item]));
Expand All @@ -24,10 +29,10 @@ export async function sync(bundle, items) {
for (const [key, page] of desired) {
const old = existing.get(key);
// A matching item that is still queued or running is already on its way. Uploading it again would restart its indexing.
if (submitted.has(old?.status) && old.next_action !== 'DELETE' && old.metadata?.content_digest === page.digest && old.metadata?.source_url === page.url) continue;
if (submitted.has(old?.status) && old.next_action !== 'DELETE' && matchesPage(old, page)) continue;
const form = new FormData();
form.set('file', new Blob([page.text], { type: 'text/markdown' }), key);
form.set('metadata', JSON.stringify({ publisher, source_url: page.url, content_digest: page.digest }));
form.set('metadata', JSON.stringify({ publisher, source_url: page.url, content_digest: page.digest, doc_kind: page.docKind }));
await items.upload(form);
changed++;
}
Expand All @@ -39,7 +44,7 @@ export async function sync(bundle, items) {
const item = indexed.get(key);
if (item?.status === 'error' || item?.status === 'skipped') throw new Error(key + ': ' + (item.error || item.status));
if (item?.status !== 'completed' || item.next_action || !item.chunks_count ||
item.metadata?.content_digest !== page.digest || item.metadata?.source_url !== page.url) pending.push(key);
!matchesPage(item, page)) pending.push(key);
}
if (!pending.length) break;
if (Date.now() >= deadline) {
Expand Down
77 changes: 71 additions & 6 deletions scripts/search-pages.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ import path from 'node:path';
import { pathToFileURL } from 'node:url';
import { parse } from 'node-html-parser';
import { NodeHtmlMarkdown } from 'node-html-markdown';
import bybit from '../sdks/bybit/sdk.config.mjs';

const markdown = new NodeHtmlMarkdown();

export function article(html, url) {
const doc = parse(html);
async function readArticle(dist, base, url) {
const route = url.pathname.slice(base.pathname.length);
const file = path.join(dist, !route || route.endsWith('/') ? route + 'index.html' : route);
const doc = parse(await readFile(file, 'utf8'));
const main = doc.querySelector('main');
if (!main?.querySelector('h1') || doc.querySelector('link[rel=canonical]')?.getAttribute('href') !== url.href) {
throw new Error('Missing article or incorrect canonical: ' + url.href);
Expand All @@ -16,7 +19,63 @@ export function article(html, url) {
for (const link of main.querySelectorAll('a[href]')) link.setAttribute('href', new URL(link.getAttribute('href'), url).href);
// Syntax highlighting splits code across spans. Preserve the rendered code and line breaks.
for (const code of main.querySelectorAll('pre code')) code.set_content(code.rawText);
return [doc.querySelector('title').text.trim(), url.href, '', markdown.translate(main.toString()), ''].join('\n');
return { title: doc.querySelector('title').text.trim(), main };
}

function searchText(article, url, context = []) {
return [article.title, url.href, ...context, '', markdown.translate(article.main.toString()), ''].join('\n');
}

async function bybitReferences(dist, base, urls, guides) {
const api = new URL('bybit/api/', base);
const typePages = new Map();
for (const url of urls) {
const match = /^(?:interfaces|type-aliases|enumerations)\/([^/]+)\.html$/.exec(url.href.slice(api.href.length));
if (match) typePages.set(url.href, { symbol: match[1], usedBy: new Set() });
}
const symbols = new Set(guides.match(/\b[A-Z][A-Za-z0-9_$]*\b/g));
const methods = new Set(bybit.referenceHelp.map(({ client, method }) => client + '.' + method));
// Keep the receiver inside its example. URLSearchParams.get() is unrelated to RestClientV5.get().
for (const [, code] of guides.matchAll(/^```[^\n]*\n([\s\S]*?)^```/gm)) {
const clients = new Map(Array.from(code.matchAll(/\b(\w+)\s*=\s*new\s+(\w+)\s*\(/g), match => [match[1], match[2]]));
for (const [, receiver, method] of code.matchAll(/\b(\w+)\.(\w+)\s*\(/g)) {
if (clients.has(receiver)) methods.add(clients.get(receiver) + '.' + method);
}
}
const anchorLinks = new Set(Array.from(guides.matchAll(/\]\(([^()\s]+#[^()\s]+)\)/g), match => match[1]));
const pages = [];
for (const client of bybit.clients) {
const url = new URL('classes/' + client + '.html', api);
if (!urls.some(entry => entry.href === url.href)) throw new Error('Bybit client is missing from the sitemap: ' + client);
const article = await readArticle(dist, base, url);
// Follow types only in the constructor and methods used or linked by the guides.
for (const heading of article.main.querySelectorAll('h3')) {
const member = heading.text.trim().replace(/\(\)$/, '');
if (heading.id !== 'constructor' && !methods.has(client + '.' + member) && !anchorLinks.has(url.href + '#' + heading.id)) continue;
for (let node = heading.nextElementSibling; node && !['H1', 'H2', 'H3'].includes(node.tagName); node = node.nextElementSibling) {
for (const link of node.querySelectorAll('a[href]')) {
const type = typePages.get(link.getAttribute('href').split('#')[0]);
if (type) type.usedBy.add(heading.id === 'constructor' ? 'new ' + client : client + '.' + member);
}
}
}
pages.push({ url: url.href, docKind: 'api_reference', text: searchText(article, url, [bybit.name + ' SDK API reference for ' + client]) });
}
for (const [href, { symbol, usedBy }] of typePages) {
if (!usedBy.size && !symbols.has(symbol)) continue;
const url = new URL(href);
const article = await readArticle(dist, base, url);
const context = [bybit.name + ' SDK API reference for ' + symbol];
if (usedBy.size) context.push('Used by ' + [...usedBy].sort().join(', ') + '.');
const properties = article.main.querySelector('h2#properties')?.nextElementSibling;
if (properties?.tagName === 'TABLE' && properties.querySelector('th')?.text.trim() === 'Property') {
const fields = properties.querySelectorAll('tbody tr').map(row => row.querySelector('td')?.text.trim());
const required = fields.filter(name => name && !name.endsWith('?'));
if (required.length) context.push('Required fields on ' + symbol + ': ' + required.join(', ') + '.');
}
pages.push({ url: href, docKind: 'api_reference', text: searchText(article, url, context) });
}
return pages;
}

export async function collectPages(dist) {
Expand All @@ -25,20 +84,26 @@ export async function collectPages(dist) {
const base = new URL(manifest.siteUrl);
const sitemap = await readFile(path.join(dist, 'sitemap.xml'), 'utf8');
const pages = [];
const bybitApi = [];
const guides = [];
for (const entry of parse(sitemap).querySelectorAll('loc')) {
const url = new URL(entry.text);
if (!url.href.startsWith(base.href) || url.search || url.hash) throw new Error('Unexpected sitemap URL: ' + url);
const route = url.pathname.slice(base.pathname.length);
if (route.startsWith('bybit/api/')) bybitApi.push(url);
if (route.split('/').includes('api')) continue;
const file = path.join(dist, !route || route.endsWith('/') ? route + 'index.html' : route);
pages.push({ url: url.href, text: article(await readFile(file, 'utf8'), url) });
const text = searchText(await readArticle(dist, base, url), url);
pages.push({ url: url.href, text });
if (route.startsWith('bybit/')) guides.push(text);
}
if (bybitApi.length) pages.push(...await bybitReferences(dist, base, bybitApi, guides.join('\n')));
if (!pages.length || new Set(pages.map(p => p.url)).size !== pages.length) throw new Error('Empty or duplicate search pages.');
return { revision: manifest.documentationRevision, siteUrl: base.href, pages };
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const bundle = await collectPages(process.argv[2]);
await writeFile(process.argv[3], JSON.stringify(bundle));
console.log('Prepared ' + bundle.pages.length + ' documentation pages for AI Search.');
console.log('Prepared ' + bundle.pages.length + ' documentation pages for AI Search, including ' +
bundle.pages.filter(page => page.docKind === 'api_reference').length + ' Bybit API references.');
}
34 changes: 32 additions & 2 deletions scripts/search-pages.test.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, writeFile, rm } from 'node:fs/promises';
import { mkdir, mkdtemp, writeFile, rm } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { collectPages } from './search-pages.mjs';
Expand Down Expand Up @@ -37,14 +37,44 @@ test('sync updates changed guides and prunes only its own retired pages after su
await sync(bundle, items);
await sync(bundle, items);
assert.deepEqual(operations, ['upload', 'upload']);
bundle.pages[1].docKind = 'api_reference';
await sync(bundle, items);
assert.equal(records.get('siebly-docs__bybit__.md').metadata.doc_kind, 'api_reference');
records.set('other', { id: 'other', source_id: 'builtin', key: 'other' });
bundle.pages.pop();
bundle.pages[0].text = 'updated';
const failure = { ...items, upload: async () => { throw new Error('rate limit'); } };
await assert.rejects(sync(bundle, failure), /rate limit/);
assert.equal(records.size, 3);
await sync(bundle, items);
assert.deepEqual(operations, ['upload', 'upload', 'upload', 'delete']);
assert.deepEqual(operations, ['upload', 'upload', 'upload', 'upload', 'delete']);
assert.ok(records.has('other'));
assert.equal(records.get('siebly-docs__home.md').metadata.source_url, base);
});

test('Bybit references follow guide symbols and client signatures without crawling other types', async t => {
const dir = await mkdtemp(path.join(os.tmpdir(), 'search-refs-'));
t.after(() => rm(dir, { recursive: true, force: true }));
const files = new Map([
['bybit/guides/orders.html', '<h1>Orders</h1><code>client.submitOrder()</code> returns <code>NamedType</code>.'],
['bybit/api/classes/RestClientV5.html', '<h1>RestClientV5</h1><h3 id="submitorder">submitOrder()</h3><p><a href="../interfaces/OrderParamsV5.html">params</a></p><h3 id="unused">unused()</h3><p><a href="../interfaces/Other.html">params</a></p>'],
['bybit/api/classes/WebsocketClient.html', '<h1>WebsocketClient</h1>'],
['bybit/api/classes/WebsocketAPIClient.html', '<h1>WebsocketAPIClient</h1>'],
['bybit/api/interfaces/OrderParamsV5.html', '<h1>OrderParamsV5</h1><h2 id="properties">Properties</h2><table><thead><tr><th>Property</th></tr></thead><tbody><tr><td>symbol</td></tr><tr><td>price?</td></tr></tbody></table><a href="Other.html">Other</a>'],
['bybit/api/type-aliases/NamedType.html', '<h1>NamedType</h1>'],
]);
const excluded = ['bybit/api/interfaces/Other.html', 'kraken/api/classes/WebsocketClient.html'];
const routes = [...files.keys(), ...excluded];
await writeFile(path.join(dir, 'build-manifest.json'), JSON.stringify({ indexable: true, siteUrl: base, documentationRevision: '123' }));
await writeFile(path.join(dir, 'sitemap.xml'), '<urlset>' + routes.map(route => '<url><loc>' + base + route + '</loc></url>').join('') + '</urlset>');
for (const [route, body] of files) {
await mkdir(path.dirname(path.join(dir, route)), { recursive: true });
await writeFile(path.join(dir, route), '<title>Bybit</title><link rel="canonical" href="' + base + route + '"><main>' + body + '</main>');
}
const { pages } = await collectPages(dir);
assert.deepEqual(pages.map(page => page.url).sort(), [...files.keys()].map(route => base + route).sort());
const reference = pages.find(page => page.url.endsWith('/OrderParamsV5.html'));
assert.ok(pages.filter(page => page.url.includes('/api/')).every(page => page.docKind === 'api_reference'));
assert.match(reference.text, /Used by RestClientV5.submitOrder\./);
assert.match(reference.text, /Required fields on OrderParamsV5: symbol\./);
});
2 changes: 1 addition & 1 deletion sdks/kraken/docs/guides/websockets.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ description: "Subscribe to Kraken Spot ticker updates with automatic reconnects

# Public streams (WebSocket) {#websocket-subscriptions}

`WebsocketClient` manages public and private subscriptions for Spot and Futures. This example subscribes to the public Spot v2 ticker for `BTC/USD`, without credentials.
`WebsocketClient` manages public and private subscriptions for Spot and Futures. To stream the Kraken Spot v2 ticker for `BTC/USD`, call `subscribe()` with `WS_KEY_MAP.spotPublicV2`. Call `closeAll()` to close the stream on shutdown. This public subscription works without credentials.

## Subscribe to a ticker

Expand Down