The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(create-twenty-app): ship a lockfile so generated apps install under an age gate (#25879)
Félix Malfaitd92787601548
diff --git a/.github/workflows/ci-create-app-e2e-minimal.yaml b/.github/workflows/ci-create-app-e2e-minimal.yamlindex 9243e14e2e3..4c68afff516 100644--- a/.github/workflows/ci-create-app-e2e-minimal.yaml+++ b/.github/workflows/ci-create-app-e2e-minimal.yaml@@ -52,7 +52,17 @@ jobs:ports:- 6379:6379env:+ # All four get the CI version and are built. Only the three libraries are+ # published before the template lockfile is generated; create-twenty-app is+ # published after it, carrying that lockfile in its tarball.PUBLISHABLE_PACKAGES: twenty-client-sdk twenty-ui twenty-sdk create-twenty-app+ LIBRARY_PACKAGES: twenty-client-sdk twenty-ui twenty-sdk+ # Deliberately beyond any realistic policy rather than a value anyone would+ # set. With a working template lockfile nothing is resolved, so no gate of+ # any length applies and this number is inert; it only bites if the lockfile+ # stops shipping, and picking a large one means this job still catches that+ # however long a real consumer's gate happens to be.+ SCAFFOLD_AGE_GATE: 30dTWENTY_API_URL: http://localhost:3000TWENTY_API_KEY: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyMDIwMjAyMC1lNmI1LTQ2ODAtOGEzMi1iODIwOTczNzE1NmIiLCJ1c2VySWQiOiIyMDIwMjAyMC1lNmI1LTQ2ODAtOGEzMi1iODIwOTczNzE1NmIiLCJ3b3Jrc3BhY2VJZCI6IjIwMjAyMDIwLTFjMjUtNGQwMi1iZjI1LTZhZWNjZjdlYTQxOSIsIndvcmtzcGFjZU1lbWJlcklkIjoiMjAyMDIwMjAtNDYzZi00MzViLTgyOGMtMTA3ZTAwN2EyNzExIiwidXNlcldvcmtzcGFjZUlkIjoiMjAyMDIwMjAtMWU3Yy00M2Q5LWE1ZGItNjg1YjUwNjlkODE2IiwidHlwZSI6IkFDQ0VTUyIsImF1dGhQcm92aWRlciI6InBhc3N3b3JkIiwiaWF0IjoxNzUxMjgxNzA0LCJleHAiOjIwNjY4NTc3MDR9.HMGqCsVlOAPVUBhKSGlD1X86VoHKt4LIUtET3CGIdiksteps:@@ -89,19 +99,33 @@ jobs:sleep 1done- - name: Publish packages to local registry+ - name: Publish libraries to local registryrun: |yarn config set npmRegistryServer http://localhost:4873yarn config set unsafeHttpWhitelist --json '["localhost"]'yarn config set npmAuthToken ci-auth-token- for pkg in $PUBLISHABLE_PACKAGES; do+ for pkg in $LIBRARY_PACKAGES; docd packages/$pkgyarn npm publish --tag cicd ../..done+ - name: Generate template lockfile+ run: |+ npx nx run create-twenty-app:generate-template-lock \+ --releaseVersion=$CI_VERSION --registry=http://localhost:4873++ - name: Publish create-twenty-app to local registry+ run: |+ cd packages/create-twenty-app+ yarn npm publish --tag ci+- name: Scaffold app using published create-twenty-app+ env:+ YARN_NPM_MINIMAL_AGE_GATE: ${{ env.SCAFFOLD_AGE_GATE }}+ YARN_NPM_REGISTRY_SERVER: http://localhost:4873+ YARN_UNSAFE_HTTP_WHITELIST: localhostrun: |npm install -g create-twenty-app@$CI_VERSION --registry http://localhost:4873create-twenty-app --version@@ -109,12 +133,33 @@ jobs:cd /tmp/e2e-test-workspacecreate-twenty-app test-app --display-name "Test scaffolded app" --description "E2E test scaffolded app" --url http://localhost:3000- - name: Install scaffolded app dependencies+ - name: Verify scaffolded app ships a usable lockfile+ env:+ YARN_NPM_MINIMAL_AGE_GATE: ${{ env.SCAFFOLD_AGE_GATE }}+ YARN_NPM_REGISTRY_SERVER: http://localhost:4873+ YARN_UNSAFE_HTTP_WHITELIST: localhostrun: |cd /tmp/e2e-test-workspace/test-app- echo 'npmRegistryServer: "http://localhost:4873"' >> .yarnrc.yml- echo 'unsafeHttpWhitelist: ["localhost"]' >> .yarnrc.yml- YARN_ENABLE_IMMUTABLE_INSTALLS=false yarn install --no-immutable++ if [ ! -f yarn.lock ]; then+ echo "::error::The scaffolded app has no yarn.lock"+ exit 1+ fi++ if ! grep -q '^__metadata:' yarn.lock; then+ echo "::error::The scaffolded yarn.lock is not a Yarn 4 lockfile"+ exit 1+ fi++ for pkg in $LIBRARY_PACKAGES; do+ if ! grep -q "resolution: \"$pkg@npm:$CI_VERSION\"" yarn.lock; then+ echo "::error::$pkg@$CI_VERSION is missing from the scaffolded lockfile"+ exit 1+ fi+ done++ # What the generated project's own CI workflow runs.+ yarn install --immutable- name: Verify installed app versionsrun: |diff --git a/.yarnrc.yml b/.yarnrc.ymlindex 1696d1178df..9bf48aa8125 100644--- a/.yarnrc.yml+++ b/.yarnrc.yml@@ -13,6 +13,7 @@ npmMinimalAgeGate: 3dnpmPreapprovedPackages:- twenty-sdk- twenty-client-sdk+ - twenty-ui- "@esbuild/*@0.28.1"diff --git a/packages/create-twenty-app/package.json b/packages/create-twenty-app/package.jsonindex d13b1d4d272..9621cd6709c 100644--- a/packages/create-twenty-app/package.json+++ b/packages/create-twenty-app/package.json@@ -51,7 +51,8 @@"twenty-shared": "workspace:*","typescript": "^5.9.3","vite": "^8.0.0",- "vite-plugin-dts": "^4.5.4"+ "vite-plugin-dts": "^4.5.4",+ "yaml": "^2.9.0"},"engines": {"node": "^24.5.0",diff --git a/packages/create-twenty-app/project.json b/packages/create-twenty-app/project.jsonindex 2bd746b97d3..27a36f73ce6 100644--- a/packages/create-twenty-app/project.json+++ b/packages/create-twenty-app/project.json@@ -25,6 +25,14 @@}},"set-local-version": {},+ "generate-template-lock": {+ "executor": "nx:run-commands",+ "cache": false,+ "options": {+ "cwd": "packages/create-twenty-app",+ "command": "tsx src/scripts/generate-template-lock.ts --version={args.releaseVersion} --registry={args.registry}"+ }+ },"typecheck": {},"lint": {},"test": {diff --git a/packages/create-twenty-app/src/constants/template-packages.ts b/packages/create-twenty-app/src/constants/template-packages.tsnew file mode 100644index 00000000000..0dad93be8a6--- /dev/null+++ b/packages/create-twenty-app/src/constants/template-packages.ts@@ -0,0 +1,9 @@+// twenty-client-sdk, twenty-sdk and twenty-ui are released together at a single+// version, so the scaffolder pins all of them to its own version. Keep this list+// as the one source of truth: the template lockfile generator resolves exactly+// these names, and a mismatch between the two silently ships an unusable lockfile.+export const TEMPLATE_FIRST_PARTY_PACKAGES = [+ 'twenty-client-sdk',+ 'twenty-sdk',+ 'twenty-ui',+] as const;diff --git a/packages/create-twenty-app/src/constants/template/SETUP.md b/packages/create-twenty-app/src/constants/template/SETUP.mdindex b226d914479..c7a92a07d36 100644--- a/packages/create-twenty-app/src/constants/template/SETUP.md+++ b/packages/create-twenty-app/src/constants/template/SETUP.md@@ -16,6 +16,9 @@ Follow these steps to get your app running locally.yarn install```+ The committed `yarn.lock` pins exact, integrity-checked versions, so this+ resolves nothing from the registry.+2. Start the local Twenty server:```bashdiff --git a/packages/create-twenty-app/src/constants/template/yarn.lock b/packages/create-twenty-app/src/constants/template/yarn.lockdeleted file mode 100644index 4a5801883d1..00000000000--- a/packages/create-twenty-app/src/constants/template/yarn.lock+++ /dev/null@@ -1,2 +0,0 @@-# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.-# yarn lockfile v1diff --git a/packages/create-twenty-app/src/scripts/generate-template-lock.ts b/packages/create-twenty-app/src/scripts/generate-template-lock.tsnew file mode 100644index 00000000000..9204977b46f--- /dev/null+++ b/packages/create-twenty-app/src/scripts/generate-template-lock.ts@@ -0,0 +1,255 @@+// Generates the yarn.lock shipped inside the scaffold template.+//+// Without it, a generated project resolves every dependency from scratch on its+// first install, which fails outright when the user's package manager enforces a+// minimum release age (Yarn's npmMinimalAgeGate, pnpm's minimumReleaseAge, npm's+// min-release-age): the first-party packages are only minutes old at that point,+// and an exact pin leaves the resolver no older candidate to fall back to. A+// lockfile removes the resolution step entirely, so the gate never applies — and+// unlike loosening the pins or disabling the gate, it leaves the user's policy+// in force for every dependency they add later.+//+// Run this AFTER `nx build create-twenty-app` and AFTER the libraries are live on+// the registry, then publish; the publish workflow in twentyhq/twenty-infra runs+// it in that order.+import { execFileSync } from 'child_process';+import * as fs from 'fs-extra';+import { tmpdir } from 'os';+import { basename, dirname, join, resolve } from 'path';++import { isDefined } from 'twenty-shared/utils';++import { TEMPLATE_FIRST_PARTY_PACKAGES } from '@/constants/template-packages';+import createTwentyAppPackageJson from 'package.json';++const PACKAGE_ROOT = resolve(__dirname, '..', '..');+const REPO_ROOT = resolve(PACKAGE_ROOT, '..', '..');+const TEMPLATE_MANIFEST_PATH = join(+ PACKAGE_ROOT,+ 'src/constants/template/package.json',+);+const DEFAULT_OUTPUT_PATH = join(+ PACKAGE_ROOT,+ 'dist/constants/template/yarn.lock',+);+const PUBLIC_REGISTRY = 'https://registry.npmjs.org';++// Matches the monorepo's own npmMinimalAgeGate. Stated explicitly because nothing+// is inherited here: the lockfile is resolved in a temp directory outside the+// repo, with YARN_* stripped, so the effective gate would otherwise be zero.+const RELEASE_MINIMAL_AGE_GATE = '3d';++type Options = {+ version: string;+ registry: string;+ outputPath: string;+};++const parseOptions = (argv: string[]): Options => {+ const read = (name: string) => {+ const prefix = `--${name}=`;+ const flag = argv.find((argument) => argument.startsWith(prefix));+ const value = flag?.slice(prefix.length);++ // nx interpolates an unsupplied {args.foo} to an empty string.+ return value === '' ? undefined : value;+ };++ return {+ version: read('version') ?? createTwentyAppPackageJson.version,+ registry: (read('registry') ?? PUBLIC_REGISTRY).replace(/\/$/, ''),+ outputPath: read('out') ?? DEFAULT_OUTPUT_PATH,+ };+};++// The generated project runs the Yarn its package.json pins. Generating the+// lockfile with a different Yarn can produce a lockfile that release pins reject+// with YN0028 on the user's first CI run, so refuse to guess.+const resolveYarnBinary = (templatePackageManager: string) => {+ const yarnrc = fs.readFileSync(join(REPO_ROOT, '.yarnrc.yml'), 'utf8');+ const yarnPath = /^yarnPath:\s*(.+)$/m.exec(yarnrc)?.[1]?.trim();++ if (!isDefined(yarnPath)) {+ throw new Error('No yarnPath found in the monorepo .yarnrc.yml');+ }++ const repoYarnVersion = /yarn-(.+)\.cjs$/.exec(basename(yarnPath))?.[1];+ const templateYarnVersion = templatePackageManager.replace(/^yarn@/, '');++ if (repoYarnVersion !== templateYarnVersion) {+ throw new Error(+ `The scaffold template pins yarn@${templateYarnVersion} but the monorepo runs yarn ${repoYarnVersion}. ` ++ 'Align them before generating the template lockfile.',+ );+ }++ return join(REPO_ROOT, yarnPath);+};++const buildTemplateManifest = (version: string) => {+ const manifest = fs.readJsonSync(TEMPLATE_MANIFEST_PATH);++ for (const packageName of TEMPLATE_FIRST_PARTY_PACKAGES) {+ manifest.devDependencies[packageName] = version;+ }++ return manifest;+};++const buildYarnrc = ({+ registry,+ version,+}: {+ registry: string;+ version: string;+}) => {+ const { protocol, hostname } = new URL(registry);++ return [+ 'nodeLinker: node-modules',+ 'enableTelemetry: false',+ 'enableScripts: false',+ `npmRegistryServer: "${registry}"`,+ // Yarn refuses plain HTTP unless the host is whitelisted by name, so take it+ // from the registry rather than assuming localhost.+ ...(protocol === 'http:'+ ? ['unsafeHttpWhitelist:', ` - ${hostname}`]+ : []),+ // Scaffolded projects install this lockfile without re-resolving, which is+ // exactly what lets them satisfy a consumer's age gate -- and equally what+ // stops that gate from ever inspecting these versions. This resolution is+ // therefore the only point at which an age gate applies to the tree a+ // generated project receives, so hold one here, and waive it for nothing+ // beyond the exact first-party versions this release is publishing.+ `npmMinimalAgeGate: ${RELEASE_MINIMAL_AGE_GATE}`,+ 'npmPreapprovedPackages:',+ ...TEMPLATE_FIRST_PARTY_PACKAGES.map((name) => ` - "${name}@${version}"`),+ '',+ ].join('\n');+};++const assertResolvedWithIntegrity = ({+ lockfile,+ packageName,+ version,+}: {+ lockfile: string;+ packageName: string;+ version: string;+}) => {+ // Entry keys merge when several descriptors share one resolution+ // ("pkg@npm:1.0.0, pkg@npm:^1.0.0":), so match the resolution line instead.+ const resolution = `resolution: "${packageName}@npm:${version}"`;+ const resolutionIndex = lockfile.indexOf(resolution);++ if (resolutionIndex === -1) {+ throw new Error(+ `${packageName}@${version} is missing from the generated lockfile. Is it published yet?`,+ );+ }++ const entryEnd = lockfile.indexOf('\n\n', resolutionIndex);+ const entry = lockfile.slice(+ resolutionIndex,+ entryEnd === -1 ? undefined : entryEnd,+ );++ if (!entry.includes('checksum:')) {+ throw new Error(+ `${packageName}@${version} resolved without an integrity checksum.`,+ );+ }+};++// A registry serving tarballs from non-conventional URLs makes Yarn pin each+// entry to that exact host via __archiveUrl, which would not resolve for anyone+// else. Only the public registry produces a lockfile we can ship.+const assertNoRegistryPinning = ({+ lockfile,+ registry,+}: {+ lockfile: string;+ registry: string;+}) => {+ if (registry !== PUBLIC_REGISTRY) {+ // The release workflow always regenerates against the public registry right+ // before publishing, so a lockfile built here is only ever local scaffolding.+ // Say so out loud rather than passing silently.+ console.warn(+ `Generated against ${registry}, not ${PUBLIC_REGISTRY}: this lockfile is for local testing and must not be published.`,+ );++ return;+ }++ if (lockfile.includes('__archiveUrl')) {+ throw new Error(+ 'The generated lockfile pins entries to a specific registry host. Regenerate it against the public registry.',+ );+ }+};++const generateTemplateLock = async ({+ version,+ registry,+ outputPath,+}: Options) => {+ const manifest = buildTemplateManifest(version);+ const yarnBinary = resolveYarnBinary(manifest.packageManager);+ const workingDirectory = await fs.mkdtemp(+ join(tmpdir(), 'twenty-template-lock-'),+ );++ try {+ await fs.writeJson(join(workingDirectory, 'package.json'), manifest, {+ spaces: 2,+ });+ await fs.writeFile(+ join(workingDirectory, '.yarnrc.yml'),+ buildYarnrc({ registry, version }),+ );++ // YARN_* variables outrank the .yarnrc.yml written above, so a registry or+ // gate exported by the surrounding CI job would silently change the result.+ const environment = Object.fromEntries(+ Object.entries(process.env).filter(([key]) => !key.startsWith('YARN_')),+ );++ execFileSync(+ process.execPath,+ [yarnBinary, 'install', '--mode=update-lockfile'],+ { cwd: workingDirectory, stdio: 'inherit', env: environment },+ );++ const lockfile = await fs.readFile(+ join(workingDirectory, 'yarn.lock'),+ 'utf8',+ );++ for (const packageName of TEMPLATE_FIRST_PARTY_PACKAGES) {+ assertResolvedWithIntegrity({ lockfile, packageName, version });+ }++ assertNoRegistryPinning({ lockfile, registry });++ await fs.ensureDir(dirname(outputPath));+ await fs.writeFile(outputPath, lockfile);++ const resolutionCount = lockfile.match(/^ {2}resolution:/gm)?.length ?? 0;++ console.log(+ `Wrote ${outputPath} (${resolutionCount} resolutions, ${TEMPLATE_FIRST_PARTY_PACKAGES.join(', ')} @ ${version})`,+ );+ } finally {+ await fs.remove(workingDirectory);+ }+};++generateTemplateLock(parseOptions(process.argv.slice(2))).catch(+ (error: unknown) => {+ console.error(+ `Failed to generate the template lockfile: ${error instanceof Error ? error.message : error}`,+ );+ process.exit(1);+ },+);diff --git a/packages/create-twenty-app/src/utils/__tests__/install.spec.ts b/packages/create-twenty-app/src/utils/__tests__/install.spec.tsnew file mode 100644index 00000000000..9ac28e98a04--- /dev/null+++ b/packages/create-twenty-app/src/utils/__tests__/install.spec.ts@@ -0,0 +1,211 @@+import { parse } from 'yaml';++import { install } from '@/utils/install';++type ExecCallback = (error: Error | null, stdout?: string) => void;++jest.mock('child_process', () => ({ exec: jest.fn() }));++// node's `exec` is overloaded and its widest overload does not accept this+// callback shape, so take the mock from the module registry under the shape the+// promisified call actually uses, rather than casting the imported binding.+const { exec: mockExec } = jest.requireMock<{+ exec: jest.Mock<void, [string, unknown, ExecCallback]>;+}>('child_process');++type CommandOutcome = { stdout?: string; stderr?: string; fails?: boolean };++const mockCommands = (outcomes: Record<string, CommandOutcome>) => {+ mockExec.mockImplementation(+ (+ command: string,+ _options: unknown,+ callback: (error: Error | null, stdout?: string) => void,+ ) => {+ const outcome =+ Object.entries(outcomes).find(([prefix]) =>+ command.startsWith(prefix),+ )?.[1] ?? {};++ if (outcome.fails !== true) {+ callback(null, outcome.stdout ?? '');+ return;+ }++ const error = Object.assign(new Error(`Command failed: ${command}`), {+ stdout: outcome.stdout ?? '',+ stderr: outcome.stderr ?? '',+ });++ callback(error);+ },+ );+};++const quarantineOutput = ({+ descriptor,+ selector,+}: {+ descriptor: string;+ selector: string;+}) =>+ `➤ YN0016: │ ${descriptor}@npm:${selector}: All versions satisfying "${selector}" are quarantined`;++const APP_DIRECTORY = '/tmp/some-scaffolded-app';++// The remediation is YAML the reader pastes into .yarnrc.yml, so assert it parses+// rather than that it reads correctly: a scoped descriptor left unquoted looks+// right in a substring check and is a YAML error in the file.+const parseSuggestedYarnrc = (message: string) => {+ const lines = message.split('\n');+ const blockStart = lines.findIndex(+ (line) => line.trim() === 'npmPreapprovedPackages:',+ );++ if (blockStart === -1) {+ throw new Error(`No npmPreapprovedPackages block in message:\n${message}`);+ }++ const block: string[] = [];++ for (const line of lines.slice(blockStart)) {+ if (line.trim().length === 0) {+ break;+ }++ block.push(line.slice(' '.length));+ }++ const parsed: { npmPreapprovedPackages: string[] } = parse(block.join('\n'));++ return parsed;+};++const installAndCatch = () =>+ install(APP_DIRECTORY).then(+ () => '',+ (error: Error) => error.message,+ );++describe('install', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ jest.spyOn(console, 'warn').mockImplementation(() => undefined);+ });++ afterEach(() => {+ jest.restoreAllMocks();+ });++ it('installs without immutable mode so the template lockfile can be finalised', async () => {+ mockCommands({});++ await install(APP_DIRECTORY);++ expect(mockExec).toHaveBeenCalledWith(+ 'yarn install --no-immutable',+ { cwd: APP_DIRECTORY },+ expect.any(Function),+ );+ });++ it('reports the failure instead of leaving a project without dependencies', async () => {+ mockCommands({+ 'yarn install': { fails: true, stdout: 'YN0001: Something exploded' },+ });++ await expect(install(APP_DIRECTORY)).rejects.toThrow(+ /Dependency installation failed/,+ );+ });++ it('says how to recover, since the scaffolded project itself is intact', async () => {+ mockCommands({+ 'yarn install': { fails: true, stdout: 'YN0001: Something exploded' },+ });++ const message = await installAndCatch();++ expect(message).toContain('YN0001: Something exploded');+ expect(message).toContain('run `yarn install` there');+ });++ it('names the packages the gate actually quarantined', async () => {+ mockCommands({+ 'yarn install': {+ fails: true,+ stdout: quarantineOutput({+ descriptor: 'twenty-ui',+ selector: '2.41.0',+ }),+ },+ });++ const message = await installAndCatch();++ expect(message).toContain('minimum');+ expect(message).toContain(APP_DIRECTORY);+ expect(parseSuggestedYarnrc(message)).toEqual({+ npmPreapprovedPackages: ['[email protected]'],+ });+ // Never advise lowering the gate itself.+ expect(message).not.toContain('npmMinimalAgeGate');+ });++ it('waives the third-party package Yarn named, not the first-party ones', async () => {+ mockCommands({+ 'yarn install': {+ fails: true,+ stdout: quarantineOutput({+ descriptor: '@scope/some-tool',+ selector: '^1.2.3',+ }),+ },+ });++ const message = await installAndCatch();++ expect(parseSuggestedYarnrc(message)).toEqual({+ npmPreapprovedPackages: ['@scope/some-tool@^1.2.3'],+ });+ expect(message).not.toContain('twenty-ui');+ expect(message).not.toContain('twenty-sdk');+ });++ it('waives a quarantined dist-tag by name, since a tag is not a usable range', async () => {+ mockCommands({+ 'yarn install': {+ fails: true,+ stdout:+ '➤ YN0016: │ twenty-ui@npm:latest: The version for tag "latest" is quarantined, and no lower version is available',+ },+ });++ const message = await installAndCatch();++ expect(parseSuggestedYarnrc(message)).toEqual({+ npmPreapprovedPackages: ['twenty-ui'],+ });+ expect(message).not.toContain('twenty-ui@latest');+ });++ it('falls back to the yarn output when no package can be identified', async () => {+ mockCommands({+ 'yarn install': {+ fails: true,+ stdout: '➤ YN0016: │ something unparseable happened',+ },+ });++ const message = await installAndCatch();++ expect(message).toContain('something unparseable happened');+ expect(message).not.toContain('npmPreapprovedPackages');+ });++ it('tolerates corepack being unavailable when yarn still installs', async () => {+ mockCommands({ 'corepack enable': { fails: true, stderr: 'no corepack' } });++ await expect(install(APP_DIRECTORY)).resolves.toBeUndefined();+ });+});diff --git a/packages/create-twenty-app/src/utils/app-template.ts b/packages/create-twenty-app/src/utils/app-template.tsindex ff09e3f4ffa..0ffec9143a7 100644--- a/packages/create-twenty-app/src/utils/app-template.ts+++ b/packages/create-twenty-app/src/utils/app-template.ts@@ -2,6 +2,7 @@ import * as fs from 'fs-extra';import { join } from 'path';import { v4 } from 'uuid';+import { TEMPLATE_FIRST_PARTY_PACKAGES } from '@/constants/template-packages';import createTwentyAppPackageJson from 'package.json';const SRC_FOLDER = 'src';@@ -119,12 +120,16 @@ const updatePackageJson = async ({}) => {const packageJson = await fs.readJson(join(appDirectory, 'package.json'));+ // The template yarn.lock keeps its placeholder workspace name: the only entry+ // naming the project is the workspace root, which the scaffolder's `yarn install`+ // rewrites from package.json without re-resolving a single dependency. Renaming+ // it here would move the entry out of sort order and break `--immutable`.packageJson.name = appName;- packageJson.devDependencies['twenty-sdk'] =- createTwentyAppPackageJson.version;- packageJson.devDependencies['twenty-client-sdk'] =- createTwentyAppPackageJson.version;- packageJson.devDependencies['twenty-ui'] = createTwentyAppPackageJson.version;++ for (const packageName of TEMPLATE_FIRST_PARTY_PACKAGES) {+ packageJson.devDependencies[packageName] =+ createTwentyAppPackageJson.version;+ }await fs.writeFile(join(appDirectory, 'package.json'),diff --git a/packages/create-twenty-app/src/utils/install.ts b/packages/create-twenty-app/src/utils/install.tsindex cea60681ec0..69aba6a30fa 100644--- a/packages/create-twenty-app/src/utils/install.ts+++ b/packages/create-twenty-app/src/utils/install.ts@@ -1,9 +1,70 @@import chalk from 'chalk';-import { promisify } from 'util';import { exec } from 'child_process';+import { promisify } from 'util';const execPromise = promisify(exec);+// Raised as "All versions satisfying <range> are quarantined", or for a tag as+// "The version for tag <tag> is quarantined", when every candidate version is+// younger than the configured npmMinimalAgeGate.+const YARN_QUARANTINE_ERROR_CODE = 'YN0016';++const QUARANTINED_PACKAGE_PATTERN =+ /(@?[\w.-]+(?:\/[\w.-]+)?)@npm:(\S+?): (?:All versions satisfying|The version for tag)/g;++const ANSI_ESCAPE_PATTERN = /\x1b\[[0-9;]*m/g;++// A selector Yarn can test against a version works as a preapproval entry; a+// dist-tag does not, and only the bare package name will waive it.+const VERSION_SELECTOR_PATTERN = /^[\^~>=<\s]*\d/;++const OUTPUT_TAIL_LINES = 20;++const tail = (output: string) =>+ output.trim().split('\n').slice(-OUTPUT_TAIL_LINES).join('\n');++const parseQuarantinedPackages = (output: string) => {+ const matches = output+ .replace(ANSI_ESCAPE_PATTERN, '')+ .matchAll(QUARANTINED_PACKAGE_PATTERN);++ return [+ ...new Set(+ [...matches].map(([, packageName, selector]) =>+ VERSION_SELECTOR_PATTERN.test(selector)+ ? `${packageName}@${selector}`+ : packageName,+ ),+ ),+ ];+};++const buildQuarantineMessage = ({+ appDirectory,+ quarantinedPackages,+}: {+ appDirectory: string;+ quarantinedPackages: string[];+}) =>+ [+ 'Dependency installation failed: your package manager enforces a minimum',+ 'release age, and these packages were published too recently to satisfy it:',+ '',+ ...quarantinedPackages.map((descriptor) => ` ${descriptor}`),+ '',+ `Your project was created at ${appDirectory} and does not need to be scaffolded again.`,+ 'You can either wait until those packages are older than your configured gate',+ 'and run `yarn install` there, or waive the gate for just them by adding to',+ "that project's .yarnrc.yml:",+ '',+ ' npmPreapprovedPackages:',+ // Quoted because a scoped descriptor starts with "@", which YAML reserves:+ // an unquoted `- @scope/pkg@^1.2.3` is a parse error, not a value.+ ...quarantinedPackages.map((descriptor) => ` - "${descriptor}"`),+ '',+ 'That leaves the gate in force for every other dependency.',+ ].join('\n');+export const install = async (root: string,onProgress?: (message: string) => void,@@ -17,8 +78,33 @@ export const install = async (onProgress?.('Running yarn install');try {- await execPromise('yarn install', { cwd: root });+ // Yarn installs immutably by default when CI is set, but this install is what+ // finalises the template's lockfile: it rewrites the workspace root entry to+ // the project's real name. Immutable mode rejects that with YN0028.+ await execPromise('yarn install --no-immutable', { cwd: root });} catch (error: any) {- console.warn(chalk.yellow('yarn install failed:'), error.stdout);+ const output = `${error.stdout ?? ''}\n${error.stderr ?? ''}`;+ const quarantinedPackages = output.includes(YARN_QUARANTINE_ERROR_CODE)+ ? parseQuarantinedPackages(output)+ : [];++ // Continuing here would authenticate, sync and report success over a project+ // that has no node_modules, so surface the failure instead.+ throw new Error(+ quarantinedPackages.length > 0+ ? buildQuarantineMessage({+ appDirectory: root,+ quarantinedPackages,+ })+ : [+ `Dependency installation failed in ${root}:`,+ '',+ tail(output),+ '',+ // The project itself is intact: package.json carries its real name and+ // the lockfile is the shipped one, which a plain install reconciles.+ 'The project was created. Fix the problem above and run `yarn install` there.',+ ].join('\n'),+ );}};diff --git a/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/successful-sync-application-workspace-migration.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/successful-sync-application-workspace-migration.integration-spec.ts.snapindex 9704875f8c9..1429f2e7dce 100644--- a/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/successful-sync-application-workspace-migration.integration-spec.ts.snap+++ b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/successful-sync-application-workspace-migration.integration-spec.ts.snap@@ -214,7 +214,7 @@ exports[`syncApplication should delete old field and create equivalent one when"applicationUniversalIdentifier": Any<String>,"createdAt": Any<String>,"defaultValue": "uuid",- "description": "Id",+ "description": "ID","icon": "Icon123","isActive": true,"isAuditLogged": true,@@ -225,7 +225,7 @@ exports[`syncApplication should delete old field and create equivalent one when"isSystemSideEffect": true,"isUIEditable": false,"isUnique": true,- "label": "Id",+ "label": "ID","morphId": null,"name": "id","objectMetadataUniversalIdentifier": Any<String>,@@ -1855,7 +1855,7 @@ exports[`syncApplication should return workspace migration actions on initial sy"applicationUniversalIdentifier": Any<String>,"createdAt": Any<String>,"defaultValue": "uuid",- "description": "Id",+ "description": "ID","icon": "Icon123","isActive": true,"isAuditLogged": true,@@ -1866,7 +1866,7 @@ exports[`syncApplication should return workspace migration actions on initial sy"isSystemSideEffect": true,"isUIEditable": false,"isUnique": true,- "label": "Id",+ "label": "ID","morphId": null,"name": "id","objectMetadataUniversalIdentifier": Any<String>,diff --git a/yarn.lock b/yarn.lockindex b06348547f0..26e0ae90ff7 100644--- a/yarn.lock+++ b/yarn.lock@@ -27958,6 +27958,7 @@ __metadata:uuid: "npm:^13.0.2"vite: "npm:^8.0.0"vite-plugin-dts: "npm:^4.5.4"+ yaml: "npm:^2.9.0"bin:create-twenty-app: dist/cli.cjslanguageName: unknown