11import type { APIRoute , GetStaticPaths } from 'astro' ;
2+ import { AstroError } from 'astro/errors' ;
23import { generateOpenGraphImage } from './generateOpenGraphImage.js' ;
34import type { OGImageOptions } from './types' ;
45
@@ -13,7 +14,6 @@ const pathToSlug = (path: string, _page: any, imageOptions: OGImageOptions): str
1314
1415async function makeGetStaticPaths ( {
1516 pages,
16- param,
1717 getSlug = pathToSlug ,
1818 getImageOptions,
1919} : OGImageRouteConfig < any > ) : Promise < GetStaticPaths > {
@@ -22,14 +22,14 @@ async function makeGetStaticPaths({
2222 const imageOptions = await getImageOptions ( ...page ) ;
2323 const slug = getSlug ( ...page , imageOptions ) ;
2424 return { slug, imageOptions } ;
25- } )
25+ } ) ,
2626 ) ;
27- const paths = entries . map ( ( { slug , imageOptions } ) => ( {
28- params : { [ param ] : slug } ,
29- props : { imageOptions } ,
30- } ) ) ;
31- return function getStaticPaths ( ) {
32- return paths ;
27+ return function getStaticPaths ( { routePattern } ) {
28+ const param = routePatternToParam ( routePattern ) ;
29+ return entries . map ( ( { slug , imageOptions } ) => ( {
30+ params : { [ param ] : slug } ,
31+ props : { imageOptions } ,
32+ } ) ) ;
3333 } ;
3434}
3535
@@ -51,7 +51,37 @@ export async function OGImageRoute<T>(opts: OGImageRouteConfig<T>): Promise<{
5151
5252interface OGImageRouteConfig < T extends unknown > {
5353 pages : { [ path : string ] : T } ;
54- param : string ;
5554 getSlug ?: ( path : string , page : T , imageOptions : OGImageOptions ) => string ;
5655 getImageOptions : ( path : string , page : T ) => OGImageOptions | Promise < OGImageOptions > ;
5756}
57+
58+ /**
59+ * Converts a `routePattern` from Astro's `getStaticPaths()` to a parameter name.
60+ * For example, extracts `slug` from both `/og/[slug].png` and `/og/[...slug].png`.
61+ */
62+ function routePatternToParam ( routePattern : string ) : string {
63+ const matches = routePattern . matchAll ( / \[ (?: \. { 3 } ) ? (?< param > .+ ?) \] / g) ;
64+ let param : string | undefined ;
65+ let paramCount = 0 ;
66+ for ( const { groups } of matches ) {
67+ if ( groups ?. param ) {
68+ param = groups . param ;
69+ paramCount ++ ;
70+ }
71+ }
72+ if ( ! param ) {
73+ throw new AstroError (
74+ `No parameter found in route: \`${ routePattern } \`` ,
75+ 'Make sure the open graph image file name contains a dynamic route parameter, e.g. `src/pages/og/[...slug].ts`.\n\n' +
76+ 'See https://docs.astro.build/en/guides/routing/#dynamic-routes for more information on dynamic routes.' ,
77+ ) ;
78+ }
79+ if ( paramCount > 1 ) {
80+ throw new AstroError (
81+ `Multiple parameters found in route: \`${ routePattern } \`` ,
82+ 'Make sure the open graph image file name only contains one dynamic route parameter, e.g. `src/pages/og/[...slug].ts`.\n\n' +
83+ 'See https://docs.astro.build/en/guides/routing/#dynamic-routes for more information on dynamic routes.' ,
84+ ) ;
85+ }
86+ return param ;
87+ }
0 commit comments