/** * Tenant-scoped index lifecycle helper. * * `createSearchIndex` is the only sanctioned way to register a new index * with Meilisearch. It enforces the package-wide invariant: every index * MUST list `tenantId` as a filterable attribute, otherwise tenant * isolation cannot be guaranteed at read time. * * The helper is idempotent — calling it twice with the same schema is a * no-op (settings are re-applied; existing documents stay put). Domain * code is expected to call it during bootstrap before any indexing or * search happens. */ import type { IndexHandle, IndexSettingsInput, SearchClient, SearchDocument } from "./client.js"; import type { SearchIndexSchema } from "./schemas/index.js"; export class IndexSchemaValidationError extends Error { override readonly name = "IndexSchemaValidationError"; readonly code: "MISSING_TENANT_FILTER" | "EMPTY_PRIMARY_KEY" | "EMPTY_NAME" | "TENANT_FIELD_NOT_ALLOWED"; constructor(message: string, code: IndexSchemaValidationError["code"]) { super(message); this.code = code; } } export function validateIndexSchema(schema: SearchIndexSchema): void { if (!schema || typeof schema.name !== "string" || schema.name.length === 0) { throw new IndexSchemaValidationError("Search index schema requires a non-empty name.", "EMPTY_NAME"); } if (typeof schema.primaryKey !== "string" || schema.primaryKey.length === 0) { throw new IndexSchemaValidationError(`Search index "${schema.name}" must declare a non-empty primaryKey.`, "EMPTY_PRIMARY_KEY"); } if (!Array.isArray(schema.filterableAttributes) || !schema.filterableAttributes.includes("tenantId")) { throw new IndexSchemaValidationError( `Search index "${schema.name}" must list "tenantId" in filterableAttributes — tenant isolation depends on it.`, "MISSING_TENANT_FILTER" ); } if (!schema.allowedDocumentFields.includes("tenantId")) { throw new IndexSchemaValidationError( `Search index "${schema.name}" must list "tenantId" in allowedDocumentFields so the sanitizer keeps it.`, "TENANT_FIELD_NOT_ALLOWED" ); } } export interface CreateSearchIndexInput { readonly client: SearchClient; readonly schema: SearchIndexSchema; /** Optional overrides merged on top of the schema's settings. */ readonly settingsOverride?: Partial; } export interface ProvisionSearchIndexesInput { readonly client: SearchClient; readonly schemas: readonly SearchIndexSchema[]; } export async function createSearchIndex(input: CreateSearchIndexInput): Promise> { validateIndexSchema(input.schema); const settings = mergeSettings(input.schema, input.settingsOverride); const handle = input.client.index(input.schema.name); await handle.ensure({ primaryKey: input.schema.primaryKey, settings }); return handle; } /** * Provision the complete registry before a worker accepts jobs. Waiting for * every create/settings task keeps filtered tenant deletes from racing index * creation or the mandatory `tenantId` filter setting. */ export async function provisionSearchIndexes(input: ProvisionSearchIndexesInput): Promise { for (const schema of input.schemas) { await createSearchIndex({ client: input.client, schema }); } } function mergeSettings(schema: SearchIndexSchema, override: Partial | undefined): IndexSettingsInput { const base: IndexSettingsInput = { searchableAttributes: schema.searchableAttributes, filterableAttributes: schema.filterableAttributes, sortableAttributes: schema.sortableAttributes, ...(schema.rankingRules ? { rankingRules: schema.rankingRules } : {}), ...(schema.stopWords ? { stopWords: schema.stopWords } : {}), ...(schema.synonyms ? { synonyms: toMutableSynonyms(schema.synonyms) } : {}), }; if (!override) return base; return { ...base, ...(override.searchableAttributes ? { searchableAttributes: override.searchableAttributes } : {}), ...(override.filterableAttributes ? { filterableAttributes: override.filterableAttributes } : {}), ...(override.sortableAttributes ? { sortableAttributes: override.sortableAttributes } : {}), ...(override.rankingRules ? { rankingRules: override.rankingRules } : {}), ...(override.stopWords ? { stopWords: override.stopWords } : {}), ...(override.synonyms ? { synonyms: override.synonyms } : {}), }; } function toMutableSynonyms(synonyms: Record): Record { const out: Record = {}; for (const key of Object.keys(synonyms)) out[key] = synonyms[key]; return out; }