@astrojs/cloudflare 12.2.1 → 12.2.3

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.
@@ -1,260 +1,225 @@
1
- import { existsSync } from 'node:fs';
2
- import { writeFile } from 'node:fs/promises';
3
- import path from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
- import { prependForwardSlash, removeLeadingForwardSlash, removeTrailingForwardSlash, } from '@astrojs/internal-helpers/path';
6
- import glob from 'tiny-glob';
7
- // Copied from https://github.com/withastro/astro/blob/3776ecf0aa9e08a992d3ae76e90682fd04093721/packages/astro/src/core/routing/manifest/create.ts#L45-L70
8
- // We're not sure how to improve this regex yet
9
- // eslint-disable-next-line regexp/no-super-linear-backtracking
1
+ import { existsSync } from "node:fs";
2
+ import { writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import {
6
+ prependForwardSlash,
7
+ removeLeadingForwardSlash,
8
+ removeTrailingForwardSlash
9
+ } from "@astrojs/internal-helpers/path";
10
+ import { glob } from "tinyglobby";
10
11
  const ROUTE_DYNAMIC_SPLIT = /\[(.+?\(.+?\)|.+?)\]/;
11
12
  const ROUTE_SPREAD = /^\.{3}.+$/;
12
- export function getParts(part) {
13
- const result = [];
14
- part.split(ROUTE_DYNAMIC_SPLIT).map((str, i) => {
15
- if (!str)
16
- return;
17
- const dynamic = i % 2 === 1;
18
- const [, content] = dynamic ? /([^(]+)$/.exec(str) || [null, null] : [null, str];
19
- if (!content || (dynamic && !/^(?:\.\.\.)?[\w$]+$/.test(content))) {
20
- throw new Error('Parameter name must match /^[a-zA-Z0-9_$]+$/');
21
- }
22
- result.push({
23
- content,
24
- dynamic,
25
- spread: dynamic && ROUTE_SPREAD.test(content),
26
- });
13
+ function getParts(part) {
14
+ const result = [];
15
+ part.split(ROUTE_DYNAMIC_SPLIT).map((str, i) => {
16
+ if (!str) return;
17
+ const dynamic = i % 2 === 1;
18
+ const [, content] = dynamic ? /([^(]+)$/.exec(str) || [null, null] : [null, str];
19
+ if (!content || dynamic && !/^(?:\.\.\.)?[\w$]+$/.test(content)) {
20
+ throw new Error("Parameter name must match /^[a-zA-Z0-9_$]+$/");
21
+ }
22
+ result.push({
23
+ content,
24
+ dynamic,
25
+ spread: dynamic && ROUTE_SPREAD.test(content)
27
26
  });
28
- return result;
27
+ });
28
+ return result;
29
29
  }
30
30
  async function writeRoutesFileToOutDir(_config, logger, include, exclude) {
31
- try {
32
- await writeFile(new URL('./_routes.json', _config.outDir), JSON.stringify({
33
- version: 1,
34
- include: include,
35
- exclude: exclude,
36
- }, null, 2), 'utf-8');
37
- }
38
- catch (error) {
39
- logger.error("There was an error writing the '_routes.json' file to the output directory.");
40
- }
31
+ try {
32
+ await writeFile(
33
+ new URL("./_routes.json", _config.outDir),
34
+ JSON.stringify(
35
+ {
36
+ version: 1,
37
+ include,
38
+ exclude
39
+ },
40
+ null,
41
+ 2
42
+ ),
43
+ "utf-8"
44
+ );
45
+ } catch (_error) {
46
+ logger.error("There was an error writing the '_routes.json' file to the output directory.");
47
+ }
41
48
  }
42
49
  function segmentsToCfSyntax(segments, _config) {
43
- const pathSegments = [];
44
- if (removeLeadingForwardSlash(removeTrailingForwardSlash(_config.base)).length > 0) {
45
- pathSegments.push(removeLeadingForwardSlash(removeTrailingForwardSlash(_config.base)));
46
- }
47
- for (const segment of segments.flat()) {
48
- if (segment.dynamic)
49
- pathSegments.push('*');
50
- else
51
- pathSegments.push(segment.content);
52
- }
53
- return pathSegments;
50
+ const pathSegments = [];
51
+ if (removeLeadingForwardSlash(removeTrailingForwardSlash(_config.base)).length > 0) {
52
+ pathSegments.push(removeLeadingForwardSlash(removeTrailingForwardSlash(_config.base)));
53
+ }
54
+ for (const segment of segments.flat()) {
55
+ if (segment.dynamic) pathSegments.push("*");
56
+ else pathSegments.push(segment.content);
57
+ }
58
+ return pathSegments;
54
59
  }
55
60
  class TrieNode {
56
- children = new Map();
57
- isEndOfPath = false;
58
- hasWildcardChild = false;
61
+ children = /* @__PURE__ */ new Map();
62
+ isEndOfPath = false;
63
+ hasWildcardChild = false;
59
64
  }
60
65
  class PathTrie {
61
- root;
62
- returnHasWildcard = false;
63
- constructor() {
64
- this.root = new TrieNode();
65
- }
66
- insert(path) {
67
- let node = this.root;
68
- for (const segment of path) {
69
- if (segment === '*') {
70
- node.hasWildcardChild = true;
71
- break;
72
- }
73
- if (!node.children.has(segment)) {
74
- node.children.set(segment, new TrieNode());
75
- }
76
- // biome-ignore lint/style/noNonNullAssertion: The `if` condition above ensures that the segment exists inside the map
77
- node = node.children.get(segment);
78
- }
79
- node.isEndOfPath = true;
80
- }
81
- /**
82
- * Depth-first search (dfs), traverses the "graph" segment by segment until the end or wildcard (*).
83
- * It makes sure that all necessary paths are returned, but not paths with an existing wildcard prefix.
84
- * e.g. if we have a path like /foo/* and /foo/bar, we only want to return /foo/*
85
- */
86
- dfs(node, path, allPaths) {
87
- if (node.hasWildcardChild) {
88
- this.returnHasWildcard = true;
89
- allPaths.push([...path, '*']);
90
- return;
91
- }
92
- if (node.isEndOfPath) {
93
- allPaths.push([...path]);
94
- }
95
- for (const [segment, childNode] of node.children) {
96
- this.dfs(childNode, [...path, segment], allPaths);
97
- }
98
- }
99
- /**
100
- * The reduce function is used to remove unnecessary paths from the trie.
101
- * It receives a trie node to compare with the current node.
102
- */
103
- reduce(compNode, node) {
104
- if (node.hasWildcardChild || compNode.hasWildcardChild)
105
- return;
106
- for (const [segment, childNode] of node.children) {
107
- if (childNode.children.size === 0)
108
- continue;
109
- const compChildNode = compNode.children.get(segment);
110
- if (compChildNode === undefined) {
111
- childNode.hasWildcardChild = true;
112
- continue;
113
- }
114
- this.reduce(compChildNode, childNode);
115
- }
116
- }
117
- reduceAllPaths(compTrie) {
118
- this.reduce(compTrie.root, this.root);
119
- return this;
120
- }
121
- getAllPaths() {
122
- const allPaths = [];
123
- this.dfs(this.root, [], allPaths);
124
- return [allPaths, this.returnHasWildcard];
125
- }
66
+ root;
67
+ returnHasWildcard = false;
68
+ constructor() {
69
+ this.root = new TrieNode();
70
+ }
71
+ insert(thisPath) {
72
+ let node = this.root;
73
+ for (const segment of thisPath) {
74
+ if (segment === "*") {
75
+ node.hasWildcardChild = true;
76
+ break;
77
+ }
78
+ if (!node.children.has(segment)) {
79
+ node.children.set(segment, new TrieNode());
80
+ }
81
+ node = node.children.get(segment);
82
+ }
83
+ node.isEndOfPath = true;
84
+ }
85
+ /**
86
+ * Depth-first search (dfs), traverses the "graph" segment by segment until the end or wildcard (*).
87
+ * It makes sure that all necessary paths are returned, but not paths with an existing wildcard prefix.
88
+ * e.g. if we have a path like /foo/* and /foo/bar, we only want to return /foo/*
89
+ */
90
+ dfs(node, thisPath, allPaths) {
91
+ if (node.hasWildcardChild) {
92
+ this.returnHasWildcard = true;
93
+ allPaths.push([...thisPath, "*"]);
94
+ return;
95
+ }
96
+ if (node.isEndOfPath) {
97
+ allPaths.push([...thisPath]);
98
+ }
99
+ for (const [segment, childNode] of node.children) {
100
+ this.dfs(childNode, [...thisPath, segment], allPaths);
101
+ }
102
+ }
103
+ /**
104
+ * The reduce function is used to remove unnecessary paths from the trie.
105
+ * It receives a trie node to compare with the current node.
106
+ */
107
+ reduce(compNode, node) {
108
+ if (node.hasWildcardChild || compNode.hasWildcardChild) return;
109
+ for (const [segment, childNode] of node.children) {
110
+ if (childNode.children.size === 0) continue;
111
+ const compChildNode = compNode.children.get(segment);
112
+ if (compChildNode === void 0) {
113
+ childNode.hasWildcardChild = true;
114
+ continue;
115
+ }
116
+ this.reduce(compChildNode, childNode);
117
+ }
118
+ }
119
+ reduceAllPaths(compTrie) {
120
+ this.reduce(compTrie.root, this.root);
121
+ return this;
122
+ }
123
+ getAllPaths() {
124
+ const allPaths = [];
125
+ this.dfs(this.root, [], allPaths);
126
+ return [allPaths, this.returnHasWildcard];
127
+ }
126
128
  }
127
- export async function createRoutesFile(_config, logger, routes, pages, redirects, includeExtends, excludeExtends) {
128
- const includePaths = [];
129
- const excludePaths = [];
130
- /**
131
- * All files in the `_config.build.assets` path, e.g. `_astro`
132
- * are considered static assets and should not be handled by the function
133
- * therefore we exclude a wildcard for that, e.g. `/_astro/*`
134
- */
135
- const assetsPath = segmentsToCfSyntax([
136
- [{ content: _config.build.assets, dynamic: false, spread: false }],
137
- [{ content: '', dynamic: true, spread: false }],
138
- ], _config);
139
- excludePaths.push(assetsPath);
140
- for (const redirect of redirects) {
141
- excludePaths.push(segmentsToCfSyntax(redirect, _config));
142
- }
143
- if (existsSync(fileURLToPath(_config.publicDir))) {
144
- const staticFiles = await glob(`${fileURLToPath(_config.publicDir)}/**/*`, {
145
- cwd: fileURLToPath(_config.publicDir),
146
- filesOnly: true,
147
- dot: true,
148
- });
149
- for (const staticFile of staticFiles) {
150
- if (['_headers', '_redirects', '_routes.json'].includes(staticFile))
151
- continue;
152
- const staticPath = staticFile;
153
- const segments = removeLeadingForwardSlash(staticPath)
154
- .split(path.sep)
155
- .filter(Boolean)
156
- .map((s) => {
157
- return getParts(s);
158
- });
159
- excludePaths.push(segmentsToCfSyntax(segments, _config));
160
- }
161
- }
162
- let hasPrerendered404 = false;
163
- for (const route of routes) {
164
- const convertedPath = segmentsToCfSyntax(route.segments, _config);
165
- if (route.pathname === '/404' && route.isPrerendered === true)
166
- hasPrerendered404 = true;
167
- // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check
168
- switch (route.type) {
169
- case 'page':
170
- if (route.isPrerendered === false)
171
- includePaths.push(convertedPath);
172
- break;
173
- case 'endpoint':
174
- if (route.isPrerendered === false)
175
- includePaths.push(convertedPath);
176
- else
177
- excludePaths.push(convertedPath);
178
- break;
179
- case 'redirect':
180
- excludePaths.push(convertedPath);
181
- break;
182
- default:
183
- /**
184
- * We don't know the type, so we are conservative!
185
- * Invoking the function on these is a safe-bet because
186
- * the function will fallback to static asset fetching
187
- */
188
- includePaths.push(convertedPath);
189
- break;
190
- }
191
- }
192
- for (const page of pages) {
193
- if (page.pathname === '404')
194
- hasPrerendered404 = true;
195
- const pageSegments = removeLeadingForwardSlash(page.pathname)
196
- .split(path.posix.sep)
197
- .filter(Boolean)
198
- .map((s) => {
199
- return getParts(s);
200
- });
201
- excludePaths.push(segmentsToCfSyntax(pageSegments, _config));
202
- }
203
- const includeTrie = new PathTrie();
204
- for (const includePath of includePaths) {
205
- includeTrie.insert(includePath);
206
- }
207
- const excludeTrie = new PathTrie();
208
- for (const excludePath of excludePaths) {
209
- /**
210
- * A excludePath with starts with a wildcard (*) is a catch-all
211
- * that would mean all routes are static, that would be equal to a full SSG project
212
- * the adapter is not needed in this case, so we do not consider such paths
213
- */
214
- if (excludePath[0] === '*')
215
- continue;
216
- excludeTrie.insert(excludePath);
217
- }
218
- const [deduplicatedIncludePaths, includedPathsHaveWildcard] = includeTrie
219
- .reduceAllPaths(excludeTrie)
220
- .getAllPaths();
221
- const [deduplicatedExcludePaths, _excludedPathsHaveWildcard] = excludeTrie
222
- .reduceAllPaths(includeTrie)
223
- .getAllPaths();
224
- /**
225
- * Cloudflare allows no more than 100 include/exclude rules combined
226
- * https://developers.cloudflare.com/pages/functions/routing/#limits
227
- */
228
- const CLOUDFLARE_COMBINED_LIMIT = 100;
229
- /**
230
- * Caluclate the number of automated and extended include rules
231
- */
232
- const AUTOMATIC_INCLUDE_RULES_COUNT = deduplicatedIncludePaths.length;
233
- const EXTENDED_INCLUDE_RULES_COUNT = includeExtends?.length ?? 0;
234
- const INCLUDE_RULES_COUNT = AUTOMATIC_INCLUDE_RULES_COUNT + EXTENDED_INCLUDE_RULES_COUNT;
235
- /**
236
- * Caluclate the number of automated and extended exclude rules
237
- */
238
- const AUTOMATIC_EXCLUDE_RULES_COUNT = deduplicatedExcludePaths.length;
239
- const EXTENDED_EXCLUDE_RULES_COUNT = excludeExtends?.length ?? 0;
240
- const EXCLUDE_RULES_COUNT = AUTOMATIC_EXCLUDE_RULES_COUNT + EXTENDED_EXCLUDE_RULES_COUNT;
241
- const OPTION2_TOTAL_COUNT = INCLUDE_RULES_COUNT + (includedPathsHaveWildcard ? EXCLUDE_RULES_COUNT : 0);
242
- if (!hasPrerendered404 || OPTION2_TOTAL_COUNT > CLOUDFLARE_COMBINED_LIMIT) {
243
- await writeRoutesFileToOutDir(_config, logger, ['/*'].concat(includeExtends?.map((entry) => entry.pattern) ?? []), deduplicatedExcludePaths
244
- .map((path) => `${prependForwardSlash(path.join('/'))}`)
245
- .slice(0, CLOUDFLARE_COMBINED_LIMIT -
246
- EXTENDED_INCLUDE_RULES_COUNT -
247
- EXTENDED_EXCLUDE_RULES_COUNT -
248
- 1)
249
- .concat(excludeExtends?.map((entry) => entry.pattern) ?? []));
250
- }
251
- else {
252
- await writeRoutesFileToOutDir(_config, logger, deduplicatedIncludePaths
253
- .map((path) => `${prependForwardSlash(path.join('/'))}`)
254
- .concat(includeExtends?.map((entry) => entry.pattern) ?? []), includedPathsHaveWildcard
255
- ? deduplicatedExcludePaths
256
- .map((path) => `${prependForwardSlash(path.join('/'))}`)
257
- .concat(excludeExtends?.map((entry) => entry.pattern) ?? [])
258
- : []);
259
- }
129
+ async function createRoutesFile(_config, logger, routes, pages, redirects, includeExtends, excludeExtends) {
130
+ const includePaths = [];
131
+ const excludePaths = [];
132
+ const assetsPath = segmentsToCfSyntax(
133
+ [
134
+ [{ content: _config.build.assets, dynamic: false, spread: false }],
135
+ [{ content: "", dynamic: true, spread: false }]
136
+ ],
137
+ _config
138
+ );
139
+ excludePaths.push(assetsPath);
140
+ for (const redirect of redirects) {
141
+ excludePaths.push(segmentsToCfSyntax(redirect, _config));
142
+ }
143
+ if (existsSync(fileURLToPath(_config.publicDir))) {
144
+ const staticFiles = await glob(`**/*`, {
145
+ cwd: fileURLToPath(_config.publicDir),
146
+ dot: true
147
+ });
148
+ for (const staticFile of staticFiles) {
149
+ if (["_headers", "_redirects", "_routes.json"].includes(staticFile)) continue;
150
+ const staticPath = staticFile;
151
+ const segments = removeLeadingForwardSlash(staticPath).split(path.sep).filter(Boolean).map((s) => {
152
+ return getParts(s);
153
+ });
154
+ excludePaths.push(segmentsToCfSyntax(segments, _config));
155
+ }
156
+ }
157
+ let hasPrerendered404 = false;
158
+ for (const route of routes) {
159
+ const convertedPath = segmentsToCfSyntax(route.segments, _config);
160
+ if (route.pathname === "/404" && route.isPrerendered === true) hasPrerendered404 = true;
161
+ switch (route.type) {
162
+ case "page":
163
+ if (route.isPrerendered === false) includePaths.push(convertedPath);
164
+ break;
165
+ case "endpoint":
166
+ if (route.isPrerendered === false) includePaths.push(convertedPath);
167
+ else excludePaths.push(convertedPath);
168
+ break;
169
+ case "redirect":
170
+ excludePaths.push(convertedPath);
171
+ break;
172
+ default:
173
+ includePaths.push(convertedPath);
174
+ break;
175
+ }
176
+ }
177
+ for (const page of pages) {
178
+ if (page.pathname === "404") hasPrerendered404 = true;
179
+ const pageSegments = removeLeadingForwardSlash(page.pathname).split(path.posix.sep).filter(Boolean).map((s) => {
180
+ return getParts(s);
181
+ });
182
+ excludePaths.push(segmentsToCfSyntax(pageSegments, _config));
183
+ }
184
+ const includeTrie = new PathTrie();
185
+ for (const includePath of includePaths) {
186
+ includeTrie.insert(includePath);
187
+ }
188
+ const excludeTrie = new PathTrie();
189
+ for (const excludePath of excludePaths) {
190
+ if (excludePath[0] === "*") continue;
191
+ excludeTrie.insert(excludePath);
192
+ }
193
+ const [deduplicatedIncludePaths, includedPathsHaveWildcard] = includeTrie.reduceAllPaths(excludeTrie).getAllPaths();
194
+ const [deduplicatedExcludePaths, _excludedPathsHaveWildcard] = excludeTrie.reduceAllPaths(includeTrie).getAllPaths();
195
+ const CLOUDFLARE_COMBINED_LIMIT = 100;
196
+ const AUTOMATIC_INCLUDE_RULES_COUNT = deduplicatedIncludePaths.length;
197
+ const EXTENDED_INCLUDE_RULES_COUNT = includeExtends?.length ?? 0;
198
+ const INCLUDE_RULES_COUNT = AUTOMATIC_INCLUDE_RULES_COUNT + EXTENDED_INCLUDE_RULES_COUNT;
199
+ const AUTOMATIC_EXCLUDE_RULES_COUNT = deduplicatedExcludePaths.length;
200
+ const EXTENDED_EXCLUDE_RULES_COUNT = excludeExtends?.length ?? 0;
201
+ const EXCLUDE_RULES_COUNT = AUTOMATIC_EXCLUDE_RULES_COUNT + EXTENDED_EXCLUDE_RULES_COUNT;
202
+ const OPTION2_TOTAL_COUNT = INCLUDE_RULES_COUNT + (includedPathsHaveWildcard ? EXCLUDE_RULES_COUNT : 0);
203
+ if (!hasPrerendered404 || OPTION2_TOTAL_COUNT > CLOUDFLARE_COMBINED_LIMIT) {
204
+ await writeRoutesFileToOutDir(
205
+ _config,
206
+ logger,
207
+ ["/*"].concat(includeExtends?.map((entry) => entry.pattern) ?? []),
208
+ deduplicatedExcludePaths.map((thisPath) => `${prependForwardSlash(thisPath.join("/"))}`).slice(
209
+ 0,
210
+ CLOUDFLARE_COMBINED_LIMIT - EXTENDED_INCLUDE_RULES_COUNT - EXTENDED_EXCLUDE_RULES_COUNT - 1
211
+ ).concat(excludeExtends?.map((entry) => entry.pattern) ?? [])
212
+ );
213
+ } else {
214
+ await writeRoutesFileToOutDir(
215
+ _config,
216
+ logger,
217
+ deduplicatedIncludePaths.map((thisPath) => `${prependForwardSlash(thisPath.join("/"))}`).concat(includeExtends?.map((entry) => entry.pattern) ?? []),
218
+ includedPathsHaveWildcard ? deduplicatedExcludePaths.map((thisPath) => `${prependForwardSlash(thisPath.join("/"))}`).concat(excludeExtends?.map((entry) => entry.pattern) ?? []) : []
219
+ );
220
+ }
260
221
  }
222
+ export {
223
+ createRoutesFile,
224
+ getParts
225
+ };
@@ -1,30 +1,33 @@
1
- import { passthroughImageService, sharpImageService } from 'astro/config';
2
- export function setImageConfig(service, config, command, logger) {
3
- switch (service) {
4
- case 'passthrough':
5
- return { ...config, service: passthroughImageService() };
6
- case 'cloudflare':
7
- return {
8
- ...config,
9
- service: command === 'dev'
10
- ? sharpImageService()
11
- : { entrypoint: '@astrojs/cloudflare/image-service' },
12
- };
13
- case 'compile':
14
- return {
15
- ...config,
16
- service: sharpImageService(),
17
- endpoint: {
18
- entrypoint: command === 'dev' ? undefined : '@astrojs/cloudflare/image-endpoint',
19
- },
20
- };
21
- case 'custom':
22
- return { ...config };
23
- default:
24
- if (config.service.entrypoint === 'astro/assets/services/sharp') {
25
- logger.warn(`The current configuration does not support image optimization. To allow your project to build with the original, unoptimized images, the image service has been automatically switched to the 'noop' option. See https://docs.astro.build/en/reference/configuration-reference/#imageservice`);
26
- return { ...config, service: passthroughImageService() };
27
- }
28
- return { ...config };
29
- }
1
+ import { passthroughImageService, sharpImageService } from "astro/config";
2
+ function setImageConfig(service, config, command, logger) {
3
+ switch (service) {
4
+ case "passthrough":
5
+ return { ...config, service: passthroughImageService() };
6
+ case "cloudflare":
7
+ return {
8
+ ...config,
9
+ service: command === "dev" ? sharpImageService() : { entrypoint: "@astrojs/cloudflare/image-service" }
10
+ };
11
+ case "compile":
12
+ return {
13
+ ...config,
14
+ service: sharpImageService(),
15
+ endpoint: {
16
+ entrypoint: command === "dev" ? void 0 : "@astrojs/cloudflare/image-endpoint"
17
+ }
18
+ };
19
+ case "custom":
20
+ return { ...config };
21
+ default:
22
+ if (config.service.entrypoint === "astro/assets/services/sharp") {
23
+ logger.warn(
24
+ `The current configuration does not support image optimization. To allow your project to build with the original, unoptimized images, the image service has been automatically switched to the 'noop' option. See https://docs.astro.build/en/reference/configuration-reference/#imageservice`
25
+ );
26
+ return { ...config, service: passthroughImageService() };
27
+ }
28
+ return { ...config };
29
+ }
30
30
  }
31
+ export {
32
+ setImageConfig
33
+ };