@tdacorp/hyle-sdk 0.3.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 +135 -5
- package/bin/hyle-sdk-check-routes.mjs +3 -0
- package/dist/check-routes-bin.js +537 -0
- package/dist/chunk-67IOIAVW.js +35 -0
- package/dist/chunk-BUJFMR3M.js +38 -0
- package/dist/chunk-EBNIKRQH.js +536 -0
- package/dist/{chunk-EARQBSMF.js → chunk-LGW2KP4X.js} +109 -5
- package/dist/{chunk-7VCMJUPC.js → chunk-N4QYPO7S.js} +1 -1
- package/dist/diagram-viewer-DYX6R63Y.js +1132 -0
- package/dist/index.cjs +279 -23
- package/dist/index.d.cts +147 -3
- package/dist/index.d.ts +147 -3
- package/dist/index.js +18 -1
- package/dist/mermaid-diagram.cjs +1267 -16
- package/dist/mermaid-diagram.d.cts +39 -1
- package/dist/mermaid-diagram.d.ts +39 -1
- package/dist/mermaid-diagram.js +35 -5
- package/dist/next.cjs +385 -30
- package/dist/next.d.cts +93 -5
- package/dist/next.d.ts +93 -5
- package/dist/next.js +210 -5
- package/dist/react.cjs +118 -5
- package/dist/react.d.cts +44 -4
- package/dist/react.d.ts +44 -4
- package/dist/react.js +2 -1
- package/dist/{resolve-fMx2W8RR.d.ts → resolve-1rQntRBh.d.ts} +1 -1
- package/dist/{resolve-B_p0p4Zn.d.cts → resolve-36-Ng1H0.d.cts} +1 -1
- package/dist/styles.css +76 -0
- package/dist/{types-CBvLhUPr.d.ts → types-BoyBWF2F.d.ts} +1 -1
- package/dist/{types-DjXf6iPo.d.cts → types-CwBCPh6K.d.cts} +20 -1
- package/dist/{types-DjXf6iPo.d.ts → types-CwBCPh6K.d.ts} +20 -1
- package/dist/{types-D0qoLh4E.d.cts → types-DnPzhrFx.d.cts} +1 -1
- package/dist/use-cache.cjs +55 -23
- package/dist/use-cache.d.cts +2 -2
- package/dist/use-cache.d.ts +2 -2
- package/dist/use-cache.js +3 -2
- package/package.json +5 -1
- package/dist/chunk-HFUJRNFP.js +0 -290
package/dist/index.cjs
CHANGED
|
@@ -23,15 +23,31 @@ __export(src_exports, {
|
|
|
23
23
|
CACHE_TAG_PATTERN: () => CACHE_TAG_PATTERN,
|
|
24
24
|
Cp1ClientError: () => Cp1ClientError,
|
|
25
25
|
DeliveryDedupe: () => DeliveryDedupe,
|
|
26
|
+
SDK_OWN_RESERVED: () => SDK_OWN_RESERVED,
|
|
27
|
+
checkRoutes: () => checkRoutes,
|
|
26
28
|
createHyleClient: () => createHyleClient,
|
|
27
29
|
createRevalidationCallbackRoute: () => createRevalidationCallbackRoute,
|
|
30
|
+
formatReport: () => formatReport,
|
|
31
|
+
hostRoutesFromManifests: () => hostRoutesFromManifests,
|
|
28
32
|
isValidCacheTag: () => isValidCacheTag,
|
|
29
33
|
listPublicationPaths: () => listPublicationPaths,
|
|
34
|
+
normalizeRoute: () => normalizeRoute,
|
|
30
35
|
parseSignatureHeader: () => parseSignatureHeader,
|
|
36
|
+
reservedFor: () => reservedFor,
|
|
37
|
+
routeMatches: () => routeMatches,
|
|
38
|
+
syncHostReserved: () => syncHostReserved,
|
|
31
39
|
verifyHyleSignature: () => verifyHyleSignature
|
|
32
40
|
});
|
|
33
41
|
module.exports = __toCommonJS(src_exports);
|
|
34
42
|
|
|
43
|
+
// src/asset-path.ts
|
|
44
|
+
var ASSET_ROUTE_PREFIX = "/api/hyle/assets";
|
|
45
|
+
var ASSET_RESERVED_PATH = "/api/hyle/*";
|
|
46
|
+
var UUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
|
|
47
|
+
var EXTENSIONS = "png|jpg|gif|webp|svg|pdf|mp4|webm|mp3|ogg";
|
|
48
|
+
var ASSET_FILE = new RegExp(`^${UUID}(?:\\.(?:${EXTENSIONS}))?$`);
|
|
49
|
+
var HYLE_ASSET_URL = new RegExp(`^/assets/(${UUID}(?:\\.(?:${EXTENSIONS}))?)$`, "i");
|
|
50
|
+
|
|
35
51
|
// src/errors.ts
|
|
36
52
|
var Cp1ClientError = class extends Error {
|
|
37
53
|
code;
|
|
@@ -72,31 +88,35 @@ async function readCapped(res, max) {
|
|
|
72
88
|
return Buffer.concat(chunks).toString("utf8");
|
|
73
89
|
}
|
|
74
90
|
var KINDS = /* @__PURE__ */ new Set(["article", "list", "redirect", "notfound", "disabled"]);
|
|
75
|
-
|
|
91
|
+
var isStrings = (value) => Array.isArray(value) && value.every((v) => typeof v === "string");
|
|
92
|
+
function isMounts(data) {
|
|
93
|
+
const mounts = data.mounts;
|
|
94
|
+
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");
|
|
95
|
+
}
|
|
96
|
+
function checkBaseUrl(baseUrl, allowInsecureHttp) {
|
|
76
97
|
let origin;
|
|
77
98
|
try {
|
|
78
|
-
origin = new URL(
|
|
99
|
+
origin = new URL(baseUrl);
|
|
79
100
|
} catch {
|
|
80
101
|
throw new TypeError("baseUrl must be an https origin");
|
|
81
102
|
}
|
|
82
|
-
if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (
|
|
103
|
+
if (origin.protocol !== "https:" && !(origin.protocol === "http:" && (allowInsecureHttp || LOOPBACK.has(origin.hostname)))) {
|
|
83
104
|
throw new TypeError("baseUrl must be https (http is allowed only for localhost, or with allowInsecureHttp)");
|
|
84
105
|
}
|
|
106
|
+
}
|
|
107
|
+
function createHyleClient(options) {
|
|
108
|
+
checkBaseUrl(options.baseUrl, options.allowInsecureHttp);
|
|
85
109
|
if (!options.token) throw new TypeError("token is required");
|
|
86
110
|
const base = options.baseUrl.replace(/\/+$/, "");
|
|
87
111
|
const fetchImpl = options.fetch ?? fetch;
|
|
88
|
-
async function
|
|
89
|
-
const url = new URL(`${base}
|
|
90
|
-
url.
|
|
91
|
-
|
|
92
|
-
if (opts.format !== void 0) url.searchParams.set("format", opts.format);
|
|
93
|
-
if (opts.cursor !== void 0) url.searchParams.set("cursor", opts.cursor);
|
|
94
|
-
if (opts.limit !== void 0) url.searchParams.set("limit", String(opts.limit));
|
|
95
|
-
const headers = new Headers(opts.init?.headers);
|
|
112
|
+
async function get(pathname, query, init) {
|
|
113
|
+
const url = new URL(`${base}${pathname}`);
|
|
114
|
+
url.search = query.toString();
|
|
115
|
+
const headers = new Headers(init?.headers);
|
|
96
116
|
headers.set("authorization", `Bearer ${options.token}`);
|
|
97
117
|
const timeout = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
98
|
-
const signal =
|
|
99
|
-
const res = await fetchImpl(url.toString(), { ...
|
|
118
|
+
const signal = init?.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
|
|
119
|
+
const res = await fetchImpl(url.toString(), { ...init, method: "GET", headers, redirect: "error", signal });
|
|
100
120
|
const text = await readCapped(res, options.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES);
|
|
101
121
|
let parsed;
|
|
102
122
|
try {
|
|
@@ -104,18 +124,80 @@ function createHyleClient(options) {
|
|
|
104
124
|
} catch {
|
|
105
125
|
parsed = void 0;
|
|
106
126
|
}
|
|
107
|
-
|
|
108
|
-
|
|
127
|
+
return { parsed, status: res.status };
|
|
128
|
+
}
|
|
129
|
+
const failure = ({ parsed, status }) => {
|
|
109
130
|
const err = parsed?.error;
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
);
|
|
131
|
+
return new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${status})`, status, err?.request_id ?? "", err?.details);
|
|
132
|
+
};
|
|
133
|
+
async function resolve(opts) {
|
|
134
|
+
const query = new URLSearchParams({ path: opts.path });
|
|
135
|
+
if (opts.locale !== void 0) query.set("locale", opts.locale);
|
|
136
|
+
if (opts.format !== void 0) query.set("format", opts.format);
|
|
137
|
+
if (opts.cursor !== void 0) query.set("cursor", opts.cursor);
|
|
138
|
+
if (opts.limit !== void 0) query.set("limit", String(opts.limit));
|
|
139
|
+
const reply = await get("/cp1/read/resolve", query, opts.init);
|
|
140
|
+
const data = reply.parsed?.data;
|
|
141
|
+
if (data && data.cp === 1 && typeof data.kind === "string" && KINDS.has(data.kind)) return data;
|
|
142
|
+
throw failure(reply);
|
|
143
|
+
}
|
|
144
|
+
async function mounts(opts = {}) {
|
|
145
|
+
const reply = await get("/cp1/read/mounts", new URLSearchParams(), opts.init);
|
|
146
|
+
const data = reply.parsed?.data;
|
|
147
|
+
if (data?.cp === 1 && data.kind === "disabled") return data;
|
|
148
|
+
if (data?.cp === 1 && data.kind === "mounts" && isMounts(data)) return data;
|
|
149
|
+
throw failure(reply);
|
|
117
150
|
}
|
|
118
|
-
|
|
151
|
+
async function asset(file, opts = {}) {
|
|
152
|
+
if (!ASSET_FILE.test(file)) throw new TypeError("asset file must be <uuid>[.<ext>]");
|
|
153
|
+
const headers = new Headers({ authorization: `Bearer ${options.token}` });
|
|
154
|
+
for (const name of ["range", "if-range", "if-none-match"]) {
|
|
155
|
+
const value = opts.headers?.[name];
|
|
156
|
+
if (value) headers.set(name, value);
|
|
157
|
+
}
|
|
158
|
+
return fetchImpl(`${base}/cp1/read/assets/${file}`, { method: "GET", headers, redirect: "error", signal: AbortSignal.timeout(opts.timeoutMs ?? options.timeoutMs ?? DEFAULT_TIMEOUT_MS) });
|
|
159
|
+
}
|
|
160
|
+
return { resolve, mounts, asset };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// src/host-sync.ts
|
|
164
|
+
var CONTROL_TOKEN_PREFIX = "hyle_tc_";
|
|
165
|
+
var DEFAULT_TIMEOUT_MS2 = 1e4;
|
|
166
|
+
var MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
167
|
+
var PATH = "/cp1/control/workspace/host-reserved-paths";
|
|
168
|
+
async function syncHostReserved(input) {
|
|
169
|
+
checkBaseUrl(input.baseUrl, input.allowInsecureHttp);
|
|
170
|
+
if (!input.token.startsWith(CONTROL_TOKEN_PREFIX)) {
|
|
171
|
+
throw new TypeError("syncing needs a control credential (hyle_tc_...); a target token is read-only and cannot write");
|
|
172
|
+
}
|
|
173
|
+
const fetchImpl = input.fetch ?? fetch;
|
|
174
|
+
const res = await fetchImpl(`${input.baseUrl.replace(/\/+$/, "")}${PATH}`, {
|
|
175
|
+
method: "PUT",
|
|
176
|
+
// redirect "error": the bearer token must never follow a redirect to another host.
|
|
177
|
+
redirect: "error",
|
|
178
|
+
signal: AbortSignal.timeout(input.timeoutMs ?? DEFAULT_TIMEOUT_MS2),
|
|
179
|
+
headers: {
|
|
180
|
+
authorization: `Bearer ${input.token}`,
|
|
181
|
+
"content-type": "application/json",
|
|
182
|
+
"cp-workspace": input.workspaceId,
|
|
183
|
+
"idempotency-key": `sync-${crypto.randomUUID()}`
|
|
184
|
+
},
|
|
185
|
+
body: JSON.stringify({ paths: input.paths, host: input.host, build_id: input.buildId })
|
|
186
|
+
});
|
|
187
|
+
const text = await readCapped(res, MAX_RESPONSE_BYTES);
|
|
188
|
+
let parsed;
|
|
189
|
+
try {
|
|
190
|
+
parsed = JSON.parse(text);
|
|
191
|
+
} catch {
|
|
192
|
+
parsed = void 0;
|
|
193
|
+
}
|
|
194
|
+
const data = parsed?.data;
|
|
195
|
+
const conflicts = data?.conflicts;
|
|
196
|
+
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)) {
|
|
197
|
+
return { paths: data.paths, changed: data.changed, syncedAt: data.synced_at, conflicts: { total: conflicts.total, offenders: conflicts.offenders } };
|
|
198
|
+
}
|
|
199
|
+
const err = parsed?.error;
|
|
200
|
+
throw new Cp1ClientError(err?.code ?? "INVALID_RESPONSE", err?.message ?? `Unexpected response from hyle (HTTP ${res.status})`, res.status, err?.request_id ?? "", err?.details);
|
|
119
201
|
}
|
|
120
202
|
|
|
121
203
|
// src/delivery-dedupe.ts
|
|
@@ -310,15 +392,189 @@ async function listPublicationPaths(options) {
|
|
|
310
392
|
}
|
|
311
393
|
return { paths: [...found].map(([path, publishedAt]) => ({ path, publishedAt })), complete };
|
|
312
394
|
}
|
|
395
|
+
|
|
396
|
+
// src/route-check.ts
|
|
397
|
+
var NOT_ROUTES = /* @__PURE__ */ new Set(["/_not-found", "/_global-error", "/_app", "/_error", "/_document", "/404", "/500"]);
|
|
398
|
+
var LOCALE_PARAM = "locale";
|
|
399
|
+
function normalizeRoute(key) {
|
|
400
|
+
const segments = key.replace(/\/(page|route)$/, "").split("/").filter((s) => s !== "");
|
|
401
|
+
if (segments.some((s) => s.startsWith("@") || /^\(\.{1,3}\)/.test(s))) return void 0;
|
|
402
|
+
const route = `/${segments.filter((s) => !/^\(.*\)$/.test(s)).join("/")}`;
|
|
403
|
+
return NOT_ROUTES.has(route) ? void 0 : route;
|
|
404
|
+
}
|
|
405
|
+
function hostRoutesFromManifests({ routesManifest, appPaths }) {
|
|
406
|
+
const keys = [...(routesManifest?.staticRoutes ?? []).map((r) => r.page), ...(routesManifest?.dynamicRoutes ?? []).map((r) => r.page), ...Object.keys(appPaths ?? {})];
|
|
407
|
+
return [...new Set(keys.map(normalizeRoute).filter((r) => r !== void 0))].sort();
|
|
408
|
+
}
|
|
409
|
+
var segmentsOf = (path) => path.split("/").filter((s) => s !== "");
|
|
410
|
+
function parse(route) {
|
|
411
|
+
return segmentsOf(route).map((value) => {
|
|
412
|
+
const optional = /^\[\[\.\.\.([^\]]+)\]\]$/.exec(value);
|
|
413
|
+
if (optional) return { kind: "optional-catch-all", name: optional[1] };
|
|
414
|
+
const rest = /^\[\.\.\.([^\]]+)\]$/.exec(value);
|
|
415
|
+
if (rest) return { kind: "catch-all", name: rest[1] };
|
|
416
|
+
const one = /^\[([^\]]+)\]$/.exec(value);
|
|
417
|
+
return one ? { kind: "dynamic", name: one[1] } : { kind: "static", value };
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
var isDynamic = (route) => parse(route).some((s) => s.kind !== "static");
|
|
421
|
+
function routeMatches(route, path) {
|
|
422
|
+
const pattern = parse(route);
|
|
423
|
+
const parts = segmentsOf(path);
|
|
424
|
+
for (const [i, seg] of pattern.entries()) {
|
|
425
|
+
if (seg.kind === "optional-catch-all") return i === pattern.length - 1;
|
|
426
|
+
if (seg.kind === "catch-all") return i === pattern.length - 1 && parts.length > i;
|
|
427
|
+
if (i >= parts.length || seg.kind === "static" && seg.value !== parts[i]) return false;
|
|
428
|
+
}
|
|
429
|
+
return parts.length === pattern.length;
|
|
430
|
+
}
|
|
431
|
+
var RANK = { static: 0, dynamic: 1, "catch-all": 2, "optional-catch-all": 3 };
|
|
432
|
+
function compareSpecificity(a, b) {
|
|
433
|
+
const [pa, pb] = [parse(a), parse(b)];
|
|
434
|
+
for (let i = 0; i < Math.min(pa.length, pb.length); i++) {
|
|
435
|
+
const d = RANK[pa[i].kind] - RANK[pb[i].kind];
|
|
436
|
+
if (d !== 0) return d;
|
|
437
|
+
}
|
|
438
|
+
return pa.length - pb.length;
|
|
439
|
+
}
|
|
440
|
+
function withLocale(path, locale) {
|
|
441
|
+
if (!locale) return [path];
|
|
442
|
+
const prefixed = (l) => path === "/" ? `/${l}` : `/${l}${path}`;
|
|
443
|
+
if (locale.prefix === "never") return [path];
|
|
444
|
+
return locale.locales.map((l) => locale.prefix === "as-needed" && l === locale.defaultLocale ? path : prefixed(l));
|
|
445
|
+
}
|
|
446
|
+
function expandLocale(route, locale) {
|
|
447
|
+
const [first, ...rest] = segmentsOf(route);
|
|
448
|
+
if (!locale || first !== `[${LOCALE_PARAM}]`) return [route];
|
|
449
|
+
return [...new Set(withLocale(`/${rest.join("/")}`, locale))];
|
|
450
|
+
}
|
|
451
|
+
var MAX_EXAMPLES = 5;
|
|
452
|
+
function checkRoutes(input) {
|
|
453
|
+
const { locale } = input;
|
|
454
|
+
const hyleParam = input.hyleParam ?? "hyle";
|
|
455
|
+
const routes = [...new Set(input.hostRoutes.flatMap((r) => expandLocale(r, locale)))];
|
|
456
|
+
const staticRoutes = new Set(routes.filter((r) => !isDynamic(r)));
|
|
457
|
+
const dynamicRoutes = routes.filter(isDynamic);
|
|
458
|
+
const catchAlls = dynamicRoutes.filter((r) => {
|
|
459
|
+
const last = parse(r).at(-1);
|
|
460
|
+
return (last?.kind === "catch-all" || last?.kind === "optional-catch-all") && last.name === hyleParam;
|
|
461
|
+
});
|
|
462
|
+
const notes = [];
|
|
463
|
+
const shadowedHylePaths = input.hylePaths.flatMap(
|
|
464
|
+
(path) => withLocale(path, locale).filter((url) => staticRoutes.has(url)).map((url) => ({ path, url, route: url }))
|
|
465
|
+
);
|
|
466
|
+
const mountCollisions = [];
|
|
467
|
+
for (const prefix of input.mounts) {
|
|
468
|
+
if (prefix === "/") {
|
|
469
|
+
if (staticRoutes.has("/")) notes.push(`root mount: the host's own home page owns "/", so hyle's index page is not served there (pages below it are)`);
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
for (const url of withLocale(prefix, locale)) if (staticRoutes.has(url)) mountCollisions.push({ prefix, url, route: url });
|
|
473
|
+
}
|
|
474
|
+
const urls = [...new Set([...input.hylePaths, ...input.mounts.filter((m) => m !== "/")].flatMap((p) => withLocale(p, locale)))];
|
|
475
|
+
const dynamicOverlaps = [];
|
|
476
|
+
for (const route of dynamicRoutes) {
|
|
477
|
+
const matched = urls.filter((u) => routeMatches(route, u));
|
|
478
|
+
if (catchAlls.includes(route)) {
|
|
479
|
+
dynamicOverlaps.push({ route, verdict: "hyle-catch-all", matches: matched.length, examples: matched.slice(0, MAX_EXAMPLES) });
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
const hostWins = matched.filter((u) => {
|
|
483
|
+
const best = catchAlls.filter((c) => routeMatches(c, u)).sort(compareSpecificity)[0];
|
|
484
|
+
return best === void 0 || compareSpecificity(route, best) <= 0;
|
|
485
|
+
});
|
|
486
|
+
if (matched.length === 0) continue;
|
|
487
|
+
const shown = hostWins.length > 0 ? hostWins : matched;
|
|
488
|
+
dynamicOverlaps.push({ route, verdict: hostWins.length > 0 ? "host-wins" : "hyle-wins", matches: shown.length, examples: shown.slice(0, MAX_EXAMPLES) });
|
|
489
|
+
}
|
|
490
|
+
if (!routes.some((r) => r.startsWith(`${ASSET_ROUTE_PREFIX}/`))) {
|
|
491
|
+
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`);
|
|
492
|
+
}
|
|
493
|
+
if (catchAlls.length === 0) notes.push(`no hyle catch-all route (a "[...${hyleParam}]" or "[[...${hyleParam}]]" page) was found in the host routes`);
|
|
494
|
+
return { shadowedHylePaths, mountCollisions, dynamicOverlaps, notes, ok: shadowedHylePaths.length === 0 && mountCollisions.length === 0 };
|
|
495
|
+
}
|
|
496
|
+
var SDK_OWN_RESERVED = [ASSET_RESERVED_PATH];
|
|
497
|
+
var HASHED_METADATA_ROUTE = /^(opengraph-image|twitter-image|icon|apple-icon)-[a-z0-9]{5,8}$/;
|
|
498
|
+
var isHashedMetadataRoute = (route) => HASHED_METADATA_ROUTE.test(segmentsOf(route).at(-1) ?? "");
|
|
499
|
+
var covers = (entry, path) => {
|
|
500
|
+
if (!entry.endsWith("/*")) return entry === path;
|
|
501
|
+
const base = entry.slice(0, -2);
|
|
502
|
+
return path === base || path.startsWith(`${base}/`);
|
|
503
|
+
};
|
|
504
|
+
function reservedFor(hostRoutes, options = {}) {
|
|
505
|
+
const dropLocale = (route) => {
|
|
506
|
+
const [first, ...rest] = segmentsOf(route);
|
|
507
|
+
return options.locale && first === `[${LOCALE_PARAM}]` ? `/${rest.join("/")}` : route;
|
|
508
|
+
};
|
|
509
|
+
const hyleParam = options.hyleParam ?? "hyle";
|
|
510
|
+
const routes = hostRoutes.map(dropLocale).filter((r) => !isHashedMetadataRoute(r));
|
|
511
|
+
const exact = new Set(routes.filter((r) => !isDynamic(r)));
|
|
512
|
+
const mounts = options.mounts?.filter((m) => m !== "/");
|
|
513
|
+
const onMount = (segment) => mounts?.some((m) => m === `/${segment}` || m.startsWith(`/${segment}/`)) ?? true;
|
|
514
|
+
const groups = /* @__PURE__ */ new Map();
|
|
515
|
+
for (const route of exact) {
|
|
516
|
+
const [first, ...rest] = segmentsOf(route);
|
|
517
|
+
if (first !== void 0 && rest.length > 0) groups.set(first, [...groups.get(first) ?? [], route]);
|
|
518
|
+
}
|
|
519
|
+
const wildcards = /* @__PURE__ */ new Set();
|
|
520
|
+
for (const [first, members] of groups) {
|
|
521
|
+
if (members.length >= 2 && !onMount(first)) wildcards.add(`/${first}/*`);
|
|
522
|
+
}
|
|
523
|
+
for (const route of routes.filter(isDynamic)) {
|
|
524
|
+
const segments = parse(route);
|
|
525
|
+
const last = segments.at(-1);
|
|
526
|
+
if ((last?.kind === "catch-all" || last?.kind === "optional-catch-all") && last.name === hyleParam) continue;
|
|
527
|
+
const dir = segments.slice(0, segments.findIndex((seg) => seg.kind !== "static")).map((seg) => seg.kind === "static" ? seg.value : "").join("/");
|
|
528
|
+
if (dir === "" || !mounts) continue;
|
|
529
|
+
if (!mounts.some((m) => m === `/${dir}` || m.startsWith(`/${dir}/`))) wildcards.add(`/${dir}/*`);
|
|
530
|
+
}
|
|
531
|
+
const all = [...exact, ...wildcards];
|
|
532
|
+
const base = (entry) => entry.endsWith("/*") ? entry.slice(0, -2) : entry;
|
|
533
|
+
return all.filter((entry) => !all.some((other) => other !== entry && other.endsWith("/*") && covers(other, base(entry)))).sort();
|
|
534
|
+
}
|
|
535
|
+
function formatReport(report) {
|
|
536
|
+
const lines = [];
|
|
537
|
+
const section = (title, rows, empty) => lines.push(`${title}`, ...rows.length ? rows.map((r) => ` ${printable(r)}`) : [` ${empty}`], "");
|
|
538
|
+
section(
|
|
539
|
+
"(a) hyle paths shadowed by host static routes (the hyle page is never served):",
|
|
540
|
+
report.shadowedHylePaths.map((s) => `${s.url} (hyle path ${s.path})`),
|
|
541
|
+
"none"
|
|
542
|
+
);
|
|
543
|
+
section("(c) mounts whose prefix is a host static route (the mount's index page is never served):", report.mountCollisions.map((m) => `${m.url} (mount ${m.prefix})`), "none");
|
|
544
|
+
section(
|
|
545
|
+
"(b) host dynamic routes matching hyle URLs:",
|
|
546
|
+
report.dynamicOverlaps.map((d) => {
|
|
547
|
+
const label = { "hyle-catch-all": "OK: this is hyle's catch-all", "hyle-wins": "OK: hyle's catch-all is more specific", "host-wins": "WARN: the host route is served, hyle content is hidden" }[d.verdict];
|
|
548
|
+
return `${d.route} ${label} (${d.matches} URLs, e.g. ${d.examples.join(", ") || "-"})`;
|
|
549
|
+
}),
|
|
550
|
+
"none"
|
|
551
|
+
);
|
|
552
|
+
if (report.notes.length) section("notes:", report.notes, "");
|
|
553
|
+
lines.push(report.ok ? "RESULT: no collisions" : "RESULT: collisions found");
|
|
554
|
+
return lines.join("\n");
|
|
555
|
+
}
|
|
556
|
+
var MAX_PRINTED = 200;
|
|
557
|
+
var printable = (text) => {
|
|
558
|
+
const clean = text.replace(/\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|.)?/g, "").replace(/[\u0000-\u001f\u007f-\u009f]/g, "");
|
|
559
|
+
return clean.length > MAX_PRINTED ? `${clean.slice(0, MAX_PRINTED)}...` : clean;
|
|
560
|
+
};
|
|
313
561
|
// Annotate the CommonJS export names for ESM import in node:
|
|
314
562
|
0 && (module.exports = {
|
|
315
563
|
CACHE_TAG_PATTERN,
|
|
316
564
|
Cp1ClientError,
|
|
317
565
|
DeliveryDedupe,
|
|
566
|
+
SDK_OWN_RESERVED,
|
|
567
|
+
checkRoutes,
|
|
318
568
|
createHyleClient,
|
|
319
569
|
createRevalidationCallbackRoute,
|
|
570
|
+
formatReport,
|
|
571
|
+
hostRoutesFromManifests,
|
|
320
572
|
isValidCacheTag,
|
|
321
573
|
listPublicationPaths,
|
|
574
|
+
normalizeRoute,
|
|
322
575
|
parseSignatureHeader,
|
|
576
|
+
reservedFor,
|
|
577
|
+
routeMatches,
|
|
578
|
+
syncHostReserved,
|
|
323
579
|
verifyHyleSignature
|
|
324
580
|
});
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { R as Resolved } from './types-
|
|
2
|
-
export { A as Alternate, a as ArticleContent, B as Breadcrumb, C as CacheInfo, F as Fallback, L as ListItem, N as NavItem,
|
|
1
|
+
import { R as Resolved, M as MountsResult } from './types-CwBCPh6K.cjs';
|
|
2
|
+
export { A as Alternate, a as ArticleContent, B as Breadcrumb, C as CacheInfo, F as Fallback, L as ListItem, b as Mount, c as Mounts, N as NavItem, d as ResolvedArticle, e as ResolvedDisabled, f as ResolvedList, g as ResolvedNotFound, h as ResolvedRedirect, T as TocEntry } from './types-CwBCPh6K.cjs';
|
|
3
3
|
export { R as RevalidationCallbackOptions, a as RevalidationCallbackRoute, b as RevalidationPayload, c as createRevalidationCallbackRoute } from './revalidation-callback-D7Ms_Puz.cjs';
|
|
4
4
|
|
|
5
5
|
/** `next` is a Next.js fetch extension with no lib.dom type; typed structurally so this module needs no Next import. */
|
|
@@ -33,8 +33,24 @@ interface ResolveOptions {
|
|
|
33
33
|
/** Extra fetch options (for example Next's `next: { tags, revalidate }`). Method, body and the auth header cannot be overridden. */
|
|
34
34
|
readonly init?: HyleRequestInit;
|
|
35
35
|
}
|
|
36
|
+
interface MountsOptions {
|
|
37
|
+
/** Extra fetch options (for example Next's `next: { tags, revalidate }`). Method, body and the auth header cannot be overridden. */
|
|
38
|
+
readonly init?: HyleRequestInit;
|
|
39
|
+
}
|
|
40
|
+
interface AssetOptions {
|
|
41
|
+
/** Only these request headers are sent upstream: a browser's own cache validators and byte range. Everything else is dropped. */
|
|
42
|
+
readonly headers?: {
|
|
43
|
+
readonly range?: string | null;
|
|
44
|
+
readonly "if-range"?: string | null;
|
|
45
|
+
readonly "if-none-match"?: string | null;
|
|
46
|
+
};
|
|
47
|
+
/** Abort after this many milliseconds, body included. Default: the client's `timeoutMs`. */
|
|
48
|
+
readonly timeoutMs?: number;
|
|
49
|
+
}
|
|
36
50
|
declare function createHyleClient(options: HyleClientOptions): {
|
|
37
51
|
resolve: (opts: ResolveOptions) => Promise<Resolved>;
|
|
52
|
+
mounts: (opts?: MountsOptions) => Promise<MountsResult>;
|
|
53
|
+
asset: (file: string, opts?: AssetOptions) => Promise<Response>;
|
|
38
54
|
};
|
|
39
55
|
type HyleClient = ReturnType<typeof createHyleClient>;
|
|
40
56
|
|
|
@@ -46,6 +62,41 @@ declare class Cp1ClientError extends Error {
|
|
|
46
62
|
constructor(code: string, message: string, status: number, requestId: string, details?: Record<string, unknown>);
|
|
47
63
|
}
|
|
48
64
|
|
|
65
|
+
interface HostSyncInput {
|
|
66
|
+
/** hyle's origin. */
|
|
67
|
+
readonly baseUrl: string;
|
|
68
|
+
/** A CONTROL credential (hyle_tc_...) holding hyle.workspace.manage on the workspace. Never a target (read) token. */
|
|
69
|
+
readonly token: string;
|
|
70
|
+
/** The workspace to write, from `client.mounts()`; the credential must be granted on it. */
|
|
71
|
+
readonly workspaceId: string;
|
|
72
|
+
/** The host's complete list of reserved paths (a replace). */
|
|
73
|
+
readonly paths: readonly string[];
|
|
74
|
+
readonly host: string;
|
|
75
|
+
readonly buildId: string;
|
|
76
|
+
readonly fetch?: typeof fetch;
|
|
77
|
+
readonly timeoutMs?: number;
|
|
78
|
+
readonly allowInsecureHttp?: boolean;
|
|
79
|
+
}
|
|
80
|
+
interface HostSyncResult {
|
|
81
|
+
/** What hyle stored: sorted, de-duplicated. */
|
|
82
|
+
readonly paths: readonly string[];
|
|
83
|
+
/** False when hyle already held exactly this list. */
|
|
84
|
+
readonly changed: boolean;
|
|
85
|
+
readonly syncedAt: string;
|
|
86
|
+
/** Published hyle URLs the list now covers. hyle unpublishes nothing; the host decides what to do. */
|
|
87
|
+
readonly conflicts: {
|
|
88
|
+
readonly total: number;
|
|
89
|
+
readonly offenders: readonly string[];
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Reports the host's reserved paths to hyle (ADR 0016): `PUT /cp1/control/workspace/host-reserved-paths`. Idempotent (resending the
|
|
94
|
+
* same list changes nothing), so a retry or a repeated deploy is safe; the random Idempotency-Key only satisfies the control
|
|
95
|
+
* surface's mutation rule. Throws `TypeError` before any request for a wrong token kind or an insecure URL, and `Cp1ClientError`
|
|
96
|
+
* for anything hyle answers or the network does.
|
|
97
|
+
*/
|
|
98
|
+
declare function syncHostReserved(input: HostSyncInput): Promise<HostSyncResult>;
|
|
99
|
+
|
|
49
100
|
/**
|
|
50
101
|
* docs/cp1-spec.md section 5.2: `Hyle-Signature: t=<unix seconds>,v1=<hex>,v1=<hex>`.
|
|
51
102
|
* Multiple v1= values support dual-secret rotation with no receiver-side
|
|
@@ -128,4 +179,97 @@ interface ListPublicationPathsOptions {
|
|
|
128
179
|
*/
|
|
129
180
|
declare function listPublicationPaths(options: ListPublicationPathsOptions): Promise<PublicationPaths>;
|
|
130
181
|
|
|
131
|
-
|
|
182
|
+
/**
|
|
183
|
+
* Route-collision analysis between a Next host app and the paths hyle serves. Pure: the CLI (`hyle-sdk-check-routes`) reads
|
|
184
|
+
* `.next` and calls hyle, then hands plain data to these functions. A host route always wins over `hyleRootPage` (Next matches
|
|
185
|
+
* specific routes first), so a collision never breaks the host: it silently hides hyle content.
|
|
186
|
+
*/
|
|
187
|
+
type LocalePrefix = "as-needed" | "always" | "never";
|
|
188
|
+
interface LocaleOptions {
|
|
189
|
+
readonly locales: readonly string[];
|
|
190
|
+
readonly defaultLocale: string;
|
|
191
|
+
/** next-intl's `localePrefix`: "as-needed" leaves the default locale unprefixed. */
|
|
192
|
+
readonly prefix: LocalePrefix;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* A host route key as a URL pattern: "/(site)/[locale]/about/page" -> "/[locale]/about". Handles `.next/server/app-paths-manifest.json`
|
|
196
|
+
* keys (trailing "/page" or "/route") and routes-manifest pages. Route groups "(x)" are removed. Returns undefined for what is not a
|
|
197
|
+
* URL a visitor can request: parallel-route slots "@x", intercepting routes "(.)x", and Next's internal pages.
|
|
198
|
+
*/
|
|
199
|
+
declare function normalizeRoute(key: string): string | undefined;
|
|
200
|
+
interface NextManifests {
|
|
201
|
+
readonly routesManifest?: {
|
|
202
|
+
readonly staticRoutes?: readonly {
|
|
203
|
+
readonly page: string;
|
|
204
|
+
}[];
|
|
205
|
+
readonly dynamicRoutes?: readonly {
|
|
206
|
+
readonly page: string;
|
|
207
|
+
}[];
|
|
208
|
+
};
|
|
209
|
+
readonly appPaths?: Readonly<Record<string, string>>;
|
|
210
|
+
}
|
|
211
|
+
/** Every host route pattern from `routes-manifest.json` and `server/app-paths-manifest.json`, normalized, de-duplicated and sorted. */
|
|
212
|
+
declare function hostRoutesFromManifests({ routesManifest, appPaths }: NextManifests): string[];
|
|
213
|
+
/** Does the route pattern match the URL path? `[x]` is one segment, `[...x]` one or more, `[[...x]]` zero or more. */
|
|
214
|
+
declare function routeMatches(route: string, path: string): boolean;
|
|
215
|
+
interface RouteCheckInput {
|
|
216
|
+
/** From `hostRoutesFromManifests`. */
|
|
217
|
+
readonly hostRoutes: readonly string[];
|
|
218
|
+
/** The mount prefixes hyle reports: "/" for a root mount. */
|
|
219
|
+
readonly mounts: readonly string[];
|
|
220
|
+
/** Every published page path (`listPublicationPaths`), in hyle's path space (no host locale prefix). */
|
|
221
|
+
readonly hylePaths: readonly string[];
|
|
222
|
+
readonly locale?: LocaleOptions;
|
|
223
|
+
/** The param name of the host's hyle catch-all (`[...hyle]`). Default "hyle". */
|
|
224
|
+
readonly hyleParam?: string;
|
|
225
|
+
}
|
|
226
|
+
interface DynamicOverlap {
|
|
227
|
+
readonly route: string;
|
|
228
|
+
/**
|
|
229
|
+
* "hyle-catch-all": the route is hyle's own catch-all, fine. "hyle-wins": it matches hyle URLs but hyle's catch-all is more specific, fine.
|
|
230
|
+
* "host-wins": Next serves this route for URLs hyle publishes, so that hyle content is never shown.
|
|
231
|
+
*/
|
|
232
|
+
readonly verdict: "hyle-catch-all" | "hyle-wins" | "host-wins";
|
|
233
|
+
readonly matches: number;
|
|
234
|
+
readonly examples: readonly string[];
|
|
235
|
+
}
|
|
236
|
+
interface RouteCheckReport {
|
|
237
|
+
/** (a) A published hyle page at a URL a static host route owns: never served. */
|
|
238
|
+
readonly shadowedHylePaths: readonly {
|
|
239
|
+
readonly path: string;
|
|
240
|
+
readonly url: string;
|
|
241
|
+
readonly route: string;
|
|
242
|
+
}[];
|
|
243
|
+
/** (c) A mount prefix that is itself a static host route: the mount's index page is never served. */
|
|
244
|
+
readonly mountCollisions: readonly {
|
|
245
|
+
readonly prefix: string;
|
|
246
|
+
readonly url: string;
|
|
247
|
+
readonly route: string;
|
|
248
|
+
}[];
|
|
249
|
+
/** (b) Host dynamic routes matching hyle URLs, grouped by route. */
|
|
250
|
+
readonly dynamicOverlaps: readonly DynamicOverlap[];
|
|
251
|
+
readonly notes: readonly string[];
|
|
252
|
+
/** False when (a) or (c) found something. */
|
|
253
|
+
readonly ok: boolean;
|
|
254
|
+
}
|
|
255
|
+
declare function checkRoutes(input: RouteCheckInput): RouteCheckReport;
|
|
256
|
+
/** Paths the SDK's own components serve inside a host app, always reserved on top of the host's routes: the asset route (ADR 0015). */
|
|
257
|
+
declare const SDK_OWN_RESERVED: readonly string[];
|
|
258
|
+
/**
|
|
259
|
+
* The host's routes in hyle's Reserved paths format. Static routes are exact paths, and "/x/*" for a segment with two or more
|
|
260
|
+
* routes under it (route groups such as "/api/*"). A dynamic route ("/shop/[id]", "/docs/[...slug]") becomes the wildcard on its
|
|
261
|
+
* static prefix ("/shop/*", "/docs/*"); one with no static prefix, and hyle's own catch-all (`hyleParam`, default "hyle"), are
|
|
262
|
+
* skipped. A segment is NOT collapsed, and a wildcard is not made, when a non-root mount prefix lies on it, so "/learn/about" stays
|
|
263
|
+
* exact while a mount serves "/learn/notes". Without `mounts` (hyle unreachable) nothing is collapsed. The leading locale segment
|
|
264
|
+
* is dropped because hyle's paths carry no host locale prefix. Per-build hashed metadata routes are omitted, an entry another
|
|
265
|
+
* wildcard already covers is dropped, and the result is sorted.
|
|
266
|
+
*/
|
|
267
|
+
declare function reservedFor(hostRoutes: readonly string[], options?: {
|
|
268
|
+
readonly locale?: LocaleOptions;
|
|
269
|
+
readonly mounts?: readonly string[];
|
|
270
|
+
readonly hyleParam?: string;
|
|
271
|
+
}): string[];
|
|
272
|
+
/** The human report. */
|
|
273
|
+
declare function formatReport(report: RouteCheckReport): string;
|
|
274
|
+
|
|
275
|
+
export { type AssetOptions, CACHE_TAG_PATTERN, Cp1ClientError, DeliveryDedupe, type DynamicOverlap, type HostSyncInput, type HostSyncResult, type HyleClient, type HyleClientOptions, type HyleRequestInit, type ListPublicationPathsOptions, type LocaleOptions, type LocalePrefix, type MountsOptions, MountsResult, type NextManifests, type ParsedSignatureHeader, type PublicationPath, type PublicationPaths, type ResolveOptions, Resolved, type RouteCheckInput, type RouteCheckReport, SDK_OWN_RESERVED, type VerifySignatureParams, checkRoutes, createHyleClient, formatReport, hostRoutesFromManifests, isValidCacheTag, listPublicationPaths, normalizeRoute, parseSignatureHeader, reservedFor, routeMatches, syncHostReserved, verifyHyleSignature };
|