@astrojs/cloudflare 7.7.1 → 8.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,50 +1,27 @@
1
- import { createRedirectsFromAstroRoutes } from '@astrojs/underscore-redirects';
2
- import { AstroError } from 'astro/errors';
3
- import esbuild from 'esbuild';
4
- import { Miniflare } from 'miniflare';
5
1
  import * as fs from 'node:fs';
6
2
  import * as os from 'node:os';
7
3
  import { dirname, relative, sep } from 'node:path';
8
4
  import { fileURLToPath, pathToFileURL } from 'node:url';
5
+ import { createRedirectsFromAstroRoutes } from '@astrojs/underscore-redirects';
6
+ import { AstroError } from 'astro/errors';
7
+ import esbuild from 'esbuild';
9
8
  import glob from 'tiny-glob';
10
9
  import { getAdapter } from './getAdapter.js';
11
10
  import { deduplicatePatterns } from './utils/deduplicatePatterns.js';
12
- import { getCFObject } from './utils/getCFObject.js';
13
11
  import { prepareImageConfig } from './utils/image-config.js';
14
- import { getD1Bindings, getDOBindings, getEnvVars, getKVBindings, getR2Bindings, } from './utils/parser.js';
12
+ import { getLocalRuntime, getRuntimeConfig } from './utils/local-runtime.js';
15
13
  import { prependForwardSlash } from './utils/prependForwardSlash.js';
16
14
  import { rewriteWasmImportPath } from './utils/rewriteWasmImportPath.js';
17
15
  import { wasmModuleLoader } from './utils/wasm-module-loader.js';
18
- const RUNTIME_WARNING = `You are using a deprecated string format for the \`runtime\` API. Please update to the current format for better support.
19
-
20
- Example:
21
- Old Format: 'local'
22
- Current Format: { mode: 'local', persistTo: '.wrangler/state/v3' }
23
-
24
- Please refer to our runtime documentation for more details on the format. https://docs.astro.build/en/guides/integrations-guide/cloudflare/#runtime`;
25
16
  export default function createIntegration(args) {
26
17
  let _config;
27
18
  let _buildConfig;
28
- let _mf;
19
+ let _localRuntime;
29
20
  let _entryPoints = new Map();
30
21
  const SERVER_BUILD_FOLDER = '/$server_build/';
31
22
  const isModeDirectory = args?.mode === 'directory';
32
23
  const functionPerRoute = args?.functionPerRoute ?? false;
33
- let runtimeMode = { mode: 'off' };
34
- if (args?.runtime === 'remote') {
35
- runtimeMode = { mode: 'remote' };
36
- }
37
- else if (args?.runtime === 'local') {
38
- runtimeMode = { mode: 'local', persistTo: '.wrangler/state/v3' };
39
- }
40
- else if (typeof args?.runtime === 'object' &&
41
- args?.runtime.mode === 'local' &&
42
- args.runtime.persistTo === undefined) {
43
- runtimeMode = { mode: 'local', persistTo: '.wrangler/state/v3' };
44
- }
45
- else if (args?.runtime) {
46
- runtimeMode = args?.runtime;
47
- }
24
+ const runtimeMode = getRuntimeConfig(args?.runtime);
48
25
  return {
49
26
  name: '@astrojs/cloudflare',
50
27
  hooks: {
@@ -68,7 +45,7 @@ export default function createIntegration(args) {
68
45
  image: prepareImageConfig(args?.imageService ?? 'DEFAULT', config.image, command, logger),
69
46
  });
70
47
  },
71
- 'astro:config:done': ({ setAdapter, config, logger }) => {
48
+ 'astro:config:done': ({ setAdapter, config }) => {
72
49
  setAdapter(getAdapter({ isModeDirectory, functionPerRoute }));
73
50
  _config = config;
74
51
  _buildConfig = config.build;
@@ -78,97 +55,38 @@ export default function createIntegration(args) {
78
55
  if (_config.base === SERVER_BUILD_FOLDER) {
79
56
  throw new AstroError('[@astrojs/cloudflare] `base: "${SERVER_BUILD_FOLDER}"` is not allowed. Please change your `base` config to something else.');
80
57
  }
81
- if (typeof args?.runtime === 'string') {
82
- logger.warn(RUNTIME_WARNING);
83
- }
84
58
  },
85
- 'astro:server:setup': ({ server }) => {
59
+ 'astro:server:setup': ({ server, logger }) => {
86
60
  if (runtimeMode.mode === 'local') {
87
- const typedRuntimeMode = runtimeMode;
88
61
  server.middlewares.use(async function middleware(req, res, next) {
89
- try {
90
- const cf = await getCFObject(typedRuntimeMode.mode);
91
- const vars = await getEnvVars();
92
- const D1Bindings = await getD1Bindings();
93
- const R2Bindings = await getR2Bindings();
94
- const KVBindings = await getKVBindings();
95
- const DOBindings = await getDOBindings();
96
- let bindingsEnv = new Object({});
97
- // fix for the error "kj/filesystem-disk-unix.c++:1709: warning: PWD environment variable doesn't match current directory."
98
- // note: This mismatch might be primarily due to the test runner.
99
- const originalPWD = process.env.PWD;
100
- process.env.PWD = process.cwd();
101
- _mf = new Miniflare({
102
- modules: true,
103
- script: '',
104
- cache: true,
105
- cachePersist: `${typedRuntimeMode.persistTo}/cache`,
106
- cacheWarnUsage: true,
107
- d1Databases: D1Bindings,
108
- d1Persist: `${typedRuntimeMode.persistTo}/d1`,
109
- r2Buckets: R2Bindings,
110
- r2Persist: `${typedRuntimeMode.persistTo}/r2`,
111
- kvNamespaces: KVBindings,
112
- kvPersist: `${typedRuntimeMode.persistTo}/kv`,
113
- durableObjects: DOBindings,
114
- durableObjectsPersist: `${typedRuntimeMode.persistTo}/do`,
115
- });
116
- await _mf.ready;
117
- for (const D1Binding of D1Bindings) {
118
- const db = await _mf.getD1Database(D1Binding);
119
- Reflect.set(bindingsEnv, D1Binding, db);
120
- }
121
- for (const R2Binding of R2Bindings) {
122
- const bucket = await _mf.getR2Bucket(R2Binding);
123
- Reflect.set(bindingsEnv, R2Binding, bucket);
124
- }
125
- for (const KVBinding of KVBindings) {
126
- const namespace = await _mf.getKVNamespace(KVBinding);
127
- Reflect.set(bindingsEnv, KVBinding, namespace);
128
- }
129
- for (const key in DOBindings) {
130
- if (Object.prototype.hasOwnProperty.call(DOBindings, key)) {
131
- const DO = await _mf.getDurableObjectNamespace(key);
132
- Reflect.set(bindingsEnv, key, DO);
133
- }
134
- }
135
- const mfCache = await _mf.getCaches();
136
- process.env.PWD = originalPWD;
137
- const clientLocalsSymbol = Symbol.for('astro.locals');
138
- Reflect.set(req, clientLocalsSymbol, {
139
- runtime: {
140
- env: {
141
- // default binding for static assets will be dynamic once we support mocking of bindings
142
- ASSETS: {},
143
- // this is just a VAR for CF to change build behavior, on dev it should be 0
144
- CF_PAGES: '0',
145
- // will be fetched from git dynamically once we support mocking of bindings
146
- CF_PAGES_BRANCH: 'TBA',
147
- // will be fetched from git dynamically once we support mocking of bindings
148
- CF_PAGES_COMMIT_SHA: 'TBA',
149
- CF_PAGES_URL: `http://${req.headers.host}`,
150
- ...bindingsEnv,
151
- ...vars,
152
- },
153
- cf: cf,
154
- waitUntil: (_promise) => {
155
- return;
156
- },
157
- caches: mfCache,
62
+ _localRuntime = getLocalRuntime(_config, runtimeMode, logger);
63
+ const bindings = await _localRuntime.getBindings();
64
+ const secrets = await _localRuntime.getSecrets();
65
+ const caches = await _localRuntime.getCaches();
66
+ const cf = await _localRuntime.getCF();
67
+ const clientLocalsSymbol = Symbol.for('astro.locals');
68
+ Reflect.set(req, clientLocalsSymbol, {
69
+ runtime: {
70
+ env: {
71
+ CF_PAGES_URL: `http://${req.headers.host}`,
72
+ ...bindings,
73
+ ...secrets,
158
74
  },
159
- });
160
- next();
161
- }
162
- catch {
163
- next();
164
- }
75
+ cf: cf,
76
+ caches: caches,
77
+ waitUntil: (_promise) => {
78
+ return;
79
+ },
80
+ },
81
+ });
82
+ next();
165
83
  });
166
84
  }
167
85
  },
168
86
  'astro:server:done': async ({ logger }) => {
169
- if (_mf) {
170
- logger.info('Cleaning up the Miniflare instance, and shutting down the workerd server.');
171
- await _mf.dispose();
87
+ if (_localRuntime) {
88
+ logger.info('Cleaning up the local Cloudflare runtime.');
89
+ await _localRuntime.dispose();
172
90
  }
173
91
  },
174
92
  'astro:build:setup': ({ vite, target }) => {
@@ -209,8 +127,7 @@ export default function createIntegration(args) {
209
127
  if (isModeDirectory) {
210
128
  await fs.promises.mkdir(functionsUrl, { recursive: true });
211
129
  }
212
- // TODO: remove _buildConfig.split in Astro 4.0
213
- if (isModeDirectory && (_buildConfig.split || functionPerRoute)) {
130
+ if (isModeDirectory && functionPerRoute) {
214
131
  const entryPointsURL = [..._entryPoints.values()];
215
132
  const entryPaths = entryPointsURL.map((entry) => fileURLToPath(entry));
216
133
  const outputUrl = new URL('$astro', _buildConfig.server);
@@ -276,7 +193,7 @@ export default function createIntegration(args) {
276
193
  : [rewriteWasmImportPath({ relativePathToAssets })],
277
194
  });
278
195
  }
279
- const outputFiles = await glob(`**/*`, {
196
+ const outputFiles = await glob('**/*', {
280
197
  cwd: outputDir,
281
198
  filesOnly: true,
282
199
  });
@@ -398,17 +315,14 @@ export default function createIntegration(args) {
398
315
  .map((route) => {
399
316
  if (route.component === 'src/pages/404.astro' && route.prerender === false)
400
317
  notFoundIsSSR = true;
401
- const includePattern = '/' +
402
- route.segments
403
- .flat()
404
- .map((segment) => (segment.dynamic ? '*' : segment.content))
405
- .join('/');
406
- const regexp = new RegExp('^\\/' +
407
- route.segments
408
- .flat()
409
- .map((segment) => (segment.dynamic ? '(.*)' : segment.content))
410
- .join('\\/') +
411
- '$');
318
+ const includePattern = `/${route.segments
319
+ .flat()
320
+ .map((segment) => (segment.dynamic ? '*' : segment.content))
321
+ .join('/')}`;
322
+ const regexp = new RegExp(`^\\/${route.segments
323
+ .flat()
324
+ .map((segment) => (segment.dynamic ? '(.*)' : segment.content))
325
+ .join('\\/')}$`);
412
326
  return {
413
327
  includePattern,
414
328
  regexp,
@@ -421,7 +335,7 @@ export default function createIntegration(args) {
421
335
  }))
422
336
  .filter((file) => cloudflareSpecialFiles.indexOf(file) < 0)
423
337
  .map((file) => `/${file.replace(/\\/g, '/')}`);
424
- for (let page of pages) {
338
+ for (const page of pages) {
425
339
  let pagePath = prependForwardSlash(page.pathname);
426
340
  if (_config.base !== '/') {
427
341
  const base = _config.base.endsWith('/') ? _config.base.slice(0, -1) : _config.base;
@@ -443,13 +357,11 @@ export default function createIntegration(args) {
443
357
  if (parts.length < 2) {
444
358
  return null;
445
359
  }
446
- else {
447
- // convert /products/:id to /products/*
448
- return (parts[0]
449
- .replace(/\/:.*?(?=\/|$)/g, '/*')
450
- // remove query params as they are not supported by cloudflare
451
- .replace(/\?.*$/, ''));
452
- }
360
+ // convert /products/:id to /products/*
361
+ return (parts[0]
362
+ .replace(/\/:.*?(?=\/|$)/g, '/*')
363
+ // remove query params as they are not supported by cloudflare
364
+ .replace(/\?.*$/, ''));
453
365
  })
454
366
  .filter((line, index, arr) => line !== null && arr.indexOf(line) === index);
455
367
  if (redirects.length > 0) {
package/dist/util.js CHANGED
@@ -4,10 +4,7 @@ export function getProcessEnvProxy() {
4
4
  get: (target, prop) => {
5
5
  console.warn(
6
6
  // NOTE: \0 prevents Vite replacement
7
- `Unable to access \`import.meta\0.env.${prop.toString()}\` on initialization ` +
8
- `as the Cloudflare platform only provides the environment variables per request. ` +
9
- `Please move the environment variable access inside a function ` +
10
- `that's only called after a request has been received.`);
7
+ `Unable to access \`import.meta\0.env.${prop.toString()}\` on initialization as the Cloudflare platform only provides the environment variables per request. Please move the environment variable access inside a function that's only called after a request has been received.`);
11
8
  },
12
9
  });
13
10
  }
@@ -8,14 +8,14 @@ export function matchHostname(url, hostname, allowWildcard) {
8
8
  if (!hostname) {
9
9
  return true;
10
10
  }
11
- else if (!allowWildcard || !hostname.startsWith('*')) {
11
+ if (!allowWildcard || !hostname.startsWith('*')) {
12
12
  return hostname === url.hostname;
13
13
  }
14
- else if (hostname.startsWith('**.')) {
14
+ if (hostname.startsWith('**.')) {
15
15
  const slicedHostname = hostname.slice(2); // ** length
16
16
  return slicedHostname !== url.hostname && url.hostname.endsWith(slicedHostname);
17
17
  }
18
- else if (hostname.startsWith('*.')) {
18
+ if (hostname.startsWith('*.')) {
19
19
  const slicedHostname = hostname.slice(1); // * length
20
20
  const additionalSubdomains = url.hostname
21
21
  .replace(slicedHostname, '')
@@ -35,14 +35,14 @@ export function matchPathname(url, pathname, allowWildcard) {
35
35
  if (!pathname) {
36
36
  return true;
37
37
  }
38
- else if (!allowWildcard || !pathname.endsWith('*')) {
38
+ if (!allowWildcard || !pathname.endsWith('*')) {
39
39
  return pathname === url.pathname;
40
40
  }
41
- else if (pathname.endsWith('/**')) {
41
+ if (pathname.endsWith('/**')) {
42
42
  const slicedPathname = pathname.slice(0, -2); // ** length
43
43
  return slicedPathname !== url.pathname && url.pathname.startsWith(slicedPathname);
44
44
  }
45
- else if (pathname.endsWith('/*')) {
45
+ if (pathname.endsWith('/*')) {
46
46
  const slicedPathname = pathname.slice(0, -1); // * length
47
47
  const additionalPathChunks = url.pathname
48
48
  .replace(slicedPathname, '')
@@ -84,12 +84,10 @@ export function joinPaths(...paths) {
84
84
  if (i === 0) {
85
85
  return removeTrailingForwardSlash(path);
86
86
  }
87
- else if (i === paths.length - 1) {
87
+ if (i === paths.length - 1) {
88
88
  return removeLeadingForwardSlash(path);
89
89
  }
90
- else {
91
- return trimSlashes(path);
92
- }
90
+ return trimSlashes(path);
93
91
  })
94
92
  .join('/');
95
93
  }