@astrojs/db 0.0.0-10646-20240402132948

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 (78) hide show
  1. package/LICENSE +59 -0
  2. package/README.md +38 -0
  3. package/dist/_internal/core/integration/error-map.d.ts +6 -0
  4. package/dist/_internal/core/schemas.d.ts +4034 -0
  5. package/dist/_internal/core/types.d.ts +59 -0
  6. package/dist/_internal/core/utils.d.ts +20 -0
  7. package/dist/_internal/runtime/config.d.ts +154 -0
  8. package/dist/_internal/runtime/types.d.ts +69 -0
  9. package/dist/core/cli/commands/execute/index.d.ts +8 -0
  10. package/dist/core/cli/commands/execute/index.js +66 -0
  11. package/dist/core/cli/commands/link/index.d.ts +20 -0
  12. package/dist/core/cli/commands/link/index.js +252 -0
  13. package/dist/core/cli/commands/login/index.d.ts +8 -0
  14. package/dist/core/cli/commands/login/index.js +55 -0
  15. package/dist/core/cli/commands/logout/index.d.ts +1 -0
  16. package/dist/core/cli/commands/logout/index.js +9 -0
  17. package/dist/core/cli/commands/push/index.d.ts +8 -0
  18. package/dist/core/cli/commands/push/index.js +93 -0
  19. package/dist/core/cli/commands/shell/index.d.ts +8 -0
  20. package/dist/core/cli/commands/shell/index.js +33 -0
  21. package/dist/core/cli/commands/verify/index.d.ts +8 -0
  22. package/dist/core/cli/commands/verify/index.js +46 -0
  23. package/dist/core/cli/index.d.ts +6 -0
  24. package/dist/core/cli/index.js +76 -0
  25. package/dist/core/cli/migration-queries.d.ts +23 -0
  26. package/dist/core/cli/migration-queries.js +386 -0
  27. package/dist/core/cli/print-help.d.ts +11 -0
  28. package/dist/core/cli/print-help.js +55 -0
  29. package/dist/core/consts.d.ts +8 -0
  30. package/dist/core/consts.js +21 -0
  31. package/dist/core/errors.d.ts +10 -0
  32. package/dist/core/errors.js +56 -0
  33. package/dist/core/integration/error-map.d.ts +6 -0
  34. package/dist/core/integration/error-map.js +79 -0
  35. package/dist/core/integration/file-url.d.ts +2 -0
  36. package/dist/core/integration/file-url.js +81 -0
  37. package/dist/core/integration/index.d.ts +2 -0
  38. package/dist/core/integration/index.js +160 -0
  39. package/dist/core/integration/typegen.d.ts +7 -0
  40. package/dist/core/integration/typegen.js +33 -0
  41. package/dist/core/integration/vite-plugin-db.d.ts +39 -0
  42. package/dist/core/integration/vite-plugin-db.js +134 -0
  43. package/dist/core/integration/vite-plugin-inject-env-ts.d.ts +11 -0
  44. package/dist/core/integration/vite-plugin-inject-env-ts.js +53 -0
  45. package/dist/core/load-file.d.ts +253 -0
  46. package/dist/core/load-file.js +170 -0
  47. package/dist/core/schemas.d.ts +4034 -0
  48. package/dist/core/schemas.js +186 -0
  49. package/dist/core/tokens.d.ts +11 -0
  50. package/dist/core/tokens.js +181 -0
  51. package/dist/core/types.d.ts +59 -0
  52. package/dist/core/types.js +0 -0
  53. package/dist/core/utils.d.ts +20 -0
  54. package/dist/core/utils.js +32 -0
  55. package/dist/index.d.ts +4 -0
  56. package/dist/index.js +8 -0
  57. package/dist/runtime/config.js +111 -0
  58. package/dist/runtime/db-client.d.ts +6 -0
  59. package/dist/runtime/db-client.js +148 -0
  60. package/dist/runtime/drizzle.d.ts +1 -0
  61. package/dist/runtime/drizzle.js +48 -0
  62. package/dist/runtime/errors.d.ts +5 -0
  63. package/dist/runtime/errors.js +31 -0
  64. package/dist/runtime/index.d.ts +26 -0
  65. package/dist/runtime/index.js +131 -0
  66. package/dist/runtime/queries.d.ts +71 -0
  67. package/dist/runtime/queries.js +169 -0
  68. package/dist/runtime/seed-local.d.ts +10 -0
  69. package/dist/runtime/seed-local.js +55 -0
  70. package/dist/runtime/types.d.ts +69 -0
  71. package/dist/runtime/types.js +8 -0
  72. package/dist/runtime/utils.d.ts +8 -0
  73. package/dist/runtime/utils.js +17 -0
  74. package/dist/utils.d.ts +2 -0
  75. package/dist/utils.js +6 -0
  76. package/index.d.ts +3 -0
  77. package/package.json +95 -0
  78. package/virtual.d.ts +45 -0
@@ -0,0 +1,186 @@
1
+ import { SQL } from "drizzle-orm";
2
+ import { SQLiteAsyncDialect } from "drizzle-orm/sqlite-core";
3
+ import { z } from "zod";
4
+ import { SERIALIZED_SQL_KEY } from "../runtime/types.js";
5
+ import { errorMap } from "./integration/error-map.js";
6
+ import { mapObject } from "./utils.js";
7
+ const sqlite = new SQLiteAsyncDialect();
8
+ const sqlSchema = z.instanceof(SQL).transform(
9
+ (sqlObj) => ({
10
+ [SERIALIZED_SQL_KEY]: true,
11
+ sql: sqlite.sqlToQuery(sqlObj).sql
12
+ })
13
+ );
14
+ const baseColumnSchema = z.object({
15
+ label: z.string().optional(),
16
+ optional: z.boolean().optional().default(false),
17
+ unique: z.boolean().optional().default(false),
18
+ deprecated: z.boolean().optional().default(false),
19
+ // Defined when `defineDb()` is called to resolve `references`
20
+ name: z.string().optional(),
21
+ // TODO: Update to `table`. Will need migration file version change
22
+ collection: z.string().optional()
23
+ });
24
+ const booleanColumnSchema = z.object({
25
+ type: z.literal("boolean"),
26
+ schema: baseColumnSchema.extend({
27
+ default: z.union([z.boolean(), sqlSchema]).optional()
28
+ })
29
+ });
30
+ const numberColumnBaseSchema = baseColumnSchema.omit({ optional: true }).and(
31
+ z.union([
32
+ z.object({
33
+ primaryKey: z.literal(false).optional().default(false),
34
+ optional: baseColumnSchema.shape.optional,
35
+ default: z.union([z.number(), sqlSchema]).optional()
36
+ }),
37
+ z.object({
38
+ // `integer primary key` uses ROWID as the default value.
39
+ // `optional` and `default` do not have an effect,
40
+ // so disable these config options for primary keys.
41
+ primaryKey: z.literal(true),
42
+ optional: z.literal(false).optional(),
43
+ default: z.literal(void 0).optional()
44
+ })
45
+ ])
46
+ );
47
+ const numberColumnOptsSchema = numberColumnBaseSchema.and(
48
+ z.object({
49
+ references: z.function().returns(z.lazy(() => numberColumnSchema)).optional().transform((fn) => fn?.())
50
+ })
51
+ );
52
+ const numberColumnSchema = z.object({
53
+ type: z.literal("number"),
54
+ schema: numberColumnOptsSchema
55
+ });
56
+ const textColumnBaseSchema = baseColumnSchema.omit({ optional: true }).extend({
57
+ default: z.union([z.string(), sqlSchema]).optional(),
58
+ multiline: z.boolean().optional()
59
+ }).and(
60
+ z.union([
61
+ z.object({
62
+ primaryKey: z.literal(false).optional().default(false),
63
+ optional: baseColumnSchema.shape.optional
64
+ }),
65
+ z.object({
66
+ // text primary key allows NULL values.
67
+ // NULL values bypass unique checks, which could
68
+ // lead to duplicate URLs per record in Astro Studio.
69
+ // disable `optional` for primary keys.
70
+ primaryKey: z.literal(true),
71
+ optional: z.literal(false).optional()
72
+ })
73
+ ])
74
+ );
75
+ const textColumnOptsSchema = textColumnBaseSchema.and(
76
+ z.object({
77
+ references: z.function().returns(z.lazy(() => textColumnSchema)).optional().transform((fn) => fn?.())
78
+ })
79
+ );
80
+ const textColumnSchema = z.object({
81
+ type: z.literal("text"),
82
+ schema: textColumnOptsSchema
83
+ });
84
+ const dateColumnSchema = z.object({
85
+ type: z.literal("date"),
86
+ schema: baseColumnSchema.extend({
87
+ default: z.union([
88
+ sqlSchema,
89
+ // transform to ISO string for serialization
90
+ z.date().transform((d) => d.toISOString())
91
+ ]).optional()
92
+ })
93
+ });
94
+ const jsonColumnSchema = z.object({
95
+ type: z.literal("json"),
96
+ schema: baseColumnSchema.extend({
97
+ default: z.unknown().optional()
98
+ })
99
+ });
100
+ const columnSchema = z.discriminatedUnion("type", [
101
+ booleanColumnSchema,
102
+ numberColumnSchema,
103
+ textColumnSchema,
104
+ dateColumnSchema,
105
+ jsonColumnSchema
106
+ ]);
107
+ const referenceableColumnSchema = z.union([textColumnSchema, numberColumnSchema]);
108
+ const columnsSchema = z.record(columnSchema);
109
+ const foreignKeysSchema = z.object({
110
+ columns: z.string().or(z.array(z.string())),
111
+ references: z.function().returns(z.lazy(() => referenceableColumnSchema.or(z.array(referenceableColumnSchema)))).transform((fn) => fn())
112
+ });
113
+ const resolvedIndexSchema = z.object({
114
+ on: z.string().or(z.array(z.string())),
115
+ unique: z.boolean().optional()
116
+ });
117
+ const legacyIndexesSchema = z.record(resolvedIndexSchema);
118
+ const indexSchema = z.object({
119
+ on: z.string().or(z.array(z.string())),
120
+ unique: z.boolean().optional(),
121
+ name: z.string().optional()
122
+ });
123
+ const indexesSchema = z.array(indexSchema);
124
+ const tableSchema = z.object({
125
+ columns: columnsSchema,
126
+ indexes: indexesSchema.or(legacyIndexesSchema).optional(),
127
+ foreignKeys: z.array(foreignKeysSchema).optional(),
128
+ deprecated: z.boolean().optional().default(false)
129
+ });
130
+ const tablesSchema = z.preprocess((rawTables) => {
131
+ const tables = z.record(z.any()).parse(rawTables, { errorMap });
132
+ for (const [tableName, table] of Object.entries(tables)) {
133
+ table.getName = () => tableName;
134
+ const { columns } = z.object({ columns: z.record(z.any()) }).parse(table, { errorMap });
135
+ for (const [columnName, column] of Object.entries(columns)) {
136
+ column.schema.name = columnName;
137
+ column.schema.collection = tableName;
138
+ }
139
+ }
140
+ return rawTables;
141
+ }, z.record(tableSchema));
142
+ const dbConfigSchema = z.object({
143
+ tables: tablesSchema.optional()
144
+ }).transform(({ tables = {}, ...config }) => {
145
+ return {
146
+ ...config,
147
+ tables: mapObject(tables, (tableName, table) => {
148
+ const { indexes = {} } = table;
149
+ if (!Array.isArray(indexes)) {
150
+ return { ...table, indexes };
151
+ }
152
+ const resolvedIndexes = {};
153
+ for (const index of indexes) {
154
+ if (index.name) {
155
+ const { name: name2, ...rest } = index;
156
+ resolvedIndexes[index.name] = rest;
157
+ continue;
158
+ }
159
+ const indexOn = Array.isArray(index.on) ? index.on.sort().join("_") : index.on;
160
+ const name = tableName + "_" + indexOn + "_idx";
161
+ resolvedIndexes[name] = index;
162
+ }
163
+ return {
164
+ ...table,
165
+ indexes: resolvedIndexes
166
+ };
167
+ })
168
+ };
169
+ });
170
+ export {
171
+ booleanColumnSchema,
172
+ columnSchema,
173
+ columnsSchema,
174
+ dateColumnSchema,
175
+ dbConfigSchema,
176
+ indexSchema,
177
+ jsonColumnSchema,
178
+ numberColumnOptsSchema,
179
+ numberColumnSchema,
180
+ referenceableColumnSchema,
181
+ resolvedIndexSchema,
182
+ tableSchema,
183
+ tablesSchema,
184
+ textColumnOptsSchema,
185
+ textColumnSchema
186
+ };
@@ -0,0 +1,11 @@
1
+ /// <reference types="node" resolution-mode="require"/>
2
+ export declare const SESSION_LOGIN_FILE: import("url").URL;
3
+ export declare const PROJECT_ID_FILE: import("url").URL;
4
+ export interface ManagedAppToken {
5
+ token: string;
6
+ renew(): Promise<void>;
7
+ destroy(): Promise<void>;
8
+ }
9
+ export declare function getProjectIdFromFile(): Promise<string | undefined>;
10
+ export declare function getSessionIdFromFile(): Promise<string | undefined>;
11
+ export declare function getManagedAppTokenOrExit(token?: string): Promise<ManagedAppToken>;
@@ -0,0 +1,181 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { green } from "kleur/colors";
6
+ import ora from "ora";
7
+ import { safeFetch } from "../runtime/utils.js";
8
+ import { MISSING_PROJECT_ID_ERROR, MISSING_SESSION_ID_ERROR } from "./errors.js";
9
+ import { getAstroStudioEnv, getAstroStudioUrl } from "./utils.js";
10
+ const SESSION_LOGIN_FILE = pathToFileURL(join(homedir(), ".astro", "session-token"));
11
+ const PROJECT_ID_FILE = pathToFileURL(join(process.cwd(), ".astro", "link"));
12
+ class ManagedLocalAppToken {
13
+ token;
14
+ constructor(token) {
15
+ this.token = token;
16
+ }
17
+ async renew() {
18
+ }
19
+ async destroy() {
20
+ }
21
+ }
22
+ class ManagedRemoteAppToken {
23
+ token;
24
+ session;
25
+ projectId;
26
+ ttl;
27
+ expires;
28
+ renewTimer;
29
+ static async create(sessionToken, projectId) {
30
+ const { token: shortLivedAppToken, ttl } = await this.createToken(sessionToken, projectId);
31
+ return new ManagedRemoteAppToken({
32
+ token: shortLivedAppToken,
33
+ session: sessionToken,
34
+ projectId,
35
+ ttl
36
+ });
37
+ }
38
+ static async createToken(sessionToken, projectId) {
39
+ const spinner = ora("Connecting to remote database...").start();
40
+ const response = await safeFetch(
41
+ new URL(`${getAstroStudioUrl()}/auth/cli/token-create`),
42
+ {
43
+ method: "POST",
44
+ headers: new Headers({
45
+ Authorization: `Bearer ${sessionToken}`
46
+ }),
47
+ body: JSON.stringify({ projectId })
48
+ },
49
+ (res) => {
50
+ throw new Error(`Failed to create token: ${res.status} ${res.statusText}`);
51
+ }
52
+ );
53
+ spinner.succeed(green("Connected to remote database."));
54
+ const { token, ttl } = await response.json();
55
+ return { token, ttl };
56
+ }
57
+ constructor(options) {
58
+ this.token = options.token;
59
+ this.session = options.session;
60
+ this.projectId = options.projectId;
61
+ this.ttl = options.ttl;
62
+ this.renewTimer = setTimeout(() => this.renew(), 1e3 * 60 * 5 / 2);
63
+ this.expires = getExpiresFromTtl(this.ttl);
64
+ }
65
+ async fetch(url, body) {
66
+ return safeFetch(
67
+ `${getAstroStudioUrl()}${url}`,
68
+ {
69
+ method: "POST",
70
+ headers: {
71
+ Authorization: `Bearer ${this.session}`,
72
+ "Content-Type": "application/json"
73
+ },
74
+ body: JSON.stringify(body)
75
+ },
76
+ () => {
77
+ throw new Error(`Failed to fetch ${url}.`);
78
+ }
79
+ );
80
+ }
81
+ tokenIsValid() {
82
+ return /* @__PURE__ */ new Date() > this.expires;
83
+ }
84
+ createRenewTimer() {
85
+ return setTimeout(() => this.renew(), 1e3 * 60 * this.ttl / 2);
86
+ }
87
+ async renew() {
88
+ clearTimeout(this.renewTimer);
89
+ delete this.renewTimer;
90
+ if (this.tokenIsValid()) {
91
+ const response = await this.fetch("/auth/cli/token-renew", {
92
+ token: this.token,
93
+ projectId: this.projectId
94
+ });
95
+ if (response.status === 200) {
96
+ this.expires = getExpiresFromTtl(this.ttl);
97
+ this.renewTimer = this.createRenewTimer();
98
+ } else {
99
+ throw new Error(`Unexpected response: ${response.status} ${response.statusText}`);
100
+ }
101
+ } else {
102
+ try {
103
+ const { token, ttl } = await ManagedRemoteAppToken.createToken(
104
+ this.session,
105
+ this.projectId
106
+ );
107
+ this.token = token;
108
+ this.ttl = ttl;
109
+ this.expires = getExpiresFromTtl(ttl);
110
+ this.renewTimer = this.createRenewTimer();
111
+ } catch {
112
+ throw new Error(
113
+ `Token has expired and attempts to renew it have failed, please try again.`
114
+ );
115
+ }
116
+ }
117
+ }
118
+ async destroy() {
119
+ try {
120
+ const response = await this.fetch("/auth/cli/token-delete", {
121
+ token: this.token,
122
+ projectId: this.projectId
123
+ });
124
+ if (response.status !== 200) {
125
+ throw new Error(`Unexpected response: ${response.status} ${response.statusText}`);
126
+ }
127
+ } catch (error) {
128
+ console.error("Failed to delete token.", error?.message);
129
+ }
130
+ }
131
+ }
132
+ async function getProjectIdFromFile() {
133
+ try {
134
+ return await readFile(PROJECT_ID_FILE, "utf-8");
135
+ } catch (error) {
136
+ return void 0;
137
+ }
138
+ }
139
+ async function getSessionIdFromFile() {
140
+ try {
141
+ return await readFile(SESSION_LOGIN_FILE, "utf-8");
142
+ } catch (error) {
143
+ return void 0;
144
+ }
145
+ }
146
+ async function getManagedAppTokenOrExit(token) {
147
+ if (token) {
148
+ return new ManagedLocalAppToken(token);
149
+ }
150
+ if (process.env.ASTRO_INTERNAL_TEST_REMOTE) {
151
+ return new ManagedLocalAppToken(
152
+ "fake"
153
+ /* token ignored in test */
154
+ );
155
+ }
156
+ const { ASTRO_STUDIO_APP_TOKEN } = getAstroStudioEnv();
157
+ if (ASTRO_STUDIO_APP_TOKEN) {
158
+ return new ManagedLocalAppToken(ASTRO_STUDIO_APP_TOKEN);
159
+ }
160
+ const sessionToken = await getSessionIdFromFile();
161
+ if (!sessionToken) {
162
+ console.error(MISSING_SESSION_ID_ERROR);
163
+ process.exit(1);
164
+ }
165
+ const projectId = await getProjectIdFromFile();
166
+ if (!sessionToken || !projectId) {
167
+ console.error(MISSING_PROJECT_ID_ERROR);
168
+ process.exit(1);
169
+ }
170
+ return ManagedRemoteAppToken.create(sessionToken, projectId);
171
+ }
172
+ function getExpiresFromTtl(ttl) {
173
+ return new Date(Date.now() + ttl * 60 * 1e3);
174
+ }
175
+ export {
176
+ PROJECT_ID_FILE,
177
+ SESSION_LOGIN_FILE,
178
+ getManagedAppTokenOrExit,
179
+ getProjectIdFromFile,
180
+ getSessionIdFromFile
181
+ };
@@ -0,0 +1,59 @@
1
+ import type { AstroIntegration } from 'astro';
2
+ import type { z } from 'zod';
3
+ import type { MaybeArray, booleanColumnSchema, columnSchema, columnsSchema, dateColumnSchema, dbConfigSchema, indexSchema, jsonColumnSchema, numberColumnOptsSchema, numberColumnSchema, referenceableColumnSchema, resolvedIndexSchema, tableSchema, textColumnOptsSchema, textColumnSchema } from './schemas.js';
4
+ export type ResolvedIndexes = z.output<typeof dbConfigSchema>['tables'][string]['indexes'];
5
+ export type BooleanColumn = z.infer<typeof booleanColumnSchema>;
6
+ export type BooleanColumnInput = z.input<typeof booleanColumnSchema>;
7
+ export type NumberColumn = z.infer<typeof numberColumnSchema>;
8
+ export type NumberColumnInput = z.input<typeof numberColumnSchema>;
9
+ export type TextColumn = z.infer<typeof textColumnSchema>;
10
+ export type TextColumnInput = z.input<typeof textColumnSchema>;
11
+ export type DateColumn = z.infer<typeof dateColumnSchema>;
12
+ export type DateColumnInput = z.input<typeof dateColumnSchema>;
13
+ export type JsonColumn = z.infer<typeof jsonColumnSchema>;
14
+ export type JsonColumnInput = z.input<typeof jsonColumnSchema>;
15
+ export type ColumnType = BooleanColumn['type'] | NumberColumn['type'] | TextColumn['type'] | DateColumn['type'] | JsonColumn['type'];
16
+ export type DBColumn = z.infer<typeof columnSchema>;
17
+ export type DBColumnInput = DateColumnInput | BooleanColumnInput | NumberColumnInput | TextColumnInput | JsonColumnInput;
18
+ export type DBColumns = z.infer<typeof columnsSchema>;
19
+ export type DBTable = z.infer<typeof tableSchema>;
20
+ export type DBTables = Record<string, DBTable>;
21
+ export type ResolvedDBTables = z.output<typeof dbConfigSchema>['tables'];
22
+ export type ResolvedDBTable = z.output<typeof dbConfigSchema>['tables'][string];
23
+ export type DBSnapshot = {
24
+ schema: Record<string, ResolvedDBTable>;
25
+ version: string;
26
+ };
27
+ export type DBConfigInput = z.input<typeof dbConfigSchema>;
28
+ export type DBConfig = z.infer<typeof dbConfigSchema>;
29
+ export type ColumnsConfig = z.input<typeof tableSchema>['columns'];
30
+ export type OutputColumnsConfig = z.output<typeof tableSchema>['columns'];
31
+ export interface TableConfig<TColumns extends ColumnsConfig = ColumnsConfig> extends Pick<z.input<typeof tableSchema>, 'columns' | 'indexes' | 'foreignKeys'> {
32
+ columns: TColumns;
33
+ foreignKeys?: Array<{
34
+ columns: MaybeArray<Extract<keyof TColumns, string>>;
35
+ references: () => MaybeArray<z.input<typeof referenceableColumnSchema>>;
36
+ }>;
37
+ indexes?: Array<IndexConfig<TColumns>> | Record<string, LegacyIndexConfig<TColumns>>;
38
+ deprecated?: boolean;
39
+ }
40
+ interface IndexConfig<TColumns extends ColumnsConfig> extends z.input<typeof indexSchema> {
41
+ on: MaybeArray<Extract<keyof TColumns, string>>;
42
+ }
43
+ /** @deprecated */
44
+ interface LegacyIndexConfig<TColumns extends ColumnsConfig> extends z.input<typeof resolvedIndexSchema> {
45
+ on: MaybeArray<Extract<keyof TColumns, string>>;
46
+ }
47
+ export type NumberColumnOpts = z.input<typeof numberColumnOptsSchema>;
48
+ export type TextColumnOpts = z.input<typeof textColumnOptsSchema>;
49
+ export type AstroDbIntegration = AstroIntegration & {
50
+ hooks: {
51
+ 'astro:db:setup'?: (options: {
52
+ extendDb: (options: {
53
+ configEntrypoint?: URL | string;
54
+ seedEntrypoint?: URL | string;
55
+ }) => void;
56
+ }) => void | Promise<void>;
57
+ };
58
+ };
59
+ export {};
File without changes
@@ -0,0 +1,20 @@
1
+ import type { AstroConfig, AstroIntegration } from 'astro';
2
+ import type { AstroDbIntegration } from './types.js';
3
+ export type VitePlugin = Required<AstroConfig['vite']>['plugins'][number];
4
+ export declare function getAstroStudioEnv(envMode?: string): Record<`ASTRO_STUDIO_${string}`, string>;
5
+ export declare function getRemoteDatabaseUrl(): string;
6
+ export declare function getAstroStudioUrl(): string;
7
+ export declare function getDbDirectoryUrl(root: URL | string): URL;
8
+ export declare function defineDbIntegration(integration: AstroDbIntegration): AstroIntegration;
9
+ export type Result<T> = {
10
+ success: true;
11
+ data: T;
12
+ } | {
13
+ success: false;
14
+ data: unknown;
15
+ };
16
+ /**
17
+ * Map an object's values to a new set of values
18
+ * while preserving types.
19
+ */
20
+ export declare function mapObject<T, U = T>(item: Record<string, T>, callback: (key: string, value: T) => U): Record<string, U>;
@@ -0,0 +1,32 @@
1
+ import { loadEnv } from "vite";
2
+ function getAstroStudioEnv(envMode = "") {
3
+ const env = loadEnv(envMode, process.cwd(), "ASTRO_STUDIO_");
4
+ return env;
5
+ }
6
+ function getRemoteDatabaseUrl() {
7
+ const env = getAstroStudioEnv();
8
+ return env.ASTRO_STUDIO_REMOTE_DB_URL || "https://db.services.astro.build";
9
+ }
10
+ function getAstroStudioUrl() {
11
+ const env = getAstroStudioEnv();
12
+ return env.ASTRO_STUDIO_URL || "https://studio.astro.build";
13
+ }
14
+ function getDbDirectoryUrl(root) {
15
+ return new URL("db/", root);
16
+ }
17
+ function defineDbIntegration(integration) {
18
+ return integration;
19
+ }
20
+ function mapObject(item, callback) {
21
+ return Object.fromEntries(
22
+ Object.entries(item).map(([key, value]) => [key, callback(key, value)])
23
+ );
24
+ }
25
+ export {
26
+ defineDbIntegration,
27
+ getAstroStudioEnv,
28
+ getAstroStudioUrl,
29
+ getDbDirectoryUrl,
30
+ getRemoteDatabaseUrl,
31
+ mapObject
32
+ };
@@ -0,0 +1,4 @@
1
+ export type { TableConfig } from './core/types.js';
2
+ export { cli } from './core/cli/index.js';
3
+ export { integration as default } from './core/integration/index.js';
4
+ export { typegen } from './core/integration/typegen.js';
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ import { cli } from "./core/cli/index.js";
2
+ import { integration } from "./core/integration/index.js";
3
+ import { typegen } from "./core/integration/typegen.js";
4
+ export {
5
+ cli,
6
+ integration as default,
7
+ typegen
8
+ };
@@ -0,0 +1,111 @@
1
+ import { LibsqlError } from "@libsql/client";
2
+ import { sql as _sql } from "drizzle-orm";
3
+ function createColumn(type, schema) {
4
+ return {
5
+ type,
6
+ /**
7
+ * @internal
8
+ */
9
+ schema
10
+ };
11
+ }
12
+ function isDbError(err) {
13
+ return err instanceof LibsqlError;
14
+ }
15
+ const column = {
16
+ number: (opts = {}) => {
17
+ return createColumn("number", opts);
18
+ },
19
+ boolean: (opts = {}) => {
20
+ return createColumn("boolean", opts);
21
+ },
22
+ text: (opts = {}) => {
23
+ return createColumn("text", opts);
24
+ },
25
+ date(opts = {}) {
26
+ return createColumn("date", opts);
27
+ },
28
+ json(opts = {}) {
29
+ return createColumn("json", opts);
30
+ }
31
+ };
32
+ function defineTable(userConfig) {
33
+ return userConfig;
34
+ }
35
+ function defineDb(userConfig) {
36
+ return userConfig;
37
+ }
38
+ const NOW = _sql`CURRENT_TIMESTAMP`;
39
+ const TRUE = _sql`TRUE`;
40
+ const FALSE = _sql`FALSE`;
41
+ import {
42
+ sql,
43
+ eq,
44
+ gt,
45
+ gte,
46
+ lt,
47
+ lte,
48
+ ne,
49
+ isNull,
50
+ isNotNull,
51
+ inArray,
52
+ notInArray,
53
+ exists,
54
+ notExists,
55
+ between,
56
+ notBetween,
57
+ like,
58
+ notIlike,
59
+ not,
60
+ asc,
61
+ desc,
62
+ and,
63
+ or,
64
+ count,
65
+ countDistinct,
66
+ avg,
67
+ avgDistinct,
68
+ sum,
69
+ sumDistinct,
70
+ max,
71
+ min
72
+ } from "drizzle-orm";
73
+ export {
74
+ FALSE,
75
+ NOW,
76
+ TRUE,
77
+ and,
78
+ asc,
79
+ avg,
80
+ avgDistinct,
81
+ between,
82
+ column,
83
+ count,
84
+ countDistinct,
85
+ defineDb,
86
+ defineTable,
87
+ desc,
88
+ eq,
89
+ exists,
90
+ gt,
91
+ gte,
92
+ inArray,
93
+ isDbError,
94
+ isNotNull,
95
+ isNull,
96
+ like,
97
+ lt,
98
+ lte,
99
+ max,
100
+ min,
101
+ ne,
102
+ not,
103
+ notBetween,
104
+ notExists,
105
+ notIlike,
106
+ notInArray,
107
+ or,
108
+ sql,
109
+ sum,
110
+ sumDistinct
111
+ };
@@ -0,0 +1,6 @@
1
+ import type { LibSQLDatabase } from 'drizzle-orm/libsql';
2
+ import { type SqliteRemoteDatabase } from 'drizzle-orm/sqlite-proxy';
3
+ export declare function createLocalDatabaseClient({ dbUrl }: {
4
+ dbUrl: string;
5
+ }): LibSQLDatabase;
6
+ export declare function createRemoteDatabaseClient(appToken: string, remoteDbURL: string): SqliteRemoteDatabase<Record<string, never>>;