@sparkelf/dsh-ocr 0.0.0-stage → 0.1.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/lib/index.js ADDED
@@ -0,0 +1,485 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import z from "@deepseek-ai/schemastery";
5
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
6
+ //#region src/api.ts
7
+ /**
8
+ * The same-origin API surface shared by this package's two halves.
9
+ *
10
+ * The Host registers one prefix and dispatches on the trailing method name; the browser
11
+ * calls the same strings. Keeping them in one module is what stops the two halves
12
+ * drifting apart -- the failure mode knowledge-base recorded when its panel called
13
+ * `/knowledge-base/config` while its Host served `/knowledge-base/api/config`.
14
+ *
15
+ * The namespace is `ocr` rather than a shared one, so this route can never collide with
16
+ * the knowledge base's `/knowledge-base/api/*` or any other plugin's prefix.
17
+ *
18
+ * This module must stay dependency-free so both bundles can import it: the Client bundle
19
+ * rejects Node builtins and non-platform packages.
20
+ *
21
+ * @module @sparkelf/dsh-ocr/api
22
+ */
23
+ /** Prefix the Host registers and the browser calls. */
24
+ const OCR_API_PREFIX = "/ocr/api";
25
+ /** Method names the Host dispatches on. */
26
+ const OCR_API = {
27
+ /** The shared MinerU address plus whether the caller may change it. */
28
+ config: "config",
29
+ /** How many members a distribution reaches, and how many it would replace. */
30
+ impact: "impact",
31
+ /** Fill only members that hold no address of their own. */
32
+ distributeDefault: "distribute-default",
33
+ /** Replace every member's address, including ones they chose themselves. */
34
+ overwrite: "overwrite",
35
+ /**
36
+ * Probe a MinerU address before saving it.
37
+ *
38
+ * Not a backend route: the Host answers this one itself, because only this process can
39
+ * reach the address from inside the workspace network. It still reads the stored config
40
+ * through the backend first, so a caller who may not edit cannot make the relay fetch an
41
+ * arbitrary URL.
42
+ */
43
+ testConnection: "test-connection"
44
+ };
45
+ //#endregion
46
+ //#region src/index.ts
47
+ /**
48
+ * Host half of the document-text-recognition plugin.
49
+ *
50
+ * Two contributions, and they serve different audiences:
51
+ *
52
+ * 1. **The skill provider.** The package ships one file the model needs -- `SKILL.md` -- and
53
+ * it does not live under a directory the skill registry scans, because `node_modules` is
54
+ * not a scan root. Registering it explicitly is the same thing
55
+ * `@sparkelf/dsh-dataops-admin` and `@sparkelf/dsh-knowledge-base` do.
56
+ *
57
+ * 2. **The settings route.** The settings page cannot call the DataOps backend directly: the
58
+ * browser's credential is an httpOnly cookie and the backend's `/api/ocr/*` routes want a
59
+ * bearer. This Host holds the DataOps JWT (or adopts the one the gateway attached), so it
60
+ * relays the four OCR calls and the page talks only to this process.
61
+ *
62
+ * The MinerU address is NOT stored here. Every member gets their own workspace container and
63
+ * their own DSH profile, so a per-profile setting cannot reach anybody else; the shared value
64
+ * lives in the backend (`GET /api/ocr/config`), which this half reads and relays. A copy in
65
+ * this profile would be a second source of truth that silently goes stale.
66
+ *
67
+ * @module @sparkelf/dsh-ocr
68
+ */
69
+ /** The name this plugin mounts as in the profile composition. */
70
+ const PLUGIN_NAME = "@sparkelf/dsh-ocr";
71
+ /**
72
+ * Host services this plugin needs before `apply` runs.
73
+ *
74
+ * Declared rather than reached for: Cordis resolves a service through the plugin's own
75
+ * context, and touching one that was not injected throws
76
+ * `cannot get property "webServer" without inject` during apply -- which took the whole
77
+ * plugin down and, with it, the skill registration. `webServer` carries the settings relay,
78
+ * `credentials` resolves the fallback DataOps token.
79
+ *
80
+ * `skills` is deliberately absent: the registry is an OPTIONAL neighbour, so it is reached
81
+ * through `ctx.inject` inside apply and skipped on a host that does not have it.
82
+ */
83
+ const inject = ["webServer", "credentials"];
84
+ /** Provider name reported to the skill registry. */
85
+ const SKILL_PROVIDER = "dsh-ocr";
86
+ /**
87
+ * Name the model sees in the skill catalog.
88
+ *
89
+ * Must match `^[a-z0-9]+(?:-[a-z0-9]+)*$`: the skill center silently skips a directory that
90
+ * does not, and this value keys the provider.
91
+ */
92
+ const SKILL_NAME = "ocr";
93
+ /**
94
+ * Short description shown in the skill list.
95
+ *
96
+ * Kept beside the SKILL.md body rather than parsed out of its frontmatter: the catalog
97
+ * answers `list()` without reading any skill content, so the text has to be available
98
+ * without touching the file.
99
+ */
100
+ const SKILL_DESCRIPTION = "识别 PDF、图片、扫描件等文档中的文字并输出 Markdown,使用管理员统一配置的 MinerU 服务。";
101
+ /**
102
+ * Display name the skill center shows for this skill.
103
+ *
104
+ * Deliberately NOT the registry name: `ocr` is the internal identifier, while users must see
105
+ * a business-facing Chinese name. The skill center reads the display name from the
106
+ * `i18n/zh.json` beside SKILL.md; this constant is the same string, so a host that reports
107
+ * the catalog without the translation file still has the right name.
108
+ */
109
+ const SKILL_DISPLAY_NAME = "文档文字识别";
110
+ /**
111
+ * Where this package's SKILL.md lives, from either build layout.
112
+ *
113
+ * The build emits `lib/index.js` while a source run executes from `src/`; both sit one level
114
+ * below the package root, so the same `..` answers both.
115
+ *
116
+ * @returns absolute path of the skill document.
117
+ */
118
+ function skillPath() {
119
+ return join(dirname(fileURLToPath(import.meta.url)), "..", "SKILL.md");
120
+ }
121
+ /** Both a human and the model may invoke this skill. */
122
+ const SKILL_INVOCATION = {
123
+ modelInvocable: true,
124
+ userInvocable: true
125
+ };
126
+ /**
127
+ * Rank places this beside the other bundled DataOps capabilities.
128
+ *
129
+ * `knowledge-base` uses 640 and `dataops-admin` uses 641; this one follows them. The value
130
+ * orders a catalog listing, not a priority -- the model reaches for these by name.
131
+ */
132
+ const SKILL_RANK = 642;
133
+ /** Backend path each relayed method calls, and the HTTP method it uses. */
134
+ const OCR_BACKEND_ROUTES = {
135
+ config: {
136
+ path: "/api/ocr/config",
137
+ method: "GET"
138
+ },
139
+ impact: {
140
+ path: "/api/ocr/admin/impact",
141
+ method: "GET"
142
+ },
143
+ "distribute-default": {
144
+ path: "/api/ocr/admin/distribute-default",
145
+ method: "POST"
146
+ },
147
+ overwrite: {
148
+ path: "/api/ocr/admin/overwrite",
149
+ method: "POST"
150
+ }
151
+ };
152
+ /**
153
+ * The skill provider that teaches the model to recognise document text.
154
+ *
155
+ * One bundled skill, read from disk on `get()` rather than kept in memory: the body is
156
+ * documentation, and a host that never asks for it should not pay for it.
157
+ *
158
+ * @returns a provider the skill registry can register.
159
+ */
160
+ function ocrSkillProvider() {
161
+ const path = skillPath();
162
+ const candidate = {
163
+ name: "ocr",
164
+ description: SKILL_DESCRIPTION,
165
+ invocation: SKILL_INVOCATION,
166
+ source: "bundled",
167
+ provider: SKILL_PROVIDER,
168
+ path,
169
+ resourceBase: {
170
+ kind: "directory",
171
+ path: dirname(path)
172
+ },
173
+ rank: 642,
174
+ locator: path
175
+ };
176
+ return {
177
+ name: SKILL_PROVIDER,
178
+ list: () => Promise.resolve([candidate]),
179
+ get: () => Promise.resolve({
180
+ ...candidate,
181
+ content: readFileSync(path, "utf8")
182
+ })
183
+ };
184
+ }
185
+ /**
186
+ * Read the bearer the browser gateway attached to one request.
187
+ *
188
+ * The page cannot supply its own credential: every browser request reaches this workspace
189
+ * through the DataOps gateway, which resolves the caller's session and forwards a fresh
190
+ * `authorization: Bearer <jwt>`. Relaying exactly that header is what keeps the backend's
191
+ * `AuthGuard` and `PermissionGuard` judging the CALLER rather than this plugin: the admin
192
+ * routes answer 403 for a member who is not a super administrator because the token in the
193
+ * header is theirs, not a service account's.
194
+ *
195
+ * @param request - the incoming request, whose headers the gateway filled in.
196
+ * @returns the token, or undefined when the request carries none.
197
+ */
198
+ function bearerToken(request) {
199
+ const authorization = request.headers.authorization?.trim() ?? "";
200
+ if (!authorization.startsWith("Bearer ")) return void 0;
201
+ const token = authorization.slice(7).trim();
202
+ return token === "" ? void 0 : token;
203
+ }
204
+ /** Config schema; an invalid value fails the profile load loudly. */
205
+ const Config = z.object({
206
+ baseUrl: z.string().default(""),
207
+ credentialRef: z.string().role("credential-ref").default("DATAOPS_ACCESS_TOKEN"),
208
+ timeoutMs: z.number().default(15e3)
209
+ });
210
+ /**
211
+ * Resolve the token one relayed call acts with.
212
+ *
213
+ * The caller's own header wins: it is the only value that makes the backend's permission
214
+ * checks correct. The stored credential is the fallback for a same-origin fetch that arrived
215
+ * without a header (a probe, or an older page); a plugin instance without either refuses
216
+ * rather than calling the backend anonymously, because an anonymous call would be answered
217
+ * 401 by the backend anyway and the page could not tell why.
218
+ *
219
+ * @param ctx - host context carrying the credential store.
220
+ * @param config - relay configuration.
221
+ * @param request - the incoming request.
222
+ * @returns the token, or undefined when neither source has one.
223
+ */
224
+ async function resolveRelayToken(ctx, config, request) {
225
+ const fromRequest = bearerToken(request);
226
+ if (fromRequest !== void 0) return fromRequest;
227
+ const value = (await ctx.credentials.resolve(credentialRef(config.credentialRef)).catch(() => void 0))?.value.trim() ?? "";
228
+ return value === "" ? void 0 : value;
229
+ }
230
+ /**
231
+ * Call one DataOps OCR route with the caller's authority.
232
+ *
233
+ * Kept separate from the route handler so the mapping from a page method to a backend path
234
+ * is testable without a server.
235
+ *
236
+ * @param method - which of the four relayed routes the page asked for.
237
+ * @param config - backend origin, credential fallback, and the call bound.
238
+ * @param token - the bearer to act with; a call without one is refused before the round trip.
239
+ * @param body - the JSON body, for the two write routes.
240
+ * @returns the backend's status and decoded body.
241
+ */
242
+ async function callOcrBackend(method, config, token, body) {
243
+ if (token === void 0) return {
244
+ status: 401,
245
+ body: { error: "the request carries no DataOps session token" }
246
+ };
247
+ if (config.baseUrl.trim() === "") return {
248
+ status: 503,
249
+ body: { error: "the DataOps backend address is not configured" }
250
+ };
251
+ const route = OCR_BACKEND_ROUTES[method];
252
+ const url = `${config.baseUrl.trim().replace(/\/+$/u, "")}${route.path}`;
253
+ let response;
254
+ try {
255
+ response = await fetch(url, {
256
+ method: route.method,
257
+ headers: {
258
+ authorization: `Bearer ${token}`,
259
+ ...route.method === "POST" ? { "content-type": "application/json" } : {}
260
+ },
261
+ ...route.method === "POST" ? { body: JSON.stringify(body ?? {}) } : {},
262
+ signal: AbortSignal.timeout(config.timeoutMs)
263
+ });
264
+ } catch (cause) {
265
+ return {
266
+ status: 502,
267
+ body: {
268
+ error: `the DataOps backend is unreachable at ${url}`,
269
+ detail: String(cause)
270
+ }
271
+ };
272
+ }
273
+ const decoded = await response.json().catch(() => ({}));
274
+ return {
275
+ status: response.status,
276
+ body: decoded
277
+ };
278
+ }
279
+ /** Longest a single connection test may block the settings panel. */
280
+ const PROBE_TIMEOUT_MS = 8e3;
281
+ /**
282
+ * Probe one MinerU address from this process.
283
+ *
284
+ * The OpenAPI document is the cheapest endpoint that both proves an HTTP server answers
285
+ * and identifies it: MinerU titles its document "MinerU API", so a 200 with that title is
286
+ * a real match rather than "something is listening on this port". Any other 200 is
287
+ * reported as `not-mineru` -- a proxy error page or a different service are both reasons
288
+ * the reader should not save the address.
289
+ *
290
+ * The probe deliberately does not use the caller's DataOps credential: MinerU is not a
291
+ * DataOps service and has its own (usually absent) auth. It also refuses non-http(s)
292
+ * schemes so the relay cannot be used to read `file:` or `ftp:` URLs.
293
+ * @param address - the candidate base address, as typed or as stored.
294
+ * @param timeoutMs - the caller's relay bound; the probe is clamped to {@link PROBE_TIMEOUT_MS}.
295
+ * @returns a structured verdict for the settings page.
296
+ */
297
+ async function probeMineruAddress(address, timeoutMs) {
298
+ const trimmed = address.trim();
299
+ let base;
300
+ try {
301
+ base = new URL(trimmed);
302
+ } catch {
303
+ return {
304
+ ok: false,
305
+ latencyMs: 0,
306
+ code: "bad-url",
307
+ testedUrl: trimmed
308
+ };
309
+ }
310
+ if (base.protocol !== "http:" && base.protocol !== "https:") return {
311
+ ok: false,
312
+ latencyMs: 0,
313
+ code: "bad-url",
314
+ testedUrl: trimmed
315
+ };
316
+ const endpoint = base.toString().replace(/\/+$/u, "") + "/openapi.json";
317
+ const started = Date.now();
318
+ try {
319
+ const response = await fetch(endpoint, {
320
+ method: "GET",
321
+ headers: { accept: "application/json" },
322
+ redirect: "manual",
323
+ signal: AbortSignal.timeout(Math.min(timeoutMs, PROBE_TIMEOUT_MS))
324
+ });
325
+ const latencyMs = Date.now() - started;
326
+ if (response.status !== 200) return {
327
+ ok: false,
328
+ latencyMs,
329
+ code: "http-error",
330
+ status: response.status,
331
+ testedUrl: trimmed
332
+ };
333
+ const document = await response.json().catch(() => void 0);
334
+ const title = typeof document?.info?.title === "string" ? document.info.title : "";
335
+ if (/mineru/iu.test(title)) return {
336
+ ok: true,
337
+ latencyMs,
338
+ code: "ok",
339
+ status: 200,
340
+ message: title,
341
+ testedUrl: trimmed
342
+ };
343
+ return {
344
+ ok: false,
345
+ latencyMs,
346
+ code: "not-mineru",
347
+ status: 200,
348
+ message: title === "" ? "the OpenAPI document has no service title" : title,
349
+ testedUrl: trimmed
350
+ };
351
+ } catch (cause) {
352
+ const message = cause instanceof Error ? cause.message : String(cause);
353
+ const code = /timeout|timed out|aborted/iu.test(message) ? "timeout" : "unreachable";
354
+ return {
355
+ ok: false,
356
+ latencyMs: Date.now() - started,
357
+ code,
358
+ message: message.slice(0, 300),
359
+ testedUrl: trimmed
360
+ };
361
+ }
362
+ }
363
+ /**
364
+ * Write one JSON reply.
365
+ *
366
+ * @param response - the browser-facing response.
367
+ * @param status - HTTP status to send.
368
+ * @param body - value to serialize.
369
+ */
370
+ function writeJson(response, status, body) {
371
+ response.statusCode = status;
372
+ response.setHeader("content-type", "application/json; charset=utf-8");
373
+ response.setHeader("cache-control", "no-store");
374
+ response.end(JSON.stringify(body));
375
+ }
376
+ /**
377
+ * Read a JSON request body, treating an empty body as `{}`.
378
+ *
379
+ * @param request - the incoming request.
380
+ * @returns the parsed object.
381
+ */
382
+ async function readJsonBody(request) {
383
+ return await new Promise((resolve, reject) => {
384
+ const chunks = [];
385
+ request.on("data", (chunk) => {
386
+ chunks.push(chunk);
387
+ });
388
+ request.on("end", () => {
389
+ const text = Buffer.concat(chunks).toString("utf8").trim();
390
+ if (text === "") return resolve({});
391
+ try {
392
+ resolve(JSON.parse(text));
393
+ } catch (error) {
394
+ reject(new Error("request body is not valid JSON", { cause: error }));
395
+ }
396
+ });
397
+ request.on("error", reject);
398
+ });
399
+ }
400
+ /**
401
+ * Answer one `test-connection` request.
402
+ *
403
+ * The stored config is read through the backend first, for two reasons that are really
404
+ * one: the backend is the authority on whether this caller may change the address, and a
405
+ * caller who may not change it must not be able to make this process fetch an arbitrary
406
+ * URL. A super administrator may test the value they are about to save; everyone else
407
+ * tests the shared value.
408
+ * @param ctx - the host context, for the caller's token.
409
+ * @param config - backend origin and probe bound.
410
+ * @param request - the browser request, whose body may carry a candidate address.
411
+ * @param response - the reply.
412
+ */
413
+ async function answerConnectionTest(ctx, config, request, response) {
414
+ const token = await resolveRelayToken(ctx, config, request);
415
+ if (token === void 0) {
416
+ writeJson(response, 401, { error: "the request carries no DataOps session token" });
417
+ return;
418
+ }
419
+ const current = await callOcrBackend("config", config, token);
420
+ if (current.status !== 200) {
421
+ writeJson(response, 503, {
422
+ error: "the caller role could not be checked against the DataOps backend",
423
+ detail: current.body
424
+ });
425
+ return;
426
+ }
427
+ const view = current.body;
428
+ const stored = typeof view.mineruUrl === "string" ? view.mineruUrl : "";
429
+ const body = await readJsonBody(request);
430
+ const candidate = typeof body.mineruUrl === "string" ? body.mineruUrl.trim() : "";
431
+ writeJson(response, 200, await probeMineruAddress(view.canEdit === true && candidate !== "" ? candidate : stored, config.timeoutMs));
432
+ }
433
+ /**
434
+ * Mount the skill provider and the settings relay on a host context.
435
+ *
436
+ * `inject` rather than a hard dependency entry, and the `typeof` guard around it, are both
437
+ * copied from `@sparkelf/dsh-knowledge-base`: the skill registry is an optional neighbour, and
438
+ * calling `inject` on a host that does not expose it would throw during apply and take the
439
+ * whole plugin down.
440
+ *
441
+ * @param host - the plugin context.
442
+ * @param resolvedConfig - backend origin, credential fallback, and call bound.
443
+ */
444
+ function apply(host, resolvedConfig) {
445
+ if (host === null || host === void 0) return;
446
+ const ctx = host;
447
+ const hostWithInject = ctx;
448
+ if (typeof hostWithInject.inject === "function") hostWithInject.inject(["skills"], (scoped) => {
449
+ scoped.skills.registerProvider(() => ocrSkillProvider());
450
+ });
451
+ if (ctx.webServer === void 0 || ctx.credentials === void 0 || typeof ctx.effect !== "function") return;
452
+ const config = {
453
+ baseUrl: resolvedConfig?.baseUrl ?? "",
454
+ credentialRef: resolvedConfig?.credentialRef ?? "DATAOPS_ACCESS_TOKEN",
455
+ timeoutMs: resolvedConfig?.timeoutMs ?? 15e3
456
+ };
457
+ ctx.effect(() => ctx.webServer.register({
458
+ kind: "prefix",
459
+ path: OCR_API_PREFIX,
460
+ handler: async (request, response) => {
461
+ const method = new URL(request.url ?? "/", "http://dsh.internal").pathname.slice(`${OCR_API_PREFIX}/`.length);
462
+ try {
463
+ if (method === OCR_API.testConnection) {
464
+ await answerConnectionTest(ctx, config, request, response);
465
+ return;
466
+ }
467
+ const route = OCR_BACKEND_ROUTES[method];
468
+ if (route === void 0) {
469
+ writeJson(response, 404, { error: `unknown document-recognition method: ${method}` });
470
+ return;
471
+ }
472
+ const token = await resolveRelayToken(ctx, config, request);
473
+ const body = route.method === "POST" ? await readJsonBody(request) : void 0;
474
+ const result = await callOcrBackend(method, config, token, body);
475
+ writeJson(response, result.status, result.body);
476
+ } catch (error) {
477
+ ctx.logger?.warn?.("dsh-ocr: settings relay failed");
478
+ ctx.logger?.warn?.(error);
479
+ writeJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
480
+ }
481
+ }
482
+ }), "dsh-ocr: settings relay");
483
+ }
484
+ //#endregion
485
+ export { Config, OCR_BACKEND_ROUTES, PLUGIN_NAME, PROBE_TIMEOUT_MS, SKILL_DESCRIPTION, SKILL_DISPLAY_NAME, SKILL_INVOCATION, SKILL_NAME, SKILL_PROVIDER, SKILL_RANK, answerConnectionTest, apply, bearerToken, callOcrBackend, inject, ocrSkillProvider, probeMineruAddress, readJsonBody, resolveRelayToken, skillPath, writeJson };
@@ -0,0 +1,134 @@
1
+ /**
2
+ * The same-origin API surface shared by this package's two halves.
3
+ *
4
+ * The Host registers one prefix and dispatches on the trailing method name; the browser
5
+ * calls the same strings. Keeping them in one module is what stops the two halves
6
+ * drifting apart -- the failure mode knowledge-base recorded when its panel called
7
+ * `/knowledge-base/config` while its Host served `/knowledge-base/api/config`.
8
+ *
9
+ * The namespace is `ocr` rather than a shared one, so this route can never collide with
10
+ * the knowledge base's `/knowledge-base/api/*` or any other plugin's prefix.
11
+ *
12
+ * This module must stay dependency-free so both bundles can import it: the Client bundle
13
+ * rejects Node builtins and non-platform packages.
14
+ *
15
+ * @module @sparkelf/dsh-ocr/api
16
+ */
17
+ /** Prefix the Host registers and the browser calls. */
18
+ export declare const OCR_API_PREFIX = "/ocr/api";
19
+ /** Method names the Host dispatches on. */
20
+ export declare const OCR_API: {
21
+ /** The shared MinerU address plus whether the caller may change it. */
22
+ readonly config: "config";
23
+ /** How many members a distribution reaches, and how many it would replace. */
24
+ readonly impact: "impact";
25
+ /** Fill only members that hold no address of their own. */
26
+ readonly distributeDefault: "distribute-default";
27
+ /** Replace every member's address, including ones they chose themselves. */
28
+ readonly overwrite: "overwrite";
29
+ /**
30
+ * Probe a MinerU address before saving it.
31
+ *
32
+ * Not a backend route: the Host answers this one itself, because only this process can
33
+ * reach the address from inside the workspace network. It still reads the stored config
34
+ * through the backend first, so a caller who may not edit cannot make the relay fetch an
35
+ * arbitrary URL.
36
+ */
37
+ readonly testConnection: "test-connection";
38
+ };
39
+ /** One valid method name. */
40
+ export type OcrApiMethod = typeof OCR_API[keyof typeof OCR_API];
41
+ /**
42
+ * Build the browser path for one method.
43
+ * @param method - one of {@link OCR_API}.
44
+ * @returns the same-origin path the Host dispatches on.
45
+ */
46
+ export declare function ocrApiPath(method: OcrApiMethod): string;
47
+ /**
48
+ * The shared configuration as the settings page reads it.
49
+ *
50
+ * `mineruUrl === ''` is "not configured yet", not an error: a deployment is allowed to
51
+ * have never had an OCR address. `canEdit` decides between two renderings of the same
52
+ * page and never whether the address may be USED -- every signed-in member can recognize
53
+ * documents with the shared value.
54
+ */
55
+ export interface OcrConfigView {
56
+ /** The shared MinerU base address, or `''` when none is stored. */
57
+ mineruUrl: string;
58
+ /** Whether the caller holds the one role this deployment lets change the shared value. */
59
+ canEdit: boolean;
60
+ }
61
+ /**
62
+ * How many members a distribution reaches.
63
+ *
64
+ * `withValue` is what an overwrite would replace while `onlyIfEmpty` would skip it, so
65
+ * the confirmation can name the number it is about to disturb instead of asking "are you
66
+ * sure?" with no quantity.
67
+ */
68
+ export interface OcrImpactView {
69
+ /** Members who already hold an address of their own. */
70
+ withValue: number;
71
+ /** Members who hold none; `onlyIfEmpty` fills exactly these. */
72
+ withoutValue: number;
73
+ /** Every member the distribution considers. */
74
+ total: number;
75
+ }
76
+ /** Per-bucket counts one distribution reports back. */
77
+ export interface OcrDistributionView {
78
+ /** `onlyIfEmpty` or `force`, as the backend names the two modes. */
79
+ mode?: string;
80
+ /** Members written. */
81
+ filled: number;
82
+ /** Members left alone. */
83
+ skipped: number;
84
+ /** Members whose write failed. */
85
+ failed: number;
86
+ /** Every member considered. */
87
+ total: number;
88
+ }
89
+ /**
90
+ * A refusal the page must show rather than swallow.
91
+ *
92
+ * The two write routes answer 400 for an empty address and 403 for a caller without the
93
+ * role. Both are decisions, so the page reports them instead of retrying.
94
+ */
95
+ export interface OcrErrorView {
96
+ /** The backend's own message, already in the reader's language. */
97
+ error: string;
98
+ }
99
+ /** Why a probe ended as it did. The page maps these codes to locale copy. */
100
+ export type OcrProbeCode =
101
+ /** The address answered as a MinerU service. */
102
+ 'ok'
103
+ /** Not an absolute http(s) address, so there is nothing to call. */
104
+ | 'bad-url'
105
+ /** No answer inside the probe window. */
106
+ | 'timeout'
107
+ /** The connection was refused, DNS failed, or the host is unreachable. */
108
+ | 'unreachable'
109
+ /** An HTTP server answered, but its OpenAPI document is not MinerU's. */
110
+ | 'not-mineru'
111
+ /** The service answered with a non-2xx status. */
112
+ | 'http-error';
113
+ /**
114
+ * What a connection test reports.
115
+ *
116
+ * `latencyMs` is measured around the probe request, not the whole redirect chain: a
117
+ * number that included the backend round trip would blame the MinerU box for the relay's
118
+ * latency. `testedUrl` is echoed because the caller may have typed a candidate before
119
+ * saving, and the panel has to label which address the tag refers to.
120
+ */
121
+ export interface OcrProbeView {
122
+ /** Whether the address is a reachable MinerU service. */
123
+ ok: boolean;
124
+ /** Round-trip time of the probe request, in milliseconds. */
125
+ latencyMs: number;
126
+ /** Machine-readable outcome. */
127
+ code: OcrProbeCode;
128
+ /** The address that was actually tested. */
129
+ testedUrl: string;
130
+ /** HTTP status when a response arrived. */
131
+ status?: number;
132
+ /** A short technical detail, for the tooltip and the operator. */
133
+ message?: string;
134
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The 「文档识别」 settings section.
3
+ *
4
+ * Three actions, and they are genuinely different:
5
+ *
6
+ * - **Test connection** probes the address in the field without saving it. It is the only
7
+ * way to answer "is this address right?" before distributing it to every member.
8
+ * - **Distribute** fills members who hold no address of their own. Nobody's own choice is
9
+ * touched, so it is the safe default.
10
+ * - **Overwrite** replaces every member's address, including one they typed themselves.
11
+ *
12
+ * Both writes are gated on `canEdit`, which the backend answers from the caller's role.
13
+ * The write routes enforce that independently: hiding a button is not a permission, so a
14
+ * caller who forges the request is refused by the backend rather than by this page.
15
+ *
16
+ * The section deliberately carries no explanatory prose: a settings page states the field
17
+ * and its state, and the reader who needs the story has the skill document. The connection
18
+ * tag inside the field is the whole status surface.
19
+ *
20
+ * @module @sparkelf/dsh-ocr/client/SettingsSection
21
+ */
22
+ import type { InjectFace } from '@deepseek-ai/dsh-client-ui-slots';
23
+ import type { en } from './locales.ts';
24
+ /** Values the Settings slot injects into this component. */
25
+ export interface OcrSettingsInjected {
26
+ /** Translate one section message key. */
27
+ t: (key: keyof typeof en) => string;
28
+ }
29
+ /** Props accepted by the injected Settings section. */
30
+ export type OcrSettingsProps = Partial<InjectFace<OcrSettingsInjected>>;
31
+ /**
32
+ * Whether a candidate is an absolute http(s) address.
33
+ *
34
+ * Mirrors the backend's own normaliser, and is checked before the round trip so the answer
35
+ * lands beside the field that was typed into rather than after a request that was always
36
+ * going to be refused. The path is preserved: a MinerU service may sit behind a prefix.
37
+ *
38
+ * @param value - the address as typed.
39
+ * @returns true when it parses and carries an http(s) scheme.
40
+ */
41
+ export declare function isAbsoluteHttpAddress(value: string): boolean;
42
+ /**
43
+ * Render the document-recognition settings section.
44
+ * @param props - the Settings slot injection.
45
+ * @returns the section, or nothing before injection.
46
+ */
47
+ export declare function OcrSettingsSection(props: OcrSettingsProps): import("react").JSX.Element | null;