@pramen/cms-editor 0.0.53 → 0.0.54

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": "@pramen/cms-editor",
3
- "version": "0.0.53",
3
+ "version": "0.0.54",
4
4
  "description": "Visual block/page editor for @pramen/cms \u2014 a standalone React SPA that talks to the CMS handlers over HTTP.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -27,7 +27,7 @@ declare global {
27
27
  hidePages?: boolean;
28
28
  /** Extra top-nav links to companion tools the host serves (e.g. a curation page).
29
29
  * Rendered as plain external `<a>` links after the built-in tabs. */
30
- extraNav?: { label: string; href: string }[];
30
+ extraNav?: { label: string; href: string; target?: "_blank" | "_self" }[];
31
31
  /** The wordmark in the topbar, on the Setup screen, and in the browser tab.
32
32
  *
33
33
  * This editor ships as a package an agency deploys FOR ITS CLIENT, so the default
package/src/mount.ts CHANGED
@@ -17,7 +17,8 @@
17
17
 
18
18
  import type { BuzolaNavigateEvent, NavigationAdapter } from "@buzola/router";
19
19
 
20
- /** A mount path must be a chain of path segments rooted at the origin.
20
+ /** A mount path must be a chain of non-empty path segments rooted at the origin, written
21
+ * only in characters that `URL.pathname` returns UNENCODED.
21
22
  *
22
23
  * Rooted, and required to say so: buzola prepends the base path to every href it builds, so
23
24
  * anything that is not already an absolute path resolves somewhere unintended. A leading
@@ -26,10 +27,14 @@ import type { BuzolaNavigateEvent, NavigationAdapter } from "@buzola/router";
26
27
  * mounted. `//cdn.example.com` is rejected for the same reason: protocol-relative, and the
27
28
  * natural product of `"/" + prefix` where the prefix already carried a slash.
28
29
  *
29
- * Segments only, too: a value carrying `?`, `#` or `\` is not a mount path, and each breaks
30
- * routing in its own silent way (a query swallows the rest of every href; a backslash
31
- * resolves off-site while looking local). */
32
- const MOUNT_PATH = /^\/[^/\\?#][^\\?#]*$/;
30
+ * The character set is not a style choice. Every comparison against a mount path in this
31
+ * file and buzola's own `stripBasePath`, which we cannot change is a raw `startsWith`
32
+ * against a `URL.pathname`, which is percent-ENCODED. Admit a character the parser encodes
33
+ * and the two sides can never match: a mount of `/správa` is compared against
34
+ * `/spr%C3%A1va/...` and EVERY in-prefix url reads as off-prefix. So the admitted set is
35
+ * derived from the parser rather than guessed — `"<>^`{}`, backslash, space and everything
36
+ * non-ASCII all encode, and are refused here. */
37
+ const MOUNT_PATH = /^(?:\/[A-Za-z0-9!$%&'()*+,\-.:;=@[\]_|~]+)+$/;
33
38
 
34
39
  /**
35
40
  * Normalize the mount node's declared prefix to buzola's shape: `""` for the origin root,
@@ -43,12 +48,16 @@ const MOUNT_PATH = /^\/[^/\\?#][^\\?#]*$/;
43
48
  */
44
49
  export function resolveBasePath(raw?: string | null): string {
45
50
  const trimmed = (raw ?? "").trim();
46
- if (trimmed === "" || trimmed === "/") return "";
47
- if (!MOUNT_PATH.test(trimmed)) {
51
+ // Trailing slashes come off FIRST, so `MOUNT_PATH` only ever judges the canonical form
52
+ // and a value that is nothing but slashes collapses to the root rather than being warned
53
+ // about as malformed.
54
+ const canonical = trimmed.replace(/\/+$/, "");
55
+ if (canonical === "") return "";
56
+ if (!MOUNT_PATH.test(canonical)) {
48
57
  console.warn(`pramen/cms-editor: ignoring unusable mount path ${JSON.stringify(trimmed)} — mounting at the origin root.`);
49
58
  return "";
50
59
  }
51
- return trimmed.replace(/\/+$/, "");
60
+ return canonical;
52
61
  }
53
62
 
54
63
  /** Read the prefix the shell stamped onto the mount node. */
@@ -86,13 +95,19 @@ export function scopeToBasePath(inner: NavigationAdapter, basePath: string): Nav
86
95
  // Keyed by the caller's handler so `removeEventListener` can find the wrapper it added;
87
96
  // without this the router's `start()` teardown would leave the listener attached.
88
97
  const wrappers = new Map<Handler, Handler>();
98
+ // Spread, not a hand-written list of the seven methods. Enumerating them forwards
99
+ // correctly today but only fails safe by luck: tsc catches a newly REQUIRED member of
100
+ // `NavigationAdapter`, while an OPTIONAL one is silently dropped — and the next planned
101
+ // buzola bump (past ^0.0.12, for `router.leaveApp`) is exactly where such a member would
102
+ // arrive. Overriding the two listener methods is the whole of what this wrapper does.
89
103
  return {
90
- getCurrentURL: () => inner.getCurrentURL(),
91
- navigate: (url, options) => inner.navigate(url, options),
92
- back: () => inner.back(),
93
- forward: () => inner.forward(),
94
- getState: () => inner.getState(),
104
+ ...inner,
95
105
  addEventListener(type, handler) {
106
+ // Adding the same handler twice would attach two wrappers to the inner adapter while
107
+ // the map kept only the second, so the first could never be removed and would keep
108
+ // feeding a torn-down router. Nothing does this today (`Router.start()` mints a fresh
109
+ // closure per call), which is precisely why it should be closed while it is free.
110
+ if (wrappers.has(handler)) return;
96
111
  const wrapper: Handler = (event) => {
97
112
  // A malformed destination is not ours to claim.
98
113
  let pathname: string;
@@ -115,6 +130,51 @@ export function scopeToBasePath(inner: NavigationAdapter, basePath: string): Nav
115
130
  };
116
131
  }
117
132
 
133
+ /**
134
+ * Whether a host-configured nav link may navigate the CURRENT tab.
135
+ *
136
+ * The default for `extraNav` is a new tab, because `_404.tsx` registers the catch-all
137
+ * `/:__notFound+`: an unmounted editor's router matches every same-origin path, so a
138
+ * same-tab click would land on the in-app 404 instead of the tool. `target: "_self"` asks
139
+ * for the co-hosted case, and is honoured only where it cannot strand the user.
140
+ *
141
+ * Lives here, not in the layout, for two reasons: these are the same containment rules
142
+ * `scopeToBasePath` enforces and they belong beside them, and a predicate that decides
143
+ * whether a click escapes the SPA has to be testable without a DOM. `documentUrl` is a
144
+ * PARAMETER rather than a read of `window.location` for the same reason — and because it
145
+ * is the one input that must not be guessed:
146
+ *
147
+ * - Resolve against `location.origin` and a relative href like `"curate"` is judged as
148
+ * `/curate` while the browser navigates to `<current dir>/curate`. Off-prefix by the
149
+ * check, in-prefix in fact, so the link lands on the very 404 this exists to avoid.
150
+ * `?tab=x` and `#top` are the same mistake with an even wider gap.
151
+ * - So the caller passes the document URL the browser will itself resolve against.
152
+ */
153
+ export function opensInSameTab(href: string, target: string | undefined, basePath: string, documentUrl: string): boolean {
154
+ if (target !== "_self") return false;
155
+ let url: URL;
156
+ let docOrigin: string;
157
+ try {
158
+ url = new URL(href, documentUrl);
159
+ docOrigin = new URL(documentUrl).origin;
160
+ } catch {
161
+ return false;
162
+ }
163
+ // `new URL` happily parses `javascript:` and `data:`, and their `pathname` is an opaque
164
+ // string that trivially fails any containment test — so without this they would take the
165
+ // same-tab branch and shed the `rel` that used to confine them. A url with no hierarchical
166
+ // path cannot be reasoned about as "inside or outside the mount"; the answer is no.
167
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
168
+ // Cross-origin ALWAYS escapes on its own — the catch-all can only claim same-origin paths
169
+ // — so it is safe in the same tab whether or not this editor is mounted. That makes an
170
+ // external tool the one configuration that works at the origin root, which is the opposite
171
+ // of what a bare `basePath` check concludes.
172
+ if (url.origin !== docOrigin) return true;
173
+ // Same origin: safe only where the router will not claim it. At the root `isWithinBasePath`
174
+ // is true for everything, so this correctly refuses every same-origin `_self` there.
175
+ return !isWithinBasePath(url.pathname, basePath);
176
+ }
177
+
118
178
  /** The backend the shell declared: which Worker to call, and as which tenant.
119
179
  *
120
180
  * When present these are NOT read from (or written to) localStorage — the server knows
@@ -2,11 +2,12 @@
2
2
  // wrapped around every route via <Outlet />. Tab highlighting is derived from the
3
3
  // current path, so a deep link or refresh lands with the right tab lit.
4
4
 
5
- import { Outlet, useNavigate, useRoute } from "@buzola/router";
5
+ import { Outlet, useNavigate, useRoute, useRouter } from "@buzola/router";
6
6
  import { Button, Card, MoonIcon, SunIcon, Text, Topbar } from "@podoba/react";
7
7
  import { useEffect, useState } from "react";
8
8
  import { useApp } from "../app-context";
9
9
  import { BRAND } from "../brand";
10
+ import { opensInSameTab } from "../mount";
10
11
 
11
12
  const THEME_KEY = "pramen.cms.theme";
12
13
 
@@ -18,8 +19,11 @@ export default function RootLayout() {
18
19
  // Every chrome action here is a way OUT of the current screen, so it runs through that
19
20
  // screen's unsaved-changes guard first (the page editor registers one; with no guard
20
21
  // registered this is a pass-through). In-app navigation fires no `beforeunload`, so
21
- // without this the topbar silently discards unsaved edits. The external `extraNav` links
22
- // open in a new tab and leave nothing behind, so they stay unguarded.
22
+ // without this the topbar silently discards unsaved edits. An `extraNav` link that opens a
23
+ // NEW tab leaves this document alone and needs no guard; one honoured as `_self` is a real
24
+ // cross-document navigation, so it takes the guard too (below). `beforeunload` is not a
25
+ // fallback for it — only `PageEditor` registers one, so a dirty CollectionEditor form would
26
+ // otherwise be discarded with no prompt of any kind.
23
27
  const guarded = (go: () => void) => () => { if (confirmNavigation()) go(); };
24
28
 
25
29
  // Dark mode: podoba tokens flip under `[data-theme="dark"]` — no `dark:` prefixes.
@@ -47,6 +51,13 @@ export default function RootLayout() {
47
51
  // Collections-only deployments hide the block/page builder entirely.
48
52
  const hidePages = typeof window !== "undefined" ? window.PRAMEN_CMS_EDITOR?.hidePages === true : false;
49
53
 
54
+ // See the extraNav comment below. The rules live in `mount.ts` beside the containment they
55
+ // depend on; what this supplies is the URL the BROWSER will resolve a relative href
56
+ // against — the current document, not the origin. Empty when there is no `window`, which
57
+ // makes every href unparseable and so degrades to the safe new-tab default.
58
+ const basePath = useRouter().basePath;
59
+ const documentUrl = typeof window !== "undefined" ? window.location.href : "";
60
+
50
61
  return (
51
62
  // Page-level surface so the whole viewport (not just the topbar + cards) flips
52
63
  // under `[data-theme="dark"]` — otherwise the body stays white in dark mode.
@@ -89,24 +100,21 @@ export default function RootLayout() {
89
100
  Settings
90
101
  </Button>
91
102
  {extraNav.map((l) => (
92
- // Companion tools live OUTSIDE this SPA (a separate static page/worker route), so
93
- // open them in a new tab. NOT a style choice, and `target: "_self"` alone would not
94
- // fix it: `_404.tsx` registers the catch-all `/:__notFound+`, so buzola matches
95
- // EVERY same-origin path and intercepts it — a same-tab click and `location.assign`
96
- // both land on the in-app 404 (verified). Only a cross-origin url escapes on its own.
103
+ // Defaults to a new tab: a companion tool is normally a separate deployment, and
104
+ // `_404.tsx` registers the catch-all `/:__notFound+`, so the router matches every
105
+ // SAME-ORIGIN path a same-tab click would land on the in-app 404 rather than the
106
+ // tool. `target: "_self"` asks for the co-hosted case, and is honoured only where
107
+ // the router provably will not claim the url (`opensInSameTab` in mount.ts):
108
+ //
109
+ // - cross-origin: always, mounted or not. The catch-all cannot reach another
110
+ // origin, so this is the ONE case that also works at the origin root.
111
+ // - same-origin: only outside the mount prefix, where `scopeToBasePath` leaves
112
+ // the navigation to the browser. At the root there is no outside, so never.
97
113
  //
98
- // The supported same-tab route is `router.leaveApp(href)` (@buzola/router >= 0.0.16),
99
- // which releases one navigation to the browser. This package still pins ^0.0.12, so
100
- // adopting it is a version bump plus a `target` option on the config item.
101
- <a
102
- key={l.href}
103
- href={l.href}
104
- target="_blank"
105
- rel="noopener noreferrer"
106
- className="rounded-md px-2.5 py-1.5 text-small text-fg-muted transition-colors hover:bg-surface-muted hover:text-fg"
107
- >
108
- {l.label}
109
- </a>
114
+ // Anything else degrades to the new tab rather than stranding the user on a 404.
115
+ // (When @buzola/router moves past ^0.0.12 here, `router.leaveApp(href)` releases
116
+ // one navigation to the browser and makes same-origin `_self` work unmounted too.)
117
+ <NavLink key={`${l.href}|${l.label}`} link={l} sameTab={opensInSameTab(l.href, l.target, basePath, documentUrl)} confirm={confirmNavigation} />
110
118
  ))}
111
119
  </Topbar.Nav>
112
120
  <Topbar.Actions>
@@ -136,3 +144,29 @@ export default function RootLayout() {
136
144
  </div>
137
145
  );
138
146
  }
147
+
148
+ /** One host-configured link to a companion tool.
149
+ *
150
+ * `rel="noreferrer"` is on BOTH branches. `noopener` is genuinely moot in the same tab (no
151
+ * new browsing context is created, so there is no `window.opener` to sever) but `noreferrer`
152
+ * is not: without it a click from `/_pramen/admin/pages/<id>` hands that full url to the
153
+ * destination as `Referer`, and `_self` is honoured for cross-origin destinations.
154
+ *
155
+ * The key pairs href with label, because two entries may legitimately point at the same href
156
+ * and differ only in label or target — keyed on href alone React reconciles them together
157
+ * and the rendered label can end up on the other one's anchor.
158
+ */
159
+ function NavLink({ link, sameTab, confirm }: { link: { label: string; href: string; target?: string }; sameTab: boolean; confirm: () => boolean }) {
160
+ return (
161
+ <a
162
+ href={link.href}
163
+ rel={sameTab ? "noreferrer" : "noopener noreferrer"}
164
+ // Only the same-tab case unloads this document, so only it consults the guard.
165
+ onClick={sameTab ? (e) => { if (!confirm()) e.preventDefault(); } : undefined}
166
+ {...(sameTab ? {} : { target: "_blank" })}
167
+ className="rounded-md px-2.5 py-1.5 text-small text-fg-muted transition-colors hover:bg-surface-muted hover:text-fg"
168
+ >
169
+ {link.label}
170
+ </a>
171
+ );
172
+ }