@superdurable/connector-xiaoetech 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
+ # Xiaoetech 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
+ `@superdurable/connector-xiaoetech` obtains and caches an access token for the active application and store, then reads root goods categories. It returns category IDs, titles, and child availability; credentials and access tokens stay outside Flow input and output.
4
+
5
+ `examples/basic/` runs a Dex Flow, Worker, and Client using relative local imports. `npm run check` replays Go provider scenarios; `npm run test:integration` uses a synthetic provider with real Dex retry and persistence. Live XiaoeTech authorization is unverified.
@@ -0,0 +1,52 @@
1
+ {
2
+ "connectorId": "xiaoetech",
3
+ "releaseTag": "connectors/xiaoetech/go/v0.1.0",
4
+ "package": {
5
+ "ecosystem": "npm",
6
+ "name": "@superdurable/connector-xiaoetech",
7
+ "version": "0.1.0"
8
+ },
9
+ "factories": [
10
+ {
11
+ "name": "newListRootGoodsCategoriesStep",
12
+ "kind": "query",
13
+ "operationId": "listRootGoodsCategories",
14
+ "inputType": "ListRootGoodsCategoriesInput",
15
+ "description": "Read root goods category IDs, titles, and child availability.",
16
+ "fields": {
17
+ "stepType": "stepType",
18
+ "annotations": "annotations",
19
+ "connectionName": "connectionName",
20
+ "resultAttribute": "resultAttribute"
21
+ },
22
+ "branches": [
23
+ {
24
+ "id": "listed",
25
+ "field": "listed",
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": "ListRootGoodsCategoriesInput has no arguments; the operation requests parent_id zero.",
47
+ "properties": {},
48
+ "type": "object"
49
+ }
50
+ }
51
+ ]
52
+ }
@@ -0,0 +1,126 @@
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(["app_id", "client_id", "secret_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["app_id"] != null && !(typeof fields["app_id"] === "string")) throw new CredentialMaterialError("credential app_id has an invalid type");
29
+ if (fields["client_id"] != null && !(typeof fields["client_id"] === "string")) throw new CredentialMaterialError("credential client_id has an invalid type");
30
+ if (fields["secret_key"] != null && !(typeof fields["secret_key"] === "string")) throw new CredentialMaterialError("credential secret_key has an invalid type");
31
+ const credentials = {};
32
+ if (!fields["app_id"]) throw new CredentialMaterialError("credential app_id is required");
33
+ credentials.appId = fields["app_id"] ?? "";
34
+ if (!fields["client_id"]) throw new CredentialMaterialError("credential client_id is required");
35
+ credentials.clientId = fields["client_id"] ?? "";
36
+ if (!fields["secret_key"]) throw new CredentialMaterialError("credential secret_key is required");
37
+ credentials.secretKey = new SecretString(fields["secret_key"] ?? "");
38
+ return credentials;
39
+ }
40
+ var ListRootGoodsCategoriesInputSchema = z.strictObject({});
41
+ var GoodsCategorySchema = z.strictObject({
42
+ "id": z.number().int(),
43
+ "title": z.string(),
44
+ "hasChildren": z.boolean()
45
+ });
46
+ var ListRootGoodsCategoriesOutputSchema = z.strictObject({
47
+ "categories": z.array(GoodsCategorySchema).nullable()
48
+ });
49
+
50
+ // src/generated/definitions.ts
51
+ var ConnectorID = "xiaoetech";
52
+ var ProviderID = "xiaoetech";
53
+ var ListRootGoodsCategoriesBranch = {
54
+ Listed: "listed",
55
+ ProviderRejected: "providerRejected",
56
+ InvalidResponse: "invalidResponse",
57
+ Defect: "defect"
58
+ };
59
+ var ListRootGoodsCategoriesBranchListed = ListRootGoodsCategoriesBranch.Listed;
60
+ var ListRootGoodsCategoriesBranchProviderRejected = ListRootGoodsCategoriesBranch.ProviderRejected;
61
+ var ListRootGoodsCategoriesBranchInvalidResponse = ListRootGoodsCategoriesBranch.InvalidResponse;
62
+ var ListRootGoodsCategoriesBranchDefect = ListRootGoodsCategoriesBranch.Defect;
63
+ var ListRootGoodsCategoriesDefinition = {
64
+ operation: { connectorId: ConnectorID, operationId: "listRootGoodsCategories" },
65
+ branches: [
66
+ { id: "listed", description: "XiaoeTech returned the root goods categories." },
67
+ { id: "providerRejected", description: "XiaoeTech rejected credentials, permissions, or the request.", optional: true },
68
+ { id: "invalidResponse", description: "XiaoeTech returned malformed or oversized data.", optional: true },
69
+ { id: "defect", description: "Local credentials or connection configuration are invalid.", optional: true }
70
+ ],
71
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async", executeRetry: { initialIntervalMs: 2e3, backoffCoefficient: 2, maximumIntervalMs: 3e4, maximumAttempts: 3, totalDurationMs: 36e5 } }
72
+ };
73
+ var ListRootGoodsCategoriesMetadata = { kind: "query", idempotency: "none", authorization: "required" };
74
+
75
+ // src/generated/connection.ts
76
+ import { ConnectionRefSchema } from "@superdurable/connectors-sdk";
77
+ var Connection = class {
78
+ /** Stable provider and connection name. */
79
+ reference;
80
+ /** Bound provider operations. */
81
+ operations;
82
+ /** Validate a reference and bind operations. */
83
+ constructor(reference, operations) {
84
+ this.reference = ConnectionRefSchema.parse(reference);
85
+ if (this.reference.provider !== ProviderID) throw new TypeError("connection provider differs from the manifest");
86
+ if (!operations) throw new TypeError("connector operations are required");
87
+ this.operations = operations;
88
+ }
89
+ };
90
+ function newConnection(client, reference) {
91
+ if (!client) throw new TypeError("connector client is required");
92
+ return new Connection(reference, client);
93
+ }
94
+ function newConnectionWithOperations(operations, reference) {
95
+ return new Connection(reference, operations);
96
+ }
97
+ function newProjectConnection(project, connectionName, createClient) {
98
+ if (!project) throw new TypeError("loaded project is required");
99
+ const reference = ConnectionRefSchema.parse({ provider: ProviderID, name: connectionName });
100
+ const selected = project.configuration.connections.find((entry) => entry.connectorId === ConnectorID && entry.connectionName === connectionName);
101
+ if (!selected || selected.provider !== ProviderID) throw new TypeError("project connection is not configured");
102
+ return newConnection(createClient(project, connectionName), reference);
103
+ }
104
+
105
+ export {
106
+ ConfigSchema,
107
+ CredentialMaterialError,
108
+ isCredentialMaterialError,
109
+ decodeCredentials,
110
+ ListRootGoodsCategoriesInputSchema,
111
+ GoodsCategorySchema,
112
+ ListRootGoodsCategoriesOutputSchema,
113
+ ConnectorID,
114
+ ProviderID,
115
+ ListRootGoodsCategoriesBranch,
116
+ ListRootGoodsCategoriesBranchListed,
117
+ ListRootGoodsCategoriesBranchProviderRejected,
118
+ ListRootGoodsCategoriesBranchInvalidResponse,
119
+ ListRootGoodsCategoriesBranchDefect,
120
+ ListRootGoodsCategoriesDefinition,
121
+ ListRootGoodsCategoriesMetadata,
122
+ Connection,
123
+ newConnection,
124
+ newConnectionWithOperations,
125
+ newProjectConnection
126
+ };
@@ -0,0 +1,91 @@
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 XiaoeTech Open API without a path. Leave blank for the displayed public endpoint; override only for a trusted test server or approved proxy. */
7
+ baseUrl?: string;
8
+ /** Maximum time for one token or category request as a positive Go duration such as 5s or 1m. Leave blank for the displayed default; raise only for a slow approved proxy. Runtime value in milliseconds. */
9
+ timeoutMs?: number;
10
+ /** Maximum provider response size in bytes as a positive integer. Leave blank for the displayed default; raise only when a legitimate category list 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
+ /** Store business App ID from https://admin.cloud.xiaoe-tech.com/ > Cloud Service Console > Application Information. Copy the opaque app_id for the authorized store. This is not secret. Blank prevents token exchange. */
22
+ appId: string;
23
+ /** Application Client ID from https://admin.cloud.xiaoe-tech.com/ > Cloud Service Console > Application Information. Copy the opaque client_id for the authorized application. This is not secret. Blank prevents token exchange. */
24
+ clientId: string;
25
+ /** Secret key from https://admin.cloud.xiaoe-tech.com/ > Cloud Service Console > Application Information. Copy the opaque secret_key and keep it private; Dex stores it only as a credential. Blank prevents token exchange. */
26
+ secretKey: SecretString;
27
+ }
28
+ /** Stored credential material that fails the connector credential checks, so no retry can succeed. */
29
+ declare class CredentialMaterialError extends TypeError {
30
+ constructor(message: string);
31
+ }
32
+ /** Report malformed stored credential material, also behind the SDK provider's decoding TypeError. */
33
+ declare function isCredentialMaterialError(error: unknown): boolean;
34
+ /** Decode private credential fields for the connector. */
35
+ declare function decodeCredentials(value: unknown): Credentials;
36
+ /** Host-owned source of private connector credentials. */
37
+ type CredentialSource = CredentialProvider<Credentials>;
38
+ /** ListRootGoodsCategoriesInput has no arguments; the operation requests parent_id zero. */
39
+ interface ListRootGoodsCategoriesInput {
40
+ }
41
+ /** GoodsCategory is a root category without nested or private provider metadata. */
42
+ interface GoodsCategory {
43
+ /** ID is the provider's category identifier. */
44
+ "id": number;
45
+ /** Title is the provider's category title. */
46
+ "title": string;
47
+ /** HasChildren reports whether child categories exist. */
48
+ "hasChildren": boolean;
49
+ }
50
+ /** ListRootGoodsCategoriesOutput holds the store's root goods categories. */
51
+ interface ListRootGoodsCategoriesOutput {
52
+ /** Categories contains only top-level goods categories. */
53
+ "categories": Array<GoodsCategory> | null;
54
+ }
55
+ /** Runtime validator for ListRootGoodsCategoriesInput. */
56
+ declare const ListRootGoodsCategoriesInputSchema: z.ZodObject<{}, z.core.$strict>;
57
+ /** Runtime validator for GoodsCategory. */
58
+ declare const GoodsCategorySchema: z.ZodObject<{
59
+ id: z.ZodNumber;
60
+ title: z.ZodString;
61
+ hasChildren: z.ZodBoolean;
62
+ }, z.core.$strict>;
63
+ /** Runtime validator for ListRootGoodsCategoriesOutput. */
64
+ declare const ListRootGoodsCategoriesOutputSchema: z.ZodObject<{
65
+ categories: z.ZodNullable<z.ZodArray<z.ZodObject<{
66
+ id: z.ZodNumber;
67
+ title: z.ZodString;
68
+ hasChildren: z.ZodBoolean;
69
+ }, z.core.$strict>>>;
70
+ }, z.core.$strict>;
71
+
72
+ /** Typed operations supplied by a client or mock. */
73
+ interface Operations {
74
+ /** Invoke listRootGoodsCategories through this connection. */
75
+ listRootGoodsCategories(): Query<ListRootGoodsCategoriesInput, ListRootGoodsCategoriesOutput>;
76
+ }
77
+ /** Named connector connection kept outside Flow state. */
78
+ declare class Connection<BoundOperations = Operations> {
79
+ /** Stable provider and connection name. */
80
+ readonly reference: ConnectionRef;
81
+ /** Bound provider operations. */
82
+ readonly operations: BoundOperations;
83
+ /** Validate a reference and bind operations. */
84
+ constructor(reference: ConnectionRef, operations: BoundOperations);
85
+ }
86
+ /** Bind a client to a named connection. */
87
+ declare function newConnection(client: Operations, reference: ConnectionRef): Connection;
88
+ /** Bind scripted operations to a named connection. */
89
+ declare function newConnectionWithOperations(operations: Operations, reference: ConnectionRef): Connection;
90
+
91
+ export { Connection as C, type GoodsCategory as G, type ListRootGoodsCategoriesInput as L, type Operations as O, type ListRootGoodsCategoriesOutput as a, type Config as b, type Credentials as c, ConfigSchema as d, CredentialMaterialError as e, type CredentialSource as f, GoodsCategorySchema as g, ListRootGoodsCategoriesInputSchema as h, ListRootGoodsCategoriesOutputSchema as i, decodeCredentials as j, isCredentialMaterialError as k, newConnectionWithOperations as l, newConnection as n };
@@ -0,0 +1,106 @@
1
+ import { L as ListRootGoodsCategoriesInput, a as ListRootGoodsCategoriesOutput, C as Connection, O as Operations, b as Config, c as Credentials } from './connection-CeIVj9Pm.js';
2
+ export { d as ConfigSchema, e as CredentialMaterialError, f as CredentialSource, G as GoodsCategory, g as GoodsCategorySchema, h as ListRootGoodsCategoriesInputSchema, i as ListRootGoodsCategoriesOutputSchema, j as decodeCredentials, k as isCredentialMaterialError, n as newConnection, l as newConnectionWithOperations } from './connection-CeIVj9Pm.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 = "xiaoetech";
11
+ /** Provider identity for named connections. */
12
+ declare const ProviderID = "xiaoetech";
13
+ /** Branch IDs for listRootGoodsCategories. */
14
+ declare const ListRootGoodsCategoriesBranch: {
15
+ readonly Listed: "listed";
16
+ readonly ProviderRejected: "providerRejected";
17
+ readonly InvalidResponse: "invalidResponse";
18
+ readonly Defect: "defect";
19
+ };
20
+ /** XiaoeTech returned the root goods categories. */
21
+ declare const ListRootGoodsCategoriesBranchListed: "listed";
22
+ /** XiaoeTech rejected credentials, permissions, or the request. */
23
+ declare const ListRootGoodsCategoriesBranchProviderRejected: "providerRejected";
24
+ /** XiaoeTech returned malformed or oversized data. */
25
+ declare const ListRootGoodsCategoriesBranchInvalidResponse: "invalidResponse";
26
+ /** Local credentials or connection configuration are invalid. */
27
+ declare const ListRootGoodsCategoriesBranchDefect: "defect";
28
+ /** Manifest definition for listRootGoodsCategories. */
29
+ declare const ListRootGoodsCategoriesDefinition: QueryDefinition;
30
+ /** Manifest metadata for listRootGoodsCategories. */
31
+ declare const ListRootGoodsCategoriesMetadata: {
32
+ readonly kind: "query";
33
+ readonly idempotency: "none";
34
+ readonly authorization: "required";
35
+ };
36
+
37
+ /** Configuration for the listRootGoodsCategories connector Step. */
38
+ interface ListRootGoodsCategoriesStepConfig<StepInput, OperationInput = ListRootGoodsCategoriesInput, OperationOutput = ListRootGoodsCategoriesOutput> extends Omit<QueryStepConfig<StepInput, OperationInput, OperationOutput>, 'operation' | 'connection' | 'branches'> {
39
+ /** Named connection supplying this operation. */
40
+ connection: Connection<{
41
+ listRootGoodsCategories(): Query<OperationInput, OperationOutput>;
42
+ }>;
43
+ /** Name matching the bound connection. */
44
+ connectionName: string;
45
+ /** XiaoeTech returned the root goods categories. */
46
+ listed: StepTarget<QueryResult<OperationOutput>>;
47
+ /** XiaoeTech rejected credentials, permissions, or the request. */
48
+ providerRejected?: StepTarget<QueryResult<OperationOutput>>;
49
+ /** XiaoeTech returned malformed or oversized data. */
50
+ invalidResponse?: StepTarget<QueryResult<OperationOutput>>;
51
+ /** Local credentials or connection configuration are invalid. */
52
+ defect?: StepTarget<QueryResult<OperationOutput>>;
53
+ }
54
+ /** Build the listRootGoodsCategories Step from a named connection. */
55
+ declare function newListRootGoodsCategoriesStep<StepInput, OperationInput = ListRootGoodsCategoriesInput, OperationOutput = ListRootGoodsCategoriesOutput>(configuration: ListRootGoodsCategoriesStepConfig<StepInput, OperationInput, OperationOutput>): QueryStep<StepInput, OperationInput, OperationOutput>;
56
+
57
+ /** Open one named Xiaoetech connection from Dex project configuration. */
58
+ declare function newProjectConnection(project: LoadedProject, connectionName: string): Connection<Operations>;
59
+
60
+ type Exchange = {
61
+ response?: ProviderResponse;
62
+ error?: 'transport' | 'tooLarge';
63
+ retryAfterMs: number;
64
+ };
65
+ /** Optional provider transport and clock for deterministic verification. */
66
+ interface XiaoetechClientOptions {
67
+ /** Send one provider request. */ send?: (request: ProviderRequest) => Promise<ProviderResponse>;
68
+ /** Supply current time for token expiry. */ now?: () => Date;
69
+ }
70
+ /** Cache an access token for the active XiaoeTech credential triple. */
71
+ declare class XiaoetechClient {
72
+ private readonly credentials;
73
+ readonly baseUrl: string;
74
+ private readonly timeoutMs;
75
+ private readonly maxResponseBytes;
76
+ private readonly send;
77
+ private readonly now;
78
+ private token;
79
+ private tokenFingerprint;
80
+ private tokenExpiry;
81
+ /** Validate endpoint and bounds without contacting XiaoeTech. */
82
+ constructor(config: Config, credentials: CredentialProvider<Credentials>, options?: XiaoetechClientOptions);
83
+ /** Bind the root category Query. */ listRootGoodsCategories(): ListRootGoodsCategoriesOperation;
84
+ /** Resolve current credentials before dispatch. */
85
+ resolve(call: Call): Promise<{
86
+ appId: string;
87
+ clientId: string;
88
+ secretKey: string;
89
+ } | null>;
90
+ /** Obtain a token for this exact credential triple. */
91
+ accessToken(call: Call, appId: string, clientId: string, secretKey: string): Promise<string | QueryAttempt<ListRootGoodsCategoriesOutput>>;
92
+ /** Send one bounded token or category request. */
93
+ request(call: Call, url: string, method: 'GET' | 'POST', body?: Uint8Array): Promise<Exchange>;
94
+ /** Read top-level goods categories using a cached token. */
95
+ categories(call: Call, token: string): Promise<QueryAttempt<ListRootGoodsCategoriesOutput>>;
96
+ }
97
+ /** Read only top-level goods categories from the authorized store. */
98
+ declare class ListRootGoodsCategoriesOperation implements Query<ListRootGoodsCategoriesInput, ListRootGoodsCategoriesOutput> {
99
+ private readonly client;
100
+ /** Bind one validated client. */ constructor(client: XiaoetechClient);
101
+ /** Return the generated Query contract. */ definition(): QueryDefinition;
102
+ /** Obtain a token and read root goods categories. */
103
+ invoke(call: Call): Promise<QueryAttempt<ListRootGoodsCategoriesOutput>>;
104
+ }
105
+
106
+ export { Config, Connection, ConnectorID, Credentials, ListRootGoodsCategoriesBranch, ListRootGoodsCategoriesBranchDefect, ListRootGoodsCategoriesBranchInvalidResponse, ListRootGoodsCategoriesBranchListed, ListRootGoodsCategoriesBranchProviderRejected, ListRootGoodsCategoriesDefinition, ListRootGoodsCategoriesInput, ListRootGoodsCategoriesMetadata, ListRootGoodsCategoriesOutput, type ListRootGoodsCategoriesStepConfig, ProviderID, XiaoetechClient, type XiaoetechClientOptions, newListRootGoodsCategoriesStep, newProjectConnection };
package/dist/index.js ADDED
@@ -0,0 +1,242 @@
1
+ import {
2
+ ConfigSchema,
3
+ Connection,
4
+ ConnectorID,
5
+ CredentialMaterialError,
6
+ GoodsCategorySchema,
7
+ ListRootGoodsCategoriesBranch,
8
+ ListRootGoodsCategoriesBranchDefect,
9
+ ListRootGoodsCategoriesBranchInvalidResponse,
10
+ ListRootGoodsCategoriesBranchListed,
11
+ ListRootGoodsCategoriesBranchProviderRejected,
12
+ ListRootGoodsCategoriesDefinition,
13
+ ListRootGoodsCategoriesInputSchema,
14
+ ListRootGoodsCategoriesMetadata,
15
+ ListRootGoodsCategoriesOutputSchema,
16
+ ProviderID,
17
+ decodeCredentials,
18
+ isCredentialMaterialError,
19
+ newConnection,
20
+ newConnectionWithOperations,
21
+ newProjectConnection
22
+ } from "./chunk-JAZCYZ62.js";
23
+
24
+ // src/generated/steps.ts
25
+ import { goToBranch, newQueryStep } from "@superdurable/connectors-sdk";
26
+ function newListRootGoodsCategoriesStep(configuration) {
27
+ const { connection, connectionName, listed, 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.listRootGoodsCategories(), connection: connection.reference, branches: [
30
+ goToBranch("listed", listed),
31
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
32
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
33
+ ...defect ? [goToBranch("defect", defect)] : []
34
+ ] });
35
+ }
36
+
37
+ // src/client.ts
38
+ import { createHash } from "crypto";
39
+ import { SecretString, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
40
+ import { BodyTooLargeError, parseRetryAfter, sendProviderRequest } from "@superdurable/connectors-sdk/providerhttp";
41
+ var empty = { categories: [] };
42
+ var XiaoetechClient = class {
43
+ /** Validate endpoint and bounds without contacting XiaoeTech. */
44
+ constructor(config, credentials, options = {}) {
45
+ this.credentials = credentials;
46
+ if (!config || !credentials) throw new TypeError("XiaoeTech configuration and credential source are required");
47
+ this.baseUrl = (config.baseUrl || "https://api.xiaoe-tech.com").replace(/\/$/, "");
48
+ const endpoint = new URL(this.baseUrl);
49
+ if (endpoint.protocol !== "https:" || endpoint.pathname !== "/" || endpoint.search || endpoint.hash || endpoint.username || endpoint.password) throw new TypeError("XiaoeTech endpoint must be an HTTPS origin");
50
+ this.timeoutMs = config.timeoutMs ?? 1e4;
51
+ this.maxResponseBytes = config.maxResponseBytes ?? 4194304;
52
+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0 || this.maxResponseBytes > 16 << 20) throw new TypeError("XiaoeTech request bounds are invalid");
53
+ this.send = options.send ?? sendProviderRequest;
54
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
55
+ }
56
+ credentials;
57
+ baseUrl;
58
+ timeoutMs;
59
+ maxResponseBytes;
60
+ send;
61
+ now;
62
+ token = "";
63
+ tokenFingerprint = "";
64
+ tokenExpiry = 0;
65
+ /** Bind the root category Query. */
66
+ listRootGoodsCategories() {
67
+ return new ListRootGoodsCategoriesOperation(this);
68
+ }
69
+ /** Resolve current credentials before dispatch. */
70
+ async resolve(call) {
71
+ try {
72
+ const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
73
+ const appId = credentials.appId;
74
+ const clientId = credentials.clientId;
75
+ const secretKey = credentials.secretKey instanceof SecretString ? credentials.secretKey.reveal() : "";
76
+ return [appId, clientId, secretKey].every(validSecret) ? { appId, clientId, secretKey } : null;
77
+ } catch {
78
+ return null;
79
+ }
80
+ }
81
+ /** Obtain a token for this exact credential triple. */
82
+ async accessToken(call, appId, clientId, secretKey) {
83
+ const fingerprint = createHash("sha256").update(`${appId}\0${clientId}\0${secretKey}`).digest("hex");
84
+ if (this.token && this.tokenFingerprint === fingerprint && this.tokenExpiry - this.now().getTime() > 3e5) return this.token;
85
+ const query = new URLSearchParams({ app_id: appId, client_id: clientId, secret_key: secretKey, grant_type: "client_credential" });
86
+ const exchange = await this.request(call, `${this.baseUrl}/token?${query}`, "GET");
87
+ const issue = classify(exchange, true);
88
+ if (issue) return issue;
89
+ const data = decode(exchange.response?.body);
90
+ if (!isRecord(data) || typeof data.code !== "number" || !Number.isInteger(data.code)) return branch("invalidResponse", "PROTOCOL");
91
+ if (data.code !== 0) return providerCode(data.code, false);
92
+ if (!isRecord(data.data) || typeof data.data.access_token !== "string" || !validSecret(data.data.access_token) || typeof data.data.expires_in !== "number" || !Number.isInteger(data.data.expires_in) || data.data.expires_in < 600 || data.data.expires_in > 86400) return branch("invalidResponse", "PROTOCOL");
93
+ this.token = data.data.access_token;
94
+ this.tokenFingerprint = fingerprint;
95
+ this.tokenExpiry = this.now().getTime() + data.data.expires_in * 1e3;
96
+ return this.token;
97
+ }
98
+ /** Send one bounded token or category request. */
99
+ async request(call, url, method, body) {
100
+ try {
101
+ const response = await this.send({ url, method, headers: method === "GET" ? { Accept: "application/json" } : { Accept: "application/json", "Content-Type": "application/json" }, body, timeoutMs: this.timeoutMs, maxResponseBytes: this.maxResponseBytes, addressPolicy: "publicHTTPS", signal: call.context.cancellationSignal });
102
+ const retryAfter = Object.entries(response.headers).find(([name]) => name.toLowerCase() === "retry-after")?.[1];
103
+ return { response, error: response.body.length > this.maxResponseBytes ? "tooLarge" : void 0, retryAfterMs: parseRetryAfter(Array.isArray(retryAfter) ? retryAfter[0] ?? "" : retryAfter ?? "") };
104
+ } catch (error) {
105
+ if (error instanceof BodyTooLargeError && error.status !== void 0) return { response: { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() }, error: "tooLarge", retryAfterMs: 0 };
106
+ return { error: "transport", retryAfterMs: 0 };
107
+ }
108
+ }
109
+ /** Read top-level goods categories using a cached token. */
110
+ async categories(call, token) {
111
+ const body = Buffer.from(JSON.stringify({ access_token: token, parent_id: 0 }));
112
+ const exchange = await this.request(call, `${this.baseUrl}/xe.goods.category.list/2.0.0`, "POST", body);
113
+ const issue = classify(exchange, false);
114
+ if (issue) return issue;
115
+ const data = decode(exchange.response?.body);
116
+ if (!isRecord(data) || typeof data.code !== "number" || !Number.isInteger(data.code)) return branch("invalidResponse", "PROTOCOL");
117
+ if (data.code !== 0) {
118
+ if (data.code === 2008) this.token = "";
119
+ return providerCode(data.code, true);
120
+ }
121
+ if (!Array.isArray(data.data) || data.data.length > 1e3) return branch("invalidResponse", "PROTOCOL");
122
+ const categories = [];
123
+ for (const item of data.data) {
124
+ if (!isRecord(item) || typeof item.id !== "number" || !Number.isSafeInteger(item.id) || item.id <= 0 || typeof item.title !== "string" || !item.title.trim() || item.title.length > 512 || item.has_children !== 0 && item.has_children !== 1 || item.parent_id !== 0) return branch("invalidResponse", "PROTOCOL");
125
+ categories.push({ id: item.id, title: item.title, hasChildren: item.has_children === 1 });
126
+ }
127
+ return newQueryBranch("listed", { categories });
128
+ }
129
+ };
130
+ var ListRootGoodsCategoriesOperation = class {
131
+ /** Bind one validated client. */
132
+ constructor(client) {
133
+ this.client = client;
134
+ }
135
+ client;
136
+ /** Return the generated Query contract. */
137
+ definition() {
138
+ return ListRootGoodsCategoriesDefinition;
139
+ }
140
+ /** Obtain a token and read root goods categories. */
141
+ async invoke(call) {
142
+ const credentials = await this.client.resolve(call);
143
+ if (!credentials) return branch("defect", "AUTHENTICATION");
144
+ const token = await this.client.accessToken(call, credentials.appId, credentials.clientId, credentials.secretKey);
145
+ return typeof token === "string" ? this.client.categories(call, token) : token;
146
+ }
147
+ };
148
+ function validSecret(value) {
149
+ return typeof value === "string" && Boolean(value) && value.length <= 512 && /^[!-~]+$/.test(value);
150
+ }
151
+ function decode(body) {
152
+ try {
153
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(body));
154
+ } catch {
155
+ return null;
156
+ }
157
+ }
158
+ function isRecord(value) {
159
+ return typeof value === "object" && value !== null && !Array.isArray(value);
160
+ }
161
+ function classify(exchange, isToken) {
162
+ if (exchange.error === "transport" || !exchange.response) return retry("AVAILABILITY");
163
+ const { status } = exchange.response;
164
+ if (status === 429) return retry("RATE_LIMIT", exchange.retryAfterMs);
165
+ if (status === 408 || status >= 500) return retry("AVAILABILITY", isToken ? 0 : exchange.retryAfterMs);
166
+ if (exchange.error === "tooLarge") return branch("invalidResponse", "RESPONSE_TOO_LARGE");
167
+ if (status !== 200) return branch("providerRejected", isToken ? "AUTHENTICATION" : status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : "PROVIDER_REJECTION");
168
+ return null;
169
+ }
170
+ function providerCode(code, isCategory) {
171
+ if (code === 1001) return retry("AVAILABILITY");
172
+ if (code === 1002) return branch("invalidResponse", "PROTOCOL");
173
+ if (code === 2053 || code === 2054) return retry("RATE_LIMIT");
174
+ if (code === 2008 && isCategory) return retry("AUTHENTICATION");
175
+ if ([2001, 2002, 2003, 2004, 2005, 2006, 2008, 2020].includes(code)) return branch("providerRejected", "AUTHENTICATION");
176
+ if (code === 2017 || code === 2051) return branch("providerRejected", "AUTHORIZATION");
177
+ return branch("providerRejected", "PROVIDER_REJECTION");
178
+ }
179
+ function failure(kind) {
180
+ return { provider: "xiaoetech", operation: "listRootGoodsCategories", kind, message: "XiaoeTech category request failed" };
181
+ }
182
+ function branch(name, kind) {
183
+ return newQueryBranch(name, empty, {}, failure(kind));
184
+ }
185
+ function retry(kind, delay = 0) {
186
+ return newQueryRetry(failure(kind), delay);
187
+ }
188
+
189
+ // src/project.ts
190
+ function newProjectConnection2(project, connectionName) {
191
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
192
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "xiaoetech" && entry.connectionName === name);
193
+ if (!selected) throw new TypeError("Xiaoetech project connection is not configured");
194
+ const fields = selected.configuration;
195
+ const config = ConfigSchema.parse({ ...fields, ...fields.timeout !== void 0 ? { timeoutMs: parseDurationMilliseconds(fields.timeout) } : {} });
196
+ const credentials = {
197
+ async resolve(_call, signal) {
198
+ return decodeCredentials(await loadedProject.resolveCredential("xiaoetech", name, signal));
199
+ }
200
+ };
201
+ return new XiaoetechClient(config, credentials);
202
+ });
203
+ }
204
+ function parseDurationMilliseconds(value) {
205
+ if (typeof value === "number") return Math.ceil(value / 1e6);
206
+ if (typeof value !== "string") throw new TypeError("timeout must be a duration");
207
+ let remaining = value;
208
+ let milliseconds = 0;
209
+ const units = { ns: 1e-6, us: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
210
+ while (remaining) {
211
+ const part = /^(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/.exec(remaining);
212
+ if (!part) throw new TypeError("timeout must be a positive Go duration");
213
+ milliseconds += Number(part[1]) * (units[part[2] ?? ""] ?? NaN);
214
+ remaining = remaining.slice(part[0].length);
215
+ }
216
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) throw new TypeError("timeout must resolve to positive whole milliseconds");
217
+ return milliseconds;
218
+ }
219
+ export {
220
+ ConfigSchema,
221
+ Connection,
222
+ ConnectorID,
223
+ CredentialMaterialError,
224
+ GoodsCategorySchema,
225
+ ListRootGoodsCategoriesBranch,
226
+ ListRootGoodsCategoriesBranchDefect,
227
+ ListRootGoodsCategoriesBranchInvalidResponse,
228
+ ListRootGoodsCategoriesBranchListed,
229
+ ListRootGoodsCategoriesBranchProviderRejected,
230
+ ListRootGoodsCategoriesDefinition,
231
+ ListRootGoodsCategoriesInputSchema,
232
+ ListRootGoodsCategoriesMetadata,
233
+ ListRootGoodsCategoriesOutputSchema,
234
+ ProviderID,
235
+ XiaoetechClient,
236
+ decodeCredentials,
237
+ isCredentialMaterialError,
238
+ newConnection,
239
+ newConnectionWithOperations,
240
+ newListRootGoodsCategoriesStep,
241
+ newProjectConnection2 as newProjectConnection
242
+ };
package/dist/mock.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { MockQuery, Case } from '@superdurable/connectors-sdk/connectormock';
2
+ import { Failure } from '@superdurable/connectors-sdk';
3
+ import { O as Operations, C as Connection, L as ListRootGoodsCategoriesInput, a as ListRootGoodsCategoriesOutput, G as GoodsCategory } from './connection-CeIVj9Pm.js';
4
+ import 'zod';
5
+
6
+ /** Go zero value for ListRootGoodsCategoriesInput in scripted cases. */
7
+ declare const emptyListRootGoodsCategoriesInput: ListRootGoodsCategoriesInput;
8
+ /** Go zero value for GoodsCategory in scripted cases. */
9
+ declare const emptyGoodsCategory: GoodsCategory;
10
+ /** Go zero value for ListRootGoodsCategoriesOutput in scripted cases. */
11
+ declare const emptyListRootGoodsCategoriesOutput: ListRootGoodsCategoriesOutput;
12
+ /** Script the listed branch. */
13
+ declare function listRootGoodsCategoriesListed(value: ListRootGoodsCategoriesOutput, failure?: Failure): Case<ListRootGoodsCategoriesOutput>;
14
+ /** Script the providerRejected branch. */
15
+ declare function listRootGoodsCategoriesProviderRejected(value: ListRootGoodsCategoriesOutput, failure?: Failure): Case<ListRootGoodsCategoriesOutput>;
16
+ /** Script the invalidResponse branch. */
17
+ declare function listRootGoodsCategoriesInvalidResponse(value: ListRootGoodsCategoriesOutput, failure?: Failure): Case<ListRootGoodsCategoriesOutput>;
18
+ /** Script the defect branch. */
19
+ declare function listRootGoodsCategoriesDefect(value: ListRootGoodsCategoriesOutput, failure?: Failure): Case<ListRootGoodsCategoriesOutput>;
20
+ /** Script a safe retry of listRootGoodsCategories. */
21
+ declare function listRootGoodsCategoriesRetry(failure: Failure, retryAfterMs?: number): Case<ListRootGoodsCategoriesOutput>;
22
+ /** Manifest scenario sampleRootCategories for listRootGoodsCategories. */
23
+ declare function listRootGoodsCategoriesSampleRootCategories(): Case<ListRootGoodsCategoriesOutput>;
24
+ /** Default listRootGoodsCategories scenario. */
25
+ declare function listRootGoodsCategoriesDefault(): Case<ListRootGoodsCategoriesOutput>;
26
+ /** Scripted operations and manifest defaults for this connector. */
27
+ declare class GeneratedMock implements Operations {
28
+ #private;
29
+ constructor(connectionName: string);
30
+ connection(): Connection;
31
+ listRootGoodsCategories(): MockQuery<ListRootGoodsCategoriesInput, ListRootGoodsCategoriesOutput>;
32
+ assertNoFailures(): void;
33
+ }
34
+
35
+ export { GeneratedMock, emptyGoodsCategory, emptyListRootGoodsCategoriesInput, emptyListRootGoodsCategoriesOutput, listRootGoodsCategoriesDefault, listRootGoodsCategoriesDefect, listRootGoodsCategoriesInvalidResponse, listRootGoodsCategoriesListed, listRootGoodsCategoriesProviderRejected, listRootGoodsCategoriesRetry, listRootGoodsCategoriesSampleRootCategories };
package/dist/mock.js ADDED
@@ -0,0 +1,72 @@
1
+ import {
2
+ GoodsCategorySchema,
3
+ ListRootGoodsCategoriesDefinition,
4
+ ListRootGoodsCategoriesInputSchema,
5
+ ListRootGoodsCategoriesOutputSchema,
6
+ ProviderID,
7
+ newConnectionWithOperations
8
+ } from "./chunk-JAZCYZ62.js";
9
+
10
+ // src/generated/mock.ts
11
+ import { branchCase, retryCase, newQuery } from "@superdurable/connectors-sdk/connectormock";
12
+ var emptyListRootGoodsCategoriesInput = ListRootGoodsCategoriesInputSchema.parse({});
13
+ var emptyGoodsCategory = GoodsCategorySchema.parse({
14
+ "id": 0,
15
+ "title": "",
16
+ "hasChildren": false
17
+ });
18
+ var emptyListRootGoodsCategoriesOutput = ListRootGoodsCategoriesOutputSchema.parse({
19
+ "categories": []
20
+ });
21
+ function listRootGoodsCategoriesListed(value, failure) {
22
+ return branchCase("listed", value, failure);
23
+ }
24
+ function listRootGoodsCategoriesProviderRejected(value, failure) {
25
+ return branchCase("providerRejected", value, failure);
26
+ }
27
+ function listRootGoodsCategoriesInvalidResponse(value, failure) {
28
+ return branchCase("invalidResponse", value, failure);
29
+ }
30
+ function listRootGoodsCategoriesDefect(value, failure) {
31
+ return branchCase("defect", value, failure);
32
+ }
33
+ function listRootGoodsCategoriesRetry(failure, retryAfterMs = 0) {
34
+ return retryCase(failure, retryAfterMs);
35
+ }
36
+ function listRootGoodsCategoriesSampleRootCategories() {
37
+ const value = ListRootGoodsCategoriesOutputSchema.parse({ "categories": [{ "hasChildren": true, "id": 16510, "title": "Sample food" }, { "hasChildren": false, "id": 18237, "title": "Sample beauty" }] });
38
+ return branchCase("listed", value);
39
+ }
40
+ function listRootGoodsCategoriesDefault() {
41
+ return listRootGoodsCategoriesSampleRootCategories();
42
+ }
43
+ var GeneratedMock = class {
44
+ #listRootGoodsCategories;
45
+ #connection;
46
+ constructor(connectionName) {
47
+ this.#listRootGoodsCategories = newQuery(ListRootGoodsCategoriesDefinition).default(listRootGoodsCategoriesDefault());
48
+ this.#connection = newConnectionWithOperations(this, { provider: ProviderID, name: connectionName });
49
+ }
50
+ connection() {
51
+ return this.#connection;
52
+ }
53
+ listRootGoodsCategories() {
54
+ return this.#listRootGoodsCategories;
55
+ }
56
+ assertNoFailures() {
57
+ this.#listRootGoodsCategories.assertNoFailures();
58
+ }
59
+ };
60
+ export {
61
+ GeneratedMock,
62
+ emptyGoodsCategory,
63
+ emptyListRootGoodsCategoriesInput,
64
+ emptyListRootGoodsCategoriesOutput,
65
+ listRootGoodsCategoriesDefault,
66
+ listRootGoodsCategoriesDefect,
67
+ listRootGoodsCategoriesInvalidResponse,
68
+ listRootGoodsCategoriesListed,
69
+ listRootGoodsCategoriesProviderRejected,
70
+ listRootGoodsCategoriesRetry,
71
+ listRootGoodsCategoriesSampleRootCategories
72
+ };
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@superdurable/connector-xiaoetech",
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": "xiaoetech connector for Dex TypeScript applications",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/superdurable/dex-connectors-library.git",
9
+ "directory": "connectors/xiaoetech/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
+ }