@decocms/blocks 8.2.2 → 8.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/v8/builtins/lazy.d.ts +1 -1
- package/dist/v8/builtins/lazy.d.ts.map +1 -1
- package/dist/v8/builtins/lazy.js +1 -1
- package/dist/v8/builtins/lazy.js.map +1 -1
- package/dist/v8/builtins/multivariate.d.ts +12 -1
- package/dist/v8/builtins/multivariate.d.ts.map +1 -1
- package/dist/v8/builtins/multivariate.js +14 -2
- package/dist/v8/builtins/multivariate.js.map +1 -1
- package/dist/v8/cli/run.d.ts.map +1 -1
- package/dist/v8/cli/run.js +7 -3
- package/dist/v8/cli/run.js.map +1 -1
- package/dist/v8/cli/schema/index.d.ts +15 -1
- package/dist/v8/cli/schema/index.d.ts.map +1 -1
- package/dist/v8/cli/schema/index.js +96 -2
- package/dist/v8/cli/schema/index.js.map +1 -1
- package/dist/v8/cms.js +9 -1
- package/dist/v8/cms.js.map +1 -1
- package/dist/v8/draft.d.ts +3 -1
- package/dist/v8/draft.d.ts.map +1 -1
- package/dist/v8/draft.js +5 -3
- package/dist/v8/draft.js.map +1 -1
- package/dist/v8/image.d.ts +140 -0
- package/dist/v8/image.d.ts.map +1 -0
- package/dist/v8/image.js +226 -0
- package/dist/v8/image.js.map +1 -0
- package/dist/v8/remoteLoader.js +3 -3
- package/dist/v8/resolver.d.ts.map +1 -1
- package/dist/v8/resolver.js +36 -3
- package/dist/v8/resolver.js.map +1 -1
- package/dist/v8/types.d.ts +7 -5
- package/dist/v8/types.d.ts.map +1 -1
- package/package.json +6 -1
- package/src/v8/builtins/lazy.ts +1 -1
- package/src/v8/builtins/multivariate.ts +28 -11
- package/src/v8/cli/run.ts +7 -3
- package/src/v8/cli/schema/index.ts +114 -3
- package/src/v8/cms.ts +12 -1
- package/src/v8/draft.ts +5 -3
- package/src/v8/image.ts +325 -0
- package/src/v8/remoteLoader.ts +3 -3
- package/src/v8/resolver.ts +40 -3
- package/src/v8/types.ts +7 -5
|
@@ -6,20 +6,37 @@ interface MultivariateProps<T> {
|
|
|
6
6
|
experiment?: string;
|
|
7
7
|
}
|
|
8
8
|
|
|
9
|
+
/** Marks the built-in `multivariate`, whose rules the resolver evaluates in order. */
|
|
10
|
+
const MULTIVARIATE_BLOCK: unique symbol = Symbol.for("decocms.blocks.v8.multivariate");
|
|
11
|
+
|
|
9
12
|
/**
|
|
10
13
|
* `multivariate`: runs the first variant whose rule is `true` and returns its
|
|
11
14
|
* value, or `undefined` when no rule is. Only the chosen variant runs, because
|
|
12
15
|
* each `value` is a `Lazy<T>`. A value saved without the `lazy` wrapper (which
|
|
13
16
|
* `deco check` flags) is returned as is rather than failing the page.
|
|
17
|
+
*
|
|
18
|
+
* Inside the resolver, the rules also run in order and stop at the first
|
|
19
|
+
* `true` one (as in v7): a later rule's matcher is never called, so a random
|
|
20
|
+
* rule after the winner draws nothing and sets no cookie. The resolver hands
|
|
21
|
+
* this function the variants up to the winner. A `multivariate` in the site's
|
|
22
|
+
* block map replaces this one and gets every rule resolved, like any block.
|
|
14
23
|
*/
|
|
15
|
-
export const multivariate =
|
|
16
|
-
variants
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
}
|
|
24
|
+
export const multivariate = Object.assign(
|
|
25
|
+
async <T>({ variants }: MultivariateProps<T> = {}): Promise<T | undefined> => {
|
|
26
|
+
if (!Array.isArray(variants)) return undefined;
|
|
27
|
+
for (const variant of variants) {
|
|
28
|
+
if (variant?.rule !== true) continue;
|
|
29
|
+
const value = variant.value as unknown;
|
|
30
|
+
return typeof value === "function" ? await (value as () => Promise<T>)() : (value as T);
|
|
31
|
+
}
|
|
32
|
+
return undefined;
|
|
33
|
+
},
|
|
34
|
+
{ [MULTIVARIATE_BLOCK]: true as const },
|
|
35
|
+
);
|
|
36
|
+
|
|
37
|
+
export function isMultivariateBuiltin(fn: unknown): boolean {
|
|
38
|
+
return (
|
|
39
|
+
typeof fn === "function" &&
|
|
40
|
+
(fn as unknown as Record<symbol, unknown>)[MULTIVARIATE_BLOCK] === true
|
|
41
|
+
);
|
|
42
|
+
}
|
package/src/v8/cli/run.ts
CHANGED
|
@@ -14,8 +14,8 @@ type FlagKind = "string" | "boolean";
|
|
|
14
14
|
|
|
15
15
|
const COMMANDS: Record<string, { usage: string; flags: Record<string, FlagKind> }> = {
|
|
16
16
|
schema: {
|
|
17
|
-
usage: "deco schema [--root <dir>] [--watch]",
|
|
18
|
-
flags: { root: "string", watch: "boolean" },
|
|
17
|
+
usage: "deco schema [--root <dir>] [--watch | --check]",
|
|
18
|
+
flags: { root: "string", watch: "boolean", check: "boolean" },
|
|
19
19
|
},
|
|
20
20
|
content: {
|
|
21
21
|
usage: "deco content [--root <dir>] [--watch]",
|
|
@@ -40,6 +40,7 @@ export const USAGE = `Usage: deco <command> [flags]
|
|
|
40
40
|
|
|
41
41
|
Commands:
|
|
42
42
|
schema turn the types in .deco/index.ts into .deco/schema.gen.json
|
|
43
|
+
(--check: write nothing, fail when the file is out of date; for CI)
|
|
43
44
|
content turn .deco/blocks into the content module, .deco/blocks.gen.ts
|
|
44
45
|
check check that every saved block fits the schema (writes nothing)
|
|
45
46
|
serve serve .deco to the site editor on this machine, at http://localhost:4545/rpc;
|
|
@@ -165,7 +166,10 @@ export async function runCli(argv: string[], options: RunOptions = {}): Promise<
|
|
|
165
166
|
const base = { root, cwd: options.cwd, reporter };
|
|
166
167
|
switch (command) {
|
|
167
168
|
case "schema": {
|
|
168
|
-
if (
|
|
169
|
+
if (flags.watch && flags.check) {
|
|
170
|
+
throw new CliError(`--watch and --check can't be combined\n${COMMANDS.schema.usage}`);
|
|
171
|
+
}
|
|
172
|
+
if (!flags.watch) return await schema({ ...base, check: flags.check === true });
|
|
169
173
|
const paths = decoPaths(findDecoRoot(base));
|
|
170
174
|
// Monorepo packages the block map imports live outside the root:
|
|
171
175
|
// watch the files the last run read there, too.
|
|
@@ -1,14 +1,20 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
1
2
|
import path from "node:path";
|
|
2
3
|
import { paint } from "../color.ts";
|
|
3
4
|
import { writeIfChanged } from "../content.ts";
|
|
4
5
|
import { consoleReporter, type Reporter } from "../log.ts";
|
|
5
6
|
import { CliError, type DecoPaths, decoPaths, findDecoRoot } from "../root.ts";
|
|
6
|
-
import { generateSchema, type SchemaResult } from "./generate.ts";
|
|
7
|
+
import { type DecoMeta, generateSchema, type SchemaResult } from "./generate.ts";
|
|
7
8
|
|
|
8
9
|
export interface SchemaOptions {
|
|
9
10
|
root?: string;
|
|
10
11
|
cwd?: string;
|
|
11
12
|
reporter?: Reporter;
|
|
13
|
+
/**
|
|
14
|
+
* `--check`: write nothing; fail (exit 1) when `.deco/schema.gen.json`
|
|
15
|
+
* differs from what `deco schema` would write. For CI.
|
|
16
|
+
*/
|
|
17
|
+
check?: boolean;
|
|
12
18
|
}
|
|
13
19
|
|
|
14
20
|
export interface WriteSchemaResult extends SchemaResult {
|
|
@@ -25,10 +31,114 @@ export async function writeSchema(paths: DecoPaths): Promise<WriteSchemaResult>
|
|
|
25
31
|
if (result.diagnostics.some((d) => d.severity === "error")) {
|
|
26
32
|
return { ...result, written: false, changed: false };
|
|
27
33
|
}
|
|
28
|
-
const changed = writeIfChanged(paths.schema,
|
|
34
|
+
const changed = writeIfChanged(paths.schema, schemaText(result));
|
|
29
35
|
return { ...result, written: true, changed };
|
|
30
36
|
}
|
|
31
37
|
|
|
38
|
+
/** The file's text, as `deco schema` writes it. */
|
|
39
|
+
function schemaText(result: SchemaResult): string {
|
|
40
|
+
return `${JSON.stringify(result.meta, null, 2)}\n`;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface CheckSchemaResult extends SchemaResult {
|
|
44
|
+
/** `undefined` when the schema has errors, so there is nothing to compare. */
|
|
45
|
+
status?: "up-to-date" | "missing" | "stale";
|
|
46
|
+
/** For a stale file: what differs, one line each. */
|
|
47
|
+
differences: string[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** `deco schema --check`: compare `.deco/schema.gen.json` with what `deco schema` would write. */
|
|
51
|
+
export async function checkSchema(paths: DecoPaths): Promise<CheckSchemaResult> {
|
|
52
|
+
const result = await generateSchema(paths);
|
|
53
|
+
if (result.diagnostics.some((d) => d.severity === "error")) {
|
|
54
|
+
return { ...result, differences: [] };
|
|
55
|
+
}
|
|
56
|
+
let saved: string;
|
|
57
|
+
try {
|
|
58
|
+
saved = fs.readFileSync(paths.schema, "utf8");
|
|
59
|
+
} catch {
|
|
60
|
+
return { ...result, status: "missing", differences: [] };
|
|
61
|
+
}
|
|
62
|
+
if (saved === schemaText(result)) return { ...result, status: "up-to-date", differences: [] };
|
|
63
|
+
return { ...result, status: "stale", differences: describeDifferences(saved, result.meta) };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const LISTED = 5;
|
|
67
|
+
|
|
68
|
+
function names(list: string[]): string {
|
|
69
|
+
const shown = list.slice(0, LISTED).join(", ");
|
|
70
|
+
return list.length > LISTED ? `${shown} and ${list.length - LISTED} more` : shown;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** One line per kind of change, so a CI log says what moved without a diff. */
|
|
74
|
+
function describeDifferences(saved: string, meta: DecoMeta): string[] {
|
|
75
|
+
let old: Partial<DecoMeta>;
|
|
76
|
+
try {
|
|
77
|
+
old = JSON.parse(saved);
|
|
78
|
+
} catch {
|
|
79
|
+
return ["the saved file is not valid JSON"];
|
|
80
|
+
}
|
|
81
|
+
if (old === null || typeof old !== "object") return ["the saved file is not a schema"];
|
|
82
|
+
const lines: string[] = [];
|
|
83
|
+
const oldGroups = old.manifest?.blocks ?? {};
|
|
84
|
+
const newGroups = meta.manifest.blocks;
|
|
85
|
+
for (const group of [...new Set([...Object.keys(newGroups), ...Object.keys(oldGroups)])]) {
|
|
86
|
+
const before = Object.keys(oldGroups[group] ?? {});
|
|
87
|
+
const after = Object.keys(newGroups[group] ?? {});
|
|
88
|
+
const added = after.filter((name) => !before.includes(name));
|
|
89
|
+
const removed = before.filter((name) => !after.includes(name));
|
|
90
|
+
if (added.length > 0) lines.push(`${group}: new in code: ${names(added)}`);
|
|
91
|
+
if (removed.length > 0) lines.push(`${group}: no longer in code: ${names(removed)}`);
|
|
92
|
+
}
|
|
93
|
+
const oldDefinitions = old.schema?.definitions ?? {};
|
|
94
|
+
const changed = Object.keys(meta.schema.definitions).filter(
|
|
95
|
+
(key) =>
|
|
96
|
+
Object.hasOwn(oldDefinitions, key) &&
|
|
97
|
+
JSON.stringify(oldDefinitions[key]) !== JSON.stringify(meta.schema.definitions[key]),
|
|
98
|
+
);
|
|
99
|
+
if (changed.length > 0) {
|
|
100
|
+
lines.push(
|
|
101
|
+
`${changed.length} schema definition${changed.length === 1 ? "" : "s"} changed (fields or choices)`,
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
if (old.version !== meta.version) {
|
|
105
|
+
lines.push(`written by version ${String(old.version)}; this is ${meta.version}`);
|
|
106
|
+
}
|
|
107
|
+
if (lines.length === 0) lines.push("the content is the same but the formatting differs");
|
|
108
|
+
return lines;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function reportSchemaCheck(result: CheckSchemaResult, reporter: Reporter): number {
|
|
112
|
+
const c = paint(reporter.color);
|
|
113
|
+
for (const d of result.diagnostics) {
|
|
114
|
+
if (d.severity === "error") reporter.error(c.red(d.message));
|
|
115
|
+
else reporter.warn(`${c.yellow("warning")}: ${d.message}`);
|
|
116
|
+
}
|
|
117
|
+
const fix = "Run `deco schema` and commit .deco/schema.gen.json.";
|
|
118
|
+
switch (result.status) {
|
|
119
|
+
case undefined:
|
|
120
|
+
reporter.error(c.red(".deco/schema.gen.json can't be checked: fix the errors above"));
|
|
121
|
+
return 1;
|
|
122
|
+
case "missing":
|
|
123
|
+
reporter.error(c.red(`.deco/schema.gen.json is missing. ${fix}`));
|
|
124
|
+
return 1;
|
|
125
|
+
case "stale":
|
|
126
|
+
reporter.error(
|
|
127
|
+
[
|
|
128
|
+
c.red(
|
|
129
|
+
".deco/schema.gen.json is out of date: the code's types have changed since it was written.",
|
|
130
|
+
),
|
|
131
|
+
...result.differences.map((line) => ` - ${line}`),
|
|
132
|
+
fix,
|
|
133
|
+
].join("\n"),
|
|
134
|
+
);
|
|
135
|
+
return 1;
|
|
136
|
+
case "up-to-date":
|
|
137
|
+
reporter.info(`.deco/schema.gen.json is up to date with ${path.basename(result.blockMap)}`);
|
|
138
|
+
return 0;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
32
142
|
export function reportSchema(result: WriteSchemaResult, reporter: Reporter): number {
|
|
33
143
|
const c = paint(reporter.color);
|
|
34
144
|
for (const d of result.diagnostics) {
|
|
@@ -49,11 +159,12 @@ export function reportSchema(result: WriteSchemaResult, reporter: Reporter): num
|
|
|
49
159
|
return 0;
|
|
50
160
|
}
|
|
51
161
|
|
|
52
|
-
/** `deco schema
|
|
162
|
+
/** `deco schema` (or `deco schema --check`), once. Returns the exit code. */
|
|
53
163
|
export async function schema(options: SchemaOptions = {}): Promise<number> {
|
|
54
164
|
const reporter = options.reporter ?? consoleReporter;
|
|
55
165
|
const paths = decoPaths(findDecoRoot(options));
|
|
56
166
|
try {
|
|
167
|
+
if (options.check) return reportSchemaCheck(await checkSchema(paths), reporter);
|
|
57
168
|
return reportSchema(await writeSchema(paths), reporter);
|
|
58
169
|
} catch (error) {
|
|
59
170
|
if (error instanceof CliError) {
|
package/src/v8/cms.ts
CHANGED
|
@@ -398,7 +398,18 @@ export function resetForTests(): void {
|
|
|
398
398
|
/** With `site`, the content is the fallback of hosted releases. */
|
|
399
399
|
function contentOf(config: CMSConfig): Snapshot | Loader {
|
|
400
400
|
if (!config.site) return config.content;
|
|
401
|
-
return remoteLoader(config.content, { site: config.site, dev: config.dev });
|
|
401
|
+
return remoteLoader(config.content, { site: config.site, dev: config.dev ?? isDevelopment() });
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* `NODE_ENV=development`: the SDK's one environment read (an explicit `dev`
|
|
406
|
+
* overrides it). Guarded, so a Worker or a browser without `process` reads
|
|
407
|
+
* `false`; spelled `process.env.NODE_ENV` so a bundler's `define` replaces it.
|
|
408
|
+
*/
|
|
409
|
+
function isDevelopment(): boolean {
|
|
410
|
+
return (
|
|
411
|
+
typeof process !== "undefined" && process.env != null && process.env.NODE_ENV === "development"
|
|
412
|
+
);
|
|
402
413
|
}
|
|
403
414
|
|
|
404
415
|
function validate(config: CMSConfig): void {
|
package/src/v8/draft.ts
CHANGED
|
@@ -158,14 +158,16 @@ function normalizeIPv6Host(authority: string): string | null {
|
|
|
158
158
|
/**
|
|
159
159
|
* The draft pointer a request carries: `?__draft=` from the URL first, then
|
|
160
160
|
* the `__deco_draft` cookie. `null` when neither is present, or when the URL
|
|
161
|
-
* says `?__draft=off`.
|
|
161
|
+
* says `?__draft=off`. A value that doesn't parse is ignored, as if it were
|
|
162
|
+
* absent: a stray `?__draft=junk` link or a mangled cookie gets the release,
|
|
163
|
+
* never an error from `cms.forDraft`.
|
|
162
164
|
*/
|
|
163
165
|
export function readDraftPointer(request: RequestLike): string | null {
|
|
164
166
|
const param = draftParam(request);
|
|
165
167
|
if (param === DRAFT_OFF) return null;
|
|
166
|
-
if (param) return param;
|
|
168
|
+
if (param && parseDraftPointer(param) !== null) return param;
|
|
167
169
|
const cookie = readCookie(request.headers.get("cookie"), DRAFT_COOKIE);
|
|
168
|
-
return cookie && cookie !==
|
|
170
|
+
return cookie && parseDraftPointer(cookie) !== null ? cookie : null;
|
|
169
171
|
}
|
|
170
172
|
|
|
171
173
|
/**
|
package/src/v8/image.ts
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@decocms/blocks/image`: image URLs for the Deco image CDN, srcset and
|
|
3
|
+
* preload data.
|
|
4
|
+
*
|
|
5
|
+
* Pure functions: no React, no framework, no module state. A site builds one
|
|
6
|
+
* `ImageUrl` from the providers its images come from and passes it to the
|
|
7
|
+
* binding's components or image loader. v7's `registerImageCdnDomain` and
|
|
8
|
+
* `registerImageQuality` do not come back: they were module-wide state, the
|
|
9
|
+
* dual-instance hazard the package split removed; their values are
|
|
10
|
+
* `decoCdn`'s `domain` and `quality` options.
|
|
11
|
+
*
|
|
12
|
+
* Only the Deco CDN lives here. A commerce platform's own resize syntax is a
|
|
13
|
+
* provider in that platform's client package (`@decocms/apps-vtex/image`,
|
|
14
|
+
* `@decocms/apps-shopify/image`), listed before `decoCdn`.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
export type Fit = "contain" | "cover" | "fill";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* A named tier ("low" | "medium" | "high" | "original", what the Deco image CDN
|
|
21
|
+
* accepts) or a number. The Deco CDN ignores numbers; a provider for another
|
|
22
|
+
* service says how it reads them.
|
|
23
|
+
*/
|
|
24
|
+
export type Quality = "low" | "medium" | "high" | "original" | number;
|
|
25
|
+
|
|
26
|
+
/** The Deco image CDN's quality tiers. */
|
|
27
|
+
export type QualityTier = "low" | "medium" | "high" | "original";
|
|
28
|
+
|
|
29
|
+
export interface ResizeOptions {
|
|
30
|
+
width: number;
|
|
31
|
+
height?: number;
|
|
32
|
+
fit?: Fit;
|
|
33
|
+
quality?: Quality;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface ImageProvider {
|
|
37
|
+
name: string;
|
|
38
|
+
/** Whether this provider handles `src` (what `ImageUrl.isOptimizable` reports). */
|
|
39
|
+
match(src: string): boolean;
|
|
40
|
+
/** The resized URL, or null to leave `src` to the next provider. */
|
|
41
|
+
format(src: string, o: ResizeOptions): string | null;
|
|
42
|
+
/** Hosts the formatted URLs point at, for CSP img-src and preconnect. */
|
|
43
|
+
hosts?: string[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface ImageUrl {
|
|
47
|
+
/** The resized URL; "" for an empty src, data: URIs and unknown sources unchanged. */
|
|
48
|
+
(src: string, o: ResizeOptions): string;
|
|
49
|
+
/** Whether a provider handles `src` (false for "", data: URIs and unknown sources). */
|
|
50
|
+
isOptimizable(src: string): boolean;
|
|
51
|
+
hosts(): string[];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// ---------------------------------------------------------------------------
|
|
55
|
+
// Deco image CDN
|
|
56
|
+
// ---------------------------------------------------------------------------
|
|
57
|
+
|
|
58
|
+
const DECO_CACHE_URL = "https://assets.decocache.com/";
|
|
59
|
+
const DECO_S3_URL = "https://deco-sites-assets.s3.sa-east-1.amazonaws.com/";
|
|
60
|
+
const LEADING_ASSET_HOST =
|
|
61
|
+
/^https:\/\/(?:assets\.decocache\.com|deco-sites-assets\.s3\.sa-east-1\.amazonaws\.com)\//;
|
|
62
|
+
/** Deco CDNs on Cloudflare: a decoims.com src= makes them fetch themselves (508), so it is stripped. */
|
|
63
|
+
const CLOUDFLARE_DECO_CDNS = new Set(["assets.decocms.com", "decoims.com"]);
|
|
64
|
+
/** Every host that serves the Deco image CDN's `/image?…&src=` endpoint. */
|
|
65
|
+
const DECO_IMAGE_HOSTS = [
|
|
66
|
+
"assets.decocms.com",
|
|
67
|
+
"decoims.com",
|
|
68
|
+
"deco-assets.edgedeco.com",
|
|
69
|
+
"deco-assets.decoazn.com",
|
|
70
|
+
];
|
|
71
|
+
/** Characters an unwrapped `src` cannot carry raw in the query this provider writes. */
|
|
72
|
+
const QUERY_UNSAFE = /[%&#+]/g;
|
|
73
|
+
|
|
74
|
+
export interface DecoCdnOptions {
|
|
75
|
+
/** The CDN host. Default "assets.decocms.com"; "decoims.com", "deco-assets.edgedeco.com" also serve it. */
|
|
76
|
+
domain?: string;
|
|
77
|
+
/** Tier asked for when a call names none (a call's numeric quality is ignored). Default: none, the CDN's 60%. */
|
|
78
|
+
quality?: QualityTier;
|
|
79
|
+
/** Fit when a call names none. Default "cover", as v7's `getSrcSet` and `Image`. */
|
|
80
|
+
fit?: Fit;
|
|
81
|
+
/**
|
|
82
|
+
* Earlier CDN hosts whose URLs are re-served from `domain`. Default ["decoims.com"]
|
|
83
|
+
* on the Cloudflare CDNs, [] otherwise (the Azion CDNs fetch decoims.com URLs fine).
|
|
84
|
+
*/
|
|
85
|
+
legacyHosts?: string[];
|
|
86
|
+
/**
|
|
87
|
+
* The sources this provider resizes. "deco" (default): the Deco asset hosts,
|
|
88
|
+
* `domain` and `legacyHosts`; others pass through. "all": every non-empty,
|
|
89
|
+
* non-data: source, v7's behaviour (put the provider last). Or a predicate.
|
|
90
|
+
*/
|
|
91
|
+
sources?: "deco" | "all" | ((src: string) => boolean);
|
|
92
|
+
/**
|
|
93
|
+
* How the Deco asset hosts (assets.decocache.com, the S3 bucket) are removed
|
|
94
|
+
* from the source. "leading" (default, v7's `Image` since 7.71.4): only a
|
|
95
|
+
* host the source starts with. "anywhere" (older v7 `getOptimizedMediaUrl`
|
|
96
|
+
* copies): the first occurrence of each, wherever it is, so a source that
|
|
97
|
+
* merely contains an asset URL (`https://other.host/https://assets.decocache.com/…`)
|
|
98
|
+
* loses that part.
|
|
99
|
+
*/
|
|
100
|
+
stripAssetHosts?: "anywhere" | "leading";
|
|
101
|
+
/**
|
|
102
|
+
* Query layout. "src-last" (default, v7's `getOptimizedMediaUrl`):
|
|
103
|
+
* `?fit=&width=[&height=][&quality=]&src=<raw path>`. "quality-last" (what
|
|
104
|
+
* next/image loaders built on v7's helper emit): the same URL re-serialised,
|
|
105
|
+
* `?fit=&width=[&height=]&src=<form-encoded path>&quality=`. Both are served
|
|
106
|
+
* the same way; keep the one a site uses so the CDN cache stays warm.
|
|
107
|
+
*/
|
|
108
|
+
layout?: "src-last" | "quality-last";
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function stripScheme(domain: string): string {
|
|
112
|
+
return domain.replace(/^https?:\/\//, "").replace(/\/+$/, "");
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* The `src` an already-resized Deco CDN URL (`https://<cdn>/image?…&src=…`)
|
|
117
|
+
* was made from, as the CDN reads it (query-decoded); null for any other URL.
|
|
118
|
+
*/
|
|
119
|
+
function decoImageSource(src: string, hosts: Set<string>): string | null {
|
|
120
|
+
if (!/^https?:\/\//i.test(src) || !/\/image\?/i.test(src)) return null;
|
|
121
|
+
let url: URL;
|
|
122
|
+
try {
|
|
123
|
+
url = new URL(src);
|
|
124
|
+
} catch {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
if (!hosts.has(url.hostname) || url.pathname !== "/image") return null;
|
|
128
|
+
const inner = url.searchParams.get("src");
|
|
129
|
+
return inner ? inner : null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The Deco image CDN (`https://<domain>/image?fit=&width=…&src=`). An
|
|
134
|
+
* already-resized Deco CDN URL (any of its hosts' `/image?…&src=`) that this
|
|
135
|
+
* provider resizes (see `sources`) is re-resized from its `src`; before, it
|
|
136
|
+
* became `src=image` or `src=<cdn>/image`, which the CDN cannot serve.
|
|
137
|
+
*/
|
|
138
|
+
export function decoCdn(o: DecoCdnOptions = {}): ImageProvider {
|
|
139
|
+
const domain = stripScheme(o.domain ?? "assets.decocms.com");
|
|
140
|
+
const legacy = (o.legacyHosts ?? (CLOUDFLARE_DECO_CDNS.has(domain) ? ["decoims.com"] : []))
|
|
141
|
+
.map(stripScheme)
|
|
142
|
+
.filter((h) => h !== domain);
|
|
143
|
+
const decoPrefixes = [
|
|
144
|
+
`https://${domain}/`,
|
|
145
|
+
...legacy.map((h) => `https://${h}/`),
|
|
146
|
+
DECO_CACHE_URL,
|
|
147
|
+
DECO_S3_URL,
|
|
148
|
+
];
|
|
149
|
+
const sources = o.sources ?? "deco";
|
|
150
|
+
const layout = o.layout ?? "src-last";
|
|
151
|
+
const imageHosts = new Set([...DECO_IMAGE_HOSTS, domain, ...legacy]);
|
|
152
|
+
|
|
153
|
+
return {
|
|
154
|
+
name: "deco",
|
|
155
|
+
hosts: [domain],
|
|
156
|
+
match(src) {
|
|
157
|
+
if (typeof sources === "function") return sources(src);
|
|
158
|
+
if (sources === "all") return src.length > 0 && !src.startsWith("data:");
|
|
159
|
+
// Only the sources resized before fix 2: a Deco CDN URL this provider
|
|
160
|
+
// did not match (another CDN host, http, an uppercase host) still passes
|
|
161
|
+
// through unchanged, as it was served fine.
|
|
162
|
+
return decoPrefixes.some((p) => src.startsWith(p));
|
|
163
|
+
},
|
|
164
|
+
format(src, r) {
|
|
165
|
+
// An already-resized Deco CDN URL is re-resized from the src it was made
|
|
166
|
+
// from (nested ones too); before, `src=` got the CDN URL's own path
|
|
167
|
+
// ("image") and the CDN answered 404.
|
|
168
|
+
let unwrapped = false;
|
|
169
|
+
for (let inner = decoImageSource(src, imageHosts), i = 0; inner !== null && i < 8; i++) {
|
|
170
|
+
src = inner;
|
|
171
|
+
unwrapped = true;
|
|
172
|
+
inner = decoImageSource(src, imageHosts);
|
|
173
|
+
}
|
|
174
|
+
let source =
|
|
175
|
+
(o.stripAssetHosts ?? "leading") === "leading"
|
|
176
|
+
? src.replace(LEADING_ASSET_HOST, "")
|
|
177
|
+
: src.replace(DECO_CACHE_URL, "").replace(DECO_S3_URL, "");
|
|
178
|
+
source = source.split("?")[0];
|
|
179
|
+
for (const host of [...legacy, domain]) {
|
|
180
|
+
if (source.startsWith(`https://${host}/`)) source = source.slice(host.length + 9);
|
|
181
|
+
}
|
|
182
|
+
if (unwrapped) source = source.replace(QUERY_UNSAFE, encodeURIComponent);
|
|
183
|
+
const quality = typeof r.quality === "string" ? r.quality : o.quality;
|
|
184
|
+
const params = new URLSearchParams();
|
|
185
|
+
params.set("fit", r.fit ?? o.fit ?? "cover");
|
|
186
|
+
params.set("width", `${r.width}`);
|
|
187
|
+
if (r.height) params.set("height", `${r.height}`);
|
|
188
|
+
if (layout === "src-last") {
|
|
189
|
+
if (quality) params.set("quality", quality);
|
|
190
|
+
return `https://${domain}/image?${params}&src=${source}`;
|
|
191
|
+
}
|
|
192
|
+
const url = new URL(`https://${domain}/image?${params}&src=${source}`);
|
|
193
|
+
if (quality) url.searchParams.set("quality", quality);
|
|
194
|
+
return url.toString();
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// ---------------------------------------------------------------------------
|
|
200
|
+
// ImageUrl, srcset, preload
|
|
201
|
+
// ---------------------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* One URL builder for a site. Providers are tried in order: the first that
|
|
205
|
+
* matches `src` and returns a URL wins; unknown sources pass through unchanged.
|
|
206
|
+
*/
|
|
207
|
+
export function createImageUrl(o: { providers: ImageProvider[] }): ImageUrl {
|
|
208
|
+
const providers = [...o.providers];
|
|
209
|
+
const usable = (src: string) =>
|
|
210
|
+
typeof src === "string" && src.length > 0 && !src.startsWith("data:");
|
|
211
|
+
const url = ((src: string, r: ResizeOptions) => {
|
|
212
|
+
if (typeof src !== "string" || src.length === 0) return "";
|
|
213
|
+
if (!usable(src)) return src;
|
|
214
|
+
for (const p of providers) {
|
|
215
|
+
if (!p.match(src)) continue;
|
|
216
|
+
const out = p.format(src, r);
|
|
217
|
+
if (out !== null) return out;
|
|
218
|
+
}
|
|
219
|
+
return src;
|
|
220
|
+
}) as ImageUrl;
|
|
221
|
+
url.isOptimizable = (src) => usable(src) && providers.some((p) => p.match(src));
|
|
222
|
+
url.hosts = () => [...new Set(providers.flatMap((p) => p.hosts ?? []))];
|
|
223
|
+
return url;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
export interface SrcSetOptions {
|
|
227
|
+
/**
|
|
228
|
+
* Base width for `factors`. Left out, each candidate is `NaN` wide, as v7's
|
|
229
|
+
* `getSrcSet` wrote it for an `Image` or `Source` without a width.
|
|
230
|
+
*/
|
|
231
|
+
width?: number;
|
|
232
|
+
/** Candidate widths; when given, `width` and `factors` are not used. */
|
|
233
|
+
widths?: number[];
|
|
234
|
+
/** Multipliers of `width` (truncated, as v7 did). Default [1, 2]. */
|
|
235
|
+
factors?: number[];
|
|
236
|
+
/** Base height for `factors`, scaled with the width. */
|
|
237
|
+
height?: number;
|
|
238
|
+
/** height / width, for a fixed frame: each candidate gets round(w * ratio). */
|
|
239
|
+
ratio?: number;
|
|
240
|
+
fit?: Fit;
|
|
241
|
+
quality?: Quality;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** `"<url> <w>w, ..."`, or undefined for an empty src or no candidates (`widths: []`). */
|
|
245
|
+
export function srcSet(url: ImageUrl, src: string, o: SrcSetOptions): string | undefined {
|
|
246
|
+
if (typeof src !== "string" || src.length === 0) return undefined;
|
|
247
|
+
const sizes: { w: number; h?: number }[] = o.widths
|
|
248
|
+
? o.widths.map((w) => ({ w, h: o.ratio ? Math.round(w * o.ratio) : undefined }))
|
|
249
|
+
: // No width: v7's NaN candidates (`width=NaN … NaNw`), kept byte for byte.
|
|
250
|
+
(o.factors ?? [1, 2]).map((f) => {
|
|
251
|
+
const w = Math.trunc(f * (o.width as number));
|
|
252
|
+
const h = o.height
|
|
253
|
+
? Math.trunc(f * o.height)
|
|
254
|
+
: o.ratio
|
|
255
|
+
? Math.round(w * o.ratio)
|
|
256
|
+
: undefined;
|
|
257
|
+
return { w, h };
|
|
258
|
+
});
|
|
259
|
+
const entries: string[] = [];
|
|
260
|
+
for (const { w, h } of sizes) {
|
|
261
|
+
const href = url(src, { width: w, height: h, fit: o.fit, quality: o.quality });
|
|
262
|
+
if (href) entries.push(`${href} ${w}w`);
|
|
263
|
+
}
|
|
264
|
+
return entries.length > 0 ? entries.join(", ") : undefined;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Candidates of a srcset attribute (URLs with commas inside are kept whole). */
|
|
268
|
+
export function parseSrcSet(s: string): { url: string; w?: number; x?: number }[] {
|
|
269
|
+
const out: { url: string; w?: number; x?: number }[] = [];
|
|
270
|
+
let i = 0;
|
|
271
|
+
while (i < s.length) {
|
|
272
|
+
while (i < s.length && /[\s,]/.test(s[i])) i++;
|
|
273
|
+
if (i >= s.length) break;
|
|
274
|
+
let j = i;
|
|
275
|
+
while (j < s.length && !/\s/.test(s[j])) j++;
|
|
276
|
+
let url = s.slice(i, j);
|
|
277
|
+
i = j;
|
|
278
|
+
let descriptor = "";
|
|
279
|
+
if (url.endsWith(",")) url = url.replace(/,+$/, "");
|
|
280
|
+
else {
|
|
281
|
+
while (i < s.length && s[i] !== ",") descriptor += s[i++];
|
|
282
|
+
i++;
|
|
283
|
+
}
|
|
284
|
+
const entry: { url: string; w?: number; x?: number } = { url };
|
|
285
|
+
const d = /^(\d+(?:\.\d+)?)([wx])$/.exec(descriptor.trim());
|
|
286
|
+
if (d) entry[d[2] as "w" | "x"] = Number(d[1]);
|
|
287
|
+
out.push(entry);
|
|
288
|
+
}
|
|
289
|
+
return out;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export interface PreloadOptions extends SrcSetOptions {
|
|
293
|
+
width: number;
|
|
294
|
+
sizes?: string;
|
|
295
|
+
media?: string;
|
|
296
|
+
/** Default "high". */
|
|
297
|
+
fetchPriority?: "high" | "low" | "auto";
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export interface PreloadLink {
|
|
301
|
+
rel: "preload";
|
|
302
|
+
as: "image";
|
|
303
|
+
href: string;
|
|
304
|
+
imageSrcSet?: string;
|
|
305
|
+
imageSizes?: string;
|
|
306
|
+
media?: string;
|
|
307
|
+
fetchPriority?: string;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** The attributes of a `<link rel="preload" as="image">` for an LCP image. */
|
|
311
|
+
export function preloadLink(url: ImageUrl, src: string, o: PreloadOptions): PreloadLink {
|
|
312
|
+
const link: PreloadLink = {
|
|
313
|
+
rel: "preload",
|
|
314
|
+
as: "image",
|
|
315
|
+
href: url(src, { width: o.width, height: o.height, fit: o.fit, quality: o.quality }),
|
|
316
|
+
};
|
|
317
|
+
const set = srcSet(url, src, o);
|
|
318
|
+
if (set) {
|
|
319
|
+
link.imageSrcSet = set;
|
|
320
|
+
if (o.sizes) link.imageSizes = o.sizes;
|
|
321
|
+
}
|
|
322
|
+
if (o.media) link.media = o.media;
|
|
323
|
+
link.fetchPriority = o.fetchPriority ?? "high";
|
|
324
|
+
return link;
|
|
325
|
+
}
|
package/src/v8/remoteLoader.ts
CHANGED
|
@@ -25,9 +25,9 @@
|
|
|
25
25
|
* a publish still loses to it.
|
|
26
26
|
* Pointers aren't ordered among themselves, and the fallback's content is
|
|
27
27
|
* never compared: only the two timestamps are.
|
|
28
|
-
* - With `dev: true
|
|
29
|
-
*
|
|
30
|
-
*
|
|
28
|
+
* - With `dev: true`, it never swaps, so local files win. `createCMS` passes
|
|
29
|
+
* its `dev` option, or `NODE_ENV === "development"` when the site omits it;
|
|
30
|
+
* this loader reads no environment itself.
|
|
31
31
|
* - A release larger than `MAX_SNAPSHOT_BYTES` is refused while it downloads,
|
|
32
32
|
* before it's buffered whole (a Worker isolate has 128 MB).
|
|
33
33
|
* - Without `site` it's a plain loader over the fallback.
|