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
10 changes: 6 additions & 4 deletions docs/recipes/02-existing-app-new-codebase.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,13 @@ stay in agreement the whole way.

| | What happens |
| --- | --- |
| `example-app` (your real app) | its **draft** is updated with whatever `app.json` says. Never published by `dev` — installed users see nothing change |
| `example-app-test-dev` | created if new, pointed at your tunnel, **published** — this is what you install |
| `example-app` (your real app) | left alone. `example-app` already exists (that's this recipe), so `dev` never writes to it — it only reads whatever draft/published manifest is already there to clone from |
| `example-app-test-dev` | created if new, gets `app.json` pushed to it **every restart**, pointed at your tunnel, **published** — this is what you install |

So editing `app.json` is safe to iterate on: it moves the prod app's draft, not its live version.
Publishing is a separate, deliberate step:
So editing `app.json` is safe to iterate on: every restart moves the *test* app, never the real
one. (The one exception: an app that doesn't exist in the registry yet gets its first draft
created this way — see recipe 01. Once it exists, `dev` never touches it again.) Publishing is a
separate, deliberate step, done at the real app on purpose:

```bash
peek apps push # push + publish (asks first, loudly, for a
Expand Down
8 changes: 4 additions & 4 deletions docs/recipes/03-existing-codebase-existing-app.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@ peek tunnel --port 4000
`peek tunnel` does the half only the CLI can do, and **starts nothing**:

1. opens a Cloudflare tunnel to `:4000` (and warns if nothing's listening there yet)
2. pushes `app.json` at `example-app` as a **draft** — production's live version is
untouched
3. creates/reuses the test app `example-app-test-dev`, points it at the tunnel and
**publishes it**
2. since `example-app` already exists (that's this recipe), leaves it alone entirely —
nothing is pushed at it
3. creates/reuses the test app `example-app-test-dev`, pushes `app.json` at **it** directly,
points it at the tunnel and **publishes it**
4. writes `PEEK_APP_URL` / `PEEK_APP_ID` / `PEEK_APP_SECRET` to `.env.local`
5. holds the tunnel open until Ctrl-C, and prints the install links

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@peektravel/app-cli",
"version": "1.1.1",
"version": "1.2.0",
"description": "CLI for scaffolding, developing, and publishing Peek apps",
"license": "MIT",
"author": "Peek Travel, Inc.",
Expand Down
42 changes: 3 additions & 39 deletions src/commands/apps/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { BaseCommand } from "../../base-command.js";
import { CLIError } from "../../errors.js";
import { ensureLoggedIn } from "../../lib/auth.js";
import { resolvePlatform, resolveStack } from "../../lib/axes.js";
import { pickExistingApp } from "../../lib/link.js";
import {
emptyManifest,
loadManifest,
Expand All @@ -18,13 +19,7 @@ import { PROJECT_FILE, readProject, writeLinkMetadata } from "../../lib/project.
import { confirmRegistryOverride } from "../../lib/registry.js";
import { STACK_VALUES } from "../../lib/stacks.js";
import { composeSkills, writeEnvLocal } from "../../lib/scaffold.js";
import {
announceSharedSecret,
findApp,
listApps,
tryExportManifest,
upsertManifest,
} from "../../lib/sync.js";
import { announceSharedSecret, findApp, tryExportManifest, upsertManifest } from "../../lib/sync.js";

// `peek apps link` is `peek init` with the scaffolding taken out. It exists for the codebase
// that already exists: an app written before the CLI did, or a checkout that has to push to
Expand Down Expand Up @@ -88,7 +83,7 @@ export default class Link extends BaseCommand {
await ensureLoggedIn();

await this.guard(async () => {
const appId = args["app-slug"] ?? (await this.pickApp(flags.debug));
const appId = args["app-slug"] ?? (await pickExistingApp(flags.debug));

// Fail before writing anything: a slug that isn't in the registry (or isn't this
// account's) would otherwise be recorded here and only blow up on the next `peek dev`.
Expand Down Expand Up @@ -194,37 +189,6 @@ export default class Link extends BaseCommand {
}
}

// No slug given: show what this account can publish to. There is no name in the
// publisher API — the slug IS the identifier a developer recognizes.
private async pickApp(debug: boolean): Promise<string> {
const apps = (await listApps({ excludeTestApps: true, debug })).sort((a, b) =>
a.appId.localeCompare(b.appId),
);

if (apps.length === 0) {
throw new CLIError(
"This account has no apps in the registry yet.",
"Run `peek init` to scaffold and create one.",
);
}

if (!process.stdin.isTTY) {
throw new CLIError("No app slug given.", "Pass the slug: `peek apps link <app-slug>`.");
}

const answer = await p.select({
message: "Which app does this directory publish to?",
options: apps.map((app) => ({ value: app.appId, label: app.appId })),
});

if (p.isCancel(answer)) {
p.cancel("Cancelled");
throw new CLIError("Aborted.");
}

return answer as string;
}

// Relinking is legitimate (an app renamed, a fork pointed at its own app) but it changes
// where every later push lands, so it isn't silent.
private async confirmRepoint(cwd: string, appId: string, force: boolean): Promise<void> {
Expand Down
35 changes: 14 additions & 21 deletions src/commands/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import * as p from "@clack/prompts";
import { BaseCommand } from "../base-command.js";
import { CLIError } from "../errors.js";
import { ensureLoggedIn } from "../lib/auth.js";
import { ensureProjectLinked } from "../lib/link.js";
import { detectPackageManager } from "../lib/pm.js";
import { confirmDerivedAppId } from "../lib/project.js";
import { confirmRegistryOverride } from "../lib/registry.js";
import { serveWithTunnel } from "../lib/serve.js";
import { checkTestIdentifier } from "../lib/sync.js";
Expand Down Expand Up @@ -39,17 +39,13 @@ export default class Dev extends BaseCommand {
}),
cmd: Flags.string({
description:
'Shell command that starts the app instead of "<pm> run dev" (e.g. "make serve"). It must listen on $PORT.',
'Shell command that starts the app instead of "./bin/server" or "<pm> run dev" (e.g. "make serve"). It must listen on $PORT.',
}),
domain: Flags.string({
description:
"Use a persistent named tunnel at <app>-dev.<domain> instead of an ephemeral quick tunnel. Requires a Cloudflare login and access to the domain's zone.",
}),
yes: Flags.boolean({
char: "y",
description: "Skip the confirmation shown when this directory isn't linked to an app yet",
default: false,
}),
debug: Flags.boolean({ description: "Print request URLs and raw responses", default: false }),
};

async run(): Promise<void> {
Expand All @@ -69,12 +65,16 @@ export default class Dev extends BaseCommand {
);
}

// package.json is only needed for the default `<pm> run dev`. With --cmd the app may not
// be a Node project at all, which is the whole point of the flag.
if (!flags.cmd && !existsSync(join(cwd, "package.json"))) {
// Not a Node project, or started by something other than an npm script: an executable
// ./bin/server (the Rails/Phoenix/Go convention) is used before falling back to
// "<pm> run dev", and only then do we need package.json at all.
const binServer = join(cwd, "bin/server");
const command = flags.cmd ?? (existsSync(binServer) ? binServer : undefined);

if (!command && !existsSync(join(cwd, "package.json"))) {
throw new CLIError(
"No package.json in the current directory.",
'Run this from inside the app, pass --cmd "<command>" if it isn\'t started by an npm script, or use `peek tunnel` if you start it yourself.',
"No package.json, no bin/server, and no --cmd in the current directory.",
'Run this from inside the app, add a `bin/server` executable, pass --cmd "<command>", or use `peek tunnel` if you start it yourself.',
);
}

Expand All @@ -84,14 +84,7 @@ export default class Dev extends BaseCommand {
if (!flags["no-sync"]) {
await ensureLoggedIn();
await confirmRegistryOverride();
if (!(await confirmDerivedAppId(cwd, {
appFlag: flags.app,
yes: flags.yes,
manifestFile: appFile,
}))) {
p.cancel("Aborted.");
this.exit(1);
}
await ensureProjectLinked(cwd, { appFlag: flags.app, manifestFile: appFile, debug: flags.debug });
}

await serveWithTunnel({
Expand All @@ -103,7 +96,7 @@ export default class Dev extends BaseCommand {
domain: flags.domain,
appId: flags.app,
testIdentifier: flags.test ? checkTestIdentifier(flags.test) : undefined,
command: flags.cmd,
command,
});
});
}
Expand Down
17 changes: 3 additions & 14 deletions src/commands/tunnel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import * as p from "@clack/prompts";
import { BaseCommand } from "../base-command.js";
import { CLIError } from "../errors.js";
import { ensureLoggedIn } from "../lib/auth.js";
import { ensureProjectLinked } from "../lib/link.js";
import { detectPackageManager } from "../lib/pm.js";
import { confirmDerivedAppId } from "../lib/project.js";
import { confirmRegistryOverride } from "../lib/registry.js";
import { serveWithTunnel } from "../lib/serve.js";
import { checkTestIdentifier } from "../lib/sync.js";
Expand Down Expand Up @@ -53,11 +53,7 @@ export default class Tunnel extends BaseCommand {
description:
"Use a persistent named tunnel at <app>-dev.<domain> instead of an ephemeral quick tunnel. Requires a Cloudflare login and access to the domain's zone.",
}),
yes: Flags.boolean({
char: "y",
description: "Skip the confirmation shown when this directory isn't linked to an app yet",
default: false,
}),
debug: Flags.boolean({ description: "Print request URLs and raw responses", default: false }),
};

async run(): Promise<void> {
Expand All @@ -83,14 +79,7 @@ export default class Tunnel extends BaseCommand {
if (!flags["no-sync"]) {
await ensureLoggedIn();
await confirmRegistryOverride();
if (!(await confirmDerivedAppId(cwd, {
appFlag: flags.app,
yes: flags.yes,
manifestFile: appFile,
}))) {
p.cancel("Aborted.");
this.exit(1);
}
await ensureProjectLinked(cwd, { appFlag: flags.app, manifestFile: appFile, debug: flags.debug });
}

await serveWithTunnel({
Expand Down
66 changes: 66 additions & 0 deletions src/lib/link.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import * as p from "@clack/prompts";
import { CLIError } from "../errors.js";
import { legacySlug, PROJECT_FILE, readProject, writeLinkMetadata } from "./project.js";
import { listApps } from "./sync.js";

// No slug given: show what this account can publish to and let them choose. There is no
// name in the publisher API — the slug IS the identifier a developer recognizes. Shared by
// `apps link` (asked explicitly) and `peek dev` / `peek tunnel` (asked because the directory
// isn't linked yet) — same question, two doors.
export async function pickExistingApp(debug = false): Promise<string> {
const apps = (await listApps({ excludeTestApps: true, debug })).sort((a, b) =>
a.appId.localeCompare(b.appId),
);

if (apps.length === 0) {
throw new CLIError(
"This account has no apps in the registry yet.",
"Run `peek init` to scaffold and create one, or `peek apps link <slug> --create` for a codebase that predates its app.",
);
}

if (!process.stdin.isTTY) {
throw new CLIError(
"No app slug given.",
"Pass the slug: `peek apps link <app-slug>`, or run this command with --app <slug>.",
);
}

const answer = await p.select({
message: "Which app does this directory publish to?",
options: apps.map((app) => ({ value: app.appId, label: app.appId })),
});

if (p.isCancel(answer)) {
p.cancel("Cancelled");
throw new CLIError("Aborted.");
}

return answer as string;
}

// The dev loop's own preflight: a directory with no project file isn't necessarily a Peek
// app — it may be an existing codebase someone just ran `peek dev` / `peek tunnel` in.
// Guessing a slug from package.json and silently creating that app would quietly make a
// second app beside the one they meant to develop against, and (for an app that already
// exists under a different slug) there is no local signal at all for which one that is — so
// this asks, every time, instead of guessing.
//
// A brand-new app is deliberately NOT offered here: `peek apps link <slug> --create` (or
// `peek init`) is the one path that creates an app, so there's exactly one place a developer
// has to look for "how do I register something new."
export async function ensureProjectLinked(
cwd: string,
options: { appFlag?: string; manifestFile?: string; debug?: boolean } = {},
): Promise<void> {
if (options.appFlag) return;
if (readProject(cwd).app?.id) return;
// A legacy manifest carries the app's own slug at .data.app.id and outranks anything we'd
// ask for — there is nothing to pick when the file already names its app.
if (legacySlug(options.manifestFile)) return;

p.log.warn(`This directory isn't linked to a registry app yet (no ${PROJECT_FILE}).`);
const appId = await pickExistingApp(options.debug);
writeLinkMetadata(cwd, appId);
p.log.step(`Linked to ${appId}.`);
}
38 changes: 1 addition & 37 deletions src/lib/project.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ export function targetAppId(
return resolveAppId(cwd, { legacyAppId: legacySlug(options.manifestFile) }).appId;
}

function legacySlug(file?: string): string | undefined {
export function legacySlug(file?: string): string | undefined {
if (!file) return undefined;
try {
return loadManifest(file).legacyAppId;
Expand All @@ -235,42 +235,6 @@ function legacySlug(file?: string): string | undefined {
}
}

// A directory with no project file isn't necessarily a Peek app — it may be an existing
// codebase someone ran `peek dev` / `peek tunnel` in. Left alone we'd derive a slug from
// package.json and CREATE that app in the registry, which quietly makes a second app beside
// the one they meant to develop against. Cheap to confirm, expensive to undo.
//
// Returns false when the developer declined, so the caller can stop before it opens a
// tunnel or starts a server.
export async function confirmDerivedAppId(
cwd: string,
options: { appFlag?: string; yes?: boolean; manifestFile?: string } = {},
): Promise<boolean> {
if (options.appFlag) return true;
if (readProject(cwd).app?.id) return true;
// A legacy manifest carries the app's own slug at .data.app.id and outranks anything we
// could derive, so there is nothing being guessed here — warning about package.json
// would name an app this run isn't going to touch.
if (legacySlug(options.manifestFile)) return true;

// No package.json name to derive from: resolveAppId raises its own (good) error later.
const derived = packageSlug(cwd);
if (!derived) return true;

p.log.warn(
[
`This directory isn't linked to a registry app yet (no ${PROJECT_FILE}).`,
`Continuing will develop against "${derived}", taken from package.json — and create that app if nothing has the slug.`,
"To use an app that already exists instead, run `peek apps link` or pass --app <slug>.",
].join("\n"),
);

if (options.yes || !process.stdin.isTTY) return true;

const answer = await p.confirm({ message: `Use "${derived}"?`, initialValue: false });
return !p.isCancel(answer) && answer === true;
}

// The generated test-app manifest the old dev loop kept beside app.json. It has no job
// now — a test app is a slug we push the same app.json at, not a second file — but its
// `.data.app.id` is the only record of which test app an existing project was using, so
Expand Down
Loading
Loading