accept-md-runtime 4.0.4 → 4.0.6-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,7 +9,7 @@ pnpm add accept-md-runtime
9
9
  # or npm install accept-md-runtime
10
10
  ```
11
11
 
12
- **Peer dependency:** Next.js 12 or later.
12
+ **Peer dependency:** Next.js 12 or later (optional; only needed for Next.js projects).
13
13
 
14
14
  ## Quick setup
15
15
 
package/dist/index.d.ts CHANGED
@@ -5,5 +5,5 @@ export { getMarkdownForPath } from './handler.js';
5
5
  export type { GetMarkdownOptions } from './handler.js';
6
6
  export type { NextMarkdownConfig } from './types.js';
7
7
  export { loadConfig } from './config.js';
8
- export { MIDDLEWARE_TEMPLATE, APP_ROUTE_HANDLER_TEMPLATE, PAGES_API_HANDLER_TEMPLATE, getNextConfigRewrite, } from './templates.js';
8
+ export { MIDDLEWARE_TEMPLATE, APP_ROUTE_HANDLER_TEMPLATE, PAGES_API_HANDLER_TEMPLATE, SVELTEKIT_ROUTE_HANDLER_TEMPLATE, getNextConfigRewrite, } from './templates.js';
9
9
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,YAAY,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,YAAY,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACvD,YAAY,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACL,mBAAmB,EACnB,0BAA0B,EAC1B,0BAA0B,EAC1B,oBAAoB,GACrB,MAAM,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAC/C,YAAY,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,YAAY,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACvD,YAAY,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACL,mBAAmB,EACnB,0BAA0B,EAC1B,0BAA0B,EAC1B,gCAAgC,EAChC,oBAAoB,GACrB,MAAM,gBAAgB,CAAC"}
package/dist/index.js CHANGED
@@ -2,5 +2,5 @@
2
2
  export { htmlToMarkdown } from './markdown.js';
3
3
  export { getMarkdownForPath } from './handler.js';
4
4
  export { loadConfig } from './config.js';
5
- export { MIDDLEWARE_TEMPLATE, APP_ROUTE_HANDLER_TEMPLATE, PAGES_API_HANDLER_TEMPLATE, getNextConfigRewrite, } from './templates.js';
5
+ export { MIDDLEWARE_TEMPLATE, APP_ROUTE_HANDLER_TEMPLATE, PAGES_API_HANDLER_TEMPLATE, SVELTEKIT_ROUTE_HANDLER_TEMPLATE, getNextConfigRewrite, } from './templates.js';
6
6
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAE/C,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAGlD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACL,mBAAmB,EACnB,0BAA0B,EAC1B,0BAA0B,EAC1B,oBAAoB,GACrB,MAAM,gBAAgB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAE/C,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAGlD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACL,mBAAmB,EACnB,0BAA0B,EAC1B,0BAA0B,EAC1B,gCAAgC,EAChC,oBAAoB,GACrB,MAAM,gBAAgB,CAAC"}
@@ -2,8 +2,9 @@
2
2
  * Generated middleware and route handler templates.
3
3
  */
4
4
  export declare const MIDDLEWARE_TEMPLATE = "// Generated by accept-md. Do not edit the markdown block by hand.\nimport { NextResponse } from 'next/server';\n\nconst MARKDOWN_ACCEPT = new RegExp('\\\\btext/markdown\\\\b', 'i');\nconst EXCLUDED_PREFIXES = ['/api/', '/_next/'];\nconst MARKDOWN_HANDLER_PATH = '/api/accept-md';\n\n/** @param {import('next/server').NextRequest} request */\nexport function middleware(request) {\n const pathname = request.nextUrl.pathname;\n const accept = (request.headers.get('accept') || '').toLowerCase();\n if (!MARKDOWN_ACCEPT.test(accept)) return NextResponse.next();\n if (EXCLUDED_PREFIXES.some((p) => pathname.startsWith(p))) return NextResponse.next();\n\n const url = request.nextUrl.clone();\n url.pathname = MARKDOWN_HANDLER_PATH;\n url.searchParams.set('path', pathname);\n // Let Vercel/Next.js forward all original request metadata (auth, cookies, protection)\n // and only use the query parameter to communicate the original pathname.\n return NextResponse.rewrite(url);\n}\n";
5
- export declare const APP_ROUTE_HANDLER_TEMPLATE = "// Generated by accept-md. Do not edit the markdown block by hand.\nimport { NextResponse } from 'next/server';\nimport { getMarkdownForPath, loadConfig } from 'accept-md-runtime';\n\nconst cache = new Map();\nconst HANDLER_PATH = '/api/accept-md';\n\n/** @param {import('next/server').NextRequest} request */\nexport async function GET(request) {\n const pathFromHeader = request.headers.get('x-accept-md-path');\n const pathFromQuery = request.nextUrl.searchParams.get('path');\n const pathname = request.nextUrl.pathname;\n // Never use the handler path itself - always prefer header, then query, then pathname (if not handler), then default to '/'\n let path = pathFromHeader;\n if (!path || path.trim() === '') {\n path = pathFromQuery && pathFromQuery.trim() !== '' ? pathFromQuery : null;\n }\n // If pathname starts with /api/accept-md, extract the original path from it\n // This handles next.config rewrites that use /api/accept-md/:path* pattern\n if (!path && pathname.startsWith(HANDLER_PATH + '/')) {\n path = pathname.slice(HANDLER_PATH.length);\n // Handle root path case: /api/accept-md/ becomes /\n if (path === '') {\n path = '/';\n }\n }\n if (!path) {\n path = pathname !== HANDLER_PATH ? pathname : null;\n }\n if (!path || path === HANDLER_PATH) {\n path = '/';\n }\n // Ensure path starts with /\n if (!path.startsWith('/')) {\n path = '/' + path;\n }\n // Exclude /api and /_next paths - return 404 for these\n if (path.startsWith('/api/') || path.startsWith('/_next/')) {\n return NextResponse.json({ error: 'Not found' }, { status: 404 });\n }\n const config = loadConfig(process.cwd());\n // Construct baseUrl reliably: prefer config, then use request origin, fall back to localhost\n let baseUrl = config.baseUrl;\n if (!baseUrl) {\n baseUrl = request.nextUrl.origin || 'http://localhost:' + (process.env.PORT || 3000);\n }\n // Forward headers but avoid sending markdown Accept header to the upstream page fetch\n const headers = new Headers(request.headers);\n headers.delete('accept');\n try {\n const markdown = await getMarkdownForPath({\n pathname: path,\n baseUrl,\n config,\n cache: config.cache !== false ? cache : undefined,\n headers,\n });\n return new NextResponse(markdown, {\n headers: {\n 'Content-Type': 'text/markdown; charset=utf-8',\n 'Cache-Control': config.cache ? 'public, s-maxage=60, stale-while-revalidate' : 'no-store',\n },\n });\n } catch (err) {\n return NextResponse.json(\n { error: err instanceof Error ? err.message : 'Markdown generation failed' },\n { status: 500 }\n );\n }\n}\n";
6
- export declare const PAGES_API_HANDLER_TEMPLATE = "// Generated by accept-md. Do not edit the markdown block by hand.\nimport { getMarkdownForPath, loadConfig } from 'accept-md-runtime';\n\nconst cache = new Map();\n\n/** @param {import('next').NextApiRequest} req @param {import('next').NextApiResponse} res */\nexport default async function handler(req, res) {\n if (req.method !== 'GET') {\n res.setHeader('Allow', 'GET');\n return res.status(405).end();\n }\n const pathFromHeader = req.headers['x-accept-md-path'];\n const pathFromQuery = Array.isArray(req.query.path) ? req.query.path[0] : req.query.path;\n const pathRaw = (pathFromHeader || pathFromQuery) || '/';\n // Handle placeholder values like \":path*\" that can appear from Next.js rewrite configs\n let path;\n if (typeof pathRaw === 'string') {\n path = (pathRaw === '' || pathRaw.includes(':path')) ? '/' : pathRaw;\n } else {\n path = pathRaw[0] || '/';\n }\n // Ensure path starts with /\n if (!path.startsWith('/')) {\n path = '/' + path;\n }\n // Exclude /api and /_next paths - return 404 for these\n if (path.startsWith('/api/') || path.startsWith('/_next/')) {\n return res.status(404).json({ error: 'Not found' });\n }\n const config = loadConfig(process.cwd());\n // Construct baseUrl reliably on Vercel: use host header with protocol, fall back to origin/referer, then VERCEL_URL, then localhost\n let baseUrl = config.baseUrl;\n if (!baseUrl) {\n const host = req.headers.host;\n if (host) {\n const protocol = req.headers['x-forwarded-proto'] || (process.env.VERCEL_URL ? 'https' : 'http');\n baseUrl = protocol + '://' + host;\n } else {\n const originOrReferer = (req.headers.origin || req.headers.referer || '').replace(/\\\\/?$/, '');\n if (originOrReferer) {\n baseUrl = originOrReferer;\n } else if (process.env.VERCEL_URL) {\n baseUrl = process.env.VERCEL_URL.startsWith('http') ? process.env.VERCEL_URL : 'https://' + process.env.VERCEL_URL;\n } else {\n baseUrl = 'http://localhost:' + (process.env.PORT || 3000);\n }\n }\n }\n // Convert req.headers to Headers for forwarding (e.g., for Vercel deployment protection)\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (!value) continue;\n // Do not forward markdown Accept header to the upstream page fetch\n if (key.toLowerCase() === 'accept') continue;\n headers.set(key, Array.isArray(value) ? value[0] : value);\n }\n try {\n const markdown = await getMarkdownForPath({\n pathname: path,\n baseUrl,\n config,\n cache: config.cache !== false ? cache : undefined,\n headers,\n });\n res.setHeader('Content-Type', 'text/markdown; charset=utf-8');\n if (config.cache) {\n res.setHeader('Cache-Control', 'public, s-maxage=60, stale-while-revalidate');\n }\n res.status(200).send(markdown);\n } catch (err) {\n res.status(500).json({\n error: err instanceof Error ? err.message : 'Markdown generation failed',\n });\n }\n}\n";
5
+ export declare const APP_ROUTE_HANDLER_TEMPLATE = "// Generated by accept-md. Do not edit the markdown block by hand.\nimport { NextResponse } from 'next/server';\nimport { getMarkdownForPath, loadConfig } from 'accept-md-runtime';\n\nconst cache = new Map();\nconst HANDLER_PATH = '/api/accept-md';\n\n/** @param {import('next/server').NextRequest} request */\nexport async function GET(request) {\n const pathFromHeader = request.headers.get('x-accept-md-path');\n const pathFromQuery = request.nextUrl.searchParams.get('path');\n // Headers that may carry the original matched path when using rewrites on Vercel/Next.js\n const pathFromMatchedHeader =\n request.headers.get('x-matched-path') ||\n request.headers.get('x-vercel-original-path') ||\n request.headers.get('x-original-path') ||\n request.headers.get('x-rewrite-path');\n const pathname = request.nextUrl.pathname;\n // Never use the handler path itself - always prefer, in order:\n // 1) explicit header, 2) internal matched-path header, 3) query param, 4) pathname (if not handler), then default to '/'\n let path = pathFromHeader && pathFromHeader.trim() !== '' ? pathFromHeader : null;\n if (!path && pathFromMatchedHeader && pathFromMatchedHeader.trim() !== '') {\n path = pathFromMatchedHeader;\n }\n if (!path && pathFromQuery && pathFromQuery.trim() !== '') {\n path = pathFromQuery;\n }\n // If pathname starts with /api/accept-md, extract the original path from it\n // This handles next.config rewrites that use /api/accept-md/:path* pattern\n if (!path && pathname.startsWith(HANDLER_PATH + '/')) {\n path = pathname.slice(HANDLER_PATH.length);\n // Handle root path case: /api/accept-md/ becomes /\n if (path === '') {\n path = '/';\n }\n }\n if (!path) {\n path = pathname !== HANDLER_PATH ? pathname : null;\n }\n if (!path || path === HANDLER_PATH) {\n path = '/';\n }\n // Ensure path starts with /\n if (!path.startsWith('/')) {\n path = '/' + path;\n }\n // Exclude /api and /_next paths - return 404 for these\n if (path.startsWith('/api/') || path.startsWith('/_next/')) {\n return NextResponse.json({ error: 'Not found' }, { status: 404 });\n }\n const config = loadConfig(process.cwd());\n // Construct baseUrl reliably: prefer config, then use request origin, fall back to localhost\n let baseUrl = config.baseUrl;\n if (!baseUrl) {\n baseUrl = request.nextUrl.origin || 'http://localhost:' + (process.env.PORT || 3000);\n }\n // Forward headers but avoid sending markdown Accept header to the upstream page fetch\n const headers = new Headers(request.headers);\n headers.delete('accept');\n try {\n const markdown = await getMarkdownForPath({\n pathname: path,\n baseUrl,\n config,\n cache: config.cache !== false ? cache : undefined,\n headers,\n });\n return new NextResponse(markdown, {\n headers: {\n 'Content-Type': 'text/markdown; charset=utf-8',\n 'Cache-Control': config.cache ? 'public, s-maxage=60, stale-while-revalidate' : 'no-store',\n },\n });\n } catch (err) {\n return NextResponse.json(\n { error: err instanceof Error ? err.message : 'Markdown generation failed' },\n { status: 500 }\n );\n }\n}\n";
6
+ export declare const PAGES_API_HANDLER_TEMPLATE = "// Generated by accept-md. Do not edit the markdown block by hand.\nimport { getMarkdownForPath, loadConfig } from 'accept-md-runtime';\n\nconst cache = new Map();\n\n/** @param {import('next').NextApiRequest} req @param {import('next').NextApiResponse} res */\nexport default async function handler(req, res) {\n if (req.method !== 'GET') {\n res.setHeader('Allow', 'GET');\n return res.status(405).end();\n }\n const pathFromHeader = req.headers['x-accept-md-path'];\n const pathFromQuery = Array.isArray(req.query.path) ? req.query.path[0] : req.query.path;\n const pathFromMatchedHeader =\n req.headers['x-matched-path'] ||\n req.headers['x-vercel-original-path'] ||\n req.headers['x-original-path'] ||\n req.headers['x-rewrite-path'];\n // Determine raw path in priority order: header, internal matched-path header, query, then fallback\n let pathRaw = pathFromHeader || pathFromMatchedHeader || pathFromQuery || '/';\n // Handle placeholder values like \":path*\" that can appear from Next.js rewrite configs\n let path;\n if (typeof pathRaw === 'string') {\n path = (pathRaw === '' || pathRaw.includes(':path')) ? '/' : pathRaw;\n } else {\n path = pathRaw[0] || '/';\n }\n // Ensure path starts with /\n if (!path.startsWith('/')) {\n path = '/' + path;\n }\n // Exclude /api and /_next paths - return 404 for these\n if (path.startsWith('/api/') || path.startsWith('/_next/')) {\n return res.status(404).json({ error: 'Not found' });\n }\n const config = loadConfig(process.cwd());\n // Construct baseUrl reliably on Vercel: use host header with protocol, fall back to origin/referer, then VERCEL_URL, then localhost\n let baseUrl = config.baseUrl;\n if (!baseUrl) {\n const host = req.headers.host;\n if (host) {\n const protocol = req.headers['x-forwarded-proto'] || (process.env.VERCEL_URL ? 'https' : 'http');\n baseUrl = protocol + '://' + host;\n } else {\n const originOrReferer = (req.headers.origin || req.headers.referer || '').replace(/\\\\/?$/, '');\n if (originOrReferer) {\n baseUrl = originOrReferer;\n } else if (process.env.VERCEL_URL) {\n baseUrl = process.env.VERCEL_URL.startsWith('http') ? process.env.VERCEL_URL : 'https://' + process.env.VERCEL_URL;\n } else {\n baseUrl = 'http://localhost:' + (process.env.PORT || 3000);\n }\n }\n }\n // Convert req.headers to Headers for forwarding (e.g., for Vercel deployment protection)\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (!value) continue;\n // Do not forward markdown Accept header to the upstream page fetch\n if (key.toLowerCase() === 'accept') continue;\n headers.set(key, Array.isArray(value) ? value[0] : value);\n }\n try {\n const markdown = await getMarkdownForPath({\n pathname: path,\n baseUrl,\n config,\n cache: config.cache !== false ? cache : undefined,\n headers,\n });\n res.setHeader('Content-Type', 'text/markdown; charset=utf-8');\n if (config.cache) {\n res.setHeader('Cache-Control', 'public, s-maxage=60, stale-while-revalidate');\n }\n res.status(200).send(markdown);\n } catch (err) {\n res.status(500).json({\n error: err instanceof Error ? err.message : 'Markdown generation failed',\n });\n }\n}\n";
7
+ export declare const SVELTEKIT_ROUTE_HANDLER_TEMPLATE = "// Generated by accept-md. Do not edit the markdown block by hand.\nimport { getMarkdownForPath, loadConfig } from 'accept-md-runtime';\n\nconst cache = new Map();\nconst HANDLER_PATH = '/api/accept-md';\n\nexport async function GET(event) {\n const url = event.url;\n const request = event.request;\n\n const pathFromHeader = request.headers.get('x-accept-md-path');\n const pathFromQuery = url.searchParams.get('path');\n const pathname = url.pathname;\n\n // Determine raw path in priority order:\n // 1) explicit header\n // 2) query parameter\n // 3) path suffix after /api/accept-md (for /api/accept-md/[...path] routes)\n let path = pathFromHeader && pathFromHeader.trim() !== '' ? pathFromHeader : null;\n if (!path && pathFromQuery && pathFromQuery.trim() !== '') {\n path = pathFromQuery;\n }\n if (!path && pathname.startsWith(HANDLER_PATH + '/')) {\n path = pathname.slice(HANDLER_PATH.length);\n if (path === '') {\n path = '/';\n }\n }\n if (!path || path === HANDLER_PATH) {\n path = '/';\n }\n // Ensure path starts with /\n if (!path.startsWith('/')) {\n path = '/' + path;\n }\n // Exclude /api and /_next paths - return 404 for these (keeps behavior aligned with Next.js)\n if (path.startsWith('/api/') || path.startsWith('/_next/')) {\n return new Response(JSON.stringify({ error: 'Not found' }), {\n status: 404,\n headers: {\n 'Content-Type': 'application/json; charset=utf-8',\n },\n });\n }\n\n const config = loadConfig(process.cwd());\n\n // Construct baseUrl: prefer config, then use request origin, fall back to localhost\n let baseUrl = config.baseUrl;\n if (!baseUrl) {\n baseUrl = url.origin || 'http://localhost:' + (process.env.PORT || 5173);\n }\n\n // Forward headers but avoid sending markdown Accept header to the upstream page fetch\n const headers = new Headers(request.headers);\n headers.delete('accept');\n\n try {\n const markdown = await getMarkdownForPath({\n pathname: path,\n baseUrl,\n config,\n cache: config.cache !== false ? cache : undefined,\n headers,\n });\n return new Response(markdown, {\n headers: {\n 'Content-Type': 'text/markdown; charset=utf-8',\n 'Cache-Control': config.cache ? 'public, s-maxage=60, stale-while-revalidate' : 'no-store',\n },\n });\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Markdown generation failed';\n return new Response(JSON.stringify({ error: message }), {\n status: 500,\n headers: {\n 'Content-Type': 'application/json; charset=utf-8',\n },\n });\n }\n}\n";
7
8
  /**
8
9
  * Returns the rewrite configuration object for next.config.js/ts
9
10
  * This is the preferred method over middleware (Next.js is moving away from middleware).
@@ -1 +1 @@
1
- {"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../src/templates.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,eAAO,MAAM,mBAAmB,k+BAqB/B,CAAC;AAEF,eAAO,MAAM,0BAA0B,qoFAsEtC,CAAC;AAEF,eAAO,MAAM,0BAA0B,y+FA2EtC,CAAC;AAEF;;;GAGG;AACH,wBAAgB,oBAAoB;;;;;;;;EAYnC"}
1
+ {"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../src/templates.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,eAAO,MAAM,mBAAmB,k+BAqB/B,CAAC;AAEF,eAAO,MAAM,0BAA0B,spGAgFtC,CAAC;AAEF,eAAO,MAAM,0BAA0B,qyGAiFtC,CAAC;AAEF,eAAO,MAAM,gCAAgC,qmFAiF5C,CAAC;AAEF;;;GAGG;AACH,wBAAgB,oBAAoB;;;;;;;;EAYnC"}
package/dist/templates.js CHANGED
@@ -34,11 +34,21 @@ const HANDLER_PATH = '/api/accept-md';
34
34
  export async function GET(request) {
35
35
  const pathFromHeader = request.headers.get('x-accept-md-path');
36
36
  const pathFromQuery = request.nextUrl.searchParams.get('path');
37
+ // Headers that may carry the original matched path when using rewrites on Vercel/Next.js
38
+ const pathFromMatchedHeader =
39
+ request.headers.get('x-matched-path') ||
40
+ request.headers.get('x-vercel-original-path') ||
41
+ request.headers.get('x-original-path') ||
42
+ request.headers.get('x-rewrite-path');
37
43
  const pathname = request.nextUrl.pathname;
38
- // Never use the handler path itself - always prefer header, then query, then pathname (if not handler), then default to '/'
39
- let path = pathFromHeader;
40
- if (!path || path.trim() === '') {
41
- path = pathFromQuery && pathFromQuery.trim() !== '' ? pathFromQuery : null;
44
+ // Never use the handler path itself - always prefer, in order:
45
+ // 1) explicit header, 2) internal matched-path header, 3) query param, 4) pathname (if not handler), then default to '/'
46
+ let path = pathFromHeader && pathFromHeader.trim() !== '' ? pathFromHeader : null;
47
+ if (!path && pathFromMatchedHeader && pathFromMatchedHeader.trim() !== '') {
48
+ path = pathFromMatchedHeader;
49
+ }
50
+ if (!path && pathFromQuery && pathFromQuery.trim() !== '') {
51
+ path = pathFromQuery;
42
52
  }
43
53
  // If pathname starts with /api/accept-md, extract the original path from it
44
54
  // This handles next.config rewrites that use /api/accept-md/:path* pattern
@@ -107,7 +117,13 @@ export default async function handler(req, res) {
107
117
  }
108
118
  const pathFromHeader = req.headers['x-accept-md-path'];
109
119
  const pathFromQuery = Array.isArray(req.query.path) ? req.query.path[0] : req.query.path;
110
- const pathRaw = (pathFromHeader || pathFromQuery) || '/';
120
+ const pathFromMatchedHeader =
121
+ req.headers['x-matched-path'] ||
122
+ req.headers['x-vercel-original-path'] ||
123
+ req.headers['x-original-path'] ||
124
+ req.headers['x-rewrite-path'];
125
+ // Determine raw path in priority order: header, internal matched-path header, query, then fallback
126
+ let pathRaw = pathFromHeader || pathFromMatchedHeader || pathFromQuery || '/';
111
127
  // Handle placeholder values like ":path*" that can appear from Next.js rewrite configs
112
128
  let path;
113
129
  if (typeof pathRaw === 'string') {
@@ -170,6 +186,88 @@ export default async function handler(req, res) {
170
186
  }
171
187
  }
172
188
  `;
189
+ export const SVELTEKIT_ROUTE_HANDLER_TEMPLATE = `// Generated by accept-md. Do not edit the markdown block by hand.
190
+ import { getMarkdownForPath, loadConfig } from 'accept-md-runtime';
191
+
192
+ const cache = new Map();
193
+ const HANDLER_PATH = '/api/accept-md';
194
+
195
+ export async function GET(event) {
196
+ const url = event.url;
197
+ const request = event.request;
198
+
199
+ const pathFromHeader = request.headers.get('x-accept-md-path');
200
+ const pathFromQuery = url.searchParams.get('path');
201
+ const pathname = url.pathname;
202
+
203
+ // Determine raw path in priority order:
204
+ // 1) explicit header
205
+ // 2) query parameter
206
+ // 3) path suffix after /api/accept-md (for /api/accept-md/[...path] routes)
207
+ let path = pathFromHeader && pathFromHeader.trim() !== '' ? pathFromHeader : null;
208
+ if (!path && pathFromQuery && pathFromQuery.trim() !== '') {
209
+ path = pathFromQuery;
210
+ }
211
+ if (!path && pathname.startsWith(HANDLER_PATH + '/')) {
212
+ path = pathname.slice(HANDLER_PATH.length);
213
+ if (path === '') {
214
+ path = '/';
215
+ }
216
+ }
217
+ if (!path || path === HANDLER_PATH) {
218
+ path = '/';
219
+ }
220
+ // Ensure path starts with /
221
+ if (!path.startsWith('/')) {
222
+ path = '/' + path;
223
+ }
224
+ // Exclude /api and /_next paths - return 404 for these (keeps behavior aligned with Next.js)
225
+ if (path.startsWith('/api/') || path.startsWith('/_next/')) {
226
+ return new Response(JSON.stringify({ error: 'Not found' }), {
227
+ status: 404,
228
+ headers: {
229
+ 'Content-Type': 'application/json; charset=utf-8',
230
+ },
231
+ });
232
+ }
233
+
234
+ const config = loadConfig(process.cwd());
235
+
236
+ // Construct baseUrl: prefer config, then use request origin, fall back to localhost
237
+ let baseUrl = config.baseUrl;
238
+ if (!baseUrl) {
239
+ baseUrl = url.origin || 'http://localhost:' + (process.env.PORT || 5173);
240
+ }
241
+
242
+ // Forward headers but avoid sending markdown Accept header to the upstream page fetch
243
+ const headers = new Headers(request.headers);
244
+ headers.delete('accept');
245
+
246
+ try {
247
+ const markdown = await getMarkdownForPath({
248
+ pathname: path,
249
+ baseUrl,
250
+ config,
251
+ cache: config.cache !== false ? cache : undefined,
252
+ headers,
253
+ });
254
+ return new Response(markdown, {
255
+ headers: {
256
+ 'Content-Type': 'text/markdown; charset=utf-8',
257
+ 'Cache-Control': config.cache ? 'public, s-maxage=60, stale-while-revalidate' : 'no-store',
258
+ },
259
+ });
260
+ } catch (err) {
261
+ const message = err instanceof Error ? err.message : 'Markdown generation failed';
262
+ return new Response(JSON.stringify({ error: message }), {
263
+ status: 500,
264
+ headers: {
265
+ 'Content-Type': 'application/json; charset=utf-8',
266
+ },
267
+ });
268
+ }
269
+ }
270
+ `;
173
271
  /**
174
272
  * Returns the rewrite configuration object for next.config.js/ts
175
273
  * This is the preferred method over middleware (Next.js is moving away from middleware).
@@ -1 +1 @@
1
- {"version":3,"file":"templates.js","sourceRoot":"","sources":["../src/templates.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,MAAM,CAAC,MAAM,mBAAmB,GAAG;;;;;;;;;;;;;;;;;;;;;CAqBlC,CAAC;AAEF,MAAM,CAAC,MAAM,0BAA0B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsEzC,CAAC;AAEF,MAAM,CAAC,MAAM,0BAA0B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2EzC,CAAC;AAEF;;;GAGG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO;QACL,MAAM,EAAE,SAAS;QACjB,WAAW,EAAE,uBAAuB;QACpC,GAAG,EAAE;YACH;gBACE,IAAI,EAAE,QAAQ;gBACd,GAAG,EAAE,QAAQ;gBACb,KAAK,EAAE,uBAAuB;aAC/B;SACF;KACF,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"templates.js","sourceRoot":"","sources":["../src/templates.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,MAAM,CAAC,MAAM,mBAAmB,GAAG;;;;;;;;;;;;;;;;;;;;;CAqBlC,CAAC;AAEF,MAAM,CAAC,MAAM,0BAA0B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgFzC,CAAC;AAEF,MAAM,CAAC,MAAM,0BAA0B,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiFzC,CAAC;AAEF,MAAM,CAAC,MAAM,gCAAgC,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiF/C,CAAC;AAEF;;;GAGG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO;QACL,MAAM,EAAE,SAAS;QACjB,WAAW,EAAE,uBAAuB;QACpC,GAAG,EAAE;YACH;gBACE,IAAI,EAAE,QAAQ;gBACd,GAAG,EAAE,QAAQ;gBACb,KAAK,EAAE,uBAAuB;aAC/B;SACF;KACF,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "accept-md-runtime",
3
- "version": "4.0.4",
3
+ "version": "4.0.6-canary.0",
4
4
  "description": "HTML→Markdown conversion and route handler for accept-md (Next.js)",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -38,6 +38,11 @@
38
38
  "peerDependencies": {
39
39
  "next": ">=12.0.0"
40
40
  },
41
+ "peerDependenciesMeta": {
42
+ "next": {
43
+ "optional": true
44
+ }
45
+ },
41
46
  "devDependencies": {
42
47
  "@types/node": "^20.10.0",
43
48
  "@types/turndown": "^5.0.0",