Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/init-identity-from-login.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@reactivapp/cli': minor
---

`reactiv app init` no longer asks for an app name and no longer takes `--name`. The merchant slug from your login now names the folder, the package, the app shown in the shell and `appName` in `reactiv.conf.js`, next to the app UUID from the same login.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ reactiv --version

```bash
reactiv login # paste your API key at the hidden prompt
reactiv app init # asks for an app name, then installs dependencies
reactiv app init # scaffolds a folder named after your merchant and installs dependencies
cd <your-app-folder>
reactiv app run ios # pod install, Metro, build, launch on the booted simulator
```
Expand Down
5 changes: 2 additions & 3 deletions docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,11 @@ Prints the merchant and app UUID, the key label and holder, the key's expiry, th
Scaffolds a new project from the current `@reactivapp/app-template`.

```
reactiv app init [--name <app name>] [--path <dir>] [--bundle-id <id>] [--app-uuid <uuid>] [--skip-install] [--package-manager npm]
reactiv app init [--path <dir>] [--bundle-id <id>] [--app-uuid <uuid>] [--skip-install] [--package-manager npm]
```

| Flag | Effect |
| --- | --- |
| `--name` | The app name shown in the app. Prompted for when omitted. Any text except quotes, backslashes and newlines; it is not used for file or package names. |
| `--app-uuid` | Optional. The app UUID; defaults to the app your login is provisioned for (`reactiv whoami` shows it) and is refused when it differs. |
| `--path` | Parent directory to scaffold into. Default: the current directory. |
| `--bundle-id` | iOS bundle identifier. Default: `com.reactiv.<slug without dashes>`. |
Expand All @@ -56,7 +55,7 @@ reactiv app init [--name <app name>] [--path <dir>] [--bundle-id <id>] [--app-uu

What happens:

1. Your login decides the project identity: the merchant slug Reactiv provisioned for your key (lowercase letters, digits and dashes) becomes the folder name, the root package name and the default bundle identifier; the app UUID comes from the same login.
1. Your login decides the project identity, and nothing is asked: the merchant slug Reactiv provisioned for your key (lowercase letters, digits and dashes) becomes the folder name, the root package name, the app name in `reactiv.conf.js` and the shell, and the default bundle identifier; the app UUID comes from the same login.
2. The current platform version and its pinned `react` and `react-native` versions are read from the registry, and the template is downloaded with npm so the transcript shows where it came from.
3. The template is expanded into `<path>/<slug>`, which must not exist or must be empty. A `git init` follows, and the CLI refuses to continue if the scaffold's `.gitignore` does not ignore `.npmrc`.
4. Dependencies are installed in the root and in `app/` with install scripts turned off. The CLI tells you which packages declared one so you can run `npm rebuild` in `app/` if the native build needs it.
Expand Down
2 changes: 1 addition & 1 deletion docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ reactiv app init
cd <your-app-folder>
```

The CLI asks for an app name (the name shown in the app; any text without quotes, backslashes or newlines), takes the app UUID and merchant slug from your login, resolves the current platform version, downloads the app template and installs dependencies. The folder is named after the merchant slug, for example `acme`, and it has two parts:
The CLI asks nothing: it takes the merchant slug and app UUID from your login, resolves the current platform version, downloads the app template and installs dependencies. The folder, the package and the app name in the shell are all the merchant slug, for example `acme`. The project has two parts:

- **The root is your library.** This is what you submit. Your code lives in `src/`, and `package.json` declares the packages you add.
- **`app/` is the runnable shell.** It wraps your library in a real app so you can run it. It is never submitted, and the platform version it runs is pinned for you.
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ reactiv --version

```bash
reactiv login # paste your API key at the hidden prompt
reactiv app init # asks for an app name, then installs dependencies
reactiv app init # scaffolds a folder named after your merchant and installs dependencies
cd <your-app-folder>
reactiv app run ios # pod install, Metro, build, launch on the booted simulator
reactiv app submit --dry-run # every check, nothing published
Expand Down
26 changes: 3 additions & 23 deletions packages/cli/src/commands/app/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {execFileSync} from 'node:child_process'
import * as fs from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'
import * as readline from 'node:readline/promises'

import {createAuthContext, reportAuthError} from '../../lib/auth/context'
import {gitIgnoreState, gitProbeEnv, installRoots} from '../../lib/auth/npmrc'
Expand All @@ -13,16 +12,6 @@ import {APP_DIR, PLATFORM_PACKAGES, readManifest} from '../../lib/layout'
import {run} from '../../lib/npm'
import {defaultBundleIdentifier, expandedName, expandTemplate, isSlug} from '../../lib/scaffold'

const prompt = async (question: string, flagHint: string): Promise<string> => {
if (!process.stdin.isTTY) {
throw new Error(`missing required value — pass ${flagHint} (interactive prompt needs a TTY)`)
}
const rl = readline.createInterface({input: process.stdin, output: process.stdout})
const answer = await rl.question(question)
rl.close()
return answer.trim()
}

const assertNpmrcIgnored = (targetDir: string): void => {
for (const root of installRoots(targetDir)) {
const relative = path.relative(targetDir, path.join(root, '.npmrc'))
Expand All @@ -45,7 +34,6 @@ export class AppInit extends Command {
'Scaffold a new Reactiv Plus app project from @reactivapp/app-template for the merchant you are logged in as (platform version stamped from the registry)'

static override flags = {
name: Flags.string({description: 'app name shown in the app (any text without quotes, backslashes or newlines)'}),
'app-uuid': Flags.string({description: 'Reactiv app UUID; defaults to the app your login is provisioned for and is refused when it differs'}),
path: Flags.string({description: 'parent directory to scaffold into', default: '.'}),
'package-manager': Flags.string({description: 'package manager for the project', options: ['npm'], default: 'npm'}),
Expand All @@ -57,14 +45,6 @@ export class AppInit extends Command {
const {renderSuccess, renderInfo} = await import('@reactivapp/cli-ui')
const {flags} = await this.parse(AppInit)

const appName = flags.name ?? (await prompt('App name: ', '--name'))
if (!appName) this.error('app name is required (use --name)')
// The name is stamped into JSON and JS files — quotes/backslashes would
// corrupt the generated configs.
if (/["'\\\n]/.test(appName)) {
this.error('app name must not contain quotes, backslashes, or newlines')
}

const ctx = createAuthContext(this)
let identity: Identity
try {
Expand All @@ -73,7 +53,7 @@ export class AppInit extends Command {
return reportAuthError(this, error)
}
// The merchant the login is provisioned for decides the project identity:
// its slug is the folder and package name, its UUID the app.
// its slug is the folder, package and app name, its UUID the app.
const appSlug = identity.merchant.slug
if (!isSlug(appSlug)) {
this.error(`the merchant slug Reactiv provisioned for this key ("${appSlug}") is not a plain lowercase name, so it cannot name a folder or package — contact Reactiv`)
Expand Down Expand Up @@ -133,7 +113,7 @@ export class AppInit extends Command {
try {
for (const name of fs.readdirSync(templateDir)) createdEntries.add(expandedName(name))
fileCount = expandTemplate(templateDir, targetDir, {
appName,
appName: appSlug,
appSlug,
appUuid,
bundleIdentifier: flags['bundle-id'] ?? defaultBundleIdentifier(appSlug),
Expand Down Expand Up @@ -203,7 +183,7 @@ export class AppInit extends Command {
}

renderSuccess({
headline: `Scaffolded ${appName}`,
headline: `Scaffolded ${appSlug}`,
body: [
`${fileCount} files expanded to ${targetDir}`,
`library: package.json + src/ (what gets submitted); runnable shell: ${APP_DIR}/`,
Expand Down
24 changes: 12 additions & 12 deletions packages/cli/test/init-run.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,20 +53,20 @@ describe('app init and app run on the library layout', () => {
// oclif wraps long error lines behind a ' ›' gutter; join them back up.
const flat = (text: string): string => text.replace(/\s*›\s*/g, ' ').replace(/\s+/g, ' ')

const init = (name = 'Acme') =>
runCli(['app', 'init', '--name', name, '--app-uuid', MERCHANT.appUuid, '--path', workDir], {cwd: workDir, env})
const init = () =>
runCli(['app', 'init', '--app-uuid', MERCHANT.appUuid, '--path', workDir], {cwd: workDir, env})

const installs = (): string[] =>
readFileSync(shim.log, 'utf8').split('\n').filter(line => line.startsWith('install '))

it('takes the folder, package name and app UUID from the login, whatever the app name is', async () => {
const result = await runCli(['app', 'init', '--name', 'Acme Shop Deluxe', '--path', workDir], {cwd: workDir, env})
it('takes the folder, package name, app name and app UUID from the login, asking nothing', async () => {
const result = await runCli(['app', 'init', '--path', workDir], {cwd: workDir, env})
expect(result.code).toBe(0)
const project = join(workDir, 'acme')
expect(JSON.parse(readFileSync(join(project, 'package.json'), 'utf8')).name).toBe('acme')
const conf = readFileSync(join(project, 'reactiv.conf.js'), 'utf8')
expect(conf).toContain(`appUuid: '${MERCHANT.appUuid}'`)
expect(conf).toContain("appName: 'Acme Shop Deluxe'")
expect(conf).toContain("appName: 'acme'")
expect(result.stdout).toContain('cd acme')
})

Expand All @@ -77,15 +77,15 @@ describe('app init and app run on the library layout', () => {
'POST /v1/tokens': () => ({status: 200, body: tokenResponse({merchant: {...MERCHANT, slug: '../outside'}})}),
})
env = {...env, REACTIV_VENDING_API_URL: mock.url}
const result = await runCli(['app', 'init', '--name', 'Acme', '--path', workDir], {cwd: workDir, env})
const result = await runCli(['app', 'init', '--path', workDir], {cwd: workDir, env})
expect(result.code).not.toBe(0)
expect(flat(result.errorText)).toContain('is not a plain lowercase name')
expect(existsSync(join(workDir, '..', 'outside'))).toBe(false)
expect(mock.requests.filter(request => request.path === '/v1/tokens')).toEqual([])
})

it('refuses an --app-uuid that is not the app the login is provisioned for', async () => {
const result = await runCli(['app', 'init', '--name', 'Acme', '--app-uuid', '11111111-1111-1111-1111-111111111111', '--path', workDir], {cwd: workDir, env})
const result = await runCli(['app', 'init', '--app-uuid', '11111111-1111-1111-1111-111111111111', '--path', workDir], {cwd: workDir, env})
expect(result.code).not.toBe(0)
expect(flat(result.stderr)).toContain('is not the app your login is provisioned for')
expect(existsSync(join(workDir, 'acme'))).toBe(false)
Expand Down Expand Up @@ -117,18 +117,18 @@ describe('app init and app run on the library layout', () => {
}, 60_000)

it.each([
['React Native', 'react-native', 'the platform already uses'],
['TypeScript', 'typescript', 'the project itself installs'],
['Metro', 'metro', 'the project itself installs'],
])('refuses the app name %s, whose package name would shadow a package', async (name, slug, reason) => {
['react-native', 'the platform already uses'],
['typescript', 'the project itself installs'],
['metro', 'the project itself installs'],
])('refuses the merchant slug %s, whose package name would shadow a package', async (slug, reason) => {
// The slug comes from the login, so the mock merchant has to carry it.
await mock.close()
mock = await startMockVending({
'GET /v1/me': () => ({status: 200, body: meResponse({merchant: {...MERCHANT, slug}, label: `${slug}/jane.doe`})}),
'POST /v1/tokens': () => ({status: 200, body: tokenResponse({merchant: {...MERCHANT, slug}})}),
})
env = {...env, REACTIV_VENDING_API_URL: mock.url}
const result = await init(name)
const result = await init()
expect(result.code).not.toBe(0)
expect(flat(result.errorText)).toContain(reason)
expect(existsSync(join(workDir, slug))).toBe(false)
Expand Down
21 changes: 15 additions & 6 deletions packages/cli/test/stub-commands.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import {execFileSync} from 'node:child_process'
import {mkdtempSync, rmSync} from 'node:fs'
import {tmpdir} from 'node:os'
import {join} from 'node:path'
import {describe, expect, it} from 'vitest'

const binPath = join(__dirname, '..', 'bin', 'run')

const runCli = (args: string[]): {stdout: string; stderr: string; failed: boolean} => {
const runCli = (args: string[], env: NodeJS.ProcessEnv = process.env): {stdout: string; stderr: string; failed: boolean} => {
try {
const stdout = execFileSync('node', [binPath, ...args], {encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']})
const stdout = execFileSync('node', [binPath, ...args], {encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env})
return {stdout, stderr: '', failed: false}
} catch (error) {
const err = error as {stdout?: string; stderr?: string}
Expand All @@ -15,10 +17,17 @@ const runCli = (args: string[]): {stdout: string; stderr: string; failed: boolea
}

describe('topic commands', () => {
it('app init without flags and no TTY fails with an actionable message', () => {
const result = runCli(['app', 'init'])
expect(result.failed).toBe(true)
expect(result.stderr).toContain('--name')
it('app init without a login fails with an actionable message instead of prompting', () => {
const home = mkdtempSync(join(tmpdir(), 'reactiv-stub-'))
const env = {...process.env}
delete env.REACTIV_API_KEY
try {
const result = runCli(['app', 'init'], {...env, HOME: home, XDG_CONFIG_HOME: home, XDG_CACHE_HOME: home})
expect(result.failed).toBe(true)
expect(result.stderr).toContain('reactiv login')
} finally {
rmSync(home, {recursive: true, force: true})
}
})

it('app run ios outside a project fails with an actionable message', () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/test/upgrade.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ describe('app upgrade against a mock vending API and a fixture registry', () =>
publish(A)
transcript.length = 0
project = workDir
const init = await step(`scaffold at ${A}`, ['app', 'init', '--name', 'Acme', '--app-uuid', MERCHANT.appUuid, '--path', workDir])
const init = await step(`scaffold at ${A}`, ['app', 'init', '--app-uuid', MERCHANT.appUuid, '--path', workDir])
expect(init.code).toBe(0)
project = join(workDir, 'acme')
clearNpmLog()
Expand Down
Loading
Loading