The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Add app publishing to npm and private registries (#28019)
Weiko68cc640b4554
diff --git a/packages/twenty-cli/docs/commands.md b/packages/twenty-cli/docs/commands.mdindex 3bfbdd014b0..1af1d5e74f0 100644--- a/packages/twenty-cli/docs/commands.md+++ b/packages/twenty-cli/docs/commands.md@@ -576,6 +576,34 @@ Exit codes:| 6 | Conflict || 130 | Cancelled |+## Publish an app to npm++```sh+twenty app publish+twenty app publish --path ./apps/billing --tag beta --json+```++Builds and typechecks the app, packs that exact build, then publishes the package with public access. No Twenty remote or workspace authentication is required. Publishing to npm does not sync or install the app in a workspace.++Install npm and authenticate with the intended registry first. npm runs from the app directory, so its project/user configuration and environment credentials apply. `--tag` sets the npm dist-tag. GitHub Actions jobs with OIDC request provenance automatically; set `TWENTY_APP_PUBLISH_DISABLE_PROVENANCE=true` to opt out, for example when publishing from a private source repository.++Packing and publishing skip npm lifecycle scripts because the CLI already built the app. npm's package-file selection still applies. If `package.json` has a `files` field, it must include `manifest.json` and the generated app files; the command rejects an incomplete package before publication. npm excludes the root `yarn.lock` from packages. Temporary packages and build snapshots are removed after completion or failure.++Human mode displays npm output and supports interactive authentication when a terminal is available. JSON mode returns one CLI envelope and does not prompt; configure an automation token or npm’s `npm_config_otp` environment option before running it. Failed npm commands return `PUBLISH_FAILED` with the subprocess exit code and captured output. If publication is interrupted after sending the package, check the registry before retrying, since the version may already have been published.++### Publish to a private Twenty registry++```sh+twenty app publish --private --remote staging+twenty app publish --private --path ./apps/billing --json+```++`--private` publishes the same built package to the selected Twenty server registry instead of npm. It uses the normal saved remote or environment credentials, requests a tarball upload, sends the bytes directly to storage, then registers the uploaded app. npm is still needed for local packing, but npm registry credentials are not used and `--tag` is rejected. The server requires file-upload permission and `MARKETPLACE_APPS` permission on the target workspace.++Publishing registers a version; it does not install the app or directly sync the selected workspace. Publishing an update can trigger automatic upgrades in workspaces where the app is already installed with automatic upgrades enabled. The server enforces application ownership, version progression and engine compatibility. JSON results contain `target: "private"`, the selected server under `registry`, the registration and `installed: false`, indicating that this command did not request installation.++Failed uploads never trigger registration. If registration fails or is interrupted after sending the request, the app may already be registered. The error includes the phase, upload file ID and an `unknown` outcome; check the server registry before retrying. Temporary packages are cleaned up in either case.+## App translations```shdiff --git a/packages/twenty-cli/package.json b/packages/twenty-cli/package.jsonindex d8a49b51444..2df996f3c01 100644--- a/packages/twenty-cli/package.json+++ b/packages/twenty-cli/package.json@@ -30,6 +30,7 @@"@types/semver": "^7.5.8","cjs-module-lexer": "^2.2.0","commander": "^14.0.3",+ "execa": "^5.1.1","lodash.startcase": "^4.4.0","npm-pick-manifest": "^11.0.1","semver": "7.6.3",diff --git a/packages/twenty-cli/src/app/publish/parse-npm-pack-output-or-throw.ts b/packages/twenty-cli/src/app/publish/parse-npm-pack-output-or-throw.tsnew file mode 100644index 00000000000..d699e4dc69b--- /dev/null+++ b/packages/twenty-cli/src/app/publish/parse-npm-pack-output-or-throw.ts@@ -0,0 +1,61 @@+import { isArray, isNonEmptyString } from '@sniptt/guards';+import { basename } from 'node:path';+import { isPlainObject } from 'twenty-shared/utils';++import { CliError } from '@/output/cli-error';++type NpmPackOutput = {+ name: string;+ version: string;+ filename: string;+ files: { path: string }[];+};++export const parseNpmPackOutputOrThrow = (stdout: string): NpmPackOutput => {+ let result: unknown;++ try {+ result = JSON.parse(stdout);+ } catch (cause) {+ throw new CliError({+ code: 'PUBLISH_FAILED',+ message: 'npm pack returned invalid JSON.',+ cause,+ });+ }++ const packed = isArray(result) && result.length === 1 ? result[0] : undefined;++ if (+ !isPlainObject(packed) ||+ !isNonEmptyString(packed.name) ||+ !isNonEmptyString(packed.version) ||+ !isNonEmptyString(packed.filename) ||+ basename(packed.filename) !== packed.filename ||+ packed.filename.includes('\\') ||+ !packed.filename.endsWith('.tgz') ||+ !isArray(packed.files)+ ) {+ throw new CliError({+ code: 'PUBLISH_FAILED',+ message: 'npm pack returned an invalid package description.',+ });+ }++ const files = packed.files.map((file) => {+ if (!isPlainObject(file) || !isNonEmptyString(file.path)) {+ throw new CliError({+ code: 'PUBLISH_FAILED',+ message: 'npm pack returned an invalid package file.',+ });+ }+ return { path: file.path };+ });++ return {+ name: packed.name,+ version: packed.version,+ filename: packed.filename,+ files,+ };+};diff --git a/packages/twenty-cli/src/app/publish/publish-app-to-npm.ts b/packages/twenty-cli/src/app/publish/publish-app-to-npm.tsnew file mode 100644index 00000000000..0d7ff5e6253--- /dev/null+++ b/packages/twenty-cli/src/app/publish/publish-app-to-npm.ts@@ -0,0 +1,51 @@+import { isDefined } from 'twenty-shared/utils';++import { runNpmCommand } from '@/app/publish/run-npm-command';+import { type PackedApp } from '@/app/publish/types/packed-app.type';+import { type CommandContext } from '@/catalog/types/command-context.type';+import { isInteractionAllowed } from '@/program/is-interaction-allowed';++export const publishAppToNpm = async ({+ packedApp,+ appPath,+ tag,+ context,+}: {+ packedApp: PackedApp;+ appPath: string;+ tag?: string;+ context: Pick<CommandContext, 'options' | 'outputMode' | 'output' | 'signal'>;+}) => {+ const supportsProvenance =+ isDefined(process.env.ACTIONS_ID_TOKEN_REQUEST_URL) &&+ process.env.TWENTY_APP_PUBLISH_DISABLE_PROVENANCE !== 'true';++ context.output.progress(+ `Publishing ${packedApp.name}@${packedApp.version} to npm…`,+ );+ await runNpmCommand({+ args: [+ 'publish',+ packedApp.path,+ '--access',+ 'public',+ '--ignore-scripts',+ '--workspaces=false',+ ...(supportsProvenance ? ['--provenance'] : []),+ ...(isDefined(tag) ? ['--tag', tag] : []),+ ],+ appPath,+ signal: context.signal,+ canInteract: isInteractionAllowed(context),+ ...(context.outputMode === 'human'+ ? { onOutput: context.output.progress }+ : {}),+ });++ return {+ target: 'npm',+ name: packedApp.name,+ version: packedApp.version,+ ...(isDefined(tag) ? { tag } : {}),+ };+};diff --git a/packages/twenty-cli/src/app/publish/publish-app-to-server.ts b/packages/twenty-cli/src/app/publish/publish-app-to-server.tsnew file mode 100644index 00000000000..81c7aecc54f--- /dev/null+++ b/packages/twenty-cli/src/app/publish/publish-app-to-server.ts@@ -0,0 +1,143 @@+import { isNonEmptyString } from '@sniptt/guards';+import { openAsBlob } from 'node:fs';+import { stat } from 'node:fs/promises';+import { basename } from 'node:path';+import { isDefined, isPlainObject } from 'twenty-shared/utils';++import { putUploadFile } from '@/app/deployment/put-upload-file';+import { withPhaseDetails } from '@/app/deployment/with-phase-details';+import { type PackedApp } from '@/app/publish/types/packed-app.type';+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';+import { CliError } from '@/output/cli-error';+import { toCliError } from '@/output/to-cli-error';+import { toPublicTarget } from '@/target/to-public-target';+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';++type PrivatePublishPhase = 'prepare-upload' | 'upload' | 'register';++export const publishAppToServer = async ({+ packedApp,+ context: { target, signal, output },+}: {+ packedApp: PackedApp;+ context: Pick<TargetCommandContext, 'target' | 'signal' | 'output'>;+}) => {+ let phase: PrivatePublishPhase = 'prepare-upload';+ const completedPhases: PrivatePublishPhase[] = [];+ let fileId: string | undefined;++ try {+ signal.throwIfAborted();+ const { size } = await stat(packedApp.path);+ const client = createMetadataClient({ target, signal });+ const data = await client.mutation({+ __name: 'CreateAppTarballUpload',+ createFileUpload: {+ __args: {+ filename: basename(packedApp.path),+ size,+ fileFolder: 'AppTarball',+ },+ fileId: true,+ uploadUrl: true,+ contentType: true,+ },+ });+ const upload = data.createFileUpload;++ if (+ !isPlainObject(upload) ||+ !isNonEmptyString(upload.fileId) ||+ !isNonEmptyString(upload.uploadUrl) ||+ !isNonEmptyString(upload.contentType)+ ) {+ throw new CliError({+ code: 'INVALID_RESPONSE',+ message: 'The server returned an invalid tarball upload target.',+ });+ }++ fileId = upload.fileId;+ completedPhases.push(phase);+ phase = 'upload';+ output.progress(+ `Uploading ${packedApp.name}@${packedApp.version} to ${target.apiUrl}…`,+ );+ const status = await putUploadFile({+ uploadUrl: upload.uploadUrl,+ contentType: upload.contentType,+ bytes: await openAsBlob(packedApp.path),+ signal,+ });++ if (status < 200 || status >= 300) {+ throw new CliError({+ code: 'UPLOAD_FAILED',+ message: `File storage answered ${status}.`,+ });+ }++ completedPhases.push(phase);+ signal.throwIfAborted();+ output.progress('Registering the uploaded app…');+ phase = 'register';+ const result = await client.mutation({+ __name: 'CompleteAppTarballUpload',+ completeAppTarballUpload: {+ __args: { fileId },+ id: true,+ name: true,+ universalIdentifier: true,+ },+ });+ const registration = result.completeAppTarballUpload;++ if (+ !isPlainObject(registration) ||+ !isNonEmptyString(registration.id) ||+ !isNonEmptyString(registration.name) ||+ !isNonEmptyString(registration.universalIdentifier)+ ) {+ throw new CliError({+ code: 'INVALID_RESPONSE',+ message: 'The server did not return the published app registration.',+ });+ }++ completedPhases.push(phase);++ return {+ target: 'private',+ registry: toPublicTarget(target),+ name: packedApp.name,+ version: packedApp.version,+ registration,+ fileId,+ installed: false,+ };+ } catch (error) {+ const failure = withPhaseDetails({+ error: toCliError(error, signal),+ phase,+ completedPhases,+ outcome: phase === 'register' ? 'unknown' : 'not-published',+ hint:+ phase === 'register'+ ? 'The app may already be registered. Check the server registry before retrying; publishing does not install the app.'+ : 'Fix the problem, then run twenty app publish --private again to create a fresh upload.',+ });++ throw new CliError({+ cause: failure,+ code: failure.code,+ exitCode: failure.exitCode,+ message: failure.message,+ hint: failure.hint,+ details: {+ ...failure.details,+ ...(isDefined(fileId) ? { fileId } : {}),+ registry: toPublicTarget(target),+ },+ });+ }+};diff --git a/packages/twenty-cli/src/app/publish/run-npm-command.ts b/packages/twenty-cli/src/app/publish/run-npm-command.tsnew file mode 100644index 00000000000..5f69351928b--- /dev/null+++ b/packages/twenty-cli/src/app/publish/run-npm-command.ts@@ -0,0 +1,71 @@+import { isNonEmptyString } from '@sniptt/guards';+import execa from 'execa';+import { isDefined } from 'twenty-shared/utils';++import { CliError } from '@/output/cli-error';+import { createCancelledError } from '@/output/create-cancelled-error';++export const runNpmCommand = async ({+ args,+ appPath,+ signal,+ canInteract = false,+ onOutput,+}: {+ args: string[];+ appPath: string;+ signal: AbortSignal;+ canInteract?: boolean;+ onOutput?: (message: string) => void;+}) => {+ signal.throwIfAborted();++ const subprocess = execa('npm', args, {+ cwd: appPath,+ stdio: canInteract ? 'inherit' : ['ignore', 'pipe', 'pipe'],+ reject: false,+ maxBuffer: 4 * 1024 * 1024,+ });+ const cancel = () =>+ subprocess.kill('SIGTERM', { forceKillAfterTimeout: 1000 });++ signal.addEventListener('abort', cancel, { once: true });++ if (signal.aborted) {+ cancel();+ }++ try {+ const result = await subprocess;++ if (signal.aborted) {+ throw createCancelledError();+ }++ if (!canInteract && isDefined(onOutput)) {+ if (isNonEmptyString(result.stdout)) {+ onOutput(result.stdout);+ }+ if (isNonEmptyString(result.stderr)) {+ onOutput(result.stderr);+ }+ }++ if (result.failed) {+ throw new CliError({+ code: 'PUBLISH_FAILED',+ message: `npm ${args[0]} failed.`,+ hint: 'Check that npm is installed and your npm registry credentials and package version are valid.',+ details: {+ exitCode: result.exitCode,+ stdout: result.stdout?.slice(-16384) ?? '',+ stderr: result.stderr?.slice(-16384) ?? '',+ },+ });+ }++ return result.stdout ?? '';+ } finally {+ signal.removeEventListener('abort', cancel);+ }+};diff --git a/packages/twenty-cli/src/app/publish/types/packed-app.type.ts b/packages/twenty-cli/src/app/publish/types/packed-app.type.tsnew file mode 100644index 00000000000..0f6b781973f--- /dev/null+++ b/packages/twenty-cli/src/app/publish/types/packed-app.type.ts@@ -0,0 +1,5 @@+export type PackedApp = {+ path: string;+ name: string;+ version: string;+};diff --git a/packages/twenty-cli/src/app/publish/with-packed-app.ts b/packages/twenty-cli/src/app/publish/with-packed-app.tsnew file mode 100644index 00000000000..c1360007f01--- /dev/null+++ b/packages/twenty-cli/src/app/publish/with-packed-app.ts@@ -0,0 +1,89 @@+import { mkdtemp, rm } from 'node:fs/promises';+import { dirname, join } from 'node:path';++import { readSnapshotFile } from '@/app/deployment/read-snapshot-file';+import { resolveSnapshotDirectory } from '@/app/deployment/resolve-snapshot-directory';+import { parseNpmPackOutputOrThrow } from '@/app/publish/parse-npm-pack-output-or-throw';+import { runNpmCommand } from '@/app/publish/run-npm-command';+import { type PackedApp } from '@/app/publish/types/packed-app.type';+import { type ToolingBuild } from '@/app/types/tooling-result.type';+import { CliError } from '@/output/cli-error';+import { type Output } from '@/output/types/output.type';++export const withPackedApp = async <TResult>({+ appPath,+ build,+ signal,+ output,+ usePackage,+}: {+ appPath: string;+ build: ToolingBuild;+ signal: AbortSignal;+ output: Output;+ usePackage: (packedApp: PackedApp) => Promise<TResult>;+}): Promise<TResult> => {+ const snapshotDirectory = resolveSnapshotDirectory({ build, appPath });++ for (const artifact of build.files) {+ signal.throwIfAborted();+ await readSnapshotFile({ snapshotDirectory, artifact });+ }++ const packageDirectory = await mkdtemp(+ join(dirname(snapshotDirectory), 'package-'),+ );++ try {+ output.progress('Packing the built app…');+ const stdout = await runNpmCommand({+ args: [+ 'pack',+ snapshotDirectory,+ '--json',+ '--ignore-scripts',+ '--workspaces=false',+ '--pack-destination',+ packageDirectory,+ ],+ appPath,+ signal,+ });+ const packed = parseNpmPackOutputOrThrow(stdout);+ const includedPaths = new Set(packed.files.map((file) => file.path));+ const requiredPaths = [+ 'manifest.json',+ 'package.json',+ ...build.files+ .map((file) => file.path)+ .filter((path) => path !== 'yarn.lock'),+ ];+ const missingPaths = [...new Set(requiredPaths)].filter(+ (path) => !includedPaths.has(path),+ );++ if (missingPaths.length > 0) {+ throw new CliError({+ code: 'PUBLISH_FAILED',+ message: 'The npm package is missing files required by the built app.',+ hint: 'Update the files field in package.json to include the manifest and built files.',+ details: { missingPaths },+ });+ }++ signal.throwIfAborted();++ return await usePackage({+ path: join(packageDirectory, packed.filename),+ name: packed.name,+ version: packed.version,+ });+ } finally {+ await rm(packageDirectory, { recursive: true, force: true }).catch(() => {+ output.warn({+ code: 'PACKAGE_CLEANUP_FAILED',+ message: `Could not remove temporary package folder ${packageDirectory}.`,+ });+ });+ }+};diff --git a/packages/twenty-cli/src/catalog/command-catalog.ts b/packages/twenty-cli/src/catalog/command-catalog.tsindex 1c8d0b41724..8b062f5011b 100644--- a/packages/twenty-cli/src/catalog/command-catalog.ts+++ b/packages/twenty-cli/src/catalog/command-catalog.ts@@ -1,3 +1,4 @@+import { APP_PUBLISH_COMMAND_DEFINITION } from '@/commands/app/publish/app-publish.command-definition';import { APP_DEV_COMMAND_DEFINITION } from '@/commands/app/dev/app-dev.command-definition';import { APP_ADD_COMMAND_DEFINITION } from '@/commands/app/add/app-add.command-definition';import { APP_EXEC_COMMAND_DEFINITION } from '@/commands/app/exec/app-exec.command-definition';@@ -44,6 +45,7 @@ export const COMMAND_CATALOG: CommandDefinition[] = [APP_INIT_COMMAND_DEFINITION,APP_PLAN_COMMAND_DEFINITION,APP_PULL_COMMAND_DEFINITION,+ APP_PUBLISH_COMMAND_DEFINITION,APP_TRANSLATIONS_EXTRACT_COMMAND_DEFINITION,APP_TYPECHECK_COMMAND_DEFINITION,APP_UNINSTALL_COMMAND_DEFINITION,diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-publish.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-publish.spec.tsnew file mode 100644index 00000000000..d9e89b7fee7--- /dev/null+++ b/packages/twenty-cli/src/commands/app/__tests__/app-publish.spec.ts@@ -0,0 +1,595 @@+import { readGraphqlRequest } from '@/__tests__/utils/read-graphql-request';+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';+import execa from 'execa';+import { build as bundle } from 'esbuild';+import { createHash } from 'node:crypto';+import {+ access,+ chmod,+ mkdir,+ mkdtemp,+ readFile,+ realpath,+ rm,+ writeFile,+} from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { delimiter, dirname, join } from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ parseSingleJsonLine,+ runCliForTest,+} from '@/__tests__/utils/run-cli-for-test';+import { runAppPublishCommand } from '@/commands/app/publish/run-app-publish-command';+import { createOutput } from '@/output/create-output';+import { runAppBuild } from '@/app/run-app-operation';+import { type ToolingBuild } from '@/app/types/tooling-result.type';++vi.mock('@/app/run-app-operation', () => ({ runAppBuild: vi.fn() }));++const PACKAGE_FILES = {+ 'package.json': JSON.stringify({ name: '@test/billing', version: '1.2.3' }),+ 'manifest.json': JSON.stringify({+ application: { universalIdentifier: 'test-app' },+ }),+ 'src/main.mjs': 'export const main = () => 42;',+ 'yarn.lock': 'lockfile',+};++let root: string;+let appPath: string;+let snapshotDirectory: string;+let build: ToolingBuild;++const readInvocations = async () =>+ (await readFile(join(root, 'invocations.jsonl'), 'utf8').catch(() => ''))+ .trim()+ .split('\n')+ .filter(Boolean)+ .map((line) => JSON.parse(line));+const runPublish = async (args: string[] = []) => {+ const result = await runCliForTest([+ 'app',+ 'publish',+ '--path',+ appPath,+ ...args,+ '--json',+ ]);+ return { ...result, envelope: parseSingleJsonLine(result.stdout) };+};++// The fixture replaces npm on PATH, so these tests never publish a package.+const NPM_FIXTURE = String.raw`#!/usr/bin/env node+const fs = require('node:fs');+const path = require('node:path');+const args = process.argv.slice(2);+const root = process.env.PUBLISH_TEST_ROOT;+fs.appendFileSync(path.join(root, 'invocations.jsonl'), JSON.stringify({ args, cwd: process.cwd(), packageExists: args[0] === 'publish' ? fs.existsSync(args[1]) : null }) + '\n');+if (process.env.PUBLISH_TEST_FAIL === args[0]) {+ console.error('Registry refused this version');+ process.exit(9);+}+if (process.env.PUBLISH_TEST_TTY === 'true' && (!process.stdin.isTTY || !process.stdout.isTTY)) {+ console.error('EOTP: terminal input and output required');+ process.exit(9);+}+if (process.env.PUBLISH_TEST_HANG === args[0]) {+ process.on('SIGTERM', () => {});+ setInterval(() => {}, 1000);+} else if (args[0] === 'pack' && process.env.PUBLISH_TEST_PACK_OUTPUT) {+ console.log(process.env.PUBLISH_TEST_PACK_OUTPUT);+} else if (args[0] === 'pack') {+ const destination = args[args.indexOf('--pack-destination') + 1];+ const filename = 'test-billing-1.2.3.tgz';+ fs.writeFileSync(path.join(destination, filename), 'packed bytes');+ const files = ['package.json', 'manifest.json', 'src/main.mjs'].filter(file => file !== process.env.PUBLISH_TEST_OMIT);+ console.log(JSON.stringify([{ name: '@test/billing', version: '1.2.3', filename, files: files.map(path => ({ path })) }]));+} else {+ console.log('npm output must not corrupt the CLI JSON');+}+`;++describe.skipIf(process.platform === 'win32')('app publish', () => {+ beforeEach(async () => {+ root = await realpath(await mkdtemp(join(tmpdir(), 'twenty-publish-')));+ appPath = join(root, 'app with spaces');+ snapshotDirectory = join(appPath, '.twenty/cli/snapshots/build-1/files');+ await mkdir(join(root, 'bin'));+ const executable = join(root, 'bin/npm');+ await writeFile(executable, NPM_FIXTURE);+ await chmod(executable, 0o755);+ vi.stubEnv('PATH', `${join(root, 'bin')}${delimiter}${process.env.PATH}`);+ vi.stubEnv('PUBLISH_TEST_ROOT', root);+ vi.stubEnv('PUBLISH_TEST_FAIL', '');+ vi.stubEnv('PUBLISH_TEST_HANG', '');+ vi.stubEnv('PUBLISH_TEST_TTY', '');+ vi.stubEnv('PUBLISH_TEST_OMIT', '');+ vi.stubEnv('PUBLISH_TEST_PACK_OUTPUT', '');+ vi.stubEnv('ACTIONS_ID_TOKEN_REQUEST_URL', undefined);+ vi.stubEnv('TWENTY_APP_PUBLISH_DISABLE_PROVENANCE', undefined);+ vi.stubEnv('CI', 'true');+ vi.stubEnv('TWENTY_API_URL', '');+ vi.stubEnv('TWENTY_API_KEY', '');+ vi.stubEnv('TWENTY_CONFIG_HOME', join(root, 'config'));++ for (const [file, content] of Object.entries(PACKAGE_FILES)) {+ await mkdir(dirname(join(snapshotDirectory, file)), { recursive: true });+ await writeFile(join(snapshotDirectory, file), content);+ }+ build = {+ buildId: 'build-1',+ directory: snapshotDirectory,+ contentHash: 'hash',+ application: {+ name: '@test/billing',+ displayName: 'Billing',+ universalIdentifier: 'test-app',+ },+ manifestFormat: 'twenty-application',+ manifest: {},+ files: Object.entries(PACKAGE_FILES)+ .filter(([path]) => path !== 'manifest.json')+ .map(([path, content]) => ({+ path,+ sourcePath: path,+ role: 'source',+ size: Buffer.byteLength(content),+ sha256: createHash('sha256').update(content).digest('hex'),+ })),+ };+ vi.mocked(runAppBuild).mockReset();+ vi.mocked(runAppBuild).mockImplementation(async ({ useHeldBuild }) => {+ const result = {+ project: { path: appPath, name: '@test/billing' },+ sdk: { version: '1.0.0', packagePath: '' },+ data: build,+ diagnostics: [],+ durationMilliseconds: 1,+ };+ try {+ await useHeldBuild?.(result);+ return result;+ } finally {+ await rm(dirname(snapshotDirectory), { recursive: true, force: true });+ }+ });+ });++ afterEach(async () => {+ vi.unstubAllEnvs();+ vi.restoreAllMocks();+ await rm(root, { recursive: true, force: true });+ });++ it('publishes the held build with the tag, project npm configuration and clean JSON', async () => {+ const result = await runPublish(['--tag', 'beta']);+ expect(result.exitCode).toBe(0);+ expect(runAppBuild).toHaveBeenCalledExactlyOnceWith({+ context: expect.objectContaining({+ command: 'app publish',+ arguments: [],+ options: expect.objectContaining({ path: appPath, tag: 'beta' }),+ outputMode: 'json',+ output: expect.any(Object),+ signal: expect.any(AbortSignal),+ }),+ useHeldBuild: expect.any(Function),+ });+ expect(result.envelope.data).toMatchObject({+ target: 'npm',+ name: '@test/billing',+ version: '1.2.3',+ tag: 'beta',+ });+ expect(result.envelope).not.toHaveProperty('target');+ const invocations = await readInvocations();+ expect(invocations).toHaveLength(2);+ expect(invocations[0]).toMatchObject({+ cwd: appPath,+ args: [+ 'pack',+ snapshotDirectory,+ '--json',+ '--ignore-scripts',+ '--workspaces=false',+ '--pack-destination',+ expect.any(String),+ ],+ });+ expect(invocations[1]).toMatchObject({+ cwd: appPath,+ packageExists: true,+ args: [+ 'publish',+ expect.stringContaining('.tgz'),+ '--access',+ 'public',+ '--ignore-scripts',+ '--workspaces=false',+ '--tag',+ 'beta',+ ],+ });+ await expect(access(invocations[1].args[1])).rejects.toThrow();+ });++ it.each([true, false])(+ 'keeps the SDK provenance opt-out, disabled=%s',+ async (disabled) => {+ vi.stubEnv('ACTIONS_ID_TOKEN_REQUEST_URL', 'https://oidc.example.test');+ if (disabled) {+ vi.stubEnv('TWENTY_APP_PUBLISH_DISABLE_PROVENANCE', 'true');+ }+ expect((await runPublish()).exitCode).toBe(0);+ expect((await readInvocations())[1].args.includes('--provenance')).toBe(+ !disabled,+ );+ },+ );++ it.each([+ ['--tag', 'bad tag'],+ ['--remote', 'prod'],+ ])('rejects invalid options before building: %s', async (...args) => {+ const result = await runPublish(args);+ expect(result.exitCode).toBe(2);+ expect(result.envelope.error.code).toBe('INVALID_INPUT');+ expect(runAppBuild).not.toHaveBeenCalled();+ expect(await readInvocations()).toEqual([]);+ });++ it('does not invoke npm when the build fails', async () => {+ vi.mocked(runAppBuild).mockRejectedValueOnce(new Error('Build failed'));+ expect((await runPublish()).exitCode).toBe(1);+ expect(await readInvocations()).toEqual([]);+ });++ it.each([+ ['{invalid', 'npm pack returned invalid JSON.'],+ ['[]', 'npm pack returned an invalid package description.'],+ [+ JSON.stringify([+ {+ name: '@test/billing',+ version: '1.2.3',+ filename: '../outside.tgz',+ files: [],+ },+ ]),+ 'npm pack returned an invalid package description.',+ ],+ [+ JSON.stringify([+ {+ name: '@test/billing',+ version: '1.2.3',+ filename: 'billing.tgz',+ files: [{ path: 1 }],+ },+ ]),+ 'npm pack returned an invalid package file.',+ ],+ ])(+ 'rejects invalid npm pack output before publishing: %s',+ async (stdout, message) => {+ vi.stubEnv('PUBLISH_TEST_PACK_OUTPUT', stdout);+ const result = await runPublish();+ expect(result.exitCode).toBe(1);+ expect(result.envelope.error).toMatchObject({+ code: 'PUBLISH_FAILED',+ message,+ });+ const invocations = await readInvocations();+ expect(invocations).toHaveLength(1);+ await expect(access(invocations[0].args.at(-1))).rejects.toThrow();+ },+ );++ it.each(['manifest.json', 'src/main.mjs'])(+ 'refuses a package that excludes %s',+ async (file) => {+ vi.stubEnv('PUBLISH_TEST_OMIT', file);+ const result = await runPublish();+ expect(result.exitCode).toBe(1);+ expect(result.envelope.error).toMatchObject({+ code: 'PUBLISH_FAILED',+ details: { missingPaths: [file] },+ });+ const invocations = await readInvocations();+ expect(invocations).toHaveLength(1);+ await expect(access(invocations[0].args.at(-1))).rejects.toThrow();+ },+ );++ it.each(['pack', 'publish'])(+ 'reports npm %s failure and removes the temporary package',+ async (operation) => {+ vi.stubEnv('PUBLISH_TEST_FAIL', operation);+ const result = await runPublish();+ expect(result.exitCode).toBe(1);+ expect(result.envelope.error).toMatchObject({+ code: 'PUBLISH_FAILED',+ details: {+ exitCode: 9,+ stderr: expect.stringContaining('Registry refused'),+ },+ });+ const invocations = await readInvocations();+ expect(invocations).toHaveLength(operation === 'pack' ? 1 : 2);+ await expect(access(invocations[0].args.at(-1))).rejects.toThrow();+ },+ );++ it('cancels an unresponsive npm process and cleans the package', async () => {+ vi.stubEnv('PUBLISH_TEST_HANG', 'publish');+ const controller = new AbortController();+ const pending = runAppPublishCommand({+ command: 'app publish',+ arguments: [],+ options: { path: appPath },+ outputMode: 'json',+ output: createOutput({ mode: 'json', command: 'app publish' }),+ signal: controller.signal,+ }).catch((error: unknown) => error);+ await expect.poll(async () => (await readInvocations()).length).toBe(2);+ controller.abort();+ const result = await pending;+ expect(result).toMatchObject({ code: 'CANCELLED', exitCode: 130 });+ const invocations = await readInvocations();+ await expect(access(invocations[1].args[1])).rejects.toThrow();+ });++ it('preserves terminal input and output for npm two-factor prompts', async () => {+ vi.stubEnv('PUBLISH_TEST_TTY', 'true');+ const runner = join(root, 'run-npm.cjs');+ await bundle({+ stdin: {+ contents: `import { runNpmCommand } from './src/app/publish/run-npm-command';+ runNpmCommand({ args: ['publish', 'fixture.tgz'], appPath: ${JSON.stringify(appPath)}, signal: new AbortController().signal, canInteract: true }).catch(() => process.exit(1));`,+ resolveDir: process.cwd(),+ },+ outfile: runner,+ bundle: true,+ platform: 'node',+ format: 'cjs',+ logLevel: 'silent',+ });+ const args =+ process.platform === 'darwin'+ ? ['-q', '/dev/null', process.execPath, runner]+ : ['-qec', `'${process.execPath}' '${runner}'`, '/dev/null'];+ const { stdout } = await execa('script', args, {+ stdin: 'ignore',+ timeout: 10_000,+ });+ expect(stdout).toContain('npm output must not corrupt the CLI JSON');+ expect(stdout).not.toContain('EOTP');+ });++ it('reports a missing npm executable', async () => {+ vi.stubEnv('PATH', join(root, 'missing-bin'));+ const result = await runPublish();+ expect(result.exitCode).toBe(1);+ expect(result.envelope.error.code).toBe('PUBLISH_FAILED');+ expect(result.envelope.error.hint).toContain('npm is installed');+ });++ it('advertises npm publishing without requiring a Twenty target', async () => {+ const result = await runCliForTest(['commands', '--json']);+ expect(parseSingleJsonLine(result.stdout).data.commands).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: 'app publish',+ needsTarget: false,+ writes: true,+ }),+ ]),+ );+ });+ describe('private server registry', () => {+ let server: Awaited<ReturnType<typeof startTestServer>>;+ let failure: string | undefined;+ const fileId = '8ba383ca-7d8a-47b1-b41c-02c172d4d0dd';+ const registration = {+ id: 'registration-id',+ name: 'Billing',+ universalIdentifier: 'test-app',+ };++ beforeEach(async () => {+ failure = undefined;+ server = await startTestServer((request, response) => {+ if (request.method === 'PUT') {+ response.writeHead(+ failure === 'upload' ? 503 : failure === 'redirect' ? 302 : 200,+ failure === 'redirect'+ ? { location: `${server.url}/must-not-follow` }+ : {},+ );+ response.end();+ return;+ }+ const { query } = readGraphqlRequest(request);+ if (query.includes('createFileUpload')) {+ if (failure === 'reserve') {+ sendJson(response, 403, { message: 'Permission denied' });+ return;+ }+ sendJson(response, 200, {+ data: {+ createFileUpload:+ failure === 'invalid-target'+ ? { fileId }+ : {+ fileId,+ uploadUrl: `${server.url}/tarball`,+ contentType: 'application/gzip',+ },+ },+ });+ return;+ }+ if (query.includes('completeAppTarballUpload')) {+ if (failure === 'hold-complete') return;+ if (failure === 'complete') {+ sendJson(response, 200, {+ data: null,+ errors: [+ {+ message: 'Version already exists',+ extensions: { code: 'BAD_USER_INPUT' },+ },+ ],+ });+ return;+ }+ sendJson(response, 200, {+ data: {+ completeAppTarballUpload:+ failure === 'invalid-complete' ? null : registration,+ },+ });+ return;+ }+ sendJson(response, 500, { message: 'Unexpected operation' });+ });+ vi.stubEnv('TWENTY_API_URL', server.url);+ vi.stubEnv('TWENTY_API_KEY', 'test-api-key');+ });++ afterEach(async () => server.close());++ it('packs, uploads bytes without credentials, then registers without installing or publishing to npm', async () => {+ const result = await runPublish(['--private']);+ expect(result.exitCode).toBe(0);+ expect(result.envelope.data).toMatchObject({+ target: 'private',+ registry: { apiUrl: server.url },+ registration,+ fileId,+ installed: false,+ });+ expect(server.requests).toHaveLength(3);+ expect(readGraphqlRequest(server.requests[0]).arguments).toEqual({+ filename: 'test-billing-1.2.3.tgz',+ size: Buffer.byteLength('packed bytes'),+ fileFolder: 'AppTarball',+ });+ expect(server.requests[0].headers.authorization).toBe(+ 'Bearer test-api-key',+ );+ expect(server.requests[1]).toMatchObject({+ method: 'PUT',+ path: '/tarball',+ body: 'packed bytes',+ });+ expect(server.requests[1].headers.authorization).toBeUndefined();+ expect(server.requests[1].headers['content-type']).toBe(+ 'application/gzip',+ );+ expect(readGraphqlRequest(server.requests[2]).arguments).toEqual({+ fileId,+ });+ expect(server.requests[2].headers.authorization).toBe(+ 'Bearer test-api-key',+ );+ const invocations = await readInvocations();+ expect(invocations).toHaveLength(1);+ expect(invocations[0].args[0]).toBe('pack');+ await expect(access(invocations[0].args.at(-1))).rejects.toThrow();+ });++ it('refuses npm-only flags before building or contacting the target', async () => {+ const result = await runPublish(['--private', '--tag', 'beta']);+ expect(result.exitCode).toBe(2);+ expect(result.envelope.error.code).toBe('INVALID_INPUT');+ expect(runAppBuild).not.toHaveBeenCalled();+ expect(server.requests).toEqual([]);+ });++ it('requires a private target before building or packing', async () => {+ vi.stubEnv('TWENTY_API_KEY', '');+ const result = await runPublish(['--private']);+ expect(result.exitCode).not.toBe(0);+ expect(runAppBuild).not.toHaveBeenCalled();+ expect(await readInvocations()).toEqual([]);+ expect(server.requests).toEqual([]);+ });++ it('does not request an upload when packing fails', async () => {+ vi.stubEnv('PUBLISH_TEST_FAIL', 'pack');+ const result = await runPublish(['--private']);+ expect(result.exitCode).toBe(1);+ expect(result.envelope.error.code).toBe('PUBLISH_FAILED');+ expect(server.requests).toEqual([]);+ });++ it.each(['reserve', 'invalid-target', 'upload', 'redirect'])(+ 'does not register when %s fails',+ async (reason) => {+ failure = reason;+ const result = await runPublish(['--private']);+ expect(result.exitCode).not.toBe(0);+ expect(result.envelope.error.details.outcome).toBe('not-published');+ expect(server.requests).toHaveLength(+ reason === 'reserve' || reason === 'invalid-target' ? 1 : 2,+ );+ expect(+ server.requests.some(+ (request) =>+ request.method === 'POST' &&+ readGraphqlRequest(request).query.includes(+ 'completeAppTarballUpload',+ ),+ ),+ ).toBe(false);+ const invocations = await readInvocations();+ await expect(access(invocations[0].args.at(-1))).rejects.toThrow();+ },+ );++ it.each(['complete', 'invalid-complete'])(+ 'reports ambiguous registration failure for %s with the file ID',+ async (reason) => {+ failure = reason;+ const result = await runPublish(['--private']);+ expect(result.exitCode).toBe(1);+ expect(result.envelope.error.details).toMatchObject({+ phase: 'register',+ outcome: 'unknown',+ completedPhases: ['prepare-upload', 'upload'],+ fileId,+ });+ expect(server.requests).toHaveLength(3);+ expect(result.envelope.error.hint).toContain(+ 'Check the server registry',+ );+ const invocations = await readInvocations();+ await expect(access(invocations[0].args.at(-1))).rejects.toThrow();+ },+ );++ it('cancels a pending registration and preserves the uncertain outcome', async () => {+ failure = 'hold-complete';+ const controller = new AbortController();+ const pending = runAppPublishCommand({+ command: 'app publish',+ arguments: [],+ options: { path: appPath, private: true },+ outputMode: 'json',+ output: createOutput({ mode: 'json', command: 'app publish' }),+ signal: controller.signal,+ }).catch((error: unknown) => error);+ await expect.poll(() => server.requests.length).toBe(3);+ controller.abort();+ expect(await pending).toMatchObject({+ code: 'CANCELLED',+ details: { phase: 'register', outcome: 'unknown', fileId },+ });+ const invocations = await readInvocations();+ await expect(access(invocations[0].args.at(-1))).rejects.toThrow();+ });+ });+});diff --git a/packages/twenty-cli/src/commands/app/publish/app-publish.command-definition.ts b/packages/twenty-cli/src/commands/app/publish/app-publish.command-definition.tsnew file mode 100644index 00000000000..d7a362a5fb6--- /dev/null+++ b/packages/twenty-cli/src/commands/app/publish/app-publish.command-definition.ts@@ -0,0 +1,34 @@+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';++export const APP_PUBLISH_COMMAND_DEFINITION: LocalCommandDefinition = {+ path: ['app', 'publish'],+ description: 'Build and publish the app to npm or a private Twenty registry',+ options: [+ {+ flags: '--private',+ description:+ 'Publish to a Twenty server registry using --remote or the active target',+ },+ {+ flags: '--path <directory>',+ description:+ 'App directory (default: the app containing the current folder)',+ },+ {+ flags: '--tag <tag>',+ description: 'npm dist-tag, for example beta or next',+ },+ ],+ examples: [+ 'twenty app publish',+ 'twenty app publish --private --remote dev',+ 'twenty app publish --path ./apps/billing --tag beta --json',+ ],+ outputModes: ['human', 'json'],+ writes: true,+ needsProject: true,+ needsTarget: false,+ load: async () =>+ (await import('@/commands/app/publish/run-app-publish-command'))+ .runAppPublishCommand,+};diff --git a/packages/twenty-cli/src/commands/app/publish/run-app-publish-command.ts b/packages/twenty-cli/src/commands/app/publish/run-app-publish-command.tsnew file mode 100644index 00000000000..e6d9c6246a6--- /dev/null+++ b/packages/twenty-cli/src/commands/app/publish/run-app-publish-command.ts@@ -0,0 +1,96 @@+import { isDefined } from 'twenty-shared/utils';++import { publishAppToServer } from '@/app/publish/publish-app-to-server';+import { resolveCommandTarget } from '@/program/resolve-command-target';+import { publishAppToNpm } from '@/app/publish/publish-app-to-npm';+import { withPackedApp } from '@/app/publish/with-packed-app';+import { runAppBuild } from '@/app/run-app-operation';+import {+ readBooleanOption,+ readStringOption,+} from '@/catalog/read-command-values';+import { type CommandRun } from '@/catalog/types/command-run.type';+import { CliError } from '@/output/cli-error';+import { EXIT_CODE } from '@/output/constants/exit-code.constant';+import { formatSuccessLine } from '@/output/style';++export const runAppPublishCommand: CommandRun = async (context) => {+ const tag = readStringOption(context.options, 'tag');+ const isPrivate = readBooleanOption(context.options, 'private');++ if (isPrivate && isDefined(tag)) {+ throw new CliError({+ code: 'INVALID_INPUT',+ exitCode: EXIT_CODE.USAGE,+ message: '--tag only applies to npm publishing.',+ });+ }++ if (isDefined(tag) && !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(tag)) {+ throw new CliError({+ code: 'INVALID_INPUT',+ exitCode: EXIT_CODE.USAGE,+ message: `Invalid npm tag: ${tag}.`,+ });+ }++ if (!isPrivate && isDefined(readStringOption(context.options, 'remote'))) {+ throw new CliError({+ code: 'INVALID_INPUT',+ exitCode: EXIT_CODE.USAGE,+ message: 'npm publishing does not use a Twenty remote.',+ });+ }++ const target = isPrivate ? await resolveCommandTarget(context) : undefined;+ let published:+ | Awaited<ReturnType<typeof publishAppToNpm | typeof publishAppToServer>>+ | undefined;+ const { project, diagnostics } = await runAppBuild({+ context,+ useHeldBuild: async ({ project, data: build }) => {+ published = await withPackedApp({+ appPath: project.path,+ build,+ signal: context.signal,+ output: context.output,+ usePackage: async (packedApp) => {+ if (isDefined(target)) {+ return publishAppToServer({+ packedApp,+ context: {+ target,+ signal: context.signal,+ output: context.output,+ },+ });+ }+ return publishAppToNpm({+ packedApp,+ appPath: project.path,+ tag,+ context,+ });+ },+ });+ },+ });++ if (!isDefined(published)) {+ throw new CliError({+ code: 'PUBLISH_FAILED',+ message: 'The build did not provide a package to publish.',+ });+ }++ return {+ data: {+ app: { path: project.path, name: project.name },+ ...published,+ diagnostics,+ },+ human: formatSuccessLine(+ `Published ${published.name}@${published.version} to ${target?.apiUrl ?? 'npm'}${isPrivate ? '. Existing installations may upgrade automatically.' : ''}`,+ ),+ };+};diff --git a/packages/twenty-cli/src/output/types/cli-error-code.type.ts b/packages/twenty-cli/src/output/types/cli-error-code.type.tsindex e2d0912e148..7ac7b4b8b1e 100644--- a/packages/twenty-cli/src/output/types/cli-error-code.type.ts+++ b/packages/twenty-cli/src/output/types/cli-error-code.type.ts@@ -42,6 +42,7 @@ export type CliErrorCode =| 'PLAN_UNAVAILABLE'| 'PULL_BASE_RECORD_FAILED'| 'PULL_FAILED'+ | 'PUBLISH_FAILED'| 'REDIRECT_NOT_FOLLOWED'| 'REMOTE_EXISTS'| 'RESPONSE_LIMIT_EXCEEDED'diff --git a/yarn.lock b/yarn.lockindex 105713bf9d2..a90c97ff902 100644--- a/yarn.lock+++ b/yarn.lock@@ -51037,6 +51037,7 @@ __metadata:cjs-module-lexer: "npm:^2.2.0"commander: "npm:^14.0.3"esbuild: "npm:^0.28.1"+ execa: "npm:^5.1.1"lodash.startcase: "npm:^4.4.0"npm-pick-manifest: "npm:^11.0.1"semver: "npm:7.6.3"