Skip to content

Commit 9975d87

Browse files
Merge pull request #255 from focusreactive/feat/translator-admin-ui-on-stubs
feat(translator)!: the 1.0 admin, built on a server stub
2 parents b382359 + cc1fcfd commit 9975d87

505 files changed

Lines changed: 25001 additions & 5564 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/dev/.env.example‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ MONGO_URL=mongodb://localhost:27017/payload
1313
# reversed in-place so you can see the pipeline working without a key).
1414
OPENAI_API_KEY=
1515

16-
1716
GA4_MEASUREMENT_ID=G-XXXXXXX
1817
GA4_PROPERTY_ID=123456789
1918
GA4_CLIENT_EMAIL=service-account@your-gcp-project.iam.gserviceaccount.com

‎apps/dev/AGENTS.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1117,3 +1117,13 @@ For deeper exploration of specific topics, refer to the context files located in
11171117
- GitHub: https://github.com/payloadcms/payload
11181118
- Examples: https://github.com/payloadcms/payload/tree/main/examples
11191119
- Templates: https://github.com/payloadcms/payload/tree/main/templates
1120+
1121+
<!-- BEGIN:nextjs-agent-rules -->
1122+
1123+
# This is NOT the Next.js you know
1124+
1125+
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
1126+
1127+
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
1128+
1129+
<!-- END:nextjs-agent-rules -->

‎apps/dev/src/app/(payload)/admin/importMap.js‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import type { CollectionConfig } from "payload";
2+
import { afterAll, beforeAll, describe, expect, it } from "vitest";
3+
4+
import { bootTestPayload } from "./bootTestPayload";
5+
import type { TestPayload } from "./bootTestPayload";
6+
import { callEndpoint } from "./callEndpoint";
7+
8+
const docs: CollectionConfig = {
9+
slug: "docs",
10+
fields: [
11+
{ name: "title", type: "text", localized: true },
12+
{ name: "secret", type: "text", localized: true, access: { read: () => false } },
13+
],
14+
};
15+
16+
let ctx: TestPayload;
17+
let id: string;
18+
let reader: { id: string; collection: string };
19+
20+
const outcomeOf = async (call: Promise<{ status: number; data: unknown }>) => {
21+
const { status, data } = await call;
22+
const message = (data as { message?: string } | undefined)?.message;
23+
return { status, message: message ?? "" };
24+
};
25+
26+
beforeAll(async () => {
27+
ctx = await bootTestPayload({ collections: [docs] });
28+
const user = await ctx.payload.create({
29+
collection: "users" as "docs",
30+
data: { email: "reader@test.dev", password: "pw123456" } as never,
31+
});
32+
reader = { id: String((user as { id: string | number }).id), collection: "users" };
33+
34+
const made = await ctx.payload.create({
35+
collection: "docs",
36+
locale: "en",
37+
data: { title: "An English title", secret: "Not for everyone" },
38+
});
39+
id = String(made.id);
40+
});
41+
42+
afterAll(async () => {
43+
await ctx?.cleanup();
44+
});
45+
46+
describe("reading the state as someone who may not read every translatable field", () => {
47+
it("answers for the document, and names no field the caller may not read", async () => {
48+
const asked = await outcomeOf(
49+
callEndpoint(
50+
ctx.payload,
51+
"get",
52+
"/translate/document-state/:collection_slug/:collection_id",
53+
{
54+
routeParams: { collection_slug: "docs", collection_id: id },
55+
user: reader,
56+
}
57+
)
58+
);
59+
60+
expect({ status: asked.status, namesTheField: asked.message.includes("secret") }).toStrictEqual(
61+
{
62+
status: 200,
63+
namesTheField: false,
64+
}
65+
);
66+
});
67+
68+
it("answers for the list the same way", async () => {
69+
const asked = await outcomeOf(
70+
callEndpoint(ctx.payload, "get", "/translate/list-state/:collection_slug", {
71+
routeParams: { collection_slug: "docs" },
72+
query: `ids=${id}`,
73+
user: reader,
74+
})
75+
);
76+
77+
expect({ status: asked.status, namesTheField: asked.message.includes("secret") }).toStrictEqual(
78+
{
79+
status: 200,
80+
namesTheField: false,
81+
}
82+
);
83+
});
84+
85+
it("refuses a partial run for the locale's sake, which is the real reason", async () => {
86+
const asked = await outcomeOf(
87+
callEndpoint(ctx.payload, "post", "/translate/enqueue", {
88+
user: reader,
89+
body: {
90+
source_lng: "en",
91+
target_lng: "de",
92+
collection_slug: "docs",
93+
collection_id: [id],
94+
filters: [{ kind: "leaves", addresses: ["title"] }],
95+
},
96+
})
97+
);
98+
99+
expect({ status: asked.status, namesTheField: asked.message.includes("secret") }).toStrictEqual(
100+
{
101+
status: 400,
102+
namesTheField: false,
103+
}
104+
);
105+
});
106+
});
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import { createPayloadJobsRunner } from "@focus-reactive/payload-plugin-translator";
2+
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
3+
4+
import { bootTestPayload } from "./bootTestPayload";
5+
import type { TestPayload } from "./bootTestPayload";
6+
7+
/*
8+
* The owner's installation runs auto-translate behind a real queue, with another plugin making
9+
* Payload validate its own job rows. No spec had put those three together: the auto-translate
10+
* specs use the inline runner, and the one spec that validates job rows enqueues by hand.
11+
*/
12+
const DRAIN = 8;
13+
14+
type Seen = { targetLng: string };
15+
16+
const onCompleted = vi.fn<(task: Seen) => void>();
17+
const onFailed = vi.fn<(task: Seen, error: unknown) => void>();
18+
19+
let ctx: TestPayload;
20+
21+
const outcomesFor = async (id: string): Promise<Array<string | null | undefined>> => {
22+
const found = await ctx.payload.find({
23+
collection: "translator-runs",
24+
depth: 0,
25+
pagination: false,
26+
overrideAccess: true,
27+
where: { collectionId: { equals: id } },
28+
});
29+
return found.docs.map((row) => (row as { outcome?: string | null }).outcome);
30+
};
31+
32+
const germanTitleOf = async (id: string): Promise<unknown> => {
33+
const doc = await ctx.payload.findByID({
34+
collection: "docs",
35+
id,
36+
locale: "de",
37+
fallbackLocale: false,
38+
draft: true,
39+
overrideAccess: true,
40+
});
41+
return (doc as { title?: unknown }).title;
42+
};
43+
44+
describe("auto-translate while the host validates its own job rows", () => {
45+
let id: string;
46+
47+
beforeAll(async () => {
48+
ctx = await bootTestPayload({
49+
autoTranslate: { targets: ["de"] },
50+
runHooks: true,
51+
runner: createPayloadJobsRunner({
52+
autoRun: false,
53+
retries: { attempts: 2, backoff: { type: "fixed", delay: 0 } },
54+
}),
55+
lifecycle: { onCompleted, onFailed },
56+
});
57+
const made = await ctx.payload.create({
58+
collection: "docs",
59+
locale: "en",
60+
data: { _status: "published", title: "A title" },
61+
});
62+
id = String(made.id);
63+
64+
for (let pass = 0; pass < DRAIN; pass++) {
65+
await ctx.payload.jobs.run({ queue: "translations" });
66+
}
67+
});
68+
69+
afterAll(async () => {
70+
await ctx?.cleanup();
71+
});
72+
73+
it("writes the translation and records the locale as delivered", async () => {
74+
expect({
75+
outcomes: await outcomesFor(id),
76+
germanTitle: await germanTitleOf(id),
77+
}).toStrictEqual({ outcomes: ["delivered"], germanTitle: "de:A title" });
78+
});
79+
80+
it("tells the host the locale completed, not that it failed", () => {
81+
expect({
82+
completed: onCompleted.mock.calls.map(([task]) => task.targetLng),
83+
failed: onFailed.mock.calls.map(([task]) => task.targetLng),
84+
}).toStrictEqual({ completed: ["de"], failed: [] });
85+
});
86+
});

‎apps/dev/src/integration/translator/bootTestPayload.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,12 @@ export type BootOptions = {
7575
* have rows to read.
7676
*/
7777
deleteJobOnComplete?: boolean;
78+
/**
79+
* Payload's own option. With it on, every internal job update goes through `payload.update` and
80+
* is validated, which is how a host that registers a jobs hook runs — and is the only way to
81+
* exercise a task whose work succeeds and whose bookkeeping then fails.
82+
*/
83+
runHooks?: boolean;
7884
/** Payload's `enableConcurrencyControl` for this boot; defaults to `EXCLUSIVE_QUEUE=1`. */
7985
exclusiveQueue?: boolean;
8086
/**
@@ -204,6 +210,7 @@ export async function bootTestPayload(opts?: BootOptions): Promise<TestPayload>
204210
jobs: {
205211
// Payload deletes completed jobs by default, leaving the status panels nothing to read.
206212
deleteJobOnComplete: opts?.deleteJobOnComplete ?? false,
213+
...(opts?.runHooks === undefined ? {} : { runHooks: opts.runHooks }),
207214
enableConcurrencyControl: opts?.exclusiveQueue ?? process.env.EXCLUSIVE_QUEUE === "1",
208215
},
209216
plugins: [

‎apps/dev/src/integration/translator/callEndpoint.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,12 @@ export async function callEndpoint(
1818
path: string,
1919
opts?: {
2020
routeParams?: Record<string, unknown>;
21+
/** The query string a GET route reads, without the leading `?`, e.g. `ids=a,b`. */
22+
query?: string;
2123
body?: unknown;
2224
user?: { id: string | number; collection: string } | null;
25+
/** The admin's language, which the state reads resolve a per-language field label against. */
26+
language?: string;
2327
}
2428
): Promise<{ status: number; data: unknown }> {
2529
const endpoint = (payload.config.endpoints ?? []).find(
@@ -32,6 +36,8 @@ export async function callEndpoint(
3236
const req = {
3337
payload,
3438
routeParams: opts?.routeParams ?? {},
39+
searchParams: new URLSearchParams(opts?.query ?? ""),
40+
i18n: { language: opts?.language ?? "en" },
3541
json: async () => opts?.body,
3642
user: opts?.user ?? null,
3743
} as unknown as PayloadRequest;
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import { createPayloadJobsRunner } from "@focus-reactive/payload-plugin-translator";
2+
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
3+
4+
import { bootTestPayload } from "./bootTestPayload";
5+
import type { TestPayload } from "./bootTestPayload";
6+
import { callEndpoint } from "./callEndpoint";
7+
8+
/*
9+
* Every other cancel spec enqueues first, so a queue row always exists by construction. This one
10+
* takes the queue row away and leaves the run records open — the state a document is left in when
11+
* something removed the work without anyone recording what became of it.
12+
*/
13+
type Seen = { targetLng: string };
14+
15+
const onCancelled = vi.fn<(task: Seen) => void>();
16+
17+
let ctx: TestPayload;
18+
19+
const outcomesFor = async (id: string): Promise<Array<string | null | undefined>> => {
20+
const found = await ctx.payload.find({
21+
collection: "translator-runs",
22+
depth: 0,
23+
pagination: false,
24+
overrideAccess: true,
25+
where: { collectionId: { equals: id } },
26+
});
27+
return found.docs.map((row) => (row as { outcome?: string | null }).outcome).sort();
28+
};
29+
30+
const openRunsFor = async (id: string): Promise<number> => {
31+
const found = await ctx.payload.find({
32+
collection: "translator-runs",
33+
depth: 0,
34+
pagination: false,
35+
overrideAccess: true,
36+
where: { and: [{ collectionId: { equals: id } }, { settledAt: { exists: false } }] },
37+
});
38+
return found.docs.length;
39+
};
40+
41+
describe("cancelling a run whose queue row is already gone", () => {
42+
let id: string;
43+
44+
beforeAll(async () => {
45+
ctx = await bootTestPayload({
46+
runner: createPayloadJobsRunner({ autoRun: false }),
47+
lifecycle: { onCancelled },
48+
});
49+
const made = await ctx.payload.create({
50+
collection: "docs",
51+
locale: "en",
52+
data: { _status: "published", title: "Left behind", note: "A note" },
53+
});
54+
id = String(made.id);
55+
56+
await callEndpoint(ctx.payload, "post", "/translate/enqueue", {
57+
body: {
58+
source_lng: "en",
59+
target_lng: ["de", "fr"],
60+
collection_slug: "docs",
61+
collection_id: [id],
62+
publish_on_translation: false,
63+
},
64+
});
65+
66+
// What the sandbox was left with: the work is gone, the records still say it is under way.
67+
await ctx.payload.delete({ collection: "payload-jobs", where: {}, overrideAccess: true });
68+
});
69+
70+
afterAll(async () => {
71+
await ctx?.cleanup();
72+
});
73+
74+
it("closes the run records, so the document stops reading as busy", async () => {
75+
expect(await openRunsFor(id), "the document starts out held by two open records").toBe(2);
76+
77+
const response = await callEndpoint(ctx.payload, "delete", "/translate/cancel", {
78+
body: { collection_slug: "docs", collection_id: [id] },
79+
});
80+
81+
expect(response.status).toBe(204);
82+
expect(
83+
{ open: await openRunsFor(id), outcomes: await outcomesFor(id) },
84+
"a record nobody closes keeps the panel saying the document is translating, for ever"
85+
).toStrictEqual({ open: 0, outcomes: ["cancelled", "cancelled"] });
86+
});
87+
88+
it("tells the host what became of each locale", async () => {
89+
expect(onCancelled.mock.calls.map(([task]) => task.targetLng).sort()).toEqual(["de", "fr"]);
90+
});
91+
});

‎apps/dev/src/integration/translator/cancel-while-running.int.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,4 +67,30 @@ describe.skipIf(!SQLITE)("cancelling a run that is already translating", () => {
6767
`nothing translated failed — a machinery error is not a locale giving up (saw: ${announced.join(", ")})`
6868
).toEqual([]);
6969
});
70+
71+
it("frees the document, so a new translation can be started", async () => {
72+
// The cancelling hook keyed off this id; clearing it lets the next run translate normally.
73+
const cancelled = documentId;
74+
documentId = undefined;
75+
76+
const response = await callEndpoint(ctx.payload, "post", "/translate/enqueue", {
77+
body: {
78+
source_lng: "en",
79+
target_lng: ["de"],
80+
collection_slug: "docs",
81+
collection_id: [cancelled],
82+
publish_on_translation: false,
83+
},
84+
});
85+
86+
const queued = (response.data as { data: { queued?: number } }).data.queued;
87+
88+
expect(
89+
{ status: response.status, queued },
90+
"a cancelled run must not keep the document busy, or the editor has no way back"
91+
).toStrictEqual({ status: 200, queued: 1 });
92+
93+
await ctx.payload.jobs.run({ queue: "translations" });
94+
expect(announced).toContain("completed:de");
95+
});
7096
});

0 commit comments

Comments
 (0)