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
.string() .refine((val) => !val.includes('*') || val.endsWith('/*') || val.endsWith('/**'), { message: 'wildcards can only be placed at the end of a pathname', }) .optional(), }), ) .default([]), experimentalLayout: z.enum(['responsive', 'fixed', 'full-width', 'none']...
We need to add a default value. In line 316, you have an example of how we do it. ```js .default(ASTRO_CONFIG_DEFAULTS.markdown.syntaxHighlight) ```
{ message: 'wildcards can only be placed at the beginning of the hostname', }, ) .optional(), port: z.string().optional(), pathname: z .string() .refine((val) => !val.includes('*') || val.endsWith('/*') || val.endsWith('/**'), { message: 'wildcard...
@@ -303,7 +305,14 @@ export const AstroConfigSchema = z.object({ markdown: z .object({ syntaxHighlight: z - .union([z.literal('shiki'), z.literal('prism'), z.literal(false)]) + .union([ + z.object({ + type: highlighterTypesSchema, + excludeLangs: z.array(z.string()).optional(),
packages/astro/src/core/config/schema.ts
26
TypeScript
0.714
suggestion
154
51
51
false
feat(markdown): add `excludeLangs` configuration to syntax highlighting
13,311
withastro/astro
47,179
TypeScript
ematipico
chrisirhc
* * See the [code syntax highlighting guide](/en/guides/syntax-highlighting/) for usage and examples. */ shikiConfig?: Partial<ShikiConfig>; /** * @docs * @name markdown.syntaxHighlight * @type {'shiki' | 'prism' | false} * @default `shiki` * @description * Which syntax highlighter to us...
I completely forgot about this one. The JsDoc must be updated to reflect the new changes
* defaultColor: false, * // Add custom languages * // Note: Shiki has countless langs built-in, including .astro! * // https://shiki.style/languages * langs: [], * // Add custom aliases for languages * // Map an alias to a Shiki language ID: https://shiki.s...
@@ -1283,7 +1284,7 @@ export interface ViteUserConfig extends OriginalViteUserConfig { * } * ``` */ - syntaxHighlight?: 'shiki' | 'prism' | false; + syntaxHighlight?: SyntaxHighlightConfig | SyntaxHighlightConfig['type'] | false;
packages/astro/src/types/public/config.ts
26
TypeScript
0.286
suggestion
89
51
51
false
feat(markdown): add `excludeLangs` configuration to syntax highlighting
13,311
withastro/astro
47,179
TypeScript
ematipico
chrisirhc
* @description * * An array of languages to exclude from the default syntax highlighting specified in `markdown.syntaxHighlight.type`. * This can be useful when using tools that create diagrams from Markdown code blocks, such as Mermaid.js and D2. * * ```js title="astro.config.mjs" ...
```suggestion ``` I would not include this part here, as this is reference documentation for the config option. If we were writing a recipe or a guide, we'd show it in use.
* This can be useful when using tools that create diagrams from Markdown code blocks, such as Mermaid.js and D2. * * ```js title="astro.config.mjs" * import { defineConfig } from 'astro/config'; * * export default defineConfig({ * markdown: { *...
@@ -1305,9 +1307,67 @@ export interface ViteUserConfig extends OriginalViteUserConfig { * } * } * ``` + * + * For more control over syntax highlighting, you can instead specify a configuration object with the properties listed below. */ - syntaxHighlight?: 'shiki' | 'prism' | false; + syntaxHig...
packages/astro/src/types/public/config.ts
26
TypeScript
0.786
suggestion
174
51
51
false
feat(markdown): add `excludeLangs` configuration to syntax highlighting
13,311
withastro/astro
47,179
TypeScript
sarah11918
chrisirhc
mode: SvgRenderMode; }; /** * @name experimental.serializeConfig * @type {boolean} * @default `false` * @version 5.x * @description * * Enables the use of the experimental virtual modules `astro:config/server` and `astro:config/client`. * * These two virtual modules contain a ser...
```suggestion * When enabled, IDs for headings ending with non-alphanumeric characters, e.g. `<Picture />`, will ```
* @type {boolean} * @default `false` * @version 5.x * @description * * Enables the use of the experimental virtual modules `astro:config/server` and `astro:config/client`. * * These two virtual modules contain a serializable subset of the Astro configuration. */ serializeConfig?: boolean; ...
@@ -2111,6 +2111,20 @@ export interface ViteUserConfig extends OriginalViteUserConfig { * These two virtual modules contain a serializable subset of the Astro configuration. */ serializeConfig?: boolean; + + /** + * @name experimental.headingIdCompat + * @type {boolean} + * @default `false` + * @ver...
packages/astro/src/types/public/config.ts
26
TypeScript
0.714
suggestion
121
51
51
false
Add `experimental.headingIdCompat` flag
13,352
withastro/astro
47,179
TypeScript
ascorbic
delucis
message: 'Unexpected problem adding heading IDs to Markdoc file. Did you modify the `ctx.headingSlugger` property in your Markdoc config?', }); } const slug = getSlug(attributes, children, config.ctx.headingSlugger); const render = config.nodes?.heading?.render ?? `h${level}`; const tagProps = ...
Rather than mutating this global, could it be added to ctx?
} const slug = getSlug( attributes, children, config.ctx.headingSlugger, config.ctx.experimentalHeadingIdCompat, ); const render = config.nodes?.heading?.render ?? `h${level}`; const tagProps = // For components, pass down `level` as a prop, // alongside `__collectHeading` for our `heading...
@@ -64,7 +70,8 @@ export const heading: Schema = { }; // Called internally to ensure `ctx` is generated per-file, instead of per-build. -export function setupHeadingConfig(): HeadingIdConfig { +export function setupHeadingConfig(experimentalHeadingIdCompat: boolean): HeadingIdConfig { + sluggerContext.experimentalH...
packages/integrations/markdoc/src/heading-ids.ts
26
TypeScript
0.286
question
59
34
36
false
Add `experimental.headingIdCompat` flag
13,352
withastro/astro
47,179
TypeScript
ascorbic
delucis
export type RemotePattern = { hostname?: string; pathname?: string; protocol?: string; port?: string; }; /** * Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname. * * @param {URL} url - The URL object to be matched against the remote pattern. * @p...
```suggestion * @return {boolean} Returns `true` if the URL matches the given remote pattern; otherwise, `false`. ```
export type RemotePattern = { hostname?: string; pathname?: string; protocol?: string; port?: string; }; /** * Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname. * * @param {URL} url - The URL object to be matched against the remote pattern. * @p...
@@ -5,7 +5,14 @@ export type RemotePattern = { port?: string; }; -export function matchPattern(url: URL, remotePattern: RemotePattern) { +/** + * Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname. + * + * @param {URL} url - The URL object to be match...
packages/internal-helpers/src/remote.ts
13
TypeScript
0.714
suggestion
120
38
38
false
docs: document asset utilities
13,355
withastro/astro
47,179
TypeScript
jsparkdev
ematipico
protocol?: string; port?: string; }; /** * Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname. * * @param {URL} url - The URL object to be matched against the remote pattern. * @param {RemotePattern} remotePattern - The remote pattern object contain...
```suggestion * @return {boolean} Returns `true` if the URL's port matches the specified port or if no port is provided; otherwise, `false`. ```
protocol?: string; port?: string; }; /** * Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname. * * @param {URL} url - The URL object to be matched against the remote pattern. * @param {RemotePattern} remotePattern - The remote pattern object contain...
@@ -14,15 +21,37 @@ export function matchPattern(url: URL, remotePattern: RemotePattern) { ); } -export function matchPort(url: URL, port?: string) { +/** + * Checks if the given URL's port matches the specified port. If no port is provided, it returns true. + * + * @param {URL} url - The URL object whose port wil...
packages/internal-helpers/src/remote.ts
26
TypeScript
0.714
suggestion
147
51
51
false
docs: document asset utilities
13,355
withastro/astro
47,179
TypeScript
jsparkdev
ematipico
export function matchPattern(url: URL, remotePattern: RemotePattern): boolean { return ( matchProtocol(url, remotePattern.protocol) && matchHostname(url, remotePattern.hostname, true) && matchPort(url, remotePattern.port) && matchPathname(url, remotePattern.pathname, true) ); } /** * Checks if the given URL...
```suggestion * @return {boolean} Returns `true` if the protocol matches or if no protocol is specified; otherwise, `false`. ```
export function matchPattern(url: URL, remotePattern: RemotePattern): boolean { return ( matchProtocol(url, remotePattern.protocol) && matchHostname(url, remotePattern.hostname, true) && matchPort(url, remotePattern.port) && matchPathname(url, remotePattern.pathname, true) ); } /** * Checks if the given URL...
@@ -14,15 +21,37 @@ export function matchPattern(url: URL, remotePattern: RemotePattern) { ); } -export function matchPort(url: URL, port?: string) { +/** + * Checks if the given URL's port matches the specified port. If no port is provided, it returns true. + * + * @param {URL} url - The URL object whose port wil...
packages/internal-helpers/src/remote.ts
26
TypeScript
0.714
suggestion
131
51
51
false
docs: document asset utilities
13,355
withastro/astro
47,179
TypeScript
jsparkdev
ematipico
* @param {URL} url - The URL object whose port will be checked. * @param {string} [port] - The port to match against the URL's port. Optional. * @return {boolean} True if the URL's port matches the specified port or if no port is provided; otherwise, false. */ export function matchPort(url: URL, port?: string): boo...
```suggestion * @return {boolean} - Returns `true` if the URL's hostname matches the given hostname criteria; otherwise, `false`. ```
* @param {URL} url - The URL object whose port will be checked. * @param {string} [port=] - The port to match against the URL's port. Optional. * @return {boolean} Returns `true` if the URL's port matches the specified port or if no port is provided; otherwise, `false`. */ export function matchPort(url: URL, port?:...
@@ -14,15 +21,37 @@ export function matchPattern(url: URL, remotePattern: RemotePattern) { ); } -export function matchPort(url: URL, port?: string) { +/** + * Checks if the given URL's port matches the specified port. If no port is provided, it returns true. + * + * @param {URL} url - The URL object whose port wil...
packages/internal-helpers/src/remote.ts
26
TypeScript
0.714
suggestion
136
51
51
false
docs: document asset utilities
13,355
withastro/astro
47,179
TypeScript
jsparkdev
ematipico
if (!hostname) { return true; } else if (!allowWildcard || !hostname.startsWith('*')) { return hostname === url.hostname; } else if (hostname.startsWith('**.')) { const slicedHostname = hostname.slice(2); // ** length return slicedHostname !== url.hostname && url.hostname.endsWith(slicedHostname); } else if...
```suggestion * @return {boolean} - Returns `true` if the URL's pathname matches the specified pattern; otherwise, `false`. ```
if (!hostname) { return true; } else if (!allowWildcard || !hostname.startsWith('*')) { return hostname === url.hostname; } else if (hostname.startsWith('**.')) { const slicedHostname = hostname.slice(2); // ** length return slicedHostname !== url.hostname && url.hostname.endsWith(slicedHostname); } else if...
@@ -42,7 +71,15 @@ export function matchHostname(url: URL, hostname?: string, allowWildcard?: boole return false; } -export function matchPathname(url: URL, pathname?: string, allowWildcard?: boolean) { +/** + * Matches a given URL's pathname against a specified pattern, with optional support for wildcards. + * + ...
packages/internal-helpers/src/remote.ts
26
TypeScript
0.714
suggestion
130
51
51
false
docs: document asset utilities
13,355
withastro/astro
47,179
TypeScript
jsparkdev
ematipico
} else if (!allowWildcard || !pathname.endsWith('*')) { return pathname === url.pathname; } else if (pathname.endsWith('/**')) { const slicedPathname = pathname.slice(0, -2); // ** length return slicedPathname !== url.pathname && url.pathname.startsWith(slicedPathname); } else if (pathname.endsWith('/*')) { ...
```suggestion * @return {boolean} Returns `true` if the source URL matches any of the specified domains or remote patterns; otherwise, `false`. ```
} else if (!allowWildcard || !pathname.endsWith('*')) { return pathname === url.pathname; } else if (pathname.endsWith('/**')) { const slicedPathname = pathname.slice(0, -2); // ** length return slicedPathname !== url.pathname && url.pathname.startsWith(slicedPathname); } else if (pathname.endsWith('/*')) { ...
@@ -62,6 +99,16 @@ export function matchPathname(url: URL, pathname?: string, allowWildcard?: boole return false; } +/** + * Determines whether a given remote resource, identified by its source URL, + * is allowed based on specified domains and remote patterns. + * + * @param {string} src - The source URL of the r...
packages/internal-helpers/src/remote.ts
26
TypeScript
0.714
suggestion
150
48
48
false
docs: document asset utilities
13,355
withastro/astro
47,179
TypeScript
jsparkdev
ematipico
export type RemotePattern = { hostname?: string; pathname?: string; protocol?: string; port?: string; }; /** * Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname. * * @param {URL} url - The URL object to be matched against the remote pattern. * @p...
```suggestion * Checks if the given URL's port matches the specified port. If no port is provided, it returns `true`. ```
export type RemotePattern = { hostname?: string; pathname?: string; protocol?: string; port?: string; }; /** * Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname. * * @param {URL} url - The URL object to be matched against the remote pattern. * @p...
@@ -14,15 +21,37 @@ export function matchPattern(url: URL, remotePattern: RemotePattern) { ); } -export function matchPort(url: URL, port?: string) { +/** + * Checks if the given URL's port matches the specified port. If no port is provided, it returns true.
packages/internal-helpers/src/remote.ts
25
TypeScript
0.714
suggestion
124
50
50
false
docs: document asset utilities
13,355
withastro/astro
47,179
TypeScript
sarah11918
ematipico
pathname?: string; protocol?: string; port?: string; }; /** * Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname. * * @param {URL} url - The URL object to be matched against the remote pattern. * @param {RemotePattern} remotePattern - The remote pa...
Just wondering whether you already have a precedent for how you show optional parameters and suggesting that you be consistent with that that if it exists. In docs, for example, I think we tend to "front-load" the optional part, or even if we don't, it's usually lowercase and in parenthesis: ``` * @param {stri...
pathname?: string; protocol?: string; port?: string; }; /** * Evaluates whether a given URL matches the specified remote pattern based on protocol, hostname, port, and pathname. * * @param {URL} url - The URL object to be matched against the remote pattern. * @param {RemotePattern} remotePattern - The remote pa...
@@ -14,15 +21,37 @@ export function matchPattern(url: URL, remotePattern: RemotePattern) { ); } -export function matchPort(url: URL, port?: string) { +/** + * Checks if the given URL's port matches the specified port. If no port is provided, it returns true. + * + * @param {URL} url - The URL object whose port wil...
packages/internal-helpers/src/remote.ts
26
TypeScript
0.857
suggestion
570
51
51
false
docs: document asset utilities
13,355
withastro/astro
47,179
TypeScript
sarah11918
ematipico
*/ export function matchPattern(url: URL, remotePattern: RemotePattern): boolean { return ( matchProtocol(url, remotePattern.protocol) && matchHostname(url, remotePattern.hostname, true) && matchPort(url, remotePattern.port) && matchPathname(url, remotePattern.pathname, true) ); } /** * Checks if the given...
```suggestion * @param {string} [protocol] - The protocol to compare against, without the trailing colon. If not provided, the method will always return `true`. ```
*/ export function matchPattern(url: URL, remotePattern: RemotePattern): boolean { return ( matchProtocol(url, remotePattern.protocol) && matchHostname(url, remotePattern.hostname, true) && matchPort(url, remotePattern.port) && matchPathname(url, remotePattern.pathname, true) ); } /** * Checks if the given...
@@ -14,15 +21,37 @@ export function matchPattern(url: URL, remotePattern: RemotePattern) { ); } -export function matchPort(url: URL, port?: string) { +/** + * Checks if the given URL's port matches the specified port. If no port is provided, it returns true. + * + * @param {URL} url - The URL object whose port wil...
packages/internal-helpers/src/remote.ts
26
TypeScript
0.714
suggestion
167
51
51
false
docs: document asset utilities
13,355
withastro/astro
47,179
TypeScript
sarah11918
ematipico
* Checks if the given URL's port matches the specified port. If no port is provided, it returns true. * * @param {URL} url - The URL object whose port will be checked. * @param {string} [port] - The port to match against the URL's port. Optional. * @return {boolean} Returns `true` if the URL's port matches the spe...
```suggestion * @param {string} [hostname] - The hostname to match against. Supports wildcard patterns if `allowWildcard` is `true`. ```
* Checks if the given URL's port matches the specified port. If no port is provided, it returns `true`. * * @param {URL} url - The URL object whose port will be checked. * @param {string} [port=] - The port to match against the URL's port. Optional. * @return {boolean} Returns `true` if the URL's port matches the ...
@@ -14,15 +21,37 @@ export function matchPattern(url: URL, remotePattern: RemotePattern) { ); } -export function matchPort(url: URL, port?: string) { +/** + * Checks if the given URL's port matches the specified port. If no port is provided, it returns true. + * + * @param {URL} url - The URL object whose port wil...
packages/internal-helpers/src/remote.ts
26
TypeScript
0.714
suggestion
139
51
51
false
docs: document asset utilities
13,355
withastro/astro
47,179
TypeScript
sarah11918
ematipico
export function matchHostname(url: URL, hostname?: string, allowWildcard?: boolean): boolean { if (!hostname) { return true; } else if (!allowWildcard || !hostname.startsWith('*')) { return hostname === url.hostname; } else if (hostname.startsWith('**.')) { const slicedHostname = hostname.slice(2); // ** lengt...
Same question whether there is a default here?
export function matchHostname(url: URL, hostname?: string, allowWildcard = false): boolean { if (!hostname) { return true; } else if (!allowWildcard || !hostname.startsWith('*')) { return hostname === url.hostname; } else if (hostname.startsWith('**.')) { const slicedHostname = hostname.slice(2); // ** length ...
@@ -42,7 +71,15 @@ export function matchHostname(url: URL, hostname?: string, allowWildcard?: boole return false; } -export function matchPathname(url: URL, pathname?: string, allowWildcard?: boolean) { +/** + * Matches a given URL's pathname against a specified pattern, with optional support for wildcards. + * + ...
packages/internal-helpers/src/remote.ts
26
TypeScript
0.071
question
46
51
51
false
docs: document asset utilities
13,355
withastro/astro
47,179
TypeScript
sarah11918
ematipico
// @ts-check import { it } from 'node:test'; import assert from 'node:assert/strict'; import { loadFonts } from '../../../../dist/assets/fonts/load.js'; it('loadFonts()', async () => { const root = new URL(import.meta.url); const base = '/test'; /** @type {Map<string, any>} */ const store = new Map(); /** @type {...
Should `--astro-font-Roboto` be `--astro-font-roboto`?
hashString: (v) => Buffer.from(v).toString('base64'), getMetricsForFamily: async () => ({ ascent: 0, descent: 0, lineGap: 0, unitsPerEm: 0, xWidthAvg: 0, }), generateFontFace: () => '', log: (message) => { logs.push(message); }, generateCSSVariableName: (name) => name, }); assert.equa...
@@ -82,4 +90,10 @@ it('loadFonts()', async () => { assert.equal(Array.from(hashToUrlMap.keys()).length > 0, true); assert.deepStrictEqual(Array.from(resolvedMap.keys()), ['Roboto']); assert.deepStrictEqual(logs, ['Fonts initialized']); + assert.equal( + resolvedMap + .get('Roboto') + .css.includes(':root { -...
packages/astro/test/units/assets/fonts/load.test.js
26
JavaScript
0.429
question
54
86
30
false
feat(fonts): css vars
13,362
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
// @ts-check import { it } from 'node:test'; import assert from 'node:assert/strict'; import { loadFonts } from '../../../../dist/assets/fonts/load.js'; it('loadFonts()', async () => { const root = new URL(import.meta.url); const base = '/test'; /** @type {Map<string, any>} */ const store = new Map(); /** @type {...
nit: if you manage to use `assert.match`, use that because it shows the string to evaluate in case there's an error
} return await import(id); }, hashString: (v) => Buffer.from(v).toString('base64'), getMetricsForFamily: async () => ({ ascent: 0, descent: 0, lineGap: 0, unitsPerEm: 0, xWidthAvg: 0, }), generateFontFace: () => '', log: (message) => { logs.push(message); }, generateCSSVariableNa...
@@ -82,4 +90,10 @@ it('loadFonts()', async () => { assert.equal(Array.from(hashToUrlMap.keys()).length > 0, true); assert.deepStrictEqual(Array.from(resolvedMap.keys()), ['Roboto']); assert.deepStrictEqual(logs, ['Fonts initialized']); + assert.equal(
packages/astro/test/units/assets/fonts/load.test.js
26
JavaScript
0.714
nitpick
115
86
33
false
feat(fonts): css vars
13,362
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
import { AstroError, AstroErrorData } from '../../core/errors/index.js'; import type { ImageMetadata } from '../types.js'; import { imageMetadata } from './metadata.js'; /** * Infers the dimensions of a remote image by streaming its data and analyzing it progressively until sufficient metadata is available. * * @pa...
Isn't it redundant to have `Throws` explained in `@return` in addition to `@throws`? ```suggestion * @return {Promise<Omit<ImageMetadata, 'src' | 'fsPath'>>} Returns a promise that resolves to an object containing the image dimensions metadata excluding `src` and `fsPath`. * @throws {AstroError} Thrown when the fe...
import { AstroError, AstroErrorData } from '../../core/errors/index.js'; import type { ImageMetadata } from '../types.js'; import { imageMetadata } from './metadata.js'; /** * Infers the dimensions of a remote image by streaming its data and analyzing it progressively until sufficient metadata is available. * * @pa...
@@ -2,6 +2,13 @@ import { AstroError, AstroErrorData } from '../../core/errors/index.js'; import type { ImageMetadata } from '../types.js'; import { imageMetadata } from './metadata.js'; +/** + * Infers the dimensions of a remote image by streaming its data and analyzing it progressively until sufficient metadata i...
packages/astro/src/assets/utils/remoteProbe.ts
10
TypeScript
1
bug
370
35
35
false
docs: document utility functions
13,367
withastro/astro
47,179
TypeScript
ArmandPhilippot
ematipico
* ```astro * --- * import Logo from './path/to/svg/file.svg'; * --- * * <Logo size={24} mode="sprite" /> * ``` */ mode: SvgRenderMode; }; /** * @name experimental.serializeConfig * @type {boolean} * @default `false` * @version 5.x * @descriptio...
```suggestion * @name experimental.preserveScriptOrder ```
* const cart = await Astro.session.get('cart'); * --- * * <a href="/checkout">🛒 {cart?.length ?? 0} items</a> * * ``` * * For more details, see [the experimental session guide](https://docs.astro.build/en/reference/experimental-flags/sessions/). * */ session?: boolean; /** * * ...
@@ -2106,6 +2106,17 @@ export interface ViteUserConfig extends OriginalViteUserConfig { * These two virtual modules contain a serializable subset of the Astro configuration. */ serializeConfig?: boolean; + + /** + * @name experimental.serializeConfig
packages/astro/src/types/public/config.ts
26
TypeScript
0.571
suggestion
63
51
51
false
feat: experimental flag from compiler
13,402
withastro/astro
47,179
TypeScript
ascorbic
ematipico
* --- * * <Logo size={24} mode="sprite" /> * ``` */ mode: SvgRenderMode; }; /** * @name experimental.serializeConfig * @type {boolean} * @default `false` * @version 5.x * @description * * Enables the use of the experimental virtual modules `astro:config/se...
```suggestion * @version 5.5 ```
* <a href="/checkout">🛒 {cart?.length ?? 0} items</a> * * ``` * * For more details, see [the experimental session guide](https://docs.astro.build/en/reference/experimental-flags/sessions/). * */ session?: boolean; /** * * @name experimental.svg * @type {boolean|object} * @default ...
@@ -2106,6 +2106,17 @@ export interface ViteUserConfig extends OriginalViteUserConfig { * These two virtual modules contain a serializable subset of the Astro configuration. */ serializeConfig?: boolean; + + /** + * @name experimental.serializeConfig + * @type {boolean} + * @default `false` + * @ver...
packages/astro/src/types/public/config.ts
26
TypeScript
0.429
suggestion
37
51
51
false
feat: experimental flag from compiler
13,402
withastro/astro
47,179
TypeScript
ascorbic
ematipico
* ``` */ mode: SvgRenderMode; }; /** * @name experimental.serializeConfig * @type {boolean} * @default `false` * @version 5.x * @description * * Enables the use of the experimental virtual modules `astro:config/server` and `astro:config/client`. * * These two virtual ...
Also here, include comparison with current behaviour
* * For more details, see [the experimental session guide](https://docs.astro.build/en/reference/experimental-flags/sessions/). * */ session?: boolean; /** * * @name experimental.svg * @type {boolean|object} * @default `undefined` * @version 5.x * @description * * This feature a...
@@ -2106,6 +2106,17 @@ export interface ViteUserConfig extends OriginalViteUserConfig { * These two virtual modules contain a serializable subset of the Astro configuration. */ serializeConfig?: boolean; + + /** + * @name experimental.serializeConfig + * @type {boolean} + * @default `false` + * @ver...
packages/astro/src/types/public/config.ts
26
TypeScript
0.214
suggestion
52
51
51
false
feat: experimental flag from compiler
13,402
withastro/astro
47,179
TypeScript
ascorbic
ematipico
* or otherwise fall back to `'fetch'`. `'link'` works better if the URL doesn't set an appropriate cache header, * as the browser will continue to cache it as long as it's used subsequently. */ with?: 'link' | 'fetch'; /** * Should prefetch even on data saver mode or slow connection. (default `false`) */ i...
A couple of suggestions: - There's no need to quote the entire text from MDN, the link is enough - Instead of quoting the docs from MDN, we should explain how this new options works. For example, we should explain that this option is applied **only if the browser supports the new speculation rules**. This is a very i...
* or otherwise fall back to `'fetch'`. `'link'` works better if the URL doesn't set an appropriate cache header, * as the browser will continue to cache it as long as it's used subsequently. */ with?: 'link' | 'fetch'; /** * Should prefetch even on data saver mode or slow connection. (default `false`) */ i...
@@ -200,6 +200,25 @@ export interface PrefetchOptions { * Should prefetch even on data saver mode or slow connection. (default `false`) */ ignoreSlowConnection?: boolean; + /** + * A string providing a hint to the browser as to how eagerly it should prefetch/prerender link targets in order to balance performan...
packages/astro/src/prefetch/index.ts
26
TypeScript
0.5
suggestion
341
51
51
false
feat: Add `eagerness` support for `prefetch()`
13,405
withastro/astro
47,179
TypeScript
ematipico
Marocco2
// Adapted from https://github.com/unjs/fontaine/ import type { Font } from '@capsizecss/unpack'; import { fontFamilyToCamelCase } from '@capsizecss/metrics'; import { fromBlob } from '@capsizecss/unpack'; const withoutQuotes = (str: string) => str.trim().replace(/^["']|["']$/g, ''); export type FontFaceMetrics = Pic...
small nit: move the regex into a top-level constant
// Adapted from https://github.com/unjs/fontaine/ import type { Font } from '@capsizecss/unpack'; import { fontFamilyToCamelCase } from '@capsizecss/metrics'; import { fromBlob } from '@capsizecss/unpack'; const QUOTES_RE = /^["']|["']$/g const withoutQuotes = (str: string) => str.trim().replace(QUOTES_RE, ''); expo...
@@ -0,0 +1,122 @@ +// Adapted from https://github.com/unjs/fontaine/ +import type { Font } from '@capsizecss/unpack'; +import { fontFamilyToCamelCase } from '@capsizecss/metrics'; +import { fromBlob } from '@capsizecss/unpack'; + +const withoutQuotes = (str: string) => str.trim().replace(/^["']|["']$/g, '');
packages/astro/src/assets/fonts/metrics.ts
6
TypeScript
0.286
nitpick
52
31
31
false
feat(fonts): use capsize instead of fontaine
13,411
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
res.setHeader('Pragma', 'no-cache'); res.setHeader('Expires', 0); res.end(data); }); }, resolveId(id) { if (id === VIRTUAL_MODULE_ID) { return RESOLVED_VIRTUAL_MODULE_ID; } }, load(id, opts) { if (id === RESOLVED_VIRTUAL_MODULE_ID && opts?.ssr) { return ` export const fontsD...
Just confirming that we can be sure `font` is always defined. Non-null assertions always make me nervous.
res.setHeader('Content-Length', data.length); res.setHeader('Content-Type', `font/${extractFontType(hash)}`); // We don't want the request to be cached in dev because we cache it already internally, // and it makes it easier to debug without needing hard refreshes res.setHeader('Cache-Control', 'no...
@@ -195,41 +201,37 @@ export function fontsPlugin({ settings, sync, logger }: Options): Plugin { } }, async buildEnd() { - resolvedMap = null; - - if (sync) { - hashToUrlMap = null; - storage = null; + if (sync || settings.config.experimental.fonts!.families.length === 0) {
packages/astro/src/assets/fonts/vite-plugin-fonts.ts
26
TypeScript
0.643
suggestion
105
51
51
false
fix(fonts): vite plugin cleanup
13,424
withastro/astro
47,179
TypeScript
ascorbic
florian-lefebvre
/** * @docs * @description * An unknown error occurred while reading or writing files to disk. It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. */ export const UnknownFilesystemError = { name: 'UnknownFilesystemError', title: 'An unknown error occurred while read...
```suggestion * Cannot extract the given font type ``` Bearing in mind that I don't know how the internals work... 😄 (And that these are placeholders!) Just noting that the error seems to be named like it's a problem *extracting* the font type from a file (that it has fetched?), whereas this description says it...
/** * @docs * @description * An unknown error occurred while reading or writing files to disk. It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. */ export const UnknownFilesystemError = { name: 'UnknownFilesystemError', title: 'An unknown error occurred while read...
@@ -1304,6 +1304,77 @@ export const UnknownFilesystemError = { hint: 'It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. Check the error cause for more details.', } satisfies ErrorData; +/** + * @docs + * @description + * Cannot extract the font type from the given ...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
1
refactor
726
51
51
false
feat(fonts): add errors
13,425
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
* @description * An unknown error occurred while reading or writing files to disk. It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. */ export const UnknownFilesystemError = { name: 'UnknownFilesystemError', title: 'An unknown error occurred while reading or writin...
```suggestion * An error occurred while extracting the font type from the given URL. ```
* @description * An unknown error occurred while reading or writing files to disk. It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. */ export const UnknownFilesystemError = { name: 'UnknownFilesystemError', title: 'An unknown error occurred while reading or writin...
@@ -1304,6 +1304,77 @@ export const UnknownFilesystemError = { hint: 'It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. Check the error cause for more details.', } satisfies ErrorData; +/** + * @docs + * @description + * Cannot extract the font type from the given ...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.786
refactor
91
51
51
false
feat(fonts): add errors
13,425
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
title: 'An unknown error occurred while reading or writing files to disk.', hint: 'It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. Check the error cause for more details.', } satisfies ErrorData; /** * @docs * @description * Cannot extract the font type from the...
```suggestion message: (url: string) => `An error occurred while fetching the font file from ${url}`, ```
title: 'An unknown error occurred while reading or writing files to disk.', hint: 'It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. Check the error cause for more details.', } satisfies ErrorData; /** * @docs * @description * Cannot extract the font type from the...
@@ -1304,6 +1304,77 @@ export const UnknownFilesystemError = { hint: 'It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. Check the error cause for more details.', } satisfies ErrorData; +/** + * @docs + * @description + * Cannot extract the font type from the given ...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.857
suggestion
108
51
51
false
feat(fonts): add errors
13,425
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
hint: 'It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. Check the error cause for more details.', } satisfies ErrorData; /** * @docs * @description * Cannot extract the font type from the given URL. */ export const CannotExtractFontType = { name: 'CannotExtractF...
```suggestion hint: 'Check that you have the correct URL to the font file. Please open an issue if Astro is unable to fetch a valid font file.', ``` Is it something like this?
hint: 'It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. Check the error cause for more details.', } satisfies ErrorData; /** * @docs * @description * Cannot extract the font type from the given URL. */ export const CannotExtractFontType = { name: 'CannotExtractF...
@@ -1304,6 +1304,77 @@ export const UnknownFilesystemError = { hint: 'It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. Check the error cause for more details.', } satisfies ErrorData; +/** + * @docs + * @description + * Cannot extract the font type from the given ...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.714
question
179
51
51
false
feat(fonts): add errors
13,425
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
} satisfies ErrorData; /** * @docs * @description * Cannot fetch the given font file * @message * An error occured while fetching font file from the given URL. */ export const CannotFetchFontFile = { name: 'CannotFetchFontFile', title: 'Cannot fetch the given font file.', message: (url: string) => `An error o...
```suggestion hint: 'Restore the file or remove this font from your configuration if it is no longer needed.', ```
} satisfies ErrorData; /** * @docs * @description * Cannot fetch the given font file * @message * An error occured while fetching font file from the given URL. */ export const CannotFetchFontFile = { name: 'CannotFetchFontFile', title: 'Cannot fetch the given font file.', message: (url: string) => `An error o...
@@ -1304,6 +1304,77 @@ export const UnknownFilesystemError = { hint: 'It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. Check the error cause for more details.', } satisfies ErrorData; +/** + * @docs + * @description + * Cannot extract the font type from the given ...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.786
refactor
117
51
51
false
feat(fonts): add errors
13,425
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
*/ export const CannotFetchFontFile = { name: 'CannotFetchFontFile', title: 'Cannot fetch the given font file.', message: (url: string) => `An error occured while fetching font file from ${url}`, hint: 'Check the error cause and open an issue if it cannot be solved on your side.', } satisfies ErrorData; /** * @d...
```suggestion * Astro is unable to load the given font provider. Open an issue on the corresponding provider's repository. ``` I think here, more than just "an error occurred" we might want to more strongly imply "Astro knows what it's doing, but it can't make sense of what it was given." Otherwise, it's hard to kn...
*/ export const CannotFetchFontFile = { name: 'CannotFetchFontFile', title: 'Cannot fetch the given font file.', message: (url: string) => `An error occurred while fetching the font file from ${url}`, hint: 'This is often caused by connectivity issues. If the error persists, open an issue at https://github.com/wit...
@@ -1304,6 +1304,77 @@ export const UnknownFilesystemError = { hint: 'It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. Check the error cause for more details.', } satisfies ErrorData; +/** + * @docs + * @description + * Cannot extract the font type from the given ...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.929
suggestion
354
51
51
false
feat(fonts): add errors
13,425
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
} satisfies ErrorData; /** * @docs * @description * A local font file referenced in your Astro config has been deleted. Restore the file or update your Astro config. */ export const DeletedLocalFont = { name: 'DeletedLocalFont', title: 'A local font has been deleted', message: 'A local font file referenced in y...
```suggestion hint: 'This is an issue with the font provider. Please open an issue on their repository.', ``` The hint is the perfect place to "let people in" on what's happening.
} satisfies ErrorData; /** * @docs * @description * A local font file referenced in your Astro config has been deleted. Restore the file or update your Astro config. */ export const DeletedLocalFont = { name: 'DeletedLocalFont', title: 'A local font has been deleted', message: 'A local font file referenced in y...
@@ -1304,6 +1304,77 @@ export const UnknownFilesystemError = { hint: 'It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. Check the error cause for more details.', } satisfies ErrorData; +/** + * @docs + * @description + * Cannot extract the font type from the given ...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.714
suggestion
183
51
51
false
feat(fonts): add errors
13,425
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
} satisfies ErrorData; /** * @docs * @description * Cannot load font provider * @message * An error occured while loading the given provider. Open an issue on the corresponding repository. */ export const CannotLoadFontProvider = { name: 'CannotLoadFontProvider', title: 'Cannot load font provider', message: (...
```suggestion 'The Font component is used but experimental fonts have not been registered in the config.', ```
} satisfies ErrorData; /** * @docs * @description * Cannot load font provider * @message * Astro is unable to load the given font provider. Open an issue on the corresponding provider's repository. */ export const CannotLoadFontProvider = { name: 'CannotLoadFontProvider', title: 'Cannot load font provider', m...
@@ -1304,6 +1304,77 @@ export const UnknownFilesystemError = { hint: 'It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. Check the error cause for more details.', } satisfies ErrorData; +/** + * @docs + * @description + * Cannot extract the font type from the given ...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.786
suggestion
114
51
51
false
feat(fonts): add errors
13,425
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
*/ export const CannotLoadFontProvider = { name: 'CannotLoadFontProvider', title: 'Cannot load font provider', message: (provider: string) => `An error occured while loading the "${provider}" provider.`, hint: 'Open an issue on the corresponding repository.', } satisfies ErrorData; /** * @docs * @description *...
```suggestion hint: 'This is often caused by a typo in your configuration. Review your config family names.', ``` Hints can include a "this is often caused by". So if e.g. the likely cause is a typo, this is a great place to guide people with easy language to a quick thing they can check!
*/ export const CannotLoadFontProvider = { name: 'CannotLoadFontProvider', title: 'Cannot load font provider', message: (provider: string) => `An error occured while loading the "${provider}" provider.`, hint: 'This is an issue with the font provider. Please open an issue on their repository.', } satisfies ErrorDa...
@@ -1304,6 +1304,77 @@ export const UnknownFilesystemError = { hint: 'It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. Check the error cause for more details.', } satisfies ErrorData; +/** + * @docs + * @description + * Cannot extract the font type from the given ...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.857
suggestion
293
51
51
false
feat(fonts): add errors
13,425
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
import { createRequire } from 'node:module'; import { google } from './google.js'; import type { FontProvider, ResolvedFontProvider } from '../types.js'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { AstroError, AstroErrorData } from '../../../core/errors/index.js'; export function resolveEntrypoin...
Let's provide more information about how a user should fix this error.
import { createRequire } from 'node:module'; import { google } from './google.js'; import type { FontProvider, ResolvedFontProvider } from '../types.js'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { AstroError, AstroErrorData } from '../../../core/errors/index.js'; export function resolveEntrypoin...
@@ -13,18 +14,25 @@ export function resolveEntrypoint(root: URL, entrypoint: string): string { } } -export function validateMod(mod: any): Pick<ResolvedFontProvider, 'provider'> { +export function validateMod( + mod: any, + providerName: string, +): Pick<ResolvedFontProvider, 'provider'> { try { if (!mod.prov...
packages/astro/src/assets/fonts/providers/utils.ts
23
TypeScript
0.429
style
71
48
48
false
feat(fonts): add errors
13,425
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
'${component}', which is marked as prerendered. This is a forbidden operation because during the build the component '${component}' is compiled to an HTML file, which can't be retrieved at runtime by Astro.`, hint: (component: string) => `Add \`export const prerender = false\` to the component '${component}', or use...
I noticed where this error is used, and I believe we can be more specific here. For example, we can pass the extension and print it if it exists. That will help us with the triaging.
'${component}', which is marked as prerendered. This is a forbidden operation because during the build the component '${component}' is compiled to an HTML file, which can't be retrieved at runtime by Astro.`, hint: (component: string) => `Add \`export const prerender = false\` to the component '${component}', or use...
@@ -1304,6 +1304,77 @@ export const UnknownFilesystemError = { hint: 'It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. Check the error cause for more details.', } satisfies ErrorData; +/** + * @docs + * @description + * Cannot extract the font type from the given ...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.571
suggestion
185
51
51
false
feat(fonts): add errors
13,425
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
?.toString() ?.split(',') .map((e) => e.trim())?.[0]; }; // Get the used protocol between the end client and first proxy. // NOTE: Some proxies append values with spaces and some do not. // We need to handle it here and parse the header correctly. // @example "https, http,http" => "http" const ...
```suggestion } catch { ```
?.toString() ?.split(',') .map((e) => e.trim())?.[0]; }; // Get the used protocol between the end client and first proxy. // NOTE: Some proxies append values with spaces and some do not. // We need to handle it here and parse the header correctly. // @example "https, http,http" => "http" const ...
@@ -75,19 +75,27 @@ export class NodeApp extends App { // We need to handle it here and parse the header correctly. // @example "https, http,http" => "http" const forwardedProtocol = getFirstForwardedValue(req.headers['x-forwarded-proto']); - const protocol = forwardedProtocol ?? (isEncrypted ? 'https' : 'htt...
packages/astro/src/core/app/node.ts
26
TypeScript
0.429
suggestion
31
51
51
false
Handle bad values in x-forwarded-host
13,428
withastro/astro
47,179
TypeScript
florian-lefebvre
matthewp
import type { CacheStorage as CLOUDFLARE_CACHESTORAGE, Request as CLOUDFLARE_REQUEST, ExecutionContext, } from '@cloudflare/workers-types'; import type { SSRManifest } from 'astro'; import { App } from 'astro/app'; import { setGetEnv } from 'astro/env/setup'; import { env as globalEnv } from 'cloudflare:workers'; im...
Could the argument for `createGetEnv` be changed, rather than casting here?
import type { CacheStorage as CLOUDFLARE_CACHESTORAGE, Request as CLOUDFLARE_REQUEST, ExecutionContext, } from '@cloudflare/workers-types'; import type { SSRManifest } from 'astro'; import { App } from 'astro/app'; import { setGetEnv } from 'astro/env/setup'; import { env as globalEnv } from 'cloudflare:workers'; im...
@@ -6,8 +6,11 @@ import type { import type { SSRManifest } from 'astro'; import { App } from 'astro/app'; import { setGetEnv } from 'astro/env/setup'; +import { env as globalEnv } from 'cloudflare:workers'; import { createGetEnv } from '../utils/env.js'; +setGetEnv(createGetEnv(globalEnv as any));
packages/integrations/cloudflare/src/entrypoints/server.ts
12
TypeScript
0.571
question
75
37
37
false
feat(cloudflare): global env
13,444
withastro/astro
47,179
TypeScript
ascorbic
florian-lefebvre
* Astro.cookies.get(key) is used to get a cookie value. The cookie value is read from the * request. If you have set a cookie via Astro.cookies.set(key, value), the value will be taken * from that set call, overriding any values already part of the request. * @param key The cookie to get. * @returns An object...
The new type returns `Record<string, string | undefined>`, so to avoid possible breakages in `AstroCookie`, I create the type only when the value isn't `undefined`
* Astro.cookies.get(key) is used to get a cookie value. The cookie value is read from the * request. If you have set a cookie via Astro.cookies.set(key, value), the value will be taken * from that set call, overriding any values already part of the request. * @param key The cookie to get. * @returns An object...
@@ -120,7 +120,9 @@ class AstroCookies implements AstroCookiesInterface { const values = this.#ensureParsed(options); if (key in values) { const value = values[key]; - return new AstroCookie(value); + if (value) { + return new AstroCookie(value); + }
packages/astro/src/core/cookies/cookies.ts
26
TypeScript
0.714
suggestion
163
51
51
false
chore: remove deprecated package
13,455
withastro/astro
47,179
TypeScript
ematipico
ematipico
// Create final response from body const init = result.response; const headers = new Headers(init.headers); // For non-streaming, convert string to byte array to calculate Content-Length if (!streaming && typeof body === 'string') { body = encoder.encode(body); headers.set('Content-Length', body.byteLength.to...
What if there's a custom status text? this would override it I think
// Create final response from body const init = result.response; const headers = new Headers(init.headers); // For non-streaming, convert string to byte array to calculate Content-Length if (!streaming && typeof body === 'string') { body = encoder.encode(body); headers.set('Content-Length', body.byteLength.to...
@@ -81,14 +81,18 @@ export async function renderPage( headers.set('Content-Length', body.byteLength.toString()); } let status = init.status; + let statusText = init.statusText; // Custom 404.astro and 500.astro are particular routes that must return a fixed status code if (route?.route === '/404') { statu...
packages/astro/src/runtime/server/render/page.ts
26
TypeScript
0.214
question
68
27
31
false
fix: set correct statusText for custom error pages
13,457
withastro/astro
47,179
TypeScript
florian-lefebvre
ascorbic
declare module 'astro:assets' { /** Run `astro dev` or `astro sync` to generate high fidelity types */ export type FontFamily = string; }
Is there a better way? This should be considered an internal type
declare module 'astro:assets' { /** @internal Run `astro dev` or `astro sync` to generate high fidelity types */ export type FontFamily = string; }
@@ -0,0 +1,4 @@ +declare module 'astro:assets' { + /** Run `astro dev` or `astro sync` to generate high fidelity types */ + export type FontFamily = string;
packages/astro/types/fonts.d.ts
3
TypeScript
0.429
suggestion
65
5
5
false
feat(fonts): typegen for <Font /> family prop
13,465
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
mode: 'inline' as SvgRenderMode, }; } } return svgConfig; }), fonts: z .object({ providers: z.array(fontProviderSchema).optional(), families: z.array( z.union([ // Shorthand z .string() .transform( (name): FontFamilyAttrib...
I would avoid a `transform` inside for our configuration. I used `.transform` in the past, which is the side effect of passing the transformed configuration **to the integrations**. This means they will have incorrect types, and they might be able to delete our defaults. I experienced this inconvenience when I imple...
mode: 'inline' as SvgRenderMode, }; } } return svgConfig; }), fonts: z .object({ providers: z.array(fontProviderSchema).optional(), families: z.array( z.union([ // Shorthand z .string() .transform( (name): FontFamilyAttrib...
@@ -621,7 +621,10 @@ export const AstroConfigSchema = z.object({ }), ), localFontFamilySchema, - commonFontFamilySchema, + commonFontFamilySchema.transform((family) => ({ + provider: GOOGLE_PROVIDER_NAME, + ...family, + })),
packages/astro/src/core/config/schema.ts
26
TypeScript
0.786
bug
407
51
51
false
fix(fonts): config family types for inferred provider
13,469
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
false, ]); } /** * Astro.cookies.get(key) is used to get a cookie value. The cookie value is read from the * request. If you have set a cookie via Astro.cookies.set(key, value), the value will be taken * from that set call, overriding any values already part of the request. * @param key The cookie to ge...
I don't understand this part. Why do we use `decodeURIComponent`? The previous code didn't use it, and the PR doesn't mention it. What am I missing?
false, ]); } /** * Astro.cookies.get(key) is used to get a cookie value. The cookie value is read from the * request. If you have set a cookie via Astro.cookies.set(key, value), the value will be taken * from that set call, overriding any values already part of the request. * @param key The cookie to ge...
@@ -117,11 +119,13 @@ class AstroCookies implements AstroCookiesInterface { } } - const values = this.#ensureParsed(options); + const decode = options?.decode ?? decodeURIComponent
packages/astro/src/core/cookies/cookies.ts
26
TypeScript
0.571
question
149
51
51
false
fix: cache raw cookie value and decode when getting
13,485
withastro/astro
47,179
TypeScript
ematipico
ascorbic
if (key in values) { const value = values[key]; if (value) { return new AstroCookie(value); } } } /** * Astro.cookies.has(key) returns a boolean indicating whether this cookie is either * part of the initial request or set via Astro.cookies.set(key) * @param key The cookie to check for. * @r...
Previously it would return `false` for `has()` when the cookie had a falsy value, even if it existed
// decodeURIComponent is the default decode function for cookies const decode = options?.decode ?? decodeURIComponent const values = this.#ensureParsed(); if (key in values) { const value = values[key]; if (value) { return new AstroCookie(decode(value)); } } } /** * Astro.cookies.has(key) r...
@@ -130,15 +134,16 @@ class AstroCookies implements AstroCookiesInterface { * Astro.cookies.has(key) returns a boolean indicating whether this cookie is either * part of the initial request or set via Astro.cookies.set(key) * @param key The cookie to check for. + * @param _options This parameter is no longer ...
packages/astro/src/core/cookies/cookies.ts
26
TypeScript
0.5
suggestion
100
51
51
false
fix: cache raw cookie value and decode when getting
13,485
withastro/astro
47,179
TypeScript
ascorbic
ascorbic
let shouldEmitFile = false; let isBuild = false; globalThis.astroAsset = { referencedImages: new Set(), }; const imageComponentPrefix = settings.config.experimental.responsiveImages ? 'Responsive' : ''; return [ // Expose the components and different utilities from `astro:assets` { name: 'astro:assets'...
Makes it an object that returns `code` (rollup/rolldown compatible shape) and `moduleType` (only rolldown I think)
let shouldEmitFile = false; let isBuild = false; globalThis.astroAsset = { referencedImages: new Set(), }; const imageComponentPrefix = settings.config.experimental.responsiveImages ? 'Responsive' : ''; return [ // Expose the components and different utilities from `astro:assets` { name: 'astro:assets'...
@@ -117,32 +117,35 @@ export default function assets({ settings }: { settings: AstroSettings }): vite. }, load(id) { if (id === resolvedVirtualModuleId) { - return /* ts */ ` - export { getConfiguredImageService, isLocalService } from "astro/assets"; - import { getImage as getImageInternal } fr...
packages/astro/src/assets/vite-plugin-assets.ts
26
TypeScript
0.643
suggestion
114
51
51
false
feat: improve rolldown compatibility
13,519
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
// new URL("dist/...") is interpreted by the bundler as a signal to include that directory // in the Lambda bundle, which would bloat the bundle with images. // To prevent this, we mark the URL construction as pure, // so that it's tree-shaken away for all platforms that don't need it. ...
In rolldown hashes are not exactly 8 long
// new URL("dist/...") is interpreted by the bundler as a signal to include that directory // in the Lambda bundle, which would bloat the bundle with images. // To prevent this, we mark the URL construction as pure, // so that it's tree-shaken away for all platforms that don't need it. ...
@@ -151,7 +154,7 @@ export default function assets({ settings }: { settings: AstroSettings }): vite. }, // In build, rewrite paths to ESM imported images in code to their final location async renderChunk(code) { - const assetUrlRE = /__ASTRO_ASSET_IMAGE__([\w$]{8})__(?:_(.*?)__)?/g; + const assetUrlRE...
packages/astro/src/assets/vite-plugin-assets.ts
26
TypeScript
0.071
suggestion
41
51
51
false
feat: improve rolldown compatibility
13,519
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
} // If the requested ID doesn't end with a valid image extension, we'll let Vite handle it if (!assetRegexEnds.test(id)) { return; } const emitFile = shouldEmitFile ? this.emitFile.bind(this) : undefined; const imageMetadata = await emitESMImage( id, this.meta.watchMod...
Makes it an object that returns `code` (rollup/rolldown compatible shape) and `moduleType` (only rolldown I think)
// If the requested ID doesn't end with a valid image extension, we'll let Vite handle it if (!assetRegexEnds.test(id)) { return; } const emitFile = shouldEmitFile ? this.emitFile.bind(this) : undefined; const imageMetadata = await emitESMImage( id, this.meta.watchMode, ...
@@ -223,22 +226,31 @@ export default function assets({ settings }: { settings: AstroSettings }): vite. if (settings.config.experimental.svg && /\.svg$/.test(id)) { const { contents, ...metadata } = imageMetadata; // We know that the contents are present, as we only emit this property for SVG files -...
packages/astro/src/assets/vite-plugin-assets.ts
26
TypeScript
0.643
suggestion
114
51
49
false
feat: improve rolldown compatibility
13,519
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
const emitFile = shouldEmitFile ? this.emitFile.bind(this) : undefined; const imageMetadata = await emitESMImage( id, this.meta.watchMode, !!settings.config.experimental.svg, emitFile, ); if (!imageMetadata) { throw new AstroError({ ...AstroErrorData.ImageNotFo...
Makes it an object that returns `code` (rollup/rolldown compatible shape) and `moduleType` (only rolldown I think)
const emitFile = shouldEmitFile ? this.emitFile.bind(this) : undefined; const imageMetadata = await emitESMImage( id, this.meta.watchMode, !!settings.config.experimental.svg, emitFile, ); if (!imageMetadata) { throw new AstroError({ ...AstroErrorData.ImageNotFou...
@@ -223,22 +226,31 @@ export default function assets({ settings }: { settings: AstroSettings }): vite. if (settings.config.experimental.svg && /\.svg$/.test(id)) { const { contents, ...metadata } = imageMetadata; // We know that the contents are present, as we only emit this property for SVG files -...
packages/astro/src/assets/vite-plugin-assets.ts
26
TypeScript
0.643
suggestion
114
51
43
false
feat: improve rolldown compatibility
13,519
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
if (!imageMetadata) { throw new AstroError({ ...AstroErrorData.ImageNotFound, message: AstroErrorData.ImageNotFound.message(id), }); } if (settings.config.experimental.svg && /\.svg$/.test(id)) { const { contents, ...metadata } = imageMetadata; // We know that the ...
Makes it an object that returns `code` (rollup/rolldown compatible shape) and `moduleType` (only rolldown I think)
if (!imageMetadata) { throw new AstroError({ ...AstroErrorData.ImageNotFound, message: AstroErrorData.ImageNotFound.message(id), }); } if (settings.config.experimental.svg && /\.svg$/.test(id)) { const { contents, ...metadata } = imageMetadata; // We know that the c...
@@ -223,22 +226,31 @@ export default function assets({ settings }: { settings: AstroSettings }): vite. if (settings.config.experimental.svg && /\.svg$/.test(id)) { const { contents, ...metadata } = imageMetadata; // We know that the contents are present, as we only emit this property for SVG files -...
packages/astro/src/assets/vite-plugin-assets.ts
26
TypeScript
0.643
suggestion
114
43
35
false
feat: improve rolldown compatibility
13,519
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
let isBuild = false; globalThis.astroAsset = { referencedImages: new Set(), }; const imageComponentPrefix = settings.config.experimental.responsiveImages ? 'Responsive' : ''; return [ // Expose the components and different utilities from `astro:assets` { name: 'astro:assets', config(_, env) { isB...
This comment isn't correct, right? It's JS code, not TS code
let isBuild = false; globalThis.astroAsset = { referencedImages: new Set(), }; const imageComponentPrefix = settings.config.experimental.responsiveImages ? 'Responsive' : ''; return [ // Expose the components and different utilities from `astro:assets` { name: 'astro:assets', config(_, env) { isB...
@@ -117,32 +117,35 @@ export default function assets({ settings }: { settings: AstroSettings }): vite. }, load(id) { if (id === resolvedVirtualModuleId) { - return /* ts */ ` - export { getConfiguredImageService, isLocalService } from "astro/assets"; - import { getImage as getImageInternal } fr...
packages/astro/src/assets/vite-plugin-assets.ts
26
TypeScript
0.214
suggestion
60
51
51
false
feat: improve rolldown compatibility
13,519
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
import type { SSRManifest } from '../core/app/types.js'; import { IncorrectStrategyForI18n } from '../core/errors/errors-data.js'; import { AstroError } from '../core/errors/index.js'; import * as I18nInternals from '../i18n/index.js'; import type { RedirectToFallback } from '../i18n/index.js'; import { toFallbackType,...
Was toCodes part of the public API? (ie. is it breaking?)
import type { SSRManifest } from '../core/app/types.js'; import { IncorrectStrategyForI18n } from '../core/errors/errors-data.js'; import { AstroError } from '../core/errors/index.js'; import * as I18nInternals from '../i18n/index.js'; import type { RedirectToFallback } from '../i18n/index.js'; import { toFallbackType,...
@@ -9,7 +9,7 @@ import type { MiddlewareHandler } from '../types/public/common.js'; import type { AstroConfig, ValidRedirectStatus } from '../types/public/config.js'; import type { APIContext } from '../types/public/context.js'; -export { normalizeTheLocale, toCodes, toPaths } from '../i18n/index.js';
packages/astro/src/virtual-modules/i18n.ts
12
TypeScript
0.214
suggestion
57
37
37
false
fix(i18n): return value from `preferredLocale`
13,524
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
locales: z.array( z.union([ z.string(), z.object({ path: z.string(), codes: z.string().array().nonempty(), }), ]), ), domains: z .record( z.string(), z .string() .url( "The domain value must be a valid URL, and it has to start ...
Are we sure this should be changed? We document this: > You can opt out of this behavior by setting `redirectToDefaultLocale: false` — https://docs.astro.build/en/guides/internationalization/#redirecttodefaultlocale and > `i18n.routing.redirectToDefaultLocale` > **Default:** `true` — https://docs.astr...
locales: z.array( z.union([ z.string(), z.object({ path: z.string(), codes: z.string().array().nonempty(), }), ]), ), domains: z .record( z.string(), z .string() .url( "The domain value must be a valid URL, and it has to start ...
@@ -402,7 +402,7 @@ export const AstroConfigSchema = z.object({ .or( z.object({ prefixDefaultLocale: z.boolean().optional().default(false), - redirectToDefaultLocale: z.boolean().optional().default(true), + redirectToDefaultLocale: z.boolean().optional().default(false),
packages/astro/src/core/config/schemas/base.ts
26
TypeScript
0.643
question
472
51
51
false
fix(i18n): incorrect validation
13,552
withastro/astro
47,179
TypeScript
delucis
ematipico
}); } if ( pathname && pathname.includes('*') && !(pathname.endsWith('/*') || pathname.endsWith('/**')) ) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'wildcards can only be placed at the end of a pathname', path: ['image', 'remotePatterns', i, 'pathname'], }); } } if...
Is the better advice not to remove the `redirectToDefaultLocale: true` rather than changing the prefix option? I’d imagine usually you don’t want to switch whether you’re prefixing or not but would not mind disabling the redirect? ```suggestion 'The option `i18n.routing.redirectToDefaultLocale` can be used only...
}); } if ( pathname && pathname.includes('*') && !(pathname.endsWith('/*') || pathname.endsWith('/**')) ) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'wildcards can only be placed at the end of a pathname', path: ['image', 'remotePatterns', i, 'pathname'], }); } } //...
@@ -45,13 +45,13 @@ export const AstroConfigRefinedSchema = z.custom<AstroConfig>().superRefine((con if ( config.i18n && typeof config.i18n.routing !== 'string' && - !config.i18n.routing.redirectToDefaultLocale && - !config.i18n.routing.prefixDefaultLocale + config.i18n.routing.prefixDefaultLocale === false ...
packages/astro/src/core/config/schemas/refined.ts
26
TypeScript
0.857
bug
523
51
51
false
fix(i18n): incorrect validation
13,552
withastro/astro
47,179
TypeScript
delucis
ematipico
return { url: fileURLToPath(resolveEntrypoint(root, url)), tech, }; }), })), fallbacks: family.fallbacks ? dedupe(family.fallbacks) : undefined, }; } const provider = family.provider === GOOGLE_PROVIDER_NAME || !family.provider ? google() : family.provider; return { ...family,...
nit: It's a bit inconsistent that we have a function `resolveProvider` that uses `resolveFontFamily`, but now we have this very function - `resolveFontFamily` - that uses `resolveEntrypoint` **directly**. Wouldn't it make more sense to have a function called `resolveVariantSources`, which uses `resolveEntrypoint` un...
generateNameWithHash, root, resolveMod, }: Omit<ResolveProviderOptions, 'provider'> & { family: FontFamily<BuiltInProvider | FontProvider>; generateNameWithHash: (family: FontFamily<any>) => string; }): Promise<ResolvedFontFamily> { const nameWithHash = generateNameWithHash(family); if (isLocalFontFamily(family...
@@ -251,7 +263,8 @@ export async function resolveFontFamily({ ...family, nameWithHash, provider: await resolveProvider({
packages/astro/src/assets/fonts/utils.ts
26
TypeScript
0.643
question
334
51
51
false
feat(fonts): update local to support entrypoints src and techs
13,556
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
resolveMod: (id) => import(id), base: new URL(CACHE_DIR, settings.config.cacheDir), }); } }, async configureServer(server) { await initialize({ resolveMod: (id) => server.ssrLoadModule(id), // In dev, we cache fonts data in .astro so it can be easily inspected and cleared base: new U...
The log mentions "a local font file", but then we suggest to delete it or restore it, however we don't mention **which file**, which is important to make the message actionable.
resolveMod: (id) => import(id), base: new URL(CACHE_DIR, settings.config.cacheDir), }); } }, async configureServer(server) { await initialize({ resolveMod: (id) => server.ssrLoadModule(id), // In dev, we cache fonts data in .astro so it can be easily inspected and cleared base: new U...
@@ -160,26 +158,29 @@ export function fontsPlugin({ settings, sync, logger }: Options): Plugin { } }, async configureServer(server) { - const moduleLoader = createViteLoader(server); await initialize({ - resolveMod: (id) => moduleLoader.import(id), + resolveMod: (id) => server.ssrLoadModule(id), ...
packages/astro/src/assets/fonts/vite-plugin-fonts.ts
26
TypeScript
0.357
suggestion
178
51
51
false
feat(fonts): improve local font files deletion
13,559
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
function adobe(config: Parameters<typeof providers.adobe>[0]) { return defineAstroFontProvider({ entrypoint: 'astro/assets/fonts/providers/adobe', config, }); } function bunny() { return defineAstroFontProvider({ entrypoint: 'astro/assets/fonts/providers/bunny', }); } function fontshare() { return defineAs...
nit: the TODO should explain what **we** have to do once the issue is solved.
function adobe(config: Parameters<typeof providers.adobe>[0]) { return defineAstroFontProvider({ entrypoint: 'astro/assets/fonts/providers/adobe', config, }); } function bunny() { return defineAstroFontProvider({ entrypoint: 'astro/assets/fonts/providers/bunny', }); } function fontshare() { return defineAs...
@@ -26,12 +26,22 @@ function fontsource() { }); } +// TODO: https://github.com/unjs/unifont/issues/108
packages/astro/src/assets/fonts/providers/index.ts
26
TypeScript
0.286
nitpick
77
48
48
false
feat(fonts): remove default provider
13,572
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
const hostId = crypto.randomUUID(); const slash = result.base.endsWith('/') ? '' : '/'; let serverIslandUrl = `${result.base}${slash}_server-islands/${componentId}${result.trailingSlash === 'always' ? '/' : ''}`; // Determine if its safe to use a GET request const potentialSearchParams = createSearchPa...
if this is only used for the test, it would be a shame to always have this in peoples builds. Can you test by getting the script contents and looking for some expected content?
const propsEncrypted = Object.keys(props).length === 0 ? '' : await encryptString(key, JSON.stringify(props)); const hostId = crypto.randomUUID(); const slash = result.base.endsWith('/') ? '' : '/'; let serverIslandUrl = `${result.base}${slash}_server-islands/${componentId}${result.trailingSlash === '...
@@ -105,8 +105,31 @@ export function renderServerIsland( ); } - destination.write(`<script async type="module" data-astro-rerun data-island-id="${hostId}"> -let script = document.querySelector('script[data-island-id="${hostId}"]'); + if(!result._metadata.hasServerIslandScript) { + result._metadata.has...
packages/astro/src/runtime/server/render/server-islands.ts
26
TypeScript
0.429
question
177
51
51
false
fix: extract shared logic for server island loading into a function and only include it once
13,576
withastro/astro
47,179
TypeScript
matthewp
ascorbic
configResolved(viteConfig) { resolvedConfig = viteConfig; }, async load(id, options) { if (assetRegex.test(id)) { if (!globalThis.astroAsset.referencedImages) globalThis.astroAsset.referencedImages = new Set(); if (id !== removeQueryString(id)) { // If our import has any query pa...
**todo(blocking):** We need to fix the memory leak issue before merging
return null; } }, }, // Return a more advanced shape for images imported in ESM { name: 'astro:assets:esm', enforce: 'pre', config(_, env) { shouldEmitFile = env.command === 'build'; }, configResolved(viteConfig) { resolvedConfig = viteConfig; }, async load(id, options) { ...
@@ -211,7 +211,8 @@ export default function assets({ settings }: { settings: AstroSettings }): vite. const imageMetadata = await emitESMImage( id, this.meta.watchMode, - !!settings.config.experimental.svg, + // TODO: Fix memory issue + id.endsWith('.svg'), //!!settings.config.experime...
packages/astro/src/assets/vite-plugin-assets.ts
26
TypeScript
0.357
performance
71
51
51
false
feat: unflag svg component feature
13,578
withastro/astro
47,179
TypeScript
stramel
stramel
define: { 'process.env.NODE_ENV': '"development"' }, }), dev: true, } : undefined, ].filter((entry) => entry), ); for (const result of results) { const code = result.build.outputFiles[0].text.trim(); const rootURL = new URL('../../', import.meta.url); const rel = path.r...
Should this use `generatedCode` instead of `code`?
? { build: await esbuild.build({ ...esbuildOptions, define: { 'process.env.NODE_ENV': '"development"' }, }), dev: true, } : undefined, ].filter((entry) => entry), ); for (const result of results) { const code = result.build.outputFiles[0].text.trim(); c...
@@ -99,17 +102,31 @@ export default async function prebuild(...args) { const code = result.build.outputFiles[0].text.trim(); const rootURL = new URL('../../', import.meta.url); const rel = path.relative(fileURLToPath(rootURL), filepath); + const generatedCode = escapeTemplateLiterals(code); const mod ...
scripts/cmd/prebuild.js
26
JavaScript
0.429
question
50
27
44
false
chore: build hashes of scripts
13,590
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
* A [font display](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display). */ display: z.enum(['auto', 'block', 'swap', 'fallback', 'optional']).optional(), /** * A [unicode range](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range). */ unicodeRange: z.array(z.string...
Is "left to right" the way we refer to organizing elements in an array? (Some languages are RTL, for example). Do we more use "beginning/end"? Thinking of a way to say something like: > Fallback fonts will be chosen in the order listed. The first available font will be used.
* A [font display](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display). */ display: z.enum(['auto', 'block', 'swap', 'fallback', 'optional']).optional(), /** * A [unicode range](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/unicode-range). */ unicodeRange: z.array(z.string...
@@ -1,36 +1,95 @@ import { z } from 'zod'; import { LOCAL_PROVIDER_NAME } from './constants.js'; -// TODO: jsdoc for everything, most of those end up in the public AstroConfig type - const weightSchema = z.union([z.string(), z.number()]); const styleSchema = z.enum(['normal', 'italic', 'oblique']); const famil...
packages/astro/src/assets/fonts/config.ts
26
TypeScript
0.5
suggestion
281
51
51
false
feat(fonts): jsdocs
13,600
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
unicodeRange: z.array(z.string()).nonempty().optional(), /** * A [font stretch](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-stretch). */ stretch: z.string().optional(), /** * Font [feature settings](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-feature-settings). */ ...
```suggestion * To disable fallback fonts completely, configure an empty array: ``` Do we need any kind of warning after the code blog about the effects of doing this? Is it possible that someone will get NO fonts when they visit a page, or does it just mean that WE won't choose the what font the visitor sees, and...
unicodeRange: z.array(z.string()).nonempty().optional(), /** * A [font stretch](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-stretch). */ stretch: z.string().optional(), /** * Font [feature settings](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-feature-settings). */ ...
@@ -1,36 +1,95 @@ import { z } from 'zod'; import { LOCAL_PROVIDER_NAME } from './constants.js'; -// TODO: jsdoc for everything, most of those end up in the public AstroConfig type - const weightSchema = z.union([z.string(), z.number()]); const styleSchema = z.enum(['normal', 'italic', 'oblique']); const famil...
packages/astro/src/assets/fonts/config.ts
26
TypeScript
0.786
question
343
51
51
false
feat(fonts): jsdocs
13,600
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
* Font [feature settings](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-feature-settings). */ featureSettings: z.string().optional(), /** * Font [variation settings](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-variation-settings). */ variationSettings: z.string().optio...
Maybe this belongs in the section about optimizedFallBacks, since it's only valid when its true?
* Font [feature settings](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-feature-settings). */ featureSettings: z.string().optional(), /** * Font [variation settings](https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-variation-settings). */ variationSettings: z.string().optio...
@@ -1,36 +1,95 @@ import { z } from 'zod'; import { LOCAL_PROVIDER_NAME } from './constants.js'; -// TODO: jsdoc for everything, most of those end up in the public AstroConfig type - const weightSchema = z.union([z.string(), z.number()]); const styleSchema = z.enum(['normal', 'italic', 'oblique']); const famil...
packages/astro/src/assets/fonts/config.ts
26
TypeScript
0.214
performance
96
51
51
false
feat(fonts): jsdocs
13,600
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
variationSettings: z.string().optional(), }); const fallbacksSchema = z.object({ /** * @default `["sans-serif"]` * * An array of fonts to use when your chosen font is unavailable, or loading. Fallbacks are applied from left to right: * * ```js * fallbacks: ["CustomFont", "serif"] * ``` * * If you d...
It's true by default, though right? So it *is* enabled, but we're saying it "should only be needed when.." Did you mean to say, *dis*abling this should only be needed? Did you mean? ```suggestion * Whether or not to enable optimized fallback generation. You may disable this default optimization to provide `fal...
variationSettings: z.string().optional(), }); const fallbacksSchema = z.object({ /** * @default `["sans-serif"]` * * An array of fonts to use when your chosen font is unavailable, or loading. Fallback fonts will be chosen in the order listed. The first available font will be used: * * ```js * fallbacks: ...
@@ -1,36 +1,95 @@ import { z } from 'zod'; import { LOCAL_PROVIDER_NAME } from './constants.js'; -// TODO: jsdoc for everything, most of those end up in the public AstroConfig type - const weightSchema = z.union([z.string(), z.number()]); const styleSchema = z.enum(['normal', 'italic', 'oblique']); const famil...
packages/astro/src/assets/fonts/config.ts
26
TypeScript
0.857
performance
523
51
51
false
feat(fonts): jsdocs
13,600
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
* ``` * * If you don't want any fallbacks, use an empty array: * * ```js * fallbacks: [] * ``` * * If `optimizedFallbacks` is set to `true`, we look for the last fallback and check if it's a [generic family name](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family#generic-name). If so, we try...
```suggestion * A valid [ident](https://developer.mozilla.org/en-US/docs/Web/CSS/ident) in the form of a CSS variable (i.e. starting with `--`). ``` I don't know if special formatting for any of those characters is required, but here's where I think it's helpful to explicitly say "start with two dashes"
* ``` * * To disable fallback fonts completely, configure an empty array: * * ```js * fallbacks: [] * ``` * * If the last font in the `fallbacks` array is a [generic family name](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family#generic-name), an [optimized fallback](https://developer.chro...
@@ -1,36 +1,95 @@ import { z } from 'zod'; import { LOCAL_PROVIDER_NAME } from './constants.js'; -// TODO: jsdoc for everything, most of those end up in the public AstroConfig type - const weightSchema = z.union([z.string(), z.number()]); const styleSchema = z.enum(['normal', 'italic', 'oblique']); const famil...
packages/astro/src/assets/fonts/config.ts
26
TypeScript
0.786
suggestion
309
51
51
false
feat(fonts): jsdocs
13,600
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
* * ```js * fallbacks: [] * ``` * * If `optimizedFallbacks` is set to `true`, we look for the last fallback and check if it's a [generic family name](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family#generic-name). If so, we try to generate an [optimized fallback](https://developer.chrome.com/blo...
Just checking, was this recently renamed to `family` to match the component attribute or was that something else?
* * ```js * fallbacks: [] * ``` * * If the last font in the `fallbacks` array is a [generic family name](https://developer.mozilla.org/en-US/docs/Web/CSS/font-family#generic-name), an [optimized fallback](https://developer.chrome.com/blog/font-fallbacks) using font metrics will be generated. To disable thi...
@@ -1,36 +1,95 @@ import { z } from 'zod'; import { LOCAL_PROVIDER_NAME } from './constants.js'; -// TODO: jsdoc for everything, most of those end up in the public AstroConfig type - const weightSchema = z.union([z.string(), z.number()]); const styleSchema = z.enum(['normal', 'italic', 'oblique']); const famil...
packages/astro/src/assets/fonts/config.ts
26
TypeScript
0.571
question
113
51
51
false
feat(fonts): jsdocs
13,600
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
* --- * import Logo from './path/to/svg/file.svg'; * --- * * <Logo size={24} /> * ``` * * For a complete overview, and to give feedback on this experimental API, * see the [Feature RFC](https://github.com/withastro/roadmap/pull/1035). */ svg?: boolean; /** * * @name experimental...
```suggestion * Web fonts can impact page performance at both load time and rendering time. This feature provides * automatic [optimization](https://web.dev/learn/performance/optimize-web-fonts) by creating * preload links and optimized fallbacks. This API includes opinionated defaults to keep your sites li...
* --- * import Logo from './path/to/svg/file.svg'; * --- * * <Logo size={24} /> * ``` * * For a complete overview, and to give feedback on this experimental API, * see the [Feature RFC](https://github.com/withastro/roadmap/pull/1035). */ svg?: boolean; /** * * @name experimental...
@@ -2128,11 +2128,19 @@ export interface ViteUserConfig extends OriginalViteUserConfig { * * @name experimental.fonts * @type {FontFamily[]} - * @default `undefined` - * @version 5.x + * @version 5.7 * @description * - * TODO: + * This experimental feature allows you to use fonts from your...
packages/astro/src/types/public/config.ts
26
TypeScript
0.929
performance
495
51
51
false
feat(fonts): jsdocs
13,600
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
}); }); }); describe('output: "static"', () => { describe('build', () => { before(async () => { process.env.STATIC_MODE = true; fixture = await loadFixture({ root: './fixtures/redirects/', output: 'static', redirects: { '/old': '/test', '/': '/test', '/one': '/test'...
The relative redirect is **the destination**, the value :)
}); }); }); describe('output: "static"', () => { describe('build', () => { before(async () => { process.env.STATIC_MODE = true; fixture = await loadFixture({ root: './fixtures/redirects/', output: 'static', redirects: { '/old': '/test', '/': '/test', '/one': '/test'...
@@ -131,6 +131,7 @@ describe('Astro.redirect', () => { '/more/old/[dynamic]/[route]': '/more/[dynamic]/[route]', '/more/old/[...spread]': '/more/new/[...spread]', '/external/redirect': 'https://example.com/', + '../dist/relative/redirect': '/test',
packages/astro/test/redirects.test.js
26
JavaScript
0.214
suggestion
59
51
51
false
Fix relative redirects regression. Closes #13607
13,616
withastro/astro
47,179
TypeScript
ematipico
lfilho
}); it('supports redirecting to an external destination', async () => { const html = await fixture.readFile('/external/redirect/index.html'); assert.equal(html.includes('http-equiv="refresh'), true); assert.equal(html.includes('url=https://example.com/'), true); }); it('supports redirecting to...
Same here, we're fixing a case where a user specifies `'test'` and it should work
}); it('supports redirecting to an external destination', async () => { const html = await fixture.readFile('/external/redirect/index.html'); assert.equal(html.includes('http-equiv="refresh'), true); assert.equal(html.includes('url=https://example.com/'), true); }); it('supports redirecting to...
@@ -226,6 +233,7 @@ describe('Astro.redirect', () => { output: 'static', redirects: { '/one': '/', + '../dist/relative/redirect': '/test',
packages/astro/test/redirects.test.js
26
JavaScript
0.429
suggestion
81
51
51
false
Fix relative redirects regression. Closes #13607
13,616
withastro/astro
47,179
TypeScript
ematipico
lfilho
import type { FontFamily, FontType, LocalFontFamily, ResolvedFontFamily, ResolvedLocalFontFamily, } from './types.js'; export function toCSS(properties: Record<string, string | undefined>, indent = 2) { return Object.entries(properties) .filter(([, value]) => Boolean(value)) .map(([key, value]) => `${' '.rep...
```suggestion 'font-weight': Array.isArray(font.weight) ? font.weight.map(s => s.trim()).join(' ') : font.weight?.toString(), ``` nit: we might want to clean the string
import type { FontFamily, FontType, LocalFontFamily, ResolvedFontFamily, ResolvedLocalFontFamily, } from './types.js'; export function toCSS(properties: Record<string, string | undefined>, indent = 2) { return Object.entries(properties) .filter(([, value]) => Boolean(value)) .map(([key, value]) => `${' '.rep...
@@ -15,26 +15,31 @@ import type { ResolvedLocalFontFamily, } from './types.js'; -// Source: https://github.com/nuxt/fonts/blob/main/src/css/render.ts#L7-L21 -export function generateFontFace(family: string, font: unifont.FontFaceData) { - return [ - '@font-face {', - ` font-family: ${family};`, - ` src: ${ren...
packages/astro/src/assets/fonts/utils.ts
26
TypeScript
0.714
suggestion
175
51
51
false
feat(fonts): fallback improvements
13,632
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
import { createRequire } from 'node:module'; import { extname } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import type * as unifont from 'unifont'; import type { Storage } from 'unstorage'; import { AstroError, AstroErrorData } from '../../core/errors/index.js'; import { DEFAULT_FALLBACK...
```suggestion return `@font-face {\n\t${toCSS(properties)}\n}\n`; ``` Some indentation :)
import { createRequire } from 'node:module'; import { extname } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import type * as unifont from 'unifont'; import type { Storage } from 'unstorage'; import { AstroError, AstroErrorData } from '../../core/errors/index.js'; import { DEFAULT_FALLBACK...
@@ -15,26 +15,31 @@ import type { ResolvedLocalFontFamily, } from './types.js'; -// Source: https://github.com/nuxt/fonts/blob/main/src/css/render.ts#L7-L21 -export function generateFontFace(family: string, font: unifont.FontFaceData) { - return [ - '@font-face {', - ` font-family: ${family};`, - ` src: ${ren...
packages/astro/src/assets/fonts/utils.ts
26
TypeScript
0.571
suggestion
94
51
51
false
feat(fonts): fallback improvements
13,632
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
storage, }); for (const family of families) { const preloadData: PreloadData = []; let css = ''; const fallbacks = family.fallbacks ?? DEFAULTS.fallbacks; const fallbackFontData: Array<GetMetricsForFamilyFont> = []; // When going through the urls/filepaths returned by providers, // We save the hash an...
Must check that the same data is not present already
storage, }); for (const family of families) { const preloadData: PreloadData = []; let css = ''; const fallbacks = family.fallbacks ?? DEFAULTS.fallbacks; const fallbackFontData: Array<GetMetricsForFamilyFont> = []; // When going through the urls/filepaths returned by providers, // We save the hash an...
@@ -62,11 +67,12 @@ export async function loadFonts({ // If a family has fallbacks, we store the first url we get that may // be used for the fallback generation, if capsize doesn't have this // family in its built-in collection - if (family.fallbacks && family.fallbacks.length > 0) { - fallbackFontDat...
packages/astro/src/assets/fonts/load.ts
26
TypeScript
0.214
suggestion
52
51
51
false
feat(fonts): generate fallbacks for all faces
13,635
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
// When going through the urls/filepaths returned by providers, // We save the hash and the associated original value so we can use // it in the vite middleware during development const collect: ( parameters: Parameters<ProxyURLOptions['collect']>[0] & { data: Partial<unifont.FontFaceData>; }, col...
```suggestion !fallbackFontData.some((f) => JSON.stringify(f.data) === JSON.stringify(data)) ```
// When going through the urls/filepaths returned by providers, // We save the hash and the associated original value so we can use // it in the vite middleware during development const collect: ( parameters: Parameters<ProxyURLOptions['collect']>[0] & { data: Partial<unifont.FontFaceData>; }, col...
@@ -67,11 +70,18 @@ export async function loadFonts({ // If a family has fallbacks, we store the first url we get that may // be used for the fallback generation, if capsize doesn't have this // family in its built-in collection - if (family.fallbacks && family.fallbacks.length > 0) { - fallbackFontDat...
packages/astro/src/assets/fonts/load.ts
26
TypeScript
0.714
suggestion
102
51
51
false
feat(fonts): generate fallbacks for all faces
13,635
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
for (const family of families) { const preloadData: PreloadData = []; let css = ''; const fallbacks = family.fallbacks ?? DEFAULTS.fallbacks; const fallbackFontData: Array<GetMetricsForFamilyFont> = []; // When going through the urls/filepaths returned by providers, // We save the hash and the associated...
The condition changed, is the comment still applicable?
for (const family of families) { const preloadData: PreloadData = []; let css = ''; const fallbacks = family.fallbacks ?? DEFAULTS.fallbacks; const fallbackFontData: Array<GetMetricsForFamilyFont> = []; // When going through the urls/filepaths returned by providers, // We save the hash and the associated...
@@ -67,11 +70,18 @@ export async function loadFonts({ // If a family has fallbacks, we store the first url we get that may // be used for the fallback generation, if capsize doesn't have this // family in its built-in collection
packages/astro/src/assets/fonts/load.ts
26
TypeScript
0.286
question
55
51
51
false
feat(fonts): generate fallbacks for all faces
13,635
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
families, hashString, }: { families: Array<ResolvedFontFamily>; hashString: (value: string) => string; }): { families: Array<ResolvedFontFamily>; providers: Array<unifont.Provider> } { const hashes = new Set<string>(); const providers: Array<unifont.Provider> = []; for (const { provider } of families) { if (p...
I'm a bit confused here. Isn't the logic here unchanged? If the hash isn't in the hashes set, add the hash to the set and push the provider into the list?
families, hashString, }: { families: Array<ResolvedFontFamily>; hashString: (value: string) => string; }): { families: Array<ResolvedFontFamily>; providers: Array<unifont.Provider> } { const hashes = new Set<string>(); const providers: Array<unifont.Provider> = []; for (const { provider } of families) { if (p...
@@ -333,9 +333,6 @@ export function familiesToUnifontProviders({ }), ), ); - if (hashes.has(hash)) { - continue; - }
packages/astro/src/assets/fonts/utils.ts
26
TypeScript
0.429
question
154
51
51
false
fix(fonts): providers deduplication logic
13,639
withastro/astro
47,179
TypeScript
ascorbic
florian-lefebvre
import { z } from 'zod'; import { LOCAL_PROVIDER_NAME } from './constants.js'; const weightSchema = z.union([z.string(), z.number()]); export const styleSchema = z.enum(['normal', 'italic', 'oblique']); const unicodeRangeSchema = z.array(z.string()); const familyPropertiesSchema = z.object({ /** * A [font weight](...
Would this make sense to keep this schema as nonempty? Does an empty range make sense?
import { z } from 'zod'; import { LOCAL_PROVIDER_NAME } from './constants.js'; const weightSchema = z.union([z.string(), z.number()]); export const styleSchema = z.enum(['normal', 'italic', 'oblique']); const unicodeRangeSchema = z.array(z.string()).nonempty(); const familyPropertiesSchema = z.object({ /** * A [fo...
@@ -2,7 +2,8 @@ import { z } from 'zod'; import { LOCAL_PROVIDER_NAME } from './constants.js'; const weightSchema = z.union([z.string(), z.number()]); -const styleSchema = z.enum(['normal', 'italic', 'oblique']); +export const styleSchema = z.enum(['normal', 'italic', 'oblique']); +const unicodeRangeSchema = z.arra...
packages/astro/src/assets/fonts/config.ts
6
TypeScript
0.214
question
86
31
31
false
feat(fonts): local provider infer
13,640
withastro/astro
47,179
TypeScript
ascorbic
florian-lefebvre
/** * @docs * @description * Cannot extract the font type from the given URL. * @message * An error occured while trying to extract the font type from the given URL. */ export const CannotExtractFontType = { name: 'CannotExtractFontType', title: 'Cannot extract the font type from the given URL.', message: (url...
Rather than talking abotu disabling inference I'd just say to set it manually, because that's how you disable inference.
/** * @docs * @description * Cannot extract the font type from the given URL. * @message * An error occured while trying to extract the font type from the given URL. */ export const CannotExtractFontType = { name: 'CannotExtractFontType', title: 'Cannot extract the font type from the given URL.', message: (url...
@@ -1309,6 +1309,20 @@ export const CannotExtractFontType = { hint: 'Open an issue at https://github.com/withastro/astro/issues.', } satisfies ErrorData; +/** + * @docs + * @description + * Cannot extract the font data from the given URL. + * @message + * An error occured while trying to extract the font data from...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.429
suggestion
120
51
51
false
feat(fonts): local provider infer
13,640
withastro/astro
47,179
TypeScript
ascorbic
florian-lefebvre
* An unknown error occurred while reading or writing files to disk. It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. */ export const UnknownFilesystemError = { name: 'UnknownFilesystemError', title: 'An unknown error occurred while reading or writing files to disk....
Just noting that "font data" sounds a little vague compared to the hint about setting weight and style being the fix. (Data could be anything!) And, always thinking about being specific enough in case there's a different situation that is also, generically, about not being able to "extract data" or "read" a file but yo...
* An unknown error occurred while reading or writing files to disk. It can be caused by many things, eg. missing permissions or a file not existing we attempt to read. */ export const UnknownFilesystemError = { name: 'UnknownFilesystemError', title: 'An unknown error occurred while reading or writing files to disk....
@@ -1309,6 +1309,20 @@ export const CannotExtractFontType = { hint: 'Open an issue at https://github.com/withastro/astro/issues.', } satisfies ErrorData; +/** + * @docs + * @description + * Cannot extract the font data from the given URL.
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.643
refactor
879
51
51
false
feat(fonts): local provider infer
13,640
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
family, urlProxy, fontTypeExtractor, fontFileReader, }: Options): { fonts: Array<unifont.FontFaceData>; } { return { fonts: family.variants.map((variant) => { const infer = variant.weight === undefined || variant.style === undefined; // We prepare the data const data: unifont.FontFaceData = { // I...
You might want to expand the comment and explain why. This is business logic :)
family, urlProxy, fontTypeExtractor, fontFileReader, }: Options): { fonts: Array<unifont.FontFaceData>; } { return { fonts: family.variants.map((variant) => { const shouldInfer = variant.weight === undefined || variant.style === undefined; // We prepare the data const data: unifont.FontFaceData = { ...
@@ -1,43 +1,66 @@ import type * as unifont from 'unifont'; import { FONT_FORMAT_MAP } from '../constants.js'; -import type { FontTypeExtractor, UrlProxy } from '../definitions.js'; +import type { FontFileReader, FontTypeExtractor, UrlProxy } from '../definitions.js'; import type { ResolvedLocalFontFamily } from '../...
packages/astro/src/assets/fonts/providers/local.ts
26
TypeScript
0.214
suggestion
80
51
51
false
feat(fonts): local provider infer
13,640
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
.map((source) => 'name' in source ? source : { ...source, originalURL: source.url, url: proxyURL({ value: source.url, // We only use the url for hashing since the service returns urls with a hash already hashString, c...
nit: for readability, I would put this code before the return, and maybe use a for loop instead
// The index keeps track of encountered URLs. We can't use the index on font.src.map // below because it may contain sources without urls, which would prevent preloading completely let index = 0; return { ...font, src: font.src.map((source) => { if ('name' in source) { ret...
@@ -117,27 +122,33 @@ export async function loadFonts({ typeof font.meta?.priority === 'number' ? font.meta.priority === 0 : true, ) // Collect URLs - .map((font) => ({ - ...font, - src: font.src - // Limit src to 1 file (eg. if woff2 and woff are present, will only take woff2) to avoid ...
packages/astro/src/assets/fonts/load.ts
26
TypeScript
0.286
suggestion
96
51
51
false
fix(fonts): do not filter sources
13,646
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
}; type ImgAttributes = import('./dist/type-utils.js').WithRequired< Omit<import('./types').HTMLAttributes<'img'>, 'src' | 'width' | 'height'>, 'alt' >; export type LocalImageProps = import('./dist/type-utils.js').Simplify< import('./dist/assets/types.js').LocalImageProps<ImgAttributes> >; export type Rem...
Otherwise the type would be global, which is confusing IMO. Check my next suggestion ```suggestion ```
type ImgAttributes = import('./dist/type-utils.js').WithRequired< Omit<import('./types').HTMLAttributes<'img'>, 'src' | 'width' | 'height'>, 'alt' >; export type LocalImageProps = import('./dist/type-utils.js').Simplify< import('./dist/assets/types.js').LocalImageProps<ImgAttributes> >; export type RemoteIm...
@@ -81,6 +81,7 @@ declare module 'astro:assets' { } type ImageMetadata = import('./dist/assets/types.js').ImageMetadata; +type SvgComponent = import('./dist/assets/types.js').SvgComponent;
packages/astro/client.d.ts
26
TypeScript
0.857
suggestion
104
51
51
false
feat(types): add SvgComponent type and update SVG module declaration
13,651
withastro/astro
47,179
TypeScript
florian-lefebvre
ADTC
declare module '*.jpeg' { const metadata: ImageMetadata; export default metadata; } declare module '*.jpg' { const metadata: ImageMetadata; export default metadata; } declare module '*.png' { const metadata: ImageMetadata; export default metadata; } declare module '*.tiff' { const metadata: ImageMetadata; expor...
Here the type is scoped so it doesn't leak. Also I think we should move the ImageMetadata usage here: ```suggestion type SvgComponent = import('./dist/assets/types.js').SvgComponent; const Component: SvgComponent & ImageMetadata; ```
} declare module '*.jpg' { const metadata: ImageMetadata; export default metadata; } declare module '*.png' { const metadata: ImageMetadata; export default metadata; } declare module '*.tiff' { const metadata: ImageMetadata; export default metadata; } declare module '*.webp' { const metadata: ImageMetadata; exp...
@@ -111,9 +112,7 @@ declare module '*.avif' { export default metadata; } declare module '*.svg' { - type Props = astroHTML.JSX.SVGAttributes; - - const Component: ((_props: Props) => any) & ImageMetadata; + const Component: SvgComponent;
packages/astro/client.d.ts
26
TypeScript
1
suggestion
242
51
51
false
feat(types): add SvgComponent type and update SVG module declaration
13,651
withastro/astro
47,179
TypeScript
florian-lefebvre
ADTC
src: string; /** * When inferSize is true width and height are not required */ inferSize: true; }) | (WithRequired<ImageSharedProps<T>, 'width' | 'height'> & { /** * URL of a remote image. Can start with a protocol (ex: `https://`) or alternatively `/`, or `Astro.url`, for images in the `pub...
```suggestion export type SvgComponent = ((props: astroHTML.JSX.SVGAttributes;) => any); ```
import type { OmitPreservingIndexSignature, Simplify, WithRequired } from '../type-utils.js'; import type { VALID_INPUT_FORMATS, VALID_OUTPUT_FORMATS } from './consts.js'; import type { ImageService } from './services/service.js'; export type ImageQualityPreset = 'low' | 'mid' | 'high' | 'max' | (string & {}); export ...
@@ -284,3 +285,6 @@ export type RemoteImageProps<T> = */ inferSize?: false | undefined; }); + +type SvgProps = astroHTML.JSX.SVGAttributes; +export type SvgComponent = ((props: SvgProps) => any) & ImageMetadata;
packages/astro/src/assets/types.ts
26
TypeScript
0.714
suggestion
94
27
287
false
feat(types): add SvgComponent type and update SVG module declaration
13,651
withastro/astro
47,179
TypeScript
florian-lefebvre
ADTC
import type * as astroHTML from 'astro/jsx-runtime'; import type { OmitPreservingIndexSignature, Simplify, WithRequired } from '../type-utils.js'; import type { VALID_INPUT_FORMATS, VALID_OUTPUT_FORMATS } from './consts.js'; import type { ImageService } from './services/service.js'; export type ImageQualityPreset = 'l...
@Princesseuh do you think this import could have weird TS implications? IIRC its always a bit tricky to import this one (at least in userland)
import type { OmitPreservingIndexSignature, Simplify, WithRequired } from '../type-utils.js'; import type { VALID_INPUT_FORMATS, VALID_OUTPUT_FORMATS } from './consts.js'; import type { ImageService } from './services/service.js'; export type ImageQualityPreset = 'low' | 'mid' | 'high' | 'max' | (string & {}); export ...
@@ -1,3 +1,4 @@ +import type * as astroHTML from 'astro/jsx-runtime';
packages/astro/src/assets/types.ts
1
TypeScript
0.429
suggestion
142
26
26
false
feat(types): add SvgComponent type and update SVG module declaration
13,651
withastro/astro
47,179
TypeScript
florian-lefebvre
ADTC
import type { SSRResult } from 'astro'; export type RendererContext = { result: SSRResult; };
Please add a new line at the end of the file
import type { SSRResult } from 'astro'; export type RendererContext = { result: SSRResult; };
@@ -0,0 +1,4 @@ +import type { SSRResult } from 'astro'; +export type RendererContext = { + result: SSRResult; +};
packages/integrations/react/src/types.ts
4
TypeScript
0.071
suggestion
45
4
5
false
feat: convert integrations to TS
13,663
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
const isHydrate = client !== 'only'; const bootstrap = isHydrate ? createSSRApp : createApp; // keep a reference to the app, props and slots so we can update a running instance later let appInstance = appMap.get(element); if (!appInstance) { appInstance = { props, slots, }; const app = boot...
This seems to change some logic, doesn't it? Is it a bug fix?
const isHydrate = client !== 'only'; const bootstrap = isHydrate ? createSSRApp : createApp; // keep a reference to the app, props and slots so we can update a running instance later let appInstance = appMap.get(element); if (!appInstance) { appInstance = { props, slots, }; const app = boot...
@@ -40,7 +48,7 @@ export default (element) => return content; }, }); - app.config.idPrefix = element.getAttribute('prefix'); + app.config.idPrefix = element.getAttribute('prefix') ?? undefined;
packages/integrations/vue/src/client.ts
26
TypeScript
0.429
bug
61
41
42
false
feat: convert integrations to TS
13,663
withastro/astro
47,179
TypeScript
ematipico
florian-lefebvre
// NOTE: if you change the value inside the style tag, you must update `prebuild.js` too export const ISLAND_STYLES = `<style>astro-island,astro-slot,astro-static-slot{display:contents}</style>`;
Could the script be updated to read the styles from here instead?
export const ISLAND_STYLES = '<style>astro-island,astro-slot,astro-static-slot{display:contents}</style>';
@@ -0,0 +1,2 @@ +// NOTE: if you change the value inside the style tag, you must update `prebuild.js` too
packages/astro/src/runtime/server/astro-island-styles.ts
1
TypeScript
0.286
question
65
3
3
false
feat(csp): create hashes of tracked scripts and hashes
13,675
withastro/astro
47,179
TypeScript
florian-lefebvre
ematipico
const root = settings.config.root; const pathsToWarn = new Set<string>(); for (const family of settings.config.experimental.fonts!) { families.push( await resolveFontFamily({ family, root, resolveMod, generateNameWithHash: (_family) => `${withoutQuotes(_family.name)}-${h64ToStrin...
This might be helpful if it suggests something people might want to *do*? maybe something like: > Found a local font file `${JSON.stringify(path)}` in the `public/` folder. To avoid duplicated files in the build output, move this file into `src/`.
const root = settings.config.root; const pathsToWarn = new Set<string>(); for (const family of settings.config.experimental.fonts!) { families.push( await resolveFontFamily({ family, root, resolveMod, generateNameWithHash: (_family) => `${withoutQuotes(_family.name)}-${h64ToStrin...
@@ -118,18 +119,35 @@ export function fontsPlugin({ settings, sync, logger }: Options): Plugin { const families: Array<ResolvedFontFamily> = []; + const root = settings.config.root; + const pathsToWarn = new Set<string>(); + for (const family of settings.config.experimental.fonts!) { families.push( ...
packages/astro/src/assets/fonts/vite-plugin-fonts.ts
26
TypeScript
0.643
refactor
253
51
51
false
feat(fonts): warn if local font is in public dir
13,678
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
const root = settings.config.root; const pathsToWarn = new Set<string>(); for (const family of settings.config.experimental.fonts!) { families.push( await resolveFontFamily({ family, root, resolveMod, generateNameWithHash: (_family) => `${withoutQuotes(_family.name)}-${h64ToStri...
```suggestion // TODO: remove when stabilizing logger.warn( ```
const root = settings.config.root; const pathsToWarn = new Set<string>(); for (const family of settings.config.experimental.fonts!) { families.push( await resolveFontFamily({ family, root, resolveMod, generateNameWithHash: (_family) => `${withoutQuotes(_family.name)}-${h64ToStri...
@@ -118,18 +119,35 @@ export function fontsPlugin({ settings, sync, logger }: Options): Plugin { const families: Array<ResolvedFontFamily> = []; + const root = settings.config.root; + const pathsToWarn = new Set<string>(); + for (const family of settings.config.experimental.fonts!) { families.push( ...
packages/astro/src/assets/fonts/vite-plugin-fonts.ts
26
TypeScript
0.643
suggestion
72
51
51
false
feat(fonts): warn if local font is in public dir
13,678
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
import type { AstroConfig, ImageMetadata, ImageQualityPreset, ImageTransform } from 'astro'; export function getDefaultImageConfig(astroImageConfig: AstroConfig['image']): VercelImageConfig { return { sizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840], domains: astroImageConfig.domains ?? [], // Cast is neces...
This should be removed in favor of `isESMImportedImage` exported from `astro/assets/utils`
import type { AstroConfig, ImageQualityPreset, ImageTransform } from 'astro'; import { isESMImportedImage } from 'astro/assets/utils'; export function getDefaultImageConfig(astroImageConfig: AstroConfig['image']): VercelImageConfig { return { sizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840], domains: astroIma...
@@ -10,7 +10,7 @@ export function getDefaultImageConfig(astroImageConfig: AstroConfig['image']): V } export function isESMImportedImage(src: ImageMetadata | string): src is ImageMetadata {
packages/integrations/vercel/src/image/shared.ts
12
TypeScript
0.429
suggestion
90
37
37
false
fix(vercel): handle SVG images correctly in build image service
13,679
withastro/astro
47,179
TypeScript
florian-lefebvre
moonclavedev
hint: 'Check the pattern for typos.', } satisfies ErrorData; /** * @docs * @see * - [Astro.redirect](https://docs.astro.build/en/reference/api-reference/#redirect) * @description * A redirect must be given a location with the `Location` header. */ export const RedirectWithNoLocation = { name: 'RedirectWithNoLoc...
I decided to move it to the hint so we can use a dynamic message, but this is still the value of the `@description` in jsdocs above
hint: 'Check the pattern for typos.', } satisfies ErrorData; /** * @docs * @see * - [Astro.redirect](https://docs.astro.build/en/reference/api-reference/#redirect) * @description * A redirect must be given a location with the `Location` header. */ export const RedirectWithNoLocation = { name: 'RedirectWithNoLoc...
@@ -976,7 +976,8 @@ export const RedirectWithNoLocation = { export const UnsupportedExternalRedirect = { name: 'UnsupportedExternalRedirect', title: 'Unsupported or malformed URL.', - message: 'An external redirect must start with http or https, and must be a valid URL.', + message: (from: string, to: string) => `...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.571
suggestion
131
51
51
false
fix: improve external redirects message
13,680
withastro/astro
47,179
TypeScript
florian-lefebvre
florian-lefebvre
message: (globStr: string) => `\`Astro.glob(${globStr})\` did not return any matching files.`, hint: 'Check the pattern for typos.', } satisfies ErrorData; /** * @docs * @see * - [Astro.redirect](https://docs.astro.build/en/reference/api-reference/#redirect) * @description * A redirect must be given a location w...
Here are some ideas for you! See if you like anything here! My motivation is: people don't like being told their stuff is "invalid" if it's just malformed for our system 😄 ```suggestion message: (from: string, to: string) => `The external redirect from "${from}" to "${to}" cannot be processed because the dest...
message: (globStr: string) => `\`Astro.glob(${globStr})\` did not return any matching files.`, hint: 'Check the pattern for typos.', } satisfies ErrorData; /** * @docs * @see * - [Astro.redirect](https://docs.astro.build/en/reference/api-reference/#redirect) * @description * A redirect must be given a location w...
@@ -976,7 +976,8 @@ export const RedirectWithNoLocation = { export const UnsupportedExternalRedirect = { name: 'UnsupportedExternalRedirect', title: 'Unsupported or malformed URL.', - message: 'An external redirect must start with http or https, and must be a valid URL.', + message: (from: string, to: string) => `...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
1
suggestion
1,045
51
51
false
fix: improve external redirects message
13,680
withastro/astro
47,179
TypeScript
sarah11918
florian-lefebvre
function searchConfig( fs: typeof fsMod, srcDir: URL, legacy?: boolean, ): { exists: boolean; url: URL } { const paths = [ ...(legacy ? [] : ['content.config.mjs', 'content.config.js', 'content.config.mts', 'content.config.ts']), 'content/config.mjs', 'content/config.js', 'content/config.mts', 'cont...
Some feedback: - `content.config` disappears at the end of he build, but what about the `live.config` file? This isn't clear from the PR and the RFC. - nit: not very fond of the `live-content` name, because it could be `liveContent` too. Maybe `live.config.*` works better
function searchConfig( fs: typeof fsMod, srcDir: URL, legacy?: boolean, ): { exists: boolean; url: URL } { const paths = [ ...(legacy ? [] : ['content.config.mjs', 'content.config.js', 'content.config.mts', 'content.config.ts']), 'content/config.mjs', 'content/config.js', 'content/config.mts', 'cont...
@@ -730,13 +757,28 @@ function search(fs: typeof fsMod, srcDir: URL, legacy?: boolean) { 'content/config.js', 'content/config.mts', 'content/config.ts', - ].map((p) => new URL(`./${p}`, srcDir)); - for (const file of paths) { + ]; + return search(fs, srcDir, paths); +} + +function searchLiveConfig(fs: typeof f...
packages/astro/src/content/utils.ts
26
TypeScript
0.643
suggestion
277
51
51
false
feat: initial live loader implementation
13,688
withastro/astro
47,179
TypeScript
ematipico
ascorbic
// Do not render the fallback route if there is already a translated page // with the same path if ( route.type === 'fallback' && // If route is index page, continue rendering. The index page should // always be rendered route.pathname !== '/' && // Check if there is a translated page with the same path ...
Can you revert this? It doesn't seem related to the fix
pipeline: BuildPipeline, gopts: GeneratePathOptions, route: RouteData, ): Promise<boolean | undefined> { const { mod } = gopts; const { config, logger, options } = pipeline; logger.debug('build', `Generating: ${pathname}`); // This adds the page name to the array so it can be shown as part of stats. if (route....
@@ -499,9 +499,23 @@ async function generatePath( // always be rendered route.pathname !== '/' && // Check if there is a translated page with the same path - Object.values(options.allPages).some((val) => val.route.pattern.test(pathname)) + Object.values(options.allPages).some((val) => { + if (val.route.pat...
packages/astro/src/core/build/generate.ts
26
TypeScript
0.214
suggestion
55
51
51
false
fix: fallback and rewrite dynamic route pattern matching
13,697
withastro/astro
47,179
TypeScript
ematipico
benosmac
pipeline: BuildPipeline, gopts: GeneratePathOptions, route: RouteData, ): Promise<boolean | undefined> { const { mod } = gopts; const { config, logger, options } = pipeline; logger.debug('build', `Generating: ${pathname}`); // This adds the page name to the array so it can be shown as part of stats. if (route....
I think we can move this outside of the loop, there's no need to create this variable at each iteration. Also, the project can have `/base` set, which means that the locale is **after** base e.g. `/base/es`. You should probably add a test case with `base` too.
} /** * * @param pathname * @param pipeline * @param gopts * @param route * @return {Promise<boolean | undefined>} If `false` the file hasn't been created. If `undefined` it's expected to not be created. */ async function generatePath( pathname: string, pipeline: BuildPipeline, gopts: GeneratePathOptions, r...
@@ -499,9 +499,23 @@ async function generatePath( // always be rendered route.pathname !== '/' && // Check if there is a translated page with the same path - Object.values(options.allPages).some((val) => val.route.pattern.test(pathname)) + Object.values(options.allPages).some((val) => { + if (val.route.pat...
packages/astro/src/core/build/generate.ts
26
TypeScript
0.643
refactor
263
51
51
false
fix: fallback and rewrite dynamic route pattern matching
13,697
withastro/astro
47,179
TypeScript
ematipico
benosmac
} // Ensure pathname starts with '/' when needed if (!pathname.startsWith('/') && shouldAppendSlash && newUrl.pathname.endsWith('/')) { pathname = prependForwardSlash(pathname); } // Convert '/' to '' for trailingSlash: 'never' if (pathname === '/' && base !== '/' && !shouldAppendSlash) { pathname = ''; } ...
Why do we check `route.params`? The comment doesn't explain it
: removeTrailingForwardSlash(newUrl.pathname); pathname = pathname.slice(base.length); } } // Ensure pathname starts with '/' when needed if (!pathname.startsWith('/') && shouldAppendSlash && newUrl.pathname.endsWith('/')) { pathname = prependForwardSlash(pathname); } // Convert '/' to '' for trailing...
@@ -96,6 +96,18 @@ export function findRouteToRewrite({ let foundRoute; for (const route of routes) { if (route.pattern.test(decodedPathname)) { + // If it's a dynamic route, make sure it actually generates the pathname + if (route.params && route.distURL && route.distURL.length !== 0) {
packages/astro/src/core/routing/rewrite.ts
26
TypeScript
0.357
question
62
51
51
false
fix: fallback and rewrite dynamic route pattern matching
13,697
withastro/astro
47,179
TypeScript
ematipico
benosmac
pathname = prependForwardSlash(pathname); } // Convert '/' to '' for trailingSlash: 'never' if (pathname === '/' && base !== '/' && !shouldAppendSlash) { pathname = ''; } // Set the final URL pathname if (base !== '/' && (pathname === '' || pathname === '/') && !shouldAppendSlash) { // Special case for ro...
I believe this is in case for `index.html` or `some-page.html`, however, we don't have any tests for these cases. Your new test fixture emits only `index.html` files. Can we add another test suite with a different build format? https://docs.astro.build/en/reference/configuration-reference/#buildformat
// Ensure pathname starts with '/' when needed if (!pathname.startsWith('/') && shouldAppendSlash && newUrl.pathname.endsWith('/')) { pathname = prependForwardSlash(pathname); } // Convert '/' to '' for trailingSlash: 'never' if (pathname === '/' && base !== '/' && !shouldAppendSlash) { pathname = ''; } //...
@@ -96,6 +96,18 @@ export function findRouteToRewrite({ let foundRoute; for (const route of routes) { if (route.pattern.test(decodedPathname)) { + // If it's a dynamic route, make sure it actually generates the pathname + if (route.params && route.distURL && route.distURL.length !== 0) { + if ( + !rou...
packages/astro/src/core/routing/rewrite.ts
26
TypeScript
0.571
style
302
51
51
false
fix: fallback and rewrite dynamic route pattern matching
13,697
withastro/astro
47,179
TypeScript
ematipico
benosmac
// we split the URL using the `/`, and then check in the returned array we have the locale const segments = context.url.pathname.split('/'); const urlLocale = segments.find((segment) => { for (const locale of locales) { if (typeof locale === 'string') { if (locale === segment) { return tr...
Can you please add a more generic comment? For example, the `/fr` part has no context and it isn't related to the fix
export type RedirectToFallback = (context: APIContext, response: Response) => Promise<Response>; export function redirectToFallback({ fallback, locales, defaultLocale, strategy, base, fallbackType, }: MiddlewarePayload) { return async function (context: APIContext, response: Response): Promise<Response> { if ...
@@ -386,6 +386,10 @@ export function redirectToFallback({ if (pathFallbackLocale === defaultLocale && strategy === 'pathname-prefix-other-locales') { if (context.url.pathname.includes(`${base}`)) { newPathname = context.url.pathname.replace(`/${urlLocale}`, ``); + // Ensure the pathname are non-e...
packages/astro/src/i18n/index.ts
26
TypeScript
0.5
suggestion
117
51
51
false
fix(i18n): ensure the redirect pathname is non-empty
13,730
withastro/astro
47,179
TypeScript
ematipico
razonyang
if (urlLocale && fallbackKeys.includes(urlLocale)) { const fallbackLocale = fallback[urlLocale]; // the user might have configured the locale using the granular locales, so we want to retrieve its corresponding path instead const pathFallbackLocale = getPathByLocale(fallbackLocale, locales); let new...
The comment is still unclear. For example, you don't explain **why** a redirect from `/fr` to `/` could create an infinite loop. By the way, I believe this isn't the right fix, or to be more precise, the bug is at line 387 where we use the `includes`. Maybe we should check if `base == "/"`, and if so, at line 388 we...
const segments = context.url.pathname.split('/'); const urlLocale = segments.find((segment) => { for (const locale of locales) { if (typeof locale === 'string') { if (locale === segment) { return true; } } else if (locale.path === segment) { return true; } } ret...
@@ -386,6 +386,11 @@ export function redirectToFallback({ if (pathFallbackLocale === defaultLocale && strategy === 'pathname-prefix-other-locales') { if (context.url.pathname.includes(`${base}`)) { newPathname = context.url.pathname.replace(`/${urlLocale}`, ``); + // Ensure the pathname are non-e...
packages/astro/src/i18n/index.ts
26
TypeScript
0.786
bug
385
44
51
false
fix(i18n): ensure the redirect pathname is non-empty
13,730
withastro/astro
47,179
TypeScript
ematipico
razonyang
export interface Product { id: number; name: string; price: number; image: string; } interface User { id: number; } interface Cart { items: Array<{ id: number; name: string; count: number; }>; } async function getJson<T>( incomingReq: Request, endpoint: string, timeout = 10_000 ): Promise<T> { const...
Since the timeout isn't used, i think it could be worth removing it altogether from the example. We try to keep examples minimal and as a starting point. So that probably means removing the abort controller too
export interface Product { id: number; name: string; price: number; image: string; } interface User { id: number; } interface Cart { items: Array<{ id: number; name: string; count: number; }>; } async function getJson<T>( incomingReq: Request, endpoint: string, ): Promise<T> { const origin = new URL(...
@@ -17,49 +17,49 @@ interface Cart { }>; } -async function get<T>( +async function getJson<T>( incomingReq: Request, endpoint: string, - cb: (response: Response) => Promise<T> + timeout = 10_000
examples/ssr/src/api.ts
23
TypeScript
0.5
suggestion
210
48
48
false
refactor(example): remove todo comment and normalize network errors
13,755
withastro/astro
47,179
TypeScript
florian-lefebvre
jp-knj
export const ExperimentalFontsNotEnabled = { name: 'ExperimentalFontsNotEnabled', title: 'Experimental fonts are not enabled', message: 'The Font component is used but experimental fonts have not been registered in the config.', hint: 'Check that you have enabled experimental fonts and also configured your prefer...
Can we instead use an example that might actually happen, because I believe you shouldn't *have* to ever pass an MDX parser to the built-in `file` loader? (If our MDX parser wasn't working, I think that would be a bug?) Similarly, should the file loader EVER be unable to parse a Markdown file automatically? (`example.m...
* @message * Astro is unable to load the given font provider. Open an issue on the corresponding provider's repository. */ export const CannotLoadFontProvider = { name: 'CannotLoadFontProvider', title: 'Cannot load font provider', message: (entrypoint: string) => `An error occured while loading the "${entrypoint}...
@@ -1365,6 +1365,40 @@ export const FontFamilyNotFound = { hint: 'This is often caused by a typo. Check that your Font component is using a `cssVariable` specified in your config.', } satisfies ErrorData; +/** + * @docs + * @message No parser found for file `example.md`. Pass a parser to the `file` loader (e.g. `p...
packages/astro/src/core/errors/errors-data.ts
26
TypeScript
0.786
bug
534
51
51
false
refactor(astro): put them to follow a pattern for errors
13,761
withastro/astro
47,179
TypeScript
sarah11918
jp-knj