Skip to content

Commit

Permalink
feat: append prerendered redirects to _redirects file (#12199)
Browse files Browse the repository at this point in the history
* feat: Generate static _routes in Cloudflare adapter

* Update .changeset/ten-shirts-add.md

* fix: add comements and newline in generated _redirects file

* fix: exclude redirect paths from cloudflare

* fix: check if there are redirects before writing

* Fix formatting

---------

Co-authored-by: Ben McCann <[email protected]>
  • Loading branch information
Zhincore and benmccann authored Jul 23, 2024
1 parent c1249f5 commit b2b7e34
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/ten-shirts-add.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@sveltejs/adapter-cloudflare": minor
---

feat: generate static `_redirects` for Cloudflare Pages
29 changes: 21 additions & 8 deletions packages/adapter-cloudflare/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ export default function (options = {}) {

writeFileSync(`${dest}/_headers`, generate_headers(builder.getAppPath()), { flag: 'a' });

if (builder.prerendered.redirects.size > 0) {
writeFileSync(`${dest}/_redirects`, generate_redirects(builder.prerendered.redirects), {
flag: 'a'
});
}

builder.copy(`${files}/worker.js`, `${tmp}/_worker.js`, {
replace: {
SERVER: `${relativePath}/index.js`,
Expand Down Expand Up @@ -208,14 +214,7 @@ function get_routes_json(builder, assets, { include = ['/*'], exclude = ['<all>'
}

if (rule === '<prerendered>') {
const prerendered = [];
for (const path of builder.prerendered.paths) {
if (!builder.prerendered.redirects.has(path)) {
prerendered.push(path);
}
}

return prerendered;
return builder.prerendered.paths;
}

return rule;
Expand Down Expand Up @@ -250,3 +249,17 @@ function generate_headers(app_dir) {
# === END AUTOGENERATED SVELTE IMMUTABLE HEADERS ===
`.trimEnd();
}

/** @param {Map<string, { status: number; location: string }>} redirects */
function generate_redirects(redirects) {
const rules = Array.from(
redirects.entries(),
([path, redirect]) => `${path} ${redirect.location} ${redirect.status}`
).join('\n');

return `
# === START AUTOGENERATED SVELTE PRERENDERED REDIRECTS ===
${rules}
# === END AUTOGENERATED SVELTE PRERENDERED REDIRECTS ===
`.trimEnd();
}

0 comments on commit b2b7e34

Please sign in to comment.