@superdurable/connector-niutrans 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
+ # Niutrans 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
+ Look up country, province, city, district, and network operator for one public IPv4 address.
4
+
5
+ Install `@superdurable/connector-niutrans` 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 `translateText` resolves credentials for each call. Local conformance tests replay the Go provider scenarios; live provider authorization has not been verified.
@@ -0,0 +1,70 @@
1
+ {
2
+ "connectorId": "niutrans",
3
+ "releaseTag": "connectors/niutrans/go/v0.1.0",
4
+ "package": {
5
+ "ecosystem": "npm",
6
+ "name": "@superdurable/connector-niutrans",
7
+ "version": "0.1.0"
8
+ },
9
+ "factories": [
10
+ {
11
+ "name": "newTranslateTextStep",
12
+ "kind": "query",
13
+ "operationId": "translateText",
14
+ "inputType": "TranslateTextInput",
15
+ "description": "Translate up to 1000 Unicode characters from one language to another.",
16
+ "fields": {
17
+ "stepType": "stepType",
18
+ "annotations": "annotations",
19
+ "connectionName": "connectionName",
20
+ "resultAttribute": "resultAttribute"
21
+ },
22
+ "branches": [
23
+ {
24
+ "id": "translated",
25
+ "field": "translated",
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": "TranslateTextInput supplies bounded source text and language codes.",
47
+ "properties": {
48
+ "from": {
49
+ "description": "From is the NiuTrans source language code, such as zh or auto.",
50
+ "type": "string"
51
+ },
52
+ "text": {
53
+ "description": "Text is the source content, limited to 1000 Unicode characters.",
54
+ "type": "string"
55
+ },
56
+ "to": {
57
+ "description": "To is the NiuTrans target language code, such as en.",
58
+ "type": "string"
59
+ }
60
+ },
61
+ "required": [
62
+ "from",
63
+ "text",
64
+ "to"
65
+ ],
66
+ "type": "object"
67
+ }
68
+ }
69
+ ]
70
+ }
@@ -0,0 +1,118 @@
1
+ // src/generated/models.ts
2
+ import { z } from "zod";
3
+ import { SecretString } from "@superdurable/connectors-sdk";
4
+ var ConfigSchema = z.object({
5
+ "baseUrl": z.string().optional(),
6
+ "timeoutMs": z.number().int().optional(),
7
+ "maxResponseBytes": z.number().int().optional()
8
+ });
9
+ var CredentialMaterialError = class extends TypeError {
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = "CredentialMaterialError";
13
+ }
14
+ };
15
+ var sdkCredentialDecodingFailureMessages = /* @__PURE__ */ new Set([
16
+ "project credential decoding failed",
17
+ "shared project credential decoding failed",
18
+ "project credential decoding failed: this connector version does not support shared credentials"
19
+ ]);
20
+ function isCredentialMaterialError(error) {
21
+ return error instanceof CredentialMaterialError || error instanceof TypeError && sdkCredentialDecodingFailureMessages.has(error.message);
22
+ }
23
+ function decodeCredentials(value) {
24
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new CredentialMaterialError("credential fields are invalid");
25
+ const fields = value;
26
+ const allowed = /* @__PURE__ */ new Set(["api_key"]);
27
+ if (Object.keys(fields).some((key) => !allowed.has(key))) throw new CredentialMaterialError("stored credential does not match the connector credential fields");
28
+ if (fields["api_key"] != null && !(typeof fields["api_key"] === "string")) throw new CredentialMaterialError("credential api_key has an invalid type");
29
+ const credentials = {};
30
+ if (!fields["api_key"]) throw new CredentialMaterialError("credential api_key is required");
31
+ credentials.apiKey = new SecretString(fields["api_key"] ?? "");
32
+ return credentials;
33
+ }
34
+ var TranslateTextInputSchema = z.strictObject({
35
+ "text": z.string(),
36
+ "from": z.string(),
37
+ "to": z.string()
38
+ });
39
+ var TranslateTextOutputSchema = z.strictObject({
40
+ "translatedText": z.string()
41
+ });
42
+
43
+ // src/generated/definitions.ts
44
+ var ConnectorID = "niutrans";
45
+ var ProviderID = "niutrans";
46
+ var TranslateTextBranch = {
47
+ Translated: "translated",
48
+ ProviderRejected: "providerRejected",
49
+ InvalidResponse: "invalidResponse",
50
+ Defect: "defect"
51
+ };
52
+ var TranslateTextBranchTranslated = TranslateTextBranch.Translated;
53
+ var TranslateTextBranchProviderRejected = TranslateTextBranch.ProviderRejected;
54
+ var TranslateTextBranchInvalidResponse = TranslateTextBranch.InvalidResponse;
55
+ var TranslateTextBranchDefect = TranslateTextBranch.Defect;
56
+ var TranslateTextDefinition = {
57
+ operation: { connectorId: ConnectorID, operationId: "translateText" },
58
+ branches: [
59
+ { id: "translated", description: "NiuTrans returned translated text." },
60
+ { id: "providerRejected", description: "NiuTrans rejected the key, quota, text, or language pair.", optional: true },
61
+ { id: "invalidResponse", description: "NiuTrans returned malformed or oversized data.", optional: true },
62
+ { id: "defect", description: "Local text, language code, or connection credentials are invalid.", optional: true }
63
+ ],
64
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async", executeRetry: { initialIntervalMs: 2e3, backoffCoefficient: 2, maximumIntervalMs: 1e4, maximumAttempts: 2, totalDurationMs: 6e4 } }
65
+ };
66
+ var TranslateTextMetadata = { kind: "query", idempotency: "none", authorization: "required" };
67
+
68
+ // src/generated/connection.ts
69
+ import { ConnectionRefSchema } from "@superdurable/connectors-sdk";
70
+ var Connection = class {
71
+ /** Stable provider and connection name. */
72
+ reference;
73
+ /** Bound provider operations. */
74
+ operations;
75
+ /** Validate a reference and bind operations. */
76
+ constructor(reference, operations) {
77
+ this.reference = ConnectionRefSchema.parse(reference);
78
+ if (this.reference.provider !== ProviderID) throw new TypeError("connection provider differs from the manifest");
79
+ if (!operations) throw new TypeError("connector operations are required");
80
+ this.operations = operations;
81
+ }
82
+ };
83
+ function newConnection(client, reference) {
84
+ if (!client) throw new TypeError("connector client is required");
85
+ return new Connection(reference, client);
86
+ }
87
+ function newConnectionWithOperations(operations, reference) {
88
+ return new Connection(reference, operations);
89
+ }
90
+ function newProjectConnection(project, connectionName, createClient) {
91
+ if (!project) throw new TypeError("loaded project is required");
92
+ const reference = ConnectionRefSchema.parse({ provider: ProviderID, name: connectionName });
93
+ const selected = project.configuration.connections.find((entry) => entry.connectorId === ConnectorID && entry.connectionName === connectionName);
94
+ if (!selected || selected.provider !== ProviderID) throw new TypeError("project connection is not configured");
95
+ return newConnection(createClient(project, connectionName), reference);
96
+ }
97
+
98
+ export {
99
+ ConfigSchema,
100
+ CredentialMaterialError,
101
+ isCredentialMaterialError,
102
+ decodeCredentials,
103
+ TranslateTextInputSchema,
104
+ TranslateTextOutputSchema,
105
+ ConnectorID,
106
+ ProviderID,
107
+ TranslateTextBranch,
108
+ TranslateTextBranchTranslated,
109
+ TranslateTextBranchProviderRejected,
110
+ TranslateTextBranchInvalidResponse,
111
+ TranslateTextBranchDefect,
112
+ TranslateTextDefinition,
113
+ TranslateTextMetadata,
114
+ Connection,
115
+ newConnection,
116
+ newConnectionWithOperations,
117
+ newProjectConnection
118
+ };
@@ -0,0 +1,78 @@
1
+ import { CredentialProvider, SecretString, Query, ConnectionRef } from '@superdurable/connectors-sdk';
2
+ import { z } from 'zod';
3
+
4
+ /** Connector configuration; omitted fields use manifest defaults. */
5
+ interface Config {
6
+ /** HTTPS origin of the NiuTrans translation API without a path. Leave blank for the displayed production endpoint; override only for an approved proxy or local test server. */
7
+ baseUrl?: string;
8
+ /** Maximum time for one translation attempt as a positive Go duration such as 10s or 1m. Leave blank for the displayed default; increase only for a slow approved proxy. Runtime value in milliseconds. */
9
+ timeoutMs?: number;
10
+ /** Maximum translation response size in bytes as a positive integer. Leave blank for the displayed default; raise only if a valid provider response exceeds it. */
11
+ maxResponseBytes?: number;
12
+ }
13
+ /** Runtime schema for manifest configuration. */
14
+ declare const ConfigSchema: z.ZodObject<{
15
+ baseUrl: z.ZodOptional<z.ZodString>;
16
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
17
+ maxResponseBytes: z.ZodOptional<z.ZodNumber>;
18
+ }, z.core.$strip>;
19
+ /** Private connector credentials resolved by the host. */
20
+ interface Credentials {
21
+ /** Secret APIKEY from https://niutrans.com > 控制台 > 个人中心 > APIKEY. Sign up, bind the account as requested, then reveal and copy the exact value; blank prevents requests. It is sent in the HTTPS form body and never Flow input. */
22
+ apiKey: SecretString;
23
+ }
24
+ /** Stored credential material that fails the connector credential checks, so no retry can succeed. */
25
+ declare class CredentialMaterialError extends TypeError {
26
+ constructor(message: string);
27
+ }
28
+ /** Report malformed stored credential material, also behind the SDK provider's decoding TypeError. */
29
+ declare function isCredentialMaterialError(error: unknown): boolean;
30
+ /** Decode private credential fields for the connector. */
31
+ declare function decodeCredentials(value: unknown): Credentials;
32
+ /** Host-owned source of private connector credentials. */
33
+ type CredentialSource = CredentialProvider<Credentials>;
34
+ /** TranslateTextInput supplies bounded source text and language codes. */
35
+ interface TranslateTextInput {
36
+ /** Text is the source content, limited to 1000 Unicode characters. */
37
+ "text": string;
38
+ /** From is the NiuTrans source language code, such as zh or auto. */
39
+ "from": string;
40
+ /** To is the NiuTrans target language code, such as en. */
41
+ "to": string;
42
+ }
43
+ /** TranslateTextOutput contains only the translated text, not provider echoes or the API key. */
44
+ interface TranslateTextOutput {
45
+ /** TranslatedText is the returned translation. */
46
+ "translatedText": string;
47
+ }
48
+ /** Runtime validator for TranslateTextInput. */
49
+ declare const TranslateTextInputSchema: z.ZodObject<{
50
+ text: z.ZodString;
51
+ from: z.ZodString;
52
+ to: z.ZodString;
53
+ }, z.core.$strict>;
54
+ /** Runtime validator for TranslateTextOutput. */
55
+ declare const TranslateTextOutputSchema: z.ZodObject<{
56
+ translatedText: z.ZodString;
57
+ }, z.core.$strict>;
58
+
59
+ /** Typed operations supplied by a client or mock. */
60
+ interface Operations {
61
+ /** Invoke translateText through this connection. */
62
+ translateText(): Query<TranslateTextInput, TranslateTextOutput>;
63
+ }
64
+ /** Named connector connection kept outside Flow state. */
65
+ declare class Connection<BoundOperations = Operations> {
66
+ /** Stable provider and connection name. */
67
+ readonly reference: ConnectionRef;
68
+ /** Bound provider operations. */
69
+ readonly operations: BoundOperations;
70
+ /** Validate a reference and bind operations. */
71
+ constructor(reference: ConnectionRef, operations: BoundOperations);
72
+ }
73
+ /** Bind a client to a named connection. */
74
+ declare function newConnection(client: Operations, reference: ConnectionRef): Connection;
75
+ /** Bind scripted operations to a named connection. */
76
+ declare function newConnectionWithOperations(operations: Operations, reference: ConnectionRef): Connection;
77
+
78
+ export { Connection as C, type Operations as O, type TranslateTextInput as T, type TranslateTextOutput as a, type Config as b, type Credentials as c, ConfigSchema as d, CredentialMaterialError as e, type CredentialSource as f, TranslateTextInputSchema as g, TranslateTextOutputSchema as h, decodeCredentials as i, isCredentialMaterialError as j, newConnectionWithOperations as k, newConnection as n };
@@ -0,0 +1,90 @@
1
+ import { T as TranslateTextInput, a as TranslateTextOutput, C as Connection, O as Operations, b as Config, c as Credentials } from './connection-CKuiEZIY.js';
2
+ export { d as ConfigSchema, e as CredentialMaterialError, f as CredentialSource, g as TranslateTextInputSchema, h as TranslateTextOutputSchema, i as decodeCredentials, j as isCredentialMaterialError, n as newConnection, k as newConnectionWithOperations } from './connection-CKuiEZIY.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 = "niutrans";
11
+ /** Provider identity for named connections. */
12
+ declare const ProviderID = "niutrans";
13
+ /** Branch IDs for translateText. */
14
+ declare const TranslateTextBranch: {
15
+ readonly Translated: "translated";
16
+ readonly ProviderRejected: "providerRejected";
17
+ readonly InvalidResponse: "invalidResponse";
18
+ readonly Defect: "defect";
19
+ };
20
+ /** NiuTrans returned translated text. */
21
+ declare const TranslateTextBranchTranslated: "translated";
22
+ /** NiuTrans rejected the key, quota, text, or language pair. */
23
+ declare const TranslateTextBranchProviderRejected: "providerRejected";
24
+ /** NiuTrans returned malformed or oversized data. */
25
+ declare const TranslateTextBranchInvalidResponse: "invalidResponse";
26
+ /** Local text, language code, or connection credentials are invalid. */
27
+ declare const TranslateTextBranchDefect: "defect";
28
+ /** Manifest definition for translateText. */
29
+ declare const TranslateTextDefinition: QueryDefinition;
30
+ /** Manifest metadata for translateText. */
31
+ declare const TranslateTextMetadata: {
32
+ readonly kind: "query";
33
+ readonly idempotency: "none";
34
+ readonly authorization: "required";
35
+ };
36
+
37
+ /** Configuration for the translateText connector Step. */
38
+ interface TranslateTextStepConfig<StepInput, OperationInput = TranslateTextInput, OperationOutput = TranslateTextOutput> extends Omit<QueryStepConfig<StepInput, OperationInput, OperationOutput>, 'operation' | 'connection' | 'branches'> {
39
+ /** Named connection supplying this operation. */
40
+ connection: Connection<{
41
+ translateText(): Query<OperationInput, OperationOutput>;
42
+ }>;
43
+ /** Name matching the bound connection. */
44
+ connectionName: string;
45
+ /** NiuTrans returned translated text. */
46
+ translated: StepTarget<QueryResult<OperationOutput>>;
47
+ /** NiuTrans rejected the key, quota, text, or language pair. */
48
+ providerRejected?: StepTarget<QueryResult<OperationOutput>>;
49
+ /** NiuTrans returned malformed or oversized data. */
50
+ invalidResponse?: StepTarget<QueryResult<OperationOutput>>;
51
+ /** Local text, language code, or connection credentials are invalid. */
52
+ defect?: StepTarget<QueryResult<OperationOutput>>;
53
+ }
54
+ /** Build the translateText Step from a named connection. */
55
+ declare function newTranslateTextStep<StepInput, OperationInput = TranslateTextInput, OperationOutput = TranslateTextOutput>(configuration: TranslateTextStepConfig<StepInput, OperationInput, OperationOutput>): QueryStep<StepInput, OperationInput, OperationOutput>;
56
+
57
+ /** Open one named Niutrans connection from Dex project configuration. */
58
+ declare function newProjectConnection(project: LoadedProject, connectionName: string): Connection<Operations>;
59
+
60
+ /** Optional HTTP transport for provider tests. */
61
+ interface NiutransClientOptions {
62
+ send?: (request: ProviderRequest) => Promise<ProviderResponse>;
63
+ }
64
+ /** Resolve NiuTrans credentials for each metered translation query. */
65
+ declare class NiutransClient {
66
+ private readonly credentials;
67
+ private readonly baseUrl;
68
+ private readonly timeoutMs;
69
+ private readonly maxResponseBytes;
70
+ private readonly send;
71
+ /** Validate settings without contacting NiuTrans. */
72
+ constructor(config: Config, credentials: CredentialProvider<Credentials>, options?: NiutransClientOptions);
73
+ /** Bind the translation Query. */ translateText(): TranslateTextOperation;
74
+ /** Send one bounded form request. */
75
+ request(call: Call, input: TranslateTextInput): Promise<{
76
+ response?: ProviderResponse;
77
+ error?: 'credential' | 'transport' | 'tooLarge';
78
+ retryAfterMs: number;
79
+ }>;
80
+ }
81
+ /** Translate bounded text through NiuTrans. */
82
+ declare class TranslateTextOperation implements Query<TranslateTextInput, TranslateTextOutput> {
83
+ private readonly client;
84
+ /** Bind the provider client. */ constructor(client: NiutransClient);
85
+ /** Return the generated Query definition. */ definition(): QueryDefinition;
86
+ /** Classify the provider response using the Go contract. */
87
+ invoke(call: Call, input: TranslateTextInput): Promise<QueryAttempt<TranslateTextOutput>>;
88
+ }
89
+
90
+ export { Config, Connection, ConnectorID, Credentials, NiutransClient, type NiutransClientOptions, ProviderID, TranslateTextBranch, TranslateTextBranchDefect, TranslateTextBranchInvalidResponse, TranslateTextBranchProviderRejected, TranslateTextBranchTranslated, TranslateTextDefinition, TranslateTextInput, TranslateTextMetadata, TranslateTextOutput, type TranslateTextStepConfig, newProjectConnection, newTranslateTextStep };
package/dist/index.js ADDED
@@ -0,0 +1,187 @@
1
+ import {
2
+ ConfigSchema,
3
+ Connection,
4
+ ConnectorID,
5
+ CredentialMaterialError,
6
+ ProviderID,
7
+ TranslateTextBranch,
8
+ TranslateTextBranchDefect,
9
+ TranslateTextBranchInvalidResponse,
10
+ TranslateTextBranchProviderRejected,
11
+ TranslateTextBranchTranslated,
12
+ TranslateTextDefinition,
13
+ TranslateTextInputSchema,
14
+ TranslateTextMetadata,
15
+ TranslateTextOutputSchema,
16
+ decodeCredentials,
17
+ isCredentialMaterialError,
18
+ newConnection,
19
+ newConnectionWithOperations,
20
+ newProjectConnection
21
+ } from "./chunk-PCCI4MRZ.js";
22
+
23
+ // src/generated/steps.ts
24
+ import { goToBranch, newQueryStep } from "@superdurable/connectors-sdk";
25
+ function newTranslateTextStep(configuration) {
26
+ const { connection, connectionName, translated, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
27
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
28
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.translateText(), connection: connection.reference, branches: [
29
+ goToBranch("translated", translated),
30
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
31
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
32
+ ...defect ? [goToBranch("defect", defect)] : []
33
+ ] });
34
+ }
35
+
36
+ // src/client.ts
37
+ import { SecretString, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
38
+ import { BodyTooLargeError, parseRetryAfter, sendProviderRequest } from "@superdurable/connectors-sdk/providerhttp";
39
+ var empty = { translatedText: "" };
40
+ var NiutransClient = class {
41
+ /** Validate settings without contacting NiuTrans. */
42
+ constructor(config, credentials, options = {}) {
43
+ this.credentials = credentials;
44
+ if (!config || !credentials) throw new TypeError("NiuTrans settings and credentials are required");
45
+ const url = new URL(config.baseUrl || "https://api.niutrans.com");
46
+ this.timeoutMs = config.timeoutMs || 15e3;
47
+ this.maxResponseBytes = config.maxResponseBytes || 65536;
48
+ if (url.protocol !== "https:" || url.pathname !== "/" && url.pathname !== "" || url.search || url.hash || !Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0 || this.maxResponseBytes > 16 * 1024 * 1024) throw new TypeError("NiuTrans settings are invalid");
49
+ this.baseUrl = url.origin;
50
+ this.send = options.send ?? sendProviderRequest;
51
+ }
52
+ credentials;
53
+ baseUrl;
54
+ timeoutMs;
55
+ maxResponseBytes;
56
+ send;
57
+ /** Bind the translation Query. */
58
+ translateText() {
59
+ return new TranslateTextOperation(this);
60
+ }
61
+ /** Send one bounded form request. */
62
+ async request(call, input) {
63
+ let apiKey = "";
64
+ try {
65
+ const resolved = await this.credentials.resolve(call, call.context.cancellationSignal);
66
+ apiKey = resolved.apiKey instanceof SecretString ? resolved.apiKey.reveal() : "";
67
+ } catch {
68
+ return { error: "credential", retryAfterMs: 0 };
69
+ }
70
+ if (!apiKey || apiKey.length > 512 || /[^\x21-\x7e]/.test(apiKey)) return { error: "credential", retryAfterMs: 0 };
71
+ const form = new URLSearchParams({ from: input.from, to: input.to, apikey: apiKey, src_text: input.text });
72
+ const request = { url: `${this.baseUrl}/NiuTransServer/translation`, method: "POST", headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded" }, body: new TextEncoder().encode(form.toString()), timeoutMs: this.timeoutMs, maxResponseBytes: this.maxResponseBytes, addressPolicy: "publicHTTPS", signal: call.context.cancellationSignal };
73
+ let response;
74
+ try {
75
+ response = await this.send(request);
76
+ } catch (error) {
77
+ if (error instanceof BodyTooLargeError && error.status !== void 0) return { response: { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() }, error: "tooLarge", retryAfterMs: 0 };
78
+ return { error: "transport", retryAfterMs: 0 };
79
+ }
80
+ return { response, error: response.body.length > this.maxResponseBytes ? "tooLarge" : void 0, retryAfterMs: parseRetryAfter(header(response.headers, "retry-after")) };
81
+ }
82
+ };
83
+ var TranslateTextOperation = class {
84
+ /** Bind the provider client. */
85
+ constructor(client) {
86
+ this.client = client;
87
+ }
88
+ client;
89
+ /** Return the generated Query definition. */
90
+ definition() {
91
+ return TranslateTextDefinition;
92
+ }
93
+ /** Classify the provider response using the Go contract. */
94
+ async invoke(call, input) {
95
+ if (typeof input?.text !== "string" || !input.text.trim() || [...input.text].length > 1e3 || typeof input.from !== "string" || !/^[A-Za-z][A-Za-z-]{1,11}$/.test(input.from) || typeof input.to !== "string" || !/^[A-Za-z][A-Za-z-]{1,11}$/.test(input.to) || input.from === input.to) return branch("defect", "VALIDATION");
96
+ const exchange = await this.client.request(call, input);
97
+ if (exchange.error === "credential") return branch("defect", "AUTHENTICATION");
98
+ if (exchange.error === "transport" || !exchange.response) return retry("AVAILABILITY");
99
+ const { status, body } = exchange.response;
100
+ if (status === 429) return retry("RATE_LIMIT", exchange.retryAfterMs);
101
+ if (status === 408 || status >= 500) return retry("AVAILABILITY", exchange.retryAfterMs);
102
+ if (exchange.error === "tooLarge") return branch("invalidResponse", "RESPONSE_TOO_LARGE");
103
+ if (status !== 200) return branch("providerRejected", status === 401 || status === 403 ? "AUTHENTICATION" : status === 400 ? "VALIDATION" : "PROVIDER_REJECTION");
104
+ let wire;
105
+ try {
106
+ wire = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
107
+ } catch {
108
+ return branch("invalidResponse", "PROTOCOL");
109
+ }
110
+ if (!wire || typeof wire !== "object" || Array.isArray(wire)) return branch("invalidResponse", "PROTOCOL");
111
+ const record = wire;
112
+ if (record.error_code !== void 0 && record.error_code !== "") {
113
+ if (record.error_code === "10001") return retry("RATE_LIMIT");
114
+ if (record.error_code === "13008") return retry("AVAILABILITY");
115
+ return branch("providerRejected", "PROVIDER_REJECTION");
116
+ }
117
+ if (typeof record.tgt_text !== "string" || !record.tgt_text || new TextEncoder().encode(record.tgt_text).length > 65536) return branch("invalidResponse", "PROTOCOL");
118
+ return newQueryBranch("translated", { translatedText: record.tgt_text });
119
+ }
120
+ };
121
+ function header(headers, name) {
122
+ const value = Object.entries(headers).find(([key]) => key.toLowerCase() === name)?.[1];
123
+ return Array.isArray(value) ? value[0] ?? "" : value ?? "";
124
+ }
125
+ function failure(kind) {
126
+ return { provider: "niutrans", operation: "translateText", kind, message: "NiuTrans translation query failed" };
127
+ }
128
+ function branch(name, kind) {
129
+ return newQueryBranch(name, empty, {}, failure(kind));
130
+ }
131
+ function retry(kind, delay = 0) {
132
+ return newQueryRetry(failure(kind), delay);
133
+ }
134
+
135
+ // src/project.ts
136
+ function newProjectConnection2(project, connectionName) {
137
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
138
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "niutrans" && entry.connectionName === name);
139
+ if (!selected) throw new TypeError("Niutrans project connection is not configured");
140
+ const fields = selected.configuration;
141
+ const config = ConfigSchema.parse({ ...fields, ...fields.timeout !== void 0 ? { timeoutMs: parseDurationMilliseconds(fields.timeout) } : {} });
142
+ const credentials = {
143
+ async resolve(_call, signal) {
144
+ return decodeCredentials(await loadedProject.resolveCredential("niutrans", name, signal));
145
+ }
146
+ };
147
+ return new NiutransClient(config, credentials);
148
+ });
149
+ }
150
+ function parseDurationMilliseconds(value) {
151
+ if (typeof value === "number") return Math.ceil(value / 1e6);
152
+ if (typeof value !== "string") throw new TypeError("timeout must be a duration");
153
+ let remaining = value;
154
+ let milliseconds = 0;
155
+ const units = { ns: 1e-6, us: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
156
+ while (remaining) {
157
+ const part = /^(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/.exec(remaining);
158
+ if (!part) throw new TypeError("timeout must be a positive Go duration");
159
+ milliseconds += Number(part[1]) * (units[part[2] ?? ""] ?? NaN);
160
+ remaining = remaining.slice(part[0].length);
161
+ }
162
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) throw new TypeError("timeout must resolve to positive whole milliseconds");
163
+ return milliseconds;
164
+ }
165
+ export {
166
+ ConfigSchema,
167
+ Connection,
168
+ ConnectorID,
169
+ CredentialMaterialError,
170
+ NiutransClient,
171
+ ProviderID,
172
+ TranslateTextBranch,
173
+ TranslateTextBranchDefect,
174
+ TranslateTextBranchInvalidResponse,
175
+ TranslateTextBranchProviderRejected,
176
+ TranslateTextBranchTranslated,
177
+ TranslateTextDefinition,
178
+ TranslateTextInputSchema,
179
+ TranslateTextMetadata,
180
+ TranslateTextOutputSchema,
181
+ decodeCredentials,
182
+ isCredentialMaterialError,
183
+ newConnection,
184
+ newConnectionWithOperations,
185
+ newProjectConnection2 as newProjectConnection,
186
+ newTranslateTextStep
187
+ };
package/dist/mock.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ import { MockQuery, Case } from '@superdurable/connectors-sdk/connectormock';
2
+ import { Failure } from '@superdurable/connectors-sdk';
3
+ import { O as Operations, C as Connection, T as TranslateTextInput, a as TranslateTextOutput } from './connection-CKuiEZIY.js';
4
+ import 'zod';
5
+
6
+ /** Go zero value for TranslateTextInput in scripted cases. */
7
+ declare const emptyTranslateTextInput: TranslateTextInput;
8
+ /** Go zero value for TranslateTextOutput in scripted cases. */
9
+ declare const emptyTranslateTextOutput: TranslateTextOutput;
10
+ /** Script the translated branch. */
11
+ declare function translateTextTranslated(value: TranslateTextOutput, failure?: Failure): Case<TranslateTextOutput>;
12
+ /** Script the providerRejected branch. */
13
+ declare function translateTextProviderRejected(value: TranslateTextOutput, failure?: Failure): Case<TranslateTextOutput>;
14
+ /** Script the invalidResponse branch. */
15
+ declare function translateTextInvalidResponse(value: TranslateTextOutput, failure?: Failure): Case<TranslateTextOutput>;
16
+ /** Script the defect branch. */
17
+ declare function translateTextDefect(value: TranslateTextOutput, failure?: Failure): Case<TranslateTextOutput>;
18
+ /** Script a safe retry of translateText. */
19
+ declare function translateTextRetry(failure: Failure, retryAfterMs?: number): Case<TranslateTextOutput>;
20
+ /** Manifest scenario sampleTranslation for translateText. */
21
+ declare function translateTextSampleTranslation(): Case<TranslateTextOutput>;
22
+ /** Default translateText scenario. */
23
+ declare function translateTextDefault(): Case<TranslateTextOutput>;
24
+ /** Scripted operations and manifest defaults for this connector. */
25
+ declare class GeneratedMock implements Operations {
26
+ #private;
27
+ constructor(connectionName: string);
28
+ connection(): Connection;
29
+ translateText(): MockQuery<TranslateTextInput, TranslateTextOutput>;
30
+ assertNoFailures(): void;
31
+ }
32
+
33
+ export { GeneratedMock, emptyTranslateTextInput, emptyTranslateTextOutput, translateTextDefault, translateTextDefect, translateTextInvalidResponse, translateTextProviderRejected, translateTextRetry, translateTextSampleTranslation, translateTextTranslated };
package/dist/mock.js ADDED
@@ -0,0 +1,69 @@
1
+ import {
2
+ ProviderID,
3
+ TranslateTextDefinition,
4
+ TranslateTextInputSchema,
5
+ TranslateTextOutputSchema,
6
+ newConnectionWithOperations
7
+ } from "./chunk-PCCI4MRZ.js";
8
+
9
+ // src/generated/mock.ts
10
+ import { branchCase, retryCase, newQuery } from "@superdurable/connectors-sdk/connectormock";
11
+ var emptyTranslateTextInput = TranslateTextInputSchema.parse({
12
+ "text": "",
13
+ "from": "",
14
+ "to": ""
15
+ });
16
+ var emptyTranslateTextOutput = TranslateTextOutputSchema.parse({
17
+ "translatedText": ""
18
+ });
19
+ function translateTextTranslated(value, failure) {
20
+ return branchCase("translated", value, failure);
21
+ }
22
+ function translateTextProviderRejected(value, failure) {
23
+ return branchCase("providerRejected", value, failure);
24
+ }
25
+ function translateTextInvalidResponse(value, failure) {
26
+ return branchCase("invalidResponse", value, failure);
27
+ }
28
+ function translateTextDefect(value, failure) {
29
+ return branchCase("defect", value, failure);
30
+ }
31
+ function translateTextRetry(failure, retryAfterMs = 0) {
32
+ return retryCase(failure, retryAfterMs);
33
+ }
34
+ function translateTextSampleTranslation() {
35
+ const value = TranslateTextOutputSchema.parse({ "translatedText": "Hello." });
36
+ return branchCase("translated", value);
37
+ }
38
+ function translateTextDefault() {
39
+ return translateTextSampleTranslation();
40
+ }
41
+ var GeneratedMock = class {
42
+ #translateText;
43
+ #connection;
44
+ constructor(connectionName) {
45
+ this.#translateText = newQuery(TranslateTextDefinition).default(translateTextDefault());
46
+ this.#connection = newConnectionWithOperations(this, { provider: ProviderID, name: connectionName });
47
+ }
48
+ connection() {
49
+ return this.#connection;
50
+ }
51
+ translateText() {
52
+ return this.#translateText;
53
+ }
54
+ assertNoFailures() {
55
+ this.#translateText.assertNoFailures();
56
+ }
57
+ };
58
+ export {
59
+ GeneratedMock,
60
+ emptyTranslateTextInput,
61
+ emptyTranslateTextOutput,
62
+ translateTextDefault,
63
+ translateTextDefect,
64
+ translateTextInvalidResponse,
65
+ translateTextProviderRejected,
66
+ translateTextRetry,
67
+ translateTextSampleTranslation,
68
+ translateTextTranslated
69
+ };
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@superdurable/connector-niutrans",
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": "niutrans connector for Dex TypeScript applications",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/superdurable/dex-connectors-library.git",
9
+ "directory": "connectors/niutrans/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.11.0",
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
+ }