// The CloudFront function that keeps Astro's directory output at the no-slash // addresses a standard.site document record claims. // // It runs at the edge on every request and is deployed as a bare source file, // so nothing else in this tree type-checks or exercises it: a mistake here is // found by a reader hitting a redirect loop. These are the cases that decide // whether an address a record claims and the object serving it stay one page. import assert from 'node:assert/strict' import { readFileSync } from 'node:fs' import { dirname, join } from 'node:path' import { test } from 'node:test' import { fileURLToPath } from 'node:url' // The CloudFront Functions runtime wants a bare top-level handler, so the // source has no exports; evaluate it and pull the handler out. const source = readFileSync( join(dirname(fileURLToPath(import.meta.url)), '../../infra/viewer-request.js'), 'utf8', ) const handler = new Function(`${source}; return handler;`)() function run(uri, querystring = {}) { return handler({ request: { uri, querystring } }) } test('the root is left to default_root_object', () => { assert.equal(run('/').uri, '/') }) test('extensionless URIs become the index.html object', () => { assert.equal(run('/posts').uri, '/posts/index.html') assert.equal(run('/posts/hello-world').uri, '/posts/hello-world/index.html') }) test('URIs that name a file pass through untouched', () => { assert.equal(run('/atom.xml').uri, '/atom.xml') assert.equal(run('/404.html').uri, '/404.html') assert.equal(run('/_astro/index.abc123.css').uri, '/_astro/index.abc123.css') // Dots in the last segment, and no extension to add. assert.equal( run('/.well-known/site.standard.publication').uri, '/.well-known/site.standard.publication', ) }) test('a trailing slash redirects to the canonical no-slash address', () => { const response = run('/posts/hello-world/') assert.equal(response.statusCode, 301) assert.equal(response.headers.location.value, '/posts/hello-world') }) test('runs of trailing slashes collapse without looping the root', () => { assert.equal(run('/posts///').headers.location.value, '/posts') assert.equal(run('///').headers.location.value, '/') }) test('a redirect keeps the query string', () => { const querystring = { ref: { value: 'feed' }, flag: { value: '' }, tag: { value: 'a', multiValue: [{ value: 'a' }, { value: 'b' }] }, } const response = run('/posts/hello-world/', querystring) assert.equal( response.headers.location.value, '/posts/hello-world?ref=feed&flag&tag=a&tag=b', ) })