@contello/astro 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -31,9 +31,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  Contello: () => Contello,
34
- createAssetsMiddleware: () => createAssetsMiddleware,
35
- createContello: () => createContello,
36
- createRoutingMiddleware: () => createRoutingMiddleware
34
+ createContello: () => createContello
37
35
  });
38
36
  module.exports = __toCommonJS(index_exports);
39
37
 
@@ -41,7 +39,203 @@ module.exports = __toCommonJS(index_exports);
41
39
  var import_node_async_hooks = require("async_hooks");
42
40
  var import_i18n = require("@astroscope/i18n");
43
41
  var import_media = require("@contello/media");
42
+ var import_store2 = require("@contello/store");
43
+
44
+ // src/assets-middleware.ts
45
+ var import_middleware = require("astro/middleware");
46
+
47
+ // src/diagnostics.ts
48
+ var import_node_diagnostics_channel = __toESM(require("diagnostics_channel"), 1);
49
+ var channels = {
50
+ start: "@contello/astro:start",
51
+ end: "@contello/astro:end",
52
+ error: "@contello/astro:error"
53
+ };
54
+ var onStart = import_node_diagnostics_channel.default.channel(channels.start);
55
+ var onEnd = import_node_diagnostics_channel.default.channel(channels.end);
56
+ var onError = import_node_diagnostics_channel.default.channel(channels.error);
57
+ function hasSubscribers() {
58
+ return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
59
+ }
60
+ function wrap(name, fn) {
61
+ if (!hasSubscribers()) {
62
+ return fn();
63
+ }
64
+ const start = performance.now();
65
+ onStart.publish({ name });
66
+ let result;
67
+ try {
68
+ result = fn();
69
+ } catch (error) {
70
+ onError.publish({ name, error, durationMs: performance.now() - start });
71
+ throw error;
72
+ }
73
+ if (result instanceof Promise) {
74
+ return result.then(
75
+ (r) => {
76
+ onEnd.publish({ name, durationMs: performance.now() - start });
77
+ return r;
78
+ },
79
+ (error) => {
80
+ onError.publish({ name, error, durationMs: performance.now() - start });
81
+ throw error;
82
+ }
83
+ );
84
+ }
85
+ onEnd.publish({ name, durationMs: performance.now() - start });
86
+ return result;
87
+ }
88
+
89
+ // src/assets-middleware.ts
90
+ var DEFAULT_IMAGES_CACHE_CONTROL = "public, max-age=31536000";
91
+ function createBoundAssetsMiddleware(contello, options) {
92
+ const imagesPrefix = contello.media.imagesPath;
93
+ const imagesCacheControl = options?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL;
94
+ const filesPrefix = contello.media.filesPath;
95
+ const filesCacheControl = options?.files?.cacheControl;
96
+ const videoPrefix = contello.media.videosPath;
97
+ return (0, import_middleware.defineMiddleware)((ctx, next) => {
98
+ const { pathname } = ctx.url;
99
+ const isImage = pathname.startsWith(imagesPrefix);
100
+ const isFile = !isImage && pathname.startsWith(filesPrefix);
101
+ const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);
102
+ if (!isImage && !isFile && !isVideo) {
103
+ return next();
104
+ }
105
+ if (!contello.isReady) {
106
+ console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);
107
+ return next();
108
+ }
109
+ if (isImage) {
110
+ return handleFile(contello.client, next, pathname.slice(imagesPrefix.length), imagesCacheControl);
111
+ }
112
+ if (isFile) {
113
+ return handleFile(contello.client, next, pathname.slice(filesPrefix.length), filesCacheControl);
114
+ }
115
+ return handleVideo(contello.client, next, pathname.slice(videoPrefix.length), ctx.request.signal);
116
+ });
117
+ }
118
+ function handleFile(client, next, rest, cacheControl) {
119
+ const dot = rest.indexOf(".");
120
+ const fileId = dot === -1 ? rest : rest.slice(0, dot);
121
+ if (!fileId) {
122
+ return next();
123
+ }
124
+ return wrap("assets:file", () => client.download(fileId)).then(
125
+ (result) => {
126
+ const headers = new Headers({ "content-type": result.mimeType });
127
+ if (cacheControl) {
128
+ headers.set("cache-control", cacheControl);
129
+ }
130
+ if (result.size) {
131
+ headers.set("content-length", String(result.size));
132
+ }
133
+ return new Response(result.stream(), { headers });
134
+ },
135
+ () => new Response(null, { status: 404 })
136
+ );
137
+ }
138
+ function handleVideo(client, next, path, signal) {
139
+ if (!path) {
140
+ return next();
141
+ }
142
+ return wrap("assets:hls", () => client.proxyHls(path, signal)).then(
143
+ (result) => new Response(result.stream(), { status: result.status, headers: result.headers }),
144
+ () => new Response("Upstream is down", { status: 502, headers: { "content-type": "text/plain" } })
145
+ );
146
+ }
147
+
148
+ // src/routing-middleware.ts
149
+ var import_excludes = require("@astroscope/excludes");
44
150
  var import_store = require("@contello/store");
151
+ var import_middleware2 = require("astro/middleware");
152
+ function customHeaders(headers) {
153
+ const result = {};
154
+ for (const h of headers) {
155
+ result[h.name] = h.value;
156
+ }
157
+ return result;
158
+ }
159
+ function createBoundRoutingMiddleware(contello, routes, exclude, resolveRoutePath) {
160
+ return (0, import_middleware2.defineMiddleware)((ctx, next) => {
161
+ if ((0, import_excludes.shouldExclude)(ctx, exclude ?? import_excludes.RECOMMENDED_EXCLUDES)) {
162
+ return next();
163
+ }
164
+ if (!contello.isReady) {
165
+ console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
166
+ return next();
167
+ }
168
+ const { url } = ctx;
169
+ if (url.pathname.startsWith("/contello/entities/")) {
170
+ return contello[runRequest]({ url, route: void 0, rewritten: false }, () => next());
171
+ }
172
+ const path = resolveRoutePath ? resolveRoutePath(ctx) : url.pathname;
173
+ const lookup = routes.getByPath(path);
174
+ return (0, import_store.maybeThen)(lookup, (route) => {
175
+ if (!route) {
176
+ return contello[runRequest]({ url, route: void 0, rewritten: false }, () => next());
177
+ }
178
+ switch (route.type) {
179
+ case "redirect":
180
+ return contello[runRequest](
181
+ { url, route, rewritten: false },
182
+ () => wrap(
183
+ "route:redirect",
184
+ () => new Response(null, {
185
+ status: route.status,
186
+ headers: {
187
+ Location: route.location,
188
+ ...customHeaders(route.customHeaders)
189
+ }
190
+ })
191
+ )
192
+ );
193
+ case "text":
194
+ return contello[runRequest](
195
+ { url, route, rewritten: false },
196
+ () => wrap(
197
+ "route:text",
198
+ () => new Response(route.content, {
199
+ status: 200,
200
+ headers: {
201
+ "Content-Type": route.mimeType,
202
+ ...customHeaders(route.customHeaders)
203
+ }
204
+ })
205
+ )
206
+ );
207
+ case "asset":
208
+ return contello[runRequest](
209
+ { url, route, rewritten: false },
210
+ () => wrap("route:asset", async () => {
211
+ const result = await contello.client.download(route.fileId);
212
+ const headers = new Headers({ "content-type": result.mimeType });
213
+ if (result.size) {
214
+ headers.set("content-length", String(result.size));
215
+ }
216
+ for (const { name, value } of route.customHeaders) {
217
+ headers.set(name, value);
218
+ }
219
+ return new Response(result.stream(), { headers });
220
+ })
221
+ );
222
+ case "entity":
223
+ return contello[runRequest](
224
+ { url, route, rewritten: true },
225
+ () => wrap(`route:entity:${route.model}`, async () => {
226
+ const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);
227
+ for (const { name, value } of route.customHeaders) {
228
+ response.headers.set(name, value);
229
+ }
230
+ return response;
231
+ })
232
+ );
233
+ }
234
+ });
235
+ });
236
+ }
237
+
238
+ // src/contello.ts
45
239
  var DEFAULT_IMAGES_PREFIX = "/_contello/i/";
46
240
  var DEFAULT_FILES_PREFIX = "/_contello/f/";
47
241
  var DEFAULT_VIDEO_PREFIX = "/_contello/v/";
@@ -83,16 +277,16 @@ async function applyTranslations(messages) {
83
277
  var Contello = class {
84
278
  _store;
85
279
  _options;
86
- _assets;
87
- _routes;
88
280
  _i18nMessages;
89
281
  _i18nUnsubscribe;
90
282
  _initialized = false;
91
283
  _als = new import_node_async_hooks.AsyncLocalStorage();
284
+ _autoEagerRoutes;
285
+ _autoLazyRoutes;
92
286
  media;
93
287
  constructor(options) {
94
288
  this._options = options;
95
- this._store = (0, import_store.createStore)(options);
289
+ this._store = (0, import_store2.createStore)(options);
96
290
  this.media = {
97
291
  baseUrl: options.media?.baseUrl ?? "",
98
292
  imagesPath: options.media?.imagesPath ?? DEFAULT_IMAGES_PREFIX,
@@ -104,12 +298,10 @@ var Contello = class {
104
298
  async init(options) {
105
299
  try {
106
300
  await this._store.init();
107
- this._assets = this._store.defineAssets(this._options.assets);
108
- this._routes = this._store.defineRoutes(this._options.routes);
109
301
  if (this._options.i18n) {
110
- const { collection, languages } = this._options.i18n;
302
+ const { collection, languages, cache } = this._options.i18n;
111
303
  const { register = true, load = true } = options?.i18n ?? {};
112
- this._i18nMessages = this._store.defineI18nMessages({ collection });
304
+ this._i18nMessages = this._store.defineI18nMessages({ collection, cache });
113
305
  await import_i18n.i18n.configure({ locales: languages });
114
306
  if (register) {
115
307
  const registrations = buildI18nRegistrations();
@@ -132,9 +324,8 @@ var Contello = class {
132
324
  })();
133
325
  }
134
326
  }
135
- if (options?.load) {
136
- await Promise.all(options.load.map((l) => l.load()));
137
- }
327
+ const loadables = [...options?.load ?? [], ...this._autoEagerRoutes ? [this._autoEagerRoutes] : []];
328
+ await Promise.all(loadables.map((l) => l.load()));
138
329
  this._initialized = true;
139
330
  } catch (err) {
140
331
  await this.destroy().catch(() => {
@@ -147,8 +338,6 @@ var Contello = class {
147
338
  this._i18nUnsubscribe?.();
148
339
  this._i18nUnsubscribe = void 0;
149
340
  await this._store.destroy();
150
- this._assets = void 0;
151
- this._routes = void 0;
152
341
  this._i18nMessages = void 0;
153
342
  }
154
343
  ping() {
@@ -157,18 +346,8 @@ var Contello = class {
157
346
  get isReady() {
158
347
  return this._initialized;
159
348
  }
160
- // --- pre-wired collections ---
161
- get assets() {
162
- if (!this._assets) {
163
- throw new Error("@contello/astro: .assets accessed before init()");
164
- }
165
- return this._assets;
166
- }
167
- get routes() {
168
- if (!this._routes) {
169
- throw new Error("@contello/astro: .routes accessed before init()");
170
- }
171
- return this._routes;
349
+ get client() {
350
+ return this._store.client;
172
351
  }
173
352
  get i18nMessages() {
174
353
  if (!this._i18nMessages) {
@@ -207,209 +386,50 @@ var Contello = class {
207
386
  defineLazyCollection(sourceOrKey, options) {
208
387
  return this._store.defineLazyCollection(sourceOrKey, options);
209
388
  }
210
- // --- ALS run ---
211
- [runRequest](ctx, fn) {
212
- return this._als.run(ctx, fn);
213
- }
214
- };
215
- function createContello(options) {
216
- return new Contello(options);
217
- }
218
-
219
- // src/assets-middleware.ts
220
- var import_middleware = require("astro/middleware");
221
-
222
- // src/diagnostics.ts
223
- var import_node_diagnostics_channel = __toESM(require("diagnostics_channel"), 1);
224
- var channels = {
225
- start: "@contello/astro:start",
226
- end: "@contello/astro:end",
227
- error: "@contello/astro:error"
228
- };
229
- var onStart = import_node_diagnostics_channel.default.channel(channels.start);
230
- var onEnd = import_node_diagnostics_channel.default.channel(channels.end);
231
- var onError = import_node_diagnostics_channel.default.channel(channels.error);
232
- function hasSubscribers() {
233
- return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
234
- }
235
- function wrap(name, fn) {
236
- if (!hasSubscribers()) {
237
- return fn();
389
+ defineRoutes(options) {
390
+ return this._store.defineRoutes(options);
238
391
  }
239
- const start = performance.now();
240
- onStart.publish({ name });
241
- let result;
242
- try {
243
- result = fn();
244
- } catch (error) {
245
- onError.publish({ name, error, durationMs: performance.now() - start });
246
- throw error;
392
+ defineRoutesSync(options) {
393
+ return this._store.defineRoutesSync(options);
247
394
  }
248
- if (result instanceof Promise) {
249
- return result.then(
250
- (r) => {
251
- onEnd.publish({ name, durationMs: performance.now() - start });
252
- return r;
253
- },
254
- (error) => {
255
- onError.publish({ name, error, durationMs: performance.now() - start });
256
- throw error;
257
- }
258
- );
395
+ defineLazyRoutes(options) {
396
+ return this._store.defineLazyRoutes(options);
259
397
  }
260
- onEnd.publish({ name, durationMs: performance.now() - start });
261
- return result;
262
- }
263
-
264
- // src/assets-middleware.ts
265
- var DEFAULT_IMAGES_CACHE_CONTROL = "public, max-age=31536000";
266
- function createAssetsMiddleware(instance, options) {
267
- const imagesPrefix = instance.media.imagesPath;
268
- const imagesCacheControl = options?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL;
269
- const filesPrefix = instance.media.filesPath;
270
- const filesCacheControl = options?.files?.cacheControl;
271
- const videoPrefix = instance.media.videosPath;
272
- return (0, import_middleware.defineMiddleware)((ctx, next) => {
273
- const { pathname } = ctx.url;
274
- const isImage = pathname.startsWith(imagesPrefix);
275
- const isFile = !isImage && pathname.startsWith(filesPrefix);
276
- const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);
277
- if (!isImage && !isFile && !isVideo) {
278
- return next();
279
- }
280
- if (!instance.isReady) {
281
- console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);
282
- return next();
283
- }
284
- if (isImage) {
285
- return handleFile(instance, next, pathname.slice(imagesPrefix.length), imagesCacheControl);
286
- }
287
- if (isFile) {
288
- return handleFile(instance, next, pathname.slice(filesPrefix.length), filesCacheControl);
289
- }
290
- return handleVideo(instance, next, pathname.slice(videoPrefix.length), ctx.request.signal);
291
- });
292
- }
293
- function handleFile(instance, next, rest, cacheControl) {
294
- const dot = rest.indexOf(".");
295
- const fileId = dot === -1 ? rest : rest.slice(0, dot);
296
- if (!fileId) {
297
- return next();
398
+ defineAssets(options) {
399
+ return this._store.defineAssets(options);
298
400
  }
299
- return wrap("assets:file", () => instance.assets.download(fileId)).then(
300
- (result) => {
301
- const headers = new Headers({ "content-type": result.mimeType });
302
- if (cacheControl) {
303
- headers.set("cache-control", cacheControl);
304
- }
305
- if (result.size) {
306
- headers.set("content-length", String(result.size));
307
- }
308
- return new Response(result.stream(), { headers });
309
- },
310
- () => new Response(null, { status: 404 })
311
- );
312
- }
313
- function handleVideo(instance, next, path, signal) {
314
- if (!path) {
315
- return next();
401
+ defineAssetsSync(options) {
402
+ return this._store.defineAssetsSync(options);
316
403
  }
317
- return wrap("assets:hls", () => instance.assets.proxyHls(path, signal)).then(
318
- (result) => new Response(result.stream(), { status: result.status, headers: result.headers }),
319
- () => new Response("Upstream is down", { status: 502, headers: { "content-type": "text/plain" } })
320
- );
321
- }
322
-
323
- // src/routing-middleware.ts
324
- var import_excludes = require("@astroscope/excludes");
325
- var import_middleware2 = require("astro/middleware");
326
- function customHeaders(headers) {
327
- const result = {};
328
- for (const h of headers) {
329
- result[h.name] = h.value;
404
+ defineLazyAssets(options) {
405
+ return this._store.defineLazyAssets(options);
330
406
  }
331
- return result;
332
- }
333
- function createRoutingMiddleware(instance, options) {
334
- const { exclude } = options ?? {};
335
- return (0, import_middleware2.defineMiddleware)(async (ctx, next) => {
336
- if ((0, import_excludes.shouldExclude)(ctx, exclude ?? import_excludes.RECOMMENDED_EXCLUDES)) {
337
- return next();
338
- }
339
- if (!instance.isReady) {
340
- console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
341
- return next();
342
- }
343
- const { url } = ctx;
344
- if (url.pathname.startsWith("/contello/entities/")) {
345
- return instance[runRequest]({ url, route: void 0, rewritten: false }, () => next());
346
- }
347
- const route = await instance.routes.getByPath(url.pathname);
348
- if (!route) {
349
- return instance[runRequest]({ url, route: void 0, rewritten: false }, () => next());
407
+ // --- middleware factories (arrow fields so destructuring works) ---
408
+ createRoutingMiddleware = (options) => {
409
+ const routesOption = options?.routes ?? "eager";
410
+ let routes;
411
+ if (routesOption === "eager") {
412
+ routes = this._autoEagerRoutes ??= this.defineRoutesSync();
413
+ } else if (routesOption === "lazy") {
414
+ routes = this._autoLazyRoutes ??= this.defineLazyRoutes();
415
+ } else {
416
+ routes = routesOption;
350
417
  }
351
- switch (route.type) {
352
- case "redirect":
353
- return instance[runRequest](
354
- { url, route, rewritten: false },
355
- () => wrap(
356
- "route:redirect",
357
- () => new Response(null, {
358
- status: route.status,
359
- headers: {
360
- Location: route.location,
361
- ...customHeaders(route.customHeaders)
362
- }
363
- })
364
- )
365
- );
366
- case "text":
367
- return instance[runRequest](
368
- { url, route, rewritten: false },
369
- () => wrap(
370
- "route:text",
371
- () => new Response(route.content, {
372
- status: 200,
373
- headers: {
374
- "Content-Type": route.mimeType,
375
- ...customHeaders(route.customHeaders)
376
- }
377
- })
378
- )
379
- );
380
- case "asset":
381
- return instance[runRequest](
382
- { url, route, rewritten: false },
383
- () => wrap("route:asset", async () => {
384
- const result = await instance.assets.download(route.fileId);
385
- const headers = new Headers({ "content-type": result.mimeType });
386
- if (result.size) {
387
- headers.set("content-length", String(result.size));
388
- }
389
- for (const { name, value } of route.customHeaders) {
390
- headers.set(name, value);
391
- }
392
- return new Response(result.stream(), { headers });
393
- })
394
- );
395
- case "entity":
396
- return instance[runRequest](
397
- { url, route, rewritten: true },
398
- () => wrap(`route:entity:${route.model}`, async () => {
399
- const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);
400
- for (const { name, value } of route.customHeaders) {
401
- response.headers.set(name, value);
402
- }
403
- return response;
404
- })
405
- );
406
- }
407
- });
418
+ return createBoundRoutingMiddleware(this, routes, options?.exclude, options?.resolveRoutePath);
419
+ };
420
+ createAssetsMiddleware = (options) => {
421
+ return createBoundAssetsMiddleware(this, options);
422
+ };
423
+ // --- ALS run ---
424
+ [runRequest](ctx, fn) {
425
+ return this._als.run(ctx, fn);
426
+ }
427
+ };
428
+ function createContello(options) {
429
+ return new Contello(options);
408
430
  }
409
431
  // Annotate the CommonJS export names for ESM import in node:
410
432
  0 && (module.exports = {
411
433
  Contello,
412
- createAssetsMiddleware,
413
- createContello,
414
- createRoutingMiddleware
434
+ createContello
415
435
  });
package/dist/index.d.cts CHANGED
@@ -1,9 +1,45 @@
1
- import { Schema, SourceDef } from '@contello/client';
2
- import { MediaResolverOptions, MediaResolver, ImageDef } from '@contello/media';
3
- import { CreateStoreOptions, AssetCollectionOptions, RouteCollectionOptions, Loadable, Assets, Routes, I18nMessages, ReadonlyDeep, StoreRoute, SourceKeysOf, ExtractSourceResult, ResolveSource, SingletonOptions, Singleton, SingletonSyncOptions, SingletonSync, CollectionOptions, Collection, CollectionSyncOptions, CollectionSync, LazyCollectionOptions, LazyCollection } from '@contello/store';
4
1
  import * as astro from 'astro';
2
+ import { APIContext } from 'astro';
3
+ import { Schema, ContelloClient, SourceDef } from '@contello/client';
4
+ import { MediaResolverOptions, MediaResolver, ImageDef } from '@contello/media';
5
+ import { Routes, RoutesSync, LazyRoutes, CreateStoreOptions, SyncCacheOptions, Loadable, I18nMessages, ReadonlyDeep, StoreRoute, SourceKeysOf, ExtractSourceResult, ResolveSource, SingletonOptions, Singleton, SingletonSyncOptions, SingletonSync, CollectionOptions, Collection, CollectionSyncOptions, CollectionSync, LazyCollectionOptions, LazyCollection, RoutesOptions, RoutesSyncOptions, LazyRoutesOptions, AssetsOptions, Assets, AssetsSyncOptions, AssetsSync, LazyAssetsOptions, LazyAssets } from '@contello/store';
5
6
  import { ExcludePattern } from '@astroscope/excludes';
6
7
 
8
+ type ContelloAssetsImagesOptions = {
9
+ cacheControl?: string | undefined;
10
+ };
11
+ type ContelloAssetsFilesOptions = {
12
+ cacheControl?: string | undefined;
13
+ };
14
+ type ContelloAssetsVideoOptions = {};
15
+ type ContelloAssetsMiddlewareOptions = {
16
+ images?: ContelloAssetsImagesOptions | undefined;
17
+ files?: ContelloAssetsFilesOptions | undefined;
18
+ video?: ContelloAssetsVideoOptions | undefined;
19
+ };
20
+
21
+ type AnyRoutes = Routes | RoutesSync | LazyRoutes;
22
+ /**
23
+ * Derives the path used to look up a Contello route from the request context.
24
+ *
25
+ * @default `(ctx) => ctx.url.pathname`
26
+ *
27
+ * ```ts
28
+ * resolveRoutePath: (ctx) => `/${ctx.url.hostname}${ctx.url.pathname}`
29
+ * ```
30
+ */
31
+ type RoutePathResolver = (ctx: APIContext) => string;
32
+ type ContelloRoutingMiddlewareOptions = {
33
+ /**
34
+ * - `'eager'` (default) — use a `RoutesSync` instance managed by contello (auto-loaded by `contello.init()`)
35
+ * - `'lazy'` — use a `LazyRoutes` instance managed by contello
36
+ * - a user-defined routes instance (`Routes` / `RoutesSync` / `LazyRoutes`) — consumer manages its lifecycle
37
+ */
38
+ routes?: 'eager' | 'lazy' | AnyRoutes | undefined;
39
+ exclude?: ExcludePattern[] | undefined;
40
+ resolveRoutePath?: RoutePathResolver | undefined;
41
+ };
42
+
7
43
  type ContelloRequestContext = {
8
44
  url: URL;
9
45
  route: ReadonlyDeep<StoreRoute> | undefined;
@@ -12,6 +48,7 @@ type ContelloRequestContext = {
12
48
  type ContelloI18nOptions = {
13
49
  collection: string;
14
50
  languages: string[];
51
+ cache?: SyncCacheOptions | undefined;
15
52
  };
16
53
  type ContelloInitOptions = {
17
54
  load?: Loadable[] | undefined;
@@ -27,9 +64,7 @@ type ContelloMediaConfig = {
27
64
  readonly filesPath: string;
28
65
  };
29
66
  type ContelloOptions<TSchema extends Schema | undefined = undefined> = CreateStoreOptions<TSchema> & {
30
- assets?: AssetCollectionOptions | undefined;
31
67
  i18n?: ContelloI18nOptions | undefined;
32
- routes?: RouteCollectionOptions | undefined;
33
68
  media?: Partial<ContelloMediaConfig> | undefined;
34
69
  };
35
70
  type HasFallback<O> = O extends {
@@ -46,20 +81,19 @@ type SingletonRaw<TSchema, TArg> = ExtractSourceResult<Extract<ResolveSource<TSc
46
81
  declare class Contello<TSchema extends Schema | undefined = undefined> {
47
82
  private readonly _store;
48
83
  private readonly _options;
49
- private _assets;
50
- private _routes;
51
84
  private _i18nMessages;
52
85
  private _i18nUnsubscribe;
53
86
  private _initialized;
54
87
  private readonly _als;
88
+ private _autoEagerRoutes?;
89
+ private _autoLazyRoutes?;
55
90
  readonly media: ContelloMediaConfig;
56
91
  constructor(options: ContelloOptions<TSchema>);
57
92
  init(options?: ContelloInitOptions | undefined): Promise<void>;
58
93
  destroy(): Promise<void>;
59
94
  ping(): Promise<void>;
60
95
  get isReady(): boolean;
61
- get assets(): Assets;
62
- get routes(): Routes;
96
+ get client(): ContelloClient<TSchema>;
63
97
  get i18nMessages(): I18nMessages;
64
98
  get request(): ContelloRequestContext;
65
99
  defineMediaResolver<O extends Partial<MediaResolverOptions>>(options?: O): MediaResolver<HasFallback<O>>;
@@ -80,27 +114,16 @@ declare class Contello<TSchema extends Schema | undefined = undefined> {
80
114
  } = CollectionRaw<TSchema, TArg> & {
81
115
  id: string;
82
116
  }>(sourceOrKey: TArg, options?: LazyCollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>): LazyCollection<TMapped>;
117
+ defineRoutes(options?: RoutesOptions | undefined): Routes;
118
+ defineRoutesSync(options?: RoutesSyncOptions | undefined): RoutesSync;
119
+ defineLazyRoutes(options?: LazyRoutesOptions | undefined): LazyRoutes;
120
+ defineAssets(options?: AssetsOptions | undefined): Assets;
121
+ defineAssetsSync(options?: AssetsSyncOptions | undefined): AssetsSync;
122
+ defineLazyAssets(options?: LazyAssetsOptions | undefined): LazyAssets;
123
+ createRoutingMiddleware: (options?: ContelloRoutingMiddlewareOptions | undefined) => astro.MiddlewareHandler;
124
+ createAssetsMiddleware: (options?: ContelloAssetsMiddlewareOptions | undefined) => astro.MiddlewareHandler;
83
125
  [runRequest]<T>(ctx: ContelloRequestContext, fn: () => T): T;
84
126
  }
85
127
  declare function createContello<TSchema extends Schema | undefined = undefined>(options: ContelloOptions<TSchema>): Contello<TSchema>;
86
128
 
87
- type ContelloAssetsImagesOptions = {
88
- cacheControl?: string | undefined;
89
- };
90
- type ContelloAssetsFilesOptions = {
91
- cacheControl?: string | undefined;
92
- };
93
- type ContelloAssetsVideoOptions = {};
94
- type ContelloAssetsMiddlewareOptions = {
95
- images?: ContelloAssetsImagesOptions | undefined;
96
- files?: ContelloAssetsFilesOptions | undefined;
97
- video?: ContelloAssetsVideoOptions | undefined;
98
- };
99
- declare function createAssetsMiddleware(instance: Contello<any>, options?: ContelloAssetsMiddlewareOptions | undefined): astro.MiddlewareHandler;
100
-
101
- type ContelloMiddlewareOptions = {
102
- exclude?: ExcludePattern[] | undefined;
103
- };
104
- declare function createRoutingMiddleware(instance: Contello<any>, options?: ContelloMiddlewareOptions | undefined): astro.MiddlewareHandler;
105
-
106
- export { Contello, type ContelloAssetsFilesOptions, type ContelloAssetsImagesOptions, type ContelloAssetsMiddlewareOptions, type ContelloAssetsVideoOptions, type ContelloI18nOptions, type ContelloInitOptions, type ContelloMiddlewareOptions, type ContelloOptions, type ContelloRequestContext, createAssetsMiddleware, createContello, createRoutingMiddleware };
129
+ export { type AnyRoutes, Contello, type ContelloAssetsFilesOptions, type ContelloAssetsImagesOptions, type ContelloAssetsMiddlewareOptions, type ContelloAssetsVideoOptions, type ContelloI18nOptions, type ContelloInitOptions, type ContelloOptions, type ContelloRequestContext, type ContelloRoutingMiddlewareOptions, createContello };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,45 @@
1
- import { Schema, SourceDef } from '@contello/client';
2
- import { MediaResolverOptions, MediaResolver, ImageDef } from '@contello/media';
3
- import { CreateStoreOptions, AssetCollectionOptions, RouteCollectionOptions, Loadable, Assets, Routes, I18nMessages, ReadonlyDeep, StoreRoute, SourceKeysOf, ExtractSourceResult, ResolveSource, SingletonOptions, Singleton, SingletonSyncOptions, SingletonSync, CollectionOptions, Collection, CollectionSyncOptions, CollectionSync, LazyCollectionOptions, LazyCollection } from '@contello/store';
4
1
  import * as astro from 'astro';
2
+ import { APIContext } from 'astro';
3
+ import { Schema, ContelloClient, SourceDef } from '@contello/client';
4
+ import { MediaResolverOptions, MediaResolver, ImageDef } from '@contello/media';
5
+ import { Routes, RoutesSync, LazyRoutes, CreateStoreOptions, SyncCacheOptions, Loadable, I18nMessages, ReadonlyDeep, StoreRoute, SourceKeysOf, ExtractSourceResult, ResolveSource, SingletonOptions, Singleton, SingletonSyncOptions, SingletonSync, CollectionOptions, Collection, CollectionSyncOptions, CollectionSync, LazyCollectionOptions, LazyCollection, RoutesOptions, RoutesSyncOptions, LazyRoutesOptions, AssetsOptions, Assets, AssetsSyncOptions, AssetsSync, LazyAssetsOptions, LazyAssets } from '@contello/store';
5
6
  import { ExcludePattern } from '@astroscope/excludes';
6
7
 
8
+ type ContelloAssetsImagesOptions = {
9
+ cacheControl?: string | undefined;
10
+ };
11
+ type ContelloAssetsFilesOptions = {
12
+ cacheControl?: string | undefined;
13
+ };
14
+ type ContelloAssetsVideoOptions = {};
15
+ type ContelloAssetsMiddlewareOptions = {
16
+ images?: ContelloAssetsImagesOptions | undefined;
17
+ files?: ContelloAssetsFilesOptions | undefined;
18
+ video?: ContelloAssetsVideoOptions | undefined;
19
+ };
20
+
21
+ type AnyRoutes = Routes | RoutesSync | LazyRoutes;
22
+ /**
23
+ * Derives the path used to look up a Contello route from the request context.
24
+ *
25
+ * @default `(ctx) => ctx.url.pathname`
26
+ *
27
+ * ```ts
28
+ * resolveRoutePath: (ctx) => `/${ctx.url.hostname}${ctx.url.pathname}`
29
+ * ```
30
+ */
31
+ type RoutePathResolver = (ctx: APIContext) => string;
32
+ type ContelloRoutingMiddlewareOptions = {
33
+ /**
34
+ * - `'eager'` (default) — use a `RoutesSync` instance managed by contello (auto-loaded by `contello.init()`)
35
+ * - `'lazy'` — use a `LazyRoutes` instance managed by contello
36
+ * - a user-defined routes instance (`Routes` / `RoutesSync` / `LazyRoutes`) — consumer manages its lifecycle
37
+ */
38
+ routes?: 'eager' | 'lazy' | AnyRoutes | undefined;
39
+ exclude?: ExcludePattern[] | undefined;
40
+ resolveRoutePath?: RoutePathResolver | undefined;
41
+ };
42
+
7
43
  type ContelloRequestContext = {
8
44
  url: URL;
9
45
  route: ReadonlyDeep<StoreRoute> | undefined;
@@ -12,6 +48,7 @@ type ContelloRequestContext = {
12
48
  type ContelloI18nOptions = {
13
49
  collection: string;
14
50
  languages: string[];
51
+ cache?: SyncCacheOptions | undefined;
15
52
  };
16
53
  type ContelloInitOptions = {
17
54
  load?: Loadable[] | undefined;
@@ -27,9 +64,7 @@ type ContelloMediaConfig = {
27
64
  readonly filesPath: string;
28
65
  };
29
66
  type ContelloOptions<TSchema extends Schema | undefined = undefined> = CreateStoreOptions<TSchema> & {
30
- assets?: AssetCollectionOptions | undefined;
31
67
  i18n?: ContelloI18nOptions | undefined;
32
- routes?: RouteCollectionOptions | undefined;
33
68
  media?: Partial<ContelloMediaConfig> | undefined;
34
69
  };
35
70
  type HasFallback<O> = O extends {
@@ -46,20 +81,19 @@ type SingletonRaw<TSchema, TArg> = ExtractSourceResult<Extract<ResolveSource<TSc
46
81
  declare class Contello<TSchema extends Schema | undefined = undefined> {
47
82
  private readonly _store;
48
83
  private readonly _options;
49
- private _assets;
50
- private _routes;
51
84
  private _i18nMessages;
52
85
  private _i18nUnsubscribe;
53
86
  private _initialized;
54
87
  private readonly _als;
88
+ private _autoEagerRoutes?;
89
+ private _autoLazyRoutes?;
55
90
  readonly media: ContelloMediaConfig;
56
91
  constructor(options: ContelloOptions<TSchema>);
57
92
  init(options?: ContelloInitOptions | undefined): Promise<void>;
58
93
  destroy(): Promise<void>;
59
94
  ping(): Promise<void>;
60
95
  get isReady(): boolean;
61
- get assets(): Assets;
62
- get routes(): Routes;
96
+ get client(): ContelloClient<TSchema>;
63
97
  get i18nMessages(): I18nMessages;
64
98
  get request(): ContelloRequestContext;
65
99
  defineMediaResolver<O extends Partial<MediaResolverOptions>>(options?: O): MediaResolver<HasFallback<O>>;
@@ -80,27 +114,16 @@ declare class Contello<TSchema extends Schema | undefined = undefined> {
80
114
  } = CollectionRaw<TSchema, TArg> & {
81
115
  id: string;
82
116
  }>(sourceOrKey: TArg, options?: LazyCollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>): LazyCollection<TMapped>;
117
+ defineRoutes(options?: RoutesOptions | undefined): Routes;
118
+ defineRoutesSync(options?: RoutesSyncOptions | undefined): RoutesSync;
119
+ defineLazyRoutes(options?: LazyRoutesOptions | undefined): LazyRoutes;
120
+ defineAssets(options?: AssetsOptions | undefined): Assets;
121
+ defineAssetsSync(options?: AssetsSyncOptions | undefined): AssetsSync;
122
+ defineLazyAssets(options?: LazyAssetsOptions | undefined): LazyAssets;
123
+ createRoutingMiddleware: (options?: ContelloRoutingMiddlewareOptions | undefined) => astro.MiddlewareHandler;
124
+ createAssetsMiddleware: (options?: ContelloAssetsMiddlewareOptions | undefined) => astro.MiddlewareHandler;
83
125
  [runRequest]<T>(ctx: ContelloRequestContext, fn: () => T): T;
84
126
  }
85
127
  declare function createContello<TSchema extends Schema | undefined = undefined>(options: ContelloOptions<TSchema>): Contello<TSchema>;
86
128
 
87
- type ContelloAssetsImagesOptions = {
88
- cacheControl?: string | undefined;
89
- };
90
- type ContelloAssetsFilesOptions = {
91
- cacheControl?: string | undefined;
92
- };
93
- type ContelloAssetsVideoOptions = {};
94
- type ContelloAssetsMiddlewareOptions = {
95
- images?: ContelloAssetsImagesOptions | undefined;
96
- files?: ContelloAssetsFilesOptions | undefined;
97
- video?: ContelloAssetsVideoOptions | undefined;
98
- };
99
- declare function createAssetsMiddleware(instance: Contello<any>, options?: ContelloAssetsMiddlewareOptions | undefined): astro.MiddlewareHandler;
100
-
101
- type ContelloMiddlewareOptions = {
102
- exclude?: ExcludePattern[] | undefined;
103
- };
104
- declare function createRoutingMiddleware(instance: Contello<any>, options?: ContelloMiddlewareOptions | undefined): astro.MiddlewareHandler;
105
-
106
- export { Contello, type ContelloAssetsFilesOptions, type ContelloAssetsImagesOptions, type ContelloAssetsMiddlewareOptions, type ContelloAssetsVideoOptions, type ContelloI18nOptions, type ContelloInitOptions, type ContelloMiddlewareOptions, type ContelloOptions, type ContelloRequestContext, createAssetsMiddleware, createContello, createRoutingMiddleware };
129
+ export { type AnyRoutes, Contello, type ContelloAssetsFilesOptions, type ContelloAssetsImagesOptions, type ContelloAssetsMiddlewareOptions, type ContelloAssetsVideoOptions, type ContelloI18nOptions, type ContelloInitOptions, type ContelloOptions, type ContelloRequestContext, type ContelloRoutingMiddlewareOptions, createContello };
package/dist/index.js CHANGED
@@ -5,6 +5,204 @@ import { createMediaResolver } from "@contello/media";
5
5
  import {
6
6
  createStore
7
7
  } from "@contello/store";
8
+
9
+ // src/assets-middleware.ts
10
+ import { defineMiddleware } from "astro/middleware";
11
+
12
+ // src/diagnostics.ts
13
+ import dc from "diagnostics_channel";
14
+ var channels = {
15
+ start: "@contello/astro:start",
16
+ end: "@contello/astro:end",
17
+ error: "@contello/astro:error"
18
+ };
19
+ var onStart = dc.channel(channels.start);
20
+ var onEnd = dc.channel(channels.end);
21
+ var onError = dc.channel(channels.error);
22
+ function hasSubscribers() {
23
+ return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
24
+ }
25
+ function wrap(name, fn) {
26
+ if (!hasSubscribers()) {
27
+ return fn();
28
+ }
29
+ const start = performance.now();
30
+ onStart.publish({ name });
31
+ let result;
32
+ try {
33
+ result = fn();
34
+ } catch (error) {
35
+ onError.publish({ name, error, durationMs: performance.now() - start });
36
+ throw error;
37
+ }
38
+ if (result instanceof Promise) {
39
+ return result.then(
40
+ (r) => {
41
+ onEnd.publish({ name, durationMs: performance.now() - start });
42
+ return r;
43
+ },
44
+ (error) => {
45
+ onError.publish({ name, error, durationMs: performance.now() - start });
46
+ throw error;
47
+ }
48
+ );
49
+ }
50
+ onEnd.publish({ name, durationMs: performance.now() - start });
51
+ return result;
52
+ }
53
+
54
+ // src/assets-middleware.ts
55
+ var DEFAULT_IMAGES_CACHE_CONTROL = "public, max-age=31536000";
56
+ function createBoundAssetsMiddleware(contello, options) {
57
+ const imagesPrefix = contello.media.imagesPath;
58
+ const imagesCacheControl = options?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL;
59
+ const filesPrefix = contello.media.filesPath;
60
+ const filesCacheControl = options?.files?.cacheControl;
61
+ const videoPrefix = contello.media.videosPath;
62
+ return defineMiddleware((ctx, next) => {
63
+ const { pathname } = ctx.url;
64
+ const isImage = pathname.startsWith(imagesPrefix);
65
+ const isFile = !isImage && pathname.startsWith(filesPrefix);
66
+ const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);
67
+ if (!isImage && !isFile && !isVideo) {
68
+ return next();
69
+ }
70
+ if (!contello.isReady) {
71
+ console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);
72
+ return next();
73
+ }
74
+ if (isImage) {
75
+ return handleFile(contello.client, next, pathname.slice(imagesPrefix.length), imagesCacheControl);
76
+ }
77
+ if (isFile) {
78
+ return handleFile(contello.client, next, pathname.slice(filesPrefix.length), filesCacheControl);
79
+ }
80
+ return handleVideo(contello.client, next, pathname.slice(videoPrefix.length), ctx.request.signal);
81
+ });
82
+ }
83
+ function handleFile(client, next, rest, cacheControl) {
84
+ const dot = rest.indexOf(".");
85
+ const fileId = dot === -1 ? rest : rest.slice(0, dot);
86
+ if (!fileId) {
87
+ return next();
88
+ }
89
+ return wrap("assets:file", () => client.download(fileId)).then(
90
+ (result) => {
91
+ const headers = new Headers({ "content-type": result.mimeType });
92
+ if (cacheControl) {
93
+ headers.set("cache-control", cacheControl);
94
+ }
95
+ if (result.size) {
96
+ headers.set("content-length", String(result.size));
97
+ }
98
+ return new Response(result.stream(), { headers });
99
+ },
100
+ () => new Response(null, { status: 404 })
101
+ );
102
+ }
103
+ function handleVideo(client, next, path, signal) {
104
+ if (!path) {
105
+ return next();
106
+ }
107
+ return wrap("assets:hls", () => client.proxyHls(path, signal)).then(
108
+ (result) => new Response(result.stream(), { status: result.status, headers: result.headers }),
109
+ () => new Response("Upstream is down", { status: 502, headers: { "content-type": "text/plain" } })
110
+ );
111
+ }
112
+
113
+ // src/routing-middleware.ts
114
+ import { RECOMMENDED_EXCLUDES, shouldExclude } from "@astroscope/excludes";
115
+ import {
116
+ maybeThen
117
+ } from "@contello/store";
118
+ import { defineMiddleware as defineMiddleware2 } from "astro/middleware";
119
+ function customHeaders(headers) {
120
+ const result = {};
121
+ for (const h of headers) {
122
+ result[h.name] = h.value;
123
+ }
124
+ return result;
125
+ }
126
+ function createBoundRoutingMiddleware(contello, routes, exclude, resolveRoutePath) {
127
+ return defineMiddleware2((ctx, next) => {
128
+ if (shouldExclude(ctx, exclude ?? RECOMMENDED_EXCLUDES)) {
129
+ return next();
130
+ }
131
+ if (!contello.isReady) {
132
+ console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
133
+ return next();
134
+ }
135
+ const { url } = ctx;
136
+ if (url.pathname.startsWith("/contello/entities/")) {
137
+ return contello[runRequest]({ url, route: void 0, rewritten: false }, () => next());
138
+ }
139
+ const path = resolveRoutePath ? resolveRoutePath(ctx) : url.pathname;
140
+ const lookup = routes.getByPath(path);
141
+ return maybeThen(lookup, (route) => {
142
+ if (!route) {
143
+ return contello[runRequest]({ url, route: void 0, rewritten: false }, () => next());
144
+ }
145
+ switch (route.type) {
146
+ case "redirect":
147
+ return contello[runRequest](
148
+ { url, route, rewritten: false },
149
+ () => wrap(
150
+ "route:redirect",
151
+ () => new Response(null, {
152
+ status: route.status,
153
+ headers: {
154
+ Location: route.location,
155
+ ...customHeaders(route.customHeaders)
156
+ }
157
+ })
158
+ )
159
+ );
160
+ case "text":
161
+ return contello[runRequest](
162
+ { url, route, rewritten: false },
163
+ () => wrap(
164
+ "route:text",
165
+ () => new Response(route.content, {
166
+ status: 200,
167
+ headers: {
168
+ "Content-Type": route.mimeType,
169
+ ...customHeaders(route.customHeaders)
170
+ }
171
+ })
172
+ )
173
+ );
174
+ case "asset":
175
+ return contello[runRequest](
176
+ { url, route, rewritten: false },
177
+ () => wrap("route:asset", async () => {
178
+ const result = await contello.client.download(route.fileId);
179
+ const headers = new Headers({ "content-type": result.mimeType });
180
+ if (result.size) {
181
+ headers.set("content-length", String(result.size));
182
+ }
183
+ for (const { name, value } of route.customHeaders) {
184
+ headers.set(name, value);
185
+ }
186
+ return new Response(result.stream(), { headers });
187
+ })
188
+ );
189
+ case "entity":
190
+ return contello[runRequest](
191
+ { url, route, rewritten: true },
192
+ () => wrap(`route:entity:${route.model}`, async () => {
193
+ const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);
194
+ for (const { name, value } of route.customHeaders) {
195
+ response.headers.set(name, value);
196
+ }
197
+ return response;
198
+ })
199
+ );
200
+ }
201
+ });
202
+ });
203
+ }
204
+
205
+ // src/contello.ts
8
206
  var DEFAULT_IMAGES_PREFIX = "/_contello/i/";
9
207
  var DEFAULT_FILES_PREFIX = "/_contello/f/";
10
208
  var DEFAULT_VIDEO_PREFIX = "/_contello/v/";
@@ -46,12 +244,12 @@ async function applyTranslations(messages) {
46
244
  var Contello = class {
47
245
  _store;
48
246
  _options;
49
- _assets;
50
- _routes;
51
247
  _i18nMessages;
52
248
  _i18nUnsubscribe;
53
249
  _initialized = false;
54
250
  _als = new AsyncLocalStorage();
251
+ _autoEagerRoutes;
252
+ _autoLazyRoutes;
55
253
  media;
56
254
  constructor(options) {
57
255
  this._options = options;
@@ -67,12 +265,10 @@ var Contello = class {
67
265
  async init(options) {
68
266
  try {
69
267
  await this._store.init();
70
- this._assets = this._store.defineAssets(this._options.assets);
71
- this._routes = this._store.defineRoutes(this._options.routes);
72
268
  if (this._options.i18n) {
73
- const { collection, languages } = this._options.i18n;
269
+ const { collection, languages, cache } = this._options.i18n;
74
270
  const { register = true, load = true } = options?.i18n ?? {};
75
- this._i18nMessages = this._store.defineI18nMessages({ collection });
271
+ this._i18nMessages = this._store.defineI18nMessages({ collection, cache });
76
272
  await i18n.configure({ locales: languages });
77
273
  if (register) {
78
274
  const registrations = buildI18nRegistrations();
@@ -95,9 +291,8 @@ var Contello = class {
95
291
  })();
96
292
  }
97
293
  }
98
- if (options?.load) {
99
- await Promise.all(options.load.map((l) => l.load()));
100
- }
294
+ const loadables = [...options?.load ?? [], ...this._autoEagerRoutes ? [this._autoEagerRoutes] : []];
295
+ await Promise.all(loadables.map((l) => l.load()));
101
296
  this._initialized = true;
102
297
  } catch (err) {
103
298
  await this.destroy().catch(() => {
@@ -110,8 +305,6 @@ var Contello = class {
110
305
  this._i18nUnsubscribe?.();
111
306
  this._i18nUnsubscribe = void 0;
112
307
  await this._store.destroy();
113
- this._assets = void 0;
114
- this._routes = void 0;
115
308
  this._i18nMessages = void 0;
116
309
  }
117
310
  ping() {
@@ -120,18 +313,8 @@ var Contello = class {
120
313
  get isReady() {
121
314
  return this._initialized;
122
315
  }
123
- // --- pre-wired collections ---
124
- get assets() {
125
- if (!this._assets) {
126
- throw new Error("@contello/astro: .assets accessed before init()");
127
- }
128
- return this._assets;
129
- }
130
- get routes() {
131
- if (!this._routes) {
132
- throw new Error("@contello/astro: .routes accessed before init()");
133
- }
134
- return this._routes;
316
+ get client() {
317
+ return this._store.client;
135
318
  }
136
319
  get i18nMessages() {
137
320
  if (!this._i18nMessages) {
@@ -170,208 +353,49 @@ var Contello = class {
170
353
  defineLazyCollection(sourceOrKey, options) {
171
354
  return this._store.defineLazyCollection(sourceOrKey, options);
172
355
  }
173
- // --- ALS run ---
174
- [runRequest](ctx, fn) {
175
- return this._als.run(ctx, fn);
356
+ defineRoutes(options) {
357
+ return this._store.defineRoutes(options);
176
358
  }
177
- };
178
- function createContello(options) {
179
- return new Contello(options);
180
- }
181
-
182
- // src/assets-middleware.ts
183
- import { defineMiddleware } from "astro/middleware";
184
-
185
- // src/diagnostics.ts
186
- import dc from "diagnostics_channel";
187
- var channels = {
188
- start: "@contello/astro:start",
189
- end: "@contello/astro:end",
190
- error: "@contello/astro:error"
191
- };
192
- var onStart = dc.channel(channels.start);
193
- var onEnd = dc.channel(channels.end);
194
- var onError = dc.channel(channels.error);
195
- function hasSubscribers() {
196
- return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
197
- }
198
- function wrap(name, fn) {
199
- if (!hasSubscribers()) {
200
- return fn();
359
+ defineRoutesSync(options) {
360
+ return this._store.defineRoutesSync(options);
201
361
  }
202
- const start = performance.now();
203
- onStart.publish({ name });
204
- let result;
205
- try {
206
- result = fn();
207
- } catch (error) {
208
- onError.publish({ name, error, durationMs: performance.now() - start });
209
- throw error;
210
- }
211
- if (result instanceof Promise) {
212
- return result.then(
213
- (r) => {
214
- onEnd.publish({ name, durationMs: performance.now() - start });
215
- return r;
216
- },
217
- (error) => {
218
- onError.publish({ name, error, durationMs: performance.now() - start });
219
- throw error;
220
- }
221
- );
362
+ defineLazyRoutes(options) {
363
+ return this._store.defineLazyRoutes(options);
222
364
  }
223
- onEnd.publish({ name, durationMs: performance.now() - start });
224
- return result;
225
- }
226
-
227
- // src/assets-middleware.ts
228
- var DEFAULT_IMAGES_CACHE_CONTROL = "public, max-age=31536000";
229
- function createAssetsMiddleware(instance, options) {
230
- const imagesPrefix = instance.media.imagesPath;
231
- const imagesCacheControl = options?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL;
232
- const filesPrefix = instance.media.filesPath;
233
- const filesCacheControl = options?.files?.cacheControl;
234
- const videoPrefix = instance.media.videosPath;
235
- return defineMiddleware((ctx, next) => {
236
- const { pathname } = ctx.url;
237
- const isImage = pathname.startsWith(imagesPrefix);
238
- const isFile = !isImage && pathname.startsWith(filesPrefix);
239
- const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);
240
- if (!isImage && !isFile && !isVideo) {
241
- return next();
242
- }
243
- if (!instance.isReady) {
244
- console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);
245
- return next();
246
- }
247
- if (isImage) {
248
- return handleFile(instance, next, pathname.slice(imagesPrefix.length), imagesCacheControl);
249
- }
250
- if (isFile) {
251
- return handleFile(instance, next, pathname.slice(filesPrefix.length), filesCacheControl);
252
- }
253
- return handleVideo(instance, next, pathname.slice(videoPrefix.length), ctx.request.signal);
254
- });
255
- }
256
- function handleFile(instance, next, rest, cacheControl) {
257
- const dot = rest.indexOf(".");
258
- const fileId = dot === -1 ? rest : rest.slice(0, dot);
259
- if (!fileId) {
260
- return next();
365
+ defineAssets(options) {
366
+ return this._store.defineAssets(options);
261
367
  }
262
- return wrap("assets:file", () => instance.assets.download(fileId)).then(
263
- (result) => {
264
- const headers = new Headers({ "content-type": result.mimeType });
265
- if (cacheControl) {
266
- headers.set("cache-control", cacheControl);
267
- }
268
- if (result.size) {
269
- headers.set("content-length", String(result.size));
270
- }
271
- return new Response(result.stream(), { headers });
272
- },
273
- () => new Response(null, { status: 404 })
274
- );
275
- }
276
- function handleVideo(instance, next, path, signal) {
277
- if (!path) {
278
- return next();
368
+ defineAssetsSync(options) {
369
+ return this._store.defineAssetsSync(options);
279
370
  }
280
- return wrap("assets:hls", () => instance.assets.proxyHls(path, signal)).then(
281
- (result) => new Response(result.stream(), { status: result.status, headers: result.headers }),
282
- () => new Response("Upstream is down", { status: 502, headers: { "content-type": "text/plain" } })
283
- );
284
- }
285
-
286
- // src/routing-middleware.ts
287
- import { RECOMMENDED_EXCLUDES, shouldExclude } from "@astroscope/excludes";
288
- import { defineMiddleware as defineMiddleware2 } from "astro/middleware";
289
- function customHeaders(headers) {
290
- const result = {};
291
- for (const h of headers) {
292
- result[h.name] = h.value;
371
+ defineLazyAssets(options) {
372
+ return this._store.defineLazyAssets(options);
293
373
  }
294
- return result;
295
- }
296
- function createRoutingMiddleware(instance, options) {
297
- const { exclude } = options ?? {};
298
- return defineMiddleware2(async (ctx, next) => {
299
- if (shouldExclude(ctx, exclude ?? RECOMMENDED_EXCLUDES)) {
300
- return next();
301
- }
302
- if (!instance.isReady) {
303
- console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
304
- return next();
305
- }
306
- const { url } = ctx;
307
- if (url.pathname.startsWith("/contello/entities/")) {
308
- return instance[runRequest]({ url, route: void 0, rewritten: false }, () => next());
309
- }
310
- const route = await instance.routes.getByPath(url.pathname);
311
- if (!route) {
312
- return instance[runRequest]({ url, route: void 0, rewritten: false }, () => next());
374
+ // --- middleware factories (arrow fields so destructuring works) ---
375
+ createRoutingMiddleware = (options) => {
376
+ const routesOption = options?.routes ?? "eager";
377
+ let routes;
378
+ if (routesOption === "eager") {
379
+ routes = this._autoEagerRoutes ??= this.defineRoutesSync();
380
+ } else if (routesOption === "lazy") {
381
+ routes = this._autoLazyRoutes ??= this.defineLazyRoutes();
382
+ } else {
383
+ routes = routesOption;
313
384
  }
314
- switch (route.type) {
315
- case "redirect":
316
- return instance[runRequest](
317
- { url, route, rewritten: false },
318
- () => wrap(
319
- "route:redirect",
320
- () => new Response(null, {
321
- status: route.status,
322
- headers: {
323
- Location: route.location,
324
- ...customHeaders(route.customHeaders)
325
- }
326
- })
327
- )
328
- );
329
- case "text":
330
- return instance[runRequest](
331
- { url, route, rewritten: false },
332
- () => wrap(
333
- "route:text",
334
- () => new Response(route.content, {
335
- status: 200,
336
- headers: {
337
- "Content-Type": route.mimeType,
338
- ...customHeaders(route.customHeaders)
339
- }
340
- })
341
- )
342
- );
343
- case "asset":
344
- return instance[runRequest](
345
- { url, route, rewritten: false },
346
- () => wrap("route:asset", async () => {
347
- const result = await instance.assets.download(route.fileId);
348
- const headers = new Headers({ "content-type": result.mimeType });
349
- if (result.size) {
350
- headers.set("content-length", String(result.size));
351
- }
352
- for (const { name, value } of route.customHeaders) {
353
- headers.set(name, value);
354
- }
355
- return new Response(result.stream(), { headers });
356
- })
357
- );
358
- case "entity":
359
- return instance[runRequest](
360
- { url, route, rewritten: true },
361
- () => wrap(`route:entity:${route.model}`, async () => {
362
- const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);
363
- for (const { name, value } of route.customHeaders) {
364
- response.headers.set(name, value);
365
- }
366
- return response;
367
- })
368
- );
369
- }
370
- });
385
+ return createBoundRoutingMiddleware(this, routes, options?.exclude, options?.resolveRoutePath);
386
+ };
387
+ createAssetsMiddleware = (options) => {
388
+ return createBoundAssetsMiddleware(this, options);
389
+ };
390
+ // --- ALS run ---
391
+ [runRequest](ctx, fn) {
392
+ return this._als.run(ctx, fn);
393
+ }
394
+ };
395
+ function createContello(options) {
396
+ return new Contello(options);
371
397
  }
372
398
  export {
373
399
  Contello,
374
- createAssetsMiddleware,
375
- createContello,
376
- createRoutingMiddleware
400
+ createContello
377
401
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contello/astro",
3
- "version": "2.0.0",
3
+ "version": "2.2.0",
4
4
  "description": "Astro integration for Contello CMS — route middleware and i18n bridge",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -14,9 +14,9 @@
14
14
  "@astroscope/excludes": ">=0.1.0",
15
15
  "@astroscope/i18n": ">=0.3.0",
16
16
  "astro": "^6.0.0",
17
- "@contello/client": "^2.0.0",
18
- "@contello/media": "^1.0.1",
19
- "@contello/store": "^2.0.0"
17
+ "@contello/client": "^2.2.0",
18
+ "@contello/store": "^2.1.0",
19
+ "@contello/media": "^1.0.1"
20
20
  },
21
21
  "peerDependenciesMeta": {
22
22
  "@astroscope/i18n": {
@@ -27,9 +27,9 @@
27
27
  "@astroscope/excludes": "^0.3.2",
28
28
  "@astroscope/i18n": "^0.4.5",
29
29
  "astro": "^6.1.8",
30
- "@contello/client": "^2.0.0",
31
- "@contello/media": "^1.0.1",
32
- "@contello/store": "^2.0.0"
30
+ "@contello/client": "^2.2.0",
31
+ "@contello/store": "^2.1.0",
32
+ "@contello/media": "^1.0.1"
33
33
  },
34
34
  "files": [
35
35
  "dist"