diff --git a/.talismanrc b/.talismanrc index f29926f0..ce2a0e53 100644 --- a/.talismanrc +++ b/.talismanrc @@ -6,7 +6,7 @@ fileignoreconfig: - filename: src/commands/launch/logs/get.test.ts checksum: d94d390de150956c799f64a84adfe0e02b5b21c66ddcc5cf55a1329aa67ec1a7 - filename: src/core/failure.test.ts - checksum: d8be306f3bde77249360475bbb76093ce67458f3530c3b4c5bd7e6a516a910aa + checksum: 3f5c731861dc816d141f6314c32bec55bc5197241447a4375bc76fa9f85339f0 - filename: test/integration/retired-commands.test.ts checksum: c38d6e8dae6bd4d2034ff48bff488e89cc00d950a7417c6df890168ac743ae37 - filename: test/integration/manage-base-path.test.ts @@ -116,7 +116,7 @@ fileignoreconfig: allowed_patterns: - "assertArray\\(response, key, `\\$\\{key\\} response`\\)" - filename: src/environments/environment.inputs.ts - checksum: 3fc2802c79457f7c7e93cd5f32c00a7986dc6f686fe3c346de4b8436a66cc0b9 + checksum: fd3a8f925444e44b0477d7c907d77526d5a4315d627bf29768912b6799a45c80 ignore_detectors: - filename - filename: src/environments/environment.builder.ts @@ -127,11 +127,11 @@ fileignoreconfig: - filename checksum: 8b7e3207630f19170dd08ca639ebca8af6bc0d70db633b98e66eedde6d2ea641 - filename: src/environments/environment.update.ts - checksum: b1e15e174f98a875f97e0683182638f93966ef4c498135d36df620a28338aacb + checksum: 85b625c571ef1a4e0c177b78fe5538f6c9506c4b692c6212d9faa63681d77ffe ignore_detectors: - filename - filename: src/environments/environment.update.test.ts - checksum: 5e90c3dd231ede1b890f7c750c7063412116a2e4be536d2f290d56d28205ceae + checksum: 451f42cd81d25088ec05f5ededc9375bfcac7cda6a29db60ccda792768afdd0e ignore_detectors: - filename - filename: src/environments/environment.create.ts @@ -145,19 +145,19 @@ fileignoreconfig: ignore_detectors: - filename - filename: src/environments/environment.update.prompt.ts - checksum: 5f2da5ae044eda92f9e555c997d23f065b5454cda8a340c12595597795ecfbb9 + checksum: 992d52bfb924105691c90fbdee53ca66fc0a585bb3273e7bcb23974ec2ef4c5c ignore_detectors: - filename - filename: src/environments/environment.update.prompt.test.ts - checksum: 6653e245baac00cef348acfc0aa2f32d03a7ff63ca3c320ee56a0c6250775004 + checksum: 2be66b5b7a394e0f2440163ee94c46fdd3884e594673b03de9d8c2eef0ca1ed0 ignore_detectors: - filename - filename: src/environments/environment.presenter.ts - checksum: 3ca3e566a136fb0100cd794e9e973fce70a80c88224b6f93027d8190ac0b6882 + checksum: 3808d26ca5eb7f345568b56fe48f5756e14f0cdb15ef68b2ae72e9556bc6bab2 ignore_detectors: - filename - filename: src/environments/environment.presenter.test.ts - checksum: f5f6e5ec469a16ca8e1c9175ec88aa406a24c6318ef95520d534c444fdd3ab88 + checksum: 3e28f6188a450b47d874453a37e22193d9e5036762d34f55315118ed54a73c0a ignore_detectors: - filename - filename: src/environments/environment.resolver.ts @@ -311,9 +311,9 @@ fileignoreconfig: - filename: test/credential-guard.setup.ts checksum: 519ccbeb0552fdb1d5f27308c56477c0258ee6cc0adec8f618e8e5bc047cbf6d - filename: src/environments/types.ts - checksum: 2825d0e70757022e518465b134878b8cc8f9eccaf4e9ad088d73a31b9a35a826 + checksum: d5506fb4ea67ef8cac77b43724ad6b0e438503d7198d68db8fb2f6d718e89f00 - filename: src/commands/launch/env/get.test.ts - checksum: 6e739ef12bc0d887e652e23ee54d9fac30dd6a3505cf464cdaefc0e696cf3e51 + checksum: 6b79822734553c7417c0a8774fae221609d008be22834113661c9925f17017b9 - filename: test/integration/environments-delete.test.ts checksum: a6f002256162971e5f4ace879153454c95199101d2acc853f2a54b39d1d48914 - filename: src/commands/launch/env/delete.test.ts @@ -327,11 +327,11 @@ fileignoreconfig: - filename: test/integration/environments-update.test.ts checksum: 249f27ad679b68f40eac3af90c616229838bceffad57ba508dd298ab053fa51a - filename: src/commands/launch/env/update.ts - checksum: 06add97108d878eaf415e32160439b8963683e63a0e37ce77a56f66b88383c7a + checksum: 981c3267005bca0453131b532c9b62ca501bc67cfd25511c261e99082677882a - filename: src/commands/launch/env/update.test.ts - checksum: 2da219594e7bdd589adc0eff9ff035252a75aaa51dfa20514b18fd3266d7b752 + checksum: 82c76af721bfdfd8eb7cf49494ffbe15d98b988e98bca1015b9d34b42b5226bd - filename: README.md - checksum: a3c7d1fc273e7b5b818f0a7f05664fd7ddbb05c2f2eb44c28b5d496aad828508 + checksum: 6386fbf38075484d6c0eb32bb40ab246a1c94dff41a107e14713f944b4f1d2b5 allowed_patterns: - "password-protection" - "-p, --password" @@ -433,7 +433,7 @@ fileignoreconfig: - filename: src/commands/launch/deployments/list.test.ts checksum: e493cd51e7c65bbf5b4f71704478b7a669bca4342efc865a1363bc508fe6f9f0 - filename: src/deployments/deployment.presenter.test.ts - checksum: e393d6bb6ce3fd92920f5003603b161186085ea8939fae704e6f71bd9e1778bc + checksum: f5a8d7ccd1118e79abd5f2717d6535ca13c576b92bd686ee429ae72aaafa955a - filename: test/integration/deployments-create.test.ts checksum: fef71ae5b4bed7bcca111e90870238a26518e7a376475aa55768f5ffbe07ba36 - filename: src/deployments/deployment.watcher.test.ts @@ -441,9 +441,9 @@ fileignoreconfig: - filename: src/deployments/deployment.create.ts checksum: ca64f3b29a68c4a2755a88a141e2cd9dbd6fa851a2776876d78c40f3168492e3 - filename: src/commands/launch/deployments/create.test.ts - checksum: bcbb2f85e0a78d38036af4723a0ce691f2692de05f5c7c9c3f97a5cca13497a6 + checksum: 9f5c60d5f6367250aa8f932acf0e5a7ece933f3fc1ca173fa908e80724d1d579 - filename: src/deployments/deployment.create.test.ts - checksum: 6545afa21a23b7e5de18ad8ff417f88a184577e7042713cfda90758ccbcd9869 + checksum: aceeba27a10ffe7bcf7f78af4c88cb19e017a46c898f02a07e314f949775841a - filename: test/integration/deployments-rollback.test.ts checksum: 98a9f7001eb5bf01e0e2f46677eeea61ad5d38c595d17ef27d366c93e603f0d5 - filename: test/integration/deployments-cancel.test.ts diff --git a/README.md b/README.md index 21cd2376..8ecd87fd 100644 --- a/README.md +++ b/README.md @@ -851,31 +851,26 @@ _See code: [src/commands/launch/secrets/unset.ts](https://github.com/contentstac ## `csdx launch:site:open` -Open an environment's live site in your browser, or print its URL when there is no terminal. On a terminal, when the environment has more than one domain, you choose which one to open; --deployment opens that deployment's preview URL without asking. +Open an environment's live site in your browser, or print its URL when there is no terminal. On a terminal, when the environment has more than one domain, you choose which one to open. ``` USAGE $ csdx launch:site:open [--config ] [-d ] [--org ] [--project ] [--env ] - [--deployment ] FLAGS - -d, --data-dir= Current working directory - --config= Path to the local '.cs-launch.json' file - --deployment= Deployment UID - --env= Environment name or UID - --org= Organization UID - --project= Project name or UID + -d, --data-dir= Current working directory + --config= Path to the local '.cs-launch.json' file + --env= Environment name or UID + --org= Organization UID + --project= Project name or UID DESCRIPTION Open an environment's live site in your browser, or print its URL when there is no terminal. On a terminal, when the - environment has more than one domain, you choose which one to open; --deployment opens that deployment's preview URL - without asking. + environment has more than one domain, you choose which one to open. EXAMPLES $ csdx launch:site:open --org --project --env - $ csdx launch:site:open --org --project --env --deployment - $ url=$(csdx launch:site:open --org --project --env ) ``` diff --git a/src/commands/launch/deployments/create.test.ts b/src/commands/launch/deployments/create.test.ts index a6d33ca8..fd0b0e8e 100644 --- a/src/commands/launch/deployments/create.test.ts +++ b/src/commands/launch/deployments/create.test.ts @@ -31,7 +31,7 @@ function commandUnderTest(resolved: Record, projectType = 'GITP created.push(params); return { uid: 'd1', status: 'QUEUED' }; }, - get: async () => ({ uid: 'd1', status: 'LIVE' }), + get: async () => ({ uid: 'd1', status: 'LIVE', deploymentUrl: 'my-site.example.test' }), }, deploymentLogs: { after: async () => [] }, }, diff --git a/src/commands/launch/site/open.test.ts b/src/commands/launch/site/open.test.ts index 4c778113..eb2479d6 100644 --- a/src/commands/launch/site/open.test.ts +++ b/src/commands/launch/site/open.test.ts @@ -1,16 +1,10 @@ -import { randomBytes } from 'node:crypto'; - import { CancelledError, UsageError } from '../../../core/errors'; import type { UxLike } from '../../../core/prompt'; -import { DEPLOYMENT_ERROR_MESSAGES } from '../../../deployments/deployment.errors'; import { ENVIRONMENT_ERROR_MESSAGES } from '../../../environments/environment.errors'; import { LaunchApiError } from '../../../transport/errors'; import SiteOpen from './open'; const SCOPE = { org: 'org1', project: 'proj1', environment: 'env1' }; -const DEPLOYMENT_UID = randomBytes(12).toString('hex'); -const DEPLOYMENT_SCOPE = { ...SCOPE, deployment: DEPLOYMENT_UID }; -const PREVIEW_URL = 'https://preview-1a2b.contentstackapps.com'; const LIVE_URL = 'https://my-site.contentstackapps.com'; const DOMAIN_URL = 'https://www.example.com'; const OTHER_DOMAIN_URL = 'https://shop.example.com'; @@ -25,9 +19,6 @@ interface Harness { environmentFails?: Error; latest?: unknown; latestFails?: Error; - deployment?: string; - fetched?: unknown; - fetchFails?: Error; } function commandUnderTest(harness: Harness = {}) { @@ -55,7 +46,7 @@ function commandUnderTest(harness: Harness = {}) { Object.assign(command, { ux, - resolved: { org: 'org1', project: 'proj1', env: 'env1', deployment: harness.deployment }, + resolved: { org: 'org1', project: 'proj1', env: 'env1' }, services: { ux, isTTY: harness.isTTY ?? true, @@ -75,16 +66,6 @@ function commandUnderTest(harness: Harness = {}) { }, }, deployments: { - get: async (params: unknown) => { - calls.push('deployments.get'); - got.push(params); - - if (harness.fetchFails) { - throw harness.fetchFails; - } - - return harness.fetched; - }, latest: async (params: unknown) => { calls.push('deployments.latest'); got.push(params); @@ -227,115 +208,6 @@ describe('launch:site:open', () => { expect(opened).toEqual([]); }); - it("opens the named deployment's preview url, not its deployment url, reading the environment first and never the latest", async () => { - const { command, stdout, calls, got, opened } = commandUnderTest({ - deployment: DEPLOYMENT_UID, - fetched: { uid: DEPLOYMENT_UID, deploymentUrl: LIVE_URL, previewUrl: 'preview-1a2b.contentstackapps.com' }, - environment: { uid: 'env1', domains: [{ url: 'https://www.example.com' }] }, - }); - - await command.run(); - - expect(calls).toEqual(['environments.get', 'deployments.get']); - expect(got).toEqual([SCOPE, DEPLOYMENT_SCOPE]); - expect(stdout).toEqual([`\u001b[32m✔ Opening ${PREVIEW_URL} in your browser...\u001b[39m`]); - expect(opened).toEqual([PREVIEW_URL]); - }); - - it('prints only the preview url and starts no browser for a named deployment when stdout is not a terminal', async () => { - const { command, stdout, stderr, opened } = commandUnderTest({ - outputIsTTY: false, - deployment: DEPLOYMENT_UID, - fetched: { uid: DEPLOYMENT_UID, previewUrl: PREVIEW_URL }, - }); - - await command.run(); - - expect(stdout).toEqual([PREVIEW_URL]); - expect(stderr).toEqual([]); - expect(opened).toEqual([]); - }); - - it.each([ - ['absent', undefined], - ['empty', ''], - ['whitespace only', ' '], - ])( - 'says the website url was not found in yellow on stdout and exits 2 when the named deployment has a %s preview url', - async (_label, previewUrl) => { - const { command, stdout, stderr, calls, got, opened } = commandUnderTest({ - deployment: DEPLOYMENT_UID, - fetched: { uid: DEPLOYMENT_UID, deploymentUrl: LIVE_URL, ...(previewUrl === undefined ? {} : { previewUrl }) }, - environment: { uid: 'env1', domains: [{ url: 'https://www.example.com' }] }, - }); - - const code = await exitCodeOf(command.run()); - - expect(code).toBe(2); - expect(stdout).toEqual(['\u001b[33mWebsite URL not found.\u001b[39m']); - expect(stderr).toEqual([]); - expect(opened).toEqual([]); - expect(calls).toEqual(['environments.get', 'deployments.get']); - expect(got).toEqual([SCOPE, DEPLOYMENT_SCOPE]); - }, - ); - - it('writes the plain message to stderr, nothing to stdout, and exits 2 for a named deployment without a preview url and no terminal', async () => { - const { command, stdout, stderr, opened } = commandUnderTest({ - outputIsTTY: false, - deployment: DEPLOYMENT_UID, - fetched: { uid: DEPLOYMENT_UID, deploymentUrl: LIVE_URL }, - }); - - const code = await exitCodeOf(command.run()); - - expect(code).toBe(2); - expect(stdout).toEqual([]); - expect(stderr).toEqual(['Website URL not found.\n']); - expect(opened).toEqual([]); - }); - - it('reports a deployment the environment does not have as a usage error in the api wording, printing and opening nothing', async () => { - const notFound = new LaunchApiError(404, [{ code: 'launch.DEPLOYMENT.NOT_FOUND' }], DEPLOYMENT_ERROR_MESSAGES); - const { command, calls, stdout, stderr, opened } = commandUnderTest({ - deployment: DEPLOYMENT_UID, - fetchFails: notFound, - }); - - const error = (await command.run().catch((thrown: unknown) => thrown)) as UsageError; - - expect(error).toBeInstanceOf(UsageError); - expect(error.exitCode).toBe(2); - expect(error.message).toBe('No deployment found with that UID.'); - expect(calls).toEqual(['environments.get', 'deployments.get']); - expect(stdout).toEqual([]); - expect(stderr).toEqual([]); - expect(opened).toEqual([]); - }); - - it('propagates any other failure reading the named deployment untouched, printing and opening nothing', async () => { - const failure = new LaunchApiError(500, []); - const { command, calls, stdout, stderr, opened } = commandUnderTest({ - deployment: DEPLOYMENT_UID, - fetchFails: failure, - }); - - await expect(command.run()).rejects.toBe(failure); - expect(failure.exitCode).toBe(1); - expect(calls).toEqual(['environments.get', 'deployments.get']); - expect(stdout).toEqual([]); - expect(stderr).toEqual([]); - expect(opened).toEqual([]); - }); - - it('reads no deployment when the environment is missing, even with --deployment', async () => { - const failure = new LaunchApiError(500, []); - const { command, calls } = commandUnderTest({ deployment: DEPLOYMENT_UID, environmentFails: failure }); - - await expect(command.run()).rejects.toBe(failure); - expect(calls).toEqual(['environments.get']); - }); - it('asks which domain to open, as a single-select list with the default preselected, and opens only the one picked', async () => { const { command, stdout, calls, opened, asked } = commandUnderTest({ environment: { uid: 'env1', domains: [{ url: DOMAIN_URL }, { url: 'shop.example.com' }] }, @@ -452,20 +324,6 @@ describe('launch:site:open', () => { expect(opened).toEqual([LIVE_URL]); }); - it('asks nothing for a named deployment even when the environment has domains', async () => { - const { command, calls, opened, asked } = commandUnderTest({ - deployment: DEPLOYMENT_UID, - fetched: { uid: DEPLOYMENT_UID, previewUrl: PREVIEW_URL }, - environment: { uid: 'env1', domains: [{ url: DOMAIN_URL }, { url: OTHER_DOMAIN_URL }] }, - }); - - await command.run(); - - expect(asked).toEqual([]); - expect(opened).toEqual([PREVIEW_URL]); - expect(calls).toEqual(['environments.get', 'deployments.get']); - }); - it.each([[[]], [[{ url: DOMAIN_URL }, { url: OTHER_DOMAIN_URL }]]])( 'exits 2 with the website url not found line and asks nothing when there is no deployment and domains %j', async (domains) => { @@ -483,24 +341,23 @@ describe('launch:site:open', () => { }, ); - it('declares no --domain flag', () => { - expect(Object.keys(SiteOpen.flags)).not.toContain('domain'); + it.each([['domain'], ['deployment']])('declares no --%s flag', (flag) => { + expect(Object.keys(SiteOpen.flags)).not.toContain(flag); }); it('describes the domain prompt in its help', () => { expect(SiteOpen.description).toContain('choose which one to open'); - expect(SiteOpen.description).toContain('--deployment'); + expect(SiteOpen.description).not.toContain('--deployment'); expect(SiteOpen.examples).toContain( '$ url=$(csdx launch:site:open --org --project --env )', ); }); - it('declares org, project and env as required inputs and --deployment as optional', () => { + it('declares org, project and env as its only inputs, all required', () => { expect(SiteOpen.inputs).toEqual({ org: { required: true }, project: { required: true }, env: { required: true }, - deployment: {}, }); }); }); diff --git a/src/commands/launch/site/open.ts b/src/commands/launch/site/open.ts index 510e795e..45df3de5 100644 --- a/src/commands/launch/site/open.ts +++ b/src/commands/launch/site/open.ts @@ -3,18 +3,16 @@ import { UsageError } from '../../../core/errors'; import { writeToStderr } from '../../../core/failure'; import { flagsFor, inputs } from '../../../core/inputs'; import { LaunchCommand } from '../../../core/launch-command'; -import type { GetDeploymentParams } from '../../../deployments/deployments.api'; import { domainChoices, askForDomain } from '../../../site/site.prompt'; import { siteOpeningLine, siteUrlNotFoundLine } from '../../../site/site.presenter'; import type { SiteDomain } from '../../../site/site.url'; -import { previewUrlOf, siteUrlOf } from '../../../site/site.url'; +import { siteUrlOf } from '../../../site/site.url'; import { LaunchApiError } from '../../../transport/errors'; const openInputs = inputs({ org: { required: true }, project: { required: true }, env: { required: true }, - deployment: {}, }); function notFoundAsUsage(error: unknown): never { @@ -28,12 +26,10 @@ function notFoundAsUsage(error: unknown): never { export default class SiteOpen extends LaunchCommand { static description = "Open an environment's live site in your browser, or print its URL when there is no terminal. " + - 'On a terminal, when the environment has more than one domain, you choose which one to open; ' + - "--deployment opens that deployment's preview URL without asking."; + 'On a terminal, when the environment has more than one domain, you choose which one to open.'; static examples = [ '$ csdx launch:site:open --org --project --env ', - '$ csdx launch:site:open --org --project --env --deployment ', '$ url=$(csdx launch:site:open --org --project --env )', ]; @@ -42,26 +38,20 @@ export default class SiteOpen extends LaunchCommand { static flags = flagsFor(openInputs); async run(): Promise { - const { org, project, env, deployment: deploymentUid } = this.resolved; + const { org, project, env } = this.resolved; const scope = { org, project, environment: env }; const outputIsTTY = this.services.outputIsTTY === true; const environment = await this.services.api.environments.get(scope).catch(notFoundAsUsage); - let url: string | undefined; + const defaultUrl = siteUrlOf(await this.services.api.deployments.latest(scope), environment.domains); - if (deploymentUid === undefined) { - url = siteUrlOf(await this.services.api.deployments.latest(scope), environment.domains); - - url = url === undefined ? url : await this.chosenUrl(url, environment.domains, outputIsTTY); - } else { - url = await this.previewUrlOfDeployment({ ...scope, deployment: deploymentUid }); - } - - if (url === undefined) { + if (defaultUrl === undefined) { this.reportMissingUrl(outputIsTTY); this.exit(EXIT_USAGE); } + const url = await this.chosenUrl(defaultUrl, environment.domains, outputIsTTY); + if (!outputIsTTY) { this.ux.print(url); return; @@ -81,12 +71,6 @@ export default class SiteOpen extends LaunchCommand { return choices.length > 1 ? askForDomain(this.ux, choices) : url; } - private async previewUrlOfDeployment(params: GetDeploymentParams): Promise { - const deployment = await this.services.api.deployments.get(params).catch(notFoundAsUsage); - - return previewUrlOf(deployment); - } - private reportMissingUrl(outputIsTTY: boolean): void { const line = siteUrlNotFoundLine(outputIsTTY); diff --git a/src/core/url.test.ts b/src/core/url.test.ts new file mode 100644 index 00000000..11a0faa0 --- /dev/null +++ b/src/core/url.test.ts @@ -0,0 +1,35 @@ +import { bareHost, webUrlOf } from './url'; + +describe('webUrlOf', () => { + it.each([ + ['http://plain.example.test', 'http://plain.example.test'], + [' https://secure.example.test ', 'https://secure.example.test'], + ['bare.example.test', 'https://bare.example.test'], + ['http-api-ab12.contentstackapps.com', 'https://http-api-ab12.contentstackapps.com'], + ])('keeps a web scheme as given and gives a bare host https://: %p', (raw, url) => { + expect(webUrlOf(raw)).toBe(url); + }); + + it.each([ + ['https://host.example.test/app/', 'https://host.example.test/app/'], + ['https://host.example.test/?next=/', 'https://host.example.test/?next=/'], + ['host.example.test/app/', 'https://host.example.test/app/'], + ['https://host.example.test//', 'https://host.example.test'], + ['host.example.test/', 'https://host.example.test'], + ])('keeps a path or query exactly and drops trailing slashes only from a bare host: %p', (raw, url) => { + expect(webUrlOf(raw)).toBe(url); + }); + + it.each([[undefined], [''], [' '], ['/'], ['//'], ['https://'], ['file:///etc/hosts'], ['ftp://files.example.test']])( + 'gives no url for %p, which has no host or is not a web url', + (raw) => { + expect(webUrlOf(raw)).toBeUndefined(); + }, + ); +}); + +describe('bareHost', () => { + it('drops the scheme and trailing slashes', () => { + expect(bareHost(' HTTPS://www.example.com// ')).toBe('www.example.com'); + }); +}); diff --git a/src/core/url.ts b/src/core/url.ts new file mode 100644 index 00000000..b5460652 --- /dev/null +++ b/src/core/url.ts @@ -0,0 +1,21 @@ +const SCHEME = /^[a-z][a-z\d+.-]*:\/\//i; +const WEB_SCHEME = /^https?:\/\//i; +const TRAILING_SLASHES = /\/+$/; + +export function bareHost(url: string): string { + return url.trim().replace(SCHEME, '').replace(TRAILING_SLASHES, ''); +} + +export function webUrlOf(raw: string | undefined): string | undefined { + const url = raw?.trim() ?? ''; + const host = bareHost(url); + const scheme = SCHEME.exec(url)?.[0]; + + if (host === '' || (scheme !== undefined && !WEB_SCHEME.test(scheme))) { + return undefined; + } + + const rest = host.includes('/') ? url.slice(scheme?.length ?? 0) : host; + + return `${scheme ?? 'https://'}${rest}`; +} diff --git a/src/deployments/deployment.create.test.ts b/src/deployments/deployment.create.test.ts index 52c10de8..c00a4f33 100644 --- a/src/deployments/deployment.create.test.ts +++ b/src/deployments/deployment.create.test.ts @@ -7,6 +7,7 @@ import type { LaunchError } from '../core/errors'; import { UsageError } from '../core/errors'; import type { ServiceContext } from '../core/service-context'; import type { ApiSurface } from '../resources'; +import type { SiteDomain } from '../site/site.url'; import { LaunchApiError } from '../transport/errors'; import type { CreateDeploymentRequest } from './deployment.create'; import { DeploymentCreator } from './deployment.create'; @@ -20,6 +21,7 @@ const PROJECT = randomBytes(12).toString('hex'); const ENVIRONMENT = randomBytes(12).toString('hex'); const DEPLOYMENT = randomBytes(12).toString('hex'); const SHA = randomBytes(20).toString('hex'); +const LIVE_URL = 'https://my-site.example.test'; const MISSING_DIR = join(tmpdir(), `launch-no-such-dir-${randomBytes(6).toString('hex')}`); const BASE: CreateDeploymentRequest = { @@ -64,6 +66,7 @@ interface Harness { fetched: unknown[]; watched: { scope: unknown; stop?: AbortSignal }[]; announced: Deployment[]; + announcedDomains: (readonly SiteDomain[] | undefined)[]; picked: unknown[]; printed: string[]; } @@ -76,6 +79,8 @@ function harness( createFails?: Error; projectFails?: Error; announceFails?: Error; + domains?: SiteDomain[]; + environmentFails?: Error; pick?: () => Promise; } = {}, ): Harness { @@ -85,6 +90,7 @@ function harness( const fetched: unknown[] = []; const watched: { scope: unknown; stop?: AbortSignal }[] = []; const announced: Deployment[] = []; + const announcedDomains: (readonly SiteDomain[] | undefined)[] = []; const picked: unknown[] = []; const printed: string[] = []; const signals = new FakeSignals(); @@ -101,6 +107,18 @@ function harness( return { uid: PROJECT, projectType: options.projectType ?? 'GITPROVIDER' }; }, }, + environments: { + get: async (params: unknown) => { + methods.push('environment'); + fetched.push(params); + + if (options.environmentFails !== undefined) { + throw options.environmentFails; + } + + return { uid: ENVIRONMENT, domains: options.domains ?? [] }; + }, + }, deployments: { create: async (params: unknown) => { methods.push('create'); @@ -144,16 +162,21 @@ function harness( return options.watch(scope, stop); } - const outcome = options.outcome ?? { kind: 'success', status: 'LIVE', deployment: { uid: DEPLOYMENT, status: 'LIVE' } }; + const outcome = options.outcome ?? { + kind: 'success', + status: 'LIVE', + deployment: { uid: DEPLOYMENT, status: 'LIVE', deploymentUrl: LIVE_URL }, + }; return typeof outcome === 'function' ? outcome() : outcome; }, - announceLive: async (deployment: Deployment) => { + announceLive: async (deployment: Deployment, domains?: readonly SiteDomain[]) => { if (options.announceFails !== undefined) { throw options.announceFails; } announced.push(deployment); + announcedDomains.push(domains); }, }; @@ -167,7 +190,19 @@ function harness( follower, }); - return { creator, signals, created, methods, signedUrlCalls, fetched, watched, announced, picked, printed }; + return { + creator, + signals, + created, + methods, + signedUrlCalls, + fetched, + watched, + announced, + announcedDomains, + picked, + printed, + }; } async function failureOf(run: Promise): Promise { @@ -192,7 +227,7 @@ describe('DeploymentCreator on a GitHub project', () => { expect(watched.map((entry) => entry.scope)).toEqual([ { org: ORG, project: PROJECT, environment: ENVIRONMENT, deployment: DEPLOYMENT }, ]); - expect(announced).toEqual([{ uid: DEPLOYMENT, status: 'LIVE' }]); + expect(announced).toEqual([{ uid: DEPLOYMENT, status: 'LIVE', deploymentUrl: LIVE_URL }]); expect(picked).toEqual([]); expect(signedUrlCalls).toEqual([]); expect(signals.listeners).toEqual([]); @@ -321,6 +356,34 @@ describe('DeploymentCreator waiting for the outcome', () => { expect(announced).toEqual([deployment]); }); + it('reads the environment and announces its domains only when the live deployment carries no url', async () => { + const domains = [{ url: 'www.example.com' }]; + const { creator, fetched, announcedDomains } = harness({ + outcome: { kind: 'success', status: 'LIVE', deployment }, + domains, + }); + + await creator.create(BASE); + + expect(fetched).toEqual([ + { org: ORG, project: PROJECT }, + { org: ORG, project: PROJECT, environment: ENVIRONMENT }, + ]); + expect(announcedDomains).toEqual([domains]); + }); + + it('still succeeds, announcing without domains, when that environment read fails after the deployment is live', async () => { + const { creator, announced, announcedDomains } = harness({ + outcome: { kind: 'success', status: 'LIVE', deployment }, + environmentFails: new LaunchApiError(503, [{ code: 'x', message: 'Service unavailable.' }]), + }); + + await creator.create(BASE); + + expect(announced).toEqual([deployment]); + expect(announcedDomains).toEqual([undefined]); + }); + it.each([['ARCHIVED'], ['SKIPPED'], ['CANCELLED'], ['FAILED']])( 'raises DeploymentUnsuccessfulError naming %s and the log command with the full scope, announcing nothing', async (status) => { diff --git a/src/deployments/deployment.create.ts b/src/deployments/deployment.create.ts index 866f4cfe..d38338e4 100644 --- a/src/deployments/deployment.create.ts +++ b/src/deployments/deployment.create.ts @@ -2,13 +2,14 @@ import { UsageError } from '../core/errors'; import type { InterruptSource } from '../core/interruptible-ux'; import type { ServiceContext } from '../core/service-context'; import { asSentence, messageOf } from '../core/values'; +import type { SiteDomain } from '../site/site.url'; import { NoUploadDirectoryError } from '../uploads/upload.errors'; import { FolderUploader } from '../uploads/upload.folder'; import { DeploymentUnsuccessfulError, DeploymentWaitInterruptedError } from './deployment.errors'; import type { DeploymentScope as FollowedDeployment } from './deployment.follower'; import { DeploymentFollower } from './deployment.follower'; import { PICK_COMMIT } from './deployment.inputs'; -import { firstDeploymentFailureMessage } from './deployment.presenter'; +import { deploymentUrlOf, firstDeploymentFailureMessage } from './deployment.presenter'; import type { DeploymentOutcome, WatchTiming } from './deployment.watcher'; import type { DeploymentScope } from './deployments.api'; import type { Deployment, IdentifiedDeployment } from './types'; @@ -24,7 +25,7 @@ export interface CreateDeploymentRequest extends DeploymentScope { export interface DeploymentFollowing { watch(scope: FollowedDeployment, stop?: AbortSignal): Promise; - announceLive(deployment: Deployment): Promise; + announceLive(deployment: Deployment, domains?: readonly SiteDomain[]): Promise; } export interface DeploymentCreatorDeps { @@ -118,13 +119,28 @@ export class DeploymentCreator { const outcome = await this.waitFor(followed); if (outcome.kind === 'success') { - await this.follower.announceLive(outcome.deployment); + await this.follower.announceLive(outcome.deployment, await this.fallbackDomains(scope, outcome.deployment)); return; } throw this.unsuccessful(followed, { status: outcome.status, timedOut: outcome.kind === 'timed-out' }); } + private async fallbackDomains( + scope: DeploymentScope, + deployment: Deployment, + ): Promise { + if (deploymentUrlOf(deployment) !== undefined) { + return undefined; + } + + try { + return (await this.services.api.environments.get(scope)).domains; + } catch { + return undefined; + } + } + private async waitFor(followed: FollowedDeployment): Promise { const stop = new AbortController(); const interrupt = (): void => stop.abort(new DeploymentWaitInterruptedError(this.interruptedMessage(followed))); diff --git a/src/deployments/deployment.follower.test.ts b/src/deployments/deployment.follower.test.ts index 65e208e8..fb1ae754 100644 --- a/src/deployments/deployment.follower.test.ts +++ b/src/deployments/deployment.follower.test.ts @@ -117,17 +117,17 @@ describe('DeploymentFollower.announceLive', () => { expect(timeline).toEqual(['print Deployment URL: https://custom.example.test']); }); - it('announces the preview url, with a scheme, when the deployment url is empty and a domain also exists', async () => { + it('never announces the preview url, a screenshot image, and uses the domain when the deployment url is empty', async () => { const { follower, timeline } = harness(); - await follower.announceLive({ uid: 'd1', deploymentUrl: '', previewUrl: 'preview.example.test' }, [ + await follower.announceLive({ uid: 'd1', deploymentUrl: '', previewUrl: 'images.example.test/preview.png' }, [ { url: 'https://www.example.com' }, ]); expect(timeline).toEqual([ - 'print Deployment URL: https://preview.example.test', + 'print Deployment URL: https://www.example.com', `sleep ${SITE_OPEN_DELAY_MS}`, - 'open https://preview.example.test', + 'open https://www.example.com', ]); }); diff --git a/src/deployments/deployment.presenter.test.ts b/src/deployments/deployment.presenter.test.ts index 771b4ced..9aea2ef2 100644 --- a/src/deployments/deployment.presenter.test.ts +++ b/src/deployments/deployment.presenter.test.ts @@ -37,10 +37,13 @@ describe('deployment presenter', () => { it('leaves an absolute deployment url alone and gives a bare host a scheme', () => { expect(deploymentUrlOf({ uid: UID, deploymentUrl: 'https://site.example.test' })).toBe('https://site.example.test'); expect(deploymentUrlOf({ uid: UID, deploymentUrl: 'site.example.test' })).toBe('https://site.example.test'); + expect(deploymentUrlOf({ uid: UID, deploymentUrl: 'http-api-ab12.contentstackapps.com' })).toBe( + 'https://http-api-ab12.contentstackapps.com', + ); }); - it('falls back to the preview url and reports nothing when neither is usable', () => { - expect(deploymentUrlOf({ uid: UID, previewUrl: 'preview.example.test' })).toBe('https://preview.example.test'); + it('reports nothing without a deployment url, never the preview url, which is a screenshot image', () => { + expect(deploymentUrlOf({ uid: UID, previewUrl: 'images.example.test/preview.png' })).toBeUndefined(); expect(deploymentUrlOf({ uid: UID })).toBeUndefined(); expect(deploymentUrlOf({ uid: UID, deploymentUrl: '', previewUrl: '' })).toBeUndefined(); }); @@ -366,7 +369,7 @@ describe('deployment table presenter', () => { } }); - it('falls back to a dash for every absent field and prefers the deployment url over the preview url', () => { + it('falls back to a dash for every absent field and shows the deployment url, never the preview url', () => { const rows = deploymentDetailRows({ uid: UID }, true, SCOPE); for (const field of ['BRANCH', 'COMMIT', 'COMMIT MESSAGE', 'URL', 'CREATED AT', 'UPDATED AT']) { diff --git a/src/deployments/deployment.presenter.ts b/src/deployments/deployment.presenter.ts index 1171e358..995eb0a9 100644 --- a/src/deployments/deployment.presenter.ts +++ b/src/deployments/deployment.presenter.ts @@ -2,6 +2,7 @@ import { stripVTControlCharacters } from 'node:util'; import type { TableColumn } from '../core/render'; import { styled } from '../core/style'; +import { webUrlOf } from '../core/url'; import { isAbsent, withoutControlCharacters } from '../core/values'; import type { DeploymentScope } from './deployments.api'; import type { Deployment, DeploymentLog } from './types'; @@ -20,13 +21,7 @@ const COLOUR_SEQUENCE = /[\u001b\u009b]\[[0-9;:]*m/g; /* eslint-enable no-control-regex */ export function deploymentUrlOf(deployment: Deployment): string | undefined { - const url = deployment.deploymentUrl || deployment.previewUrl; - - if (!url) { - return undefined; - } - - return url.startsWith('http') ? url : `https://${url}`; + return webUrlOf(deployment.deploymentUrl); } export function deploymentUrlLine(url: string, outputIsTTY: boolean): string { diff --git a/src/deployments/types.ts b/src/deployments/types.ts index 0c3564c2..760e022c 100644 --- a/src/deployments/types.ts +++ b/src/deployments/types.ts @@ -24,6 +24,7 @@ export interface Deployment { status?: string; deploymentNumber?: number; deploymentUrl?: string; + /** The screenshot image taken once the deployment is live, never a URL for the site itself. */ previewUrl?: string; gitBranch?: string; commitHash?: string; diff --git a/src/site/site.prompt.ts b/src/site/site.prompt.ts index 6b314719..5b61457f 100644 --- a/src/site/site.prompt.ts +++ b/src/site/site.prompt.ts @@ -1,22 +1,10 @@ import type { Choice, UxLike } from '../core/prompt'; import { askOption } from '../core/prompt'; +import { bareHost, webUrlOf } from '../core/url'; import type { SiteDomain } from './site.url'; export const DOMAIN_QUESTION = 'Which domain do you want to open?'; -const SCHEME = /^[a-z][a-z\d+.-]*:\/\//i; -const TRAILING_SLASHES = /\/+$/; - -function bareHost(url: string): string { - return url.trim().replace(SCHEME, '').replace(TRAILING_SLASHES, ''); -} - -function withScheme(url: string): string { - const trimmed = url.trim().replace(TRAILING_SLASHES, ''); - - return SCHEME.test(trimmed) ? trimmed : `https://${trimmed}`; -} - export function domainChoices(defaultUrl: string, domains: readonly SiteDomain[] = []): Choice[] { const defaultHost = bareHost(defaultUrl); const seen = new Set([defaultHost.toLowerCase()]); @@ -24,10 +12,11 @@ export function domainChoices(defaultUrl: string, domains: readonly SiteDomain[] for (const domain of domains) { const host = bareHost(domain.url ?? ''); + const url = webUrlOf(domain.url); - if (host !== '' && !seen.has(host.toLowerCase())) { + if (url !== undefined && !seen.has(host.toLowerCase())) { seen.add(host.toLowerCase()); - choices.push({ name: host, value: withScheme(domain.url as string) }); + choices.push({ name: host, value: url }); } } diff --git a/src/site/site.url.test.ts b/src/site/site.url.test.ts index 907b096d..d9c936b5 100644 --- a/src/site/site.url.test.ts +++ b/src/site/site.url.test.ts @@ -1,4 +1,4 @@ -import { previewUrlOf, siteUrlOf } from './site.url'; +import { siteUrlOf } from './site.url'; describe('siteUrlOf', () => { it("chooses the deployment's own url over any domain", () => { @@ -17,6 +17,12 @@ describe('siteUrlOf', () => { expect(url).toBe('https://www.example.com'); }); + it('treats a whitespace-only deployment url or domain as absent', () => { + const url = siteUrlOf({ uid: 'd1', deploymentUrl: ' ' }, [{ url: ' ' }, { url: 'www.example.com' }]); + + expect(url).toBe('https://www.example.com'); + }); + it('adds https:// to a deployment url without a scheme and leaves an http:// one alone', () => { const bare = siteUrlOf({ uid: 'd1', deploymentUrl: 'my-site.contentstackapps.com' }); const plain = siteUrlOf({ uid: 'd1', deploymentUrl: 'http://my-site.example.test' }); @@ -25,10 +31,10 @@ describe('siteUrlOf', () => { expect(plain).toBe('http://my-site.example.test'); }); - it('uses the preview url when the deployment has no deployment url, before any domain', () => { - const url = siteUrlOf({ uid: 'd1', previewUrl: 'preview.example.test' }, [{ url: 'https://www.example.com' }]); + it('skips the preview url, a screenshot image, and falls back to a domain when the deployment has no deployment url', () => { + const url = siteUrlOf({ uid: 'd1', previewUrl: 'images.example.test/preview.png' }, [{ url: 'https://www.example.com' }]); - expect(url).toBe('https://preview.example.test'); + expect(url).toBe('https://www.example.com'); }); it('returns nothing without a deployment, even when the environment has domains', () => { @@ -49,19 +55,3 @@ describe('siteUrlOf', () => { expect(url).toBeUndefined(); }); }); - -describe('previewUrlOf', () => { - it('reads the preview url alone, adding the scheme, and ignores the deployment url', () => { - const bare = previewUrlOf({ uid: 'd1', deploymentUrl: 'https://my-site.contentstackapps.com', previewUrl: 'preview.example.test' }); - const plain = previewUrlOf({ uid: 'd1', previewUrl: 'http://preview.example.test' }); - - expect(bare).toBe('https://preview.example.test'); - expect(plain).toBe('http://preview.example.test'); - }); - - it.each([[undefined], [''], [' ']])('returns nothing for a preview url of %p even with a deployment url', (previewUrl) => { - const url = previewUrlOf({ uid: 'd1', deploymentUrl: 'https://my-site.contentstackapps.com', previewUrl }); - - expect(url).toBeUndefined(); - }); -}); diff --git a/src/site/site.url.ts b/src/site/site.url.ts index 2694ae87..7d9fbe29 100644 --- a/src/site/site.url.ts +++ b/src/site/site.url.ts @@ -1,3 +1,4 @@ +import { webUrlOf } from '../core/url'; import { deploymentUrlOf } from '../deployments/deployment.presenter'; import type { Deployment } from '../deployments/types'; @@ -16,13 +17,5 @@ export function siteUrlOf(deployment: Deployment | undefined, domains: readonly return fromDeployment; } - const domain = domains.find((entry) => Boolean(entry.url)); - - return domain === undefined ? undefined : deploymentUrlOf({ uid: deployment.uid, deploymentUrl: domain.url }); -} - -export function previewUrlOf(deployment: Deployment): string | undefined { - const previewUrl = deployment.previewUrl?.trim(); - - return previewUrl ? deploymentUrlOf({ uid: deployment.uid, previewUrl }) : undefined; + return domains.map((entry) => webUrlOf(entry.url)).find((url) => url !== undefined); } diff --git a/test/integration/site-open.test.ts b/test/integration/site-open.test.ts index 7dc42419..0469c286 100644 --- a/test/integration/site-open.test.ts +++ b/test/integration/site-open.test.ts @@ -30,8 +30,6 @@ const ENVIRONMENTS_PATH = `/manage/projects/${PROJECT_UID}/environments`; const ENV_PATH = `${ENVIRONMENTS_PATH}/${ENV_UID}`; const DEPLOYMENTS_PATH = `${ENV_PATH}/deployments`; const DEPLOYMENT_UID = randomBytes(12).toString('hex'); -const DEPLOYMENT_PATH = `${DEPLOYMENTS_PATH}/${DEPLOYMENT_UID}`; -const PREVIEW_URL = 'https://preview-1a2b.contentstackapps.com'; const LIVE_URL = 'https://sample-project.contentstackapps.com'; const DOMAIN_URL = 'https://production-sample-project.contentstackapps.com'; const QUESTION = 'Which domain do you want to open?'; @@ -250,39 +248,6 @@ describe('integration: launch:site:open on the wire', () => { expect(nock.pendingMocks()).toEqual([]); }); - it("opens the named deployment's preview url, not its deployment url, reading the environment first and never the list", async () => { - withTerminal(true); - const ownership = projectOwnership(LAUNCH_HUB_URL, ORG_UID, PROJECT_UID); - const environment = nock(LAUNCH_HUB_URL) - .matchHeader('x-organization-uid', ORG_UID) - .matchHeader('x-project-uid', PROJECT_UID) - .get(ENV_PATH) - .reply(200, () => { - sent.push(`GET ${ENV_PATH}`); - return getFixture; - }); - const deployment = nock(LAUNCH_HUB_URL) - .matchHeader('x-organization-uid', ORG_UID) - .matchHeader('x-project-uid', PROJECT_UID) - .get(DEPLOYMENT_PATH) - .reply(200, () => { - sent.push(`GET ${DEPLOYMENT_PATH}`); - return { deployment: { uid: DEPLOYMENT_UID, deploymentUrl: LIVE_URL, previewUrl: PREVIEW_URL } }; - }); - const list = nock(LAUNCH_HUB_URL).get(DEPLOYMENTS_PATH).query(true).reply(200, { deployments: [] }); - - const { error, stdout } = await runOpen(openArgs('--env', ENV_UID, '--deployment', DEPLOYMENT_UID)); - - expect(error).toBeUndefined(); - expect(stripVTControlCharacters(stdout)).toContain(`✔ Opening ${PREVIEW_URL} in your browser...`); - expect(open).toHaveBeenCalledTimes(1); - expect(open).toHaveBeenCalledWith(PREVIEW_URL); - expect(sent).toEqual([`GET ${ENV_PATH}`, `GET ${DEPLOYMENT_PATH}`]); - expect([ownership, environment, deployment].map((scope) => scope.isDone())).toEqual([true, true, true]); - expect(list.isDone()).toBe(false); - expect(onWire).toEqual([]); - }); - it('asks which domain to open as a single-select list with the default first and preselected, and opens only the one picked', async () => { withTerminal(true); const prompts = answerPrompts({ [QUESTION]: DOMAIN_URL }); @@ -322,12 +287,15 @@ describe('integration: launch:site:open on the wire', () => { expect(onWire).toEqual([]); }); - it('has no --domain flag: it is refused as unknown with exit 2 before any request or browser', async () => { + it.each([ + ['--domain', 'www.example.com'], + ['--deployment', DEPLOYMENT_UID], + ])('has no %s flag: it is refused as unknown with exit 2 before any request or browser', async (flag, value) => { withTerminal(true); forbidPrompts(); reads([{ uid: 'd1', deploymentUrl: LIVE_URL }]); - const { error } = await runOpen(openArgs('--env', ENV_UID, '--domain', 'www.example.com')); + const { error } = await runOpen(openArgs('--env', ENV_UID, flag, value)); expect(error?.oclif?.exit).toBe(2); expect(error?.message).toContain('Nonexistent flag'); @@ -366,31 +334,6 @@ describe('integration: launch:site:open on the wire', () => { expect(stripVTControlCharacters(stdout)).toContain(`✔ Opening ${LIVE_URL} in your browser...`); }); - it('asks nothing for a named deployment on a terminal and opens its preview url', async () => { - withTerminal(true); - const prompts = forbidPrompts(); - projectOwnership(LAUNCH_HUB_URL, ORG_UID, PROJECT_UID); - nock(LAUNCH_HUB_URL) - .get(ENV_PATH) - .reply(200, () => { - sent.push(`GET ${ENV_PATH}`); - return getFixture; - }); - nock(LAUNCH_HUB_URL) - .get(DEPLOYMENT_PATH) - .reply(200, () => { - sent.push(`GET ${DEPLOYMENT_PATH}`); - return { deployment: { uid: DEPLOYMENT_UID, deploymentUrl: LIVE_URL, previewUrl: PREVIEW_URL } }; - }); - - const { error } = await runOpen(openArgs('--env', ENV_UID, '--deployment', DEPLOYMENT_UID)); - - expect(error).toBeUndefined(); - expect(prompts.messages).toEqual([]); - expect(open).toHaveBeenCalledWith(PREVIEW_URL); - expect(sent).toEqual([`GET ${ENV_PATH}`, `GET ${DEPLOYMENT_PATH}`]); - }); - it('exits 2 with the yellow not-found line and asks nothing when there is no deployment but two domains', async () => { withTerminal(true); const prompts = forbidPrompts(); @@ -416,35 +359,6 @@ describe('integration: launch:site:open on the wire', () => { expect(open).not.toHaveBeenCalled(); }); - it('refuses a deployment that is not a 24-hex uid before any request reaches the wire', async () => { - withTerminal(true); - - const { error, stdout } = await runOpen(openArgs('--env', ENV_UID, '--deployment', 'not-a-uid')); - - expect(error?.oclif?.exit).toBe(2); - expect(error?.message).toContain('--deployment'); - expect(stdout).toBe(''); - expect(onWire).toEqual([]); - expect(open).not.toHaveBeenCalled(); - }); - - it('exits 2 with the not-found wording for a deployment the environment does not have', async () => { - withTerminal(true); - projectOwnership(LAUNCH_HUB_URL, ORG_UID, PROJECT_UID); - nock(LAUNCH_HUB_URL).get(ENV_PATH).reply(200, getFixture); - const deployment = nock(LAUNCH_HUB_URL) - .get(DEPLOYMENT_PATH) - .reply(404, { errors: [{ code: 'launch.DEPLOYMENT.NOT_FOUND', message: 'Deployment not found' }] }); - - const { error, stdout } = await runOpen(openArgs('--env', ENV_UID, '--deployment', DEPLOYMENT_UID)); - - expect(error?.oclif?.exit).toBe(2); - expect(error?.message).toBe('No deployment found with that UID.'); - expect(deployment.isDone()).toBe(true); - expect(stdout).toBe(''); - expect(open).not.toHaveBeenCalled(); - }); - it('refuses a project that belongs to another organization before reading the environment', async () => { withTerminal(true); const ownership = projectOwnership(LAUNCH_HUB_URL, OTHER_ORG_UID, PROJECT_UID);