gemi 0.54.2 → 0.54.4
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/dist/app/index.js +2 -2
- package/dist/app/index.js.map +1 -1
- package/dist/bun/plugin.js +2 -2
- package/dist/bun/plugin.js.map +1 -1
- package/dist/bun/preload.js +2 -2
- package/dist/bun/preload.js.map +2 -2
- package/dist/chunk-1312a1t4.js +4 -0
- package/dist/{chunk-r9z5rrk0.js.map → chunk-1312a1t4.js.map} +2 -2
- package/dist/{chunk-9taz1h3t.js → chunk-1psx59jt.js} +2 -2
- package/dist/{chunk-9taz1h3t.js.map → chunk-1psx59jt.js.map} +1 -1
- package/dist/chunk-2s75crt8.js +4 -0
- package/dist/{chunk-07t0dmdg.js.map → chunk-2s75crt8.js.map} +2 -2
- package/dist/chunk-2zyharpa.js +4 -0
- package/dist/{chunk-hk067634.js.map → chunk-2zyharpa.js.map} +2 -2
- package/dist/chunk-35j03vge.js +4 -0
- package/dist/{chunk-br8ten26.js.map → chunk-35j03vge.js.map} +2 -2
- package/dist/chunk-3njyfdj5.js +19 -0
- package/dist/chunk-3njyfdj5.js.map +60 -0
- package/dist/chunk-4n0xx0y6.js +66 -0
- package/dist/{chunk-n382ygnp.js.map → chunk-4n0xx0y6.js.map} +4 -53
- package/dist/{chunk-gn9zjgep.js → chunk-5ad8era8.js} +2 -2
- package/dist/{chunk-gn9zjgep.js.map → chunk-5ad8era8.js.map} +1 -1
- package/dist/{chunk-50vm7x98.js → chunk-6c5xkj0z.js} +2 -2
- package/dist/{chunk-50vm7x98.js.map → chunk-6c5xkj0z.js.map} +1 -1
- package/dist/chunk-6yy92txx.js +9 -0
- package/dist/{chunk-k8endm5j.js.map → chunk-6yy92txx.js.map} +6 -6
- package/dist/chunk-796pyrm9.js +4 -0
- package/dist/{chunk-1snh7yc4.js.map → chunk-796pyrm9.js.map} +2 -2
- package/dist/chunk-876p591d.js +5 -0
- package/dist/chunk-876p591d.js.map +13 -0
- package/dist/chunk-95t14jaw.js +13 -0
- package/dist/chunk-95t14jaw.js.map +222 -0
- package/dist/{chunk-kz39hphm.js → chunk-97rcmaps.js} +3 -3
- package/dist/{chunk-kz39hphm.js.map → chunk-97rcmaps.js.map} +1 -1
- package/dist/{chunk-c22vcxty.js → chunk-9agd5hjw.js} +2 -2
- package/dist/{chunk-c22vcxty.js.map → chunk-9agd5hjw.js.map} +2 -2
- package/dist/chunk-9wrbnr38.js +4 -0
- package/dist/{chunk-c0wcsmpj.js.map → chunk-9wrbnr38.js.map} +2 -2
- package/dist/{chunk-sqp7kn7h.js → chunk-a1h4paj1.js} +3 -3
- package/dist/{chunk-sqp7kn7h.js.map → chunk-a1h4paj1.js.map} +1 -1
- package/dist/{chunk-r06rxn19.js → chunk-b5mc1st9.js} +2 -2
- package/dist/{chunk-r06rxn19.js.map → chunk-b5mc1st9.js.map} +1 -1
- package/dist/chunk-c6qxw3v9.js +5 -0
- package/dist/{chunk-f13f68c0.js.map → chunk-c6qxw3v9.js.map} +2 -2
- package/dist/{chunk-113khwbw.js → chunk-cbqrkfjm.js} +2 -2
- package/dist/{chunk-113khwbw.js.map → chunk-cbqrkfjm.js.map} +1 -1
- package/dist/{chunk-jp4pf3yt.js → chunk-dngwctnt.js} +4 -4
- package/dist/{chunk-jp4pf3yt.js.map → chunk-dngwctnt.js.map} +2 -2
- package/dist/{chunk-f418jh9k.js → chunk-ejrcyzx8.js} +2 -2
- package/dist/{chunk-f418jh9k.js.map → chunk-ejrcyzx8.js.map} +1 -1
- package/dist/chunk-h3b0v3bz.js +4 -0
- package/dist/{chunk-4qkzdyj7.js.map → chunk-h3b0v3bz.js.map} +1 -1
- package/dist/{chunk-jb022m7n.js → chunk-hg9y6ctt.js} +2 -2
- package/dist/{chunk-jb022m7n.js.map → chunk-hg9y6ctt.js.map} +1 -1
- package/dist/chunk-j15ewww3.js +5 -0
- package/dist/{chunk-2pt6kyn9.js.map → chunk-j15ewww3.js.map} +2 -2
- package/dist/{chunk-zckj6bs6.js → chunk-j3tzdcz7.js} +3 -3
- package/dist/{chunk-zckj6bs6.js.map → chunk-j3tzdcz7.js.map} +1 -1
- package/dist/chunk-jq46m17j.js +5 -0
- package/dist/{chunk-efsk1wy0.js.map → chunk-jq46m17j.js.map} +2 -2
- package/dist/{chunk-pgjk5ft3.js → chunk-k5jvafmh.js} +1 -1
- package/dist/chunk-kckva77b.js +5 -0
- package/dist/{chunk-dxw8k6f1.js.map → chunk-kckva77b.js.map} +2 -2
- package/dist/{chunk-cz3szqhq.js → chunk-ke6tsnx1.js} +2 -2
- package/dist/{chunk-cz3szqhq.js.map → chunk-ke6tsnx1.js.map} +1 -1
- package/dist/{chunk-qq2yhtpp.js → chunk-kz5zcw6s.js} +2 -2
- package/dist/{chunk-qq2yhtpp.js.map → chunk-kz5zcw6s.js.map} +2 -2
- package/dist/{chunk-h7mcwfg5.js → chunk-nakfv7pa.js} +4 -4
- package/dist/{chunk-h7mcwfg5.js.map → chunk-nakfv7pa.js.map} +2 -2
- package/dist/chunk-nph4mm6k.js +4 -0
- package/dist/{chunk-jb2nst6v.js.map → chunk-nph4mm6k.js.map} +2 -2
- package/dist/{chunk-dwx2y7br.js → chunk-r07s2p1z.js} +4 -4
- package/dist/{chunk-dwx2y7br.js.map → chunk-r07s2p1z.js.map} +2 -2
- package/dist/chunk-teyphwr0.js +5 -0
- package/dist/{chunk-6rhebm18.js.map → chunk-teyphwr0.js.map} +2 -2
- package/dist/{chunk-agabw2w1.js → chunk-tkdxv6cq.js} +2 -2
- package/dist/{chunk-agabw2w1.js.map → chunk-tkdxv6cq.js.map} +1 -1
- package/dist/chunk-v094r7tz.js +6 -0
- package/dist/{chunk-05edp1zf.js.map → chunk-v094r7tz.js.map} +2 -2
- package/dist/{chunk-3xa807p3.js → chunk-v0t5dejz.js} +2 -2
- package/dist/{chunk-3xa807p3.js.map → chunk-v0t5dejz.js.map} +1 -1
- package/dist/{chunk-f4e7fh95.js → chunk-v7y8zm61.js} +3 -3
- package/dist/{chunk-f4e7fh95.js.map → chunk-v7y8zm61.js.map} +2 -2
- package/dist/{chunk-kv2ep453.js → chunk-vj1vt6qs.js} +18 -19
- package/dist/{chunk-kv2ep453.js.map → chunk-vj1vt6qs.js.map} +4 -8
- package/dist/{chunk-71m47kad.js → chunk-wxepr09t.js} +2 -2
- package/dist/{chunk-71m47kad.js.map → chunk-wxepr09t.js.map} +2 -2
- package/dist/{chunk-efp54183.js → chunk-x1g40y59.js} +1 -1
- package/dist/chunk-x5w7es67.js +4 -0
- package/dist/{chunk-s6e7cvek.js.map → chunk-x5w7es67.js.map} +2 -2
- package/dist/chunk-x67dm5ef.js +5 -0
- package/dist/{chunk-jdgvdddd.js.map → chunk-x67dm5ef.js.map} +2 -2
- package/dist/{chunk-fcqc3e3r.js → chunk-xnytbrda.js} +2 -2
- package/dist/{chunk-fcqc3e3r.js.map → chunk-xnytbrda.js.map} +1 -1
- package/dist/chunk-xska2hx3.js +4 -0
- package/dist/{chunk-hrrmxreg.js.map → chunk-xska2hx3.js.map} +2 -2
- package/dist/{chunk-ms8qd7da.js → chunk-yd6aqeyc.js} +2 -2
- package/dist/{chunk-ms8qd7da.js.map → chunk-yd6aqeyc.js.map} +1 -1
- package/dist/{chunk-bb3zvxsf.js → chunk-zacf5ph0.js} +2 -2
- package/dist/{chunk-bb3zvxsf.js.map → chunk-zacf5ph0.js.map} +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/database/DatabaseManager.d.ts.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +1 -1
- package/dist/facades/Storage.d.ts +1 -1
- package/dist/facades/Storage.d.ts.map +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +2 -2
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +2 -2
- package/dist/orm/corpus.d.ts.map +1 -1
- package/dist/orm/dialect/index.d.ts +32 -1
- package/dist/orm/dialect/index.d.ts.map +1 -1
- package/dist/orm/dialect/postgres.d.ts +14 -0
- package/dist/orm/dialect/postgres.d.ts.map +1 -1
- package/dist/orm/dialect/sqlite.d.ts +31 -0
- package/dist/orm/dialect/sqlite.d.ts.map +1 -1
- package/dist/orm/index.js +3 -3
- package/dist/orm/index.js.map +3 -3
- package/dist/orm/types.d.ts +82 -38
- package/dist/orm/types.d.ts.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +2 -2
- package/dist/services/email/drivers/ResendDriver.d.ts.map +1 -1
- package/dist/services/file-storage/drivers/S3Driver.d.ts +24 -1
- package/dist/services/file-storage/drivers/S3Driver.d.ts.map +1 -1
- package/dist/services/image-optimization/drivers/SharpDriver.d.ts.map +1 -1
- package/dist/services/index.js +9 -18
- package/dist/services/index.js.map +5 -99
- package/dist/services/rate-limiter/drivers/RedisRateLimiterDriver.d.ts.map +1 -1
- package/dist/services/redis/RedisManager.d.ts +19 -2
- package/dist/services/redis/RedisManager.d.ts.map +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/dist/services/router/htmlInsertionPoint.d.ts +64 -0
- package/dist/services/router/htmlInsertionPoint.d.ts.map +1 -0
- package/dist/services/router/streamQueryInjection.d.ts +10 -0
- package/dist/services/router/streamQueryInjection.d.ts.map +1 -1
- package/dist/support/sharp.d.ts +21 -0
- package/dist/support/sharp.d.ts.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-05edp1zf.js +0 -6
- package/dist/chunk-07t0dmdg.js +0 -4
- package/dist/chunk-1snh7yc4.js +0 -4
- package/dist/chunk-2pt6kyn9.js +0 -5
- package/dist/chunk-4qkzdyj7.js +0 -4
- package/dist/chunk-6rhebm18.js +0 -5
- package/dist/chunk-br8ten26.js +0 -4
- package/dist/chunk-c0wcsmpj.js +0 -4
- package/dist/chunk-dxw8k6f1.js +0 -5
- package/dist/chunk-efsk1wy0.js +0 -5
- package/dist/chunk-f13f68c0.js +0 -5
- package/dist/chunk-hk067634.js +0 -4
- package/dist/chunk-hrrmxreg.js +0 -4
- package/dist/chunk-jb2nst6v.js +0 -4
- package/dist/chunk-jdgvdddd.js +0 -5
- package/dist/chunk-k8endm5j.js +0 -9
- package/dist/chunk-n382ygnp.js +0 -81
- package/dist/chunk-r9z5rrk0.js +0 -4
- package/dist/chunk-s6e7cvek.js +0 -4
- /package/dist/{chunk-pgjk5ft3.js.map → chunk-k5jvafmh.js.map} +0 -0
- /package/dist/{chunk-efp54183.js.map → chunk-x1g40y59.js.map} +0 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../facades/Facade.ts", "../services/pubsub/BroadcastManager.ts", "../facades/Broadcast.ts", "../facades/Auth.ts", "../facades/Lang.ts", "../facades/Storage.ts", "../support/sharp.ts", "../services/file-storage/drivers/FileStorageDriver.ts", "../services/file-storage/drivers/FileSystemDriver.ts", "../services/file-storage/config.ts", "../services/file-storage/FilesystemManager.ts", "../utils/omitNullishValues.ts", "../services/router/ServerQueryStore.ts", "../client/QueryError.ts", "../auth/AuthController.ts", "../auth/routes.ts", "../i18n/I18nRouter.ts", "../services/image-optimization/drivers/ImageOptimizationDriver.ts", "../services/image-optimization/drivers/SharpDriver.ts", "../services/image-optimization/config.ts", "../services/image-optimization/ImageManager.ts", "../services/logging/LogManager.ts", "../services/logging/LoggingRouter.ts", "../services/middleware/MiddlewareRegistry.ts", "../services/router/config.ts", "../services/router/createFlatApiRoutes.ts", "../services/router/createFlatViewRoutes.ts", "../../../node_modules/.bun/urlpattern-polyfill@10.1.0/node_modules/urlpattern-polyfill/dist/urlpattern.js", "../services/router/matchViewRoute.ts", "../services/router/planPartialRender.ts", "../utils/partialRender.ts", "../services/router/ViewRouteDispatcher.ts", "../services/router/createRouteManifest.ts", "../services/router/createComponentTree.ts", "../client/helpers/flattenComponentTree.ts", "../facades/Log.ts", "../services/kernel-id/KernelId.ts", "../services/router/htmlInsertionPoint.ts", "../services/router/streamQueryInjection.ts", "../services/router/shellContentReport.ts", "../services/router/routePayloadStream.ts", "../services/router/ApiRouteDispatcher.ts", "../services/router/serverQueryFetcher.ts", "../facades/Prefetch.ts", "../facades/Url.ts", "../facades/Meta.ts", "../facades/Cookie.ts", "../services/redis/RedisManager.ts", "../facades/Redis.ts", "../facades/RateLimiter.ts", "../facades/DB.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { ServiceToken } from \"../container/Container\";\nimport { app } from \"../foundation/app\";\n\n/**\n * Base for the facades that front a container binding. A subclass names the\n * service it proxies with `getFacadeAccessor()` and reaches the live instance\n * through `this.getFacadeRoot()`, so the binding is resolved per call against\n * the Application for the current async context — never captured at module\n * load, which is what makes a facade swappable in tests.\n *\n * Two deliberate divergences from `Illuminate\\Support\\Facades\\Facade`:\n *\n * 1. No `__callStatic`. TypeScript has no typed equivalent, and a Proxy would\n * erase the very signatures that make these facades worth having. Subclasses\n * therefore declare explicit statics that forward to `getFacadeRoot()`.\n *\n * 2. `getFacadeAccessor()` is public, not protected. `getFacadeRoot()` types\n * its `this` structurally in order to infer the service type from the\n * accessor's return, and a protected static is not structurally assignable\n * to that.\n *\n * Facades that resolve nothing from the container — Cookie, Redirect, Url,\n * Meta — do not extend this class.\n */\nexport abstract class Facade {\n static getFacadeAccessor(): ServiceToken<any> {\n throw new Error(\n `Facade [${this.name}] does not implement getFacadeAccessor().`,\n );\n }\n\n static getFacadeRoot<T>(this: {\n getFacadeAccessor(): ServiceToken<T>;\n }): T {\n return app(this.getFacadeAccessor());\n }\n}\n",
|
|
6
|
+
"import type { ServerWebSocket } from \"bun\";\nimport type { BroadcastConfig } from \"./config\";\nimport type { PublishArgs } from \"./types\";\nimport { AsyncLocalStorage } from \"async_hooks\";\n\ntype PublishCallback = (...args: PublishArgs) => void;\n\nexport class BroadcastManager {\n static token = \"broadcast\";\n\n publishCb: PublishCallback;\n context = new AsyncLocalStorage<{\n headers: Headers;\n cookies: Map<string, string>;\n }>();\n\n constructor(public config: Required<BroadcastConfig>) {}\n\n get channels() {\n return this.config.channels;\n }\n\n onPublish(cb: PublishCallback) {\n this.publishCb = cb;\n }\n\n publish(...args: PublishArgs) {\n const [topic, data, compress] = args;\n this.publishCb(topic, data, compress);\n }\n\n async handleMessage(\n ws: ServerWebSocket<{ headers: Headers }>,\n message: string | Buffer,\n ) {\n const messageData = JSON.parse(message as string);\n if (messageData.type === \"subscribe\") {\n const sortedChannels = Object.entries(this.channels).sort(\n ([keyA], [keyB]) => keyA.length - keyB.length,\n );\n for (const [pathname, Channel] of sortedChannels) {\n const urlPattern = new URLPattern({ pathname });\n if (urlPattern.test({ pathname: messageData.topic })) {\n const params = urlPattern.exec({ pathname: messageData.topic })\n ?.pathname.groups!;\n const instance = new Channel();\n const canSubscribe = await instance.subscribe.call(instance, params);\n if (canSubscribe) {\n ws.subscribe(messageData.topic);\n }\n\n break;\n }\n }\n }\n if (messageData.type === \"broadcast\") {\n ws.publish(\n messageData.topic,\n JSON.stringify({ topic: messageData.topic, data: messageData.payload }),\n );\n }\n if (messageData.type === \"unsubscribe\") {\n ws.unsubscribe(messageData.topic);\n }\n }\n\n run(headers: Headers, fn: VoidFunction) {\n const cookie = headers.get(\"Cookie\");\n const cookies = new Map();\n if (cookie) {\n const cookieArray = cookie.split(\";\");\n for (const c of cookieArray) {\n const [key, value] = c.split(\"=\");\n cookies.set(key.trim(), value.trim());\n }\n }\n this.context.run({ headers, cookies }, fn);\n }\n}\n",
|
|
7
|
+
"import { BroadcastManager } from \"../services/pubsub/BroadcastManager\";\nimport { applyParams } from \"../utils/applyParams\";\nimport { Facade } from \"./Facade\";\n\nexport class Broadcast extends Facade {\n static getFacadeAccessor() {\n return BroadcastManager;\n }\n\n static channel<T>(route: T, params: any) {\n const broadcast = this.getFacadeRoot();\n const channel = broadcast.channels[route as any];\n if (!channel) {\n console.error(`Channel ${route} not found`);\n return {\n publish: () => {},\n };\n }\n const instance = new channel();\n return {\n publish: (\n data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,\n compress: boolean = false,\n ) => {\n const topic = applyParams(route as any, params);\n broadcast.publish(\n topic,\n JSON.stringify({ topic, data: instance.publish(data) }),\n compress,\n );\n },\n };\n }\n}\n",
|
|
8
|
+
"import type { User } from \"../auth/types\";\nimport { AuthManager } from \"../auth/AuthManager\";\nimport {\n AuthenticationError,\n InsufficientPermissionsError,\n} from \"../http/errors\";\nimport { RequestContext } from \"../http/requestContext\";\nimport { Broadcast } from \"./Broadcast\";\nimport { Facade } from \"./Facade\";\n\nexport class Auth extends Facade {\n static getFacadeAccessor() {\n return AuthManager;\n }\n\n static async user(): Promise<User> {\n const requestContextStore = RequestContext.getStore();\n const broadcastingContextStore =\n Broadcast.getFacadeRoot().context.getStore();\n\n let accessToken = \"\";\n let userAgent = \"\";\n\n if (requestContextStore?.req) {\n accessToken = requestContextStore.req.cookies.get(\"access_token\");\n userAgent = requestContextStore.req.headers.get(\"User-Agent\");\n }\n\n if (broadcastingContextStore?.cookies) {\n userAgent = broadcastingContextStore.headers.get(\"User-Agent\");\n accessToken = broadcastingContextStore.cookies.get(\"access_token\");\n }\n\n let user = requestContextStore?.user;\n\n if (!user) {\n const container = this.getFacadeRoot();\n // TODO: extend session if its expired\n const session = await container.getSession(accessToken, userAgent);\n\n user = session?.user;\n requestContextStore?.setUser(user);\n }\n\n if (user) {\n return user;\n }\n throw new AuthenticationError();\n }\n\n static async guard(\n fn: (user: User) => Promise<boolean> | boolean,\n ): Promise<void> {\n const user = await Auth.user();\n\n if (!user) {\n throw new InsufficientPermissionsError();\n }\n\n try {\n if (!(await fn(user))) {\n throw new InsufficientPermissionsError();\n }\n } catch (err) {\n throw new InsufficientPermissionsError();\n }\n }\n\n static async guardSafe(\n fn: (user: User) => Promise<boolean> | boolean,\n ): Promise<boolean> {\n const user = await Auth.user();\n\n if (!user) {\n return false;\n }\n try {\n return await fn(user);\n } catch (err) {\n return false;\n }\n }\n\n static async authenticate(email: string) {\n const container = this.getFacadeRoot();\n return await container.authenticate(email);\n }\n\n static async createMagicLink(email: string) {\n const container = this.getFacadeRoot();\n return await container.createMagicLinkToken(email);\n }\n}\n",
|
|
9
|
+
"import { Translator } from \"../i18n/Translator\";\nimport { RequestContext } from \"../http/requestContext\";\nimport { Facade } from \"./Facade\";\n\nexport class Lang extends Facade {\n static getFacadeAccessor() {\n return Translator;\n }\n\n static getSupportedLocales() {\n return this.getFacadeRoot().supportedLocales;\n }\n\n static getDefaultLocale() {\n return this.getFacadeRoot().defaultLocale;\n }\n\n static locale() {\n const translator = this.getFacadeRoot();\n const requestStore = RequestContext.getStore();\n if (requestStore) {\n // The locale this request actually resolved to, when something has\n // resolved one. `detectLocale` re-reads the *incoming* cookie and\n // `accept-language`, so it does not see `ctx.setLocale()` or the URL\n // locale segment: a visitor whose cookie says `en-US` opening `/tr/about`\n // gets a Turkish page whose server-rendered strings — flash messages,\n // breadcrumbs, an order-confirmation email — come back in English, with\n // nothing raised. Detection stays the fallback for requests where no\n // locale was resolved, which is every API route.\n return requestStore.locale ?? translator.detectLocale(requestStore.req);\n }\n\n return translator.defaultLocale;\n }\n\n static setLocale(locale = Lang.locale()) {\n const translator = this.getFacadeRoot();\n let _locale = locale;\n if (!translator.supportedLocales.includes(locale)) {\n _locale = translator.defaultLocale;\n }\n\n const store = RequestContext.getStore();\n\n store.setCookie(\"i18n-locale\", _locale, {\n expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),\n secure: false,\n httpOnly: false,\n });\n\n // The cookie is for the *next* request. Without also recording it here,\n // `Lang.locale()` would keep answering with the locale this request arrived\n // under — so setting the locale would not change what the rest of the\n // request renders in, which is the one thing calling it implies.\n store.setLocale(_locale);\n\n return _locale;\n }\n}\n",
|
|
10
|
+
"//@ts-ignore - type-only; the module itself is loaded on first use by `metadata()`.\nimport type sharp from \"sharp\";\n\nimport { Buffer } from \"node:buffer\";\nimport { loadSharp } from \"../support/sharp\";\nimport type { Prettify } from \"../utils/type\";\n\nimport { RequestContext } from \"../http/requestContext\";\nimport type { ByteRange } from \"../http/range\";\nimport type {\n PutFileParams,\n ReadFileParams,\n ReadResult,\n} from \"../services/file-storage/drivers/types\";\nimport { FilesystemManager } from \"../services/file-storage/FilesystemManager\";\nimport { Facade } from \"./Facade\";\n\ntype Metadata = Prettify<sharp.Metadata>;\n\nexport class Storage extends Facade {\n static getFacadeAccessor() {\n return FilesystemManager;\n }\n\n static async put(params: PutFileParams | Blob) {\n return this.getFacadeRoot().driver.put(params);\n }\n\n static async metadata(obj: Blob | File): Promise<Partial<Metadata>> {\n const buffer = Buffer.from(await obj.arrayBuffer());\n // Outside the catch: the empty object below means \"this blob is not an\n // image sharp can read\", and a missing `sharp` install must not be able to\n // hide behind it.\n const sharp = await loadSharp(\"Storage.metadata()\");\n try {\n return await sharp(buffer).metadata();\n } catch {\n return {};\n }\n }\n\n static async fetch(params: ReadFileParams | string) {\n return this.getFacadeRoot().driver.fetch(params);\n }\n\n /**\n * Reads an object as bytes plus metadata, pushing any byte range down to the\n * storage backend so a seek transfers one window rather than the whole file.\n *\n * The range is resolved in this order: an explicit `options.range`, then a\n * `range` on `params`, then the in-flight request's `Range` header when this\n * is called inside a `this.stream()` route. Pass `{ range: null }` to force a\n * full read inside a stream route.\n */\n static async read(\n params: ReadFileParams | string,\n options: { range?: ByteRange | null } = {},\n ): Promise<ReadResult> {\n const base: ReadFileParams =\n typeof params === \"string\" ? { name: params } : { ...params };\n\n const range =\n \"range\" in options\n ? (options.range ?? null)\n : base.range !== undefined\n ? base.range\n : (RequestContext.getStore()?.rangeRequest ?? null);\n\n return this.getFacadeRoot().driver.read({\n ...base,\n range,\n });\n }\n static list(folder: string) {\n return this.getFacadeRoot().driver.list(folder);\n }\n static delete() {}\n}\n",
|
|
11
|
+
"// @ts-ignore - `sharp` is a peer dependency; only its types are wanted here.\nimport type sharpNamespace from \"sharp\";\n\n/**\n * `sharp`, imported on first use rather than at module load.\n *\n * Three modules need it — the `Sharp` optimization driver, the `Storage` facade\n * and the OG-image branch of `ViewRouteDispatcher` — and all three are reachable\n * from the `gemi/services` and `gemi/facades` barrels, which are also the only\n * door an application has to `CronJob`, `Job`, `DB` and `Lang`. A static import\n * made every one of those imports load a native binary (#403).\n *\n * `sharp` is the only one of the four that can be genuinely absent — it is a\n * peer dependency, so an install can skip its platform binary — which is why\n * the failure gets a message naming the caller rather than a bare resolution\n * error. `usedBy` is that name, written as the caller reads in a stack trace.\n *\n * No memo: the module registry already caches a resolved `import()`, and\n * caching the *failure* would make every later call report the first call's\n * stack instead of its own.\n */\nexport async function loadSharp(usedBy: string): Promise<typeof sharpNamespace> {\n try {\n // @ts-ignore - peer dependency, resolved out of the application's own tree\n return (await import(\"sharp\")).default;\n } catch (error) {\n throw new Error(\n `${usedBy} requires the 'sharp' package. Install it with \\`bun add sharp\\`.`,\n { cause: error },\n );\n }\n}\n",
|
|
12
|
+
"import { FileNotFoundError } from \"../../../http/errors\";\nimport type {\n IFileStorageDriver,\n PutFileParams,\n ReadFileParams,\n ReadResult,\n} from \"./types\";\n\nexport abstract class FileStorageDriver implements IFileStorageDriver {\n abstract fetch(params: ReadFileParams | string): Promise<Response>;\n abstract put(params: PutFileParams | Blob): Promise<string>;\n abstract list(folder: string): Promise<any>;\n\n /**\n * Default `read()` for drivers that only implement `fetch()`.\n *\n * Deliberately not abstract: every driver written before `read()` existed\n * keeps compiling and gains working range support for free. It is not\n * *efficient* though — to serve a range it buffers the whole object so the\n * framework can slice it, which saves no bandwidth from the backend. Any\n * driver whose backend can range natively should override this.\n */\n async read(input: ReadFileParams | string): Promise<ReadResult> {\n const params = typeof input === \"string\" ? { name: input } : input;\n const response = await this.fetch({\n name: params.name,\n bucket: params.bucket,\n });\n\n if (!response.ok) {\n throw new FileNotFoundError(params.name);\n }\n\n const type =\n response.headers.get(\"Content-Type\") ?? \"application/octet-stream\";\n const etag = response.headers.get(\"ETag\") ?? undefined;\n const lastModifiedHeader = response.headers.get(\"Last-Modified\");\n const lastModified = lastModifiedHeader\n ? new Date(lastModifiedHeader)\n : undefined;\n\n if (params.range) {\n const blob = await response.blob();\n return {\n body: blob,\n start: 0,\n end: blob.size - 1,\n total: blob.size,\n // The range was not applied by the backend. Reporting `false` hands\n // the slicing to `createStreamResponse`, which has the total in hand.\n partial: false,\n type,\n etag,\n lastModified,\n name: params.name,\n };\n }\n\n const contentLength = Number(response.headers.get(\"Content-Length\"));\n const total = Number.isFinite(contentLength) ? contentLength : 0;\n\n return {\n body: response.body,\n start: 0,\n end: total - 1,\n total,\n partial: false,\n type,\n etag,\n lastModified,\n name: params.name,\n };\n }\n\n /**\n * Total size of an object. Used to resolve suffix ranges on backends without\n * native suffix support, and to report the total on a 416. Override with a\n * HEAD-style request wherever one is available.\n */\n async size(params: ReadFileParams | string): Promise<number> {\n const name = typeof params === \"string\" ? params : params.name;\n const bucket = typeof params === \"string\" ? undefined : params.bucket;\n const response = await this.fetch({ name, bucket });\n if (!response.ok) {\n throw new FileNotFoundError(name);\n }\n const contentLength = Number(response.headers.get(\"Content-Length\"));\n if (Number.isFinite(contentLength)) {\n await response.body?.cancel();\n return contentLength;\n }\n return (await response.blob()).size;\n }\n}\n",
|
|
13
|
+
"import type { PutFileParams, ReadFileParams, ReadResult } from \"./types\";\nimport { FileStorageDriver } from \"./FileStorageDriver\";\nimport { readdir } from \"fs/promises\";\nimport { resolveRange } from \"../../../http/range\";\nimport {\n FileNotFoundError,\n RangeNotSatisfiableError,\n} from \"../../../http/errors\";\n\nexport class FileSystemDriver extends FileStorageDriver {\n constructor(private folderPath: string = `${process.env.ROOT_DIR}/storage`) {\n super();\n }\n\n async put(params: PutFileParams | Blob) {\n let body: Blob | File | Buffer;\n let name: string;\n\n if (params instanceof Blob) {\n body = params;\n name = `${Bun.randomUUIDv7()}.${params.type.split(\"/\")[1].split(\";\")[0]}`;\n } else {\n body = params.body;\n name = params.name;\n }\n\n const buffer =\n body instanceof Buffer\n ? body\n : body instanceof Blob || body instanceof File\n ? Buffer.from(await body.arrayBuffer())\n : \"\";\n\n const path = `${this.folderPath}/${name}`;\n\n await Bun.write(path, buffer as any);\n\n return name;\n }\n\n async fetch(params: ReadFileParams | string) {\n let bucket = process.env.BUCKET_NAME;\n let name: string | undefined;\n\n if (typeof params === \"string\") {\n name = params;\n } else {\n bucket = params.bucket ?? bucket;\n name = params.name;\n }\n\n if (!name) {\n throw new Error(\"Object name has to be specified\");\n }\n\n const path = `${this.folderPath}/${name}`;\n const file = Bun.file(path);\n const result = Bun.file(path).stream();\n const date = new Date(file.lastModified).toUTCString();\n\n return new Response(result, {\n headers: {\n \"Content-Type\": file.type,\n \"Content-Length\": String(file.size),\n \"Cache-Control\": \"private, max-age=12000, must-revalidate\",\n // TODO: fix this.\n \"Last-Modified\": date,\n },\n });\n }\n\n async read(input: ReadFileParams | string): Promise<ReadResult> {\n const params = typeof input === \"string\" ? { name: input } : input;\n const { name, range = null } = params;\n\n if (!name) {\n throw new Error(\"Object name has to be specified\");\n }\n\n const file = Bun.file(`${this.folderPath}/${name}`);\n\n // `Bun.file()` is lazy. Without this the response commits with a 200 and\n // the ENOENT only surfaces once the stream is pulled, as an unhandled\n // rejection with the status already on the wire.\n if (!(await file.exists())) {\n throw new FileNotFoundError(name);\n }\n\n const total = file.size;\n const resolved = range ? resolveRange(range, total) : null;\n\n if (range && !resolved) {\n throw new RangeNotSatisfiableError(total);\n }\n\n const start = resolved?.start ?? 0;\n const end = resolved ? resolved.end : total - 1;\n\n return {\n // A BunFile slice stays lazy and keeps a known size, so Bun can send it\n // with a real Content-Length instead of falling back to chunked.\n body: resolved ? file.slice(start, end + 1) : file,\n start,\n end,\n total,\n partial: Boolean(resolved),\n type: file.type || \"application/octet-stream\",\n lastModified: new Date(file.lastModified),\n name,\n };\n }\n\n async size(params: ReadFileParams | string) {\n const name = typeof params === \"string\" ? params : params.name;\n const file = Bun.file(`${this.folderPath}/${name}`);\n if (!(await file.exists())) {\n throw new FileNotFoundError(name);\n }\n return file.size;\n }\n\n async list() {\n const files = await readdir(this.folderPath);\n\n return files;\n }\n}\n",
|
|
14
|
+
"import type { FileStorageDriver } from \"./drivers/FileStorageDriver\";\nimport { FileSystemDriver } from \"./drivers/FileSystemDriver\";\n\n// Config key: `filesystem`. Derived from `FileStorageServiceProvider`.\nexport interface FilesystemConfig {\n driver?: FileStorageDriver;\n}\n\nexport function defineFilesystemConfig(\n config: FilesystemConfig,\n): FilesystemConfig {\n return config;\n}\n\nexport function filesystemConfigDefaults(): Required<FilesystemConfig> {\n return {\n driver: new FileSystemDriver(),\n };\n}\n",
|
|
15
|
+
"import type { FileStorageDriver } from \"./drivers/FileStorageDriver\";\nimport { filesystemConfigDefaults, type FilesystemConfig } from \"./config\";\n\nexport class FilesystemManager {\n static token = \"filesystem\";\n\n readonly driver: FileStorageDriver;\n\n constructor(config: FilesystemConfig = {}) {\n this.driver = config.driver ?? filesystemConfigDefaults().driver;\n }\n}\n",
|
|
16
|
+
"export function omitNullishValues<T>(input: T) {\n return Object.fromEntries(\n Object.entries(input).filter(([, value]) => {\n return value !== null && value !== undefined;\n }),\n ) as T;\n}\n",
|
|
17
|
+
"import { applyParams } from \"../../utils/applyParams\";\nimport { omitNullishValues } from \"../../utils/omitNullishValues\";\n\nexport type ServerQueryOptions = {\n params?: Record<string, any>;\n search?: Record<string, string | number | boolean | null>;\n};\n\nexport type ServerQuerySource = \"prefetch\" | \"render\";\n\nexport interface ServerQueryEntry {\n /** Concrete path, params applied — `/posts/123`, not `/posts/:id`. */\n path: string;\n /** The route pattern the query was declared with — `/posts/:id`. */\n patternPath: string;\n /** Sorted search params — the same variant key `useQuery` derives. */\n variantKey: string;\n /**\n * How many ms into the render this entry was discovered, when that was late\n * enough to mean it sat under a suspended segment. Set at `ensure`, acted\n * on at settle — the hint reports the resolved payload size, which only\n * exists once the fetch lands.\n */\n lateBy?: number;\n status: \"pending\" | \"resolved\" | \"rejected\";\n data?: any;\n error?: any;\n /**\n * Settles (always resolves, never rejects — a rejection would surface as an\n * unhandled rejection in every render attempt React discards) only after the\n * result is recorded AND the settle listener has run. A suspended server\n * render woken by this promise can therefore rely on the entry's data being\n * readable and its payload script being queued ahead of React's own chunks.\n */\n promise: Promise<void>;\n source: ServerQuerySource;\n /** ms since the request started. */\n startedAt: number;\n settledAt?: number;\n}\n\nexport type ServerQueryFetcher = (\n patternPath: string,\n params: Record<string, any>,\n searchParams: URLSearchParams,\n) => Promise<any>;\n\n/** One query's timings in a `StreamSummary` — a serialization of its entry. */\nexport interface StreamQuerySummary {\n path: string;\n variantKey: string;\n /** ms since the request started. */\n startedAt: number;\n /** Absent when the stream closed (deadline) with the query still pending. */\n settledAt?: number;\n status: \"pending\" | \"resolved\" | \"rejected\";\n source: ServerQuerySource;\n}\n\n/**\n * What `onStreamComplete` receives when the response body actually closes —\n * the numbers an APM span wrapped around the *handler* gets wrong under\n * streaming, where the handler returns at time-to-shell while the body keeps\n * streaming.\n */\nexport interface StreamSummary {\n /** ms from request start to the response's first byte. */\n shellAt: number;\n /** ms from request start to the last chunk — when the body closed. */\n settledAt: number;\n /** The stream deadline cut rendering short. */\n aborted: boolean;\n queries: StreamQuerySummary[];\n}\n\n/**\n * When a render-discovered query starts this long after the render began, it\n * was blocked behind another suspended segment (or conditional data) — the\n * fetch that could have been overlapping wasn't. Anything under this is just\n * first-pass discovery, which needs no declaration.\n */\nconst LATE_DISCOVERY_THRESHOLD_MS = 50;\n\n/**\n * Per-request registry of every server-side query — the streaming-SSR twin of\n * the client's `QueryResource`.\n *\n * Fetches decouple from render: `Query.prefetch` starts its request the\n * moment it is called (in the route handler, before any rendering), and a\n * `useQuery` the render discovers starts one on the spot. Every entry is\n * inflight-deduped by path + variant, so the request total is always\n * `max(query times)`, never a sum — a suspended layout does not delay the\n * fetch of the leaf below it.\n */\nexport class ServerQueryStore {\n private entries = new Map<string, ServerQueryEntry>();\n private settleListener: ((entry: ServerQueryEntry) => void) | null = null;\n private failListener: ((entry: ServerQueryEntry) => void) | null = null;\n /** ms to the response's first byte — set only for progressive responses. */\n private shellAt: number | null = null;\n /** Entries settled before the stream injector subscribed. */\n private settledBacklog: ServerQueryEntry[] = [];\n /** Variants already serialized into `__GEMI_DATA__` — not streamed again. */\n private shipped = new Set<string>();\n private requestStartedAt = performance.now();\n private renderStartedAt: number | null = null;\n /** Set by `Query.noPrefetch()` — the route declared its lack of priming intentional. */\n private discoveryHintsMuted = false;\n\n constructor(private fetcher: ServerQueryFetcher) {}\n\n private elapsed() {\n return Math.round(performance.now() - this.requestStartedAt);\n }\n\n private keyFor(path: string, variantKey: string) {\n return [path, variantKey].filter((s) => s.length > 0).join(\"?\");\n }\n\n /** Marks the point streaming render begins — the late-discovery baseline. */\n markRenderStart() {\n if (this.renderStartedAt === null) {\n this.renderStartedAt = performance.now();\n }\n }\n\n /**\n * Marks the response's first byte — time-to-shell. Only progressive\n * responses mark it; a response that never does (settled documents for bots\n * and `no-stream` routes, `.json` navigation payloads) reports\n * `shellAt === settledAt` in its summary, because its body has no\n * shell-then-stream phase to distinguish.\n */\n markShell() {\n if (this.shellAt === null) {\n this.shellAt = this.elapsed();\n }\n }\n\n /**\n * The stream lifecycle summary for `onStreamComplete`. `settledAt` is \"now\",\n * so call it at the moment the response body actually closes.\n */\n summarize(aborted: boolean): StreamSummary {\n const settledAt = this.elapsed();\n return {\n shellAt: this.shellAt ?? settledAt,\n settledAt,\n aborted,\n queries: Array.from(this.entries.values(), (entry) => ({\n path: entry.path,\n variantKey: entry.variantKey,\n startedAt: entry.startedAt,\n settledAt: entry.settledAt,\n status: entry.status,\n source: entry.source,\n })),\n };\n }\n\n /**\n * Single-subscriber rejection feed. A query that rejects during the\n * streamed render never throws the handler — React client-renders the\n * segment and moves on — so without this the failure is invisible to\n * `onRequestFail`-style error reporting. Fires once per rejected entry\n * (`ensure` dedupes, so a query rejects at most once per request), before\n * the entry's promise wakes any awaiter.\n */\n onQueryFail(listener: (entry: ServerQueryEntry) => void) {\n this.failListener = listener;\n }\n\n /**\n * `Query.noPrefetch()` — the route's handler primes nothing on purpose\n * (heavy payloads it would rather cache-then-revalidate, for instance), so\n * late-discovery hints are noise for this request.\n */\n muteDiscoveryHints() {\n this.discoveryHintsMuted = true;\n }\n\n /**\n * The late-discovery hint (#287): reported at settle time, not discovery\n * time, so it can state the resolved payload size — the single number that\n * decides whether priming is a win (it is serialized into, and awaited by,\n * every client-navigation payload for the route) or a regression. The\n * observation is asserted; the remedies are offered, because \"discovered\n * late\" does not imply \"should be prefetched\" — the query may not belong on\n * the route at all.\n */\n private maybeLogLateDiscovery(entry: ServerQueryEntry) {\n if (!entry.lateBy || this.discoveryHintsMuted) return;\n if (entry.status !== \"resolved\") return; // failures have their own visibility\n if (process.env.NODE_ENV === \"production\") return;\n\n let size = \"\";\n try {\n const bytes = JSON.stringify(entry.data)?.length ?? 0;\n size = bytes >= 1024 ? `${(bytes / 1024).toFixed(1)} kB` : `${bytes} B`;\n } catch {\n size = \"an unserializable payload\";\n }\n const duration = (entry.settledAt ?? 0) - entry.startedAt;\n const searchHint = entry.variantKey\n ? `, { search: ${JSON.stringify(Object.fromEntries(new URLSearchParams(entry.variantKey)))} }`\n : \"\";\n\n console.warn(\n `[gemi] useQuery(\"${entry.patternPath}\") was discovered ${entry.lateBy}ms into the ` +\n `server render — under a suspended segment, so its fetch (${duration}ms, resolved ` +\n `${size}) could not overlap the others. It still streamed. If the query belongs on ` +\n `this route, \\`Query.prefetch(\"${entry.patternPath}\"${searchHint})\\` in the view ` +\n `handler starts it at request time — but note prefetched data is also re-fetched and ` +\n `streamed into every client-side navigation payload for the route, even when the ` +\n `client already holds it, so weigh that bandwidth against the ${size}. If the data ` +\n `is only needed conditionally (a closed popover, a hidden tab), \\`{ lazy: true }\\` + ` +\n `\\`trigger()\\` avoids running it here at all. \\`Query.noPrefetch()\\` in the handler ` +\n `marks the omission intentional and silences this hint for the route.`,\n );\n }\n\n read(path: string, variantKey: string): ServerQueryEntry | undefined {\n return this.entries.get(this.keyFor(path, variantKey));\n }\n\n /**\n * The single entry point for starting (or joining) a server-side query.\n * Callable from the route-handler phase (`Query.prefetch` / `Query.instant`)\n * and from the render phase (`useQuery` on the server) — React discards and\n * retries suspended renders, so idempotence per path + variant is load-bearing.\n */\n ensure(\n patternPath: string,\n options: ServerQueryOptions = {},\n source: ServerQuerySource = \"render\",\n ): ServerQueryEntry {\n const params = options.params ?? {};\n const searchParams = new URLSearchParams(\n omitNullishValues((options.search ?? {}) as Record<string, string>),\n );\n searchParams.delete(\"json\");\n searchParams.sort();\n\n const path = applyParams(patternPath, params);\n const variantKey = searchParams.toString();\n const key = this.keyFor(path, variantKey);\n\n const existing = this.entries.get(key);\n if (existing) return existing;\n\n let lateBy: number | undefined;\n if (source === \"render\" && this.renderStartedAt !== null) {\n const delay = Math.round(performance.now() - this.renderStartedAt);\n if (delay > LATE_DISCOVERY_THRESHOLD_MS) {\n lateBy = delay;\n }\n }\n\n let settle!: () => void;\n const promise = new Promise<void>((resolve) => {\n settle = resolve;\n });\n\n const entry: ServerQueryEntry = {\n path,\n patternPath,\n variantKey,\n lateBy,\n status: \"pending\",\n promise,\n source,\n startedAt: this.elapsed(),\n };\n this.entries.set(key, entry);\n\n this.fetcher(patternPath, params, searchParams)\n .then(\n (data) => {\n entry.status = \"resolved\";\n entry.data = data;\n },\n (error) => {\n entry.status = \"rejected\";\n entry.error = error;\n },\n )\n .then(() => {\n entry.settledAt = this.elapsed();\n this.maybeLogLateDiscovery(entry);\n if (entry.status === \"rejected\" && this.failListener) {\n this.failListener(entry);\n }\n // Listener first, wake second: the payload script must be queued for\n // injection before React resumes the suspended segment, so the data\n // always precedes the segment's reveal in the stream.\n if (this.settleListener) {\n this.settleListener(entry);\n } else {\n this.settledBacklog.push(entry);\n }\n settle();\n });\n\n return entry;\n }\n\n /**\n * Everything currently registered, settled — including entries added while\n * waiting. The non-streaming paths (`.json` route data responses) sit on\n * this to keep their all-data-in-one-payload contract.\n */\n async allSettled(): Promise<void> {\n let count = 0;\n while (count !== this.entries.size) {\n count = this.entries.size;\n await Promise.all(Array.from(this.entries.values(), (e) => e.promise));\n }\n }\n\n /**\n * Resolved data in `prefetchedData` shape — `{ path: { variantKey: data } }`.\n * Marks what it returns as shipped so the stream injector skips it.\n */\n snapshotResolved(): Record<string, Record<string, any>> {\n const snapshot: Record<string, Record<string, any>> = {};\n for (const [key, entry] of this.entries) {\n if (entry.status !== \"resolved\") continue;\n this.shipped.add(key);\n snapshot[entry.path] ??= {};\n snapshot[entry.path][entry.variantKey] = entry.data;\n }\n return snapshot;\n }\n\n /**\n * Single-subscriber settle feed for the stream injector. Entries that\n * settled before subscription are replayed, minus anything a snapshot\n * already shipped.\n */\n onSettle(listener: (entry: ServerQueryEntry) => void) {\n this.settleListener = (entry) => {\n if (this.shipped.has(this.keyFor(entry.path, entry.variantKey))) return;\n listener(entry);\n };\n const backlog = this.settledBacklog;\n this.settledBacklog = [];\n for (const entry of backlog) {\n this.settleListener(entry);\n }\n }\n}\n",
|
|
18
|
+
"/**\n * An HTTP failure from a query endpoint, in a shape an error boundary can\n * work with. `resolveVariant` used to store the parsed response body as the\n * error; boundaries expect an `Error`, so the body moves to a field.\n */\nexport class QueryError extends Error {\n constructor(\n public path: string,\n public variantKey: string,\n public status: number,\n public body: any,\n ) {\n super(\n typeof body?.message === \"string\"\n ? body.message\n : `Request to /api${path} failed with status ${status}`,\n );\n this.name = \"QueryError\";\n }\n}\n",
|
|
19
|
+
"import { Temporal } from \"temporal-polyfill\";\n\nimport { Controller } from \"../http/Controller\";\nimport { HttpRequest } from \"../http/HttpRequest\";\nimport { ValidationError } from \"../http\";\nimport { AuthorizationError } from \"../http/errors\";\nimport { Auth } from \"../facades\";\nimport { app } from \"../foundation/app\";\nimport { Translator } from \"../i18n/Translator\";\nimport type { Invitation, User } from \"./types\";\nimport { AuthManager } from \"./AuthManager\";\n\nclass SignInRequest extends HttpRequest<\n {\n email: string;\n password: string;\n },\n Record<string, string>\n> {\n schema = {\n email: {\n required: \"Email is required\",\n string: \"Invalid email\",\n email: \"Invalid email\",\n },\n password: {\n required: \"Password is required\",\n },\n };\n}\n\nclass ForgotPasswordRequest extends HttpRequest<\n {\n email: string;\n },\n Record<string, string>\n> {\n schema = {\n email: {\n required: \"Email is required\",\n email: \"Invalid email\",\n },\n };\n}\n\nclass ResetPasswordRequest extends HttpRequest<\n {\n password: string;\n token: string;\n },\n Record<string, string>\n> {\n schema = {\n password: {\n required: \"Password is required\",\n password: \"Invalid password\",\n },\n };\n}\n\nexport class AuthController extends Controller {\n async me() {\n const user = await Auth.user();\n\n if (!user) {\n throw new AuthorizationError();\n }\n\n return user;\n }\n\n async verifyEmail(req = new HttpRequest<{ token: string }>()) {\n const input = await req.input();\n const { userProvider } = app(AuthManager);\n\n const user = await userProvider.findUserByVerificationToken(\n input.get(\"token\"),\n );\n\n if (!user) {\n return { email: null };\n }\n\n await userProvider.verifyUser(user.email);\n\n return {\n email: user.email,\n };\n }\n\n async signInWithMagicLink(req = new HttpRequest()) {\n const auth = app(AuthManager);\n const { userProvider } = auth;\n const token = req.search.get(\"token\");\n const email = decodeURIComponent(req.search.get(\"email\"))\n .toLowerCase()\n .trim();\n\n let magicLink = null;\n\n try {\n magicLink = await userProvider.findUserMagicLinkToken({\n email,\n token,\n });\n } catch (err) {\n console.log(err);\n return { error: JSON.stringify(err) };\n }\n\n if (!magicLink) {\n return { error: \"Invalid token\" };\n }\n\n await userProvider.verifyUser(email);\n await userProvider.deleteMagicLinkToken(email);\n const session = await auth.createOrUpdateSession({ email });\n\n const url = new URL(req.rawRequest.url);\n req.ctx().setCookie(\"access_token\", session.token, {\n expires: session.expiresAt,\n secure: !url.origin.includes(\"localhost\"),\n httpOnly: true,\n });\n\n await auth.config.onSignIn(session, req.search.toJSON());\n\n return { session };\n }\n\n async signInWithPinV2(\n req = new HttpRequest<{ email: string; pin: string }>(),\n ) {\n const auth = app(AuthManager);\n const { userProvider } = auth;\n const input = await req.input();\n const { email: _email, pin } = input.toJSON();\n const email = _email.toLowerCase().trim();\n\n const magicLinkToken = await userProvider.findUserMagicLinkToken({\n email,\n pin,\n });\n\n if (!magicLinkToken) {\n throw new ValidationError({\n pin: [\"Invalid pin\"],\n });\n }\n\n await userProvider.deleteMagicLinkToken(email);\n await userProvider.verifyUser(email);\n\n const session = await auth.createOrUpdateSessionV2({ email });\n\n const url = new URL(req.rawRequest.url);\n req.ctx().setCookie(\"access_token\", session.token, {\n expires: session.expiresAt,\n secure: !url.origin.includes(\"localhost\"),\n httpOnly: true,\n });\n\n await auth.config.onSignIn(session, req.search.toJSON());\n\n return session;\n }\n\n async signInWithPin(req = new HttpRequest<{ email: string; pin: string }>()) {\n const auth = app(AuthManager);\n const { userProvider } = auth;\n const input = await req.input();\n const { email: _email, pin } = input.toJSON();\n const email = _email.toLowerCase().trim();\n\n const magicLinkToken = await userProvider.findUserMagicLinkToken({\n email,\n pin,\n });\n\n if (!magicLinkToken) {\n throw new ValidationError({\n pin: [\"Invalid pin\"],\n });\n }\n\n await userProvider.deleteMagicLinkToken(email);\n await userProvider.verifyUser(email);\n\n const session = await auth.createOrUpdateSession({ email });\n\n const url = new URL(req.rawRequest.url);\n req.ctx().setCookie(\"access_token\", session.token, {\n expires: session.expiresAt,\n secure: !url.origin.includes(\"localhost\"),\n httpOnly: true,\n });\n\n await auth.config.onSignIn(session, req.search.toJSON());\n\n return { session };\n }\n\n async signInV2(req = new SignInRequest()) {\n const url = new URL(req.rawRequest.url);\n const input = await req.input();\n const { email: _email, password } = input.toJSON();\n const email = _email.toLowerCase().trim();\n\n const auth = app(AuthManager);\n\n const user = await auth.userProvider.findUserByEmailAddress(\n email,\n auth.config.verifyEmail,\n );\n\n if (!user) {\n throw new ValidationError({\n invalid_credentials: [\"Invalid credentials\"],\n });\n }\n\n const isPasswordValid = await auth.config.verifyPassword(\n password,\n user.password,\n );\n\n if (!isPasswordValid) {\n throw new ValidationError({\n invalid_credentials: [\"Invalid credentials\"],\n });\n }\n\n const session = await auth.createOrUpdateSessionV2({\n email: user.email,\n id: user.id,\n });\n\n req.ctx().setCookie(\"access_token\", session.token, {\n expires: session.expiresAt,\n secure: !url.origin.includes(\"localhost\"),\n httpOnly: true,\n });\n\n await auth.config.onSignIn(user, req.search.toJSON());\n\n const { password: _, ...rest } = user;\n\n return rest;\n }\n\n async signIn(req = new SignInRequest()) {\n const input = await req.input();\n const { email: _email, password } = input.toJSON();\n const email = _email.toLowerCase().trim();\n\n const auth = app(AuthManager);\n\n const user = await auth.userProvider.findUserByEmailAddress(\n email,\n auth.config.verifyEmail,\n );\n\n if (!user) {\n throw new ValidationError({\n invalid_credentials: [\"Invalid credentials\"],\n });\n }\n\n const isPasswordValid = await auth.config.verifyPassword(\n password,\n user.password,\n );\n\n if (!isPasswordValid) {\n throw new ValidationError({\n invalid_credentials: [\"Invalid credentials\"],\n });\n }\n\n const session = await auth.createOrUpdateSession({\n email: user.email,\n id: user.id,\n });\n\n const url = new URL(req.rawRequest.url);\n req.ctx().setCookie(\"access_token\", session.token, {\n expires: session.expiresAt,\n secure: !url.origin.includes(\"localhost\"),\n httpOnly: true,\n });\n\n await auth.config.onSignIn(user, req.search.toJSON());\n\n const { password: _, ...rest } = user;\n\n return rest;\n }\n\n async signUp() {\n const auth = app(AuthManager);\n const { userProvider, config } = auth;\n const req = new config.signUpRequest();\n const input = await req.input();\n const {\n email: _email,\n password,\n name,\n invitationId,\n } = input.toJSON();\n const email = _email.toLowerCase().trim();\n\n const user = await userProvider.findUserByEmailAddress(email, false);\n\n if (user) {\n throw new ValidationError({\n email: [\"Email address already exists\"],\n });\n }\n\n const hashedPassword = await config.hashPassword(password);\n\n const locale = app(Translator).detectLocale(req);\n\n let invitation: Invitation;\n if (invitationId) {\n invitation = await userProvider.findInvitation(invitationId, email);\n }\n\n let newUser: User;\n // `\"\"` rather than left undefined, because only the `else` branch below\n // assigns it. An invited sign-up sets `emailVerifiedAt` and never writes a\n // token, so there is nothing to verify — the same reason `oauthCallback`\n // passes `\"\"` — and `onSignUp` is typed `verificationToken: string`. Left\n // undeclared, the invited path handed the hook `undefined` against that\n // signature.\n let verificationToken = \"\";\n\n // Both branches write the user and everything that has to exist alongside\n // it in one transaction, `config.onUserCreated` last. A throw from the hook\n // takes the user with it, which is the whole point of the hook: an app\n // provisioning an organization in `onSignUp` — which fires after the commit\n // — gets a user with no organization when that insert fails.\n if (invitation) {\n newUser = await userProvider.transaction(async () => {\n // Consuming the invitation belongs in here too. Deleted before the\n // transaction, a rollback would leave the invite burned and no user to\n // show for it, so the invitee could not retry.\n await userProvider.deleteInvitationById(invitationId);\n\n const user = await userProvider.createUser({\n email,\n name,\n password: hashedPassword,\n emailVerifiedAt: new Date(),\n locale,\n });\n await userProvider.createAccount({\n organizationId: invitation.organizationId,\n userId: user.id,\n organizationRole: invitation.role,\n });\n\n await config.onUserCreated(user);\n\n return user;\n });\n } else {\n // Outside the transaction: it is a hash, not a query, and the\n // transaction holds a connection for as long as it is open.\n verificationToken = await config.generateEmailVerificationToken(email);\n\n newUser = await userProvider.transaction(async () => {\n const user = await userProvider.createUser({\n email,\n name,\n password: hashedPassword,\n verificationToken,\n locale,\n });\n\n await config.onUserCreated(user);\n\n return user;\n });\n }\n\n await config.onSignUp(newUser, verificationToken, req.search.toJSON());\n\n return newUser;\n }\n\n async signOut(req = new HttpRequest()) {\n const token = req.cookies.get(\"access_token\");\n\n const user = await Auth.user();\n\n const { userProvider, config } = app(AuthManager);\n\n await userProvider.deleteSession({ token });\n\n const url = new URL(req.rawRequest.url);\n req.ctx().setCookie(\"access_token\", \"\", {\n expires: new Date(0),\n secure: !url.origin.includes(\"localhost\"),\n httpOnly: true,\n });\n\n await config.onSignOut(user);\n\n return {};\n }\n\n async forgotPassword(req = new ForgotPasswordRequest()) {\n const input = await req.input();\n const email = input.get(\"email\").toLowerCase().trim();\n\n const { userProvider, config } = app(AuthManager);\n\n const user = await userProvider.findUserByEmailAddress(\n email,\n config.verifyEmail,\n );\n\n if (!user) {\n return {};\n }\n\n const token = await config.generateForgotPasswordToken(user);\n\n // TODO: Do not create token if already there is one that is valid\n // Prevent token spamming\n await userProvider.createPasswordResetToken({\n user,\n token,\n });\n\n await config.onForgotPassword(user, token);\n\n return {};\n }\n\n async resetPassword(req = new ResetPasswordRequest()) {\n const { userProvider, config } = app(AuthManager);\n const input = await req.input();\n const { password, token } = input.toJSON();\n\n const passwordResetToken = await userProvider.findPasswordResetToken({\n token,\n });\n\n if (!passwordResetToken) {\n throw new ValidationError({\n token: [\"Invalid token\"],\n });\n }\n\n const isTokenExpired = Temporal.Instant.from(\n passwordResetToken.createdAt.toISOString(),\n )\n .add({ hours: 24 })\n .until(Temporal.Now.instant()).sign;\n\n if (isTokenExpired >= 0) {\n throw new ValidationError({\n token: [\"Token expired\"],\n });\n }\n\n await userProvider.deletePasswordResetToken({ token });\n\n const user = await userProvider.findUserByEmailAddress(\n passwordResetToken.user.email,\n config.verifyEmail,\n );\n\n if (!user) {\n throw new ValidationError({\n email: [\"User not found\"],\n });\n }\n\n const hashedPassword = await config.hashPassword(password);\n\n await userProvider.updateUserPassword({\n id: user.id,\n password: hashedPassword,\n });\n\n await userProvider.deleteAllUserSessions(user.id);\n\n await config.onResetPassword(user);\n\n return {};\n }\n\n async changePassword(\n req = new HttpRequest<{ oldPassword: string; newPassword: string }>(),\n ) {\n const { userProvider, config } = app(AuthManager);\n const user = await Auth.user();\n const input = await req.input();\n const { oldPassword, newPassword } = input.toJSON();\n\n const { password } = await userProvider.findUserByEmailAddress(\n user.email,\n config.verifyEmail,\n );\n\n const isPasswordValid = await config.verifyPassword(oldPassword, password);\n\n if (!isPasswordValid) {\n throw new ValidationError({\n oldPassword: [\"Incorrect password\"],\n });\n }\n\n const hashedPassword = await config.hashPassword(newPassword);\n\n await userProvider.updateUserPassword({\n id: user.id,\n password: hashedPassword,\n });\n\n await userProvider.deleteAllUserSessions(user.id);\n return {};\n }\n\n async oauthRedirect(req = new HttpRequest()) {\n const { provider } = req.params;\n const oauthProvider =\n app(AuthManager).config.oauthProviders[provider as string];\n\n if (!oauthProvider) {\n throw new Error(`Invalid provider: ${provider}`);\n }\n\n return {\n destination: await oauthProvider.getRedirectUrl(req),\n };\n }\n\n async oauthCallback(req = new HttpRequest()) {\n const { provider } = req.params;\n const auth = app(AuthManager);\n const { userProvider, config } = auth;\n const oauthProvider = config.oauthProviders[provider as string];\n\n const { email, name } = await oauthProvider.onCallback(req);\n\n if (!email) {\n console.error(\n \"Authentication error: No email returned from OAuth provider callback\",\n );\n return {\n session: null,\n };\n }\n\n let user = await userProvider.findUserByEmailAddress(email, false);\n\n const locale = app(Translator).detectLocale(req);\n\n let action: \"signin\" | \"signup\" = \"signin\";\n\n if (!user) {\n action = \"signup\";\n\n // Same shape as `signUp`: the user, the row that has to exist beside it,\n // and `onUserCreated`, in one transaction. The social account in\n // particular has a foreign key onto the user — created outside, a rolled\n // back user would leave it pointing at nothing.\n user = await userProvider.transaction(async () => {\n const created = await userProvider.createUser({\n email,\n name,\n locale,\n emailVerifiedAt: new Date(),\n });\n\n // TODO: fix missing fields\n await userProvider.createSocialAccount({\n provider,\n userId: created.id,\n email,\n username: name,\n providerId: \"\",\n expiresAt: new Date(),\n accessToken: \"\",\n refreshToken: \"\",\n });\n\n await config.onUserCreated(created);\n\n return created;\n });\n }\n\n const session = await auth.createOrUpdateSessionV2({\n email: user.email,\n id: user.id,\n });\n\n const url = new URL(req.rawRequest.url);\n\n req.ctx().setCookie(\"access_token\", session.token, {\n secure: !url.origin.includes(\"localhost\"),\n httpOnly: true,\n expires: session.expiresAt,\n });\n\n if (action === \"signup\") {\n // `\"\"`, and not a token, deliberately.\n //\n // This used to hand the hook `config.generateMagicLinkToken(email)`.\n // That function is a pure hash and nothing here persisted what it\n // returned — `userProvider.createMagicLinkToken`, which writes the\n // `MagicLinkToken` row, was never called — so the value resolved in\n // neither place a token can be looked up: not `User.verificationToken`,\n // which `createUser` above does not set, and not the `MagicLinkToken`\n // table. An application doing the obvious thing with the argument, and\n // mailing a confirmation link carrying it, sent every OAuth signup a link\n // that could not resolve, and it tested clean against email/password\n // signup, where the same parameter is the persisted verification token.\n //\n // There is nothing to verify on this path — the user arrives with\n // `emailVerifiedAt` already set — so \"no token\" is the honest value, and\n // it is the one the email path already passes under `verifyEmail: false`.\n // An app that does want to hand new OAuth users a magic link should mint\n // a persisted one with `Auth.createMagicLink(user.email)` from the hook.\n await config.onSignUp(user, \"\", req.search.toJSON());\n } else {\n await config.onSignIn(user, req.search.toJSON());\n }\n\n return { session };\n }\n\n async createMagicLinkToken(req = new HttpRequest<{ email: string }>()) {\n const input = await req.input();\n const email = input.get(\"email\").toLowerCase().trim();\n const auth = app(AuthManager);\n const { user, pin, token } = await auth.createMagicLinkToken(email);\n\n if (user) {\n await auth.config.onMagicLinkCreated(user, { email, pin, token });\n return {\n email,\n };\n }\n\n return { email: null };\n }\n}\n",
|
|
20
|
+
"import { ApiRouter } from \"../http/ApiRouter\";\nimport { ViewRouter } from \"../http/ViewRouter\";\nimport { AuthController } from \"./AuthController\";\n\nclass OAuthViewRouter extends ViewRouter {\n middlewares = [\"cache:private\"];\n routes = {\n \"/:provider\": this.view(\"_Redirect\", [AuthController, \"oauthRedirect\"]),\n \"/:provider/callback\": this.view(\"auth/OauthCallback\", [\n AuthController,\n \"oauthCallback\",\n ]),\n };\n}\n\nexport class AuthViewRouter extends ViewRouter {\n middlewares = [\"cache:private\"];\n routes = {\n \"/sign-in/magic-link\": this.view(\"auth/MagicLinkSignIn\", [\n AuthController,\n \"signInWithMagicLink\",\n ]),\n \"/oauth\": OAuthViewRouter,\n };\n}\n\nexport class AuthApiRouter extends ApiRouter {\n middlewares = [\"cache:private\"];\n routes = {\n \"/sign-in\": this.post(AuthController, \"signIn\"),\n \"/sign-in-v2\": this.post(AuthController, \"signInV2\"),\n \"/sign-up\": this.post(AuthController, \"signUp\"),\n \"/sign-out\": this.post(AuthController, \"signOut\"),\n \"/forgot-password\": this.post(AuthController, \"forgotPassword\"),\n \"/reset-password\": this.post(AuthController, \"resetPassword\"),\n \"/change-password\": this.post(AuthController, \"changePassword\"),\n \"/verify-email\": this.post(AuthController, \"verifyEmail\"),\n \"/me\": this.get(AuthController, \"me\").middleware([\"auth\"]),\n \"/magic-link\": this.post(AuthController, \"createMagicLinkToken\"),\n \"/sign-in-with-pin\": this.post(AuthController, \"signInWithPin\"),\n \"/sign-in-with-pin-v2\": this.post(AuthController, \"signInWithPinV2\"),\n };\n}\n",
|
|
21
|
+
"import { ApiRouter, HttpRequest } from \"../http\";\nimport { app } from \"../foundation/app\";\nimport { Translator } from \"./Translator\";\n\nexport class I18nRouter extends ApiRouter {\n middlewares = [\"cache:private,0,no-store\"];\n routes = {\n // Fires `onLocaleChange` and nothing else. The `i18n-locale` cookie is\n // written by the client before it navigates (`useLocale`), because the\n // navigation's own route-data request already has to carry it. Setting it\n // here as well could only ever undo that: this response would replace the\n // client's year-long cookie with a session one, and two switches in quick\n // succession put two responses in flight, where the later-landing one wins\n // regardless of which locale the user actually stopped on.\n \"/set-locale/:locale\": this.get(async () => {\n const req = new HttpRequest<any, any>();\n const locale = req.params.locale;\n await app(Translator).onLocaleChange(locale);\n return { locale };\n }),\n \"/translations/:locale/:scope*\": this.get(async () => {\n const req = new HttpRequest<any, any>();\n\n const scope = `/${req.params.scope ?? \"\"}`;\n const forcedLocale = req.params.locale;\n\n const translator = app(Translator);\n const locale = forcedLocale ?? translator.detectLocale(req);\n\n const translations = translator.getPageTranslations(locale, scope);\n\n req.ctx().setCookie(\"i18n-locale\", locale, {\n expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),\n });\n\n return {\n [locale]: translations,\n };\n }),\n };\n}\n",
|
|
22
|
+
"import type { ResizeParameters } from \"./types\";\n\nexport abstract class ImageOptimizationDriver {\n abstract resize(\n buffer: Buffer,\n parameters: ResizeParameters,\n ): Promise<Buffer>;\n}\n",
|
|
23
|
+
"import { ImageOptimizationDriver } from \"./ImageOptimizationDriver\";\nimport { loadSharp } from \"../../../support/sharp\";\nimport type { ResizeParameters } from \"./types\";\n\nexport class Sharp extends ImageOptimizationDriver {\n async resize(buffer: Buffer, parameters: ResizeParameters) {\n const { height, width, quality, fit } = parameters;\n const sharp = await loadSharp(\"The Sharp image optimization driver\");\n return await sharp(buffer)\n .resize(width > 0 ? width : undefined, height > 0 ? height : undefined, {\n fit,\n })\n .webp({ quality: quality > 0 ? quality : 80, force: true })\n .toBuffer();\n }\n}\n",
|
|
24
|
+
"import type { ImageOptimizationDriver } from \"./drivers/ImageOptimizationDriver\";\nimport { Sharp } from \"./drivers/SharpDriver\";\n\n// Config key: `image`.\nexport interface ImageConfig {\n driver?: ImageOptimizationDriver;\n}\n\nexport function defineImageConfig(config: ImageConfig): ImageConfig {\n return config;\n}\n\nexport function imageConfigDefaults(): Required<ImageConfig> {\n return {\n driver: new Sharp(),\n };\n}\n",
|
|
25
|
+
"import { app } from \"../../foundation/app\";\nimport { ApiRouter, HttpRequest } from \"../../http\";\nimport { imageConfigDefaults, type ImageConfig } from \"./config\";\nimport type { ImageOptimizationDriver } from \"./drivers/ImageOptimizationDriver\";\nimport type { ResizeParameters } from \"./drivers/types\";\n\nexport class ImageOptimizationRouter extends ApiRouter {\n routes = {\n \"/resize\": this.file(async () => {\n const req = new HttpRequest();\n const url = new URL(req.rawRequest.url);\n const rawImageUrl = url.searchParams.get(\"url\");\n const width = Number(url.searchParams.get(\"w\"));\n const height = Number(url.searchParams.get(\"h\"));\n const fit = url.searchParams.get(\"fit\") ?? \"cover\";\n const quality = Number(url.searchParams.get(\"q\"));\n\n if (!rawImageUrl) {\n return new Response(\n JSON.stringify({\n error: \"url query parameter is required\",\n }),\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n status: 404,\n },\n );\n }\n const prefix = rawImageUrl.startsWith(\"http\")\n ? \"\"\n : `http://localhost:${process.env.PORT || 5173}`;\n const fullImageUrl = `${prefix}${rawImageUrl}`;\n const res = await fetch(fullImageUrl);\n if (!res.ok) {\n return new Response(\n JSON.stringify({\n error: \"Image not found\",\n info: fullImageUrl,\n }),\n {\n headers: {\n \"Content-Type\": \"application/json\",\n },\n status: 404,\n },\n );\n }\n\n const imageBuffer = Buffer.from(await res.arrayBuffer());\n\n const buffer = await app(ImageManager).resize(imageBuffer, {\n height,\n width,\n fit: fit as any,\n quality,\n });\n\n res.headers.delete(\"Content-Type\");\n res.headers.delete(\"Content-Length\");\n const _headers = new Headers(res.headers);\n _headers.set(\"Content-Type\", \"image/webp\");\n _headers.set(\"Content-Length\", `${buffer.byteLength}`);\n return new Response(new Uint8Array(buffer), {\n headers: _headers,\n });\n }),\n };\n}\n\nexport class ImageManager {\n static token = \"image\";\n\n readonly driver: ImageOptimizationDriver;\n\n constructor(config: ImageConfig = {}) {\n this.driver = config.driver ?? imageConfigDefaults().driver;\n }\n\n resize(buffer: Buffer, params: ResizeParameters) {\n return this.driver.resize(buffer, params);\n }\n}\n",
|
|
26
|
+
"import type { FileSink } from \"bun\";\nimport { mkdir, readdir, access } from \"fs/promises\";\n\nasync function exists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\nimport { RequestContext } from \"../../http/requestContext\";\nimport type { LogConfig } from \"./config\";\nimport type { LogEntry, LogLevel } from \"./types\";\n\nexport class LogManager {\n static token = \"log\";\n\n writer: FileSink;\n isReady: boolean = false;\n\n private logsDirPath: string = `${process.env.ROOT_DIR}/storage/logs`;\n private flushTimeout: Timer;\n private fileSize: number = 0;\n private writerSize: number = 0;\n private isCreatingFile: boolean = false;\n private bootPromise: Promise<void> | null = null;\n public currentLogFilePath: string;\n\n constructor(public config: Required<LogConfig>) {}\n\n /**\n * Idempotent. `LogServiceProvider.boot()` calls this so the storage\n * directory exists before the first request; a lazy first `log()` triggers\n * it too, so the manager still works when it is resolved on its own.\n */\n boot(): Promise<void> {\n if (!this.bootPromise) {\n this.bootPromise = this.createStorage().then(() => {\n this.isReady = true;\n });\n }\n return this.bootPromise;\n }\n\n private async createStorage() {\n if (!process.env.ROOT_DIR) {\n return;\n }\n if (!(await exists(`${process.env.ROOT_DIR}/storage`))) {\n await mkdir(`${process.env.ROOT_DIR}/storage`);\n }\n if (!(await exists(this.logsDirPath))) {\n await mkdir(this.logsDirPath);\n }\n await this.newLogFile();\n }\n\n async newLogFile() {\n if (!(await exists(this.logsDirPath))) {\n await mkdir(this.logsDirPath);\n }\n this.isCreatingFile = true;\n if (this.currentLogFilePath) {\n this.writer.flush();\n this.writer.end();\n this.writer = null;\n const file = new File(\n [await Bun.file(this.currentLogFilePath).arrayBuffer()],\n this.currentLogFilePath.split(\"/\").pop(),\n { type: \"text/plain\" },\n );\n this.config.onLogFileClosed(file);\n this.fileSize = 0;\n this.writerSize = 0;\n }\n\n const logFiles = await readdir(this.logsDirPath);\n\n const lastLogFile = logFiles.sort().reverse()[0];\n\n if (lastLogFile) {\n const _file = Bun.file(`${this.logsDirPath}/${lastLogFile}`);\n if (_file.size < this.config.maxFileSize) {\n this.currentLogFilePath = `${this.logsDirPath}/${lastLogFile}`;\n\n this.writer = _file.writer();\n this.writer.write(await _file.text());\n this.writer.write(\"\\n\");\n this.writer.flush();\n this.fileSize = _file.size;\n }\n }\n\n if (!this.writer) {\n const logFileName =\n `${new Date(Date.now()).toISOString()}.log`.replaceAll(\":\", \"-\");\n this.currentLogFilePath = `${this.logsDirPath}/${logFileName}`;\n const file = Bun.file(`${this.logsDirPath}/${logFileName}`);\n this.writer = file.writer();\n this.fileSize = 0;\n this.writerSize = 0;\n }\n this.isCreatingFile = false;\n }\n\n async log(\n level: LogLevel,\n message: string,\n metadata: Record<string, any> = {},\n ) {\n if (!this.isReady) {\n await this.boot();\n }\n\n const reqCtx = RequestContext.getStore();\n let requestMetadata = {};\n if (reqCtx) {\n requestMetadata = {\n url: reqCtx.req.rawRequest.url,\n method: reqCtx.req.rawRequest.method,\n headers: reqCtx.req.rawRequest.headers,\n body: reqCtx.req.rawRequest.body,\n };\n }\n\n const logObject: LogEntry = {\n timestamp: new Date(Date.now()).toISOString(),\n env: process.env.NODE_ENV,\n level,\n message,\n metadata: { ...requestMetadata, ...metadata },\n };\n\n let log = \"\";\n try {\n log = JSON.stringify(logObject);\n } catch (err) {\n console.log(\"Error parsing log object\", err);\n }\n this.writerSize += log.length;\n this.fileSize += log.length;\n\n try {\n this.writer.write(log);\n this.writer.write(\"\\n\");\n // Broadcast.channel(\"/logs/live\", {}).publish(JSON.stringify(logObject));\n this.config.onLogCreated(logObject);\n this.tryFlush();\n } catch (err) {\n console.error(\"Error writing log\", err);\n // Do something\n }\n }\n\n async tryFlush() {\n if (this.fileSize > this.config.maxFileSize) {\n if (!this.isCreatingFile) {\n await this.newLogFile();\n }\n }\n if (this.writerSize > this.config.maxFileSize / 2) {\n await this.writer.flush();\n this.writerSize = 0;\n await this.newLogFile();\n } else {\n clearTimeout(this.flushTimeout);\n this.flushTimeout = setTimeout(async () => {\n await this.writer.flush();\n this.writerSize = 0;\n }, 100);\n }\n }\n}\n",
|
|
27
|
+
"import { ApiRouter } from \"../../http\";\nimport { app } from \"../../foundation/app\";\nimport { LogManager } from \"./LogManager\";\n\nexport class LoggingRouter extends ApiRouter {\n middlewares = [\"cache:private,0\"];\n routes = {\n \"/live\": this.get(async () => {\n const file = Bun.file(app(LogManager).currentLogFilePath);\n return new Response(await file.text(), {\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n }),\n };\n}\n",
|
|
28
|
+
"import { HttpRequest, Middleware } from \"../../http\";\nimport type { MiddlewareConfig } from \"../../http/middleware-config\";\nimport type { RouterMiddleware } from \"../../http/Router\";\nimport { isConstructor } from \"../../internal/isConstructor\";\n\nfunction transformMiddleware(input: (string | Function)[]) {\n const map = new Map();\n for (const middleware of input) {\n if (typeof middleware === \"string\") {\n const [alias, params = \"\"] = middleware.split(\":\");\n if (alias.startsWith(\"-\")) {\n if (map.has(alias.replace(\"-\", \"\"))) {\n map.delete(alias.replace(\"-\", \"\"));\n }\n } else {\n map.set(alias, params.split(\",\").filter(Boolean));\n }\n } else {\n map.set(middleware, []);\n }\n }\n return map;\n}\n\nexport class MiddlewareRegistry {\n static token = \"middleware\";\n\n constructor(public config: Required<MiddlewareConfig>) {}\n\n get aliases() {\n return this.config.aliases;\n }\n\n public runMiddleware(\n middleware: (\n | string\n | RouterMiddleware\n | (new (req: HttpRequest) => Middleware)\n )[],\n ) {\n const req = new HttpRequest();\n return Array.from(transformMiddleware(middleware).entries())\n .map(([key, params]) => {\n if (typeof key === \"string\") {\n const Middleware = this.aliases[key];\n if (Middleware) {\n const middleware = new Middleware(req);\n return () => middleware.run.call(middleware, ...params);\n }\n } else {\n if (isConstructor(key)) {\n const middleware = new key(req);\n return middleware.run.bind(middleware);\n }\n return key;\n }\n })\n .filter(Boolean)\n .reduce(\n (acc: any, middleware: any) => {\n return async () => {\n return {\n ...(await acc()),\n ...(await middleware()),\n };\n };\n },\n () => Promise.resolve({}),\n )();\n }\n}\n",
|
|
29
|
+
"import type { JSX } from \"react\";\nimport type { HttpRequest } from \"../../http/HttpRequest\";\nimport type { ApiRouter } from \"../../http/ApiRouter\";\nimport type { ViewRouter } from \"../../http/ViewRouter\";\nimport type { StreamSummary } from \"./ServerQueryStore\";\n\n// Config key: `route.api`. Derived from `ApiRouterServiceProvider`.\nexport interface ApiRouteConfig {\n // `typeof ApiRouter`, not `new () => ApiRouter`: route flattening identifies\n // nested routers by the static `__brand`, which a bare construct signature\n // does not carry.\n rootRouter: typeof ApiRouter;\n\n onRequestStart?: (req: HttpRequest) => void | Promise<void>;\n onRequestEnd?: (req: HttpRequest) => void | Promise<void>;\n onRequestFail?: (req: HttpRequest, error: any) => void | Promise<void>;\n}\n\n// Config key: `route.view`. Derived from `ViewRouterServiceProvider`.\nexport interface ViewRouteConfig {\n root: (props: any) => JSX.Element;\n rootRouter: new () => ViewRouter;\n\n /**\n * Whether a client-side navigation may skip the handlers of the layout\n * segments the client already has mounted, rather than re-running the whole\n * chain for every route below a layout.\n *\n * Set to `false` to run every handler on every navigation. Prefer\n * `alwaysRun()` on the one layout that needs it — this switch is for when an\n * app cannot audit them all at once.\n */\n partialRendering?: boolean;\n\n onRequestStart?: (req: HttpRequest) => void | Promise<void>;\n onRequestEnd?: (req: HttpRequest) => void | Promise<void>;\n onRequestFail?: (req: HttpRequest, error: any) => void | Promise<void>;\n\n /**\n * Fires when the response body actually closes — after the last streamed\n * chunk, not when the handler returns. Under streaming those are very\n * different moments: the handler returns at time-to-shell while queries keep\n * streaming for as long as the slowest one takes, so an APM span ended in the\n * handler under-reports every streamed request. End it here instead;\n * `summary` carries `shellAt`/`settledAt`, whether the stream deadline\n * aborted rendering, and per-query timings. Non-streamed responses (`.json`\n * payloads, `no-stream` routes, bot requests) report `shellAt === settledAt`.\n *\n * Although the body closes long after the handler returned, the dispatcher\n * re-enters the request's scopes around this hook — facades and `req.ctx()`\n * work here exactly as they do in the other lifecycle hooks.\n */\n onStreamComplete?: (\n req: HttpRequest,\n summary: StreamSummary,\n ) => void | Promise<void>;\n}\n\n// Config key: `route`. Covers both route dispatchers.\nexport interface RouteConfig {\n api: ApiRouteConfig;\n view: ViewRouteConfig;\n}\n\nexport function defineRouteConfig(config: RouteConfig): RouteConfig {\n return config;\n}\n\n// `rootRouter` / `root` have no defaults — the app must supply them.\nexport function apiRouteConfigDefaults(): Omit<\n Required<ApiRouteConfig>,\n \"rootRouter\"\n> {\n return {\n onRequestStart: () => {},\n onRequestEnd: () => {},\n onRequestFail: () => {},\n };\n}\n\nexport function viewRouteConfigDefaults(): Omit<\n Required<ViewRouteConfig>,\n \"root\" | \"rootRouter\"\n> {\n return {\n partialRendering: true,\n onRequestStart: () => {},\n onRequestEnd: () => {},\n onRequestFail: () => {},\n onStreamComplete: () => {},\n };\n}\n",
|
|
30
|
+
"import { HttpRequest, type Middleware } from \"../../http\";\nimport {\n type ApiRoutes,\n type RouteHandlers,\n type ApiRouter,\n type ResourceRoutes,\n RouteHandler,\n type ProxyHandler,\n} from \"../../http/ApiRouter\";\nimport type { RouterMiddleware } from \"../../http/Router\";\n\ntype ApiRouteExec = any;\nexport type FlatApiRoutes = Record<\n string,\n Record<\n string,\n {\n exec: ApiRouteExec;\n middleware: (string | (new () => Middleware) | RouterMiddleware)[];\n }\n >\n>;\n\nfunction isRouteHandler(option: ApiRoutes[string]): option is RouteHandler<any, any, any, any> {\n return \"run\" in option;\n}\n\nfunction isRouteHandlers(option: ApiRoutes[string]): option is RouteHandlers {\n return (\n Object.hasOwn(option, \"get\") ||\n Object.hasOwn(option, \"post\") ||\n Object.hasOwn(option, \"put\") ||\n Object.hasOwn(option, \"delete\")\n );\n}\n\nfunction isResouceRoutes(option: ApiRoutes[string]): option is ResourceRoutes<any> {\n return Object.hasOwn(option, \"first\") && Object.hasOwn(option, \"second\");\n}\n\n// Narrows to `typeof ApiRouter`, not `new () => ApiRouter`: the latter lacks\n// the static `__brand` this very guard reads, so it is not a subtype of the\n// parameter and TypeScript rejects the predicate under a strict lib.\nfunction isApiRouter(routeHandlers: ApiRoutes[string]): routeHandlers is typeof ApiRouter {\n if (\"__brand\" in routeHandlers) {\n return routeHandlers.__brand === \"ApiRouter\";\n }\n return false;\n}\n\nfunction isProxyHandler(option: ApiRoutes[string]): option is ProxyHandler {\n if (\"__internal_brand\" in option) {\n return option.__internal_brand === \"ProxyHandler\";\n }\n return false;\n}\n\nfunction isStreamHandler(option: ApiRoutes[string]) {\n if (\"__internal_brand\" in option) {\n return option.__internal_brand === \"StreamHandler\";\n }\n return false;\n}\n\nexport function createFlatApiRoutes(\n routes: ApiRoutes,\n rootPath = \"\",\n rootMiddleware: RouterMiddleware[] | string[] = [],\n) {\n const flatApiRoutes: FlatApiRoutes = {};\n\n function addRoute(\n path: string,\n method: string,\n exec: ApiRouteExec,\n middleware: RouterMiddleware[] | string[],\n ) {\n const subPath = path === \"/\" ? \"\" : path;\n const _rootPath = rootPath === \"/\" ? \"\" : rootPath;\n const finalPath = (`${_rootPath}${subPath}` === \"\" ? \"/\" : `${_rootPath}${subPath}`).replaceAll(\n \"//\",\n \"/\",\n );\n if (!flatApiRoutes[finalPath]) {\n flatApiRoutes[finalPath] = {};\n }\n flatApiRoutes[finalPath][method.toUpperCase()] = {\n exec,\n middleware: [...rootMiddleware, ...middleware],\n };\n flatApiRoutes[finalPath].OPTIONS = {\n exec: () => {\n const req = new HttpRequest();\n const headers = req.ctx().headers;\n return new Response(null, { headers, status: 204 });\n },\n middleware: [],\n };\n }\n\n for (const [path, option] of Object.entries(routes)) {\n if (isProxyHandler(option)) {\n const proxyHandler = option;\n for (const method of [\"GET\", \"POST\", \"PUT\", \"DELETE\"]) {\n addRoute(path, method, proxyHandler.run.bind(proxyHandler), []);\n }\n continue;\n }\n\n if (isRouteHandler(option)) {\n const routeHandler = option;\n const method = routeHandler.method;\n const middleware = routeHandler.middlewares;\n const exec = routeHandler.run.bind(routeHandler);\n addRoute(path, method, exec, middleware);\n // A stream route also answers HEAD, so a client can read the size and\n // Accept-Ranges without pulling the body.\n if (isStreamHandler(option)) {\n addRoute(path, \"HEAD\", exec, middleware);\n }\n }\n\n if (isRouteHandlers(option)) {\n for (const [method, routeHandler] of Object.entries(option)) {\n const middleware = routeHandler.middlewares;\n const exec = routeHandler.run.bind(routeHandler);\n addRoute(path, method, exec, middleware);\n }\n }\n\n if (isApiRouter(option)) {\n const router = new option();\n const routes = createFlatApiRoutes(router.routes, `${rootPath}${path}`, router.middlewares);\n for (const [path, route] of Object.entries(routes)) {\n flatApiRoutes[path.replaceAll(\"//\", \"/\")] = route;\n }\n }\n\n if (isResouceRoutes(option)) {\n const { first, second } = option;\n for (const [method, routeHandler] of Object.entries(first)) {\n const middleware = routeHandler.middlewares;\n const exec = routeHandler.run.bind(routeHandler);\n const [lastSegment, ...rest] = path.split(\"/\").reverse();\n if (!lastSegment.startsWith(\":\")) {\n throw new Error(\"Resource route must end with a dynamic segment\");\n }\n addRoute(rest.reverse().join(\"/\"), method, exec, middleware);\n }\n for (const [method, routeHandler] of Object.entries(second)) {\n const middleware = routeHandler.middlewares;\n const exec = routeHandler.run.bind(routeHandler);\n addRoute(path, method, exec, middleware);\n }\n }\n }\n\n return Object.fromEntries(\n Object.entries(flatApiRoutes).sort(([a], [b]) => {\n const x = a.split(\"/\").length + a.split(\":\").length;\n const y = b.split(\"/\").length + b.split(\":\").length;\n return x - y;\n }),\n );\n}\n",
|
|
31
|
+
"import type { HttpRequest } from \"../../http\";\nimport type { ViewRoutes } from \"../../http/ViewRouter\";\n\nexport type ViewRouteExec = (req: HttpRequest<any, any>) => any; // TODO: fix type\n\n/**\n * One entry per segment of a route, parallel to `exec` — `segments[i]` is what\n * `exec[i]` renders. `path` is the segment's own route pattern, prefixed by\n * every ancestor, so the last segment's `path` is always the flat route key.\n *\n * Partial rendering compares these pairwise between the route the client is on\n * and the one it is navigating to, to find the segments it can skip.\n */\nexport type ViewRouteSegment = {\n path: string;\n viewPath: string;\n /** Layout opted out of being skipped, via `alwaysRun()`. */\n alwaysRun?: boolean;\n};\n\nexport type FlatViewRoutes = Record<\n string,\n {\n exec: ViewRouteExec[];\n middleware: (string | any)[];\n viewPath: string;\n segments: ViewRouteSegment[];\n }\n>;\n\nfunction removeGroupPrefix(input: string) {\n // Remove all (str) patterns\n const withoutParentheses = input.replace(/\\([^)]*\\)/g, \"\");\n\n // Remove all double slashes // by replacing with single slash\n const withoutDoubleSlashes = withoutParentheses.replace(/\\/\\//g, \"/\");\n return withoutDoubleSlashes;\n}\n\n/** How a child route path is mounted under its parent's. */\nfunction joinRoutePath(prefix: string, path: string) {\n if (prefix === \"/\") return path;\n if (path === \"/\") return prefix;\n return `${prefix}${path}`;\n}\n\n/**\n * A segment path is compared against other segment paths, so it has to be\n * spelled one way only. A group as the last part of a path (`/app/(private)`)\n * leaves a trailing slash behind once the group is stripped.\n */\nfunction segmentPath(path: string) {\n const withoutGroups = removeGroupPrefix(path);\n return withoutGroups.length > 1 ? withoutGroups.replace(/\\/$/, \"\") : withoutGroups;\n}\n\nfunction prefixSegments(prefix: string, segments: ViewRouteSegment[]) {\n return segments.map((segment) => ({\n ...segment,\n path: segmentPath(joinRoutePath(prefix, segment.path)),\n }));\n}\n\nexport function createFlatViewRoutes(routes: ViewRoutes) {\n const flatRoutes: FlatViewRoutes = {};\n\n for (const [routePath, viewConfigOrViewRouter] of Object.entries(routes)) {\n if (\"run\" in viewConfigOrViewRouter) {\n const route = viewConfigOrViewRouter;\n if (\"children\" in route) {\n const children = new route.children();\n const result = createFlatViewRoutes(children.routes);\n\n for (const [path, { exec, middleware, segments }] of Object.entries(\n result,\n )) {\n const _key = joinRoutePath(routePath, path);\n\n const handler = (req: HttpRequest<any, any>) =>\n route.run.call(route, req, routePath);\n\n flatRoutes[removeGroupPrefix(_key)] = {\n exec: [handler, ...exec],\n middleware: [...route.middlewares, ...middleware],\n viewPath: route.viewPath,\n segments: [\n {\n path: segmentPath(routePath),\n viewPath: route.viewPath,\n ...(route.alwaysRuns ? { alwaysRun: true } : {}),\n },\n ...prefixSegments(routePath, segments),\n ],\n };\n }\n } else {\n const handler = (req: HttpRequest<any, any>) =>\n route.run.call(route, req, routePath);\n flatRoutes[removeGroupPrefix(routePath)] = {\n exec: [handler],\n middleware: route.middlewares,\n viewPath: route.viewPath,\n segments: [{ path: segmentPath(routePath), viewPath: route.viewPath }],\n };\n }\n } else {\n const router = new viewConfigOrViewRouter();\n const result = createFlatViewRoutes(router.routes);\n for (const [\n path,\n { exec, middleware, viewPath, segments },\n ] of Object.entries(result)) {\n const _key = joinRoutePath(routePath, path);\n flatRoutes[removeGroupPrefix(_key)] = {\n exec,\n middleware: [...router.middlewares, ...middleware],\n viewPath,\n segments: prefixSegments(routePath, segments),\n };\n }\n }\n }\n\n return Object.fromEntries(\n Object.entries(flatRoutes).sort(([a], [b]) => {\n const x = a.split(\"/\").length + a.split(\":\").length;\n const y = b.split(\"/\").length + b.split(\":\").length;\n return x - y;\n }),\n );\n}\n",
|
|
32
|
+
"var Pe=Object.defineProperty;var a=(e,t)=>Pe(e,\"name\",{value:t,configurable:!0});var P=class{type=3;name=\"\";prefix=\"\";value=\"\";suffix=\"\";modifier=3;constructor(t,r,n,c,l,f){this.type=t,this.name=r,this.prefix=n,this.value=c,this.suffix=l,this.modifier=f}hasCustomName(){return this.name!==\"\"&&typeof this.name!=\"number\"}};a(P,\"Part\");var Re=/[$_\\p{ID_Start}]/u,Ee=/[$_\\u200C\\u200D\\p{ID_Continue}]/u,v=\".*\";function Oe(e,t){return(t?/^[\\x00-\\xFF]*$/:/^[\\x00-\\x7F]*$/).test(e)}a(Oe,\"isASCII\");function D(e,t=!1){let r=[],n=0;for(;n<e.length;){let c=e[n],l=a(function(f){if(!t)throw new TypeError(f);r.push({type:\"INVALID_CHAR\",index:n,value:e[n++]})},\"ErrorOrInvalid\");if(c===\"*\"){r.push({type:\"ASTERISK\",index:n,value:e[n++]});continue}if(c===\"+\"||c===\"?\"){r.push({type:\"OTHER_MODIFIER\",index:n,value:e[n++]});continue}if(c===\"\\\\\"){r.push({type:\"ESCAPED_CHAR\",index:n++,value:e[n++]});continue}if(c===\"{\"){r.push({type:\"OPEN\",index:n,value:e[n++]});continue}if(c===\"}\"){r.push({type:\"CLOSE\",index:n,value:e[n++]});continue}if(c===\":\"){let f=\"\",s=n+1;for(;s<e.length;){let i=e.substr(s,1);if(s===n+1&&Re.test(i)||s!==n+1&&Ee.test(i)){f+=e[s++];continue}break}if(!f){l(`Missing parameter name at ${n}`);continue}r.push({type:\"NAME\",index:n,value:f}),n=s;continue}if(c===\"(\"){let f=1,s=\"\",i=n+1,o=!1;if(e[i]===\"?\"){l(`Pattern cannot start with \"?\" at ${i}`);continue}for(;i<e.length;){if(!Oe(e[i],!1)){l(`Invalid character '${e[i]}' at ${i}.`),o=!0;break}if(e[i]===\"\\\\\"){s+=e[i++]+e[i++];continue}if(e[i]===\")\"){if(f--,f===0){i++;break}}else if(e[i]===\"(\"&&(f++,e[i+1]!==\"?\")){l(`Capturing groups are not allowed at ${i}`),o=!0;break}s+=e[i++]}if(o)continue;if(f){l(`Unbalanced pattern at ${n}`);continue}if(!s){l(`Missing pattern at ${n}`);continue}r.push({type:\"REGEX\",index:n,value:s}),n=i;continue}r.push({type:\"CHAR\",index:n,value:e[n++]})}return r.push({type:\"END\",index:n,value:\"\"}),r}a(D,\"lexer\");function F(e,t={}){let r=D(e);t.delimiter??=\"/#?\",t.prefixes??=\"./\";let n=`[^${x(t.delimiter)}]+?`,c=[],l=0,f=0,s=\"\",i=new Set,o=a(u=>{if(f<r.length&&r[f].type===u)return r[f++].value},\"tryConsume\"),h=a(()=>o(\"OTHER_MODIFIER\")??o(\"ASTERISK\"),\"tryConsumeModifier\"),p=a(u=>{let d=o(u);if(d!==void 0)return d;let{type:g,index:y}=r[f];throw new TypeError(`Unexpected ${g} at ${y}, expected ${u}`)},\"mustConsume\"),A=a(()=>{let u=\"\",d;for(;d=o(\"CHAR\")??o(\"ESCAPED_CHAR\");)u+=d;return u},\"consumeText\"),xe=a(u=>u,\"DefaultEncodePart\"),N=t.encodePart||xe,H=\"\",$=a(u=>{H+=u},\"appendToPendingFixedValue\"),M=a(()=>{H.length&&(c.push(new P(3,\"\",\"\",N(H),\"\",3)),H=\"\")},\"maybeAddPartFromPendingFixedValue\"),X=a((u,d,g,y,Z)=>{let m=3;switch(Z){case\"?\":m=1;break;case\"*\":m=0;break;case\"+\":m=2;break}if(!d&&!g&&m===3){$(u);return}if(M(),!d&&!g){if(!u)return;c.push(new P(3,\"\",\"\",N(u),\"\",m));return}let S;g?g===\"*\"?S=v:S=g:S=n;let k=2;S===n?(k=1,S=\"\"):S===v&&(k=0,S=\"\");let E;if(d?E=d:g&&(E=l++),i.has(E))throw new TypeError(`Duplicate name '${E}'.`);i.add(E),c.push(new P(k,E,N(u),S,N(y),m))},\"addPart\");for(;f<r.length;){let u=o(\"CHAR\"),d=o(\"NAME\"),g=o(\"REGEX\");if(!d&&!g&&(g=o(\"ASTERISK\")),d||g){let m=u??\"\";t.prefixes.indexOf(m)===-1&&($(m),m=\"\"),M();let S=h();X(m,d,g,\"\",S);continue}let y=u??o(\"ESCAPED_CHAR\");if(y){$(y);continue}if(o(\"OPEN\")){let m=A(),S=o(\"NAME\"),k=o(\"REGEX\");!S&&!k&&(k=o(\"ASTERISK\"));let E=A();p(\"CLOSE\");let be=h();X(m,S,k,E,be);continue}M(),p(\"END\")}return c}a(F,\"parse\");function x(e){return e.replace(/([.+*?^${}()[\\]|/\\\\])/g,\"\\\\$1\")}a(x,\"escapeString\");function B(e){return e&&e.ignoreCase?\"ui\":\"u\"}a(B,\"flags\");function q(e,t,r){return W(F(e,r),t,r)}a(q,\"stringToRegexp\");function T(e){switch(e){case 0:return\"*\";case 1:return\"?\";case 2:return\"+\";case 3:return\"\"}}a(T,\"modifierToString\");function W(e,t,r={}){r.delimiter??=\"/#?\",r.prefixes??=\"./\",r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith=\"\";let n=r.start?\"^\":\"\";for(let s of e){if(s.type===3){s.modifier===3?n+=x(s.value):n+=`(?:${x(s.value)})${T(s.modifier)}`;continue}t&&t.push(s.name);let i=`[^${x(r.delimiter)}]+?`,o=s.value;if(s.type===1?o=i:s.type===0&&(o=v),!s.prefix.length&&!s.suffix.length){s.modifier===3||s.modifier===1?n+=`(${o})${T(s.modifier)}`:n+=`((?:${o})${T(s.modifier)})`;continue}if(s.modifier===3||s.modifier===1){n+=`(?:${x(s.prefix)}(${o})${x(s.suffix)})`,n+=T(s.modifier);continue}n+=`(?:${x(s.prefix)}`,n+=`((?:${o})(?:`,n+=x(s.suffix),n+=x(s.prefix),n+=`(?:${o}))*)${x(s.suffix)})`,s.modifier===0&&(n+=\"?\")}let c=`[${x(r.endsWith)}]|$`,l=`[${x(r.delimiter)}]`;if(r.end)return r.strict||(n+=`${l}?`),r.endsWith.length?n+=`(?=${c})`:n+=\"$\",new RegExp(n,B(r));r.strict||(n+=`(?:${l}(?=${c}))?`);let f=!1;if(e.length){let s=e[e.length-1];s.type===3&&s.modifier===3&&(f=r.delimiter.indexOf(s)>-1)}return f||(n+=`(?=${l}|${c})`),new RegExp(n,B(r))}a(W,\"partsToRegexp\");var b={delimiter:\"\",prefixes:\"\",sensitive:!0,strict:!0},J={delimiter:\".\",prefixes:\"\",sensitive:!0,strict:!0},Q={delimiter:\"/\",prefixes:\"/\",sensitive:!0,strict:!0};function ee(e,t){return e.length?e[0]===\"/\"?!0:!t||e.length<2?!1:(e[0]==\"\\\\\"||e[0]==\"{\")&&e[1]==\"/\":!1}a(ee,\"isAbsolutePathname\");function te(e,t){return e.startsWith(t)?e.substring(t.length,e.length):e}a(te,\"maybeStripPrefix\");function ke(e,t){return e.endsWith(t)?e.substr(0,e.length-t.length):e}a(ke,\"maybeStripSuffix\");function _(e){return!e||e.length<2?!1:e[0]===\"[\"||(e[0]===\"\\\\\"||e[0]===\"{\")&&e[1]===\"[\"}a(_,\"treatAsIPv6Hostname\");var re=[\"ftp\",\"file\",\"http\",\"https\",\"ws\",\"wss\"];function U(e){if(!e)return!0;for(let t of re)if(e.test(t))return!0;return!1}a(U,\"isSpecialScheme\");function ne(e,t){if(e=te(e,\"#\"),t||e===\"\")return e;let r=new URL(\"https://example.com\");return r.hash=e,r.hash?r.hash.substring(1,r.hash.length):\"\"}a(ne,\"canonicalizeHash\");function se(e,t){if(e=te(e,\"?\"),t||e===\"\")return e;let r=new URL(\"https://example.com\");return r.search=e,r.search?r.search.substring(1,r.search.length):\"\"}a(se,\"canonicalizeSearch\");function ie(e,t){return t||e===\"\"?e:_(e)?K(e):j(e)}a(ie,\"canonicalizeHostname\");function ae(e,t){if(t||e===\"\")return e;let r=new URL(\"https://example.com\");return r.password=e,r.password}a(ae,\"canonicalizePassword\");function oe(e,t){if(t||e===\"\")return e;let r=new URL(\"https://example.com\");return r.username=e,r.username}a(oe,\"canonicalizeUsername\");function ce(e,t,r){if(r||e===\"\")return e;if(t&&!re.includes(t))return new URL(`${t}:${e}`).pathname;let n=e[0]==\"/\";return e=new URL(n?e:\"/-\"+e,\"https://example.com\").pathname,n||(e=e.substring(2,e.length)),e}a(ce,\"canonicalizePathname\");function le(e,t,r){return z(t)===e&&(e=\"\"),r||e===\"\"?e:G(e)}a(le,\"canonicalizePort\");function fe(e,t){return e=ke(e,\":\"),t||e===\"\"?e:w(e)}a(fe,\"canonicalizeProtocol\");function z(e){switch(e){case\"ws\":case\"http\":return\"80\";case\"wws\":case\"https\":return\"443\";case\"ftp\":return\"21\";default:return\"\"}}a(z,\"defaultPortForProtocol\");function w(e){if(e===\"\")return e;if(/^[-+.A-Za-z0-9]*$/.test(e))return e.toLowerCase();throw new TypeError(`Invalid protocol '${e}'.`)}a(w,\"protocolEncodeCallback\");function he(e){if(e===\"\")return e;let t=new URL(\"https://example.com\");return t.username=e,t.username}a(he,\"usernameEncodeCallback\");function ue(e){if(e===\"\")return e;let t=new URL(\"https://example.com\");return t.password=e,t.password}a(ue,\"passwordEncodeCallback\");function j(e){if(e===\"\")return e;if(/[\\t\\n\\r #%/:<>?@[\\]^\\\\|]/g.test(e))throw new TypeError(`Invalid hostname '${e}'`);let t=new URL(\"https://example.com\");return t.hostname=e,t.hostname}a(j,\"hostnameEncodeCallback\");function K(e){if(e===\"\")return e;if(/[^0-9a-fA-F[\\]:]/g.test(e))throw new TypeError(`Invalid IPv6 hostname '${e}'`);return e.toLowerCase()}a(K,\"ipv6HostnameEncodeCallback\");function G(e){if(e===\"\"||/^[0-9]*$/.test(e)&&parseInt(e)<=65535)return e;throw new TypeError(`Invalid port '${e}'.`)}a(G,\"portEncodeCallback\");function de(e){if(e===\"\")return e;let t=new URL(\"https://example.com\");return t.pathname=e[0]!==\"/\"?\"/-\"+e:e,e[0]!==\"/\"?t.pathname.substring(2,t.pathname.length):t.pathname}a(de,\"standardURLPathnameEncodeCallback\");function pe(e){return e===\"\"?e:new URL(`data:${e}`).pathname}a(pe,\"pathURLPathnameEncodeCallback\");function ge(e){if(e===\"\")return e;let t=new URL(\"https://example.com\");return t.search=e,t.search.substring(1,t.search.length)}a(ge,\"searchEncodeCallback\");function me(e){if(e===\"\")return e;let t=new URL(\"https://example.com\");return t.hash=e,t.hash.substring(1,t.hash.length)}a(me,\"hashEncodeCallback\");var C=class{#i;#n=[];#t={};#e=0;#s=1;#l=0;#o=0;#d=0;#p=0;#g=!1;constructor(t){this.#i=t}get result(){return this.#t}parse(){for(this.#n=D(this.#i,!0);this.#e<this.#n.length;this.#e+=this.#s){if(this.#s=1,this.#n[this.#e].type===\"END\"){if(this.#o===0){this.#b(),this.#f()?this.#r(9,1):this.#h()?this.#r(8,1):this.#r(7,0);continue}else if(this.#o===2){this.#u(5);continue}this.#r(10,0);break}if(this.#d>0)if(this.#A())this.#d-=1;else continue;if(this.#T()){this.#d+=1;continue}switch(this.#o){case 0:this.#P()&&this.#u(1);break;case 1:if(this.#P()){this.#C();let t=7,r=1;this.#E()?(t=2,r=3):this.#g&&(t=2),this.#r(t,r)}break;case 2:this.#S()?this.#u(3):(this.#x()||this.#h()||this.#f())&&this.#u(5);break;case 3:this.#O()?this.#r(4,1):this.#S()&&this.#r(5,1);break;case 4:this.#S()&&this.#r(5,1);break;case 5:this.#y()?this.#p+=1:this.#w()&&(this.#p-=1),this.#k()&&!this.#p?this.#r(6,1):this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 6:this.#x()?this.#r(7,0):this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 7:this.#h()?this.#r(8,1):this.#f()&&this.#r(9,1);break;case 8:this.#f()&&this.#r(9,1);break;case 9:break;case 10:break}}this.#t.hostname!==void 0&&this.#t.port===void 0&&(this.#t.port=\"\")}#r(t,r){switch(this.#o){case 0:break;case 1:this.#t.protocol=this.#c();break;case 2:break;case 3:this.#t.username=this.#c();break;case 4:this.#t.password=this.#c();break;case 5:this.#t.hostname=this.#c();break;case 6:this.#t.port=this.#c();break;case 7:this.#t.pathname=this.#c();break;case 8:this.#t.search=this.#c();break;case 9:this.#t.hash=this.#c();break;case 10:break}this.#o!==0&&t!==10&&([1,2,3,4].includes(this.#o)&&[6,7,8,9].includes(t)&&(this.#t.hostname??=\"\"),[1,2,3,4,5,6].includes(this.#o)&&[8,9].includes(t)&&(this.#t.pathname??=this.#g?\"/\":\"\"),[1,2,3,4,5,6,7].includes(this.#o)&&t===9&&(this.#t.search??=\"\")),this.#R(t,r)}#R(t,r){this.#o=t,this.#l=this.#e+r,this.#e+=r,this.#s=0}#b(){this.#e=this.#l,this.#s=0}#u(t){this.#b(),this.#o=t}#m(t){return t<0&&(t=this.#n.length-t),t<this.#n.length?this.#n[t]:this.#n[this.#n.length-1]}#a(t,r){let n=this.#m(t);return n.value===r&&(n.type===\"CHAR\"||n.type===\"ESCAPED_CHAR\"||n.type===\"INVALID_CHAR\")}#P(){return this.#a(this.#e,\":\")}#E(){return this.#a(this.#e+1,\"/\")&&this.#a(this.#e+2,\"/\")}#S(){return this.#a(this.#e,\"@\")}#O(){return this.#a(this.#e,\":\")}#k(){return this.#a(this.#e,\":\")}#x(){return this.#a(this.#e,\"/\")}#h(){if(this.#a(this.#e,\"?\"))return!0;if(this.#n[this.#e].value!==\"?\")return!1;let t=this.#m(this.#e-1);return t.type!==\"NAME\"&&t.type!==\"REGEX\"&&t.type!==\"CLOSE\"&&t.type!==\"ASTERISK\"}#f(){return this.#a(this.#e,\"#\")}#T(){return this.#n[this.#e].type==\"OPEN\"}#A(){return this.#n[this.#e].type==\"CLOSE\"}#y(){return this.#a(this.#e,\"[\")}#w(){return this.#a(this.#e,\"]\")}#c(){let t=this.#n[this.#e],r=this.#m(this.#l).index;return this.#i.substring(r,t.index)}#C(){let t={};Object.assign(t,b),t.encodePart=w;let r=q(this.#c(),void 0,t);this.#g=U(r)}};a(C,\"Parser\");var V=[\"protocol\",\"username\",\"password\",\"hostname\",\"port\",\"pathname\",\"search\",\"hash\"],O=\"*\";function Se(e,t){if(typeof e!=\"string\")throw new TypeError(\"parameter 1 is not of type 'string'.\");let r=new URL(e,t);return{protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==\"\"?r.search.substring(1,r.search.length):void 0,hash:r.hash!==\"\"?r.hash.substring(1,r.hash.length):void 0}}a(Se,\"extractValues\");function R(e,t){return t?I(e):e}a(R,\"processBaseURLString\");function L(e,t,r){let n;if(typeof t.baseURL==\"string\")try{n=new URL(t.baseURL),t.protocol===void 0&&(e.protocol=R(n.protocol.substring(0,n.protocol.length-1),r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&(e.username=R(n.username,r)),!r&&t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.username===void 0&&t.password===void 0&&(e.password=R(n.password,r)),t.protocol===void 0&&t.hostname===void 0&&(e.hostname=R(n.hostname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&(e.port=R(n.port,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&(e.pathname=R(n.pathname,r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&(e.search=R(n.search.substring(1,n.search.length),r)),t.protocol===void 0&&t.hostname===void 0&&t.port===void 0&&t.pathname===void 0&&t.search===void 0&&t.hash===void 0&&(e.hash=R(n.hash.substring(1,n.hash.length),r))}catch{throw new TypeError(`invalid baseURL '${t.baseURL}'.`)}if(typeof t.protocol==\"string\"&&(e.protocol=fe(t.protocol,r)),typeof t.username==\"string\"&&(e.username=oe(t.username,r)),typeof t.password==\"string\"&&(e.password=ae(t.password,r)),typeof t.hostname==\"string\"&&(e.hostname=ie(t.hostname,r)),typeof t.port==\"string\"&&(e.port=le(t.port,e.protocol,r)),typeof t.pathname==\"string\"){if(e.pathname=t.pathname,n&&!ee(e.pathname,r)){let c=n.pathname.lastIndexOf(\"/\");c>=0&&(e.pathname=R(n.pathname.substring(0,c+1),r)+e.pathname)}e.pathname=ce(e.pathname,e.protocol,r)}return typeof t.search==\"string\"&&(e.search=se(t.search,r)),typeof t.hash==\"string\"&&(e.hash=ne(t.hash,r)),e}a(L,\"applyInit\");function I(e){return e.replace(/([+*?:{}()\\\\])/g,\"\\\\$1\")}a(I,\"escapePatternString\");function Te(e){return e.replace(/([.+*?^${}()[\\]|/\\\\])/g,\"\\\\$1\")}a(Te,\"escapeRegexpString\");function Ae(e,t){t.delimiter??=\"/#?\",t.prefixes??=\"./\",t.sensitive??=!1,t.strict??=!1,t.end??=!0,t.start??=!0,t.endsWith=\"\";let r=\".*\",n=`[^${Te(t.delimiter)}]+?`,c=/[$_\\u200C\\u200D\\p{ID_Continue}]/u,l=\"\";for(let f=0;f<e.length;++f){let s=e[f];if(s.type===3){if(s.modifier===3){l+=I(s.value);continue}l+=`{${I(s.value)}}${T(s.modifier)}`;continue}let i=s.hasCustomName(),o=!!s.suffix.length||!!s.prefix.length&&(s.prefix.length!==1||!t.prefixes.includes(s.prefix)),h=f>0?e[f-1]:null,p=f<e.length-1?e[f+1]:null;if(!o&&i&&s.type===1&&s.modifier===3&&p&&!p.prefix.length&&!p.suffix.length)if(p.type===3){let A=p.value.length>0?p.value[0]:\"\";o=c.test(A)}else o=!p.hasCustomName();if(!o&&!s.prefix.length&&h&&h.type===3){let A=h.value[h.value.length-1];o=t.prefixes.includes(A)}o&&(l+=\"{\"),l+=I(s.prefix),i&&(l+=`:${s.name}`),s.type===2?l+=`(${s.value})`:s.type===1?i||(l+=`(${n})`):s.type===0&&(!i&&(!h||h.type===3||h.modifier!==3||o||s.prefix!==\"\")?l+=\"*\":l+=`(${r})`),s.type===1&&i&&s.suffix.length&&c.test(s.suffix[0])&&(l+=\"\\\\\"),l+=I(s.suffix),o&&(l+=\"}\"),s.modifier!==3&&(l+=T(s.modifier))}return l}a(Ae,\"partsToPattern\");var Y=class{#i;#n={};#t={};#e={};#s={};#l=!1;constructor(t={},r,n){try{let c;if(typeof r==\"string\"?c=r:n=r,typeof t==\"string\"){let i=new C(t);if(i.parse(),t=i.result,c===void 0&&typeof t.protocol!=\"string\")throw new TypeError(\"A base URL must be provided for a relative constructor string.\");t.baseURL=c}else{if(!t||typeof t!=\"object\")throw new TypeError(\"parameter 1 is not of type 'string' and cannot convert to dictionary.\");if(c)throw new TypeError(\"parameter 1 is not of type 'string'.\")}typeof n>\"u\"&&(n={ignoreCase:!1});let l={ignoreCase:n.ignoreCase===!0},f={pathname:O,protocol:O,username:O,password:O,hostname:O,port:O,search:O,hash:O};this.#i=L(f,t,!0),z(this.#i.protocol)===this.#i.port&&(this.#i.port=\"\");let s;for(s of V){if(!(s in this.#i))continue;let i={},o=this.#i[s];switch(this.#t[s]=[],s){case\"protocol\":Object.assign(i,b),i.encodePart=w;break;case\"username\":Object.assign(i,b),i.encodePart=he;break;case\"password\":Object.assign(i,b),i.encodePart=ue;break;case\"hostname\":Object.assign(i,J),_(o)?i.encodePart=K:i.encodePart=j;break;case\"port\":Object.assign(i,b),i.encodePart=G;break;case\"pathname\":U(this.#n.protocol)?(Object.assign(i,Q,l),i.encodePart=de):(Object.assign(i,b,l),i.encodePart=pe);break;case\"search\":Object.assign(i,b,l),i.encodePart=ge;break;case\"hash\":Object.assign(i,b,l),i.encodePart=me;break}try{this.#s[s]=F(o,i),this.#n[s]=W(this.#s[s],this.#t[s],i),this.#e[s]=Ae(this.#s[s],i),this.#l=this.#l||this.#s[s].some(h=>h.type===2)}catch{throw new TypeError(`invalid ${s} pattern '${this.#i[s]}'.`)}}}catch(c){throw new TypeError(`Failed to construct 'URLPattern': ${c.message}`)}}get[Symbol.toStringTag](){return\"URLPattern\"}test(t={},r){let n={pathname:\"\",protocol:\"\",username:\"\",password:\"\",hostname:\"\",port:\"\",search:\"\",hash:\"\"};if(typeof t!=\"string\"&&r)throw new TypeError(\"parameter 1 is not of type 'string'.\");if(typeof t>\"u\")return!1;try{typeof t==\"object\"?n=L(n,t,!1):n=L(n,Se(t,r),!1)}catch{return!1}let c;for(c of V)if(!this.#n[c].exec(n[c]))return!1;return!0}exec(t={},r){let n={pathname:\"\",protocol:\"\",username:\"\",password:\"\",hostname:\"\",port:\"\",search:\"\",hash:\"\"};if(typeof t!=\"string\"&&r)throw new TypeError(\"parameter 1 is not of type 'string'.\");if(typeof t>\"u\")return;try{typeof t==\"object\"?n=L(n,t,!1):n=L(n,Se(t,r),!1)}catch{return null}let c={};r?c.inputs=[t,r]:c.inputs=[t];let l;for(l of V){let f=this.#n[l].exec(n[l]);if(!f)return null;let s={};for(let[i,o]of this.#t[l].entries())if(typeof o==\"string\"||typeof o==\"number\"){let h=f[i+1];s[o]=h}c[l]={input:n[l]??\"\",groups:s}}return c}static compareComponent(t,r,n){let c=a((i,o)=>{for(let h of[\"type\",\"modifier\",\"prefix\",\"value\",\"suffix\"]){if(i[h]<o[h])return-1;if(i[h]===o[h])continue;return 1}return 0},\"comparePart\"),l=new P(3,\"\",\"\",\"\",\"\",3),f=new P(0,\"\",\"\",\"\",\"\",3),s=a((i,o)=>{let h=0;for(;h<Math.min(i.length,o.length);++h){let p=c(i[h],o[h]);if(p)return p}return i.length===o.length?0:c(i[h]??l,o[h]??l)},\"comparePartList\");return!r.#e[t]&&!n.#e[t]?0:r.#e[t]&&!n.#e[t]?s(r.#s[t],[f]):!r.#e[t]&&n.#e[t]?s([f],n.#s[t]):s(r.#s[t],n.#s[t])}get protocol(){return this.#e.protocol}get username(){return this.#e.username}get password(){return this.#e.password}get hostname(){return this.#e.hostname}get port(){return this.#e.port}get pathname(){return this.#e.pathname}get search(){return this.#e.search}get hash(){return this.#e.hash}get hasRegExpGroups(){return this.#l}};a(Y,\"URLPattern\");export{Y as URLPattern};\n",
|
|
33
|
+
"// @ts-ignore\nimport { URLPattern } from \"urlpattern-polyfill/urlpattern\";\nimport type { FlatViewRoutes } from \"./createFlatViewRoutes\";\n\nexport interface ViewRouteMatch {\n routePath: string;\n params: Record<string, string>;\n route: FlatViewRoutes[string];\n}\n\n/**\n * First route whose pattern matches `pathname`. `flatViewRoutes` is ordered\n * least-specific-first, so this is insertion order, not a best match.\n */\nexport function matchViewRoute(\n flatViewRoutes: FlatViewRoutes,\n pathname: string,\n): ViewRouteMatch | null {\n for (const [routePath, route] of Object.entries(flatViewRoutes)) {\n const pattern = new URLPattern({ pathname: routePath });\n if (pattern.test({ pathname })) {\n return {\n routePath,\n params: pattern.exec({ pathname })?.pathname.groups ?? {},\n route,\n };\n }\n }\n\n return null;\n}\n",
|
|
34
|
+
"import { applyParams } from \"../../utils/applyParams\";\nimport type { FlatViewRoutes, ViewRouteSegment } from \"./createFlatViewRoutes\";\nimport { matchViewRoute } from \"./matchViewRoute\";\n\n/** A route, as matched for one request, in the terms partial rendering needs. */\nexport interface PartialRenderRoute {\n segments: ViewRouteSegment[];\n params: Record<string, string>;\n search: string;\n}\n\nexport interface PartialRenderPlan {\n /** Index of the first segment whose handler has to run. */\n startIndex: number;\n /** View paths of the segments that were skipped, in order. */\n carriedViews: string[];\n}\n\nconst NOTHING_SKIPPED: PartialRenderPlan = { startIndex: 0, carriedViews: [] };\n\nfunction resolve(segment: ViewRouteSegment, params: Record<string, string>) {\n const resolved = applyParams(segment.path, params);\n // `applyParams` only substitutes `:name`. A bare `*` survives, and two\n // different URLs would then compare equal — never skip such a segment.\n return resolved.includes(\"*\") ? null : resolved;\n}\n\n/**\n * Works out which of the target route's segments the client already has\n * rendered, and so which of its handlers this request can skip.\n *\n * A segment is carried forward only when it is *the same segment on the same\n * resolved path*: `/app/A/chat` → `/app/A/lists` reuses the layout, but\n * `/app/A/chat` → `/app/B/chat` re-runs it even though the view is the same.\n *\n * The target's own leaf always runs — navigating to the URL you are already on\n * is a reload, not a no-op.\n */\nexport function planPartialRender(\n from: PartialRenderRoute | null,\n to: PartialRenderRoute,\n): PartialRenderPlan {\n if (!from) {\n return NOTHING_SKIPPED;\n }\n\n // Handlers read `req.search`, and there is no way to know which ones do.\n if (from.search !== to.search) {\n return NOTHING_SKIPPED;\n }\n\n const limit = Math.min(from.segments.length, to.segments.length - 1);\n\n let startIndex = 0;\n while (startIndex < limit) {\n const fromSegment = from.segments[startIndex];\n const toSegment = to.segments[startIndex];\n\n // This layout asked to run on every navigation underneath it. Segments are\n // skipped as a prefix, so everything from here down runs too.\n if (toSegment.alwaysRun) break;\n\n if (fromSegment.viewPath !== toSegment.viewPath) break;\n\n const fromPath = resolve(fromSegment, from.params);\n const toPath = resolve(toSegment, to.params);\n if (fromPath === null || toPath === null || fromPath !== toPath) break;\n\n startIndex++;\n }\n\n if (startIndex === 0) {\n return NOTHING_SKIPPED;\n }\n\n return {\n startIndex,\n carriedViews: to.segments.slice(0, startIndex).map(({ viewPath }) => viewPath),\n };\n}\n\nfunction stripLocaleSegment(pathname: string, supportedLocales: string[]) {\n const [, maybeLocale, ...rest] = pathname.split(\"/\");\n if (!supportedLocales.includes(maybeLocale)) {\n return pathname;\n }\n const stripped = `/${rest.join(\"/\")}`;\n return stripped === \"/\" ? \"/\" : stripped.replace(/\\/$/, \"\");\n}\n\n/**\n * Turns the `x-gemi-from` header into a plan for the request being served.\n *\n * Every way of not knowing what the client has — no header, an unparseable\n * one, a path this server does not route — ends in the same place: render\n * everything. The client is telling the server what to skip, so the failure\n * mode has to be doing the work, never trusting a value that did not check out.\n */\nexport function resolvePartialRender(options: {\n flatViewRoutes: FlatViewRoutes;\n supportedLocales: string[];\n /** Raw `x-gemi-from` value. */\n from: string | null;\n /** Origin to resolve the header value against. */\n origin: string;\n to: PartialRenderRoute;\n}): PartialRenderPlan {\n const { flatViewRoutes, supportedLocales, from, origin, to } = options;\n\n if (!from) {\n return NOTHING_SKIPPED;\n }\n\n let url: URL;\n try {\n url = new URL(from, origin);\n } catch {\n return NOTHING_SKIPPED;\n }\n\n // The client sends a path. Anything that resolved somewhere else was not one.\n if (url.origin !== origin) {\n return NOTHING_SKIPPED;\n }\n\n const match = matchViewRoute(flatViewRoutes, stripLocaleSegment(url.pathname, supportedLocales));\n\n if (!match) {\n return NOTHING_SKIPPED;\n }\n\n return planPartialRender(\n { segments: match.route.segments, params: match.params, search: url.search },\n to,\n );\n}\n",
|
|
35
|
+
"import { applyParams } from \"./applyParams\";\n\n/**\n * Route the client is currently rendering, sent on `.json` navigations so the\n * server can skip the handlers of the segments that route already has mounted.\n * Value is a locale-less pathname plus search, e.g. `/app/A/chat?tab=2`.\n */\nexport const PARTIAL_RENDER_HEADER = \"x-gemi-from\";\n\n/** What the server reports back about the skip it performed, if any. */\nexport interface PartialRenderInfo {\n /** The `x-gemi-from` value the plan was computed against. */\n from: string;\n /** View paths of the skipped segments, in order. Their data is carried forward. */\n carriedViews: string[];\n}\n\n/**\n * The `x-gemi-from` value for the route the client starts on.\n *\n * On the first render the router's `pathname` is still the route *pattern* the\n * server matched — it only becomes a resolved path once the history listener\n * has run — so this has to apply the params. Sending `/app/:orgId/chat` names\n * no route the server can resolve, and the first navigation after every full\n * page load would skip nothing.\n */\nexport function initialRenderedRoute(route: {\n pathname?: string;\n params?: Record<string, string>;\n search?: string;\n}) {\n // `applyParams` strips the trailing slash, so the root route resolves to the\n // empty string — which the server reads as \"no header\" and renders in full.\n const pathname = applyParams(route.pathname ?? \"/\", route.params ?? {}) || \"/\";\n return `${pathname}${route.search ?? \"\"}`;\n}\n",
|
|
36
|
+
"import { HttpRequest } from \"../../http\";\nimport { GEMI_REQUEST_BREAKER_ERROR } from \"../../http/Error\";\nimport { RequestContext } from \"../../http/requestContext\";\nimport type { RouterMiddleware } from \"../../http/Router\";\nimport {\n createFlatViewRoutes,\n type FlatViewRoutes,\n type ViewRouteExec,\n} from \"./createFlatViewRoutes\";\nimport { viewRouteConfigDefaults, type ViewRouteConfig } from \"./config\";\nimport { resolvePartialRender } from \"./planPartialRender\";\nimport { matchViewRoute } from \"./matchViewRoute\";\nimport { PARTIAL_RENDER_HEADER, type PartialRenderInfo } from \"../../utils/partialRender\";\nimport { createElement, Fragment } from \"react\";\n\nimport { createFileResponse, type FileOutput, type ViewRoutes } from \"../../http/ViewRouter\";\nimport { createRouteManifest } from \"./createRouteManifest\";\nimport { createComponentTree } from \"./createComponentTree\";\nimport { flattenComponentTree } from \"../../client/helpers/flattenComponentTree\";\nimport type { ComponentTree } from \"../../client/types\";\nimport { Translator } from \"../../i18n/Translator\";\nimport { preloadDictionaries } from \"../../i18n/dictionaryRegistry\";\nimport { createDictionarySink } from \"../../i18n/dictionarySink\";\nimport { MiddlewareRegistry } from \"../middleware/MiddlewareRegistry\";\nimport { Log } from \"../../facades/Log\";\nimport { Lang } from \"../../facades/Lang\";\nimport { AuthViewRouter } from \"../../auth/routes\";\nimport { KernelId } from \"../kernel-id/KernelId\";\nimport { app } from \"../../foundation/app\";\nimport { kernelContext } from \"../../kernel/context\";\nimport { ServerQueryStore, type StreamSummary } from \"./ServerQueryStore\";\nimport { createServerQueryFetcher } from \"./serverQueryFetcher\";\nimport { injectQueryPayloads, isBotUserAgent } from \"./streamQueryInjection\";\nimport { createShellContentObserver, createShellContentReporter } from \"./shellContentReport\";\nimport { createRoutePayloadStream } from \"./routePayloadStream\";\nimport { loadSharp } from \"../../support/sharp\";\n\n/**\n * `satori`, loaded on the first OG-image request rather than on import, for the\n * same reason `sharp` is (see `support/sharp.ts`): this module is reachable\n * from `gemi/services` through `RouteServiceProvider`, so a static import put\n * satori — and, one hop on, a font parser and an SVG layout engine — in the\n * module graph of every app and test that imported the barrel to reach\n * `CronJob` (#403).\n *\n * Rendering an OG image is a cold path by definition: a crawler asks for it\n * once and a CDN serves it afterwards.\n */\nconst loadSatori = async () => (await import(\"satori\")).default;\n\n/**\n * React's server renderer, loaded on the first render rather than on import.\n *\n * **Importing `react-dom/server.browser` keeps the process alive forever.** On\n * React 19.2.3 under Bun, that one import — nothing else, no render, no server\n * — is enough that the process never exits: `getActiveResourcesInfo()` comes\n * back empty, there are no timers, no sockets and an empty kqueue, and it hangs\n * anyway. `react-dom/server.node` does not do it. Reduced from #316's third\n * item, which reports the same hang from `await import(\"gemi/kernel\")` and\n * predates the 0.51 line.\n *\n * That import sat at module scope here, and this module is reachable from\n * `gemi/kernel` through `RouteServiceProvider` — so *any* script that touched\n * the kernel inherited the hang and needed an explicit `process.exit()`. A\n * one-off migration, a seeder, a cron entry point, a CI check: all of them\n * loaded the SSR renderer to get a `Kernel` they were going to use for\n * something else entirely.\n *\n * Deferring it costs one already-resolved dynamic import on the first document\n * render and nothing after — `react-dom` is external in the framework build, so\n * this stays a runtime resolve out of the app's own `node_modules` exactly as\n * the static import was. A server renders, so it pays this once at first\n * request; a script that never renders no longer pays it at all, which is the\n * whole point.\n *\n * Wrapped rather than awaited at each call site so the three of them read\n * unchanged.\n *\n * The slot is cleared on failure so a rejection is not what gets memoised. A\n * missing `react-dom` is fatal either way — this is about the diagnostic, not\n * about recovery: caching the rejected promise would make every later render\n * report whatever the loader threw the first time, with no stack from the call\n * that actually failed.\n */\nlet serverRenderer:\n | Promise<{ renderToReadableStream: (...args: any[]) => Promise<any> }>\n | undefined;\n\nconst renderToReadableStream = async (...args: any[]): Promise<any> => {\n // @ts-ignore\n serverRenderer ??= import(\"react-dom/server.browser\").catch((error) => {\n serverRenderer = undefined;\n throw error;\n });\n return (await serverRenderer).renderToReadableStream(...args);\n};\n\n/**\n * How long a document response may keep streaming before pending segments are\n * cut over to client rendering. One hung query must not hold the connection\n * open forever; the browser resolves whatever was aborted over `/api`.\n */\nconst STREAM_DEADLINE_MS = 10_000;\n\nconst themeScript = `\n!function(){try{var d=document.documentElement,c=d.classList;\nc.remove('light','dark');\nvar e=localStorage.getItem('theme');\nif('system'===e||(!e&&'system'===defaultTheme)){\n var t='(prefers-color-scheme: dark)',m=window.matchMedia(t);\n if(m.media!==t||m.matches){d.style.colorScheme='dark';c.add('dark')}\n else{d.style.colorScheme='light';c.add('light')}\n}else if(e){\n c.add(e||'')\n}}catch(e){}}()\n`;\n\nasync function getTtfFont(\n family: string,\n weight: number,\n style: \"normal\" | \"italic\",\n): Promise<ArrayBuffer> {\n const familyParam = `${style === \"italic\" ? \"italic,\" : \"\"}wght@${style === \"italic\" ? \"1,\" : \"\"}${weight}`;\n\n // Get css style sheet with user agent Mozilla/5.0 Firefox/1.0 to ensure non-variable TTF is returned\n const cssCall = await fetch(\n `https://fonts.googleapis.com/css2?family=${family}:${familyParam}&display=swap`,\n {\n headers: {\n \"User-Agent\": \"Mozilla/5.0 Firefox/1.0\",\n },\n },\n );\n\n const css = await cssCall.text();\n const ttfUrl = css.match(/url\\(([^)]+)\\)/)?.[1];\n\n return await fetch(ttfUrl).then((res) => res.arrayBuffer());\n}\n\n/**\n * `/assets` is where the client build output is served from, ahead of the\n * router — a route mounted there could never be reached in production, and in\n * dev it would appear to work. Fail at boot instead of shipping that.\n */\nexport const RESERVED_ROUTE_PREFIX = \"/assets\";\n\nexport function assertNoReservedRoutePaths(routePaths: string[]) {\n const reserved = routePaths.filter(\n (path) => path === RESERVED_ROUTE_PREFIX || path.startsWith(`${RESERVED_ROUTE_PREFIX}/`),\n );\n\n if (reserved.length > 0) {\n const many = reserved.length > 1;\n throw new Error(\n `View route path${many ? \"s\" : \"\"} ${reserved.map((path) => `\"${path}\"`).join(\", \")} ` +\n `use${many ? \"\" : \"s\"} the reserved \"${RESERVED_ROUTE_PREFIX}\" prefix. ` +\n `The client build output is served from there before the router runs, so the route would never match. ` +\n `Mount it somewhere else.`,\n );\n }\n}\n\nexport class ViewRouteDispatcher {\n static token = \"router.view\";\n\n flatViewRoutes: FlatViewRoutes = {};\n routeManifest: Record<string, string[]> = {};\n /** `routeManifest` without file routes — they have no component to render client side. */\n clientRouteManifest: Record<string, string[]> = {};\n componentTree: ComponentTree = [];\n flatComponentTree: string[] = [];\n root: any = null;\n /**\n * The shell-content hint (#294): React defers any boundary over\n * `progressiveChunkSize` on size alone, so a page that reads fine without\n * JS can go blank the day one more section pushes it over the budget — and\n * nothing else notices the transition (#289 was found by hand-measuring).\n * The reporter owns the once-per-route-per-boot dedup so a hot route\n * doesn't spam the dev console.\n */\n private shellReporter = createShellContentReporter();\n\n /**\n * `modulepreload` elements per route, built once instead of per request —\n * everything they derive from (the built chunk graph, the client entry) is\n * fixed at boot, and React elements are immutable, so one set is reusable\n * across every render of that route.\n *\n * Keyed on the manifest object rather than a plain field so a process that\n * ever renders against two of them — a test suite, most obviously — can\n * never serve one route's chunks out of the other's cache.\n */\n private preloadCache = new WeakMap<\n object,\n { clientEntry: unknown; byRoute: Map<string, any[]> }\n >();\n\n private readonly hooks: Required<\n Pick<\n ViewRouteConfig,\n \"onRequestStart\" | \"onRequestEnd\" | \"onRequestFail\" | \"onStreamComplete\"\n >\n >;\n\n /** See `ViewRouteConfig.partialRendering`. */\n readonly partialRendering: boolean;\n\n constructor(config: ViewRouteConfig) {\n const defaults = viewRouteConfigDefaults();\n\n this.partialRendering = config.partialRendering ?? defaults.partialRendering;\n\n this.hooks = {\n onRequestStart: config.onRequestStart ?? defaults.onRequestStart,\n onRequestEnd: config.onRequestEnd ?? defaults.onRequestEnd,\n onRequestFail: config.onRequestFail ?? defaults.onRequestFail,\n onStreamComplete: config.onStreamComplete ?? defaults.onStreamComplete,\n };\n\n const routes: ViewRoutes = {\n \"/\": config.rootRouter,\n \"/auth\": AuthViewRouter,\n };\n this.flatViewRoutes = createFlatViewRoutes(routes);\n assertNoReservedRoutePaths(Object.keys(this.flatViewRoutes));\n this.routeManifest = createRouteManifest(routes);\n this.clientRouteManifest = Object.fromEntries(\n Object.entries(this.routeManifest).filter(([, views]) => views.at(-1) !== \"FILE\"),\n );\n this.componentTree = createComponentTree(routes);\n this.flatComponentTree = flattenComponentTree(this.componentTree);\n this.root = config.root;\n }\n\n async onRequestEnd(req: HttpRequest) {\n if (!req.cookies.has(\"session_id\")) {\n req.ctx().setCookie(\"session_id\", Bun.randomUUIDv7(), {\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"Strict\",\n expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 365),\n });\n }\n\n return await this.hooks.onRequestEnd(req);\n }\n\n /**\n * Fires the provider's `onStreamComplete` from a stream callback — an\n * observability hook must never break the response body it observes, so\n * sync throws and rejections are logged and swallowed.\n *\n * Call sites must invoke this inside the request scope (see\n * `runInRequestScope` in `handleViewRequest`): stream callbacks are driven\n * by the HTTP server after the handler returned, outside the kernel\n * AsyncLocalStorage — where both the user's hook and this very `Log.error`\n * guard would break.\n */\n private completeStream(req: HttpRequest, summary: StreamSummary) {\n const logError = (err: any) => {\n Log.error(err?.message ?? 'Error in \"onStreamComplete\" event handler', {\n err: JSON.stringify(err),\n });\n };\n try {\n Promise.resolve(this.hooks.onStreamComplete(req, summary)).catch(logError);\n } catch (err) {\n logError(err);\n }\n }\n\n /** See `preloadCache`. */\n private modulePreloadLinks(args: {\n clientEntry?: { module: string; preload: string[] };\n modulePreloadManifest?: Record<string, string[]>;\n views: string[];\n routeKey: string;\n }) {\n const { clientEntry, modulePreloadManifest, views, routeKey } = args;\n\n const build = () => {\n const hrefs = new Set<string>(clientEntry?.preload ?? []);\n for (const view of views) {\n for (const href of modulePreloadManifest?.[view] ?? []) {\n hrefs.add(href);\n }\n }\n return [...hrefs].map((href) =>\n createElement(\"link\", {\n key: `modulepreload:${href}`,\n rel: \"modulepreload\",\n href,\n }),\n );\n };\n\n // Dev: no chunk graph to announce, so there is nothing worth caching.\n if (!modulePreloadManifest) {\n return build();\n }\n\n let cached = this.preloadCache.get(modulePreloadManifest);\n if (!cached || cached.clientEntry !== clientEntry) {\n cached = { clientEntry, byRoute: new Map() };\n this.preloadCache.set(modulePreloadManifest, cached);\n }\n let links = cached.byRoute.get(routeKey);\n if (!links) {\n links = build();\n cached.byRoute.set(routeKey, links);\n }\n return links;\n }\n\n private async render(props: {\n req: HttpRequest;\n /**\n * Re-enters the kernel + request AsyncLocalStorage scopes captured while\n * the request was live. Every stream lifecycle callback below runs after\n * the handler returned — driven by the HTTP server, outside both scopes —\n * so user hooks are always invoked through this.\n */\n runInRequestScope: <T>(fn: () => T) => T;\n viewData: any;\n pathname: string;\n currentPathName: string;\n csrfTokenHMAC: Buffer;\n headers: any;\n url: URL;\n i18n: any;\n user: any;\n serverQueries: ServerQueryStore;\n userAgent: string | null;\n noStream: boolean;\n params: any;\n breadcrumbs: any;\n urlLocaleSegment?: string;\n meta: any;\n isOgRequest?: boolean;\n appId: string;\n }) {\n const {\n req,\n runInRequestScope,\n csrfTokenHMAC,\n currentPathName,\n headers,\n i18n,\n params,\n pathname,\n serverQueries,\n userAgent,\n noStream,\n url,\n user,\n viewData,\n breadcrumbs,\n urlLocaleSegment,\n meta,\n isOgRequest,\n appId,\n } = props;\n\n const pageDataKey = pathname.replace(`/${urlLocaleSegment}`, \"\");\n\n const result = {\n kind: \"view\",\n data: {\n meta,\n pageData: {\n [pageDataKey]: viewData,\n },\n __csrf: csrfTokenHMAC.toString(\"base64\"),\n // Placeholder — re-snapshotted at render time (below) so everything\n // that resolved while styles and modules loaded still makes the\n // document payload instead of streaming.\n prefetchedData: {} as Record<string, Record<string, any>>,\n i18n,\n auth: { user },\n routeManifest: this.clientRouteManifest,\n breadcrumbs,\n router: {\n urlLocaleSegment,\n pathname: currentPathName,\n params,\n currentPath: pathname,\n searchParams: url.search,\n is404: !currentPathName ? true : false,\n },\n appId,\n componentTree: [[\"404\", []], ...this.componentTree],\n },\n head: {},\n };\n\n const Root = this.root;\n const currentViews = this.routeManifest[currentPathName];\n return async (params: {\n getStyles: (p: string[]) => Promise<any[]>;\n viewImportMap: any;\n bootstrapModules?: string[];\n loaders: string;\n cssManifest: Record<string, string[]>;\n ogMap: Record<string, any>;\n /**\n * Full view modules (not just default exports) so `Route` can render a\n * view's `Loading`/`Error` exports on the server — a streamed shell\n * carries real fallbacks, and they must match what the client hydrates.\n */\n viewModules?: Record<string, any>;\n /**\n * The client entry, when the server wants it booted from the bootstrap\n * script instead of handed to React as a `bootstrapModule`: `module` is\n * imported, `preload` is every chunk that import pulls in.\n *\n * React preloads its own `bootstrapModules` with `fetchPriority=\"low\"`\n * hardcoded (Fizz has no option for it), which parks the one module\n * that unblocks hydration behind everything else the page is fetching.\n * Emitting the `modulepreload` ourselves gets it the browser's default\n * script priority, and it is the same request either way — the\n * `import()` below consumes the preloaded module (#352).\n */\n clientEntry?: { module: string; preload: string[] };\n /**\n * Built chunk URLs per view name, like `cssManifest`. Only the current\n * route's chain is preloaded.\n */\n modulePreloadManifest?: Record<string, string[]>;\n }) => {\n const {\n bootstrapModules = [],\n loaders,\n getStyles,\n viewImportMap,\n cssManifest,\n ogMap,\n viewModules,\n clientEntry,\n modulePreloadManifest,\n } = params;\n\n // `clientEntry` and `bootstrapModules` are two spellings of the same job,\n // and running both would boot the entry twice — once through React's\n // `<script type=\"module\">`, once through the `import()` below. The entry\n // wins where it is offered, so React is handed nothing and never emits\n // the `fetchPriority=\"low\"` preload that made it worth taking over.\n const reactBootstrapModules = clientEntry ? [] : bootstrapModules;\n\n const bootstrapScriptContent = (data: string) =>\n [\n data,\n `window.loaders=${loaders}`,\n // Nothing imports the entry when the server routed it through\n // `clientEntry` — the bootstrap script is where it starts. The\n // `.catch` re-throws out of the microtask because a bare `import()`\n // here would report a chunk that 404s after a deploy, or an entry\n // that throws while evaluating, as an `unhandledrejection` only —\n // which `window.onerror`-based reporters do not see. The page would\n // then sit permanently unhydrated with nothing raised.\n ...(clientEntry\n ? [\n `import(${JSON.stringify(clientEntry.module)}).catch(function(e){setTimeout(function(){throw e})})`,\n ]\n : []),\n ].join(\";\");\n\n if (isOgRequest) {\n let ogHandler = null;\n let ogComponent = null;\n // `currentViews` is `undefined` on an unmatched route. Without the\n // guard `GET /nope.og` throws here and `httpProd` answers with the raw\n // stack trace, where the 404 below is what a crawler should get.\n for (const view of currentViews ?? []) {\n if (typeof ogMap[view] === \"function\") {\n ogComponent = view;\n ogHandler = ogMap[view];\n }\n }\n if (!ogHandler) {\n return new Response(\"Not found\", { status: 404 });\n }\n const data = Object.values(result.data.pageData)[0];\n\n try {\n await renderToReadableStream(createElement(ogHandler, data[ogComponent]), {\n onError: () => {},\n });\n } catch (err) {\n const { fonts, ...options } = err.satoriOptions;\n const _fonts = await Promise.all(\n fonts.map((font) => {\n return getTtfFont(font.name, font.weight, font.style).then((data) => ({\n ...font,\n data,\n }));\n }),\n );\n\n const ogHeaders = new Headers(headers);\n ogHeaders.set(\"Content-Type\", \"image/png\");\n const [satori, sharp] = await Promise.all([\n loadSatori(),\n loadSharp(\"Rendering an OG image\"),\n ]);\n const svg = await satori(err.jsx, { ...options, fonts: _fonts });\n const png = await sharp(Buffer.from(svg))\n .png({\n compressionLevel: 0,\n effort: 10,\n })\n .toBuffer();\n\n return new Response(new Uint8Array(png), { headers: ogHeaders });\n }\n\n return new Response(\"data\");\n }\n\n result.data[\"cssManifest\"] = cssManifest;\n // Client-side navigation reaches a route's chunks the same serial way a\n // hard load did, one `import()` per level, so it needs the same list the\n // shell head carries — shipped like `cssManifest` and warmed by\n // `preloadRouteModules` (#352).\n result.data[\"modulePreloadManifest\"] = modulePreloadManifest ?? {};\n\n // Hydration reaches each route segment through `window.loaders`, i.e. an\n // `import()` the browser cannot see until the entry has run — and it\n // sees a nested chunk only once its parent has parsed. On a real\n // network that serial chain shows every boundary's `Loading` fallback\n // where server-rendered content already is, collapsing the page height\n // and restoring it a round trip later (#352). Preloaded in the shell\n // head, the whole chain is fetched in parallel with the entry and is\n // resident before hydration asks for it.\n //\n // An unmatched route leaves `currentViews` undefined but still renders a\n // document — the `404` view, the one route class most likely to be hit\n // cold — so it preloads that view's chain, mirroring the `[\"404\"]` the\n // client mounts.\n const preloadLinks = this.modulePreloadLinks({\n clientEntry,\n modulePreloadManifest,\n views: currentViews ?? [\"404\"],\n routeKey: currentPathName ?? \"404\",\n });\n\n const styles = await getStyles(currentViews);\n\n // Everything resolved by now ships in the document payload; everything\n // still in flight streams in behind it. The snapshot marks its entries\n // as shipped so the injector doesn't send them twice.\n result.data.prefetchedData = serverQueries.snapshotResolved();\n serverQueries.markRenderStart();\n\n const deadline = new AbortController();\n const deadlineTimer = setTimeout(() => deadline.abort(), STREAM_DEADLINE_MS);\n\n // Decided before the render call because it changes *render-time*\n // behavior: React splits any boundary bigger than\n // `progressiveChunkSize` (~12.8KB) out of the shell as it renders, and\n // awaiting `allReady` afterwards settles the data but cannot undo the\n // split — a non-JS reader would see a body whose content is parked in\n // `<div hidden>` + `$RC()` reveal scripts (#286, #289). Two audiences\n // need the settled document: crawlers (detected by UA — progressive\n // chunking only exists to reach a browser sooner, which is worthless to\n // a client that buffers the whole response) and routes that declared\n // `\"no-stream\"` (marketing/content pages that must render for\n // JS-disabled humans, text browsers, and failed-script loads too).\n const settled = isBotUserAgent(userAgent) || noStream;\n\n // Dev-only: collect the streamed bytes so the close hook can measure\n // what a no-JS reader gets (#294). A settled document carries its\n // content inline by construction — nothing to measure — and a route\n // already hinted this boot skips the collection entirely.\n const shellObserver =\n process.env.NODE_ENV !== \"production\" &&\n !settled &&\n currentPathName &&\n this.shellReporter.shouldObserve(currentPathName)\n ? createShellContentObserver()\n : null;\n\n // Which dictionaries a page reads is only knowable once it has rendered,\n // so they cannot ride the `__GEMI_DATA__` snapshot (serialized below,\n // before the render starts). The sink collects them during the render and\n // the injector streams each one into the document.\n const dictionarySink = createDictionarySink();\n\n try {\n const stream = await renderToReadableStream(\n createElement(Fragment, {\n children: [\n // React hoists these into `<head>`, ahead of the inlined\n // stylesheets, so the browser starts the fetches on the shell's\n // first bytes.\n ...preloadLinks,\n ...styles,\n createElement(\"script\", {\n key: \"theme-script\",\n dangerouslySetInnerHTML: {\n __html: themeScript,\n },\n }),\n createElement(Root, {\n data: result.data,\n viewImportMap,\n viewModules,\n serverQueries,\n dictionarySink,\n key: \"root\",\n }),\n ],\n }),\n {\n bootstrapScriptContent: bootstrapScriptContent(\n `window.__GEMI_DATA__ = ${JSON.stringify(result.data)}`,\n ),\n bootstrapModules: reactBootstrapModules,\n signal: deadline.signal,\n ...(settled ? { progressiveChunkSize: Number.MAX_SAFE_INTEGER } : {}),\n // A query rejecting inside a streamed segment is expected: React\n // client-renders that boundary and the browser surfaces the error\n // through its own fetch. Log it and move on.\n onError(error: unknown) {\n if (process.env.NODE_ENV !== \"production\") {\n console.error(error);\n }\n },\n },\n );\n\n stream.allReady\n .catch(() => {})\n .finally(() => clearTimeout(deadlineTimer));\n\n // A settled response waits for everything before the first byte.\n // Works only together with the `progressiveChunkSize` override\n // above: this waits for the data, that keeps the content inline\n // instead of script-revealed.\n if (settled) {\n await stream.allReady.catch(() => {});\n }\n\n return new Response(\n injectQueryPayloads(stream, serverQueries, {\n // A settled body has no shell-then-stream phase — its first byte\n // already carries everything — so only progressive responses mark\n // one; the summary then reports `shellAt === settledAt` for the\n // settled ones.\n onShell: settled ? undefined : () => serverQueries.markShell(),\n onChunk: shellObserver?.onChunk,\n // The APM-visible end of the request: the body closed, not the\n // handler returned (that was at time-to-shell).\n onClose: () =>\n runInRequestScope(() => {\n this.completeStream(req, serverQueries.summarize(deadline.signal.aborted));\n if (shellObserver) {\n // The injector's `onChunk` collected the exact bytes the\n // visitor got; measured once the body closed (#294).\n this.shellReporter.report(currentPathName, shellObserver.measure());\n }\n }),\n },\n dictionarySink),\n {\n status: !currentPathName ? 404 : 200,\n headers,\n },\n );\n } catch (err) {\n clearTimeout(deadlineTimer);\n const stream = await renderToReadableStream(createElement(\"div\"), {\n bootstrapScriptContent: bootstrapScriptContent(\n `window.error= ${JSON.stringify(err.message)}; window.stack_trace=${JSON.stringify(err.stack)};window.__GEMI_DATA__ = ${JSON.stringify(result.data)}`,\n ),\n bootstrapModules:\n process.env.NODE_ENV === \"development\"\n ? [\"/render-error.js\", ...reactBootstrapModules]\n : reactBootstrapModules,\n });\n // The failed-render body still closes, and the span-ending hook is\n // pinned to the body closing, not the render succeeding — a span that\n // only ends on happy paths leaks for exactly the requests worth\n // seeing. No shell mark: this body is one settled error document.\n return new Response(\n injectQueryPayloads(stream, serverQueries, {\n onClose: () =>\n runInRequestScope(() =>\n this.completeStream(req, serverQueries.summarize(deadline.signal.aborted)),\n ),\n }),\n {\n status: !currentPathName ? 404 : 200,\n headers,\n },\n );\n }\n };\n }\n\n async handleViewRequest(req: Request) {\n const url = new URL(req.url);\n const isViewDataRequest = url.pathname.endsWith(\".json\");\n const isOgRequest = url.pathname.endsWith(\".og\");\n const urlPathnameWithLocale = url.pathname.replace(\".json\", \"\").replace(\".og\", \"\");\n\n const [, maybeLocale, ...rest] = urlPathnameWithLocale.split(\"/\");\n let urlPathname = `/${rest.join(\"/\")}`;\n let urlLocaleSegment = null;\n let urlLocale: string | null = null;\n\n const translator = app(Translator);\n\n const isPathnameWithLocale =\n !translator.supportedLocales.includes(maybeLocale);\n\n if (isPathnameWithLocale) {\n urlPathname = urlPathnameWithLocale;\n } else {\n urlLocaleSegment = maybeLocale;\n urlLocale = maybeLocale;\n }\n\n if (translator.isLocaleAware && !isOgRequest) {\n const locale = app(Translator).detectLocale(\n new HttpRequest(req, {}, \"view\", urlPathname),\n );\n\n if (urlLocale === null && locale !== translator.defaultLocale) {\n const _pathname = url.pathname === \"/\" ? \"\" : url.pathname;\n return new Response(\"\", {\n status: 302,\n headers: {\n \"Cache-Control\": \"private, no-cache, no-store, max-age=0, must-revalidate\",\n Location: `/${locale}${_pathname}${url.search}`,\n },\n });\n }\n }\n\n urlPathname = urlPathname.replace(\"//\", \"/\");\n let handlers: ViewRouteExec[] = [];\n let middlewares: (RouterMiddleware | string)[] = [];\n let currentPathName: null | string = null;\n let params: Record<string, any> = {};\n let partial: PartialRenderInfo | null = null;\n // `\"no-stream\"` in a route's (or its router's) middleware list opts the\n // route out of progressive streaming: everyone gets the fully settled\n // document a bot UA would (#289). It is a directive read here, not real\n // middleware — the middleware runner ignores unknown aliases.\n let noStream = false;\n\n try {\n const match = matchViewRoute(this.flatViewRoutes, urlPathname);\n if (match) {\n currentPathName = match.routePath;\n params = match.params;\n handlers = match.route.exec;\n middlewares = match.route.middleware;\n noStream = middlewares.includes(\"no-stream\");\n\n // Only navigations skip work. A document request renders the whole\n // tree, and the client has nothing to carry forward yet.\n if (isViewDataRequest && this.partialRendering) {\n const from = req.headers.get(PARTIAL_RENDER_HEADER);\n const plan = resolvePartialRender({\n flatViewRoutes: this.flatViewRoutes,\n supportedLocales: app(Translator).supportedLocales,\n from,\n origin: url.origin,\n to: { segments: match.route.segments, params, search: url.search },\n });\n\n if (plan.startIndex > 0) {\n handlers = handlers.slice(plan.startIndex);\n partial = { from, carriedViews: plan.carriedViews };\n }\n }\n }\n } catch (err) {\n // TODO: Handle this\n throw err;\n }\n\n const httpRequest = new HttpRequest(req, params, \"view\", currentPathName);\n this.hooks.onRequestStart(httpRequest);\n return await RequestContext.run(httpRequest, async () => {\n let pageData: {\n cookies: Set<string>;\n headers: Headers;\n currentPathName: string;\n data: Record<string, any>;\n prefetchedData: Record<string, any>;\n user: any; // TODO: fix type\n params: Record<string, any>;\n urlLocaleSegment: string | null;\n meta: any;\n appId: string;\n } | null = null;\n const ctx = RequestContext.getStore();\n // The HTTP server drives the response body — and therefore every stream\n // lifecycle callback — after `app.fetch` returned, outside the kernel\n // AsyncLocalStorage scope and outside this request's context (the same\n // phenomenon `createServerQueryFetcher` documents for render-discovered\n // fetches). Facades and `req.ctx()` inside `onStreamComplete` /\n // `onRequestFail` would break there, so capture both scopes while they\n // are live and re-enter them around every hook invocation below.\n const kernelStore = kernelContext.getStore();\n const runInRequestScope = <T>(fn: () => T): T =>\n kernelContext.run(kernelStore, () => RequestContext.runWith(ctx, fn));\n // Before middleware and handlers, so every `Query.prefetch` along the\n // way lands in one live, request-scoped store.\n ctx.serverQueries = new ServerQueryStore(createServerQueryFetcher(req));\n // A query rejecting during the streamed render (or a fire-and-forget\n // prefetch) never throws the handler, so the catch below can't see it —\n // error tracking wired to `onRequestFail` would miss server-side work\n // that failed. Route rejections through the hook here. The identity set\n // keeps `Query.instant` rethrows — which DO reach the catch — from\n // reporting the same error twice.\n const reportedQueryErrors = new Set<any>();\n ctx.serverQueries.onQueryFail((entry) => {\n reportedQueryErrors.add(entry.error);\n try {\n // In scope, and with the rejection handler attached *inside* the\n // scope, so a facade-using hook works for render-phase failures\n // exactly as it does for handler-phase ones.\n runInRequestScope(() =>\n Promise.resolve(this.hooks.onRequestFail(httpRequest, entry.error)).catch(\n () => {},\n ),\n );\n } catch {\n // An error-reporting hook must not break the settle chain it\n // observes — a suspended segment is waiting on it.\n }\n });\n\n if (urlLocale) {\n const locale = urlLocale.replaceAll(\"/\", \"\");\n Lang.setLocale(locale);\n } else {\n Lang.setLocale();\n }\n\n const httpRequest = ctx.req;\n\n try {\n await app(MiddlewareRegistry).runMiddleware(middlewares);\n\n const translator = app(Translator);\n // Two ways to be an i18n app now. `isEnabled` means the legacy\n // `prefetch` config has dictionaries to serve; configured\n // `supportedLocales` alone means the app uses `defineDictionary` and\n // still needs its locale detected, or every `useDictionary` would fall\n // back to its source language. `isLocaleAware` is the same predicate\n // the locale-prefix redirect above uses — they have to agree.\n const hasLegacyDictionaries = translator.isEnabled;\n const isI18nEnabled = translator.isLocaleAware;\n let i18n: Record<string, any> = {};\n if (isI18nEnabled) {\n let locale = null;\n if (urlLocale) {\n locale = urlLocale.replaceAll(\"/\", \"\");\n ctx.setLocale(locale);\n } else {\n locale = translator.detectLocale(\n new HttpRequest(req, httpRequest.params as any),\n );\n ctx.setLocale(locale);\n }\n\n const translations = hasLegacyDictionaries\n ? translator.getPageTranslations(locale, httpRequest.routePath)\n : {};\n\n i18n = {\n supportedLocales: translator.supportedLocales,\n currentLocale: locale,\n dictionary: {\n [locale]: translations,\n },\n defaultLocale: translator.defaultLocale,\n };\n }\n\n // Outside the `isI18nEnabled` branch on purpose. `defineDictionary`\n // needs no `translation` config at all — that is what `docs/i18n.md`\n // presents as the whole setup — so gating the preload on it left the\n // documented minimal app taking the unwarmed path: every\n // `useDictionary` suspends, and on a streamed route each component's\n // markup lands in `<div hidden>` behind a `$RC()` reveal instead of\n // inline in the shell (#286/#289). A reader without JS would see the\n // Suspense fallback where the page text belongs.\n //\n // An empty locale means the app configured none; `preloadDictionaries`\n // then warms each dictionary under its own source language, which is\n // the key `useDictionary` will ask for. It returns immediately when\n // nothing is registered, so an app with no dictionaries pays nothing.\n await preloadDictionaries(i18n.currentLocale ?? \"\");\n\n // Handlers gate the response — they decide redirects, status codes,\n // cookies — so they are awaited. Queries do not: `Query.prefetch`\n // starts its request the moment it is called (a live store, so a\n // prefetch after a handler's first `await` is no longer silently\n // dropped), and both response shapes stream whatever is still in\n // flight — the document as interleaved payload scripts, the `.json`\n // navigation payload as NDJSON lines (#290).\n const data = await Promise.all(handlers.map((fn) => fn(httpRequest as any)));\n\n const cookies = ctx.cookies;\n const headers = ctx.headers;\n\n pageData = {\n data,\n cookies,\n headers,\n user: ctx.user,\n prefetchedData: ctx.serverQueries.snapshotResolved(),\n currentPathName: httpRequest.routePath,\n params: httpRequest.params,\n urlLocaleSegment,\n meta: ctx.renderMeta(),\n appId: app(KernelId).id,\n };\n\n const { params, currentPathName, user } = pageData;\n\n const viewData = {};\n const breadcrumbs = {};\n for (const part of data ?? []) {\n const [key, value] = Object.entries(part)?.[0] ?? [];\n if (!key || !value) {\n continue;\n }\n breadcrumbs[`${key}:${currentPathName}`] = (value as any).breadcrumb;\n viewData[key] = value;\n }\n\n const fileOutput: FileOutput | undefined = (viewData as any).FILE;\n if (fileOutput) {\n for (const cookie of cookies) {\n headers.append(\"Set-Cookie\", cookie.toString());\n }\n\n try {\n await this.onRequestEnd(httpRequest);\n } catch (err) {\n Log.error(err?.message ?? 'Error in \"onRequestEnd\" event handler', {\n err: JSON.stringify(err),\n });\n }\n\n return await createFileResponse(fileOutput, headers);\n }\n\n if (isViewDataRequest) {\n // NDJSON: envelope first — sent at handler speed — then one line\n // per query as it settles (#290). The client commits the\n // navigation off the envelope and hydrates the rest as it lands.\n headers.set(\"Content-Type\", \"application/x-ndjson; charset=utf-8\");\n // The body depends on the route the client came from, so no shared\n // cache may serve one client's partial response to another.\n headers.append(\"Vary\", PARTIAL_RENDER_HEADER);\n\n cookies.forEach((cookie) => headers.append(\"Set-Cookie\", cookie.toString()));\n\n await this.hooks.onRequestEnd(httpRequest);\n\n const envelope = {\n // Nothing that rendered touched the metadata, so the segments\n // that were skipped are still the ones that own it.\n meta: partial && !ctx.metadata.touched ? null : pageData.meta,\n data: {\n [urlPathname]: viewData,\n },\n breadcrumbs,\n // Resolved-so-far; the rest streams behind the envelope. The\n // snapshot marks its entries shipped so they aren't sent twice.\n prefetchedData: ctx.serverQueries.snapshotResolved(),\n i18n,\n is404: !currentPathName,\n appId: pageData.appId,\n partial,\n };\n\n return new Response(\n createRoutePayloadStream(envelope, ctx.serverQueries, undefined, ({ aborted }) =>\n // No shell was marked, so the summary reports\n // `shellAt === settledAt` — the NDJSON body is one payload, not\n // a shell followed by streamed content.\n runInRequestScope(() =>\n this.completeStream(httpRequest, ctx.serverQueries.summarize(aborted)),\n ),\n ),\n {\n headers,\n },\n );\n }\n\n headers.set(\"Content-Type\", \"text/html; charset=utf-8\");\n\n // The streamed/settled decision is UA-derived (crawlers get inline\n // settled documents), so the body varies by User-Agent and a shared\n // cache must key on it — otherwise a cached browser shell full of\n // fallbacks and reveal scripts gets served to a bot. `no-stream`\n // routes serve one settled body to everyone, so they stay cacheable\n // without the (CDN-hostile) Vary.\n if (!noStream) {\n headers.append(\"Vary\", \"User-Agent\");\n }\n\n for (const cookie of cookies) {\n headers.append(\"Set-Cookie\", cookie.toString());\n }\n\n // const { csrfToken, csrfTokenHMAC } = this.generateCSRFTokenWithHmac();\n\n const csrfToken = Bun.CSRF.generate(process.env.SECRET);\n headers.append(\n \"Set-Cookie\",\n `csrf_token=${csrfToken}; HttpOnly; Secure; SameSite=Strict; Expires=${new Date(Date.now() + 1000 * 60 * 60 * 24).toUTCString()}`,\n );\n\n try {\n await this.onRequestEnd(httpRequest);\n } catch (err) {\n Log.error(err?.message ?? 'Error in \"onRequestEnd\" event handler', {\n err: JSON.stringify(err),\n });\n }\n\n return await this.render({\n req: httpRequest,\n runInRequestScope,\n csrfTokenHMAC: Buffer.from(\"\"),\n currentPathName,\n headers,\n i18n,\n params,\n pathname: url.pathname,\n serverQueries: ctx.serverQueries,\n userAgent: req.headers.get(\"user-agent\"),\n noStream,\n url,\n user,\n viewData,\n breadcrumbs,\n urlLocaleSegment,\n meta: pageData.meta,\n appId: pageData.appId,\n isOgRequest,\n });\n } catch (err) {\n if (err.kind === GEMI_REQUEST_BREAKER_ERROR) {\n if (isViewDataRequest) {\n const { status = 400, data, directive, headers } = err.payload.api;\n return new Response(JSON.stringify({ data, directive }), {\n headers,\n status,\n });\n } else {\n const { status = 400, error } = err.payload.view;\n return new Response(error?.message, {\n ...err.payload.view,\n status,\n });\n }\n }\n // `Query.instant` rethrows the entry's error object into this catch —\n // already reported when the rejection settled, so skip the duplicate.\n if (!reportedQueryErrors.has(err)) {\n this.hooks.onRequestFail(httpRequest, err);\n }\n throw err;\n }\n });\n }\n}\n",
|
|
37
|
+
"import type { ViewRoutes } from \"../../http/ViewRouter\";\nfunction removeGroupPrefix(input: string) {\n // Remove all (str) patterns\n const withoutParentheses = input.replace(/\\([^)]*\\)/g, \"\");\n\n // Remove all double slashes // by replacing with single slash\n const withoutDoubleSlashes = withoutParentheses.replace(/\\/\\//g, \"/\");\n return withoutDoubleSlashes;\n}\n\nexport function createRouteManifest(routes: ViewRoutes) {\n const routeManifest: Record<string, string[]> = {};\n for (const [routePath, routeHandler] of Object.entries(routes)) {\n if (\"run\" in routeHandler) {\n // `viewPath` is \"FILE\" for file routes and \"REDIRECT\" for redirect routes,\n // neither of which resolves to a component — consumers filter them out.\n const viewPath = routeHandler.viewPath;\n\n if (\"children\" in routeHandler) {\n // Add the layout view\n routeManifest[routePath] = [viewPath];\n const children = new routeHandler.children();\n const manifest = createRouteManifest(children.routes);\n for (const [path, viewPaths] of Object.entries(manifest)) {\n const key = routePath === \"/\" ? path : `${routePath}${path}`;\n const _key = path === \"/\" && routePath !== \"/\" ? routePath : key;\n routeManifest[_key] = [viewPath, ...viewPaths];\n }\n // **A layout with no index route is not a navigable path.**\n //\n // Still length 1 means nothing merged into this key — the layout has no\n // `\"/\"` child — so the path would resolve to layouts and no page, and\n // rendering it would produce a blank content area. `createFlatViewRoutes`\n // agrees: `/foo` and `/foo/bar` appear there only as *segments* of\n // `/foo/bar/baz`, never as matchable routes of their own.\n //\n // The condition is \"no index route\", which is broader than the \"no\n // children at all\" this comment used to claim — a layout whose only\n // children are deeper layouts is removed too, and that is the case the\n // stale test in this directory expected to survive.\n if (routeManifest[routePath].length === 1) {\n delete routeManifest[routePath];\n }\n } else {\n routeManifest[routePath] = [viewPath];\n }\n } else {\n const router = new routeHandler();\n\n const manifest = createRouteManifest(router.routes);\n for (const [path, viewPaths] of Object.entries(manifest)) {\n const key = routePath === \"/\" ? path : `${routePath}${path}`;\n const _key = path === \"/\" && routePath !== \"/\" ? routePath : key;\n routeManifest[_key] = viewPaths;\n }\n }\n }\n\n return Object.fromEntries(\n Object.entries(routeManifest).map(([key, value]) => [\n removeGroupPrefix(key),\n value,\n ]),\n );\n}\n",
|
|
38
|
+
"import type { ComponentTree } from \"../../client/types\";\nimport type { ViewRoutes } from \"../../http/ViewRouter\";\n\nexport function createComponentTree(routes: ViewRoutes): ComponentTree {\n const componentTree: ComponentTree = [];\n\n for (const [_, routeHandler] of Object.entries(routes)) {\n if (\"run\" in routeHandler) {\n const viewPath = routeHandler.viewPath;\n if (viewPath === \"__\") {\n continue;\n }\n\n // File and redirect routes never resolve to a component.\n if (viewPath === \"REDIRECT\") {\n continue;\n }\n\n if (viewPath === \"FILE\") {\n continue;\n }\n\n if (\"children\" in routeHandler) {\n const router = new routeHandler.children();\n const branch = createComponentTree(router.routes);\n componentTree.push([viewPath, branch]);\n } else {\n componentTree.push([viewPath, []]);\n }\n } else {\n const router = new routeHandler();\n const branch = createComponentTree(router.routes);\n componentTree.push(...branch);\n }\n }\n\n return componentTree;\n}\n",
|
|
39
|
+
"import type { ComponentTree } from \"../types\";\n\nexport function flattenComponentTree(componentTree: ComponentTree): string[] {\n let out: string[] = [];\n for (const [root, branches] of componentTree) {\n out.push(root, ...flattenComponentTree(branches).flat());\n }\n return Array.from(new Set(out));\n}\n",
|
|
40
|
+
"import { LogManager } from \"../services/logging/LogManager\";\nimport { Facade } from \"./Facade\";\n\nexport class Log extends Facade {\n static getFacadeAccessor() {\n return LogManager;\n }\n\n static debug(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"debug\", message, metadata);\n }\n\n static info(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"info\", message, metadata);\n }\n\n static notice(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"notice\", message, metadata);\n }\n\n static warning(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"warning\", message, metadata);\n }\n\n static error(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"error\", message, metadata);\n }\n\n static critical(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"critical\", message, metadata);\n }\n\n static alert(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"alert\", message, metadata);\n }\n\n static emergency(message: string, metadata?: Record<string, any>) {\n this.getFacadeRoot().log(\"emergency\", message, metadata);\n }\n}\n",
|
|
41
|
+
"/**\n * Identifies one booted kernel process. The client compares it across\n * navigations to detect a server restart, so it must be stable for the life of\n * the process and different after a reboot.\n */\nexport class KernelId {\n static token = \"kernel.id\";\n\n constructor(public readonly id: string = crypto.randomUUID()) {}\n}\n",
|
|
42
|
+
"/**\n * Tracks where an HTML byte stream *is* — mid-tag, inside a comment, inside a\n * `<script>` body, or between elements — so the stream injector only splices a\n * payload script in at a point the parser will read it as markup (#404).\n *\n * React's SSR stream copies into a fixed 2048-byte view and enqueues it when\n * full, so its chunk boundaries fall at arbitrary byte offsets — routinely\n * inside a tag. Splicing at one produced\n *\n * <link rel=\"modulepre<script>(self.__GEMI_STREAM__=…)…</script>load\" href=\"…\"/>\n *\n * where the push script is swallowed as `<link>` attributes (so the payload\n * never reaches the client), the tail leaks as text, and the modulepreload is\n * lost.\n *\n * This is a byte scanner, not an HTML parser: it answers one question, \"would a\n * `<script>` spliced here be parsed as markup and executed\", and it only has to\n * be conservative in one direction. Reporting \"not safe\" when a splice would in\n * fact have been legal just defers the payload to the next opportunity;\n * reporting \"safe\" when it isn't is the bug. Ambiguous constructs therefore\n * resolve to *unsafe*.\n *\n * Tokenizer state alone does not answer that question, because two regions are\n * in DATA yet swallow a script at tree-construction time:\n *\n * - `<template>`. Its content is parsed into a `DocumentFragment`, where a\n * script never runs. This is not hypothetical on this code path: React emits\n * `<template id=\"B:n\"></template>` for every Suspense boundary, so a view\n * boundary landing inside that ~19-byte start tag would put the payload\n * somewhere it is silently dropped — #404's outcome by another route.\n * - Foreign content. Inside `<math>` a spliced `<script>` lands in the MathML\n * namespace as an unknown element and never runs. `<svg>` is the benign half\n * of the same divergence — an SVG script *does* execute — but it costs\n * nothing to sit out both.\n *\n * So the scanner also counts template and foreign-content nesting, and reports\n * safe only at depth zero.\n *\n * Scanning bytes rather than decoded text is sound because every byte it keys\n * on (`<`, `>`, `\"`, `'`, `/`, `!`, `-`) is ASCII, and no ASCII byte can appear\n * inside a multi-byte UTF-8 sequence. A chunk that splits a character mid-way\n * is therefore harmless.\n */\n\nconst TAB = 9;\nconst LF = 10;\nconst FF = 12;\nconst CR = 13;\nconst SPACE = 32;\nconst BANG = 33;\nconst DQUOTE = 34;\nconst SQUOTE = 39;\nconst DASH = 45;\nconst SLASH = 47;\nconst LT = 60;\nconst GT = 62;\nconst QUESTION = 63;\n\n/**\n * Elements whose content is raw text or RCDATA — everything until the matching\n * end tag is text, so a `<script>` spliced inside one is never executed.\n * `<noscript>` is raw text exactly when scripting is enabled, which is the case\n * that matters here. `<plaintext>` is deliberately absent: it has no end tag,\n * so treating it as raw text would stall every later payload, and React never\n * emits it.\n */\nconst RAW_TEXT_ELEMENTS = new Set([\n \"script\",\n \"style\",\n \"textarea\",\n \"title\",\n \"xmp\",\n \"iframe\",\n \"noembed\",\n \"noframes\",\n \"noscript\",\n]);\n\n/**\n * Roots of a foreign-content subtree. Everything inside is built in the SVG or\n * MathML namespace rather than the HTML one.\n */\nconst FOREIGN_ROOTS = new Set([\"svg\", \"math\"]);\n\ntype State =\n | \"data\"\n | \"tagOpen\"\n | \"endTagOpen\"\n | \"tagName\"\n | \"inTag\"\n | \"attrDouble\"\n | \"attrSingle\"\n | \"bang\"\n | \"bogus\"\n | \"comment\"\n | \"rawText\";\n\nfunction isWhitespace(byte: number): boolean {\n return (\n byte === SPACE || byte === TAB || byte === LF || byte === FF || byte === CR\n );\n}\n\nfunction isAsciiAlpha(byte: number): boolean {\n return (byte >= 65 && byte <= 90) || (byte >= 97 && byte <= 122);\n}\n\n/** ASCII lower-case; tag names are compared case-insensitively. */\nfunction toLower(byte: number): number {\n return byte >= 65 && byte <= 90 ? byte + 32 : byte;\n}\n\nexport interface HtmlInsertionScanner {\n /**\n * Consume `chunk`, stopping at the first byte offset where the output is in\n * the DATA state, and return that offset. Returns `chunk.length` if the whole\n * chunk was consumed without reaching DATA — the caller then forwards it\n * whole and asks again with the next one.\n *\n * The scanner's state always reflects exactly the bytes it consumed, so a\n * caller that stops short resumes by calling again with the remainder.\n */\n scanToInsertionPoint(chunk: Uint8Array): number;\n /** Consume `chunk` whole, for bytes forwarded without looking for a splice. */\n write(chunk: Uint8Array): void;\n /**\n * As of every byte consumed so far, would a `<script>` appended here be\n * parsed as an executable HTML script element?\n */\n isSafe(): boolean;\n}\n\nexport function createHtmlInsertionScanner(): HtmlInsertionScanner {\n let state: State = \"data\";\n /** Accumulated name of the tag currently being read. */\n let tagName = \"\";\n let isEndTag = false;\n /** `\"</\" + name` for the raw-text element being scanned past. */\n let closeSequence = \"\";\n /** How much of `closeSequence` the raw-text scan has matched so far. */\n let closeMatched = 0;\n /** Consecutive `-` bytes: two after `<!` open a comment, two before `>` close one. */\n let dashes = 0;\n /** Did the tag being read end with `/>`? Only meaningful in foreign content. */\n let selfClosing = false;\n /** Open `<template>` elements: their content is inert to a script. */\n let templateDepth = 0;\n /** Open `<svg>`/`<math>` elements: their content is not in the HTML namespace. */\n let foreignDepth = 0;\n\n const isSafe = () =>\n state === \"data\" && templateDepth === 0 && foreignDepth === 0;\n\n const finishTag = () => {\n if (!isEndTag && RAW_TEXT_ELEMENTS.has(tagName)) {\n // A raw-text element's content is text, so nothing may be spliced into\n // it. `<script/>` does not self-close in HTML — browsers open a script\n // element either way — so the end tag is what gets us out.\n state = \"rawText\";\n closeSequence = `</${tagName}`;\n closeMatched = 0;\n tagName = \"\";\n return;\n }\n state = \"data\";\n if (tagName === \"template\") {\n // `<template/>` is not self-closing in the HTML namespace, so the flag is\n // only honoured for the foreign roots below.\n if (isEndTag) templateDepth = Math.max(0, templateDepth - 1);\n else templateDepth += 1;\n } else if (FOREIGN_ROOTS.has(tagName)) {\n if (isEndTag) foreignDepth = Math.max(0, foreignDepth - 1);\n else if (!selfClosing) foreignDepth += 1;\n }\n tagName = \"\";\n };\n\n const step = (byte: number) => {\n switch (state) {\n case \"data\":\n if (byte === LT) state = \"tagOpen\";\n return;\n\n case \"tagOpen\":\n if (byte === BANG) {\n state = \"bang\";\n dashes = 0;\n } else if (byte === SLASH) {\n state = \"endTagOpen\";\n } else if (isAsciiAlpha(byte)) {\n state = \"tagName\";\n isEndTag = false;\n selfClosing = false;\n tagName = String.fromCharCode(toLower(byte));\n } else if (byte === QUESTION) {\n // A bogus comment: consumed to the next `>`.\n state = \"bogus\";\n } else if (byte === LT) {\n // `<<` — the second `<` is the one that opens a tag.\n state = \"tagOpen\";\n } else {\n // `<` followed by anything else is literal text.\n state = \"data\";\n }\n return;\n\n case \"endTagOpen\":\n if (isAsciiAlpha(byte)) {\n state = \"tagName\";\n isEndTag = true;\n selfClosing = false;\n tagName = String.fromCharCode(toLower(byte));\n } else if (byte === GT) {\n state = \"data\";\n } else {\n state = \"bogus\";\n }\n return;\n\n case \"tagName\":\n if (isWhitespace(byte) || byte === SLASH) {\n state = \"inTag\";\n selfClosing = byte === SLASH;\n } else if (byte === GT) {\n finishTag();\n } else {\n tagName += String.fromCharCode(toLower(byte));\n }\n return;\n\n case \"inTag\":\n if (byte === GT) {\n finishTag();\n return;\n }\n // Only `/` immediately before `>` self-closes; `/ >` does not.\n selfClosing = byte === SLASH;\n if (byte === DQUOTE) state = \"attrDouble\";\n else if (byte === SQUOTE) state = \"attrSingle\";\n return;\n\n case \"attrDouble\":\n if (byte === DQUOTE) state = \"inTag\";\n selfClosing = false;\n return;\n\n case \"attrSingle\":\n if (byte === SQUOTE) state = \"inTag\";\n selfClosing = false;\n return;\n\n case \"bang\":\n // `<!--` opens a comment; `<!DOCTYPE …` and anything else runs to `>`.\n if (byte === DASH) {\n dashes += 1;\n if (dashes === 2) {\n state = \"comment\";\n dashes = 0;\n }\n } else if (byte === GT) {\n state = \"data\";\n } else {\n state = \"bogus\";\n }\n return;\n\n case \"bogus\":\n if (byte === GT) state = \"data\";\n return;\n\n case \"comment\":\n if (byte === DASH) {\n // `--->` closes too, so the count saturates rather than resetting.\n dashes = dashes < 2 ? dashes + 1 : 2;\n } else if (byte === GT && dashes >= 2) {\n state = \"data\";\n dashes = 0;\n } else {\n dashes = 0;\n }\n return;\n\n case \"rawText\": {\n if (closeMatched < closeSequence.length) {\n if (toLower(byte) === closeSequence.charCodeAt(closeMatched)) {\n closeMatched += 1;\n } else {\n // `<` only ever appears at index 0 of `</name`, so a mismatch can\n // only restart the match on a `<`.\n closeMatched = byte === LT ? 1 : 0;\n }\n return;\n }\n // `</name` only ends the element when a tag-name delimiter follows —\n // `</scriptx>` is text, not an end tag.\n if (byte === GT) {\n state = \"data\";\n tagName = \"\";\n } else if (isWhitespace(byte) || byte === SLASH) {\n state = \"inTag\";\n tagName = \"\";\n } else {\n closeMatched = byte === LT ? 1 : 0;\n }\n return;\n }\n }\n };\n\n return {\n scanToInsertionPoint(chunk) {\n for (let i = 0; i < chunk.length; i++) {\n if (isSafe()) return i;\n step(chunk[i]!);\n }\n return chunk.length;\n },\n write(chunk) {\n for (let i = 0; i < chunk.length; i++) {\n step(chunk[i]!);\n }\n },\n isSafe,\n };\n}\n",
|
|
43
|
+
"import type { DictionarySink, DictionaryUse } from \"../../i18n/dictionarySink\";\nimport { createHtmlInsertionScanner } from \"./htmlInsertionPoint\";\nimport type { ServerQueryEntry, ServerQueryStore } from \"./ServerQueryStore\";\n\n/**\n * `</script>`-safe (and `<!--`-safe) JSON for inlining into an HTML script\n * element: any `<` in the data would otherwise let a string value close the\n * tag and inject markup.\n */\nexport function htmlSafeJson(value: unknown): string {\n return JSON.stringify(value)\n .replace(/</g, \"\\\\u003c\")\n .replace(/\\u2028/g, \"\\\\u2028\")\n .replace(/\\u2029/g, \"\\\\u2029\");\n}\n\nexport function queryPayloadScript(entry: ServerQueryEntry): string {\n const payload = htmlSafeJson([entry.path, entry.variantKey, entry.data]);\n // Self-shimming: the first payload to arrive creates the buffer, so no\n // separate bootstrap is needed and execution order never matters.\n return `<script>(self.__GEMI_STREAM__=self.__GEMI_STREAM__||[]).push(${payload})</script>`;\n}\n\n/**\n * The same trick for a `defineDictionary` dictionary a segment just rendered\n * with. It rides the same queue as query payloads, so it lands ahead of the\n * reveal chunk for the segment that used it and hydration never re-fetches\n * strings the document already carries.\n */\nexport function dictionaryPayloadScript(use: DictionaryUse): string {\n const payload = htmlSafeJson([use.id, use.locale, use.strings]);\n return `<script>(self.__GEMI_DICT__=self.__GEMI_DICT__||[]).push(${payload})</script>`;\n}\n\n/**\n * The injector sits at the end of the response pipe, so it is the one place\n * that knows when the body's first byte goes out and when the body actually\n * closes — the two marks a handler-scoped span gets wrong under streaming.\n */\nexport interface StreamLifecycleHooks {\n /** The response's first chunk was enqueued — time-to-shell. */\n onShell?: () => void;\n /**\n * Every chunk enqueued into the response body, in order — the byte stream\n * exactly as the client receives it, injected payload scripts included.\n * The dev-mode shell-content measurement (#294) hangs here.\n */\n onChunk?: (chunk: Uint8Array) => void;\n /**\n * The body closed: the last chunk (and any leftover payload scripts)\n * flushed, the client went away, or the source stream errored. Fires\n * exactly once.\n */\n onClose?: () => void;\n}\n\n/**\n * Interleaves resolved query payloads with React's streamed HTML.\n *\n * A manual pull-pump around the source, not a `pipeThrough` — React's SSR\n * stream is a byte stream, and piping one through a `TransformStream` stalls\n * chunk delivery until close under Node's web-streams implementation. Pulling\n * with a plain reader behaves identically under Bun and Node.\n *\n * Ordering is the whole point, and it is guaranteed by construction twice\n * over:\n *\n * 1. Payload before reveal. The store queues the payload script *before* it\n * settles the promise the suspended segment threw (see\n * `ServerQueryStore.ensure`), and React only starts re-rendering the\n * segment after that promise resolves. By the time React produces the\n * segment's reveal chunk, the script is already waiting in `queue` — and\n * every forwarded chunk is preceded by a queue flush, so the script lands\n * first. Hydration can therefore never see a revealed segment whose data\n * isn't in the client cache.\n *\n * 2. Nothing before the shell's first byte. The queue is never flushed ahead\n * of the first React chunk, so a query that settles before streaming\n * begins can't push a script in front of `<!doctype html>`. (Those are\n * normally in the `__GEMI_DATA__` snapshot anyway and skipped here.)\n *\n * 3. Only ever between elements. React's chunk boundaries fall at arbitrary\n * byte offsets — 2048-byte views, not markup — so \"flush at a chunk\n * boundary\" used to splice scripts into the middle of a tag or into a\n * `<style>` body (#404). The scanner tracks the emitted bytes' parse state\n * and the flush moves to the first DATA-state offset *inside* the chunk\n * instead, which is still ahead of anything else that chunk carries. That\n * keeps guarantee 1: the reveal script cannot precede the payload, because\n * the earliest safe offset is at worst the end of the one tag straddling\n * the boundary.\n */\nexport function injectQueryPayloads(\n source: ReadableStream<Uint8Array>,\n store: ServerQueryStore,\n hooks: StreamLifecycleHooks = {},\n dictionaries?: DictionarySink,\n): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n const queue: string[] = [];\n let sentFirstChunk = false;\n let closed = false;\n const closeOnce = () => {\n if (closed) return;\n closed = true;\n hooks.onClose?.();\n };\n\n store.onSettle((entry) => {\n // Rejected entries stream nothing: React client-renders that segment and\n // the browser's own `/api` fetch surfaces the error into the boundary.\n if (entry.status !== \"resolved\") return;\n queue.push(queryPayloadScript(entry));\n });\n\n // Dictionaries read during render join the same queue, and inherit its\n // ordering guarantee: `useDictionary` reports a dictionary while rendering\n // the segment that uses it, so the script is queued before React can emit\n // that segment's chunk.\n dictionaries?.onUse((use) => {\n queue.push(dictionaryPayloadScript(use));\n });\n\n const reader = source.getReader();\n const scanner = createHtmlInsertionScanner();\n const forward = (\n controller: ReadableStreamDefaultController<Uint8Array>,\n chunk: Uint8Array,\n ) => {\n controller.enqueue(chunk);\n hooks.onChunk?.(chunk);\n };\n const flush = (controller: ReadableStreamDefaultController<Uint8Array>) => {\n while (queue.length > 0) {\n const script = encoder.encode(queue.shift()!);\n // Scanned like any other output so the state stays continuous. A payload\n // script is balanced markup, so this always lands back in DATA.\n scanner.write(script);\n forward(controller, script);\n }\n };\n\n /**\n * Forward one React chunk, splicing the queue in at the first offset the\n * parser would read a `<script>` as markup — offset 0 when the previous\n * chunk ended between elements, which is the common case.\n */\n const forwardWithPayloads = (\n controller: ReadableStreamDefaultController<Uint8Array>,\n chunk: Uint8Array,\n ) => {\n if (queue.length === 0) {\n scanner.write(chunk);\n forward(controller, chunk);\n return;\n }\n const at = scanner.scanToInsertionPoint(chunk);\n if (at > 0) {\n forward(controller, chunk.subarray(0, at));\n }\n // False only when the whole chunk was consumed without ever reaching DATA\n // (one very long tag or raw-text element), in which case the payload waits\n // for the next chunk — or, failing that, for the stream-end flush.\n if (scanner.isSafe()) {\n flush(controller);\n }\n const rest = chunk.subarray(at);\n if (rest.length > 0) {\n scanner.write(rest);\n forward(controller, rest);\n }\n };\n\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n let result: Awaited<ReturnType<typeof reader.read>>;\n try {\n result = await reader.read();\n } catch (err) {\n // A source error (React's stream failing post-shell) still ends the\n // body — without this, \"fires exactly once\" would be zero times on\n // the error exit, leaking whatever span `onClose` was meant to end.\n closeOnce();\n throw err;\n }\n const { done, value } = result;\n if (done) {\n // Queries nothing rendered (an unused prefetch) settle after React's\n // last chunk — they still belong in the client cache.\n flush(controller);\n controller.close();\n closeOnce();\n return;\n }\n if (!sentFirstChunk) {\n sentFirstChunk = true;\n scanner.write(value);\n forward(controller, value);\n hooks.onShell?.();\n // Guarantee 2 forbids splicing *into* the first chunk, so the queue\n // goes out behind it — and only if that chunk ended cleanly. A settled\n // (`no-stream`) document arrives with its whole backlog already queued,\n // which is why this boundary was the one that broke deterministically.\n if (scanner.isSafe()) {\n flush(controller);\n }\n return;\n }\n forwardWithPayloads(controller, value);\n },\n cancel(reason) {\n closeOnce();\n return reader.cancel(reason);\n },\n });\n}\n\n/**\n * Crawlers don't run scripts and don't wait — they index whatever HTML the\n * response body contains, so they get the fully-settled document\n * (`stream.allReady`) instead of a shell with fallbacks.\n */\nconst BOT_UA =\n /bot|crawler|spider|crawling|slurp|bingpreview|mediapartners|headless|lighthouse|prerender|facebookexternalhit|whatsapp|telegram|discord|twitterbot|linkedinbot/i;\n\nexport function isBotUserAgent(userAgent: string | null): boolean {\n if (!userAgent) return false;\n return BOT_UA.test(userAgent);\n}\n",
|
|
44
|
+
"/**\n * Dev-mode guard against the silent no-JS blanking threshold (#289, #294).\n *\n * React defers any boundary bigger than `progressiveChunkSize` (~12.8 kB) out\n * of the shell on size alone, so a public page that reads fine without JS\n * today goes blank the day one more section pushes it over the budget — its\n * content is parked in `<div hidden>` segments revealed by `$RC()` scripts,\n * and nothing in typecheck, tests, or CI notices the transition. `\"no-stream\"`\n * fixes it, but only for routes someone already knows are affected.\n *\n * The measurement is nearly free where the bytes already flow: the stream\n * injector is the last thing to see the response body, so an observer hung on\n * its `onChunk` hook holds the document exactly as the visitor received it.\n * After the body closes, the bytes are split into shell-readable text (what a\n * no-JS reader can see) versus deferred text (parked behind reveal scripts),\n * and a route shipping its content deferred while its shell is near-blank gets\n * a console hint — once per route per boot.\n */\n\nexport interface ShellContentMeasurement {\n /** Non-whitespace text chars a no-JS reader can see in the shell. */\n shellChars: number;\n /** Non-whitespace text chars parked in `<div hidden>` reveal segments. */\n deferredChars: number;\n}\n\n/**\n * Their text is code, styling, or metadata — never readable content. React's\n * `<template id=\"B:...\">` fallback markers are empty anyway; skipping the tag\n * also covers hand-written templates.\n */\nconst RAW_TEXT_TAGS = new Set([\"script\", \"style\", \"template\", \"title\"]);\n\n/**\n * `hidden` as a standalone attribute (`<div hidden id=\"S:0\">`, `hidden=\"\"`).\n * Tested against the tag with its quoted attribute values blanked out\n * (`QUOTED_VALUE` below), so the word `hidden` inside a value — a Tailwind\n * list like `class=\"mt-2 hidden md:block\"` or prose like\n * `title=\"show hidden files\"` — never opens a deferred segment.\n */\nconst HIDDEN_ATTR = /\\shidden([\\s=/]|$)/i;\n\n/**\n * Quoted attribute values, to be blanked before the `HIDDEN_ATTR` test. Safe\n * as a regex because React escapes `\"` and `'` inside attribute values, so a\n * quoted span never contains its own delimiter.\n */\nconst QUOTED_VALUE = /\"[^\"]*\"|'[^']*'/g;\n\n/**\n * Splits a streamed HTML document into shell-readable versus deferred text.\n *\n * A scanner, not a parser: it only needs to tell text from markup, skip the\n * tags whose text is never content, and track `<div hidden>` nesting — the\n * container React streams deferred segments in. Attribute text and comments\n * (including React's `<!--$?-->` boundary marks) never count; whitespace\n * never counts.\n */\nexport function measureShellContent(html: string): ShellContentMeasurement {\n let shellChars = 0;\n let deferredChars = 0;\n /** `<div>` nesting depth inside the current hidden segment; 0 = in the shell. */\n let hiddenDepth = 0;\n let i = 0;\n\n while (i < html.length) {\n const lt = html.indexOf(\"<\", i);\n const textEnd = lt === -1 ? html.length : lt;\n if (textEnd > i) {\n const visible = html.slice(i, textEnd).replace(/\\s+/g, \"\").length;\n if (hiddenDepth > 0) {\n deferredChars += visible;\n } else {\n shellChars += visible;\n }\n }\n if (lt === -1) break;\n\n if (html.startsWith(\"<!--\", lt)) {\n const end = html.indexOf(\"-->\", lt + 4);\n i = end === -1 ? html.length : end + 3;\n continue;\n }\n\n const gt = html.indexOf(\">\", lt);\n if (gt === -1) break; // truncated tag — nothing readable follows\n const tag = html.slice(lt + 1, gt);\n i = gt + 1;\n\n const name = /^\\/?([a-zA-Z][a-zA-Z0-9-]*)/.exec(tag)?.[1]?.toLowerCase();\n if (!name) continue;\n const isClosing = tag.startsWith(\"/\");\n\n if (!isClosing && RAW_TEXT_TAGS.has(name) && !tag.endsWith(\"/\")) {\n const close = html.indexOf(`</${name}`, i);\n i = close === -1 ? html.length : close;\n continue;\n }\n\n // Only `div` is tracked because that is the container React streams\n // deferred segments in. A hand-written `<section hidden>` still counts as\n // shell text — a false negative (stays silent), never a false hint.\n if (name !== \"div\") continue;\n if (isClosing) {\n if (hiddenDepth > 0) hiddenDepth -= 1;\n } else if (hiddenDepth > 0) {\n hiddenDepth += 1;\n } else if (HIDDEN_ATTR.test(tag.replace(QUOTED_VALUE, '\"\"'))) {\n hiddenDepth = 1;\n }\n }\n\n return { shellChars, deferredChars };\n}\n\n/** Below this much deferred text the page isn't relying on reveal scripts. */\nexport const DEFERRED_TEXT_FLOOR = 1000;\n\n/**\n * \"Near zero\": under this many readable chars the shell is effectively blank\n * — less than a sentence, no headline worth of content.\n */\nexport const SHELL_TEXT_NEAR_ZERO = 64;\n\nfunction formatChars(chars: number): string {\n return chars >= 1000 ? `${(chars / 1000).toFixed(1)} kB` : `${chars} chars`;\n}\n\n/**\n * The hint for a route whose content streams behind reveal scripts while its\n * shell is near-blank — exactly the transition #289 was discovered through by\n * hand-measuring. Null when the measurement is fine: a shell that carries its\n * own text, or too little deferred text to matter.\n */\nexport function shellContentHint(\n routePath: string,\n measurement: ShellContentMeasurement,\n): string | null {\n if (measurement.deferredChars < DEFERRED_TEXT_FLOOR) return null;\n if (measurement.shellChars >= SHELL_TEXT_NEAR_ZERO) return null;\n return (\n `[gemi] GET ${routePath} streams ${formatChars(measurement.deferredChars)} of its ` +\n `content behind reveal scripts — a no-JS visitor sees ~${measurement.shellChars} chars. ` +\n `If this is a public/content route, add \"no-stream\" to its middleware.`\n );\n}\n\n/**\n * Owns the once-per-route-per-boot dedup (#294's \"logs the hint once\"): a hot\n * route must not spam the dev console, but a route whose measurement is\n * healthy today must stay eligible for the hint the day it crosses the\n * threshold — only an actually-emitted hint marks the route as done.\n *\n * `warn` is injectable for tests; production callers use the default.\n */\nexport function createShellContentReporter(warn: (hint: string) => void = console.warn) {\n /** Routes already hinted this boot. */\n const hintedRoutes = new Set<string>();\n return {\n /**\n * Whether collecting bytes for this route can still lead to a hint —\n * false once the route has been hinted, so the caller can skip the\n * observer entirely.\n */\n shouldObserve(routePath: string): boolean {\n return !hintedRoutes.has(routePath);\n },\n report(routePath: string, measurement: ShellContentMeasurement): void {\n if (hintedRoutes.has(routePath)) return;\n const hint = shellContentHint(routePath, measurement);\n if (!hint) return;\n hintedRoutes.add(routePath);\n warn(hint);\n },\n };\n}\n\nexport type ShellContentReporter = ReturnType<typeof createShellContentReporter>;\n\n/**\n * Accumulates the response body for a post-close measurement. Wire `onChunk`\n * into `StreamLifecycleHooks.onChunk`; call `measure` once the body closed.\n * Decoding is streaming-safe — a multi-byte character split across chunks\n * still decodes as one character.\n */\nexport function createShellContentObserver() {\n const decoder = new TextDecoder();\n let html = \"\";\n return {\n onChunk(chunk: Uint8Array) {\n html += decoder.decode(chunk, { stream: true });\n },\n measure(): ShellContentMeasurement {\n html += decoder.decode();\n return measureShellContent(html);\n },\n };\n}\n",
|
|
45
|
+
"import type { ServerQueryStore } from \"./ServerQueryStore\";\n\n/**\n * How long a navigation payload may keep streaming query results before it\n * closes with whatever has settled. A hung query must not hold the response\n * open — the suspended segment it strands resolves over `/api` instead.\n */\nconst PAYLOAD_STREAM_DEADLINE_MS = 10_000;\n\n/**\n * The streamed `.json` navigation response (#290): NDJSON, one JSON value per\n * line.\n *\n * - **Line 1 — the envelope**: route data, meta, i18n, partial info, and the\n * `prefetchedData` that has already resolved. Written immediately, so the\n * client can commit the navigation at handler speed instead of waiting for\n * `allSettled` — the blocking that made priming a heavy query a tax on\n * every navigation.\n * - **Later lines — query payloads**: `[path, variantKey, data]`, one per\n * query as it settles. The client hydrates each into the cache, which\n * settles any segment suspended on that variant — the same wake path the\n * document stream uses.\n *\n * The envelope is an object and payload lines are arrays, which is how the\n * reader tells them apart. `JSON.stringify` never emits a raw newline, so\n * line framing is unambiguous. Rejected queries stream nothing: the\n * suspended segment's own `/api` fetch surfaces the error into its boundary.\n */\nexport function createRoutePayloadStream(\n envelope: unknown,\n store: ServerQueryStore,\n deadlineMs: number = PAYLOAD_STREAM_DEADLINE_MS,\n /**\n * The body actually closed — every settled query streamed, the deadline\n * fired (`aborted: true`), or the client went away. Fires exactly once;\n * the stream-lifecycle mirror of the document injector's `onClose`.\n */\n onClose?: (info: { aborted: boolean }) => void,\n): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n let closeStream: (aborted: boolean) => void = () => {};\n\n return new ReadableStream<Uint8Array>({\n start(controller) {\n let closed = false;\n const close = (aborted: boolean) => {\n if (closed) return;\n closed = true;\n clearTimeout(deadline);\n try {\n controller.close();\n } catch {}\n onClose?.({ aborted });\n };\n closeStream = close;\n\n controller.enqueue(encoder.encode(`${JSON.stringify(envelope)}\\n`));\n\n // Entries the envelope's snapshot already shipped are skipped by the\n // store itself (same contract the document injector relies on).\n store.onSettle((entry) => {\n if (closed || entry.status !== \"resolved\") return;\n controller.enqueue(\n encoder.encode(\n `${JSON.stringify([entry.path, entry.variantKey, entry.data])}\\n`,\n ),\n );\n });\n\n const deadline = setTimeout(() => close(true), deadlineMs);\n store.allSettled().then(\n () => close(false),\n () => close(false),\n );\n },\n cancel() {\n closeStream(false);\n },\n });\n}\n",
|
|
46
|
+
"import { AuthApiRouter } from \"../../auth/routes\";\nimport { ApiRouter, HttpRequest } from \"../../http\";\nimport { GEMI_REQUEST_BREAKER_ERROR } from \"../../http/Error\";\nimport { I18nRouter } from \"../../i18n/I18nRouter\";\nimport { RequestContext } from \"../../http/requestContext\";\nimport { ImageOptimizationRouter } from \"../image-optimization/ImageManager\";\nimport { LoggingRouter } from \"../logging/LoggingRouter\";\nimport { MiddlewareRegistry } from \"../middleware/MiddlewareRegistry\";\nimport { apiRouteConfigDefaults, type ApiRouteConfig } from \"./config\";\nimport { createFlatApiRoutes, type FlatApiRoutes } from \"./createFlatApiRoutes\";\nimport { ViewRouteDispatcher } from \"./ViewRouteDispatcher\";\nimport { Translator } from \"../../i18n/Translator\";\nimport { app } from \"../../foundation/app\";\n\nclass DebugRouter extends ApiRouter {\n routes = {\n \"/api-routes\": this.get(() => {\n const flatroutes = app(ApiRouteDispatcher).flatRoutes;\n const out = [];\n for (const [path, methods] of Object.entries(flatroutes)) {\n for (const [method, handler] of Object.entries(methods)) {\n const { exec, middleware } = handler;\n out.push({ path, method, middleware });\n }\n }\n return out;\n }),\n \"/view-routes\": this.get(() => {\n const flatroutes = app(ViewRouteDispatcher).flatViewRoutes;\n const out = [];\n for (const [path, { middleware, viewPath }] of Object.entries(flatroutes)) {\n out.push({ path, method: \"GET\", viewPath, middleware });\n }\n return out;\n }),\n };\n}\n\nexport class ApiRouteDispatcher {\n static token = \"router.api\";\n\n flatRoutes: FlatApiRoutes = {};\n\n private readonly onRequestStart: NonNullable<ApiRouteConfig[\"onRequestStart\"]>;\n private readonly onRequestEnd: NonNullable<ApiRouteConfig[\"onRequestEnd\"]>;\n private readonly onRequestFail: NonNullable<ApiRouteConfig[\"onRequestFail\"]>;\n\n constructor(config: ApiRouteConfig) {\n const defaults = apiRouteConfigDefaults();\n\n this.onRequestStart = config.onRequestStart ?? defaults.onRequestStart;\n this.onRequestEnd = config.onRequestEnd ?? defaults.onRequestEnd;\n this.onRequestFail = config.onRequestFail ?? defaults.onRequestFail;\n\n this.flatRoutes = createFlatApiRoutes({\n \"/\": config.rootRouter,\n \"/auth\": AuthApiRouter,\n \"/__gemi__/services/i18n\": I18nRouter,\n \"/__gemi__/services/logs\": LoggingRouter,\n \"/__gemi__/services/image\": ImageOptimizationRouter,\n \"/__gemi__/debug\": DebugRouter,\n });\n }\n\n public getRouteHandlerAndParams(req: Request) {\n const url = new URL(req.url);\n\n const apiPath = url.pathname.replace(\"/api\", \"\");\n\n let params: Record<string, any> = {};\n let path: string;\n for (const [_path] of Object.entries(this.flatRoutes)) {\n try {\n const pattern = new URLPattern({ pathname: _path });\n if (pattern.test({ pathname: apiPath })) {\n path = _path;\n params = pattern.exec({ pathname: apiPath })?.pathname.groups!;\n break;\n }\n } catch (err) {\n console.error(err);\n // Do something\n }\n }\n return { params, path };\n }\n\n async runRouteMiddleware(path: string, httpRequest: HttpRequest) {\n const routeHandler = this.flatRoutes[path];\n const middlewares = routeHandler[httpRequest.rawRequest.method].middleware;\n try {\n await app(MiddlewareRegistry).runMiddleware(middlewares);\n } catch (err) {\n if (err.kind === GEMI_REQUEST_BREAKER_ERROR) {\n if (httpRequest.rawRequest.url.includes(\"/api\")) {\n const { status = 400, data, headers } = err.payload.api;\n return new Response(JSON.stringify(data), {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n ...headers,\n },\n });\n }\n } else {\n this.onRequestFail(httpRequest, err);\n console.error(err);\n throw err;\n }\n }\n }\n\n async getRouteData(path: string): Promise<any> {\n const routeHandler = this.flatRoutes[path];\n\n const ctx = RequestContext.getStore();\n const exec = routeHandler[ctx.req.rawRequest.method].exec ?? (() => Promise.resolve({}));\n\n let data = {};\n try {\n data = await exec();\n } catch (err) {\n if (err.kind === GEMI_REQUEST_BREAKER_ERROR) {\n const { status = 400, data, headers } = err.payload.api;\n\n return new Response(JSON.stringify(data), {\n status,\n headers: {\n \"Content-Type\": \"application/json\",\n ...headers,\n },\n });\n }\n this.onRequestFail(ctx.req, err);\n console.error(err);\n throw err;\n }\n\n return data;\n }\n\n /**\n * Copies request-context headers and cookies onto a Response a handler built\n * itself, without disturbing what the handler already set.\n */\n private mergeContextIntoResponse(\n response: Response,\n headers: Headers,\n cookies: Set<string>,\n ) {\n // Built with forEach rather than spread: the browser tsconfig's lib set\n // has DOM but not DOM.Iterable, so `Headers` has no [Symbol.iterator].\n const entries: [string, string][] = [];\n headers?.forEach((value, key) => entries.push([key, value]));\n const setCookies = [\n ...(typeof headers?.getSetCookie === \"function\"\n ? headers.getSetCookie()\n : []),\n ...Array.from(cookies ?? []),\n ];\n\n if (entries.length === 0 && setCookies.length === 0) {\n return response;\n }\n\n const apply = (target: Headers) => {\n for (const [key, value] of entries) {\n if (key.toLowerCase() === \"set-cookie\") {\n continue;\n }\n if (!target.has(key)) {\n target.set(key, value);\n }\n }\n for (const cookie of setCookies) {\n target.append(\"Set-Cookie\", cookie);\n }\n };\n\n try {\n // Mutating in place keeps the original Response object, and with it a\n // sized Blob body — rebuilding turns that into a stream, which costs the\n // Content-Length that Bun only emits for known-length bodies.\n apply(response.headers);\n return response;\n } catch {\n // A Response from fetch() — this.proxy() routes — has immutable headers.\n const merged = new Headers(response.headers);\n apply(merged);\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: merged,\n });\n }\n }\n\n async handleApiRequest(req: Request) {\n const { params, path } = this.getRouteHandlerAndParams(req);\n\n const routeHandler = this.flatRoutes[path];\n\n if (!routeHandler || !routeHandler[req.method]) {\n return new Response(JSON.stringify({ error: { message: \"Not found\" } }), {\n status: 404,\n });\n }\n\n const httpRequest = new HttpRequest(req, params, \"api\", path);\n if (!req.url.includes(\"/__gemi__\")) {\n this.onRequestStart(httpRequest);\n }\n return await RequestContext.run(httpRequest, async () => {\n const ctx = RequestContext.getStore();\n\n const translator = app(Translator);\n if (translator.isEnabled) {\n const locale = translator.detectLocale(httpRequest);\n ctx.setLocale(locale);\n }\n\n ctx.setRequest(httpRequest);\n const middlewareResponse = await this.runRouteMiddleware(path, httpRequest);\n\n if (middlewareResponse instanceof Response) {\n return middlewareResponse;\n }\n const data = await this.getRouteData(path);\n\n const headers = ctx.headers;\n const cookies = ctx.cookies;\n\n if (data instanceof Response) {\n // A handler owning its own Response — stream, file and proxy routes,\n // and the RequestBreakerError path in getRouteData — still has to carry\n // what the request context accumulated: headers set by middleware via\n // ctx.setHeaders (CORS, Cache-Control) and any Set-Cookie. The\n // response's own headers win; the context only fills gaps.\n const response = this.mergeContextIntoResponse(data, headers, cookies);\n\n if (!req.url.includes(\"/__gemi__\")) {\n // Before destroy(), which empties the store the hook reads from.\n this.onRequestEnd(httpRequest);\n }\n ctx.destroy();\n return response;\n }\n\n headers.set(\"Content-Type\", \"application/json\");\n\n cookies.forEach((cookie) => headers.append(\"Set-Cookie\", cookie.toString()));\n\n if (!req.url.includes(\"/__gemi__\")) {\n this.onRequestEnd(httpRequest);\n }\n\n ctx.destroy();\n\n return new Response(JSON.stringify(data), {\n headers,\n });\n });\n }\n}\n",
|
|
47
|
+
"import { QueryError } from \"../../client/QueryError\";\nimport { HttpRequest } from \"../../http/HttpRequest\";\nimport { RequestContext } from \"../../http/requestContext\";\nimport { kernelContext } from \"../../kernel/context\";\nimport { applyParams } from \"../../utils/applyParams\";\nimport { app } from \"../../foundation/app\";\nimport { ApiRouteDispatcher } from \"./ApiRouteDispatcher\";\nimport type { ServerQueryFetcher } from \"./ServerQueryStore\";\n\n/**\n * The in-process \"fetch\" behind every server-side query: rebuild the request\n * the browser would have sent to `/api` and run the api handler directly.\n * Mirrors what `Query.prefetch` has always done, factored out so\n * render-discovered queries go through the identical path.\n *\n * Lives apart from `ServerQueryStore` on purpose: the store is pure and\n * unit-testable, while this pulls in the whole service-container graph.\n */\nexport function createServerQueryFetcher(req: Request): ServerQueryFetcher {\n // `app()` resolves through the kernel's AsyncLocalStorage. The factory runs\n // inside it (request handling always does), but a render-discovered query\n // fires from React's streaming render, which the http server drives\n // *outside* the kernel scope — so capture the store now and re-enter it\n // around every fetch.\n const kernelStore = kernelContext.getStore();\n return (patternPath, params, searchParams) => {\n const origin = new URL(req.url).origin;\n const pathnameWithSearch = [applyParams(patternPath, params), searchParams.toString()]\n .filter((s) => s.length > 0)\n .join(\"?\");\n const newReq = new Request(`${origin}/${pathnameWithSearch}`, {\n headers: req.headers,\n });\n const httpRequest = new HttpRequest(newReq, params);\n return kernelContext.run(kernelStore, () =>\n RequestContext.run(httpRequest, async () => {\n try {\n const data = await app(ApiRouteDispatcher).getRouteData(patternPath);\n // A handler that broke (`RequestBreakerError`) comes back as an\n // error `Response`, not a throw. Surface it as the same\n // `QueryError` the browser's fetch would produce — otherwise the\n // entry \"resolves\" and the view renders with a Response object for\n // data.\n if (data instanceof Response) {\n const body = await data.json().catch(() => null);\n if (!data.ok) {\n throw new QueryError(\n applyParams(patternPath, params),\n searchParams.toString(),\n data.status,\n body,\n );\n }\n return body;\n }\n return data;\n } catch (err) {\n if (err instanceof QueryError) throw err;\n // A raw throw inside the api handler (not a `RequestBreakerError`)\n // would otherwise leave this boundary unwrapped, so `onRequestFail`\n // would see an error with no path/variant/status attached — the\n // browser's fetch for the same failure produces a 500 `QueryError`.\n // Wrapping here keeps the two paths interchangeable and keeps the\n // error identity stable for the router's rethrow dedupe\n // (`Query.instant` rethrows the entry's — now wrapped — error).\n const wrapped = new QueryError(\n applyParams(patternPath, params),\n searchParams.toString(),\n 500,\n { message: err instanceof Error ? err.message : String(err) },\n );\n wrapped.cause = err;\n throw wrapped;\n }\n }),\n );\n };\n}\n",
|
|
48
|
+
"import type { RPC } from \"../client/rpc\";\nimport type { UrlParser } from \"../client/types\";\nimport type { ApiRouterHandler } from \"../http/ApiRouter\";\nimport { RequestContext } from \"../http/requestContext\";\nimport { ServerQueryStore, type ServerQueryEntry } from \"../services/router/ServerQueryStore\";\nimport { createServerQueryFetcher } from \"../services/router/serverQueryFetcher\";\n\ntype GetRPC = {\n [K in keyof RPC as K extends `GET:${infer P}` ? P : never]: RPC[K];\n};\n\ntype Data<T extends keyof GetRPC> = GetRPC[T] extends ApiRouterHandler<\n any,\n infer Data,\n any\n>\n ? Awaited<Data>\n : never;\n\ntype QueryFacadeOptions<T extends keyof GetRPC> = {\n search?: Record<string, string | number | boolean | null>;\n params?: Partial<UrlParser<T>>;\n};\n\nexport class Query {\n private static ensure<T extends keyof GetRPC>(\n path: T,\n options: QueryFacadeOptions<T> = {},\n ): ServerQueryEntry {\n const ctx = RequestContext.getStore();\n\n if (ctx.req.kind === \"api\") {\n throw new Error(\"Query.prefetch() cannot be called from an API request\");\n }\n\n // The view router creates the store up front; this lazy fallback keeps the\n // facade usable anywhere else a view-kind request context exists.\n ctx.serverQueries ??= new ServerQueryStore(\n createServerQueryFetcher(ctx.req.rawRequest),\n );\n\n return ctx.serverQueries.ensure(path, options, \"prefetch\");\n }\n\n /**\n * Start the query AND wait for it — the response cannot begin until it\n * resolves, so its data is part of the first paint. Use for data the shell\n * itself needs; `prefetch` for everything that may stream.\n */\n static async instant<T extends keyof GetRPC>(\n path: T,\n ...args: [options?: QueryFacadeOptions<T>]\n ): Promise<Data<T>> {\n const entry = Query.ensure(path, args[0]);\n await entry.promise;\n if (entry.status === \"rejected\") {\n throw entry.error;\n }\n return entry.data as Data<T>;\n }\n\n /**\n * Start the query now, in parallel with everything else this request does,\n * without blocking the response on it. A `useQuery` for the same path and\n * search renders with this data the moment it lands — in the document\n * payload when it wins the render, streamed into the page when it doesn't.\n */\n static prefetch<T extends keyof GetRPC>(\n path: T,\n ...args: [options?: QueryFacadeOptions<T>]\n ) {\n Query.ensure(path, args[0]);\n }\n\n /**\n * Declare that this route primes nothing on purpose, silencing the dev-mode\n * late-discovery hints for the request. Priming is not free — prefetched\n * data is re-fetched and streamed into every client-navigation payload for\n * the route, even when the client already holds it — so a handler that\n * deliberately leaves a heavy query to `useQuery`'s cache-then-revalidate\n * can say so instead of being nagged.\n */\n static noPrefetch() {\n const ctx = RequestContext.getStore();\n\n if (ctx.req.kind === \"api\") {\n throw new Error(\"Query.noPrefetch() cannot be called from an API request\");\n }\n\n ctx.serverQueries ??= new ServerQueryStore(\n createServerQueryFetcher(ctx.req.rawRequest),\n );\n ctx.serverQueries.muteDiscoveryHints();\n }\n}\n",
|
|
49
|
+
"import type { UrlParser, ViewPaths } from \"../client/types\";\nimport { applyParams } from \"../utils/applyParams\";\n\nexport class Url {\n static absolute<T extends ViewPaths>(\n key: T,\n ...args: UrlParser<T> extends Record<string, never>\n ? []\n : [params: UrlParser<T>]\n ) {\n return `${process.env.HOST_NAME}${applyParams(String(key), args[0] ?? {})}`;\n }\n\n static relative<T extends ViewPaths>(\n key: T,\n ...args: UrlParser<T> extends Record<string, never>\n ? []\n : [params: UrlParser<T>]\n ) {\n return applyParams(String(key), args[0] ?? {});\n }\n}\n",
|
|
50
|
+
"import type { OpenGraphParams } from \"../http/Metadata\";\nimport { RequestContext } from \"../http/requestContext\";\n\nexport class Meta {\n protected name = \"Meta\";\n static description(description: string) {\n RequestContext.getStore().metadata.description(description);\n }\n static title(title: string) {\n RequestContext.getStore().metadata.title(title);\n }\n static openGraph(params: OpenGraphParams) {\n RequestContext.getStore().metadata.openGraph(params);\n }\n}\n",
|
|
51
|
+
"import {\n RequestContext,\n type CreateCookieOptions,\n} from \"../http/requestContext\";\n\nexport const Cookie = {\n set(name: string, value: string, options: CreateCookieOptions) {\n RequestContext.getStore().setCookie(name, value, options);\n },\n setIfAbsent(name: string, value: string, options: CreateCookieOptions) {\n if (RequestContext.getStore().req.cookies.has(name)) {\n return false;\n }\n RequestContext.getStore().setCookie(name, value, options);\n return true;\n },\n delete(name: string) {\n RequestContext.getStore().deleteCookie(name);\n },\n};\n",
|
|
52
|
+
"import type { RedisClient, RedisOptions } from \"bun\";\nimport type { RedisConfig } from \"./config\";\n\n/**\n * The constructor `Bun.RedisClient` is, described structurally.\n *\n * Reached through the `Bun` global rather than `import { RedisClient } from\n * \"bun\"`, which is what this module used to do. That was a **value** import of\n * a specifier only the Bun runtime can resolve, and this class is re-exported\n * from `gemi/services` and reached from `gemi/facades` through the `Redis`\n * facade — the two barrels that are also the only door to `CronJob`, `Job`,\n * `DB` and `Lang`. So the specifier landed in the graph of every app and every\n * test that imported either one, and under a browser-targeted runner the whole\n * barrel simply failed to resolve (#396, #403).\n *\n * The global carries no specifier for a bundler or a test runner to resolve, so\n * the cost is paid only by code that actually asks for a client.\n */\ntype RedisClientConstructor = new (\n url?: string,\n options?: RedisOptions,\n) => RedisClient;\n\nexport class RedisManager {\n static token = \"redis\";\n\n private instance: RedisClient | null = null;\n\n constructor(public config: RedisConfig = {}) {}\n\n /**\n * Bun's Redis client. Built on first access and memoized.\n *\n * It connects lazily on the first command, so building it here is safe even\n * when Redis isn't running or configured — nothing connects until something\n * actually issues a command.\n */\n get client(): RedisClient {\n return (this.instance ??= new (redisClientConstructor())(\n this.config.url,\n this.config.options,\n ));\n }\n\n /**\n * `client` was a plain public property before it was a getter, and\n * overwriting a manager's client is how this repo fakes one —\n * `S3Driver.test.ts` does exactly that, and the `S3Driver` half of #403 kept\n * that seam working on purpose. An accessor with no setter would have turned\n * `manager.client = fake` into `TypeError: Attempted to assign to readonly\n * property` instead, which is not a change this was meant to make.\n */\n set client(client: RedisClient) {\n this.instance = client;\n }\n}\n\nfunction redisClientConstructor(): RedisClientConstructor {\n const ctor = (globalThis as any).Bun?.RedisClient as\n | RedisClientConstructor\n | undefined;\n\n if (typeof ctor !== \"function\") {\n throw new Error(\n \"Redis requires Bun's built-in Redis client, which this runtime does not provide. Run the app under Bun, or bind your own client for the 'redis' token.\",\n );\n }\n\n return ctor;\n}\n",
|
|
53
|
+
"import type { RedisClient } from \"bun\";\nimport { RedisManager } from \"../services/redis/RedisManager\";\nimport { Facade } from \"./Facade\";\n\n// Ergonomic access to the app's Redis client. Use `Redis.client` for the full\n// Bun Redis API (hashes, sets, sorted sets, pub/sub, pipelining, ...); the\n// static shortcuts below cover the most common string commands.\nexport class Redis extends Facade {\n static getFacadeAccessor() {\n return RedisManager;\n }\n\n static get client(): RedisClient {\n return this.getFacadeRoot().client;\n }\n\n static get(key: string) {\n return Redis.client.get(key);\n }\n\n static set(key: string, value: string) {\n return Redis.client.set(key, value);\n }\n\n static del(...keys: string[]) {\n return Redis.client.del(...keys);\n }\n\n static exists(key: string) {\n return Redis.client.exists(key);\n }\n\n static incr(key: string) {\n return Redis.client.incr(key);\n }\n\n static expire(key: string, seconds: number) {\n return Redis.client.expire(key, seconds);\n }\n\n static ttl(key: string) {\n return Redis.client.ttl(key);\n }\n}\n",
|
|
54
|
+
"import {\n type ConsumeOptions,\n RateLimiter as RateLimiterManager,\n} from \"../services/rate-limiter/RateLimiter\";\nimport type { RateLimitResult } from \"../services/rate-limiter/types\";\nimport { Facade } from \"./Facade\";\n\n/**\n * The rate limiter, outside of middleware — for the things a route-level limit\n * cannot express: a per-user budget on an expensive job, a cooldown on\n * password-reset emails, a quota on a third-party API you pay for.\n *\n * ```ts\n * const result = await RateLimiter.consume(`reset-password:${email}`, {\n * limit: 3,\n * window: 3600,\n * });\n *\n * if (!result.allowed) {\n * return { error: `Try again in ${Math.ceil(result.retryAfter / 1000)}s` };\n * }\n * ```\n */\nexport class RateLimiter extends Facade {\n static getFacadeAccessor() {\n return RateLimiterManager;\n }\n\n /** Records one hit against `key` and reports whether it fits the budget. */\n static consume(\n key: string,\n options: ConsumeOptions = {},\n ): Promise<RateLimitResult> {\n return this.getFacadeRoot().consume(key, options);\n }\n}\n",
|
|
55
|
+
"import type { SQL } from \"bun\";\nimport type { DatabaseConnection } from \"../database/Connection\";\nimport { DatabaseManager } from \"../database/DatabaseManager\";\nimport type { Dialect } from \"../database/dialect\";\nimport { app } from \"../foundation/app\";\nimport {\n assertConnectionUsable,\n currentConnectionName,\n currentTransaction,\n runOnConnection,\n withTransaction,\n} from \"../orm/context\";\nimport { dialectFor } from \"../orm/dialect\";\nimport { renderFragment, type SqlFragment } from \"../orm/sql\";\nimport { Facade } from \"./Facade\";\n\n/**\n * The raw-SQL surface, pointed at one connection.\n *\n * `DB` itself is one of these — the one that resolves the **ambient**\n * connection per call — and `DB.connection(name)` returns one bound to a name.\n * Written once rather than twice so the two cannot drift: a fragment run\n * through a named connection has to reach the driver by exactly the path\n * `DB.query` does, or the ambient transaction, the placeholder numbering and\n * the string refusal would each be a thing that works on one of them.\n *\n * Every method resolves the manager, the connection and the dialect **per\n * call** and captures none of them, which is the rule `Model.$exec` follows and\n * what keeps the connection swappable in tests.\n */\nexport class ConnectionQueries {\n /**\n * `undefined` means *whichever connection is ambient*, which is the default\n * one unless an enclosing transaction or `Model.on` named another. That is\n * the mode `DB`'s own statics use, and it is why an unqualified `DB.query`\n * inside `DB.connection(\"analytics\").transaction(...)` joins that transaction\n * instead of being refused by it.\n */\n constructor(private readonly bound?: string) {}\n\n /** The name this handle will use for the call happening now. */\n get name(): string {\n return this.bound ?? currentConnectionName();\n }\n\n /**\n * The Bun `SQL` client. Tagged-template queries go through here.\n *\n * **The pool, not the open transaction.** `DB.sql` has always been Bun's own\n * template and has never joined the ambient transaction — on Postgres it runs\n * on a pooled connection and survives a rollback — and a named handle does\n * not change that, only which pool it is. `query` and `execute` are the ones\n * that join; reach for them when the difference matters.\n *\n * **This getter throws where the methods reject**, and it cannot do\n * otherwise: an accessor has nowhere to put a rejection. So\n * `DB.connection(\"typo\").sql` throws `UnknownConnectionError` synchronously,\n * and reading it while a transaction is open on another connection throws\n * `CrossConnectionTransactionError` the same way. `query`, `execute` and\n * `transaction` are `async` precisely so a `.catch()` cannot miss those.\n */\n get sql(): SQL {\n return this.connection().sql;\n }\n\n /**\n * Which database is in use, inferred from the connection URL. Read this when\n * generating SQL that differs across databases (upserts, `RETURNING`,\n * autoincrement, boolean and timestamp types).\n *\n * Throws rather than rejects, for the reason given on `sql` above.\n */\n get dialect(): Dialect {\n return this.connection().dialect;\n }\n\n // Runs a composed fragment and returns its rows.\n //\n // const where = filters.length ? sql`where ${join(filters, \" and \")}` : empty\n // const rows = await DB.query(sql`select * from \"Product\" ${where}`)\n //\n // Two things it does that `DB.sql` does not, and they are the reason it\n // exists rather than being sugar:\n //\n // - It takes a **fragment**, so a predicate can be built as a value and\n // passed around. See `orm/sql.ts` for why that shape is the one raw SQL\n // actually needs.\n // - It runs on the **ambient transaction** when there is one. A raw statement\n // that quietly escapes `Model.transaction` and commits while its neighbours\n // roll back is worse than no raw statement at all — so this resolves the\n // handle exactly as `Model.$exec` does, through `currentTransaction()`.\n //\n // A plain string is refused. That is deliberate: accepting one would make an\n // interpolated template the path of least resistance, which is the injection\n // this whole mechanism exists to keep closed. `unsafeSql` is the door, and it\n // is named so that using it is a decision.\n //\n // `async` rather than returning the driver's promise directly, so that a\n // rejected fragment — a plain string, a parameter count over the ceiling —\n // *rejects* instead of throwing synchronously. An API that does one sometimes\n // and the other otherwise is a footgun: `DB.query(...).catch(…)` would miss\n // exactly the errors this refuses to run.\n async query<T = any>(fragment: SqlFragment): Promise<T[]> {\n return (await this.run(fragment, \"query\")) as T[];\n }\n\n // The same, for a statement whose answer is *how many rows it touched*.\n //\n // const won = await DB.execute(\n // sql`update \"Reservation\" set status = 'claimed'\n // where id = ${id} and status = 'reserved'`,\n // )\n // if (won === 0) { /* somebody else claimed it first */ }\n //\n // The count is the concurrency primitive there, not a diagnostic: 1 means this\n // caller won the compare-and-swap and 0 means it lost, and an API that\n // discarded it could not express that at all.\n //\n // **Where the number comes from.** Bun puts it on `count`, and leaves\n // `affectedRows` null — measured on both dialects rather than read from a\n // changelog, for `update`, `delete`, `insert`, a statement matching nothing,\n // and one with `returning`.\n //\n // `result.count` on what is otherwise an *array* reads like a bug, so: Bun\n // returns an array with `count`, `command` and `lastInsertRowid` hung off it,\n // on every statement including the ones that return no rows at all. A write\n // without `returning` is therefore a zero-length array whose `count` is the\n // number of rows it touched, and a write *with* one is an array of the rows\n // whose `count` matches their number. `compile/write.ts` records the same measurement\n // from the other side: the *ORM's* counts come from `RETURNING` instead,\n // because there the statement shape is ours to choose and an exact count that\n // depends on nothing undocumented is worth a key column per row. Here the\n // statement is the caller's, so there is nothing to add a `RETURNING` to.\n async execute(fragment: SqlFragment): Promise<number> {\n const result = await this.run(fragment, \"execute\");\n return Number((result as { count?: unknown })?.count ?? 0);\n }\n\n // Runs the callback inside a transaction, committing when it resolves and\n // rolling back if it throws. The callback still receives the raw handle, as\n // it always has.\n //\n // It goes through the ORM's `withTransaction` rather than straight to\n // `sql.begin` so that the two transaction systems are one: a `User.create`\n // inside a `DB.transaction` joins it instead of committing separately on a\n // pooled connection, and a `DB.transaction` nested inside a\n // `Model.transaction` becomes a savepoint instead of throwing (Bun refuses\n // `begin` inside a transaction). Two systems that silently ignored each other\n // would be worse than either alone — a rollback would leave half the work\n // committed.\n //\n // The slow-transaction threshold comes from the same `database` config as it\n // does for the ORM, so a `DB.transaction` holding a connection too long warns\n // exactly as a `Model.transaction` would. Same reason as above: one system.\n //\n // On a named connection the whole callback runs with that connection ambient,\n // so a `User.create` inside `DB.connection(\"analytics\").transaction(...)`\n // joins the transaction rather than opening a second one on the hot path.\n //\n // `async` so that a handle used inside a transaction on another connection\n // *rejects* rather than throwing synchronously — the same reason `query`\n // above is, and the same `.catch()` that would otherwise miss it.\n async transaction<T>(fn: (tx: SQL) => Promise<T>): Promise<T> {\n const name = this.name;\n const connection = this.connection(name);\n\n return withTransaction(\n connection.sql,\n (tx) => runOnConnection(name, () => fn(tx)),\n {\n slowTransactionThreshold: connection.config.slowTransactionThreshold,\n connection: name,\n },\n );\n }\n\n private run(fragment: SqlFragment, operation: string) {\n const db = this.connection();\n // Per call, never captured: the same rule `Model.$exec` follows, and what\n // keeps the connection swappable in tests.\n const { text, values } = renderFragment(\n fragment,\n dialectFor(db.dialect),\n operation,\n );\n return (this.handle() ?? db.sql).unsafe(text, values);\n }\n\n /**\n * The open transaction, but only when it belongs to this handle's connection.\n *\n * `assertConnectionUsable` has already refused the case where they differ, so\n * reaching this with a mismatch is impossible — except for the unqualified\n * handle, whose name *is* the transaction's. The comparison is kept anyway\n * because it is what makes that reasoning local: nothing here has to know\n * which caller checked what.\n */\n private handle() {\n const tx = currentTransaction();\n if (tx === undefined) return undefined;\n return currentConnectionName() === this.name ? tx : undefined;\n }\n\n private connection(name = this.name): DatabaseConnection {\n assertConnectionUsable(name);\n return app(DatabaseManager).connection(name);\n }\n}\n\n/** The unqualified handle: whichever connection is ambient, per call. */\nconst ambient = new ConnectionQueries();\n\n// Access to the app's database connections. Bun's `SQL` client is a tagged\n// template, so queries read the same here as they do in Bun's own docs:\n//\n// const users = await DB.sql`select * from users where id = ${id}`\n//\n// Values interpolated into the template are bound as parameters, not\n// concatenated into the SQL string — `${id}` is a placeholder, so this is not a\n// SQL injection risk.\n//\n// Every static here works on the **ambient** connection: the default one,\n// unless an enclosing `DB.connection(name).transaction(...)` named another.\n// `DB.connection(name)` is the way to name one explicitly.\nexport class DB extends Facade {\n static getFacadeAccessor() {\n return DatabaseManager;\n }\n\n /**\n * The raw-SQL surface for a named connection.\n *\n * const rows = await DB.connection(\"analytics\").query(sql`…`)\n * await DB.connection(\"analytics\").transaction(async () => { … })\n *\n * The names are the keys of `connections` in `app/config/database.ts`, plus\n * `\"default\"` for the top-level `url`. An unknown one raises\n * `UnknownConnectionError` when the handle is used, listing what is\n * configured — never a silent fall back to the default, which would put the\n * query on precisely the pool the caller was trying to stay off.\n *\n * A transaction cannot span two connections. Using a named handle while a\n * transaction is open on another connection raises\n * `CrossConnectionTransactionError` rather than running the statement outside\n * that transaction, where it would survive the rollback.\n */\n // Built per call rather than memoised by name. A handle is one string and a\n // few methods that resolve everything else per call, so caching it saves an\n // allocation — and a `Map` keyed on the caller's string is a slow leak the\n // moment a name reaches it from a request, since an unknown name is not\n // rejected until the handle is *used*. Nothing is worth keeping here.\n static connection(name: string): ConnectionQueries {\n return new ConnectionQueries(name);\n }\n\n // The Bun `SQL` client. Tagged-template queries go through here.\n static get sql(): SQL {\n return ambient.sql;\n }\n\n // Which database is in use, inferred from the connection URL. Read this when\n // generating SQL that differs across databases (upserts, `RETURNING`,\n // autoincrement, boolean and timestamp types).\n static get dialect(): Dialect {\n return ambient.dialect;\n }\n\n // Runs a composed fragment and returns its rows, on the ambient transaction\n // when there is one. See `ConnectionQueries.query`, which is the whole of it.\n static query<T = any>(fragment: SqlFragment): Promise<T[]> {\n return ambient.query<T>(fragment);\n }\n\n // The same, for a statement whose answer is *how many rows it touched* — the\n // compare-and-swap primitive. See `ConnectionQueries.execute`.\n static execute(fragment: SqlFragment): Promise<number> {\n return ambient.execute(fragment);\n }\n\n // Runs the callback inside a transaction, committing when it resolves and\n // rolling back if it throws. One transaction system with the ORM's, so a\n // `User.create` inside this joins it. See `ConnectionQueries.transaction`.\n static transaction<T>(fn: (tx: SQL) => Promise<T>): Promise<T> {\n return ambient.transaction(fn);\n }\n\n /** Closes every configured connection, not only the default one. */\n static close(): Promise<void> {\n return this.getFacadeRoot().close();\n }\n}\n"
|
|
56
|
+
],
|
|
57
|
+
"mappings": ";mlBAwBO,AAAe,LAAO,CACpB,YAAiB,JAAsB,LAC5C,AAAU,MACR,WAAW,KAAK,+CAClB,QAGK,cAAgB,EAEjB,CACJ,OAAO,EAAI,KAAK,kBAAkB,CAAC,EAEvC,CCjCA,4BAAS,qBAIF,MAAM,EAAiB,CAST,aARZ,OAAQ,YAEf,UACA,QAAU,IAAI,GAKd,WAAW,CAAQ,EAAmC,CAAnC,iBAEf,SAAQ,EAAG,CACb,OAAO,KAAK,OAAO,SAGrB,SAAS,CAAC,EAAqB,CAC7B,KAAK,UAAY,EAGnB,OAAO,IAAI,EAAmB,CAC5B,IAAO,EAAO,EAAM,GAAY,EAChC,KAAK,UAAU,EAAO,EAAM,CAAQ,OAGhC,cAAa,CACjB,EACA,EACA,CACA,IAAM,EAAc,KAAK,MAAM,CAAiB,EAChD,GAAI,EAAY,OAAS,YAAa,CACpC,IAAM,EAAiB,OAAO,QAAQ,KAAK,QAAQ,EAAE,KACnD,EAAE,IAAQ,KAAU,EAAK,OAAS,EAAK,MACzC,EACA,QAAY,EAAU,KAAY,EAAgB,CAChD,IAAM,EAAa,IAAI,WAAW,CAAE,UAAS,CAAC,EAC9C,GAAI,EAAW,KAAK,CAAE,SAAU,EAAY,KAAM,CAAC,EAAG,CACpD,IAAM,EAAS,EAAW,KAAK,CAAE,SAAU,EAAY,KAAM,CAAC,GAC1D,SAAS,OACP,EAAW,IAAI,EAErB,GADqB,MAAM,EAAS,UAAU,KAAK,EAAU,CAAM,EAEjE,EAAG,UAAU,EAAY,KAAK,EAGhC,QAIN,GAAI,EAAY,OAAS,YACvB,EAAG,QACD,EAAY,MACZ,KAAK,UAAU,CAAE,MAAO,EAAY,MAAO,KAAM,EAAY,OAAQ,CAAC,CACxE,EAEF,GAAI,EAAY,OAAS,c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