Skip to content

Commit 1658c4c

Browse files
committed
fix(i18n): serve the translation bundle without Studio's server-resolved metadataForms
GET /i18n/translations/:locale now answers the platform groups without SERVER_RESOLVED_TRANSLATION_GROUPS (metadataForms). Studio's authoring forms are already translated on the server by /meta/types, from the same i18n service tree, which the door copies and never edits. GetTranslationsResponseSchema declares the served face (ServedTranslationDataSchema), closed, so a body that still carries the group fails it. Claude-Session: https://claude.ai/code/session_01Vy85beHdawtEtqNscYBy7V Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0a69482 commit 1658c4c

4 files changed

Lines changed: 330 additions & 6 deletions

File tree

Lines changed: 237 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,237 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #25785 — the translation bundle a console open downloads leaves out
5+
* Studio's `metadataForms`, and Studio's forms stay translated.
6+
*
7+
* ## The defect
8+
*
9+
* `GET /i18n/translations/:locale` served the i18n service's whole locale tree,
10+
* `metadataForms` included: 75 KB of the 221 KB raw a console open downloaded
11+
* on `examples/app-crm` zh-CN, the second-largest group after `objects`. No
12+
* browser reads it there. Studio's authoring forms arrive already translated:
13+
* the `/meta` (`/meta/types`) handler resolves `metadataForms.<type>` on the
14+
* server, over the same service, before it serves each form.
15+
*
16+
* ## What is pinned
17+
*
18+
* - A: both exits (the requested locale and the `zh` → `zh-CN` fallback) and
19+
* both spellings serve every group but the server-resolved ones, unchanged,
20+
* and the body is the closed `GetTranslationsResponseSchema`.
21+
* - B: the service's own tree is never edited, and `/meta`, read over the same
22+
* service AFTER a boot read, still serves Studio's form translated. That is
23+
* the consumer an in-place delete would silently break.
24+
* - C: the validator still hashes the bytes served, so a warm reopen is still
25+
* `304`, and a change confined to a group that is not served does not move it.
26+
*/
27+
28+
import { createHash } from 'node:crypto';
29+
import { describe, it, expect, vi } from 'vitest';
30+
import { RestServer } from '@objectstack/rest';
31+
import { GetTranslationsResponseSchema } from '@objectstack/spec/api';
32+
import { SERVER_RESOLVED_TRANSLATION_GROUPS } from '@objectstack/spec/system';
33+
34+
import { handleI18nRequest } from './i18n.js';
35+
import { apiErrorResponse } from '../error-envelope.js';
36+
import type { DomainHandlerDeps } from '../domain-handler-registry.js';
37+
import type { HttpProtocolContext } from '../http-dispatcher.js';
38+
39+
const MEMBER_EC = { userId: 'usr_member', isSystem: false, positions: [], permissions: [], systemPermissions: [] };
40+
41+
function member(headers: Record<string, string> = {}): HttpProtocolContext {
42+
return { request: { headers }, executionContext: { ...MEMBER_EC } } as unknown as HttpProtocolContext;
43+
}
44+
45+
type Bundles = Record<string, Record<string, unknown>>;
46+
47+
/** Hands back the STORED tree, as the core fallback and service-i18n both do. */
48+
function makeService(bundles: Bundles) {
49+
return {
50+
getLocales: vi.fn(() => Object.keys(bundles)),
51+
getDefaultLocale: vi.fn(() => 'en'),
52+
getFallbackLocale: vi.fn(() => 'en'),
53+
getTranslations: vi.fn((locale: string) => bundles[locale] ?? {}),
54+
};
55+
}
56+
57+
function makeDeps(service: ReturnType<typeof makeService>): DomainHandlerDeps {
58+
return {
59+
getService: vi.fn(async () => service),
60+
resolveService: vi.fn(async () => service),
61+
success: (data: any, meta?: any) => ({ status: 200, body: { success: true, data, meta } }),
62+
error: (message: string, httpStatus = 500, details?: any) =>
63+
apiErrorResponse({ message, httpStatus, details }),
64+
} as unknown as DomainHandlerDeps;
65+
}
66+
67+
async function read(
68+
service: ReturnType<typeof makeService>,
69+
subPath = '/translations/zh-CN',
70+
query: Record<string, unknown> = {},
71+
context: HttpProtocolContext = member(),
72+
): Promise<any> {
73+
return handleI18nRequest(makeDeps(service), subPath, 'GET', query, context);
74+
}
75+
76+
function validatorOf(body: unknown): string {
77+
return `W/"${createHash('sha256').update(JSON.stringify(body)).digest('base64url')}"`;
78+
}
79+
80+
/** The groups a console reads, as the platform bundle carries them. */
81+
const SERVED_GROUPS = {
82+
objects: { lead: { label: '潜在客户', fields: { company: { label: '公司' } } } },
83+
apps: { crm: { label: '客户关系管理' } },
84+
settings: { mail: { title: '邮件投递' } },
85+
messages: { save: '保存' },
86+
};
87+
88+
/** Studio's dashboard authoring form, translated the way platform-objects ships it. */
89+
const METADATA_FORMS = {
90+
dashboard: {
91+
label: '仪表板',
92+
sections: { layout: { label: '布局' } },
93+
fields: { columns: { label: '列数', helpText: '栅格列数' } },
94+
},
95+
};
96+
97+
function zhTree(): Record<string, unknown> {
98+
return { ...SERVED_GROUPS, metadataForms: METADATA_FORMS };
99+
}
100+
101+
describe('#25785 A — the served document leaves the server-resolved groups out', () => {
102+
it('names metadataForms as a server-resolved group (the constant this door reads)', () => {
103+
expect(SERVER_RESOLVED_TRANSLATION_GROUPS).toContain('metadataForms');
104+
});
105+
106+
it.each([
107+
['the path spelling', '/translations/zh-CN', {}],
108+
['the query spelling', '/translations', { locale: 'zh-CN' }],
109+
])('%s: every other group is served unchanged, metadataForms is not', async (_label, subPath, query) => {
110+
const result = await read(makeService({ en: {}, 'zh-CN': zhTree() }), subPath, query);
111+
expect(result.response.status).toBe(200);
112+
expect(result.response.body.data).toEqual({ locale: 'zh-CN', translations: SERVED_GROUPS });
113+
expect(result.response.body.data.translations).not.toHaveProperty('metadataForms');
114+
});
115+
116+
it('the locale fallback exit (zh → zh-CN) leaves it out too', async () => {
117+
const result = await read(makeService({ en: {}, 'zh-CN': zhTree() }), '/translations/zh');
118+
expect(result.response.status).toBe(200);
119+
expect(result.response.body.data).toEqual({ locale: 'zh-CN', requestedLocale: 'zh', translations: SERVED_GROUPS });
120+
});
121+
122+
it('the body satisfies the closed GetTranslationsResponseSchema, which refuses the unserved group', async () => {
123+
const result = await read(makeService({ en: {}, 'zh-CN': zhTree() }));
124+
expect(GetTranslationsResponseSchema.safeParse(result.response.body.data).success).toBe(true);
125+
126+
// Control: the same document WITH the group is refused by the schema, so
127+
// the parse above passes because the door left it out, not because the
128+
// schema reads nothing.
129+
const unserved = GetTranslationsResponseSchema.safeParse({ locale: 'zh-CN', translations: zhTree() });
130+
expect(unserved.success).toBe(false);
131+
expect(unserved.error?.issues.map((i) => i.code)).toContain('unrecognized_keys');
132+
});
133+
134+
it('a tree with nothing to leave out is served as it is', async () => {
135+
const result = await read(makeService({ en: {}, 'zh-CN': { ...SERVED_GROUPS } }));
136+
expect(result.response.body.data.translations).toEqual(SERVED_GROUPS);
137+
});
138+
});
139+
140+
// ── B: the service's tree, and the consumer that reads it ───────────────────
141+
142+
function mockRes() {
143+
return { json: vi.fn(), status: vi.fn().mockReturnThis(), header: vi.fn(), send: vi.fn() };
144+
}
145+
146+
/** A RestServer whose `/meta` handler translates from `i18n` — the route Studio reads its forms from. */
147+
function restOver(i18n: ReturnType<typeof makeService>): RestServer {
148+
const server = {
149+
get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(),
150+
use: vi.fn(), listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined),
151+
};
152+
const protocol = {
153+
getDiscovery: vi.fn().mockResolvedValue({ version: 'v0', routes: { data: '', metadata: '', ui: '', auth: '/auth' } }),
154+
getMetaTypes: vi.fn(async () => ({
155+
entries: [{
156+
type: 'dashboard',
157+
label: 'Dashboard',
158+
form: {
159+
schemaId: 'dashboard',
160+
type: 'simple',
161+
sections: [{ name: 'layout', label: 'Layout', fields: [{ field: 'columns', type: 'number', label: 'Columns' }] }],
162+
},
163+
}],
164+
types: ['dashboard'],
165+
registered: ['dashboard'],
166+
})),
167+
getMetaItems: vi.fn(async () => []),
168+
getMetaItem: vi.fn(async () => undefined),
169+
getMetaItemCached: undefined as any,
170+
findData: vi.fn().mockResolvedValue([]),
171+
};
172+
const rest = new RestServer(
173+
server as any, protocol as any, { api: { requireAuth: false } } as any,
174+
undefined, undefined, undefined, undefined, undefined,
175+
undefined, undefined, undefined, undefined, undefined,
176+
async () => i18n,
177+
);
178+
(rest as any).resolveExecCtx = async () => ({ userId: 'u1', systemPermissions: [] });
179+
rest.registerRoutes();
180+
return rest;
181+
}
182+
183+
async function readStudioForm(rest: RestServer, locale: string): Promise<any> {
184+
const route = (rest as any).getRoutes().find((r: any) => r.method === 'GET' && r.path === '/api/v1/meta');
185+
if (!route) throw new Error('route not registered: GET /api/v1/meta');
186+
const res = mockRes();
187+
await route.handler({ method: 'GET', params: {}, query: {}, body: {}, headers: { 'accept-language': locale } }, res);
188+
const body = res.json.mock.calls.at(-1)?.[0];
189+
return body.entries.find((e: any) => e.type === 'dashboard');
190+
}
191+
192+
describe("#25785 B — the service keeps the group, and Studio's forms stay translated", () => {
193+
it("a boot read does not edit the service's tree", async () => {
194+
const stored = zhTree();
195+
const service = makeService({ en: {}, 'zh-CN': stored });
196+
await read(service);
197+
expect(stored.metadataForms).toBe(METADATA_FORMS);
198+
expect(service.getTranslations('zh-CN')).toHaveProperty('metadataForms', METADATA_FORMS);
199+
});
200+
201+
it('/meta, read over the same service after a boot read, serves the form translated', async () => {
202+
const service = makeService({ en: {}, 'zh-CN': zhTree() });
203+
const boot = await read(service);
204+
expect(boot.response.body.data.translations).not.toHaveProperty('metadataForms');
205+
206+
const entry = await readStudioForm(restOver(service), 'zh-CN');
207+
expect(entry.label).toBe('仪表板');
208+
expect(entry.form.sections[0].label).toBe('布局');
209+
expect(entry.form.sections[0].fields[0].label).toBe('列数');
210+
});
211+
});
212+
213+
// ── C: the validator, over the bytes now served ─────────────────────────────
214+
215+
describe('#25785 C — a warm reopen is still answered 304', () => {
216+
it('the validator hashes the served body, and naming it answers 304', async () => {
217+
const service = makeService({ en: {}, 'zh-CN': zhTree() });
218+
const first = await read(service);
219+
expect(first.response.headers.ETag).toBe(validatorOf(first.response.body));
220+
221+
const again = await read(service, '/translations/zh-CN', {}, member({ 'if-none-match': first.response.headers.ETag }));
222+
expect(again.response.status).toBe(304);
223+
expect(again.response.body).toBeUndefined();
224+
});
225+
226+
it('a change confined to an unserved group serves the same bytes, so the validator holds', async () => {
227+
const bundles: Bundles = { en: {}, 'zh-CN': zhTree() };
228+
const service = makeService(bundles);
229+
const before = (await read(service)).response.headers.ETag;
230+
231+
bundles['zh-CN'] = { ...SERVED_GROUPS, metadataForms: { dashboard: { label: '看板' } } };
232+
expect((await read(service)).response.headers.ETag).toBe(before);
233+
234+
bundles['zh-CN'] = { ...SERVED_GROUPS, messages: { save: '存储' }, metadataForms: METADATA_FORMS };
235+
expect((await read(service)).response.headers.ETag).not.toBe(before);
236+
});
237+
});

‎packages/runtime/src/domains/i18n.ts‎

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,18 @@
2626
* The translation bundle is the one face a browser revalidates: it carries an
2727
* `ETag` and `Cache-Control: private, no-cache`, and a matching
2828
* `If-None-Match` is answered `304` with no body (#25785, see
29-
* {@link translationsAnswer}).
29+
* {@link translationsAnswer}). It is served without the groups the server
30+
* resolves itself, Studio's `metadataForms` (see {@link servedTranslations}).
3031
*/
3132

3233
import { createHash } from 'node:crypto';
3334
import {
3435
resolveLocale,
3536
shouldDenyAnonymous, ANONYMOUS_DENY_STATUS, ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_MESSAGE,
3637
} from '@objectstack/core';
37-
import { CoreServiceName, resolveObjectFieldLabels, toLocaleDescriptors } from '@objectstack/spec/system';
38+
import {
39+
CoreServiceName, SERVER_RESOLVED_TRANSLATION_GROUPS, resolveObjectFieldLabels, toLocaleDescriptors,
40+
} from '@objectstack/spec/system';
3841
import { isServiceServeable } from '../service-serveable.js';
3942
import type { TranslationData } from '@objectstack/spec/system';
4043
import type { HttpProtocolContext, HttpDispatcherResult } from '../http-dispatcher.js';
@@ -108,6 +111,28 @@ function ifNoneMatchHits(header: string | undefined, etag: string): boolean {
108111
});
109112
}
110113

114+
/**
115+
* [#25785] The document a translations read serves: the locale tree the i18n
116+
* service holds, without `SERVER_RESOLVED_TRANSLATION_GROUPS`, the groups the
117+
* server resolves before it serves what they translate. `metadataForms` is the
118+
* one today: `/meta/types` answers Studio's authoring forms already translated
119+
* from it, and no browser reads it here. `GetTranslationsResponseSchema`
120+
* declares the served face without it.
121+
*
122+
* ⛔ A COPY, never an edit of `translations`. `getTranslations` hands back the
123+
* service's own tree (the core fallback and service-i18n both return the stored
124+
* object), and that tree is the one `/meta/types` translates from: deleting the
125+
* group in place would leave every later Studio form in English.
126+
*/
127+
function servedTranslations(translations: Record<string, unknown>): Record<string, unknown> {
128+
const resolvedOnServer: readonly string[] = SERVER_RESOLVED_TRANSLATION_GROUPS;
129+
const served: Record<string, unknown> = {};
130+
for (const [group, value] of Object.entries(translations)) {
131+
if (!resolvedOnServer.includes(group)) served[group] = value;
132+
}
133+
return served;
134+
}
135+
111136
/**
112137
* [#25785] Answer a translations read with its validator. Every console open
113138
* read the whole locale bundle again (80–88 KB compressed on a hosted tenant)
@@ -239,11 +264,15 @@ export async function handleI18nRequest(
239264
const resolved = resolveLocale(locale, availableLocales);
240265
if (resolved && resolved !== locale) {
241266
translations = i18nService.getTranslations(resolved);
242-
return translationsAnswer(deps, { locale: resolved, requestedLocale: locale, translations }, context);
267+
return translationsAnswer(
268+
deps,
269+
{ locale: resolved, requestedLocale: locale, translations: servedTranslations(translations) },
270+
context,
271+
);
243272
}
244273
}
245274

246-
return translationsAnswer(deps, { locale, translations }, context);
275+
return translationsAnswer(deps, { locale, translations: servedTranslations(translations) }, context);
247276
}
248277

249278
// GET /i18n/labels/:object/:locale OR /i18n/labels/:object?locale=xx

‎packages/spec/src/api/protocol.zod.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import {
2828
import { RealtimePresenceSchema, TransportProtocol } from './realtime.zod';
2929
import { ObjectPermissionSchema, EffectiveObjectPermissionSchema, FieldPermissionSchema } from '../security/permission.zod';
3030
import { ActionDescriptorSchema } from '../automation/node-executor.zod';
31-
import { PlatformTranslationDataSchema } from '../system/translation.zod';
31+
import { ServedTranslationDataSchema } from '../system/translation.zod';
3232
// #5950 / #5882 — the ADR-0010 read-side protection envelope both metadata-item
3333
// responses publish. Same three vocabularies the resolver filters against, so a
3434
// value this spec cannot name is a value the resolver would have dropped.
@@ -3705,10 +3705,16 @@ export const GetTranslationsRequestSchema = lazySchema(() => z.object({
37053705
* `stack.translations` — so it carries the platform-only `settings` group and
37063706
* is typed against the platform face, not the per-app one
37073707
* (`system/translation.zod.ts`).
3708+
*
3709+
* Less the groups the server resolves itself (`SERVER_RESOLVED_TRANSLATION_GROUPS`,
3710+
* #25785): `metadataForms` stays in the i18n service, where `/meta/types`
3711+
* translates Studio's authoring forms from it, and is not part of this answer.
3712+
* `translations` is therefore {@link ServedTranslationDataSchema}, the platform
3713+
* face without those groups, closed so a body that still carries one fails it.
37083714
*/
37093715
export const GetTranslationsResponseSchema = lazySchema(() => z.object({
37103716
locale: z.string().describe('Locale code'),
3711-
translations: PlatformTranslationDataSchema.describe('Translation data'),
3717+
translations: ServedTranslationDataSchema.describe('Translation data'),
37123718
}));
37133719

37143720
export const GetFieldLabelsRequestSchema = lazySchema(() => z.object({

‎packages/spec/src/system/translation.zod.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2009,6 +2009,58 @@ export const PlatformTranslationDataSchema = lazySchema(() => strictObject({
20092009

20102010
export type PlatformTranslationData = z.input<typeof PlatformTranslationDataSchema>;
20112011

2012+
/**
2013+
* The platform groups the SERVED document leaves out —
2014+
* `GET /i18n/translations/:locale` answers {@link ServedTranslationDataSchema},
2015+
* the platform face without these (#25785).
2016+
*
2017+
* A group belongs here when the server resolves it before it serves the
2018+
* surface the group translates, so no browser reads it from the served
2019+
* document. `metadataForms` is the one member: it translates Studio's
2020+
* metadata-type authoring forms, and those reach Studio already translated —
2021+
* the `/meta/types` handler applies `resolveMetadataTypeLabel`,
2022+
* `resolveMetadataFormLabels` and `resolveMetadataFormSchemaTitles` to each
2023+
* entry over the i18n service's in-process bundle before it answers. Carried in
2024+
* the served document as well, it was the second-largest group of every console
2025+
* open (75 KB of 221 KB raw on `examples/app-crm` zh-CN) and nothing read it.
2026+
*
2027+
* ⛔ Only the served document leaves these out. Every bundle face still
2028+
* declares the group, and the i18n service still holds it: the serving door
2029+
* copies the document without them and never edits the service's own tree,
2030+
* which is the tree `/meta/types` translates from.
2031+
*/
2032+
export const SERVER_RESOLVED_TRANSLATION_GROUPS = ['metadataForms'] as const;
2033+
2034+
/**
2035+
* One locale of the SERVED translation document — what
2036+
* `GET /i18n/translations/:locale` answers: {@link PlatformTranslationDataSchema}
2037+
* without {@link SERVER_RESOLVED_TRANSLATION_GROUPS}.
2038+
*
2039+
* Its own `strictObject` rather than `.omit()` on the platform face, for the
2040+
* reason {@link appTranslationDataShape} gives against `.extend()`: the derived
2041+
* schema would keep the error map that closed over the base's keys, so a body
2042+
* still carrying `metadataForms` would be told the key it should not carry is
2043+
* a declared one. Closed, a served body that carries a server-resolved group
2044+
* fails this schema, which is what the response conformance suites parse with.
2045+
*/
2046+
export const ServedTranslationDataSchema = lazySchema(() => {
2047+
const { metadataForms: _serverResolved, ...appGroups } = appTranslationDataShape();
2048+
return strictObject({
2049+
surface: 'this locale of the served translation document',
2050+
history: TRANSLATION_HISTORY,
2051+
guidance: {
2052+
metadataForms:
2053+
"the served document leaves 'metadataForms' out: Studio's authoring forms are translated "
2054+
+ 'on the server, and /meta/types serves each form already in the requested locale.',
2055+
},
2056+
}, {
2057+
...appGroups,
2058+
...platformSettingsShape(),
2059+
}).describe('Served translation data — the platform groups the browser reads, without the server-resolved `metadataForms`');
2060+
});
2061+
2062+
export type ServedTranslationData = z.input<typeof ServedTranslationDataSchema>;
2063+
20122064
// ────────────────────────────────────────────────────────────────────────────
20132065
// Translation Bundle (all locales)
20142066
// ────────────────────────────────────────────────────────────────────────────

0 commit comments

Comments
 (0)