before_code
stringlengths
14
465k
reviewer_comment
stringlengths
16
64.5k
after_code
stringlengths
9
467k
diff_context
stringlengths
0
97k
file_path
stringlengths
5
226
comment_line
int32
0
26
language
stringclasses
37 values
quality_score
float32
0.07
1
comment_type
stringclasses
9 values
comment_length
int32
16
64.5k
before_lines
int32
1
17.2k
after_lines
int32
1
12.1k
is_negative
bool
2 classes
pr_title
stringlengths
1
308
pr_number
int32
1
299k
repo_name
stringclasses
533 values
repo_stars
int64
321
419k
repo_language
stringclasses
27 values
reviewer_username
stringlengths
0
39
author_username
stringlengths
2
39
const nodeBuiltinsBare = [ 'async_hooks', 'child_process', 'cluster', 'crypto', 'diagnostics_channel', 'dns', 'events', 'fs', 'http', 'https', 'http2', 'net', 'os', 'path', 'perf_hooks', 'process', 'querystring', 'readline', 'stream', 'string_decoder', 'tls', 'tty', 'url',...
Do we need to hardcode these? ```js import {builtinModules} from 'module'; ```
import {builtinModules} from 'module'; export const nodeBuiltinsSet = new Set(builtinModules); export const nodeBuiltinsMap = new Map(builtinModules.map(bareName => [bareName, 'node:' + bareName]));
@@ -0,0 +1,35 @@ +
packages/astro/src/node_builtins.ts
1
TypeScript
0.571
question
83
26
5
false
Allow usage of node builtins through node: prefix
520
withastro/astro
47,179
TypeScript
natemoo-re
matthewp
if (reqPath !== '/500') { requestURL.search = ''; } let html = (await mod.exports.__renderPage({ request: { // params should go here when implemented url: requestURL, canonicalURL: canonicalURL(requestURL.pathname, requestURL.origin), }, children: [], p...
Probably want to remove this 😉
if (reqPath !== '/500') { requestURL.search = ''; } let html = (await mod.exports.__renderPage({ request: { // params should go here when implemented url: requestURL, canonicalURL: canonicalURL(requestURL.pathname, requestURL.origin), }, children: [], p...
@@ -241,6 +242,7 @@ async function load(config: RuntimeConfig, rawPathname: string | undefined): Pro }, }; } catch (err) { + debugger;
packages/astro/src/runtime.ts
26
TypeScript
0.143
refactor
31
51
51
false
Allow usage of node builtins through node: prefix
520
withastro/astro
47,179
TypeScript
natemoo-re
matthewp
import { encryptString } from '../../../core/encryption.js'; import type { SSRResult } from '../../../types/public/internal.js'; import { renderChild } from './any.js'; import type { RenderInstance } from './common.js'; import { type ComponentSlots, renderSlotToString } from './slot.js'; const internalProps = new Set(...
We usually use upper-case for top-level constants like this ones
import { encryptString } from '../../../core/encryption.js'; import type { SSRResult } from '../../../types/public/internal.js'; import { renderChild } from './any.js'; import type { RenderInstance } from './common.js'; import { type ComponentSlots, renderSlotToString } from './slot.js'; const internalProps = new Set(...
@@ -15,13 +15,19 @@ export function containsServerDirective(props: Record<string | number, any>) { return 'server:component-directive' in props; } +const scriptRegex = /<\/script/giu; +const commentRegex = /<!--/gu; +const scriptReplacer = '<\\/script'; +const commentReplacer = '\\u003C!--';
packages/astro/src/runtime/server/render/server-islands.ts
21
TypeScript
0.286
suggestion
64
46
46
false
feat(server-islands): only encode ETAGO delimiter
11,513
withastro/astro
47,179
TypeScript
ematipico
kurtextrem
absolute: true, cwd: fileURLToPath(root), fs, }, ); // Run 10 at a time to prevent `await getEntrySlug` from accessing the filesystem all at once. // Each await shouldn't take too long for the work to be noticeably slow too. const limit = pLimit(10); const promises: Promise<void>[] = []; for (const f...
this is an unrelated change, but this `await` is on a sync function, so I removed.
const limit = pLimit(10); const promises: Promise<void>[] = []; for (const filePath of contentGlob) { promises.push( limit(async () => { const entryType = getEntryType(filePath, contentPaths, contentEntryExts, dataEntryExts); // Globbed ignored or unsupported entry. // Logs warning during type gene...
@@ -360,7 +372,7 @@ export async function generateLookupMap({ const contentEntryType = contentEntryConfigByExt.get(extname(filePath)); if (!contentEntryType) throw UnexpectedLookupMapError; - const { id, slug: generatedSlug } = await getContentEntryIdAndSlug({ + const { id, slug: generatedSlug } =...
packages/astro/src/content/vite-plugin-content-virtual-mod.ts
26
TypeScript
0.429
suggestion
82
51
51
false
Prevent usage of astro:content in the client
11,827
withastro/astro
47,179
TypeScript
matthewp
matthewp
contentEntryGlobResult = createGlob( globWithUnderscoresIgnored(relContentDir, contentEntryExts), CONTENT_FLAG, ); dataEntryGlobResult = createGlob( globWithUnderscoresIgnored(relContentDir, dataEntryExts), DATA_FLAG, ); renderEntryGlobResult = createGlob( globWithUnderscoresIgnored(relContentD...
If is is imported dynamically like `await import('astro:content');` it won't fail the build either.
DATA_FLAG, ); renderEntryGlobResult = createGlob( globWithUnderscoresIgnored(relContentDir, contentEntryExts), CONTENT_RENDER_FLAG, ); } else { contentEntryGlobResult = getStringifiedCollectionFromLookup( 'content', relContentDir, lookupMap, ); dataEntryGlobResult = getStringifiedCollecti...
@@ -253,18 +259,24 @@ export async function generateContentEntryFile({ renderEntryGlobResult = getStringifiedCollectionFromLookup('render', relContentDir, lookupMap); } - let virtualModContents = - nodeFs - .readFileSync(contentPaths.virtualModTemplate, 'utf-8') - .replace('@@CONTENT_DIR@@', relContentDir) ...
packages/astro/src/content/vite-plugin-content-virtual-mod.ts
26
TypeScript
0.357
bug
99
51
51
false
Prevent usage of astro:content in the client
11,827
withastro/astro
47,179
TypeScript
Fryuni
matthewp
dataEntryGlobResult = createGlob( globWithUnderscoresIgnored(relContentDir, dataEntryExts), DATA_FLAG, ); renderEntryGlobResult = createGlob( globWithUnderscoresIgnored(relContentDir, contentEntryExts), CONTENT_RENDER_FLAG, ); } else { contentEntryGlobResult = getStringifiedCollectionFromLookup( ...
We could throw an `AstroError` to make it break immediately with the instruction about where it is being used and should be removed right
CONTENT_RENDER_FLAG, ); } else { contentEntryGlobResult = getStringifiedCollectionFromLookup( 'content', relContentDir, lookupMap, ); dataEntryGlobResult = getStringifiedCollectionFromLookup('data', relContentDir, lookupMap); renderEntryGlobResult = getStringifiedCollectionFromLookup('render', re...
@@ -253,18 +259,24 @@ export async function generateContentEntryFile({ renderEntryGlobResult = getStringifiedCollectionFromLookup('render', relContentDir, lookupMap); } - let virtualModContents = - nodeFs - .readFileSync(contentPaths.virtualModTemplate, 'utf-8') - .replace('@@CONTENT_DIR@@', relContentDir) ...
packages/astro/src/content/vite-plugin-content-virtual-mod.ts
26
TypeScript
0.714
suggestion
137
51
51
false
Prevent usage of astro:content in the client
11,827
withastro/astro
47,179
TypeScript
Fryuni
matthewp
globWithUnderscoresIgnored(relContentDir, contentEntryExts), CONTENT_FLAG, ); dataEntryGlobResult = createGlob( globWithUnderscoresIgnored(relContentDir, dataEntryExts), DATA_FLAG, ); renderEntryGlobResult = createGlob( globWithUnderscoresIgnored(relContentDir, contentEntryExts), CONTENT_RENDE...
Is this really needed? I think for `astro:env` I just throw without returning any content
globWithUnderscoresIgnored(relContentDir, contentEntryExts), CONTENT_FLAG, ); dataEntryGlobResult = createGlob( globWithUnderscoresIgnored(relContentDir, dataEntryExts), DATA_FLAG, ); renderEntryGlobResult = createGlob( globWithUnderscoresIgnored(relContentDir, contentEntryExts), CONTENT_RENDE...
@@ -253,18 +253,27 @@ export async function generateContentEntryFile({ renderEntryGlobResult = getStringifiedCollectionFromLookup('render', relContentDir, lookupMap); } - let virtualModContents = - nodeFs - .readFileSync(contentPaths.virtualModTemplate, 'utf-8') - .replace('@@CONTENT_DIR@@', relContentDir) ...
packages/astro/src/content/vite-plugin-content-virtual-mod.ts
26
TypeScript
0.357
question
89
51
51
false
Prevent usage of astro:content in the client
11,827
withastro/astro
47,179
TypeScript
florian-lefebvre
matthewp
import { createVite } from '../create-vite.js'; import { createKey, getEnvironmentKey, hasEnvironmentKey } from '../encryption.js'; import type { Logger } from '../logger/core.js'; import { levels, timerMessage } from '../logger/core.js'; import { apply as applyPolyfill } from '../polyfill.js'; import { createRouteMani...
I'd prefer to keep this internal still. I imagine for external libraries this shouldn't have a significant impact if not used since it only mattered for Astro having tons of tests.
import { levels, timerMessage } from '../logger/core.js'; import { apply as applyPolyfill } from '../polyfill.js'; import { createRoutesList } from '../routing/index.js'; import { getServerIslandRouteData } from '../server-islands/endpoint.js'; import { clearContentLayerCache } from '../sync/index.js'; import { ensureP...
@@ -40,7 +40,9 @@ export interface BuildOptions { * Teardown the compiler WASM instance after build. This can improve performance when * building once, but may cause a performance hit if building multiple times in a row. * - * @internal only used for testing + * When building multiple projects in the same ex...
packages/astro/src/core/build/index.ts
26
TypeScript
0.429
suggestion
180
51
51
false
feat(astro): Exposes extra APIs for script and testing
12,052
withastro/astro
47,179
TypeScript
bluwy
Fryuni
#createRoute(url: URL, params: Record<string, string | undefined>, type: RouteType): RouteData { const segments = removeLeadingForwardSlash(url.pathname) .split(posix.sep) .filter(Boolean) .map((s: string) => { validateSegment(s); return getParts(s, url.pathname); }); return { route: url.pat...
I'm not sure what we should use here
#createRoute(url: URL, params: Record<string, string | undefined>, type: RouteType): RouteData { const segments = removeLeadingForwardSlash(url.pathname) .split(posix.sep) .filter(Boolean) .map((s: string) => { validateSegment(s); return getParts(s, url.pathname); }); return { route: url.pat...
@@ -544,6 +544,7 @@ export class experimental_AstroContainer { type, fallbackRoutes: [], isIndex: false, + origin: 'user',
packages/astro/src/container/index.ts
26
TypeScript
0.143
suggestion
36
51
51
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
import notFoundTemplate from '../../template/4xx.js'; import type { ComponentInstance, ManifestData } from '../../types/astro.js'; import type { RouteData } from '../../types/public/internal.js'; import { DEFAULT_404_COMPONENT, DEFAULT_500_COMPONENT } from '../constants.js'; export const DEFAULT_404_ROUTE: RouteData =...
Although we use "core" to refer to the `astro` package, is this as clear to users of the API as it is to us? Maybe `origin: 'astro'` would be better for users.
import notFoundTemplate from '../../template/4xx.js'; import type { ComponentInstance, ManifestData } from '../../types/astro.js'; import type { RouteData } from '../../types/public/internal.js'; import { DEFAULT_404_COMPONENT, DEFAULT_500_COMPONENT } from '../constants.js'; export const DEFAULT_404_ROUTE: RouteData =...
@@ -15,6 +15,7 @@ export const DEFAULT_404_ROUTE: RouteData = { route: '/404', fallbackRoutes: [], isIndex: false, + origin: 'core',
packages/astro/src/core/routing/astro-designed-error-pages.ts
18
TypeScript
0.571
suggestion
159
43
43
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
Fryuni
florian-lefebvre
}) => void | Promise<void>; 'astro:build:start': (options: { logger: AstroIntegrationLogger }) => void | Promise<void>; 'astro:build:setup': (options: { vite: ViteInlineConfig; pages: Map<string, PageBuildData>; target: 'client' | 'server'; updateConfig: (newConfig: ViteInlineConfig) => void; logger: Astro...
For consistency with the other arrays in the type ```suggestion routes: IntegrationResolvedRoute[]; ```
}) => void | Promise<void>; 'astro:build:start': (options: { logger: AstroIntegrationLogger }) => void | Promise<void>; 'astro:build:setup': (options: { vite: ViteInlineConfig; pages: Map<string, PageBuildData>; target: 'client' | 'server'; updateConfig: (newConfig: ViteInlineConfig) => void; logger: Astro...
@@ -225,13 +217,18 @@ export interface BaseIntegrationHooks { 'astro:build:done': (options: { pages: { pathname: string }[]; dir: URL; + /** @deprecated Use `routes` from `astro:routes:resolved` instead */ routes: IntegrationRouteData[]; logger: AstroIntegrationLogger; }) => void | Promise<void>; 'as...
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.857
suggestion
108
51
51
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
Fryuni
florian-lefebvre
}; export interface IntegrationResolvedRoute { /** * The current **pattern** of the route. For example: * - `src/pages/index.astro` has a pattern of `/` * - `src/pages/blog/[...slug].astro` has a pattern of `/blog/[...slug]` * - `src/pages/site/[blog]/[...slug].astro` has a pattern of `/site/[blog]/[...slug]`...
I'll miss the `generate` function from `IntegrationRouteData` to generate URLs for a given route. Integrations will have to construct their own URL generator function based on the `pattern` and `params` which seems somewhat unnecessary since that function already exists in Astro and just isn't exposed. It is not a b...
*/ redirectRoute?: IntegrationRouteData; }; export interface IntegrationResolvedRoute extends Pick< RouteData, 'generate' | 'params' | 'pathname' | 'segments' | 'type' | 'redirect' | 'origin' > { /** * {@link RouteData.route} */ pattern: RouteData['route']; /** * {@link RouteData.pattern} */ patt...
@@ -248,10 +245,41 @@ export interface AstroIntegration { */ export type IntegrationRouteData = Omit< RouteData, - 'isIndex' | 'fallbackRoutes' | 'redirectRoute' + 'isIndex' | 'fallbackRoutes' | 'redirectRoute' | 'origin' > & { /** * {@link RouteData.redirectRoute} */ redirectRoute?: IntegrationRouteDat...
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.643
suggestion
360
33
35
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
Fryuni
florian-lefebvre
loader, logger, manifest: devSSRManifest, settings, }); const controller = createController({ loader }); const localStorage = new AsyncLocalStorage(); /** rebuild the route cache + manifest */ async function rebuildManifest() { pipeline.clearRouteCache(); routeManifest = injectDe...
I get why the optimization was removed, but isn't it too drastic? The entire route manifest will be recomputed on every change anywhere. Even tho it will most likely not change anything in the routes. - `add` changes routes, that's fine - `unlink` changes routes, that's fine - `change` only changes routes if the ...
name: 'astro:server', configureServer(viteServer) { const loader = createViteLoader(viteServer); const pipeline = DevPipeline.create(routeManifest, { loader, logger, manifest: devSSRManifest, settings, }); const controller = createController({ loader }); const localStorage = new Async...
@@ -50,26 +50,24 @@ export default function createVitePluginAstroServer({ const controller = createController({ loader }); const localStorage = new AsyncLocalStorage(); - /** rebuild the route cache + manifest, as needed. */ - async function rebuildManifest(needsManifestRebuild: boolean) { + /** rebuild...
packages/astro/src/vite-plugin-astro-server/plugin.ts
26
TypeScript
0.643
performance
866
51
51
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
Fryuni
florian-lefebvre
* This maps a {@link RouteData} to an {@link URL}, this URL represents * the physical file you should import. */ entryPoints: Map<IntegrationRouteData, URL>; /** * File path of the emitted middleware */ middlewareEntryPoint: URL | undefined; logger: AstroIntegrationLogger; }) => void | Promise<v...
If we intend to remove this, we'll need to think more about how to provide the existing functionality elsewhere. Fields not exposed on the new hook are relied upon by integrations and adapters, including official ones: - Sitemap [relies on `type`, `pathname`, and `generate`](https://github.com/withastro/astro/blob/75a...
* This maps a {@link RouteData} to an {@link URL}, this URL represents * the physical file you should import. */ entryPoints: Map<IntegrationRouteData, URL>; /** * File path of the emitted middleware */ middlewareEntryPoint: URL | undefined; logger: AstroIntegrationLogger; }) => void | Promise<v...
@@ -225,13 +217,18 @@ export interface BaseIntegrationHooks { 'astro:build:done': (options: { pages: { pathname: string }[]; dir: URL; + /** @deprecated Use `routes` from `astro:routes:resolved` instead */
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.786
performance
1,091
51
51
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
Fryuni
florian-lefebvre
prerender: boolean; /** * The route to redirect to. It holds information regarding the status code and its destination. */ redirect?: RedirectConfig; /** * The {@link RouteData} to redirect to. It's present when `RouteData.type` is `redirect`. */ redirectRoute?: RouteData; /** * A list of {@link RouteDa...
Some alternatives: - internal: coming from Astro - external: coming from integrations outside Astro core - project: coming from a user project
prerender: boolean; /** * The route to redirect to. It holds information regarding the status code and its destination. */ redirect?: RedirectConfig; /** * The {@link RouteData} to redirect to. It's present when `RouteData.type` is `redirect`. */ redirectRoute?: RouteData; /** * A list of {@link RouteDa...
@@ -136,6 +136,11 @@ export interface RouteData { * - src/pages/blog/index.astro */ isIndex: boolean; + + /** + * Whether the route comes from Astro core, an integration or the user's project + */ + origin: 'core' | 'integration' | 'user';
packages/astro/src/types/public/internal.ts
26
TypeScript
0.429
suggestion
145
51
51
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
*/ export interface SSRMetadata { hasHydrationScript: boolean; /** * Names of renderers that have injected their hydration scripts * into the current page. For example, Solid SSR needs a hydration * script in the page HTML before the first Solid component. */ rendererSpecificHydrationScripts: Set<string>; ...
Let's add a comment, maybe explaining why origin is hardcoded
*/ export interface SSRMetadata { hasHydrationScript: boolean; /** * Names of renderers that have injected their hydration scripts * into the current page. For example, Solid SSR needs a hydration * script in the page HTML before the first Solid component. */ rendererSpecificHydrationScripts: Set<string>; ...
@@ -284,3 +289,14 @@ export interface SSRMetadata { } export type SSRError = Error & ViteErrorPayload['err']; + +export interface InternalInjectedRoute {
packages/astro/src/types/public/internal.ts
26
TypeScript
0.214
suggestion
61
34
36
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
}) => void | Promise<void>; } export interface AstroIntegration { /** The name of the integration. */ name: string; /** The different hooks available to extend. */ hooks: { [K in keyof Astro.IntegrationHooks]?: Astro.IntegrationHooks[K]; } & Partial<Record<string, unknown>>; } /** * A smaller version of the ...
What's the need to create yet another interface? I know that Bjorn expressed a desire to do so. However, the previous PR didn't show an explanation, and even this PR didn't. I am fine with any changes, as long as there's an explanation
logger: AstroIntegrationLogger; }) => void | Promise<void>; } export interface AstroIntegration { /** The name of the integration. */ name: string; /** The different hooks available to extend. */ hooks: { [K in keyof Astro.IntegrationHooks]?: Astro.IntegrationHooks[K]; } & Partial<Record<string, unknown>>; }...
@@ -248,10 +245,41 @@ export interface AstroIntegration { */ export type IntegrationRouteData = Omit< RouteData, - 'isIndex' | 'fallbackRoutes' | 'redirectRoute' + 'isIndex' | 'fallbackRoutes' | 'redirectRoute' | 'origin' > & { /** * {@link RouteData.redirectRoute} */ redirectRoute?: IntegrationRouteDat...
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.5
question
240
51
51
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
/** * A smaller version of the {@link RouteData} that is used in the integrations. */ export type IntegrationRouteData = Omit< RouteData, 'isIndex' | 'fallbackRoutes' | 'redirectRoute' | 'origin' > & { /** * {@link RouteData.redirectRoute} */ redirectRoute?: IntegrationRouteData; }; export interface Integrat...
Why do we change the internal naming? Wouldn't it create fragmentation? Also, we shifted into a pattern where "entrypoint" is `URL` or `string`, where the `string` is an absolute file path. In this case, these are `string`, and they are relative paths. I think we should keep `component`, so they are not misunderstood l...
/** * A smaller version of the {@link RouteData} that is used in the integrations. * @deprecated Use {@link IntegrationResolvedRoute} */ export type IntegrationRouteData = Omit< RouteData, 'isIndex' | 'fallbackRoutes' | 'redirectRoute' | 'origin' > & { /** * {@link RouteData.redirectRoute} */ redirectRoute?...
@@ -248,10 +245,41 @@ export interface AstroIntegration { */ export type IntegrationRouteData = Omit< RouteData, - 'isIndex' | 'fallbackRoutes' | 'redirectRoute' + 'isIndex' | 'fallbackRoutes' | 'redirectRoute' | 'origin' > & { /** * {@link RouteData.redirectRoute} */ redirectRoute?: IntegrationRouteDat...
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.643
question
371
44
46
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
'isIndex' | 'fallbackRoutes' | 'redirectRoute' | 'origin' > & { /** * {@link RouteData.redirectRoute} */ redirectRoute?: IntegrationRouteData; }; export interface IntegrationResolvedRoute { /** * The current **pattern** of the route. For example: * - `src/pages/index.astro` has a pattern of `/` * - `src/...
We should call it `isPrerendered`. That's the same flag we added to `APIContext`. Consistency.
export type IntegrationRouteData = Omit< RouteData, 'isIndex' | 'fallbackRoutes' | 'redirectRoute' | 'origin' > & { /** * {@link RouteData.redirectRoute} */ redirectRoute?: IntegrationRouteData; }; export interface IntegrationResolvedRoute extends Pick< RouteData, 'generate' | 'params' | 'pathname' | 'seg...
@@ -248,10 +245,41 @@ export interface AstroIntegration { */ export type IntegrationRouteData = Omit< RouteData, - 'isIndex' | 'fallbackRoutes' | 'redirectRoute' + 'isIndex' | 'fallbackRoutes' | 'redirectRoute' | 'origin' > & { /** * {@link RouteData.redirectRoute} */ redirectRoute?: IntegrationRouteDat...
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.429
style
95
39
41
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
export interface AstroIntegration { /** The name of the integration. */ name: string; /** The different hooks available to extend. */ hooks: { [K in keyof Astro.IntegrationHooks]?: Astro.IntegrationHooks[K]; } & Partial<Record<string, unknown>>; } /** * A smaller version of the {@link RouteData} that is used i...
The discussion was marked as resolved because of commits, but we need to figure out the renaming of some fields
} export interface AstroIntegration { /** The name of the integration. */ name: string; /** The different hooks available to extend. */ hooks: { [K in keyof Astro.IntegrationHooks]?: Astro.IntegrationHooks[K]; } & Partial<Record<string, unknown>>; } /** * A smaller version of the {@link RouteData} that is use...
@@ -246,12 +242,105 @@ export interface AstroIntegration { /** * A smaller version of the {@link RouteData} that is used in the integrations. */ -export type IntegrationRouteData = Omit< +export type IntegrationRouteData = Pick< RouteData, - 'isIndex' | 'fallbackRoutes' | 'redirectRoute' + 'route' | 'distURL' >...
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.429
style
111
51
51
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
{ isPrerendered: true, entrypoint: 'src/pages/bar.astro', pattern: '/bar', params: [], origin: 'project', }, { isPrerendered: true, entrypoint: 'src/foo.astro', pattern: '/foo', params: [], origin: 'external', },...
This is failing but I can't figure out why. Looks like the partial update of the manifest is not working as expected
}, { isPrerendered: false, entrypoint: '../../../../dist/assets/endpoint/node.js', pattern: '/_image', params: [], origin: 'internal', }, { isPrerendered: false, entrypoint: 'astro-default-404.astro', pattern: '/404', pa...
@@ -131,6 +131,158 @@ describe('Integration API', () => { assert.equal(updatedSettings.config.site, site); assert.equal(updatedSettings.config.integrations.length, 2); }); + + describe('Routes resolved hooks', () => { + it('should work in dev', async () => { + let routes = []; + const fixture = await creat...
packages/astro/test/units/integrations/api.test.js
26
JavaScript
0.357
bug
116
51
51
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
logger, fs: fsMod, manifest: routeManifest, ssrManifest: devSSRManifest, }: AstroPluginOptions): vite.Plugin { return { name: 'astro:server', configureServer(viteServer) { const loader = createViteLoader(viteServer); const pipeline = DevPipeline.create(routeManifest, { loader, logger, manifes...
I don't think we need to use `new URL`. I think `path.endsWith(r.component)` should be enough, because `r.component` is already a byproduct of `URL`
settings, logger, fs: fsMod, manifest: routeManifest, ssrManifest: devSSRManifest, }: AstroPluginOptions): vite.Plugin { return { name: 'astro:server', configureServer(viteServer) { const loader = createViteLoader(viteServer); const pipeline = DevPipeline.create(routeManifest, { loader, logger, ...
@@ -50,26 +53,46 @@ export default function createVitePluginAstroServer({ const controller = createController({ loader }); const localStorage = new AsyncLocalStorage(); - /** rebuild the route cache + manifest, as needed. */ - async function rebuildManifest(needsManifestRebuild: boolean) { + /** rebuild...
packages/astro/src/vite-plugin-astro-server/plugin.ts
26
TypeScript
0.571
suggestion
148
51
51
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
const routePath = fileURLToPath(new URL(route.component, settings.config.root)); if (!fsMod.existsSync(routePath)) { // Route was renamed so it does not exist anymore return; } const content = await fsMod.promises.readFile(routePath, 'utf-8'); await getRoutePrerenderOption(content, ...
```suggestion viteServer.watcher.on('add', rebuildManifest); viteServer.watcher.on('unlink', rebuildManifest); viteServer.watcher.on('change', rebuildManifest); ``` I think this should work
} if (route.type !== 'page' && route.type !== 'endpoint') return; const routePath = fileURLToPath(new URL(route.component, settings.config.root)); try { const content = await fsMod.promises.readFile(routePath, 'utf-8'); await getRoutePrerenderOption(content, route, settings, logger); ...
@@ -50,26 +53,46 @@ export default function createVitePluginAstroServer({ const controller = createController({ loader }); const localStorage = new AsyncLocalStorage(); - /** rebuild the route cache + manifest, as needed. */ - async function rebuildManifest(needsManifestRebuild: boolean) { + /** rebuild...
packages/astro/src/vite-plugin-astro-server/plugin.ts
26
TypeScript
0.857
suggestion
205
51
51
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
manifest: routeManifest, ssrManifest: devSSRManifest, }: AstroPluginOptions): vite.Plugin { return { name: 'astro:server', configureServer(viteServer) { const loader = createViteLoader(viteServer); const pipeline = DevPipeline.create(routeManifest, { loader, logger, manifest: devSSRManifest, ...
There's an edge case where this causes a conflict: - Component `src/pages/index.astro` exists - Component `src/src/pages/index.astro` is edited `path.endsWith(r.component)` will match the index page and apply the prerender option from `src/src/pages/index.astro` instead of its own. ~~At first, I thought of sugg...
fs: fsMod, manifest: routeManifest, ssrManifest: devSSRManifest, }: AstroPluginOptions): vite.Plugin { return { name: 'astro:server', configureServer(viteServer) { const loader = createViteLoader(viteServer); const pipeline = DevPipeline.create(routeManifest, { loader, logger, manifest: devSSR...
@@ -51,13 +54,33 @@ export default function createVitePluginAstroServer({ const localStorage = new AsyncLocalStorage(); /** rebuild the route cache + manifest */ - async function rebuildManifest() { + async function rebuildManifest(path: string | null = null) { pipeline.clearRouteCache(); - routeM...
packages/astro/src/vite-plugin-astro-server/plugin.ts
26
TypeScript
0.786
bug
691
51
51
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
Fryuni
florian-lefebvre
const pipeline = DevPipeline.create(routeManifest, { loader, logger, manifest: devSSRManifest, settings, }); const controller = createController({ loader }); const localStorage = new AsyncLocalStorage(); /** rebuild the route cache + manifest */ async function rebuildManifest(path: st...
Shouldn't the manifest be updated in this case so it knows about the new name and stops handling the old one?
const loader = createViteLoader(viteServer); const pipeline = DevPipeline.create(routeManifest, { loader, logger, manifest: devSSRManifest, settings, }); const controller = createController({ loader }); const localStorage = new AsyncLocalStorage(); /** rebuild the route cache + manife...
@@ -51,13 +54,33 @@ export default function createVitePluginAstroServer({ const localStorage = new AsyncLocalStorage(); /** rebuild the route cache + manifest */ - async function rebuildManifest() { + async function rebuildManifest(path: string | null = null) { pipeline.clearRouteCache(); - routeM...
packages/astro/src/vite-plugin-astro-server/plugin.ts
26
TypeScript
0.429
question
109
51
51
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
Fryuni
florian-lefebvre
const loader = createViteLoader(viteServer); const pipeline = DevPipeline.create(routeManifest, { loader, logger, manifest: devSSRManifest, settings, }); const controller = createController({ loader }); const localStorage = new AsyncLocalStorage(); /** rebuild the route cache + manife...
`route.component` can also be an import path (like `@astrojs/starlight/index.astro`). In that case the `new URL` won't resolve to the file path so it will reach this conditional. I don't think this is a problem since this would only be reached on a conflict from my other comment. But maybe it should be in the commen...
configureServer(viteServer) { const loader = createViteLoader(viteServer); const pipeline = DevPipeline.create(routeManifest, { loader, logger, manifest: devSSRManifest, settings, }); const controller = createController({ loader }); const localStorage = new AsyncLocalStorage(); /** ...
@@ -51,13 +54,33 @@ export default function createVitePluginAstroServer({ const localStorage = new AsyncLocalStorage(); /** rebuild the route cache + manifest */ - async function rebuildManifest() { + async function rebuildManifest(path: string | null = null) { pipeline.clearRouteCache(); - routeM...
packages/astro/src/vite-plugin-astro-server/plugin.ts
26
TypeScript
0.643
suggestion
322
51
51
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
Fryuni
florian-lefebvre
loader, logger, manifest: devSSRManifest, settings, }); const controller = createController({ loader }); const localStorage = new AsyncLocalStorage(); /** rebuild the route cache + manifest */ async function rebuildManifest(path: string | null = null) { pipeline.clearRouteCache(); ...
There is technically a race here. The file could be deleted in between the call to `existsSync` and `readFile`, this would throw an error in that case. We can change this to use only `readFile` and detect a non-existing file from the error.
const pipeline = DevPipeline.create(routeManifest, { loader, logger, manifest: devSSRManifest, settings, }); const controller = createController({ loader }); const localStorage = new AsyncLocalStorage(); /** rebuild the route cache + manifest */ async function rebuildManifest(path: st...
@@ -51,13 +54,33 @@ export default function createVitePluginAstroServer({ const localStorage = new AsyncLocalStorage(); /** rebuild the route cache + manifest */ - async function rebuildManifest() { + async function rebuildManifest(path: string | null = null) { pipeline.clearRouteCache(); - routeM...
packages/astro/src/vite-plugin-astro-server/plugin.ts
26
TypeScript
0.786
suggestion
240
51
51
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
Fryuni
florian-lefebvre
/** * A smaller version of the {@link RouteData} that is used in the integrations. * @deprecated Use {@link IntegrationResolvedRoute} */ export type IntegrationRouteData = Omit< RouteData, 'isIndex' | 'fallbackRoutes' | 'redirectRoute' | 'origin' > & { /** * {@link RouteData.redirectRoute} */ redirectRoute?:...
(optional) Maybe this could use `Pick` so we don't accidentally expose new props
/** * A smaller version of the {@link RouteData} that is used in the integrations. * @deprecated Use {@link IntegrationResolvedRoute} */ export type IntegrationRouteData = Omit< RouteData, 'isIndex' | 'fallbackRoutes' | 'redirectRoute' | 'origin' > & { /** * {@link RouteData.redirectRoute} */ redirectRoute?:...
@@ -245,13 +243,52 @@ export interface AstroIntegration { /** * A smaller version of the {@link RouteData} that is used in the integrations. + * @deprecated Use {@link IntegrationResolvedRoute} */ export type IntegrationRouteData = Omit< RouteData, - 'isIndex' | 'fallbackRoutes' | 'redirectRoute' + 'isIndex' ...
packages/astro/src/types/public/integrations.ts
26
TypeScript
0.429
suggestion
80
51
45
false
feat(next): astro:routes:resolved
12,329
withastro/astro
47,179
TypeScript
bluwy
florian-lefebvre
TextColumnOpts, } from '../core/types.js'; function createColumn<S extends string, T extends Record<string, unknown>>(type: S, schema: T) { return { type, /** * @internal */ schema, }; } export function isDbError(err: unknown): err is LibsqlError { // guard for `err instanceof LibsqlError` if (!err |...
It looks like the libsql errors also have the `libsqlError: true` property which perhaps should be sufficient enough for the checks? Here was the logs: <details> <summary>open logs</summary> ``` Error thrown: Error: UNIQUE constraint failed: User.name at Object.next (/Users/bjorn/Work/repros/astro-issue-12...
TextColumnOpts, } from '../core/types.js'; function createColumn<S extends string, T extends Record<string, unknown>>(type: S, schema: T) { return { type, /** * @internal */ schema, }; } export const column = { number: <T extends NumberColumnOpts>(opts: T = {} as T) => { return createColumn('number'...
@@ -22,7 +22,18 @@ function createColumn<S extends string, T extends Record<string, unknown>>(type: } export function isDbError(err: unknown): err is LibsqlError { - return err instanceof LibsqlError; + // guard for `err instanceof LibsqlError` + if (!err || !(err instanceof Error)) return false; + const value = er...
packages/db/src/runtime/virtual.ts
26
TypeScript
1
bug
2,129
51
51
false
🐛 Fix isDbError()-guard does not work
12,416
withastro/astro
47,179
TypeScript
bluwy
abegehr
import { existsSync } from 'node:fs'; import type { AstroConfig } from 'astro'; import { green } from 'kleur/colors'; import type { Arguments } from 'yargs-parser'; import { EXEC_DEFAULT_EXPORT_ERROR, EXEC_ERROR, FILE_NOT_FOUND_ERROR, MISSING_EXECUTE_PATH_ERROR, } from '../../../errors.js'; import { getLocalVirtua...
I don't know if this causes the CI fail, but I _think_ we may need to copy `isDbError` into `../../../utils.js` so there's two implementations of it for now. The `virtual.js` is only for the `astro:db` virtual module and we don't want to mix it with the non-virtual code.
import { existsSync } from 'node:fs'; import type { AstroConfig } from 'astro'; import { green } from 'kleur/colors'; import type { Arguments } from 'yargs-parser'; import { EXEC_DEFAULT_EXPORT_ERROR, EXEC_ERROR, FILE_NOT_FOUND_ERROR, MISSING_EXECUTE_PATH_ERROR, } from '../../../errors.js'; import { getLocalVirtua...
@@ -16,6 +15,7 @@ import { import { bundleFile, importBundledFile } from '../../../load-file.js'; import type { DBConfig } from '../../../types.js'; import { getManagedRemoteToken } from '../../../utils.js'; +import { isDbError } from '../../../../runtime/virtual.js';
packages/db/src/core/cli/commands/execute/index.ts
18
TypeScript
0.786
bug
271
43
43
false
🐛 Fix isDbError()-guard does not work
12,416
withastro/astro
47,179
TypeScript
bluwy
abegehr
type GenerationData = GenerationDataUncached | GenerationDataCached; type AssetEnv = { logger: Logger; isSSR: boolean; count: { total: number; current: number }; useCache: boolean; assetsCacheDir: URL; serverRoot: URL; clientRoot: URL; imageConfig: AstroConfig['image']; assetsFolder: AstroConfig['build']['ass...
Internally, we try to avoid TS features that generate code. In this case, a variant is better: ```ts const CACHE_STATUS = "miss" | "revalidated" | "hit" ```
type AssetEnv = { logger: Logger; isSSR: boolean; count: { total: number; current: number }; useCache: boolean; assetsCacheDir: URL; serverRoot: URL; clientRoot: URL; imageConfig: AstroConfig['image']; assetsFolder: AstroConfig['build']['assets']; }; type ImageData = { data: Uint8Array; expires: number; e...
@@ -44,7 +44,17 @@ type AssetEnv = { assetsFolder: AstroConfig['build']['assets']; }; -type ImageData = { data: Uint8Array; expires: number }; +type ImageData = { + data: Uint8Array; + expires: number; + etag?: string | null; +}; + +enum CacheStatus { + Miss = 0, + Revalidated, + Hit, +}
packages/astro/src/assets/build/generate.ts
26
TypeScript
0.786
performance
163
51
51
false
feat(assets): Use entity-tags to revalidate cached remote images
12,426
withastro/astro
47,179
TypeScript
ematipico
oliverlynch
return { cached: CacheStatus.Hit, }; } else { const JSONData = JSON.parse(readFileSync(cachedFileURL, 'utf-8')) as RemoteCacheEntry; if (!JSONData.data || !JSONData.expires) { await fs.promises.unlink(cachedFileURL); throw new Error( `Malformed cache entry for ${filepath}, cach...
Is it safe to cast `src` to `string`?
const JSONData = JSON.parse(readFileSync(cachedFileURL, 'utf-8')) as RemoteCacheEntry; if (!JSONData.data || !JSONData.expires) { await fs.promises.unlink(cachedFileURL); throw new Error( `Malformed cache entry for ${filepath}, cache will be regenerated for this file.`, ); } // I...
@@ -184,11 +196,29 @@ export async function generateImagesForPath( await fs.promises.writeFile(finalFileURL, Buffer.from(JSONData.data, 'base64')); return { - cached: true, + cached: CacheStatus.Hit, }; - } else { - await fs.promises.unlink(cachedFileURL); } + + // Try to re...
packages/astro/src/assets/build/generate.ts
26
TypeScript
0.357
question
38
51
51
false
feat(assets): Use entity-tags to revalidate cached remote images
12,426
withastro/astro
47,179
TypeScript
ematipico
oliverlynch
if (!JSONData.data || !JSONData.expires) { await fs.promises.unlink(cachedFileURL); throw new Error( `Malformed cache entry for ${filepath}, cache will be regenerated for this file.`, ); } // If the cache entry is not expired, use it if (JSONData.expires > Date.now()) { await...
Should we at least use a `try/catch` with `Buffer.from`? In case it fails, should we should handle the error gracefully
`Malformed cache entry for ${filepath}, cache will be regenerated for this file.`, ); } // If the cache entry is not expired, use it if (JSONData.expires > Date.now()) { await fs.promises.writeFile(finalFileURL, Buffer.from(JSONData.data, 'base64')); return { cached: 'hit', ...
@@ -184,11 +196,29 @@ export async function generateImagesForPath( await fs.promises.writeFile(finalFileURL, Buffer.from(JSONData.data, 'base64')); return { - cached: true, + cached: CacheStatus.Hit, }; - } else { - await fs.promises.unlink(cachedFileURL); } + + // Try to re...
packages/astro/src/assets/build/generate.ts
26
TypeScript
0.714
bug
120
51
51
false
feat(assets): Use entity-tags to revalidate cached remote images
12,426
withastro/astro
47,179
TypeScript
ematipico
oliverlynch
import type { AstroConfig } from '../../@types/astro.js'; import { getOutDirWithinCwd } from '../../core/build/common.js'; import type { BuildPipeline } from '../../core/build/pipeline.js'; import { getTimeStat } from '../../core/build/util.js'; import { AstroError } from '../../core/errors/errors.js'; import { AstroEr...
`CacheStatus.Revalidated` is never read (only `.Hit`). At this point isn't a boolean a better fit?
import { getOutDirWithinCwd } from '../../core/build/common.js'; import type { BuildPipeline } from '../../core/build/pipeline.js'; import { getTimeStat } from '../../core/build/util.js'; import { AstroError } from '../../core/errors/errors.js'; import { AstroErrorData } from '../../core/errors/index.js'; import type {...
@@ -16,18 +16,18 @@ import { getConfiguredImageService } from '../internal.js'; import type { LocalImageService } from '../services/service.js'; import type { AssetsGlobalStaticImagesList, ImageMetadata, ImageTransform } from '../types.js'; import { isESMImportedImage } from '../utils/imageKind.js'; -import { type R...
packages/astro/src/assets/build/generate.ts
26
TypeScript
0.429
performance
99
51
51
false
feat(assets): Use entity-tags to revalidate cached remote images
12,426
withastro/astro
47,179
TypeScript
ematipico
oliverlynch
`An error was encountered while creating the cache directory. Proceeding without caching. Error: ${e}`, ); } finally { // Write the final file await fs.promises.writeFile(finalFileURL, resultData.data); } return { cached: CacheStatus.Miss, weight: { // Divide by 1024 to get size in kilobyt...
`JSON.stringify` and `Buffer.from` can be both fail at runtime, we should handle the errors somehow
// Write the cache entry if (env.useCache) { if (isLocalImage) { await fs.promises.writeFile(cachedFileURL, resultData.data); } else { await writeRemoteCacheFile(cachedFileURL, resultData as ImageData, env); } } } catch (e) { env.logger.warn( null, `An error was encountered w...
@@ -269,6 +294,17 @@ export async function generateImagesForPath( } } +async function writeRemoteCacheFile(cachedFileURL: URL, resultData: ImageData) { + return await fs.promises.writeFile( + cachedFileURL, + JSON.stringify({ + data: Buffer.from(resultData.data).toString('base64'), + expires: resultData.expi...
packages/astro/src/assets/build/generate.ts
26
TypeScript
0.571
bug
100
48
51
false
feat(assets): Use entity-tags to revalidate cached remote images
12,426
withastro/astro
47,179
TypeScript
ematipico
oliverlynch
import CachePolicy from 'http-cache-semantics'; export type RemoteCacheEntry = { data: string; expires: number; etag?: string }; export async function loadRemoteImage(src: string) { const req = new Request(src); const res = await fetch(req); if (!res.ok) { throw new Error( `Failed to load remote image ${src}...
It think it's valuable to document the business logic of the function. For example, you used some headers, checked specific status codes and more. From a POV of a reviewer (me), I have no idea what's going on, so it's available to have this knowledge base written a JSDoc, so other developers will know about it.
import CachePolicy from 'http-cache-semantics'; export type RemoteCacheEntry = { data: string; expires: number; etag?: string; lastModified?: string; }; export async function loadRemoteImage(src: string) { const req = new Request(src); const res = await fetch(req); if (!res.ok) { throw new Error( `Failed...
@@ -19,6 +19,40 @@ export async function loadRemoteImage(src: string) { return { data: Buffer.from(await res.arrayBuffer()), expires: Date.now() + expires, + etag: res.headers.get('Etag'), + }; +} + +export async function revalidateRemoteImage(src: string, etag: string) {
packages/astro/src/assets/build/remote.ts
26
TypeScript
0.5
suggestion
314
51
51
false
feat(assets): Use entity-tags to revalidate cached remote images
12,426
withastro/astro
47,179
TypeScript
ematipico
oliverlynch
const res = await fetch(req); if (!res.ok) { throw new Error( `Failed to load remote image ${src}. The request did not return a 200 OK response. (received ${res.status}))`, ); } // calculate an expiration date based on the response's TTL const policy = new CachePolicy(webToCachePolicyRequest(req), webToCa...
This error isn't actionable. If a user sees that, they don't know what to do in order to fix it. We should provide a better error that gives the user an action.
lastModified?: string; }; export async function loadRemoteImage(src: string) { const req = new Request(src); const res = await fetch(req); if (!res.ok) { throw new Error( `Failed to load remote image ${src}. The request did not return a 200 OK response. (received ${res.status}))`, ); } // calculate an e...
@@ -19,6 +19,40 @@ export async function loadRemoteImage(src: string) { return { data: Buffer.from(await res.arrayBuffer()), expires: Date.now() + expires, + etag: res.headers.get('Etag'), + }; +} + +export async function revalidateRemoteImage(src: string, etag: string) { + const req = new Request(src, { heade...
packages/astro/src/assets/build/remote.ts
26
TypeScript
0.571
suggestion
161
51
51
false
feat(assets): Use entity-tags to revalidate cached remote images
12,426
withastro/astro
47,179
TypeScript
ematipico
oliverlynch
export type RemoteCacheEntry = { data: string; expires: number; etag?: string }; export async function loadRemoteImage(src: string) { const req = new Request(src); const res = await fetch(req); if (!res.ok) { throw new Error( `Failed to load remote image ${src}. The request did not return a 200 OK response. (...
```suggestion * Uses the [If-None-Match](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match) header to check with the remote server if the cached version of a remote asset is still up to date. ```
export type RemoteCacheEntry = { data: string; expires: number; etag?: string; lastModified?: string; }; export async function loadRemoteImage(src: string) { const req = new Request(src); const res = await fetch(req); if (!res.ok) { throw new Error( `Failed to load remote image ${src}. The request did not...
@@ -19,6 +19,48 @@ export async function loadRemoteImage(src: string) { return { data: Buffer.from(await res.arrayBuffer()), expires: Date.now() + expires, + etag: res.headers.get('Etag'), + }; +} + +/** + * Revalidate a cached remote asset using its entity-tag. + * Uses the If-None-Match header to check with ...
packages/astro/src/assets/build/remote.ts
26
TypeScript
0.857
performance
220
51
51
false
feat(assets): Use entity-tags to revalidate cached remote images
12,426
withastro/astro
47,179
TypeScript
ematipico
oliverlynch
} // calculate an expiration date based on the response's TTL const policy = new CachePolicy(webToCachePolicyRequest(req), webToCachePolicyResponse(res)); const expires = policy.storable() ? policy.timeToLive() : 0; return { data: Buffer.from(await res.arrayBuffer()), expires: Date.now() + expires, etag: r...
```suggestion // Asset not modified: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304 if (!res.ok && res.status !== 304) { ```
if (!res.ok) { throw new Error( `Failed to load remote image ${src}. The request did not return a 200 OK response. (received ${res.status}))`, ); } // calculate an expiration date based on the response's TTL const policy = new CachePolicy(webToCachePolicyRequest(req), webToCachePolicyResponse(res)); const...
@@ -19,6 +19,48 @@ export async function loadRemoteImage(src: string) { return { data: Buffer.from(await res.arrayBuffer()), expires: Date.now() + expires, + etag: res.headers.get('Etag'), + }; +} + +/** + * Revalidate a cached remote asset using its entity-tag. + * Uses the If-None-Match header to check with ...
packages/astro/src/assets/build/remote.ts
26
TypeScript
0.714
suggestion
144
51
51
false
feat(assets): Use entity-tags to revalidate cached remote images
12,426
withastro/astro
47,179
TypeScript
ematipico
oliverlynch
throw new Error( `Failed to load remote image ${src}. The request did not return a 200 OK response. (received ${res.status}))`, ); } // calculate an expiration date based on the response's TTL const policy = new CachePolicy(webToCachePolicyRequest(req), webToCachePolicyResponse(res)); const expires = policy...
It would be worth also supporting `If-Modified-Since`, and storing the `Last-Modified` or `Date` for image responses that don't include an etag.
export async function loadRemoteImage(src: string) { const req = new Request(src); const res = await fetch(req); if (!res.ok) { throw new Error( `Failed to load remote image ${src}. The request did not return a 200 OK response. (received ${res.status}))`, ); } // calculate an expiration date based on the ...
@@ -19,6 +19,49 @@ export async function loadRemoteImage(src: string) { return { data: Buffer.from(await res.arrayBuffer()), expires: Date.now() + expires, + etag: res.headers.get('Etag'), + }; +} + +/** + * Revalidate a cached remote asset using its entity-tag. + * Uses the [If-None-Match](https://developer.m...
packages/astro/src/assets/build/remote.ts
26
TypeScript
0.5
suggestion
144
51
51
false
feat(assets): Use entity-tags to revalidate cached remote images
12,426
withastro/astro
47,179
TypeScript
ascorbic
oliverlynch
`An error was encountered while creating the cache directory. Proceeding without caching. Error: ${e}`, ); } finally { // Write the final file await fs.promises.writeFile(finalFileURL, resultData.data); } return { cached: 'miss', weight: { // Divide by 1024 to get size in kilobytes bef...
I realise that this is what we were already doing, but it does seem a bit wasteful to be saving images as JSON-encoded base64 strings, and this could be a good time to fix it. I think it would be better to store the image in a binary, and then use a separate JSON file for metadata, probably with the same filename along...
env.logger.warn( null, `An error was encountered while creating the cache directory. Proceeding without caching. Error: ${e}`, ); } finally { // Write the final file await fs.promises.writeFile(finalFileURL, resultData.data); } return { cached: 'miss', weight: { // Divide by 1024 to...
@@ -269,6 +303,24 @@ export async function generateImagesForPath( } } +async function writeRemoteCacheFile(cachedFileURL: URL, resultData: ImageData, env: AssetEnv) { + try { + return await fs.promises.writeFile( + cachedFileURL, + JSON.stringify({ + data: Buffer.from(resultData.data).toString('base64'),
packages/astro/src/assets/build/generate.ts
26
TypeScript
0.643
suggestion
371
51
51
false
feat(assets): Use entity-tags to revalidate cached remote images
12,426
withastro/astro
47,179
TypeScript
ascorbic
oliverlynch
env.imageConfig, ) ).data; } catch (e) { const error = new AstroError( { ...AstroErrorData.CouldNotTransformImage, message: AstroErrorData.CouldNotTransformImage.message(originalFilePath), }, { cause: e }, ); throw error; } try { // Write the cache entry if (env....
I have no idea what happened here, but thank you for cleaning it, ha
originalImage.data, { ...options, src: originalImagePath }, env.imageConfig, ) ).data; } catch (e) { const error = new AstroError( { ...AstroErrorData.CouldNotTransformImage, message: AstroErrorData.CouldNotTransformImage.message(originalFilePath), }, { cause: e }, );...
@@ -279,11 +331,7 @@ export function getStaticImageList(): AssetsGlobalStaticImagesList { async function loadImage(path: string, env: AssetEnv): Promise<ImageData> { if (isRemotePath(path)) { - const remoteImage = await loadRemoteImage(path); - return { - data: remoteImage.data, - expires: remoteImage.expire...
packages/astro/src/assets/build/generate.ts
26
TypeScript
0.214
suggestion
68
51
51
false
feat(assets): Use entity-tags to revalidate cached remote images
12,426
withastro/astro
47,179
TypeScript
Princesseuh
oliverlynch
}); if (files.length === 0) return; return await Promise.all( files.map(async function copyFile(filename) { const from = new URL(filename, fromFolder); const to = new URL(filename, toFolder); const lastFolder = new URL('./', to); return fs.promises.mkdir(lastFolder, { recursive: true }).then(async func...
I'm not sure this is the best way to check if the user has defined custom assetFileNames. I am open to suggestions for a better approach.
import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { teardown } from '@astrojs/compiler'; import glob from 'fast-glob'; import { bgGreen, black, green } from 'kleur/colors'; import * as vite from 'vite'; import { type BuildInternals, createBuildIntern...
@@ -470,30 +475,36 @@ export async function copyFiles(fromFolder: URL, toFolder: URL, includeDotfiles ); } -async function ssrMoveAssets(opts: StaticBuildOptions) { +async function ssrMoveAssets(opts: StaticBuildOptions, ssrOutputAssetNames: string[]) { opts.logger.info('build', 'Rearranging server assets...'); ...
packages/astro/src/core/build/static-build.ts
26
TypeScript
0.429
suggestion
137
51
476
false
fix custom `assetFileNames` issue
12,449
withastro/astro
47,179
TypeScript
apatel369
apatel369
$ = cheerio.load(html); assert.equal($('h1').text(), 'Client Directives'); }); it('renders SSR custom renderer functional components as expected', async () => { const res = await fixture.fetch('/'); assert.equal(res.status, 200); const html = await res.text(); $ = cheerio.load(html); assert....
I think I'd prefer removing this test since it's only guarding if we ever revert this PR, which if we do we probably have a good reason for it. That way we also avoiding patching `console.warn` for this test. The other test cases are fine to keep though, we're lacking tests for custom renderers.
import assert from 'node:assert/strict'; import { after, before, describe, it } from 'node:test'; import * as cheerio from 'cheerio'; import { loadFixture } from './test-utils.js'; describe('Custom Renderer - SSR', () => { let fixture; before(async () => { fixture = await loadFixture({ root: './fixtures/custom...
@@ -0,0 +1,69 @@ +import assert from 'node:assert/strict'; +import { after, before, describe, it } from 'node:test'; +import * as cheerio from 'cheerio'; +import { loadFixture } from './test-utils.js'; + +describe('Custom Renderer - SSR', () => { + let fixture; + let warnLogsWritten = ''; + + // store the original cons...
packages/astro/test/custom-renderer.test.js
26
JavaScript
0.643
suggestion
299
28
43
false
Remove misleading warning when using a custom renderer
12,461
withastro/astro
47,179
TypeScript
bluwy
kyr0
fancy?: boolean; add?: string[]; dryRun?: boolean; yes?: boolean; projectName?: string; template?: string; ref: string; install?: boolean; git?: boolean; typescript?: string; stdin?: typeof process.stdin; stdout?: typeof process.stdout; exit(code: number): never; welcome?: string; hat?: string; tie?: st...
Should we play a bit safer here and only allow known tags? e.g. ```js switch (packageSpecifier) { case 'alpha': case 'beta': case 'rc': return packageSpecifier; default: return 'latest' } ``` The code here is inferring the tag between `create-astro` and `astro`, and they might not match i...
fancy?: boolean; add?: string[]; dryRun?: boolean; yes?: boolean; projectName?: string; template?: string; ref: string; install?: boolean; git?: boolean; typescript?: string; stdin?: typeof process.stdin; stdout?: typeof process.stdout; exit(code: number): never; welcome?: string; hat?: string; tie?: st...
@@ -34,6 +34,13 @@ export interface Context { } export async function getContext(argv: string[]): Promise<Context> { + const packageSpecifier = argv + .find((argItem) => /^(astro|create-astro)@/.exec(argItem)) + ?.split('@')[1]; + // Fallback to 'latest' if it's a version number + const packageTag = + packageSpe...
packages/create-astro/src/actions/context.ts
26
TypeScript
0.857
question
349
51
51
false
fix(create-astro): use CLI version tag to determine `astro` version
12,529
withastro/astro
47,179
TypeScript
bluwy
apatel369
let request = new Request('http://example.com/new-site/it/start'); let response = await app.render(request); assert.equal(response.status, 302); assert.equal(response.headers.get('location'), '/new-site/start'); }); it('should redirect to the english locale when locale has codes+path', async () => { ...
```suggestion assert.match(text, /Oi essa e start/); assert.match(text, /search=1/); ```
let request = new Request('http://example.com/new-site/it/start'); let response = await app.render(request); assert.equal(response.status, 302); assert.equal(response.headers.get('location'), '/new-site/start'); }); it('should redirect to the english locale when locale has codes+path', async () => { ...
@@ -1582,6 +1582,22 @@ describe('[SSR] i18n routing', () => { assert.equal(response.status, 404); }); + it('should pass search to render when using requested locale', async () => { + let request = new Request('http://example.com/new-site/pt/start?search=1'); + let response = await app.render(request); + ...
packages/astro/test/i18n-routing.test.js
26
JavaScript
0.571
suggestion
97
51
51
false
fix(i18n): pass search params to fallback
12,547
withastro/astro
47,179
TypeScript
ematipico
mtwilliams-code
export function vitePluginServerIslands({ settings, logger }: AstroPluginOptions): VitePlugin { let command: ConfigEnv['command'] = 'serve'; let viteServer: ViteDevServer | null = null; const referenceIdMap = new Map<string, string>(); return { name: 'astro:server-islands', enforce: 'post', config(_config, {...
This was preventing retrieving server islands data from mdx files metadata
export function vitePluginServerIslands({ settings, logger }: AstroPluginOptions): VitePlugin { let command: ConfigEnv['command'] = 'serve'; let viteServer: ViteDevServer | null = null; const referenceIdMap = new Map<string, string>(); return { name: 'astro:server-islands', enforce: 'post', config(_config, {...
@@ -31,52 +31,49 @@ export function vitePluginServerIslands({ settings, logger }: AstroPluginOptions } }, transform(_code, id) { - if (id.endsWith('.astro')) {
packages/astro/src/core/server-islands/vite-plugin-server-islands.ts
26
TypeScript
0.214
suggestion
74
51
51
false
feat: add server islands support for `MDX`
12,574
withastro/astro
47,179
TypeScript
florian-lefebvre
apatel369
(await Promise.all(vnode.map((v: any) => renderJSX(result, v)))).join(''), ); } return renderJSXVNode(result, vnode); } async function renderJSXVNode(result: SSRResult, vnode: AstroVNode): Promise<any> { if (isVNode(vnode)) { // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check swi...
This was calling the component factory as is. Instead, we want it to go through `renderAstroComponent` so the server island special handling can take effect
} return renderJSXVNode(result, vnode); } async function renderJSXVNode(result: SSRResult, vnode: AstroVNode): Promise<any> { if (isVNode(vnode)) { // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check switch (true) { case !vnode.type: { throw new Error(`Unable to render ${result.pa...
@@ -64,7 +66,10 @@ Did you forget to import the component or is it possible there is a typo?`); props[key] = value; } } - const str = await renderToString(result, vnode.type as any, props, slots);
packages/astro/src/runtime/server/jsx.ts
26
TypeScript
0.571
suggestion
156
51
51
false
feat: add server islands support for `MDX`
12,574
withastro/astro
47,179
TypeScript
florian-lefebvre
apatel369
} async function renderJSXVNode(result: SSRResult, vnode: AstroVNode): Promise<any> { if (isVNode(vnode)) { // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check switch (true) { case !vnode.type: { throw new Error(`Unable to render ${result.pathname} because it contains an undefined Co...
`renderAstroComponent` is not exposed so I slightly refactored `renderToString` to expose the underlying render template logic
async function renderJSXVNode(result: SSRResult, vnode: AstroVNode): Promise<any> { if (isVNode(vnode)) { // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check switch (true) { case !vnode.type: { throw new Error(`Unable to render ${result.pathname} because it contains an undefined Compo...
@@ -64,7 +66,10 @@ Did you forget to import the component or is it possible there is a typo?`); props[key] = value; } } - const str = await renderToString(result, vnode.type as any, props, slots); + const str = await renderTemplateResultToString( + result, + renderTemplate`${await render...
packages/astro/src/runtime/server/jsx.ts
26
TypeScript
0.571
refactor
126
51
51
false
feat: add server islands support for `MDX`
12,574
withastro/astro
47,179
TypeScript
florian-lefebvre
apatel369
viteServer = _server; }, resolveId(name) { if (name === VIRTUAL_ISLAND_MAP_ID) { return RESOLVED_VIRTUAL_ISLAND_MAP_ID; } }, load(id) { if (id === RESOLVED_VIRTUAL_ISLAND_MAP_ID) { return { code: `export const serverIslandMap = ${serverIslandPlaceholder};` }; } }, transform(_code, id)...
```suggestion logger.error( 'islands', 'You tried to render a server island without an adapter added to your project. An adapter is required to use the `server:defer` attribute on any component. Your project will fail to build unless you add an adapter or remove the attribute.', ); ...
viteServer = _server; }, resolveId(name) { if (name === VIRTUAL_ISLAND_MAP_ID) { return RESOLVED_VIRTUAL_ISLAND_MAP_ID; } }, load(id) { if (id === RESOLVED_VIRTUAL_ISLAND_MAP_ID) { return { code: `export const serverIslandMap = ${serverIslandPlaceholder};` }; } }, transform(_code, id)...
@@ -31,52 +31,50 @@ export function vitePluginServerIslands({ settings, logger }: AstroPluginOptions } }, transform(_code, id) { - if (id.endsWith('.astro')) { - const info = this.getModuleInfo(id); - if (info?.meta) { - const astro = info.meta.astro as AstroPluginMetadata['astro'] | undefined; - ...
packages/astro/src/core/server-islands/vite-plugin-server-islands.ts
26
TypeScript
1
bug
478
51
51
false
feat: add server islands support for `MDX`
12,574
withastro/astro
47,179
TypeScript
ematipico
apatel369
// @ts-check import { schema } from 'virtual:astro:env/internal'; import { createInvalidVariablesError, getEnv as _getEnv, getEnvFieldType, setOnSetGetEnv, validateEnvVariable, } from 'astro/env/runtime'; const getEnv = (key) => { // @@GET_ENV@@ return _getEnv(key); } export const getSecret = (key) => { retur...
This code will end up with two `return` statements, which isn't the best. Maybe we can leave the placeholder and add an `else` clause to the `if` we have `vite-plugin-env.ts`, line 157, which will replace the placeholder with `return _getEnv(key)`
// @ts-check import { schema } from 'virtual:astro:env/internal'; import { createInvalidVariablesError, getEnv as _getEnv, getEnvFieldType, setOnSetGetEnv, validateEnvVariable, } from 'astro/env/runtime'; // @ts-expect-error /** @returns {string} */ // used while generating the virtual module // biome-ignore lint...
@@ -2,14 +2,19 @@ import { schema } from 'virtual:astro:env/internal'; import { createInvalidVariablesError, - getEnv, + getEnv as _getEnv, getEnvFieldType, setOnSetGetEnv, validateEnvVariable, } from 'astro/env/runtime'; +const getEnv = (key) => { + // @@GET_ENV@@ + return _getEnv(key);
packages/astro/templates/env.mjs
13
JavaScript
0.643
suggestion
247
36
38
false
fix: do not freeze process.env in dev
12,585
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
// @ts-check import { schema } from 'virtual:astro:env/internal'; import { createInvalidVariablesError, getEnv as _getEnv, getEnvFieldType, setOnSetGetEnv, validateEnvVariable, } from 'astro/env/runtime'; // @ts-ignore /** @returns {string} */ // used while generating the virtual module // biome-ignore lint/corre...
```suggestion // @ts-expect-error ```
// @ts-check import { schema } from 'virtual:astro:env/internal'; import { createInvalidVariablesError, getEnv as _getEnv, getEnvFieldType, setOnSetGetEnv, validateEnvVariable, } from 'astro/env/runtime'; // @ts-expect-error /** @returns {string} */ // used while generating the virtual module // biome-ignore lint...
@@ -2,14 +2,23 @@ import { schema } from 'virtual:astro:env/internal'; import { createInvalidVariablesError, - getEnv, + getEnv as _getEnv, getEnvFieldType, setOnSetGetEnv, validateEnvVariable, } from 'astro/env/runtime'; +// @ts-ignore
packages/astro/templates/env.mjs
11
JavaScript
0.571
suggestion
39
36
36
false
fix: do not freeze process.env in dev
12,585
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
); const hasKey = hasEnvironmentKey(); const keyPromise = hasKey ? getEnvironmentKey() : createKey(); const opts: StaticBuildOptions = { allPages, settings: this.settings, logger: this.logger, manifest: this.manifest, runtimeMode: this.runtimeMode, origin: this.origin, pageNames, teard...
Looks like the data is not passed to the manifest, probably a matter of changing when this is called
const hasKey = hasEnvironmentKey(); const keyPromise = hasKey ? getEnvironmentKey() : createKey(); const opts: StaticBuildOptions = { allPages, settings: this.settings, logger: this.logger, manifest: this.manifest, runtimeMode: this.runtimeMode, origin: this.origin, pageNames, teardownCo...
@@ -214,9 +209,15 @@ class AstroBuilder { const { internals, ssrOutputChunkNames, contentFileNames } = await viteBuild(opts); const hasServerIslands = this.settings.serverIslandNameMap.size > 0; - // Error if there are server islands but no adapter provided. - if (hasServerIslands && this.settings.buildOutput...
packages/astro/src/core/build/index.ts
26
TypeScript
0.357
suggestion
100
51
51
false
feat: route manifest refactor
12,597
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
const routeData = routes[index]; routeData.fallbackRoutes.push(fallbackRoute); } } } } } } } if (dev) { ensure404Route({ routes }); injectImageEndpoint(settings, { routes }, 'dev'); injectServerIslandRoute(settings.config, { routes }); } else if (settings.buildOutput...
Is this intended? Now, the hook is called even in dev.
const routeData = routes[index]; routeData.fallbackRoutes.push(fallbackRoute); } } } } } } } if (dev) { // In SSR, a 404 route is injected in the App directly for some special handling, // it must not appear in the manifest ensure404Route({ routes }); } if (dev || s...
@@ -732,9 +735,20 @@ export async function createRouteManifest( } } - if (!dev) { - await runHookRoutesResolved({ routes, settings, logger }); + if (dev) { + ensure404Route({ routes }); + injectImageEndpoint(settings, { routes }, 'dev'); + injectServerIslandRoute(settings.config, { routes }); + } else if (se...
packages/astro/src/core/routing/manifest/create.ts
26
TypeScript
0.214
question
55
51
51
false
feat: route manifest refactor
12,597
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
pattern: getPattern(segments, config.base, config.trailingSlash), type: 'fallback', fallbackRoutes: [], }; const routeData = routes[index]; routeData.fallbackRoutes.push(fallbackRoute); } } } } } } } if (dev) { ensure404Route({ routes })...
Can't we write the code like this? Less branching and less repetition. ```js if (dev || severOutput) { if (dev) { ensure404() } injectInternaloutes() } ``` It would be nice to have a generic function called `injectInternalRoutes`, so future routes to add can be added to this new function
pattern: getPattern(segments, config.base, config.trailingSlash), type: 'fallback', fallbackRoutes: [], }; const routeData = routes[index]; routeData.fallbackRoutes.push(fallbackRoute); } } } } } } } if (dev) { // In SSR, a 404 route is ...
@@ -732,9 +735,20 @@ export async function createRouteManifest( } } - if (!dev) { - await runHookRoutesResolved({ routes, settings, logger }); + if (dev) { + ensure404Route({ routes }); + injectImageEndpoint(settings, { routes }, 'dev'); + injectServerIslandRoute(settings.config, { routes }); + } else if (se...
packages/astro/src/core/routing/manifest/create.ts
26
TypeScript
0.929
suggestion
301
51
51
false
feat: route manifest refactor
12,597
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
pathname, route, segments, generate, pattern: getPattern(segments, config.base, config.trailingSlash), type: 'fallback', fallbackRoutes: [], }; const routeData = routes[index]; routeData.fallbackRoutes.push(fallbackRoute); } ...
this comments a little confusing. I'm not sure what happens today if you have a static project with only server islands. Does it generate a server build or not? If it does, then I think this change will break it. If not, that's a bug but probably not one that this affects. Could you test this and confirm what hap...
pathname, route, segments, generate, pattern: getPattern(segments, config.base, config.trailingSlash), type: 'fallback', fallbackRoutes: [], }; const routeData = routes[index]; routeData.fallbackRoutes.push(fallbackRoute); } ...
@@ -732,9 +735,19 @@ export async function createRouteManifest( } } - if (!dev) { - await runHookRoutesResolved({ routes, settings, logger }); + if (dev) { + // In SSR, a 404 route is injected in the App directly for some special handling, + // it must not appear in the manifest + ensure404Route({ routes });...
packages/astro/src/core/routing/manifest/create.ts
26
TypeScript
0.643
bug
325
51
51
false
feat: route manifest refactor
12,597
withastro/astro
47,179
TypeScript
matthewp
florian-lefebvre
request: this.request, response, site: pipeline.site, getActionResult: createGetActionResult(locals), get callAction() { return createCallAction(this); }, url, get originPathname() { return getOriginPathname(renderContext.request); }, }; } getClientAddress() { const { pipeline,...
Can the word TODO be added here so that we can find it back easily whenever we'll do Astro 6 or later?
request: this.request, response, site: pipeline.site, getActionResult: createGetActionResult(locals), get callAction() { return createCallAction(this); }, url, get originPathname() { return getOriginPathname(renderContext.request); }, }; } getClientAddress() { const { pipeline,...
@@ -519,16 +522,24 @@ export class RenderContext { }; } - clientAddress() { - const { pipeline, request } = this; - if (clientAddressSymbol in request) { - return Reflect.get(request, clientAddressSymbol) as string; - } + getClientAddress() { + const { pipeline, request, routeData, clientAddress } = this; ...
packages/astro/src/core/render-context.ts
26
TypeScript
0.357
question
102
51
51
false
Keep clientAddress on cloned requests
12,613
withastro/astro
47,179
TypeScript
Princesseuh
matthewp
request: this.request, response, site: pipeline.site, getActionResult: createGetActionResult(locals), get callAction() { return createCallAction(this); }, url, get originPathname() { return getOriginPathname(renderContext.request); }, }; } getClientAddress() { const { pipeline,...
```suggestion // TODO: Legacy, should not need to get here. ```
request: this.request, response, site: pipeline.site, getActionResult: createGetActionResult(locals), get callAction() { return createCallAction(this); }, url, get originPathname() { return getOriginPathname(renderContext.request); }, }; } getClientAddress() { const { pipeline,...
@@ -519,16 +522,24 @@ export class RenderContext { }; } - clientAddress() { - const { pipeline, request } = this; - if (clientAddressSymbol in request) { - return Reflect.get(request, clientAddressSymbol) as string; - } + getClientAddress() { + const { pipeline, request, routeData, clientAddress } = this; ...
packages/astro/src/core/render-context.ts
26
TypeScript
0.643
suggestion
67
51
51
false
Keep clientAddress on cloned requests
12,613
withastro/astro
47,179
TypeScript
matthewp
matthewp
import { parse, renderSync } from 'ultrahtml'; import type { SvgComponentProps } from '../runtime.js'; import { dropAttributes } from '../runtime.js'; import type { ImageMetadata } from '../types.js'; function parseSvg(contents: string) { const root = parse(contents); const svgNode = root.children.find( ({ name, t...
Having an optional `mode` should be a bug. Users should either provide a boolean, or provide an object with explicit `mode`
import { parse, renderSync } from 'ultrahtml'; import type { SvgComponentProps } from '../runtime.js'; import { dropAttributes } from '../runtime.js'; import type { ImageMetadata } from '../types.js'; function parseSvg(contents: string) { const root = parse(contents); const svgNode = root.children.find( ({ name, t...
@@ -22,7 +22,7 @@ export type SvgRenderMode = 'inline' | 'sprite'; export function makeSvgComponent( meta: ImageMetadata, contents: Buffer | string, - options?: { mode?: SvgRenderMode }, + options?: { mode: SvgRenderMode },
packages/astro/src/assets/utils/svg.ts
25
TypeScript
0.714
bug
123
38
38
false
fix: experimental svg types
12,625
withastro/astro
47,179
TypeScript
ematipico
ematipico
import mdx from '@astrojs/mdx'; import { defineConfig } from 'astro/config'; export default defineConfig({ integrations: [mdx()], experimental: { svg: true } });
This way of passing the option shouldn't be valid
import mdx from '@astrojs/mdx'; import { defineConfig } from 'astro/config'; export default defineConfig({ integrations: [mdx()], experimental: { svg: {} } });
@@ -4,6 +4,6 @@ import { defineConfig } from 'astro/config'; export default defineConfig({ integrations: [mdx()], experimental: { - svg: {}
packages/astro/test/fixtures/core-image-svg/astro.config.mjs
7
JavaScript
0.143
suggestion
49
10
10
false
fix: experimental svg types
12,625
withastro/astro
47,179
TypeScript
ematipico
ematipico
* https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/enctype * @private */ const FORM_CONTENT_TYPES = [ 'application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain', ]; /** * Returns a middleware function in charge to check the `origin` header. * * @private */ export function create...
Should we allow empty origins too?
* https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/enctype * @private */ const FORM_CONTENT_TYPES = [ 'application/x-www-form-urlencoded', 'multipart/form-data', 'text/plain', ]; /** * Returns a middleware function in charge to check the `origin` header. * * @private */ export function create...
@@ -21,22 +21,43 @@ const FORM_CONTENT_TYPES = [ export function createOriginCheckMiddleware(): MiddlewareHandler { return defineMiddleware((context, next) => { const { request, url } = context; - const contentType = request.headers.get('content-type'); - if (contentType) { - if (FORM_CONTENT_TYPES.includes(c...
packages/astro/src/core/app/middlewares.ts
26
TypeScript
0.143
question
34
37
51
false
fix: `checkOrigin` headers check
12,632
withastro/astro
47,179
TypeScript
ascorbic
ematipico
const badge = bgYellow(black(` cancelled `)); const headline = yellow(message); const footer = tip ? `\n ▶ ${tip}` : undefined; return ['', `${badge} ${headline}`, footer] .filter((v) => v !== undefined) .map((msg) => ` ${msg}`) .join('\n'); } const LOCAL_IP_HOSTS = new Set(['localhost', '127.0.0.1']); fu...
My highly-featured markdown renderer keep seeing usage 🫡
const badge = bgYellow(black(` cancelled `)); const headline = yellow(message); const footer = tip ? `\n ▶ ${tip}` : undefined; return ['', `${badge} ${headline}`, footer] .filter((v) => v !== undefined) .map((msg) => ` ${msg}`) .join('\n'); } const LOCAL_IP_HOSTS = new Set(['localhost', '127.0.0.1']); fu...
@@ -231,12 +231,22 @@ function getNetworkLogging(host: string | boolean): 'none' | 'host-to-expose' | } } +const codeRegex = /`([^`]+)`/g; + export function formatConfigErrorMessage(err: ZodError) { - const errorList = err.issues.map( - (issue) => ` ! ${bold(issue.path.join('.'))} ${red(issue.message + '.')}`,...
packages/astro/src/core/messages.ts
26
TypeScript
0.214
suggestion
57
51
51
false
Improve Zod error messages and user config error messages
12,634
withastro/astro
47,179
TypeScript
Princesseuh
delucis
} if (!command) { console.error(colors.red('\nClipboard command not found!')); console.log('Please manually copy the text above.'); return; } if (!force) { const { shouldCopy } = await prompts({ type: 'confirm', name: 'shouldCopy', message: 'Copy to clipboard?', initial: true, }); if (!sh...
Unused (thank you github annotations)
} if (!command) { console.error(colors.red('\nClipboard command not found!')); console.info('Please manually copy the text above.'); return; } if (!force) { const { shouldCopy } = await prompts({ type: 'confirm', name: 'shouldCopy', message: 'Copy to clipboard?', initial: true, }); if (!s...
@@ -49,63 +49,110 @@ export async function printInfo({ flags }: InfoOptions) { applyPolyfill(); const { userConfig } = await resolveConfig(flagsToAstroInlineConfig(flags), 'info'); const output = await getInfoOutput({ userConfig, print: true }); - - await copyToClipboard(output); + await copyToClipboard(output, f...
packages/astro/src/cli/info/index.ts
26
TypeScript
0.143
suggestion
38
51
51
false
fix: correctly copy to clipboard in `astro info`
12,641
withastro/astro
47,179
TypeScript
ematipico
ascorbic
} else if (system === 'win32') { command = 'clip'; } else { // Unix: check if a supported command is installed const unixCommands: Array<[string, Array<string>]> = [ ['xclip', ['-sel', 'clipboard', '-l', '1']], ['wl-copy', []], ]; for (const [unixCommand, unixArgs] of unixCommands) { try { con...
Use `.info` instead. Usually `.log` is more for debugging
} else if (system === 'win32') { command = 'clip'; } else { // Unix: check if a supported command is installed const unixCommands: Array<[string, Array<string>]> = [ ['xclip', ['-sel', 'clipboard', '-l', '1']], ['wl-copy', []], ]; for (const [unixCommand, unixArgs] of unixCommands) { try { con...
@@ -49,63 +49,110 @@ export async function printInfo({ flags }: InfoOptions) { applyPolyfill(); const { userConfig } = await resolveConfig(flagsToAstroInlineConfig(flags), 'info'); const output = await getInfoOutput({ userConfig, print: true }); - - await copyToClipboard(output); + await copyToClipboard(output, f...
packages/astro/src/cli/info/index.ts
26
TypeScript
0.571
bug
58
51
51
false
fix: correctly copy to clipboard in `astro info`
12,641
withastro/astro
47,179
TypeScript
ematipico
ascorbic
// Remove search parameters if the request is for a page that will be on-demand rendered if (isPrerendered) { url.search = ''; } const request = new Request(url, { method: method, headers: headersObj, // body is made available only if the request is for a page that will be on-demand rendered body: isPrer...
```suggestion `\`Astro.request.headers\` was used when rendering the route \`${routePattern}'\`. \`Astro.request.headers\` is not available on prerendered pages. If you need access to request headers, make sure that the page is server-rendered using \`export const prerender = false;\` or by setting \`output\` to ...
// Remove search parameters if the request is for a page that will be on-demand rendered if (isPrerendered) { url.search = ''; } const request = new Request(url, { method: method, headers: headersObj, // body is made available only if the request is for a page that will be on-demand rendered body: isPrer...
@@ -82,7 +85,7 @@ export function createRequest({ get() { logger.warn( null, - `\`Astro.request.headers\` is not available on prerendered pages. If you need access to request headers, make sure that the page is server rendered using \`export const prerender = false;\` or by setting \`output\` to \`"s...
packages/astro/src/core/request.ts
26
TypeScript
0.857
suggestion
411
43
43
false
chore: better warning
12,642
withastro/astro
47,179
TypeScript
sarah11918
ematipico
import yaml from 'js-yaml'; export function isFrontmatterValid(frontmatter: Record<string, any>) { try { // ensure frontmatter is JSON-serializable JSON.stringify(frontmatter); } catch { return false; } return typeof frontmatter === 'object' && frontmatter !== null; } const frontmatterRE = /^\s*---([\s\S]*?...
```suggestion // Capture frontmatter wrapped with `---`, including any characters and new lines within it. // Only capture if it exists near the top of the file (whitespaces between the start of file and // the start of `---` are allowed) const frontmatterRE = /^\s*---([\s\S]*?\n)---/; ```
import yaml from 'js-yaml'; export function isFrontmatterValid(frontmatter: Record<string, any>) { try { // ensure frontmatter is JSON-serializable JSON.stringify(frontmatter); } catch { return false; } return typeof frontmatter === 'object' && frontmatter !== null; } // Capture frontmatter wrapped with `--...
@@ -10,7 +10,7 @@ export function isFrontmatterValid(frontmatter: Record<string, any>) { return typeof frontmatter === 'object' && frontmatter !== null; } -const frontmatterRE = /^---(.*?)^---/ms; +const frontmatterRE = /^\s*---([\s\S]*?\n)---/;
packages/markdown/remark/src/frontmatter.ts
16
TypeScript
0.786
suggestion
295
41
41
false
Only parse frontmatter at top of file
12,646
withastro/astro
47,179
TypeScript
bluwy
bluwy
'access-control-allow-origin': '*', 'x-single': 'single', 'x-triple': 'one, two, three', 'set-cookie': ['hello', 'world'], }); }); it('Can bail on streaming', async () => { const { req, res, done } = createRequestAndResponse({ method: 'GET', url: '/streaming', }); container.handle(req, res...
Wouldn't the assert.fail hide the errors from the catch if it happened to help debug this in the future?
'access-control-allow-origin': '*', 'x-single': 'single', 'x-triple': 'one, two, three', 'set-cookie': ['hello', 'world'], }); }); it('Can bail on streaming', async () => { const { req, res, done } = createRequestAndResponse({ method: 'GET', url: '/streaming', }); container.handle(req, res...
@@ -87,16 +87,18 @@ describe('endpoints', () => { url: '/streaming', }); - const locals = { cancelledByTheServer: false }; - req[Symbol.for('astro.locals')] = locals; - container.handle(req, res); await new Promise((resolve) => setTimeout(resolve, 500)); res.emit('close'); - await done; + try ...
packages/astro/test/units/vite-plugin-astro-server/response.test.js
26
JavaScript
0.5
bug
104
29
29
false
fix(routing): don't attach locals to request
12,647
withastro/astro
47,179
TypeScript
bluwy
ematipico
this.#storage = createStorage({ driver: driver(this.#config.options), }); return this.#storage; } catch (err) { throw new AstroError( { ...SessionStorageInitError, message: SessionStorageInitError.message('Unknown error', this.#config.driver), }, { cause: err }, ); } } } e...
We support older node versions that may have import.meta.resolve return promises, so it might be safer to also await here. https://nodejs.org/api/esm.html#importmetaresolvespecifier
this.#storage = createStorage({ driver: driver(this.#config.options), }); return this.#storage; } catch (err) { throw new AstroError( { ...SessionStorageInitError, message: SessionStorageInitError.message('Unknown error', this.#config.driver), }, { cause: err }, ); } } } //...
@@ -431,3 +433,16 @@ export class AstroSession<TDriver extends SessionDriverName = any> { } } } + +export function resolveSessionDriver(driver: string | undefined): string | null { + if (!driver) { + return null; + } + if (driver === 'fs') { + return import.meta.resolve(builtinDrivers.fsLite); + } + if (driver ...
packages/astro/src/core/session.ts
26
TypeScript
0.357
suggestion
181
29
29
false
fix: [sessions] import storage driver in manifest
12,654
withastro/astro
47,179
TypeScript
bluwy
ascorbic
} }, async configureServer(server) { const filePresentOnStartup = await isActionsFilePresent(fs, settings.config.srcDir); // Watch for the actions file to be created. async function watcherCallback() { const filePresent = await isActionsFilePresent(fs, settings.config.srcDir); if (filePresentOnS...
Not sure if this is a correct way to pass config settings
return RESOLVED_VIRTUAL_MODULE_ID; } }, async configureServer(server) { const filePresentOnStartup = await isActionsFilePresent(fs, settings.config.srcDir); // Watch for the actions file to be created. async function watcherCallback() { const filePresent = await isActionsFilePresent(fs, settings...
@@ -84,6 +84,7 @@ 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(settings.config.trailingSlash === 'always...
packages/astro/src/actions/plugins.ts
26
TypeScript
0.214
suggestion
57
32
38
false
fix(actions): support trailing slash
12,657
withastro/astro
47,179
TypeScript
darkmaga
darkmaga
deserializeActionResult: typeof deserializeActionResult; }; /** * Access information about Action requests from middleware. */ export function getActionContext(context: APIContext): ActionMiddlewareContext { const callerInfo = getCallerInfo(context); // Prevents action results from being handled on a rewrite. /...
We have three utilities for manage the trailing slash, you should use them. Here's an example from the source code: https://github.com/withastro/astro/blob/72c1d5d531d1fb59e29707986405a6aa7f9ca835/packages/astro/src/core/routing/rewrite.ts#L48-L50
* Deserialize an action result to access data and error objects. */ deserializeActionResult: typeof deserializeActionResult; }; /** * Access information about Action requests from middleware. */ export function getActionContext(context: APIContext): ActionMiddlewareContext { const callerInfo = getCallerInfo(co...
@@ -279,7 +281,12 @@ 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, apiContextRoutesSymb...
packages/astro/src/actions/runtime/virtual/server.ts
26
TypeScript
0.5
suggestion
252
51
51
false
fix(actions): support trailing slash
12,657
withastro/astro
47,179
TypeScript
ematipico
darkmaga
import * as assert from 'node:assert/strict'; import { describe, it, before } from 'node:test'; import { pathToFileURL } from 'node:url'; import { init, parse } from 'es-module-lexer'; import { resolveConfig } from 'vite'; import { compileAstro } from '../../../dist/vite-plugin-astro/compile.js'; let inlineConfig; /**...
Can we pass the `inlineConfig` as a parameter of `compile` instead? That way we avoid passing the global around.
import * as assert from 'node:assert/strict'; import { describe, it } from 'node:test'; import { pathToFileURL } from 'node:url'; import { init, parse } from 'es-module-lexer'; import { resolveConfig } from 'vite'; import { compileAstro } from '../../../dist/vite-plugin-astro/compile.js'; /** * @param {string} source...
@@ -1,17 +1,17 @@ import * as assert from 'node:assert/strict'; -import { describe, it } from 'node:test'; +import { describe, it, before } from 'node:test'; import { pathToFileURL } from 'node:url'; import { init, parse } from 'es-module-lexer'; import { resolveConfig } from 'vite'; import { compileAstro } from '...
packages/astro/test/units/vite-plugin-astro/compile.test.js
14
JavaScript
0.571
question
112
39
39
false
fix: Reflect the configuration for esbuild
12,676
withastro/astro
47,179
TypeScript
bluwy
koyopro
throw new AstroError({ ...SessionStorageSaveError, message: 'The session key was not provided.', }); } try { // Attempt to serialize the value so we can throw an error early if needed stringify(value); } catch (err) { throw new AstroError( { ...SessionStorageSaveError, message...
Can we add a comment that explains the `1000`?
throw new AstroError({ ...SessionStorageSaveError, message: 'The session key was not provided.', }); } try { // Attempt to serialize the value so we can throw an error early if needed stringify(value); } catch (err) { throw new AstroError( { ...SessionStorageSaveError, message...
@@ -138,10 +147,19 @@ export class AstroSession<TDriver extends SessionDriverName = any> { this.#cookieSet = true; } this.#data ??= new Map(); - this.#data.set(key, value); + const lifetime = ttl ?? this.#config.ttl; + const expires = typeof lifetime === 'number' ? Date.now() + lifetime * 1000 : lifetime;
packages/astro/src/core/session.ts
26
TypeScript
0.214
question
46
51
51
false
feat(sessions): implement ttl and flash
12,693
withastro/astro
47,179
TypeScript
ematipico
ascorbic
const url = pathToFileURL(id); let fileData: Buffer; try { fileData = await fs.readFile(url); } catch { return undefined; } const fileMetadata = await imageMetadata(fileData, id); const emittedImage: Omit<ImageMetadataWithContents, 'fsPath'> = { src: '', ...fileMetadata, }; // Private for now, we g...
Could you add a TODO with the proper solution here? (or at least just "figure a better solution") We definitely need to fix it before leaving experimental. A good fix would be to make this lazy.. but it's unfortunately annoying in serverless (it'd need to work like the image endpoint with a fetch, which is doable, h...
const url = pathToFileURL(id); let fileData: Buffer; try { fileData = await fs.readFile(url); } catch { return undefined; } const fileMetadata = await imageMetadata(fileData, id); const emittedImage: Omit<ImageMetadataWithContents, 'fsPath'> = { src: '', ...fileMetadata, }; // Private for now, we g...
@@ -44,7 +45,7 @@ export async function emitESMImage( }); // Attach file data for SVGs - if (fileMetadata.format === 'svg') { + if (fileMetadata.format === 'svg' && experimentalSvgEnabled === true) {
packages/astro/src/assets/utils/node/emitAsset.ts
26
TypeScript
0.5
question
449
51
51
false
fix(svg): conditional opt-in
12,694
withastro/astro
47,179
TypeScript
Princesseuh
ematipico
} const url = pathToFileURL(id); let fileData: Buffer; try { fileData = await fs.readFile(url); } catch { return undefined; } const fileMetadata = await imageMetadata(fileData, id); const emittedImage: Omit<ImageMetadataWithContents, 'fsPath'> = { src: '', ...fileMetadata, }; // Private for now, w...
```suggestion // TODO: this is a workaround to prevent a memory leak, and it must be fixed before we remove the experimental flag, see ```
} const url = pathToFileURL(id); let fileData: Buffer; try { fileData = await fs.readFile(url); } catch { return undefined; } const fileMetadata = await imageMetadata(fileData, id); const emittedImage: Omit<ImageMetadataWithContents, 'fsPath'> = { src: '', ...fileMetadata, }; // Private for now, w...
@@ -44,7 +45,8 @@ export async function emitESMImage( }); // Attach file data for SVGs - if (fileMetadata.format === 'svg') { + // TODO: this is a workaround to prevent the a memory leak, and it must be fixed before we remove the experimental flag
packages/astro/src/assets/utils/node/emitAsset.ts
26
TypeScript
0.929
performance
141
51
51
false
fix(svg): conditional opt-in
12,694
withastro/astro
47,179
TypeScript
Princesseuh
ematipico
* * @param staticBuildOptions */ static async retrieveManifest( staticBuildOptions: StaticBuildOptions, internals: BuildInternals, ): Promise<SSRManifest> { const baseDirectory = getOutputDirectory(staticBuildOptions.settings); const manifestEntryUrl = new URL( `${internals.manifestFileName}?time=${D...
```suggestion const mod = await import(internals.middlewareEntryPoint!.toString()); ``` I think you need this to make the build pass since it's inside the function now
* * @param staticBuildOptions */ static async retrieveManifest( staticBuildOptions: StaticBuildOptions, internals: BuildInternals, ): Promise<SSRManifest> { const baseDirectory = getOutputDirectory(staticBuildOptions.settings); const manifestEntryUrl = new URL( `${internals.manifestFileName}?time=${D...
@@ -131,11 +131,10 @@ export class BuildPipeline extends Pipeline { const renderers = await import(renderersEntryUrl.toString()); const middleware = internals.middlewareEntryPoint - ? await import(internals.middlewareEntryPoint.toString()).then((mod) => { - return function () { - return { onRequest: ...
packages/astro/src/core/build/pipeline.ts
26
TypeScript
0.714
suggestion
175
51
51
false
fix(middleware): don't import via entrypoint
12,707
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
return {}; } if ( routeIsRedirect(route) || routeIsFallback(route) || route.component === DEFAULT_404_COMPONENT ) { return {}; } // During build, the route cache should already be populated. // During development, the route cache is filled on-demand and may be empty. const staticPaths = await callGet...
There's no need to move this line, especially because the comments belongs exactly this line you just moved. This will make the comments confusing. Please revert this tiny change.
return {}; } if ( routeIsRedirect(route) || routeIsFallback(route) || route.component === DEFAULT_404_COMPONENT ) { return {}; } // During build, the route cache should already be populated. // During development, the route cache is filled on-demand and may be empty. const staticPaths = await callGet...
@@ -47,10 +47,11 @@ export async function getProps(opts: GetParamsAndPropsOptions): Promise<Props> { base, }); + if (!staticPaths.length) return {}; + const params = getParams(route, decodeURI(pathname)); // The pathname used here comes from the server, which already encored. // Since we decided to not mess ...
packages/astro/src/core/render/params-and-props.ts
26
TypeScript
0.429
refactor
179
51
51
false
fix(i18n): parse params and props correctly with fallback
12,709
withastro/astro
47,179
TypeScript
ematipico
mtwilliams-code
...AstroErrorData.NoMatchingStaticPathFound, message: AstroErrorData.NoMatchingStaticPathFound.message(pathname), hint: AstroErrorData.NoMatchingStaticPathFound.hint([route.component]), }); } if (mod) { validatePrerenderEndpointCollision(route, mod, params); } const props: Props = matchedStaticPath?....
This doesn't seem correct to me. We're looping over all fallback routes and use `exec`, but we always pick the first one. Instead, we should use a for loop, and assign to `paramsMatch` that matches the route. ```js for (const fallbackRoute in route.fallbackRoutes) { if (fallbackRoute.test(pathname)) { paramsMa...
...AstroErrorData.NoMatchingStaticPathFound, message: AstroErrorData.NoMatchingStaticPathFound.message(pathname), hint: AstroErrorData.NoMatchingStaticPathFound.hint([route.component]), }); } if (mod) { validatePrerenderEndpointCollision(route, mod, params); } const props: Props = matchedStaticPath?....
@@ -77,7 +78,10 @@ export function getParams(route: RouteData, pathname: string): Params { if (!route.params.length) return {}; // The RegExp pattern expects a decoded string, but the pathname is encoded // when the URL contains non-English characters. - const paramsMatch = route.pattern.exec(pathname); + const p...
packages/astro/src/core/render/params-and-props.ts
26
TypeScript
0.857
suggestion
377
51
51
false
fix(i18n): parse params and props correctly with fallback
12,709
withastro/astro
47,179
TypeScript
ematipico
mtwilliams-code
prefixDefaultLocale: false, fallbackType: 'rewrite', }, fallback: { fr: 'en', }, }, }); await fixture.build(); app = await fixture.loadTestAdapterApp(); }); it('should correctly rewrite to en', async () => { const request = new Request('http://example.com/fr'); const response ...
Use `assert.match` ```suggestion assert.match(text, /Hello world/); ```
// app = await fixture.loadTestAdapterApp(); }); it('should correctly rewrite to en', async () => { const html = await fixture.readFile('/fr/index.html'); assert.match(html, /Hello/); // assert.fail() }); it('should render fallback locale paths with path parameters correctly (fr)', async () => { const h...
@@ -2087,4 +2087,12 @@ describe('Fallback rewrite SSR', () => { const html = await response.text(); assert.match(html, /Hello/); }); + + it('should render paths with path parameters correctly', async () => { + let request = new Request('http://example.com/new-site/fr/blog/1'); + let response = await app.rende...
packages/astro/test/i18n-routing.test.js
26
JavaScript
0.643
suggestion
78
29
51
false
fix(i18n): parse params and props correctly with fallback
12,709
withastro/astro
47,179
TypeScript
ematipico
mtwilliams-code
i18n: { defaultLocale: 'en', locales: ['en', 'fr'], routing: { prefixDefaultLocale: false, fallbackType: 'rewrite', }, fallback: { fr: 'en', }, }, }); await fixture.build(); app = await fixture.loadTestAdapterApp(); }); it('should correctly rewrite to en', async () ...
Can we update the test with more locales? At the moment there's only `fr: 'en'`, let's add two more and make sure that the fallback of params works for all of them.
}, }, }); await fixture.build(); // app = await fixture.loadTestAdapterApp(); }); it('should correctly rewrite to en', async () => { const html = await fixture.readFile('/fr/index.html'); assert.match(html, /Hello/); // assert.fail() }); it('should render fallback locale paths with path paramet...
@@ -2087,4 +2087,12 @@ describe('Fallback rewrite SSR', () => { const html = await response.text(); assert.match(html, /Hello/); }); + + it('should render paths with path parameters correctly', async () => { + let request = new Request('http://example.com/new-site/fr/blog/1');
packages/astro/test/i18n-routing.test.js
26
JavaScript
0.5
question
165
33
51
false
fix(i18n): parse params and props correctly with fallback
12,709
withastro/astro
47,179
TypeScript
ematipico
mtwilliams-code
import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import type { AstroSettings } from '../types/astro.js'; import type { AstroConfig } from '../types/public/config.js'; import type { RouteType } from '../types/public/internal.js'; import { SUPPORTED_MARKDOWN_FILE_EXTENSION...
Don't we have a stripQueryParams util somewhere?
import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import type { AstroSettings } from '../types/astro.js'; import type { AstroConfig } from '../types/public/config.js'; import type { RouteType } from '../types/public/internal.js'; import { SUPPORTED_MARKDOWN_FILE_EXTENSION...
@@ -18,9 +18,11 @@ export function isURL(value: unknown): value is URL { } /** Check if a file is a markdown file based on its extension */ export function isMarkdownFile(fileId: string, option?: { suffix?: string }): boolean { + // Strip query string + const id = fileId.split("?")[0];
packages/astro/src/core/util.ts
22
TypeScript
0.071
question
48
47
47
false
fix: strip query string before checking md extension
12,712
withastro/astro
47,179
TypeScript
Princesseuh
ascorbic
import { promises as fs, type PathLike, existsSync } from 'node:fs'; import * as devalue from 'devalue'; import { Traverse } from 'neotraverse/modern'; import { imageSrcToImportId, importIdToSymbolName } from '../assets/utils/resolveImports.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; impo...
I'm not too fond of this solution because now ALL projects, without discrimination, will incur in **four** (create temp dir, write file, rename file, remove directory) writing I/O operations instead of one. And writing operations are slow. Maybe we could have an internal heuristic, where we enable this atomic rewrit...
import { promises as fs, type PathLike, existsSync } from 'node:fs'; import * as devalue from 'devalue'; import { Traverse } from 'neotraverse/modern'; import { imageSrcToImportId, importIdToSymbolName } from '../assets/utils/resolveImports.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; impo...
@@ -6,9 +6,23 @@ import { AstroError, AstroErrorData } from '../core/errors/index.js'; import { IMAGE_IMPORT_PREFIX } from './consts.js'; import { type DataEntry, ImmutableDataStore } from './data-store.js'; import { contentModuleToId } from './utils.js'; +import { tmpdir } from 'node:os'; +import { join } from 'nod...
packages/astro/src/content/mutable-data-store.ts
23
TypeScript
0.5
performance
438
48
48
false
fix: use atomic writes for data store file operations
12,715
withastro/astro
47,179
TypeScript
ematipico
ascorbic
this.#saveTimeout = undefined; this.writeToDisk(this.#file!); }, SAVE_DEBOUNCE_MS); } } #writing = new Set<string>(); #pending = new Set<string>(); async #writeFileAtomic(filePath: PathLike, data: string, depth = 0) { const fileKey = filePath.toString(); if (this.#writing.has(fileKey)) { this....
I am not really sure what this code does and why we use the resursion, but would happen if the pending files exceed the ` MAX_DEPTH`?
this.#saveTimeout = undefined; this.writeToDisk(this.#file!); }, SAVE_DEBOUNCE_MS); } } #writing = new Set<string>(); #pending = new Set<string>(); async #writeFileAtomic(filePath: PathLike, data: string, depth = 0) { if(depth > MAX_DEPTH) { // If we hit the max depth, we skip a write to prevent...
@@ -190,6 +192,29 @@ export default new Map([\n${lines.join(',\n')}]); } } + #writing = new Set<string>(); + #pending = new Set<string>(); + + async #writeFileAtomic(filePath: PathLike, data: string, depth = 0) { + const fileKey = filePath.toString(); + if (this.#writing.has(fileKey)) { + this.#pending.add(f...
packages/astro/src/content/mutable-data-store.ts
26
TypeScript
0.571
question
133
51
51
false
fix: use atomic writes for data store file operations
12,715
withastro/astro
47,179
TypeScript
ematipico
ascorbic
fallback: Record<string, string> | undefined; fallbackType: 'redirect' | 'rewrite'; }; // NOTE: public function exported to the users via `astro:i18n` module export function redirectToDefaultLocale({ trailingSlash, format, base, defaultLocale, }: MiddlewarePayload) { return function (context: APIContext, status...
Even though we're about to render the internal `404` or `500`, we still want to handle the fallback
fallback: Record<string, string> | undefined; fallbackType: 'redirect' | 'rewrite'; }; // NOTE: public function exported to the users via `astro:i18n` module export function redirectToDefaultLocale({ trailingSlash, format, base, defaultLocale, }: MiddlewarePayload) { return function (context: APIContext, status...
@@ -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...
packages/astro/src/i18n/index.ts
26
TypeScript
0.5
suggestion
99
51
51
false
fix(i18n): manual routing with rewrite
12,718
withastro/astro
47,179
TypeScript
ematipico
ematipico
handler: () => MaybePromise<TOutput>, ): Promise<SafeResult<z.ZodType, TOutput>> { try { const data = await handler(); return { data, error: undefined }; } catch (e) { if (e instanceof ActionError) { return { data: undefined, error: e }; } return { data: undefined, error: new ActionError({ mes...
We need to handle `trailingSlash` too. I just [merged](https://github.com/withastro/astro/pull/12657) a bug where now action URLs have one.
export async function callSafely<TOutput>( handler: () => MaybePromise<TOutput>, ): Promise<SafeResult<z.ZodType, TOutput>> { try { const data = await handler(); return { data, error: undefined }; } catch (e) { if (e instanceof ActionError) { return { data: undefined, error: e }; } return { data: un...
@@ -180,6 +181,10 @@ export function getActionQueryString(name: string) { return `?${searchParams.toString()}`; } +export function getActionPath(action: ActionClient<any, any, any>) { + return `${import.meta.env.BASE_URL.replace(/\/$/, '')}/_actions/${new URLSearchParams(action.toString()).get(ACTION_QUERY_PARAMS....
packages/astro/src/actions/runtime/virtual/shared.ts
26
TypeScript
0.643
bug
140
51
51
false
feat(actions): getActionPath()
12,721
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
const injectedRoutes = createInjectedRoutes(params); for (const route of injectedRoutes) { routeMap.set(route.route, route); } const redirectRoutes = createRedirectRoutes(params, routeMap, logger); if (dev && config.base === '/') { // Add a redirect for `//` to `/`. We only do this in dev because different pl...
I would advise against creating full routes like this because many of those data might not be mandatory, and some of them need to be built using the proper functions. E.g. `getPattern` or `getRouteGenerator`. Plus, we need to take into consideration things like `base`, `trailing slash` and more. Follow this pattern:...
if (route.type !== 'page' && route.type !== 'endpoint') return; const localFs = params.fsMod ?? nodeFs; const content = await localFs.promises.readFile( fileURLToPath(new URL(route.component, settings.config.root)), 'utf-8', ); await getRoutePrerenderOption(content, route, settings, logge...
@@ -502,6 +506,27 @@ export async function createRouteManifest( } const redirectRoutes = createRedirectRoutes(params, routeMap, logger); + if (dev && config.base === '/') { + // Add a redirect for `//` to `/`. We only do this in dev because different platforms + // vary a lot in how or whether they handle this ...
packages/astro/src/core/routing/manifest/create.ts
26
TypeScript
0.643
suggestion
514
51
51
false
fix: handle requests for double slash in dev
12,733
withastro/astro
47,179
TypeScript
ematipico
ascorbic
console.error(`Failed to init app ${app.id}, error: ${e}`); app.status = 'error'; if (import.meta.hot) { import.meta.hot.send('astro:devtoolbar:error:init', { app: app, error: e instanceof Error ? e.stack : e, }); } const appButton = this.getAppButtonById(app.id); const appTooltip ...
Could you explain what’s intended here? I’m not 100% sure where this code is used, but in theory `aria-labelledby` should be unnecessary here as a `<button>` is already automatically labelled by its text content.
console.error(`Failed to init app ${app.id}, error: ${e}`); app.status = 'error'; if (import.meta.hot) { import.meta.hot.send('astro:devtoolbar:error:init', { app: app, error: e instanceof Error ? e.stack : e, }); } const appButton = this.getAppButtonById(app.id); const appTooltip ...
@@ -416,9 +416,9 @@ export class AstroDevToolbar extends HTMLElement { } getAppTemplate(app: DevToolbarApp) { - return `<button class="item" data-app-id="${app.id}"> + return `<button class="item" data-app-id="${app.id}" aria-labelledby="app-name-${app.name}"> <div class="icon">${app.icon ? getAppIcon(app....
packages/astro/src/runtime/client/dev-toolbar/toolbar.ts
26
TypeScript
0.643
question
212
51
51
false
fix(toolbar): assign label to icons
12,734
withastro/astro
47,179
TypeScript
delucis
ematipico
log(`${label(prefix, color.bgCyan, color.black)} ${text}`); }; export const info = async (prefix: string, text: string, version = '') => { const length = 11 + prefix.length + text.length + version?.length; const symbol = '◼'; if (length > stdout.columns) { log(`${' '.repeat(5)} ${color.cyan(symbol)} ${prefix}`...
```suggestion const version = `from v${fromVersion} to v${toVersion}`; ```
log(`${label(prefix, color.bgCyan, color.black)} ${text}`); }; export const info = async (prefix: string, text: string, version = '') => { const length = 11 + prefix.length + text.length + version?.length; const symbol = '◼'; if (length > stdout.columns) { log(`${' '.repeat(5)} ${color.cyan(symbol)} ${prefix}`...
@@ -109,14 +109,17 @@ export const info = async (prefix: string, text: string, version = '') => { ); } }; + export const upgrade = async (packageInfo: PackageInfo, text: string) => { - const { name, isMajor = false, targetVersion } = packageInfo; + const { name, isMajor = false, targetVersion, currentVersion } =...
packages/upgrade/src/messages.ts
26
TypeScript
0.571
suggestion
77
51
51
false
Version transitions in CLI outputs
12,739
withastro/astro
47,179
TypeScript
florian-lefebvre
outslept
...this.#settings.dataEntryTypes, ] as Array<ContentEntryType>), }; } /** * Enqueues a sync job that runs the `load()` method of each collection's loader, which will load the data and save it in the data store. * The loader itself is responsible for deciding whether this will clear and reload the full c...
I think we should **pick** the keys that we want to hash. This is safer in the long run, so we can add new configuration (even functions) without risking to breaking this code. For example, the fonts RFC will add some runtime code for loading custom providers, and I doubt that we can create a hash from them.
...this.#settings.dataEntryTypes, ] as Array<ContentEntryType>), }; } /** * Enqueues a sync job that runs the `load()` method of each collection's loader, which will load the data and save it in the data store. * The loader itself is responsible for deciding whether this will clear and reload the full c...
@@ -143,12 +144,24 @@ export class ContentLayer { } logger.info('Syncing content'); + const { vite: _vite, integrations: _integrations, adapter: _adapter, ...hashableConfig } = this.#settings.config;
packages/astro/src/content/content-layer.ts
26
TypeScript
0.5
suggestion
314
51
51
false
fix: clear the content layer cache when the Astro config changes
12,767
withastro/astro
47,179
TypeScript
ematipico
ascorbic
import { promises as fs, existsSync } from 'node:fs'; import { deterministicString } from 'deterministic-object-hash'; import PQueue from 'p-queue'; import type { FSWatcher } from 'vite'; import xxhash from 'xxhash-wasm'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; import type { Logger } from ...
Micro-nit, but I’m guessing this was introduced accidentally? ```suggestion ```
import { promises as fs, existsSync } from 'node:fs'; import PQueue from 'p-queue'; import type { FSWatcher } from 'vite'; import xxhash from 'xxhash-wasm'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; import type { Logger } from '../core/logger/core.js'; import type { AstroSettings } from '../...
@@ -1,10 +1,12 @@ import { promises as fs, existsSync } from 'node:fs'; +import { deterministicString } from 'deterministic-object-hash'; import PQueue from 'p-queue'; import type { FSWatcher } from 'vite'; import xxhash from 'xxhash-wasm'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; imp...
packages/astro/src/content/content-layer.ts
9
TypeScript
0.571
suggestion
81
34
34
false
fix: clear the content layer cache when the Astro config changes
12,767
withastro/astro
47,179
TypeScript
delucis
ascorbic
load(id) { if (id === RESOLVED_VIRTUAL_ISLAND_MAP_ID) { return `export const serverIslandMap = ${serverIslandPlaceholder};`; } }, transform(_code, id) { if (id.endsWith('.astro')) { const info = this.getModuleInfo(id); if (info?.meta) { const astro = info.meta.astro as AstroPluginMetadat...
Won't this duplicate with the built-in warning? It's also incorrect for when the bug will be fixed.
load(id) { if (id === RESOLVED_VIRTUAL_ISLAND_MAP_ID) { return `export const serverIslandMap = ${serverIslandPlaceholder};`; } }, transform(_code, id) { if (id.endsWith('.astro')) { const info = this.getModuleInfo(id); if (info?.meta) { const astro = info.meta.astro as AstroPluginMetadat...
@@ -37,6 +37,20 @@ export function vitePluginServerIslands({ settings }: { settings: AstroSettings if (astro?.serverComponents.length) { for (const comp of astro.serverComponents) { if (!settings.serverIslandNameMap.has(comp.resolvedPath)) { + if (!settings.adapter) { + logger.error(...
packages/astro/src/core/server-islands/vite-plugin-server-islands.ts
26
TypeScript
0.357
bug
99
51
51
false
fix(core): add error log for server islands
12,768
withastro/astro
47,179
TypeScript
Princesseuh
ematipico
} }, load(id) { if (id === RESOLVED_VIRTUAL_ISLAND_MAP_ID) { return `export const serverIslandMap = ${serverIslandPlaceholder};`; } }, transform(_code, id) { if (id.endsWith('.astro')) { const info = this.getModuleInfo(id); if (info?.meta) { const astro = info.meta.astro as AstroPlu...
Since you don't *need* `output: 'server'` for server islands, and since changing the output value is a pretty large change to someone's project, I would hesitate to give a message that says this is required. Is there a situation where someone really would need a) THIS message, forcing them to use `output: 'server'` ...
} }, load(id) { if (id === RESOLVED_VIRTUAL_ISLAND_MAP_ID) { return `export const serverIslandMap = ${serverIslandPlaceholder};`; } }, transform(_code, id) { if (id.endsWith('.astro')) { const info = this.getModuleInfo(id); if (info?.meta) { const astro = info.meta.astro as AstroPlu...
@@ -37,6 +37,20 @@ export function vitePluginServerIslands({ settings }: { settings: AstroSettings if (astro?.serverComponents.length) { for (const comp of astro.serverComponents) { if (!settings.serverIslandNameMap.has(comp.resolvedPath)) { + if (!settings.adapter) { + logger.error(...
packages/astro/src/core/server-islands/vite-plugin-server-islands.ts
26
TypeScript
0.643
question
362
51
51
false
fix(core): add error log for server islands
12,768
withastro/astro
47,179
TypeScript
sarah11918
ematipico
}, configureServer(_server) { viteServer = _server; }, resolveId(name) { if (name === VIRTUAL_ISLAND_MAP_ID) { return RESOLVED_VIRTUAL_ISLAND_MAP_ID; } }, load(id) { if (id === RESOLVED_VIRTUAL_ISLAND_MAP_ID) { return `export const serverIslandMap = ${serverIslandPlaceholder};`; } }...
```suggestion "You tried to render a server island without an adapter added to your project. An adapter is required to use the `server: defer` attribute on any component. Your project will fail to build unless you add an adapter or remove the attribute.", ``` Here's a suggestion for what this could be! ...
}, configureServer(_server) { viteServer = _server; }, resolveId(name) { if (name === VIRTUAL_ISLAND_MAP_ID) { return RESOLVED_VIRTUAL_ISLAND_MAP_ID; } }, load(id) { if (id === RESOLVED_VIRTUAL_ISLAND_MAP_ID) { return `export const serverIslandMap = ${serverIslandPlaceholder};`; } }...
@@ -37,6 +37,20 @@ export function vitePluginServerIslands({ settings }: { settings: AstroSettings if (astro?.serverComponents.length) { for (const comp of astro.serverComponents) { if (!settings.serverIslandNameMap.has(comp.resolvedPath)) { + if (!settings.adapter) { + logger.error(...
packages/astro/src/core/server-islands/vite-plugin-server-islands.ts
26
TypeScript
1
bug
570
51
51
false
fix(core): add error log for server islands
12,768
withastro/astro
47,179
TypeScript
sarah11918
ematipico
}, configureServer(_server) { viteServer = _server; }, resolveId(name) { if (name === VIRTUAL_ISLAND_MAP_ID) { return RESOLVED_VIRTUAL_ISLAND_MAP_ID; } }, load(id) { if (id === RESOLVED_VIRTUAL_ISLAND_MAP_ID) { return `export const serverIslandMap = ${serverIslandPlaceholder};`; } }...
```suggestion "You tried to render a server island without an adapter added to your project. An adapter is required to use the `server:defer` attribute on any component. Your project will fail to build unless you add an adapter or remove the attribute.", ```
}, configureServer(_server) { viteServer = _server; }, resolveId(name) { if (name === VIRTUAL_ISLAND_MAP_ID) { return RESOLVED_VIRTUAL_ISLAND_MAP_ID; } }, load(id) { if (id === RESOLVED_VIRTUAL_ISLAND_MAP_ID) { return `export const serverIslandMap = ${serverIslandPlaceholder};`; } }...
@@ -37,6 +37,13 @@ export function vitePluginServerIslands({ settings }: { settings: AstroSettings if (astro?.serverComponents.length) { for (const comp of astro.serverComponents) { if (!settings.serverIslandNameMap.has(comp.resolvedPath)) { + if (!settings.adapter) { + logger.error(...
packages/astro/src/core/server-islands/vite-plugin-server-islands.ts
26
TypeScript
0.857
bug
270
51
51
false
fix(core): add error log for server islands
12,768
withastro/astro
47,179
TypeScript
ascorbic
ematipico
.strict(), ) .optional(), families: z.array( z .object({ provider: z.string(), }) .strict(), ), }) .strict() .optional() .superRefine((fonts, ctx) => { if (!fonts) { return; } const providersNames = [ ...BUILTIN_...
We could do better and list the valid providers since we already have them in `providersNames`.
.strict(), ) .optional(), families: z.array( z .object({ provider: z.string(), }) .strict(), ), }) .strict() .optional() .superRefine((fonts, ctx) => { if (!fonts) { return; } const providersNames = [ ...BUILTIN_...
@@ -589,6 +590,53 @@ export const AstroConfigSchema = z.object({ } return svgConfig; }), + fonts: z + .object({ + providers: z + .array( + z + .object({ + name: z.string().superRefine((name, ctx) => { + if (BUILTIN_PROVIDERS.includes(name as any)) { + ...
packages/astro/src/core/config/schema.ts
26
TypeScript
0.429
suggestion
96
51
51
false
feat(fonts): config
12,777
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
globalDataStore.get().then((s) => (store = s)); return function reference(collection: string) { return z .union([ z.string(), z.object({ id: z.string(), collection: z.string(), }), z.object({ slug: z.string(), collection: z.string(), }), ]) .transform( ( loo...
I would add a more actionable message. If the user encounters this error, what should they do? File an issue? Purge the store? We should provide an escape hatch to our users
globalDataStore.get().then((s) => (store = s)); return function reference(collection: string) { return z .union([ z.string(), z.object({ id: z.string(), collection: z.string(), }), z.object({ slug: z.string(), collection: z.string(), }), ]) .transform( ( loo...
@@ -618,15 +622,22 @@ export function createReference({ lookupMap }: { lookupMap: ContentLookupMap }) }), ]) .transform( - async ( + ( lookup: | string | { id: string; collection: string } | { slug: string; collection: string }, ctx, ) => { + if (!store) { + ...
packages/astro/src/content/runtime.ts
26
TypeScript
0.571
security
174
51
51
false
fix: make `reference()` a sync transform
12,781
withastro/astro
47,179
TypeScript
ematipico
ascorbic
] as Array<ContentEntryType>), }; } /** * Enqueues a sync job that runs the `load()` method of each collection's loader, which will load the data and save it in the data store. * The loader itself is responsible for deciding whether this will clear and reload the full collection, or * perform an increment...
Does this check pass when there is no content config? I’d guess a project without a config shouldn’t error/log anything?
] as Array<ContentEntryType>), }; } /** * Enqueues a sync job that runs the `load()` method of each collection's loader, which will load the data and save it in the data store. * The loader itself is responsible for deciding whether this will clear and reload the full collection, or * perform an increment...
@@ -138,8 +138,14 @@ export class ContentLayer { async #doSync(options: RefreshContentOptions) { const contentConfig = globalContentConfigObserver.get(); const logger = this.#logger.forkIntegrationLogger('content'); + + if (contentConfig?.status === 'error') { + logger.error(`Error loading content config. Sk...
packages/astro/src/content/content-layer.ts
26
TypeScript
0.571
question
120
51
51
false
fix: better logs for invalid content config
12,798
withastro/astro
47,179
TypeScript
delucis
ascorbic
// preserving in-memory changes and deletions. #partial = true; constructor( cookies: AstroCookies, { cookie: cookieConfig = DEFAULT_COOKIE_NAME, ...config }: Exclude<ResolvedSessionConfig<TDriver>, undefined>, ) { this.#cookies = cookies; if (typeof cookieConfig === 'object') { this.#cookieConf...
Can't we move these lines inside the `if` block at line 70? It seems we don't need a temporary `cookieConfigObject` object.
// preserving in-memory changes and deletions. #partial = true; constructor( cookies: AstroCookies, { cookie: cookieConfig = DEFAULT_COOKIE_NAME, ...config }: Exclude<ResolvedSessionConfig<TDriver>, undefined>, ) { this.#cookies = cookies; let cookieConfigObject: AstroCookieSetOptions | undefined; ...
@@ -63,12 +63,21 @@ export class AstroSession<TDriver extends SessionDriverName = any> { }: Exclude<ResolvedSessionConfig<TDriver>, undefined>, ) { this.#cookies = cookies; + let cookieConfigObject: AstroCookieSetOptions | undefined; if (typeof cookieConfig === 'object') { - this.#cookieConfig = cookieCon...
packages/astro/src/core/session.ts
26
TypeScript
0.571
suggestion
123
51
51
false
fix: pass cookie options to delete
12,820
withastro/astro
47,179
TypeScript
ematipico
ascorbic
}); describe('dev', () => { let devServer; before(async () => { process.env.ASTRO_KEY = 'eKBaVEuI7YjfanEXHuJe/pwZKKt3LkAHeMxvTU7aR0M='; devServer = await fixture.startDevServer(); }); after(async () => { await devServer.stop(); delete process.env.ASTRO_KEY; }); it('omits the is...
this is failing because you're not providing a body. Change it to a POST and do like in the other test, here: https://github.com/withastro/astro/blob/2d02170611a1d75e7dad00e1b86ffbb962c0b699/packages/astro/test/server-islands.test.js#L48-L52
}); describe('dev', () => { let devServer; before(async () => { process.env.ASTRO_KEY = 'eKBaVEuI7YjfanEXHuJe/pwZKKt3LkAHeMxvTU7aR0M='; devServer = await fixture.startDevServer(); }); after(async () => { await devServer.stop(); delete process.env.ASTRO_KEY; }); it('omits the is...
@@ -37,6 +37,11 @@ describe('Server islands', () => { assert.equal(serverIslandEl.length, 0); }); + it('island is not indexed', async () => { + const res = await fixture.fetch('/_server-islands/Island');
packages/astro/test/server-islands.test.js
26
JavaScript
0.5
bug
241
51
51
false
fix: add noindex to server island headers
12,827
withastro/astro
47,179
TypeScript
matthewp
sinskiy
const fallbackTo = strategy === 'pathname-prefix-other-locales' || strategy === 'domains-prefix-other-locales' ? defaultLocale : undefined; if (this.#currentLocale) { return this.#currentLocale; } let computedLocale; if (routeData.component === SERVER_ISLAND_COMPONENT) { let referer = this....
In the past we used these operators and they made the readability worse, and we decided to use simple if/else. We would appreciate it if we keep using them
const fallbackTo = strategy === 'pathname-prefix-other-locales' || strategy === 'domains-prefix-other-locales' ? defaultLocale : undefined; if (this.#currentLocale) { return this.#currentLocale; } let computedLocale; if (routeData.component === SERVER_ISLAND_COMPONENT) { let referer = this....
@@ -591,8 +591,14 @@ export class RenderContext { computedLocale = computeCurrentLocale(referer, locales, defaultLocale); } } else { - const pathname = - routeData.pathname && !isRoute404or500(routeData) ? routeData.pathname : url.pathname; + // For SSG we match the route naively, for dev we handle f...
packages/astro/src/core/render-context.ts
26
TypeScript
0.429
suggestion
155
51
51
false
Fix i18n current locale
12,839
withastro/astro
47,179
TypeScript
ematipico
mtwilliams-code
import assert from 'node:assert/strict'; import { before, describe, it } from 'node:test'; import testAdapter from './test-adapter.js'; import { loadFixture } from './test-utils.js'; describe('Astro.cookies', () => { /** @type {import('./test-utils').Fixture} */ let fixture; before(async () => { fixture = await ...
```suggestion describe('Astro.session', () => { ```
import assert from 'node:assert/strict'; import { before, describe, it } from 'node:test'; import testAdapter from './test-adapter.js'; import { loadFixture } from './test-utils.js'; describe('Astro.session', () => { /** @type {import('./test-utils').Fixture} */ let fixture; before(async () => { fixture = await ...
@@ -0,0 +1,47 @@ +import assert from 'node:assert/strict'; +import { before, describe, it } from 'node:test'; +import testAdapter from './test-adapter.js'; +import { loadFixture } from './test-utils.js'; + +describe('Astro.cookies', () => {
packages/astro/test/sessions.test.js
6
JavaScript
0.571
suggestion
53
31
31
false
fix: session regeneration
12,864
withastro/astro
47,179
TypeScript
ascorbic
kaytwo