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
19 changes: 13 additions & 6 deletions packages/integrations/cloudflare/src/wrangler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ interface CloudflareConfigOptions {
imagesBindingName?: string | false | undefined;
}

type KVNamespace = NonNullable<WorkerConfig['kv_namespaces']>[number];

function withSessionKVBinding(
existing: KVNamespace[] | undefined,
sessionBinding: string,
): KVNamespace[] {
const namespaces: KVNamespace[] = existing ? [...existing] : [];
namespaces.push({ binding: sessionBinding });
return namespaces;
}

/**
* Returns a config customizer that sets up the Astro Cloudflare defaults.
* Sets the main entrypoint and adds bindings for auto-provisioning.
Expand All @@ -36,19 +47,15 @@ export function cloudflareConfigCustomizer(
nonInheritableConfig: WorkerConfig['previews'],
): WorkerConfig['previews'] => {
const hasSessionBinding = nonInheritableConfig?.kv_namespaces?.some(
(kv) => kv.binding === sessionKVBindingName,
(kv: KVNamespace) => kv.binding === sessionKVBindingName,
);
const hasImagesBinding = nonInheritableConfig?.images?.binding !== undefined;

return {
kv_namespaces:
!needsSessionKVBinding || hasSessionBinding
? undefined
: [
{
binding: sessionKVBindingName,
},
],
: withSessionKVBinding(nonInheritableConfig?.kv_namespaces, sessionKVBindingName),
images:
hasImagesBinding || !imagesBindingName
? undefined
Expand Down
19 changes: 18 additions & 1 deletion packages/integrations/cloudflare/test/wrangler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ describe('cloudflareConfigCustomizer', () => {
kv_namespaces: [{ binding: 'OTHER_KV', id: 'other-id' }],
});

assert.deepEqual(result.kv_namespaces, [{ binding: DEFAULT_SESSION_KV_BINDING_NAME }]);
assert.deepEqual(result.kv_namespaces, [
{ binding: 'OTHER_KV', id: 'other-id' },
{ binding: DEFAULT_SESSION_KV_BINDING_NAME },
]);
});

it('does not add SESSION binding when session KV binding is disabled', () => {
Expand Down Expand Up @@ -157,6 +160,20 @@ describe('cloudflareConfigCustomizer', () => {
assert.equal(result.previews?.images, undefined);
});

it('preserves existing previews KV bindings when adding SESSION binding', () => {
const customizer = cloudflareConfigCustomizer();
const result = customizer({
previews: {
kv_namespaces: [{ binding: 'OTHER_KV', id: 'other-id' }],
},
});

assert.deepEqual(result.previews?.kv_namespaces, [
{ binding: 'OTHER_KV', id: 'other-id' },
{ binding: DEFAULT_SESSION_KV_BINDING_NAME },
]);
});

it('adds SESSION binding to previews even when top-level has it', () => {
const customizer = cloudflareConfigCustomizer();
const result = customizer({
Expand Down
Loading