@contello/astro 4.4.1 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2 @@
1
+ export declare const onRequest: any;
2
+ //# sourceMappingURL=assets-middleware-entrypoint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assets-middleware-entrypoint.d.ts","names":[],"sources":["../src/assets-middleware-entrypoint.ts"],"mappings":"A,qBAEa"}
@@ -0,0 +1,6 @@
1
+ import { contello } from "virtual:@contello/astro/instance";
2
+ // src/assets-middleware-entrypoint.ts
3
+ const onRequest = contello.createAssetsMiddleware();
4
+ export { onRequest };
5
+
6
+ //# sourceMappingURL=assets-middleware-entrypoint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assets-middleware-entrypoint.js","names":[],"sources":["../src/assets-middleware-entrypoint.ts"],"sourcesContent":["import { contello } from 'virtual:@contello/astro/instance';\n\nexport const onRequest = contello.createAssetsMiddleware();\n"],"mappings":";;AAEA,MAAa,YAAY,SAAS,uBAAuB"}
package/dist/index.cjs CHANGED
@@ -1,28 +1,109 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ // \0rolldown/runtime.js
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: ((k) => from[k]).bind(null, key),
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+ let node_fs = require("node:fs");
27
+ node_fs = __toESM(node_fs, 1);
28
+ let node_path = require("node:path");
29
+ node_path = __toESM(node_path, 1);
30
+ let node_url = require("node:url");
31
+ let _astroscope_node_excludes = require("@astroscope/node/excludes");
2
32
  let node_async_hooks = require("node:async_hooks");
3
33
  let _astroscope_i18n = require("@astroscope/i18n");
4
34
  let _astroscope_node_boot = require("@astroscope/node/boot");
35
+ let _astroscope_node_health = require("@astroscope/node/health");
5
36
  let _contello_media = require("@contello/media");
6
37
  let _contello_store = require("@contello/store");
7
38
  let _astroscope_node_log = require("@astroscope/node/log");
8
39
  let _contello_opentelemetry = require("@contello/opentelemetry");
9
- let _astroscope_node_excludes = require("@astroscope/node/excludes");
10
40
  let _entwico_dash = require("@entwico/dash");
11
- //#region src/middleware.ts
41
+ const RESOLVED_CONFIG_VIRTUAL_MODULE_ID = `\0virtual:@contello/astro/config`;
42
+ /**
43
+ * Resolves the instance id straight to the project's module, so the injected
44
+ * middlewares and the project's own imports share one `Contello` instance, and
45
+ * serves the serializable integration options as a config module.
46
+ */
47
+ function contelloVitePlugin(options) {
48
+ return {
49
+ name: "@contello/astro",
50
+ resolveId(id) {
51
+ if (id === "virtual:@contello/astro/instance") return options.entry;
52
+ if (id === "virtual:@contello/astro/config") return RESOLVED_CONFIG_VIRTUAL_MODULE_ID;
53
+ },
54
+ load(id) {
55
+ if (id === RESOLVED_CONFIG_VIRTUAL_MODULE_ID) return `export const exclude = ${options.exclude ? (0, _astroscope_node_excludes.serializeExcludePatterns)(options.exclude) : "null"};`;
56
+ }
57
+ };
58
+ }
59
+ // src/integration.ts
60
+ const DEFAULT_ENTRY = "src/server/contello.ts";
61
+ /**
62
+ * Astro integration for Contello.
63
+ *
64
+ * Injects the assets middleware ahead of the project's own middleware and the routing
65
+ * middleware after it, both bound to the project's `contello` instance, which the
66
+ * integration resolves from `src/server/contello.ts` (or `entry`). Runtime options
67
+ * (`resolveRoutePath`, assets cache control, the routes instance) live on the instance,
68
+ * only serializable ones belong here.
69
+ */
70
+ function contelloIntegration(options = {}) {
71
+ const { entry = DEFAULT_ENTRY, assets = "pre", routing = "post", exclude = null } = options;
72
+ return {
73
+ name: "@contello/astro",
74
+ hooks: { "astro:config:setup": ({ config, updateConfig, addMiddleware }) => {
75
+ const entryPath = node_path.default.resolve((0, node_url.fileURLToPath)(config.root), entry);
76
+ if (!node_fs.default.existsSync(entryPath)) throw new Error(`@contello/astro: instance module ${entry} not found — export \`contello = createContello(...)\` from it or point the integration's \`entry\` option at it`);
77
+ if (assets) addMiddleware({
78
+ order: assets,
79
+ entrypoint: "@contello/astro/assets-middleware"
80
+ });
81
+ if (routing) addMiddleware({
82
+ order: routing,
83
+ entrypoint: "@contello/astro/routing-middleware"
84
+ });
85
+ updateConfig({ vite: { plugins: [contelloVitePlugin({
86
+ entry: entryPath,
87
+ exclude
88
+ })] } });
89
+ } }
90
+ };
91
+ }
92
+ // src/middleware.ts
12
93
  function defineMiddleware(handler) {
13
94
  return handler;
14
95
  }
15
- //#endregion
16
- //#region src/telemetry.ts
96
+ // src/telemetry.ts
17
97
  const { wrap } = (0, _contello_opentelemetry.createOperationTelemetry)("@contello/astro");
18
- //#endregion
19
- //#region src/assets-middleware.ts
98
+ // src/assets-middleware.ts
20
99
  const DEFAULT_IMAGES_CACHE_CONTROL = "public, max-age=31536000";
100
+ /**
101
+ * `options` is read per request: the integration creates the middleware before `init()`
102
+ * brings the project's assets options; `false` disables the middleware (`init({ assets: false })`).
103
+ */
21
104
  function createBoundAssetsMiddleware(contello, options) {
22
105
  const imagesPrefix = contello.media.imagesPath;
23
- const imagesCacheControl = options?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL;
24
106
  const filesPrefix = contello.media.filesPath;
25
- const filesCacheControl = options?.files?.cacheControl;
26
107
  const videoPrefix = contello.media.videosPath;
27
108
  return defineMiddleware((ctx, next) => {
28
109
  const { pathname } = ctx.url;
@@ -30,12 +111,14 @@ function createBoundAssetsMiddleware(contello, options) {
30
111
  const isFile = !isImage && pathname.startsWith(filesPrefix);
31
112
  const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);
32
113
  if (!isImage && !isFile && !isVideo) return next();
114
+ const current = options();
115
+ if (current === false) return next();
33
116
  if (!contello.isReady) {
34
117
  console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);
35
118
  return next();
36
119
  }
37
- if (isImage) return handleFile(contello.client, next, pathname.slice(imagesPrefix.length), imagesCacheControl, `${imagesPrefix}[file]`);
38
- if (isFile) return handleFile(contello.client, next, pathname.slice(filesPrefix.length), filesCacheControl, `${filesPrefix}[file]`);
120
+ if (isImage) return handleFile(contello.client, next, pathname.slice(imagesPrefix.length), current?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL, `${imagesPrefix}[file]`);
121
+ if (isFile) return handleFile(contello.client, next, pathname.slice(filesPrefix.length), current?.files?.cacheControl, `${filesPrefix}[file]`);
39
122
  return handleVideo(contello.client, next, pathname.slice(videoPrefix.length), ctx.request.signal, `${videoPrefix}[...path]`);
40
123
  });
41
124
  }
@@ -74,8 +157,7 @@ function handleVideo(client, next, path, signal, routeLabel) {
74
157
  }
75
158
  })();
76
159
  }
77
- //#endregion
78
- //#region src/routing-middleware.ts
160
+ // src/routing-middleware.ts
79
161
  function customHeaders(headers) {
80
162
  const result = {};
81
163
  for (const h of headers) result[h.name] = h.value;
@@ -112,6 +194,8 @@ function createBoundRoutingMiddleware(contello, routes, exclude, resolveRoutePat
112
194
  console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
113
195
  return next();
114
196
  }
197
+ const current = routes();
198
+ if (!current) return next();
115
199
  const { url } = ctx;
116
200
  if (url.pathname.startsWith("/contello/entities/")) return contello[runRequest]({
117
201
  url,
@@ -119,7 +203,7 @@ function createBoundRoutingMiddleware(contello, routes, exclude, resolveRoutePat
119
203
  rewritten: false
120
204
  }, () => next());
121
205
  const path = resolveRoutePath ? resolveRoutePath(ctx) : url.pathname;
122
- const lookup = routes.getByPath(path);
206
+ const lookup = current.getByPath(path);
123
207
  return (0, _entwico_dash.maybeThen)(lookup, (route) => {
124
208
  if (!route) return contello[runRequest]({
125
209
  url,
@@ -200,13 +284,15 @@ function createBoundRoutingMiddleware(contello, routes, exclude, resolveRoutePat
200
284
  });
201
285
  });
202
286
  }
203
- //#endregion
204
- //#region src/contello.ts
287
+ // src/contello.ts
205
288
  const DEFAULT_IMAGES_PREFIX = "/_contello/i/";
206
289
  const DEFAULT_FILES_PREFIX = "/_contello/f/";
207
290
  const DEFAULT_VIDEO_PREFIX = "/_contello/v/";
291
+ function isLoadable(value) {
292
+ return typeof value.load === "function";
293
+ }
208
294
  const runRequest = Symbol("@contello/astro/runRequest");
209
- function buildI18nRegistrations() {
295
+ function createI18nRegistrations() {
210
296
  const manifest = _astroscope_i18n.i18n.getManifest();
211
297
  const defaultLanguage = _astroscope_i18n.i18n.getConfig().defaultLocale;
212
298
  return manifest.keys.map((extracted) => ({
@@ -242,14 +328,20 @@ var Contello = class {
242
328
  _i18nUnsubscribe;
243
329
  _initialized = false;
244
330
  _als = new node_async_hooks.AsyncLocalStorage();
245
- _autoLazyRoutes;
331
+ _routes;
332
+ _initOptions;
333
+ _unregisterHealthCheck;
246
334
  media;
247
335
  createRoutingMiddleware = (options) => {
248
- const routes = options?.routes ?? (this._autoLazyRoutes ??= this.defineLazyRoutes());
249
- return createBoundRoutingMiddleware(this, routes, options?.exclude, options?.resolveRoutePath);
336
+ const routes = () => options?.routes ?? (this._initOptions?.routes === false ? void 0 : this.routes);
337
+ const resolveRoutePath = (ctx) => {
338
+ const resolver = options?.resolveRoutePath ?? this._initOptions?.routing?.resolveRoutePath;
339
+ return resolver ? resolver(ctx) : ctx.url.pathname;
340
+ };
341
+ return createBoundRoutingMiddleware(this, routes, options?.exclude, resolveRoutePath);
250
342
  };
251
343
  createAssetsMiddleware = (options) => {
252
- return createBoundAssetsMiddleware(this, options);
344
+ return createBoundAssetsMiddleware(this, () => options ?? this._initOptions?.assets);
253
345
  };
254
346
  constructor(options) {
255
347
  this._options = options;
@@ -261,20 +353,42 @@ var Contello = class {
261
353
  filesPath: options.media?.filesPath ?? DEFAULT_FILES_PREFIX
262
354
  };
263
355
  }
356
+ createRoutes(routes) {
357
+ switch (routes) {
358
+ case false: return;
359
+ case "sync": return this.defineRoutesSync();
360
+ case "lazy": return this.defineLazyRoutes();
361
+ default: return routes;
362
+ }
363
+ }
364
+ registerHealthCheck(health) {
365
+ if (health === false) return;
366
+ this._unregisterHealthCheck?.();
367
+ this._unregisterHealthCheck = (0, _astroscope_node_health.registerHealthCheck)({
368
+ name: health?.name ?? "contello",
369
+ check: () => this.ping(),
370
+ optional: health?.optional,
371
+ timeout: health?.timeout
372
+ });
373
+ }
264
374
  async init(options) {
265
375
  try {
376
+ this._initOptions = options;
377
+ this.registerHealthCheck(options.health);
266
378
  await this._store.init();
379
+ this._routes = this.createRoutes(options.routes);
267
380
  if (this._options.i18n) {
268
- const { collection, languages, cache } = this._options.i18n;
381
+ if (!options.i18n) throw new Error("@contello/astro: init() needs the i18n option (locales, locale resolver) for the configured i18n collection");
382
+ const { collection, cache } = this._options.i18n;
269
383
  const dev = (0, _astroscope_node_boot.getBootContext)()?.dev ?? false;
270
- const { register = !dev, load = true } = options?.i18n ?? {};
384
+ const { register = !dev, load = true, ...i18nConfig } = options.i18n;
271
385
  this._i18nMessages = this._store.defineI18nMessages({
272
386
  collection,
273
387
  cache
274
388
  });
275
- await _astroscope_i18n.i18n.configure({ locales: languages });
389
+ await _astroscope_i18n.i18n.configure(i18nConfig);
276
390
  if (register) {
277
- const registrations = buildI18nRegistrations();
391
+ const registrations = createI18nRegistrations();
278
392
  if (registrations.length > 0) await this._i18nMessages.register(registrations);
279
393
  }
280
394
  if (load) {
@@ -290,7 +404,9 @@ var Contello = class {
290
404
  })();
291
405
  }
292
406
  }
293
- await Promise.all((options?.load ?? []).map((l) => l.load()));
407
+ const routes = this._routes;
408
+ const loadables = [...options.load ?? [], ...routes && isLoadable(routes) ? [routes] : []];
409
+ await Promise.all(loadables.map((l) => l.load()));
294
410
  this._initialized = true;
295
411
  } catch (error) {
296
412
  try {
@@ -303,8 +419,12 @@ var Contello = class {
303
419
  this._initialized = false;
304
420
  this._i18nUnsubscribe?.();
305
421
  this._i18nUnsubscribe = void 0;
422
+ this._unregisterHealthCheck?.();
423
+ this._unregisterHealthCheck = void 0;
306
424
  await this._store.destroy();
307
425
  this._i18nMessages = void 0;
426
+ this._routes = void 0;
427
+ this._initOptions = void 0;
308
428
  }
309
429
  ping() {
310
430
  return this._store.ping();
@@ -315,6 +435,11 @@ var Contello = class {
315
435
  get client() {
316
436
  return this._store.client;
317
437
  }
438
+ /** the routes backing the routing middleware, created by `init()` from its `routes` option */
439
+ get routes() {
440
+ if (!this._routes) throw new Error("@contello/astro: .routes accessed before init() or with routes disabled");
441
+ return this._routes;
442
+ }
318
443
  get i18nMessages() {
319
444
  if (!this._i18nMessages) throw new Error("@contello/astro: .i18nMessages accessed before init() with i18n config");
320
445
  return this._i18nMessages;
@@ -370,6 +495,6 @@ var Contello = class {
370
495
  function createContello(options) {
371
496
  return new Contello(options);
372
497
  }
373
- //#endregion
374
498
  exports.Contello = Contello;
375
499
  exports.createContello = createContello;
500
+ exports.default = contelloIntegration;
package/dist/index.d.cts CHANGED
@@ -1,10 +1,46 @@
1
+ import { ExcludePattern } from "@astroscope/node/excludes";
2
+ import { APIContext, AstroIntegration } from "astro";
3
+ import { I18nConfig } from "@astroscope/i18n";
1
4
  import { ContelloClient, Schema, SourceDef } from "@contello/client";
2
5
  import { MediaResolver, MediaResolverOptions } from "@contello/media";
3
6
  import { Assets, AssetsOptions, AssetsSync, AssetsSyncOptions, BuiltInWrites, Collection, CollectionOptions, CollectionSync, CollectionSyncOptions, CreateStoreOptions, ExtractSourceResult, ExtractSourceWrites, I18nMessages, LazyAssets, LazyAssetsOptions, LazyCollection, LazyCollectionOptions, LazyRoutes, LazyRoutesOptions, Loadable, ResolveSource, Routes, RoutesOptions, RoutesSync, RoutesSyncOptions, Singleton, SingletonOptions, SingletonSync, SingletonSyncOptions, SourceKeysOf, StoreRoute, SyncCacheOptions } from "@contello/store";
4
7
  import { ReadonlyDeep } from "@entwico/dash";
5
- import { ExcludePattern } from "@astroscope/node/excludes";
6
- import { APIContext } from "astro";
7
- //#region src/assets-middleware.d.ts
8
+ type ContelloIntegrationOptions = {
9
+ /**
10
+ * Module exporting the `contello` instance (`export const contello = createContello(...)`),
11
+ * relative to the project root.
12
+ * @default 'src/server/contello.ts'
13
+ */
14
+ entry?: string | undefined;
15
+ /**
16
+ * Where the assets middleware (`/_contello/i/`, `/_contello/f/`, `/_contello/v/`) is injected;
17
+ * `false` leaves it to the project (`contello.createAssetsMiddleware()`).
18
+ * @default 'pre'
19
+ */
20
+ assets?: 'pre' | false | undefined;
21
+ /**
22
+ * Where the routing middleware is injected; `false` leaves it to the project
23
+ * (`contello.createRoutingMiddleware()`). Post middlewares run in `integrations` order, so list
24
+ * `contello()` before integrations whose middleware depends on the resolved route, e.g. `@astroscope/wormhole`.
25
+ * @default 'post'
26
+ */
27
+ routing?: 'post' | false | undefined;
28
+ /**
29
+ * Paths the routing middleware skips.
30
+ * @default RECOMMENDED_EXCLUDES from `@astroscope/node/excludes`
31
+ */
32
+ exclude?: ExcludePattern[] | undefined;
33
+ };
34
+ /**
35
+ * Astro integration for Contello.
36
+ *
37
+ * Injects the assets middleware ahead of the project's own middleware and the routing
38
+ * middleware after it, both bound to the project's `contello` instance, which the
39
+ * integration resolves from `src/server/contello.ts` (or `entry`). Runtime options
40
+ * (`resolveRoutePath`, assets cache control, the routes instance) live on the instance,
41
+ * only serializable ones belong here.
42
+ */
43
+ export default function contelloIntegration(options?: ContelloIntegrationOptions): AstroIntegration;
8
44
  type ContelloAssetsImagesOptions = {
9
45
  cacheControl?: string | undefined;
10
46
  };
@@ -17,8 +53,6 @@ type ContelloAssetsMiddlewareOptions = {
17
53
  files?: ContelloAssetsFilesOptions | undefined;
18
54
  video?: ContelloAssetsVideoOptions | undefined;
19
55
  };
20
- //#endregion
21
- //#region src/routing-middleware.d.ts
22
56
  type AnyRoutes = Routes | RoutesSync | LazyRoutes;
23
57
  /**
24
58
  * Derives the path used to look up a Contello route from the request context.
@@ -42,25 +76,55 @@ type ContelloRoutingMiddlewareOptions = {
42
76
  exclude?: ExcludePattern[] | undefined;
43
77
  resolveRoutePath?: RoutePathResolver | undefined;
44
78
  };
45
- //#endregion
46
- //#region src/contello.d.ts
47
79
  type ContelloRequestContext = {
48
80
  url: URL;
49
81
  route: ReadonlyDeep<StoreRoute> | undefined;
50
82
  rewritten: boolean;
51
83
  };
84
+ /** The Contello i18n message collection bridged to `@astroscope/i18n`; `init()` takes the runtime side. */
52
85
  type ContelloI18nOptions = {
53
86
  collection: string;
54
- languages: string[];
55
87
  cache?: SyncCacheOptions | undefined;
56
88
  };
89
+ /**
90
+ * The `@astroscope/i18n` config `init()` passes to `i18n.configure()` before it pushes the
91
+ * collection's translations, plus what to do with the extracted keys.
92
+ */
93
+ type ContelloInitI18nOptions = I18nConfig & {
94
+ /**
95
+ * Register the extracted keys in the collection; defaults to `true`, except in dev mode (detected via the
96
+ * @astroscope/node boot context).
97
+ */
98
+ register?: boolean | undefined;
99
+ /** push the collection's translations and follow its refreshes; defaults to `true` */
100
+ load?: boolean | undefined;
101
+ };
102
+ type ContelloRoutingOptions = {
103
+ resolveRoutePath?: RoutePathResolver | undefined;
104
+ };
105
+ /** The readiness check `init()` registers with `@astroscope/node/health`; `false` registers none. */
106
+ type ContelloHealthOptions = {
107
+ /** @default 'contello' */
108
+ name?: string | undefined;
109
+ optional?: boolean | undefined;
110
+ timeout?: number | undefined;
111
+ };
57
112
  type ContelloInitOptions = {
58
113
  load?: Loadable[] | undefined;
59
- i18n?: {
60
- /** defaults to `true`, except in dev mode (detected via the @astroscope/node boot context) */
61
- register?: boolean | undefined;
62
- load?: boolean | undefined;
63
- } | undefined;
114
+ /**
115
+ * Routes backing the routing middleware: `'sync'` creates and loads a `RoutesSync` (eager, synchronous
116
+ * lookups), `'lazy'` creates a `LazyRoutes` (fetched on demand), or an instance the project defined
117
+ * itself, loaded by `init()` when it is loadable. Reachable as `contello.routes` after `init()`.
118
+ * `false` for a project without Contello routes: the routing middleware passes through.
119
+ */
120
+ routes: 'sync' | 'lazy' | AnyRoutes | false;
121
+ /** required when `createContello` got an `i18n` collection */
122
+ i18n?: ContelloInitI18nOptions | undefined;
123
+ /** defaults for the routing middleware, used by the integration-injected one */
124
+ routing?: ContelloRoutingOptions | undefined;
125
+ /** defaults for the assets middleware, used by the integration-injected one; `false` makes it pass through */
126
+ assets?: ContelloAssetsMiddlewareOptions | false | undefined;
127
+ health?: ContelloHealthOptions | false | undefined;
64
128
  };
65
129
  type ContelloMediaConfig = {
66
130
  readonly baseUrl: string;
@@ -94,16 +158,22 @@ export declare class Contello<TSchema extends Schema | undefined = undefined> {
94
158
  private _i18nUnsubscribe;
95
159
  private _initialized;
96
160
  private readonly _als;
97
- private _autoLazyRoutes?;
161
+ private _routes;
162
+ private _initOptions;
163
+ private _unregisterHealthCheck;
98
164
  readonly media: ContelloMediaConfig;
99
165
  createRoutingMiddleware: (options?: ContelloRoutingMiddlewareOptions | undefined) => import("astro").MiddlewareHandler;
100
166
  createAssetsMiddleware: (options?: ContelloAssetsMiddlewareOptions | undefined) => import("astro").MiddlewareHandler;
101
167
  constructor(options: ContelloOptions<TSchema>);
102
- init(options?: ContelloInitOptions | undefined): Promise<void>;
168
+ private createRoutes;
169
+ private registerHealthCheck;
170
+ init(options: ContelloInitOptions): Promise<void>;
103
171
  destroy(): Promise<void>;
104
172
  ping(): Promise<void>;
105
173
  get isReady(): boolean;
106
174
  get client(): ContelloClient<TSchema>;
175
+ /** the routes backing the routing middleware, created by `init()` from its `routes` option */
176
+ get routes(): AnyRoutes;
107
177
  get i18nMessages(): I18nMessages;
108
178
  get request(): ContelloRequestContext;
109
179
  defineMediaResolver<O extends Partial<MediaResolverOptions>>(options?: O): MediaResolver<HasFallback<O>>;
@@ -133,6 +203,5 @@ export declare class Contello<TSchema extends Schema | undefined = undefined> {
133
203
  [runRequest]<T>(ctx: ContelloRequestContext, fn: () => T): T;
134
204
  }
135
205
  export declare function createContello<TSchema extends Schema | undefined = undefined>(options: ContelloOptions<TSchema>): Contello<TSchema>;
136
- //#endregion
137
- export type { AnyRoutes, ContelloAssetsFilesOptions, ContelloAssetsImagesOptions, ContelloAssetsMiddlewareOptions, ContelloAssetsVideoOptions, ContelloI18nOptions, ContelloInitOptions, ContelloOptions, ContelloRequestContext, ContelloRoutingMiddlewareOptions };
206
+ export type { AnyRoutes, ContelloAssetsFilesOptions, ContelloAssetsImagesOptions, ContelloAssetsMiddlewareOptions, ContelloAssetsVideoOptions, ContelloHealthOptions, ContelloI18nOptions, ContelloInitI18nOptions, ContelloInitOptions, ContelloIntegrationOptions, ContelloOptions, ContelloRequestContext, ContelloRoutingMiddlewareOptions, ContelloRoutingOptions, RoutePathResolver };
138
207
  //# sourceMappingURL=index.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../src/assets-middleware.ts","../src/routing-middleware.ts","../src/contello.ts"],"mappings":";;;;;;;KAMY;EACV;;KAGU;EACV;;KAGU,6BAA6B;KAE7B;EACV,SAAS;EACT,QAAQ;EACR,QAAQ;;;;KCTE,YAAY,SAAS,aAAa;;;;;;;;;;KAWlC,qBAAqB,KAAK;KAE1B;;;;;;;;EAQV,SAAS;EACT,UAAU;EACV,mBAAmB;;;;KCiBT;EACV,KAAK;EACL,OAAO,aAAa;EACpB;;KAGU;EAC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B,cAAc,SAAS,OAAO,SAAS,SAAS,YAC3E,WAAW,SAAS,mBAAmB,SAAS;EAOnD,qBACE,aAAa,cAAc,UAC3B;IAAkB;MAAe,cAAc,SAAS;IAAU;KAElE,aAAa,MACb,UAAU,sBAAsB,cAAc,SAAS,OAAO,SAAS,SAAS,YAC/E,eAAe,SAAS,mBAAmB,SAAS;EAOvD,qBACE,aAAa,cAAc,UAC3B;IAAkB;MAAe,cAAc,SAAS;IAAU;KAElE,aAAa,MACb,UAAU,sBAAsB,cAAc,SAAS,OAAO,SAAS,SAAS,YAC/E,eAAe;EAIlB,aAAa,UAAU,4BAA4B,OAAO,YAAY;EAItE,iBAAiB,UAAU,gCAAgC,WAAW,YAAY;EAIlF,iBAAiB,UAAU,gCAAgC;EAI3D,aAAa,UAAU,4BAA4B,OAAO,YAAY;EAItE,iBAAiB,UAAU,gCAAgC,WAAW,YAAY;EAIlF,iBAAiB,UAAU,gCAAgC;GAM1D,YAAY,GAAG,KAAK,wBAAwB,UAAU,IAAI;;wBAK7C,eAAe,gBAAgB,gCAC7C,SAAS,gBAAgB,WACxB,SAAS"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/integration.ts","../src/assets-middleware.ts","../src/routing-middleware.ts","../src/contello.ts"],"mappings":";;;;;;;KASY;;;;;;EAMV;;;;;;EAMA;;;;;;;EAOA;;;;;EAKA,UAAU;;;;;;;;;;;wBAYY,oBAAoB,UAAS,6BAAkC;KCvC3E;EACV;;KAGU;EACV;;KAGU,6BAA6B;KAE7B;EACV,SAAS;EACT,QAAQ;EACR,QAAQ;;KCTE,YAAY,SAAS,aAAa;;;;;;;;;;KAWlC,qBAAqB,KAAK;KAE1B;;;;;;;;EAQV,SAAS;EACT,UAAU;EACV,mBAAmB;;KCuBT;EACV,KAAK;EACL,OAAO,aAAa;EACpB;;;KAIU;EACV;EACA,QAAQ;;;;;;KAOE,0BAA0B;;;;;EAKpC;;EAEA;;KAGU;EACV,mBAAmB;;;KAIT;;EAEV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E,aAAa,cAAc,UAC3B;IAAkB;MAAe,cAAc,SAAS;IAAU;KAElE,aAAa,MACb,UAAU,kBAAkB,cAAc,SAAS,OAAO,SAAS,SAAS,YAC3E,WAAW,SAAS,mBAAmB,SAAS;EAOnD,qBACE,aAAa,cAAc,UAC3B;IAAkB;MAAe,cAAc,SAAS;IAAU;KAElE,aAAa,MACb,UAAU,sBAAsB,cAAc,SAAS,OAAO,SAAS,SAAS,YAC/E,eAAe,SAAS,mBAAmB,SAAS;EAOvD,qBACE,aAAa,cAAc,UAC3B;IAAkB;MAAe,cAAc,SAAS;IAAU;KAElE,aAAa,MACb,UAAU,sBAAsB,cAAc,SAAS,OAAO,SAAS,SAAS,YAC/E,eAAe;EAIlB,aAAa,UAAU,4BAA4B,OAAO,YAAY;EAItE,iBAAiB,UAAU,gCAAgC,WAAW,YAAY;EAIlF,iBAAiB,UAAU,gCAAgC;EAI3D,aAAa,UAAU,4BAA4B,OAAO,YAAY;EAItE,iBAAiB,UAAU,gCAAgC,WAAW,YAAY;EAIlF,iBAAiB,UAAU,gCAAgC;GAM1D,YAAY,GAAG,KAAK,wBAAwB,UAAU,IAAI;;wBAK7C,eAAe,gBAAgB,gCAC7C,SAAS,gBAAgB,WACxB,SAAS"}
package/dist/index.d.ts CHANGED
@@ -1,10 +1,46 @@
1
+ import { ExcludePattern } from "@astroscope/node/excludes";
2
+ import { I18nConfig } from "@astroscope/i18n";
1
3
  import { MediaResolver, MediaResolverOptions } from "@contello/media";
2
4
  import { Assets, AssetsOptions, AssetsSync, AssetsSyncOptions, BuiltInWrites, Collection, CollectionOptions, CollectionSync, CollectionSyncOptions, CreateStoreOptions, ExtractSourceResult, ExtractSourceWrites, I18nMessages, LazyAssets, LazyAssetsOptions, LazyCollection, LazyCollectionOptions, LazyRoutes, LazyRoutesOptions, Loadable, ResolveSource, Routes, RoutesOptions, RoutesSync, RoutesSyncOptions, Singleton, SingletonOptions, SingletonSync, SingletonSyncOptions, SourceKeysOf, StoreRoute, SyncCacheOptions } from "@contello/store";
3
- import { ExcludePattern } from "@astroscope/node/excludes";
4
5
  import { ReadonlyDeep } from "@entwico/dash";
6
+ import { APIContext, AstroIntegration } from "astro";
5
7
  import { ContelloClient, Schema, SourceDef } from "@contello/client";
6
- import { APIContext } from "astro";
7
- //#region src/assets-middleware.d.ts
8
+ type ContelloIntegrationOptions = {
9
+ /**
10
+ * Module exporting the `contello` instance (`export const contello = createContello(...)`),
11
+ * relative to the project root.
12
+ * @default 'src/server/contello.ts'
13
+ */
14
+ entry?: string | undefined;
15
+ /**
16
+ * Where the assets middleware (`/_contello/i/`, `/_contello/f/`, `/_contello/v/`) is injected;
17
+ * `false` leaves it to the project (`contello.createAssetsMiddleware()`).
18
+ * @default 'pre'
19
+ */
20
+ assets?: 'pre' | false | undefined;
21
+ /**
22
+ * Where the routing middleware is injected; `false` leaves it to the project
23
+ * (`contello.createRoutingMiddleware()`). Post middlewares run in `integrations` order, so list
24
+ * `contello()` before integrations whose middleware depends on the resolved route, e.g. `@astroscope/wormhole`.
25
+ * @default 'post'
26
+ */
27
+ routing?: 'post' | false | undefined;
28
+ /**
29
+ * Paths the routing middleware skips.
30
+ * @default RECOMMENDED_EXCLUDES from `@astroscope/node/excludes`
31
+ */
32
+ exclude?: ExcludePattern[] | undefined;
33
+ };
34
+ /**
35
+ * Astro integration for Contello.
36
+ *
37
+ * Injects the assets middleware ahead of the project's own middleware and the routing
38
+ * middleware after it, both bound to the project's `contello` instance, which the
39
+ * integration resolves from `src/server/contello.ts` (or `entry`). Runtime options
40
+ * (`resolveRoutePath`, assets cache control, the routes instance) live on the instance,
41
+ * only serializable ones belong here.
42
+ */
43
+ export default function contelloIntegration(options?: ContelloIntegrationOptions): AstroIntegration;
8
44
  type ContelloAssetsImagesOptions = {
9
45
  cacheControl?: string | undefined;
10
46
  };
@@ -17,8 +53,6 @@ type ContelloAssetsMiddlewareOptions = {
17
53
  files?: ContelloAssetsFilesOptions | undefined;
18
54
  video?: ContelloAssetsVideoOptions | undefined;
19
55
  };
20
- //#endregion
21
- //#region src/routing-middleware.d.ts
22
56
  type AnyRoutes = Routes | RoutesSync | LazyRoutes;
23
57
  /**
24
58
  * Derives the path used to look up a Contello route from the request context.
@@ -42,25 +76,55 @@ type ContelloRoutingMiddlewareOptions = {
42
76
  exclude?: ExcludePattern[] | undefined;
43
77
  resolveRoutePath?: RoutePathResolver | undefined;
44
78
  };
45
- //#endregion
46
- //#region src/contello.d.ts
47
79
  type ContelloRequestContext = {
48
80
  url: URL;
49
81
  route: ReadonlyDeep<StoreRoute> | undefined;
50
82
  rewritten: boolean;
51
83
  };
84
+ /** The Contello i18n message collection bridged to `@astroscope/i18n`; `init()` takes the runtime side. */
52
85
  type ContelloI18nOptions = {
53
86
  collection: string;
54
- languages: string[];
55
87
  cache?: SyncCacheOptions | undefined;
56
88
  };
89
+ /**
90
+ * The `@astroscope/i18n` config `init()` passes to `i18n.configure()` before it pushes the
91
+ * collection's translations, plus what to do with the extracted keys.
92
+ */
93
+ type ContelloInitI18nOptions = I18nConfig & {
94
+ /**
95
+ * Register the extracted keys in the collection; defaults to `true`, except in dev mode (detected via the
96
+ * @astroscope/node boot context).
97
+ */
98
+ register?: boolean | undefined;
99
+ /** push the collection's translations and follow its refreshes; defaults to `true` */
100
+ load?: boolean | undefined;
101
+ };
102
+ type ContelloRoutingOptions = {
103
+ resolveRoutePath?: RoutePathResolver | undefined;
104
+ };
105
+ /** The readiness check `init()` registers with `@astroscope/node/health`; `false` registers none. */
106
+ type ContelloHealthOptions = {
107
+ /** @default 'contello' */
108
+ name?: string | undefined;
109
+ optional?: boolean | undefined;
110
+ timeout?: number | undefined;
111
+ };
57
112
  type ContelloInitOptions = {
58
113
  load?: Loadable[] | undefined;
59
- i18n?: {
60
- /** defaults to `true`, except in dev mode (detected via the @astroscope/node boot context) */
61
- register?: boolean | undefined;
62
- load?: boolean | undefined;
63
- } | undefined;
114
+ /**
115
+ * Routes backing the routing middleware: `'sync'` creates and loads a `RoutesSync` (eager, synchronous
116
+ * lookups), `'lazy'` creates a `LazyRoutes` (fetched on demand), or an instance the project defined
117
+ * itself, loaded by `init()` when it is loadable. Reachable as `contello.routes` after `init()`.
118
+ * `false` for a project without Contello routes: the routing middleware passes through.
119
+ */
120
+ routes: 'sync' | 'lazy' | AnyRoutes | false;
121
+ /** required when `createContello` got an `i18n` collection */
122
+ i18n?: ContelloInitI18nOptions | undefined;
123
+ /** defaults for the routing middleware, used by the integration-injected one */
124
+ routing?: ContelloRoutingOptions | undefined;
125
+ /** defaults for the assets middleware, used by the integration-injected one; `false` makes it pass through */
126
+ assets?: ContelloAssetsMiddlewareOptions | false | undefined;
127
+ health?: ContelloHealthOptions | false | undefined;
64
128
  };
65
129
  type ContelloMediaConfig = {
66
130
  readonly baseUrl: string;
@@ -94,16 +158,22 @@ export declare class Contello<TSchema extends Schema | undefined = undefined> {
94
158
  private _i18nUnsubscribe;
95
159
  private _initialized;
96
160
  private readonly _als;
97
- private _autoLazyRoutes?;
161
+ private _routes;
162
+ private _initOptions;
163
+ private _unregisterHealthCheck;
98
164
  readonly media: ContelloMediaConfig;
99
165
  createRoutingMiddleware: (options?: ContelloRoutingMiddlewareOptions | undefined) => import("astro").MiddlewareHandler;
100
166
  createAssetsMiddleware: (options?: ContelloAssetsMiddlewareOptions | undefined) => import("astro").MiddlewareHandler;
101
167
  constructor(options: ContelloOptions<TSchema>);
102
- init(options?: ContelloInitOptions | undefined): Promise<void>;
168
+ private createRoutes;
169
+ private registerHealthCheck;
170
+ init(options: ContelloInitOptions): Promise<void>;
103
171
  destroy(): Promise<void>;
104
172
  ping(): Promise<void>;
105
173
  get isReady(): boolean;
106
174
  get client(): ContelloClient<TSchema>;
175
+ /** the routes backing the routing middleware, created by `init()` from its `routes` option */
176
+ get routes(): AnyRoutes;
107
177
  get i18nMessages(): I18nMessages;
108
178
  get request(): ContelloRequestContext;
109
179
  defineMediaResolver<O extends Partial<MediaResolverOptions>>(options?: O): MediaResolver<HasFallback<O>>;
@@ -133,6 +203,5 @@ export declare class Contello<TSchema extends Schema | undefined = undefined> {
133
203
  [runRequest]<T>(ctx: ContelloRequestContext, fn: () => T): T;
134
204
  }
135
205
  export declare function createContello<TSchema extends Schema | undefined = undefined>(options: ContelloOptions<TSchema>): Contello<TSchema>;
136
- //#endregion
137
- export type { AnyRoutes, ContelloAssetsFilesOptions, ContelloAssetsImagesOptions, ContelloAssetsMiddlewareOptions, ContelloAssetsVideoOptions, ContelloI18nOptions, ContelloInitOptions, ContelloOptions, ContelloRequestContext, ContelloRoutingMiddlewareOptions };
206
+ export type { AnyRoutes, ContelloAssetsFilesOptions, ContelloAssetsImagesOptions, ContelloAssetsMiddlewareOptions, ContelloAssetsVideoOptions, ContelloHealthOptions, ContelloI18nOptions, ContelloInitI18nOptions, ContelloInitOptions, ContelloIntegrationOptions, ContelloOptions, ContelloRequestContext, ContelloRoutingMiddlewareOptions, ContelloRoutingOptions, RoutePathResolver };
138
207
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/assets-middleware.ts","../src/routing-middleware.ts","../src/contello.ts"],"mappings":";;;;;;;KAMY;EACV;;KAGU;EACV;;KAGU,6BAA6B;KAE7B;EACV,SAAS;EACT,QAAQ;EACR,QAAQ;;;;KCTE,YAAY,SAAS,aAAa;;;;;;;;;;KAWlC,qBAAqB,KAAK;KAE1B;;;;;;;;EAQV,SAAS;EACT,UAAU;EACV,mBAAmB;;;;KCiBT;EACV,KAAK;EACL,OAAO,aAAa;EACpB;;KAGU;EACV;EACA;EACA,QAAQ;;KAGE;EACV,OAAO;EACP;;IAGI;IACA;;;KAKM;WACD;WACA;WACA;WACA;;KAGC,gBAAgB,gBAAgB,kCAAkC,mBAAmB;EAC/F,OAAO;EACP,QAAQ,QAAQ;;KAGb,YAAY,KAAK;EAAY,gBAAgB;MAAQ;cAE7C;KA2CR,SAAS,WAAW;EAAkB,cAAc;UAAY;KAChE,cAAc,WAAW,aAAa,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AAe,cAAc,SAAS;IAAU;KAElE,aAAa,MACb,UAAU,sBAAsB,cAAc,SAAS,OAAO,SAAS,SAAS,YAC/E,eAAe;EAIlB,aAAa,UAAU,4BAA4B,OAAO,YAAY;EAItE,iBAAiB,UAAU,gCAAgC,WAAW,YAAY;EAIlF,iBAAiB,UAAU,gCAAgC;EAI3D,aAAa,UAAU,4BAA4B,OAAO,YAAY;EAItE,iBAAiB,UAAU,gCAAgC,WAAW,YAAY;EAIlF,iBAAiB,UAAU,gCAAgC;GAM1D,YAAY,GAAG,KAAK,wBAAwB,UAAU,IAAI;;wBAK7C,eAAe,gBAAgB,gCAC7C,SAAS,gBAAgB,WACxB,SAAS"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/integration.ts","../src/assets-middleware.ts","../src/routing-middleware.ts","../src/contello.ts"],"mappings":";;;;;;;KASY;;;;;;EAMV;;;;;;EAMA;;;;;;;EAOA;;;;;EAKA,UAAU;;;;;;;;;;;wBAYY,oBAAoB,UAAS,6BAAkC;KCvC3E;EACV;;KAGU;EACV;;KAGU,6BAA6B;KAE7B;EACV,SAAS;EACT,QAAQ;EACR,QAAQ;;KCTE,YAAY,SAAS,aAAa;;;;;;;;;;KAWlC,qBAAqB,KAAK;KAE1B;;;;;;;;EAQV,SAAS;EACT,UAAU;EACV,mBAAmB;;KCuBT;EACV,KAAK;EACL,OAAO,aAAa;EACpB;;;KAIU;EACV;EACA,QAAQ;;;;;;KAOE,0BAA0B;;;;;EAKpC;;EAEA;;KAGU;EACV,mBAAmB;;;KAIT;;EAEV;EACA;EACA;;KAGU;EACV,OAAO;;;;;;;EAOP,0BAA0B;;EAE1B,OAAO;;EAEP,UAAU;;EAEV,SAAS;EACT,SAAS;;KAGC;WACD;WACA;WACA;WACA;;KAGC,gBAAgB,gBAAgB,kCAAkC,mBAAmB;EAC/F,OAAO;EACP,QAAQ,QAAQ;;KAOb,YAAY,KAAK;EAAY,gBAAgB;MAAQ;cAE7C;KA2CR,SAAS,WA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,SAAS,YAC/E,eAAe,SAAS,mBAAmB,SAAS;EAOvD,qBACE,aAAa,cAAc,UAC3B;IAAkB;MAAe,cAAc,SAAS;IAAU;KAElE,aAAa,MACb,UAAU,sBAAsB,cAAc,SAAS,OAAO,SAAS,SAAS,YAC/E,eAAe;EAIlB,aAAa,UAAU,4BAA4B,OAAO,YAAY;EAItE,iBAAiB,UAAU,gCAAgC,WAAW,YAAY;EAIlF,iBAAiB,UAAU,gCAAgC;EAI3D,aAAa,UAAU,4BAA4B,OAAO,YAAY;EAItE,iBAAiB,UAAU,gCAAgC,WAAW,YAAY;EAIlF,iBAAiB,UAAU,gCAAgC;GAM1D,YAAY,GAAG,KAAK,wBAAwB,UAAU,IAAI;;wBAK7C,eAAe,gBAAgB,gCAC7C,SAAS,gBAAgB,WACxB,SAAS"}
package/dist/index.js CHANGED
@@ -1,27 +1,82 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { RECOMMENDED_EXCLUDES, serializeExcludePatterns, shouldExclude } from "@astroscope/node/excludes";
1
5
  import { AsyncLocalStorage } from "node:async_hooks";
2
6
  import { i18n } from "@astroscope/i18n";
3
7
  import { getBootContext } from "@astroscope/node/boot";
8
+ import { registerHealthCheck } from "@astroscope/node/health";
4
9
  import { createMediaResolver } from "@contello/media";
5
10
  import { createStore } from "@contello/store";
6
11
  import { overrideRequestRoute } from "@astroscope/node/log";
7
12
  import { createOperationTelemetry, updateActiveSpan } from "@contello/opentelemetry";
8
- import { RECOMMENDED_EXCLUDES, shouldExclude } from "@astroscope/node/excludes";
9
13
  import { maybeThen } from "@entwico/dash";
10
- //#region src/middleware.ts
14
+ const RESOLVED_CONFIG_VIRTUAL_MODULE_ID = `\0virtual:@contello/astro/config`;
15
+ /**
16
+ * Resolves the instance id straight to the project's module, so the injected
17
+ * middlewares and the project's own imports share one `Contello` instance, and
18
+ * serves the serializable integration options as a config module.
19
+ */
20
+ function contelloVitePlugin(options) {
21
+ return {
22
+ name: "@contello/astro",
23
+ resolveId(id) {
24
+ if (id === "virtual:@contello/astro/instance") return options.entry;
25
+ if (id === "virtual:@contello/astro/config") return RESOLVED_CONFIG_VIRTUAL_MODULE_ID;
26
+ },
27
+ load(id) {
28
+ if (id === RESOLVED_CONFIG_VIRTUAL_MODULE_ID) return `export const exclude = ${options.exclude ? serializeExcludePatterns(options.exclude) : "null"};`;
29
+ }
30
+ };
31
+ }
32
+ // src/integration.ts
33
+ const DEFAULT_ENTRY = "src/server/contello.ts";
34
+ /**
35
+ * Astro integration for Contello.
36
+ *
37
+ * Injects the assets middleware ahead of the project's own middleware and the routing
38
+ * middleware after it, both bound to the project's `contello` instance, which the
39
+ * integration resolves from `src/server/contello.ts` (or `entry`). Runtime options
40
+ * (`resolveRoutePath`, assets cache control, the routes instance) live on the instance,
41
+ * only serializable ones belong here.
42
+ */
43
+ function contelloIntegration(options = {}) {
44
+ const { entry = DEFAULT_ENTRY, assets = "pre", routing = "post", exclude = null } = options;
45
+ return {
46
+ name: "@contello/astro",
47
+ hooks: { "astro:config:setup": ({ config, updateConfig, addMiddleware }) => {
48
+ const entryPath = path.resolve(fileURLToPath(config.root), entry);
49
+ if (!fs.existsSync(entryPath)) throw new Error(`@contello/astro: instance module ${entry} not found — export \`contello = createContello(...)\` from it or point the integration's \`entry\` option at it`);
50
+ if (assets) addMiddleware({
51
+ order: assets,
52
+ entrypoint: "@contello/astro/assets-middleware"
53
+ });
54
+ if (routing) addMiddleware({
55
+ order: routing,
56
+ entrypoint: "@contello/astro/routing-middleware"
57
+ });
58
+ updateConfig({ vite: { plugins: [contelloVitePlugin({
59
+ entry: entryPath,
60
+ exclude
61
+ })] } });
62
+ } }
63
+ };
64
+ }
65
+ // src/middleware.ts
11
66
  function defineMiddleware(handler) {
12
67
  return handler;
13
68
  }
14
- //#endregion
15
- //#region src/telemetry.ts
69
+ // src/telemetry.ts
16
70
  const { wrap } = createOperationTelemetry("@contello/astro");
17
- //#endregion
18
- //#region src/assets-middleware.ts
71
+ // src/assets-middleware.ts
19
72
  const DEFAULT_IMAGES_CACHE_CONTROL = "public, max-age=31536000";
73
+ /**
74
+ * `options` is read per request: the integration creates the middleware before `init()`
75
+ * brings the project's assets options; `false` disables the middleware (`init({ assets: false })`).
76
+ */
20
77
  function createBoundAssetsMiddleware(contello, options) {
21
78
  const imagesPrefix = contello.media.imagesPath;
22
- const imagesCacheControl = options?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL;
23
79
  const filesPrefix = contello.media.filesPath;
24
- const filesCacheControl = options?.files?.cacheControl;
25
80
  const videoPrefix = contello.media.videosPath;
26
81
  return defineMiddleware((ctx, next) => {
27
82
  const { pathname } = ctx.url;
@@ -29,12 +84,14 @@ function createBoundAssetsMiddleware(contello, options) {
29
84
  const isFile = !isImage && pathname.startsWith(filesPrefix);
30
85
  const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);
31
86
  if (!isImage && !isFile && !isVideo) return next();
87
+ const current = options();
88
+ if (current === false) return next();
32
89
  if (!contello.isReady) {
33
90
  console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);
34
91
  return next();
35
92
  }
36
- if (isImage) return handleFile(contello.client, next, pathname.slice(imagesPrefix.length), imagesCacheControl, `${imagesPrefix}[file]`);
37
- if (isFile) return handleFile(contello.client, next, pathname.slice(filesPrefix.length), filesCacheControl, `${filesPrefix}[file]`);
93
+ if (isImage) return handleFile(contello.client, next, pathname.slice(imagesPrefix.length), current?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL, `${imagesPrefix}[file]`);
94
+ if (isFile) return handleFile(contello.client, next, pathname.slice(filesPrefix.length), current?.files?.cacheControl, `${filesPrefix}[file]`);
38
95
  return handleVideo(contello.client, next, pathname.slice(videoPrefix.length), ctx.request.signal, `${videoPrefix}[...path]`);
39
96
  });
40
97
  }
@@ -73,8 +130,7 @@ function handleVideo(client, next, path, signal, routeLabel) {
73
130
  }
74
131
  })();
75
132
  }
76
- //#endregion
77
- //#region src/routing-middleware.ts
133
+ // src/routing-middleware.ts
78
134
  function customHeaders(headers) {
79
135
  const result = {};
80
136
  for (const h of headers) result[h.name] = h.value;
@@ -111,6 +167,8 @@ function createBoundRoutingMiddleware(contello, routes, exclude, resolveRoutePat
111
167
  console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
112
168
  return next();
113
169
  }
170
+ const current = routes();
171
+ if (!current) return next();
114
172
  const { url } = ctx;
115
173
  if (url.pathname.startsWith("/contello/entities/")) return contello[runRequest]({
116
174
  url,
@@ -118,7 +176,7 @@ function createBoundRoutingMiddleware(contello, routes, exclude, resolveRoutePat
118
176
  rewritten: false
119
177
  }, () => next());
120
178
  const path = resolveRoutePath ? resolveRoutePath(ctx) : url.pathname;
121
- const lookup = routes.getByPath(path);
179
+ const lookup = current.getByPath(path);
122
180
  return maybeThen(lookup, (route) => {
123
181
  if (!route) return contello[runRequest]({
124
182
  url,
@@ -199,13 +257,15 @@ function createBoundRoutingMiddleware(contello, routes, exclude, resolveRoutePat
199
257
  });
200
258
  });
201
259
  }
202
- //#endregion
203
- //#region src/contello.ts
260
+ // src/contello.ts
204
261
  const DEFAULT_IMAGES_PREFIX = "/_contello/i/";
205
262
  const DEFAULT_FILES_PREFIX = "/_contello/f/";
206
263
  const DEFAULT_VIDEO_PREFIX = "/_contello/v/";
264
+ function isLoadable(value) {
265
+ return typeof value.load === "function";
266
+ }
207
267
  const runRequest = Symbol("@contello/astro/runRequest");
208
- function buildI18nRegistrations() {
268
+ function createI18nRegistrations() {
209
269
  const manifest = i18n.getManifest();
210
270
  const defaultLanguage = i18n.getConfig().defaultLocale;
211
271
  return manifest.keys.map((extracted) => ({
@@ -241,14 +301,20 @@ var Contello = class {
241
301
  _i18nUnsubscribe;
242
302
  _initialized = false;
243
303
  _als = new AsyncLocalStorage();
244
- _autoLazyRoutes;
304
+ _routes;
305
+ _initOptions;
306
+ _unregisterHealthCheck;
245
307
  media;
246
308
  createRoutingMiddleware = (options) => {
247
- const routes = options?.routes ?? (this._autoLazyRoutes ??= this.defineLazyRoutes());
248
- return createBoundRoutingMiddleware(this, routes, options?.exclude, options?.resolveRoutePath);
309
+ const routes = () => options?.routes ?? (this._initOptions?.routes === false ? void 0 : this.routes);
310
+ const resolveRoutePath = (ctx) => {
311
+ const resolver = options?.resolveRoutePath ?? this._initOptions?.routing?.resolveRoutePath;
312
+ return resolver ? resolver(ctx) : ctx.url.pathname;
313
+ };
314
+ return createBoundRoutingMiddleware(this, routes, options?.exclude, resolveRoutePath);
249
315
  };
250
316
  createAssetsMiddleware = (options) => {
251
- return createBoundAssetsMiddleware(this, options);
317
+ return createBoundAssetsMiddleware(this, () => options ?? this._initOptions?.assets);
252
318
  };
253
319
  constructor(options) {
254
320
  this._options = options;
@@ -260,20 +326,42 @@ var Contello = class {
260
326
  filesPath: options.media?.filesPath ?? DEFAULT_FILES_PREFIX
261
327
  };
262
328
  }
329
+ createRoutes(routes) {
330
+ switch (routes) {
331
+ case false: return;
332
+ case "sync": return this.defineRoutesSync();
333
+ case "lazy": return this.defineLazyRoutes();
334
+ default: return routes;
335
+ }
336
+ }
337
+ registerHealthCheck(health) {
338
+ if (health === false) return;
339
+ this._unregisterHealthCheck?.();
340
+ this._unregisterHealthCheck = registerHealthCheck({
341
+ name: health?.name ?? "contello",
342
+ check: () => this.ping(),
343
+ optional: health?.optional,
344
+ timeout: health?.timeout
345
+ });
346
+ }
263
347
  async init(options) {
264
348
  try {
349
+ this._initOptions = options;
350
+ this.registerHealthCheck(options.health);
265
351
  await this._store.init();
352
+ this._routes = this.createRoutes(options.routes);
266
353
  if (this._options.i18n) {
267
- const { collection, languages, cache } = this._options.i18n;
354
+ if (!options.i18n) throw new Error("@contello/astro: init() needs the i18n option (locales, locale resolver) for the configured i18n collection");
355
+ const { collection, cache } = this._options.i18n;
268
356
  const dev = getBootContext()?.dev ?? false;
269
- const { register = !dev, load = true } = options?.i18n ?? {};
357
+ const { register = !dev, load = true, ...i18nConfig } = options.i18n;
270
358
  this._i18nMessages = this._store.defineI18nMessages({
271
359
  collection,
272
360
  cache
273
361
  });
274
- await i18n.configure({ locales: languages });
362
+ await i18n.configure(i18nConfig);
275
363
  if (register) {
276
- const registrations = buildI18nRegistrations();
364
+ const registrations = createI18nRegistrations();
277
365
  if (registrations.length > 0) await this._i18nMessages.register(registrations);
278
366
  }
279
367
  if (load) {
@@ -289,7 +377,9 @@ var Contello = class {
289
377
  })();
290
378
  }
291
379
  }
292
- await Promise.all((options?.load ?? []).map((l) => l.load()));
380
+ const routes = this._routes;
381
+ const loadables = [...options.load ?? [], ...routes && isLoadable(routes) ? [routes] : []];
382
+ await Promise.all(loadables.map((l) => l.load()));
293
383
  this._initialized = true;
294
384
  } catch (error) {
295
385
  try {
@@ -302,8 +392,12 @@ var Contello = class {
302
392
  this._initialized = false;
303
393
  this._i18nUnsubscribe?.();
304
394
  this._i18nUnsubscribe = void 0;
395
+ this._unregisterHealthCheck?.();
396
+ this._unregisterHealthCheck = void 0;
305
397
  await this._store.destroy();
306
398
  this._i18nMessages = void 0;
399
+ this._routes = void 0;
400
+ this._initOptions = void 0;
307
401
  }
308
402
  ping() {
309
403
  return this._store.ping();
@@ -314,6 +408,11 @@ var Contello = class {
314
408
  get client() {
315
409
  return this._store.client;
316
410
  }
411
+ /** the routes backing the routing middleware, created by `init()` from its `routes` option */
412
+ get routes() {
413
+ if (!this._routes) throw new Error("@contello/astro: .routes accessed before init() or with routes disabled");
414
+ return this._routes;
415
+ }
317
416
  get i18nMessages() {
318
417
  if (!this._i18nMessages) throw new Error("@contello/astro: .i18nMessages accessed before init() with i18n config");
319
418
  return this._i18nMessages;
@@ -369,7 +468,6 @@ var Contello = class {
369
468
  function createContello(options) {
370
469
  return new Contello(options);
371
470
  }
372
- //#endregion
373
- export { Contello, createContello };
471
+ export { Contello, createContello, contelloIntegration as default };
374
472
 
375
473
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/middleware.ts","../src/telemetry.ts","../src/assets-middleware.ts","../src/routing-middleware.ts","../src/contello.ts"],"sourcesContent":["import type { MiddlewareHandler } from 'astro';\n\n// a local identity instead of `astro/middleware`: a runtime import of astro's middleware entry pulls every module that\n// imports this package into astro's runtime module graph — in dev, astro invalidates that graph on any file change,\n// which re-evaluates boot-loaded singletons and makes @astroscope/node restart the server on every component edit\nexport function defineMiddleware(handler: MiddlewareHandler): MiddlewareHandler {\n return handler;\n}\n","import { createOperationTelemetry } from '@contello/opentelemetry';\n\nexport const { wrap } = createOperationTelemetry('@contello/astro');\n","import { overrideRequestRoute } from '@astroscope/node/log';\nimport type { ContelloClient } from '@contello/client';\nimport type { Contello } from './contello';\nimport { defineMiddleware } from './middleware';\nimport { wrap } from './telemetry';\n\nexport type ContelloAssetsImagesOptions = {\n cacheControl?: string | undefined;\n};\n\nexport type ContelloAssetsFilesOptions = {\n cacheControl?: string | undefined;\n};\n\nexport type ContelloAssetsVideoOptions = Record<string, never>;\n\nexport type ContelloAssetsMiddlewareOptions = {\n images?: ContelloAssetsImagesOptions | undefined;\n files?: ContelloAssetsFilesOptions | undefined;\n video?: ContelloAssetsVideoOptions | undefined;\n};\n\nconst DEFAULT_IMAGES_CACHE_CONTROL = 'public, max-age=31536000';\n\nexport function createBoundAssetsMiddleware(\n contello: Contello<any>,\n options: ContelloAssetsMiddlewareOptions | undefined,\n) {\n const imagesPrefix = contello.media.imagesPath;\n const imagesCacheControl = options?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL;\n const filesPrefix = contello.media.filesPath;\n const filesCacheControl = options?.files?.cacheControl;\n const videoPrefix = contello.media.videosPath;\n\n return defineMiddleware((ctx, next) => {\n const { pathname } = ctx.url;\n const isImage = pathname.startsWith(imagesPrefix);\n const isFile = !isImage && pathname.startsWith(filesPrefix);\n const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);\n\n if (!isImage && !isFile && !isVideo) {\n return next();\n }\n\n if (!contello.isReady) {\n console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);\n\n return next();\n }\n\n if (isImage) {\n return handleFile(\n contello.client,\n next,\n pathname.slice(imagesPrefix.length),\n imagesCacheControl,\n `${imagesPrefix}[file]`,\n );\n }\n\n if (isFile) {\n return handleFile(\n contello.client,\n next,\n pathname.slice(filesPrefix.length),\n filesCacheControl,\n `${filesPrefix}[file]`,\n );\n }\n\n return handleVideo(\n contello.client,\n next,\n pathname.slice(videoPrefix.length),\n ctx.request.signal,\n `${videoPrefix}[...path]`,\n );\n });\n}\n\nfunction handleFile(\n client: ContelloClient<any>,\n next: () => Response | Promise<Response>,\n rest: string,\n cacheControl: string | undefined,\n routeLabel: string,\n) {\n const dot = rest.indexOf('.');\n const fileId = dot === -1 ? rest : rest.slice(0, dot);\n\n if (!fileId) {\n return next();\n }\n\n overrideRequestRoute(routeLabel);\n\n return (async () => {\n try {\n const result = await wrap('assets:file', () => client.download(fileId));\n const headers = new Headers({ 'content-type': result.mimeType });\n\n if (cacheControl) {\n headers.set('cache-control', cacheControl);\n }\n\n if (result.size > 0) {\n headers.set('content-length', String(result.size));\n }\n\n return new Response(result.stream(), { headers });\n } catch {\n return new Response(null, { status: 404 });\n }\n })();\n}\n\nfunction handleVideo(\n client: ContelloClient<any>,\n next: () => Response | Promise<Response>,\n path: string,\n signal: AbortSignal,\n routeLabel: string,\n) {\n if (!path) {\n return next();\n }\n\n overrideRequestRoute(routeLabel);\n\n return (async () => {\n try {\n const result = await wrap('assets:hls', () => client.proxyHls(path, signal));\n\n return new Response(result.stream(), { status: result.status, headers: result.headers });\n } catch {\n return new Response('Upstream is down', { status: 502, headers: { 'content-type': 'text/plain' } });\n }\n })();\n}\n","import { type ExcludePattern, RECOMMENDED_EXCLUDES, shouldExclude } from '@astroscope/node/excludes';\nimport { overrideRequestRoute } from '@astroscope/node/log';\nimport { updateActiveSpan } from '@contello/opentelemetry';\nimport type { LazyRoutes, Routes, RoutesSync, StoreRoute, StoreRouteCustomHeader } from '@contello/store';\nimport { type MaybePromise, maybeThen } from '@entwico/dash';\nimport type { APIContext, ValidRedirectStatus } from 'astro';\nimport { type Contello, runRequest } from './contello';\nimport { defineMiddleware } from './middleware';\nimport { wrap } from './telemetry';\n\nexport type AnyRoutes = Routes | RoutesSync | LazyRoutes;\n\n/**\n * Derives the path used to look up a Contello route from the request context.\n *\n * @default `(ctx) => ctx.url.pathname`\n *\n * ```ts\n * resolveRoutePath: (ctx) => `/${ctx.url.hostname}${ctx.url.pathname}`\n * ```\n */\nexport type RoutePathResolver = (ctx: APIContext) => string;\n\nexport type ContelloRoutingMiddlewareOptions = {\n /**\n * Routes instance backing the middleware.\n *\n * Defaults to a `LazyRoutes` instance managed by contello (fetched on demand, no init-time load).\n * For eager routing, create a `RoutesSync` via `contello.defineRoutesSync()`, add it to\n * `contello.init({ load: [routes] })`, and pass that same instance here.\n */\n routes?: AnyRoutes | undefined;\n exclude?: ExcludePattern[] | undefined;\n resolveRoutePath?: RoutePathResolver | undefined;\n};\n\nfunction customHeaders(headers: readonly StoreRouteCustomHeader[]): Record<string, string> {\n const result: Record<string, string> = {};\n\n for (const h of headers) {\n result[h.name] = h.value;\n }\n\n return result;\n}\n\nconst VALID_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\nfunction toRedirectStatus(status: number): ValidRedirectStatus {\n return (VALID_REDIRECT_STATUSES.has(status) ? status : 302) as ValidRedirectStatus;\n}\n\n/**\n * Astro's routing matches the 404 fallback for paths only contello knows how to\n * serve, so report what contello resolved: `overrideRequestRoute` corrects the\n * request log line, the request duration metric and the server span name\n * together, then record the contello-specific attributes on top.\n */\nfunction markRequestRoute(route: StoreRoute): void {\n overrideRequestRoute(\n route.type === 'entity' ? `/contello/entities/${route.model}/[id]` : `contello:route:${route.type}`,\n );\n\n updateActiveSpan({\n attributes: {\n 'contello.route.type': route.type,\n 'contello.route.path': route.path,\n ...(route.type === 'entity' && { 'contello.route.model': route.model }),\n },\n });\n}\n\nexport function createBoundRoutingMiddleware(\n contello: Contello<any>,\n routes: AnyRoutes,\n exclude: ExcludePattern[] | undefined,\n resolveRoutePath: RoutePathResolver | undefined,\n) {\n return defineMiddleware((ctx, next) => {\n if (shouldExclude(ctx, exclude ?? RECOMMENDED_EXCLUDES)) {\n return next();\n }\n\n if (!contello.isReady) {\n console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);\n\n return next();\n }\n\n const { url } = ctx;\n\n if (url.pathname.startsWith('/contello/entities/')) {\n return contello[runRequest]({ url, route: undefined, rewritten: false }, () => next());\n }\n\n const path = resolveRoutePath ? resolveRoutePath(ctx) : url.pathname;\n const lookup = routes.getByPath(path) as MaybePromise<StoreRoute | undefined>;\n\n return maybeThen(lookup, (route) => {\n if (!route) {\n return contello[runRequest]({ url, route: undefined, rewritten: false }, () => next());\n }\n\n markRequestRoute(route);\n\n switch (route.type) {\n case 'redirect': {\n return contello[runRequest](\n { url, route, rewritten: false },\n () => wrap(\n 'route:redirect',\n () => new Response(null, {\n status: toRedirectStatus(route.status),\n headers: {\n Location: route.location,\n ...customHeaders(route.customHeaders),\n },\n }),\n ),\n );\n }\n\n case 'text': {\n return contello[runRequest](\n { url, route, rewritten: false },\n () => wrap(\n 'route:text',\n () => new Response(route.content, {\n status: 200,\n headers: {\n 'Content-Type': route.mimeType,\n ...customHeaders(route.customHeaders),\n },\n }),\n ),\n );\n }\n\n case 'asset': {\n return contello[runRequest](\n { url, route, rewritten: false },\n () => wrap('route:asset', async () => {\n const result = await contello.client.download(route.fileId);\n const headers = new Headers({ 'content-type': route.mimeType || result.mimeType });\n\n headers.set('content-disposition', route.contentDisposition);\n\n if (result.size > 0) {\n headers.set('content-length', String(result.size));\n }\n\n for (const { name, value } of route.customHeaders) {\n headers.set(name, value);\n }\n\n return new Response(result.stream(), { headers });\n }),\n );\n }\n\n case 'sitemap': {\n return contello[runRequest](\n { url, route, rewritten: false },\n () => wrap('route:sitemap', async () => {\n const result = await contello.client.proxySitemap(\n route.sitemapId,\n {\n source: url.searchParams.get('source') ?? undefined,\n page: url.searchParams.get('page') ?? undefined,\n acceptEncoding: ctx.request.headers.get('accept-encoding') ?? undefined,\n ifNoneMatch: ctx.request.headers.get('if-none-match') ?? undefined,\n },\n ctx.request.signal,\n );\n\n const passthrough = result.status === 304 || (result.status >= 200 && result.status < 300);\n\n if (!passthrough) {\n // core's error format stays internal: same status, no body, none of the upstream headers\n await result.stream().cancel();\n\n return new Response(null, { status: result.status, headers: customHeaders(route.customHeaders) });\n }\n\n const headers = new Headers(result.headers);\n\n for (const { name, value } of route.customHeaders) {\n headers.set(name, value);\n }\n\n return new Response(result.status === 304 ? null : result.stream(), { status: result.status, headers });\n }),\n );\n }\n\n case 'entity': {\n return contello[runRequest](\n { url, route, rewritten: true },\n () => wrap(`route:entity:${route.model}`, async () => {\n const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);\n\n for (const { name, value } of route.customHeaders) {\n response.headers.set(name, value);\n }\n\n return response;\n }),\n );\n }\n }\n });\n });\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport { type RawTranslations, i18n } from '@astroscope/i18n';\nimport { getBootContext } from '@astroscope/node/boot';\nimport type { ContelloClient, Schema, SourceDef } from '@contello/client';\nimport { type MediaResolver, type MediaResolverOptions, createMediaResolver } from '@contello/media';\nimport {\n type Assets,\n type AssetsOptions,\n type AssetsSync,\n type AssetsSyncOptions,\n type BuiltInWrites,\n type Collection,\n type CollectionOptions,\n type CollectionSync,\n type CollectionSyncOptions,\n type CreateStoreOptions,\n type ExtractSourceResult,\n type ExtractSourceWrites,\n type I18nMessageRegistrationDefinition,\n type I18nMessages,\n type LazyAssets,\n type LazyAssetsOptions,\n type LazyCollection,\n type LazyCollectionOptions,\n type LazyRoutes,\n type LazyRoutesOptions,\n type Loadable,\n type ResolveSource,\n type Routes,\n type RoutesOptions,\n type RoutesSync,\n type RoutesSyncOptions,\n type Singleton,\n type SingletonOptions,\n type SingletonSync,\n type SingletonSyncOptions,\n type SourceKeysOf,\n type Store,\n type StoreRoute,\n type SyncCacheOptions,\n createStore,\n} from '@contello/store';\nimport type { ReadonlyDeep } from '@entwico/dash';\nimport { type ContelloAssetsMiddlewareOptions, createBoundAssetsMiddleware } from './assets-middleware';\nimport { type ContelloRoutingMiddlewareOptions, createBoundRoutingMiddleware } from './routing-middleware';\n\nconst DEFAULT_IMAGES_PREFIX = '/_contello/i/';\nconst DEFAULT_FILES_PREFIX = '/_contello/f/';\nconst DEFAULT_VIDEO_PREFIX = '/_contello/v/';\n\nexport type ContelloRequestContext = {\n url: URL;\n route: ReadonlyDeep<StoreRoute> | undefined;\n rewritten: boolean;\n};\n\nexport type ContelloI18nOptions = {\n collection: string;\n languages: string[];\n cache?: SyncCacheOptions | undefined;\n};\n\nexport type ContelloInitOptions = {\n load?: Loadable[] | undefined;\n i18n?:\n | {\n /** defaults to `true`, except in dev mode (detected via the @astroscope/node boot context) */\n register?: boolean | undefined;\n load?: boolean | undefined;\n }\n | undefined;\n};\n\nexport type ContelloMediaConfig = {\n readonly baseUrl: string;\n readonly imagesPath: string;\n readonly videosPath: string;\n readonly filesPath: string;\n};\n\nexport type ContelloOptions<TSchema extends Schema | undefined = undefined> = CreateStoreOptions<TSchema> & {\n i18n?: ContelloI18nOptions | undefined;\n media?: Partial<ContelloMediaConfig> | undefined;\n};\n\ntype HasFallback<O> = O extends { fallback: infer F } ? ([F] extends [undefined] ? false : true) : false;\n\nexport const runRequest = Symbol('@contello/astro/runRequest');\n\nfunction buildI18nRegistrations(): I18nMessageRegistrationDefinition[] {\n const manifest = i18n.getManifest();\n const defaultLanguage = i18n.getConfig().defaultLocale;\n\n return manifest.keys.map((extracted) => ({\n token: extracted.key,\n example: extracted.meta.fallback,\n description: extracted.meta.description ?? '',\n variables: Object.entries(extracted.meta.variables ?? {}).map(([name, def]) => ({\n name,\n description: def?.description ?? '',\n example: def?.fallback ?? '',\n })),\n initialTranslations: [{ language: defaultLanguage, message: extracted.meta.fallback }],\n }));\n}\n\nasync function applyTranslations(messages: I18nMessages): Promise<void> {\n const config = i18n.getConfig();\n const all = await messages.getAll();\n const byLocale = new Map<string, RawTranslations>();\n\n for (const locale of config.locales) {\n byLocale.set(locale, {});\n }\n\n for (const msg of all) {\n msg.translations.forEach((value, language) => {\n const raw = byLocale.get(language);\n\n if (raw) {\n raw[msg.token] = value;\n }\n });\n }\n\n for (const [locale, translations] of byLocale) {\n i18n.setTranslations(locale, translations);\n }\n}\n\ntype ModelsOf<TSchema> = TSchema extends { models: infer M } ? keyof M & string : string;\ntype CollectionArg<TSchema> = SourceKeysOf<TSchema, 'entity'> | SourceDef<ModelsOf<TSchema>, 'entity'>;\ntype SingletonArg<TSchema> = SourceKeysOf<TSchema, 'singleton'> | SourceDef<ModelsOf<TSchema>, 'singleton'>;\ntype CollectionRaw<TSchema, TArg> = ExtractSourceResult<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'entity'>>\n>;\n/** The write-input shape the source carries — keeps the collection's write half through the proxy. */\ntype CollectionWritesOf<TSchema, TArg> = ExtractSourceWrites<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'entity'>>\n>;\ntype RouteWrites<TSchema> = BuiltInWrites<TSchema, 'route'>;\ntype AssetWrites<TSchema> = BuiltInWrites<TSchema, 'asset'>;\ntype SingletonRaw<TSchema, TArg> = ExtractSourceResult<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'singleton'>>\n>;\n\nexport class Contello<TSchema extends Schema | undefined = undefined> {\n private readonly _store: Store<TSchema>;\n private readonly _options: ContelloOptions<TSchema>;\n private _i18nMessages: I18nMessages | undefined;\n private _i18nUnsubscribe: (() => void) | undefined;\n private _initialized = false;\n private readonly _als = new AsyncLocalStorage<ContelloRequestContext>();\n private _autoLazyRoutes?: LazyRoutes;\n\n readonly media: ContelloMediaConfig;\n\n // --- middleware factories (arrow fields so destructuring works) ---\n\n createRoutingMiddleware = (options?: ContelloRoutingMiddlewareOptions | undefined) => {\n const routes = options?.routes ?? (this._autoLazyRoutes ??= this.defineLazyRoutes());\n\n return createBoundRoutingMiddleware(this, routes, options?.exclude, options?.resolveRoutePath);\n };\n\n createAssetsMiddleware = (options?: ContelloAssetsMiddlewareOptions | undefined) => {\n return createBoundAssetsMiddleware(this, options);\n };\n\n constructor(options: ContelloOptions<TSchema>) {\n this._options = options;\n this._store = createStore<TSchema>(options);\n\n this.media = {\n baseUrl: options.media?.baseUrl ?? '',\n imagesPath: options.media?.imagesPath ?? DEFAULT_IMAGES_PREFIX,\n videosPath: options.media?.videosPath ?? DEFAULT_VIDEO_PREFIX,\n filesPath: options.media?.filesPath ?? DEFAULT_FILES_PREFIX,\n };\n }\n\n // --- lifecycle ---\n\n async init(options?: ContelloInitOptions | undefined): Promise<void> {\n try {\n await this._store.init();\n\n if (this._options.i18n) {\n const { collection, languages, cache } = this._options.i18n;\n const dev = getBootContext()?.dev ?? false;\n const { register = !dev, load = true } = options?.i18n ?? {};\n\n this._i18nMessages = this._store.defineI18nMessages({ collection, cache });\n\n await i18n.configure({ locales: languages });\n\n if (register) {\n const registrations = buildI18nRegistrations();\n\n if (registrations.length > 0) {\n await this._i18nMessages.register(registrations);\n }\n }\n\n if (load) {\n await applyTranslations(this._i18nMessages);\n\n const messages = this._i18nMessages;\n const controller = new AbortController();\n\n this._i18nUnsubscribe = () => controller.abort();\n\n // background loop: re-apply translations on every refresh until destroy()\n void (async () => {\n for await (const _ of messages.refresh$) {\n if (controller.signal.aborted) {\n return;\n }\n\n await applyTranslations(messages);\n }\n })();\n }\n }\n\n await Promise.all((options?.load ?? []).map((l) => l.load()));\n\n this._initialized = true;\n } catch (error) {\n try {\n await this.destroy();\n } catch {\n // ignore teardown errors; the original init error is rethrown below\n }\n\n throw error;\n }\n }\n\n async destroy(): Promise<void> {\n this._initialized = false;\n\n this._i18nUnsubscribe?.();\n this._i18nUnsubscribe = undefined;\n\n await this._store.destroy();\n\n this._i18nMessages = undefined;\n }\n\n ping(): Promise<void> {\n return this._store.ping();\n }\n\n get isReady(): boolean {\n return this._initialized;\n }\n\n get client(): ContelloClient<TSchema> {\n return this._store.client;\n }\n\n get i18nMessages(): I18nMessages {\n if (!this._i18nMessages) {\n throw new Error('@contello/astro: .i18nMessages accessed before init() with i18n config');\n }\n\n return this._i18nMessages;\n }\n\n // --- ALS request context ---\n\n get request(): ContelloRequestContext {\n const ctx = this._als.getStore();\n\n if (!ctx) {\n throw new Error('@contello/astro: .request accessed outside of request context');\n }\n\n return ctx;\n }\n\n // --- media resolvers (on-demand) ---\n\n defineMediaResolver<O extends Partial<MediaResolverOptions>>(options?: O): MediaResolver<HasFallback<O>> {\n return createMediaResolver({\n ...this.media,\n ...options,\n }) as MediaResolver<HasFallback<O>>;\n }\n\n // --- store delegation ---\n\n defineSingleton<TArg extends SingletonArg<TSchema>, TMapped = SingletonRaw<TSchema, TArg>>(\n sourceOrKey: TArg,\n options?: SingletonOptions<SingletonRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): Singleton<TMapped> {\n return this._store.defineSingleton(sourceOrKey as any, options as any) as Singleton<TMapped>;\n }\n\n defineSingletonSync<TArg extends SingletonArg<TSchema>, TMapped = SingletonRaw<TSchema, TArg>>(\n sourceOrKey: TArg,\n options?: SingletonSyncOptions<SingletonRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): SingletonSync<TMapped> {\n return this._store.defineSingletonSync(sourceOrKey as any, options as any) as SingletonSync<TMapped>;\n }\n\n defineCollection<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: CollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): Collection<TMapped, CollectionWritesOf<TSchema, TArg>> {\n return this._store.defineCollection(sourceOrKey as any, options as any) as Collection<\n TMapped,\n CollectionWritesOf<TSchema, TArg>\n >;\n }\n\n defineCollectionSync<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: CollectionSyncOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): CollectionSync<TMapped, CollectionWritesOf<TSchema, TArg>> {\n return this._store.defineCollectionSync(sourceOrKey as any, options as any) as CollectionSync<\n TMapped,\n CollectionWritesOf<TSchema, TArg>\n >;\n }\n\n defineLazyCollection<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: LazyCollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): LazyCollection<TMapped> {\n return this._store.defineLazyCollection(sourceOrKey as any, options as any) as LazyCollection<TMapped>;\n }\n\n defineRoutes(options?: RoutesOptions | undefined): Routes<RouteWrites<TSchema>> {\n return this._store.defineRoutes(options);\n }\n\n defineRoutesSync(options?: RoutesSyncOptions | undefined): RoutesSync<RouteWrites<TSchema>> {\n return this._store.defineRoutesSync(options);\n }\n\n defineLazyRoutes(options?: LazyRoutesOptions | undefined): LazyRoutes {\n return this._store.defineLazyRoutes(options);\n }\n\n defineAssets(options?: AssetsOptions | undefined): Assets<AssetWrites<TSchema>> {\n return this._store.defineAssets(options);\n }\n\n defineAssetsSync(options?: AssetsSyncOptions | undefined): AssetsSync<AssetWrites<TSchema>> {\n return this._store.defineAssetsSync(options);\n }\n\n defineLazyAssets(options?: LazyAssetsOptions | undefined): LazyAssets {\n return this._store.defineLazyAssets(options);\n }\n\n // --- ALS run ---\n\n [runRequest]<T>(ctx: ContelloRequestContext, fn: () => T): T {\n return this._als.run(ctx, fn);\n }\n}\n\nexport function createContello<TSchema extends Schema | undefined = undefined>(\n options: ContelloOptions<TSchema>,\n): Contello<TSchema> {\n return new Contello(options);\n}\n"],"mappings":";;;;;;;;;;AAKA,SAAgB,iBAAiB,SAA+C;CAC9E,OAAO;AACT;;;ACLA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OAAc;CAIxE;CAEA,qBAIE,aACA,SAC4D;EAC5D,OAAO,KAAK,OAAO,qBAAqB,aAAoB,OAAc;CAI5E;CAEA,qBAIE,aACA,SACyB;EACzB,OAAO,KAAK,OAAO,qBAAqB,aAAoB,OAAc;CAC5E;CAEA,aAAa,SAAmE;EAC9E,OAAO,KAAK,OAAO,aAAa,OAAO;CACzC;CAEA,iBAAiB,SAA2E;EAC1F,OAAO,KAAK,OAAO,iBAAiB,OAAO;CAC7C;CAEA,iBAAiB,SAAqD;EACpE,OAAO,KAAK,OAAO,iBAAiB,OAAO;CAC7C;CAEA,aAAa,SAAmE;EAC9E,OAAO,KAAK,OAAO,aAAa,OAAO;CACzC;CAEA,iBAAiB,SAA2E;EAC1F,OAAO,KAAK,OAAO,iBAAiB,OAAO;CAC7C;CAEA,iBAAiB,SAAqD;EACpE,OAAO,KAAK,OAAO,iBAAiB,OAAO;CAC7C;CAIA,CAAC,YAAe,KAA6B,IAAgB;EAC3D,OAAO,KAAK,KAAK,IAAI,KAAK,EAAE;CAC9B;AACF;AAEA,SAAgB,eACd,SACmB;CACnB,OAAO,IAAI,SAAS,OAAO;AAC7B"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/vite-plugin.ts","../src/integration.ts","../src/middleware.ts","../src/telemetry.ts","../src/assets-middleware.ts","../src/routing-middleware.ts","../src/contello.ts"],"sourcesContent":["import { type ExcludePattern, serializeExcludePatterns } from '@astroscope/node/excludes';\nimport type { Plugin } from 'vite';\n\nexport const INSTANCE_VIRTUAL_MODULE_ID = 'virtual:@contello/astro/instance';\nexport const CONFIG_VIRTUAL_MODULE_ID = 'virtual:@contello/astro/config';\n\nconst RESOLVED_CONFIG_VIRTUAL_MODULE_ID = `\\0${CONFIG_VIRTUAL_MODULE_ID}`;\n\nexport type ContelloVitePluginOptions = {\n /** absolute path of the module exporting the `contello` instance */\n entry: string;\n /** routing exclude patterns, null for the middleware default */\n exclude: ExcludePattern[] | null;\n};\n\n/**\n * Resolves the instance id straight to the project's module, so the injected\n * middlewares and the project's own imports share one `Contello` instance, and\n * serves the serializable integration options as a config module.\n */\nexport function contelloVitePlugin(options: ContelloVitePluginOptions): Plugin {\n return {\n name: '@contello/astro',\n\n resolveId(id) {\n if (id === INSTANCE_VIRTUAL_MODULE_ID) {\n return options.entry;\n }\n\n if (id === CONFIG_VIRTUAL_MODULE_ID) {\n return RESOLVED_CONFIG_VIRTUAL_MODULE_ID;\n }\n },\n\n load(id) {\n if (id === RESOLVED_CONFIG_VIRTUAL_MODULE_ID) {\n // exclude patterns may contain RegExp — serialized as code, not JSON\n return `export const exclude = ${options.exclude ? serializeExcludePatterns(options.exclude) : 'null'};`;\n }\n },\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ExcludePattern } from '@astroscope/node/excludes';\nimport type { AstroIntegration } from 'astro';\nimport { contelloVitePlugin } from './vite-plugin';\n\nconst DEFAULT_ENTRY = 'src/server/contello.ts';\n\nexport type ContelloIntegrationOptions = {\n /**\n * Module exporting the `contello` instance (`export const contello = createContello(...)`),\n * relative to the project root.\n * @default 'src/server/contello.ts'\n */\n entry?: string | undefined;\n /**\n * Where the assets middleware (`/_contello/i/`, `/_contello/f/`, `/_contello/v/`) is injected;\n * `false` leaves it to the project (`contello.createAssetsMiddleware()`).\n * @default 'pre'\n */\n assets?: 'pre' | false | undefined;\n /**\n * Where the routing middleware is injected; `false` leaves it to the project\n * (`contello.createRoutingMiddleware()`). Post middlewares run in `integrations` order, so list\n * `contello()` before integrations whose middleware depends on the resolved route, e.g. `@astroscope/wormhole`.\n * @default 'post'\n */\n routing?: 'post' | false | undefined;\n /**\n * Paths the routing middleware skips.\n * @default RECOMMENDED_EXCLUDES from `@astroscope/node/excludes`\n */\n exclude?: ExcludePattern[] | undefined;\n};\n\n/**\n * Astro integration for Contello.\n *\n * Injects the assets middleware ahead of the project's own middleware and the routing\n * middleware after it, both bound to the project's `contello` instance, which the\n * integration resolves from `src/server/contello.ts` (or `entry`). Runtime options\n * (`resolveRoutePath`, assets cache control, the routes instance) live on the instance,\n * only serializable ones belong here.\n */\nexport default function contelloIntegration(options: ContelloIntegrationOptions = {}): AstroIntegration {\n const { entry = DEFAULT_ENTRY, assets = 'pre', routing = 'post', exclude = null } = options;\n\n return {\n name: '@contello/astro',\n hooks: {\n 'astro:config:setup': ({ config, updateConfig, addMiddleware }) => {\n const entryPath = path.resolve(fileURLToPath(config.root), entry);\n\n if (!fs.existsSync(entryPath)) {\n throw new Error(\n `@contello/astro: instance module ${entry} not found — ` +\n 'export `contello = createContello(...)` from it or point the integration\\'s `entry` option at it',\n );\n }\n\n if (assets) {\n addMiddleware({ order: assets, entrypoint: '@contello/astro/assets-middleware' });\n }\n\n if (routing) {\n addMiddleware({ order: routing, entrypoint: '@contello/astro/routing-middleware' });\n }\n\n updateConfig({\n vite: {\n plugins: [contelloVitePlugin({ entry: entryPath, exclude })],\n },\n });\n },\n },\n };\n}\n","import type { MiddlewareHandler } from 'astro';\n\n// a local identity instead of `astro/middleware`: a runtime import of astro's middleware entry pulls every module that\n// imports this package into astro's runtime module graph — in dev, astro invalidates that graph on any file change,\n// which re-evaluates boot-loaded singletons and makes @astroscope/node restart the server on every component edit\nexport function defineMiddleware(handler: MiddlewareHandler): MiddlewareHandler {\n return handler;\n}\n","import { createOperationTelemetry } from '@contello/opentelemetry';\n\nexport const { wrap } = createOperationTelemetry('@contello/astro');\n","import { overrideRequestRoute } from '@astroscope/node/log';\nimport type { ContelloClient } from '@contello/client';\nimport type { Contello } from './contello';\nimport { defineMiddleware } from './middleware';\nimport { wrap } from './telemetry';\n\nexport type ContelloAssetsImagesOptions = {\n cacheControl?: string | undefined;\n};\n\nexport type ContelloAssetsFilesOptions = {\n cacheControl?: string | undefined;\n};\n\nexport type ContelloAssetsVideoOptions = Record<string, never>;\n\nexport type ContelloAssetsMiddlewareOptions = {\n images?: ContelloAssetsImagesOptions | undefined;\n files?: ContelloAssetsFilesOptions | undefined;\n video?: ContelloAssetsVideoOptions | undefined;\n};\n\nconst DEFAULT_IMAGES_CACHE_CONTROL = 'public, max-age=31536000';\n\n/**\n * `options` is read per request: the integration creates the middleware before `init()`\n * brings the project's assets options; `false` disables the middleware (`init({ assets: false })`).\n */\nexport function createBoundAssetsMiddleware(\n contello: Contello<any>,\n options: () => ContelloAssetsMiddlewareOptions | false | undefined,\n) {\n const imagesPrefix = contello.media.imagesPath;\n const filesPrefix = contello.media.filesPath;\n const videoPrefix = contello.media.videosPath;\n\n return defineMiddleware((ctx, next) => {\n const { pathname } = ctx.url;\n const isImage = pathname.startsWith(imagesPrefix);\n const isFile = !isImage && pathname.startsWith(filesPrefix);\n const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);\n\n if (!isImage && !isFile && !isVideo) {\n return next();\n }\n\n const current = options();\n\n if (current === false) {\n return next();\n }\n\n if (!contello.isReady) {\n console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);\n\n return next();\n }\n\n if (isImage) {\n return handleFile(\n contello.client,\n next,\n pathname.slice(imagesPrefix.length),\n current?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL,\n `${imagesPrefix}[file]`,\n );\n }\n\n if (isFile) {\n return handleFile(\n contello.client,\n next,\n pathname.slice(filesPrefix.length),\n current?.files?.cacheControl,\n `${filesPrefix}[file]`,\n );\n }\n\n return handleVideo(\n contello.client,\n next,\n pathname.slice(videoPrefix.length),\n ctx.request.signal,\n `${videoPrefix}[...path]`,\n );\n });\n}\n\nfunction handleFile(\n client: ContelloClient<any>,\n next: () => Response | Promise<Response>,\n rest: string,\n cacheControl: string | undefined,\n routeLabel: string,\n) {\n const dot = rest.indexOf('.');\n const fileId = dot === -1 ? rest : rest.slice(0, dot);\n\n if (!fileId) {\n return next();\n }\n\n overrideRequestRoute(routeLabel);\n\n return (async () => {\n try {\n const result = await wrap('assets:file', () => client.download(fileId));\n const headers = new Headers({ 'content-type': result.mimeType });\n\n if (cacheControl) {\n headers.set('cache-control', cacheControl);\n }\n\n if (result.size > 0) {\n headers.set('content-length', String(result.size));\n }\n\n return new Response(result.stream(), { headers });\n } catch {\n return new Response(null, { status: 404 });\n }\n })();\n}\n\nfunction handleVideo(\n client: ContelloClient<any>,\n next: () => Response | Promise<Response>,\n path: string,\n signal: AbortSignal,\n routeLabel: string,\n) {\n if (!path) {\n return next();\n }\n\n overrideRequestRoute(routeLabel);\n\n return (async () => {\n try {\n const result = await wrap('assets:hls', () => client.proxyHls(path, signal));\n\n return new Response(result.stream(), { status: result.status, headers: result.headers });\n } catch {\n return new Response('Upstream is down', { status: 502, headers: { 'content-type': 'text/plain' } });\n }\n })();\n}\n","import { type ExcludePattern, RECOMMENDED_EXCLUDES, shouldExclude } from '@astroscope/node/excludes';\nimport { overrideRequestRoute } from '@astroscope/node/log';\nimport { updateActiveSpan } from '@contello/opentelemetry';\nimport type { LazyRoutes, Routes, RoutesSync, StoreRoute, StoreRouteCustomHeader } from '@contello/store';\nimport { type MaybePromise, maybeThen } from '@entwico/dash';\nimport type { APIContext, ValidRedirectStatus } from 'astro';\nimport { type Contello, runRequest } from './contello';\nimport { defineMiddleware } from './middleware';\nimport { wrap } from './telemetry';\n\nexport type AnyRoutes = Routes | RoutesSync | LazyRoutes;\n\n/**\n * Derives the path used to look up a Contello route from the request context.\n *\n * @default `(ctx) => ctx.url.pathname`\n *\n * ```ts\n * resolveRoutePath: (ctx) => `/${ctx.url.hostname}${ctx.url.pathname}`\n * ```\n */\nexport type RoutePathResolver = (ctx: APIContext) => string;\n\nexport type ContelloRoutingMiddlewareOptions = {\n /**\n * Routes instance backing the middleware.\n *\n * Defaults to a `LazyRoutes` instance managed by contello (fetched on demand, no init-time load).\n * For eager routing, create a `RoutesSync` via `contello.defineRoutesSync()`, add it to\n * `contello.init({ load: [routes] })`, and pass that same instance here.\n */\n routes?: AnyRoutes | undefined;\n exclude?: ExcludePattern[] | undefined;\n resolveRoutePath?: RoutePathResolver | undefined;\n};\n\nfunction customHeaders(headers: readonly StoreRouteCustomHeader[]): Record<string, string> {\n const result: Record<string, string> = {};\n\n for (const h of headers) {\n result[h.name] = h.value;\n }\n\n return result;\n}\n\nconst VALID_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);\n\nfunction toRedirectStatus(status: number): ValidRedirectStatus {\n return (VALID_REDIRECT_STATUSES.has(status) ? status : 302) as ValidRedirectStatus;\n}\n\n/**\n * Astro's routing matches the 404 fallback for paths only contello knows how to\n * serve, so report what contello resolved: `overrideRequestRoute` corrects the\n * request log line, the request duration metric and the server span name\n * together, then record the contello-specific attributes on top.\n */\nfunction markRequestRoute(route: StoreRoute): void {\n overrideRequestRoute(\n route.type === 'entity' ? `/contello/entities/${route.model}/[id]` : `contello:route:${route.type}`,\n );\n\n updateActiveSpan({\n attributes: {\n 'contello.route.type': route.type,\n 'contello.route.path': route.path,\n ...(route.type === 'entity' && { 'contello.route.model': route.model }),\n },\n });\n}\n\nexport function createBoundRoutingMiddleware(\n contello: Contello<any>,\n routes: () => AnyRoutes | undefined,\n exclude: ExcludePattern[] | undefined,\n resolveRoutePath: RoutePathResolver | undefined,\n) {\n return defineMiddleware((ctx, next) => {\n if (shouldExclude(ctx, exclude ?? RECOMMENDED_EXCLUDES)) {\n return next();\n }\n\n if (!contello.isReady) {\n console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);\n\n return next();\n }\n\n // undefined: the project disabled routing (`init({ routes: false })`)\n const current = routes();\n\n if (!current) {\n return next();\n }\n\n const { url } = ctx;\n\n if (url.pathname.startsWith('/contello/entities/')) {\n return contello[runRequest]({ url, route: undefined, rewritten: false }, () => next());\n }\n\n const path = resolveRoutePath ? resolveRoutePath(ctx) : url.pathname;\n const lookup = current.getByPath(path) as MaybePromise<StoreRoute | undefined>;\n\n return maybeThen(lookup, (route) => {\n if (!route) {\n return contello[runRequest]({ url, route: undefined, rewritten: false }, () => next());\n }\n\n markRequestRoute(route);\n\n switch (route.type) {\n case 'redirect': {\n return contello[runRequest](\n { url, route, rewritten: false },\n () => wrap(\n 'route:redirect',\n () => new Response(null, {\n status: toRedirectStatus(route.status),\n headers: {\n Location: route.location,\n ...customHeaders(route.customHeaders),\n },\n }),\n ),\n );\n }\n\n case 'text': {\n return contello[runRequest](\n { url, route, rewritten: false },\n () => wrap(\n 'route:text',\n () => new Response(route.content, {\n status: 200,\n headers: {\n 'Content-Type': route.mimeType,\n ...customHeaders(route.customHeaders),\n },\n }),\n ),\n );\n }\n\n case 'asset': {\n return contello[runRequest](\n { url, route, rewritten: false },\n () => wrap('route:asset', async () => {\n const result = await contello.client.download(route.fileId);\n const headers = new Headers({ 'content-type': route.mimeType || result.mimeType });\n\n headers.set('content-disposition', route.contentDisposition);\n\n if (result.size > 0) {\n headers.set('content-length', String(result.size));\n }\n\n for (const { name, value } of route.customHeaders) {\n headers.set(name, value);\n }\n\n return new Response(result.stream(), { headers });\n }),\n );\n }\n\n case 'sitemap': {\n return contello[runRequest](\n { url, route, rewritten: false },\n () => wrap('route:sitemap', async () => {\n const result = await contello.client.proxySitemap(\n route.sitemapId,\n {\n source: url.searchParams.get('source') ?? undefined,\n page: url.searchParams.get('page') ?? undefined,\n acceptEncoding: ctx.request.headers.get('accept-encoding') ?? undefined,\n ifNoneMatch: ctx.request.headers.get('if-none-match') ?? undefined,\n },\n ctx.request.signal,\n );\n\n const passthrough = result.status === 304 || (result.status >= 200 && result.status < 300);\n\n if (!passthrough) {\n // core's error format stays internal: same status, no body, none of the upstream headers\n await result.stream().cancel();\n\n return new Response(null, { status: result.status, headers: customHeaders(route.customHeaders) });\n }\n\n const headers = new Headers(result.headers);\n\n for (const { name, value } of route.customHeaders) {\n headers.set(name, value);\n }\n\n return new Response(result.status === 304 ? null : result.stream(), { status: result.status, headers });\n }),\n );\n }\n\n case 'entity': {\n return contello[runRequest](\n { url, route, rewritten: true },\n () => wrap(`route:entity:${route.model}`, async () => {\n const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);\n\n for (const { name, value } of route.customHeaders) {\n response.headers.set(name, value);\n }\n\n return response;\n }),\n );\n }\n }\n });\n });\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport { type I18nConfig, type RawTranslations, i18n } from '@astroscope/i18n';\nimport { getBootContext } from '@astroscope/node/boot';\nimport { registerHealthCheck } from '@astroscope/node/health';\nimport type { ContelloClient, Schema, SourceDef } from '@contello/client';\nimport { type MediaResolver, type MediaResolverOptions, createMediaResolver } from '@contello/media';\nimport {\n type Assets,\n type AssetsOptions,\n type AssetsSync,\n type AssetsSyncOptions,\n type BuiltInWrites,\n type Collection,\n type CollectionOptions,\n type CollectionSync,\n type CollectionSyncOptions,\n type CreateStoreOptions,\n type ExtractSourceResult,\n type ExtractSourceWrites,\n type I18nMessageRegistrationDefinition,\n type I18nMessages,\n type LazyAssets,\n type LazyAssetsOptions,\n type LazyCollection,\n type LazyCollectionOptions,\n type LazyRoutes,\n type LazyRoutesOptions,\n type Loadable,\n type ResolveSource,\n type Routes,\n type RoutesOptions,\n type RoutesSync,\n type RoutesSyncOptions,\n type Singleton,\n type SingletonOptions,\n type SingletonSync,\n type SingletonSyncOptions,\n type SourceKeysOf,\n type Store,\n type StoreRoute,\n type SyncCacheOptions,\n createStore,\n} from '@contello/store';\nimport type { ReadonlyDeep } from '@entwico/dash';\nimport { type ContelloAssetsMiddlewareOptions, createBoundAssetsMiddleware } from './assets-middleware';\nimport {\n type AnyRoutes,\n type ContelloRoutingMiddlewareOptions,\n type RoutePathResolver,\n createBoundRoutingMiddleware,\n} from './routing-middleware';\n\nconst DEFAULT_IMAGES_PREFIX = '/_contello/i/';\nconst DEFAULT_FILES_PREFIX = '/_contello/f/';\nconst DEFAULT_VIDEO_PREFIX = '/_contello/v/';\n\nexport type ContelloRequestContext = {\n url: URL;\n route: ReadonlyDeep<StoreRoute> | undefined;\n rewritten: boolean;\n};\n\n/** The Contello i18n message collection bridged to `@astroscope/i18n`; `init()` takes the runtime side. */\nexport type ContelloI18nOptions = {\n collection: string;\n cache?: SyncCacheOptions | undefined;\n};\n\n/**\n * The `@astroscope/i18n` config `init()` passes to `i18n.configure()` before it pushes the\n * collection's translations, plus what to do with the extracted keys.\n */\nexport type ContelloInitI18nOptions = I18nConfig & {\n /**\n * Register the extracted keys in the collection; defaults to `true`, except in dev mode (detected via the\n * @astroscope/node boot context).\n */\n register?: boolean | undefined;\n /** push the collection's translations and follow its refreshes; defaults to `true` */\n load?: boolean | undefined;\n};\n\nexport type ContelloRoutingOptions = {\n resolveRoutePath?: RoutePathResolver | undefined;\n};\n\n/** The readiness check `init()` registers with `@astroscope/node/health`; `false` registers none. */\nexport type ContelloHealthOptions = {\n /** @default 'contello' */\n name?: string | undefined;\n optional?: boolean | undefined;\n timeout?: number | undefined;\n};\n\nexport type ContelloInitOptions = {\n load?: Loadable[] | undefined;\n /**\n * Routes backing the routing middleware: `'sync'` creates and loads a `RoutesSync` (eager, synchronous\n * lookups), `'lazy'` creates a `LazyRoutes` (fetched on demand), or an instance the project defined\n * itself, loaded by `init()` when it is loadable. Reachable as `contello.routes` after `init()`.\n * `false` for a project without Contello routes: the routing middleware passes through.\n */\n routes: 'sync' | 'lazy' | AnyRoutes | false;\n /** required when `createContello` got an `i18n` collection */\n i18n?: ContelloInitI18nOptions | undefined;\n /** defaults for the routing middleware, used by the integration-injected one */\n routing?: ContelloRoutingOptions | undefined;\n /** defaults for the assets middleware, used by the integration-injected one; `false` makes it pass through */\n assets?: ContelloAssetsMiddlewareOptions | false | undefined;\n health?: ContelloHealthOptions | false | undefined;\n};\n\nexport type ContelloMediaConfig = {\n readonly baseUrl: string;\n readonly imagesPath: string;\n readonly videosPath: string;\n readonly filesPath: string;\n};\n\nexport type ContelloOptions<TSchema extends Schema | undefined = undefined> = CreateStoreOptions<TSchema> & {\n i18n?: ContelloI18nOptions | undefined;\n media?: Partial<ContelloMediaConfig> | undefined;\n};\n\nfunction isLoadable(value: object): value is Loadable {\n return typeof (value as Partial<Loadable>).load === 'function';\n}\n\ntype HasFallback<O> = O extends { fallback: infer F } ? ([F] extends [undefined] ? false : true) : false;\n\nexport const runRequest = Symbol('@contello/astro/runRequest');\n\nfunction createI18nRegistrations(): I18nMessageRegistrationDefinition[] {\n const manifest = i18n.getManifest();\n const defaultLanguage = i18n.getConfig().defaultLocale;\n\n return manifest.keys.map((extracted) => ({\n token: extracted.key,\n example: extracted.meta.fallback,\n description: extracted.meta.description ?? '',\n variables: Object.entries(extracted.meta.variables ?? {}).map(([name, def]) => ({\n name,\n description: def?.description ?? '',\n example: def?.fallback ?? '',\n })),\n initialTranslations: [{ language: defaultLanguage, message: extracted.meta.fallback }],\n }));\n}\n\nasync function applyTranslations(messages: I18nMessages): Promise<void> {\n const config = i18n.getConfig();\n const all = await messages.getAll();\n const byLocale = new Map<string, RawTranslations>();\n\n for (const locale of config.locales) {\n byLocale.set(locale, {});\n }\n\n for (const msg of all) {\n msg.translations.forEach((value, language) => {\n const raw = byLocale.get(language);\n\n if (raw) {\n raw[msg.token] = value;\n }\n });\n }\n\n for (const [locale, translations] of byLocale) {\n i18n.setTranslations(locale, translations);\n }\n}\n\ntype ModelsOf<TSchema> = TSchema extends { models: infer M } ? keyof M & string : string;\ntype CollectionArg<TSchema> = SourceKeysOf<TSchema, 'entity'> | SourceDef<ModelsOf<TSchema>, 'entity'>;\ntype SingletonArg<TSchema> = SourceKeysOf<TSchema, 'singleton'> | SourceDef<ModelsOf<TSchema>, 'singleton'>;\ntype CollectionRaw<TSchema, TArg> = ExtractSourceResult<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'entity'>>\n>;\n/** The write-input shape the source carries — keeps the collection's write half through the proxy. */\ntype CollectionWritesOf<TSchema, TArg> = ExtractSourceWrites<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'entity'>>\n>;\ntype RouteWrites<TSchema> = BuiltInWrites<TSchema, 'route'>;\ntype AssetWrites<TSchema> = BuiltInWrites<TSchema, 'asset'>;\ntype SingletonRaw<TSchema, TArg> = ExtractSourceResult<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'singleton'>>\n>;\n\nexport class Contello<TSchema extends Schema | undefined = undefined> {\n private readonly _store: Store<TSchema>;\n private readonly _options: ContelloOptions<TSchema>;\n private _i18nMessages: I18nMessages | undefined;\n private _i18nUnsubscribe: (() => void) | undefined;\n private _initialized = false;\n private readonly _als = new AsyncLocalStorage<ContelloRequestContext>();\n private _routes: AnyRoutes | undefined;\n private _initOptions: ContelloInitOptions | undefined;\n private _unregisterHealthCheck: (() => void) | undefined;\n\n readonly media: ContelloMediaConfig;\n\n // --- middleware factories (arrow fields so destructuring works) ---\n\n createRoutingMiddleware = (options?: ContelloRoutingMiddlewareOptions | undefined) => {\n // resolved per request: the integration creates the middleware before init() brings the routes and options\n const routes = () => options?.routes ?? (this._initOptions?.routes === false ? undefined : this.routes);\n const resolveRoutePath: RoutePathResolver = (ctx) => {\n const resolver = options?.resolveRoutePath ?? this._initOptions?.routing?.resolveRoutePath;\n\n return resolver ? resolver(ctx) : ctx.url.pathname;\n };\n\n return createBoundRoutingMiddleware(this, routes, options?.exclude, resolveRoutePath);\n };\n\n createAssetsMiddleware = (options?: ContelloAssetsMiddlewareOptions | undefined) => {\n return createBoundAssetsMiddleware(this, () => options ?? this._initOptions?.assets);\n };\n\n constructor(options: ContelloOptions<TSchema>) {\n this._options = options;\n this._store = createStore<TSchema>(options);\n\n this.media = {\n baseUrl: options.media?.baseUrl ?? '',\n imagesPath: options.media?.imagesPath ?? DEFAULT_IMAGES_PREFIX,\n videosPath: options.media?.videosPath ?? DEFAULT_VIDEO_PREFIX,\n filesPath: options.media?.filesPath ?? DEFAULT_FILES_PREFIX,\n };\n }\n\n // --- lifecycle ---\n\n private createRoutes(routes: ContelloInitOptions['routes']): AnyRoutes | undefined {\n switch (routes) {\n case false: {\n return undefined;\n }\n\n case 'sync': {\n return this.defineRoutesSync();\n }\n\n case 'lazy': {\n return this.defineLazyRoutes();\n }\n\n default: {\n return routes;\n }\n }\n }\n\n private registerHealthCheck(health: ContelloHealthOptions | false | undefined): void {\n if (health === false) {\n return;\n }\n\n this._unregisterHealthCheck?.();\n this._unregisterHealthCheck = registerHealthCheck({\n name: health?.name ?? 'contello',\n check: () => this.ping(),\n optional: health?.optional,\n timeout: health?.timeout,\n });\n }\n\n async init(options: ContelloInitOptions): Promise<void> {\n try {\n this._initOptions = options;\n\n this.registerHealthCheck(options.health);\n\n await this._store.init();\n\n this._routes = this.createRoutes(options.routes);\n\n if (this._options.i18n) {\n if (!options.i18n) {\n throw new Error('@contello/astro: init() needs the i18n option (locales, locale resolver) for the configured i18n collection');\n }\n\n const { collection, cache } = this._options.i18n;\n const dev = getBootContext()?.dev ?? false;\n const { register = !dev, load = true, ...i18nConfig } = options.i18n;\n\n this._i18nMessages = this._store.defineI18nMessages({ collection, cache });\n\n await i18n.configure(i18nConfig);\n\n if (register) {\n const registrations = createI18nRegistrations();\n\n if (registrations.length > 0) {\n await this._i18nMessages.register(registrations);\n }\n }\n\n if (load) {\n await applyTranslations(this._i18nMessages);\n\n const messages = this._i18nMessages;\n const controller = new AbortController();\n\n this._i18nUnsubscribe = () => controller.abort();\n\n // background loop: re-apply translations on every refresh until destroy()\n void (async () => {\n for await (const _ of messages.refresh$) {\n if (controller.signal.aborted) {\n return;\n }\n\n await applyTranslations(messages);\n }\n })();\n }\n }\n\n const routes = this._routes;\n const loadables = [...(options.load ?? []), ...(routes && isLoadable(routes) ? [routes] : [])];\n\n await Promise.all(loadables.map((l) => l.load()));\n\n this._initialized = true;\n } catch (error) {\n try {\n await this.destroy();\n } catch {\n // ignore teardown errors; the original init error is rethrown below\n }\n\n throw error;\n }\n }\n\n async destroy(): Promise<void> {\n this._initialized = false;\n\n this._i18nUnsubscribe?.();\n this._i18nUnsubscribe = undefined;\n this._unregisterHealthCheck?.();\n this._unregisterHealthCheck = undefined;\n\n await this._store.destroy();\n\n this._i18nMessages = undefined;\n this._routes = undefined;\n this._initOptions = undefined;\n }\n\n ping(): Promise<void> {\n return this._store.ping();\n }\n\n get isReady(): boolean {\n return this._initialized;\n }\n\n get client(): ContelloClient<TSchema> {\n return this._store.client;\n }\n\n /** the routes backing the routing middleware, created by `init()` from its `routes` option */\n get routes(): AnyRoutes {\n if (!this._routes) {\n throw new Error('@contello/astro: .routes accessed before init() or with routes disabled');\n }\n\n return this._routes;\n }\n\n get i18nMessages(): I18nMessages {\n if (!this._i18nMessages) {\n throw new Error('@contello/astro: .i18nMessages accessed before init() with i18n config');\n }\n\n return this._i18nMessages;\n }\n\n // --- ALS request context ---\n\n get request(): ContelloRequestContext {\n const ctx = this._als.getStore();\n\n if (!ctx) {\n throw new Error('@contello/astro: .request accessed outside of request context');\n }\n\n return ctx;\n }\n\n // --- media resolvers (on-demand) ---\n\n defineMediaResolver<O extends Partial<MediaResolverOptions>>(options?: O): MediaResolver<HasFallback<O>> {\n return createMediaResolver({\n ...this.media,\n ...options,\n }) as MediaResolver<HasFallback<O>>;\n }\n\n // --- store delegation ---\n\n defineSingleton<TArg extends SingletonArg<TSchema>, TMapped = SingletonRaw<TSchema, TArg>>(\n sourceOrKey: TArg,\n options?: SingletonOptions<SingletonRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): Singleton<TMapped> {\n return this._store.defineSingleton(sourceOrKey as any, options as any) as Singleton<TMapped>;\n }\n\n defineSingletonSync<TArg extends SingletonArg<TSchema>, TMapped = SingletonRaw<TSchema, TArg>>(\n sourceOrKey: TArg,\n options?: SingletonSyncOptions<SingletonRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): SingletonSync<TMapped> {\n return this._store.defineSingletonSync(sourceOrKey as any, options as any) as SingletonSync<TMapped>;\n }\n\n defineCollection<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: CollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): Collection<TMapped, CollectionWritesOf<TSchema, TArg>> {\n return this._store.defineCollection(sourceOrKey as any, options as any) as Collection<\n TMapped,\n CollectionWritesOf<TSchema, TArg>\n >;\n }\n\n defineCollectionSync<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: CollectionSyncOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): CollectionSync<TMapped, CollectionWritesOf<TSchema, TArg>> {\n return this._store.defineCollectionSync(sourceOrKey as any, options as any) as CollectionSync<\n TMapped,\n CollectionWritesOf<TSchema, TArg>\n >;\n }\n\n defineLazyCollection<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: LazyCollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): LazyCollection<TMapped> {\n return this._store.defineLazyCollection(sourceOrKey as any, options as any) as LazyCollection<TMapped>;\n }\n\n defineRoutes(options?: RoutesOptions | undefined): Routes<RouteWrites<TSchema>> {\n return this._store.defineRoutes(options);\n }\n\n defineRoutesSync(options?: RoutesSyncOptions | undefined): RoutesSync<RouteWrites<TSchema>> {\n return this._store.defineRoutesSync(options);\n }\n\n defineLazyRoutes(options?: LazyRoutesOptions | undefined): LazyRoutes {\n return this._store.defineLazyRoutes(options);\n }\n\n defineAssets(options?: AssetsOptions | undefined): Assets<AssetWrites<TSchema>> {\n return this._store.defineAssets(options);\n }\n\n defineAssetsSync(options?: AssetsSyncOptions | undefined): AssetsSync<AssetWrites<TSchema>> {\n return this._store.defineAssetsSync(options);\n }\n\n defineLazyAssets(options?: LazyAssetsOptions | undefined): LazyAssets {\n return this._store.defineLazyAssets(options);\n }\n\n // --- ALS run ---\n\n [runRequest]<T>(ctx: ContelloRequestContext, fn: () => T): T {\n return this._als.run(ctx, fn);\n }\n}\n\nexport function createContello<TSchema extends Schema | undefined = undefined>(\n options: ContelloOptions<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,SAAqD;EACpE,OAAO,KAAK,OAAO,iBAAiB,OAAO;CAC7C;CAEA,aAAa,SAAmE;EAC9E,OAAO,KAAK,OAAO,aAAa,OAAO;CACzC;CAEA,iBAAiB,SAA2E;EAC1F,OAAO,KAAK,OAAO,iBAAiB,OAAO;CAC7C;CAEA,iBAAiB,SAAqD;EACpE,OAAO,KAAK,OAAO,iBAAiB,OAAO;CAC7C;CAIA,CAAC,YAAe,KAA6B,IAAgB;EAC3D,OAAO,KAAK,KAAK,IAAI,KAAK,EAAE;CAC9B;AACF;AAEA,SAAgB,eACd,SACmB;CACnB,OAAO,IAAI,SAAS,OAAO;AAC7B"}
@@ -0,0 +1,2 @@
1
+ export declare const onRequest: any;
2
+ //# sourceMappingURL=routing-middleware-entrypoint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routing-middleware-entrypoint.d.ts","names":[],"sources":["../src/routing-middleware-entrypoint.ts"],"mappings":"A,qBAGa"}
@@ -0,0 +1,7 @@
1
+ import { contello } from "virtual:@contello/astro/instance";
2
+ import { exclude } from "virtual:@contello/astro/config";
3
+ // src/routing-middleware-entrypoint.ts
4
+ const onRequest = contello.createRoutingMiddleware({ exclude: exclude ?? void 0 });
5
+ export { onRequest };
6
+
7
+ //# sourceMappingURL=routing-middleware-entrypoint.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routing-middleware-entrypoint.js","names":[],"sources":["../src/routing-middleware-entrypoint.ts"],"sourcesContent":["import { exclude } from 'virtual:@contello/astro/config';\nimport { contello } from 'virtual:@contello/astro/instance';\n\nexport const onRequest = contello.createRoutingMiddleware({ exclude: exclude ?? undefined });\n"],"mappings":";;;AAGA,MAAa,YAAY,SAAS,wBAAwB,EAAE,SAAS,WAAW,KAAA,EAAU,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,13 @@
1
1
  {
2
2
  "name": "@contello/astro",
3
- "version": "4.4.1",
4
- "description": "Astro integration for Contello CMS — route middleware and i18n bridge",
3
+ "version": "6.0.0",
4
+ "description": "Astro integration for Contello CMS — assets and routing middlewares, i18n bridge",
5
+ "keywords": [
6
+ "astro",
7
+ "astro-integration",
8
+ "contello",
9
+ "cms"
10
+ ],
5
11
  "type": "module",
6
12
  "license": "MIT",
7
13
  "author": "admin@entwico.com",
@@ -15,11 +21,11 @@
15
21
  "@entwico/dash": "^1.3.0"
16
22
  },
17
23
  "peerDependencies": {
18
- "@astroscope/i18n": ">=1.0.0",
19
- "@astroscope/node": ">=1.3.0",
20
- "@contello/client": "^3.2.1",
24
+ "@astroscope/i18n": "^4.0.0",
25
+ "@astroscope/node": "^5.0.0",
26
+ "@contello/client": "^3.4.1",
21
27
  "@contello/media": "^2.2.3",
22
- "@contello/store": "^4.4.1",
28
+ "@contello/store": "^4.5.0",
23
29
  "astro": "^6.0.0 || ^7.0.0"
24
30
  },
25
31
  "peerDependenciesMeta": {
@@ -28,12 +34,13 @@
28
34
  }
29
35
  },
30
36
  "devDependencies": {
31
- "@astroscope/i18n": "^2.1.2",
32
- "@astroscope/node": "^4.0.0",
33
- "@contello/client": "^3.2.1",
37
+ "@astroscope/i18n": "^4.0.0",
38
+ "@astroscope/node": "^5.0.0",
39
+ "@contello/client": "^3.4.1",
34
40
  "@contello/media": "^2.2.3",
35
- "@contello/store": "^4.4.1",
36
- "astro": "^7.3.8"
41
+ "@contello/store": "^4.5.0",
42
+ "astro": "^7.4.5",
43
+ "vite": "^8.3.5"
37
44
  },
38
45
  "files": [
39
46
  "dist"
@@ -44,6 +51,12 @@
44
51
  ".": {
45
52
  "import": "./dist/index.js",
46
53
  "require": "./dist/index.cjs"
54
+ },
55
+ "./assets-middleware": {
56
+ "import": "./dist/assets-middleware-entrypoint.js"
57
+ },
58
+ "./routing-middleware": {
59
+ "import": "./dist/routing-middleware-entrypoint.js"
47
60
  }
48
61
  },
49
62
  "publishConfig": {