@apifuse/provider-sdk 2.2.0-beta.5 → 2.2.0-beta.51
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/AUTHORING.md +537 -33
- package/CHANGELOG.md +205 -1
- package/README.md +83 -22
- package/SUBMISSION.md +2 -2
- package/bin/apifuse-check.ts +165 -11
- package/bin/apifuse-dev.ts +57 -13
- package/bin/apifuse-migrate-operation-declaration.ts +55 -0
- package/bin/apifuse-migrate-shape.ts +202 -0
- package/bin/apifuse-pack-check.ts +22 -2
- package/bin/apifuse-pack-smoke.ts +57 -2
- package/bin/apifuse-pack-types.ts +357 -38
- package/bin/apifuse-perf.ts +14 -13
- package/bin/apifuse-record.ts +709 -72
- package/bin/apifuse-submit-check.ts +2344 -324
- package/bin/apifuse-sync-assets.ts +117 -0
- package/bin/submit-check-delimited-text.ts +50 -0
- package/dist/auth-turn/index.d.ts +3 -3
- package/dist/auth-turn/index.js +1 -1
- package/dist/auth.d.ts +14 -0
- package/dist/auth.js +67 -0
- package/dist/ceremonies/index.d.ts +16 -0
- package/dist/ceremonies/index.js +141 -36
- package/dist/cli/commands.d.ts +1 -1
- package/dist/cli/commands.js +27 -0
- package/dist/cli/create.d.ts +4 -1
- package/dist/cli/create.js +42 -37
- package/dist/cli/migrate-operation-declaration.d.ts +59 -0
- package/dist/cli/migrate-operation-declaration.js +1249 -0
- package/dist/cli/migrate-operation-shape.d.ts +44 -0
- package/dist/cli/migrate-operation-shape.js +113 -0
- package/dist/cli/migrate-provider-shape.d.ts +52 -0
- package/dist/cli/migrate-provider-shape.js +578 -0
- package/dist/cli/prompt-assets.d.ts +80 -0
- package/dist/cli/prompt-assets.js +743 -0
- package/dist/cli/templates/provider/AGENTS.md.tpl +17 -8
- package/dist/cli/templates/provider/Dockerfile.tpl +1 -1
- package/dist/cli/templates/provider/README.md.tpl +5 -5
- package/dist/cli/templates/provider/index.ts.tpl +6 -3
- package/dist/cli/templates/provider/operations/ping.ts.tpl +4 -1
- package/dist/cli/templates/provider/provider.json.tpl +6 -0
- package/dist/config/loader.d.ts +179 -16
- package/dist/config/loader.js +435 -127
- package/dist/contract-serialization.js +4 -8
- package/dist/contract-types.d.ts +12 -5
- package/dist/contract.js +24 -10
- package/dist/declaration-validation.d.ts +33 -0
- package/dist/declaration-validation.js +266 -0
- package/dist/define.d.ts +66 -29
- package/dist/define.js +778 -69
- package/dist/dev.d.ts +3 -0
- package/dist/dev.js +1 -1
- package/dist/engine.d.ts +78 -0
- package/dist/engine.js +133 -0
- package/dist/error-observability.d.ts +7 -0
- package/dist/error-observability.js +61 -0
- package/dist/error-resolution.d.ts +4 -0
- package/dist/error-resolution.js +122 -0
- package/dist/errors.d.ts +33 -0
- package/dist/errors.js +40 -0
- package/dist/fixture-sanitization.d.ts +28 -0
- package/dist/fixture-sanitization.js +227 -0
- package/dist/health-scenario.d.ts +1842 -0
- package/dist/health-scenario.js +624 -0
- package/dist/index.d.ts +21 -10
- package/dist/index.js +12 -7
- package/dist/lint.d.ts +23 -11
- package/dist/lint.js +572 -69
- package/dist/native-address.d.ts +43 -0
- package/dist/native-address.js +281 -0
- package/dist/native-egress-policy.d.ts +31 -0
- package/dist/native-egress-policy.js +288 -0
- package/dist/observability.d.ts +5 -2
- package/dist/observability.js +48 -1
- package/dist/provider.d.ts +10 -2
- package/dist/provider.js +4 -1
- package/dist/runtime/auth-flow.d.ts +5 -1
- package/dist/runtime/auth-flow.js +6 -0
- package/dist/runtime/browser.d.ts +1 -0
- package/dist/runtime/browser.js +492 -49
- package/dist/runtime/cache.d.ts +1 -0
- package/dist/runtime/cache.js +169 -15
- package/dist/runtime/choice-wordlist.d.ts +9 -0
- package/dist/runtime/choice-wordlist.js +138 -0
- package/dist/runtime/choice.d.ts +13 -1
- package/dist/runtime/choice.js +490 -102
- package/dist/runtime/chrome149-header-order.d.ts +58 -0
- package/dist/runtime/chrome149-header-order.js +289 -0
- package/dist/runtime/env.js +12 -0
- package/dist/runtime/executor.d.ts +3 -2
- package/dist/runtime/executor.js +26 -25
- package/dist/runtime/http.d.ts +1 -0
- package/dist/runtime/http.js +515 -53
- package/dist/runtime/insights.js +2 -2
- package/dist/runtime/instrumentation.d.ts +2 -2
- package/dist/runtime/instrumentation.js +366 -8
- package/dist/runtime/native-network-errors.d.ts +33 -0
- package/dist/runtime/native-network-errors.js +69 -0
- package/dist/runtime/native-network.d.ts +96 -0
- package/dist/runtime/native-network.js +1232 -0
- package/dist/runtime/ocr.d.ts +29 -0
- package/dist/runtime/ocr.js +440 -0
- package/dist/runtime/otlp.d.ts +71 -2
- package/dist/runtime/otlp.js +397 -16
- package/dist/runtime/proxy-errors.js +6 -2
- package/dist/runtime/proxy-nodemaven.d.ts +56 -0
- package/dist/runtime/proxy-nodemaven.js +146 -0
- package/dist/runtime/proxy-telemetry.d.ts +80 -1
- package/dist/runtime/proxy-telemetry.js +154 -47
- package/dist/runtime/redirects.d.ts +29 -0
- package/dist/runtime/redirects.js +36 -0
- package/dist/runtime/redis.d.ts +1 -1
- package/dist/runtime/redis.js +4 -2
- package/dist/runtime/request-options.d.ts +68 -1
- package/dist/runtime/request-options.js +548 -0
- package/dist/runtime/resolver-config.d.ts +6 -0
- package/dist/runtime/resolver-config.js +6 -0
- package/dist/runtime/resolver-public.d.ts +1 -0
- package/dist/runtime/resolver-public.js +1 -0
- package/dist/runtime/resolver-shared.d.ts +14 -0
- package/dist/runtime/resolver-shared.js +12 -0
- package/dist/runtime/resolver-vendors/bindings.d.ts +48 -0
- package/dist/runtime/resolver-vendors/bindings.js +40 -0
- package/dist/runtime/resolver-vendors/browser.d.ts +22 -0
- package/dist/runtime/resolver-vendors/browser.js +377 -0
- package/dist/runtime/resolver-vendors/capsolver.d.ts +22 -0
- package/dist/runtime/resolver-vendors/capsolver.js +531 -0
- package/dist/runtime/resolver-vendors/hosts.d.ts +2 -0
- package/dist/runtime/resolver-vendors/hosts.js +33 -0
- package/dist/runtime/resolver-vendors/twocaptcha.d.ts +24 -0
- package/dist/runtime/resolver-vendors/twocaptcha.js +408 -0
- package/dist/runtime/resolver-vendors/types.d.ts +94 -0
- package/dist/runtime/resolver-vendors/types.js +96 -0
- package/dist/runtime/resolver.d.ts +72 -0
- package/dist/runtime/resolver.js +771 -0
- package/dist/runtime/secrets.d.ts +27 -0
- package/dist/runtime/secrets.js +51 -0
- package/dist/runtime/state.d.ts +3 -0
- package/dist/runtime/state.js +277 -71
- package/dist/runtime/stealth-cookies.d.ts +20 -0
- package/dist/runtime/stealth-cookies.js +111 -0
- package/dist/runtime/stealth.d.ts +41 -5
- package/dist/runtime/stealth.js +997 -291
- package/dist/runtime/stt.js +1 -12
- package/dist/runtime/timeout.d.ts +5 -0
- package/dist/runtime/timeout.js +12 -0
- package/dist/runtime/trace-config.d.ts +12 -0
- package/dist/runtime/trace-config.js +62 -0
- package/dist/runtime/trace.d.ts +5 -0
- package/dist/runtime/trace.js +43 -10
- package/dist/serve.d.ts +1 -1
- package/dist/serve.js +1 -1
- package/dist/server/error-observability.d.ts +1 -0
- package/dist/server/error-observability.js +1 -0
- package/dist/server/index.d.ts +5 -2
- package/dist/server/index.js +2 -2
- package/dist/server/self-test-input-tokens.d.ts +2 -1
- package/dist/server/self-test-input-tokens.js +18 -14
- package/dist/server/self-test.d.ts +14 -3
- package/dist/server/self-test.js +129 -58
- package/dist/server/serve-implementation.d.ts +230 -0
- package/dist/server/serve-implementation.js +2265 -0
- package/dist/server/serve.d.ts +1 -70
- package/dist/server/serve.js +1 -1131
- package/dist/server/trace-output.d.ts +6 -0
- package/dist/server/trace-output.js +79 -0
- package/dist/server/types.d.ts +30 -5
- package/dist/server/types.js +13 -1
- package/dist/stateful/errors.d.ts +19 -0
- package/dist/stateful/errors.js +24 -0
- package/dist/stateful/http-provider-event-emitter.d.ts +40 -0
- package/dist/stateful/http-provider-event-emitter.js +237 -0
- package/dist/stateful/http-session-owner-registry.d.ts +44 -0
- package/dist/stateful/http-session-owner-registry.js +210 -0
- package/dist/stateful/index.d.ts +18 -0
- package/dist/stateful/index.js +18 -0
- package/dist/stateful/provider-event-delivery-failures.d.ts +32 -0
- package/dist/stateful/provider-event-delivery-failures.js +43 -0
- package/dist/stateful/provider-event-pipeline-metrics.d.ts +46 -0
- package/dist/stateful/provider-event-pipeline-metrics.js +48 -0
- package/dist/stateful/provider-event-pipeline.d.ts +50 -0
- package/dist/stateful/provider-event-pipeline.js +1 -0
- package/dist/stateful/provider-events.d.ts +101 -0
- package/dist/stateful/provider-events.js +289 -0
- package/dist/stateful/session-key.d.ts +15 -0
- package/dist/stateful/session-key.js +86 -0
- package/dist/stateful/stateful-provider-adapter-context.d.ts +5 -0
- package/dist/stateful/stateful-provider-adapter-context.js +42 -0
- package/dist/stateful/stateful-provider-adapter-metrics.d.ts +15 -0
- package/dist/stateful/stateful-provider-adapter-metrics.js +21 -0
- package/dist/stateful/stateful-provider-adapter.d.ts +98 -0
- package/dist/stateful/stateful-provider-adapter.js +287 -0
- package/dist/stateful/stateful-provider-observability.d.ts +62 -0
- package/dist/stateful/stateful-provider-observability.js +161 -0
- package/dist/stateful/stateful-provider-owner-forwarder.d.ts +41 -0
- package/dist/stateful/stateful-provider-owner-forwarder.js +215 -0
- package/dist/stateful/stateful-provider-runtime-context.d.ts +32 -0
- package/dist/stateful/stateful-provider-runtime-context.js +60 -0
- package/dist/stateful/stateful-provider-runtime-executor.d.ts +34 -0
- package/dist/stateful/stateful-provider-runtime-executor.js +52 -0
- package/dist/stateful/stateful-provider-session-routing.d.ts +67 -0
- package/dist/stateful/stateful-provider-session-routing.js +345 -0
- package/dist/stateful/stateful-provider-session-runtime.d.ts +98 -0
- package/dist/stateful/stateful-provider-session-runtime.js +245 -0
- package/dist/stateful-signing.d.ts +18 -0
- package/dist/stateful-signing.js +27 -0
- package/dist/stealth/profiles.d.ts +9 -4
- package/dist/stealth/profiles.js +160 -211
- package/dist/stream-evidence.d.ts +74 -0
- package/dist/stream-evidence.js +785 -0
- package/dist/stream.js +7 -1
- package/dist/testing/index.d.ts +2 -1
- package/dist/testing/index.js +2 -1
- package/dist/testing/run.d.ts +32 -2
- package/dist/testing/run.js +489 -21
- package/dist/trace-sanitization.d.ts +5 -0
- package/dist/trace-sanitization.js +45 -0
- package/dist/types.d.ts +673 -131
- package/dist/types.js +1 -0
- package/package.json +45 -5
- package/src/auth-turn/index.ts +1 -1
- package/src/auth.ts +118 -0
- package/src/ceremonies/index.ts +189 -46
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/approval-override.ts.txt +6 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/codemod-syntax.ts.txt +3 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/connection-precedence.ts.txt +10 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/docs-conflict.ts.txt +8 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/examples-hoisted-array-spread.ts.txt +15 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/examples-imported-array-spread.ts.txt +9 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/examples-map.ts.txt +5 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/examples-mixed-array-spread.ts.txt +24 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/examples-operation.ts.txt +16 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/factory-map.ts.txt +3 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/hoist-all.ts.txt +31 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/hoisted-const.ts.txt +11 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/imported-spread.ts.txt +11 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/inline-map.ts.txt +11 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/inline-spread-cast-tail.ts.txt +21 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/inline-spread-ekitan.ts.txt +11 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/inline-spread-override.ts.txt +14 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/missing-english-locale.ts.txt +7 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/no-safety.ts.txt +6 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/non-literal.ts.txt +7 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/redundant-approval.ts.txt +6 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/safety-conflict.ts.txt +7 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/stream.ts.txt +7 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/tool-router-spread.ts.txt +15 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/unparseable.ts.txt +4 -0
- package/src/cli/__tests__/fixtures/migrate-operation-declaration/verbatim-template.ts.txt +12 -0
- package/src/cli/commands.ts +33 -0
- package/src/cli/create.ts +50 -37
- package/src/cli/migrate-operation-declaration.ts +1751 -0
- package/src/cli/migrate-operation-shape.ts +184 -0
- package/src/cli/migrate-provider-shape.ts +772 -0
- package/src/cli/prompt-assets.ts +865 -0
- package/src/cli/templates/provider/AGENTS.md.tpl +17 -8
- package/src/cli/templates/provider/Dockerfile.tpl +1 -1
- package/src/cli/templates/provider/README.md.tpl +5 -5
- package/src/cli/templates/provider/index.ts.tpl +6 -3
- package/src/cli/templates/provider/operations/ping.ts.tpl +4 -1
- package/src/cli/templates/provider/provider.json.tpl +6 -0
- package/src/config/loader.ts +690 -163
- package/src/contract-serialization.ts +5 -7
- package/src/contract-types.ts +12 -5
- package/src/contract.ts +24 -10
- package/src/declaration-validation.ts +330 -0
- package/src/define.ts +1048 -131
- package/src/dev.ts +4 -1
- package/src/engine.ts +279 -0
- package/src/error-observability.ts +64 -0
- package/src/error-resolution.ts +127 -0
- package/src/errors.ts +68 -0
- package/src/fixture-sanitization.ts +264 -0
- package/src/health-scenario.ts +875 -0
- package/src/index.ts +220 -13
- package/src/lint.ts +698 -90
- package/src/native-address.ts +340 -0
- package/src/native-egress-policy.ts +358 -0
- package/src/observability.ts +51 -1
- package/src/provider.ts +161 -3
- package/src/runtime/auth-flow.ts +12 -0
- package/src/runtime/browser.ts +661 -63
- package/src/runtime/cache.ts +189 -14
- package/src/runtime/choice-wordlist.ts +145 -0
- package/src/runtime/choice.ts +631 -120
- package/src/runtime/chrome149-header-order.ts +330 -0
- package/src/runtime/env.ts +13 -0
- package/src/runtime/executor.ts +43 -31
- package/src/runtime/http.ts +641 -61
- package/src/runtime/insights.ts +2 -2
- package/src/runtime/instrumentation.ts +520 -15
- package/src/runtime/native-network-errors.ts +99 -0
- package/src/runtime/native-network.ts +1605 -0
- package/src/runtime/ocr.ts +523 -0
- package/src/runtime/otlp.ts +467 -21
- package/src/runtime/proxy-errors.ts +12 -4
- package/src/runtime/proxy-nodemaven.ts +221 -0
- package/src/runtime/proxy-telemetry.ts +244 -75
- package/src/runtime/redirects.ts +66 -0
- package/src/runtime/redis.ts +7 -2
- package/src/runtime/request-options.ts +680 -1
- package/src/runtime/resolver-config.ts +6 -0
- package/src/runtime/resolver-public.ts +23 -0
- package/src/runtime/resolver-shared.ts +33 -0
- package/src/runtime/resolver-vendors/bindings.ts +56 -0
- package/src/runtime/resolver-vendors/browser.ts +533 -0
- package/src/runtime/resolver-vendors/capsolver.ts +707 -0
- package/src/runtime/resolver-vendors/hosts.ts +38 -0
- package/src/runtime/resolver-vendors/twocaptcha.ts +540 -0
- package/src/runtime/resolver-vendors/types.ts +212 -0
- package/src/runtime/resolver.ts +1157 -0
- package/src/runtime/secrets.ts +64 -0
- package/src/runtime/state.ts +394 -77
- package/src/runtime/stealth-cookies.ts +132 -0
- package/src/runtime/stealth.ts +1280 -336
- package/src/runtime/stt.ts +1 -19
- package/src/runtime/timeout.ts +18 -0
- package/src/runtime/trace-config.ts +78 -0
- package/src/runtime/trace.ts +57 -17
- package/src/serve.ts +6 -1
- package/src/server/error-observability.ts +1 -0
- package/src/server/index.ts +34 -2
- package/src/server/self-test-input-tokens.ts +29 -14
- package/src/server/self-test.ts +191 -68
- package/src/server/serve-implementation.ts +3378 -0
- package/src/server/serve.ts +1 -1632
- package/src/server/trace-output.ts +129 -0
- package/src/server/types.ts +13 -1
- package/src/stateful/README.md +146 -0
- package/src/stateful/errors.ts +35 -0
- package/src/stateful/http-provider-event-emitter.ts +314 -0
- package/src/stateful/http-session-owner-registry.ts +306 -0
- package/src/stateful/index.ts +18 -0
- package/src/stateful/provider-event-delivery-failures.ts +80 -0
- package/src/stateful/provider-event-pipeline-metrics.ts +95 -0
- package/src/stateful/provider-event-pipeline.ts +61 -0
- package/src/stateful/provider-events.ts +462 -0
- package/src/stateful/session-key.ts +111 -0
- package/src/stateful/stateful-provider-adapter-context.ts +59 -0
- package/src/stateful/stateful-provider-adapter-metrics.ts +48 -0
- package/src/stateful/stateful-provider-adapter.ts +562 -0
- package/src/stateful/stateful-provider-observability.ts +261 -0
- package/src/stateful/stateful-provider-owner-forwarder.ts +287 -0
- package/src/stateful/stateful-provider-runtime-context.ts +92 -0
- package/src/stateful/stateful-provider-runtime-executor.ts +96 -0
- package/src/stateful/stateful-provider-session-routing.ts +546 -0
- package/src/stateful/stateful-provider-session-runtime.ts +403 -0
- package/src/stateful-signing.ts +46 -0
- package/src/stealth/profiles.ts +202 -231
- package/src/stream-evidence.ts +988 -0
- package/src/stream.ts +8 -1
- package/src/testing/index.ts +10 -1
- package/src/testing/run.ts +658 -15
- package/src/trace-sanitization.ts +63 -0
- package/src/types.ts +788 -174
- package/dist/cli/templates/provider/CLAUDE.md.tpl +0 -1
- package/src/cli/templates/provider/CLAUDE.md.tpl +0 -1
- /package/dist/cli/templates/provider/{skills → .agents/skills}/fixtures-and-recording/SKILL.md.tpl +0 -0
- /package/dist/cli/templates/provider/{skills → .agents/skills}/health-checks-and-fail-closed/SKILL.md.tpl +0 -0
- /package/dist/cli/templates/provider/{skills → .agents/skills}/normalization-standards/SKILL.md.tpl +0 -0
- /package/dist/cli/templates/provider/{skills → .agents/skills}/pagination-and-counts/SKILL.md.tpl +0 -0
- /package/dist/cli/templates/provider/{skills → .agents/skills}/upstream-contract-verification/SKILL.md.tpl +0 -0
- /package/dist/cli/templates/provider/{skills → .agents/skills}/upstream-notes/README.md.tpl +0 -0
- /package/src/cli/templates/provider/{skills → .agents/skills}/fixtures-and-recording/SKILL.md.tpl +0 -0
- /package/src/cli/templates/provider/{skills → .agents/skills}/health-checks-and-fail-closed/SKILL.md.tpl +0 -0
- /package/src/cli/templates/provider/{skills → .agents/skills}/normalization-standards/SKILL.md.tpl +0 -0
- /package/src/cli/templates/provider/{skills → .agents/skills}/pagination-and-counts/SKILL.md.tpl +0 -0
- /package/src/cli/templates/provider/{skills → .agents/skills}/upstream-contract-verification/SKILL.md.tpl +0 -0
- /package/src/cli/templates/provider/{skills → .agents/skills}/upstream-notes/README.md.tpl +0 -0
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
import { ProviderError, TransportError } from "../errors.js";
|
|
2
|
+
import type {
|
|
3
|
+
OcrCaptchaCandidate,
|
|
4
|
+
OcrCaptchaOptions,
|
|
5
|
+
OcrCaptchaResult,
|
|
6
|
+
OcrContext,
|
|
7
|
+
OcrImageInput,
|
|
8
|
+
OcrRecognizeRequest,
|
|
9
|
+
OcrResult,
|
|
10
|
+
ProviderOcrConfig,
|
|
11
|
+
} from "../types.js";
|
|
12
|
+
import { CLOUDFLARE_ACCOUNT_ID_ENV } from "./stt.js";
|
|
13
|
+
import { createTimeoutController, isTimeoutLikeError } from "./timeout.js";
|
|
14
|
+
|
|
15
|
+
export { CLOUDFLARE_ACCOUNT_ID_ENV } from "./stt.js";
|
|
16
|
+
|
|
17
|
+
export const APIFUSE__OCR__BACKEND_ENV = "APIFUSE__OCR__BACKEND";
|
|
18
|
+
export const APIFUSE__OCR__MODEL_ENV = "APIFUSE__OCR__MODEL";
|
|
19
|
+
export const APIFUSE__OCR__CLOUDFLARE_API_TOKEN_ENV = "APIFUSE__OCR__CLOUDFLARE_API_TOKEN";
|
|
20
|
+
export const APIFUSE__OCR__BASE_URL_ENV = "APIFUSE__OCR__BASE_URL";
|
|
21
|
+
export const APIFUSE__OCR__API_KEY_ENV = "APIFUSE__OCR__API_KEY";
|
|
22
|
+
export const CLOUDFLARE_WORKERS_AI_OCR_BACKEND = "cloudflare-workers-ai";
|
|
23
|
+
export const OPENAI_COMPATIBLE_OCR_BACKEND = "openai-compatible";
|
|
24
|
+
export const DEFAULT_CLOUDFLARE_WORKERS_AI_OCR_MODEL = "@cf/google/gemma-4-26b-a4b-it";
|
|
25
|
+
|
|
26
|
+
export const DEFAULT_OCR_TIMEOUT_MS = 30_000;
|
|
27
|
+
const DEFAULT_CAPTCHA_MAX_TOKENS = 64;
|
|
28
|
+
const DEFAULT_DOCUMENT_MAX_TOKENS = 4_096;
|
|
29
|
+
const KIMI_MIN_MAX_TOKENS = 3_000;
|
|
30
|
+
const DEFAULT_MAX_CAPTCHA_CANDIDATES = 3;
|
|
31
|
+
const MAX_HOMOGLYPH_SEARCH_NODES = 512;
|
|
32
|
+
const HOMOGLYPH_CLASSES: readonly (readonly string[])[] = [
|
|
33
|
+
["I", "l", "1", "i"],
|
|
34
|
+
["O", "0", "o"],
|
|
35
|
+
["S", "5", "s"],
|
|
36
|
+
["Z", "2", "z"],
|
|
37
|
+
["B", "8"],
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
const HINT_PROMPTS = {
|
|
41
|
+
captcha:
|
|
42
|
+
"Read the CAPTCHA image. Return only the characters, with no explanation. Preserve character case.",
|
|
43
|
+
document: "Transcribe all visible text in the document image.",
|
|
44
|
+
generic: "Read and return the visible text in this image.",
|
|
45
|
+
} as const;
|
|
46
|
+
|
|
47
|
+
type EnvLike = Record<string, string | undefined>;
|
|
48
|
+
|
|
49
|
+
type CloudflareWorkersAiOcrClientOptions = {
|
|
50
|
+
accountId: string;
|
|
51
|
+
apiToken: string;
|
|
52
|
+
model?: string;
|
|
53
|
+
fetch?: typeof fetch;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
type OpenAiCompatibleOcrClientOptions = {
|
|
57
|
+
baseUrl: string;
|
|
58
|
+
apiKey?: string;
|
|
59
|
+
model: string;
|
|
60
|
+
fetch?: typeof fetch;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
type ErrorOcrClientOptions = {
|
|
64
|
+
code: string;
|
|
65
|
+
message: string;
|
|
66
|
+
fix?: string;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
function providerError(message: string, options: { code: string; fix?: string }): ProviderError {
|
|
70
|
+
return new ProviderError(message, options);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function createErrorOcrClient(options: ErrorOcrClientOptions): OcrContext {
|
|
74
|
+
const unavailable = (): never => {
|
|
75
|
+
throw providerError(options.message, {
|
|
76
|
+
code: options.code,
|
|
77
|
+
fix: options.fix,
|
|
78
|
+
});
|
|
79
|
+
};
|
|
80
|
+
return {
|
|
81
|
+
async recognize() {
|
|
82
|
+
return unavailable();
|
|
83
|
+
},
|
|
84
|
+
async extractCaptchaText() {
|
|
85
|
+
return unavailable();
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function createUnsupportedOcrClient(reason?: string): OcrContext {
|
|
91
|
+
return createErrorOcrClient({
|
|
92
|
+
code: "OCR_UNAVAILABLE",
|
|
93
|
+
message: reason ?? "OCR runtime is not configured",
|
|
94
|
+
fix: `Configure ${APIFUSE__OCR__BACKEND_ENV} and ${APIFUSE__OCR__MODEL_ENV}; Cloudflare uses ${CLOUDFLARE_ACCOUNT_ID_ENV} and ${APIFUSE__OCR__CLOUDFLARE_API_TOKEN_ENV}, while openai-compatible uses ${APIFUSE__OCR__BASE_URL_ENV} and optional ${APIFUSE__OCR__API_KEY_ENV}. Alternatively, provide a test OcrContext override.`,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function normalizedEnvValue(env: EnvLike, key: string): string | undefined {
|
|
99
|
+
const value = env[key]?.trim();
|
|
100
|
+
return value ? value : undefined;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function createOcrClientFromEnv(
|
|
104
|
+
config: ProviderOcrConfig | undefined,
|
|
105
|
+
env: EnvLike = process.env,
|
|
106
|
+
): OcrContext {
|
|
107
|
+
if (!config) {
|
|
108
|
+
return createUnsupportedOcrClient("Provider does not declare OCR capability");
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const backend =
|
|
112
|
+
normalizedEnvValue(env, APIFUSE__OCR__BACKEND_ENV) ?? CLOUDFLARE_WORKERS_AI_OCR_BACKEND;
|
|
113
|
+
const configuredModel = normalizedEnvValue(env, APIFUSE__OCR__MODEL_ENV);
|
|
114
|
+
|
|
115
|
+
if (backend === CLOUDFLARE_WORKERS_AI_OCR_BACKEND) {
|
|
116
|
+
const model = configuredModel ?? DEFAULT_CLOUDFLARE_WORKERS_AI_OCR_MODEL;
|
|
117
|
+
const accountId = normalizedEnvValue(env, CLOUDFLARE_ACCOUNT_ID_ENV);
|
|
118
|
+
const apiToken = normalizedEnvValue(env, APIFUSE__OCR__CLOUDFLARE_API_TOKEN_ENV);
|
|
119
|
+
if (!accountId || !apiToken) {
|
|
120
|
+
return createUnsupportedOcrClient(
|
|
121
|
+
`OCR backend ${backend} requires ${CLOUDFLARE_ACCOUNT_ID_ENV} and ${APIFUSE__OCR__CLOUDFLARE_API_TOKEN_ENV}`,
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
return createCloudflareWorkersAiOcrClient({ accountId, apiToken, model });
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (backend === OPENAI_COMPATIBLE_OCR_BACKEND) {
|
|
128
|
+
const baseUrl = normalizedEnvValue(env, APIFUSE__OCR__BASE_URL_ENV);
|
|
129
|
+
if (!baseUrl) {
|
|
130
|
+
return createUnsupportedOcrClient(
|
|
131
|
+
`OCR backend ${backend} requires ${APIFUSE__OCR__BASE_URL_ENV}`,
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
if (!configuredModel) {
|
|
135
|
+
return createErrorOcrClient({
|
|
136
|
+
code: "OCR_UNAVAILABLE",
|
|
137
|
+
message: `OCR backend ${backend} requires ${APIFUSE__OCR__MODEL_ENV}`,
|
|
138
|
+
fix: `Set ${APIFUSE__OCR__MODEL_ENV} to the exact model ID served by your self-hosted endpoint, for example ${APIFUSE__OCR__MODEL_ENV}=zai-org/GLM-OCR.`,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
return createOpenAiCompatibleOcrClient({
|
|
142
|
+
baseUrl,
|
|
143
|
+
apiKey: normalizedEnvValue(env, APIFUSE__OCR__API_KEY_ENV),
|
|
144
|
+
model: configuredModel,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return createErrorOcrClient({
|
|
149
|
+
code: "UNSUPPORTED_OCR_BACKEND",
|
|
150
|
+
message: `Unsupported OCR backend "${backend}"`,
|
|
151
|
+
fix: `Use ${APIFUSE__OCR__BACKEND_ENV}=${CLOUDFLARE_WORKERS_AI_OCR_BACKEND} or ${APIFUSE__OCR__BACKEND_ENV}=${OPENAI_COMPATIBLE_OCR_BACKEND}, or provide a custom OcrContext override.`,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function unknownRecord(value: unknown): Record<string, unknown> | undefined {
|
|
156
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
157
|
+
return Object.fromEntries(Object.entries(value));
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function imageUrl(image: OcrImageInput): string {
|
|
161
|
+
if (image.kind === "url") return image.url.trim();
|
|
162
|
+
return `data:${image.mediaType?.trim() || "image/png"};base64,${image.data.trim()}`;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function resolvePrompt(request: OcrRecognizeRequest): string {
|
|
166
|
+
return request.prompt ?? HINT_PROMPTS[request.hint ?? "generic"];
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function isGemmaModel(model: string): boolean {
|
|
170
|
+
return model.toLowerCase().includes("gemma");
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function isKimiModel(model: string): boolean {
|
|
174
|
+
return model.toLowerCase().includes("kimi");
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function isMoondreamModel(model: string): boolean {
|
|
178
|
+
return model.toLowerCase().includes("moondream");
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function defaultMaxTokens(request: OcrRecognizeRequest): number {
|
|
182
|
+
return request.hint === "captcha" ? DEFAULT_CAPTCHA_MAX_TOKENS : DEFAULT_DOCUMENT_MAX_TOKENS;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function resolvedMaxTokens(request: OcrRecognizeRequest, model = ""): number {
|
|
186
|
+
const requestedMaxTokens = request.maxTokens ?? defaultMaxTokens(request);
|
|
187
|
+
return isKimiModel(model)
|
|
188
|
+
? Math.max(requestedMaxTokens, KIMI_MIN_MAX_TOKENS)
|
|
189
|
+
: requestedMaxTokens;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function messagesPayload(request: OcrRecognizeRequest, model?: string): Record<string, unknown> {
|
|
193
|
+
const payload: Record<string, unknown> = {
|
|
194
|
+
...(model ? { model } : {}),
|
|
195
|
+
messages: [
|
|
196
|
+
{
|
|
197
|
+
role: "user",
|
|
198
|
+
content: [
|
|
199
|
+
{ type: "text", text: resolvePrompt(request) },
|
|
200
|
+
{ type: "image_url", image_url: { url: imageUrl(request.image) } },
|
|
201
|
+
],
|
|
202
|
+
},
|
|
203
|
+
],
|
|
204
|
+
max_tokens: resolvedMaxTokens(request, model),
|
|
205
|
+
temperature: 0,
|
|
206
|
+
};
|
|
207
|
+
if (isGemmaModel(model ?? "")) {
|
|
208
|
+
payload.chat_template_kwargs = { enable_thinking: false };
|
|
209
|
+
}
|
|
210
|
+
return payload;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function cloudflareMessagesPayload(
|
|
214
|
+
request: OcrRecognizeRequest,
|
|
215
|
+
model: string,
|
|
216
|
+
): Record<string, unknown> {
|
|
217
|
+
const payload = messagesPayload(request, model);
|
|
218
|
+
delete payload.model;
|
|
219
|
+
return payload;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function moondreamPayload(request: OcrRecognizeRequest): Record<string, unknown> {
|
|
223
|
+
return {
|
|
224
|
+
task: "query",
|
|
225
|
+
image: imageUrl(request.image),
|
|
226
|
+
question: resolvePrompt(request),
|
|
227
|
+
stream: true,
|
|
228
|
+
reasoning: false,
|
|
229
|
+
temperature: 0,
|
|
230
|
+
max_tokens: resolvedMaxTokens(request),
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function incompleteResponseError(model: string, finishReason: string): TransportError {
|
|
235
|
+
return new TransportError(
|
|
236
|
+
`OCR model "${model}" did not complete normally (finish_reason: ${finishReason})`,
|
|
237
|
+
{
|
|
238
|
+
code: "OCR_INCOMPLETE_RESPONSE",
|
|
239
|
+
status: 502,
|
|
240
|
+
details: { finishReason },
|
|
241
|
+
},
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function responseContent(payload: unknown, cloudflare: boolean, model: string): string | undefined {
|
|
246
|
+
const envelope = unknownRecord(payload);
|
|
247
|
+
const root = cloudflare ? unknownRecord(envelope?.result) : envelope;
|
|
248
|
+
const choices = root?.choices;
|
|
249
|
+
if (!Array.isArray(choices)) return undefined;
|
|
250
|
+
const choice = unknownRecord(choices[0]);
|
|
251
|
+
if (typeof choice?.finish_reason === "string" && choice.finish_reason !== "stop") {
|
|
252
|
+
throw incompleteResponseError(model, choice.finish_reason);
|
|
253
|
+
}
|
|
254
|
+
const message = unknownRecord(choice?.message);
|
|
255
|
+
return typeof message?.content === "string" ? message.content.trim() || undefined : undefined;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function malformedResponseError(model: string, cause: Error): TransportError {
|
|
259
|
+
return new TransportError(`OCR model "${model}" returned a malformed response`, {
|
|
260
|
+
code: "OCR_UPSTREAM_FAILED",
|
|
261
|
+
status: 502,
|
|
262
|
+
cause,
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async function responseJson(response: Response, model: string): Promise<unknown> {
|
|
267
|
+
try {
|
|
268
|
+
return await response.json();
|
|
269
|
+
} catch (error) {
|
|
270
|
+
if (isTimeoutLikeError(error)) throw toOcrTransportError(error);
|
|
271
|
+
throw malformedResponseError(
|
|
272
|
+
model,
|
|
273
|
+
error instanceof Error ? error : new Error("Failed to decode OCR response JSON"),
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function moondreamSseContent(body: string, model: string): string | undefined {
|
|
279
|
+
let finalAnswer: string | undefined;
|
|
280
|
+
let firstDecodingFailure: Error | undefined;
|
|
281
|
+
let terminalFinishReason: string | undefined;
|
|
282
|
+
for (const line of body.split(/\r?\n/u)) {
|
|
283
|
+
const trimmed = line.trim();
|
|
284
|
+
if (!trimmed.startsWith("data:")) continue;
|
|
285
|
+
const data = trimmed.slice("data:".length).trim();
|
|
286
|
+
if (!data || data === "[DONE]") continue;
|
|
287
|
+
let parsed: unknown;
|
|
288
|
+
try {
|
|
289
|
+
parsed = JSON.parse(data);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
firstDecodingFailure ??=
|
|
292
|
+
error instanceof Error ? error : new Error("Failed to decode OCR SSE event");
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
const event = unknownRecord(parsed);
|
|
296
|
+
const chunk = unknownRecord(event?.chunk) ?? unknownRecord(event?.result) ?? event;
|
|
297
|
+
if (
|
|
298
|
+
chunk?.finish_reason === "stop" &&
|
|
299
|
+
typeof chunk.answer === "string" &&
|
|
300
|
+
chunk.answer.trim()
|
|
301
|
+
) {
|
|
302
|
+
finalAnswer = chunk.answer.trim();
|
|
303
|
+
} else if (typeof chunk?.finish_reason === "string") {
|
|
304
|
+
terminalFinishReason = chunk.finish_reason;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
if (finalAnswer) return finalAnswer;
|
|
308
|
+
if (terminalFinishReason) throw incompleteResponseError(model, terminalFinishReason);
|
|
309
|
+
if (firstDecodingFailure) throw malformedResponseError(model, firstDecodingFailure);
|
|
310
|
+
return finalAnswer;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function emptyResponseError(model: string): TransportError {
|
|
314
|
+
return new TransportError(`OCR model "${model}" returned no usable text`, {
|
|
315
|
+
code: "OCR_UPSTREAM_FAILED",
|
|
316
|
+
status: 502,
|
|
317
|
+
fix: `Verify ${APIFUSE__OCR__MODEL_ENV}="${model}" supports image input and the runtime calling convention for that model.`,
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function toOcrTransportError(error: unknown): TransportError {
|
|
322
|
+
if (error instanceof TransportError) return error;
|
|
323
|
+
if (isTimeoutLikeError(error)) {
|
|
324
|
+
return new TransportError("OCR upstream request timed out", {
|
|
325
|
+
code: "transport_timeout",
|
|
326
|
+
status: 0,
|
|
327
|
+
cause: error,
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
return new TransportError("OCR upstream network request failed", {
|
|
331
|
+
code: "transport_network_error",
|
|
332
|
+
status: 0,
|
|
333
|
+
cause: error instanceof Error ? error : undefined,
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function createOcrClient(
|
|
338
|
+
model: string,
|
|
339
|
+
recognize: (request: OcrRecognizeRequest) => Promise<OcrResult>,
|
|
340
|
+
): OcrContext {
|
|
341
|
+
return {
|
|
342
|
+
recognize,
|
|
343
|
+
async extractCaptchaText(image, options = {}): Promise<OcrCaptchaResult> {
|
|
344
|
+
const result = await recognize({ image, hint: "captcha" });
|
|
345
|
+
const candidates = extractCaptchaCandidates(result.text, options);
|
|
346
|
+
const primary = candidates[0];
|
|
347
|
+
if (!primary?.text) throw emptyResponseError(model);
|
|
348
|
+
return {
|
|
349
|
+
text: primary.text,
|
|
350
|
+
candidates,
|
|
351
|
+
satisfiesConstraints: primary.satisfiesConstraints,
|
|
352
|
+
model: result.model,
|
|
353
|
+
};
|
|
354
|
+
},
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
export function createCloudflareWorkersAiOcrClient(
|
|
359
|
+
options: CloudflareWorkersAiOcrClientOptions,
|
|
360
|
+
): OcrContext {
|
|
361
|
+
const model = options.model ?? DEFAULT_CLOUDFLARE_WORKERS_AI_OCR_MODEL;
|
|
362
|
+
const runFetch = options.fetch ?? fetch;
|
|
363
|
+
return createOcrClient(model, async (request) => {
|
|
364
|
+
const timeout = createTimeoutController(request.timeoutMs ?? DEFAULT_OCR_TIMEOUT_MS);
|
|
365
|
+
try {
|
|
366
|
+
let response: Response;
|
|
367
|
+
try {
|
|
368
|
+
response = await runFetch(
|
|
369
|
+
`https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(options.accountId)}/ai/run/${model}`,
|
|
370
|
+
{
|
|
371
|
+
method: "POST",
|
|
372
|
+
headers: {
|
|
373
|
+
Authorization: `Bearer ${options.apiToken}`,
|
|
374
|
+
"Content-Type": "application/json",
|
|
375
|
+
},
|
|
376
|
+
body: JSON.stringify(
|
|
377
|
+
isMoondreamModel(model)
|
|
378
|
+
? moondreamPayload(request)
|
|
379
|
+
: cloudflareMessagesPayload(request, model),
|
|
380
|
+
),
|
|
381
|
+
signal: timeout.controller.signal,
|
|
382
|
+
},
|
|
383
|
+
);
|
|
384
|
+
} catch (error) {
|
|
385
|
+
throw toOcrTransportError(error);
|
|
386
|
+
}
|
|
387
|
+
if (!response.ok) {
|
|
388
|
+
throw new TransportError("OCR upstream request failed", {
|
|
389
|
+
code: "OCR_UPSTREAM_FAILED",
|
|
390
|
+
status: response.status,
|
|
391
|
+
upstreamStatus: response.status,
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
const text = isMoondreamModel(model)
|
|
395
|
+
? moondreamSseContent(await response.text(), model)
|
|
396
|
+
: responseContent(await responseJson(response, model), true, model);
|
|
397
|
+
if (!text) throw emptyResponseError(model);
|
|
398
|
+
return { text, model };
|
|
399
|
+
} catch (error) {
|
|
400
|
+
throw toOcrTransportError(error);
|
|
401
|
+
} finally {
|
|
402
|
+
timeout.clear();
|
|
403
|
+
}
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
export function createOpenAiCompatibleOcrClient(
|
|
408
|
+
options: OpenAiCompatibleOcrClientOptions,
|
|
409
|
+
): OcrContext {
|
|
410
|
+
const model = options.model;
|
|
411
|
+
const runFetch = options.fetch ?? fetch;
|
|
412
|
+
return createOcrClient(model, async (request) => {
|
|
413
|
+
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
|
414
|
+
if (options.apiKey) headers.Authorization = `Bearer ${options.apiKey}`;
|
|
415
|
+
const timeout = createTimeoutController(request.timeoutMs ?? DEFAULT_OCR_TIMEOUT_MS);
|
|
416
|
+
try {
|
|
417
|
+
let response: Response;
|
|
418
|
+
try {
|
|
419
|
+
response = await runFetch(`${options.baseUrl.replace(/\/+$/u, "")}/chat/completions`, {
|
|
420
|
+
method: "POST",
|
|
421
|
+
headers,
|
|
422
|
+
body: JSON.stringify(messagesPayload(request, model)),
|
|
423
|
+
signal: timeout.controller.signal,
|
|
424
|
+
});
|
|
425
|
+
} catch (error) {
|
|
426
|
+
throw toOcrTransportError(error);
|
|
427
|
+
}
|
|
428
|
+
if (!response.ok) {
|
|
429
|
+
throw new TransportError("OCR upstream request failed", {
|
|
430
|
+
code: "OCR_UPSTREAM_FAILED",
|
|
431
|
+
status: response.status,
|
|
432
|
+
upstreamStatus: response.status,
|
|
433
|
+
});
|
|
434
|
+
}
|
|
435
|
+
const text = responseContent(await responseJson(response, model), false, model);
|
|
436
|
+
if (!text) throw emptyResponseError(model);
|
|
437
|
+
return { text, model };
|
|
438
|
+
} catch (error) {
|
|
439
|
+
throw toOcrTransportError(error);
|
|
440
|
+
} finally {
|
|
441
|
+
timeout.clear();
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function cleanCaptchaText(text: string): string {
|
|
447
|
+
const afterColon = text.slice(text.lastIndexOf(":") + 1).trim();
|
|
448
|
+
return afterColon.replace(/^[\s\p{P}\p{S}]+|[\s\p{P}\p{S}]+$/gu, "");
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function caseFold(value: string, caseSensitive: boolean): string {
|
|
452
|
+
return caseSensitive ? value : value.toLocaleLowerCase();
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function matchesCharset(
|
|
456
|
+
text: string,
|
|
457
|
+
charset: string | RegExp | undefined,
|
|
458
|
+
caseSensitive: boolean,
|
|
459
|
+
): boolean {
|
|
460
|
+
if (charset === undefined) return true;
|
|
461
|
+
if (typeof charset === "string") {
|
|
462
|
+
const allowed = new Set([...caseFold(charset, caseSensitive)]);
|
|
463
|
+
return [...caseFold(text, caseSensitive)].every((character) => allowed.has(character));
|
|
464
|
+
}
|
|
465
|
+
const flags = caseSensitive || charset.flags.includes("i") ? charset.flags : `${charset.flags}i`;
|
|
466
|
+
const matcher = new RegExp(charset.source, flags);
|
|
467
|
+
return [...text].every((character) => {
|
|
468
|
+
matcher.lastIndex = 0;
|
|
469
|
+
return matcher.test(character);
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function satisfiesCaptchaConstraints(text: string, options: OcrCaptchaOptions): boolean {
|
|
474
|
+
const lengthMatches = options.length === undefined || [...text].length === options.length;
|
|
475
|
+
return lengthMatches && matchesCharset(text, options.charset, options.caseSensitive !== false);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function homoglyphAlternatives(character: string): readonly string[] {
|
|
479
|
+
const group = HOMOGLYPH_CLASSES.find((characters) => characters.includes(character));
|
|
480
|
+
return group?.filter((alternative) => alternative !== character) ?? [];
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
export function extractCaptchaCandidates(
|
|
484
|
+
modelText: string,
|
|
485
|
+
options: OcrCaptchaOptions = {},
|
|
486
|
+
): readonly OcrCaptchaCandidate[] {
|
|
487
|
+
const primaryText = cleanCaptchaText(modelText);
|
|
488
|
+
const primary = {
|
|
489
|
+
text: primaryText,
|
|
490
|
+
satisfiesConstraints: satisfiesCaptchaConstraints(primaryText, options),
|
|
491
|
+
};
|
|
492
|
+
const requestedMaxCandidates = options.maxCandidates ?? DEFAULT_MAX_CAPTCHA_CANDIDATES;
|
|
493
|
+
const maxCandidates = Number.isFinite(requestedMaxCandidates)
|
|
494
|
+
? Math.max(1, Math.floor(requestedMaxCandidates))
|
|
495
|
+
: DEFAULT_MAX_CAPTCHA_CANDIDATES;
|
|
496
|
+
if (primary.satisfiesConstraints || maxCandidates === 1) return [primary];
|
|
497
|
+
if (options.length !== undefined && [...primaryText].length !== options.length) return [primary];
|
|
498
|
+
|
|
499
|
+
const candidates: OcrCaptchaCandidate[] = [primary];
|
|
500
|
+
const queue = [primaryText];
|
|
501
|
+
const visited = new Set(queue);
|
|
502
|
+
for (let index = 0; index < queue.length && candidates.length < maxCandidates; index += 1) {
|
|
503
|
+
const current = queue[index] ?? "";
|
|
504
|
+
const characters = [...current];
|
|
505
|
+
for (let position = 0; position < characters.length; position += 1) {
|
|
506
|
+
const character = characters[position] ?? "";
|
|
507
|
+
for (const alternative of homoglyphAlternatives(character)) {
|
|
508
|
+
const nextCharacters = [...characters];
|
|
509
|
+
nextCharacters[position] = alternative;
|
|
510
|
+
const next = nextCharacters.join("");
|
|
511
|
+
if (visited.has(next)) continue;
|
|
512
|
+
visited.add(next);
|
|
513
|
+
queue.push(next);
|
|
514
|
+
if (satisfiesCaptchaConstraints(next, options)) {
|
|
515
|
+
candidates.push({ text: next, satisfiesConstraints: true });
|
|
516
|
+
if (candidates.length >= maxCandidates) return candidates;
|
|
517
|
+
}
|
|
518
|
+
if (visited.size >= MAX_HOMOGLYPH_SEARCH_NODES) return candidates;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
return candidates;
|
|
523
|
+
}
|