Skip to content

Commit

Permalink
Merge branch 'main' into bump-db
Browse files Browse the repository at this point in the history
  • Loading branch information
ascorbic authored Dec 12, 2024
2 parents ac87363 + eef4b74 commit 565bdf5
Show file tree
Hide file tree
Showing 27 changed files with 102 additions and 20 deletions.
5 changes: 5 additions & 0 deletions .changeset/fuzzy-windows-cover.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fixes an issue where Astro couldn't correctly handle i18n fallback when using the i18n middleware
5 changes: 5 additions & 0 deletions .changeset/spicy-guests-protect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Trailing slash support for actions
2 changes: 1 addition & 1 deletion benchmark/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { pathToFileURL } from 'node:url';
import mri from 'mri';
import { makeProject } from './bench/_util.js';

Expand Down
2 changes: 1 addition & 1 deletion benchmark/packages/adapter/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AstroAdapter, AstroIntegration } from 'astro';
import type { AstroIntegration } from 'astro';

export default function createIntegration(): AstroIntegration {
return {
Expand Down
4 changes: 3 additions & 1 deletion biome.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"correctness": {
"noUnusedVariables": "info",
"noUnusedFunctionParameters": "info",
"noUnusedImports": "warn",
},
},
},
Expand Down Expand Up @@ -87,11 +88,12 @@
},
},
{
"include": ["*.astro", "client.d.ts"],
"include": ["*.astro", "client.d.ts", "jsx-runtime.d.ts"],
"linter": {
"rules": {
"correctness": {
"noUnusedVariables": "off",
"noUnusedImports": "off",
},
},
},
Expand Down
7 changes: 7 additions & 0 deletions packages/astro/src/actions/plugins.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type fsMod from 'node:fs';
import type { Plugin as VitePlugin } from 'vite';
import { shouldAppendForwardSlash } from '../core/build/util.js';
import type { AstroSettings } from '../types/astro.js';
import {
NOOP_ACTIONS,
Expand Down Expand Up @@ -84,6 +85,12 @@ export function vitePluginActions({
code += `\nexport * from 'astro/actions/runtime/virtual/server.js';`;
} else {
code += `\nexport * from 'astro/actions/runtime/virtual/client.js';`;
code = code.replace(
"'/** @TRAILING_SLASH@ **/'",
JSON.stringify(
shouldAppendForwardSlash(settings.config.trailingSlash, settings.config.build.format),
),
);
}
return code;
},
Expand Down
14 changes: 13 additions & 1 deletion packages/astro/src/actions/runtime/virtual/server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { z } from 'zod';
import type { Pipeline } from '../../../core/base-pipeline.js';
import { shouldAppendForwardSlash } from '../../../core/build/util.js';
import { ActionCalledFromServerError } from '../../../core/errors/errors-data.js';
import { AstroError } from '../../../core/errors/errors.js';
import { removeTrailingForwardSlash } from '../../../core/path.js';
import { apiContextRoutesSymbol } from '../../../core/render-context.js';
import type { APIContext } from '../../../types/public/index.js';
import { ACTION_RPC_ROUTE_PATTERN } from '../../consts.js';
import {
Expand Down Expand Up @@ -279,7 +283,15 @@ export function getActionContext(context: APIContext): ActionMiddlewareContext {
calledFrom: callerInfo.from,
name: callerInfo.name,
handler: async () => {
const baseAction = await getAction(callerInfo.name);
const pipeline: Pipeline = Reflect.get(context, apiContextRoutesSymbol);
const callerInfoName = shouldAppendForwardSlash(
pipeline.manifest.trailingSlash,
pipeline.manifest.buildFormat,
)
? removeTrailingForwardSlash(callerInfo.name)
: callerInfo.name;

const baseAction = await getAction(callerInfoName);
let input;
try {
input = await parseRequestBody(context.request);
Expand Down
3 changes: 3 additions & 0 deletions packages/astro/src/actions/runtime/virtual/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { z } from 'zod';
import { REDIRECT_STATUS_CODES } from '../../../core/constants.js';
import { ActionsReturnedInvalidDataError } from '../../../core/errors/errors-data.js';
import { AstroError } from '../../../core/errors/errors.js';
import { appendForwardSlash as _appendForwardSlash } from '../../../core/path.js';
import { ACTION_QUERY_PARAMS as _ACTION_QUERY_PARAMS } from '../../consts.js';
import type {
ErrorInferenceObject,
Expand All @@ -13,6 +14,8 @@ import type {
export type ActionAPIContext = _ActionAPIContext;
export const ACTION_QUERY_PARAMS = _ACTION_QUERY_PARAMS;

export const appendForwardSlash = _appendForwardSlash;

export const ACTION_ERROR_CODES = [
'BAD_REQUEST',
'UNAUTHORIZED',
Expand Down
1 change: 0 additions & 1 deletion packages/astro/src/assets/utils/imageAttributes.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { toStyleString } from '../../runtime/server/render/util.js';
import type { AstroConfig } from '../../types/public/config.js';
import type { GetImageResult, ImageLayout, LocalImageProps, RemoteImageProps } from '../types.js';

export function addCSSVarsToStyle(
Expand Down
1 change: 0 additions & 1 deletion packages/astro/src/core/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
REROUTABLE_STATUS_CODES,
REROUTE_DIRECTIVE_HEADER,
clientAddressSymbol,
clientLocalsSymbol,
responseSentSymbol,
} from '../constants.js';
import { getSetCookiesFromResponse } from '../cookies/index.js';
Expand Down
1 change: 0 additions & 1 deletion packages/astro/src/core/build/plugins/plugin-manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import type { Plugin as VitePlugin } from 'vite';
import { getAssetsPrefix } from '../../../assets/utils/getAssetsPrefix.js';
import { normalizeTheLocale } from '../../../i18n/index.js';
import { toFallbackType, toRoutingStrategy } from '../../../i18n/utils.js';
import { unwrapSupportKind } from '../../../integrations/features-validation.js';
import { runHookBuildSsr } from '../../../integrations/hooks.js';
import { BEFORE_HYDRATION_SCRIPT_ID, PAGE_SCRIPT_ID } from '../../../vite-plugin-scripts/index.js';
import type {
Expand Down
1 change: 0 additions & 1 deletion packages/astro/src/core/build/plugins/plugin-ssr.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { Plugin as VitePlugin } from 'vite';
import type { AstroSettings } from '../../../types/astro.js';
import type { AstroAdapter } from '../../../types/public/integrations.js';
import { routeIsRedirect } from '../../redirects/index.js';
import { VIRTUAL_ISLAND_MAP_ID } from '../../server-islands/vite-plugin-server-islands.js';
Expand Down
9 changes: 7 additions & 2 deletions packages/astro/src/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,9 +298,14 @@ export function redirectToDefaultLocale({
}

// NOTE: public function exported to the users via `astro:i18n` module
export function notFound({ base, locales }: MiddlewarePayload) {
export function notFound({ base, locales, fallback }: MiddlewarePayload) {
return function (context: APIContext, response?: Response): Response | undefined {
if (response?.headers.get(REROUTE_DIRECTIVE_HEADER) === 'no') return response;
if (
response?.headers.get(REROUTE_DIRECTIVE_HEADER) === 'no' &&
typeof fallback === 'undefined'
) {
return response;
}

const url = context.url;
// We return a 404 if:
Expand Down
1 change: 0 additions & 1 deletion packages/astro/src/i18n/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ export function createI18nMiddleware(
}

const { currentLocale } = context;

switch (i18n.strategy) {
// NOTE: theoretically, we should never hit this code path
case 'manual': {
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/virtual-modules/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,10 +378,10 @@ if (i18n?.routing === 'manual') {
fallbackType = toFallbackType(customOptions);
const manifest: SSRManifest['i18n'] = {
...i18n,
fallback: undefined,
strategy,
domainLookupTable: {},
fallbackType,
fallback: i18n.fallback,
};
return I18nInternals.createMiddleware(manifest, base, trailingSlash, format);
};
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/vite-plugin-astro-server/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { req } from '../core/messages.js';
import { loadMiddleware } from '../core/middleware/loadMiddleware.js';
import { routeIsRedirect } from '../core/redirects/index.js';
import { RenderContext } from '../core/render-context.js';
import { type SSROptions, getProps } from '../core/render/index.js';
import { getProps } from '../core/render/index.js';
import { createRequest } from '../core/request.js';
import { redirectTemplate } from '../core/routing/3xx.js';
import { matchAllRoutes } from '../core/routing/index.js';
Expand Down
17 changes: 15 additions & 2 deletions packages/astro/templates/actions.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { ActionError, deserializeActionResult, getActionQueryString } from 'astro:actions';
import {
ActionError,
appendForwardSlash,
deserializeActionResult,
getActionQueryString,
} from 'astro:actions';

const ENCODED_DOT = '%2E';

Expand Down Expand Up @@ -83,7 +88,15 @@ async function handleAction(param, path, context) {
headers.set('Content-Length', '0');
}
}
const rawResult = await fetch(`${import.meta.env.BASE_URL.replace(/\/$/, '')}/_actions/${path}`, {

const shouldAppendTrailingSlash = '/** @TRAILING_SLASH@ **/';
let actionPath = import.meta.env.BASE_URL.replace(/\/$/, '') + '/_actions/' + path;

if (shouldAppendTrailingSlash) {
actionPath = appendForwardSlash(actionPath);
}

const rawResult = await fetch(actionPath, {
method: 'POST',
body,
headers,
Expand Down
1 change: 1 addition & 0 deletions packages/astro/templates/env.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// @ts-check
import { schema } from 'virtual:astro:env/internal';
import {
// biome-ignore lint/correctness/noUnusedImports: `_getEnv` is used by the generated code
getEnv as _getEnv,
createInvalidVariablesError,
getEnvFieldType,
Expand Down
24 changes: 24 additions & 0 deletions packages/astro/test/actions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,30 @@ it('Base path should be used', async () => {
await devServer.stop();
});

it('Should support trailing slash', async () => {
const fixture = await loadFixture({
root: './fixtures/actions/',
adapter: testAdapter(),
trailingSlash: 'always',
});
const devServer = await fixture.startDevServer();
const formData = new FormData();
formData.append('channel', 'bholmesdev');
formData.append('comment', 'Hello, World!');
const res = await fixture.fetch('/_actions/comment/', {
method: 'POST',
body: formData,
});

assert.equal(res.ok, true);
assert.equal(res.headers.get('Content-Type'), 'application/json+devalue');

const data = devalue.parse(await res.text());
assert.equal(data.channel, 'bholmesdev');
assert.equal(data.comment, 'Hello, World!');
await devServer.stop();
});

/**
* Follow an expected redirect response.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ export default defineConfig({
codes: ["es", "es-ar"]
}
],
routing: "manual"
routing: "manual",
fallback: {
it: 'en'
}
}
})
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@ export const onRequest = sequence(
customLogic,
middleware({
prefixDefaultLocale: true,
fallbackType: "rewrite"
})
);
Original file line number Diff line number Diff line change
Expand Up @@ -117,4 +117,13 @@ describe('SSR manual routing', () => {
const $ = cheerio.load(html);
assert.equal($('p').text(), '/en/blog/title/');
});

it('should use the fallback', async () => {
let request = new Request('http://example.com/it/start');
let response = await app.render(request);
assert.equal(response.status, 200);
const html = await response.text();
const $ = cheerio.load(html);
assert.equal($('p').text(), '/en/blog/title/');
});
});
1 change: 0 additions & 1 deletion packages/astro/test/units/routing/route-matching.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test';
import { fileURLToPath } from 'node:url';
import * as cheerio from 'cheerio';
import { createContainer } from '../../../dist/core/dev/container.js';
import { createViteLoader } from '../../../dist/core/module-loader/vite.js';
Expand Down
1 change: 0 additions & 1 deletion packages/db/src/core/integration/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import {
type LateSeedFiles,
type LateTables,
type SeedHandler,
resolved,
vitePluginDb,
} from './vite-plugin-db.js';

Expand Down
1 change: 0 additions & 1 deletion packages/db/src/runtime/virtual.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { LibsqlError } from '@libsql/client';
import { sql as _sql } from 'drizzle-orm';
import type {
BooleanColumnInput,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { Tokenizer } from '@markdoc/markdoc';
import { Parser } from 'htmlparser2';
// @ts-expect-error This type isn't exported
// biome-ignore lint/correctness/noUnusedImports: not correctly detected because type isn't exported
import type * as Token from 'markdown-it/lib/token';

export function htmlTokenTransform(tokenizer: Tokenizer, tokens: Token[]): Token[] {
Expand Down
1 change: 0 additions & 1 deletion scripts/cmd/build.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import fs from 'node:fs/promises';
import esbuild from 'esbuild';
import { copy } from 'esbuild-plugin-copy';
import glob from 'fast-glob';
import { dim, green, red, yellow } from 'kleur/colors';
import prebuild from './prebuild.js';
Expand Down

0 comments on commit 565bdf5

Please sign in to comment.