@astrojs/db 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/LICENSE +59 -0
  2. package/components/Renderer.astro +14 -0
  3. package/components/astro-env.d.ts +1 -0
  4. package/components/index.ts +2 -0
  5. package/components/tsconfig.json +7 -0
  6. package/config-augment.d.ts +4 -0
  7. package/dist/cli/commands/push/index.d.ts +6 -0
  8. package/dist/cli/commands/push/index.js +144 -0
  9. package/dist/cli/commands/sync/index.d.ts +6 -0
  10. package/dist/cli/commands/sync/index.js +45 -0
  11. package/dist/cli/commands/verify/index.d.ts +6 -0
  12. package/dist/cli/commands/verify/index.js +25 -0
  13. package/dist/cli/index.d.ts +6 -0
  14. package/dist/cli/index.js +24 -0
  15. package/dist/cli/queries.d.ts +19 -0
  16. package/dist/cli/queries.js +453 -0
  17. package/dist/cli/seed.d.ts +6 -0
  18. package/dist/cli/sync/admin.d.ts +33 -0
  19. package/dist/cli/sync/index.d.ts +1 -0
  20. package/dist/cli/sync/index.js +0 -0
  21. package/dist/cli/sync/migrate.d.ts +1 -0
  22. package/dist/cli/sync/migrate.js +0 -0
  23. package/dist/cli/sync/queries.d.ts +19 -0
  24. package/dist/cli/sync/remote-db.d.ts +1 -0
  25. package/dist/config.d.ts +1149 -0
  26. package/dist/config.js +53 -0
  27. package/dist/consts.d.ts +6 -0
  28. package/dist/consts.js +19 -0
  29. package/dist/error-map.d.ts +6 -0
  30. package/dist/error-map.js +79 -0
  31. package/dist/errors.d.ts +3 -0
  32. package/dist/errors.js +15 -0
  33. package/dist/index.d.ts +3 -0
  34. package/dist/index.js +10 -0
  35. package/dist/integration.d.ts +2 -0
  36. package/dist/integration.js +68 -0
  37. package/dist/internal-drizzle.d.ts +1 -0
  38. package/dist/internal-drizzle.js +48 -0
  39. package/dist/internal.d.ts +50 -0
  40. package/dist/internal.js +250 -0
  41. package/dist/load-astro-config.d.ts +6 -0
  42. package/dist/load-astro-config.js +79 -0
  43. package/dist/migrations.d.ts +9 -0
  44. package/dist/migrations.js +41 -0
  45. package/dist/typegen.d.ts +5 -0
  46. package/dist/typegen.js +57 -0
  47. package/dist/types.d.ts +1367 -0
  48. package/dist/types.js +58 -0
  49. package/dist/utils.d.ts +59 -0
  50. package/dist/utils.js +84 -0
  51. package/dist/vite-plugin-db.d.ts +19 -0
  52. package/dist/vite-plugin-db.js +66 -0
  53. package/dist/vite-plugin-inject-env-ts.d.ts +9 -0
  54. package/dist/vite-plugin-inject-env-ts.js +49 -0
  55. package/index.d.ts +3 -0
  56. package/package.json +72 -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
+ """
@@ -0,0 +1,14 @@
1
+ ---
2
+ import { Renderer as MarkdocRenderer } from '@astrojs/markdoc/components';
3
+ import { Markdoc } from '@astrojs/markdoc/config';
4
+
5
+ interface Props {
6
+ content: string;
7
+ }
8
+
9
+ const { content } = Astro.props;
10
+
11
+ const ast = Markdoc.parse(content);
12
+ ---
13
+
14
+ <MarkdocRenderer stringifiedAst={JSON.stringify(ast)} config={{}} />
@@ -0,0 +1 @@
1
+ /// <reference types="astro/client" />
@@ -0,0 +1,2 @@
1
+ // @ts-expect-error: missing types
2
+ export { default as Renderer } from './Renderer.astro';
@@ -0,0 +1,7 @@
1
+ {
2
+ "extends": "astro/tsconfigs/strict",
3
+ "include": ["."],
4
+ "compilerOptions": {
5
+ "strictNullChecks": true
6
+ }
7
+ }
@@ -0,0 +1,4 @@
1
+ declare namespace Config {
2
+ type DBUserConfig = import('./dist/config.js').DBUserConfig;
3
+ export interface Database extends DBUserConfig {}
4
+ }
@@ -0,0 +1,6 @@
1
+ import type { AstroConfig } from 'astro';
2
+ import type { Arguments } from 'yargs-parser';
3
+ export declare function cmd({ config, flags }: {
4
+ config: AstroConfig;
5
+ flags: Arguments;
6
+ }): Promise<void>;
@@ -0,0 +1,144 @@
1
+ import deepDiff from "deep-diff";
2
+ import { eq, sql } from "drizzle-orm";
3
+ import { SQLiteAsyncDialect } from "drizzle-orm/sqlite-core";
4
+ import { appTokenError } from "../../../errors.js";
5
+ import { collectionToTable, createLocalDatabaseClient } from "../../../internal.js";
6
+ import { getMigrations, initializeFromMigrations, loadInitialSnapshot, loadMigration } from "../../../migrations.js";
7
+ import {
8
+ STUDIO_ADMIN_TABLE_ROW_ID,
9
+ adminTable,
10
+ createRemoteDatabaseClient,
11
+ getAstroStudioEnv,
12
+ getRemoteDatabaseUrl,
13
+ migrationsTable
14
+ } from "../../../utils.js";
15
+ import { getMigrationQueries } from "../../queries.js";
16
+ const { diff } = deepDiff;
17
+ const sqliteDialect = new SQLiteAsyncDialect();
18
+ async function cmd({ config, flags }) {
19
+ const isSeedData = flags.seed;
20
+ const isDryRun = flags.dryRun;
21
+ const currentDb = config.db?.collections ?? {};
22
+ const currentSnapshot = JSON.parse(JSON.stringify(currentDb));
23
+ const allMigrationFiles = await getMigrations();
24
+ if (allMigrationFiles.length === 0) {
25
+ console.log("Project not yet initialized!");
26
+ process.exit(1);
27
+ }
28
+ const prevSnapshot = await initializeFromMigrations(allMigrationFiles);
29
+ const calculatedDiff = diff(prevSnapshot, currentSnapshot);
30
+ if (calculatedDiff) {
31
+ console.log("Changes detected!");
32
+ process.exit(1);
33
+ }
34
+ const appToken = getAstroStudioEnv().ASTRO_STUDIO_APP_TOKEN;
35
+ if (!appToken) {
36
+ console.error(appTokenError);
37
+ process.exit(1);
38
+ }
39
+ const db = createRemoteDatabaseClient(appToken);
40
+ await db.run(
41
+ sql`CREATE TABLE IF NOT EXISTS ReservedAstroStudioMigrations ( name TEXT PRIMARY KEY )`
42
+ );
43
+ const allRemoteMigrations = await db.select().from(migrationsTable);
44
+ const allLocalMigrations = await getMigrations();
45
+ const missingMigrations = allLocalMigrations.filter((migration) => {
46
+ return !allRemoteMigrations.find((m) => m.name === migration);
47
+ });
48
+ if (missingMigrations.length === 0) {
49
+ console.info("No migrations to push! Your database is up to date!");
50
+ } else {
51
+ console.log(`Pushing ${missingMigrations.length} migrations...`);
52
+ await pushSchema({ migrations: missingMigrations, appToken, isDryRun, db, currentSnapshot });
53
+ }
54
+ if (isSeedData) {
55
+ console.info("Pushing data...");
56
+ await tempDataPush({ currentDb, appToken, isDryRun });
57
+ }
58
+ console.info("Push complete!");
59
+ }
60
+ async function pushSchema({
61
+ migrations,
62
+ appToken,
63
+ isDryRun,
64
+ db,
65
+ currentSnapshot
66
+ }) {
67
+ const initialSnapshot = migrations.find((m) => m === "0000_snapshot.json");
68
+ const filteredMigrations = migrations.filter((m) => m !== "0000_snapshot.json");
69
+ const missingMigrationContents = await Promise.all(filteredMigrations.map(loadMigration));
70
+ const initialMigrationBatch = initialSnapshot ? await getMigrationQueries({
71
+ oldCollections: {},
72
+ newCollections: await loadInitialSnapshot()
73
+ }) : [];
74
+ const missingMigrationBatch = missingMigrationContents.reduce((acc, curr) => {
75
+ return [...acc, ...curr.db];
76
+ }, initialMigrationBatch);
77
+ const queries = missingMigrationBatch.map((q) => sql.raw(q));
78
+ await runBatchQuery({ queries, appToken, isDryRun });
79
+ await db.insert(migrationsTable).values(migrations.map((m) => ({ name: m })));
80
+ await db.update(adminTable).set({ collections: JSON.stringify(currentSnapshot) }).where(eq(adminTable.id, STUDIO_ADMIN_TABLE_ROW_ID));
81
+ }
82
+ async function tempDataPush({
83
+ currentDb,
84
+ appToken,
85
+ isDryRun
86
+ }) {
87
+ const db = await createLocalDatabaseClient({
88
+ collections: JSON.parse(JSON.stringify(currentDb)),
89
+ dbUrl: ":memory:",
90
+ seeding: true
91
+ });
92
+ const queries = [];
93
+ for (const [name, collection] of Object.entries(currentDb)) {
94
+ console.log(name, collection);
95
+ if (collection.writable || !collection.data)
96
+ continue;
97
+ const table = collectionToTable(name, collection);
98
+ const insert = db.insert(table).values(await collection.data());
99
+ queries.push(insert.toSQL());
100
+ }
101
+ console.log(queries);
102
+ const url = new URL("/db/query", getRemoteDatabaseUrl());
103
+ const requestBody = queries.map((q) => ({
104
+ sql: q.sql,
105
+ args: q.params
106
+ }));
107
+ if (isDryRun) {
108
+ console.info("[DRY RUN] Batch data seed:", JSON.stringify(requestBody, null, 2));
109
+ return new Response(null, { status: 200 });
110
+ }
111
+ return await fetch(url, {
112
+ method: "POST",
113
+ headers: new Headers({
114
+ Authorization: `Bearer ${appToken}`
115
+ }),
116
+ body: JSON.stringify(requestBody)
117
+ });
118
+ }
119
+ async function runBatchQuery({
120
+ queries: sqlQueries,
121
+ appToken,
122
+ isDryRun
123
+ }) {
124
+ const queries = sqlQueries.map((q) => sqliteDialect.sqlToQuery(q));
125
+ const requestBody = queries.map((q) => ({
126
+ sql: q.sql,
127
+ args: q.params
128
+ }));
129
+ if (isDryRun) {
130
+ console.info("[DRY RUN] Batch query:", JSON.stringify(requestBody, null, 2));
131
+ return new Response(null, { status: 200 });
132
+ }
133
+ const url = new URL("/db/query", getRemoteDatabaseUrl());
134
+ return await fetch(url, {
135
+ method: "POST",
136
+ headers: new Headers({
137
+ Authorization: `Bearer ${appToken}`
138
+ }),
139
+ body: JSON.stringify(requestBody)
140
+ });
141
+ }
142
+ export {
143
+ cmd
144
+ };
@@ -0,0 +1,6 @@
1
+ import type { AstroConfig } from 'astro';
2
+ import type { Arguments } from 'yargs-parser';
3
+ export declare function cmd({ config }: {
4
+ config: AstroConfig;
5
+ flags: Arguments;
6
+ }): Promise<void>;
@@ -0,0 +1,45 @@
1
+ import deepDiff from "deep-diff";
2
+ import { writeFile } from "fs/promises";
3
+ import {
4
+ getMigrations,
5
+ initializeFromMigrations,
6
+ initializeMigrationsDirectory
7
+ } from "../../../migrations.js";
8
+ import { getMigrationQueries } from "../../queries.js";
9
+ const { diff } = deepDiff;
10
+ async function cmd({ config }) {
11
+ const currentSnapshot = JSON.parse(JSON.stringify(config.db?.collections ?? {}));
12
+ const allMigrationFiles = await getMigrations();
13
+ if (allMigrationFiles.length === 0) {
14
+ await initializeMigrationsDirectory(currentSnapshot);
15
+ console.log("Project initialized!");
16
+ return;
17
+ }
18
+ const prevSnapshot = await initializeFromMigrations(allMigrationFiles);
19
+ const calculatedDiff = diff(prevSnapshot, currentSnapshot);
20
+ if (!calculatedDiff) {
21
+ console.log("No changes detected!");
22
+ return;
23
+ }
24
+ const migrationQueries = await getMigrationQueries({
25
+ oldCollections: prevSnapshot,
26
+ newCollections: currentSnapshot
27
+ });
28
+ const largestNumber = allMigrationFiles.reduce((acc, curr) => {
29
+ const num = parseInt(curr.split("_")[0]);
30
+ return num > acc ? num : acc;
31
+ }, 0);
32
+ const migrationFileContent = {
33
+ diff: calculatedDiff,
34
+ db: migrationQueries
35
+ };
36
+ const migrationFileName = `./migrations/${String(largestNumber + 1).padStart(
37
+ 4,
38
+ "0"
39
+ )}_migration.json`;
40
+ await writeFile(migrationFileName, JSON.stringify(migrationFileContent, void 0, 2));
41
+ console.log(migrationFileName + " created!");
42
+ }
43
+ export {
44
+ cmd
45
+ };
@@ -0,0 +1,6 @@
1
+ import type { AstroConfig } from 'astro';
2
+ import type { Arguments } from 'yargs-parser';
3
+ export declare function cmd({ config }: {
4
+ config: AstroConfig;
5
+ flags: Arguments;
6
+ }): Promise<void>;
@@ -0,0 +1,25 @@
1
+ import deepDiff from "deep-diff";
2
+ import {
3
+ getMigrations,
4
+ initializeFromMigrations
5
+ } from "../../../migrations.js";
6
+ const { diff, applyChange } = deepDiff;
7
+ async function cmd({ config }) {
8
+ const currentSnapshot = JSON.parse(JSON.stringify(config.db?.collections ?? {}));
9
+ const allMigrationFiles = await getMigrations();
10
+ if (allMigrationFiles.length === 0) {
11
+ console.log("Project not yet initialized!");
12
+ process.exit(1);
13
+ }
14
+ const prevSnapshot = await initializeFromMigrations(allMigrationFiles);
15
+ const calculatedDiff = diff(prevSnapshot, currentSnapshot);
16
+ if (calculatedDiff) {
17
+ console.log("Changes detected!");
18
+ process.exit(1);
19
+ }
20
+ console.log("No changes detected.");
21
+ return;
22
+ }
23
+ export {
24
+ cmd
25
+ };
@@ -0,0 +1,6 @@
1
+ import type { AstroConfig } from 'astro';
2
+ import type { Arguments } from 'yargs-parser';
3
+ export declare function cli({ flags, config }: {
4
+ flags: Arguments;
5
+ config: AstroConfig;
6
+ }): Promise<void>;
@@ -0,0 +1,24 @@
1
+ async function cli({ flags, config }) {
2
+ const command = flags._[3];
3
+ switch (command) {
4
+ case "sync": {
5
+ const { cmd: syncCommand } = await import("./commands/sync/index.js");
6
+ return await syncCommand({ config, flags });
7
+ }
8
+ case "push": {
9
+ const { cmd: pushCommand } = await import("./commands/push/index.js");
10
+ return await pushCommand({ config, flags });
11
+ }
12
+ case "verify": {
13
+ const { cmd: verifyCommand } = await import("./commands/verify/index.js");
14
+ return await verifyCommand({ config, flags });
15
+ }
16
+ default: {
17
+ console.error(`Unknown command: ${command}`);
18
+ return;
19
+ }
20
+ }
21
+ }
22
+ export {
23
+ cli
24
+ };
@@ -0,0 +1,19 @@
1
+ import type { DBCollection, DBCollections } from '../types.js';
2
+ interface PromptResponses {
3
+ allowDataLoss: boolean;
4
+ fieldRenames: Record<string, string | false>;
5
+ collectionRenames: Record<string, string | false>;
6
+ }
7
+ export declare function getMigrationQueries({ oldCollections, newCollections, promptResponses, }: {
8
+ oldCollections: DBCollections;
9
+ newCollections: DBCollections;
10
+ promptResponses?: PromptResponses;
11
+ }): Promise<string[]>;
12
+ export declare function getCollectionChangeQueries({ collectionName, oldCollection, newCollection, promptResponses, }: {
13
+ collectionName: string;
14
+ oldCollection: DBCollection;
15
+ newCollection: DBCollection;
16
+ promptResponses?: PromptResponses;
17
+ }): Promise<string[]>;
18
+ export declare function getCreateTableQuery(collectionName: string, collection: DBCollection): string;
19
+ export {};