Skip to content

Commit 51b67f1

Browse files
feat(refusals)!: one refusal names several declared reasons, each in the person's language (#37395)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wg4gWSndajcnTbbpCWXcNy9Q)_ Fixes #36877 Clause-②: yes (narrowing) Metadata-protocol: narrowed Skills-docs: follow-up #37407 ## 维护者速读 - 用户能看到什么变化:批量操作(如 HotCRM 的「提交报销」)一次拒绝多条记录时,每条原因都按用户的语言逐行显示,最后一行是总结句。 - 为什么做:拒绝语目录原来一次只能回一句,中文界面下只能给用户看英文清单;HotCRM 的报销提交卡在这里。 - 出错会怎样:只影响声明了拒绝语目录、并且一次抛出多条原因的钩子和动作;写错的原因会在保存或运行时被明确拒绝,不会把未翻译的英文漏给用户。 - 破坏性:这是一次收窄。旧版本里被忽略的 `reasons` 键现在会被读取,三种原来能保存、能运行的写法现在会被拒绝(见下方 Narrowing)。changeset 带 BREAKING 标注、迁移说明和 ADR-0087 登记。 - 要你做什么:无(入队前的批准由席位安排)。 ## What changes Ruling 7178348458 (option A, 「A 一次抛多条原因逐行翻译」), executed term by term: - **(1) Throw shape.** A hook or `script` action body may throw `{ code, reasons: [{ reason, params? }, …] }` beside the existing single `reason`/`params` form. One reader, `refusalAddressFrom` (`packages/runtime/src/sandbox/quickjs-runner.ts`), reads the address for both run paths: the VM's `__errorInfo` channel now also carries `reasons` (JSON-cloned like `params`) and whether the key was present. A `reason` beside a `reasons` list, an empty list, or a list that is not `{ reason, params? }` elements is a `listProblem`, which is the loud fault. - **(2) Every listed reason checked.** `declaredAnswer` (`hook-refusal-catalogue.ts`) checks each listed reason against the entry's `reasons`. One undeclared reason makes the whole throw the `500` fault naming the hook or action, the code and the reason (the existing `undeclared…ReasonAtRun` sentence). Under a code with no `reasons`, every listed reason is undeclared. At save, `hookRefusalReasonsThrownIn` already read `reason: 'x'` inside an inline list (the regex is unanchored within the throw statement); it now marks such pairs `listed: true` when the `reasons: [` list is a direct member of the thrown object literal (the one key the run reads, so a `params: { reasons: [ … ] }` stays the body's own data), and also reads the assignment form `e.reasons = [{ reason: 'x' }]; throw e`. Both save checks (`HookSchema`, `ActionSchema`) judge a listed pair through one predicate, `isUndeclaredThrownReason`: a single reason is still read only under a code that declares `reasons`, as before; a listed one under every code. - **(3) Rendering and wire.** Each line is that reason's sentence, translated and filled from its own `params` through the existing `ownerRefusalMessage`. `userMessage` is the lines joined by `\n`, then the entry's own `message` as the last line (holes from the throw's top-level `params`). The rendered lines ride the `SandboxError` as `refusals`, and every door answers them as `details.refusals: [{ reason, message }]`: one shape reader, `declaredRefusalLines` (`packages/types/src/thrown-http-error.ts`, the `candidates` precedent), read by `resolveThrownHttpError` (the `/actions` door, MCP `run_action`, the dispatcher) and by `mapDataError`'s `userMessage` rider (the `/data` door). The VM never sets `refusals`: only the catalogue does, so a body cannot hand the wire a list it did not render. - **(4) Parity.** The in-process hook handler reads its throw through the same `refusalAddressFrom` and builds the same error shape (`code`, `status`, `userMessage`, `refusals`), so the two paths answer byte-identically (pinned below). - **(5)** The catalogue entry schema and the translation keys are unchanged. The ruling's two declaration lines (`yes` / `added`) rested on "nothing accepted today is refused"; the diff falsifies that premise, so the PR declares the narrowing instead (contract review M1; zone order, on the seat's recommendation, with the fork on Bill's decision card). If Bill keeps term 5's lines, only the declaration lines, the BREAKING banner, the migration and the semantic entry come out. ## Narrowing (declared) Three sources that save and run on `main` are refused at this head: 1. A literal `throw { code: 'X', reasons: [{ reason: 'y' }] }` where `X` declares no `reasons`: refused at save at `body.source` (`main` skips every reason under such a code). A literal `y` under a code that declares `reasons` without it was already refused. 2. `e.code = 'X'; e.reasons = [{ reason: 'y' }]; throw e` with `y` undeclared: refused at save (`main` has no reader for the assignment form). 3. A body that throws a declared code with a `reasons` property of its own (empty, not a list of `{ reason, params? }`, beside a `reason`, or naming an undeclared reason): the run answers the loud `500` fault where `main` answered the declared sentence and status. The changeset carries the BREAKING banner, the FROM → TO migration for each (declare the reason under the code's `reasons`, remove the key, or rename the body's own property) and the ADR-0087 disposition `registered refusal-reasons-list-literal-judged`, a new semantic entry (`packages/spec/src/migrations/entries/semantic/18.refusal-reasons-list-literal-judged.ts`, fence amendment 2, comment 7181270799). No mechanical rewrite: whether a `reasons` key was meant as the list or as the body's own data is the author's call. The surface was widened by the zone before the edit (claim amendment 7179332961) to `packages/types/src/thrown-http-error.ts` and `packages/types/src/data-error-classification.ts`: each door builds `details` from a closed set of fields read there, so term (3) could not reach the wire from `packages/runtime/src/sandbox/**` alone. ## Tests - `packages/runtime/src/sandbox/hook-refusal-catalogue.test.ts`: the body path (en and zh-CN lines, per-line params, closing line, `details.refusals` on `/data` and through `thrownAnswerOf`, the `e.reasons = […]` form); seven fault cases (undeclared listed reason, listed reason under a code with no `reasons`, both forms, empty, element without `reason`, non-list, list `params`), each a `500` with no `userMessage` and no `details`; the parity pin (body vs in-process handler, `JSON.stringify` equal on `mapDataError` and `thrownAnswerOf`, en and zh-CN) plus the same faults in-process; CONTROL: a single reason carries no `details.refusals` on either path. - `packages/runtime/src/sandbox/action-refusal-catalogue.test.ts`: through the real `/actions` door, translated lines plus `error.details.refusals`, and `actionsDoorAnswerOf` (the MCP reader) agrees; an undeclared listed reason is the fault naming the action. - `packages/spec/src/data/hook-refusals.test.ts`, `packages/spec/src/ui/action-refusals.test.ts`: the reader's listed pairs (inline and assignment), what it leaves to run time, the predicate, the save refusal for an undeclared listed reason and for one under a code with no `reasons`, CONTROL: a single reason under such a code still saves, CONTROL: a `reasons` list nested under `params` is not a thrown list (the reader reads it as an unlisted pair, and it saves under a code with no `reasons` on both the hook and the action check). - `packages/types/src/thrown-http-error.test.ts`: `declaredRefusalLines` shape reading (five no-list cases, copies only `reason`/`message`) and both door compositions. <details><summary>Package suites and typecheck (local)</summary> - `pnpm --filter @objectstack/types test`: Test Files 41 passed, Tests 939 passed. - `pnpm --filter @objectstack/runtime test`: Test Files 649 passed, Tests 12051 passed, 25 skipped. - `pnpm --filter @objectstack/spec test`: Test Files 895 passed, Tests 28435 passed, 1 todo. - `typecheck` for `@objectstack/types`, `@objectstack/runtime`, `@objectstack/spec`: exit 0 (lock VERDICT command-exit 0). - Re-run after the last source commit (`e8d60127`): `src/sandbox/` of runtime, 46 files / 529 passed, 2 skipped; runtime typecheck exit 0. </details> <details><summary>Ablation (one, on the behaviour this PR adds)</summary> `node scripts/ablation-replace.mjs` on `hook-refusal-catalogue.ts`, the listed-reason check `if (!reasons || !Object.prototype.hasOwnProperty.call(reasons, line.reason)) {` replaced by `if (/* ABLATED_36877 */ false) {` (anchor 1 → 0, blob 5f2aba5 → ae48d69f): 3 failed / 50 passed, the three `[#36877]` undeclared-reason cases on both paths. Restored: blob equals HEAD (5f2aba5), `git diff HEAD` empty. The runtime tests import the module from `src/`, so no rebuild was needed. </details> <details><summary>Ablation (rework: the direct-member bound)</summary> On `hook-refusal-codes.ts`, `if (!direct) continue;` replaced by `if (/* ABLATED */ false) continue;` (anchor 1): 3 failed / 145 passed in `hook-refusals.test.ts` + `action-refusals.test.ts`, exactly the three nested-`params` controls. Restored from a byte copy; `git diff HEAD` empty. </details> ## Acceptance notes - `/data` keeps bounding `userMessage` at 500 characters (#5423). `details.refusals` is not bounded, so each listed reason's line stays whole there; the closing line (the code's own `message`) is only the last line of `userMessage`, so on a list long enough to be cut, `/data` loses it. A client renders the lines from `details.refusals` (the zone passes this to #37403). - The console still shows the first sentence with the rest behind "More"; the list rendering is ruling term 6, follow-up #37403. - A `reasons` key a body threw beside a declared code used to be ignored (the card's probe table). It is now answered, or is the loud fault when it is not a readable list. That is the declared narrowing above. - MCP: `actionsDoorAnswerOf` carries `details.refusals`; whether the MCP tool result renders `details` was not re-measured (analysis confidence gap (c)). ## Verification Derived gate list (`node scripts/pm/dispatch-gates.mjs --commands`, 97 commands) run locally: - 94 exit 0. - `pnpm check:dispatcher-error-vocabulary`: red on the first run (a `refusalError(code)` helper read as an unresolved code stamp); fixed in `e8d60127` by building the error inline at both sites as before; re-run exit 0. - NOT MEASURED, prerequisites of this checkout, not of the diff: `node scripts/check-plugin-teardown-shape.mjs --self-test` (exit 3, its pinned positive control needs an unshallowed clone; it grades the script, which this PR does not touch); `pnpm check:dual-build-cjs-loads` (exit 3, needs the whole workspace built; CI's Build Core runs it). - `pnpm --filter @objectstack/spec check:generated`: `api-surface/` and `export-origins/` were stale (new exports) and are regenerated in this PR; re-check green. Rework (`4031cd56`): `check-adr-0087-registration --base origin/main` ✓ (`[BREAKING+bang+clause-②-narrowing+metadata-protocol-narrowed] registered refusal-reasons-list-literal-judged (new here)`); `check-changeset-no-major`, `check-empty-changeset`, `check:changeset-gate-self-tests`, `check:commit-card-trailers`, `check:spec-changes`, `check:upgrade-guide` exit 0; `src/migrations` 201 passed; the two spec refusal suites 148 passed. CI's check-runs are the authority for every family. The `(narrowing)` arm owes the full dogfood battery on the final head: on `4031cd56`, `pnpm --filter '@objectstack/dogfood^...' build` then, under the lock, `pnpm --filter @objectstack/dogfood test` (no shard, no path): Test Files 487 passed, 3 skipped; Tests 4128 passed, 68 skipped; exit 0. CI on `4031cd56`: 73 runs, success or skipped, none failed. Two-minute check: `pnpm --filter @objectstack/runtime exec vitest run --maxWorkers=2 src/sandbox/hook-refusal-catalogue.test.ts -t 36877` — expect every `[#36877]` case green, including the parity pin. Read first: `packages/runtime/src/sandbox/hook-refusal-catalogue.ts` (`declaredAnswer`, the list branch), `packages/runtime/src/sandbox/quickjs-runner.ts` (`refusalAddressFrom` and the reject handler's new `reasons` clone), `packages/types/src/thrown-http-error.ts` (`declaredRefusalLines`). --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CXvMJTCqCs1b69pCH7)_ <!-- signed: repo:objectstack#5 · os-bill · session_01Utp6CXvMJTCqCs1b69pCH7 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 66c854d commit 51b67f1

16 files changed

Lines changed: 965 additions & 60 deletions
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/runtime': minor
4+
'@objectstack/types': minor
5+
---
6+
7+
feat(refusals)!: one refusal names several declared reasons, each in the person's language
8+
9+
Clause-②: yes (narrowing)
10+
Metadata-protocol: narrowed
11+
12+
<!-- adr-0087: registered refusal-reasons-list-literal-judged -->
13+
14+
**BREAKING** accept-set narrowing beside a widening, shipped as `minor`. The widening is the new `reasons` list below. The narrowing is what that list makes of a `reasons` key that was ignored before: three sources that save and run on the previous release are refused now (see the migration at the end).
15+
16+
A hook or a `script` action that declares `refusals` can now refuse with several declared sentences at once, for example when it checks a whole selection and refuses all of it. Under one declared code it throws an ordered list of the code's declared reasons, each with its own `params`, instead of one `reason`:
17+
18+
```js
19+
throw { code: 'SUBMIT_REFUSED', params: { count }, reasons: [
20+
{ reason: 'on_report', params: { name: 'Taxi 12' } },
21+
{ reason: 'approved', params: { name: 'Hotel 7' } },
22+
] };
23+
```
24+
25+
- Each listed reason's sentence is picked in the caller's locale and its holes are filled from that reason's own `params`, as a single reason's sentence is. The answer's `userMessage` is those sentences joined by a line break, in the order thrown, then the code's own `message` as the last line (its holes are filled from the throw's top-level `params`). The code's status and the code on the wire are unchanged.
26+
- Every door that answers the refusal also carries each listed reason's sentence structured, as `details.refusals: [{ reason, message }, …]`. The `/data` door bounds `userMessage` at 500 characters as before, and `details.refusals` is not bounded, so each listed line stays whole there. The closing line (the code's own `message`) is not on `details.refusals`: on a list long enough that `/data` cuts `userMessage`, the closing line is lost on that door. A client that renders the list reads the lines from `details.refusals`.
27+
- Every listed reason must be one the code declares under `reasons`. One that is not makes the whole throw the loud `500` fault naming the hook or action, the code and the reason. Under a code that declares no `reasons`, every listed reason is undeclared. A literal list in the source (`throw { code, reasons: [{ reason: 'x' }] }`, or `e.reasons = [{ reason: 'x' }]` on an error the body throws) is refused when the hook or action is saved. Only a `reasons` key that is a direct member of the thrown object is a list; one nested deeper (`params: { reasons: [ … ] }`) is the body's own data, as before.
28+
- A throw that carries both a `reason` and a `reasons` list, an empty list, or a `reasons` value that is not a list of `{ reason, params? }` is the same loud fault.
29+
- The sandboxed body and the in-process hook handler read the list the same way and answer byte-identically.
30+
31+
The catalogue entry (`message`, `status`, `reasons`, `params`) and the translation keys do not change, so no `os i18n` key is added. A throw with one `reason`, or none, is answered exactly as before.
32+
33+
New exports: `@objectstack/spec` adds `isUndeclaredThrownReason`, `unreadableHookRefusalListAtRun`, `unreadableActionRefusalListAtRun` and the `HookRefusalThrownReason` and `RefusalListProblem` types (`data`); `hookRefusalReasonsThrownIn` now answers `HookRefusalThrownReason[]` (a listed pair carries `listed: true`). `@objectstack/types` adds `declaredRefusalLines` and the `DeclaredRefusalLine` type. `@objectstack/runtime` adds no export; its `SandboxError` gains an optional `refusals`, the list the doors read.
34+
35+
**Migration (FROM → TO).** Each row was accepted and answered as if the `reasons` key were absent; it is refused now.
36+
37+
| FROM (accepted before, refused now) | Where it is refused | TO |
38+
|:---|:---|:---|
39+
| A literal `throw { code: 'X', reasons: [{ reason: 'y' }] }` where `X` declares no `reasons` (a literal `y` under a code that declares `reasons` without it was already refused) | At save: `HookSchema` / `ActionSchema` at `body.source` (the metadata save door, `defineStack`, `os validate`, compile, an artifact's parse) | Declare `reasons` on `X` with `y` and its `message`, or remove the `reasons` key |
40+
| `e.code = 'X'; e.reasons = [{ reason: 'y' }]; throw e` with `y` undeclared under `X` | At save, as above | Declare `y` under `refusals.X.reasons`, or remove the `e.reasons` assignment |
41+
| A body that throws a declared code with a `reasons` property of its own: an empty list, a value that is not a list of `{ reason, params? }`, a list beside a `reason`, or a list naming an undeclared reason | At run: the loud `500` fault naming the hook or action and the code, where the declared sentence and status answered before | Rename the body's own property (for example to `items`, or put it under `params`), or throw it as the declared list |
42+
43+
One-line fix: a `reasons` key on a thrown refusal is now the declared list, so name only reasons the code declares there, or rename the key.

‎packages/runtime/src/sandbox/action-refusal-catalogue.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,3 +370,57 @@ describe('the runner\'s own faults pass an action\'s refusal catalogue untouched
370370
}
371371
});
372372
});
373+
374+
/**
375+
* [#36877, ruling 7178348458 letter A] An action that refuses a whole selection
376+
* names several declared reasons in one throw; the `/actions` door answers each
377+
* sentence in the caller's language, in the order thrown, with the entry's own
378+
* sentence last, and the lines structured on `details.refusals`.
379+
*/
380+
describe('[#36877] an action\'s reasons list on the `/actions` door', () => {
381+
const LIST = {
382+
...REFUSALS,
383+
NOT_SUBMITTED: {
384+
message: 'Nothing was submitted.',
385+
status: 409,
386+
params: ['name'],
387+
reasons: {
388+
on_report: { message: 'Expense {{ name }} is already on an expense report.' },
389+
approved: { message: 'Expense {{ name }} is already approved.' },
390+
},
391+
},
392+
};
393+
const KEY = 'objects.crm_invoice._actions.submit_signoff.refusals.NOT_SUBMITTED';
394+
const i18n = () => i18nService({
395+
[`${KEY}.message`]: '未提交任何费用。',
396+
[`${KEY}.reasons.on_report.message`]: '费用 {{ name }} 已在报销单上。',
397+
[`${KEY}.reasons.approved.message`]: '费用 {{ name }} 已审批。',
398+
});
399+
const source = "throw Object.assign(new Error('internal detail'), { code: 'NOT_SUBMITTED', reasons: ["
400+
+ "{ reason: 'on_report', params: { name: 'Taxi 12' } }, { reason: 'approved', params: { name: 'Hotel 7' } }] });";
401+
402+
it('every line translated, the closing sentence last, the list on details.refusals', async () => {
403+
const err = await rejectionOf(boundAction(source, { refusals: LIST, i18n })(actionCtx('zh-CN')));
404+
const response = await throughActionsDoor(err);
405+
expect(response.status).toBe(409);
406+
expect(response.body.error.userMessage).toBe('费用 Taxi 12 已在报销单上。\n费用 Hotel 7 已审批。\n未提交任何费用。');
407+
expect(response.body.error.details.refusals).toEqual([
408+
{ reason: 'on_report', message: '费用 Taxi 12 已在报销单上。' },
409+
{ reason: 'approved', message: '费用 Hotel 7 已审批。' },
410+
]);
411+
expect(JSON.stringify(response.body)).not.toContain('internal detail');
412+
// The reader the MCP `run_action` tool answers a throw with agrees.
413+
expect(actionsDoorAnswerOf(err, 'crm_invoice').details).toEqual({ refusals: response.body.error.details.refusals });
414+
});
415+
416+
it('an undeclared listed reason is the 500 fault naming the action, the code and the reason', async () => {
417+
const err = await rejectionOf(boundAction(
418+
"const r = 'gone'; throw { code: 'NOT_SUBMITTED', reasons: [{ reason: 'approved' }, { reason: r }] };",
419+
{ refusals: LIST },
420+
)(actionCtx()));
421+
expect(err).toBeInstanceOf(SandboxError);
422+
expect(err.innerMessage).toBeUndefined();
423+
expect(err.message).toContain("action 'submit_signoff' threw code 'NOT_SUBMITTED' with reason 'gone'");
424+
expect(mapDataError(err, 'crm_invoice').status).toBe(500);
425+
});
426+
});

‎packages/runtime/src/sandbox/hook-refusal-catalogue.test.ts‎

Lines changed: 156 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
*/
1111

1212
import { describe, it, expect } from 'vitest';
13-
import { mapDataError } from '@objectstack/types';
13+
import { mapDataError, thrownAnswerOf } from '@objectstack/types';
1414

1515
import { hookBodyRunnerFactory, withInProcessHookTitle } from './body-runner.js';
1616
import { QuickJSScriptRunner, SandboxError } from './quickjs-runner.js';
@@ -490,3 +490,158 @@ describe('[#33214] the in-process seam answers the catalogue with the body path\
490490
expect(resolveInProcessHookRefusal({ name: 'plan_gate', refusals: PLAN_REFUSALS } as any, nested, planCtx())).toBe(nested);
491491
});
492492
});
493+
494+
// ── #36877 (ruling 7178348458 letter A): one throw, several declared reasons ──
495+
496+
/** A catalogue whose code holds two reasons with params and a closing entry sentence. */
497+
const LIST_REFUSALS = {
498+
SUBMIT_REFUSED: {
499+
message: 'Nothing was submitted ({{ count }} selected).',
500+
status: 409,
501+
params: ['name', 'count'],
502+
reasons: {
503+
on_report: { message: 'Expense {{ name }} is already on an expense report.' },
504+
approved: { message: 'Expense {{ name }} is already approved.' },
505+
},
506+
},
507+
PLAIN: { message: 'Refused.' },
508+
};
509+
510+
const LIST_ZH = {
511+
'hooks.expense_gate.refusals.SUBMIT_REFUSED.message': '未提交任何费用(已选 {{ count }} 条)。',
512+
'hooks.expense_gate.refusals.SUBMIT_REFUSED.reasons.on_report.message': '费用 {{ name }} 已在报销单上。',
513+
'hooks.expense_gate.refusals.SUBMIT_REFUSED.reasons.approved.message': '费用 {{ name }} 已审批。',
514+
};
515+
516+
function listI18n(): HookRefusalI18nService {
517+
return { t: (key, locale) => (locale === 'zh-CN' ? (LIST_ZH as Record<string, string>)[key] ?? key : key), getLocales: () => ['en', 'zh-CN'] };
518+
}
519+
520+
const LIST_HOOK = { name: 'expense_gate', object: 'expense', events: ['beforeUpdate'], refusals: LIST_REFUSALS };
521+
522+
function listBody(source: string) {
523+
return hookBodyRunnerFactory(runner, { ql: {}, appId: 'crm', i18n: () => listI18n() })({
524+
...LIST_HOOK,
525+
body: { language: 'js', source, capabilities: [] },
526+
} as any)!;
527+
}
528+
529+
function listHandler(handler: (ctx: any) => unknown) {
530+
return withInProcessHookTitle(handler, {}, LIST_HOOK as any, { i18n: () => listI18n() });
531+
}
532+
533+
const LIST_THROW = "throw Object.assign(new Error('internal detail'), { code: 'SUBMIT_REFUSED', params: { count: 3 }, "
534+
+ "reasons: [{ reason: 'on_report', params: { name: 'Taxi 12' } }, { reason: 'approved', params: { name: 'Hotel 7' } }] });";
535+
const listCtx = (locale?: string) => ({
536+
object: 'expense', event: 'beforeUpdate', input: {}, session: locale ? { userId: 'u1', locale } : { userId: 'u1' },
537+
});
538+
539+
describe('[#36877] a reasons list is answered line by line — the body path', () => {
540+
it('each listed sentence in the order thrown, the entry\'s own sentence last, and the list on details.refusals', async () => {
541+
const err = await rejectionOf(listBody(LIST_THROW)(listCtx()));
542+
expect(err).toBeInstanceOf(SandboxError);
543+
const wire = mapDataError(err, 'expense');
544+
expect(wire.status).toBe(409);
545+
expect(wire.body.declaredCode).toBe('SUBMIT_REFUSED');
546+
expect(wire.body.userMessage).toBe(
547+
'Expense Taxi 12 is already on an expense report.\nExpense Hotel 7 is already approved.\nNothing was submitted (3 selected).',
548+
);
549+
expect(wire.body.details).toEqual({
550+
refusals: [
551+
{ reason: 'on_report', message: 'Expense Taxi 12 is already on an expense report.' },
552+
{ reason: 'approved', message: 'Expense Hotel 7 is already approved.' },
553+
],
554+
});
555+
expect(JSON.stringify(wire.body)).not.toContain('internal detail');
556+
});
557+
558+
it('every line translated in the caller\'s locale and filled from its own params', async () => {
559+
const err = await rejectionOf(listBody(LIST_THROW)(listCtx('zh-CN')));
560+
const wire = mapDataError(err, 'expense');
561+
expect(wire.body.userMessage).toBe('费用 Taxi 12 已在报销单上。\n费用 Hotel 7 已审批。\n未提交任何费用(已选 3 条)。');
562+
expect((wire.body.details as any).refusals.map((l: any) => l.message)).toEqual(['费用 Taxi 12 已在报销单上。', '费用 Hotel 7 已审批。']);
563+
});
564+
565+
it('a list assigned onto the thrown error (`e.reasons = […]`) is read the same way', async () => {
566+
const err = await rejectionOf(listBody(
567+
"const e = new Error('x'); e.code = 'SUBMIT_REFUSED'; e.reasons = [{ reason: 'approved', params: { name: 'A' } }]; throw e;",
568+
)(listCtx()));
569+
expect(mapDataError(err, 'expense').body.userMessage).toBe('Expense A is already approved.\nNothing was submitted ( selected).');
570+
});
571+
572+
it('the /actions and dispatcher composition carries the same list', async () => {
573+
const err = await rejectionOf(listBody(LIST_THROW)(listCtx()));
574+
const answer = thrownAnswerOf(err, 500);
575+
expect(answer.status).toBe(409);
576+
expect(answer.declaredCode).toBe('SUBMIT_REFUSED');
577+
expect(answer.details).toEqual({ refusals: (mapDataError(err, 'expense').body.details as any).refusals });
578+
});
579+
});
580+
581+
describe('[#36877] a list the catalogue cannot answer makes the whole throw the loud fault', () => {
582+
const cases: Array<[string, string, string]> = [
583+
['an undeclared listed reason (computed)', "const r = 'no' + 'pe'; throw { code: 'SUBMIT_REFUSED', reasons: [{ reason: 'approved' }, { reason: r }] };", "with reason 'nope'"],
584+
['a listed reason under a code that declares no reasons', "const r = 'appr' + 'oved'; throw { code: 'PLAIN', reasons: [{ reason: r }] };", "code 'PLAIN' with reason 'approved'"],
585+
['a single reason beside a list', "throw { code: 'SUBMIT_REFUSED', reason: 'approved', reasons: [{ reason: 'approved' }] };", 'both a `reason` and a `reasons` list'],
586+
['an empty list', "throw { code: 'SUBMIT_REFUSED', reasons: [] };", 'names no reason'],
587+
['an element with no reason', "throw { code: 'SUBMIT_REFUSED', reasons: [{ reason: 'approved' }, { params: {} }] };", 'not a list of'],
588+
['a reasons value that is not a list', "throw { code: 'SUBMIT_REFUSED', reasons: 'approved' };", 'not a list of'],
589+
['an element whose params is a list', "throw { code: 'SUBMIT_REFUSED', reasons: [{ reason: 'approved', params: ['A'] }] };", 'not a list of'],
590+
];
591+
it.each(cases)('%s', async (_name, source, text) => {
592+
const err = await rejectionOf(listBody(source)(listCtx()));
593+
expect(err).toBeInstanceOf(SandboxError);
594+
expect(err.innerMessage).toBeUndefined();
595+
expect(err.message).toContain("hook 'expense_gate' threw code");
596+
expect(err.message).toContain(text);
597+
const wire = mapDataError(err, 'expense');
598+
expect(wire.status).toBe(500);
599+
expect(wire.body.userMessage).toBeUndefined();
600+
expect(wire.body.details).toBeUndefined();
601+
});
602+
});
603+
604+
describe('[#36877] the in-process handler answers a list byte-identically to the sandboxed body (parity pin)', () => {
605+
const thrownList = () => Object.assign(new Error('internal detail'), {
606+
code: 'SUBMIT_REFUSED',
607+
params: { count: 3 },
608+
reasons: [{ reason: 'on_report', params: { name: 'Taxi 12' } }, { reason: 'approved', params: { name: 'Hotel 7' } }],
609+
});
610+
611+
it.each([undefined, 'zh-CN'])('locale %s: /data envelope and dispatcher answer identical', async (locale) => {
612+
const viaBody = await rejectionOf(listBody(LIST_THROW)(listCtx(locale)));
613+
const viaHandler = await rejectionOf(listHandler(async () => { throw thrownList(); })(listCtx(locale)));
614+
expect(viaHandler).toBeInstanceOf(SandboxError);
615+
expect(JSON.stringify(mapDataError(viaHandler, 'expense'))).toBe(JSON.stringify(mapDataError(viaBody, 'expense')));
616+
expect(JSON.stringify(thrownAnswerOf(viaHandler, 500))).toBe(JSON.stringify(thrownAnswerOf(viaBody, 500)));
617+
expect((mapDataError(viaHandler, 'expense').body.details as any).refusals).toHaveLength(2);
618+
});
619+
620+
it('the same faults: an undeclared listed reason, both forms, an empty list', async () => {
621+
const cases: Array<[() => never, string]> = [
622+
[() => { throw { code: 'SUBMIT_REFUSED', reasons: [{ reason: 'nope' }] }; }, "with reason 'nope'"],
623+
[() => { throw { code: 'SUBMIT_REFUSED', reason: 'approved', reasons: [{ reason: 'approved' }] }; }, 'both a `reason`'],
624+
[() => { throw { code: 'SUBMIT_REFUSED', reasons: [] }; }, 'names no reason'],
625+
];
626+
for (const [thrower, text] of cases) {
627+
const err = await rejectionOf(listHandler(async () => thrower())(listCtx()));
628+
expect(err).toBeInstanceOf(SandboxError);
629+
expect(err.innerMessage).toBeUndefined();
630+
expect(err.message).toContain(text);
631+
expect(mapDataError(err, 'expense').status).toBe(500);
632+
}
633+
});
634+
635+
it('CONTROL: a single declared reason carries no details.refusals on either path', async () => {
636+
const viaBody = await rejectionOf(listBody("throw { code: 'SUBMIT_REFUSED', reason: 'approved', params: { name: 'A' } };")(listCtx()));
637+
const viaHandler = await rejectionOf(listHandler(async () => {
638+
throw { code: 'SUBMIT_REFUSED', reason: 'approved', params: { name: 'A' } };
639+
})(listCtx()));
640+
for (const err of [viaBody, viaHandler]) {
641+
const wire = mapDataError(err, 'expense');
642+
expect(wire.body.userMessage).toBe('Expense A is already approved.');
643+
expect(wire.body.details).toBeUndefined();
644+
expect(err.refusals).toBeUndefined();
645+
}
646+
});
647+
});

0 commit comments

Comments
 (0)