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