@motherbase/cli 0.2.5 → 0.2.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,39 +1,45 @@
1
- 'use strict';
2
-
3
- const api = require('../api');
4
- const config = require('../config');
5
- const prompt = require('../prompt');
6
- const ui = require('../ui');
7
- const { CliError } = require('../context');
8
-
9
- module.exports = {
10
- summary: 'Log in to a Motherbase Console (email/password → session token)',
11
- usage: 'motherbase login [--url <consoleUrl>] [--email <email>]',
12
- async run(ctx, args, flags) {
13
- const consoleUrl = config.normalizeUrl(
14
- flags.url || ctx.env.MOTHERBASE_CONSOLE_URL || ctx.consoleUrl || '',
15
- );
16
- if (!consoleUrl) {
17
- throw new CliError('Console URL required. Use --url <consoleUrl> or set MOTHERBASE_CONSOLE_URL.');
18
- }
19
-
20
- // Non-interactive: accept a token directly (CI).
21
- if (flags.token) {
22
- const email = flags.email || 'token';
23
- config.saveConsoleToken(consoleUrl, flags.token, email);
24
- ui.success(`Stored token for ${consoleUrl}`);
25
- return;
26
- }
27
-
28
- const email = flags.email || (await prompt.question('Email: '));
29
- if (!email) throw new CliError('email is required');
30
- const password = flags.password || (await prompt.password('Password: '));
31
- if (!password) throw new CliError('password is required');
32
-
33
- const data = await api.loginRequest(consoleUrl, email, password);
34
- const token = data && data.token;
35
- if (!token) throw new CliError('login succeeded but no token was returned');
36
- config.saveConsoleToken(consoleUrl, token, email);
37
- ui.success(`Logged in to ${consoleUrl} as ${email}`);
38
- },
39
- };
1
+ 'use strict';
2
+
3
+ const api = require('../api');
4
+ const config = require('../config');
5
+ const prompt = require('../prompt');
6
+ const ui = require('../ui');
7
+ const { CliError } = require('../context');
8
+
9
+ module.exports = {
10
+ summary: 'Log in to a Motherbase Console (email/password → session token)',
11
+ usage: 'motherbase login [--url <consoleUrl>] [--email <email>] [--code <totp>]',
12
+ async run(ctx, args, flags) {
13
+ const consoleUrl = config.normalizeUrl(
14
+ flags.url || ctx.env.MOTHERBASE_CONSOLE_URL || ctx.consoleUrl || '',
15
+ );
16
+ if (!consoleUrl) {
17
+ throw new CliError('Console URL required. Use --url <consoleUrl> or set MOTHERBASE_CONSOLE_URL.');
18
+ }
19
+
20
+ // Non-interactive: accept a token directly (CI).
21
+ if (flags.token) {
22
+ const email = flags.email || 'token';
23
+ config.saveConsoleToken(consoleUrl, flags.token, email);
24
+ ui.success(`Stored token for ${consoleUrl}`);
25
+ return;
26
+ }
27
+
28
+
29
+ const email = flags.email || (await prompt.question('Email: '));
30
+ if (!email) throw new CliError('email is required');
31
+ const password = (typeof flags.password === 'string' && flags.password) || (await prompt.password('Password: '));
32
+ if (!password) throw new CliError('password is required');
33
+
34
+ let data = await api.loginRequest(consoleUrl, email, password);
35
+ if (data.twoFactorCookie) {
36
+ const code = (typeof flags.code === 'string' && flags.code) || (await prompt.question('Authenticator code: '));
37
+ if (!code) throw new CliError('two-factor code is required');
38
+ data = await api.verifyTotpRequest(consoleUrl, data.twoFactorCookie, code);
39
+ }
40
+ const token = data.token;
41
+ if (!token) throw new CliError('login succeeded but no token was returned');
42
+ config.saveConsoleToken(consoleUrl, token, email);
43
+ ui.success(`Logged in to ${consoleUrl} as ${email}`);
44
+ },
45
+ };
@@ -1,179 +1,202 @@
1
- 'use strict';
2
-
3
- // `motherbase migrate codemod <dir>`: port a Supabase codebase's imports, and
4
- // report what this SDK does not implement.
5
- //
6
- // The rewrite is trivial and the report is the point. `@motherbase/client` is
7
- // supabase-js shaped, so most files need one import line changed; what breaks a
8
- // port is the handful of calls that do not exist here, and finding those at
9
- // build time beats finding them when a user hits that screen.
10
- //
11
- // Deliberately a text pass, not an AST pass. A codemod that needs a TypeScript
12
- // parser needs typescript as a CLI dependency, and the patterns below are
13
- // import specifiers and method names, which do not need one. The cost is that a
14
- // match inside a comment or a string is still reported: over-reporting in a
15
- // list a human reads is the acceptable direction to be wrong in.
16
-
17
- const fs = require('fs');
18
- const path = require('path');
19
- const { output } = require('./_util');
20
- const { CliError } = require('../context');
21
-
22
- const SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts']);
23
- const SKIP_DIRECTORIES = new Set(['node_modules', '.git', 'dist', 'build', '.next', 'coverage', '.turbo']);
24
-
25
- /** Import specifiers that map one to one. */
26
- const IMPORT_REWRITES = [
27
- { from: '@supabase/supabase-js', to: '@motherbase/client' },
28
- { from: '@supabase/ssr', to: '@motherbase/ssr' },
29
- ];
30
-
31
- /**
32
- * Calls this SDK does not implement, and what to do instead.
33
- *
34
- * Kept short and kept true: every entry here is a row marked `Not supported` in
35
- * packages/client/COMPATIBILITY.md. An entry that becomes supported and is left
36
- * behind sends people to rewrite working code, so this list is part of the same
37
- * change as implementing the feature.
38
- */
39
- const UNSUPPORTED = [
40
- {
41
- pattern: /\.schema\(\s*['"`](?!public['"`])/g,
42
- what: 'schema() on a schema other than public',
43
- advice: 'The REST API exposes public only. Move the tables, or expose them through a view or an RPC.',
44
- },
45
- {
46
- pattern: /exchangeCodeForSession\s*\(/g,
47
- what: 'auth.exchangeCodeForSession()',
48
- advice: 'This install runs the implicit flow. Read the session client side with auth.getSessionFromUrl().',
49
- },
50
- {
51
- pattern: /signInAnonymously\s*\(/g,
52
- what: 'auth.signInAnonymously()',
53
- advice: 'Not implemented. Create a real user, or gate the feature behind sign-in.',
54
- },
55
- {
56
- pattern: /transform\s*:\s*\{/g,
57
- what: 'storage image transform options',
58
- advice: 'No image pipeline yet. Store the sizes you need at upload time.',
59
- },
60
- {
61
- pattern: /\.delete\(\s*\)\s*(?![\s\S]{0,200}?\.(eq|neq|in|gt|gte|lt|lte|like|ilike|is|filter|match|or|not)\()/g,
62
- what: 'delete() with no filter',
63
- advice: 'Refused with 400 on purpose, so a missing filter cannot empty a table. Add a filter.',
64
- },
65
- ];
66
-
67
- function walk(dir, files = []) {
68
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
69
- if (entry.name.startsWith('.') && entry.name !== '.') continue;
70
- const full = path.join(dir, entry.name);
71
- if (entry.isDirectory()) {
72
- if (SKIP_DIRECTORIES.has(entry.name)) continue;
73
- walk(full, files);
74
- } else if (SOURCE_EXTENSIONS.has(path.extname(entry.name))) {
75
- files.push(full);
76
- }
77
- }
78
- return files;
79
- }
80
-
81
- /** Line number of an offset, 1-based, for a report a human can act on. */
82
- function lineAt(text, index) {
83
- let line = 1;
84
- for (let i = 0; i < index && i < text.length; i++) if (text[i] === '\n') line++;
85
- return line;
86
- }
87
-
88
- function rewriteImports(text) {
89
- let out = text;
90
- let changed = 0;
91
- for (const { from, to } of IMPORT_REWRITES) {
92
- // Only inside a quoted specifier, so a mention in prose is left alone.
93
- const pattern = new RegExp(`(['"\`])${from.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\1`, 'g');
94
- out = out.replace(pattern, match => {
95
- changed++;
96
- return match.replace(from, to);
97
- });
98
- }
99
- return { text: out, changed };
100
- }
101
-
102
- function scanUnsupported(text, file) {
103
- const findings = [];
104
- for (const rule of UNSUPPORTED) {
105
- rule.pattern.lastIndex = 0;
106
- let match;
107
- while ((match = rule.pattern.exec(text)) !== null) {
108
- findings.push({ file, line: lineAt(text, match.index), what: rule.what, advice: rule.advice });
109
- if (match.index === rule.pattern.lastIndex) rule.pattern.lastIndex++;
110
- }
111
- }
112
- return findings;
113
- }
114
-
115
- const codemod = {
116
- summary: 'Rewrite Supabase imports and report what this SDK does not support',
117
- usage: 'motherbase migrate codemod <dir> [--write]',
118
- async run(ctx, args, flags) {
119
- const target = path.resolve(ctx.cwd, args[0] || '.');
120
- if (!fs.existsSync(target) || !fs.statSync(target).isDirectory()) {
121
- throw new CliError(`${target} is not a directory.`);
122
- }
123
-
124
- const files = walk(target);
125
- const rewritten = [];
126
- const findings = [];
127
-
128
- for (const file of files) {
129
- const original = fs.readFileSync(file, 'utf8');
130
- const { text, changed } = rewriteImports(original);
131
- if (changed) {
132
- rewritten.push({ file: path.relative(ctx.cwd, file), imports: changed });
133
- // Scan the rewritten text so a line number matches what the file will
134
- // hold after --write, not what it held before.
135
- if (flags.write) fs.writeFileSync(file, text, 'utf8');
136
- }
137
- findings.push(...scanUnsupported(text, path.relative(ctx.cwd, file)));
138
- }
139
-
140
- const result = {
141
- root: target,
142
- scanned: files.length,
143
- rewritten,
144
- written: Boolean(flags.write),
145
- findings,
146
- };
147
-
148
- output(ctx, result, (data, ui) => {
149
- const verb = data.written ? 'Rewrote' : 'Would rewrite';
150
- ui.info(`Scanned ${data.scanned} files under ${data.root}`);
151
- if (data.rewritten.length) {
152
- ui.info(`${verb} imports in ${data.rewritten.length} file(s):`);
153
- for (const entry of data.rewritten) ui.info(` ${entry.file} (${entry.imports})`);
154
- } else {
155
- ui.info('No Supabase imports found.');
156
- }
157
- if (!data.written && data.rewritten.length) ui.info('Re-run with --write to apply.');
158
-
159
- if (!data.findings.length) {
160
- ui.success('No unsupported calls found.');
161
- return;
162
- }
163
- ui.info('');
164
- ui.info(`${data.findings.length} call(s) this SDK does not support:`);
165
- for (const finding of data.findings) {
166
- ui.info(` ${finding.file}:${finding.line} ${finding.what}`);
167
- ui.info(` ${finding.advice}`);
168
- }
169
- });
170
- },
171
- };
172
-
173
- module.exports = {
174
- summary: 'Port an application from Supabase',
175
- usage: 'motherbase migrate codemod <dir> [--write]',
176
- subcommands: { codemod },
177
- // Exported for the unit test: the scanner is the part worth pinning.
178
- _internals: { rewriteImports, scanUnsupported },
179
- };
1
+ 'use strict';
2
+
3
+ // `motherbase migrate codemod <dir>`: port a Supabase codebase's imports, and
4
+ // report what this SDK does not implement.
5
+ //
6
+ // The rewrite is trivial and the report is the point. `@motherbase/client` is
7
+ // supabase-js shaped (auth aside: it is Better Auth's client), so most files
8
+ // need one import line changed; what breaks a port is the calls that do not
9
+ // exist here, and finding those at build time beats finding them when a user
10
+ // hits that screen.
11
+ //
12
+ // Deliberately a text pass, not an AST pass. A codemod that needs a TypeScript
13
+ // parser needs typescript as a CLI dependency, and the patterns below are
14
+ // import specifiers and method names, which do not need one. The cost is that a
15
+ // match inside a comment or a string is still reported: over-reporting in a
16
+ // list a human reads is the acceptable direction to be wrong in.
17
+
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+ const { output } = require('./_util');
21
+ const { CliError } = require('../context');
22
+
23
+ const SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts']);
24
+ const SKIP_DIRECTORIES = new Set(['node_modules', '.git', 'dist', 'build', '.next', 'coverage', '.turbo']);
25
+
26
+ /** Import specifiers that map one to one. */
27
+ const IMPORT_REWRITES = [
28
+ { from: '@supabase/supabase-js', to: '@motherbase/client' },
29
+ { from: '@supabase/ssr', to: '@motherbase/ssr' },
30
+ ];
31
+
32
+ /**
33
+ * supabase-js auth calls, with the Better Auth call that replaces each one.
34
+ * `client.auth` is Better Auth's own client, and it turns an unknown method
35
+ * into a request that answers 404, so these fail at runtime, not at import.
36
+ */
37
+ function authRenames(renames) {
38
+ return Object.entries(renames).map(([method, replacement]) => ({
39
+ pattern: new RegExp(`\\.auth\\.${method}\\s*\\(`, 'g'),
40
+ what: `auth.${method}()`,
41
+ advice: `Use ${replacement}.`,
42
+ }));
43
+ }
44
+
45
+ /**
46
+ * Calls this SDK does not implement, and what to do instead.
47
+ *
48
+ * Kept short and kept true: every entry here is a row marked `Not supported` in
49
+ * packages/client/COMPATIBILITY.md. An entry that becomes supported and is left
50
+ * behind sends people to rewrite working code, so this list is part of the same
51
+ * change as implementing the feature.
52
+ */
53
+ const UNSUPPORTED = [
54
+ {
55
+ pattern: /\.schema\(\s*['"`](?!public['"`])/g,
56
+ what: 'schema() on a schema other than public',
57
+ advice: 'The REST API exposes public only. Move the tables, or expose them through a view or an RPC.',
58
+ },
59
+ ...authRenames({
60
+ signInWithPassword: 'auth.signIn.email({ email, password })',
61
+ signUp: 'auth.signUp.email({ email, password, name })',
62
+ signInWithOAuth: 'auth.signIn.social({ provider, callbackURL })',
63
+ signInWithIdToken: 'auth.signIn.social({ provider, idToken: { token } })',
64
+ signInWithOtp: "auth.emailOtp.sendVerificationOtp({ email, type: 'sign-in' }), or auth.phoneNumber.sendOtp({ phoneNumber })",
65
+ verifyOtp: 'auth.signIn.emailOtp({ email, otp }), or auth.phoneNumber.verify({ phoneNumber, code })',
66
+ signInAnonymously: 'auth.signIn.anonymous()',
67
+ signInWithSSO: 'auth.signIn.sso({ email, callbackURL })',
68
+ getUser: 'auth.getSession(), which asks the server and returns { session, user }',
69
+ refreshSession: 'auth.getSession(): Better Auth sessions are revalidated, not rotated',
70
+ setSession: 'a storage adapter holding the session, or auth.getSessionFromUrl() on an OAuth return',
71
+ resetPasswordForEmail: 'auth.emailOtp.requestPasswordReset({ email }), then auth.emailOtp.resetPassword({ email, otp, password })',
72
+ getUserIdentities: 'auth.listAccounts()',
73
+ linkIdentity: 'auth.linkSocial({ provider, callbackURL })',
74
+ unlinkIdentity: 'auth.unlinkAccount({ providerId })',
75
+ getClaims: 'auth.token(), which returns a JWT for the session',
76
+ startAutoRefresh: 'nothing: the client revalidates on a 401',
77
+ }),
78
+ {
79
+ pattern: /\.auth\.mfa\./g,
80
+ what: 'auth.mfa.*',
81
+ advice: 'Use auth.twoFactor: enable({ password }), verifyTotp({ code }), disable({ password }).',
82
+ },
83
+ {
84
+ pattern: /\.delete\(\s*\)\s*(?![\s\S]{0,200}?\.(eq|neq|in|gt|gte|lt|lte|like|ilike|is|filter|match|or|not)\()/g,
85
+ what: 'delete() with no filter',
86
+ advice: 'Refused with 400 on purpose, so a missing filter cannot empty a table. Add a filter.',
87
+ },
88
+ ];
89
+
90
+ function walk(dir, files = []) {
91
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
92
+ if (entry.name.startsWith('.') && entry.name !== '.') continue;
93
+ const full = path.join(dir, entry.name);
94
+ if (entry.isDirectory()) {
95
+ if (SKIP_DIRECTORIES.has(entry.name)) continue;
96
+ walk(full, files);
97
+ } else if (SOURCE_EXTENSIONS.has(path.extname(entry.name))) {
98
+ files.push(full);
99
+ }
100
+ }
101
+ return files;
102
+ }
103
+
104
+ /** Line number of an offset, 1-based, for a report a human can act on. */
105
+ function lineAt(text, index) {
106
+ let line = 1;
107
+ for (let i = 0; i < index && i < text.length; i++) if (text[i] === '\n') line++;
108
+ return line;
109
+ }
110
+
111
+ function rewriteImports(text) {
112
+ let out = text;
113
+ let changed = 0;
114
+ for (const { from, to } of IMPORT_REWRITES) {
115
+ // Only inside a quoted specifier, so a mention in prose is left alone.
116
+ const pattern = new RegExp(`(['"\`])${from.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\1`, 'g');
117
+ out = out.replace(pattern, match => {
118
+ changed++;
119
+ return match.replace(from, to);
120
+ });
121
+ }
122
+ return { text: out, changed };
123
+ }
124
+
125
+ function scanUnsupported(text, file) {
126
+ const findings = [];
127
+ for (const rule of UNSUPPORTED) {
128
+ rule.pattern.lastIndex = 0;
129
+ let match;
130
+ while ((match = rule.pattern.exec(text)) !== null) {
131
+ findings.push({ file, line: lineAt(text, match.index), what: rule.what, advice: rule.advice });
132
+ if (match.index === rule.pattern.lastIndex) rule.pattern.lastIndex++;
133
+ }
134
+ }
135
+ return findings;
136
+ }
137
+
138
+ const codemod = {
139
+ summary: 'Rewrite Supabase imports and report what this SDK does not support',
140
+ usage: 'motherbase migrate codemod <dir> [--write]',
141
+ async run(ctx, args, flags) {
142
+ const target = path.resolve(ctx.cwd, args[0] || '.');
143
+ if (!fs.existsSync(target) || !fs.statSync(target).isDirectory()) {
144
+ throw new CliError(`${target} is not a directory.`);
145
+ }
146
+
147
+ const files = walk(target);
148
+ const rewritten = [];
149
+ const findings = [];
150
+
151
+ for (const file of files) {
152
+ const original = fs.readFileSync(file, 'utf8');
153
+ const { text, changed } = rewriteImports(original);
154
+ if (changed) {
155
+ rewritten.push({ file: path.relative(ctx.cwd, file), imports: changed });
156
+ // Scan the rewritten text so a line number matches what the file will
157
+ // hold after --write, not what it held before.
158
+ if (flags.write) fs.writeFileSync(file, text, 'utf8');
159
+ }
160
+ findings.push(...scanUnsupported(text, path.relative(ctx.cwd, file)));
161
+ }
162
+
163
+ const result = {
164
+ root: target,
165
+ scanned: files.length,
166
+ rewritten,
167
+ written: Boolean(flags.write),
168
+ findings,
169
+ };
170
+
171
+ output(ctx, result, (data, ui) => {
172
+ const verb = data.written ? 'Rewrote' : 'Would rewrite';
173
+ ui.info(`Scanned ${data.scanned} files under ${data.root}`);
174
+ if (data.rewritten.length) {
175
+ ui.info(`${verb} imports in ${data.rewritten.length} file(s):`);
176
+ for (const entry of data.rewritten) ui.info(` ${entry.file} (${entry.imports})`);
177
+ } else {
178
+ ui.info('No Supabase imports found.');
179
+ }
180
+ if (!data.written && data.rewritten.length) ui.info('Re-run with --write to apply.');
181
+
182
+ if (!data.findings.length) {
183
+ ui.success('No unsupported calls found.');
184
+ return;
185
+ }
186
+ ui.info('');
187
+ ui.info(`${data.findings.length} call(s) this SDK does not support:`);
188
+ for (const finding of data.findings) {
189
+ ui.info(` ${finding.file}:${finding.line} ${finding.what}`);
190
+ ui.info(` ${finding.advice}`);
191
+ }
192
+ });
193
+ },
194
+ };
195
+
196
+ module.exports = {
197
+ summary: 'Port an application from Supabase',
198
+ usage: 'motherbase migrate codemod <dir> [--write]',
199
+ subcommands: { codemod },
200
+ // Exported for the unit test: the scanner is the part worth pinning.
201
+ _internals: { rewriteImports, scanUnsupported },
202
+ };