@chaim-tools/client-java 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,342 @@
1
+ # chaim-client-java
2
+
3
+ A production-ready Java SDK generator for the Chaim framework. Generates type-safe DynamoDB Enhanced Client code using **schema-defined keys**, Lombok annotations, and DI-friendly architecture.
4
+
5
+ ## Overview
6
+
7
+ The chaim-client-java is a **hybrid Java/TypeScript package** that serves as the code generation engine for the Chaim ecosystem. It is an **internal dependency** of `chaim-cli` — end users should not invoke it directly.
8
+
9
+ - **Schema-Driven Keys**: Uses your schema-defined PK/SK fields directly (no invented fields)
10
+ - **DynamoDB Enhanced Client**: Full `@DynamoDbBean` annotation support
11
+ - **Lombok Integration**: `@Data`, `@Builder`, `@NoArgsConstructor`, `@AllArgsConstructor`
12
+ - **DI-Friendly**: Builder pattern, endpoint override, client injection for testing
13
+ - **Drop-in Ready**: Generated code matches your existing table structure
14
+ - **No Scan by Default**: Promotes NoSQL best practices
15
+
16
+ **Invocation Model**:
17
+ ```
18
+ End users → chaim-cli → chaim-client-java (internal)
19
+ ```
20
+
21
+ **Data Flow**:
22
+ ```
23
+ .bprint file → chaim-cdk → OS cache snapshot → chaim-cli → chaim-client-java → .java files
24
+ ↑ ↑ ↑
25
+ user defines user deploys user generates
26
+ ```
27
+
28
+ > **Note**: This package does not read `.bprint` files or OS cache snapshots directly. It receives parsed schema JSON from `chaim-cli`. Direct invocation is only for local development/testing.
29
+
30
+ ## Schema-Driven Keys
31
+
32
+ **The generator uses exactly what you define.**
33
+
34
+ Your schema:
35
+ ```json
36
+ {
37
+ "entity": {
38
+ "primaryKey": {
39
+ "partitionKey": "userId",
40
+ "sortKey": "entityType"
41
+ },
42
+ "fields": [
43
+ { "name": "userId", "type": "string" },
44
+ { "name": "entityType", "type": "string" },
45
+ ...
46
+ ]
47
+ }
48
+ }
49
+ ```
50
+
51
+ Generated Java:
52
+ ```java
53
+ @DynamoDbBean
54
+ public class User {
55
+ private String userId; // YOUR partition key
56
+ private String entityType; // YOUR sort key
57
+
58
+ @DynamoDbPartitionKey
59
+ public String getUserId() { return userId; }
60
+
61
+ @DynamoDbSortKey
62
+ public String getEntityType() { return entityType; }
63
+ }
64
+ ```
65
+
66
+ **Benefits**:
67
+ - ✅ Works with existing tables and data
68
+ - ✅ Easy data migrations
69
+ - ✅ Schema is the single source of truth
70
+
71
+ ## Installation
72
+
73
+ ### As npm Dependency (Recommended)
74
+
75
+ ```bash
76
+ npm install @chaim-tools/client-java
77
+ ```
78
+
79
+ This installs the TypeScript wrapper and bundled Java JAR together.
80
+
81
+ ### Building from Source
82
+
83
+ ```bash
84
+ # Clone the repository
85
+ git clone https://github.com/chaim-tools/chaim-client-java.git
86
+ cd chaim-client-java
87
+
88
+ # Build everything
89
+ npm run build
90
+ ```
91
+
92
+ ## Requirements
93
+
94
+ - **Java**: 17 LTS (runtime — JAR targets Java 17 for enterprise compatibility)
95
+ - **Node.js**: 18+ (for TypeScript wrapper)
96
+ - **Gradle**: 8+ (for building from source)
97
+
98
+ ## Repository Structure
99
+
100
+ ```
101
+ chaim-client-java/
102
+ ├── schema-core/ # Core schema handling (BprintLoader, Validator)
103
+ ├── codegen-java/ # Code generation engine (JavaPoet, TableMetadata)
104
+ ├── src/
105
+ │ └── index.ts # TypeScript wrapper
106
+ ├── dist/ # Compiled output
107
+ │ ├── index.js # TypeScript wrapper
108
+ │ └── jars/
109
+ │ └── codegen-java-0.1.0.jar # Bundled fat JAR
110
+ └── package.json
111
+ ```
112
+
113
+ ## Usage
114
+
115
+ ### From chaim-cli (End User Method)
116
+
117
+ End users should always use the CLI — it handles snapshot discovery and invokes this package internally:
118
+
119
+ ```bash
120
+ chaim generate --package com.example.model --language java
121
+ ```
122
+
123
+ The CLI:
124
+ 1. Reads snapshots from OS cache (`~/.chaim/cache/snapshots/`)
125
+ 2. Groups snapshots by physical table (using `tableArn` or composite key)
126
+ 3. **Validates PK/SK consistency** across all entities for each table
127
+ 4. Invokes chaim-client-java with all schemas for each table
128
+ 5. Writes generated `.java` files to the output directory
129
+
130
+ ## Generated Output
131
+
132
+ For a package `com.example.model` with User and Order schemas:
133
+
134
+ ```
135
+ com/example/model/
136
+ ├── User.java # Entity DTO with schema-defined keys
137
+ ├── Order.java # Entity DTO with schema-defined keys
138
+ ├── keys/
139
+ │ ├── UserKeys.java # Key constants and helpers
140
+ │ └── OrderKeys.java # Key constants and helpers
141
+ ├── repository/
142
+ │ ├── UserRepository.java # Key-based CRUD operations
143
+ │ └── OrderRepository.java # Key-based CRUD operations
144
+ ├── client/
145
+ │ └── ChaimDynamoDbClient.java # DI-friendly client wrapper
146
+ └── config/
147
+ └── ChaimConfig.java # Constants + repository factories
148
+ ```
149
+
150
+ ### Entity DTO
151
+
152
+ Uses your schema-defined keys:
153
+
154
+ ```java
155
+ @Data
156
+ @Builder
157
+ @NoArgsConstructor
158
+ @AllArgsConstructor
159
+ @DynamoDbBean
160
+ public class User {
161
+ private String userId; // Schema-defined partition key
162
+ private String entityType; // Schema-defined sort key
163
+ private String email;
164
+
165
+ @DynamoDbPartitionKey
166
+ public String getUserId() { return userId; }
167
+
168
+ @DynamoDbSortKey
169
+ public String getEntityType() { return entityType; }
170
+ }
171
+ ```
172
+
173
+ ### Key Constants
174
+
175
+ ```java
176
+ public final class UserKeys {
177
+ public static final String PARTITION_KEY_FIELD = "userId";
178
+ public static final String SORT_KEY_FIELD = "entityType";
179
+
180
+ public static Key key(String userId, String entityType) {
181
+ return Key.builder()
182
+ .partitionValue(userId)
183
+ .sortValue(entityType)
184
+ .build();
185
+ }
186
+ }
187
+ ```
188
+
189
+ ### Repository
190
+
191
+ ```java
192
+ public class UserRepository {
193
+ // DI-friendly constructors
194
+ public UserRepository(ChaimDynamoDbClient client) { ... }
195
+ public UserRepository(DynamoDbEnhancedClient client, String tableName) { ... }
196
+
197
+ public void save(User entity) { ... }
198
+ public Optional<User> findByKey(String userId, String entityType) { ... }
199
+ public void deleteByKey(String userId, String entityType) { ... }
200
+ // NOTE: No findAll() or scan() - promotes NoSQL best practices
201
+ }
202
+ ```
203
+
204
+ ### DI-Friendly Client
205
+
206
+ ```java
207
+ // Builder pattern for configuration
208
+ ChaimDynamoDbClient client = ChaimDynamoDbClient.builder()
209
+ .tableName("DataTable")
210
+ .region("us-east-1")
211
+ .endpoint("http://localhost:8000") // For local DynamoDB
212
+ .build();
213
+
214
+ // Or inject existing client for testing
215
+ ChaimDynamoDbClient client = ChaimDynamoDbClient.wrap(mockEnhancedClient, "DataTable");
216
+ ```
217
+
218
+ ### Configuration
219
+
220
+ ```java
221
+ // Use shared client (lazy singleton)
222
+ UserRepository users = ChaimConfig.userRepository();
223
+ OrderRepository orders = ChaimConfig.orderRepository();
224
+
225
+ // Or with custom client
226
+ ChaimDynamoDbClient customClient = ChaimConfig.clientBuilder()
227
+ .endpoint("http://localhost:8000")
228
+ .build();
229
+ UserRepository users = ChaimConfig.userRepository(customClient);
230
+ ```
231
+
232
+ ## Multi-Entity Table Validation
233
+
234
+ For entities sharing a table, all must have **matching PK/SK field names**:
235
+
236
+ ```
237
+ Table: DataTable (PK: userId, SK: entityType)
238
+ ├── User → partitionKey: "userId", sortKey: "entityType" ✅
239
+ ├── Order → partitionKey: "userId", sortKey: "entityType" ✅
240
+ └── Product → partitionKey: "productId", sortKey: "category" ❌ ERROR!
241
+ ```
242
+
243
+ chaim-cli validates this before generation.
244
+
245
+ ## Type Mappings
246
+
247
+ | .bprint Type | Java Type |
248
+ |--------------|-----------|
249
+ | `string` | `String` |
250
+ | `number` | `Double` |
251
+ | `boolean` | `Boolean` |
252
+ | `timestamp` | `Instant` |
253
+
254
+ ## Entity Name Derivation
255
+
256
+ The generator uses the `entityName` field directly from schema v1.1:
257
+
258
+ - `"entityName": "User"` → Class name: `User`
259
+ - `"entityName": "Order"` → Class name: `Order`
260
+
261
+ If `entityName` is not provided, the generator defaults to `"Entity"`.
262
+
263
+ ## Building
264
+
265
+ ### Full Build
266
+
267
+ ```bash
268
+ npm run build
269
+ ```
270
+
271
+ This runs:
272
+ 1. `./gradlew build` - Build Java modules
273
+ 2. `tsc` - Compile TypeScript
274
+ 3. Copy JAR to `dist/jars/`
275
+
276
+ ### Individual Steps
277
+
278
+ ```bash
279
+ # Java only
280
+ ./gradlew build
281
+ ./gradlew :codegen-java:build
282
+
283
+ # TypeScript only
284
+ npm run build:ts
285
+
286
+ # Tests
287
+ ./gradlew test
288
+ ```
289
+
290
+ ### Clean
291
+
292
+ ```bash
293
+ npm run clean
294
+ ```
295
+
296
+ ## Modules
297
+
298
+ ### schema-core
299
+
300
+ Core schema handling:
301
+ - `BprintLoader` - Load schema JSON strings
302
+ - `BprintValidator` - Validate schema structure
303
+ - `BprintSchema` - Java model with Jackson annotations
304
+ - `FieldType` - Type mapping utilities
305
+
306
+ ### codegen-java
307
+
308
+ Code generation:
309
+ - `Main` - CLI entry point (supports `--schemas`, `--schemas-file`)
310
+ - `JavaGenerator` - JavaPoet-based code generator with schema-driven keys
311
+ - `TableMetadata` - Simple record for table metadata (passed from CLI)
312
+
313
+ ## npm Packaging
314
+
315
+ The package publishes `dist/` containing:
316
+ - TypeScript wrapper (`index.js`)
317
+ - Bundled fat JAR (`jars/codegen-java-0.1.0.jar`)
318
+
319
+ The TypeScript wrapper automatically resolves the JAR location for both:
320
+ - **npm install**: `dist/jars/codegen-java-0.1.0.jar`
321
+ - **Development**: `codegen-java/build/libs/codegen-java-0.1.0.jar`
322
+
323
+ ## Related Packages
324
+
325
+ | Package | Purpose |
326
+ |---------|---------|
327
+ | [chaim-cli](https://github.com/chaim-tools/chaim-cli) | CLI tool that uses this generator |
328
+ | [chaim-bprint-spec](https://github.com/chaim-tools/chaim-bprint-spec) | Schema specification |
329
+ | [chaim-cdk](https://github.com/chaim-tools/chaim-cdk) | CDK constructs that produce snapshots |
330
+
331
+ ## Roadmap
332
+
333
+ - AWS SDK v1 DynamoDBMapper annotation support (planned)
334
+ - Additional language generators
335
+
336
+ ## License
337
+
338
+ Apache-2.0
339
+
340
+ ---
341
+
342
+ **Chaim** means life, representing our mission: supporting the life (data) of software applications as they grow and evolve alongside businesses.
@@ -0,0 +1,15 @@
1
+ export declare class JavaGenerator {
2
+ private javaGeneratorPath;
3
+ constructor();
4
+ /**
5
+ * Generate code for multiple schemas sharing the same table.
6
+ * This is the primary API for single-table design support.
7
+ *
8
+ * @param schemas - Array of .bprint schemas for entities in this table
9
+ * @param packageName - Java package name for generated code
10
+ * @param outputDir - Output directory for generated files
11
+ * @param tableMetadata - Table metadata (name, ARN, region, keys)
12
+ */
13
+ generateForTable(schemas: any[], packageName: string, outputDir: string, tableMetadata?: any): Promise<void>;
14
+ }
15
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AASA,qBAAa,aAAa;IACxB,OAAO,CAAC,iBAAiB,CAAS;;IAYlC;;;;;;;;OAQG;IACG,gBAAgB,CACpB,OAAO,EAAE,GAAG,EAAE,EACd,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,MAAM,EACjB,aAAa,CAAC,EAAE,GAAG,GAClB,OAAO,CAAC,IAAI,CAAC;CAyFjB"}
package/dist/index.js ADDED
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.JavaGenerator = void 0;
30
+ const child_process_1 = require("child_process");
31
+ const path = __importStar(require("path"));
32
+ const fs = __importStar(require("fs"));
33
+ const os = __importStar(require("os"));
34
+ const chalk_1 = __importDefault(require("chalk"));
35
+ // Threshold for using file-based schema passing (100KB)
36
+ const FILE_THRESHOLD_BYTES = 100000;
37
+ class JavaGenerator {
38
+ constructor() {
39
+ // Path to the Java generator JAR
40
+ // When published: dist/jars/codegen-java-0.1.0.jar (bundled during build)
41
+ // During development: codegen-java/build/libs/codegen-java-0.1.0.jar
42
+ const bundledJar = path.join(__dirname, 'jars', 'codegen-java-0.1.0.jar');
43
+ const devJar = path.join(__dirname, '../codegen-java/build/libs/codegen-java-0.1.0.jar');
44
+ this.javaGeneratorPath = fs.existsSync(bundledJar) ? bundledJar : devJar;
45
+ }
46
+ /**
47
+ * Generate code for multiple schemas sharing the same table.
48
+ * This is the primary API for single-table design support.
49
+ *
50
+ * @param schemas - Array of .bprint schemas for entities in this table
51
+ * @param packageName - Java package name for generated code
52
+ * @param outputDir - Output directory for generated files
53
+ * @param tableMetadata - Table metadata (name, ARN, region, keys)
54
+ */
55
+ async generateForTable(schemas, packageName, outputDir, tableMetadata) {
56
+ return new Promise((resolve, reject) => {
57
+ // Ensure output directory exists
58
+ if (!fs.existsSync(outputDir)) {
59
+ fs.mkdirSync(outputDir, { recursive: true });
60
+ }
61
+ const schemasJson = JSON.stringify(schemas);
62
+ let tempFile = null;
63
+ // Prepare arguments for Java generator
64
+ const args = [
65
+ '-jar',
66
+ this.javaGeneratorPath,
67
+ ];
68
+ // Use file-based passing for large payloads
69
+ if (schemasJson.length > FILE_THRESHOLD_BYTES) {
70
+ tempFile = path.join(os.tmpdir(), `chaim-schemas-${Date.now()}.json`);
71
+ fs.writeFileSync(tempFile, schemasJson);
72
+ args.push('--schemas-file', tempFile);
73
+ }
74
+ else {
75
+ args.push('--schemas', schemasJson);
76
+ }
77
+ args.push('--package', packageName);
78
+ args.push('--output', outputDir);
79
+ if (tableMetadata) {
80
+ args.push('--table-metadata', JSON.stringify(tableMetadata));
81
+ }
82
+ // Spawn Java process
83
+ const javaProcess = (0, child_process_1.spawn)('java', args, {
84
+ stdio: ['pipe', 'pipe', 'pipe']
85
+ });
86
+ let stdout = '';
87
+ let stderr = '';
88
+ javaProcess.stdout.on('data', (data) => {
89
+ stdout += data.toString();
90
+ });
91
+ javaProcess.stderr.on('data', (data) => {
92
+ stderr += data.toString();
93
+ });
94
+ javaProcess.on('close', (code) => {
95
+ // Clean up temp file if used
96
+ if (tempFile && fs.existsSync(tempFile)) {
97
+ try {
98
+ fs.unlinkSync(tempFile);
99
+ }
100
+ catch {
101
+ // Ignore cleanup errors
102
+ }
103
+ }
104
+ if (code === 0) {
105
+ if (stdout) {
106
+ console.log(chalk_1.default.gray(stdout));
107
+ }
108
+ resolve();
109
+ }
110
+ else {
111
+ console.error(chalk_1.default.red('Java generator failed:'));
112
+ if (stderr) {
113
+ console.error(chalk_1.default.red(stderr));
114
+ }
115
+ if (stdout) {
116
+ console.error(chalk_1.default.red(stdout));
117
+ }
118
+ reject(new Error(`Java generator exited with code ${code}`));
119
+ }
120
+ });
121
+ javaProcess.on('error', (error) => {
122
+ // Clean up temp file on error
123
+ if (tempFile && fs.existsSync(tempFile)) {
124
+ try {
125
+ fs.unlinkSync(tempFile);
126
+ }
127
+ catch {
128
+ // Ignore cleanup errors
129
+ }
130
+ }
131
+ console.error(chalk_1.default.red('Failed to start Java generator:'), error.message);
132
+ reject(error);
133
+ });
134
+ });
135
+ }
136
+ }
137
+ exports.JavaGenerator = JavaGenerator;
138
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,iDAAsC;AACtC,2CAA6B;AAC7B,uCAAyB;AACzB,uCAAyB;AACzB,kDAA0B;AAE1B,wDAAwD;AACxD,MAAM,oBAAoB,GAAG,MAAM,CAAC;AAEpC,MAAa,aAAa;IAGxB;QACE,iCAAiC;QACjC,0EAA0E;QAC1E,qEAAqE;QACrE,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,wBAAwB,CAAC,CAAC;QAC1E,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,mDAAmD,CAAC,CAAC;QAEzF,IAAI,CAAC,iBAAiB,GAAG,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC;IAC3E,CAAC;IAED;;;;;;;;OAQG;IACH,KAAK,CAAC,gBAAgB,CACpB,OAAc,EACd,WAAmB,EACnB,SAAiB,EACjB,aAAmB;QAEnB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACrC,iCAAiC;YACjC,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,SAAS,CAAC,EAAE;gBAC7B,EAAE,CAAC,SAAS,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;aAC9C;YAED,MAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;YA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AK,CAAC,GAAG,CAAC,iCAAiC,CAAC,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;gBAC3E,MAAM,CAAC,KAAK,CAAC,CAAC;YAChB,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AApHD,sCAoHC"}
Binary file
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@chaim-tools/client-java",
3
+ "version": "0.1.0",
4
+ "description": "Java code generation and SDK creation for Chaim schemas",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist",
9
+ "README.md",
10
+ "LICENSE"
11
+ ],
12
+ "engines": {
13
+ "node": ">=18"
14
+ },
15
+ "scripts": {
16
+ "build": "npm run build:java && npm run build:ts && npm run bundle:jar",
17
+ "build:java": "./gradlew build",
18
+ "build:ts": "tsc",
19
+ "bundle:jar": "mkdir -p dist/jars && cp codegen-java/build/libs/codegen-java-*.jar dist/jars/",
20
+ "clean": "./gradlew clean && rm -rf dist",
21
+ "test": "./gradlew test",
22
+ "test:java": "./gradlew test",
23
+ "lint": "eslint . --ext .ts",
24
+ "lint:fix": "eslint . --ext .ts --fix"
25
+ },
26
+ "keywords": [
27
+ "chaim",
28
+ "java",
29
+ "code-generation",
30
+ "dynamodb",
31
+ "sdk",
32
+ "schema"
33
+ ],
34
+ "author": "Chaim Builder",
35
+ "license": "Apache-2.0",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "https://github.com/chaim-tools/chaim-client-java.git"
39
+ },
40
+ "bugs": {
41
+ "url": "https://github.com/chaim-tools/chaim-client-java/issues"
42
+ },
43
+ "homepage": "https://github.com/chaim-tools/chaim-client-java#readme",
44
+ "dependencies": {
45
+ "@chaim-tools/chaim-bprint-spec": "workspace:^0.2.0",
46
+ "chalk": "^4.1.2"
47
+ },
48
+ "devDependencies": {
49
+ "@types/node": "^20.0.0",
50
+ "typescript": "^5.0.0",
51
+ "eslint": "^8.0.0",
52
+ "@typescript-eslint/eslint-plugin": "^6.21.0",
53
+ "@typescript-eslint/parser": "^6.21.0"
54
+ }
55
+ }