@jini-ai/search 0.7.3-next.2 → 0.7.4
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 +21 -0
- package/dist/indexer-backfill.d.ts +28 -23
- package/dist/indexer-backfill.js +7 -7
- package/dist/indexer-reconcile.d.ts +44 -33
- package/dist/indexer-reconcile.js +17 -11
- package/dist/indexer-write.d.ts +30 -19
- package/dist/indexer-write.js +8 -8
- package/dist/indexer.js +16 -16
- package/dist/public-http/routes/site/search.d.ts +65 -0
- package/dist/public-http/routes/site/search.js +75 -0
- package/dist/site/access.d.ts +42 -0
- package/dist/site/access.js +63 -0
- package/dist/site/cms-document-source.d.ts +137 -0
- package/dist/site/cms-document-source.js +136 -0
- package/dist/site/index-state-store.d.ts +85 -0
- package/dist/site/index-state-store.js +212 -0
- package/dist/site/media-search-source.d.ts +100 -0
- package/dist/site/media-search-source.js +134 -0
- package/dist/site/settings.d.ts +63 -0
- package/dist/site/settings.js +54 -0
- package/package.json +61 -4
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { encodeSearchKey } from "../contract.js";
|
|
2
|
+
const STATUSES = ["pending", "indexed", "unknown", "failed"];
|
|
3
|
+
/** Row → port shape; optional fields are omitted rather than `undefined`. @complexity O(1). */
|
|
4
|
+
function toStateRow(row) {
|
|
5
|
+
return {
|
|
6
|
+
target: { siteId: row.site_id, providerId: row.provider_id, generation: Number(row.generation) },
|
|
7
|
+
key: { siteId: row.site_id, workspaceId: row.workspace_id, collection: row.collection, documentId: row.document_id },
|
|
8
|
+
revision: Number(row.revision),
|
|
9
|
+
deleted: Number(row.deleted) === 1,
|
|
10
|
+
status: row.status,
|
|
11
|
+
attempts: Number(row.attempts),
|
|
12
|
+
...(row.task_id === null ? {} : { taskId: row.task_id }),
|
|
13
|
+
...(row.last_error === null ? {} : { lastError: row.last_error }),
|
|
14
|
+
updatedAtMs: Number(row.updated_at_ms),
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/** Port row → columns. The key's own `siteId` is the target's (one site per target). @complexity O(key length). */
|
|
18
|
+
function toStateColumns(row) {
|
|
19
|
+
return {
|
|
20
|
+
site_id: row.target.siteId, provider_id: row.target.providerId, generation: row.target.generation,
|
|
21
|
+
doc_key: encodeSearchKey({ key: row.key }),
|
|
22
|
+
workspace_id: row.key.workspaceId, collection: row.key.collection, document_id: row.key.documentId,
|
|
23
|
+
revision: row.revision, deleted: row.deleted ? 1 : 0, status: row.status, attempts: row.attempts,
|
|
24
|
+
task_id: row.taskId ?? null, last_error: row.lastError ?? null, updated_at_ms: row.updatedAtMs,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** A stored pointer pair, or `null` when that half is empty (the CHECK keeps both columns in step). */
|
|
28
|
+
function toTarget({ siteId, providerId, generation }, _optional = {}) {
|
|
29
|
+
return providerId === null || generation === null ? null : { siteId, providerId, generation: Number(generation) };
|
|
30
|
+
}
|
|
31
|
+
function createIndexWatermarks({ kernel, t }, scoped) {
|
|
32
|
+
return {
|
|
33
|
+
async getWatermark({ target, collection }) {
|
|
34
|
+
const row = await kernel.run(db => db.selectFrom(t.watermarks).select(["cursor", "done"])
|
|
35
|
+
.where("site_id", "=", target.siteId).where("provider_id", "=", target.providerId)
|
|
36
|
+
.where("generation", "=", target.generation).where("collection", "=", collection)
|
|
37
|
+
.executeTakeFirst());
|
|
38
|
+
if (!row)
|
|
39
|
+
return null;
|
|
40
|
+
return { ...(row.cursor === null ? {} : { cursor: row.cursor }), done: Number(row.done) === 1 };
|
|
41
|
+
},
|
|
42
|
+
async putWatermark({ target, collection, cursor, done }) {
|
|
43
|
+
const changes = { cursor: cursor ?? null, done: done ? 1 : 0 };
|
|
44
|
+
await kernel.run(db => db.insertInto(t.watermarks).values({ ...scoped(target), collection, ...changes })
|
|
45
|
+
.onConflict(oc => oc.columns(["site_id", "provider_id", "generation", "collection"]).doUpdateSet(changes))
|
|
46
|
+
.execute());
|
|
47
|
+
},
|
|
48
|
+
async deleteTarget({ target }) {
|
|
49
|
+
await kernel.transaction(async () => {
|
|
50
|
+
for (const table of [t.state, t.watermarks]) {
|
|
51
|
+
await kernel.run(db => db.deleteFrom(table).where("site_id", "=", target.siteId)
|
|
52
|
+
.where("provider_id", "=", target.providerId).where("generation", "=", target.generation).execute());
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
async function readIndexCounts({ kernel, t }, { target }) {
|
|
59
|
+
const rows = await kernel.run(db => db.selectFrom(t.state)
|
|
60
|
+
.select(eb => ["status", eb.fn.countAll().as("n")])
|
|
61
|
+
.where("site_id", "=", target.siteId).where("provider_id", "=", target.providerId)
|
|
62
|
+
.where("generation", "=", target.generation).groupBy("status").execute());
|
|
63
|
+
const counts = Object.fromEntries(STATUSES.map(status => [status, 0]));
|
|
64
|
+
for (const row of rows)
|
|
65
|
+
counts[row.status] = Number(row.n);
|
|
66
|
+
return counts;
|
|
67
|
+
}
|
|
68
|
+
/** The bookkeeping half. @complexity each method is one indexed statement (deleteTarget: two). */
|
|
69
|
+
function createIndexState({ kernel, t }) {
|
|
70
|
+
const scoped = (target) => ({ site_id: target.siteId, provider_id: target.providerId, generation: target.generation });
|
|
71
|
+
return {
|
|
72
|
+
async get({ target, key }) {
|
|
73
|
+
const row = await kernel.run(db => db.selectFrom(t.state).selectAll()
|
|
74
|
+
.where("site_id", "=", target.siteId).where("provider_id", "=", target.providerId)
|
|
75
|
+
.where("generation", "=", target.generation).where("doc_key", "=", encodeSearchKey({ key }))
|
|
76
|
+
.executeTakeFirst());
|
|
77
|
+
return row ? toStateRow(row) : null;
|
|
78
|
+
},
|
|
79
|
+
async put({ row }) {
|
|
80
|
+
const values = toStateColumns(row);
|
|
81
|
+
const { site_id: _s, provider_id: _p, generation: _g, doc_key: _k, ...updatable } = values;
|
|
82
|
+
const result = await kernel.run(db => db.insertInto(t.state).values(values)
|
|
83
|
+
.onConflict(oc => oc.columns(["site_id", "provider_id", "generation", "doc_key"]).doUpdateSet(updatable)
|
|
84
|
+
.where(`${t.state}.revision`, "<=", row.revision))
|
|
85
|
+
.executeTakeFirst());
|
|
86
|
+
return Number(result.numInsertedOrUpdatedRows ?? 0n) === 1;
|
|
87
|
+
},
|
|
88
|
+
/**
|
|
89
|
+
* Compare-and-swap settle: ONE UPDATE that matches only while the stored row still carries the
|
|
90
|
+
* observed revision and task, so an older write's completion never replaces a newer revision's
|
|
91
|
+
* bookkeeping. @complexity O(1), one primary-key UPDATE.
|
|
92
|
+
*/
|
|
93
|
+
async settle({ row, expected }) {
|
|
94
|
+
const values = toStateColumns(row);
|
|
95
|
+
const { site_id: _s, provider_id: _p, generation: _g, doc_key: _k, ...updatable } = values;
|
|
96
|
+
const result = await kernel.run(db => db.updateTable(t.state).set(updatable)
|
|
97
|
+
.where("site_id", "=", values.site_id).where("provider_id", "=", values.provider_id)
|
|
98
|
+
.where("generation", "=", values.generation).where("doc_key", "=", values.doc_key)
|
|
99
|
+
.where("revision", "=", expected.revision)
|
|
100
|
+
.where("task_id", expected.taskId === null ? "is" : "=", expected.taskId)
|
|
101
|
+
.executeTakeFirst());
|
|
102
|
+
return Number(result.numUpdatedRows) === 1;
|
|
103
|
+
},
|
|
104
|
+
async listByStatus({ target, statuses, limit }, { failedBelowAttempts } = {}) {
|
|
105
|
+
// `IN ()` is not valid SQL; asking for no status matches no row.
|
|
106
|
+
if (statuses.length === 0)
|
|
107
|
+
return [];
|
|
108
|
+
const rows = await kernel.run(db => {
|
|
109
|
+
const candidates = db.selectFrom(t.state).selectAll()
|
|
110
|
+
.where("site_id", "=", target.siteId).where("provider_id", "=", target.providerId)
|
|
111
|
+
.where("generation", "=", target.generation).where("status", "in", [...statuses]);
|
|
112
|
+
// Exhausted failures leave the candidate set BEFORE the limit, so they cannot starve the rest.
|
|
113
|
+
const retryable = failedBelowAttempts === undefined
|
|
114
|
+
? candidates
|
|
115
|
+
: candidates.where((eb) => eb.or([eb("status", "!=", "failed"), eb("attempts", "<", failedBelowAttempts)]));
|
|
116
|
+
// Oldest first so a retry sweep reaches every row, with the key breaking ties stably.
|
|
117
|
+
return retryable.orderBy("updated_at_ms", "asc").orderBy("doc_key", "asc").limit(limit).execute();
|
|
118
|
+
});
|
|
119
|
+
return rows.map(toStateRow);
|
|
120
|
+
},
|
|
121
|
+
counts: input => readIndexCounts({ kernel, t }, input),
|
|
122
|
+
...createIndexWatermarks({ kernel, t }, scoped),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* ONE compare-and-swap statement: the building pointer must still be `expected` AND the active
|
|
127
|
+
* pointer still `active` (as just read), so the caller's `replaced` is exactly what this switch
|
|
128
|
+
* displaced. A concurrent promote, rebuild or clear changes one of them first and no row updates.
|
|
129
|
+
* @complexity O(1), one primary-key UPDATE.
|
|
130
|
+
*/
|
|
131
|
+
async function swapPointers({ kernel, t }, required) {
|
|
132
|
+
const { siteId, expected, active, nowMs } = required;
|
|
133
|
+
const result = await kernel.run(db => {
|
|
134
|
+
const swap = db.updateTable(t.targets)
|
|
135
|
+
.set(({ ref }) => ({
|
|
136
|
+
active_provider_id: ref("building_provider_id"), active_generation: ref("building_generation"),
|
|
137
|
+
building_provider_id: null, building_generation: null, updated_at_ms: nowMs,
|
|
138
|
+
}))
|
|
139
|
+
.where("site_id", "=", siteId)
|
|
140
|
+
.where("building_provider_id", "=", expected.providerId).where("building_generation", "=", expected.generation);
|
|
141
|
+
return (active === null
|
|
142
|
+
? swap.where("active_provider_id", "is", null)
|
|
143
|
+
: swap.where("active_provider_id", "=", active.providerId).where("active_generation", "=", active.generation))
|
|
144
|
+
.executeTakeFirst();
|
|
145
|
+
});
|
|
146
|
+
return Number(result.numUpdatedRows) === 1;
|
|
147
|
+
}
|
|
148
|
+
/** The pointer half. `promote` is the atomic generation switch. @complexity O(1) per call. */
|
|
149
|
+
function createTargets({ kernel, t, now }, _optional = {}) {
|
|
150
|
+
const retainRetired = async ({ siteId, active }, _options = {}) => {
|
|
151
|
+
await kernel.run(db => db.insertInto(t.retired)
|
|
152
|
+
.values({ site_id: siteId, provider_id: active.providerId, generation: active.generation, retired_at_ms: now() })
|
|
153
|
+
.onConflict(oc => oc.columns(["site_id", "provider_id", "generation"]).doNothing()).execute());
|
|
154
|
+
};
|
|
155
|
+
const read = async ({ siteId }, _optional = {}) => {
|
|
156
|
+
const row = await kernel.run(db => db.selectFrom(t.targets).selectAll().where("site_id", "=", siteId).executeTakeFirst());
|
|
157
|
+
if (!row)
|
|
158
|
+
return { active: null, building: null };
|
|
159
|
+
return {
|
|
160
|
+
active: toTarget({ siteId, providerId: row.active_provider_id, generation: row.active_generation }),
|
|
161
|
+
building: toTarget({ siteId, providerId: row.building_provider_id, generation: row.building_generation }),
|
|
162
|
+
};
|
|
163
|
+
};
|
|
164
|
+
return {
|
|
165
|
+
get: ({ siteId }) => read({ siteId }),
|
|
166
|
+
async setBuilding({ target }) {
|
|
167
|
+
const building = { building_provider_id: target.providerId, building_generation: target.generation, updated_at_ms: now() };
|
|
168
|
+
await kernel.run(db => db.insertInto(t.targets)
|
|
169
|
+
.values({ site_id: target.siteId, active_provider_id: null, active_generation: null, ...building })
|
|
170
|
+
.onConflict(oc => oc.column("site_id").doUpdateSet(building)).execute());
|
|
171
|
+
},
|
|
172
|
+
promote: ({ siteId, expected }) => kernel.transaction(async () => {
|
|
173
|
+
const { active } = await read({ siteId });
|
|
174
|
+
const swapped = await swapPointers({ kernel, t }, { siteId, expected, active, nowMs: now() });
|
|
175
|
+
if (!swapped)
|
|
176
|
+
return false;
|
|
177
|
+
// Same transaction as the switch: the replaced index is dropped later even if this process dies now.
|
|
178
|
+
if (active !== null) {
|
|
179
|
+
await retainRetired({ siteId, active });
|
|
180
|
+
}
|
|
181
|
+
return { replaced: active };
|
|
182
|
+
}),
|
|
183
|
+
async listRetired({ siteId }) {
|
|
184
|
+
const rows = await kernel.run(db => db.selectFrom(t.retired).select(["provider_id", "generation"])
|
|
185
|
+
.where("site_id", "=", siteId).orderBy("retired_at_ms", "asc").orderBy("provider_id", "asc").orderBy("generation", "asc").execute());
|
|
186
|
+
return rows.map(row => ({ siteId, providerId: row.provider_id, generation: Number(row.generation) }));
|
|
187
|
+
},
|
|
188
|
+
async forgetRetired({ target }) {
|
|
189
|
+
await kernel.run(db => db.deleteFrom(t.retired).where("site_id", "=", target.siteId)
|
|
190
|
+
.where("provider_id", "=", target.providerId).where("generation", "=", target.generation).execute());
|
|
191
|
+
},
|
|
192
|
+
async clearBuilding({ siteId }) {
|
|
193
|
+
await kernel.run(db => db.updateTable(t.targets)
|
|
194
|
+
.set({ building_provider_id: null, building_generation: null, updated_at_ms: now() })
|
|
195
|
+
.where("site_id", "=", siteId).execute());
|
|
196
|
+
},
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* The SQL search-index store on one content database.
|
|
201
|
+
* @example const { indexState, targets } = createSqlSearchIndexStore({ kernel, now: clock.nowMs, tables });
|
|
202
|
+
* @complexity O(1) to build; see each half for per-call cost.
|
|
203
|
+
*/
|
|
204
|
+
export function createSqlSearchIndexStore(required, _optional = {}) {
|
|
205
|
+
// The host kernel is typed against its own schema, which never lists these raw-SQL tables; the
|
|
206
|
+
// same kernel is re-typed for them, and the injected names are typed as their literal keys
|
|
207
|
+
// (Kysely types are compile-time only, the real names reach the SQL).
|
|
208
|
+
const kernel = required.kernel;
|
|
209
|
+
const t = required.tables;
|
|
210
|
+
return { indexState: createIndexState({ kernel, t }), targets: createTargets({ kernel, t, now: required.now }) };
|
|
211
|
+
}
|
|
212
|
+
//# sourceMappingURL=index-state-store.js.map
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { type SearchAccessPort, type SearchDocumentSource } from "@jini-ai/search";
|
|
2
|
+
import type { DomainEvent } from "@jini-ai/core/contracts/events";
|
|
3
|
+
import type { MediaRecord } from "@jini-ai/core/contracts/site/cms-media";
|
|
4
|
+
/**
|
|
5
|
+
* @file Public image descriptions as a site-search document source (P10-M5.T2).
|
|
6
|
+
*
|
|
7
|
+
* The source indexes the stored, human-authored `description` of a current, eligible PUBLIC image
|
|
8
|
+
* and nothing else from the record: never the generation prompt in `source.provenance`, never
|
|
9
|
+
* Library documents, private ingress, trashed rows, or non-image media. The SAME publication rule
|
|
10
|
+
* ({@link isPublicSearchImage} by default, injected as `publicAccess`) decides both what `load`
|
|
11
|
+
* emits and what the query-time access port lets through, so a lagging index can never show what
|
|
12
|
+
* `load` would refuse.
|
|
13
|
+
*
|
|
14
|
+
* Change events: {@link createMediaSearchChangeSink} is the media repo's change sink, so every
|
|
15
|
+
* committed write (save, CAS save, file replace or restore, insert, trash marker, purge) enqueues one
|
|
16
|
+
* {@link MEDIA_SEARCH_CHANGED_EVENT} through the outbox in the SAME transaction as the write. The event only names the asset; delivery re-reads current
|
|
17
|
+
* state, so redelivery and an older event arriving after a newer change converge.
|
|
18
|
+
*/
|
|
19
|
+
/** The search collection of public images (grammar `^[a-z][a-z0-9_]{0,63}$`). */
|
|
20
|
+
export declare const MEDIA_SEARCH_COLLECTION = "media_image";
|
|
21
|
+
/** The outbox event a committed media write enqueues; payload-free beyond the asset id. */
|
|
22
|
+
export declare const MEDIA_SEARCH_CHANGED_EVENT = "media.search_changed";
|
|
23
|
+
/** Host ports for {@link createMediaSearchSource} and {@link createMediaSearchAccessPort}. */
|
|
24
|
+
export interface MediaSearchPorts {
|
|
25
|
+
/** The current row, or null when it no longer exists (purged). */
|
|
26
|
+
loadMedia(required: {
|
|
27
|
+
readonly workspaceId: string;
|
|
28
|
+
readonly id: string;
|
|
29
|
+
}): Promise<MediaRecord | null>;
|
|
30
|
+
/** One stable-order page of rows for backfill; `nextCursor` absent means done. */
|
|
31
|
+
scanMedia(required: {
|
|
32
|
+
readonly workspaceId: string;
|
|
33
|
+
readonly limit: number;
|
|
34
|
+
}, optional?: {
|
|
35
|
+
readonly cursor?: string;
|
|
36
|
+
}): Promise<{
|
|
37
|
+
readonly records: readonly MediaRecord[];
|
|
38
|
+
readonly nextCursor?: string;
|
|
39
|
+
}>;
|
|
40
|
+
/** The publication rule: whether this row is a public search document right now. */
|
|
41
|
+
publicAccess(required: {
|
|
42
|
+
readonly record: MediaRecord;
|
|
43
|
+
}): boolean;
|
|
44
|
+
/** The site-relative public URL of the image (its sanitized public rendition). */
|
|
45
|
+
publicPath(required: {
|
|
46
|
+
readonly record: MediaRecord;
|
|
47
|
+
}): string;
|
|
48
|
+
now(): number;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* The default publication rule: an active, non-Library, non-private raster or vector image with a
|
|
52
|
+
* known image MIME. Unknown MIME fails closed.
|
|
53
|
+
* @complexity O(1).
|
|
54
|
+
*/
|
|
55
|
+
export declare function isPublicSearchImage(required: {
|
|
56
|
+
readonly record: MediaRecord;
|
|
57
|
+
}, _optional?: Record<string, never>): boolean;
|
|
58
|
+
/**
|
|
59
|
+
* The media search source: emits only current, eligible public images.
|
|
60
|
+
* @complexity load O(1) port calls; scan O(page).
|
|
61
|
+
*/
|
|
62
|
+
export declare function createMediaSearchSource(required: MediaSearchPorts, _optional?: Record<string, never>): SearchDocumentSource;
|
|
63
|
+
/**
|
|
64
|
+
* Query-time access for media keys: re-reads each named row and applies the same publication rule
|
|
65
|
+
* as `load`. Keys of other sites, workspaces or collections are dropped (fail closed).
|
|
66
|
+
* @complexity O(k) row reads.
|
|
67
|
+
*/
|
|
68
|
+
export declare function createMediaSearchAccessPort(required: Pick<MediaSearchPorts, "loadMedia" | "publicAccess">, _optional?: Record<string, never>): SearchAccessPort;
|
|
69
|
+
/**
|
|
70
|
+
* Several access ports as one: a key is visible when the port owning its collection says so. Each
|
|
71
|
+
* port already drops collections it does not own, so the union never widens any one port's rule.
|
|
72
|
+
* @complexity O(ports) calls.
|
|
73
|
+
*/
|
|
74
|
+
export declare function unionSearchAccessPorts(required: {
|
|
75
|
+
readonly ports: readonly SearchAccessPort[];
|
|
76
|
+
}, _optional?: Record<string, never>): SearchAccessPort;
|
|
77
|
+
/** The outbox slice the sink writes through; its `enqueue` must join the caller's transaction. */
|
|
78
|
+
export interface MediaSearchOutbox {
|
|
79
|
+
enqueue(event: DomainEvent): Promise<void>;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* The media repo's change sink for site search: each committed description change, restore, trash
|
|
83
|
+
* or purge of ordinary media enqueues one {@link MEDIA_SEARCH_CHANGED_EVENT}. The repo calls it
|
|
84
|
+
* INSIDE the write's transaction and `outbox` runs on the same kernel, so the event row commits or
|
|
85
|
+
* rolls back with the media write: a failed write leaves no event, and a failed enqueue undoes the
|
|
86
|
+
* write. Library documents never emit. The event only names the asset; delivery re-reads current state.
|
|
87
|
+
* @complexity O(1) per change.
|
|
88
|
+
*/
|
|
89
|
+
export declare function createMediaSearchChangeSink(required: {
|
|
90
|
+
readonly outbox: MediaSearchOutbox;
|
|
91
|
+
readonly nowIso: () => string;
|
|
92
|
+
}, _optional?: Record<string, never>): {
|
|
93
|
+
changed(required: {
|
|
94
|
+
workspaceId: string;
|
|
95
|
+
mediaId: string;
|
|
96
|
+
kind: string;
|
|
97
|
+
marker: string;
|
|
98
|
+
}): Promise<void>;
|
|
99
|
+
};
|
|
100
|
+
//# sourceMappingURL=media-search-source.d.ts.map
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { encodeSearchKey } from "@jini-ai/search";
|
|
2
|
+
import { cmsSearchRevision } from "@jini-ai/search/site/cms-document-source";
|
|
3
|
+
/**
|
|
4
|
+
* @file Public image descriptions as a site-search document source (P10-M5.T2).
|
|
5
|
+
*
|
|
6
|
+
* The source indexes the stored, human-authored `description` of a current, eligible PUBLIC image
|
|
7
|
+
* and nothing else from the record: never the generation prompt in `source.provenance`, never
|
|
8
|
+
* Library documents, private ingress, trashed rows, or non-image media. The SAME publication rule
|
|
9
|
+
* ({@link isPublicSearchImage} by default, injected as `publicAccess`) decides both what `load`
|
|
10
|
+
* emits and what the query-time access port lets through, so a lagging index can never show what
|
|
11
|
+
* `load` would refuse.
|
|
12
|
+
*
|
|
13
|
+
* Change events: {@link createMediaSearchChangeSink} is the media repo's change sink, so every
|
|
14
|
+
* committed write (save, CAS save, file replace or restore, insert, trash marker, purge) enqueues one
|
|
15
|
+
* {@link MEDIA_SEARCH_CHANGED_EVENT} through the outbox in the SAME transaction as the write. The event only names the asset; delivery re-reads current
|
|
16
|
+
* state, so redelivery and an older event arriving after a newer change converge.
|
|
17
|
+
*/
|
|
18
|
+
/** The search collection of public images (grammar `^[a-z][a-z0-9_]{0,63}$`). */
|
|
19
|
+
export const MEDIA_SEARCH_COLLECTION = "media_image";
|
|
20
|
+
/** The outbox event a committed media write enqueues; payload-free beyond the asset id. */
|
|
21
|
+
export const MEDIA_SEARCH_CHANGED_EVENT = "media.search_changed";
|
|
22
|
+
/**
|
|
23
|
+
* The default publication rule: an active, non-Library, non-private raster or vector image with a
|
|
24
|
+
* known image MIME. Unknown MIME fails closed.
|
|
25
|
+
* @complexity O(1).
|
|
26
|
+
*/
|
|
27
|
+
export function isPublicSearchImage(required, _optional = {}) {
|
|
28
|
+
const { record } = required;
|
|
29
|
+
// A file an admin can read is not necessarily a public search document.
|
|
30
|
+
if (record.kind === "document" || record.status !== "active" || record.source.private === true)
|
|
31
|
+
return false;
|
|
32
|
+
return typeof record.source.contentType === "string" && record.source.contentType.startsWith("image/");
|
|
33
|
+
}
|
|
34
|
+
/** One record for a row (or its absence), with the CMS revision scheme so tombstones always outrank. */
|
|
35
|
+
function toRecord(required, _optional = {}) {
|
|
36
|
+
const { siteId, workspaceId, documentId, record, occurredAtMs, ports } = required;
|
|
37
|
+
const key = { siteId, workspaceId, collection: MEDIA_SEARCH_COLLECTION, documentId };
|
|
38
|
+
const live = record !== null && record.workspaceId === workspaceId && ports.publicAccess({ record });
|
|
39
|
+
const row = record === null ? null : { updated_at: record.updatedAt, publish_at: null, version: record.version };
|
|
40
|
+
const revision = cmsSearchRevision({ row, live, occurredAtMs });
|
|
41
|
+
if (!live)
|
|
42
|
+
return { key, revision, document: null };
|
|
43
|
+
// Index the stored description only; the title is the editorial display name, never a prompt.
|
|
44
|
+
return {
|
|
45
|
+
key, revision,
|
|
46
|
+
document: { key, revision, url: ports.publicPath({ record }), title: record.title, body: record.description ?? "", visibility: { kind: "public" } },
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The media search source: emits only current, eligible public images.
|
|
51
|
+
* @complexity load O(1) port calls; scan O(page).
|
|
52
|
+
*/
|
|
53
|
+
export function createMediaSearchSource(required, _optional = {}) {
|
|
54
|
+
const ports = required;
|
|
55
|
+
return {
|
|
56
|
+
collection: MEDIA_SEARCH_COLLECTION,
|
|
57
|
+
events: [MEDIA_SEARCH_CHANGED_EVENT],
|
|
58
|
+
documentIdOf: ({ event }) => (event.name === MEDIA_SEARCH_CHANGED_EVENT && typeof event.aggregateId === "string" && event.aggregateId !== "" ? event.aggregateId : null),
|
|
59
|
+
async load({ siteId, workspaceId, documentId, occurredAtMs }) {
|
|
60
|
+
const record = await ports.loadMedia({ workspaceId, id: documentId });
|
|
61
|
+
return toRecord({ siteId, workspaceId, documentId, record, occurredAtMs, ports });
|
|
62
|
+
},
|
|
63
|
+
async scan({ siteId, workspaceId, limit }, optional = {}) {
|
|
64
|
+
const page = await ports.scanMedia({ workspaceId, limit }, optional.cursor === undefined ? {} : { cursor: optional.cursor });
|
|
65
|
+
const occurredAtMs = ports.now();
|
|
66
|
+
const records = page.records
|
|
67
|
+
.filter(record => record.workspaceId === workspaceId && ports.publicAccess({ record }))
|
|
68
|
+
.map(record => toRecord({ siteId, workspaceId, documentId: record.id, record, occurredAtMs, ports }));
|
|
69
|
+
return page.nextCursor === undefined ? { records } : { records, nextCursor: page.nextCursor };
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Query-time access for media keys: re-reads each named row and applies the same publication rule
|
|
75
|
+
* as `load`. Keys of other sites, workspaces or collections are dropped (fail closed).
|
|
76
|
+
* @complexity O(k) row reads.
|
|
77
|
+
*/
|
|
78
|
+
export function createMediaSearchAccessPort(required, _optional = {}) {
|
|
79
|
+
const { loadMedia, publicAccess } = required;
|
|
80
|
+
return {
|
|
81
|
+
async visibleKeys({ siteId, keys }) {
|
|
82
|
+
const visible = new Set();
|
|
83
|
+
for (const key of keys) {
|
|
84
|
+
if (key.siteId !== siteId || key.collection !== MEDIA_SEARCH_COLLECTION)
|
|
85
|
+
continue;
|
|
86
|
+
const record = await loadMedia({ workspaceId: key.workspaceId, id: key.documentId });
|
|
87
|
+
if (record !== null && record.workspaceId === key.workspaceId && publicAccess({ record }))
|
|
88
|
+
visible.add(encodeSearchKey({ key }));
|
|
89
|
+
}
|
|
90
|
+
return visible;
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Several access ports as one: a key is visible when the port owning its collection says so. Each
|
|
96
|
+
* port already drops collections it does not own, so the union never widens any one port's rule.
|
|
97
|
+
* @complexity O(ports) calls.
|
|
98
|
+
*/
|
|
99
|
+
export function unionSearchAccessPorts(required, _optional = {}) {
|
|
100
|
+
return {
|
|
101
|
+
async visibleKeys(input) {
|
|
102
|
+
const sets = await Promise.all(required.ports.map(port => port.visibleKeys(input)));
|
|
103
|
+
return new Set(sets.flatMap(set => [...set]));
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/** Ids are deterministic per committed write, so a retried enqueue of the same write is one event. */
|
|
108
|
+
function changeEvent(required, _optional = {}) {
|
|
109
|
+
const { workspaceId, mediaId, marker, occurredAt } = required;
|
|
110
|
+
return {
|
|
111
|
+
id: `${MEDIA_SEARCH_CHANGED_EVENT}:${workspaceId}:${mediaId}:${marker}`, name: MEDIA_SEARCH_CHANGED_EVENT,
|
|
112
|
+
occurredAt, workspaceId, aggregateId: mediaId, payload: { mediaId },
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* The media repo's change sink for site search: each committed description change, restore, trash
|
|
117
|
+
* or purge of ordinary media enqueues one {@link MEDIA_SEARCH_CHANGED_EVENT}. The repo calls it
|
|
118
|
+
* INSIDE the write's transaction and `outbox` runs on the same kernel, so the event row commits or
|
|
119
|
+
* rolls back with the media write: a failed write leaves no event, and a failed enqueue undoes the
|
|
120
|
+
* write. Library documents never emit. The event only names the asset; delivery re-reads current state.
|
|
121
|
+
* @complexity O(1) per change.
|
|
122
|
+
*/
|
|
123
|
+
export function createMediaSearchChangeSink(required, _optional = {}) {
|
|
124
|
+
const { outbox, nowIso } = required;
|
|
125
|
+
return {
|
|
126
|
+
async changed({ workspaceId, mediaId, kind, marker }) {
|
|
127
|
+
// A file an admin can read is not necessarily a public search document.
|
|
128
|
+
if (kind === "document")
|
|
129
|
+
return;
|
|
130
|
+
await outbox.enqueue(changeEvent({ workspaceId, mediaId, marker, occurredAt: nowIso() }));
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
//# sourceMappingURL=media-search-source.js.map
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The per-site `core.search/provider` setting: which search provider a site's index and
|
|
3
|
+
* queries use. Default `builtin` (`@jini-ai/search`'s `BUILTIN_SEARCH_PROVIDER_ID`), so a site with
|
|
4
|
+
* no choice keeps every document in the owner's in-process provider.
|
|
5
|
+
*
|
|
6
|
+
* On the existing settings ledger, workspace scope (one workspace per site in v1). Writes go
|
|
7
|
+
* through the host chokepoint (`features/settings/site-title-write.ts`), which authorizes and
|
|
8
|
+
* records a revision. The id grammar is checked here on both sides: the typed write refuses a bad
|
|
9
|
+
* id, and a read of a value stored any other way refuses it too rather than guessing a provider.
|
|
10
|
+
*/
|
|
11
|
+
import type { JsonValue } from "@jini-ai/core/primitives";
|
|
12
|
+
import { type EnsureSettingDefinitionsDeps, type EnsureSettingDefinitionsPort, type GetEffectivePort, type SetValueRequired, type SettingsRepoPort } from "@jini-ai/core/settings";
|
|
13
|
+
export declare const SEARCH_SETTINGS_NAMESPACE = "core.search";
|
|
14
|
+
export declare const SEARCH_PROVIDER_KEY = "provider";
|
|
15
|
+
/** True for a value that can name a registered provider. @complexity O(1), bounded length. */
|
|
16
|
+
export declare function isSearchProviderId(required: {
|
|
17
|
+
value: unknown;
|
|
18
|
+
}, _optional?: Record<string, never>): required is {
|
|
19
|
+
value: string;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Register the definition without replacing an owner's stored value.
|
|
23
|
+
* @complexity O(1), one definition.
|
|
24
|
+
*/
|
|
25
|
+
export declare function ensureSearchProviderSetting(required: {
|
|
26
|
+
deps: EnsureSettingDefinitionsDeps & EnsureSettingDefinitionsPort;
|
|
27
|
+
systemPrincipalId: string;
|
|
28
|
+
}, _optional?: Record<string, never>): Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* A reader of a site's provider id, read fresh on each call. An unregistered definition reads as
|
|
31
|
+
* the default.
|
|
32
|
+
* @throws ValueValidationFailedError (from the returned reader) for a stored value outside the grammar.
|
|
33
|
+
* @complexity O(1) to build; each read is one effective-setting read.
|
|
34
|
+
*/
|
|
35
|
+
export declare function readSearchProviderSetting(required: {
|
|
36
|
+
settingsRepo: SettingsRepoPort;
|
|
37
|
+
} & GetEffectivePort, _optional?: Record<string, never>): (input: {
|
|
38
|
+
workspaceId: string;
|
|
39
|
+
}) => Promise<string>;
|
|
40
|
+
/** The host settings write (`features/settings` `set`), injected by composition so search never imports settings. */
|
|
41
|
+
export type SearchSettingWriter = (required: SetValueRequired) => Promise<{
|
|
42
|
+
value: JsonValue;
|
|
43
|
+
revisionSeq: number;
|
|
44
|
+
}>;
|
|
45
|
+
/**
|
|
46
|
+
* A writer of a site's provider id through the host settings chokepoint. It checks the grammar
|
|
47
|
+
* only: whether a provider with that id is installed is the caller's question (the registry).
|
|
48
|
+
* @throws ValueValidationFailedError for an id outside the grammar, before anything is written;
|
|
49
|
+
* authorization and ledger errors from the settings write propagate.
|
|
50
|
+
* @complexity O(1) to build; each write is one settings write.
|
|
51
|
+
*/
|
|
52
|
+
export declare function writeSearchProviderSetting(required: {
|
|
53
|
+
deps: SetValueRequired["deps"];
|
|
54
|
+
writeSetting: SearchSettingWriter;
|
|
55
|
+
}, _optional?: Record<string, never>): (input: {
|
|
56
|
+
workspaceId: string;
|
|
57
|
+
callerPrincipalId: string;
|
|
58
|
+
providerId: string;
|
|
59
|
+
}) => Promise<{
|
|
60
|
+
value: JsonValue;
|
|
61
|
+
revisionSeq: number;
|
|
62
|
+
}>;
|
|
63
|
+
//# sourceMappingURL=settings.d.ts.map
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { SCOPE_BIT, ValueValidationFailedError, } from "@jini-ai/core/settings";
|
|
2
|
+
import { BUILTIN_SEARCH_PROVIDER_ID } from "../index.js";
|
|
3
|
+
export const SEARCH_SETTINGS_NAMESPACE = "core.search";
|
|
4
|
+
export const SEARCH_PROVIDER_KEY = "provider";
|
|
5
|
+
/** The provider registry's id grammar. */
|
|
6
|
+
const PROVIDER_ID = /^[a-z][a-z0-9_]{0,63}$/;
|
|
7
|
+
/** True for a value that can name a registered provider. @complexity O(1), bounded length. */
|
|
8
|
+
export function isSearchProviderId(required, _optional = {}) {
|
|
9
|
+
const { value } = required;
|
|
10
|
+
return typeof value === "string" && PROVIDER_ID.test(value);
|
|
11
|
+
}
|
|
12
|
+
const rejection = ({ value }, _optional = {}) => new ValueValidationFailedError(`value for '${SEARCH_SETTINGS_NAMESPACE}.${SEARCH_PROVIDER_KEY}' must match ${PROVIDER_ID.source}; got ${JSON.stringify(value).slice(0, 80)}`);
|
|
13
|
+
/**
|
|
14
|
+
* Register the definition without replacing an owner's stored value.
|
|
15
|
+
* @complexity O(1), one definition.
|
|
16
|
+
*/
|
|
17
|
+
export function ensureSearchProviderSetting(required, _optional = {}) {
|
|
18
|
+
return required.deps.ensureSettingDefinitions(required.deps, {
|
|
19
|
+
namespace: SEARCH_SETTINGS_NAMESPACE, systemPrincipalId: required.systemPrincipalId,
|
|
20
|
+
definitions: [{ key: SEARCH_PROVIDER_KEY, schema: { type: "string" }, defaultValue: BUILTIN_SEARCH_PROVIDER_ID, scopes: SCOPE_BIT.workspace }],
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* A reader of a site's provider id, read fresh on each call. An unregistered definition reads as
|
|
25
|
+
* the default.
|
|
26
|
+
* @throws ValueValidationFailedError (from the returned reader) for a stored value outside the grammar.
|
|
27
|
+
* @complexity O(1) to build; each read is one effective-setting read.
|
|
28
|
+
*/
|
|
29
|
+
export function readSearchProviderSetting(required, _optional = {}) {
|
|
30
|
+
return async ({ workspaceId }) => {
|
|
31
|
+
const found = await required.getEffective({ deps: { repo: required.settingsRepo }, namespace: SEARCH_SETTINGS_NAMESPACE, key: SEARCH_PROVIDER_KEY, scopeContext: { workspaceId } });
|
|
32
|
+
const stored = { value: found?.value ?? BUILTIN_SEARCH_PROVIDER_ID };
|
|
33
|
+
if (!isSearchProviderId(stored))
|
|
34
|
+
throw rejection(stored);
|
|
35
|
+
return stored.value;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* A writer of a site's provider id through the host settings chokepoint. It checks the grammar
|
|
40
|
+
* only: whether a provider with that id is installed is the caller's question (the registry).
|
|
41
|
+
* @throws ValueValidationFailedError for an id outside the grammar, before anything is written;
|
|
42
|
+
* authorization and ledger errors from the settings write propagate.
|
|
43
|
+
* @complexity O(1) to build; each write is one settings write.
|
|
44
|
+
*/
|
|
45
|
+
export function writeSearchProviderSetting(required, _optional = {}) {
|
|
46
|
+
return async ({ workspaceId, callerPrincipalId, providerId }) => {
|
|
47
|
+
if (!isSearchProviderId({ value: providerId }))
|
|
48
|
+
throw rejection({ value: providerId });
|
|
49
|
+
return required.writeSetting({ deps: required.deps, input: {
|
|
50
|
+
namespace: SEARCH_SETTINGS_NAMESPACE, key: SEARCH_PROVIDER_KEY, scope: "workspace", workspaceId, callerPrincipalId, value: providerId,
|
|
51
|
+
} });
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=settings.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jini-ai/search",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.4",
|
|
4
4
|
"description": "Generic site-search contract: provider interface, registry, single-writer indexer, query service with access revalidation, agent tools and a provider conformance test-kit.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -17,7 +17,21 @@
|
|
|
17
17
|
"./tools": "universal",
|
|
18
18
|
"./http-query": "universal",
|
|
19
19
|
"./testkit": "universal",
|
|
20
|
-
"./contribution": "node"
|
|
20
|
+
"./contribution": "node",
|
|
21
|
+
"./site/settings": "universal",
|
|
22
|
+
"./site/cms-document-source": "universal",
|
|
23
|
+
"./site/access": "universal",
|
|
24
|
+
"./site/index-state-store": "node",
|
|
25
|
+
"./public-http/routes/site/search": "universal",
|
|
26
|
+
"./site/media-search-source": "universal"
|
|
27
|
+
},
|
|
28
|
+
"optionalPeers": {
|
|
29
|
+
"kysely": "opt-in: sql search-index store; import @jini-ai/search/site/index-state-store — The SQL search-index store could not load kysely. Install kysely to enable this feature, or check its installed version."
|
|
30
|
+
},
|
|
31
|
+
"isolation": {
|
|
32
|
+
"entries": {
|
|
33
|
+
"./public-http/routes/site/search": "http-query"
|
|
34
|
+
}
|
|
21
35
|
}
|
|
22
36
|
},
|
|
23
37
|
"type": "module",
|
|
@@ -47,6 +61,36 @@
|
|
|
47
61
|
"types": "./dist/testkit/index.d.ts",
|
|
48
62
|
"import": "./dist/testkit/index.js",
|
|
49
63
|
"default": "./dist/testkit/index.js"
|
|
64
|
+
},
|
|
65
|
+
"./site/settings": {
|
|
66
|
+
"types": "./dist/site/settings.d.ts",
|
|
67
|
+
"import": "./dist/site/settings.js",
|
|
68
|
+
"default": "./dist/site/settings.js"
|
|
69
|
+
},
|
|
70
|
+
"./site/cms-document-source": {
|
|
71
|
+
"types": "./dist/site/cms-document-source.d.ts",
|
|
72
|
+
"import": "./dist/site/cms-document-source.js",
|
|
73
|
+
"default": "./dist/site/cms-document-source.js"
|
|
74
|
+
},
|
|
75
|
+
"./site/access": {
|
|
76
|
+
"types": "./dist/site/access.d.ts",
|
|
77
|
+
"import": "./dist/site/access.js",
|
|
78
|
+
"default": "./dist/site/access.js"
|
|
79
|
+
},
|
|
80
|
+
"./site/index-state-store": {
|
|
81
|
+
"types": "./dist/site/index-state-store.d.ts",
|
|
82
|
+
"import": "./dist/site/index-state-store.js",
|
|
83
|
+
"default": "./dist/site/index-state-store.js"
|
|
84
|
+
},
|
|
85
|
+
"./public-http/routes/site/search": {
|
|
86
|
+
"types": "./dist/public-http/routes/site/search.d.ts",
|
|
87
|
+
"import": "./dist/public-http/routes/site/search.js",
|
|
88
|
+
"default": "./dist/public-http/routes/site/search.js"
|
|
89
|
+
},
|
|
90
|
+
"./site/media-search-source": {
|
|
91
|
+
"types": "./dist/site/media-search-source.d.ts",
|
|
92
|
+
"import": "./dist/site/media-search-source.js",
|
|
93
|
+
"default": "./dist/site/media-search-source.js"
|
|
50
94
|
}
|
|
51
95
|
},
|
|
52
96
|
"files": [
|
|
@@ -61,12 +105,25 @@
|
|
|
61
105
|
"registry": "https://registry.npmjs.org"
|
|
62
106
|
},
|
|
63
107
|
"dependencies": {
|
|
64
|
-
"@jini-ai/core": "^0.7.
|
|
108
|
+
"@jini-ai/core": "^0.7.4"
|
|
109
|
+
},
|
|
110
|
+
"peerDependencies": {
|
|
111
|
+
"kysely": "^0.29.6"
|
|
65
112
|
},
|
|
66
113
|
"devDependencies": {
|
|
67
114
|
"@vitest/coverage-v8": "^3.2.6",
|
|
68
115
|
"vitest": "^3.2.6",
|
|
69
|
-
"
|
|
116
|
+
"kysely": "^0.29.6",
|
|
117
|
+
"@electric-sql/pglite": "0.5.8",
|
|
118
|
+
"@types/better-sqlite3": "^7.6.13",
|
|
119
|
+
"better-sqlite3": "^13.0.0",
|
|
120
|
+
"@jini-ai/agent-plugins": "0.7.4",
|
|
121
|
+
"@jini-ai/db": "0.7.4"
|
|
122
|
+
},
|
|
123
|
+
"peerDependenciesMeta": {
|
|
124
|
+
"kysely": {
|
|
125
|
+
"optional": true
|
|
126
|
+
}
|
|
70
127
|
},
|
|
71
128
|
"scripts": {
|
|
72
129
|
"build": "tsc -p tsconfig.json",
|