@superdurable/connector-amazon-dynamodb 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 keyation 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,3 @@
1
- # Temporary Holding Version
1
+ # Amazon DynamoDB TypeScript package
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
+ `AmazonDynamoDBClient.getItem()` binds the signed `getItem` Query. `GetItemInput` contains `tableName`, the complete DynamoDB `key` AttributeValue map, and `consistentRead`. The `found` output contains `{ exists: true, item }`; `missing` has an empty item map. See the [connector guide](../README.md) for configuration and IAM permissions. The [runnable Flow](examples/item-lookup/README.md) exercises a real Dex Worker with a local provider fixture. Live AWS access has not been verified.
@@ -0,0 +1,76 @@
1
+ {
2
+ "connectorId": "amazon-dynamodb",
3
+ "releaseTag": "connectors/amazon/dynamodb/go/v0.1.0",
4
+ "package": {
5
+ "ecosystem": "npm",
6
+ "name": "@superdurable/connector-amazon-dynamodb",
7
+ "version": "0.1.0"
8
+ },
9
+ "factories": [
10
+ {
11
+ "name": "newGetItemStep",
12
+ "kind": "query",
13
+ "operationId": "getItem",
14
+ "inputType": "GetItemInput",
15
+ "description": "Read one DynamoDB item by its complete primary key, with an optional strongly consistent read.",
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": "missing",
30
+ "field": "missing",
31
+ "optional": true
32
+ },
33
+ {
34
+ "id": "providerRejected",
35
+ "field": "providerRejected",
36
+ "optional": true
37
+ },
38
+ {
39
+ "id": "invalidResponse",
40
+ "field": "invalidResponse",
41
+ "optional": true
42
+ },
43
+ {
44
+ "id": "defect",
45
+ "field": "defect",
46
+ "optional": true
47
+ }
48
+ ],
49
+ "inputSchema": {
50
+ "additionalProperties": false,
51
+ "description": "GetItemInput identifies a table row by all of its S, N, or B key attributes.",
52
+ "properties": {
53
+ "consistentRead": {
54
+ "type": "boolean"
55
+ },
56
+ "key": {
57
+ "additionalProperties": {},
58
+ "type": [
59
+ "object",
60
+ "null"
61
+ ]
62
+ },
63
+ "tableName": {
64
+ "type": "string"
65
+ }
66
+ },
67
+ "required": [
68
+ "consistentRead",
69
+ "key",
70
+ "tableName"
71
+ ],
72
+ "type": "object"
73
+ }
74
+ }
75
+ ]
76
+ }
@@ -0,0 +1,113 @@
1
+ // src/generated/models.ts
2
+ import { z } from "zod";
3
+ import { SecretString } from "@superdurable/connectors-sdk";
4
+ var ConfigSchema = z.object({
5
+ "region": z.string().optional(),
6
+ "endpoint": z.string().optional(),
7
+ "timeoutMs": z.number().int().optional(),
8
+ "maxResponseBytes": z.number().int().optional()
9
+ });
10
+ function decodeCredentials(value) {
11
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("credential fields are invalid");
12
+ const fields = value;
13
+ const allowed = /* @__PURE__ */ new Set(["access_key_id", "secret_access_key", "session_token"]);
14
+ if (Object.keys(fields).some((key) => !allowed.has(key))) throw new TypeError("stored credential does not match the connector credential fields");
15
+ if (fields["access_key_id"] != null && !(typeof fields["access_key_id"] === "string")) throw new TypeError("credential access_key_id has an invalid type");
16
+ if (fields["secret_access_key"] != null && !(typeof fields["secret_access_key"] === "string")) throw new TypeError("credential secret_access_key has an invalid type");
17
+ if (fields["session_token"] != null && !(typeof fields["session_token"] === "string")) throw new TypeError("credential session_token has an invalid type");
18
+ const credentials = {};
19
+ if (!fields["access_key_id"]) throw new TypeError("credential access_key_id is required");
20
+ credentials.accessKeyId = new SecretString(fields["access_key_id"] ?? "");
21
+ if (!fields["secret_access_key"]) throw new TypeError("credential secret_access_key is required");
22
+ credentials.secretAccessKey = new SecretString(fields["secret_access_key"] ?? "");
23
+ credentials.sessionToken = new SecretString(fields["session_token"] ?? "");
24
+ return credentials;
25
+ }
26
+ var GetItemInputSchema = z.strictObject({
27
+ "tableName": z.string(),
28
+ "key": z.record(z.string(), z.unknown().nullable()).nullable(),
29
+ "consistentRead": z.boolean()
30
+ });
31
+ var ItemResultSchema = z.strictObject({
32
+ "exists": z.boolean(),
33
+ "item": z.record(z.string(), z.unknown().nullable()).nullable()
34
+ });
35
+
36
+ // src/generated/definitions.ts
37
+ var ConnectorID = "amazon-dynamodb";
38
+ var ProviderID = "amazon-dynamodb";
39
+ var GetItemBranch = {
40
+ Found: "found",
41
+ Missing: "missing",
42
+ ProviderRejected: "providerRejected",
43
+ InvalidResponse: "invalidResponse",
44
+ Defect: "defect"
45
+ };
46
+ var GetItemBranchFound = GetItemBranch.Found;
47
+ var GetItemBranchMissing = GetItemBranch.Missing;
48
+ var GetItemBranchProviderRejected = GetItemBranch.ProviderRejected;
49
+ var GetItemBranchInvalidResponse = GetItemBranch.InvalidResponse;
50
+ var GetItemBranchDefect = GetItemBranch.Defect;
51
+ var GetItemDefinition = {
52
+ operation: { connectorId: ConnectorID, operationId: "getItem" },
53
+ branches: [
54
+ { id: "found", description: "DynamoDB returned the item." },
55
+ { id: "missing", description: "The table has no item with that key.", optional: true },
56
+ { id: "providerRejected", description: "DynamoDB conclusively rejected the request or credentials.", optional: true },
57
+ { id: "invalidResponse", description: "DynamoDB returned malformed or oversized item JSON.", optional: true },
58
+ { id: "defect", description: "The table, key, endpoint, Region, or credentials are invalid.", optional: true }
59
+ ],
60
+ stepDefaults: { executeMethodTimeoutMs: 3e4, executeDurability: "async" }
61
+ };
62
+ var GetItemMetadata = { kind: "query", idempotency: "none", authorization: "required" };
63
+
64
+ // src/generated/connection.ts
65
+ import { ConnectionRefSchema } from "@superdurable/connectors-sdk";
66
+ var Connection = class {
67
+ /** Stable provider and connection name. */
68
+ reference;
69
+ /** Bound provider operations. */
70
+ operations;
71
+ /** Validate a reference and bind operations. */
72
+ constructor(reference, operations) {
73
+ this.reference = ConnectionRefSchema.parse(reference);
74
+ if (this.reference.provider !== ProviderID) throw new TypeError("connection provider differs from the manifest");
75
+ if (!operations) throw new TypeError("connector operations are required");
76
+ this.operations = operations;
77
+ }
78
+ };
79
+ function newConnection(client, reference) {
80
+ if (!client) throw new TypeError("connector client is required");
81
+ return new Connection(reference, client);
82
+ }
83
+ function newConnectionWithOperations(operations, reference) {
84
+ return new Connection(reference, operations);
85
+ }
86
+ function newProjectConnection(project, connectionName, createClient) {
87
+ if (!project) throw new TypeError("loaded project is required");
88
+ const reference = ConnectionRefSchema.parse({ provider: ProviderID, name: connectionName });
89
+ const selected = project.configuration.connections.find((entry) => entry.connectorId === ConnectorID && entry.connectionName === connectionName);
90
+ if (!selected || selected.provider !== ProviderID) throw new TypeError("project connection is not configured");
91
+ return newConnection(createClient(project, connectionName), reference);
92
+ }
93
+
94
+ export {
95
+ ConfigSchema,
96
+ decodeCredentials,
97
+ GetItemInputSchema,
98
+ ItemResultSchema,
99
+ ConnectorID,
100
+ ProviderID,
101
+ GetItemBranch,
102
+ GetItemBranchFound,
103
+ GetItemBranchMissing,
104
+ GetItemBranchProviderRejected,
105
+ GetItemBranchInvalidResponse,
106
+ GetItemBranchDefect,
107
+ GetItemDefinition,
108
+ GetItemMetadata,
109
+ Connection,
110
+ newConnection,
111
+ newConnectionWithOperations,
112
+ newProjectConnection
113
+ };
@@ -0,0 +1,81 @@
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
+ /** AWS Region code for the table, such as eu-west-1. In https://console.aws.amazon.com/dynamodb > Tables, use the console Region selector; blank uses the displayed default. */
7
+ region?: string;
8
+ /** Optional DynamoDB-compatible API root. Blank derives the regional AWS endpoint from region. Override only for a trusted compatible endpoint; local tests may use loopback HTTP. */
9
+ endpoint?: string;
10
+ /** Maximum duration of one GetItem request as a positive Go duration such as 15s. Blank uses the displayed default; increase only for a slow network. Runtime value in milliseconds. */
11
+ timeoutMs?: number;
12
+ /** Maximum complete item response in bytes. Blank uses the displayed default; increase only for unusually large items. */
13
+ maxResponseBytes?: number;
14
+ }
15
+ /** Runtime schema for manifest configuration. */
16
+ declare const ConfigSchema: z.ZodObject<{
17
+ region: z.ZodOptional<z.ZodString>;
18
+ endpoint: z.ZodOptional<z.ZodString>;
19
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
20
+ maxResponseBytes: z.ZodOptional<z.ZodNumber>;
21
+ }, z.core.$strip>;
22
+ /** Private connector credentials resolved by the host. */
23
+ interface Credentials {
24
+ /** Secret-stored AWS access key ID from https://console.aws.amazon.com/iam > Users > selected user > Security credentials > Access keys > Create access key. Long-term IDs start AKIA and temporary IDs start ASIA. Blank prevents signing. */
25
+ accessKeyId: SecretString;
26
+ /** Secret access key paired with access_key_id, shown once on the IAM Retrieve access keys page. Copy the Value, never the key ID. Blank prevents signing; rotate through IAM. */
27
+ secretAccessKey: SecretString;
28
+ /** Secret session token for temporary ASIA credentials, from AWS STS. Blank means long-term IAM user credentials. Temporary credentials expire; replace all three fields before expiry. */
29
+ sessionToken?: SecretString;
30
+ }
31
+ /** Decode private credential fields for the connector. */
32
+ declare function decodeCredentials(value: unknown): Credentials;
33
+ /** Host-owned source of private connector credentials. */
34
+ type CredentialSource = CredentialProvider<Credentials>;
35
+ /** GetItemInput identifies a table row by all of its S, N, or B key attributes. */
36
+ interface GetItemInput {
37
+ "tableName": string;
38
+ "key": {
39
+ [key: string]: unknown | null;
40
+ } | null;
41
+ "consistentRead": boolean;
42
+ }
43
+ /** ItemResult returns the item's AttributeValue map when it exists. */
44
+ interface ItemResult {
45
+ "exists": boolean;
46
+ "item": {
47
+ [key: string]: unknown | null;
48
+ } | null;
49
+ }
50
+ /** Runtime validator for GetItemInput. */
51
+ declare const GetItemInputSchema: z.ZodObject<{
52
+ tableName: z.ZodString;
53
+ key: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodUnknown>>>;
54
+ consistentRead: z.ZodBoolean;
55
+ }, z.core.$strict>;
56
+ /** Runtime validator for ItemResult. */
57
+ declare const ItemResultSchema: z.ZodObject<{
58
+ exists: z.ZodBoolean;
59
+ item: z.ZodNullable<z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodUnknown>>>;
60
+ }, z.core.$strict>;
61
+
62
+ /** Typed operations supplied by a client or mock. */
63
+ interface Operations {
64
+ /** Invoke getItem through this connection. */
65
+ getItem(): Query<GetItemInput, ItemResult>;
66
+ }
67
+ /** Named connector connection kept outside Flow state. */
68
+ declare class Connection<BoundOperations = Operations> {
69
+ /** Stable provider and connection name. */
70
+ readonly reference: ConnectionRef;
71
+ /** Bound provider operations. */
72
+ readonly operations: BoundOperations;
73
+ /** Validate a reference and bind operations. */
74
+ constructor(reference: ConnectionRef, operations: BoundOperations);
75
+ }
76
+ /** Bind a client to a named connection. */
77
+ declare function newConnection(client: Operations, reference: ConnectionRef): Connection;
78
+ /** Bind scripted operations to a named connection. */
79
+ declare function newConnectionWithOperations(operations: Operations, reference: ConnectionRef): Connection;
80
+
81
+ export { Connection as C, type GetItemInput as G, type ItemResult as I, type Operations as O, type Config as a, type Credentials as b, ConfigSchema as c, type CredentialSource as d, GetItemInputSchema as e, ItemResultSchema as f, decodeCredentials as g, newConnectionWithOperations as h, newConnection as n };
@@ -0,0 +1,100 @@
1
+ import { G as GetItemInput, I as ItemResult, C as Connection, O as Operations, a as Config, b as Credentials } from './connection-DjOgB3k-.js';
2
+ export { c as ConfigSchema, d as CredentialSource, e as GetItemInputSchema, f as ItemResultSchema, g as decodeCredentials, n as newConnection, h as newConnectionWithOperations } from './connection-DjOgB3k-.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 = "amazon-dynamodb";
11
+ /** Provider identity for named connections. */
12
+ declare const ProviderID = "amazon-dynamodb";
13
+ /** Branch IDs for getItem. */
14
+ declare const GetItemBranch: {
15
+ readonly Found: "found";
16
+ readonly Missing: "missing";
17
+ readonly ProviderRejected: "providerRejected";
18
+ readonly InvalidResponse: "invalidResponse";
19
+ readonly Defect: "defect";
20
+ };
21
+ /** DynamoDB returned the item. */
22
+ declare const GetItemBranchFound: "found";
23
+ /** The table has no item with that key. */
24
+ declare const GetItemBranchMissing: "missing";
25
+ /** DynamoDB conclusively rejected the request or credentials. */
26
+ declare const GetItemBranchProviderRejected: "providerRejected";
27
+ /** DynamoDB returned malformed or oversized item JSON. */
28
+ declare const GetItemBranchInvalidResponse: "invalidResponse";
29
+ /** The table, key, endpoint, Region, or credentials are invalid. */
30
+ declare const GetItemBranchDefect: "defect";
31
+ /** Manifest definition for getItem. */
32
+ declare const GetItemDefinition: QueryDefinition;
33
+ /** Manifest metadata for getItem. */
34
+ declare const GetItemMetadata: {
35
+ readonly kind: "query";
36
+ readonly idempotency: "none";
37
+ readonly authorization: "required";
38
+ };
39
+
40
+ /** Configuration for the getItem connector Step. */
41
+ interface GetItemStepConfig<StepInput, OperationInput = GetItemInput, OperationOutput = ItemResult> extends Omit<QueryStepConfig<StepInput, OperationInput, OperationOutput>, 'operation' | 'connection' | 'branches'> {
42
+ /** Named connection supplying this operation. */
43
+ connection: Connection<{
44
+ getItem(): Query<OperationInput, OperationOutput>;
45
+ }>;
46
+ /** Name matching the bound connection. */
47
+ connectionName: string;
48
+ /** DynamoDB returned the item. */
49
+ found: StepTarget<QueryResult<OperationOutput>>;
50
+ /** The table has no item with that key. */
51
+ missing?: StepTarget<QueryResult<OperationOutput>>;
52
+ /** DynamoDB conclusively rejected the request or credentials. */
53
+ providerRejected?: StepTarget<QueryResult<OperationOutput>>;
54
+ /** DynamoDB returned malformed or oversized item JSON. */
55
+ invalidResponse?: StepTarget<QueryResult<OperationOutput>>;
56
+ /** The table, key, endpoint, Region, or credentials are invalid. */
57
+ defect?: StepTarget<QueryResult<OperationOutput>>;
58
+ }
59
+ /** Build the getItem Step from a named connection. */
60
+ declare function newGetItemStep<StepInput, OperationInput = GetItemInput, OperationOutput = ItemResult>(configuration: GetItemStepConfig<StepInput, OperationInput, OperationOutput>): QueryStep<StepInput, OperationInput, OperationOutput>;
61
+
62
+ /** Open one named Amazon DynamoDB connection from Dex project configuration. */
63
+ declare function newProjectConnection(project: LoadedProject, connectionName: string): Connection<Operations>;
64
+
65
+ /** Injectable transport and clock for tests and local applications. */
66
+ interface AmazonDynamoDBClientOptions {
67
+ /** Provider sender; omitted uses the SDK transport. */ send?: (request: ProviderRequest) => Promise<ProviderResponse>;
68
+ /** Signing clock; omitted uses the current time. */ now?: () => Date;
69
+ }
70
+ interface Exchange {
71
+ status: number;
72
+ body: Uint8Array;
73
+ retryAfterMs: number;
74
+ error?: 'credential' | 'request' | 'tooLarge';
75
+ }
76
+ /** Authenticated DynamoDB client for signed GetItem requests. */
77
+ declare class AmazonDynamoDBClient {
78
+ private readonly credentials;
79
+ private readonly endpoint;
80
+ private readonly region;
81
+ private readonly timeoutMs;
82
+ private readonly maxResponseBytes;
83
+ private readonly send;
84
+ private readonly now;
85
+ /** Validate the Region, endpoint, and limits without contacting AWS. */
86
+ constructor(config: Config, credentials: CredentialProvider<Credentials>, options?: AmazonDynamoDBClientOptions);
87
+ /** Bind the getItem Query. */ getItem(): GetItemOperation;
88
+ /** Sign and send one bounded GetItem request. */
89
+ readItem(call: Call, body: Buffer): Promise<Exchange>;
90
+ }
91
+ /** Read one item by its complete primary key. */
92
+ declare class GetItemOperation implements Query<GetItemInput, ItemResult> {
93
+ private readonly client;
94
+ /** Bind the provider client. */ constructor(client: AmazonDynamoDBClient);
95
+ /** Return the generated Query contract. */ definition(): QueryDefinition;
96
+ /** Classify provider outcomes consistently with the Go implementation. */
97
+ invoke(call: Call, input: GetItemInput): Promise<QueryAttempt<ItemResult>>;
98
+ }
99
+
100
+ export { AmazonDynamoDBClient, type AmazonDynamoDBClientOptions, Config, Connection, ConnectorID, Credentials, GetItemBranch, GetItemBranchDefect, GetItemBranchFound, GetItemBranchInvalidResponse, GetItemBranchMissing, GetItemBranchProviderRejected, GetItemDefinition, GetItemInput, GetItemMetadata, GetItemOperation, type GetItemStepConfig, ItemResult, ProviderID, newGetItemStep, newProjectConnection };
package/dist/index.js ADDED
@@ -0,0 +1,288 @@
1
+ import {
2
+ ConfigSchema,
3
+ Connection,
4
+ ConnectorID,
5
+ GetItemBranch,
6
+ GetItemBranchDefect,
7
+ GetItemBranchFound,
8
+ GetItemBranchInvalidResponse,
9
+ GetItemBranchMissing,
10
+ GetItemBranchProviderRejected,
11
+ GetItemDefinition,
12
+ GetItemInputSchema,
13
+ GetItemMetadata,
14
+ ItemResultSchema,
15
+ ProviderID,
16
+ decodeCredentials,
17
+ newConnection,
18
+ newConnectionWithOperations,
19
+ newProjectConnection
20
+ } from "./chunk-JOLOQV45.js";
21
+
22
+ // src/generated/steps.ts
23
+ import { goToBranch, newQueryStep } from "@superdurable/connectors-sdk";
24
+ function newGetItemStep(configuration) {
25
+ const { connection, connectionName, found, missing, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
26
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
27
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getItem(), connection: connection.reference, branches: [
28
+ goToBranch("found", found),
29
+ ...missing ? [goToBranch("missing", missing)] : [],
30
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
31
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
32
+ ...defect ? [goToBranch("defect", defect)] : []
33
+ ] });
34
+ }
35
+
36
+ // src/project.ts
37
+ import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
38
+ import { z } from "zod";
39
+
40
+ // src/client.ts
41
+ import { createHash, createHmac } from "crypto";
42
+ import { SecretString, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
43
+ import { BodyTooLargeError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
44
+ var emptyItem = () => ({ exists: false, item: {} });
45
+ var regionPattern = /^[a-z]{2}(?:-gov)?-[a-z]+-[0-9]+$/;
46
+ var tablePattern = /^[A-Za-z0-9_.-]{3,255}$/;
47
+ var numberPattern = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[Ee][+-]?[0-9]+)?$/;
48
+ var AmazonDynamoDBClient = class {
49
+ /** Validate the Region, endpoint, and limits without contacting AWS. */
50
+ constructor(config, credentials, options = {}) {
51
+ this.credentials = credentials;
52
+ if (!config || !credentials) throw new TypeError("DynamoDB configuration and credentials are required");
53
+ this.region = config.region || "us-east-1";
54
+ if (!regionPattern.test(this.region)) throw new TypeError("DynamoDB Region is invalid");
55
+ this.endpoint = validateBaseURL(config.endpoint || `https://dynamodb.${this.region}.amazonaws.com`).replace(/\/+$/, "");
56
+ this.timeoutMs = config.timeoutMs || 15e3;
57
+ this.maxResponseBytes = config.maxResponseBytes || 2097152;
58
+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0)
59
+ throw new TypeError("DynamoDB request limits must be positive integers");
60
+ this.send = options.send ?? sendProviderRequest;
61
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
62
+ }
63
+ credentials;
64
+ endpoint;
65
+ region;
66
+ timeoutMs;
67
+ maxResponseBytes;
68
+ send;
69
+ now;
70
+ /** Bind the getItem Query. */
71
+ getItem() {
72
+ return new GetItemOperation(this);
73
+ }
74
+ /** Sign and send one bounded GetItem request. */
75
+ async readItem(call, body) {
76
+ let accessKey;
77
+ let secretKey;
78
+ let sessionToken;
79
+ try {
80
+ const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
81
+ accessKey = credentials.accessKeyId instanceof SecretString ? credentials.accessKeyId.reveal() : "";
82
+ secretKey = credentials.secretAccessKey instanceof SecretString ? credentials.secretAccessKey.reveal() : "";
83
+ sessionToken = credentials.sessionToken instanceof SecretString ? credentials.sessionToken.reveal() : "";
84
+ } catch {
85
+ return emptyExchange("credential");
86
+ }
87
+ if (!accessKey || !secretKey || !isHeaderSafeCredential(accessKey) || !isHeaderSafeCredential(secretKey) || sessionToken && !isHeaderSafeCredential(sessionToken)) return emptyExchange("credential");
88
+ const url = `${this.endpoint}/`;
89
+ const timestamp = this.now().toISOString().replace(/[-:]|\.\d{3}/g, "");
90
+ const day = timestamp.slice(0, 8);
91
+ const headersForSignature = {
92
+ "content-length": String(body.length),
93
+ "content-type": "application/x-amz-json-1.0",
94
+ host: new URL(url).host,
95
+ "x-amz-date": timestamp,
96
+ "x-amz-target": "DynamoDB_20120810.GetItem"
97
+ };
98
+ if (sessionToken) headersForSignature["x-amz-security-token"] = sessionToken;
99
+ const signedHeaders = Object.keys(headersForSignature).sort().join(";");
100
+ const canonicalHeaders = Object.entries(headersForSignature).sort(([left], [right]) => left.localeCompare(right)).map(([name, value]) => `${name}:${value.trim()}
101
+ `).join("");
102
+ const payloadHash = createHash("sha256").update(body).digest("hex");
103
+ const canonicalRequest = `POST
104
+ /
105
+
106
+ ${canonicalHeaders}
107
+ ${signedHeaders}
108
+ ${payloadHash}`;
109
+ const scope = `${day}/${this.region}/dynamodb/aws4_request`;
110
+ const stringToSign = `AWS4-HMAC-SHA256
111
+ ${timestamp}
112
+ ${scope}
113
+ ${createHash("sha256").update(canonicalRequest).digest("hex")}`;
114
+ const hmac = (key, value) => createHmac("sha256", key).update(value).digest();
115
+ const signingKey = hmac(hmac(hmac(hmac(`AWS4${secretKey}`, day), this.region), "dynamodb"), "aws4_request");
116
+ const signature = createHmac("sha256", signingKey).update(stringToSign).digest("hex");
117
+ const headers = {
118
+ "Content-Type": headersForSignature["content-type"],
119
+ "X-Amz-Date": timestamp,
120
+ "X-Amz-Target": headersForSignature["x-amz-target"],
121
+ Authorization: `AWS4-HMAC-SHA256 Credential=${accessKey}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`
122
+ };
123
+ if (sessionToken) headers["X-Amz-Security-Token"] = sessionToken;
124
+ const request = {
125
+ url,
126
+ method: "POST",
127
+ headers,
128
+ body,
129
+ maxResponseBytes: this.maxResponseBytes,
130
+ timeoutMs: this.timeoutMs,
131
+ addressPolicy: this.endpoint.startsWith("https://") ? "publicHTTPS" : "privateNetworkHTTP",
132
+ signal: call.context.cancellationSignal
133
+ };
134
+ let response;
135
+ let isTooLarge = false;
136
+ try {
137
+ response = await this.send(request);
138
+ } catch (error) {
139
+ if (error instanceof BodyTooLargeError && error.status !== void 0) {
140
+ response = { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() };
141
+ isTooLarge = true;
142
+ } else return emptyExchange("request");
143
+ }
144
+ const retryAfterMs = parseRetryAfter(header(response.headers, "retry-after"));
145
+ if (isTooLarge || response.body.length > this.maxResponseBytes)
146
+ return { status: response.status, body: new Uint8Array(), retryAfterMs, error: "tooLarge" };
147
+ if ([accessKey, secretKey, sessionToken].some((secret) => secret && Buffer.from(response.body).includes(secret)))
148
+ return { ...emptyExchange("credential"), status: response.status, retryAfterMs };
149
+ return { status: response.status, body: response.body, retryAfterMs };
150
+ }
151
+ };
152
+ var GetItemOperation = class {
153
+ /** Bind the provider client. */
154
+ constructor(client) {
155
+ this.client = client;
156
+ }
157
+ client;
158
+ /** Return the generated Query contract. */
159
+ definition() {
160
+ return GetItemDefinition;
161
+ }
162
+ /** Classify provider outcomes consistently with the Go implementation. */
163
+ async invoke(call, input) {
164
+ if (!input || typeof input.tableName !== "string" || !tablePattern.test(input.tableName) || !validKey(input.key))
165
+ return terminal("defect", "VALIDATION", "DynamoDB table or key is invalid");
166
+ const sortedKey = Object.fromEntries(Object.entries(input.key).sort(([left], [right]) => left.localeCompare(right)));
167
+ const body = Buffer.from(JSON.stringify({ TableName: input.tableName, Key: sortedKey, ConsistentRead: input.consistentRead }));
168
+ const exchange = await this.client.readItem(call, body);
169
+ if (exchange.error === "credential") return terminal("defect", "AUTHENTICATION", "DynamoDB credentials are unavailable or invalid");
170
+ if (exchange.error === "request") return retry("TRANSPORT", "DynamoDB request failed");
171
+ if (exchange.status === 429 || exchange.status !== 200 && isThrottled(exchange.body)) return retry("RATE_LIMIT", "DynamoDB rate limited the request", exchange.retryAfterMs);
172
+ if (exchange.status === 408 || exchange.status >= 500) return retry("AVAILABILITY", "DynamoDB is temporarily unavailable", exchange.retryAfterMs);
173
+ if (exchange.status !== 200) return terminal("providerRejected", "PROVIDER_REJECTION", `DynamoDB rejected HTTP ${exchange.status}`);
174
+ if (exchange.error === "tooLarge") return terminal("invalidResponse", "RESPONSE_TOO_LARGE", "DynamoDB response exceeded the configured limit");
175
+ let document;
176
+ try {
177
+ document = JSON.parse(Buffer.from(exchange.body).toString("utf8"));
178
+ } catch {
179
+ return terminal("invalidResponse", "PROTOCOL", "DynamoDB returned invalid item JSON");
180
+ }
181
+ if (!isObject(document)) return terminal("invalidResponse", "PROTOCOL", "DynamoDB returned invalid item JSON");
182
+ const item = document.Item;
183
+ if (item === void 0 || item === null || isObject(item) && Object.keys(item).length === 0) return newQueryBranch("missing", emptyItem());
184
+ if (!isObject(item) || Object.entries(item).some(([name, value]) => !name || !isObject(value) || Object.keys(value).length !== 1))
185
+ return terminal("invalidResponse", "PROTOCOL", "DynamoDB returned invalid item JSON");
186
+ return newQueryBranch("found", { exists: true, item });
187
+ }
188
+ };
189
+ function validKey(key) {
190
+ if (!isObject(key) || ![1, 2].includes(Object.keys(key).length)) return false;
191
+ return Object.entries(key).every(([name, attribute]) => {
192
+ if (!name || name.length > 255 || [...name].some((character) => character.charCodeAt(0) === 0 || character === "\r" || character === "\n") || !isObject(attribute) || Object.keys(attribute).length !== 1) return false;
193
+ const [kind, value] = Object.entries(attribute)[0];
194
+ if (typeof value !== "string" || !value) return false;
195
+ if (kind === "S") return true;
196
+ if (kind === "N") return numberPattern.test(value);
197
+ if (kind === "B") return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value);
198
+ return false;
199
+ });
200
+ }
201
+ function isObject(value) {
202
+ return typeof value === "object" && value !== null && !Array.isArray(value);
203
+ }
204
+ function isThrottled(body) {
205
+ try {
206
+ const document = JSON.parse(Buffer.from(body).toString("utf8"));
207
+ if (!isObject(document) || typeof document.__type !== "string") return false;
208
+ return ["ProvisionedThroughputExceededException", "ThrottlingException", "RequestLimitExceeded", "TransactionConflictException"].includes(document.__type.split("#").at(-1) ?? "");
209
+ } catch {
210
+ return false;
211
+ }
212
+ }
213
+ function emptyExchange(error) {
214
+ return { status: 0, body: new Uint8Array(), retryAfterMs: 0, error };
215
+ }
216
+ function failure(kind, message) {
217
+ return { provider: "amazon-dynamodb", operation: "getItem", kind, message };
218
+ }
219
+ function terminal(branch, kind, message) {
220
+ return newQueryBranch(branch, emptyItem(), {}, failure(kind, message));
221
+ }
222
+ function retry(kind, message, delay = 0) {
223
+ return newQueryRetry(failure(kind, message), delay);
224
+ }
225
+ function header(headers, name) {
226
+ const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
227
+ return Array.isArray(entry) ? entry[0] ?? "" : entry ?? "";
228
+ }
229
+
230
+ // src/project.ts
231
+ function newProjectConnection2(project, connectionName) {
232
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
233
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "amazon-dynamodb" && entry.connectionName === name);
234
+ if (!selected) throw new TypeError("Amazon DynamoDB project connection is not configured");
235
+ const fields = z.strictObject({ region: z.string().optional(), endpoint: z.string().optional(), timeout: z.union([z.string(), z.number().int()]).optional(), maxResponseBytes: z.number().int().optional() }).parse(selected.configuration);
236
+ const timeoutMs = typeof fields.timeout === "number" ? Math.ceil(fields.timeout / 1e6) : fields.timeout ? parseDurationMilliseconds(fields.timeout) : void 0;
237
+ const config = {
238
+ ...fields.region ? { region: fields.region } : {},
239
+ ...fields.endpoint ? { endpoint: fields.endpoint } : {},
240
+ ...timeoutMs !== void 0 ? { timeoutMs } : {},
241
+ ...fields.maxResponseBytes !== void 0 ? { maxResponseBytes: fields.maxResponseBytes } : {}
242
+ };
243
+ const credentials = {
244
+ async resolve(_call, signal) {
245
+ const privateFields = await loadedProject.resolveCredential("amazon-dynamodb", name, signal);
246
+ if (typeof privateFields.access_key_id !== "string" || typeof privateFields.secret_access_key !== "string") throw new TypeError("Amazon DynamoDB credentials are unavailable");
247
+ return { accessKeyId: new SecretString2(privateFields.access_key_id), secretAccessKey: new SecretString2(privateFields.secret_access_key), sessionToken: new SecretString2(typeof privateFields.session_token === "string" ? privateFields.session_token : "") };
248
+ }
249
+ };
250
+ return new AmazonDynamoDBClient(config, credentials);
251
+ });
252
+ }
253
+ function parseDurationMilliseconds(value) {
254
+ let remaining = value;
255
+ let milliseconds = 0;
256
+ const units = { ns: 1e-6, us: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
257
+ while (remaining) {
258
+ const part = /^(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/.exec(remaining);
259
+ if (!part) throw new TypeError("Amazon DynamoDB timeout must be a positive Go duration");
260
+ milliseconds += Number(part[1]) * (units[part[2] ?? ""] ?? NaN);
261
+ remaining = remaining.slice(part[0].length);
262
+ }
263
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) throw new TypeError("Amazon DynamoDB timeout must resolve to positive whole milliseconds");
264
+ return milliseconds;
265
+ }
266
+ export {
267
+ AmazonDynamoDBClient,
268
+ ConfigSchema,
269
+ Connection,
270
+ ConnectorID,
271
+ GetItemBranch,
272
+ GetItemBranchDefect,
273
+ GetItemBranchFound,
274
+ GetItemBranchInvalidResponse,
275
+ GetItemBranchMissing,
276
+ GetItemBranchProviderRejected,
277
+ GetItemDefinition,
278
+ GetItemInputSchema,
279
+ GetItemMetadata,
280
+ GetItemOperation,
281
+ ItemResultSchema,
282
+ ProviderID,
283
+ decodeCredentials,
284
+ newConnection,
285
+ newConnectionWithOperations,
286
+ newGetItemStep,
287
+ newProjectConnection2 as newProjectConnection
288
+ };
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, G as GetItemInput, I as ItemResult } from './connection-DjOgB3k-.js';
4
+ import 'zod';
5
+
6
+ /** Go zero value for GetItemInput in scripted cases. */
7
+ declare const emptyGetItemInput: GetItemInput;
8
+ /** Go zero value for ItemResult in scripted cases. */
9
+ declare const emptyItemResult: ItemResult;
10
+ /** Script the found branch. */
11
+ declare function getItemFound(value: ItemResult, failure?: Failure): Case<ItemResult>;
12
+ /** Script the missing branch. */
13
+ declare function getItemMissing(value: ItemResult, failure?: Failure): Case<ItemResult>;
14
+ /** Script the providerRejected branch. */
15
+ declare function getItemProviderRejected(value: ItemResult, failure?: Failure): Case<ItemResult>;
16
+ /** Script the invalidResponse branch. */
17
+ declare function getItemInvalidResponse(value: ItemResult, failure?: Failure): Case<ItemResult>;
18
+ /** Script the defect branch. */
19
+ declare function getItemDefect(value: ItemResult, failure?: Failure): Case<ItemResult>;
20
+ /** Script a safe retry of getItem. */
21
+ declare function getItemRetry(failure: Failure, retryAfterMs?: number): Case<ItemResult>;
22
+ /** Manifest scenario foundDefault for getItem. */
23
+ declare function getItemFoundDefault(): Case<ItemResult>;
24
+ /** Default getItem scenario. */
25
+ declare function getItemDefault(): Case<ItemResult>;
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
+ getItem(): MockQuery<GetItemInput, ItemResult>;
32
+ assertNoFailures(): void;
33
+ }
34
+
35
+ export { GeneratedMock, GeneratedMock as Mock, emptyGetItemInput, emptyItemResult, getItemDefault, getItemDefect, getItemFound, getItemFoundDefault, getItemInvalidResponse, getItemMissing, getItemProviderRejected, getItemRetry };
package/dist/mock.js ADDED
@@ -0,0 +1,75 @@
1
+ import {
2
+ GetItemDefinition,
3
+ GetItemInputSchema,
4
+ ItemResultSchema,
5
+ ProviderID,
6
+ newConnectionWithOperations
7
+ } from "./chunk-JOLOQV45.js";
8
+
9
+ // src/generated/mock.ts
10
+ import { branchCase, retryCase, newQuery } from "@superdurable/connectors-sdk/connectormock";
11
+ var emptyGetItemInput = GetItemInputSchema.parse({
12
+ "tableName": "",
13
+ "key": {},
14
+ "consistentRead": false
15
+ });
16
+ var emptyItemResult = ItemResultSchema.parse({
17
+ "exists": false,
18
+ "item": {}
19
+ });
20
+ function getItemFound(value, failure) {
21
+ return branchCase("found", value, failure);
22
+ }
23
+ function getItemMissing(value, failure) {
24
+ return branchCase("missing", value, failure);
25
+ }
26
+ function getItemProviderRejected(value, failure) {
27
+ return branchCase("providerRejected", value, failure);
28
+ }
29
+ function getItemInvalidResponse(value, failure) {
30
+ return branchCase("invalidResponse", value, failure);
31
+ }
32
+ function getItemDefect(value, failure) {
33
+ return branchCase("defect", value, failure);
34
+ }
35
+ function getItemRetry(failure, retryAfterMs = 0) {
36
+ return retryCase(failure, retryAfterMs);
37
+ }
38
+ function getItemFoundDefault() {
39
+ const value = ItemResultSchema.parse({ "exists": true, "item": { "pk": { "S": "example" } } });
40
+ return branchCase("found", value);
41
+ }
42
+ function getItemDefault() {
43
+ return getItemFoundDefault();
44
+ }
45
+ var GeneratedMock = class {
46
+ #getItem;
47
+ #connection;
48
+ constructor(connectionName) {
49
+ this.#getItem = newQuery(GetItemDefinition).default(getItemDefault());
50
+ this.#connection = newConnectionWithOperations(this, { provider: ProviderID, name: connectionName });
51
+ }
52
+ connection() {
53
+ return this.#connection;
54
+ }
55
+ getItem() {
56
+ return this.#getItem;
57
+ }
58
+ assertNoFailures() {
59
+ this.#getItem.assertNoFailures();
60
+ }
61
+ };
62
+ export {
63
+ GeneratedMock,
64
+ GeneratedMock as Mock,
65
+ emptyGetItemInput,
66
+ emptyItemResult,
67
+ getItemDefault,
68
+ getItemDefect,
69
+ getItemFound,
70
+ getItemFoundDefault,
71
+ getItemInvalidResponse,
72
+ getItemMissing,
73
+ getItemProviderRejected,
74
+ getItemRetry
75
+ };
package/package.json CHANGED
@@ -1,6 +1,61 @@
1
1
  {
2
2
  "name": "@superdurable/connector-amazon-dynamodb",
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": "Amazon DynamoDB connector for Dex TypeScript applications",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/superdurable/dex-connectors-library.git",
9
+ "directory": "connectors/amazon/dynamodb/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/item-lookup/worker.ts",
42
+ "example:start": "tsx examples/item-lookup/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
+ }