emdash 0.17.0 → 0.17.1
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/{apply-CgamLmed.mjs → apply-CuuZG6op.mjs} +4 -4
- package/dist/{apply-CgamLmed.mjs.map → apply-CuuZG6op.mjs.map} +1 -1
- package/dist/astro/index.mjs +10 -1
- package/dist/astro/index.mjs.map +1 -1
- package/dist/astro/middleware.mjs +6 -6
- package/dist/astro/routes/api/admin/plugins/_id_/disable.mjs +2 -2
- package/dist/astro/routes/api/admin/plugins/_id_/enable.mjs +2 -2
- package/dist/astro/routes/api/admin/plugins/_id_/index.mjs +2 -2
- package/dist/astro/routes/api/admin/plugins/_id_/uninstall.mjs +2 -2
- package/dist/astro/routes/api/admin/plugins/_id_/update.mjs +2 -2
- package/dist/astro/routes/api/admin/plugins/index.mjs +2 -2
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/index.mjs +2 -2
- package/dist/astro/routes/api/admin/plugins/marketplace/_id_/install.mjs +2 -2
- package/dist/astro/routes/api/admin/plugins/marketplace/index.mjs +2 -2
- package/dist/astro/routes/api/admin/plugins/registry/_id_/uninstall.mjs +2 -2
- package/dist/astro/routes/api/admin/plugins/registry/_id_/update.mjs +3 -3
- package/dist/astro/routes/api/admin/plugins/registry/artifact.mjs +2 -2
- package/dist/astro/routes/api/admin/plugins/registry/install.mjs +3 -3
- package/dist/astro/routes/api/admin/plugins/updates.mjs +2 -2
- package/dist/astro/routes/api/admin/themes/marketplace/_id_/index.mjs +2 -2
- package/dist/astro/routes/api/admin/themes/marketplace/index.mjs +2 -2
- package/dist/astro/routes/api/content/_collection_/_id_/terms/_taxonomy_.mjs +1 -1
- package/dist/astro/routes/api/import/wordpress/execute.mjs +1 -1
- package/dist/astro/routes/api/manifest.mjs +1 -1
- package/dist/astro/routes/api/mcp.mjs +6 -6
- package/dist/astro/routes/api/schema/collections/_slug_/fields/_fieldSlug_.mjs +2 -2
- package/dist/astro/routes/api/schema/collections/_slug_/fields/index.mjs +2 -2
- package/dist/astro/routes/api/schema/collections/_slug_/fields/reorder.mjs +2 -2
- package/dist/astro/routes/api/schema/collections/_slug_/index.mjs +2 -2
- package/dist/astro/routes/api/schema/collections/index.mjs +2 -2
- package/dist/astro/routes/api/schema/orphans/_slug_.mjs +2 -2
- package/dist/astro/routes/api/schema/orphans/index.mjs +2 -2
- package/dist/astro/routes/api/setup/dev-bypass.mjs +1 -1
- package/dist/astro/routes/api/setup/index.mjs +1 -1
- package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_/translations.mjs +2 -2
- package/dist/astro/routes/api/taxonomies/_name_/terms/_slug_.mjs +2 -2
- package/dist/astro/routes/api/taxonomies/_name_/terms/index.mjs +2 -2
- package/dist/astro/routes/api/taxonomies/index.mjs +2 -2
- package/dist/cli/index.mjs +113 -11
- package/dist/cli/index.mjs.map +1 -1
- package/dist/index.mjs +4 -4
- package/dist/{query-CuvjwhrE.mjs → query-Bt52mHXp.mjs} +9 -8
- package/dist/query-Bt52mHXp.mjs.map +1 -0
- package/dist/seed/index.mjs +1 -1
- package/dist/{taxonomies-CgpzAU6F.mjs → taxonomies-ByLlXrv5.mjs} +2 -2
- package/dist/{taxonomies-CgpzAU6F.mjs.map → taxonomies-ByLlXrv5.mjs.map} +1 -1
- package/dist/{taxonomies-D72gTOg_.mjs → taxonomies-CbO6v7EE.mjs} +2 -2
- package/dist/{taxonomies-D72gTOg_.mjs.map → taxonomies-CbO6v7EE.mjs.map} +1 -1
- package/dist/version-CWbvq9LG.mjs +7 -0
- package/dist/{version-FGcv0ooe.mjs.map → version-CWbvq9LG.mjs.map} +1 -1
- package/package.json +6 -6
- package/src/astro/integration/vite-config.ts +16 -0
- package/src/cli/commands/export-seed.ts +174 -12
- package/src/query.ts +7 -7
- package/dist/query-CuvjwhrE.mjs.map +0 -1
- package/dist/version-FGcv0ooe.mjs +0 -7
|
@@ -395,10 +395,25 @@ export function createViteConfig(
|
|
|
395
395
|
"emdash > @emdash-cms/auth > @oslojs/crypto/ecdsa",
|
|
396
396
|
"emdash > @emdash-cms/auth > @oslojs/crypto/sha2",
|
|
397
397
|
"emdash > @emdash-cms/auth > @oslojs/webauthn",
|
|
398
|
+
// Auth deps imported only on auth/login/callback routes, so
|
|
399
|
+
// the initial page scan misses them. Pre-bundle to avoid a
|
|
400
|
+
// re-optimize + reload cascade on first authenticated request.
|
|
401
|
+
"emdash > @oslojs/crypto/hmac",
|
|
402
|
+
"emdash > @oslojs/crypto/subtle",
|
|
403
|
+
"emdash > @oslojs/crypto/rsa",
|
|
404
|
+
"emdash > arctic",
|
|
398
405
|
// MCP SDK — server/index.js statically imports ajv (CJS-only).
|
|
399
406
|
// Pre-bundling converts CJS to ESM so workerd can load it.
|
|
400
407
|
"emdash > @modelcontextprotocol/sdk > ajv",
|
|
401
408
|
"emdash > @modelcontextprotocol/sdk > ajv-formats",
|
|
409
|
+
// MCP server entrypoints — only imported on the MCP route, so
|
|
410
|
+
// also missed by the initial scan.
|
|
411
|
+
"emdash > @modelcontextprotocol/sdk/server/mcp.js",
|
|
412
|
+
"emdash > @modelcontextprotocol/sdk/server/webStandardStreamableHttp.js",
|
|
413
|
+
// Admin shell SSR deps, reached only when the admin route is
|
|
414
|
+
// first rendered.
|
|
415
|
+
"emdash > @emdash-cms/admin > @lingui/react",
|
|
416
|
+
"emdash > @emdash-cms/admin > @cloudflare/kumo/primitives",
|
|
402
417
|
// React (commonly used, may be hoisted)
|
|
403
418
|
"react",
|
|
404
419
|
"react/jsx-dev-runtime",
|
|
@@ -415,6 +430,7 @@ export function createViteConfig(
|
|
|
415
430
|
"astro/content/runtime",
|
|
416
431
|
"astro/assets/utils/inferRemoteSize.js",
|
|
417
432
|
"astro/assets/fonts/runtime.js",
|
|
433
|
+
"astro/assets/services/noop",
|
|
418
434
|
"@astrojs/cloudflare/image-service",
|
|
419
435
|
],
|
|
420
436
|
},
|
|
@@ -9,14 +9,17 @@ import { resolve } from "node:path";
|
|
|
9
9
|
import { defineCommand } from "citty";
|
|
10
10
|
import consola from "consola";
|
|
11
11
|
import type { Kysely } from "kysely";
|
|
12
|
+
import { sql } from "kysely";
|
|
12
13
|
|
|
13
14
|
import { createDatabase } from "../../database/connection.js";
|
|
14
15
|
import { runMigrations } from "../../database/migrations/runner.js";
|
|
16
|
+
import { BylineRepository } from "../../database/repositories/byline.js";
|
|
15
17
|
import { ContentRepository } from "../../database/repositories/content.js";
|
|
16
18
|
import { MediaRepository } from "../../database/repositories/media.js";
|
|
17
19
|
import { OptionsRepository } from "../../database/repositories/options.js";
|
|
18
20
|
import { TaxonomyRepository } from "../../database/repositories/taxonomy.js";
|
|
19
21
|
import type { Database } from "../../database/types.js";
|
|
22
|
+
import { validateIdentifier } from "../../database/validate.js";
|
|
20
23
|
import { isI18nEnabled } from "../../i18n/config.js";
|
|
21
24
|
import { SchemaRegistry } from "../../schema/registry.js";
|
|
22
25
|
import type { FieldType } from "../../schema/types.js";
|
|
@@ -31,7 +34,10 @@ import type {
|
|
|
31
34
|
SeedWidgetArea,
|
|
32
35
|
SeedWidget,
|
|
33
36
|
SeedContentEntry,
|
|
37
|
+
SeedByline,
|
|
38
|
+
SeedBylineCredit,
|
|
34
39
|
} from "../../seed/types.js";
|
|
40
|
+
import { isMissingTableError } from "../../utils/db-errors.js";
|
|
35
41
|
import { slugify } from "../../utils/slugify.js";
|
|
36
42
|
|
|
37
43
|
const SETTINGS_PREFIX = "site:";
|
|
@@ -118,16 +124,29 @@ export async function exportSeed(db: Kysely<Database>, withContent?: string): Pr
|
|
|
118
124
|
// 2. Export collections and fields
|
|
119
125
|
seed.collections = await exportCollections(db);
|
|
120
126
|
|
|
127
|
+
// Decide locale-awareness from the data. The runtime sets the i18n config via
|
|
128
|
+
// middleware, but the CLI never does, so `isI18nEnabled()` is always false
|
|
129
|
+
// under `emdash export-seed` (#1330). Detecting multiple locales in the data
|
|
130
|
+
// keeps the export locale-aware without the runtime flag.
|
|
131
|
+
const i18nEnabled = await detectI18nEnabled(db, seed.collections);
|
|
132
|
+
|
|
121
133
|
// 3. Export taxonomy definitions and terms
|
|
122
|
-
seed.taxonomies = await exportTaxonomies(db);
|
|
134
|
+
seed.taxonomies = await exportTaxonomies(db, i18nEnabled);
|
|
123
135
|
|
|
124
136
|
// 4. Export menus
|
|
125
|
-
seed.menus = await exportMenus(db);
|
|
137
|
+
seed.menus = await exportMenus(db, i18nEnabled);
|
|
126
138
|
|
|
127
139
|
// 5. Export widget areas
|
|
128
140
|
seed.widgetAreas = await exportWidgetAreas(db);
|
|
129
141
|
|
|
130
|
-
// 6. Export
|
|
142
|
+
// 6. Export byline profiles. The returned map (translation_group -> seed-local
|
|
143
|
+
// id) lets content credits below reference the same ids the root list emits.
|
|
144
|
+
const { bylines, groupToSeedId } = await exportBylines(db);
|
|
145
|
+
if (bylines.length > 0) {
|
|
146
|
+
seed.bylines = bylines;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// 7. Export content (if requested)
|
|
131
150
|
if (withContent !== undefined) {
|
|
132
151
|
const collections =
|
|
133
152
|
withContent === "" || withContent === "true"
|
|
@@ -137,12 +156,112 @@ export async function exportSeed(db: Kysely<Database>, withContent?: string): Pr
|
|
|
137
156
|
.map((s) => s.trim())
|
|
138
157
|
.filter(Boolean);
|
|
139
158
|
|
|
140
|
-
seed.content = await exportContent(
|
|
159
|
+
seed.content = await exportContent(
|
|
160
|
+
db,
|
|
161
|
+
seed.collections || [],
|
|
162
|
+
collections,
|
|
163
|
+
groupToSeedId,
|
|
164
|
+
i18nEnabled,
|
|
165
|
+
);
|
|
141
166
|
}
|
|
142
167
|
|
|
143
168
|
return seed;
|
|
144
169
|
}
|
|
145
170
|
|
|
171
|
+
/**
|
|
172
|
+
* Export byline profiles as root-level `bylines[]`.
|
|
173
|
+
*
|
|
174
|
+
* `SeedByline` has no locale axis, so locale siblings of the same byline
|
|
175
|
+
* (sharing a `translation_group`) collapse to a single profile. The returned
|
|
176
|
+
* `groupToSeedId` map keys on `translation_group` — the value stored in
|
|
177
|
+
* `_emdash_content_bylines.byline_id` — so content credits can resolve to the
|
|
178
|
+
* emitted seed id.
|
|
179
|
+
*/
|
|
180
|
+
async function exportBylines(
|
|
181
|
+
db: Kysely<Database>,
|
|
182
|
+
): Promise<{ bylines: SeedByline[]; groupToSeedId: Map<string, string> }> {
|
|
183
|
+
const bylineRepo = new BylineRepository(db);
|
|
184
|
+
const bylines: SeedByline[] = [];
|
|
185
|
+
const groupToSeedId = new Map<string, string>();
|
|
186
|
+
const usedSeedIds = new Set<string>();
|
|
187
|
+
|
|
188
|
+
let cursor: string | undefined;
|
|
189
|
+
do {
|
|
190
|
+
const result = await bylineRepo.findMany({ limit: 100, cursor });
|
|
191
|
+
for (const byline of result.items) {
|
|
192
|
+
const group = byline.translationGroup ?? byline.id;
|
|
193
|
+
// One seed entry per translation group; first row seen wins.
|
|
194
|
+
if (groupToSeedId.has(group)) continue;
|
|
195
|
+
|
|
196
|
+
let seedId = `byline:${byline.slug}`;
|
|
197
|
+
// Disambiguate the rare case of two distinct groups sharing a slug
|
|
198
|
+
// (slug is unique per-locale, not globally) so seed ids stay unique.
|
|
199
|
+
if (usedSeedIds.has(seedId)) seedId = `byline:${byline.slug}:${group}`;
|
|
200
|
+
usedSeedIds.add(seedId);
|
|
201
|
+
groupToSeedId.set(group, seedId);
|
|
202
|
+
|
|
203
|
+
bylines.push({
|
|
204
|
+
id: seedId,
|
|
205
|
+
slug: byline.slug,
|
|
206
|
+
displayName: byline.displayName,
|
|
207
|
+
bio: byline.bio || undefined,
|
|
208
|
+
websiteUrl: byline.websiteUrl || undefined,
|
|
209
|
+
isGuest: byline.isGuest || undefined,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
cursor = result.nextCursor;
|
|
213
|
+
} while (cursor);
|
|
214
|
+
|
|
215
|
+
return { bylines, groupToSeedId };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Determine whether the export should emit locale-suffixed seed ids.
|
|
220
|
+
*
|
|
221
|
+
* The runtime initializes the i18n config in middleware, but the CLI never does,
|
|
222
|
+
* so `isI18nEnabled()` is always false under `emdash export-seed` (#1330). When
|
|
223
|
+
* the flag is unset, fall back to the data: a project is multi-locale when its
|
|
224
|
+
* i18n-aware tables hold rows in more than one distinct locale. `locale` is
|
|
225
|
+
* NOT NULL (defaulting to the site's default locale), so a per-row presence
|
|
226
|
+
* check is not enough — only the *count* of distinct locales distinguishes a
|
|
227
|
+
* genuinely single-locale project from a multi-locale one. This keeps
|
|
228
|
+
* single-locale exports on bare ids and gives multi-locale exports the
|
|
229
|
+
* per-locale suffix they need to avoid duplicate seed ids.
|
|
230
|
+
*/
|
|
231
|
+
async function detectI18nEnabled(
|
|
232
|
+
db: Kysely<Database>,
|
|
233
|
+
collections: SeedCollection[],
|
|
234
|
+
): Promise<boolean> {
|
|
235
|
+
if (isI18nEnabled()) return true;
|
|
236
|
+
|
|
237
|
+
const locales = new Set<string>();
|
|
238
|
+
const collectDistinctLocales = async (tableRef: ReturnType<typeof sql.ref>): Promise<boolean> => {
|
|
239
|
+
const result = await sql<{ locale: string | null }>`
|
|
240
|
+
SELECT DISTINCT locale FROM ${tableRef}
|
|
241
|
+
`.execute(db);
|
|
242
|
+
for (const row of result.rows) {
|
|
243
|
+
if (row.locale) locales.add(row.locale);
|
|
244
|
+
}
|
|
245
|
+
return locales.size > 1;
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
if (await collectDistinctLocales(sql.ref("_emdash_taxonomy_defs"))) return true;
|
|
249
|
+
if (await collectDistinctLocales(sql.ref("_emdash_menus"))) return true;
|
|
250
|
+
|
|
251
|
+
for (const collection of collections) {
|
|
252
|
+
validateIdentifier(collection.slug, "collection slug");
|
|
253
|
+
// On D1, deleteCollection is non-atomic, so a collection row can outlive
|
|
254
|
+
// its ec_* table. Skip missing tables rather than crashing the export.
|
|
255
|
+
try {
|
|
256
|
+
if (await collectDistinctLocales(sql.ref(`ec_${collection.slug}`))) return true;
|
|
257
|
+
} catch (error) {
|
|
258
|
+
if (!isMissingTableError(error)) throw error;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
|
|
146
265
|
/**
|
|
147
266
|
* Export site settings
|
|
148
267
|
*/
|
|
@@ -212,9 +331,10 @@ async function exportCollections(db: Kysely<Database>): Promise<SeedCollection[]
|
|
|
212
331
|
/**
|
|
213
332
|
* Export taxonomy definitions and terms
|
|
214
333
|
*/
|
|
215
|
-
async function exportTaxonomies(
|
|
216
|
-
|
|
217
|
-
|
|
334
|
+
async function exportTaxonomies(
|
|
335
|
+
db: Kysely<Database>,
|
|
336
|
+
i18nEnabled: boolean,
|
|
337
|
+
): Promise<SeedTaxonomy[]> {
|
|
218
338
|
// Mirrors the content export pattern: one entry per (name, locale), stable
|
|
219
339
|
// seed-local id, translations linked via `translationOf` to the anchor's id.
|
|
220
340
|
const defs = await db
|
|
@@ -306,9 +426,7 @@ async function exportTaxonomies(db: Kysely<Database>): Promise<SeedTaxonomy[]> {
|
|
|
306
426
|
/**
|
|
307
427
|
* Export menus with their items
|
|
308
428
|
*/
|
|
309
|
-
async function exportMenus(db: Kysely<Database
|
|
310
|
-
const i18nEnabled = isI18nEnabled();
|
|
311
|
-
|
|
429
|
+
async function exportMenus(db: Kysely<Database>, i18nEnabled: boolean): Promise<SeedMenu[]> {
|
|
312
430
|
const menus = await db
|
|
313
431
|
.selectFrom("_emdash_menus")
|
|
314
432
|
.selectAll()
|
|
@@ -546,6 +664,8 @@ async function exportContent(
|
|
|
546
664
|
db: Kysely<Database>,
|
|
547
665
|
collections: SeedCollection[],
|
|
548
666
|
includeCollections: string[] | null,
|
|
667
|
+
bylineGroupToSeedId: Map<string, string>,
|
|
668
|
+
i18nEnabled: boolean,
|
|
549
669
|
): Promise<Record<string, SeedContentEntry[]>> {
|
|
550
670
|
const content: Record<string, SeedContentEntry[]> = {};
|
|
551
671
|
const contentRepo = new ContentRepository(db);
|
|
@@ -579,8 +699,6 @@ async function exportContent(
|
|
|
579
699
|
// Media table might not exist or be empty
|
|
580
700
|
}
|
|
581
701
|
|
|
582
|
-
const i18nEnabled = isI18nEnabled();
|
|
583
|
-
|
|
584
702
|
for (const collection of collections) {
|
|
585
703
|
// Skip if not in include list
|
|
586
704
|
if (includeCollections && !includeCollections.includes(collection.slug)) {
|
|
@@ -642,6 +760,16 @@ async function exportContent(
|
|
|
642
760
|
entry.taxonomies = taxonomies;
|
|
643
761
|
}
|
|
644
762
|
|
|
763
|
+
// Get byline credits. Read the junction directly: its `byline_id`
|
|
764
|
+
// stores the translation_group, which is exactly the key in
|
|
765
|
+
// `bylineGroupToSeedId`. This is locale-agnostic (one row per
|
|
766
|
+
// credit) and avoids the locale-sibling fan-out a hydrated read
|
|
767
|
+
// would produce.
|
|
768
|
+
const bylines = await getBylineCredits(db, collection.slug, item.id, bylineGroupToSeedId);
|
|
769
|
+
if (bylines.length > 0) {
|
|
770
|
+
entry.bylines = bylines;
|
|
771
|
+
}
|
|
772
|
+
|
|
645
773
|
entries.push(entry);
|
|
646
774
|
}
|
|
647
775
|
|
|
@@ -723,6 +851,40 @@ function processDataForExport(
|
|
|
723
851
|
return result;
|
|
724
852
|
}
|
|
725
853
|
|
|
854
|
+
/**
|
|
855
|
+
* Get ordered byline credits for a content entry as `SeedBylineCredit[]`.
|
|
856
|
+
*
|
|
857
|
+
* The `_emdash_content_bylines.byline_id` column stores the credited byline's
|
|
858
|
+
* `translation_group`, so it maps straight through `groupToSeedId`. Credits
|
|
859
|
+
* whose group wasn't emitted in the root `bylines[]` are skipped (defensive;
|
|
860
|
+
* shouldn't happen for a consistent DB).
|
|
861
|
+
*/
|
|
862
|
+
async function getBylineCredits(
|
|
863
|
+
db: Kysely<Database>,
|
|
864
|
+
collection: string,
|
|
865
|
+
entryId: string,
|
|
866
|
+
groupToSeedId: Map<string, string>,
|
|
867
|
+
): Promise<SeedBylineCredit[]> {
|
|
868
|
+
const rows = await db
|
|
869
|
+
.selectFrom("_emdash_content_bylines")
|
|
870
|
+
.select(["byline_id", "role_label"])
|
|
871
|
+
.where("collection_slug", "=", collection)
|
|
872
|
+
.where("content_id", "=", entryId)
|
|
873
|
+
.orderBy("sort_order", "asc")
|
|
874
|
+
.execute();
|
|
875
|
+
|
|
876
|
+
const credits: SeedBylineCredit[] = [];
|
|
877
|
+
for (const row of rows) {
|
|
878
|
+
const seedId = groupToSeedId.get(row.byline_id);
|
|
879
|
+
if (!seedId) continue;
|
|
880
|
+
const credit: SeedBylineCredit = { byline: seedId };
|
|
881
|
+
if (row.role_label) credit.roleLabel = row.role_label;
|
|
882
|
+
credits.push(credit);
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
return credits;
|
|
886
|
+
}
|
|
887
|
+
|
|
726
888
|
/**
|
|
727
889
|
* Get taxonomy term assignments for a content entry
|
|
728
890
|
*/
|
package/src/query.ts
CHANGED
|
@@ -495,10 +495,11 @@ async function getEmDashCollectionUncached<T extends string, D = InferCollection
|
|
|
495
495
|
const resolvedLocale =
|
|
496
496
|
filter?.locale ?? ctx?.locale ?? (isI18nEnabled() ? i18nConfig!.defaultLocale : undefined);
|
|
497
497
|
|
|
498
|
+
const requestedLimit = filter?.limit;
|
|
498
499
|
const result = await getLiveCollection(COLLECTION_NAME, {
|
|
499
500
|
type,
|
|
500
501
|
status: filter?.status,
|
|
501
|
-
limit: filter?.limit,
|
|
502
|
+
limit: requestedLimit && requestedLimit > 0 ? requestedLimit + 1 : filter?.limit,
|
|
502
503
|
cursor: filter?.cursor,
|
|
503
504
|
where: filter?.where,
|
|
504
505
|
orderBy: filter?.orderBy,
|
|
@@ -506,18 +507,17 @@ async function getEmDashCollectionUncached<T extends string, D = InferCollection
|
|
|
506
507
|
});
|
|
507
508
|
|
|
508
509
|
const { entries, error, cacheHint } = result;
|
|
509
|
-
// nextCursor is returned by the emdash loader but not part of Astro's base
|
|
510
|
-
// LiveLoader return type. Extract it safely via property descriptor to avoid
|
|
511
|
-
// an unsafe type assertion on the `any`-typed result object.
|
|
512
|
-
const rawCursor = Object.getOwnPropertyDescriptor(result, "nextCursor")?.value;
|
|
513
|
-
const nextCursor: string | undefined = typeof rawCursor === "string" ? rawCursor : undefined;
|
|
514
510
|
|
|
515
511
|
if (error) {
|
|
516
512
|
return { entries: [], error, cacheHint: {} };
|
|
517
513
|
}
|
|
518
514
|
|
|
515
|
+
const hasMore = requestedLimit != null && requestedLimit > 0 && entries.length > requestedLimit;
|
|
516
|
+
const pageEntries = hasMore ? entries.slice(0, requestedLimit) : entries;
|
|
517
|
+
const nextCursor = hasMore ? encodeEntryCursor(pageEntries.at(-1), filter?.orderBy) : undefined;
|
|
518
|
+
|
|
519
519
|
const isEditMode = ctx?.editMode ?? false;
|
|
520
|
-
const entriesWithEdit =
|
|
520
|
+
const entriesWithEdit = pageEntries.map((entry: ContentEntry<D>) => {
|
|
521
521
|
const dbId = entryDatabaseId(entry);
|
|
522
522
|
if (isEditMode) {
|
|
523
523
|
tagEditableFields(entryData(entry), type, dbId);
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"query-CuvjwhrE.mjs","names":[],"sources":["../src/visual-editing/editable.ts","../src/query.ts"],"sourcesContent":["/**\n * Visual editing annotation system\n *\n * Creates Proxy objects that emit data-emdash-ref attributes when spread onto elements.\n */\n\nexport interface CMSAnnotation {\n\tcollection: string;\n\tid: string;\n\tfield?: string;\n\t/** Entry status — only present on entry-level annotations (not field-level) */\n\tstatus?: string;\n\t/** Whether the entry has unpublished draft changes */\n\thasDraft?: boolean;\n}\n\n/** The shape returned when spreading an edit annotation onto an element */\nexport interface FieldAnnotation {\n\t\"data-emdash-ref\": string;\n}\n\nexport interface EditableOptions {\n\t/** Entry status: \"draft\", \"published\", \"scheduled\" */\n\tstatus?: string;\n\t/** true when draftRevisionId exists and differs from liveRevisionId */\n\thasDraft?: boolean;\n}\n\n/**\n * Create an editable proxy for an entry.\n *\n * Usage:\n * - `{...entry.edit}` - entry-level annotation (includes status/hasDraft)\n * - `{...entry.edit.title}` - field-level annotation\n * - `{...entry.edit['nested.field']}` - nested field (bracket notation)\n */\nexport function createEditable(\n\tcollection: string,\n\tid: string,\n\toptions?: EditableOptions,\n): EditProxy {\n\tconst base: CMSAnnotation = {\n\t\tcollection,\n\t\tid,\n\t\t...(options?.status && { status: options.status }),\n\t\t...(options?.hasDraft && { hasDraft: true }),\n\t};\n\n\treturn new Proxy({} as EditProxy, {\n\t\tget(_, prop) {\n\t\t\tif (prop === \"toJSON\") return () => ({ \"data-emdash-ref\": JSON.stringify(base) });\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\n\t\t\t// data-emdash-ref access returns the entry-level string\n\t\t\tif (prop === \"data-emdash-ref\") return JSON.stringify(base);\n\n\t\t\t// Field-level: return a FieldAnnotation for the specific field\n\t\t\treturn {\n\t\t\t\t\"data-emdash-ref\": JSON.stringify({ ...base, field: String(prop) }),\n\t\t\t} satisfies FieldAnnotation;\n\t\t},\n\t\townKeys() {\n\t\t\treturn [\"data-emdash-ref\"];\n\t\t},\n\t\tgetOwnPropertyDescriptor(_, prop) {\n\t\t\tif (prop === \"data-emdash-ref\") {\n\t\t\t\treturn {\n\t\t\t\t\tconfigurable: true,\n\t\t\t\t\tenumerable: true,\n\t\t\t\t\tvalue: JSON.stringify(base),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t});\n}\n\n/**\n * Create a noop proxy for production mode.\n * Spreading this produces no attributes.\n */\nexport function createNoop(): EditProxy {\n\treturn new Proxy({} as EditProxy, {\n\t\tget(_, prop) {\n\t\t\tif (typeof prop === \"symbol\") return undefined;\n\t\t\t// All property access returns undefined in noop mode\n\t\t\treturn undefined;\n\t\t},\n\t\townKeys() {\n\t\t\treturn [];\n\t\t},\n\t\tgetOwnPropertyDescriptor() {\n\t\t\treturn undefined;\n\t\t},\n\t});\n}\n\n/**\n * Visual editing proxy type.\n *\n * Spread directly onto elements for entry-level annotations: `{...entry.edit}`\n * Access a field for field-level annotations: `{...entry.edit.title}`\n *\n * In production, spreading produces no attributes (noop).\n */\nexport type EditProxy = {\n\treadonly [field: string]: Partial<FieldAnnotation>;\n};\n","/// <reference types=\"astro/client\" />\n/**\n * Query functions for EmDash content\n *\n * These wrap Astro's getLiveCollection/getLiveEntry with type filtering.\n * Use these instead of calling Astro's functions directly.\n *\n * Error handling follows Astro's pattern - returns { entries/entry, error }\n * so callers can gracefully handle errors (including 404s).\n *\n * Preview mode is handled implicitly via ALS request context —\n * no parameters needed. The middleware verifies the preview token\n * and sets the context; query functions read it automatically.\n *\n * The triple-slash directive above pulls in the ambient declaration for\n * `astro:content` (used by the dynamic imports below) so this source\n * file typechecks even when reached transitively by a sibling package\n * whose tsconfig doesn't list `astro/client` in `compilerOptions.types`.\n *\n * Note: the directive is stripped from the compiled output (`dist/*`)\n * by tsdown, so it does not propagate to downstream consumers of the\n * published package. Consumers are Astro sites and already provide their\n * own `astro/client` ambient surface anyway, so the runtime dynamic\n * import resolves there at typecheck time without our help.\n */\n\nimport { encodeCursor } from \"./database/repositories/types.js\";\nimport { getFallbackChain, getI18nConfig, isI18nEnabled } from \"./i18n/config.js\";\nimport { CURSOR_RAW_VALUES, type WhereRange, type WhereValue } from \"./loader.js\";\nimport { requestCached } from \"./request-cache.js\";\nimport { getRequestContext } from \"./request-context.js\";\nimport { isMissingTableError } from \"./utils/db-errors.js\";\nimport {\n\tcreateEditable,\n\tcreateNoop,\n\ttype EditProxy,\n\ttype EditableOptions,\n} from \"./visual-editing/editable.js\";\n\n/**\n * Collection type registry for type-safe queries.\n *\n * This interface is extended by the generated emdash-env.d.ts file\n * to provide type inference for collection names and their data shapes.\n *\n * @example\n * ```ts\n * // In emdash-env.d.ts (generated):\n * declare module \"emdash\" {\n * interface EmDashCollections {\n * posts: { title: string; content: PortableTextBlock[]; };\n * pages: { title: string; body: PortableTextBlock[]; };\n * }\n * }\n *\n * // Then in your code:\n * const { entries } = await getEmDashCollection(\"posts\");\n * // entries[0].data.title is typed as string\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface EmDashCollections {}\n\n/**\n * Helper type to infer the data type for a collection.\n * Returns the registered type if known, otherwise falls back to Record<string, unknown>.\n */\nexport type InferCollectionData<T extends string> = T extends keyof EmDashCollections\n\t? EmDashCollections[T]\n\t: Record<string, unknown>;\n\n/**\n * Sort direction\n */\nexport type SortDirection = \"asc\" | \"desc\";\n\n/**\n * Order by specification - field name to direction\n * @example { created_at: \"desc\" } - Sort by created_at descending\n * @example { title: \"asc\" } - Sort by title ascending\n * @example { published_at: \"desc\", title: \"asc\" } - Multi-field sort\n */\nexport type OrderBySpec = Record<string, SortDirection>;\n\nexport type { WhereRange, WhereValue };\n\nexport interface CollectionFilter {\n\tstatus?: \"draft\" | \"published\" | \"archived\";\n\tlimit?: number;\n\t/**\n\t * Opaque cursor for keyset pagination.\n\t * Pass the `nextCursor` value from a previous result to fetch the next page.\n\t * @example\n\t * ```ts\n\t * const cursor = Astro.url.searchParams.get(\"cursor\") ?? undefined;\n\t * const { entries, nextCursor } = await getEmDashCollection(\"posts\", {\n\t * limit: 10,\n\t * cursor,\n\t * });\n\t * ```\n\t */\n\tcursor?: string;\n\t/**\n\t * Filter by field values, taxonomy terms, or ranges.\n\t *\n\t * Taxonomy names are detected automatically and filtered via JOIN.\n\t * Other keys are treated as column filters on the content table.\n\t *\n\t * @example { category: 'news' } - Filter by taxonomy term\n\t * @example { category: ['news', 'featured'] } - Filter by multiple terms (OR)\n\t * @example { series: 'main' } - Exact match on a content field\n\t * @example { published_at: { gte: '2024-01-01', lt: '2025-01-01' } } - Date range\n\t */\n\twhere?: Record<string, WhereValue>;\n\t/**\n\t * Order results by field(s)\n\t * @default { created_at: \"desc\" }\n\t * @example { created_at: \"desc\" } - Sort by created_at descending (default)\n\t * @example { title: \"asc\" } - Sort by title ascending\n\t * @example { published_at: \"desc\", title: \"asc\" } - Multi-field sort\n\t */\n\torderBy?: OrderBySpec;\n\t/**\n\t * Filter by locale. When set, only returns entries in this locale.\n\t * Only relevant when i18n is configured.\n\t * @example \"en\" — English entries only\n\t * @example \"fr\" — French entries only\n\t */\n\tlocale?: string;\n}\n\nexport interface ContentEntry<T = Record<string, unknown>> {\n\tid: string;\n\tdata: T;\n\t/** Visual editing annotations. Spread onto elements: {...entry.edit.title} */\n\tedit: EditProxy;\n}\n\n/** Cache hint returned by the content loader for route caching */\nexport interface CacheHint {\n\ttags?: string[];\n\tlastModified?: Date;\n}\n\n/**\n * Result from getEmDashCollection\n */\nexport interface CollectionResult<T> {\n\t/** The entries (empty array if error or none found) */\n\tentries: ContentEntry<T>[];\n\t/** Error if the query failed */\n\terror?: Error;\n\t/** Cache hint for route caching (pass to Astro.cache.set()) */\n\tcacheHint: CacheHint;\n\t/**\n\t * Opaque cursor for the next page.\n\t * Undefined when there are no more results.\n\t * Pass this as `cursor` in the next query to get the next page.\n\t */\n\tnextCursor?: string;\n}\n\n/**\n * Result from getEmDashEntry\n */\nexport interface EntryResult<T> {\n\t/** The entry, or null if not found */\n\tentry: ContentEntry<T> | null;\n\t/** Error if the query failed (not set for \"not found\", only for actual errors) */\n\terror?: Error;\n\t/** Whether we're in preview mode (valid token was provided) */\n\tisPreview: boolean;\n\t/** Set when a fallback locale was used instead of the requested locale */\n\tfallbackLocale?: string;\n\t/** Cache hint for route caching (pass to Astro.cache.set()) */\n\tcacheHint: CacheHint;\n}\n\nconst COLLECTION_NAME = \"_emdash\";\n\n/** Symbol key for edit metadata on PT arrays — avoids collision with user data */\nconst EMDASH_EDIT = Symbol.for(\"__emdash\");\n\n/** Edit metadata attached to PT arrays in edit mode */\nexport interface EditFieldMeta {\n\tcollection: string;\n\tid: string;\n\tfield: string;\n}\n\n/** Type guard for EditFieldMeta */\nfunction isEditFieldMeta(value: unknown): value is EditFieldMeta {\n\tif (typeof value !== \"object\" || value === null) return false;\n\tif (!(\"collection\" in value) || !(\"id\" in value) || !(\"field\" in value)) return false;\n\t// After `in` checks, TS narrows to Record<\"collection\" | \"id\" | \"field\", unknown>\n\tconst { collection, id, field } = value;\n\treturn typeof collection === \"string\" && typeof id === \"string\" && typeof field === \"string\";\n}\n\n/**\n * Read edit metadata from a value (returns undefined if not tagged).\n * Uses Object.getOwnPropertyDescriptor to access Symbol-keyed property\n * without an unsafe type assertion.\n */\nexport function getEditMeta(value: unknown): EditFieldMeta | undefined {\n\tif (value && typeof value === \"object\") {\n\t\tconst desc = Object.getOwnPropertyDescriptor(value, EMDASH_EDIT);\n\t\tconst meta: unknown = desc?.value;\n\t\tif (isEditFieldMeta(meta)) {\n\t\t\treturn meta;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/**\n * Tag PT-like arrays in entry data with edit metadata (non-enumerable).\n * A PT array is identified by: is an array, first element has _type property.\n */\nfunction tagEditableFields(data: Record<string, unknown>, collection: string, id: string): void {\n\tfor (const [field, value] of Object.entries(data)) {\n\t\tif (\n\t\t\tArray.isArray(value) &&\n\t\t\tvalue.length > 0 &&\n\t\t\tvalue[0] &&\n\t\t\ttypeof value[0] === \"object\" &&\n\t\t\t\"_type\" in value[0]\n\t\t) {\n\t\t\tObject.defineProperty(value, EMDASH_EDIT, {\n\t\t\t\tvalue: { collection, id, field } satisfies EditFieldMeta,\n\t\t\t\tenumerable: false,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\t}\n\t}\n}\n\n/** Safely read a string field from a Record, with optional fallback */\nfunction dataStr(data: Record<string, unknown>, key: string, fallback = \"\"): string {\n\tconst val = data[key];\n\treturn typeof val === \"string\" ? val : fallback;\n}\n\n/** Type guard for Record<string, unknown> */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** Extract data as Record from an Astro entry (which is any-typed) */\nfunction entryData(entry: { data?: unknown }): Record<string, unknown> {\n\treturn isRecord(entry.data) ? entry.data : {};\n}\n\n/** Extract the database ID from entry data (data.id is the ULID, entry.id is the slug) */\nfunction entryDatabaseId(entry: { id: string; data?: unknown }): string {\n\tconst d = entryData(entry);\n\treturn dataStr(d, \"id\") || entry.id;\n}\n\n/** Extract edit options from entry data for the proxy */\nfunction entryEditOptions(entry: { data?: unknown }): EditableOptions {\n\tconst data = entryData(entry);\n\tconst status = dataStr(data, \"status\", \"draft\");\n\tconst draftRevisionId = dataStr(data, \"draftRevisionId\") || undefined;\n\tconst liveRevisionId = dataStr(data, \"liveRevisionId\") || undefined;\n\tconst hasDraft = !!draftRevisionId && draftRevisionId !== liveRevisionId;\n\treturn { status, hasDraft };\n}\n\n/**\n * Get all entries of a content type\n *\n * Returns { entries, error } for graceful error handling.\n *\n * When emdash-env.d.ts is generated, the collection name will be\n * type-checked and the return type will be inferred automatically.\n *\n * @example\n * ```ts\n * import { getEmDashCollection } from \"emdash\";\n *\n * const { entries: posts, error } = await getEmDashCollection(\"posts\");\n * if (error) {\n * console.error(\"Failed to load posts:\", error);\n * return;\n * }\n * // posts[0].data.title is typed (if emdash-env.d.ts exists)\n *\n * // With filters\n * const { entries: drafts } = await getEmDashCollection(\"posts\", { status: \"draft\" });\n * ```\n */\nexport async function getEmDashCollection<T extends string, D = InferCollectionData<T>>(\n\ttype: T,\n\tfilter?: CollectionFilter,\n): Promise<CollectionResult<D>> {\n\t// Cache per (type, filter) within a single request. Edit mode and\n\t// preview are request-scoped and stable, so they don't need to be\n\t// part of the key. Widgets and layouts frequently request the same\n\t// collection shape as the page itself (e.g. a \"recent posts\" list\n\t// appears on the home page AND in the sidebar) — caching collapses\n\t// those duplicate queries, along with the bylines and taxonomy-term\n\t// hydration each call would otherwise re-do.\n\t//\n\t// Bucket small limits to a shared minimum so a page with several\n\t// \"recent N posts\" widgets at slightly different limits (e.g. a\n\t// post-detail page asking for 4 in the body and 5 in the sidebar)\n\t// shares one fetch + hydration round-trip rather than running two.\n\t// Cursor-paginated calls are exempt: their limit is part of the\n\t// pagination contract.\n\tconst bucketed = bucketFilter(filter);\n\tconst cached = await requestCached(collectionCacheKey(type, bucketed.fetchFilter), () =>\n\t\tgetEmDashCollectionUncached<T, D>(type, bucketed.fetchFilter),\n\t);\n\treturn bucketed.requestedLimit === undefined\n\t\t? cached\n\t\t: sliceCollectionResult(cached, bucketed.requestedLimit, filter?.orderBy);\n}\n\n/**\n * Threshold for limit bucketing. Page templates routinely render small\n * \"recent posts\" widgets at limits 3-8; rounding those up to a single\n * shared bucket lets one fetch satisfy several widgets within a request.\n * Above this, the requested limit is honoured exactly — bucketing limit:50\n * to limit:64 would waste hydration work for callers fetching real pages.\n */\nconst BUCKET_LIMIT_THRESHOLD = 10;\n\ninterface BucketedFilter {\n\t/** Filter to pass to the loader (with limit possibly raised). */\n\tfetchFilter: CollectionFilter | undefined;\n\t/** Original limit; defined only when bucketing was applied. */\n\trequestedLimit: number | undefined;\n}\n\n/** @internal exported for unit tests; not part of the public API. */\nexport function bucketFilter(filter: CollectionFilter | undefined): BucketedFilter {\n\tconst limit = filter?.limit;\n\tif (\n\t\tlimit === undefined ||\n\t\tlimit >= BUCKET_LIMIT_THRESHOLD ||\n\t\tlimit <= 0 ||\n\t\tfilter?.cursor !== undefined\n\t) {\n\t\treturn { fetchFilter: filter, requestedLimit: undefined };\n\t}\n\treturn {\n\t\tfetchFilter: { ...filter, limit: BUCKET_LIMIT_THRESHOLD },\n\t\trequestedLimit: limit,\n\t};\n}\n\n/**\n * Slice a cached bucketed result down to the originally-requested limit\n * and recompute `nextCursor` from the row that would have been the\n * over-fetch detector for that limit. When truncation is needed, returns\n * a shallow-copied result with a new `entries` array; otherwise returns\n * the cached result unchanged (including error results and results\n * already within the requested limit).\n */\n/** @internal exported for unit tests; not part of the public API. */\nexport function sliceCollectionResult<D>(\n\tcached: CollectionResult<D>,\n\tlimit: number,\n\torderBy: OrderBySpec | undefined,\n): CollectionResult<D> {\n\tif (cached.error) return cached;\n\tif (cached.entries.length <= limit) return cached;\n\tconst sliced = cached.entries.slice(0, limit);\n\t// Mirror the loader's encoding: cursor points at the last returned row,\n\t// so \"next page\" picks up at the row immediately after it. See\n\t// buildCursorCondition in loader.ts — it filters strictly past this row.\n\tconst lastEntry = sliced.at(-1);\n\tconst nextCursor = lastEntry ? encodeEntryCursor(lastEntry, orderBy) : undefined;\n\treturn { ...cached, entries: sliced, nextCursor };\n}\n\n/** Map of database column names to camelCase keys present on entry.data. */\nconst ENTRY_DATA_KEY_MAP: Record<string, string> = {\n\tcreated_at: \"createdAt\",\n\tupdated_at: \"updatedAt\",\n\tpublished_at: \"publishedAt\",\n\tscheduled_at: \"scheduledAt\",\n\tauthor_id: \"authorId\",\n\tprimary_byline_id: \"primaryBylineId\",\n};\n\n// Mirror loader.ts FIELD_NAME_PATTERN. Kept in sync intentionally — diverging\n// would let the encoder accept a field name the loader's getPrimarySort then\n// rejected, producing a cursor that paginates against a different column.\nconst FIELD_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/**\n * Encode a `nextCursor` from a content entry, mirroring the loader's\n * encoding scheme: `(orderValue, id)` where `orderValue` is the primary\n * sort field's stringified value. For date columns, reads the raw DB\n * string the loader stashed via CURSOR_RAW_VALUES — round-tripping the\n * parsed Date through `toISOString()` would lose precision for stored\n * values that aren't already ISO-with-milliseconds.\n */\nfunction encodeEntryCursor<D>(\n\tentry: ContentEntry<D>,\n\torderBy: OrderBySpec | undefined,\n): string | undefined {\n\tconst data = entryData(entry);\n\tconst id = dataStr(data, \"id\");\n\tif (!id) return undefined;\n\n\t// Match loader.ts getPrimarySort: take the first valid field, default to created_at.\n\tlet dbField = \"created_at\";\n\tif (orderBy) {\n\t\tfor (const field of Object.keys(orderBy)) {\n\t\t\tif (FIELD_NAME_PATTERN.test(field)) {\n\t\t\t\tdbField = field;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Date columns: prefer the raw stored string captured by the loader so\n\t// the cursor matches what a direct loader fetch would emit, regardless\n\t// of how the DB stored the timestamp.\n\tconst rawDateValuesRaw = Reflect.get(data, CURSOR_RAW_VALUES);\n\tif (rawDateValuesRaw !== null && typeof rawDateValuesRaw === \"object\") {\n\t\tconst raw = Reflect.get(rawDateValuesRaw, dbField);\n\t\tif (typeof raw === \"string\") return encodeCursor(raw, id);\n\t}\n\n\tconst dataKey = ENTRY_DATA_KEY_MAP[dbField] ?? dbField;\n\tconst value = data[dataKey];\n\tlet orderValue: string;\n\tif (value instanceof Date) {\n\t\torderValue = value.toISOString();\n\t} else if (typeof value === \"string\" || typeof value === \"number\") {\n\t\torderValue = String(value);\n\t} else {\n\t\t// Match the loader's empty-string fallback for null/undefined order\n\t\t// values so cursor decoding stays valid even at the boundary.\n\t\torderValue = \"\";\n\t}\n\treturn encodeCursor(orderValue, id);\n}\n\n/**\n * Build a canonical cache key for `getEmDashCollection`.\n *\n * `JSON.stringify` is insertion-order-sensitive, so two callers passing\n * semantically identical filters with different key orders would miss\n * the cache. We fix the top-level field order and sort `where` keys\n * (order there is irrelevant), while preserving `orderBy` key order\n * because that's the sort priority.\n */\nfunction collectionCacheKey(type: string, filter?: CollectionFilter): string {\n\tif (!filter) return `collection:${type}:`;\n\tconst parts = [\n\t\tfilter.status ?? \"\",\n\t\tfilter.limit ?? \"\",\n\t\tfilter.cursor ?? \"\",\n\t\tfilter.where ? stableStringify(filter.where) : \"\",\n\t\tfilter.orderBy ? JSON.stringify(filter.orderBy) : \"\",\n\t\tfilter.locale ?? \"\",\n\t];\n\treturn `collection:${type}:${parts.join(\"|\")}`;\n}\n\nfunction stableStringify(value: Record<string, unknown>): string {\n\treturn JSON.stringify(stableOrder(value));\n}\n\nfunction stableOrder(value: Record<string, unknown>): Record<string, unknown> {\n\tconst keys = Object.keys(value).toSorted();\n\tconst ordered: Record<string, unknown> = {};\n\tfor (const k of keys) {\n\t\tconst v = value[k];\n\t\tif (isRecord(v)) {\n\t\t\tordered[k] = stableOrder(v);\n\t\t} else {\n\t\t\tordered[k] = v;\n\t\t}\n\t}\n\treturn ordered;\n}\n\nasync function getEmDashCollectionUncached<T extends string, D = InferCollectionData<T>>(\n\ttype: T,\n\tfilter?: CollectionFilter,\n): Promise<CollectionResult<D>> {\n\t// Dynamic import to avoid build-time issues\n\tconst { getLiveCollection } = await import(\"astro:content\");\n\n\t// Resolve locale: explicit filter > ALS context > defaultLocale (when i18n enabled)\n\t// Without this, queries return all locale rows, producing broken IDs\n\tconst ctx = getRequestContext();\n\tconst i18nConfig = getI18nConfig();\n\tconst resolvedLocale =\n\t\tfilter?.locale ?? ctx?.locale ?? (isI18nEnabled() ? i18nConfig!.defaultLocale : undefined);\n\n\tconst result = await getLiveCollection(COLLECTION_NAME, {\n\t\ttype,\n\t\tstatus: filter?.status,\n\t\tlimit: filter?.limit,\n\t\tcursor: filter?.cursor,\n\t\twhere: filter?.where,\n\t\torderBy: filter?.orderBy,\n\t\tlocale: resolvedLocale,\n\t});\n\n\tconst { entries, error, cacheHint } = result;\n\t// nextCursor is returned by the emdash loader but not part of Astro's base\n\t// LiveLoader return type. Extract it safely via property descriptor to avoid\n\t// an unsafe type assertion on the `any`-typed result object.\n\tconst rawCursor = Object.getOwnPropertyDescriptor(result, \"nextCursor\")?.value;\n\tconst nextCursor: string | undefined = typeof rawCursor === \"string\" ? rawCursor : undefined;\n\n\tif (error) {\n\t\treturn { entries: [], error, cacheHint: {} };\n\t}\n\n\tconst isEditMode = ctx?.editMode ?? false;\n\tconst entriesWithEdit = entries.map((entry: ContentEntry<D>) => {\n\t\tconst dbId = entryDatabaseId(entry);\n\t\tif (isEditMode) {\n\t\t\ttagEditableFields(entryData(entry), type, dbId);\n\t\t}\n\t\treturn {\n\t\t\t...entry,\n\t\t\tedit: isEditMode ? createEditable(type, dbId, entryEditOptions(entry)) : createNoop(),\n\t\t};\n\t});\n\n\t// Eagerly hydrate bylines and taxonomy terms for all entries in parallel.\n\t// Both are independent queries, so running them concurrently halves the\n\t// round-trip cost on remote databases (D1 replicas, etc.).\n\tawait Promise.all([\n\t\thydrateEntryBylines(type, entriesWithEdit),\n\t\thydrateEntryTerms(type, entriesWithEdit),\n\t]);\n\n\treturn { entries: entriesWithEdit, nextCursor, cacheHint: cacheHint ?? {} };\n}\n\n/**\n * Get a single entry by type and ID/slug\n *\n * Returns { entry, error, isPreview } for graceful error handling.\n * - entry is null if not found (not an error)\n * - error is set only for actual errors (db issues, etc.)\n *\n * Preview mode is detected automatically from request context (ALS).\n * When the URL has a valid `_preview` token, the middleware sets preview\n * context and this function serves draft revision data if available.\n *\n * @example\n * ```ts\n * import { getEmDashEntry } from \"emdash\";\n *\n * // Simple usage — preview just works via middleware\n * const { entry: post, isPreview, error } = await getEmDashEntry(\"posts\", \"my-slug\");\n * if (!post) return Astro.redirect(\"/404\");\n * ```\n */\nexport async function getEmDashEntry<T extends string, D = InferCollectionData<T>>(\n\ttype: T,\n\tid: string,\n\toptions?: { locale?: string },\n): Promise<EntryResult<D>> {\n\t// Dynamic import to avoid build-time issues\n\tconst { getLiveEntry } = await import(\"astro:content\");\n\n\t// Check ALS for preview and edit mode context\n\tconst ctx = getRequestContext();\n\tconst preview = ctx?.preview;\n\tconst isEditMode = ctx?.editMode ?? false;\n\tconst isPreviewMode = !!preview && preview.collection === type;\n\t// Edit mode implies preview — editors should see draft content\n\tconst serveDrafts = isPreviewMode || isEditMode;\n\n\t// Resolve locale: explicit option > ALS context > undefined (no filter)\n\tconst requestedLocale = options?.locale ?? ctx?.locale;\n\n\t/** Wrap a raw Astro entry with edit proxy, tagging editable fields if needed */\n\tfunction wrapEntry(raw: ContentEntry<D>): ContentEntry<D> {\n\t\tconst dbId = entryDatabaseId(raw);\n\t\tif (isEditMode) {\n\t\t\ttagEditableFields(entryData(raw), type, dbId);\n\t\t}\n\t\treturn {\n\t\t\t...raw,\n\t\t\tedit: isEditMode ? createEditable(type, dbId, entryEditOptions(raw)) : createNoop(),\n\t\t};\n\t}\n\n\t/** Check if an entry is publicly visible (published or scheduled past its time) */\n\tfunction isVisible(entry: ContentEntry<D>): boolean {\n\t\tconst data = entryData(entry);\n\t\tconst status = dataStr(data, \"status\");\n\t\tconst scheduledAt = dataStr(data, \"scheduledAt\") || undefined;\n\t\tconst isPublished = status === \"published\";\n\t\tconst isScheduledAndReady =\n\t\t\tstatus === \"scheduled\" && scheduledAt && new Date(scheduledAt) <= new Date();\n\t\treturn isPublished || !!isScheduledAndReady;\n\t}\n\n\t// Build the fallback chain: [requestedLocale, fallback1, ..., defaultLocale]\n\t// When i18n is disabled or no locale requested, just use a single-element chain\n\tconst localeChain =\n\t\trequestedLocale && isI18nEnabled() ? getFallbackChain(requestedLocale) : [requestedLocale];\n\n\t/** Return a successful EntryResult with bylines and taxonomy terms hydrated */\n\tasync function successResult(\n\t\twrapped: ContentEntry<D>,\n\t\topts: { isPreview: boolean; fallbackLocale?: string; cacheHint: CacheHint },\n\t): Promise<EntryResult<D>> {\n\t\tawait Promise.all([hydrateEntryBylines(type, [wrapped]), hydrateEntryTerms(type, [wrapped])]);\n\t\treturn {\n\t\t\tentry: wrapped,\n\t\t\tisPreview: opts.isPreview,\n\t\t\tfallbackLocale: opts.fallbackLocale,\n\t\t\tcacheHint: opts.cacheHint,\n\t\t};\n\t}\n\n\tif (serveDrafts) {\n\t\t// Draft mode: try each locale in the fallback chain\n\t\tfor (let i = 0; i < localeChain.length; i++) {\n\t\t\tconst locale = localeChain[i];\n\t\t\tconst fallbackLocale = i > 0 ? locale : undefined;\n\n\t\t\tconst {\n\t\t\t\tentry: baseEntry,\n\t\t\t\terror: baseError,\n\t\t\t\tcacheHint,\n\t\t\t} = await getLiveEntry(COLLECTION_NAME, {\n\t\t\t\ttype,\n\t\t\t\tid,\n\t\t\t\tlocale,\n\t\t\t});\n\n\t\t\tif (baseError) {\n\t\t\t\treturn { entry: null, error: baseError, isPreview: serveDrafts, cacheHint: {} };\n\t\t\t}\n\n\t\t\tif (!baseEntry) continue; // Try next locale in chain\n\n\t\t\t// Preview tokens are item-scoped: verify the resolved entry matches.\n\t\t\t// Edit mode (authenticated editors) has collection-wide draft access.\n\t\t\tif (isPreviewMode && !isEditMode) {\n\t\t\t\tconst dbId = entryDatabaseId(baseEntry);\n\t\t\t\tif (preview.id !== dbId && preview.id !== id) {\n\t\t\t\t\t// Token doesn't match — serve only if publicly visible, without draft access\n\t\t\t\t\tif (isVisible(baseEntry)) {\n\t\t\t\t\t\treturn successResult(wrapEntry(baseEntry), {\n\t\t\t\t\t\t\tisPreview: false,\n\t\t\t\t\t\t\tfallbackLocale,\n\t\t\t\t\t\t\tcacheHint: cacheHint ?? {},\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\t// Not visible — try next locale in fallback chain\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check if entry has a draft revision — if so, re-fetch with revision data\n\t\t\tconst baseData = entryData(baseEntry);\n\t\t\tconst draftRevisionId = dataStr(baseData, \"draftRevisionId\") || undefined;\n\n\t\t\tif (draftRevisionId) {\n\t\t\t\tconst { entry: draftEntry, error: draftError } = await getLiveEntry(COLLECTION_NAME, {\n\t\t\t\t\ttype,\n\t\t\t\t\tid,\n\t\t\t\t\trevisionId: draftRevisionId,\n\t\t\t\t\tlocale,\n\t\t\t\t});\n\n\t\t\t\tif (!draftError && draftEntry) {\n\t\t\t\t\treturn successResult(wrapEntry(draftEntry), {\n\t\t\t\t\t\tisPreview: serveDrafts,\n\t\t\t\t\t\tfallbackLocale,\n\t\t\t\t\t\tcacheHint: cacheHint ?? {},\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn successResult(wrapEntry(baseEntry), {\n\t\t\t\tisPreview: serveDrafts,\n\t\t\t\tfallbackLocale,\n\t\t\t\tcacheHint: cacheHint ?? {},\n\t\t\t});\n\t\t}\n\n\t\t// No entry found in any locale\n\t\treturn { entry: null, isPreview: serveDrafts, cacheHint: {} };\n\t}\n\n\t// Normal mode: try each locale in the fallback chain, only return published content\n\tfor (let i = 0; i < localeChain.length; i++) {\n\t\tconst locale = localeChain[i];\n\t\tconst fallbackLocale = i > 0 ? locale : undefined;\n\n\t\tconst { entry, error, cacheHint } = await getLiveEntry(COLLECTION_NAME, { type, id, locale });\n\t\tif (error) {\n\t\t\treturn { entry: null, error, isPreview: false, cacheHint: {} };\n\t\t}\n\n\t\tif (entry && isVisible(entry)) {\n\t\t\treturn successResult(wrapEntry(entry), {\n\t\t\t\tisPreview: false,\n\t\t\t\tfallbackLocale,\n\t\t\t\tcacheHint: cacheHint ?? {},\n\t\t\t});\n\t\t}\n\t\t// Entry not found or not visible in this locale — try next\n\t}\n\n\treturn { entry: null, isPreview: false, cacheHint: {} };\n}\n\n/**\n * Eagerly hydrate byline data onto entry.data for one or more entries.\n *\n * Attaches `bylines` (array of ContentBylineCredit) and `byline`\n * (primary BylineSummary or null) to each entry's data object.\n * Uses batch queries to avoid N+1.\n *\n * Fails silently if the byline tables don't exist yet (pre-migration).\n */\nasync function hydrateEntryBylines<D>(type: string, entries: ContentEntry<D>[]): Promise<void> {\n\tif (entries.length === 0) return;\n\n\ttry {\n\t\tconst { getBylinesForEntries } = await import(\"./bylines/index.js\");\n\n\t\tconst refs = entries\n\t\t\t.map((e) => {\n\t\t\t\tconst data = entryData(e);\n\t\t\t\tconst id = dataStr(data, \"id\");\n\t\t\t\tif (!id) return null;\n\t\t\t\treturn {\n\t\t\t\t\tid,\n\t\t\t\t\tauthorId: dataStr(data, \"authorId\") || null,\n\t\t\t\t\tprimaryBylineId: dataStr(data, \"primaryBylineId\") || null,\n\t\t\t\t\tlocale: dataStr(data, \"locale\") || null,\n\t\t\t\t};\n\t\t\t})\n\t\t\t.filter(\n\t\t\t\t(\n\t\t\t\t\tr,\n\t\t\t\t): r is {\n\t\t\t\t\tid: string;\n\t\t\t\t\tauthorId: string | null;\n\t\t\t\t\tprimaryBylineId: string | null;\n\t\t\t\t\tlocale: string | null;\n\t\t\t\t} => r !== null,\n\t\t\t);\n\t\tif (refs.length === 0) return;\n\n\t\tconst bylinesMap = await getBylinesForEntries(type, refs);\n\n\t\tfor (const entry of entries) {\n\t\t\tconst data = entryData(entry);\n\t\t\tconst dbId = dataStr(data, \"id\");\n\t\t\tif (!dbId) continue;\n\n\t\t\tconst credits = bylinesMap.get(dbId) ?? [];\n\t\t\tdata.bylines = credits;\n\t\t\tdata.byline = credits[0]?.byline ?? null;\n\t\t}\n\t} catch (err) {\n\t\t// Only swallow \"table not found\" errors from pre-migration databases.\n\t\t// Matches SQLite/D1 (\"no such table\") and PostgreSQL (\"relation/table\n\t\t// ... does not exist\") via the shared helper.\n\t\tif (!isMissingTableError(err)) {\n\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\tconsole.warn(\"[emdash] Failed to hydrate bylines:\", msg);\n\t\t}\n\t}\n}\n\n/**\n * Eagerly hydrate taxonomy term data onto entry.data for one or more entries.\n *\n * Attaches `terms` (Record keyed by taxonomy name with an array of TaxonomyTerm\n * values) to each entry's data object. Uses a single batched JOIN query across\n * all taxonomies so the cost is O(1) regardless of the number of entries or\n * taxonomies on the site.\n *\n * This eliminates the common N+1 pattern where templates loop over list\n * results and call getEntryTerms() per entry. With hydration, the list page\n * stays at a single round-trip for term data.\n *\n * Fails silently if the taxonomy tables don't exist yet (pre-migration).\n */\nasync function hydrateEntryTerms<D>(type: string, entries: ContentEntry<D>[]): Promise<void> {\n\tif (entries.length === 0) return;\n\n\ttry {\n\t\tconst { getAllTermsForEntries } = await import(\"./taxonomies/index.js\");\n\n\t\tconst ids = entries.map((e) => dataStr(entryData(e), \"id\")).filter(Boolean);\n\t\tif (ids.length === 0) return;\n\n\t\tconst termsMap = await getAllTermsForEntries(type, ids);\n\n\t\tfor (const entry of entries) {\n\t\t\tconst data = entryData(entry);\n\t\t\tconst dbId = dataStr(data, \"id\");\n\t\t\tif (!dbId) continue;\n\n\t\t\tdata.terms = termsMap.get(dbId) ?? {};\n\t\t}\n\t} catch (err) {\n\t\t// Only swallow \"table not found\" errors from pre-migration databases.\n\t\t// Matches SQLite/D1 (\"no such table\") and PostgreSQL (\"relation/table\n\t\t// ... does not exist\") via the shared helper.\n\t\tif (!isMissingTableError(err)) {\n\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\tconsole.warn(\"[emdash] Failed to hydrate terms:\", msg);\n\t\t}\n\t}\n}\n\n/**\n * Translation summary for a single locale variant\n */\nexport interface TranslationSummary {\n\t/** Content item ID */\n\tid: string;\n\t/** Locale code (e.g. \"en\", \"fr\") */\n\tlocale: string;\n\t/** URL slug */\n\tslug: string | null;\n\t/** Current status */\n\tstatus: string;\n}\n\n/**\n * Result from getTranslations\n */\nexport interface TranslationsResult {\n\t/** The translation group ID (shared across locales) */\n\ttranslationGroup: string;\n\t/** All locale variants in this group */\n\ttranslations: TranslationSummary[];\n\t/** Error if the query failed */\n\terror?: Error;\n}\n\n/**\n * Get all translations of a content item.\n *\n * Given a content entry, returns all locale variants that share the same\n * translation group. This is useful for building language switcher UI.\n *\n * @example\n * ```ts\n * import { getEmDashEntry, getTranslations } from \"emdash\";\n *\n * const { entry: post } = await getEmDashEntry(\"posts\", \"hello-world\", { locale: \"en\" });\n * const { translations } = await getTranslations(\"posts\", post.data.id);\n * // translations = [{ id: \"...\", locale: \"en\", slug: \"hello-world\", status: \"published\" }, ...]\n * ```\n */\nexport async function getTranslations(type: string, id: string): Promise<TranslationsResult> {\n\ttry {\n\t\tconst db = (await import(\"./loader.js\")).getDb;\n\t\tconst dbInstance = await db();\n\t\tconst { ContentRepository } = await import(\"./database/repositories/content.js\");\n\t\tconst repo = new ContentRepository(dbInstance);\n\n\t\t// Find the item to get its translation group\n\t\tconst item = await repo.findByIdOrSlug(type, id);\n\t\tif (!item) {\n\t\t\treturn {\n\t\t\t\ttranslationGroup: \"\",\n\t\t\t\ttranslations: [],\n\t\t\t\terror: new Error(`Content item not found: ${id}`),\n\t\t\t};\n\t\t}\n\n\t\tconst group = item.translationGroup || item.id;\n\t\tconst translations = await repo.findTranslations(type, group);\n\n\t\treturn {\n\t\t\ttranslationGroup: group,\n\t\t\ttranslations: translations.map((t) => ({\n\t\t\t\tid: t.id,\n\t\t\t\tlocale: t.locale || \"en\",\n\t\t\t\tslug: t.slug,\n\t\t\t\tstatus: t.status,\n\t\t\t})),\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\ttranslationGroup: \"\",\n\t\t\ttranslations: [],\n\t\t\terror: error instanceof Error ? error : new Error(String(error)),\n\t\t};\n\t}\n}\n\n/**\n * Result from resolveEmDashPath\n */\nexport interface ResolvePathResult<T = Record<string, unknown>> {\n\t/** The matched entry */\n\tentry: ContentEntry<T>;\n\t/** The collection slug that matched */\n\tcollection: string;\n\t/** Extracted parameters from the URL pattern (e.g. { slug: \"my-post\" }) */\n\tparams: Record<string, string>;\n}\n\n/** Matches `{paramName}` placeholders in URL patterns */\nconst URL_PARAM_PATTERN = /\\{(\\w+)\\}/g;\n\n/** Convert a URL pattern like \"/blog/{slug}\" to a regex and param name list */\nfunction patternToRegex(pattern: string): { regex: RegExp; paramNames: string[] } {\n\tconst paramNames: string[] = [];\n\tconst regexStr = pattern.replace(URL_PARAM_PATTERN, (_match, name: string) => {\n\t\tparamNames.push(name);\n\t\treturn \"([^/]+)\";\n\t});\n\treturn { regex: new RegExp(`^${regexStr}$`), paramNames };\n}\n\n/** Cached compiled URL patterns for resolveEmDashPath */\ninterface CachedPattern {\n\tslug: string;\n\tregex: RegExp;\n\tparamNames: string[];\n}\nlet cachedUrlPatterns: CachedPattern[] | null = null;\n\n/**\n * Invalidate the cached URL patterns used by resolveEmDashPath.\n * Call when collection URL patterns change (schema updates).\n */\nexport function invalidateUrlPatternCache(): void {\n\tcachedUrlPatterns = null;\n}\n\n/**\n * Resolve a URL path to a content entry by matching against collection URL patterns.\n *\n * Loads all collections with a `urlPattern` set, converts each pattern to a regex,\n * and tests the given path. On match, extracts the slug and fetches the entry.\n *\n * @example\n * ```ts\n * import { resolveEmDashPath } from \"emdash\";\n *\n * // Given pages with urlPattern \"/{slug}\" and posts with \"/blog/{slug}\":\n * const result = await resolveEmDashPath(\"/blog/hello-world\");\n * if (result) {\n * console.log(result.collection); // \"posts\"\n * console.log(result.params.slug); // \"hello-world\"\n * console.log(result.entry.data); // post data\n * }\n * ```\n */\nexport async function resolveEmDashPath<T = Record<string, unknown>>(\n\tpath: string,\n): Promise<ResolvePathResult<T> | null> {\n\t// Build and cache compiled patterns on first call\n\tif (!cachedUrlPatterns) {\n\t\tconst { getDb } = await import(\"./loader.js\");\n\t\tconst { SchemaRegistry } = await import(\"./schema/registry.js\");\n\t\tconst db = await getDb();\n\t\tconst registry = new SchemaRegistry(db);\n\t\tconst collections = await registry.listCollections();\n\n\t\tcachedUrlPatterns = [];\n\t\tfor (const collection of collections) {\n\t\t\tif (!collection.urlPattern) continue;\n\t\t\tconst { regex, paramNames } = patternToRegex(collection.urlPattern);\n\t\t\tcachedUrlPatterns.push({ slug: collection.slug, regex, paramNames });\n\t\t}\n\t}\n\n\tfor (const pattern of cachedUrlPatterns) {\n\t\tconst match = path.match(pattern.regex);\n\t\tif (!match) continue;\n\n\t\t// Extract params\n\t\tconst params: Record<string, string> = {};\n\t\tfor (let i = 0; i < pattern.paramNames.length; i++) {\n\t\t\tparams[pattern.paramNames[i]] = match[i + 1];\n\t\t}\n\n\t\t// Look up entry by slug (most common pattern)\n\t\tconst slug = params.slug;\n\t\tif (!slug) continue;\n\n\t\tconst { entry } = await getEmDashEntry<string, T>(pattern.slug, slug);\n\t\tif (entry) {\n\t\t\treturn { entry, collection: pattern.slug, params };\n\t\t}\n\t}\n\n\treturn null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAoCA,SAAgB,eACf,YACA,IACA,SACY;CACZ,MAAM,OAAsB;EAC3B;EACA;EACA,GAAI,SAAS,UAAU,EAAE,QAAQ,QAAQ,QAAQ;EACjD,GAAI,SAAS,YAAY,EAAE,UAAU,MAAM;EAC3C;AAED,QAAO,IAAI,MAAM,EAAE,EAAe;EACjC,IAAI,GAAG,MAAM;AACZ,OAAI,SAAS,SAAU,eAAc,EAAE,mBAAmB,KAAK,UAAU,KAAK,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