feat(blog): add file-based blog with dynamic slugs, MDX content and layout shell

- Introduced blog routing using Next.js App Router
- Implemented dynamic [slug] pages for blog posts
- Added MDX-based content loading via lib/posts
- Integrated shared TopBar layout with navigation
- Established clear content, lib and component separation
This commit is contained in:
PascalSchattenburg
2026-01-22 14:14:15 +01:00
parent b717952234
commit d147843c76
10412 changed files with 2475583 additions and 0 deletions

View File

@@ -0,0 +1,230 @@
import { isDynamicRoute } from '../../shared/lib/router/utils';
import { getSortedRoutes } from '../../shared/lib/router/utils';
import { LocaleRouteMatcher } from '../route-matchers/locale-route-matcher';
import { ensureLeadingSlash } from '../../shared/lib/page-path/ensure-leading-slash';
import { DetachedPromise } from '../../lib/detached-promise';
export class DefaultRouteMatcherManager {
/**
* When this value changes, it indicates that a change has been introduced
* that requires recompilation.
*/ get compilationID() {
return this.providers.length;
}
async waitTillReady() {
if (this.waitTillReadyPromise) {
await this.waitTillReadyPromise;
delete this.waitTillReadyPromise;
}
}
async reload() {
const { promise, resolve, reject } = new DetachedPromise();
this.waitTillReadyPromise = promise;
// Grab the compilation ID for this run, we'll verify it at the end to
// ensure that if any routes were added before reloading is finished that
// we error out.
const compilationID = this.compilationID;
try {
// Collect all the matchers from each provider.
const matchers = [];
// Get all the providers matchers.
const providersMatchers = await Promise.all(this.providers.map((provider)=>provider.matchers()));
// Use this to detect duplicate pathnames.
const all = new Map();
const duplicates = {};
for (const providerMatchers of providersMatchers){
for (const matcher of providerMatchers){
// Reset duplicated matches when reloading from pages conflicting state.
if (matcher.duplicated) delete matcher.duplicated;
// Test to see if the matcher being added is a duplicate.
const duplicate = all.get(matcher.definition.pathname);
if (duplicate) {
// This looks a little weird, but essentially if the pathname
// already exists in the duplicates map, then we got that array
// reference. Otherwise, we create a new array with the original
// duplicate first. Then we push the new matcher into the duplicate
// array, and reset it to the duplicates object (which may be a
// no-op if the pathname already existed in the duplicates object).
// Then we set the array of duplicates on both the original
// duplicate object and the new one, so we can keep them in sync.
// If a new duplicate is found, and it matches an existing pathname,
// the retrieval of the `other` will actually return the array
// reference used by all other duplicates. This is why ReadonlyArray
// is so important! Array's are always references!
const others = duplicates[matcher.definition.pathname] ?? [
duplicate
];
others.push(matcher);
duplicates[matcher.definition.pathname] = others;
// Add duplicated details to each route.
duplicate.duplicated = others;
matcher.duplicated = others;
// TODO: see if we should error for duplicates in production?
}
matchers.push(matcher);
// Add the matcher's pathname to the set.
all.set(matcher.definition.pathname, matcher);
}
}
// Update the duplicate matchers. This is used in the development manager
// to warn about duplicates.
this.matchers.duplicates = duplicates;
// If the cache is the same as what we just parsed, we can exit now. We
// can tell by using the `===` which compares object identity, which for
// the manifest matchers, will return the same matcher each time.
if (this.previousMatchers.length === matchers.length && this.previousMatchers.every((cachedMatcher, index)=>cachedMatcher === matchers[index])) {
return;
}
this.previousMatchers = matchers;
// For matchers that are for static routes, filter them now.
this.matchers.static = matchers.filter((matcher)=>!matcher.isDynamic);
// For matchers that are for dynamic routes, filter them and sort them now.
const dynamic = matchers.filter((matcher)=>matcher.isDynamic);
// As `getSortedRoutes` only takes an array of strings, we need to create
// a map of the pathnames (used for sorting) and the matchers. When we
// have locales, there may be multiple matches for the same pathname. To
// handle this, we keep a map of all the indexes (in `reference`) and
// merge them in later.
const reference = new Map();
const pathnames = new Array();
for(let index = 0; index < dynamic.length; index++){
// Grab the pathname from the definition.
const pathname = dynamic[index].definition.pathname;
// Grab the index in the dynamic array, push it into the reference.
const indexes = reference.get(pathname) ?? [];
indexes.push(index);
// If this is the first one set it. If it isn't, we don't need to
// because pushing above on the array will mutate the array already
// stored there because array's are always a reference!
if (indexes.length === 1) reference.set(pathname, indexes);
else continue;
pathnames.push(pathname);
}
// Sort the array of pathnames.
const sorted = getSortedRoutes(pathnames);
// For each of the sorted pathnames, iterate over them, grabbing the list
// of indexes and merging them back into the new `sortedDynamicMatchers`
// array. The order of the same matching pathname doesn't matter because
// they will have other matching characteristics (like the locale) that
// is considered.
const sortedDynamicMatchers = [];
for (const pathname of sorted){
const indexes = reference.get(pathname);
if (!Array.isArray(indexes)) {
throw Object.defineProperty(new Error('Invariant: expected to find identity in indexes map'), "__NEXT_ERROR_CODE", {
value: "E271",
enumerable: false,
configurable: true
});
}
const dynamicMatches = indexes.map((index)=>dynamic[index]);
sortedDynamicMatchers.push(...dynamicMatches);
}
this.matchers.dynamic = sortedDynamicMatchers;
// This means that there was a new matcher pushed while we were waiting
if (this.compilationID !== compilationID) {
throw Object.defineProperty(new Error('Invariant: expected compilation to finish before new matchers were added, possible missing await'), "__NEXT_ERROR_CODE", {
value: "E242",
enumerable: false,
configurable: true
});
}
} catch (err) {
reject(err);
} finally{
// The compilation ID matched, so mark the complication as finished.
this.lastCompilationID = compilationID;
resolve();
}
}
push(provider) {
this.providers.push(provider);
}
async test(pathname, options) {
// See if there's a match for the pathname...
const match = await this.match(pathname, options);
// This default implementation only needs to check to see if there _was_ a
// match. The development matcher actually changes it's behavior by not
// recompiling the routes.
return match !== null;
}
async match(pathname, options) {
// "Iterate" over the match options. Once we found a single match, exit with
// it, otherwise return null below. If no match is found, the inner block
// won't be called.
for await (const match of this.matchAll(pathname, options)){
return match;
}
return null;
}
/**
* This is a point for other managers to override to inject other checking
* behavior like duplicate route checking on a per-request basis.
*
* @param pathname the pathname to validate against
* @param matcher the matcher to validate/test with
* @returns the match if found
*/ validate(pathname, matcher, options) {
var _options_i18n;
if (matcher instanceof LocaleRouteMatcher) {
return matcher.match(pathname, options);
}
// If the locale was inferred from the default locale, then it will have
// already added a locale to the pathname. We need to remove it before
// matching because this matcher is not locale aware.
if ((_options_i18n = options.i18n) == null ? void 0 : _options_i18n.inferredFromDefault) {
return matcher.match(options.i18n.pathname);
}
return matcher.match(pathname);
}
async *matchAll(pathname, options) {
// Guard against the matcher manager from being run before it needs to be
// recompiled. This was preferred to re-running the compilation here because
// it should be re-ran only when it changes. If a match is attempted before
// this is done, it indicates that there is a case where a provider is added
// before it was recompiled (an error). We also don't want to affect request
// times.
if (this.lastCompilationID !== this.compilationID) {
throw Object.defineProperty(new Error('Invariant: expected routes to have been loaded before match'), "__NEXT_ERROR_CODE", {
value: "E235",
enumerable: false,
configurable: true
});
}
// Ensure that path matching is done with a leading slash.
pathname = ensureLeadingSlash(pathname);
// If this pathname doesn't look like a dynamic route, and this pathname is
// listed in the normalized list of routes, then return it. This ensures
// that when a route like `/user/[id]` is encountered, it doesn't just match
// with the list of normalized routes.
if (!isDynamicRoute(pathname)) {
for (const matcher of this.matchers.static){
const match = this.validate(pathname, matcher, options);
if (!match) continue;
yield match;
}
}
// If we should skip handling dynamic routes, exit now.
if (options == null ? void 0 : options.skipDynamic) return null;
// Loop over the dynamic matchers, yielding each match.
for (const matcher of this.matchers.dynamic){
const match = this.validate(pathname, matcher, options);
if (!match) continue;
yield match;
}
// We tried direct matching against the pathname and against all the dynamic
// paths, so there was no match.
return null;
}
constructor(){
this.providers = [];
this.matchers = {
static: [],
dynamic: [],
duplicates: {}
};
this.lastCompilationID = this.compilationID;
this.previousMatchers = [];
}
}
//# sourceMappingURL=default-route-matcher-manager.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,64 @@
import { RouteKind } from '../route-kind';
import { DefaultRouteMatcherManager } from './default-route-matcher-manager';
import path from '../../shared/lib/isomorphic/path';
import * as Log from '../../build/output/log';
import { cyan } from '../../lib/picocolors';
export class DevRouteMatcherManager extends DefaultRouteMatcherManager {
constructor(production, ensurer, dir){
super(), this.production = production, this.ensurer = ensurer, this.dir = dir;
}
async test(pathname, options) {
// Try to find a match within the developer routes.
const match = await super.match(pathname, options);
// Return if the match wasn't null. Unlike the implementation of `match`
// which uses `matchAll` here, this does not call `ensure` on the match
// found via the development matches.
return match !== null;
}
validate(pathname, matcher, options) {
const match = super.validate(pathname, matcher, options);
// If a match was found, check to see if there were any conflicting app or
// pages files.
// TODO: maybe expand this to _any_ duplicated routes instead?
if (match && matcher.duplicated && matcher.duplicated.some((duplicate)=>duplicate.definition.kind === RouteKind.APP_PAGE || duplicate.definition.kind === RouteKind.APP_ROUTE) && matcher.duplicated.some((duplicate)=>duplicate.definition.kind === RouteKind.PAGES || duplicate.definition.kind === RouteKind.PAGES_API)) {
return null;
}
return match;
}
async *matchAll(pathname, options) {
// Iterate over the development matches to see if one of them match the
// request path.
for await (const developmentMatch of super.matchAll(pathname, options)){
// We're here, which means that we haven't seen this match yet, so we
// should try to ensure it and recompile the production matcher.
await this.ensurer.ensure(developmentMatch, pathname);
await this.production.reload();
// Iterate over the production matches again, this time we should be able
// to match it against the production matcher unless there's an error.
for await (const productionMatch of this.production.matchAll(pathname, options)){
yield productionMatch;
}
}
// We tried direct matching against the pathname and against all the dynamic
// paths, so there was no match.
return null;
}
async reload() {
// Compile the production routes again.
await this.production.reload();
// Compile the development routes.
await super.reload();
// Check for and warn of any duplicates.
for (const [pathname, matchers] of Object.entries(this.matchers.duplicates)){
// We only want to warn about matchers resolving to the same path if their
// identities are different.
const identity = matchers[0].identity;
if (matchers.slice(1).some((matcher)=>matcher.identity !== identity)) {
continue;
}
Log.warn(`Duplicate page detected. ${matchers.map((matcher)=>cyan(path.relative(this.dir, matcher.definition.filename))).join(' and ')} resolve to ${cyan(pathname)}`);
}
}
}
//# sourceMappingURL=dev-route-matcher-manager.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
export { };
//# sourceMappingURL=route-matcher-manager.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/server/route-matcher-managers/route-matcher-manager.ts"],"sourcesContent":["import type { RouteMatch } from '../route-matches/route-match'\nimport type { RouteMatcherProvider } from '../route-matcher-providers/route-matcher-provider'\nimport type { LocaleAnalysisResult } from '../lib/i18n-provider'\n\nexport type MatchOptions = {\n skipDynamic?: boolean\n\n /**\n * If defined, this indicates to the matcher that the request should be\n * treated as locale-aware. If this is undefined, it means that this\n * application was not configured for additional locales.\n */\n i18n?: LocaleAnalysisResult | undefined\n}\n\nexport interface RouteMatcherManager {\n /**\n * Returns a promise that resolves when the matcher manager has finished\n * reloading.\n */\n waitTillReady(): Promise<void>\n\n /**\n * Pushes in a new matcher for this manager to manage. After all the\n * providers have been pushed, the manager must be reloaded.\n *\n * @param provider the provider for this manager to also manage\n */\n push(provider: RouteMatcherProvider): void\n\n /**\n * Reloads the matchers from the providers. This should be done after all the\n * providers have been added or the underlying providers should be refreshed.\n */\n reload(): Promise<void>\n\n /**\n * Tests the underlying matchers to find a match. It does not return the\n * match.\n *\n * @param pathname the pathname to test for matches\n * @param options the options for the testing\n */\n test(pathname: string, options: MatchOptions): Promise<boolean>\n\n /**\n * Returns the first match for a given request.\n *\n * @param pathname the pathname to match against\n * @param options the options for the matching\n */\n match(pathname: string, options: MatchOptions): Promise<RouteMatch | null>\n\n /**\n * Returns a generator for each match for a given request. This should be\n * consumed in a `for await (...)` loop, when finished, breaking or returning\n * from the loop will terminate the matching operation.\n *\n * @param pathname the pathname to match against\n * @param options the options for the matching\n */\n matchAll(\n pathname: string,\n options: MatchOptions\n ): AsyncGenerator<RouteMatch, null, undefined>\n}\n"],"names":[],"mappings":"AAeA,WAkDC","ignoreList":[0]}