@jini-ai/registry 0.5.1 → 0.5.3

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/CHANGELOG.md CHANGED
@@ -1,3 +1,11 @@
1
+ ## 0.5.3 — 2026-10-22
2
+
3
+ - 2026-10-22: Model-facing tool errors keep diagnostic codes, complexity refactors, coverage.
4
+
5
+ ## 0.5.2 — 2026-10-08
6
+
7
+ - Tovu clean-up release: code Tovu moved into Jini, plus the Jini clean-up (see the commit log).
8
+
1
9
  ## 0.5.1 — 2026-10-05
2
10
 
3
11
  - The `@jini-ai/db` peer range is `^0.2.0 || ^0.3.0` (registry uses only db's SQLite entry, which 0.3.0 leaves unchanged), so a host on db 0.3.0 installs without a peer conflict.
@@ -138,21 +138,28 @@ export class GithubRegistryBackend extends StaticRegistryBackend {
138
138
  return { ok: true, dryRun: false, name, version, reason, pullRequestUrl: pr.url, warnings: [] };
139
139
  }
140
140
  }
141
+ /**
142
+ * Render the publish PR body. Empty parts (no description, no changelog) are
143
+ * dropped by `filter(Boolean)`, so the body carries no blank separator lines
144
+ * apart from the ones embedded in the changelog section.
145
+ */
141
146
  function renderPublishBody(request) {
147
+ const { entry } = request;
142
148
  return [
143
- `Publish ${request.entry.name}@${request.entry.version}`,
144
- '',
145
- request.entry.description ?? '',
146
- '',
149
+ `Publish ${entry.name}@${entry.version}`,
150
+ entry.description,
147
151
  '## Registry metadata',
148
- '',
149
- `- source: ${request.entry.source}`,
150
- `- integrity: ${request.entry.integrity ?? request.entry.dist?.integrity ?? '(pending)'}`,
151
- `- manifestDigest: ${request.entry.manifestDigest ?? request.entry.dist?.manifestDigest ?? '(pending)'}`,
152
- `- capabilities: ${(request.entry.capabilitiesSummary ?? []).join(', ') || '(none declared)'}`,
153
- request.changelog ? `\n## Changelog\n\n${request.changelog}` : '',
152
+ `- source: ${entry.source}`,
153
+ `- integrity: ${digestField(entry, 'integrity')}`,
154
+ `- manifestDigest: ${digestField(entry, 'manifestDigest')}`,
155
+ `- capabilities: ${(entry.capabilitiesSummary ?? []).join(', ') || '(none declared)'}`,
156
+ request.changelog && `\n## Changelog\n\n${request.changelog}`,
154
157
  ]
155
158
  .filter(Boolean)
156
159
  .join('\n');
157
160
  }
161
+ /** A top-level digest wins over the `dist` one; neither yet means the publish pipeline has not computed it. */
162
+ function digestField(entry, key) {
163
+ return entry[key] ?? entry.dist?.[key] ?? '(pending)';
164
+ }
158
165
  //# sourceMappingURL=github-backend.js.map
@@ -101,5 +101,11 @@ export declare class GithubApiRegistryClient implements GithubRegistryClient {
101
101
  */
102
102
  private ensurePullRequest;
103
103
  private findOpenPullRequest;
104
+ /**
105
+ * The single request builder: every call goes to `apiUrl` with the GitHub
106
+ * headers (bearer auth only when a token is configured) and the QUICK
107
+ * idle/total bounds. A JSON `body` adds the JSON content type.
108
+ */
109
+ private send;
104
110
  }
105
111
  //# sourceMappingURL=github-client.d.ts.map
@@ -67,35 +67,16 @@ export class GithubApiRegistryClient {
67
67
  * this endpoint's inline-content response, or is not valid JSON.
68
68
  */
69
69
  async readManifest({ owner, repo, ref, path }) {
70
- const url = `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/contents/${encPath(path)}?${new URLSearchParams({ ref }).toString()}`;
71
- const resp = await this.http.send({ request: { url, method: 'GET', headers: githubHeaders(this.token), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
70
+ const where = `${owner}/${repo}@${ref}:${path}`;
71
+ const resp = await this.send('GET', `${repoPath(owner, repo)}/contents/${encPath(path)}?${new URLSearchParams({ ref }).toString()}`);
72
72
  if (resp.status === 404) {
73
- throw new Error(`Registry manifest not found: ${owner}/${repo}@${ref}:${path}`);
73
+ throw new Error(`Registry manifest not found: ${where}`);
74
74
  }
75
75
  const json = await readGithubJson(resp);
76
- if (!(resp.status >= 200 && resp.status < 300)) {
77
- throw githubError(Array.isArray(json) ? {} : json, resp.status, `Failed to read registry manifest ${owner}/${repo}@${ref}:${path}.`);
76
+ if (!isOk(resp.status)) {
77
+ throw githubError(Array.isArray(json) ? {} : json, resp.status, `Failed to read registry manifest ${where}.`);
78
78
  }
79
- if (Array.isArray(json)) {
80
- throw new Error(`Registry manifest path is a directory, not a file: ${owner}/${repo}@${ref}:${path}`);
81
- }
82
- if (json.type !== 'file') {
83
- throw new Error(`Registry manifest path is not a file (type: ${String(json.type)}): ${owner}/${repo}@${ref}:${path}`);
84
- }
85
- if (json.encoding !== 'base64' || typeof json.content !== 'string') {
86
- throw new Error(`Registry manifest at ${owner}/${repo}@${ref}:${path} is too large for the Contents API's inline response ` +
87
- `(size: ${typeof json.size === 'number' ? json.size : 'unknown'} bytes, encoding: ${String(json.encoding)}); ` +
88
- 'split the manifest into a smaller file or fetch it via the Git Trees/raw-media-type API instead.');
89
- }
90
- const decoded = Buffer.from(json.content.replace(/\n/g, ''), 'base64').toString('utf8');
91
- let parsed;
92
- try {
93
- parsed = JSON.parse(decoded);
94
- }
95
- catch (cause) {
96
- throw new Error(`Registry manifest at ${owner}/${repo}@${ref}:${path} is not valid JSON.`, { cause });
97
- }
98
- return parsed;
79
+ return parseManifest(inlineFileContent(json, where), where);
99
80
  }
100
81
  /**
101
82
  * Pushes `request.files` as a new commit on a fresh branch (created off
@@ -127,36 +108,23 @@ export class GithubApiRegistryClient {
127
108
  return this.ensurePullRequest(owner, repo, request);
128
109
  }
129
110
  async getRefSha(owner, repo, branch) {
130
- const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/ref/heads/${enc(branch)}`, method: 'GET', headers: githubHeaders(this.token), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
111
+ const resp = await this.send('GET', `${repoPath(owner, repo)}/git/ref/heads/${enc(branch)}`);
131
112
  if (resp.status === 404)
132
113
  return undefined;
133
- const json = await readGithubJson(resp);
134
- if (!(resp.status >= 200 && resp.status < 300))
135
- throw githubError(json, resp.status, 'GitHub ref lookup failed.');
114
+ const json = await okJson(resp, 'GitHub ref lookup failed.');
136
115
  const object = json.object;
137
116
  return typeof object?.sha === 'string' ? object.sha : undefined;
138
117
  }
139
118
  /** `GET /repos/{owner}/{repo}/git/commits/{sha}` (Git Data API) — the tree API's `base_tree` param needs a *tree* sha, not the commit sha `getRefSha` returns. */
140
119
  async getCommitTreeSha(owner, repo, commitSha) {
141
- const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/commits/${enc(commitSha)}`, method: 'GET', headers: githubHeaders(this.token), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
142
- const json = await readGithubJson(resp);
143
- if (!(resp.status >= 200 && resp.status < 300))
144
- throw githubError(json, resp.status, 'GitHub base commit lookup failed.');
120
+ const json = await okJson(await this.send('GET', `${repoPath(owner, repo)}/git/commits/${enc(commitSha)}`), 'GitHub base commit lookup failed.');
145
121
  const tree = json.tree;
146
- const sha = typeof tree?.sha === 'string' ? tree.sha : '';
147
- if (!sha)
148
- throw new Error('GitHub base commit response did not include a tree sha.');
149
- return sha;
122
+ return requireString(tree?.sha, 'GitHub base commit response did not include a tree sha.');
150
123
  }
151
124
  async createBlob(owner, repo, content) {
152
- const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/blobs`, method: 'POST', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ content: Buffer.from(content, 'utf8').toString('base64'), encoding: 'base64' }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
153
- const json = await readGithubJson(resp);
154
- if (!(resp.status >= 200 && resp.status < 300))
155
- throw githubError(json, resp.status, 'GitHub blob creation failed.');
156
- const sha = typeof json.sha === 'string' ? json.sha : '';
157
- if (!sha)
158
- throw new Error('GitHub blob response did not include a sha.');
159
- return sha;
125
+ const body = { content: Buffer.from(content, 'utf8').toString('base64'), encoding: 'base64' };
126
+ const json = await okJson(await this.send('POST', `${repoPath(owner, repo)}/git/blobs`, body), 'GitHub blob creation failed.');
127
+ return requireString(json.sha, 'GitHub blob response did not include a sha.');
160
128
  }
161
129
  async createTree(owner, repo, baseTreeSha, files) {
162
130
  const tree = [];
@@ -164,24 +132,12 @@ export class GithubApiRegistryClient {
164
132
  const blobSha = await this.createBlob(owner, repo, file.content);
165
133
  tree.push({ path: file.path, mode: '100644', type: 'blob', sha: blobSha });
166
134
  }
167
- const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/trees`, method: 'POST', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ base_tree: baseTreeSha, tree }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
168
- const json = await readGithubJson(resp);
169
- if (!(resp.status >= 200 && resp.status < 300))
170
- throw githubError(json, resp.status, 'GitHub tree creation failed.');
171
- const sha = typeof json.sha === 'string' ? json.sha : '';
172
- if (!sha)
173
- throw new Error('GitHub tree response did not include a sha.');
174
- return sha;
135
+ const json = await okJson(await this.send('POST', `${repoPath(owner, repo)}/git/trees`, { base_tree: baseTreeSha, tree }), 'GitHub tree creation failed.');
136
+ return requireString(json.sha, 'GitHub tree response did not include a sha.');
175
137
  }
176
138
  async createCommit(owner, repo, message, treeSha, parents) {
177
- const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/commits`, method: 'POST', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ message, tree: treeSha, parents }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
178
- const json = await readGithubJson(resp);
179
- if (!(resp.status >= 200 && resp.status < 300))
180
- throw githubError(json, resp.status, 'GitHub commit creation failed.');
181
- const sha = typeof json.sha === 'string' ? json.sha : '';
182
- if (!sha)
183
- throw new Error('GitHub commit response did not include a sha.');
184
- return sha;
139
+ const json = await okJson(await this.send('POST', `${repoPath(owner, repo)}/git/commits`, { message, tree: treeSha, parents }), 'GitHub commit creation failed.');
140
+ return requireString(json.sha, 'GitHub commit response did not include a sha.');
185
141
  }
186
142
  /**
187
143
  * Creates `refs/heads/{branch}` pointing at `sha`, or (if it already
@@ -193,17 +149,15 @@ export class GithubApiRegistryClient {
193
149
  * `@jini-ai/deploy`'s `github-pages.ts` already documents for its own ref update.
194
150
  */
195
151
  async ensureBranch(owner, repo, branch, sha) {
196
- const createResp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/refs`, method: 'POST', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ ref: `refs/heads/${branch}`, sha }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
197
- if ((createResp.status >= 200 && createResp.status < 300))
152
+ const createResp = await this.send('POST', `${repoPath(owner, repo)}/git/refs`, { ref: `refs/heads/${branch}`, sha });
153
+ if (isOk(createResp.status))
198
154
  return;
199
155
  if (createResp.status !== 409 && createResp.status !== 422) {
200
156
  const json = await readGithubJson(createResp);
201
157
  throw githubError(json, createResp.status, 'GitHub branch creation failed.');
202
158
  }
203
- const updateResp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/git/refs/heads/${enc(branch)}`, method: 'PATCH', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ sha, force: true }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
204
- const json = await readGithubJson(updateResp);
205
- if (!(updateResp.status >= 200 && updateResp.status < 300))
206
- throw githubError(json, updateResp.status, 'GitHub branch update failed.');
159
+ const updateResp = await this.send('PATCH', `${repoPath(owner, repo)}/git/refs/heads/${enc(branch)}`, { sha, force: true });
160
+ await okJson(updateResp, 'GitHub branch update failed.');
207
161
  }
208
162
  /**
209
163
  * Opens `POST /repos/{owner}/{repo}/pulls`, or — if GitHub rejects it
@@ -215,16 +169,13 @@ export class GithubApiRegistryClient {
215
169
  * analogous "create-or-find" race.
216
170
  */
217
171
  async ensurePullRequest(owner, repo, request) {
218
- const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/pulls`, method: 'POST', headers: githubHeaders(this.token, { 'Content-Type': 'application/json' }), body: JSON.stringify({ title: request.title, body: request.body, head: request.branchName, base: request.baseRef }), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
172
+ const body = { title: request.title, body: request.body, head: request.branchName, base: request.baseRef };
173
+ const resp = await this.send('POST', `${repoPath(owner, repo)}/pulls`, body);
219
174
  const json = await readGithubJson(resp);
220
- if ((resp.status >= 200 && resp.status < 300)) {
221
- const url = typeof json.html_url === 'string' ? json.html_url : '';
222
- if (!url)
223
- throw new Error('GitHub pull request response did not include an html_url.');
224
- return { url };
175
+ if (isOk(resp.status)) {
176
+ return { url: requireString(json.html_url, 'GitHub pull request response did not include an html_url.') };
225
177
  }
226
- const message = typeof json.message === 'string' ? json.message : '';
227
- if (resp.status === 422 && /already exists/i.test(message)) {
178
+ if (isExistingPullRequestConflict(resp.status, json)) {
228
179
  const existing = await this.findOpenPullRequest(owner, repo, request.baseRef, request.branchName);
229
180
  if (existing)
230
181
  return { url: existing };
@@ -233,17 +184,87 @@ export class GithubApiRegistryClient {
233
184
  }
234
185
  async findOpenPullRequest(owner, repo, base, branch) {
235
186
  const query = new URLSearchParams({ head: `${owner}:${branch}`, base, state: 'open' });
236
- const resp = await this.http.send({ request: { url: `${this.apiUrl}/repos/${enc(owner)}/${enc(repo)}/pulls?${query.toString()}`, method: 'GET', headers: githubHeaders(this.token), idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK } });
187
+ const resp = await this.send('GET', `${repoPath(owner, repo)}/pulls?${query.toString()}`);
237
188
  const json = await readGithubJson(resp);
238
- if (!(resp.status >= 200 && resp.status < 300) || !Array.isArray(json))
189
+ if (!isOk(resp.status) || !Array.isArray(json))
239
190
  return undefined;
240
191
  const first = json[0];
241
192
  return first && typeof first.html_url === 'string' ? first.html_url : undefined;
242
193
  }
194
+ /**
195
+ * The single request builder: every call goes to `apiUrl` with the GitHub
196
+ * headers (bearer auth only when a token is configured) and the QUICK
197
+ * idle/total bounds. A JSON `body` adds the JSON content type.
198
+ */
199
+ send(method, path, body) {
200
+ const json = body === undefined ? undefined : JSON.stringify(body);
201
+ const headers = githubHeaders(this.token, json === undefined ? {} : { 'Content-Type': 'application/json' });
202
+ const request = { url: `${this.apiUrl}${path}`, method, headers, idleTimeoutMs: FETCH_TIMEOUT_MS.QUICK, totalDeadlineMs: FETCH_TIMEOUT_MS.QUICK, ...(json === undefined ? {} : { body: json }) };
203
+ return this.http.send({ request });
204
+ }
243
205
  }
244
206
  function enc(value) {
245
207
  return encodeURIComponent(value);
246
208
  }
209
+ function repoPath(owner, repo) {
210
+ return `/repos/${enc(owner)}/${enc(repo)}`;
211
+ }
212
+ function isOk(status) {
213
+ return status >= 200 && status < 300;
214
+ }
215
+ /** Parse the body (a non-JSON body fails first, as before), then reject a non-2xx status with GitHub's own message. */
216
+ async function okJson(resp, failure) {
217
+ const json = await readGithubJson(resp);
218
+ if (!isOk(resp.status))
219
+ throw githubError(json, resp.status, failure);
220
+ return json;
221
+ }
222
+ /** A required non-empty string field of a GitHub response; anything else is a malformed response. */
223
+ function requireString(value, missing) {
224
+ if (typeof value !== 'string' || !value)
225
+ throw new Error(missing);
226
+ return value;
227
+ }
228
+ /** GitHub's documented "a pull request already exists for this head/base" failure: a 422 whose message says so. */
229
+ function isExistingPullRequestConflict(status, json) {
230
+ // `message` is read before the status test on purpose: it keeps the exact
231
+ // pre-refactor behaviour for a non-2xx JSON `null` body (a TypeError here).
232
+ const message = typeof json.message === 'string' ? json.message : '';
233
+ return status === 422 && /already exists/i.test(message);
234
+ }
235
+ /**
236
+ * The Contents API's inline base64 content, or a clear, attributable error
237
+ * for a directory listing, a non-file entry, or the 1-100 MB shape that
238
+ * carries no inline content (see `readManifest`'s doc comment).
239
+ */
240
+ function inlineFileContent(json, where) {
241
+ if (Array.isArray(json)) {
242
+ throw new Error(`Registry manifest path is a directory, not a file: ${where}`);
243
+ }
244
+ if (json.type !== 'file') {
245
+ throw new Error(`Registry manifest path is not a file (type: ${String(json.type)}): ${where}`);
246
+ }
247
+ if (json.encoding !== 'base64' || typeof json.content !== 'string') {
248
+ throw new Error(`Registry manifest at ${where} is too large for the Contents API's inline response ` +
249
+ `(size: ${typeof json.size === 'number' ? json.size : 'unknown'} bytes, encoding: ${String(json.encoding)}); ` +
250
+ 'split the manifest into a smaller file or fetch it via the Git Trees/raw-media-type API instead.');
251
+ }
252
+ return json.content;
253
+ }
254
+ /**
255
+ * Decode GitHub's newline-wrapped base64 and JSON-parse it (not schema-validated
256
+ * here; see `readManifest`). Node's base64 decoder already skips the embedded
257
+ * newlines, so no pre-stripping is needed (pinned by the newline-wrapped test).
258
+ */
259
+ function parseManifest(content, where) {
260
+ const decoded = Buffer.from(content, 'base64').toString('utf8');
261
+ try {
262
+ return JSON.parse(decoded);
263
+ }
264
+ catch (cause) {
265
+ throw new Error(`Registry manifest at ${where} is not valid JSON.`, { cause });
266
+ }
267
+ }
247
268
  /** URL-encodes each path segment individually so directory separators survive but special characters within a segment don't. */
248
269
  function encPath(path) {
249
270
  return path.split('/').filter(Boolean).map(encodeURIComponent).join('/');
package/dist/index.d.ts CHANGED
@@ -1,67 +1,16 @@
1
1
  /**
2
2
  * @module @jini-ai/registry
3
- *
4
- * Root barrel for pluggable content-registry backend implementations
5
- * (`static`/`github`/`database`) plus the shared version-resolution helpers
6
- * they build on. Wire types (`RegistryEntry`, `RegistryManifest`,
7
- * `RegistryBackend`, ...) live in `@jini-ai/protocol`; this package only adds
8
- * concrete backend logic, matching concern-owned storage adapters' split (protocol defines
9
- * the port, a leaf package implements adapters against it).
10
-
11
- * Archived provenance rationale:
12
- * ## Why a new package instead of folding into `@jini/core` or `@jini/sqlite`
13
- *
14
- * The task brief suggested `@jini/core` as a likely home. Read `@jini/core`'s
15
- * own `archived provenance ledger` first: its charter is explicitly composition-only — "a
16
- * from-scratch implementation of the typed composition contract... there is
17
- * nothing to port" — it holds zero concrete port/adapter implementations
18
- * today (`token.ts`/`pack.ts`/`bindings.ts`/`daemon.ts` are all pure DI
19
- * machinery). Adding stateful backend classes (in-memory, GitHub-PR-mutating,
20
- * sqlite-backed) would be a first-of-its-kind widening of that charter, which
21
- * reads as exactly the kind of ad-hoc scope creep extraction-plan.md §9 warns
22
- * against ("a new kernel token requires a kernel invariant, not merely a need
23
- * discovered by the first consumer").
24
- *
25
- * `@jini/sqlite` was the other candidate (it already holds one concrete
26
- * `better-sqlite3`-backed adapter, `event-log.ts`, implementing `@jini/daemon`'s
27
- * `EventLog` port). But `@jini/sqlite`'s own archived provenance ledger scopes it
28
- * specifically to durable adapters for daemon/core kernel ports; a registry
29
- * backend is not a kernel port and two of the three backends here
30
- * (`static`/`github`) have no sqlite dependency at all.
31
- *
32
- * Instead this follows the same shape as `@jini/sqlite` itself: `@jini/protocol`
33
- * defines the pure wire types and the `RegistryBackend` port (already true
34
- * before this change — see "What already existed" below); this new leaf
35
- * package holds concrete backend implementations against that port, exactly
36
- * as `@jini/sqlite` holds concrete `EventLog` implementations against
37
- * `@jini/daemon`'s port.
38
- *
39
- * ## 2026-10-02 registry merge and object arguments (dbpkg-registry)
40
- *
41
- * The catalog-builder subpath keeps descriptor enumeration, source classification,
42
- * search vocabulary and clock policy behind host ports. Its SQLite bridge lives in
43
- * `src/tool-catalog-builder/sqlite.ts`, separately from the provider-free barrel,
44
- * so a browser or alternate search backend never acquires a storage dependency.
45
- * The bridge borrows its connection; the caller allocates one database per independent
46
- * snapshot and owns retirement. Reusing the same database intentionally reseeds that
47
- * shared snapshot rather than allocating or closing an implicit default database.
48
- *
49
- * All existing public export names are retained. Functions and constructors now take
50
- * required argument objects followed by optional argument objects; no old-shape
51
- * wrappers or aliases were added. Backend methods match the current protocol port.
52
- * `src/ports.ts` defines database, HTTP and clock seams. The GitHub client passes the
53
- * existing QUICK timeout to its required transport port, which owns timeout error
54
- * and cancellation behavior. Default timestamps still use the system clock. SQL,
55
- * transaction boundaries, canonical signing bytes, BM25 weights and error messages
56
- * for valid argument shapes remain unchanged. Unknown trust/backend modes now fail
57
- * closed through the existing protocol schemas.
58
- *
59
- * No rationale comment was removed by this job. Manifest/barrel/changelog merge
60
- * proposals and cross-package caller needs are recorded in
61
- * `dbpkg-registry-merge-needs.json` and `dbpkg-registry-handoff.md`. The existing dirty
62
- * manifest, root barrel and changelog remain owned by their previous writers.
63
- * Tests are written; execution, typecheck, build and packaging are UNPROVEN because
64
- * the owner explicitly deferred verification. No version change or lockfile edit.
3
+ * Concrete static/GitHub/database backends implement the protocol-owned RegistryBackend port.
4
+ * Keep them outside composition-only core and kernel-store adapters: registry storage is a
5
+ * feature concern, and static/GitHub backends need no SQLite dependency.
6
+ * Catalog-building enumeration, classification, search vocabulary and clock policy are host ports.
7
+ * Its SQLite bridge is a separate entry so browser/alternate-search consumers remain storage-free.
8
+ * The bridge borrows its connection; hosts own snapshot allocation and retirement. Reusing one
9
+ * database deliberately reseeds that snapshot, never allocates/closes an implicit default.
10
+ * Public functions/constructors take required and optional argument objects; backend methods follow
11
+ * the protocol port. The required GitHub transport owns QUICK timeout/cancellation behavior.
12
+ * Signing bytes, transaction boundaries and BM25 policy stay at their owning implementations;
13
+ * protocol schemas reject unknown trust/backend modes rather than guessing.
65
14
  */
66
15
  export type { ParsedRegistrySpecifier, ResolvedRegistryEntryVersion } from './versioning.js';
67
16
  export { parseRegistrySpecifier, resolveRegistryEntryVersion } from './versioning.js';
@@ -28,55 +28,18 @@ export class StaticRegistryBackend {
28
28
  this.clock = options.clock ?? { nowMs: () => Date.now() };
29
29
  }
30
30
  async list(_required, filter = {}) {
31
- const parsedFilter = RegistryListFilterSchema.parse(filter);
32
- let entries = validEntries(this.getManifest());
33
- if (!parsedFilter?.includeYanked) {
34
- entries = entries.filter((entry) => !entry.yanked);
35
- }
36
- if (parsedFilter?.publisher) {
37
- const publisher = parsedFilter.publisher.toLowerCase();
38
- entries = entries.filter((entry) => entry.publisher?.id?.toLowerCase() === publisher || entry.publisher?.github?.toLowerCase() === publisher);
39
- }
40
- if (parsedFilter?.tags && parsedFilter.tags.length > 0) {
41
- const tags = parsedFilter.tags.map((tag) => tag.toLowerCase());
42
- entries = entries.filter((entry) => {
43
- const entryTags = new Set((entry.tags ?? []).map((tag) => tag.toLowerCase()));
44
- return tags.every((tag) => entryTags.has(tag));
45
- });
46
- }
47
- if (parsedFilter?.query) {
48
- const terms = parsedFilter.query.toLowerCase().split(/\s+/g).filter(Boolean);
49
- if (terms.length > 0) {
50
- entries = entries.filter((entry) => terms.some((term) => searchHaystack(entry).includes(term)));
51
- }
52
- }
53
- return entries;
31
+ const parsedFilter = RegistryListFilterSchema.unwrap().parse(filter);
32
+ return validEntries(this.getManifest()).filter(listFilterPredicate(parsedFilter));
54
33
  }
55
34
  async search(required, optional = {}) {
56
35
  const query = RegistrySearchQuerySchema.parse({ ...required, ...optional });
57
- const terms = query.query.toLowerCase().split(/\s+/g).filter(Boolean);
58
- const tags = new Set((query.tags ?? []).map((tag) => tag.toLowerCase()));
36
+ const terms = queryTerms(query.query);
37
+ const tags = lowercased(query.tags);
59
38
  // Pass `includeYanked` through to `list` so search honors the same
60
39
  // filter contract instead of unconditionally dropping yanked entries.
61
40
  const entries = await this.list({}, { includeYanked: query.includeYanked });
62
- const results = [];
63
- for (const entry of entries) {
64
- if (tags.size > 0) {
65
- const entryTags = new Set((entry.tags ?? []).map((tag) => tag.toLowerCase()));
66
- if (![...tags].every((tag) => entryTags.has(tag)))
67
- continue;
68
- }
69
- const haystack = searchHaystack(entry);
70
- const matched = terms.filter((term) => haystack.includes(term));
71
- if (terms.length > 0 && matched.length === 0)
72
- continue;
73
- results.push({
74
- entry,
75
- score: terms.length === 0 ? 0 : matched.length / terms.length,
76
- matched,
77
- });
78
- }
79
- return results
41
+ return entries
42
+ .flatMap((entry) => searchResultFor(entry, terms, tags))
80
43
  .sort((left, right) => right.score - left.score || left.entry.name.localeCompare(right.entry.name))
81
44
  .slice(0, query.limit ?? 100);
82
45
  }
@@ -121,7 +84,6 @@ export class StaticRegistryBackend {
121
84
  return resolved?.entry ?? null;
122
85
  }
123
86
  async doctor(_required) {
124
- const issues = [];
125
87
  // Deliberately audits the RAW manifest entries (not the `validEntries()`
126
88
  // schema-filtered set `list`/`search`/`resolve` use) — doctor's whole
127
89
  // purpose is to surface malformed data, so silently dropping a bad entry
@@ -139,69 +101,11 @@ export class StaticRegistryBackend {
139
101
  // Report that as one explicit issue instead of letting `for...of` throw
140
102
  // a bare `TypeError` out of a caller-facing diagnostic method.
141
103
  const rawEntries = manifestEntriesRaw(this.getManifest());
142
- if (!Array.isArray(rawEntries)) {
143
- issues.push({
144
- severity: 'error',
145
- code: 'malformed-manifest',
146
- message: 'Registry manifest "entries" is missing or not an array; no entries could be checked.',
147
- });
148
- }
149
104
  const entries = Array.isArray(rawEntries) ? rawEntries : [];
150
- for (const raw of entries) {
151
- const value = raw;
152
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
153
- issues.push({
154
- severity: 'error',
155
- code: 'malformed-entry',
156
- message: 'Registry entry is not a valid object and could not be checked.',
157
- });
158
- continue;
159
- }
160
- const candidate = value;
161
- const name = typeof candidate.name === 'string' ? candidate.name : undefined;
162
- if (!name || !/^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/.test(name)) {
163
- issues.push({
164
- severity: 'error',
165
- code: 'invalid-name',
166
- message: 'Registry entry name must be vendor/name.',
167
- pluginName: name,
168
- });
169
- }
170
- const dist = candidate.dist && typeof candidate.dist === 'object' ? candidate.dist : undefined;
171
- if (!candidate.source && !dist?.archive) {
172
- issues.push({
173
- severity: 'error',
174
- code: 'missing-source',
175
- message: 'Registry entry must provide source or dist.archive.',
176
- pluginName: name,
177
- });
178
- }
179
- if (!candidate.license) {
180
- issues.push({
181
- severity: 'warning',
182
- code: 'missing-license',
183
- message: 'Registry entry should declare a license.',
184
- pluginName: name,
185
- });
186
- }
187
- const capabilitiesSummary = Array.isArray(candidate.capabilitiesSummary) ? candidate.capabilitiesSummary : undefined;
188
- if (!capabilitiesSummary || capabilitiesSummary.length === 0) {
189
- issues.push({
190
- severity: 'warning',
191
- code: 'missing-capabilities',
192
- message: 'Registry entry should summarize its capabilities.',
193
- pluginName: name,
194
- });
195
- }
196
- if (candidate.yanked && !candidate.yankReason) {
197
- issues.push({
198
- severity: 'error',
199
- code: 'missing-yank-reason',
200
- message: 'Yanked entries must keep a human-readable reason.',
201
- pluginName: name,
202
- });
203
- }
204
- }
105
+ const issues = [
106
+ ...(Array.isArray(rawEntries) ? [] : [{ ...MALFORMED_MANIFEST_ISSUE }]),
107
+ ...entries.flatMap(doctorEntryIssues),
108
+ ];
205
109
  return {
206
110
  ok: !issues.some((issue) => issue.severity === 'error'),
207
111
  backendId: this.id,
@@ -281,4 +185,100 @@ function searchHaystack(entry) {
281
185
  .join(' ')
282
186
  .toLowerCase();
283
187
  }
188
+ /** @internal Lowercase every string in an optional list. */
189
+ function lowercased(values) {
190
+ return (values ?? []).map((value) => value.toLowerCase());
191
+ }
192
+ /** @internal Whitespace-separated, lowercased, non-empty query terms. */
193
+ function queryTerms(query) {
194
+ return query.toLowerCase().split(/\s+/g).filter(Boolean);
195
+ }
196
+ /** @internal True when the entry carries every one of the (already lowercased) `tags`; an empty list admits every entry. */
197
+ function hasEveryTag(entry, tags) {
198
+ const entryTags = new Set(lowercased(entry.tags));
199
+ return tags.every((tag) => entryTags.has(tag));
200
+ }
201
+ /** @internal `list`'s filter: yanked, publisher id/github handle, every tag, and any query term — all case-insensitive. */
202
+ function listFilterPredicate(filter) {
203
+ const publisher = filter.publisher?.toLowerCase();
204
+ const tags = lowercased(filter.tags);
205
+ const terms = queryTerms(filter.query ?? '');
206
+ return (entry) => (filter.includeYanked === true || !entry.yanked) &&
207
+ (!publisher || publishedBy(entry, publisher)) &&
208
+ hasEveryTag(entry, tags) &&
209
+ (terms.length === 0 || terms.some((term) => searchHaystack(entry).includes(term)));
210
+ }
211
+ /** @internal True when the (already lowercased) `publisher` is the entry's publisher id or GitHub handle. */
212
+ function publishedBy(entry, publisher) {
213
+ return entry.publisher?.id?.toLowerCase() === publisher || entry.publisher?.github?.toLowerCase() === publisher;
214
+ }
215
+ /** @internal `search`'s per-entry result: none when a tag is missing or no term matches, else the matched fraction of terms (0 for an empty query). */
216
+ function searchResultFor(entry, terms, tags) {
217
+ if (!hasEveryTag(entry, tags))
218
+ return [];
219
+ const haystack = searchHaystack(entry);
220
+ const matched = terms.filter((term) => haystack.includes(term));
221
+ if (terms.length > 0 && matched.length === 0)
222
+ return [];
223
+ return [{ entry, score: terms.length === 0 ? 0 : matched.length / terms.length, matched }];
224
+ }
225
+ const MALFORMED_MANIFEST_ISSUE = {
226
+ severity: 'error',
227
+ code: 'malformed-manifest',
228
+ message: 'Registry manifest "entries" is missing or not an array; no entries could be checked.',
229
+ };
230
+ /**
231
+ * @internal The per-entry `doctor` checks, in report order. Each reads a RAW,
232
+ * unvalidated entry, so every field is guarded before it is dereferenced.
233
+ */
234
+ const DOCTOR_ENTRY_CHECKS = [
235
+ {
236
+ severity: 'error',
237
+ code: 'invalid-name',
238
+ message: 'Registry entry name must be vendor/name.',
239
+ // The schema rejects undefined and "" too, so no separate presence check.
240
+ failed: (_candidate, name) => !RegistryEntrySchema.shape.name.safeParse(name).success,
241
+ },
242
+ {
243
+ severity: 'error',
244
+ code: 'missing-source',
245
+ message: 'Registry entry must provide source or dist.archive.',
246
+ failed: (candidate) => {
247
+ const dist = candidate.dist && typeof candidate.dist === 'object' ? candidate.dist : undefined;
248
+ return !candidate.source && !dist?.archive;
249
+ },
250
+ },
251
+ {
252
+ severity: 'warning',
253
+ code: 'missing-license',
254
+ message: 'Registry entry should declare a license.',
255
+ failed: (candidate) => !candidate.license,
256
+ },
257
+ {
258
+ severity: 'warning',
259
+ code: 'missing-capabilities',
260
+ message: 'Registry entry should summarize its capabilities.',
261
+ failed: (candidate) => !Array.isArray(candidate.capabilitiesSummary) || candidate.capabilitiesSummary.length === 0,
262
+ },
263
+ {
264
+ severity: 'error',
265
+ code: 'missing-yank-reason',
266
+ message: 'Yanked entries must keep a human-readable reason.',
267
+ failed: (candidate) => Boolean(candidate.yanked) && !candidate.yankReason,
268
+ },
269
+ ];
270
+ /** @internal `doctor`'s issues for one raw manifest entry; a value that is not a plain object is one `malformed-entry` issue. */
271
+ function doctorEntryIssues(raw) {
272
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
273
+ return [{ severity: 'error', code: 'malformed-entry', message: 'Registry entry is not a valid object and could not be checked.' }];
274
+ }
275
+ const candidate = raw;
276
+ const name = typeof candidate.name === 'string' ? candidate.name : undefined;
277
+ return DOCTOR_ENTRY_CHECKS.filter((check) => check.failed(candidate, name)).map(({ severity, code, message }) => ({
278
+ severity,
279
+ code,
280
+ message,
281
+ pluginName: name,
282
+ }));
283
+ }
284
284
  //# sourceMappingURL=static-backend.js.map