@neondatabase/neon-js 0.1.0-alpha.1

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.
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env node
2
+ import meow from "meow";
3
+ import { PostgresMeta } from "@supabase/postgres-meta";
4
+ import { getGeneratorMetadata } from "@supabase/postgres-meta/dist/lib/generators.js";
5
+ import { apply } from "@supabase/postgres-meta/dist/server/templates/typescript.js";
6
+ import { mkdirSync, writeFileSync } from "fs";
7
+ import { dirname } from "path";
8
+
9
+ //#region src/cli/utils/parse-duration.ts
10
+ function parseDuration(duration) {
11
+ const match = duration.match(/^(\d+)(s|m|h)?$/);
12
+ if (!match) throw new Error(`Invalid duration format: ${duration}. Use format like "30s", "1m", "90s"`);
13
+ const value = parseInt(match[1], 10);
14
+ const unit = match[2] || "s";
15
+ switch (unit) {
16
+ case "s": return value * 1e3;
17
+ case "m": return value * 60 * 1e3;
18
+ case "h": return value * 60 * 60 * 1e3;
19
+ default: throw new Error(`Unknown duration unit: ${unit}`);
20
+ }
21
+ }
22
+
23
+ //#endregion
24
+ //#region src/cli/commands/generate-types.ts
25
+ async function generateTypes(options) {
26
+ const { connectionString, schemas = ["public"], detectOneToOneRelationships = true } = options;
27
+ const pgMeta = new PostgresMeta({ connectionString });
28
+ try {
29
+ const { data: metadata } = await getGeneratorMetadata(pgMeta, { includedSchemas: schemas });
30
+ if (!metadata) throw new Error("No metadata found. Please check your database connection and schema.");
31
+ return await apply({
32
+ ...metadata,
33
+ detectOneToOneRelationships
34
+ });
35
+ } finally {
36
+ await pgMeta.end();
37
+ }
38
+ }
39
+
40
+ //#endregion
41
+ //#region src/cli/commands/gen-types.ts
42
+ async function genTypes(flags) {
43
+ const dbUrl = flags.dbUrl?.trim();
44
+ if (!dbUrl) {
45
+ console.error("Error: --db-url is required");
46
+ console.error("Run \"neon-js gen-types --help\" for usage information");
47
+ process.exit(1);
48
+ }
49
+ const options = {
50
+ connectionString: dbUrl,
51
+ schemas: flags.schema,
52
+ detectOneToOneRelationships: !flags.postgrestV9Compat
53
+ };
54
+ if (flags.queryTimeout) try {
55
+ options.queryTimeout = parseDuration(flags.queryTimeout);
56
+ } catch (error) {
57
+ console.error(`Error: ${error instanceof Error ? error.message : error}`);
58
+ process.exit(1);
59
+ }
60
+ const outputPath = flags.output;
61
+ console.log("Generating types...");
62
+ console.log(`Database: ${options.connectionString.split("@")[1] || "connected"}`);
63
+ console.log(`Schemas: ${options.schemas?.join(", ") || "public"}`);
64
+ console.log(`Output: ${outputPath}`);
65
+ const types = await generateTypes(options);
66
+ const outputDir = dirname(outputPath);
67
+ if (outputDir !== ".") mkdirSync(outputDir, { recursive: true });
68
+ writeFileSync(outputPath, types);
69
+ console.log(`✅ Types generated successfully at ${outputPath}`);
70
+ }
71
+
72
+ //#endregion
73
+ //#region src/cli/index.ts
74
+ async function main() {
75
+ const cli = meow(`
76
+ Usage
77
+ $ neon-js gen-types --db-url <url> [options]
78
+
79
+ Commands
80
+ gen-types Generate TypeScript types from your database schema
81
+
82
+ Required Options
83
+ --db-url <url> Database connection string
84
+
85
+ Options
86
+ --output, -o <path> Output file path (default: database.types.ts)
87
+ --schema, -s <name> Schema to include (repeatable, default: public)
88
+ --postgrest-v9-compat Disable one-to-one relationship detection
89
+ --query-timeout <duration> Query timeout (default: 15s, format: 30s, 1m, 90s)
90
+
91
+ Examples
92
+ $ neon-js gen-types --db-url "postgresql://user:pass@host:5432/db"
93
+ $ neon-js gen-types --db-url "postgresql://..." --output src/types/db.ts
94
+ $ neon-js gen-types --db-url "postgresql://..." -s public -s auth
95
+ $ neon-js gen-types --db-url "postgresql://..." --postgrest-v9-compat
96
+ $ neon-js gen-types --db-url "postgresql://..." --query-timeout 30s
97
+ `, {
98
+ importMeta: import.meta,
99
+ description: "A TypeScript SDK for Neon services",
100
+ flags: {
101
+ dbUrl: {
102
+ type: "string",
103
+ isRequired: (flags, input) => {
104
+ if (flags.help || flags.version || input.length === 0) return false;
105
+ return true;
106
+ }
107
+ },
108
+ output: {
109
+ type: "string",
110
+ shortFlag: "o",
111
+ default: "database.types.ts"
112
+ },
113
+ schema: {
114
+ type: "string",
115
+ shortFlag: "s",
116
+ isMultiple: true,
117
+ default: ["public"]
118
+ },
119
+ postgrestV9Compat: {
120
+ type: "boolean",
121
+ default: false
122
+ },
123
+ queryTimeout: { type: "string" }
124
+ }
125
+ });
126
+ const command = cli.input[0];
127
+ if (!command) {
128
+ cli.showHelp(0);
129
+ return;
130
+ }
131
+ if (cli.flags.help) {
132
+ cli.showHelp(0);
133
+ return;
134
+ }
135
+ if (command === "gen-types") await genTypes(cli.flags);
136
+ else {
137
+ console.error(`Unknown command: ${command}`);
138
+ console.error("Run \"neon-js --help\" for usage information");
139
+ process.exit(1);
140
+ }
141
+ }
142
+ main();
143
+
144
+ //#endregion
145
+ export { };
@@ -0,0 +1,147 @@
1
+ import { AdminUserAttributes, AuthApiError, AuthChangeEvent, AuthClient as AuthClient$1, AuthError, AuthResponse, Provider as OAuthProvider, Session, SignInWithOAuthCredentials, SignInWithPasswordCredentials as SignInCredentials, SignUpWithPasswordCredentials as SignUpCredentials, Subscription, User, UserAttributes, UserResponse, VerifyOtpParams as VerifyOTPParams, isAuthError } from "@supabase/auth-js";
2
+ import { StackClientApp, StackClientAppConstructorOptions, StackServerApp, StackServerAppConstructorOptions } from "@stackframe/js";
3
+ import { PostgrestClient } from "@supabase/postgrest-js";
4
+ import { StackClientInterface } from "@stackframe/stack-shared";
5
+ import { InternalSession } from "@stackframe/stack-shared/dist/sessions";
6
+
7
+ //#region src/auth/auth-interface.d.ts
8
+ type _AuthClientSupabaseInstance = InstanceType<typeof AuthClient$1>;
9
+ type AuthClient = { [K in keyof _AuthClientSupabaseInstance as _AuthClientSupabaseInstance[K] extends never ? never : K]: _AuthClientSupabaseInstance[K] };
10
+ //#endregion
11
+ //#region src/auth/adapters/stack-auth/stack-auth-types.d.ts
12
+ interface StackAppInternals {
13
+ _getSession(overrideTokenStoreInit?: any): Promise<InternalSession>;
14
+ _getSessionFromTokenStore(tokenStore: any): InternalSession;
15
+ _getOrCreateTokenStore(cookieHelper: any, overrideTokenStoreInit?: any): any;
16
+ _createCookieHelper(): Promise<any>;
17
+ _interface: StackClientInterface;
18
+ redirectToAfterSignOut(): Promise<void>;
19
+ }
20
+ /**
21
+ * Stack Auth client
22
+ * This type extends StackServerApp or StackClientApp to include the _interface property
23
+ * This is a workaround to get the _interface property from the StackAuthAdapter
24
+ */
25
+ type StackAuthClient = (StackServerApp | StackClientApp) & StackAppInternals;
26
+ /**
27
+ * OnAuthStateChangeConfig type
28
+ * This type is used to configure the onAuthStateChange function
29
+ * It is based on the OnAuthStateChangeConfig type from Stack Auth (not exported)
30
+ */
31
+ interface OnAuthStateChangeConfig {
32
+ enableTokenRefreshDetection?: boolean;
33
+ tokenRefreshCheckInterval?: number;
34
+ }
35
+ //#endregion
36
+ //#region src/auth/adapters/stack-auth/stack-auth-adapter.d.ts
37
+ /**
38
+ * Stack Auth adapter implementing the AuthClient interface
39
+ */
40
+ declare class StackAuthAdapter<HasTokenStore extends boolean = boolean, ProjectId extends string = string> implements AuthClient {
41
+ stackAuth: StackAuthClient;
42
+ private stateChangeEmitters;
43
+ private broadcastChannel;
44
+ private tokenRefreshCheckInterval;
45
+ private config;
46
+ constructor(params: StackServerAppConstructorOptions<HasTokenStore, ProjectId>, config?: OnAuthStateChangeConfig);
47
+ admin: AuthClient['admin'];
48
+ mfa: AuthClient['mfa'];
49
+ initialize: AuthClient['initialize'];
50
+ signUp: AuthClient['signUp'];
51
+ signInAnonymously: AuthClient['signInAnonymously'];
52
+ signInWithPassword: AuthClient['signInWithPassword'];
53
+ signInWithOAuth: AuthClient['signInWithOAuth'];
54
+ signInWithOtp: AuthClient['signInWithOtp'];
55
+ signInWithIdToken: AuthClient['signInWithIdToken'];
56
+ signInWithSSO: AuthClient['signInWithSSO'];
57
+ signInWithWeb3: AuthClient['signInWithWeb3'];
58
+ signOut: AuthClient['signOut'];
59
+ verifyOtp: AuthClient['verifyOtp'];
60
+ /**
61
+ * Fetches fresh session data from Stack Auth API.
62
+ * Always makes a network request to get the latest user metadata.
63
+ * Used when we need fresh data (after setSession, refreshSession, etc.)
64
+ */
65
+ private _fetchFreshSession;
66
+ getSession: AuthClient['getSession'];
67
+ refreshSession: AuthClient['refreshSession'];
68
+ setSession: AuthClient['setSession'];
69
+ getUser: AuthClient['getUser'];
70
+ getClaims: AuthClient['getClaims'];
71
+ updateUser: AuthClient['updateUser'];
72
+ getUserIdentities: AuthClient['getUserIdentities'];
73
+ linkIdentity: AuthClient['linkIdentity'];
74
+ unlinkIdentity: AuthClient['unlinkIdentity'];
75
+ resetPasswordForEmail: AuthClient['resetPasswordForEmail'];
76
+ reauthenticate: AuthClient['reauthenticate'];
77
+ resend: AuthClient['resend'];
78
+ onAuthStateChange: AuthClient['onAuthStateChange'];
79
+ private _getSessionFromStackAuthInternals;
80
+ private _getCachedTokensFromStackAuthInternals;
81
+ private emitInitialSession;
82
+ private notifyAllSubscribers;
83
+ private initializeBroadcastChannel;
84
+ private closeBroadcastChannel;
85
+ private startTokenRefreshDetection;
86
+ private stopTokenRefreshDetection;
87
+ /**
88
+ * Exchange an OAuth authorization code for a session.
89
+ *
90
+ * Note: Stack Auth handles OAuth callbacks automatically via callOAuthCallback().
91
+ * This method delegates to Stack Auth's internal flow which:
92
+ * - Retrieves the code and state from the current URL
93
+ * - Retrieves the PKCE verifier from cookies (stored during signInWithOAuth)
94
+ * - Exchanges the code for access/refresh tokens
95
+ * - Creates and stores the user session
96
+ *
97
+ * @param authCode - The authorization code (Stack Auth reads this from URL automatically)
98
+ * @returns Session data or error
99
+ */
100
+ exchangeCodeForSession: AuthClient['exchangeCodeForSession'];
101
+ startAutoRefresh: AuthClient['startAutoRefresh'];
102
+ stopAutoRefresh: AuthClient['stopAutoRefresh'];
103
+ }
104
+ //#endregion
105
+ //#region src/client/neon-client.d.ts
106
+ type NeonClientConstructorOptions<SchemaName> = {
107
+ url: string;
108
+ options?: {
109
+ db?: {
110
+ schema?: Exclude<SchemaName, '__InternalSupabase'>;
111
+ };
112
+ global?: {
113
+ fetch: typeof fetch;
114
+ headers?: Record<string, string>;
115
+ };
116
+ };
117
+ };
118
+ type DefaultSchemaName<Database> = 'public' extends keyof Database ? 'public' : string & keyof Database;
119
+ declare class NeonClient<Database = any, SchemaName extends string & keyof Database = DefaultSchemaName<Database>> extends PostgrestClient<Database, {
120
+ PostgrestVersion: '12';
121
+ }, Exclude<SchemaName, '__InternalSupabase'>> {
122
+ auth?: AuthClient;
123
+ constructor({
124
+ url,
125
+ options
126
+ }: NeonClientConstructorOptions<SchemaName>);
127
+ }
128
+ //#endregion
129
+ //#region src/client/client-factory.d.ts
130
+ type StackAuthOptions<HasTokenStore extends boolean = boolean, ProjectId extends string = string> = StackClientAppConstructorOptions<HasTokenStore, ProjectId> | StackServerAppConstructorOptions<HasTokenStore, ProjectId>;
131
+ type CreateClientOptions<SchemaName> = NeonClientConstructorOptions<SchemaName> & {
132
+ auth: StackAuthOptions;
133
+ };
134
+ /**
135
+ * Factory function to create NeonClient with seamless auth integration
136
+ *
137
+ * @param options - Configuration options
138
+ * @returns NeonClient instance with auth-aware fetch wrapper
139
+ * @throws AuthRequiredError when making requests without authentication
140
+ */
141
+ declare function createClient<Database = any, SchemaName extends string & keyof Database = DefaultSchemaName<Database>>({
142
+ url,
143
+ auth: authOptions,
144
+ options
145
+ }: CreateClientOptions<SchemaName>): NeonClient<Database, SchemaName>;
146
+ //#endregion
147
+ export { type AdminUserAttributes, AuthApiError, type AuthChangeEvent, type AuthClient, AuthError, type AuthResponse, type CreateClientOptions, NeonClient, type OAuthProvider, type Session, type SignInCredentials, type SignInWithOAuthCredentials, type SignUpCredentials, StackAuthAdapter, type Subscription, type User, type UserAttributes, type UserResponse, type VerifyOTPParams, createClient, isAuthError };