@tdacorp/hyle-sdk 0.5.0 → 0.8.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/README.md +48 -7
- package/dist/check-routes-bin.js +167 -19
- package/dist/chunk-67IOIAVW.js +35 -0
- package/dist/{chunk-4OB77ZOD.js → chunk-EBNIKRQH.js} +92 -11
- package/dist/{chunk-SO6H2UGL.js → chunk-LGW2KP4X.js} +7 -1
- package/dist/{chunk-OW6S7IZX.js → chunk-N4QYPO7S.js} +1 -1
- package/dist/index.cjs +96 -11
- package/dist/index.d.cts +57 -5
- package/dist/index.d.ts +57 -5
- package/dist/index.js +6 -1
- package/dist/next.cjs +120 -5
- package/dist/next.d.cts +43 -1
- package/dist/next.d.ts +43 -1
- package/dist/next.js +82 -3
- package/dist/react.cjs +16 -1
- package/dist/react.js +2 -1
- package/dist/use-cache.cjs +22 -4
- package/dist/use-cache.js +3 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -43,15 +43,22 @@ import { createRevalidateRoute } from "@tdacorp/hyle-sdk/next";
|
|
|
43
43
|
export const { POST } = createRevalidateRoute({ workspaceId: process.env.HYLE_WORKSPACE_ID, secrets: [process.env.HYLE_WEBHOOK_SECRET] });
|
|
44
44
|
```
|
|
45
45
|
|
|
46
|
-
|
|
46
|
+
`app/api/hyle/assets/[file]/route.ts` (images, video and audio in hyle content; see "Media"):
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { createAssetRoute } from "@tdacorp/hyle-sdk/next";
|
|
50
|
+
export const { GET, HEAD } = createAssetRoute({ baseUrl: process.env.HYLE_TARGET_BASE_URL, token: process.env.HYLE_TARGET_TOKEN });
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Register the revalidate URL as the workspace's webhook endpoint in hyle. Set `metadataBase` in your root layout so canonical and hreflang URLs are absolute.
|
|
47
54
|
|
|
48
55
|
## Entry points
|
|
49
56
|
|
|
50
57
|
| Import | Contents | Needs |
|
|
51
58
|
|---|---|---|
|
|
52
|
-
| `@tdacorp/hyle-sdk` | `createHyleClient` (typed `resolve` and `
|
|
59
|
+
| `@tdacorp/hyle-sdk` | `createHyleClient` (typed `resolve`, `mounts` and `asset`), `listPublicationPaths`, `checkRoutes` and the other route-check functions, `Cp1ClientError`, `verifyHyleSignature`, `parseSignatureHeader`, `isValidCacheTag`, `DeliveryDedupe`, `createRevalidationCallbackRoute`, the result types | nothing (no framework) |
|
|
53
60
|
| `@tdacorp/hyle-sdk/react` | `ArticlePage`, `ListPage`, `DocsPage`, `NotFound`, `Redirecting`, `Unavailable`, `HastContent`, `TrustedServerHtml`, `sanitizeHast` | react >= 19 |
|
|
54
|
-
| `@tdacorp/hyle-sdk/next` | `hylePage`, `hyleMetadata`, `hyleSitemap`, `hyleRootPage`, `hyleRootMetadata`, `hyleRootSitemap`, `createRevalidateRoute`, `fetchResolver`, `workspaceTags` | next >= 16 |
|
|
61
|
+
| `@tdacorp/hyle-sdk/next` | `hylePage`, `hyleMetadata`, `hyleSitemap`, `hyleRootPage`, `hyleRootMetadata`, `hyleRootSitemap`, `createRevalidateRoute`, `createAssetRoute`, `fetchResolver`, `workspaceTags` | next >= 16 |
|
|
55
62
|
| `@tdacorp/hyle-sdk/next/use-cache` | `cachedResolver` | next >= 16 with `cacheComponents: true` |
|
|
56
63
|
| `@tdacorp/hyle-sdk/styles.css` | the stylesheet | |
|
|
57
64
|
|
|
@@ -163,19 +170,43 @@ The last good copy is in process memory, keyed by hyle origin plus workspace id
|
|
|
163
170
|
|
|
164
171
|
### Adopting it on a Next 16 + next-intl site
|
|
165
172
|
|
|
166
|
-
1.
|
|
173
|
+
1. Add the reserved-paths sync to your production build (see "Syncing reserved paths" below); nothing is pasted into hyle by hand. `--print-reserved` still prints what would be sent.
|
|
167
174
|
2. Replace `app/[locale]/[...rest]/page.tsx` (the `notFound()` catch-all) with `app/[locale]/(site)/[...hyle]/page.tsx`, put it under the layout group that carries the site chrome, and keep your `not-found.tsx` in that group: a 404 from the catch-all then renders inside the chrome. Pass `locale: (p) => String(p.locale)` and `localePrefix` as for `hylePage`.
|
|
168
175
|
3. Keep `dynamicParams` true (see Host requirements). Keep the proxy matcher as is.
|
|
169
176
|
4. Add `hyleRootSitemap` to `app/sitemap.ts`, run the checker (below), deploy.
|
|
170
177
|
|
|
171
178
|
### Collision checker
|
|
172
179
|
|
|
173
|
-
`hyle-sdk-check-routes` (bin of this package) reads `.next/routes-manifest.json` and `.next/server/app-paths-manifest.json` of a finished `next build`, and hyle's `mounts` plus the published pages of each mount (read-only; `HYLE_TARGET_BASE_URL` or `--base-url`, and `HYLE_TARGET_TOKEN` from the environment only). It reports (a) hyle pages shadowed by a host static route, (b) host dynamic routes that match hyle URLs, with a verdict from route specificity (`[x]` before `[...x]` before `[[...x]]`; the hyle catch-all itself is fine), (c) mounts whose prefix is a host static route. Exit 1 on (a) or (c), 0 otherwise, 2 when it cannot run (no build, no credentials, hyle unreachable or the listing incomplete). `--json` prints the report; `--print-reserved` prints the host's
|
|
180
|
+
`hyle-sdk-check-routes` (bin of this package) reads `.next/routes-manifest.json` and `.next/server/app-paths-manifest.json` of a finished `next build`, and hyle's `mounts` plus the published pages of each mount (read-only; `HYLE_TARGET_BASE_URL` or `--base-url`, and `HYLE_TARGET_TOKEN` from the environment only). It reports (a) hyle pages shadowed by a host static route, (b) host dynamic routes that match hyle URLs, with a verdict from route specificity (`[x]` before `[...x]` before `[[...x]]`; the hyle catch-all itself is fine), (c) mounts whose prefix is a host static route. Exit 1 on (a) or (c), 0 otherwise, 2 when it cannot run (no build, no credentials, hyle unreachable or the listing incomplete). `--json` prints the report; `--print-reserved` prints the host's routes in hyle's Reserved paths format (see "Syncing reserved paths" for the derivation). `--locales`, `--default-locale` and `--locale-prefix as-needed|always|never` expand a leading `[locale]` segment (next-intl). `--sections a,b` lists extra sections; `--hyle-param` names the catch-all param. A root mount over the host's home page is a note, not a failure. In CI, run it after `next build` as a required step. The same functions are exported from `@tdacorp/hyle-sdk` (`hostRoutesFromManifests`, `checkRoutes`, `reservedFor`, `formatReport`).
|
|
181
|
+
|
|
182
|
+
### Syncing reserved paths
|
|
183
|
+
|
|
184
|
+
Reserved paths are the URLs your app owns, which hyle refuses to publish onto. They are derived from your build and sent to hyle, so nobody maintains them in hyle's UI:
|
|
185
|
+
|
|
186
|
+
```
|
|
187
|
+
hyle-sdk-check-routes --sync --no-check --locales en,fr,es --default-locale en --locale-prefix as-needed
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
Run it as the last step of the PRODUCTION build (a `postbuild` script, or the build command after `next build`). It needs, from the environment only:
|
|
191
|
+
|
|
192
|
+
| Variable | What |
|
|
193
|
+
|---|---|
|
|
194
|
+
| `HYLE_TARGET_BASE_URL`, `HYLE_TARGET_TOKEN` | already set for the site: finds the workspace through `mounts` (the read token only reads) |
|
|
195
|
+
| `HYLE_CONTROL_TOKEN` | NEW: a control credential (`hyle_tc_...`) whose principal holds `hyle.workspace.manage` on that workspace. The read token cannot write and is refused before any request. Mint it in hyle under Workspace > Agents (a name like `site-sync`); while hyle authorizes through identity, also link that agent's principal to an identity service principal bound to `hyle.workspace.manage` only (`scripts/link-principal-identity.mjs`, as the Agents screen says), otherwise the write answers 404. Store it as a secret in the Production scope of the host only |
|
|
196
|
+
| `HYLE_HOST_ID` | optional name for the audit trail; defaults to `VERCEL_PROJECT_PRODUCTION_URL`, or pass `--host` |
|
|
197
|
+
|
|
198
|
+
What is sent: `PUT /cp1/control/workspace/host-reserved-paths` with `{ paths, host, build_id }` (the build id is `.next/BUILD_ID`). The list: static routes exact; a segment with two or more routes becomes `/x/*`; a dynamic route becomes the wildcard on its static prefix (`/shop/[id]` is `/shop/*`, `/docs/[...slug]` is `/docs/*`); skipped are your hyle catch-all (`--hyle-param`), a route with no static prefix, anything on a mount's segment (the checker reports those as (b)), per-build hashed metadata routes (`/opengraph-image-1ycygp`), and `/` when hyle is mounted at the root. At most 512 entries. hyle stores it as a separate set (the workspace's own Reserved paths are never touched), enforces the union when publishing, renaming and re-prefixing, and shows it read-only in the workspace settings with the host, build and time.
|
|
199
|
+
|
|
200
|
+
- **Never fails your deploy.** A failed sync (hyle down, wrong token, not granted) prints a `sync:` warning and exits 0. Add `--strict` to exit 3 instead. Without `--no-check` the collision check also runs and keeps its own exit codes (1 collision, 2 cannot run).
|
|
201
|
+
- **Production only.** When `VERCEL_ENV` is set and is not `production` the sync is skipped, so a preview cannot replace production's list (`--allow-non-production` overrides). Elsewhere, only run it in production builds.
|
|
202
|
+
- **Idempotent.** The same list changes nothing in hyle (`unchanged`). An empty list is refused (`--allow-empty` overrides) so a broken manifest read cannot erase the reservations.
|
|
203
|
+
- **Conflicts.** If a path you now own already has a published hyle page, hyle unpublishes nothing: the result lists those URLs (CLI output and the settings page). Your own route wins in Next, so the hyle page is simply not shown; move or unpublish it in hyle.
|
|
204
|
+
- `--json` adds a `sync` object. The programmatic form is `syncHostReserved({ baseUrl, token, workspaceId, paths, host, buildId })`.
|
|
174
205
|
|
|
175
206
|
### Limits
|
|
176
207
|
|
|
177
208
|
- A junk URL still renders a 404 page in your site chrome; whether and how long Next keeps that render is Next's own ISR behaviour (not measured here). It never reaches hyle either way.
|
|
178
|
-
- The checker sees the published default-locale pages of each mount (at most 10,000 per mount) and host routes known to the build; routes that only a proxy rewrite creates, or translated pathnames, are invisible to it, so list those in Reserved paths by hand.
|
|
209
|
+
- The checker sees the published default-locale pages of each mount (at most 10,000 per mount) and host routes known to the build; routes that only a proxy rewrite creates, or translated pathnames, are invisible to it, so list those in the workspace's own Reserved paths by hand (that list is separate from the synced one and is never overwritten by a sync).
|
|
179
210
|
- Matching uses the mounts of the last successful read: a new mount is served after the mounts revalidate window (default 300 s) or a workspace-tag purge.
|
|
180
211
|
- A reserved or mounted URL can only be reached if no host route matches it first; that is the intended precedence.
|
|
181
212
|
|
|
@@ -193,6 +224,16 @@ Verify after `next build`: `.next/prerender-manifest.json` must not show `"fallb
|
|
|
193
224
|
|
|
194
225
|
Locale-prefixed hosts: you may keep `generateStaticParams` for the locales, but validate the locale in the layout (call `notFound()` for an unknown one) and set `dynamicParams = true` there, so unknown locales are still rejected.
|
|
195
226
|
|
|
227
|
+
## Media
|
|
228
|
+
|
|
229
|
+
hyle stores an image, video or audio reference as `/assets/<uuid>.<ext>`, a path that exists only on hyle's own (authenticated) origin. On a host site it would 404, so the SDK rewrites it while rendering (`HastContent`, so every page component, and the `format: "html"` escape hatch) to `/api/hyle/assets/<uuid>.<ext>` on the host's own origin. That path is answered by the one route file in the quickstart, `app/api/hyle/assets/[file]/route.ts`; nothing else is needed per site, and a strict CSP such as `img-src 'self' data:` (and `media-src` left at `default-src 'self'`) works unchanged. The `Image` slot receives the rewritten `src`, so a `next/image` slot also works; the default is a plain `<img loading="lazy">`.
|
|
230
|
+
|
|
231
|
+
How it works: `createAssetRoute` asks hyle for exactly that file (`GET /cp1/read/assets/<file>`, ADR 0015) with the target credential and streams the bytes back. hyle answers only for an asset that a currently published, non-trashed page of this workspace references, so a draft, unpublished or other workspace's asset is a 404 on your site too. Responses carry `Cache-Control: public, max-age=3600, s-maxage=86400, stale-while-revalidate=86400`, hyle's strong `ETag` (revalidation is a 304) and `Accept-Ranges`; `Range` is forwarded, so video and audio seek. After an unpublish a cached copy can still be served for up to the cache window (about a day on a CDN).
|
|
232
|
+
|
|
233
|
+
Safety: the only input is the `file` segment and it must match `<lowercase uuid>[.png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg]` before anything is sent, so the route is not an open proxy. Only `Range`, `If-Range` and `If-None-Match` are forwarded (never the visitor's cookies or `Authorization`); the token goes to hyle only. Response headers are built by the SDK, the content type must be on the asset allowlist (an HTML or script answer is refused), the body is capped at 16 MiB (`maxBytes`) and the upstream call times out after 30 s (`timeoutMs`). Failures are empty responses: 404 for an unknown or unpublished asset, a bad name, a missing configuration or `HYLE_CONTENT_ENABLED=0`, 502 for any upstream error, so hyle's state and your token never leak. SVG is served as `image/svg+xml` with `Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox` and `nosniff` (an `<img>` never runs SVG script; navigating to the URL runs none either).
|
|
234
|
+
|
|
235
|
+
The route sits under `/api/hyle/*`, which hyle's Reserved paths must cover (`hyle-sdk-check-routes --print-reserved` always lists `/api/hyle/*`, and so does `--sync`), and the checker prints a note when the build has no `/api/hyle/assets/...` route. If your proxy or middleware matcher intercepts `/api`, exclude `/api/hyle/assets`. Nothing renders `/assets/...` for you outside the SDK's components: a custom renderer of the `hast` tree should map `src` the same way (`/assets/<id>.<ext>` to `/api/hyle/assets/<id>.<ext>`).
|
|
236
|
+
|
|
196
237
|
## Mermaid diagrams
|
|
197
238
|
|
|
198
239
|
Zero setup. A Mermaid fence arrives from hyle as a sandboxed `<iframe srcdoc>` that loads a script from cdnjs, and a `srcdoc` frame inherits the host page's CSP, so a host with `script-src 'self'` would show a blank box. The SDK therefore reads the diagram text out of that document (only after it matched hyle's exact template) and renders it in your page with the Mermaid library it bundles as a dependency (`mermaid` `~11.9.0`, MIT). No cdnjs, no extra package, no config.
|
|
@@ -265,7 +306,7 @@ Chrome strings exist for en, fr and es (fr and es are unreviewed drafts). The pa
|
|
|
265
306
|
|
|
266
307
|
## Not included
|
|
267
308
|
|
|
268
|
-
Docs versions, reading time, scroll-spy, "closest matches" on the 404 page and a copy-code button: hyle does not provide that data or the page would need client JavaScript. Image URLs in content such as `/assets/<id>` are passed through unchanged
|
|
309
|
+
Docs versions, reading time, scroll-spy, "closest matches" on the 404 page and a copy-code button: hyle does not provide that data or the page would need client JavaScript. Image URLs in content such as `/assets/<id>` are no longer passed through unchanged: see "Media".
|
|
269
310
|
|
|
270
311
|
## Contract
|
|
271
312
|
|
package/dist/check-routes-bin.js
CHANGED
|
@@ -2,6 +2,14 @@
|
|
|
2
2
|
import { readFileSync } from "fs";
|
|
3
3
|
import { join } from "path";
|
|
4
4
|
|
|
5
|
+
// src/asset-path.ts
|
|
6
|
+
var ASSET_ROUTE_PREFIX = "/api/hyle/assets";
|
|
7
|
+
var ASSET_RESERVED_PATH = "/api/hyle/*";
|
|
8
|
+
var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
|
9
|
+
var EXTENSIONS = "png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg";
|
|
10
|
+
var ASSET_FILE = new RegExp(`^${UUID}(?:\\.(?:${EXTENSIONS}))?$`);
|
|
11
|
+
var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)$`, "i");
|
|
12
|
+
|
|
5
13
|
// src/errors.ts
|
|
6
14
|
var Cp1ClientError = class extends Error {
|
|
7
15
|
code;
|
|
@@ -47,16 +55,19 @@ function isMounts(data) {
|
|
|
47
55
|
const mounts = data.mounts;
|
|
48
56
|
return typeof data.workspace_id === "string" && isStrings(data.reserved) && isStrings(data.supported_locales) && Array.isArray(mounts) && mounts.every((m) => typeof m?.prefix === "string" && typeof m.default_section === "string");
|
|
49
57
|
}
|
|
50
|
-
function
|
|
58
|
+
function checkBaseUrl(baseUrl, allowInsecureHttp) {
|
|
51
59
|
let origin;
|
|
52
60
|
try {
|
|
53
|
-
origin = new URL(
|
|
61
|
+
origin = new URL(baseUrl);
|
|
54
62
|
} catch {
|
|
55
63
|
throw new TypeError("baseUrl must be an https origin");
|
|
56
64
|
}
|
|
57
|
-
if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (
|
|
65
|
+
if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (allowInsecureHttp || LOOPBACK.has(origin.hostname)))) {
|
|
58
66
|
throw new TypeError("baseUrl must be https (http is allowed only for localhost, or with allowInsecureHttp)");
|
|
59
67
|
}
|
|
68
|
+
}
|
|
69
|
+
function createHyleClient(options) {
|
|
70
|
+
checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
|
|
60
71
|
if (!options.token) throw new TypeError("token is required");
|
|
61
72
|
const base = options.baseUrl.replace(/\/+$/, "");
|
|
62
73
|
const fetchImpl = options.fetch ?? fetch;
|
|
@@ -99,7 +110,56 @@ function createHyleClient(options) {
|
|
|
99
110
|
if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
|
|
100
111
|
throw failure(reply);
|
|
101
112
|
}
|
|
102
|
-
|
|
113
|
+
async function asset(file, opts = {}) {
|
|
114
|
+
if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
|
|
115
|
+
const headers = new Headers({ authorization: `Bearer ${options.token}` });
|
|
116
|
+
for (const name of ["range", "if-range", "if-none-match"]) {
|
|
117
|
+
const value = opts.headers?.[name];
|
|
118
|
+
if (value) headers.set(name, value);
|
|
119
|
+
}
|
|
120
|
+
return fetchImpl(`${base}/cp1/read/assets/${file}`, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
|
|
121
|
+
}
|
|
122
|
+
return { resolve, mounts, asset };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// src/host-sync.ts
|
|
126
|
+
var CONTROL_TOKEN_PREFIX = "hyle_tc_";
|
|
127
|
+
var DEFAULT_TIMEOUT_MS2 = 1e4;
|
|
128
|
+
var MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
129
|
+
var PATH = "/cp1/control/workspace/host-reserved-paths";
|
|
130
|
+
async function syncHostReserved(input) {
|
|
131
|
+
checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
|
|
132
|
+
if (!input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
|
|
133
|
+
throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
|
|
134
|
+
}
|
|
135
|
+
const fetchImpl = input.fetch ?? fetch;
|
|
136
|
+
const res = await fetchImpl(`${input.baseUrl.replace(/\/+$/, "")}${PATH}`, {
|
|
137
|
+
method: "PUT",
|
|
138
|
+
// redirect "error": the bearer token must never follow a redirect to another host.
|
|
139
|
+
redirect: "error",
|
|
140
|
+
signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
|
|
141
|
+
headers: {
|
|
142
|
+
authorization: `Bearer ${input.token}`,
|
|
143
|
+
"content-type": "application/json",
|
|
144
|
+
"cp-workspace": input.workspaceId,
|
|
145
|
+
"idempotency-key": `sync-${crypto.randomUUID()}`
|
|
146
|
+
},
|
|
147
|
+
body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
|
|
148
|
+
});
|
|
149
|
+
const text = await readCapped(res, MAX_RESPONSE_BYTES);
|
|
150
|
+
let parsed;
|
|
151
|
+
try {
|
|
152
|
+
parsed = JSON.parse(text);
|
|
153
|
+
} catch {
|
|
154
|
+
parsed = void 0;
|
|
155
|
+
}
|
|
156
|
+
const data = parsed?.data;
|
|
157
|
+
const conflicts = data?.conflicts;
|
|
158
|
+
if (res.ok && data && Array.isArray(data.paths) && typeof data.changed === "boolean" && typeof data.synced_at === "string" && typeof conflicts?.total === "number" && Array.isArray(conflicts.offenders)) {
|
|
159
|
+
return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
|
|
160
|
+
}
|
|
161
|
+
const err = parsed?.error;
|
|
162
|
+
throw new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${res.status})`, res.status, err?.request_id ?? "", err?.details);
|
|
103
163
|
}
|
|
104
164
|
|
|
105
165
|
// src/next/paths.ts
|
|
@@ -205,29 +265,50 @@ function checkRoutes(input) {
|
|
|
205
265
|
const shown = hostWins.length > 0 ? hostWins : matched;
|
|
206
266
|
dynamicOverlaps.push({ route, verdict: hostWins.length > 0 ? "host-wins" : "hyle-wins", matches: shown.length, examples: shown.slice(0, MAX_EXAMPLES) });
|
|
207
267
|
}
|
|
268
|
+
if (!routes.some((r) => r.startsWith(`${ASSET_ROUTE_PREFIX}/`))) {
|
|
269
|
+
notes.push(`no asset route (${ASSET_ROUTE_PREFIX}/[file], createAssetRoute) was found in the host routes: images, video and audio in hyle content will 404`);
|
|
270
|
+
}
|
|
208
271
|
if (catchAlls.length === 0) notes.push(`no hyle catch-all route (a "[...${hyleParam}]" or "[[...${hyleParam}]]" page) was found in the host routes`);
|
|
209
272
|
return { shadowedHylePaths, mountCollisions, dynamicOverlaps, notes, ok: shadowedHylePaths.length === 0 && mountCollisions.length === 0 };
|
|
210
273
|
}
|
|
274
|
+
var SDK_OWN_RESERVED = [ASSET_RESERVED_PATH];
|
|
275
|
+
var HASHED_METADATA_ROUTE = /^(opengraph-image|twitter-image|icon|apple-icon)-[a-z0-9]{5,8}$/;
|
|
276
|
+
var isHashedMetadataRoute = (route) => HASHED_METADATA_ROUTE.test(segmentsOf(route).at(-1) ?? "");
|
|
277
|
+
var covers = (entry, path) => {
|
|
278
|
+
if (!entry.endsWith("/*")) return entry === path;
|
|
279
|
+
const base = entry.slice(0, -2);
|
|
280
|
+
return path === base || path.startsWith(`${base}/`);
|
|
281
|
+
};
|
|
211
282
|
function reservedFor(hostRoutes, options = {}) {
|
|
212
283
|
const dropLocale = (route) => {
|
|
213
284
|
const [first, ...rest] = segmentsOf(route);
|
|
214
285
|
return options.locale && first === `[${LOCALE_PARAM}]` ? `/${rest.join("/")}` : route;
|
|
215
286
|
};
|
|
216
|
-
const
|
|
287
|
+
const hyleParam = options.hyleParam ?? "hyle";
|
|
288
|
+
const routes = hostRoutes.map(dropLocale).filter((r) => !isHashedMetadataRoute(r));
|
|
289
|
+
const exact = new Set(routes.filter((r) => !isDynamic(r)));
|
|
217
290
|
const mounts = options.mounts?.filter((m) => m !== "/");
|
|
291
|
+
const onMount = (segment) => mounts?.some((m) => m === `/${segment}` || m.startsWith(`/${segment}/`)) ?? true;
|
|
218
292
|
const groups = /* @__PURE__ */ new Map();
|
|
219
293
|
for (const route of exact) {
|
|
220
294
|
const [first, ...rest] = segmentsOf(route);
|
|
221
295
|
if (first !== void 0 && rest.length > 0) groups.set(first, [...groups.get(first) ?? [], route]);
|
|
222
296
|
}
|
|
297
|
+
const wildcards = /* @__PURE__ */ new Set();
|
|
223
298
|
for (const [first, members] of groups) {
|
|
224
|
-
|
|
225
|
-
if (members.length < 2 || onMount) continue;
|
|
226
|
-
for (const m of members) exact.delete(m);
|
|
227
|
-
exact.delete(`/${first}`);
|
|
228
|
-
exact.add(`/${first}/*`);
|
|
299
|
+
if (members.length >= 2 && !onMount(first)) wildcards.add(`/${first}/*`);
|
|
229
300
|
}
|
|
230
|
-
|
|
301
|
+
for (const route of routes.filter(isDynamic)) {
|
|
302
|
+
const segments = parse(route);
|
|
303
|
+
const last = segments.at(-1);
|
|
304
|
+
if ((last?.kind === "catch-all" || last?.kind === "optional-catch-all") && last.name === hyleParam) continue;
|
|
305
|
+
const dir = segments.slice(0, segments.findIndex((seg) => seg.kind !== "static")).map((seg) => seg.kind === "static" ? seg.value : "").join("/");
|
|
306
|
+
if (dir === "" || !mounts) continue;
|
|
307
|
+
if (!mounts.some((m) => m === `/${dir}` || m.startsWith(`/${dir}/`))) wildcards.add(`/${dir}/*`);
|
|
308
|
+
}
|
|
309
|
+
const all = [...exact, ...wildcards];
|
|
310
|
+
const base = (entry) => entry.endsWith("/*") ? entry.slice(0, -2) : entry;
|
|
311
|
+
return all.filter((entry) => !all.some((other) => other !== entry && other.endsWith("/*") && covers(other, base(entry)))).sort();
|
|
231
312
|
}
|
|
232
313
|
function formatReport(report) {
|
|
233
314
|
const lines = [];
|
|
@@ -298,16 +379,25 @@ async function listPublicationPaths(options) {
|
|
|
298
379
|
|
|
299
380
|
// src/check-routes-cli.ts
|
|
300
381
|
var USAGE = `hyle-sdk-check-routes [--next-dir .next] [--base-url URL] [--json] [--print-reserved]
|
|
382
|
+
[--sync [--strict] [--no-check] [--host ID] [--build-id ID] [--allow-empty] [--allow-non-production]]
|
|
301
383
|
[--locales en,fr,es --default-locale en --locale-prefix as-needed|always|never] [--sections a,b] [--hyle-param hyle]
|
|
302
384
|
|
|
303
385
|
Run after \`next build\`. Reads the build's route manifests and hyle's read-only endpoints (mounts, and the published pages of each mount).
|
|
304
386
|
Credentials: HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN. The token is read from the environment only, never a flag.
|
|
305
387
|
(a) hyle pages a host static route shadows, (b) host dynamic routes that match hyle URLs, (c) mounts that are host static routes.
|
|
306
|
-
--print-reserved print the host's
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
388
|
+
--print-reserved print the host's routes in hyle's "Reserved paths" format and exit.
|
|
389
|
+
--sync report that list to hyle (ADR 0016) so nobody maintains it by hand, then run the check. Needs HYLE_CONTROL_TOKEN
|
|
390
|
+
(a hyle_tc_ control credential with hyle.workspace.manage; the read token cannot write), read from the environment only.
|
|
391
|
+
A failed sync only warns, so it never fails a deploy, unless --strict (exit 3). Skipped on a non-production Vercel
|
|
392
|
+
build (VERCEL_ENV) unless --allow-non-production. --no-check syncs without the collision check. The host id comes
|
|
393
|
+
from --host, HYLE_HOST_ID or VERCEL_PROJECT_PRODUCTION_URL; the build id from <next-dir>/BUILD_ID or --build-id.
|
|
394
|
+
An empty list is refused unless --allow-empty.
|
|
395
|
+
Exit: 0 no collision, 1 collision (a) or (c), 2 cannot run, 3 sync failed under --strict.`;
|
|
396
|
+
var FLAGS = /* @__PURE__ */ new Set(["--next-dir", "--base-url", "--locales", "--default-locale", "--locale-prefix", "--sections", "--hyle-param", "--host", "--build-id"]);
|
|
397
|
+
var BOOLEAN = /* @__PURE__ */ new Set(["--json", "--print-reserved", "--help", "--sync", "--strict", "--no-check", "--allow-empty", "--allow-non-production"]);
|
|
310
398
|
var CANNOT_RUN = 2;
|
|
399
|
+
var SYNC_FAILED = 3;
|
|
400
|
+
var MAX_SYNCED_PATHS = 512;
|
|
311
401
|
function parseArgs(argv) {
|
|
312
402
|
const args = /* @__PURE__ */ new Map();
|
|
313
403
|
for (let i = 0; i < argv.length; i++) {
|
|
@@ -319,6 +409,46 @@ function parseArgs(argv) {
|
|
|
319
409
|
return args;
|
|
320
410
|
}
|
|
321
411
|
var readJson = (file) => JSON.parse(readFileSync(file, "utf8"));
|
|
412
|
+
var SAFE_ID = /[^A-Za-z0-9._-]/g;
|
|
413
|
+
async function syncStep(args, io, ctx) {
|
|
414
|
+
const fail = (reason) => (io.err(`sync: ${printable(reason)}`), { status: "failed", reason });
|
|
415
|
+
const vercelEnv = io.env.VERCEL_ENV;
|
|
416
|
+
if (vercelEnv !== void 0 && vercelEnv !== "production" && !args.has("--allow-non-production")) {
|
|
417
|
+
io.err(`sync: skipped, this is a ${printable(vercelEnv)} build (a preview must not replace production's list; --allow-non-production overrides)`);
|
|
418
|
+
return { status: "skipped" };
|
|
419
|
+
}
|
|
420
|
+
const { baseUrl, mounts } = ctx.plan;
|
|
421
|
+
const token = io.env.HYLE_CONTROL_TOKEN;
|
|
422
|
+
if (!token) return fail("set HYLE_CONTROL_TOKEN (a hyle_tc_ control credential with hyle.workspace.manage; the read token cannot write)");
|
|
423
|
+
if (!baseUrl || !mounts) return fail(ctx.plan.mountsError ?? "set HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN so the workspace can be found");
|
|
424
|
+
const host = (args.get("--host") ?? io.env.HYLE_HOST_ID ?? io.env.VERCEL_PROJECT_PRODUCTION_URL)?.replace(SAFE_ID, "-").slice(0, 128);
|
|
425
|
+
if (!host) return fail("name this host with --host, HYLE_HOST_ID or VERCEL_PROJECT_PRODUCTION_URL");
|
|
426
|
+
let buildId = args.get("--build-id") ?? io.env.VERCEL_GIT_COMMIT_SHA;
|
|
427
|
+
try {
|
|
428
|
+
buildId = readFileSync(join(ctx.nextDir, "BUILD_ID"), "utf8").trim();
|
|
429
|
+
} catch {
|
|
430
|
+
}
|
|
431
|
+
buildId = buildId?.replace(SAFE_ID, "-").slice(0, 128);
|
|
432
|
+
if (!buildId) return fail("no build id: <next-dir>/BUILD_ID is missing; pass --build-id");
|
|
433
|
+
const rootMount = mounts.prefixes.includes("/");
|
|
434
|
+
const fromHost = reservedFor(ctx.hostRoutes, { ...ctx.locale ? { locale: ctx.locale } : {}, mounts: mounts.prefixes, hyleParam: ctx.hyleParam }).filter((p) => !(rootMount && p === "/"));
|
|
435
|
+
const reserved = [.../* @__PURE__ */ new Set([...fromHost, ...SDK_OWN_RESERVED])].sort();
|
|
436
|
+
if (fromHost.length === 0 && !args.has("--allow-empty")) return fail("the build has no reservable routes; refusing to replace hyle's list with an empty one (--allow-empty overrides)");
|
|
437
|
+
if (reserved.length > MAX_SYNCED_PATHS) return fail(`${reserved.length} reserved paths exceed hyle's limit of ${MAX_SYNCED_PATHS}`);
|
|
438
|
+
try {
|
|
439
|
+
const result = await syncHostReserved({ baseUrl, token, workspaceId: mounts.workspaceId, paths: reserved, host, buildId, ...io.fetch ? { fetch: io.fetch } : {} });
|
|
440
|
+
if (!args.has("--json")) {
|
|
441
|
+
io.out(`sync: ${result.paths.length} reserved paths ${result.changed ? "updated" : "unchanged"} in hyle (host ${printable(host)}, build ${printable(buildId)})`);
|
|
442
|
+
if (result.conflicts.total > 0) {
|
|
443
|
+
io.out(`sync: ${result.conflicts.total} published hyle URL(s) are on paths this host owns (hyle unpublished nothing):`);
|
|
444
|
+
for (const path of result.conflicts.offenders) io.out(` ${printable(path)}`);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
return { status: "ok", result };
|
|
448
|
+
} catch (error) {
|
|
449
|
+
return fail(error instanceof Error ? `${error.name}: ${error.message}` : "unknown error");
|
|
450
|
+
}
|
|
451
|
+
}
|
|
322
452
|
async function runCli(argv, io) {
|
|
323
453
|
try {
|
|
324
454
|
const args = parseArgs(argv);
|
|
@@ -350,18 +480,35 @@ async function runCli(argv, io) {
|
|
|
350
480
|
const baseUrl = args.get("--base-url") ?? io.env.HYLE_TARGET_BASE_URL;
|
|
351
481
|
const token = io.env.HYLE_TARGET_TOKEN;
|
|
352
482
|
const client = baseUrl && token ? createHyleClient({ baseUrl, token, ...io.fetch ? { fetch: io.fetch } : {} }) : void 0;
|
|
353
|
-
|
|
483
|
+
let mounts;
|
|
484
|
+
let mountsError;
|
|
485
|
+
try {
|
|
486
|
+
mounts = client ? await client.mounts() : void 0;
|
|
487
|
+
} catch (error) {
|
|
488
|
+
if (!args.has("--sync")) throw error;
|
|
489
|
+
mountsError = error;
|
|
490
|
+
}
|
|
354
491
|
if (mounts?.kind === "disabled") {
|
|
355
492
|
io.err("CANNOT RUN: hyle's read surface is switched off (kind: disabled)");
|
|
356
493
|
return CANNOT_RUN;
|
|
357
494
|
}
|
|
358
495
|
const prefixes = mounts?.mounts.map((m) => m.prefix);
|
|
496
|
+
const strict = args.has("--strict");
|
|
497
|
+
let sync;
|
|
498
|
+
if (args.has("--sync")) {
|
|
499
|
+
sync = await syncStep(args, io, { nextDir, hostRoutes, locale, hyleParam, plan: { baseUrl, mounts: mounts?.kind === "mounts" && prefixes ? { workspaceId: mounts.workspace_id, prefixes } : void 0, ...mountsError instanceof Error ? { mountsError: `${mountsError.name}: ${mountsError.message}` } : {} } });
|
|
500
|
+
if (args.has("--no-check")) {
|
|
501
|
+
if (args.has("--json")) io.out(JSON.stringify({ sync }));
|
|
502
|
+
return sync.status === "failed" && strict ? SYNC_FAILED : 0;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
359
505
|
if (args.has("--print-reserved")) {
|
|
360
|
-
const reserved = reservedFor(hostRoutes, { ...locale ? { locale } : {}, ...prefixes ? { mounts: prefixes } : {} });
|
|
506
|
+
const reserved = [.../* @__PURE__ */ new Set([...reservedFor(hostRoutes, { ...locale ? { locale } : {}, ...prefixes ? { mounts: prefixes } : {}, hyleParam }), ...SDK_OWN_RESERVED])].sort();
|
|
361
507
|
if (!prefixes) io.err("note: hyle was not reachable (set HYLE_TARGET_BASE_URL and HYLE_TARGET_TOKEN), so route groups are listed exactly, not collapsed to /x/*");
|
|
362
508
|
io.out(args.has("--json") ? JSON.stringify(reserved) : reserved.join("\n"));
|
|
363
509
|
return 0;
|
|
364
510
|
}
|
|
511
|
+
if (mountsError) throw mountsError;
|
|
365
512
|
if (!client || !mounts || mounts.kind !== "mounts") {
|
|
366
513
|
io.err("CANNOT RUN: set HYLE_TARGET_BASE_URL (or --base-url) and HYLE_TARGET_TOKEN");
|
|
367
514
|
return CANNOT_RUN;
|
|
@@ -377,8 +524,9 @@ async function runCli(argv, io) {
|
|
|
377
524
|
hylePaths.push(...listing.paths.map((p) => p.path));
|
|
378
525
|
}
|
|
379
526
|
const report = checkRoutes({ hostRoutes, mounts: mounts.mounts.map((m) => m.prefix), hylePaths, hyleParam, ...locale ? { locale } : {} });
|
|
380
|
-
io.out(args.has("--json") ? JSON.stringify(report, null, 2) : formatReport(report));
|
|
381
|
-
|
|
527
|
+
io.out(args.has("--json") ? JSON.stringify(sync ? { ...report, sync } : report, null, 2) : formatReport(report));
|
|
528
|
+
if (!report.ok) return 1;
|
|
529
|
+
return sync?.status === "failed" && strict ? SYNC_FAILED : 0;
|
|
382
530
|
} catch (error) {
|
|
383
531
|
io.err(`CANNOT RUN: ${error instanceof Error ? printable(`${error.name}: ${error.message}`) : "unknown error"}`);
|
|
384
532
|
return CANNOT_RUN;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// src/asset-path.ts
|
|
2
|
+
var ASSET_ROUTE_PREFIX = "/api/hyle/assets";
|
|
3
|
+
var ASSET_RESERVED_PATH = "/api/hyle/*";
|
|
4
|
+
var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
|
5
|
+
var EXTENSIONS = "png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg";
|
|
6
|
+
var ASSET_FILE = new RegExp(`^${UUID}(?:\\.(?:${EXTENSIONS}))?$`);
|
|
7
|
+
var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)$`, "i");
|
|
8
|
+
function hostAssetSrc(src) {
|
|
9
|
+
const file = HYLE_ASSET_URL.exec(src)?.[1];
|
|
10
|
+
return file ? `${ASSET_ROUTE_PREFIX}/${file.toLowerCase()}` : src;
|
|
11
|
+
}
|
|
12
|
+
function hostAssetHtml(html) {
|
|
13
|
+
return html.replace(new RegExp(`(\\ssrc=")(/assets/${UUID}(?:\\.(?:${EXTENSIONS}))?)(")`, "gi"), (_m, open, url, close) => `${open}${hostAssetSrc(url)}${close}`);
|
|
14
|
+
}
|
|
15
|
+
var ASSET_CONTENT_TYPES = /* @__PURE__ */ new Set([
|
|
16
|
+
"image/png",
|
|
17
|
+
"image/jpeg",
|
|
18
|
+
"image/gif",
|
|
19
|
+
"image/webp",
|
|
20
|
+
"image/svg+xml",
|
|
21
|
+
"application/pdf",
|
|
22
|
+
"video/mp4",
|
|
23
|
+
"video/webm",
|
|
24
|
+
"audio/mpeg",
|
|
25
|
+
"audio/ogg"
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
export {
|
|
29
|
+
ASSET_ROUTE_PREFIX,
|
|
30
|
+
ASSET_RESERVED_PATH,
|
|
31
|
+
ASSET_FILE,
|
|
32
|
+
hostAssetSrc,
|
|
33
|
+
hostAssetHtml,
|
|
34
|
+
ASSET_CONTENT_TYPES
|
|
35
|
+
};
|
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ASSET_FILE,
|
|
3
|
+
ASSET_RESERVED_PATH,
|
|
4
|
+
ASSET_ROUTE_PREFIX
|
|
5
|
+
} from "./chunk-67IOIAVW.js";
|
|
6
|
+
|
|
1
7
|
// src/errors.ts
|
|
2
8
|
var Cp1ClientError = class extends Error {
|
|
3
9
|
code;
|
|
@@ -43,16 +49,19 @@ function isMounts(data) {
|
|
|
43
49
|
const mounts = data.mounts;
|
|
44
50
|
return typeof data.workspace_id === "string" && isStrings(data.reserved) && isStrings(data.supported_locales) && Array.isArray(mounts) && mounts.every((m) => typeof m?.prefix === "string" && typeof m.default_section === "string");
|
|
45
51
|
}
|
|
46
|
-
function
|
|
52
|
+
function checkBaseUrl(baseUrl, allowInsecureHttp) {
|
|
47
53
|
let origin;
|
|
48
54
|
try {
|
|
49
|
-
origin = new URL(
|
|
55
|
+
origin = new URL(baseUrl);
|
|
50
56
|
} catch {
|
|
51
57
|
throw new TypeError("baseUrl must be an https origin");
|
|
52
58
|
}
|
|
53
|
-
if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (
|
|
59
|
+
if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (allowInsecureHttp || LOOPBACK.has(origin.hostname)))) {
|
|
54
60
|
throw new TypeError("baseUrl must be https (http is allowed only for localhost, or with allowInsecureHttp)");
|
|
55
61
|
}
|
|
62
|
+
}
|
|
63
|
+
function createHyleClient(options) {
|
|
64
|
+
checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
|
|
56
65
|
if (!options.token) throw new TypeError("token is required");
|
|
57
66
|
const base = options.baseUrl.replace(/\/+$/, "");
|
|
58
67
|
const fetchImpl = options.fetch ?? fetch;
|
|
@@ -95,7 +104,56 @@ function createHyleClient(options) {
|
|
|
95
104
|
if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
|
|
96
105
|
throw failure(reply);
|
|
97
106
|
}
|
|
98
|
-
|
|
107
|
+
async function asset(file, opts = {}) {
|
|
108
|
+
if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
|
|
109
|
+
const headers = new Headers({ authorization: `Bearer ${options.token}` });
|
|
110
|
+
for (const name of ["range", "if-range", "if-none-match"]) {
|
|
111
|
+
const value = opts.headers?.[name];
|
|
112
|
+
if (value) headers.set(name, value);
|
|
113
|
+
}
|
|
114
|
+
return fetchImpl(`${base}/cp1/read/assets/${file}`, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
|
|
115
|
+
}
|
|
116
|
+
return { resolve, mounts, asset };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/host-sync.ts
|
|
120
|
+
var CONTROL_TOKEN_PREFIX = "hyle_tc_";
|
|
121
|
+
var DEFAULT_TIMEOUT_MS2 = 1e4;
|
|
122
|
+
var MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
123
|
+
var PATH = "/cp1/control/workspace/host-reserved-paths";
|
|
124
|
+
async function syncHostReserved(input) {
|
|
125
|
+
checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
|
|
126
|
+
if (!input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
|
|
127
|
+
throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
|
|
128
|
+
}
|
|
129
|
+
const fetchImpl = input.fetch ?? fetch;
|
|
130
|
+
const res = await fetchImpl(`${input.baseUrl.replace(/\/+$/, "")}${PATH}`, {
|
|
131
|
+
method: "PUT",
|
|
132
|
+
// redirect "error": the bearer token must never follow a redirect to another host.
|
|
133
|
+
redirect: "error",
|
|
134
|
+
signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
|
|
135
|
+
headers: {
|
|
136
|
+
authorization: `Bearer ${input.token}`,
|
|
137
|
+
"content-type": "application/json",
|
|
138
|
+
"cp-workspace": input.workspaceId,
|
|
139
|
+
"idempotency-key": `sync-${crypto.randomUUID()}`
|
|
140
|
+
},
|
|
141
|
+
body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
|
|
142
|
+
});
|
|
143
|
+
const text = await readCapped(res, MAX_RESPONSE_BYTES);
|
|
144
|
+
let parsed;
|
|
145
|
+
try {
|
|
146
|
+
parsed = JSON.parse(text);
|
|
147
|
+
} catch {
|
|
148
|
+
parsed = void 0;
|
|
149
|
+
}
|
|
150
|
+
const data = parsed?.data;
|
|
151
|
+
const conflicts = data?.conflicts;
|
|
152
|
+
if (res.ok && data && Array.isArray(data.paths) && typeof data.changed === "boolean" && typeof data.synced_at === "string" && typeof conflicts?.total === "number" && Array.isArray(conflicts.offenders)) {
|
|
153
|
+
return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
|
|
154
|
+
}
|
|
155
|
+
const err = parsed?.error;
|
|
156
|
+
throw new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${res.status})`, res.status, err?.request_id ?? "", err?.details);
|
|
99
157
|
}
|
|
100
158
|
|
|
101
159
|
// src/delivery-dedupe.ts
|
|
@@ -385,29 +443,50 @@ function checkRoutes(input) {
|
|
|
385
443
|
const shown = hostWins.length > 0 ? hostWins : matched;
|
|
386
444
|
dynamicOverlaps.push({ route, verdict: hostWins.length > 0 ? "host-wins" : "hyle-wins", matches: shown.length, examples: shown.slice(0, MAX_EXAMPLES) });
|
|
387
445
|
}
|
|
446
|
+
if (!routes.some((r) => r.startsWith(`${ASSET_ROUTE_PREFIX}/`))) {
|
|
447
|
+
notes.push(`no asset route (${ASSET_ROUTE_PREFIX}/[file], createAssetRoute) was found in the host routes: images, video and audio in hyle content will 404`);
|
|
448
|
+
}
|
|
388
449
|
if (catchAlls.length === 0) notes.push(`no hyle catch-all route (a "[...${hyleParam}]" or "[[...${hyleParam}]]" page) was found in the host routes`);
|
|
389
450
|
return { shadowedHylePaths, mountCollisions, dynamicOverlaps, notes, ok: shadowedHylePaths.length === 0 && mountCollisions.length === 0 };
|
|
390
451
|
}
|
|
452
|
+
var SDK_OWN_RESERVED = [ASSET_RESERVED_PATH];
|
|
453
|
+
var HASHED_METADATA_ROUTE = /^(opengraph-image|twitter-image|icon|apple-icon)-[a-z0-9]{5,8}$/;
|
|
454
|
+
var isHashedMetadataRoute = (route) => HASHED_METADATA_ROUTE.test(segmentsOf(route).at(-1) ?? "");
|
|
455
|
+
var covers = (entry, path) => {
|
|
456
|
+
if (!entry.endsWith("/*")) return entry === path;
|
|
457
|
+
const base = entry.slice(0, -2);
|
|
458
|
+
return path === base || path.startsWith(`${base}/`);
|
|
459
|
+
};
|
|
391
460
|
function reservedFor(hostRoutes, options = {}) {
|
|
392
461
|
const dropLocale = (route) => {
|
|
393
462
|
const [first, ...rest] = segmentsOf(route);
|
|
394
463
|
return options.locale && first === `[${LOCALE_PARAM}]` ? `/${rest.join("/")}` : route;
|
|
395
464
|
};
|
|
396
|
-
const
|
|
465
|
+
const hyleParam = options.hyleParam ?? "hyle";
|
|
466
|
+
const routes = hostRoutes.map(dropLocale).filter((r) => !isHashedMetadataRoute(r));
|
|
467
|
+
const exact = new Set(routes.filter((r) => !isDynamic(r)));
|
|
397
468
|
const mounts = options.mounts?.filter((m) => m !== "/");
|
|
469
|
+
const onMount = (segment) => mounts?.some((m) => m === `/${segment}` || m.startsWith(`/${segment}/`)) ?? true;
|
|
398
470
|
const groups = /* @__PURE__ */ new Map();
|
|
399
471
|
for (const route of exact) {
|
|
400
472
|
const [first, ...rest] = segmentsOf(route);
|
|
401
473
|
if (first !== void 0 && rest.length > 0) groups.set(first, [...groups.get(first) ?? [], route]);
|
|
402
474
|
}
|
|
475
|
+
const wildcards = /* @__PURE__ */ new Set();
|
|
403
476
|
for (const [first, members] of groups) {
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
477
|
+
if (members.length >= 2 && !onMount(first)) wildcards.add(`/${first}/*`);
|
|
478
|
+
}
|
|
479
|
+
for (const route of routes.filter(isDynamic)) {
|
|
480
|
+
const segments = parse(route);
|
|
481
|
+
const last = segments.at(-1);
|
|
482
|
+
if ((last?.kind === "catch-all" || last?.kind === "optional-catch-all") && last.name === hyleParam) continue;
|
|
483
|
+
const dir = segments.slice(0, segments.findIndex((seg) => seg.kind !== "static")).map((seg) => seg.kind === "static" ? seg.value : "").join("/");
|
|
484
|
+
if (dir === "" || !mounts) continue;
|
|
485
|
+
if (!mounts.some((m) => m === `/${dir}` || m.startsWith(`/${dir}/`))) wildcards.add(`/${dir}/*`);
|
|
409
486
|
}
|
|
410
|
-
|
|
487
|
+
const all = [...exact, ...wildcards];
|
|
488
|
+
const base = (entry) => entry.endsWith("/*") ? entry.slice(0, -2) : entry;
|
|
489
|
+
return all.filter((entry) => !all.some((other) => other !== entry && other.endsWith("/*") && covers(other, base(entry)))).sort();
|
|
411
490
|
}
|
|
412
491
|
function formatReport(report) {
|
|
413
492
|
const lines = [];
|
|
@@ -439,6 +518,7 @@ var printable = (text) => {
|
|
|
439
518
|
export {
|
|
440
519
|
Cp1ClientError,
|
|
441
520
|
createHyleClient,
|
|
521
|
+
syncHostReserved,
|
|
442
522
|
DeliveryDedupe,
|
|
443
523
|
parseSignatureHeader,
|
|
444
524
|
verifyHyleSignature,
|
|
@@ -450,6 +530,7 @@ export {
|
|
|
450
530
|
hostRoutesFromManifests,
|
|
451
531
|
routeMatches,
|
|
452
532
|
checkRoutes,
|
|
533
|
+
SDK_OWN_RESERVED,
|
|
453
534
|
reservedFor,
|
|
454
535
|
formatReport
|
|
455
536
|
};
|
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import {
|
|
2
|
+
hostAssetHtml,
|
|
3
|
+
hostAssetSrc
|
|
4
|
+
} from "./chunk-67IOIAVW.js";
|
|
5
|
+
|
|
1
6
|
// src/react/content.tsx
|
|
2
7
|
import { toJsxRuntime } from "hast-util-to-jsx-runtime";
|
|
3
8
|
import { Children, Fragment as Fragment2, isValidElement } from "react";
|
|
@@ -194,6 +199,7 @@ function clean(node, depth, ctx2, budget) {
|
|
|
194
199
|
if (Object.hasOwn(rules, key) && rules[key](value, inner)) properties[key] = value;
|
|
195
200
|
}
|
|
196
201
|
}
|
|
202
|
+
if ((tag === "img" || tag === "video" || tag === "audio") && typeof properties.src === "string") properties.src = hostAssetSrc(properties.src);
|
|
197
203
|
if (tag === "iframe") {
|
|
198
204
|
if (properties.sandbox === void 0 || properties.srcdoc === void 0) return [];
|
|
199
205
|
properties.sandbox = "allow-scripts";
|
|
@@ -541,7 +547,7 @@ function HastContent({ tree, title, components = {}, locale }) {
|
|
|
541
547
|
});
|
|
542
548
|
}
|
|
543
549
|
function TrustedServerHtml({ html }) {
|
|
544
|
-
return /* @__PURE__ */ jsx3("div", { dangerouslySetInnerHTML: { __html: html } });
|
|
550
|
+
return /* @__PURE__ */ jsx3("div", { dangerouslySetInnerHTML: { __html: hostAssetHtml(html) } });
|
|
545
551
|
}
|
|
546
552
|
|
|
547
553
|
// src/react/index.ts
|