Skip to content

Commit beb000b

Browse files
committed
test(rest): pin the served plural of an object an extension renames (red on main)
Claude-Session: https://claude.ai/code/session_01Utp6CYaDMYnWxbm95qon7G Co-authored-by: Claude <noreply@anthropic.com>
1 parent 09720e2 commit beb000b

1 file changed

Lines changed: 267 additions & 0 deletions

File tree

Lines changed: 267 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,267 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #30391 — an object extension that renames `label` and sets no `pluralLabel`
5+
* is served as an object that declares no `pluralLabel`: the base's plural
6+
* names the old label, so neither it nor the catalog's translation of it is
7+
* served for the renamed object. The pair's own translation of the plural, when
8+
* the extension's `.custom` package ships one, is served first (ruling record
9+
* 6631250894: a translation in the pair, then the override's own text, then
10+
* the base's translation).
11+
*
12+
* Real `SchemaRegistry`, real protocol, real `RestServer`, an i18n service
13+
* whose catalog is the deployment's (every package's translations merged, the
14+
* pair's authored row included). Both `/meta/object` reads, `en` and `zh-CN`.
15+
*
16+
* The reference is MEASURED on the same boot, never written down: an object
17+
* that declares no `pluralLabel` (`crm_note`) is read through the same routes,
18+
* and the renamed object's plural must equal what that one serves.
19+
*/
20+
21+
import { describe, it, expect, vi } from 'vitest';
22+
import { SchemaRegistry, assertEngineFindOnePredicate } from '@objectstack/objectql';
23+
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
24+
import { RestServer } from './rest-server.js';
25+
26+
const BASE = 'com.acme.crm';
27+
const PAIR = 'com.acme.crm.custom';
28+
29+
/** The base package's object: both scalars declared. */
30+
const TASK = {
31+
name: 'crm_task',
32+
label: 'Task',
33+
pluralLabel: 'Tasks',
34+
fields: { title: { name: 'title', type: 'text', label: 'Title' } },
35+
};
36+
37+
/** The base package's object that declares no plural: the platform's own answer for a missing one. */
38+
const NOTE = {
39+
name: 'crm_note',
40+
label: 'Note',
41+
fields: { body: { name: 'body', type: 'text', label: 'Body' } },
42+
};
43+
44+
/** The base package's catalog: `en` repeats the source (what `i18n:extract` writes), `zh-CN` translates it. */
45+
const BASE_CATALOG: Record<string, any> = {
46+
en: { objects: { crm_task: { label: 'Task', pluralLabel: 'Tasks' }, crm_note: { label: 'Note' } } },
47+
'zh-CN': { objects: { crm_task: { label: '任务', pluralLabel: '任务' }, crm_note: { label: '备注' } } },
48+
};
49+
50+
const clone = <T>(v: T): T => JSON.parse(JSON.stringify(v)) as T;
51+
52+
type Row = Record<string, unknown>;
53+
54+
/**
55+
* Plain equality and `$in` (the by-name read asks `type` in both spellings);
56+
* any other operator or combinator is refused, so a matcher that ignored one
57+
* proves nothing.
58+
*/
59+
function matches(row: Row, where: Record<string, unknown> = {}): boolean {
60+
for (const [key, want] of Object.entries(where)) {
61+
if (want === undefined) continue;
62+
if (key.startsWith('$')) throw new Error(`fake engine: unsupported combinator ${key}`);
63+
if (want !== null && typeof want === 'object') {
64+
const ops = Object.keys(want);
65+
const list = (want as { $in?: unknown }).$in;
66+
if (ops.length !== 1 || !Array.isArray(list)) throw new Error(`fake engine: unsupported operator on ${key}`);
67+
if (!list.includes(row[key] ?? null)) return false;
68+
continue;
69+
}
70+
if ((row[key] ?? null) !== want) return false;
71+
}
72+
return true;
73+
}
74+
75+
/** A pair's saved `translation` row, as `getPairTranslationBundle` reads it. */
76+
function pairTranslationRow(locale: string, objects: Record<string, unknown>): Row {
77+
const name = `pair_${locale}`;
78+
return {
79+
id: name, type: 'translation', name, package_id: PAIR, organization_id: null, state: 'active',
80+
metadata: JSON.stringify({ name, locale, objects }),
81+
};
82+
}
83+
84+
/** Deep-merge `top` over `under`, one locale's data: the deployment catalog's shape. */
85+
function overlay(under: any, top: any): any {
86+
if (!top) return under;
87+
const out: any = { ...under };
88+
for (const [k, v] of Object.entries(top)) {
89+
out[k] = v && typeof v === 'object' && under?.[k] && typeof under[k] === 'object' ? overlay(under[k], v) : v;
90+
}
91+
return out;
92+
}
93+
94+
function mockServer() {
95+
return {
96+
get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(),
97+
use: vi.fn(), listen: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined),
98+
};
99+
}
100+
101+
interface Boot {
102+
/** The `.custom` extension of `crm_task`, or none. */
103+
extension?: Record<string, unknown>;
104+
/** The pair's own translations, locale → `objects` data; they also reach the deployment catalog. */
105+
pairObjects?: Record<string, Record<string, unknown>>;
106+
}
107+
108+
/** Boot one host and answer `read(locale, name)` → the served object on both reads. */
109+
function boot(opts: Boot = {}) {
110+
const registry = new SchemaRegistry();
111+
registry.registerObject(clone(TASK) as never, BASE, undefined, 'own');
112+
registry.registerObject(clone(NOTE) as never, BASE, undefined, 'own');
113+
if (opts.extension) registry.registerObjectExtension({ extend: 'crm_task', ...clone(opts.extension) }, PAIR);
114+
115+
const rows: Row[] = Object.entries(opts.pairObjects ?? {}).map(([locale, objects]) => pairTranslationRow(locale, objects));
116+
const read = async (table: string, q?: { where?: Record<string, unknown>; limit?: number }) => {
117+
const found = table === 'sys_metadata' ? rows.filter((r) => matches(r, q?.where)) : [];
118+
return typeof q?.limit === 'number' ? found.slice(0, q.limit) : found;
119+
};
120+
const engine = {
121+
registry,
122+
find: read,
123+
findOne: async (table: string, q: { where: Record<string, unknown> }) => {
124+
assertEngineFindOnePredicate(table, q);
125+
return (await read(table, q))[0] ?? null;
126+
},
127+
};
128+
const protocol = new ObjectStackProtocolImplementation(engine as never, undefined, 'env_test');
129+
130+
// The deployment catalog: every package's translations deep-merged, the pair's authored rows on top.
131+
const catalog = (locale: string) => overlay(BASE_CATALOG[locale], opts.pairObjects?.[locale] && { objects: opts.pairObjects[locale] });
132+
const i18nService = {
133+
getLocales: () => ['en', 'zh-CN'],
134+
getTranslations: (locale: string) => catalog(locale),
135+
getDefaultLocale: () => 'en',
136+
};
137+
138+
const rest = new RestServer(
139+
mockServer() as never, protocol as never, { api: { requireAuth: false } } as never,
140+
undefined, undefined, undefined, undefined, undefined,
141+
undefined, undefined, undefined, undefined, undefined,
142+
// i18nServiceProvider — the 14th constructor argument.
143+
async () => i18nService as never,
144+
);
145+
(rest as unknown as { resolveExecCtx: () => Promise<unknown> }).resolveExecCtx = async () => ({ userId: 'u1', systemPermissions: [] });
146+
rest.registerRoutes();
147+
const routes = rest.getRouteManager();
148+
149+
const run = async (path: string, params: Record<string, string>, locale: string) => {
150+
const entry = routes.get('GET', path);
151+
if (!entry) throw new Error(`route not registered: ${path}`);
152+
let body: any;
153+
const res = {
154+
status: () => res, header: () => res,
155+
json: (b: unknown) => { body = b; }, send: (b: unknown) => { body = b; },
156+
} as unknown as Parameters<typeof entry.handler>[1];
157+
await entry.handler(
158+
{ params, query: {}, headers: { 'accept-language': locale }, method: 'GET', path } as unknown as Parameters<typeof entry.handler>[0],
159+
res,
160+
);
161+
return body;
162+
};
163+
164+
/** The served object on the by-name read and on the list read, as `{ label, pluralLabel }`. */
165+
return async (locale: string, name: string) => {
166+
const byName = (await run('/api/v1/meta/:type/:name', { type: 'object', name }, locale))?.item;
167+
const listBody = await run('/api/v1/meta/:type', { type: 'object' }, locale);
168+
const listed = (Array.isArray(listBody) ? listBody : listBody?.items ?? []).find((o: any) => o?.name === name);
169+
const scalars = (doc: any) => ({
170+
label: doc?.label,
171+
pluralLabel: doc?.pluralLabel,
172+
hasPluralLabel: !!doc && Object.prototype.hasOwnProperty.call(doc, 'pluralLabel'),
173+
});
174+
return { byName: scalars(byName), listed: scalars(listed) };
175+
};
176+
}
177+
178+
const LOCALES = ['en', 'zh-CN'] as const;
179+
180+
describe('#30391 — the platform\'s own answer for an object with no pluralLabel (the reference)', () => {
181+
for (const locale of LOCALES) {
182+
it(`an object that declares no pluralLabel is served with none [${locale}]`, async () => {
183+
const read = boot();
184+
const note = await read(locale, 'crm_note');
185+
expect(note.byName.hasPluralLabel).toBe(false);
186+
expect(note.listed.hasPluralLabel).toBe(false);
187+
});
188+
}
189+
});
190+
191+
describe('#30391 — an extension that renames only label', () => {
192+
const RENAME = { label: 'Work Item' };
193+
194+
for (const locale of LOCALES) {
195+
it(`serves the renamed label and what an object with no pluralLabel serves [${locale}]`, async () => {
196+
const read = boot({ extension: RENAME });
197+
const reference = await read(locale, 'crm_note');
198+
const task = await read(locale, 'crm_task');
199+
for (const served of [task.byName, task.listed]) {
200+
expect(served.label).toBe('Work Item');
201+
expect(served.hasPluralLabel).toBe(reference.byName.hasPluralLabel);
202+
expect(served.pluralLabel).toBe(reference.byName.pluralLabel);
203+
}
204+
});
205+
}
206+
207+
it('serves the pair\'s own translation of the plural first, where the pair ships one', async () => {
208+
const read = boot({ extension: RENAME, pairObjects: { 'zh-CN': { crm_task: { pluralLabel: '工作项' } } } });
209+
const zh = await read('zh-CN', 'crm_task');
210+
expect(zh.byName.pluralLabel).toBe('工作项');
211+
expect(zh.listed.pluralLabel).toBe('工作项');
212+
// A locale the pair does not translate is served no plural, as before.
213+
const en = await read('en', 'crm_task');
214+
expect(en.byName.hasPluralLabel).toBe(false);
215+
expect(en.listed.hasPluralLabel).toBe(false);
216+
});
217+
218+
it('a deployment translation that is not the pair\'s is not the pair\'s translation', async () => {
219+
// The base's catalog translates its OWN plural: with the pair silent,
220+
// that entry is exactly what must not come back for the renamed object.
221+
const read = boot({ extension: RENAME, pairObjects: { 'zh-CN': { crm_task: { label: '工作项' } } } });
222+
const zh = await read('zh-CN', 'crm_task');
223+
expect(zh.byName.hasPluralLabel).toBe(false);
224+
expect(zh.listed.hasPluralLabel).toBe(false);
225+
});
226+
});
227+
228+
describe('#30391 — controls', () => {
229+
it('an extension that sets pluralLabel is served as set', async () => {
230+
const read = boot({ extension: { label: 'Work Item', pluralLabel: 'Work Items' } });
231+
for (const locale of LOCALES) {
232+
const task = await read(locale, 'crm_task');
233+
for (const served of [task.byName, task.listed]) {
234+
expect(served.label).toBe('Work Item');
235+
expect(served.pluralLabel).toBe('Work Items');
236+
}
237+
}
238+
});
239+
240+
it('an extension that sets only pluralLabel keeps the base label and serves its plural', async () => {
241+
const read = boot({ extension: { pluralLabel: 'Work Items' } });
242+
const zh = await read('zh-CN', 'crm_task');
243+
expect(zh.byName.label).toBe('任务');
244+
expect(zh.byName.pluralLabel).toBe('Work Items');
245+
});
246+
247+
it('an extension that changes neither keeps the base plural and its translation', async () => {
248+
const read = boot({ extension: { fields: { region__c: { name: 'region__c', type: 'text', label: 'Region' } } } });
249+
const en = await read('en', 'crm_task');
250+
const zh = await read('zh-CN', 'crm_task');
251+
for (const served of [en.byName, en.listed]) expect(served).toEqual({ label: 'Task', pluralLabel: 'Tasks', hasPluralLabel: true });
252+
for (const served of [zh.byName, zh.listed]) expect(served).toEqual({ label: '任务', pluralLabel: '任务', hasPluralLabel: true });
253+
});
254+
255+
it('an extension that repeats the base label is no rename', async () => {
256+
const read = boot({ extension: { label: 'Task' } });
257+
const zh = await read('zh-CN', 'crm_task');
258+
expect(zh.byName.pluralLabel).toBe('任务');
259+
expect(zh.listed.pluralLabel).toBe('任务');
260+
});
261+
262+
it('an object nothing extends keeps its plural and its translation', async () => {
263+
const read = boot({ extension: { label: 'Work Item' } });
264+
const zh = await read('zh-CN', 'crm_note');
265+
expect(zh.byName.label).toBe('备注');
266+
});
267+
});

0 commit comments

Comments
 (0)