cloesce 0.0.3-fix.3 → 0.0.3-fix.6

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/dist/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/dist/README.md ADDED
@@ -0,0 +1,403 @@
1
+ # cloesce (experimental, `v0.0.3`)
2
+
3
+ Cloesce is a full stack compiler for the Cloudflare developer platform, allowing class definitions in high level languages to serve as the metadata basis for databases, a backend REST API, a frontend API client, and Cloudflare infrastructure.
4
+
5
+ Cloesce is working towards an alpha MVP (v0.1.0), with the general milestones being [here](https://cloesce.pages.dev/schreiber/v0.1.0_milestones/).
6
+
7
+ Internal documentation going over design decisions and general thoughts for each milestone can be found [here](https://cloesce.pages.dev/).
8
+
9
+ # Documentation `v0.0.3`
10
+
11
+ Note that this version is very unstable (ie, it passes our set of happy-path tests).
12
+
13
+ ## Getting Started
14
+
15
+ `v0.0.3` supports only Typescript-to-Typescript projects. An example project is shown [here](https://github.com/bens-schreiber/cloesce/tree/main/examples).
16
+
17
+ 1. NPM
18
+
19
+ - Create an NPM project and install cloesce
20
+
21
+ ```sh
22
+ npm i cloesce@0.0.3-fix.3
23
+ ```
24
+
25
+ 2. TypeScript
26
+
27
+ - Create a `tsconfig.json` with the following values:
28
+
29
+ ```json
30
+ {
31
+ "compilerOptions": {
32
+ // ...
33
+ "resolveJsonModule": true,
34
+ "strict": true,
35
+ "strictPropertyInitialization": false,
36
+ "experimentalDecorators": true,
37
+ "emitDecoratorMetadata": true
38
+ },
39
+ "include": ["<your_src_dir>/**/*.ts", ".generated/*.ts"]
40
+ }
41
+ ```
42
+
43
+ 3. Cloesce Config
44
+
45
+ - Create a `cloesce.config.json` with the following values:
46
+
47
+ ```json
48
+ {
49
+ "source": "./src", // or whatever src you want
50
+ "workersUrl": "http://localhost:5002/api", // or whatever url you want
51
+ "clientUrl": "http://localhost:5002/api"
52
+ }
53
+ ```
54
+
55
+ 4. Vite
56
+
57
+ - `v0.0.3` does not yet support middleware, so you'll run into CORs problems. A vite proxy in some `vite.config.ts` can fix this:
58
+
59
+ ```ts
60
+ import { defineConfig } from "vite";
61
+
62
+ export default defineConfig({
63
+ server: {
64
+ port: 5173,
65
+ proxy: {
66
+ "/api": {
67
+ target: "http://localhost:5000",
68
+ changeOrigin: true,
69
+ },
70
+ },
71
+ },
72
+ });
73
+ ```
74
+
75
+ 5. Wrangler Config
76
+
77
+ - `v0.0.3` will generate the required areas of your wrangler config. A full config looks like this:
78
+
79
+ ```toml
80
+ compatibility_date = "2025-10-02"
81
+ main = ".generated/workers.ts"
82
+ name = "example"
83
+
84
+ [[d1_databases]]
85
+ binding = "db"
86
+ database_id = "..."
87
+ database_name = "example"
88
+ ```
89
+
90
+ ## A Simple Model
91
+
92
+ A model is a type which represents a database table, database view, backend api, frontend client and Cloudflare infrastructure (D1 + Workers).
93
+
94
+ Suprisingly, it's pretty compact. A basic scalar model (being, without foreign keys) looks like this:
95
+
96
+ ```ts
97
+ // horse.cloesce.ts
98
+
99
+ @D1
100
+ export class Horse {
101
+ @PrimaryKey
102
+ id: number;
103
+
104
+ name: string | null;
105
+
106
+ @POST
107
+ async neigh(): Promise<string> {
108
+ return `i am ${this.name}, this is my horse noise`;
109
+ }
110
+ }
111
+ ```
112
+
113
+ - `@D1` denotes that this is a SQL Table
114
+ - `@PrimaryKey` sets the SQL primary key. All models require a primary key.
115
+ - `@POST` reveals the method as an API endpoint with the `POST` HTTP Verb.
116
+
117
+ After running `cloesce run`, you will get a fully generated project that can be ran with:
118
+
119
+ ```sh
120
+ # migrate wrangler
121
+ npx wrangler d1 migrations apply proj-name
122
+
123
+ # build
124
+ npx wrangler build
125
+
126
+ # run wrangler
127
+ npx wrangler dev --port 5000
128
+ ```
129
+
130
+ Note the output in the `.generated/` dir:
131
+
132
+ - `client.ts` is an importable API with all of your backend types and endpoints
133
+ - `migrations/*.sql` is the generated SQL code (note, migrations beyond the initial aren't really supported yet)
134
+ - `workers.ts` is the workers entrypoint.
135
+
136
+ ## Features
137
+
138
+ ### Wrangler Environment
139
+
140
+ In order to interact with your database, you will need to define a WranglerEnv
141
+
142
+ ```ts
143
+ // horse.cloesce.ts
144
+
145
+ @WranglerEnv
146
+ export class Env {
147
+ db: D1Database; // only one DB is supported for now-- make sure it matches the name in `wrangler.toml`
148
+
149
+ // you can also define values in the toml under [[vars]]
150
+ motd: string;
151
+ }
152
+ ```
153
+
154
+ The wrangler environment is dependency injected into your method calls:
155
+
156
+ ```ts
157
+ @D1
158
+ export class Horse {
159
+ @PrimaryKey
160
+ id: number;
161
+
162
+ @POST
163
+ async neigh(@Inject env: WranglerEnv): Promise<string> {
164
+ env.db.prepare(...);
165
+
166
+ return `i am ${this.name}, this is my horse noise`;
167
+ }
168
+ }
169
+ ```
170
+
171
+ ## Foreign Keys, One to One, Data Sources
172
+
173
+ More complex model relationships are permitted via the `@ForeignKey`, `@OneToOne / @OneToMany @ManyToMany` and `@DataSource` decorators.
174
+ Foreign keys are scalar attributes which must reference some other model's primary key:
175
+
176
+ ```ts
177
+ @D1
178
+ export class B {
179
+ @PrimaryKey
180
+ id: number;
181
+ }
182
+
183
+ @D1
184
+ export class A {
185
+ @PrimaryKey
186
+ id: number;
187
+
188
+ @ForeignKey(B)
189
+ bId: number;
190
+ }
191
+ ```
192
+
193
+ This representation is true to the underlying SQL table: `A` has a column `bId` which is a foreign key to `B`. Cloesce allows you to actually join these tables together in your model representation:
194
+
195
+ ```ts
196
+ @D1
197
+ export class B {
198
+ @PrimaryKey
199
+ id: number;
200
+ }
201
+
202
+ @D1
203
+ export class A {
204
+ @PrimaryKey
205
+ id: number;
206
+
207
+ @ForeignKey(B)
208
+ bId: number;
209
+
210
+ @OneToOne("bId") // references A.bId
211
+ b: B | undefined; // This value is a "navigation property", which may or may not exist at runtime
212
+ }
213
+ ```
214
+
215
+ In `v0.0.3`, there are no defaults, only very explicit decisons. Because of that, navigation properties won't exist at runtime unless you tell them to. Cloesce does this via a `DataSource`, which describes the foreign key dependencies you wish to include. All scalar properties are included by default and cannot be excluded.
216
+
217
+ ```ts
218
+ @D1
219
+ export class B {
220
+ @PrimaryKey
221
+ id: number;
222
+ }
223
+
224
+ @D1
225
+ export class A {
226
+ @PrimaryKey
227
+ id: number;
228
+
229
+ @ForeignKey(B)
230
+ bId: number;
231
+
232
+ @OneToOne("bId")
233
+ b: B | undefined;
234
+
235
+ @DataSource
236
+ static readonly default: IncludeTree<A> = {
237
+ b: {}, // says: on model population, join A's B
238
+ };
239
+ }
240
+ ```
241
+
242
+ Datasources are just SQL views and can be invoked in your queries. They are aliased in such a way that its identical to object properties. The frontend chooses which datasource to use in it's API client. `null` is a valid option, meaning no joins will occur.
243
+
244
+ ```ts
245
+ @D1
246
+ export class A {
247
+ @PrimaryKey
248
+ id: number;
249
+
250
+ @ForeignKey(B)
251
+ bId: number;
252
+
253
+ @OneToOne("bId")
254
+ b: B | undefined;
255
+
256
+ @DataSource
257
+ static readonly default: IncludeTree<A> = {
258
+ b: {},
259
+ };
260
+
261
+ @GET
262
+ static async get(id: number, @Inject env: WranglerEnv): Promise<A> {
263
+ let records = await env.db
264
+ .prepare("SELECT * FROM [A.default] WHERE [A.id] = ?") // A.default is the SQL view generated from the IncludeTree
265
+ .bind(id)
266
+ .run();
267
+
268
+ // modelsFromSql is a provided function to turn sql rows into an object.
269
+ // More ORM functions will be expanded on in v0.0.4.
270
+ return modelsFromSql(A, records.results, A.default)[0] as A;
271
+ }
272
+ }
273
+ ```
274
+
275
+ Note: In later versions, nearly all of the code from the example above won't be needed (we can usually infer primary keys, foreign keys, relationships, have default made include trees, and generate CRUD methods like `get`).
276
+
277
+ ### One to Many
278
+
279
+ Cloesce supports models with `1:M` relationships:
280
+
281
+ ```ts
282
+ @D1
283
+ export class Person {
284
+ @PrimaryKey
285
+ id: number;
286
+
287
+ @OneToMany("personId") // directly references the FK on Dog
288
+ dogs: Dog[];
289
+
290
+ @DataSource
291
+ static readonly default: IncludeTree<Person> = {
292
+ dogs: {
293
+ person: {
294
+ dogs: {
295
+ // essentially means: "When you get a person, get their dogs, and get all of those dog's Person, ..."
296
+ // we could go on as long as we want
297
+ },
298
+ },
299
+ },
300
+ };
301
+ }
302
+
303
+ @D1
304
+ export class Dog {
305
+ @PrimaryKey
306
+ id: number;
307
+
308
+ @ForeignKey(Person)
309
+ personId: number;
310
+
311
+ // optional navigation property, not needed.
312
+ @OneToOne("personId")
313
+ person: Person | undefined;
314
+ }
315
+ ```
316
+
317
+ ### Many to Many
318
+
319
+ NOTE: `M:M` relationships have a [bug](https://github.com/bens-schreiber/cloesce/issues/88) in `v0.0.3`, but the syntax is as follows:
320
+
321
+ ```ts
322
+ @D1
323
+ export class Student {
324
+ @PrimaryKey
325
+ id: number;
326
+
327
+ @ManyToMany("StudentsCourses") // unique ID for the generated junction table
328
+ courses: Course[];
329
+ }
330
+
331
+ @D1
332
+ export class Course {
333
+ @PrimaryKey
334
+ id: number;
335
+
336
+ @ManyToMany("StudentsCourses")
337
+ students: Student[];
338
+ }
339
+ ```
340
+
341
+ ### Plain Old Objects
342
+
343
+ Simple non-model objects can be returned and serialized from a model method:
344
+
345
+ ```ts
346
+ @PlainOldObject
347
+ export class CatStuff {
348
+ catFacts: string[],
349
+ catNames: string[],
350
+ }
351
+
352
+ @D1
353
+ export class Cat {
354
+ @PrimaryKey
355
+ id: number;
356
+
357
+ @GET
358
+ async query(): Promise<CatStuff> {
359
+ return {
360
+ catFacts: ["cats r cool"],
361
+ catNames: ["reginald"]
362
+ }
363
+ }
364
+ }
365
+ ```
366
+
367
+ ### HttpResult
368
+
369
+ Methods can return any kind of status code via the `HttpResult` wrapper:
370
+
371
+ ```ts
372
+ @D1
373
+ class Foo {
374
+ ...
375
+
376
+ @GET
377
+ async foo(): Promise<HttpResult<number>> {
378
+ return { ok: false, status: 500, message: "divided by 0"};
379
+ }
380
+ }
381
+ ```
382
+
383
+ # Testing the Compiler
384
+
385
+ ## Unit Tests
386
+
387
+ - `src/extractor/ts` run `npm test`
388
+ - `src/generator` run `cargo test`
389
+
390
+ ## Integration Tests
391
+
392
+ - To run the regression tests: `cargo run --bin test regression`
393
+ - To run the pass fail extractor tests: `cargo run --bin test run-fail`
394
+
395
+ Optionally, pass `--check` if new snapshots should not be created.
396
+
397
+ ## E2E
398
+
399
+ - `tests/e2e` run `npm test`
400
+
401
+ ## Code Formatting
402
+
403
+ - `cargo fmt`, `cargo clippy`, `npm run format:fix`
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
@@ -5,8 +5,8 @@ import { readFile } from "fs/promises";
5
5
  import path from "node:path";
6
6
  import { command, run, subcommands, flag, option, optional, string, } from "cmd-ts";
7
7
  import { Project } from "ts-morph";
8
- import { CidlExtractor } from "./extract.js";
9
- import { ExtractorError, ExtractorErrorCode, getErrorInfo } from "../common.js";
8
+ import { CidlExtractor } from "./extractor/extract.js";
9
+ import { ExtractorError, ExtractorErrorCode, getErrorInfo } from "./common.js";
10
10
  const cmds = subcommands({
11
11
  name: "cloesce",
12
12
  cmds: {
@@ -28,7 +28,6 @@ const cmds = subcommands({
28
28
  }
29
29
  // Creates a `cidl.json` file. Exits the process on failure.
30
30
  await extract({ debug: args.debug });
31
- const root = process.cwd();
32
31
  const outputDir = config.outputDir ?? ".generated";
33
32
  const allConfig = {
34
33
  name: "all",
@@ -37,8 +36,8 @@ const cmds = subcommands({
37
36
  "generate",
38
37
  "all",
39
38
  path.join(outputDir, "cidl.json"),
40
- path.join(root, "wrangler.toml"),
41
- path.join(root, "migrations/migrations.sql"),
39
+ "wrangler.toml",
40
+ "migrations/migrations.sql",
42
41
  path.join(outputDir, "workers.ts"),
43
42
  path.join(outputDir, "client.ts"),
44
43
  config.clientUrl,
@@ -54,11 +53,10 @@ const cmds = subcommands({
54
53
  description: "Generate wrangler.toml configuration",
55
54
  args: {},
56
55
  handler: async () => {
57
- const root = process.cwd();
58
56
  await generate({
59
57
  name: "wrangler",
60
58
  wasmFile: "generator.wasm",
61
- args: ["generate", "wrangler", path.join(root, "wrangler.toml")],
59
+ args: ["generate", "wrangler", "wrangler.toml"],
62
60
  });
63
61
  },
64
62
  }),
@@ -68,7 +66,6 @@ const cmds = subcommands({
68
66
  args: {},
69
67
  handler: async () => {
70
68
  const config = loadCloesceConfig(process.cwd());
71
- const root = process.cwd();
72
69
  const outputDir = config.outputDir ?? ".generated";
73
70
  await generate({
74
71
  name: "d1",
@@ -77,7 +74,7 @@ const cmds = subcommands({
77
74
  "generate",
78
75
  "d1",
79
76
  path.join(outputDir, "cidl.json"),
80
- path.join(root, "migrations/migrations.sql"),
77
+ "migrations/migrations.sql",
81
78
  ],
82
79
  });
83
80
  },
@@ -88,10 +85,9 @@ const cmds = subcommands({
88
85
  args: {},
89
86
  handler: async () => {
90
87
  const config = loadCloesceConfig(process.cwd());
91
- const root = process.cwd();
92
88
  const outputDir = config.outputDir ?? ".generated";
93
89
  if (!config.workersUrl) {
94
- console.error("Error: workersUrl must be defined in cloesce-config.json");
90
+ console.error("Error: workersUrl must be defined in cloesce.config.json");
95
91
  process.exit(1);
96
92
  }
97
93
  await generate({
@@ -102,7 +98,7 @@ const cmds = subcommands({
102
98
  "workers",
103
99
  path.join(outputDir, "cidl.json"),
104
100
  path.join(outputDir, "workers.ts"),
105
- path.join(root, "wrangler.toml"),
101
+ "wrangler.toml",
106
102
  config.workersUrl,
107
103
  ],
108
104
  });
@@ -238,32 +234,13 @@ async function generate(config) {
238
234
  if (!fs.existsSync(wranglerPath)) {
239
235
  fs.writeFileSync(wranglerPath, "");
240
236
  }
241
- const wasiArgs = config.args.map((arg) => {
242
- // Skip URLs
243
- if (/^[a-zA-Z]+:\/\//.test(arg)) {
244
- return arg;
245
- }
246
- // Convert file path it to Unix style
247
- if (arg.includes(path.sep) || arg.includes("/")) {
248
- // Convert to relative path from root
249
- const relativePath = path.isAbsolute(arg)
250
- ? path.relative(root, arg)
251
- : arg;
252
- // Convert Windows separators to Unix and ensure leading slash
253
- const unixPath = relativePath.replace(/\\/g, "/");
254
- return unixPath.startsWith("/") ? unixPath : "/" + unixPath;
255
- }
256
- return arg;
257
- });
258
237
  const wasi = new WASI({
259
238
  version: "preview1",
260
- args: ["generate", ...wasiArgs],
239
+ args: ["generate", ...config.args],
261
240
  env: { ...process.env, ...config.env },
262
- preopens: { "/": root },
241
+ preopens: { ".": root },
263
242
  });
264
- // Since `generator.wasm` is a binary and not a library, it must be
265
- // manually read
266
- const wasm = await readFile(new URL("../generator.wasm", import.meta.url));
243
+ const wasm = await readFile(new URL("./generator.wasm", import.meta.url));
267
244
  const mod = await WebAssembly.compile(new Uint8Array(wasm));
268
245
  let instance = await WebAssembly.instantiate(mod, {
269
246
  wasi_snapshot_preview1: wasi.wasiImport,
@@ -0,0 +1,126 @@
1
+ export type Either<L, R> = {
2
+ ok: false;
3
+ value: L;
4
+ } | {
5
+ ok: true;
6
+ value: R;
7
+ };
8
+ export declare function left<L>(value: L): Either<L, never>;
9
+ export declare function right<R>(value: R): Either<never, R>;
10
+ export declare enum ExtractorErrorCode {
11
+ UnknownType = 0,
12
+ MultipleGenericType = 1,
13
+ InvalidIncludeTree = 2,
14
+ UnknownNavigationPropertyReference = 3,
15
+ InvalidNavigationPropertyReference = 4,
16
+ MissingNavigationPropertyReference = 5,
17
+ MissingManyToManyUniqueId = 6,
18
+ MissingPrimaryKey = 7,
19
+ MissingWranglerEnv = 8,
20
+ TooManyWranglerEnvs = 9,
21
+ MissingFile = 10
22
+ }
23
+ export declare function getErrorInfo(code: ExtractorErrorCode): {
24
+ description: string;
25
+ suggestion: string;
26
+ };
27
+ export declare class ExtractorError {
28
+ code: ExtractorErrorCode;
29
+ context?: string;
30
+ snippet?: string;
31
+ constructor(code: ExtractorErrorCode);
32
+ addContext(fn: (val: string | undefined) => string | undefined): void;
33
+ }
34
+ export type HttpResult<T = unknown> = {
35
+ ok: boolean;
36
+ status: number;
37
+ data?: T;
38
+ message?: string;
39
+ };
40
+ export type CidlType = "Void" | "Integer" | "Real" | "Text" | "Blob" | {
41
+ Inject: string;
42
+ } | {
43
+ Object: string;
44
+ } | {
45
+ Nullable: CidlType;
46
+ } | {
47
+ Array: CidlType;
48
+ } | {
49
+ HttpResult: CidlType;
50
+ };
51
+ export declare function isNullableType(ty: CidlType): boolean;
52
+ export declare enum HttpVerb {
53
+ GET = "GET",
54
+ POST = "POST",
55
+ PUT = "PUT",
56
+ PATCH = "PATCH",
57
+ DELETE = "DELETE"
58
+ }
59
+ export interface NamedTypedValue {
60
+ name: string;
61
+ cidl_type: CidlType;
62
+ }
63
+ export interface ModelAttribute {
64
+ value: NamedTypedValue;
65
+ foreign_key_reference: string | null;
66
+ }
67
+ export interface ModelMethod {
68
+ name: string;
69
+ is_static: boolean;
70
+ http_verb: HttpVerb;
71
+ return_type: CidlType | null;
72
+ parameters: NamedTypedValue[];
73
+ }
74
+ export type NavigationPropertyKind = {
75
+ OneToOne: {
76
+ reference: string;
77
+ };
78
+ } | {
79
+ OneToMany: {
80
+ reference: string;
81
+ };
82
+ } | {
83
+ ManyToMany: {
84
+ unique_id: string;
85
+ };
86
+ };
87
+ export interface NavigationProperty {
88
+ var_name: string;
89
+ model_name: string;
90
+ kind: NavigationPropertyKind;
91
+ }
92
+ export declare function getNavigationPropertyCidlType(nav: NavigationProperty): CidlType;
93
+ export interface Model {
94
+ name: string;
95
+ primary_key: NamedTypedValue;
96
+ attributes: ModelAttribute[];
97
+ navigation_properties: NavigationProperty[];
98
+ methods: Record<string, ModelMethod>;
99
+ data_sources: Record<string, DataSource>;
100
+ source_path: string;
101
+ }
102
+ export interface PlainOldObject {
103
+ name: string;
104
+ attributes: NamedTypedValue[];
105
+ source_path: string;
106
+ }
107
+ export interface CidlIncludeTree {
108
+ [key: string]: CidlIncludeTree;
109
+ }
110
+ export interface DataSource {
111
+ name: string;
112
+ tree: CidlIncludeTree;
113
+ }
114
+ export interface WranglerEnv {
115
+ name: string;
116
+ source_path: string;
117
+ }
118
+ export interface CloesceAst {
119
+ version: string;
120
+ project_name: string;
121
+ language: "TypeScript";
122
+ wrangler_env: WranglerEnv;
123
+ models: Record<string, Model>;
124
+ poos: Record<string, PlainOldObject>;
125
+ }
126
+ //# sourceMappingURL=common.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.d.ts","sourceRoot":"","sources":["../src/common.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,MAAM,CAAC,CAAC,EAAE,CAAC,IAAI;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,CAAC;AAC5E,wBAAgB,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,CAAC,CAAC,EAAE,KAAK,CAAC,CAElD;AACD,wBAAgB,KAAK,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAEnD;AAED,oBAAY,kBAAkB;IAC5B,WAAW,IAAA;IACX,mBAAmB,IAAA;IACnB,kBAAkB,IAAA;IAClB,kCAAkC,IAAA;IAClC,kCAAkC,IAAA;IAClC,kCAAkC,IAAA;IAClC,yBAAyB,IAAA;IACzB,iBAAiB,IAAA;IACjB,kBAAkB,IAAA;IAClB,mBAAmB,IAAA;IACnB,WAAW,KAAA;CACZ;AAyDD,wBAAgB,YAAY,CAAC,IAAI,EAAE,kBAAkB;iBArDpC,MAAM;gBAAc,MAAM;EAuD1C;AAED,qBAAa,cAAc;IAIN,IAAI,EAAE,kBAAkB;IAH3C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MA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CAAC;IACvB,YAAY,EAAE,WAAW,CAAC;IAC1B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IAC9B,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;CACtC"}
@@ -0,0 +1,15 @@
1
+ import { Project } from "ts-morph";
2
+ import { CloesceAst, Either, ExtractorError } from "../common.js";
3
+ export declare class CidlExtractor {
4
+ projectName: string;
5
+ version: string;
6
+ constructor(projectName: string, version: string);
7
+ extract(project: Project): Either<ExtractorError, CloesceAst>;
8
+ private static model;
9
+ private static poo;
10
+ private static readonly primTypeMap;
11
+ private static cidlType;
12
+ private static includeTree;
13
+ private static method;
14
+ }
15
+ //# sourceMappingURL=extract.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extract.d.ts","sourceRoot":"","sources":["../../src/extractor/extract.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,OAAO,EASR,MAAM,UAAU,CAAC;AAElB,OAAO,EAEL,UAAU,EAGV,MAAM,EAUN,cAAc,EAGf,MAAM,cAAc,CAAC;AAsBtB,qBAAa,aAAa;IAEf,WAAW,EAAE,MAAM;IACnB,OAAO,EAAE,MAAM;gBADf,WAAW,EAAE,MAAM,EACnB,OAAO,EAAE,MAAM;IAGxB,OAAO,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,CAAC,cAAc,EAAE,UAAU,CAAC;IAuE7D,OAAO,CAAC,MAAM,CAAC,KAAK;IA6MpB,OAAO,CAAC,MAAM,CAAC,GAAG;IAgClB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,WAAW,CAQjC;IAEF,OAAO,CAAC,MAAM,CAAC,QAAQ;IAoGvB,OAAO,CAAC,MAAM,CAAC,WAAW;IAqF1B,OAAO,CAAC,MAAM,CAAC,MAAM;CA+DtB"}
Binary file
@@ -0,0 +1,22 @@
1
+ export { cloesce, modelsFromSql } from "../runtime/runtime.js";
2
+ export type { HttpResult, Either } from "../common.js";
3
+ export declare const D1: ClassDecorator;
4
+ export declare const PlainOldObject: ClassDecorator;
5
+ export declare const WranglerEnv: ClassDecorator;
6
+ export declare const PrimaryKey: PropertyDecorator;
7
+ export declare const GET: MethodDecorator;
8
+ export declare const POST: MethodDecorator;
9
+ export declare const PUT: MethodDecorator;
10
+ export declare const PATCH: MethodDecorator;
11
+ export declare const DELETE: MethodDecorator;
12
+ export declare const DataSource: PropertyDecorator;
13
+ export declare const OneToMany: (_: string) => PropertyDecorator;
14
+ export declare const OneToOne: (_: string) => PropertyDecorator;
15
+ export declare const ManyToMany: (_: string) => PropertyDecorator;
16
+ export declare const ForeignKey: <T>(_: T) => PropertyDecorator;
17
+ export declare const Inject: ParameterDecorator;
18
+ type Primitive = string | number | boolean | bigint | symbol | null | undefined;
19
+ export type IncludeTree<T> = T extends Primitive ? never : {
20
+ [K in keyof T]?: T[K] extends (infer U)[] ? IncludeTree<NonNullable<U>> : IncludeTree<NonNullable<T[K]>>;
21
+ };
22
+ //# sourceMappingURL=backend.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backend.d.ts","sourceRoot":"","sources":["../../src/index/backend.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAC/D,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAGvD,eAAO,MAAM,EAAE,EAAE,cAAyB,CAAC;AAC3C,eAAO,MAAM,cAAc,EAAE,cAAyB,CAAC;AACvD,eAAO,MAAM,WAAW,EAAE,cAAyB,CAAC;AACpD,eAAO,MAAM,UAAU,EAAE,iBAA4B,CAAC;AACtD,eAAO,MAAM,GAAG,EAAE,eAA0B,CAAC;AAC7C,eAAO,MAAM,IAAI,EAAE,eAA0B,CAAC;AAC9C,eAAO,MAAM,GAAG,EAAE,eAA0B,CAAC;AAC7C,eAAO,MAAM,KAAK,EAAE,eAA0B,CAAC;AAC/C,eAAO,MAAM,MAAM,EAAE,eAA0B,CAAC;AAChD,eAAO,MAAM,UAAU,EAAE,iBAA4B,CAAC;AACtD,eAAO,MAAM,SAAS,GACnB,GAAG,MAAM,KAAG,iBACL,CAAC;AACX,eAAO,MAAM,QAAQ,GAClB,GAAG,MAAM,KAAG,iBACL,CAAC;AACX,eAAO,MAAM,UAAU,GACpB,GAAG,MAAM,KAAG,iBACL,CAAC;AACX,eAAO,MAAM,UAAU,GACpB,CAAC,EAAE,GAAG,CAAC,KAAG,iBACH,CAAC;AACX,eAAO,MAAM,MAAM,EAAE,kBAA6B,CAAC;AAGnD,KAAK,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;AAChF,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI,CAAC,SAAS,SAAS,GAC5C,KAAK,GACL;KACG,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,EAAE,GACrC,WAAW,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,GAC3B,WAAW,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CACnC,CAAC"}
@@ -1,4 +1,4 @@
1
- export { cloesce, modelsFromSql } from "./runtime/runtime.js";
1
+ export { cloesce, modelsFromSql } from "../runtime/runtime.js";
2
2
  // Compiler hints
3
3
  export const D1 = () => { };
4
4
  export const PlainOldObject = () => { };
@@ -15,10 +15,3 @@ export const OneToOne = (_) => () => { };
15
15
  export const ManyToMany = (_) => () => { };
16
16
  export const ForeignKey = (_) => () => { };
17
17
  export const Inject = () => { };
18
- // Helpers
19
- export function instantiateObjectArray(data, ctor) {
20
- if (Array.isArray(data)) {
21
- return data.map((x) => instantiateObjectArray(x, ctor)).flat();
22
- }
23
- return [Object.assign(new ctor(), data)];
24
- }
@@ -0,0 +1,5 @@
1
+ export type { HttpResult, Either } from "../common.js";
2
+ export declare function instantiateObjectArray<T extends object>(data: any, ctor: {
3
+ new (): T;
4
+ }): T[];
5
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/index/client.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAGvD,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,MAAM,EACrD,IAAI,EAAE,GAAG,EACT,IAAI,EAAE;IAAE,QAAQ,CAAC,CAAA;CAAE,GAClB,CAAC,EAAE,CAKL"}
@@ -0,0 +1,7 @@
1
+ // Helpers
2
+ export function instantiateObjectArray(data, ctor) {
3
+ if (Array.isArray(data)) {
4
+ return data.map((x) => instantiateObjectArray(x, ctor)).flat();
5
+ }
6
+ return [Object.assign(new ctor(), data)];
7
+ }
@@ -0,0 +1,112 @@
1
+ import { HttpResult, Either, ModelMethod, CloesceAst, Model } from "../common.js";
2
+ import { IncludeTree } from "../index/backend.js";
3
+ /**
4
+ * Map of model names to their respective constructor.
5
+ *
6
+ * The value accepted into the `cloesce` function is generated by the Cloesce compiler, and
7
+ * is guaranteed to contain all model definitions.
8
+ */
9
+ type ModelConstructorRegistry = Record<string, new () => UserDefinedModel>;
10
+ /**
11
+ * Dependency injection container, mapping an object type name to an instance of that object.
12
+ *
13
+ * The value accepted into the `cloesce` function is generated by the Cloesce compiler, and is
14
+ * guaranteed to contain all injected model method parameters.
15
+ */
16
+ type InstanceRegistry = Map<string, any>;
17
+ /**
18
+ * Users will create Cloesce models, which have metadata for them in the ast.
19
+ * For TypeScript's purposes, these models can be anything. We can assume any
20
+ * `UserDefinedModel` has been verified by the compiler.
21
+ */
22
+ type UserDefinedModel = any;
23
+ /**
24
+ * Given a request, this represents a map of each body / url param name to
25
+ * its actual value. Unknown, as the a request can be anything.
26
+ */
27
+ type RequestParamMap = Record<string, unknown>;
28
+ /**
29
+ * Meta information on the wrangler env and db bindings
30
+ */
31
+ interface MetaWranglerEnv {
32
+ envName: string;
33
+ dbName: string;
34
+ }
35
+ /**
36
+ * WASM ABI
37
+ */
38
+ interface RuntimeWasmExports {
39
+ memory: WebAssembly.Memory;
40
+ get_return_len(): number;
41
+ set_meta_ptr(ptr: number, len: number): number;
42
+ alloc(len: number): number;
43
+ dealloc(ptr: number, len: number): void;
44
+ object_relational_mapping(model_name_ptr: number, model_name_len: number, sql_rows_ptr: number, sql_rows_len: number, include_tree_ptr: number, include_tree_len: number): number;
45
+ }
46
+ /**
47
+ * Singleton instances of the cidl, constructor registry, and wasm binary.
48
+ * These values are guaranteed to never change throughout a program lifetime.
49
+ */
50
+ declare class RuntimeContainer {
51
+ readonly ast: CloesceAst;
52
+ readonly constructorRegistry: ModelConstructorRegistry;
53
+ readonly wasm: RuntimeWasmExports;
54
+ private static instance;
55
+ private constructor();
56
+ static init(ast: CloesceAst, constructorRegistry: ModelConstructorRegistry, wasm?: WebAssembly.Instance): Promise<void>;
57
+ static get(): RuntimeContainer;
58
+ }
59
+ /**
60
+ * Runtime entry point. Given a request, undergoes: routing, validating,
61
+ * hydrating, and method dispatch.
62
+ *
63
+ * @returns A Response with an `HttpResult` JSON body.
64
+ */
65
+ export declare function cloesce(request: Request, ast: CloesceAst, constructorRegistry: ModelConstructorRegistry, instanceRegistry: InstanceRegistry, envMeta: MetaWranglerEnv, api_route: string): Promise<Response>;
66
+ /**
67
+ * Matches a request to a method on a model.
68
+ * @param api_route The route from the domain to the actual API, ie https://foo.com/route/to/api => route/to/api/
69
+ * @returns 404 or a `MatchedRoute`
70
+ */
71
+ declare function matchRoute(request: Request, ast: CloesceAst, api_route: string): Either<HttpResult, {
72
+ model: Model;
73
+ method: ModelMethod;
74
+ id: string | null;
75
+ }>;
76
+ /**
77
+ * Validates the request's body/search params against a ModelMethod
78
+ * @returns 400 or a `RequestParamMap` consisting of each parameters name mapped to its value, and
79
+ * a data source
80
+ */
81
+ declare function validateRequest(request: Request, ast: CloesceAst, model: Model, method: ModelMethod, id: string | null): Promise<Either<HttpResult, {
82
+ params: RequestParamMap;
83
+ dataSource: string | null;
84
+ }>>;
85
+ /**
86
+ * Calls a method on a model given a list of parameters.
87
+ * @returns 500 on an uncaught client error, 200 with a result body on success
88
+ */
89
+ declare function methodDispatch(instance: object, instanceRegistry: InstanceRegistry, envMeta: MetaWranglerEnv, method: ModelMethod, params: Record<string, unknown>): Promise<HttpResult<unknown>>;
90
+ /**
91
+ * Creates model instances given a properly formatted SQL record, being either:
92
+ *
93
+ * 1. Flat, relationship-less (ex: id, name, location, ...)
94
+ * 2. `DataSource` formatted (ex: Horse.id, Horse.name, Horse.rider, ...)
95
+ *
96
+ * @param ctor The type of the model
97
+ * @param records SQL records
98
+ * @param includeTree The include tree to use when parsing the records
99
+ * @returns An instantiated array of `T`, containing one or more objects.
100
+ */
101
+ export declare function modelsFromSql<T extends object>(ctor: new () => T, records: Record<string, any>[], includeTree: IncludeTree<T> | null): T[];
102
+ /**
103
+ * For testing purposes
104
+ */
105
+ export declare const _cloesceInternal: {
106
+ matchRoute: typeof matchRoute;
107
+ validateRequest: typeof validateRequest;
108
+ methodDispatch: typeof methodDispatch;
109
+ RuntimeContainer: typeof RuntimeContainer;
110
+ };
111
+ export {};
112
+ //# sourceMappingURL=runtime.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../src/runtime/runtime.ts"],"names":[],"mappings":"AACA,OAAO,EACL,UAAU,EACV,MAAM,EACN,WAAW,EAIX,UAAU,EAEV,KAAK,EAGN,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAKlD;;;;;GAKG;AACH,KAAK,wBAAwB,GAAG,MAAM,CAAC,MAAM,EAAE,UAAU,gBAAgB,CAAC,CAAC;AAE3E;;;;;GAKG;AACH,KAAK,gBAAgB,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAEzC;;;;G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",
3
+ "version": "0.0.3-fix.6",
4
4
  "description": "A tool to extract and compile TypeScript code into something wrangler can consume and deploy for D1 Databases and Cloudflare Workers",
5
5
  "type": "module",
6
- "main": "./dist/index.js",
7
- "types": "./dist/index.d.ts",
8
6
  "license": "Apache-2.0",
9
7
  "scripts": {
10
8
  "test": "vitest",
11
9
  "format:fix": "prettier --write .",
12
10
  "format": "prettier --check .",
13
11
  "typecheck": "tsc --noEmit",
14
- "build": "tsc -p tsconfig.json && npm run copy-rs-runtime-wasm && npm run copy-generator-wasm",
12
+ "build": "tsc -p tsconfig.json && npm run copy-rs-runtime-wasm && npm run copy-generator-wasm && npm run copy-readme-license",
15
13
  "copy-rs-runtime-wasm": "cp ../../runtime/target/wasm32-unknown-unknown/release/runtime.wasm ./dist/runtime.wasm",
16
- "copy-generator-wasm": "cp ../../generator/target/wasm32-wasip1/release/cli.wasm ./dist/generator.wasm"
14
+ "copy-generator-wasm": "cp ../../generator/target/wasm32-wasip1/release/cli.wasm ./dist/generator.wasm",
15
+ "copy-readme-license": "cp ../../../README.md ./dist/README.md && cp ../../../LICENSE ./dist/LICENSE"
17
16
  },
18
17
  "dependencies": {
19
18
  "cmd-ts": "^0.14.1",
@@ -29,19 +28,26 @@
29
28
  "vite-plugin-wasm": "^3.5.0"
30
29
  },
31
30
  "exports": {
32
- ".": {
33
- "types": "./dist/index.d.ts",
34
- "import": "./dist/index.js"
31
+ "./client": {
32
+ "types": "./dist/index/client.d.ts",
33
+ "import": "./dist/index/client.js"
35
34
  },
36
- "./cli": "./dist/extractor/cli.js"
35
+ "./backend": {
36
+ "types": "./dist/index/backend.d.ts",
37
+ "import": "./dist/index/backend.js"
38
+ }
37
39
  },
38
40
  "bin": {
39
- "cloesce": "dist/extractor/cli.js"
41
+ "cloesce": "dist/cli.js"
42
+ },
43
+ "typesVersions": {
44
+ "*": {
45
+ "backend": ["dist/index/backend.d.ts"],
46
+ "client": ["dist/index/client.d.ts"]
47
+ }
40
48
  },
41
49
  "files": [
42
- "dist/**/*",
43
- "README.md",
44
- "LICENSE"
50
+ "dist/**/*"
45
51
  ],
46
52
  "sideEffects": false,
47
53
  "engines": {