@contello/astro 1.4.2 → 2.1.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,202 @@ 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) {
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 lookup = routes.getByPath(url.pathname);
173
+ return (0, import_store.maybeThen)(lookup, (route) => {
174
+ if (!route) {
175
+ return contello[runRequest]({ url, route: void 0, rewritten: false }, () => next());
176
+ }
177
+ switch (route.type) {
178
+ case "redirect":
179
+ return contello[runRequest](
180
+ { url, route, rewritten: false },
181
+ () => wrap(
182
+ "route:redirect",
183
+ () => new Response(null, {
184
+ status: route.status,
185
+ headers: {
186
+ Location: route.location,
187
+ ...customHeaders(route.customHeaders)
188
+ }
189
+ })
190
+ )
191
+ );
192
+ case "text":
193
+ return contello[runRequest](
194
+ { url, route, rewritten: false },
195
+ () => wrap(
196
+ "route:text",
197
+ () => new Response(route.content, {
198
+ status: 200,
199
+ headers: {
200
+ "Content-Type": route.mimeType,
201
+ ...customHeaders(route.customHeaders)
202
+ }
203
+ })
204
+ )
205
+ );
206
+ case "asset":
207
+ return contello[runRequest](
208
+ { url, route, rewritten: false },
209
+ () => wrap("route:asset", async () => {
210
+ const result = await contello.client.download(route.fileId);
211
+ const headers = new Headers({ "content-type": result.mimeType });
212
+ if (result.size) {
213
+ headers.set("content-length", String(result.size));
214
+ }
215
+ for (const { name, value } of route.customHeaders) {
216
+ headers.set(name, value);
217
+ }
218
+ return new Response(result.stream(), { headers });
219
+ })
220
+ );
221
+ case "entity":
222
+ return contello[runRequest](
223
+ { url, route, rewritten: true },
224
+ () => wrap(`route:entity:${route.model}`, async () => {
225
+ const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);
226
+ for (const { name, value } of route.customHeaders) {
227
+ response.headers.set(name, value);
228
+ }
229
+ return response;
230
+ })
231
+ );
232
+ }
233
+ });
234
+ });
235
+ }
236
+
237
+ // src/contello.ts
45
238
  var DEFAULT_IMAGES_PREFIX = "/_contello/i/";
46
239
  var DEFAULT_FILES_PREFIX = "/_contello/f/";
47
240
  var DEFAULT_VIDEO_PREFIX = "/_contello/v/";
@@ -83,16 +276,16 @@ async function applyTranslations(messages) {
83
276
  var Contello = class {
84
277
  _store;
85
278
  _options;
86
- _assets;
87
- _routes;
88
279
  _i18nMessages;
89
- _i18nSubscription;
280
+ _i18nUnsubscribe;
90
281
  _initialized = false;
91
282
  _als = new import_node_async_hooks.AsyncLocalStorage();
283
+ _autoEagerRoutes;
284
+ _autoLazyRoutes;
92
285
  media;
93
286
  constructor(options) {
94
287
  this._options = options;
95
- this._store = (0, import_store.createStore)(options);
288
+ this._store = (0, import_store2.createStore)(options);
96
289
  this.media = {
97
290
  baseUrl: options.media?.baseUrl ?? "",
98
291
  imagesPath: options.media?.imagesPath ?? DEFAULT_IMAGES_PREFIX,
@@ -104,12 +297,10 @@ var Contello = class {
104
297
  async init(options) {
105
298
  try {
106
299
  await this._store.init();
107
- this._assets = this._store.defineAssets(this._options.assets);
108
- this._routes = this._store.defineRoutes(this._options.routes);
109
300
  if (this._options.i18n) {
110
- const { collection, languages } = this._options.i18n;
301
+ const { collection, languages, cache } = this._options.i18n;
111
302
  const { register = true, load = true } = options?.i18n ?? {};
112
- this._i18nMessages = this._store.defineI18nMessages({ collection });
303
+ this._i18nMessages = this._store.defineI18nMessages({ collection, cache });
113
304
  await import_i18n.i18n.configure({ locales: languages });
114
305
  if (register) {
115
306
  const registrations = buildI18nRegistrations();
@@ -120,12 +311,20 @@ var Contello = class {
120
311
  if (load) {
121
312
  await applyTranslations(this._i18nMessages);
122
313
  const messages = this._i18nMessages;
123
- this._i18nSubscription = messages.refresh$.subscribe(() => applyTranslations(messages));
314
+ const controller = new AbortController();
315
+ this._i18nUnsubscribe = () => controller.abort();
316
+ void (async () => {
317
+ for await (const _ of messages.refresh$) {
318
+ if (controller.signal.aborted) {
319
+ return;
320
+ }
321
+ await applyTranslations(messages);
322
+ }
323
+ })();
124
324
  }
125
325
  }
126
- if (options?.load) {
127
- await Promise.all(options.load.map((l) => l.load()));
128
- }
326
+ const loadables = [...options?.load ?? [], ...this._autoEagerRoutes ? [this._autoEagerRoutes] : []];
327
+ await Promise.all(loadables.map((l) => l.load()));
129
328
  this._initialized = true;
130
329
  } catch (err) {
131
330
  await this.destroy().catch(() => {
@@ -135,11 +334,9 @@ var Contello = class {
135
334
  }
136
335
  async destroy() {
137
336
  this._initialized = false;
138
- this._i18nSubscription?.unsubscribe();
139
- this._i18nSubscription = void 0;
337
+ this._i18nUnsubscribe?.();
338
+ this._i18nUnsubscribe = void 0;
140
339
  await this._store.destroy();
141
- this._assets = void 0;
142
- this._routes = void 0;
143
340
  this._i18nMessages = void 0;
144
341
  }
145
342
  ping() {
@@ -148,18 +345,8 @@ var Contello = class {
148
345
  get isReady() {
149
346
  return this._initialized;
150
347
  }
151
- // --- pre-wired collections ---
152
- get assets() {
153
- if (!this._assets) {
154
- throw new Error("@contello/astro: .assets accessed before init()");
155
- }
156
- return this._assets;
157
- }
158
- get routes() {
159
- if (!this._routes) {
160
- throw new Error("@contello/astro: .routes accessed before init()");
161
- }
162
- return this._routes;
348
+ get client() {
349
+ return this._store.client;
163
350
  }
164
351
  get i18nMessages() {
165
352
  if (!this._i18nMessages) {
@@ -183,224 +370,65 @@ var Contello = class {
183
370
  });
184
371
  }
185
372
  // --- store delegation ---
186
- defineSingleton(def) {
187
- return this._store.defineSingleton(def);
373
+ defineSingleton(sourceOrKey, options) {
374
+ return this._store.defineSingleton(sourceOrKey, options);
188
375
  }
189
- defineSingletonSync(def) {
190
- return this._store.defineSingletonSync(def);
376
+ defineSingletonSync(sourceOrKey, options) {
377
+ return this._store.defineSingletonSync(sourceOrKey, options);
191
378
  }
192
- defineCollection(def) {
193
- return this._store.defineCollection(def);
379
+ defineCollection(sourceOrKey, options) {
380
+ return this._store.defineCollection(sourceOrKey, options);
194
381
  }
195
- defineCollectionSync(def) {
196
- return this._store.defineCollectionSync(def);
382
+ defineCollectionSync(sourceOrKey, options) {
383
+ return this._store.defineCollectionSync(sourceOrKey, options);
197
384
  }
198
- defineLazyCollection(def) {
199
- return this._store.defineLazyCollection(def);
385
+ defineLazyCollection(sourceOrKey, options) {
386
+ return this._store.defineLazyCollection(sourceOrKey, options);
200
387
  }
201
- // --- ALS run ---
202
- [runRequest](ctx, fn) {
203
- return this._als.run(ctx, fn);
388
+ defineRoutes(options) {
389
+ return this._store.defineRoutes(options);
204
390
  }
205
- };
206
- function createContello(options) {
207
- return new Contello(options);
208
- }
209
-
210
- // src/assets-middleware.ts
211
- var import_middleware = require("astro/middleware");
212
-
213
- // src/diagnostics.ts
214
- var import_node_diagnostics_channel = __toESM(require("diagnostics_channel"), 1);
215
- var channels = {
216
- start: "@contello/astro:start",
217
- end: "@contello/astro:end",
218
- error: "@contello/astro:error"
219
- };
220
- var onStart = import_node_diagnostics_channel.default.channel(channels.start);
221
- var onEnd = import_node_diagnostics_channel.default.channel(channels.end);
222
- var onError = import_node_diagnostics_channel.default.channel(channels.error);
223
- function hasSubscribers() {
224
- return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
225
- }
226
- function wrap(name, fn) {
227
- if (!hasSubscribers()) {
228
- return fn();
391
+ defineRoutesSync(options) {
392
+ return this._store.defineRoutesSync(options);
229
393
  }
230
- const start = performance.now();
231
- onStart.publish({ name });
232
- let result;
233
- try {
234
- result = fn();
235
- } catch (error) {
236
- onError.publish({ name, error, durationMs: performance.now() - start });
237
- throw error;
238
- }
239
- if (result instanceof Promise) {
240
- return result.then(
241
- (r) => {
242
- onEnd.publish({ name, durationMs: performance.now() - start });
243
- return r;
244
- },
245
- (error) => {
246
- onError.publish({ name, error, durationMs: performance.now() - start });
247
- throw error;
248
- }
249
- );
394
+ defineLazyRoutes(options) {
395
+ return this._store.defineLazyRoutes(options);
250
396
  }
251
- onEnd.publish({ name, durationMs: performance.now() - start });
252
- return result;
253
- }
254
-
255
- // src/assets-middleware.ts
256
- var DEFAULT_IMAGES_CACHE_CONTROL = "public, max-age=31536000";
257
- function createAssetsMiddleware(instance, options) {
258
- const imagesPrefix = instance.media.imagesPath;
259
- const imagesCacheControl = options?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL;
260
- const filesPrefix = instance.media.filesPath;
261
- const filesCacheControl = options?.files?.cacheControl;
262
- const videoPrefix = instance.media.videosPath;
263
- return (0, import_middleware.defineMiddleware)((ctx, next) => {
264
- const { pathname } = ctx.url;
265
- const isImage = pathname.startsWith(imagesPrefix);
266
- const isFile = !isImage && pathname.startsWith(filesPrefix);
267
- const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);
268
- if (!isImage && !isFile && !isVideo) {
269
- return next();
270
- }
271
- if (!instance.isReady) {
272
- console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);
273
- return next();
274
- }
275
- if (isImage) {
276
- return handleFile(instance, next, pathname.slice(imagesPrefix.length), imagesCacheControl);
277
- }
278
- if (isFile) {
279
- return handleFile(instance, next, pathname.slice(filesPrefix.length), filesCacheControl);
280
- }
281
- return handleVideo(instance, next, pathname.slice(videoPrefix.length), ctx.request.signal);
282
- });
283
- }
284
- function handleFile(instance, next, rest, cacheControl) {
285
- const dot = rest.indexOf(".");
286
- const fileId = dot === -1 ? rest : rest.slice(0, dot);
287
- if (!fileId) {
288
- return next();
397
+ defineAssets(options) {
398
+ return this._store.defineAssets(options);
289
399
  }
290
- return wrap("assets:file", () => instance.assets.download(fileId)).then(
291
- (result) => {
292
- const headers = new Headers({ "content-type": result.mimeType });
293
- if (cacheControl) {
294
- headers.set("cache-control", cacheControl);
295
- }
296
- if (result.size) {
297
- headers.set("content-length", String(result.size));
298
- }
299
- return new Response(result.stream(), { headers });
300
- },
301
- () => new Response(null, { status: 404 })
302
- );
303
- }
304
- function handleVideo(instance, next, path, signal) {
305
- if (!path) {
306
- return next();
400
+ defineAssetsSync(options) {
401
+ return this._store.defineAssetsSync(options);
307
402
  }
308
- return wrap("assets:hls", () => instance.assets.proxyHls(path, signal)).then(
309
- (result) => new Response(result.stream(), { status: result.status, headers: result.headers }),
310
- () => new Response("Upstream is down", { status: 502, headers: { "content-type": "text/plain" } })
311
- );
312
- }
313
-
314
- // src/routing-middleware.ts
315
- var import_excludes = require("@astroscope/excludes");
316
- var import_middleware2 = require("astro/middleware");
317
- function customHeaders(headers) {
318
- const result = {};
319
- for (const h of headers) {
320
- result[h.name] = h.value;
403
+ defineLazyAssets(options) {
404
+ return this._store.defineLazyAssets(options);
321
405
  }
322
- return result;
323
- }
324
- function createRoutingMiddleware(instance, options) {
325
- const { exclude } = options ?? {};
326
- return (0, import_middleware2.defineMiddleware)(async (ctx, next) => {
327
- if ((0, import_excludes.shouldExclude)(ctx, exclude ?? import_excludes.RECOMMENDED_EXCLUDES)) {
328
- return next();
329
- }
330
- if (!instance.isReady) {
331
- console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
332
- return next();
333
- }
334
- const { url } = ctx;
335
- if (url.pathname.startsWith("/contello/entities/")) {
336
- return instance[runRequest]({ url, route: void 0, rewritten: false }, () => next());
337
- }
338
- const route = await instance.routes.getByPath(url.pathname);
339
- if (!route) {
340
- return instance[runRequest]({ url, route: void 0, rewritten: false }, () => next());
406
+ // --- middleware factories (arrow fields so destructuring works) ---
407
+ createRoutingMiddleware = (options) => {
408
+ const routesOption = options?.routes ?? "eager";
409
+ let routes;
410
+ if (routesOption === "eager") {
411
+ routes = this._autoEagerRoutes ??= this.defineRoutesSync();
412
+ } else if (routesOption === "lazy") {
413
+ routes = this._autoLazyRoutes ??= this.defineLazyRoutes();
414
+ } else {
415
+ routes = routesOption;
341
416
  }
342
- switch (route.type) {
343
- case "redirect":
344
- return instance[runRequest](
345
- { url, route, rewritten: false },
346
- () => wrap(
347
- "route:redirect",
348
- () => new Response(null, {
349
- status: route.status,
350
- headers: {
351
- Location: route.location,
352
- ...customHeaders(route.customHeaders)
353
- }
354
- })
355
- )
356
- );
357
- case "text":
358
- return instance[runRequest](
359
- { url, route, rewritten: false },
360
- () => wrap(
361
- "route:text",
362
- () => new Response(route.content, {
363
- status: 200,
364
- headers: {
365
- "Content-Type": route.mimeType,
366
- ...customHeaders(route.customHeaders)
367
- }
368
- })
369
- )
370
- );
371
- case "asset":
372
- return instance[runRequest](
373
- { url, route, rewritten: false },
374
- () => wrap("route:asset", async () => {
375
- const result = await instance.assets.download(route.fileId);
376
- const headers = new Headers({ "content-type": result.mimeType });
377
- if (result.size) {
378
- headers.set("content-length", String(result.size));
379
- }
380
- for (const { name, value } of route.customHeaders) {
381
- headers.set(name, value);
382
- }
383
- return new Response(result.stream(), { headers });
384
- })
385
- );
386
- case "entity":
387
- return instance[runRequest](
388
- { url, route, rewritten: true },
389
- () => wrap(`route:entity:${route.model}`, async () => {
390
- const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);
391
- for (const { name, value } of route.customHeaders) {
392
- response.headers.set(name, value);
393
- }
394
- return response;
395
- })
396
- );
397
- }
398
- });
417
+ return createBoundRoutingMiddleware(this, routes, options?.exclude);
418
+ };
419
+ createAssetsMiddleware = (options) => {
420
+ return createBoundAssetsMiddleware(this, options);
421
+ };
422
+ // --- ALS run ---
423
+ [runRequest](ctx, fn) {
424
+ return this._als.run(ctx, fn);
425
+ }
426
+ };
427
+ function createContello(options) {
428
+ return new Contello(options);
399
429
  }
400
430
  // Annotate the CommonJS export names for ESM import in node:
401
431
  0 && (module.exports = {
402
432
  Contello,
403
- createAssetsMiddleware,
404
- createContello,
405
- createRoutingMiddleware
433
+ createContello
406
434
  });