@superdurable/connector-cloopen 0.0.0-stage → 0.1.1

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,9 @@
1
- # Temporary Holding Version
1
+ # Cloopen connector for Dex TypeScript
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
+ `@superdurable/connector-cloopen` implements the read-only `getBalance` Query. It calls the official [AccountInfo endpoint](https://doc.yuntongxun.com/p/5a533b4b3b8496dd00dce034) and returns only Cloopen's exact decimal balance string. The connector does not infer currency or units, and it omits account names, status, dates, and provider error text from Flow results.
4
+
5
+ Create a Dex Web connection named `cloopen`. Sign in at <https://console.yuntongxun.com>, open the management console account information, and copy the main-account 32-character `ACCOUNT SID` and `AUTH TOKEN` into the protected connection fields. Leave `baseUrl`, `timeout`, and `maxResponseBytes` blank for their production defaults unless an approved override is needed. Credentials never belong in Flow input.
6
+
7
+ Each request uses one UTC timestamp for an uppercase MD5 `sig` of `ACCOUNT SID + AUTH TOKEN + timestamp` and Base64 `Authorization` of `ACCOUNT SID + : + timestamp`, following the [REST authentication contract](https://doc.yuntongxun.com/p/5a533ac73b8496dd00dce025). A successful `statusCode` of `000000` selects `fetched`. Definite provider errors select the optional `providerRejected` branch; malformed or oversized data selects `invalidResponse`; invalid credentials select `defect` before any request. HTTP 408, 429, 5xx, transport errors, concurrency errors, and documented internal errors Retry through Dex.
8
+
9
+ [Run the balance Flow](examples/balance/README.md). Its real Dex integration test exercises a signed provider 503 followed by success and verifies persistence. Fourteen Go-recorded [conformance scenarios](../../../conformance/connectors/cloopen/scenarios.json) check exact signatures, requests, and outcomes. A real Cloopen account and live balance lookup have not been verified.
@@ -0,0 +1,52 @@
1
+ {
2
+ "connectorId": "cloopen",
3
+ "releaseTag": "connectors/cloopen/go/v0.1.0",
4
+ "package": {
5
+ "ecosystem": "npm",
6
+ "name": "@superdurable/connector-cloopen",
7
+ "version": "0.1.1"
8
+ },
9
+ "factories": [
10
+ {
11
+ "name": "newGetBalanceStep",
12
+ "kind": "query",
13
+ "operationId": "getBalance",
14
+ "inputType": "GetBalanceInput",
15
+ "description": "Read the main account balance as the provider's exact decimal string.",
16
+ "fields": {
17
+ "stepType": "stepType",
18
+ "annotations": "annotations",
19
+ "connectionName": "connectionName",
20
+ "resultAttribute": "resultAttribute"
21
+ },
22
+ "branches": [
23
+ {
24
+ "id": "fetched",
25
+ "field": "fetched",
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": "GetBalanceInput has no fields because the connected main account identifies the balance.",
47
+ "properties": {},
48
+ "type": "object"
49
+ }
50
+ }
51
+ ]
52
+ }
@@ -0,0 +1,117 @@
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(["account_sid", "auth_token"]);
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["account_sid"] != null && !(typeof fields["account_sid"] === "string")) throw new CredentialMaterialError("credential account_sid has an invalid type");
29
+ if (fields["auth_token"] != null && !(typeof fields["auth_token"] === "string")) throw new CredentialMaterialError("credential auth_token has an invalid type");
30
+ const credentials = {};
31
+ if (!fields["account_sid"]) throw new CredentialMaterialError("credential account_sid is required");
32
+ credentials.accountSid = new SecretString(fields["account_sid"] ?? "");
33
+ if (!fields["auth_token"]) throw new CredentialMaterialError("credential auth_token is required");
34
+ credentials.authToken = new SecretString(fields["auth_token"] ?? "");
35
+ return credentials;
36
+ }
37
+ var GetBalanceInputSchema = z.strictObject({});
38
+ var GetBalanceOutputSchema = z.strictObject({
39
+ "balance": z.string()
40
+ });
41
+
42
+ // src/generated/definitions.ts
43
+ var ConnectorID = "cloopen";
44
+ var ProviderID = "cloopen";
45
+ var GetBalanceBranch = {
46
+ Fetched: "fetched",
47
+ ProviderRejected: "providerRejected",
48
+ InvalidResponse: "invalidResponse",
49
+ Defect: "defect"
50
+ };
51
+ var GetBalanceBranchFetched = GetBalanceBranch.Fetched;
52
+ var GetBalanceBranchProviderRejected = GetBalanceBranch.ProviderRejected;
53
+ var GetBalanceBranchInvalidResponse = GetBalanceBranch.InvalidResponse;
54
+ var GetBalanceBranchDefect = GetBalanceBranch.Defect;
55
+ var GetBalanceDefinition = {
56
+ operation: { connectorId: ConnectorID, operationId: "getBalance" },
57
+ branches: [
58
+ { id: "fetched", description: "Cloopen returned the main-account balance." },
59
+ { id: "providerRejected", description: "Cloopen rejected the account or request.", optional: true },
60
+ { id: "invalidResponse", description: "Cloopen returned malformed or oversized data.", optional: true },
61
+ { id: "defect", description: "Connection credentials are missing or invalid.", optional: true }
62
+ ],
63
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async" }
64
+ };
65
+ var GetBalanceMetadata = { kind: "query", idempotency: "none", authorization: "required" };
66
+
67
+ // src/generated/connection.ts
68
+ import { ConnectionRefSchema } from "@superdurable/connectors-sdk";
69
+ var Connection = class {
70
+ /** Stable provider and connection name. */
71
+ reference;
72
+ /** Bound provider operations. */
73
+ operations;
74
+ /** Validate a reference and bind operations. */
75
+ constructor(reference, operations) {
76
+ this.reference = ConnectionRefSchema.parse(reference);
77
+ if (this.reference.provider !== ProviderID) throw new TypeError("connection provider differs from the manifest");
78
+ if (!operations) throw new TypeError("connector operations are required");
79
+ this.operations = operations;
80
+ }
81
+ };
82
+ function newConnection(client, reference) {
83
+ if (!client) throw new TypeError("connector client is required");
84
+ return new Connection(reference, client);
85
+ }
86
+ function newConnectionWithOperations(operations, reference) {
87
+ return new Connection(reference, operations);
88
+ }
89
+ function newProjectConnection(project, connectionName, createClient) {
90
+ if (!project) throw new TypeError("loaded project is required");
91
+ const reference = ConnectionRefSchema.parse({ provider: ProviderID, name: connectionName });
92
+ const selected = project.configuration.connections.find((entry) => entry.connectorId === ConnectorID && entry.connectionName === connectionName);
93
+ if (!selected || selected.provider !== ProviderID) throw new TypeError("project connection is not configured");
94
+ return newConnection(createClient(project, connectionName), reference);
95
+ }
96
+
97
+ export {
98
+ ConfigSchema,
99
+ CredentialMaterialError,
100
+ isCredentialMaterialError,
101
+ decodeCredentials,
102
+ GetBalanceInputSchema,
103
+ GetBalanceOutputSchema,
104
+ ConnectorID,
105
+ ProviderID,
106
+ GetBalanceBranch,
107
+ GetBalanceBranchFetched,
108
+ GetBalanceBranchProviderRejected,
109
+ GetBalanceBranchInvalidResponse,
110
+ GetBalanceBranchDefect,
111
+ GetBalanceDefinition,
112
+ GetBalanceMetadata,
113
+ Connection,
114
+ newConnection,
115
+ newConnectionWithOperations,
116
+ newProjectConnection
117
+ };
@@ -0,0 +1,70 @@
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
+ /** HTTPS origin of the Cloopen REST API without the version 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 account lookup as a positive Go duration such as 5s or 1m. Leave blank for the displayed default; increase only for a slow approved proxy. Runtime value in milliseconds. */
9
+ timeoutMs?: number;
10
+ /** Maximum account 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 main-account ACCOUNT SID from https://console.yuntongxun.com > management console > account information. Copy the exact 32-character alphanumeric ID; it is placed in the API path and signed header. Blank prevents requests. */
22
+ accountSid: SecretString;
23
+ /** Main-account AUTH TOKEN from https://console.yuntongxun.com > management console > account information. Copy the exact 32-character secret; it is used only to create the request signature. Blank prevents requests. */
24
+ authToken: SecretString;
25
+ }
26
+ /** Stored credential material that fails the connector credential checks, so no retry can succeed. */
27
+ declare class CredentialMaterialError extends TypeError {
28
+ constructor(message: string);
29
+ }
30
+ /** Report malformed stored credential material, also behind the SDK provider's decoding TypeError. */
31
+ declare function isCredentialMaterialError(error: unknown): boolean;
32
+ /** Decode private credential fields for the connector. */
33
+ declare function decodeCredentials(value: unknown): Credentials;
34
+ /** Host-owned source of private connector credentials. */
35
+ type CredentialSource = CredentialProvider<Credentials>;
36
+ /** GetBalanceInput has no fields because the connected main account identifies the balance. */
37
+ interface GetBalanceInput {
38
+ }
39
+ /** GetBalanceOutput reports the provider's account balance without changing its units. */
40
+ interface GetBalanceOutput {
41
+ /** Balance is Cloopen's nonnegative decimal balance string in provider units. */
42
+ "balance": string;
43
+ }
44
+ /** Runtime validator for GetBalanceInput. */
45
+ declare const GetBalanceInputSchema: z.ZodObject<{}, z.core.$strict>;
46
+ /** Runtime validator for GetBalanceOutput. */
47
+ declare const GetBalanceOutputSchema: z.ZodObject<{
48
+ balance: z.ZodString;
49
+ }, z.core.$strict>;
50
+
51
+ /** Typed operations supplied by a client or mock. */
52
+ interface Operations {
53
+ /** Invoke getBalance through this connection. */
54
+ getBalance(): Query<GetBalanceInput, GetBalanceOutput>;
55
+ }
56
+ /** Named connector connection kept outside Flow state. */
57
+ declare class Connection<BoundOperations = Operations> {
58
+ /** Stable provider and connection name. */
59
+ readonly reference: ConnectionRef;
60
+ /** Bound provider operations. */
61
+ readonly operations: BoundOperations;
62
+ /** Validate a reference and bind operations. */
63
+ constructor(reference: ConnectionRef, operations: BoundOperations);
64
+ }
65
+ /** Bind a client to a named connection. */
66
+ declare function newConnection(client: Operations, reference: ConnectionRef): Connection;
67
+ /** Bind scripted operations to a named connection. */
68
+ declare function newConnectionWithOperations(operations: Operations, reference: ConnectionRef): Connection;
69
+
70
+ export { Connection as C, type GetBalanceInput as G, type Operations as O, type GetBalanceOutput as a, type Config as b, type Credentials as c, ConfigSchema as d, CredentialMaterialError as e, type CredentialSource as f, GetBalanceInputSchema as g, GetBalanceOutputSchema as h, decodeCredentials as i, isCredentialMaterialError as j, newConnectionWithOperations as k, newConnection as n };
@@ -0,0 +1,97 @@
1
+ import { G as GetBalanceInput, a as GetBalanceOutput, C as Connection, b as Config, c as Credentials, O as Operations } from './connection-utPMl6ey.js';
2
+ export { d as ConfigSchema, e as CredentialMaterialError, f as CredentialSource, g as GetBalanceInputSchema, h as GetBalanceOutputSchema, i as decodeCredentials, j as isCredentialMaterialError, n as newConnection, k as newConnectionWithOperations } from './connection-utPMl6ey.js';
3
+ import { QueryDefinition, QueryStepConfig, Query, QueryResult, QueryStep, CredentialProvider, Call, QueryAttempt, Failure } 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 = "cloopen";
11
+ /** Provider identity for named connections. */
12
+ declare const ProviderID = "cloopen";
13
+ /** Branch IDs for getBalance. */
14
+ declare const GetBalanceBranch: {
15
+ readonly Fetched: "fetched";
16
+ readonly ProviderRejected: "providerRejected";
17
+ readonly InvalidResponse: "invalidResponse";
18
+ readonly Defect: "defect";
19
+ };
20
+ /** Cloopen returned the main-account balance. */
21
+ declare const GetBalanceBranchFetched: "fetched";
22
+ /** Cloopen rejected the account or request. */
23
+ declare const GetBalanceBranchProviderRejected: "providerRejected";
24
+ /** Cloopen returned malformed or oversized data. */
25
+ declare const GetBalanceBranchInvalidResponse: "invalidResponse";
26
+ /** Connection credentials are missing or invalid. */
27
+ declare const GetBalanceBranchDefect: "defect";
28
+ /** Manifest definition for getBalance. */
29
+ declare const GetBalanceDefinition: QueryDefinition;
30
+ /** Manifest metadata for getBalance. */
31
+ declare const GetBalanceMetadata: {
32
+ readonly kind: "query";
33
+ readonly idempotency: "none";
34
+ readonly authorization: "required";
35
+ };
36
+
37
+ /** Configuration for the getBalance connector Step. */
38
+ interface GetBalanceStepConfig<StepInput, OperationInput = GetBalanceInput, OperationOutput = GetBalanceOutput> extends Omit<QueryStepConfig<StepInput, OperationInput, OperationOutput>, 'operation' | 'connection' | 'branches'> {
39
+ /** Named connection supplying this operation. */
40
+ connection: Connection<{
41
+ getBalance(): Query<OperationInput, OperationOutput>;
42
+ }>;
43
+ /** Name matching the bound connection. */
44
+ connectionName: string;
45
+ /** Cloopen returned the main-account balance. */
46
+ fetched: StepTarget<QueryResult<OperationOutput>>;
47
+ /** Cloopen rejected the account or request. */
48
+ providerRejected?: StepTarget<QueryResult<OperationOutput>>;
49
+ /** Cloopen returned malformed or oversized data. */
50
+ invalidResponse?: StepTarget<QueryResult<OperationOutput>>;
51
+ /** Connection credentials are missing or invalid. */
52
+ defect?: StepTarget<QueryResult<OperationOutput>>;
53
+ }
54
+ /** Build the getBalance Step from a named connection. */
55
+ declare function newGetBalanceStep<StepInput, OperationInput = GetBalanceInput, OperationOutput = GetBalanceOutput>(configuration: GetBalanceStepConfig<StepInput, OperationInput, OperationOutput>): QueryStep<StepInput, OperationInput, OperationOutput>;
56
+
57
+ /** Provider HTTP sender, injectable for deterministic tests. */
58
+ type CloopenRequestSender = (request: ProviderRequest) => Promise<ProviderResponse>;
59
+ /** Client dependencies for tests and approved transports. */
60
+ interface CloopenClientOptions {
61
+ /** SDK transport when omitted. */ send?: CloopenRequestSender;
62
+ /** UTC clock used for request signatures and Retry-After dates. */ now?: () => Date;
63
+ }
64
+ /** Authenticated Cloopen main-account balance client. */
65
+ declare class CloopenClient {
66
+ private readonly credentials;
67
+ private readonly baseURL;
68
+ private readonly timeoutMs;
69
+ private readonly maxResponseBytes;
70
+ private readonly send;
71
+ private readonly now;
72
+ /** Validate settings without contacting the provider; credentials resolve for each call. */
73
+ constructor(config: Config, credentials: CredentialProvider<Credentials>, options?: CloopenClientOptions);
74
+ /** Bind the read-only getBalance Query. */ getBalance(): GetBalanceOperation;
75
+ /** Resolve credentials and send one signed, bounded account request. */
76
+ lookup(call: Call): Promise<{
77
+ response: ProviderResponse;
78
+ } | {
79
+ failure: Failure;
80
+ retry?: true;
81
+ retryAfterMs?: number;
82
+ branch?: string;
83
+ }>;
84
+ }
85
+ /** Read the main account balance without changing its provider units. */
86
+ declare class GetBalanceOperation implements Query<GetBalanceInput, GetBalanceOutput> {
87
+ private readonly client;
88
+ /** Bind the provider client. */ constructor(client: CloopenClient);
89
+ /** Generated Query definition. */ definition(): QueryDefinition;
90
+ /** Send one signed request and classify its result. */
91
+ invoke(call: Call, input: GetBalanceInput): Promise<QueryAttempt<GetBalanceOutput>>;
92
+ }
93
+
94
+ /** Bind a static Cloopen connection from Dex project configuration. */
95
+ declare function newProjectConnection(project: LoadedProject, connectionName: string, options?: CloopenClientOptions): Connection<Operations>;
96
+
97
+ export { CloopenClient, type CloopenClientOptions, type CloopenRequestSender, Config, Connection, ConnectorID, Credentials, GetBalanceBranch, GetBalanceBranchDefect, GetBalanceBranchFetched, GetBalanceBranchInvalidResponse, GetBalanceBranchProviderRejected, GetBalanceDefinition, GetBalanceInput, GetBalanceMetadata, GetBalanceOperation, GetBalanceOutput, type GetBalanceStepConfig, ProviderID, newGetBalanceStep, newProjectConnection };
package/dist/index.js ADDED
@@ -0,0 +1,224 @@
1
+ import {
2
+ ConfigSchema,
3
+ Connection,
4
+ ConnectorID,
5
+ CredentialMaterialError,
6
+ GetBalanceBranch,
7
+ GetBalanceBranchDefect,
8
+ GetBalanceBranchFetched,
9
+ GetBalanceBranchInvalidResponse,
10
+ GetBalanceBranchProviderRejected,
11
+ GetBalanceDefinition,
12
+ GetBalanceInputSchema,
13
+ GetBalanceMetadata,
14
+ GetBalanceOutputSchema,
15
+ ProviderID,
16
+ decodeCredentials,
17
+ isCredentialMaterialError,
18
+ newConnection,
19
+ newConnectionWithOperations,
20
+ newProjectConnection
21
+ } from "./chunk-YQ2YLXXH.js";
22
+
23
+ // src/generated/steps.ts
24
+ import { goToBranch, newQueryStep } from "@superdurable/connectors-sdk";
25
+ function newGetBalanceStep(configuration) {
26
+ const { connection, connectionName, fetched, 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.getBalance(), connection: connection.reference, branches: [
29
+ goToBranch("fetched", fetched),
30
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
31
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
32
+ ...defect ? [goToBranch("defect", defect)] : []
33
+ ] });
34
+ }
35
+
36
+ // src/project.ts
37
+ import { z } from "zod";
38
+
39
+ // src/client.ts
40
+ import { createHash } from "crypto";
41
+ import { SecretString, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
42
+ import { BodyTooLargeError, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
43
+ var emptyBalance = () => ({ balance: "" });
44
+ var CloopenClient = class {
45
+ /** Validate settings without contacting the provider; credentials resolve for each call. */
46
+ constructor(config, credentials, options = {}) {
47
+ this.credentials = credentials;
48
+ if (!config || !credentials) throw new TypeError("Cloopen configuration and credentials are required");
49
+ this.baseURL = validateBaseURL(config.baseUrl || "https://app.cloopen.com:8883").replace(/\/$/, "");
50
+ this.timeoutMs = config.timeoutMs ?? 1e4;
51
+ this.maxResponseBytes = config.maxResponseBytes ?? 65536;
52
+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0)
53
+ throw new TypeError("Cloopen timeout and maxResponseBytes must be positive whole numbers");
54
+ this.send = options.send ?? sendProviderRequest;
55
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
56
+ }
57
+ credentials;
58
+ baseURL;
59
+ timeoutMs;
60
+ maxResponseBytes;
61
+ send;
62
+ now;
63
+ /** Bind the read-only getBalance Query. */
64
+ getBalance() {
65
+ return new GetBalanceOperation(this);
66
+ }
67
+ /** Resolve credentials and send one signed, bounded account request. */
68
+ async lookup(call) {
69
+ let accountSid;
70
+ let authToken;
71
+ try {
72
+ const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
73
+ accountSid = credentials.accountSid instanceof SecretString ? credentials.accountSid.reveal() : "";
74
+ authToken = credentials.authToken instanceof SecretString ? credentials.authToken.reveal() : "";
75
+ } catch {
76
+ return { branch: "defect", failure: failure("AUTHENTICATION", "connection credentials are unavailable or invalid") };
77
+ }
78
+ if (!validAccountSid(accountSid) || !validAuthToken(authToken)) return { branch: "defect", failure: failure("AUTHENTICATION", "connection credentials are unavailable or invalid") };
79
+ const timestamp = this.now().toISOString().slice(0, 19).replace(/[-:T]/g, "");
80
+ const signature = createHash("md5").update(accountSid + authToken + timestamp).digest("hex").toUpperCase();
81
+ const authorization = Buffer.from(`${accountSid}:${timestamp}`, "utf8").toString("base64");
82
+ const request = {
83
+ url: `${this.baseURL}/2013-12-26/Accounts/${accountSid}/AccountInfo?sig=${signature}`,
84
+ method: "GET",
85
+ headers: { Authorization: authorization, Accept: "application/json", "Content-Type": "application/json;charset=utf-8" },
86
+ timeoutMs: this.timeoutMs,
87
+ maxResponseBytes: this.maxResponseBytes,
88
+ addressPolicy: this.baseURL.startsWith("https://") ? "publicHTTPS" : "privateNetworkHTTP",
89
+ signal: call.context.cancellationSignal
90
+ };
91
+ let response;
92
+ try {
93
+ response = await this.send(request);
94
+ } catch (error) {
95
+ if (error instanceof BodyTooLargeError && error.status !== void 0) {
96
+ if (error.status === 429 || error.status === 408 || error.status >= 500) return statusOutcome(error.status, error.headers ?? {}, this.now());
97
+ return { branch: "invalidResponse", failure: failure("RESPONSE_TOO_LARGE", "Cloopen response exceeded the configured limit") };
98
+ }
99
+ return { retry: true, failure: failure("AVAILABILITY", "Cloopen request failed") };
100
+ }
101
+ if (response.status === 429 || response.status === 408 || response.status >= 500) return statusOutcome(response.status, response.headers, this.now());
102
+ if (response.body.length > this.maxResponseBytes) return { branch: "invalidResponse", failure: failure("RESPONSE_TOO_LARGE", "Cloopen response exceeded the configured limit") };
103
+ return { response };
104
+ }
105
+ };
106
+ var GetBalanceOperation = class {
107
+ /** Bind the provider client. */
108
+ constructor(client) {
109
+ this.client = client;
110
+ }
111
+ client;
112
+ /** Generated Query definition. */
113
+ definition() {
114
+ return GetBalanceDefinition;
115
+ }
116
+ /** Send one signed request and classify its result. */
117
+ async invoke(call, input) {
118
+ if (!input || Object.keys(input).length !== 0) return terminal("defect", "VALIDATION", "balance input must be empty");
119
+ const exchange = await this.client.lookup(call);
120
+ if ("failure" in exchange) return exchange.retry ? newQueryRetry(exchange.failure, exchange.retryAfterMs ?? 0) : newQueryBranch(exchange.branch, emptyBalance(), {}, exchange.failure);
121
+ const response = exchange.response;
122
+ if (response.status !== 200) return terminal("providerRejected", httpFailureKind(response.status), "Cloopen rejected the account lookup");
123
+ let wire;
124
+ try {
125
+ wire = JSON.parse(new TextDecoder().decode(response.body), (_name, value) => isRecord(value) ? Object.fromEntries(Object.entries(value).map(([name, field]) => [name.toLowerCase(), field])) : value);
126
+ } catch {
127
+ return terminal("invalidResponse", "PROTOCOL", "Cloopen returned an invalid account response");
128
+ }
129
+ if (!isRecord(wire)) return terminal("invalidResponse", "PROTOCOL", "Cloopen returned an invalid account response");
130
+ const statusCode = wire.statuscode;
131
+ const account = wire.account;
132
+ if (account != null && !isRecord(account)) return terminal("invalidResponse", "PROTOCOL", "Cloopen returned an invalid account response");
133
+ const balance = account?.balance;
134
+ if (balance != null && typeof balance !== "string") return terminal("invalidResponse", "PROTOCOL", "Cloopen returned an invalid balance");
135
+ if (typeof statusCode !== "string" || !statusCode) return terminal("invalidResponse", "PROTOCOL", "Cloopen returned an invalid account response");
136
+ if (statusCode === "111111") return newQueryRetry(failure("RATE_LIMIT", "Cloopen concurrency limit reached"));
137
+ if (statusCode.startsWith("1110")) return newQueryRetry(failure("AVAILABILITY", "Cloopen reported an internal failure"));
138
+ if (statusCode !== "000000") return terminal("providerRejected", "PROVIDER_REJECTION", "Cloopen rejected the account lookup");
139
+ if (typeof balance !== "string" || balance.length > 64 || !/^(0|[1-9][0-9]*)(\.[0-9]+)?$/.test(balance)) return terminal("invalidResponse", "PROTOCOL", "Cloopen returned an invalid balance");
140
+ return newQueryBranch("fetched", { balance });
141
+ }
142
+ };
143
+ function isRecord(value) {
144
+ return typeof value === "object" && value !== null && !Array.isArray(value);
145
+ }
146
+ function validAccountSid(value) {
147
+ return /^[A-Za-z0-9]{32}$/.test(value);
148
+ }
149
+ function validAuthToken(value) {
150
+ return value.length === 32 && /^[!-~]+$/.test(value);
151
+ }
152
+ function failure(kind, message) {
153
+ return { kind, provider: "cloopen", operation: "getBalance", message };
154
+ }
155
+ function terminal(branch, kind, message) {
156
+ return newQueryBranch(branch, emptyBalance(), {}, failure(kind, message));
157
+ }
158
+ function httpFailureKind(status) {
159
+ return status === 401 || status === 403 ? "AUTHENTICATION" : status === 400 ? "VALIDATION" : "PROVIDER_REJECTION";
160
+ }
161
+ function statusOutcome(status, headers, now) {
162
+ const entry = Object.entries(headers).find(([name]) => name.toLowerCase() === "retry-after")?.[1];
163
+ const retryAfter = Array.isArray(entry) ? entry[0] ?? "" : entry ?? "";
164
+ return { retry: true, retryAfterMs: parseRetryAfter(retryAfter, now), failure: status === 429 ? failure("RATE_LIMIT", "Cloopen rate limit reached") : failure("AVAILABILITY", "Cloopen is temporarily unavailable") };
165
+ }
166
+
167
+ // src/project.ts
168
+ function newProjectConnection2(project, connectionName, options = {}) {
169
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
170
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "cloopen" && entry.connectionName === name);
171
+ if (!selected) throw new TypeError("Cloopen project connection is not configured");
172
+ const fields = z.strictObject({ baseUrl: z.string().optional(), timeout: z.union([z.string(), z.number().int()]).optional(), maxResponseBytes: z.number().int().optional() }).parse(selected.configuration);
173
+ const timeoutMs = typeof fields.timeout === "number" ? Math.ceil(fields.timeout / 1e6) : fields.timeout ? parseDurationMilliseconds(fields.timeout) : void 0;
174
+ const config = {
175
+ ...fields.baseUrl ? { baseUrl: fields.baseUrl } : {},
176
+ ...timeoutMs !== void 0 ? { timeoutMs } : {},
177
+ ...fields.maxResponseBytes !== void 0 ? { maxResponseBytes: fields.maxResponseBytes } : {}
178
+ };
179
+ const credentials = {
180
+ async resolve(_call, signal) {
181
+ const privateFields = await loadedProject.resolveCredential("cloopen", name, signal);
182
+ return decodeCredentials(z.record(z.string(), z.unknown()).parse(privateFields));
183
+ }
184
+ };
185
+ return new CloopenClient(config, credentials, options);
186
+ });
187
+ }
188
+ function parseDurationMilliseconds(value) {
189
+ let remaining = value;
190
+ let milliseconds = 0;
191
+ const units = { ns: 1e-6, us: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
192
+ while (remaining) {
193
+ const part = /^(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/.exec(remaining);
194
+ if (!part) throw new TypeError("Cloopen timeout must be a positive Go duration");
195
+ milliseconds += Number(part[1]) * (units[part[2] ?? ""] ?? NaN);
196
+ remaining = remaining.slice(part[0].length);
197
+ }
198
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) throw new TypeError("Cloopen timeout must resolve to positive whole milliseconds");
199
+ return milliseconds;
200
+ }
201
+ export {
202
+ CloopenClient,
203
+ ConfigSchema,
204
+ Connection,
205
+ ConnectorID,
206
+ CredentialMaterialError,
207
+ GetBalanceBranch,
208
+ GetBalanceBranchDefect,
209
+ GetBalanceBranchFetched,
210
+ GetBalanceBranchInvalidResponse,
211
+ GetBalanceBranchProviderRejected,
212
+ GetBalanceDefinition,
213
+ GetBalanceInputSchema,
214
+ GetBalanceMetadata,
215
+ GetBalanceOperation,
216
+ GetBalanceOutputSchema,
217
+ ProviderID,
218
+ decodeCredentials,
219
+ isCredentialMaterialError,
220
+ newConnection,
221
+ newConnectionWithOperations,
222
+ newGetBalanceStep,
223
+ newProjectConnection2 as newProjectConnection
224
+ };
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, G as GetBalanceInput, a as GetBalanceOutput } from './connection-utPMl6ey.js';
4
+ import 'zod';
5
+
6
+ /** Go zero value for GetBalanceInput in scripted cases. */
7
+ declare const emptyGetBalanceInput: GetBalanceInput;
8
+ /** Go zero value for GetBalanceOutput in scripted cases. */
9
+ declare const emptyGetBalanceOutput: GetBalanceOutput;
10
+ /** Script the fetched branch. */
11
+ declare function getBalanceFetched(value: GetBalanceOutput, failure?: Failure): Case<GetBalanceOutput>;
12
+ /** Script the providerRejected branch. */
13
+ declare function getBalanceProviderRejected(value: GetBalanceOutput, failure?: Failure): Case<GetBalanceOutput>;
14
+ /** Script the invalidResponse branch. */
15
+ declare function getBalanceInvalidResponse(value: GetBalanceOutput, failure?: Failure): Case<GetBalanceOutput>;
16
+ /** Script the defect branch. */
17
+ declare function getBalanceDefect(value: GetBalanceOutput, failure?: Failure): Case<GetBalanceOutput>;
18
+ /** Script a safe retry of getBalance. */
19
+ declare function getBalanceRetry(failure: Failure, retryAfterMs?: number): Case<GetBalanceOutput>;
20
+ /** Manifest scenario sampleBalance for getBalance. */
21
+ declare function getBalanceSampleBalance(): Case<GetBalanceOutput>;
22
+ /** Default getBalance scenario. */
23
+ declare function getBalanceDefault(): Case<GetBalanceOutput>;
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
+ getBalance(): MockQuery<GetBalanceInput, GetBalanceOutput>;
30
+ assertNoFailures(): void;
31
+ }
32
+
33
+ export { GeneratedMock, GeneratedMock as Mock, emptyGetBalanceInput, emptyGetBalanceOutput, getBalanceDefault, getBalanceDefect, getBalanceFetched, getBalanceInvalidResponse, getBalanceProviderRejected, getBalanceRetry, getBalanceSampleBalance };
package/dist/mock.js ADDED
@@ -0,0 +1,66 @@
1
+ import {
2
+ GetBalanceDefinition,
3
+ GetBalanceInputSchema,
4
+ GetBalanceOutputSchema,
5
+ ProviderID,
6
+ newConnectionWithOperations
7
+ } from "./chunk-YQ2YLXXH.js";
8
+
9
+ // src/generated/mock.ts
10
+ import { branchCase, retryCase, newQuery } from "@superdurable/connectors-sdk/connectormock";
11
+ var emptyGetBalanceInput = GetBalanceInputSchema.parse({});
12
+ var emptyGetBalanceOutput = GetBalanceOutputSchema.parse({
13
+ "balance": ""
14
+ });
15
+ function getBalanceFetched(value, failure) {
16
+ return branchCase("fetched", value, failure);
17
+ }
18
+ function getBalanceProviderRejected(value, failure) {
19
+ return branchCase("providerRejected", value, failure);
20
+ }
21
+ function getBalanceInvalidResponse(value, failure) {
22
+ return branchCase("invalidResponse", value, failure);
23
+ }
24
+ function getBalanceDefect(value, failure) {
25
+ return branchCase("defect", value, failure);
26
+ }
27
+ function getBalanceRetry(failure, retryAfterMs = 0) {
28
+ return retryCase(failure, retryAfterMs);
29
+ }
30
+ function getBalanceSampleBalance() {
31
+ const value = GetBalanceOutputSchema.parse({ "balance": "211" });
32
+ return branchCase("fetched", value);
33
+ }
34
+ function getBalanceDefault() {
35
+ return getBalanceSampleBalance();
36
+ }
37
+ var GeneratedMock = class {
38
+ #getBalance;
39
+ #connection;
40
+ constructor(connectionName) {
41
+ this.#getBalance = newQuery(GetBalanceDefinition).default(getBalanceDefault());
42
+ this.#connection = newConnectionWithOperations(this, { provider: ProviderID, name: connectionName });
43
+ }
44
+ connection() {
45
+ return this.#connection;
46
+ }
47
+ getBalance() {
48
+ return this.#getBalance;
49
+ }
50
+ assertNoFailures() {
51
+ this.#getBalance.assertNoFailures();
52
+ }
53
+ };
54
+ export {
55
+ GeneratedMock,
56
+ GeneratedMock as Mock,
57
+ emptyGetBalanceInput,
58
+ emptyGetBalanceOutput,
59
+ getBalanceDefault,
60
+ getBalanceDefect,
61
+ getBalanceFetched,
62
+ getBalanceInvalidResponse,
63
+ getBalanceProviderRejected,
64
+ getBalanceRetry,
65
+ getBalanceSampleBalance
66
+ };
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@superdurable/connector-cloopen",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "license": "MIT",
5
+ "description": "Cloopen main-account balance connector for Dex TypeScript applications",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/superdurable/dex-connectors-library.git",
9
+ "directory": "connectors/cloopen/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": "npm run build && vitest run test/integration/*.integration.test.ts",
41
+ "example:worker": "tsx examples/balance/worker.ts",
42
+ "example:start": "tsx examples/balance/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.45.4",
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
+ }