@effect-gql/cli 1.1.0 → 1.2.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/index.js CHANGED
@@ -1,7 +1,9 @@
1
- import { Effect } from 'effect';
1
+ import { Effect, pipe, Option, Console } from 'effect';
2
2
  import { lexicographicSortSchema, printSchema } from '@effect-gql/core';
3
- import * as fs from 'fs';
4
- import * as path from 'path';
3
+ import * as fs3 from 'fs';
4
+ import * as path2 from 'path';
5
+ import * as readline from 'readline';
6
+ import { spawn } from 'child_process';
5
7
 
6
8
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
7
9
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
@@ -10,8 +12,8 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
10
12
  throw Error('Dynamic require of "' + x + '" is not supported');
11
13
  });
12
14
  var loadSchema = (modulePath) => Effect.gen(function* () {
13
- const absolutePath = path.resolve(process.cwd(), modulePath);
14
- if (!fs.existsSync(absolutePath)) {
15
+ const absolutePath = path2.resolve(process.cwd(), modulePath);
16
+ if (!fs3.existsSync(absolutePath)) {
15
17
  return yield* Effect.fail(new Error(`File not found: ${absolutePath}`));
16
18
  }
17
19
  const module = yield* Effect.tryPromise({
@@ -50,6 +52,1123 @@ var generateSDL = (schema, options = {}) => {
50
52
  };
51
53
  var generateSDLFromModule = (modulePath, options = {}) => loadSchema(modulePath).pipe(Effect.map((schema) => generateSDL(schema, options)));
52
54
 
53
- export { generateSDL, generateSDLFromModule, loadSchema };
55
+ // src/commands/create/types.ts
56
+ var SERVER_TYPES = ["node", "bun", "express", "web"];
57
+ var isValidServerType = (value) => SERVER_TYPES.includes(value);
58
+ var PACKAGE_MANAGERS = ["npm", "pnpm", "yarn", "bun"];
59
+ var isValidPackageManager = (value) => PACKAGE_MANAGERS.includes(value);
60
+
61
+ // src/commands/create/args.ts
62
+ var parseArgs = (args) => {
63
+ const positional = [];
64
+ let serverType;
65
+ let directory = Option.none();
66
+ let monorepo = Option.none();
67
+ let skipInstall = false;
68
+ let packageManager = Option.none();
69
+ let interactive = false;
70
+ for (let i = 0; i < args.length; i++) {
71
+ const arg = args[i];
72
+ if (arg === "-h" || arg === "--help") {
73
+ return { help: true };
74
+ } else if (arg === "-i" || arg === "--interactive") {
75
+ interactive = true;
76
+ } else if (arg === "-s" || arg === "--server-type") {
77
+ const value = args[++i];
78
+ if (!value) {
79
+ return { error: "Missing value for --server-type" };
80
+ }
81
+ if (!isValidServerType(value)) {
82
+ return {
83
+ error: `Invalid server type: ${value}. Must be one of: ${SERVER_TYPES.join(", ")}`
84
+ };
85
+ }
86
+ serverType = value;
87
+ } else if (arg === "-d" || arg === "--directory") {
88
+ const value = args[++i];
89
+ if (!value) {
90
+ return { error: "Missing value for --directory" };
91
+ }
92
+ directory = Option.some(value);
93
+ } else if (arg === "--monorepo") {
94
+ monorepo = Option.some(true);
95
+ } else if (arg === "--skip-install") {
96
+ skipInstall = true;
97
+ } else if (arg === "--package-manager") {
98
+ const value = args[++i];
99
+ if (!value) {
100
+ return { error: "Missing value for --package-manager" };
101
+ }
102
+ if (!isValidPackageManager(value)) {
103
+ return { error: `Invalid package manager: ${value}. Must be one of: npm, pnpm, yarn, bun` };
104
+ }
105
+ packageManager = Option.some(value);
106
+ } else if (!arg.startsWith("-")) {
107
+ positional.push(arg);
108
+ } else {
109
+ return { error: `Unknown option: ${arg}` };
110
+ }
111
+ }
112
+ if (interactive) {
113
+ return { interactive: true };
114
+ }
115
+ if (args.length === 0) {
116
+ return { interactive: true };
117
+ }
118
+ if (positional.length === 0) {
119
+ return {
120
+ error: "Missing project name. Use --interactive or provide: effect-gql create <name> --server-type <type>"
121
+ };
122
+ }
123
+ if (!serverType) {
124
+ return { error: "Missing --server-type. Must be one of: " + SERVER_TYPES.join(", ") };
125
+ }
126
+ const options = {
127
+ name: positional[0],
128
+ serverType,
129
+ directory,
130
+ monorepo,
131
+ skipInstall,
132
+ packageManager
133
+ };
134
+ return { options };
135
+ };
136
+
137
+ // src/commands/create/templates/package-json.ts
138
+ var VERSIONS = {
139
+ core: "^1.1.0",
140
+ node: "^1.1.0",
141
+ bun: "^1.1.0",
142
+ express: "^1.1.0",
143
+ web: "^1.1.0",
144
+ effect: "^3.19.0",
145
+ platform: "^0.94.0",
146
+ platformNode: "^0.104.0",
147
+ platformBun: "^0.87.0",
148
+ graphql: "^16.0.0",
149
+ expressLib: "^5.0.0",
150
+ tsx: "^4.19.0",
151
+ typescript: "^5.0.0"
152
+ };
153
+ var getDependencies = (serverType, isMonorepo) => {
154
+ const toVersion = (pkg, version) => isMonorepo && pkg.startsWith("@effect-gql/") ? "workspace:*" : version;
155
+ const baseDeps = {
156
+ "@effect-gql/core": toVersion("@effect-gql/core", VERSIONS.core),
157
+ "@effect/platform": VERSIONS.platform,
158
+ effect: VERSIONS.effect,
159
+ graphql: VERSIONS.graphql
160
+ };
161
+ const baseDevDeps = {
162
+ tsx: VERSIONS.tsx,
163
+ typescript: VERSIONS.typescript
164
+ };
165
+ switch (serverType) {
166
+ case "node":
167
+ return {
168
+ dependencies: {
169
+ ...baseDeps,
170
+ "@effect-gql/node": toVersion("@effect-gql/node", VERSIONS.node),
171
+ "@effect/platform-node": VERSIONS.platformNode
172
+ },
173
+ devDependencies: baseDevDeps
174
+ };
175
+ case "bun":
176
+ return {
177
+ dependencies: {
178
+ ...baseDeps,
179
+ "@effect-gql/bun": toVersion("@effect-gql/bun", VERSIONS.bun),
180
+ "@effect/platform-bun": VERSIONS.platformBun
181
+ },
182
+ devDependencies: {
183
+ typescript: VERSIONS.typescript
184
+ // Bun has built-in TypeScript support, no tsx needed
185
+ }
186
+ };
187
+ case "express":
188
+ return {
189
+ dependencies: {
190
+ ...baseDeps,
191
+ "@effect-gql/express": toVersion("@effect-gql/express", VERSIONS.express),
192
+ express: VERSIONS.expressLib
193
+ },
194
+ devDependencies: {
195
+ ...baseDevDeps,
196
+ "@types/express": "^5.0.0"
197
+ }
198
+ };
199
+ case "web":
200
+ return {
201
+ dependencies: {
202
+ ...baseDeps,
203
+ "@effect-gql/web": toVersion("@effect-gql/web", VERSIONS.web)
204
+ },
205
+ devDependencies: baseDevDeps
206
+ };
207
+ }
208
+ };
209
+ var getScripts = (serverType) => {
210
+ switch (serverType) {
211
+ case "node":
212
+ return {
213
+ start: "tsx src/index.ts",
214
+ dev: "tsx watch src/index.ts",
215
+ build: "tsc",
216
+ typecheck: "tsc --noEmit"
217
+ };
218
+ case "bun":
219
+ return {
220
+ start: "bun run src/index.ts",
221
+ dev: "bun --watch src/index.ts",
222
+ build: "bun build src/index.ts --outdir dist --target bun",
223
+ typecheck: "tsc --noEmit"
224
+ };
225
+ case "express":
226
+ return {
227
+ start: "tsx src/index.ts",
228
+ dev: "tsx watch src/index.ts",
229
+ build: "tsc",
230
+ typecheck: "tsc --noEmit"
231
+ };
232
+ case "web":
233
+ return {
234
+ start: "tsx src/index.ts",
235
+ dev: "tsx watch src/index.ts",
236
+ build: "tsc",
237
+ typecheck: "tsc --noEmit"
238
+ // Users will typically add wrangler/deno commands as needed
239
+ };
240
+ }
241
+ };
242
+ var generatePackageJson = (ctx) => {
243
+ const deps = getDependencies(ctx.serverType, ctx.isMonorepo);
244
+ const pkg = {
245
+ name: ctx.name,
246
+ version: "0.0.1",
247
+ private: true,
248
+ type: "module",
249
+ scripts: getScripts(ctx.serverType),
250
+ dependencies: deps.dependencies,
251
+ devDependencies: deps.devDependencies
252
+ };
253
+ return JSON.stringify(pkg, null, 2) + "\n";
254
+ };
255
+
256
+ // src/commands/create/templates/tsconfig.ts
257
+ var generateTsConfig = (ctx) => {
258
+ const config = ctx.isMonorepo ? {
259
+ // In a monorepo, extend from root tsconfig
260
+ extends: "../../tsconfig.json",
261
+ compilerOptions: {
262
+ outDir: "./dist",
263
+ rootDir: "./src",
264
+ noEmit: true
265
+ },
266
+ include: ["src/**/*"],
267
+ exclude: ["node_modules", "dist"]
268
+ } : {
269
+ // Standalone project config
270
+ compilerOptions: {
271
+ target: "ES2022",
272
+ module: "NodeNext",
273
+ moduleResolution: "NodeNext",
274
+ lib: ["ES2022"],
275
+ outDir: "./dist",
276
+ rootDir: "./src",
277
+ strict: true,
278
+ esModuleInterop: true,
279
+ skipLibCheck: true,
280
+ forceConsistentCasingInFileNames: true,
281
+ declaration: true,
282
+ declarationMap: true,
283
+ sourceMap: true,
284
+ noEmit: true,
285
+ // Effect requires these for decorators
286
+ experimentalDecorators: true,
287
+ emitDecoratorMetadata: true
288
+ },
289
+ include: ["src/**/*"],
290
+ exclude: ["node_modules", "dist"]
291
+ };
292
+ return JSON.stringify(config, null, 2) + "\n";
293
+ };
294
+
295
+ // src/commands/create/templates/server.ts
296
+ var generateNodeServer = (ctx) => `/**
297
+ * ${ctx.name} - GraphQL Server
298
+ *
299
+ * A GraphQL server built with Effect GQL and Node.js.
300
+ */
301
+
302
+ import { Effect, Layer } from "effect"
303
+ import * as S from "effect/Schema"
304
+ import { HttpRouter, HttpServerResponse } from "@effect/platform"
305
+ import { GraphQLSchemaBuilder, query, mutation, makeGraphQLRouter } from "@effect-gql/core"
306
+ import { serve } from "@effect-gql/node"
307
+
308
+ // =============================================================================
309
+ // Domain Models
310
+ // =============================================================================
311
+
312
+ /**
313
+ * Define your types with Effect Schema.
314
+ * This single definition is used for both TypeScript types AND GraphQL types.
315
+ */
316
+ const User = S.Struct({
317
+ id: S.String,
318
+ name: S.String,
319
+ email: S.String,
320
+ })
321
+
322
+ type User = S.Schema.Type<typeof User>
323
+
324
+ // =============================================================================
325
+ // In-Memory Data Store (replace with your database)
326
+ // =============================================================================
327
+
328
+ const users: User[] = [
329
+ { id: "1", name: "Alice", email: "alice@example.com" },
330
+ { id: "2", name: "Bob", email: "bob@example.com" },
331
+ ]
332
+
333
+ // =============================================================================
334
+ // GraphQL Schema
335
+ // =============================================================================
336
+
337
+ const schema = GraphQLSchemaBuilder.empty
338
+ .pipe(
339
+ // Simple query
340
+ query("hello", {
341
+ type: S.String,
342
+ description: "Returns a friendly greeting",
343
+ resolve: () => Effect.succeed("Hello from ${ctx.name}!"),
344
+ }),
345
+
346
+ // Query with arguments
347
+ query("user", {
348
+ args: S.Struct({ id: S.String }),
349
+ type: S.NullOr(User),
350
+ description: "Get a user by ID",
351
+ resolve: (args) => Effect.succeed(users.find((u) => u.id === args.id) ?? null),
352
+ }),
353
+
354
+ // Query that returns a list
355
+ query("users", {
356
+ type: S.Array(User),
357
+ description: "Get all users",
358
+ resolve: () => Effect.succeed(users),
359
+ }),
360
+
361
+ // Mutation
362
+ mutation("createUser", {
363
+ args: S.Struct({
364
+ name: S.String,
365
+ email: S.String,
366
+ }),
367
+ type: User,
368
+ description: "Create a new user",
369
+ resolve: (args) =>
370
+ Effect.sync(() => {
371
+ const newUser: User = {
372
+ id: String(users.length + 1),
373
+ name: args.name,
374
+ email: args.email,
375
+ }
376
+ users.push(newUser)
377
+ return newUser
378
+ }),
379
+ })
380
+ )
381
+ .buildSchema()
382
+
383
+ // =============================================================================
384
+ // HTTP Router
385
+ // =============================================================================
386
+
387
+ const graphqlRouter = makeGraphQLRouter(schema, Layer.empty, {
388
+ path: "/graphql",
389
+ graphiql: {
390
+ path: "/graphiql",
391
+ endpoint: "/graphql",
392
+ },
393
+ })
394
+
395
+ const router = HttpRouter.empty.pipe(
396
+ HttpRouter.get("/health", HttpServerResponse.json({ status: "ok" })),
397
+ HttpRouter.concat(graphqlRouter)
398
+ )
399
+
400
+ // =============================================================================
401
+ // Server Startup
402
+ // =============================================================================
403
+
404
+ serve(router, Layer.empty, {
405
+ port: 4000,
406
+ onStart: (url: string) => {
407
+ console.log(\`Server ready at \${url}\`)
408
+ console.log(\`GraphQL endpoint: \${url}/graphql\`)
409
+ console.log(\`GraphiQL playground: \${url}/graphiql\`)
410
+ console.log(\`Health check: \${url}/health\`)
411
+ },
412
+ })
413
+ `;
414
+ var generateBunServer = (ctx) => `/**
415
+ * ${ctx.name} - GraphQL Server
416
+ *
417
+ * A GraphQL server built with Effect GQL and Bun.
418
+ */
419
+
420
+ import { Effect, Layer } from "effect"
421
+ import * as S from "effect/Schema"
422
+ import { HttpRouter, HttpServerResponse } from "@effect/platform"
423
+ import { GraphQLSchemaBuilder, query, mutation, makeGraphQLRouter } from "@effect-gql/core"
424
+ import { serve } from "@effect-gql/bun"
425
+
426
+ // =============================================================================
427
+ // Domain Models
428
+ // =============================================================================
429
+
430
+ const User = S.Struct({
431
+ id: S.String,
432
+ name: S.String,
433
+ email: S.String,
434
+ })
435
+
436
+ type User = S.Schema.Type<typeof User>
437
+
438
+ // =============================================================================
439
+ // In-Memory Data Store (replace with your database)
440
+ // =============================================================================
441
+
442
+ const users: User[] = [
443
+ { id: "1", name: "Alice", email: "alice@example.com" },
444
+ { id: "2", name: "Bob", email: "bob@example.com" },
445
+ ]
446
+
447
+ // =============================================================================
448
+ // GraphQL Schema
449
+ // =============================================================================
450
+
451
+ const schema = GraphQLSchemaBuilder.empty
452
+ .pipe(
453
+ query("hello", {
454
+ type: S.String,
455
+ description: "Returns a friendly greeting",
456
+ resolve: () => Effect.succeed("Hello from ${ctx.name}!"),
457
+ }),
458
+
459
+ query("user", {
460
+ args: S.Struct({ id: S.String }),
461
+ type: S.NullOr(User),
462
+ description: "Get a user by ID",
463
+ resolve: (args) => Effect.succeed(users.find((u) => u.id === args.id) ?? null),
464
+ }),
465
+
466
+ query("users", {
467
+ type: S.Array(User),
468
+ description: "Get all users",
469
+ resolve: () => Effect.succeed(users),
470
+ }),
471
+
472
+ mutation("createUser", {
473
+ args: S.Struct({
474
+ name: S.String,
475
+ email: S.String,
476
+ }),
477
+ type: User,
478
+ description: "Create a new user",
479
+ resolve: (args) =>
480
+ Effect.sync(() => {
481
+ const newUser: User = {
482
+ id: String(users.length + 1),
483
+ name: args.name,
484
+ email: args.email,
485
+ }
486
+ users.push(newUser)
487
+ return newUser
488
+ }),
489
+ })
490
+ )
491
+ .buildSchema()
492
+
493
+ // =============================================================================
494
+ // HTTP Router
495
+ // =============================================================================
496
+
497
+ const graphqlRouter = makeGraphQLRouter(schema, Layer.empty, {
498
+ path: "/graphql",
499
+ graphiql: {
500
+ path: "/graphiql",
501
+ endpoint: "/graphql",
502
+ },
503
+ })
504
+
505
+ const router = HttpRouter.empty.pipe(
506
+ HttpRouter.get("/health", HttpServerResponse.json({ status: "ok" })),
507
+ HttpRouter.concat(graphqlRouter)
508
+ )
509
+
510
+ // =============================================================================
511
+ // Server Startup
512
+ // =============================================================================
513
+
514
+ serve(router, Layer.empty, {
515
+ port: 4000,
516
+ onStart: (url: string) => {
517
+ console.log(\`Server ready at \${url}\`)
518
+ console.log(\`GraphQL endpoint: \${url}/graphql\`)
519
+ console.log(\`GraphiQL playground: \${url}/graphiql\`)
520
+ console.log(\`Health check: \${url}/health\`)
521
+ },
522
+ })
523
+ `;
524
+ var generateExpressServer = (ctx) => `/**
525
+ * ${ctx.name} - GraphQL Server
526
+ *
527
+ * A GraphQL server built with Effect GQL and Express.
528
+ */
529
+
530
+ import express from "express"
531
+ import { Effect, Layer } from "effect"
532
+ import * as S from "effect/Schema"
533
+ import { GraphQLSchemaBuilder, query, mutation, makeGraphQLRouter } from "@effect-gql/core"
534
+ import { toMiddleware } from "@effect-gql/express"
535
+
536
+ // =============================================================================
537
+ // Domain Models
538
+ // =============================================================================
539
+
540
+ const User = S.Struct({
541
+ id: S.String,
542
+ name: S.String,
543
+ email: S.String,
544
+ })
545
+
546
+ type User = S.Schema.Type<typeof User>
547
+
548
+ // =============================================================================
549
+ // In-Memory Data Store (replace with your database)
550
+ // =============================================================================
551
+
552
+ const users: User[] = [
553
+ { id: "1", name: "Alice", email: "alice@example.com" },
554
+ { id: "2", name: "Bob", email: "bob@example.com" },
555
+ ]
556
+
557
+ // =============================================================================
558
+ // GraphQL Schema
559
+ // =============================================================================
560
+
561
+ const schema = GraphQLSchemaBuilder.empty
562
+ .pipe(
563
+ query("hello", {
564
+ type: S.String,
565
+ description: "Returns a friendly greeting",
566
+ resolve: () => Effect.succeed("Hello from ${ctx.name}!"),
567
+ }),
568
+
569
+ query("user", {
570
+ args: S.Struct({ id: S.String }),
571
+ type: S.NullOr(User),
572
+ description: "Get a user by ID",
573
+ resolve: (args) => Effect.succeed(users.find((u) => u.id === args.id) ?? null),
574
+ }),
575
+
576
+ query("users", {
577
+ type: S.Array(User),
578
+ description: "Get all users",
579
+ resolve: () => Effect.succeed(users),
580
+ }),
581
+
582
+ mutation("createUser", {
583
+ args: S.Struct({
584
+ name: S.String,
585
+ email: S.String,
586
+ }),
587
+ type: User,
588
+ description: "Create a new user",
589
+ resolve: (args) =>
590
+ Effect.sync(() => {
591
+ const newUser: User = {
592
+ id: String(users.length + 1),
593
+ name: args.name,
594
+ email: args.email,
595
+ }
596
+ users.push(newUser)
597
+ return newUser
598
+ }),
599
+ })
600
+ )
601
+ .buildSchema()
602
+
603
+ // =============================================================================
604
+ // GraphQL Router
605
+ // =============================================================================
606
+
607
+ const graphqlRouter = makeGraphQLRouter(schema, Layer.empty, {
608
+ path: "/graphql",
609
+ graphiql: {
610
+ path: "/graphiql",
611
+ endpoint: "/graphql",
612
+ },
613
+ })
614
+
615
+ // =============================================================================
616
+ // Express App
617
+ // =============================================================================
618
+
619
+ const app = express()
620
+ app.use(express.json())
621
+
622
+ // Health check
623
+ app.get("/health", (_, res) => {
624
+ res.json({ status: "ok" })
625
+ })
626
+
627
+ // Mount GraphQL middleware
628
+ app.use(toMiddleware(graphqlRouter, Layer.empty))
629
+
630
+ // =============================================================================
631
+ // Server Startup
632
+ // =============================================================================
633
+
634
+ const port = process.env.PORT || 4000
635
+
636
+ app.listen(port, () => {
637
+ console.log(\`Server ready at http://localhost:\${port}\`)
638
+ console.log(\`GraphQL endpoint: http://localhost:\${port}/graphql\`)
639
+ console.log(\`GraphiQL playground: http://localhost:\${port}/graphiql\`)
640
+ console.log(\`Health check: http://localhost:\${port}/health\`)
641
+ })
642
+ `;
643
+ var generateWebHandler = (ctx) => `/**
644
+ * ${ctx.name} - GraphQL Server
645
+ *
646
+ * A GraphQL server built with Effect GQL using Web standard APIs.
647
+ * Compatible with Cloudflare Workers, Deno, and other WASM runtimes.
648
+ */
649
+
650
+ import { Effect, Layer } from "effect"
651
+ import * as S from "effect/Schema"
652
+ import { GraphQLSchemaBuilder, query, mutation, makeGraphQLRouter } from "@effect-gql/core"
653
+ import { toHandler } from "@effect-gql/web"
654
+
655
+ // =============================================================================
656
+ // Domain Models
657
+ // =============================================================================
658
+
659
+ const User = S.Struct({
660
+ id: S.String,
661
+ name: S.String,
662
+ email: S.String,
663
+ })
664
+
665
+ type User = S.Schema.Type<typeof User>
666
+
667
+ // =============================================================================
668
+ // In-Memory Data Store (replace with your database)
669
+ // =============================================================================
670
+
671
+ const users: User[] = [
672
+ { id: "1", name: "Alice", email: "alice@example.com" },
673
+ { id: "2", name: "Bob", email: "bob@example.com" },
674
+ ]
675
+
676
+ // =============================================================================
677
+ // GraphQL Schema
678
+ // =============================================================================
679
+
680
+ const schema = GraphQLSchemaBuilder.empty
681
+ .pipe(
682
+ query("hello", {
683
+ type: S.String,
684
+ description: "Returns a friendly greeting",
685
+ resolve: () => Effect.succeed("Hello from ${ctx.name}!"),
686
+ }),
687
+
688
+ query("user", {
689
+ args: S.Struct({ id: S.String }),
690
+ type: S.NullOr(User),
691
+ description: "Get a user by ID",
692
+ resolve: (args) => Effect.succeed(users.find((u) => u.id === args.id) ?? null),
693
+ }),
694
+
695
+ query("users", {
696
+ type: S.Array(User),
697
+ description: "Get all users",
698
+ resolve: () => Effect.succeed(users),
699
+ }),
700
+
701
+ mutation("createUser", {
702
+ args: S.Struct({
703
+ name: S.String,
704
+ email: S.String,
705
+ }),
706
+ type: User,
707
+ description: "Create a new user",
708
+ resolve: (args) =>
709
+ Effect.sync(() => {
710
+ const newUser: User = {
711
+ id: String(users.length + 1),
712
+ name: args.name,
713
+ email: args.email,
714
+ }
715
+ users.push(newUser)
716
+ return newUser
717
+ }),
718
+ })
719
+ )
720
+ .buildSchema()
721
+
722
+ // =============================================================================
723
+ // GraphQL Router
724
+ // =============================================================================
725
+
726
+ const graphqlRouter = makeGraphQLRouter(schema, Layer.empty, {
727
+ path: "/graphql",
728
+ graphiql: {
729
+ path: "/graphiql",
730
+ endpoint: "/graphql",
731
+ },
732
+ })
733
+
734
+ // =============================================================================
735
+ // Web Handler
736
+ // =============================================================================
737
+
738
+ const { handler } = toHandler(graphqlRouter, Layer.empty)
739
+
740
+ /**
741
+ * Export for Cloudflare Workers
742
+ */
743
+ export default {
744
+ async fetch(request: Request): Promise<Response> {
745
+ const url = new URL(request.url)
746
+
747
+ // Health check
748
+ if (url.pathname === "/health") {
749
+ return new Response(JSON.stringify({ status: "ok" }), {
750
+ headers: { "Content-Type": "application/json" },
751
+ })
752
+ }
753
+
754
+ return handler(request)
755
+ },
756
+ }
757
+
758
+ /**
759
+ * For local development with Deno or other runtimes, you can use:
760
+ *
761
+ * Deno.serve((request) => {
762
+ * const url = new URL(request.url)
763
+ * if (url.pathname === "/health") {
764
+ * return new Response(JSON.stringify({ status: "ok" }), {
765
+ * headers: { "Content-Type": "application/json" },
766
+ * })
767
+ * }
768
+ * return handler(request)
769
+ * })
770
+ */
771
+ `;
772
+ var generateServerTemplate = (ctx) => {
773
+ switch (ctx.serverType) {
774
+ case "node":
775
+ return generateNodeServer(ctx);
776
+ case "bun":
777
+ return generateBunServer(ctx);
778
+ case "express":
779
+ return generateExpressServer(ctx);
780
+ case "web":
781
+ return generateWebHandler(ctx);
782
+ }
783
+ };
784
+
785
+ // src/commands/create/templates/index.ts
786
+ var generateGitignore = () => `# Dependencies
787
+ node_modules/
788
+
789
+ # Build output
790
+ dist/
791
+ *.tsbuildinfo
792
+
793
+ # IDE
794
+ .idea/
795
+ .vscode/
796
+ *.swp
797
+ *.swo
798
+
799
+ # OS
800
+ .DS_Store
801
+ Thumbs.db
802
+
803
+ # Environment
804
+ .env
805
+ .env.local
806
+ .env.*.local
807
+
808
+ # Logs
809
+ *.log
810
+ npm-debug.log*
811
+ yarn-debug.log*
812
+ yarn-error.log*
813
+
814
+ # Testing
815
+ coverage/
816
+ `;
817
+ var generateProject = (ctx) => [
818
+ {
819
+ path: "package.json",
820
+ content: generatePackageJson(ctx)
821
+ },
822
+ {
823
+ path: "tsconfig.json",
824
+ content: generateTsConfig(ctx)
825
+ },
826
+ {
827
+ path: "src/index.ts",
828
+ content: generateServerTemplate(ctx)
829
+ },
830
+ {
831
+ path: ".gitignore",
832
+ content: generateGitignore()
833
+ }
834
+ ];
835
+ var fileExists = (filePath) => Effect.sync(() => fs3.existsSync(filePath));
836
+ var readFile = (filePath) => Effect.try({
837
+ try: () => fs3.readFileSync(filePath, "utf-8"),
838
+ catch: (error) => new Error(`Failed to read ${filePath}: ${error}`)
839
+ });
840
+ var detectPackageManager = (dir) => Effect.gen(function* () {
841
+ if (yield* fileExists(path2.join(dir, "pnpm-lock.yaml"))) return "pnpm";
842
+ if (yield* fileExists(path2.join(dir, "bun.lockb"))) return "bun";
843
+ if (yield* fileExists(path2.join(dir, "yarn.lock"))) return "yarn";
844
+ return "npm";
845
+ });
846
+ var detectMonorepo = (targetDir) => Effect.gen(function* () {
847
+ let currentDir = path2.dirname(path2.resolve(targetDir));
848
+ const root = path2.parse(currentDir).root;
849
+ while (currentDir !== root) {
850
+ const pnpmWorkspacePath = path2.join(currentDir, "pnpm-workspace.yaml");
851
+ if (yield* fileExists(pnpmWorkspacePath)) {
852
+ return {
853
+ isMonorepo: true,
854
+ packageManager: Option.some("pnpm"),
855
+ workspacesRoot: Option.some(currentDir)
856
+ };
857
+ }
858
+ const pkgPath = path2.join(currentDir, "package.json");
859
+ if (yield* fileExists(pkgPath)) {
860
+ const content = yield* readFile(pkgPath).pipe(Effect.catchAll(() => Effect.succeed("")));
861
+ if (content) {
862
+ try {
863
+ const pkg = JSON.parse(content);
864
+ if (pkg.workspaces) {
865
+ const pm = yield* detectPackageManager(currentDir);
866
+ return {
867
+ isMonorepo: true,
868
+ packageManager: Option.some(pm),
869
+ workspacesRoot: Option.some(currentDir)
870
+ };
871
+ }
872
+ } catch {
873
+ }
874
+ }
875
+ }
876
+ const turboPath = path2.join(currentDir, "turbo.json");
877
+ if (yield* fileExists(turboPath)) {
878
+ const pm = yield* detectPackageManager(currentDir);
879
+ return {
880
+ isMonorepo: true,
881
+ packageManager: Option.some(pm),
882
+ workspacesRoot: Option.some(currentDir)
883
+ };
884
+ }
885
+ currentDir = path2.dirname(currentDir);
886
+ }
887
+ return {
888
+ isMonorepo: false,
889
+ packageManager: Option.none(),
890
+ workspacesRoot: Option.none()
891
+ };
892
+ });
893
+ var getInstallCommand = (pm) => {
894
+ switch (pm) {
895
+ case "npm":
896
+ return "npm install";
897
+ case "pnpm":
898
+ return "pnpm install";
899
+ case "yarn":
900
+ return "yarn";
901
+ case "bun":
902
+ return "bun install";
903
+ }
904
+ };
905
+ var getRunPrefix = (pm) => {
906
+ switch (pm) {
907
+ case "npm":
908
+ return "npm run";
909
+ case "pnpm":
910
+ return "pnpm";
911
+ case "yarn":
912
+ return "yarn";
913
+ case "bun":
914
+ return "bun run";
915
+ }
916
+ };
917
+
918
+ // src/commands/create/scaffolder.ts
919
+ var validateDirectory = (targetDir) => Effect.try({
920
+ try: () => {
921
+ if (fs3.existsSync(targetDir)) {
922
+ const files = fs3.readdirSync(targetDir);
923
+ if (files.length > 0) {
924
+ throw new Error(`Directory ${targetDir} is not empty`);
925
+ }
926
+ }
927
+ },
928
+ catch: (error) => error instanceof Error ? error : new Error(`Failed to validate directory: ${error}`)
929
+ });
930
+ var mkdirp = (dir) => Effect.try({
931
+ try: () => fs3.mkdirSync(dir, { recursive: true }),
932
+ catch: (error) => new Error(`Failed to create directory ${dir}: ${error}`)
933
+ });
934
+ var writeFile = (filePath, content) => Effect.gen(function* () {
935
+ yield* mkdirp(path2.dirname(filePath));
936
+ yield* Effect.try({
937
+ try: () => fs3.writeFileSync(filePath, content, "utf-8"),
938
+ catch: (error) => new Error(`Failed to write ${filePath}: ${error}`)
939
+ });
940
+ });
941
+ var runCommand = (command, args, cwd) => Effect.async((resume) => {
942
+ const child = spawn(command, args, {
943
+ cwd,
944
+ stdio: "inherit",
945
+ shell: true
946
+ });
947
+ child.on("close", (code) => {
948
+ if (code === 0) {
949
+ resume(Effect.succeed(void 0));
950
+ } else {
951
+ resume(Effect.fail(new Error(`Command failed with exit code ${code}`)));
952
+ }
953
+ });
954
+ child.on("error", (error) => {
955
+ resume(Effect.fail(new Error(`Failed to run command: ${error.message}`)));
956
+ });
957
+ return Effect.sync(() => {
958
+ child.kill();
959
+ });
960
+ });
961
+ var installDependencies = (targetDir, packageManager) => Effect.gen(function* () {
962
+ yield* Console.log("");
963
+ yield* Console.log("Installing dependencies...");
964
+ const installCmd = getInstallCommand(packageManager);
965
+ const [cmd, ...args] = installCmd.split(" ");
966
+ yield* runCommand(cmd, args, targetDir);
967
+ yield* Console.log("Dependencies installed successfully!");
968
+ });
969
+ var printSuccessMessage = (ctx, targetDir) => Effect.gen(function* () {
970
+ const relativePath = path2.relative(process.cwd(), targetDir) || ".";
971
+ const runPrefix = getRunPrefix(ctx.packageManager);
972
+ yield* Console.log("");
973
+ yield* Console.log(`Successfully created ${ctx.name}!`);
974
+ yield* Console.log("");
975
+ yield* Console.log("Next steps:");
976
+ yield* Console.log(` cd ${relativePath}`);
977
+ yield* Console.log(` ${runPrefix} dev`);
978
+ yield* Console.log("");
979
+ yield* Console.log("Your GraphQL server will be available at:");
980
+ yield* Console.log(" http://localhost:4000/graphql");
981
+ yield* Console.log(" http://localhost:4000/graphiql (playground)");
982
+ yield* Console.log("");
983
+ });
984
+ var scaffold = (options) => Effect.gen(function* () {
985
+ const targetDir = pipe(
986
+ options.directory,
987
+ Option.map((dir) => path2.resolve(process.cwd(), dir)),
988
+ Option.getOrElse(() => path2.resolve(process.cwd(), options.name))
989
+ );
990
+ const monorepoInfo = yield* detectMonorepo(targetDir);
991
+ const isMonorepo = pipe(
992
+ options.monorepo,
993
+ Option.getOrElse(() => monorepoInfo.isMonorepo)
994
+ );
995
+ const packageManager = yield* pipe(
996
+ options.packageManager,
997
+ Option.orElse(() => monorepoInfo.packageManager),
998
+ Option.match({
999
+ onNone: () => detectPackageManager(process.cwd()),
1000
+ onSome: (pm) => Effect.succeed(pm)
1001
+ })
1002
+ );
1003
+ const ctx = {
1004
+ name: options.name,
1005
+ serverType: options.serverType,
1006
+ isMonorepo,
1007
+ packageManager
1008
+ };
1009
+ yield* Console.log("");
1010
+ yield* Console.log(`Creating ${ctx.name} with ${ctx.serverType} server...`);
1011
+ yield* validateDirectory(targetDir);
1012
+ const files = generateProject(ctx);
1013
+ for (const file of files) {
1014
+ const filePath = path2.join(targetDir, file.path);
1015
+ yield* writeFile(filePath, file.content);
1016
+ yield* Console.log(` Created ${file.path}`);
1017
+ }
1018
+ if (!options.skipInstall) {
1019
+ yield* installDependencies(targetDir, packageManager).pipe(
1020
+ Effect.catchAll(
1021
+ (error) => Console.log(`Warning: Failed to install dependencies: ${error.message}`).pipe(
1022
+ Effect.andThen(
1023
+ Console.log(
1024
+ "You can install them manually by running: " + getInstallCommand(packageManager)
1025
+ )
1026
+ )
1027
+ )
1028
+ )
1029
+ );
1030
+ } else {
1031
+ yield* Console.log("");
1032
+ yield* Console.log(
1033
+ `Skipping dependency installation. Run '${getInstallCommand(packageManager)}' to install.`
1034
+ );
1035
+ }
1036
+ yield* printSuccessMessage(ctx, targetDir);
1037
+ });
1038
+
1039
+ // src/commands/create/index.ts
1040
+ var printCreateHelp = () => {
1041
+ console.log(`
1042
+ Usage: effect-gql create <name> --server-type <type> [options]
1043
+
1044
+ Create a new Effect GraphQL project.
1045
+
1046
+ Arguments:
1047
+ name Package/project name
1048
+
1049
+ Required Options:
1050
+ -s, --server-type Server type: node, bun, express, web
1051
+
1052
+ Optional Options:
1053
+ -d, --directory Target directory (default: ./<name>)
1054
+ --monorepo Create as workspace package (auto-detected)
1055
+ --skip-install Skip dependency installation
1056
+ --package-manager Package manager: npm, pnpm, yarn, bun
1057
+ -i, --interactive Interactive mode (prompts for options)
1058
+ -h, --help Show this help message
1059
+
1060
+ Server Types:
1061
+ node Node.js server using @effect-gql/node
1062
+ Best for: General Node.js deployments
1063
+
1064
+ bun Bun server using @effect-gql/bun
1065
+ Best for: Bun runtime with native WebSocket support
1066
+
1067
+ express Express middleware using @effect-gql/express
1068
+ Best for: Integrating into existing Express apps
1069
+
1070
+ web Web standard handler using @effect-gql/web
1071
+ Best for: Cloudflare Workers, Deno, edge runtimes
1072
+
1073
+ Examples:
1074
+ effect-gql create my-api --server-type node
1075
+ effect-gql create my-api -s bun
1076
+ effect-gql create my-api -s express -d ./packages/api --monorepo
1077
+ effect-gql create my-api -s web --skip-install
1078
+ effect-gql create --interactive
1079
+ `);
1080
+ };
1081
+ var prompt = (question) => Effect.async((resume) => {
1082
+ const rl = readline.createInterface({
1083
+ input: process.stdin,
1084
+ output: process.stdout
1085
+ });
1086
+ rl.question(question, (answer) => {
1087
+ rl.close();
1088
+ resume(Effect.succeed(answer.trim()));
1089
+ });
1090
+ rl.on("error", (error) => {
1091
+ rl.close();
1092
+ resume(Effect.fail(new Error(`Input error: ${error.message}`)));
1093
+ });
1094
+ return Effect.sync(() => rl.close());
1095
+ });
1096
+ var selectPrompt = (question, options) => Effect.gen(function* () {
1097
+ yield* Console.log(question);
1098
+ options.forEach((opt, i) => {
1099
+ console.log(` ${i + 1}) ${opt.label}`);
1100
+ });
1101
+ const answer = yield* prompt("Enter number: ");
1102
+ const index = parseInt(answer, 10) - 1;
1103
+ if (isNaN(index) || index < 0 || index >= options.length) {
1104
+ yield* Console.log(`Invalid selection. Please enter 1-${options.length}.`);
1105
+ return yield* selectPrompt(question, options);
1106
+ }
1107
+ return options[index].value;
1108
+ });
1109
+ var confirmPrompt = (question, defaultValue) => Effect.gen(function* () {
1110
+ const hint = "[y/N]";
1111
+ const answer = yield* prompt(`${question} ${hint} `);
1112
+ if (answer === "") return defaultValue;
1113
+ const lower = answer.toLowerCase();
1114
+ if (lower === "y" || lower === "yes") return true;
1115
+ if (lower === "n" || lower === "no") return false;
1116
+ yield* Console.log("Please answer 'y' or 'n'.");
1117
+ return yield* confirmPrompt(question, defaultValue);
1118
+ });
1119
+ var runInteractive = () => Effect.gen(function* () {
1120
+ yield* Console.log("");
1121
+ yield* Console.log("Create a new Effect GraphQL project");
1122
+ yield* Console.log("====================================");
1123
+ yield* Console.log("");
1124
+ const name = yield* prompt("Project name: ");
1125
+ if (!name) {
1126
+ return yield* Effect.fail(new Error("Project name is required"));
1127
+ }
1128
+ if (!/^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(name)) {
1129
+ yield* Console.log("Warning: Name may not be a valid npm package name.");
1130
+ }
1131
+ const serverType = yield* selectPrompt("Select server type:", [
1132
+ { label: "Node.js (@effect-gql/node)", value: "node" },
1133
+ { label: "Bun (@effect-gql/bun)", value: "bun" },
1134
+ { label: "Express (@effect-gql/express)", value: "express" },
1135
+ { label: "Web/Workers (@effect-gql/web)", value: "web" }
1136
+ ]);
1137
+ const monorepo = yield* confirmPrompt("Create as monorepo workspace package?", false);
1138
+ const packageManager = monorepo ? Option.some(
1139
+ yield* selectPrompt("Select package manager:", [
1140
+ { label: "pnpm", value: "pnpm" },
1141
+ { label: "npm", value: "npm" },
1142
+ { label: "yarn", value: "yarn" },
1143
+ { label: "bun", value: "bun" }
1144
+ ])
1145
+ ) : Option.none();
1146
+ return {
1147
+ name,
1148
+ serverType,
1149
+ directory: Option.none(),
1150
+ monorepo: Option.some(monorepo),
1151
+ skipInstall: false,
1152
+ packageManager
1153
+ };
1154
+ });
1155
+ var runCreate = (args) => Effect.gen(function* () {
1156
+ const parsed = parseArgs(args);
1157
+ if ("help" in parsed) {
1158
+ printCreateHelp();
1159
+ return;
1160
+ }
1161
+ if ("error" in parsed) {
1162
+ yield* Console.error(`Error: ${parsed.error}`);
1163
+ yield* Console.log("");
1164
+ printCreateHelp();
1165
+ process.exitCode = 1;
1166
+ return;
1167
+ }
1168
+ const options = "interactive" in parsed ? yield* runInteractive() : parsed.options;
1169
+ yield* scaffold(options);
1170
+ });
1171
+
1172
+ export { SERVER_TYPES, generateSDL, generateSDLFromModule, isValidServerType, loadSchema, printCreateHelp, runCreate, scaffold };
54
1173
  //# sourceMappingURL=index.js.map
55
1174
  //# sourceMappingURL=index.js.map