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
@@ -0,0 +1,622 @@
1
+ 'use strict';
2
+
3
+ var chunk7UJJ7JXM_cjs = require('./chunk-7UJJ7JXM.cjs');
4
+
5
+ // src/builders/entity-aware-builders.ts
6
+ function createEntityAwareBuilder(builder, entityName) {
7
+ return new Proxy(builder, {
8
+ get(target, prop, receiver) {
9
+ if (prop === "entityName") {
10
+ return entityName;
11
+ }
12
+ if (prop === "withBatch" && typeof target[prop] === "function") {
13
+ return (batch, entityType) => {
14
+ const typeToUse = entityType ?? entityName;
15
+ const fn = target[prop];
16
+ return fn.call(target, batch, typeToUse);
17
+ };
18
+ }
19
+ return Reflect.get(target, prop, receiver);
20
+ }
21
+ });
22
+ }
23
+ function createEntityAwarePutBuilder(builder, entityName) {
24
+ return createEntityAwareBuilder(builder, entityName);
25
+ }
26
+ function createEntityAwareGetBuilder(builder, entityName) {
27
+ return createEntityAwareBuilder(builder, entityName);
28
+ }
29
+ function createEntityAwareDeleteBuilder(builder, entityName) {
30
+ return createEntityAwareBuilder(builder, entityName);
31
+ }
32
+ var EntityAwareUpdateBuilder = class {
33
+ forceRebuildIndexes = [];
34
+ entityName;
35
+ builder;
36
+ entityConfig;
37
+ updateDataApplied = false;
38
+ constructor(builder, entityName) {
39
+ this.builder = builder;
40
+ this.entityName = entityName;
41
+ }
42
+ /**
43
+ * Configure entity-specific logic for automatic timestamp generation and index updates
44
+ */
45
+ configureEntityLogic(config) {
46
+ this.entityConfig = config;
47
+ }
48
+ /**
49
+ * Forces a rebuild of one or more readonly indexes during the update operation.
50
+ *
51
+ * By default, readonly indexes are not updated during entity updates to prevent
52
+ * errors when required index attributes are missing. This method allows you to
53
+ * override that behavior and force specific indexes to be rebuilt.
54
+ *
55
+ * @example
56
+ * ```typescript
57
+ * // Force rebuild a single readonly index
58
+ * const result = await repo.update({ id: 'TREX-001' }, { status: 'ACTIVE' })
59
+ * .forceIndexRebuild('gsi1')
60
+ * .execute();
61
+ *
62
+ * // Force rebuild multiple readonly indexes
63
+ * const result = await repo.update({ id: 'TREX-001' }, { status: 'ACTIVE' })
64
+ * .forceIndexRebuild(['gsi1', 'gsi2'])
65
+ * .execute();
66
+ *
67
+ * // Chain with other update operations
68
+ * const result = await repo.update({ id: 'TREX-001' }, { status: 'ACTIVE' })
69
+ * .set('lastUpdated', new Date().toISOString())
70
+ * .forceIndexRebuild('gsi1')
71
+ * .condition(op => op.eq('status', 'INACTIVE'))
72
+ * .execute();
73
+ * ```
74
+ *
75
+ * @param indexes - A single index name or array of index names to force rebuild
76
+ * @returns The builder instance for method chaining
77
+ */
78
+ forceIndexRebuild(indexes) {
79
+ if (Array.isArray(indexes)) {
80
+ this.forceRebuildIndexes = [...this.forceRebuildIndexes, ...indexes];
81
+ } else {
82
+ this.forceRebuildIndexes.push(indexes);
83
+ }
84
+ return this;
85
+ }
86
+ /**
87
+ * Gets the list of indexes that should be force rebuilt.
88
+ * This is used internally by entity update logic.
89
+ *
90
+ * @returns Array of index names to force rebuild
91
+ */
92
+ getForceRebuildIndexes() {
93
+ return [...this.forceRebuildIndexes];
94
+ }
95
+ /**
96
+ * Apply entity-specific update data (timestamps and index updates)
97
+ * This is called automatically when needed
98
+ */
99
+ applyEntityUpdates() {
100
+ if (!this.entityConfig || this.updateDataApplied) return;
101
+ const timestamps = this.entityConfig.generateTimestamps();
102
+ const updatedItem = { ...this.entityConfig.key, ...this.entityConfig.data, ...timestamps };
103
+ const indexUpdates = this.entityConfig.buildIndexUpdates(
104
+ this.entityConfig.key,
105
+ updatedItem,
106
+ this.entityConfig.table,
107
+ this.entityConfig.indexes,
108
+ this.forceRebuildIndexes
109
+ );
110
+ this.builder.set({ ...this.entityConfig.data, ...timestamps, ...indexUpdates });
111
+ this.updateDataApplied = true;
112
+ }
113
+ set(valuesOrPath, value) {
114
+ if (typeof valuesOrPath === "object") {
115
+ this.builder.set(valuesOrPath);
116
+ } else {
117
+ if (value === void 0) {
118
+ throw new Error("Value is required when setting a single path");
119
+ }
120
+ this.builder.set(valuesOrPath, value);
121
+ }
122
+ return this;
123
+ }
124
+ remove(path) {
125
+ this.builder.remove(path);
126
+ return this;
127
+ }
128
+ add(path, value) {
129
+ this.builder.add(path, value);
130
+ return this;
131
+ }
132
+ deleteElementsFromSet(path, value) {
133
+ this.builder.deleteElementsFromSet(path, value);
134
+ return this;
135
+ }
136
+ condition(condition) {
137
+ this.builder.condition(condition);
138
+ return this;
139
+ }
140
+ returnValues(returnValues) {
141
+ this.builder.returnValues(returnValues);
142
+ return this;
143
+ }
144
+ toDynamoCommand() {
145
+ return this.builder.toDynamoCommand();
146
+ }
147
+ withTransaction(transaction) {
148
+ this.applyEntityUpdates();
149
+ this.builder.withTransaction(transaction);
150
+ }
151
+ debug() {
152
+ return this.builder.debug();
153
+ }
154
+ async execute() {
155
+ this.updateDataApplied = false;
156
+ this.applyEntityUpdates();
157
+ return this.builder.execute();
158
+ }
159
+ };
160
+ function createEntityAwareUpdateBuilder(builder, entityName) {
161
+ return new EntityAwareUpdateBuilder(builder, entityName);
162
+ }
163
+
164
+ // src/entity/ddb-indexing.ts
165
+ var IndexBuilder = class {
166
+ /**
167
+ * Creates a new IndexBuilder instance
168
+ *
169
+ * @param table - The DynamoDB table instance
170
+ * @param indexes - The index definitions
171
+ */
172
+ constructor(table, indexes = {}) {
173
+ this.table = table;
174
+ this.indexes = indexes;
175
+ }
176
+ /**
177
+ * Build index attributes for item creation
178
+ *
179
+ * @param item - The item to generate indexes for
180
+ * @param options - Options for building indexes
181
+ * @returns Record of GSI attribute names to their values
182
+ */
183
+ buildForCreate(item, options = {}) {
184
+ const attributes = {};
185
+ for (const [indexName, indexDef] of Object.entries(this.indexes)) {
186
+ if (options.excludeReadOnly && indexDef.isReadOnly) {
187
+ continue;
188
+ }
189
+ const key = indexDef.generateKey(item);
190
+ const gsiConfig = this.table.gsis[indexName];
191
+ if (!gsiConfig) {
192
+ throw new Error(`GSI configuration not found for index: ${indexName}`);
193
+ }
194
+ if (key.pk) {
195
+ attributes[gsiConfig.partitionKey] = key.pk;
196
+ }
197
+ if (key.sk && gsiConfig.sortKey) {
198
+ attributes[gsiConfig.sortKey] = key.sk;
199
+ }
200
+ }
201
+ return attributes;
202
+ }
203
+ /**
204
+ * Build index attributes for item updates
205
+ *
206
+ * @param currentData - The current data before update
207
+ * @param updates - The update data
208
+ * @param options - Options for building indexes
209
+ * @returns Record of GSI attribute names to their updated values
210
+ */
211
+ buildForUpdate(currentData, updates, options = {}) {
212
+ const attributes = {};
213
+ const updatedItem = { ...currentData, ...updates };
214
+ if (options.forceRebuildIndexes && options.forceRebuildIndexes.length > 0) {
215
+ const invalidIndexes = options.forceRebuildIndexes.filter((indexName) => !this.indexes[indexName]);
216
+ if (invalidIndexes.length > 0) {
217
+ throw new Error(
218
+ `Cannot force rebuild unknown indexes: ${invalidIndexes.join(", ")}. Available indexes: ${Object.keys(this.indexes).join(", ")}`
219
+ );
220
+ }
221
+ }
222
+ for (const [indexName, indexDef] of Object.entries(this.indexes)) {
223
+ const isForced = options.forceRebuildIndexes?.includes(indexName);
224
+ if (indexDef.isReadOnly && !isForced) {
225
+ continue;
226
+ }
227
+ if (!isForced) {
228
+ let shouldUpdateIndex = false;
229
+ try {
230
+ const currentKey = indexDef.generateKey(currentData);
231
+ const updatedKey = indexDef.generateKey(updatedItem);
232
+ if (currentKey.pk !== updatedKey.pk || currentKey.sk !== updatedKey.sk) {
233
+ shouldUpdateIndex = true;
234
+ }
235
+ } catch {
236
+ shouldUpdateIndex = true;
237
+ }
238
+ if (!shouldUpdateIndex) {
239
+ continue;
240
+ }
241
+ }
242
+ let key;
243
+ try {
244
+ key = indexDef.generateKey(updatedItem);
245
+ } catch (error) {
246
+ if (error instanceof Error) {
247
+ throw new Error(`Missing attributes: ${error.message}`);
248
+ }
249
+ throw error;
250
+ }
251
+ if (this.hasUndefinedValues(key)) {
252
+ throw new Error(
253
+ `Missing attributes: Cannot update entity: insufficient data to regenerate index "${indexName}". All attributes required by the index must be provided in the update operation, or the index must be marked as readOnly.`
254
+ );
255
+ }
256
+ const gsiConfig = this.table.gsis[indexName];
257
+ if (!gsiConfig) {
258
+ throw new Error(`GSI configuration not found for index: ${indexName}`);
259
+ }
260
+ if (key.pk) {
261
+ attributes[gsiConfig.partitionKey] = key.pk;
262
+ }
263
+ if (key.sk && gsiConfig.sortKey) {
264
+ attributes[gsiConfig.sortKey] = key.sk;
265
+ }
266
+ }
267
+ return attributes;
268
+ }
269
+ /**
270
+ * Check if a key has undefined values
271
+ *
272
+ * @param key - The index key to check
273
+ * @returns True if the key contains undefined values, false otherwise
274
+ */
275
+ hasUndefinedValues(key) {
276
+ return (key.pk?.includes("undefined") ?? false) || (key.sk?.includes("undefined") ?? false);
277
+ }
278
+ };
279
+
280
+ // src/entity/index-utils.ts
281
+ function buildIndexes(dataForKeyGeneration, table, indexes, excludeReadOnly = false) {
282
+ if (!indexes) {
283
+ return {};
284
+ }
285
+ const indexBuilder = new IndexBuilder(table, indexes);
286
+ return indexBuilder.buildForCreate(dataForKeyGeneration, { excludeReadOnly });
287
+ }
288
+ function buildIndexUpdates(currentData, updates, table, indexes, forceRebuildIndexes) {
289
+ if (!indexes) {
290
+ return {};
291
+ }
292
+ const indexBuilder = new IndexBuilder(table, indexes);
293
+ return indexBuilder.buildForUpdate(currentData, updates, { forceRebuildIndexes });
294
+ }
295
+
296
+ // src/entity/entity.ts
297
+ function defineEntity(config) {
298
+ const entityTypeAttributeName = config.settings?.entityTypeAttributeName ?? "entityType";
299
+ const buildIndexes2 = (dataForKeyGeneration, table, excludeReadOnly = false) => {
300
+ return buildIndexes(dataForKeyGeneration, table, config.indexes, excludeReadOnly);
301
+ };
302
+ const wrapMethodWithPreparation = (originalMethod, prepareFn, context) => {
303
+ const wrappedMethod = (...args) => {
304
+ prepareFn();
305
+ return originalMethod.call(context, ...args);
306
+ };
307
+ Object.setPrototypeOf(wrappedMethod, originalMethod);
308
+ const propertyNames = Object.getOwnPropertyNames(originalMethod);
309
+ for (let i = 0; i < propertyNames.length; i++) {
310
+ const prop = propertyNames[i];
311
+ if (prop !== "length" && prop !== "name" && prop !== "prototype") {
312
+ const descriptor = Object.getOwnPropertyDescriptor(originalMethod, prop);
313
+ if (descriptor && descriptor.writable !== false && !descriptor.get) {
314
+ wrappedMethod[prop] = originalMethod[prop];
315
+ }
316
+ }
317
+ }
318
+ return wrappedMethod;
319
+ };
320
+ const generateTimestamps = (timestampsToGenerate, data) => {
321
+ if (!config.settings?.timestamps) return {};
322
+ const timestamps = {};
323
+ const now = /* @__PURE__ */ new Date();
324
+ const unixTime = Math.floor(Date.now() / 1e3);
325
+ const { createdAt, updatedAt } = config.settings.timestamps;
326
+ if (createdAt && timestampsToGenerate.includes("createdAt") && !data.createdAt) {
327
+ const name = createdAt.attributeName ?? "createdAt";
328
+ timestamps[name] = createdAt.format === "UNIX" ? unixTime : now.toISOString();
329
+ }
330
+ if (updatedAt && timestampsToGenerate.includes("updatedAt") && !data.updatedAt) {
331
+ const name = updatedAt.attributeName ?? "updatedAt";
332
+ timestamps[name] = updatedAt.format === "UNIX" ? unixTime : now.toISOString();
333
+ }
334
+ return timestamps;
335
+ };
336
+ return {
337
+ name: config.name,
338
+ createRepository: (table) => {
339
+ const repository = {
340
+ create: (data) => {
341
+ const builder = table.create({});
342
+ const prepareValidatedItemAsync = async () => {
343
+ const validatedData = await config.schema["~standard"].validate(data);
344
+ if ("issues" in validatedData && validatedData.issues) {
345
+ throw new Error(`Validation failed: ${validatedData.issues.map((i) => i.message).join(", ")}`);
346
+ }
347
+ const dataForKeyGeneration = {
348
+ ...validatedData.value,
349
+ ...generateTimestamps(["createdAt", "updatedAt"], validatedData.value)
350
+ };
351
+ const primaryKey = config.primaryKey.generateKey(dataForKeyGeneration);
352
+ const indexes = buildIndexes(dataForKeyGeneration, table, config.indexes, false);
353
+ const validatedItem = {
354
+ ...dataForKeyGeneration,
355
+ [entityTypeAttributeName]: config.name,
356
+ [table.partitionKey]: primaryKey.pk,
357
+ ...table.sortKey ? { [table.sortKey]: primaryKey.sk } : {},
358
+ ...indexes
359
+ };
360
+ Object.assign(builder, { item: validatedItem });
361
+ return validatedItem;
362
+ };
363
+ const prepareValidatedItemSync = () => {
364
+ const validationResult = config.schema["~standard"].validate(data);
365
+ if (validationResult instanceof Promise) {
366
+ throw new Error(
367
+ "Async validation is not supported in withBatch or withTransaction. The schema must support synchronous validation for compatibility."
368
+ );
369
+ }
370
+ if ("issues" in validationResult && validationResult.issues) {
371
+ throw new Error(`Validation failed: ${validationResult.issues.map((i) => i.message).join(", ")}`);
372
+ }
373
+ const dataForKeyGeneration = {
374
+ ...validationResult.value,
375
+ ...generateTimestamps(["createdAt", "updatedAt"], validationResult.value)
376
+ };
377
+ const primaryKey = config.primaryKey.generateKey(dataForKeyGeneration);
378
+ const indexes = buildIndexes(dataForKeyGeneration, table, config.indexes, false);
379
+ const validatedItem = {
380
+ ...dataForKeyGeneration,
381
+ [entityTypeAttributeName]: config.name,
382
+ [table.partitionKey]: primaryKey.pk,
383
+ ...table.sortKey ? { [table.sortKey]: primaryKey.sk } : {},
384
+ ...indexes
385
+ };
386
+ Object.assign(builder, { item: validatedItem });
387
+ return validatedItem;
388
+ };
389
+ const originalExecute = builder.execute;
390
+ builder.execute = async () => {
391
+ await prepareValidatedItemAsync();
392
+ return await originalExecute.call(builder);
393
+ };
394
+ const originalWithTransaction = builder.withTransaction;
395
+ if (originalWithTransaction) {
396
+ builder.withTransaction = wrapMethodWithPreparation(
397
+ originalWithTransaction,
398
+ prepareValidatedItemSync,
399
+ builder
400
+ );
401
+ }
402
+ const originalWithBatch = builder.withBatch;
403
+ if (originalWithBatch) {
404
+ builder.withBatch = wrapMethodWithPreparation(originalWithBatch, prepareValidatedItemSync, builder);
405
+ }
406
+ return createEntityAwarePutBuilder(builder, config.name);
407
+ },
408
+ upsert: (data) => {
409
+ const builder = table.put({});
410
+ const prepareValidatedItemAsync = async () => {
411
+ const validatedData = await config.schema["~standard"].validate(data);
412
+ if ("issues" in validatedData && validatedData.issues) {
413
+ throw new Error(`Validation failed: ${validatedData.issues.map((i) => i.message).join(", ")}`);
414
+ }
415
+ const dataForKeyGeneration = {
416
+ ...validatedData.value,
417
+ ...generateTimestamps(["createdAt", "updatedAt"], validatedData.value)
418
+ };
419
+ const primaryKey = config.primaryKey.generateKey(dataForKeyGeneration);
420
+ const indexes = buildIndexes2(dataForKeyGeneration, table, false);
421
+ const validatedItem = {
422
+ [table.partitionKey]: primaryKey.pk,
423
+ ...table.sortKey ? { [table.sortKey]: primaryKey.sk } : {},
424
+ ...dataForKeyGeneration,
425
+ [entityTypeAttributeName]: config.name,
426
+ ...indexes
427
+ };
428
+ Object.assign(builder, { item: validatedItem });
429
+ return validatedItem;
430
+ };
431
+ const prepareValidatedItemSync = () => {
432
+ const validationResult = config.schema["~standard"].validate(data);
433
+ if (validationResult instanceof Promise) {
434
+ throw new Error(
435
+ "Async validation is not supported in withTransaction or withBatch. Use execute() instead."
436
+ );
437
+ }
438
+ if ("issues" in validationResult && validationResult.issues) {
439
+ throw new Error(`Validation failed: ${validationResult.issues.map((i) => i.message).join(", ")}`);
440
+ }
441
+ const dataForKeyGeneration = {
442
+ ...validationResult.value,
443
+ ...generateTimestamps(["createdAt", "updatedAt"], validationResult.value)
444
+ };
445
+ const primaryKey = config.primaryKey.generateKey(dataForKeyGeneration);
446
+ const indexes = buildIndexes(dataForKeyGeneration, table, config.indexes, false);
447
+ const validatedItem = {
448
+ [table.partitionKey]: primaryKey.pk,
449
+ ...table.sortKey ? { [table.sortKey]: primaryKey.sk } : {},
450
+ ...dataForKeyGeneration,
451
+ [entityTypeAttributeName]: config.name,
452
+ ...indexes
453
+ };
454
+ Object.assign(builder, { item: validatedItem });
455
+ return validatedItem;
456
+ };
457
+ const originalExecute = builder.execute;
458
+ builder.execute = async () => {
459
+ await prepareValidatedItemAsync();
460
+ const result = await originalExecute.call(builder);
461
+ if (!result) {
462
+ throw new Error("Failed to upsert item");
463
+ }
464
+ return result;
465
+ };
466
+ const originalWithTransaction = builder.withTransaction;
467
+ if (originalWithTransaction) {
468
+ builder.withTransaction = wrapMethodWithPreparation(
469
+ originalWithTransaction,
470
+ prepareValidatedItemSync,
471
+ builder
472
+ );
473
+ }
474
+ const originalWithBatch = builder.withBatch;
475
+ if (originalWithBatch) {
476
+ builder.withBatch = wrapMethodWithPreparation(originalWithBatch, prepareValidatedItemSync, builder);
477
+ }
478
+ return createEntityAwarePutBuilder(builder, config.name);
479
+ },
480
+ get: (key) => {
481
+ return createEntityAwareGetBuilder(table.get(config.primaryKey.generateKey(key)), config.name);
482
+ },
483
+ update: (key, data) => {
484
+ const primaryKeyObj = config.primaryKey.generateKey(key);
485
+ const builder = table.update(primaryKeyObj);
486
+ builder.condition(chunk7UJJ7JXM_cjs.eq(entityTypeAttributeName, config.name));
487
+ const entityAwareBuilder = createEntityAwareUpdateBuilder(builder, config.name);
488
+ entityAwareBuilder.configureEntityLogic({
489
+ data,
490
+ key,
491
+ table,
492
+ indexes: config.indexes,
493
+ generateTimestamps: () => generateTimestamps(["updatedAt"], data),
494
+ buildIndexUpdates
495
+ });
496
+ return entityAwareBuilder;
497
+ },
498
+ delete: (key) => {
499
+ const builder = table.delete(config.primaryKey.generateKey(key));
500
+ builder.condition(chunk7UJJ7JXM_cjs.eq(entityTypeAttributeName, config.name));
501
+ return createEntityAwareDeleteBuilder(builder, config.name);
502
+ },
503
+ query: Object.entries(config.queries || {}).reduce((acc, [key, inputCallback]) => {
504
+ acc[key] = (input) => {
505
+ const queryEntity = {
506
+ scan: repository.scan,
507
+ get: (key2) => createEntityAwareGetBuilder(table.get(key2), config.name),
508
+ query: (keyCondition) => {
509
+ return table.query(keyCondition);
510
+ }
511
+ };
512
+ const queryBuilderCallback = inputCallback(input);
513
+ const builder = queryBuilderCallback(queryEntity);
514
+ if (builder && typeof builder === "object" && "filter" in builder && typeof builder.filter === "function") {
515
+ builder.filter(chunk7UJJ7JXM_cjs.eq(entityTypeAttributeName, config.name));
516
+ }
517
+ if (builder && typeof builder === "object" && "execute" in builder) {
518
+ const originalExecute = builder.execute;
519
+ builder.execute = async () => {
520
+ const queryFn = config.queries[key];
521
+ if (queryFn && typeof queryFn === "function") {
522
+ const schema = queryFn.schema;
523
+ if (schema?.["~standard"]?.validate && typeof schema["~standard"].validate === "function") {
524
+ const validationResult = schema["~standard"].validate(input);
525
+ if ("issues" in validationResult && validationResult.issues) {
526
+ throw new Error(
527
+ `Validation failed: ${validationResult.issues.map((issue) => issue.message).join(", ")}`
528
+ );
529
+ }
530
+ }
531
+ }
532
+ const result = await originalExecute.call(builder);
533
+ if (!result) {
534
+ throw new Error("Failed to execute query");
535
+ }
536
+ return result;
537
+ };
538
+ }
539
+ return builder;
540
+ };
541
+ return acc;
542
+ }, {}),
543
+ scan: () => {
544
+ const builder = table.scan();
545
+ builder.filter(chunk7UJJ7JXM_cjs.eq(entityTypeAttributeName, config.name));
546
+ return builder;
547
+ }
548
+ };
549
+ return repository;
550
+ }
551
+ };
552
+ }
553
+ function createQueries() {
554
+ return {
555
+ input: (schema) => ({
556
+ query: (handler) => {
557
+ const queryFn = (input) => (entity) => handler({ input, entity });
558
+ queryFn.schema = schema;
559
+ return queryFn;
560
+ }
561
+ })
562
+ };
563
+ }
564
+ function createIndex() {
565
+ return {
566
+ input: (schema) => {
567
+ const createIndexBuilder = (isReadOnly = false) => ({
568
+ partitionKey: (pkFn) => ({
569
+ sortKey: (skFn) => {
570
+ const index = {
571
+ name: "custom",
572
+ partitionKey: "pk",
573
+ sortKey: "sk",
574
+ isReadOnly,
575
+ generateKey: (item) => {
576
+ const data = schema["~standard"].validate(item);
577
+ if ("issues" in data && data.issues) {
578
+ throw new Error(`Index validation failed: ${data.issues.map((i) => i.message).join(", ")}`);
579
+ }
580
+ const validData = "value" in data ? data.value : item;
581
+ return { pk: pkFn(validData), sk: skFn(validData) };
582
+ }
583
+ };
584
+ return Object.assign(index, {
585
+ readOnly: (value = false) => ({
586
+ ...index,
587
+ isReadOnly: value
588
+ })
589
+ });
590
+ },
591
+ withoutSortKey: () => {
592
+ const index = {
593
+ name: "custom",
594
+ partitionKey: "pk",
595
+ isReadOnly,
596
+ generateKey: (item) => {
597
+ const data = schema["~standard"].validate(item);
598
+ if ("issues" in data && data.issues) {
599
+ throw new Error(`Index validation failed: ${data.issues.map((i) => i.message).join(", ")}`);
600
+ }
601
+ const validData = "value" in data ? data.value : item;
602
+ return { pk: pkFn(validData) };
603
+ }
604
+ };
605
+ return Object.assign(index, {
606
+ readOnly: (value = true) => ({
607
+ ...index,
608
+ isReadOnly: value
609
+ })
610
+ });
611
+ }
612
+ }),
613
+ readOnly: (value = true) => createIndexBuilder(value)
614
+ });
615
+ return createIndexBuilder(false);
616
+ }
617
+ };
618
+ }
619
+
620
+ exports.createIndex = createIndex;
621
+ exports.createQueries = createQueries;
622
+ exports.defineEntity = defineEntity;
@@ -0,0 +1,32 @@
1
+ 'use strict';
2
+
3
+ // src/utils/partition-key-template.ts
4
+ function partitionKey(strings, ...keys) {
5
+ return (params) => {
6
+ let result = strings[0] ?? "";
7
+ for (let i = 0; i < keys.length; i++) {
8
+ const key = keys[i];
9
+ if (key) {
10
+ result += params[key] + (strings[i + 1] ?? "");
11
+ }
12
+ }
13
+ return result;
14
+ };
15
+ }
16
+
17
+ // src/utils/sort-key-template.ts
18
+ function sortKey(strings, ...keys) {
19
+ return (params) => {
20
+ let result = strings[0] ?? "";
21
+ for (let i = 0; i < keys.length; i++) {
22
+ const key = keys[i];
23
+ if (key && params && key in params) {
24
+ result += params[key] + (strings[i + 1] ?? "");
25
+ }
26
+ }
27
+ return result;
28
+ };
29
+ }
30
+
31
+ exports.partitionKey = partitionKey;
32
+ exports.sortKey = sortKey;
@@ -0,0 +1,29 @@
1
+ // src/utils/partition-key-template.ts
2
+ function partitionKey(strings, ...keys) {
3
+ return (params) => {
4
+ let result = strings[0] ?? "";
5
+ for (let i = 0; i < keys.length; i++) {
6
+ const key = keys[i];
7
+ if (key) {
8
+ result += params[key] + (strings[i + 1] ?? "");
9
+ }
10
+ }
11
+ return result;
12
+ };
13
+ }
14
+
15
+ // src/utils/sort-key-template.ts
16
+ function sortKey(strings, ...keys) {
17
+ return (params) => {
18
+ let result = strings[0] ?? "";
19
+ for (let i = 0; i < keys.length; i++) {
20
+ const key = keys[i];
21
+ if (key && params && key in params) {
22
+ result += params[key] + (strings[i + 1] ?? "");
23
+ }
24
+ }
25
+ return result;
26
+ };
27
+ }
28
+
29
+ export { partitionKey, sortKey };