@surf-ai/sdk 1.0.0-alpha.0 → 1.0.0-alpha.2

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.
package/dist/db/index.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/db/index.ts
@@ -24,7 +34,9 @@ __export(db_exports, {
24
34
  dbQuery: () => dbQuery,
25
35
  dbStatus: () => dbStatus,
26
36
  dbTableSchema: () => dbTableSchema,
27
- dbTables: () => dbTables
37
+ dbTables: () => dbTables,
38
+ syncSchema: () => syncSchema,
39
+ watchSchema: () => watchSchema
28
40
  });
29
41
  module.exports = __toCommonJS(db_exports);
30
42
 
@@ -112,9 +124,146 @@ async function post(path, body) {
112
124
  return postJson(path, body);
113
125
  }
114
126
 
127
+ // src/db/schema-sync.ts
128
+ var import_fs = __toESM(require("fs"), 1);
129
+ var syncing = false;
130
+ async function syncSchema(options) {
131
+ const { schemaPath, retries = 3, retryDelay = 2e3 } = options;
132
+ for (let i = 0; i < retries; i++) {
133
+ try {
134
+ await doSyncSchema(schemaPath);
135
+ return;
136
+ } catch (err) {
137
+ console.error(`DB schema sync attempt ${i + 1}/${retries} failed: ${err.message}`);
138
+ if (i < retries - 1) await new Promise((r) => setTimeout(r, retryDelay * (i + 1)));
139
+ }
140
+ }
141
+ console.error("DB schema sync failed after all retries");
142
+ }
143
+ async function doSyncSchema(schemaPath) {
144
+ if (syncing) return;
145
+ syncing = true;
146
+ try {
147
+ if (!import_fs.default.existsSync(schemaPath)) return;
148
+ let schema;
149
+ if (schemaPath.endsWith(".ts")) {
150
+ try {
151
+ schema = await import(`${schemaPath}?t=${Date.now()}`);
152
+ } catch (err) {
153
+ if (err instanceof SyntaxError) {
154
+ console.log("DB: schema file has syntax error, waiting for next change...");
155
+ return;
156
+ }
157
+ if (err.message.includes("Cannot find module") || err.message.includes("is not a function")) {
158
+ return;
159
+ }
160
+ throw err;
161
+ }
162
+ } else {
163
+ try {
164
+ delete require.cache[require.resolve(schemaPath)];
165
+ } catch {
166
+ }
167
+ try {
168
+ schema = require(schemaPath);
169
+ } catch (err) {
170
+ if (err instanceof SyntaxError) {
171
+ console.log("DB: schema file has syntax error, waiting for next change...");
172
+ return;
173
+ }
174
+ if (err.message.includes("Cannot find module") || err.message.includes("is not a function")) {
175
+ return;
176
+ }
177
+ throw err;
178
+ }
179
+ }
180
+ let getTableConfig;
181
+ try {
182
+ getTableConfig = require("drizzle-orm/pg-core").getTableConfig;
183
+ } catch {
184
+ return;
185
+ }
186
+ const tables = Object.values(schema).filter(
187
+ (t) => t && typeof t === "object" && /* @__PURE__ */ Symbol.for("drizzle:Name") in t
188
+ );
189
+ if (tables.length === 0) return;
190
+ await post("db/provision", {});
191
+ const existing = (await get("db/tables")).map((t) => t.name);
192
+ const missing = tables.filter((t) => !existing.includes(getTableConfig(t).name));
193
+ if (missing.length > 0) {
194
+ const { generateDrizzleJson, generateMigration } = require("drizzle-kit/api");
195
+ const missingSchema = {};
196
+ for (const t of missing) missingSchema[getTableConfig(t).name] = t;
197
+ const sqls = await generateMigration(generateDrizzleJson({}), generateDrizzleJson(missingSchema));
198
+ for (const sql of sqls) {
199
+ for (let attempt = 0; attempt < 2; attempt++) {
200
+ try {
201
+ await post("db/query", { sql, params: [] });
202
+ console.log(`DB: Executed: ${sql.slice(0, 80)}...`);
203
+ break;
204
+ } catch (err) {
205
+ if (attempt === 0) {
206
+ console.warn(`DB: Retrying after: ${err.message}`);
207
+ await new Promise((r) => setTimeout(r, 1500));
208
+ } else {
209
+ console.error(`DB: Failed: ${sql.slice(0, 80)}... \u2014 ${err.message}`);
210
+ }
211
+ }
212
+ }
213
+ }
214
+ }
215
+ const existingTables = tables.filter((t) => existing.includes(getTableConfig(t).name));
216
+ for (const t of existingTables) {
217
+ const cfg = getTableConfig(t);
218
+ try {
219
+ const live = await get("db/table-schema", { table: cfg.name });
220
+ const liveCols = new Set((live.columns || []).map((c) => c.name));
221
+ for (const col of cfg.columns) {
222
+ if (!liveCols.has(col.name)) {
223
+ const colType = col.getSQLType();
224
+ const ddl = `ALTER TABLE "${cfg.name}" ADD COLUMN IF NOT EXISTS "${col.name}" ${colType}`;
225
+ try {
226
+ await post("db/query", { sql: ddl, params: [] });
227
+ console.log(`DB: Added column ${col.name} to ${cfg.name}`);
228
+ } catch (err) {
229
+ console.warn(`DB: Failed to add column ${col.name} to ${cfg.name}: ${err.message}`);
230
+ }
231
+ }
232
+ }
233
+ } catch (err) {
234
+ console.warn(`DB: Column check failed for ${cfg.name}: ${err.message}`);
235
+ }
236
+ }
237
+ } finally {
238
+ syncing = false;
239
+ }
240
+ }
241
+ function watchSchema(schemaPath, options) {
242
+ const { debounceMs = 1e3, retries = 2, retryDelay = 1500 } = options || {};
243
+ if (!import_fs.default.existsSync(schemaPath)) return () => {
244
+ };
245
+ let debounce = null;
246
+ import_fs.default.watchFile(schemaPath, { interval: 2e3 }, () => {
247
+ if (debounce) clearTimeout(debounce);
248
+ debounce = setTimeout(async () => {
249
+ console.log("DB: schema file changed, re-syncing tables...");
250
+ try {
251
+ await syncSchema({ schemaPath, retries, retryDelay });
252
+ console.log("DB: schema re-sync complete");
253
+ } catch (err) {
254
+ console.error(`DB: schema re-sync failed: ${err.message}`);
255
+ }
256
+ }, debounceMs);
257
+ });
258
+ return () => {
259
+ import_fs.default.unwatchFile(schemaPath);
260
+ if (debounce) clearTimeout(debounce);
261
+ };
262
+ }
263
+
115
264
  // src/db/index.ts
116
265
  async function dbProvision() {
117
- return post("db/provision");
266
+ return post("db/provision", {});
118
267
  }
119
268
  async function dbQuery(sql, params, options) {
120
269
  return post("db/query", { sql, params, arrayMode: options?.arrayMode ?? false });
@@ -134,5 +283,7 @@ async function dbStatus() {
134
283
  dbQuery,
135
284
  dbStatus,
136
285
  dbTableSchema,
137
- dbTables
286
+ dbTables,
287
+ syncSchema,
288
+ watchSchema
138
289
  });
@@ -1,3 +1,36 @@
1
+ /**
2
+ * Shared schema sync logic — used by both Express runtime (createServer)
3
+ * and Next.js template (instrumentation.ts).
4
+ *
5
+ * Reads a Drizzle schema file, provisions the database, creates missing
6
+ * tables, and adds missing columns to existing tables.
7
+ */
8
+ interface SchemaSyncOptions {
9
+ /** Path to the schema file (e.g., 'db/schema.js' or 'db/schema.ts') */
10
+ schemaPath: string;
11
+ /** Number of retries on failure (default: 3) */
12
+ retries?: number;
13
+ /** Base delay between retries in ms (default: 2000) */
14
+ retryDelay?: number;
15
+ }
16
+ /**
17
+ * Sync a Drizzle schema file to the database.
18
+ *
19
+ * - Provisions the database via the Surf proxy
20
+ * - Creates missing tables using drizzle-kit DDL generation
21
+ * - Adds missing columns to existing tables via ALTER TABLE
22
+ */
23
+ declare function syncSchema(options: SchemaSyncOptions): Promise<void>;
24
+ /**
25
+ * Watch a schema file for changes and re-sync on edit.
26
+ * Returns a cleanup function to stop watching.
27
+ */
28
+ declare function watchSchema(schemaPath: string, options?: {
29
+ debounceMs?: number;
30
+ retries?: number;
31
+ retryDelay?: number;
32
+ }): () => void;
33
+
1
34
  /**
2
35
  * @surf-ai/sdk/db — Drizzle ORM + Neon PostgreSQL database helpers.
3
36
  *
@@ -12,6 +45,7 @@
12
45
  * // Raw SQL:
13
46
  * const result = await dbQuery('SELECT * FROM users WHERE id = $1', [userId])
14
47
  */
48
+
15
49
  /**
16
50
  * Provision a database for the current user via db/provision.
17
51
  * Returns connection metadata. Neon auto-creates the DB if it doesn't exist.
@@ -48,4 +82,4 @@ declare function dbStatus(): Promise<{
48
82
  database?: string;
49
83
  }>;
50
84
 
51
- export { dbProvision, dbQuery, dbStatus, dbTableSchema, dbTables };
85
+ export { type SchemaSyncOptions, dbProvision, dbQuery, dbStatus, dbTableSchema, dbTables, syncSchema, watchSchema };
@@ -1,3 +1,36 @@
1
+ /**
2
+ * Shared schema sync logic — used by both Express runtime (createServer)
3
+ * and Next.js template (instrumentation.ts).
4
+ *
5
+ * Reads a Drizzle schema file, provisions the database, creates missing
6
+ * tables, and adds missing columns to existing tables.
7
+ */
8
+ interface SchemaSyncOptions {
9
+ /** Path to the schema file (e.g., 'db/schema.js' or 'db/schema.ts') */
10
+ schemaPath: string;
11
+ /** Number of retries on failure (default: 3) */
12
+ retries?: number;
13
+ /** Base delay between retries in ms (default: 2000) */
14
+ retryDelay?: number;
15
+ }
16
+ /**
17
+ * Sync a Drizzle schema file to the database.
18
+ *
19
+ * - Provisions the database via the Surf proxy
20
+ * - Creates missing tables using drizzle-kit DDL generation
21
+ * - Adds missing columns to existing tables via ALTER TABLE
22
+ */
23
+ declare function syncSchema(options: SchemaSyncOptions): Promise<void>;
24
+ /**
25
+ * Watch a schema file for changes and re-sync on edit.
26
+ * Returns a cleanup function to stop watching.
27
+ */
28
+ declare function watchSchema(schemaPath: string, options?: {
29
+ debounceMs?: number;
30
+ retries?: number;
31
+ retryDelay?: number;
32
+ }): () => void;
33
+
1
34
  /**
2
35
  * @surf-ai/sdk/db — Drizzle ORM + Neon PostgreSQL database helpers.
3
36
  *
@@ -12,6 +45,7 @@
12
45
  * // Raw SQL:
13
46
  * const result = await dbQuery('SELECT * FROM users WHERE id = $1', [userId])
14
47
  */
48
+
15
49
  /**
16
50
  * Provision a database for the current user via db/provision.
17
51
  * Returns connection metadata. Neon auto-creates the DB if it doesn't exist.
@@ -48,4 +82,4 @@ declare function dbStatus(): Promise<{
48
82
  database?: string;
49
83
  }>;
50
84
 
51
- export { dbProvision, dbQuery, dbStatus, dbTableSchema, dbTables };
85
+ export { type SchemaSyncOptions, dbProvision, dbQuery, dbStatus, dbTableSchema, dbTables, syncSchema, watchSchema };
package/dist/db/index.js CHANGED
@@ -1,3 +1,10 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
1
8
  // src/core/config.ts
2
9
  var DEFAULT_API_BASE_URL = "https://api.ask.surf/gateway/v1";
3
10
  function trimTrailingSlashes(value) {
@@ -82,9 +89,146 @@ async function post(path, body) {
82
89
  return postJson(path, body);
83
90
  }
84
91
 
92
+ // src/db/schema-sync.ts
93
+ import fs from "fs";
94
+ var syncing = false;
95
+ async function syncSchema(options) {
96
+ const { schemaPath, retries = 3, retryDelay = 2e3 } = options;
97
+ for (let i = 0; i < retries; i++) {
98
+ try {
99
+ await doSyncSchema(schemaPath);
100
+ return;
101
+ } catch (err) {
102
+ console.error(`DB schema sync attempt ${i + 1}/${retries} failed: ${err.message}`);
103
+ if (i < retries - 1) await new Promise((r) => setTimeout(r, retryDelay * (i + 1)));
104
+ }
105
+ }
106
+ console.error("DB schema sync failed after all retries");
107
+ }
108
+ async function doSyncSchema(schemaPath) {
109
+ if (syncing) return;
110
+ syncing = true;
111
+ try {
112
+ if (!fs.existsSync(schemaPath)) return;
113
+ let schema;
114
+ if (schemaPath.endsWith(".ts")) {
115
+ try {
116
+ schema = await import(`${schemaPath}?t=${Date.now()}`);
117
+ } catch (err) {
118
+ if (err instanceof SyntaxError) {
119
+ console.log("DB: schema file has syntax error, waiting for next change...");
120
+ return;
121
+ }
122
+ if (err.message.includes("Cannot find module") || err.message.includes("is not a function")) {
123
+ return;
124
+ }
125
+ throw err;
126
+ }
127
+ } else {
128
+ try {
129
+ delete __require.cache[__require.resolve(schemaPath)];
130
+ } catch {
131
+ }
132
+ try {
133
+ schema = __require(schemaPath);
134
+ } catch (err) {
135
+ if (err instanceof SyntaxError) {
136
+ console.log("DB: schema file has syntax error, waiting for next change...");
137
+ return;
138
+ }
139
+ if (err.message.includes("Cannot find module") || err.message.includes("is not a function")) {
140
+ return;
141
+ }
142
+ throw err;
143
+ }
144
+ }
145
+ let getTableConfig;
146
+ try {
147
+ getTableConfig = __require("drizzle-orm/pg-core").getTableConfig;
148
+ } catch {
149
+ return;
150
+ }
151
+ const tables = Object.values(schema).filter(
152
+ (t) => t && typeof t === "object" && /* @__PURE__ */ Symbol.for("drizzle:Name") in t
153
+ );
154
+ if (tables.length === 0) return;
155
+ await post("db/provision", {});
156
+ const existing = (await get("db/tables")).map((t) => t.name);
157
+ const missing = tables.filter((t) => !existing.includes(getTableConfig(t).name));
158
+ if (missing.length > 0) {
159
+ const { generateDrizzleJson, generateMigration } = __require("drizzle-kit/api");
160
+ const missingSchema = {};
161
+ for (const t of missing) missingSchema[getTableConfig(t).name] = t;
162
+ const sqls = await generateMigration(generateDrizzleJson({}), generateDrizzleJson(missingSchema));
163
+ for (const sql of sqls) {
164
+ for (let attempt = 0; attempt < 2; attempt++) {
165
+ try {
166
+ await post("db/query", { sql, params: [] });
167
+ console.log(`DB: Executed: ${sql.slice(0, 80)}...`);
168
+ break;
169
+ } catch (err) {
170
+ if (attempt === 0) {
171
+ console.warn(`DB: Retrying after: ${err.message}`);
172
+ await new Promise((r) => setTimeout(r, 1500));
173
+ } else {
174
+ console.error(`DB: Failed: ${sql.slice(0, 80)}... \u2014 ${err.message}`);
175
+ }
176
+ }
177
+ }
178
+ }
179
+ }
180
+ const existingTables = tables.filter((t) => existing.includes(getTableConfig(t).name));
181
+ for (const t of existingTables) {
182
+ const cfg = getTableConfig(t);
183
+ try {
184
+ const live = await get("db/table-schema", { table: cfg.name });
185
+ const liveCols = new Set((live.columns || []).map((c) => c.name));
186
+ for (const col of cfg.columns) {
187
+ if (!liveCols.has(col.name)) {
188
+ const colType = col.getSQLType();
189
+ const ddl = `ALTER TABLE "${cfg.name}" ADD COLUMN IF NOT EXISTS "${col.name}" ${colType}`;
190
+ try {
191
+ await post("db/query", { sql: ddl, params: [] });
192
+ console.log(`DB: Added column ${col.name} to ${cfg.name}`);
193
+ } catch (err) {
194
+ console.warn(`DB: Failed to add column ${col.name} to ${cfg.name}: ${err.message}`);
195
+ }
196
+ }
197
+ }
198
+ } catch (err) {
199
+ console.warn(`DB: Column check failed for ${cfg.name}: ${err.message}`);
200
+ }
201
+ }
202
+ } finally {
203
+ syncing = false;
204
+ }
205
+ }
206
+ function watchSchema(schemaPath, options) {
207
+ const { debounceMs = 1e3, retries = 2, retryDelay = 1500 } = options || {};
208
+ if (!fs.existsSync(schemaPath)) return () => {
209
+ };
210
+ let debounce = null;
211
+ fs.watchFile(schemaPath, { interval: 2e3 }, () => {
212
+ if (debounce) clearTimeout(debounce);
213
+ debounce = setTimeout(async () => {
214
+ console.log("DB: schema file changed, re-syncing tables...");
215
+ try {
216
+ await syncSchema({ schemaPath, retries, retryDelay });
217
+ console.log("DB: schema re-sync complete");
218
+ } catch (err) {
219
+ console.error(`DB: schema re-sync failed: ${err.message}`);
220
+ }
221
+ }, debounceMs);
222
+ });
223
+ return () => {
224
+ fs.unwatchFile(schemaPath);
225
+ if (debounce) clearTimeout(debounce);
226
+ };
227
+ }
228
+
85
229
  // src/db/index.ts
86
230
  async function dbProvision() {
87
- return post("db/provision");
231
+ return post("db/provision", {});
88
232
  }
89
233
  async function dbQuery(sql, params, options) {
90
234
  return post("db/query", { sql, params, arrayMode: options?.arrayMode ?? false });
@@ -103,5 +247,7 @@ export {
103
247
  dbQuery,
104
248
  dbStatus,
105
249
  dbTableSchema,
106
- dbTables
250
+ dbTables,
251
+ syncSchema,
252
+ watchSchema
107
253
  };