@prisma/cli-init 0.0.1 → 0.0.3

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