dyno-table 0.1.8 → 0.2.0-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 (82) hide show
  1. package/README.md +570 -147
  2. package/dist/builder-types-C_PDZhnP.d.ts +118 -0
  3. package/dist/builder-types-DtwbqMeF.d.cts +118 -0
  4. package/dist/builders/condition-check-builder.cjs +1 -1
  5. package/dist/builders/condition-check-builder.cjs.map +1 -1
  6. package/dist/builders/condition-check-builder.d.cts +157 -0
  7. package/dist/builders/condition-check-builder.d.ts +157 -0
  8. package/dist/builders/condition-check-builder.js +1 -1
  9. package/dist/builders/condition-check-builder.js.map +1 -1
  10. package/dist/builders/delete-builder.cjs +0 -17
  11. package/dist/builders/delete-builder.cjs.map +1 -1
  12. package/dist/builders/delete-builder.d.cts +166 -0
  13. package/dist/builders/delete-builder.d.ts +166 -0
  14. package/dist/builders/delete-builder.js +0 -17
  15. package/dist/builders/delete-builder.js.map +1 -1
  16. package/dist/builders/paginator.cjs.map +1 -1
  17. package/dist/builders/paginator.d.cts +179 -0
  18. package/dist/builders/paginator.d.ts +179 -0
  19. package/dist/builders/paginator.js.map +1 -1
  20. package/dist/builders/put-builder.cjs +8 -0
  21. package/dist/builders/put-builder.cjs.map +1 -1
  22. package/dist/builders/put-builder.d.cts +274 -0
  23. package/dist/builders/put-builder.d.ts +274 -0
  24. package/dist/builders/put-builder.js +8 -0
  25. package/dist/builders/put-builder.js.map +1 -1
  26. package/dist/builders/query-builder.cjs.map +1 -1
  27. package/dist/builders/query-builder.d.cts +6 -0
  28. package/dist/builders/query-builder.d.ts +6 -0
  29. package/dist/builders/query-builder.js.map +1 -1
  30. package/dist/builders/transaction-builder.cjs +40 -22
  31. package/dist/builders/transaction-builder.cjs.map +1 -1
  32. package/dist/builders/transaction-builder.d.cts +511 -0
  33. package/dist/builders/transaction-builder.d.ts +511 -0
  34. package/dist/builders/transaction-builder.js +40 -22
  35. package/dist/builders/transaction-builder.js.map +1 -1
  36. package/dist/builders/update-builder.cjs +3 -38
  37. package/dist/builders/update-builder.cjs.map +1 -1
  38. package/dist/builders/update-builder.d.cts +365 -0
  39. package/dist/builders/update-builder.d.ts +365 -0
  40. package/dist/builders/update-builder.js +3 -38
  41. package/dist/builders/update-builder.js.map +1 -1
  42. package/dist/conditions--ld9a78i.d.ts +331 -0
  43. package/dist/conditions-ChhQWd6z.d.cts +331 -0
  44. package/dist/conditions.cjs.map +1 -1
  45. package/dist/conditions.d.cts +3 -0
  46. package/dist/conditions.d.ts +3 -0
  47. package/dist/conditions.js.map +1 -1
  48. package/dist/entity.cjs +156 -97
  49. package/dist/entity.cjs.map +1 -1
  50. package/dist/entity.d.cts +149 -0
  51. package/dist/entity.d.ts +149 -0
  52. package/dist/entity.js +156 -97
  53. package/dist/entity.js.map +1 -1
  54. package/dist/query-builder-Csror9Iu.d.ts +507 -0
  55. package/dist/query-builder-D2FM9rsu.d.cts +507 -0
  56. package/dist/standard-schema.d.cts +57 -0
  57. package/dist/standard-schema.d.ts +57 -0
  58. package/dist/table-BEhBPy2G.d.cts +364 -0
  59. package/dist/table-BW3cmUqr.d.ts +364 -0
  60. package/dist/table.cjs +82 -102
  61. package/dist/table.cjs.map +1 -1
  62. package/dist/table.d.cts +12 -0
  63. package/dist/table.d.ts +12 -0
  64. package/dist/table.js +82 -102
  65. package/dist/table.js.map +1 -1
  66. package/dist/types.d.cts +22 -0
  67. package/dist/types.d.ts +22 -0
  68. package/dist/utils/{key-template.cjs → partition-key-template.cjs} +3 -3
  69. package/dist/utils/partition-key-template.cjs.map +1 -0
  70. package/dist/utils/partition-key-template.d.cts +32 -0
  71. package/dist/utils/partition-key-template.d.ts +32 -0
  72. package/dist/utils/{key-template.js → partition-key-template.js} +3 -3
  73. package/dist/utils/partition-key-template.js.map +1 -0
  74. package/dist/utils/sort-key-template.d.cts +35 -0
  75. package/dist/utils/sort-key-template.d.ts +35 -0
  76. package/package.json +86 -9
  77. package/dist/index.cjs +0 -3333
  78. package/dist/index.d.cts +0 -2971
  79. package/dist/index.d.ts +0 -2971
  80. package/dist/index.js +0 -3284
  81. package/dist/utils/key-template.cjs.map +0 -1
  82. package/dist/utils/key-template.js.map +0 -1
package/dist/entity.cjs CHANGED
@@ -1,37 +1,101 @@
1
1
  'use strict';
2
2
 
3
+ // src/conditions.ts
4
+ var createComparisonCondition = (type) => (attr, value) => ({
5
+ type,
6
+ attr,
7
+ value
8
+ });
9
+ var eq = createComparisonCondition("eq");
10
+
3
11
  // src/entity.ts
4
12
  function defineEntity(config) {
13
+ const entityTypeAttributeName = config.settings?.entityTypeAttributeName ?? "entityType";
14
+ const generateTimestamps = () => {
15
+ const timestamps = {};
16
+ if (config.settings?.timestamps) {
17
+ const now = /* @__PURE__ */ new Date();
18
+ if (config.settings.timestamps.createdAt) {
19
+ const attributeName = config.settings.timestamps.createdAt.attributeName ?? "createdAt";
20
+ timestamps[attributeName] = config.settings.timestamps.createdAt.format === "UNIX" ? Math.floor(Date.now() / 1e3) : now.toISOString();
21
+ }
22
+ if (config.settings.timestamps.updatedAt) {
23
+ const attributeName = config.settings.timestamps.updatedAt.attributeName ?? "updatedAt";
24
+ timestamps[attributeName] = config.settings.timestamps.updatedAt.format === "UNIX" ? Math.floor(Date.now() / 1e3) : now.toISOString();
25
+ }
26
+ }
27
+ return timestamps;
28
+ };
5
29
  return {
30
+ name: config.name,
6
31
  createRepository: (table) => {
7
32
  const repository = {
8
- _hooks: config.hooks,
9
33
  create: (data) => {
10
- const builder = table.create(data);
34
+ const builder = table.create({
35
+ ...data,
36
+ [entityTypeAttributeName]: config.name,
37
+ ...generateTimestamps()
38
+ });
11
39
  const originalExecute = builder.execute;
12
40
  builder.execute = async () => {
13
41
  const validationResult = await config.schema["~standard"].validate(data);
14
42
  if ("issues" in validationResult && validationResult.issues) {
15
43
  throw new Error(`Validation failed: ${validationResult.issues.map((i) => i.message).join(", ")}`);
16
44
  }
17
- Object.assign(builder, { item: validationResult.value });
18
- const result = await originalExecute.call(builder);
19
- if (!result) {
20
- throw new Error("Failed to create item");
21
- }
22
- return result;
45
+ const primaryKey = config.primaryKey.generateKey(validationResult.value);
46
+ const indexes = Object.entries(config.indexes ?? {}).reduce(
47
+ (acc, [indexName, index]) => {
48
+ const key = index.generateKey(validationResult.value);
49
+ const gsiConfig = table.gsis[indexName];
50
+ if (!gsiConfig) {
51
+ throw new Error(`GSI configuration not found for index: ${indexName}`);
52
+ }
53
+ if (key.pk) {
54
+ acc[gsiConfig.partitionKey] = key.pk;
55
+ }
56
+ if (key.sk && gsiConfig.sortKey) {
57
+ acc[gsiConfig.sortKey] = key.sk;
58
+ }
59
+ return acc;
60
+ },
61
+ {}
62
+ );
63
+ Object.assign(builder, {
64
+ item: {
65
+ ...validationResult.value,
66
+ [entityTypeAttributeName]: config.name,
67
+ [table.partitionKey]: primaryKey.pk,
68
+ ...table.sortKey ? { [table.sortKey]: primaryKey.sk } : {},
69
+ ...indexes,
70
+ ...generateTimestamps()
71
+ }
72
+ });
73
+ return await originalExecute.call(builder);
23
74
  };
24
75
  return builder;
25
76
  },
26
77
  upsert: (data) => {
27
- const builder = table.put(data);
78
+ const primaryKey = config.primaryKey.generateKey(data);
79
+ const builder = table.put({
80
+ [table.partitionKey]: primaryKey.pk,
81
+ ...table.sortKey ? { [table.sortKey]: primaryKey.sk } : {},
82
+ ...data,
83
+ [entityTypeAttributeName]: config.name,
84
+ ...generateTimestamps()
85
+ });
28
86
  const originalExecute = builder.execute;
29
87
  builder.execute = async () => {
30
88
  const validationResult = await config.schema["~standard"].validate(data);
31
89
  if ("issues" in validationResult && validationResult.issues) {
32
90
  throw new Error(`Validation failed: ${validationResult.issues.map((i) => i.message).join(", ")}`);
33
91
  }
34
- Object.assign(builder, { item: validationResult.value });
92
+ Object.assign(builder, {
93
+ item: {
94
+ ...validationResult.value,
95
+ [entityTypeAttributeName]: config.name,
96
+ ...generateTimestamps()
97
+ }
98
+ });
35
99
  const result = await originalExecute.call(builder);
36
100
  if (!result) {
37
101
  throw new Error("Failed to upsert item");
@@ -41,69 +105,77 @@ function defineEntity(config) {
41
105
  return builder;
42
106
  },
43
107
  get: (key) => {
44
- const builder = table.get(key);
45
- const originalExecute = builder.execute;
46
- builder.execute = async () => {
47
- const result = await originalExecute.call(builder);
48
- const item = result?.item;
49
- return {
50
- item: config.hooks?.afterGet ? await config.hooks.afterGet(item) : item
51
- };
52
- };
53
- return builder;
108
+ const primaryKeyObj = config.primaryKey.generateKey(key);
109
+ return table.get(primaryKeyObj);
54
110
  },
55
111
  update: (key, data) => {
56
- const builder = table.update(key);
57
- const originalExecute = builder.execute;
58
- builder.execute = async () => {
59
- const result = await originalExecute.call(builder);
60
- if (!result?.item) {
61
- throw new Error("Failed to update item");
62
- }
63
- return result.item;
64
- };
112
+ const primaryKeyObj = config.primaryKey.generateKey(key);
113
+ const builder = table.update(primaryKeyObj);
114
+ builder.condition(eq(entityTypeAttributeName, config.name));
115
+ const timestamps = {};
116
+ if (config.settings?.timestamps?.updatedAt) {
117
+ const now = /* @__PURE__ */ new Date();
118
+ const attributeName = config.settings.timestamps.updatedAt.attributeName ?? "updatedAt";
119
+ timestamps[attributeName] = config.settings.timestamps.updatedAt.format === "UNIX" ? Math.floor(Date.now() / 1e3) : now.toISOString();
120
+ }
121
+ builder.set({
122
+ ...data,
123
+ ...timestamps
124
+ });
65
125
  return builder;
66
126
  },
67
127
  delete: (key) => {
68
- return table.delete(key);
128
+ const primaryKeyObj = config.primaryKey.generateKey(key);
129
+ const builder = table.delete(primaryKeyObj);
130
+ builder.condition(eq(entityTypeAttributeName, config.name));
131
+ return builder;
69
132
  },
70
- query: {},
71
- // Add a method to create a query builder
72
- queryBuilder: (key) => {
73
- const primaryKey = {
74
- pk: key.pk,
75
- ...key.sk ? { sk: (op) => op.eq(key.sk) } : {}
133
+ query: Object.entries(config.queries || {}).reduce((acc, [key, inputCallback]) => {
134
+ acc[key] = (input) => {
135
+ const queryEntity = {
136
+ scan: repository.scan,
137
+ get: (key2) => table.get(key2),
138
+ query: (keyCondition) => {
139
+ return table.query(keyCondition);
140
+ }
141
+ };
142
+ const queryBuilderCallback = inputCallback(input);
143
+ const builder = queryBuilderCallback(queryEntity);
144
+ if (builder && typeof builder === "object" && "filter" in builder && typeof builder.filter === "function") {
145
+ builder.filter(eq(entityTypeAttributeName, config.name));
146
+ }
147
+ if (builder && typeof builder === "object" && "execute" in builder) {
148
+ const originalExecute = builder.execute;
149
+ builder.execute = async () => {
150
+ const queryFn = config.queries[key];
151
+ if (queryFn && typeof queryFn === "function") {
152
+ const schema = queryFn.schema;
153
+ if (schema?.["~standard"]?.validate && typeof schema["~standard"].validate === "function") {
154
+ const validationResult = schema["~standard"].validate(input);
155
+ if ("issues" in validationResult && validationResult.issues) {
156
+ throw new Error(
157
+ `Validation failed: ${validationResult.issues.map((issue) => issue.message).join(", ")}`
158
+ );
159
+ }
160
+ }
161
+ }
162
+ const result = await originalExecute.call(builder);
163
+ if (!result) {
164
+ throw new Error("Failed to execute query");
165
+ }
166
+ return result;
167
+ };
168
+ }
169
+ return builder;
76
170
  };
77
- return table.query(primaryKey);
78
- },
79
- // Implement findBy method to find entities by their attributes
80
- findBy: (attribute, value, options) => {
81
- const scanBuilder = table.scan().filter((op) => op.eq(attribute, value));
82
- if (options?.limit) {
83
- scanBuilder.limit(options.limit);
84
- }
85
- if (options?.lastEvaluatedKey) {
86
- scanBuilder.startFrom(options.lastEvaluatedKey);
87
- }
88
- return scanBuilder;
89
- },
90
- // Implement scan method to scan all entities
91
- scan: (options) => {
171
+ return acc;
172
+ }, {}),
173
+ scan: () => {
92
174
  const scanBuilder = table.scan();
93
- if (options?.limit) {
94
- scanBuilder.limit(options.limit);
95
- }
96
- if (options?.lastEvaluatedKey) {
97
- scanBuilder.startFrom(options.lastEvaluatedKey);
98
- }
175
+ scanBuilder.filter(eq(entityTypeAttributeName, config.name));
99
176
  return scanBuilder;
100
177
  }
101
178
  };
102
- if (config.queries) {
103
- for (const [key, queryFn] of Object.entries(config.queries)) {
104
- repository.query[key] = queryFn.bind(repository);
105
- }
106
- }
107
179
  return repository;
108
180
  }
109
181
  };
@@ -111,28 +183,13 @@ function defineEntity(config) {
111
183
  function createQueries() {
112
184
  return {
113
185
  input: (schema) => ({
114
- // biome-ignore lint/complexity/noBannedTypes: <explanation>
115
186
  query: (handler) => {
116
- const queryFn = async function(input) {
117
- const validationResult = await schema["~standard"].validate(input);
118
- if ("issues" in validationResult && validationResult.issues) {
119
- throw new Error(`Validation failed: ${validationResult.issues.map((i) => i.message).join(", ")}`);
120
- }
121
- const queryBuilder = handler({ input: validationResult.value, entity: this });
122
- const result = await queryBuilder.execute();
123
- let items = result.items;
124
- if (this._hooks?.afterGet) {
125
- const processedItems = await Promise.all(
126
- // biome-ignore lint/style/noNonNullAssertion: The method will exit as it's confirmed above
127
- items.map(async (item) => await this._hooks.afterGet(item))
128
- );
129
- items = processedItems.filter((item) => item !== null);
130
- }
131
- return {
132
- items,
133
- lastEvaluatedKey: result.lastEvaluatedKey
187
+ const queryFn = (input) => {
188
+ return (entity) => {
189
+ return handler({ input, entity });
134
190
  };
135
191
  };
192
+ queryFn.schema = schema;
136
193
  return queryFn;
137
194
  }
138
195
  })
@@ -140,22 +197,24 @@ function createQueries() {
140
197
  }
141
198
  function createIndex() {
142
199
  return {
143
- partitionKey: (pkFn) => ({
144
- sortKey: (skFn) => ({
145
- name: "custom",
146
- partitionKey: "pk",
147
- sortKey: "sk",
148
- generateKey: (item) => ({
149
- pk: pkFn(item),
150
- sk: skFn(item)
151
- })
152
- }),
153
- // Allow creating an index with only a partition key
154
- withoutSortKey: () => ({
155
- name: "custom",
156
- partitionKey: "pk",
157
- generateKey: (item) => ({
158
- pk: pkFn(item)
200
+ input: (schema) => ({
201
+ partitionKey: (pkFn) => ({
202
+ sortKey: (skFn) => ({
203
+ name: "custom",
204
+ partitionKey: "pk",
205
+ sortKey: "sk",
206
+ generateKey: (item) => ({
207
+ pk: pkFn(item),
208
+ sk: skFn(item)
209
+ })
210
+ }),
211
+ // Allow creating an index with only a partition key
212
+ withoutSortKey: () => ({
213
+ name: "custom",
214
+ partitionKey: "pk",
215
+ generateKey: (item) => ({
216
+ pk: pkFn(item)
217
+ })
159
218
  })
160
219
  })
161
220
  })
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/entity.ts"],"names":[],"mappings":";;;AAqEO,SAAS,aACd,MACA,EAAA;AACA,EAAO,OAAA;AAAA,IACL,gBAAA,EAAkB,CAAC,KAAyC,KAAA;AAE1D,MAAA,MAAM,UAAa,GAAA;AAAA,QACjB,QAAQ,MAAO,CAAA,KAAA;AAAA,QACf,MAAA,EAAQ,CAAC,IAAY,KAAA;AAEnB,UAAM,MAAA,OAAA,GAAU,KAAM,CAAA,MAAA,CAAO,IAAI,CAAA;AAGjC,UAAA,MAAM,kBAAkB,OAAQ,CAAA,OAAA;AAChC,UAAA,OAAA,CAAQ,UAAU,YAAY;AAE5B,YAAA,MAAM,mBAAmB,MAAM,MAAA,CAAO,OAAO,WAAW,CAAA,CAAE,SAAS,IAAI,CAAA;AACvE,YAAI,IAAA,QAAA,IAAY,gBAAoB,IAAA,gBAAA,CAAiB,MAAQ,EAAA;AAC3D,cAAA,MAAM,IAAI,KAAA,CAAM,CAAsB,mBAAA,EAAA,gBAAA,CAAiB,OAAO,GAAI,CAAA,CAAC,CAAM,KAAA,CAAA,CAAE,OAAO,CAAA,CAAE,IAAK,CAAA,IAAI,CAAC,CAAE,CAAA,CAAA;AAAA;AAIlG,YAAA,MAAA,CAAO,OAAO,OAAS,EAAA,EAAE,IAAM,EAAA,gBAAA,CAAiB,OAAO,CAAA;AAGvD,YAAA,MAAM,MAAS,GAAA,MAAM,eAAgB,CAAA,IAAA,CAAK,OAAO,CAAA;AACjD,YAAA,IAAI,CAAC,MAAQ,EAAA;AACX,cAAM,MAAA,IAAI,MAAM,uBAAuB,CAAA;AAAA;AAGzC,YAAO,OAAA,MAAA;AAAA,WACT;AAEA,UAAO,OAAA,OAAA;AAAA,SACT;AAAA,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,MAGF,gBAAgB,OACb;AAAA,QACC,IAAM,EAAA,QAAA;AAAA,QACN,YAAc,EAAA,IAAA;AAAA,QACd,WAAA,EAAa,CAAC,IAAa,MAAA;AAAA,UACzB,EAAA,EAAI,KAAK,IAAI;AAAA,SACf;AAAA,OACF;AAAA,KACJ;AAAA,GACF;AACF","file":"entity.cjs","sourcesContent":["import type { Table } from \"./table\";\nimport type { StandardSchemaV1 } from \"./standard-schema\";\nimport type { PrimaryKeyWithoutExpression } from \"./conditions\";\nimport type { Index } from \"./types\";\nimport type { QueryBuilder } from \"./builders/query-builder\";\nimport type { Path, PathType } from \"./builders/types\";\nimport type { KeyConditionOperator } from \"./conditions\";\nimport type { ScanBuilder } from \"./builders/scan-builder\";\nimport type { DeleteBuilder } from \"./builders/delete-builder\";\nimport type { UpdateBuilder } from \"./builders/update-builder\";\nimport type { GetBuilder } from \"./builders/get-builder\";\nimport type { PutBuilder } from \"./builders/put-builder\";\n\nexport interface EntityHooks<T extends Record<string, unknown>> {\n beforeCreate?: (data: T) => Promise<T> | T;\n afterCreate?: (data: T) => Promise<T> | T;\n beforeUpdate?: (data: Partial<T>) => Promise<Partial<T>> | Partial<T>;\n afterUpdate?: (data: T) => Promise<T> | T;\n afterGet?: (data: T | undefined) => Promise<T | undefined> | T | undefined;\n}\n\n// Define a type for query functions\nexport type QueryFunction<T extends Record<string, unknown>, I, R = T[]> = (input: I) => R;\n\n// Define a type for the query record\nexport type QueryRecord<T extends Record<string, unknown>> = Record<string, QueryBuilder<T>>;\n\n// Define a type for the result of a query builder\nexport type QueryBuilderResult<T extends Record<string, unknown>> = {\n items: T[];\n lastEvaluatedKey?: Record<string, unknown>;\n};\n\nexport interface EntityConfig<T extends Record<string, unknown>, Q extends QueryRecord<T> = {}> {\n name: string;\n schema: StandardSchemaV1<T>;\n primaryKey: Index;\n indexes?: Record<string, Index>;\n queries?: Q;\n hooks?: EntityHooks<T>;\n}\n\nexport interface PaginationOptions {\n limit?: number;\n lastEvaluatedKey?: Record<string, any>;\n}\n\nexport interface PaginatedResult<T> {\n items: T[];\n lastEvaluatedKey?: Record<string, any>;\n hasMore: boolean;\n}\n\nexport interface EntityRepository<T extends Record<string, unknown>, Q extends QueryRecord<T> = {}> {\n _hooks?: EntityHooks<T>;\n create: (data: T) => PutBuilder<T>;\n upsert: (data: T) => PutBuilder<T>;\n get: (key: PrimaryKeyWithoutExpression) => GetBuilder<T>;\n update: (key: PrimaryKeyWithoutExpression, data: Partial<T>) => UpdateBuilder<T>;\n delete: (key: PrimaryKeyWithoutExpression) => DeleteBuilder;\n query: Q;\n // Add a method to create a query builder\n queryBuilder: (key: PrimaryKeyWithoutExpression) => QueryBuilder<T, any>;\n // Add a method to find entities by their attributes\n findBy: <K extends keyof T>(attribute: K, value: T[K], options?: PaginationOptions) => any; // Returns ScanBuilder<T>\n // Add a method to scan all entities\n scan: (options?: PaginationOptions) => ScanBuilder<T>;\n}\n\nexport function defineEntity<T extends Record<string, unknown>, Q extends QueryRecord<T> = {}>(\n config: EntityConfig<T, Q>,\n) {\n return {\n createRepository: (table: Table): EntityRepository<T, Q> => {\n // Create a repository with hooks attached\n const repository = {\n _hooks: config.hooks,\n create: (data: T) => {\n // We need to handle the async operations when the consumer calls execute\n const builder = table.create(data);\n\n // Wrap the builder's execute method to apply validation only (no hooks)\n const originalExecute = builder.execute;\n builder.execute = async () => {\n // Validate data against schema\n const validationResult = await config.schema[\"~standard\"].validate(data);\n if (\"issues\" in validationResult && validationResult.issues) {\n throw new Error(`Validation failed: ${validationResult.issues.map((i) => i.message).join(\", \")}`);\n }\n\n // Update the item in the builder with the validated data\n Object.assign(builder, { item: validationResult.value });\n\n // Execute the builder\n const result = await originalExecute.call(builder);\n if (!result) {\n throw new Error(\"Failed to create item\");\n }\n\n return result;\n };\n\n return builder;\n },\n\n upsert: (data: T) => {\n // We need to handle the async operations when the consumer calls execute\n const builder = table.put(data);\n\n // Wrap the builder's execute method to apply validation only (no hooks)\n const originalExecute = builder.execute;\n builder.execute = async () => {\n // Validate data against schema\n const validationResult = await config.schema[\"~standard\"].validate(data);\n if (\"issues\" in validationResult && validationResult.issues) {\n throw new Error(`Validation failed: ${validationResult.issues.map((i) => i.message).join(\", \")}`);\n }\n\n // Update the item in the builder with the validated data\n Object.assign(builder, { item: validationResult.value });\n\n // Execute the builder\n const result = await originalExecute.call(builder);\n if (!result) {\n throw new Error(\"Failed to upsert item\");\n }\n\n return result;\n };\n\n return builder;\n },\n\n get: (key: PrimaryKeyWithoutExpression) => {\n const builder = table.get<T>(key);\n\n // Wrap the builder's execute method to apply afterGet hook\n const originalExecute = builder.execute;\n\n builder.execute = async () => {\n const result = await originalExecute.call(builder);\n const item = result?.item;\n\n // Apply afterGet hook if exists\n return {\n item: config.hooks?.afterGet ? await config.hooks.afterGet(item as T) : item,\n };\n };\n\n return builder;\n },\n\n update: (key: PrimaryKeyWithoutExpression, data: Partial<T>) => {\n // Create a builder without hooks\n const builder = table.update<T>(key);\n\n // Wrap the builder's execute method to handle errors\n const originalExecute = builder.execute;\n builder.execute = async () => {\n const result = await originalExecute.call(builder);\n if (!result?.item) {\n throw new Error(\"Failed to update item\");\n }\n\n // Return the item without applying hooks\n return result.item as T;\n };\n\n return builder;\n },\n\n delete: (key: PrimaryKeyWithoutExpression) => {\n return table.delete(key);\n },\n\n query: {} as Q,\n\n // Add a method to create a query builder\n queryBuilder: (key: PrimaryKeyWithoutExpression) => {\n // Convert PrimaryKeyWithoutExpression to PrimaryKey\n const primaryKey = {\n pk: key.pk,\n ...(key.sk ? { sk: (op: KeyConditionOperator) => op.eq(key.sk as string) } : {}),\n };\n return table.query<T>(primaryKey);\n },\n\n // Implement findBy method to find entities by their attributes\n findBy: <K extends keyof T>(attribute: K, value: T[K], options?: PaginationOptions) => {\n // Use scan with a filter to find entities by attribute\n const scanBuilder = table.scan<T>().filter((op) => op.eq(attribute as string as Path<T>, value as any));\n\n // Apply pagination options if provided\n if (options?.limit) {\n scanBuilder.limit(options.limit);\n }\n\n if (options?.lastEvaluatedKey) {\n scanBuilder.startFrom(options.lastEvaluatedKey);\n }\n\n // Return the builder without applying hooks\n return scanBuilder;\n },\n\n // Implement scan method to scan all entities\n scan: (options?: PaginationOptions) => {\n // Create a scan builder\n const scanBuilder = table.scan<T>();\n\n // Apply pagination options if provided\n if (options?.limit) {\n scanBuilder.limit(options.limit);\n }\n\n if (options?.lastEvaluatedKey) {\n scanBuilder.startFrom(options.lastEvaluatedKey);\n }\n\n // Return the builder without applying hooks\n return scanBuilder;\n },\n };\n\n // Bind query functions to the repository after it's fully defined\n if (config.queries) {\n for (const [key, queryFn] of Object.entries(config.queries)) {\n // biome-ignore lint/suspicious/noExplicitAny: Let the magic happen\n (repository.query as any)[key] = queryFn.bind(repository);\n }\n }\n\n return repository;\n },\n };\n}\n\nexport function createQueries<T extends Record<string, unknown>>() {\n return {\n input: <I, R = QueryBuilderResult<T>>(schema: StandardSchemaV1<I>) => ({\n // biome-ignore lint/complexity/noBannedTypes: <explanation>\n query: <Q extends QueryRecord<T> = {}>(\n // biome-ignore lint/suspicious/noExplicitAny: <explanation>\n handler: (params: { input: I; entity: EntityRepository<T, Q> }) => QueryBuilder<T, any>,\n ): QueryFunction<T, I, R> => {\n // Return a function that will be bound to the repository when it's created\n const queryFn = async function (this: EntityRepository<T, Q>, input: I): Promise<R> {\n // Validate input against schema\n const validationResult = await schema[\"~standard\"].validate(input);\n if (\"issues\" in validationResult && validationResult.issues) {\n throw new Error(`Validation failed: ${validationResult.issues.map((i) => i.message).join(\", \")}`);\n }\n\n // Use 'this' as the entity repository (will be bound when the repository is created)\n const queryBuilder = handler({ input: validationResult.value, entity: this });\n\n // Execute the query\n const result = await queryBuilder.execute();\n\n // Apply afterGet hook to each item if exists\n let items = result.items;\n if (this._hooks?.afterGet) {\n const processedItems = await Promise.all(\n // biome-ignore lint/style/noNonNullAssertion: The method will exit as it's confirmed above\n items.map(async (item) => await this._hooks!.afterGet!(item as T)),\n );\n items = processedItems.filter((item): item is NonNullable<typeof item> => item !== null) as T[];\n }\n\n // Return the full result with processed items\n return {\n items,\n lastEvaluatedKey: result.lastEvaluatedKey,\n } as unknown as R;\n };\n\n return queryFn as unknown as QueryFunction<T, I, R>;\n },\n }),\n };\n}\n\nexport interface IndexDefinition<T extends Record<string, unknown>> extends Index {\n name: string;\n generateKey: (item: T) => { pk: string; sk?: string };\n}\n\nexport function createIndex<T extends Record<string, unknown>>() {\n return {\n partitionKey: <P extends (item: T) => string>(pkFn: P) => ({\n sortKey: <S extends (item: T) => string>(skFn: S) =>\n ({\n name: \"custom\",\n partitionKey: \"pk\",\n sortKey: \"sk\",\n generateKey: (item: T) => ({\n pk: pkFn(item),\n sk: skFn(item),\n }),\n }) as IndexDefinition<T>,\n\n // Allow creating an index with only a partition key\n withoutSortKey: () =>\n ({\n name: \"custom\",\n partitionKey: \"pk\",\n generateKey: (item: T) => ({\n pk: pkFn(item),\n }),\n }) as IndexDefinition<T>,\n }),\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/conditions.ts","../src/entity.ts"],"names":["key"],"mappings":";;;AA+FO,IAAM,yBACX,GAAA,CAAC,IACD,KAAA,CAAC,MAAc,KAA+B,MAAA;AAAA,EAC5C,IAAA;AAAA,EACA,IAAA;AAAA,EACA;AACF,CAAA,CAAA;AAQK,IAAM,EAAA,GAAK,0BAA0B,IAAI,CAAA;;;ACwBzC,SAAS,aACd,MACA,EAAA;AACA,EAAM,MAAA,uBAAA,GAA0B,MAAO,CAAA,QAAA,EAAU,uBAA2B,IAAA,YAAA;AAkB5E,EAAA,MAAM,qBAAqB,MAAuC;AAChE,IAAA,MAAM,aAA8C,EAAC;AAErD,IAAI,IAAA,MAAA,CAAO,UAAU,UAAY,EAAA;AAC/B,MAAM,MAAA,GAAA,uBAAU,IAAK,EAAA;AAErB,MAAI,IAAA,MAAA,CAAO,QAAS,CAAA,UAAA,CAAW,SAAW,EAAA;AACxC,QAAA,MAAM,aAAgB,GAAA,MAAA,CAAO,QAAS,CAAA,UAAA,CAAW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ACf;AAAA,SACF;AAAA,OACJ;AAAA,KACF;AAAA,GACF;AACF","file":"entity.cjs","sourcesContent":["import type { Path, PathType } from \"./builders/types\";\nimport type { DynamoItem } from \"./types\";\n\n/**\n * Supported comparison operators for DynamoDB conditions.\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html AWS DynamoDB - Comparison Operator Reference}\n *\n * - eq: Equals (=)\n * - ne: Not equals (≠ / <>)\n * - lt: Less than (<)\n * - lte: Less than or equal to (≤)\n * - gt: Greater than (>)\n * - gte: Greater than or equal to (≥)\n * - between: Between two values (inclusive)\n * - beginsWith: Checks if string attribute begins with specified substring\n * - contains: Checks if string/set attribute contains specified value\n * - attributeExists: Checks if attribute exists\n * - attributeNotExists: Checks if attribute does not exist\n */\nexport type ComparisonOperator =\n | \"eq\"\n | \"ne\"\n | \"lt\"\n | \"lte\"\n | \"gt\"\n | \"gte\"\n | \"between\"\n | \"beginsWith\"\n | \"contains\"\n | \"attributeExists\"\n | \"attributeNotExists\";\n\n/**\n * Logical operators for combining multiple conditions.\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html#Expressions.OperatorsAndFunctions.Logical AWS DynamoDB - Logical Operator Reference}\n *\n * - and: Evaluates to true if all conditions are true\n * - or: Evaluates to true if any condition is true\n * - not: Negate the result of a condition\n */\nexport type LogicalOperator = \"and\" | \"or\" | \"not\";\n\n/**\n * Represents a DynamoDB condition expression.\n * Can be either a comparison condition or a logical combination of conditions.\n *\n * @example\n * // Simple comparison condition\n * const condition: Condition = {\n * type: \"eq\",\n * attr: \"status\",\n * value: \"ACTIVE\"\n * };\n *\n * @example\n * // Logical combination of conditions\n * const condition: Condition = {\n * type: \"and\",\n * conditions: [\n * { type: \"eq\", attr: \"status\", value: \"ACTIVE\" },\n * { type: \"gt\", attr: \"age\", value: 5 }\n * ]\n * };\n */\nexport interface Condition {\n /** The type of condition (comparison or logical operator) */\n type: ComparisonOperator | LogicalOperator;\n /** The attribute name for comparison conditions */\n attr?: string;\n /** The value to compare against for comparison conditions */\n value?: unknown;\n /** Array of conditions for logical operators (and/or) */\n conditions?: Condition[];\n /** Single condition for the 'not' operator */\n condition?: Condition;\n}\n\n/**\n * Parameters used to build DynamoDB expression strings.\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeNames.html Expression Attribute Names}\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeValues.html Expression Attribute Values}\n */\nexport interface ExpressionParams {\n /** Map of attribute name placeholders to actual attribute names */\n expressionAttributeNames: Record<string, string>;\n /** Map of value placeholders to actual values */\n expressionAttributeValues: DynamoItem;\n /** Counter for generating unique value placeholders */\n valueCounter: { count: number };\n}\n\n/**\n * Creates a comparison condition builder function for the specified operator.\n * @internal\n */\nexport const createComparisonCondition =\n (type: ComparisonOperator) =>\n (attr: string, value: unknown): Condition => ({\n type,\n attr,\n value,\n });\n\n/**\n * Creates an equals (=) condition\n * @example\n * eq(\"status\", \"ACTIVE\") // status = \"ACTIVE\"\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html}\n */\nexport const eq = createComparisonCondition(\"eq\");\n\n/**\n * Creates a not equals (≠) condition\n * @example\n * ne(\"status\", \"DELETED\") // status <> \"DELETED\"\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html}\n */\nexport const ne = createComparisonCondition(\"ne\");\n\n/**\n * Creates a less than (<) condition\n * @example\n * lt(\"age\", 18) // age < 18\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html}\n */\nexport const lt = createComparisonCondition(\"lt\");\n\n/**\n * Creates a less than or equal to (≤) condition\n * @example\n * lte(\"age\", 18) // age <= 18\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html}\n */\nexport const lte = createComparisonCondition(\"lte\");\n\n/**\n * Creates a greater than (>) condition\n * @example\n * gt(\"price\", 100) // price > 100\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html}\n */\nexport const gt = createComparisonCondition(\"gt\");\n\n/**\n * Creates a greater than or equal to (≥) condition\n * @example\n * gte(\"price\", 100) // price >= 100\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html}\n */\nexport const gte = createComparisonCondition(\"gte\");\n\n/**\n * Creates a between condition that checks if a value is within a range (inclusive)\n * @example\n * between(\"age\", 18, 65) // age BETWEEN 18 AND 65\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html#Expressions.OperatorsAndFunctions.Comparators AWS DynamoDB - BETWEEN}\n */\nexport const between = (attr: string, lower: unknown, upper: unknown): Condition => ({\n type: \"between\",\n attr,\n value: [lower, upper],\n});\n\n/**\n * Creates a begins_with condition that checks if a string attribute starts with a substring\n * @example\n * beginsWith(\"email\", \"@example.com\") // begins_with(email, \"@example.com\")\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html#Expressions.OperatorsAndFunctions.Functions AWS DynamoDB - begins_with}\n */\nexport const beginsWith = createComparisonCondition(\"beginsWith\");\n\n/**\n * Creates a contains condition that checks if a string contains a substring or if a set contains an element\n * @example\n * contains(\"tags\", \"important\") // contains(tags, \"important\")\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html#Expressions.OperatorsAndFunctions.Functions AWS DynamoDB - contains}\n */\nexport const contains = createComparisonCondition(\"contains\");\n\n/**\n * Creates a condition that checks if an attribute exists\n * @example\n * attributeExists(\"email\") // attribute_exists(email)\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html#Expressions.OperatorsAndFunctions.Functions AWS DynamoDB - attribute_exists}\n */\nexport const attributeExists = (attr: string): Condition => ({\n type: \"attributeExists\",\n attr,\n});\n\n/**\n * Creates a condition that checks if an attribute does not exist\n * @example\n * attributeNotExists(\"deletedAt\") // attribute_not_exists(deletedAt)\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html#Expressions.OperatorsAndFunctions.Functions AWS DynamoDB - attribute_not_exists}\n */\nexport const attributeNotExists = (attr: string): Condition => ({\n type: \"attributeNotExists\",\n attr,\n});\n\n// --- Logical Operators ---\n\n/**\n * Combines multiple conditions with AND operator\n * @example\n * and(\n * eq(\"status\", \"ACTIVE\"),\n * gt(\"age\", 18)\n * ) // status = \"ACTIVE\" AND age > 18\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html#Expressions.OperatorsAndFunctions.Logical AWS DynamoDB - AND}\n */\nexport const and = (...conditions: Condition[]): Condition => ({\n type: \"and\",\n conditions,\n});\n\n/**\n * Combines multiple conditions with OR operator\n * @example\n * or(\n * eq(\"status\", \"PENDING\"),\n * eq(\"status\", \"PROCESSING\")\n * ) // status = \"PENDING\" OR status = \"PROCESSING\"\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html#Expressions.OperatorsAndFunctions.Logical AWS DynamoDB - OR}\n */\nexport const or = (...conditions: Condition[]): Condition => ({\n type: \"or\",\n conditions,\n});\n\n/**\n * Negates a condition\n * @example\n * not(eq(\"status\", \"DELETED\")) // NOT status = \"DELETED\"\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html#Expressions.OperatorsAndFunctions.Logical AWS DynamoDB - NOT}\n */\nexport const not = (condition: Condition): Condition => ({\n type: \"not\",\n condition,\n});\n\n/**\n * Type-safe operators for building key conditions in DynamoDB queries.\n * Only includes operators that are valid for key conditions.\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html#Query.KeyConditionExpressions AWS DynamoDB - Key Condition Expressions}\n *\n * @example\n * // Using with sort key conditions\n * table.query({\n * pk: \"USER#123\",\n * sk: op => op.beginsWith(\"ORDER#\")\n * })\n */\nexport type KeyConditionOperator = {\n /** Equals comparison for key attributes */\n eq: (value: unknown) => Condition;\n /** Less than comparison for key attributes */\n lt: (value: unknown) => Condition;\n /** Less than or equal comparison for key attributes */\n lte: (value: unknown) => Condition;\n /** Greater than comparison for key attributes */\n gt: (value: unknown) => Condition;\n /** Greater than or equal comparison for key attributes */\n gte: (value: unknown) => Condition;\n /** Between range comparison for key attributes */\n between: (lower: unknown, upper: unknown) => Condition;\n /** Begins with comparison for key attributes */\n beginsWith: (value: unknown) => Condition;\n /** Combines multiple key conditions with AND */\n and: (...conditions: Condition[]) => Condition;\n};\n\n/**\n * Type-safe operators for building conditions in DynamoDB operations.\n * Includes all available condition operators with proper type inference.\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.OperatorsAndFunctions.html AWS DynamoDB - Condition Expressions}\n *\n * @example\n * // Using with type-safe conditions\n * interface User {\n * status: string;\n * age: number;\n * email?: string;\n * }\n *\n * table.scan<User>()\n * .where(op => op.and(\n * op.eq(\"status\", \"ACTIVE\"),\n * op.gt(\"age\", 18),\n * op.attributeExists(\"email\")\n * ))\n *\n * @template T The type of the item being operated on\n */\nexport type ConditionOperator<T extends DynamoItem> = {\n eq: <K extends Path<T>>(attr: K, value: PathType<T, K>) => Condition;\n ne: <K extends Path<T>>(attr: K, value: PathType<T, K>) => Condition;\n lt: <K extends Path<T>>(attr: K, value: PathType<T, K>) => Condition;\n lte: <K extends Path<T>>(attr: K, value: PathType<T, K>) => Condition;\n gt: <K extends Path<T>>(attr: K, value: PathType<T, K>) => Condition;\n gte: <K extends Path<T>>(attr: K, value: PathType<T, K>) => Condition;\n between: <K extends Path<T>>(attr: K, lower: PathType<T, K>, upper: PathType<T, K>) => Condition;\n beginsWith: <K extends Path<T>>(attr: K, value: PathType<T, K>) => Condition;\n contains: <K extends Path<T>>(attr: K, value: PathType<T, K>) => Condition;\n attributeExists: <K extends Path<T>>(attr: K) => Condition;\n attributeNotExists: <K extends Path<T>>(attr: K) => Condition;\n and: (...conditions: Condition[]) => Condition;\n or: (...conditions: Condition[]) => Condition;\n not: (condition: Condition) => Condition;\n};\n\n/**\n * Primary key type for QUERY operations.\n * Allows building complex key conditions for the sort key.\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html AWS DynamoDB - Query Operations}\n *\n * @example\n * // Query items with a specific partition key and sort key prefix\n * table.query({\n * pk: \"USER#123\",\n * sk: op => op.beginsWith(\"ORDER#2023\")\n * })\n *\n * @example\n * // Query items within a specific sort key range\n * table.query({\n * pk: \"USER#123\",\n * sk: op => op.between(\"ORDER#2023-01\", \"ORDER#2023-12\")\n * })\n */\nexport type PrimaryKey = {\n /** Partition key value */\n pk: string;\n /** Optional sort key condition builder */\n sk?: (op: KeyConditionOperator) => Condition;\n};\n\n/**\n * Primary key type for GET and DELETE operations.\n * Used when you need to specify exact key values without conditions.\n * @see {@link https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html AWS DynamoDB - Working with Items}\n *\n * @example\n * // Get a specific item by its complete primary key\n * table.get({\n * pk: \"USER#123\",\n * sk: \"PROFILE#123\"\n * })\n *\n * @example\n * // Delete a specific item by its complete primary key\n * table.delete({\n * pk: \"USER#123\",\n * sk: \"ORDER#456\"\n * })\n */\nexport type PrimaryKeyWithoutExpression = {\n /** Partition key value */\n pk: string;\n /** Optional sort key value */\n sk?: string;\n};\n","import type { DeleteBuilder } from \"./builders/delete-builder\";\nimport type { GetBuilder } from \"./builders/get-builder\";\nimport type { PutBuilder } from \"./builders/put-builder\";\nimport type { ScanBuilder } from \"./builders/scan-builder\";\nimport type { UpdateBuilder } from \"./builders/update-builder\";\nimport type { StandardSchemaV1 } from \"./standard-schema\";\nimport type { Table } from \"./table\";\nimport type { DynamoItem, Index, TableConfig } from \"./types\";\nimport { eq, type PrimaryKey, type PrimaryKeyWithoutExpression } from \"./conditions\";\nimport type { QueryBuilder } from \"./builders/query-builder\";\n\n// Define the QueryFunction type with a generic return type\nexport type QueryFunction<T extends DynamoItem, I, R> = (input: I) => R;\n\n// Define a type for the query record that preserves the input type for each query function\nexport type QueryFunctionWithSchema<T extends DynamoItem, I, R> = QueryFunction<T, I, R> & {\n schema?: StandardSchemaV1<I>;\n};\n\nexport type QueryRecord<T extends DynamoItem> = {\n // biome-ignore lint/suspicious/noExplicitAny: This is for flexibility\n [K: string]: QueryFunctionWithSchema<T, any, ScanBuilder<T> | QueryBuilder<T, TableConfig> | GetBuilder<T>>;\n};\n\n// Define a type for entity with only scan, get and query methods\nexport type QueryEntity<T extends DynamoItem> = {\n scan: () => ScanBuilder<T>;\n get: (key: PrimaryKeyWithoutExpression) => GetBuilder<T>;\n query: (keyCondition: PrimaryKey) => QueryBuilder<T, TableConfig>;\n};\n\ninterface Settings {\n /**\n * Defaults to \"entityType\"\n */\n entityTypeAttributeName?: string;\n timestamps?: {\n createdAt?: {\n /**\n * ISO vs Unix trade-offs\n *\n * Both options support between, greater than and less than comparisons.\n *\n * ISO:\n * - Human readable, but requires more storage space\n * - Does not work with DynamoDBs TTL feature.\n *\n * UNIX:\n * - Less readable, but requires less storage space.\n * - Works with DynamoDBs TTL feature.\n */\n format: \"ISO\" | \"UNIX\";\n /**\n * Defaults to \"createdAt\"\n */\n attributeName?: string;\n };\n updatedAt?: {\n /**\n * ISO vs Unix trade-offs\n *\n * Both options support between, greater than and less than comparisons.\n *\n * ISO:\n * - Human readable, but requires more storage space\n * - Does not work with DynamoDBs TTL feature.\n *\n * UNIX:\n * - Less readable, but requires less storage space.\n * - Works with DynamoDBs TTL feature.\n */\n format: \"ISO\" | \"UNIX\";\n /**\n * Defaults to \"updatedAt\"\n */\n attributeName?: string;\n };\n };\n}\n\nexport interface EntityConfig<\n T extends DynamoItem,\n I extends DynamoItem = T,\n Q extends QueryRecord<T> = QueryRecord<T>,\n> {\n name: string;\n schema: StandardSchemaV1<T>;\n primaryKey: IndexDefinition<I>;\n indexes?: Record<string, Index>;\n queries: Q;\n settings?: Settings;\n}\n\nexport interface EntityRepository<\n /**\n * The Entity Type\n */\n T extends DynamoItem,\n /**\n * The Primary Index (Partition index) Type\n */\n I extends DynamoItem = T,\n /**\n * The Queries object\n */\n Q extends QueryRecord<T> = QueryRecord<T>,\n> {\n create: (data: T) => PutBuilder<T>;\n upsert: (data: T & I) => PutBuilder<T>;\n get: (key: I) => GetBuilder<T>;\n update: (key: I, data: Partial<T>) => UpdateBuilder<T>;\n delete: (key: I) => DeleteBuilder;\n query: Q;\n scan: () => ScanBuilder<T>;\n}\n\n/**\n * Creates an entity definition with type-safe operations\n *\n * @example\n * ```typescript\n * interface User {\n * id: string;\n * name: string;\n * }\n *\n * const UserEntity = defineEntity<User>({\n * name: \"User\",\n * schema: userSchema,\n * primaryKey: primaryKey,\n * });\n * ```\n */\nexport function defineEntity<T extends DynamoItem, I extends DynamoItem = T, Q extends QueryRecord<T> = QueryRecord<T>>(\n config: EntityConfig<T, I, Q>,\n) {\n const entityTypeAttributeName = config.settings?.entityTypeAttributeName ?? \"entityType\";\n\n /**\n * Generates an object containing timestamp attributes based on the given configuration settings.\n * The function determines the presence and format of \"createdAt\" and \"updatedAt\" timestamps dynamically.\n *\n * @returns {Record<string, string | number>} An object containing one or both of the \"createdAt\" and \"updatedAt\" timestamp attributes, depending on the configuration. Each timestamp can be formatted as either an ISO string or a UNIX timestamp.\n *\n * @throws Will not throw errors but depends on `config.settings?.timestamps` to be properly defined.\n * - If `createdAt` is configured, the function adds a timestamp using the attribute name specified in `config.settings.timestamps.createdAt.attributeName` or defaults to \"createdAt\".\n * - If `updatedAt` is configured, the function adds a timestamp using the attribute name specified in `config.settings.timestamps.updatedAt.attributeName` or defaults to \"updatedAt\".\n *\n * Configuration Details:\n * - `config.settings.timestamps.createdAt.format`: Determines the format of the \"createdAt\" timestamp. Accepts \"UNIX\" or defaults to ISO string.\n * - `config.settings.timestamps.updatedAt.format`: Determines the format of the \"updatedAt\" timestamp. Accepts \"UNIX\" or defaults to ISO string.\n *\n * The returned object keys and values depend on the provided configuration.\n */\n const generateTimestamps = (): Record<string, string | number> => {\n const timestamps: Record<string, string | number> = {};\n\n if (config.settings?.timestamps) {\n const now = new Date();\n\n if (config.settings.timestamps.createdAt) {\n const attributeName = config.settings.timestamps.createdAt.attributeName ?? \"createdAt\";\n timestamps[attributeName] =\n config.settings.timestamps.createdAt.format === \"UNIX\" ? Math.floor(Date.now() / 1000) : now.toISOString();\n }\n\n if (config.settings.timestamps.updatedAt) {\n const attributeName = config.settings.timestamps.updatedAt.attributeName ?? \"updatedAt\";\n timestamps[attributeName] =\n config.settings.timestamps.updatedAt.format === \"UNIX\" ? Math.floor(Date.now() / 1000) : now.toISOString();\n }\n }\n\n return timestamps;\n };\n\n return {\n name: config.name,\n createRepository: (table: Table): EntityRepository<T, I, Q> => {\n // Create a repository\n const repository = {\n create: (data: T) => {\n // We need to handle the async operations when the consumer calls execute\n const builder = table.create<T>({\n ...data,\n [entityTypeAttributeName]: config.name,\n ...generateTimestamps(),\n });\n\n // Wrap the builder's execute method to apply validation only\n const originalExecute = builder.execute;\n builder.execute = async () => {\n // Validate data against schema\n const validationResult = await config.schema[\"~standard\"].validate(data);\n if (\"issues\" in validationResult && validationResult.issues) {\n throw new Error(`Validation failed: ${validationResult.issues.map((i) => i.message).join(\", \")}`);\n }\n\n const primaryKey = config.primaryKey.generateKey(validationResult.value as unknown as I);\n\n const indexes = Object.entries(config.indexes ?? {}).reduce(\n (acc, [indexName, index]) => {\n const key = (index as IndexDefinition<T>).generateKey(validationResult.value);\n const gsiConfig = table.gsis[indexName];\n\n if (!gsiConfig) {\n throw new Error(`GSI configuration not found for index: ${indexName}`);\n }\n\n if (key.pk) {\n acc[gsiConfig.partitionKey] = key.pk;\n }\n if (key.sk && gsiConfig.sortKey) {\n acc[gsiConfig.sortKey] = key.sk;\n }\n return acc;\n },\n {} as Record<string, string>,\n );\n\n // Update the item in the builder with the validated data, entity type, and timestamps\n Object.assign(builder, {\n item: {\n ...validationResult.value,\n [entityTypeAttributeName]: config.name,\n [table.partitionKey]: primaryKey.pk,\n ...(table.sortKey ? { [table.sortKey]: primaryKey.sk } : {}),\n ...indexes,\n ...generateTimestamps(),\n },\n });\n\n // Execute the builder\n return await originalExecute.call(builder);\n };\n\n return builder;\n },\n\n upsert: (data: T & I) => {\n const primaryKey = config.primaryKey.generateKey(data);\n\n // We need to handle the async operations when the consumer calls execute\n const builder = table.put<T>({\n [table.partitionKey]: primaryKey.pk,\n ...(table.sortKey ? { [table.sortKey]: primaryKey.sk } : {}),\n ...data,\n [entityTypeAttributeName]: config.name,\n ...generateTimestamps(),\n });\n\n // Wrap the builder's execute method to apply validation only\n const originalExecute = builder.execute;\n builder.execute = async () => {\n // Validate data against schema\n const validationResult = await config.schema[\"~standard\"].validate(data);\n if (\"issues\" in validationResult && validationResult.issues) {\n throw new Error(`Validation failed: ${validationResult.issues.map((i) => i.message).join(\", \")}`);\n }\n\n // Update the item in the builder with the validated data, entity type, and timestamps\n Object.assign(builder, {\n item: {\n ...validationResult.value,\n [entityTypeAttributeName]: config.name,\n ...generateTimestamps(),\n },\n });\n\n // Execute the builder\n const result = await originalExecute.call(builder);\n if (!result) {\n throw new Error(\"Failed to upsert item\");\n }\n\n return result;\n };\n\n return builder;\n },\n\n get: <K extends I>(key: K) => {\n // Transform the input key into a PrimaryKeyWithoutExpression using the primary key definition\n const primaryKeyObj = config.primaryKey.generateKey(key);\n return table.get<T>(primaryKeyObj);\n },\n\n update: <K extends I>(key: K, data: Partial<T>) => {\n // Transform the input key into a PrimaryKeyWithoutExpression using the primary key definition\n const primaryKeyObj = config.primaryKey.generateKey(key);\n const builder = table.update<T>(primaryKeyObj);\n builder.condition(eq(entityTypeAttributeName, config.name));\n\n // Generate updatedAt timestamp if configured\n const timestamps: Record<string, string | number> = {};\n if (config.settings?.timestamps?.updatedAt) {\n const now = new Date();\n const attributeName = config.settings.timestamps.updatedAt.attributeName ?? \"updatedAt\";\n timestamps[attributeName] =\n config.settings.timestamps.updatedAt.format === \"UNIX\"\n ? Math.floor(Date.now() / 1000)\n : now.toISOString();\n }\n\n // Merge the data with timestamps\n builder.set({\n ...data,\n ...timestamps,\n });\n\n return builder;\n },\n\n delete: <K extends I>(key: K) => {\n // Transform the input key into a PrimaryKeyWithoutExpression using the primary key definition\n const primaryKeyObj = config.primaryKey.generateKey(key);\n const builder = table.delete(primaryKeyObj);\n builder.condition(eq(entityTypeAttributeName, config.name));\n return builder;\n },\n\n query: Object.entries(config.queries || {}).reduce((acc, [key, inputCallback]) => {\n // @ts-expect-error - We need to cast the queryFn to a function that takes an unknown input\n acc[key] = (input: unknown) => {\n // Create a QueryEntity object with only the necessary methods\n const queryEntity: QueryEntity<T> = {\n scan: repository.scan,\n get: (key: PrimaryKeyWithoutExpression) => table.get<T>(key),\n query: (keyCondition: PrimaryKey) => {\n return table.query<T>(keyCondition);\n },\n };\n\n // Execute the query function to get the builder - This type is incorrect and needs to be fixed\n const queryBuilderCallback = inputCallback(input);\n\n // Run the inner handler which allows the user to apply their desired contraints\n // to the query builder of their choice\n // @ts-expect-error - We need to cast the queryBuilderCallback to a function that takes a QueryEntity\n const builder = queryBuilderCallback(queryEntity);\n\n // Add entity type filter if the builder has filter method\n if (builder && typeof builder === \"object\" && \"filter\" in builder && typeof builder.filter === \"function\") {\n builder.filter(eq(entityTypeAttributeName, config.name));\n }\n\n // Wrap the builder's execute method if it exists\n if (builder && typeof builder === \"object\" && \"execute\" in builder) {\n const originalExecute = builder.execute;\n builder.execute = async () => {\n // Validate the input before executing the query\n const queryFn = (\n config.queries as unknown as Record<string, QueryFunctionWithSchema<T, I, typeof builder>>\n )[key];\n\n if (queryFn && typeof queryFn === \"function\") {\n // Get the schema from the query function\n const schema = queryFn.schema;\n if (schema?.[\"~standard\"]?.validate && typeof schema[\"~standard\"].validate === \"function\") {\n const validationResult = schema[\"~standard\"].validate(input);\n if (\"issues\" in validationResult && validationResult.issues) {\n throw new Error(\n `Validation failed: ${validationResult.issues.map((issue) => issue.message).join(\", \")}`,\n );\n }\n }\n }\n\n // Execute the original builder\n const result = await originalExecute.call(builder);\n if (!result) {\n throw new Error(\"Failed to execute query\");\n }\n return result;\n };\n }\n\n return builder;\n };\n return acc;\n }, {} as Q),\n\n scan: () => {\n const scanBuilder = table.scan<T>();\n scanBuilder.filter(eq(entityTypeAttributeName, config.name));\n\n return scanBuilder;\n },\n };\n\n return repository;\n },\n };\n}\n\nexport function createQueries<T extends DynamoItem>() {\n return {\n input: <I>(schema: StandardSchemaV1<I>) => ({\n query: <\n Q extends QueryRecord<T> = QueryRecord<T>,\n R = ScanBuilder<T> | QueryBuilder<T, TableConfig> | GetBuilder<T>,\n >(\n handler: (params: { input: I; entity: QueryEntity<T> }) => R,\n ) => {\n // Create a query function that conforms to QueryFunctionWithSchema type\n const queryFn = (input: I) => {\n // This function will be called by the repository later with the real queryEntity\n return (entity: QueryEntity<T>) => {\n return handler({ input, entity });\n };\n };\n\n // Attach the schema to the function for validation purposes\n queryFn.schema = schema;\n\n // Return the query function (this satisfies the QueryFunctionWithSchema type)\n return queryFn as unknown as QueryFunctionWithSchema<T, I, R>;\n },\n }),\n };\n}\n\nexport interface IndexDefinition<T extends DynamoItem> extends Index {\n name: string;\n generateKey: (item: T) => { pk: string; sk?: string };\n}\n\nexport function createIndex() {\n return {\n input: <T extends DynamoItem>(schema: StandardSchemaV1<T>) => ({\n partitionKey: <P extends (item: T) => string>(pkFn: P) => ({\n sortKey: <S extends (item: T) => string>(skFn: S) =>\n ({\n name: \"custom\",\n partitionKey: \"pk\",\n sortKey: \"sk\",\n generateKey: (item: T) => ({\n pk: pkFn(item),\n sk: skFn(item),\n }),\n }) as IndexDefinition<T>,\n\n // Allow creating an index with only a partition key\n withoutSortKey: () =>\n ({\n name: \"custom\",\n partitionKey: \"pk\",\n generateKey: (item: T) => ({\n pk: pkFn(item),\n }),\n }) as IndexDefinition<T>,\n }),\n }),\n };\n}\n"]}
@@ -0,0 +1,149 @@
1
+ import { DeleteBuilder } from './builders/delete-builder.cjs';
2
+ import { S as ScanBuilder, G as GetBuilder, T as Table } from './table-BEhBPy2G.cjs';
3
+ import { PutBuilder } from './builders/put-builder.cjs';
4
+ import { UpdateBuilder } from './builders/update-builder.cjs';
5
+ import { StandardSchemaV1 } from './standard-schema.cjs';
6
+ import { DynamoItem, TableConfig, Index } from './types.cjs';
7
+ import { P as PrimaryKeyWithoutExpression, a as PrimaryKey } from './conditions-ChhQWd6z.cjs';
8
+ import { Q as QueryBuilder } from './query-builder-D2FM9rsu.cjs';
9
+ import './builders/transaction-builder.cjs';
10
+ import '@aws-sdk/lib-dynamodb';
11
+ import './builder-types-DtwbqMeF.cjs';
12
+ import './builders/condition-check-builder.cjs';
13
+ import './builders/paginator.cjs';
14
+
15
+ type QueryFunction<T extends DynamoItem, I, R> = (input: I) => R;
16
+ type QueryFunctionWithSchema<T extends DynamoItem, I, R> = QueryFunction<T, I, R> & {
17
+ schema?: StandardSchemaV1<I>;
18
+ };
19
+ type QueryRecord<T extends DynamoItem> = {
20
+ [K: string]: QueryFunctionWithSchema<T, any, ScanBuilder<T> | QueryBuilder<T, TableConfig> | GetBuilder<T>>;
21
+ };
22
+ type QueryEntity<T extends DynamoItem> = {
23
+ scan: () => ScanBuilder<T>;
24
+ get: (key: PrimaryKeyWithoutExpression) => GetBuilder<T>;
25
+ query: (keyCondition: PrimaryKey) => QueryBuilder<T, TableConfig>;
26
+ };
27
+ interface Settings {
28
+ /**
29
+ * Defaults to "entityType"
30
+ */
31
+ entityTypeAttributeName?: string;
32
+ timestamps?: {
33
+ createdAt?: {
34
+ /**
35
+ * ISO vs Unix trade-offs
36
+ *
37
+ * Both options support between, greater than and less than comparisons.
38
+ *
39
+ * ISO:
40
+ * - Human readable, but requires more storage space
41
+ * - Does not work with DynamoDBs TTL feature.
42
+ *
43
+ * UNIX:
44
+ * - Less readable, but requires less storage space.
45
+ * - Works with DynamoDBs TTL feature.
46
+ */
47
+ format: "ISO" | "UNIX";
48
+ /**
49
+ * Defaults to "createdAt"
50
+ */
51
+ attributeName?: string;
52
+ };
53
+ updatedAt?: {
54
+ /**
55
+ * ISO vs Unix trade-offs
56
+ *
57
+ * Both options support between, greater than and less than comparisons.
58
+ *
59
+ * ISO:
60
+ * - Human readable, but requires more storage space
61
+ * - Does not work with DynamoDBs TTL feature.
62
+ *
63
+ * UNIX:
64
+ * - Less readable, but requires less storage space.
65
+ * - Works with DynamoDBs TTL feature.
66
+ */
67
+ format: "ISO" | "UNIX";
68
+ /**
69
+ * Defaults to "updatedAt"
70
+ */
71
+ attributeName?: string;
72
+ };
73
+ };
74
+ }
75
+ interface EntityConfig<T extends DynamoItem, I extends DynamoItem = T, Q extends QueryRecord<T> = QueryRecord<T>> {
76
+ name: string;
77
+ schema: StandardSchemaV1<T>;
78
+ primaryKey: IndexDefinition<I>;
79
+ indexes?: Record<string, Index>;
80
+ queries: Q;
81
+ settings?: Settings;
82
+ }
83
+ interface EntityRepository<
84
+ /**
85
+ * The Entity Type
86
+ */
87
+ T extends DynamoItem,
88
+ /**
89
+ * The Primary Index (Partition index) Type
90
+ */
91
+ I extends DynamoItem = T,
92
+ /**
93
+ * The Queries object
94
+ */
95
+ Q extends QueryRecord<T> = QueryRecord<T>> {
96
+ create: (data: T) => PutBuilder<T>;
97
+ upsert: (data: T & I) => PutBuilder<T>;
98
+ get: (key: I) => GetBuilder<T>;
99
+ update: (key: I, data: Partial<T>) => UpdateBuilder<T>;
100
+ delete: (key: I) => DeleteBuilder;
101
+ query: Q;
102
+ scan: () => ScanBuilder<T>;
103
+ }
104
+ /**
105
+ * Creates an entity definition with type-safe operations
106
+ *
107
+ * @example
108
+ * ```typescript
109
+ * interface User {
110
+ * id: string;
111
+ * name: string;
112
+ * }
113
+ *
114
+ * const UserEntity = defineEntity<User>({
115
+ * name: "User",
116
+ * schema: userSchema,
117
+ * primaryKey: primaryKey,
118
+ * });
119
+ * ```
120
+ */
121
+ declare function defineEntity<T extends DynamoItem, I extends DynamoItem = T, Q extends QueryRecord<T> = QueryRecord<T>>(config: EntityConfig<T, I, Q>): {
122
+ name: string;
123
+ createRepository: (table: Table) => EntityRepository<T, I, Q>;
124
+ };
125
+ declare function createQueries<T extends DynamoItem>(): {
126
+ input: <I>(schema: StandardSchemaV1<I>) => {
127
+ query: <Q extends QueryRecord<T> = QueryRecord<T>, R = ScanBuilder<T, TableConfig> | QueryBuilder<T, TableConfig> | GetBuilder<T>>(handler: (params: {
128
+ input: I;
129
+ entity: QueryEntity<T>;
130
+ }) => R) => QueryFunctionWithSchema<T, I, R>;
131
+ };
132
+ };
133
+ interface IndexDefinition<T extends DynamoItem> extends Index {
134
+ name: string;
135
+ generateKey: (item: T) => {
136
+ pk: string;
137
+ sk?: string;
138
+ };
139
+ }
140
+ declare function createIndex(): {
141
+ input: <T extends DynamoItem>(schema: StandardSchemaV1<T>) => {
142
+ partitionKey: <P extends (item: T) => string>(pkFn: P) => {
143
+ sortKey: <S extends (item: T) => string>(skFn: S) => IndexDefinition<T>;
144
+ withoutSortKey: () => IndexDefinition<T>;
145
+ };
146
+ };
147
+ };
148
+
149
+ export { type EntityConfig, type EntityRepository, type IndexDefinition, type QueryEntity, type QueryFunction, type QueryFunctionWithSchema, type QueryRecord, createIndex, createQueries, defineEntity };