@aurios/mizzle 1.1.2 → 1.1.4

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 (116) hide show
  1. package/.turbo/turbo-build.log +37 -0
  2. package/LICENSE +21 -0
  3. package/README.md +166 -57
  4. package/dist/chunk-AQVECMXP.js +1 -0
  5. package/dist/chunk-DU7UPWBW.js +1 -0
  6. package/dist/chunk-GPYZK4WY.js +1 -0
  7. package/dist/chunk-NPPZW6VT.js +1 -0
  8. package/dist/chunk-TOYV2M4M.js +1 -0
  9. package/dist/chunk-UM3YF5EC.js +1 -0
  10. package/dist/columns.d.ts +1 -0
  11. package/dist/columns.js +1 -0
  12. package/dist/db-zHIHBm1E.d.ts +815 -0
  13. package/dist/db.d.ts +3 -0
  14. package/dist/db.js +1 -0
  15. package/dist/diff.d.ts +18 -0
  16. package/dist/diff.js +1 -0
  17. package/dist/index.d.ts +42 -0
  18. package/dist/index.js +1 -0
  19. package/dist/introspection.d.ts +7 -0
  20. package/dist/introspection.js +1 -0
  21. package/dist/operators-BVreW0ky.d.ts +719 -0
  22. package/dist/snapshot.d.ts +24 -0
  23. package/dist/snapshot.js +1 -0
  24. package/dist/table.d.ts +1 -0
  25. package/dist/table.js +1 -0
  26. package/dist/transaction-RE7LXTGV.js +1 -0
  27. package/package.json +82 -66
  28. package/src/builders/base.ts +53 -56
  29. package/src/builders/batch-get.ts +63 -58
  30. package/src/builders/batch-write.ts +81 -78
  31. package/src/builders/delete.ts +46 -53
  32. package/src/builders/insert.ts +158 -150
  33. package/src/builders/query-promise.ts +26 -35
  34. package/src/builders/relational-builder.ts +214 -191
  35. package/src/builders/select.ts +250 -237
  36. package/src/builders/transaction.ts +170 -152
  37. package/src/builders/update.ts +197 -192
  38. package/src/columns/binary-set.ts +29 -38
  39. package/src/columns/binary.ts +25 -35
  40. package/src/columns/boolean.ts +25 -30
  41. package/src/columns/date.ts +57 -64
  42. package/src/columns/index.ts +15 -15
  43. package/src/columns/json.ts +39 -48
  44. package/src/columns/list.ts +26 -36
  45. package/src/columns/map.ts +26 -34
  46. package/src/columns/number-set.ts +29 -38
  47. package/src/columns/number.ts +33 -40
  48. package/src/columns/string-set.ts +38 -47
  49. package/src/columns/string.ts +37 -49
  50. package/src/columns/uuid.ts +26 -33
  51. package/src/core/client.ts +9 -9
  52. package/src/core/column-builder.ts +194 -220
  53. package/src/core/column.ts +127 -135
  54. package/src/core/diff.ts +40 -34
  55. package/src/core/errors.ts +20 -17
  56. package/src/core/introspection.ts +62 -58
  57. package/src/core/operations.ts +17 -23
  58. package/src/core/parser.ts +82 -89
  59. package/src/core/relations.ts +164 -154
  60. package/src/core/retry.ts +52 -52
  61. package/src/core/snapshot.ts +131 -130
  62. package/src/core/strategies.ts +222 -218
  63. package/src/core/table.ts +189 -202
  64. package/src/core/validation.ts +52 -52
  65. package/src/db.ts +211 -209
  66. package/src/expressions/actions.ts +26 -26
  67. package/src/expressions/builder.ts +62 -54
  68. package/src/expressions/operators.ts +48 -48
  69. package/src/expressions/update-builder.ts +78 -76
  70. package/src/index.ts +1 -1
  71. package/src/indexes.ts +8 -8
  72. package/test/batch-resilience.test.ts +138 -0
  73. package/test/builders/delete.test.ts +100 -0
  74. package/test/builders/insert.test.ts +216 -0
  75. package/test/builders/relational-types.test.ts +55 -0
  76. package/test/builders/relational.integration.test.ts +291 -0
  77. package/test/builders/relational.test.ts +66 -0
  78. package/test/builders/select.test.ts +411 -0
  79. package/test/builders/transaction-errors.test.ts +46 -0
  80. package/test/builders/transaction-execution.test.ts +99 -0
  81. package/test/builders/transaction-proxy.test.ts +41 -0
  82. package/test/builders/update-expression.test.ts +106 -0
  83. package/test/builders/update.test.ts +179 -0
  84. package/test/core/diff.test.ts +152 -0
  85. package/test/core/expressions.test.ts +64 -0
  86. package/test/core/introspection.test.ts +47 -0
  87. package/test/core/parser.test.ts +69 -0
  88. package/test/core/snapshot-gen.test.ts +155 -0
  89. package/test/core/snapshot.test.ts +52 -0
  90. package/test/date-column.test.ts +159 -0
  91. package/test/fluent-writes.integration.test.ts +148 -0
  92. package/test/integration-retry.test.ts +77 -0
  93. package/test/integration.test.ts +105 -0
  94. package/test/item-size-error.test.ts +16 -0
  95. package/test/item-size-validation.test.ts +82 -0
  96. package/test/item-size.test.ts +47 -0
  97. package/test/iterator-pagination.integration.test.ts +132 -0
  98. package/test/jsdoc-builders.test.ts +55 -0
  99. package/test/jsdoc-schema.test.ts +107 -0
  100. package/test/json-column.test.ts +51 -0
  101. package/test/metadata.test.ts +54 -0
  102. package/test/mizzle-package.test.ts +20 -0
  103. package/test/relational-centralized.test.ts +83 -0
  104. package/test/relational-definition.test.ts +75 -0
  105. package/test/relational-init.test.ts +30 -0
  106. package/test/relational-proxy.test.ts +52 -0
  107. package/test/relations.test.ts +45 -0
  108. package/test/resilience-config.test.ts +34 -0
  109. package/test/retry-handler.test.ts +63 -0
  110. package/test/transaction.integration.test.ts +153 -0
  111. package/test/unified-select.integration.test.ts +153 -0
  112. package/test/unified-update.integration.test.ts +139 -0
  113. package/test/update.integration.test.ts +132 -0
  114. package/tsconfig.json +12 -8
  115. package/tsup.config.ts +11 -11
  116. package/vitest.config.ts +8 -0
@@ -0,0 +1,37 @@
1
+
2
+ > @aurios/mizzle@1.1.4 build /home/runner/work/mizzle/mizzle/packages/mizzle
3
+ > tsup
4
+
5
+ CLI Building entry: {"index":"src/index.ts","columns":"src/columns/index.ts","table":"src/core/table.ts","snapshot":"src/core/snapshot.ts","diff":"src/core/diff.ts","introspection":"src/core/introspection.ts","db":"src/db.ts"}
6
+ CLI Using tsconfig: tsconfig.json
7
+ CLI tsup v8.5.1
8
+ CLI Using tsup config: /home/runner/work/mizzle/mizzle/packages/mizzle/tsup.config.ts
9
+ CLI Target: esnext
10
+ CLI Cleaning output folder
11
+ ESM Build start
12
+ ESM dist/index.js 2.32 KB
13
+ ESM dist/columns.js 299.00 B
14
+ ESM dist/snapshot.js 193.00 B
15
+ ESM dist/table.js 144.00 B
16
+ ESM dist/chunk-TOYV2M4M.js 866.00 B
17
+ ESM dist/diff.js 147.00 B
18
+ ESM dist/introspection.js 1.47 KB
19
+ ESM dist/chunk-AQVECMXP.js 2.38 KB
20
+ ESM dist/db.js 166.00 B
21
+ ESM dist/transaction-RE7LXTGV.js 193.00 B
22
+ ESM dist/chunk-NPPZW6VT.js 9.59 KB
23
+ ESM dist/chunk-UM3YF5EC.js 15.21 KB
24
+ ESM dist/chunk-GPYZK4WY.js 1.12 KB
25
+ ESM dist/chunk-DU7UPWBW.js 5.17 KB
26
+ ESM ⚡️ Build success in 45ms
27
+ DTS Build start
28
+ DTS ⚡️ Build success in 3819ms
29
+ DTS dist/index.d.ts 3.84 KB
30
+ DTS dist/diff.d.ts 485.00 B
31
+ DTS dist/introspection.d.ts 258.00 B
32
+ DTS dist/snapshot.d.ts 1.05 KB
33
+ DTS dist/db.d.ts 169.00 B
34
+ DTS dist/columns.d.ts 250.00 B
35
+ DTS dist/table.d.ts 403.00 B
36
+ DTS dist/db-zHIHBm1E.d.ts 31.72 KB
37
+ DTS dist/operators-BVreW0ky.d.ts 29.24 KB
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lucas A. Ouverney
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,57 +1,166 @@
1
- # @aurios/mizzle
2
-
3
- A Drizzle-like ORM for DynamoDB. Mizzle provides a type-safe, fluent API for interacting with DynamoDB, supporting relational queries, batch operations, and transactions.
4
-
5
- ## Installation
6
-
7
- ```bash
8
- npm install @aurios/mizzle
9
- # or
10
- bun add @aurios/mizzle
11
- ```
12
-
13
- ## Usage
14
-
15
- ### Initialization
16
-
17
- ```ts
18
- import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
19
- import { mizzle } from "@aurios/mizzle";
20
-
21
- const client = new DynamoDBClient({});
22
- const db = mizzle(client);
23
- ```
24
-
25
- ### Key Features
26
-
27
- - **Type-Safe Schema Definition**: Define your tables and entities with strict TypeScript types.
28
- - **Fluent Query Builder**: precise API for `insert`, `select`, `update`, and `delete` operations.
29
- - **Relational Queries**: Query related entities with `db.query`.
30
- - **Batch Operations**: `batchGet` and `batchWrite` support.
31
- - **Transactions**: Atomic operations using `db.transaction`.
32
- - **Automatic Type Inference**: `InferSelectModel` and `InferInsertModel` utilities.
33
-
34
- ### Example
35
-
36
- ```ts
37
- // Define your schema (simplified)
38
- import { dynamoTable, dynamoEntity, string } from "@aurios/mizzle";
39
-
40
- const myTable = dynamoTable("my-app-table", {
41
- pk: string("pk"),
42
- sk: string("sk"),
43
- });
44
-
45
- const users = dynamoEntity(myTable, "users", {
46
- id: string("id"),
47
- name: string("name"),
48
- email: string("email"),
49
- });
50
-
51
- // Query
52
- const result = await db.select().from(users).where(eq(users.id, "123")).execute();
53
- ```
54
-
55
- ## License
56
-
57
- MIT
1
+ # 🌧️ mizzle
2
+
3
+ ![NPM Last Update](https://img.shields.io/npm/last-update/%40aurios%2Fmizzle?style=flat&color=0EA5E9)
4
+ ![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/realfakenerd/mizzle/release.yml?style=flat&color=0EA5E9)
5
+ ![GitHub License](https://img.shields.io/github/license/realfakenerd/mizzle?style=flat&color=0EA5E9)
6
+
7
+ ![NPM Downloads](https://img.shields.io/npm/dw/%40aurios%2Fmizzle?style=flat&color=0EA5E9)
8
+ A Drizzle-like ORM for DynamoDB. Mizzle provides a type-safe, fluent API for interacting with DynamoDB, supporting relational queries, batch operations, and transactions.
9
+
10
+ ## Key Features
11
+
12
+ - **Type-Safe Schema Definition**: Define your tables and entities with strict TypeScript types.
13
+ - **Fluent Query Builder**: precise API for `insert`, `select`, `update`, and `delete` operations.
14
+ - **Relational Queries**: Query related entities with `db.query`.
15
+ - **Batch Operations**: `batchGet` and `batchWrite` support.
16
+ - **Transactions**: Atomic operations using `db.transaction`.
17
+ - **Automatic Type Inference**: `InferSelectModel` and `InferInsertModel` utilities.
18
+
19
+ > Skip this with the [way less boring docs](https://mizzle-docs.vercel.app)
20
+
21
+ ## 🚀 Installation
22
+
23
+ ```bash
24
+ npm install @aurios/mizzle
25
+ # or
26
+ bun add @aurios/mizzle
27
+ ```
28
+
29
+ ## Get Started
30
+
31
+ ### Defining the Table
32
+
33
+ In DynamoDB, you first need a physical table. Mizzle separates the definition of the physical table structure (PK, SK, Indexes) from the logical entities that live within it and with this making your database well organized and easier to reason about.
34
+
35
+ ```ts
36
+ import { dynamoTable, string } from "@aurios/mizzle";
37
+
38
+ // This matches your actual DynamoDB table configuration
39
+ export const myTable = dynamoTable("JediOrder", {
40
+ pk: string("pk"), // The partition key attribute name
41
+ sk: string("sk"), // The sort key attribute name (optional)
42
+ });
43
+ ```
44
+
45
+ ### Defining the Entity
46
+
47
+ An Entity represents your data model (e.g., an user, an item on an user). You map the Entity to a Physical Table and define how its keys are generated, so every entity looks kinda like an separated table.
48
+
49
+ ```ts
50
+ import { dynamoEntity, string, uuid, number, enum, date, prefixKey, staticKey } from "@aurios/mizzle";
51
+
52
+ export const jedi = dynamoEntity(
53
+ myTable,
54
+ "Jedi",
55
+ {
56
+ id: uuid(), // Automatically generates a v7 UUID
57
+ name: string(),
58
+ homeworld: string()
59
+ },
60
+ (cols) => ({
61
+ // PK will look like "JEDI#<uuid>"
62
+ pk: prefixKey("JEDI#", cols.id),
63
+ // SK will be a static string "PROFILE"
64
+ sk: staticKey("PROFILE"),
65
+ }),
66
+ );
67
+
68
+ export const jediRank = dynamoEntity(
69
+ myTable,
70
+ 'JediRank',
71
+ {
72
+ jediId: uuid(),
73
+ position: string().default('initiate'),
74
+ joinedCouncilDate: string(),
75
+ },
76
+ (cols) => ({
77
+ // Same as the jedi so they can be related
78
+ pk: prefixKey('JEDI#', cols.jediId),
79
+ // RANK#initiate
80
+ sk: prefixKey('RANK#', cols.position),
81
+ })
82
+ )
83
+ ```
84
+
85
+ > The UUID V7 was chosen for better sorting, since the values are time-sortable with 1 millisecond precision.
86
+
87
+ ### Define the Relations
88
+
89
+ Relationships in Mizzle are established using the defineRelations function. This step creates a logical map of how your entities interact, enabling you to perform powerful relational queries—such as fetching a Jedi along with their entire rank history—in a single operation.
90
+
91
+ ```ts
92
+ import { defineRelations } from "@aurios/mizzle";
93
+ import * as schema from "./schema";
94
+
95
+ export const relations = defineRelations(schema, (r) => ({
96
+ jedi: {
97
+ // A Jedi could've a lot of ranks throughout his year
98
+ ranks: r.many.jediRank({
99
+ fields: [r.jedi.id],
100
+ references: [r.jediRank.jediId],
101
+ }),
102
+ },
103
+ jediRank: {
104
+ // Every registry points to one Jedi only
105
+ member: r.one.jedi({
106
+ fields: [r.jediRank.jediId],
107
+ references: [r.jedi.id],
108
+ }),
109
+ },
110
+ }));
111
+ ```
112
+
113
+ ### Initialization
114
+
115
+ Initialize the mizzle client by passing it an instance of the standard AWS DynamoDBClient and the relations we just defined.
116
+
117
+ ```ts
118
+ import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
119
+ import { mizzle } from "@aurios/mizzle";
120
+ import { relations } from "./relations";
121
+
122
+ const client = new DynamoDBClient({ region: "us-east-1" });
123
+ export const db = mizzle({ client, relations });
124
+ ```
125
+
126
+ ### Query
127
+
128
+ Now you can use the fluent API to interact with your data in the best way possible.
129
+
130
+ #### Insert Data
131
+
132
+ ```typescript
133
+ // api/jedi/new.ts
134
+ import { jedi } from "$lib/schema.ts";
135
+
136
+ const newJedi = await db
137
+ .insert(jedi)
138
+ .values({
139
+ name: "Luke Skywalker",
140
+ homeworld: "Tatooine",
141
+ })
142
+ .returning();
143
+
144
+ console.log(newJedi.id); // The auto-generated UUID
145
+ ```
146
+
147
+ #### Select Data
148
+
149
+ Mizzle intelligently routes your request to `GetItem`, `Query`, or `Scan` based on the filters you provide.
150
+
151
+ ```typescript
152
+ // /api/jedi/get.ts
153
+ import { jedi } from "$lib/schema.ts";
154
+ import { eq } from "@aurios/mizzle";
155
+
156
+ // This will use GetItem because both PK and SK are fully resolved
157
+ const user = await db.select().from(jedi).where(eq(jedi.id, "some-uuid")).execute();
158
+ ```
159
+
160
+ ## Mizzling
161
+
162
+ This will work if you already has a DynamoDB table with data in it. If you want to create a new table with the schema you defined, you can use the [`mizzling`](https://www.npmjs.com/package/@aurios/mizzling) CLI.
163
+
164
+ ## 📄 License
165
+
166
+ This project is licensed under the MIT License.
@@ -0,0 +1 @@
1
+ import{d as l,e as d}from"./chunk-DU7UPWBW.js";import{join as g}from"path";import{writeFile as E,readFile as I,mkdir as k,readdir as L}from"fs/promises";import{existsSync as h}from"fs";var A="snapshot.json";async function G(e,t){h(e)||await k(e,{recursive:!0});let n=g(e,A);await E(n,JSON.stringify(t,null,2),"utf-8")}async function v(e){let t=g(e,A);if(!h(t))return null;let n=await I(t,"utf-8");return JSON.parse(n)}function B(e){let t={};for(let n of e.tables){let o=e.entities.filter(a=>a[d.PHYSICAL_TABLE]===n),s=K(n,o);t[s.TableName]=s}return{version:"1",tables:t}}async function H(e){if(!h(e))return"0000";let t=await L(e),n=-1;for(let o of t){if(!o.endsWith(".ts"))continue;let s=o.match(/^(\d{4})_/);if(s){let a=parseInt(s[1],10);a>n&&(n=a)}}return n===-1?"0000":(n+1).toString().padStart(4,"0")}function K(e,t){let n=e[l.TABLE_NAME],o=new Map,s=e[l.PARTITION_KEY];o.set(s.name,s.getDynamoType());let a=e[l.SORT_KEY];a&&o.set(a.name,a.getDynamoType());let m=[{AttributeName:s.name,KeyType:"HASH"}];a&&m.push({AttributeName:a.name,KeyType:"RANGE"});let p=[],f=[],N=e[l.INDEXES]||{};for(let[r,c]of Object.entries(N)){let b=c.type,i=c.config;if(b==="gsi"){if(i.pk){let y=T(i.pk,e,t);o.set(i.pk,y)}if(i.sk){let y=T(i.sk,e,t);o.set(i.sk,y)}let u={IndexName:r,KeySchema:[{AttributeName:i.pk,KeyType:"HASH"}],Projection:{ProjectionType:"ALL"}};i.sk&&u.KeySchema.push({AttributeName:i.sk,KeyType:"RANGE"}),p.push(u)}else if(b==="lsi"){if(i.sk){let y=T(i.sk,e,t);o.set(i.sk,y)}let u={IndexName:r,KeySchema:[{AttributeName:s.name,KeyType:"HASH"},{AttributeName:i.sk,KeyType:"RANGE"}],Projection:{ProjectionType:"ALL"}};f.push(u)}}let x=Array.from(o.entries()).map(([r,c])=>({AttributeName:r,AttributeType:c})).sort((r,c)=>r.AttributeName.localeCompare(c.AttributeName));p.sort((r,c)=>(r.IndexName||"").localeCompare(c.IndexName||"")),f.sort((r,c)=>(r.IndexName||"").localeCompare(c.IndexName||""));let S={TableName:n,AttributeDefinitions:x,KeySchema:m};return p.length>0&&(S.GlobalSecondaryIndexes=p),f.length>0&&(S.LocalSecondaryIndexes=f),S}function T(e,t,n){let o=t[l.PARTITION_KEY];if(o.name===e)return o.getDynamoType();let s=t[l.SORT_KEY];if(s&&s.name===e)return s.getDynamoType();for(let a of n){let m=a[d.COLUMNS];if(m){let p=m[e];if(p)return p.getDynamoType()}}throw new Error(`Could not resolve type for column '${e}' in table '${t[l.TABLE_NAME]}'. Ensure it is defined in an Entity.`)}export{G as a,v as b,B as c,H as d};
@@ -0,0 +1 @@
1
+ var W={QUERY:"query",RAW:"raw"},V={ASC:"asc",DESC:"desc"},J={FIRST:"first",LAST:"last"},v={COLUMNS:Symbol.for("mizzle:Columns"),INDEXES:Symbol.for("mizzle:Indexes"),SORT_KEY:Symbol.for("mizzle:SortKey"),TABLE_NAME:Symbol.for("mizzle:TableName"),PARTITION_KEY:Symbol.for("mizzle:PartitionKey")},s={ENTITY_NAME:Symbol.for("mizzle:EntityName"),ENTITY_STRATEGY:Symbol.for("mizzle:EntityStrategy"),PHYSICAL_TABLE:Symbol.for("mizzle:PhysicalTable"),COLUMNS:Symbol.for("mizzle:Columns"),ENTITY_KIND:Symbol.for("mizzle:EntityKind")},Q={RELATION_CONFIG:Symbol.for("mizzle:RelationConfig")};function ee(n){return n[s.COLUMNS]}function ne(n){return n[s.PHYSICAL_TABLE][v.TABLE_NAME]}function te(n,e){let a=n[s.COLUMNS]||{},r={};for(let[i,$]of Object.entries(a))e[$.name]!==void 0?r[i]=e[$.name]:e[i]!==void 0&&(r[i]=e[i]);return e.pk&&!Object.values(a).some(i=>i.name==="pk")&&(r.pk=e.pk),e.sk&&!Object.values(a).some(i=>i.name==="sk")&&(r.sk=e.sk),r}var t=class{constructor(e,a){this.table=e;this.config=a,this.name=a.name,this.primary=a.partitionKey,this.notNull=a.notNull,this.default=a.default,this.defaultFn=a.defaultFn,this.onUpdateFn=a.onUpdateFn,this.hasDefault=a.hasDefault,this.dataType=a.dataType,this.columnType=a.columnType}name;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;dataType;columnType;config;getDynamoType(){return this.columnType}mapFromDynamoValue(e){return e}mapToDynamoValue(e){return e}};var o=class{config;constructor(e,a,r){this.config={name:e,dataType:a,columnType:r,notNull:!1,default:void 0,hasDefault:!1,isPartitionKey:!1,isSortKey:!1}}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$type(){return this}getConfig(){return this.config}partitionKey(){return this.config.isPartitionKey=!0,this.config.notNull=!1,this}sortKey(){return this.config.isSortKey=!0,this.config.notNull=!1,this}notNull(){return this.config.notNull=!0,this}setName(e){this.config.name===""&&(this.config.name=e)}};var l=class extends o{constructor(e){super(e,"binary","B")}build(e){return new u(e,this.config)}},u=class extends t{};function m(n){return new l(n??"")}var T=class extends o{constructor(e){super(e,"binarySet","BS")}build(e){return new p(e,this.config)}},p=class extends t{};function f(n){return new T(n??"")}var d=class extends o{constructor(e){super(e,"boolean","BOOL")}build(e){return new C(e,this.config)}},C=class extends t{};function y(n){return new d(n??"")}var g=class extends o{constructor(e){super(e,"date","S")}defaultNow(){return this.$defaultFn(()=>new Date)}onUpdateNow(){return this.$onUpdateFn(()=>new Date)}build(e){return new x(e,this.config)}},x=class extends t{mapToDynamoValue(e){if(e==null)return e;let a;if(e instanceof Date)a=e;else if(typeof e=="string"||typeof e=="number")a=new Date(e);else throw new Error(`Invalid date value: ${e}`);if(Number.isNaN(a.getTime()))throw new Error(`Invalid date value: ${e}`);return a.toISOString()}mapFromDynamoValue(e){return typeof e=="string"?new Date(e):e}};function c(n){return new g(n??"")}var b=class extends o{constructor(e){super(e,"array","L")}build(e){return new N(e,this.config)}},N=class extends t{};function B(n){return new b(n??"")}var S=class extends o{constructor(e){super(e,"map","M")}build(e){return new h(e,this.config)}},h=class extends t{};function D(n){return new S(n??"")}var M=class extends o{constructor(e){super(e,"number","N")}min(e){return this.config.validators??={},this.config.validators.min=e,this}max(e){return this.config.validators??={},this.config.validators.max=e,this}build(e){return new I(e,this.config)}},I=class extends t{};function k(n){return new M(n??"")}var E=class extends o{constructor(e){super(e,"numberSet","NS")}build(e){return new L(e,this.config)}},L=class extends t{};function R(n){return new E(n??"")}var A=class extends o{constructor(e){super(e,"string","S")}length(e){return this.config.validators??={},this.config.validators.length=e,this}email(){return this.config.validators??={},this.config.validators.email=!0,this}build(e){return new K(e,this.config)}},K=class extends t{};function U(n){return new A(n??"")}var _=class extends o{constructor(e){super(e,"string","SS")}default(e){let a=e instanceof Set?e:new Set(e);return this.config.default=a,this.config.hasDefault=!0,this}build(e){return new w(e,this.config)}},w=class extends t{};function O(n){return new _(n??"")}import{v7 as q}from"uuid";var G=()=>q(),j=class extends o{constructor(e){super(e,"string","S"),this.config.defaultFn=G}build(e){return new F(e,this.config)}},F=class extends t{};function H(n){return new j(n??"")}var Y=class extends o{constructor(e){super(e,"json","S")}build(e){return new P(e,this.config)}},P=class extends t{mapToDynamoValue(e){return JSON.stringify(e)}mapFromDynamoValue(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}};function z(n){return new Y(n??"")}function un(){return{binary:m,binarySet:f,boolean:y,date:c,json:z,list:B,map:D,number:k,numberSet:R,string:U,stringSet:O,uuid:H}}export{W as a,V as b,J as c,v as d,s as e,Q as f,ee as g,ne as h,te as i,t as j,m as k,f as l,y as m,c as n,B as o,D as p,k as q,R as r,U as s,O as t,H as u,z as v,un as w};
@@ -0,0 +1 @@
1
+ import{d as l,e,j as T,w as c}from"./chunk-DU7UPWBW.js";var y=class{[l.TABLE_NAME]="";[l.INDEXES]=void 0;[l.PARTITION_KEY]={};[l.SORT_KEY]=void 0;static Symbol=l;constructor(s,n){this[l.TABLE_NAME]=s,this[l.PARTITION_KEY]=n.pk.build(this),this[l.SORT_KEY]=n.sk?n.sk.build(this):void 0,this[l.INDEXES]=n.indexes}},C=class{[e.ENTITY_NAME]="";[e.PHYSICAL_TABLE]={};[e.COLUMNS]={};[e.ENTITY_STRATEGY]={};static Symbol=e;constructor(s,n,r,m){this[e.ENTITY_NAME]=s,this[e.PHYSICAL_TABLE]=n,this[e.COLUMNS]=r,this[e.ENTITY_STRATEGY]=m}};function S(i,s,n,r){let m=typeof n=="function"?n(c()):n,u=Object.fromEntries(Object.entries(m).map(([a,t])=>{let o=t;o.setName(a);let g=o.build({});return[a,g]})),p=r?r(u):{},d={};for(let[a,t]of Object.entries(p))if(t instanceof T)d[a]={type:"prefix",segments:["",t]};else if(t&&typeof t=="object"&&!("type"in t&&"segments"in t)){let o={...t};o.pk instanceof T&&(o.pk={type:"prefix",segments:["",o.pk]}),o.sk instanceof T&&(o.sk={type:"prefix",segments:["",o.sk]}),d[a]=o}else d[a]=t;let f=new C(s,i,{},d);return f[e.COLUMNS]=u,Object.assign(f,u)}function M(i,s){return new y(i,s)}export{y as a,C as b,S as c,M as d};
@@ -0,0 +1 @@
1
+ import{D as Q,E as U,I as L,J as w,K as H,L as $,N as J,P as X,Q as Z,S as ee,e as P,p as q,q as G,r as z}from"./chunk-UM3YF5EC.js";import{b as D}from"./chunk-GPYZK4WY.js";import{d as E,e as d,f as k,i as v}from"./chunk-DU7UPWBW.js";import{DynamoDBClient as ne}from"@aws-sdk/client-dynamodb";import{DynamoDBDocumentClient as le}from"@aws-sdk/lib-dynamodb";import{GetCommand as ie,QueryCommand as se,ScanCommand as oe}from"@aws-sdk/lib-dynamodb";var O=class{constructor(t,e){this.client=t;this.fields=e}from(t){return new I(t,this.client,this.fields)}},I=class extends w{constructor(e,i,n){super(e,i);this.fields=n}static[d.ENTITY_KIND]="SelectBase";_whereClause;_limitVal;_pageSizeVal;_consistentReadVal;_sortForward=!0;_forcedIndexName;where(e){return this._whereClause=e,this}limit(e){return this._limitVal=e,this}pageSize(e){return this._pageSizeVal=e,this}consistentRead(e=!0){return this._consistentReadVal=e,this}sort(e){return this._sortForward=e,this}index(e){return this._forcedIndexName=e,this}iterator(){return async function*(){let e,i=0;do{let n=await this.fetchPage(e);for(let s of n.items)if(yield s,i++,this._limitVal!==void 0&&i>=this._limitVal)return;e=n.lastEvaluatedKey}while(e)}.bind(this)()}async fetchPage(e){let i=this.resolveKeys(this._whereClause,void 0,this._forcedIndexName);return i.hasPartitionKey&&i.hasSortKey&&!i.indexName&&!e?{items:await this.executeGet(i.keys)}:i.hasPartitionKey||i.indexName?await this.executeQuery(i,e):await this.executeScan(e)}async execute(){let{items:e}=await this.fetchPage();return e}async executeGet(e){let i=new ie({TableName:this.tableName,Key:e,ConsistentRead:this._consistentReadVal}),n=await this.client.send(i);return n.Item?[this.mapToLogical(n.Item)]:[]}async executeQuery(e,i){let{expressionAttributeNames:n,expressionAttributeValues:s,addName:r,addValue:o}=this.createExpressionContext(),a=[],c=new Set;for(let[p,_]of Object.entries(e.keys))a.push(`${r(p)} = ${o(_)}`),c.add(p);let m=a.join(" AND "),u=this._whereClause?z(this._whereClause,r,o,c):void 0,f=new se({TableName:this.tableName,IndexName:e.indexName,KeyConditionExpression:m,FilterExpression:u||void 0,ExpressionAttributeNames:Object.keys(n).length>0?n:void 0,ExpressionAttributeValues:Object.keys(s).length>0?s:void 0,Limit:this._pageSizeVal??this._limitVal,ScanIndexForward:this._sortForward,ConsistentRead:e.indexName?void 0:this._consistentReadVal,ExclusiveStartKey:i}),T=await this.client.send(f);return{items:(T.Items||[]).map(p=>this.mapToLogical(p)),lastEvaluatedKey:T.LastEvaluatedKey}}async executeScan(e){let{expressionAttributeNames:i,expressionAttributeValues:n,addName:s,addValue:r}=this.createExpressionContext(),o=this._whereClause?z(this._whereClause,s,r):void 0,a=new oe({TableName:this.tableName,FilterExpression:o,ExpressionAttributeNames:Object.keys(i).length>0?i:void 0,ExpressionAttributeValues:Object.keys(n).length>0?n:void 0,Limit:this._pageSizeVal??this._limitVal,ConsistentRead:this._consistentReadVal,ExclusiveStartKey:e}),c=await this.client.send(a);return{items:(c.Items||[]).map(m=>this.mapToLogical(m)),lastEvaluatedKey:c.LastEvaluatedKey}}};var N=class{constructor(t){this.schema=t}parse(t,e,i={}){let n=this.schema.entities[e];if(!n)throw new Error(`Root entity ${e} not found in schema`);let s=[],r=[];for(let o of t)this.isEntity(o,n.entity)?s.push({...o}):r.push(o);for(let o of s)for(let[a,c]of Object.entries(i)){if(!c)continue;let m=n.relations[a];if(!m)continue;let u=m.config.to,f=r.filter(T=>this.isEntity(T,u));f.length>0&&(m.type==="many"?o[a]=f:m.type==="one"&&(o[a]=f[0]||null))}return s}isEntity(t,e){let i=e[d.ENTITY_STRATEGY],n=e[d.PHYSICAL_TABLE];if(!n||!n[E.PARTITION_KEY])return!1;let s=n[E.PARTITION_KEY].name,r=n[E.SORT_KEY]?.name,o=this.matchStrategy(t[s],i.pk),a=r?this.matchStrategy(t[r],i.sk):!0;return o&&a}matchStrategy(t,e){if(!e)return!0;if(t==null)return!1;let i=String(t);if(e.type==="static")return i===e.segments[0];if(e.type==="prefix"||e.type==="composite"){let n=e.segments[0];return typeof n=="string"&&i.startsWith(n)}return!1}};var b=class l{constructor(t,e,i,n){this.client=t;this.table=e;this.schema=i;this.entityName=n}async findFirst(t={}){return(await this.findMany({...t,limit:1}))[0]}async findMany(t={}){let e=new I(this.table,this.client,void 0);t.orderBy&&e.sort(t.orderBy==="asc");let i;if(t.where){let r=this.table._?.columns||this.table;typeof t.where=="function"?i=t.where(r,G):i=t.where}let n,s=L(this.table,i);if(this.schema&&this.entityName&&(t.with||t.include)&&s.hasPartitionKey&&!s.indexName){let r=this.table[d.PHYSICAL_TABLE];if(!r)throw new Error("Physical table not found for entity");let o=r[E.PARTITION_KEY].name,a=s.keys[o];e.where(P({name:o},a));let m=(await e).map(f=>v(this.table,f));n=new N(this.schema).parse(m,this.entityName,t.with||t.include),t.limit&&(n=n.slice(0,t.limit))}else t.limit&&e.limit(t.limit),i&&e.where(i),n=await e;if(this.schema&&this.entityName&&(t.with||t.include)){let r=t.with||t.include;await Promise.all(n.map(async o=>{for(let[a,c]of Object.entries(r)){let m=this.schema.entities[this.entityName];if(!m)continue;let u=m.relations[a];if(!u)continue;let f=o[a]!==void 0,T=typeof c=="object"&&(c.with||c.include);if(f&&!T)continue;let p=u.config.to,_=Object.entries(this.schema.entities).find(([R,y])=>y.entity===p)?.[0],V=v(this.table,o);if(u.config.fields&&u.config.references){let R={};u.config.fields.forEach((y,g)=>{let h=u.config.references[g];if(!h)return;let F=Object.entries(p[d.COLUMNS]).find(([K,C])=>C===h||C.name===h.name)?.[0];if(F){let K=Object.entries(this.table[d.COLUMNS]).find(([de,W])=>W===y||W.name===y.name)?.[0],C=K?o[K]??o[y.name]:o[y.name];C!==void 0&&(R[F]=C)}}),V=R}let j=L(p,void 0,V);if(j.hasPartitionKey){let R=new l(this.client,p,this.schema,_),y=[];for(let[g,h]of Object.entries(j.keys))y.push(P({name:g},h));if(y.length>0){let g=y.length===1?y[0]:q(...y),h=typeof c=="object"?c:{};u.type==="one"?o[a]=await R.findFirst({...h,where:g}):o[a]=await R.findMany({...h,where:g})}}}}))}return n}};import{BatchGetCommand as re}from"@aws-sdk/lib-dynamodb";var M=class{constructor(t){this.client=t}items(t,e){return new A(t,this.client,e)}},A=class extends w{constructor(e,i,n){super(e,i);this.keysData=n}static[d.ENTITY_KIND]="BatchGetBase";async execute(){let e=[],i=[],n=this.keysData.map(o=>this.resolveKeys(void 0,o).keys),s=0,r=5;for(;n.length>0&&s<r;){s++;let o=new re({RequestItems:{[this.tableName]:{Keys:n}}}),a=await this.client.send(o);a.Responses?.[this.tableName]&&e.push(...a.Responses[this.tableName]);let c=a.UnprocessedKeys?.[this.tableName]?.Keys;c&&c.length>0?n=c:n=[]}return n.length>0&&i.push(...n),{succeeded:e,failed:i}}};import{BatchWriteCommand as ae}from"@aws-sdk/lib-dynamodb";var B=class{constructor(t){this.client=t}operations(t,e){return new Y(t,this.client,e)}},Y=class extends w{constructor(e,i,n){super(e,i);this.ops=n}static[d.ENTITY_KIND]="BatchWriteBase";async execute(){let e=0,i=[],s=[...this.ops.map(a=>{if(a.type==="put"){let c=a.item;if(H(c)>400*1024)throw new $("Item in batch exceeds the 400KB limit.");return{PutRequest:{Item:c}}}else return{DeleteRequest:{Key:a.keys}}})],r=0,o=5;for(;s.length>0&&r<o;){r++;let a=new ae({RequestItems:{[this.tableName]:s}}),m=(await this.client.send(a)).UnprocessedItems?.[this.tableName]||[];e+=s.length-m.length,m.length>0?s=m:s=[]}return s.length>0&&(i=s),{succeededCount:e,failed:i}}};var x=class{constructor(t,e){this.type=t;this.config=e}};function st(l,t){if(l instanceof D){let i=t({one:(n,s)=>new x("one",{to:n,...s}),many:(n,s)=>new x("many",{to:n,...s})});return{entity:l,config:i,[k.RELATION_CONFIG]:!0}}else{let e=l,i=t,n={one:{},many:{}};for(let[r,o]of Object.entries(e))n.one[r]=a=>new x("one",{to:o,...a}),n.many[r]=a=>new x("many",{to:o,...a}),n[r]=o;let s=i(n);return{schema:e,definitions:s,[k.RELATION_CONFIG]:!0}}}function te(l){let t={entities:{}};for(let[e,i]of Object.entries(l))i instanceof D&&(t.entities[e]={entity:i,relations:{}});for(let[,e]of Object.entries(l))if(e&&typeof e=="object"&&e[k.RELATION_CONFIG]){let i=e;if(i.entity){let n=e,s=Object.entries(t.entities).find(([r,o])=>o.entity===n.entity);if(s){let[,r]=s;r.relations={...r.relations,...n.config}}}else if(i.definitions){let n=e;for(let[s,r]of Object.entries(n.definitions)){let o=n.schema[s],a=Object.entries(t.entities).find(([c,m])=>m.entity===o);if(a&&r){let[,c]=a;c.relations={...c.relations,...r}}}}}return t}var S=class{docClient;schema;retryConfig;query;constructor(t,e,i){this.retryConfig={maxAttempts:i?.maxAttempts??3,baseDelay:i?.baseDelay??100},this.docClient=new U(le.from(t),new Q(this.retryConfig)),e&&(this.schema=te(e)),this.query=new Proxy({},{get:(n,s)=>{if(typeof s!="string")return;if(!this.schema)throw new Error("No relations defined. Initialize mizzle with a relations object to use db.query.");let r=this.schema.entities[s];if(!r)throw new Error(`Entity ${s} not found in relations schema.`);return new b(this.docClient,r.entity,this.schema,s)}})}insert(t){return new J(t,this.docClient)}select(t){return new O(this.docClient,t)}batchGet(t,e){return new M(this.docClient).items(t,e)}batchWrite(t,e){return new B(this.docClient).operations(t,e)}_query(t){return new b(this.docClient,t)}update(t){return new X(t,this.docClient)}delete(t,e){return new Z(t,this.docClient,e)}async transaction(t,e){let i=new ee(this.docClient),n=await e(i);if(n.length===0)return;if(n.length>100)throw new Error("DynamoDB transactions are limited to 100 items.");let{TransactionExecutor:s}=await import("./transaction-RE7LXTGV.js");await new s(this.docClient).execute(t,n)}};function gt(l){return l instanceof ne?new S(l):"client"in l&&l.client instanceof ne?new S(l.client,l.relations,l.retry):"client"in l&&l.client?new S(l.client,l.relations,l.retry):new S(l)}export{O as a,I as b,M as c,A as d,B as e,Y as f,b as g,x as h,st as i,te as j,S as k,gt as l};
@@ -0,0 +1 @@
1
+ import{c as h}from"./chunk-AQVECMXP.js";function S(c,l){let a=[],e=h(c).tables,t=l.tables||{},n=new Set([...Object.keys(e),...Object.keys(t)]);for(let s of n){let o=e[s],r=t[s];o&&!r?a.push({type:"create",table:o}):!o&&r?a.push({type:"delete",tableName:s}):o&&r&&(i(o,r)||a.push({type:"update",tableName:s,changes:["Changed"]}))}return a}function i(c,l){let a=p=>{let e={...p};return e.AttributeDefinitions=[...e.AttributeDefinitions||[]].sort((t,n)=>(t.AttributeName||"").localeCompare(n.AttributeName||"")),e.GlobalSecondaryIndexes&&(e.GlobalSecondaryIndexes=[...e.GlobalSecondaryIndexes].sort((t,n)=>(t.IndexName||"").localeCompare(n.IndexName||""))),e.LocalSecondaryIndexes&&(e.LocalSecondaryIndexes=[...e.LocalSecondaryIndexes].sort((t,n)=>(t.IndexName||"").localeCompare(n.IndexName||""))),e};return JSON.stringify(a(c))===JSON.stringify(a(l))}export{S as a};
@@ -0,0 +1 @@
1
+ import{d as T,e as m,h as F,i as W,j as v}from"./chunk-DU7UPWBW.js";import{TransactWriteCommand as he}from"@aws-sdk/lib-dynamodb";import{PutCommand as ye}from"@aws-sdk/lib-dynamodb";import"@aws-sdk/lib-dynamodb";var te=new Set(["ProvisionedThroughputExceededException","RequestLimitExceeded","InternalServerError","ServiceUnavailable","ThrottlingException"]),ne=new Set([500,503]),H=class{constructor(e){this.config=e}async execute(e){let n;for(let r=1;r<=this.config.maxAttempts;r++)try{return await e()}catch(s){if(n=s,r>=this.config.maxAttempts||!this.isRetryable(s))throw s;await this.delay(r-1)}throw n}isRetryable(e){if(!e||typeof e!="object")return!1;let n=e;return!!(n.name&&te.has(n.name)||n.$metadata?.httpStatusCode&&ne.has(n.$metadata.httpStatusCode))}async delay(e){let n=this.config.baseDelay*Math.pow(2,e),r=Math.random()*n,s=n+r;return new Promise(o=>setTimeout(o,s))}};var X=class{constructor(e,n){this.client=e;this.retryHandler=n}send(e,n){return this.retryHandler.execute(()=>this.client.send(e,n))}};var N=class{[Symbol.toStringTag]="QueryPromise";catch(e){return this.then(void 0,e)}finally(e){return this.then(n=>(e?.(),n),n=>{throw e?.(),n})}then(e,n){return this.execute().then(e,n)}};var I=class{},k=class extends I{constructor(n,r,s){super();this.column=n;this.operator=r;this.value=s}type="binary"},w=class extends I{constructor(n,r){super();this.conditions=n;this.operator=r}type="logical"},S=class extends I{constructor(n,r,s){super();this.column=n;this.operator=r;this.value=s}type="function"};function re(t,e){return new k(t,"=",e)}function se(t,e){return new k(t,">",e)}function oe(t,e){return new k(t,">=",e)}function ie(t,e){return new k(t,"<",e)}function ae(t,e){return new k(t,"<=",e)}function ue(t,e){return new k(t,"between",e)}function ce(t,e){return new k(t,"in",e)}function le(t,e){return new S(t,"begins_with",e)}function pe(t,e){return new S(t,"contains",e)}function me(t){return new S(t,"attribute_exists",void 0)}function de(...t){return new w(t,"OR")}function fe(...t){return new w(t,"AND")}var Ie={eq:re,gt:se,gte:oe,lt:ie,lte:ae,between:ue,in:ce,and:fe,or:de,contains:pe,beginsWith:le,attributeExists:me};function Oe(t){return{type:"static",segments:[t]}}function Ve(t,e){return{type:"prefix",segments:[t,e]}}function Le(t,...e){return{type:"composite",separator:t,segments:e}}function q(t,e){if(t instanceof k)t.operator==="="&&(e[t.column.name]=t.value);else if(t instanceof w&&t.operator==="AND")for(let n of t.conditions)q(n,e)}function b(t,e){if(t.type==="static")return t.segments[0];if(t.segments.length===0)return;if(t.type==="prefix"&&t.segments.length===2&&typeof t.segments[0]=="string"&&t.segments[1]instanceof v){let r=t.segments[0],s=t.segments[1],o=e[s.name];if(o==null)return;let i=String(o);return i.startsWith(r)?i:r+i}let n=[];for(let r of t.segments)if(typeof r=="string")n.push(r);else if(r instanceof v){let s=e[r.name];if(s==null)return;n.push(String(s))}if(t.type==="prefix")return n.join("");if(t.type==="composite")return n.join(t.separator||"#")}function G(t,e,n,r){let s=t[m.ENTITY_STRATEGY],o=t[m.PHYSICAL_TABLE],i=o[T.PARTITION_KEY],c=o[T.SORT_KEY],u={},p=t[m.COLUMNS];if(n)for(let[f,l]of Object.entries(n))if(p[f])u[f]=l;else{let y=Object.entries(p).find(([d,g])=>g.name===f);y?u[y[0]]=l:u[f]=l}e&&q(e,u);let a={keys:{},hasPartitionKey:!1,hasSortKey:!1};if(r){let l=o[T.INDEXES]?.[r],y=s[r],d=y&&"pk"in y?y:void 0;if(l&&d){if(u[l.config.pk]!==void 0)return a.indexName=r,a.keys[l.config.pk]=u[l.config.pk],a.hasPartitionKey=!0,l.config.sk&&u[l.config.sk]!==void 0&&(a.keys[l.config.sk]=u[l.config.sk],a.hasSortKey=!0),a;let g=b(d.pk,u);if(g){a.indexName=r,a.keys[l.config.pk]=g,a.hasPartitionKey=!0;let E=d.sk?b(d.sk,u):void 0;return E&&l.config.sk&&(a.keys[l.config.sk]=E,a.hasSortKey=!0),a}}}if(u[i.name]!==void 0&&(a.keys[i.name]=u[i.name],a.hasPartitionKey=!0,c&&u[c.name]!==void 0?(a.keys[c.name]=u[c.name],a.hasSortKey=!0):c||(a.hasSortKey=!0),a.hasPartitionKey))return a;if("pk"in s&&s.pk){let f=s.pk,l=b(f,u);l&&(a.keys[i.name]=l,a.hasPartitionKey=!0)}if("sk"in s&&s.sk){let f=s.sk,l=b(f,u);l&&c&&(a.keys[c.name]=l,a.hasSortKey=!0)}else a.hasSortKey=!c;if(!a.hasPartitionKey){let f=o[T.INDEXES];if(f)for(let[l,y]of Object.entries(f)){let d=y,g=s[l],E=g&&"pk"in g?g:void 0;if(E){if(u[d.config.pk]!==void 0){a.indexName=l,a.keys={},a.keys[d.config.pk]=u[d.config.pk],a.hasPartitionKey=!0,d.config.sk&&u[d.config.sk]!==void 0&&(a.keys[d.config.sk]=u[d.config.sk],a.hasSortKey=!0);break}if(E.pk&&d.config.pk){let j=b(E.pk,u);if(j){if(a.indexName=l,a.keys={},a.keys[d.config.pk]=j,a.hasPartitionKey=!0,E.sk&&d.config.sk){let Y=b(E.sk,u);Y&&(a.keys[d.config.sk]=Y,a.hasSortKey=!0)}break}}}}}return a}var h=class extends N{constructor(n,r){super();this.entity=n;this.client=r}get tableName(){return F(this.entity)}get physicalTable(){return this.entity[m.PHYSICAL_TABLE]}resolveKeys(n,r,s){return G(this.entity,n,r,s)}createExpressionContext(n=""){let r={},s={},o=0,i=0;return{expressionAttributeNames:r,expressionAttributeValues:s,addName:p=>p.split(".").map(l=>{let y=`#${n}n${o++}`;return r[y]=l,y}).join("."),addValue:p=>{let a=`:${n}v${i++}`;return s[a]=p,a}}}mapToLogical(n){return W(this.entity,n)}};function K(t){let e=0;for(let[n,r]of Object.entries(t))e+=Buffer.byteLength(n,"utf8"),e+=_(r);return e}function _(t){if(t==null)return 1;if(typeof t=="string")return Buffer.byteLength(t,"utf8");if(typeof t=="number")return 21;if(typeof t=="boolean")return 1;if(t instanceof Buffer||t instanceof Uint8Array)return t.byteLength;if(Array.isArray(t)){let e=3;for(let n of t)e+=_(n);return e}if(t instanceof Set){let e=3;for(let n of t)e+=_(n);return e}if(typeof t=="object"){let e=3;for(let[n,r]of Object.entries(t))e+=Buffer.byteLength(n,"utf8"),e+=_(r);return e}return 0}var C=class t extends Error{constructor(e){super(e),this.name="ItemSizeExceededError",Object.setPrototypeOf(this,t.prototype)}},D=class t extends Error{constructor(n,r){super(n);this.reasons=r;this.name="TransactionFailedError",Object.setPrototypeOf(this,t.prototype)}};var A=class{constructor(e,n){this.entity=e;this.client=n}static[m.ENTITY_KIND]="InsertBuilder";values(e){return new M(this.entity,this.client,e)}},M=class extends h{constructor(n,r,s){super(n,r);this.valuesData=s}static[m.ENTITY_KIND]="InsertBase";shouldReturnValues=!1;get values(){return this.valuesData}returning(){return this.shouldReturnValues=!0,this}buildItem(){let n=this.processValues(this.valuesData),r=this.resolveKeys(void 0,n),s={...n,...r.keys},o=this.entity[m.ENTITY_STRATEGY],c=this.entity[m.PHYSICAL_TABLE]?.[T.INDEXES]||{};for(let[u,p]of Object.entries(o)){if(u==="pk"||u==="sk")continue;let a=c[u];if(a){if(p.pk&&a.config.pk){let f=this.resolveStrategyValue(p.pk,n);f&&(s[a.config.pk]=f)}if(p.sk&&a.config.sk){let f=this.resolveStrategyValue(p.sk,n);f&&(s[a.config.sk]=f)}}}return s}async execute(){let n=this.buildItem(),r=K(n);if(r>400*1024)throw new C(`Item size of ${Math.round(r/1024)}KB exceeds the 400KB limit.`);let s=new ye({TableName:this.tableName,Item:n});if(await this.client.send(s),this.shouldReturnValues)return n}resolveStrategyValue(n,r){if(n.type==="static")return n.segments[0];let s=[];for(let o of n.segments)if(typeof o=="string")s.push(o);else{let i=r[o.name];if(i==null)return;s.push(String(i))}if(n.type==="prefix")return s.join("");if(n.type==="composite")return s.join(n.separator||"#")}processValues(n){let r={...n},s=this.entity[m.COLUMNS];for(let o in s){let i=s[o];if(!i)continue;r[o]===void 0&&(i.default!==void 0?r[o]=i.default:i.defaultFn&&(r[o]=i.defaultFn()));let u=r[o];if(i instanceof v&&(r[o]=i.mapToDynamoValue(u)),["SS","NS","BS"].includes(i.columnType)&&Array.isArray(u)){let p=new Set(u);r[o]=p,p.size===0&&delete r[o]}}return r}};import{UpdateCommand as ke}from"@aws-sdk/lib-dynamodb";function R(t,e,n,r){if(t instanceof w){let s=t.conditions.map(o=>R(o,e,n,r)).filter(o=>o!==void 0&&o!=="");return s.length===0?void 0:s.length===1?s[0]:`(${s.join(` ${t.operator} `)})`}if(t instanceof k){if(r?.has(t.column.name))return;let s=e(t.column.name),o=c=>typeof t.column.mapToDynamoValue=="function"?t.column.mapToDynamoValue(c):c;if(t.operator==="between"){let c=t.value,u=n(o(c[0])),p=n(o(c[1]));return`${s} BETWEEN ${u} AND ${p}`}if(t.operator==="in"){let u=t.value.map(p=>n(o(p)));return`${s} IN (${u.join(", ")})`}let i=n(o(t.value));return`${s} ${t.operator} ${i}`}if(t instanceof S){if(r?.has(t.column.name))return;let s=e(t.column.name),o=c=>typeof t.column.mapToDynamoValue=="function"?t.column.mapToDynamoValue(c):c;if(t.operator==="attribute_exists")return`attribute_exists(${s})`;let i=n(o(t.value));return`${t.operator}(${s}, ${i})`}}var x=class{},B=class extends x{constructor(n,r,s=!1){super();this.value=n;this.functionName=r;this.usePathAsFirstArg=s}action="SET"},O=class extends x{constructor(n){super();this.value=n}action="ADD"},U=class extends x{action="REMOVE"},z=class extends x{constructor(n){super();this.value=n}action="DELETE"};function ut(t){return new O(t)}function ct(t){return new B(t,"list_append",!0)}function lt(t){return new B(t,"if_not_exists",!0)}function pt(){return new U}function mt(t){let e=Array.isArray(t)?new Set(t):t;return new O(e)}function dt(t){let e=Array.isArray(t)?new Set(t):t;return new z(e)}function Q(){return{set:{},add:{},remove:[],delete:{}}}function J(t,e,n){for(let[r,s]of Object.entries(t)){let o=n?.[r],i=c=>o&&typeof o.mapToDynamoValue=="function"?o.mapToDynamoValue(c):c;if(s instanceof x)switch(s.action){case"SET":{let c=s;e.set[r]={value:i(c.value),functionName:c.functionName,usePathAsFirstArg:c.usePathAsFirstArg};break}case"ADD":e.add[r]=i(s.value);break;case"REMOVE":e.remove.push(r);break;case"DELETE":e.delete[r]=i(s.value);break}else s!==void 0&&(e.set[r]={value:i(s)})}}function V(t,e,n){let r=[];if(Object.keys(t.set).length>0){let s=Object.entries(t.set).map(([o,i])=>{let c=e(o),u=n(i.value);return i.functionName?i.usePathAsFirstArg?`${c} = ${i.functionName}(${c}, ${u})`:`${c} = ${i.functionName}(${u})`:`${c} = ${u}`});r.push(`SET ${s.join(", ")}`)}if(Object.keys(t.add).length>0){let s=Object.entries(t.add).map(([o,i])=>`${e(o)} ${n(i)}`);r.push(`ADD ${s.join(", ")}`)}if(t.remove.length>0){let s=t.remove.map(o=>e(o));r.push(`REMOVE ${s.join(", ")}`)}if(Object.keys(t.delete).length>0){let s=Object.entries(t.delete).map(([o,i])=>`${e(o)} ${n(i)}`);r.push(`DELETE ${s.join(", ")}`)}return r.join(" ")}var L=class extends h{static[m.ENTITY_KIND]="UpdateBuilder";_state=Q();_whereClause;_returnValues;_explicitKey;constructor(e,n){super(e,n)}key(e){return this._explicitKey=e,this}set(e){return J(e,this._state,this.entity[m.COLUMNS]),this}add(e){let n=this.entity[m.COLUMNS];for(let[r,s]of Object.entries(e)){let o=n[r];this._state.add[r]=o&&typeof o.mapToDynamoValue=="function"?o.mapToDynamoValue(s):s}return this}remove(...e){return this._state.remove.push(...e),this}delete(e){let n=this.entity[m.COLUMNS];for(let[r,s]of Object.entries(e)){let o=n[r];this._state.delete[r]=o&&typeof o.mapToDynamoValue=="function"?o.mapToDynamoValue(s):s}return this}where(e){return this._whereClause=e,this}returning(e){return this._returnValues=e,this}get state(){return this._state}get whereClause(){return this._whereClause}createExpressionContext(e=""){return super.createExpressionContext(e)}async execute(){let e=this.entity[m.COLUMNS];for(let[l,y]of Object.entries(e)){let d=y;if(d.onUpdateFn&&!this._state.set[l]&&!this._state.remove.includes(l)){let g=d.onUpdateFn();this._state.set[l]={value:typeof d.mapToDynamoValue=="function"?d.mapToDynamoValue(g):g}}}let n=this.resolveUpdateKeys(),{expressionAttributeNames:r,expressionAttributeValues:s,addName:o,addValue:i}=this.createExpressionContext("up_"),c=V(this._state,o,i),u;this._whereClause&&(u=R(this._whereClause,o,i));let p=K({...n,...s});if(p>400*1024)throw new C(`Estimated update size of ${Math.round(p/1024)}KB exceeds the 400KB limit.`);let a=new ke({TableName:this.tableName,Key:n,UpdateExpression:c,ConditionExpression:u,ExpressionAttributeNames:Object.keys(r).length>0?r:void 0,ExpressionAttributeValues:Object.keys(s).length>0?s:void 0,ReturnValues:this._returnValues});return(await this.client.send(a)).Attributes}resolveUpdateKeys(){return this._explicitKey?this._explicitKey:this.resolveKeys(this._whereClause).keys}};import{DeleteCommand as ge}from"@aws-sdk/lib-dynamodb";var P=class extends h{static[m.ENTITY_KIND]="DeleteBuilder";_returnValues;_keys;constructor(e,n,r){super(e,n),this._keys=r}returning(){return this._returnValues="ALL_OLD",this}get keys(){return this._keys}resolveKeys(e,n){return super.resolveKeys(e,n)}createExpressionContext(e=""){return super.createExpressionContext(e)}async execute(){let e=this.resolveKeys(void 0,this._keys),n=new ge({TableName:this.tableName,Key:e.keys,ReturnValues:this._returnValues});return(await this.client.send(n)).Attributes}};var $=class extends h{static[m.ENTITY_KIND]="ConditionCheckBuilder";_whereClause;constructor(e,n){super(e,n)}where(e){return this._whereClause=e,this}async execute(){throw new Error("ConditionCheckBuilder cannot be executed directly. Use it within a transaction.")}get whereClause(){return this._whereClause}createExpressionContext(e=""){return super.createExpressionContext(e)}resolveKeys(e,n){return super.resolveKeys(e,n)}},Z=class{constructor(e){this.client=e}insert(e){return new A(e,this.client)}update(e){return new L(e,this.client)}delete(e,n){return new P(e,this.client,n)}conditionCheck(e){return new $(e,this.client)}},ee=class{constructor(e){this.client=e}async execute(e,n){let r=n.map(o=>this.mapToTransactItem(o)),s=new he({TransactItems:r,ClientRequestToken:e});try{await this.client.send(s)}catch(o){let i=o;if(i.name==="TransactionCanceledException"||i.__type?.includes("TransactionCanceledException")){let c=(i.CancellationReasons||[]).map((u,p)=>({index:p,code:u.Code,message:u.Message,item:u.Item})).filter(u=>u.code!=="None");throw new D("Transaction canceled by server.",c)}throw o}}mapToTransactItem(e){let n=e.constructor[m.ENTITY_KIND];switch(n){case"InsertBase":return{Put:this.mapPut(e)};case"UpdateBuilder":return{Update:this.mapUpdate(e)};case"DeleteBuilder":return{Delete:this.mapDelete(e)};case"ConditionCheckBuilder":return{ConditionCheck:this.mapConditionCheck(e)};default:throw new Error(`Unsupported transaction operation: ${n}`)}}mapPut(e){let n=e.buildItem();return{TableName:e.tableName,Item:n}}mapUpdate(e){let{expressionAttributeNames:n,expressionAttributeValues:r,addName:s,addValue:o}=e.createExpressionContext("up_"),i=V(e.state,s,o),c;return e.whereClause&&(c=R(e.whereClause,s,o)),{TableName:e.tableName,Key:e.resolveUpdateKeys(),UpdateExpression:i,ConditionExpression:c,ExpressionAttributeNames:Object.keys(n).length>0?n:void 0,ExpressionAttributeValues:Object.keys(r).length>0?r:void 0}}mapDelete(e){let n=e.resolveKeys(void 0,e.keys);return{TableName:e.tableName,Key:n.keys}}mapConditionCheck(e){let{expressionAttributeNames:n,expressionAttributeValues:r,addName:s,addValue:o}=e.createExpressionContext("cc_"),i=e.resolveKeys(e.whereClause),c;return e.whereClause&&(c=R(e.whereClause,s,o)),{TableName:e.tableName,Key:i.keys,ConditionExpression:c,ExpressionAttributeNames:Object.keys(n).length>0?n:void 0,ExpressionAttributeValues:Object.keys(r).length>0?r:void 0}}};export{I as a,k as b,w as c,S as d,re as e,se as f,oe as g,ie as h,ae as i,ue as j,ce as k,le as l,pe as m,me as n,de as o,fe as p,Ie as q,R as r,x as s,B as t,O as u,U as v,z as w,ut as x,ct as y,lt as z,pt as A,mt as B,dt as C,H as D,X as E,Oe as F,Ve as G,Le as H,G as I,h as J,K,C as L,D as M,A as N,M as O,L as P,P as Q,$ as R,Z as S,ee as T};
@@ -0,0 +1 @@
1
+ export { c as ColumnsBuilder, z as binary, D as binarySet, G as boolean, Q as date, Y as getColumnBuilders, a2 as json, a3 as list, a7 as map, a9 as number, aa as numberSet, ah as string, ai as stringSet, aj as uuid } from './operators-BVreW0ky.js';
@@ -0,0 +1 @@
1
+ import{k as a,l as b,m as c,n as d,o as e,p as f,q as g,r as h,s as i,t as j,u as k,v as l,w as m}from"./chunk-DU7UPWBW.js";export{a as binary,b as binarySet,c as boolean,d as date,m as getColumnBuilders,l as json,e as list,f as map,g as number,h as numberSet,i as string,j as stringSet,k as uuid};