Skip to content

Commit c94191d

Browse files
fix(service-print, spec): the print door's 5xx sentences follow the request's language (#37272)
Fixes #37260 repo:objectstack#4 · os-justin · session_01QSeKYnagJvGbCtNg2PhvgW Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:在中文(以及日文、西班牙文)界面里点击打印,若服务器上的打印引擎未就绪、打印超时或服务器出错,提示条现在用界面语言显示;英文界面与以前一字不差。 - 为什么做:报价单打印失败时中文界面弹出整句英文,看起来像坏了,业务用户也看不懂;这是该缺陷卡(打印失败提示不跟随界面语言)本身。 - 出错会怎样:最坏情况是某种语言的提示措辞不够好,状态码与错误码都不变,不影响打印本身;可直接撤回本改动。 - 要你做什么:无。 ## What changes - `packages/spec/src/system/operation-message.ts`: four keys in the platform's operation-message catalog (`BUILTIN_OPERATION_MESSAGES`), in all four locales it carries (`en`, `zh-CN`, `ja-JP`, `es-ES`): `print_engine_unavailable` (503), `print_timed_out` (504), `print_failed` (the 5xx fallback) and `print_caller_unresolved` (the door's caller-resolution 500). English is byte-identical to the fixed text the door answered before. No placeholder; the header documents them beside the other keys. - `packages/services/service-print/src/print-routes.ts`: `serverAnswerFor(status, locale)` maps the status to its catalog key and renders it through `operationUserMessage` (`@objectstack/core`), the shared helper the platform's other localized refusals use; `relayPrintFailure` and the caller-resolution fault pass the request's top `Accept-Language` tag (`preferredLocaleFromHeader`). The door reads no query parameter, so `?locale` is not a source. Code, status, the fault log and the 4xx relay are unchanged. - `packages/services/service-print/vitest.config.ts`: aliases `@objectstack/spec/system` to source like the other spec subpaths, so the new import is judged against this checkout, never a stale `dist/`. The mechanism reused, not a new one: the operation-message catalog plus `operationUserMessage` is the platform's one seat for localized user-facing server sentences (its header: "a second mechanism for the second producer is exactly what this module exists to prevent"). The door's `message` itself is localized, because `sendServerFault`'s `message` is already the route's generic user-facing text (the thrown detail goes only to the fault log) and `sendServerFault` declares no `userMessage` channel; widening it would change an `@objectstack/types` export outside this card's file surface. The action path from the repro (`POST /api/v1/actions/crm_quote/print_quote`) produces no sentence of its own for these failures: the `/actions` door forwards a same-origin `type: 'api'` action in-process with `accept-language` on its header allowlist (`API_FORWARD_HEADER_ALLOWLIST`, `packages/runtime/src/action-execution.ts`) and relays the target's refusal envelope with its `message` as written (`restAnswerOf`, `forward-refused`, `packages/runtime/src/action-dispatch.ts`). So fixing the door fixes the action toast; nothing changed in `packages/runtime`. Bounded in-place fix, declared: the caller-resolution 500 (`The caller of this print could not be resolved.`) is the same door's own 5xx sentence, the same defect class, the same file in the claim's surface, the same gate family; it is localized the same way and pinned below. ### Read first 1. `packages/services/service-print/src/print-routes.ts` (the `requestLocaleOf` / `serverAnswerKeyFor` / `serverAnswerFor` hunk) — the only behaviour change. 2. `packages/spec/src/system/operation-message.ts` — the 16 new catalog strings; the zh-CN, ja-JP and es-ES wording is the review risk. 3. `packages/services/service-print/src/print-routes.test.ts` — the new top-level `describe`. ### Two-minute verification `pnpm --filter @objectstack/service-print exec vitest run --maxWorkers=2 src/print-routes.test.ts` — expect 36 passed, including ten under "its own 5xx sentences, in the request's language". ## Tests All at head `3dfbfdb5a`. - `pnpm --filter @objectstack/service-print test` — Test Files 9 passed (9), Tests 145 passed (145). - `pnpm --filter @objectstack/spec test` — Test Files 891 passed (891), Tests 28371 passed, 1 todo. - `pnpm --filter @objectstack/service-print typecheck` exit 0; `pnpm --filter @objectstack/spec typecheck` exit 0 (tsc, scripts and test typecheck). - New pins (door, `print-routes.test.ts`): 503, 504 and 500 under `accept-language: zh-CN,zh;q=0.9,en;q=0.8` answer the zh-CN catalog sentence and not the English one; the control: `en-US` and an absent header answer the English sentence, for each of the three; the English sentences equal the pre-change text; `ja` reaches ja-JP and `de-DE` falls back to English; the caller-resolution 500 in zh-CN and absent; a 4xx keeps its producer's text under zh-CN. - New pins (catalog, `operation-message.test.ts`): all four keys in every locale, placeholder-free, naming no wire code or host vocabulary, distinct from every other key, rendering zh-CN / es / en fallback. <details><summary>Ablation: hard-coded English restored, zh pins turn red</summary> `node scripts/ablation-replace.mjs` on `print-routes.ts`, anchor `return operationUserMessage(serverAnswerKeyFor(status), { locale });` replaced with the three original hard-coded English returns. The test imports the subject by relative path and aliases core/spec to source, so no build stands between the mutation and the run. ``` ablation-replace: anchor x1 -> x0 ablation-replace: blob 44b2c38 -> 97403a9b77a977dc80088aafb8a207052ec53393 ablation-replace: ok mutation landed: anchor 1 -> 0, blob 44b2c38 -> 97403a9b77a9 × no print engine ready: SERVICE_UNAVAILABLE / 503 under accept-language zh-CN answers the zh-CN sentence × the render ran past its time: TIMEOUT / 504 under accept-language zh-CN answers the zh-CN sentence × an undeclared fault: INTERNAL_ERROR / 500 under accept-language zh-CN answers the zh-CN sentence × a base language reaches its regional catalog (ja → ja-JP); a language the catalog lacks answers English Tests 4 failed | 32 passed (36) ablation-replace: ok restored: blob == HEAD (44b2c38) and `git diff HEAD` is empty ``` The three English controls stayed green under the mutation, as they should. </details> <details><summary>Gates</summary> `node scripts/pm/dispatch-gates.mjs --commands` derived 91 families for this diff; all 91 were run at `3dfbfdb5a`, each exit captured before any pipe. Reconciliation (`--ran` with exit codes): `✓ 91 derived famil(ies) accounted for — 88 run, 3 NOT-MEASURED (3 DERIVED from a recorded exit 3)`. - 88 exit 0. - NOT MEASURED: `node scripts/check-plugin-teardown-shape.mjs --self-test`, reason: shallow clone cannot reach its pinned positive-control commit. - NOT MEASURED: `pnpm check:dual-build-cjs-loads`, reason: reads every package's built output; only the service-print closure was built here. - NOT MEASURED: `pnpm check:type-check-debt`, reason: its re-measure queued on the shared verify lock behind a long dogfood run (exit 99 twice). All three run in CI on this PR. `test:repo` was not run locally (no diff in that project); declared to CI's `Test Core`. </details> ## Acceptance notes - The language source is the request's `Accept-Language` only. The door's execution context carries no locale and no workspace default (`requestLocale: undefined`, `localization: undefined`), so `operationUserMessage`'s second rung (the workspace default) has nothing to read here; the console sends its UI language on every call, which is the issue's case. - No deployment `errors.print_*` translation override is consulted: `operationUserMessage` is the helper for producers that hold no i18n service, and the door holds none. - The door's own 4xx refusals (the impersonation refusal, the request-shape refusals) stay English developer text; they are outside this card, which names the 5xx sentences. - Observation only, not filed: the `/actions` door's own forward-unavailable sentence (`apiActionForwardUnavailableError`, 503) and the print bridge's `501` are English too; neither is on this card's path when the door is mounted, and neither was reproduced here. - Clause-② measured: no new export, no type change, no new envelope field, no new input read as a contract (any header was already accepted); the catalog gains entries in an existing exported `Record` value, and the wire `message` changes language only for a non-English request. --- _Generated by [Claude Code](https://claude.ai/code/session_01QSeKYnagJvGbCtNg2PhvgW)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent 622f398 commit c94191d

6 files changed

Lines changed: 236 additions & 12 deletions

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/service-print': patch
4+
---
5+
6+
Clause-②: no
7+
Metadata-protocol: none
8+
9+
The print door (`POST /api/v1/print/records`) now answers its own 5xx sentences in the request's language. A print that fails on the server because the print engine is not ready (`503`), ran past its time (`504`), failed for any other reason (`500`), or could not resolve its caller (`500`) used to answer a fixed English `error.message` whatever the request's `Accept-Language`, so a Chinese console showed the toast in English. The sentences are now four keys of the platform's operation-message catalog (`print_engine_unavailable`, `print_timed_out`, `print_failed`, `print_caller_unresolved` in `BUILTIN_OPERATION_MESSAGES`, `@objectstack/spec/system`) in `en`, `zh-CN`, `ja-JP` and `es-ES`, written through `operationUserMessage` (`@objectstack/core`) in the request's top `Accept-Language` tag. A print clicked as a `type: 'api'` action answers the same way: the `/actions` door forwards the caller's `Accept-Language` and relays the door's `message` as written.
10+
11+
Code, status and the English text do not change: a request in English, with no `Accept-Language`, or in a language the catalog carries no text for, reads the same sentence as before. What the engine or the host said is still withheld from the wire and kept in the server fault log.

‎packages/services/service-print/src/print-routes.test.ts‎

Lines changed: 110 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import { describe, expect, it, vi } from 'vitest';
44
import { ApiErrorSchema, envelopeViolations } from '@objectstack/spec/api';
5+
import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system';
56
import type { ExecutionContext } from '@objectstack/spec/kernel';
67
import type { ChromiumDriver } from './chromium-driver.js';
78
import type { PrintPlacementResolution } from './config.js';
@@ -57,6 +58,8 @@ interface DoorSetup {
5758
page?: Record<string, unknown>;
5859
/** Hand the door this service instead of a real `PrintService`. */
5960
service?: IPrintService;
61+
/** Replace the tenancy-posture read the resolver awaits (a rejection fails the caller's resolution). */
62+
resolveTenancyPosture?: () => Promise<undefined>;
6063
}
6164

6265
function door(setup: DoorSetup = {}) {
@@ -159,10 +162,12 @@ function door(setup: DoorSetup = {}) {
159162
},
160163
}),
161164
getAuth: () => auth as never,
162-
resolveTenancyPosture: async () => undefined,
165+
resolveTenancyPosture: setup.resolveTenancyPosture ?? (async () => undefined),
163166
});
164167

165-
async function call(opts: { bearer?: string; body?: unknown; query?: Record<string, string> } = {}) {
168+
async function call(
169+
opts: { bearer?: string; body?: unknown; query?: Record<string, string>; headers?: Record<string, string> } = {},
170+
) {
166171
const handler = handlers.get(`POST ${PRINT_RECORDS_ROUTE}`);
167172
if (!handler) throw new Error('the door mounted no POST handler at its route');
168173
const answer: { status: number; body: any } = { status: 0, body: undefined };
@@ -182,7 +187,7 @@ function door(setup: DoorSetup = {}) {
182187
params: {},
183188
query: opts.query ?? {},
184189
body: opts.body,
185-
headers: opts.bearer ? { authorization: `Bearer ${opts.bearer}` } : {},
190+
headers: { ...(opts.bearer ? { authorization: `Bearer ${opts.bearer}` } : {}), ...opts.headers },
186191
method: 'POST',
187192
path: PRINT_RECORDS_ROUTE,
188193
},
@@ -362,6 +367,108 @@ describe('the print door — the refusals card ③ pins, relayed through the doo
362367
});
363368
});
364369

370+
describe("the print door — its own 5xx sentences, in the request's language", () => {
371+
/** A service whose print throws `error`: a declared 504, an undeclared fault. */
372+
function throwing(error: unknown): IPrintService {
373+
return {
374+
status: () => ({ state: 'ready', placement: 'local', version: 'stand-in' }),
375+
printRecordToFile: async () => {
376+
throw error;
377+
},
378+
};
379+
}
380+
381+
/** The three failures the card names, each with the door setup that produces it and the catalog key it answers. */
382+
const FAILURES: Array<{ name: string; code: string; status: number; key: string; setup: () => DoorSetup }> = [
383+
{
384+
name: 'no print engine ready',
385+
code: 'SERVICE_UNAVAILABLE',
386+
status: 503,
387+
key: 'print_engine_unavailable',
388+
setup: () => ({ placement: { state: 'unconfigured', reason: 'No print engine is configured. Set OS_PRINT_CHROMIUM_PATH.' } }),
389+
},
390+
{
391+
name: 'the render ran past its time',
392+
code: 'TIMEOUT',
393+
status: 504,
394+
key: 'print_timed_out',
395+
setup: () => ({ service: throwing(Object.assign(new Error('render timed out at /srv/secret'), { code: 'TIMEOUT', status: 504 })) }),
396+
},
397+
{
398+
name: 'an undeclared fault',
399+
code: 'INTERNAL_ERROR',
400+
status: 500,
401+
key: 'print_failed',
402+
setup: () => ({ service: throwing(new Error('ECONNRESET at /srv/secret')) }),
403+
},
404+
];
405+
406+
async function printAs(setup: DoorSetup, headers?: Record<string, string>) {
407+
const d = door(setup);
408+
const logged = quietFaultLog();
409+
const answer = await d.call({ bearer: 'alice', body: { ...INVOICE, recordId: 'inv_alice' }, headers });
410+
logged.restore();
411+
return answer;
412+
}
413+
414+
for (const failure of FAILURES) {
415+
it(`${failure.name}: ${failure.code} / ${failure.status} under accept-language zh-CN answers the zh-CN sentence`, async () => {
416+
const answer = await printAs(failure.setup(), { 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8' });
417+
expect(envelope(answer)).toEqual([failure.code, failure.status]);
418+
expect(answer.body.error.message).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'][failure.key]);
419+
expect(answer.body.error.message).not.toBe(BUILTIN_OPERATION_MESSAGES.en[failure.key]);
420+
});
421+
422+
it(`${failure.name}: the control — an English or absent accept-language keeps the English sentence`, async () => {
423+
const english = BUILTIN_OPERATION_MESSAGES.en[failure.key];
424+
for (const headers of [{ 'accept-language': 'en-US,en;q=0.9' }, undefined]) {
425+
const answer = await printAs(failure.setup(), headers);
426+
expect(envelope(answer)).toEqual([failure.code, failure.status]);
427+
expect(answer.body.error.message, JSON.stringify(headers)).toBe(english);
428+
}
429+
});
430+
}
431+
432+
it('the English sentences are the ones the door answered before they were localized', () => {
433+
expect(FAILURES.map((f) => BUILTIN_OPERATION_MESSAGES.en[f.key])).toEqual([
434+
'Records cannot be printed to a file right now: the print engine is not ready. The server log records why.',
435+
'The record could not be printed to a file in the time a print is allowed.',
436+
'The record could not be printed to a file because of an error on the server.',
437+
]);
438+
});
439+
440+
it('a base language reaches its regional catalog (ja → ja-JP); a language the catalog lacks answers English', async () => {
441+
const [unavailable] = FAILURES;
442+
const ja = await printAs(unavailable!.setup(), { 'accept-language': 'ja' });
443+
expect(ja.body.error.message).toBe(BUILTIN_OPERATION_MESSAGES['ja-JP'].print_engine_unavailable);
444+
const de = await printAs(unavailable!.setup(), { 'accept-language': 'de-DE' });
445+
expect(de.body.error.message).toBe(BUILTIN_OPERATION_MESSAGES.en.print_engine_unavailable);
446+
});
447+
448+
it('a caller the door cannot resolve: INTERNAL_ERROR / 500 in the request\'s language, the cause in the fault log only', async () => {
449+
const setup: DoorSetup = {
450+
resolveTenancyPosture: async () => {
451+
throw new Error('posture read failed at /srv/secret');
452+
},
453+
};
454+
const zh = await printAs(setup, { 'accept-language': 'zh-CN' });
455+
expect(envelope(zh)).toEqual(['INTERNAL_ERROR', 500]);
456+
expect(zh.body.error.message).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'].print_caller_unresolved);
457+
const absent = await printAs(setup);
458+
expect(absent.body.error.message).toBe('The caller of this print could not be resolved.');
459+
});
460+
461+
it('a 4xx refusal keeps its producer\'s own text whatever the request\'s language', async () => {
462+
const text = 'the service\'s own refusal text';
463+
const answer = await printAs(
464+
{ service: throwing(Object.assign(new Error(text), { code: 'VALIDATION_ERROR', status: 400 })) },
465+
{ 'accept-language': 'zh-CN' },
466+
);
467+
expect(envelope(answer)).toEqual(['VALIDATION_ERROR', 400]);
468+
expect(answer.body.error.message).toBe(text);
469+
});
470+
});
471+
365472
describe('the print door — its own refusals, before the service is asked', () => {
366473
it('an impersonation session: PERMISSION_DENIED / 403, saying so, before anything is minted or read', async () => {
367474
const d = door();

‎packages/services/service-print/src/print-routes.ts‎

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
evaluateAuthGate,
1010
isApiKeyLifecycleRefusalError,
1111
isAuthzStoreUnavailableError,
12+
operationUserMessage,
1213
resolveAuthzContext,
1314
shouldDenyAnonymous,
1415
userAuthGateSourceOf,
@@ -18,6 +19,7 @@ import type { ErrorCode } from '@objectstack/spec/api';
1819
import type { AuthSessionApi, IAuthService, IHttpRequest, IHttpResponse, IHttpServer } from '@objectstack/spec/contracts';
1920
import type { ExecutionContext } from '@objectstack/spec/kernel';
2021
import type { TenancyPosture } from '@objectstack/spec/security';
22+
import { preferredLocaleFromHeader } from '@objectstack/spec/system';
2123
import {
2224
declaredRefusalMessage,
2325
demotedDeclaredCode,
@@ -97,6 +99,12 @@ import type { IPrintService, PrintedRecordFile, PrintRecordRequest } from './pri
9799
* - **Anything else** is a fault: `500` / `INTERNAL_ERROR`, the door's generic
98100
* sentence, and the error in the fault log.
99101
*
102+
* The door's own 5xx sentences are entries of the platform's operation-message
103+
* catalog (the `print_*` keys of `BUILTIN_OPERATION_MESSAGES`), written in the
104+
* request's language: its top `Accept-Language` tag, English when the catalog
105+
* carries no text for it. A print that fails in a Chinese console is answered
106+
* in Chinese. A refusal relayed with its producer's own text keeps that text.
107+
*
100108
* ## What is not recorded
101109
*
102110
* The door writes no audit row of its own. A print signs a session in and out
@@ -153,7 +161,7 @@ async function handlePrintRecord(req: IHttpRequest, res: IHttpResponse, deps: Pr
153161
sendError(res, err.status, err.code, err.message);
154162
return;
155163
}
156-
sendServerFault(res, 500, 'INTERNAL_ERROR', 'The caller of this print could not be resolved.', err, {
164+
sendServerFault(res, 500, 'INTERNAL_ERROR', operationUserMessage('print_caller_unresolved', { locale: requestLocaleOf(req) }), err, {
157165
method: 'POST',
158166
path: PRINT_RECORDS_ROUTE,
159167
});
@@ -210,7 +218,7 @@ async function handlePrintRecord(req: IHttpRequest, res: IHttpResponse, deps: Pr
210218
try {
211219
printed = await deps.print.printRecordToFile(request, context);
212220
} catch (err) {
213-
relayPrintFailure(res, err);
221+
relayPrintFailure(res, err, requestLocaleOf(req));
214222
return;
215223
}
216224
sendOk(res, printed, 201);
@@ -302,15 +310,38 @@ function printRequestOf(body: unknown): PrintRecordRequest | string {
302310
return request as unknown as PrintRecordRequest;
303311
}
304312

305-
/** This door's own sentence for a 5xx whose producer declared no text for its caller. */
306-
function serverAnswerFor(status: number): string {
307-
if (status === 503) return 'Records cannot be printed to a file right now: the print engine is not ready. The server log records why.';
308-
if (status === 504) return 'The record could not be printed to a file in the time a print is allowed.';
309-
return 'The record could not be printed to a file because of an error on the server.';
313+
/**
314+
* The language this door's own 5xx sentences are written in: the request's top
315+
* `Accept-Language` tag. The console sends its UI language on every call, and
316+
* the `/actions` door's in-process forward of a `type: 'api'` action carries
317+
* the caller's header across, so a print clicked as an action is answered in
318+
* the same language. The door reads no query parameter, so `?locale` is no
319+
* source here. It picks the language of the door's words and nothing else.
320+
*/
321+
function requestLocaleOf(req: IHttpRequest): string | undefined {
322+
const header = req.headers?.['accept-language'] ?? req.headers?.['Accept-Language'];
323+
const value = Array.isArray(header) ? header[0] : header;
324+
return preferredLocaleFromHeader(typeof value === 'string' ? value : undefined);
325+
}
326+
327+
/**
328+
* The catalog key of this door's own sentence for a 5xx whose producer declared
329+
* no text for its caller: the platform's operation-message catalog
330+
* (`BUILTIN_OPERATION_MESSAGES`, `@objectstack/spec/system`), never a second one.
331+
*/
332+
function serverAnswerKeyFor(status: number): 'print_engine_unavailable' | 'print_timed_out' | 'print_failed' {
333+
if (status === 503) return 'print_engine_unavailable';
334+
if (status === 504) return 'print_timed_out';
335+
return 'print_failed';
336+
}
337+
338+
/** This door's own sentence for a 5xx whose producer declared no text for its caller, in the request's language. */
339+
function serverAnswerFor(status: number, locale: string | undefined): string {
340+
return operationUserMessage(serverAnswerKeyFor(status), { locale });
310341
}
311342

312343
/** Relay a failed print: a declared refusal with its own `code` and `status`, anything else as a fault. */
313-
function relayPrintFailure(res: IHttpResponse, err: unknown): void {
344+
function relayPrintFailure(res: IHttpResponse, err: unknown, locale: string | undefined): void {
314345
const thrown = resolveThrownHttpError(err, 500);
315346
if (thrown.status < 500) {
316347
const declaredCode = demotedDeclaredCode(thrown);
@@ -326,7 +357,7 @@ function relayPrintFailure(res: IHttpResponse, err: unknown): void {
326357
sendError(res, thrown.status, thrown.code, refusal);
327358
return;
328359
}
329-
sendServerFault(res, thrown.status, thrown.code, serverAnswerFor(thrown.status), err, {
360+
sendServerFault(res, thrown.status, thrown.code, serverAnswerFor(thrown.status, locale), err, {
330361
method: 'POST',
331362
path: PRINT_RECORDS_ROUTE,
332363
});

‎packages/services/service-print/vitest.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ export default defineConfig({
2828
{ find: /^@objectstack\/spec\/contracts$/, replacement: path.resolve(__dirname, '../../spec/src/contracts/index.ts') },
2929
{ find: /^@objectstack\/spec\/kernel$/, replacement: path.resolve(__dirname, '../../spec/src/kernel/index.ts') },
3030
{ find: /^@objectstack\/spec\/ui$/, replacement: path.resolve(__dirname, '../../spec/src/ui/index.ts') },
31+
{ find: /^@objectstack\/spec\/system$/, replacement: path.resolve(__dirname, '../../spec/src/system/index.ts') },
3132
{ find: /^@objectstack\/types$/, replacement: path.resolve(__dirname, '../../types/src/index.ts') },
3233
],
3334
},

‎packages/spec/src/system/operation-message.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -724,3 +724,42 @@ describe('operation message catalog — not found, unreadable query field, deleg
724724
expect(renderOperationMessage({ messageKey: 'record_not_found' }, { locale: 'zh-CN', translate })).toBe('记录不见了');
725725
});
726726
});
727+
728+
describe('operation message catalog — the print door\'s own 5xx sentences', () => {
729+
const KEYS = ['print_engine_unavailable', 'print_timed_out', 'print_failed', 'print_caller_unresolved'] as const;
730+
731+
it('every locale defines all four, placeholder-free', () => {
732+
for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) {
733+
for (const key of KEYS) {
734+
expect(catalog[key], `${locale} defines ${key}`).toBeTypeOf('string');
735+
expect(catalog[key].match(/\{\{\w+\}\}/g) ?? [], `${locale}.${key}`).toEqual([]);
736+
}
737+
}
738+
});
739+
740+
it('names no wire code, engine or host vocabulary — in every locale', () => {
741+
for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) {
742+
for (const key of KEYS) {
743+
expect(catalog[key], `${locale}.${key}`).not.toMatch(/SERVICE_UNAVAILABLE|TIMEOUT|INTERNAL_ERROR|Chromium|OS_PRINT|\//);
744+
}
745+
}
746+
});
747+
748+
it('renders the caller locale, matches a base language, and falls back to en for a locale the catalog lacks', () => {
749+
for (const key of KEYS) {
750+
expect(renderOperationMessage({ messageKey: key }, { locale: 'zh-CN' })).toBe(BUILTIN_OPERATION_MESSAGES['zh-CN'][key]);
751+
expect(renderOperationMessage({ messageKey: key }, { locale: 'zh-CN' })).not.toBe(BUILTIN_OPERATION_MESSAGES.en[key]);
752+
expect(renderOperationMessage({ messageKey: key }, { locale: 'es' })).toBe(BUILTIN_OPERATION_MESSAGES['es-ES'][key]);
753+
expect(renderOperationMessage({ messageKey: key }, { locale: 'de-DE' })).toBe(BUILTIN_OPERATION_MESSAGES.en[key]);
754+
}
755+
});
756+
757+
it('each says something different from every other key, in every locale', () => {
758+
for (const [locale, catalog] of Object.entries(BUILTIN_OPERATION_MESSAGES)) {
759+
for (const key of KEYS) {
760+
const others = Object.entries(catalog).filter(([k]) => k !== key).map(([, v]) => v);
761+
expect(others, `${locale}.${key}`).not.toContain(catalog[key]);
762+
}
763+
}
764+
});
765+
});

0 commit comments

Comments
 (0)