@open-mercato/search 0.10.1-develop.7576.1.21d5b50435 → 0.10.1-develop.7578.1.677eeb8343
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/.turbo/turbo-build.log +1 -1
- package/dist/lib/index-doc-filter.js +76 -0
- package/dist/lib/index-doc-filter.js.map +7 -0
- package/dist/modules/search/__integration__/TC-SEARCH-014.spec.js +198 -0
- package/dist/modules/search/__integration__/TC-SEARCH-014.spec.js.map +7 -0
- package/dist/service.js +3 -2
- package/dist/service.js.map +2 -2
- package/dist/strategies/fulltext.strategy.js +1 -0
- package/dist/strategies/fulltext.strategy.js.map +2 -2
- package/dist/strategies/index.js +10 -0
- package/dist/strategies/index.js.map +2 -2
- package/dist/strategies/token.strategy.js +12 -0
- package/dist/strategies/token.strategy.js.map +2 -2
- package/dist/strategies/vector.strategy.js +7 -1
- package/dist/strategies/vector.strategy.js.map +2 -2
- package/dist/vector/drivers/pgvector/index.js +13 -0
- package/dist/vector/drivers/pgvector/index.js.map +2 -2
- package/dist/vector/types.js.map +2 -2
- package/package.json +4 -4
- package/src/__tests__/index-doc-filter.test.ts +259 -0
- package/src/lib/index-doc-filter.ts +109 -0
- package/src/modules/search/__integration__/TC-SEARCH-014.spec.ts +398 -0
- package/src/modules/search/frontend/lib/__tests__/entityTypeLabel.test.ts +5 -2
- package/src/service.ts +4 -2
- package/src/strategies/fulltext.strategy.ts +1 -0
- package/src/strategies/index.ts +7 -0
- package/src/strategies/token.strategy.ts +12 -0
- package/src/strategies/vector.strategy.ts +7 -0
- package/src/types.ts +2 -0
- package/src/vector/drivers/pgvector/index.ts +15 -0
- package/src/vector/types.ts +11 -0
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
[build:search] found
|
|
1
|
+
[build:search] found 101 entry points
|
|
2
2
|
[build:search] built successfully
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DummyDriver,
|
|
3
|
+
Kysely,
|
|
4
|
+
PostgresAdapter,
|
|
5
|
+
PostgresIntrospector,
|
|
6
|
+
PostgresQueryCompiler,
|
|
7
|
+
sql
|
|
8
|
+
} from "kysely";
|
|
9
|
+
import {
|
|
10
|
+
buildJsonbNoOverlapPredicate,
|
|
11
|
+
buildJsonbOverlapPredicate,
|
|
12
|
+
jsonbDocKeyExpression,
|
|
13
|
+
normalizeOverlapValues
|
|
14
|
+
} from "@open-mercato/shared/lib/query/overlap";
|
|
15
|
+
const INDEX_DOC_FILTER_ALIAS = "om_index_doc";
|
|
16
|
+
const DOC_REF = `${INDEX_DOC_FILTER_ALIAS}.doc`;
|
|
17
|
+
function conditionPredicate(condition) {
|
|
18
|
+
switch (condition.op) {
|
|
19
|
+
case "exists": {
|
|
20
|
+
const keyExpr = jsonbDocKeyExpression(DOC_REF, condition.key);
|
|
21
|
+
return sql`(jsonb_typeof(${keyExpr}) is not null and jsonb_typeof(${keyExpr}) <> 'null')`;
|
|
22
|
+
}
|
|
23
|
+
case "eq":
|
|
24
|
+
return sql`(${jsonbDocKeyExpression(DOC_REF, condition.key)} #>> '{}') = ${String(condition.value)}`;
|
|
25
|
+
case "overlap":
|
|
26
|
+
return buildJsonbOverlapPredicate(DOC_REF, condition.key, condition.values);
|
|
27
|
+
case "noverlap":
|
|
28
|
+
return buildJsonbNoOverlapPredicate(DOC_REF, condition.key, condition.values);
|
|
29
|
+
case "recordIdNotIn": {
|
|
30
|
+
const values = normalizeOverlapValues(condition.values);
|
|
31
|
+
if (!values.length) return sql`true`;
|
|
32
|
+
return sql`not (${sql.ref(`${INDEX_DOC_FILTER_ALIAS}.entity_id`)} = any(${values}::text[]))`;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function branchPredicate(branch) {
|
|
37
|
+
if (!branch.length) return sql`true`;
|
|
38
|
+
return sql`(${sql.join(branch.map(conditionPredicate), sql` and `)})`;
|
|
39
|
+
}
|
|
40
|
+
function buildIndexDocFilterPredicate(filter) {
|
|
41
|
+
if (!filter.anyOf.length) return sql`false`;
|
|
42
|
+
return sql`(${sql.join(filter.anyOf.map(branchPredicate), sql` or `)})`;
|
|
43
|
+
}
|
|
44
|
+
function buildIndexDocFilterExists(filter, target) {
|
|
45
|
+
const alias = (column) => sql.ref(`${INDEX_DOC_FILTER_ALIAS}.${column}`);
|
|
46
|
+
return sql`exists (select 1 from entity_indexes as ${sql.id(INDEX_DOC_FILTER_ALIAS)} where ${alias("entity_type")} = ${sql.ref(target.entityTypeRef)} and ${alias("entity_id")} = (${sql.ref(target.recordIdRef)})::text and ${alias("tenant_id")} = ${sql.ref(target.tenantIdRef)} and ${alias("deleted_at")} is null and ${buildIndexDocFilterPredicate(filter)})`;
|
|
47
|
+
}
|
|
48
|
+
let compileOnlyDb = null;
|
|
49
|
+
function compiler() {
|
|
50
|
+
if (!compileOnlyDb) {
|
|
51
|
+
compileOnlyDb = new Kysely({
|
|
52
|
+
dialect: {
|
|
53
|
+
createAdapter: () => new PostgresAdapter(),
|
|
54
|
+
createDriver: () => new DummyDriver(),
|
|
55
|
+
createIntrospector: (db) => new PostgresIntrospector(db),
|
|
56
|
+
createQueryCompiler: () => new PostgresQueryCompiler()
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
return compileOnlyDb;
|
|
61
|
+
}
|
|
62
|
+
function compileIndexDocFilterExists(filter, target, firstParameterIndex) {
|
|
63
|
+
const compiled = buildIndexDocFilterExists(filter, target).compile(compiler());
|
|
64
|
+
const offset = firstParameterIndex - 1;
|
|
65
|
+
return {
|
|
66
|
+
sql: compiled.sql.replace(/\$(\d+)/g, (_match, index) => `$${Number(index) + offset}`),
|
|
67
|
+
parameters: [...compiled.parameters]
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
export {
|
|
71
|
+
INDEX_DOC_FILTER_ALIAS,
|
|
72
|
+
buildIndexDocFilterExists,
|
|
73
|
+
buildIndexDocFilterPredicate,
|
|
74
|
+
compileIndexDocFilterExists
|
|
75
|
+
};
|
|
76
|
+
//# sourceMappingURL=index-doc-filter.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/lib/index-doc-filter.ts"],
|
|
4
|
+
"sourcesContent": ["import {\n DummyDriver,\n Kysely,\n PostgresAdapter,\n PostgresIntrospector,\n PostgresQueryCompiler,\n sql,\n type RawBuilder,\n} from 'kysely'\nimport type { SearchIndexDocCondition, SearchIndexDocFilter } from '@open-mercato/shared/modules/search'\nimport {\n buildJsonbNoOverlapPredicate,\n buildJsonbOverlapPredicate,\n jsonbDocKeyExpression,\n normalizeOverlapValues,\n} from '@open-mercato/shared/lib/query/overlap'\n\n/**\n * `SearchOptions.indexDocFilter` compiled to one correlated `exists` over `entity_indexes`, so a\n * strategy can AND it into the query that ranks \u2014 the predicate decides which rows are ranked,\n * never which ranked rows are kept, and a restrictive filter cannot starve the result set (except\n * under a pgvector `ivfflat` index scan, which applies it to the probed lists' candidates only).\n */\n\nexport const INDEX_DOC_FILTER_ALIAS = 'om_index_doc'\n\nexport type IndexDocFilterTarget = {\n /** Column of the ranked table holding the entity type (`module:entity`). */\n entityTypeRef: string\n /** Column of the ranked table holding the record id. */\n recordIdRef: string\n /** Column of the ranked table holding the tenant id. */\n tenantIdRef: string\n}\n\nconst DOC_REF = `${INDEX_DOC_FILTER_ALIAS}.doc`\n\nfunction conditionPredicate(condition: SearchIndexDocCondition): RawBuilder<boolean> {\n switch (condition.op) {\n case 'exists': {\n const keyExpr = jsonbDocKeyExpression(DOC_REF, condition.key)\n return sql<boolean>`(jsonb_typeof(${keyExpr}) is not null and jsonb_typeof(${keyExpr}) <> 'null')`\n }\n case 'eq':\n return sql<boolean>`(${jsonbDocKeyExpression(DOC_REF, condition.key)} #>> '{}') = ${String(condition.value)}`\n case 'overlap':\n return buildJsonbOverlapPredicate(DOC_REF, condition.key, condition.values)\n case 'noverlap':\n return buildJsonbNoOverlapPredicate(DOC_REF, condition.key, condition.values)\n case 'recordIdNotIn': {\n const values = normalizeOverlapValues(condition.values)\n if (!values.length) return sql<boolean>`true`\n return sql<boolean>`not (${sql.ref(`${INDEX_DOC_FILTER_ALIAS}.entity_id`)} = any(${values}::text[]))`\n }\n }\n}\n\nfunction branchPredicate(branch: SearchIndexDocCondition[]): RawBuilder<boolean> {\n if (!branch.length) return sql<boolean>`true`\n return sql<boolean>`(${sql.join(branch.map(conditionPredicate), sql` and `)})`\n}\n\n/** The filter's DNF over the `entity_indexes` row aliased `INDEX_DOC_FILTER_ALIAS`. */\nexport function buildIndexDocFilterPredicate(filter: SearchIndexDocFilter): RawBuilder<boolean> {\n if (!filter.anyOf.length) return sql<boolean>`false`\n return sql<boolean>`(${sql.join(filter.anyOf.map(branchPredicate), sql` or `)})`\n}\n\n/**\n * `exists (select 1 from entity_indexes \u2026 )` correlated to the ranked row by entity type, record id\n * and tenant, restricted to live index rows and to the filter's DNF.\n */\nexport function buildIndexDocFilterExists(filter: SearchIndexDocFilter, target: IndexDocFilterTarget): RawBuilder<boolean> {\n const alias = (column: string) => sql.ref(`${INDEX_DOC_FILTER_ALIAS}.${column}`)\n return sql<boolean>`exists (select 1 from entity_indexes as ${sql.id(INDEX_DOC_FILTER_ALIAS)} where ${alias('entity_type')} = ${sql.ref(target.entityTypeRef)} and ${alias('entity_id')} = (${sql.ref(target.recordIdRef)})::text and ${alias('tenant_id')} = ${sql.ref(target.tenantIdRef)} and ${alias('deleted_at')} is null and ${buildIndexDocFilterPredicate(filter)})`\n}\n\nlet compileOnlyDb: Kysely<Record<string, never>> | null = null\n\nfunction compiler(): Kysely<Record<string, never>> {\n if (!compileOnlyDb) {\n compileOnlyDb = new Kysely<Record<string, never>>({\n dialect: {\n createAdapter: () => new PostgresAdapter(),\n createDriver: () => new DummyDriver(),\n createIntrospector: (db) => new PostgresIntrospector(db),\n createQueryCompiler: () => new PostgresQueryCompiler(),\n },\n })\n }\n return compileOnlyDb\n}\n\n/**\n * The `exists` clause as Postgres text for drivers that issue raw SQL: placeholders start at\n * `$<firstParameterIndex>` so the caller appends `parameters` after its own.\n */\nexport function compileIndexDocFilterExists(\n filter: SearchIndexDocFilter,\n target: IndexDocFilterTarget,\n firstParameterIndex: number,\n): { sql: string; parameters: unknown[] } {\n const compiled = buildIndexDocFilterExists(filter, target).compile(compiler())\n const offset = firstParameterIndex - 1\n return {\n sql: compiled.sql.replace(/\\$(\\d+)/g, (_match, index: string) => `$${Number(index) + offset}`),\n parameters: [...compiled.parameters],\n }\n}\n"],
|
|
5
|
+
"mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AASA,MAAM,yBAAyB;AAWtC,MAAM,UAAU,GAAG,sBAAsB;AAEzC,SAAS,mBAAmB,WAAyD;AACnF,UAAQ,UAAU,IAAI;AAAA,IACpB,KAAK,UAAU;AACb,YAAM,UAAU,sBAAsB,SAAS,UAAU,GAAG;AAC5D,aAAO,oBAA6B,OAAO,kCAAkC,OAAO;AAAA,IACtF;AAAA,IACA,KAAK;AACH,aAAO,OAAgB,sBAAsB,SAAS,UAAU,GAAG,CAAC,gBAAgB,OAAO,UAAU,KAAK,CAAC;AAAA,IAC7G,KAAK;AACH,aAAO,2BAA2B,SAAS,UAAU,KAAK,UAAU,MAAM;AAAA,IAC5E,KAAK;AACH,aAAO,6BAA6B,SAAS,UAAU,KAAK,UAAU,MAAM;AAAA,IAC9E,KAAK,iBAAiB;AACpB,YAAM,SAAS,uBAAuB,UAAU,MAAM;AACtD,UAAI,CAAC,OAAO,OAAQ,QAAO;AAC3B,aAAO,WAAoB,IAAI,IAAI,GAAG,sBAAsB,YAAY,CAAC,UAAU,MAAM;AAAA,IAC3F;AAAA,EACF;AACF;AAEA,SAAS,gBAAgB,QAAwD;AAC/E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EAAE;AAAA,IAC7F,YAAY,CAAC,GAAG,SAAS,UAAU;AAAA,EACrC;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { expect, test } from "@playwright/test";
|
|
2
|
+
import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
|
|
3
|
+
import { getTokenContext, readJsonSafe } from "@open-mercato/core/helpers/integration/generalFixtures";
|
|
4
|
+
import { login } from "@open-mercato/core/modules/core/__integration__/helpers/auth";
|
|
5
|
+
import {
|
|
6
|
+
createCompanyFixture,
|
|
7
|
+
createPersonFixture,
|
|
8
|
+
deleteEntityIfExists
|
|
9
|
+
} from "@open-mercato/core/helpers/integration/crmFixtures";
|
|
10
|
+
const integrationMeta = { dependsOnModules: ["search", "customers"] };
|
|
11
|
+
const DEFAULT_STRATEGIES = ["fulltext", "vector", "tokens"];
|
|
12
|
+
const PERSON_PROFILE = "customers:customer_person_profile";
|
|
13
|
+
const COMPANY_PROFILE = "customers:customer_company_profile";
|
|
14
|
+
const LIST_SEARCH_PLACEHOLDER = /Search by name/i;
|
|
15
|
+
function presenterTitle(result) {
|
|
16
|
+
const title = result.presenter?.title;
|
|
17
|
+
return typeof title === "string" && title.trim().length > 0 ? title.trim() : null;
|
|
18
|
+
}
|
|
19
|
+
async function readEnabledStrategies(request, token) {
|
|
20
|
+
const response = await apiRequest(request, "GET", "/api/search/settings/global-search", { token });
|
|
21
|
+
expect(response.ok(), "GET global-search settings should succeed").toBeTruthy();
|
|
22
|
+
const body = await readJsonSafe(response) ?? {};
|
|
23
|
+
return Array.isArray(body.enabledStrategies) && body.enabledStrategies.length > 0 ? body.enabledStrategies : DEFAULT_STRATEGIES;
|
|
24
|
+
}
|
|
25
|
+
async function writeEnabledStrategies(request, token, strategies) {
|
|
26
|
+
const response = await apiRequest(request, "POST", "/api/search/settings/global-search", {
|
|
27
|
+
token,
|
|
28
|
+
data: { enabledStrategies: strategies }
|
|
29
|
+
});
|
|
30
|
+
expect(response.status(), "POST global-search settings should return 200").toBe(200);
|
|
31
|
+
}
|
|
32
|
+
async function waitForIndexedProfile(request, token, title, expectedEntityId) {
|
|
33
|
+
await expect.poll(
|
|
34
|
+
async () => {
|
|
35
|
+
const params = new URLSearchParams({ q: title, limit: "20" });
|
|
36
|
+
const response = await apiRequest(
|
|
37
|
+
request,
|
|
38
|
+
"GET",
|
|
39
|
+
`/api/search/search/global?${params.toString()}`,
|
|
40
|
+
{ token }
|
|
41
|
+
);
|
|
42
|
+
if (!response.ok()) return `status:${response.status()}`;
|
|
43
|
+
const body = await readJsonSafe(response) ?? {};
|
|
44
|
+
const results = Array.isArray(body.results) ? body.results : [];
|
|
45
|
+
const matches = results.filter((result) => presenterTitle(result) === title);
|
|
46
|
+
if (!matches.some((match) => match.entityId === expectedEntityId)) {
|
|
47
|
+
return `awaiting ${expectedEntityId} (titles matched: ${matches.length})`;
|
|
48
|
+
}
|
|
49
|
+
return "ready";
|
|
50
|
+
},
|
|
51
|
+
{ timeout: 3e4 }
|
|
52
|
+
).toBe("ready");
|
|
53
|
+
}
|
|
54
|
+
async function resolveTokens(request) {
|
|
55
|
+
const adminToken = await getAuthToken(request, "admin");
|
|
56
|
+
const superToken = await getAuthToken(request, "superadmin");
|
|
57
|
+
const adminTenant = getTokenContext(adminToken).tenantId;
|
|
58
|
+
const superTenant = getTokenContext(superToken).tenantId;
|
|
59
|
+
expect(adminTenant.length, "the admin token carries a tenant id").toBeGreaterThan(0);
|
|
60
|
+
expect(
|
|
61
|
+
superTenant,
|
|
62
|
+
"admin and superadmin must share a tenant, or the superadmin palette cannot see the seeded customers"
|
|
63
|
+
).toBe(adminTenant);
|
|
64
|
+
return { adminToken, superToken };
|
|
65
|
+
}
|
|
66
|
+
async function openPaletteWithQuery(page, query) {
|
|
67
|
+
await page.locator("header").getByRole("button", { name: "Open global search" }).click();
|
|
68
|
+
const input = page.locator('[data-search-expanded="true"] input[type="text"]');
|
|
69
|
+
await expect(input).toBeVisible();
|
|
70
|
+
await input.fill(query);
|
|
71
|
+
}
|
|
72
|
+
test.describe("TC-SEARCH-014: a customer appears once in the global search palette", () => {
|
|
73
|
+
test("the palette renders exactly one navigable row per customer", async ({ page, request }) => {
|
|
74
|
+
test.setTimeout(18e4);
|
|
75
|
+
const stamp = Date.now();
|
|
76
|
+
const personName = `QASRCH014P${stamp}`;
|
|
77
|
+
const companyName = `QASRCH014C${stamp}`;
|
|
78
|
+
let adminToken = null;
|
|
79
|
+
let superToken = null;
|
|
80
|
+
let originalStrategies = null;
|
|
81
|
+
let personId = null;
|
|
82
|
+
let companyId = null;
|
|
83
|
+
try {
|
|
84
|
+
const tokens = await resolveTokens(request);
|
|
85
|
+
adminToken = tokens.adminToken;
|
|
86
|
+
superToken = tokens.superToken;
|
|
87
|
+
originalStrategies = await readEnabledStrategies(request, superToken);
|
|
88
|
+
await writeEnabledStrategies(request, superToken, ["tokens"]);
|
|
89
|
+
personId = await createPersonFixture(request, adminToken, {
|
|
90
|
+
firstName: "QA",
|
|
91
|
+
lastName: `Search 014 ${stamp}`,
|
|
92
|
+
displayName: personName
|
|
93
|
+
});
|
|
94
|
+
companyId = await createCompanyFixture(request, adminToken, companyName);
|
|
95
|
+
const fixtures = [
|
|
96
|
+
{
|
|
97
|
+
label: "person",
|
|
98
|
+
title: personName,
|
|
99
|
+
entityId: PERSON_PROFILE,
|
|
100
|
+
detailPrefix: "/backend/customers/people-v2",
|
|
101
|
+
listPath: "/backend/customers/people"
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
label: "company",
|
|
105
|
+
title: companyName,
|
|
106
|
+
entityId: COMPANY_PROFILE,
|
|
107
|
+
detailPrefix: "/backend/customers/companies-v2",
|
|
108
|
+
listPath: "/backend/customers/companies"
|
|
109
|
+
}
|
|
110
|
+
];
|
|
111
|
+
for (const fixture of fixtures) {
|
|
112
|
+
await waitForIndexedProfile(request, superToken, fixture.title, fixture.entityId);
|
|
113
|
+
}
|
|
114
|
+
await login(page, "superadmin");
|
|
115
|
+
for (const fixture of fixtures) {
|
|
116
|
+
await page.goto("/backend");
|
|
117
|
+
await page.waitForLoadState("domcontentloaded");
|
|
118
|
+
await openPaletteWithQuery(page, fixture.title);
|
|
119
|
+
const panel = page.locator("#topbar-search-results");
|
|
120
|
+
await expect(panel).toBeVisible();
|
|
121
|
+
const options = panel.getByRole("option");
|
|
122
|
+
await expect(options).toHaveCount(1, { timeout: 2e4 });
|
|
123
|
+
const option = options.first();
|
|
124
|
+
await expect(
|
|
125
|
+
option,
|
|
126
|
+
`the single ${fixture.label} row must be the seeded customer, not an unrelated result`
|
|
127
|
+
).toContainText(fixture.title);
|
|
128
|
+
const optionClass = await option.getAttribute("class") ?? "";
|
|
129
|
+
expect(
|
|
130
|
+
optionClass,
|
|
131
|
+
`the ${fixture.label} row must have a primary link \u2014 'opacity-60' marks the greyed-out, unclickable duplicate`
|
|
132
|
+
).not.toContain("opacity-60");
|
|
133
|
+
await option.click();
|
|
134
|
+
await page.waitForURL(new RegExp(`${fixture.detailPrefix}/[^/?#]+$`), { timeout: 2e4 });
|
|
135
|
+
}
|
|
136
|
+
} finally {
|
|
137
|
+
await deleteEntityIfExists(request, adminToken, "/api/customers/people", personId);
|
|
138
|
+
await deleteEntityIfExists(request, adminToken, "/api/customers/companies", companyId);
|
|
139
|
+
if (superToken && originalStrategies) {
|
|
140
|
+
await writeEnabledStrategies(request, superToken, originalStrategies).catch(() => void 0);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
test("the People and Companies list search still finds the customer", async ({ page, request }) => {
|
|
145
|
+
test.setTimeout(18e4);
|
|
146
|
+
const stamp = Date.now();
|
|
147
|
+
const personName = `QASRCH014LP${stamp}`;
|
|
148
|
+
const companyName = `QASRCH014LC${stamp}`;
|
|
149
|
+
let adminToken = null;
|
|
150
|
+
let personId = null;
|
|
151
|
+
let companyId = null;
|
|
152
|
+
try {
|
|
153
|
+
adminToken = (await resolveTokens(request)).adminToken;
|
|
154
|
+
personId = await createPersonFixture(request, adminToken, {
|
|
155
|
+
firstName: "QA",
|
|
156
|
+
lastName: `Search 014 List ${stamp}`,
|
|
157
|
+
displayName: personName
|
|
158
|
+
});
|
|
159
|
+
companyId = await createCompanyFixture(request, adminToken, companyName);
|
|
160
|
+
await login(page, "superadmin");
|
|
161
|
+
const listArms = [
|
|
162
|
+
{ label: "people", path: "/backend/customers/people", endpoint: "/api/customers/people", title: personName },
|
|
163
|
+
{
|
|
164
|
+
label: "companies",
|
|
165
|
+
path: "/backend/customers/companies",
|
|
166
|
+
endpoint: "/api/customers/companies",
|
|
167
|
+
title: companyName
|
|
168
|
+
}
|
|
169
|
+
];
|
|
170
|
+
for (const arm of listArms) {
|
|
171
|
+
await page.goto(arm.path);
|
|
172
|
+
await page.waitForLoadState("domcontentloaded");
|
|
173
|
+
const searchBox = page.getByPlaceholder(LIST_SEARCH_PLACEHOLDER);
|
|
174
|
+
await expect(searchBox).toBeVisible();
|
|
175
|
+
const filteredResponse = page.waitForResponse(
|
|
176
|
+
(response) => {
|
|
177
|
+
const url = new URL(response.url());
|
|
178
|
+
return url.pathname === arm.endpoint && url.searchParams.get("search") === arm.title && response.status() === 200;
|
|
179
|
+
},
|
|
180
|
+
{ timeout: 3e4 }
|
|
181
|
+
);
|
|
182
|
+
await searchBox.fill(arm.title);
|
|
183
|
+
await filteredResponse;
|
|
184
|
+
await expect(
|
|
185
|
+
page.getByText(arm.title, { exact: true }).first(),
|
|
186
|
+
`${arm.label} list search must still return the customer after #5073 stopped offering base customer rows as search results`
|
|
187
|
+
).toBeVisible({ timeout: 2e4 });
|
|
188
|
+
}
|
|
189
|
+
} finally {
|
|
190
|
+
await deleteEntityIfExists(request, adminToken, "/api/customers/people", personId);
|
|
191
|
+
await deleteEntityIfExists(request, adminToken, "/api/customers/companies", companyId);
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
});
|
|
195
|
+
export {
|
|
196
|
+
integrationMeta
|
|
197
|
+
};
|
|
198
|
+
//# sourceMappingURL=TC-SEARCH-014.spec.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/modules/search/__integration__/TC-SEARCH-014.spec.ts"],
|
|
4
|
+
"sourcesContent": ["import { expect, test, type APIRequestContext, type Page } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { getTokenContext, readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\nimport { login } from '@open-mercato/core/modules/core/__integration__/helpers/auth'\nimport {\n createCompanyFixture,\n createPersonFixture,\n deleteEntityIfExists,\n} from '@open-mercato/core/helpers/integration/crmFixtures'\n\nexport const integrationMeta = { dependsOnModules: ['search', 'customers'] }\n\ntype GlobalSearchSettings = { enabledStrategies?: string[] }\ntype SearchResultItem = {\n entityId?: string\n recordId?: string\n presenter?: { title?: string } | null\n url?: string | null\n}\ntype GlobalSearchResponse = { results?: SearchResultItem[] }\n\nconst DEFAULT_STRATEGIES = ['fulltext', 'vector', 'tokens']\nconst PERSON_PROFILE = 'customers:customer_person_profile'\nconst COMPANY_PROFILE = 'customers:customer_company_profile'\n// Matched as a pattern, not the full string. The rendered placeholder is\n// `customers.{people,companies}.list.searchPlaceholder` \u2014 \"Search by name, email, phone\u2026\" \u2014 whose\n// trailing ellipsis is a single U+2026 character and whose tail is ordinary copy. TC-CRM-001, -014,\n// -015, -029, -030, -033 and -065 all locate this same input with `/Search by name/i`; matching\n// the stable prefix keeps this spec failing on the palette contract it guards rather than on an\n// i18n copy edit.\nconst LIST_SEARCH_PLACEHOLDER = /Search by name/i\n\ntype Fixture = {\n label: 'person' | 'company'\n title: string\n entityId: string\n detailPrefix: string\n listPath: string\n}\n\nfunction presenterTitle(result: SearchResultItem): string | null {\n const title = result.presenter?.title\n return typeof title === 'string' && title.trim().length > 0 ? title.trim() : null\n}\n\nasync function readEnabledStrategies(request: APIRequestContext, token: string): Promise<string[]> {\n const response = await apiRequest(request, 'GET', '/api/search/settings/global-search', { token })\n expect(response.ok(), 'GET global-search settings should succeed').toBeTruthy()\n const body = (await readJsonSafe<GlobalSearchSettings>(response)) ?? {}\n return Array.isArray(body.enabledStrategies) && body.enabledStrategies.length > 0\n ? body.enabledStrategies\n : DEFAULT_STRATEGIES\n}\n\nasync function writeEnabledStrategies(\n request: APIRequestContext,\n token: string,\n strategies: string[],\n): Promise<void> {\n const response = await apiRequest(request, 'POST', '/api/search/settings/global-search', {\n token,\n data: { enabledStrategies: strategies },\n })\n expect(response.status(), 'POST global-search settings should return 200').toBe(200)\n}\n\n/**\n * Waits until global search has indexed the customer's profile row for `title`.\n *\n * The wait exists for one reason only: to keep the browser assertions below from racing the\n * indexer. A palette that renders zero rows because indexing has not caught up is\n * indistinguishable, at the DOM level, from a palette that correctly renders one.\n *\n * It therefore polls for the PRESENCE of the expected profile and never for a row count.\n * Requiring exactly one match here would be the palette's own assertion moved to the API \u2014 and\n * moved in front of the browser, where it short-circuits the run: on a pre-#5073 build the\n * global-search API returns two rows for the title, so a count-based poll would spin for its\n * full timeout and fail here, before `login()` and before the palette was ever opened. The\n * duplicate has to flow through to the DOM `toHaveCount(1)`, which is precisely what this spec\n * adds over the API-level TC-SEARCH-006.\n */\nasync function waitForIndexedProfile(\n request: APIRequestContext,\n token: string,\n title: string,\n expectedEntityId: string,\n): Promise<void> {\n await expect\n .poll(\n async () => {\n const params = new URLSearchParams({ q: title, limit: '20' })\n const response = await apiRequest(\n request,\n 'GET',\n `/api/search/search/global?${params.toString()}`,\n { token },\n )\n if (!response.ok()) return `status:${response.status()}`\n const body = (await readJsonSafe<GlobalSearchResponse>(response)) ?? {}\n const results = Array.isArray(body.results) ? body.results : []\n const matches = results.filter((result) => presenterTitle(result) === title)\n if (!matches.some((match) => match.entityId === expectedEntityId)) {\n return `awaiting ${expectedEntityId} (titles matched: ${matches.length})`\n }\n return 'ready'\n },\n { timeout: 30_000 },\n )\n .toBe('ready')\n}\n\n/**\n * Fixtures are seeded with the `admin` token, never the `superadmin` one, even though every\n * search-side operation below runs as `superadmin`.\n *\n * `withScopedPayload` (`packages/shared/src/lib/api/scoped.ts`) rejects a create with\n * `400 organizationRequired` unless an organization resolves from\n * `payload.organizationId ?? ctx.selectedOrganizationId ?? ctx.auth?.orgId`. A superadmin is\n * tenant-wide with `orgId: null`, so seeding an org-scoped customer with its token is a\n * guaranteed 400 \u2014 the same split TC-CRM-084 uses, where `superadmin` does tenant-level work\n * and `admin` creates the org-scoped records.\n *\n * Both accounts are seeded into the same tenant, which is what makes the split safe: the\n * superadmin's tenant-wide search still sees the admin's records. That assumption is asserted\n * rather than trusted, so a seeding change fails here with a clear message instead of\n * surfacing later as an inexplicably empty palette.\n */\nasync function resolveTokens(\n request: APIRequestContext,\n): Promise<{ adminToken: string; superToken: string }> {\n const adminToken = await getAuthToken(request, 'admin')\n const superToken = await getAuthToken(request, 'superadmin')\n const adminTenant = getTokenContext(adminToken).tenantId\n const superTenant = getTokenContext(superToken).tenantId\n expect(adminTenant.length, 'the admin token carries a tenant id').toBeGreaterThan(0)\n expect(\n superTenant,\n 'admin and superadmin must share a tenant, or the superadmin palette cannot see the seeded customers',\n ).toBe(adminTenant)\n return { adminToken, superToken }\n}\n\nasync function openPaletteWithQuery(page: Page, query: string): Promise<void> {\n await page.locator('header').getByRole('button', { name: 'Open global search' }).click()\n const input = page.locator('[data-search-expanded=\"true\"] input[type=\"text\"]')\n await expect(input).toBeVisible()\n await input.fill(query)\n}\n\n/**\n * TC-SEARCH-014: a customer appears exactly ONCE in the \u2318K palette, as a navigable row.\n * Source: issue #5547, the browser-level follow-up to #5073 (fixes #5046).\n *\n * #5073 shipped TC-SEARCH-006, which asserts the same contract against the JSON of\n * `GET /api/search/search{,/global}`. That is the right level for the strategy/entity-type\n * contract, but it cannot see the thing the original report describes: two rows in the\n * palette, one greyed out and unclickable. `TopbarSearchInline.tsx` renders a result with no\n * primary link at `opacity-60` with muted text and makes `openResult` a no-op for it, and it\n * is that rendering \u2014 not the response shape \u2014 that made the duplicate look like a broken\n * search result rather than an extra API row.\n *\n * Two things make this spec load-bearing rather than a duplicate of TC-SEARCH-006:\n *\n * 1. It asserts the `role=\"option\"` COUNT. A `toBeVisible()` on the profile row passes even\n * when the duplicate sits next to it, which is precisely the failure mode being guarded.\n * The count also stays honest if a future strategy, enricher or injected result\n * re-introduces a second row by some path other than the token strategy.\n * 2. It signs in as `superadmin`, and that is essential. `resolveReadableEntityTypes`\n * (`packages/shared/src/lib/search/entityAccess.ts:90` \u2014 note that the `packages/search`\n * `lib/entity-access.ts` path, which #5547 cites, is a six-line re-export shim, so the\n * reasoning below is only readable at the shared implementation) returns the caller's\n * requested entity types unchanged for a superadmin and narrows every other principal to\n * entity types a module registered in its `search.ts`. No module registers\n * `customers:customer_entity`, so the duplicate was only ever visible to a superadmin \u2014\n * the same test written as `admin` passes on the broken build too.\n *\n * Strategies are pinned to `tokens` (and restored in `finally`) so the run needs neither\n * Meilisearch nor an embedding provider, and because the duplicate is a token-strategy\n * artifact in the first place. `workers: 1` in the shared Playwright config keeps that\n * tenant-scoped settings write from colliding with a concurrent spec.\n */\ntest.describe('TC-SEARCH-014: a customer appears once in the global search palette', () => {\n test('the palette renders exactly one navigable row per customer', async ({ page, request }) => {\n test.setTimeout(180_000)\n\n const stamp = Date.now()\n const personName = `QASRCH014P${stamp}`\n const companyName = `QASRCH014C${stamp}`\n let adminToken: string | null = null\n let superToken: string | null = null\n let originalStrategies: string[] | null = null\n let personId: string | null = null\n let companyId: string | null = null\n\n try {\n const tokens = await resolveTokens(request)\n adminToken = tokens.adminToken\n superToken = tokens.superToken\n\n originalStrategies = await readEnabledStrategies(request, superToken)\n await writeEnabledStrategies(request, superToken, ['tokens'])\n\n personId = await createPersonFixture(request, adminToken, {\n firstName: 'QA',\n lastName: `Search 014 ${stamp}`,\n displayName: personName,\n })\n companyId = await createCompanyFixture(request, adminToken, companyName)\n\n const fixtures: Fixture[] = [\n {\n label: 'person',\n title: personName,\n entityId: PERSON_PROFILE,\n detailPrefix: '/backend/customers/people-v2',\n listPath: '/backend/customers/people',\n },\n {\n label: 'company',\n title: companyName,\n entityId: COMPANY_PROFILE,\n detailPrefix: '/backend/customers/companies-v2',\n listPath: '/backend/customers/companies',\n },\n ]\n\n // Poll as `superadmin` \u2014 the same principal the palette queries as \u2014 so an entity-access\n // difference between the two accounts surfaces here rather than as an empty palette.\n for (const fixture of fixtures) {\n await waitForIndexedProfile(request, superToken, fixture.title, fixture.entityId)\n }\n\n await login(page, 'superadmin')\n\n for (const fixture of fixtures) {\n await page.goto('/backend')\n await page.waitForLoadState('domcontentloaded')\n await openPaletteWithQuery(page, fixture.title)\n\n const panel = page.locator('#topbar-search-results')\n await expect(panel).toBeVisible()\n\n // -- The duplicate guard, and the reason it counts EVERY option rather than only the\n // ones whose text matches the title. Pre-#5073 a superadmin saw two rows here: the\n // person/company profile plus a navigation-less `customers:customer_entity` row.\n // Filtering by `hasText: title` first would make the assertion depend on the\n // duplicate carrying the same title \u2014 true today, because `customer_entity`\n // registers no `formatResult` and the fallback resolver picks `display_name`, but\n // not a property this spec controls. Since the query is a `Date.now()`-stamped\n // token that matches nothing else in the tenant, the honest assertion is that the\n // palette holds exactly one row, whatever it is titled. `role=\"option\"` is rendered\n // once per result and nowhere else in the listbox (`TopbarSearchInline.tsx`), so\n // the count is exactly the result rows.\n //\n // The palette also debounces by 220ms and renders a \"no results\" placeholder until\n // the response lands, so this waits for the row rather than asserting on an empty\n // list.\n const options = panel.getByRole('option')\n await expect(options).toHaveCount(1, { timeout: 20_000 })\n\n const option = options.first()\n await expect(\n option,\n `the single ${fixture.label} row must be the seeded customer, not an unrelated result`,\n ).toContainText(fixture.title)\n const optionClass = (await option.getAttribute('class')) ?? ''\n expect(\n optionClass,\n `the ${fixture.label} row must have a primary link \u2014 'opacity-60' marks the greyed-out, unclickable duplicate`,\n ).not.toContain('opacity-60')\n\n // -- The row navigates. `openResult` is a no-op when the result has no primary link,\n // so a duplicate row would leave the URL on /backend.\n await option.click()\n await page.waitForURL(new RegExp(`${fixture.detailPrefix}/[^/?#]+$`), { timeout: 20_000 })\n }\n } finally {\n await deleteEntityIfExists(request, adminToken, '/api/customers/people', personId)\n await deleteEntityIfExists(request, adminToken, '/api/customers/companies', companyId)\n if (superToken && originalStrategies) {\n await writeEnabledStrategies(request, superToken, originalStrategies).catch(() => undefined)\n }\n }\n })\n\n /**\n * End-to-end sanity arm for the deliberate read-side-only decision behind #5073: #5073 stopped\n * the token strategy from OFFERING base `customers:customer_entity` rows, but deliberately kept\n * writing them, because the People/Companies list search resolves ids through them. This arm\n * asserts that a customer is still findable through the list search boxes.\n *\n * What this arm pins is exactly that \u2014 the customer stays findable \u2014 and NOT the write-side\n * decision, so a future engineer weighing a `search_tokens` cleanup should not read a green run\n * here as clearance. Searching by `displayName` can be served by three different paths:\n *\n * 1. The `customers:customer_entity` token source \u2014 the one the read-side-only decision is\n * about.\n * 2. The `customers:customer_person_profile` / `customer_company_profile` token source. Both\n * list routes pass TWO sources to `findMatchingEntityIdsBySearchTokensAcrossSources`\n * (`api/people/route.ts`, `api/companies/route.ts`), the profile source also indexes\n * `display_name`, and `api/utils.ts` UNIONS the per-source ids.\n * 3. The `$or` ILIKE fallback both routes take when that union comes back null or empty.\n *\n * Path 2 is why a green run here says nothing about path 1, and the mechanism is the union\n * rather than anything about encryption. A source that queries successfully and matches nothing\n * returns `[]`, not `null` \u2014 `findEntityIdsBySearchTokensCompat` reserves `null` for a blank\n * query alone (`shared/lib/search/tokenLookup.ts`) \u2014 so ONE matching source keeps the union\n * non-empty, and the route then takes `applyEntityIdRestriction` and never builds the ILIKE\n * `$or` at all. Drop the base rows write-side and the profile source still resolves\n * `display_name` by itself, because a profile's index document merges the parent\n * `customer_entities` row before tokenizing (`query_index/lib/indexer.ts`). The union stays\n * non-empty, the customer is still found, and this arm stays green \u2014 encrypted or not.\n *\n * Pinning the write-side property IS reachable, just not by this query. `next_interaction_name`\n * is listed by the base source in BOTH routes and by NEITHER profile source, and the token\n * lookup restricts its query to the field names its source declares (`tokenLookup.ts`), so no\n * profile-source token can answer it. It is also declared encrypted for\n * `customers:customer_entity` (`packages/core/src/modules/customers/encryption.ts`), so the\n * ILIKE fallback cannot serve it either: against a known-encrypted column the query engine\n * rewrites the ILIKE back into a `search_tokens` EXISTS subquery, or \u2014 once the availability\n * probe finds no tokens at all \u2014 runs a literal ILIKE against ciphertext that matches nothing\n * (`query_index/lib/engine.ts`). So with the base rows gone both sources return `[]`, the union\n * empties, the route falls through to ILIKE, and a search on that field finds nothing \u2014 failing\n * exactly when the write-side rows go away. Left for a follow-up rather than written here:\n * `createPersonFixture` would need to accept the field first.\n *\n * Treat a failure here as a real signal that list search broke, and a pass as saying nothing\n * about whether the base `customers:customer_entity` rows still exist.\n */\n test('the People and Companies list search still finds the customer', async ({ page, request }) => {\n test.setTimeout(180_000)\n\n const stamp = Date.now()\n const personName = `QASRCH014LP${stamp}`\n const companyName = `QASRCH014LC${stamp}`\n let adminToken: string | null = null\n let personId: string | null = null\n let companyId: string | null = null\n\n try {\n adminToken = (await resolveTokens(request)).adminToken\n\n personId = await createPersonFixture(request, adminToken, {\n firstName: 'QA',\n lastName: `Search 014 List ${stamp}`,\n displayName: personName,\n })\n companyId = await createCompanyFixture(request, adminToken, companyName)\n\n await login(page, 'superadmin')\n\n const listArms = [\n { label: 'people', path: '/backend/customers/people', endpoint: '/api/customers/people', title: personName },\n {\n label: 'companies',\n path: '/backend/customers/companies',\n endpoint: '/api/customers/companies',\n title: companyName,\n },\n ] as const\n\n for (const arm of listArms) {\n await page.goto(arm.path)\n await page.waitForLoadState('domcontentloaded')\n\n const searchBox = page.getByPlaceholder(LIST_SEARCH_PLACEHOLDER)\n await expect(searchBox).toBeVisible()\n\n // Wait for the FILTERED response specifically. Asserting only that the row is\n // visible after typing would be a false guard: a freshly created customer can\n // already sit on the unfiltered first page, so the assertion would pass even if\n // list search resolved no ids at all \u2014 the exact regression this arm exists to\n // catch. Keying the wait on `search=<token>` proves the query really ran.\n const filteredResponse = page.waitForResponse(\n (response) => {\n const url = new URL(response.url())\n return (\n url.pathname === arm.endpoint &&\n url.searchParams.get('search') === arm.title &&\n response.status() === 200\n )\n },\n { timeout: 30_000 },\n )\n await searchBox.fill(arm.title)\n await filteredResponse\n\n await expect(\n page.getByText(arm.title, { exact: true }).first(),\n `${arm.label} list search must still return the customer after #5073 stopped offering base customer rows as search results`,\n ).toBeVisible({ timeout: 20_000 })\n }\n } finally {\n await deleteEntityIfExists(request, adminToken, '/api/customers/people', personId)\n await deleteEntityIfExists(request, adminToken, '/api/customers/companies', companyId)\n }\n })\n})\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,QAAQ,YAA+C;AAChE,SAAS,YAAY,oBAAoB;AACzC,SAAS,iBAAiB,oBAAoB;AAC9C,SAAS,aAAa;AACtB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEA,MAAM,kBAAkB,EAAE,kBAAkB,CAAC,UAAU,WAAW,EAAE;AAW3E,MAAM,qBAAqB,CAAC,YAAY,UAAU,QAAQ;AAC1D,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;AAOxB,MAAM,0BAA0B;AAUhC,SAAS,eAAe,QAAyC;AAC/D,QAAM,QAAQ,OAAO,WAAW;AAChC,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,MAAM,KAAK,IAAI;AAC/E;AAEA,eAAe,sBAAsB,SAA4B,OAAkC;AACjG,QAAM,WAAW,MAAM,WAAW,SAAS,OAAO,sCAAsC,EAAE,MAAM,CAAC;AACjG,SAAO,SAAS,GAAG,GAAG,2CAA2C,EAAE,WAAW;AAC9E,QAAM,OAAQ,MAAM,aAAmC,QAAQ,KAAM,CAAC;AACtE,SAAO,MAAM,QAAQ,KAAK,iBAAiB,KAAK,KAAK,kBAAkB,SAAS,IAC5E,KAAK,oBACL;AACN;AAEA,eAAe,uBACb,SACA,OACA,YACe;AAC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AC;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/service.js
CHANGED
|
@@ -69,10 +69,11 @@ class SearchService {
|
|
|
69
69
|
return [];
|
|
70
70
|
}
|
|
71
71
|
const strategyIds = options.strategies ?? this.defaultStrategies;
|
|
72
|
-
const
|
|
72
|
+
const honorsFilter = (strategy) => !options.indexDocFilter || strategy.supportsIndexDocFilter === true;
|
|
73
|
+
const activeStrategies = (await this.getAvailableStrategies(strategyIds)).filter(honorsFilter);
|
|
73
74
|
if (activeStrategies.length === 0) {
|
|
74
75
|
if (this.fallbackStrategy) {
|
|
75
|
-
const fallback = await this.getAvailableStrategies([this.fallbackStrategy]);
|
|
76
|
+
const fallback = (await this.getAvailableStrategies([this.fallbackStrategy])).filter(honorsFilter);
|
|
76
77
|
if (fallback.length > 0) {
|
|
77
78
|
activeStrategies.push(...fallback);
|
|
78
79
|
}
|
package/dist/service.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/service.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n SearchStrategy,\n SearchStrategyId,\n SearchOptions,\n SearchResult,\n SearchServiceOptions,\n ResultMergeConfig,\n IndexableRecord,\n PresenterEnricherFn,\n} from './types'\nimport { mergeAndRankResults } from './lib/merger'\nimport { searchError } from './lib/debug'\n\n/**\n * Default merge configuration.\n */\nconst DEFAULT_MERGE_CONFIG: ResultMergeConfig = {\n duplicateHandling: 'highest_score',\n}\n\n/**\n * Cache TTL for strategy availability checks.\n * Short window so connectivity changes (Meilisearch up/down) propagate quickly,\n * long enough to skip per-request RTT to remote backends on hot paths.\n */\nconst STRATEGY_AVAILABILITY_CACHE_TTL_MS = 2_000\n\n/**\n * Maximum records indexed at once when bulkIndex falls back to per-record writes\n * for a strategy that has no bulkIndex implementation (currently the vector\n * strategy, whose index() performs an embedding-provider round trip per record).\n * A whole reindex page arrives in one bulkIndex call, so an unbounded fan-out\n * would burst hundreds of concurrent provider requests from a single job.\n */\nconst BULK_INDEX_FALLBACK_CONCURRENCY = 4\n\n/**\n * Map items through an async worker with a fixed number of in-flight calls.\n * Rejects with the first error, matching Promise.all semantics.\n */\nasync function mapWithConcurrency<T>(\n items: T[],\n limit: number,\n worker: (item: T) => Promise<void>,\n): Promise<void> {\n if (items.length === 0) return\n\n let nextIndex = 0\n const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {\n for (;;) {\n const currentIndex = nextIndex++\n if (currentIndex >= items.length) return\n await worker(items[currentIndex])\n }\n })\n\n await Promise.all(runners)\n}\n\nfunction normalizeOrganizationFilter(options: SearchOptions): string[] | null {\n const single = typeof options.organizationId === 'string' ? options.organizationId.trim() : ''\n if (single) return [single]\n if (!Array.isArray(options.organizationIds)) return null\n\n const values = Array.from(new Set(\n options.organizationIds\n .map((value) => (typeof value === 'string' ? value.trim() : ''))\n .filter((value) => value.length > 0),\n ))\n return values\n}\n\nfunction filterResultsByOrganizationScope(results: SearchResult[], options: SearchOptions): SearchResult[] {\n const organizationIds = normalizeOrganizationFilter(options)\n if (!organizationIds) return results\n if (organizationIds.length === 0) return []\n\n const allowed = new Set(organizationIds)\n return results.filter((result) => {\n const organizationId = typeof result.organizationId === 'string' ? result.organizationId.trim() : ''\n return organizationId.length > 0 && allowed.has(organizationId)\n })\n}\n\n/**\n * SearchService orchestrates multiple search strategies, executing searches in parallel\n * and merging results using the RRF algorithm.\n *\n * Features:\n * - Parallel strategy execution for optimal performance\n * - Graceful degradation when strategies fail\n * - Result merging with configurable weights\n * - Strategy availability checking\n *\n * @example\n * ```typescript\n * const service = new SearchService({\n * strategies: [tokenStrategy, vectorStrategy, fulltextStrategy],\n * defaultStrategies: ['fulltext', 'vector', 'tokens'],\n * mergeConfig: {\n * duplicateHandling: 'highest_score',\n * strategyWeights: { fulltext: 1.2, vector: 1.0, tokens: 0.8 },\n * },\n * })\n *\n * const results = await service.search('john doe', { tenantId: 'tenant-123' })\n * ```\n */\nexport class SearchService {\n private readonly strategies: Map<SearchStrategyId, SearchStrategy>\n private readonly defaultStrategies: SearchStrategyId[]\n private readonly fallbackStrategy: SearchStrategyId | undefined\n private readonly mergeConfig: ResultMergeConfig\n private readonly presenterEnricher?: PresenterEnricherFn\n private readonly availabilityCache = new Map<SearchStrategyId, { value: boolean; expiresAt: number }>()\n private readonly availabilityInflight = new Map<SearchStrategyId, Promise<boolean>>()\n private readonly availabilityCacheTtlMs: number\n\n constructor(options: SearchServiceOptions = {}) {\n this.strategies = new Map()\n for (const strategy of options.strategies ?? []) {\n this.strategies.set(strategy.id, strategy)\n }\n this.defaultStrategies = options.defaultStrategies ?? ['tokens']\n this.fallbackStrategy = options.fallbackStrategy\n this.mergeConfig = options.mergeConfig ?? DEFAULT_MERGE_CONFIG\n this.presenterEnricher = options.presenterEnricher\n this.availabilityCacheTtlMs = options.availabilityCacheTtlMs ?? STRATEGY_AVAILABILITY_CACHE_TTL_MS\n }\n\n /**\n * Get all registered strategies.\n */\n getStrategies(): SearchStrategy[] {\n return Array.from(this.strategies.values())\n }\n\n /**\n * Execute a search query across configured strategies.\n *\n * @param query - Search query string\n * @param options - Search options with tenant, filters, etc.\n * @returns Merged and ranked search results\n */\n async search(query: string, options: SearchOptions): Promise<SearchResult[]> {\n const organizationIds = normalizeOrganizationFilter(options)\n if (organizationIds && organizationIds.length === 0) {\n return []\n }\n\n const strategyIds = options.strategies ?? this.defaultStrategies\n const activeStrategies = await this.getAvailableStrategies(strategyIds)\n\n if (activeStrategies.length === 0) {\n // Try fallback strategy if defined\n if (this.fallbackStrategy) {\n const fallback = await this.getAvailableStrategies([this.fallbackStrategy])\n if (fallback.length > 0) {\n activeStrategies.push(...fallback)\n }\n }\n }\n\n if (activeStrategies.length === 0) {\n return []\n }\n\n // Execute searches in parallel with graceful degradation\n const results = await Promise.allSettled(\n activeStrategies.map((strategy) => this.executeStrategySearch(strategy, query, options)),\n )\n\n // Collect successful results, log failures\n const allResults: SearchResult[] = []\n for (let i = 0; i < results.length; i++) {\n const result = results[i]\n if (result.status === 'fulfilled') {\n allResults.push(...result.value)\n } else {\n const strategy = activeStrategies[i]\n searchError('SearchService', 'Strategy search failed', {\n strategyId: strategy?.id,\n error: result.reason instanceof Error ? result.reason.message : result.reason,\n })\n }\n }\n\n // Merge and rank results\n const merged = mergeAndRankResults(allResults, this.mergeConfig)\n const scoped = filterResultsByOrganizationScope(merged, options)\n\n // Enrich results missing presenter or navigation metadata\n return this.enrichResultsWithPresenter(scoped, options.tenantId, options.organizationId)\n }\n\n /**\n * Recompute configured presenters at request time and fill missing presenter\n * or navigation data for unconfigured results.\n */\n private async enrichResultsWithPresenter(\n results: SearchResult[],\n tenantId: string,\n organizationId?: string | null,\n ): Promise<SearchResult[]> {\n // If no enricher configured, return as-is\n if (!this.presenterEnricher) return results\n\n try {\n return await this.presenterEnricher(results, tenantId, organizationId)\n } catch {\n // Enrichment failed, return results as-is\n return results\n }\n }\n\n /**\n * Index a record across all available strategies.\n *\n * @param record - Record to index\n */\n async index(record: IndexableRecord): Promise<void> {\n const strategies = await this.getAvailableStrategies()\n\n if (strategies.length === 0) {\n return\n }\n\n const results = await Promise.allSettled(\n strategies.map((strategy) => this.executeStrategyIndex(strategy, record)),\n )\n\n this.throwOnStrategyFailures('index', strategies, results, {\n entityId: record.entityId,\n recordId: record.recordId,\n })\n }\n\n /**\n * Delete a record from all strategies.\n *\n * @param entityId - Entity type identifier\n * @param recordId - Record primary key\n * @param tenantId - Tenant for isolation\n */\n async delete(entityId: string, recordId: string, tenantId: string): Promise<void> {\n const strategies = await this.getAvailableStrategies()\n\n const results = await Promise.allSettled(\n strategies.map((strategy) => this.executeStrategyDelete(strategy, entityId, recordId, tenantId)),\n )\n\n this.throwOnStrategyFailures('delete', strategies, results, { entityId, recordId })\n }\n\n /**\n * Bulk index multiple records.\n *\n * @param records - Records to index\n */\n async bulkIndex(records: IndexableRecord[]): Promise<void> {\n if (records.length === 0) return\n\n const strategies = await this.getAvailableStrategies()\n\n const results = await Promise.allSettled(\n strategies.map((strategy) => {\n if (strategy.bulkIndex) {\n return strategy.bulkIndex(records)\n }\n // Fallback to individual indexing, bounded so a strategy without a batch\n // implementation cannot turn one batch job into hundreds of concurrent writes.\n return mapWithConcurrency(records, BULK_INDEX_FALLBACK_CONCURRENCY, (record) =>\n this.executeStrategyIndex(strategy, record),\n )\n }),\n )\n\n // Collect failures and throw if any occurred\n const failures: Array<{ strategyId: string; error: string }> = []\n for (let i = 0; i < results.length; i++) {\n const result = results[i]\n if (result.status === 'rejected') {\n const strategy = strategies[i]\n const errorMessage = result.reason instanceof Error ? result.reason.message : result.reason\n failures.push({\n strategyId: strategy?.id || 'unknown',\n error: errorMessage,\n })\n searchError('SearchService', 'Strategy bulkIndex failed', {\n strategyId: strategy?.id,\n recordCount: records.length,\n error: errorMessage,\n })\n }\n }\n\n if (failures.length > 0) {\n throw new Error(\n `Bulk indexing failed for ${failures.length} strategy(ies): ${failures\n .map((f) => `${f.strategyId} (${f.error})`)\n .join(', ')}`\n )\n }\n }\n\n /**\n * Purge all records for an entity type.\n *\n * @param entityId - Entity type to purge\n * @param tenantId - Tenant for isolation\n */\n async purge(entityId: string, tenantId: string, organizationId?: string | null): Promise<void> {\n const strategies = await this.getAvailableStrategies()\n\n const results = await Promise.allSettled(\n strategies.map((strategy) => {\n if (strategy.purge) {\n return strategy.purge(entityId, tenantId, organizationId)\n }\n return Promise.resolve()\n }),\n )\n\n this.throwOnStrategyFailures('purge', strategies, results, { entityId })\n }\n\n /**\n * Inspect the settled results of a per-strategy write operation, log every\n * rejection, and re-throw an aggregated error when any strategy failed.\n *\n * Write operations (index/delete/purge) must surface failures to the caller\n * so the queue worker re-throws and the job is retried. Swallowing rejections\n * here causes silent, permanent index gaps on transient failures such as\n * Postgres connection-pool exhaustion (issue #3103). Successful strategies\n * still commit their work; only the aggregated failure propagates.\n */\n private throwOnStrategyFailures(\n operation: 'index' | 'delete' | 'purge',\n strategies: SearchStrategy[],\n results: PromiseSettledResult<unknown>[],\n context: { entityId: string; recordId?: string },\n ): void {\n const failures: Array<{ strategyId: string; reason: unknown }> = []\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i]\n if (result.status === 'rejected') {\n const strategy = strategies[i]\n failures.push({ strategyId: strategy?.id || 'unknown', reason: result.reason })\n searchError('SearchService', `Strategy ${operation} failed`, {\n strategyId: strategy?.id,\n entityId: context.entityId,\n recordId: context.recordId,\n error: result.reason instanceof Error ? result.reason.message : result.reason,\n })\n }\n }\n\n if (failures.length === 0) return\n\n const summary = `Search ${operation} failed for ${failures.length} strategy(ies): ${failures\n .map((failure) => {\n const message = failure.reason instanceof Error ? failure.reason.message : String(failure.reason)\n return `${failure.strategyId} (${message})`\n })\n .join(', ')}`\n\n throw new AggregateError(\n failures.map((failure) => failure.reason),\n summary,\n )\n }\n\n /**\n * Register a new strategy at runtime.\n *\n * @param strategy - Strategy to register\n */\n registerStrategy(strategy: SearchStrategy): void {\n this.strategies.set(strategy.id, strategy)\n this.availabilityCache.delete(strategy.id)\n this.availabilityInflight.delete(strategy.id)\n }\n\n /**\n * Unregister a strategy.\n *\n * @param strategyId - Strategy ID to remove\n */\n unregisterStrategy(strategyId: SearchStrategyId): void {\n this.strategies.delete(strategyId)\n this.availabilityCache.delete(strategyId)\n this.availabilityInflight.delete(strategyId)\n }\n\n /**\n * Invalidate the strategy availability cache.\n * Call after manual reconnects or env changes when callers must observe the\n * current backend state immediately rather than waiting for TTL expiry.\n */\n invalidateAvailabilityCache(strategyId?: SearchStrategyId): void {\n if (strategyId) {\n this.availabilityCache.delete(strategyId)\n this.availabilityInflight.delete(strategyId)\n return\n }\n this.availabilityCache.clear()\n this.availabilityInflight.clear()\n }\n\n /**\n * Get all registered strategy IDs.\n */\n getRegisteredStrategies(): SearchStrategyId[] {\n return Array.from(this.strategies.keys())\n }\n\n /**\n * Get a specific strategy by ID.\n *\n * @param strategyId - Strategy ID to retrieve\n * @returns The strategy if registered, undefined otherwise\n */\n getStrategy(strategyId: SearchStrategyId): SearchStrategy | undefined {\n return this.strategies.get(strategyId)\n }\n\n /**\n * Get the default strategies list.\n */\n getDefaultStrategies(): SearchStrategyId[] {\n return [...this.defaultStrategies]\n }\n\n /**\n * Check if a specific strategy is available.\n *\n * @param strategyId - Strategy ID to check\n */\n async isStrategyAvailable(strategyId: SearchStrategyId): Promise<boolean> {\n const strategy = this.strategies.get(strategyId)\n if (!strategy) return false\n return this.checkStrategyAvailability(strategy)\n }\n\n /**\n * Resolve a strategy's availability via the short-lived TTL cache.\n * Coalesces concurrent callers onto a single in-flight probe to avoid\n * thundering-herd on remote backends.\n */\n private async checkStrategyAvailability(strategy: SearchStrategy): Promise<boolean> {\n const now = Date.now()\n const cached = this.availabilityCache.get(strategy.id)\n if (cached && cached.expiresAt > now) return cached.value\n\n const inflight = this.availabilityInflight.get(strategy.id)\n if (inflight) return inflight\n\n const probe = (async () => {\n try {\n const value = await strategy.isAvailable()\n this.availabilityCache.set(strategy.id, {\n value,\n expiresAt: Date.now() + this.availabilityCacheTtlMs,\n })\n return value\n } catch {\n this.availabilityCache.set(strategy.id, {\n value: false,\n expiresAt: Date.now() + this.availabilityCacheTtlMs,\n })\n return false\n } finally {\n this.availabilityInflight.delete(strategy.id)\n }\n })()\n this.availabilityInflight.set(strategy.id, probe)\n return probe\n }\n\n /**\n * Get available strategies from the requested list.\n * Filters out strategies that are not registered or not available.\n * Probes run in parallel and reuse a short-lived per-strategy availability\n * cache, so hot paths pay the max latency of the slowest probe (or zero\n * when cached) instead of the sum of all probes.\n */\n private async getAvailableStrategies(ids?: SearchStrategyId[]): Promise<SearchStrategy[]> {\n const targetIds = ids ?? Array.from(this.strategies.keys())\n const candidates: SearchStrategy[] = []\n for (const id of targetIds) {\n const strategy = this.strategies.get(id)\n if (strategy) candidates.push(strategy)\n }\n\n const probes = await Promise.allSettled(\n candidates.map((strategy) => this.checkStrategyAvailability(strategy)),\n )\n\n const available: SearchStrategy[] = []\n for (let i = 0; i < probes.length; i++) {\n const probe = probes[i]\n if (probe.status === 'fulfilled' && probe.value) {\n available.push(candidates[i])\n }\n }\n\n return available.sort((a, b) => b.priority - a.priority)\n }\n\n /**\n * Execute search on a single strategy with error handling.\n */\n private async executeStrategySearch(\n strategy: SearchStrategy,\n query: string,\n options: SearchOptions,\n ): Promise<SearchResult[]> {\n await strategy.ensureReady()\n return strategy.search(query, options)\n }\n\n /**\n * Execute index on a single strategy with error handling.\n */\n private async executeStrategyIndex(\n strategy: SearchStrategy,\n record: IndexableRecord,\n ): Promise<void> {\n await strategy.ensureReady()\n return strategy.index(record)\n }\n\n /**\n * Execute delete on a single strategy with error handling.\n */\n private async executeStrategyDelete(\n strategy: SearchStrategy,\n entityId: string,\n recordId: string,\n tenantId: string,\n ): Promise<void> {\n await strategy.ensureReady()\n return strategy.delete(entityId, recordId, tenantId)\n }\n}\n"],
|
|
5
|
-
"mappings": "AAUA,SAAS,2BAA2B;AACpC,SAAS,mBAAmB;AAK5B,MAAM,uBAA0C;AAAA,EAC9C,mBAAmB;AACrB;AAOA,MAAM,qCAAqC;AAS3C,MAAM,kCAAkC;AAMxC,eAAe,mBACb,OACA,OACA,QACe;AACf,MAAI,MAAM,WAAW,EAAG;AAExB,MAAI,YAAY;AAChB,QAAM,UAAU,MAAM,KAAK,EAAE,QAAQ,KAAK,IAAI,OAAO,MAAM,MAAM,EAAE,GAAG,YAAY;AAChF,eAAS;AACP,YAAM,eAAe;AACrB,UAAI,gBAAgB,MAAM,OAAQ;AAClC,YAAM,OAAO,MAAM,YAAY,CAAC;AAAA,IAClC;AAAA,EACF,CAAC;AAED,QAAM,QAAQ,IAAI,OAAO;AAC3B;AAEA,SAAS,4BAA4B,SAAyC;AAC5E,QAAM,SAAS,OAAO,QAAQ,mBAAmB,WAAW,QAAQ,eAAe,KAAK,IAAI;AAC5F,MAAI,OAAQ,QAAO,CAAC,MAAM;AAC1B,MAAI,CAAC,MAAM,QAAQ,QAAQ,eAAe,EAAG,QAAO;AAEpD,QAAM,SAAS,MAAM,KA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gB,WAAW,GAAG;AACnD,aAAO,CAAC;AAAA,IACV;AAEA,UAAM,cAAc,QAAQ,cAAc,KAAK;AAC/C,UAAM,
|
|
4
|
+
"sourcesContent": ["import type {\n SearchStrategy,\n SearchStrategyId,\n SearchOptions,\n SearchResult,\n SearchServiceOptions,\n ResultMergeConfig,\n IndexableRecord,\n PresenterEnricherFn,\n} from './types'\nimport { mergeAndRankResults } from './lib/merger'\nimport { searchError } from './lib/debug'\n\n/**\n * Default merge configuration.\n */\nconst DEFAULT_MERGE_CONFIG: ResultMergeConfig = {\n duplicateHandling: 'highest_score',\n}\n\n/**\n * Cache TTL for strategy availability checks.\n * Short window so connectivity changes (Meilisearch up/down) propagate quickly,\n * long enough to skip per-request RTT to remote backends on hot paths.\n */\nconst STRATEGY_AVAILABILITY_CACHE_TTL_MS = 2_000\n\n/**\n * Maximum records indexed at once when bulkIndex falls back to per-record writes\n * for a strategy that has no bulkIndex implementation (currently the vector\n * strategy, whose index() performs an embedding-provider round trip per record).\n * A whole reindex page arrives in one bulkIndex call, so an unbounded fan-out\n * would burst hundreds of concurrent provider requests from a single job.\n */\nconst BULK_INDEX_FALLBACK_CONCURRENCY = 4\n\n/**\n * Map items through an async worker with a fixed number of in-flight calls.\n * Rejects with the first error, matching Promise.all semantics.\n */\nasync function mapWithConcurrency<T>(\n items: T[],\n limit: number,\n worker: (item: T) => Promise<void>,\n): Promise<void> {\n if (items.length === 0) return\n\n let nextIndex = 0\n const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {\n for (;;) {\n const currentIndex = nextIndex++\n if (currentIndex >= items.length) return\n await worker(items[currentIndex])\n }\n })\n\n await Promise.all(runners)\n}\n\nfunction normalizeOrganizationFilter(options: SearchOptions): string[] | null {\n const single = typeof options.organizationId === 'string' ? options.organizationId.trim() : ''\n if (single) return [single]\n if (!Array.isArray(options.organizationIds)) return null\n\n const values = Array.from(new Set(\n options.organizationIds\n .map((value) => (typeof value === 'string' ? value.trim() : ''))\n .filter((value) => value.length > 0),\n ))\n return values\n}\n\nfunction filterResultsByOrganizationScope(results: SearchResult[], options: SearchOptions): SearchResult[] {\n const organizationIds = normalizeOrganizationFilter(options)\n if (!organizationIds) return results\n if (organizationIds.length === 0) return []\n\n const allowed = new Set(organizationIds)\n return results.filter((result) => {\n const organizationId = typeof result.organizationId === 'string' ? result.organizationId.trim() : ''\n return organizationId.length > 0 && allowed.has(organizationId)\n })\n}\n\n/**\n * SearchService orchestrates multiple search strategies, executing searches in parallel\n * and merging results using the RRF algorithm.\n *\n * Features:\n * - Parallel strategy execution for optimal performance\n * - Graceful degradation when strategies fail\n * - Result merging with configurable weights\n * - Strategy availability checking\n *\n * @example\n * ```typescript\n * const service = new SearchService({\n * strategies: [tokenStrategy, vectorStrategy, fulltextStrategy],\n * defaultStrategies: ['fulltext', 'vector', 'tokens'],\n * mergeConfig: {\n * duplicateHandling: 'highest_score',\n * strategyWeights: { fulltext: 1.2, vector: 1.0, tokens: 0.8 },\n * },\n * })\n *\n * const results = await service.search('john doe', { tenantId: 'tenant-123' })\n * ```\n */\nexport class SearchService {\n private readonly strategies: Map<SearchStrategyId, SearchStrategy>\n private readonly defaultStrategies: SearchStrategyId[]\n private readonly fallbackStrategy: SearchStrategyId | undefined\n private readonly mergeConfig: ResultMergeConfig\n private readonly presenterEnricher?: PresenterEnricherFn\n private readonly availabilityCache = new Map<SearchStrategyId, { value: boolean; expiresAt: number }>()\n private readonly availabilityInflight = new Map<SearchStrategyId, Promise<boolean>>()\n private readonly availabilityCacheTtlMs: number\n\n constructor(options: SearchServiceOptions = {}) {\n this.strategies = new Map()\n for (const strategy of options.strategies ?? []) {\n this.strategies.set(strategy.id, strategy)\n }\n this.defaultStrategies = options.defaultStrategies ?? ['tokens']\n this.fallbackStrategy = options.fallbackStrategy\n this.mergeConfig = options.mergeConfig ?? DEFAULT_MERGE_CONFIG\n this.presenterEnricher = options.presenterEnricher\n this.availabilityCacheTtlMs = options.availabilityCacheTtlMs ?? STRATEGY_AVAILABILITY_CACHE_TTL_MS\n }\n\n /**\n * Get all registered strategies.\n */\n getStrategies(): SearchStrategy[] {\n return Array.from(this.strategies.values())\n }\n\n /**\n * Execute a search query across configured strategies.\n *\n * @param query - Search query string\n * @param options - Search options with tenant, filters, etc.\n * @returns Merged and ranked search results\n */\n async search(query: string, options: SearchOptions): Promise<SearchResult[]> {\n const organizationIds = normalizeOrganizationFilter(options)\n if (organizationIds && organizationIds.length === 0) {\n return []\n }\n\n const strategyIds = options.strategies ?? this.defaultStrategies\n const honorsFilter = (strategy: SearchStrategy) =>\n !options.indexDocFilter || strategy.supportsIndexDocFilter === true\n const activeStrategies = (await this.getAvailableStrategies(strategyIds)).filter(honorsFilter)\n\n if (activeStrategies.length === 0) {\n // Try fallback strategy if defined\n if (this.fallbackStrategy) {\n const fallback = (await this.getAvailableStrategies([this.fallbackStrategy])).filter(honorsFilter)\n if (fallback.length > 0) {\n activeStrategies.push(...fallback)\n }\n }\n }\n\n if (activeStrategies.length === 0) {\n return []\n }\n\n // Execute searches in parallel with graceful degradation\n const results = await Promise.allSettled(\n activeStrategies.map((strategy) => this.executeStrategySearch(strategy, query, options)),\n )\n\n // Collect successful results, log failures\n const allResults: SearchResult[] = []\n for (let i = 0; i < results.length; i++) {\n const result = results[i]\n if (result.status === 'fulfilled') {\n allResults.push(...result.value)\n } else {\n const strategy = activeStrategies[i]\n searchError('SearchService', 'Strategy search failed', {\n strategyId: strategy?.id,\n error: result.reason instanceof Error ? result.reason.message : result.reason,\n })\n }\n }\n\n // Merge and rank results\n const merged = mergeAndRankResults(allResults, this.mergeConfig)\n const scoped = filterResultsByOrganizationScope(merged, options)\n\n // Enrich results missing presenter or navigation metadata\n return this.enrichResultsWithPresenter(scoped, options.tenantId, options.organizationId)\n }\n\n /**\n * Recompute configured presenters at request time and fill missing presenter\n * or navigation data for unconfigured results.\n */\n private async enrichResultsWithPresenter(\n results: SearchResult[],\n tenantId: string,\n organizationId?: string | null,\n ): Promise<SearchResult[]> {\n // If no enricher configured, return as-is\n if (!this.presenterEnricher) return results\n\n try {\n return await this.presenterEnricher(results, tenantId, organizationId)\n } catch {\n // Enrichment failed, return results as-is\n return results\n }\n }\n\n /**\n * Index a record across all available strategies.\n *\n * @param record - Record to index\n */\n async index(record: IndexableRecord): Promise<void> {\n const strategies = await this.getAvailableStrategies()\n\n if (strategies.length === 0) {\n return\n }\n\n const results = await Promise.allSettled(\n strategies.map((strategy) => this.executeStrategyIndex(strategy, record)),\n )\n\n this.throwOnStrategyFailures('index', strategies, results, {\n entityId: record.entityId,\n recordId: record.recordId,\n })\n }\n\n /**\n * Delete a record from all strategies.\n *\n * @param entityId - Entity type identifier\n * @param recordId - Record primary key\n * @param tenantId - Tenant for isolation\n */\n async delete(entityId: string, recordId: string, tenantId: string): Promise<void> {\n const strategies = await this.getAvailableStrategies()\n\n const results = await Promise.allSettled(\n strategies.map((strategy) => this.executeStrategyDelete(strategy, entityId, recordId, tenantId)),\n )\n\n this.throwOnStrategyFailures('delete', strategies, results, { entityId, recordId })\n }\n\n /**\n * Bulk index multiple records.\n *\n * @param records - Records to index\n */\n async bulkIndex(records: IndexableRecord[]): Promise<void> {\n if (records.length === 0) return\n\n const strategies = await this.getAvailableStrategies()\n\n const results = await Promise.allSettled(\n strategies.map((strategy) => {\n if (strategy.bulkIndex) {\n return strategy.bulkIndex(records)\n }\n // Fallback to individual indexing, bounded so a strategy without a batch\n // implementation cannot turn one batch job into hundreds of concurrent writes.\n return mapWithConcurrency(records, BULK_INDEX_FALLBACK_CONCURRENCY, (record) =>\n this.executeStrategyIndex(strategy, record),\n )\n }),\n )\n\n // Collect failures and throw if any occurred\n const failures: Array<{ strategyId: string; error: string }> = []\n for (let i = 0; i < results.length; i++) {\n const result = results[i]\n if (result.status === 'rejected') {\n const strategy = strategies[i]\n const errorMessage = result.reason instanceof Error ? result.reason.message : result.reason\n failures.push({\n strategyId: strategy?.id || 'unknown',\n error: errorMessage,\n })\n searchError('SearchService', 'Strategy bulkIndex failed', {\n strategyId: strategy?.id,\n recordCount: records.length,\n error: errorMessage,\n })\n }\n }\n\n if (failures.length > 0) {\n throw new Error(\n `Bulk indexing failed for ${failures.length} strategy(ies): ${failures\n .map((f) => `${f.strategyId} (${f.error})`)\n .join(', ')}`\n )\n }\n }\n\n /**\n * Purge all records for an entity type.\n *\n * @param entityId - Entity type to purge\n * @param tenantId - Tenant for isolation\n */\n async purge(entityId: string, tenantId: string, organizationId?: string | null): Promise<void> {\n const strategies = await this.getAvailableStrategies()\n\n const results = await Promise.allSettled(\n strategies.map((strategy) => {\n if (strategy.purge) {\n return strategy.purge(entityId, tenantId, organizationId)\n }\n return Promise.resolve()\n }),\n )\n\n this.throwOnStrategyFailures('purge', strategies, results, { entityId })\n }\n\n /**\n * Inspect the settled results of a per-strategy write operation, log every\n * rejection, and re-throw an aggregated error when any strategy failed.\n *\n * Write operations (index/delete/purge) must surface failures to the caller\n * so the queue worker re-throws and the job is retried. Swallowing rejections\n * here causes silent, permanent index gaps on transient failures such as\n * Postgres connection-pool exhaustion (issue #3103). Successful strategies\n * still commit their work; only the aggregated failure propagates.\n */\n private throwOnStrategyFailures(\n operation: 'index' | 'delete' | 'purge',\n strategies: SearchStrategy[],\n results: PromiseSettledResult<unknown>[],\n context: { entityId: string; recordId?: string },\n ): void {\n const failures: Array<{ strategyId: string; reason: unknown }> = []\n\n for (let i = 0; i < results.length; i++) {\n const result = results[i]\n if (result.status === 'rejected') {\n const strategy = strategies[i]\n failures.push({ strategyId: strategy?.id || 'unknown', reason: result.reason })\n searchError('SearchService', `Strategy ${operation} failed`, {\n strategyId: strategy?.id,\n entityId: context.entityId,\n recordId: context.recordId,\n error: result.reason instanceof Error ? result.reason.message : result.reason,\n })\n }\n }\n\n if (failures.length === 0) return\n\n const summary = `Search ${operation} failed for ${failures.length} strategy(ies): ${failures\n .map((failure) => {\n const message = failure.reason instanceof Error ? failure.reason.message : String(failure.reason)\n return `${failure.strategyId} (${message})`\n })\n .join(', ')}`\n\n throw new AggregateError(\n failures.map((failure) => failure.reason),\n summary,\n )\n }\n\n /**\n * Register a new strategy at runtime.\n *\n * @param strategy - Strategy to register\n */\n registerStrategy(strategy: SearchStrategy): void {\n this.strategies.set(strategy.id, strategy)\n this.availabilityCache.delete(strategy.id)\n this.availabilityInflight.delete(strategy.id)\n }\n\n /**\n * Unregister a strategy.\n *\n * @param strategyId - Strategy ID to remove\n */\n unregisterStrategy(strategyId: SearchStrategyId): void {\n this.strategies.delete(strategyId)\n this.availabilityCache.delete(strategyId)\n this.availabilityInflight.delete(strategyId)\n }\n\n /**\n * Invalidate the strategy availability cache.\n * Call after manual reconnects or env changes when callers must observe the\n * current backend state immediately rather than waiting for TTL expiry.\n */\n invalidateAvailabilityCache(strategyId?: SearchStrategyId): void {\n if (strategyId) {\n this.availabilityCache.delete(strategyId)\n this.availabilityInflight.delete(strategyId)\n return\n }\n this.availabilityCache.clear()\n this.availabilityInflight.clear()\n }\n\n /**\n * Get all registered strategy IDs.\n */\n getRegisteredStrategies(): SearchStrategyId[] {\n return Array.from(this.strategies.keys())\n }\n\n /**\n * Get a specific strategy by ID.\n *\n * @param strategyId - Strategy ID to retrieve\n * @returns The strategy if registered, undefined otherwise\n */\n getStrategy(strategyId: SearchStrategyId): SearchStrategy | undefined {\n return this.strategies.get(strategyId)\n }\n\n /**\n * Get the default strategies list.\n */\n getDefaultStrategies(): SearchStrategyId[] {\n return [...this.defaultStrategies]\n }\n\n /**\n * Check if a specific strategy is available.\n *\n * @param strategyId - Strategy ID to check\n */\n async isStrategyAvailable(strategyId: SearchStrategyId): Promise<boolean> {\n const strategy = this.strategies.get(strategyId)\n if (!strategy) return false\n return this.checkStrategyAvailability(strategy)\n }\n\n /**\n * Resolve a strategy's availability via the short-lived TTL cache.\n * Coalesces concurrent callers onto a single in-flight probe to avoid\n * thundering-herd on remote backends.\n */\n private async checkStrategyAvailability(strategy: SearchStrategy): Promise<boolean> {\n const now = Date.now()\n const cached = this.availabilityCache.get(strategy.id)\n if (cached && cached.expiresAt > now) return cached.value\n\n const inflight = this.availabilityInflight.get(strategy.id)\n if (inflight) return inflight\n\n const probe = (async () => {\n try {\n const value = await strategy.isAvailable()\n this.availabilityCache.set(strategy.id, {\n value,\n expiresAt: Date.now() + this.availabilityCacheTtlMs,\n })\n return value\n } catch {\n this.availabilityCache.set(strategy.id, {\n value: false,\n expiresAt: Date.now() + this.availabilityCacheTtlMs,\n })\n return false\n } finally {\n this.availabilityInflight.delete(strategy.id)\n }\n })()\n this.availabilityInflight.set(strategy.id, probe)\n return probe\n }\n\n /**\n * Get available strategies from the requested list.\n * Filters out strategies that are not registered or not available.\n * Probes run in parallel and reuse a short-lived per-strategy availability\n * cache, so hot paths pay the max latency of the slowest probe (or zero\n * when cached) instead of the sum of all probes.\n */\n private async getAvailableStrategies(ids?: SearchStrategyId[]): Promise<SearchStrategy[]> {\n const targetIds = ids ?? Array.from(this.strategies.keys())\n const candidates: SearchStrategy[] = []\n for (const id of targetIds) {\n const strategy = this.strategies.get(id)\n if (strategy) candidates.push(strategy)\n }\n\n const probes = await Promise.allSettled(\n candidates.map((strategy) => this.checkStrategyAvailability(strategy)),\n )\n\n const available: SearchStrategy[] = []\n for (let i = 0; i < probes.length; i++) {\n const probe = probes[i]\n if (probe.status === 'fulfilled' && probe.value) {\n available.push(candidates[i])\n }\n }\n\n return available.sort((a, b) => b.priority - a.priority)\n }\n\n /**\n * Execute search on a single strategy with error handling.\n */\n private async executeStrategySearch(\n strategy: SearchStrategy,\n query: string,\n options: SearchOptions,\n ): Promise<SearchResult[]> {\n await strategy.ensureReady()\n return strategy.search(query, options)\n }\n\n /**\n * Execute index on a single strategy with error handling.\n */\n private async executeStrategyIndex(\n strategy: SearchStrategy,\n record: IndexableRecord,\n ): Promise<void> {\n await strategy.ensureReady()\n return strategy.index(record)\n }\n\n /**\n * Execute delete on a single strategy with error handling.\n */\n private async executeStrategyDelete(\n strategy: SearchStrategy,\n entityId: string,\n recordId: string,\n tenantId: string,\n ): Promise<void> {\n await strategy.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AAAA,MAC3B,WAAW,IAAI,CAAC,aAAa,KAAK,0BAA0B,QAAQ,CAAC;AAAA,IACvE;AAEA,UAAM,YAA8B,CAAC;AACrC,aAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;AACtC,YAAM,QAAQ,OAAO,CAAC;AACtB,UAAI,MAAM,WAAW,eAAe,MAAM,OAAO;AAC/C,kBAAU,KAAK,WAAW,CAAC,CAAC;AAAA,MAC9B;AAAA,IACF;AAEA,WAAO,UAAU,KAAK,CAAC,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;AAAA,EACzD;AAAA;AAAA;AAAA;AAAA,EAKA,MAAc,sBACZ,UACA,OACA,SACyB;AACzB,UAAM,SAAS,YAAY;AAC3B,WAAO,SAAS,OAAO,OAAO,OAAO;AAAA,EACvC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAc,qBACZ,UACA,QACe;AACf,UAAM,SAAS,YAAY;AAC3B,WAAO,SAAS,MAAM,MAAM;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA,EAKA,MAAc,sBACZ,UACA,UACA,UACA,UACe;AACf,UAAM,SAAS,YAAY;AAC3B,WAAO,SAAS,OAAO,UAAU,UAAU,QAAQ;AAAA,EACrD;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -13,6 +13,7 @@ class FullTextSearchStrategy {
|
|
|
13
13
|
return this.driver.ensureReady();
|
|
14
14
|
}
|
|
15
15
|
async search(query, options) {
|
|
16
|
+
if (options.indexDocFilter) return [];
|
|
16
17
|
if (Array.isArray(options.organizationIds)) {
|
|
17
18
|
const organizationIds = options.organizationIds.map((value) => typeof value === "string" ? value.trim() : "").filter((value) => value.length > 0);
|
|
18
19
|
if (!options.organizationId && organizationIds.length === 0) return [];
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/strategies/fulltext.strategy.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n SearchStrategy,\n SearchStrategyId,\n SearchOptions,\n SearchResult,\n IndexableRecord,\n} from '../types'\nimport type { EntityId } from '@open-mercato/shared/modules/entities'\nimport type {\n FullTextSearchDriver,\n FullTextSearchDocument,\n FullTextSearchHit,\n DocumentLookupKey,\n ListDocumentIdsOptions,\n IndexStats,\n} from '../fulltext/types'\n\n/**\n * FullTextSearchStrategy provides full-text fuzzy search using a pluggable driver.\n * Default driver is Meilisearch, but can be swapped for Algolia, Elasticsearch, etc.\n */\nexport class FullTextSearchStrategy implements SearchStrategy {\n readonly id: SearchStrategyId = 'fulltext'\n readonly name = 'Full-Text Search'\n readonly priority = 30 // Highest priority when available\n\n constructor(private readonly driver: FullTextSearchDriver) {}\n\n async isAvailable(): Promise<boolean> {\n return this.driver.isHealthy()\n }\n\n async ensureReady(): Promise<void> {\n return this.driver.ensureReady()\n }\n\n async search(query: string, options: SearchOptions): Promise<SearchResult[]> {\n if (Array.isArray(options.organizationIds)) {\n const organizationIds = options.organizationIds\n .map((value) => (typeof value === 'string' ? value.trim() : ''))\n .filter((value) => value.length > 0)\n if (!options.organizationId && organizationIds.length === 0) return []\n }\n\n const hits = await this.driver.search(query, {\n tenantId: options.tenantId,\n organizationId: options.organizationId,\n organizationIds: options.organizationIds,\n entityTypes: options.entityTypes,\n limit: options.limit,\n offset: options.offset,\n })\n\n return hits.map((hit) => this.mapHitToResult(hit))\n }\n\n async index(record: IndexableRecord): Promise<void> {\n const doc = this.mapRecordToDocument(record)\n await this.driver.index(doc)\n }\n\n async delete(entityId: EntityId, recordId: string, tenantId: string): Promise<void> {\n return this.driver.delete(recordId, tenantId)\n }\n\n async bulkIndex(records: IndexableRecord[]): Promise<void> {\n if (!this.driver.bulkIndex) {\n // Fallback to sequential indexing\n for (const record of records) {\n await this.index(record)\n }\n return\n }\n\n const docs = records.map((record) => this.mapRecordToDocument(record))\n return this.driver.bulkIndex(docs)\n }\n\n async purge(entityId: EntityId, tenantId: string, organizationId?: string | null): Promise<void> {\n if (!this.driver.purge) {\n return\n }\n return this.driver.purge(entityId, tenantId, organizationId)\n }\n\n // Additional methods exposed for enrichment and admin purposes\n // These delegate to optional driver methods\n\n async clearIndex(tenantId: string): Promise<void> {\n if (!this.driver.clearIndex) {\n return\n }\n return this.driver.clearIndex(tenantId)\n }\n\n async recreateIndex(tenantId: string): Promise<void> {\n if (!this.driver.recreateIndex) {\n return\n }\n return this.driver.recreateIndex(tenantId)\n }\n\n async getDocuments(\n ids: DocumentLookupKey[],\n tenantId: string\n ): Promise<Map<string, SearchResult>> {\n if (!this.driver.getDocuments) {\n return new Map()\n }\n\n const hits = await this.driver.getDocuments(ids, tenantId)\n const result = new Map<string, SearchResult>()\n\n for (const [key, hit] of hits) {\n result.set(key, this.mapHitToResult(hit))\n }\n\n return result\n }\n\n async getIndexStats(tenantId: string): Promise<IndexStats | null> {\n if (!this.driver.getIndexStats) {\n return null\n }\n return this.driver.getIndexStats(tenantId)\n }\n\n async getEntityCounts(tenantId: string): Promise<Record<string, number> | null> {\n if (!this.driver.getEntityCounts) {\n return null\n }\n return this.driver.getEntityCounts(tenantId)\n }\n\n async listDocumentIds(\n entityId: EntityId,\n tenantId: string,\n options?: ListDocumentIdsOptions\n ): Promise<string[] | null> {\n if (!this.driver.listDocumentIds) {\n return null\n }\n return this.driver.listDocumentIds(entityId, tenantId, options)\n }\n\n get driverId(): string {\n return this.driver.id\n }\n\n private mapHitToResult(hit: FullTextSearchHit): SearchResult {\n return {\n entityId: hit.entityId,\n recordId: hit.recordId,\n score: hit.score,\n source: this.id,\n organizationId: hit.organizationId ?? null,\n presenter: hit.presenter,\n url: hit.url,\n links: hit.links,\n metadata: hit.metadata,\n }\n }\n\n private mapRecordToDocument(record: IndexableRecord): FullTextSearchDocument {\n return {\n recordId: record.recordId,\n entityId: record.entityId,\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n fields: record.fields,\n presenter: record.presenter,\n url: record.url,\n links: record.links,\n }\n }\n}\n"],
|
|
5
|
-
"mappings": "AA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,QAAI,CAAC,KAAK,OAAO,iBAAiB;AAChC,aAAO;AAAA,IACT;AACA,WAAO,KAAK,OAAO,gBAAgB,UAAU,UAAU,OAAO;AAAA,EAChE;AAAA,EAEA,IAAI,WAAmB;AACrB,WAAO,KAAK,OAAO;AAAA,EACrB;AAAA,EAEQ,eAAe,KAAsC;AAC3D,WAAO;AAAA,MACL,UAAU,IAAI;AAAA,MACd,UAAU,IAAI;AAAA,MACd,OAAO,IAAI;AAAA,MACX,QAAQ,KAAK;AAAA,MACb,gBAAgB,IAAI,kBAAkB;AAAA,MACtC,WAAW,IAAI;AAAA,MACf,KAAK,IAAI;AAAA,MACT,OAAO,IAAI;AAAA,MACX,UAAU,IAAI;AAAA,IAChB;AAAA,EACF;AAAA,EAEQ,oBAAoB,QAAiD;AAC3E,WAAO;AAAA,MACL,UAAU,OAAO;AAAA,MACjB,UAAU,OAAO;AAAA,MACjB,UAAU,OAAO;AAAA,MACjB,gBAAgB,OAAO;AAAA,MACvB,QAAQ,OAAO;AAAA,MACf,WAAW,OAAO;AAAA,MAClB,KAAK,OAAO;AAAA,MACZ,OAAO,OAAO;AAAA,IAChB;AAAA,EACF;AACF;",
|
|
4
|
+
"sourcesContent": ["import type {\n SearchStrategy,\n SearchStrategyId,\n SearchOptions,\n SearchResult,\n IndexableRecord,\n} from '../types'\nimport type { EntityId } from '@open-mercato/shared/modules/entities'\nimport type {\n FullTextSearchDriver,\n FullTextSearchDocument,\n FullTextSearchHit,\n DocumentLookupKey,\n ListDocumentIdsOptions,\n IndexStats,\n} from '../fulltext/types'\n\n/**\n * FullTextSearchStrategy provides full-text fuzzy search using a pluggable driver.\n * Default driver is Meilisearch, but can be swapped for Algolia, Elasticsearch, etc.\n */\nexport class FullTextSearchStrategy implements SearchStrategy {\n readonly id: SearchStrategyId = 'fulltext'\n readonly name = 'Full-Text Search'\n readonly priority = 30 // Highest priority when available\n\n constructor(private readonly driver: FullTextSearchDriver) {}\n\n async isAvailable(): Promise<boolean> {\n return this.driver.isHealthy()\n }\n\n async ensureReady(): Promise<void> {\n return this.driver.ensureReady()\n }\n\n async search(query: string, options: SearchOptions): Promise<SearchResult[]> {\n if (options.indexDocFilter) return []\n if (Array.isArray(options.organizationIds)) {\n const organizationIds = options.organizationIds\n .map((value) => (typeof value === 'string' ? value.trim() : ''))\n .filter((value) => value.length > 0)\n if (!options.organizationId && organizationIds.length === 0) return []\n }\n\n const hits = await this.driver.search(query, {\n tenantId: options.tenantId,\n organizationId: options.organizationId,\n organizationIds: options.organizationIds,\n entityTypes: options.entityTypes,\n limit: options.limit,\n offset: options.offset,\n })\n\n return hits.map((hit) => this.mapHitToResult(hit))\n }\n\n async index(record: IndexableRecord): Promise<void> {\n const doc = this.mapRecordToDocument(record)\n await this.driver.index(doc)\n }\n\n async delete(entityId: EntityId, recordId: string, tenantId: string): Promise<void> {\n return this.driver.delete(recordId, tenantId)\n }\n\n async bulkIndex(records: IndexableRecord[]): Promise<void> {\n if (!this.driver.bulkIndex) {\n // Fallback to sequential indexing\n for (const record of records) {\n await this.index(record)\n }\n return\n }\n\n const docs = records.map((record) => this.mapRecordToDocument(record))\n return this.driver.bulkIndex(docs)\n }\n\n async purge(entityId: EntityId, tenantId: string, organizationId?: string | null): Promise<void> {\n if (!this.driver.purge) {\n return\n }\n return this.driver.purge(entityId, tenantId, organizationId)\n }\n\n // Additional methods exposed for enrichment and admin purposes\n // These delegate to optional driver methods\n\n async clearIndex(tenantId: string): Promise<void> {\n if (!this.driver.clearIndex) {\n return\n }\n return this.driver.clearIndex(tenantId)\n }\n\n async recreateIndex(tenantId: string): Promise<void> {\n if (!this.driver.recreateIndex) {\n return\n }\n return this.driver.recreateIndex(tenantId)\n }\n\n async getDocuments(\n ids: DocumentLookupKey[],\n tenantId: string\n ): Promise<Map<string, SearchResult>> {\n if (!this.driver.getDocuments) {\n return new Map()\n }\n\n const hits = await this.driver.getDocuments(ids, tenantId)\n const result = new Map<string, SearchResult>()\n\n for (const [key, hit] of hits) {\n result.set(key, this.mapHitToResult(hit))\n }\n\n return result\n }\n\n async getIndexStats(tenantId: string): Promise<IndexStats | null> {\n if (!this.driver.getIndexStats) {\n return null\n }\n return this.driver.getIndexStats(tenantId)\n }\n\n async getEntityCounts(tenantId: string): Promise<Record<string, number> | null> {\n if (!this.driver.getEntityCounts) {\n return null\n }\n return this.driver.getEntityCounts(tenantId)\n }\n\n async listDocumentIds(\n entityId: EntityId,\n tenantId: string,\n options?: ListDocumentIdsOptions\n ): Promise<string[] | null> {\n if (!this.driver.listDocumentIds) {\n return null\n }\n return this.driver.listDocumentIds(entityId, tenantId, options)\n }\n\n get driverId(): string {\n return this.driver.id\n }\n\n private mapHitToResult(hit: FullTextSearchHit): SearchResult {\n return {\n entityId: hit.entityId,\n recordId: hit.recordId,\n score: hit.score,\n source: this.id,\n organizationId: hit.organizationId ?? null,\n presenter: hit.presenter,\n url: hit.url,\n links: hit.links,\n metadata: hit.metadata,\n }\n }\n\n private mapRecordToDocument(record: IndexableRecord): FullTextSearchDocument {\n return {\n recordId: record.recordId,\n entityId: record.entityId,\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n fields: record.fields,\n presenter: record.presenter,\n url: record.url,\n links: record.links,\n }\n }\n}\n"],
|
|
5
|
+
"mappings": "AAqBO,MAAM,uBAAiD;AAAA;AAAA,EAK5D,YAA6B,QAA8B;AAA9B;AAJ7B,SAAS,KAAuB;AAChC,SAAS,OAAO;AAChB,SAAS,WAAW;AAAA,EAEwC;AAAA,EAE5D,MAAM,cAAgC;AACpC,WAAO,KAAK,OAAO,UAAU;AAAA,EAC/B;AAAA,EAEA,MAAM,cAA6B;AACjC,WAAO,KAAK,OAAO,YAAY;AAAA,EACjC;AAAA,EAEA,MAAM,OAAO,OAAe,SAAiD;AAC3E,QAAI,QAAQ,eAAgB,QAAO,CAAC;AACpC,QAAI,MAAM,QAAQ,QAAQ,eAAe,GAAG;AAC1C,YAAM,kBAAkB,QAAQ,gBAC7B,IAAI,CAAC,UAAW,OAAO,UAA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AAA,MACX,UAAU,IAAI;AAAA,IAChB;AAAA,EACF;AAAA,EAEQ,oBAAoB,QAAiD;AAC3E,WAAO;AAAA,MACL,UAAU,OAAO;AAAA,MACjB,UAAU,OAAO;AAAA,MACjB,UAAU,OAAO;AAAA,MACjB,gBAAgB,OAAO;AAAA,MACvB,QAAQ,OAAO;AAAA,MACf,WAAW,OAAO;AAAA,MAClB,KAAK,OAAO;AAAA,MACZ,OAAO,OAAO;AAAA,IAChB;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/strategies/index.js
CHANGED
|
@@ -1,11 +1,21 @@
|
|
|
1
1
|
import { TokenSearchStrategy } from "./token.strategy.js";
|
|
2
2
|
import { VectorSearchStrategy } from "./vector.strategy.js";
|
|
3
3
|
import { FullTextSearchStrategy } from "./fulltext.strategy.js";
|
|
4
|
+
import {
|
|
5
|
+
buildIndexDocFilterExists,
|
|
6
|
+
buildIndexDocFilterPredicate,
|
|
7
|
+
compileIndexDocFilterExists,
|
|
8
|
+
INDEX_DOC_FILTER_ALIAS
|
|
9
|
+
} from "../lib/index-doc-filter.js";
|
|
4
10
|
import { createMeilisearchDriver, createFulltextDriver } from "../fulltext/drivers/index.js";
|
|
5
11
|
export {
|
|
6
12
|
FullTextSearchStrategy,
|
|
13
|
+
INDEX_DOC_FILTER_ALIAS,
|
|
7
14
|
TokenSearchStrategy,
|
|
8
15
|
VectorSearchStrategy,
|
|
16
|
+
buildIndexDocFilterExists,
|
|
17
|
+
buildIndexDocFilterPredicate,
|
|
18
|
+
compileIndexDocFilterExists,
|
|
9
19
|
createFulltextDriver,
|
|
10
20
|
createMeilisearchDriver
|
|
11
21
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/strategies/index.ts"],
|
|
4
|
-
"sourcesContent": ["export { TokenSearchStrategy, type TokenStrategyConfig } from './token.strategy'\nexport { VectorSearchStrategy, type VectorStrategyConfig, type EmbeddingService } from './vector.strategy'\nexport { FullTextSearchStrategy } from './fulltext.strategy'\n\n// Re-export fulltext driver types for convenience\nexport type {\n FullTextSearchDriver,\n FullTextSearchDriverId,\n FullTextSearchDocument,\n FullTextSearchQuery,\n FullTextSearchHit,\n FullTextSearchDriverConfig,\n DocumentLookupKey,\n IndexStats,\n} from '../fulltext/types'\nexport { createMeilisearchDriver, createFulltextDriver } from '../fulltext/drivers'\nexport type { MeilisearchDriverOptions } from '../fulltext/drivers/meilisearch'\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,2BAAqD;AAC9D,SAAS,4BAA8E;AACvF,SAAS,8BAA8B;
|
|
4
|
+
"sourcesContent": ["export { TokenSearchStrategy, type TokenStrategyConfig } from './token.strategy'\nexport { VectorSearchStrategy, type VectorStrategyConfig, type EmbeddingService } from './vector.strategy'\nexport { FullTextSearchStrategy } from './fulltext.strategy'\nexport {\n buildIndexDocFilterExists,\n buildIndexDocFilterPredicate,\n compileIndexDocFilterExists,\n INDEX_DOC_FILTER_ALIAS,\n type IndexDocFilterTarget,\n} from '../lib/index-doc-filter'\n\n// Re-export fulltext driver types for convenience\nexport type {\n FullTextSearchDriver,\n FullTextSearchDriverId,\n FullTextSearchDocument,\n FullTextSearchQuery,\n FullTextSearchHit,\n FullTextSearchDriverConfig,\n DocumentLookupKey,\n IndexStats,\n} from '../fulltext/types'\nexport { createMeilisearchDriver, createFulltextDriver } from '../fulltext/drivers'\nexport type { MeilisearchDriverOptions } from '../fulltext/drivers/meilisearch'\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,2BAAqD;AAC9D,SAAS,4BAA8E;AACvF,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAaP,SAAS,yBAAyB,4BAA4B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|