@nuvler/cli 0.5.3 → 0.5.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nuvler/cli",
3
- "version": "0.5.3",
3
+ "version": "0.5.4",
4
4
  "description": "CLI oficial para criação, validação, preview e empacotamento de temas Nuvler",
5
5
  "type": "module",
6
6
  "bin": {
@@ -11,6 +11,11 @@ import type {
11
11
  import type { ThemePagination, ThemeProduct, ThemeRuntimeSdk } from "@nuvler/theme-sdk";
12
12
  import ActiveTheme from "virtual:nuvler-active-theme";
13
13
  import context from "virtual:nuvler-theme-context";
14
+ import { classifyPreviewPath } from "./preview-path.mjs";
15
+
16
+ class PreviewHttpError extends Error {
17
+ constructor(public status: number) { super(`HTTP ${status}`); }
18
+ }
14
19
 
15
20
  function PreviewImage({ image, fallbackAlt, className }: ThemeImageProps) {
16
21
  if (!image?.url) return <span className={`store-image-placeholder theme-image-placeholder ${className ?? ""}`} aria-hidden="true"><span>N</span></span>;
@@ -68,7 +73,7 @@ async function previewApi<T>(path: string): Promise<T> {
68
73
  const response = await fetch(`/__nuvler-api/${path.replace(/^\/+/, "")}`, {
69
74
  headers: { accept: "application/json" },
70
75
  });
71
- if (!response.ok) throw new Error(`HTTP ${response.status}`);
76
+ if (!response.ok) throw new PreviewHttpError(response.status);
72
77
  return response.json() as Promise<T>;
73
78
  }
74
79
 
@@ -93,6 +98,7 @@ function routeFromLocalData(url: URL): ThemeRoute | null {
93
98
  function PreviewApp() {
94
99
  const [route, setRoute] = useState<ThemeRoute>({ type: "loading", pathname: window.location.pathname });
95
100
  const requestId = useRef(0);
101
+ const [routeError, setRouteError] = useState<string | null>(null);
96
102
 
97
103
  useEffect(() => {
98
104
  const favicon = document.querySelector<HTMLLinkElement>('link[rel~="icon"]');
@@ -101,26 +107,26 @@ function PreviewApp() {
101
107
 
102
108
  const loadRoute = useCallback(async (url: URL) => {
103
109
  const currentRequest = ++requestId.current;
110
+ setRouteError(null);
104
111
  const localRoute = routeFromLocalData(url);
105
112
  if (localRoute) { setRoute(localRoute); return; }
106
113
  setRoute({ type: "loading", pathname: url.pathname });
107
114
  try {
108
- if (url.pathname.startsWith("/produto/")) {
109
- const slug = decodeURIComponent(url.pathname.slice("/produto/".length));
115
+ const target = classifyPreviewPath(url.pathname);
116
+ if (target.type === "product") {
117
+ const slug = target.slug;
110
118
  const product = normalizeProduct(await previewApi<unknown>(`products/${encodeURIComponent(slug)}`));
111
119
  if (currentRequest === requestId.current) setRoute({ type: "product", product });
112
120
  return;
113
121
  }
114
- if (url.pathname.split("/").filter(Boolean).length === 1) {
115
- const slug = decodeURIComponent(url.pathname.slice(1));
122
+ if (target.type === "page") {
123
+ const slug = target.slug;
116
124
  const page = await previewApi<{ title: string; slug: string; content: { schemaVersion: 1; time?: number; version?: string; blocks: Array<{ id?: string; type: string; data: Record<string, unknown> }> } }>(`pages/${encodeURIComponent(slug)}`);
117
125
  if (currentRequest === requestId.current) setRoute({ type: "page", title: page.title, slug: page.slug, content: page.content });
118
126
  return;
119
127
  }
120
- if (url.pathname === "/produtos" || url.pathname.startsWith("/categoria/")) {
121
- const categoryPath = url.pathname.startsWith("/categoria/")
122
- ? url.pathname.slice("/categoria/".length).split("/").filter(Boolean).map(decodeURIComponent)
123
- : [];
128
+ if (target.type === "catalog") {
129
+ const categoryPath = target.categoryPath;
124
130
  const params = new URLSearchParams();
125
131
  const page = Math.max(1, Number(url.searchParams.get("pagina")) || 1);
126
132
  const search = url.searchParams.get("busca")?.trim() || "";
@@ -139,8 +145,15 @@ function PreviewApp() {
139
145
  return;
140
146
  }
141
147
  setRoute({ type: "not-found", pathname: url.pathname });
142
- } catch {
143
- if (currentRequest === requestId.current) setRoute({ type: "not-found", pathname: url.pathname });
148
+ } catch (error) {
149
+ if (currentRequest !== requestId.current) return;
150
+ if (error instanceof PreviewHttpError && error.status === 404) {
151
+ setRoute({ type: "not-found", pathname: url.pathname });
152
+ } else {
153
+ setRouteError(error instanceof PreviewHttpError
154
+ ? `A API respondeu HTTP ${error.status}. Confira a conexão e a configuração do preview.`
155
+ : "Não foi possível carregar o conteúdo. Confira a conexão com a API.");
156
+ }
144
157
  }
145
158
  }, []);
146
159
 
@@ -199,6 +212,13 @@ function PreviewApp() {
199
212
  },
200
213
  }), [loadRoute]);
201
214
 
215
+ if (routeError) return <main role="alert" style={{ padding: "2rem" }}>
216
+ <h1>Não foi possível carregar esta página</h1>
217
+ <p>{routeError}</p>
218
+ <button onClick={() => void loadRoute(new URL(window.location.href))}>Tentar novamente</button>
219
+ <a href="/">Voltar ao início</a>
220
+ </main>;
221
+
202
222
  return <>
203
223
  <ActiveTheme adapters={adapters} context={context} route={route} sdk={sdk} />
204
224
  <PlatformBrand routeKey={`${route.type}:${window.location.pathname}`} />
@@ -0,0 +1,4 @@
1
+ export function classifyPreviewPath(pathname: string):
2
+ | { type: "catalog"; categoryPath: string[] }
3
+ | { type: "page" | "product"; slug: string }
4
+ | { type: "not-found" };
@@ -0,0 +1,14 @@
1
+ export function classifyPreviewPath(pathname) {
2
+ const segments = pathname.split("/").filter(Boolean).map(decodeURIComponent);
3
+ if (segments.length === 1 && segments[0] === "produtos") {
4
+ return { type: "catalog", categoryPath: [] };
5
+ }
6
+ if (segments[0] === "categoria" && segments.length > 1) {
7
+ return { type: "catalog", categoryPath: segments.slice(1) };
8
+ }
9
+ if (segments[0] === "produto" && segments.length === 2) {
10
+ return { type: "product", slug: segments[1] };
11
+ }
12
+ if (segments.length === 1) return { type: "page", slug: segments[0] };
13
+ return { type: "not-found" };
14
+ }
@@ -37,7 +37,7 @@ export function resolvePublicPreviewUrl(requestUrl, apiUrl, store) {
37
37
  }
38
38
 
39
39
  const allowed = (
40
- (segments[0] === "products" && segments.length <= 2)
40
+ (["products", "pages"].includes(segments[0]) && segments.length <= 2)
41
41
  || (segments.length === 1 && singleResourcePaths.has(segments[0] ?? ""))
42
42
  );
43
43
  if (!allowed) return null;