@contello/astro 3.1.0 → 3.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
@@ -1,434 +1,324 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- Contello: () => Contello,
34
- createContello: () => createContello
35
- });
36
- module.exports = __toCommonJS(index_exports);
37
-
38
- // src/contello.ts
39
- var import_node_async_hooks = require("async_hooks");
40
- var import_i18n = require("@astroscope/i18n");
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";
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let node_async_hooks = require("node:async_hooks");
3
+ let _astroscope_i18n = require("@astroscope/i18n");
4
+ let _contello_media = require("@contello/media");
5
+ let _contello_store = require("@contello/store");
6
+ let astro_middleware = require("astro/middleware");
7
+ let _contello_opentelemetry = require("@contello/opentelemetry");
8
+ let _astroscope_excludes = require("@astroscope/excludes");
9
+ //#region src/telemetry.ts
10
+ const { wrap } = (0, _contello_opentelemetry.createOperationTelemetry)("@contello/astro");
11
+ //#endregion
12
+ //#region src/assets-middleware.ts
13
+ const DEFAULT_IMAGES_CACHE_CONTROL = "public, max-age=31536000";
91
14
  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
- });
15
+ const imagesPrefix = contello.media.imagesPath;
16
+ const imagesCacheControl = options?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL;
17
+ const filesPrefix = contello.media.filesPath;
18
+ const filesCacheControl = options?.files?.cacheControl;
19
+ const videoPrefix = contello.media.videosPath;
20
+ return (0, astro_middleware.defineMiddleware)((ctx, next) => {
21
+ const { pathname } = ctx.url;
22
+ const isImage = pathname.startsWith(imagesPrefix);
23
+ const isFile = !isImage && pathname.startsWith(filesPrefix);
24
+ const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);
25
+ if (!isImage && !isFile && !isVideo) return next();
26
+ if (!contello.isReady) {
27
+ console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);
28
+ return next();
29
+ }
30
+ if (isImage) return handleFile(contello.client, next, pathname.slice(imagesPrefix.length), imagesCacheControl);
31
+ if (isFile) return handleFile(contello.client, next, pathname.slice(filesPrefix.length), filesCacheControl);
32
+ return handleVideo(contello.client, next, pathname.slice(videoPrefix.length), ctx.request.signal);
33
+ });
117
34
  }
118
35
  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 > 0) {
131
- headers.set("content-length", String(result.size));
132
- }
133
- return new Response(result.stream(), { headers });
134
- },
135
- () => new Response(null, { status: 404 })
136
- );
36
+ const dot = rest.indexOf(".");
37
+ const fileId = dot === -1 ? rest : rest.slice(0, dot);
38
+ if (!fileId) return next();
39
+ return (async () => {
40
+ try {
41
+ const result = await wrap("assets:file", () => client.download(fileId));
42
+ const headers = new Headers({ "content-type": result.mimeType });
43
+ if (cacheControl) headers.set("cache-control", cacheControl);
44
+ if (result.size > 0) headers.set("content-length", String(result.size));
45
+ return new Response(result.stream(), { headers });
46
+ } catch {
47
+ return new Response(null, { status: 404 });
48
+ }
49
+ })();
137
50
  }
138
51
  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
- );
52
+ if (!path) return next();
53
+ return (async () => {
54
+ try {
55
+ const result = await wrap("assets:hls", () => client.proxyHls(path, signal));
56
+ return new Response(result.stream(), {
57
+ status: result.status,
58
+ headers: result.headers
59
+ });
60
+ } catch {
61
+ return new Response("Upstream is down", {
62
+ status: 502,
63
+ headers: { "content-type": "text/plain" }
64
+ });
65
+ }
66
+ })();
146
67
  }
147
-
148
- // src/routing-middleware.ts
149
- var import_excludes = require("@astroscope/excludes");
150
- var import_store = require("@contello/store");
151
- var import_middleware2 = require("astro/middleware");
68
+ //#endregion
69
+ //#region src/routing-middleware.ts
152
70
  function customHeaders(headers) {
153
- const result = {};
154
- for (const h of headers) {
155
- result[h.name] = h.value;
156
- }
157
- return result;
71
+ const result = {};
72
+ for (const h of headers) result[h.name] = h.value;
73
+ return result;
158
74
  }
159
- var VALID_REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
75
+ const VALID_REDIRECT_STATUSES = /* @__PURE__ */ new Set([
76
+ 301,
77
+ 302,
78
+ 303,
79
+ 307,
80
+ 308
81
+ ]);
160
82
  function toRedirectStatus(status) {
161
- return VALID_REDIRECT_STATUSES.has(status) ? status : 302;
83
+ return VALID_REDIRECT_STATUSES.has(status) ? status : 302;
162
84
  }
163
85
  function createBoundRoutingMiddleware(contello, routes, exclude, resolveRoutePath) {
164
- return (0, import_middleware2.defineMiddleware)((ctx, next) => {
165
- if ((0, import_excludes.shouldExclude)(ctx, exclude ?? import_excludes.RECOMMENDED_EXCLUDES)) {
166
- return next();
167
- }
168
- if (!contello.isReady) {
169
- console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
170
- return next();
171
- }
172
- const { url } = ctx;
173
- if (url.pathname.startsWith("/contello/entities/")) {
174
- return contello[runRequest]({ url, route: void 0, rewritten: false }, () => next());
175
- }
176
- const path = resolveRoutePath ? resolveRoutePath(ctx) : url.pathname;
177
- const lookup = routes.getByPath(path);
178
- return (0, import_store.maybeThen)(lookup, (route) => {
179
- if (!route) {
180
- return contello[runRequest]({ url, route: void 0, rewritten: false }, () => next());
181
- }
182
- switch (route.type) {
183
- case "redirect": {
184
- return contello[runRequest](
185
- { url, route, rewritten: false },
186
- () => wrap(
187
- "route:redirect",
188
- () => new Response(null, {
189
- status: toRedirectStatus(route.status),
190
- headers: {
191
- Location: route.location,
192
- ...customHeaders(route.customHeaders)
193
- }
194
- })
195
- )
196
- );
197
- }
198
- case "text": {
199
- return contello[runRequest](
200
- { url, route, rewritten: false },
201
- () => wrap(
202
- "route:text",
203
- () => new Response(route.content, {
204
- status: 200,
205
- headers: {
206
- "Content-Type": route.mimeType,
207
- ...customHeaders(route.customHeaders)
208
- }
209
- })
210
- )
211
- );
212
- }
213
- case "asset": {
214
- return contello[runRequest](
215
- { url, route, rewritten: false },
216
- () => wrap("route:asset", async () => {
217
- const result = await contello.client.download(route.fileId);
218
- const headers = new Headers({ "content-type": route.mimeType || result.mimeType });
219
- headers.set("content-disposition", route.contentDisposition);
220
- if (result.size > 0) {
221
- headers.set("content-length", String(result.size));
222
- }
223
- for (const { name, value } of route.customHeaders) {
224
- headers.set(name, value);
225
- }
226
- return new Response(result.stream(), { headers });
227
- })
228
- );
229
- }
230
- case "entity": {
231
- return contello[runRequest](
232
- { url, route, rewritten: true },
233
- () => wrap(`route:entity:${route.model}`, async () => {
234
- const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);
235
- for (const { name, value } of route.customHeaders) {
236
- response.headers.set(name, value);
237
- }
238
- return response;
239
- })
240
- );
241
- }
242
- }
243
- });
244
- });
86
+ return (0, astro_middleware.defineMiddleware)((ctx, next) => {
87
+ if ((0, _astroscope_excludes.shouldExclude)(ctx, exclude ?? _astroscope_excludes.RECOMMENDED_EXCLUDES)) return next();
88
+ if (!contello.isReady) {
89
+ console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
90
+ return next();
91
+ }
92
+ const { url } = ctx;
93
+ if (url.pathname.startsWith("/contello/entities/")) return contello[runRequest]({
94
+ url,
95
+ route: void 0,
96
+ rewritten: false
97
+ }, () => next());
98
+ const path = resolveRoutePath ? resolveRoutePath(ctx) : url.pathname;
99
+ return (0, _contello_store.maybeThen)(routes.getByPath(path), (route) => {
100
+ if (!route) return contello[runRequest]({
101
+ url,
102
+ route: void 0,
103
+ rewritten: false
104
+ }, () => next());
105
+ switch (route.type) {
106
+ case "redirect": return contello[runRequest]({
107
+ url,
108
+ route,
109
+ rewritten: false
110
+ }, () => wrap("route:redirect", () => new Response(null, {
111
+ status: toRedirectStatus(route.status),
112
+ headers: {
113
+ Location: route.location,
114
+ ...customHeaders(route.customHeaders)
115
+ }
116
+ })));
117
+ case "text": return contello[runRequest]({
118
+ url,
119
+ route,
120
+ rewritten: false
121
+ }, () => wrap("route:text", () => new Response(route.content, {
122
+ status: 200,
123
+ headers: {
124
+ "Content-Type": route.mimeType,
125
+ ...customHeaders(route.customHeaders)
126
+ }
127
+ })));
128
+ case "asset": return contello[runRequest]({
129
+ url,
130
+ route,
131
+ rewritten: false
132
+ }, () => wrap("route:asset", async () => {
133
+ const result = await contello.client.download(route.fileId);
134
+ const headers = new Headers({ "content-type": route.mimeType || result.mimeType });
135
+ headers.set("content-disposition", route.contentDisposition);
136
+ if (result.size > 0) headers.set("content-length", String(result.size));
137
+ for (const { name, value } of route.customHeaders) headers.set(name, value);
138
+ return new Response(result.stream(), { headers });
139
+ }));
140
+ case "entity": return contello[runRequest]({
141
+ url,
142
+ route,
143
+ rewritten: true
144
+ }, () => wrap(`route:entity:${route.model}`, async () => {
145
+ const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);
146
+ for (const { name, value } of route.customHeaders) response.headers.set(name, value);
147
+ return response;
148
+ }));
149
+ }
150
+ });
151
+ });
245
152
  }
246
-
247
- // src/contello.ts
248
- var DEFAULT_IMAGES_PREFIX = "/_contello/i/";
249
- var DEFAULT_FILES_PREFIX = "/_contello/f/";
250
- var DEFAULT_VIDEO_PREFIX = "/_contello/v/";
251
- var runRequest = /* @__PURE__ */ Symbol("@contello/astro/runRequest");
153
+ //#endregion
154
+ //#region src/contello.ts
155
+ const DEFAULT_IMAGES_PREFIX = "/_contello/i/";
156
+ const DEFAULT_FILES_PREFIX = "/_contello/f/";
157
+ const DEFAULT_VIDEO_PREFIX = "/_contello/v/";
158
+ const runRequest = Symbol("@contello/astro/runRequest");
252
159
  function buildI18nRegistrations() {
253
- const manifest = import_i18n.i18n.getManifest();
254
- const defaultLanguage = import_i18n.i18n.getConfig().defaultLocale;
255
- return manifest.keys.map((extracted) => ({
256
- token: extracted.key,
257
- example: extracted.meta.fallback,
258
- description: extracted.meta.description ?? "",
259
- variables: Object.entries(extracted.meta.variables ?? {}).map(([name, def]) => ({
260
- name,
261
- description: def?.description ?? "",
262
- example: def?.fallback ?? ""
263
- })),
264
- initialTranslations: [{ language: defaultLanguage, message: extracted.meta.fallback }]
265
- }));
160
+ const manifest = _astroscope_i18n.i18n.getManifest();
161
+ const defaultLanguage = _astroscope_i18n.i18n.getConfig().defaultLocale;
162
+ return manifest.keys.map((extracted) => ({
163
+ token: extracted.key,
164
+ example: extracted.meta.fallback,
165
+ description: extracted.meta.description ?? "",
166
+ variables: Object.entries(extracted.meta.variables ?? {}).map(([name, def]) => ({
167
+ name,
168
+ description: def?.description ?? "",
169
+ example: def?.fallback ?? ""
170
+ })),
171
+ initialTranslations: [{
172
+ language: defaultLanguage,
173
+ message: extracted.meta.fallback
174
+ }]
175
+ }));
266
176
  }
267
177
  async function applyTranslations(messages) {
268
- const config = import_i18n.i18n.getConfig();
269
- const all = await messages.getAll();
270
- const byLocale = /* @__PURE__ */ new Map();
271
- for (const locale of config.locales) {
272
- byLocale.set(locale, {});
273
- }
274
- for (const msg of all) {
275
- msg.translations.forEach((value, language) => {
276
- const raw = byLocale.get(language);
277
- if (raw) {
278
- raw[msg.token] = value;
279
- }
280
- });
281
- }
282
- for (const [locale, translations] of byLocale.entries()) {
283
- import_i18n.i18n.setTranslations(locale, translations);
284
- }
178
+ const config = _astroscope_i18n.i18n.getConfig();
179
+ const all = await messages.getAll();
180
+ const byLocale = /* @__PURE__ */ new Map();
181
+ for (const locale of config.locales) byLocale.set(locale, {});
182
+ for (const msg of all) msg.translations.forEach((value, language) => {
183
+ const raw = byLocale.get(language);
184
+ if (raw) raw[msg.token] = value;
185
+ });
186
+ for (const [locale, translations] of byLocale) _astroscope_i18n.i18n.setTranslations(locale, translations);
285
187
  }
286
188
  var Contello = class {
287
- _store;
288
- _options;
289
- _i18nMessages;
290
- _i18nUnsubscribe;
291
- _initialized = false;
292
- _als = new import_node_async_hooks.AsyncLocalStorage();
293
- _autoLazyRoutes;
294
- media;
295
- constructor(options) {
296
- this._options = options;
297
- this._store = (0, import_store2.createStore)(options);
298
- this.media = {
299
- baseUrl: options.media?.baseUrl ?? "",
300
- imagesPath: options.media?.imagesPath ?? DEFAULT_IMAGES_PREFIX,
301
- videosPath: options.media?.videosPath ?? DEFAULT_VIDEO_PREFIX,
302
- filesPath: options.media?.filesPath ?? DEFAULT_FILES_PREFIX
303
- };
304
- }
305
- // --- lifecycle ---
306
- async init(options) {
307
- try {
308
- await this._store.init();
309
- if (this._options.i18n) {
310
- const { collection, languages, cache } = this._options.i18n;
311
- const { register = true, load = true } = options?.i18n ?? {};
312
- this._i18nMessages = this._store.defineI18nMessages({ collection, cache });
313
- await import_i18n.i18n.configure({ locales: languages });
314
- if (register) {
315
- const registrations = buildI18nRegistrations();
316
- if (registrations.length > 0) {
317
- await this._i18nMessages.register(registrations);
318
- }
319
- }
320
- if (load) {
321
- await applyTranslations(this._i18nMessages);
322
- const messages = this._i18nMessages;
323
- const controller = new AbortController();
324
- this._i18nUnsubscribe = () => controller.abort();
325
- void (async () => {
326
- for await (const _ of messages.refresh$) {
327
- if (controller.signal.aborted) {
328
- return;
329
- }
330
- await applyTranslations(messages);
331
- }
332
- })();
333
- }
334
- }
335
- await Promise.all((options?.load ?? []).map((l) => l.load()));
336
- this._initialized = true;
337
- } catch (error) {
338
- await this.destroy().catch(() => {
339
- });
340
- throw error;
341
- }
342
- }
343
- async destroy() {
344
- this._initialized = false;
345
- this._i18nUnsubscribe?.();
346
- this._i18nUnsubscribe = void 0;
347
- await this._store.destroy();
348
- this._i18nMessages = void 0;
349
- }
350
- ping() {
351
- return this._store.ping();
352
- }
353
- get isReady() {
354
- return this._initialized;
355
- }
356
- get client() {
357
- return this._store.client;
358
- }
359
- get i18nMessages() {
360
- if (!this._i18nMessages) {
361
- throw new Error("@contello/astro: .i18nMessages accessed before init() with i18n config");
362
- }
363
- return this._i18nMessages;
364
- }
365
- // --- ALS request context ---
366
- get request() {
367
- const ctx = this._als.getStore();
368
- if (!ctx) {
369
- throw new Error("@contello/astro: .request accessed outside of request context");
370
- }
371
- return ctx;
372
- }
373
- // --- media resolvers (on-demand) ---
374
- defineMediaResolver(options) {
375
- return (0, import_media.createMediaResolver)({
376
- ...this.media,
377
- ...options
378
- });
379
- }
380
- // --- store delegation ---
381
- defineSingleton(sourceOrKey, options) {
382
- return this._store.defineSingleton(sourceOrKey, options);
383
- }
384
- defineSingletonSync(sourceOrKey, options) {
385
- return this._store.defineSingletonSync(sourceOrKey, options);
386
- }
387
- defineCollection(sourceOrKey, options) {
388
- return this._store.defineCollection(sourceOrKey, options);
389
- }
390
- defineCollectionSync(sourceOrKey, options) {
391
- return this._store.defineCollectionSync(sourceOrKey, options);
392
- }
393
- defineLazyCollection(sourceOrKey, options) {
394
- return this._store.defineLazyCollection(sourceOrKey, options);
395
- }
396
- defineRoutes(options) {
397
- return this._store.defineRoutes(options);
398
- }
399
- defineRoutesSync(options) {
400
- return this._store.defineRoutesSync(options);
401
- }
402
- defineLazyRoutes(options) {
403
- return this._store.defineLazyRoutes(options);
404
- }
405
- defineAssets(options) {
406
- return this._store.defineAssets(options);
407
- }
408
- defineAssetsSync(options) {
409
- return this._store.defineAssetsSync(options);
410
- }
411
- defineLazyAssets(options) {
412
- return this._store.defineLazyAssets(options);
413
- }
414
- // --- middleware factories (arrow fields so destructuring works) ---
415
- createRoutingMiddleware = (options) => {
416
- const routes = options?.routes ?? (this._autoLazyRoutes ??= this.defineLazyRoutes());
417
- return createBoundRoutingMiddleware(this, routes, options?.exclude, options?.resolveRoutePath);
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
- }
189
+ _store;
190
+ _options;
191
+ _i18nMessages;
192
+ _i18nUnsubscribe;
193
+ _initialized = false;
194
+ _als = new node_async_hooks.AsyncLocalStorage();
195
+ _autoLazyRoutes;
196
+ media;
197
+ createRoutingMiddleware = (options) => {
198
+ const routes = options?.routes ?? (this._autoLazyRoutes ??= this.defineLazyRoutes());
199
+ return createBoundRoutingMiddleware(this, routes, options?.exclude, options?.resolveRoutePath);
200
+ };
201
+ createAssetsMiddleware = (options) => {
202
+ return createBoundAssetsMiddleware(this, options);
203
+ };
204
+ constructor(options) {
205
+ this._options = options;
206
+ this._store = (0, _contello_store.createStore)(options);
207
+ this.media = {
208
+ baseUrl: options.media?.baseUrl ?? "",
209
+ imagesPath: options.media?.imagesPath ?? DEFAULT_IMAGES_PREFIX,
210
+ videosPath: options.media?.videosPath ?? DEFAULT_VIDEO_PREFIX,
211
+ filesPath: options.media?.filesPath ?? DEFAULT_FILES_PREFIX
212
+ };
213
+ }
214
+ async init(options) {
215
+ try {
216
+ await this._store.init();
217
+ if (this._options.i18n) {
218
+ const { collection, languages, cache } = this._options.i18n;
219
+ const { register = true, load = true } = options?.i18n ?? {};
220
+ this._i18nMessages = this._store.defineI18nMessages({
221
+ collection,
222
+ cache
223
+ });
224
+ await _astroscope_i18n.i18n.configure({ locales: languages });
225
+ if (register) {
226
+ const registrations = buildI18nRegistrations();
227
+ if (registrations.length > 0) await this._i18nMessages.register(registrations);
228
+ }
229
+ if (load) {
230
+ await applyTranslations(this._i18nMessages);
231
+ const messages = this._i18nMessages;
232
+ const controller = new AbortController();
233
+ this._i18nUnsubscribe = () => controller.abort();
234
+ (async () => {
235
+ for await (const _ of messages.refresh$) {
236
+ if (controller.signal.aborted) return;
237
+ await applyTranslations(messages);
238
+ }
239
+ })();
240
+ }
241
+ }
242
+ await Promise.all((options?.load ?? []).map((l) => l.load()));
243
+ this._initialized = true;
244
+ } catch (error) {
245
+ try {
246
+ await this.destroy();
247
+ } catch {}
248
+ throw error;
249
+ }
250
+ }
251
+ async destroy() {
252
+ this._initialized = false;
253
+ this._i18nUnsubscribe?.();
254
+ this._i18nUnsubscribe = void 0;
255
+ await this._store.destroy();
256
+ this._i18nMessages = void 0;
257
+ }
258
+ ping() {
259
+ return this._store.ping();
260
+ }
261
+ get isReady() {
262
+ return this._initialized;
263
+ }
264
+ get client() {
265
+ return this._store.client;
266
+ }
267
+ get i18nMessages() {
268
+ if (!this._i18nMessages) throw new Error("@contello/astro: .i18nMessages accessed before init() with i18n config");
269
+ return this._i18nMessages;
270
+ }
271
+ get request() {
272
+ const ctx = this._als.getStore();
273
+ if (!ctx) throw new Error("@contello/astro: .request accessed outside of request context");
274
+ return ctx;
275
+ }
276
+ defineMediaResolver(options) {
277
+ return (0, _contello_media.createMediaResolver)({
278
+ ...this.media,
279
+ ...options
280
+ });
281
+ }
282
+ defineSingleton(sourceOrKey, options) {
283
+ return this._store.defineSingleton(sourceOrKey, options);
284
+ }
285
+ defineSingletonSync(sourceOrKey, options) {
286
+ return this._store.defineSingletonSync(sourceOrKey, options);
287
+ }
288
+ defineCollection(sourceOrKey, options) {
289
+ return this._store.defineCollection(sourceOrKey, options);
290
+ }
291
+ defineCollectionSync(sourceOrKey, options) {
292
+ return this._store.defineCollectionSync(sourceOrKey, options);
293
+ }
294
+ defineLazyCollection(sourceOrKey, options) {
295
+ return this._store.defineLazyCollection(sourceOrKey, options);
296
+ }
297
+ defineRoutes(options) {
298
+ return this._store.defineRoutes(options);
299
+ }
300
+ defineRoutesSync(options) {
301
+ return this._store.defineRoutesSync(options);
302
+ }
303
+ defineLazyRoutes(options) {
304
+ return this._store.defineLazyRoutes(options);
305
+ }
306
+ defineAssets(options) {
307
+ return this._store.defineAssets(options);
308
+ }
309
+ defineAssetsSync(options) {
310
+ return this._store.defineAssetsSync(options);
311
+ }
312
+ defineLazyAssets(options) {
313
+ return this._store.defineLazyAssets(options);
314
+ }
315
+ [runRequest](ctx, fn) {
316
+ return this._als.run(ctx, fn);
317
+ }
426
318
  };
427
319
  function createContello(options) {
428
- return new Contello(options);
320
+ return new Contello(options);
429
321
  }
430
- // Annotate the CommonJS export names for ESM import in node:
431
- 0 && (module.exports = {
432
- Contello,
433
- createContello
434
- });
322
+ //#endregion
323
+ exports.Contello = Contello;
324
+ exports.createContello = createContello;