@astrojs/db 0.8.6 → 0.8.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import type { ColumnsConfig, DBConfigInput, TableConfig } from '../core/types.js';
2
+ export type { LibSQLDatabase } from 'drizzle-orm/libsql';
2
3
  export declare const column: {
3
4
  number: <T extends ({
4
5
  name?: string | undefined;
@@ -144,5 +145,7 @@ export declare function defineTable<TColumns extends ColumnsConfig>(userConfig:
144
145
  export declare function defineDb(userConfig: DBConfigInput): {
145
146
  tables?: unknown;
146
147
  };
147
- export { NOW, TRUE, FALSE } from './index.js';
148
+ export declare const NOW: import("drizzle-orm").SQL<unknown>;
149
+ export declare const TRUE: import("drizzle-orm").SQL<unknown>;
150
+ export declare const FALSE: import("drizzle-orm").SQL<unknown>;
148
151
  export { sql, eq, gt, gte, lt, lte, ne, isNull, isNotNull, inArray, notInArray, exists, notExists, between, notBetween, like, notIlike, not, asc, desc, and, or, } from 'drizzle-orm';
@@ -27,7 +27,7 @@ function printHelp({
27
27
  message.push(
28
28
  linebreak(),
29
29
  ` ${bgGreen(black(` ${commandName} `))} ${green(
30
- `v${"0.8.6"}`
30
+ `v${"0.8.8"}`
31
31
  )} ${headline}`
32
32
  );
33
33
  }
@@ -9,9 +9,6 @@ async function typegen(astroConfig) {
9
9
  async function typegenInternal({ tables, root }) {
10
10
  const content = `// This file is generated by Astro DB
11
11
  declare module 'astro:db' {
12
- export const db: import(${RUNTIME_IMPORT}).SqliteDB;
13
- export const dbUrl: string;
14
-
15
12
  ${Object.entries(tables).map(([name, collection]) => generateTableType(name, collection)).join("\n")}
16
13
  }
17
14
  `;
@@ -24,8 +24,18 @@ class ManagedRemoteAppToken {
24
24
  session;
25
25
  projectId;
26
26
  ttl;
27
+ expires;
27
28
  renewTimer;
28
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) {
29
39
  const spinner = ora("Connecting to remote database...").start();
30
40
  const response = await safeFetch(
31
41
  new URL(`${getAstroStudioUrl()}/auth/cli/token-create`),
@@ -40,15 +50,9 @@ class ManagedRemoteAppToken {
40
50
  throw new Error(`Failed to create token: ${res.status} ${res.statusText}`);
41
51
  }
42
52
  );
43
- await new Promise((resolve) => setTimeout(resolve, 2e3));
44
53
  spinner.succeed(green("Connected to remote database."));
45
- const { token: shortLivedAppToken, ttl } = await response.json();
46
- return new ManagedRemoteAppToken({
47
- token: shortLivedAppToken,
48
- session: sessionToken,
49
- projectId,
50
- ttl
51
- });
54
+ const { token, ttl } = await response.json();
55
+ return { token, ttl };
52
56
  }
53
57
  constructor(options) {
54
58
  this.token = options.token;
@@ -56,6 +60,7 @@ class ManagedRemoteAppToken {
56
60
  this.projectId = options.projectId;
57
61
  this.ttl = options.ttl;
58
62
  this.renewTimer = setTimeout(() => this.renew(), 1e3 * 60 * 5 / 2);
63
+ this.expires = getExpiresFromTtl(this.ttl);
59
64
  }
60
65
  async fetch(url, body) {
61
66
  return safeFetch(
@@ -73,23 +78,41 @@ class ManagedRemoteAppToken {
73
78
  }
74
79
  );
75
80
  }
81
+ tokenIsValid() {
82
+ return /* @__PURE__ */ new Date() > this.expires;
83
+ }
84
+ createRenewTimer() {
85
+ return setTimeout(() => this.renew(), 1e3 * 60 * this.ttl / 2);
86
+ }
76
87
  async renew() {
77
88
  clearTimeout(this.renewTimer);
78
89
  delete this.renewTimer;
79
- try {
90
+ if (this.tokenIsValid()) {
80
91
  const response = await this.fetch("/auth/cli/token-renew", {
81
92
  token: this.token,
82
93
  projectId: this.projectId
83
94
  });
84
95
  if (response.status === 200) {
85
- this.renewTimer = setTimeout(() => this.renew(), 1e3 * 60 * this.ttl / 2);
96
+ this.expires = getExpiresFromTtl(this.ttl);
97
+ this.renewTimer = this.createRenewTimer();
86
98
  } else {
87
99
  throw new Error(`Unexpected response: ${response.status} ${response.statusText}`);
88
100
  }
89
- } catch (error) {
90
- const retryIn = 60 * this.ttl / 10;
91
- console.error(`Failed to renew token. Retrying in ${retryIn} seconds.`, error?.message);
92
- this.renewTimer = setTimeout(() => this.renew(), retryIn * 1e3);
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
+ }
93
116
  }
94
117
  }
95
118
  async destroy() {
@@ -140,6 +163,9 @@ async function getManagedAppTokenOrExit(token) {
140
163
  }
141
164
  return ManagedRemoteAppToken.create(sessionToken, projectId);
142
165
  }
166
+ function getExpiresFromTtl(ttl) {
167
+ return new Date(Date.now() + ttl * 60 * 1e3);
168
+ }
143
169
  export {
144
170
  PROJECT_ID_FILE,
145
171
  SESSION_LOGIN_FILE,
@@ -1,3 +1,4 @@
1
+ import { sql as _sql } from "drizzle-orm";
1
2
  function createColumn(type, schema) {
2
3
  return {
3
4
  type,
@@ -30,7 +31,9 @@ function defineTable(userConfig) {
30
31
  function defineDb(userConfig) {
31
32
  return userConfig;
32
33
  }
33
- import { NOW, TRUE, FALSE } from "./index.js";
34
+ const NOW = _sql`CURRENT_TIMESTAMP`;
35
+ const TRUE = _sql`TRUE`;
36
+ const FALSE = _sql`FALSE`;
34
37
  import {
35
38
  sql,
36
39
  eq,
@@ -1,15 +1,9 @@
1
- import { type ColumnDataType, sql } from 'drizzle-orm';
2
- import type { LibSQLDatabase } from 'drizzle-orm/libsql';
1
+ import { type ColumnDataType } from 'drizzle-orm';
3
2
  import { type DBColumn, type DBTable } from '../core/types.js';
4
- export { sql };
5
- export type SqliteDB = LibSQLDatabase;
6
3
  export type { Table } from './types.js';
7
4
  export { createRemoteDatabaseClient, createLocalDatabaseClient } from './db-client.js';
8
5
  export { seedLocal } from './seed-local.js';
9
6
  export declare function hasPrimaryKey(column: DBColumn): boolean;
10
- export declare const NOW: import("drizzle-orm").SQL<unknown>;
11
- export declare const TRUE: import("drizzle-orm").SQL<unknown>;
12
- export declare const FALSE: import("drizzle-orm").SQL<unknown>;
13
7
  export declare function asDrizzleTable(name: string, table: DBTable): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
14
8
  name: string;
15
9
  schema: undefined;
@@ -13,9 +13,6 @@ import { seedLocal } from "./seed-local.js";
13
13
  function hasPrimaryKey(column) {
14
14
  return "primaryKey" in column.schema && !!column.schema.primaryKey;
15
15
  }
16
- const NOW = sql`CURRENT_TIMESTAMP`;
17
- const TRUE = sql`TRUE`;
18
- const FALSE = sql`FALSE`;
19
16
  const dateType = customType({
20
17
  dataType() {
21
18
  return "text";
@@ -114,13 +111,9 @@ function handleSerializedSQL(def) {
114
111
  return def;
115
112
  }
116
113
  export {
117
- FALSE,
118
- NOW,
119
- TRUE,
120
114
  asDrizzleTable,
121
115
  createLocalDatabaseClient,
122
116
  createRemoteDatabaseClient,
123
117
  hasPrimaryKey,
124
- seedLocal,
125
- sql
118
+ seedLocal
126
119
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrojs/db",
3
- "version": "0.8.6",
3
+ "version": "0.8.8",
4
4
  "description": "",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -80,7 +80,7 @@
80
80
  "mocha": "^10.2.0",
81
81
  "typescript": "^5.2.2",
82
82
  "vite": "^5.1.4",
83
- "astro": "4.5.5",
83
+ "astro": "4.5.6",
84
84
  "astro-scripts": "0.0.14"
85
85
  },
86
86
  "scripts": {
package/virtual.d.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  declare module 'astro:db' {
2
2
  type RuntimeConfig = typeof import('./dist/_internal/runtime/config.js');
3
3
 
4
+ export const db: import('./dist/_internal/runtime/config.js').LibSQLDatabase;
5
+ export const dbUrl: string;
6
+
4
7
  export const sql: RuntimeConfig['sql'];
5
8
  export const NOW: RuntimeConfig['NOW'];
6
9
  export const TRUE: RuntimeConfig['TRUE'];
@@ -1,16 +0,0 @@
1
- export declare const MISSING_SESSION_ID_ERROR: string;
2
- export declare const MISSING_PROJECT_ID_ERROR: string;
3
- export declare const MISSING_EXECUTE_PATH_ERROR: string;
4
- export declare const RENAME_TABLE_ERROR: (oldTable: string, newTable: string) => string;
5
- export declare const RENAME_COLUMN_ERROR: (oldSelector: string, newSelector: string) => string;
6
- export declare const FILE_NOT_FOUND_ERROR: (path: string) => string;
7
- export declare const SHELL_QUERY_MISSING_ERROR: string;
8
- export declare const SEED_ERROR: (error: string) => string;
9
- export declare const EXEC_ERROR: (error: string) => string;
10
- export declare const SEED_DEFAULT_EXPORT_ERROR: (fileName: string) => string;
11
- export declare const EXEC_DEFAULT_EXPORT_ERROR: (fileName: string) => string;
12
- export declare const REFERENCE_DNE_ERROR: (columnName: string) => string;
13
- export declare const FOREIGN_KEY_DNE_ERROR: (tableName: string) => string;
14
- export declare const FOREIGN_KEY_REFERENCES_LENGTH_ERROR: (tableName: string) => string;
15
- export declare const FOREIGN_KEY_REFERENCES_EMPTY_ERROR: (tableName: string) => string;
16
- export declare const INTEGRATION_TABLE_CONFLICT_ERROR: (integrationName: string, tableName: string, isUserConflict: boolean) => string;
@@ -1,5 +0,0 @@
1
- import type { LibSQLDatabase } from 'drizzle-orm/libsql';
2
- export declare function createLocalDatabaseClient({ dbUrl }: {
3
- dbUrl: string;
4
- }): LibSQLDatabase;
5
- export declare function createRemoteDatabaseClient(appToken: string, remoteDbURL: string): import("drizzle-orm/sqlite-proxy").SqliteRemoteDatabase<Record<string, never>>;
@@ -1,31 +0,0 @@
1
- import { type ColumnDataType, sql } from 'drizzle-orm';
2
- import type { LibSQLDatabase } from 'drizzle-orm/libsql';
3
- import { type DBColumn, type DBTable } from '../core/types.js';
4
- export { sql };
5
- export type SqliteDB = LibSQLDatabase;
6
- export type { Table } from './types.js';
7
- export { createRemoteDatabaseClient, createLocalDatabaseClient } from './db-client.js';
8
- export { seedLocal } from './seed-local.js';
9
- export declare function hasPrimaryKey(column: DBColumn): boolean;
10
- export declare const NOW: import("drizzle-orm").SQL<unknown>;
11
- export declare const TRUE: import("drizzle-orm").SQL<unknown>;
12
- export declare const FALSE: import("drizzle-orm").SQL<unknown>;
13
- export declare function asDrizzleTable(name: string, table: DBTable): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
14
- name: string;
15
- schema: undefined;
16
- columns: {
17
- [x: string]: import("drizzle-orm/sqlite-core").SQLiteColumn<{
18
- name: string;
19
- tableName: string;
20
- dataType: ColumnDataType;
21
- columnType: string;
22
- data: unknown;
23
- driverParam: unknown;
24
- notNull: false;
25
- hasDefault: false;
26
- enumValues: string[] | undefined;
27
- baseColumn: never;
28
- }, object>;
29
- };
30
- dialect: "sqlite";
31
- }>;
@@ -1,71 +0,0 @@
1
- import type { BooleanColumn, ColumnType, DBColumn, DBTable, DateColumn, JsonColumn, NumberColumn, TextColumn } from '../core/types.js';
2
- export declare const SEED_DEV_FILE_NAME: string[];
3
- export declare function getDropTableIfExistsQuery(tableName: string): string;
4
- export declare function getCreateTableQuery(tableName: string, table: DBTable): string;
5
- export declare function getCreateIndexQueries(tableName: string, table: Pick<DBTable, 'indexes'>): string[];
6
- export declare function getCreateForeignKeyQueries(tableName: string, table: DBTable): string[];
7
- export declare function schemaTypeToSqlType(type: ColumnType): 'text' | 'integer';
8
- export declare function getModifiers(columnName: string, column: DBColumn): string;
9
- export declare function getReferencesConfig(column: DBColumn): {
10
- type: "number";
11
- schema: ({
12
- unique: boolean;
13
- deprecated: boolean;
14
- name?: string | undefined;
15
- label?: string | undefined;
16
- collection?: string | undefined;
17
- } & {
18
- optional: boolean;
19
- primaryKey: false;
20
- default?: number | import("./types.js").SerializedSQL | undefined;
21
- } & {
22
- references?: any | undefined;
23
- }) | ({
24
- unique: boolean;
25
- deprecated: boolean;
26
- name?: string | undefined;
27
- label?: string | undefined;
28
- collection?: string | undefined;
29
- } & {
30
- primaryKey: true;
31
- optional?: false | undefined;
32
- default?: undefined;
33
- } & {
34
- references?: any | undefined;
35
- });
36
- } | {
37
- type: "text";
38
- schema: ({
39
- unique: boolean;
40
- deprecated: boolean;
41
- name?: string | undefined;
42
- label?: string | undefined;
43
- collection?: string | undefined;
44
- default?: string | import("./types.js").SerializedSQL | undefined;
45
- multiline?: boolean | undefined;
46
- } & {
47
- optional: boolean;
48
- primaryKey: false;
49
- } & {
50
- references?: any | undefined;
51
- }) | ({
52
- unique: boolean;
53
- deprecated: boolean;
54
- name?: string | undefined;
55
- label?: string | undefined;
56
- collection?: string | undefined;
57
- default?: string | import("./types.js").SerializedSQL | undefined;
58
- multiline?: boolean | undefined;
59
- } & {
60
- primaryKey: true;
61
- optional?: false | undefined;
62
- } & {
63
- references?: any | undefined;
64
- });
65
- } | undefined;
66
- type WithDefaultDefined<T extends DBColumn> = T & {
67
- schema: Required<Pick<T['schema'], 'default'>>;
68
- };
69
- type DBColumnWithDefault = WithDefaultDefined<TextColumn> | WithDefaultDefined<DateColumn> | WithDefaultDefined<NumberColumn> | WithDefaultDefined<BooleanColumn> | WithDefaultDefined<JsonColumn>;
70
- export declare function hasDefault(column: DBColumn): column is DBColumnWithDefault;
71
- export {};
@@ -1,10 +0,0 @@
1
- import type { LibSQLDatabase } from 'drizzle-orm/libsql';
2
- import { type DBTables } from '../core/types.js';
3
- export declare function seedLocal({ db, tables, userSeedGlob, integrationSeedFunctions, }: {
4
- db: LibSQLDatabase;
5
- tables: DBTables;
6
- userSeedGlob: Record<string, {
7
- default?: () => Promise<void>;
8
- }>;
9
- integrationSeedFunctions: Array<() => Promise<void>>;
10
- }): Promise<void>;
@@ -1,4 +0,0 @@
1
- /**
2
- * Small wrapper around fetch that throws an error if the response is not OK. Allows for custom error handling as well through the onNotOK callback.
3
- */
4
- export declare function safeFetch(url: Parameters<typeof fetch>[0], options?: Parameters<typeof fetch>[1], onNotOK?: (response: Response) => void | Promise<void>): Promise<Response>;