dyno-table 2.2.0 → 2.3.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.
Files changed (106) hide show
  1. package/README.md +200 -1860
  2. package/dist/builders.cjs +55 -0
  3. package/dist/builders.d.cts +4 -0
  4. package/dist/builders.d.ts +4 -0
  5. package/dist/builders.js +2 -0
  6. package/dist/chunk-2EWNZOUK.js +618 -0
  7. package/dist/chunk-2WIBY7PZ.js +46 -0
  8. package/dist/chunk-7UJJ7JXM.cjs +63 -0
  9. package/dist/chunk-DTFJJASK.js +3200 -0
  10. package/dist/chunk-EODPMYPE.js +558 -0
  11. package/dist/chunk-KA3VPIPS.cjs +560 -0
  12. package/dist/chunk-NTA6GDPP.cjs +622 -0
  13. package/dist/chunk-PB7BBCZO.cjs +32 -0
  14. package/dist/chunk-QVRMYGC4.js +29 -0
  15. package/dist/chunk-XYL43FDX.cjs +3217 -0
  16. package/dist/{conditions-CC3NDfUU.d.cts → conditions-CcZL0sR2.d.cts} +1 -1
  17. package/dist/{conditions-DD0bvyHm.d.ts → conditions-D_w7vVYG.d.ts} +1 -1
  18. package/dist/conditions.cjs +67 -62
  19. package/dist/conditions.d.cts +1 -1
  20. package/dist/conditions.d.ts +1 -1
  21. package/dist/conditions.js +1 -48
  22. package/dist/entity.cjs +14 -625
  23. package/dist/entity.d.cts +5 -13
  24. package/dist/entity.d.ts +5 -13
  25. package/dist/entity.js +2 -626
  26. package/dist/index-2cbm07Bi.d.ts +2797 -0
  27. package/dist/index-DlN8G9hd.d.cts +2797 -0
  28. package/dist/index.cjs +111 -4446
  29. package/dist/index.d.cts +3 -11
  30. package/dist/index.d.ts +3 -11
  31. package/dist/index.js +5 -4428
  32. package/dist/standard-schema.cjs +0 -2
  33. package/dist/standard-schema.js +0 -2
  34. package/dist/table.cjs +7 -3782
  35. package/dist/table.d.cts +163 -12
  36. package/dist/table.d.ts +163 -12
  37. package/dist/table.js +3 -3785
  38. package/dist/types.cjs +0 -2
  39. package/dist/types.js +0 -2
  40. package/dist/utils.cjs +10 -30
  41. package/dist/utils.js +1 -31
  42. package/package.json +12 -67
  43. package/dist/batch-builder-BPoHyN_Q.d.cts +0 -398
  44. package/dist/batch-builder-Cdo49C2r.d.ts +0 -398
  45. package/dist/builder-types-BTVhQSHI.d.cts +0 -169
  46. package/dist/builder-types-CzuLR4Th.d.ts +0 -169
  47. package/dist/builders/condition-check-builder.cjs +0 -422
  48. package/dist/builders/condition-check-builder.cjs.map +0 -1
  49. package/dist/builders/condition-check-builder.d.cts +0 -153
  50. package/dist/builders/condition-check-builder.d.ts +0 -153
  51. package/dist/builders/condition-check-builder.js +0 -420
  52. package/dist/builders/condition-check-builder.js.map +0 -1
  53. package/dist/builders/delete-builder.cjs +0 -484
  54. package/dist/builders/delete-builder.cjs.map +0 -1
  55. package/dist/builders/delete-builder.d.cts +0 -211
  56. package/dist/builders/delete-builder.d.ts +0 -211
  57. package/dist/builders/delete-builder.js +0 -482
  58. package/dist/builders/delete-builder.js.map +0 -1
  59. package/dist/builders/paginator.cjs +0 -193
  60. package/dist/builders/paginator.cjs.map +0 -1
  61. package/dist/builders/paginator.d.cts +0 -155
  62. package/dist/builders/paginator.d.ts +0 -155
  63. package/dist/builders/paginator.js +0 -191
  64. package/dist/builders/paginator.js.map +0 -1
  65. package/dist/builders/put-builder.cjs +0 -554
  66. package/dist/builders/put-builder.cjs.map +0 -1
  67. package/dist/builders/put-builder.d.cts +0 -319
  68. package/dist/builders/put-builder.d.ts +0 -319
  69. package/dist/builders/put-builder.js +0 -552
  70. package/dist/builders/put-builder.js.map +0 -1
  71. package/dist/builders/query-builder.cjs +0 -743
  72. package/dist/builders/query-builder.cjs.map +0 -1
  73. package/dist/builders/query-builder.d.cts +0 -6
  74. package/dist/builders/query-builder.d.ts +0 -6
  75. package/dist/builders/query-builder.js +0 -741
  76. package/dist/builders/query-builder.js.map +0 -1
  77. package/dist/builders/transaction-builder.cjs +0 -906
  78. package/dist/builders/transaction-builder.cjs.map +0 -1
  79. package/dist/builders/transaction-builder.d.cts +0 -464
  80. package/dist/builders/transaction-builder.d.ts +0 -464
  81. package/dist/builders/transaction-builder.js +0 -904
  82. package/dist/builders/transaction-builder.js.map +0 -1
  83. package/dist/builders/update-builder.cjs +0 -668
  84. package/dist/builders/update-builder.cjs.map +0 -1
  85. package/dist/builders/update-builder.d.cts +0 -374
  86. package/dist/builders/update-builder.d.ts +0 -374
  87. package/dist/builders/update-builder.js +0 -666
  88. package/dist/builders/update-builder.js.map +0 -1
  89. package/dist/conditions.cjs.map +0 -1
  90. package/dist/conditions.js.map +0 -1
  91. package/dist/entity.cjs.map +0 -1
  92. package/dist/entity.js.map +0 -1
  93. package/dist/index.cjs.map +0 -1
  94. package/dist/index.js.map +0 -1
  95. package/dist/query-builder-CUWdavZw.d.ts +0 -477
  96. package/dist/query-builder-DoZzZz_c.d.cts +0 -477
  97. package/dist/standard-schema.cjs.map +0 -1
  98. package/dist/standard-schema.js.map +0 -1
  99. package/dist/table-CZBMkW2Z.d.ts +0 -276
  100. package/dist/table-f-3wsT7K.d.cts +0 -276
  101. package/dist/table.cjs.map +0 -1
  102. package/dist/table.js.map +0 -1
  103. package/dist/types.cjs.map +0 -1
  104. package/dist/types.js.map +0 -1
  105. package/dist/utils.cjs.map +0 -1
  106. package/dist/utils.js.map +0 -1
package/dist/table.js CHANGED
@@ -1,3785 +1,3 @@
1
- // src/builders/batch-builder.ts
2
- var BatchError = class extends Error {
3
- operation;
4
- cause;
5
- constructor(message, operation, cause) {
6
- super(message);
7
- this.name = "BatchError";
8
- this.operation = operation;
9
- this.cause = cause;
10
- }
11
- };
12
- var BatchBuilder = class {
13
- constructor(batchWriteExecutor, batchGetExecutor, config) {
14
- this.batchWriteExecutor = batchWriteExecutor;
15
- this.batchGetExecutor = batchGetExecutor;
16
- this.config = config;
17
- }
18
- writeItems = [];
19
- getItems = [];
20
- /**
21
- * Checks if the batch is empty (contains no operations)
22
- *
23
- * @returns true if the batch contains no operations
24
- */
25
- isEmpty() {
26
- return this.writeItems.length === 0 && this.getItems.length === 0;
27
- }
28
- /**
29
- * Gets the count of operations in the batch
30
- *
31
- * @returns Object containing the count of write and read operations
32
- */
33
- getOperationCount() {
34
- return {
35
- writes: this.writeItems.length,
36
- reads: this.getItems.length
37
- };
38
- }
39
- /**
40
- * Validates that the batch is not empty before execution
41
- *
42
- * @throws {BatchError} If the batch is empty
43
- */
44
- validateNotEmpty() {
45
- if (this.isEmpty()) {
46
- throw new BatchError(
47
- "Cannot execute empty batch. Add operations using entity builders with .withBatch()",
48
- "write"
49
- );
50
- }
51
- }
52
- /**
53
- * Adds a put operation to the batch with entity type information.
54
- * This method is used internally by entity builders.
55
- *
56
- * @param command - The complete put command configuration
57
- * @param entityType - The entity type name for type tracking
58
- * @returns The batch builder for method chaining
59
- * @internal
60
- */
61
- putWithCommand(command, entityType) {
62
- const batchItem = {
63
- type: "Put",
64
- params: command,
65
- entityType
66
- };
67
- this.writeItems.push(batchItem);
68
- return this;
69
- }
70
- /**
71
- * Adds a delete operation to the batch with entity type information.
72
- * This method is used internally by entity builders.
73
- *
74
- * @param command - The complete delete command configuration
75
- * @param entityType - The entity type name for type tracking
76
- * @returns The batch builder for method chaining
77
- * @internal
78
- */
79
- deleteWithCommand(command, entityType) {
80
- const batchItem = {
81
- type: "Delete",
82
- params: command,
83
- entityType
84
- };
85
- this.writeItems.push(batchItem);
86
- return this;
87
- }
88
- /**
89
- * Adds a get operation to the batch with entity type information.
90
- * This method is used internally by entity builders.
91
- *
92
- * @param command - The complete get command configuration
93
- * @param entityType - The entity type name for type tracking
94
- * @returns The batch builder for method chaining
95
- * @internal
96
- */
97
- getWithCommand(command, entityType) {
98
- const batchItem = {
99
- type: "Get",
100
- params: command,
101
- entityType
102
- };
103
- this.getItems.push(batchItem);
104
- return this;
105
- }
106
- /**
107
- * Executes all write operations in the batch.
108
- *
109
- * @returns A promise that resolves to any unprocessed operations
110
- * @private
111
- */
112
- async executeWrites() {
113
- if (this.writeItems.length === 0) {
114
- return { unprocessedItems: [] };
115
- }
116
- try {
117
- const operations = this.writeItems.map((item) => {
118
- if (item.type === "Put") {
119
- return {
120
- type: "put",
121
- item: item.params.item
122
- };
123
- }
124
- if (item.type === "Delete") {
125
- let key;
126
- if (typeof item.params.key === "object" && item.params.key !== null && "pk" in item.params.key) {
127
- key = item.params.key;
128
- } else {
129
- const tableKey = item.params.key;
130
- key = {
131
- pk: tableKey[this.config.partitionKey],
132
- sk: this.config.sortKey ? tableKey[this.config.sortKey] : void 0
133
- };
134
- }
135
- return {
136
- type: "delete",
137
- key
138
- };
139
- }
140
- throw new BatchError(`Unsupported batch item type for write operation: ${item.type}`, "write");
141
- });
142
- return await this.batchWriteExecutor(operations);
143
- } catch (error) {
144
- throw new BatchError(
145
- `Failed to execute batch write operations: ${error instanceof Error ? error.message : "Unknown error"}`,
146
- "write",
147
- error instanceof Error ? error : void 0
148
- );
149
- }
150
- }
151
- /**
152
- * Executes all get operations in the batch.
153
- *
154
- * @returns A promise that resolves to the retrieved items
155
- * @private
156
- */
157
- async executeGets() {
158
- if (this.getItems.length === 0) {
159
- return { items: [], unprocessedKeys: [] };
160
- }
161
- try {
162
- const keys = this.getItems.map((item) => {
163
- if (item.type === "Get") {
164
- if (typeof item.params.key === "object" && item.params.key !== null && "pk" in item.params.key) {
165
- return item.params.key;
166
- }
167
- const tableKey = item.params.key;
168
- return {
169
- pk: tableKey[this.config.partitionKey],
170
- sk: this.config.sortKey ? tableKey[this.config.sortKey] : void 0
171
- };
172
- }
173
- throw new BatchError(`Unsupported batch item type for get operation: ${item.type}`, "read");
174
- });
175
- return await this.batchGetExecutor(keys);
176
- } catch (error) {
177
- throw new BatchError(
178
- `Failed to execute batch get operations: ${error instanceof Error ? error.message : "Unknown error"}`,
179
- "read",
180
- error instanceof Error ? error : void 0
181
- );
182
- }
183
- }
184
- /**
185
- * Groups retrieved items by their entity type.
186
- * @private
187
- */
188
- groupItemsByType(items) {
189
- const grouped = {};
190
- for (const item of this.getItems) {
191
- if (item.entityType) {
192
- const entityType = item.entityType;
193
- if (!grouped[entityType]) {
194
- grouped[entityType] = [];
195
- }
196
- }
197
- }
198
- for (const item of items) {
199
- const entityType = item.entityType;
200
- if (entityType && grouped[entityType]) {
201
- grouped[entityType].push(item);
202
- }
203
- }
204
- return grouped;
205
- }
206
- /**
207
- * Executes all operations in the batch with typed results.
208
- * Performs write operations first, then get operations.
209
- *
210
- * @returns A promise that resolves to a TypedBatchResult with entity type information
211
- * @throws {BatchError} If the batch is empty or if operations fail
212
- */
213
- async execute() {
214
- this.validateNotEmpty();
215
- const errors = [];
216
- let writeResults = { unprocessedItems: [] };
217
- let getResults = {
218
- items: [],
219
- unprocessedKeys: []
220
- };
221
- if (this.writeItems.length > 0) {
222
- try {
223
- writeResults = await this.executeWrites();
224
- } catch (error) {
225
- if (error instanceof BatchError) {
226
- errors.push(error);
227
- } else {
228
- errors.push(
229
- new BatchError(
230
- "Unexpected error during write operations",
231
- "write",
232
- error instanceof Error ? error : void 0
233
- )
234
- );
235
- }
236
- }
237
- }
238
- if (this.getItems.length > 0) {
239
- try {
240
- getResults = await this.executeGets();
241
- } catch (error) {
242
- if (error instanceof BatchError) {
243
- errors.push(error);
244
- } else {
245
- errors.push(
246
- new BatchError(
247
- "Unexpected error during read operations",
248
- "read",
249
- error instanceof Error ? error : void 0
250
- )
251
- );
252
- }
253
- }
254
- }
255
- if (errors.length > 0 && (writeResults.unprocessedItems.length === this.writeItems.length || getResults.unprocessedKeys.length === this.getItems.length)) {
256
- throw errors[0];
257
- }
258
- const totalOperations = this.writeItems.length + this.getItems.length;
259
- const success = errors.length === 0 && writeResults.unprocessedItems.length === 0 && getResults.unprocessedKeys.length === 0;
260
- return {
261
- success,
262
- writes: {
263
- processed: this.writeItems.length - writeResults.unprocessedItems.length,
264
- unprocessed: writeResults.unprocessedItems
265
- },
266
- reads: {
267
- itemsByType: this.groupItemsByType(getResults.items),
268
- items: getResults.items,
269
- found: getResults.items.length,
270
- unprocessed: getResults.unprocessedKeys
271
- },
272
- totalOperations,
273
- errors: errors.length > 0 ? errors : void 0
274
- };
275
- }
276
- };
277
-
278
- // src/conditions.ts
279
- var createComparisonCondition = (type) => (attr, value) => ({
280
- type,
281
- attr,
282
- value
283
- });
284
- var eq = createComparisonCondition("eq");
285
- var ne = createComparisonCondition("ne");
286
- var lt = createComparisonCondition("lt");
287
- var lte = createComparisonCondition("lte");
288
- var gt = createComparisonCondition("gt");
289
- var gte = createComparisonCondition("gte");
290
- var between = (attr, lower, upper) => ({
291
- type: "between",
292
- attr,
293
- value: [lower, upper]
294
- });
295
- var inArray = (attr, values) => ({
296
- type: "in",
297
- attr,
298
- value: values
299
- });
300
- var beginsWith = createComparisonCondition("beginsWith");
301
- var contains = createComparisonCondition("contains");
302
- var attributeExists = (attr) => ({
303
- type: "attributeExists",
304
- attr
305
- });
306
- var attributeNotExists = (attr) => ({
307
- type: "attributeNotExists",
308
- attr
309
- });
310
- var and = (...conditions) => ({
311
- type: "and",
312
- conditions
313
- });
314
- var or = (...conditions) => ({
315
- type: "or",
316
- conditions
317
- });
318
- var not = (condition) => ({
319
- type: "not",
320
- condition
321
- });
322
-
323
- // src/expression.ts
324
- var generateAttributeName = (params, attr) => {
325
- if (attr.includes(".")) {
326
- const pathSegments = attr.split(".");
327
- const segmentNames = [];
328
- for (const segment of pathSegments) {
329
- let segmentName;
330
- for (const [existingName, existingAttr] of Object.entries(params.expressionAttributeNames)) {
331
- if (existingAttr === segment) {
332
- segmentName = existingName;
333
- break;
334
- }
335
- }
336
- if (!segmentName) {
337
- segmentName = `#${Object.keys(params.expressionAttributeNames).length}`;
338
- params.expressionAttributeNames[segmentName] = segment;
339
- }
340
- segmentNames.push(segmentName);
341
- }
342
- return segmentNames.join(".");
343
- }
344
- for (const [existingName, existingAttr] of Object.entries(params.expressionAttributeNames)) {
345
- if (existingAttr === attr) {
346
- return existingName;
347
- }
348
- }
349
- const attrName = `#${Object.keys(params.expressionAttributeNames).length}`;
350
- params.expressionAttributeNames[attrName] = attr;
351
- return attrName;
352
- };
353
- var generateValueName = (params, value) => {
354
- const valueName = `:${params.valueCounter.count++}`;
355
- params.expressionAttributeValues[valueName] = value;
356
- return valueName;
357
- };
358
- var validateCondition = (condition, requiresAttr = true, requiresValue = true) => {
359
- if (requiresAttr && !condition.attr) {
360
- throw new Error(`Attribute is required for ${condition.type} condition`);
361
- }
362
- if (requiresValue && condition.value === void 0) {
363
- throw new Error(`Value is required for ${condition.type} condition`);
364
- }
365
- };
366
- var buildComparisonExpression = (condition, operator, params) => {
367
- validateCondition(condition);
368
- if (!condition.attr) {
369
- throw new Error(`Attribute is required for ${condition.type} condition`);
370
- }
371
- const attrName = generateAttributeName(params, condition.attr);
372
- const valueName = generateValueName(params, condition.value);
373
- return `${attrName} ${operator} ${valueName}`;
374
- };
375
- var buildBetweenExpression = (condition, params) => {
376
- validateCondition(condition);
377
- if (!condition.attr) {
378
- throw new Error(`Attribute is required for ${condition.type} condition`);
379
- }
380
- if (!Array.isArray(condition.value) || condition.value.length !== 2) {
381
- throw new Error("Between condition requires an array of two values");
382
- }
383
- const attrName = generateAttributeName(params, condition.attr);
384
- const lowerName = generateValueName(params, condition.value[0]);
385
- const upperName = generateValueName(params, condition.value[1]);
386
- return `${attrName} BETWEEN ${lowerName} AND ${upperName}`;
387
- };
388
- var buildInExpression = (condition, params) => {
389
- validateCondition(condition);
390
- if (!condition.attr) {
391
- throw new Error(`Attribute is required for ${condition.type} condition`);
392
- }
393
- if (!Array.isArray(condition.value) || condition.value.length === 0) {
394
- throw new Error("In condition requires a non-empty array of values");
395
- }
396
- if (condition.value.length > 100) {
397
- throw new Error("In condition supports a maximum of 100 values");
398
- }
399
- const attrName = generateAttributeName(params, condition.attr);
400
- const valueNames = condition.value.map((value) => generateValueName(params, value));
401
- return `${attrName} IN (${valueNames.join(", ")})`;
402
- };
403
- var buildFunctionExpression = (functionName, condition, params) => {
404
- validateCondition(condition);
405
- if (!condition.attr) {
406
- throw new Error(`Attribute is required for ${condition.type} condition`);
407
- }
408
- const attrName = generateAttributeName(params, condition.attr);
409
- const valueName = generateValueName(params, condition.value);
410
- return `${functionName}(${attrName}, ${valueName})`;
411
- };
412
- var buildAttributeFunction = (functionName, condition, params) => {
413
- validateCondition(condition, true, false);
414
- if (!condition.attr) {
415
- throw new Error(`Attribute is required for ${condition.type} condition`);
416
- }
417
- const attrName = generateAttributeName(params, condition.attr);
418
- return `${functionName}(${attrName})`;
419
- };
420
- var buildLogicalExpression = (operator, conditions, params) => {
421
- if (!conditions || conditions.length === 0) {
422
- throw new Error(`At least one condition is required for ${operator} expression`);
423
- }
424
- const expressions = conditions.map((c) => buildExpression(c, params));
425
- return `(${expressions.join(` ${operator} `)})`;
426
- };
427
- var buildExpression = (condition, params) => {
428
- if (!condition) return "";
429
- try {
430
- const expressionBuilders = {
431
- eq: () => buildComparisonExpression(condition, "=", params),
432
- ne: () => buildComparisonExpression(condition, "<>", params),
433
- lt: () => buildComparisonExpression(condition, "<", params),
434
- lte: () => buildComparisonExpression(condition, "<=", params),
435
- gt: () => buildComparisonExpression(condition, ">", params),
436
- gte: () => buildComparisonExpression(condition, ">=", params),
437
- between: () => buildBetweenExpression(condition, params),
438
- in: () => buildInExpression(condition, params),
439
- beginsWith: () => buildFunctionExpression("begins_with", condition, params),
440
- contains: () => buildFunctionExpression("contains", condition, params),
441
- attributeExists: () => buildAttributeFunction("attribute_exists", condition, params),
442
- attributeNotExists: () => buildAttributeFunction("attribute_not_exists", condition, params),
443
- and: () => {
444
- if (!condition.conditions) {
445
- throw new Error("Conditions array is required for AND operator");
446
- }
447
- return buildLogicalExpression("AND", condition.conditions, params);
448
- },
449
- or: () => {
450
- if (!condition.conditions) {
451
- throw new Error("Conditions array is required for OR operator");
452
- }
453
- return buildLogicalExpression("OR", condition.conditions, params);
454
- },
455
- not: () => {
456
- if (!condition.condition) {
457
- throw new Error("Condition is required for NOT operator");
458
- }
459
- return `NOT (${buildExpression(condition.condition, params)})`;
460
- }
461
- };
462
- const builder = expressionBuilders[condition.type];
463
- if (!builder) {
464
- throw new Error(`Unknown condition type: ${condition.type}`);
465
- }
466
- return builder();
467
- } catch (error) {
468
- if (error instanceof Error) {
469
- console.error(`Error building expression for condition type ${condition.type}:`, error.message);
470
- } else {
471
- console.error(`Error building expression for condition type ${condition.type}:`, error);
472
- }
473
- throw error;
474
- }
475
- };
476
- var prepareExpressionParams = (condition) => {
477
- if (!condition) return {};
478
- const params = {
479
- expressionAttributeNames: {},
480
- expressionAttributeValues: {},
481
- valueCounter: { count: 0 }
482
- };
483
- const expression = buildExpression(condition, params);
484
- return {
485
- expression,
486
- names: Object.keys(params.expressionAttributeNames).length > 0 ? params.expressionAttributeNames : void 0,
487
- values: Object.keys(params.expressionAttributeValues).length > 0 ? params.expressionAttributeValues : void 0
488
- };
489
- };
490
-
491
- // src/utils/debug-expression.ts
492
- function debugCommand(command) {
493
- const result = {};
494
- function replaceAliases(expressionString) {
495
- if (!expressionString) {
496
- return expressionString;
497
- }
498
- let replacedString = expressionString;
499
- for (const alias in command.expressionAttributeNames) {
500
- const attributeName = command.expressionAttributeNames[alias];
501
- const regex = new RegExp(alias, "g");
502
- replacedString = replacedString.replace(regex, attributeName);
503
- }
504
- for (const alias in command.expressionAttributeValues) {
505
- let attributeValue = command.expressionAttributeValues[alias];
506
- if (attributeValue instanceof Set) {
507
- const array = Array.from(attributeValue);
508
- attributeValue = `Set(${array.length}){${array.map((v) => JSON.stringify(v)).join(", ")}}`;
509
- } else {
510
- attributeValue = JSON.stringify(attributeValue);
511
- }
512
- const regex = new RegExp(alias, "g");
513
- replacedString = replacedString.replace(regex, attributeValue);
514
- }
515
- return replacedString;
516
- }
517
- if (command.updateExpression) {
518
- result.updateExpression = replaceAliases(command.updateExpression);
519
- }
520
- if (command.conditionExpression) {
521
- result.conditionExpression = replaceAliases(command.conditionExpression);
522
- }
523
- if (command.filterExpression) {
524
- result.filterExpression = replaceAliases(command.filterExpression);
525
- }
526
- if (command.keyConditionExpression) {
527
- result.keyConditionExpression = replaceAliases(command.keyConditionExpression);
528
- }
529
- if (command.projectionExpression) {
530
- result.projectionExpression = replaceAliases(command.projectionExpression);
531
- }
532
- return {
533
- raw: command,
534
- readable: result
535
- };
536
- }
537
-
538
- // src/builders/condition-check-builder.ts
539
- var ConditionCheckBuilder = class {
540
- key;
541
- tableName;
542
- conditionExpression;
543
- constructor(tableName, key) {
544
- this.tableName = tableName;
545
- this.key = key;
546
- }
547
- /**
548
- * Adds a condition that must be satisfied for the check to succeed.
549
- *
550
- * @example
551
- * ```typescript
552
- * // Check dinosaur health and behavior
553
- * builder.condition(op =>
554
- * op.and([
555
- * op.gt('stats.health', 50),
556
- * op.not(op.eq('status', 'SEDATED')),
557
- * op.lt('aggressionLevel', 8)
558
- * ])
559
- * );
560
- *
561
- * // Verify habitat conditions
562
- * builder.condition(op =>
563
- * op.and([
564
- * op.eq('powerStatus', 'ONLINE'),
565
- * op.between('temperature', 20, 30),
566
- * op.attributeExists('lastMaintenance')
567
- * ])
568
- * );
569
- *
570
- * // Check breeding conditions
571
- * builder.condition(op =>
572
- * op.and([
573
- * op.eq('species', 'VELOCIRAPTOR'),
574
- * op.gte('age', 3),
575
- * op.eq('geneticPurity', 100)
576
- * ])
577
- * );
578
- * ```
579
- *
580
- * @param condition - Either a Condition DynamoItem or a callback function that builds the condition
581
- * @returns The builder instance for method chaining
582
- */
583
- condition(condition) {
584
- if (typeof condition === "function") {
585
- const conditionOperator = {
586
- eq,
587
- ne,
588
- lt,
589
- lte,
590
- gt,
591
- gte,
592
- between,
593
- inArray,
594
- beginsWith,
595
- contains,
596
- attributeExists,
597
- attributeNotExists,
598
- and,
599
- or,
600
- not
601
- };
602
- this.conditionExpression = condition(conditionOperator);
603
- } else {
604
- this.conditionExpression = condition;
605
- }
606
- return this;
607
- }
608
- /**
609
- * Generates the DynamoDB command parameters for direct execution.
610
- * Use this method when you want to:
611
- * - Execute the condition check as a standalone operation
612
- * - Get the raw DynamoDB command for custom execution
613
- * - Inspect the generated command parameters
614
- *
615
- * @example
616
- * ```ts
617
- * const command = new ConditionCheckBuilder('myTable', { id: '123' })
618
- * .condition(op => op.attributeExists('status'))
619
- * .toDynamoCommand();
620
- * // Use command with DynamoDB client
621
- * ```
622
- *
623
- * @throws {Error} If no condition has been set
624
- * @returns The DynamoDB command parameters
625
- */
626
- toDynamoCommand() {
627
- if (!this.conditionExpression) {
628
- throw new Error("Condition is required for condition check operations");
629
- }
630
- const { expression, names, values } = prepareExpressionParams(this.conditionExpression);
631
- if (!expression) {
632
- throw new Error("Failed to generate condition expression");
633
- }
634
- return {
635
- tableName: this.tableName,
636
- key: this.key,
637
- conditionExpression: expression,
638
- expressionAttributeNames: names,
639
- expressionAttributeValues: values
640
- };
641
- }
642
- /**
643
- * Adds this condition check operation to a transaction.
644
- *
645
- * @example
646
- * ```ts
647
- * const transaction = new TransactionBuilder();
648
- * new ConditionCheckBuilder('habitats', { id: 'PADDOCK-B' })
649
- * .condition(op => op.and([
650
- * op.eq('securityStatus', 'ACTIVE'),
651
- * op.lt('currentOccupants', 3),
652
- * op.eq('habitatType', 'CARNIVORE')
653
- * ]))
654
- * .withTransaction(transaction);
655
- * // Add dinosaur transfer operations
656
- * ```
657
- *
658
- * @param transaction - The transaction builder to add this operation to
659
- * @throws {Error} If no condition has been set
660
- * @returns The builder instance for method chaining
661
- */
662
- withTransaction(transaction) {
663
- if (!this.conditionExpression) {
664
- throw new Error("Condition is required for condition check operations");
665
- }
666
- const command = this.toDynamoCommand();
667
- transaction.conditionCheckWithCommand(command);
668
- return this;
669
- }
670
- /**
671
- * Gets a human-readable representation of the condition check command
672
- * with all expression placeholders replaced by their actual values.
673
- *
674
- * @example
675
- * ```ts
676
- * const debugInfo = new ConditionCheckBuilder('dinosaurs', { id: 'TREX-001' })
677
- * .condition(op => op.and([
678
- * op.between('stats.health', 50, 100),
679
- * op.not(op.eq('status', 'SEDATED')),
680
- * op.attributeExists('lastFeedingTime')
681
- * op.eq('version', 1)
682
- * ]))
683
- * .debug();
684
- * console.log(debugInfo);
685
- * ```
686
- *
687
- * @returns A readable representation of the condition check command with resolved expressions
688
- */
689
- debug() {
690
- const command = this.toDynamoCommand();
691
- return debugCommand(command);
692
- }
693
- };
694
-
695
- // src/builders/delete-builder.ts
696
- var DeleteBuilder = class {
697
- options = {
698
- returnValues: "ALL_OLD"
699
- };
700
- executor;
701
- tableName;
702
- key;
703
- constructor(executor, tableName, key) {
704
- this.executor = executor;
705
- this.tableName = tableName;
706
- this.key = key;
707
- }
708
- /**
709
- * Adds a condition that must be satisfied for the delete operation to succeed.
710
- *
711
- * @example
712
- * ```typescript
713
- * // Ensure dinosaur can be safely removed
714
- * builder.condition(op =>
715
- * op.and([
716
- * op.eq('status', 'SEDATED'),
717
- * op.eq('location', 'MEDICAL_BAY'),
718
- * op.attributeExists('lastCheckup')
719
- * ])
720
- * );
721
- *
722
- * // Verify habitat is empty
723
- * builder.condition(op =>
724
- * op.and([
725
- * op.eq('occupants', 0),
726
- * op.eq('maintenanceStatus', 'COMPLETE'),
727
- * op.not(op.attributeExists('activeAlerts'))
728
- * ])
729
- * );
730
- * ```
731
- *
732
- * @param condition - Either a Condition object or a callback function that builds the condition
733
- * @returns The builder instance for method chaining
734
- */
735
- condition(condition) {
736
- if (typeof condition === "function") {
737
- const conditionOperator = {
738
- eq,
739
- ne,
740
- lt,
741
- lte,
742
- gt,
743
- gte,
744
- between,
745
- inArray,
746
- beginsWith,
747
- contains,
748
- attributeExists,
749
- attributeNotExists,
750
- and,
751
- or,
752
- not
753
- };
754
- this.options.condition = condition(conditionOperator);
755
- } else {
756
- this.options.condition = condition;
757
- }
758
- return this;
759
- }
760
- /**
761
- * Sets whether to return the item's attribute values before deletion.
762
- *
763
- * @example
764
- * ```ts
765
- * // Archive dinosaur data before removal
766
- * const result = await builder
767
- * .returnValues('ALL_OLD')
768
- * .execute();
769
- *
770
- * if (result.item) {
771
- * console.log('Removed dinosaur data:', {
772
- * species: result.item.species,
773
- * age: result.item.age,
774
- * lastLocation: result.item.location
775
- * });
776
- * }
777
- * ```
778
- *
779
- * @param returnValues - Use 'ALL_OLD' to return all attributes of the deleted item
780
- * @returns The builder instance for method chaining
781
- */
782
- returnValues(returnValues) {
783
- this.options.returnValues = returnValues;
784
- return this;
785
- }
786
- /**
787
- * Generate the DynamoDB command parameters
788
- */
789
- toDynamoCommand() {
790
- const { expression, names, values } = prepareExpressionParams(this.options.condition);
791
- return {
792
- tableName: this.tableName,
793
- key: this.key,
794
- conditionExpression: expression,
795
- expressionAttributeNames: names,
796
- expressionAttributeValues: values,
797
- returnValues: this.options.returnValues
798
- };
799
- }
800
- /**
801
- * Adds this delete operation to a transaction.
802
- *
803
- * @example
804
- * ```ts
805
- * const transaction = new TransactionBuilder();
806
- *
807
- * // Remove dinosaur from old habitat
808
- * new DeleteBuilder(executor, 'dinosaurs', { id: 'RAPTOR-001' })
809
- * .condition(op => op.eq('status', 'SEDATED'))
810
- * .withTransaction(transaction);
811
- *
812
- * // Update old habitat occupancy
813
- * new UpdateBuilder(executor, 'habitats', { id: 'PADDOCK-A' })
814
- * .add('occupants', -1)
815
- * .withTransaction(transaction);
816
- *
817
- * // Execute transfer atomically
818
- * await transaction.execute();
819
- * ```
820
- *
821
- * @param transaction - The transaction builder to add this operation to
822
- */
823
- withTransaction(transaction) {
824
- const command = this.toDynamoCommand();
825
- transaction.deleteWithCommand(command);
826
- }
827
- /**
828
- * Adds this delete operation to a batch with optional entity type information.
829
- *
830
- * @example Basic Usage
831
- * ```ts
832
- * const batch = table.batchBuilder();
833
- *
834
- * // Remove multiple dinosaurs in batch
835
- * dinosaurRepo.delete({ id: 'old-dino-1' }).withBatch(batch);
836
- * dinosaurRepo.delete({ id: 'old-dino-2' }).withBatch(batch);
837
- * dinosaurRepo.delete({ id: 'old-dino-3' }).withBatch(batch);
838
- *
839
- * // Execute all deletions efficiently
840
- * await batch.execute();
841
- * ```
842
- *
843
- * @example Typed Usage
844
- * ```ts
845
- * const batch = table.batchBuilder<{
846
- * User: UserEntity;
847
- * Order: OrderEntity;
848
- * }>();
849
- *
850
- * // Add operations with type information
851
- * userRepo.delete({ id: 'user-1' }).withBatch(batch, 'User');
852
- * orderRepo.delete({ id: 'order-1' }).withBatch(batch, 'Order');
853
- *
854
- * // Execute batch operations
855
- * await batch.execute();
856
- * ```
857
- *
858
- * @param batch - The batch builder to add this operation to
859
- * @param entityType - Optional entity type key for type tracking
860
- */
861
- withBatch(batch, entityType) {
862
- const command = this.toDynamoCommand();
863
- batch.deleteWithCommand(command, entityType);
864
- }
865
- /**
866
- * Executes the delete operation against DynamoDB.
867
- *
868
- * @example
869
- * ```ts
870
- * // Delete with condition and retrieve old values
871
- * const result = await new DeleteBuilder(executor, 'myTable', { id: '123' })
872
- * .condition(op => op.eq('status', 'INACTIVE'))
873
- * .returnValues('ALL_OLD')
874
- * .execute();
875
- *
876
- * if (result.item) {
877
- * console.log('Deleted item:', result.item);
878
- * }
879
- * ```
880
- *
881
- * @returns A promise that resolves to an object containing the deleted item's attributes (if returnValues is 'ALL_OLD')
882
- */
883
- async execute() {
884
- const params = this.toDynamoCommand();
885
- return this.executor(params);
886
- }
887
- /**
888
- * Gets a human-readable representation of the delete command
889
- * with all expression placeholders replaced by their actual values.
890
- *
891
- * @example
892
- * ```ts
893
- * const debugInfo = new DeleteBuilder(executor, 'dinosaurs', { id: 'TREX-001' })
894
- * .condition(op => op.and([
895
- * op.eq('status', 'SEDATED'),
896
- * op.eq('location', 'MEDICAL_BAY'),
897
- * op.gt('sedationLevel', 8)
898
- * op.eq('version', 1),
899
- * op.attributeExists('status')
900
- * ]))
901
- * .debug();
902
- *
903
- * console.log('Delete command:', debugInfo);
904
- * ```
905
- *
906
- * @returns A readable representation of the delete command with resolved expressions
907
- */
908
- debug() {
909
- const command = this.toDynamoCommand();
910
- return debugCommand(command);
911
- }
912
- };
913
-
914
- // src/builders/get-builder.ts
915
- var GetBuilder = class {
916
- /**
917
- * Creates a new GetBuilder instance.
918
- *
919
- * @param executor - Function that executes the get operation
920
- * @param key - Primary key of the item to retrieve
921
- * @param tableName - Name of the DynamoDB table
922
- */
923
- constructor(executor, key, tableName) {
924
- this.executor = executor;
925
- this.params = {
926
- tableName,
927
- key
928
- };
929
- }
930
- params;
931
- options = {};
932
- selectedFields = /* @__PURE__ */ new Set();
933
- /**
934
- * Specifies which attributes to return in the get results.
935
- *
936
- * @example
937
- * ```typescript
938
- * // Select single attribute
939
- * builder.select('species')
940
- *
941
- * // Select multiple attributes
942
- * builder.select(['id', 'species', 'diet'])
943
- *
944
- * // Chain multiple select calls
945
- * builder
946
- * .select('id')
947
- * .select(['species', 'diet'])
948
- * ```
949
- *
950
- * @param fields - A single field name or an array of field names to return
951
- * @returns The builder instance for method chaining
952
- */
953
- select(fields) {
954
- if (typeof fields === "string") {
955
- this.selectedFields.add(fields);
956
- } else if (Array.isArray(fields)) {
957
- for (const field of fields) {
958
- this.selectedFields.add(field);
959
- }
960
- }
961
- this.options.projection = Array.from(this.selectedFields);
962
- return this;
963
- }
964
- /**
965
- * Sets whether to use strongly consistent reads for the get operation.
966
- * Use this method when you need:
967
- * - The most up-to-date dinosaur data
968
- * - To ensure you're reading the latest dinosaur status
969
- * - Critical safety information about dangerous species
970
- *
971
- * Note: Consistent reads consume twice the throughput
972
- *
973
- * @example
974
- * ```typescript
975
- * // Get the latest T-Rex data
976
- * const result = await new GetBuilder(executor, { pk: 'dinosaur#123', sk: 'profile' })
977
- * .consistentRead()
978
- * .execute();
979
- * ```
980
- *
981
- * @param consistentRead - Whether to use consistent reads (defaults to true)
982
- * @returns The builder instance for method chaining
983
- */
984
- consistentRead(consistentRead = true) {
985
- this.params.consistentRead = consistentRead;
986
- return this;
987
- }
988
- /**
989
- * Adds this get operation to a batch with optional entity type information.
990
- *
991
- * @example Basic Usage
992
- * ```ts
993
- * const batch = table.batchBuilder();
994
- *
995
- * // Add multiple get operations to batch
996
- * dinosaurRepo.get({ id: 'dino-1' }).withBatch(batch);
997
- * dinosaurRepo.get({ id: 'dino-2' }).withBatch(batch);
998
- * dinosaurRepo.get({ id: 'dino-3' }).withBatch(batch);
999
- *
1000
- * // Execute all gets efficiently
1001
- * const results = await batch.execute();
1002
- * ```
1003
- *
1004
- * @example Typed Usage
1005
- * ```ts
1006
- * const batch = table.batchBuilder<{
1007
- * User: UserEntity;
1008
- * Order: OrderEntity;
1009
- * }>();
1010
- *
1011
- * // Add operations with type information
1012
- * userRepo.get({ id: 'user-1' }).withBatch(batch, 'User');
1013
- * orderRepo.get({ id: 'order-1' }).withBatch(batch, 'Order');
1014
- *
1015
- * // Execute and get typed results
1016
- * const result = await batch.execute();
1017
- * const users: UserEntity[] = result.reads.itemsByType.User;
1018
- * const orders: OrderEntity[] = result.reads.itemsByType.Order;
1019
- * ```
1020
- *
1021
- * @param batch - The batch builder to add this operation to
1022
- * @param entityType - Optional entity type key for type tracking
1023
- */
1024
- withBatch(batch, entityType) {
1025
- const command = this.toDynamoCommand();
1026
- batch.getWithCommand(command, entityType);
1027
- }
1028
- /**
1029
- * Converts the builder configuration to a DynamoDB command
1030
- */
1031
- toDynamoCommand() {
1032
- const expressionParams = {
1033
- expressionAttributeNames: {}};
1034
- const projectionExpression = Array.from(this.selectedFields).map((p) => generateAttributeName(expressionParams, p)).join(", ");
1035
- const { expressionAttributeNames } = expressionParams;
1036
- return {
1037
- ...this.params,
1038
- projectionExpression: projectionExpression.length > 0 ? projectionExpression : void 0,
1039
- expressionAttributeNames: Object.keys(expressionAttributeNames).length > 0 ? expressionAttributeNames : void 0
1040
- };
1041
- }
1042
- /**
1043
- * Executes the get operation against DynamoDB.
1044
- *
1045
- * @example
1046
- * ```typescript
1047
- * try {
1048
- * const result = await new GetBuilder(executor, { pk: 'dinosaur#123', sk: 'profile' })
1049
- * .select(['species', 'name', 'diet'])
1050
- * .consistentRead()
1051
- * .execute();
1052
- *
1053
- * if (result.item) {
1054
- * console.log('Dinosaur found:', result.item);
1055
- * } else {
1056
- * console.log('Dinosaur not found');
1057
- * }
1058
- * } catch (error) {
1059
- * console.error('Error getting dinosaur:', error);
1060
- * }
1061
- * ```
1062
- *
1063
- * @returns A promise that resolves to an object containing:
1064
- * - item: The retrieved dinosaur or undefined if not found
1065
- */
1066
- async execute() {
1067
- const command = this.toDynamoCommand();
1068
- return this.executor(command);
1069
- }
1070
- };
1071
-
1072
- // src/builders/put-builder.ts
1073
- var PutBuilder = class {
1074
- item;
1075
- options;
1076
- executor;
1077
- tableName;
1078
- constructor(executor, item, tableName) {
1079
- this.executor = executor;
1080
- this.item = item;
1081
- this.tableName = tableName;
1082
- this.options = {
1083
- returnValues: "NONE"
1084
- };
1085
- }
1086
- set(valuesOrPath, value) {
1087
- if (typeof valuesOrPath === "object") {
1088
- Object.assign(this.item, valuesOrPath);
1089
- } else {
1090
- this.item[valuesOrPath] = value;
1091
- }
1092
- return this;
1093
- }
1094
- /**
1095
- * Adds a condition that must be satisfied for the put operation to succeed.
1096
- *
1097
- * @example
1098
- * ```ts
1099
- * // Ensure item doesn't exist (insert only)
1100
- * builder.condition(op => op.attributeNotExists('id'))
1101
- *
1102
- * // Complex condition with version check
1103
- * builder.condition(op =>
1104
- * op.and([
1105
- * op.attributeExists('id'),
1106
- * op.eq('version', currentVersion),
1107
- * op.eq('status', 'ACTIVE')
1108
- * ])
1109
- * )
1110
- * ```
1111
- *
1112
- * @param condition - Either a Condition object or a callback function that builds the condition
1113
- * @returns The builder instance for method chaining
1114
- */
1115
- /**
1116
- * Adds a condition that must be satisfied for the put operation to succeed.
1117
- *
1118
- * @example
1119
- * ```typescript
1120
- * // Ensure unique dinosaur ID
1121
- * builder.condition(op =>
1122
- * op.attributeNotExists('id')
1123
- * );
1124
- *
1125
- * // Verify habitat requirements
1126
- * builder.condition(op =>
1127
- * op.and([
1128
- * op.eq('securityStatus', 'READY'),
1129
- * op.attributeExists('lastInspection'),
1130
- * op.gt('securityLevel', 5)
1131
- * ])
1132
- * );
1133
- *
1134
- * // Check breeding facility conditions
1135
- * builder.condition(op =>
1136
- * op.and([
1137
- * op.between('temperature', 25, 30),
1138
- * op.between('humidity', 60, 80),
1139
- * op.eq('quarantineStatus', 'CLEAR')
1140
- * ])
1141
- * );
1142
- * ```
1143
- *
1144
- * @param condition - Either a Condition object or a callback function that builds the condition
1145
- * @returns The builder instance for method chaining
1146
- */
1147
- condition(condition) {
1148
- if (typeof condition === "function") {
1149
- const conditionOperator = {
1150
- eq,
1151
- ne,
1152
- lt,
1153
- lte,
1154
- gt,
1155
- gte,
1156
- between,
1157
- inArray,
1158
- beginsWith,
1159
- contains,
1160
- attributeExists,
1161
- attributeNotExists,
1162
- and,
1163
- or,
1164
- not
1165
- };
1166
- this.options.condition = condition(conditionOperator);
1167
- } else {
1168
- this.options.condition = condition;
1169
- }
1170
- return this;
1171
- }
1172
- /**
1173
- * Sets whether to return the item's previous values (if it existed).
1174
- *
1175
- * @options
1176
- * - NONE: No return value
1177
- * - ALL_OLD: Returns the item's previous state if it existed, no read capacity units are consumed
1178
- * - CONSISTENT: Performs a GET operation after the put to retrieve the item's new state
1179
- * - INPUT: Returns the input values that were passed to the operation
1180
- *
1181
- * @example
1182
- * ```ts
1183
- * // Get previous dinosaur state
1184
- * const result = await builder
1185
- * .returnValues('ALL_OLD')
1186
- * .execute();
1187
- *
1188
- * if (result) {
1189
- * console.log('Previous profile:', {
1190
- * species: result.species,
1191
- * status: result.status,
1192
- * stats: {
1193
- * health: result.stats.health,
1194
- * threatLevel: result.stats.threatLevel
1195
- * }
1196
- * });
1197
- * }
1198
- *
1199
- * // Return input values for create operations
1200
- * const createResult = await builder
1201
- * .returnValues('INPUT')
1202
- * .execute();
1203
- * ```
1204
- *
1205
- * @param returnValues - Use 'ALL_OLD' to return previous values, 'INPUT' to return input values, 'CONSISTENT' for fresh data, or 'NONE' (default).
1206
- * @returns The builder instance for method chaining
1207
- */
1208
- returnValues(returnValues) {
1209
- this.options.returnValues = returnValues;
1210
- return this;
1211
- }
1212
- /**
1213
- * Generate the DynamoDB command parameters
1214
- */
1215
- toDynamoCommand() {
1216
- const { expression, names, values } = prepareExpressionParams(this.options.condition);
1217
- return {
1218
- tableName: this.tableName,
1219
- item: this.item,
1220
- conditionExpression: expression,
1221
- expressionAttributeNames: names,
1222
- expressionAttributeValues: values,
1223
- returnValues: this.options.returnValues
1224
- };
1225
- }
1226
- /**
1227
- * Adds this put operation to a transaction.
1228
- *
1229
- * @example
1230
- * ```ts
1231
- * const transaction = new TransactionBuilder();
1232
- *
1233
- * // Add dinosaur to new habitat
1234
- * new PutBuilder(executor, {
1235
- * id: 'TREX-002',
1236
- * location: 'PADDOCK-B',
1237
- * status: 'ACTIVE',
1238
- * transferDate: new Date().toISOString()
1239
- * }, 'dinosaurs')
1240
- * .withTransaction(transaction);
1241
- *
1242
- * // Update habitat records
1243
- * new UpdateBuilder(executor, 'habitats', { id: 'PADDOCK-B' })
1244
- * .add('occupants', 1)
1245
- * .set('lastTransfer', new Date().toISOString())
1246
- * .withTransaction(transaction);
1247
- *
1248
- * // Execute transfer atomically
1249
- * await transaction.execute();
1250
- * ```
1251
- *
1252
- * @param transaction - The transaction builder to add this operation to
1253
- * @returns The builder instance for method chaining
1254
- */
1255
- withTransaction(transaction) {
1256
- const command = this.toDynamoCommand();
1257
- transaction.putWithCommand(command);
1258
- return this;
1259
- }
1260
- /**
1261
- * Adds this put operation to a batch with optional entity type information.
1262
- *
1263
- * @example Basic Usage
1264
- * ```ts
1265
- * const batch = table.batchBuilder();
1266
- *
1267
- * // Add multiple dinosaurs to batch
1268
- * dinosaurRepo.create(newDino1).withBatch(batch);
1269
- * dinosaurRepo.create(newDino2).withBatch(batch);
1270
- * dinosaurRepo.create(newDino3).withBatch(batch);
1271
- *
1272
- * // Execute all operations efficiently
1273
- * await batch.execute();
1274
- * ```
1275
- *
1276
- * @example Typed Usage
1277
- * ```ts
1278
- * const batch = table.batchBuilder<{
1279
- * User: UserEntity;
1280
- * Order: OrderEntity;
1281
- * }>();
1282
- *
1283
- * // Add operations with type information
1284
- * userRepo.create(newUser).withBatch(batch, 'User');
1285
- * orderRepo.create(newOrder).withBatch(batch, 'Order');
1286
- *
1287
- * // Execute and get typed results
1288
- * const result = await batch.execute();
1289
- * const users: UserEntity[] = result.reads.itemsByType.User;
1290
- * ```
1291
- *
1292
- * @param batch - The batch builder to add this operation to
1293
- * @param entityType - Optional entity type key for type tracking
1294
- */
1295
- withBatch(batch, entityType) {
1296
- const command = this.toDynamoCommand();
1297
- batch.putWithCommand(command, entityType);
1298
- }
1299
- /**
1300
- * Executes the put operation against DynamoDB.
1301
- *
1302
- * @example
1303
- * ```ts
1304
- * try {
1305
- * // Put with condition and return old values
1306
- * const result = await new PutBuilder(executor, newItem, 'myTable')
1307
- * .condition(op => op.eq('version', 1))
1308
- * .returnValues('ALL_OLD')
1309
- * .execute();
1310
- *
1311
- * console.log('Put successful, old item:', result);
1312
- * } catch (error) {
1313
- * // Handle condition check failure or other errors
1314
- * console.error('Put failed:', error);
1315
- * }
1316
- * ```
1317
- *
1318
- * @returns A promise that resolves to the operation result (type depends on returnValues setting)
1319
- * @throws Will throw an error if the condition check fails or other DynamoDB errors occur
1320
- */
1321
- async execute() {
1322
- const params = this.toDynamoCommand();
1323
- return this.executor(params);
1324
- }
1325
- /**
1326
- * Gets a human-readable representation of the put command
1327
- * with all expression placeholders replaced by their actual values.
1328
- *
1329
- * @example
1330
- * ```ts
1331
- * const debugInfo = new PutBuilder(executor, {
1332
- * id: 'RAPTOR-003',
1333
- * species: 'Velociraptor',
1334
- * status: 'QUARANTINE',
1335
- * stats: {
1336
- * health: 100,
1337
- * aggressionLevel: 7,
1338
- * age: 2
1339
- * }
1340
- * }, 'dinosaurs')
1341
- * .condition(op =>
1342
- * op.and([
1343
- * op.attributeNotExists('id'),
1344
- * op.eq('quarantineStatus', 'READY'),
1345
- * op.gt('securityLevel', 8)
1346
- * ])
1347
- * )
1348
- * .debug();
1349
- *
1350
- * console.log('Dinosaur transfer command:', debugInfo);
1351
- * ```
1352
- *
1353
- * @returns A readable representation of the put command with resolved expressions
1354
- */
1355
- debug() {
1356
- const command = this.toDynamoCommand();
1357
- return debugCommand(command);
1358
- }
1359
- };
1360
-
1361
- // src/builders/paginator.ts
1362
- var Paginator = class {
1363
- queryBuilder;
1364
- pageSize;
1365
- currentPage = 0;
1366
- lastEvaluatedKey;
1367
- hasMorePages = true;
1368
- totalItemsRetrieved = 0;
1369
- overallLimit;
1370
- constructor(queryBuilder, pageSize) {
1371
- this.queryBuilder = queryBuilder;
1372
- this.pageSize = pageSize;
1373
- this.overallLimit = queryBuilder.getLimit();
1374
- }
1375
- /**
1376
- * Gets the current page number (1-indexed).
1377
- *
1378
- * @example
1379
- * ```ts
1380
- * const paginator = new QueryBuilder(executor, eq('species', 'Tyrannosaurus'))
1381
- * .paginate(5);
1382
- *
1383
- * await paginator.getNextPage();
1384
- * console.log(`Reviewing T-Rex group ${paginator.getCurrentPage()}`);
1385
- * ```
1386
- *
1387
- * @returns The current page number, starting from 1
1388
- */
1389
- getCurrentPage() {
1390
- return this.currentPage;
1391
- }
1392
- /**
1393
- * Checks if there are more pages of dinosaurs or habitats to process.
1394
- *
1395
- * This method takes into account both:
1396
- * - DynamoDB's lastEvaluatedKey mechanism
1397
- * - Any overall limit set on the query
1398
- *
1399
- * @example
1400
- * ```ts
1401
- * // Process all security incidents
1402
- * const paginator = new QueryBuilder(executor, eq('type', 'SECURITY_BREACH'))
1403
- * .sortDescending()
1404
- * .paginate(10);
1405
- *
1406
- * while (paginator.hasNextPage()) {
1407
- * const page = await paginator.getNextPage();
1408
- * for (const incident of page.items) {
1409
- * await processSecurityBreach(incident);
1410
- * }
1411
- * console.log(`Processed incidents page ${page.page}`);
1412
- * }
1413
- * ```
1414
- *
1415
- * @returns true if there are more pages available, false otherwise
1416
- */
1417
- hasNextPage() {
1418
- if (this.overallLimit !== void 0 && this.totalItemsRetrieved >= this.overallLimit) {
1419
- return false;
1420
- }
1421
- return this.hasMorePages;
1422
- }
1423
- /**
1424
- * Retrieves the next page of dinosaurs or habitats from DynamoDB.
1425
- *
1426
- * This method handles:
1427
- * - Automatic continuation between groups
1428
- * - Respect for park capacity limits
1429
- * - Group size adjustments for safety
1430
- *
1431
- * @example
1432
- * ```ts
1433
- * const paginator = new QueryBuilder(executor, eq('species', 'Velociraptor'))
1434
- * .filter(op => op.eq('status', 'ACTIVE'))
1435
- * .paginate(5);
1436
- *
1437
- * // Check first raptor group
1438
- * const page1 = await paginator.getNextPage();
1439
- * console.log(`Found ${page1.items.length} active raptors`);
1440
- *
1441
- * // Continue inspection if more groups exist
1442
- * if (page1.hasNextPage) {
1443
- * const page2 = await paginator.getNextPage();
1444
- * console.log(`Inspecting raptor group ${page2.page}`);
1445
- *
1446
- * for (const raptor of page2.items) {
1447
- * await performHealthCheck(raptor);
1448
- * }
1449
- * }
1450
- * ```
1451
- *
1452
- * @returns A promise that resolves to a PaginationResult containing:
1453
- * - items: The dinosaurs/habitats for this page
1454
- * - hasNextPage: Whether more groups exist
1455
- * - page: The current group number
1456
- * - lastEvaluatedKey: DynamoDB's continuation token
1457
- */
1458
- async getNextPage() {
1459
- if (!this.hasNextPage()) {
1460
- return {
1461
- items: [],
1462
- hasNextPage: false,
1463
- page: this.currentPage
1464
- };
1465
- }
1466
- let effectivePageSize = this.pageSize;
1467
- if (this.overallLimit !== void 0) {
1468
- const remainingItems = this.overallLimit - this.totalItemsRetrieved;
1469
- if (remainingItems <= 0) {
1470
- return {
1471
- items: [],
1472
- hasNextPage: false,
1473
- page: this.currentPage
1474
- };
1475
- }
1476
- if (effectivePageSize !== void 0) {
1477
- effectivePageSize = Math.min(effectivePageSize, remainingItems);
1478
- } else {
1479
- effectivePageSize = remainingItems;
1480
- }
1481
- }
1482
- const query = this.queryBuilder.clone();
1483
- if (effectivePageSize !== void 0) {
1484
- query.limit(effectivePageSize);
1485
- }
1486
- if (this.lastEvaluatedKey) {
1487
- query.startFrom(this.lastEvaluatedKey);
1488
- }
1489
- const generator = await query.execute();
1490
- const items = [];
1491
- let itemCount = 0;
1492
- for await (const item of generator) {
1493
- if (effectivePageSize !== void 0 && itemCount >= effectivePageSize) {
1494
- break;
1495
- }
1496
- items.push(item);
1497
- itemCount++;
1498
- }
1499
- const lastEvaluatedKey = generator.getLastEvaluatedKey();
1500
- const result = { items, lastEvaluatedKey };
1501
- this.currentPage += 1;
1502
- this.lastEvaluatedKey = result.lastEvaluatedKey;
1503
- this.totalItemsRetrieved += result.items.length;
1504
- this.hasMorePages = !!result.lastEvaluatedKey && (this.overallLimit === void 0 || this.totalItemsRetrieved < this.overallLimit);
1505
- return {
1506
- items: result.items,
1507
- lastEvaluatedKey: result.lastEvaluatedKey,
1508
- hasNextPage: this.hasNextPage(),
1509
- page: this.currentPage
1510
- };
1511
- }
1512
- /**
1513
- * Gets all remaining dinosaurs or habitats and combines them into a single array.
1514
- *
1515
- * @example
1516
- * ```ts
1517
- * // Get complete carnivore inventory
1518
- * const paginator = new QueryBuilder(executor, eq('diet', 'CARNIVORE'))
1519
- * .filter(op => op.eq('status', 'ACTIVE'))
1520
- * .paginate(10);
1521
- *
1522
- * try {
1523
- * const allCarnivores = await paginator.getAllPages();
1524
- * console.log(`Park contains ${allCarnivores.length} active carnivores`);
1525
- *
1526
- * // Calculate total threat level
1527
- * const totalThreat = allCarnivores.reduce(
1528
- * (sum, dino) => sum + dino.stats.threatLevel,
1529
- * 0
1530
- * );
1531
- * console.log(`Total threat level: ${totalThreat}`);
1532
- * } catch (error) {
1533
- * console.error('Failed to complete carnivore census:', error);
1534
- * }
1535
- * ```
1536
- *
1537
- * @returns A promise that resolves to an array containing all remaining items
1538
- */
1539
- async getAllPages() {
1540
- const allItems = [];
1541
- while (this.hasNextPage()) {
1542
- const result = await this.getNextPage();
1543
- allItems.push(...result.items);
1544
- }
1545
- return allItems;
1546
- }
1547
- };
1548
-
1549
- // src/builders/filter-builder.ts
1550
- var FilterBuilder = class {
1551
- options = {};
1552
- selectedFields = /* @__PURE__ */ new Set();
1553
- /**
1554
- * Sets the maximum number of items to return.
1555
- *
1556
- * Note: This limit applies to the items that match the key condition
1557
- * before any filter expressions are applied.
1558
- *
1559
- * @example
1560
- * ```typescript
1561
- * // Get first 10 dinosaurs
1562
- * const result = await builder
1563
- * .limit(10)
1564
- * .execute();
1565
- * ```
1566
- *
1567
- * @param limit - Maximum number of items to return
1568
- * @returns The builder instance for method chaining
1569
- */
1570
- limit(limit) {
1571
- this.options.limit = limit;
1572
- return this;
1573
- }
1574
- /**
1575
- * Gets the current limit set on the operation.
1576
- * This is used internally by the paginator to manage result sets.
1577
- *
1578
- * @returns The current limit or undefined if no limit is set
1579
- */
1580
- getLimit() {
1581
- return this.options.limit;
1582
- }
1583
- /**
1584
- * Specifies a Global Secondary Index (GSI) to use for the operation.
1585
- *
1586
- * @example
1587
- * ```typescript
1588
- * // Find all dinosaurs of a specific species
1589
- * builder
1590
- * .useIndex('species-status-index')
1591
- * .filter(op => op.eq('status', 'ACTIVE'));
1592
- *
1593
- * // Search high-security habitats
1594
- * builder
1595
- * .useIndex('security-level-index')
1596
- * .filter(op =>
1597
- * op.and([
1598
- * op.gt('securityLevel', 8),
1599
- * op.eq('status', 'OPERATIONAL')
1600
- * ])
1601
- * );
1602
- * ```
1603
- *
1604
- * @param indexName - The name of the GSI to use (type-safe based on table configuration)
1605
- * @returns The builder instance for method chaining
1606
- */
1607
- useIndex(indexName) {
1608
- this.options.indexName = indexName;
1609
- return this;
1610
- }
1611
- /**
1612
- * Sets whether to use strongly consistent reads for the operation.
1613
- *
1614
- * Note:
1615
- * - Consistent reads are not available on GSIs
1616
- * - Consistent reads consume twice the throughput
1617
- * - Default is eventually consistent reads
1618
- *
1619
- * @example
1620
- * ```typescript
1621
- * // Check immediate dinosaur status
1622
- * const result = await builder
1623
- * .filter(op => op.eq('status', 'ACTIVE'))
1624
- * .consistentRead()
1625
- * .execute();
1626
- *
1627
- * // Monitor security breaches
1628
- * const result = await builder
1629
- * .useIndex('primary-index')
1630
- * .consistentRead(isEmergencyMode)
1631
- * .execute();
1632
- * ```
1633
- *
1634
- * @param consistentRead - Whether to use consistent reads (defaults to true)
1635
- * @returns The builder instance for method chaining
1636
- */
1637
- consistentRead(consistentRead = true) {
1638
- this.options.consistentRead = consistentRead;
1639
- return this;
1640
- }
1641
- /**
1642
- * Adds a filter expression to refine the operation results.
1643
- *
1644
- * @example
1645
- * ```typescript
1646
- * // Find aggressive carnivores
1647
- * builder.filter(op =>
1648
- * op.and([
1649
- * op.eq('diet', 'CARNIVORE'),
1650
- * op.gt('aggressionLevel', 7),
1651
- * op.eq('status', 'ACTIVE')
1652
- * ])
1653
- * );
1654
- *
1655
- * // Search suitable breeding habitats
1656
- * builder.filter(op =>
1657
- * op.and([
1658
- * op.between('temperature', 25, 30),
1659
- * op.lt('currentOccupants', 3),
1660
- * op.eq('quarantineStatus', 'CLEAR')
1661
- * ])
1662
- * );
1663
- * ```
1664
- *
1665
- * @param condition - Either a Condition object or a callback function that builds the condition
1666
- * @returns The builder instance for method chaining
1667
- */
1668
- filter(condition) {
1669
- const newCondition = typeof condition === "function" ? condition(this.getConditionOperator()) : condition;
1670
- if (this.options.filter) {
1671
- if (this.options.filter.type === "and" && this.options.filter.conditions) {
1672
- this.options.filter = {
1673
- type: "and",
1674
- conditions: [...this.options.filter.conditions, newCondition]
1675
- };
1676
- } else {
1677
- this.options.filter = and(this.options.filter, newCondition);
1678
- }
1679
- } else {
1680
- this.options.filter = newCondition;
1681
- }
1682
- return this;
1683
- }
1684
- getConditionOperator() {
1685
- return {
1686
- eq,
1687
- ne,
1688
- lt,
1689
- lte,
1690
- gt,
1691
- gte,
1692
- between,
1693
- inArray,
1694
- beginsWith,
1695
- contains,
1696
- attributeExists,
1697
- attributeNotExists,
1698
- and,
1699
- or,
1700
- not
1701
- };
1702
- }
1703
- /**
1704
- * Specifies which attributes to return in the results.
1705
- *
1706
- * @example
1707
- * ```typescript
1708
- * // Get basic dinosaur info
1709
- * builder.select([
1710
- * 'species',
1711
- * 'status',
1712
- * 'stats.health',
1713
- * 'stats.aggressionLevel'
1714
- * ]);
1715
- *
1716
- * // Monitor habitat conditions
1717
- * builder
1718
- * .select('securityStatus')
1719
- * .select([
1720
- * 'currentOccupants',
1721
- * 'temperature',
1722
- * 'lastInspectionDate'
1723
- * ]);
1724
- * ```
1725
- *
1726
- * @param fields - A single field name or an array of field names to return
1727
- * @returns The builder instance for method chaining
1728
- */
1729
- select(fields) {
1730
- if (typeof fields === "string") {
1731
- this.selectedFields.add(fields);
1732
- } else if (Array.isArray(fields)) {
1733
- for (const field of fields) {
1734
- this.selectedFields.add(field);
1735
- }
1736
- }
1737
- this.options.projection = Array.from(this.selectedFields);
1738
- return this;
1739
- }
1740
- /**
1741
- * Creates a paginator that handles DynamoDB pagination automatically.
1742
- * The paginator handles:
1743
- * - Tracking the last evaluated key
1744
- * - Managing page boundaries
1745
- * - Respecting overall query limits
1746
- *
1747
- * @example
1748
- * ```typescript
1749
- * // Create a paginator for dinosaur records with specific page size
1750
- * const paginator = builder
1751
- * .filter(op => op.eq('status', 'ACTIVE'))
1752
- * .paginate(10);
1753
- *
1754
- * // Create a paginator with automatic DynamoDB paging (no page size limit)
1755
- * const autoPaginator = builder
1756
- * .filter(op => op.eq('status', 'ACTIVE'))
1757
- * .paginate();
1758
- *
1759
- * // Process pages of dinosaur results
1760
- * while (paginator.hasNextPage()) {
1761
- * const page = await paginator.getNextPage();
1762
- * console.log(`Processing page ${page.page}, count: ${page.items.length}`);
1763
- * // Process dinosaur data
1764
- * }
1765
- * ```
1766
- *
1767
- * @param pageSize - The number of items to return per page. If not provided, DynamoDB will automatically determine page sizes.
1768
- * @returns A Paginator instance that manages the pagination state
1769
- * @see Paginator for more pagination control options
1770
- */
1771
- paginate(pageSize) {
1772
- return new Paginator(this, pageSize);
1773
- }
1774
- /**
1775
- * Sets the starting point using a previous lastEvaluatedKey.
1776
- *
1777
- * Note: This method is typically used for manual pagination.
1778
- * For automatic pagination, use the paginate() method instead.
1779
- *
1780
- * @example
1781
- * ```typescript
1782
- * // First batch of dinosaurs
1783
- * const result1 = await builder
1784
- * .filter(op => op.eq('status', 'ACTIVE'))
1785
- * .limit(5)
1786
- * .execute();
1787
- *
1788
- * const lastKey = result1.getLastEvaluatedKey();
1789
- * if (lastKey) {
1790
- * // Continue listing dinosaurs
1791
- * const result2 = await builder
1792
- * .filter(op => op.eq('status', 'ACTIVE'))
1793
- * .startFrom(lastKey)
1794
- * .limit(5)
1795
- * .execute();
1796
- *
1797
- * const items = await result2.toArray();
1798
- * console.log('Additional dinosaurs:', items);
1799
- * }
1800
- * ```
1801
- *
1802
- * @param lastEvaluatedKey - The exclusive start key from a previous result
1803
- * @returns The builder instance for method chaining
1804
- */
1805
- startFrom(lastEvaluatedKey) {
1806
- this.options.lastEvaluatedKey = lastEvaluatedKey;
1807
- return this;
1808
- }
1809
- };
1810
-
1811
- // src/builders/result-iterator.ts
1812
- var ResultIterator = class {
1813
- constructor(queryBuilder, directExecutor) {
1814
- this.queryBuilder = queryBuilder;
1815
- this.directExecutor = directExecutor;
1816
- this.overallLimit = queryBuilder.getLimit();
1817
- }
1818
- lastEvaluatedKey;
1819
- itemsYielded = 0;
1820
- overallLimit;
1821
- /**
1822
- * Async iterator with automatic pagination
1823
- */
1824
- async *[Symbol.asyncIterator]() {
1825
- let hasMorePages = true;
1826
- while (hasMorePages) {
1827
- const result = await this.directExecutor();
1828
- for (const item of result.items) {
1829
- if (this.overallLimit !== void 0 && this.itemsYielded >= this.overallLimit) {
1830
- return;
1831
- }
1832
- yield item;
1833
- this.itemsYielded++;
1834
- }
1835
- if (result.lastEvaluatedKey !== null && result.lastEvaluatedKey !== void 0) {
1836
- this.lastEvaluatedKey = result.lastEvaluatedKey;
1837
- this.queryBuilder.startFrom(result.lastEvaluatedKey);
1838
- } else if (result.lastEvaluatedKey === null) {
1839
- if (this.lastEvaluatedKey === void 0) {
1840
- this.lastEvaluatedKey = null;
1841
- }
1842
- }
1843
- hasMorePages = !!result.lastEvaluatedKey && (this.overallLimit === void 0 || this.itemsYielded < this.overallLimit);
1844
- }
1845
- }
1846
- /**
1847
- * Convert to array (loads all pages).
1848
- *
1849
- * ```ts
1850
- * const result = await table.query({ pk: "foo" }).execute();
1851
- * const allItemsFromDynamo = await result.toArray();
1852
- * ```
1853
- *
1854
- * Note: This will load all pages into memory. For large datasets, consider using async iteration instead.
1855
- *```ts
1856
- * const result = await table.query({ pk: "foo" }).execute();
1857
- * for await (const item of result) {
1858
- * // Process each item
1859
- * }
1860
- * ```
1861
- */
1862
- async toArray() {
1863
- const items = [];
1864
- for await (const item of this) {
1865
- items.push(item);
1866
- }
1867
- return items;
1868
- }
1869
- /**
1870
- * Get the last evaluated key
1871
- */
1872
- getLastEvaluatedKey() {
1873
- return this.lastEvaluatedKey === null ? void 0 : this.lastEvaluatedKey;
1874
- }
1875
- };
1876
-
1877
- // src/builders/query-builder.ts
1878
- var QueryBuilder = class _QueryBuilder extends FilterBuilder {
1879
- keyCondition;
1880
- options = {};
1881
- executor;
1882
- constructor(executor, keyCondition) {
1883
- super();
1884
- this.executor = executor;
1885
- this.keyCondition = keyCondition;
1886
- }
1887
- /**
1888
- * Sets the maximum number of items to return from the query.
1889
- *
1890
- * Note: This is the default behavior if no sort order is specified.
1891
- *
1892
- * @example
1893
- * ```typescript
1894
- * // Get orders in chronological order
1895
- * const result = await new QueryBuilder(executor, eq('userId', '123'))
1896
- * .sortAscending()
1897
- * .execute();
1898
- *
1899
- * // Get events from oldest to newest
1900
- * const result = await new QueryBuilder(executor, eq('entityId', 'order-123'))
1901
- * .useIndex('entity-timestamp-index')
1902
- * .sortAscending()
1903
- * .execute();
1904
- * ```
1905
- *
1906
- * @returns The builder instance for method chaining
1907
- */
1908
- /**
1909
- * Sets the query to return items in ascending order by sort key.
1910
- *
1911
- * @example
1912
- * ```typescript
1913
- * // List dinosaurs by age
1914
- * const result = await new QueryBuilder(executor, eq('species', 'Velociraptor'))
1915
- * .useIndex('age-index')
1916
- * .sortAscending()
1917
- * .execute();
1918
- *
1919
- * // View incidents chronologically
1920
- * const result = await new QueryBuilder(executor, eq('type', 'SECURITY_BREACH'))
1921
- * .useIndex('date-index')
1922
- * .sortAscending()
1923
- * .execute();
1924
- * ```
1925
- *
1926
- * @returns The builder instance for method chaining
1927
- */
1928
- sortAscending() {
1929
- this.options.scanIndexForward = true;
1930
- return this;
1931
- }
1932
- /**
1933
- * Sets the query to return items in descending order by sort key.
1934
- *
1935
- * @example
1936
- * ```typescript
1937
- * // Get most recent security incidents
1938
- * const result = await new QueryBuilder(executor, eq('type', 'SECURITY_BREACH'))
1939
- * .useIndex('date-index')
1940
- * .sortDescending()
1941
- * .limit(10)
1942
- * .execute();
1943
- *
1944
- * // Check latest dinosaur activities
1945
- * const result = await new QueryBuilder(executor, eq('species', 'Velociraptor'))
1946
- * .useIndex('activity-time-index')
1947
- * .filter(op => op.eq('status', 'ACTIVE'))
1948
- * .sortDescending()
1949
- * .execute();
1950
- * ```
1951
- *
1952
- * @returns The builder instance for method chaining
1953
- */
1954
- sortDescending() {
1955
- this.options.scanIndexForward = false;
1956
- return this;
1957
- }
1958
- /**
1959
- * Creates a deep clone of this QueryBuilder instance.
1960
- *
1961
- * This is particularly useful when:
1962
- * - Implementing pagination (used internally by paginate())
1963
- * - Creating query templates
1964
- * - Running multiple variations of a query
1965
- *
1966
- * @example
1967
- * ```typescript
1968
- * // Create base dinosaur query
1969
- * const baseQuery = new QueryBuilder(executor, eq('species', 'Velociraptor'))
1970
- * .useIndex('status-index')
1971
- * .select(['id', 'status', 'location']);
1972
- *
1973
- * // Check active dinosaurs
1974
- * const activeRaptors = baseQuery.clone()
1975
- * .filter(op => op.eq('status', 'HUNTING'))
1976
- * .execute();
1977
- *
1978
- * // Check contained dinosaurs
1979
- * const containedRaptors = baseQuery.clone()
1980
- * .filter(op => op.eq('status', 'CONTAINED'))
1981
- * .execute();
1982
- *
1983
- * // Check sedated dinosaurs
1984
- * const sedatedRaptors = baseQuery.clone()
1985
- * .filter(op => op.eq('status', 'SEDATED'))
1986
- * .execute();
1987
- * ```
1988
- *
1989
- * @returns A new QueryBuilder instance with the same configuration
1990
- */
1991
- clone() {
1992
- const clone = new _QueryBuilder(this.executor, this.keyCondition);
1993
- clone.options = {
1994
- ...this.options,
1995
- filter: this.deepCloneFilter(this.options.filter)
1996
- };
1997
- clone.selectedFields = new Set(this.selectedFields);
1998
- return clone;
1999
- }
2000
- deepCloneFilter(filter) {
2001
- if (!filter) return filter;
2002
- if (filter.type === "and" || filter.type === "or") {
2003
- return {
2004
- ...filter,
2005
- conditions: filter.conditions?.map((condition) => this.deepCloneFilter(condition)).filter((c) => c !== void 0)
2006
- };
2007
- }
2008
- return { ...filter };
2009
- }
2010
- /**
2011
- * Executes the query against DynamoDB and returns a generator that behaves like an array.
2012
- *
2013
- * The generator automatically handles pagination and provides array-like methods
2014
- * for processing results efficiently without loading everything into memory at once.
2015
- *
2016
- * @example
2017
- * ```typescript
2018
- * try {
2019
- * // Find active carnivores with automatic pagination
2020
- * const results = await new QueryBuilder(executor, eq('habitatId', 'PADDOCK-A'))
2021
- * .useIndex('species-status-index')
2022
- * .filter(op =>
2023
- * op.and([
2024
- * op.eq('diet', 'CARNIVORE'),
2025
- * op.eq('status', 'ACTIVE'),
2026
- * op.gt('aggressionLevel', 7)
2027
- * ])
2028
- * )
2029
- * .sortDescending()
2030
- * .execute();
2031
- *
2032
- * // Use like an array with automatic pagination
2033
- * for await (const dinosaur of results) {
2034
- * console.log(`Processing ${dinosaur.name}`);
2035
- * }
2036
- *
2037
- * // Or convert to array and use array methods
2038
- * const allItems = await results.toArray();
2039
- * const dangerousOnes = allItems.filter(dino => dino.aggressionLevel > 9);
2040
- * const totalCount = allItems.length;
2041
- * } catch (error) {
2042
- * console.error('Security scan failed:', error);
2043
- * }
2044
- * ```
2045
- *
2046
- * @returns A promise that resolves to a ResultGenerator that behaves like an array
2047
- */
2048
- async execute() {
2049
- const directExecutor = () => this.executor(this.keyCondition, this.options);
2050
- return new ResultIterator(this, directExecutor);
2051
- }
2052
- };
2053
-
2054
- // src/builders/scan-builder.ts
2055
- var ScanBuilder = class _ScanBuilder extends FilterBuilder {
2056
- executor;
2057
- constructor(executor) {
2058
- super();
2059
- this.executor = executor;
2060
- }
2061
- /**
2062
- * Creates a deep clone of this ScanBuilder instance.
2063
- *
2064
- * @returns A new ScanBuilder instance with the same configuration
2065
- */
2066
- clone() {
2067
- const clone = new _ScanBuilder(this.executor);
2068
- clone.options = {
2069
- ...this.options,
2070
- filter: this.deepCloneFilter(this.options.filter)
2071
- };
2072
- clone.selectedFields = new Set(this.selectedFields);
2073
- return clone;
2074
- }
2075
- deepCloneFilter(filter) {
2076
- if (!filter) return filter;
2077
- if (filter.type === "and" || filter.type === "or") {
2078
- return {
2079
- ...filter,
2080
- conditions: filter.conditions?.map((condition) => this.deepCloneFilter(condition)).filter((c) => c !== void 0)
2081
- };
2082
- }
2083
- return { ...filter };
2084
- }
2085
- /**
2086
- * Executes the scan against DynamoDB and returns a generator that behaves like an array.
2087
- *
2088
- * The generator automatically handles pagination and provides array-like methods
2089
- * for processing results efficiently without loading everything into memory at once.
2090
- *
2091
- * @example
2092
- * ```typescript
2093
- * try {
2094
- * // Find all dinosaurs with high aggression levels with automatic pagination
2095
- * const results = await new ScanBuilder(executor)
2096
- * .filter(op =>
2097
- * op.and([
2098
- * op.eq('status', 'ACTIVE'),
2099
- * op.gt('aggressionLevel', 7)
2100
- * ])
2101
- * )
2102
- * .execute();
2103
- *
2104
- * // Use like an array with automatic pagination
2105
- * for await (const dinosaur of results) {
2106
- * console.log(`Processing dangerous dinosaur: ${dinosaur.name}`);
2107
- * }
2108
- *
2109
- * // Or convert to array and use array methods
2110
- * const allItems = await results.toArray();
2111
- * const criticalThreats = allItems.filter(dino => dino.aggressionLevel > 9);
2112
- * const totalCount = allItems.length;
2113
- * } catch (error) {
2114
- * console.error('Security scan failed:', error);
2115
- * }
2116
- * ```
2117
- *
2118
- * @returns A promise that resolves to a ResultGenerator that behaves like an array
2119
- */
2120
- async execute() {
2121
- const directExecutor = () => this.executor(this.options);
2122
- return new ResultIterator(this, directExecutor);
2123
- }
2124
- };
2125
-
2126
- // src/utils/debug-transaction.ts
2127
- function debugTransactionItem(item) {
2128
- const result = {
2129
- type: item.type,
2130
- tableName: item.params.tableName
2131
- };
2132
- if ("key" in item.params) {
2133
- result.key = item.params.key;
2134
- }
2135
- if (item.type === "Put") {
2136
- result.item = item.params.item;
2137
- }
2138
- switch (item.type) {
2139
- case "Put":
2140
- case "Delete":
2141
- case "ConditionCheck":
2142
- result.readable = debugCommand(item.params).readable;
2143
- break;
2144
- case "Update":
2145
- result.readable = debugCommand(item.params).readable;
2146
- break;
2147
- }
2148
- return result;
2149
- }
2150
- function debugTransaction(items) {
2151
- return items.map((item) => debugTransactionItem(item));
2152
- }
2153
-
2154
- // src/builders/transaction-builder.ts
2155
- var TransactionBuilder = class {
2156
- items = [];
2157
- options = {};
2158
- indexConfig;
2159
- executor;
2160
- constructor(executor, indexConfig) {
2161
- this.executor = executor;
2162
- this.indexConfig = indexConfig;
2163
- }
2164
- /**
2165
- * Checks if an item with the same primary key already exists in the transaction
2166
- * @private
2167
- */
2168
- checkForDuplicateItem(tableName, newItem) {
2169
- const pkName = this.indexConfig.partitionKey;
2170
- const skName = this.indexConfig.sortKey ?? "";
2171
- const pkValue = newItem[pkName];
2172
- const skValue = skName ? newItem[skName] : void 0;
2173
- if (!pkValue) {
2174
- throw new Error(`Primary key value for '${pkName}' is missing`);
2175
- }
2176
- const duplicateItem = this.items.find((item) => {
2177
- let itemKey;
2178
- let itemTableName;
2179
- switch (item.type) {
2180
- case "Put":
2181
- itemTableName = item.params.tableName;
2182
- itemKey = item.params.item;
2183
- break;
2184
- case "Update":
2185
- case "Delete":
2186
- case "ConditionCheck":
2187
- itemTableName = item.params.tableName;
2188
- itemKey = item.params.key;
2189
- break;
2190
- }
2191
- if (itemTableName === tableName && itemKey) {
2192
- const itemPkValue = itemKey[pkName];
2193
- const itemSkValue = skName ? itemKey[skName] : void 0;
2194
- if (itemPkValue === pkValue) {
2195
- if (skValue === void 0 && itemSkValue === void 0) {
2196
- return true;
2197
- }
2198
- if (skValue !== void 0 && itemSkValue !== void 0 && skValue === itemSkValue) {
2199
- return true;
2200
- }
2201
- }
2202
- }
2203
- return false;
2204
- });
2205
- if (duplicateItem) {
2206
- throw new Error(
2207
- `Duplicate item detected in transaction: Table=${tableName}, ${pkName}=${String(pkValue)}, ${skName}=${skValue !== void 0 ? String(skValue) : "undefined"}. DynamoDB transactions do not allow multiple operations on the same item.`
2208
- );
2209
- }
2210
- }
2211
- createKeyForPrimaryIndex(key) {
2212
- const keyCondition = {
2213
- [this.indexConfig.partitionKey]: key.pk
2214
- };
2215
- if (this.indexConfig.sortKey) {
2216
- if (key.sk === void 0) {
2217
- throw new Error("Sort key is required for delete operation");
2218
- }
2219
- keyCondition[this.indexConfig.sortKey] = key.sk;
2220
- }
2221
- return keyCondition;
2222
- }
2223
- /**
2224
- * Adds a put operation to the transaction.
2225
- *
2226
- * The method automatically checks for duplicate items within the transaction
2227
- * to prevent multiple operations on the same item.
2228
- *
2229
- * @example
2230
- * ```typescript
2231
- * // Simple put operation
2232
- * transaction.put('orders', {
2233
- * orderId: '123',
2234
- * status: 'PENDING',
2235
- * amount: 100
2236
- * });
2237
- *
2238
- * // Conditional put operation
2239
- * transaction.put(
2240
- * 'inventory',
2241
- * { productId: 'ABC', quantity: 50 },
2242
- * op => op.attributeNotExists('productId')
2243
- * );
2244
- *
2245
- * // Put with complex condition
2246
- * transaction.put(
2247
- * 'users',
2248
- * { userId: '123', status: 'ACTIVE' },
2249
- * op => op.and([
2250
- * op.attributeNotExists('userId'),
2251
- * op.beginsWith('status', 'ACTIVE')
2252
- * ])
2253
- * );
2254
- * ```
2255
- *
2256
- * @param tableName - The name of the DynamoDB table
2257
- * @param item - The item to put into the table
2258
- * @param condition - Optional condition that must be satisfied
2259
- * @returns The transaction builder for method chaining
2260
- * @throws {Error} If a duplicate item is detected in the transaction
2261
- */
2262
- put(tableName, item, condition) {
2263
- this.checkForDuplicateItem(tableName, item);
2264
- const transactionItem = {
2265
- type: "Put",
2266
- params: {
2267
- tableName,
2268
- item
2269
- }
2270
- };
2271
- if (condition) {
2272
- const { expression, names, values } = prepareExpressionParams(condition);
2273
- transactionItem.params.conditionExpression = expression;
2274
- transactionItem.params.expressionAttributeNames = names;
2275
- transactionItem.params.expressionAttributeValues = values;
2276
- }
2277
- this.items.push(transactionItem);
2278
- return this;
2279
- }
2280
- /**
2281
- * Adds a pre-configured put operation to the transaction.
2282
- *
2283
- * This method is particularly useful when working with PutBuilder
2284
- * to maintain consistency in put operations across your application.
2285
- *
2286
- * @example
2287
- * ```typescript
2288
- * // Create a put command with PutBuilder
2289
- * const putCommand = new PutBuilder(executor, newItem, 'users')
2290
- * .condition(op => op.attributeNotExists('userId'))
2291
- * .toDynamoCommand();
2292
- *
2293
- * // Add the command to the transaction
2294
- * transaction.putWithCommand(putCommand);
2295
- * ```
2296
- *
2297
- * @param command - The complete put command configuration
2298
- * @returns The transaction builder for method chaining
2299
- * @throws {Error} If a duplicate item is detected in the transaction
2300
- * @see PutBuilder for creating put commands
2301
- */
2302
- putWithCommand(command) {
2303
- this.checkForDuplicateItem(command.tableName, command.item);
2304
- const transactionItem = {
2305
- type: "Put",
2306
- params: command
2307
- };
2308
- this.items.push(transactionItem);
2309
- return this;
2310
- }
2311
- /**
2312
- * Adds a delete operation to the transaction.
2313
- *
2314
- * The method automatically checks for duplicate items within the transaction
2315
- * to prevent multiple operations on the same item.
2316
- *
2317
- * @example
2318
- * ```typescript
2319
- * // Simple delete operation
2320
- * transaction.delete('orders', {
2321
- * pk: 'ORDER#123',
2322
- * sk: 'METADATA'
2323
- * });
2324
- *
2325
- * // Conditional delete operation
2326
- * transaction.delete(
2327
- * 'users',
2328
- * { pk: 'USER#123' },
2329
- * op => op.eq('status', 'INACTIVE')
2330
- * );
2331
- *
2332
- * // Delete with complex condition
2333
- * transaction.delete(
2334
- * 'products',
2335
- * { pk: 'PROD#ABC' },
2336
- * op => op.and([
2337
- * op.eq('status', 'DRAFT'),
2338
- * op.lt('version', 5)
2339
- * ])
2340
- * );
2341
- * ```
2342
- *
2343
- * @param tableName - The name of the DynamoDB table
2344
- * @param key - The primary key of the item to delete
2345
- * @param condition - Optional condition that must be satisfied
2346
- * @returns The transaction builder for method chaining
2347
- * @throws {Error} If a duplicate item is detected in the transaction
2348
- */
2349
- delete(tableName, key, condition) {
2350
- const keyCondition = this.createKeyForPrimaryIndex(key);
2351
- this.checkForDuplicateItem(tableName, keyCondition);
2352
- const transactionItem = {
2353
- type: "Delete",
2354
- params: {
2355
- tableName,
2356
- key: keyCondition
2357
- }
2358
- };
2359
- if (condition) {
2360
- const { expression, names, values } = prepareExpressionParams(condition);
2361
- transactionItem.params.conditionExpression = expression;
2362
- transactionItem.params.expressionAttributeNames = names;
2363
- transactionItem.params.expressionAttributeValues = values;
2364
- }
2365
- this.items.push(transactionItem);
2366
- return this;
2367
- }
2368
- /**
2369
- * Adds a pre-configured delete operation to the transaction.
2370
- *
2371
- * This method is particularly useful when working with DeleteBuilder
2372
- * to maintain consistency in delete operations across your application.
2373
- *
2374
- * @example
2375
- * ```typescript
2376
- * // Create a delete command with DeleteBuilder
2377
- * const deleteCommand = new DeleteBuilder(executor, 'users', { pk: 'USER#123' })
2378
- * .condition(op => op.and([
2379
- * op.attributeExists('pk'),
2380
- * op.eq('status', 'INACTIVE')
2381
- * ]))
2382
- * .toDynamoCommand();
2383
- *
2384
- * // Add the command to the transaction
2385
- * transaction.deleteWithCommand(deleteCommand);
2386
- * ```
2387
- *
2388
- * @param command - The complete delete command configuration
2389
- * @returns The transaction builder for method chaining
2390
- * @throws {Error} If a duplicate item is detected in the transaction
2391
- * @see DeleteBuilder for creating delete commands
2392
- */
2393
- deleteWithCommand(command) {
2394
- let keyForDuplicateCheck;
2395
- let keyForTransaction;
2396
- if (typeof command.key === "object" && command.key !== null && "pk" in command.key) {
2397
- keyForTransaction = this.createKeyForPrimaryIndex(command.key);
2398
- keyForDuplicateCheck = keyForTransaction;
2399
- } else {
2400
- keyForTransaction = command.key;
2401
- keyForDuplicateCheck = command.key;
2402
- }
2403
- this.checkForDuplicateItem(command.tableName, keyForDuplicateCheck);
2404
- const transactionItem = {
2405
- type: "Delete",
2406
- params: {
2407
- ...command,
2408
- key: keyForTransaction
2409
- }
2410
- };
2411
- this.items.push(transactionItem);
2412
- return this;
2413
- }
2414
- /**
2415
- * Adds an update operation to the transaction.
2416
- *
2417
- * The method supports all DynamoDB update expressions:
2418
- * - SET: Modify or add attributes
2419
- * - REMOVE: Delete attributes
2420
- * - ADD: Update numbers and sets
2421
- * - DELETE: Remove elements from a set
2422
- *
2423
- * @example
2424
- * ```typescript
2425
- * // Simple update
2426
- * transaction.update(
2427
- * 'orders',
2428
- * { pk: 'ORDER#123' },
2429
- * 'SET #status = :status',
2430
- * { '#status': 'status' },
2431
- * { ':status': 'PROCESSING' }
2432
- * );
2433
- *
2434
- * // Complex update with multiple operations
2435
- * transaction.update(
2436
- * 'products',
2437
- * { pk: 'PROD#ABC' },
2438
- * 'SET #qty = #qty - :amount, #status = :status REMOVE #oldAttr',
2439
- * { '#qty': 'quantity', '#status': 'status', '#oldAttr': 'deprecated_field' },
2440
- * { ':amount': 1, ':status': 'LOW_STOCK' }
2441
- * );
2442
- *
2443
- * // Conditional update
2444
- * transaction.update(
2445
- * 'users',
2446
- * { pk: 'USER#123' },
2447
- * 'SET #lastLogin = :now',
2448
- * { '#lastLogin': 'lastLoginDate' },
2449
- * { ':now': new Date().toISOString() },
2450
- * op => op.attributeExists('pk')
2451
- * );
2452
- * ```
2453
- *
2454
- * @param tableName - The name of the DynamoDB table
2455
- * @param key - The primary key of the item to update
2456
- * @param updateExpression - The update expression (SET, REMOVE, ADD, DELETE)
2457
- * @param expressionAttributeNames - Map of attribute name placeholders to actual names
2458
- * @param expressionAttributeValues - Map of value placeholders to actual values
2459
- * @param condition - Optional condition that must be satisfied
2460
- * @returns The transaction builder for method chaining
2461
- * @throws {Error} If a duplicate item is detected in the transaction
2462
- */
2463
- update(tableName, key, updateExpression, expressionAttributeNames, expressionAttributeValues, condition) {
2464
- const keyCondition = this.createKeyForPrimaryIndex(key);
2465
- this.checkForDuplicateItem(tableName, keyCondition);
2466
- const transactionItem = {
2467
- type: "Update",
2468
- params: {
2469
- tableName,
2470
- key: keyCondition,
2471
- updateExpression,
2472
- expressionAttributeNames,
2473
- expressionAttributeValues
2474
- }
2475
- };
2476
- if (condition) {
2477
- const { expression, names, values } = prepareExpressionParams(condition);
2478
- transactionItem.params.conditionExpression = expression;
2479
- transactionItem.params.expressionAttributeNames = {
2480
- ...transactionItem.params.expressionAttributeNames,
2481
- ...names
2482
- };
2483
- transactionItem.params.expressionAttributeValues = {
2484
- ...transactionItem.params.expressionAttributeValues,
2485
- ...values
2486
- };
2487
- }
2488
- this.items.push(transactionItem);
2489
- return this;
2490
- }
2491
- /**
2492
- * Adds a pre-configured update operation to the transaction.
2493
- *
2494
- * This method is particularly useful when working with UpdateBuilder
2495
- * to maintain consistency in update operations across your application.
2496
- *
2497
- * @example
2498
- * ```typescript
2499
- * // Create an update command with UpdateBuilder
2500
- * const updateCommand = new UpdateBuilder(executor, 'inventory', { pk: 'PROD#ABC' })
2501
- * .set('quantity', ':qty')
2502
- * .set('lastUpdated', ':now')
2503
- * .values({
2504
- * ':qty': 100,
2505
- * ':now': new Date().toISOString()
2506
- * })
2507
- * .condition(op => op.gt('quantity', 0))
2508
- * .toDynamoCommand();
2509
- *
2510
- * // Add the command to the transaction
2511
- * transaction.updateWithCommand(updateCommand);
2512
- * ```
2513
- *
2514
- * @param command - The complete update command configuration
2515
- * @returns The transaction builder for method chaining
2516
- * @throws {Error} If a duplicate item is detected in the transaction
2517
- * @see UpdateBuilder for creating update commands
2518
- */
2519
- updateWithCommand(command) {
2520
- let keyForDuplicateCheck;
2521
- let keyForTransaction;
2522
- if (typeof command.key === "object" && command.key !== null && "pk" in command.key) {
2523
- keyForTransaction = this.createKeyForPrimaryIndex(command.key);
2524
- keyForDuplicateCheck = keyForTransaction;
2525
- } else {
2526
- keyForTransaction = command.key;
2527
- keyForDuplicateCheck = command.key;
2528
- }
2529
- this.checkForDuplicateItem(command.tableName, keyForDuplicateCheck);
2530
- const transactionItem = {
2531
- type: "Update",
2532
- params: {
2533
- ...command,
2534
- key: keyForTransaction
2535
- }
2536
- };
2537
- this.items.push(transactionItem);
2538
- return this;
2539
- }
2540
- /**
2541
- * Adds a condition check operation to the transaction.
2542
- *
2543
- * Condition checks are particularly useful for:
2544
- * - Implementing optimistic locking
2545
- * - Ensuring referential integrity
2546
- * - Validating business rules atomically
2547
- *
2548
- * @example
2549
- * ```typescript
2550
- * // Check if order is in correct state
2551
- * transaction.conditionCheck(
2552
- * 'orders',
2553
- * { pk: 'ORDER#123' },
2554
- * op => op.eq('status', 'PENDING')
2555
- * );
2556
- *
2557
- * // Complex condition check
2558
- * transaction.conditionCheck(
2559
- * 'inventory',
2560
- * { pk: 'PROD#ABC' },
2561
- * op => op.and([
2562
- * op.gt('quantity', 0),
2563
- * op.eq('status', 'ACTIVE'),
2564
- * op.attributeExists('lastRestockDate')
2565
- * ])
2566
- * );
2567
- *
2568
- * // Check with multiple attributes
2569
- * transaction.conditionCheck(
2570
- * 'users',
2571
- * { pk: 'USER#123' },
2572
- * op => op.or([
2573
- * op.eq('status', 'PREMIUM'),
2574
- * op.gte('credits', 100)
2575
- * ])
2576
- * );
2577
- * ```
2578
- *
2579
- * @param tableName - The name of the DynamoDB table
2580
- * @param key - The primary key of the item to check
2581
- * @param condition - The condition that must be satisfied
2582
- * @returns The transaction builder for method chaining
2583
- * @throws {Error} If a duplicate item is detected in the transaction
2584
- * @throws {Error} If condition expression generation fails
2585
- */
2586
- conditionCheck(tableName, key, condition) {
2587
- const keyCondition = this.createKeyForPrimaryIndex(key);
2588
- this.checkForDuplicateItem(tableName, keyCondition);
2589
- const { expression, names, values } = prepareExpressionParams(condition);
2590
- if (!expression) {
2591
- throw new Error("Failed to generate condition expression");
2592
- }
2593
- const transactionItem = {
2594
- type: "ConditionCheck",
2595
- params: {
2596
- tableName,
2597
- key: keyCondition,
2598
- conditionExpression: expression,
2599
- expressionAttributeNames: names,
2600
- expressionAttributeValues: values
2601
- }
2602
- };
2603
- this.items.push(transactionItem);
2604
- return this;
2605
- }
2606
- /**
2607
- * Adds a pre-configured condition check operation to the transaction.
2608
- *
2609
- * This method is particularly useful when working with ConditionCheckBuilder
2610
- * to maintain consistency in condition checks across your application.
2611
- *
2612
- * @example
2613
- * ```typescript
2614
- * // Create a condition check with ConditionCheckBuilder
2615
- * const checkCommand = new ConditionCheckBuilder('inventory', { pk: 'PROD#ABC' })
2616
- * .condition(op => op.and([
2617
- * op.between('quantity', 10, 100),
2618
- * op.beginsWith('category', 'ELECTRONICS'),
2619
- * op.attributeExists('lastAuditDate')
2620
- * ]))
2621
- * .toDynamoCommand();
2622
- *
2623
- * // Add the command to the transaction
2624
- * transaction.conditionCheckWithCommand(checkCommand);
2625
- * ```
2626
- *
2627
- * @param command - The complete condition check command configuration
2628
- * @returns The transaction builder for method chaining
2629
- * @throws {Error} If a duplicate item is detected in the transaction
2630
- * @see ConditionCheckBuilder for creating condition check commands
2631
- */
2632
- conditionCheckWithCommand(command) {
2633
- let keyForDuplicateCheck;
2634
- let keyForTransaction;
2635
- if (typeof command.key === "object" && command.key !== null && "pk" in command.key) {
2636
- keyForTransaction = this.createKeyForPrimaryIndex(command.key);
2637
- keyForDuplicateCheck = keyForTransaction;
2638
- } else {
2639
- keyForTransaction = command.key;
2640
- keyForDuplicateCheck = command.key;
2641
- }
2642
- this.checkForDuplicateItem(command.tableName, keyForDuplicateCheck);
2643
- const transactionItem = {
2644
- type: "ConditionCheck",
2645
- params: {
2646
- ...command,
2647
- key: keyForTransaction
2648
- }
2649
- };
2650
- this.items.push(transactionItem);
2651
- return this;
2652
- }
2653
- /**
2654
- * Sets options for the transaction execution.
2655
- *
2656
- * @example
2657
- * ```typescript
2658
- * // Enable idempotency and capacity tracking
2659
- * transaction.withOptions({
2660
- * clientRequestToken: 'unique-request-id-123',
2661
- * returnConsumedCapacity: 'TOTAL'
2662
- * });
2663
- *
2664
- * // Track item collection metrics
2665
- * transaction.withOptions({
2666
- * returnItemCollectionMetrics: 'SIZE'
2667
- * });
2668
- * ```
2669
- *
2670
- * Note: ClientRequestToken can be used to make transactions idempotent,
2671
- * ensuring the same transaction is not executed multiple times.
2672
- *
2673
- * @param options - Configuration options for the transaction
2674
- * @returns The transaction builder for method chaining
2675
- */
2676
- withOptions(options) {
2677
- this.options = { ...this.options, ...options };
2678
- return this;
2679
- }
2680
- /**
2681
- * Gets a human-readable representation of the transaction items.
2682
- *
2683
- * The method resolves all expression placeholders with their actual values,
2684
- * making it easier to understand the transaction's operations.
2685
- *
2686
- * @example
2687
- * ```typescript
2688
- * // Add multiple operations
2689
- * transaction
2690
- * .put('orders', { orderId: '123', status: 'PENDING' })
2691
- * .update('inventory',
2692
- * { productId: 'ABC' },
2693
- * 'SET quantity = quantity - :amount',
2694
- * undefined,
2695
- * { ':amount': 1 }
2696
- * );
2697
- *
2698
- * // Debug the transaction
2699
- * const debugInfo = transaction.debug();
2700
- * console.log('Transaction operations:', debugInfo);
2701
- * ```
2702
- *
2703
- * @returns An array of readable representations of the transaction items
2704
- */
2705
- debug() {
2706
- return debugTransaction(this.items);
2707
- }
2708
- /**
2709
- * Executes all operations in the transaction atomically.
2710
- *
2711
- * The transaction will only succeed if all operations succeed.
2712
- * If any operation fails, the entire transaction is rolled back.
2713
- *
2714
- * @example
2715
- * ```typescript
2716
- * try {
2717
- * // Build and execute transaction
2718
- * await transaction
2719
- * .put('orders', newOrder)
2720
- * .update('inventory',
2721
- * { productId: 'ABC' },
2722
- * 'SET quantity = quantity - :qty',
2723
- * undefined,
2724
- * { ':qty': 1 }
2725
- * )
2726
- * .conditionCheck('products',
2727
- * { productId: 'ABC' },
2728
- * op => op.eq('status', 'ACTIVE')
2729
- * )
2730
- * .execute();
2731
- *
2732
- * console.log('Transaction completed successfully');
2733
- * } catch (error) {
2734
- * // Handle transaction failure
2735
- * console.error('Transaction failed:', error);
2736
- * }
2737
- * ```
2738
- *
2739
- * @throws {Error} If no transaction items are specified
2740
- * @throws {Error} If any operation in the transaction fails
2741
- * @returns A promise that resolves when the transaction completes
2742
- */
2743
- async execute() {
2744
- if (this.items.length === 0) {
2745
- throw new Error("No transaction items specified");
2746
- }
2747
- const transactItems = this.items.map((item) => {
2748
- switch (item.type) {
2749
- case "Put":
2750
- return {
2751
- Put: {
2752
- TableName: item.params.tableName,
2753
- Item: item.params.item,
2754
- ConditionExpression: item.params.conditionExpression,
2755
- ExpressionAttributeNames: item.params.expressionAttributeNames,
2756
- ExpressionAttributeValues: item.params.expressionAttributeValues
2757
- }
2758
- };
2759
- case "Delete":
2760
- return {
2761
- Delete: {
2762
- TableName: item.params.tableName,
2763
- Key: item.params.key,
2764
- ConditionExpression: item.params.conditionExpression,
2765
- ExpressionAttributeNames: item.params.expressionAttributeNames,
2766
- ExpressionAttributeValues: item.params.expressionAttributeValues
2767
- }
2768
- };
2769
- case "Update":
2770
- return {
2771
- Update: {
2772
- TableName: item.params.tableName,
2773
- Key: item.params.key,
2774
- UpdateExpression: item.params.updateExpression,
2775
- ConditionExpression: item.params.conditionExpression,
2776
- ExpressionAttributeNames: item.params.expressionAttributeNames,
2777
- ExpressionAttributeValues: item.params.expressionAttributeValues
2778
- }
2779
- };
2780
- case "ConditionCheck":
2781
- return {
2782
- ConditionCheck: {
2783
- TableName: item.params.tableName,
2784
- Key: item.params.key,
2785
- ConditionExpression: item.params.conditionExpression,
2786
- ExpressionAttributeNames: item.params.expressionAttributeNames,
2787
- ExpressionAttributeValues: item.params.expressionAttributeValues
2788
- }
2789
- };
2790
- default: {
2791
- const exhaustiveCheck = item;
2792
- throw new Error(`Unsupported transaction item type: ${String(exhaustiveCheck)}`);
2793
- }
2794
- }
2795
- });
2796
- const params = {
2797
- TransactItems: transactItems,
2798
- ClientRequestToken: this.options.clientRequestToken,
2799
- ReturnConsumedCapacity: this.options.returnConsumedCapacity,
2800
- ReturnItemCollectionMetrics: this.options.returnItemCollectionMetrics
2801
- };
2802
- try {
2803
- await this.executor(params);
2804
- } catch (error) {
2805
- console.log(this.debug());
2806
- console.error("Error executing transaction:", error);
2807
- throw error;
2808
- }
2809
- }
2810
- };
2811
-
2812
- // src/builders/update-builder.ts
2813
- var UpdateBuilder = class {
2814
- updates = [];
2815
- options = {
2816
- returnValues: "ALL_NEW"
2817
- };
2818
- executor;
2819
- tableName;
2820
- key;
2821
- constructor(executor, tableName, key) {
2822
- this.executor = executor;
2823
- this.tableName = tableName;
2824
- this.key = key;
2825
- }
2826
- set(valuesOrPath, value) {
2827
- if (typeof valuesOrPath === "object") {
2828
- for (const [key, value2] of Object.entries(valuesOrPath)) {
2829
- this.updates.push({
2830
- type: "SET",
2831
- path: key,
2832
- value: value2
2833
- });
2834
- }
2835
- } else {
2836
- this.updates.push({
2837
- type: "SET",
2838
- path: valuesOrPath,
2839
- value
2840
- });
2841
- }
2842
- return this;
2843
- }
2844
- /**
2845
- * Removes an attribute from the item.
2846
- *
2847
- * @example
2848
- * ```typescript
2849
- * // Remove simple attributes
2850
- * builder
2851
- * .remove('temporaryTag')
2852
- * .remove('previousLocation');
2853
- *
2854
- * // Remove nested attributes
2855
- * builder
2856
- * .remove('metadata.testData')
2857
- * .remove('stats.experimentalMetrics');
2858
- * ```
2859
- *
2860
- * @param path - The path to the attribute to remove
2861
- * @returns The builder instance for method chaining
2862
- */
2863
- remove(path) {
2864
- this.updates.push({
2865
- type: "REMOVE",
2866
- path
2867
- });
2868
- return this;
2869
- }
2870
- /**
2871
- * Adds a value to a number attribute or adds elements to a set.
2872
- *
2873
- * @example
2874
- * ```typescript
2875
- * // Increment counters
2876
- * builder
2877
- * .add('escapeAttempts', 1)
2878
- * .add('feedingCount', 1);
2879
- *
2880
- * // Add to sets
2881
- * builder
2882
- * .add('knownBehaviors', new Set(['PACK_HUNTING', 'AMBUSH_TACTICS']))
2883
- * .add('visitedZones', new Set(['ZONE_A', 'ZONE_B']));
2884
- * ```
2885
- *
2886
- * @param path - The path to the attribute to update
2887
- * @param value - The value to add (number or set)
2888
- * @returns The builder instance for method chaining
2889
- */
2890
- add(path, value) {
2891
- this.updates.push({
2892
- type: "ADD",
2893
- path,
2894
- value
2895
- });
2896
- return this;
2897
- }
2898
- /**
2899
- * Removes elements from a set attribute.
2900
- *
2901
- * @example
2902
- * ```typescript
2903
- * // Remove from sets using arrays
2904
- * builder.deleteElementsFromSet(
2905
- * 'allowedHabitats',
2906
- * ['JUNGLE', 'COASTAL']
2907
- * );
2908
- *
2909
- * // Remove from sets using Set DynamoItems
2910
- * builder.deleteElementsFromSet(
2911
- * 'knownBehaviors',
2912
- * new Set(['NOCTURNAL', 'TERRITORIAL'])
2913
- * );
2914
- *
2915
- * // Remove from nested sets
2916
- * builder.deleteElementsFromSet(
2917
- * 'stats.compatibleSpecies',
2918
- * ['VELOCIRAPTOR', 'DILOPHOSAURUS']
2919
- * );
2920
- * ```
2921
- *
2922
- * @param path - The path to the set attribute
2923
- * @param value - Elements to remove (array or Set)
2924
- * @returns The builder instance for method chaining
2925
- */
2926
- deleteElementsFromSet(path, value) {
2927
- let valuesToDelete;
2928
- if (Array.isArray(value)) {
2929
- valuesToDelete = new Set(value);
2930
- } else {
2931
- valuesToDelete = value;
2932
- }
2933
- this.updates.push({
2934
- type: "DELETE",
2935
- path,
2936
- value: valuesToDelete
2937
- });
2938
- return this;
2939
- }
2940
- /**
2941
- * Adds a condition that must be satisfied for the update to succeed.
2942
- *
2943
- * @example
2944
- * ```typescript
2945
- * // Simple condition
2946
- * builder.condition(op =>
2947
- * op.eq('status', 'ACTIVE')
2948
- * );
2949
- *
2950
- * // Health check condition
2951
- * builder.condition(op =>
2952
- * op.and([
2953
- * op.gt('health', 50),
2954
- * op.eq('status', 'HUNTING')
2955
- * ])
2956
- * );
2957
- *
2958
- * // Complex security condition
2959
- * builder.condition(op =>
2960
- * op.and([
2961
- * op.attributeExists('securitySystem'),
2962
- * op.eq('containmentStatus', 'SECURE'),
2963
- * op.lt('aggressionLevel', 8)
2964
- * ])
2965
- * );
2966
- *
2967
- * // Version check (optimistic locking)
2968
- * builder.condition(op =>
2969
- * op.eq('version', currentVersion)
2970
- * );
2971
- * ```
2972
- *
2973
- * @param condition - Either a Condition DynamoItem or a callback function that builds the condition
2974
- * @returns The builder instance for method chaining
2975
- */
2976
- condition(condition) {
2977
- if (typeof condition === "function") {
2978
- const conditionOperator = {
2979
- eq,
2980
- ne,
2981
- lt,
2982
- lte,
2983
- gt,
2984
- gte,
2985
- between,
2986
- inArray,
2987
- beginsWith,
2988
- contains,
2989
- attributeExists,
2990
- attributeNotExists,
2991
- and,
2992
- or,
2993
- not
2994
- };
2995
- this.options.condition = condition(conditionOperator);
2996
- } else {
2997
- this.options.condition = condition;
2998
- }
2999
- return this;
3000
- }
3001
- /**
3002
- * Sets which item attributes to include in the response.
3003
- *
3004
- * Available options:
3005
- * - ALL_NEW: All attributes after the update (default)
3006
- * - UPDATED_NEW: Only updated attributes, new values
3007
- * - ALL_OLD: All attributes before the update
3008
- * - UPDATED_OLD: Only updated attributes, old values
3009
- * - NONE: No attributes returned
3010
- *
3011
- * @example
3012
- * ```typescript
3013
- * // Get complete updated dinosaur
3014
- * const result = await builder
3015
- * .set('status', 'SLEEPING')
3016
- * .returnValues('ALL_NEW')
3017
- * .execute();
3018
- *
3019
- * // Track specific attribute changes
3020
- * const result = await builder
3021
- * .set({
3022
- * 'stats.health': 100,
3023
- * 'stats.energy': 95
3024
- * })
3025
- * .returnValues('UPDATED_OLD')
3026
- * .execute();
3027
- *
3028
- * if (result.item) {
3029
- * console.log('Previous health:', result.item.stats?.health);
3030
- * }
3031
- * ```
3032
- *
3033
- * @param returnValues - Which attributes to return in the response
3034
- * @returns The builder instance for method chaining
3035
- */
3036
- returnValues(returnValues) {
3037
- this.options.returnValues = returnValues;
3038
- return this;
3039
- }
3040
- /**
3041
- * Generate the DynamoDB command parameters
3042
- */
3043
- toDynamoCommand() {
3044
- if (this.updates.length === 0) {
3045
- throw new Error("No update actions specified");
3046
- }
3047
- const expressionParams = {
3048
- expressionAttributeNames: {},
3049
- expressionAttributeValues: {},
3050
- valueCounter: { count: 0 }
3051
- };
3052
- let updateExpression = "";
3053
- const setUpdates = [];
3054
- const removeUpdates = [];
3055
- const addUpdates = [];
3056
- const deleteUpdates = [];
3057
- for (const update of this.updates) {
3058
- switch (update.type) {
3059
- case "SET":
3060
- setUpdates.push(update);
3061
- break;
3062
- case "REMOVE":
3063
- removeUpdates.push(update);
3064
- break;
3065
- case "ADD":
3066
- addUpdates.push(update);
3067
- break;
3068
- case "DELETE":
3069
- deleteUpdates.push(update);
3070
- break;
3071
- }
3072
- }
3073
- if (setUpdates.length > 0) {
3074
- updateExpression += "SET ";
3075
- updateExpression += setUpdates.map((update) => {
3076
- const attrName = generateAttributeName(expressionParams, update.path);
3077
- const valueName = generateValueName(expressionParams, update.value);
3078
- expressionParams.expressionAttributeValues[valueName] = update.value;
3079
- return `${attrName} = ${valueName}`;
3080
- }).join(", ");
3081
- }
3082
- if (removeUpdates.length > 0) {
3083
- if (updateExpression) {
3084
- updateExpression += " ";
3085
- }
3086
- updateExpression += "REMOVE ";
3087
- updateExpression += removeUpdates.map((update) => {
3088
- return generateAttributeName(expressionParams, update.path);
3089
- }).join(", ");
3090
- }
3091
- if (addUpdates.length > 0) {
3092
- if (updateExpression) {
3093
- updateExpression += " ";
3094
- }
3095
- updateExpression += "ADD ";
3096
- updateExpression += addUpdates.map((update) => {
3097
- const attrName = generateAttributeName(expressionParams, update.path);
3098
- const valueName = generateValueName(expressionParams, update.value);
3099
- return `${attrName} ${valueName}`;
3100
- }).join(", ");
3101
- }
3102
- if (deleteUpdates.length > 0) {
3103
- if (updateExpression) {
3104
- updateExpression += " ";
3105
- }
3106
- updateExpression += "DELETE ";
3107
- updateExpression += deleteUpdates.map((update) => {
3108
- const attrName = generateAttributeName(expressionParams, update.path);
3109
- const valueName = generateValueName(expressionParams, update.value);
3110
- return `${attrName} ${valueName}`;
3111
- }).join(", ");
3112
- }
3113
- let conditionExpression;
3114
- if (this.options.condition) {
3115
- conditionExpression = buildExpression(this.options.condition, expressionParams);
3116
- }
3117
- const { expressionAttributeNames, expressionAttributeValues } = expressionParams;
3118
- return {
3119
- tableName: this.tableName,
3120
- key: this.key,
3121
- updateExpression,
3122
- conditionExpression,
3123
- expressionAttributeNames: Object.keys(expressionAttributeNames).length > 0 ? expressionAttributeNames : void 0,
3124
- expressionAttributeValues: Object.keys(expressionAttributeValues).length > 0 ? expressionAttributeValues : void 0,
3125
- returnValues: this.options.returnValues
3126
- };
3127
- }
3128
- /**
3129
- * Adds this update operation to a transaction.
3130
- *
3131
- * @example
3132
- * ```typescript
3133
- * const transaction = new TransactionBuilder(executor);
3134
- *
3135
- * // Update dinosaur status and habitat occupancy atomically
3136
- * new UpdateBuilder(executor, 'dinosaurs', { id: 'TREX-001' })
3137
- * .set('location', 'PADDOCK_A')
3138
- * .set('status', 'CONTAINED')
3139
- * .withTransaction(transaction);
3140
- *
3141
- * new UpdateBuilder(executor, 'habitats', { id: 'PADDOCK-A' })
3142
- * .add('occupants', 1)
3143
- * .set('lastOccupied', new Date().toISOString())
3144
- * .withTransaction(transaction);
3145
- *
3146
- * // Execute all operations atomically
3147
- * await transaction.execute();
3148
- * ```
3149
- *
3150
- * @param transaction - The transaction builder to add this operation to
3151
- * @returns The builder instance for method chaining
3152
- */
3153
- withTransaction(transaction) {
3154
- const command = this.toDynamoCommand();
3155
- transaction.updateWithCommand(command);
3156
- }
3157
- /**
3158
- * Gets a human-readable representation of the update command.
3159
- *
3160
- * @example
3161
- * ```typescript
3162
- * // Create complex update
3163
- * const builder = new UpdateBuilder(executor, 'dinosaurs', { id: 'RAPTOR-001' })
3164
- * .set({
3165
- * status: 'HUNTING',
3166
- * 'stats.health': 95,
3167
- * 'behavior.lastObserved': new Date().toISOString()
3168
- * })
3169
- * .add('huntingSuccesses', 1)
3170
- * .condition(op => op.gt('health', 50));
3171
- *
3172
- * // Debug the update
3173
- * const debugInfo = builder.debug();
3174
- * console.log('Update operation:', debugInfo);
3175
- * ```
3176
- *
3177
- * @returns A readable representation of the update command with resolved expressions
3178
- */
3179
- debug() {
3180
- const command = this.toDynamoCommand();
3181
- return debugCommand(command);
3182
- }
3183
- /**
3184
- * Executes the update operation against DynamoDB.
3185
- *
3186
- * @example
3187
- * ```typescript
3188
- * try {
3189
- * // Update dinosaur status with conditions
3190
- * const result = await new UpdateBuilder(executor, 'dinosaurs', { id: 'TREX-001' })
3191
- * .set({
3192
- * status: 'FEEDING',
3193
- * lastMeal: new Date().toISOString(),
3194
- * 'stats.hunger': 0
3195
- * })
3196
- * .add('feedingCount', 1)
3197
- * .condition(op =>
3198
- * op.and([
3199
- * op.gt('stats.hunger', 80),
3200
- * op.eq('status', 'HUNTING')
3201
- * ])
3202
- * )
3203
- * .returnValues('ALL_NEW')
3204
- * .execute();
3205
- *
3206
- * if (result.item) {
3207
- * console.log('Updated dinosaur:', result.item);
3208
- * }
3209
- * } catch (error) {
3210
- * // Handle condition check failure
3211
- * console.error('Failed to update dinosaur:', error);
3212
- * // Check if dinosaur wasn't hungry enough
3213
- * if (error.name === 'ConditionalCheckFailedException') {
3214
- * console.log('Dinosaur not ready for feeding');
3215
- * }
3216
- * }
3217
- * ```
3218
- *
3219
- * @returns A promise that resolves to an DynamoItem containing the updated item (if returnValues is set)
3220
- * @throws {ConditionalCheckFailedException} If the condition check fails
3221
- * @throws {Error} If the update operation fails for other reasons
3222
- */
3223
- async execute() {
3224
- const params = this.toDynamoCommand();
3225
- return this.executor(params);
3226
- }
3227
- };
3228
-
3229
- // src/utils/chunk-array.ts
3230
- function* chunkArray(array, size) {
3231
- if (size <= 0) {
3232
- throw new Error("Chunk size must be greater than 0");
3233
- }
3234
- for (let i = 0; i < array.length; i += size) {
3235
- yield array.slice(i, i + size);
3236
- }
3237
- }
3238
-
3239
- // src/table.ts
3240
- var DDB_BATCH_WRITE_LIMIT = 25;
3241
- var DDB_BATCH_GET_LIMIT = 100;
3242
- var Table = class {
3243
- dynamoClient;
3244
- tableName;
3245
- /**
3246
- * The column name of the partitionKey for the Table
3247
- */
3248
- partitionKey;
3249
- /**
3250
- * The column name of the sortKey for the Table
3251
- */
3252
- sortKey;
3253
- /**
3254
- * The Global Secondary Indexes that are configured on this table
3255
- */
3256
- gsis;
3257
- constructor(config) {
3258
- this.dynamoClient = config.client;
3259
- this.tableName = config.tableName;
3260
- this.partitionKey = config.indexes.partitionKey;
3261
- this.sortKey = config.indexes.sortKey;
3262
- this.gsis = config.indexes.gsis || {};
3263
- }
3264
- createKeyForPrimaryIndex(keyCondition) {
3265
- const primaryCondition = { [this.partitionKey]: keyCondition.pk };
3266
- if (this.sortKey) {
3267
- if (!keyCondition.sk) {
3268
- throw new Error("Sort key has not been provided but the Table has a sort key");
3269
- }
3270
- primaryCondition[this.sortKey] = keyCondition.sk;
3271
- }
3272
- return primaryCondition;
3273
- }
3274
- /**
3275
- * Creates a new item in the table, it will fail if the item already exists.
3276
- *
3277
- * By default, this method returns the input values passed to the create operation
3278
- * upon successful creation.
3279
- *
3280
- * You can customise the return behaviour by chaining the `.returnValues()` method:
3281
- *
3282
- * @param item The item to create
3283
- * @returns A PutBuilder instance for chaining additional conditions and executing the create operation
3284
- *
3285
- * @example
3286
- * ```ts
3287
- * // Create with default behavior (returns input values)
3288
- * const result = await table.create({
3289
- * id: 'user-123',
3290
- * name: 'John Doe',
3291
- * email: 'john@example.com'
3292
- * }).execute();
3293
- * console.log(result); // Returns the input object
3294
- *
3295
- * // Create with no return value for better performance
3296
- * await table.create(userData).returnValues('NONE').execute();
3297
- *
3298
- * // Create and get fresh data from dynamodb using a strongly consistent read
3299
- * const freshData = await table.create(userData).returnValues('CONSISTENT').execute();
3300
- *
3301
- * // Create and get previous values (if the item was overwritten)
3302
- * const oldData = await table.create(userData).returnValues('ALL_OLD').execute();
3303
- * ```
3304
- */
3305
- create(item) {
3306
- return this.put(item).condition((op) => op.attributeNotExists(this.partitionKey)).returnValues("INPUT");
3307
- }
3308
- get(keyCondition) {
3309
- const executor = async (params) => {
3310
- try {
3311
- const result = await this.dynamoClient.get({
3312
- TableName: params.tableName,
3313
- Key: this.createKeyForPrimaryIndex(keyCondition),
3314
- ProjectionExpression: params.projectionExpression,
3315
- ExpressionAttributeNames: params.expressionAttributeNames,
3316
- ConsistentRead: params.consistentRead
3317
- });
3318
- return {
3319
- item: result.Item ? result.Item : void 0
3320
- };
3321
- } catch (error) {
3322
- console.error("Error getting item:", error);
3323
- throw error;
3324
- }
3325
- };
3326
- return new GetBuilder(executor, keyCondition, this.tableName);
3327
- }
3328
- /**
3329
- * Updates an item in the table
3330
- *
3331
- * @param item The item to update
3332
- * @returns A PutBuilder instance for chaining conditions and executing the put operation
3333
- */
3334
- put(item) {
3335
- const executor = async (params) => {
3336
- try {
3337
- const result = await this.dynamoClient.put({
3338
- TableName: params.tableName,
3339
- Item: params.item,
3340
- ConditionExpression: params.conditionExpression,
3341
- ExpressionAttributeNames: params.expressionAttributeNames,
3342
- ExpressionAttributeValues: params.expressionAttributeValues,
3343
- // CONSISTENT and INPUT are not valid ReturnValues for DDB, so we set NONE as we are not interested in its
3344
- // response and will be handling these cases separately
3345
- ReturnValues: params.returnValues === "CONSISTENT" || params.returnValues === "INPUT" ? "NONE" : params.returnValues
3346
- });
3347
- if (params.returnValues === "INPUT") {
3348
- return params.item;
3349
- }
3350
- if (params.returnValues === "CONSISTENT") {
3351
- const getResult = await this.dynamoClient.get({
3352
- TableName: params.tableName,
3353
- Key: this.createKeyForPrimaryIndex({
3354
- pk: params.item[this.partitionKey],
3355
- ...this.sortKey && { sk: params.item[this.sortKey] }
3356
- }),
3357
- ConsistentRead: true
3358
- });
3359
- return getResult.Item;
3360
- }
3361
- return result.Attributes;
3362
- } catch (error) {
3363
- console.error("Error creating item:", error);
3364
- throw error;
3365
- }
3366
- };
3367
- return new PutBuilder(executor, item, this.tableName);
3368
- }
3369
- /**
3370
- * Creates a query builder for complex queries
3371
- * If useIndex is called on the returned QueryBuilder, it will use the GSI configuration
3372
- */
3373
- query(keyCondition) {
3374
- const pkAttributeName = this.partitionKey;
3375
- const skAttributeName = this.sortKey;
3376
- let keyConditionExpression = eq(pkAttributeName, keyCondition.pk);
3377
- if (keyCondition.sk) {
3378
- if (!skAttributeName) {
3379
- throw new Error("Sort key is not defined for Index");
3380
- }
3381
- const keyConditionOperator = {
3382
- eq: (value) => eq(skAttributeName, value),
3383
- lt: (value) => lt(skAttributeName, value),
3384
- lte: (value) => lte(skAttributeName, value),
3385
- gt: (value) => gt(skAttributeName, value),
3386
- gte: (value) => gte(skAttributeName, value),
3387
- between: (lower, upper) => between(skAttributeName, lower, upper),
3388
- beginsWith: (value) => beginsWith(skAttributeName, value),
3389
- and: (...conditions) => and(...conditions)
3390
- };
3391
- const skCondition = keyCondition.sk(keyConditionOperator);
3392
- keyConditionExpression = and(eq(pkAttributeName, keyCondition.pk), skCondition);
3393
- }
3394
- const executor = async (originalKeyCondition, options) => {
3395
- let finalKeyCondition = originalKeyCondition;
3396
- if (options.indexName) {
3397
- const gsiName = String(options.indexName);
3398
- const gsi = this.gsis[gsiName];
3399
- if (!gsi) {
3400
- throw new Error(`GSI with name "${gsiName}" does not exist on table "${this.tableName}"`);
3401
- }
3402
- const gsiPkAttributeName = gsi.partitionKey;
3403
- const gsiSkAttributeName = gsi.sortKey;
3404
- let pkValue;
3405
- let skValue;
3406
- let extractedSkCondition;
3407
- if (originalKeyCondition.type === "eq") {
3408
- pkValue = originalKeyCondition.value;
3409
- } else if (originalKeyCondition.type === "and" && originalKeyCondition.conditions) {
3410
- const pkCondition = originalKeyCondition.conditions.find(
3411
- (c) => c.type === "eq" && c.attr === pkAttributeName
3412
- );
3413
- if (pkCondition && pkCondition.type === "eq") {
3414
- pkValue = pkCondition.value;
3415
- }
3416
- const skConditions = originalKeyCondition.conditions.filter((c) => c.attr === skAttributeName);
3417
- if (skConditions.length > 0) {
3418
- if (skConditions.length === 1) {
3419
- extractedSkCondition = skConditions[0];
3420
- if (extractedSkCondition && extractedSkCondition.type === "eq") {
3421
- skValue = extractedSkCondition.value;
3422
- }
3423
- } else if (skConditions.length > 1) {
3424
- extractedSkCondition = and(...skConditions);
3425
- }
3426
- }
3427
- }
3428
- if (!pkValue) {
3429
- throw new Error("Could not extract partition key value from key condition");
3430
- }
3431
- let gsiKeyCondition = eq(gsiPkAttributeName, pkValue);
3432
- if (skValue && gsiSkAttributeName) {
3433
- gsiKeyCondition = and(gsiKeyCondition, eq(gsiSkAttributeName, skValue));
3434
- } else if (extractedSkCondition && gsiSkAttributeName) {
3435
- if (extractedSkCondition.attr === skAttributeName) {
3436
- const updatedSkCondition = {
3437
- ...extractedSkCondition,
3438
- attr: gsiSkAttributeName
3439
- };
3440
- gsiKeyCondition = and(gsiKeyCondition, updatedSkCondition);
3441
- } else {
3442
- gsiKeyCondition = and(gsiKeyCondition, extractedSkCondition);
3443
- }
3444
- }
3445
- finalKeyCondition = gsiKeyCondition;
3446
- }
3447
- const expressionParams = {
3448
- expressionAttributeNames: {},
3449
- expressionAttributeValues: {},
3450
- valueCounter: { count: 0 }
3451
- };
3452
- const keyConditionExpression2 = buildExpression(finalKeyCondition, expressionParams);
3453
- let filterExpression;
3454
- if (options.filter) {
3455
- filterExpression = buildExpression(options.filter, expressionParams);
3456
- }
3457
- const projectionExpression = options.projection?.map((p) => generateAttributeName(expressionParams, p)).join(", ");
3458
- const { expressionAttributeNames, expressionAttributeValues } = expressionParams;
3459
- const { indexName, limit, consistentRead, scanIndexForward, lastEvaluatedKey } = options;
3460
- const params = {
3461
- TableName: this.tableName,
3462
- KeyConditionExpression: keyConditionExpression2,
3463
- FilterExpression: filterExpression,
3464
- ExpressionAttributeNames: expressionAttributeNames,
3465
- ExpressionAttributeValues: expressionAttributeValues,
3466
- IndexName: indexName,
3467
- Limit: limit,
3468
- ConsistentRead: consistentRead,
3469
- ScanIndexForward: scanIndexForward,
3470
- ProjectionExpression: projectionExpression,
3471
- ExclusiveStartKey: lastEvaluatedKey
3472
- };
3473
- try {
3474
- const result = await this.dynamoClient.query(params);
3475
- return {
3476
- items: result.Items,
3477
- lastEvaluatedKey: result.LastEvaluatedKey
3478
- };
3479
- } catch (error) {
3480
- console.log(debugCommand(params));
3481
- console.error("Error querying items:", error);
3482
- throw error;
3483
- }
3484
- };
3485
- return new QueryBuilder(executor, keyConditionExpression);
3486
- }
3487
- /**
3488
- * Creates a scan builder for scanning the entire table
3489
- * Use this when you need to:
3490
- * - Process all items in a table
3491
- * - Apply filters to a large dataset
3492
- * - Use a GSI for scanning
3493
- *
3494
- * @returns A ScanBuilder instance for chaining operations
3495
- */
3496
- scan() {
3497
- const executor = async (options) => {
3498
- const expressionParams = {
3499
- expressionAttributeNames: {},
3500
- expressionAttributeValues: {},
3501
- valueCounter: { count: 0 }
3502
- };
3503
- let filterExpression;
3504
- if (options.filter) {
3505
- filterExpression = buildExpression(options.filter, expressionParams);
3506
- }
3507
- const projectionExpression = options.projection?.map((p) => generateAttributeName(expressionParams, p)).join(", ");
3508
- const { expressionAttributeNames, expressionAttributeValues } = expressionParams;
3509
- const { indexName, limit, consistentRead, lastEvaluatedKey } = options;
3510
- const params = {
3511
- TableName: this.tableName,
3512
- FilterExpression: filterExpression,
3513
- ExpressionAttributeNames: Object.keys(expressionAttributeNames).length > 0 ? expressionAttributeNames : void 0,
3514
- ExpressionAttributeValues: Object.keys(expressionAttributeValues).length > 0 ? expressionAttributeValues : void 0,
3515
- IndexName: indexName,
3516
- Limit: limit,
3517
- ConsistentRead: consistentRead,
3518
- ProjectionExpression: projectionExpression,
3519
- ExclusiveStartKey: lastEvaluatedKey
3520
- };
3521
- try {
3522
- const result = await this.dynamoClient.scan(params);
3523
- return {
3524
- items: result.Items,
3525
- lastEvaluatedKey: result.LastEvaluatedKey
3526
- };
3527
- } catch (error) {
3528
- console.log(debugCommand(params));
3529
- console.error("Error scanning items:", error);
3530
- throw error;
3531
- }
3532
- };
3533
- return new ScanBuilder(executor);
3534
- }
3535
- delete(keyCondition) {
3536
- const executor = async (params) => {
3537
- try {
3538
- const result = await this.dynamoClient.delete({
3539
- TableName: params.tableName,
3540
- Key: this.createKeyForPrimaryIndex(keyCondition),
3541
- ConditionExpression: params.conditionExpression,
3542
- ExpressionAttributeNames: params.expressionAttributeNames,
3543
- ExpressionAttributeValues: params.expressionAttributeValues,
3544
- ReturnValues: params.returnValues
3545
- });
3546
- return {
3547
- item: result.Attributes
3548
- };
3549
- } catch (error) {
3550
- console.error("Error deleting item:", error);
3551
- throw error;
3552
- }
3553
- };
3554
- return new DeleteBuilder(executor, this.tableName, keyCondition);
3555
- }
3556
- /**
3557
- * Updates an item in the table
3558
- *
3559
- * @param keyCondition The primary key of the item to update
3560
- * @returns An UpdateBuilder instance for chaining update operations and conditions
3561
- */
3562
- update(keyCondition) {
3563
- const executor = async (params) => {
3564
- try {
3565
- const result = await this.dynamoClient.update({
3566
- TableName: params.tableName,
3567
- Key: this.createKeyForPrimaryIndex(keyCondition),
3568
- UpdateExpression: params.updateExpression,
3569
- ConditionExpression: params.conditionExpression,
3570
- ExpressionAttributeNames: params.expressionAttributeNames,
3571
- ExpressionAttributeValues: params.expressionAttributeValues,
3572
- ReturnValues: params.returnValues
3573
- });
3574
- return {
3575
- item: result.Attributes
3576
- };
3577
- } catch (error) {
3578
- console.error("Error updating item:", error);
3579
- throw error;
3580
- }
3581
- };
3582
- return new UpdateBuilder(executor, this.tableName, keyCondition);
3583
- }
3584
- /**
3585
- * Creates a transaction builder for performing multiple operations atomically
3586
- */
3587
- transactionBuilder() {
3588
- const executor = async (params) => {
3589
- await this.dynamoClient.transactWrite(params);
3590
- };
3591
- return new TransactionBuilder(executor, {
3592
- partitionKey: this.partitionKey,
3593
- sortKey: this.sortKey
3594
- });
3595
- }
3596
- /**
3597
- * Creates a batch builder for performing multiple operations efficiently with optional type inference
3598
- *
3599
- * @example Basic Usage
3600
- * ```typescript
3601
- * const batch = table.batchBuilder();
3602
- *
3603
- * // Add operations
3604
- * userRepo.create(newUser).withBatch(batch);
3605
- * orderRepo.get({ id: 'order-1' }).withBatch(batch);
3606
- *
3607
- * // Execute operations
3608
- * const result = await batch.execute();
3609
- * ```
3610
- *
3611
- * @example Typed Usage
3612
- * ```typescript
3613
- * // Define entity types for the batch
3614
- * const batch = table.batchBuilder<{
3615
- * User: UserEntity;
3616
- * Order: OrderEntity;
3617
- * Product: ProductEntity;
3618
- * }>();
3619
- *
3620
- * // Add operations with type information
3621
- * userRepo.create(newUser).withBatch(batch, 'User');
3622
- * orderRepo.get({ id: 'order-1' }).withBatch(batch, 'Order');
3623
- * productRepo.delete({ id: 'old-product' }).withBatch(batch, 'Product');
3624
- *
3625
- * // Execute and get typed results
3626
- * const result = await batch.execute();
3627
- * const users: UserEntity[] = result.reads.itemsByType.User;
3628
- * const orders: OrderEntity[] = result.reads.itemsByType.Order;
3629
- * ```
3630
- */
3631
- batchBuilder() {
3632
- const batchWriteExecutor = async (operations) => {
3633
- return this.batchWrite(operations);
3634
- };
3635
- const batchGetExecutor = async (keys) => {
3636
- return this.batchGet(keys);
3637
- };
3638
- return new BatchBuilder(batchWriteExecutor, batchGetExecutor, {
3639
- partitionKey: this.partitionKey,
3640
- sortKey: this.sortKey
3641
- });
3642
- }
3643
- /**
3644
- * Executes a transaction using a callback function
3645
- *
3646
- * @param callback A function that receives a transaction context and performs operations on it
3647
- * @param options Optional transaction options
3648
- * @returns A promise that resolves when the transaction is complete
3649
- */
3650
- async transaction(callback, options) {
3651
- const transactionExecutor = async (params) => {
3652
- await this.dynamoClient.transactWrite(params);
3653
- };
3654
- const transaction = new TransactionBuilder(transactionExecutor, {
3655
- partitionKey: this.partitionKey,
3656
- sortKey: this.sortKey
3657
- });
3658
- if (options) {
3659
- transaction.withOptions(options);
3660
- }
3661
- const result = await callback(transaction);
3662
- await transaction.execute();
3663
- return result;
3664
- }
3665
- /**
3666
- * Creates a condition check operation for use in transactions
3667
- *
3668
- * This is useful for when you require a transaction to succeed only when a specific condition is met on a
3669
- * a record within the database that you are not directly updating.
3670
- *
3671
- * For example, you are updating a record and you want to ensure that another record exists and/or has a specific value before proceeding.
3672
- */
3673
- conditionCheck(keyCondition) {
3674
- return new ConditionCheckBuilder(this.tableName, keyCondition);
3675
- }
3676
- /**
3677
- * Performs a batch get operation to retrieve multiple items at once
3678
- *
3679
- * @param keys Array of primary keys to retrieve
3680
- * @returns A promise that resolves to the retrieved items
3681
- */
3682
- async batchGet(keys) {
3683
- const allItems = [];
3684
- const allUnprocessedKeys = [];
3685
- for (const chunk of chunkArray(keys, DDB_BATCH_GET_LIMIT)) {
3686
- const formattedKeys = chunk.map((key) => ({
3687
- [this.partitionKey]: key.pk,
3688
- ...this.sortKey ? { [this.sortKey]: key.sk } : {}
3689
- }));
3690
- const params = {
3691
- RequestItems: {
3692
- [this.tableName]: {
3693
- Keys: formattedKeys
3694
- }
3695
- }
3696
- };
3697
- try {
3698
- const result = await this.dynamoClient.batchGet(params);
3699
- if (result.Responses?.[this.tableName]) {
3700
- allItems.push(...result.Responses[this.tableName]);
3701
- }
3702
- const unprocessedKeysArray = result.UnprocessedKeys?.[this.tableName]?.Keys || [];
3703
- const unprocessedKeys = unprocessedKeysArray.map((key) => ({
3704
- pk: key[this.partitionKey],
3705
- sk: this.sortKey ? key[this.sortKey] : void 0
3706
- }));
3707
- if (unprocessedKeys.length > 0) {
3708
- allUnprocessedKeys.push(...unprocessedKeys);
3709
- }
3710
- } catch (error) {
3711
- console.error("Error in batch get operation:", error);
3712
- throw error;
3713
- }
3714
- }
3715
- return {
3716
- items: allItems,
3717
- unprocessedKeys: allUnprocessedKeys
3718
- };
3719
- }
3720
- /**
3721
- * Performs a batch write operation to put or delete multiple items at once
3722
- *
3723
- * @param operations Array of put or delete operations
3724
- * @returns A promise that resolves to any unprocessed operations
3725
- */
3726
- async batchWrite(operations) {
3727
- const allUnprocessedItems = [];
3728
- for (const chunk of chunkArray(operations, DDB_BATCH_WRITE_LIMIT)) {
3729
- const writeRequests = chunk.map((operation) => {
3730
- if (operation.type === "put") {
3731
- return {
3732
- PutRequest: {
3733
- Item: operation.item
3734
- }
3735
- };
3736
- }
3737
- return {
3738
- DeleteRequest: {
3739
- Key: this.createKeyForPrimaryIndex(operation.key)
3740
- }
3741
- };
3742
- });
3743
- const params = {
3744
- RequestItems: {
3745
- [this.tableName]: writeRequests
3746
- }
3747
- };
3748
- try {
3749
- const result = await this.dynamoClient.batchWrite(params);
3750
- const unprocessedRequestsArray = result.UnprocessedItems?.[this.tableName] || [];
3751
- if (unprocessedRequestsArray.length > 0) {
3752
- const unprocessedItems = unprocessedRequestsArray.map((request) => {
3753
- if (request?.PutRequest?.Item) {
3754
- return {
3755
- type: "put",
3756
- item: request.PutRequest.Item
3757
- };
3758
- }
3759
- if (request?.DeleteRequest?.Key) {
3760
- return {
3761
- type: "delete",
3762
- key: {
3763
- pk: request.DeleteRequest.Key[this.partitionKey],
3764
- sk: this.sortKey ? request.DeleteRequest.Key[this.sortKey] : void 0
3765
- }
3766
- };
3767
- }
3768
- throw new Error("Invalid unprocessed item format returned from DynamoDB");
3769
- });
3770
- allUnprocessedItems.push(...unprocessedItems);
3771
- }
3772
- } catch (error) {
3773
- console.error("Error in batch write operation:", error);
3774
- throw error;
3775
- }
3776
- }
3777
- return {
3778
- unprocessedItems: allUnprocessedItems
3779
- };
3780
- }
3781
- };
3782
-
3783
- export { Table };
3784
- //# sourceMappingURL=table.js.map
3785
- //# sourceMappingURL=table.js.map
1
+ export { Table } from './chunk-EODPMYPE.js';
2
+ import './chunk-DTFJJASK.js';
3
+ import './chunk-2WIBY7PZ.js';