@open-mercato/core 0.7.1-develop.7180.1.9717fbbb43 → 0.7.1-develop.7182.1.789943f937

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.
@@ -1,4 +1,4 @@
1
- [build:core] found 4628 entry points
1
+ [build:core] found 4629 entry points
2
2
  [build:core] built successfully
3
3
  [build:core:generated] found 230 entry points
4
4
  [build:core:generated] built successfully
@@ -1,12 +1,16 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
- import { locales } from "@open-mercato/shared/lib/i18n/config";
4
- import { resolveForcedLocale } from "@open-mercato/shared/lib/i18n/locale";
3
+ import {
4
+ isSupportedLocale,
5
+ resolveSupportedLocalesForRequest
6
+ } from "@open-mercato/shared/lib/i18n/locale-registry";
7
+ import { resolveForcedLocale, resolveSupportedLocale } from "@open-mercato/shared/lib/i18n/locale";
5
8
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
6
9
  import { sanitizeRedirectPath } from "@open-mercato/core/modules/auth/lib/safeRedirect";
7
10
  import { getAppBaseUrl } from "@open-mercato/shared/lib/url";
8
- const supportedLocales = new Set(locales);
9
- const localeSchema = z.object({ locale: z.enum(locales) });
11
+ const localeSchema = z.object({
12
+ locale: z.string().refine(isSupportedLocale, { message: "Unsupported locale" }).describe("A locale code this tenant serves \u2014 one of the `servable` entries returned by `GET /api/translations/locales`. Codes are canonicalized (`de-AT` \u2192 `de`).")
13
+ });
10
14
  const localeQuerySchema = localeSchema.extend({
11
15
  redirect: z.string().optional()
12
16
  });
@@ -16,6 +20,10 @@ const metadata = {
16
20
  GET: { requireAuth: false },
17
21
  POST: { requireAuth: false }
18
22
  };
23
+ async function resolveLocaleForRequest(value) {
24
+ if (typeof value !== "string") return null;
25
+ return resolveSupportedLocale(value, await resolveSupportedLocalesForRequest());
26
+ }
19
27
  async function POST(req) {
20
28
  const { t } = await resolveTranslations();
21
29
  if (resolveForcedLocale(process.env)) {
@@ -23,11 +31,12 @@ async function POST(req) {
23
31
  }
24
32
  try {
25
33
  const { locale } = await req.json();
26
- if (typeof locale !== "string" || !supportedLocales.has(locale)) {
34
+ const resolved = await resolveLocaleForRequest(locale);
35
+ if (!resolved) {
27
36
  return NextResponse.json({ error: t("api.errors.invalidLocale", "Invalid locale") }, { status: 400 });
28
37
  }
29
38
  const res = NextResponse.json({ ok: true });
30
- res.cookies.set("locale", locale, { path: "/", maxAge: 60 * 60 * 24 * 365 });
39
+ res.cookies.set("locale", resolved, { path: "/", maxAge: 60 * 60 * 24 * 365 });
31
40
  return res;
32
41
  } catch {
33
42
  return NextResponse.json({ error: t("api.errors.badRequest", "Bad request") }, { status: 400 });
@@ -39,14 +48,14 @@ async function GET(req) {
39
48
  return NextResponse.json({ error: t("api.errors.localeForced", "Locale is fixed by configuration") }, { status: 409 });
40
49
  }
41
50
  const url = new URL(req.url);
42
- const locale = url.searchParams.get("locale");
43
- if (!locale || !supportedLocales.has(locale)) {
51
+ const resolved = await resolveLocaleForRequest(url.searchParams.get("locale"));
52
+ if (!resolved) {
44
53
  return NextResponse.json({ error: t("api.errors.invalidLocale", "Invalid locale") }, { status: 400 });
45
54
  }
46
55
  const baseUrl = getAppBaseUrl(req);
47
56
  const safePath = sanitizeRedirectPath(url.searchParams.get("redirect"), baseUrl, "/");
48
57
  const res = NextResponse.redirect(new URL(safePath, url.origin));
49
- res.cookies.set("locale", locale, { path: "/", maxAge: 60 * 60 * 24 * 365 });
58
+ res.cookies.set("locale", resolved, { path: "/", maxAge: 60 * 60 * 24 * 365 });
50
59
  return res;
51
60
  }
52
61
  const openApi = {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/auth/api/locale/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { locales, type Locale } from '@open-mercato/shared/lib/i18n/config'\nimport { resolveForcedLocale } from '@open-mercato/shared/lib/i18n/locale'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { sanitizeRedirectPath } from '@open-mercato/core/modules/auth/lib/safeRedirect'\nimport { getAppBaseUrl } from '@open-mercato/shared/lib/url'\n\nconst supportedLocales = new Set<Locale>(locales)\nconst localeSchema = z.object({ locale: z.enum(locales as [Locale, ...Locale[]]) })\nconst localeQuerySchema = localeSchema.extend({\n redirect: z.string().optional(),\n})\nconst localeResponseSchema = z.object({ ok: z.boolean() })\nconst localeErrorSchema = z.object({ error: z.string() })\n\nexport const metadata = {\n GET: { requireAuth: false },\n POST: { requireAuth: false },\n}\n\nexport async function POST(req: Request) {\n const { t } = await resolveTranslations()\n if (resolveForcedLocale(process.env)) {\n return NextResponse.json({ error: t('api.errors.localeForced', 'Locale is fixed by configuration') }, { status: 409 })\n }\n try {\n const { locale } = await req.json()\n if (typeof locale !== 'string' || !supportedLocales.has(locale as Locale)) {\n return NextResponse.json({ error: t('api.errors.invalidLocale', 'Invalid locale') }, { status: 400 })\n }\n const res = NextResponse.json({ ok: true })\n res.cookies.set('locale', locale as Locale, { path: '/', maxAge: 60 * 60 * 24 * 365 })\n return res\n } catch {\n return NextResponse.json({ error: t('api.errors.badRequest', 'Bad request') }, { status: 400 })\n }\n}\n\nexport async function GET(req: Request) {\n const { t } = await resolveTranslations()\n if (resolveForcedLocale(process.env)) {\n return NextResponse.json({ error: t('api.errors.localeForced', 'Locale is fixed by configuration') }, { status: 409 })\n }\n const url = new URL(req.url)\n const locale = url.searchParams.get('locale')\n if (!locale || !supportedLocales.has(locale as Locale)) {\n return NextResponse.json({ error: t('api.errors.invalidLocale', 'Invalid locale') }, { status: 400 })\n }\n const baseUrl = getAppBaseUrl(req)\n const safePath = sanitizeRedirectPath(url.searchParams.get('redirect'), baseUrl, '/')\n const res = NextResponse.redirect(new URL(safePath, url.origin))\n res.cookies.set('locale', locale as Locale, { path: '/', maxAge: 60 * 60 * 24 * 365 })\n return res\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Locale preference',\n methods: {\n GET: {\n summary: 'Set locale and redirect',\n description: 'Stores the selected locale in a cookie and redirects to a safe local path.',\n query: localeQuerySchema,\n responses: [\n { status: 302, description: 'Locale cookie set and request redirected' },\n { status: 400, description: 'Invalid locale', schema: localeErrorSchema },\n ],\n },\n POST: {\n summary: 'Set locale',\n description: 'Stores the selected locale in a cookie and returns a JSON success response.',\n requestBody: {\n contentType: 'application/json',\n schema: localeSchema,\n },\n responses: [\n { status: 200, description: 'Locale cookie set', schema: localeResponseSchema },\n { status: 400, description: 'Invalid locale or malformed request body', schema: localeErrorSchema },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,eAA4B;AACrC,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AACpC,SAAS,4BAA4B;AACrC,SAAS,qBAAqB;AAE9B,MAAM,mBAAmB,IAAI,IAAY,OAAO;AAChD,MAAM,eAAe,EAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,OAAgC,EAAE,CAAC;AAClF,MAAM,oBAAoB,aAAa,OAAO;AAAA,EAC5C,UAAU,EAAE,OAAO,EAAE,SAAS;AAChC,CAAC;AACD,MAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;AACzD,MAAM,oBAAoB,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;AAEjD,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM;AAAA,EAC1B,MAAM,EAAE,aAAa,MAAM;AAC7B;AAEA,eAAsB,KAAK,KAAc;AACvC,QAAM,EAAE,EAAE,IAAI,MAAM,oBAAoB;AACxC,MAAI,oBAAoB,QAAQ,GAAG,GAAG;AACpC,WAAO,aAAa,KAAK,EAAE,OAAO,EAAE,2BAA2B,kCAAkC,EAAE,GAAG,EAAE,QAAQ,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,QAAQ,KAAK,KAAK,KAAK,IAAI,CAAC;AACrF,SAAO;AACT;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,OAAO;AAAA,MACP,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,2CAA2C;AAAA,QACvE,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,kBAAkB;AAAA,MAC1E;AAAA,IACF;AAAA,IACA,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa;AAAA,MACb,aAAa;AAAA,QACX,aAAa;AAAA,QACb,QAAQ;AAAA,MACV;AAAA,MACA,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,qBAAqB;AAAA,QAC9E,EAAE,QAAQ,KAAK,aAAa,4CAA4C,QAAQ,kBAAkB;AAAA,MACpG;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport {\n isSupportedLocale,\n resolveSupportedLocalesForRequest,\n} from '@open-mercato/shared/lib/i18n/locale-registry'\nimport { resolveForcedLocale, resolveSupportedLocale } from '@open-mercato/shared/lib/i18n/locale'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { sanitizeRedirectPath } from '@open-mercato/core/modules/auth/lib/safeRedirect'\nimport { getAppBaseUrl } from '@open-mercato/shared/lib/url'\n\n// Resolved per request, not at module scope: an app or tenant may register a\n// locale after this module is first imported, and a snapshot taken at import\n// time would reject it for the lifetime of the process.\n//\n// This costs the generated OpenAPI its `enum` of valid values, which a closed\n// `z.enum(locales)` used to give for free. That is the honest documentation now\n// rather than a regression: the accepted set is per-tenant (see\n// `resolveLocaleForRequest` below), so any static list published in a spec\n// shared by every tenant would be wrong for most of them. The description points\n// at the endpoint that answers the question for the caller's own tenant.\nconst localeSchema = z.object({\n locale: z\n .string()\n .refine(isSupportedLocale, { message: 'Unsupported locale' })\n .describe('A locale code this tenant serves \u2014 one of the `servable` entries returned by `GET /api/translations/locales`. Codes are canonicalized (`de-AT` \u2192 `de`).'),\n})\nconst localeQuerySchema = localeSchema.extend({\n redirect: z.string().optional(),\n})\nconst localeResponseSchema = z.object({ ok: z.boolean() })\nconst localeErrorSchema = z.object({ error: z.string() })\n\nexport const metadata = {\n GET: { requireAuth: false },\n POST: { requireAuth: false },\n}\n\n// Both handlers write the `locale` cookie, and `detectLocale` later reads it back\n// against the *request's* served set \u2014 the tenant's selection, not the\n// process-wide registry. Validating against the wider set would make a locale the\n// tenant has not selected return 200 (or 302) and set a year-long cookie that\n// every subsequent render silently discards, so the caller is told the change\n// took effect and nothing ever changes.\nasync function resolveLocaleForRequest(value: unknown) {\n if (typeof value !== 'string') return null\n // Resolve rather than merely validate: the cookie must hold the canonical\n // code the registry stores (`pt-BR` \u2192 `pt-br`, `cs-CZ` \u2192 `cs`), because\n // `detectLocale` compares it against the served set verbatim.\n return resolveSupportedLocale(value, await resolveSupportedLocalesForRequest())\n}\n\nexport async function POST(req: Request) {\n const { t } = await resolveTranslations()\n if (resolveForcedLocale(process.env)) {\n return NextResponse.json({ error: t('api.errors.localeForced', 'Locale is fixed by configuration') }, { status: 409 })\n }\n try {\n const { locale } = await req.json()\n const resolved = await resolveLocaleForRequest(locale)\n if (!resolved) {\n return NextResponse.json({ error: t('api.errors.invalidLocale', 'Invalid locale') }, { status: 400 })\n }\n const res = NextResponse.json({ ok: true })\n res.cookies.set('locale', resolved, { path: '/', maxAge: 60 * 60 * 24 * 365 })\n return res\n } catch {\n return NextResponse.json({ error: t('api.errors.badRequest', 'Bad request') }, { status: 400 })\n }\n}\n\nexport async function GET(req: Request) {\n const { t } = await resolveTranslations()\n if (resolveForcedLocale(process.env)) {\n return NextResponse.json({ error: t('api.errors.localeForced', 'Locale is fixed by configuration') }, { status: 409 })\n }\n const url = new URL(req.url)\n const resolved = await resolveLocaleForRequest(url.searchParams.get('locale'))\n if (!resolved) {\n return NextResponse.json({ error: t('api.errors.invalidLocale', 'Invalid locale') }, { status: 400 })\n }\n const baseUrl = getAppBaseUrl(req)\n const safePath = sanitizeRedirectPath(url.searchParams.get('redirect'), baseUrl, '/')\n const res = NextResponse.redirect(new URL(safePath, url.origin))\n res.cookies.set('locale', resolved, { path: '/', maxAge: 60 * 60 * 24 * 365 })\n return res\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Authentication & Accounts',\n summary: 'Locale preference',\n methods: {\n GET: {\n summary: 'Set locale and redirect',\n description: 'Stores the selected locale in a cookie and redirects to a safe local path.',\n query: localeQuerySchema,\n responses: [\n { status: 302, description: 'Locale cookie set and request redirected' },\n { status: 400, description: 'Invalid locale', schema: localeErrorSchema },\n ],\n },\n POST: {\n summary: 'Set locale',\n description: 'Stores the selected locale in a cookie and returns a JSON success response.',\n requestBody: {\n contentType: 'application/json',\n schema: localeSchema,\n },\n responses: [\n { status: 200, description: 'Locale cookie set', schema: localeResponseSchema },\n { status: 400, description: 'Invalid locale or malformed request body', schema: localeErrorSchema },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB,8BAA8B;AAC5D,SAAS,2BAA2B;AACpC,SAAS,4BAA4B;AACrC,SAAS,qBAAqB;AAY9B,MAAM,eAAe,EAAE,OAAO;AAAA,EAC5B,QAAQ,EACL,OAAO,EACP,OAAO,mBAAmB,EAAE,SAAS,qBAAqB,CAAC,EAC3D,SAAS,mKAAyJ;AACvK,CAAC;AACD,MAAM,oBAAoB,aAAa,OAAO;AAAA,EAC5C,UAAU,EAAE,OAAO,EAAE,SAAS;AAChC,CAAC;AACD,MAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ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CAAC;AAAA,EACvH;AACA,QAAM,MAAM,IAAI,IAAI,IAAI,GAAG;AAC3B,QAAM,WAAW,MAAM,wBAAwB,IAAI,aAAa,IAAI,QAAQ,CAAC;AAC7E,MAAI,CAAC,UAAU;AACb,WAAO,aAAa,KAAK,EAAE,OAAO,EAAE,4BAA4B,gBAAgB,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACtG;AACA,QAAM,UAAU,cAAc,GAAG;AACjC,QAAM,WAAW,qBAAqB,IAAI,aAAa,IAAI,UAAU,GAAG,SAAS,GAAG;AACpF,QAAM,MAAM,aAAa,SAAS,IAAI,IAAI,UAAU,IAAI,MAAM,CAAC;AAC/D,MAAI,QAAQ,IAAI,UAAU,UAAU,EAAE,MAAM,KAAK,QAAQ,KAAK,KAAK,KAAK,IAAI,CAAC;AAC7E,SAAO;AACT;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,OAAO;AAAA,MACP,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,2CAA2C;AAAA,QACvE,EAAE,QAAQ,KAAK,aAAa,kBAAkB,QAAQ,kBAAkB;AAAA,MAC1E;AAAA,IACF;AAAA,IACA,MAAM;AAAA,MACJ,SAAS;AAAA,MACT,aAAa;AAAA,MACb,aAAa;AAAA,QACX,aAAa;AAAA,QACb,QAAQ;AAAA,MACV;AAAA,MACA,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,qBAAqB,QAAQ,qBAAqB;AAAA,QAC9E,EAAE,QAAQ,KAAK,aAAa,4CAA4C,QAAQ,kBAAkB;AAAA,MACpG;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -3,6 +3,7 @@ import { z } from "zod";
3
3
  import { resolveTranslationsRouteContext } from "@open-mercato/core/modules/translations/api/context";
4
4
  import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
5
5
  import { locales as defaultLocales } from "@open-mercato/shared/lib/i18n/config";
6
+ import { getSupportedLocales } from "@open-mercato/shared/lib/i18n/locale-set";
6
7
  import { createLogger } from "@open-mercato/shared/lib/logger";
7
8
  const logger = createLogger("translations").child({ component: "locales" });
8
9
  const metadata = {
@@ -17,7 +18,10 @@ async function GET(req) {
17
18
  defaultValue: [...defaultLocales],
18
19
  scope: { tenantId: context.tenantId }
19
20
  });
20
- return NextResponse.json({ locales: Array.isArray(locales) ? locales : [...defaultLocales] });
21
+ return NextResponse.json({
22
+ locales: Array.isArray(locales) ? locales : [...defaultLocales],
23
+ servable: [...getSupportedLocales()]
24
+ });
21
25
  } catch (err) {
22
26
  if (isCrudHttpError(err)) {
23
27
  return NextResponse.json(err.body, { status: err.status });
@@ -27,7 +31,8 @@ async function GET(req) {
27
31
  }
28
32
  }
29
33
  const responseSchema = z.object({
30
- locales: z.array(z.string())
34
+ locales: z.array(z.string()),
35
+ servable: z.array(z.string())
31
36
  });
32
37
  const getDoc = {
33
38
  summary: "List supported translation locales",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/translations/api/get/locales.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { resolveTranslationsRouteContext } from '@open-mercato/core/modules/translations/api/context'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { locales as defaultLocales } from '@open-mercato/shared/lib/i18n/config'\nimport type { ModuleConfigService } from '@open-mercato/core/modules/configs/lib/module-config-service'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('translations').child({ component: 'locales' })\n\nexport const metadata = {\n path: '/translations/locales',\n GET: { requireAuth: true, requireFeatures: ['translations.view'] },\n}\n\nasync function GET(req: Request) {\n try {\n const context = await resolveTranslationsRouteContext(req)\n\n const configService = context.container.resolve('moduleConfigService') as ModuleConfigService\n const locales = await configService.getValue<string[]>('translations', 'supported_locales', {\n defaultValue: [...defaultLocales],\n scope: { tenantId: context.tenantId },\n })\n\n return NextResponse.json({ locales: Array.isArray(locales) ? locales : [...defaultLocales] })\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n logger.error('Failed to load locales', { err })\n return NextResponse.json({ error: 'Internal server error' }, { status: 500 })\n }\n}\n\nconst responseSchema = z.object({\n locales: z.array(z.string()),\n})\n\nconst getDoc: OpenApiMethodDoc = {\n summary: 'List supported translation locales',\n tags: ['Translations'],\n responses: [\n { status: 200, description: 'Supported locales list', schema: responseSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Translations',\n summary: 'List supported translation locales',\n methods: {\n GET: getDoc,\n },\n}\n\nexport default GET\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,uCAAuC;AAChD,SAAwB,uBAAuB;AAC/C,SAAS,WAAW,sBAAsB;AAG1C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,cAAc,EAAE,MAAM,EAAE,WAAW,UAAU,CAAC;AAEnE,MAAM,WAAW;AAAA,EACtB,MAAM;AAAA,EACN,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,mBAAmB,EAAE;AACnE;AAEA,eAAe,IAAI,KAAc;AAC/B,MAAI;AACF,UAAM,UAAU,MAAM,gCAAgC,GAAG;AAEzD,UAAM,gBAAgB,QAAQ,UAAU,QAAQ,qBAAqB;AACrE,UAAM,UAAU,MAAM,cAAc,SAAmB,gBAAgB,qBAAqB;AAAA,MAC1F,cAAc,CAAC,GAAG,cAAc;AAAA,MAChC,OAAO,EAAE,UAAU,QAAQ,SAAS;AAAA,IACtC,CAAC;AAED,WAAO,aAAa,KAAK,EAAE,SAAS,MAAM,QAAQ,OAAO,IAAI,UAAU,CAAC,GAAG,cAAc,EAAE,CAAC;AAAA,EAC9F,SAAS,KAAK;AACZ,QAAI,gBAAgB,GAAG,GAAG;AACxB,aAAO,aAAa,KAAK,IAAI,MAAM,EAAE,QAAQ,IAAI,OAAO,CAAC;AAAA,IAC3D;AACA,WAAO,MAAM,0BAA0B,EAAE,IAAI,CAAC;AAC9C,WAAO,aAAa,KAAK,EAAE,OAAO,wBAAwB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC9E;AACF;AAEA,MAAM,iBAAiB,EAAE,OAAO;AAAA,EAC9B,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC;AAC7B,CAAC;AAED,MAAM,SAA2B;AAAA,EAC/B,SAAS;AAAA,EACT,MAAM,CAAC,cAAc;AAAA,EACrB,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,eAAe;AAAA,EAC/E;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,EACP;AACF;AAEA,IAAO,kBAAQ;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { resolveTranslationsRouteContext } from '@open-mercato/core/modules/translations/api/context'\nimport { CrudHttpError, isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { locales as defaultLocales } from '@open-mercato/shared/lib/i18n/config'\nimport { getSupportedLocales } from '@open-mercato/shared/lib/i18n/locale-set'\nimport type { ModuleConfigService } from '@open-mercato/core/modules/configs/lib/module-config-service'\nimport type { OpenApiMethodDoc, OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('translations').child({ component: 'locales' })\n\nexport const metadata = {\n path: '/translations/locales',\n GET: { requireAuth: true, requireFeatures: ['translations.view'] },\n}\n\nasync function GET(req: Request) {\n try {\n const context = await resolveTranslationsRouteContext(req)\n\n const configService = context.container.resolve('moduleConfigService') as ModuleConfigService\n const locales = await configService.getValue<string[]>('translations', 'supported_locales', {\n defaultValue: [...defaultLocales],\n scope: { tenantId: context.tenantId },\n })\n\n // `servable` is what the application can actually render its own UI in\n // (platform baseline plus app-registered locales). The stored selection also\n // drives the content-translation editor, which accepts any ISO 639-1 code, so\n // the two sets differ and the settings screen has to be able to tell them\n // apart before it claims a locale was added to the UI language set.\n return NextResponse.json({\n locales: Array.isArray(locales) ? locales : [...defaultLocales],\n servable: [...getSupportedLocales()],\n })\n } catch (err) {\n if (isCrudHttpError(err)) {\n return NextResponse.json(err.body, { status: err.status })\n }\n logger.error('Failed to load locales', { err })\n return NextResponse.json({ error: 'Internal server error' }, { status: 500 })\n }\n}\n\nconst responseSchema = z.object({\n locales: z.array(z.string()),\n servable: z.array(z.string()),\n})\n\nconst getDoc: OpenApiMethodDoc = {\n summary: 'List supported translation locales',\n tags: ['Translations'],\n responses: [\n { status: 200, description: 'Supported locales list', schema: responseSchema },\n ],\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Translations',\n summary: 'List supported translation locales',\n methods: {\n GET: getDoc,\n },\n}\n\nexport default GET\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,uCAAuC;AAChD,SAAwB,uBAAuB;AAC/C,SAAS,WAAW,sBAAsB;AAC1C,SAAS,2BAA2B;AAGpC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,cAAc,EAAE,MAAM,EAAE,WAAW,UAAU,CAAC;AAEnE,MAAM,WAAW;AAAA,EACtB,MAAM;AAAA,EACN,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,mBAAmB,EAAE;AACnE;AAEA,eAAe,IAAI,KAAc;AAC/B,MAAI;AACF,UAAM,UAAU,MAAM,gCAAgC,GAAG;AAEzD,UAAM,gBAAgB,QAAQ,UAAU,QAAQ,qBAAqB;AACrE,UAAM,UAAU,MAAM,cAAc,SAAmB,gBAAgB,qBAAqB;AAAA,MAC1F,cAAc,CAAC,GAAG,cAAc;AAAA,MAChC,OAAO,EAAE,UAAU,QAAQ,SAAS;AAAA,IACtC,CAAC;AAOD,WAAO,aAAa,KAAK;AAAA,MACvB,SAAS,MAAM,QAAQ,OAAO,IAAI,UAAU,CAAC,GAAG,cAAc;AAAA,MAC9D,UAAU,CAAC,GAAG,oBAAoB,CAAC;AAAA,IACrC,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,QAAI,gBAAgB,GAAG,GAAG;AACxB,aAAO,aAAa,KAAK,IAAI,MAAM,EAAE,QAAQ,IAAI,OAAO,CAAC;AAAA,IAC3D;AACA,WAAO,MAAM,0BAA0B,EAAE,IAAI,CAAC;AAC9C,WAAO,aAAa,KAAK,EAAE,OAAO,wBAAwB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC9E;AACF;AAEA,MAAM,iBAAiB,EAAE,OAAO;AAAA,EAC9B,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC;AAAA,EAC3B,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC;AAC9B,CAAC;AAED,MAAM,SAA2B;AAAA,EAC/B,SAAS;AAAA,EACT,MAAM,CAAC,cAAc;AAAA,EACrB,WAAW;AAAA,IACT,EAAE,QAAQ,KAAK,aAAa,0BAA0B,QAAQ,eAAe;AAAA,EAC/E;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,EACP;AACF;AAEA,IAAO,kBAAQ;",
6
6
  "names": []
7
7
  }
@@ -4,6 +4,7 @@ import * as React from "react";
4
4
  import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
5
5
  import { Button } from "@open-mercato/ui/primitives/button";
6
6
  import { IconButton } from "@open-mercato/ui/primitives/icon-button";
7
+ import { Badge } from "@open-mercato/ui/primitives/badge";
7
8
  import { Tabs, TabsList, TabsTrigger } from "@open-mercato/ui/primitives/tabs";
8
9
  import { Input } from "@open-mercato/ui/primitives/input";
9
10
  import { ComboboxInput } from "@open-mercato/ui/backend/inputs";
@@ -17,7 +18,7 @@ import { useCustomFieldDefs } from "@open-mercato/ui/backend/utils/customFieldDe
17
18
  import { Save, Plus, X } from "lucide-react";
18
19
  import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
19
20
  import { useT } from "@open-mercato/shared/lib/i18n/context";
20
- import { locales as defaultLocales } from "@open-mercato/shared/lib/i18n/config";
21
+ import { defaultLocale, locales as defaultLocales } from "@open-mercato/shared/lib/i18n/config";
21
22
  import { ISO_639_1, isValidIso639, getIso639Label } from "@open-mercato/shared/lib/i18n/iso639";
22
23
  import { formatEntityLabel, buildEntityListUrl, getRecordLabel, resolveBaseValue } from "../lib/helpers.js";
23
24
  import { resolveFieldList } from "../lib/resolve-field-list.js";
@@ -30,8 +31,11 @@ function useTranslationLocales() {
30
31
  queryKey: ["translation-locales"],
31
32
  queryFn: async () => {
32
33
  const res = await apiCall("/api/translations/locales");
33
- if (!res.ok) return [...defaultLocales];
34
- return Array.isArray(res.result?.locales) && res.result.locales.length > 0 ? res.result.locales : [...defaultLocales];
34
+ const fallback = { locales: [...defaultLocales], servable: [...defaultLocales] };
35
+ if (!res.ok) return fallback;
36
+ const locales = Array.isArray(res.result?.locales) && res.result.locales.length > 0 ? res.result.locales : [...defaultLocales];
37
+ const servable = Array.isArray(res.result?.servable) && res.result.servable.length > 0 ? res.result.servable : [...defaultLocales];
38
+ return { locales, servable };
35
39
  },
36
40
  staleTime: 6e4
37
41
  });
@@ -56,7 +60,8 @@ function TranslationManager({
56
60
  const hasUserEditedRef = React.useRef(false);
57
61
  const entityType = isEmbedded ? propEntityType ?? "" : selectedEntityType;
58
62
  const recordId = isEmbedded ? propRecordId ?? "" : selectedRecordId;
59
- const { data: locales = [...defaultLocales] } = useTranslationLocales();
63
+ const { data: localeData } = useTranslationLocales();
64
+ const locales = React.useMemo(() => localeData?.locales ?? [...defaultLocales], [localeData]);
60
65
  React.useEffect(() => {
61
66
  if (locales.length > 0 && (!activeLocale || !locales.includes(activeLocale))) {
62
67
  setActiveLocale(locales[0]);
@@ -427,7 +432,9 @@ function TranslationManager({
427
432
  function LocaleManager() {
428
433
  const t = useT();
429
434
  const queryClient = useQueryClient();
430
- const { data: locales = [], isLoading } = useTranslationLocales();
435
+ const { data: localeData, isLoading } = useTranslationLocales();
436
+ const locales = React.useMemo(() => localeData?.locales ?? [], [localeData]);
437
+ const servable = React.useMemo(() => localeData?.servable ?? [], [localeData]);
431
438
  const [newLocale, setNewLocale] = React.useState("");
432
439
  const { runMutation, retryLastMutation } = useGuardedMutation({ contextId: SUPPORTED_LOCALES_MUTATION_CONTEXT_ID });
433
440
  const mutation = useMutation({
@@ -451,18 +458,32 @@ function LocaleManager() {
451
458
  });
452
459
  },
453
460
  onSuccess: (result) => {
454
- queryClient.setQueryData(["translation-locales"], result);
461
+ const previous = queryClient.getQueryData(["translation-locales"]);
462
+ if (previous) {
463
+ queryClient.setQueryData(["translation-locales"], { ...previous, locales: result });
464
+ } else {
465
+ void queryClient.invalidateQueries({ queryKey: ["translation-locales"] });
466
+ }
455
467
  flash(t("translations.locales.flash.saved", "Locales updated"), "success");
456
468
  },
457
469
  onError: () => {
458
470
  flash(t("translations.locales.flash.error", "Failed to update locales"), "error");
459
471
  }
460
472
  });
473
+ const contentOnlyLabel = t("translations.locales.contentOnly", "Content only");
474
+ const isServable = React.useCallback(
475
+ (code) => servable.includes(code.toLowerCase()),
476
+ [servable]
477
+ );
461
478
  const availableLocales = React.useMemo(
462
479
  () => ISO_639_1.filter((entry) => !locales.includes(entry.code)).map((entry) => ({
463
480
  value: entry.code,
464
- label: `${entry.code.toUpperCase()} \u2014 ${entry.label}`
481
+ label: isServable(entry.code) ? `${entry.code.toUpperCase()} \u2014 ${entry.label}` : `${entry.code.toUpperCase()} \u2014 ${entry.label} (${contentOnlyLabel})`
465
482
  })),
483
+ [locales, isServable, contentOnlyLabel]
484
+ );
485
+ const chips = React.useMemo(
486
+ () => locales.includes(defaultLocale) ? locales : [defaultLocale, ...locales],
466
487
  [locales]
467
488
  );
468
489
  const addLocale = () => {
@@ -473,6 +494,7 @@ function LocaleManager() {
473
494
  };
474
495
  const removeLocale = (locale) => {
475
496
  if (locales.length <= 1) return;
497
+ if (locale === defaultLocale) return;
476
498
  mutation.mutate(locales.filter((l) => l !== locale));
477
499
  };
478
500
  if (isLoading) {
@@ -481,44 +503,57 @@ function LocaleManager() {
481
503
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 rounded-lg border bg-card p-4 shadow-sm", children: [
482
504
  /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
483
505
  /* @__PURE__ */ jsx("h3", { className: "text-lg font-semibold", children: t("translations.locales.title", "Supported locales") }),
484
- /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("translations.locales.description", "Configure which locales are available for translations. Add ISO language codes (e.g. fr, it, ja, zh).") })
506
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("translations.locales.description", "Which languages content can be translated into. A language the application ships an interface for is also offered in the admin language switcher; the rest are available for content only.") })
485
507
  ] }),
486
- /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: locales.map((locale) => /* @__PURE__ */ jsxs(
487
- "span",
488
- {
489
- className: "inline-flex items-center gap-1.5 rounded-full border bg-muted/50 px-3 py-1 text-sm font-medium",
490
- title: getIso639Label(locale) ?? locale,
491
- children: [
492
- locale.toUpperCase(),
493
- getIso639Label(locale) ? ` \u2014 ${getIso639Label(locale)}` : "",
494
- locales.length > 1 && /* @__PURE__ */ jsx(
495
- IconButton,
496
- {
497
- variant: "ghost",
498
- size: "xs",
499
- fullRadius: true,
500
- "aria-label": t("translations.locales.remove", "Remove {{locale}}", { locale: getIso639Label(locale) ?? locale.toUpperCase() }),
501
- title: t("translations.locales.remove", "Remove {{locale}}", { locale: getIso639Label(locale) ?? locale.toUpperCase() }),
502
- onClick: () => removeLocale(locale),
503
- disabled: mutation.isPending,
504
- children: /* @__PURE__ */ jsx(X, { className: "h-3 w-3" })
505
- }
506
- )
507
- ]
508
- },
509
- locale
510
- )) }),
508
+ /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: chips.map((locale) => {
509
+ const localeLabel = getIso639Label(locale) ?? locale.toUpperCase();
510
+ const isDefault = locale === defaultLocale;
511
+ const isStored = locales.includes(locale);
512
+ const removeLabel = t("translations.locales.remove", "Remove {{locale}}", { locale: localeLabel });
513
+ const defaultLabel = t(
514
+ "translations.locales.alwaysServed",
515
+ "{{locale}} is the default language and is always served, so it cannot be removed.",
516
+ { locale: localeLabel }
517
+ );
518
+ return /* @__PURE__ */ jsxs(
519
+ "span",
520
+ {
521
+ className: "inline-flex items-center gap-1.5 rounded-full border bg-muted/50 px-3 py-1 text-sm font-medium",
522
+ title: isStored ? getIso639Label(locale) ?? locale : defaultLabel,
523
+ children: [
524
+ locale.toUpperCase(),
525
+ getIso639Label(locale) ? ` \u2014 ${getIso639Label(locale)}` : "",
526
+ !isServable(locale) && /* @__PURE__ */ jsx(Badge, { variant: "outline", size: "sm", title: t("translations.locales.contentOnlyHint", "The application ships no interface for this language, so it is available for content translations only."), children: contentOnlyLabel }),
527
+ isStored && locales.length > 1 && /* @__PURE__ */ jsx(
528
+ IconButton,
529
+ {
530
+ variant: "ghost",
531
+ size: "xs",
532
+ fullRadius: true,
533
+ "aria-label": isDefault ? defaultLabel : removeLabel,
534
+ title: isDefault ? defaultLabel : removeLabel,
535
+ onClick: () => removeLocale(locale),
536
+ disabled: mutation.isPending || isDefault,
537
+ children: /* @__PURE__ */ jsx(X, { className: "h-3 w-3" })
538
+ }
539
+ )
540
+ ]
541
+ },
542
+ locale
543
+ );
544
+ }) }),
511
545
  /* @__PURE__ */ jsxs("div", { className: "flex gap-2 items-center", children: [
512
546
  /* @__PURE__ */ jsx("div", { className: "max-w-[240px] flex-1", children: /* @__PURE__ */ jsx(
513
547
  ComboboxInput,
514
548
  {
515
549
  value: newLocale,
516
550
  onChange: setNewLocale,
517
- placeholder: t("translations.locales.addPlaceholder", "Search language..."),
551
+ placeholder: t("translations.locales.addPlaceholder", "e.g. fr, it, ja..."),
518
552
  suggestions: availableLocales,
519
553
  resolveLabel: (value) => {
520
554
  const label = getIso639Label(value);
521
- return label ? `${value.toUpperCase()} \u2014 ${label}` : value.toUpperCase();
555
+ const base = label ? `${value.toUpperCase()} \u2014 ${label}` : value.toUpperCase();
556
+ return isServable(value) ? base : `${base} (${contentOnlyLabel})`;
522
557
  }
523
558
  }
524
559
  ) }),
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/translations/components/TranslationManager.tsx"],
4
- "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { IconButton } from '@open-mercato/ui/primitives/icon-button'\nimport { Tabs, TabsList, TabsTrigger } from '@open-mercato/ui/primitives/tabs'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { ComboboxInput } from '@open-mercato/ui/backend/inputs'\nimport { LoadingMessage, ErrorMessage } from '@open-mercato/ui/backend/detail'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { apiCall, readApiResultOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { useCustomFieldDefs } from '@open-mercato/ui/backend/utils/customFieldDefs'\nimport { Save, Plus, X } from 'lucide-react'\nimport { useOrganizationScopeVersion } from '@open-mercato/shared/lib/frontend/useOrganizationScope'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { locales as defaultLocales } from '@open-mercato/shared/lib/i18n/config'\nimport { ISO_639_1, isValidIso639, getIso639Label } from '@open-mercato/shared/lib/i18n/iso639'\nimport { formatEntityLabel, buildEntityListUrl, getRecordLabel, resolveBaseValue } from '../lib/helpers'\nimport { resolveFieldList } from '../lib/resolve-field-list'\nimport type { ResolvedField } from '../lib/resolve-field-list'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('translations').child({ component: 'TranslationManager' })\n\nconst TRANSLATION_MUTATION_CONTEXT_ID = 'translations.entity-translations'\nconst SUPPORTED_LOCALES_MUTATION_CONTEXT_ID = 'translations.supported-locales'\n\ntype TranslationManagerProps = {\n entityType?: string\n recordId?: string\n baseValues?: Record<string, unknown>\n translatableFields?: string[]\n mode?: 'standalone' | 'embedded'\n compact?: boolean\n}\n\ntype EntityOption = { entityId: string; label?: string; source?: string }\n\ntype TranslationsResponse = {\n entityType: string\n entityId: string\n translations: Record<string, Record<string, unknown>>\n createdAt?: string\n updatedAt?: string\n}\n\nfunction useTranslationLocales() {\n return useQuery<string[]>({\n queryKey: ['translation-locales'],\n queryFn: async () => {\n const res = await apiCall<{ locales: string[] }>('/api/translations/locales')\n if (!res.ok) return [...defaultLocales]\n return Array.isArray(res.result?.locales) && res.result.locales.length > 0\n ? res.result.locales\n : [...defaultLocales]\n },\n staleTime: 60_000,\n })\n}\n\nexport function TranslationManager({\n entityType: propEntityType,\n recordId: propRecordId,\n baseValues: propBaseValues,\n translatableFields: propTranslatableFields,\n mode = 'standalone',\n compact = false,\n}: TranslationManagerProps) {\n const t = useT()\n const scopeVersion = useOrganizationScopeVersion()\n const isEmbedded = mode === 'embedded'\n\n const [selectedEntityType, setSelectedEntityType] = React.useState(propEntityType ?? '')\n const [selectedRecordId, setSelectedRecordId] = React.useState(propRecordId ?? '')\n const [activeLocale, setActiveLocale] = React.useState('')\n const [editedTranslations, setEditedTranslations] = React.useState<Record<string, Record<string, string>>>({})\n const editedTranslationsRef = React.useRef<Record<string, Record<string, string>>>({})\n const [hasUserEdited, setHasUserEdited] = React.useState(false)\n const hasUserEditedRef = React.useRef(false)\n\n const entityType = isEmbedded ? (propEntityType ?? '') : selectedEntityType\n const recordId = isEmbedded ? (propRecordId ?? '') : selectedRecordId\n\n const { data: locales = [...defaultLocales] } = useTranslationLocales()\n\n React.useEffect(() => {\n if (locales.length > 0 && (!activeLocale || !locales.includes(activeLocale))) {\n setActiveLocale(locales[0])\n }\n }, [locales, activeLocale])\n\n React.useEffect(() => {\n if (isEmbedded && propEntityType) setSelectedEntityType(propEntityType)\n }, [isEmbedded, propEntityType])\n\n React.useEffect(() => {\n if (isEmbedded && propRecordId) setSelectedRecordId(propRecordId)\n }, [isEmbedded, propRecordId])\n\n const { data: entities, isLoading: loadingEntities, error: entitiesError } = useQuery<{ items: EntityOption[] }>({\n queryKey: ['entities-list', scopeVersion],\n enabled: !isEmbedded,\n queryFn: async () =>\n readApiResultOrThrow('/api/entities/entities', undefined, {\n errorMessage: t('translations.manager.errors.loadEntities', 'Failed to load entities'),\n }),\n })\n\n const entitySuggestions = React.useMemo(\n () =>\n (entities?.items || []).map((item) => ({\n value: item.entityId,\n label: formatEntityLabel(item.entityId, item.label),\n description: item.entityId,\n })),\n [entities],\n )\n\n const resolveEntityLabel = React.useCallback(\n (value: string) => {\n const match = entities?.items?.find((e) => e.entityId === value)\n return match ? formatEntityLabel(match.entityId, match.label) : formatEntityLabel(value)\n },\n [entities],\n )\n\n const listUrl = React.useMemo(() => entityType ? buildEntityListUrl(entityType) : null, [entityType])\n\n const loadRecordSuggestions = React.useCallback(\n async (query?: string) => {\n if (!entityType || !listUrl) return []\n const url = `${listUrl}?pageSize=20${query ? `&search=${encodeURIComponent(query)}` : ''}`\n const res = await apiCall<{ items: Array<Record<string, unknown>> }>(url)\n if (!res.ok) return []\n const items = res.result?.items ?? []\n return items.map((item) => ({\n value: String(item.id ?? ''),\n label: getRecordLabel(item),\n }))\n },\n [entityType, listUrl],\n )\n\n const { data: recordData } = useQuery<Record<string, unknown> | null>({\n queryKey: ['translation-record-data', entityType, recordId, listUrl, scopeVersion],\n enabled: !isEmbedded && !!entityType && !!recordId && !!listUrl,\n queryFn: async () => {\n const res = await apiCall<{ items: Array<Record<string, unknown>> }>(\n // Some APIs filter by `id` (catalog), others by `ids` (resources) \u2014 send both so the one recognized by the target route's buildFilters is applied\n `${listUrl}?id=${encodeURIComponent(recordId)}&ids=${encodeURIComponent(recordId)}&pageSize=1`,\n )\n if (!res.ok) return null\n const items = res.result?.items\n return Array.isArray(items) && items.length > 0 ? items[0] : null\n },\n })\n\n const baseValues = isEmbedded ? (propBaseValues ?? {}) : (recordData ?? {})\n\n const resolveRecordLabel = React.useCallback(\n (value: string) => {\n if (recordData) return getRecordLabel(recordData)\n return value\n },\n [recordData],\n )\n\n const { data: fieldDefs = [], isLoading: loadingFieldDefs } = useCustomFieldDefs(entityType ? [entityType] : [], {\n enabled: !!entityType,\n })\n\n const fieldList = React.useMemo(\n () => resolveFieldList(entityType, propTranslatableFields, fieldDefs as Array<{ key: string; kind: string; label?: string }>),\n [entityType, propTranslatableFields, fieldDefs],\n )\n\n const {\n data: translationData,\n isLoading: loadingTranslation,\n isError: translationError,\n refetch: refetchTranslation,\n } = useQuery<TranslationsResponse | null>({\n queryKey: ['entity-translation', entityType, recordId, scopeVersion],\n enabled: !!entityType && !!recordId,\n queryFn: async () => {\n const res = await apiCall<TranslationsResponse>(\n `/api/translations/${encodeURIComponent(entityType)}/${encodeURIComponent(recordId)}`,\n )\n if (!res.ok) {\n if (res.response?.status === 404) return null\n return null\n }\n return res.result ?? null\n },\n })\n\n // Optimistic lock keys off the TRANSLATION ROW'S OWN version (`updatedAt` from\n // the GET response), not the host entity's: the host's EAV `entityType`\n // (`module:entity`) has no reliable server-side mapping to a registered\n // optimistic-lock reader, so the route enforces against the translation row's\n // own `updated_at`. `null` for a brand-new translation (no existing row \u2192 the\n // header is omitted and the route enforces nothing on insert).\n const translationRowUpdatedAt = React.useMemo(() => {\n const value = translationData?.updatedAt\n return typeof value === 'string' && value.trim().length > 0 ? value : null\n }, [translationData])\n\n const translationSignature = React.useMemo(() => JSON.stringify(translationData ?? null), [translationData])\n const lastTranslationSignatureRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n const sig = translationSignature\n if (sig === lastTranslationSignatureRef.current && hasUserEditedRef.current) return\n lastTranslationSignatureRef.current = sig\n\n if (!translationData?.translations) {\n if (!hasUserEditedRef.current) {\n editedTranslationsRef.current = {}\n setEditedTranslations({})\n }\n return\n }\n\n const parsed: Record<string, Record<string, string>> = {}\n for (const [locale, fields] of Object.entries(translationData.translations)) {\n if (!fields || typeof fields !== 'object') continue\n parsed[locale] = {}\n for (const [key, val] of Object.entries(fields)) {\n parsed[locale][key] = typeof val === 'string' ? val : ''\n }\n }\n if (!hasUserEditedRef.current) {\n editedTranslationsRef.current = parsed\n setEditedTranslations(parsed)\n }\n }, [translationSignature, translationData])\n\n const { runMutation, retryLastMutation } = useGuardedMutation<{\n formId: string\n entityType: string\n recordId: string\n resourceKind: string\n resourceId: string\n data: TranslationsResponse | null\n retryLastMutation: () => Promise<boolean>\n }>({ contextId: TRANSLATION_MUTATION_CONTEXT_ID })\n\n const mutation = useMutation({\n mutationFn: async () => {\n if (!entityType || !recordId) {\n throw new Error(t('translations.manager.errors.selectRecord', 'Select an entity and record before saving'))\n }\n const body: Record<string, Record<string, string | null>> = {}\n for (const [locale, fields] of Object.entries(editedTranslationsRef.current)) {\n const localeFields: Record<string, string | null> = {}\n let hasValues = false\n for (const [key, val] of Object.entries(fields)) {\n if (val && val.trim().length > 0) {\n localeFields[key] = val.trim()\n hasValues = true\n }\n }\n if (hasValues) body[locale] = localeFields\n }\n if (Object.keys(body).length === 0) {\n logger.warn('Save skipped: payload is empty \u2014 no locale contains any non-empty field')\n throw new Error(t('translations.manager.errors.nothingToSave', 'Nothing to save \u2014 enter a translation first'))\n }\n return runMutation({\n operation: async () => {\n const res = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(translationRowUpdatedAt),\n () => apiCall(\n `/api/translations/${encodeURIComponent(entityType)}/${encodeURIComponent(recordId)}`,\n {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n },\n ),\n )\n if (!res.ok) {\n throw new Error(t('translations.manager.errors.save', 'Failed to save translations'))\n }\n return true\n },\n context: {\n formId: TRANSLATION_MUTATION_CONTEXT_ID,\n entityType,\n recordId,\n resourceKind: 'translation',\n resourceId: recordId,\n data: translationData ?? null,\n retryLastMutation,\n },\n mutationPayload: body,\n })\n },\n onSuccess: () => {\n flash(t('translations.manager.flash.saved', 'Translations saved'), 'success')\n hasUserEditedRef.current = false\n setHasUserEdited(false)\n void refetchTranslation()\n },\n onError: (err: unknown) => {\n if (surfaceRecordConflict(err, t)) return\n const message = err instanceof Error ? err.message : t('translations.manager.errors.save', 'Failed to save translations')\n flash(message, 'error')\n },\n })\n\n const updateFieldValue = (locale: string, fieldKey: string, value: string) => {\n hasUserEditedRef.current = true\n setHasUserEdited(true)\n const next = {\n ...editedTranslationsRef.current,\n [locale]: {\n ...editedTranslationsRef.current[locale],\n [fieldKey]: value,\n },\n }\n editedTranslationsRef.current = next\n setEditedTranslations(next)\n }\n\n const getBaseValue = (fieldKey: string): string => resolveBaseValue(baseValues, fieldKey)\n\n const renderRecordPicker = () => {\n if (isEmbedded) return null\n\n return (\n <div className=\"space-y-2\">\n <label className=\"text-xs text-muted-foreground\">\n {t('translations.manager.selectRecord', 'Select record')}\n </label>\n <ComboboxInput\n value={selectedRecordId}\n onChange={(next) => {\n setSelectedRecordId(next)\n hasUserEditedRef.current = false\n setHasUserEdited(false)\n }}\n placeholder={t('translations.manager.searchRecords', 'Search records...')}\n loadSuggestions={loadRecordSuggestions}\n resolveLabel={resolveRecordLabel}\n allowCustomValues\n disabled={!entityType}\n />\n </div>\n )\n }\n\n const renderLocaleTabs = () => (\n <Tabs variant=\"underline\" value={activeLocale} onValueChange={setActiveLocale}>\n <TabsList>\n {locales.map((locale) => (\n <TabsTrigger key={locale} value={locale}>\n {locale.toUpperCase()}\n </TabsTrigger>\n ))}\n </TabsList>\n </Tabs>\n )\n\n const renderFieldTable = () => {\n if (!entityType || !recordId) {\n return (\n <div className=\"rounded border bg-background/80 p-4 text-sm text-muted-foreground\">\n {t('translations.manager.selectFirst', 'Select an entity and record to manage translations.')}\n </div>\n )\n }\n if (loadingTranslation || loadingFieldDefs) {\n return (\n <LoadingMessage\n label={t('translations.manager.loadingTranslations', 'Loading translations...')}\n className=\"border-0 bg-transparent p-4\"\n />\n )\n }\n if (translationError) {\n return (\n <ErrorMessage\n label={t('translations.manager.errors.loadTranslation', 'Failed to load translations')}\n action={(\n <Button variant=\"outline\" size=\"sm\" onClick={() => void refetchTranslation()}>\n {t('translations.manager.actions.retry', 'Retry')}\n </Button>\n )}\n />\n )\n }\n if (!fieldList.length) {\n return (\n <div className=\"rounded border bg-background/80 p-4 text-sm text-muted-foreground\">\n {t('translations.manager.noFields', 'No translatable fields found for this entity type.')}\n </div>\n )\n }\n\n const localeTranslations = editedTranslations[activeLocale] ?? {}\n\n return (\n <div className=\"overflow-x-auto\">\n <table className=\"w-full min-w-[480px] text-sm\">\n <thead>\n <tr className=\"text-xs uppercase tracking-wide text-muted-foreground\">\n <th className=\"px-3 py-2 text-left w-[140px]\">\n {t('translations.manager.fields.field', 'Field')}\n </th>\n {!compact && (\n <th className=\"px-3 py-2 text-left\">\n {t('translations.manager.fields.baseValue', 'Base value')}\n </th>\n )}\n <th className=\"px-3 py-2 text-left\">\n {t('translations.manager.fields.translation', 'Translation')} ({activeLocale.toUpperCase()})\n </th>\n </tr>\n </thead>\n <tbody>\n {fieldList.map((field) => {\n const baseVal = getBaseValue(field.key)\n const translatedVal = localeTranslations[field.key] ?? ''\n\n return (\n <tr key={field.key} className=\"border-t\">\n <td className=\"px-3 py-2 align-top text-xs font-medium text-muted-foreground\">\n {field.label}\n </td>\n {!compact && (\n <td className=\"px-3 py-2 align-top text-xs text-muted-foreground max-w-[200px]\">\n {baseVal ? (\n <span className=\"line-clamp-3\">{baseVal}</span>\n ) : (\n <span className=\"text-muted-foreground/50\">-</span>\n )}\n </td>\n )}\n <td className=\"px-3 py-2 align-top\">\n {field.multiline ? (\n <textarea\n className=\"flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50\"\n rows={3}\n value={translatedVal}\n onChange={(e) => updateFieldValue(activeLocale, field.key, e.target.value)}\n placeholder={baseVal || field.label}\n />\n ) : (\n <Input\n value={translatedVal}\n onChange={(e) => updateFieldValue(activeLocale, field.key, e.target.value)}\n placeholder={baseVal || field.label}\n />\n )}\n </td>\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n )\n }\n\n React.useEffect(() => {\n const handler = (e: KeyboardEvent) => {\n if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {\n e.preventDefault()\n if (entityType && recordId && !mutation.isPending) mutation.mutate()\n }\n }\n document.addEventListener('keydown', handler)\n return () => document.removeEventListener('keydown', handler)\n }, [entityType, recordId, mutation])\n\n if (compact) {\n return (\n <div className=\"space-y-3\">\n {renderLocaleTabs()}\n {renderFieldTable()}\n <div className=\"flex justify-end\">\n <Button\n type=\"button\"\n size=\"sm\"\n onClick={() => mutation.mutate()}\n disabled={mutation.isPending || !entityType || !recordId}\n data-testid=\"translations-save\"\n >\n <Save className=\"mr-2 h-3 w-3\" />\n {mutation.isPending\n ? t('translations.manager.actions.saving', 'Saving...')\n : t('translations.manager.actions.save', 'Save translations')}\n </Button>\n </div>\n </div>\n )\n }\n\n return (\n <div className=\"space-y-6\">\n <div className=\"flex flex-col gap-3 rounded-lg border bg-card p-4 shadow-sm\">\n <div className=\"space-y-2\">\n <h2 className=\"text-xl font-semibold\">{t('translations.manager.title', 'Translations')}</h2>\n <p className=\"text-sm text-muted-foreground\">\n {t('translations.manager.description', 'Manage translations for entity records across supported locales.')}\n </p>\n </div>\n\n {!isEmbedded && (\n <div className=\"flex flex-col gap-4 sm:flex-row sm:items-start\">\n <div className=\"flex-1 space-y-3\">\n <div>\n <label className=\"text-xs text-muted-foreground\">\n {t('translations.manager.selectEntity', 'Choose entity')}\n </label>\n <div className=\"mt-1\">\n <ComboboxInput\n value={selectedEntityType}\n onChange={(next) => {\n setSelectedEntityType(next)\n setSelectedRecordId('')\n hasUserEditedRef.current = false\n setHasUserEdited(false)\n }}\n placeholder={t('translations.manager.placeholder', 'Select an entity')}\n suggestions={entitySuggestions}\n resolveLabel={resolveEntityLabel}\n disabled={loadingEntities || !!entitiesError}\n />\n </div>\n {entitiesError && (\n <p className=\"mt-1 text-xs text-destructive\">\n {t('translations.manager.errors.loadEntities', 'Failed to load entities')}\n </p>\n )}\n </div>\n {renderRecordPicker()}\n </div>\n </div>\n )}\n\n <div className=\"rounded-lg border bg-background/80 p-4\">\n {renderLocaleTabs()}\n <div className=\"mt-3\">\n {renderFieldTable()}\n </div>\n </div>\n\n <div className=\"flex justify-end\">\n <Button\n type=\"button\"\n onClick={() => mutation.mutate()}\n disabled={mutation.isPending || loadingEntities || !!entitiesError || !entityType || !recordId}\n data-testid=\"translations-save\"\n >\n <Save className=\"mr-2 h-4 w-4\" />\n {mutation.isPending\n ? t('translations.manager.actions.saving', 'Saving...')\n : t('translations.manager.actions.save', 'Save translations')}\n </Button>\n </div>\n </div>\n </div>\n )\n}\n\nexport function LocaleManager() {\n const t = useT()\n const queryClient = useQueryClient()\n const { data: locales = [], isLoading } = useTranslationLocales()\n const [newLocale, setNewLocale] = React.useState('')\n\n const { runMutation, retryLastMutation } = useGuardedMutation<{\n formId: string\n resourceKind: string\n retryLastMutation: () => Promise<boolean>\n }>({ contextId: SUPPORTED_LOCALES_MUTATION_CONTEXT_ID })\n\n const mutation = useMutation({\n mutationFn: async (updatedLocales: string[]) => {\n // optimistic-lock-exempt: single-row tenant supported-locales settings list \u2014 no per-record version / concurrent record edit\n return runMutation({\n operation: async () => {\n const res = await apiCall<{ locales: string[] }>('/api/translations/locales', {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ locales: updatedLocales }),\n })\n if (!res.ok) throw new Error('Failed to save locales')\n return res.result?.locales ?? updatedLocales\n },\n context: {\n formId: SUPPORTED_LOCALES_MUTATION_CONTEXT_ID,\n resourceKind: 'translation-locales',\n retryLastMutation,\n },\n mutationPayload: { locales: updatedLocales },\n })\n },\n onSuccess: (result) => {\n queryClient.setQueryData(['translation-locales'], result)\n flash(t('translations.locales.flash.saved', 'Locales updated'), 'success')\n },\n onError: () => {\n flash(t('translations.locales.flash.error', 'Failed to update locales'), 'error')\n },\n })\n\n const availableLocales = React.useMemo(\n () => ISO_639_1.filter((entry) => !locales.includes(entry.code)).map((entry) => ({\n value: entry.code,\n label: `${entry.code.toUpperCase()} \u2014 ${entry.label}`,\n })),\n [locales],\n )\n\n const addLocale = () => {\n const code = newLocale.toLowerCase().trim()\n if (!code || !isValidIso639(code) || locales.includes(code)) return\n mutation.mutate([...locales, code])\n setNewLocale('')\n }\n\n const removeLocale = (locale: string) => {\n if (locales.length <= 1) return\n mutation.mutate(locales.filter((l) => l !== locale))\n }\n\n if (isLoading) {\n return <LoadingMessage label={t('translations.locales.loading', 'Loading locales...')} className=\"border-0 bg-transparent p-4\" />\n }\n\n return (\n <div className=\"flex flex-col gap-3 rounded-lg border bg-card p-4 shadow-sm\">\n <div className=\"space-y-1\">\n <h3 className=\"text-lg font-semibold\">{t('translations.locales.title', 'Supported locales')}</h3>\n <p className=\"text-sm text-muted-foreground\">\n {t('translations.locales.description', 'Configure which locales are available for translations. Add ISO language codes (e.g. fr, it, ja, zh).')}\n </p>\n </div>\n\n <div className=\"flex flex-wrap gap-2\">\n {locales.map((locale) => (\n <span\n key={locale}\n className=\"inline-flex items-center gap-1.5 rounded-full border bg-muted/50 px-3 py-1 text-sm font-medium\"\n title={getIso639Label(locale) ?? locale}\n >\n {locale.toUpperCase()}{getIso639Label(locale) ? ` \u2014 ${getIso639Label(locale)}` : ''}\n {locales.length > 1 && (\n <IconButton\n variant=\"ghost\"\n size=\"xs\"\n fullRadius\n aria-label={t('translations.locales.remove', 'Remove {{locale}}', { locale: getIso639Label(locale) ?? locale.toUpperCase() })}\n title={t('translations.locales.remove', 'Remove {{locale}}', { locale: getIso639Label(locale) ?? locale.toUpperCase() })}\n onClick={() => removeLocale(locale)}\n disabled={mutation.isPending}\n >\n <X className=\"h-3 w-3\" />\n </IconButton>\n )}\n </span>\n ))}\n </div>\n\n <div className=\"flex gap-2 items-center\">\n <div className=\"max-w-[240px] flex-1\">\n <ComboboxInput\n value={newLocale}\n onChange={setNewLocale}\n placeholder={t('translations.locales.addPlaceholder', 'Search language...')}\n suggestions={availableLocales}\n resolveLabel={(value) => {\n const label = getIso639Label(value)\n return label ? `${value.toUpperCase()} \u2014 ${label}` : value.toUpperCase()\n }}\n />\n </div>\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={addLocale}\n disabled={mutation.isPending || !newLocale.trim() || !isValidIso639(newLocale) || locales.includes(newLocale.toLowerCase().trim())}\n >\n <Plus className=\"mr-1 h-3 w-3\" />\n {t('translations.locales.add', 'Add')}\n </Button>\n </div>\n </div>\n )\n}\n"],
5
- "mappings": ";AA+UM,SACE,KADF;AA7UN,YAAY,WAAW;AACvB,SAAS,UAAU,aAAa,sBAAsB;AACtD,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,MAAM,UAAU,mBAAmB;AAC5C,SAAS,aAAa;AACtB,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB,oBAAoB;AAC7C,SAAS,aAAa;AACtB,SAAS,SAAS,sBAAsB,mCAAmC;AAC3E,SAAS,iCAAiC;AAC1C,SAAS,6BAA6B;AACtC,SAAS,0BAA0B;AACnC,SAAS,0BAA0B;AACnC,SAAS,MAAM,MAAM,SAAS;AAC9B,SAAS,mCAAmC;AAC5C,SAAS,YAAY;AACrB,SAAS,WAAW,sBAAsB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AClC,UAAU,SAAS;AAAA,cAEnB,8BAAC,KAAE,WAAU,WAAU;AAAA;AAAA,UACzB;AAAA;AAAA;AAAA,MAhBG;AAAA,IAkBP,CACD,GACH;AAAA,IAEA,qBAAC,SAAI,WAAU,2BACb;AAAA,0BAAC,SAAI,WAAU,wBACb;AAAA,QAAC;AAAA;AAAA,UACC,OAAO;AAAA,UACP,UAAU;AAAA,UACV,aAAa,EAAE,uCAAuC,oBAAoB;AAAA,UAC1E,aAAa;AAAA,UACb,cAAc,CAAC,UAAU;AACvB,kBAAM,QAAQ,eAAe,KAAK;AAClC,mBAAO,QAAQ,GAAG,MAAM,YAAY,CAAC,WAAM,KAAK,KAAK,MAAM,YAAY;AAAA,UACzE;AAAA;AAAA,MACF,GACF;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,SAAQ;AAAA,UACR,MAAK;AAAA,UACL,SAAS;AAAA,UACT,UAAU,SAAS,aAAa,CAAC,UAAU,KAAK,KAAK,CAAC,cAAc,SAAS,KAAK,QAAQ,SAAS,UAAU,YAAY,EAAE,KAAK,CAAC;AAAA,UAEjI;AAAA,gCAAC,QAAK,WAAU,gBAAe;AAAA,YAC9B,EAAE,4BAA4B,KAAK;AAAA;AAAA;AAAA,MACtC;AAAA,OACF;AAAA,KACF;AAEJ;",
4
+ "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { IconButton } from '@open-mercato/ui/primitives/icon-button'\nimport { Badge } from '@open-mercato/ui/primitives/badge'\nimport { Tabs, TabsList, TabsTrigger } from '@open-mercato/ui/primitives/tabs'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { ComboboxInput } from '@open-mercato/ui/backend/inputs'\nimport { LoadingMessage, ErrorMessage } from '@open-mercato/ui/backend/detail'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { apiCall, readApiResultOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { useCustomFieldDefs } from '@open-mercato/ui/backend/utils/customFieldDefs'\nimport { Save, Plus, X } from 'lucide-react'\nimport { useOrganizationScopeVersion } from '@open-mercato/shared/lib/frontend/useOrganizationScope'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { defaultLocale, locales as defaultLocales } from '@open-mercato/shared/lib/i18n/config'\nimport { ISO_639_1, isValidIso639, getIso639Label } from '@open-mercato/shared/lib/i18n/iso639'\nimport { formatEntityLabel, buildEntityListUrl, getRecordLabel, resolveBaseValue } from '../lib/helpers'\nimport { resolveFieldList } from '../lib/resolve-field-list'\nimport type { ResolvedField } from '../lib/resolve-field-list'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('translations').child({ component: 'TranslationManager' })\n\nconst TRANSLATION_MUTATION_CONTEXT_ID = 'translations.entity-translations'\nconst SUPPORTED_LOCALES_MUTATION_CONTEXT_ID = 'translations.supported-locales'\n\ntype TranslationManagerProps = {\n entityType?: string\n recordId?: string\n baseValues?: Record<string, unknown>\n translatableFields?: string[]\n mode?: 'standalone' | 'embedded'\n compact?: boolean\n}\n\ntype EntityOption = { entityId: string; label?: string; source?: string }\n\ntype TranslationsResponse = {\n entityType: string\n entityId: string\n translations: Record<string, Record<string, unknown>>\n createdAt?: string\n updatedAt?: string\n}\n\ntype TranslationLocales = {\n /** The tenant's stored selection: which locales content can be translated into. */\n locales: string[]\n /** Which of those the admin UI itself can be rendered in. Resolved on the server. */\n servable: string[]\n}\n\nfunction useTranslationLocales() {\n return useQuery<TranslationLocales>({\n queryKey: ['translation-locales'],\n queryFn: async () => {\n const res = await apiCall<TranslationLocales>('/api/translations/locales')\n const fallback = { locales: [...defaultLocales], servable: [...defaultLocales] }\n if (!res.ok) return fallback\n const locales = Array.isArray(res.result?.locales) && res.result.locales.length > 0\n ? res.result.locales\n : [...defaultLocales]\n const servable = Array.isArray(res.result?.servable) && res.result.servable.length > 0\n ? res.result.servable\n : [...defaultLocales]\n return { locales, servable }\n },\n staleTime: 60_000,\n })\n}\n\nexport function TranslationManager({\n entityType: propEntityType,\n recordId: propRecordId,\n baseValues: propBaseValues,\n translatableFields: propTranslatableFields,\n mode = 'standalone',\n compact = false,\n}: TranslationManagerProps) {\n const t = useT()\n const scopeVersion = useOrganizationScopeVersion()\n const isEmbedded = mode === 'embedded'\n\n const [selectedEntityType, setSelectedEntityType] = React.useState(propEntityType ?? '')\n const [selectedRecordId, setSelectedRecordId] = React.useState(propRecordId ?? '')\n const [activeLocale, setActiveLocale] = React.useState('')\n const [editedTranslations, setEditedTranslations] = React.useState<Record<string, Record<string, string>>>({})\n const editedTranslationsRef = React.useRef<Record<string, Record<string, string>>>({})\n const [hasUserEdited, setHasUserEdited] = React.useState(false)\n const hasUserEditedRef = React.useRef(false)\n\n const entityType = isEmbedded ? (propEntityType ?? '') : selectedEntityType\n const recordId = isEmbedded ? (propRecordId ?? '') : selectedRecordId\n\n const { data: localeData } = useTranslationLocales()\n // Memoized: `locales` feeds effect dependency lists below, and a fresh array\n // on every render while the query is still loading would re-fire them.\n const locales = React.useMemo(() => localeData?.locales ?? [...defaultLocales], [localeData])\n\n React.useEffect(() => {\n if (locales.length > 0 && (!activeLocale || !locales.includes(activeLocale))) {\n setActiveLocale(locales[0])\n }\n }, [locales, activeLocale])\n\n React.useEffect(() => {\n if (isEmbedded && propEntityType) setSelectedEntityType(propEntityType)\n }, [isEmbedded, propEntityType])\n\n React.useEffect(() => {\n if (isEmbedded && propRecordId) setSelectedRecordId(propRecordId)\n }, [isEmbedded, propRecordId])\n\n const { data: entities, isLoading: loadingEntities, error: entitiesError } = useQuery<{ items: EntityOption[] }>({\n queryKey: ['entities-list', scopeVersion],\n enabled: !isEmbedded,\n queryFn: async () =>\n readApiResultOrThrow('/api/entities/entities', undefined, {\n errorMessage: t('translations.manager.errors.loadEntities', 'Failed to load entities'),\n }),\n })\n\n const entitySuggestions = React.useMemo(\n () =>\n (entities?.items || []).map((item) => ({\n value: item.entityId,\n label: formatEntityLabel(item.entityId, item.label),\n description: item.entityId,\n })),\n [entities],\n )\n\n const resolveEntityLabel = React.useCallback(\n (value: string) => {\n const match = entities?.items?.find((e) => e.entityId === value)\n return match ? formatEntityLabel(match.entityId, match.label) : formatEntityLabel(value)\n },\n [entities],\n )\n\n const listUrl = React.useMemo(() => entityType ? buildEntityListUrl(entityType) : null, [entityType])\n\n const loadRecordSuggestions = React.useCallback(\n async (query?: string) => {\n if (!entityType || !listUrl) return []\n const url = `${listUrl}?pageSize=20${query ? `&search=${encodeURIComponent(query)}` : ''}`\n const res = await apiCall<{ items: Array<Record<string, unknown>> }>(url)\n if (!res.ok) return []\n const items = res.result?.items ?? []\n return items.map((item) => ({\n value: String(item.id ?? ''),\n label: getRecordLabel(item),\n }))\n },\n [entityType, listUrl],\n )\n\n const { data: recordData } = useQuery<Record<string, unknown> | null>({\n queryKey: ['translation-record-data', entityType, recordId, listUrl, scopeVersion],\n enabled: !isEmbedded && !!entityType && !!recordId && !!listUrl,\n queryFn: async () => {\n const res = await apiCall<{ items: Array<Record<string, unknown>> }>(\n // Some APIs filter by `id` (catalog), others by `ids` (resources) \u2014 send both so the one recognized by the target route's buildFilters is applied\n `${listUrl}?id=${encodeURIComponent(recordId)}&ids=${encodeURIComponent(recordId)}&pageSize=1`,\n )\n if (!res.ok) return null\n const items = res.result?.items\n return Array.isArray(items) && items.length > 0 ? items[0] : null\n },\n })\n\n const baseValues = isEmbedded ? (propBaseValues ?? {}) : (recordData ?? {})\n\n const resolveRecordLabel = React.useCallback(\n (value: string) => {\n if (recordData) return getRecordLabel(recordData)\n return value\n },\n [recordData],\n )\n\n const { data: fieldDefs = [], isLoading: loadingFieldDefs } = useCustomFieldDefs(entityType ? [entityType] : [], {\n enabled: !!entityType,\n })\n\n const fieldList = React.useMemo(\n () => resolveFieldList(entityType, propTranslatableFields, fieldDefs as Array<{ key: string; kind: string; label?: string }>),\n [entityType, propTranslatableFields, fieldDefs],\n )\n\n const {\n data: translationData,\n isLoading: loadingTranslation,\n isError: translationError,\n refetch: refetchTranslation,\n } = useQuery<TranslationsResponse | null>({\n queryKey: ['entity-translation', entityType, recordId, scopeVersion],\n enabled: !!entityType && !!recordId,\n queryFn: async () => {\n const res = await apiCall<TranslationsResponse>(\n `/api/translations/${encodeURIComponent(entityType)}/${encodeURIComponent(recordId)}`,\n )\n if (!res.ok) {\n if (res.response?.status === 404) return null\n return null\n }\n return res.result ?? null\n },\n })\n\n // Optimistic lock keys off the TRANSLATION ROW'S OWN version (`updatedAt` from\n // the GET response), not the host entity's: the host's EAV `entityType`\n // (`module:entity`) has no reliable server-side mapping to a registered\n // optimistic-lock reader, so the route enforces against the translation row's\n // own `updated_at`. `null` for a brand-new translation (no existing row \u2192 the\n // header is omitted and the route enforces nothing on insert).\n const translationRowUpdatedAt = React.useMemo(() => {\n const value = translationData?.updatedAt\n return typeof value === 'string' && value.trim().length > 0 ? value : null\n }, [translationData])\n\n const translationSignature = React.useMemo(() => JSON.stringify(translationData ?? null), [translationData])\n const lastTranslationSignatureRef = React.useRef<string | null>(null)\n\n React.useEffect(() => {\n const sig = translationSignature\n if (sig === lastTranslationSignatureRef.current && hasUserEditedRef.current) return\n lastTranslationSignatureRef.current = sig\n\n if (!translationData?.translations) {\n if (!hasUserEditedRef.current) {\n editedTranslationsRef.current = {}\n setEditedTranslations({})\n }\n return\n }\n\n const parsed: Record<string, Record<string, string>> = {}\n for (const [locale, fields] of Object.entries(translationData.translations)) {\n if (!fields || typeof fields !== 'object') continue\n parsed[locale] = {}\n for (const [key, val] of Object.entries(fields)) {\n parsed[locale][key] = typeof val === 'string' ? val : ''\n }\n }\n if (!hasUserEditedRef.current) {\n editedTranslationsRef.current = parsed\n setEditedTranslations(parsed)\n }\n }, [translationSignature, translationData])\n\n const { runMutation, retryLastMutation } = useGuardedMutation<{\n formId: string\n entityType: string\n recordId: string\n resourceKind: string\n resourceId: string\n data: TranslationsResponse | null\n retryLastMutation: () => Promise<boolean>\n }>({ contextId: TRANSLATION_MUTATION_CONTEXT_ID })\n\n const mutation = useMutation({\n mutationFn: async () => {\n if (!entityType || !recordId) {\n throw new Error(t('translations.manager.errors.selectRecord', 'Select an entity and record before saving'))\n }\n const body: Record<string, Record<string, string | null>> = {}\n for (const [locale, fields] of Object.entries(editedTranslationsRef.current)) {\n const localeFields: Record<string, string | null> = {}\n let hasValues = false\n for (const [key, val] of Object.entries(fields)) {\n if (val && val.trim().length > 0) {\n localeFields[key] = val.trim()\n hasValues = true\n }\n }\n if (hasValues) body[locale] = localeFields\n }\n if (Object.keys(body).length === 0) {\n logger.warn('Save skipped: payload is empty \u2014 no locale contains any non-empty field')\n throw new Error(t('translations.manager.errors.nothingToSave', 'Nothing to save \u2014 enter a translation first'))\n }\n return runMutation({\n operation: async () => {\n const res = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(translationRowUpdatedAt),\n () => apiCall(\n `/api/translations/${encodeURIComponent(entityType)}/${encodeURIComponent(recordId)}`,\n {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n },\n ),\n )\n if (!res.ok) {\n throw new Error(t('translations.manager.errors.save', 'Failed to save translations'))\n }\n return true\n },\n context: {\n formId: TRANSLATION_MUTATION_CONTEXT_ID,\n entityType,\n recordId,\n resourceKind: 'translation',\n resourceId: recordId,\n data: translationData ?? null,\n retryLastMutation,\n },\n mutationPayload: body,\n })\n },\n onSuccess: () => {\n flash(t('translations.manager.flash.saved', 'Translations saved'), 'success')\n hasUserEditedRef.current = false\n setHasUserEdited(false)\n void refetchTranslation()\n },\n onError: (err: unknown) => {\n if (surfaceRecordConflict(err, t)) return\n const message = err instanceof Error ? err.message : t('translations.manager.errors.save', 'Failed to save translations')\n flash(message, 'error')\n },\n })\n\n const updateFieldValue = (locale: string, fieldKey: string, value: string) => {\n hasUserEditedRef.current = true\n setHasUserEdited(true)\n const next = {\n ...editedTranslationsRef.current,\n [locale]: {\n ...editedTranslationsRef.current[locale],\n [fieldKey]: value,\n },\n }\n editedTranslationsRef.current = next\n setEditedTranslations(next)\n }\n\n const getBaseValue = (fieldKey: string): string => resolveBaseValue(baseValues, fieldKey)\n\n const renderRecordPicker = () => {\n if (isEmbedded) return null\n\n return (\n <div className=\"space-y-2\">\n <label className=\"text-xs text-muted-foreground\">\n {t('translations.manager.selectRecord', 'Select record')}\n </label>\n <ComboboxInput\n value={selectedRecordId}\n onChange={(next) => {\n setSelectedRecordId(next)\n hasUserEditedRef.current = false\n setHasUserEdited(false)\n }}\n placeholder={t('translations.manager.searchRecords', 'Search records...')}\n loadSuggestions={loadRecordSuggestions}\n resolveLabel={resolveRecordLabel}\n allowCustomValues\n disabled={!entityType}\n />\n </div>\n )\n }\n\n const renderLocaleTabs = () => (\n <Tabs variant=\"underline\" value={activeLocale} onValueChange={setActiveLocale}>\n <TabsList>\n {locales.map((locale) => (\n <TabsTrigger key={locale} value={locale}>\n {locale.toUpperCase()}\n </TabsTrigger>\n ))}\n </TabsList>\n </Tabs>\n )\n\n const renderFieldTable = () => {\n if (!entityType || !recordId) {\n return (\n <div className=\"rounded border bg-background/80 p-4 text-sm text-muted-foreground\">\n {t('translations.manager.selectFirst', 'Select an entity and record to manage translations.')}\n </div>\n )\n }\n if (loadingTranslation || loadingFieldDefs) {\n return (\n <LoadingMessage\n label={t('translations.manager.loadingTranslations', 'Loading translations...')}\n className=\"border-0 bg-transparent p-4\"\n />\n )\n }\n if (translationError) {\n return (\n <ErrorMessage\n label={t('translations.manager.errors.loadTranslation', 'Failed to load translations')}\n action={(\n <Button variant=\"outline\" size=\"sm\" onClick={() => void refetchTranslation()}>\n {t('translations.manager.actions.retry', 'Retry')}\n </Button>\n )}\n />\n )\n }\n if (!fieldList.length) {\n return (\n <div className=\"rounded border bg-background/80 p-4 text-sm text-muted-foreground\">\n {t('translations.manager.noFields', 'No translatable fields found for this entity type.')}\n </div>\n )\n }\n\n const localeTranslations = editedTranslations[activeLocale] ?? {}\n\n return (\n <div className=\"overflow-x-auto\">\n <table className=\"w-full min-w-[480px] text-sm\">\n <thead>\n <tr className=\"text-xs uppercase tracking-wide text-muted-foreground\">\n <th className=\"px-3 py-2 text-left w-[140px]\">\n {t('translations.manager.fields.field', 'Field')}\n </th>\n {!compact && (\n <th className=\"px-3 py-2 text-left\">\n {t('translations.manager.fields.baseValue', 'Base value')}\n </th>\n )}\n <th className=\"px-3 py-2 text-left\">\n {t('translations.manager.fields.translation', 'Translation')} ({activeLocale.toUpperCase()})\n </th>\n </tr>\n </thead>\n <tbody>\n {fieldList.map((field) => {\n const baseVal = getBaseValue(field.key)\n const translatedVal = localeTranslations[field.key] ?? ''\n\n return (\n <tr key={field.key} className=\"border-t\">\n <td className=\"px-3 py-2 align-top text-xs font-medium text-muted-foreground\">\n {field.label}\n </td>\n {!compact && (\n <td className=\"px-3 py-2 align-top text-xs text-muted-foreground max-w-[200px]\">\n {baseVal ? (\n <span className=\"line-clamp-3\">{baseVal}</span>\n ) : (\n <span className=\"text-muted-foreground/50\">-</span>\n )}\n </td>\n )}\n <td className=\"px-3 py-2 align-top\">\n {field.multiline ? (\n <textarea\n className=\"flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50\"\n rows={3}\n value={translatedVal}\n onChange={(e) => updateFieldValue(activeLocale, field.key, e.target.value)}\n placeholder={baseVal || field.label}\n />\n ) : (\n <Input\n value={translatedVal}\n onChange={(e) => updateFieldValue(activeLocale, field.key, e.target.value)}\n placeholder={baseVal || field.label}\n />\n )}\n </td>\n </tr>\n )\n })}\n </tbody>\n </table>\n </div>\n )\n }\n\n React.useEffect(() => {\n const handler = (e: KeyboardEvent) => {\n if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {\n e.preventDefault()\n if (entityType && recordId && !mutation.isPending) mutation.mutate()\n }\n }\n document.addEventListener('keydown', handler)\n return () => document.removeEventListener('keydown', handler)\n }, [entityType, recordId, mutation])\n\n if (compact) {\n return (\n <div className=\"space-y-3\">\n {renderLocaleTabs()}\n {renderFieldTable()}\n <div className=\"flex justify-end\">\n <Button\n type=\"button\"\n size=\"sm\"\n onClick={() => mutation.mutate()}\n disabled={mutation.isPending || !entityType || !recordId}\n data-testid=\"translations-save\"\n >\n <Save className=\"mr-2 h-3 w-3\" />\n {mutation.isPending\n ? t('translations.manager.actions.saving', 'Saving...')\n : t('translations.manager.actions.save', 'Save translations')}\n </Button>\n </div>\n </div>\n )\n }\n\n return (\n <div className=\"space-y-6\">\n <div className=\"flex flex-col gap-3 rounded-lg border bg-card p-4 shadow-sm\">\n <div className=\"space-y-2\">\n <h2 className=\"text-xl font-semibold\">{t('translations.manager.title', 'Translations')}</h2>\n <p className=\"text-sm text-muted-foreground\">\n {t('translations.manager.description', 'Manage translations for entity records across supported locales.')}\n </p>\n </div>\n\n {!isEmbedded && (\n <div className=\"flex flex-col gap-4 sm:flex-row sm:items-start\">\n <div className=\"flex-1 space-y-3\">\n <div>\n <label className=\"text-xs text-muted-foreground\">\n {t('translations.manager.selectEntity', 'Choose entity')}\n </label>\n <div className=\"mt-1\">\n <ComboboxInput\n value={selectedEntityType}\n onChange={(next) => {\n setSelectedEntityType(next)\n setSelectedRecordId('')\n hasUserEditedRef.current = false\n setHasUserEdited(false)\n }}\n placeholder={t('translations.manager.placeholder', 'Select an entity')}\n suggestions={entitySuggestions}\n resolveLabel={resolveEntityLabel}\n disabled={loadingEntities || !!entitiesError}\n />\n </div>\n {entitiesError && (\n <p className=\"mt-1 text-xs text-destructive\">\n {t('translations.manager.errors.loadEntities', 'Failed to load entities')}\n </p>\n )}\n </div>\n {renderRecordPicker()}\n </div>\n </div>\n )}\n\n <div className=\"rounded-lg border bg-background/80 p-4\">\n {renderLocaleTabs()}\n <div className=\"mt-3\">\n {renderFieldTable()}\n </div>\n </div>\n\n <div className=\"flex justify-end\">\n <Button\n type=\"button\"\n onClick={() => mutation.mutate()}\n disabled={mutation.isPending || loadingEntities || !!entitiesError || !entityType || !recordId}\n data-testid=\"translations-save\"\n >\n <Save className=\"mr-2 h-4 w-4\" />\n {mutation.isPending\n ? t('translations.manager.actions.saving', 'Saving...')\n : t('translations.manager.actions.save', 'Save translations')}\n </Button>\n </div>\n </div>\n </div>\n )\n}\n\nexport function LocaleManager() {\n const t = useT()\n const queryClient = useQueryClient()\n const { data: localeData, isLoading } = useTranslationLocales()\n const locales = React.useMemo(() => localeData?.locales ?? [], [localeData])\n const servable = React.useMemo(() => localeData?.servable ?? [], [localeData])\n const [newLocale, setNewLocale] = React.useState('')\n\n const { runMutation, retryLastMutation } = useGuardedMutation<{\n formId: string\n resourceKind: string\n retryLastMutation: () => Promise<boolean>\n }>({ contextId: SUPPORTED_LOCALES_MUTATION_CONTEXT_ID })\n\n const mutation = useMutation({\n mutationFn: async (updatedLocales: string[]) => {\n // optimistic-lock-exempt: single-row tenant supported-locales settings list \u2014 no per-record version / concurrent record edit\n return runMutation({\n operation: async () => {\n const res = await apiCall<{ locales: string[] }>('/api/translations/locales', {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ locales: updatedLocales }),\n })\n if (!res.ok) throw new Error('Failed to save locales')\n return res.result?.locales ?? updatedLocales\n },\n context: {\n formId: SUPPORTED_LOCALES_MUTATION_CONTEXT_ID,\n resourceKind: 'translation-locales',\n retryLastMutation,\n },\n mutationPayload: { locales: updatedLocales },\n })\n },\n onSuccess: (result) => {\n // The PUT response carries the stored selection only, so `servable` has to\n // come from the cached entry. With no entry to read, defaulting it to `[]`\n // would mark every chip \"Content only\" \u2014 including the shipped locales \u2014\n // which is the one answer that is definitely wrong. Refetch instead.\n const previous = queryClient.getQueryData<TranslationLocales>(['translation-locales'])\n if (previous) {\n queryClient.setQueryData<TranslationLocales>(['translation-locales'], { ...previous, locales: result })\n } else {\n void queryClient.invalidateQueries({ queryKey: ['translation-locales'] })\n }\n flash(t('translations.locales.flash.saved', 'Locales updated'), 'success')\n },\n onError: () => {\n flash(t('translations.locales.flash.error', 'Failed to update locales'), 'error')\n },\n })\n\n // A locale the app has no dictionary for can be translated into, but the admin\n // UI can never be shown in it \u2014 `resolveSupportedLocalesForRequest` intersects\n // the selection with what the app serves. Saying so at the point of action is\n // what keeps the successful-looking add honest.\n const contentOnlyLabel = t('translations.locales.contentOnly', 'Content only')\n const isServable = React.useCallback(\n (code: string) => servable.includes(code.toLowerCase()),\n [servable],\n )\n\n const availableLocales = React.useMemo(\n () => ISO_639_1.filter((entry) => !locales.includes(entry.code)).map((entry) => ({\n value: entry.code,\n label: isServable(entry.code)\n ? `${entry.code.toUpperCase()} \u2014 ${entry.label}`\n : `${entry.code.toUpperCase()} \u2014 ${entry.label} (${contentOnlyLabel})`,\n })),\n [locales, isServable, contentOnlyLabel],\n )\n\n // `resolveSupportedLocalesForRequest` keeps `defaultLocale` in the served set\n // whatever the stored selection says, so a tenant whose saved list omits it\n // still gets it in the language switcher. Rendering the raw selection here\n // would leave this screen and the switcher disagreeing about what is served.\n const chips = React.useMemo(\n () => (locales.includes(defaultLocale) ? locales : [defaultLocale, ...locales]),\n [locales],\n )\n\n const addLocale = () => {\n const code = newLocale.toLowerCase().trim()\n if (!code || !isValidIso639(code) || locales.includes(code)) return\n mutation.mutate([...locales, code])\n setNewLocale('')\n }\n\n const removeLocale = (locale: string) => {\n if (locales.length <= 1) return\n // The default locale stays servable whatever the selection says\n // (`resolveSupportedLocalesForRequest` re-adds it), so letting it be removed\n // here would leave the chip list claiming something untrue.\n if (locale === defaultLocale) return\n mutation.mutate(locales.filter((l) => l !== locale))\n }\n\n if (isLoading) {\n return <LoadingMessage label={t('translations.locales.loading', 'Loading locales...')} className=\"border-0 bg-transparent p-4\" />\n }\n\n return (\n <div className=\"flex flex-col gap-3 rounded-lg border bg-card p-4 shadow-sm\">\n <div className=\"space-y-1\">\n <h3 className=\"text-lg font-semibold\">{t('translations.locales.title', 'Supported locales')}</h3>\n <p className=\"text-sm text-muted-foreground\">\n {t('translations.locales.description', 'Which languages content can be translated into. A language the application ships an interface for is also offered in the admin language switcher; the rest are available for content only.')}\n </p>\n </div>\n\n <div className=\"flex flex-wrap gap-2\">\n {chips.map((locale) => {\n const localeLabel = getIso639Label(locale) ?? locale.toUpperCase()\n const isDefault = locale === defaultLocale\n const isStored = locales.includes(locale)\n const removeLabel = t('translations.locales.remove', 'Remove {{locale}}', { locale: localeLabel })\n const defaultLabel = t(\n 'translations.locales.alwaysServed',\n '{{locale}} is the default language and is always served, so it cannot be removed.',\n { locale: localeLabel },\n )\n return (\n <span\n key={locale}\n className=\"inline-flex items-center gap-1.5 rounded-full border bg-muted/50 px-3 py-1 text-sm font-medium\"\n title={isStored ? (getIso639Label(locale) ?? locale) : defaultLabel}\n >\n {locale.toUpperCase()}{getIso639Label(locale) ? ` \u2014 ${getIso639Label(locale)}` : ''}\n {!isServable(locale) && (\n <Badge variant=\"outline\" size=\"sm\" title={t('translations.locales.contentOnlyHint', 'The application ships no interface for this language, so it is available for content translations only.')}>\n {contentOnlyLabel}\n </Badge>\n )}\n {isStored && locales.length > 1 && (\n <IconButton\n variant=\"ghost\"\n size=\"xs\"\n fullRadius\n aria-label={isDefault ? defaultLabel : removeLabel}\n title={isDefault ? defaultLabel : removeLabel}\n onClick={() => removeLocale(locale)}\n disabled={mutation.isPending || isDefault}\n >\n <X className=\"h-3 w-3\" />\n </IconButton>\n )}\n </span>\n )\n })}\n </div>\n\n <div className=\"flex gap-2 items-center\">\n <div className=\"max-w-[240px] flex-1\">\n <ComboboxInput\n value={newLocale}\n onChange={setNewLocale}\n placeholder={t('translations.locales.addPlaceholder', 'e.g. fr, it, ja...')}\n suggestions={availableLocales}\n resolveLabel={(value) => {\n const label = getIso639Label(value)\n const base = label ? `${value.toUpperCase()} \u2014 ${label}` : value.toUpperCase()\n return isServable(value) ? base : `${base} (${contentOnlyLabel})`\n }}\n />\n </div>\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={addLocale}\n disabled={mutation.isPending || !newLocale.trim() || !isValidIso639(newLocale) || locales.includes(newLocale.toLowerCase().trim())}\n >\n <Plus className=\"mr-1 h-3 w-3\" />\n {t('translations.locales.add', 'Add')}\n </Button>\n </div>\n </div>\n )\n}\n"],
5
+ "mappings": ";AA+VM,SACE,KADF;AA7VN,YAAY,WAAW;AACvB,SAAS,UAAU,aAAa,sBAAsB;AACtD,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AACtB,SAAS,MAAM,UAAU,mBAAmB;AAC5C,SAAS,aAAa;AACtB,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB,oBAAoB;AAC7C,SAAS,aAAa;AACtB,SAAS,SAAS,sBAAsB,mCAAmC;AAC3E,SAAS,iCAAiC;AAC1C,SAAS,6BAA6B;AACtC,SAAS,0BAA0B;AACnC,SAAS,0BAA0B;AACnC,SAAS,MAAM,MAAM,SAAS;AAC9B,SAAS,mCAAmC;AAC5C,SAAS,YAAY;AACrB,SAAS,eAAe,WAAW,sBAAsB;AACzD,SAAS,WAAW,eAAe,sBAAsB;AACzD,SAAS,mBAAmB,oBAAoB,gBAAgB,wBAAwB;AACxF,SAAS,wBAAwB;AAEjC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,cAAc,EAAE,MAAM,EAAE,WAAW,qBAAqB,CAAC;AAErF,MAAM,kCAAkC;AACxC,MAAM,wCAAwC;AA4B9C,SAAS,wBAAwB;AAC/B,SAAO,SAA6B;AAAA,IAClC,UAAU,CAAC,qBAAqB;AAAA,IAChC,SAAS,YAAY;AACnB,YAAM,MAAM,MAAM,QAA4B,2BAA2B;AACzE,YAAM,WAAW,EAAE,SAAS,CAAC,GAAG,cAAc,GAAG,UAAU,CAAC,GAAG,cA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,cAAc,CAAC,UAAU;AACvB,kBAAM,QAAQ,eAAe,KAAK;AAClC,kBAAM,OAAO,QAAQ,GAAG,MAAM,YAAY,CAAC,WAAM,KAAK,KAAK,MAAM,YAAY;AAC7E,mBAAO,WAAW,KAAK,IAAI,OAAO,GAAG,IAAI,KAAK,gBAAgB;AAAA,UAChE;AAAA;AAAA,MACF,GACF;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,SAAQ;AAAA,UACR,MAAK;AAAA,UACL,SAAS;AAAA,UACT,UAAU,SAAS,aAAa,CAAC,UAAU,KAAK,KAAK,CAAC,cAAc,SAAS,KAAK,QAAQ,SAAS,UAAU,YAAY,EAAE,KAAK,CAAC;AAAA,UAEjI;AAAA,gCAAC,QAAK,WAAU,gBAAe;AAAA,YAC9B,EAAE,4BAA4B,KAAK;AAAA;AAAA;AAAA,MACtC;AAAA,OACF;AAAA,KACF;AAEJ;",
6
6
  "names": []
7
7
  }
@@ -1,11 +1,14 @@
1
1
  import { registerTranslatableFields } from "@open-mercato/shared/lib/localization/translatable-fields";
2
2
  import { registerTranslationOverlayPlugin } from "@open-mercato/shared/lib/localization/overlay-plugin";
3
+ import { registerSupportedLocalesResolver } from "@open-mercato/shared/lib/i18n/locale-registry";
3
4
  import { translatableFields as catalogFields } from "../catalog/translations.js";
4
5
  import { translatableFields as dictionaryFields } from "../dictionaries/translations.js";
5
6
  import { translatableFields as entitiesFields } from "../entities/translations.js";
6
7
  import { translatableFields as resourcesFields } from "../resources/translations.js";
7
8
  import { applyTranslationOverlays } from "./lib/apply.js";
8
9
  import { resolveLocaleFromRequest } from "./lib/locale.js";
10
+ import { resolveTenantSupportedLocales } from "./lib/supported-locales.js";
11
+ registerSupportedLocalesResolver(resolveTenantSupportedLocales);
9
12
  function register() {
10
13
  registerTranslatableFields(catalogFields);
11
14
  registerTranslatableFields(dictionaryFields);