@open-mercato/search 0.10.1-develop.8024.1.02dbc16b49 → 0.10.1-develop.8026.1.a65d0b4a3f

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.
Files changed (28) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/search/__integration__/TC-SEARCH-015.spec.js +75 -0
  3. package/dist/modules/search/__integration__/TC-SEARCH-015.spec.js.map +7 -0
  4. package/dist/modules/search/api/embeddings/route.js +9 -6
  5. package/dist/modules/search/api/embeddings/route.js.map +2 -2
  6. package/dist/modules/search/api/settings/fulltext/route.js +5 -4
  7. package/dist/modules/search/api/settings/fulltext/route.js.map +2 -2
  8. package/dist/modules/search/i18n/de.json +10 -0
  9. package/dist/modules/search/i18n/en.json +10 -0
  10. package/dist/modules/search/i18n/es.json +10 -0
  11. package/dist/modules/search/i18n/ko.json +10 -0
  12. package/dist/modules/search/i18n/pl.json +10 -0
  13. package/dist/modules/search/lib/provider-diagnostics.js +30 -0
  14. package/dist/modules/search/lib/provider-diagnostics.js.map +7 -0
  15. package/dist/modules/search/lib/provider-probe.js +30 -9
  16. package/dist/modules/search/lib/provider-probe.js.map +2 -2
  17. package/package.json +4 -4
  18. package/src/modules/search/__integration__/TC-SEARCH-015.spec.ts +65 -0
  19. package/src/modules/search/api/__tests__/settings-diagnostics.routes.test.ts +166 -0
  20. package/src/modules/search/api/embeddings/route.ts +10 -5
  21. package/src/modules/search/api/settings/fulltext/route.ts +6 -4
  22. package/src/modules/search/i18n/de.json +10 -0
  23. package/src/modules/search/i18n/en.json +10 -0
  24. package/src/modules/search/i18n/es.json +10 -0
  25. package/src/modules/search/i18n/ko.json +10 -0
  26. package/src/modules/search/i18n/pl.json +10 -0
  27. package/src/modules/search/lib/provider-diagnostics.ts +33 -0
  28. package/src/modules/search/lib/provider-probe.ts +30 -8
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/search/lib/provider-probe.ts"],
4
- "sourcesContent": ["import type { CacheStrategy } from '@open-mercato/cache'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EmbeddingProviderId } from '../../../vector'\nimport { EMBEDDING_PROVIDERS } from '../../../vector'\nimport { safeOllamaFetch } from '../../../vector/lib/ollama-url-safety'\n\nconst CACHE_VERSION = 'v1'\nconst CACHE_TTL_MS = 30_000\nconst OLLAMA_PROBE_TIMEOUT_MS = 1500\n\nexport type ProviderAvailability = {\n available: boolean\n reason?: string\n models?: number\n}\n\nexport type ProviderAvailabilityEntry = ProviderAvailability & {\n providerId: EmbeddingProviderId\n}\n\nexport type EmbeddingProviderProbe = {\n checkAvailability(\n providerId: EmbeddingProviderId,\n options?: { force?: boolean; baseUrl?: string },\n ): Promise<ProviderAvailability>\n}\n\nconst ALL_PROVIDERS: EmbeddingProviderId[] = ['openai', 'google', 'mistral', 'cohere', 'bedrock', 'ollama']\n\nexport async function checkAllProviders(\n probe: EmbeddingProviderProbe,\n options?: { force?: boolean },\n): Promise<ProviderAvailabilityEntry[]> {\n return Promise.all(\n ALL_PROVIDERS.map(async (providerId) => ({\n providerId,\n ...(await probe.checkAvailability(providerId, options)),\n })),\n )\n}\n\nconst cacheKey = (providerId: string) => `embedding-provider-probe:${CACHE_VERSION}:${providerId}`\n\nconst resolveCache = (container: AppContainer): CacheStrategy | null => {\n try {\n return container.resolve('cache') as CacheStrategy\n } catch {\n return null\n }\n}\n\nconst ollamaBaseUrl = () => process.env.OLLAMA_BASE_URL?.trim() || 'http://localhost:11434'\n\nconst keyPresence = (providerId: EmbeddingProviderId): ProviderAvailability => {\n const info = EMBEDDING_PROVIDERS[providerId]\n const envKey = info?.envKeyRequired\n switch (providerId) {\n case 'openai':\n return process.env.OPENAI_API_KEY?.trim()\n ? { available: true }\n : { available: false, reason: `Set ${envKey} to enable ${info?.name ?? providerId}` }\n case 'google':\n return process.env.GOOGLE_GENERATIVE_AI_API_KEY?.trim()\n ? { available: true }\n : { available: false, reason: `Set ${envKey} to enable ${info?.name ?? providerId}` }\n case 'mistral':\n return process.env.MISTRAL_API_KEY?.trim()\n ? { available: true }\n : { available: false, reason: `Set ${envKey} to enable ${info?.name ?? providerId}` }\n case 'cohere':\n return process.env.COHERE_API_KEY?.trim()\n ? { available: true }\n : { available: false, reason: `Set ${envKey} to enable ${info?.name ?? providerId}` }\n case 'bedrock':\n return process.env.AWS_ACCESS_KEY_ID?.trim() && process.env.AWS_SECRET_ACCESS_KEY?.trim()\n ? { available: true }\n : { available: false, reason: 'Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to enable Bedrock' }\n default:\n return { available: false, reason: `Unknown provider: ${providerId}` }\n }\n}\n\nexport async function probeOllama(baseUrl: string): Promise<ProviderAvailability> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), OLLAMA_PROBE_TIMEOUT_MS)\n try {\n const response = await safeOllamaFetch(`${baseUrl.replace(/\\/$/, '')}/api/tags`, {\n method: 'GET',\n signal: controller.signal,\n })\n if (!response.ok) {\n return { available: false, reason: `Ollama responded ${response.status} at ${baseUrl}` }\n }\n let models: number | undefined\n try {\n const payload = (await response.json()) as { models?: unknown[] }\n if (Array.isArray(payload?.models)) models = payload.models.length\n } catch {}\n return { available: true, models }\n } catch (error) {\n const aborted = error instanceof Error && error.name === 'AbortError'\n return {\n available: false,\n reason: aborted ? `Ollama not reachable at ${baseUrl} (timed out)` : `Ollama not reachable at ${baseUrl}`,\n }\n } finally {\n clearTimeout(timer)\n }\n}\n\nasync function computeAvailability(\n providerId: EmbeddingProviderId,\n options?: { baseUrl?: string },\n): Promise<ProviderAvailability> {\n try {\n if (providerId === 'ollama') {\n return await probeOllama(options?.baseUrl?.trim() || ollamaBaseUrl())\n }\n return keyPresence(providerId)\n } catch (error) {\n // Fail closed: any unexpected error means the provider is treated as unavailable.\n return { available: false, reason: error instanceof Error ? error.message : 'Availability check failed' }\n }\n}\n\nexport function createEmbeddingProviderProbe(container: AppContainer): EmbeddingProviderProbe {\n const checkAvailability = async (\n providerId: EmbeddingProviderId,\n options?: { force?: boolean; baseUrl?: string },\n ): Promise<ProviderAvailability> => {\n const cache = resolveCache(container)\n const key = cacheKey(providerId)\n const probesCandidateUrl = providerId === 'ollama' && options?.baseUrl !== undefined\n if (!options?.force && !probesCandidateUrl && cache) {\n try {\n const cached = await cache.get(key)\n if (cached && typeof cached === 'object' && 'available' in cached) {\n return cached as ProviderAvailability\n }\n } catch {}\n }\n const result = await computeAvailability(providerId, options)\n if (cache && !probesCandidateUrl) {\n try {\n await cache.set(key, result, { ttl: CACHE_TTL_MS })\n } catch {}\n }\n return result\n }\n return { checkAvailability }\n}\n"],
5
- "mappings": "AAGA,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAEhC,MAAM,gBAAgB;AACtB,MAAM,eAAe;AACrB,MAAM,0BAA0B;AAmBhC,MAAM,gBAAuC,CAAC,UAAU,UAAU,WAAW,UAAU,WAAW,QAAQ;AAE1G,eAAsB,kBACpB,OACA,SACsC;AACtC,SAAO,QAAQ;AAAA,IACb,cAAc,IAAI,OAAO,gBAAgB;AAAA,MACvC;AAAA,MACA,GAAI,MAAM,MAAM,kBAAkB,YAAY,OAAO;AAAA,IACvD,EAAE;AAAA,EACJ;AACF;AAEA,MAAM,WAAW,CAAC,eAAuB,4BAA4B,aAAa,IAAI,UAAU;AAEhG,MAAM,eAAe,CAAC,cAAkD;AACtE,MAAI;AACF,WAAO,UAAU,QAAQ,OAAO;AAAA,EAClC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,MAAM,gBAAgB,MAAM,QAAQ,IAAI,iBAAiB,KAAK,KAAK;AAEnE,MAAM,cAAc,CAAC,eAA0D;AAC7E,QAAM,OAAO,oBAAoB,UAAU;AAC3C,QAAM,SAAS,MAAM;AACrB,UAAQ,YAAY;AAAA,IAClB,KAAK;AACH,aAAO,QAAQ,IAAI,gBAAgB,KAAK,IACpC,EAAE,WAAW,KAAK,IAClB,EAAE,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BAAkB;AAC7B;",
4
+ "sourcesContent": ["import type { CacheStrategy } from '@open-mercato/cache'\nimport type { AppContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EmbeddingProviderId } from '../../../vector'\nimport { EMBEDDING_PROVIDERS } from '../../../vector'\nimport { safeOllamaFetch } from '../../../vector/lib/ollama-url-safety'\n\nconst CACHE_VERSION = 'v2'\nconst CACHE_TTL_MS = 30_000\nconst OLLAMA_PROBE_TIMEOUT_MS = 1500\n\nexport type ProviderAvailability = {\n available: boolean\n reason?: string\n diagnostic?: { key: string; params?: Record<string, string | number> }\n models?: number\n}\n\nexport type ProviderAvailabilityEntry = ProviderAvailability & {\n providerId: EmbeddingProviderId\n}\n\nexport type EmbeddingProviderProbe = {\n checkAvailability(\n providerId: EmbeddingProviderId,\n options?: { force?: boolean; baseUrl?: string },\n ): Promise<ProviderAvailability>\n}\n\nconst ALL_PROVIDERS: EmbeddingProviderId[] = ['openai', 'google', 'mistral', 'cohere', 'bedrock', 'ollama']\n\nexport async function checkAllProviders(\n probe: EmbeddingProviderProbe,\n options?: { force?: boolean },\n): Promise<ProviderAvailabilityEntry[]> {\n return Promise.all(\n ALL_PROVIDERS.map(async (providerId) => ({\n providerId,\n ...(await probe.checkAvailability(providerId, options)),\n })),\n )\n}\n\nconst cacheKey = (providerId: string) => `embedding-provider-probe:${CACHE_VERSION}:${providerId}`\n\nconst resolveCache = (container: AppContainer): CacheStrategy | null => {\n try {\n return container.resolve('cache') as CacheStrategy\n } catch {\n return null\n }\n}\n\nconst ollamaBaseUrl = () => process.env.OLLAMA_BASE_URL?.trim() || 'http://localhost:11434'\n\nconst keyPresence = (providerId: EmbeddingProviderId): ProviderAvailability => {\n const info = EMBEDDING_PROVIDERS[providerId]\n const envKey = info?.envKeyRequired\n switch (providerId) {\n case 'openai':\n return process.env.OPENAI_API_KEY?.trim()\n ? { available: true }\n : {\n available: false,\n reason: `Set ${envKey} to enable ${info?.name ?? providerId}`,\n diagnostic: { key: 'missingKey', params: { envKey: envKey ?? '', provider: info?.name ?? providerId } },\n }\n case 'google':\n return process.env.GOOGLE_GENERATIVE_AI_API_KEY?.trim()\n ? { available: true }\n : {\n available: false,\n reason: `Set ${envKey} to enable ${info?.name ?? providerId}`,\n diagnostic: { key: 'missingKey', params: { envKey: envKey ?? '', provider: info?.name ?? providerId } },\n }\n case 'mistral':\n return process.env.MISTRAL_API_KEY?.trim()\n ? { available: true }\n : {\n available: false,\n reason: `Set ${envKey} to enable ${info?.name ?? providerId}`,\n diagnostic: { key: 'missingKey', params: { envKey: envKey ?? '', provider: info?.name ?? providerId } },\n }\n case 'cohere':\n return process.env.COHERE_API_KEY?.trim()\n ? { available: true }\n : {\n available: false,\n reason: `Set ${envKey} to enable ${info?.name ?? providerId}`,\n diagnostic: { key: 'missingKey', params: { envKey: envKey ?? '', provider: info?.name ?? providerId } },\n }\n case 'bedrock':\n return process.env.AWS_ACCESS_KEY_ID?.trim() && process.env.AWS_SECRET_ACCESS_KEY?.trim()\n ? { available: true }\n : {\n available: false,\n reason: 'Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to enable Bedrock',\n diagnostic: { key: 'missingKey', params: { envKey: 'AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY', provider: 'Bedrock' } },\n }\n default:\n return { available: false, reason: `Unknown provider: ${providerId}`, diagnostic: { key: 'unknownProvider', params: { provider: providerId } } }\n }\n}\n\nexport async function probeOllama(baseUrl: string): Promise<ProviderAvailability> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), OLLAMA_PROBE_TIMEOUT_MS)\n try {\n const response = await safeOllamaFetch(`${baseUrl.replace(/\\/$/, '')}/api/tags`, {\n method: 'GET',\n signal: controller.signal,\n })\n if (!response.ok) {\n return { available: false, reason: `Ollama responded ${response.status} at ${baseUrl}`, diagnostic: { key: 'ollamaResponse', params: { status: response.status, baseUrl } } }\n }\n let models: number | undefined\n try {\n const payload = (await response.json()) as { models?: unknown[] }\n if (Array.isArray(payload?.models)) models = payload.models.length\n } catch {}\n return { available: true, models }\n } catch (error) {\n const aborted = error instanceof Error && error.name === 'AbortError'\n return {\n available: false,\n reason: aborted ? `Ollama not reachable at ${baseUrl} (timed out)` : `Ollama not reachable at ${baseUrl}`,\n diagnostic: { key: aborted ? 'ollamaTimeout' : 'ollamaUnreachable', params: { baseUrl } },\n }\n } finally {\n clearTimeout(timer)\n }\n}\n\nasync function computeAvailability(\n providerId: EmbeddingProviderId,\n options?: { baseUrl?: string },\n): Promise<ProviderAvailability> {\n try {\n if (providerId === 'ollama') {\n return await probeOllama(options?.baseUrl?.trim() || ollamaBaseUrl())\n }\n return keyPresence(providerId)\n } catch (error) {\n // Fail closed: any unexpected error means the provider is treated as unavailable.\n return { available: false, reason: error instanceof Error ? error.message : 'Availability check failed' }\n }\n}\n\nexport function createEmbeddingProviderProbe(container: AppContainer): EmbeddingProviderProbe {\n const checkAvailability = async (\n providerId: EmbeddingProviderId,\n options?: { force?: boolean; baseUrl?: string },\n ): Promise<ProviderAvailability> => {\n const cache = resolveCache(container)\n const key = cacheKey(providerId)\n const probesCandidateUrl = providerId === 'ollama' && options?.baseUrl !== undefined\n if (!options?.force && !probesCandidateUrl && cache) {\n try {\n const cached = await cache.get(key)\n if (cached && typeof cached === 'object' && 'available' in cached) {\n return cached as ProviderAvailability\n }\n } catch {}\n }\n const result = await computeAvailability(providerId, options)\n if (cache && !probesCandidateUrl) {\n try {\n await cache.set(key, result, { ttl: CACHE_TTL_MS })\n } catch {}\n }\n return result\n }\n return { checkAvailability }\n}\n"],
5
+ "mappings": "AAGA,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAEhC,MAAM,gBAAgB;AACtB,MAAM,eAAe;AACrB,MAAM,0BAA0B;AAoBhC,MAAM,gBAAuC,CAAC,UAAU,UAAU,WAAW,UAAU,WAAW,QAAQ;AAE1G,eAAsB,kBACpB,OACA,SACsC;AACtC,SAAO,QAAQ;AAAA,IACb,cAAc,IAAI,OAAO,gBAAgB;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CAAC;AAAA,MACpD,QAAQ;AAAA,MAAC;AAAA,IACX;AACA,WAAO;AAAA,EACT;AACA,SAAO,EAAE,kBAAkB;AAC7B;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/search",
3
- "version": "0.10.1-develop.8024.1.02dbc16b49",
3
+ "version": "0.10.1-develop.8026.1.a65d0b4a3f",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -127,9 +127,9 @@
127
127
  "zod": "^4.6.6"
128
128
  },
129
129
  "peerDependencies": {
130
- "@open-mercato/core": "0.10.1-develop.8024.1.02dbc16b49",
131
- "@open-mercato/queue": "0.10.1-develop.8024.1.02dbc16b49",
132
- "@open-mercato/shared": "0.10.1-develop.8024.1.02dbc16b49"
130
+ "@open-mercato/core": "0.10.1-develop.8026.1.a65d0b4a3f",
131
+ "@open-mercato/queue": "0.10.1-develop.8026.1.a65d0b4a3f",
132
+ "@open-mercato/shared": "0.10.1-develop.8026.1.a65d0b4a3f"
133
133
  },
134
134
  "devDependencies": {
135
135
  "@types/jest": "^30.0.0",
@@ -0,0 +1,65 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { expect, test } from '@playwright/test'
3
+ import { getAuthToken } from '@open-mercato/core/helpers/integration/api'
4
+ import {
5
+ createRoleFixture, createUserFixture, deleteRoleIfExists, deleteUserIfExists, setRoleAclFeatures,
6
+ } from '@open-mercato/core/helpers/integration/authFixtures'
7
+ import { getTokenContext } from '@open-mercato/core/helpers/integration/generalFixtures'
8
+ import { acknowledgeGlobalNotices } from '@open-mercato/core/helpers/integration/auth'
9
+ import { createTranslator } from '@open-mercato/shared/lib/i18n/translate'
10
+ import { localizeProviderAvailability } from '../lib/provider-diagnostics'
11
+ import pl from '../i18n/pl.json' with { type: 'json' }
12
+
13
+ export const integrationMeta = { dependsOnModules: ['search', 'auth'] }
14
+
15
+ test('TC-SEARCH-015: Polish settings show environment hints and isolated unavailable-provider diagnostics', async ({ page, request, baseURL }) => {
16
+ test.setTimeout(120_000)
17
+ const token = await getAuthToken(request, 'admin')
18
+ const { organizationId } = getTokenContext(token)
19
+ const stamp = randomUUID()
20
+ const email = `search-diagnostics-${stamp}@example.com`
21
+ const password = `Search-015-${stamp}!`
22
+ let roleId: string | null = null
23
+ let userId: string | null = null
24
+ const translate = createTranslator(pl)
25
+ const missingKey = localizeProviderAvailability({
26
+ providerId: 'openai', available: false, reason: 'Set OPENAI_API_KEY to enable OpenAI',
27
+ diagnostic: { key: 'missingKey', params: { envKey: 'OPENAI_API_KEY', provider: 'OpenAI' } },
28
+ }, translate)
29
+ const unreachable = localizeProviderAvailability({
30
+ providerId: 'ollama', available: false, reason: 'Ollama not reachable',
31
+ diagnostic: { key: 'ollamaTimeout', params: { baseUrl: 'http://ollama.test:11434' } },
32
+ }, translate)
33
+ try {
34
+ roleId = await createRoleFixture(request, token, { name: `search-diagnostics-${stamp}` })
35
+ await setRoleAclFeatures(request, token, { roleId, features: ['search.view', 'search.embeddings.view'] })
36
+ userId = await createUserFixture(request, token, { email, password, organizationId, roles: [roleId] })
37
+ const login = await page.request.post('/api/auth/login', { form: { email, password } })
38
+ expect(login.ok()).toBeTruthy()
39
+ await acknowledgeGlobalNotices(page)
40
+ await page.context().addCookies([{ name: 'locale', value: 'pl', url: baseURL ?? 'http://localhost:3000' }])
41
+ await page.route('**/api/search/embeddings', async (route) => {
42
+ const response = await route.fetch()
43
+ expect(response.status()).toBe(200)
44
+ const body = await response.json()
45
+ await route.fulfill({ response, json: {
46
+ ...body,
47
+ settings: { ...body.settings, embeddingConfig: null, configuredProviders: [], providerAvailability: [missingKey, unreachable] },
48
+ } })
49
+ })
50
+ await page.goto('/backend/config/search')
51
+ for (const key of ['host', 'apiKey', 'indexPrefix', 'excludeEncrypted']) {
52
+ await expect(page.getByText(translate(`search.settings.fulltext.hints.${key}`), { exact: true })).toBeVisible()
53
+ }
54
+ await expect(page.getByText(missingKey.reason!, { exact: true })).toBeVisible()
55
+ await expect(page.getByText(unreachable.reason!, { exact: true })).toBeVisible()
56
+ await expect(page.getByRole('button', { name: /OpenAI/ })).toBeDisabled()
57
+ await expect(page.getByRole('button', { name: /Ollama/ })).toBeDisabled()
58
+ await expect(page.locator('body')).not.toContainText(/The URL of your|API key for authentication|Set OPENAI_API_KEY|Ollama not reachable|search\.settings\.(fulltext\.hints|providers\.diagnostics)/)
59
+ } finally {
60
+ await page.unroute('**/api/search/embeddings')
61
+ await page.context().clearCookies()
62
+ await deleteUserIfExists(request, token, userId)
63
+ await deleteRoleIfExists(request, token, roleId)
64
+ }
65
+ })
@@ -0,0 +1,166 @@
1
+ import { createTranslator } from '@open-mercato/shared/lib/i18n/translate'
2
+ import en from '../../i18n/en.json'
3
+ import pl from '../../i18n/pl.json'
4
+ import de from '../../i18n/de.json'
5
+ import es from '../../i18n/es.json'
6
+ import ko from '../../i18n/ko.json'
7
+
8
+ let mockLocale: keyof typeof mockDictionaries | undefined = 'pl'
9
+ const mockDictionaries = { en, pl, de, es, ko }
10
+ const mockAuth = jest.fn()
11
+ const mockContainer = jest.fn()
12
+ const mockProbe = jest.fn()
13
+ jest.mock('@open-mercato/shared/lib/auth/server', () => ({ getAuthFromRequest: () => mockAuth() }))
14
+ jest.mock('@open-mercato/shared/lib/di/container', () => ({ createRequestContainer: () => mockContainer() }))
15
+ jest.mock('next/headers', () => ({
16
+ cookies: async () => ({ get: () => mockLocale ? { value: mockLocale } : undefined }),
17
+ headers: async () => new Headers({ 'accept-language': 'pl-PL,pl;q=0.9,en;q=0.8' }),
18
+ }))
19
+ jest.mock('@open-mercato/shared/lib/i18n/app-dictionaries', () => ({
20
+ loadAppDictionary: async (locale: keyof typeof mockDictionaries) => mockDictionaries[locale],
21
+ }))
22
+ jest.mock('../../lib/embedding-config', () => ({
23
+ resolveEmbeddingConfigResult: async () => ({ config: null, source: 'env' }),
24
+ resolveEmbeddingConfig: async () => null,
25
+ getConfiguredProviders: () => ['ollama'],
26
+ getEffectiveDimension: () => 1536,
27
+ }))
28
+ jest.mock('../../lib/auto-indexing', () => ({
29
+ envDisablesAutoIndexing: () => false,
30
+ resolveAutoIndexingEnabled: async () => true,
31
+ }))
32
+
33
+ import { GET as fulltextGET } from '../settings/fulltext/route'
34
+ import { GET as embeddingsGET, POST as embeddingsPOST } from '../embeddings/route'
35
+ import { localizeProviderAvailability } from '../../lib/provider-diagnostics'
36
+ import { createEmbeddingProviderProbe } from '../../lib/provider-probe'
37
+ import type { AppContainer } from '@open-mercato/shared/lib/di/container'
38
+
39
+ const originalEnv = { ...process.env }
40
+ const req = () => new Request('http://localhost/api/search/settings/fulltext')
41
+
42
+ beforeEach(() => {
43
+ process.env = { ...originalEnv }
44
+ mockLocale = 'pl'
45
+ delete process.env.OM_FORCE_LOCALE
46
+ mockAuth.mockResolvedValue({ sub: 'user', tenantId: 'tenant', orgId: 'org' })
47
+ mockProbe.mockResolvedValue({ available: false, reason: 'internal English failure' })
48
+ mockContainer.mockResolvedValue({
49
+ resolve: (name: string) => {
50
+ if (name === 'embeddingProviderProbe') return { checkAvailability: mockProbe }
51
+ if (name === 'vectorDrivers') return []
52
+ if (name === 'moduleConfigService') return { setValue: jest.fn() }
53
+ throw new Error(`[internal] unexpected service ${name}`)
54
+ },
55
+ dispose: jest.fn(),
56
+ })
57
+ })
58
+ afterEach(() => { process.env = originalEnv; jest.restoreAllMocks() })
59
+
60
+ test.each(['en', 'pl', 'de', 'es', 'ko'] as const)('fulltext hints resolve the %s dictionary without changing the response shape', async (locale) => {
61
+ mockLocale = locale
62
+ process.env.MEILISEARCH_HOST = ' http://search.test:7700 '
63
+ process.env.MEILISEARCH_API_KEY = 'never-return-this-secret'
64
+ process.env.MEILISEARCH_INDEX_PREFIX = 'tenant'
65
+ process.env.SEARCH_EXCLUDE_ENCRYPTED_FIELDS = 'true'
66
+ const response = await fulltextGET(req())
67
+ expect(response.status).toBe(200)
68
+ expect(await response.json()).toEqual({
69
+ driver: 'meilisearch', configured: true,
70
+ envVars: {
71
+ MEILISEARCH_HOST: { set: true, hint: mockDictionaries[locale]['search.settings.fulltext.hints.host'] },
72
+ MEILISEARCH_API_KEY: { set: true, hint: mockDictionaries[locale]['search.settings.fulltext.hints.apiKey'] },
73
+ },
74
+ optionalEnvVars: {
75
+ MEILISEARCH_INDEX_PREFIX: { set: true, value: 'tenant', default: 'om', hint: mockDictionaries[locale]['search.settings.fulltext.hints.indexPrefix'] },
76
+ SEARCH_EXCLUDE_ENCRYPTED_FIELDS: { set: true, value: true, default: false, hint: mockDictionaries[locale]['search.settings.fulltext.hints.excludeEncrypted'] },
77
+ },
78
+ })
79
+ })
80
+
81
+ test('unconfigured fulltext retains booleans and omitted optional value', async () => {
82
+ for (const key of ['MEILISEARCH_HOST', 'MEILISEARCH_API_KEY', 'MEILISEARCH_INDEX_PREFIX', 'SEARCH_EXCLUDE_ENCRYPTED_FIELDS']) delete process.env[key]
83
+ const body = await (await fulltextGET(req())).json()
84
+ expect(body).toMatchObject({ driver: null, configured: false, envVars: { MEILISEARCH_HOST: { set: false }, MEILISEARCH_API_KEY: { set: false } } })
85
+ expect(body.optionalEnvVars.MEILISEARCH_INDEX_PREFIX).not.toHaveProperty('value')
86
+ })
87
+
88
+ test('authenticated routes reject anonymous requests', async () => {
89
+ mockAuth.mockResolvedValue(null)
90
+ expect((await fulltextGET(req())).status).toBe(401)
91
+ expect((await embeddingsGET(req())).status).toBe(401)
92
+ })
93
+
94
+ test('cached provider diagnostics translate per request and never leak internal metadata', async () => {
95
+ const cache = new Map<string, unknown>()
96
+ delete process.env.OPENAI_API_KEY
97
+ const probe = createEmbeddingProviderProbe({ resolve: () => ({
98
+ get: async (key: string) => cache.get(key),
99
+ set: async (key: string, value: unknown) => { cache.set(key, value) },
100
+ }) } as unknown as AppContainer)
101
+ mockProbe.mockImplementation((providerId: string) => providerId === 'openai'
102
+ ? probe.checkAvailability('openai')
103
+ : Promise.resolve({ available: true, models: 3 }))
104
+ for (const locale of ['en', 'pl', 'de', 'es', 'ko', 'pl'] as const) {
105
+ mockLocale = locale
106
+ const response = await embeddingsGET(req())
107
+ expect(response.status).toBe(200)
108
+ const { settings } = await response.json()
109
+ expect(Object.keys(settings).sort()).toEqual(['openaiConfigured', 'autoIndexingEnabled', 'autoIndexingLocked', 'lockReason', 'embeddingConfig', 'embeddingConfigSource', 'configuredProviders', 'providerAvailability', 'indexedDimension', 'reindexRequired', 'documentCount'].sort())
110
+ expect(settings.providerAvailability[0]).toEqual({ providerId: 'openai', available: false, reason: createTranslator(mockDictionaries[locale])('search.settings.providers.diagnostics.missingKey', { envKey: 'OPENAI_API_KEY', provider: 'OpenAI' }) })
111
+ expect(settings.providerAvailability[1]).toEqual({ providerId: 'google', available: true, models: 3 })
112
+ }
113
+ expect(cache.size).toBe(1)
114
+ expect([...cache.values()][0]).toMatchObject({ reason: 'Set OPENAI_API_KEY to enable OpenAI' })
115
+ })
116
+
117
+ test('provider save rejection localizes the reason without persisting settings', async () => {
118
+ const response = await embeddingsPOST(new Request('http://localhost/api/search/embeddings', {
119
+ method: 'POST', headers: { 'content-type': 'application/json' },
120
+ body: JSON.stringify({ embeddingConfig: { providerId: 'ollama', model: 'test', dimension: 1536 } }),
121
+ }))
122
+ expect(response.status).toBe(409)
123
+ expect(await response.json()).toEqual({ error: pl['search.api.errors.providerUnavailable'], reason: pl['search.settings.providers.diagnostics.unavailable'] })
124
+ })
125
+
126
+ test.each(['unknownProvider', 'ollamaResponse', 'ollamaTimeout', 'ollamaUnreachable', 'missingKey'] as const)('translates %s diagnostics in every supported locale', (key) => {
127
+ for (const dictionary of Object.values(mockDictionaries)) {
128
+ const t = createTranslator(dictionary)
129
+ const result = localizeProviderAvailability({ available: false, reason: 'English detail', diagnostic: { key, params: { provider: 'Ollama', envKey: 'KEY', status: 503, baseUrl: 'http://localhost:11434' } } }, t)
130
+ expect(result.reason).toBe(t(`search.settings.providers.diagnostics.${key}`, { provider: 'Ollama', envKey: 'KEY', status: 503, baseUrl: 'http://localhost:11434' }))
131
+ expect(result.reason).not.toMatch(/English detail|search\.settings|\{\w+\}/)
132
+ expect(result).not.toHaveProperty('diagnostic')
133
+ }
134
+ })
135
+
136
+ test('uses Accept-Language when no locale cookie is present', async () => {
137
+ mockLocale = undefined
138
+ const response = await fulltextGET(req())
139
+ expect((await response.json()).envVars.MEILISEARCH_HOST.hint).toBe(pl['search.settings.fulltext.hints.host'])
140
+ })
141
+
142
+ test.each([
143
+ ['google', 'GOOGLE_GENERATIVE_AI_API_KEY'], ['mistral', 'MISTRAL_API_KEY'], ['cohere', 'COHERE_API_KEY'],
144
+ ['bedrock', 'AWS_ACCESS_KEY_ID'],
145
+ ] as const)('the %s producer supplies translatable missing-credential diagnostics', async (provider, envKey) => {
146
+ delete process.env[envKey]
147
+ const probe = createEmbeddingProviderProbe({ resolve: () => { throw new Error('[internal] no cache') } } as unknown as AppContainer)
148
+ const result = localizeProviderAvailability(await probe.checkAvailability(provider), createTranslator(pl))
149
+ expect(result.available).toBe(false)
150
+ expect(result.reason).toMatch(/^Ustaw /)
151
+ expect(result.reason).toContain(envKey)
152
+ expect(result).not.toHaveProperty('diagnostic')
153
+ })
154
+
155
+ test.each(['response', 'timeout', 'unreachable'] as const)('the Ollama %s producer supplies localized API diagnostics', async (mode) => {
156
+ jest.spyOn(globalThis, 'fetch').mockImplementation(async () => {
157
+ if (mode === 'response') return new Response('', { status: 503 })
158
+ throw Object.assign(new Error('network error'), { name: mode === 'timeout' ? 'AbortError' : 'Error' })
159
+ })
160
+ const probe = createEmbeddingProviderProbe({ resolve: () => { throw new Error('[internal] no cache') } } as unknown as AppContainer)
161
+ const result = localizeProviderAvailability(await probe.checkAvailability('ollama', { baseUrl: 'http://localhost:11434' }), createTranslator(pl))
162
+ expect(result.available).toBe(false)
163
+ expect(result.reason).toMatch(mode === 'response' ? /zwróciła kod 503/ : /jest nieosiągalna/)
164
+ expect(result.reason).toContain('http://localhost:11434')
165
+ expect(result).not.toHaveProperty('diagnostic')
166
+ })
@@ -14,6 +14,8 @@ import {
14
14
  getEffectiveDimension,
15
15
  } from '../../lib/embedding-config'
16
16
  import type { EmbeddingConfigSource } from '../../lib/embedding-config'
17
+ import { localizeProviderAvailability } from '../../lib/provider-diagnostics'
18
+ import type { TranslateFn } from '@open-mercato/shared/lib/i18n/context'
17
19
  import { checkAllProviders } from '../../lib/provider-probe'
18
20
  import type { EmbeddingProviderProbe, ProviderAvailabilityEntry } from '../../lib/provider-probe'
19
21
  import { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'
@@ -84,11 +86,12 @@ function resolveProbe(container: { resolve: <T = unknown>(name: string) => T }):
84
86
 
85
87
  async function resolveProviderAvailability(
86
88
  container: { resolve: <T = unknown>(name: string) => T },
89
+ t: TranslateFn,
87
90
  ): Promise<ProviderAvailabilityEntry[]> {
88
91
  const probe = resolveProbe(container)
89
92
  if (!probe) return []
90
93
  try {
91
- return await checkAllProviders(probe)
94
+ return (await checkAllProviders(probe)).map((entry) => localizeProviderAvailability(entry, t))
92
95
  } catch {
93
96
  return []
94
97
  }
@@ -125,6 +128,7 @@ async function getVectorDocumentCount(
125
128
  }
126
129
 
127
130
  export async function GET(req: Request) {
131
+ const { t } = await resolveTranslations()
128
132
  const auth = await getAuthFromRequest(req)
129
133
  if (!auth?.sub) return await unauthorized()
130
134
 
@@ -144,7 +148,7 @@ export async function GET(req: Request) {
144
148
  scope: { tenantId: auth.tenantId },
145
149
  })
146
150
  const configuredProviders = getConfiguredProviders()
147
- const providerAvailability = await resolveProviderAvailability(container)
151
+ const providerAvailability = await resolveProviderAvailability(container, t)
148
152
  const indexedDimension = await getIndexedDimension(container)
149
153
 
150
154
  const effectiveDimension = embeddingConfig
@@ -276,13 +280,14 @@ export async function POST(req: Request) {
276
280
  : undefined,
277
281
  )
278
282
  if (!availability.available) {
283
+ const localized = localizeProviderAvailability(availability, t)
279
284
  return NextResponse.json(
280
285
  {
281
286
  error: t(
282
287
  'search.api.errors.providerUnavailable',
283
- `Provider ${providerInfo.name} is not available: ${availability.reason ?? 'unreachable'}`,
288
+ 'The selected provider is not available.',
284
289
  ),
285
- reason: availability.reason ?? null,
290
+ reason: localized.reason ?? null,
286
291
  },
287
292
  { status: 409 },
288
293
  )
@@ -370,7 +375,7 @@ export async function POST(req: Request) {
370
375
  embeddingConfig,
371
376
  embeddingConfigSource,
372
377
  configuredProviders: getConfiguredProviders(),
373
- providerAvailability: await resolveProviderAvailability(container),
378
+ providerAvailability: await resolveProviderAvailability(container, t),
374
379
  indexedDimension,
375
380
  reindexRequired,
376
381
  documentCount: updatedDocumentCount,
@@ -41,6 +41,8 @@ export async function GET(req: Request) {
41
41
  const auth = await getAuthFromRequest(req)
42
42
  if (!auth?.sub) return await unauthorized()
43
43
 
44
+ const { t } = await resolveTranslations()
45
+
44
46
  const hostSet = Boolean(process.env.MEILISEARCH_HOST?.trim())
45
47
  const apiKeySet = Boolean(process.env.MEILISEARCH_API_KEY?.trim())
46
48
  const configured = hostSet && apiKeySet
@@ -56,11 +58,11 @@ export async function GET(req: Request) {
56
58
  envVars: {
57
59
  MEILISEARCH_HOST: {
58
60
  set: hostSet,
59
- hint: 'The URL of your Meilisearch server (e.g., http://localhost:7700)',
61
+ hint: t('search.settings.fulltext.hints.host', 'The URL of your Meilisearch server (e.g., http://localhost:7700)'),
60
62
  },
61
63
  MEILISEARCH_API_KEY: {
62
64
  set: apiKeySet,
63
- hint: 'API key for authentication with Meilisearch',
65
+ hint: t('search.settings.fulltext.hints.apiKey', 'API key for authentication with Meilisearch'),
64
66
  },
65
67
  },
66
68
  optionalEnvVars: {
@@ -68,13 +70,13 @@ export async function GET(req: Request) {
68
70
  set: Boolean(indexPrefix),
69
71
  value: indexPrefix,
70
72
  default: 'om',
71
- hint: 'Prefix for index names to namespace indexes per tenant',
73
+ hint: t('search.settings.fulltext.hints.indexPrefix', 'Prefix for index names to namespace indexes per tenant'),
72
74
  },
73
75
  SEARCH_EXCLUDE_ENCRYPTED_FIELDS: {
74
76
  set: Boolean(process.env.SEARCH_EXCLUDE_ENCRYPTED_FIELDS),
75
77
  value: excludeEncrypted,
76
78
  default: false,
77
- hint: 'Exclude encrypted fields from full-text indexing for security',
79
+ hint: t('search.settings.fulltext.hints.excludeEncrypted', 'Exclude encrypted fields from full-text indexing for security'),
78
80
  },
79
81
  },
80
82
  }
@@ -142,6 +142,10 @@
142
142
  "search.settings.fulltext.envMissing": "Umgebungsvariable ist nicht gesetzt.",
143
143
  "search.settings.fulltext.envSet": "Umgebungsvariable ist gesetzt.",
144
144
  "search.settings.fulltext.envVars": "Umgebungsvariablen",
145
+ "search.settings.fulltext.hints.apiKey": "API-Schlüssel zur Authentifizierung bei Meilisearch",
146
+ "search.settings.fulltext.hints.excludeEncrypted": "Verschlüsselte Felder aus Sicherheitsgründen von der Volltextindexierung ausschließen",
147
+ "search.settings.fulltext.hints.host": "Die URL Ihres Meilisearch-Servers (z. B. http://localhost:7700)",
148
+ "search.settings.fulltext.hints.indexPrefix": "Präfix für Indexnamen zur Trennung der Indizes nach Mandant",
145
149
  "search.settings.fulltext.howTo": "Konfigurationsanleitung",
146
150
  "search.settings.fulltext.howToDescription": "Setzen Sie die erforderlichen Umgebungsvariablen für die Volltextsuche.",
147
151
  "search.settings.fulltext.learnMore": "Mehr erfahren",
@@ -180,6 +184,12 @@
180
184
  "search.settings.provider.label": "Anbieter",
181
185
  "search.settings.provider.notConfigured": "nicht konfiguriert",
182
186
  "search.settings.provider.title": "Embedding-Anbieter",
187
+ "search.settings.providers.diagnostics.missingKey": "Setzen Sie {envKey}, um {provider} zu aktivieren",
188
+ "search.settings.providers.diagnostics.ollamaResponse": "Ollama antwortete mit {status} unter {baseUrl}",
189
+ "search.settings.providers.diagnostics.ollamaTimeout": "Ollama ist unter {baseUrl} nicht erreichbar (Zeitüberschreitung)",
190
+ "search.settings.providers.diagnostics.ollamaUnreachable": "Ollama ist unter {baseUrl} nicht erreichbar",
191
+ "search.settings.providers.diagnostics.unavailable": "Die Verfügbarkeit des Anbieters konnte nicht geprüft werden",
192
+ "search.settings.providers.diagnostics.unknownProvider": "Unbekannter Anbieter: {provider}",
183
193
  "search.settings.recreateIndexDescription": "Suchindex-Struktur löschen und neu erstellen.",
184
194
  "search.settings.recreateIndexDialogDescription": "Der Suchindex wird gelöscht und neu erstellt.",
185
195
  "search.settings.recreateIndexDialogTitle": "Suchindex neu erstellen",
@@ -142,6 +142,10 @@
142
142
  "search.settings.fulltext.envMissing": "Environment variable is not set.",
143
143
  "search.settings.fulltext.envSet": "Environment variable is set.",
144
144
  "search.settings.fulltext.envVars": "Environment variables",
145
+ "search.settings.fulltext.hints.apiKey": "API key for authentication with Meilisearch",
146
+ "search.settings.fulltext.hints.excludeEncrypted": "Exclude encrypted fields from full-text indexing for security",
147
+ "search.settings.fulltext.hints.host": "The URL of your Meilisearch server (e.g., http://localhost:7700)",
148
+ "search.settings.fulltext.hints.indexPrefix": "Prefix for index names to namespace indexes per tenant",
145
149
  "search.settings.fulltext.howTo": "How to configure",
146
150
  "search.settings.fulltext.howToDescription": "Set the required environment variables to enable fulltext search.",
147
151
  "search.settings.fulltext.learnMore": "Learn more",
@@ -180,6 +184,12 @@
180
184
  "search.settings.provider.label": "Provider",
181
185
  "search.settings.provider.notConfigured": "not configured",
182
186
  "search.settings.provider.title": "Embedding Provider",
187
+ "search.settings.providers.diagnostics.missingKey": "Set {envKey} to enable {provider}",
188
+ "search.settings.providers.diagnostics.ollamaResponse": "Ollama responded {status} at {baseUrl}",
189
+ "search.settings.providers.diagnostics.ollamaTimeout": "Ollama not reachable at {baseUrl} (timed out)",
190
+ "search.settings.providers.diagnostics.ollamaUnreachable": "Ollama not reachable at {baseUrl}",
191
+ "search.settings.providers.diagnostics.unavailable": "Provider availability check failed",
192
+ "search.settings.providers.diagnostics.unknownProvider": "Unknown provider: {provider}",
183
193
  "search.settings.recreateIndexDescription": "Drop and recreate the search index structure.",
184
194
  "search.settings.recreateIndexDialogDescription": "This will drop and recreate the search index.",
185
195
  "search.settings.recreateIndexDialogTitle": "Recreate Search Index",
@@ -142,6 +142,10 @@
142
142
  "search.settings.fulltext.envMissing": "La variable de entorno no está configurada.",
143
143
  "search.settings.fulltext.envSet": "La variable de entorno está configurada.",
144
144
  "search.settings.fulltext.envVars": "Variables de entorno",
145
+ "search.settings.fulltext.hints.apiKey": "Clave API para autenticarse con Meilisearch",
146
+ "search.settings.fulltext.hints.excludeEncrypted": "Excluir los campos cifrados de la indexación de texto completo por seguridad",
147
+ "search.settings.fulltext.hints.host": "La URL de su servidor Meilisearch (p. ej., http://localhost:7700)",
148
+ "search.settings.fulltext.hints.indexPrefix": "Prefijo de los nombres de índices para separar los índices por inquilino",
145
149
  "search.settings.fulltext.howTo": "Cómo configurar",
146
150
  "search.settings.fulltext.howToDescription": "Configure las variables de entorno requeridas para habilitar la búsqueda de texto completo.",
147
151
  "search.settings.fulltext.learnMore": "Más información",
@@ -180,6 +184,12 @@
180
184
  "search.settings.provider.label": "Proveedor",
181
185
  "search.settings.provider.notConfigured": "no configurado",
182
186
  "search.settings.provider.title": "Proveedor de embeddings",
187
+ "search.settings.providers.diagnostics.missingKey": "Configure {envKey} para habilitar {provider}",
188
+ "search.settings.providers.diagnostics.ollamaResponse": "Ollama respondió con {status} en {baseUrl}",
189
+ "search.settings.providers.diagnostics.ollamaTimeout": "No se puede acceder a Ollama en {baseUrl} (tiempo de espera agotado)",
190
+ "search.settings.providers.diagnostics.ollamaUnreachable": "No se puede acceder a Ollama en {baseUrl}",
191
+ "search.settings.providers.diagnostics.unavailable": "No se pudo comprobar la disponibilidad del proveedor",
192
+ "search.settings.providers.diagnostics.unknownProvider": "Proveedor desconocido: {provider}",
183
193
  "search.settings.recreateIndexDescription": "Eliminar y recrear la estructura del índice de búsqueda.",
184
194
  "search.settings.recreateIndexDialogDescription": "Esto eliminará y recreará el índice de búsqueda.",
185
195
  "search.settings.recreateIndexDialogTitle": "Recrear índice de búsqueda",
@@ -142,6 +142,10 @@
142
142
  "search.settings.fulltext.envMissing": "환경 변수가 설정되지 않았습니다.",
143
143
  "search.settings.fulltext.envSet": "환경 변수가 설정되어 있습니다.",
144
144
  "search.settings.fulltext.envVars": "환경 변수",
145
+ "search.settings.fulltext.hints.apiKey": "Meilisearch 인증용 API 키",
146
+ "search.settings.fulltext.hints.excludeEncrypted": "보안을 위해 전체 텍스트 인덱싱에서 암호화된 필드 제외",
147
+ "search.settings.fulltext.hints.host": "Meilisearch 서버 URL (예: http://localhost:7700)",
148
+ "search.settings.fulltext.hints.indexPrefix": "테넌트별 인덱스를 구분하는 인덱스 이름 접두사",
145
149
  "search.settings.fulltext.howTo": "구성 방법",
146
150
  "search.settings.fulltext.howToDescription": "전체 텍스트 검색을 활성화하려면 필요한 환경 변수를 설정하세요.",
147
151
  "search.settings.fulltext.learnMore": "더 알아보기",
@@ -180,6 +184,12 @@
180
184
  "search.settings.provider.label": "제공업체",
181
185
  "search.settings.provider.notConfigured": "구성되지 않음",
182
186
  "search.settings.provider.title": "임베딩 제공업체",
187
+ "search.settings.providers.diagnostics.missingKey": "{provider}을(를) 활성화하려면 {envKey}을(를) 설정하세요",
188
+ "search.settings.providers.diagnostics.ollamaResponse": "{baseUrl}에서 Ollama가 {status} 상태로 응답했습니다",
189
+ "search.settings.providers.diagnostics.ollamaTimeout": "{baseUrl}에서 Ollama에 연결할 수 없습니다 (시간 초과)",
190
+ "search.settings.providers.diagnostics.ollamaUnreachable": "{baseUrl}에서 Ollama에 연결할 수 없습니다",
191
+ "search.settings.providers.diagnostics.unavailable": "제공업체의 가용성을 확인하지 못했습니다",
192
+ "search.settings.providers.diagnostics.unknownProvider": "알 수 없는 제공업체: {provider}",
183
193
  "search.settings.recreateIndexDescription": "검색 인덱스 구조를 삭제하고 다시 생성합니다.",
184
194
  "search.settings.recreateIndexDialogDescription": "검색 인덱스를 삭제하고 다시 생성합니다.",
185
195
  "search.settings.recreateIndexDialogTitle": "검색 인덱스 재생성",
@@ -142,6 +142,10 @@
142
142
  "search.settings.fulltext.envMissing": "Zmienna środowiskowa nie jest ustawiona.",
143
143
  "search.settings.fulltext.envSet": "Zmienna środowiskowa jest ustawiona.",
144
144
  "search.settings.fulltext.envVars": "Zmienne środowiskowe",
145
+ "search.settings.fulltext.hints.apiKey": "Klucz API do uwierzytelniania w Meilisearch",
146
+ "search.settings.fulltext.hints.excludeEncrypted": "Wyklucz zaszyfrowane pola z indeksowania pełnotekstowego ze względów bezpieczeństwa",
147
+ "search.settings.fulltext.hints.host": "Adres URL serwera Meilisearch (np. http://localhost:7700)",
148
+ "search.settings.fulltext.hints.indexPrefix": "Prefiks nazw indeksów oddzielający indeksy poszczególnych dzierżawców",
145
149
  "search.settings.fulltext.howTo": "Jak skonfigurować",
146
150
  "search.settings.fulltext.howToDescription": "Ustaw wymagane zmienne środowiskowe, aby włączyć wyszukiwanie pełnotekstowe.",
147
151
  "search.settings.fulltext.learnMore": "Dowiedz się więcej",
@@ -180,6 +184,12 @@
180
184
  "search.settings.provider.label": "Dostawca",
181
185
  "search.settings.provider.notConfigured": "nie skonfigurowany",
182
186
  "search.settings.provider.title": "Dostawca embeddingów",
187
+ "search.settings.providers.diagnostics.missingKey": "Ustaw {envKey}, aby włączyć dostawcę {provider}",
188
+ "search.settings.providers.diagnostics.ollamaResponse": "Ollama zwróciła kod {status} pod adresem {baseUrl}",
189
+ "search.settings.providers.diagnostics.ollamaTimeout": "Ollama jest nieosiągalna pod adresem {baseUrl} (przekroczono czas oczekiwania)",
190
+ "search.settings.providers.diagnostics.ollamaUnreachable": "Ollama jest nieosiągalna pod adresem {baseUrl}",
191
+ "search.settings.providers.diagnostics.unavailable": "Nie udało się sprawdzić dostępności dostawcy",
192
+ "search.settings.providers.diagnostics.unknownProvider": "Nieznany dostawca: {provider}",
183
193
  "search.settings.recreateIndexDescription": "Usuń i utwórz ponownie strukturę indeksu wyszukiwania.",
184
194
  "search.settings.recreateIndexDialogDescription": "Spowoduje to usunięcie i ponowne utworzenie indeksu wyszukiwania.",
185
195
  "search.settings.recreateIndexDialogTitle": "Utwórz ponownie indeks wyszukiwania",
@@ -0,0 +1,33 @@
1
+ import type { TranslateFn } from '@open-mercato/shared/lib/i18n/context'
2
+ import type { ProviderAvailability } from './provider-probe'
3
+
4
+ export function localizeProviderAvailability<Availability extends ProviderAvailability>(
5
+ availability: Availability,
6
+ t: TranslateFn,
7
+ ): Omit<Availability, 'diagnostic'> {
8
+ const { diagnostic, ...result } = availability
9
+ if (availability.available) return result
10
+
11
+ const params = diagnostic?.params
12
+ let reason: string
13
+ switch (diagnostic?.key) {
14
+ case 'missingKey':
15
+ reason = t('search.settings.providers.diagnostics.missingKey', 'Set {envKey} to enable {provider}', params)
16
+ break
17
+ case 'unknownProvider':
18
+ reason = t('search.settings.providers.diagnostics.unknownProvider', 'Unknown provider: {provider}', params)
19
+ break
20
+ case 'ollamaResponse':
21
+ reason = t('search.settings.providers.diagnostics.ollamaResponse', 'Ollama responded {status} at {baseUrl}', params)
22
+ break
23
+ case 'ollamaTimeout':
24
+ reason = t('search.settings.providers.diagnostics.ollamaTimeout', 'Ollama not reachable at {baseUrl} (timed out)', params)
25
+ break
26
+ case 'ollamaUnreachable':
27
+ reason = t('search.settings.providers.diagnostics.ollamaUnreachable', 'Ollama not reachable at {baseUrl}', params)
28
+ break
29
+ default:
30
+ reason = t('search.settings.providers.diagnostics.unavailable', 'Provider availability check failed')
31
+ }
32
+ return { ...result, reason }
33
+ }