### Copy Example Dev Variables Source: https://github.com/codius/codius-workers/blob/main/packages/codius-astro/README.md Copies the example development variables file to be used for local development. This is a bash command used to set up local environment variables. ```bash cp .example.dev.vars .dev.vars ``` -------------------------------- ### Start Local Development Server Source: https://github.com/codius/codius-workers/blob/main/packages/codius-astro/README.md Starts the local development server for the codius-astro project. The server will be accessible at localhost:8788. This command is run using pnpm. ```bash pnpm --filter codius-astro run dev ``` -------------------------------- ### Install Dependencies Source: https://github.com/codius/codius-workers/blob/main/packages/codius-astro/README.md Installs all project dependencies using the pnpm package manager. This command should be run from the root of the monorepo. ```bash pnpm install ``` -------------------------------- ### Get Astro CLI Help Source: https://github.com/codius/codius-workers/blob/main/packages/codius-astro/README.md Displays help information for the Astro CLI, showing available commands and options. This command is run using pnpm. ```bash pnpm --filter codius-astro run astro -- --help ``` -------------------------------- ### Start Local Webhook Proxy Source: https://github.com/codius/codius-workers/blob/main/packages/codius-astro/README.md Starts a local webhook proxy using Smee.io for the codius-astro project. This is useful for testing webhooks during local development. This command is run using pnpm. ```bash pnpm --filter codius-astro run smee ``` -------------------------------- ### Authentication - Lucia and Arctic GitHub OAuth Setup (TypeScript) Source: https://context7.com/codius/codius-workers/llms.txt Initializes authentication using Lucia for session management and Arctic for GitHub OAuth. This includes creating and validating user sessions, and generating authorization URLs for GitHub login. Dependencies include a D1 database instance and crypto module. ```typescript import { initializeLucia, initializeGitHub } from './lib/auth'; // Initialize Lucia auth with D1 database const lucia = initializeLucia(d1Database); // Create a new session for a user const session = await lucia.createSession(userId, {}); const sessionCookie = lucia.createSessionCookie(session.id); // Validate an existing session const { session, user } = await lucia.validateSession(sessionId); if (session?.fresh) { // Extend session expiry const sessionCookie = lucia.createSessionCookie(session.id); } // Initialize GitHub OAuth client const github = initializeGitHub( 'your-github-client-id', 'your-github-client-secret' ); // Generate OAuth authorization URL const state = crypto.randomUUID(); const authUrl = await github.createAuthorizationURL(state, { scopes: ['read:user'] }); // Redirect user to: authUrl // Exchange code for tokens after OAuth callback const tokens = await github.validateAuthorizationCode(code); console.log(tokens.accessToken); ``` -------------------------------- ### Build Production Site Source: https://github.com/codius/codius-workers/blob/main/packages/codius-astro/README.md Builds the production-ready static site for the codius-astro project. The output will be placed in the './dist/' directory. This command is executed via pnpm. ```bash pnpm --filter codius-astro run build ``` -------------------------------- ### Preview Local Build Source: https://github.com/codius/codius-workers/blob/main/packages/codius-astro/README.md Previews the production build of the codius-astro site locally before deploying. This allows for testing the built site in a production-like environment. This command is run using pnpm. ```bash pnpm --filter codius-astro run preview ``` -------------------------------- ### Deploy Codius Astro Site via pnpm Source: https://github.com/codius/codius-workers/blob/main/packages/codius-astro/README.md Deploys the codius-astro site to Cloudflare Pages using the pnpm package manager. This command is executed from the monorepo root. ```bash pnpm --filter codius-astro pages deploy ``` -------------------------------- ### Apply D1 Database Migrations Source: https://github.com/codius/codius-workers/blob/main/packages/codius-astro/README.md These commands apply database migrations to a Cloudflare D1 database. The first command generates migrations using drizzle-kit, and the subsequent commands apply them locally or remotely. It requires pnpm and targets the 'codius-astro' package. ```bash pnpm --filter codius-astro drizzle-kit generate pnpm --filter codius-astro d1 migrations apply --local pnpm --filter codius-astro d1 migrations apply --remote ``` -------------------------------- ### Create D1 Database with Wrangler CLI Source: https://github.com/codius/codius-workers/blob/main/packages/codius-astro/README.md This command creates a new Cloudflare D1 Database instance from the monorepo root. It requires the pnpm package manager and specifies the 'codius-astro' filter. The database name is provided as an argument. ```bash pnpm --filter codius-astro d1 create ``` -------------------------------- ### YAML - GitHub Actions for Worker Deployment Source: https://context7.com/codius/codius-workers/llms.txt Automates the process of building and deploying user-submitted workers using GitHub Actions. The workflow checks out code, detects package managers, sanitizes configuration, bundles the worker, deploys it, and generates attestations for security and provenance. It requires specific inputs for application ID, repository details, and commit information. ```yaml # Trigger the workflow via workflow_dispatch API # POST https://api.github.com/repos/codius/codius-astro/actions/workflows/deploy-worker.yml/dispatches # { # "ref": "main", # "inputs": { # "appId": "cm12abc3def4", # "repo": "username/my-worker", # "commit": "abc123def456", # "ref": "main", # "directory": "src/worker", # "dispatchNamespace": "testing" # } # } # Workflow process: # 1. Checkout user's repository at specified commit # 2. Detect package manager (checks for pnpm-lock.yaml) # 3. Sanitize wrangler.toml (removes D1 databases for security) # 4. Bundle worker code with wrangler deploy --dry-run # 5. Deploy to Workers for Platforms dispatch namespace # 6. Generate build provenance attestation # 7. Create cryptographic attestation linking deployed worker to source code # The workflow outputs: # - Deployed worker accessible at: https://{appId}.codius-workers.pages.dev # - Attestation bundle downloadable from GitHub # - Worker script artifact stored in GitHub Actions ``` -------------------------------- ### Create and Deploy Worker App - TypeScript Source: https://context7.com/codius/codius-workers/llms.txt Creates and deploys a new worker application from a specified GitHub repository. It validates the URL, extracts repository information, fetches the commit hash, and initiates the deployment process. Returns the application ID upon successful creation. Includes error handling for unauthorized access, existing applications, and invalid repository details. ```typescript import { actions } from 'astro:actions'; // Create a new worker app from a GitHub repository // Validates the URL, extracts repo info, fetches commit hash, and triggers deployment const result = await actions.app.create({ githubUrl: 'https://github.com/username/repo/tree/main/worker-dir' }); // Returns the app ID for the newly created worker console.log(result.data.appId); // e.g., 'cm12abc3def4' // Error handling for various scenarios try { const result = await actions.app.create({ githubUrl: 'https://github.com/myorg/myworker' }); } catch (error) { if (error.code === 'UNAUTHORIZED') { // User not logged in } else if (error.code === 'CONFLICT') { // App with these details already exists } else if (error.code === 'BAD_REQUEST') { // Invalid GitHub URL or repo not accessible } } ``` -------------------------------- ### Run Astro CLI Commands Source: https://github.com/codius/codius-workers/blob/main/packages/codius-astro/README.md Executes Astro CLI commands for the codius-astro project, such as adding integrations or checking the project. The '--' is used to pass arguments to the Astro CLI. ```bash pnpm --filter codius-astro run astro ... ``` -------------------------------- ### Bash - User Request to Deployed Worker Source: https://context7.com/codius/codius-workers/llms.txt Illustrates the initial step of a user making a request to their deployed worker. This command shows how a client would interact with a worker hosted on the codius-workers.pages.dev domain. The subsequent 'Internal flow' implies that this request triggers a series of internal processes managed by Codius Workers, including billing checks. ```bash # User makes request to their deployed worker curl https://my-worker.codius-workers.pages.dev/api/hello # Internal flow: ``` -------------------------------- ### Dispatch Worker - Request Routing and Billing (TypeScript) Source: https://context7.com/codius/codius-workers/llms.txt Handles incoming requests by routing them to the appropriate user worker. It includes extracting the worker name from the subdomain, checking billing balances, and forwarding the request to the user's worker. This code runs on Cloudflare Workers and requires environment variables for API tokens and bindings. ```typescript // Deployed at: https://{workerName}.codius-workers.pages.dev export default { async fetch(request, env, ctx): Promise { const cloudflare = new Cloudflare({ apiToken: env.CLOUDFLARE_API_TOKEN }); // Extract worker name from subdomain const workerName = new URL(request.url).host.split('.')[0]; // Special endpoint: Get worker script information if (new URL(request.url).pathname === '/.well-known/codius') { const { script } = await cloudflare.workersForPlatforms .dispatch.namespaces.scripts.get( env.DISPATCH_NAMESPACE, workerName, { account_id: env.CLOUDFLARE_ACCOUNT_ID } ); return Response.json(script); } // Check billing balance and increment request count const billingId = env.BILLING_DURABLE_OBJECT.idFromName(workerName); const billing = env.BILLING_DURABLE_OBJECT.get(billingId); try { await billing.incrementWorkerRequests(); } catch (e) { if (isLimitExceededError(e)) { // Redirect to payment page when quota exceeded return new Response(null, { status: 302, headers: { Location: `https://codius-workers.pages.dev/apps/${workerName}/402` } }); } throw e; } // Forward request to user worker const userWorker = env.DISPATCH_NAMESPACE_BINDING.get(workerName); return await userWorker.fetch(request); } } ``` -------------------------------- ### GitHub API Integration - Repository and Workflow Operations (TypeScript) Source: https://context7.com/codius/codius-workers/llms.txt Provides functions to interact with the GitHub API for repository and workflow management. It includes fetching commit details, retrieving the default branch, and triggering deployment workflows. Requires a GitHub access token and uses functions from './lib/github'. ```typescript import { getCommit, getDefaultBranch, triggerWorkflow } from './lib/github'; // Get commit information for a specific ref const commit = await getCommit({ owner: 'username', repo: 'my-worker', ref: 'main' // Can be branch, tag, or commit SHA }); console.log(commit.sha); // Full commit hash console.log(commit.commit.message); // Get the default branch for a repository const defaultBranch = await getDefaultBranch({ owner: 'username', repo: 'my-worker' }); console.log(defaultBranch); // e.g., 'main' or 'master' // Trigger the deployment workflow // This dispatches to codius/codius-astro's deploy-worker.yml workflow await triggerWorkflow(githubAccessToken, { appId: 'cm12abc3def4', owner: 'username', repo: 'my-worker', commitHash: 'abc123def456', gitRef: 'main', directory: 'src/worker', dispatchNamespace: 'testing' }); ``` -------------------------------- ### TOML - Codius Workers Environment Configuration Source: https://context7.com/codius/codius-workers/llms.txt Defines the necessary environment variables, bindings, and secrets for both the Astro web application and the dispatch worker within the Codius Workers platform. This includes settings for GitHub integration, Cloudflare services, and Stripe payments. Secrets must be managed securely using `wrangler secret put`. ```toml # packages/codius-astro/wrangler.toml - Astro web application [vars] GITHUB_APP_NAME = "Codius Workers" GITHUB_CLIENT_ID = "your-github-client-id" CF_DISPATCH_NAMESPACE = "testing" DISPATCHER_HOSTNAME = "coil.app" # Secrets (set via: wrangler secret put SECRET_NAME) # GITHUB_CLIENT_SECRET - GitHub OAuth app secret # GITHUB_ACCESS_TOKEN - GitHub personal access token for workflow dispatch # CLOUDFLARE_API_TOKEN - Cloudflare API token with Workers permissions # CLOUDFLARE_ACCOUNT_ID - Cloudflare account ID # STRIPE_SECRET_KEY - Stripe secret key for checkout sessions # STRIPE_TOPUP_PRICE_ID - Stripe price ID for top-up product [[d1_databases]] binding = "DB" database_name = "codius-workers" database_id = "your-database-id" [[durable_objects.bindings]] name = "BILLING_DURABLE_OBJECT" class_name = "BillingDurableObject" script_name = 'dispatcher' # packages/dispatch-worker/wrangler.toml - Dispatch worker [vars] DISPATCH_NAMESPACE = "testing" REQUEST_UNIT_PRICE_NANO_USD = "300000000" TOTAL_REQUESTS_PER_UNIT = "1000000" INCLUDED_REQUESTS = "100" # Secrets # CLOUDFLARE_API_TOKEN - Cloudflare API token # CLOUDFLARE_ACCOUNT_ID - Cloudflare account ID [[dispatch_namespaces]] binding = "DISPATCH_NAMESPACE_BINDING" namespace = "testing" [[durable_objects.bindings]] name = "BILLING_DURABLE_OBJECT" class_name = "BillingDurableObject" ``` -------------------------------- ### Bash - Retrieve Deployed Worker Script Metadata Source: https://context7.com/codius/codius-workers/llms.txt Demonstrates how to fetch metadata for a deployed worker script using a simple curl command to a specific API endpoint. The endpoint returns JSON data including the worker's ID, script content, ETag, handlers, and creation/modification timestamps. This is useful for verifying deployment and inspecting worker details. ```bash # Get worker script information curl https://worker-id.codius-workers.pages.dev/.well-known/codius # Response (example): # { # "id": "worker-id", # "script": "export default { async fetch(request) { return new Response('Hello'); } }", # "etag": "abc123", # "handlers": ["fetch"], # "created_on": "2024-01-01T00:00:00.000Z", # "modified_on": "2024-01-01T00:00:00.000Z" # } ``` -------------------------------- ### Create Stripe Checkout Session - TypeScript Source: https://context7.com/codius/codius-workers/llms.txt Creates a Stripe checkout session for adding funds to a worker's balance. It requires the application ID and returns a URL to redirect the user to Stripe's payment page. The session includes metadata for tracking the application and user. After payment, users are redirected to a success or cancellation URL. ```typescript import { actions } from 'astro:actions'; // Create a Stripe checkout session for worker top-up // Returns a URL to redirect the user to Stripe's payment page const checkoutUrl = await actions.checkoutSession.create({ appId: 'cm12abc3def4' }); // Redirect user to Stripe checkout window.location.href = checkoutUrl; // After payment, user is redirected to: /checkout-sessions/{CHECKOUT_SESSION_ID}/success // On cancel, redirected to: /?canceled=true // The checkout session includes metadata for tracking: // - appId: The worker app being funded // - userId: The user making the payment (if logged in) ``` -------------------------------- ### TypeScript - Track and Manage Worker Billing Source: https://context7.com/codius/codius-workers/llms.txt Implements billing logic for tracking request usage and managing payments for individual workers using Cloudflare Durable Objects. It handles incrementing request counts, checking limits, and adding funds. Dependencies include the 'billing-durable-object' library. ```typescript import { BillingDurableObject, isLimitExceededError } from 'billing-durable-object'; // Environment configuration (set in wrangler.toml) const env = { REQUEST_UNIT_PRICE_NANO_USD: '300000000', // $0.30 per million requests TOTAL_REQUESTS_PER_UNIT: '1000000', // 1 million requests per unit INCLUDED_REQUESTS: '100' // 100 free requests }; // Get billing information for a worker const billingId = env.BILLING_DURABLE_OBJECT.idFromName('worker-id'); const billing = env.BILLING_DURABLE_OBJECT.get(billingId); const billingInfo = await billing.getWorkerBilling(); console.log(billingInfo); // { // requests: { // total: 1500n, // totalAllowed: 1000100n // }, // funding: { // totalNanoUSD: 300000000n // }, // pricing: { // unitPriceNanoUSD: 300000000n, // requestsPerUnit: 1000000n, // includedRequests: 100n // } // } // Increment request count (throws if limit exceeded) try { await billing.incrementWorkerRequests(); } catch (error) { if (isLimitExceededError(error)) { // Handle quota exceeded console.log('Request limit exceeded'); } } // Add funds to increase allowed requests // After successful Stripe payment const amountNanoUSD = 300000000n; // $0.30 await billing.addWorkerFunds(amountNanoUSD); // This automatically recalculates totalAllowedRequests: // totalAllowed = INCLUDED_REQUESTS + (totalFundingNanoUSD * requestsPerUnit) / unitPriceNanoUSD ``` -------------------------------- ### App Database Schema - TypeScript Source: https://context7.com/codius/codius-workers/llms.txt Defines the structure for worker application records in the database, including deployment status and GitHub repository information. It specifies fields like ID, user ID, repository details, commit hash, status, and timestamps. This schema is used with Drizzle ORM and Cloudflare D1. ```typescript import { drizzle } from 'drizzle-orm/d1'; import * as schema from './schema'; const db = drizzle(d1Database, { schema }); // App record structure type App = { id: string; // Auto-generated CUID userId: string; // Reference to users table githubOwner: string; // GitHub repo owner repo: string; // Repository name gitRef: string; // Branch/tag reference commitHash: string; // Specific commit directory: string; // Subdirectory path (default: '') status: 'deployed' | 'failed' | 'pending'; githubWorkflowRunId: number | null; createdAt: Date; updatedAt: Date; deletedAt: Date | null; }; // Unique constraint on: userId, githubOwner, repo, commitHash, directory, deletedAt // This prevents duplicate deployments of the same code ``` -------------------------------- ### Database API - Apps Class Operations (TypeScript) Source: https://context7.com/codius/codius-workers/llms.txt Manages worker applications in the database using CRUD operations. Supports creating, retrieving, updating, and deleting application records. It requires a database instance (e.g., d1Database) and interacts with the './lib/db/apps' module. ```typescript import { Apps } from './lib/db/apps'; const apps = new Apps(d1Database); // Create a new app const app = await apps.create({ userId: 'cm1user123', githubOwner: 'username', repo: 'my-worker', gitRef: 'main', commitHash: 'abc123def456', directory: 'src/worker' }); // Get all apps for a user (ordered by creation date, newest first) const userApps = await apps.getByUserId('cm1user123'); // Get a single app by ID (includes deployer user info) const singleApp = await apps.getById('cm12abc3def4'); // Update workflow run ID after triggering GitHub Actions await apps.updateGitHubWorkflowRunId('cm12abc3def4', 12345678); // Update deployment status (called by GitHub webhook) await apps.updateStatus({ githubWorkflowRunId: 12345678, status: 'deployed' }); // Soft delete an app const deletedApp = await apps.delete({ id: 'cm12abc3def4', userId: 'cm1user123' }); ``` -------------------------------- ### Remove Local D1 Migrations State Source: https://github.com/codius/codius-workers/blob/main/packages/codius-astro/README.md This command removes the local state files for D1 database migrations. It is used for rolling back local changes and requires the 'rm' command. The path targets the specific state files within the .wrangler directory. ```bash rm packages/codius-astro/.wrangler/state/v3/d1/miniflare-D1DatabaseObject/* ``` -------------------------------- ### Delete Worker App - TypeScript Source: https://context7.com/codius/codius-workers/llms.txt Deletes a deployed worker application and removes it from the dispatch namespace. It requires the application ID for deletion. Returns a success status upon successful removal. Includes error handling for unauthorized access and cases where the application is not found. ```typescript import { actions } from 'astro:actions'; // Delete an existing worker app // Removes from database and Cloudflare Workers for Platforms namespace const result = await actions.app.delete({ id: 'cm12abc3def4' }); console.log(result.data.success); // true // Error handling try { await actions.app.delete({ id: 'invalid-id' }); } catch (error) { if (error.code === 'UNAUTHORIZED') { // User not logged in } else if (error.code === 'NOT_FOUND') { // App not found or doesn't belong to user } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.