Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/reference/cli/deploy.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ Void signs you in through your browser when needed and saves the selected accoun

After `--skip-migrations`, direct Cloudflare deployment history shows the applied migration state as unknown. Rolling back code doesn't reverse database changes.

When using an API token, grant **Workers Admin** to create the Worker or **Workers Editor** to update it. See [Cloudflare CI credentials](../../integrations/cloudflare.md#deploying-from-ci) for zone and resource permissions. Commit `void.lock.json` after the first deploy before using other machines or CI.
When using an API token, grant **Workers Admin** to create the Worker or **Workers Editor** to update it. See [Cloudflare CI credentials](../../integrations/cloudflare.md#deploying-from-ci) for zone and resource permissions. Commit `void.lock.json` after the first deploy before using other machines or CI. If the deploy creates `void.config.ts`, commit it and any `.gitignore` changes too.

Use `void secret put <NAME>` for production server values. Local `.env` values are never deployed. Run `void db generate` and commit schema changes before deploying.

Expand Down
2 changes: 1 addition & 1 deletion packages/void/src/cli/cloudflare-candidate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { existsSync, mkdirSync, readFileSync, unlinkSync } from 'node:fs';
import { join } from 'pathslash';
import { writeFileAtomic } from '../shared/atomic-write.ts';

const CANDIDATE_FILE = '.void/cloudflare-candidate.json';
export const CANDIDATE_FILE = '.void/cloudflare-candidate.json';
const INVALID_CANDIDATE_MESSAGE =
'The saved Cloudflare candidate receipt is invalid. Restore or remove .void/cloudflare-candidate.json before retrying.';

Expand Down
52 changes: 51 additions & 1 deletion packages/void/src/cli/cloudflare-deploy/classify.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,40 @@
import { existsSync, writeFileSync } from 'node:fs';
import { join } from 'pathslash';
import type { ApplicationAnalysis } from '../../application-analysis.ts';
import {
ignoreMaterializedCloudflareConfig,
MATERIALIZED_CLOUDFLARE_FILE,
VOID_LOCK_FILE,
} from '../../cloudflare-config.ts';
import { LEGACY_CONFIG_FILE, TYPED_CONFIG_FILE } from '../../config-loader.ts';
import { renderDeploySeedConfig } from '../../config-write.ts';
import type { VoidConfig } from '../../config.ts';
import { assertNoRootSourceConventionConflicts } from '../../project-paths.ts';
import { validateSsrEntry } from '../../ssr/entry.ts';
import { CANDIDATE_FILE } from '../cloudflare-candidate.ts';
import { log } from '../deploy-helpers.ts';
import { deriveWorkerName } from '../deploy-resources.ts';
import { getErrorMessage } from '../output.ts';
import { detectPreset, hasBackendFiles } from '../preset.ts';
import { syncWranglerDurableObjects, syncWranglerWebSockets } from '../wrangler.ts';
import {
LATEST_KNOWN_COMPAT_DATE,
syncWranglerDurableObjects,
syncWranglerWebSockets,
} from '../wrangler.ts';

const workerSources = ['wrangler.jsonc', 'wrangler.json', 'wrangler.toml', 'cloudflare.config.ts'];
const configSources = [TYPED_CONFIG_FILE, LEGACY_CONFIG_FILE, ...workerSources];
const savedFiles = [VOID_LOCK_FILE, MATERIALIZED_CLOUDFLARE_FILE, CANDIDATE_FILE];
const configChanged = 'deploy: Configuration changed during setup. Rerun `void deploy`.';

export function hasDeployConfigSource(root: string): boolean {
return configSources.some((name) => existsSync(join(root, name)));
}

export type CloudflareDeployAppOptions = {
dir?: string;
spa?: boolean;
seedConfig?: boolean;
};

export type CloudflareDeployAppClassification =
Expand Down Expand Up @@ -61,6 +87,30 @@ export function classifyCloudflareDeployApp(
const paths = application.paths;
assertNoRootSourceConventionConflicts(paths);
validateSsrEntry(root, paths);
if (options.seedConfig && (!framework || framework.class === 'a')) {
const hasSavedState = () => savedFiles.some((name) => existsSync(join(root, name)));
if (hasSavedState()) {
return unsupported('deploy: Restore void.config.ts from version control or a backup.');
}
ignoreMaterializedCloudflareConfig(root);
if (hasDeployConfigSource(root) || hasSavedState()) {
return unsupported(configChanged);
}
const worker = { compatibility_date: LATEST_KNOWN_COMPAT_DATE };
const config = { cloudflare: { name: deriveWorkerName(root) }, worker };
const contents = renderDeploySeedConfig(config);
try {
writeFileSync(join(root, TYPED_CONFIG_FILE), contents, { flag: 'wx' });
} catch (error) {
if ((error as NodeJS.ErrnoException)?.code === 'EEXIST') {
return unsupported(configChanged);
}
throw error;
}
log.step(
'Created void.config.ts. Commit it, the .gitignore change, and void.lock.json when present.',
);
}
syncWranglerDurableObjects(root, application.durableObjects);
syncWranglerWebSockets(root, application.websockets);
} catch (error) {
Expand Down
9 changes: 8 additions & 1 deletion packages/void/src/cli/cloudflare-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { applyEdits, modify, parse } from 'jsonc-parser';
import type { ParseError } from 'jsonc-parser';
import { basename, join } from 'pathslash';
import { materializeCloudflareConfig, persistCloudflareConfig } from '../cloudflare-config.ts';
import { isUnchangedDeploySeed } from '../config-write.ts';
import { isVersionIdChain } from './cloudflare-candidate.ts';
import type { RunDeployOptions } from './deploy.ts';
import { discoverFrameworkWranglerFiles } from './framework-config-migrate.ts';
Expand Down Expand Up @@ -225,7 +226,13 @@ export async function maybeLinkCloudflareDeploy(
...discoverFrameworkWranglerFiles(root),
]),
];
if (!files.length && !existsSync(join(root, 'void.config.ts'))) {
const typedPath = join(root, 'void.config.ts');
if (
!files.length &&
(!existsSync(typedPath) ||
(!existsSync(join(root, 'void.lock.json')) &&
isUnchangedDeploySeed(readFileSync(typedPath, 'utf8'))))
) {
return null;
}
if (files.length > 1) {
Expand Down
2 changes: 1 addition & 1 deletion packages/void/src/cli/deploy-cloudflare-preflight.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ import { sameMigrationsDir, writeProvisionedWranglerConfig } from './wrangler.ts
/** Validate source-level native deploy inputs before account operations or project code. */
export async function prepareCloudflareDeploySource(
root: string,
options: RunDeployOptions,
options: RunDeployOptions & { seedConfig: boolean },
voidConfig: VoidConfig,
): Promise<
({ configPath: string } & Awaited<ReturnType<typeof computeDesiredCloudflareResources>>) | null
Expand Down
5 changes: 4 additions & 1 deletion packages/void/src/cli/deploy-cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { detectFramework } from '../plugin-inference.ts';
import { hasOwnKey } from '../shared/has-own-key.ts';
import { readCloudflareCandidate } from './cloudflare-candidate.ts';
import { createCloudflareChildReporter } from './cloudflare-child-report.ts';
import { hasDeployConfigSource } from './cloudflare-deploy/classify.ts';
import { readCloudflareLink } from './cloudflare-link.ts';
import { withRecordedReadinessAccessOrigin } from './cloudflare-readiness.ts';
import {
Expand Down Expand Up @@ -56,6 +57,8 @@ export async function runCloudflareDeploy(
deps = { ...deps, exit };
// One redactor for the whole deploy, so a bearer learned by one child is scrubbed everywhere.
const reporter = createCloudflareChildReporter(cliLog);
const seedConfig =
!initialCloudflareLink && !options.reuseExistingWorker && !hasDeployConfigSource(root);
const voidConfig = readConfig(root);
const atomic = options.atomic === true || voidConfig.deploy?.cloudflare?.mode === 'atomic';
if (atomic && (options.reuseExistingWorker || initialCloudflareLink)) {
Expand Down Expand Up @@ -131,7 +134,7 @@ export async function runCloudflareDeploy(
return exit(1);
}

const source = await prepareCloudflareDeploySource(root, options, voidConfig);
const source = await prepareCloudflareDeploySource(root, { ...options, seedConfig }, voidConfig);
if (!source) {
return exit(1);
}
Expand Down
4 changes: 3 additions & 1 deletion packages/void/src/cli/migrate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,9 @@ export function migrateLegacyVoidConfig(root: string): boolean {
const existing = readFileSync(typedPath, 'utf8');
if (!GENERATED_MARKERS.some((marker) => existing.startsWith(marker))) {
throw new Error(
`migrate: ${TYPED_CONFIG_FILE} already exists. Move the legacy settings into it before deleting the old files.`,
existsSync(join(root, VOID_LOCK_FILE))
? `migrate: ${TYPED_CONFIG_FILE} already exists. Move the legacy settings into it before deleting the old files.`
: `migrate: ${TYPED_CONFIG_FILE} already exists. Rename it to a backup, run \`void migrate\`, then merge your saved settings into the new file and keep the migrated resource IDs.`,
);
}
current = validateConfig(loadTypedVoidConfigFile(typedPath), TYPED_CONFIG_FILE);
Expand Down
36 changes: 33 additions & 3 deletions packages/void/src/config-write.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { createHash } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { join } from 'pathslash';
import { parseSync } from 'vite';
import { loadTypedVoidConfigFile, TYPED_CONFIG_FILE } from './config-loader.ts';
import { validateConfig } from './config.ts';
import type { VoidConfig } from './config.ts';

const DEPLOY_CONFIG_MARKER = '// Generated by void deploy. ';
export const GENERATED_MARKERS: ReadonlyArray<string> = [
'// Generated by void migrate.',
'// Generated from void.json by void migrate.',
Expand All @@ -15,7 +17,30 @@ export function renderVoidConfig(
config: VoidConfig,
marker: string = GENERATED_MARKERS[0],
): string {
return `${marker}\nimport { defineConfig } from 'void/config';\n\nexport default defineConfig(${JSON.stringify(config, null, 2)});\n`;
return `${marker}\n${renderConfigBody(config)}`;
}

function renderConfigBody(config: VoidConfig): string {
return `import { defineConfig } from 'void/config';\n\nexport default defineConfig(${JSON.stringify(config, null, 2)});\n`;
}

function deployConfigMarker(body: string): string {
return DEPLOY_CONFIG_MARKER + createHash('sha256').update(body).digest('hex');
}

export function renderDeploySeedConfig(config: VoidConfig): string {
const body = renderConfigBody(config);
return `${deployConfigMarker(body)}\n${body}`;
}

// Recognize an interrupted deploy's original seed even if the project directory or CLI changes.
export function isUnchangedDeploySeed(source: string): boolean {
if (!source.startsWith(DEPLOY_CONFIG_MARKER)) {
return false;
}
const newline = source.indexOf('\n');
const body = source.slice(newline + 1).replaceAll('\r\n', '\n');
return source.slice(0, newline).trimEnd() === deployConfigMarker(body);
}

type StaticNode = {
Expand Down Expand Up @@ -72,7 +97,12 @@ function isStaticValue(node: StaticNode | null | undefined): boolean {
}

function isGeneratedStaticConfig(source: string): boolean {
if (!GENERATED_MARKERS.some((marker) => source.startsWith(marker))) {
const [line] = source.split('\n', 1);
const marker = line.trimEnd();
const deployMarker =
marker.startsWith(DEPLOY_CONFIG_MARKER) &&
/^[a-f0-9]{64}$/.test(marker.slice(DEPLOY_CONFIG_MARKER.length));
if (!deployMarker && !GENERATED_MARKERS.includes(marker)) {
return false;
}
let program: StaticNode;
Expand All @@ -87,7 +117,7 @@ function isGeneratedStaticConfig(source: string): boolean {
if (
parsed.errors.length > 0 ||
parsed.comments.length !== 1 ||
!GENERATED_MARKERS.includes(`// ${parsed.comments[0]?.value.trim()}`)
`// ${parsed.comments[0]?.value.trim()}` !== marker
) {
return false;
}
Expand Down
Loading