Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[C3] Astro template dev bindings improvements #5072

Merged
merged 5 commits into from
Feb 23, 2024
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
11 changes: 11 additions & 0 deletions .changeset/tricky-beers-push.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"create-cloudflare": minor
---

feature: Improve bindings support in Astro template.

C3 will now create Astro projects configured to use miniflare in dev automatically. This is done by adding a configuration for the adapter of `{ runtime: 'local'}` (see [Astro docs](https://docs.astro.build/en/guides/integrations-guide/cloudflare/#runtime) for more details). A `wrangler.toml` file will also be added where bindings can be added to be used in dev.

Along with this change, projects will now use the default vite-based `astro dev` command instead of using `wrangler pages dev` on build output.

When Typescript is used, the `src/env.d.ts` file will be updated to add type definitions `runtime.env` which can be re-generated with a newly added `build-cf-types` script.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { APIRoute } from "astro";

export const GET: APIRoute = async ({ locals }) => {
const { TEST } = locals.runtime.env;

return new Response(JSON.stringify({ test: TEST }), {
status: 200,
});
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[vars]
TEST = "C3_TEST"
20 changes: 19 additions & 1 deletion packages/create-cloudflare/e2e-tests/frameworks.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import type { Suite } from "vitest";

const TEST_TIMEOUT = 1000 * 60 * 5;
const LONG_TIMEOUT = 1000 * 60 * 10;
const TEST_RETRIES = 1;

type FrameworkTestConfig = RunnerConfig & {
testCommitMessage: boolean;
Expand All @@ -60,6 +61,16 @@ const frameworkTests: Record<string, FrameworkTestConfig> = {
route: "/",
expectedText: "Hello, Astronaut!",
},
verifyDev: {
route: "/test",
expectedText: "C3_TEST",
},
verifyBuild: {
outputDir: "./dist",
script: "build",
route: "/test",
expectedText: "C3_TEST",
},
},
docusaurus: {
unsupportedPms: ["bun"],
Expand Down Expand Up @@ -271,6 +282,10 @@ describe.concurrent(`E2E: Web frameworks`, () => {

const quarantineModeMatch = isQuarantineMode() == (quarantine ?? false);

const retries = process.env.E2E_RETRIES
? parseInt(process.env.E2E_RETRIES)
: TEST_RETRIES;

// If the framework in question is being run in isolation, always run it.
// Otherwise, only run the test if it's configured `quarantine` value matches
// what is set in E2E_QUARANTINE
Expand Down Expand Up @@ -353,7 +368,10 @@ describe.concurrent(`E2E: Web frameworks`, () => {
}
}
},
{ retry: 1, timeout: timeout || TEST_TIMEOUT }
{
retry: retries,
timeout: timeout || TEST_TIMEOUT,
}
);
});
});
Expand Down
1 change: 1 addition & 0 deletions packages/create-cloudflare/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
"deepmerge": "^4.3.1",
"degit": "^2.8.4",
"dns2": "^2.1.0",
"dotenv": "^16.0.0",
"esbuild": "^0.17.12",
"execa": "^7.1.1",
"glob": "^10.3.3",
Expand Down
86 changes: 78 additions & 8 deletions packages/create-cloudflare/templates/astro/c3.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { logRaw } from "@cloudflare/cli";
import { brandColor, dim } from "@cloudflare/cli/colors";
import { logRaw, updateStatus } from "@cloudflare/cli";
import { blue, brandColor, dim } from "@cloudflare/cli/colors";
import { loadTemplateSnippets, transformFile } from "helpers/codemod";
import { runCommand, runFrameworkGenerator } from "helpers/command";
import { compatDateFlag } from "helpers/files";
import { usesTypescript } from "helpers/files";
import { detectPackageManager } from "helpers/packages";
import * as recast from "recast";
import type { TemplateConfig } from "../../src/templates";
import type { C3Context } from "types";
import type { C3Context, PackageJson } from "types";

const { npx } = detectPackageManager();

Expand All @@ -14,27 +16,95 @@ const generate = async (ctx: C3Context) => {
logRaw(""); // newline
};

const configure = async () => {
const configure = async (ctx: C3Context) => {
await runCommand([npx, "astro", "add", "cloudflare", "-y"], {
silent: true,
startText: "Installing adapter",
doneText: `${brandColor("installed")} ${dim(
`via \`${npx} astro add cloudflare\``
)}`,
});

updateAstroConfig();
updateEnvDeclaration(ctx);
};

const updateAstroConfig = () => {
const filePath = "astro.config.mjs";

updateStatus(`Updating configuration in ${blue(filePath)}`);

transformFile(filePath, {
visitCallExpression: function (n) {
const callee = n.node.callee as recast.types.namedTypes.Identifier;
if (callee.name !== "cloudflare") {
return this.traverse(n);
}

const b = recast.types.builders;
n.node.arguments = [
b.objectExpression([
b.objectProperty(
b.identifier("runtime"),
b.objectExpression([
b.objectProperty(b.identifier("mode"), b.stringLiteral("local")),
])
),
]),
];

return false;
},
});
};

const updateEnvDeclaration = (ctx: C3Context) => {
if (!usesTypescript(ctx)) {
return;
}

const filePath = "src/env.d.ts";

updateStatus(`Adding type declarations in ${blue(filePath)}`);

transformFile(filePath, {
visitProgram: function (n) {
const snippets = loadTemplateSnippets(ctx);
const patch = snippets.runtimeDeclarationTs;
const b = recast.types.builders;

// Preserve comments with the new body
const comments = n.get("comments").value;
n.node.comments = comments.map((c: recast.types.namedTypes.CommentLine) =>
b.commentLine(c.value)
);

// Add the patch
n.get("body").push(...patch);

return false;
},
});
};

const config: TemplateConfig = {
configVersion: 1,
id: "astro",
platform: "pages",
displayName: "Astro",
copyFiles: {
path: "./templates",
},
devScript: "dev",
deployScript: "deploy",
jculvey marked this conversation as resolved.
Show resolved Hide resolved
previewScript: "preview",
generate,
configure,
transformPackageJson: async () => ({
transformPackageJson: async (pkgJson: PackageJson, ctx: C3Context) => ({
scripts: {
"pages:dev": `wrangler pages dev ${await compatDateFlag()} -- astro dev`,
"pages:deploy": `astro build && wrangler pages deploy ./dist`,
deploy: `astro build && wrangler pages deploy ./dist`,
preview: `astro build && wrangler pages dev ./dist`,
...(usesTypescript(ctx) && { "build-cf-types": `wrangler types` }),
},
}),
testFlags: [
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
type Runtime = import("@astrojs/cloudflare").DirectoryRuntime<Env>;
declare namespace App {
interface Locals extends Runtime {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
name = "<TBD>"
compatibility_date = "<TBD>"

# Variable bindings. These are arbitrary, plaintext strings (similar to environment variables)
# Note: Use secrets to store sensitive data.
# Docs: https://developers.cloudflare.com/workers/platform/environment-variables
# [vars]
# MY_VARIABLE = "production_value"

# Bind a KV Namespace. Use KV as persistent storage for small key-value pairs.
# Docs: https://developers.cloudflare.com/workers/runtime-apis/kv
# [[kv_namespaces]]
# binding = "MY_KV_NAMESPACE"
# id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# Bind an R2 Bucket. Use R2 to store arbitrarily large blobs of data, such as files.
# Docs: https://developers.cloudflare.com/r2/api/workers/workers-api-usage/
# [[r2_buckets]]
# binding = "MY_BUCKET"
# bucket_name = "my-bucket"

# Bind a Queue producer. Use this binding to schedule an arbitrary task that may be processed later by a Queue consumer.
# Docs: https://developers.cloudflare.com/queues/get-started
# [[queues.producers]]
# binding = "MY_QUEUE"
# queue = "my-queue"

# Bind a Queue consumer. Queue Consumers can retrieve tasks scheduled by Producers to act on them.
# Docs: https://developers.cloudflare.com/queues/get-started
# [[queues.consumers]]
# queue = "my-queue"

# Bind another Worker service. Use this binding to call another Worker without network overhead.
# Docs: https://developers.cloudflare.com/workers/platform/services
# [[services]]
# binding = "MY_SERVICE"
# service = "my-service"

# Bind a Durable Object. Durable objects are a scale-to-zero compute primitive based on the actor model.
# Durable Objects can live for as long as needed. Use these when you need a long-running "server", such as in realtime apps.
# Docs: https://developers.cloudflare.com/workers/runtime-apis/durable-objects
# [[durable_objects.bindings]]
# name = "MY_DURABLE_OBJECT"
# class_name = "MyDurableObject"

# Durable Object migrations.
# Docs: https://developers.cloudflare.com/workers/learning/using-durable-objects#configure-durable-object-classes-with-migrations
# [[migrations]]
# tag = "v1"
# new_classes = ["MyDurableObject"]
2 changes: 1 addition & 1 deletion packages/create-cloudflare/templates/nuxt/c3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,10 @@ const config: TemplateConfig = {
configVersion: 1,
id: "nuxt",
platform: "pages",
displayName: "Nuxt",
copyFiles: {
path: "./templates",
},
displayName: "Nuxt",
devScript: "dev",
deployScript: "deploy",
generate,
Expand Down
3 changes: 2 additions & 1 deletion packages/create-cloudflare/turbo.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"CLOUDFLARE_API_TOKEN",
"FRAMEWORK_CLI_TO_TEST",
"E2E_QUARANTINE",
"E2E_PROJECT_PATH"
"E2E_PROJECT_PATH",
"E2E_RETRIES"
]
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/create-cloudflare/vitest-e2e.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export default defineConfig({
root: ".",
testTimeout: 1000 * 60 * 10, // 10 min for lengthy installs
maxConcurrency: 3,
setupFiles: ["e2e-tests/setup.ts"],
setupFiles: ["e2e-tests/setup.ts", "dotenv/config"],
reporters: ["json", "verbose", "hanging-process"],
outputFile: {
json: "./.e2e-logs/" + process.env.TEST_PM + "/results.json",
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading