Skip to content

Commit 68adfc4

Browse files
committed
wip(cli): tests and changeset for the self-hosted deploy target
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017ihL2dLQEXWGsE2SZ3Qn5F
1 parent 0e3e03c commit 68adfc4

5 files changed

Lines changed: 486 additions & 1 deletion

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@objectstack/cli': patch
3+
---
4+
5+
feat(cli): `os deploy` and the `d` key in `os dev` deploy to a self-hosted runtime (Docker Community or Enterprise) that `os environments use-runtime` remembered; `os package install` falls back to it
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
**`os environments use-runtime <url> --token <key>`** (new) remembers a self-hosted runtime and an API key it issued, and makes it the deploy target. The key is tried on the runtime's install-local door first (`--no-verify` skips that); a rejected key, a runtime that does not serve install-local, or one that cannot be reached is refused and nothing is recorded. Both are stored in `~/.objectstack/cloud.json` (0600) as their own record beside the cloud session: `os cloud login` and `os cloud logout` keep it, and the key is only ever sent to that url. `os environments switch <id>` makes ObjectOS Cloud the deploy target again (the runtime stays remembered); `os environments use-runtime --forget` drops it.
11+
12+
**`os deploy`** with a runtime as the active target (and no `--env`) builds the app, asks the runtime's install-local dry run and prints the upgrade plan (declared `renamedFrom` renames included), then installs the build inline — no catalog publish and no `-dev` version — and reports it live from the runtime's answer. A refusal from the dry run or the install stops the deploy with exit 1 and the runtime's sentence; a runtime that does not serve install-local (one booted from a composed artifact) or that predates the dry run is named, with what to do, exit 1. `--confirm-access-upgrade <finding-set>` passes the access-upgrade confirmation through (and is refused when the target is ObjectOS Cloud). **The `d` key** names the remembered runtime and deploys there without asking for a cloud login.
13+
14+
**`os package install`** without `-u` / `$OS_RUNTIME_URL` installs into the remembered runtime, and without `-t` / `--email` uses its key — only when the url is that runtime's. With nothing remembered the default stays `http://localhost:3000`. Its 404 answer now names the composed-artifact case and what to do.

‎packages/cli/test/deploy.test.ts‎

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,3 +408,196 @@ describe('devVersion — a semver pre-release of the version the author wrote',
408408
expect(result.ok).toBe(false);
409409
});
410410
});
411+
412+
describe('os deploy — a self-hosted runtime as the active target (os environments use-runtime)', () => {
413+
const RUNTIME = 'http://runtime.test:8080';
414+
const KEY = 'osk_runtime_key';
415+
let home = '';
416+
let work = '';
417+
const previous: Record<string, string | undefined> = {};
418+
const prevCwd = process.cwd();
419+
let output: string[] = [];
420+
const RUNTIME_ENV = [...MANAGED_ENV, 'OS_RUNTIME_URL', 'OS_RUNTIME_TOKEN', 'OS_RUNTIME_EMAIL', 'OS_RUNTIME_PASSWORD'] as const;
421+
422+
beforeEach(async () => {
423+
home = await mkdtemp(join(tmpdir(), 'os-30888-deploy-home-'));
424+
work = await mkdtemp(join(tmpdir(), 'os-30888-deploy-work-'));
425+
await mkdir(join(home, '.objectstack'), { recursive: true });
426+
for (const key of ['HOME', 'USERPROFILE', ...RUNTIME_ENV]) previous[key] = process.env[key];
427+
process.env.HOME = home;
428+
process.env.USERPROFILE = home;
429+
for (const key of RUNTIME_ENV) delete process.env[key];
430+
// A cloud login AND a remembered runtime that is the active target: the runtime wins.
431+
await writeFile(join(home, '.objectstack', 'cloud.json'), JSON.stringify({
432+
url: CLOUD_PLANE, token: 'cloud_tok', createdAt: 'now',
433+
runtimeTarget: { url: RUNTIME, token: KEY, recordedAt: 'then' }, deployTarget: 'runtime',
434+
}));
435+
process.chdir(work);
436+
compileForDeploy.mockReset();
437+
compileForDeploy.mockImplementation((artifactPath: string) => {
438+
mkdirSync(dirname(artifactPath), { recursive: true });
439+
writeFileSync(artifactPath, JSON.stringify({ manifest: { id: 'com.acme.crm', name: 'Acme CRM', version: '1.2.0' }, objects: [] }));
440+
return 0;
441+
});
442+
output = [];
443+
const record = (...args: unknown[]) => { output.push(args.map(String).join(' ')); };
444+
vi.spyOn(console, 'log').mockImplementation(record);
445+
vi.spyOn(console, 'error').mockImplementation(record);
446+
});
447+
448+
afterEach(async () => {
449+
process.chdir(prevCwd);
450+
vi.unstubAllGlobals();
451+
vi.restoreAllMocks();
452+
for (const [key, value] of Object.entries(previous)) {
453+
if (value === undefined) delete process.env[key];
454+
else process.env[key] = value;
455+
}
456+
await rm(home, { recursive: true, force: true });
457+
await rm(work, { recursive: true, force: true });
458+
});
459+
460+
type Sent = { url: string; method: string; headers: Record<string, string>; body: any };
461+
type Answer = { status: number; body: unknown };
462+
const PLAN = {
463+
dryRun: true, manifestId: 'com.acme.crm', version: '1.2.0', installedVersion: '1.1.0',
464+
plan: { declaredRenames: [{ object: 'lead', from: 'phone', to: 'mobile' }] },
465+
environment: { columns: [{ object: 'lead', field: 'phone', rows: 3 }] },
466+
};
467+
const INSTALLED = { manifestId: 'com.acme.crm', version: '1.2.0', hotLoaded: true, installedAt: '2026-11-07T00:00:00.000Z' };
468+
const ok = (data: unknown): Answer => ({ status: 200, body: { success: true, data } });
469+
const refused = (status: number, code: string, message: string, details?: unknown): Answer =>
470+
({ status, body: { success: false, error: { code, message, ...(details ? { details } : {}) } } });
471+
472+
/** The runtime: the dry-run answer, then the install answer. Anything else is unexpected. */
473+
function stubRuntime(answers: { dryRun?: Answer; install?: Answer }): Sent[] {
474+
const sent: Sent[] = [];
475+
vi.stubGlobal('fetch', vi.fn(async (input: string, init: any = {}) => {
476+
const url = String(input);
477+
const body = typeof init.body === 'string' ? JSON.parse(init.body) : undefined;
478+
sent.push({ url, method: init.method ?? 'GET', headers: { ...(init.headers ?? {}) }, body });
479+
const answer = url === `${RUNTIME}/api/v1/marketplace/install-local` && init.method === 'POST'
480+
? (body?.dryRun ? answers.dryRun ?? ok(PLAN) : answers.install ?? ok(INSTALLED))
481+
: { status: 599, body: { success: false, error: { message: `unexpected ${init.method} ${url}` } } };
482+
return {
483+
ok: answer.status >= 200 && answer.status < 300,
484+
status: answer.status,
485+
statusText: String(answer.status),
486+
headers: { get: () => null },
487+
json: async () => answer.body,
488+
} as any;
489+
}));
490+
return sent;
491+
}
492+
493+
async function deploy(argv: string[] = []): Promise<number | undefined> {
494+
try {
495+
await Deploy.run(argv);
496+
return undefined;
497+
} catch (err: any) {
498+
const exit = err?.oclif?.exit ?? err?.exitCode;
499+
if (exit === undefined) throw err;
500+
return exit;
501+
}
502+
}
503+
const text = () => output.join('\n');
504+
505+
it('with no flags: builds, asks the dry run (plan printed), installs the build inline, and reports it live', async () => {
506+
const sent = stubRuntime({});
507+
508+
const exit = await deploy();
509+
510+
expect(exit, text()).toBeUndefined();
511+
expect(compileForDeploy).toHaveBeenCalledWith(join(work, 'dist', 'objectstack.json'));
512+
// Two calls, both to the remembered runtime with its key: the dry run, then the install. No cloud call.
513+
expect(sent.map((s) => [s.method, s.url, s.body?.dryRun === true])).toEqual([
514+
['POST', `${RUNTIME}/api/v1/marketplace/install-local`, true],
515+
['POST', `${RUNTIME}/api/v1/marketplace/install-local`, false],
516+
]);
517+
for (const s of sent) expect(s.headers.Authorization).toBe(`Bearer ${KEY}`);
518+
// Inline artifact, the manifest's own version: no catalog, no -dev suffix.
519+
expect(sent[1].body.manifest.id).toBe('com.acme.crm');
520+
expect(sent[1].body.manifest.version).toBe('1.2.0');
521+
expect(sent[1].body.packageId).toBeUndefined();
522+
// The plan is printed, declared rename included, before the install.
523+
expect(text()).toContain('Renames declared by renamedFrom');
524+
expect(text()).toContain('lead.phone → mobile — 3 row(s) hold a value');
525+
expect(text()).toContain(`Live: ${RUNTIME} now serves com.acme.crm 1.2.0.`);
526+
});
527+
528+
it('a refusal from the dry run stops the deploy before any install', async () => {
529+
const sent = stubRuntime({ dryRun: refused(422, 'VALIDATION_ERROR', "Package 'com.acme.crm' declares a job with no body.") });
530+
531+
const exit = await deploy();
532+
533+
expect(exit).toBe(1);
534+
expect(sent).toHaveLength(1);
535+
expect(sent[0].body.dryRun).toBe(true);
536+
expect(text()).toContain('Install failed (422 VALIDATION_ERROR)');
537+
});
538+
539+
it('a runtime that declines install-local (404, e.g. booted from a composed artifact) is named, exit 1', async () => {
540+
const sent = stubRuntime({ dryRun: { status: 404, body: { success: false, error: { message: 'Not Found' } } } });
541+
542+
const exit = await deploy();
543+
544+
expect(exit).toBe(1);
545+
expect(sent).toHaveLength(1);
546+
expect(text()).toContain(`${RUNTIME} does not serve install-local`);
547+
expect(text()).toContain('A runtime booted from a composed artifact takes no package installs');
548+
});
549+
550+
it('a runtime that predates the dry run is said so, exit 1, naming what to do', async () => {
551+
// It ignored `dryRun` and installed: the answer carries no `dryRun`.
552+
const sent = stubRuntime({ dryRun: ok(INSTALLED) });
553+
554+
const exit = await deploy();
555+
556+
expect(exit).toBe(1);
557+
expect(sent).toHaveLength(1);
558+
expect(text()).toContain('does not support a dry run');
559+
expect(text()).toContain('Upgrade the runtime to preview an upgrade before it is installed, then run `os deploy` again.');
560+
});
561+
562+
it("the install's refusal stops the deploy, and its retry names os deploy; the confirmation passes through", async () => {
563+
const accessRefusal = refused(409, 'ACCESS_UPGRADE_CONFIRMATION_REQUIRED', 'confirm', {
564+
findings: [{ describe: "permission set 'sales' would re-enable lead.delete" }], findingSet: 'fs_123',
565+
});
566+
let sent = stubRuntime({ install: accessRefusal });
567+
expect(await deploy()).toBe(1);
568+
expect(sent).toHaveLength(2);
569+
expect(text()).toContain('os deploy --confirm-access-upgrade fs_123');
570+
571+
vi.unstubAllGlobals();
572+
sent = stubRuntime({});
573+
expect(await deploy(['--confirm-access-upgrade', 'fs_123']), text()).toBeUndefined();
574+
expect(sent[0].body.confirmAccessUpgrade).toBeUndefined();
575+
expect(sent[1].body.confirmAccessUpgrade).toBe('fs_123');
576+
});
577+
578+
it('a package the running kernel could not load is not called live: exit 1', async () => {
579+
stubRuntime({ install: ok({ ...INSTALLED, hotLoaded: false, hotLoadError: 'boom' }) });
580+
581+
expect(await deploy()).toBe(1);
582+
expect(text()).toContain('it is not live: it loads when the runtime restarts');
583+
expect(text()).not.toContain('Live:');
584+
});
585+
586+
it('a failed build installs nothing', async () => {
587+
const sent = stubRuntime({});
588+
compileForDeploy.mockImplementation(() => 1);
589+
590+
expect(await deploy()).toBe(1);
591+
expect(sent).toHaveLength(0);
592+
expect(text()).toContain('Nothing was installed.');
593+
});
594+
595+
it('--confirm-access-upgrade is refused when the target is ObjectOS Cloud, before anything is sent', async () => {
596+
await writeFile(join(home, '.objectstack', 'cloud.json'), JSON.stringify({ url: CLOUD_PLANE, token: 'cloud_tok', createdAt: 'now' }));
597+
const sent = stubRuntime({});
598+
599+
expect(await deploy(['--confirm-access-upgrade', 'fs_123'])).toBe(1);
600+
expect(sent).toHaveLength(0);
601+
expect(compileForDeploy).not.toHaveBeenCalled();
602+
});
603+
});

‎packages/cli/test/dev-deploy-key.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,3 +157,34 @@ describe('os dev deploy key', () => {
157157
expect(dev).toMatch(/if \(!deployKey\) deployKey = startDevDeployKey\(binPath,/);
158158
});
159159
});
160+
161+
describe('os dev deploy key — a self-hosted runtime as the active target (#30888)', () => {
162+
it('names the runtime, and d runs `os deploy` with no cloud login asked for', async () => {
163+
const terminal = new FakeTerminal();
164+
const printed: string[] = [];
165+
const runDeploy = vi.fn(async () => 0);
166+
const runLogin = vi.fn(async () => 0);
167+
const handle = attachDeployKey({
168+
input: terminal,
169+
print: (line) => printed.push(line),
170+
isLoggedIn: async () => false,
171+
runDeploy,
172+
runLogin,
173+
runtimeTarget: async () => 'http://runtime.test:8080',
174+
onInterrupt: () => {},
175+
});
176+
await handle!.offer();
177+
expect(printed[0]).toBe(deployKeyHint(false, 'http://runtime.test:8080'));
178+
expect(printed[0]).toContain('to the self-hosted runtime http://runtime.test:8080');
179+
180+
terminal.press('d');
181+
await handle!.current;
182+
expect(runLogin).not.toHaveBeenCalled();
183+
expect(runDeploy).toHaveBeenCalledTimes(1);
184+
});
185+
186+
it('is wired to the remembered target in os dev', () => {
187+
const source = readFileSync(resolve(HERE, '../src/utils/dev-deploy-key.ts'), 'utf8');
188+
expect(source).toMatch(/runtimeTarget: async \(\) => \(await activeRuntimeTarget\(\)/);
189+
});
190+
});

0 commit comments

Comments
 (0)