@superdurable/connector-easyapi 0.0.0-stage → 0.2.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,9 @@
1
- # Temporary Holding Version
1
+ # EasyAPI E-Invoice 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-easyapi` implements the read-only `queryShop` Query for one authorized company's invoicing service configuration. Its result includes only `shopId`, `name`, `apiState`, and `endTime`. The tax number, credentials, address, bank, and certificate data stay out of Flow results.
4
+
5
+ In the [EasyAPI E-Invoice console](https://fapiao.easyapi.com/console/), open **服务认证**, create or select a key pair associated with the company, and save its Key and Secret as Dex secret credentials. Use the company's 15, 17, 18, 19, or 20 character tax number as Query input. Blank credentials prevent requests. Leave baseUrl, timeout and maxResponseBytes blank for their displayed production defaults.
6
+
7
+ The [runnable Flow](examples/basic/) uses static connection name `easyapi`. `npm run check` replays all Go-recorded provider scenarios, including rejection, retry, and secret-safe output. Live provider authorization remains unverified without a user-controlled connection.
8
+
9
+ In v0.2, `ShopResult.shopId` uses `SignedInteger`. Safe IDs remain numbers. Larger IDs retain their decimal digits in a raw JSON token. Use `exactIntegerJSONCodec<ShopResult>()` for Blob, Attribute and Flow result decoding. The [Flow](examples/basic/flow.ts) and [starter](examples/basic/start.ts) demonstrate both sides.
@@ -0,0 +1,60 @@
1
+ {
2
+ "connectorId": "easyapi",
3
+ "releaseTag": "connectors/easyapi/go/v0.1.1",
4
+ "package": {
5
+ "ecosystem": "npm",
6
+ "name": "@superdurable/connector-easyapi",
7
+ "version": "0.2.0"
8
+ },
9
+ "factories": [
10
+ {
11
+ "name": "newQueryShopStep",
12
+ "kind": "query",
13
+ "operationId": "queryShop",
14
+ "inputType": "QueryShopInput",
15
+ "description": "Read service status for one authorized invoicing company, excluding tax number, address, phone, bank, staff, and certificate fields.",
16
+ "fields": {
17
+ "stepType": "stepType",
18
+ "annotations": "annotations",
19
+ "connectionName": "connectionName",
20
+ "resultAttribute": "resultAttribute"
21
+ },
22
+ "branches": [
23
+ {
24
+ "id": "found",
25
+ "field": "found",
26
+ "optional": false
27
+ },
28
+ {
29
+ "id": "providerRejected",
30
+ "field": "providerRejected",
31
+ "optional": true
32
+ },
33
+ {
34
+ "id": "invalidResponse",
35
+ "field": "invalidResponse",
36
+ "optional": true
37
+ },
38
+ {
39
+ "id": "defect",
40
+ "field": "defect",
41
+ "optional": true
42
+ }
43
+ ],
44
+ "inputSchema": {
45
+ "additionalProperties": false,
46
+ "description": "QueryShopInput identifies one authorized invoicing company.",
47
+ "properties": {
48
+ "taxNumber": {
49
+ "description": "TaxNumber is the company's taxpayer identification number, 15, 17, 18, 19, or 20 characters.",
50
+ "type": "string"
51
+ }
52
+ },
53
+ "required": [
54
+ "taxNumber"
55
+ ],
56
+ "type": "object"
57
+ }
58
+ }
59
+ ]
60
+ }
@@ -0,0 +1,175 @@
1
+ // src/generated/models.ts
2
+ import { z } from "zod";
3
+ import { SecretString } from "@superdurable/connectors-sdk";
4
+ var nativeJSON = JSON;
5
+ var signedIntegerToken = /^-?(?:0|[1-9][0-9]*)$/;
6
+ var minimumSignedInteger = -(1n << 63n);
7
+ var maximumSignedInteger = (1n << 63n) - 1n;
8
+ function decodeSignedInteger(value) {
9
+ if (typeof value === "number" && Number.isSafeInteger(value)) return value === 0 ? 0 : value;
10
+ if (!nativeJSON.isRawJSON(value) || value.rawJSON.length > 20 || !signedIntegerToken.test(value.rawJSON)) {
11
+ throw new TypeError("expected a signed 64-bit integer");
12
+ }
13
+ const integer = BigInt(value.rawJSON);
14
+ if (integer < minimumSignedInteger || integer > maximumSignedInteger) throw new RangeError("signed 64-bit integer out of range");
15
+ const number = Number(integer);
16
+ return Number.isSafeInteger(number) ? number : value;
17
+ }
18
+ var signedIntegerSchema = z.unknown().transform((value, context) => {
19
+ try {
20
+ return decodeSignedInteger(value);
21
+ } catch {
22
+ context.addIssue({ code: "custom", message: "expected a signed 64-bit integer" });
23
+ return z.NEVER;
24
+ }
25
+ });
26
+ function parseJSONNumberTokens(text) {
27
+ return JSON.parse(text, (_key, value, context) => typeof value === "number" && context?.source !== void 0 ? nativeJSON.rawJSON(context.source) : value);
28
+ }
29
+ function parseExactIntegerJSON(text) {
30
+ return JSON.parse(text, (_key, field, context) => typeof field === "number" && !Number.isSafeInteger(field) && context?.source && signedIntegerToken.test(context.source) ? nativeJSON.rawJSON(context.source) : field);
31
+ }
32
+ function exactIntegerJSONCodec(decode) {
33
+ return {
34
+ typeName: "json",
35
+ wireKind: "json",
36
+ encode(value) {
37
+ const data = JSON.stringify(value, (_key, field) => {
38
+ if (typeof field === "number" && Number.isInteger(field) && !Number.isSafeInteger(field)) {
39
+ throw new RangeError("use a raw JSON token for integers outside the safe number range");
40
+ }
41
+ return field;
42
+ });
43
+ if (data === void 0) throw new TypeError("value cannot be encoded as JSON");
44
+ return { kind: "json", data };
45
+ },
46
+ decode(wire) {
47
+ if (wire.kind !== "json" || typeof wire.data !== "string") throw new TypeError("expected Dex JSON wire data");
48
+ const value = parseExactIntegerJSON(wire.data);
49
+ return decode ? decode(value) : value;
50
+ }
51
+ };
52
+ }
53
+ var ConfigSchema = z.object({
54
+ "baseUrl": z.string().optional(),
55
+ "timeoutMs": z.number().int().optional(),
56
+ "maxResponseBytes": z.number().int().optional()
57
+ });
58
+ var CredentialMaterialError = class extends TypeError {
59
+ constructor(message) {
60
+ super(message);
61
+ this.name = "CredentialMaterialError";
62
+ }
63
+ };
64
+ var sdkCredentialDecodingFailureMessages = /* @__PURE__ */ new Set([
65
+ "project credential decoding failed",
66
+ "shared project credential decoding failed",
67
+ "project credential decoding failed: this connector version does not support shared credentials"
68
+ ]);
69
+ function isCredentialMaterialError(error) {
70
+ return error instanceof CredentialMaterialError || error instanceof TypeError && sdkCredentialDecodingFailureMessages.has(error.message);
71
+ }
72
+ function decodeCredentials(value) {
73
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new CredentialMaterialError("credential fields are invalid");
74
+ const fields = value;
75
+ const allowed = /* @__PURE__ */ new Set(["app_key", "app_secret"]);
76
+ if (Object.keys(fields).some((key) => !allowed.has(key))) throw new CredentialMaterialError("stored credential does not match the connector credential fields");
77
+ if (fields["app_key"] != null && !(typeof fields["app_key"] === "string")) throw new CredentialMaterialError("credential app_key has an invalid type");
78
+ if (fields["app_secret"] != null && !(typeof fields["app_secret"] === "string")) throw new CredentialMaterialError("credential app_secret has an invalid type");
79
+ const credentials = {};
80
+ if (!fields["app_key"]) throw new CredentialMaterialError("credential app_key is required");
81
+ credentials.appKey = new SecretString(fields["app_key"] ?? "");
82
+ if (!fields["app_secret"]) throw new CredentialMaterialError("credential app_secret is required");
83
+ credentials.appSecret = new SecretString(fields["app_secret"] ?? "");
84
+ return credentials;
85
+ }
86
+ var QueryShopInputSchema = z.strictObject({
87
+ "taxNumber": z.string()
88
+ });
89
+ var ShopResultSchema = z.strictObject({
90
+ "shopId": signedIntegerSchema,
91
+ "name": z.string(),
92
+ "apiState": signedIntegerSchema,
93
+ "endTime": z.string()
94
+ });
95
+
96
+ // src/generated/definitions.ts
97
+ var ConnectorID = "easyapi";
98
+ var ProviderID = "easyapi";
99
+ var QueryShopBranch = {
100
+ Found: "found",
101
+ ProviderRejected: "providerRejected",
102
+ InvalidResponse: "invalidResponse",
103
+ Defect: "defect"
104
+ };
105
+ var QueryShopBranchFound = QueryShopBranch.Found;
106
+ var QueryShopBranchProviderRejected = QueryShopBranch.ProviderRejected;
107
+ var QueryShopBranchInvalidResponse = QueryShopBranch.InvalidResponse;
108
+ var QueryShopBranchDefect = QueryShopBranch.Defect;
109
+ var QueryShopDefinition = {
110
+ operation: { connectorId: ConnectorID, operationId: "queryShop" },
111
+ branches: [
112
+ { id: "found", description: "EasyAPI returned the company's invoicing service configuration." },
113
+ { id: "providerRejected", description: "EasyAPI rejected the credentials or tax number.", optional: true },
114
+ { id: "invalidResponse", description: "EasyAPI returned malformed or oversized company data.", optional: true },
115
+ { id: "defect", description: "The local tax number or connection is invalid.", optional: true }
116
+ ],
117
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async" }
118
+ };
119
+ var QueryShopMetadata = { kind: "query", idempotency: "none", authorization: "required" };
120
+
121
+ // src/generated/connection.ts
122
+ import { ConnectionRefSchema } from "@superdurable/connectors-sdk";
123
+ var Connection = class {
124
+ /** Stable provider and connection name. */
125
+ reference;
126
+ /** Bound provider operations. */
127
+ operations;
128
+ /** Validate a reference and bind operations. */
129
+ constructor(reference, operations) {
130
+ this.reference = ConnectionRefSchema.parse(reference);
131
+ if (this.reference.provider !== ProviderID) throw new TypeError("connection provider differs from the manifest");
132
+ if (!operations) throw new TypeError("connector operations are required");
133
+ this.operations = operations;
134
+ }
135
+ };
136
+ function newConnection(client, reference) {
137
+ if (!client) throw new TypeError("connector client is required");
138
+ return new Connection(reference, client);
139
+ }
140
+ function newConnectionWithOperations(operations, reference) {
141
+ return new Connection(reference, operations);
142
+ }
143
+ function newProjectConnection(project, connectionName, createClient) {
144
+ if (!project) throw new TypeError("loaded project is required");
145
+ const reference = ConnectionRefSchema.parse({ provider: ProviderID, name: connectionName });
146
+ const selected = project.configuration.connections.find((entry) => entry.connectorId === ConnectorID && entry.connectionName === connectionName);
147
+ if (!selected || selected.provider !== ProviderID) throw new TypeError("project connection is not configured");
148
+ return newConnection(createClient(project, connectionName), reference);
149
+ }
150
+
151
+ export {
152
+ decodeSignedInteger,
153
+ parseJSONNumberTokens,
154
+ parseExactIntegerJSON,
155
+ exactIntegerJSONCodec,
156
+ ConfigSchema,
157
+ CredentialMaterialError,
158
+ isCredentialMaterialError,
159
+ decodeCredentials,
160
+ QueryShopInputSchema,
161
+ ShopResultSchema,
162
+ ConnectorID,
163
+ ProviderID,
164
+ QueryShopBranch,
165
+ QueryShopBranchFound,
166
+ QueryShopBranchProviderRejected,
167
+ QueryShopBranchInvalidResponse,
168
+ QueryShopBranchDefect,
169
+ QueryShopDefinition,
170
+ QueryShopMetadata,
171
+ Connection,
172
+ newConnection,
173
+ newConnectionWithOperations,
174
+ newProjectConnection
175
+ };
@@ -0,0 +1,100 @@
1
+ import { CredentialProvider, SecretString, Query, ConnectionRef } from '@superdurable/connectors-sdk';
2
+ import { z } from 'zod';
3
+ import { Codec } from '@superdurable/dex';
4
+
5
+ /** A signed 64-bit JSON integer. Values outside the safe number range retain their decimal token. */
6
+ type SignedInteger = number | Readonly<{
7
+ rawJSON: string;
8
+ }>;
9
+ /** Decode one signed Go integer from a safe number or a native raw JSON number token. */
10
+ declare function decodeSignedInteger(value: unknown): SignedInteger;
11
+ /** Read provider JSON with the original syntax of every numeric token for typed field validation. */
12
+ declare function parseJSONNumberTokens(text: string): unknown;
13
+ /** Decode JSON while retaining exact decimal tokens for integers outside JavaScript's safe range. */
14
+ declare function parseExactIntegerJSON(text: string): unknown;
15
+ /** JSON-wire codec for records with signed integer fields. An optional decoder validates the application type. */
16
+ declare function exactIntegerJSONCodec<T>(decode?: (value: unknown) => T): Codec<T>;
17
+ /** Connector configuration; omitted fields use manifest defaults. */
18
+ interface Config {
19
+ /** HTTPS origin of the EasyAPI E-Invoice API. Leave blank for the displayed production endpoint; override only for a trusted provider-issued HTTPS endpoint. */
20
+ baseUrl?: string;
21
+ /** Maximum duration of one company configuration query as a positive Go duration such as 30s or 1m. Leave blank for the displayed default; raise it only when the provider responds slowly from your network. Runtime value in milliseconds. */
22
+ timeoutMs?: number;
23
+ /** Maximum company response size in bytes as a positive integer. Leave blank for the displayed default; raise only if provider responses exceed it. */
24
+ maxResponseBytes?: number;
25
+ }
26
+ /** Runtime schema for manifest configuration. */
27
+ declare const ConfigSchema: z.ZodObject<{
28
+ baseUrl: z.ZodOptional<z.ZodString>;
29
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
30
+ maxResponseBytes: z.ZodOptional<z.ZodNumber>;
31
+ }, z.core.$strip>;
32
+ /** Private connector credentials resolved by the host. */
33
+ interface Credentials {
34
+ /** Service Key from https://fapiao.easyapi.com/console/ > 服务认证. Copy exactly into this protected field; blank prevents requests. */
35
+ appKey: SecretString;
36
+ /** Service Secret paired with the Key on the same 服务认证 page. Copy exactly into this protected field; blank prevents requests. */
37
+ appSecret: SecretString;
38
+ }
39
+ /** Stored credential material that fails the connector credential checks, so no retry can succeed. */
40
+ declare class CredentialMaterialError extends TypeError {
41
+ constructor(message: string);
42
+ }
43
+ /** Report malformed stored credential material, also behind the SDK provider's decoding TypeError. */
44
+ declare function isCredentialMaterialError(error: unknown): boolean;
45
+ /** Decode private credential fields for the connector. */
46
+ declare function decodeCredentials(value: unknown): Credentials;
47
+ /** Host-owned source of private connector credentials. */
48
+ type CredentialSource = CredentialProvider<Credentials>;
49
+ /** QueryShopInput identifies one authorized invoicing company. */
50
+ interface QueryShopInput {
51
+ /** TaxNumber is the company's taxpayer identification number, 15, 17, 18, 19, or 20 characters. */
52
+ "taxNumber": string;
53
+ }
54
+ /** ShopResult contains only non-sensitive invoicing service configuration. */
55
+ interface ShopResult {
56
+ /** ShopID is EasyAPI's company ID. */
57
+ "shopId": SignedInteger;
58
+ /** Name is the company's registered name. */
59
+ "name": string;
60
+ /** APIState is 1 normal, 0 expired, or -1 not activated. */
61
+ "apiState": SignedInteger;
62
+ /** EndTime is the service expiry time in provider local time, or blank if absent. */
63
+ "endTime": string;
64
+ }
65
+ /** Runtime validator for QueryShopInput. */
66
+ declare const QueryShopInputSchema: z.ZodObject<{
67
+ taxNumber: z.ZodString;
68
+ }, z.core.$strict>;
69
+ /** Runtime validator for ShopResult. */
70
+ declare const ShopResultSchema: z.ZodObject<{
71
+ shopId: z.ZodPipe<z.ZodUnknown, z.ZodTransform<number | Readonly<{
72
+ rawJSON: string;
73
+ }>, unknown>>;
74
+ name: z.ZodString;
75
+ apiState: z.ZodPipe<z.ZodUnknown, z.ZodTransform<number | Readonly<{
76
+ rawJSON: string;
77
+ }>, unknown>>;
78
+ endTime: z.ZodString;
79
+ }, z.core.$strict>;
80
+
81
+ /** Typed operations supplied by a client or mock. */
82
+ interface Operations {
83
+ /** Invoke queryShop through this connection. */
84
+ queryShop(): Query<QueryShopInput, ShopResult>;
85
+ }
86
+ /** Named connector connection kept outside Flow state. */
87
+ declare class Connection<BoundOperations = Operations> {
88
+ /** Stable provider and connection name. */
89
+ readonly reference: ConnectionRef;
90
+ /** Bound provider operations. */
91
+ readonly operations: BoundOperations;
92
+ /** Validate a reference and bind operations. */
93
+ constructor(reference: ConnectionRef, operations: BoundOperations);
94
+ }
95
+ /** Bind a client to a named connection. */
96
+ declare function newConnection(client: Operations, reference: ConnectionRef): Connection;
97
+ /** Bind scripted operations to a named connection. */
98
+ declare function newConnectionWithOperations(operations: Operations, reference: ConnectionRef): Connection;
99
+
100
+ export { Connection as C, type Operations as O, type QueryShopInput as Q, type ShopResult as S, type Config as a, type Credentials as b, ConfigSchema as c, CredentialMaterialError as d, type CredentialSource as e, QueryShopInputSchema as f, ShopResultSchema as g, type SignedInteger as h, decodeCredentials as i, decodeSignedInteger as j, exactIntegerJSONCodec as k, isCredentialMaterialError as l, newConnectionWithOperations as m, newConnection as n, parseJSONNumberTokens as o, parseExactIntegerJSON as p };
@@ -0,0 +1,91 @@
1
+ import { Q as QueryShopInput, S as ShopResult, C as Connection, O as Operations, a as Config, b as Credentials } from './connection-CmwaCEu5.js';
2
+ export { c as ConfigSchema, d as CredentialMaterialError, e as CredentialSource, f as QueryShopInputSchema, g as ShopResultSchema, h as SignedInteger, i as decodeCredentials, j as decodeSignedInteger, k as exactIntegerJSONCodec, l as isCredentialMaterialError, n as newConnection, m as newConnectionWithOperations, p as parseExactIntegerJSON, o as parseJSONNumberTokens } from './connection-CmwaCEu5.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 = "easyapi";
11
+ /** Provider identity for named connections. */
12
+ declare const ProviderID = "easyapi";
13
+ /** Branch IDs for queryShop. */
14
+ declare const QueryShopBranch: {
15
+ readonly Found: "found";
16
+ readonly ProviderRejected: "providerRejected";
17
+ readonly InvalidResponse: "invalidResponse";
18
+ readonly Defect: "defect";
19
+ };
20
+ /** EasyAPI returned the company's invoicing service configuration. */
21
+ declare const QueryShopBranchFound: "found";
22
+ /** EasyAPI rejected the credentials or tax number. */
23
+ declare const QueryShopBranchProviderRejected: "providerRejected";
24
+ /** EasyAPI returned malformed or oversized company data. */
25
+ declare const QueryShopBranchInvalidResponse: "invalidResponse";
26
+ /** The local tax number or connection is invalid. */
27
+ declare const QueryShopBranchDefect: "defect";
28
+ /** Manifest definition for queryShop. */
29
+ declare const QueryShopDefinition: QueryDefinition;
30
+ /** Manifest metadata for queryShop. */
31
+ declare const QueryShopMetadata: {
32
+ readonly kind: "query";
33
+ readonly idempotency: "none";
34
+ readonly authorization: "required";
35
+ };
36
+
37
+ /** Configuration for the queryShop connector Step. */
38
+ interface QueryShopStepConfig<StepInput, OperationInput = QueryShopInput, OperationOutput = ShopResult> extends Omit<QueryStepConfig<StepInput, OperationInput, OperationOutput>, 'operation' | 'connection' | 'branches'> {
39
+ /** Named connection supplying this operation. */
40
+ connection: Connection<{
41
+ queryShop(): Query<OperationInput, OperationOutput>;
42
+ }>;
43
+ /** Name matching the bound connection. */
44
+ connectionName: string;
45
+ /** EasyAPI returned the company's invoicing service configuration. */
46
+ found: StepTarget<QueryResult<OperationOutput>>;
47
+ /** EasyAPI rejected the credentials or tax number. */
48
+ providerRejected?: StepTarget<QueryResult<OperationOutput>>;
49
+ /** EasyAPI returned malformed or oversized company data. */
50
+ invalidResponse?: StepTarget<QueryResult<OperationOutput>>;
51
+ /** The local tax number or connection is invalid. */
52
+ defect?: StepTarget<QueryResult<OperationOutput>>;
53
+ }
54
+ /** Build the queryShop Step from a named connection. */
55
+ declare function newQueryShopStep<StepInput, OperationInput = QueryShopInput, OperationOutput = ShopResult>(configuration: QueryShopStepConfig<StepInput, OperationInput, OperationOutput>): QueryStep<StepInput, OperationInput, OperationOutput>;
56
+
57
+ /** Open one named Easyapi connection from Dex project configuration. */
58
+ declare function newProjectConnection(project: LoadedProject, connectionName: string): Connection<Operations>;
59
+
60
+ /** Optional sender for isolated conformance replay. */
61
+ interface EasyapiClientOptions {
62
+ /** Sender; omitted uses the SDK HTTPS transport. */ send?: (request: ProviderRequest) => Promise<ProviderResponse>;
63
+ }
64
+ /** Read one authorized company's invoicing service metadata. */
65
+ declare class EasyapiClient {
66
+ private readonly credentials;
67
+ private readonly baseUrl;
68
+ private readonly timeoutMs;
69
+ private readonly maxResponseBytes;
70
+ private readonly send;
71
+ /** Validate local settings without contacting EasyAPI. */
72
+ constructor(config: Config, credentials: CredentialProvider<Credentials>, options?: EasyapiClientOptions);
73
+ /** Bind the company Query. */ queryShop(): QueryShopOperation;
74
+ /** Send one bounded shop query. */
75
+ readShop(call: Call, taxNumber: string): Promise<{
76
+ response?: ProviderResponse;
77
+ error?: 'credential' | 'transport' | 'tooLarge';
78
+ retryAfterMs: number;
79
+ outcome?: QueryAttempt<ShopResult>;
80
+ }>;
81
+ }
82
+ /** Read one company's non-sensitive service configuration. */
83
+ declare class QueryShopOperation implements Query<QueryShopInput, ShopResult> {
84
+ private readonly client;
85
+ /** Bind the provider client. */ constructor(client: EasyapiClient);
86
+ /** Return the generated Query definition. */ definition(): QueryDefinition;
87
+ /** Classify one company read according to the Go connector contract. */
88
+ invoke(call: Call, input: QueryShopInput): Promise<QueryAttempt<ShopResult>>;
89
+ }
90
+
91
+ export { Config, Connection, ConnectorID, Credentials, EasyapiClient, type EasyapiClientOptions, ProviderID, QueryShopBranch, QueryShopBranchDefect, QueryShopBranchFound, QueryShopBranchInvalidResponse, QueryShopBranchProviderRejected, QueryShopDefinition, QueryShopInput, QueryShopMetadata, type QueryShopStepConfig, ShopResult, newProjectConnection, newQueryShopStep };
package/dist/index.js ADDED
@@ -0,0 +1,245 @@
1
+ import {
2
+ ConfigSchema,
3
+ Connection,
4
+ ConnectorID,
5
+ CredentialMaterialError,
6
+ ProviderID,
7
+ QueryShopBranch,
8
+ QueryShopBranchDefect,
9
+ QueryShopBranchFound,
10
+ QueryShopBranchInvalidResponse,
11
+ QueryShopBranchProviderRejected,
12
+ QueryShopDefinition,
13
+ QueryShopInputSchema,
14
+ QueryShopMetadata,
15
+ ShopResultSchema,
16
+ decodeCredentials,
17
+ decodeSignedInteger,
18
+ exactIntegerJSONCodec,
19
+ isCredentialMaterialError,
20
+ newConnection,
21
+ newConnectionWithOperations,
22
+ newProjectConnection,
23
+ parseExactIntegerJSON,
24
+ parseJSONNumberTokens
25
+ } from "./chunk-AC3VW4YR.js";
26
+
27
+ // src/generated/steps.ts
28
+ import { goToBranch, newQueryStep } from "@superdurable/connectors-sdk";
29
+ function newQueryShopStep(configuration) {
30
+ const { connection, connectionName, found, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
31
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
32
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.queryShop(), connection: connection.reference, branches: [
33
+ goToBranch("found", found),
34
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
35
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
36
+ ...defect ? [goToBranch("defect", defect)] : []
37
+ ] });
38
+ }
39
+
40
+ // src/client.ts
41
+ import {
42
+ SecretString,
43
+ newQueryBranch,
44
+ newQueryRetry
45
+ } from "@superdurable/connectors-sdk";
46
+ import {
47
+ BodyTooLargeError,
48
+ parseRetryAfter,
49
+ sendProviderRequest,
50
+ validateBaseURL
51
+ } from "@superdurable/connectors-sdk/providerhttp";
52
+ var emptyResult = { shopId: 0, name: "", apiState: 0, endTime: "" };
53
+ var EasyapiClient = class {
54
+ /** Validate local settings without contacting EasyAPI. */
55
+ constructor(config, credentials, options = {}) {
56
+ this.credentials = credentials;
57
+ if (!config || !credentials) throw new TypeError("EasyAPI configuration and credentials are required");
58
+ this.baseUrl = validateBaseURL(config.baseUrl || "https://fapiao-api.easyapi.com");
59
+ this.timeoutMs = config.timeoutMs || 15e3;
60
+ this.maxResponseBytes = config.maxResponseBytes || 262144;
61
+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0)
62
+ throw new TypeError("EasyAPI request limits are invalid");
63
+ this.send = options.send ?? sendProviderRequest;
64
+ }
65
+ credentials;
66
+ baseUrl;
67
+ timeoutMs;
68
+ maxResponseBytes;
69
+ send;
70
+ /** Bind the company Query. */
71
+ queryShop() {
72
+ return new QueryShopOperation(this);
73
+ }
74
+ /** Send one bounded shop query. */
75
+ async readShop(call, taxNumber) {
76
+ let appKey = "", appSecret = "";
77
+ try {
78
+ const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
79
+ appKey = credentials.appKey instanceof SecretString ? credentials.appKey.reveal() : "";
80
+ appSecret = credentials.appSecret instanceof SecretString ? credentials.appSecret.reveal() : "";
81
+ } catch {
82
+ return { error: "credential", retryAfterMs: 0 };
83
+ }
84
+ if (!validCredential(appKey) || !validCredential(appSecret))
85
+ return { error: "credential", retryAfterMs: 0 };
86
+ const query = new URLSearchParams({ appKey, appSecret, taxNumber });
87
+ const request = {
88
+ url: this.baseUrl + "/shop/query?" + query.toString(),
89
+ method: "GET",
90
+ headers: { Accept: "application/json" },
91
+ timeoutMs: this.timeoutMs,
92
+ maxResponseBytes: this.maxResponseBytes,
93
+ addressPolicy: "publicHTTPS",
94
+ signal: call.context.cancellationSignal
95
+ };
96
+ let response;
97
+ try {
98
+ response = await this.send(request);
99
+ } catch (error) {
100
+ if (error instanceof BodyTooLargeError && error.status !== void 0)
101
+ return {
102
+ response: { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() },
103
+ error: "tooLarge",
104
+ retryAfterMs: parseRetryAfter(header(error.headers ?? {}, "retry-after"))
105
+ };
106
+ return { error: "transport", retryAfterMs: 0 };
107
+ }
108
+ const outcome = response.status === 200 && response.body.length <= this.maxResponseBytes ? decodeShop(response.body, [appKey, appSecret, taxNumber]) : void 0;
109
+ return {
110
+ response,
111
+ outcome,
112
+ error: response.body.length > this.maxResponseBytes ? "tooLarge" : void 0,
113
+ retryAfterMs: parseRetryAfter(header(response.headers, "retry-after"))
114
+ };
115
+ }
116
+ };
117
+ var QueryShopOperation = class {
118
+ /** Bind the provider client. */
119
+ constructor(client) {
120
+ this.client = client;
121
+ }
122
+ client;
123
+ /** Return the generated Query definition. */
124
+ definition() {
125
+ return QueryShopDefinition;
126
+ }
127
+ /** Classify one company read according to the Go connector contract. */
128
+ async invoke(call, input) {
129
+ const taxNumber = input?.taxNumber;
130
+ if (typeof taxNumber !== "string" || ![15, 17, 18, 19, 20].includes(taxNumber.length) || /[^0-9A-Z]/.test(taxNumber))
131
+ return branch("defect", "VALIDATION");
132
+ const exchange = await this.client.readShop(call, taxNumber);
133
+ if (exchange.error === "credential") return branch("defect", "AUTHENTICATION");
134
+ if (exchange.error === "transport" || !exchange.response) return retry("AVAILABILITY");
135
+ const { status } = exchange.response;
136
+ if (status === 429) return retry("RATE_LIMIT", exchange.retryAfterMs);
137
+ if (status === 408 || status >= 500) return retry("AVAILABILITY", exchange.retryAfterMs);
138
+ if (exchange.error === "tooLarge") return branch("invalidResponse", "RESPONSE_TOO_LARGE");
139
+ if (status !== 200)
140
+ return branch(
141
+ "providerRejected",
142
+ status === 401 ? "AUTHENTICATION" : status === 403 ? "AUTHORIZATION" : [400, 404, 412].includes(status) ? "VALIDATION" : "PROVIDER_REJECTION"
143
+ );
144
+ return exchange.outcome ?? branch("invalidResponse", "PROTOCOL");
145
+ }
146
+ };
147
+ function decodeShop(body, privateValues) {
148
+ try {
149
+ const envelope = record(
150
+ parseJSONNumberTokens(new TextDecoder("utf-8", { ignoreBOM: true }).decode(body))
151
+ );
152
+ const code = decodeSignedInteger(envelope.code);
153
+ const content = record(envelope.content ?? {});
154
+ const id = decodeSignedInteger(content.shopid ?? 0);
155
+ const state = decodeSignedInteger(content.apistate ?? 0);
156
+ const name = content.name ?? "", endTime = content.endtime ?? "";
157
+ if (typeof name !== "string" || typeof endTime !== "string") throw new Error("invalid company fields");
158
+ if (code !== 1) return branch("providerRejected", "PROVIDER_REJECTION");
159
+ const positiveId = typeof id === "number" ? id > 0 : BigInt(id.rawJSON) > 0n;
160
+ if (!positiveId || !name || Buffer.byteLength(name) > 256 || Buffer.byteLength(endTime) > 32 || content.apistate == null || state !== -1 && state !== 0 && state !== 1 || privateValues.some((value) => name.includes(value) || endTime.includes(value)))
161
+ throw new Error("invalid company fields");
162
+ return newQueryBranch("found", { shopId: id, name, apiState: state, endTime }, {});
163
+ } catch {
164
+ return branch("invalidResponse", "PROTOCOL");
165
+ }
166
+ }
167
+ function record(value) {
168
+ if (value === null || typeof value !== "object" || Array.isArray(value) || JSON.isRawJSON(value))
169
+ throw new Error("invalid response object");
170
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key.toLowerCase(), item]));
171
+ }
172
+ function validCredential(value) {
173
+ return !!value && Buffer.byteLength(value) <= 2048 && !/^\p{White_Space}|\p{White_Space}$/u.test(value);
174
+ }
175
+ function header(headers, name) {
176
+ const value = Object.entries(headers).find(([key]) => key.toLowerCase() === name)?.[1];
177
+ return Array.isArray(value) ? value[0] ?? "" : value ?? "";
178
+ }
179
+ function failure(kind) {
180
+ return { provider: "easyapi", operation: "queryShop", kind, message: "EasyAPI company query failed" };
181
+ }
182
+ function branch(name, kind) {
183
+ return newQueryBranch(name, emptyResult, {}, 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 === "easyapi" && entry.connectionName === name);
193
+ if (!selected) throw new TypeError("Easyapi 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("easyapi", name, signal));
199
+ }
200
+ };
201
+ return new EasyapiClient(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
+ EasyapiClient,
225
+ ProviderID,
226
+ QueryShopBranch,
227
+ QueryShopBranchDefect,
228
+ QueryShopBranchFound,
229
+ QueryShopBranchInvalidResponse,
230
+ QueryShopBranchProviderRejected,
231
+ QueryShopDefinition,
232
+ QueryShopInputSchema,
233
+ QueryShopMetadata,
234
+ ShopResultSchema,
235
+ decodeCredentials,
236
+ decodeSignedInteger,
237
+ exactIntegerJSONCodec,
238
+ isCredentialMaterialError,
239
+ newConnection,
240
+ newConnectionWithOperations,
241
+ newProjectConnection2 as newProjectConnection,
242
+ newQueryShopStep,
243
+ parseExactIntegerJSON,
244
+ parseJSONNumberTokens
245
+ };
package/dist/mock.d.ts ADDED
@@ -0,0 +1,34 @@
1
+ import { MockQuery, Case } from '@superdurable/connectors-sdk/connectormock';
2
+ import { Failure } from '@superdurable/connectors-sdk';
3
+ import { O as Operations, C as Connection, Q as QueryShopInput, S as ShopResult } from './connection-CmwaCEu5.js';
4
+ import 'zod';
5
+ import '@superdurable/dex';
6
+
7
+ /** Go zero value for QueryShopInput in scripted cases. */
8
+ declare const emptyQueryShopInput: QueryShopInput;
9
+ /** Go zero value for ShopResult in scripted cases. */
10
+ declare const emptyShopResult: ShopResult;
11
+ /** Script the found branch. */
12
+ declare function queryShopFound(value: ShopResult, failure?: Failure): Case<ShopResult>;
13
+ /** Script the providerRejected branch. */
14
+ declare function queryShopProviderRejected(value: ShopResult, failure?: Failure): Case<ShopResult>;
15
+ /** Script the invalidResponse branch. */
16
+ declare function queryShopInvalidResponse(value: ShopResult, failure?: Failure): Case<ShopResult>;
17
+ /** Script the defect branch. */
18
+ declare function queryShopDefect(value: ShopResult, failure?: Failure): Case<ShopResult>;
19
+ /** Script a safe retry of queryShop. */
20
+ declare function queryShopRetry(failure: Failure, retryAfterMs?: number): Case<ShopResult>;
21
+ /** Manifest scenario foundShop for queryShop. */
22
+ declare function queryShopFoundShop(): Case<ShopResult>;
23
+ /** Default queryShop scenario. */
24
+ declare function queryShopDefault(): Case<ShopResult>;
25
+ /** Scripted operations and manifest defaults for this connector. */
26
+ declare class GeneratedMock implements Operations {
27
+ #private;
28
+ constructor(connectionName: string);
29
+ connection(): Connection;
30
+ queryShop(): MockQuery<QueryShopInput, ShopResult>;
31
+ assertNoFailures(): void;
32
+ }
33
+
34
+ export { GeneratedMock, emptyQueryShopInput, emptyShopResult, queryShopDefault, queryShopDefect, queryShopFound, queryShopFoundShop, queryShopInvalidResponse, queryShopProviderRejected, queryShopRetry };
package/dist/mock.js ADDED
@@ -0,0 +1,71 @@
1
+ import {
2
+ ProviderID,
3
+ QueryShopDefinition,
4
+ QueryShopInputSchema,
5
+ ShopResultSchema,
6
+ newConnectionWithOperations,
7
+ parseExactIntegerJSON
8
+ } from "./chunk-AC3VW4YR.js";
9
+
10
+ // src/generated/mock.ts
11
+ import { branchCase, retryCase, newQuery } from "@superdurable/connectors-sdk/connectormock";
12
+ var emptyQueryShopInput = QueryShopInputSchema.parse({
13
+ "taxNumber": ""
14
+ });
15
+ var emptyShopResult = ShopResultSchema.parse({
16
+ "shopId": 0,
17
+ "name": "",
18
+ "apiState": 0,
19
+ "endTime": ""
20
+ });
21
+ function queryShopFound(value, failure) {
22
+ return branchCase("found", value, failure);
23
+ }
24
+ function queryShopProviderRejected(value, failure) {
25
+ return branchCase("providerRejected", value, failure);
26
+ }
27
+ function queryShopInvalidResponse(value, failure) {
28
+ return branchCase("invalidResponse", value, failure);
29
+ }
30
+ function queryShopDefect(value, failure) {
31
+ return branchCase("defect", value, failure);
32
+ }
33
+ function queryShopRetry(failure, retryAfterMs = 0) {
34
+ return retryCase(failure, retryAfterMs);
35
+ }
36
+ function queryShopFoundShop() {
37
+ const value = ShopResultSchema.parse(parseExactIntegerJSON('{"apiState":1,"endTime":"2027-01-01 00:00:00","name":"Example Company","shopId":1001}'));
38
+ return branchCase("found", value);
39
+ }
40
+ function queryShopDefault() {
41
+ return queryShopFoundShop();
42
+ }
43
+ var GeneratedMock = class {
44
+ #queryShop;
45
+ #connection;
46
+ constructor(connectionName) {
47
+ this.#queryShop = newQuery(QueryShopDefinition).default(queryShopDefault());
48
+ this.#connection = newConnectionWithOperations(this, { provider: ProviderID, name: connectionName });
49
+ }
50
+ connection() {
51
+ return this.#connection;
52
+ }
53
+ queryShop() {
54
+ return this.#queryShop;
55
+ }
56
+ assertNoFailures() {
57
+ this.#queryShop.assertNoFailures();
58
+ }
59
+ };
60
+ export {
61
+ GeneratedMock,
62
+ emptyQueryShopInput,
63
+ emptyShopResult,
64
+ queryShopDefault,
65
+ queryShopDefect,
66
+ queryShopFound,
67
+ queryShopFoundShop,
68
+ queryShopInvalidResponse,
69
+ queryShopProviderRejected,
70
+ queryShopRetry
71
+ };
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@superdurable/connector-easyapi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "license": "MIT",
5
+ "description": "EasyAPI E-Invoice company query connector for Dex TypeScript applications",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/superdurable/dex-connectors-library.git",
9
+ "directory": "connectors/easyapi/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
+ }