@rig-c/review 2.2.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/job-hub.ts ADDED
@@ -0,0 +1,298 @@
1
+ /** Embedded job owner. Trusted callback registrations never cross a process boundary. */
2
+ import {randomBytes, randomUUID} from 'node:crypto';
3
+ import {mkdir, unlink} from 'node:fs/promises';
4
+ import {join} from 'node:path';
5
+ import {buildWeb} from './build.ts';
6
+ import {jobBody, jobObject, sameCapability} from './job-api.ts';
7
+ import {JOB_API_SCHEMA, JOB_ACT_SCHEMA, type JobHostPorts, type JobReviewerBinding} from './job-contract.ts';
8
+ import {assertJobHostCompatible, createJobRequestContext, installJobWriterBinding, jobHostIdentity,
9
+ jobWindowResources, type JobHostOptions, type JobHostRecord} from './job-front.ts';
10
+ import {JobSession} from './job-session.ts';
11
+ import {captureJobRoot} from './job-source.ts';
12
+ import {JobError} from './job-store.ts';
13
+ import {acquireClaim, readOpenStatus, releaseClaim, running} from './open.ts';
14
+ import {assertPrivate, readPrivate, writePrivate} from './open-workspace-state.ts';
15
+ import {canonicalStatePath} from './state-dir.ts';
16
+
17
+ export interface JobHubOptions {
18
+ readonly stateDir: string;
19
+ readonly reviewer: JobReviewerBinding;
20
+ readonly port?: number;
21
+ }
22
+ export type JobHubJobOptions = Omit<JobHostOptions, 'stateDir' | 'port' | 'reviewer'>;
23
+ export interface JobHubJob {
24
+ readonly session: JobSession;
25
+ readonly ports: JobHostPorts;
26
+ readonly origin: string;
27
+ readonly jobUrl: string;
28
+ readonly reused: boolean;
29
+ }
30
+ export interface JobOwnerHub {
31
+ readonly origin: string;
32
+ readonly ownerUrl: string;
33
+ openJob(options: JobHubJobOptions): Promise<JobHubJob>;
34
+ stop(): Promise<void>;
35
+ }
36
+
37
+ export interface JobHubRow {
38
+ jobId: string;
39
+ generation: number;
40
+ status: 'active' | 'closed';
41
+ publication: {publicationId: string; instanceKey: string; sourceHash: string; label: string} | null;
42
+ pendingCount: number;
43
+ }
44
+ export interface JobHubList {
45
+ schema: 'rig-review-job-hub/1';
46
+ incarnation: string;
47
+ limit: number;
48
+ jobs: JobHubRow[];
49
+ }
50
+
51
+ const schema = 'rig-review-job-hub/1';
52
+ const maximumJobs = 32;
53
+ const responseHeaders = {'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer'};
54
+ type HubCode = 'JOB_HUB_ALREADY_RUNNING' | 'JOB_HUB_EXTERNAL_HOST' | 'JOB_HUB_HOST_UNRESPONSIVE' |
55
+ 'JOB_HUB_CLOSED' | 'JOB_HUB_LIMIT' | 'JOB_HUB_STATE_INVALID';
56
+ class HubError extends Error {
57
+ constructor(readonly code: HubCode) {super(code);}
58
+ }
59
+ interface HubRecord {
60
+ schema: typeof schema;
61
+ pid: number;
62
+ origin: string;
63
+ incarnation: string;
64
+ capability: string;
65
+ }
66
+ interface Member {
67
+ root: string;
68
+ fingerprint: string;
69
+ session: JobSession;
70
+ context: ReturnType<typeof createJobRequestContext>;
71
+ recordPath: string;
72
+ ready: boolean;
73
+ }
74
+ function refused(code: string, status: number) {
75
+ return Response.json({ok: false, error: {code, message: code}}, {status, headers: responseHeaders});
76
+ }
77
+ function hostRecord(value: unknown, jobId?: string): JobHostRecord {
78
+ if (!value || typeof value !== 'object') throw new HubError('JOB_HUB_STATE_INVALID');
79
+ const row = value as JobHostRecord;
80
+ let origin: URL;
81
+ try {origin = new URL(row.origin);} catch {throw new HubError('JOB_HUB_STATE_INVALID');}
82
+ if (row.schema !== 'rig-review-job-host/1' || typeof row.jobId !== 'string' || jobId && row.jobId !== jobId ||
83
+ typeof row.fingerprint !== 'string' || !Number.isSafeInteger(row.pid) || row.pid < 1 ||
84
+ origin.origin !== row.origin || origin.protocol !== 'http:' || origin.hostname !== '127.0.0.1') {
85
+ throw new HubError('JOB_HUB_STATE_INVALID');
86
+ }
87
+ return row;
88
+ }
89
+
90
+ export async function startJobHub(options: JobHubOptions): Promise<JobOwnerHub> {
91
+ const reviewer = structuredClone(options.reviewer);
92
+ if (!reviewer?.id || !['owner', 'delegate'].includes(reviewer.role)) throw new JobError('JOB_AUTHORITY_REFUSED');
93
+ if (options.port !== undefined && (!Number.isSafeInteger(options.port) || options.port < 0 || options.port > 65535)) {
94
+ throw new JobError('JOB_REQUEST_INVALID');
95
+ }
96
+ const stateDir = canonicalStatePath(options.stateDir);
97
+ const directory = join(stateDir, 'job-hub'), control = join(stateDir, 'job-ui');
98
+ for (const path of [directory, control]) {
99
+ await mkdir(path, {recursive: true, mode: 0o700}); await assertPrivate(path, true);
100
+ }
101
+ const recordPath = join(directory, 'host.json'), incarnation = randomUUID();
102
+ const capability = randomBytes(32).toString('hex');
103
+ async function refuseLiveHub(): Promise<null> {
104
+ const previous = await readPrivate(recordPath) as HubRecord | null;
105
+ if (!previous) return null;
106
+ if (previous.schema !== schema || !Number.isSafeInteger(previous.pid) || previous.pid < 1) {
107
+ throw new HubError('JOB_HUB_STATE_INVALID');
108
+ }
109
+ if (running(previous.pid)) throw new HubError('JOB_HUB_ALREADY_RUNNING');
110
+ return null;
111
+ }
112
+ await refuseLiveHub();
113
+ const acquired = await acquireClaim(directory, 'hub', incarnation, refuseLiveHub,
114
+ performance.now() + 20_000, 'JOB_HUB_ALREADY_RUNNING');
115
+ if (!('claim' in acquired)) throw new HubError('JOB_HUB_ALREADY_RUNNING');
116
+ const hubClaim = acquired.claim;
117
+ let server: ReturnType<typeof Bun.serve> | undefined;
118
+ const members = new Map<string, Member>();
119
+ let queue = Promise.resolve(), closing = false, requests = 0;
120
+ let stopping: Promise<void> | undefined;
121
+ const resources = jobWindowResources();
122
+ let hubBundle: Promise<Blob> | undefined;
123
+ async function removeOwned(path: string) {
124
+ const value = await readPrivate(path) as {incarnation?: string; hubIncarnation?: string} | null;
125
+ if (value?.incarnation === incarnation || value?.hubIncarnation === incarnation) {
126
+ await unlink(path).catch(error => {if (error.code !== 'ENOENT') throw error;});
127
+ }
128
+ }
129
+ function stop(): Promise<void> {
130
+ if (stopping) return stopping;
131
+ closing = true;
132
+ stopping = (async () => {
133
+ await queue;
134
+ for (const member of members.values()) member.context.stop();
135
+ while (requests || [...members.values()].some(member => member.context.busy)) await Bun.sleep(10);
136
+ await server?.stop(true);
137
+ for (const member of members.values()) {
138
+ member.session.dispose(); await removeOwned(member.recordPath);
139
+ }
140
+ members.clear();
141
+ await removeOwned(recordPath);
142
+ await releaseClaim(hubClaim, incarnation);
143
+ })();
144
+ return stopping;
145
+ }
146
+ try {
147
+ await refuseLiveHub();
148
+ server = Bun.serve({hostname: '127.0.0.1', port: options.port ?? 0, idleTimeout: 0,
149
+ async fetch(request): Promise<Response> {
150
+ if (closing) return refused('JOB_HUB_CLOSED', 503);
151
+ requests++;
152
+ try {
153
+ const url = new URL(request.url);
154
+ if (url.origin !== origin) return refused('JOB_LOOPBACK_REQUIRED', 403);
155
+ const resource = url.pathname === '/hub/' ? 'job-hub.html' : url.pathname === '/hub/job-hub.js' ? 'job-hub.js'
156
+ : url.pathname === '/hub/job-hub.css' ? 'job-hub.css' : url.pathname === '/hub/styles.css' ? 'styles.css' : null;
157
+ if (resource) {
158
+ if (!['GET', 'HEAD'].includes(request.method)) return refused('JOB_REQUEST_INVALID', 405);
159
+ if (request.headers.get('sec-fetch-site') === 'cross-site' ||
160
+ request.headers.get('origin') !== null && request.headers.get('origin') !== origin) return refused('JOB_SAME_ORIGIN_REQUIRED', 403);
161
+ if (resource === 'job-hub.html') {
162
+ if (url.searchParams.get('workspace') !== incarnation ||
163
+ [...url.searchParams.keys()].some(key => !['workspace', 'lang'].includes(key) || url.searchParams.getAll(key).length !== 1) ||
164
+ url.searchParams.has('lang') && !['en', 'ko'].includes(url.searchParams.get('lang')!)) return refused('JOB_REQUEST_INVALID', 400);
165
+ } else if (url.search) return refused('JOB_REQUEST_INVALID', 400);
166
+ let body: BodyInit | null = null;
167
+ if (request.method !== 'HEAD') {
168
+ if (resource === 'job-hub.js') body = await (hubBundle ??= buildWeb('job-hub'));
169
+ else body = Bun.file(new URL('../web/' + resource, import.meta.url));
170
+ }
171
+ return new Response(body, {headers: {...responseHeaders,
172
+ 'Content-Type': resource.endsWith('.html') ? 'text/html; charset=utf-8' : resource.endsWith('.js') ? 'text/javascript' : 'text/css',
173
+ 'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; frame-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'"}});
174
+ }
175
+ const selected = /^\/hub\/api\/jobs\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/open$/.exec(url.pathname);
176
+ if (url.pathname === '/hub/host' || url.pathname === '/hub/api/jobs' || selected) {
177
+ if (request.method !== (selected ? 'POST' : 'GET') || url.search) return refused('JOB_REQUEST_INVALID', 400);
178
+ if (request.headers.get('sec-fetch-site') === 'cross-site' ||
179
+ request.headers.get('origin') !== null && request.headers.get('origin') !== origin) {
180
+ return refused('JOB_SAME_ORIGIN_REQUIRED', 403);
181
+ }
182
+ if (!sameCapability(request.headers.get('X-Review-Capability'), capability)) {
183
+ return refused('JOB_CAPABILITY_REQUIRED', 403);
184
+ }
185
+ if (selected) {
186
+ if (request.headers.get('origin') !== origin) return refused('JOB_SAME_ORIGIN_REQUIRED', 403);
187
+ try {
188
+ const input = jobObject(await jobBody(request), ['schema', 'incarnation']);
189
+ if (input.schema !== schema || input.incarnation !== incarnation) return refused('JOB_REQUEST_INVALID', 400);
190
+ } catch (error) {return refused(error instanceof JobError ? error.code : 'JOB_REQUEST_INVALID',
191
+ error instanceof JobError && error.code === 'JOB_BODY_LIMIT' ? 413 : 400);}
192
+ const member = members.get(selected[1]!);
193
+ if (!member?.ready) return refused('JOB_UNKNOWN', 404);
194
+ if (member.session.status().status === 'closed') return refused('JOB_CLOSED', 409);
195
+ return Response.json({schema, incarnation, jobId: selected[1],
196
+ entry: `/jobs/${selected[1]}/?hub=${incarnation}`, capability: member.session.hostCredentials().ui}, {headers: responseHeaders});
197
+ }
198
+ if (url.pathname === '/hub/host') return Response.json({schema, incarnation, pid: process.pid,
199
+ origin, apiSchema: JOB_API_SCHEMA, actSchema: JOB_ACT_SCHEMA}, {headers: responseHeaders});
200
+ return Response.json({schema, incarnation, limit: maximumJobs, jobs: [...members.values()].filter(member => member.ready).map(member => {
201
+ const status = member.session.status();
202
+ return {jobId: status.jobId, generation: status.generation, status: status.status,
203
+ publication: status.publication && {publicationId: status.publication.publicationId,
204
+ instanceKey: status.publication.instanceKey, sourceHash: status.publication.source.sourceHash,
205
+ label: status.publication.label.slice(0, 512)}, pendingCount: status.pending.length};
206
+ })}, {headers: responseHeaders});
207
+ }
208
+ const match = /^\/jobs\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\//.exec(url.pathname);
209
+ const member = match && members.get(match[1]!);
210
+ return member ? await member.context.fetch(request) : refused('JOB_UNKNOWN', 404);
211
+ } finally {requests--;}
212
+ },
213
+ });
214
+ const origin: string = `http://127.0.0.1:${server.port}`;
215
+ const record: HubRecord = {schema, pid: process.pid, origin, incarnation, capability};
216
+ await writePrivate(recordPath, record);
217
+ async function register(input: JobHubJobOptions): Promise<JobHubJob> {
218
+ if (closing) throw new HubError('JOB_HUB_CLOSED');
219
+ const startup: JobHostOptions = {...input, stateDir, reviewer};
220
+ const identity = jobHostIdentity(startup);
221
+ const root = captureJobRoot(startup.root).path;
222
+ if (members.size >= maximumJobs && ![...members.values()].some(member =>
223
+ member.root === root && member.fingerprint === startup.fingerprint && member.session.status().status === 'active')) {
224
+ throw new HubError('JOB_HUB_LIMIT');
225
+ }
226
+ const session = new JobSession(startup);
227
+ let retained = false;
228
+ let claim: string | undefined;
229
+ let member: Member | undefined;
230
+ const nonce = randomUUID();
231
+ try {
232
+ const existing = members.get(session.jobId);
233
+ if (existing) {
234
+ assertJobHostCompatible(existing.context.record, identity);
235
+ await installJobWriterBinding(existing.session, startup, origin);
236
+ return {session: existing.session, ports: existing.context.ports, origin,
237
+ jobUrl: origin + `/jobs/${session.jobId}/#cap=${existing.session.hostCredentials().ui}`, reused: true};
238
+ }
239
+ if (members.size >= maximumJobs) throw new HubError('JOB_HUB_LIMIT');
240
+ const path = join(control, session.jobId + '.json');
241
+ async function refuseExternal(): Promise<null> {
242
+ const value = await readPrivate(path);
243
+ if (!value) return null;
244
+ const row = hostRecord(value, session.jobId);
245
+ if (row.fingerprint !== startup.fingerprint) throw new HubError('JOB_HUB_STATE_INVALID');
246
+ if (!running(row.pid)) return null;
247
+ let remote: JobHostRecord;
248
+ try {
249
+ const response = await fetch(row.origin + `/jobs/${session.jobId}/host`, {
250
+ headers: {'X-Review-Capability': session.hostCredentials().ui}, redirect: 'error', signal: AbortSignal.timeout(1500),
251
+ });
252
+ if (!response.ok) {await response.body?.cancel(); throw new HubError('JOB_HUB_HOST_UNRESPONSIVE');}
253
+ remote = hostRecord(await readOpenStatus(response, 1500), session.jobId);
254
+ if (remote.origin !== row.origin || remote.pid !== row.pid || remote.fingerprint !== row.fingerprint) {
255
+ throw new HubError('JOB_HUB_HOST_UNRESPONSIVE');
256
+ }
257
+ } catch {throw new HubError('JOB_HUB_HOST_UNRESPONSIVE');}
258
+ assertJobHostCompatible(row, identity); assertJobHostCompatible(remote, identity);
259
+ throw new HubError('JOB_HUB_EXTERNAL_HOST');
260
+ }
261
+ await refuseExternal();
262
+ const acquiredJob = await acquireClaim(control, 'job-' + session.jobId, nonce, refuseExternal,
263
+ performance.now() + 20_000, 'JOB_HUB_EXTERNAL_HOST');
264
+ if (!('claim' in acquiredJob)) throw new HubError('JOB_HUB_EXTERNAL_HOST');
265
+ claim = acquiredJob.claim;
266
+ await refuseExternal();
267
+ const context = createJobRequestContext(session, startup, origin, identity, resources, incarnation);
268
+ Object.assign(context.record, {hubIncarnation: incarnation});
269
+ member = {root, fingerprint: startup.fingerprint, session, context, recordPath: path, ready: false};
270
+ members.set(session.jobId, member);
271
+ await installJobWriterBinding(session, startup, origin);
272
+ if (closing) throw new HubError('JOB_HUB_CLOSED');
273
+ await writePrivate(path, context.record);
274
+ member.ready = true; retained = true;
275
+ return {session, ports: context.ports, origin,
276
+ jobUrl: origin + `/jobs/${session.jobId}/#cap=${session.hostCredentials().ui}`, reused: false};
277
+ } finally {
278
+ if (!retained) {
279
+ if (member) {
280
+ members.delete(session.jobId); member.context.stop();
281
+ while (member.context.busy) await Bun.sleep(10);
282
+ }
283
+ session.dispose();
284
+ }
285
+ if (claim) await releaseClaim(claim, nonce);
286
+ }
287
+ }
288
+ return {origin, ownerUrl: origin + '/hub/?workspace=' + incarnation + '#cap=' + capability,
289
+ openJob(input) {
290
+ const startup = {...input};
291
+ const task = queue.then(() => register(startup));
292
+ queue = task.then(() => {}, () => {});
293
+ return task;
294
+ }, stop};
295
+ } catch (error) {
296
+ await stop(); throw error;
297
+ }
298
+ }
package/web/catalog-en.ts CHANGED
@@ -3393,6 +3393,21 @@ export const enCatalog: Readonly<Record<string, string>> = {
3393
3393
  "JOB_SOURCE_MISMATCH": "JOB_SOURCE_MISMATCH",
3394
3394
  "JOB_SOURCE_UNRETAINABLE": "JOB_SOURCE_UNRETAINABLE",
3395
3395
  "JOB_STORAGE_FAILED": "JOB_STORAGE_FAILED",
3396
+ "rig-review-job-hub/1": "rig-review-job-hub/1",
3397
+ "JOB_HUB_ALREADY_RUNNING": "JOB_HUB_ALREADY_RUNNING",
3398
+ "JOB_HUB_EXTERNAL_HOST": "JOB_HUB_EXTERNAL_HOST",
3399
+ "JOB_HUB_HOST_UNRESPONSIVE": "JOB_HUB_HOST_UNRESPONSIVE",
3400
+ "JOB_HUB_CLOSED": "JOB_HUB_CLOSED",
3401
+ "JOB_HUB_LIMIT": "JOB_HUB_LIMIT",
3402
+ "JOB_HUB_STATE_INVALID": "JOB_HUB_STATE_INVALID",
3403
+ "JOB_HUB_REQUEST_REFUSED": "JOB_HUB_REQUEST_REFUSED",
3404
+ "rig-review-job-hub-ready/1": "rig-review-job-hub-ready/1",
3405
+ "rig-review-job-hub-visibility/1": "rig-review-job-hub-visibility/1",
3406
+ "job.hubTitle": "Review jobs",
3407
+ "job.hubJobs": "Review jobs",
3408
+ "job.hubHint": "Select a job. Drafts stay with their original source.",
3409
+ "job.hubClosed": "Explicitly closed",
3410
+ "job.hubPending": "Active · {0} pending asks",
3396
3411
  "JOB_STREAM_FAILED": "JOB_STREAM_FAILED",
3397
3412
  "JOB_STREAM_INCOMPLETE": "JOB_STREAM_INCOMPLETE",
3398
3413
  "JOB_UNKNOWN": "JOB_UNKNOWN",
package/web/catalog-ko.ts CHANGED
@@ -3393,6 +3393,21 @@ export const koCatalog: Readonly<Record<string, string>> = {
3393
3393
  "JOB_SOURCE_MISMATCH": "JOB_SOURCE_MISMATCH",
3394
3394
  "JOB_SOURCE_UNRETAINABLE": "JOB_SOURCE_UNRETAINABLE",
3395
3395
  "JOB_STORAGE_FAILED": "JOB_STORAGE_FAILED",
3396
+ "rig-review-job-hub/1": "rig-review-job-hub/1",
3397
+ "JOB_HUB_ALREADY_RUNNING": "JOB_HUB_ALREADY_RUNNING",
3398
+ "JOB_HUB_EXTERNAL_HOST": "JOB_HUB_EXTERNAL_HOST",
3399
+ "JOB_HUB_HOST_UNRESPONSIVE": "JOB_HUB_HOST_UNRESPONSIVE",
3400
+ "JOB_HUB_CLOSED": "JOB_HUB_CLOSED",
3401
+ "JOB_HUB_LIMIT": "JOB_HUB_LIMIT",
3402
+ "JOB_HUB_STATE_INVALID": "JOB_HUB_STATE_INVALID",
3403
+ "JOB_HUB_REQUEST_REFUSED": "JOB_HUB_REQUEST_REFUSED",
3404
+ "rig-review-job-hub-ready/1": "rig-review-job-hub-ready/1",
3405
+ "rig-review-job-hub-visibility/1": "rig-review-job-hub-visibility/1",
3406
+ "job.hubTitle": "리뷰 작업",
3407
+ "job.hubJobs": "리뷰 작업",
3408
+ "job.hubHint": "작업을 선택해. 초안은 원래 소스에 보관돼.",
3409
+ "job.hubClosed": "명시적으로 종료됨",
3410
+ "job.hubPending": "진행 중 · 대기 요청 {0}개",
3396
3411
  "JOB_STREAM_FAILED": "JOB_STREAM_FAILED",
3397
3412
  "JOB_STREAM_INCOMPLETE": "JOB_STREAM_INCOMPLETE",
3398
3413
  "JOB_UNKNOWN": "JOB_UNKNOWN",
@@ -0,0 +1,14 @@
1
+ html, body, #job-hub { height: 100%; margin: 0; }
2
+ #job-hub { display: grid; grid-template: auto 1fr / minmax(12rem, 18rem) minmax(0, 1fr); color: var(--fg); background: var(--bg); }
3
+ .hub-header { grid-column: 1 / -1; display: flex; align-items: center; gap: 1rem; padding: .75rem 1rem; border-bottom: 1px solid var(--border); }
4
+ .hub-header h1 { margin: 0; font-size: 1rem; flex: 0 0 auto; }
5
+ .hub-header select { width: auto; min-width: 6rem; max-width: 12rem; flex: 0 0 auto; }
6
+ .hub-status { flex: 1; min-width: 0; color: var(--fg-muted); }
7
+ .hub-list { overflow: auto; border-right: 1px solid var(--border); padding: .5rem; }
8
+ .hub-list button { width: 100%; display: grid; gap: .25rem; margin-bottom: .5rem; padding: .75rem; text-align: left; }
9
+ .hub-list button[aria-pressed="true"] { border-color: var(--pass); }
10
+ .hub-list span { overflow-wrap: anywhere; }
11
+ .hub-job-state, .hub-job-source { color: var(--fg-muted); font-size: .8rem; }
12
+ .hub-stage { position: relative; min-width: 0; min-height: 0; }
13
+ .hub-stage iframe { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; }
14
+ .hub-stage iframe[hidden] { display: block !important; visibility: hidden; pointer-events: none; }
@@ -0,0 +1,5 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title></title><link rel="stylesheet" href="styles.css"><link rel="stylesheet" href="job-hub.css"></head>
4
+ <body data-job-hub><div id="job-hub"></div><script type="module" src="job-hub.js"></script></body>
5
+ </html>
package/web/job-hub.ts ADDED
@@ -0,0 +1,179 @@
1
+ /** Owner-only job selection. Each retained frame owns its existing job window and draft. */
2
+ import type {JobHubList, JobHubRow} from '../src/job-hub.ts';
3
+
4
+ export const JOB_HUB_READY = 'rig-review-job-hub-ready/1';
5
+ export const JOB_HUB_VISIBILITY = 'rig-review-job-hub-visibility/1';
6
+ export interface JobHubBinding {
7
+ incarnation: string;
8
+ jobId: string;
9
+ publicationId: string | null;
10
+ sourceHash: string | null;
11
+ }
12
+ export function jobHubMessageMatches(event: Pick<MessageEvent, 'origin' | 'source' | 'data'>,
13
+ origin: string, source: MessageEventSource | null, binding: JobHubBinding, kind: 'ready' | 'visibility'): boolean {
14
+ if (!source || event.origin !== origin || event.source !== source || !event.data || typeof event.data !== 'object') return false;
15
+ const value = event.data;
16
+ const keys = ['schema', 'incarnation', 'jobId', 'publicationId', 'sourceHash', ...(kind === 'visibility' ? ['visible', 'language'] : [])];
17
+ return !Object.keys(value).some(key => !keys.includes(key)) &&
18
+ value.schema === (kind === 'ready' ? JOB_HUB_READY : JOB_HUB_VISIBILITY) &&
19
+ value.incarnation === binding.incarnation && value.jobId === binding.jobId &&
20
+ value.publicationId === binding.publicationId && value.sourceHash === binding.sourceHash &&
21
+ (binding.publicationId === null && binding.sourceHash === null ||
22
+ typeof binding.publicationId === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(binding.publicationId) &&
23
+ typeof binding.sourceHash === 'string' && /^[a-f0-9]{64}$/.test(binding.sourceHash)) &&
24
+ (kind === 'ready' || typeof value.visible === 'boolean' && ['en', 'ko'].includes(value.language));
25
+ }
26
+ export function jobHubAccess(href: string, storage: Pick<Storage, 'getItem' | 'setItem'> | null, replace: (href: string) => void) {
27
+ const url = new URL(href), incarnation = url.searchParams.get('workspace');
28
+ if (url.pathname !== '/hub/' || !incarnation || !/^[a-f0-9-]{36}$/.test(incarnation) ||
29
+ [...url.searchParams.keys()].some(key => !['workspace', 'lang'].includes(key) || url.searchParams.getAll(key).length !== 1) ||
30
+ url.searchParams.has('lang') && !['en', 'ko'].includes(url.searchParams.get('lang')!)) throw new Error('JOB_REQUEST_INVALID');
31
+ const slot = 'rig-review-job-hub/1:' + url.origin + ':' + incarnation;
32
+ let capability = url.hash.startsWith('#cap=') ? url.hash.slice(5) : '';
33
+ if (!/^[a-f0-9]{64}$/.test(capability)) capability = '';
34
+ try {
35
+ if (capability) storage?.setItem(slot, capability);
36
+ else capability = storage?.getItem(slot) ?? '';
37
+ } catch { /* Memory-only owner access. */ }
38
+ if (!/^[a-f0-9]{64}$/.test(capability)) capability = '';
39
+ url.hash = ''; replace(url.href);
40
+ return {incarnation, capability};
41
+ }
42
+ export function checkedJobHubList(value: JobHubList, incarnation: string): JobHubList {
43
+ if (value?.schema !== 'rig-review-job-hub/1' || value.incarnation !== incarnation ||
44
+ !Number.isSafeInteger(value.limit) || value.limit < 1 || value.limit > 32 ||
45
+ !Array.isArray(value.jobs) || value.jobs.length > value.limit) throw new Error('JOB_HUB_STATE_INVALID');
46
+ const ids = new Set<string>();
47
+ for (const job of value.jobs) {
48
+ if (!job || typeof job.jobId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(job.jobId) || ids.has(job.jobId) ||
49
+ !['active', 'closed'].includes(job.status) || !Number.isSafeInteger(job.generation) || job.generation < 0 ||
50
+ !Number.isSafeInteger(job.pendingCount) || job.pendingCount < 0 || job.publication !== null &&
51
+ (!job.publication || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(job.publication.publicationId) ||
52
+ !/^[a-f0-9]{64}$/.test(job.publication.instanceKey) || !/^[a-f0-9]{64}$/.test(job.publication.sourceHash) ||
53
+ typeof job.publication.label !== 'string' || job.publication.label.length > 512)) throw new Error('JOB_HUB_STATE_INVALID');
54
+ ids.add(job.jobId);
55
+ }
56
+ return value;
57
+ }
58
+
59
+ export async function mountJobHub(root: HTMLElement): Promise<() => void> {
60
+ const i18n = await import('./i18n.ts');
61
+ const {t, getLanguage} = i18n;
62
+ let storage: Storage | null = null;
63
+ try {storage = sessionStorage;} catch { /* Memory-only access. */ }
64
+ const access = jobHubAccess(location.href, storage, href => history.replaceState(history.state, '', href));
65
+ const requestedLanguage = new URL(location.href).searchParams.get('lang');
66
+ if (requestedLanguage === 'en' || requestedLanguage === 'ko') i18n.setLanguagePreference(requestedLanguage);
67
+ const header = document.createElement('header'); header.className = 'hub-header';
68
+ const title = document.createElement('h1');
69
+ const notice = document.createElement('p'); notice.className = 'hub-status'; notice.setAttribute('role', 'status');
70
+ const language = document.createElement('select');
71
+ for (const name of ['en', 'ko']) {const option = document.createElement('option'); option.value = name; language.append(option);}
72
+ header.append(title, notice, language);
73
+ const list = document.createElement('nav'); list.className = 'hub-list';
74
+ const stage = document.createElement('main'); stage.className = 'hub-stage';
75
+ root.replaceChildren(header, list, stage);
76
+ type Frame = {frame: HTMLIFrameElement; row: JobHubRow; binding: JobHubBinding; announced?: JobHubBinding};
77
+ const frames = new Map<string, Frame>(), cancellation = new AbortController();
78
+ let current: JobHubList | null = null, selected: string | null = null, intent = 0, disposed = false;
79
+ let status = 'job.hubHint', timer: ReturnType<typeof setTimeout> | undefined;
80
+ const binding = (row: JobHubRow): JobHubBinding => ({incarnation: access.incarnation, jobId: row.jobId,
81
+ publicationId: row.publication?.publicationId ?? null, sourceHash: row.publication?.sourceHash ?? null});
82
+ function visibility(entry: Frame) {
83
+ entry.frame.contentWindow?.postMessage({...entry.binding, schema: JOB_HUB_VISIBILITY,
84
+ visible: entry.row.jobId === selected, language: getLanguage()}, location.origin);
85
+ }
86
+ function showSelection() {
87
+ for (const entry of frames.values()) {
88
+ entry.frame.hidden = entry.row.jobId !== selected;
89
+ entry.frame.inert = entry.frame.hidden;
90
+ entry.frame.setAttribute('aria-hidden', String(entry.frame.hidden)); visibility(entry);
91
+ }
92
+ }
93
+ function render() {
94
+ document.documentElement.lang = getLanguage();
95
+ title.textContent = t('job.hubTitle'); document.title = t('job.hubTitle'); notice.textContent = t(status);
96
+ list.setAttribute('aria-label', t('job.hubJobs')); language.setAttribute('aria-label', t('interview.language'));
97
+ language.options[0]!.textContent = t('English'); language.options[1]!.textContent = t('Korean'); language.value = getLanguage();
98
+ list.replaceChildren();
99
+ for (const row of current?.jobs ?? []) {
100
+ const button = document.createElement('button'); button.type = 'button';
101
+ button.dataset.jobId = row.jobId; button.setAttribute('aria-pressed', String(row.jobId === selected));
102
+ const name = document.createElement('span'); name.textContent = row.publication?.label || row.jobId;
103
+ const state = document.createElement('span'); state.className = 'hub-job-state';
104
+ state.textContent = row.status === 'closed' ? t('job.hubClosed') : t('job.hubPending', [row.pendingCount]);
105
+ const source = document.createElement('span'); source.className = 'hub-job-source'; source.textContent = row.publication?.sourceHash ?? '';
106
+ button.append(name, state, source);
107
+ button.onclick = () => {void select(row).catch(() => {status = 'JOB_HUB_REQUEST_REFUSED'; render();});}; list.append(button);
108
+ }
109
+ }
110
+ async function select(row: JobHubRow) {
111
+ const selection = ++intent;
112
+ let entry = frames.get(row.jobId);
113
+ if (!entry && row.status === 'closed') {
114
+ selected = row.jobId; status = 'job.hubClosed'; showSelection(); render(); return;
115
+ }
116
+ if (!entry) {
117
+ if (!current || frames.size >= current.limit) throw new Error('JOB_HUB_LIMIT');
118
+ const response = await fetch('/hub/api/jobs/' + row.jobId + '/open', {method: 'POST',
119
+ headers: {'Content-Type': 'application/json', 'X-Review-Capability': access.capability},
120
+ body: JSON.stringify({schema: 'rig-review-job-hub/1', incarnation: access.incarnation}),
121
+ signal: AbortSignal.any([cancellation.signal, AbortSignal.timeout(5000)])});
122
+ const grant = await response.json();
123
+ if (!response.ok) throw new Error('JOB_HUB_REQUEST_REFUSED');
124
+ if (disposed || selection !== intent) return;
125
+ if (grant.schema !== 'rig-review-job-hub/1' || grant.incarnation !== access.incarnation || grant.jobId !== row.jobId ||
126
+ grant.entry !== '/jobs/' + row.jobId + '/?hub=' + access.incarnation || !/^[a-f0-9]{64}$/.test(grant.capability)) throw new Error('JOB_HUB_STATE_INVALID');
127
+ const url = new URL(grant.entry, location.origin); url.searchParams.set('lang', getLanguage()); url.hash = 'cap=' + grant.capability;
128
+ const frame = document.createElement('iframe'); frame.title = row.publication?.label || row.jobId; frame.hidden = true; frame.src = url.href;
129
+ entry = {frame, row, binding: {...binding(row), publicationId: null, sourceHash: null}};
130
+ frames.set(row.jobId, entry); stage.append(frame);
131
+ }
132
+ selected = row.jobId; status = 'job.hubHint'; showSelection(); render();
133
+ }
134
+ function ready(event: MessageEvent) {
135
+ const entry = frames.get(event.data?.jobId);
136
+ if (!entry || !current) return;
137
+ const candidate: JobHubBinding = {incarnation: access.incarnation, jobId: entry.row.jobId,
138
+ publicationId: event.data?.publicationId, sourceHash: event.data?.sourceHash};
139
+ if (!jobHubMessageMatches(event, location.origin, entry.frame.contentWindow, candidate, 'ready')) return;
140
+ entry.announced = candidate;
141
+ if (jobHubMessageMatches(event, location.origin, entry.frame.contentWindow, binding(entry.row), 'ready')) {
142
+ entry.binding = candidate; visibility(entry);
143
+ }
144
+ }
145
+ async function refresh() {
146
+ try {
147
+ const response = await fetch('/hub/api/jobs', {headers: {'X-Review-Capability': access.capability},
148
+ signal: AbortSignal.any([cancellation.signal, AbortSignal.timeout(5000)])});
149
+ if (!response.ok) throw new Error('JOB_HUB_REQUEST_REFUSED');
150
+ current = checkedJobHubList(await response.json(), access.incarnation);
151
+ for (const row of current.jobs) {
152
+ const entry = frames.get(row.jobId);
153
+ if (!entry) continue;
154
+ entry.row = row;
155
+ if (entry.announced && JSON.stringify(entry.announced) === JSON.stringify(binding(row))) entry.binding = entry.announced;
156
+ visibility(entry);
157
+ }
158
+ render();
159
+ if (!selected && current.jobs[0]) await select(current.jobs[0]);
160
+ } catch {if (!disposed) {status = 'JOB_HUB_REQUEST_REFUSED'; render();}}
161
+ finally {if (!disposed) timer = setTimeout(() => {void refresh();}, 1000);}
162
+ }
163
+ language.onchange = () => {i18n.setLinkLanguage(null); i18n.setLanguagePreference(language.value === 'ko' ? 'ko' : 'en');};
164
+ const unlocalize = i18n.onLanguageChange(() => {render(); showSelection();});
165
+ globalThis.addEventListener('message', ready);
166
+ const stop = () => {
167
+ if (disposed) return;
168
+ disposed = true; clearTimeout(timer); cancellation.abort(); unlocalize();
169
+ globalThis.removeEventListener('message', ready); globalThis.removeEventListener('pagehide', stop);
170
+ };
171
+ globalThis.addEventListener('pagehide', stop, {once: true});
172
+ render(); void refresh(); return stop;
173
+ }
174
+ if (typeof document !== 'undefined' && document.body?.hasAttribute('data-job-hub')) {
175
+ void mountJobHub(document.getElementById('job-hub')!).catch(async () => {
176
+ const {t} = await import('./i18n.ts');
177
+ document.getElementById('job-hub')!.textContent = t('JOB_HUB_REQUEST_REFUSED');
178
+ });
179
+ }