@eldrajs/theme-nuxt 0.0.0 → 0.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/CHANGELOG.md +255 -0
- package/LICENSE +21 -0
- package/README.md +323 -1
- package/dist/module.cjs +5 -0
- package/dist/module.d.mts +56 -0
- package/dist/module.d.ts +56 -0
- package/dist/module.json +12 -0
- package/dist/module.mjs +320 -0
- package/dist/runtime/catalog.d.ts +119 -0
- package/dist/runtime/catalog.js +226 -0
- package/dist/runtime/commerce.d.ts +68 -0
- package/dist/runtime/commerce.js +40 -0
- package/dist/runtime/composables/useEldraPage.d.ts +17 -0
- package/dist/runtime/composables/useEldraPage.js +229 -0
- package/dist/runtime/designTokens.d.ts +59 -0
- package/dist/runtime/designTokens.js +55 -0
- package/dist/runtime/drafts.d.ts +3 -0
- package/dist/runtime/drafts.js +89 -0
- package/dist/runtime/links.d.ts +32 -0
- package/dist/runtime/links.js +132 -0
- package/dist/runtime/locale.d.ts +21 -0
- package/dist/runtime/locale.js +9 -0
- package/dist/runtime/localeState.d.ts +52 -0
- package/dist/runtime/localeState.js +48 -0
- package/dist/runtime/locales.d.ts +186 -0
- package/dist/runtime/locales.js +109 -0
- package/dist/runtime/messages.d.ts +59 -0
- package/dist/runtime/messages.js +66 -0
- package/dist/runtime/origins.d.ts +18 -0
- package/dist/runtime/origins.js +28 -0
- package/dist/runtime/plugin.d.ts +3 -0
- package/dist/runtime/plugin.js +83 -0
- package/dist/runtime/resolveRoute.d.ts +81 -0
- package/dist/runtime/resolveRoute.js +166 -0
- package/dist/runtime/routePath.d.ts +31 -0
- package/dist/runtime/routePath.js +7 -0
- package/dist/runtime/siteIconAssets.d.ts +19 -0
- package/dist/runtime/siteIconAssets.js +29 -0
- package/dist/runtime/siteIcons.d.ts +74 -0
- package/dist/runtime/siteIcons.js +96 -0
- package/dist/runtime/staticRoutes.d.ts +14 -0
- package/dist/runtime/staticRoutes.js +26 -0
- package/dist/types.d.mts +7 -0
- package/dist/types.d.ts +7 -0
- package/package.json +60 -2
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import {
|
|
2
|
+
buildDynamicRoutePath
|
|
3
|
+
} from "@eldrajs/theme-core";
|
|
4
|
+
import { localeQuery } from "./locale.js";
|
|
5
|
+
const CATALOG_PAGE_SIZE = 100;
|
|
6
|
+
const ACTIVE_STATUS = "ACTIVE";
|
|
7
|
+
export function projectCatalogEntry(kind, doc) {
|
|
8
|
+
if (typeof doc !== "object" || doc === null || Array.isArray(doc)) return null;
|
|
9
|
+
const raw = doc;
|
|
10
|
+
const id = text(raw.id);
|
|
11
|
+
if (id === "") return null;
|
|
12
|
+
return {
|
|
13
|
+
id,
|
|
14
|
+
data: kind === "product" ? productProjection(raw) : collectionProjection(raw)
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function productProjection(raw) {
|
|
18
|
+
return {
|
|
19
|
+
slug: text(raw.slug),
|
|
20
|
+
title: text(raw.title),
|
|
21
|
+
// Rich text: handed to the theme's rich-text renderer unchanged.
|
|
22
|
+
description: raw.description ?? null,
|
|
23
|
+
status: text(raw.status),
|
|
24
|
+
categoryId: optionalText(raw.categoryId),
|
|
25
|
+
tags: stringList(raw.tags),
|
|
26
|
+
variants: list(raw.variants).map((variant) => ({
|
|
27
|
+
sku: text(variant.sku),
|
|
28
|
+
price: optionalNumber(variant.price),
|
|
29
|
+
compareAtPrice: optionalNumber(variant.compareAtPrice),
|
|
30
|
+
optionValues: list(variant.optionValues).map((value) => ({
|
|
31
|
+
id: text(value.id),
|
|
32
|
+
name: text(value.name),
|
|
33
|
+
optionId: text(value.optionId),
|
|
34
|
+
optionValueId: text(value.optionValueId)
|
|
35
|
+
}))
|
|
36
|
+
})),
|
|
37
|
+
images: mediaList(raw.mediaLinks)
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
function collectionProjection(raw) {
|
|
41
|
+
return {
|
|
42
|
+
slug: text(raw.slug),
|
|
43
|
+
title: text(raw.title),
|
|
44
|
+
description: optionalText(raw.description),
|
|
45
|
+
productCount: typeof raw.productCount === "number" ? raw.productCount : 0,
|
|
46
|
+
image: mediaItem(raw.image)
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
const MAX_CATEGORY_DEPTH = 6;
|
|
50
|
+
export function buildCategoryTree(docs) {
|
|
51
|
+
const rows = /* @__PURE__ */ new Map();
|
|
52
|
+
const order = [];
|
|
53
|
+
for (const doc of docs) {
|
|
54
|
+
const id = text(doc.id);
|
|
55
|
+
const slug = text(doc.slug);
|
|
56
|
+
const title = text(doc.title);
|
|
57
|
+
if (id === "" || slug === "" || rows.has(id)) continue;
|
|
58
|
+
const row = { id, slug, title, parentId: optionalText(doc.parentId), raw: doc };
|
|
59
|
+
rows.set(id, row);
|
|
60
|
+
order.push(row);
|
|
61
|
+
}
|
|
62
|
+
const chainOf = (row) => {
|
|
63
|
+
const chain = [];
|
|
64
|
+
const seen = /* @__PURE__ */ new Set([row.id]);
|
|
65
|
+
let parentId = row.parentId;
|
|
66
|
+
for (let depth = 0; depth < MAX_CATEGORY_DEPTH; depth += 1) {
|
|
67
|
+
if (parentId === null) return chain;
|
|
68
|
+
if (seen.has(parentId)) return null;
|
|
69
|
+
const parent = rows.get(parentId);
|
|
70
|
+
if (parent === void 0) return null;
|
|
71
|
+
seen.add(parentId);
|
|
72
|
+
chain.unshift(parent);
|
|
73
|
+
parentId = parent.parentId;
|
|
74
|
+
}
|
|
75
|
+
return null;
|
|
76
|
+
};
|
|
77
|
+
const chains = /* @__PURE__ */ new Map();
|
|
78
|
+
const pathOf = /* @__PURE__ */ new Map();
|
|
79
|
+
for (const row of order) {
|
|
80
|
+
const chain = chainOf(row);
|
|
81
|
+
if (chain === null) continue;
|
|
82
|
+
chains.set(row.id, chain);
|
|
83
|
+
pathOf.set(row.id, [...chain, row].map((level) => level.slug).join("/"));
|
|
84
|
+
}
|
|
85
|
+
const childrenOf = /* @__PURE__ */ new Map();
|
|
86
|
+
for (const row of order) {
|
|
87
|
+
const parentId = row.parentId;
|
|
88
|
+
if (parentId === null || !pathOf.has(row.id) || !pathOf.has(parentId)) continue;
|
|
89
|
+
const siblings = childrenOf.get(parentId);
|
|
90
|
+
if (siblings === void 0) childrenOf.set(parentId, [row]);
|
|
91
|
+
else siblings.push(row);
|
|
92
|
+
}
|
|
93
|
+
const refOf = (row) => ({
|
|
94
|
+
slug: row.slug,
|
|
95
|
+
title: row.title,
|
|
96
|
+
path: pathOf.get(row.id) ?? ""
|
|
97
|
+
});
|
|
98
|
+
const tree = /* @__PURE__ */ new Map();
|
|
99
|
+
for (const row of order) {
|
|
100
|
+
const path = pathOf.get(row.id);
|
|
101
|
+
if (path === void 0 || tree.has(path)) continue;
|
|
102
|
+
tree.set(path, {
|
|
103
|
+
id: row.id,
|
|
104
|
+
slug: row.slug,
|
|
105
|
+
title: row.title,
|
|
106
|
+
path,
|
|
107
|
+
ancestors: (chains.get(row.id) ?? []).map(refOf),
|
|
108
|
+
children: (childrenOf.get(row.id) ?? []).map(refOf),
|
|
109
|
+
raw: row.raw
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
return tree;
|
|
113
|
+
}
|
|
114
|
+
export function projectCategoryNode(node) {
|
|
115
|
+
const description = node.raw.description;
|
|
116
|
+
const productCount = node.raw.productCount;
|
|
117
|
+
return {
|
|
118
|
+
id: node.id,
|
|
119
|
+
data: {
|
|
120
|
+
slug: node.slug,
|
|
121
|
+
title: node.title,
|
|
122
|
+
path: node.path,
|
|
123
|
+
ancestors: node.ancestors.map(plainRef),
|
|
124
|
+
children: node.children.map(plainRef),
|
|
125
|
+
...typeof description === "string" && description !== "" ? { description } : {},
|
|
126
|
+
...typeof productCount === "number" ? { productCount } : {}
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
function plainRef(ref) {
|
|
131
|
+
return { slug: ref.slug, title: ref.title, path: ref.path };
|
|
132
|
+
}
|
|
133
|
+
export function findCategoryByPath(tree, path) {
|
|
134
|
+
return tree.get(path) ?? null;
|
|
135
|
+
}
|
|
136
|
+
export async function loadCatalogEntry(client, kind, slug, locale) {
|
|
137
|
+
const query = localeQuery(locale);
|
|
138
|
+
if (kind === "category") {
|
|
139
|
+
const node = findCategoryByPath(
|
|
140
|
+
buildCategoryTree(await listCatalogDocs(client, "category", locale)),
|
|
141
|
+
slug
|
|
142
|
+
);
|
|
143
|
+
return node === null ? null : projectCategoryNode(node);
|
|
144
|
+
}
|
|
145
|
+
const doc = kind === "product" ? await client.catalog.getProduct(slug, query) : await client.catalog.getCollection(slug, query);
|
|
146
|
+
return projectCatalogEntry(kind, doc);
|
|
147
|
+
}
|
|
148
|
+
export async function listCatalogDocs(client, kind, locale) {
|
|
149
|
+
const listCategories = client.catalog.listCategories?.bind(client.catalog);
|
|
150
|
+
if (kind === "category" && listCategories === void 0) return [];
|
|
151
|
+
const docs = [];
|
|
152
|
+
let page = 1;
|
|
153
|
+
for (; ; ) {
|
|
154
|
+
const query = { page, pageSize: CATALOG_PAGE_SIZE, ...localeQuery(locale) };
|
|
155
|
+
const list2 = kind === "product" ? await client.catalog.listProducts({ ...query, filter: [`status:eq:${ACTIVE_STATUS}`] }) : kind === "collection" ? await client.catalog.listCollections(query) : await listCategories(query);
|
|
156
|
+
docs.push(...list2.data);
|
|
157
|
+
if (list2.meta.hasNext !== true || list2.data.length === 0) return docs;
|
|
158
|
+
page += 1;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
export function catalogDocRoutes(kind, docs, pattern, warn = (message) => console.warn(message)) {
|
|
162
|
+
const paths = [];
|
|
163
|
+
if (kind === "category") {
|
|
164
|
+
for (const node of buildCategoryTree(docs).values()) {
|
|
165
|
+
const path = buildDynamicRoutePath(pattern, node.path);
|
|
166
|
+
if (path === null) {
|
|
167
|
+
warn(
|
|
168
|
+
`[eldra] skipped ${routeLabel(pattern, node.path)}: unusable category path ${JSON.stringify(node.path)}`
|
|
169
|
+
);
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
paths.push(path);
|
|
173
|
+
}
|
|
174
|
+
return paths;
|
|
175
|
+
}
|
|
176
|
+
for (const doc of docs) {
|
|
177
|
+
if (!isActive(doc)) continue;
|
|
178
|
+
const path = buildDynamicRoutePath(pattern, doc.slug);
|
|
179
|
+
if (path === null) {
|
|
180
|
+
warn(
|
|
181
|
+
`[eldra] skipped ${routeLabel(pattern, doc.slug)}: unusable catalog slug ${JSON.stringify(
|
|
182
|
+
text(doc.slug)
|
|
183
|
+
)}`
|
|
184
|
+
);
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
paths.push(path);
|
|
188
|
+
}
|
|
189
|
+
return paths;
|
|
190
|
+
}
|
|
191
|
+
function isActive(doc) {
|
|
192
|
+
const status = doc.status;
|
|
193
|
+
return typeof status !== "string" || status.toUpperCase() === ACTIVE_STATUS;
|
|
194
|
+
}
|
|
195
|
+
function routeLabel(pattern, slug) {
|
|
196
|
+
return `${pattern.replace(/:[^/]*$/, "")}${text(slug)}`;
|
|
197
|
+
}
|
|
198
|
+
function mediaList(value) {
|
|
199
|
+
return list(value).filter((item) => text(item.url) !== "").map((item, index) => ({ item, index })).sort((a, b) => sortOrder(a.item) - sortOrder(b.item) || a.index - b.index).map(({ item }) => ({ url: text(item.url), alt: text(item.altText) }));
|
|
200
|
+
}
|
|
201
|
+
function mediaItem(value) {
|
|
202
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
|
203
|
+
const record = value;
|
|
204
|
+
const url = text(record.url);
|
|
205
|
+
return url === "" ? null : { url, alt: text(record.altText) };
|
|
206
|
+
}
|
|
207
|
+
function sortOrder(item) {
|
|
208
|
+
return typeof item.sortOrder === "number" ? item.sortOrder : Number.MAX_SAFE_INTEGER;
|
|
209
|
+
}
|
|
210
|
+
function list(value) {
|
|
211
|
+
return Array.isArray(value) ? value.filter(
|
|
212
|
+
(item) => typeof item === "object" && item !== null && !Array.isArray(item)
|
|
213
|
+
) : [];
|
|
214
|
+
}
|
|
215
|
+
function stringList(value) {
|
|
216
|
+
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
217
|
+
}
|
|
218
|
+
function text(value) {
|
|
219
|
+
return typeof value === "string" ? value : "";
|
|
220
|
+
}
|
|
221
|
+
function optionalText(value) {
|
|
222
|
+
return typeof value === "string" && value !== "" ? value : null;
|
|
223
|
+
}
|
|
224
|
+
function optionalNumber(value) {
|
|
225
|
+
return typeof value === "number" ? value : null;
|
|
226
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { EldraFeatureClient, EldraOrganizationCommerce } from '@eldrajs/sdk';
|
|
2
|
+
/**
|
|
3
|
+
* What the store sells in, as it reaches a theme on `runtimeConfig.public.eldra.commerce`:
|
|
4
|
+
* `{ currency, taxInclusivePricing, defaultTaxRate }`, or `null`.
|
|
5
|
+
*
|
|
6
|
+
* Published as `@eldrajs/theme-nuxt/commerce`, so a theme reading that key types it from here
|
|
7
|
+
* instead of hand-writing the record — it is the public contract of a public runtime-config key,
|
|
8
|
+
* and the first field added to it should not have to be added again in every theme. (Its own
|
|
9
|
+
* subpath rather than the package root: `nuxt-module-build` generates the root's `.d.mts` itself,
|
|
10
|
+
* and that file carries the module and `ModuleOptions` only.)
|
|
11
|
+
*
|
|
12
|
+
* It is the gateway's own organisation `commerce` record unchanged, so the shape is declared **once**
|
|
13
|
+
* — in `@eldrajs/sdk`, which is where the read comes from — and aliased here under the name the
|
|
14
|
+
* runtime config uses.
|
|
15
|
+
*
|
|
16
|
+
* Read **once, at build**, from the organisation the site is deployed for
|
|
17
|
+
* (`@eldrajs/sdk`'s `features.getCommerce()`), because every price a prerendered page carries is
|
|
18
|
+
* formatted against it: a value fetched in the browser would mean every amount on a static page
|
|
19
|
+
* rendering without a currency first and reflowing a tick later.
|
|
20
|
+
*
|
|
21
|
+
* `null` is a real answer, not a failure: a store that has not configured commerce publishes
|
|
22
|
+
* nothing, and a theme that knows that can render a price as a plain number instead of guessing a
|
|
23
|
+
* symbol. The module itself adds **no override** — the platform is the one source for this, and a
|
|
24
|
+
* site whose own currency setting disagreed with the catalogue would relabel real amounts rather
|
|
25
|
+
* than correct them.
|
|
26
|
+
*/
|
|
27
|
+
export type StoreCommerce = EldraOrganizationCommerce;
|
|
28
|
+
/**
|
|
29
|
+
* The slice of an `@eldrajs/sdk` client this read needs — a whole `EldraClient` satisfies it.
|
|
30
|
+
* Narrow on purpose: it is what lets the module's own tests hand `readStoreCommerce` a client that
|
|
31
|
+
* answers, omits or throws with no gateway anywhere near them.
|
|
32
|
+
*/
|
|
33
|
+
export interface StoreCommerceReader {
|
|
34
|
+
features: Pick<EldraFeatureClient, 'getCommerce'>;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The one line a theme's build prints when it could not learn the store's currency. It says *plain
|
|
38
|
+
* numbers* because that is what a theme with no currency has to render: there is no code to print
|
|
39
|
+
* either — the "number plus its code" shape belongs to a currency that was published but is
|
|
40
|
+
* unusable, which this warning is never about.
|
|
41
|
+
*/
|
|
42
|
+
export declare const NO_CURRENCY_WARNING = "[eldra] the store publishes no currency \u2014 prices render as plain numbers";
|
|
43
|
+
/**
|
|
44
|
+
* How long the build waits for the answer. A bound rather than none, because this read is
|
|
45
|
+
* optional: the page and route-template reads a prerender depends on may hang until the gateway
|
|
46
|
+
* answers or fails, but a currency nobody can fetch must not be the reason a deploy never
|
|
47
|
+
* finishes.
|
|
48
|
+
*
|
|
49
|
+
* Exported so the test that proves the bound can assert the value rather than restate it.
|
|
50
|
+
*/
|
|
51
|
+
export declare const READ_TIMEOUT_MS = 10000;
|
|
52
|
+
/**
|
|
53
|
+
* The store's commerce settings for `runtimeConfig.public.eldra`, or `null`.
|
|
54
|
+
*
|
|
55
|
+
* Fail-soft by construction: a gateway that cannot be reached, a read that times out, a response
|
|
56
|
+
* that is not the shape the gateway documents and a store with no commerce at all all end the same
|
|
57
|
+
* way — `null`, **exactly one** warning, and a build that finishes. A theme must stay deployable
|
|
58
|
+
* while the platform is having a bad afternoon, and the only thing lost is a currency symbol.
|
|
59
|
+
*
|
|
60
|
+
* When the read itself failed, that one warning carries the cause: "not configured" and
|
|
61
|
+
* "refused or unreachable" are different problems to whoever is reading the build log, and only
|
|
62
|
+
* the second is a mistake someone can fix. It is still one line, so a build log cannot be read as
|
|
63
|
+
* reporting two separate faults.
|
|
64
|
+
*
|
|
65
|
+
* `reader` is `null` for a site built without gateway credentials (a scaffolded theme nobody has
|
|
66
|
+
* connected yet, a CI build with no secrets). Same outcome, same single warning, no request.
|
|
67
|
+
*/
|
|
68
|
+
export declare function readStoreCommerce(reader: StoreCommerceReader | null, warn?: (message: string) => void): Promise<StoreCommerce | null>;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export const NO_CURRENCY_WARNING = "[eldra] the store publishes no currency \u2014 prices render as plain numbers";
|
|
2
|
+
export const READ_TIMEOUT_MS = 1e4;
|
|
3
|
+
export async function readStoreCommerce(reader, warn = console.warn) {
|
|
4
|
+
const read = reader === null ? { commerce: null, cause: null } : await readOrNull(reader);
|
|
5
|
+
if (read.commerce === null) {
|
|
6
|
+
warn(read.cause === null ? NO_CURRENCY_WARNING : `${NO_CURRENCY_WARNING} (${read.cause})`);
|
|
7
|
+
return null;
|
|
8
|
+
}
|
|
9
|
+
return read.commerce;
|
|
10
|
+
}
|
|
11
|
+
async function readOrNull(reader) {
|
|
12
|
+
const controller = new AbortController();
|
|
13
|
+
const timer = setTimeout(
|
|
14
|
+
() => controller.abort(new Error(`timed out after ${READ_TIMEOUT_MS}ms`)),
|
|
15
|
+
READ_TIMEOUT_MS
|
|
16
|
+
);
|
|
17
|
+
let answer;
|
|
18
|
+
try {
|
|
19
|
+
answer = await reader.features.getCommerce(void 0, { signal: controller.signal });
|
|
20
|
+
} catch (error) {
|
|
21
|
+
return { commerce: null, cause: `the organisation read failed: ${describe(error)}` };
|
|
22
|
+
} finally {
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
}
|
|
25
|
+
const commerce = toStoreCommerce(answer);
|
|
26
|
+
return {
|
|
27
|
+
commerce,
|
|
28
|
+
cause: commerce === null && answer !== null && answer !== void 0 ? "the organisation published an incomplete commerce record" : null
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function toStoreCommerce(value) {
|
|
32
|
+
if (value === null || typeof value !== "object") return null;
|
|
33
|
+
const { currency, taxInclusivePricing, defaultTaxRate } = value;
|
|
34
|
+
if (typeof currency !== "string" || currency === "") return null;
|
|
35
|
+
if (typeof taxInclusivePricing !== "boolean" || typeof defaultTaxRate !== "number") return null;
|
|
36
|
+
return { currency, taxInclusivePricing, defaultTaxRate };
|
|
37
|
+
}
|
|
38
|
+
function describe(error) {
|
|
39
|
+
return error instanceof Error ? error.message : String(error);
|
|
40
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type EntryDoc } from '@eldrajs/theme-core';
|
|
2
|
+
import { type ComputedRef, type Ref } from 'vue';
|
|
3
|
+
import type { CatalogRouteRef } from '../catalog.js';
|
|
4
|
+
import { type ResolvedEldraRoute } from '../resolveRoute.js';
|
|
5
|
+
export declare function useEldraPage(): {
|
|
6
|
+
page: Ref<EntryDoc | null>;
|
|
7
|
+
template: Ref<EntryDoc | null>;
|
|
8
|
+
entry: Ref<EntryDoc | null>;
|
|
9
|
+
catalog: ComputedRef<CatalogRouteRef | null>;
|
|
10
|
+
layout: ComputedRef<unknown | null>;
|
|
11
|
+
blocks: ComputedRef<EntryDoc[]>;
|
|
12
|
+
reusableComponentProjection: ComputedRef<unknown | undefined>;
|
|
13
|
+
links: ComputedRef<ResolvedEldraRoute['links']>;
|
|
14
|
+
pending: Ref<boolean>;
|
|
15
|
+
/** Readonly: it is derived from the resolution (`ResolvedEldraRoute.error`), not held here. */
|
|
16
|
+
error: ComputedRef<string | null>;
|
|
17
|
+
};
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { EldraClientError } from "@eldrajs/theme-core";
|
|
2
|
+
import { useEldra } from "@eldrajs/theme-vue";
|
|
3
|
+
import {
|
|
4
|
+
clearNuxtData,
|
|
5
|
+
loadPayload,
|
|
6
|
+
setResponseStatus,
|
|
7
|
+
useAsyncData,
|
|
8
|
+
useRequestEvent,
|
|
9
|
+
useRoute,
|
|
10
|
+
useRouter,
|
|
11
|
+
useRuntimeConfig
|
|
12
|
+
} from "nuxt/app";
|
|
13
|
+
import { computed, getCurrentInstance, ref, watch } from "vue";
|
|
14
|
+
import { overlayPreviewDrafts } from "../drafts.js";
|
|
15
|
+
import { normalizeLocale } from "../locale.js";
|
|
16
|
+
import {
|
|
17
|
+
localeForPath,
|
|
18
|
+
resolveLocaleRouting,
|
|
19
|
+
resolveStoreLocales,
|
|
20
|
+
stripLocalePrefix
|
|
21
|
+
} from "../locales.js";
|
|
22
|
+
import { isStudioPreviewFrame } from "../origins.js";
|
|
23
|
+
import { EMPTY_ELDRA_ROUTE, resolveEldraRoute } from "../resolveRoute.js";
|
|
24
|
+
import { canonicalRoutePath } from "../routePath.js";
|
|
25
|
+
import { knownPrerenderedRoutes, prerenderedRoutes } from "../staticRoutes.js";
|
|
26
|
+
const PAGE_KEY_PREFIX = "eldra-page:";
|
|
27
|
+
const routeDataKey = (path) => `${PAGE_KEY_PREFIX}${path}`;
|
|
28
|
+
export function useEldraPage() {
|
|
29
|
+
const route = useRoute();
|
|
30
|
+
const activePath = createActivePath(route, useRouter());
|
|
31
|
+
const requestEvent = useRequestEvent();
|
|
32
|
+
const ctx = useEldra();
|
|
33
|
+
const cfg = useRuntimeConfig().public.eldra;
|
|
34
|
+
const routing = resolveLocaleRouting(resolveStoreLocales(cfg.locales), cfg.locale);
|
|
35
|
+
const routeTarget = (path) => ({
|
|
36
|
+
path: stripLocalePrefix(path, routing),
|
|
37
|
+
locale: localeForPath(path, routing)
|
|
38
|
+
});
|
|
39
|
+
const runtimeLocale = (path) => normalizeLocale(ctx.preview.active ? ctx.preview.locale : null) ?? routeTarget(path).locale;
|
|
40
|
+
const buildAnswersRoutes = () => !ctx.preview.active && !isStudioPreviewFrame(cfg.studioOrigins);
|
|
41
|
+
const cachedRoute = (key, nuxtApp, context) => {
|
|
42
|
+
if (context.cause !== "refresh:manual" && context.cause !== "refresh:hook") {
|
|
43
|
+
const fromBuild = nuxtApp.isHydrating ? nuxtApp.payload.data[key] : nuxtApp.static.data[key];
|
|
44
|
+
if (fromBuild !== void 0) return fromBuild;
|
|
45
|
+
}
|
|
46
|
+
if (!buildAnswersRoutes()) return void 0;
|
|
47
|
+
const prerendered = knownPrerenderedRoutes();
|
|
48
|
+
if (prerendered === null) return void 0;
|
|
49
|
+
return prerendered.has(key.slice(PAGE_KEY_PREFIX.length)) ? void 0 : EMPTY_ELDRA_ROUTE;
|
|
50
|
+
};
|
|
51
|
+
const PREVIEW_AUTH_RECOVERY_GRACE_MS = 1e4;
|
|
52
|
+
let heldPreviewAuthFailure = null;
|
|
53
|
+
const holdPreviewAuthFailure = (cause) => {
|
|
54
|
+
if (!ctx.preview.active) return false;
|
|
55
|
+
if (!(cause instanceof EldraClientError) || cause.status !== 401) return false;
|
|
56
|
+
const tokenRevision = ctx.preview.tokenRevision;
|
|
57
|
+
const now = Date.now();
|
|
58
|
+
if (heldPreviewAuthFailure === null) {
|
|
59
|
+
heldPreviewAuthFailure = { tokenRevision, at: now };
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
if (tokenRevision > heldPreviewAuthFailure.tokenRevision) return false;
|
|
63
|
+
return now - heldPreviewAuthFailure.at <= PREVIEW_AUTH_RECOVERY_GRACE_MS;
|
|
64
|
+
};
|
|
65
|
+
const hasCredentials = cfg.gatewayUrl !== "" && cfg.orgId !== "";
|
|
66
|
+
const reportServerFailure = () => {
|
|
67
|
+
if (!import.meta.server || requestEvent === void 0) return;
|
|
68
|
+
setResponseStatus(requestEvent, 500, "Eldra route resolution failed");
|
|
69
|
+
};
|
|
70
|
+
const resolveRouteOutcome = async () => {
|
|
71
|
+
const path = activePath();
|
|
72
|
+
if (buildAnswersRoutes()) {
|
|
73
|
+
const prerendered = await prerenderedRoutes();
|
|
74
|
+
if (prerendered !== null) {
|
|
75
|
+
if (!prerendered.has(path)) return { route: EMPTY_ELDRA_ROUTE, holdPrevious: false };
|
|
76
|
+
const fromBuild = await prerenderedRouteData(path);
|
|
77
|
+
if (fromBuild !== void 0) return { route: fromBuild, holdPrevious: false };
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
const route2 = await resolveEldraRoute(
|
|
82
|
+
ctx.client,
|
|
83
|
+
cfg,
|
|
84
|
+
routeTarget(path).path,
|
|
85
|
+
runtimeLocale(path)
|
|
86
|
+
);
|
|
87
|
+
heldPreviewAuthFailure = null;
|
|
88
|
+
return { route: route2, holdPrevious: false };
|
|
89
|
+
} catch (cause) {
|
|
90
|
+
if (holdPreviewAuthFailure(cause)) return { route: EMPTY_ELDRA_ROUTE, holdPrevious: true };
|
|
91
|
+
if (!hasCredentials) return { route: EMPTY_ELDRA_ROUTE, holdPrevious: false };
|
|
92
|
+
reportServerFailure();
|
|
93
|
+
return {
|
|
94
|
+
route: {
|
|
95
|
+
...EMPTY_ELDRA_ROUTE,
|
|
96
|
+
error: cause instanceof Error ? cause.message : String(cause)
|
|
97
|
+
},
|
|
98
|
+
holdPrevious: false
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
const resolveCurrentRoute = async () => (await resolveRouteOutcome()).route;
|
|
103
|
+
const { data: resolvedRoute, pending } = useAsyncData(
|
|
104
|
+
() => routeDataKey(activePath()),
|
|
105
|
+
resolveCurrentRoute,
|
|
106
|
+
{
|
|
107
|
+
// The same source the key reads, and the **canonical** path in both (`../routePath.ts`): a
|
|
108
|
+
// static host that answers `/products/x` with a 308 to `/products/x/` makes Nuxt re-navigate
|
|
109
|
+
// between the two during hydration, and watching the raw path would make that a route change
|
|
110
|
+
// — a second gateway resolve, `pending` back to true, and the whole block tree torn down and
|
|
111
|
+
// built again while the answer is in flight.
|
|
112
|
+
watch: [() => activePath()],
|
|
113
|
+
default: () => EMPTY_ELDRA_ROUTE,
|
|
114
|
+
getCachedData: cachedRoute
|
|
115
|
+
}
|
|
116
|
+
);
|
|
117
|
+
const previewResolvedRoute = ref(void 0);
|
|
118
|
+
let previewRefreshRequest = 0;
|
|
119
|
+
const resolvePreviewRoute = () => {
|
|
120
|
+
if (!ctx.preview.active) return;
|
|
121
|
+
const request = ++previewRefreshRequest;
|
|
122
|
+
const path = activePath();
|
|
123
|
+
const activeKey = routeDataKey(path);
|
|
124
|
+
clearNuxtData((key) => key.startsWith(PAGE_KEY_PREFIX) && key !== activeKey);
|
|
125
|
+
void resolveRouteOutcome().then(({ route: route2, holdPrevious }) => {
|
|
126
|
+
if (request !== previewRefreshRequest || path !== activePath()) return;
|
|
127
|
+
if (holdPrevious) return;
|
|
128
|
+
previewResolvedRoute.value = route2;
|
|
129
|
+
});
|
|
130
|
+
};
|
|
131
|
+
watch(() => ctx.preview.refreshRevision, resolvePreviewRoute);
|
|
132
|
+
watch(
|
|
133
|
+
() => ctx.preview.active,
|
|
134
|
+
(active2) => {
|
|
135
|
+
if (active2) resolvePreviewRoute();
|
|
136
|
+
},
|
|
137
|
+
{ immediate: true }
|
|
138
|
+
);
|
|
139
|
+
watch(
|
|
140
|
+
() => activePath(),
|
|
141
|
+
() => {
|
|
142
|
+
previewRefreshRequest += 1;
|
|
143
|
+
previewResolvedRoute.value = void 0;
|
|
144
|
+
}
|
|
145
|
+
);
|
|
146
|
+
const active = computed(
|
|
147
|
+
() => previewResolvedRoute.value ?? resolvedRoute.value ?? EMPTY_ELDRA_ROUTE
|
|
148
|
+
);
|
|
149
|
+
const error = computed(() => active.value.error ?? null);
|
|
150
|
+
const page = computed(() => {
|
|
151
|
+
void ctx.preview.revision;
|
|
152
|
+
return overlayPreviewDrafts(
|
|
153
|
+
active.value.page,
|
|
154
|
+
ctx.preview.drafts,
|
|
155
|
+
ctx.preview.draftSchemaApiIds
|
|
156
|
+
);
|
|
157
|
+
});
|
|
158
|
+
const template = computed(
|
|
159
|
+
() => overlayPreviewDrafts(active.value.template, ctx.preview.drafts, ctx.preview.draftSchemaApiIds)
|
|
160
|
+
);
|
|
161
|
+
const entry = computed(() => overlayEntryDraft(active.value.entry, ctx.preview.drafts));
|
|
162
|
+
const catalog = computed(() => active.value.catalog);
|
|
163
|
+
const linkState = computed(
|
|
164
|
+
() => active.value.links ?? { pages: [], templates: [], targets: /* @__PURE__ */ new Map() }
|
|
165
|
+
);
|
|
166
|
+
watch(
|
|
167
|
+
linkState,
|
|
168
|
+
(links) => {
|
|
169
|
+
ctx.links.pages = links.pages;
|
|
170
|
+
ctx.links.templates = links.templates;
|
|
171
|
+
ctx.links.targets = links.targets;
|
|
172
|
+
},
|
|
173
|
+
{ immediate: true }
|
|
174
|
+
);
|
|
175
|
+
const layout = computed(
|
|
176
|
+
() => template.value?.data.layout ?? page.value?.data.layout ?? null
|
|
177
|
+
);
|
|
178
|
+
const blocks = computed(() => {
|
|
179
|
+
const raw = template.value?.data.blocks ?? page.value?.data.blocks;
|
|
180
|
+
return Array.isArray(raw) ? raw.filter(isEntryDoc) : [];
|
|
181
|
+
});
|
|
182
|
+
const reusableComponentProjection = computed(
|
|
183
|
+
() => page.value?.reusableComponentProjection ?? template.value?.reusableComponentProjection
|
|
184
|
+
);
|
|
185
|
+
return {
|
|
186
|
+
page,
|
|
187
|
+
template,
|
|
188
|
+
entry,
|
|
189
|
+
catalog,
|
|
190
|
+
layout,
|
|
191
|
+
blocks,
|
|
192
|
+
reusableComponentProjection,
|
|
193
|
+
links: linkState,
|
|
194
|
+
pending,
|
|
195
|
+
error
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
async function prerenderedRouteData(path) {
|
|
199
|
+
try {
|
|
200
|
+
const payload = await loadPayload(path);
|
|
201
|
+
const data = payload?.data;
|
|
202
|
+
const value = data?.[routeDataKey(path)];
|
|
203
|
+
return value === void 0 ? void 0 : value;
|
|
204
|
+
} catch {
|
|
205
|
+
return void 0;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function createActivePath(route, router) {
|
|
209
|
+
const committed = () => canonicalRoutePath(router.currentRoute.value.path);
|
|
210
|
+
if (getCurrentInstance() === null) return committed;
|
|
211
|
+
let pinned = committed();
|
|
212
|
+
return () => {
|
|
213
|
+
const settled = canonicalRoutePath(route.path);
|
|
214
|
+
if (pinned === null) return settled;
|
|
215
|
+
if (settled === pinned) {
|
|
216
|
+
pinned = null;
|
|
217
|
+
return settled;
|
|
218
|
+
}
|
|
219
|
+
return pinned;
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
function overlayEntryDraft(entry, drafts) {
|
|
223
|
+
if (entry === null) return null;
|
|
224
|
+
const draft = drafts[entry.id];
|
|
225
|
+
return draft === void 0 ? entry : { ...entry, data: { ...entry.data, ...draft } };
|
|
226
|
+
}
|
|
227
|
+
function isEntryDoc(value) {
|
|
228
|
+
return typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.data === "object" && value.data !== null;
|
|
229
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { EldraClient } from '@eldrajs/sdk';
|
|
2
|
+
import { type ThemeDesignTokens } from '@eldrajs/theme-core';
|
|
3
|
+
/**
|
|
4
|
+
* Re-exported from `@eldrajs/theme-core` under the name this package's own reads use, the same way
|
|
5
|
+
* `./commerce.ts`/`./locales.ts` alias the SDK's organisation types and `./messages.ts` aliases
|
|
6
|
+
* `ThemeMessages`.
|
|
7
|
+
*/
|
|
8
|
+
export type { ThemeDesignTokens };
|
|
9
|
+
/**
|
|
10
|
+
* The slice of an `@eldrajs/sdk` client this read needs — a whole `EldraClient` satisfies it.
|
|
11
|
+
* Narrow on purpose, like `ThemeMessagesReader`: it is what lets this read's own tests hand it a
|
|
12
|
+
* client that answers, omits or throws with no gateway anywhere near them.
|
|
13
|
+
*
|
|
14
|
+
* `request` rather than a `features.*` method: the public route this reads
|
|
15
|
+
* (`GET /site/v1/design-tokens`) is a **site**-module read, not an organisation-feature one, so
|
|
16
|
+
* there is no typed `EldraFeatureClient` method for it to call through — the client's own generic
|
|
17
|
+
* escape hatch carries the same base URL, org header and retry policy every other read here uses.
|
|
18
|
+
*/
|
|
19
|
+
export interface DesignTokensReader {
|
|
20
|
+
request: EldraClient['request'];
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The one line a build prints when it could not read the platform's design-token overrides. Said
|
|
24
|
+
* unconditionally whenever the read comes back `null` — absent gateway credentials included — the
|
|
25
|
+
* same discipline `THEME_MESSAGES_WARNING`/`NO_CURRENCY_WARNING` follow and for the same reason:
|
|
26
|
+
* "serving the theme's own tokens" is the real, useful thing to know happened, not a fault to hide.
|
|
27
|
+
*/
|
|
28
|
+
export declare const DESIGN_TOKENS_WARNING = "[eldra] could not read the platform\u2019s design-token overrides \u2014 serving the theme\u2019s own tokens";
|
|
29
|
+
/**
|
|
30
|
+
* How long the build waits for the answer. A bound rather than none, for the same reason
|
|
31
|
+
* `messages.ts`/`commerce.ts`/`locales.ts` have one: this read is optional, and a design-token
|
|
32
|
+
* override nobody can fetch must not be the reason a deploy never finishes.
|
|
33
|
+
*
|
|
34
|
+
* Exported so the test that proves the bound can assert the value rather than restate it.
|
|
35
|
+
*/
|
|
36
|
+
export declare const READ_TIMEOUT_MS = 10000;
|
|
37
|
+
/**
|
|
38
|
+
* The platform's resolved design-token catalog for the build-time merge, or `null`.
|
|
39
|
+
*
|
|
40
|
+
* Fail-soft by construction, exactly like `readThemeMessages`: a gateway that cannot be reached, a
|
|
41
|
+
* read that times out, a response that is not the shape the gateway documents and a site built with
|
|
42
|
+
* no gateway credentials at all end the same way — `null` and **one** warning — so a theme keeps
|
|
43
|
+
* deploying while serving its own tokens.
|
|
44
|
+
*/
|
|
45
|
+
export declare function readDesignTokens(reader: DesignTokensReader | null, warn?: (message: string) => void): Promise<ThemeDesignTokens | null>;
|
|
46
|
+
/**
|
|
47
|
+
* The platform's design-token catalog as it reaches the running site on
|
|
48
|
+
* `runtimeConfig.public.eldra.designTokens` — already `normalizeThemeDesignTokens`'d at build time
|
|
49
|
+
* (this is `readDesignTokens`'s own answer, round-tripped through the runtime config payload), or
|
|
50
|
+
* `null`.
|
|
51
|
+
*
|
|
52
|
+
* Re-validates rather than trusting the payload outright, for the same reason
|
|
53
|
+
* `toStoreLocales`/`resolveStoreLocales` do: this is also what reads the value back out in the
|
|
54
|
+
* browser, where it arrives as whatever Nitro serialised — `''` for an absent one, same as
|
|
55
|
+
* `commerce`/`locale`. A value that fails the theme's own validation is treated exactly like an
|
|
56
|
+
* absent one, so the runtime plugin's own fallback to the manifest's tokens is the only thing that
|
|
57
|
+
* ever reaches `context.designTokens`.
|
|
58
|
+
*/
|
|
59
|
+
export declare function resolveSiteDesignTokens(value: unknown): ThemeDesignTokens | null;
|