@prisma/cli-init 0.5.1 → 0.6.1

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.
@@ -1,1486 +0,0 @@
1
- import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
2
- import {
3
- __export
4
- } from "./chunk-YX4UTTNJ.js";
5
-
6
- // src/platform/_lib/utils.ts
7
- import internals2 from "@prisma/internals";
8
- import { bold, green } from "kleur/colors";
9
-
10
- // src/platform/_lib/cli/parameters.ts
11
- import internals from "@prisma/internals";
12
- var getRequiredParameter = (args, names, environmentVariable) => {
13
- const value = getOptionalParameter(args, names, environmentVariable);
14
- if (value === void 0)
15
- return new Error(`Missing ${names.join(" or ")} parameter`);
16
- return value;
17
- };
18
- function argOrThrow(argv, spec) {
19
- const args = internals.arg(argv, spec);
20
- if (internals.isError(args))
21
- throw args;
22
- return args;
23
- }
24
- var getRequiredParameterOrThrow = (args, names, environmentVariable) => {
25
- const value = getRequiredParameter(args, names, environmentVariable);
26
- if (value instanceof Error)
27
- throw new Error(`Missing ${names.join(" or ")} parameter`);
28
- return value;
29
- };
30
- var getOptionalParameter = (args, names, environmentVariable) => {
31
- const entry = Object.entries(args).find(([key]) => names.includes(key));
32
- if (!entry) {
33
- if (environmentVariable) {
34
- const value = process.env[environmentVariable];
35
- if (value) {
36
- return value;
37
- }
38
- }
39
- }
40
- return entry?.[1] ?? void 0;
41
- };
42
-
43
- // src/platform/_lib/credentials.ts
44
- import fs2 from "fs-extra";
45
- import path from "path";
46
- import XdgAppPaths from "xdg-app-paths";
47
-
48
- // src/platform/_lib/jsonFile.ts
49
- import fs from "fs-extra";
50
- var parse = (buffer, { beforeParse, reviver } = {}) => {
51
- let data = new TextDecoder().decode(buffer);
52
- if (typeof beforeParse === "function") {
53
- data = beforeParse(data);
54
- }
55
- return JSON.parse(data, reviver);
56
- };
57
- var loadJsonFile = async (filePath, options) => {
58
- const buffer = await fs.readFile(filePath);
59
- return parse(buffer, options);
60
- };
61
-
62
- // src/platform/_lib/prelude.ts
63
- var unknownToError = (unknown) => {
64
- if (unknown instanceof Error)
65
- return unknown;
66
- return new Error(`Unknown error: ${unknown}`);
67
- };
68
- var id = (value) => value;
69
- var isObject = (obj) => {
70
- return obj !== null && typeof obj === "object" && !Array.isArray(obj);
71
- };
72
- var tryCatch = (fn, catcher) => {
73
- try {
74
- return fn();
75
- } catch (e) {
76
- return catcher ? catcher(unknownToError(e)) : unknownToError(e);
77
- }
78
- };
79
-
80
- // src/platform/_lib/credentials.ts
81
- var credentialsFileDirectoryPath = new XdgAppPaths("prisma-platform-cli").config();
82
- var credentialsFilePath = path.join(credentialsFileDirectoryPath, "auth.json");
83
- var parseCredentials = (data) => {
84
- if (typeof data !== "object" || data === null)
85
- throw new Error("Invalid credentials");
86
- if (!("token" in data) || typeof data["token"] !== "string")
87
- throw new Error("Invalid credentials");
88
- return data;
89
- };
90
- var credentialsFile = {
91
- path: credentialsFilePath,
92
- save: async (data) => fs2.mkdirp(credentialsFileDirectoryPath).then(() => fs2.writeJSON(credentialsFilePath, data)).catch(unknownToError),
93
- load: async () => fs2.pathExists(credentialsFilePath).then((exists) => exists ? loadJsonFile(credentialsFilePath).then(parseCredentials) : null).catch(unknownToError),
94
- delete: async () => fs2.pathExists(credentialsFilePath).then((exists) => exists ? fs2.remove(credentialsFilePath) : void 0).then(() => null).catch(unknownToError)
95
- };
96
-
97
- // src/platform/_lib/utils.ts
98
- var platformParameters = {
99
- global: {
100
- // TODO Remove this from global once we have a way for parents to strip out flags upon parsing.
101
- "--token": String,
102
- "--json": Boolean
103
- },
104
- workspace: {
105
- "--token": String,
106
- "--workspace": String,
107
- "--json": Boolean,
108
- "-w": "--workspace"
109
- },
110
- project: {
111
- "--token": String,
112
- "--project": String,
113
- "-p": "--project"
114
- },
115
- environment: {
116
- "--token": String,
117
- "--environment": String,
118
- "-e": "--environment"
119
- },
120
- serviceToken: {
121
- "--token": String,
122
- "--serviceToken": String,
123
- "-s": "--serviceToken"
124
- },
125
- apikey: {
126
- "--token": String,
127
- "--apikey": String
128
- }
129
- };
130
- var ErrorPlatformUnauthorized = new Error(
131
- `No platform credentials found. Run ${green(internals2.getCommandWithExecutor("prisma platform auth login --early-access"))} first. Alternatively you can provide a token via the \`--token\` or \`-t\` parameters, or set the 'PRISMA_TOKEN' environment variable with a token.`
132
- // prettier-ignore
133
- );
134
- var getTokenOrThrow = async (args) => {
135
- const token = getOptionalParameter(args, ["--token", "-t"], "PRISMA_TOKEN");
136
- if (token)
137
- return token;
138
- const credentials = await credentialsFile.load();
139
- if (internals2.isError(credentials))
140
- throw credentials;
141
- if (!credentials)
142
- throw ErrorPlatformUnauthorized;
143
- return credentials.token;
144
- };
145
- var accelerateConnectionStringUrl = "prisma://accelerate.prisma-data.net";
146
- var generateConnectionString = (apiKey) => {
147
- const url = new URL(accelerateConnectionStringUrl);
148
- url.searchParams.set("api_key", apiKey);
149
- return bold(url.href);
150
- };
151
- var poll = async (fn, until, waitMs, timeoutMs, message) => {
152
- const endTime = (/* @__PURE__ */ new Date()).getMilliseconds() + timeoutMs;
153
- const wait = () => new Promise((resolve) => {
154
- setTimeout(resolve, waitMs);
155
- });
156
- let result = await fn();
157
- while (!until(result)) {
158
- const waitTime = (/* @__PURE__ */ new Date()).getMilliseconds() + waitMs;
159
- if (waitTime > endTime) {
160
- throw new Error(`polling timed out after ${timeoutMs}ms`);
161
- }
162
- if (message)
163
- console.log(message);
164
- result = await wait().then(fn);
165
- }
166
- if (internals2.isError(result))
167
- throw result;
168
- return result;
169
- };
170
- var printPpgInitOutput = ({
171
- databaseUrl,
172
- workspaceId,
173
- projectId,
174
- environmentId,
175
- isExistingPrismaProject = false
176
- }) => {
177
- const newPrismaProjectOutput = `
178
- We created an initial ${green("schema.prisma")} file and a ${green(".env")} file with your ${green(
179
- "DATABASE_URL"
180
- )} environment variable already set.
181
-
182
- ${bold("--- Next steps ---")}
183
-
184
- Go to ${internals2.link("https://pris.ly/ppg-init")} for detailed instructions.
185
-
186
- ${bold("1. Define your database schema")}
187
- Open the ${green("schema.prisma")} file and define your first models. Check the docs if you need inspiration: ${internals2.link(
188
- "https://pris.ly/ppg-init"
189
- )}.
190
-
191
- ${bold("2. Apply migrations")}
192
- Run the following command to create and apply a migration:
193
- ${green("npx prisma migrate dev --name init")}
194
-
195
- ${bold(`3. Manage your data`)}
196
- View and edit your data locally by running this command:
197
- ${green("npx prisma studio")}
198
-
199
- ...or online in Console:
200
- ${internals2.link(`https://console.prisma.io/${workspaceId}/${projectId}/${environmentId}/studio`)}
201
-
202
- ${bold(`4. Send queries from your app`)}
203
- To access your database from a JavaScript/TypeScript app, you need to use Prisma ORM. Go here for step-by-step instructions: ${internals2.link(
204
- "https://pris.ly/ppg-init"
205
- )}
206
- `;
207
- const existingPrismaProjectOutput = `
208
- We found an existing ${green("schema.prisma")} file in your current project directory.
209
-
210
- ${bold("--- Database URL ---")}
211
-
212
- Connect Prisma ORM to your Prisma Postgres database with this URL:
213
-
214
- ${green(databaseUrl)}
215
-
216
- ${bold("--- Next steps ---")}
217
-
218
- Go to ${internals2.link("https://pris.ly/ppg-init")} for detailed instructions.
219
-
220
- ${bold("1. Install and use the Prisma Accelerate extension")}
221
- Prisma Postgres requires the Prisma Accelerate extension for querying. If you haven't already installed it, install it in your project:
222
- ${green("npm install @prisma/extension-accelerate")}
223
-
224
- ...and add it to your Prisma Client instance:
225
- ${green('import { withAccelerate } from "@prisma/extension-accelerate"')}
226
-
227
- ${green("const prisma = new PrismaClient().$extends(withAccelerate())")}
228
-
229
- ${bold("2. Apply migrations")}
230
- Run the following command to create and apply a migration:
231
- ${green("npx prisma migrate dev")}
232
-
233
- ${bold(`3. Manage your data`)}
234
- View and edit your data locally by running this command:
235
- ${green("npx prisma studio")}
236
-
237
- ...or online in Console:
238
- ${internals2.link(`https://console.prisma.io/${workspaceId}/${projectId}/${environmentId}/studio`)}
239
-
240
- ${bold(`4. Send queries from your app`)}
241
- If you already have an existing app with Prisma ORM, you can now run it and it will send queries against your newly created Prisma Postgres instance.
242
-
243
- ${bold(`5. Learn more`)}
244
- For more info, visit the Prisma Postgres docs: ${internals2.link("https://pris.ly/ppg-docs")}
245
- `;
246
- return isExistingPrismaProject ? existingPrismaProjectOutput : newPrismaProjectOutput;
247
- };
248
-
249
- // src/platform/accelerate/_.ts
250
- var __exports = {};
251
- __export(__exports, {
252
- $: () => $,
253
- Disable: () => Disable,
254
- Enable: () => Enable
255
- });
256
-
257
- // src/platform/_lib/cli/dispatchToSubCommand.ts
258
- import internals3 from "@prisma/internals";
259
- var { HelpError, link } = internals3;
260
- var dispatchToSubCommand = async (commands, argv, config) => {
261
- const commandName = argv[0];
262
- if (!commandName)
263
- return new HelpError(`Unknown command.`);
264
- const command = commands[commandName];
265
- if (!command)
266
- return new HelpError(`Unknown command or parameter "${commandName}"`);
267
- const hasHelpFlag = Boolean(argv.find((it) => ["-h", "--help"].includes(it)));
268
- if (hasHelpFlag)
269
- return `Help output for this command will be available soon. In the meantime, visit ${link("https://pris.ly/cli/platform-docs")} for more information.`;
270
- const result = await command.parse(argv.slice(1), config);
271
- return result;
272
- };
273
-
274
- // src/platform/_lib/cli/namespace.ts
275
- var createNamespace = () => {
276
- return class $7 {
277
- constructor(commands) {
278
- this.commands = commands;
279
- }
280
- static new(commands) {
281
- return new $7(commands);
282
- }
283
- async parse(argv, config) {
284
- return await dispatchToSubCommand(this.commands, argv, config);
285
- }
286
- };
287
- };
288
-
289
- // src/platform/accelerate/$.ts
290
- var $ = createNamespace();
291
-
292
- // src/platform/_lib/messages.ts
293
- import internals4 from "@prisma/internals";
294
- import { bold as bold2, dim, green as green2, white } from "kleur/colors";
295
- var table = (object, renderersInput) => {
296
- const renderers = {
297
- key: renderersInput.key ?? dim,
298
- // eslint-disable-next-line
299
- values: internals4.mapObjectValues(
300
- renderersInput.values ?? {},
301
- (_) => _ === true ? id : _
302
- )
303
- };
304
- return internals4.formatTable(
305
- Object.entries(renderers.values).map(([propertyName, renderer]) => {
306
- const valueRendered = renderer(object[propertyName]);
307
- if (valueRendered === null)
308
- return null;
309
- return [renderers.key(String(propertyName)), valueRendered];
310
- }).filter(Boolean)
311
- );
312
- };
313
- var successMessage = (message) => `${green2("Success!")} ${message}`;
314
- var messages = {
315
- resourceCreated: (resource) => successMessage(`${resource.__typename} ${resource.displayName} - ${resource.id} created.`),
316
- resourceDeleted: (resource) => successMessage(`${resource.__typename} ${resource.displayName} - ${resource.id} deleted.`),
317
- resource: (resource, renderers) => {
318
- return messages.table(resource, {
319
- values: {
320
- displayName: (_) => white(bold2(_)),
321
- id: true,
322
- createdAt: (_) => _ ? Intl.DateTimeFormat().format(new Date(_)) : null,
323
- ...renderers
324
- }
325
- });
326
- },
327
- resourceList: (records) => {
328
- if (records.length === 0)
329
- return messages.info("No records found.");
330
- return records.map((record) => messages.resource(record)).join("\n\n\n");
331
- },
332
- info: (message) => message,
333
- sections: (sections) => sections.join("\n\n"),
334
- table,
335
- success: successMessage
336
- };
337
-
338
- // src/platform/_lib/pdp.ts
339
- import fetch, { Headers } from "node-fetch";
340
-
341
- // src/platform/_lib/userAgent.ts
342
- import Debug from "@prisma/debug";
343
- import internals5 from "@prisma/internals";
344
- import * as Checkpoint from "checkpoint-client";
345
-
346
- // package.json
347
- var version = "0.5.1";
348
-
349
- // src/platform/_lib/userAgent.ts
350
- var debug = Debug("prisma:cli:platform:_lib:userAgent");
351
- var getUserAgent = async () => {
352
- const signature = await Checkpoint.getSignature().catch(unknownToError);
353
- if (internals5.isError(signature))
354
- debug(`await checkpoint.getSignature() failed silently with ${signature.message}`);
355
- const signatureString = internals5.isError(signature) ? "unknown" : signature;
356
- return `prisma-cli-init/${version} (Signature: ${signatureString})`;
357
- };
358
-
359
- // src/platform/_lib/pdp.ts
360
- var platformAPIEndpoint = new URL("https://console.prisma.io/api");
361
- var consoleUrl = new URL("https://console.prisma.io");
362
- var requestOrThrow = async (params) => {
363
- const userAgent = await getUserAgent();
364
- const method = "POST";
365
- const headers = new Headers({
366
- "Content-Type": "application/json",
367
- Authorization: `Bearer ${params.token}`,
368
- // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
369
- "User-Agent": userAgent
370
- });
371
- const body = JSON.stringify(params.body);
372
- const response = await fetch(platformAPIEndpoint.href, { method, headers, body });
373
- const text = await response.text();
374
- if (response.status >= 400)
375
- throw new Error(text);
376
- const json = JSON.parse(text);
377
- if (json.error)
378
- throw new Error(`Error from PDP Platform API: ${text}`);
379
- const error = Object.values(json.data).filter(
380
- (rootFieldValue) => typeof rootFieldValue === "object" && rootFieldValue !== null && rootFieldValue["__typename"]?.startsWith("Error")
381
- )[0];
382
- if (error)
383
- throw errorFromPlatformError({ message: "<message not selected from server>", ...error });
384
- return json.data;
385
- };
386
- var errorFromPlatformError = (error) => {
387
- return new Error(error.message);
388
- };
389
-
390
- // src/platform/accelerate/disable.ts
391
- var Disable = class _Disable {
392
- static new() {
393
- return new _Disable();
394
- }
395
- async parse(argv, _config) {
396
- const args = argOrThrow(argv, {
397
- ...platformParameters.environment
398
- });
399
- const token = await getTokenOrThrow(args);
400
- const environmentId = getRequiredParameterOrThrow(args, ["--environment", "-e"]);
401
- await requestOrThrow({
402
- token,
403
- body: {
404
- query: (
405
- /* GraphQL */
406
- `
407
- mutation ($input: MutationAccelerateDisableInput!) {
408
- accelerateDisable(input: $input) {
409
- __typename
410
- ... on Error {
411
- message
412
- }
413
- }
414
- }
415
- `
416
- ),
417
- variables: {
418
- input: { environmentId }
419
- }
420
- }
421
- });
422
- return messages.success(
423
- `Accelerate disabled. Prisma clients connected to ${environmentId} will not be able to send queries through Accelerate.`
424
- );
425
- }
426
- };
427
-
428
- // src/platform/accelerate/enable.ts
429
- import internals6 from "@prisma/internals";
430
- var Enable = class _Enable {
431
- static new() {
432
- return new _Enable();
433
- }
434
- async parse(argv, _config) {
435
- const args = internals6.arg(argv, {
436
- ...platformParameters.environment,
437
- "--url": String,
438
- // TODO rename to "serviceToken" in a future release.
439
- "--apikey": Boolean,
440
- "--region": String
441
- });
442
- if (internals6.isError(args))
443
- return args;
444
- const token = await getTokenOrThrow(args);
445
- const environmentId = getRequiredParameterOrThrow(args, ["--environment", "-e"]);
446
- const connectionString = getRequiredParameterOrThrow(args, ["--url"]);
447
- const withServiceToken = getOptionalParameter(args, ["--apikey"]) ?? false;
448
- const regionId = getOptionalParameter(args, ["--region"]);
449
- const { databaseLinkCreate } = await requestOrThrow({
450
- token,
451
- body: {
452
- query: (
453
- /* GraphQL */
454
- `
455
- mutation ($input: MutationDatabaseLinkCreateInput!) {
456
- databaseLinkCreate(input: $input) {
457
- __typename
458
- ... on Error {
459
- message
460
- }
461
- ... on DatabaseLink {
462
- id
463
- }
464
- }
465
- }
466
- `
467
- ),
468
- variables: {
469
- input: {
470
- environmentId,
471
- connectionString,
472
- ...regionId && { regionId }
473
- }
474
- }
475
- }
476
- });
477
- const { serviceTokenCreate } = await requestOrThrow({
478
- token,
479
- body: {
480
- query: (
481
- /* GraphQL */
482
- `
483
- mutation (
484
- $accelerateEnableInput: MutationAccelerateEnableInput!
485
- $serviceTokenCreateInput: MutationServiceTokenCreateInput!
486
- $withServiceToken: Boolean!
487
- ) {
488
- accelerateEnable(input: $accelerateEnableInput) {
489
- __typename
490
- ... on Error {
491
- message
492
- }
493
- }
494
- serviceTokenCreate(input: $serviceTokenCreateInput) @include(if: $withServiceToken) {
495
- __typename
496
- ... on Error {
497
- message
498
- }
499
- ... on ServiceTokenWithValue {
500
- value
501
- }
502
- }
503
- }
504
- `
505
- ),
506
- variables: {
507
- withServiceToken,
508
- accelerateEnableInput: { databaseLinkId: databaseLinkCreate.id },
509
- serviceTokenCreateInput: { environmentId }
510
- }
511
- }
512
- });
513
- const gettingStartedUrl = internals6.link("https://pris.ly/d/accelerate-getting-started");
514
- if (serviceTokenCreate) {
515
- return messages.success(
516
- `Accelerate enabled. Use this Accelerate connection string to authenticate requests:
517
-
518
- ${generateConnectionString(serviceTokenCreate.value)}
519
-
520
- For more information, check out the Getting started guide here: ${gettingStartedUrl}`
521
- );
522
- } else {
523
- return messages.success(
524
- `Accelerate enabled. Use your secure API key in your Accelerate connection string to authenticate requests.
525
-
526
- For more information, check out the Getting started guide here: ${gettingStartedUrl}`
527
- );
528
- }
529
- }
530
- };
531
-
532
- // src/platform/auth/_.ts
533
- var __exports2 = {};
534
- __export(__exports2, {
535
- $: () => $2,
536
- Login: () => Login,
537
- Logout: () => Logout,
538
- Show: () => Show,
539
- loginOrSignup: () => loginOrSignup
540
- });
541
-
542
- // src/platform/auth/$.ts
543
- var $2 = createNamespace();
544
-
545
- // src/platform/auth/login.ts
546
- import { select } from "@inquirer/prompts";
547
- import Debug2 from "@prisma/debug";
548
- import internals7 from "@prisma/internals";
549
- import { listen } from "async-listen";
550
- import http from "http";
551
- import { green as green3 } from "kleur/colors";
552
- import open from "open";
553
- var debug2 = Debug2("prisma:cli:platform:login");
554
- var Login = class _Login {
555
- static new() {
556
- return new _Login();
557
- }
558
- async parse(argv, _config) {
559
- const args = internals7.arg(argv, {
560
- // internal optimize flag to track signup attribution
561
- "--optimize": Boolean
562
- });
563
- if (internals7.isError(args))
564
- return args;
565
- if (args["--optimize"]) {
566
- console.warn("The '--optimize' flag is deprecated. Use API keys instead.");
567
- }
568
- const credentials = await credentialsFile.load();
569
- if (internals7.isError(credentials))
570
- throw credentials;
571
- if (credentials)
572
- return `Already authenticated. Run ${green3(internals7.getCommandWithExecutor("prisma platform auth show --early-access"))} to see the current user.`;
573
- console.info("Authenticating to Prisma Platform CLI via browser.\n");
574
- const server = http.createServer();
575
- const randomPort = 0;
576
- const redirectUrl = await listen(server, randomPort, "127.0.0.1");
577
- const loginUrl = await createLoginUrl({ connection: "github", redirectTo: redirectUrl.href });
578
- console.info("Visit the following URL in your browser to authenticate:");
579
- console.info(internals7.link(loginUrl.href));
580
- const callbackResult = await Promise.all([
581
- new Promise((resolve, reject) => {
582
- server.once("request", (req, res) => {
583
- server.close();
584
- res.setHeader("connection", "close");
585
- const searchParams = new URL(req.url || "/", "http://localhost").searchParams;
586
- const token = searchParams.get("token") ?? "";
587
- const error = searchParams.get("error");
588
- const location = getBaseAuthUrl();
589
- if (error) {
590
- location.pathname += "/error";
591
- location.searchParams.set("error", error);
592
- reject(new Error(error));
593
- } else {
594
- const user = decodeUser(searchParams.get("user") ?? "");
595
- if (user) {
596
- searchParams.delete("token");
597
- searchParams.delete("user");
598
- location.pathname += "/success";
599
- const nextSearchParams = new URLSearchParams({
600
- ...Object.fromEntries(searchParams.entries()),
601
- email: user.email
602
- });
603
- location.search = nextSearchParams.toString();
604
- resolve({ token, user });
605
- } else {
606
- location.pathname += "/error";
607
- location.searchParams.set("error", "Invalid user");
608
- reject(new Error("Invalid user"));
609
- }
610
- }
611
- res.statusCode = 302;
612
- res.setHeader("location", location.href);
613
- res.end();
614
- });
615
- server.once("error", reject);
616
- }),
617
- open(loginUrl.href)
618
- ]).then((results) => results[0]).catch(unknownToError);
619
- if (internals7.isError(callbackResult))
620
- throw new Error(`Authentication failed: ${callbackResult.message}`);
621
- {
622
- const writeResult = await credentialsFile.save({ token: callbackResult.token });
623
- if (internals7.isError(writeResult))
624
- throw new Error("Writing credentials to disk failed", { cause: writeResult });
625
- }
626
- return successMessage(`Authentication successful for ${callbackResult.user.email}`);
627
- }
628
- };
629
- var getBaseAuthUrl = () => new URL("/auth/cli", consoleUrl);
630
- var createLoginUrl = async (params) => {
631
- const userAgent = await getUserAgent();
632
- const state = {
633
- client: userAgent,
634
- ...params
635
- };
636
- const stateEncoded = encodeState(state);
637
- const url = getBaseAuthUrl();
638
- url.searchParams.set("state", stateEncoded);
639
- return url;
640
- };
641
- var encodeState = (state) => Buffer.from(JSON.stringify(state), "utf-8").toString("base64");
642
- var decodeUser = (stringifiedUser) => {
643
- try {
644
- const maybeUser = JSON.parse(Buffer.from(stringifiedUser, `base64`).toString(`utf-8`));
645
- if (typeof maybeUser !== "object" || maybeUser === null)
646
- return false;
647
- const isUser = typeof maybeUser.id === "string" && typeof maybeUser.displayName === "string" && typeof maybeUser.email === "string";
648
- return isUser ? maybeUser : null;
649
- } catch (e) {
650
- debug2(`parseUser() failed silently with ${e}`);
651
- return null;
652
- }
653
- };
654
- var loginOrSignup = async () => {
655
- const providerAnswer = await select({
656
- message: "Select an authentication method",
657
- default: "google",
658
- choices: [
659
- { name: "Google", value: "google" },
660
- { name: "GitHub", value: "github" }
661
- ]
662
- });
663
- console.info("Authenticating to Prisma Platform via browser.\n");
664
- const server = http.createServer();
665
- const randomPort = 0;
666
- const redirectUrl = await listen(server, randomPort, "127.0.0.1");
667
- const loginUrl = await createLoginUrl({ connection: providerAnswer, redirectTo: redirectUrl.href });
668
- console.info("Visit the following URL in your browser to authenticate:");
669
- console.info(internals7.link(loginUrl.href));
670
- const callbackResult = await Promise.all([
671
- new Promise((resolve, reject) => {
672
- server.once("request", (req, res) => {
673
- server.close();
674
- res.setHeader("connection", "close");
675
- const searchParams = new URL(req.url || "/", "http://localhost").searchParams;
676
- const token = searchParams.get("token") ?? "";
677
- const error = searchParams.get("error");
678
- const location = getBaseAuthUrl();
679
- if (error) {
680
- location.pathname += "/error";
681
- location.searchParams.set("error", error);
682
- reject(new Error(error));
683
- } else {
684
- const user = decodeUser(searchParams.get("user") ?? "");
685
- if (user) {
686
- searchParams.delete("token");
687
- searchParams.delete("user");
688
- location.pathname += "/success";
689
- const nextSearchParams = new URLSearchParams({
690
- ...Object.fromEntries(searchParams.entries()),
691
- email: user.email
692
- });
693
- location.search = nextSearchParams.toString();
694
- resolve({ token, user });
695
- } else {
696
- location.pathname += "/error";
697
- location.searchParams.set("error", "Invalid user");
698
- reject(new Error("Invalid user"));
699
- }
700
- }
701
- res.statusCode = 302;
702
- res.setHeader("location", location.href);
703
- res.end();
704
- });
705
- server.once("error", reject);
706
- }),
707
- open(loginUrl.href)
708
- ]).then((results) => results[0]).catch(unknownToError);
709
- if (internals7.isError(callbackResult))
710
- throw new Error(`Authentication failed: ${callbackResult.message}`);
711
- {
712
- const writeResult = await credentialsFile.save({ token: callbackResult.token });
713
- if (internals7.isError(writeResult))
714
- throw new Error("Writing credentials to disk failed", { cause: writeResult });
715
- }
716
- return {
717
- message: successMessage(`Authentication successful for ${callbackResult.user.email}`),
718
- email: callbackResult.user.email,
719
- token: callbackResult.token
720
- };
721
- };
722
-
723
- // src/platform/auth/logout.ts
724
- import internals9 from "@prisma/internals";
725
- import { green as green4 } from "kleur/colors";
726
-
727
- // src/platform/_lib/jwt.ts
728
- import internals8 from "@prisma/internals";
729
- var decodeJwt = (jwt) => {
730
- if (typeof jwt !== "string")
731
- throw new Error("JWTs must use Compact JWS serialization, JWT must be a string");
732
- const { 1: payload, length } = jwt.split(".");
733
- if (length === 5)
734
- throw new Error("Only JWTs using Compact JWS serialization can be decoded");
735
- if (length !== 3)
736
- throw new Error("Invalid JWT");
737
- if (!payload)
738
- throw new Error("JWTs must contain a payload");
739
- const decoded = tryCatch(
740
- () => atob(payload),
741
- () => new Error("Failed to base64 decode the payload.")
742
- );
743
- if (internals8.isError(decoded))
744
- return decoded;
745
- const result = tryCatch(
746
- () => JSON.parse(decoded),
747
- () => new Error("Failed to parse the decoded payload as JSON.")
748
- );
749
- if (internals8.isError(result))
750
- return result;
751
- if (!isObject(result))
752
- throw new Error("Invalid JWT Claims Set.");
753
- return result;
754
- };
755
-
756
- // src/platform/auth/logout.ts
757
- var Logout = class _Logout {
758
- static new() {
759
- return new _Logout();
760
- }
761
- async parse() {
762
- const credentials = await credentialsFile.load();
763
- if (internals9.isError(credentials))
764
- throw credentials;
765
- if (!credentials)
766
- return `You are not currently logged in. Run ${green4(internals9.getCommandWithExecutor("prisma platform auth login --early-access"))} to log in.`;
767
- if (credentials.token) {
768
- const jwt = decodeJwt(credentials.token);
769
- if (!internals9.isError(jwt) && jwt.jti) {
770
- await requestOrThrow({
771
- token: credentials.token,
772
- body: {
773
- query: (
774
- /* GraphQL */
775
- `
776
- mutation ($input: MutationManagementTokenDeleteInput!) {
777
- managementTokenDelete(input: $input) {
778
- __typename
779
- ... on Error {
780
- message
781
- }
782
- }
783
- }
784
- `
785
- ),
786
- variables: {
787
- input: {
788
- id: jwt.jti
789
- }
790
- }
791
- }
792
- });
793
- }
794
- }
795
- await credentialsFile.delete();
796
- return successMessage("You have logged out.");
797
- }
798
- };
799
-
800
- // src/platform/auth/show.ts
801
- import { green as green5 } from "kleur/colors";
802
- var Show = class _Show {
803
- static new() {
804
- return new _Show();
805
- }
806
- async parse(argv, _config) {
807
- const args = argOrThrow(argv, {
808
- ...platformParameters.global,
809
- "--sensitive": Boolean
810
- });
811
- const token = await getTokenOrThrow(args);
812
- const { me } = await requestOrThrow({
813
- token,
814
- body: {
815
- query: (
816
- /* graphql */
817
- `
818
- query {
819
- me {
820
- __typename
821
- user {
822
- __typename
823
- id
824
- email
825
- displayName
826
- }
827
- }
828
- }
829
- `
830
- )
831
- }
832
- });
833
- const data = {
834
- ...me.user,
835
- token: getOptionalParameter(args, ["--sensitive"]) ? token : null
836
- };
837
- return messages.sections([
838
- messages.info(`Currently authenticated as ${green5(me.user.email)}`),
839
- messages.resource(data, {
840
- email: true,
841
- token: true
842
- })
843
- ]);
844
- }
845
- };
846
-
847
- // src/platform/environment/_.ts
848
- var __exports3 = {};
849
- __export(__exports3, {
850
- $: () => $3,
851
- Create: () => Create,
852
- Delete: () => Delete,
853
- Show: () => Show2,
854
- getEnvironmentOrThrow: () => getEnvironmentOrThrow
855
- });
856
-
857
- // src/platform/environment/$.ts
858
- var $3 = createNamespace();
859
-
860
- // src/platform/environment/create.ts
861
- var Create = class _Create {
862
- static new() {
863
- return new _Create();
864
- }
865
- async parse(argv, _config) {
866
- const args = argOrThrow(argv, {
867
- ...platformParameters.project,
868
- "--name": String,
869
- "-n": "--name"
870
- });
871
- const token = await getTokenOrThrow(args);
872
- const projectId = getRequiredParameterOrThrow(args, ["--project", "-p"]);
873
- const displayName = getOptionalParameter(args, ["--name", "-n"]);
874
- const { environmentCreate } = await requestOrThrow({
875
- token,
876
- body: {
877
- query: (
878
- /* graphql */
879
- `
880
- mutation ($input: MutationEnvironmentCreateInput!) {
881
- environmentCreate(input: $input) {
882
- __typename
883
- ...on Error {
884
- message
885
- }
886
- ...on Environment {
887
- id
888
- createdAt
889
- displayName
890
- }
891
- }
892
- }
893
- `
894
- ),
895
- variables: {
896
- input: {
897
- projectId,
898
- displayName
899
- }
900
- }
901
- }
902
- });
903
- return messages.resourceCreated(environmentCreate);
904
- }
905
- };
906
-
907
- // src/platform/environment/delete.ts
908
- import internals10 from "@prisma/internals";
909
- var Delete = class _Delete {
910
- static new() {
911
- return new _Delete();
912
- }
913
- async parse(argv, _config) {
914
- const args = internals10.arg(argv, {
915
- ...platformParameters.environment
916
- });
917
- if (internals10.isError(args))
918
- return args;
919
- const token = await getTokenOrThrow(args);
920
- const environmentId = getRequiredParameterOrThrow(args, ["--environment", "-e"]);
921
- const { environmentDelete } = await requestOrThrow({
922
- token,
923
- body: {
924
- query: (
925
- /* graphql */
926
- `
927
- mutation ($input: MutationEnvironmentDeleteInput!) {
928
- environmentDelete(input: $input) {
929
- __typename
930
- ...on Error {
931
- message
932
- }
933
- ...on Environment {
934
- id
935
- createdAt
936
- displayName
937
- }
938
- }
939
- }
940
- `
941
- ),
942
- variables: {
943
- input: {
944
- id: environmentId
945
- }
946
- }
947
- }
948
- });
949
- return messages.resourceDeleted(environmentDelete);
950
- }
951
- };
952
-
953
- // src/platform/environment/show.ts
954
- import internals11 from "@prisma/internals";
955
- var Show2 = class _Show {
956
- static new() {
957
- return new _Show();
958
- }
959
- async parse(argv, _config) {
960
- const args = internals11.arg(argv, {
961
- ...platformParameters.project
962
- });
963
- if (internals11.isError(args))
964
- return args;
965
- const token = await getTokenOrThrow(args);
966
- const projectId = getRequiredParameterOrThrow(args, ["--project", "-p"]);
967
- const { project } = await requestOrThrow({
968
- token,
969
- body: {
970
- query: (
971
- /* GraphQL */
972
- `
973
- query ($input: QueryProjectInput!) {
974
- project(input: $input) {
975
- __typename
976
- ... on Error {
977
- message
978
- }
979
- ... on Project {
980
- environments {
981
- __typename
982
- id
983
- createdAt
984
- displayName
985
- }
986
- }
987
- }
988
- }
989
- `
990
- ),
991
- variables: {
992
- input: {
993
- id: projectId
994
- }
995
- }
996
- }
997
- });
998
- return messages.resourceList(project.environments);
999
- }
1000
- };
1001
- var getEnvironmentOrThrow = async (input) => {
1002
- const { token, environmentId } = input;
1003
- const { environment } = await requestOrThrow({
1004
- token,
1005
- body: {
1006
- query: (
1007
- /* GraphQL */
1008
- `
1009
- query ($input: QueryEnvironmentInput!) {
1010
- environment(input: $input) {
1011
- __typename
1012
- ... on Error {
1013
- message
1014
- }
1015
- ... on Environment {
1016
- __typename
1017
- id
1018
- displayName
1019
- ppg {
1020
- status
1021
- }
1022
- accelerate {
1023
- status {
1024
- ... on AccelerateStatusEnabled {
1025
- __typename
1026
- enabled
1027
- }
1028
- ... on AccelerateStatusDisabled {
1029
- __typename
1030
- enabled
1031
- }
1032
- }
1033
- }
1034
- }
1035
- }
1036
- }
1037
- `
1038
- ),
1039
- variables: {
1040
- input: {
1041
- id: environmentId
1042
- }
1043
- }
1044
- }
1045
- });
1046
- return environment;
1047
- };
1048
-
1049
- // src/platform/project/_.ts
1050
- var __exports4 = {};
1051
- __export(__exports4, {
1052
- $: () => $4,
1053
- Create: () => Create2,
1054
- Delete: () => Delete2,
1055
- Show: () => Show3,
1056
- createProjectOrThrow: () => createProjectOrThrow
1057
- });
1058
-
1059
- // src/platform/project/$.ts
1060
- var $4 = createNamespace();
1061
-
1062
- // src/platform/project/create.ts
1063
- var Create2 = class _Create {
1064
- static new() {
1065
- return new _Create();
1066
- }
1067
- async parse(argv, _config) {
1068
- const args = argOrThrow(argv, {
1069
- ...platformParameters.workspace,
1070
- "--name": String,
1071
- "-n": "--name"
1072
- });
1073
- const workspaceId = getRequiredParameterOrThrow(args, ["--workspace", "-w"]);
1074
- const displayName = getOptionalParameter(args, ["--name", "-n"]);
1075
- const project = await createProjectOrThrow({
1076
- token: await getTokenOrThrow(args),
1077
- workspaceId,
1078
- displayName
1079
- });
1080
- return messages.resourceCreated(project);
1081
- }
1082
- };
1083
- var createProjectOrThrow = async (input) => {
1084
- const { token, ...mutationInput } = input;
1085
- const { projectCreate } = await requestOrThrow({
1086
- token,
1087
- body: {
1088
- query: (
1089
- /* graphql */
1090
- `
1091
- mutation ($input: MutationProjectCreateInput!) {
1092
- projectCreate(input: $input) {
1093
- __typename
1094
- ...on Error {
1095
- message
1096
- }
1097
- ...on Project {
1098
- id
1099
- createdAt
1100
- displayName
1101
- defaultEnvironment {
1102
- id
1103
- displayName
1104
- }
1105
- }
1106
- }
1107
- }
1108
- `
1109
- ),
1110
- variables: {
1111
- input: mutationInput
1112
- }
1113
- }
1114
- });
1115
- return projectCreate;
1116
- };
1117
-
1118
- // src/platform/project/delete.ts
1119
- import internals12 from "@prisma/internals";
1120
- var Delete2 = class _Delete {
1121
- static new() {
1122
- return new _Delete();
1123
- }
1124
- async parse(argv, _config) {
1125
- const args = internals12.arg(argv, {
1126
- ...platformParameters.project
1127
- });
1128
- if (internals12.isError(args))
1129
- return args;
1130
- const token = await getTokenOrThrow(args);
1131
- const projectId = getRequiredParameterOrThrow(args, ["--project", "-p"]);
1132
- const { projectDelete } = await requestOrThrow({
1133
- token,
1134
- body: {
1135
- query: (
1136
- /* graphql */
1137
- `
1138
- mutation ($input: MutationProjectDeleteInput!) {
1139
- projectDelete(input: $input) {
1140
- __typename
1141
- ...on Error {
1142
- message
1143
- }
1144
- ...on ProjectNode {
1145
- id
1146
- createdAt
1147
- displayName
1148
- }
1149
- }
1150
- }
1151
- `
1152
- ),
1153
- variables: {
1154
- input: {
1155
- id: projectId
1156
- }
1157
- }
1158
- }
1159
- });
1160
- return messages.resourceDeleted(projectDelete);
1161
- }
1162
- };
1163
-
1164
- // src/platform/project/show.ts
1165
- import internals13 from "@prisma/internals";
1166
- var Show3 = class _Show {
1167
- static new() {
1168
- return new _Show();
1169
- }
1170
- async parse(argv, _config) {
1171
- const args = internals13.arg(argv, {
1172
- ...platformParameters.workspace
1173
- });
1174
- if (internals13.isError(args))
1175
- return args;
1176
- const token = await getTokenOrThrow(args);
1177
- const workspaceId = getRequiredParameterOrThrow(args, ["--workspace", "-w"]);
1178
- const { workspace } = await requestOrThrow({
1179
- token,
1180
- body: {
1181
- query: (
1182
- /* GraphQL */
1183
- `
1184
- query ($input: QueryWorkspaceInput!) {
1185
- workspace(input: $input) {
1186
- __typename
1187
- ... on Error {
1188
- message
1189
- }
1190
- ... on Workspace {
1191
- projects {
1192
- __typename
1193
- id
1194
- createdAt
1195
- displayName
1196
- }
1197
- }
1198
- }
1199
- }
1200
- `
1201
- ),
1202
- variables: {
1203
- input: {
1204
- id: workspaceId
1205
- }
1206
- }
1207
- }
1208
- });
1209
- return messages.resourceList(workspace.projects);
1210
- }
1211
- };
1212
-
1213
- // src/platform/serviceToken/_.ts
1214
- var __exports5 = {};
1215
- __export(__exports5, {
1216
- $: () => $5,
1217
- Create: () => Create3,
1218
- Delete: () => Delete3,
1219
- Show: () => Show4,
1220
- createOrThrow: () => createOrThrow
1221
- });
1222
-
1223
- // src/platform/serviceToken/$.ts
1224
- var $5 = createNamespace();
1225
-
1226
- // src/platform/serviceToken/create.ts
1227
- var Create3 = class _Create {
1228
- constructor(legacy = false) {
1229
- this.legacy = legacy;
1230
- }
1231
- static new(legacy = false) {
1232
- return new _Create(legacy);
1233
- }
1234
- async parse(argv, _config) {
1235
- const args = argOrThrow(argv, {
1236
- ...platformParameters.environment,
1237
- "--name": String,
1238
- "-n": "--name"
1239
- });
1240
- const token = await getTokenOrThrow(args);
1241
- const environmentId = getRequiredParameterOrThrow(args, ["--environment", "-e"]);
1242
- const displayName = getOptionalParameter(args, ["--name", "-n"]);
1243
- const serviceTokenCreate = await createOrThrow({ environmentId, displayName, token });
1244
- const resource = this.legacy ? {
1245
- ...serviceTokenCreate.serviceToken,
1246
- __typename: "APIKey"
1247
- } : serviceTokenCreate.serviceToken;
1248
- return messages.sections([messages.resourceCreated(resource), messages.info(serviceTokenCreate.value)]);
1249
- }
1250
- };
1251
- var createOrThrow = async (input) => {
1252
- const { environmentId, displayName, token } = input;
1253
- const { serviceTokenCreate } = await requestOrThrow({
1254
- token,
1255
- body: {
1256
- query: (
1257
- /* GraphQL */
1258
- `
1259
- mutation ($input: MutationServiceTokenCreateInput!) {
1260
- serviceTokenCreate(input: $input) {
1261
- __typename
1262
- ... on Error {
1263
- message
1264
- }
1265
- ... on ServiceTokenWithValue {
1266
- value
1267
- serviceToken {
1268
- __typename
1269
- id
1270
- createdAt
1271
- displayName
1272
- }
1273
- }
1274
- }
1275
- }
1276
- `
1277
- ),
1278
- variables: {
1279
- input: {
1280
- displayName,
1281
- environmentId
1282
- }
1283
- }
1284
- }
1285
- });
1286
- return serviceTokenCreate;
1287
- };
1288
-
1289
- // src/platform/serviceToken/delete.ts
1290
- var Delete3 = class _Delete {
1291
- constructor(legacy = false) {
1292
- this.legacy = legacy;
1293
- }
1294
- static new(legacy = false) {
1295
- return new _Delete(legacy);
1296
- }
1297
- async parse(argv, _config) {
1298
- const args = argOrThrow(argv, {
1299
- ...platformParameters[this.legacy ? "apikey" : "serviceToken"]
1300
- });
1301
- const token = await getTokenOrThrow(args);
1302
- const serviceTokenId = this.legacy ? getRequiredParameterOrThrow(args, ["--apikey"]) : getRequiredParameterOrThrow(args, ["--serviceToken", "-s"]);
1303
- const { serviceTokenDelete } = await requestOrThrow({
1304
- token,
1305
- body: {
1306
- query: (
1307
- /* GraphQL */
1308
- `
1309
- mutation ($input: MutationServiceTokenDeleteInput!) {
1310
- serviceTokenDelete(input: $input) {
1311
- __typename
1312
- ... on Error {
1313
- message
1314
- }
1315
- ... on ServiceTokenNode {
1316
- id
1317
- displayName
1318
- }
1319
- }
1320
- }
1321
- `
1322
- ),
1323
- variables: {
1324
- input: {
1325
- id: serviceTokenId
1326
- }
1327
- }
1328
- }
1329
- });
1330
- return messages.resourceDeleted(this.legacy ? { ...serviceTokenDelete, __typename: "APIKey" } : serviceTokenDelete);
1331
- }
1332
- };
1333
-
1334
- // src/platform/serviceToken/show.ts
1335
- import internals14 from "@prisma/internals";
1336
- var Show4 = class _Show {
1337
- constructor(legacy = false) {
1338
- this.legacy = legacy;
1339
- }
1340
- static new(legacy = false) {
1341
- return new _Show(legacy);
1342
- }
1343
- async parse(argv, _config) {
1344
- const args = internals14.arg(argv, {
1345
- ...platformParameters.environment
1346
- });
1347
- if (internals14.isError(args))
1348
- return args;
1349
- const token = await getTokenOrThrow(args);
1350
- const environmentId = getRequiredParameterOrThrow(args, ["--environment", "-e"]);
1351
- const { environment } = await requestOrThrow({
1352
- token,
1353
- body: {
1354
- query: (
1355
- /* GraphQL */
1356
- `
1357
- query ($input: QueryEnvironmentInput!) {
1358
- environment(input: $input) {
1359
- __typename
1360
- ... on Error {
1361
- message
1362
- }
1363
- ... on Environment {
1364
- serviceTokens {
1365
- id
1366
- createdAt
1367
- displayName
1368
- }
1369
- }
1370
- }
1371
- }
1372
- `
1373
- ),
1374
- variables: {
1375
- input: {
1376
- id: environmentId
1377
- }
1378
- }
1379
- }
1380
- });
1381
- const resources = this.legacy ? environment.serviceTokens.map((serviceToken) => ({ ...serviceToken, __typename: "APIKey" })) : environment.serviceTokens;
1382
- return messages.resourceList(resources);
1383
- }
1384
- };
1385
-
1386
- // src/platform/workspace/_.ts
1387
- var __exports6 = {};
1388
- __export(__exports6, {
1389
- $: () => $6,
1390
- Show: () => Show5,
1391
- getDefaultWorkspaceOrThrow: () => getDefaultWorkspaceOrThrow,
1392
- getUserWorkspacesOrThrow: () => getUserWorkspacesOrThrow
1393
- });
1394
-
1395
- // src/platform/workspace/$.ts
1396
- var $6 = createNamespace();
1397
-
1398
- // src/platform/workspace/show.ts
1399
- var Show5 = class _Show {
1400
- static new() {
1401
- return new _Show();
1402
- }
1403
- async parse(argv, _config) {
1404
- const args = argOrThrow(argv, {
1405
- ...platformParameters.global
1406
- });
1407
- const token = await getTokenOrThrow(args);
1408
- const userWorkspaces = await getUserWorkspacesOrThrow({ token });
1409
- return messages.resourceList(userWorkspaces);
1410
- }
1411
- };
1412
- var getUserWorkspacesOrThrow = async (input) => {
1413
- const { token } = input;
1414
- const { me } = await requestOrThrow({
1415
- token,
1416
- body: {
1417
- query: (
1418
- /* GraphQL */
1419
- `
1420
- query {
1421
- me {
1422
- __typename
1423
- workspaces {
1424
- id
1425
- displayName
1426
- createdAt
1427
- isDefault
1428
- }
1429
- }
1430
- }
1431
- `
1432
- )
1433
- }
1434
- });
1435
- return me.workspaces;
1436
- };
1437
- var getDefaultWorkspaceOrThrow = async (input) => {
1438
- const { token } = input;
1439
- const { me } = await requestOrThrow({
1440
- token,
1441
- body: {
1442
- query: (
1443
- /* GraphQL */
1444
- `
1445
- query {
1446
- me {
1447
- __typename
1448
- workspaces {
1449
- id
1450
- displayName
1451
- createdAt
1452
- isDefault
1453
- }
1454
- }
1455
- }
1456
- `
1457
- )
1458
- }
1459
- });
1460
- const defaultWorkspace = me.workspaces.find((_) => _.isDefault);
1461
- if (!defaultWorkspace) {
1462
- throw new Error("No default workspace found");
1463
- }
1464
- return defaultWorkspace;
1465
- };
1466
-
1467
- export {
1468
- credentialsFile,
1469
- platformParameters,
1470
- ErrorPlatformUnauthorized,
1471
- getTokenOrThrow,
1472
- generateConnectionString,
1473
- poll,
1474
- printPpgInitOutput,
1475
- successMessage,
1476
- requestOrThrow,
1477
- __exports,
1478
- Login,
1479
- loginOrSignup,
1480
- Logout,
1481
- __exports2,
1482
- __exports3,
1483
- __exports4,
1484
- __exports5,
1485
- __exports6
1486
- };