layerbase 0.1.3 → 0.3.0

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 (81) hide show
  1. package/{src/cli.tsx → dist/cli.js} +37 -36
  2. package/dist/cli.js.map +1 -0
  3. package/dist/commands/alias.js +27 -0
  4. package/dist/commands/alias.js.map +1 -0
  5. package/dist/commands/connect.js +51 -0
  6. package/dist/commands/connect.js.map +1 -0
  7. package/dist/commands/connection-string.js +43 -0
  8. package/dist/commands/connection-string.js.map +1 -0
  9. package/dist/commands/interactive.js +148 -0
  10. package/dist/commands/interactive.js.map +1 -0
  11. package/dist/commands/login.js +61 -0
  12. package/dist/commands/login.js.map +1 -0
  13. package/dist/commands/logout.js +25 -0
  14. package/dist/commands/logout.js.map +1 -0
  15. package/dist/commands/ls.js +60 -0
  16. package/dist/commands/ls.js.map +1 -0
  17. package/dist/commands/whoami.js +49 -0
  18. package/dist/commands/whoami.js.map +1 -0
  19. package/dist/lib/alias.js +68 -0
  20. package/dist/lib/alias.js.map +1 -0
  21. package/dist/lib/browser-login.js +78 -0
  22. package/dist/lib/browser-login.js.map +1 -0
  23. package/dist/lib/cloud-api.js +44 -0
  24. package/dist/lib/cloud-api.js.map +1 -0
  25. package/dist/lib/commands.js +73 -0
  26. package/dist/lib/commands.js.map +1 -0
  27. package/dist/lib/config.js +32 -0
  28. package/dist/lib/config.js.map +1 -0
  29. package/dist/lib/engines.js +89 -0
  30. package/dist/lib/engines.js.map +1 -0
  31. package/dist/lib/format.js +38 -0
  32. package/dist/lib/format.js.map +1 -0
  33. package/dist/lib/launch.js +43 -0
  34. package/dist/lib/launch.js.map +1 -0
  35. package/dist/lib/open-browser.js +18 -0
  36. package/dist/lib/open-browser.js.map +1 -0
  37. package/dist/lib/run-spindb.js +49 -0
  38. package/dist/lib/run-spindb.js.map +1 -0
  39. package/dist/lib/token.js +15 -0
  40. package/dist/lib/token.js.map +1 -0
  41. package/dist/ui/app.js +27 -0
  42. package/dist/ui/app.js.map +1 -0
  43. package/dist/ui/brand.js +8 -0
  44. package/dist/ui/brand.js.map +1 -0
  45. package/dist/ui/connecting.js +7 -0
  46. package/dist/ui/connecting.js.map +1 -0
  47. package/dist/ui/menu.js +33 -0
  48. package/dist/ui/menu.js.map +1 -0
  49. package/dist/ui/press-enter.js +13 -0
  50. package/dist/ui/press-enter.js.map +1 -0
  51. package/dist/ui/prompt.js +59 -0
  52. package/dist/ui/prompt.js.map +1 -0
  53. package/dist/ui/unknown.js +12 -0
  54. package/dist/ui/unknown.js.map +1 -0
  55. package/package.json +15 -10
  56. package/bin/layerbase.mjs +0 -15
  57. package/src/commands/alias.tsx +0 -28
  58. package/src/commands/connect.tsx +0 -66
  59. package/src/commands/connection-string.tsx +0 -49
  60. package/src/commands/interactive.tsx +0 -168
  61. package/src/commands/login.tsx +0 -103
  62. package/src/commands/logout.tsx +0 -27
  63. package/src/commands/ls.tsx +0 -99
  64. package/src/commands/whoami.tsx +0 -64
  65. package/src/lib/alias.ts +0 -84
  66. package/src/lib/browser-login.ts +0 -115
  67. package/src/lib/cloud-api.ts +0 -96
  68. package/src/lib/config.ts +0 -45
  69. package/src/lib/engines.ts +0 -124
  70. package/src/lib/format.ts +0 -47
  71. package/src/lib/launch.ts +0 -47
  72. package/src/lib/open-browser.ts +0 -20
  73. package/src/lib/run-spindb.ts +0 -51
  74. package/src/lib/token.ts +0 -19
  75. package/src/ui/app.tsx +0 -38
  76. package/src/ui/brand.tsx +0 -15
  77. package/src/ui/connecting.tsx +0 -13
  78. package/src/ui/menu.tsx +0 -56
  79. package/src/ui/press-enter.tsx +0 -11
  80. package/src/ui/unknown.tsx +0 -17
  81. package/tsconfig.json +0 -17
@@ -1,124 +0,0 @@
1
- import type { ConnectionInfo } from './cloud-api'
2
-
3
- // Engine values mirror the canonical `Engine` map shared across the Layerbase
4
- // ecosystem (web `lib/databases.ts`, cloud `src/config/engines.ts`). Kept as a
5
- // local literal here so the CLI stays a standalone package with no cross-repo
6
- // import.
7
- const PG_FAMILY = new Set(['postgresql', 'cockroachdb'])
8
- const MYSQL_FAMILY = new Set(['mysql', 'mariadb'])
9
- const REDIS_FAMILY = new Set(['redis', 'valkey'])
10
-
11
- // How the child process learns a path-based secret without it touching argv as
12
- // a value: either via an env var pointing at a 0600 file, or via an argv option
13
- // whose value is the (non-secret) path to a 0600 file.
14
- export type TempFile = {
15
- contents: string
16
- mode: number
17
- via:
18
- | { type: 'env'; envVar: string }
19
- | { type: 'argv'; render: (path: string) => string[] }
20
- }
21
-
22
- export type LaunchPlan = {
23
- bin: string
24
- // argv never contains the password. Host/port/db/user are not secret.
25
- argv: string[]
26
- env?: Record<string, string>
27
- // Secret env vars are merged just for the child, never logged.
28
- secretEnv?: Record<string, string>
29
- tempFile?: TempFile
30
- }
31
-
32
- function commandMatchesEngine(command: string, engine: string): void {
33
- const aliasFamily: Record<string, Set<string>> = {
34
- psql: PG_FAMILY,
35
- 'redis-cli': REDIS_FAMILY,
36
- mysql: MYSQL_FAMILY,
37
- }
38
- const expected = aliasFamily[command]
39
- if (expected && !expected.has(engine)) {
40
- throw new Error(
41
- `\`layerbase ${command}\` does not match engine "${engine}". ` +
42
- 'Use `layerbase connect <db>` to auto-pick the right client.',
43
- )
44
- }
45
- }
46
-
47
- export function buildLaunchPlan(options: {
48
- info: ConnectionInfo
49
- command: string
50
- }): LaunchPlan {
51
- const { info, command } = options
52
- const engine = info.engine.toLowerCase()
53
- commandMatchesEngine(command, engine)
54
-
55
- if (PG_FAMILY.has(engine)) {
56
- return {
57
- bin: 'psql',
58
- argv: [
59
- '-h',
60
- info.host,
61
- '-p',
62
- String(info.port),
63
- '-U',
64
- info.username,
65
- '-d',
66
- info.database,
67
- ],
68
- env: { PGSSLMODE: info.tls === false ? 'prefer' : 'require' },
69
- tempFile: {
70
- // ~/.pgpass line format: host:port:database:user:password
71
- contents: `${info.host}:${info.port}:${info.database}:${info.username}:${info.password}\n`,
72
- mode: 0o600,
73
- via: { type: 'env', envVar: 'PGPASSFILE' },
74
- },
75
- }
76
- }
77
-
78
- if (MYSQL_FAMILY.has(engine)) {
79
- return {
80
- bin: 'mysql',
81
- argv: [
82
- '-h',
83
- info.host,
84
- '-P',
85
- String(info.port),
86
- '-u',
87
- info.username,
88
- info.database,
89
- ],
90
- tempFile: {
91
- // --defaults-extra-file must precede other client options, so it is
92
- // prepended to argv. The file (0600) holds the password, not argv.
93
- contents: `[client]\npassword="${info.password}"\n`,
94
- mode: 0o600,
95
- via: {
96
- type: 'argv',
97
- render: (path) => [`--defaults-extra-file=${path}`],
98
- },
99
- },
100
- }
101
- }
102
-
103
- if (REDIS_FAMILY.has(engine)) {
104
- const argv = ['-h', info.host, '-p', String(info.port)]
105
- if (info.tls !== false) {
106
- argv.push('--tls', '--sni', info.host)
107
- }
108
- if (info.username && info.username !== 'default') {
109
- argv.push('--user', info.username)
110
- }
111
- return {
112
- bin: 'redis-cli',
113
- argv,
114
- // redis-cli reads the password from REDISCLI_AUTH instead of -a, which
115
- // would otherwise show in `ps` and trigger its own warning.
116
- secretEnv: { REDISCLI_AUTH: info.password },
117
- }
118
- }
119
-
120
- throw new Error(
121
- `No secure interactive client is wired for engine "${engine}" yet. ` +
122
- `Use \`layerbase connection-string <db>\` or the dashboard query console.`,
123
- )
124
- }
package/src/lib/format.ts DELETED
@@ -1,47 +0,0 @@
1
- import type { ConnectionInfo } from './cloud-api'
2
-
3
- const SCHEME_BY_ENGINE: Record<string, string> = {
4
- postgresql: 'postgresql',
5
- cockroachdb: 'postgresql',
6
- mysql: 'mysql',
7
- mariadb: 'mysql',
8
- redis: 'redis',
9
- valkey: 'redis',
10
- mongodb: 'mongodb',
11
- ferretdb: 'mongodb',
12
- }
13
-
14
- export function buildConnectionString(info: ConnectionInfo): string {
15
- if (info.uri) {
16
- return info.uri
17
- }
18
-
19
- const scheme = SCHEME_BY_ENGINE[info.engine.toLowerCase()]
20
- if (!scheme) {
21
- throw new Error(
22
- `Cannot build a connection string for engine "${info.engine}". ` +
23
- 'The cloud API did not return a ready-made uri for it.',
24
- )
25
- }
26
-
27
- const auth = `${encodeURIComponent(info.username)}:${encodeURIComponent(
28
- info.password,
29
- )}`
30
- const path = info.database ? `/${info.database}` : ''
31
- return `${scheme}://${auth}@${info.host}:${info.port}${path}`
32
- }
33
-
34
- // Prints connection details for `--print`. The password is masked; use
35
- // `layerbase connection-string <db>` to deliberately reveal it.
36
- export function printConnectionInfo(info: ConnectionInfo): void {
37
- const lines = [
38
- `engine ${info.engine}`,
39
- `host ${info.host}`,
40
- `port ${info.port}`,
41
- `database ${info.database}`,
42
- `username ${info.username}`,
43
- `password ${'*'.repeat(8)} (hidden)`,
44
- `tls ${info.tls === false ? 'off' : 'on'}`,
45
- ]
46
- process.stdout.write(`${lines.join('\n')}\n`)
47
- }
package/src/lib/launch.ts DELETED
@@ -1,47 +0,0 @@
1
- import { spawn } from 'node:child_process'
2
- import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises'
3
- import { tmpdir } from 'node:os'
4
- import { join } from 'node:path'
5
- import type { LaunchPlan } from './engines'
6
-
7
- // Spawns the engine's native client with credentials passed via env or a
8
- // transient 0600 file, never on argv, then cleans the credential up on exit.
9
- export async function runClient(plan: LaunchPlan): Promise<number> {
10
- const scratch = await mkdtemp(join(tmpdir(), 'layerbase-'))
11
- const env: NodeJS.ProcessEnv = {
12
- ...process.env,
13
- ...plan.env,
14
- ...plan.secretEnv,
15
- }
16
- let argv = plan.argv
17
-
18
- try {
19
- if (plan.tempFile) {
20
- const file = join(scratch, 'credential')
21
- await writeFile(file, plan.tempFile.contents, {
22
- mode: plan.tempFile.mode,
23
- })
24
- await chmod(file, plan.tempFile.mode)
25
-
26
- if (plan.tempFile.via.type === 'env') {
27
- env[plan.tempFile.via.envVar] = file
28
- } else {
29
- argv = [...plan.tempFile.via.render(file), ...argv]
30
- }
31
- }
32
-
33
- return await new Promise<number>((resolve) => {
34
- const child = spawn(plan.bin, argv, { stdio: 'inherit', env })
35
- child.on('error', (error) => {
36
- process.stderr.write(
37
- `Failed to launch \`${plan.bin}\`: ${error.message}\n` +
38
- `Make sure \`${plan.bin}\` is installed and on your PATH.\n`,
39
- )
40
- resolve(127)
41
- })
42
- child.on('exit', (exitCode) => resolve(exitCode ?? 0))
43
- })
44
- } finally {
45
- await rm(scratch, { recursive: true, force: true })
46
- }
47
- }
@@ -1,20 +0,0 @@
1
- import { spawn } from 'node:child_process'
2
-
3
- // Opens a URL in the user's default browser. No dependency: just the per-OS
4
- // opener. Rejects if the opener binary can't be spawned (e.g. headless box),
5
- // so the caller can fall back to printing the URL.
6
- export async function openBrowser(url: string): Promise<void> {
7
- const platform = process.platform
8
- const command =
9
- platform === 'darwin' ? 'open' : platform === 'win32' ? 'cmd' : 'xdg-open'
10
- const args = platform === 'win32' ? ['/c', 'start', '', url] : [url]
11
-
12
- await new Promise<void>((resolve, reject) => {
13
- const child = spawn(command, args, { stdio: 'ignore', detached: true })
14
- child.on('error', reject)
15
- child.on('spawn', () => {
16
- child.unref()
17
- resolve()
18
- })
19
- })
20
- }
@@ -1,51 +0,0 @@
1
- import { spawn } from 'node:child_process'
2
- import { existsSync } from 'node:fs'
3
- import { join, delimiter } from 'node:path'
4
-
5
- // Is spindb installed on PATH? If so we run it by bare name (spawn resolves it
6
- // via PATH); otherwise we run it through the package runner that launched
7
- // layerbase, so `npx layerbase` users get `npx spindb` with no global install.
8
- function spindbOnPath(): boolean {
9
- const exts =
10
- process.platform === 'win32' ? ['.cmd', '.exe', '.bat', ''] : ['']
11
- for (const dir of (process.env.PATH ?? '').split(delimiter)) {
12
- if (!dir) continue
13
- for (const ext of exts) {
14
- if (existsSync(join(dir, `spindb${ext}`))) return true
15
- }
16
- }
17
- return false
18
- }
19
-
20
- function detectPackageRunner(): string {
21
- const userAgent = process.env.npm_config_user_agent ?? ''
22
- if (userAgent.startsWith('pnpm')) return 'pnpx'
23
- if (userAgent.startsWith('bun')) return 'bunx'
24
- return 'npx'
25
- }
26
-
27
- // Hand the terminal to the local spindb CLI, passing through any args. This is
28
- // the bridge: spindb manages local databases, layerbase adds the cloud account
29
- // layer around it.
30
- export async function runSpindb(args: string[] = []): Promise<number> {
31
- const onPath = spindbOnPath()
32
- const command = onPath ? 'spindb' : detectPackageRunner()
33
- const fullArgs = onPath ? args : ['spindb', ...args]
34
-
35
- return new Promise<number>((resolve) => {
36
- const child = spawn(command, fullArgs, {
37
- stdio: 'inherit',
38
- // Windows needs a shell to resolve `spindb.cmd` / the package runner.
39
- shell: process.platform === 'win32',
40
- })
41
- child.on('error', (error) => {
42
- process.stderr.write(
43
- `Failed to run spindb: ${error.message}\n` +
44
- 'Install spindb (https://github.com/robertjbass/spindb) or make sure ' +
45
- 'it is on your PATH.\n',
46
- )
47
- resolve(127)
48
- })
49
- child.on('exit', (code) => resolve(code ?? 0))
50
- })
51
- }
package/src/lib/token.ts DELETED
@@ -1,19 +0,0 @@
1
- export type TokenClaims = {
2
- email?: string
3
- // JWT exp claim, in SECONDS since the epoch.
4
- exp?: number
5
- sub?: string
6
- }
7
-
8
- // Decode (without verifying) the claims from the stored JWT. Used only for
9
- // friendly local display: the email and the expiry. Returns null on any parse
10
- // failure.
11
- export function decodeTokenClaims(token: string): TokenClaims | null {
12
- const part = token.split('.')[1]
13
- if (!part) return null
14
- try {
15
- return JSON.parse(Buffer.from(part, 'base64url').toString()) as TokenClaims
16
- } catch {
17
- return null
18
- }
19
- }
package/src/ui/app.tsx DELETED
@@ -1,38 +0,0 @@
1
- import { Login } from '../commands/login'
2
- import { Logout } from '../commands/logout'
3
- import { List } from '../commands/ls'
4
- import { Whoami } from '../commands/whoami'
5
- import { Alias } from '../commands/alias'
6
- import { ConnectionString } from '../commands/connection-string'
7
- import { Unknown } from './unknown'
8
-
9
- export type CommandFlags = {
10
- print?: boolean
11
- json?: boolean
12
- apiUrl?: string
13
- }
14
-
15
- type AppProps = {
16
- command: string
17
- args: string[]
18
- flags: CommandFlags
19
- }
20
-
21
- export function App({ command, args, flags }: AppProps) {
22
- switch (command) {
23
- case 'login':
24
- return <Login flags={flags} />
25
- case 'logout':
26
- return <Logout />
27
- case 'ls':
28
- return <List json={flags.json ?? false} />
29
- case 'whoami':
30
- return <Whoami json={flags.json ?? false} />
31
- case 'alias':
32
- return <Alias />
33
- case 'connection-string':
34
- return <ConnectionString dbRef={args[0]} />
35
- default:
36
- return <Unknown command={command} />
37
- }
38
- }
package/src/ui/brand.tsx DELETED
@@ -1,15 +0,0 @@
1
- import { Box, Text } from 'ink'
2
-
3
- // Soft Layerbase blue. Truecolor terminals get the exact shade; others degrade.
4
- export const ACCENT = '#7c9cff'
5
-
6
- export function Header({ subtitle }: { subtitle?: string }) {
7
- return (
8
- <Box marginBottom={1}>
9
- <Text bold color={ACCENT}>
10
- {'◆'} Layerbase
11
- </Text>
12
- {subtitle ? <Text dimColor> {subtitle}</Text> : null}
13
- </Box>
14
- )
15
- }
@@ -1,13 +0,0 @@
1
- import { Box, Text } from 'ink'
2
- import Spinner from 'ink-spinner'
3
-
4
- export function Connecting({ label }: { label: string }) {
5
- return (
6
- <Box>
7
- <Text color="cyan">
8
- <Spinner type="dots" />
9
- </Text>
10
- <Text> {label}</Text>
11
- </Box>
12
- )
13
- }
package/src/ui/menu.tsx DELETED
@@ -1,56 +0,0 @@
1
- import { useState } from 'react'
2
- import { Box, Text, useInput } from 'ink'
3
- import { ACCENT } from './brand'
4
-
5
- export type MenuItem = { label: string; value: string; hint?: string }
6
-
7
- // A minimal arrow-key select list (no dependency), so `layerbase` with no
8
- // command lands on a menu the way spindb does.
9
- export function Menu({
10
- items,
11
- onSelect,
12
- }: {
13
- items: MenuItem[]
14
- onSelect: (value: string) => void
15
- }) {
16
- const [index, setIndex] = useState(0)
17
-
18
- useInput((input, key) => {
19
- if (key.upArrow) {
20
- setIndex((i) => (i === 0 ? items.length - 1 : i - 1))
21
- } else if (key.downArrow) {
22
- setIndex((i) => (i === items.length - 1 ? 0 : i + 1))
23
- } else if (key.return) {
24
- const item = items[index]
25
- if (item) onSelect(item.value)
26
- } else if (input === 'q') {
27
- onSelect('quit')
28
- }
29
- })
30
-
31
- // Pad labels so any hints line up in a column.
32
- const labelWidth = Math.max(...items.map((i) => i.label.length)) + 3
33
-
34
- return (
35
- <Box flexDirection="column">
36
- {items.map((item, i) => {
37
- const active = i === index
38
- const label = item.hint ? item.label.padEnd(labelWidth) : item.label
39
- return (
40
- <Box key={item.value}>
41
- <Text color={active ? ACCENT : undefined} bold={active}>
42
- {active ? '❯ ' : ' '}
43
- {label}
44
- </Text>
45
- {item.hint ? <Text dimColor>{item.hint}</Text> : null}
46
- </Box>
47
- )
48
- })}
49
- <Box marginTop={1}>
50
- <Text dimColor>
51
- Up/Down to move {'·'} Enter to select {'·'} q to quit
52
- </Text>
53
- </Box>
54
- </Box>
55
- )
56
- }
@@ -1,11 +0,0 @@
1
- import { Text, useApp, useInput } from 'ink'
2
-
3
- // A tiny gate between a hub action and returning to the menu, so the action's
4
- // output stays readable until the user is ready to move on.
5
- export function PressEnter() {
6
- const { exit } = useApp()
7
- useInput((_input, key) => {
8
- if (key.return) exit()
9
- })
10
- return <Text dimColor>Press Enter to return to the menu</Text>
11
- }
@@ -1,17 +0,0 @@
1
- import { useEffect } from 'react'
2
- import { Text, useApp } from 'ink'
3
-
4
- export function Unknown({ command }: { command: string }) {
5
- const { exit } = useApp()
6
-
7
- useEffect(() => {
8
- process.exitCode = 1
9
- exit()
10
- }, [exit])
11
-
12
- return (
13
- <Text color="red">
14
- Unknown command: {command}. Run `layerbase help` to see the commands.
15
- </Text>
16
- )
17
- }
package/tsconfig.json DELETED
@@ -1,17 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2022",
4
- "module": "ESNext",
5
- "moduleResolution": "Bundler",
6
- "jsx": "react-jsx",
7
- "lib": ["ES2023"],
8
- "strict": true,
9
- "noUncheckedIndexedAccess": true,
10
- "esModuleInterop": true,
11
- "skipLibCheck": true,
12
- "noEmit": true,
13
- "verbatimModuleSyntax": true,
14
- "types": ["node", "react"]
15
- },
16
- "include": ["src", "bin"]
17
- }