Skip to content

Commit b475fae

Browse files
committed
fix(service-datasource): serve the driver catalog's words in the requester's language
GET /api/v1/datasources/drivers served every driver label, description and connection field title/description in English, so a Chinese console's New datasource dialog read Filename, Auto-migrate schema, Host and Port in English. The route now reads the requester's language (Accept-Language, else ?locale) and serves driverCatalogFor(locale), which negotiates through resolveLocaleAmong and overlays a service-local zh-CN table on the English catalog. Any word without a translation stays English. Claude-Session: https://claude.ai/code/session_016WV4czJVaL8SDBxjng4RLk Co-authored-by: Claude <noreply@anthropic.com>
1 parent f4d568b commit b475fae

6 files changed

Lines changed: 420 additions & 3 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/service-datasource': patch
3+
---
4+
5+
fix(service-datasource): the datasource driver catalog serves its words in the requester's language, so the New datasource dialog reads in one language
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`GET /api/v1/datasources/drivers` now serves each driver's label and description, and each connection field's `title` and `description` (Filename, Auto-migrate schema, Host, Port, …), in the language the request names: the top `Accept-Language` tag, else `?locale=`, matched by the platform's locale ladder (`resolveLocaleAmong`), so `zh`, `zh-cn` and `zh-SG` reach `zh-CN`. Simplified Chinese is translated for every offered driver. English requests, languages without a translation, and any word a translation leaves out are served the English text, never a key. `DRIVER_CATALOG` stays the English catalog, and the new `driverCatalogFor(locale)` in the package source builds the localized one; ids, icons, types and defaults are unchanged in every language.

‎packages/services/service-datasource/src/__tests__/admin-routes.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,38 @@ describe('registerDatasourceAdminRoutes (real HonoHttpServer)', () => {
122122
expect(sqlite!.configSchema?.properties?.filename?.type).toBe('string');
123123
});
124124

125+
it('GET /api/v1/datasources/drivers serves the words in the requester\'s language', async () => {
126+
const app = mount({});
127+
type Served = { data: { drivers: Array<{ id: string; label: string; description?: string; configSchema: any }> } };
128+
const read = async (init?: RequestInit, path = '/api/v1/datasources/drivers') => {
129+
const res = await app.fetch(json(path, init));
130+
expect(res.status).toBe(200);
131+
const drivers = ((await res.json()) as Served).data.drivers;
132+
return (id: string) => drivers.find((d) => d.id === id)!;
133+
};
134+
135+
// The console sends its language as `Accept-Language` on every API call.
136+
const zh = await read({ headers: { 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8' } });
137+
expect(zh('sqlite').configSchema.properties.filename.title).toBe('文件名');
138+
expect(zh('sqlite').configSchema.properties.autoMigrate.title).toBe('自动迁移表结构');
139+
expect(zh('postgres').configSchema.properties.host.title).toBe('主机');
140+
expect(zh('postgres').configSchema.properties.port.title).toBe('端口');
141+
expect(zh('mysql').description).toBe('MySQL 或 MariaDB 连接。');
142+
// A word the locale does not translate is the English one, not a key.
143+
expect(zh('sqlite').label).toBe('SQLite');
144+
145+
// `?locale=` when no header names a language.
146+
const query = await read(undefined, '/api/v1/datasources/drivers?locale=zh-CN');
147+
expect(query('sqlite').configSchema.properties.filename.title).toBe('文件名');
148+
149+
// English and an untranslated language are served the English words.
150+
for (const lang of ['en-US', 'fr-FR']) {
151+
const en = await read({ headers: { 'accept-language': lang } });
152+
expect(en('sqlite').configSchema.properties.filename.title, lang).toBe('Filename');
153+
expect(en('postgres').configSchema.properties.host.title, lang).toBe('Host');
154+
}
155+
});
156+
125157
it('GET /api/v1/datasources/:name/remote-tables lists remote tables', async () => {
126158
const listRemoteTables = vi.fn().mockResolvedValue([{ name: 'customers', columnCount: 4 }]);
127159
const app = mount({ listRemoteTables });

‎packages/services/service-datasource/src/__tests__/driver-catalog.test.ts‎

Lines changed: 123 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ import {
2323
type BuiltinDriverId,
2424
} from '@objectstack/spec/data';
2525

26-
import { DRIVER_CATALOG } from '../driver-catalog.js';
26+
import { DRIVER_CATALOG, driverCatalogFor } from '../driver-catalog.js';
27+
import { DRIVER_CATALOG_TRANSLATIONS } from '../driver-catalog-translations.js';
2728

2829
describe('DRIVER_CATALOG', () => {
2930
it('serves the spec projection for every offered driver', () => {
@@ -82,3 +83,124 @@ describe('DRIVER_CATALOG', () => {
8283
}
8384
});
8485
});
86+
87+
type JsonProp = { title?: string; description?: string; type?: string };
88+
const propsOf = (entry: { configSchema: Record<string, unknown> }) =>
89+
(entry.configSchema as { properties: Record<string, JsonProp> }).properties;
90+
const entryOf = (catalog: typeof DRIVER_CATALOG, id: string) => {
91+
const entry = catalog.find((d) => d.id === id);
92+
if (!entry) throw new Error(`no ${id} entry`);
93+
return entry;
94+
};
95+
96+
/**
97+
* The catalog's words in the requester's language. The New datasource dialog
98+
* draws exactly what the drivers route serves and has no key of its own for
99+
* these words, so a Chinese console read `Filename`, `Auto-migrate schema`,
100+
* `Host` and `Port` in English until the route served them translated.
101+
*/
102+
describe('driverCatalogFor', () => {
103+
it('serves zh-CN words for SQLite and the network drivers', () => {
104+
const zh = driverCatalogFor('zh-CN');
105+
106+
const sqlite = entryOf(zh, 'sqlite');
107+
expect(sqlite.description).toBe('基于文件(或内存)的 SQL 数据库,适合本地开发和小型部署。');
108+
expect(propsOf(sqlite).filename.title).toBe('文件名');
109+
expect(propsOf(sqlite).filename.description).toBe('数据库文件路径,或填 ":memory:" 使用临时内存数据库');
110+
expect(propsOf(sqlite).autoMigrate.title).toBe('自动迁移表结构');
111+
112+
const postgres = entryOf(zh, 'postgres');
113+
expect(propsOf(postgres).host).toMatchObject({ title: '主机', description: '主机地址' });
114+
expect(propsOf(postgres).port).toMatchObject({ title: '端口', description: '端口号' });
115+
expect(propsOf(postgres).password.title).toBe('密码');
116+
117+
expect(propsOf(entryOf(zh, 'mysql')).host.title).toBe('主机');
118+
expect(propsOf(entryOf(zh, 'mongodb')).port.title).toBe('端口');
119+
expect(entryOf(zh, 'memory').label).toBe('内存');
120+
});
121+
122+
it('keeps everything but the words: ids, icons, types and defaults are the English entry\'s', () => {
123+
const zh = driverCatalogFor('zh-CN');
124+
expect(zh.map((d) => [d.id, d.icon])).toEqual(DRIVER_CATALOG.map((d) => [d.id, d.icon]));
125+
for (const entry of zh) {
126+
const english = propsOf(entryOf(DRIVER_CATALOG, entry.id));
127+
const translated = propsOf(entry);
128+
expect(Object.keys(translated), entry.id).toEqual(Object.keys(english));
129+
for (const key of Object.keys(english)) {
130+
const { title: _t, description: _d, ...rest } = translated[key];
131+
const { title: _et, description: _ed, ...englishRest } = english[key];
132+
expect(rest, `${entry.id}.${key}`).toEqual(englishRest);
133+
}
134+
}
135+
});
136+
137+
it('negotiates the requested tag through the platform ladder', () => {
138+
for (const tag of ['zh', 'zh-cn', 'zh-SG', 'zh-Hans']) {
139+
expect(propsOf(entryOf(driverCatalogFor(tag), 'sqlite')).filename.title, tag).toBe('文件名');
140+
}
141+
});
142+
143+
it('serves English for no locale, en, or a locale nothing translates', () => {
144+
for (const tag of [undefined, '', 'en', 'en-US', 'fr', 'constructor', '__proto__']) {
145+
expect(driverCatalogFor(tag), String(tag)).toBe(DRIVER_CATALOG);
146+
}
147+
expect(propsOf(entryOf(DRIVER_CATALOG, 'sqlite')).filename.title).toBe('Filename');
148+
expect(propsOf(entryOf(DRIVER_CATALOG, 'postgres')).host.title).toBe('Host');
149+
});
150+
151+
it('falls back to the English word where a locale has none, never to a key', () => {
152+
const zh = driverCatalogFor('zh-CN');
153+
// Product names are not in the zh-CN table: the English label is served.
154+
expect(entryOf(zh, 'sqlite').label).toBe('SQLite');
155+
expect(entryOf(zh, 'postgres').label).toBe('PostgreSQL');
156+
// The memory driver's fields carry a description and no title in English;
157+
// the translation adds no title, so the form still names the field by key.
158+
expect(propsOf(entryOf(zh, 'memory')).strictMode.title).toBeUndefined();
159+
expect(propsOf(entryOf(zh, 'memory')).strictMode.description).toBe('记录不存在时抛出错误,而不是返回 null');
160+
});
161+
162+
it('never writes the spec projection it overlays', () => {
163+
driverCatalogFor('zh-CN');
164+
const sqlite = getDriverConfigJsonSchemaById('sqlite') as { properties: Record<string, JsonProp> };
165+
expect(sqlite.properties.filename.title).toBe('Filename');
166+
expect(propsOf(entryOf(DRIVER_CATALOG, 'sqlite')).filename.title).toBe('Filename');
167+
expect(entryOf(DRIVER_CATALOG, 'memory').label).toBe('In-Memory');
168+
});
169+
});
170+
171+
/**
172+
* Every locale in `driver-catalog-translations.ts` against the served shape:
173+
* a driver or field it names must exist, so a renamed field cannot leave a
174+
* translation that silently stops applying, and every field word the English
175+
* form shows must be translated, so a field the spec adds goes red here rather
176+
* than reading English in a translated dialog.
177+
*/
178+
describe('DRIVER_CATALOG_TRANSLATIONS coverage', () => {
179+
const offered = new Set(DRIVER_CATALOG.map((d) => d.id));
180+
181+
for (const [locale, table] of Object.entries(DRIVER_CATALOG_TRANSLATIONS)) {
182+
it(`${locale}: names only drivers and fields the catalog serves`, () => {
183+
for (const [id, text] of Object.entries(table)) {
184+
expect(offered.has(id), `${locale}.${id}`).toBe(true);
185+
const props = propsOf(entryOf(DRIVER_CATALOG, id));
186+
for (const key of Object.keys(text?.fields ?? {})) {
187+
expect(Object.prototype.hasOwnProperty.call(props, key), `${locale}.${id}.fields.${key}`).toBe(true);
188+
}
189+
}
190+
});
191+
192+
it(`${locale}: translates every driver description and every field word the English form shows`, () => {
193+
for (const entry of DRIVER_CATALOG) {
194+
const text = table[entry.id as keyof typeof table];
195+
expect(text?.description, `${locale}.${entry.id}.description`).toBeTruthy();
196+
for (const [key, prop] of Object.entries(propsOf(entry))) {
197+
const field = text?.fields?.[key];
198+
if (prop.title !== undefined) expect(field?.title, `${locale}.${entry.id}.${key}.title`).toBeTruthy();
199+
if (prop.description !== undefined) {
200+
expect(field?.description, `${locale}.${entry.id}.${key}.description`).toBeTruthy();
201+
}
202+
}
203+
}
204+
});
205+
}
206+
});

‎packages/services/service-datasource/src/admin-routes.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import {
3535
} from '@objectstack/core';
3636
import type { TenancyPosture } from '@objectstack/spec/security';
3737
import type { ErrorCode } from '@objectstack/spec/api';
38+
import { preferredLocaleFromHeader } from '@objectstack/spec/system';
3839
// The slots this module resolves, by their declared contracts. Erasing a
3940
// lookup to `any` is banned (#4127/#4176/#4202/#4251) and the ban is right
4041
// here: `IAuthService` is what declares BOTH shapes of the session accessor
@@ -44,7 +45,7 @@ import type { ErrorCode } from '@objectstack/spec/api';
4445
import type { IAuthService, IDataEngine, IHttpServer } from '@objectstack/spec/contracts';
4546
// The declared envelope is written in ONE place for the whole platform (#3973).
4647
import { inProcessSessionReadInput, sendOk, sendError } from '@objectstack/types';
47-
import { DRIVER_CATALOG } from './driver-catalog.js';
48+
import { driverCatalogFor } from './driver-catalog.js';
4849
import { DRIVER_CATALOG_SEGMENT } from './datasource-route-reserved-names.js';
4950
// [#27618] The package's one "no such datasource" refusal: GET answers an
5051
// unknown name in its words, as every other by-name door does.
@@ -201,6 +202,19 @@ function toWebHeaders(raw: unknown): Headers | undefined {
201202
return undefined;
202203
}
203204

205+
/**
206+
* The requester's display language, read the way the REST metadata door and
207+
* the settings routes read it: the top `Accept-Language` tag, else a string
208+
* `?locale=`. The console sends its own language as `Accept-Language` on every
209+
* API call. It picks the language of served words only and authorizes nothing.
210+
*/
211+
function requestLocaleOf(req: { headers?: unknown; query?: Record<string, unknown> } | undefined): string | undefined {
212+
const preferred = preferredLocaleFromHeader(toWebHeaders(req?.headers)?.get('accept-language'));
213+
if (preferred) return preferred;
214+
const query = req?.query?.locale;
215+
return typeof query === 'string' && query.length > 0 ? query : undefined;
216+
}
217+
204218
/**
205219
* A `getSession(headers)` bound to the kernel's `auth` service, or `undefined`
206220
* when this deployment registers none.
@@ -705,9 +719,10 @@ export function registerDatasourceAdminRoutes(
705719
// Catalog of connection drivers + their JSON-Schema config (drives the
706720
// Studio connection form). Static metadata — no service dependency, so it
707721
// is always available even before any datasource-admin service is wired.
722+
// Its words are served in the requester's language (`driverCatalogFor`).
708723
server.get(`${root}/${DRIVER_CATALOG_SEGMENT}`, async (req: any, res: any) => {
709724
if (await requireDatasourceAdmin(req, res)) return;
710-
sendOk(res, { drivers: DRIVER_CATALOG });
725+
sendOk(res, { drivers: driverCatalogFor(requestLocaleOf(req)) });
711726
});
712727

713728
// Read-only schema introspection for the Studio "sync objects" flow.
Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The driver catalog's words in the languages the New datasource dialog is
5+
* written in, keyed by locale tag.
6+
*
7+
* `GET /api/v1/datasources/drivers` serves every word the dialog shows about a
8+
* driver: the entry's `label` and `description`, and each connection field's
9+
* JSON-Schema `title` and `description`. The console has no key of its own for
10+
* any of them, so before this table a Chinese console read `Filename`,
11+
* `Auto-migrate schema`, `Host` and `Port` in English beside Chinese text
12+
* everywhere else in the dialog.
13+
*
14+
* ## What is translated, and what stays English
15+
*
16+
* English is the source and is never restated here: the entry words come from
17+
* `CURATED` in `driver-catalog.ts`, the field words from the spec's per-driver
18+
* zod schemas, projected to JSON Schema. A locale below overrides a word only
19+
* where the English side has one, and any word it leaves out is served in
20+
* English (`driverCatalogFor`), never as a key.
21+
*
22+
* The fields are the top-level properties of each driver's `configSchema`, the
23+
* ones the dialog draws as inputs. Nested shapes (the memory driver's
24+
* persistence variants) are not drawn, so they are not translated.
25+
*
26+
* `zh-CN` is the one locale today because the dialog's own strings are written
27+
* in English and Chinese only (the console's `studio` namespace); a Japanese or
28+
* Spanish dialog is English around these fields, so translating the fields
29+
* alone would make it read in two languages the other way round. A locale is
30+
* added here when the dialog gains it.
31+
*
32+
* `__tests__/driver-catalog.test.ts` holds every locale to the served
33+
* shape: each driver and field named here exists, and every field word the
34+
* English side carries is translated.
35+
*/
36+
37+
import type { BuiltinDriverId } from '@objectstack/spec/data';
38+
39+
/** One connection field's words: the JSON-Schema `title` and `description`. */
40+
export interface DriverFieldText {
41+
title?: string;
42+
description?: string;
43+
}
44+
45+
/** One driver's words in one locale. */
46+
export interface DriverCatalogText {
47+
label?: string;
48+
description?: string;
49+
/** Keyed by the field's property name in the driver's `configSchema`. */
50+
fields?: Readonly<Record<string, DriverFieldText>>;
51+
}
52+
53+
/** Every curated driver's words in one locale. */
54+
export type DriverCatalogLocaleText = Readonly<Partial<Record<BuiltinDriverId, DriverCatalogText>>>;
55+
56+
// Fields several drivers share, in the same words.
57+
const ZH_HOST: DriverFieldText = { title: '主机', description: '主机地址' };
58+
const ZH_PORT: DriverFieldText = { title: '端口', description: '端口号' };
59+
const ZH_DATABASE: DriverFieldText = { title: '数据库', description: '数据库名称' };
60+
const ZH_USERNAME: DriverFieldText = { title: '用户', description: '认证用户' };
61+
const ZH_PASSWORD: DriverFieldText = {
62+
title: '密码',
63+
description:
64+
'通过连接表单的密钥字段或 `external.credentialsRef` 设置,加密存入 `sys_secret`,从不存放在 `config` 中。'
65+
+ '在代码中定义的数据源(`defineDatasource`)不在声明中写凭据:连接时从按数据源名称派生的运行时环境变量读取'
66+
+ '(名为 `warehouse` 的数据源读取 `OS_DATASOURCE_WAREHOUSE_PASSWORD`),'
67+
+ '`os serve` / `os start` 默认启用此方式(`OS_DATASOURCE_ENV_CREDENTIALS=on`)。',
68+
};
69+
const ZH_SSL: DriverFieldText = {
70+
title: '使用 SSL/TLS',
71+
description: '启用 TLS。证书填写在数据源级别的 `ssl` 配置块中。',
72+
};
73+
const ZH_AUTO_MIGRATE: DriverFieldText = {
74+
title: '自动迁移表结构',
75+
description: '仅限开发环境:以非破坏性方式自动修复表结构',
76+
};
77+
const ZH_URL_NO_PASSWORD = '连接 URI(优先于各单项字段;不得内嵌密码,请改为绑定密钥)';
78+
79+
/** 简体中文 (zh-CN). */
80+
const zhCN: DriverCatalogLocaleText = {
81+
memory: {
82+
label: '内存',
83+
description: '用于开发、测试和原型验证的临时内存驱动,无需连接设置。',
84+
fields: {
85+
initialData: { description: '按对象名称组织的预置数据' },
86+
strictMode: { description: '记录不存在时抛出错误,而不是返回 null' },
87+
persistence: { description: '持久化配置(可选;默认纯内存)' },
88+
},
89+
},
90+
sqlite: {
91+
description: '基于文件(或内存)的 SQL 数据库,适合本地开发和小型部署。',
92+
fields: {
93+
filename: { title: '文件名', description: '数据库文件路径,或填 ":memory:" 使用临时内存数据库' },
94+
autoMigrate: ZH_AUTO_MIGRATE,
95+
},
96+
},
97+
postgres: {
98+
description: 'PostgreSQL 连接。填写主机、端口和数据库,或提供连接 URL。',
99+
fields: {
100+
url: {
101+
title: '连接 URL',
102+
description: '连接 URI(优先于各单项字段;必须是 `pg` 能解析的 URL;不得内嵌密码,请改为绑定密钥)',
103+
},
104+
host: ZH_HOST,
105+
port: ZH_PORT,
106+
database: ZH_DATABASE,
107+
username: ZH_USERNAME,
108+
password: ZH_PASSWORD,
109+
ssl: ZH_SSL,
110+
schema: { title: '模式', description: '默认模式(knex searchPath)' },
111+
applicationName: { title: '应用名称', description: 'Postgres 的 application_name' },
112+
statementTimeout: { title: '语句超时(毫秒)', description: '中止运行时间超过此值的语句(毫秒)' },
113+
autoMigrate: ZH_AUTO_MIGRATE,
114+
},
115+
},
116+
mysql: {
117+
description: 'MySQL 或 MariaDB 连接。',
118+
fields: {
119+
url: { title: '连接 URL', description: ZH_URL_NO_PASSWORD },
120+
host: ZH_HOST,
121+
port: ZH_PORT,
122+
database: ZH_DATABASE,
123+
username: ZH_USERNAME,
124+
password: ZH_PASSWORD,
125+
ssl: ZH_SSL,
126+
autoMigrate: ZH_AUTO_MIGRATE,
127+
},
128+
},
129+
mongodb: {
130+
description: '通过连接 URI 连接 MongoDB。',
131+
fields: {
132+
url: { title: '连接 URI', description: ZH_URL_NO_PASSWORD },
133+
database: ZH_DATABASE,
134+
host: ZH_HOST,
135+
port: ZH_PORT,
136+
username: ZH_USERNAME,
137+
password: ZH_PASSWORD,
138+
authSource: { title: '认证库', description: '认证数据库' },
139+
options: {
140+
description:
141+
'额外的 MongoClient 选项(replicaSet、tls、超时等)。以凭据命名的键(`password`、`authToken` 及其旧别名)'
142+
+ '在任何层级都会被直接拒绝,请通过连接表单或 external.credentialsRef 绑定密钥。'
143+
+ '`proxyPassword`、`tlsCertificateKeyFilePassword`、`key` 和 `passphrase` 会被接受,并以明文静态存储;'
144+
+ '它们只在读回数据源时被遮蔽,写入时不会被拒绝。',
145+
},
146+
},
147+
},
148+
};
149+
150+
/**
151+
* The catalog's translations, by locale tag. A requested locale is matched
152+
* against these keys by the platform's one negotiation ladder
153+
* (`resolveLocaleAmong`), so `zh`, `zh-cn` and `zh-SG` reach `zh-CN`.
154+
*/
155+
export const DRIVER_CATALOG_TRANSLATIONS: Readonly<Record<string, DriverCatalogLocaleText>> = {
156+
'zh-CN': zhCN,
157+
};

0 commit comments

Comments
 (0)