Skip to content

Commit

Permalink
refactors runtime
Browse files Browse the repository at this point in the history
  • Loading branch information
alexanderniebuhr committed Mar 22, 2024
1 parent 5881358 commit a7e5a79
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 750 deletions.
8 changes: 2 additions & 6 deletions packages/cloudflare/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 +31,19 @@
"@astrojs/underscore-redirects": "^0.3.3",
"@cloudflare/workers-types": "^4.20240320.1",
"miniflare": "^3.20240314.0",
"@iarna/toml": "^2.2.5",
"dotenv": "^16.3.1",
"esbuild": "^0.19.5",
"find-up": "^6.3.0",
"tiny-glob": "^0.2.9"
"tiny-glob": "^0.2.9",
"wrangler": "^3.36.0"
},
"peerDependencies": {
"astro": "^4.2.0"
},
"devDependencies": {
"execa": "^8.0.1",
"fast-glob": "^3.3.2",
"@types/iarna__toml": "^2.0.2",
"strip-ansi": "^7.1.0",
"astro": "^4.5.8",
"cheerio": "1.0.0-rc.12",
"wrangler": "^3.36.0",
"@astrojs/test-utils": "workspace:*",
"astro-scripts": "workspace:*"
},
Expand Down
70 changes: 25 additions & 45 deletions packages/cloudflare/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { AstroConfig, AstroIntegration, RouteData } from 'astro';
import type { LocalPagesRuntime, LocalWorkersRuntime, RUNTIME } from './utils/local-runtime.js';

import * as fs from 'node:fs';
import * as os from 'node:os';
Expand All @@ -12,11 +11,11 @@ import glob from 'tiny-glob';
import { getAdapter } from './getAdapter.js';
import { deduplicatePatterns } from './utils/deduplicatePatterns.js';
import { prepareImageConfig } from './utils/image-config.js';
import { getLocalRuntime, getRuntimeConfig } from './utils/local-runtime.js';
import { prependForwardSlash } from './utils/prependForwardSlash.js';
import { rewriteWasmImportPath } from './utils/rewriteWasmImportPath.js';
import { patchSharpBundle } from './utils/sharpBundlePatch.js';
import { wasmModuleLoader } from './utils/wasm-module-loader.js';
import { getPlatformProxy } from 'wrangler';

export type { AdvancedRuntime } from './entrypoints/server.advanced.js';

Expand All @@ -36,22 +35,18 @@ export type Options = {
exclude?: string[];
};
/**
* { mode: 'off' }: current behaviour (wrangler is needed)
* { mode: 'local', ... }: adds cf request object, locals bindings, env vars/secrets which are defined by the user to `astro.dev` with `Astro.locals.runtime` / `context.locals.runtime`
* Proxy configuration for the platform.
*/
runtime?:
| { mode: 'off' }
| {
mode: Extract<RUNTIME, { type: 'pages' }>['mode'];
type: Extract<RUNTIME, { type: 'pages' }>['type'];
persistTo?: Extract<RUNTIME, { type: 'pages' }>['persistTo'];
bindings?: Extract<RUNTIME, { type: 'pages' }>['bindings'];
}
| {
mode: Extract<RUNTIME, { type: 'workers' }>['mode'];
type: Extract<RUNTIME, { type: 'workers' }>['type'];
persistTo?: Extract<RUNTIME, { type: 'workers' }>['persistTo'];
};
platformProxy?: {
/** Toggle the proxy. Default `undefined`, which equals to `false`. */
enabled?: boolean;
/** Path to the configuration file. Default `wrangler.toml`. */
configPath?: string;
/** Enable experimental support for JSON configuration. Default `false`. */
experimentalJsonConfig?: boolean;
/** Configuration persistence settings. Default '.wrangler/state/v3' */
persist?: boolean | { path: string };
};
wasmModuleImports?: boolean;
};

Expand All @@ -66,12 +61,9 @@ interface BuildConfig {
export default function createIntegration(args?: Options): AstroIntegration {
let _config: AstroConfig;
let _buildConfig: BuildConfig;
let _localRuntime: LocalPagesRuntime | LocalWorkersRuntime;

const SERVER_BUILD_FOLDER = '/$server_build/';

const runtimeMode = getRuntimeConfig(args?.runtime);

return {
name: '@astrojs/cloudflare',
hooks: {
Expand Down Expand Up @@ -112,41 +104,29 @@ export default function createIntegration(args?: Options): AstroIntegration {
);
}
},
'astro:server:setup': ({ server, logger }) => {
if (runtimeMode.mode === 'local') {
server.middlewares.use(async function middleware(req, res, next) {
_localRuntime = getLocalRuntime(_config, runtimeMode, logger);
'astro:server:setup': async ({ server, logger }) => {
if (args?.platformProxy?.enabled === true) {
const platformProxy = await getPlatformProxy({
configPath: args.platformProxy.configPath ?? 'wrangler.toml',
experimentalJsonConfig: args.platformProxy.experimentalJsonConfig ?? false,
persist: args.platformProxy.persist ?? true,
});

const bindings = await _localRuntime.getBindings();
const secrets = await _localRuntime.getSecrets();
const caches = await _localRuntime.getCaches();
const cf = await _localRuntime.getCF();
const clientLocalsSymbol = Symbol.for('astro.locals');

const clientLocalsSymbol = Symbol.for('astro.locals');
server.middlewares.use(async function middleware(req, res, next) {
Reflect.set(req, clientLocalsSymbol, {
runtime: {
env: {
CF_PAGES_URL: `http://${req.headers.host}`,
...bindings,
...secrets,
},
cf: cf,
caches: caches,
waitUntil: (_promise: Promise<any>) => {
return;
},
env: platformProxy.env,
cf: platformProxy.cf,
caches: platformProxy.caches,
ctx: platformProxy.ctx,
},
});
next();
});
}
},
'astro:server:done': async ({ logger }) => {
if (_localRuntime) {
logger.info('Cleaning up the local Cloudflare runtime.');
await _localRuntime.dispose();
}
},
'astro:build:setup': ({ vite, target }) => {
if (target === 'server') {
vite.resolve ||= {};
Expand Down
139 changes: 0 additions & 139 deletions packages/cloudflare/src/tmp-types.d.ts

This file was deleted.

Loading

0 comments on commit a7e5a79

Please sign in to comment.