@cedarjs/gqlorm 3.0.0-canary.13429

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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +3 -0
  3. package/dist/cjs/generator/graphqlGenerator.d.ts +24 -0
  4. package/dist/cjs/generator/graphqlGenerator.d.ts.map +1 -0
  5. package/dist/cjs/generator/graphqlGenerator.js +421 -0
  6. package/dist/cjs/live/types.d.ts +262 -0
  7. package/dist/cjs/live/types.d.ts.map +1 -0
  8. package/dist/cjs/live/types.js +16 -0
  9. package/dist/cjs/package.json +1 -0
  10. package/dist/cjs/parser/queryParser.d.ts +27 -0
  11. package/dist/cjs/parser/queryParser.d.ts.map +1 -0
  12. package/dist/cjs/parser/queryParser.js +338 -0
  13. package/dist/cjs/queryBuilder.d.ts +106 -0
  14. package/dist/cjs/queryBuilder.d.ts.map +1 -0
  15. package/dist/cjs/queryBuilder.js +225 -0
  16. package/dist/cjs/react/useLiveQuery.d.ts +12 -0
  17. package/dist/cjs/react/useLiveQuery.d.ts.map +1 -0
  18. package/dist/cjs/react/useLiveQuery.js +62 -0
  19. package/dist/cjs/types/ast.d.ts +80 -0
  20. package/dist/cjs/types/ast.d.ts.map +1 -0
  21. package/dist/cjs/types/ast.js +16 -0
  22. package/dist/cjs/types/orm.d.ts +157 -0
  23. package/dist/cjs/types/orm.d.ts.map +1 -0
  24. package/dist/cjs/types/orm.js +16 -0
  25. package/dist/cjs/types/orm_for_testing.d.ts +44 -0
  26. package/dist/cjs/types/orm_for_testing.d.ts.map +1 -0
  27. package/dist/cjs/types/orm_for_testing.js +16 -0
  28. package/dist/cjs/types/schema.d.ts +4 -0
  29. package/dist/cjs/types/schema.d.ts.map +1 -0
  30. package/dist/cjs/types/schema.js +16 -0
  31. package/dist/cjs/types/typeUtils.d.ts +10 -0
  32. package/dist/cjs/types/typeUtils.d.ts.map +1 -0
  33. package/dist/cjs/types/typeUtils.js +65 -0
  34. package/dist/generator/graphqlGenerator.d.ts +24 -0
  35. package/dist/generator/graphqlGenerator.d.ts.map +1 -0
  36. package/dist/generator/graphqlGenerator.js +399 -0
  37. package/dist/live/types.d.ts +262 -0
  38. package/dist/live/types.d.ts.map +1 -0
  39. package/dist/live/types.js +0 -0
  40. package/dist/parser/queryParser.d.ts +27 -0
  41. package/dist/parser/queryParser.d.ts.map +1 -0
  42. package/dist/parser/queryParser.js +312 -0
  43. package/dist/queryBuilder.d.ts +106 -0
  44. package/dist/queryBuilder.d.ts.map +1 -0
  45. package/dist/queryBuilder.js +196 -0
  46. package/dist/react/useLiveQuery.d.ts +12 -0
  47. package/dist/react/useLiveQuery.d.ts.map +1 -0
  48. package/dist/react/useLiveQuery.js +38 -0
  49. package/dist/types/ast.d.ts +80 -0
  50. package/dist/types/ast.d.ts.map +1 -0
  51. package/dist/types/ast.js +0 -0
  52. package/dist/types/orm.d.ts +157 -0
  53. package/dist/types/orm.d.ts.map +1 -0
  54. package/dist/types/orm.js +0 -0
  55. package/dist/types/orm_for_testing.d.ts +44 -0
  56. package/dist/types/orm_for_testing.d.ts.map +1 -0
  57. package/dist/types/orm_for_testing.js +0 -0
  58. package/dist/types/schema.d.ts +4 -0
  59. package/dist/types/schema.d.ts.map +1 -0
  60. package/dist/types/schema.js +0 -0
  61. package/dist/types/typeUtils.d.ts +10 -0
  62. package/dist/types/typeUtils.d.ts.map +1 -0
  63. package/dist/types/typeUtils.js +34 -0
  64. package/package.json +164 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Cedar
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 ADDED
@@ -0,0 +1,3 @@
1
+ # gqlorm
2
+
3
+ Prisma inspired GraphQL query builder
@@ -0,0 +1,24 @@
1
+ /**
2
+ * GraphQL query generator that converts AST to GraphQL query strings
3
+ * Transforms our internal AST representation into valid GraphQL queries
4
+ */
5
+ import type { QueryAST } from '../types/ast.js';
6
+ import { type ModelSchema } from '../types/schema.js';
7
+ export declare class GraphQLGenerateError extends Error {
8
+ context?: any | undefined;
9
+ constructor(message: string, context?: any | undefined);
10
+ }
11
+ export interface GraphQLQuery {
12
+ query: string;
13
+ variables?: Record<string, any>;
14
+ }
15
+ export declare class GraphQLGenerator {
16
+ #private;
17
+ constructor(schema?: ModelSchema);
18
+ /**
19
+ * Generate GraphQL query from AST
20
+ */
21
+ generate(ast: QueryAST): GraphQLQuery;
22
+ }
23
+ export declare const graphqlGenerator: GraphQLGenerator;
24
+ //# sourceMappingURL=graphqlGenerator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graphqlGenerator.d.ts","sourceRoot":"","sources":["../../../src/generator/graphqlGenerator.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAOV,QAAQ,EAKT,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,KAAK,WAAW,EAAE,MAAM,oBAAoB,CAAA;AAOrD,qBAAa,oBAAqB,SAAQ,KAAK;IAGpC,OAAO,CAAC,EAAE,GAAG;gBADpB,OAAO,EAAE,MAAM,EACR,OAAO,CAAC,EAAE,GAAG,YAAA;CAKvB;AAED,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,MAAM,CAAA;IACb,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;CAChC;AAED,qBAAa,gBAAgB;;gBASf,MAAM,CAAC,EAAE,WAAW;IAIhC;;OAEG;IACH,QAAQ,CAAC,GAAG,EAAE,QAAQ,GAAG,YAAY;CAodtC;AAGD,eAAO,MAAM,gBAAgB,kBAAyB,CAAA"}
@@ -0,0 +1,421 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var graphqlGenerator_exports = {};
20
+ __export(graphqlGenerator_exports, {
21
+ GraphQLGenerateError: () => GraphQLGenerateError,
22
+ GraphQLGenerator: () => GraphQLGenerator,
23
+ graphqlGenerator: () => graphqlGenerator
24
+ });
25
+ module.exports = __toCommonJS(graphqlGenerator_exports);
26
+ var import_typeUtils = require("../types/typeUtils.js");
27
+ class GraphQLGenerateError extends Error {
28
+ constructor(message, context) {
29
+ super(message);
30
+ this.context = context;
31
+ this.name = "GraphQLGenerateError";
32
+ }
33
+ }
34
+ class GraphQLGenerator {
35
+ #variableCounter = 0;
36
+ #variables = {};
37
+ // Track field names for each variable
38
+ #variableFields = /* @__PURE__ */ new Map();
39
+ // Track current operation for context-aware type generation
40
+ #operation;
41
+ #schema;
42
+ constructor(schema) {
43
+ this.#schema = schema;
44
+ }
45
+ /**
46
+ * Generate GraphQL query from AST
47
+ */
48
+ generate(ast) {
49
+ this.#resetState();
50
+ this.#operation = ast.operation;
51
+ const operationName = this.#generateOperationName(ast);
52
+ const queryBody = this.#generateQueryBody(ast);
53
+ let query = `query ${operationName}`;
54
+ const hasVariables = Object.keys(this.#variables).length > 0;
55
+ if (hasVariables) {
56
+ const variableDefinitions = this.#generateVariableDefinitions();
57
+ query += `(${variableDefinitions})`;
58
+ }
59
+ query += ` {
60
+ ${queryBody}
61
+ }`;
62
+ const result = { query };
63
+ if (hasVariables) {
64
+ result.variables = structuredClone(this.#variables);
65
+ }
66
+ return result;
67
+ }
68
+ /**
69
+ * Reset internal state for new query generation
70
+ */
71
+ #resetState() {
72
+ this.#variableCounter = 0;
73
+ this.#variables = {};
74
+ this.#variableFields.clear();
75
+ this.#operation = void 0;
76
+ }
77
+ /**
78
+ * Generate operation name
79
+ */
80
+ #generateOperationName(ast) {
81
+ const { model, operation } = ast;
82
+ return `${operation}${this.#capitalize(model)}`;
83
+ }
84
+ /**
85
+ * Generate main query body
86
+ */
87
+ #generateQueryBody(ast) {
88
+ const { model, operation, args, isLive } = ast;
89
+ const fieldName = this.#getGraphQLFieldName(model, operation);
90
+ let query = ` ${fieldName}`;
91
+ if (args) {
92
+ const argsString = this.#generateArguments(args, operation);
93
+ if (argsString) {
94
+ query += `(${argsString})`;
95
+ }
96
+ }
97
+ if (isLive) {
98
+ query += " @live";
99
+ }
100
+ const fields = this.#generateFieldSelection(args, model);
101
+ query += ` {
102
+ ${fields}
103
+ }`;
104
+ return query;
105
+ }
106
+ /**
107
+ * Convert operation to GraphQL field name
108
+ */
109
+ #getGraphQLFieldName(model, operation) {
110
+ switch (operation) {
111
+ case "findMany":
112
+ return `${model}s`;
113
+ case "findUnique":
114
+ case "findUniqueOrThrow":
115
+ return model;
116
+ case "findFirst":
117
+ case "findFirstOrThrow":
118
+ return model;
119
+ default:
120
+ throw new GraphQLGenerateError(`Unsupported operation: ${operation}`);
121
+ }
122
+ }
123
+ /**
124
+ * Generate GraphQL arguments from query args
125
+ */
126
+ #generateArguments(args, operation) {
127
+ const argParts = [];
128
+ if (args?.where) {
129
+ const isFindUnique = operation === "findUnique" || operation === "findUniqueOrThrow";
130
+ const simpleUniqueArg = isFindUnique ? this.#extractSimpleUniqueArgument(args.where) : null;
131
+ if (simpleUniqueArg) {
132
+ argParts.push(simpleUniqueArg);
133
+ } else {
134
+ const whereArg = this.#generateWhereArgument(args.where);
135
+ if (whereArg && whereArg !== "{}") {
136
+ argParts.push(`where: ${whereArg}`);
137
+ }
138
+ }
139
+ }
140
+ if (args?.orderBy) {
141
+ const orderByArg = this.#generateOrderByArgument(args.orderBy);
142
+ argParts.push(`orderBy: ${orderByArg}`);
143
+ }
144
+ if (typeof args?.take === "number") {
145
+ argParts.push(`first: ${args.take}`);
146
+ }
147
+ if (typeof args?.skip === "number") {
148
+ argParts.push(`skip: ${args.skip}`);
149
+ }
150
+ return argParts.join(", ");
151
+ }
152
+ /**
153
+ * Extract simple unique argument for findUnique operations
154
+ * Returns direct argument format (e.g., "id: $var0") if the where clause
155
+ * contains a single simple field equality, otherwise returns null
156
+ */
157
+ #extractSimpleUniqueArgument(where) {
158
+ if (where.conditions.length !== 1) {
159
+ return null;
160
+ }
161
+ const condition = where.conditions[0];
162
+ if (!(0, import_typeUtils.isFieldCondition)(condition) || condition.operator !== "equals") {
163
+ return null;
164
+ }
165
+ const variableName = this.#addVariable(condition.value, condition.field);
166
+ return `${condition.field}: $${variableName}`;
167
+ }
168
+ /**
169
+ * Generate variable definitions for GraphQL query
170
+ */
171
+ #generateVariableDefinitions() {
172
+ return Object.entries(this.#variables).map(([name, value]) => {
173
+ const fieldName = this.#variableFields.get(name);
174
+ const baseType = this.#getGraphQLType(value, fieldName);
175
+ const isFindUnique = this.#operation === "findUnique" || this.#operation === "findUniqueOrThrow";
176
+ const isIdField = fieldName === "id" || fieldName?.endsWith("Id");
177
+ if (isFindUnique && isIdField && !baseType.includes("!")) {
178
+ return `$${name}: ${baseType}!`;
179
+ }
180
+ return `$${name}: ${baseType}`;
181
+ }).join(", ");
182
+ }
183
+ /**
184
+ * Generate WHERE argument
185
+ */
186
+ #generateWhereArgument(where) {
187
+ const conditions = where.conditions.map(
188
+ (condition) => this.#generateCondition(condition)
189
+ );
190
+ if (conditions.length === 0) {
191
+ return "{}";
192
+ }
193
+ if (conditions.length === 1) {
194
+ return conditions[0];
195
+ }
196
+ return `{ AND: [${conditions.join(", ")}] }`;
197
+ }
198
+ /**
199
+ * Generate individual where condition
200
+ */
201
+ #generateCondition(condition) {
202
+ if ((0, import_typeUtils.isFieldCondition)(condition)) {
203
+ return this.#generateFieldCondition(condition);
204
+ } else if ((0, import_typeUtils.isLogicalCondition)(condition)) {
205
+ return this.#generateLogicalCondition(condition);
206
+ } else if ((0, import_typeUtils.isRelationCondition)(condition)) {
207
+ return this.#generateRelationCondition(condition);
208
+ }
209
+ throw new GraphQLGenerateError("Unknown condition type", { condition });
210
+ }
211
+ /**
212
+ * Generate field condition
213
+ */
214
+ #generateFieldCondition(condition) {
215
+ const { field, operator, value } = condition;
216
+ if (operator === "equals") {
217
+ const variableName2 = this.#addVariable(value, field);
218
+ return `{ ${field}: $${variableName2} }`;
219
+ }
220
+ const operatorMap = {
221
+ equals: "equals",
222
+ not: "not",
223
+ in: "in",
224
+ notIn: "notIn",
225
+ lt: "lt",
226
+ lte: "lte",
227
+ gt: "gt",
228
+ gte: "gte",
229
+ contains: "contains",
230
+ startsWith: "startsWith",
231
+ endsWith: "endsWith",
232
+ isNull: "isNull",
233
+ isNotNull: "isNotNull"
234
+ };
235
+ const gqlOperator = operatorMap[operator];
236
+ if (!gqlOperator) {
237
+ throw new GraphQLGenerateError(`Unsupported operator: ${operator}`);
238
+ }
239
+ if (operator === "isNull" || operator === "isNotNull") {
240
+ return `{ ${field}: { ${gqlOperator}: ${operator === "isNull"} } }`;
241
+ }
242
+ const variableName = this.#addVariable(value, field);
243
+ return `{ ${field}: { ${gqlOperator}: $${variableName} } }`;
244
+ }
245
+ /**
246
+ * Generate logical condition
247
+ */
248
+ #generateLogicalCondition(condition) {
249
+ const { operator, conditions } = condition;
250
+ const conditionStrings = conditions.map(
251
+ (cond) => this.#generateCondition(cond)
252
+ );
253
+ if (operator === "NOT") {
254
+ if (conditionStrings.length !== 1) {
255
+ throw new GraphQLGenerateError(
256
+ "NOT operator must have exactly one condition"
257
+ );
258
+ }
259
+ return `{ NOT: ${conditionStrings[0]} }`;
260
+ }
261
+ return `{ ${operator}: [${conditionStrings.join(", ")}] }`;
262
+ }
263
+ /**
264
+ * Generate relation condition
265
+ */
266
+ #generateRelationCondition(condition) {
267
+ const { relation, condition: nestedCondition } = condition;
268
+ const whereArg = this.#generateWhereArgument(nestedCondition);
269
+ return `{ ${relation}: ${whereArg} }`;
270
+ }
271
+ /**
272
+ * Generate ORDER BY argument
273
+ */
274
+ #generateOrderByArgument(orderBy) {
275
+ const fields = orderBy.fields.map((field) => {
276
+ const direction = field.direction.toUpperCase();
277
+ return `{ ${field.field}: ${direction} }`;
278
+ });
279
+ if (fields.length === 1) {
280
+ return fields[0];
281
+ }
282
+ return `[${fields.join(", ")}]`;
283
+ }
284
+ /**
285
+ * Generate field selection
286
+ */
287
+ #generateFieldSelection(args, model) {
288
+ if (args?.select) {
289
+ return this.#generateSelectFields(args.select);
290
+ }
291
+ if (args?.include) {
292
+ return this.#generateIncludeFields(args.include);
293
+ }
294
+ if (model && this.#schema && this.#schema[model]) {
295
+ const fields = this.#schema[model];
296
+ return fields.map((field) => ` ${field}`).join("\n");
297
+ }
298
+ return " id\n createdAt\n updatedAt";
299
+ }
300
+ /**
301
+ * Generate fields from SELECT clause
302
+ */
303
+ #generateSelectFields(select) {
304
+ const fieldStrings = [];
305
+ for (const fieldSelection of select.fields) {
306
+ if (!fieldSelection.selected) {
307
+ continue;
308
+ }
309
+ if (fieldSelection.nested) {
310
+ const nestedFields = fieldSelection.nested.type === "Select" ? this.#generateSelectFields(fieldSelection.nested) : this.#generateIncludeFields(fieldSelection.nested);
311
+ const indentedFields = this.#indent(nestedFields, 2);
312
+ fieldStrings.push(
313
+ ` ${fieldSelection.field} {
314
+ ${indentedFields}
315
+ }`
316
+ );
317
+ } else {
318
+ fieldStrings.push(` ${fieldSelection.field}`);
319
+ }
320
+ }
321
+ return fieldStrings.join("\n");
322
+ }
323
+ /**
324
+ * Generate fields from INCLUDE clause
325
+ */
326
+ #generateIncludeFields(include) {
327
+ const fieldStrings = [];
328
+ fieldStrings.push(" id");
329
+ for (const relationInclusion of include.relations) {
330
+ if (!relationInclusion.included) {
331
+ continue;
332
+ }
333
+ let relationQuery = ` ${relationInclusion.relation}`;
334
+ if (relationInclusion.args) {
335
+ const argsString = this.#generateArguments(relationInclusion.args);
336
+ if (argsString) {
337
+ relationQuery += `(${argsString})`;
338
+ }
339
+ }
340
+ let nestedFields;
341
+ if (relationInclusion.nested) {
342
+ nestedFields = this.#generateIncludeFields(relationInclusion.nested);
343
+ } else if (relationInclusion.args?.select) {
344
+ nestedFields = this.#generateSelectFields(relationInclusion.args.select);
345
+ } else {
346
+ nestedFields = " id";
347
+ }
348
+ relationQuery += ` {
349
+ ${this.#indent(nestedFields, 2)}
350
+ }`;
351
+ fieldStrings.push(relationQuery);
352
+ }
353
+ return fieldStrings.join("\n");
354
+ }
355
+ /**
356
+ * Add variable and return variable name
357
+ */
358
+ #addVariable(value, fieldName) {
359
+ const variableName = `var${this.#variableCounter++}`;
360
+ this.#variables[variableName] = value;
361
+ if (fieldName) {
362
+ this.#variableFields.set(variableName, fieldName);
363
+ }
364
+ return variableName;
365
+ }
366
+ /**
367
+ * Get GraphQL type for a value
368
+ */
369
+ #getGraphQLType(value, fieldName) {
370
+ const isIdField = fieldName && /^(id|.*Id|.*ID)$/.test(fieldName);
371
+ if (value === void 0 || value === null) {
372
+ return isIdField ? "ID" : "String";
373
+ }
374
+ if (typeof value === "string") {
375
+ return isIdField ? "ID" : "String";
376
+ }
377
+ if (typeof value === "number") {
378
+ if (isIdField) {
379
+ return "ID";
380
+ }
381
+ return Number.isInteger(value) ? "Int" : "Float";
382
+ }
383
+ if (typeof value === "boolean") {
384
+ return "Boolean";
385
+ }
386
+ if (value instanceof Date) {
387
+ return "DateTime";
388
+ }
389
+ if (Array.isArray(value)) {
390
+ if (value.length === 0) {
391
+ return "[String]";
392
+ }
393
+ const itemType = this.#getGraphQLType(value[0], fieldName);
394
+ if (isIdField && (itemType === "ID" || itemType === "String")) {
395
+ return `[ID!]`;
396
+ }
397
+ return `[${itemType}]`;
398
+ }
399
+ return "String";
400
+ }
401
+ /**
402
+ * Capitalize first letter of string
403
+ */
404
+ #capitalize(str) {
405
+ return str.charAt(0).toUpperCase() + str.slice(1);
406
+ }
407
+ /**
408
+ * Indent text by specified number of levels
409
+ */
410
+ #indent(text, levels) {
411
+ const indentation = " ".repeat(levels);
412
+ return text.split("\n").map((line) => line.trim() ? `${indentation}${line}` : line).join("\n");
413
+ }
414
+ }
415
+ const graphqlGenerator = new GraphQLGenerator();
416
+ // Annotate the CommonJS export names for ESM import in node:
417
+ 0 && (module.exports = {
418
+ GraphQLGenerateError,
419
+ GraphQLGenerator,
420
+ graphqlGenerator
421
+ });