@superdurable/connector-amazon-dynamodb 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/dist/index.js ADDED
@@ -0,0 +1,635 @@
1
+ import {
2
+ ConfigSchema,
3
+ Connection,
4
+ ConnectorID,
5
+ CredentialMaterialError,
6
+ DeleteItemBranch,
7
+ DeleteItemBranchDefect,
8
+ DeleteItemBranchDeleted,
9
+ DeleteItemBranchInvalidResponse,
10
+ DeleteItemBranchProviderRejected,
11
+ DeleteItemDefinition,
12
+ DeleteItemInputSchema,
13
+ DeleteItemMetadata,
14
+ GetItemBranch,
15
+ GetItemBranchDefect,
16
+ GetItemBranchFound,
17
+ GetItemBranchInvalidResponse,
18
+ GetItemBranchMissing,
19
+ GetItemBranchProviderRejected,
20
+ GetItemDefinition,
21
+ GetItemInputSchema,
22
+ GetItemMetadata,
23
+ ItemPageSchema,
24
+ ItemResultSchema,
25
+ ItemWriteResultSchema,
26
+ ProviderID,
27
+ PutItemBranch,
28
+ PutItemBranchDefect,
29
+ PutItemBranchInvalidResponse,
30
+ PutItemBranchProviderRejected,
31
+ PutItemBranchWritten,
32
+ PutItemDefinition,
33
+ PutItemInputSchema,
34
+ PutItemMetadata,
35
+ ScanItemsBranch,
36
+ ScanItemsBranchDefect,
37
+ ScanItemsBranchInvalidResponse,
38
+ ScanItemsBranchProviderRejected,
39
+ ScanItemsBranchScanned,
40
+ ScanItemsDefinition,
41
+ ScanItemsInputSchema,
42
+ ScanItemsMetadata,
43
+ UpdateItemBranch,
44
+ UpdateItemBranchDefect,
45
+ UpdateItemBranchInvalidResponse,
46
+ UpdateItemBranchProviderRejected,
47
+ UpdateItemBranchUpdated,
48
+ UpdateItemDefinition,
49
+ UpdateItemInputSchema,
50
+ UpdateItemMetadata,
51
+ decodeCredentials,
52
+ isCredentialMaterialError,
53
+ newConnection,
54
+ newConnectionWithOperations,
55
+ newProjectConnection
56
+ } from "./chunk-NNCKP6U7.js";
57
+
58
+ // src/generated/steps.ts
59
+ import { goToBranch, newMutationStep, newQueryStep } from "@superdurable/connectors-sdk";
60
+ function newGetItemStep(configuration) {
61
+ const { connection, connectionName, found, missing, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
62
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
63
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.getItem(), connection: connection.reference, branches: [
64
+ goToBranch("found", found),
65
+ ...missing ? [goToBranch("missing", missing)] : [],
66
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
67
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
68
+ ...defect ? [goToBranch("defect", defect)] : []
69
+ ] });
70
+ }
71
+ function newPutItemStep(configuration) {
72
+ const { connection, connectionName, written, providerRejected, invalidResponse, defect, maxSends, ...stepConfiguration } = configuration;
73
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
74
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.putItem(), connection: connection.reference, branches: [
75
+ goToBranch("written", written),
76
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
77
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
78
+ ...defect ? [goToBranch("defect", defect)] : []
79
+ ] });
80
+ }
81
+ function newUpdateItemStep(configuration) {
82
+ const { connection, connectionName, updated, providerRejected, invalidResponse, defect, maxSends, ...stepConfiguration } = configuration;
83
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
84
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.updateItem(), connection: connection.reference, branches: [
85
+ goToBranch("updated", updated),
86
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
87
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
88
+ ...defect ? [goToBranch("defect", defect)] : []
89
+ ] });
90
+ }
91
+ function newDeleteItemStep(configuration) {
92
+ const { connection, connectionName, deleted, providerRejected, invalidResponse, defect, maxSends, ...stepConfiguration } = configuration;
93
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
94
+ return newMutationStep({ ...stepConfiguration, operation: connection.operations.deleteItem(), connection: connection.reference, branches: [
95
+ goToBranch("deleted", deleted),
96
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
97
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
98
+ ...defect ? [goToBranch("defect", defect)] : []
99
+ ] });
100
+ }
101
+ function newScanItemsStep(configuration) {
102
+ const { connection, connectionName, scanned, providerRejected, invalidResponse, defect, ...stepConfiguration } = configuration;
103
+ if (!connection || connection.reference.name !== connectionName) throw new TypeError("Step connection name differs from the bound connection");
104
+ return newQueryStep({ ...stepConfiguration, operation: connection.operations.scanItems(), connection: connection.reference, branches: [
105
+ goToBranch("scanned", scanned),
106
+ ...providerRejected ? [goToBranch("providerRejected", providerRejected)] : [],
107
+ ...invalidResponse ? [goToBranch("invalidResponse", invalidResponse)] : [],
108
+ ...defect ? [goToBranch("defect", defect)] : []
109
+ ] });
110
+ }
111
+
112
+ // src/project.ts
113
+ import { SecretString as SecretString2 } from "@superdurable/connectors-sdk";
114
+ import { z } from "zod";
115
+
116
+ // src/client.ts
117
+ import { createHash, createHmac } from "crypto";
118
+ import { SecretString, newMutationBranch, newMutationRetry, newQueryBranch, newQueryRetry } from "@superdurable/connectors-sdk";
119
+ import { BodyTooLargeError, ProviderStalledError, ProviderTransportError, isHeaderSafeCredential, parseRetryAfter, sendProviderRequest, validateBaseURL } from "@superdurable/connectors-sdk/providerhttp";
120
+ var emptyItem = () => ({ exists: false, item: {} });
121
+ var regionPattern = /^[a-z]{2}(?:-gov)?-[a-z]+-[0-9]+$/;
122
+ var tablePattern = /^[A-Za-z0-9_.-]{3,255}$/;
123
+ var numberPattern = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[Ee][+-]?[0-9]+)?$/;
124
+ var AmazonDynamoDBClient = class {
125
+ /** Validate the Region, endpoint, and limits without contacting AWS. */
126
+ constructor(config, credentials, options = {}) {
127
+ this.credentials = credentials;
128
+ if (!config || !credentials) throw new TypeError("DynamoDB configuration and credentials are required");
129
+ this.region = config.region || "us-east-1";
130
+ if (!regionPattern.test(this.region)) throw new TypeError("DynamoDB Region is invalid");
131
+ this.endpoint = validateBaseURL(config.endpoint || `https://dynamodb.${this.region}.amazonaws.com`).replace(/\/+$/, "");
132
+ this.timeoutMs = config.timeoutMs || 15e3;
133
+ this.maxResponseBytes = config.maxResponseBytes || 2097152;
134
+ if (!Number.isSafeInteger(this.timeoutMs) || this.timeoutMs <= 0 || !Number.isSafeInteger(this.maxResponseBytes) || this.maxResponseBytes <= 0)
135
+ throw new TypeError("DynamoDB request limits must be positive integers");
136
+ this.send = options.send ?? sendProviderRequest;
137
+ this.now = options.now ?? (() => /* @__PURE__ */ new Date());
138
+ }
139
+ credentials;
140
+ endpoint;
141
+ region;
142
+ timeoutMs;
143
+ maxResponseBytes;
144
+ send;
145
+ now;
146
+ /** Bind the getItem Query. */
147
+ getItem() {
148
+ return new GetItemOperation(this);
149
+ }
150
+ /** Bind the complete replacement Mutation. */
151
+ putItem() {
152
+ return new PutItemOperation(this);
153
+ }
154
+ /** Bind the absolute update Mutation. */
155
+ updateItem() {
156
+ return new UpdateItemOperation(this);
157
+ }
158
+ /** Bind the repeat-safe delete Mutation. */
159
+ deleteItem() {
160
+ return new DeleteItemOperation(this);
161
+ }
162
+ /** Bind the bounded scan Query. */
163
+ scanItems() {
164
+ return new ScanItemsOperation(this);
165
+ }
166
+ /** Sign and send one bounded GetItem request. */
167
+ async readItem(call, body) {
168
+ return this.sendItemRequest(call, "GetItem", body);
169
+ }
170
+ /** Sign and send one bounded DynamoDB request using the configured endpoint and Region. */
171
+ async sendItemRequest(call, target, body) {
172
+ let accessKey;
173
+ let secretKey;
174
+ let sessionToken;
175
+ try {
176
+ const credentials = await this.credentials.resolve(call, call.context.cancellationSignal);
177
+ accessKey = credentials.accessKeyId instanceof SecretString ? credentials.accessKeyId.reveal() : "";
178
+ secretKey = credentials.secretAccessKey instanceof SecretString ? credentials.secretAccessKey.reveal() : "";
179
+ sessionToken = credentials.sessionToken instanceof SecretString ? credentials.sessionToken.reveal() : "";
180
+ } catch {
181
+ return emptyExchange("credential");
182
+ }
183
+ if (!accessKey || !secretKey || !isHeaderSafeCredential(accessKey) || !isHeaderSafeCredential(secretKey) || sessionToken && !isHeaderSafeCredential(sessionToken)) return emptyExchange("credential");
184
+ const url = `${this.endpoint}/`;
185
+ const timestamp = this.now().toISOString().replace(/[-:]|\.\d{3}/g, "");
186
+ const day = timestamp.slice(0, 8);
187
+ const headersForSignature = {
188
+ "content-length": String(body.length),
189
+ "content-type": "application/x-amz-json-1.0",
190
+ host: new URL(url).host,
191
+ "x-amz-date": timestamp,
192
+ "x-amz-target": `DynamoDB_20120810.${target}`
193
+ };
194
+ if (sessionToken) headersForSignature["x-amz-security-token"] = sessionToken;
195
+ const signedHeaders = Object.keys(headersForSignature).sort().join(";");
196
+ const canonicalHeaders = Object.entries(headersForSignature).sort(([left], [right]) => left.localeCompare(right)).map(([name, value]) => `${name}:${value.trim()}
197
+ `).join("");
198
+ const payloadHash = createHash("sha256").update(body).digest("hex");
199
+ const canonicalRequest = `POST
200
+ /
201
+
202
+ ${canonicalHeaders}
203
+ ${signedHeaders}
204
+ ${payloadHash}`;
205
+ const scope = `${day}/${this.region}/dynamodb/aws4_request`;
206
+ const stringToSign = `AWS4-HMAC-SHA256
207
+ ${timestamp}
208
+ ${scope}
209
+ ${createHash("sha256").update(canonicalRequest).digest("hex")}`;
210
+ const hmac = (key, value) => createHmac("sha256", key).update(value).digest();
211
+ const signingKey = hmac(hmac(hmac(hmac(`AWS4${secretKey}`, day), this.region), "dynamodb"), "aws4_request");
212
+ const signature = createHmac("sha256", signingKey).update(stringToSign).digest("hex");
213
+ const headers = {
214
+ "Content-Type": headersForSignature["content-type"],
215
+ "X-Amz-Date": timestamp,
216
+ "X-Amz-Target": headersForSignature["x-amz-target"],
217
+ Authorization: `AWS4-HMAC-SHA256 Credential=${accessKey}/${scope}, SignedHeaders=${signedHeaders}, Signature=${signature}`
218
+ };
219
+ if (sessionToken) headers["X-Amz-Security-Token"] = sessionToken;
220
+ const request = {
221
+ url,
222
+ method: "POST",
223
+ headers,
224
+ body,
225
+ maxResponseBytes: this.maxResponseBytes,
226
+ timeoutMs: this.timeoutMs,
227
+ addressPolicy: this.endpoint.startsWith("https://") ? "publicHTTPS" : "privateNetworkHTTP",
228
+ signal: call.context.cancellationSignal
229
+ };
230
+ let response;
231
+ let isTooLarge = false;
232
+ try {
233
+ response = await this.send(request);
234
+ } catch (error) {
235
+ if (error instanceof BodyTooLargeError && error.status !== void 0) {
236
+ response = { status: error.status, headers: error.headers ?? {}, body: new Uint8Array() };
237
+ isTooLarge = true;
238
+ } else if ((error instanceof ProviderTransportError || error instanceof ProviderStalledError) && error.status !== void 0) {
239
+ return { status: error.status, body: new Uint8Array(), retryAfterMs: parseRetryAfter(header(error.headers ?? {}, "retry-after")), error: "interrupted" };
240
+ } else return emptyExchange("request");
241
+ }
242
+ const retryAfterMs = parseRetryAfter(header(response.headers, "retry-after"));
243
+ if (isTooLarge || response.body.length > this.maxResponseBytes)
244
+ return { status: response.status, body: new Uint8Array(), retryAfterMs, error: "tooLarge" };
245
+ if ([accessKey, secretKey, sessionToken].some((secret) => secret && Buffer.from(response.body).includes(secret)))
246
+ return { ...emptyExchange("credential"), status: response.status, retryAfterMs };
247
+ return { status: response.status, body: response.body, retryAfterMs };
248
+ }
249
+ };
250
+ var GetItemOperation = class {
251
+ /** Bind the provider client. */
252
+ constructor(client) {
253
+ this.client = client;
254
+ }
255
+ client;
256
+ /** Return the generated Query contract. */
257
+ definition() {
258
+ return GetItemDefinition;
259
+ }
260
+ /** Classify provider outcomes consistently with the Go implementation. */
261
+ async invoke(call, input) {
262
+ if (!input || typeof input.tableName !== "string" || !tablePattern.test(input.tableName) || !validKey(input.key))
263
+ return terminal("defect", "VALIDATION", "DynamoDB table or key is invalid");
264
+ const sortedKey = Object.fromEntries(Object.entries(input.key).sort(([left], [right]) => left.localeCompare(right)));
265
+ const body = Buffer.from(JSON.stringify({ TableName: input.tableName, Key: sortedKey, ConsistentRead: input.consistentRead }));
266
+ const exchange = await this.client.readItem(call, body);
267
+ if (exchange.error === "credential") return terminal("defect", "AUTHENTICATION", "DynamoDB credentials are unavailable or invalid");
268
+ if (exchange.error === "request") return retry("TRANSPORT", "DynamoDB request failed");
269
+ if (exchange.status === 429 || exchange.status !== 200 && isThrottled(exchange.body)) return retry("RATE_LIMIT", "DynamoDB rate limited the request", exchange.retryAfterMs);
270
+ if (exchange.status === 408 || exchange.status >= 500) return retry("AVAILABILITY", "DynamoDB is temporarily unavailable", exchange.retryAfterMs);
271
+ if (exchange.status !== 200) return terminal("providerRejected", "PROVIDER_REJECTION", `DynamoDB rejected HTTP ${exchange.status}`);
272
+ if (exchange.error === "tooLarge") return terminal("invalidResponse", "RESPONSE_TOO_LARGE", "DynamoDB response exceeded the configured limit");
273
+ if (exchange.error === "interrupted") return retry("TRANSPORT", "DynamoDB response was interrupted");
274
+ let document;
275
+ try {
276
+ document = JSON.parse(Buffer.from(exchange.body).toString("utf8"));
277
+ } catch {
278
+ return terminal("invalidResponse", "PROTOCOL", "DynamoDB returned invalid item JSON");
279
+ }
280
+ if (!isObject(document)) return terminal("invalidResponse", "PROTOCOL", "DynamoDB returned invalid item JSON");
281
+ const item = document.Item;
282
+ if (item === void 0 || item === null || isObject(item) && Object.keys(item).length === 0) return newQueryBranch("missing", emptyItem());
283
+ if (!isObject(item) || Object.entries(item).some(([name, value]) => !name || !isObject(value) || Object.keys(value).length !== 1))
284
+ return terminal("invalidResponse", "PROTOCOL", "DynamoDB returned invalid item JSON");
285
+ return newQueryBranch("found", { exists: true, item });
286
+ }
287
+ };
288
+ function validKey(key) {
289
+ if (!isObject(key) || ![1, 2].includes(Object.keys(key).length)) return false;
290
+ return Object.entries(key).every(([name, attribute]) => {
291
+ if (!name || Buffer.byteLength(name) > 255 || [...name].some((character) => character.charCodeAt(0) === 0 || character === "\r" || character === "\n") || !isObject(attribute) || Object.keys(attribute).length !== 1) return false;
292
+ const [kind, value] = Object.entries(attribute)[0];
293
+ if (typeof value !== "string" || !value) return false;
294
+ if (kind === "S") return true;
295
+ if (kind === "N") return numberPattern.test(value);
296
+ if (kind === "B") return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value);
297
+ return false;
298
+ });
299
+ }
300
+ function isObject(value) {
301
+ return typeof value === "object" && value !== null && !Array.isArray(value);
302
+ }
303
+ function isThrottled(body) {
304
+ try {
305
+ const document = JSON.parse(Buffer.from(body).toString("utf8"));
306
+ if (!isObject(document) || typeof document.__type !== "string") return false;
307
+ return ["ProvisionedThroughputExceededException", "ThrottlingException", "RequestLimitExceeded", "TransactionConflictException"].includes(document.__type.split("#").at(-1) ?? "");
308
+ } catch {
309
+ return false;
310
+ }
311
+ }
312
+ function emptyExchange(error) {
313
+ return { status: 0, body: new Uint8Array(), retryAfterMs: 0, error };
314
+ }
315
+ function failure(kind, message) {
316
+ return { provider: "amazon-dynamodb", operation: "getItem", kind, message };
317
+ }
318
+ function terminal(branch, kind, message) {
319
+ return newQueryBranch(branch, emptyItem(), {}, failure(kind, message));
320
+ }
321
+ function retry(kind, message, delay = 0) {
322
+ return newQueryRetry(failure(kind, message), delay);
323
+ }
324
+ function header(headers, name) {
325
+ const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
326
+ return Array.isArray(entry) ? entry[0] ?? "" : entry ?? "";
327
+ }
328
+ var PutItemOperation = class {
329
+ /** Bind the provider client. */
330
+ constructor(client) {
331
+ this.client = client;
332
+ }
333
+ client;
334
+ /** Return the generated replacement contract. */
335
+ definition() {
336
+ return PutItemDefinition;
337
+ }
338
+ /** Correlate repeat-safe replacements with the Dex call. */
339
+ idempotencyKey(callId) {
340
+ return callId;
341
+ }
342
+ /** Replace the item using the supplied absolute values. */
343
+ async invoke(call, input) {
344
+ if (!tablePattern.test(input.tableName) || !validItem(input.item))
345
+ return invalidWrite("putItem", "DynamoDB table or item is invalid");
346
+ return writeItem(this.client, call, "putItem", "PutItem", "written", {
347
+ TableName: input.tableName,
348
+ Item: sortedMap(input.item)
349
+ });
350
+ }
351
+ };
352
+ var UpdateItemOperation = class {
353
+ /** Bind the provider client. */
354
+ constructor(client) {
355
+ this.client = client;
356
+ }
357
+ client;
358
+ /** Return the generated update contract. */
359
+ definition() {
360
+ return UpdateItemDefinition;
361
+ }
362
+ /** Correlate repeat-safe updates with the Dex call. */
363
+ idempotencyKey(callId) {
364
+ return callId;
365
+ }
366
+ /** Update the supplied attributes without changing the key. */
367
+ async invoke(call, input) {
368
+ const { tableName, key, attributes } = input;
369
+ if (!tablePattern.test(tableName) || !validKey(key) || !validItem(attributes))
370
+ return invalidWrite("updateItem", "DynamoDB table, key, or attributes are invalid");
371
+ const names = Object.keys(attributes).sort(compareUTF8);
372
+ if (names.some((name) => Object.hasOwn(key, name)))
373
+ return invalidWrite("updateItem", "DynamoDB key attributes cannot be updated");
374
+ const aliases = {};
375
+ const values = {};
376
+ const assignments = names.map((name, index) => {
377
+ const nameAlias = "#a" + index;
378
+ const valueAlias = ":v" + index;
379
+ aliases[nameAlias] = name;
380
+ values[valueAlias] = attributes[name];
381
+ return nameAlias + " = " + valueAlias;
382
+ });
383
+ return writeItem(this.client, call, "updateItem", "UpdateItem", "updated", {
384
+ TableName: tableName,
385
+ Key: sortedMap(key),
386
+ UpdateExpression: "SET " + assignments.join(", "),
387
+ ExpressionAttributeNames: sortedMap(aliases),
388
+ ExpressionAttributeValues: sortedMap(values)
389
+ });
390
+ }
391
+ };
392
+ var DeleteItemOperation = class {
393
+ /** Bind the provider client. */
394
+ constructor(client) {
395
+ this.client = client;
396
+ }
397
+ client;
398
+ /** Return the generated deletion contract. */
399
+ definition() {
400
+ return DeleteItemDefinition;
401
+ }
402
+ /** Correlate repeat-safe deletions with the Dex call. */
403
+ idempotencyKey(callId) {
404
+ return callId;
405
+ }
406
+ /** Delete the item or retry a temporary response. */
407
+ async invoke(call, input) {
408
+ if (!tablePattern.test(input.tableName) || !validKey(input.key))
409
+ return invalidWrite("deleteItem", "DynamoDB table or key is invalid");
410
+ return writeItem(this.client, call, "deleteItem", "DeleteItem", "deleted", {
411
+ TableName: input.tableName,
412
+ Key: sortedMap(input.key)
413
+ });
414
+ }
415
+ };
416
+ var ScanItemsOperation = class {
417
+ /** Bind the provider client. */
418
+ constructor(client) {
419
+ this.client = client;
420
+ }
421
+ client;
422
+ /** Return the generated scan contract. */
423
+ definition() {
424
+ return ScanItemsDefinition;
425
+ }
426
+ /** Scan one page using the supplied limit and cursor. */
427
+ async invoke(call, input) {
428
+ const { tableName, limit = 0, exclusiveStartKey } = input;
429
+ if (!tablePattern.test(tableName) || !Number.isInteger(limit) || limit < 0 || limit > 1e3 || exclusiveStartKey !== void 0 && !validKey(exclusiveStartKey))
430
+ return scanBranch("defect", "VALIDATION", "DynamoDB scan input is invalid");
431
+ const exchange = await this.client.sendItemRequest(call, "Scan", jsonBody({
432
+ TableName: tableName,
433
+ ...limit ? { Limit: limit } : {},
434
+ ...exclusiveStartKey ? { ExclusiveStartKey: sortedMap(exclusiveStartKey) } : {}
435
+ }));
436
+ if (exchange.error === "credential")
437
+ return scanBranch("defect", "AUTHENTICATION", "DynamoDB credentials are unavailable or invalid");
438
+ const transient = transientFailure(exchange, "scanItems", "scan");
439
+ if (transient) return newQueryRetry(transient.failure, transient.delay);
440
+ if (exchange.status !== 200) return scanBranch("providerRejected", "PROVIDER_REJECTION", `DynamoDB rejected HTTP ${exchange.status}`);
441
+ if (exchange.error === "tooLarge") return scanBranch("invalidResponse", "RESPONSE_TOO_LARGE", "DynamoDB response exceeded the configured limit");
442
+ if (exchange.error) return newQueryRetry(operationFailure("scanItems", "TRANSPORT", "DynamoDB response was interrupted"));
443
+ const page = decodePage(exchange.body);
444
+ if (!page) return scanBranch("invalidResponse", "PROTOCOL", "DynamoDB returned invalid scan JSON");
445
+ return newQueryBranch("scanned", page);
446
+ }
447
+ };
448
+ function validItem(value) {
449
+ if (!isObject(value)) return false;
450
+ const entries = Object.entries(value);
451
+ return entries.length >= 1 && entries.length <= 400 && entries.every(([name, attribute]) => name.length > 0 && Buffer.byteLength(name) <= 255 && !name.includes("\0") && !name.includes("\r") && !name.includes("\n") && isObject(attribute) && Object.keys(attribute).length === 1);
452
+ }
453
+ function compareUTF8(left, right) {
454
+ return Buffer.compare(Buffer.from(left), Buffer.from(right));
455
+ }
456
+ function sortedMap(values) {
457
+ return Object.fromEntries(Object.entries(values).sort(([left], [right]) => compareUTF8(left, right)));
458
+ }
459
+ function jsonBody(fields) {
460
+ const encoded = JSON.stringify(fields).replace(/[<>&\u2028\u2029]/g, (character) => "\\u" + character.charCodeAt(0).toString(16).padStart(4, "0"));
461
+ return Buffer.from(encoded);
462
+ }
463
+ function decodeObject(body) {
464
+ try {
465
+ const value = JSON.parse(Buffer.from(body).toString("utf8"));
466
+ return isObject(value) ? value : void 0;
467
+ } catch {
468
+ return void 0;
469
+ }
470
+ }
471
+ function decodePage(body) {
472
+ const document = decodeObject(body);
473
+ if (!document) return void 0;
474
+ const { Items: items, Count: count = 0, LastEvaluatedKey: lastEvaluatedKey = null } = document;
475
+ const itemCount = count ?? 0;
476
+ if (!Array.isArray(items) || itemCount !== items.length || !items.every(validItem) || lastEvaluatedKey !== null && !validKey(lastEvaluatedKey)) return void 0;
477
+ return { items, count: itemCount, lastEvaluatedKey: lastEvaluatedKey ?? {} };
478
+ }
479
+ async function writeItem(client, call, operation, target, branch, fields) {
480
+ let body;
481
+ try {
482
+ body = jsonBody(fields);
483
+ } catch {
484
+ return invalidWrite(operation, "DynamoDB write input could not be encoded");
485
+ }
486
+ const exchange = await client.sendItemRequest(call, target, body);
487
+ const attempt = call.context.attempt;
488
+ if (exchange.error === "credential") {
489
+ const failure2 = operationFailure(operation, "AUTHENTICATION", "DynamoDB credentials are unavailable or invalid");
490
+ return attempt > 1 ? newMutationRetry(failure2) : newMutationBranch("defect", { applied: false }, {}, failure2);
491
+ }
492
+ const transient = transientFailure(exchange, operation, "write");
493
+ if (transient) return newMutationRetry(transient.failure, transient.delay);
494
+ if (exchange.status !== 200) {
495
+ if (attempt <= 1 && isDefiniteRefusal(exchange)) {
496
+ const failure2 = operationFailure(operation, "PROVIDER_REJECTION", `DynamoDB rejected HTTP ${exchange.status}`);
497
+ return newMutationBranch("providerRejected", { applied: false }, {}, failure2);
498
+ }
499
+ return newMutationRetry(operationFailure(operation, "TRANSPORT", "DynamoDB write outcome is unknown"));
500
+ }
501
+ if (exchange.error === "tooLarge") return newMutationRetry(operationFailure(operation, "RESPONSE_TOO_LARGE", "DynamoDB response exceeded the configured limit"));
502
+ if (exchange.error) return newMutationRetry(operationFailure(operation, "TRANSPORT", "DynamoDB response was interrupted"));
503
+ if (!decodeObject(exchange.body)) return newMutationRetry(operationFailure(operation, "PROTOCOL", "DynamoDB returned invalid write JSON"));
504
+ return newMutationBranch(branch, { applied: true });
505
+ }
506
+ var refusalStatuses = /* @__PURE__ */ new Set([400, 401, 403, 404, 411, 413, 414, 415, 422]);
507
+ function isDefiniteRefusal(exchange) {
508
+ if (!refusalStatuses.has(exchange.status)) return false;
509
+ const document = decodeObject(exchange.body);
510
+ if (!document || Object.hasOwn(document, "Attributes")) return false;
511
+ const { __type, code } = document;
512
+ return (__type == null || typeof __type === "string") && (code == null || typeof code === "string") && Boolean(__type || code);
513
+ }
514
+ function transientFailure(exchange, operation, request) {
515
+ if (exchange.error === "request")
516
+ return { failure: operationFailure(operation, "TRANSPORT", "DynamoDB request failed"), delay: 0 };
517
+ if (exchange.status === 429 || exchange.status !== 200 && isThrottled(exchange.body))
518
+ return { failure: operationFailure(operation, "RATE_LIMIT", `DynamoDB rate limited the ${request}`), delay: exchange.retryAfterMs };
519
+ if (exchange.status === 408 || exchange.status >= 500)
520
+ return { failure: operationFailure(operation, "AVAILABILITY", "DynamoDB is temporarily unavailable"), delay: exchange.retryAfterMs };
521
+ return void 0;
522
+ }
523
+ function operationFailure(operation, kind, message) {
524
+ return { provider: "amazon-dynamodb", operation, kind, message };
525
+ }
526
+ function invalidWrite(operation, message) {
527
+ return newMutationBranch("defect", { applied: false }, {}, operationFailure(operation, "VALIDATION", message));
528
+ }
529
+ function scanBranch(branch, kind, message) {
530
+ return newQueryBranch(branch, { items: [], count: 0, lastEvaluatedKey: {} }, {}, operationFailure("scanItems", kind, message));
531
+ }
532
+
533
+ // src/project.ts
534
+ function newProjectConnection2(project, connectionName) {
535
+ return newProjectConnection(project, connectionName, (loadedProject, name) => {
536
+ const selected = loadedProject.configuration.connections.find((entry) => entry.connectorId === "amazon-dynamodb" && entry.connectionName === name);
537
+ if (!selected) throw new TypeError("Amazon DynamoDB project connection is not configured");
538
+ 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);
539
+ const timeoutMs = typeof fields.timeout === "number" ? Math.ceil(fields.timeout / 1e6) : fields.timeout ? parseDurationMilliseconds(fields.timeout) : void 0;
540
+ const config = {
541
+ ...fields.region ? { region: fields.region } : {},
542
+ ...fields.endpoint ? { endpoint: fields.endpoint } : {},
543
+ ...timeoutMs !== void 0 ? { timeoutMs } : {},
544
+ ...fields.maxResponseBytes !== void 0 ? { maxResponseBytes: fields.maxResponseBytes } : {}
545
+ };
546
+ const credentials = {
547
+ async resolve(_call, signal) {
548
+ const privateFields = await loadedProject.resolveCredential("amazon-dynamodb", name, signal);
549
+ if (typeof privateFields.access_key_id !== "string" || typeof privateFields.secret_access_key !== "string") throw new TypeError("Amazon DynamoDB credentials are unavailable");
550
+ 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 : "") };
551
+ }
552
+ };
553
+ return new AmazonDynamoDBClient(config, credentials);
554
+ });
555
+ }
556
+ function parseDurationMilliseconds(value) {
557
+ let remaining = value;
558
+ let milliseconds = 0;
559
+ const units = { ns: 1e-6, us: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
560
+ while (remaining) {
561
+ const part = /^(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/.exec(remaining);
562
+ if (!part) throw new TypeError("Amazon DynamoDB timeout must be a positive Go duration");
563
+ milliseconds += Number(part[1]) * (units[part[2] ?? ""] ?? NaN);
564
+ remaining = remaining.slice(part[0].length);
565
+ }
566
+ if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) throw new TypeError("Amazon DynamoDB timeout must resolve to positive whole milliseconds");
567
+ return milliseconds;
568
+ }
569
+ export {
570
+ AmazonDynamoDBClient,
571
+ ConfigSchema,
572
+ Connection,
573
+ ConnectorID,
574
+ CredentialMaterialError,
575
+ DeleteItemBranch,
576
+ DeleteItemBranchDefect,
577
+ DeleteItemBranchDeleted,
578
+ DeleteItemBranchInvalidResponse,
579
+ DeleteItemBranchProviderRejected,
580
+ DeleteItemDefinition,
581
+ DeleteItemInputSchema,
582
+ DeleteItemMetadata,
583
+ DeleteItemOperation,
584
+ GetItemBranch,
585
+ GetItemBranchDefect,
586
+ GetItemBranchFound,
587
+ GetItemBranchInvalidResponse,
588
+ GetItemBranchMissing,
589
+ GetItemBranchProviderRejected,
590
+ GetItemDefinition,
591
+ GetItemInputSchema,
592
+ GetItemMetadata,
593
+ GetItemOperation,
594
+ ItemPageSchema,
595
+ ItemResultSchema,
596
+ ItemWriteResultSchema,
597
+ ProviderID,
598
+ PutItemBranch,
599
+ PutItemBranchDefect,
600
+ PutItemBranchInvalidResponse,
601
+ PutItemBranchProviderRejected,
602
+ PutItemBranchWritten,
603
+ PutItemDefinition,
604
+ PutItemInputSchema,
605
+ PutItemMetadata,
606
+ PutItemOperation,
607
+ ScanItemsBranch,
608
+ ScanItemsBranchDefect,
609
+ ScanItemsBranchInvalidResponse,
610
+ ScanItemsBranchProviderRejected,
611
+ ScanItemsBranchScanned,
612
+ ScanItemsDefinition,
613
+ ScanItemsInputSchema,
614
+ ScanItemsMetadata,
615
+ ScanItemsOperation,
616
+ UpdateItemBranch,
617
+ UpdateItemBranchDefect,
618
+ UpdateItemBranchInvalidResponse,
619
+ UpdateItemBranchProviderRejected,
620
+ UpdateItemBranchUpdated,
621
+ UpdateItemDefinition,
622
+ UpdateItemInputSchema,
623
+ UpdateItemMetadata,
624
+ UpdateItemOperation,
625
+ decodeCredentials,
626
+ isCredentialMaterialError,
627
+ newConnection,
628
+ newConnectionWithOperations,
629
+ newDeleteItemStep,
630
+ newGetItemStep,
631
+ newProjectConnection2 as newProjectConnection,
632
+ newPutItemStep,
633
+ newScanItemsStep,
634
+ newUpdateItemStep
635
+ };