@astrojs/db 0.0.0-db-export-bug-20240307130354

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +59 -0
  2. package/README.md +38 -0
  3. package/dist/core/cli/commands/execute/index.d.ts +8 -0
  4. package/dist/core/cli/commands/execute/index.js +32 -0
  5. package/dist/core/cli/commands/link/index.d.ts +20 -0
  6. package/dist/core/cli/commands/link/index.js +238 -0
  7. package/dist/core/cli/commands/login/index.d.ts +8 -0
  8. package/dist/core/cli/commands/login/index.js +55 -0
  9. package/dist/core/cli/commands/logout/index.d.ts +1 -0
  10. package/dist/core/cli/commands/logout/index.js +9 -0
  11. package/dist/core/cli/commands/push/index.d.ts +8 -0
  12. package/dist/core/cli/commands/push/index.js +77 -0
  13. package/dist/core/cli/commands/shell/index.d.ts +8 -0
  14. package/dist/core/cli/commands/shell/index.js +17 -0
  15. package/dist/core/cli/commands/verify/index.d.ts +8 -0
  16. package/dist/core/cli/commands/verify/index.js +46 -0
  17. package/dist/core/cli/index.d.ts +6 -0
  18. package/dist/core/cli/index.js +77 -0
  19. package/dist/core/cli/migration-queries.d.ts +22 -0
  20. package/dist/core/cli/migration-queries.js +366 -0
  21. package/dist/core/consts.d.ts +7 -0
  22. package/dist/core/consts.js +19 -0
  23. package/dist/core/errors.d.ts +11 -0
  24. package/dist/core/errors.js +65 -0
  25. package/dist/core/integration/error-map.d.ts +6 -0
  26. package/dist/core/integration/error-map.js +79 -0
  27. package/dist/core/integration/file-url.d.ts +2 -0
  28. package/dist/core/integration/file-url.js +81 -0
  29. package/dist/core/integration/index.d.ts +2 -0
  30. package/dist/core/integration/index.js +112 -0
  31. package/dist/core/integration/typegen.d.ts +5 -0
  32. package/dist/core/integration/typegen.js +31 -0
  33. package/dist/core/integration/vite-plugin-db.d.ts +29 -0
  34. package/dist/core/integration/vite-plugin-db.js +111 -0
  35. package/dist/core/integration/vite-plugin-inject-env-ts.d.ts +11 -0
  36. package/dist/core/integration/vite-plugin-inject-env-ts.js +53 -0
  37. package/dist/core/load-file.d.ts +31 -0
  38. package/dist/core/load-file.js +98 -0
  39. package/dist/core/tokens.d.ts +11 -0
  40. package/dist/core/tokens.js +131 -0
  41. package/dist/core/types.d.ts +3901 -0
  42. package/dist/core/types.js +143 -0
  43. package/dist/core/utils.d.ts +6 -0
  44. package/dist/core/utils.js +22 -0
  45. package/dist/index.d.ts +3 -0
  46. package/dist/index.js +6 -0
  47. package/dist/runtime/config.d.ts +148 -0
  48. package/dist/runtime/config.js +87 -0
  49. package/dist/runtime/db-client.d.ts +5 -0
  50. package/dist/runtime/db-client.js +64 -0
  51. package/dist/runtime/drizzle.d.ts +1 -0
  52. package/dist/runtime/drizzle.js +48 -0
  53. package/dist/runtime/index.d.ts +31 -0
  54. package/dist/runtime/index.js +126 -0
  55. package/dist/runtime/queries.d.ts +81 -0
  56. package/dist/runtime/queries.js +206 -0
  57. package/dist/runtime/types.d.ts +69 -0
  58. package/dist/runtime/types.js +8 -0
  59. package/dist/utils.d.ts +1 -0
  60. package/dist/utils.js +4 -0
  61. package/index.d.ts +3 -0
  62. package/package.json +90 -0
  63. package/virtual.d.ts +9 -0
package/LICENSE ADDED
@@ -0,0 +1,59 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Fred K. Schott
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ """
24
+ This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/sveltejs/kit repository:
25
+
26
+ Copyright (c) 2020 [these people](https://github.com/sveltejs/kit/graphs/contributors)
27
+
28
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
29
+
30
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
31
+
32
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33
+ """
34
+
35
+ """
36
+ This license applies to parts of the `packages/create-astro` and `packages/astro` subdirectories originating from the https://github.com/vitejs/vite repository:
37
+
38
+ MIT License
39
+
40
+ Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors
41
+
42
+ Permission is hereby granted, free of charge, to any person obtaining a copy
43
+ of this software and associated documentation files (the "Software"), to deal
44
+ in the Software without restriction, including without limitation the rights
45
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
46
+ copies of the Software, and to permit persons to whom the Software is
47
+ furnished to do so, subject to the following conditions:
48
+
49
+ The above copyright notice and this permission notice shall be included in all
50
+ copies or substantial portions of the Software.
51
+
52
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
53
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
54
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
55
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
56
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
57
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
58
+ SOFTWARE.
59
+ """
package/README.md ADDED
@@ -0,0 +1,38 @@
1
+ # @astrojs/db (experimental) 💿
2
+
3
+ This **[Astro integration][astro-integration]** enables the usage of [SQLite](https://www.sqlite.org/) in Astro Projects.
4
+
5
+ ## Documentation
6
+
7
+ Read the [`@astrojs/db` docs][docs]
8
+
9
+ ## Support
10
+
11
+ - Get help in the [Astro Discord][discord]. Post questions in our `#support` forum, or visit our dedicated `#dev` channel to discuss current development and more!
12
+
13
+ - Check our [Astro Integration Documentation][astro-integration] for more on integrations.
14
+
15
+ - Submit bug reports and feature requests as [GitHub issues][issues].
16
+
17
+ ## Contributing
18
+
19
+ This package is maintained by Astro's Core team. You're welcome to submit an issue or PR! These links will help you get started:
20
+
21
+ - [Contributor Manual][contributing]
22
+ - [Code of Conduct][coc]
23
+ - [Community Guide][community]
24
+
25
+ ## License
26
+
27
+ MIT
28
+
29
+ Copyright (c) 2023–present [Astro][astro]
30
+
31
+ [astro]: https://astro.build/
32
+ [docs]: https://docs.astro.build/en/guides/integrations-guide/db/
33
+ [contributing]: https://github.com/withastro/astro/blob/main/CONTRIBUTING.md
34
+ [coc]: https://github.com/withastro/.github/blob/main/CODE_OF_CONDUCT.md
35
+ [community]: https://github.com/withastro/.github/blob/main/COMMUNITY_GUIDE.md
36
+ [discord]: https://astro.build/chat/
37
+ [issues]: https://github.com/withastro/astro/issues
38
+ [astro-integration]: https://docs.astro.build/en/guides/integrations-guide/
@@ -0,0 +1,8 @@
1
+ import type { AstroConfig } from 'astro';
2
+ import type { Arguments } from 'yargs-parser';
3
+ import { type DBConfig } from '../../../types.js';
4
+ export declare function cmd({ astroConfig, dbConfig, flags, }: {
5
+ astroConfig: AstroConfig;
6
+ dbConfig: DBConfig;
7
+ flags: Arguments;
8
+ }): Promise<void>;
@@ -0,0 +1,32 @@
1
+ import { existsSync } from "node:fs";
2
+ import { FILE_NOT_FOUND_ERROR, MISSING_EXECUTE_PATH_ERROR } from "../../../errors.js";
3
+ import { getStudioVirtualModContents } from "../../../integration/vite-plugin-db.js";
4
+ import { bundleFile, importBundledFile } from "../../../load-file.js";
5
+ import { getManagedAppTokenOrExit } from "../../../tokens.js";
6
+ import {} from "../../../types.js";
7
+ async function cmd({
8
+ astroConfig,
9
+ dbConfig,
10
+ flags
11
+ }) {
12
+ const filePath = flags._[4];
13
+ if (typeof filePath !== "string") {
14
+ console.error(MISSING_EXECUTE_PATH_ERROR);
15
+ process.exit(1);
16
+ }
17
+ const fileUrl = new URL(filePath, astroConfig.root);
18
+ if (!existsSync(fileUrl)) {
19
+ console.error(FILE_NOT_FOUND_ERROR(filePath));
20
+ process.exit(1);
21
+ }
22
+ const appToken = await getManagedAppTokenOrExit(flags.token);
23
+ const virtualModContents = getStudioVirtualModContents({
24
+ tables: dbConfig.tables ?? {},
25
+ appToken: appToken.token
26
+ });
27
+ const { code } = await bundleFile({ virtualModContents, root: astroConfig.root, fileUrl });
28
+ await importBundledFile({ code, root: astroConfig.root });
29
+ }
30
+ export {
31
+ cmd
32
+ };
@@ -0,0 +1,20 @@
1
+ export declare function cmd(): Promise<void>;
2
+ export declare function createNewProject({ workspaceId, name, region, }: {
3
+ workspaceId: string;
4
+ name: string;
5
+ region: string;
6
+ }): Promise<{
7
+ id: string;
8
+ idName: string;
9
+ }>;
10
+ export declare function promptExistingProjectName({ workspaceId }: {
11
+ workspaceId: string;
12
+ }): Promise<{
13
+ id: string;
14
+ idName: string;
15
+ }>;
16
+ export declare function promptBegin(): Promise<void>;
17
+ export declare function promptLinkExisting(): Promise<boolean>;
18
+ export declare function promptLinkNew(): Promise<boolean>;
19
+ export declare function promptNewProjectName(): Promise<string>;
20
+ export declare function promptNewProjectRegion(): Promise<string>;
@@ -0,0 +1,238 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { basename } from "node:path";
4
+ import { slug } from "github-slugger";
5
+ import { bgRed, cyan } from "kleur/colors";
6
+ import ora from "ora";
7
+ import prompts from "prompts";
8
+ import { MISSING_SESSION_ID_ERROR } from "../../../errors.js";
9
+ import { PROJECT_ID_FILE, getSessionIdFromFile } from "../../../tokens.js";
10
+ import { getAstroStudioUrl } from "../../../utils.js";
11
+ async function cmd() {
12
+ const sessionToken = await getSessionIdFromFile();
13
+ if (!sessionToken) {
14
+ console.error(MISSING_SESSION_ID_ERROR);
15
+ process.exit(1);
16
+ }
17
+ const getWorkspaceIdAsync = getWorkspaceId();
18
+ await promptBegin();
19
+ const isLinkExisting = await promptLinkExisting();
20
+ if (isLinkExisting) {
21
+ const workspaceId = await getWorkspaceIdAsync;
22
+ const existingProjectData = await promptExistingProjectName({ workspaceId });
23
+ return await linkProject(existingProjectData.id);
24
+ }
25
+ const isLinkNew = await promptLinkNew();
26
+ if (isLinkNew) {
27
+ const workspaceId = await getWorkspaceIdAsync;
28
+ const newProjectName = await promptNewProjectName();
29
+ const newProjectRegion = await promptNewProjectRegion();
30
+ const spinner = ora("Creating new project...").start();
31
+ const newProjectData = await createNewProject({
32
+ workspaceId,
33
+ name: newProjectName,
34
+ region: newProjectRegion
35
+ });
36
+ await new Promise((r) => setTimeout(r, 4e3));
37
+ spinner.succeed("Project created!");
38
+ return await linkProject(newProjectData.id);
39
+ }
40
+ }
41
+ async function linkProject(id) {
42
+ await mkdir(new URL(".", PROJECT_ID_FILE), { recursive: true });
43
+ await writeFile(PROJECT_ID_FILE, `${id}`);
44
+ console.info("Project linked.");
45
+ }
46
+ async function getWorkspaceId() {
47
+ const linkUrl = new URL(getAstroStudioUrl() + "/api/cli/workspaces.list");
48
+ const response = await fetch(linkUrl, {
49
+ method: "POST",
50
+ headers: {
51
+ Authorization: `Bearer ${await getSessionIdFromFile()}`,
52
+ "Content-Type": "application/json"
53
+ }
54
+ });
55
+ if (!response.ok) {
56
+ if (response.status === 401) {
57
+ console.error(
58
+ `${bgRed("Unauthorized")}
59
+
60
+ Are you logged in?
61
+ Run ${cyan(
62
+ "astro db login"
63
+ )} to authenticate and then try linking again.
64
+
65
+ `
66
+ );
67
+ process.exit(1);
68
+ }
69
+ console.error(`Failed to fetch user workspace: ${response.status} ${response.statusText}`);
70
+ process.exit(1);
71
+ }
72
+ const { data, success } = await response.json();
73
+ if (!success) {
74
+ console.error(`Failed to fetch user's workspace.`);
75
+ process.exit(1);
76
+ }
77
+ return data[0].id;
78
+ }
79
+ async function createNewProject({
80
+ workspaceId,
81
+ name,
82
+ region
83
+ }) {
84
+ const linkUrl = new URL(getAstroStudioUrl() + "/api/cli/projects.create");
85
+ const response = await fetch(linkUrl, {
86
+ method: "POST",
87
+ headers: {
88
+ Authorization: `Bearer ${await getSessionIdFromFile()}`,
89
+ "Content-Type": "application/json"
90
+ },
91
+ body: JSON.stringify({ workspaceId, name, region })
92
+ });
93
+ if (!response.ok) {
94
+ if (response.status === 401) {
95
+ console.error(
96
+ `${bgRed("Unauthorized")}
97
+
98
+ Are you logged in?
99
+ Run ${cyan(
100
+ "astro db login"
101
+ )} to authenticate and then try linking again.
102
+
103
+ `
104
+ );
105
+ process.exit(1);
106
+ }
107
+ console.error(`Failed to create project: ${response.status} ${response.statusText}`);
108
+ process.exit(1);
109
+ }
110
+ const { data, success } = await response.json();
111
+ if (!success) {
112
+ console.error(`Failed to create project.`);
113
+ process.exit(1);
114
+ }
115
+ return { id: data.id, idName: data.idName };
116
+ }
117
+ async function promptExistingProjectName({ workspaceId }) {
118
+ const linkUrl = new URL(getAstroStudioUrl() + "/api/cli/projects.list");
119
+ const response = await fetch(linkUrl, {
120
+ method: "POST",
121
+ headers: {
122
+ Authorization: `Bearer ${await getSessionIdFromFile()}`,
123
+ "Content-Type": "application/json"
124
+ },
125
+ body: JSON.stringify({ workspaceId })
126
+ });
127
+ if (!response.ok) {
128
+ if (response.status === 401) {
129
+ console.error(
130
+ `${bgRed("Unauthorized")}
131
+
132
+ Are you logged in?
133
+ Run ${cyan(
134
+ "astro db login"
135
+ )} to authenticate and then try linking again.
136
+
137
+ `
138
+ );
139
+ process.exit(1);
140
+ }
141
+ console.error(`Failed to fetch projects: ${response.status} ${response.statusText}`);
142
+ process.exit(1);
143
+ }
144
+ const { data, success } = await response.json();
145
+ if (!success) {
146
+ console.error(`Failed to fetch projects.`);
147
+ process.exit(1);
148
+ }
149
+ const { projectId } = await prompts({
150
+ type: "autocomplete",
151
+ name: "projectId",
152
+ message: "What is your project name?",
153
+ limit: 5,
154
+ choices: data.map((p) => ({ title: p.name, value: p.id }))
155
+ });
156
+ if (typeof projectId !== "string") {
157
+ console.log("Canceled.");
158
+ process.exit(0);
159
+ }
160
+ const selectedProjectData = data.find((p) => p.id === projectId);
161
+ return selectedProjectData;
162
+ }
163
+ async function promptBegin() {
164
+ const prettyCwd = process.cwd().replace(homedir(), "~");
165
+ const { begin } = await prompts({
166
+ type: "confirm",
167
+ name: "begin",
168
+ message: `Link "${prettyCwd}" with Astro Studio?`,
169
+ initial: true
170
+ });
171
+ if (!begin) {
172
+ console.log("Canceled.");
173
+ process.exit(0);
174
+ }
175
+ }
176
+ async function promptLinkExisting() {
177
+ const { linkExisting } = await prompts({
178
+ type: "confirm",
179
+ name: "linkExisting",
180
+ message: `Link with an existing project in Astro Studio?`,
181
+ initial: true
182
+ });
183
+ return !!linkExisting;
184
+ }
185
+ async function promptLinkNew() {
186
+ const { linkNew } = await prompts({
187
+ type: "confirm",
188
+ name: "linkNew",
189
+ message: `Create a new project in Astro Studio?`,
190
+ initial: true
191
+ });
192
+ if (!linkNew) {
193
+ console.log("Canceled.");
194
+ process.exit(0);
195
+ }
196
+ return true;
197
+ }
198
+ async function promptNewProjectName() {
199
+ const { newProjectName } = await prompts({
200
+ type: "text",
201
+ name: "newProjectName",
202
+ message: `What is your new project's name?`,
203
+ initial: basename(process.cwd()),
204
+ format: (val) => slug(val)
205
+ });
206
+ if (!newProjectName) {
207
+ console.log("Canceled.");
208
+ process.exit(0);
209
+ }
210
+ return newProjectName;
211
+ }
212
+ async function promptNewProjectRegion() {
213
+ const { newProjectRegion } = await prompts({
214
+ type: "select",
215
+ name: "newProjectRegion",
216
+ message: `Where should your new database live?`,
217
+ choices: [
218
+ { title: "North America (East)", value: "NorthAmericaEast" },
219
+ { title: "North America (West)", value: "NorthAmericaWest" }
220
+ ],
221
+ initial: 0
222
+ });
223
+ if (!newProjectRegion) {
224
+ console.log("Canceled.");
225
+ process.exit(0);
226
+ }
227
+ return newProjectRegion;
228
+ }
229
+ export {
230
+ cmd,
231
+ createNewProject,
232
+ promptBegin,
233
+ promptExistingProjectName,
234
+ promptLinkExisting,
235
+ promptLinkNew,
236
+ promptNewProjectName,
237
+ promptNewProjectRegion
238
+ };
@@ -0,0 +1,8 @@
1
+ import type { AstroConfig } from 'astro';
2
+ import type { Arguments } from 'yargs-parser';
3
+ import type { DBConfig } from '../../../types.js';
4
+ export declare function cmd({ flags, }: {
5
+ astroConfig: AstroConfig;
6
+ dbConfig: DBConfig;
7
+ flags: Arguments;
8
+ }): Promise<void>;
@@ -0,0 +1,55 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import { createServer as _createServer } from "node:http";
3
+ import { listen } from "async-listen";
4
+ import { cyan } from "kleur/colors";
5
+ import open from "open";
6
+ import ora from "ora";
7
+ import { SESSION_LOGIN_FILE } from "../../../tokens.js";
8
+ import { getAstroStudioUrl } from "../../../utils.js";
9
+ async function createServer() {
10
+ let resolve, reject;
11
+ const server = _createServer((req, res) => {
12
+ const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
13
+ const sessionParam = url.searchParams.get("session");
14
+ res.statusCode = 302;
15
+ if (!sessionParam) {
16
+ res.setHeader("location", getAstroStudioUrl() + "/auth/cli/error");
17
+ reject(new Error("Failed to log in"));
18
+ } else {
19
+ res.setHeader("location", getAstroStudioUrl() + "/auth/cli/success");
20
+ resolve(sessionParam);
21
+ }
22
+ res.end();
23
+ });
24
+ const { port } = await listen(server, 0, "127.0.0.1");
25
+ const serverUrl = `http://localhost:${port}`;
26
+ const sessionPromise = new Promise((_resolve, _reject) => {
27
+ resolve = _resolve;
28
+ reject = _reject;
29
+ }).finally(() => {
30
+ server.closeAllConnections();
31
+ server.close();
32
+ });
33
+ return { url: serverUrl, promise: sessionPromise };
34
+ }
35
+ async function cmd({
36
+ flags
37
+ }) {
38
+ let session = flags.session;
39
+ if (!session) {
40
+ const { url, promise } = await createServer();
41
+ const loginUrl = getAstroStudioUrl() + "/auth/cli/login?returnTo=" + encodeURIComponent(url);
42
+ console.log(`Opening the following URL in your browser...`);
43
+ console.log(cyan(loginUrl));
44
+ console.log(`If something goes wrong, copy-and-paste the URL into your browser.`);
45
+ open(loginUrl);
46
+ const spinner = ora("Waiting for confirmation...");
47
+ session = await promise;
48
+ spinner.succeed("Successfully logged in!");
49
+ }
50
+ await mkdir(new URL(".", SESSION_LOGIN_FILE), { recursive: true });
51
+ await writeFile(SESSION_LOGIN_FILE, `${session}`);
52
+ }
53
+ export {
54
+ cmd
55
+ };
@@ -0,0 +1 @@
1
+ export declare function cmd(): Promise<void>;
@@ -0,0 +1,9 @@
1
+ import { unlink } from "node:fs/promises";
2
+ import { SESSION_LOGIN_FILE } from "../../../tokens.js";
3
+ async function cmd() {
4
+ await unlink(SESSION_LOGIN_FILE);
5
+ console.log("Successfully logged out of Astro Studio.");
6
+ }
7
+ export {
8
+ cmd
9
+ };
@@ -0,0 +1,8 @@
1
+ import type { AstroConfig } from 'astro';
2
+ import type { Arguments } from 'yargs-parser';
3
+ import { type DBConfig } from '../../../types.js';
4
+ export declare function cmd({ dbConfig, flags, }: {
5
+ astroConfig: AstroConfig;
6
+ dbConfig: DBConfig;
7
+ flags: Arguments;
8
+ }): Promise<void>;
@@ -0,0 +1,77 @@
1
+ import { red } from "kleur/colors";
2
+ import { getManagedAppTokenOrExit } from "../../../tokens.js";
3
+ import {} from "../../../types.js";
4
+ import { getRemoteDatabaseUrl } from "../../../utils.js";
5
+ import {
6
+ createCurrentSnapshot,
7
+ createEmptySnapshot,
8
+ formatDataLossMessage,
9
+ getMigrationQueries,
10
+ getProductionCurrentSnapshot
11
+ } from "../../migration-queries.js";
12
+ async function cmd({
13
+ dbConfig,
14
+ flags
15
+ }) {
16
+ const isDryRun = flags.dryRun;
17
+ const isForceReset = flags.forceReset;
18
+ const appToken = await getManagedAppTokenOrExit(flags.token);
19
+ const productionSnapshot = await getProductionCurrentSnapshot({ appToken: appToken.token });
20
+ const currentSnapshot = createCurrentSnapshot(dbConfig);
21
+ const isFromScratch = isForceReset || JSON.stringify(productionSnapshot) === "{}";
22
+ const { queries: migrationQueries, confirmations } = await getMigrationQueries({
23
+ oldSnapshot: isFromScratch ? createEmptySnapshot() : productionSnapshot,
24
+ newSnapshot: currentSnapshot
25
+ });
26
+ if (migrationQueries.length === 0) {
27
+ console.log("Database schema is up to date.");
28
+ } else {
29
+ console.log(`Database schema is out of date.`);
30
+ }
31
+ if (isForceReset) {
32
+ console.log(`Force-pushing to the database. All existing data will be erased.`);
33
+ } else if (confirmations.length > 0) {
34
+ console.log("\n" + formatDataLossMessage(confirmations) + "\n");
35
+ throw new Error("Exiting.");
36
+ }
37
+ if (isDryRun) {
38
+ console.log("Statements:", JSON.stringify(migrationQueries, void 0, 2));
39
+ } else {
40
+ console.log(`Pushing database schema updates...`);
41
+ await pushSchema({
42
+ statements: migrationQueries,
43
+ appToken: appToken.token,
44
+ isDryRun,
45
+ currentSnapshot
46
+ });
47
+ }
48
+ await appToken.destroy();
49
+ console.info("Push complete!");
50
+ }
51
+ async function pushSchema({
52
+ statements,
53
+ appToken,
54
+ isDryRun,
55
+ currentSnapshot
56
+ }) {
57
+ const requestBody = {
58
+ snapshot: currentSnapshot,
59
+ sql: statements,
60
+ experimentalVersion: 1
61
+ };
62
+ if (isDryRun) {
63
+ console.info("[DRY RUN] Batch query:", JSON.stringify(requestBody, null, 2));
64
+ return new Response(null, { status: 200 });
65
+ }
66
+ const url = new URL("/db/push", getRemoteDatabaseUrl());
67
+ return await fetch(url, {
68
+ method: "POST",
69
+ headers: new Headers({
70
+ Authorization: `Bearer ${appToken}`
71
+ }),
72
+ body: JSON.stringify(requestBody)
73
+ });
74
+ }
75
+ export {
76
+ cmd
77
+ };
@@ -0,0 +1,8 @@
1
+ import type { AstroConfig } from 'astro';
2
+ import type { Arguments } from 'yargs-parser';
3
+ import type { DBConfigInput } from '../../../types.js';
4
+ export declare function cmd({ flags, }: {
5
+ dbConfig: DBConfigInput;
6
+ astroConfig: AstroConfig;
7
+ flags: Arguments;
8
+ }): Promise<void>;
@@ -0,0 +1,17 @@
1
+ import { sql } from "drizzle-orm";
2
+ import { createRemoteDatabaseClient } from "../../../../runtime/db-client.js";
3
+ import { getManagedAppTokenOrExit } from "../../../tokens.js";
4
+ import { getRemoteDatabaseUrl } from "../../../utils.js";
5
+ async function cmd({
6
+ flags
7
+ }) {
8
+ const query = flags.query;
9
+ const appToken = await getManagedAppTokenOrExit(flags.token);
10
+ const db = createRemoteDatabaseClient(appToken.token, getRemoteDatabaseUrl());
11
+ const result = await db.run(sql.raw(query));
12
+ await appToken.destroy();
13
+ console.log(result);
14
+ }
15
+ export {
16
+ cmd
17
+ };
@@ -0,0 +1,8 @@
1
+ import type { AstroConfig } from 'astro';
2
+ import type { Arguments } from 'yargs-parser';
3
+ import type { DBConfig } from '../../../types.js';
4
+ export declare function cmd({ dbConfig, flags, }: {
5
+ astroConfig: AstroConfig;
6
+ dbConfig: DBConfig;
7
+ flags: Arguments;
8
+ }): Promise<void>;
@@ -0,0 +1,46 @@
1
+ import { getManagedAppTokenOrExit } from "../../../tokens.js";
2
+ import {
3
+ createCurrentSnapshot,
4
+ createEmptySnapshot,
5
+ formatDataLossMessage,
6
+ getMigrationQueries,
7
+ getProductionCurrentSnapshot
8
+ } from "../../migration-queries.js";
9
+ async function cmd({
10
+ dbConfig,
11
+ flags
12
+ }) {
13
+ const isJson = flags.json;
14
+ const appToken = await getManagedAppTokenOrExit(flags.token);
15
+ const productionSnapshot = await getProductionCurrentSnapshot({ appToken: appToken.token });
16
+ const currentSnapshot = createCurrentSnapshot(dbConfig);
17
+ const { queries: migrationQueries, confirmations } = await getMigrationQueries({
18
+ oldSnapshot: JSON.stringify(productionSnapshot) !== "{}" ? productionSnapshot : createEmptySnapshot(),
19
+ newSnapshot: currentSnapshot
20
+ });
21
+ const result = { exitCode: 0, message: "", code: "", data: void 0 };
22
+ if (migrationQueries.length === 0) {
23
+ result.code = "MATCH";
24
+ result.message = `Database schema is up to date.`;
25
+ } else {
26
+ result.code = "NO_MATCH";
27
+ result.message = `Database schema is out of date.
28
+ Run 'astro db push' to push up your latest changes.`;
29
+ }
30
+ if (confirmations.length > 0) {
31
+ result.code = "DATA_LOSS";
32
+ result.exitCode = 1;
33
+ result.data = confirmations;
34
+ result.message = formatDataLossMessage(confirmations, !isJson);
35
+ }
36
+ if (isJson) {
37
+ console.log(JSON.stringify(result));
38
+ } else {
39
+ console.log(result.message);
40
+ }
41
+ await appToken.destroy();
42
+ process.exit(result.exitCode);
43
+ }
44
+ export {
45
+ cmd
46
+ };
@@ -0,0 +1,6 @@
1
+ import type { AstroConfig } from 'astro';
2
+ import type { Arguments } from 'yargs-parser';
3
+ export declare function cli({ flags, config: astroConfig, }: {
4
+ flags: Arguments;
5
+ config: AstroConfig;
6
+ }): Promise<void>;