@superdurable/connector-bocha 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Super Durable
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # Bocha TypeScript connector
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Search public web pages and return at most five titles, HTTPS URLs, and snippets.
4
+
5
+ Install `@superdurable/connector-bocha` and use `newProjectConnection` with the static connection name in the runnable [`examples/basic`](examples/basic) Flow. Configure the connection and provider credentials in Dex Web Connections. The operation `searchWeb` resolves credentials for each call. Local conformance tests replay the Go provider scenarios; live provider authorization has not been verified.
@@ -0,0 +1,60 @@
1
+ {
2
+ "connectorId": "bocha",
3
+ "releaseTag": "connectors/bocha/go/v0.1.1",
4
+ "package": {
5
+ "ecosystem": "npm",
6
+ "name": "@superdurable/connector-bocha",
7
+ "version": "0.1.0"
8
+ },
9
+ "factories": [
10
+ {
11
+ "name": "newSearchWebStep",
12
+ "kind": "query",
13
+ "operationId": "searchWeb",
14
+ "inputType": "SearchWebInput",
15
+ "description": "Search public web pages and return up to five titles, URLs, and snippets.",
16
+ "fields": {
17
+ "stepType": "stepType",
18
+ "annotations": "annotations",
19
+ "connectionName": "connectionName",
20
+ "resultAttribute": "resultAttribute"
21
+ },
22
+ "branches": [
23
+ {
24
+ "id": "found",
25
+ "field": "found",
26
+ "optional": false
27
+ },
28
+ {
29
+ "id": "providerRejected",
30
+ "field": "providerRejected",
31
+ "optional": true
32
+ },
33
+ {
34
+ "id": "invalidResponse",
35
+ "field": "invalidResponse",
36
+ "optional": true
37
+ },
38
+ {
39
+ "id": "defect",
40
+ "field": "defect",
41
+ "optional": true
42
+ }
43
+ ],
44
+ "inputSchema": {
45
+ "additionalProperties": false,
46
+ "description": "SearchWebInput supplies a public web search query.",
47
+ "properties": {
48
+ "query": {
49
+ "description": "Query is a nonblank search phrase of at most 256 Unicode characters.",
50
+ "type": "string"
51
+ }
52
+ },
53
+ "required": [
54
+ "query"
55
+ ],
56
+ "type": "object"
57
+ }
58
+ }
59
+ ]
60
+ }
@@ -0,0 +1,121 @@
1
+ // src/generated/models.ts
2
+ import { z } from "zod";
3
+ import { SecretString } from "@superdurable/connectors-sdk";
4
+ var ConfigSchema = z.object({
5
+ "timeoutMs": z.number().int().optional(),
6
+ "maxResponseBytes": z.number().int().optional()
7
+ });
8
+ var CredentialMaterialError = class extends TypeError {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = "CredentialMaterialError";
12
+ }
13
+ };
14
+ var sdkCredentialDecodingFailureMessages = /* @__PURE__ */ new Set([
15
+ "project credential decoding failed",
16
+ "shared project credential decoding failed",
17
+ "project credential decoding failed: this connector version does not support shared credentials"
18
+ ]);
19
+ function isCredentialMaterialError(error) {
20
+ return error instanceof CredentialMaterialError || error instanceof TypeError && sdkCredentialDecodingFailureMessages.has(error.message);
21
+ }
22
+ function decodeCredentials(value) {
23
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new CredentialMaterialError("credential fields are invalid");
24
+ const fields = value;
25
+ const allowed = /* @__PURE__ */ new Set(["apiKey"]);
26
+ if (Object.keys(fields).some((key) => !allowed.has(key))) throw new CredentialMaterialError("stored credential does not match the connector credential fields");
27
+ if (fields["apiKey"] != null && !(typeof fields["apiKey"] === "string")) throw new CredentialMaterialError("credential apiKey has an invalid type");
28
+ const credentials = {};
29
+ if (!fields["apiKey"]) throw new CredentialMaterialError("credential apiKey is required");
30
+ credentials.apiKey = new SecretString(fields["apiKey"] ?? "");
31
+ return credentials;
32
+ }
33
+ var SearchWebInputSchema = z.strictObject({
34
+ "query": z.string()
35
+ });
36
+ var WebResultSchema = z.strictObject({
37
+ "title": z.string(),
38
+ "url": z.string(),
39
+ "snippet": z.string()
40
+ });
41
+ var SearchWebOutputSchema = z.strictObject({
42
+ "results": z.array(WebResultSchema).nullable()
43
+ });
44
+
45
+ // src/generated/definitions.ts
46
+ var ConnectorID = "bocha";
47
+ var ProviderID = "bocha";
48
+ var SearchWebBranch = {
49
+ Found: "found",
50
+ ProviderRejected: "providerRejected",
51
+ InvalidResponse: "invalidResponse",
52
+ Defect: "defect"
53
+ };
54
+ var SearchWebBranchFound = SearchWebBranch.Found;
55
+ var SearchWebBranchProviderRejected = SearchWebBranch.ProviderRejected;
56
+ var SearchWebBranchInvalidResponse = SearchWebBranch.InvalidResponse;
57
+ var SearchWebBranchDefect = SearchWebBranch.Defect;
58
+ var SearchWebDefinition = {
59
+ operation: { connectorId: ConnectorID, operationId: "searchWeb" },
60
+ branches: [
61
+ { id: "found", description: "Bocha returned public web search results." },
62
+ { id: "providerRejected", description: "Bocha rejected the Key or query.", optional: true },
63
+ { id: "invalidResponse", description: "Bocha returned malformed or oversized search data.", optional: true },
64
+ { id: "defect", description: "The local query or API Key is invalid.", optional: true }
65
+ ],
66
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async", executeRetry: { initialIntervalMs: 2e3, backoffCoefficient: 2, maximumIntervalMs: 1e4, maximumAttempts: 2, totalDurationMs: 6e4 } }
67
+ };
68
+ var SearchWebMetadata = { kind: "query", idempotency: "none", authorization: "required" };
69
+
70
+ // src/generated/connection.ts
71
+ import { ConnectionRefSchema } from "@superdurable/connectors-sdk";
72
+ var Connection = class {
73
+ /** Stable provider and connection name. */
74
+ reference;
75
+ /** Bound provider operations. */
76
+ operations;
77
+ /** Validate a reference and bind operations. */
78
+ constructor(reference, operations) {
79
+ this.reference = ConnectionRefSchema.parse(reference);
80
+ if (this.reference.provider !== ProviderID) throw new TypeError("connection provider differs from the manifest");
81
+ if (!operations) throw new TypeError("connector operations are required");
82
+ this.operations = operations;
83
+ }
84
+ };
85
+ function newConnection(client, reference) {
86
+ if (!client) throw new TypeError("connector client is required");
87
+ return new Connection(reference, client);
88
+ }
89
+ function newConnectionWithOperations(operations, reference) {
90
+ return new Connection(reference, operations);
91
+ }
92
+ function newProjectConnection(project, connectionName, createClient) {
93
+ if (!project) throw new TypeError("loaded project is required");
94
+ const reference = ConnectionRefSchema.parse({ provider: ProviderID, name: connectionName });
95
+ const selected = project.configuration.connections.find((entry) => entry.connectorId === ConnectorID && entry.connectionName === connectionName);
96
+ if (!selected || selected.provider !== ProviderID) throw new TypeError("project connection is not configured");
97
+ return newConnection(createClient(project, connectionName), reference);
98
+ }
99
+
100
+ export {
101
+ ConfigSchema,
102
+ CredentialMaterialError,
103
+ isCredentialMaterialError,
104
+ decodeCredentials,
105
+ SearchWebInputSchema,
106
+ WebResultSchema,
107
+ SearchWebOutputSchema,
108
+ ConnectorID,
109
+ ProviderID,
110
+ SearchWebBranch,
111
+ SearchWebBranchFound,
112
+ SearchWebBranchProviderRejected,
113
+ SearchWebBranchInvalidResponse,
114
+ SearchWebBranchDefect,
115
+ SearchWebDefinition,
116
+ SearchWebMetadata,
117
+ Connection,
118
+ newConnection,
119
+ newConnectionWithOperations,
120
+ newProjectConnection
121
+ };
@@ -0,0 +1,88 @@
1
+ import { SecretString, CredentialProvider, Query, ConnectionRef } from '@superdurable/connectors-sdk';
2
+ import { z } from 'zod';
3
+
4
+ /** Connector configuration; omitted fields use manifest defaults. */
5
+ interface Config {
6
+ /** Maximum duration of one web search HTTP request as a positive Go duration such as 5s or 1m. Blank uses the displayed default; increase only for a slow approved network. Runtime value in milliseconds. */
7
+ timeoutMs?: number;
8
+ /** Maximum provider response size in bytes as a positive integer. Blank uses the displayed default; increase only if the search response grows. */
9
+ maxResponseBytes?: number;
10
+ }
11
+ /** Runtime schema for manifest configuration. */
12
+ declare const ConfigSchema: z.ZodObject<{
13
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
14
+ maxResponseBytes: z.ZodOptional<z.ZodNumber>;
15
+ }, z.core.$strip>;
16
+ /** Private connector credentials resolved by the host. */
17
+ interface Credentials {
18
+ /** Secret API Key from https://open.bochaai.com/api-keys > 账户管理 > API KEY管理 > 创建 API KEY. Copy the exact ASCII value shown once, without whitespace; blank prevents requests. Dex stores it as a secret. */
19
+ apiKey: SecretString;
20
+ }
21
+ /** Stored credential material that fails the connector credential checks, so no retry can succeed. */
22
+ declare class CredentialMaterialError extends TypeError {
23
+ constructor(message: string);
24
+ }
25
+ /** Report malformed stored credential material, also behind the SDK provider's decoding TypeError. */
26
+ declare function isCredentialMaterialError(error: unknown): boolean;
27
+ /** Decode private credential fields for the connector. */
28
+ declare function decodeCredentials(value: unknown): Credentials;
29
+ /** Host-owned source of private connector credentials. */
30
+ type CredentialSource = CredentialProvider<Credentials>;
31
+ /** SearchWebInput supplies a public web search query. */
32
+ interface SearchWebInput {
33
+ /** Query is a nonblank search phrase of at most 256 Unicode characters. */
34
+ "query": string;
35
+ }
36
+ /** WebResult contains a title, HTTPS URL, and short search excerpt. */
37
+ interface WebResult {
38
+ /** Title is the provider's page title. */
39
+ "title": string;
40
+ /** URL is the page's public HTTPS URL. */
41
+ "url": string;
42
+ /** Snippet is the provider's short search excerpt. */
43
+ "snippet": string;
44
+ }
45
+ /** SearchWebOutput contains up to five public web results. */
46
+ interface SearchWebOutput {
47
+ /** Results are the public pages returned in provider ranking order. */
48
+ "results": Array<WebResult> | null;
49
+ }
50
+ /** Runtime validator for SearchWebInput. */
51
+ declare const SearchWebInputSchema: z.ZodObject<{
52
+ query: z.ZodString;
53
+ }, z.core.$strict>;
54
+ /** Runtime validator for WebResult. */
55
+ declare const WebResultSchema: z.ZodObject<{
56
+ title: z.ZodString;
57
+ url: z.ZodString;
58
+ snippet: z.ZodString;
59
+ }, z.core.$strict>;
60
+ /** Runtime validator for SearchWebOutput. */
61
+ declare const SearchWebOutputSchema: z.ZodObject<{
62
+ results: z.ZodNullable<z.ZodArray<z.ZodObject<{
63
+ title: z.ZodString;
64
+ url: z.ZodString;
65
+ snippet: z.ZodString;
66
+ }, z.core.$strict>>>;
67
+ }, z.core.$strict>;
68
+
69
+ /** Typed operations supplied by a client or mock. */
70
+ interface Operations {
71
+ /** Invoke searchWeb through this connection. */
72
+ searchWeb(): Query<SearchWebInput, SearchWebOutput>;
73
+ }
74
+ /** Named connector connection kept outside Flow state. */
75
+ declare class Connection<BoundOperations = Operations> {
76
+ /** Stable provider and connection name. */
77
+ readonly reference: ConnectionRef;
78
+ /** Bound provider operations. */
79
+ readonly operations: BoundOperations;
80
+ /** Validate a reference and bind operations. */
81
+ constructor(reference: ConnectionRef, operations: BoundOperations);
82
+ }
83
+ /** Bind a client to a named connection. */
84
+ declare function newConnection(client: Operations, reference: ConnectionRef): Connection;
85
+ /** Bind scripted operations to a named connection. */
86
+ declare function newConnectionWithOperations(operations: Operations, reference: ConnectionRef): Connection;
87
+
88
+ export { Connection as C, type Operations as O, type SearchWebInput as S, type WebResult as W, type SearchWebOutput as a, type Config as b, type Credentials as c, ConfigSchema as d, CredentialMaterialError as e, type CredentialSource as f, SearchWebInputSchema as g, SearchWebOutputSchema as h, WebResultSchema as i, decodeCredentials as j, isCredentialMaterialError as k, newConnectionWithOperations as l, newConnection as n };
@@ -0,0 +1,89 @@
1
+ import { S as SearchWebInput, a as SearchWebOutput, C as Connection, O as Operations, b as Config, c as Credentials } from './connection-CBfBAI-2.js';
2
+ export { d as ConfigSchema, e as CredentialMaterialError, f as CredentialSource, g as SearchWebInputSchema, h as SearchWebOutputSchema, W as WebResult, i as WebResultSchema, j as decodeCredentials, k as isCredentialMaterialError, n as newConnection, l as newConnectionWithOperations } from './connection-CBfBAI-2.js';
3
+ import { QueryDefinition, QueryStepConfig, Query, QueryResult, QueryStep, CredentialProvider, Call, QueryAttempt } from '@superdurable/connectors-sdk';
4
+ import { StepTarget } from '@superdurable/dex';
5
+ import { LoadedProject } from '@superdurable/connectors-sdk/projectconfig';
6
+ import { ProviderRequest, ProviderResponse } from '@superdurable/connectors-sdk/providerhttp';
7
+ import 'zod';
8
+
9
+ /** Stable connector identity. */
10
+ declare const ConnectorID = "bocha";
11
+ /** Provider identity for named connections. */
12
+ declare const ProviderID = "bocha";
13
+ /** Branch IDs for searchWeb. */
14
+ declare const SearchWebBranch: {
15
+ readonly Found: "found";
16
+ readonly ProviderRejected: "providerRejected";
17
+ readonly InvalidResponse: "invalidResponse";
18
+ readonly Defect: "defect";
19
+ };
20
+ /** Bocha returned public web search results. */
21
+ declare const SearchWebBranchFound: "found";
22
+ /** Bocha rejected the Key or query. */
23
+ declare const SearchWebBranchProviderRejected: "providerRejected";
24
+ /** Bocha returned malformed or oversized search data. */
25
+ declare const SearchWebBranchInvalidResponse: "invalidResponse";
26
+ /** The local query or API Key is invalid. */
27
+ declare const SearchWebBranchDefect: "defect";
28
+ /** Manifest definition for searchWeb. */
29
+ declare const SearchWebDefinition: QueryDefinition;
30
+ /** Manifest metadata for searchWeb. */
31
+ declare const SearchWebMetadata: {
32
+ readonly kind: "query";
33
+ readonly idempotency: "none";
34
+ readonly authorization: "required";
35
+ };
36
+
37
+ /** Configuration for the searchWeb connector Step. */
38
+ interface SearchWebStepConfig<StepInput, OperationInput = SearchWebInput, OperationOutput = SearchWebOutput> extends Omit<QueryStepConfig<StepInput, OperationInput, OperationOutput>, 'operation' | 'connection' | 'branches'> {
39
+ /** Named connection supplying this operation. */
40
+ connection: Connection<{
41
+ searchWeb(): Query<OperationInput, OperationOutput>;
42
+ }>;
43
+ /** Name matching the bound connection. */
44
+ connectionName: string;
45
+ /** Bocha returned public web search results. */
46
+ found: StepTarget<QueryResult<OperationOutput>>;
47
+ /** Bocha rejected the Key or query. */
48
+ providerRejected?: StepTarget<QueryResult<OperationOutput>>;
49
+ /** Bocha returned malformed or oversized search data. */
50
+ invalidResponse?: StepTarget<QueryResult<OperationOutput>>;
51
+ /** The local query or API Key is invalid. */
52
+ defect?: StepTarget<QueryResult<OperationOutput>>;
53
+ }
54
+ /** Build the searchWeb Step from a named connection. */
55
+ declare function newSearchWebStep<StepInput, OperationInput = SearchWebInput, OperationOutput = SearchWebOutput>(configuration: SearchWebStepConfig<StepInput, OperationInput, OperationOutput>): QueryStep<StepInput, OperationInput, OperationOutput>;
56
+
57
+ /** Open one named Bocha connection from Dex project configuration. */
58
+ declare function newProjectConnection(project: LoadedProject, connectionName: string): Connection<Operations>;
59
+
60
+ /** Optional HTTP transport for local provider tests. */
61
+ interface BochaClientOptions {
62
+ send?: (request: ProviderRequest) => Promise<ProviderResponse>;
63
+ }
64
+ /** Resolve Bocha credentials for each billed web search. */
65
+ declare class BochaClient {
66
+ private readonly credentials;
67
+ private readonly timeoutMs;
68
+ private readonly maxResponseBytes;
69
+ private readonly send;
70
+ /** Validate connection settings without contacting Bocha. */
71
+ constructor(config: Config, credentials: CredentialProvider<Credentials>, options?: BochaClientOptions);
72
+ /** Bind the public web search Query. */ searchWeb(): SearchWebOperation;
73
+ /** Send one bounded web search request. */
74
+ getSearchResults(call: Call, query: string): Promise<{
75
+ response?: ProviderResponse;
76
+ error?: 'credential' | 'transport' | 'tooLarge';
77
+ retryAfterMs: number;
78
+ }>;
79
+ }
80
+ /** Search public web pages and return at most five results. */
81
+ declare class SearchWebOperation implements Query<SearchWebInput, SearchWebOutput> {
82
+ private readonly client;
83
+ /** Bind the provider client. */ constructor(client: BochaClient);
84
+ /** Return the generated Query definition. */ definition(): QueryDefinition;
85
+ /** Classify one provider response using the Go connector contract. */
86
+ invoke(call: Call, input: SearchWebInput): Promise<QueryAttempt<SearchWebOutput>>;
87
+ }
88
+
89
+ export { BochaClient, type BochaClientOptions, Config, Connection, ConnectorID, Credentials, ProviderID, SearchWebBranch, SearchWebBranchDefect, SearchWebBranchFound, SearchWebBranchInvalidResponse, SearchWebBranchProviderRejected, SearchWebDefinition, SearchWebInput, SearchWebMetadata, SearchWebOutput, type SearchWebStepConfig, newProjectConnection, newSearchWebStep };
package/dist/index.js ADDED
@@ -0,0 +1,196 @@
1
+ import {
2
+ ConfigSchema,
3
+ Connection,
4
+ ConnectorID,
5
+ CredentialMaterialError,
6
+ ProviderID,
7
+ SearchWebBranch,
8
+ SearchWebBranchDefect,
9
+ SearchWebBranchFound,
10
+ SearchWebBranchInvalidResponse,
11
+ SearchWebBranchProviderRejected,
12
+ SearchWebDefinition,
13
+ SearchWebInputSchema,
14
+ SearchWebMetadata,
15
+ SearchWebOutputSchema,
16
+ WebResultSchema,
17
+ decodeCredentials,
18
+ isCredentialMaterialError,
19
+ newConnection,
20
+ newConnectionWithOperations,
21
+ newProjectConnection
22
+ } from "./chunk-M35YPGGU.js";
23
+
24
+ // src/generated/steps.ts
25
+ import { goToBranch, newQueryStep } from "@superdurable/connectors-sdk";
26
+ function newSearchWebStep(configuration) {
27
+ const { connection, connectionName, found, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
28
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
29
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.searchWeb(), connection: connection.reference, branches: [
30
+ goToBranch("found", found),
31
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
32
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
33
+ ...defect ? [goToBranch("defect", defect)] : []
34
+ ] });
35
+ }
36
+
37
+ // src/client.ts
38
+ import { SecretString, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
39
+ import { BodyTooLargeError, parseRetryAfter, sendProviderRequest } from "@superdurable/connectors-sdk/providerhttp";
40
+ var BochaClient = class {
41
+ /** Validate connection settings without contacting Bocha. */
42
+ constructor(config, credentials, options = {}) {
43
+ this.credentials = credentials;
44
+ if (!config || !credentials) throw new TypeError("Bocha configuration and credentials are required");
45
+ this.timeoutMs = config.timeoutMs || 15e3;
46
+ this.maxResponseBytes = config.maxResponseBytes || 1048576;
47
+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0 || this.maxResponseBytes > 16 * 1024 * 1024) throw new TypeError("Bocha request limits are invalid");
48
+ this.send = options.send ?? sendProviderRequest;
49
+ }
50
+ credentials;
51
+ timeoutMs;
52
+ maxResponseBytes;
53
+ send;
54
+ /** Bind the public web search Query. */
55
+ searchWeb() {
56
+ return new SearchWebOperation(this);
57
+ }
58
+ /** Send one bounded web search request. */
59
+ async getSearchResults(call, query) {
60
+ let apiKey = "";
61
+ try {
62
+ const credential = await this.credentials.resolve(call, call.context.cancellationSignal);
63
+ apiKey = credential.apiKey instanceof SecretString ? credential.apiKey.reveal() : "";
64
+ } catch {
65
+ return { error: "credential", retryAfterMs: 0 };
66
+ }
67
+ if (!apiKey || apiKey.length > 1024 || /[^\x21-\x7e]/.test(apiKey)) return { error: "credential", retryAfterMs: 0 };
68
+ const request = { url: "https://api.bochaai.com/v1/web-search", method: "POST", headers: { Accept: "application/json", Authorization: "Bearer " + apiKey, "Content-Type": "application/json" }, body: new TextEncoder().encode(JSON.stringify({ query, count: 5, summary: false })), timeoutMs: this.timeoutMs, maxResponseBytes: this.maxResponseBytes, addressPolicy: "publicHTTPS", signal: call.context.cancellationSignal };
69
+ let response;
70
+ try {
71
+ response = await this.send(request);
72
+ } catch (error) {
73
+ if (error instanceof BodyTooLargeError && error.status !== void 0) return { response: { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() }, error: "tooLarge", retryAfterMs: 0 };
74
+ return { error: "transport", retryAfterMs: 0 };
75
+ }
76
+ return { response, error: response.body.length > this.maxResponseBytes ? "tooLarge" : void 0, retryAfterMs: parseRetryAfter(header(response.headers, "retry-after")) };
77
+ }
78
+ };
79
+ var SearchWebOperation = class {
80
+ /** Bind the provider client. */
81
+ constructor(client) {
82
+ this.client = client;
83
+ }
84
+ client;
85
+ /** Return the generated Query definition. */
86
+ definition() {
87
+ return SearchWebDefinition;
88
+ }
89
+ /** Classify one provider response using the Go connector contract. */
90
+ async invoke(call, input) {
91
+ if (!input || typeof input.query !== "string" || !input.query.trim() || [...input.query].length > 256) return branch("defect", "VALIDATION");
92
+ const exchange = await this.client.getSearchResults(call, input.query);
93
+ if (exchange.error === "credential") return branch("defect", "AUTHENTICATION");
94
+ if (exchange.error === "transport" || !exchange.response) return retry("AVAILABILITY");
95
+ const { status, body } = exchange.response;
96
+ if (status === 429) return retry("RATE_LIMIT", exchange.retryAfterMs);
97
+ if (status === 408 || status >= 500) return retry("AVAILABILITY", exchange.retryAfterMs);
98
+ if (status !== 200) return branch("providerRejected", status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : "PROVIDER_REJECTION");
99
+ if (exchange.error === "tooLarge") return branch("invalidResponse", "RESPONSE_TOO_LARGE");
100
+ let wire;
101
+ try {
102
+ wire = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
103
+ } catch {
104
+ return branch("invalidResponse", "PROTOCOL");
105
+ }
106
+ if (!wire || typeof wire !== "object" || Array.isArray(wire)) return branch("invalidResponse", "PROTOCOL");
107
+ const result = wire;
108
+ if (typeof result.code !== "number" || !Number.isInteger(result.code)) return branch("invalidResponse", "PROTOCOL");
109
+ if (result.code !== 200) return branch("providerRejected", "PROVIDER_REJECTION");
110
+ const pages = result.data?.webPages?.value;
111
+ if (!Array.isArray(pages) || pages.length > 50) return branch("invalidResponse", "PROTOCOL");
112
+ const results = [];
113
+ for (const page of pages.slice(0, 5)) {
114
+ if (!page || typeof page !== "object" || Array.isArray(page)) return branch("invalidResponse", "PROTOCOL");
115
+ const candidate = page;
116
+ if (typeof candidate.name !== "string" || !candidate.name || Buffer.byteLength(candidate.name) > 500 || typeof candidate.url !== "string" || typeof candidate.snippet !== "string" || Buffer.byteLength(candidate.snippet) > 2e3) return branch("invalidResponse", "PROTOCOL");
117
+ let parsed;
118
+ try {
119
+ parsed = new URL(candidate.url);
120
+ } catch {
121
+ return branch("invalidResponse", "PROTOCOL");
122
+ }
123
+ if (parsed.protocol !== "https:" || !parsed.hostname || parsed.username || parsed.password) return branch("invalidResponse", "PROTOCOL");
124
+ results.push({ title: candidate.name, url: candidate.url, snippet: candidate.snippet });
125
+ }
126
+ return newQueryBranch("found", { results });
127
+ }
128
+ };
129
+ function header(headers, name) {
130
+ const value = Object.entries(headers).find(([key]) => key.toLowerCase() === name)?.[1];
131
+ return Array.isArray(value) ? value[0] ?? "" : value ?? "";
132
+ }
133
+ function failure(kind) {
134
+ return { provider: "bocha", operation: "searchWeb", kind, message: "Bocha web search failed" };
135
+ }
136
+ function branch(name, kind) {
137
+ return newQueryBranch(name, { results: [] }, {}, failure(kind));
138
+ }
139
+ function retry(kind, delay = 0) {
140
+ return newQueryRetry(failure(kind), delay);
141
+ }
142
+
143
+ // src/project.ts
144
+ function newProjectConnection2(project, connectionName) {
145
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
146
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "bocha" && entry.connectionName === name);
147
+ if (!selected) throw new TypeError("Bocha project connection is not configured");
148
+ const fields = selected.configuration;
149
+ const config = ConfigSchema.parse({ ...fields, ...fields.timeout !== void 0 ? { timeoutMs: parseDurationMilliseconds(fields.timeout) } : {} });
150
+ const credentials = {
151
+ async resolve(_call, signal) {
152
+ return decodeCredentials(await loadedProject.resolveCredential("bocha", name, signal));
153
+ }
154
+ };
155
+ return new BochaClient(config, credentials);
156
+ });
157
+ }
158
+ function parseDurationMilliseconds(value) {
159
+ if (typeof value === "number") return Math.ceil(value / 1e6);
160
+ if (typeof value !== "string") throw new TypeError("timeout must be a duration");
161
+ let remaining = value;
162
+ let milliseconds = 0;
163
+ const units = { ns: 1e-6, us: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
164
+ while (remaining) {
165
+ const part = /^(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/.exec(remaining);
166
+ if (!part) throw new TypeError("timeout must be a positive Go duration");
167
+ milliseconds += Number(part[1]) * (units[part[2] ?? ""] ?? NaN);
168
+ remaining = remaining.slice(part[0].length);
169
+ }
170
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) throw new TypeError("timeout must resolve to positive whole milliseconds");
171
+ return milliseconds;
172
+ }
173
+ export {
174
+ BochaClient,
175
+ ConfigSchema,
176
+ Connection,
177
+ ConnectorID,
178
+ CredentialMaterialError,
179
+ ProviderID,
180
+ SearchWebBranch,
181
+ SearchWebBranchDefect,
182
+ SearchWebBranchFound,
183
+ SearchWebBranchInvalidResponse,
184
+ SearchWebBranchProviderRejected,
185
+ SearchWebDefinition,
186
+ SearchWebInputSchema,
187
+ SearchWebMetadata,
188
+ SearchWebOutputSchema,
189
+ WebResultSchema,
190
+ decodeCredentials,
191
+ isCredentialMaterialError,
192
+ newConnection,
193
+ newConnectionWithOperations,
194
+ newProjectConnection2 as newProjectConnection,
195
+ newSearchWebStep
196
+ };
package/dist/mock.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { MockQuery, Case } from '@superdurable/connectors-sdk/connectormock';
2
+ import { Failure } from '@superdurable/connectors-sdk';
3
+ import { O as Operations, C as Connection, S as SearchWebInput, a as SearchWebOutput, W as WebResult } from './connection-CBfBAI-2.js';
4
+ import 'zod';
5
+
6
+ /** Go zero value for SearchWebInput in scripted cases. */
7
+ declare const emptySearchWebInput: SearchWebInput;
8
+ /** Go zero value for WebResult in scripted cases. */
9
+ declare const emptyWebResult: WebResult;
10
+ /** Go zero value for SearchWebOutput in scripted cases. */
11
+ declare const emptySearchWebOutput: SearchWebOutput;
12
+ /** Script the found branch. */
13
+ declare function searchWebFound(value: SearchWebOutput, failure?: Failure): Case<SearchWebOutput>;
14
+ /** Script the providerRejected branch. */
15
+ declare function searchWebProviderRejected(value: SearchWebOutput, failure?: Failure): Case<SearchWebOutput>;
16
+ /** Script the invalidResponse branch. */
17
+ declare function searchWebInvalidResponse(value: SearchWebOutput, failure?: Failure): Case<SearchWebOutput>;
18
+ /** Script the defect branch. */
19
+ declare function searchWebDefect(value: SearchWebOutput, failure?: Failure): Case<SearchWebOutput>;
20
+ /** Script a safe retry of searchWeb. */
21
+ declare function searchWebRetry(failure: Failure, retryAfterMs?: number): Case<SearchWebOutput>;
22
+ /** Manifest scenario searchResults for searchWeb. */
23
+ declare function searchWebSearchResults(): Case<SearchWebOutput>;
24
+ /** Default searchWeb scenario. */
25
+ declare function searchWebDefault(): Case<SearchWebOutput>;
26
+ /** Manifest scenario noResults for searchWeb. */
27
+ declare function searchWebNoResults(): Case<SearchWebOutput>;
28
+ /** Scripted operations and manifest defaults for this connector. */
29
+ declare class GeneratedMock implements Operations {
30
+ #private;
31
+ constructor(connectionName: string);
32
+ connection(): Connection;
33
+ searchWeb(): MockQuery<SearchWebInput, SearchWebOutput>;
34
+ assertNoFailures(): void;
35
+ }
36
+
37
+ export { GeneratedMock, emptySearchWebInput, emptySearchWebOutput, emptyWebResult, searchWebDefault, searchWebDefect, searchWebFound, searchWebInvalidResponse, searchWebNoResults, searchWebProviderRejected, searchWebRetry, searchWebSearchResults };
package/dist/mock.js ADDED
@@ -0,0 +1,79 @@
1
+ import {
2
+ ProviderID,
3
+ SearchWebDefinition,
4
+ SearchWebInputSchema,
5
+ SearchWebOutputSchema,
6
+ WebResultSchema,
7
+ newConnectionWithOperations
8
+ } from "./chunk-M35YPGGU.js";
9
+
10
+ // src/generated/mock.ts
11
+ import { branchCase, retryCase, newQuery } from "@superdurable/connectors-sdk/connectormock";
12
+ var emptySearchWebInput = SearchWebInputSchema.parse({
13
+ "query": ""
14
+ });
15
+ var emptyWebResult = WebResultSchema.parse({
16
+ "title": "",
17
+ "url": "",
18
+ "snippet": ""
19
+ });
20
+ var emptySearchWebOutput = SearchWebOutputSchema.parse({
21
+ "results": []
22
+ });
23
+ function searchWebFound(value, failure) {
24
+ return branchCase("found", value, failure);
25
+ }
26
+ function searchWebProviderRejected(value, failure) {
27
+ return branchCase("providerRejected", value, failure);
28
+ }
29
+ function searchWebInvalidResponse(value, failure) {
30
+ return branchCase("invalidResponse", value, failure);
31
+ }
32
+ function searchWebDefect(value, failure) {
33
+ return branchCase("defect", value, failure);
34
+ }
35
+ function searchWebRetry(failure, retryAfterMs = 0) {
36
+ return retryCase(failure, retryAfterMs);
37
+ }
38
+ function searchWebSearchResults() {
39
+ const value = SearchWebOutputSchema.parse({ "results": [{ "snippet": "Example search excerpt.", "title": "Example page", "url": "https://example.com/article" }] });
40
+ return branchCase("found", value);
41
+ }
42
+ function searchWebDefault() {
43
+ return searchWebSearchResults();
44
+ }
45
+ function searchWebNoResults() {
46
+ const value = SearchWebOutputSchema.parse({ "results": [] });
47
+ return branchCase("found", value);
48
+ }
49
+ var GeneratedMock = class {
50
+ #searchWeb;
51
+ #connection;
52
+ constructor(connectionName) {
53
+ this.#searchWeb = newQuery(SearchWebDefinition).default(searchWebDefault());
54
+ this.#connection = newConnectionWithOperations(this, { provider: ProviderID, name: connectionName });
55
+ }
56
+ connection() {
57
+ return this.#connection;
58
+ }
59
+ searchWeb() {
60
+ return this.#searchWeb;
61
+ }
62
+ assertNoFailures() {
63
+ this.#searchWeb.assertNoFailures();
64
+ }
65
+ };
66
+ export {
67
+ GeneratedMock,
68
+ emptySearchWebInput,
69
+ emptySearchWebOutput,
70
+ emptyWebResult,
71
+ searchWebDefault,
72
+ searchWebDefect,
73
+ searchWebFound,
74
+ searchWebInvalidResponse,
75
+ searchWebNoResults,
76
+ searchWebProviderRejected,
77
+ searchWebRetry,
78
+ searchWebSearchResults
79
+ };
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@superdurable/connector-bocha",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "license": "MIT",
5
+ "description": "bocha connector for Dex TypeScript applications",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/superdurable/dex-connectors-library.git",
9
+ "directory": "connectors/bocha/typescript"
10
+ },
11
+ "type": "module",
12
+ "engines": {
13
+ "node": "^22.0.0 || ^24.0.0"
14
+ },
15
+ "module": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ },
22
+ "./mock": {
23
+ "types": "./dist/mock.d.ts",
24
+ "import": "./dist/mock.js"
25
+ },
26
+ "./dex-connector.json": "./dex-connector.json"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "README.md",
31
+ "LICENSE",
32
+ "dex-connector.json"
33
+ ],
34
+ "scripts": {
35
+ "prepack": "npm run build",
36
+ "build": "tsup src/index.ts src/mock.ts --format esm --dts --clean",
37
+ "typecheck": "tsc --noEmit",
38
+ "lint": "eslint src test examples",
39
+ "test": "vitest run --exclude test/integration/**",
40
+ "test:integration": "vitest run test/integration/*.integration.test.ts",
41
+ "example:worker": "tsx examples/basic/worker.ts",
42
+ "example:start": "tsx examples/basic/start.ts",
43
+ "check": "npm run typecheck && npm run lint && npm test && npm run build"
44
+ },
45
+ "dependencies": {
46
+ "@superdurable/connectors-sdk": "0.1.1",
47
+ "@superdurable/dex": ">=1.28.0",
48
+ "zod": "^4.1.0"
49
+ },
50
+ "devDependencies": {
51
+ "@eslint/js": "^9.0.0",
52
+ "@types/node": "^22.0.0",
53
+ "eslint": "^9.0.0",
54
+ "tsup": "^8.0.0",
55
+ "tsx": "^4.23.15",
56
+ "typescript": "^5.9.0",
57
+ "typescript-eslint": "^8.0.0",
58
+ "vitest": "^3.0.0",
59
+ "yaml": "^2.9.1"
60
+ }
61
+ }